API Reference#

This page is generated from the Cython type-stub files (.pyi) so signatures and docstrings are always in sync with the compiled extensions. Each entry below lists the public class for the module; private helpers prefixed with _ are intentionally hidden.

For task-oriented documentation see the User Guide.

openswmm#

The top-level package. Importing openswmm configures the platform-specific shared-library search path and re-exports the legacy SWMM 5 symbols for backward compatibility.

openswmm – Python bindings for the OpenSWMM stormwater modelling engine.

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Subpackages#

legacy.engine

Legacy EPA SWMM 5.x solver bindings (Cython).

legacy.output

Legacy EPA SWMM 5.x binary output reader (Cython).

engine

New data-oriented engine 6.x bindings (Cython).

This top-level package additionally:

  • Configures the platform-specific shared-library search path so the bundled C/C++ shared libraries can be located by the dynamic linker.

  • Resolves the package version string into __version__.

  • Re-exports the legacy engine and legacy output public symbols when their compiled Cython extensions are available, for backward compatibility with pre-6.x callers.


OpenSWMM 6 — refactored engine#

The openswmm.engine subpackage exposes the new, refactored OpenSWMM 6 engine — the recommended API for all new work.

All domain access is class-based: each class takes an active Solver in its constructor and may only be called when the solver is in an appropriate EngineState.

See also

OpenSWMM 6 User Guide (refactored engine) — task-oriented user guide for this engine.

openswmm.engine#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Cython bindings for the OpenSWMM Engine 6.0 C API.

The package is split by domain to mirror the C header organisation:

Table 1 Module Map#

Python class

C header

Contents

Solver

openswmm_engine.h

Engine lifecycle, timing, error reporting

ModelBuilder

openswmm_model.h

Programmatic model construction

ModelEditor

openswmm_edit.h

In-place model editing (delete + type conversion)

Nodes

openswmm_nodes.h

Node get/set, lateral inflow, bulk arrays

Links

openswmm_links.h

Link get/set, control settings, bulk arrays

Subcatchments

openswmm_subcatchments.h

Subcatchment runoff, rainfall override

Gages

openswmm_gages.h

Rain gage rainfall get/set

HotStart

openswmm_hotstart.h

Hot start save/open/apply/close

MassBalance

openswmm_massbalance.h

Continuity error queries

Statistics

openswmm_statistics.h

Cumulative simulation statistics

OutputReader

openswmm_output.h

Binary output file reader

Pollutants

openswmm_pollutants.h

Pollutant management and quality injection

Quality

openswmm_quality.h

Landuse, buildup, washoff, treatment

Tables

openswmm_tables.h

Time series, curves, patterns

Inflows

openswmm_inflows.h

External inflows, DWF, RDII

Controls

openswmm_controls.h

Control rules and direct actions

Forcing

openswmm_forcing.h

Advanced runtime forcing (mode + persistence)

Infrastructure

openswmm_infrastructure.h

Transects, streets, inlets, LIDs

Spatial

openswmm_spatial.h

Coordinates, CRS, vertices, polygons

Surface2D

openswmm_2d.h

2D surface mesh / coupled overland flow

GeoPackage (Optional)

openswmm_geopackage.h

GeoPackage import/export (requires OPENSWMM_WITH_GEOPACKAGE build)

Quick start#

from openswmm.engine import Solver, Nodes, Links

with Solver("model.inp", "model.rpt", "model.out") as s:
    nodes = Nodes(s)
    links = Links(s)
    while s.state == EngineState.RUNNING:
        if s.step() != 0:
            break
        depths = nodes.get_depths_bulk()  # numpy array
        flows  = links.get_flows_bulk()   # numpy array

Programmatic model building#

from openswmm.engine import ModelBuilder, NodeType, LinkType, XSectShape

m = ModelBuilder()
m.add_node("J1", NodeType.JUNCTION)
m.add_node("OUT1", NodeType.OUTFALL)
m.add_link("C1", LinkType.CONDUIT)
m.set_link_nodes(0, 0, 1)
m.set_link_length(0, 300.0)
m.set_link_roughness(0, 0.013)
m.set_link_xsect(0, XSectShape.CIRCULAR, 1.0)
m.validate()
m.finalize()

solver = m.to_solver()
solver.start()
while solver.state == EngineState.RUNNING:
    if solver.step() != 0:
        break
    pass
solver.end()
solver.destroy()

Advanced forcing#

from openswmm.engine import Solver, Nodes, Forcing, ForcingMode

with Solver("model.inp", "model.rpt", "model.out") as s:
    nodes   = Nodes(s)
    forcing = Forcing(s)

    j1 = nodes.get_index("J1")
    forcing.node_lat_inflow(j1, 1.5, ForcingMode.REPLACE, persist=True)

    while s.state == EngineState.RUNNING:
        if s.step() != 0:
            break
        pass

    forcing.clear_all()

Solver lifecycle#

Engine Lifecycle#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._solver.

The Solver class manages the full SWMM engine lifecycle: create -> open -> initialize -> start -> step -> end -> report -> close -> destroy.

exception EngineError(code, message='')#

Bases: Exception

Raised when a C API call returns a non-zero error code.

Variables:
  • code – The SWMM error code returned by the C API.

  • message – Human-readable error description.

Parameters:
  • code (int) – The SWMM error code.

  • message (str) – Human-readable error description. When empty, a default message is derived from the SWMM error code via the C API.

Return type:

None

class Solver(inp='', rpt='', out='')#

Bases: object

SWMM engine lifecycle manager.

Manages the complete SWMM simulation lifecycle from file parsing through timestep execution to report generation. Supports both manual lifecycle control and the context manager protocol.

Parameters:
  • inp (str) – Path to the SWMM input file (.inp).

  • rpt (str) – Path for the report file (.rpt). Empty string to skip.

  • out (str) – Path for the binary output file (.out). Empty string to skip.

Note

The engine handle is created lazily on the first call to open. Multiple independent Solver instances may coexist.

Example:

from openswmm.engine import EngineState

with Solver("model.inp", "model.rpt", "model.out") as s:
    while s.state == EngineState.RUNNING:
        rc = s.step()
        if rc != 0:
            break
        print(f"Elapsed: {s.elapsed:.4f} days")
close()#

Close all files and free simulation state.

Transitions the engine to CLOSED state. Safe to call when the handle is already NULL.

Returns:

Error code from the C API (0 on success or when the handle is NULL, non-zero on failure).

Return type:

int

create()#

Create the engine instance.

Allocates the underlying C engine handle. This is normally called automatically by open; explicit calls are only needed when working with the engine handle directly.

Returns:

None

Return type:

None

Raises:

MemoryError – If allocation fails.

destroy()#

Destroy the engine handle and free all memory.

After this call the Solver no longer holds a valid C handle. Safe to call when the handle is already NULL.

Returns:

None

Return type:

None

property elapsed: float#

Elapsed simulation time in decimal days after the last step.

Returns:

Elapsed simulation time (decimal days).

Return type:

float

end()#

End the simulation; join the IO thread; finalize plugins.

Transitions the engine to ENDED state.

Returns:

Error code from the C API (0 on success, non-zero on failure).

Return type:

int

events_add(start, end)#

Append a new event window. Returns the new row index.

Raises:

EngineError – When start >= end or on C API failure.

Parameters:
Return type:

int

events_clear()#

Remove every event window. Safe on an already-empty list.

Raises:

EngineError – On C API failure.

Return type:

None

events_count()#

Number of [EVENTS] rows.

Return type:

int

Raises:

EngineError – On C API failure.

events_get(idx)#

Get the start/end OADate for the idx-th event window.

Parameters:

idx (int) – Zero-based row index.

Returns:

(start, end) OADate decimal days.

Raises:

EngineError – On bad index.

Return type:

tuple[float, float]

events_remove(idx)#

Remove the idx-th event. Trailing entries shift down.

Raises:

EngineError – On bad index.

Parameters:

idx (int)

Return type:

None

events_set(idx, start, end)#

Overwrite the idx-th event window.

Raises:

EngineError – On bad index or when start >= end.

Parameters:
Return type:

None

get_crs()#

Return the model’s coordinate reference system string.

Returns:

CRS string (EPSG identifier, PROJ string, or WKT).

Raises:

EngineError – On C API failure.

Return type:

str

get_current_time()#

Return the current simulation time.

Returns:

Current simulation time (decimal days).

Return type:

float

Raises:

EngineError – On C API failure.

get_end_time()#

Return the simulation end time.

Returns:

Simulation end time (decimal days).

Return type:

float

Raises:

EngineError – On C API failure.

get_event_count()#

Number of [EVENTS] rows. Synonym of events_count.

Return type:

int

Raises:

EngineError – On C API failure.

get_option(key)#

Return a SWMM option value as a string.

Parameters:

key (str) – Option key (e.g. "FLOW_UNITS", "FLOW_ROUTING").

Returns:

Option value as a string.

Raises:

EngineError – On unknown key or other C API failure.

Return type:

str

get_option_ext(key)#

Return the value of an extension option (unknown to base SWMM).

Raises:

EngineError – On unknown key.

Parameters:

key (str)

Return type:

str

get_routing_step()#

Return the routing timestep.

Returns:

Routing timestep (seconds).

Return type:

float

Raises:

EngineError – On C API failure.

get_start_time()#

Return the simulation start time.

Returns:

Simulation start time (decimal days).

Return type:

float

Raises:

EngineError – On C API failure.

get_steady_state_skip()#

Whether SKIP_STEADY_STATE routing skip is enabled.

Raises:

EngineError – On C API failure.

Return type:

bool

property handle: int#

Raw C engine handle as an integer (for advanced interop).

Returns:

The underlying C engine pointer cast to an integer.

Return type:

int

initialize()#

Initialize the simulation.

Allocates simulation arrays and applies initial conditions. Transitions the engine to INITIALIZED state.

Returns:

Error code from the C API (0 on success, non-zero on failure).

Return type:

int

is_between_events()#

Whether the current simulation time is inside a defined event window.

Returns:

True if there are no events, or if the current sim time falls within one.

Return type:

bool

Raises:

EngineError – On C API failure.

model_write(path)#

Write the current model to a SWMM .inp file.

Parameters:

path (str) – Output file path.

Returns:

None

Return type:

None

Raises:

EngineError – On C API failure.

open(plugin_lib=None)#

Open and parse the input file; load plugins.

Transitions the engine to OPENED state.

Parameters:

plugin_lib (str or None) – Optional path to a plugin shared library.

Returns:

Error code from the C API (0 on success, non-zero on failure). Lifecycle status is queryable via state.

Return type:

int

report()#

Write the summary report to the .rpt file.

Returns:

Error code from the C API (0 on success, non-zero on failure).

Return type:

int

set_option(key, value)#

Set a SWMM option.

Raises:

EngineError – On unknown key or invalid value.

Parameters:
Return type:

None

set_option_ext(key, value)#

Set the value of an extension option.

Raises:

EngineError – On C API failure.

Parameters:
Return type:

None

set_steady_state_skip(enabled)#

Enable or disable SKIP_STEADY_STATE routing.

Raises:

EngineError – On C API failure.

Parameters:

enabled (bool)

Return type:

None

set_step_begin_callback(callback)#

Register a callback invoked at the start of each routing timestep.

The callable receives (sim_time, dt) and is invoked before physics are computed — the right place to inject forcings or override boundary conditions. Pass None to unregister.

Lifetime: the callable is stored on the Solver instance for the duration of registration; do not hold a separate strong reference that outlives the solver.

Raises:

EngineError – On C API failure.

Parameters:

callback (Callable[[float, float], None] | None)

Return type:

None

set_step_end_callback(callback)#

Register a callback invoked at the end of each routing timestep.

The callable receives (sim_time, dt) and runs after physics — the right place to read results for monitoring or control. Pass None to unregister.

Raises:

EngineError – On C API failure.

Parameters:

callback (Callable[[float, float], None] | None)

Return type:

None

set_warning_callback(callback)#

Register a callback invoked on each non-fatal engine warning.

The callable receives (code, message). Pass None to unregister.

Lifetime: the callable is stored on the Solver instance for the duration of registration; do not hold a separate strong reference that outlives the solver.

Raises:

EngineError – On C API failure.

Parameters:

callback (Callable[[int, str], None] | None)

Return type:

None

start(save_results=True)#

Start the simulation.

Transitions the engine to RUNNING state and prepares the binary output file when save_results is True.

Parameters:

save_results (bool) – If True, write binary output to the C{.out} file. When False, no binary output is produced.

Returns:

Error code from the C API (0 on success, non-zero on failure).

Return type:

int

property state: int#

Current engine lifecycle state code.

Returns:

Lifecycle state code.

Return type:

int

@see: openswmm.engine.EngineState for code meanings.

step()#

Advance the simulation by one explicit timestep.

Caller polls state to detect completion: when the simulation is finished the engine transitions from RUNNING to ENDED, so the idiomatic loop is:

from openswmm.engine import EngineState
while solver.state == EngineState.RUNNING:
    rc = solver.step()
    if rc != 0:
        break
Returns:

Error code from the C API (0 on success, non-zero on failure).

Return type:

int

stride(n_steps)#

Advance the simulation by n_steps timesteps in one call.

Updates elapsed as a side effect.

Parameters:

n_steps (int) – Number of timesteps to advance.

Returns:

Error code from the C API (0 on success, non-zero on failure).

Return type:

int

start_datetime: datetime#
end_datetime: datetime#
report_start_datetime: datetime#
run(inp, rpt='', out='', plugin_lib=None)#

Run a SWMM simulation from start to finish in a single call.

Convenience wrapper that performs the full lifecycle (open through destroy) without exposing intermediate state.

Parameters:
  • inp (str) – Path to the SWMM input file (.inp).

  • rpt (str) – Path for the report file (.rpt). Empty string to skip.

  • out (str) – Path for the binary output file (.out). Empty string to skip.

  • plugin_lib (str or None) – Optional path to a plugin shared library.

Returns:

Error code from the C API (0 on success, non-zero on failure).

Return type:

int

run_with_callback(inp, rpt='', out='', callback=None, plugin_lib=None)#

Run a SWMM simulation with a progress callback.

Convenience wrapper around run that periodically invokes C{callback} with the simulation’s elapsed-time fraction. When callback is None, behaves identically to run.

Parameters:
  • inp (str) – Path to the SWMM input file (.inp).

  • rpt (str) – Path for the report file (.rpt). Empty string to skip.

  • out (str) – Path for the binary output file (.out). Empty string to skip.

  • callback (callable or None) – A callable receiving (progress: float) where progress is a fraction in [0, 1]. None disables the callback.

  • plugin_lib (str or None) – Optional path to a plugin shared library.

Returns:

Error code from the C API (0 on success, non-zero on failure).

Return type:

int

Model construction#

Programmatic Model Building#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._model.

The ModelBuilder class creates a SWMM model entirely through the API without requiring a .inp file.

class ModelBuilder#

Bases: object

Build a SWMM model programmatically (no .inp file).

The engine starts in BUILDING state. Use add_node, add_link, etc. to populate the model, then call finalize to transition to INITIALIZED.

Note

The ModelBuilder owns its engine handle until to_solver is called; the resulting Solver then takes ownership.

Example:

m = ModelBuilder()
m.add_node("J1", 0)       # JUNCTION
m.add_node("OUT1", 1)     # OUTFALL
m.add_link("C1", 0)       # CONDUIT
m.set_link_nodes(0, 0, 1)
m.set_link_length(0, 300.0)
m.set_link_roughness(0, 0.013)
m.validate()
m.finalize()
solver = m.to_solver()
add_gage(gage_id)#

Add a rain gage to the model.

Parameters:

gage_id (str) – Unique gage identifier.

Returns:

Error code (0 on success).

Return type:

int

Add a link to the model.

Valid in BUILDING or OPENED state.

Parameters:
  • link_id (str) – Unique link identifier.

  • link_type (int) – Link type code (0=CONDUIT, 1=PUMP, 2=ORIFICE, 3=WEIR, 4=OUTLET).

Returns:

Error code (0 on success).

Return type:

int

@see: L{openswmm.engine.LinkType}

add_node(node_id, node_type)#

Add a node to the model.

Valid in BUILDING or OPENED state.

Parameters:
  • node_id (str) – Unique node identifier.

  • node_type (int) – Node type code (0=JUNCTION, 1=OUTFALL, 2=STORAGE, 3=DIVIDER).

Returns:

Error code (0 on success).

Return type:

int

@see: L{openswmm.engine.NodeType}

add_subcatch(sc_id)#

Backward-compatible alias for add_subcatchment.

Parameters:

sc_id (str) – Unique subcatchment identifier.

Returns:

Error code (0 on success).

Return type:

int

add_subcatchment(sc_id)#

Add a subcatchment to the model.

Parameters:

sc_id (str) – Unique subcatchment identifier.

Returns:

Error code (0 on success).

Return type:

int

add_title_line(line)#

Append a new line to the [TITLE] section.

Raises:

EngineError – On C API failure.

Parameters:

line (str)

Return type:

None

clear_title()#

Remove all lines from the [TITLE] section.

Raises:

EngineError – On C API failure.

Return type:

None

files_get(key)#

Read one [FILES] field by key.

Parameters:

key (str) – Field key (e.g. "RAINFALL_PATH", "HOTSTART_USE_PATH").

Returns:

Field value string.

Return type:

str

files_set(key, value)#

Write one [FILES] field by key.

Parameters:
  • key (str) – Field key.

  • value (str) – New value; "" to clear.

Return type:

None

finalize()#

Finalize the model – build connectivity and allocate arrays.

Transitions to INITIALIZED state.

Returns:

None

Return type:

None

Raises:

EngineError – If finalization fails.

get_crs()#

Return the model’s coordinate reference system string.

Returns:

CRS string (EPSG identifier, PROJ string, or WKT).

Raises:

EngineError – On C API failure.

Return type:

str

get_option(key)#

Return a SWMM option value as a string.

Raises:

EngineError – On unknown key.

Parameters:

key (str)

Return type:

str

get_option_ext(key)#

Return the value of an extension option (unknown to base SWMM).

Raises:

EngineError – On unknown key.

Parameters:

key (str)

Return type:

str

get_title_count()#

Number of lines in the [TITLE] section.

Raises:

EngineError – On C API failure.

Return type:

int

get_title_line(index)#

Return a title line by zero-based index.

Raises:

EngineError – On bad index.

Parameters:

index (int)

Return type:

str

get_userflag_bool(name)#

Return a boolean user flag value.

Raises:

EngineError – On unknown flag.

Parameters:

name (str)

Return type:

bool

get_userflag_int(name)#

Return an integer user flag value.

Raises:

EngineError – On unknown flag.

Parameters:

name (str)

Return type:

int

get_userflag_real(name)#

Return a real-valued user flag.

Raises:

EngineError – On unknown flag.

Parameters:

name (str)

Return type:

float

property handle: int#

Raw engine handle as an integer (for use by ModelEditor).

Returns:

The underlying C engine pointer cast to an integer.

Return type:

int

plugin_get(idx)#

Read one [PLUGINS] row by index.

Parameters:

idx (int) – Plugin index in [0, plugins_count()).

Returns:

Tuple (path, args).

Return type:

tuple[str, str]

plugin_remove(path_or_id)#

Remove the [PLUGINS] row matching path_or_id.

Parameters:

path_or_id (str) – Library path, plugin id, or id:version string.

Return type:

None

plugin_set(path_or_id, args='')#

Add or replace a [PLUGINS] row keyed by path/id.

Parameters:
  • path_or_id (str) – Library path, plugin id, or id:version string.

  • args (str) – Space-separated argument tokens.

Return type:

None

plugins_count()#

Return the number of [PLUGINS] entries on the engine.

Returns:

Plugin count.

Return type:

int

Remove the most recently added link (undo-of-add).

Valid in BUILDING or OPENED state. The link_id must match the current tail; otherwise SWMM_ERR_BADINDEX is returned.

Parameters:

link_id (str) – Expected tail link identifier.

Returns:

Error code (0 on success).

Return type:

int

pop_last_node(node_id)#

Remove the most recently added node (undo-of-add).

Valid in BUILDING or OPENED state. The node_id must match the current tail; otherwise SWMM_ERR_BADINDEX is returned. Returns SWMM_ERR_BADPARAM if any link still references the tail node – pop those links first via pop_last_link.

Parameters:

node_id (str) – Expected tail node identifier.

Returns:

Error code (0 on success).

Return type:

int

Set the length of a conduit link.

Parameters:
  • idx (int) – Link index.

  • length (float) – Conduit length (project length units).

Returns:

None

Return type:

None

Raises:

EngineError – On C API failure.

Set the upstream and downstream nodes for a link.

Parameters:
  • idx (int) – Link index.

  • from_node (int) – Upstream node index.

  • to_node (int) – Downstream node index.

Returns:

None

Return type:

None

Raises:

EngineError – On C API failure.

Set Manning’s roughness coefficient for a conduit.

Parameters:
  • idx (int) – Link index.

  • n (float) – Manning’s n (dimensionless).

Returns:

None

Return type:

None

Raises:

EngineError – On C API failure.

Set the cross-section geometry of a conduit.

Parameters:
  • idx (int) – Link index.

  • shape (int) – Cross-section shape code.

  • g1 (float) – Primary geometry parameter (e.g. diameter for circular).

  • g2 (float) – Secondary geometry parameter.

  • g3 (float) – Tertiary geometry parameter.

  • g4 (float) – Quaternary geometry parameter.

Returns:

None

Return type:

None

Raises:

EngineError – On C API failure.

@see: L{openswmm.engine.XSectShape}

set_node_invert(idx, elev)#

Set the invert elevation of a node.

Parameters:
  • idx (int) – Node index.

  • elev (float) – Invert elevation (project length units).

Returns:

None

Return type:

None

Raises:

EngineError – On C API failure.

set_node_max_depth(idx, depth)#

Set the maximum depth of a node.

Parameters:
  • idx (int) – Node index.

  • depth (float) – Maximum depth (project length units).

Returns:

None

Return type:

None

Raises:

EngineError – On C API failure.

set_option(key, value)#

Set a SWMM option.

Raises:

EngineError – On unknown key or invalid value.

Parameters:
Return type:

None

set_option_ext(key, value)#

Set the value of an extension option.

Raises:

EngineError – On C API failure.

Parameters:
Return type:

None

set_title(text)#

Replace all title lines with new text. Newlines split lines.

Raises:

EngineError – On C API failure.

Parameters:

text (str)

Return type:

None

set_userflag_bool(name, value)#

Set a boolean user flag.

Raises:

EngineError – On C API failure.

Parameters:
Return type:

None

set_userflag_int(name, value)#

Set an integer user flag.

Raises:

EngineError – On C API failure.

Parameters:
Return type:

None

set_userflag_real(name, value)#

Set a real-valued user flag.

Raises:

EngineError – On C API failure.

Parameters:
Return type:

None

to_solver()#

Transfer ownership of the engine handle to a Solver.

After this call, the ModelBuilder is invalidated and must not be used. The returned Solver owns the engine handle.

Returns:

A new Solver wrapping this model’s engine.

Return type:

L{Solver}

validate()#

Validate model topology.

Checks for orphaned links and ensures at least one outfall is present. Does not change state. Safe to call multiple times.

Returns:

None

Return type:

None

Raises:

EngineError – If topology validation fails.

write(path)#

Write the model to a SWMM .inp file.

Parameters:

path (str) – Output file path.

Returns:

None

Return type:

None

Raises:

EngineError – On C API failure.

write_with_plugin(path, output_plugin_id='')#

Write the current model to disk using an output plugin.

Parameters:
  • path (str) – Destination file path.

  • output_plugin_id (str) – Plugin id, or "" for the built-in writer.

Return type:

None

start_datetime: datetime#
end_datetime: datetime#
report_start_datetime: datetime#

Model editing (deletion + type conversion)#

Model Editing — Object Deletion and Type Conversion#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._edit.

class ConversionResult(new_type, cleared_fields, warnings)#

Bases: object

Result of an in-place node or link type conversion.

Variables:
  • new_type – The new C-API type enum value.

  • cleared_fields – List of field names cleared during conversion.

  • warnings – Non-fatal topology warnings.

Parameters:
  • new_type (int) – The new C-API type enum value.

  • cleared_fields (list[str]) – List of field names that were cleared (reset to defaults) during the conversion.

  • warnings (list[str]) – Non-fatal topology warnings (e.g. “model has no outfall after this conversion”). Conversion still proceeds even when warnings are present.

new_type: int#
cleared_fields: list[str]#
warnings: list[str]#
class ImpactEntry(obj_type, obj_idx, field, cascaded)#

Bases: object

One cross-reference that would be affected by a deletion.

Variables:
  • obj_type – Integer code for the referencing object type (0=node, 1=link, 2=subcatchment, 3=gage, 4=table, 5=transect, 6=inlet_usage).

  • obj_type_name – Human-readable name for obj_type.

  • obj_idx – Zero-based index of the referencing object.

  • field – Name of the specific cross-reference field (e.g. "node1", "outlet_node").

  • cascadedTrue if the referencing object will be deleted; False if only the reference will be nullified.

Parameters:
  • obj_type (int) – Integer code for the referencing object type.

  • obj_idx (int) – Zero-based index of the referencing object.

  • field (str) – Name of the specific cross-reference field.

  • cascaded (bool) – True for cascade-delete, False for nullify.

obj_type: int#
obj_type_name: str#
obj_idx: int#
field: str#
cascaded: bool#
class ModelEditor(engine)#

Bases: object

Edit an existing SWMM model – delete objects and convert types.

Accepts any object that exposes a handle property returning the raw engine pointer as an integer. Both ModelBuilder (BUILDING state) and Solver (OPENED state) satisfy this contract.

Parameters:

engine (object) – A ModelBuilder or Solver instance.

Example:

from openswmm.engine import ModelBuilder, ModelEditor, NodeType, LinkType

m = ModelBuilder()
m.add_node("J1", NodeType.JUNCTION)
m.add_node("J2", NodeType.JUNCTION)
m.add_node("OUT1", NodeType.OUTFALL)
m.add_link("C1", LinkType.CONDUIT)
m.add_link("C2", LinkType.CONDUIT)
m.set_link_nodes(0, 0, 1)
m.set_link_nodes(1, 1, 2)

ed = ModelEditor(m)

# Non-destructive preview
impacts = ed.analyze_node_impact("J1")

# Delete J1 -- C1 cascade-deleted automatically
cascade = ed.delete_node("J1")

# Convert C2 conduit -> weir
result = ed.convert_link("C2", LinkType.WEIR)
analyze_gage_impact(id_or_idx)#

Preview which objects reference a rain gage.

Parameters:

id_or_idx (int or str) – Gage name or zero-based index.

Returns:

List of ImpactEntry describing what would be affected.

Return type:

list[ImpactEntry]

Raises:
  • KeyError – If id_or_idx is a name and the gage is not found.

  • EngineError – On C API failure.

Preview which objects reference a link, without deleting it.

Parameters:

id_or_idx (int or str) – Link name or zero-based index.

Returns:

List of ImpactEntry describing what would be affected.

Return type:

list[ImpactEntry]

Raises:
  • KeyError – If id_or_idx is a name and the link is not found.

  • EngineError – On C API failure.

analyze_node_impact(id_or_idx)#

Preview which objects reference a node, without deleting it.

Parameters:

id_or_idx (int or str) – Node name or zero-based index.

Returns:

List of ImpactEntry describing what would be affected.

Return type:

list[ImpactEntry]

Raises:
  • KeyError – If id_or_idx is a name and the node is not found.

  • EngineError – On C API failure.

analyze_subcatch_impact(id_or_idx)#

Preview which objects reference a subcatchment.

Parameters:

id_or_idx (int or str) – Subcatchment name or zero-based index.

Returns:

List of ImpactEntry describing what would be affected.

Return type:

list[ImpactEntry]

Raises:
  • KeyError – If id_or_idx is a name and the subcatchment is not found.

  • EngineError – On C API failure.

analyze_table_impact(id_or_idx)#

Preview which objects reference a time series or curve.

Parameters:

id_or_idx (int or str) – Table name or zero-based index.

Returns:

List of ImpactEntry describing what would be affected.

Return type:

list[ImpactEntry]

Raises:
  • KeyError – If id_or_idx is a name and the table is not found.

  • EngineError – On C API failure.

analyze_transect_impact(idx)#

Preview which links reference a transect.

Parameters:

idx (int) – Zero-based transect index.

Returns:

List of ImpactEntry describing what would be affected.

Return type:

list[ImpactEntry]

Raises:

EngineError – On C API failure.

Convert a link to a different type in place.

Parameters:
  • id_or_idx (int or str) – Link name or zero-based index.

  • new_type (int) – Target link type code.

Returns:

ConversionResult with cleared fields and warnings.

Return type:

L{ConversionResult}

Raises:
  • RuntimeError – If not in BUILDING or OPENED state, the type is invalid, or new_type equals the current type.

  • KeyError – If id_or_idx is a name and the link is not found.

  • EngineError – On C API failure.

@see: L{openswmm.engine.LinkType}

convert_node(id_or_idx, new_type)#

Convert a node to a different type in place.

Parameters:
  • id_or_idx (int or str) – Node name or zero-based index.

  • new_type (int) – Target node type code.

Returns:

ConversionResult with cleared fields and warnings.

Return type:

L{ConversionResult}

Raises:
  • RuntimeError – If not in BUILDING or OPENED state, the type is invalid, or new_type equals the current type.

  • KeyError – If id_or_idx is a name and the node is not found.

  • EngineError – On C API failure.

@see: L{openswmm.engine.NodeType}

delete_gage(id_or_idx)#

Delete a rain gage and nullify subcatchment gage references.

Parameters:

id_or_idx (int or str) – Gage name or zero-based index.

Returns:

List of ImpactEntry describing what was affected.

Return type:

list[ImpactEntry]

Raises:

Delete a link and cascade-delete or nullify referencing objects.

Parameters:

id_or_idx (int or str) – Link name or zero-based index.

Returns:

List of ImpactEntry describing what was affected.

Return type:

list[ImpactEntry]

Raises:
delete_node(id_or_idx)#

Delete a node and cascade-delete or nullify all referencing objects.

Parameters:

id_or_idx (int or str) – Node name or zero-based index.

Returns:

List of ImpactEntry describing what was affected.

Return type:

list[ImpactEntry]

Raises:
delete_subcatch(id_or_idx)#

Delete a subcatchment and nullify referencing objects.

Parameters:

id_or_idx (int or str) – Subcatchment name or zero-based index.

Returns:

List of ImpactEntry describing what was affected.

Return type:

list[ImpactEntry]

Raises:
  • RuntimeError – If not in BUILDING or OPENED state.

  • KeyError – If id_or_idx is a name and the subcatchment is not found.

  • EngineError – On C API failure.

delete_table(id_or_idx)#

Delete a time series or curve and nullify all referencing objects.

Parameters:

id_or_idx (int or str) – Table name or zero-based index.

Returns:

List of ImpactEntry describing what was affected.

Return type:

list[ImpactEntry]

Raises:
delete_transect(idx)#

Delete a transect and reset referencing conduit cross-sections.

Parameters:

idx (int) – Zero-based transect index.

Returns:

List of ImpactEntry describing what was affected.

Return type:

list[ImpactEntry]

Raises:
property gage_count: int#

Current number of rain gages in the model.

Returns:

Gage count.

Return type:

int

Current number of links in the model.

Returns:

Link count.

Return type:

int

property node_count: int#

Current number of nodes in the model.

Returns:

Node count.

Return type:

int

property subcatch_count: int#

Current number of subcatchments in the model.

Returns:

Subcatchment count.

Return type:

int

property table_count: int#

Current number of tables (time series + curves) in the model.

Returns:

Table count.

Return type:

int

start_datetime: datetime#
end_datetime: datetime#
report_start_datetime: datetime#

Nodes#

Node Access#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._nodes.

The Nodes class provides access to node properties during a simulation.

class Nodes(solver)#

Bases: object

Access node properties during a simulation.

All per-element methods accept either an integer index or a string node ID. When a string is passed it is resolved via get_index.

Parameters:

solver (L{Solver}) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Example:

from openswmm.engine import Solver, Nodes

with Solver("model.inp", "model.rpt", "model.out") as s:
    nodes = Nodes(s)
    depth = nodes.get_depth(0)      # by index
    depth = nodes.get_depth("J1")   # by name
add(node_id, node_type)#

Add a node to the model (OPENED-state editing).

Wraps swmm_node_add. Valid in BUILDING or OPENED state.

Parameters:
  • node_id (str) – Unique node identifier.

  • node_type (int) – Node type code (see NodeType).

Returns:

Error code (0 on success).

Return type:

int

count()#

Return the number of nodes in the model.

Returns:

Node count.

Return type:

int

get_crown_elev(idx)#

Return the crown elevation of a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Crown elevation (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_degree(idx)#

Return the number of links connected to a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Node degree (number of connected links).

Return type:

int

Raises:

KeyError – If idx is a string and the node ID is not found.

get_depth(idx)#

Return the current water depth at a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str). Strings are resolved via get_index.

Returns:

Water depth in project length units (feet for US, metres for SI).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_depth_from_volume(idx, volume)#

Compute depth from volume (inverse of volume-depth relationship).

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • volume (float) – Volume (project volume units).

Returns:

Depth (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_depths_bulk()#

Return all node depths as a NumPy array.

Uses the bulk C API for a single memcpy – much faster than calling get_depth in a loop.

Returns:

Array of shape (n_nodes,) with dtype float64.

Return type:

numpy.typing.NDArray[numpy.float64]

get_divider_type(idx)#

Return the divider type for a divider node.

Parameters:

idx (int | str) – Node index (int) or node ID (str).

Returns:

Divider type code.

Return type:

int

get_exfil_params(idx)#

Return exfiltration parameters for a storage node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Tuple of (suction, ksat, imd).

Return type:

Tuple[float, float, float]

Raises:

KeyError – If idx is a string and the node ID is not found.

get_full_volume(idx)#

Return the full volume of a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Full volume (project volume units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_head(idx)#

Return the hydraulic head at a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Hydraulic head (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_heads_bulk()#

Return all node heads as a NumPy array.

Returns:

Array of shape (n_nodes,) with dtype float64.

Return type:

numpy.typing.NDArray[numpy.float64]

get_id(idx)#

Return the string ID of a node by index.

Parameters:

idx (int) – Node index.

Returns:

Node ID string.

Return type:

str

get_index(node_id)#

Return the integer index of a node by its string ID.

Parameters:

node_id (str) – Node identifier string.

Returns:

Node index, or -1 if not found.

Return type:

int

get_inflow(idx)#

Return the total inflow at a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Total inflow (project flow units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_inflows_bulk()#

Return all node total inflows as a NumPy array.

Returns:

Array of shape (n_nodes,) with dtype float64.

Return type:

numpy.typing.NDArray[numpy.float64]

get_initial_depth(idx)#

Return the initial depth of a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Initial depth (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_invert_elev(idx)#

Return the invert elevation of a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Invert elevation (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_lateral_inflow(idx)#

Return the lateral inflow at a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Lateral inflow (project flow units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_losses(idx)#

Return the losses at a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Losses (project flow units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_max_depth(idx)#

Return the maximum depth of a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Maximum depth (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_outfall_flap_gate(idx)#

Return whether an outfall node has a flap gate.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

True if the outfall has a flap gate.

Return type:

bool

Raises:

KeyError – If idx is a string and the node ID is not found.

get_outfall_param(idx)#

Return the outfall parameter value for an outfall node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Outfall parameter value.

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_outfall_route_to(idx)#

Get the subcatchment index outfall discharge is routed to.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Subcatchment index (-1 = no routing).

Return type:

int

Raises:

KeyError – If idx is a string and the node ID is not found.

get_outfall_type(idx)#

Return the outfall type code for an outfall node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Outfall type code.

Return type:

int

Raises:

KeyError – If idx is a string and the node ID is not found.

get_outflow(idx)#

Return the outflow from a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Outflow (project flow units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_overflow(idx)#

Return the overflow rate at a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Overflow rate (project flow units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_overflows_bulk()#

Return all node overflow rates as a NumPy array.

Returns:

Array of shape (n_nodes,) with dtype float64.

Return type:

numpy.typing.NDArray[numpy.float64]

get_ponded_area(idx)#

Return the ponded area of a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Ponded area (project area units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_quality(idx, pollutant_idx)#

Return the concentration of a pollutant at a node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • pollutant_idx (int) – Pollutant index.

Returns:

Pollutant concentration.

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_quality_bulk(pollutant_idx)#

Return all node concentrations for a pollutant as a NumPy array.

Parameters:

pollutant_idx (int) – Pollutant index.

Returns:

Array of shape (n_nodes,) with dtype float64.

Return type:

numpy.typing.NDArray[numpy.float64]

get_stat_max_depth(idx)#

Return the maximum depth recorded at a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Maximum depth (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_stat_max_overflow(idx)#

Return the maximum overflow rate recorded at a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Maximum overflow rate (project flow units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_stat_time_flooded(idx)#

Return the total time a node was flooded.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Time flooded (hours).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_stat_vol_flooded(idx)#

Return the total volume flooded at a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Volume flooded (project volume units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_storage_curve(idx)#

Return the storage curve index for a storage node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Curve index.

Return type:

int

Raises:

KeyError – If idx is a string and the node ID is not found.

get_storage_functional(idx)#

Return the functional storage parameters (A, B, C) for a storage node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Tuple of (a, b, c) coefficients.

Return type:

Tuple[float, float, float]

Raises:

KeyError – If idx is a string and the node ID is not found.

get_storage_seep_rate(idx)#

Return the seepage rate for a storage node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Seepage rate.

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_surcharge_depth(idx)#

Return the surcharge depth of a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Surcharge depth (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

get_type(idx)#

Return the node type code.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Node type code.

Return type:

int

Raises:

KeyError – If idx is a string and the node ID is not found.

get_volume(idx)#

Return the volume stored at a node.

Parameters:

idx (Union[int, str]) – Node index (int) or node ID (str).

Returns:

Volume (project volume units).

Return type:

float

Raises:

KeyError – If idx is a string and the node ID is not found.

pop_last(node_id)#

Remove the most recently added node (undo-of-add).

Wraps swmm_node_pop_last. Valid in BUILDING or C{OPENED} state. node_id must match the current tail; otherwise SWMM_ERR_BADINDEX is returned.

Parameters:

node_id (str) – Expected tail node identifier.

Returns:

Error code (0 on success).

Return type:

int

rename(idx, new_id)#

Rename a node.

Parameters:
  • idx (int | str) – Node index (int) or current node ID (str).

  • new_id (str) – New identifier string.

Return type:

None

set_depth(idx, value)#

Set the water depth at a node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • value (float) – New depth (project length units).

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_depths_bulk(values)#

Set all node depths from a NumPy array.

Parameters:

values (numpy.typing.NDArray[numpy.float64]) – Array of shape (n_nodes,) with dtype float64.

Return type:

None

set_divider_type(idx, type)#

Set the divider type for a divider node.

Parameters:
  • idx (int | str) – Node index (int) or node ID (str).

  • type (int) – Divider type code.

Return type:

None

set_exfil_params(idx, suction, ksat, imd)#

Set exfiltration parameters for a storage node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • suction (float) – Suction head.

  • ksat (float) – Saturated hydraulic conductivity.

  • imd (float) – Initial moisture deficit.

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_head_boundary(idx, head)#

Set a fixed head boundary condition at a node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • head (float) – Boundary head value (project length units).

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_initial_depth(idx, depth)#

Set the initial depth of a node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • depth (float) – Initial depth (project length units).

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_invert_elev(idx, elev)#

Set the invert elevation of a node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • elev (float) – Invert elevation (project length units).

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_lat_inflows_bulk(values)#

Set all node lateral inflows from a NumPy array.

Parameters:

values (numpy.typing.NDArray[numpy.float64]) – Array of shape (n_nodes,) with dtype float64.

Return type:

None

set_lateral_inflow(idx, flow)#

Prescribe a lateral inflow at a node (RUNNING state only).

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • flow (float) – Lateral inflow rate (project flow units).

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_max_depth(idx, depth)#

Set the maximum depth of a node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • depth (float) – Maximum depth (project length units).

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_outfall_flap_gate(idx, has_gate)#

Set whether an outfall node has a flap gate.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • has_gate (bool) – True if the outfall has a flap gate.

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_outfall_route_to(idx, subcatch_idx)#

Set the subcatchment to route outfall discharge to.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • subcatch_idx (int) – Subcatchment index (-1 = no routing).

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_outfall_stage(idx, stage)#

Set a fixed stage for an outfall node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • stage (float) – Fixed stage value (project length units).

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_outfall_tidal(idx, curve_idx)#

Assign a tidal curve to an outfall node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • curve_idx (int) – Tidal curve index.

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_outfall_timeseries(idx, ts_idx)#

Assign a time series to an outfall node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • ts_idx (int) – Time series index.

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_outfall_type(idx, type)#

Set the outfall type for an outfall node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • type (int) – Outfall type code.

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_pond_area(idx, area)#

Set the ponded area of a node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • area (float) – Ponded area (project area units).

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_quality_mass_flux(idx, pollutant_idx, mass_rate)#

Inject a pollutant mass flux at a node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • pollutant_idx (int) – Pollutant index.

  • mass_rate (float) – Mass injection rate (mass/time in model units).

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_storage_curve(idx, curve_idx)#

Assign a storage curve to a storage node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • curve_idx (int) – Curve index.

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_storage_functional(idx, a, b, c)#

Set the functional storage parameters (A, B, C) for a storage node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • a (float) – Coefficient A.

  • b (float) – Coefficient B.

  • c (float) – Coefficient C.

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_storage_seep_rate(idx, rate)#

Set the seepage rate for a storage node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • rate (float) – Seepage rate.

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

set_surcharge_depth(idx, depth)#

Set the surcharge depth of a node.

Parameters:
  • idx (Union[int, str]) – Node index (int) or node ID (str).

  • depth (float) – Surcharge depth (project length units).

Raises:

KeyError – If idx is a string and the node ID is not found.

Return type:

None

Subcatchments#

Subcatchment Access#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._subcatchments.

The Subcatchments class provides access to subcatchment properties during a simulation.

class Subcatchments(solver)#

Bases: object

Access subcatchment properties during a simulation.

All per-element methods accept either an integer index or a string subcatchment ID. When a string is passed it is resolved via get_index.

Parameters:

solver (L{Solver}) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Example:

from openswmm.engine import Solver, Subcatchments

with Solver("model.inp", "model.rpt", "model.out") as s:
    sc = Subcatchments(s)
    runoff = sc.get_runoff(0)      # by index
    runoff = sc.get_runoff("S1")   # by name
add(sc_id)#

Add a subcatchment to the model (OPENED-state editing).

Wraps swmm_subcatch_add. Valid in BUILDING or OPENED state.

Parameters:

sc_id (str) – Unique subcatchment identifier.

Returns:

Error code (0 on success).

Return type:

int

count()#

Return the number of subcatchments in the model.

Returns:

Subcatchment count.

Return type:

int

delete(idx)#

Delete a subcatchment and cascade-nullify all referencing objects.

Valid in BUILDING or OPENED state.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

List of ImpactEntry describing cascaded changes.

Return type:

list

Raises:
  • KeyError – If idx is a string and the subcatchment is not found.

  • RuntimeError – On engine error.

get_area(idx)#

Return the area of a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Subcatchment area (project area units).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_coverage(idx, lu_idx)#

Return the land-use coverage fraction for a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • lu_idx (int) – Land-use index.

Returns:

Coverage fraction (0-1).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_ds_imperv(idx)#

Return the depression storage for the impervious area.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Depression storage depth (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_ds_perv(idx)#

Return the depression storage for the pervious area.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Depression storage depth (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_evap(idx)#

Return the current evaporation rate from a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Evaporation rate (project length units per time).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_gage(idx)#

Return the rain gage index assigned to a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Rain gage index.

Return type:

int

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_groundwater(idx)#

Return the groundwater outflow from a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Groundwater flow rate (project flow units).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_id(idx)#

Return the string ID of a subcatchment by index.

Parameters:

idx (int) – Subcatchment index.

Returns:

Subcatchment ID string.

Return type:

str

get_imperv_pct(idx)#

Return the percent imperviousness of a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Percent imperviousness (0-100).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_index(sc_id)#

Return the integer index of a subcatchment by its string ID.

Parameters:

sc_id (str) – Subcatchment identifier.

Returns:

Index, or -1 if not found.

Return type:

int

get_infil(idx)#

Return the current infiltration rate on a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Infiltration rate (project length units per time).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_infil_curve_number(idx)#

Return the SCS Curve Number for a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

SCS curve number.

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_infil_green_ampt(idx)#

Return Green-Ampt infiltration parameters for a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Tuple of (suction, conductivity, deficit).

Return type:

Tuple[float, float, float]

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_infil_horton(idx)#

Return Horton infiltration parameters for a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Tuple of (f0, fmin, decay, dry_time).

Return type:

Tuple[float, float, float, float]

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_infil_model(idx)#

Return the infiltration model type for a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Infiltration model type code.

Return type:

int

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_n_imperv(idx)#

Return Manning’s N for the impervious area.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Manning’s roughness coefficient.

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_n_perv(idx)#

Return Manning’s N for the pervious area.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Manning’s roughness coefficient.

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_outlet(idx)#

Return the outlet node index for a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Outlet node index.

Return type:

int

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_outlet_subcatch(idx)#

Return the outlet subcatchment index for a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Outlet subcatchment index.

Return type:

int

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_ponded_quality(idx, pollutant_idx)#

Return ponded quality mass for a subcatchment-pollutant pair.

Ponded quality persists between wet/dry events and represents pollutant mass in standing water on the subcatchment surface.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or ID (str).

  • pollutant_idx (int) – Pollutant index.

Returns:

Ponded quality mass (project mass units).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_quality(idx, pollutant_idx)#

Return the pollutant concentration in subcatchment runoff.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • pollutant_idx (int) – Pollutant index.

Returns:

Concentration (project quality units).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_quality_bulk(pollutant_idx)#

Return all subcatchment pollutant concentrations as a NumPy array.

Parameters:

pollutant_idx (int) – Pollutant index.

Returns:

Array of shape (n_subcatchments,) with dtype float64.

Return type:

numpy.typing.NDArray[numpy.float64]

get_rainfall(idx)#

Return the current rainfall rate on a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Rainfall rate (project rainfall units).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_runoff(idx)#

Return the current runoff rate from a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Runoff rate (project flow units).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_runoff_bulk()#

Return all subcatchment runoff rates as a NumPy array.

Uses the bulk C API for a single memcpy – much faster than calling get_runoff in a loop.

Returns:

Array of shape (n_subcatchments,) with dtype float64.

Return type:

numpy.typing.NDArray[numpy.float64]

get_slope(idx)#

Return the average surface slope of a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Average slope (fraction).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_snow_depth(idx)#

Return the current snow depth on a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Snow depth (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_stat_max_runoff(idx)#

Return the maximum runoff rate for a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Maximum runoff rate.

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_stat_precip(idx)#

Return the total precipitation volume for a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Precipitation volume.

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_stat_runoff_vol(idx)#

Return the total runoff volume for a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Runoff volume.

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

get_width(idx)#

Return the characteristic width of a subcatchment.

Parameters:

idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

Returns:

Overland flow width (project length units).

Return type:

float

Raises:

KeyError – If idx is a string and the subcatchment is not found.

rename(idx, new_id)#

Rename a subcatchment.

Parameters:
  • idx (int | str) – Subcatchment index (int) or current subcatchment ID (str).

  • new_id (str) – New identifier string.

Return type:

None

set_area(idx, area)#

Set the area of a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • area (float) – Subcatchment area (project area units).

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_coverage(idx, lu_idx, fraction)#

Set the land-use coverage fraction for a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • lu_idx (int) – Land-use index.

  • fraction (float) – Coverage fraction (0-1).

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_ds_imperv(idx, ds)#

Set the depression storage for the impervious area.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • ds (float) – Depression storage depth (project length units).

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_ds_perv(idx, ds)#

Set the depression storage for the pervious area.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • ds (float) – Depression storage depth (project length units).

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_gage(idx, gage_idx)#

Set the rain gage assigned to a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • gage_idx (int) – Index of the rain gage.

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_imperv_pct(idx, pct)#

Set the percent imperviousness of a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • pct (float) – Percent imperviousness (0-100).

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_infil_curve_number(idx, cn)#

Set SCS Curve Number infiltration parameter for a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • cn (float) – SCS curve number.

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_infil_green_ampt(idx, suction, conductivity, initial_deficit)#

Set Green-Ampt infiltration parameters for a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • suction (float) – Soil capillary suction.

  • conductivity (float) – Soil saturated hydraulic conductivity.

  • initial_deficit (float) – Initial moisture deficit.

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_infil_horton(idx, f0, fmin, decay, dry_time)#

Set Horton infiltration parameters for a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • f0 (float) – Maximum infiltration rate.

  • fmin (float) – Minimum infiltration rate.

  • decay (float) – Decay constant.

  • dry_time (float) – Drying time.

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_n_imperv(idx, n)#

Set Manning’s N for the impervious area.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • n (float) – Manning’s roughness coefficient.

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_n_perv(idx, n)#

Set Manning’s N for the pervious area.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • n (float) – Manning’s roughness coefficient.

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_outlet(idx, node_idx)#

Set the outlet node for a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • node_idx (int) – Index of the outlet node.

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_outlet_subcatch(idx, sc_idx)#

Set the outlet subcatchment for a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • sc_idx (int) – Index of the outlet subcatchment.

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_ponded_quality(idx, pollutant_idx, mass)#

Set ponded quality mass for a subcatchment-pollutant pair.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or ID (str).

  • pollutant_idx (int) – Pollutant index.

  • mass (float) – Ponded quality mass (project mass units).

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_rainfall(idx, rainfall)#

Override rainfall on a subcatchment for the current timestep.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • rainfall (float) – Rainfall rate (project rainfall units). Negative value reverts to gage-driven.

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_slope(idx, slope)#

Set the average surface slope of a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • slope (float) – Average slope (fraction).

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

set_width(idx, width)#

Set the characteristic width of a subcatchment.

Parameters:
  • idx (Union[int, str]) – Subcatchment index (int) or subcatchment ID (str).

  • width (float) – Overland flow width (project length units).

Raises:

KeyError – If idx is a string and the subcatchment is not found.

Return type:

None

Rain gages#

Rain Gage Access#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._gages.

The Gages class provides access to rain gage rainfall during a simulation.

class Gages(solver)#

Bases: object

Access and override rain gage rainfall during a simulation.

All per-element methods accept either an integer index or a string gage ID. When a string is passed it is resolved via get_index.

Parameters:

solver (L{Solver}) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Example:

from openswmm.engine import Solver, Gages

with Solver("model.inp", "model.rpt", "model.out") as s:
    gages = Gages(s)
    rain = gages.get_rainfall(0)           # by index
    rain = gages.get_rainfall("RainGage")  # by name
add(gage_id)#

Add a rain gage to the model (OPENED-state editing).

Wraps swmm_gage_add. Valid in BUILDING or OPENED state.

Parameters:

gage_id (str) – Unique gage identifier.

Returns:

Error code (0 on success).

Return type:

int

count()#

Return the number of rain gages in the model.

Returns:

Gage count.

Return type:

int

delete(idx)#

Delete a rain gage and cascade-nullify all referencing objects.

Valid in BUILDING or OPENED state.

Parameters:

idx (Union[int, str]) – Gage index (int) or gage ID (str).

Returns:

List of ImpactEntry describing cascaded changes.

Return type:

list

Raises:
get_data_source(idx)#

Return the data source code for a gage.

Parameters:

idx (Union[int, str]) – Gage index (int) or gage ID (str).

Returns:

Data source code.

Return type:

int

Raises:

KeyError – If idx is a string and the gage ID is not found.

get_id(idx)#

Return the string ID of a rain gage by index.

Parameters:

idx (int) – Gage index.

Returns:

Gage identifier, or empty string if not found.

Return type:

str

get_index(gage_id)#

Return the integer index of a rain gage by its string ID.

Parameters:

gage_id (str) – Gage identifier.

Returns:

Gage index, or -1 if not found.

Return type:

int

get_rain_type(idx)#

Return the rain type code for a gage.

Parameters:

idx (Union[int, str]) – Gage index (int) or gage ID (str).

Returns:

Rain type code.

Return type:

int

Raises:

KeyError – If idx is a string and the gage ID is not found.

get_rainfall(idx)#

Return the current rainfall rate at a gage.

Parameters:

idx (Union[int, str]) – Gage index (int) or gage ID (str). Strings are resolved via get_index.

Returns:

Rainfall rate (project rainfall units).

Return type:

float

Raises:

KeyError – If idx is a string and the gage ID is not found.

get_rainfall_bulk()#

Return rainfall for all gages as a NumPy array.

Returns:

1-D array of rainfall values, one per gage. Shape (n_gages,), dtype float64.

Return type:

numpy.typing.NDArray[numpy.float64]

rename(idx, new_id)#

Rename a rain gage.

Parameters:
  • idx (int | str) – Gage index (int) or current gage ID (str).

  • new_id (str) – New identifier string.

Return type:

None

set_data_source(idx, source)#

Set the data source type for a gage.

Parameters:
  • idx (Union[int, str]) – Gage index (int) or gage ID (str).

  • source (int) – Data source code.

Raises:

KeyError – If idx is a string and the gage ID is not found.

Return type:

None

set_filename(idx, path, station_id)#

Set the external rainfall file and station for a gage.

Parameters:
  • idx (Union[int, str]) – Gage index (int) or gage ID (str).

  • path (str) – Path to the rainfall data file.

  • station_id (str) – Station identifier within the file.

Raises:

KeyError – If idx is a string and the gage ID is not found.

Return type:

None

set_rain_interval(idx, seconds)#

Set the rain recording interval for a gage.

Parameters:
  • idx (Union[int, str]) – Gage index (int) or gage ID (str).

  • seconds (float) – Recording interval in seconds.

Raises:

KeyError – If idx is a string and the gage ID is not found.

Return type:

None

set_rain_type(idx, type)#

Set the rain type for a gage.

Parameters:
  • idx (Union[int, str]) – Gage index (int) or gage ID (str).

  • type (int) – Rain type code.

Raises:

KeyError – If idx is a string and the gage ID is not found.

Return type:

None

set_rainfall(idx, rainfall)#

Override rainfall at a gage for the current timestep.

Affects all subcatchments that use this gage. Applied for one timestep only – call again each step to sustain.

Parameters:
  • idx (Union[int, str]) – Gage index (int) or gage ID (str).

  • rainfall (float) – Rainfall rate (project rainfall units).

Raises:

KeyError – If idx is a string and the gage ID is not found.

Return type:

None

set_timeseries(idx, ts_id)#

Set the timeseries data source for a gage.

Parameters:
  • idx (Union[int, str]) – Gage index (int) or gage ID (str).

  • ts_id (str) – Timeseries identifier.

Raises:

KeyError – If idx is a string and the gage ID is not found.

Return type:

None

External inflows (DWF, RDII, time-series)#

Inflow Access#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._inflows.

The Inflows class provides methods for adding external inflows, dry-weather flows, and RDII to model nodes.

class HydrographEntry#

Bases: TypedDict

Parameters of a single [HYDROGRAPHS] parameter row.

uh_name: str#
month: int#
response: int#
r: float#
t: float#
k: float#
dmax: float#
drecov: float#
dinit: float#
class Inflows(solver)#

Bases: object

Add external inflows, dry-weather flows, and RDII to the model.

Variables:

_solver – The owning solver instance whose engine handle is used for every C call.

Parameters:

solver (Solver)

Example:

from openswmm.engine import Solver, Inflows

with Solver("model.inp", "model.rpt", "model.out") as s:
    inflows = Inflows(s)
    inflows.add_external(0, "FLOW", ts_name="InflowTS")
    inflows.add_dwf(0, "FLOW", 1.5)
Parameters:

solver (L{Solver}) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Construct an Inflows accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent inflow operations.

__init__(solver)#

Construct an Inflows accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent inflow operations.

Return type:

None

add_dwf(node_idx, constituent, avg_value, pat1='', pat2='', pat3='', pat4='')#

Add a dry-weather flow to a node.

Parameters:
  • node_idx (int) – Node index.

  • constituent (str) – Constituent name (e.g. "FLOW").

  • avg_value (float) – Average DWF value.

  • pat1 (str) – Monthly pattern name; empty string if none.

  • pat2 (str) – Daily pattern name; empty string if none.

  • pat3 (str) – Hourly pattern name; empty string if none.

  • pat4 (str) – Weekend pattern name; empty string if none.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_dwf_add call returns a non-zero error code.

add_external(node_idx, constituent, ts_name='', type='FLOW', m_factor=1.0, s_factor=1.0, baseline=0.0, pattern='')#

Add an external inflow to a node.

Parameters:
  • node_idx (int) – Node index.

  • constituent (str) – Constituent name (e.g. "FLOW" or a pollutant ID).

  • ts_name (str) – Time-series name; empty string if none.

  • type (str) – Inflow type string (default "FLOW").

  • m_factor (float) – Multiplier factor (default 1.0).

  • s_factor (float) – Scale factor (default 1.0).

  • baseline (float) – Baseline value (default 0.0).

  • pattern (str) – Pattern name; empty string if none.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_ext_inflow_add call returns a non-zero error code.

add_hydrograph(uh_name, month, response, r, t, k, dmax=0.0, drecov=0.0, dinit=0.0)#

Add a unit hydrograph parameter line.

Parameters:
  • uh_name (str) – Unit hydrograph group name.

  • month (int) – -1 = ALL, or 0..11 = JAN..DEC.

  • response (int) – 0 = SHORT, 1 = MEDIUM, 2 = LONG.

  • r (float) – Fraction of rainfall that becomes RDII.

  • t (float) – Time to peak in hours.

  • k (float) – Ratio of base time to peak time (>= 1).

  • dmax (float) – Maximum initial-abstraction depth.

  • drecov (float) – Linear-model IA recovery rate. Ignored when an exponential decay row exists for this (uh_name, response) pair.

  • dinit (float) – Initial IA already used.

Return type:

None

add_hydrograph_gage(uh_name, gage_name)#

Assign a rain gage to a unit hydrograph group.

Parameters:
  • uh_name (str)

  • gage_name (str)

Return type:

None

add_rdii(node_idx, uh_name, area)#

Add an RDII inflow to a node.

Parameters:
  • node_idx (int) – Node index.

  • uh_name (str) – Unit hydrograph name.

  • area (float) – Sewershed area contributing RDII.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_rdii_add call returns a non-zero error code.

add_rdii_decay(uh_name, response, k_dep, k_0, k_T, T_ref=10.0, theta_rec=0.0, T_freeze=0.0)#

Add an exponential-decay row for a (uh_name, response) pair.

Physically-based replacement for the legacy linear IA recovery. Depletion during storms follows S{exp}(-k_dep * rainfall); recovery during dry periods uses an additive base+thermal rate k_rec(T) = k_0 + k_T * exp(theta_rec * (T - T_ref)) with suppression when T <= T_freeze.

Parameters:
  • uh_name (str) – UH group name (must match a hydrograph entry).

  • response (int) – 0 = SHORT, 1 = MEDIUM, 2 = LONG.

  • k_dep (float) – Depletion rate (1/project-depth-unit).

  • k_0 (float) – Base recovery rate (1/hr).

  • k_T (float) – Thermal recovery rate at T_ref (1/hr).

  • T_ref (float) – Reference temperature (deg C). Default 10.

  • theta_rec (float) – Temperature sensitivity (1/deg C).

  • T_freeze (float) – Frozen-ground threshold (deg C). Default 0.

Return type:

None

dwf_count()#

Return the number of dry-weather flows in the model.

Returns:

DWF count.

Return type:

int

ext_inflow_count()#

Return the number of external inflows in the model.

Returns:

External inflow count.

Return type:

int

get_hydrograph(entry_idx)#

Read back a hydrograph parameter entry by index.

Return type:

L{HydrographEntry}

Parameters:

entry_idx (int)

get_hydrograph_gage(entry_idx)#

Read back a UH-to-gage assignment.

Returns:

(uh_name, gage_name).

Return type:

tuple[str, str]

Parameters:

entry_idx (int)

get_hydrograph_group_id(idx)#

Read back the name of a unit-hydrograph group by index.

Parameters:

idx (int) – Zero-based group index (0..hydrograph_group_count()-1).

Returns:

The group name.

Return type:

str

get_rdii(entry_idx)#

Read back an RDII assignment by entry index.

Parameters:

entry_idx (int) – Zero-based index.

Returns:

(node_idx, uh_name, area).

Return type:

tuple[int, str, float]

get_rdii_decay(entry_idx)#

Read back an exponential-decay row by index.

Return type:

L{RDIIDecayEntry}

Parameters:

entry_idx (int)

hydrograph_count()#

Return the number of hydrograph parameter entries.

Return type:

int

hydrograph_gage_count()#

Return the number of UH-to-gage assignments.

Return type:

int

hydrograph_group_count()#

Return the number of unique unit-hydrograph group names defined.

Return type:

int

rdii_count()#

Return the number of RDII inflows in the model.

Returns:

RDII inflow count.

Return type:

int

rdii_decay_count()#

Return the number of exponential-decay rows.

Return type:

int

class RDIIDecayEntry#

Bases: TypedDict

Parameters of a single [RDII_DECAY] row (exponential IA model).

uh_name: str#
response: int#
k_dep: float#
k_0: float#
k_T: float#
T_ref: float#
theta_rec: float#
T_freeze: float#

Advanced forcing (mode + persistence)#

Runtime Forcing#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._forcing.

The Forcing class provides advanced runtime forcing of node, link, subcatchment, and gage values with support for mode (replace or add) and persistence (single-step vs. held until cleared).

class Forcing(solver)#

Bases: object

Advanced runtime forcing for nodes, links, subcatchments, and gages.

All per-element methods accept an integer index. Use the corresponding domain accessor (e.g. solver.nodes.get_index("J1")) to resolve string IDs to indices.

Variables:

_solver – The owning solver instance whose engine handle is used for every C call.

Parameters:

solver (Solver)

Example:

from openswmm.engine import Solver, Forcing, ForcingMode

with Solver("model.inp", "model.rpt", "model.out") as s:
    forcing = Forcing(s)
    j1 = s.nodes.get_index("J1")
    forcing.node_lat_inflow(j1, 1.5, ForcingMode.REPLACE, persist=True)
    while s.state == EngineState.RUNNING:
        if s.step() != 0:
            break
        pass
    forcing.clear_all()
Parameters:

solver (L{Solver}) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Construct a Forcing accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent forcing operations.

__init__(solver)#

Construct a Forcing accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent forcing operations.

Return type:

None

clear(target_type, idx)#

Remove all active forcing on a specific object.

Parameters:
  • target_type (int) – Target type code – see ForcingTarget: NODE (0), LINK (1), SUBCATCH (2), GAGE (3).

  • idx (int) – Object index within its type.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_forcing_clear call returns a non-zero error code.

clear_all()#

Remove all active forcing across all object types.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying C{swmm_forcing_clear_all} call returns a non-zero error code.

gage_rainfall(idx, value, mode=0, persist=False)#

Force a rainfall rate at a rain gage.

Affects all subcatchments assigned to the gage.

Parameters:
  • idx (int) – Gage index.

  • value (float) – Rainfall rate (project rainfall units).

  • mode (int) – Forcing mode – see ForcingMode.

  • persist (bool) – If True, hold the value every step until cleared.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying C{swmm_forcing_gage_rainfall} call returns a non-zero error code.

Force a flow rate in a link.

Parameters:
  • idx (int) – Link index.

  • value (float) – Flow rate (project flow units).

  • mode (int) – Forcing mode – see ForcingMode.

  • persist (bool) – If True, hold the value every step until cleared.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying C{swmm_forcing_link_flow} call returns a non-zero error code.

Force a control setting on a link (pump speed, gate opening, …).

Parameters:
  • idx (int) – Link index.

  • value (float) – Setting value (0.0-1.0 for gates; speed multiplier for pumps).

  • mode (int) – Forcing mode – see ForcingMode.

  • persist (bool) – If True, hold the value every step until cleared.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying C{swmm_forcing_link_setting} call returns a non-zero error code.

node_head_boundary(idx, value, mode=0, persist=False)#

Force a head boundary condition at a node.

Parameters:
  • idx (int) – Node index.

  • value (float) – Boundary head (project length units).

  • mode (int) – Forcing mode – see ForcingMode.

  • persist (bool) – If True, hold the value every step until cleared.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_forcing_node_head_boundary call returns a non-zero error code.

node_lat_inflow(idx, value, mode=0, persist=False)#

Force a lateral inflow at a node.

Parameters:
  • idx (int) – Node index.

  • value (float) – Lateral inflow rate (project flow units).

  • mode (int) – Forcing mode – see ForcingMode: REPLACE (0) or ADD (1).

  • persist (bool) – If True, hold the value every step until cleared; otherwise apply only for the next timestep.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_forcing_node_lat_inflow call returns a non-zero error code.

node_quality(node_idx, pollutant_idx, mass_rate, mode=0, persist=False)#

Force a pollutant mass-rate injection at a node.

Parameters:
  • node_idx (int) – Node index.

  • pollutant_idx (int) – Pollutant index.

  • mass_rate (float) – Mass rate (mass / time, in project units).

  • mode (int) – Forcing mode – see ForcingMode.

  • persist (bool) – If True, hold the value every step until cleared.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying C{swmm_forcing_node_quality} call returns a non-zero error code.

subcatch_evap(idx, value, mode=0, persist=False)#

Force an evaporation rate on a subcatchment.

Parameters:
  • idx (int) – Subcatchment index.

  • value (float) – Evaporation rate (project length / time units).

  • mode (int) – Forcing mode – see ForcingMode.

  • persist (bool) – If True, hold the value every step until cleared.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying C{swmm_forcing_subcatch_evap} call returns a non-zero error code.

subcatch_rainfall(idx, value, mode=0, persist=False)#

Force a rainfall rate on a subcatchment.

Parameters:
  • idx (int) – Subcatchment index.

  • value (float) – Rainfall rate (project rainfall units).

  • mode (int) – Forcing mode – see ForcingMode.

  • persist (bool) – If True, hold the value every step until cleared.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_forcing_subcatch_rainfall call returns a non-zero error code.

Control rules#

Control Rule Access#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._controls.

The Controls class provides access to control rules and runtime link overrides during a simulation.

class Controls(solver)#

Bases: object

Access control rules and override link settings at runtime.

Variables:

_solver – The owning solver instance whose engine handle is used for every C call.

Parameters:

solver (Solver)

Example:

from openswmm.engine import Solver, Controls

with Solver("model.inp", "model.rpt", "model.out") as s:
    ctrl = Controls(s)
    ctrl.add_rule("RULE R1\nIF NODE J1 DEPTH > 5\nTHEN PUMP P1 STATUS = ON")
    print(f"Rule count: {ctrl.count()}")
Parameters:

solver (L{Solver}) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Construct a Controls accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent control operations.

__init__(solver)#

Construct a Controls accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent control operations.

Return type:

None

add_rule(rule_text)#

Add a control rule to the model.

Parameters:

rule_text (str) – Full rule text including RULE, IF, and THEN clauses.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying C{swmm_control_add_rule} call returns a non-zero error code (e.g. malformed rule text).

clear_rules()#

Remove all control rules from the model.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying C{swmm_control_clear_rules} call returns a non-zero error code.

count()#

Return the number of control rules in the model.

Returns:

Rule count.

Return type:

int

get_id(idx)#

Return the canonical name of a control rule by index.

Parses the stored rule text and returns the first whitespace-delimited token following the RULE keyword (case-insensitive, leading whitespace tolerated). Returns C{None} when the rule text has no parseable RULE keyword token, so callers can render a sentinel display name without catching exceptions.

Parameters:

idx (int) – Rule index.

Returns:

The rule name, or None if the rule text is malformed.

Return type:

str | None

Raises:

EngineError – If idx is out of range or the engine handle is invalid.

get_rule(idx)#

Return the text of a control rule by index.

Parameters:

idx (int) – Rule index.

Returns:

Rule text string.

Return type:

str

Raises:

EngineError – If the underlying swmm_control_get_rule call returns a non-zero error code.

Override a link’s control setting at runtime.

Parameters:
  • link_idx (int) – Link index.

  • setting (float) – New setting value (typically 0.0-1.0).

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_control_set_link_setting call returns a non-zero error code.

Override a link’s open/closed status at runtime.

Parameters:
  • link_idx (int) – Link index.

  • status (int) – Status code (0 = closed, 1 = open).

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_control_set_link_status call returns a non-zero error code.

Pollutants#

Pollutant Access#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._pollutants.

The Pollutants class provides access to pollutant properties and runtime water-quality injection during a simulation.

class Pollutants(solver)#

Bases: object

Access pollutant properties and inject quality at nodes and links.

All per-element methods accept either an integer index or a string pollutant ID. When a string is passed it is resolved via get_index.

Variables:

_solver – The owning solver instance whose engine handle is used for every C call.

Parameters:

solver (Solver)

Example:

from openswmm.engine import Solver, Pollutants

with Solver("model.inp", "model.rpt", "model.out") as s:
    poll = Pollutants(s)
    print(f"Pollutant count: {poll.count()}")
    while s.state == EngineState.RUNNING:
        if s.step() != 0:
            break
        conc = poll.get_init_conc("TSS")
        poll.set_node_quality("J1", 0, 12.5)
Parameters:

solver (L{Solver}) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Construct a Pollutants accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent pollutant operations.

__init__(solver)#

Construct a Pollutants accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent pollutant operations.

Return type:

None

add(pollut_id, units)#

Add a pollutant to the model (BUILDING / OPENED state).

Parameters:
  • pollut_id (str) – Unique pollutant identifier.

  • units (int) – Concentration units code (0=MG/L, 1=UG/L, 2=#/L).

Returns:

Zero-based index of the newly added pollutant.

Return type:

int

Raises:

RuntimeError – On engine error.

count()#

Return the number of pollutants in the model.

Returns:

Pollutant count.

Return type:

int

get_co_pollutant(idx)#

Return the co-pollutant index and fraction.

Parameters:

idx (Union[int, str]) – Pollutant index (int) or ID (str).

Returns:

Tuple of (co_pollutant_index, fraction).

Return type:

tuple[int, float]

Raises:
  • EngineError – If the underlying swmm_pollutant_get_co_pollutant call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

get_gw_conc(idx)#

Return the groundwater concentration.

Parameters:

idx (Union[int, str]) – Pollutant index (int) or ID (str).

Returns:

Groundwater concentration.

Return type:

float

Raises:
  • EngineError – If the underlying C{swmm_pollutant_get_gw_conc} call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

get_id(idx)#

Return the string ID of a pollutant by index.

Parameters:

idx (int) – Pollutant index.

Returns:

Pollutant ID string, or empty string if idx is invalid.

Return type:

str

get_index(pollut_id)#

Return the integer index of a pollutant by its string ID.

Parameters:

pollut_id (str) – Pollutant identifier string.

Returns:

Pollutant index, or -1 if not found.

Return type:

int

get_init_conc(idx)#

Return the initial concentration.

Parameters:

idx (Union[int, str]) – Pollutant index (int) or ID (str).

Returns:

Initial concentration.

Return type:

float

Raises:
  • EngineError – If the underlying swmm_pollutant_get_init_conc call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

get_kdecay(idx)#

Return the first-order decay coefficient.

Parameters:

idx (Union[int, str]) – Pollutant index (int) or ID (str).

Returns:

Decay coefficient (1/day).

Return type:

float

Raises:
  • EngineError – If the underlying C{swmm_pollutant_get_kdecay} call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

get_mwt(idx)#

Return the molecular weight.

Parameters:

idx (Union[int, str]) – Pollutant index (int) or ID (str).

Returns:

Molecular weight.

Return type:

float

Raises:
  • EngineError – If the underlying C{swmm_pollutant_get_mwt} call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

get_rain_conc(idx)#

Return the rain concentration.

Parameters:

idx (Union[int, str]) – Pollutant index (int) or ID (str).

Returns:

Rain concentration.

Return type:

float

Raises:
  • EngineError – If the underlying swmm_pollutant_get_rain_conc call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

get_rdii_conc(idx)#

Return the RDII concentration.

Parameters:

idx (Union[int, str]) – Pollutant index (int) or ID (str).

Returns:

RDII concentration.

Return type:

float

Raises:
  • EngineError – If the underlying swmm_pollutant_get_rdii_conc call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

get_snow_only(idx)#

Return whether the pollutant applies only to snow events.

Parameters:

idx (Union[int, str]) – Pollutant index (int) or ID (str).

Returns:

True if the pollutant is snow-only.

Return type:

bool

Raises:
  • EngineError – If the underlying swmm_pollutant_get_snow_only call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

get_units(idx)#

Return the concentration units code for a pollutant.

Parameters:

idx (Union[int, str]) – Pollutant index (int) or ID (str).

Returns:

Units code – see ConcentrationUnits.

Return type:

int

Raises:
  • EngineError – If the underlying C{swmm_pollutant_get_units} call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

set_co_pollutant(idx, co_idx, frac)#

Set the co-pollutant relationship.

Parameters:
  • idx (Union[int, str]) – Pollutant index (int) or ID (str).

  • co_idx (int) – Co-pollutant index.

  • frac (float) – Fraction of co-pollutant contribution.

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying swmm_pollutant_set_co_pollutant call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

set_gw_conc(idx, conc)#

Set the groundwater concentration.

Parameters:
  • idx (Union[int, str]) – Pollutant index (int) or ID (str).

  • conc (float) – Groundwater concentration.

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying C{swmm_pollutant_set_gw_conc} call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

set_init_conc(idx, conc)#

Set the initial concentration.

Parameters:
  • idx (Union[int, str]) – Pollutant index (int) or ID (str).

  • conc (float) – Initial concentration.

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying swmm_pollutant_set_init_conc call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

set_kdecay(idx, k)#

Set the first-order decay coefficient.

Parameters:
  • idx (Union[int, str]) – Pollutant index (int) or ID (str).

  • k (float) – Decay coefficient (1/day).

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying C{swmm_pollutant_set_kdecay} call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

Inject a pollutant concentration at a link.

Parameters:
  • link_idx (Union[int, str]) – Link index (int) or link ID (str).

  • pollut_idx (int) – Pollutant index.

  • conc (float) – Concentration to inject.

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying C{swmm_link_set_quality} call returns a non-zero error code.

  • KeyError – If link_idx is a string not found in the model.

set_mwt(idx, mwt)#

Set the molecular weight.

Parameters:
  • idx (Union[int, str]) – Pollutant index (int) or ID (str).

  • mwt (float) – Molecular weight.

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying C{swmm_pollutant_set_mwt} call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

set_node_quality(node_idx, pollut_idx, conc)#

Inject a pollutant concentration at a node.

Parameters:
  • node_idx (Union[int, str]) – Node index (int) or node ID (str).

  • pollut_idx (int) – Pollutant index.

  • conc (float) – Concentration to inject.

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying C{swmm_node_set_quality} call returns a non-zero error code.

  • KeyError – If node_idx is a string not found in the model.

set_rain_conc(idx, conc)#

Set the rain concentration.

Parameters:
  • idx (Union[int, str]) – Pollutant index (int) or ID (str).

  • conc (float) – Rain concentration.

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying swmm_pollutant_set_rain_conc call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

set_rdii_conc(idx, conc)#

Set the RDII concentration.

Parameters:
  • idx (Union[int, str]) – Pollutant index (int) or ID (str).

  • conc (float) – RDII concentration.

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying swmm_pollutant_set_rdii_conc call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

set_snow_only(idx, flag)#

Set whether the pollutant applies only to snow events.

Parameters:
  • idx (Union[int, str]) – Pollutant index (int) or ID (str).

  • flag (bool) – True for snow-only.

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying swmm_pollutant_set_snow_only call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

Water quality (landuse, buildup, washoff, treatment)#

Water Quality Access#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._quality.

The Quality class provides access to landuse, buildup, washoff, and treatment parameters during a simulation.

class Quality(solver)#

Bases: object

Access landuse, buildup, washoff, and treatment parameters.

Variables:

_solver – The owning solver instance whose engine handle is used for every C call.

Parameters:

solver (Solver)

Example:

from openswmm.engine import Solver
from openswmm.engine._quality import Quality

with Solver("model.inp", "model.rpt", "model.out") as s:
    q = Quality(s)
    print(f"Landuse count: {q.landuse_count()}")
Parameters:

solver (L{Solver}) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Construct a Quality accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent water-quality operations.

__init__(solver)#

Construct a Quality accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent water-quality operations.

Return type:

None

buildup_get(lu_idx, pollut_idx)#

Return buildup parameters for a land use / pollutant pair.

Parameters:
  • lu_idx (int) – Land use index.

  • pollut_idx (int) – Pollutant index.

Returns:

Dict with keys func_type, c1, c2, c3, normalizer.

Return type:

dict

Raises:

EngineError – If the underlying swmm_buildup_get call returns a non-zero error code.

buildup_set(lu_idx, pollut_idx, func_type, c1, c2, c3, normalizer)#

Set buildup parameters for a land use / pollutant pair.

Parameters:
  • lu_idx (int) – Land use index.

  • pollut_idx (int) – Pollutant index.

  • func_type (int) – Buildup function type code – see BuildupFunc.

  • c1 (float) – Coefficient C1.

  • c2 (float) – Coefficient C2.

  • c3 (float) – Coefficient C3.

  • normalizer (int) – Normalizer code (e.g. by area or curb-length).

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_buildup_set call returns a non-zero error code.

landuse_add(landuse_id)#

Add a new land use to the model.

Parameters:

landuse_id (str) – Identifier string for the new land use.

Returns:

Index of the newly created land use.

Return type:

int

landuse_count()#

Return the number of land uses in the model.

Returns:

Land use count.

Return type:

int

landuse_get_sweep_interval(idx)#

Return the street-sweeping interval for a land use.

Parameters:

idx (int) – Land use index.

Returns:

Sweep interval in days.

Return type:

float

Raises:

EngineError – If the underlying swmm_landuse_get_sweep_interval call returns a non-zero error code.

landuse_get_sweep_removal(idx)#

Return the street-sweeping removal fraction for a land use.

Parameters:

idx (int) – Land use index.

Returns:

Removal fraction in [0, 1].

Return type:

float

Raises:

EngineError – If the underlying swmm_landuse_get_sweep_removal call returns a non-zero error code.

landuse_id(idx)#

Return the ID string of a land use by index.

Parameters:

idx (int) – Land use index.

Returns:

Land use identifier, or empty string if idx is invalid.

Return type:

str

landuse_index(id)#

Return the index of a land use by ID.

Parameters:

id (str) – Land use identifier.

Returns:

Index, or -1 if not found.

Return type:

int

landuse_set_sweep_interval(idx, days)#

Set the street-sweeping interval for a land use.

Parameters:
  • idx (int) – Land use index.

  • days (float) – Sweep interval in days.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_landuse_set_sweep_interval call returns a non-zero error code.

landuse_set_sweep_removal(idx, frac)#

Set the street-sweeping removal fraction for a land use.

Parameters:
  • idx (int) – Land use index.

  • frac (float) – Removal fraction in [0, 1].

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_landuse_set_sweep_removal call returns a non-zero error code.

treatment_clear(node_idx, pollut_idx)#

Remove the treatment expression for a node / pollutant pair.

Parameters:
  • node_idx (int) – Node index.

  • pollut_idx (int) – Pollutant index.

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_treatment_clear call returns a non-zero error code.

treatment_get(node_idx, pollut_idx)#

Return the treatment expression for a node / pollutant pair.

Parameters:
  • node_idx (int) – Node index.

  • pollut_idx (int) – Pollutant index.

Returns:

Treatment expression string.

Return type:

str

Raises:

EngineError – If the underlying swmm_treatment_get call returns a non-zero error code.

treatment_set(node_idx, pollut_idx, expression)#

Set a treatment expression for a node / pollutant pair.

Parameters:
  • node_idx (int) – Node index.

  • pollut_idx (int) – Pollutant index.

  • expression (str) – Treatment expression string (SWMM treatment syntax).

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_treatment_set call returns a non-zero error code (e.g. invalid expression).

washoff_get(lu_idx, pollut_idx)#

Return washoff parameters for a land use / pollutant pair.

Parameters:
  • lu_idx (int) – Land use index.

  • pollut_idx (int) – Pollutant index.

Returns:

Dict with keys func_type, coeff, expon, sweep_effic, bmp_effic.

Return type:

dict

Raises:

EngineError – If the underlying swmm_washoff_get call returns a non-zero error code.

washoff_set(lu_idx, pollut_idx, func_type, coeff, expon, sweep_effic, bmp_effic)#

Set washoff parameters for a land use / pollutant pair.

Parameters:
  • lu_idx (int) – Land use index.

  • pollut_idx (int) – Pollutant index.

  • func_type (int) – Washoff function type code – see WashoffFunc.

  • coeff (float) – Washoff coefficient.

  • expon (float) – Washoff exponent.

  • sweep_effic (float) – Street-sweeping efficiency in [0, 1].

  • bmp_effic (float) – BMP removal efficiency in [0, 1].

Returns:

None.

Return type:

None

Raises:

EngineError – If the underlying swmm_washoff_set call returns a non-zero error code.

Tables (time series, curves, patterns)#

Table / Curve / Time-Series Access#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._tables.

The Tables class provides access to curves, time-series, and pattern objects stored in the model.

class Tables(solver)#

Bases: object

Access curve, time-series, and pattern data.

All per-element methods accept either an integer index or a string table ID. When a string is passed it is resolved via get_index.

Variables:

_solver – The owning solver instance whose engine handle is used for every C call.

Parameters:

solver (Solver)

Example:

from openswmm.engine import Solver, Tables

with Solver("model.inp", "model.rpt", "model.out") as s:
    tables = Tables(s)
    print(f"Table count: {tables.count()}")
    y = tables.lookup("StorageCurve", 2.5)
Parameters:

solver (L{Solver}) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Construct a Tables accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent table operations.

__init__(solver)#

Construct a Tables accessor bound to solver.

Parameters:

solver (L{Solver}) – An active Solver instance whose engine handle will be used for all subsequent table operations.

Return type:

None

add_point(idx, x, y)#

Append a data point to a table.

Parameters:
  • idx (Union[int, str]) – Table index (int) or table ID (str).

  • x (float) – X value.

  • y (float) – Y value.

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying swmm_table_add_point call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

clear(idx)#

Remove all data points from a table.

Parameters:

idx (Union[int, str]) – Table index (int) or table ID (str).

Returns:

None.

Return type:

None

Raises:
  • EngineError – If the underlying swmm_table_clear call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

count()#

Return the number of tables (curves + time-series) in the model.

Returns:

Table count.

Return type:

int

curve_add(curve_id, curve_type)#

Add a new curve to the model.

Parameters:
  • curve_id (str) – Identifier string for the new curve.

  • curve_type (int) – Curve type code.

Returns:

Index of the newly created curve.

Return type:

int

get_id(idx)#

Return the string ID of a table by index.

Parameters:

idx (int) – Table index.

Returns:

Table ID string, or empty string if idx is invalid.

Return type:

str

get_index(table_id)#

Return the integer index of a table by its string ID.

Parameters:

table_id (str) – Table identifier string.

Returns:

Table index, or -1 if not found.

Return type:

int

get_point(idx, pt_idx)#

Return a single data point from a table.

Parameters:
  • idx (Union[int, str]) – Table index (int) or table ID (str).

  • pt_idx (int) – Point index within the table.

Returns:

Tuple of (x, y).

Return type:

tuple[float, float]

Raises:
  • EngineError – If the underlying swmm_table_get_point call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

get_point_count(idx)#

Return the number of data points in a table.

Parameters:

idx (Union[int, str]) – Table index (int) or table ID (str).

Returns:

Point count.

Return type:

int

Raises:
  • EngineError – If the underlying C{swmm_table_get_point_count} call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

lookup(idx, x)#

Interpolate a Y value from a table for a given X.

Parameters:
  • idx (Union[int, str]) – Table index (int) or table ID (str).

  • x (float) – X value to look up.

Returns:

Interpolated Y value.

Return type:

float

Raises:
  • EngineError – If the underlying swmm_table_lookup call returns a non-zero error code.

  • KeyError – If idx is a string not found in the model.

pattern_add(pattern_id, pattern_type)#

Add a new time pattern to the model.

Parameters:
  • pattern_id (str) – Identifier string for the new pattern.

  • pattern_type (int) – Pattern type code.

Returns:

Index of the newly created pattern.

Return type:

int

pattern_count()#

Return the number of time patterns in the model.

Returns:

Pattern count.

Return type:

int

pattern_set_factors(idx, factors)#

Set the multiplier factors for a time pattern.

Parameters:
  • idx (int) – Pattern index.

  • factors (ndarray[Any, dtype[float64]]) – Array of multiplier factors.

Return type:

None

timeseries_add(ts_id)#

Add a new time series to the model.

Parameters:

ts_id (str) – Identifier string for the new time series.

Returns:

Index of the newly created time series.

Return type:

int

Infrastructure (transects, streets, inlets, LIDs)#

Infrastructure Access#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._infrastructure.

The Infrastructure class provides access to transects, streets, inlets, and LID controls/usage within the model.

class Infrastructure(solver)#

Bases: object

Access transects, streets, inlets, and LID controls.

The class wraps the swmm_transect_*, swmm_street_*, swmm_inlet_*, swmm_lid_*, and swmm_lid_usage_* entry points of the OpenSWMM C API.

Example:

from openswmm.engine import Solver, Infrastructure

with Solver("model.inp", "model.rpt", "model.out") as s:
    infra = Infrastructure(s)
    print(f"Transects: {infra.transect_count()}")
    print(f"Streets:   {infra.street_count()}")
    print(f"LIDs:      {infra.lid_count()}")
Variables:

_solver – The Solver instance whose engine handle is used for every C API call.

Parameters:

solver (Solver)

Construct an Infrastructure accessor bound to a solver.

Parameters:

solver (Solver) – An active Solver instance. The solver must remain alive for the lifetime of this object.

__init__(solver)#

Construct an Infrastructure accessor bound to a solver.

Parameters:

solver (Solver) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Return type:

None

inlet_add(inlet_id, inlet_type)#

Add a new inlet to the model.

Parameters:
  • inlet_id (str) – Identifier string for the new inlet.

  • inlet_type (str) – Inlet type string.

Returns:

Index of the newly created inlet.

Return type:

int

inlet_count()#

Return the number of inlets defined in the model.

Returns:

Inlet count.

Return type:

int

inlet_set_params(idx, length, width, grate_type, open_area, splash_veloc)#

Set the parameters for an inlet.

Parameters:
  • idx (int) – Inlet index.

  • length (float) – Inlet length.

  • width (float) – Inlet width.

  • grate_type (str) – Grate type identifier string (e.g. "P_BAR-50").

  • open_area (float) – Open area fraction.

  • splash_veloc (float) – Splash-over velocity.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

lid_add(lid_id, lid_type)#

Add a new LID control to the model.

Parameters:
  • lid_id (str) – Identifier string for the new LID control.

  • lid_type (int) – LID type code.

Returns:

Index of the newly created LID control.

Return type:

int

lid_count()#

Return the number of LID controls in the model.

Returns:

LID control count.

Return type:

int

lid_set_drain(idx, coeff, expon, offset)#

Set LID underdrain parameters.

Parameters:
  • idx (int) – LID control index.

  • coeff (float) – Drain coefficient.

  • expon (float) – Drain exponent.

  • offset (float) – Drain offset height.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

lid_set_soil(idx, thick, porosity, fc, wp, ksat, kslope)#

Set LID soil-layer parameters.

Parameters:
  • idx (int) – LID control index.

  • thick (float) – Soil thickness.

  • porosity (float) – Porosity (volume fraction).

  • fc (float) – Field capacity (volume fraction).

  • wp (float) – Wilting point (volume fraction).

  • ksat (float) – Saturated hydraulic conductivity.

  • kslope (float) – Conductivity slope (Green-Ampt parameter).

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

lid_set_storage(idx, thick, void_frac, ksat)#

Set LID storage-layer parameters.

Parameters:
  • idx (int) – LID control index.

  • thick (float) – Storage thickness.

  • void_frac (float) – Void fraction.

  • ksat (float) – Saturated hydraulic conductivity.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

lid_set_surface(idx, storage, roughness, slope)#

Set LID surface-layer parameters.

Parameters:
  • idx (int) – LID control index.

  • storage (float) – Surface storage depth.

  • roughness (float) – Surface Manning’s M{n}.

  • slope (float) – Surface slope.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

lid_usage_add(subcatch_idx, lid_idx, number, area, width, init_sat, from_imperv)#

Assign an LID control to a subcatchment.

Parameters:
  • subcatch_idx (int) – Subcatchment index.

  • lid_idx (int) – LID control index.

  • number (int) – Number of LID units placed.

  • area (float) – Area of each LID unit.

  • width (float) – Top width of overland flow surface.

  • init_sat (float) – Initial saturation in the range 0.0-1.0.

  • from_imperv (float) – Fraction of impervious area treated, in 0.0-1.0.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

street_add(street_id)#

Add a new street cross-section to the model.

Parameters:

street_id (str) – Identifier string for the new street.

Returns:

Index of the newly created street.

Return type:

int

street_count()#

Return the number of street cross-sections in the model.

Returns:

Street count.

Return type:

int

street_set_params(idx, t_crown, h_curb, sx, n_road, gutter_depres, gutter_width, sides, back_width, back_slope, back_n)#

Set the geometric parameters for a street cross-section.

Parameters:
  • idx (int) – Street index.

  • t_crown (float) – Crown width.

  • h_curb (float) – Curb height.

  • sx (float) – Cross slope.

  • n_road (float) – Road Manning’s M{n}.

  • gutter_depres (float) – Gutter depression depth.

  • gutter_width (float) – Gutter width.

  • sides (int) – Number of sides (1 or 2).

  • back_width (float) – Backing width.

  • back_slope (float) – Backing slope.

  • back_n (float) – Backing Manning’s M{n}.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

transect_add(transect_id)#

Add a new transect to the model.

Parameters:

transect_id (str) – Identifier string for the new transect.

Returns:

Index of the newly created transect.

Return type:

int

transect_add_station(idx, station, elevation)#

Append a station-elevation point to a transect.

Parameters:
  • idx (int) – Transect index.

  • station (float) – Station (horizontal distance) in project units.

  • elevation (float) – Elevation at station in project units.

Raises:

RuntimeError – If the C API rejects the point.

Return type:

None

transect_count()#

Return the number of transects defined in the model.

Returns:

Transect count.

Return type:

int

transect_set_roughness(idx, n_left, n_right, n_channel)#

Set Manning’s roughness values for a transect.

Parameters:
  • idx (int) – Transect index.

  • n_left (float) – Left overbank Manning’s M{n}.

  • n_right (float) – Right overbank Manning’s M{n}.

  • n_channel (float) – Channel Manning’s M{n}.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

Hot start#

Hot Start File Management#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._hotstart.

The HotStart class manages hot start files for saving and restoring simulation state across runs.

class HotStart#

Bases: object

Handle to a hot start file.

Use HotStart.save to write simulation state to disk and L{HotStart.open} to read it back. Supports the context manager protocol for automatic cleanup.

Example – Saving a hot start:

with Solver("model.inp") as s:
    while s.state == EngineState.RUNNING:
        if s.step() != 0:
            break
        pass
    HotStart.save(s, "warmup.hs")

Example – Applying a hot start:

with HotStart.open("warmup.hs") as hs:
    s = Solver("model.inp")
    s.open()
    s.initialize()
    hs.apply(s)
    s.start()
    while s.state == EngineState.RUNNING:
        if s.step() != 0:
            break
        pass
    s.end()
    s.destroy()
Variables:

_handle – Opaque pointer to the underlying C{SWMM_HotStart} handle. Managed internally; not part of the public API.

Construct an empty HotStart handle.

Use the HotStart.open class method or HotStart.save static method instead of constructing an instance directly.

Returns:

A new, unattached HotStart instance.

Return type:

HotStart

__init__()#

Construct an empty HotStart handle.

Use the HotStart.open class method or HotStart.save static method instead of constructing an instance directly.

Returns:

A new, unattached HotStart instance.

Return type:

HotStart

apply(solver)#

Apply this hot start state to an engine.

Wraps swmm_hotstart_apply. The engine must be in C{INITIALIZED} state (after Solver.initialize but before Solver.start).

Parameters:

solver (Solver) – Target Solver to which the hot start state is applied.

Raises:

EngineError – If the state cannot be applied.

Return type:

None

close()#

Close the hot start file and free resources.

Wraps swmm_hotstart_close. Safe to call multiple times; once closed, the handle becomes inert.

Returns:

None.

Return type:

NoneType

get_crs()#

Return the coordinate reference system string from the hot start file.

Wraps swmm_hotstart_get_crs.

Returns:

Coordinate reference system string (UTF-8 decoded). May be empty if no CRS was recorded.

Return type:

str

Raises:

EngineError – If the underlying C call fails.

get_sim_time()#

Return the simulation time stored in the hot start file.

Wraps swmm_hotstart_get_sim_time.

Returns:

Simulation time (decimal days).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

get_warning(index)#

Return a warning message by index.

Wraps swmm_hotstart_warning.

Parameters:

index (int) – Zero-based warning index in [0, warning_count()).

Returns:

Warning message, or empty string if not available.

Return type:

str

Return the number of links in the hot start file.

Wraps swmm_hotstart_link_count.

Returns:

Number of links.

Return type:

int

node_count()#

Return the number of nodes in the hot start file.

Wraps swmm_hotstart_node_count.

Returns:

Number of nodes.

Return type:

int

classmethod open(path)#

Open a hot start file for reading.

Wraps swmm_hotstart_open. The returned handle should be closed with HotStart.close or by using a with block.

Parameters:

path (str) – Path to an existing hot start file.

Returns:

A new HotStart handle bound to the opened file.

Return type:

HotStart

Raises:

IOError – If the file cannot be opened.

static save(solver, path)#

Save the current simulation state to a hot start file.

Wraps swmm_hotstart_save. Valid only when the solver is in RUNNING or ENDED state.

Parameters:
  • solver (Solver) – An active Solver in RUNNING or ENDED state.

  • path (str) – Output file path.

Raises:

EngineError – If the state cannot be saved.

Return type:

None

static saves_add(solver, path, datetime=0.0)#

Append a new scheduled hotstart save entry.

Parameters:
  • solver (Solver) – An active Solver instance.

  • path (str) – Output file path.

  • datetime (float) – OADate decimal-day (0.0 = end of run).

Return type:

None

static saves_clear(solver)#

Remove all scheduled hotstart save entries.

Parameters:

solver (Solver) – An active Solver instance.

Return type:

None

static saves_count(solver)#

Return the number of scheduled hotstart saves on an engine.

Parameters:

solver (Solver) – An active Solver instance.

Returns:

Number of SAVE HOTSTART entries.

Return type:

int

static saves_get_datetime(solver, idx)#

Return the datetime (decimal day) for a scheduled hotstart save.

Parameters:
  • solver (Solver) – An active Solver instance.

  • idx (int) – Save entry index.

Returns:

OADate decimal-day datetime (0.0 = end of run).

Return type:

float

static saves_get_path(solver, idx)#

Return the file path for a scheduled hotstart save entry.

Parameters:
  • solver (Solver) – An active Solver instance.

  • idx (int) – Save entry index.

Returns:

File path string.

Return type:

str

static saves_remove(solver, idx)#

Remove a scheduled hotstart save entry by index.

Parameters:
  • solver (Solver) – An active Solver instance.

  • idx (int) – Index of the entry to remove.

Return type:

None

static saves_set_datetime(solver, idx, datetime)#

Update the datetime for an existing scheduled hotstart save.

Parameters:
  • solver (Solver) – An active Solver instance.

  • idx (int) – Save entry index.

  • datetime (float) – OADate decimal-day (0.0 = end of run).

Return type:

None

static saves_set_path(solver, idx, path)#

Update the file path for an existing scheduled hotstart save.

Parameters:
  • solver (Solver) – An active Solver instance.

  • idx (int) – Save entry index.

  • path (str) – New file path.

Return type:

None

Set the depth of a link in the hot start state.

Wraps swmm_hotstart_set_link_depth.

Parameters:
  • link_id (str) – Link identifier.

  • depth (float) – Depth value (project length units).

Raises:

EngineError – If the underlying C call fails.

Return type:

None

Set the flow of a link in the hot start state.

Wraps swmm_hotstart_set_link_flow.

Parameters:
  • link_id (str) – Link identifier.

  • flow (float) – Flow value (project flow units).

Raises:

EngineError – If the underlying C call fails.

Return type:

None

set_node_depth(node_id, depth)#

Set the depth of a node in the hot start state.

Wraps swmm_hotstart_set_node_depth.

Parameters:
  • node_id (str) – Node identifier.

  • depth (float) – Depth value (project length units).

Raises:

EngineError – If the underlying C call fails.

Return type:

None

set_node_head(node_id, head)#

Set the hydraulic head of a node in the hot start state.

Wraps swmm_hotstart_set_node_head.

Parameters:
  • node_id (str) – Node identifier.

  • head (float) – Hydraulic head value (project length units).

Raises:

EngineError – If the underlying C call fails.

Return type:

None

set_subcatch_runoff(subcatch_id, runoff)#

Set the runoff of a subcatchment in the hot start state.

Wraps swmm_hotstart_set_subcatch_runoff.

Parameters:
  • subcatch_id (str) – Subcatchment identifier.

  • runoff (float) – Runoff value (project flow units).

Raises:

EngineError – If the underlying C call fails.

Return type:

None

warning_count()#

Return the number of warnings generated when opening the hot start file.

Wraps swmm_hotstart_warning_count.

Returns:

Number of warnings.

Return type:

int

Mass balance#

Mass Balance and Continuity#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._massbalance.

The MassBalance class provides continuity error queries after a simulation completes.

class MassBalance(solver)#

Bases: object

Query continuity errors and cumulative flux totals.

All methods operate on the engine handle held by the L{Solver} passed at construction time.

Example:

from openswmm.engine import Solver, MassBalance

with Solver("model.inp") as s:
    while s.state == EngineState.RUNNING:
        if s.step() != 0:
            break
        pass

mb = MassBalance(s)
print(f"Runoff error:  {mb.get_runoff_continuity_error():.4%}")
print(f"Routing error: {mb.get_routing_continuity_error():.4%}")
Variables:

_solver – The Solver instance providing the engine handle.

Parameters:

solver (Solver)

Construct a MassBalance bound to a solver.

Parameters:

solver (Solver) – An active Solver instance (typically after the simulation has ended).

__init__(solver)#

Construct a MassBalance bound to a solver.

Parameters:

solver (Solver) – An active Solver instance (typically after the simulation has ended).

Return type:

None

get_max_courant()#

Return the maximum Courant number observed during simulation.

Wraps swmm_get_max_courant.

Returns:

Maximum Courant number (dimensionless).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

get_quality_continuity_error(pollutant_idx)#

Return the quality continuity error for a pollutant.

Wraps swmm_get_quality_continuity_error.

Parameters:

pollutant_idx (int) – Zero-based pollutant index.

Returns:

Continuity error as a fraction.

Return type:

float

Raises:

EngineError – If the underlying C call fails.

get_quality_evap_loss(pollutant_idx)#

Return quality mass lost to evaporation for a pollutant.

Wraps swmm_get_quality_evap_loss.

Parameters:

pollutant_idx (int) – Zero-based pollutant index.

Returns:

Cumulative mass lost to evaporation (project mass units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

get_quality_seep_loss(pollutant_idx)#

Return quality mass lost to seepage for a pollutant.

Wraps swmm_get_quality_seep_loss.

Parameters:

pollutant_idx (int) – Zero-based pollutant index.

Returns:

Cumulative mass lost to seepage (project mass units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

get_routing_continuity_error()#

Return the routing continuity error.

Wraps swmm_get_routing_continuity_error.

Returns:

Continuity error as a fraction.

Return type:

float

Raises:

EngineError – If the underlying C call fails.

get_routing_stats()#

Return combined routing statistics in a single call.

Wraps swmm_get_routing_stats. Provides time-step diagnostics for the routing solver.

Returns:

Dictionary with keys avg_step, min_step, max_step, n_steps, pct_non_converged, avg_iterations, max_courant.

Return type:

dict

Raises:

EngineError – If the underlying C call fails.

get_routing_total(component)#

Return a cumulative routing total.

Wraps swmm_get_routing_total.

Parameters:

component (int) – SWMM_RoutingTotal enum code (0-10).

Returns:

Cumulative volume (project volume units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

@see: L{openswmm.engine.RoutingTotal}

get_runoff_continuity_error()#

Return the runoff continuity error.

Wraps swmm_get_runoff_continuity_error.

Returns:

Continuity error as a fraction (e.g., 0.001 = 0.1%).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

get_runoff_total(component)#

Return a cumulative runoff total.

Wraps swmm_get_runoff_total.

Parameters:

component (int) – SWMM_RunoffTotal enum code (0-6).

Returns:

Cumulative volume (project volume units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

@see: L{openswmm.engine.RunoffTotal}

Statistics#

Simulation Statistics#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._statistics.

The Statistics class provides access to post-simulation summary statistics for nodes, links, and subcatchments.

class Statistics(solver)#

Bases: object

Access post-simulation summary statistics.

Query after calling Solver.end to obtain cumulative extremes and totals computed over the full simulation. The Solver must remain alive for the lifetime of this object.

Example:

from openswmm.engine import Solver
from openswmm.engine._statistics import Statistics

with Solver("model.inp", "model.rpt", "model.out") as s:
    while s.state == EngineState.RUNNING:
        if s.step() != 0:
            break
        pass
stats = Statistics(s)
print(f"Max depth at node 0: {stats.node_max_depth(0)}")
Variables:

_solver – The Solver instance providing the engine handle.

Parameters:

solver (Solver)

Construct a Statistics bound to a solver.

Parameters:

solver (Solver) – An active Solver instance. The solver must remain alive for the lifetime of this object.

__init__(solver)#

Construct a Statistics bound to a solver.

Parameters:

solver (Solver) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Return type:

None

Return the maximum filling fraction recorded in a link.

Wraps swmm_stat_link_max_filling.

Parameters:

idx (int) – Zero-based link index.

Returns:

Maximum filling fraction (0-1).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

Return the maximum flow recorded in a link.

Wraps swmm_stat_link_max_flow.

Parameters:

idx (int) – Zero-based link index.

Returns:

Maximum flow (project flow units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

Return maximum flows for all links as a NumPy array.

Wraps swmm_stat_link_max_flow_bulk.

Returns:

Array of shape (n_links,) with dtype float64.

Return type:

np.ndarray

Raises:

EngineError – If the underlying C call fails.

Return the maximum velocity recorded in a link.

Wraps swmm_stat_link_max_velocity.

Parameters:

idx (int) – Zero-based link index.

Returns:

Maximum velocity (project length / time units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

Return the total surcharge time for a link.

Wraps swmm_stat_link_surcharge_time.

Parameters:

idx (int) – Zero-based link index.

Returns:

Surcharge time (hours).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

Return the total volume of flow through a link.

Wraps swmm_stat_link_vol_flow.

Parameters:

idx (int) – Zero-based link index.

Returns:

Total flow volume (project volume units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

node_max_depth(idx)#

Return the maximum depth recorded at a node.

Wraps swmm_stat_node_max_depth.

Parameters:

idx (int) – Zero-based node index.

Returns:

Maximum depth (project length units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

node_max_depth_bulk()#

Return maximum depths for all nodes as a NumPy array.

Wraps swmm_stat_node_max_depth_bulk.

Returns:

Array of shape (n_nodes,) with dtype float64.

Return type:

np.ndarray

Raises:

EngineError – If the underlying C call fails.

node_max_overflow(idx)#

Return the maximum overflow rate recorded at a node.

Wraps swmm_stat_node_max_overflow.

Parameters:

idx (int) – Zero-based node index.

Returns:

Maximum overflow rate (project flow units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

node_time_flooded(idx)#

Return the total time a node was flooded.

Wraps swmm_stat_node_time_flooded.

Parameters:

idx (int) – Zero-based node index.

Returns:

Time flooded (hours).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

node_vol_flooded(idx)#

Return the total volume flooded at a node.

Wraps swmm_stat_node_vol_flooded.

Parameters:

idx (int) – Zero-based node index.

Returns:

Volume flooded (project volume units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

subcatch_max_runoff(idx)#

Return the maximum runoff rate from a subcatchment.

Wraps swmm_stat_subcatch_max_runoff.

Parameters:

idx (int) – Zero-based subcatchment index.

Returns:

Maximum runoff rate (project flow units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

subcatch_precip(idx)#

Return the total precipitation on a subcatchment.

Wraps swmm_stat_subcatch_precip.

Parameters:

idx (int) – Zero-based subcatchment index.

Returns:

Total precipitation volume (project depth x area units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

subcatch_runoff_vol(idx)#

Return the total runoff volume from a subcatchment.

Wraps swmm_stat_subcatch_runoff_vol.

Parameters:

idx (int) – Zero-based subcatchment index.

Returns:

Total runoff volume (project volume units).

Return type:

float

Raises:

EngineError – If the underlying C call fails.

subcatch_runoff_vol_bulk()#

Return total runoff volumes for all subcatchments as a NumPy array.

Wraps swmm_stat_subcatch_runoff_vol_bulk.

Returns:

Array of shape (n_subcatchments,) with dtype float64.

Return type:

np.ndarray

Raises:

EngineError – If the underlying C call fails.

Output reader (binary .out file)#

Binary Output File Reader#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._output_reader.

The OutputReader class reads SWMM binary output files (.out) independently of the engine handle.

class OutputReader(path)#

Bases: object

Read a SWMM binary output file.

Supports the context manager protocol for automatic resource cleanup. Operates on the binary .out file produced by a completed simulation and does not require an active engine handle.

Example:

from openswmm.engine._output_reader import OutputReader

with OutputReader("model.out") as out:
    print(f"Periods: {out.get_period_count()}")
    depths = out.get_node_result(0, 0)
Variables:

_handle – Opaque pointer to the underlying C{SWMM_Output} handle. Managed internally; not part of the public API.

Parameters:

path (str)

Open a SWMM binary output file.

Wraps swmm_output_open.

Parameters:

path (str) – Path to the .out file.

Raises:

IOError – If the file cannot be opened.

__init__(path)#

Open a SWMM binary output file.

Wraps swmm_output_open.

Parameters:

path (str) – Path to the .out file.

Raises:

IOError – If the file cannot be opened.

Return type:

None

close()#

Close the output file and release resources.

Wraps swmm_output_close. Safe to call multiple times.

Returns:

None.

Return type:

NoneType

get_error_code()#

Return the error code stored in the output file.

Wraps swmm_output_get_error_code.

Returns:

Error code (0 on success).

Return type:

int

get_flow_units()#

Return the flow units code.

Wraps swmm_output_get_flow_units.

Returns:

Flow units code (see openswmm.engine.FlowUnits).

Return type:

int

@see: L{openswmm.engine.FlowUnits}

Return all attribute values for a link at a period.

Wraps swmm_output_get_link_attribute.

Parameters:
  • link_idx (int) – Zero-based link index.

  • period (int) – Zero-based reporting period index.

Returns:

Array of attribute values with dtype float32.

Return type:

np.ndarray

Raises:

RuntimeError – If the underlying read fails.

Return the number of links in the output file.

Wraps swmm_output_get_link_count.

Returns:

Number of links.

Return type:

int

Return the ID string of a link by index.

Wraps swmm_output_get_link_id.

Parameters:

index (int) – Zero-based link index.

Returns:

Link identifier (UTF-8 decoded), or empty string if not available.

Return type:

str

Return a link variable for all links at a period.

Wraps swmm_output_get_link_result.

Parameters:
  • period (int) – Zero-based reporting period index.

  • var (int) – Variable code (see openswmm.engine.OutLinkVar).

Returns:

Array of shape (n_links,) with dtype float32.

Return type:

np.ndarray

Raises:

RuntimeError – If the underlying read fails.

@see: L{openswmm.engine.OutLinkVar}

Return a time series of a link variable.

Wraps swmm_output_get_link_series.

Parameters:
  • link_idx (int) – Zero-based link index.

  • var (int) – Variable code (see openswmm.engine.OutLinkVar).

  • start (int) – Start period index.

  • end (int) – End period index (inclusive).

Returns:

Array of shape (end - start + 1,) with dtype float32.

Return type:

np.ndarray

Raises:

RuntimeError – If the underlying read fails.

get_node_attribute(node_idx, period)#

Return all attribute values for a node at a period.

Wraps swmm_output_get_node_attribute.

Parameters:
  • node_idx (int) – Zero-based node index.

  • period (int) – Zero-based reporting period index.

Returns:

Array of attribute values with dtype float32.

Return type:

np.ndarray

Raises:

RuntimeError – If the underlying read fails.

get_node_count()#

Return the number of nodes in the output file.

Wraps swmm_output_get_node_count.

Returns:

Number of nodes.

Return type:

int

get_node_id(index)#

Return the ID string of a node by index.

Wraps swmm_output_get_node_id.

Parameters:

index (int) – Zero-based node index.

Returns:

Node identifier (UTF-8 decoded), or empty string if not available.

Return type:

str

get_node_result(period, var)#

Return a node variable for all nodes at a period.

Wraps swmm_output_get_node_result.

Parameters:
  • period (int) – Zero-based reporting period index.

  • var (int) – Variable code (see openswmm.engine.OutNodeVar).

Returns:

Array of shape (n_nodes,) with dtype float32.

Return type:

np.ndarray

Raises:

RuntimeError – If the underlying read fails.

@see: L{openswmm.engine.OutNodeVar}

get_node_series(node_idx, var, start, end)#

Return a time series of a node variable.

Wraps swmm_output_get_node_series.

Parameters:
  • node_idx (int) – Zero-based node index.

  • var (int) – Variable code (see openswmm.engine.OutNodeVar).

  • start (int) – Start period index.

  • end (int) – End period index (inclusive).

Returns:

Array of shape (end - start + 1,) with dtype float32.

Return type:

np.ndarray

Raises:

RuntimeError – If the underlying read fails.

get_period_count()#

Return the number of reporting periods.

Wraps swmm_output_get_period_count.

Returns:

Number of reporting periods.

Return type:

int

get_period_time(period)#

Return the elapsed time for a reporting period.

Wraps swmm_output_get_period_time.

Parameters:

period (int) – Zero-based reporting period index.

Returns:

Elapsed time value (project time units).

Return type:

float

Raises:

RuntimeError – If the underlying read fails.

get_pollut_count()#

Return the number of pollutants in the output file.

Wraps swmm_output_get_pollut_count.

Returns:

Number of pollutants.

Return type:

int

get_report_step()#

Return the reporting time step in seconds.

Wraps swmm_output_get_report_step.

Returns:

Reporting time step (seconds).

Return type:

int

get_start_date()#

Return the simulation start date as a Julian date value.

Wraps swmm_output_get_start_date.

Returns:

Julian date.

Return type:

float

Raises:

RuntimeError – If the underlying read fails.

get_subcatch_attribute(subcatch_idx, period)#

Return all attribute values for a subcatchment at a period.

Wraps swmm_output_get_subcatch_attribute.

Parameters:
  • subcatch_idx (int) – Zero-based subcatchment index.

  • period (int) – Zero-based reporting period index.

Returns:

Array of attribute values with dtype float32.

Return type:

np.ndarray

Raises:

RuntimeError – If the underlying read fails.

get_subcatch_count()#

Return the number of subcatchments in the output file.

Wraps swmm_output_get_subcatch_count.

Returns:

Number of subcatchments.

Return type:

int

get_subcatch_id(index)#

Return the ID string of a subcatchment by index.

Wraps swmm_output_get_subcatch_id.

Parameters:

index (int) – Zero-based subcatchment index.

Returns:

Subcatchment identifier (UTF-8 decoded), or empty string if not available.

Return type:

str

get_subcatch_result(period, var)#

Return a subcatchment variable for all subcatchments at a period.

Wraps swmm_output_get_subcatch_result.

Parameters:
  • period (int) – Zero-based reporting period index.

  • var (int) – Variable code (see openswmm.engine.OutSubcatchVar).

Returns:

Array of shape (n_subcatchments,) with dtype float32.

Return type:

np.ndarray

Raises:

RuntimeError – If the underlying read fails.

@see: L{openswmm.engine.OutSubcatchVar}

get_subcatch_series(subcatch_idx, var, start, end)#

Return a time series of a subcatchment variable.

Wraps swmm_output_get_subcatch_series.

Parameters:
  • subcatch_idx (int) – Zero-based subcatchment index.

  • var (int) – Variable code (see openswmm.engine.OutSubcatchVar).

  • start (int) – Start period index.

  • end (int) – End period index (inclusive).

Returns:

Array of shape (end - start + 1,) with dtype float32.

Return type:

np.ndarray

Raises:

RuntimeError – If the underlying read fails.

get_system_result(period, var)#

Return a system-level variable at a period.

Wraps swmm_output_get_system_result.

Parameters:
  • period (int) – Zero-based reporting period index.

  • var (int) – Variable code (see openswmm.engine.OutSystemVar).

Returns:

Variable value.

Return type:

float

Raises:

RuntimeError – If the underlying read fails.

@see: L{openswmm.engine.OutSystemVar}

get_system_series(var, start, end)#

Return a time series of a system-level variable.

Wraps swmm_output_get_system_series.

Parameters:
  • var (int) – Variable code (see openswmm.engine.OutSystemVar).

  • start (int) – Start period index.

  • end (int) – End period index (inclusive).

Returns:

Array of shape (end - start + 1,) with dtype float32.

Return type:

np.ndarray

Raises:

RuntimeError – If the underlying read fails.

get_version()#

Return the SWMM version that produced the output file.

Wraps swmm_output_get_version.

Returns:

Version integer.

Return type:

int

Spatial (CRS, coordinates, vertices, polygons)#

Spatial Coordinate Access#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._spatial.

The Spatial class provides access to geographic coordinates of nodes, links, subcatchments, and rain gages.

class Spatial(solver)#

Bases: object

Access geographic coordinates for model elements.

Provides scalar and bulk numpy-array accessors for nodes, links (single coordinates and polyline vertices), subcatchments (centroid and polygon outlines), and rain gages, plus a project-wide coordinate reference system.

Example:

from openswmm.engine import Solver
from openswmm.engine._spatial import Spatial

with Solver("model.inp", "model.rpt", "model.out") as s:
    sp = Spatial(s)
    x, y = sp.get_node_coord(0)
    sp.set_node_coord(0, x + 100.0, y)
Variables:

_solver – The Solver instance whose engine handle is used for every C API call.

Parameters:

solver (Solver)

Construct a Spatial accessor bound to a solver.

Parameters:

solver (Solver) – An active Solver instance. The solver must remain alive for the lifetime of this object.

__init__(solver)#

Construct a Spatial accessor bound to a solver.

Parameters:

solver (Solver) – An active Solver instance. The solver must remain alive for the lifetime of this object.

Return type:

None

get_crs()#

Return the project coordinate reference system.

Returns:

CRS identifier string.

Return type:

str

Raises:

RuntimeError – If the C API call fails.

get_gage_coord(idx)#

Return the coordinate of a rain gage.

Parameters:

idx (int) – Gage index.

Returns:

Tuple (x, y) of the gage’s coordinate.

Return type:

tuple[float, float]

Raises:

RuntimeError – If the C API call fails.

Return the representative (X, Y) coordinate of a link.

Parameters:

idx (int) – Link index.

Returns:

Tuple (x, y) of the link’s representative coordinate.

Return type:

tuple[float, float]

Raises:

RuntimeError – If the C API call fails.

Return the number of ordered polyline vertices for a link.

The count includes the upstream node coordinate at index 0, any interior vertices, and the downstream node coordinate at the last index.

Parameters:

idx (int) – Link index.

Returns:

Vertex count.

Return type:

int

Raises:

RuntimeError – If the C API call fails.

Return ordered polyline vertices of a link as NumPy arrays.

Ordering is upstream node, interior vertices, downstream node.

Parameters:

idx (int) – Link index.

Returns:

Tuple (x_array, y_array), each of shape (get_link_vertex_count(idx),) with dtype float64.

Return type:

tuple[np.ndarray, np.ndarray]

Raises:

RuntimeError – If the C API call fails.

@see: L{get_link_vertex_count}

get_node_coord(idx)#

Return the projected (X, Y) coordinate of a node.

Parameters:

idx (int) – Node index.

Returns:

Tuple (x, y) of node coordinates.

Return type:

tuple[float, float]

Raises:

RuntimeError – If the C API call fails.

get_node_coords_bulk()#

Return coordinates for all nodes as NumPy arrays.

Returns:

Tuple (x_array, y_array), each of shape (n_nodes,) with dtype float64.

Return type:

tuple[np.ndarray, np.ndarray]

Raises:

RuntimeError – If the C API call fails.

get_subcatch_coord(idx)#

Return the centroid coordinate of a subcatchment.

Parameters:

idx (int) – Subcatchment index.

Returns:

Tuple (x, y) centroid coordinate.

Return type:

tuple[float, float]

Raises:

RuntimeError – If the C API call fails.

get_subcatch_polygon(idx)#

Return the polygon vertices of a subcatchment as NumPy arrays.

Parameters:

idx (int) – Subcatchment index.

Returns:

Tuple (x_array, y_array), each of shape (get_subcatch_polygon_count(idx),) with dtype float64.

Return type:

tuple[np.ndarray, np.ndarray]

Raises:

RuntimeError – If the C API call fails.

@see: L{get_subcatch_polygon_count}

get_subcatch_polygon_count(idx)#

Return the number of polygon vertices for a subcatchment.

Parameters:

idx (int) – Subcatchment index.

Returns:

Vertex count.

Return type:

int

Raises:

RuntimeError – If the C API call fails.

set_crs(crs)#

Set the project coordinate reference system.

Parameters:

crs (str) – CRS identifier (e.g. an EPSG code such as "EPSG:4326" or a WKT string).

Raises:

RuntimeError – If the C API rejects the CRS string.

Return type:

None

set_gage_coord(idx, x, y)#

Set the coordinate of a rain gage.

Parameters:
  • idx (int) – Gage index.

  • x (float) – X coordinate in the project CRS.

  • y (float) – Y coordinate in the project CRS.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

Set the representative (X, Y) coordinate of a link.

Parameters:
  • idx (int) – Link index.

  • x (float) – X coordinate in the project CRS.

  • y (float) – Y coordinate in the project CRS.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

Set the polyline vertices of a link.

The x and y arrays must have the same length and define the ordered polyline geometry of the link.

Parameters:
  • idx (int) – Link index.

  • x (np.ndarray) – X coordinates of vertices, dtype float64.

  • y (np.ndarray) – Y coordinates of vertices, dtype float64.

Raises:

RuntimeError – If the C API rejects the geometry.

Return type:

None

set_node_coord(idx, x, y)#

Set the projected (X, Y) coordinate of a node.

Parameters:
  • idx (int) – Node index.

  • x (float) – X coordinate in the project CRS.

  • y (float) – Y coordinate in the project CRS.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

set_node_coords_bulk(x, y)#

Set coordinates for all nodes from NumPy arrays.

Parameters:
  • x (np.ndarray) – X coordinates of shape (n_nodes,), dtype float64.

  • y (np.ndarray) – Y coordinates of shape (n_nodes,), dtype float64.

Raises:

RuntimeError – If the C API rejects the bulk assignment.

Return type:

None

set_subcatch_coord(idx, x, y)#

Set the centroid coordinate of a subcatchment.

Parameters:
  • idx (int) – Subcatchment index.

  • x (float) – X coordinate in the project CRS.

  • y (float) – Y coordinate in the project CRS.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

set_subcatch_polygon(idx, x, y)#

Set the polygon vertices of a subcatchment.

Parameters:
  • idx (int) – Subcatchment index.

  • x (np.ndarray) – X coordinates of polygon vertices, dtype float64.

  • y (np.ndarray) – Y coordinates of polygon vertices, dtype float64.

Raises:

RuntimeError – If the C API rejects the polygon.

Return type:

None

Enumerations#

Enumerations#

author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._enums.

Integer-backed enums mirroring the C API enum definitions in openswmm_engine.h. All enums inherit from enum.IntEnum and can be compared directly with integer return values from C API functions.

class BuildupFunc(*values)

Bases: IntEnum

Pollutant buildup function type.

Variables:
  • NONE – No buildup.

  • POW – Power function.

  • EXP – Exponential function.

  • SAT – Saturation function.

  • EXT – External time series.

NONE = 0
POW = 1
EXP = 2
SAT = 3
EXT = 4
class ConcentrationUnits(*values)

Bases: IntEnum

Pollutant concentration units.

Variables:
  • MG_PER_L – Milligrams per liter.

  • UG_PER_L – Micrograms per liter.

  • COUNT_PER_L – Counts per liter.

MG_PER_L = 0
UG_PER_L = 1
COUNT_PER_L = 2
class EngineState(*values)

Bases: IntEnum

Engine lifecycle states.

Values match the C++ internal openswmm::EngineState enum (which is what swmm_engine_get_state actually returns).

Variables:
  • CREATED – Context allocated, no input loaded.

  • OPENED – Input file parsed, objects allocated.

  • INITIALIZED – Initial conditions applied.

  • RUNNING – Simulation loop in progress.

  • PAUSED – Simulation paused (future hot-swap support).

  • ENDED – Simulation loop completed.

  • REPORTED – Summary report written.

  • CLOSED – Resources released.

  • ERROR_STATE – Fatal error.

  • BUILDING – Programmatic model construction in progress (no .inp).

CREATED = 0
OPENED = 1
INITIALIZED = 2
RUNNING = 3
PAUSED = 4
ENDED = 5
REPORTED = 6
CLOSED = 7
ERROR_STATE = 8
BUILDING = 9
class ErrorCode(*values)

Bases: IntEnum

SWMM C API return codes.

Mirrors the integer error codes returned by every C API entry point in openswmm_engine.h.

Variables:
  • OK – Success (0).

  • NOMEM – Out of memory.

  • INPFILE – Cannot open input file.

  • RPTFILE – Cannot open report file.

  • OUTFILE – Cannot open output file.

  • PARSE – Input file parse error.

  • LIFECYCLE – Function called in wrong lifecycle state.

  • BADHANDLE – NULL or invalid engine handle.

  • BADINDEX – Object index out of range.

  • BADPARAM – Invalid parameter value.

  • PLUGIN – Plugin error.

  • IO – I/O error.

  • HOTSTART – Hot start file error.

  • CRS – Coordinate reference system error.

  • NUMERICAL – Numerical error.

  • INTERNAL – Internal error.

OK = 0
NOMEM = 1
INPFILE = 2
RPTFILE = 3
OUTFILE = 4
PARSE = 5
LIFECYCLE = 6
BADHANDLE = 7
BADINDEX = 8
BADPARAM = 9
PLUGIN = 10
IO = 11
HOTSTART = 12
CRS = 13
NUMERICAL = 14
INTERNAL = 99
class FlowUnits(*values)

Bases: IntEnum

Flow unit systems.

Variables:
  • CFS – Cubic feet per second (US customary).

  • GPM – Gallons per minute (US customary).

  • MGD – Million gallons per day (US customary).

  • CMS – Cubic meters per second (SI).

  • LPS – Liters per second (SI).

  • MLD – Million liters per day (SI).

CFS = 0
GPM = 1
MGD = 2
CMS = 3
LPS = 4
MLD = 5
class ForcingMode(*values)

Bases: IntEnum

Forcing application mode.

Determines how a forced value is combined with the model-computed value.

Variables:
  • REPLACE – Replace the computed value entirely.

  • ADD – Add the forced value to the computed value.

REPLACE = 0
ADD = 1
class ForcingTarget(*values)

Bases: IntEnum

Object type codes used with openswmm.engine.Forcing.clear.

Variables:
  • NODE – Node forcing target.

  • LINK – Link forcing target.

  • SUBCATCH – Subcatchment forcing target.

  • GAGE – Rain gage forcing target.

NODE = 0
LINK = 1
SUBCATCH = 2
GAGE = 3
class GageDataSource(*values)

Bases: IntEnum

Rain gage data source type.

Variables:
  • TIMESERIES – Data comes from a time series object.

  • FILE – Data comes from an external rainfall file.

TIMESERIES = 0
FILE = 1
class GageRainType(*values)

Bases: IntEnum

Rain gage rainfall data format.

Variables:
  • INTENSITY – Rainfall intensity (depth/time).

  • VOLUME – Rainfall volume (depth per interval).

  • CUMULATIVE – Cumulative rainfall depth.

INTENSITY = 0
VOLUME = 1
CUMULATIVE = 2
class InfilModel(*values)

Bases: IntEnum

Infiltration model type.

Variables:
  • HORTON – Original Horton model.

  • MOD_HORTON – Modified Horton model.

  • GREEN_AMPT – Green-Ampt model.

  • MOD_GREEN_AMPT – Modified Green-Ampt model.

  • CURVE_NUMBER – SCS Curve Number model.

HORTON = 0
MOD_HORTON = 1
GREEN_AMPT = 2
MOD_GREEN_AMPT = 3
CURVE_NUMBER = 4
class LidType(*values)

Bases: IntEnum

Low Impact Development (LID) control type.

Variables:
  • BIO_CELL – Bioretention cell.

  • RAIN_GARDEN – Rain garden.

  • GREEN_ROOF – Green roof.

  • INFIL_TRENCH – Infiltration trench.

  • PERM_PAVEMENT – Permeable pavement.

  • RAIN_BARREL – Rain barrel.

  • ROOFTOP_DISCONN – Rooftop disconnection.

  • VEGETATIVE_SWALE – Vegetative swale.

BIO_CELL = 0
RAIN_GARDEN = 1
GREEN_ROOF = 2
INFIL_TRENCH = 3
PERM_PAVEMENT = 4
RAIN_BARREL = 5
ROOFTOP_DISCONN = 6
VEGETATIVE_SWALE = 7
class LinkType(*values)

Bases: IntEnum

Link type codes for openswmm.engine.ModelBuilder.add_link.

Variables:
  • CONDUIT – Conduit (pipe or channel).

  • PUMP – Pump.

  • ORIFICE – Orifice.

  • WEIR – Weir.

  • OUTLET – Outlet.

CONDUIT = 0
PUMP = 1
ORIFICE = 2
WEIR = 3
OUTLET = 4
class NodeType(*values)

Bases: IntEnum

Node type codes for openswmm.engine.ModelBuilder.add_node.

Variables:
  • JUNCTION – Junction node.

  • OUTFALL – Outfall node.

  • STORAGE – Storage unit.

  • DIVIDER – Flow divider.

JUNCTION = 0
OUTFALL = 1
STORAGE = 2
DIVIDER = 3
class ObjectType(*values)

Bases: IntEnum

SWMM object type codes.

Variables:
  • GAGE – Rain gage.

  • SUBCATCH – Subcatchment.

  • NODE – Node (junction, outfall, storage, divider).

  • LINK – Link (conduit, pump, orifice, weir, outlet).

  • POLLUT – Pollutant.

  • LANDUSE – Land use category.

  • TIMESER – Time series.

  • TABLE – Curve / table.

  • RDII – RDII unit hydrograph group.

  • UNITHYD – Unit hydrograph.

  • SNOWMELT – Snowmelt parameter set.

  • SHAPE – Custom cross-section shape.

  • LID – LID control.

GAGE = 0
SUBCATCH = 1
NODE = 2
LINK = 3
POLLUT = 4
LANDUSE = 5
TIMESER = 6
TABLE = 7
RDII = 8
UNITHYD = 9
SNOWMELT = 10
SHAPE = 11
LID = 12
class OutLinkVar(*values)

Bases: IntEnum

Link output result variable indices.

Variables:
  • FLOW – Flow rate.

  • DEPTH – Water depth.

  • VELOCITY – Flow velocity.

  • VOLUME – Stored volume.

  • CAPACITY – Capacity fraction (flow / full flow).

  • POLLUT_BASE – Base index for pollutant concentrations.

FLOW = 0
DEPTH = 1
VELOCITY = 2
VOLUME = 3
CAPACITY = 4
POLLUT_BASE = 5
class OutNodeVar(*values)

Bases: IntEnum

Node output result variable indices.

Variables:
  • DEPTH – Water depth.

  • HEAD – Hydraulic head.

  • VOLUME – Stored volume.

  • LATERAL_INFLOW – Lateral inflow rate.

  • TOTAL_INFLOW – Total inflow rate.

  • OVERFLOW – Overflow / flooding rate.

  • POLLUT_BASE – Base index for pollutant concentrations.

DEPTH = 0
HEAD = 1
VOLUME = 2
LATERAL_INFLOW = 3
TOTAL_INFLOW = 4
OVERFLOW = 5
POLLUT_BASE = 6
class OutSubcatchVar(*values)

Bases: IntEnum

Subcatchment output result variable indices.

Variables:
  • RAINFALL – Rainfall rate.

  • SNOW_DEPTH – Snow depth.

  • EVAP – Evaporation rate.

  • INFIL – Infiltration rate.

  • RUNOFF – Runoff rate.

  • GW_FLOW – Groundwater outflow rate.

  • GW_ELEV – Groundwater table elevation.

  • SOIL_MOIST – Soil moisture fraction.

  • POLLUT_BASE – Base index for pollutant concentrations.

RAINFALL = 0
SNOW_DEPTH = 1
EVAP = 2
INFIL = 3
RUNOFF = 4
GW_FLOW = 5
GW_ELEV = 6
SOIL_MOIST = 7
POLLUT_BASE = 8
class OutSystemVar(*values)

Bases: IntEnum

System-wide output result variable indices.

Variables:
  • TEMPERATURE – Air temperature.

  • RAINFALL – System-wide rainfall rate.

  • SNOW_DEPTH – Average snow depth.

  • EVAP – System-wide evaporation rate.

  • INFIL – System-wide infiltration rate.

  • RUNOFF – System-wide runoff rate.

  • DW_INFLOW – Dry-weather inflow rate.

  • GW_INFLOW – Groundwater inflow rate.

  • LAT_INFLOW – Total lateral inflow rate.

  • FLOODING – Total flooding rate.

  • OUTFLOW – Total outfall outflow rate.

  • STORAGE – Total network storage volume.

  • EVAP_TOTAL – Actual evaporation rate.

  • PET – Potential evapotranspiration rate.

TEMPERATURE = 0
RAINFALL = 1
SNOW_DEPTH = 2
EVAP = 3
INFIL = 4
RUNOFF = 5
DW_INFLOW = 6
GW_INFLOW = 7
LAT_INFLOW = 8
FLOODING = 9
OUTFLOW = 10
STORAGE = 11
EVAP_TOTAL = 12
PET = 13
class OutfallType(*values)

Bases: IntEnum

Outfall boundary condition type.

Variables:
  • FREE – Free outfall.

  • NORMAL – Normal depth outfall.

  • FIXED – Fixed head outfall.

  • TIDAL – Tidal stage outfall.

  • TIMESERIES – Time-series stage outfall.

FREE = 0
NORMAL = 1
FIXED = 2
TIDAL = 3
TIMESERIES = 4
class PatternType(*values)

Bases: IntEnum

Time pattern type.

Variables:
  • MONTHLY – Monthly variation pattern.

  • DAILY – Daily variation pattern.

  • HOURLY – Hourly variation pattern.

  • WEEKEND – Weekend hourly variation pattern.

MONTHLY = 0
DAILY = 1
HOURLY = 2
WEEKEND = 3
class RouteModel(*values)

Bases: IntEnum

Hydraulic routing models.

Variables:
  • STEADY – Steady-state routing.

  • KINWAVE – Kinematic wave routing.

  • DYNWAVE – Dynamic wave (full Saint-Venant) routing.

STEADY = 0
KINWAVE = 1
DYNWAVE = 2
class RoutingTotal(*values)

Bases: IntEnum

Routing mass balance component codes.

Variables:
  • DRY_WEATHER – Dry-weather inflow.

  • WET_WEATHER – Wet-weather (runoff) inflow.

  • GW_INFLOW – Groundwater inflow.

  • RDII – RDII inflow.

  • EXTERNAL – External inflow.

  • FLOODING – Flooding loss.

  • OUTFLOW – Outfall outflow.

  • EVAP_LOSS – Evaporation loss.

  • SEEP_LOSS – Seepage loss.

  • INIT_STORAGE – Initial network storage.

  • FINAL_STORAGE – Final network storage.

DRY_WEATHER = 0
WET_WEATHER = 1
GW_INFLOW = 2
RDII = 3
EXTERNAL = 4
FLOODING = 5
OUTFLOW = 6
EVAP_LOSS = 7
SEEP_LOSS = 8
INIT_STORAGE = 9
FINAL_STORAGE = 10
class RunoffTotal(*values)

Bases: IntEnum

Runoff mass balance component codes.

Variables:
  • RAINFALL – Total rainfall.

  • EVAP – Evaporation loss.

  • INFIL – Infiltration loss.

  • RUNOFF – Surface runoff.

  • SNOWREMOV – Snow removal.

  • INITSTORE – Initial surface storage.

  • FINALSTORE – Final surface storage.

RAINFALL = 0
EVAP = 1
INFIL = 2
RUNOFF = 3
SNOWREMOV = 4
INITSTORE = 5
FINALSTORE = 6
class WarnCode(*values)

Bases: IntEnum

Engine warning codes emitted via the warning callback.

Variables:
  • NONE – No warning.

  • HOTSTART_MISSING – Object missing during hot start application.

  • UNKNOWN_SECTION – Unrecognised input section encountered.

  • UNKNOWN_OPTION – Unrecognised option keyword.

  • DEPRECATED_KW – Deprecated keyword used.

  • PLUGIN_INIT – Plugin initialisation issue.

  • NUMERICAL – Numerical instability handled gracefully.

  • STABILITY_LIMIT – Timestep limited by stability criterion.

NONE = 0
HOTSTART_MISSING = 1
UNKNOWN_SECTION = 2
UNKNOWN_OPTION = 3
DEPRECATED_KW = 4
PLUGIN_INIT = 5
NUMERICAL = 6
STABILITY_LIMIT = 7
class WashoffFunc(*values)

Bases: IntEnum

Pollutant washoff function type.

Variables:
  • NONE – No washoff.

  • EXP – Exponential washoff.

  • RC – Rating curve washoff.

  • EMC – Event mean concentration.

NONE = 0
EXP = 1
RC = 2
EMC = 3
class XSectShape(*values)

Bases: IntEnum

Cross-section shape codes.

Variables:
  • CIRCULAR – Circular pipe.

  • FILLED_CIRCULAR – Filled circular pipe.

  • RECT_CLOSED – Closed rectangular.

  • RECT_OPEN – Open rectangular.

  • TRAPEZOIDAL – Trapezoidal channel.

  • TRIANGULAR – Triangular channel.

  • PARABOLIC – Parabolic channel.

  • POWER – Power-law shaped channel.

  • MODBASKETHANDLE – Modified baskethandle.

  • EGGSHAPED – Egg-shaped pipe.

  • HORSESHOE – Horseshoe-shaped pipe.

  • GOTHIC – Gothic arch pipe.

  • CATENARY – Catenary-shaped pipe.

  • SEMIELLIPTICAL – Semi-elliptical pipe.

  • BASKETHANDLE – Baskethandle-shaped pipe.

  • SEMICIRCULAR – Semi-circular pipe.

  • IRREGULAR – Irregular (from transect data).

  • CUSTOM – Custom shape (from shape curve).

  • FORCE_MAIN – Force main (pressurized).

CIRCULAR = 0
FILLED_CIRCULAR = 1
RECT_CLOSED = 2
RECT_OPEN = 3
TRAPEZOIDAL = 4
TRIANGULAR = 5
PARABOLIC = 6
POWER = 7
MODBASKETHANDLE = 8
EGGSHAPED = 9
HORSESHOE = 10
GOTHIC = 11
CATENARY = 12
SEMIELLIPTICAL = 13
BASKETHANDLE = 14
SEMICIRCULAR = 15
IRREGULAR = 16
CUSTOM = 17
FORCE_MAIN = 18

Optional modules#

These extensions are only built when the matching CMake flag is enabled on the parent C/C++ engine. They expose HAS_* flags at runtime so client code can degrade gracefully.

GeoPackage I/O (OPENSWMM_WITH_GEOPACKAGE=ON)#

GeoPackage Access#
author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._geopackage.

The GeoPackage class provides read/write access to SWMM GeoPackage databases for querying multi-run simulation results, importing observed data, and performing spatial analysis.

This module is optional - it is only available when the package is built with OPENSWMM_WITH_GEOPACKAGE=ON.

class GeoPackage(path)#

Bases: object

GeoPackage database access for SWMM models, results, and observed data.

Wraps the swmm_gpkg_* entry points of the OpenSWMM GeoPackage plugin. Supports the context-manager protocol for automatic resource cleanup.

Example:

from openswmm.engine import GeoPackage

with GeoPackage("model.gpkg") as gpkg:
    sims = gpkg.simulation_ids()
    times, depths = gpkg.read_result_ts(
        sims[0], "NODE", "J1", "depth")
Variables:

last_error – The most recent error message reported by the underlying GeoPackage library.

Parameters:

path (str)

Open a GeoPackage file.

Parameters:

path (str) – Path to the .gpkg file.

Raises:

RuntimeError – If the file cannot be opened.

__init__(path)#

Open a GeoPackage file.

Parameters:

path (str) – Path to the .gpkg file.

Raises:

RuntimeError – If the file cannot be opened.

Return type:

None

begin()#

Begin a transaction for bulk operations.

Raises:

RuntimeError – If the transaction cannot be started.

Return type:

None

close()#

Close the database connection.

Calling close more than once is harmless.

Return type:

None

commit()#

Commit the current transaction.

Raises:

RuntimeError – If the commit fails.

Return type:

None

create_observed_series(name, variable, obj_type='', obj_id='', source='', units='')#

Create an observed-data series.

Parameters:
  • name (str) – Unique series name.

  • variable (str) – Variable being measured.

  • obj_type (str) – Model object type for linking, or "" for none.

  • obj_id (str) – Model object ID for linking, or "" for none.

  • source (str) – Data source description, or "" for none.

  • units (str) – Measurement units, or "" for none.

Returns:

Series ID (M{>= 0}).

Return type:

int

Raises:

RuntimeError – If the series cannot be created.

property last_error: str#

The last error message from the GeoPackage library.

Returns:

Error message string, or "" if no error has been reported.

Return type:

str

object_counts(sim_id)#

Return model object counts for a simulation.

Parameters:

sim_id (str) – Simulation identifier.

Returns:

Dict with keys "nodes", "links", "subcatchments", and "gages".

Return type:

dict

observed_series_count()#

Return the number of observed-data series.

Returns:

Observed-series count.

Return type:

int

observed_value_count(series_id)#

Return the number of values in an observed series.

Parameters:

series_id (int) – Series ID.

Returns:

Value count.

Return type:

int

query_double(sql)#

Execute a read-only SQL query and return the first double result.

Parameters:

sql (str) – SELECT query string.

Returns:

Double-precision result of the query.

Return type:

float

Raises:

RuntimeError – If the query fails.

query_int(sql)#

Execute a read-only SQL query and return the first integer result.

Parameters:

sql (str) – SELECT query string.

Returns:

Integer result of the query.

Return type:

int

read_observed_values(series_id)#

Read observed-timeseries values.

Parameters:

series_id (int) – Series ID.

Returns:

Tuple (timestamps, values) where timestamps is a list of ISO 8601 strings and values is a NumPy float64 array.

Return type:

Tuple[List[str], np.ndarray]

read_result_ts(sim_id, obj_type, obj_id, variable)#

Read a result timeseries as NumPy arrays.

Parameters:
  • sim_id (str) – Simulation identifier.

  • obj_type (str) – One of "NODE", "LINK", "SUBCATCH", or "SYSTEM".

  • obj_id (str) – Object identifier.

  • variable (str) – Variable name.

Returns:

Tuple (times, values) as NumPy float64 arrays.

Return type:

Tuple[np.ndarray, np.ndarray]

@see: L{result_ts_count}

read_summary(sim_id, obj_type, obj_id, variable)#

Read a single summary statistic value.

Parameters:
  • sim_id (str) – Simulation identifier.

  • obj_type (str) – One of "NODE", "LINK", or "SUBCATCH".

  • obj_id (str) – Object identifier.

  • variable (str) – Variable name (e.g. "max_depth").

Returns:

Statistic value.

Return type:

float

Raises:

KeyError – If the summary record is not found.

result_ts_count(sim_id, obj_type, obj_id, variable)#

Return the number of result timeseries records for a query.

Parameters:
  • sim_id (str) – Simulation identifier.

  • obj_type (str) – One of "NODE", "LINK", "SUBCATCH", or "SYSTEM".

  • obj_id (str) – Object identifier (e.g. "J1").

  • variable (str) – Variable name (e.g. "depth", "flow").

Returns:

Record count.

Return type:

int

rollback()#

Roll back the current transaction.

Raises:

RuntimeError – If the rollback fails.

Return type:

None

simulation_count()#

Return the number of simulation runs in the file.

Returns:

Simulation count.

Return type:

int

simulation_ids()#

Return all simulation IDs as a list of strings.

Returns:

List of simulation identifier strings.

Return type:

List[str]

topology_edge_count(sim_id)#

Return the number of topology edges for a simulation.

Parameters:

sim_id (str) – Simulation identifier.

Returns:

Topology edge count.

Return type:

int

variable_count()#

Return the number of output variables defined.

Returns:

Variable count.

Return type:

int

write_observed_value(series_id, timestamp, value, flag='')#

Write a single observed data point.

Parameters:
  • series_id (int) – Series ID returned by create_observed_series.

  • timestamp (str) – ISO 8601 timestamp string.

  • value (float) – Measured value.

  • flag (str) – Quality flag (e.g. "A", "P"), or "" for none.

Raises:

RuntimeError – If the write fails.

Return type:

None

write_observed_values(series_id, timestamps, values, flags=None)#

Bulk-write observed data points.

For best performance wrap the call in a transaction:

gpkg.begin()
gpkg.write_observed_values(sid, timestamps, values)
gpkg.commit()
Parameters:
  • series_id (int) – Series ID.

  • timestamps (List[str]) – List of ISO 8601 timestamp strings.

  • values (npt.ArrayLike) – List or NumPy array of values.

  • flags (Optional[List[str]]) – Optional list of quality-flag strings, one per timestamp.

Raises:
Return type:

None

is_registered()#

Check whether the GeoPackage plugin is registered.

Returns:

True if registered.

Return type:

bool

register(key='', org='', email='', deploy='')#

Register the GeoPackage plugin.

Parameters:
  • key (str) – License key, or "" if not required.

  • org (str) – Organisation name, or "".

  • email (str) – Contact e-mail, or "".

  • deploy (str) – Deployment identifier, or "".

Returns:

True if registration succeeded.

Return type:

bool

2-D surface routing (OPENSWMM_BUILD_2D=ON)#

2D Surface Routing#
author:

Caleb Buahin

copyright:

Copyright (c) 2026 Caleb Buahin

license:

MIT

Type stubs for openswmm.engine._2d.

The Surface2D class provides read/write access to the optional 2D surface routing module (requires OPENSWMM_BUILD_2D=ON and SUNDIALS).

class Surface2D(engine_ptr)#

Bases: object

Read/write interface to the optional 2D surface routing module.

The module solves the depth-averaged shallow-water equations on an unstructured triangular mesh and is integrated in time with CVODE from SUNDIALS. Two-way coupling with the 1D drainage network is supported per-vertex and per-triangle.

Example:

from openswmm.engine import Solver
from openswmm.engine._2d import Surface2D

with Solver("model.inp", "model.rpt", "model.out") as s:
    mesh = Surface2D(s.handle)
    if mesh.is_active:
        depths = mesh.get_depths()
Variables:

_engine – Internal pointer to the underlying C{SWMM_Engine} handle (managed by the Cython extension).

Parameters:

engine_ptr (int)

Construct a Surface2D accessor from a raw engine handle.

Parameters:

engine_ptr (int) – The raw engine handle (SWMM_Engine cast to an integer via solver.handle).

__init__(engine_ptr)#

Construct a Surface2D accessor from a raw engine handle.

Parameters:

engine_ptr (int) – The raw engine handle (SWMM_Engine cast to an integer via solver.handle).

Return type:

None

property abs_tolerance: float#

CVODE absolute tolerance.

Returns:

Absolute tolerance.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

property boundary_edge_count: int#

Number of boundary edges in the 2D mesh.

Returns:

Boundary edge count.

Return type:

int

Raises:

RuntimeError – If the C API call fails.

property cvode_last_step: float#

Last CVODE internal step size.

Returns:

Step size.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

property cvode_steps: int#

Number of CVODE internal steps in the last advance.

Returns:

Step count.

Return type:

int

Raises:

RuntimeError – If the C API call fails.

property dry_depth: float#

Dry-depth threshold (m); triangles below this are treated as dry.

Returns:

Threshold depth.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

force_clear_all()#

Clear all 2D forcings.

Raises:

RuntimeError – If the C API call fails.

Return type:

None

force_coupling_flux(idx, value, mode=1, persist=0)#

Force a coupling flux on a specific triangle.

Parameters:
  • idx (int) – Triangle index.

  • value (float) – Coupling flux value.

  • mode (int) – Forcing mode (1 = ADD, 0 = REPLACE).

  • persist (int) – 1 to hold until cleared; 0 for single-step.

Raises:

RuntimeError – If the C API rejects the forcing.

Return type:

None

force_rainfall(idx, value, mode=1, persist=0)#

Force rainfall on a specific triangle.

Parameters:
  • idx (int) – Triangle index.

  • value (float) – Rainfall rate.

  • mode (int) – Forcing mode (1 = ADD, 0 = REPLACE).

  • persist (int) – 1 to hold until cleared; 0 for single-step.

Raises:

RuntimeError – If the C API rejects the forcing.

Return type:

None

force_rainfall_uniform(value, mode=1, persist=0)#

Force uniform rainfall on all triangles.

Parameters:
  • value (float) – Rainfall rate.

  • mode (int) – Forcing mode (1 = ADD, 0 = REPLACE).

  • persist (int) – 1 to hold until cleared; 0 for single-step.

Raises:

RuntimeError – If the C API rejects the forcing.

Return type:

None

get_coupling_flux(idx)#

Return the coupling flux at a specific triangle.

Parameters:

idx (int) – Triangle index.

Returns:

Coupling flux value (positive = into 2D surface).

Return type:

float

Raises:

RuntimeError – If the C API call fails.

get_coupling_fluxes()#

Return coupling fluxes for all triangles as a NumPy array.

Returns:

Array of shape (n_triangles,) with dtype float64. Positive values denote flux into the 2D surface.

Return type:

np.ndarray

Raises:

RuntimeError – If the C API call fails.

get_depth(idx)#

Return the water depth at a specific triangle.

Parameters:

idx (int) – Triangle index.

Returns:

Water depth.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

get_depths()#

Return depths for all triangles as a NumPy array.

Returns:

Array of shape (n_triangles,) with dtype float64.

Return type:

np.ndarray

Raises:

RuntimeError – If the C API call fails.

get_edge_bc_cum_flux(tri_idx, edge)#

Return the cumulative boundary flux for a triangle edge.

Parameters:
  • tri_idx (int) – Triangle index.

  • edge (int) – Edge index in 0-2.

Returns:

Cumulative boundary flux through the edge.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

get_edge_bc_head(tri_idx, edge)#

Return the boundary head for a triangle edge.

Parameters:
  • tri_idx (int) – Triangle index.

  • edge (int) – Edge index in 0-2.

Returns:

Boundary head value.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

get_edge_bc_slope(tri_idx, edge)#

Return the boundary slope for a triangle edge.

Parameters:
  • tri_idx (int) – Triangle index.

  • edge (int) – Edge index in 0-2.

Returns:

Boundary slope.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

get_edge_bc_type(tri_idx, edge)#

Return the boundary condition type for a triangle edge.

Parameters:
  • tri_idx (int) – Triangle index.

  • edge (int) – Edge index in 0-2.

Returns:

Boundary condition type code.

Return type:

int

Raises:

RuntimeError – If the C API call fails.

get_edge_flux_bulk()#

Return normal edge fluxes for all triangle edges.

Indexed as [tri*3 + localEdge].

Returns:

Array of shape (n_triangles*3,) with dtype float64.

Return type:

ndarray[Any, dtype[float64]]

get_edge_geometry_bulk()#

Return time-invariant edge lengths and outward unit normal components.

Returns (length, nx, ny), each indexed as [tri*3 + localEdge].

Returns:

Tuple (length, nx, ny), each of shape (n_triangles*3,).

Return type:

tuple[ndarray[Any, dtype[float64]], ndarray[Any, dtype[float64]], ndarray[Any, dtype[float64]]]

get_head(idx)#

Return the total head at a specific triangle.

Parameters:

idx (int) – Triangle index.

Returns:

Total head.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

get_heads()#

Return total heads for all triangles as a NumPy array.

Returns:

Array of shape (n_triangles,) with dtype float64.

Return type:

np.ndarray

Raises:

RuntimeError – If the C API call fails.

get_net_source(idx)#

Return the net source term at a specific triangle.

Parameters:

idx (int) – Triangle index.

Returns:

Net source term.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

get_rainfall(idx)#

Return the current rainfall at a specific triangle.

Parameters:

idx (int) – Triangle index.

Returns:

Rainfall rate.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

get_stat_max_depths()#

Return cumulative maximum-depth statistics for all triangles.

Returns:

Array of shape (n_triangles,) with dtype float64.

Return type:

np.ndarray

Raises:

RuntimeError – If the C API call fails.

get_triangle_area(idx)#

Return the area of a triangle.

Parameters:

idx (int) – Triangle index.

Returns:

Triangle area in project units squared.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

get_triangle_centroid(idx)#

Return the (cx, cy, cz) centroid coordinates for a triangle.

Parameters:

idx (int) – Triangle index.

Returns:

Tuple (cx, cy, cz) centroid coordinates.

Return type:

tuple[float, float, float]

Raises:

RuntimeError – If the C API call fails.

get_triangle_coupled_node(tri_idx)#

Return the SWMM node index coupled to a triangle.

Parameters:

tri_idx (int) – Triangle index.

Returns:

Node index, or -1 if no coupling exists.

Return type:

int

Raises:

RuntimeError – If the C API call fails.

get_triangle_mannings(idx)#

Return Manning’s M{n} for a triangle.

Parameters:

idx (int) – Triangle index.

Returns:

Manning’s M{n} roughness.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

get_triangle_neighbours(idx)#

Return the (n0, n1, n2) neighbour triangle indices.

Parameters:

idx (int) – Triangle index.

Returns:

Tuple of three neighbour triangle indices; C{-1} indicates a boundary edge.

Return type:

tuple[int, int, int]

Raises:

RuntimeError – If the C API call fails.

get_triangle_vertices(idx)#

Return the (v0, v1, v2) vertex indices for a triangle.

Parameters:

idx (int) – Triangle index.

Returns:

Tuple of three vertex indices.

Return type:

tuple[int, int, int]

Raises:

RuntimeError – If the C API call fails.

get_vertex_coords()#

Return (x, y, z) NumPy arrays for all vertices.

Returns:

Tuple (x, y, z), each of shape (n_vertices,) with dtype float64.

Return type:

tuple[np.ndarray, np.ndarray, np.ndarray]

Raises:

RuntimeError – If the C API call fails.

get_vertex_coupled_node(vertex_idx)#

Return the SWMM node index coupled to a vertex.

Parameters:

vertex_idx (int) – Vertex index.

Returns:

Node index, or -1 if no coupling exists.

Return type:

int

Raises:

RuntimeError – If the C API call fails.

get_vertex_heads()#

Return reconstructed heads at all vertices as a NumPy array.

Returns:

Array of shape (n_vertices,) with dtype float64.

Return type:

np.ndarray

Raises:

RuntimeError – If the C API call fails.

property is_active: bool#

True if the 2D module is active for this simulation.

Returns:

Activation flag.

Return type:

bool

Raises:

RuntimeError – If the C API call fails.

property max_depth: float#

Maximum depth across all triangles.

Returns:

Maximum depth.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

property n_triangles: int#

Number of mesh triangles.

Returns:

Triangle count.

Return type:

int

Raises:

RuntimeError – If the C API call fails.

property n_vertices: int#

Number of mesh vertices.

Returns:

Vertex count.

Return type:

int

Raises:

RuntimeError – If the C API call fails.

property rel_tolerance: float#

CVODE relative tolerance.

Returns:

Relative tolerance.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

set_edge_bc_head(tri_idx, edge, head)#

Set the boundary head for a triangle edge.

Parameters:
  • tri_idx (int) – Triangle index.

  • edge (int) – Edge index in 0-2.

  • head (float) – Boundary head value.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

set_edge_bc_slope(tri_idx, edge, slope)#

Set the boundary slope for a triangle edge.

Parameters:
  • tri_idx (int) – Triangle index.

  • edge (int) – Edge index in 0-2.

  • slope (float) – Boundary slope.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

set_edge_bc_type(tri_idx, edge, bc_type)#

Set the boundary condition type for a triangle edge.

Parameters:
  • tri_idx (int) – Triangle index.

  • edge (int) – Edge index in 0-2.

  • bc_type (int) – Boundary condition type code.

Raises:

RuntimeError – If the C API rejects the assignment.

Return type:

None

property total_exchange_flow: float#

Total exchange flow rate.

Returns:

Exchange flow rate in m^3/s (positive = into 1D network).

Return type:

float

Raises:

RuntimeError – If the C API call fails.

property total_volume: float#

Total 2D surface volume (sum of M{depth x area}).

Returns:

Total volume.

Return type:

float

Raises:

RuntimeError – If the C API call fails.

property triangle_coupling_count: int#

Number of triangle-to-node coupling points.

Returns:

Coupling count.

Return type:

int

Raises:

RuntimeError – If the C API call fails.

property vertex_coupling_count: int#

Number of vertex-to-node coupling points.

Returns:

Coupling count.

Return type:

int

Raises:

RuntimeError – If the C API call fails.

Legacy SWMM 5 — compatibility layer#

The openswmm.legacy.engine and openswmm.legacy.output subpackages preserve the original EPA SWMM 5.x C solver and binary-output reader verbatim for backward compatibility with existing scripts. No new development happens here; new projects should prefer openswmm.engine (above).

See also

Legacy SWMM 5 — Compatibility Layer — task-oriented guide for the legacy layer.

Migrating from SWMM 5 to v6 — translating legacy patterns to the OpenSWMM 6 API.

openswmm.legacy.engine — SWMM 5.x solver#

openswmm.legacy.engine#

Legacy EPA SWMM 5.x solver bindings (Cython).

This subpackage provides the Solver class for running SWMM simulations, enumeration types for object/property access, and utility functions for date encoding and version queries.

class SWMMObjects(*values)#

Bases: Enum

Enumeration of SWMM objects.

Variables:
  • RAIN_GAGE – Raingage object

  • SUBCATCHMENT – Subcatchment object

  • NODE – Node object

  • LINK – Link object

  • AQUIFER – Aquifer object

  • SNOWPACK – Snowpack object

  • UNIT_HYDROGRAPH – Unit hydrograph object

  • LID – LID object

  • STREET – Street object

  • INLET – Inlet object

  • TRANSECT – Transect object

  • XSECTION_SHAPE – Cross-section shape object

  • CONTROL_RULE – Control rule object

  • POLLUTANT – Pollutant object

  • LANDUSE – Land use object

  • CURVE – Curve object

  • TIMESERIES – Time series object

  • TIME_PATTERN – Time pattern object

  • SYSTEM – System object

RAIN_GAGE = Ellipsis#
SUBCATCHMENT = Ellipsis#
NODE = Ellipsis#
AQUIFER = Ellipsis#
SNOWPACK = Ellipsis#
UNIT_HYDROGRAPH = Ellipsis#
LID = Ellipsis#
STREET = Ellipsis#
INLET = Ellipsis#
TRANSECT = Ellipsis#
XSECTION_SHAPE = Ellipsis#
CONTROL_RULE = Ellipsis#
POLLUTANT = Ellipsis#
LANDUSE = Ellipsis#
CURVE = Ellipsis#
TIMESERIES = Ellipsis#
TIME_PATTERN = Ellipsis#
SYSTEM = Ellipsis#
class SWMMNodeTypes(*values)#

Bases: Enum

Enumeration of SWMM node types.

Variables:
  • JUNCTION – Junction node

  • OUTFALL – Outfall node

  • STORAGE – Storage node

  • DIVIDER – Divider node

JUNCTION = Ellipsis#
OUTFALL = Ellipsis#
STORAGE = Ellipsis#
DIVIDER = Ellipsis#
class SWMMLinkTypes(*values)#

Bases: Enum

Enumeration of SWMM link types.

Variables:
  • CONDUIT – Conduit link

  • PUMP – Pump link

  • ORIFICE – Orifice link

  • WEIR – Weir link

  • OUTLET – Outlet link

CONDUIT = Ellipsis#
PUMP = Ellipsis#
ORIFICE = Ellipsis#
WEIR = Ellipsis#
OUTLET = Ellipsis#
class SWMMRainGageProperties(*values)#

Bases: Enum

Enumeration of SWMM raingage properties.

Variables:
  • GAGE_TOTAL_PRECIPITATION – Total precipitation

  • GAGE_RAINFALL – Rainfall

  • GAGE_SNOWFALL – Snowfall

GAGE_TOTAL_PRECIPITATION = Ellipsis#
GAGE_RAINFALL = Ellipsis#
GAGE_SNOWFALL = Ellipsis#
class SWMMSubcatchmentProperties(*values)#

Bases: Enum

Enumeration of SWMM subcatchment properties.

Variables:
  • AREA – Area

  • RAINGAGE – Raingage

  • RAINFALL – Rainfall

  • EVAPORATION – Evaporation

  • INFILTRATION – Infiltration

  • RUNOFF – Runoff

  • REPORT_FLAG – Report flag

  • WIDTH – Width

  • SLOPE – Slope

  • CURB_LENGTH – Curb length

  • API_RAINFALL – API Rainfall

  • API_SNOWFALL – API Snowfall

  • POLLUTANT_BUILDUP – Pollutant buildup

  • EXTERNAL_POLLUTANT_BUILDUP – External pollutant buildup

  • POLLUTANT_RUNOFF_CONCENTRATION – Pollutant runoff concentration

  • POLLUTANT_PONDED_CONCENTRATION – Pollutant ponded concentration

  • POLLUTANT_TOTAL_LOAD – Pollutant total load

AREA = Ellipsis#
RAINGAGE = Ellipsis#
RAINFALL = Ellipsis#
EVAPORATION = Ellipsis#
INFILTRATION = Ellipsis#
RUNOFF = Ellipsis#
REPORT_FLAG = Ellipsis#
WIDTH = Ellipsis#
SLOPE = Ellipsis#
CURB_LENGTH = Ellipsis#
API_RAINFALL = Ellipsis#
API_SNOWFALL = Ellipsis#
POLLUTANT_BUILDUP = Ellipsis#
EXTERNAL_POLLUTANT_BUILDUP = Ellipsis#
POLLUTANT_RUNOFF_CONCENTRATION = Ellipsis#
POLLUTANT_PONDED_CONCENTRATION = Ellipsis#
POLLUTANT_TOTAL_LOAD = Ellipsis#
class SWMMNodeProperties(*values)#

Bases: Enum

Enumeration of SWMM node properties.

Variables:
  • TYPE – Node type

  • INVERT_ELEVATION – Invert elevation

  • MAX_DEPTH – Maximum depth

  • DEPTH – Depth

  • HYDRAULIC_HEAD – Hydraulic head

  • VOLUME – Volume

  • LATERAL_INFLOW – Lateral inflow

  • TOTAL_INFLOW – Total inflow

  • FLOODING – Flooding

  • REPORT_FLAG – Report flag

  • SURCHARGE_DEPTH – Surcharge depth

  • PONDING_AREA – Ponding area

  • INITIAL_DEPTH – Initial depth

  • POLLUTANT_CONCENTRATION – Pollutant concentration

  • POLLUTANT_LATERAL_MASS_FLUX – Pollutant lateral mass flux

TYPE = Ellipsis#
INVERT_ELEVATION = Ellipsis#
MAX_DEPTH = Ellipsis#
DEPTH = Ellipsis#
HYDRAULIC_HEAD = Ellipsis#
VOLUME = Ellipsis#
LATERAL_INFLOW = Ellipsis#
TOTAL_INFLOW = Ellipsis#
FLOODING = Ellipsis#
REPORT_FLAG = Ellipsis#
SURCHARGE_DEPTH = Ellipsis#
PONDING_AREA = Ellipsis#
INITIAL_DEPTH = Ellipsis#
POLLUTANT_CONCENTRATION = Ellipsis#
POLLUTANT_LATERAL_MASS_FLUX = Ellipsis#
class SWMMLinkProperties(*values)#

Bases: Enum

Enumeration of SWMM link properties.

Variables:
  • TYPE – Link type

  • START_NODE – Start node

  • END_NODE – End node

  • LENGTH – Length

  • SLOPE – Slope

  • FULL_DEPTH – Full depth

  • FULL_FLOW – Full flow

  • SETTING – Setting

  • TIME_OPEN – Time open

  • TIME_CLOSED – Time closed

  • FLOW – Flow

  • DEPTH – Depth

  • VELOCITY – Velocity

  • TOP_WIDTH – Top width

  • REPORT_FLAG – Report flag

  • START_NODE_OFFSET – Start node offset

  • END_NODE_OFFSET – End node offset

  • INITIAL_FLOW – Initial flow

  • FLOW_LIMIT – Flow limit

  • INLET_LOSS – Inlet loss

  • OUTLET_LOSS – Outlet loss

  • AVERAGE_LOSS – Average loss

  • SEEPAGE_RATE – Seepage rate

  • HAS_FLAPGATE – Has flapgate

  • POLLUTANT_CONCENTRATION – Pollutant concentration

  • POLLUTANT_LOAD – Pollutant load

  • POLLUTANT_LATERAL_MASS_FLUX – Pollutant lateral mass flux

TYPE = Ellipsis#
START_NODE = Ellipsis#
END_NODE = Ellipsis#
LENGTH = Ellipsis#
SLOPE = Ellipsis#
FULL_DEPTH = Ellipsis#
FULL_FLOW = Ellipsis#
SETTING = Ellipsis#
TIME_OPEN = Ellipsis#
TIME_CLOSED = Ellipsis#
FLOW = Ellipsis#
DEPTH = Ellipsis#
VELOCITY = Ellipsis#
TOP_WIDTH = Ellipsis#
VOLUME = Ellipsis#
CAPACITY = Ellipsis#
REPORT_FLAG = Ellipsis#
START_NODE_OFFSET = Ellipsis#
END_NODE_OFFSET = Ellipsis#
INITIAL_FLOW = Ellipsis#
FLOW_LIMIT = Ellipsis#
INLET_LOSS = Ellipsis#
OUTLET_LOSS = Ellipsis#
AVERAGE_LOSS = Ellipsis#
SEEPAGE_RATE = Ellipsis#
HAS_FLAPGATE = Ellipsis#
POLLUTANT_CONCENTRATION = Ellipsis#
POLLUTANT_LOAD = Ellipsis#
POLLUTANT_LATERAL_MASS_FLUX = Ellipsis#
class SWMMSystemProperties(*values)#

Bases: Enum

Enumeration of SWMM system properties.

Variables:
  • START_DATE – Start date for the simulation

  • CURRENT_DATE – Current date for the simulation

  • ELAPSED_TIME – Elapsed time for the simulation

  • ROUTING_STEP – Routing time step

  • MAX_ROUTING_STEP – Maximum routing time step

  • REPORT_STEP – Report time step

  • TOTAL_STEPS – Total number of steps

  • NO_REPORT_FLAG – No report flag

  • FLOW_UNITS – Flow units

  • END_DATE – End date for the simulation

  • REPORT_START_DATE – Report start date

  • UNIT_SYSTEM – Unit system

  • SURCHARGE_METHOD – Surcharge method

  • ALLOW_PONDING – Allow ponding

  • INTERTIAL_DAMPING – Inertial damping

  • NORMAL_FLOW_LIMITED – Normal flow limited

  • SKIP_STEADY_STATE – Skip steady state

  • IGNORE_RAINFALL – Ignore rainfall

  • IGNORE_RDII – Ignore RDII

  • IGNORE_SNOWMELT – Ignore snowmelt

  • IGNORE_GROUNDWATER – Ignore groundwater

  • IGNORE_ROUTING – Ignore routing

  • IGNORE_QUALITY – Ignore quality

  • RULE_STEP – Rule step

  • SWEEP_START – Sweep start

  • SWEEP_END – Sweep end

  • MAX_TRIALS – Maximum trials

  • NUM_THREADS – Number of threads

  • MIN_ROUTE_STEP – Minimum routing step

  • LENGTHENING_STEP – Lengthening step

  • START_DRY_DAYS – Start dry days

  • COURANT_FACTOR – Courant factor

  • MIN_SURF_AREA – Minimum surface area

  • MIN_SLOPE – Minimum slope

  • RUNOFF_ERROR – Runoff error

  • FLOW_ERROR – Flow error

  • QUAL_ERROR – Quality error

  • HEAD_TOL – Head tolerance

  • SYS_FLOW_TOL – System flow tolerance

  • LAT_FLOW_TOL – Lateral flow tolerance

START_DATE = Ellipsis#
CURRENT_DATE = Ellipsis#
ELAPSED_TIME = Ellipsis#
ROUTING_STEP = Ellipsis#
MAX_ROUTING_STEP = Ellipsis#
REPORT_STEP = Ellipsis#
TOTAL_STEPS = Ellipsis#
NO_REPORT_FLAG = Ellipsis#
FLOW_UNITS = Ellipsis#
END_DATE = Ellipsis#
REPORT_START_DATE = Ellipsis#
UNIT_SYSTEM = Ellipsis#
SURCHARGE_METHOD = Ellipsis#
ALLOW_PONDING = Ellipsis#
INTERTIAL_DAMPING = Ellipsis#
NORMAL_FLOW_LIMITED = Ellipsis#
SKIP_STEADY_STATE = Ellipsis#
IGNORE_RAINFALL = Ellipsis#
IGNORE_RDII = Ellipsis#
IGNORE_SNOWMELT = Ellipsis#
IGNORE_GROUNDWATER = Ellipsis#
IGNORE_ROUTING = Ellipsis#
IGNORE_QUALITY = Ellipsis#
ERROR_CODE = Ellipsis#
RULE_STEP = Ellipsis#
SWEEP_START = Ellipsis#
SWEEP_END = Ellipsis#
MAX_TRIALS = Ellipsis#
NUM_THREADS = Ellipsis#
MIN_ROUTE_STEP = Ellipsis#
LENGTHENING_STEP = Ellipsis#
START_DRY_DAYS = Ellipsis#
COURANT_FACTOR = Ellipsis#
MIN_SURF_AREA = Ellipsis#
MIN_SLOPE = Ellipsis#
RUNOFF_ERROR = Ellipsis#
FLOW_ERROR = Ellipsis#
QUAL_ERROR = Ellipsis#
HEAD_TOL = Ellipsis#
SYS_FLOW_TOL = Ellipsis#
LAT_FLOW_TOL = Ellipsis#
class SWMMFlowUnits(*values)#

Bases: Enum

Enumeration of SWMM flow units.

Variables:
  • CFS – Cubic feet per second

  • GPM – Gallons per minute

  • MGD – Million gallons per day

  • CMS – Cubic meters per second

  • LPS – Liters per second

  • MLD – Million liters per day

CFS = Ellipsis#
GPM = Ellipsis#
MGD = Ellipsis#
CMS = Ellipsis#
LPS = Ellipsis#
MLD = Ellipsis#
class SWMMAPIErrors(*values)#

Bases: Enum

Enumeration of SWMM API errors.

Variables:
  • PROJECT_NOT_OPENED – Project not opened

  • SIMULATION_NOT_STARTED – Simulation not started

  • SIMULATION_NOT_ENDED – Simulation not ended

PROJECT_NOT_OPENED = Ellipsis#
SIMULATION_NOT_STARTED = Ellipsis#
SIMULATION_NOT_ENDED = Ellipsis#
OBJECT_TYPE = Ellipsis#
OBJECT_INDEX = Ellipsis#
OBJECT_NAME = Ellipsis#
PROPERTY_TYPE = Ellipsis#
PROPERTY_VALUE = Ellipsis#
TIME_PERIOD = Ellipsis#
HOTSTART_FILE_OPEN = Ellipsis#
HOTSTART_FILE_FORMAT = Ellipsis#
SIMULATION_IS_RUNNING = Ellipsis#
run_solver(inp_file, rpt_file=None, out_file=None, swmm_progress_callback=Ellipsis)#

Run a SWMM simulation with a progress callback.

Parameters:
  • inp_file (str) – Input file name

  • rpt_file (str) – Report file name

  • out_file (str) – Output file name

  • swmm_progress_callback (callable) – Progress callback function

Rtype inp_file:

str

Rtype rpt_file:

str

Rtype out_file:

str

Returns:

Error code from the underlying SWMM C API (0 on success, non-zero on failure). Callers should check the return value rather than relying on an exception.

Return type:

int

decode_swmm_datetime(swmm_datetime)#

Decode a SWMM datetime into a datetime object.

Parameters:

swmm_datetime (float) – SWMM datetime float value

Returns:

datetime object

Return type:

datetime

encode_swmm_datetime(dt)#

Encode a datetime object into a SWMM datetime float value.

Parameters:

dt (datetime) – datetime object

Returns:

SWMM datetime float value

Return type:

float

version()#

Get the SWMM version.

Returns:

SWMM version

Return type:

str

get_error_message(error_code)#

Get the error message for a SWMM error code.

Parameters:

error_code (int) – Error code

Returns:

Error message

Return type:

str

class SolverState(*values)#

Bases: Enum

An enumeration to represent the state of the solver.

CREATED = Ellipsis#
OPEN = Ellipsis#
STARTED = Ellipsis#
FINISHED = Ellipsis#
ENDED = Ellipsis#
REPORTED = Ellipsis#
CLOSED = Ellipsis#
class CallbackType(*values)#

Bases: Enum

An enumeration to represent the type of callback.

BEFORE_INITIALIZE = Ellipsis#
BEFORE_OPEN = Ellipsis#
AFTER_OPEN = Ellipsis#
BEFORE_START = Ellipsis#
AFTER_START = Ellipsis#
BEFORE_STEP = Ellipsis#
AFTER_STEP = Ellipsis#
BEFORE_END = Ellipsis#
AFTER_END = Ellipsis#
BEFORE_REPORT = Ellipsis#
AFTER_REPORT = Ellipsis#
BEFORE_CLOSE = Ellipsis#
AFTER_CLOSE = Ellipsis#
exception SWMMSolverException(message)#

Bases: Exception

Exception class for SWMM output file processing errors.

Constructor to initialize the exception message.

Parameters:

message (str) – Error message.

Return type:

None

__init__(message)#

Constructor to initialize the exception message.

Parameters:

message (str) – Error message.

Return type:

None

class Solver(inp_file, rpt_file=None, out_file=None, stride_step=300, save_results=True)#

Bases: object

Constructor to create a new SWMM solver.

Parameters:
  • inp_file (str) – Input file name

  • rpt_file (str) – Report file name

  • out_file (str) – Output file name

  • stride_step (int)

  • save_results (bool)

__init__(inp_file, rpt_file=None, out_file=None, stride_step=300, save_results=True)#

Constructor to create a new SWMM solver.

Parameters:
  • inp_file (str) – Input file name

  • rpt_file (str) – Report file name

  • out_file (str) – Output file name

  • stride_step (int)

  • save_results (bool)

add_callback(callback_type, callback)#

Add a callback to the solver.

Parameters:
  • callback_type (CallbackType) – Type of callback

  • callback (callable) – Callback function

Return type:

None

add_progress_callback(callback)#

Add a progress callback to the solver.

Parameters:

callback (callable) – Progress callback function

Return type:

None

close()#

Close the solver.

Returns:

Error code (0 on success or no-op, non-zero on failure; -1 if not in REPORTED state).

Return type:

int

property current_datetime: datetime#

Get the current date of the simulation.

Returns:

Current date

Return type:

datetime

end()#

End the SWMM simulation.

Returns:

Error code (0 on success or no-op, non-zero on failure; -1 if called from an invalid solver state).

Return type:

int

property end_datetime: datetime#

Get the end date of the simulation.

Returns:

End date

Return type:

datetime

execute()#

Run the solver to completion.

Returns:

Error code (0 if successful)

Return type:

Any

finalize()#

Finalize the solver. Ends simulation, reports the results, and dispose objects.

Return type:

Any

get_mass_balance_error()#

Get the mass balance error.

Returns:

Mass balance error

Return type:

Tuple[float, float, float]

get_object_count(object_type)#

Get the count of a SWMM object type.

Parameters:

object_type (SWMMObjects) – SWMM object type

Returns:

Object count

Return type:

int

get_object_index(object_type, object_name)#

Get the index of a SWMM object.

Parameters:
  • object_type (SWMMObjects) – SWMM object type

  • object_name (str) – Object name

Returns:

Object index

Return type:

int

get_object_name(object_type, index)#

Get the name of a SWMM object.

Parameters:
  • object_type (SWMMObjects) – SWMM object type

  • index (int) – Object index

Returns:

Object name

Return type:

str

get_object_names(object_type)#

Get the names of all SWMM objects of a given type.

Parameters:

object_type (SWMMObjects) – SWMM object type

Returns:

Object names

Return type:

List[str]

get_value(object_type, property_type, index, sub_index=Ellipsis)#

Get a SWMM system property value.

Parameters:
Returns:

Property value

Return type:

double

initialize()#

Initialize the solver and start the simulation. Calls the open and start methods in the SWMM API.

Returns:

Error code (0 on success, non-zero from the first failing sub-call).

Return type:

int

open()#

Open the SWMM solver by calling the open method in the SWMM API.

Returns:

Error code (0 on success or no-op, non-zero on failure; -1 if called from an invalid solver state).

Return type:

int

property progress_callbacks_per_second: int#

Get the number of progress callbacks per second.

Returns:

Progress callbacks per second

Return type:

int

report()#

Report the results of the SWMM simulation.

Returns:

Error code (0 on success or no-op, non-zero on failure; -1 if not in ENDED state).

Return type:

int

property report_start_datetime: datetime#

Get the report start date of the simulation.

Returns:

Report start date

Return type:

datetime

property reporting_step: float#

Get the reporting time step of the simulation in seconds.

Returns:

Reporting time step

Return type:

double

property routing_step: float#

Get the routing time step of the simulation in seconds.

Returns:

Routing time step

Return type:

double

save_hotstart(hotstart_file)#

Save a hotstart file.

Parameters:

hotstart_file (str) – Hotstart file name

Return type:

Any

set_value(object_type, property_type, index, value, sub_index=Ellipsis)#

Set a SWMM system property value.

Parameters:
Return type:

None

property solver_state: SolverState#

Get the state of the solver.

Returns:

Solver state

Return type:

SolverState

start()#

Start the SWMM solver.

Returns:

Error code (0 on success or no-op, non-zero on failure; -1 if not in OPEN state).

Return type:

int

property start_datetime: datetime#

Get the start date of the simulation.

Returns:

Start date

Return type:

datetime

step(steps=Ellipsis)#

Step a SWMM simulation forward.

Parameters:

steps (int) – Number of steps to run. Overrides internal stride step if greater than 0.

Returns:

Error code (0 on success, non-zero on failure). The simulation transitions to the FINISHED state when complete; poll solver_state or read current_datetime for per-step data.

Return type:

int

property stride_step: int#

Get the stride step of the simulation.

Returns:

Stride step

Return type:

int

use_hotstart(hotstart_file)#

Use a hotstart file.

Parameters:

hotstart_file (str) – Hotstart file name

Return type:

Any

class LegacyNodes(solver)[source]#

Bases: object

Iterable collection of all SWMM nodes in the model.

Parameters:

solver (Solver)

class LegacyNode(solver, index, name='')[source]#

Bases: object

Property-based access to a single SWMM node.

Parameters:
property index: int#
property name: str#
property node_type: SWMMNodeTypes#
property invert_elevation: float#

Node invert elevation (project length units).

property max_depth: float#

Maximum water depth above invert (length units).

property surcharge_depth: float#

Additional depth allowed before flooding (length units).

property ponded_area: float#

Surface area used to compute ponded volume (area units).

property initial_depth: float#

Initial water depth at start of simulation.

property depth: float#

Current water depth above invert.

property head: float#

Current hydraulic head (invert + depth).

property volume: float#

Current stored volume.

property lateral_inflow: float#

Current lateral inflow rate.

property total_inflow: float#

Current total inflow rate (lateral + upstream).

property flooding: float#

Current flooding (overflow) rate.

get_pollutant_concentration(pollutant_index=0)[source]#

Get pollutant concentration at this node.

Parameters:

pollutant_index (int) – 0-based pollutant index.

Return type:

float

set_lateral_inflow(flow, log=None)[source]#

Prescribe an external lateral inflow at this node.

Mass balance impact:

Adds flow to the node’s lateral inflow for the current timestep only. The value resets each step — call again to sustain. The injected volume appears in the routing mass balance under ex_inflow (external inflow).

Parameters:
Return type:

None

set_pollutant_lateral_mass_flux(value, pollutant_index=0, log=None)[source]#

Set pollutant lateral mass flux at this node.

Mass balance impact:

The mass flux = value (mass/time). This mass is added to the quality routing mass balance. Must be used together with set_lateral_inflow() for the mass to be transported.

Parameters:
Return type:

None

set_depth(value, log=None)[source]#

Override current water depth at this node.

Mass balance impact:

Directly changes stored volume — affects storage balance. Use with care: the volume difference is not automatically tracked as an inflow or outflow.

Parameters:
Return type:

None

property statistics: dict#

Cumulative node statistics (call after solver.end()).

Bases: object

Iterable collection of all SWMM links in the model.

Parameters:

solver (Solver)

Bases: object

Property-based access to a single SWMM link.

Parameters:
property index: int#
property name: str#
property length: float#

Conduit length.

property slope: float#

Conduit slope.

property full_depth: float#

Full (maximum) depth.

property full_flow: float#

Full-pipe flow rate.

property start_node_offset: float#

Upstream invert offset.

property end_node_offset: float#

Downstream invert offset.

property initial_flow: float#

Initial flow at start of simulation.

property flow_limit: float#

User-specified flow limit.

property inlet_loss: float#
property outlet_loss: float#
property average_loss: float#
property seepage_rate: float#
property flow: float#

Current flow rate.

property depth: float#

Current flow depth.

property velocity: float#

Current flow velocity.

property volume: float#

Current volume in link.

property capacity: float#

Current capacity utilization (0-1).

property setting: float#

Current link control setting (0-1 for pumps/orifices/weirs).

get_pollutant_concentration(pollutant_index=0)[source]#
Parameters:

pollutant_index (int)

Return type:

float

set_setting(value, log=None)[source]#

Set the link control setting.

Mass balance impact:

Changes flow capacity — affects routing. For pumps this controls on/off (0 or 1). For orifices/weirs it controls the fraction open (0-1). For conduits this has no direct effect unless used with inlet control.

Parameters:
Return type:

None

set_flow(value, log=None)[source]#

Directly override the flow in this link.

Mass balance impact:

Bypasses hydraulic routing — the specified flow is used regardless of head difference. Use with extreme care as this can break mass balance if the override is inconsistent with node volumes.

Parameters:
Return type:

None

property statistics: dict#

Cumulative link statistics (call after solver.end()).

property pump_statistics: dict#

Cumulative pump statistics (only valid for PUMP links).

class LegacySubcatchments(solver)[source]#

Bases: object

Iterable collection of all SWMM subcatchments.

Parameters:

solver (Solver)

class LegacySubcatchment(solver, index, name='')[source]#

Bases: object

Property-based access to a single SWMM subcatchment.

Parameters:
property index: int#
property name: str#
property area: float#

Subcatchment area (project area units).

property width: float#

Characteristic width of overland flow.

property slope: float#

Average surface slope (%).

property curb_length: float#

Total curb length.

property fraction_impervious: float#

Fraction of impervious area (0-1).

property outlet_type: int#

Outlet type (0=node, 1=subcatchment).

property outlet_index: int#

Index of outlet node or subcatchment.

property infiltration_model: int#

Infiltration model code (0=Horton, 1=ModHorton, 2=GreenAmpt, etc.).

property rainfall: float#

Current rainfall intensity.

property evaporation: float#

Current evaporation rate.

property infiltration: float#

Current infiltration rate.

property runoff: float#

Current runoff flow rate.

get_subarea_mannings_n(sub_index)[source]#

Manning’s n for a subarea. sub_index: 0=impervious, 1=pervious.

Parameters:

sub_index (int)

Return type:

float

get_subarea_depression_storage(sub_index)[source]#

Depression storage for a subarea.

Parameters:

sub_index (int)

Return type:

float

get_subarea_runoff(sub_index)[source]#

Current runoff for a subarea.

Parameters:

sub_index (int)

Return type:

float

get_subarea_depth(sub_index)[source]#

Current depth for a subarea.

Parameters:

sub_index (int)

Return type:

float

property lid_units_count: int#

Number of LID units in this subcatchment.

get_lid_unit_area(lid_index)[source]#

Area of a specific LID unit.

Parameters:

lid_index (int)

Return type:

float

get_lid_unit_full_width(lid_index)[source]#

Full top width of a specific LID unit.

Parameters:

lid_index (int)

Return type:

float

get_lid_unit_surface_depth(lid_index)[source]#

Surface depth of a specific LID unit.

Parameters:

lid_index (int)

Return type:

float

get_lid_unit_soil_moisture(lid_index)[source]#

Soil moisture of a specific LID unit.

Parameters:

lid_index (int)

Return type:

float

get_pollutant_buildup(pollutant_index=0)[source]#

Current pollutant buildup on subcatchment.

Parameters:

pollutant_index (int)

Return type:

float

get_pollutant_runoff_concentration(pollutant_index=0)[source]#

Current pollutant concentration in runoff.

Parameters:

pollutant_index (int)

Return type:

float

get_pollutant_total_load(pollutant_index=0)[source]#

Total pollutant load washed off.

Parameters:

pollutant_index (int)

Return type:

float

set_api_rainfall(value, log=None)[source]#

Override rainfall for this subcatchment.

Mass balance impact:

Overrides the rainfall used in the runoff calculation for this subcatchment. The overridden value appears in the runoff totals under rainfall. Resets each timestep.

Parameters:
Return type:

None

set_api_snowfall(value, log=None)[source]#

Override snowfall for this subcatchment.

Mass balance impact:

Overrides the snowfall used in the snow accumulation/melt calculation. Affects the snow balance in runoff totals.

Parameters:
Return type:

None

set_external_pollutant_buildup(value, pollutant_index=0, log=None)[source]#

Add external pollutant buildup on this subcatchment.

Mass balance impact:

Adds pollutant mass to the surface. This mass is available for washoff and appears in the quality mass balance.

Parameters:
Return type:

None

property statistics: dict#

Cumulative subcatchment statistics (call after solver.end()).

class LegacyRainGages(solver)[source]#

Bases: object

Iterable collection of all SWMM rain gages.

Parameters:

solver (Solver)

class LegacyRainGage(solver, index, name='')[source]#

Bases: object

Property-based access to a single SWMM rain gage.

Parameters:
property index: int#
property name: str#
property total_precipitation: float#

Current total precipitation (rainfall + snowfall).

property rainfall: float#

Current rainfall intensity.

property snowfall: float#

Current snowfall intensity.

set_rainfall(value, log=None)[source]#

Override rainfall at this gage.

Mass balance impact:

Overrides rainfall for all subcatchments linked to this gage. Appears in runoff totals under rainfall.

Parameters:
Return type:

None

class LegacySystem(solver)[source]#

Bases: object

System-level properties, simulation settings, and mass balance totals.

Wraps a Solver instance and provides convenient property-based access to global simulation parameters and post-simulation mass balance breakdowns.

Parameters:

solver (Solver)

property flow_units: SWMMFlowUnits#

Flow units used in this simulation.

property unit_system: int#

Unit system (0=US, 1=SI).

property routing_step: float#

Routing time step (seconds).

property report_step: float#

Reporting time step (seconds).

property total_steps: int#

Total number of routing steps.

property num_threads: int#

Number of threads for parallel computation.

property allow_ponding: bool#

Whether ponding is allowed at nodes.

property head_tolerance: float#

Head convergence tolerance (length units).

property sys_flow_tolerance: float#

System flow convergence tolerance.

property lat_flow_tolerance: float#

Lateral flow convergence tolerance.

property runoff_error: float#

Runoff continuity error (%).

property flow_error: float#

Flow routing continuity error (%).

property quality_error: float#

Quality routing continuity error (%).

property routing_totals: dict#

System-level flow routing mass balance totals.

Returns a dict with keys: dw_inflow, ww_inflow, gw_inflow, ii_inflow, ex_inflow, flooding, outflow, evap_loss, seep_loss, reacted, init_storage, final_storage, pct_error.

Mass balance equation:

total_inflow = dw + ww + gw + ii + ex
total_outflow = flooding + outflow + evap_loss + seep_loss
storage_change = final_storage - init_storage
balance = total_inflow - total_outflow - storage_change
property runoff_totals: dict#

System-level surface runoff mass balance totals.

Returns a dict with keys: rainfall, evap, infil, runoff, drains, runon, init_storage, final_storage, init_snow_cover, final_snow_cover, snow_removed, pct_error.

property mass_balance_error#

Mass balance errors as (runoff_err%, flow_err%, quality_err%).

class ExternalForcingLog[source]#

Bases: object

Append-only log that records external forcing applied during a simulation.

Each entry stores the simulation time, target object, property modified, and the value applied.

record(sim_time, object_type, object_id, property_name, value, mass_balance_category='')[source]#

Append a forcing record.

Parameters:
  • sim_time (datetime) – Current simulation datetime.

  • object_type (str) – E.g. "node", "link", "subcatchment".

  • object_id (str) – Object name or index string.

  • property_name (str) – Property that was set.

  • value (float) – The value applied.

  • mass_balance_category (str) – Which mass-balance bucket is affected.

Return type:

None

property records: List[dict]#

Return the raw list of recorded forcing entries.

clear()[source]#

Remove all recorded entries.

Return type:

None

to_dataframe()[source]#

Convert to a pandas.DataFrame.

Columns: time, object_type, object_id, property, value, mass_balance_category.

Raises:

ImportError – If pandas is not installed.


openswmm.legacy.output — SWMM 5.x binary output reader#

The openswmm.legacy.output subpackage reads the binary .out file produced by either the legacy SWMM 5.x solver or the v6.0 engine.

openswmm.legacy.output#

Legacy EPA SWMM 5.x binary output file reader (Cython).

This subpackage provides the Output class for reading SWMM .out result files, and enumeration types for element and attribute access.

class UnitSystem(*values)#

Bases: Enum

Enumeration of the unit system used in the output file.

Variables:
  • US – US customary units.

  • SI – SI metric units.

US = Ellipsis#
SI = Ellipsis#
class FlowUnits(*values)#

Bases: Enum

Enumeration of the flow units used in the simulation.

Variables:
  • CFS – Cubic feet per second.

  • GPM – Gallons per minute.

  • MGD – Million gallons per day.

  • CMS – Cubic meters per second.

  • LPS – Liters per second.

  • MLD – Million liters per day.

CFS = Ellipsis#
GPM = Ellipsis#
MGD = Ellipsis#
CMS = Ellipsis#
LPS = Ellipsis#
MLD = Ellipsis#
class ConcentrationUnits(*values)#

Bases: Enum

Enumeration of the concentration units used in the simulation.

Variables:
  • MG – Milligrams per liter.

  • UG – Micrograms per liter.

  • COUNT – Counts per liter.

  • NONE – No units.

MG = Ellipsis#
UG = Ellipsis#
COUNT = Ellipsis#
NONE = Ellipsis#
class ElementType(*values)#

Bases: Enum

Enumeration of the SWMM element types.

Variables:
  • SUBCATCHMENT – Subcatchment.

  • NODE – Node.

  • LINK – Link.

  • SYS – System.

  • POLLUTANT – Pollutant.

SUBCATCHMENT = Ellipsis#
NODE = Ellipsis#
SYSTEM = Ellipsis#
POLLUTANT = Ellipsis#
class TimeAttribute(*values)#

Bases: Enum

Enumeration of the report time related attributes.

Variables:
  • REPORT_STEP – Report step size (seconds).

  • NUM_PERIODS – Number of reporting periods.

REPORT_STEP = Ellipsis#
NUM_PERIODS = Ellipsis#
class SubcatchAttribute(*values)#

Bases: Enum

Enumeration of the subcatchment attributes.

Variables:
  • RAINFALL – Subcatchment rainfall (in/hr or mm/hr).

  • SNOW_DEPTH – Subcatchment snow depth (in or mm).

  • EVAPORATION_LOSS – Subcatchment evaporation loss (in/hr or mm/hr).

  • INFILTRATION_LOSS – Subcatchment infiltration loss (in/hr or mm/hr).

  • RUNOFF_RATE – Subcatchment runoff flow (flow units).

  • GROUNDWATER_OUTFLOW – Subcatchment groundwater flow (flow units).

  • GW_TABLE – Subcatchment groundwater elevation (ft or m).

  • SOIL_MOISTURE – Subcatchment soil moisture content (-).

  • POLLUTANT_CONCENTRATION – Subcatchment pollutant concentration (-).

RAINFALL = Ellipsis#
SNOW_DEPTH = Ellipsis#
EVAPORATION_LOSS = Ellipsis#
INFILTRATION_LOSS = Ellipsis#
RUNOFF_RATE = Ellipsis#
GROUNDWATER_OUTFLOW = Ellipsis#
GROUNDWATER_TABLE_ELEVATION = Ellipsis#
SOIL_MOISTURE = Ellipsis#
POLLUTANT_CONCENTRATION = Ellipsis#
class NodeAttribute(*values)#

Bases: Enum

Enumeration of the node attributes.

Variables:
  • INVERT_DEPTH – Node depth above invert (ft or m).

  • HYDRAULIC_HEAD – Node hydraulic head (ft or m).

  • STORED_VOLUME – Node volume stored (ft3 or m3).

  • LATERAL_INFLOW – Node lateral inflow (flow units).

  • TOTAL_INFLOW – Node total inflow (flow units).

  • FLOODING_LOSSES – Node flooding losses (flow units).

  • POLLUTANT_CONCENTRATION – Node pollutant concentration (-).

INVERT_DEPTH = Ellipsis#
HYDRAULIC_HEAD = Ellipsis#
STORED_VOLUME = Ellipsis#
LATERAL_INFLOW = Ellipsis#
TOTAL_INFLOW = Ellipsis#
FLOODING_LOSSES = Ellipsis#
POLLUTANT_CONCENTRATION = Ellipsis#
class LinkAttribute(*values)#

Bases: Enum

Enumeration of the link attributes.

Variables:
  • FLOW_RATE – Link flow rate (flow units).

  • FLOW_DEPTH – Link flow depth (ft or m).

  • FLOW_VELOCITY – Link flow velocity (ft/s or m/s).

  • FLOW_VOLUME – Link flow volume (ft3 or m3).

  • CAPACITY – Link capacity (fraction of conduit filled).

  • POLLUTANT_CONCENTRATION – Link pollutant concentration (-).

FLOW_RATE = Ellipsis#
FLOW_DEPTH = Ellipsis#
FLOW_VELOCITY = Ellipsis#
FLOW_VOLUME = Ellipsis#
CAPACITY = Ellipsis#
POLLUTANT_CONCENTRATION = Ellipsis#
class SystemAttribute(*values)#

Bases: Enum

Enumeration of the system attributes.

Variables:
  • AIR_TEMP – Air temperature (deg. F or deg. C).

  • RAINFALL – Rainfall intensity (in/hr or mm/hr).

  • SNOW_DEPTH – Snow depth (in or mm).

  • EVAP_INFIL_LOSS – Evaporation and infiltration loss rate (in/day or mm/day).

  • RUNOFF_FLOW – Runoff flow (flow units).

  • DRY_WEATHER_INFLOW – Dry weather inflow (flow units).

  • GROUNDWATER_INFLOW – Groundwater inflow (flow units).

  • RDII_INFLOW – Rainfall Derived Infiltration and Inflow (RDII) (flow units).

  • DIRECT_INFLOW – Direct inflow (flow units).

  • TOTAL_LATERAL_INFLOW – Total lateral inflow; sum of variables 4 to 8 (flow units).

  • FLOOD_LOSSES – Flooding losses (flow units).

  • OUTFALL_FLOWS – Outfall flow (flow units).

  • VOLUME_STORED – Volume stored in storage nodes (ft3 or m3).

  • EVAPORATION_RATE – Evaporation rate (in/day or mm/day).

AIR_TEMP = Ellipsis#
RAINFALL = Ellipsis#
SNOW_DEPTH = Ellipsis#
EVAP_INFIL_LOSS = Ellipsis#
RUNOFF_FLOW = Ellipsis#
DRY_WEATHER_INFLOW = Ellipsis#
GROUNDWATER_INFLOW = Ellipsis#
RDII_INFLOW = Ellipsis#
DIRECT_INFLOW = Ellipsis#
TOTAL_LATERAL_INFLOW = Ellipsis#
FLOOD_LOSSES = Ellipsis#
OUTFALL_FLOWS = Ellipsis#
VOLUME_STORED = Ellipsis#
EVAPORATION_RATE = Ellipsis#
exception SWMMOutputException(message)#

Bases: Exception

Exception class for SWMM output file processing errors.

Constructor to initialize the exception message.

Parameters:

message (str) – Error message.

Return type:

None

__init__(message)#

Constructor to initialize the exception message.

Parameters:

message (str) – Error message.

Return type:

None

class Output(output_file)#

Bases: object

Class to read and process the output file generated by the SWMM simulation.

Variables:
  • _output_file_handle – Handle to the SWMM output file.

  • _version – Version of the SWMM output file.

  • _units – Unit system used in the SWMM output file.

  • _flow_units – Flow units used in the SWMM output file.

  • _output_size – Size of the project in the SWMM output file.

  • _pollutant_units – Pollutant units used in the SWMM output file.

  • _start_date – Start date of the simulation in the SWMM output file.

  • _report_step – Report step size in seconds.

  • _num_periods – Number of reporting periods.

  • _times – Times of the simulation in the SWMM output file.

Parameters:

output_file (str)

Constructor to open the SWMM output file.

Parameters:

output_file (str) – Path to the SWMM output file.

__init__(output_file)#

Constructor to open the SWMM output file.

Parameters:

output_file (str) – Path to the SWMM output file.

Return type:

None

property flow_units: FlowUnits#

Method to get the flow units used in the SWMM output file.

Returns:

Flow units used in the SWMM output file.

Return type:

FlowUnits

get_element_name(element_type, element_index)#

Method to get the name of an element in the SWMM output file.

Parameters:
  • element_type (int) – Type of the element.

  • indelement_indexex – Index of the element.

  • element_index (int)

Returns:

Name of the element.

Return type:

str

get_element_names(element_type)#

Method to get the names of all elements of a given type in the SWMM output file.

Parameters:

element_type (int) – Type of the element.

Returns:

Names of all elements of the given type.

Return type:

List[str]

Method to get the time series data for a link attribute in the SWMM output file.

Parameters:
  • element_index (int) – Index of the link.

  • attribute (LinkAttribute) – Link attribute.

  • start_date_index (int) – Start date index. Default is 0.

  • end_date_index (int) – End date index. Default is the last date index.

  • sub_index (int) – Attribute index for the subcatchment non enumerated attributes primarily for the pollutants

Returns:

Time series data for the link attribute.

Return type:

Dict[datetime, double]

Method to get the link values for all links for a given time index and attribute.

Parameters:
  • time_index (int) – Time index.

  • attribute (LinkAttribute) – Link attribute.

  • sub_index (int) – Attribute index for the subcatchment non enumerated attributes primarily for the pollutants

Returns:

Link values for all links.

Return type:

Dict[str, float]

Method to get all attributes of a given link for specified time.

Parameters:
  • time_index (int) – Time index.

  • element_index (int, str) – Index of the link.

Returns:

Dictionary of link attributes.

Return type:

Dict[str, float]

get_node_timeseries(element_index, attribute, start_date_index=Ellipsis, end_date_index=Ellipsis, sub_index=Ellipsis)#

Method to get the time series data for a node attribute in the SWMM output file.

Parameters:
  • element_index (int or str) – Index of the node.

  • attribute (NodeAttribute) – Node attribute.

  • start_date_index (int) – Start date index. Default is 0.

  • end_date_index (int) – End date index. Default is the last date index.

  • sub_index (int) – Attribute index for the subcatchment non enumerated attributes primarily for the pollutants

Returns:

Time series data for the node attribute.

Return type:

Dict[datetime, double]

get_node_values_by_time_and_attribute(time_index, attribute, sub_index=Ellipsis)#

Method to get the node values for all nodes for a given time index and attribute.

Parameters:
  • time_index (int) – Time index.

  • attribute (NodeAttribute) – Node attribute.

  • sub_index (int) – Attribute index for the subcatchment non enumerated attributes primarily for the pollutants

Returns:

Node values for all nodes.

Return type:

Dict[str, float]

get_node_values_by_time_and_element_index(time_index, element_index)#

Method to get all attributes of a given node for specified time.

Parameters:
  • time_index (int) – Time index.

  • element_index (int) – Index of the node.

Returns:

Dictionary of node attributes.

Return type:

Dict[str, float]

get_num_properties(element_type)#

Method to get the number of properties for an element type in the SWMM output file.

Parameters:

element_type (int) – Type of the element.

Returns:

Number of properties for the element type.

Return type:

int

get_num_variables(element_type)#

Method to get the number of variables for an element type in the SWMM output file.

Parameters:

element_type (int) – Type of the element.

Returns:

Number of variables for the element type.

Return type:

int

get_property_code(element_type, property_index)#

Method to get the property code for an element type in the SWMM output file.

Parameters:
  • element_type (int) – Type of the element.

  • property_index (int) – Index of the property.

Returns:

Property code for the element type.

Return type:

int

get_property_codes(element_type)#

Method to get the property codes for an element type in the SWMM output file.

Parameters:

element_type (int) – Type of the element.

Returns:

Property codes for the element type.

Return type:

List[int]

get_property_value(element_type, element_index, property_code)#

Method to get the property value for an element in the SWMM output file.

Parameters:
  • element_type (int) – Type of the element.

  • element_index (int) – Index of the element.

  • property_code (int) – Property code.

Returns:

Property value for the element.

Return type:

float

get_property_values(element_type, element_index)#

Method to get the property values for an element type in the SWMM output file.

Parameters:
  • element_type (int) – Type of the element.

  • element_index (int) – Element index.

Returns:

Property values for the element type.

Return type:

List[float]

get_subcatchment_timeseries(element_index, attribute, start_date_index=Ellipsis, end_date_index=Ellipsis, sub_index=Ellipsis)#

Method to get the time series data for a subcatchment attribute in the SWMM output file.

Parameters:
  • element_index (int or str) – Index of the subcatchment.

  • attribute (SubcatchAttribute) – Subcatchment attribute.

  • start_date_index (int) – Start date index. Default is 0.

  • end_date_index (int) – End date index. Default is the last date index.

  • sub_index (int) – Attribute index for the subcatchment non enumerated attributes primarily for the pollutants

Returns:

Time series data for the subcatchment attribute.

Return type:

Dict[datetime, double]

get_subcatchment_values_by_time_and_attribute(time_index, attribute, sub_index=Ellipsis)#

Method to get the subcatchment values for all subcatchments for a given time index and attribute.

Parameters:
  • time_index (int) – Time index.

  • attribute (SubcatchAttribute) – Subcatchment attribute.

  • sub_index (int) – Attribute index for the subcatchment non enumerated attributes primarily for the pollutants

Returns:

Subcatchment values for all subcatchments.

Return type:

Dict[str, float]

get_subcatchment_values_by_time_and_element_index(time_index, element_index)#

Method to get all attributes of a given subcatchment for specified time.

Parameters:
  • time_index (int) – Time index.

  • element_index (int or str) – Index of the subcatchment.

Returns:

Dictionary of subcatchment attributes.

Return type:

Dict[str, float]

get_system_timeseries(attribute, start_date_index=Ellipsis, end_date_index=Ellipsis, sub_index=Ellipsis)#

Method to get the time series data for a system attribute in the SWMM output file.

Parameters:
  • attribute (SystemAttribute) – System attribute.

  • start_date_index (int) – Start date index. Default is 0.

  • end_date_index (int) – End date index. Default is the last date index.

  • sub_index (int) – Attribute index for the subcatchment non enumerated attributes primarily for the pollutants

Returns:

Time series data for the system attribute.

Return type:

Dict[datetime, double]

get_system_values_by_time(time_index)#

Method to get all attributes of the system for specified time.

Parameters:

time_index (int) – Time index.

Returns:

Dictionary of system attributes.

Return type:

Dict[str, float]

get_system_values_by_time_and_attribute(time_index, attribute, sub_index=Ellipsis)#

Method to get the system values for a given time index and attribute.

Parameters:
  • time_index (int) – Time index.

  • attribute (SystemAttribute) – System attribute.

  • sub_index (int) – Attribute index for the subcatchment non enumerated attributes primarily for the pollutants

Returns:

System values.

Return type:

Dict[str, float]

get_time_attribute(time_attribute)#

Method to get the temporal attributes of the simulation in the SWMM output file.

Parameters:

time_attribute (TimeAttribute) – Temporal attribute.

Returns:

Temporal attributes of the simulation in the SWMM output file.

Return type:

int

get_variable_code(element_type, variable_index)#

Method to get the variable code for an element type in the SWMM output file.

Parameters:
  • element_type (int) – Type of the element.

  • variable_index (int) – Index of the variable.

Returns:

Variable code for the element type.

Return type:

int

get_variable_codes(element_type)#

Method to get the variable codes for an element type in the SWMM output file.

Parameters:

element_type (int) – Type of the element.

Returns:

Variable codes for the element type.

Return type:

List[int]

property output_size: Dict[str, int]#

Method to get the size of the project in the SWMM output file.

Returns:

Size of the project in the SWMM output file.

Return type:

int

property pollutant_units: List[ConcentrationUnits]#

Method to get the pollutant units used in the SWMM output file.

Returns:

Pollutant units used in the SWMM output file.

Return type:

List[ConcentrationUnits]

property start_date: datetime#

Method to get the start date of the simulation in the SWMM output file.

Returns:

Start date of the simulation in the SWMM output file.

Return type:

datetime

property times: List[datetime]#

Method to get the times of the simulation in the SWMM output file.

Returns:

Times of the simulation in the SWMM output file.

Return type:

List[datetime]

property units: Tuple[UnitSystem, FlowUnits, List[ConcentrationUnits] | None]#

Method to get the unit system used in the SWMM output file.

Returns:

Tuple of the unit system, flow units, and pollutant units used in the SWMM output file.

Return type:

Tuple[UnitSystem, FlowUnits, Optional[List[ConcentrationUnits]]]

property version: int#

Method to get the version of the SWMM output file.

Returns:

Version of the SWMM output file.

Return type:

str