Monday, December 30, 2024

PYSWMM system.py Summary


• errors.py

® lidcontrols.py

® lidgroups.py

® lidlayers.py

® lidunits.py

® links.py

® nodes.py

® output.py

® raingages.py

® reader.py

® simulation.py

® subcatchments.py

® swmm5.py

® system.py

® toolkitapi.py

• warnings.py

PYSWMM system.py Summary


Below is an extended summary of the PySWMM class (and related components) that illustrates its purpose, core structure, and role as a Pythonic bridge to the SWMM5 toolkit.


Overview

This module provides the foundational class PySWMM for running and controlling SWMM (Storm Water Management Model) simulations programmatically through Python. It leverages the swmm.toolkit.solver functions (i.e., the “toolkit API”) to manage SWMM input, execution, result retrieval, and memory cleanup. Additionally, it includes custom exceptions and convenience methods for setting or getting various SWMM parameters (e.g., node inflows, link offsets, LID properties) at runtime.

Key Capabilities

  1. Execution Modes:
    • Mode 1: A single-shot run via swmm_run, which automates the open-run-close sequence.
    • Mode 2: A step-by-step simulation approach (swmm_startswmm_stepswmm_end) that allows real-time manipulation and monitoring of SWMM objects.
  2. In-Simulation Adjustments:
    • Dynamically set node inflows, outfall stages, or link control settings (for pumps, weirs, orifices).
    • Update LID unit parameters or subcatchment attributes on the fly.
  3. Data Retrieval:
    • Detailed access to internal SWMM objects (nodes, links, subcatchments, etc.) through parameter getters/setters.
    • Extraction of simulation results and statistical summaries (flows, water depths, pollutant concentrations, mass balance errors, etc.).
  4. Hotstart File Management:
    • Load or save a model state at any point during a simulation, enabling partial runs, scenario branching, or warm-start capabilities.

Class Design

1. Constructor

def __init__(self, inpfile="", rptfile=None, binfile=None, swmm_lib_path=None):
    ...
  • Initializes file paths for SWMM input (inpfile), report (rptfile), and binary output (binfile).
  • Sets fileLoaded to False, preventing accidental calls to simulation methods when the model is not properly initialized.

2. Core Methods for Running Simulations

  1. swmm_open / swmm_close

    • swmm_open: Loads the SWMM input file into memory, reads network data, and prepares the solver.
    • swmm_close: Frees memory, closes files, and resets the internal state (fileLoaded).
  2. swmm_run / swmmExec

    • swmm_run: Single command to open, run, and close SWMM, generating a report and binary file.
    • swmmExec: Wrapper around swmm_run primarily used for one-line end-to-end execution.
  3. swmm_start / swmm_step / swmm_end

    • swmm_start: Prepares the SWMM engine for a time-stepped run; optionally defines if output is written to the report file.
    • swmm_step: Advances the simulation by a single routing step, returning the new simulation time in decimal days.
    • swmm_end: Finalizes the simulation steps and closes out any time-related processes.
  4. swmm_stride

    • Advances the simulation by a user-defined number of seconds, offering a coarse, customizable stepping interval.
    • Especially useful for real-time control experiments or scenarios where advanced computations (e.g., machine learning) may need to occur between steps.
  5. swmm_report

    • Copies time-series data from .out to .rpt.
    • Typically called after swmm_end if the user needs a fully populated, final report file.

3. File Management & Hotstart Support

  • swmm_save_hotstart and swmm_use_hotstart let you:
    • Save a partial or complete simulation state to disk.
    • Restart from a saved state for subsequent runs or different scenarios.

4. Exception Handling

  • SWMMException / PYSWMMException:
    • Custom exception classes that provide clearer error messages and help differentiate between SWMM solver errors vs. PySWMM interface errors.

In-Simulation Parameter Manipulation

One of PySWMM’s greatest strengths is its ability to modify model parameters mid-simulation. Rather than re-running an entire SWMM simulation each time an adjustment is needed, you can interactively change:

  1. Node Inflows
    • setNodeInflow(node_id, flow_rate) can introduce or update external inflow in the user-defined flow units.
  2. Link Settings
    • setLinkSetting(link_id, target_setting) sets the link’s control status (e.g., pump speed, weir gate opening).
  3. Outfall Stages
    • setOutfallStage(node_id, stage) to dynamically impose a backwater or tidal condition at an outfall node.
  4. Pollutant Concentrations
    • setNodePollut(node_id, pollutant_id, value) or setLinkPollut(link_id, pollutant_id, value) to change water quality values in real time.

Network & Object Queries

The class provides a suite of functions for discovering and manipulating SWMM objects:

  1. Project Size & IDs

    • getProjectSize(object_type) returns the number of objects (e.g., all nodes, all links).
    • getObjectIDList(object_type) gathers the list of IDs, simplifying iteration over model elements.
  2. Getting/Setting Parameters

    • Node parameters: getNodeParam / setNodeParam (e.g., invert elevation, initial depth).
    • Link parameters: getLinkParam / setLinkParam (e.g., offset, seepage rate).
    • Subcatchment parameters: getSubcatchParam / setSubcatchParam (e.g., area, slope).
    • LID control parameters: getLidCParam / setLidCParam and getLidUParam / setLidUParam.
  3. Connections & Types

    • getLinkConnections(link_id): Returns the upstream and downstream node IDs for a given link, factoring in slope reversal if needed.
    • getNodeType(node_id): Distinguishes between a junction, outfall, storage, or divider.

Retrieving Simulation Results

After or during a simulation, PySWMM fetches results at both global and object levels:

  1. Global System Stats

    • flow_routing_stats() and runoff_routing_stats() return dictionary-based summaries of volume flows (inflows, outflows, flooding, infiltration, evaporation, etc.) and mass-balance errors.
  2. Node, Link, and Subcatchment Results

    • getNodeResult(node_id, result_type) or getLinkResult(link_id, result_type) provides time-varying hydraulic data (e.g., depth, flow, velocity).
    • getSubcatchResult(subcatch_id, result_type) for retrieving subcatchment properties (e.g., runoff rate, infiltration).
  3. Quality Data

    • getNodePollut(node_id, pollut_result_type) or getLinkPollut(link_id, pollut_result_type) returns pollutant concentration or load arrays.
  4. Statistical Summaries

    • node_statistics(node_id), pump_statistics(pump_id), storage_statistics(node_id), etc. Each returns a dictionary of min/max/average metrics tracked throughout the simulation.

Example Usage

Below is a high-level workflow showing how a typical PySWMM session might look:

from pyswmm import PySWMM

# 1. Initialize PySWMM with input, report, and output file paths
swmm_model = PySWMM('model.inp', 'model.rpt', 'model.out')

# 2. Open the SWMM model
swmm_model.swmm_open()

# 3. Start the simulation in step-by-step mode
swmm_model.swmm_start(SaveOut2rpt=True)

while True:
    sim_time = swmm_model.swmm_step()
    
    if sim_time <= 0:  # Reached the end of the simulation
        break

    # For instance, dynamically update a link setting at a certain time step
    if sim_time > 1.5:  # example threshold in decimal days
        swmm_model.setLinkSetting('Pump1', 0.7)

# 4. Finalize run, generate report, and close the model
swmm_model.swmm_end()
swmm_model.swmm_report()
swmm_model.swmm_close()

In this snippet:

  1. The user loads a SWMM input file and opens the simulation.
  2. Each routing step is iterated until the simulation ends.
  3. Mid-simulation interventions can update SWMM parameters (e.g., link settings, node inflows).
  4. Once finished, results are written to the report file, and the model instance is closed.

Conclusion

The PySWMM class is a robust, user-friendly wrapper that unlocks the full power of the SWMM toolkit from Python. It supports both “turnkey” runs and intricate, real-time control scenarios. By abstracting low-level details (e.g., C-based memory management) and providing dictionary-based result retrieval, it significantly streamlines stormwater modeling workflows for engineers, researchers, and data scientists working on advanced hydrologic/hydraulic analyses.

No comments:

A comprehensive explanation of how minimum travel distance relates to link length in InfoSewer

In hydraulic modeling of sewer networks, the minimum travel distance is a fundamental parameter that affects how accurately the model can si...