Skip to main content

License PyPI Python versions Downloads DOI

Development notice: swmmx is under active testing and development. Issues are being identified and corrected continuously, so please make sure you are using the latest available release before reporting unexpected behavior.

Disclaimer

  • Domain knowledge required: swmmx is a programmatic wrapper and toolkit for EPA SWMM. Effective use requires an understanding of hydrologic and hydraulic principles, SWMM input conventions, and the mechanics of the EPA SWMM engine.
  • Engineering judgment required: Simulation results should always be validated before use. Professional engineering judgment is required to interpret, verify, and apply any output generated by this package for real-world design, planning, or decision-making.
  • Beta software / notice of risk: This project is actively maintained, but it may still contain bugs, errors, or unresolved issues that can cause incorrect calculations, incomplete outputs, or runtime errors. Please verify critical calculations independently and report bugs through the repository Issues tab.

swmmx

swmmx A Unified Python Toolkit for Building, Editing, Running, Importing, Visualizing, and Exporting EPA SWMM Models:

Install:

pip install swmmx

How to use:

from swmmx import swmm

m = swmm("examples/example.inp")
m.plot_layout()
print(m.time.count())
lengths = m.get.conduit.length()
m.set.conduit.roughness(0.013)
m.run()
print(m.log())
m.plot_timeseries.link.flow()

Version 0.0.44 currently provides:

  • swmm(path=None, new=None, flow_unit=None, custom_dll_path=None)
  • m.time.vector(), m.time.count(), m.time.vector_run(), m.time.count_run()
  • structured parameter access through m.get.<main_category>.<sub_category>() and m.set.<main_category>.<sub_category>()
  • discoverable object counts through m.count.<main_category>(), m.count.model(), m.count.model_dict(), and m.count.model_df()
  • editable model construction through m.add.<category>.<element_type>() and m.remove.<category>.<element_type>()
  • complete storage-unit and flow-divider construction, validated parameter editing, coordinates/tags, native results, and CSV/Excel/GIS interchange
  • matplotlib plotting through m.plot_layout(), m.plot_timeseries.<category>.<sub_category>(), and m.plot_profile.*
  • tabular and spatial imports through m.import_csv.<category>.<element_type>() and m.import_gis.<category>.<element_type>()
  • external-format export through m.export.gis(), m.export.csv(), and m.export.excel()
  • m.save(), m.run(), m.runs() for step-by-step simulation, m.validate(), m.log(), and m.clone()
  • lazy native-engine loading for bundled Windows/Linux/macOS engines plus custom engine paths
  • preserving .inp parsing/writing that keeps comments, unknown sections, and section order whenever possible

Constructor examples:

m = swmm("examples/example.inp")         # open an existing model
m = swmm()                               # new SI model, LPS by default
m = swmm(new="SI", flow_unit="CMS")      # new SI model
m = swmm(new="US", flow_unit="GPM")      # new US model

Storage units and flow dividers

Storage units and dividers are first-class nodes, with coordinates, tags, dependency-aware removal, layout annotations and native simulation results. Example 22 — Storage units and flow dividers builds a two-pond network and compares all four divider rules. See also the release notes.

from swmmx import swmm

m = swmm(new="SI", flow_unit="CMS")
m.options["FLOW_ROUTING"] = "KINWAVE"
m.add.node.storage_unit("Pond", x=0, y=0, invert_elevation=2,
    max_depth=3, initial_depth=0.5, area=100, tag="Detention",
    evaporation_factor=0.8, seepage_loss=(75, 1.5, 0.25))
m.add.node.divider("Split", x=100, y=0, invert_elevation=1,
    max_depth=3, type="CUTOFF", cutoff_flow=0.05)
m.add.node.outfall("River", x=200, y=50, invert_elevation=0)
m.add.node.outfall("BypassOut", x=200, y=-50, invert_elevation=0)
m.add.link.conduit("Feed", from_node="Pond", to_node="Split", length=100)
m.add.link.conduit("Normal", from_node="Split", to_node="River", length=100)
m.add.link.conduit("Bypass", from_node="Split", to_node="BypassOut", length=100)
m.set.flow_divider.diverted_link("Bypass", ids="Split")
assert m.validate().ok
m.save("detention.inp")
result = m.run()
assert result.success, m.log()
depth = m.get.storage_unit.depth(ids="Pond")
split_inflow = m.get.flow_divider.total_inflow(ids="Split")
  • FUNCTIONAL storage uses area_coefficient * depth ** area_exponent + area_constant. area aliases area_constant; both must agree if supplied together. Omitted numeric geometry values default to zero. TABULAR requires storage_curve pointing to an existing STORAGE curve and rejects functional fields.
  • storage_curve_type also accepts EPA 5.2 CYLINDRICAL, CONICAL, PARABOLIC and PYRAMIDAL. The three area_* fields then carry EPA's length, width and slope/height tokens. PARABOLIC uses top dimensions and top height; the other shapes use base dimensions (the third token is unused for CYLINDRICAL).
  • surcharge_depth, evaporation_factor, suction_head, hydraulic_conductivity and initial_moisture_deficit are persisted. seepage_loss accepts a Ksat scalar, a (Psi, Ksat, IMD) tuple/list, or a dictionary using the three named seepage fields. The getter returns Ksat; use the named getters for all three components. SI infiltration units are mm and mm/hour; US units are inches and inches/hour. Evaporation factor and moisture deficit are fractions from 0 to 1.
  • Divider types are OVERFLOW (default), CUTOFF (cutoff_flow), TABULAR (diversion_curve, referencing a DIVERSION curve), and WEIR (cutoff_flow, weir_height, weir_coefficient). cutoff_flow is the minimum diversion flow for WEIR. Inapplicable fields raise InvalidParameterError.
  • Omit diverted_link or use "*" while constructing the network, then assign the existing outgoing link. validate() reports an unassigned link as an error. Named references must exist and leave that divider. Dividers operate under Steady/Kinematic Wave routing; Dynamic Wave treats them as junctions.
  • m.get.storage_unit.* / m.set.storage_unit.* and m.get.flow_divider.* / m.set.flow_divider.* expose input fields, x, y, and tag; getters also expose depth, head, volume, lateral_inflow, total_inflow, and flooding. Inapplicable getters return None. Successful mutations mark results stale. Relation-type changes accept a mapping with the type and its new parameters, for example m.set.flow_divider.type({"type": "CUTOFF", "cutoff_flow": 0.1}, ids="Split") or m.set.storage_unit.storage_curve_type({"storage_curve_type": "TABULAR", "storage_curve": "AreaCurve"}, ids="Pond"). Common node fields are preserved and the whole edit is validated before writing. A complete import update is also supported. Scalar type changes and ID renames are guarded to prevent partial changes to dependent data.
  • m.remove.node.storage_unit(ids, force=False) and m.remove.node.divider(ids, force=False) block link/subcatchment dependencies. force=True only cascades safe conduits. Complex references and subcatchment cascades raise NotImplementedYetError without changing the model.

Use m.export.csv(elements=["storage_units", "dividers"]) (or .excel() / .gis()) and m.import_csv.node.storage_unit(...) / m.import_csv.node.flow_divider(...); GIS uses the same paths under m.import_gis. Exports include named hydraulic fields, x/y and tags. For a fresh network, import curves, create nodes with unassigned divider links, import links, then assign diverted links. With existing links/curves, mode="update" supports direct export/import round trips.

Examples

The repository includes a small learning suite in examples/. The main folder now holds the simplest teaching scripts: no main() function, no try blocks, and fewer defensive branches, so the API is easy to read line by line. The fuller runnable versions live in examples/standard/, where they include validation, safer branching, and file-output handling.

Topic Simple learning version Standard example
Open, validate, and run 01_open_validate_run.py standard/01_open_validate_run.py
Modify conduit diameters and compare 02_modify_conduit_diameters_compare.py standard/02_modify_conduit_diameters_compare.py
Step-by-step runs 03_step_by_step_runs_dynamic_control.py standard/03_step_by_step_runs_dynamic_control.py
Layout plots 04_plot_layout_examples.py standard/04_plot_layout_examples.py
Time-series plots 05_plot_timeseries_examples.py standard/05_plot_timeseries_examples.py
Profile plots 06_plot_profile_examples.py standard/06_plot_profile_examples.py
GIS/CSV/Excel export 07_export_examples.py standard/07_export_examples.py
Time and count helpers 08_time_and_count_functions.py standard/08_time_and_count_functions.py
Get/set patterns 09_get_set_examples.py standard/09_get_set_examples.py
Build a model from scratch 10_create_model_from_scratch_add_remove.py standard/10_create_model_from_scratch_add_remove.py
Add/remove LID controls 17_add_remove_lids.ipynb Focused notebook
Assign LIDs to subcatchments 18_subcatchment_lid_usage.ipynb Focused notebook
Compare LID scenarios 19_lid_scenario_comparison.ipynb Scenario lab notebook
Compare rainfall scenarios 20_rainfall_scenario_comparison.ipynb Design-storm scenario lab
Run scenarios in parallel 21_parallel_scenario_runs.ipynb Parallel scenario lab

Run them from the repository root:

python examples/01_open_validate_run.py
python examples/standard/01_open_validate_run.py

The examples use examples/example.inp, avoid overwriting it, and write generated files into examples/output/.

Installation note

swmmx intentionally does not install third-party scientific packages for you. This keeps package installation lightweight and avoids changing an existing scientific Python environment unexpectedly.

Before creating a model, install the runtime packages you need:

python -m pip install numpy pandas matplotlib networkx

When you call swmm(...), the package checks that those runtime packages are available and raises a clear error if any are missing.

Native engines

The package includes the supplied bundled engines:

  • Windows 64-bit: swmm5.dll
  • Linux 64-bit: libswmm5.so
  • macOS: libswmm5.dylib

Time semantics

m.time.vector() mirrors SWMM reporting behavior: it starts at the first report interval after REPORT_START_* and proceeds through END_*.

frame = m.time.vector() # pandas DataFrame with timestamp index

Run-time vectors use the actual period count read from the .out file after the engine finishes. m.time.count() remains the expected pre-run count; m.time.count_run() is the actual post-run count and requires results.

Step-by-step simulation with m.runs()

m.runs() is one of the most powerful tools in swmmx: it exposes the native SWMM step loop as a Python iterator. Use it when you want to monitor a simulation as it advances, build progress displays, inspect step times, or prepare workflows that react during a run instead of waiting only for the final .out file.

for step in m.runs():
    print(step.index, step.time, step.elapsed_days)

print(m.time.count_run())  # available after the stepped run finishes

Parameter access

lengths = m.get.conduit.length()
one_length = m.get.conduit.length("P001")
flow = m.get.link.flow(ids=["P001", "P005"], format="df")

m.set.conduit.roughness(0.013)
m.set.conduit.roughness([0.013, 0.014], ids=["P001", "P005"])

Supported getters default to NumPy output; format="df" gives pandas output. dir(m.get.<category>) now exposes the full declared parameter surface, including input fields, attached records, derived values, and result variables. dir(m.set.<category>) exposes the full editable surface. Attempting to set a derived or result parameter raises a read-only error. If a valid model simply has no objects of a requested type, an all-object getter such as m.get.weir.crest_height() returns an empty result; explicit missing IDs still raise a clear UnknownIDError.

API reference notebooks

For users who prefer a browsable learning reference, the examples/ folder includes several complete Jupyter notebooks:

These notebooks are useful both as tutorials and as a practical API checklist when editing models interactively in Jupyter, VS Code, or Spyder.

Counts

m.count.conduit()
m.count.node()
m.count.subcatchment()

total = m.count.model()
by_type = m.count.model_dict()
summary = m.count.model_df()

Count helpers take no ids or format arguments and always reflect the current in-memory model, including unsaved add/remove edits. m.count.model() totals detailed element types without double-counting composite rollups such as node and link; the dictionary and DataFrame summaries expose the detailed counts behind that total.

Add and remove elements

from swmmx import swmm

m = swmm(new="SI")

m.add.node.junction("J1", x=0.0, y=0.0, invert_elevation=10, max_depth=3)
m.add.node.outfall("OUT1", x=100.0, y=0.0, invert_elevation=9, type="FREE")

m.add.link.conduit(
    "C1",
    from_node="J1",
    to_node="OUT1",
    length=100,
    roughness=0.013,
    shape="CIRCULAR",
    diameter=1.0,
)

# Referenced objects must exist before they are used.
m.add.time.time_series(
    "Rain1",
    data=[
        ("2026-01-01 00:00", 0.0),
        ("2026-01-01 00:05", 5.0),
    ],
)
m.add.hydrology.rain_gage(
    "RG1",
    format="INTENSITY",
    interval="00:05",
    source_type="TIMESERIES",
    time_series="Rain1",
)
m.add.hydrology.subcatchment(
    "S1",
    rain_gage="RG1",
    outlet="J1",
    x=0.0,
    y=0.0,
    area=1.0,
)

m.save("new_model.inp")

m.remove.link.conduit("C1")

The add API validates IDs, required fields, numeric values, enums, and references before it writes EPA SWMM records. The remove API validates dependencies before deletion; by default it refuses unsafe removals, while force=True performs only conservative cascades that are known to remain valid. For example, removing a node with force=True can remove dependent conduits, but unsupported cascades raise a clear error instead of leaving broken references.

Coordinate handling is explicit where geometry is part of the object definition:

  • new node objects require x and y map coordinates;
  • new subcatchments require x and y centroid coordinates, while polygon= remains the optional outline geometry;
  • new rain gages may still omit coordinates, in which case swmmx uses the maximum mapped x and y, or (0, 0) when the model has no map coordinates.

Every add or remove operation sets m.modified to True. If the model already had results, the edit also sets m.results_stale to True and invalidates the old result accessors until the model is run again.

LID controls

swmmx can create and remove complete EPA SWMM LID controls through the same editable API. A LID control is written as a multi-row [LID_CONTROLS] object: one type row plus the required process-layer rows for the selected LID type. The public function accepts friendly type names or SWMM codes (BC, RG, GR, IT, PP, RB, RD, VS) and layer dictionaries for surface, soil, storage, pavement, drain, drain_mat, and pollutant removals.

m.add.hydrology.lid_control(
    "BR1",
    type="bio_retention_cell",
    surface={
        "storage_depth": 150,
        "vegetation_fraction": 0.1,
        "roughness": 0.05,
        "slope": 0.0,
        "side_slope": 0.0,
    },
    soil={
        "thickness": 450,
        "porosity": 0.45,
        "field_capacity": 0.20,
        "wilting_point": 0.10,
        "conductivity": 25,
        "conductivity_slope": 10,
        "suction_head": 75,
    },
    storage={
        "height": 300,
        "void_ratio": 0.75,
        "seepage_rate": 5,
        "clogging_factor": 0,
    },
    drain={
        "coefficient": 0.5,
        "exponent": 0.5,
        "offset_height": 0,
        "delay": 0,
    },
)

# Remove one control. If it is used by [LID_USAGE], this blocks by default.
m.remove.hydrology.lid_control("BR1")

# Cascade-remove dependent LID_USAGE rows intentionally.
m.remove.hydrology.lid_control(["BR1", "RG1"], force=True)

By default, lid_control validates the layer combination for each EPA SWMM LID type: bio-retention cells, rain gardens, green roofs, infiltration trenches, permeable pavement, rain barrels, rooftop disconnection, and vegetative swales. Missing values inside a provided layer are filled with SWMM-safe zeros so users can start simple and then refine parameters. Use strict_layers=False only when deliberately preserving an advanced or non-standard SWMM layer combination.

Subcatchment LID usage

Version 0.0.42 adds high-level support for assigning LID controls to subcatchments through the same namespace style as other model edits. These methods write [LID_USAGE] rows and cover the EPA SWMM LID Usage Editor and LID Group Editor settings.

# Add one LID control assignment to a subcatchment.
m.set.subcatchment.lid_controls.add("S1", "BR1", area_percent=10)

# Use full editor options when needed.
m.set.subcatchment.lid_controls.add(
    "S1",
    "BR1",
    area_percent=10,
    number=2,
    width=4.5,
    initial_saturation=25,
    from_impervious_percent=40,
    from_pervious_percent=10,
    return_flow_to_pervious=True,
    report_file="S1_BR1_lid.txt",
    drain_to="J1",
    replace=True,
)

# Inspect, remove one assignment, or clear all assignments from a subcatchment.
m.get.subcatchment.lid_controls("S1")
m.set.subcatchment.lid_controls.remove("S1", "BR1")
m.set.subcatchment.lid_controls.clear("S1")

# Replace all LID assignments for S1 in one call.
m.set.subcatchment.lid_controls(
    [
        {"lid_control": "BR1", "area_percent": 10},
        {"lid_control": "RG1", "area_percent": 5},
    ],
    ids="S1",
)

Mandatory inputs for .add() are the subcatchment ID, the LID control ID, and one sizing definition: area, area_percent, or occupies_full_subcatchment=True. Optional inputs are number (default 1), width (auto-estimated from area when omitted), initial_saturation, from_impervious_percent, from_pervious_percent, return_flow_to_pervious, report_file, drain_to, and replace. area_percent is converted to SWMM's per-unit LID area using the model unit system: hectares to square meters for SI flow units, and acres to square feet for US flow units. Group checks prevent total LID area, impervious-area treatment, or pervious-area treatment from exceeding 100% within a subcatchment.

For worked LID guides, see examples/17_add_remove_lids.ipynb and examples/18_subcatchment_lid_usage.ipynb.

Generic fallbacks are also available:

m.add_element("node", "junction", "J2", x=200.0, y=0.0, invert_elevation=11, max_depth=2)
m.remove_element("node", "junction", "J2")

Add/remove reference notebooks

For a full constructor/removal reference, see:

  • examples/13_all_add_functions.ipynb: every m.add.<category>.<element_type>() endpoint, grouped by category, with tables for required inputs, optional inputs, types, defaults, coordinate rules, references, implementation status, and conditions.
  • examples/14_all_remove_functions.ipynb: every m.remove.<category>.<element_type>() endpoint, grouped by category, with tables for ids, force, dependency checks, removal summaries, implementation status, and safe-cascade behavior.

Plotting

swmmx uses matplotlib directly for network maps, result time series, and longitudinal profiles:

m.plot_layout()

m.plot_layout(
    title="Drainage Network",
    legend=True,
    grid=True,
    axis=True,
)

m.plot_layout(
    links={
        "color": {
            "by": "parameter",
            "category": "conduit",
            "variable": "roughness",
            "mode": "continuous",
            "cmap": "viridis",
        }
    }
)

m.plot_layout(
    annotation={
        "nodes": "id",
        "conduits": {
            "template": "{id}\nD={diameter:.2f} m",
            "rotation": "link",
            "bbox": True,
        },
    }
)

m.plot_timeseries.link.flow(["C1", "C2"])

m.plot_profile.nodes(
    "J1",
    "OUT1",
    show_hgl=True,
    aggregation="max",
)

m.plot_layout() draws mapped subcatchments, links, nodes, rain gages, and LID usages from the model coordinates. Subcatchments show dashed outlet connectors from each polygon centroid to its outlet node or downstream subcatchment. The default symbology is type-aware: node types use different markers, link types use different line styles, and LID controls use distinct markers in the legend when present. Presentation controls are explicit: title=... sets the map title, axis=True shows coordinate axes, grid=True keeps a visible reference grid even when coordinate labels stay hidden, and show=False suppresses automatic figure display while still returning (fig, ax). Layout maps now render titles, grids, and visible coordinate axes with safe ordinary artists instead of Matplotlib's native title/tick/grid machinery, avoiding the Spyder/Agg recursive tick-copy path while keeping the same public API. On non-interactive matplotlib canvases such as Agg, show=True avoids useless GUI calls but keeps the figure available for Spyder/Jupyter rendering; show=False removes only the library-created figure manager so hidden plots stay hidden.

Layer dictionaries support ordinary static styling as well as data-driven styling from fixed input parameters, simulation results, or your own ID-to-value mappings. Nodes, links, and subcatchments can be colored with continuous or discrete colormaps; nodes can use data-driven marker size, and links can use data-driven line width (or the size alias). Result-driven styles require a completed run; user-data styles are useful for classes such as risk bands, inspection status, or scenario groups. When color, size, or width is data-driven, the plot adds a dedicated legend section so the encoded value is visible on the finished figure instead of living only in the function call. Continuous-color legends are rendered with safe sampled swatches rather than native Matplotlib colorbar axes, which keeps Spyder/Agg rendering out of the recursive tick-copy path.

m.plot_layout(annotation=...) adds map labels without changing existing layout behavior. It supports simple ID annotations, multi-field labels, templates such as {id}\nD={diameter:.2f} m, prefixes, suffixes, numeric formatting, callables, per-layer styling, ID and conditional filtering, max_labels, external user data, and link-aligned rotation with rotation="link".

m.plot_timeseries.<category>.<sub_category>() routes through the result API and plots one or many timestamped series with matplotlib. The time axis has three explicit modes: time_format="datetime" for full date-time labels, time_format="clock" for hour-minute labels, and time_format="elapsed" for elapsed hours. X-axis tick labels are rotated 45 degrees by default for readability. Time-series and profile plots draw their title, grid, frame, ticks, and axis labels with safe ordinary artists instead of Matplotlib's native Axis artists, and their legends use lightweight proxy handles rather than cloning plotted Line2D artists. This keeps Spyder/Agg out of both recursive marker-copy paths while preserving the same public plotting API.

m.plot_profile.nodes(), .links(), and .longest() render geometry-first longitudinal profiles, with HGL/water overlays available after a run. Profiles show prominent vertical dotted node guides, shaded conduit barrels between invert and crown, and link names by default; distance and elevation axes infer ft or m automatically from the model units. m.plot_profile.links([...]) accepts any connected ordered walk, even when the supplied sequence runs opposite to the hydraulic direction.

All plotting calls return (fig, ax), accept ax= for composition, and support save_path= / save_format=. Common errors are explicit: layout plots need coordinates, result-based plots need m.run(), invalid IDs raise UnknownIDError, and disconnected profile requests raise NoPathError.

For a complete plotting reference, see examples/15_all_plot_functions.ipynb. It documents every plotting endpoint, every input and default, all dynamic time-series variables, runnable layer-dictionary examples for nodes/links/subcatchments/connectors/rain gages/LIDs/labels, custom-style legend behavior, profile controls, outputs, save behavior, and common validation errors.

Import

swmmx uses m.import_csv and m.import_gis instead of m.import because import is a reserved Python keyword. The import API mirrors the rest of the package:

m.import_csv.node.junction("junctions.csv")
m.import_csv.node.outfall("outfalls.csv")
m.import_csv.link.conduit("conduits.csv")
m.import_csv.hydrology.subcatchment("subcatchments.csv")

m.import_gis.node.junction("junctions.shp")
m.import_gis.link.conduit("pipes.geojson")
m.import_gis.hydrology.subcatchment("subcatchments.gpkg", layer="subcatchments")

Importers normalize column names, apply aliases such as Node ID -> id, Easting -> x, Northing -> y, validate rows, and return an ImportResult:

import_result = m.import_csv.node.junction("junctions.csv")
print(import_result.summary())

result = m.import_csv.link.conduit(
    "pipes.csv",
    field_map={
        "id": "PipeID",
        "from_node": "FromNode",
        "to_node": "ToNode",
        "length": "Length",
        "roughness": "ManningN",
        "diameter": "Diameter",
    },
)

print(result.summary())
print(result.to_frame())

Use dry_run=True to validate without modifying the model, and mode="upsert" to add missing objects while updating existing ones:

dry_run = m.import_csv.node.junction("junctions.csv", dry_run=True)
upserted = m.import_csv.node.junction("junctions.csv", mode="upsert")

Group-level shortcuts dispatch rows by a type column:

m.import_csv.node("nodes.csv", default_type="junction")
m.import_csv.link("links.csv", default_type="conduit")
m.import_gis.node("nodes.shp")
m.import_gis.link("links.shp")

Common options are mode="add" | "update" | "upsert", dry_run=True, on_missing_required="error" | "skip", on_unknown_fields="ignore" | "warn" | "error", and on_error="raise" | "skip" | "collect". GIS import lazily requires geopandas and shapely; install them with pip install geopandas shapely.

CSV files created by m.export.csv() are designed to import back cleanly. Exact SWMM input columns take priority over result or derived columns with similar names (for example, max_depth is preferred over exported result depth), and exported helper fields such as element_type, stage_data, source_data, and serialized coordinates are translated back into the matching import options where possible.

For a complete import/export reference, see examples/16_all_import_export_functions.ipynb.

Export

m.export.gis()

m.export.gis(
    path="exports/gis",
    elements=["nodes", "links", "subcatchments"],
)

m.export.csv(
    path="exports/csv",
    elements="all",
    time_step=-1,
)

m.export.excel(
    path="exports",
    file_name="model_export.xlsx",
)

If path is omitted, exports go beside the model file when one exists, otherwise into the current working directory. file_name controls a single workbook name or the prefix used for multi-file CSV/GIS exports. elements accepts named tables, groups such as hydrology or quality, or "all".

When results are available, time_step=-1 attaches the last simulated snapshot to result-capable tables. Without results, exports continue with parameter-only tables and a warning by default; use strict_results=True when missing results should be treated as an error. CSV writes one UTF-8 file per table, while Excel writes one workbook with one sheet per selected table. All CSV, Excel, and GIS export tables include a coordinates field: point objects store [x,y], links store the full coordinate chain from upstream node through vertices to downstream node, and subcatchments store polygon coordinates when available. Node-based and point-based export tables also include plain x and y fields: all node types use [COORDINATES], rain gages use [SYMBOLS], node-attached records inherit their node coordinates, and subcatchments/subcatchment-attached records use the polygon centre point.

GIS export writes spatial layers for nodes, links, subcatchments, and rain gages. It requires the optional packages geopandas and shapely (pip install geopandas shapely). Existing outputs are protected by default; pass overwrite=True only when replacing files is intentional.

Public parameter catalog

The public dotted API is organized into the following categories and subcategories:

  • option_general: flow_units, infiltration_model, flow_routing, link_offsets, force_main_equation, allow_ponding, minimum_slope, skip_steady_state, system_flow_tolerance, lateral_flow_tolerance
  • option_process: ignore_rainfall, ignore_snowmelt, ignore_groundwater, ignore_rdii, ignore_routing, ignore_quality
  • option_date_time: start_date, start_time, end_date, end_time, report_start_date, report_start_time, report_step, wet_step, dry_step, routing_step, rule_step, sweep_start, sweep_end, dry_days
  • option_dynamic_wave: inertial_damping, normal_flow_limited, surcharge_method, variable_step, minimum_step, lengthening_step, minimum_surface_area, head_tolerance, maximum_trials, threads
  • rain_gage: id, count, format, interval, snow_catch_factor, source_type, time_series, filename, station, units, rainfall
  • subcatchment: id, count, rain_gage, outlet, area, width, slope, impervious_percent, curb_length, snow_pack, tag, polygon, centroid, rainfall, snow_depth, evaporation, infiltration, runoff, groundwater_flow, groundwater_elevation, soil_moisture, pollutant_concentration, n_impervious, n_pervious, depression_storage_impervious, depression_storage_pervious, zero_depression_storage_impervious_percent, subarea_routing, percent_routed
  • infiltration_horton: maximum_rate, minimum_rate, decay, dry_time, maximum_volume
  • infiltration_green_ampt: suction_head, hydraulic_conductivity, initial_moisture_deficit
  • infiltration_curve_number: curve_number, conductivity, dry_time
  • node: id, count, type, invert_elevation, max_depth, initial_depth, surcharge_depth, ponded_area, tag, coordinate, external_inflow, dry_weather_flow, treatment, depth, head, volume, lateral_inflow, total_inflow, flooding, overflow, pollutant_concentration
  • junction: id, count, invert_elevation, max_depth, initial_depth, surcharge_depth, ponded_area
  • outfall: id, count, invert_elevation, type, fixed_stage, tidal_curve, time_series, tide_gate, route_to
  • flow_divider: id, count, invert_elevation, max_depth, initial_depth, surcharge_depth, ponded_area, type, diverted_link, cutoff_flow, diversion_curve, weir_height, weir_coefficient, x, y, tag, depth, head, volume, lateral_inflow, total_inflow, flooding
  • storage_unit: id, count, invert_elevation, max_depth, initial_depth, storage_curve_type, storage_curve, area, area_coefficient, area_exponent, area_constant, evaporation_factor, seepage_loss, x, y, tag, depth, head, volume, lateral_inflow, total_inflow, flooding, surcharge_depth, suction_head, hydraulic_conductivity, initial_moisture_deficit
  • link: id, count, type, from_node, to_node, inlet_offset, outlet_offset, initial_flow, maximum_flow, flap_gate, tag, vertices, flow, depth, velocity, volume, capacity, setting, pollutant_concentration
  • conduit: id, count, from_node, to_node, length, roughness, inlet_offset, outlet_offset, initial_flow, maximum_flow, shape, geometry, barrels, culvert_code, entry_loss, exit_loss, average_loss, flap_gate, seepage_rate, slope, full_area, full_depth, hydraulic_radius, full_flow, normal_depth, critical_depth, flow, depth, velocity, capacity
  • pump: id, count, from_node, to_node, curve, initial_status, startup_depth, shutoff_depth, flow, status, setting, energy
  • orifice: id, count, from_node, to_node, type, shape, height, width, offset, discharge_coefficient, flap_gate, open_close_time, flow, setting
  • weir: id, count, from_node, to_node, type, crest_height, length, side_slope, discharge_coefficient, flap_gate, end_contractions, end_coefficient, surcharge, road_width, road_surface, flow, setting
  • outlet: id, count, from_node, to_node, offset, flap_gate, rating_type, curve, coefficient, exponent, flow, setting
  • cross_section: link, shape, geometry_1, geometry_2, geometry_3, geometry_4, barrels, culvert_code, height, width, side_slope, shape_curve
  • transect: id, count, roughness_left, roughness_right, roughness_channel, left_bank, right_bank, stations, elevations, modifiers
  • curve: id, count, type, x, y, points
  • coordinate: node_coordinates, subcatchment_coordinates, link_vertices, polygons, labels, map_dimensions, map_units
  • street: id, count, crown_width, curb_height, cross_slope, roughness, depression_storage, gutter_width, gutter_slope, spread
  • inlet: id, count, type, grate_length, grate_width, grate_type, curb_length, curb_height, slotted_length, slotted_width, captured_flow
  • inlet_usage: node, inlet, conduit, number, clogging_factor, flow_restriction
  • lid_control: id, count, type
  • lid_surface: storage_depth, vegetation_fraction, roughness, slope, side_slope
  • lid_pavement: thickness, void_ratio, impervious_surface_fraction, permeability, clogging_factor, regeneration_interval, regeneration_fraction
  • lid_soil: thickness, porosity, field_capacity, wilting_point, conductivity, conductivity_slope, suction_head
  • lid_storage: height, void_ratio, seepage_rate, clogging_factor, covered
  • lid_drain: coefficient, exponent, offset_height, delay, open_level, closed_level, control_curve
  • lid_drain_mat: thickness, void_ratio, roughness
  • lid_usage: subcatchment, lid_control, number, area, width, initial_saturation, from_impervious_percent, return_flow_to_pervious, report_file, drain_to, from_pervious_percent, area_percent, occupies_full_subcatchment, inflow, evaporation, infiltration, surface_outflow, drain_outflow, storage
  • aquifer: id, count, porosity, wilting_point, field_capacity, conductivity, conductivity_slope, tension_slope, upper_evaporation_fraction, lower_evaporation_depth, lower_groundwater_loss_rate, bottom_elevation, water_table_elevation, unsaturated_moisture, upper_evaporation_pattern
  • groundwater: subcatchment, aquifer, node, surface_elevation, a1, b1, a2, b2, a3, fixed_depth, threshold_elevation, lateral_flow_equation, deep_flow_equation
  • snow_pack: id, count, plowable_fraction, impervious_fraction, pervious_fraction, minimum_melt_coefficient, maximum_melt_coefficient, base_temperature, free_water_capacity_fraction, initial_snow_depth, initial_free_water, depth_at_100_percent_cover, removal_depth, fraction_to_impervious, fraction_to_pervious, fraction_to_immediate_melt, fraction_to_subcatchment, fraction_to_outflow, destination_subcatchment
  • climate: temperature_time_series, evaporation_type, evaporation_constant, evaporation_monthly, evaporation_time_series, evaporation_recovery_pattern, evaporation_dry_only, wind_speed_type, wind_speed_monthly, snowmelt_parameters, areal_depletion_impervious, areal_depletion_pervious
  • climate_adjustment: temperature, evaporation, rainfall, conductivity
  • pollutant: id, count, units, rain_concentration, groundwater_concentration, rdii_concentration, decay_coefficient, snow_only, co_pollutant, co_pollutant_fraction, dry_weather_flow_concentration, initial_concentration
  • land_use: id, count, sweeping_interval, sweeping_availability, last_swept
  • coverage: subcatchment, land_use, percent
  • loading: subcatchment, pollutant, initial_buildup
  • buildup: land_use, pollutant, function, maximum_buildup, rate_constant, power, normalizer
  • washoff: land_use, pollutant, function, coefficient, exponent, cleaning_efficiency, bmp_efficiency
  • treatment: node, pollutant, expression
  • time_series: id, count, datetime, values, filename, description
  • time_pattern: id, count, type, multipliers
  • external_inflow: node, constituent, time_series, type, units_factor, scale_factor, baseline, pattern
  • dry_weather_flow: node, constituent, average_value, monthly_pattern, daily_pattern, hourly_pattern, weekend_pattern
  • rdii: node, unit_hydrograph, sewer_area
  • unit_hydrograph: id, count, rain_gage, month, short_term_r, short_term_t, short_term_k, medium_term_r, medium_term_t, medium_term_k, long_term_r, long_term_t, long_term_k
  • control_rule: id, count, text, conditions, actions, priority, enabled, action_log
  • interface_file: rainfall, runoff, hotstart, rdii, inflow, outflow, use_file, save_file
  • system_result: air_temperature, rainfall, snow_depth, evaporation, infiltration, runoff, dry_weather_inflow, groundwater_inflow, rdii_inflow, direct_inflow, total_lateral_inflow, flooding, outfall_flow, storage_volume, pollutant_loading
  • summary: model, counts, options, subcatchment_runoff, subcatchment_washoff, node_depth, node_inflow, node_flooding, node_surcharge, storage_volume, outfall_loading, link_flow, link_velocity, conduit_surcharge, pump_operation, lid_performance, runoff_continuity, flow_routing_continuity, quality_routing_continuity, validation_issues

Validation

validation = m.validate()
print(validation.ok)
print(validation.to_frame())

The first validator checks duplicate IDs, missing required options, invalid unit values, missing nodes/links, conduit endpoints, and several common cross-section/reference errors.

Comparison with common EPA SWMM Python packages

Feature / capability swmmx PySWMM swmm_api swmmio swmm-toolkit
Main purpose End-to-end SWMM modeling toolkit Runtime SWMM control SWMM file/result automation Pandas-based model/result analysis Low-level solver/output bindings
Unified model object Yes — m = swmm(...) Partial Partial Yes, but more DataFrame/file oriented No
Discoverable dotted API Yes — m.get, m.set, m.add, m.remove, m.import_csv, m.import_gis, m.export Limited More section/object oriented More pandas/DataFrame oriented Low-level API
Open existing .inp model Yes Yes Yes Yes Solver-level
Create new model from scratch Yes — swmm(new="SI"), m.add.* Limited / not main focus Supported in workflows Limited / not main focus No
Add/remove SWMM elements Yes — validated m.add.* and m.remove.* Limited Yes, through model/input structures Some support No
Structured parameter get/set Yes — broad public parameter catalog Yes for runtime objects Yes Yes via DataFrames Low-level
Step-by-step simulation Yes — m.runs() iterator Very strong; core strength Run support, less runtime-control focused Usually external / via integration Engine-level possible
Runtime control during simulation Developing / possible through m.runs() workflows Strongest option Not primary focus Not primary focus Low-level possible
Run SWMM from Python Yes — m.run() and m.runs() Yes Yes Usually via integration/tools Yes
Read simulation results Yes — result variables through m.get.* and plots Yes Yes, including .out / .rpt workflows Yes Output API level
Layout plotting Yes — built-in m.plot_layout() Not primary Available in ecosystem/examples Yes / visualization support No
Time-series plotting Yes — m.plot_timeseries.* User builds or uses ecosystem Possible Possible No
Longitudinal profile plotting Yes — m.plot_profile.* Not primary Available / supported in workflows Some visualization support No
CSV import Yes — m.import_csv.<category>.<element_type>() Not primary Possible through user workflows DataFrame-based workflows No
GIS import Yes — m.import_gis.<category>.<element_type>() Not primary GIS interaction available GeoDataFrame support No
CSV export Yes — m.export.csv() Not primary Possible DataFrame export possible No
GIS export Yes — m.export.gis() Not primary GIS interaction available GeoDataFrame support No
Excel export Yes — m.export.excel() Not primary Possible through pandas workflows Possible through pandas workflows No
Round-trip import/export workflow Yes — exported CSV designed to import back cleanly No Partial / workflow dependent Partial / workflow dependent No
Preserve .inp comments / unknown sections / section order Yes, where possible Not main focus Strong .inp handling .inp handling support No
Validation helpers Yes — m.validate() and import result reporting Engine/runtime errors Strong file/model checks depending workflow Data checks possible Low-level
Native engine handling Bundled Windows/Linux/macOS engines plus custom path Uses SWMM engine bindings Runs SWMM through configured executable/tooling Usually external / integration Solver bindings
Best use case Complete model lifecycle in one Python API Real-time control and simulation intervention Advanced .inp, .rpt, .out automation Pandas/GeoPandas engineering analysis Developers needing solver/output bindings
Main strength Unified, readable, high-level workflow Runtime control Mature file/result automation Pandas-first productivity Low-level SWMM access

Land-cover and GIS-based subcatchment parameterization

SWMMX landcover is distinct from EPA SWMM's native water-quality [LANDUSES] feature. Define physical classes, assign fractions or intersect GIS polygons, preview hydrology, assess LID candidate areas, and compare independent scenarios.

from swmmx import swmm, landcover

m = swmm("model.inp")
lc = landcover(m, units="SI")
lc.define_classes({"roof": {"impervious": 1}, "green": {"impervious": 0}})
lc.set_coverage({"S1": {"roof": 0.4, "green": 0.6}})
preview = lc.preview(parameters=["imperviousness"])
print(preview.changes)  # inspect before/after values and units
if preview.can_apply:
    lc.apply(preview)
m.save("landcover_model.inp")  # also writes landcover_model.swmmx.json

Area-weighted parameters are a preprocessing approximation, not independent SWMM runoff planes. GIS requires optional GeoPandas/Shapely and an explicit projected area CRS. LID suitability supplies candidate bounds without creating controls or usage. Native LANDUSES conversion is optional and protects existing quality data by default.

See the API, capability matrix and modelling guide and executable notebook 23 for GIS, subcatchments, infiltration, LIDs, native quality integration, validation and persistence.

Bulk tables, structured validation and frontend integration are explained in the backend contract.

Metadata

Release files for swmmx 0.0.44

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for swmmx 0.0.44
File Size Uploaded Provenance Actions
swmmx-0.0.44.tar.gz 1.4 MB With provenance Details for swmmx-0.0.44.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for swmmx 0.0.44
File Interpreter ABI Platform Actions
swmmx-0.0.44-py3-none-any.whl Python 3 none any Details for swmmx-0.0.44-py3-none-any.whl

Total release size: 2.6 MB

Release files / swmmx-0.0.44.tar.gz

Download URL swmmx-0.0.44.tar.gz
Size 1.4 MB
Tags Source
SHA-256 checksum
How to use checksums
f60672d2d3b58cb1377b6801cd74a71091a2536ab392492f77597cf8897f094f
BLAKE2b-256 checksum
How to use checksums
8672c08b791e1e3fb139fd4a313868425a4d44f187a9d856288ddbc0c3b8f2dd
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Release files / swmmx-0.0.44-py3-none-any.whl

Download URL swmmx-0.0.44-py3-none-any.whl
Size 1.2 MB
Tags Python 3
SHA-256 checksum
How to use checksums
0db2dca30af29d1e462f69cbb570f5ec3f8328ae1fdd3cbaaa1b4e7bfc294890
BLAKE2b-256 checksum
How to use checksums
3256860370f5eed4e27fa12053a8f9792a9eb2b0cf1fe5daaee420493bc68c1c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

Security for swmmx 0.0.44

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for swmmx-0.0.44.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 15, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.0.44 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page