swmmio

repository·master·Indexed 40 days ago

https://github.com/pyswmm/swmmio

A Python library for the programmatic pre- and post-processing of EPA Stormwater Management Model (SWMM5) files. It provides a Pandas-based interface for model analysis and modification, allowing users to access model elements as DataFrames or GeoDataFrames. Key features include high-level analysis via the swmmio.Model class, low-level manipulation of .inp files, NetworkX graph integration, spatial visualization tools, and a CLI for running models in serial or parallel.

Tokens
7.9K
Snippets
29
Records
36
Agent score
100%

What's inside swmmio

  1. Overview of swmmio

    master

    swmmio is a Python library designed for the programmatic pre- and post-processing of EPA Stormwater Management Model (SWMM) files. It allows engineers and hydrologists to automate the modification and analysis of SWMM models and results using a Pandas-based interface.

    Key capabilities include:

    • High-level analysis: Using the swmmio.Model object to access model elements (like subcatchments) as Pandas DataFrames or GeoDataFrames. These objects automatically join data from the .inp file (e.g., [SUBCATCHMENTS] and [SUBAREAS] tables) with results from the .rpt file (e.g., Subcatchment Runoff Summary).
    • Low-level manipulation: A lower-level API for reading and writing nearly all sections of the .inp file, enabling programmatic model modification.
  2. Scale and shift SWMM model coordinates

    master

    To generate fractal-like patterns, you can manually manipulate the model's spatial data. While swmmio provides rotation, you can implement scaling and shifting by updating the model.inp.coordinates, model.inp.vertices, and model.inp.polygons DataFrames.

    Scaling involves applying a factor to the distance between each coordinate and a center_point. Shifting involves adding a translation vector to all coordinate sets.

    # Example logic for scaling coordinates
    def scale_model_coords(model, scale_factor, center_point):
        def scale_coordinates(coords, scale_factor, center_point):
            coords = np.array(coords)
            center_point = np.array(center_point)
            scaled_coords = center_point + scale_factor * (coords - center_point)
            return scaled_coords.tolist()
    
        model.inp.coordinates = pd.DataFrame(
            data=scale_coordinates(model.inp.coordinates.values, scale_factor, center_point),
            columns=model.inp.coordinates.columns,
            index=model.inp.coordinates.index
        )
        # Repeat for vertices and polygons...
        return model
  3. Configure hot-start files in the `.inp` file

    master

    To implement hot-starting manually using swmmio.Model, you must manipulate the model.inp.files attribute. This attribute accepts a pandas.DataFrame where the column name is [FILES] and the values are the SWMM command strings.

    Common Commands:

    • SAVE HOTSTART "path/to/file.hsf": Instructs SWMM to write the current state to a hot-start file.
    • USE HOTSTART "path/to/file.hsf": Instructs SWMM to initialize the model using the state from the specified file.

    Example: Saving and Using Hot-starts

    import pandas as pd
    from swmmio import Model
    
    model = Model('model.inp')
    
    # To save a hot-start file
    model.inp.files = pd.DataFrame([f'SAVE HOTSTART "model_hot1.hsf"'], columns=['[FILES]'])
    model.inp.save()
    
    # To use a hot-start file
    model.inp.files = pd.DataFrame([f'USE HOTSTART "model_hot1.hsf"'], columns=['[FILES]'])
    model.inp.save()
  4. Rotate a SWMM model about its centroid

    master

    You can create visual effects like a Spirograph by rotating a model around its center. To do this accurately, use centroid_and_bbox_from_coords to find the center of the model's coordinates, then use rotate_model within a loop to apply incremental rotations.

    Note: When performing multiple transformations in a loop, it is often best to reload the original model using swmmio.Model(path) in each iteration to avoid cumulative floating-point errors or unintended state changes.

    from swmmio.utils.functions import rotate_model
    from swmmio.utils.spatial import centroid_and_bbox_from_coords
    import numpy as np
    
    # Get centroid and bounding box
    (xc, yc), [x1, y1, x2, y2] = centroid_and_bbox_from_coords(jersey.inp.coordinates)
    
    # Create a plot
    ax = jersey.links.geodataframe.plot(linewidth=jersey.links.dataframe['Geom1'], capstyle='round')
    
    # Rotate and replot
    for rads in np.arange(0, 3*3.14, 0.1):
        # Rotate the model about the centroid
        jersey = rotate_model(jersey, rads=rads, origin=(xc, yc))
        jersey.links.geodataframe.plot(linewidth=1, capstyle='round', ax=ax, alpha=0.5)
        jersey.nodes.geodataframe.plot('MaxDepth', ax=ax, markersize='InvertElev', zorder=2, alpha=0.5)
  5. Edit Model Parameters using the Model.inp API

    master

    The Model.inp API provides low-level access to modify specific sections of the INP file. You can access sections like outfalls, junctions, or conduits as DataFrames, modify them using standard pandas syntax, and then save the changes back to a file. This is useful for programmatically altering model parameters.

    # modify the outfall DataFrame
    model.inp.outfalls.loc['J4', 'OutfallType'] = 'FIXED'
    model.inp.outfalls.loc['J4', 'StageOrTimeseries'] = 3.0
    
    # save the updated model to a new .inp file
    model.inp.save('new_model.inp')
    
    # instantiate a new Model object with the modified inp file to verify
    new_model = swmmio.Model('new_model.inp')
  6. Instantiate a Model object

    master

    To begin working with a SWMM model, instantiate a swmmio.Model object by passing the path to an EPA SWMM input file (.inp). Once instantiated, you can access high-level data representations like model.links.dataframe or model.nodes.dataframe.

    import swmmio
    
    # instantiate a model object
    model = swmmio.Model('path/to/your_model.inp')
    
    # get the data related to links as a pandas DataFrame
    print(model.links.dataframe)
  7. Import the swmmio library

    master

    The swmmio package provides tools for interacting with EPA SWMM input (.inp) and report (.rpt) files. You can access the full suite of core functionality, element management, version control, and data utilities by importing the top-level package.

    import swmmio
  8. Use swmmio.Model to manage SWMM models

    master

    The swmmio.core.Model class is the primary interface for interacting with a Storm Water Management Model (SWMM) file. It serves as a high-level container for all model components (such as junctions, conduits, subcatchments, etc.), allowing you to load, manipulate, and save model data.

    To use it, you typically instantiate the class by providing a path to an existing .inp file. Once loaded, you can access and modify the various elements of the hydraulic model through the model object.

    from swmmio import Model
    
    # Load an existing SWMM input file
    model = Model('path/to/your_model.inp')
    
    # Access model components and perform operations
    # (e.g., model.junctions, model.conduits, etc.)
    
    # Save changes back to a file
    model.write('path/to/updated_model.inp')
  9. Use the swmmio.core.inp class to manage SWMM input files

    master
    The swmmio.core.inp class is the primary interface for reading, manipulating, and writing EPA SWMM .inp files. It provides a structured way to access and modify the various components of a SWMM model (such as junctions, conduits, nodes, etc.) programmatically.
  10. Build variations of models for sensitivity analysis

    master

    You can automate the creation of multiple model variations (e.g., for climate change scenarios or sensitivity analysis) by looping through parameter changes and saving each iteration as a new .inp file. This involves modifying the model.inp section and calling .save() within a loop.

    import os
    import swmmio
    
    model = swmmio.Model('base_model.inp')
    sea_level_rise = 0.0
    rise_increment = 0.25
    
    # set initial conditions
    model.inp.outfalls.loc[:, 'OutfallType'] = 'FIXED'
    model.inp.outfalls.loc[:, 'StageOrTimeseries'] = 576
    
    while sea_level_rise < 5:
        outfalls = model.inp.outfalls
        outfalls.loc[:, 'StageOrTimeseries'] = outfalls.loc[:, 'StageOrTimeseries'] + rise_increment
        model.inp.outfalls = outfalls
    
        newfilepath = os.path.join(model.inp.dir, f'{model.inp.name}_{sea_level_rise}_SLR.inp')
        model.inp.save(newfilepath)
        sea_level_rise += rise_increment
  11. Access RPT file metadata and sections

    master

    The Model.rpt object (an instance of the rpt class) provides access to simulation results.

    Key features include:

    • Metadata: Access swmm_version, simulationStart, simulationEnd, and dateOfAnalysis.
    • Headers: Use rpt.headers to see all available section headers and their column names.
    • Data Access: Access specific result sections (like link_flow_summary) as DataFrames.
    from swmmio.tests.data import RPT_FULL_FEATURES
    
    report = rpt(RPT_FULL_FEATURES)
    # Access link flow summary
    report.link_flow_summary.loc['C1:C2']