MOTOSHARE 🚗🏍️

Rent Bikes & Cars Directly from Owners

Motoshare connects vehicle owners with people who need bikes and cars on rent. Owners earn from idle vehicles, and renters get flexible ride options.

Visit Motoshare

Swmm-Api: Python-Powered Real-Time Access to EPA’s SWMM Models

Uncategorized

#WhatIsSwmmAPI

1. What is swmm-api?

swmm-api is an open-source Python library that provides a low-level, real-time interface to the EPA Storm Water Management Model (SWMM). It allows Python developers to:

  • Read, modify, and control SWMM simulations dynamically
  • Access internal states of SWMM objects at each timestep
  • Inject custom control logic for pumps, valves, inflows, or rain events
  • Integrate SWMM models into automated workflows, simulations, or optimization loops

Unlike high-level tools like PySWMM, swmm-api provides direct memory access to the internal SWMM simulation, making it extremely powerful for real-time control, data assimilation, and fine-grained simulation manipulation.

It is developed and maintained by jbgo/swmm-api and supports SWMM5 engine integration across platforms.


#SwmmAPIUseCases

2. Major Use Cases of swmm-api

The swmm-api package offers advanced control and automation for stormwater simulations. It is best suited for professionals and developers requiring programmatic, stepwise control of the simulation process.


💧 2.1. Real-Time Control (RTC) of Urban Drainage Systems

  • Implement sensor-driven control of gates, pumps, or regulators
  • Integrate SCADA systems to drive SWMM control logic
  • Update model parameters based on live weather or flow data

🧪 2.2. Calibration and Sensitivity Analysis

  • Adjust parameters (e.g., catchment area, slope, or roughness) during runtime
  • Run multiple simulation iterations programmatically
  • Export results for analysis or optimization

📊 2.3. Research and Custom Simulation Scenarios

  • Experiment with novel flow control strategies
  • Apply machine learning to predict optimal setpoints
  • Conduct storm event scenario testing with variable rainfall profiles

📡 2.4. Data Assimilation and Digital Twins

  • Ingest real-time sensor data (rainfall, depth, flow) and simulate system response
  • Use SWMM as a digital twin of a physical urban stormwater system
  • Validate and refine predictive models in real-time

🧰 2.5. Automation and Workflow Integration

  • Integrate with CI/CD pipelines, APIs, or data dashboards
  • Use in notebooks or remote simulations
  • Combine with optimization libraries like scipy.optimize or pyomo

#SwmmAPIArchitecture

3. How swmm-api Works – Architecture Overview

The swmm-api package operates by directly interfacing with the SWMM5 engine’s compiled binary (usually swmm5.dll or swmm5.so) and accessing its simulation memory using Python’s ctypes module.


🧱 3.1. Architecture Layers

✅ A. SWMM Engine (Core)

  • Original C-based SWMM5 engine (e.g., version 5.1.15 or newer)
  • Responsible for time-based hydrologic/hydraulic simulations
  • Processes .inp files defining system topology and parameters

✅ B. swmm-api Memory Interface

  • Loads SWMM engine dynamically using ctypes
  • Attaches to the in-memory objects used during simulation
  • Provides access to core SWMM structures like:
    • Nodes
    • Links
    • Subcatchments
    • Controls

✅ C. Python Interface Layer

  • Offers Pythonic classes and methods to:
    • Read simulation outputs in real time
    • Set inflows, control settings, and time parameters
    • Monitor water quality, depth, volume, and more

✅ D. User Script / Application

  • Typically written in Python
  • Drives the simulation loop, custom control logic, optimization, or logging
  • Optionally visualizes results using matplotlib, pandas, or Plotly

#SwmmAPIWorkflow

4. Basic Workflow of swmm-api

Here’s a high-level view of how a typical swmm-api based simulation workflow proceeds:


🔄 Simulation Loop Workflow

StepAction
1.Load and compile the SWMM5 engine (DLL or shared object)
2.Initialize simulation with .inp model
3.Step through the simulation in real-time (1 timestep at a time)
4.At each step, read/write values (e.g., depth, flow, rainfall)
5.Optionally modify parameters based on logic or inputs
6.Save results or visualize after simulation completes

🔍 Access Points

  • getNodeParam, setLinkFlow, getRainfall
  • stepSimulation, getSimulationTime, getWaterQuality
  • All access is low-level and performant (direct pointer access)

#GettingStartedWithSwmmAPI

5. Step-by-Step Guide to Using swmm-api

This guide assumes you’re familiar with SWMM .inp files and basic Python.


✅ Step 1: Install Dependencies

Clone the repository:

git clone https://github.com/jbgo/swmm-api.git
cd swmm-api
pip install -r requirements.txt

Install a compatible version of SWMM5 engine:

  • Windows: download swmm5.dll
  • Linux: compile swmm5.so
  • Place it in your project directory or system path

✅ Step 2: Prepare a SWMM Model

Use EPA SWMM or QGIS plugin to create a .inp file defining:

  • Subcatchments
  • Junctions
  • Pipes
  • Control rules
  • Simulation time and rainfall data

✅ Step 3: Initialize Simulation

from swmm_api.input_file import read_inp_file
from swmm_api.simulation import Simulation

inp = read_inp_file("model.inp")
sim = Simulation(inp)

sim.start()


✅ Step 4: Step Through Simulation

while not sim.is_finished():
    sim.step_advance()  # advance simulation
    flow = sim.get_link_result('C1')['flow_rate']
    depth = sim.get_node_result('J2')['depth']
    print(f"Flow at C1: {flow:.2f} m³/s, Depth at J2: {depth:.3f} m")


✅ Step 5: Inject Custom Logic

if depth > 1.5:
    sim.set_link_setting('C1', 0.3)  # throttle valve


✅ Step 6: Post-Process and Visualize

import matplotlib.pyplot as plt

times = sim.get_times()
flows = sim.get_link_result('C1')['flow_rate_series']

plt.plot(times, flows)
plt.title("Flow Rate at Conduit C1")
plt.xlabel("Time")
plt.ylabel("Flow (m³/s)")
plt.show()


✅ Step 7: Advanced Uses

  • Combine with sensor data via requests or MQTT
  • Integrate with Jupyter notebooks for interactive analysis
  • Automate batch runs for calibration

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
0
Would love your thoughts, please comment.x
()
x