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:
Apache-2.0
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.
Runtime 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.
Saved result readers operate independently of a solver; see Working with results.
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:
Apache-2.0
Cython bindings for the OpenSWMM Engine 6.0 C API.
The package is split by domain to mirror the C header organisation:
Python class |
C header |
Contents |
|---|---|---|
|
|
Engine lifecycle, timing, error reporting |
|
|
Programmatic model construction |
|
|
In-place model editing (delete + type conversion) |
|
|
Node get/set, lateral inflow, bulk arrays |
|
|
Link get/set, control settings, bulk arrays |
|
|
Cross-section geometry kernels (standalone or per-link) |
|
|
Subcatchment runoff, rainfall override |
|
|
Rain gage rainfall get/set |
|
|
Hot start save/open/apply/close |
|
|
Continuity error queries |
|
|
Cumulative simulation statistics |
|
|
Binary output file reader |
|
|
Pollutant management and quality injection |
|
|
Landuse, buildup, washoff, treatment |
|
|
|
|
|
Multi-species reaction system: species, coefficients, terms, expressions |
|
|
Heat-transport fluxes, solar/cloud forcing, inlet temperatures |
|
|
|
|
|
|
|
|
Time series, curves, patterns |
|
|
External inflows, DWF, RDII |
|
|
Control rules and direct actions |
|
|
Advanced runtime forcing (mode + persistence) |
|
|
Transects, streets, inlets, LIDs |
|
|
Coordinates, CRS, vertices, polygons |
|
|
2D surface mesh / coupled overland flow |
|
|
GeoPackage import/export (requires |
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)
for elapsed in s.steps():
depths = nodes.depths
flows = links.flows
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()
for elapsed in solver.steps():
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#
- class Event(start, end)#
Bases:
NamedTupleCreate new instance of Event(start, end)
- class EventsView(solver)#
Bases:
MutableSequence[Event][EVENTS]block as aMutableSequence. SeeSolver.events.- Parameters:
solver (Solver)
- append(value)#
S.append(value) – append value to the end of the sequence
- Parameters:
value (Any)
- Return type:
None
- clear() None -- remove all items from S#
- Return type:
None
- class SimulationOptions(solver)#
Bases:
MutableMapping[str,str]View over the
[OPTIONS]block. SeeSolver.options.- Parameters:
solver (Solver)
- ext: _OptionsExtView#
- class Solver(inp='', rpt=None, out=None, *, plugin_lib=None)#
Bases:
objectSWMM engine lifecycle manager.
Accepts
strorpathlib.Pathfor every file argument.from datetime import timedelta from openswmm.engine import Solver with Solver("model.inp", "model.rpt", "model.out") as s: for elapsed in s.steps(): if elapsed >= timedelta(hours=24): break
- Parameters:
inp (_PathLike)
rpt (Optional[_PathLike])
out (Optional[_PathLike])
plugin_lib (Optional[_PathLike])
- property checkpoints: Checkpoints#
- close()#
- Return type:
None
- close_runoff_interface()#
- Return type:
None
- property coupling: Coupling#
- create()#
- Return type:
None
- destroy()#
- Return type:
None
- property editor: ModelEditor#
- end()#
- Return type:
None
- property events: EventsView#
- property flow_units: FlowUnits#
The model’s flow-unit system, resolved from
FLOW_UNITS.- Returns:
Active flow-unit system; read this to interpret the project-unit magnitudes returned by all getters.
- Return type:
L{FlowUnits}
- property groundwater2d: Groundwater#
- property infrastructure: Infrastructure#
- property initial_quality: InitialQuality#
- initialize()#
- Return type:
None
- property mass_balance: MassBalance#
- property material_split: MaterialSplitParticipant#
- open_metadata()#
- Return type:
None
- open_results(*, surface=Ellipsis, live=Ellipsis)#
Open independent results after end(); live=True opens only 1D output.
- open_simulation_period()#
Open the configured model only as far as its simulation period.
A metadata open (see
open_metadata()) that leaves out the 2D mesh and every row that addresses its cells: the built-in reader skips the mesh sections and the per-cell ones, and a[2D_MESH_FILE]is not read, so a large 2D model opens in a fraction of the time and memory. The start and end times are the onesopen_metadata()gives. Other answers can differ: there is no 2D mesh, the[GW_*]rows are not checked, heat overrides scopedCELL2DorMESH_TAGare dropped, and a mesh or cell row a full open would refuse is not detected. Close and open normally before initializing a simulation.- Raises:
EngineError – On C API failure (specific subclass per code).
- Return type:
None
- property options: SimulationOptions#
- property passive_exchange: PassiveExchange#
- property pollutants: Pollutants#
- property process_components: ProcessComponents#
- report()#
- Return type:
None
- run()#
- Return type:
None
- property save_schedule: SaveSchedule#
- set_phase_callback(callback)#
- set_progress_callback(callback)#
Register a progress callback receiving the elapsed fraction [0, 1].
- set_step_begin_callback(callback)#
- set_step_end_callback(callback)#
- set_warning_callback(callback)#
- property sim_start_time: datetime#
Resolved simulation start (
swmm_get_start_time).- Return type:
datetime
- property snow: Snow#
- property split: SplitParticipant#
- property state: EngineState#
- property statistics: Statistics#
- property subcatchments: Subcatchments#
- property thread_info: ThreadInfo#
- property transport_matrix: dict[TransportDomain, dict[TransportClass, TransportCell]]#
- write_compat(path, profile)#
- write_geopackage(path, crs=Ellipsis)#
- write_staged(final_path, mapper)#
- class UserFlagDef(name, type, description)#
Bases:
NamedTupleA
[USER_FLAGS]schema definition:(name, type, description).typeis 0=BOOLEAN, 1=INTEGER, 2=REAL, 3=STRING (seeUserFlagType).Create new instance of UserFlagDef(name, type, description)
- class UserFlags(solver)#
Bases:
MutableMapping[str,bool|int|float|str]Typed user-flag mapping. See
Solver.userflags.- Parameters:
solver (Solver)
- clear_value(obj_type, obj_name, flag_name)#
- define(name, type, description='')#
- definitions()#
- Return type:
- get_value(obj_type, obj_name, flag_name)#
- set_value(obj_type, obj_name, flag_name, value)#
- abi_tag()#
Return the immutable C ABI identity of the engine loaded by these bindings.
Compare it with a native host’s engine identity before sharing handles. This query creates no solver and is valid before opening a model. The wheel’s
openswmm/engine/_abi.jsonrecords its expected build identity.- Return type:
- run(inp, rpt=None, out=None, *, plugin_lib=None)#
Run a SWMM simulation start-to-finish. Raises
EngineErroron failure.
- run_with_callback(inp, rpt=None, out=None, callback=None, *, plugin_lib=None)#
Run a SWMM simulation with an optional progress callback. Raises
EngineErroron failure.
Exceptions#
The EngineError hierarchy and the dispatch helper used by
_check(). Each subclass also inherits from a standard-library
exception so idiomatic except IndexError: / except ValueError:
handlers do the right thing.
Type stubs for openswmm.engine._exceptions.
- exception BadHandleError(code, message=Ellipsis)#
Bases:
EngineError,RuntimeError
- exception BadIndexError(code, message=Ellipsis)#
Bases:
EngineError,IndexError
- exception BadParamError(code, message=Ellipsis)#
Bases:
EngineError,ValueError
- exception CRSError(code, message=Ellipsis)#
Bases:
EngineError,ValueError
- exception DependencyError(code, message=Ellipsis)#
Bases:
EngineError,RuntimeError
- exception FileError(code, message=Ellipsis)#
Bases:
EngineError,OSError
- exception GeoPackageError(code, message=Ellipsis)#
Bases:
EngineError,RuntimeError
- exception HotStartError(code, message=Ellipsis)#
Bases:
EngineError,RuntimeError
- exception LifecycleError(code, message=Ellipsis)#
Bases:
EngineError,RuntimeError
- exception NumericalError(code, message=Ellipsis)#
Bases:
EngineError,RuntimeError
- exception ParseError(code, message=Ellipsis)#
Bases:
EngineError,ValueError
- exception PluginError(code, message=Ellipsis)#
Bases:
EngineError,RuntimeError
- exception StaleObjectError(message=Ellipsis)#
Bases:
LifecycleError- Parameters:
message (str)
- Return type:
None
DateTime conversion#
The low-level C API encode/decode primitives plus the high-level
oadate_to_datetime / datetime_to_oadate helpers used throughout
the bindings.
Type stubs for openswmm.engine._datetime.
Low-level Python bindings around the SWMM DateTime conversion C API
declared in openswmm_datetime.h. SWMM’s native DateTime is a double
whose integer part is days since 1899-12-30 and fractional part is the
time-of-day fraction.
- encode_time(hour, minute, second)#
Type stubs for openswmm.engine._dates.
High-level helpers that convert between SWMM’s native DateTime double
(decimal days since 1899-12-30) and datetime.datetime. The
calendar arithmetic is delegated to the C API in openswmm_datetime.h.
Model construction#
Programmatic Model Building#
- author:
Caleb Buahin
- copyright:
Copyright (c) 2026 Caleb Buahin
- license:
Apache-2.0
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:
objectBuild a SWMM model programmatically (no
.inpfile).The engine starts in
BUILDINGstate. Useadd_node,add_link, etc. to populate the model, then callfinalizeto transition toINITIALIZED.Note
The
ModelBuilderowns its engine handle untilto_solveris called; the resultingSolverthen 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.
- add_link(link_id, link_type)#
Add a link to the model.
Valid in
BUILDINGorOPENEDstate.- Parameters:
- Returns:
Error code (
0on success).- Return type:
@see: L{openswmm.engine.LinkType}
- add_node(node_id, node_type)#
Add a node to the model.
Valid in
BUILDINGorOPENEDstate.- Parameters:
- Returns:
Error code (
0on success).- Return type:
@see: L{openswmm.engine.NodeType}
- add_subcatch(sc_id)#
Backward-compatible alias for
add_subcatchment.
- add_subcatchment(sc_id)#
Add a subcatchment to the model.
- 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
- clear_userflag_value(obj_type, obj_name, flag_name)#
Remove a per-object flag value (idempotent).
- Raises:
EngineError – On C API failure.
- Parameters:
- Return type:
None
- define_userflag(name, type, description='')#
Define (or redefine) a user-flag schema entry (
[USER_FLAGS]).- Parameters:
- Raises:
EngineError – On empty name or invalid type.
- Return type:
None
- files_get(key)#
Read one [FILES] field by key.
- files_set(key, value)#
Write one [FILES] field by key.
- finalize()#
Finalize the model – build connectivity and allocate arrays.
Transitions to
INITIALIZEDstate.- Returns:
None
- Return type:
None
- Raises:
EngineError – If finalization fails.
- property generation: int#
Monotonic counter bumped on every structural mutation.
Mirrors
Solver.generationso wrapper objects minted from aModelBuildercan detect staleness the same way.
- 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:
- get_file_path(role, owner=Ellipsis)#
Read an external-file slot’s
(absolute, original)paths.
- get_option(key)#
Return a SWMM option value as a string.
- Raises:
EngineError – On unknown key.
- Parameters:
key (str)
- Return type:
- 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:
- get_title_count()#
Number of lines in the
[TITLE]section.- Raises:
EngineError – On C API failure.
- Return type:
- get_title_line(index)#
Return a title line by zero-based index.
- Raises:
EngineError – On bad index.
- Parameters:
index (int)
- Return type:
- get_userflag_bool(name)#
Return a boolean user flag value.
- Raises:
EngineError – On unknown flag.
- Parameters:
name (str)
- Return type:
- get_userflag_def(index)#
Return
(name, type, description)for the definition atindex.
- get_userflag_int(name)#
Return an integer user flag value.
- Raises:
EngineError – On unknown flag.
- Parameters:
name (str)
- Return type:
- get_userflag_real(name)#
Return a real-valued user flag.
- Raises:
EngineError – On unknown flag.
- Parameters:
name (str)
- Return type:
- get_userflag_value(obj_type, obj_name, flag_name)#
Return a per-object flag value string, or
Nonewhen unassigned.- Raises:
EngineError – On C API failure.
- Parameters:
- Return type:
str | None
- 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:
- plugin_get(idx)#
Read one [PLUGINS] row by index.
- plugin_remove(path_or_id)#
Remove the [PLUGINS] row matching
path_or_id.- Parameters:
path_or_id (str) – Library path, plugin id, or
id:versionstring.- Return type:
None
- plugin_set(path_or_id, args='')#
Add or replace a [PLUGINS] row keyed by path/id.
- plugins_count()#
Return the number of [PLUGINS] entries on the engine.
- Returns:
Plugin count.
- Return type:
- pop_last_link(link_id)#
Remove the most recently added link (undo-of-add).
Valid in
BUILDINGorOPENEDstate. Thelink_idmust match the current tail; otherwiseSWMM_ERR_BADINDEXis returned.
- pop_last_node(node_id)#
Remove the most recently added node (undo-of-add).
Valid in
BUILDINGorOPENEDstate. Thenode_idmust match the current tail; otherwiseSWMM_ERR_BADINDEXis returned. ReturnsSWMM_ERR_BADPARAMif any link still references the tail node – pop those links first viapop_last_link.
- set_file_path(role, new_path, owner=Ellipsis)#
Set an external-file slot’s path token (empty clears it).
- set_link_length(idx, length)#
Set the length of a conduit link.
- Parameters:
- Returns:
None
- Return type:
None
- Raises:
EngineError – On C API failure.
- set_link_nodes(idx, from_node, to_node)#
Set the upstream and downstream nodes for a link.
- Parameters:
- Returns:
None
- Return type:
None
- Raises:
EngineError – On C API failure.
- set_link_roughness(idx, n)#
Set Manning’s roughness coefficient for a conduit.
- Parameters:
- Returns:
None
- Return type:
None
- Raises:
EngineError – On C API failure.
- set_link_xsect(idx, shape, g1, g2=0, g3=0, g4=0)#
Set the cross-section geometry of a conduit.
- Parameters:
- 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:
- 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:
- 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
- set_userflag_value(obj_type, obj_name, flag_name, value)#
Assign a per-object flag value from a string (typed parse).
- Raises:
EngineError – On undefined flag or unparseable value.
- Parameters:
- Return type:
None
- to_solver()#
Transfer ownership of the engine handle to a
Solver.After this call, the
ModelBuilderis invalidated and must not be used. The returnedSolverowns the engine handle.- Returns:
A new
Solverwrapping this model’s engine.- Return type:
L{Solver}
- undefine_userflag(name)#
Remove a user-flag definition and all its per-object values.
- Raises:
EngineError – If the flag is not defined.
- Parameters:
name (str)
- Return type:
None
- 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
.inpfile.- 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.
Model editing (deletion + type conversion)#
Model Editing — Object Deletion and Type Conversion#
- author:
Caleb Buahin
- copyright:
Copyright (c) 2026 Caleb Buahin
- license:
Apache-2.0
Type stubs for openswmm.engine._edit.
- class ConversionResult(new_type, cleared_fields, warnings)#
Bases:
objectResult 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.
- class DeleteRecord#
Bases:
objectHow to undo one recorded delete exactly.
Returned by the
*_recordeddelete methods ofModelEditor. It holds every row the delete removed, with its original index, and every reference the delete cleared or renumbered.restoreputs all of it back, at most once, on the engine that made the delete.The native record is released when this object is garbage-collected, or earlier by
close. It cannot be constructed directly.- close()#
Release the native record; it can no longer be restored.
Safe to call more than once, and after the engine is destroyed.
- Return type:
None
- restore()#
Undo the delete: reinsert every removed row at its original index and restore every reference the delete cleared or renumbered.
The engine refuses, changing nothing, when the model no longer matches the state the delete left (object counts, the name being free, cleared references still clear); the record then stays restorable. A successful restore spends the record and invalidates existing element wrappers, as a delete does.
- Raises:
ValueError – If the record was already restored or closed.
BadHandleError – If the engine that made the record has been destroyed.
BadParamError – If the model no longer matches the state the delete left.
EngineError – On another C API failure, such as an engine that is not in
BUILDINGorOPENEDstate.
- Return type:
None
- class ImpactEntry(obj_type, obj_idx, field, cascaded)#
Bases:
objectOne 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").cascaded –
Trueif the referencing object will be deleted;Falseif only the reference will be nullified.
- Parameters:
- class ModelEditor(engine)#
Bases:
objectEdit an existing SWMM model – delete objects and convert types.
Accepts any object that exposes a
handleproperty returning the raw engine pointer as an integer. BothModelBuilder(BUILDINGstate) andSolver(OPENEDstate) satisfy this contract.- Parameters:
engine (object) – A
ModelBuilderorSolverinstance.
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_aquifer_impact(id_or_idx)#
Preview which subcatchments reference an aquifer.
- Parameters:
- Return type:
- analyze_gage_impact(id_or_idx)#
Preview which objects reference a rain gage.
- Parameters:
- Returns:
List of
ImpactEntrydescribing what would be affected.- Return type:
list[
ImpactEntry]- Raises:
KeyError – If
id_or_idxis a name and the gage is not found.EngineError – On C API failure.
- analyze_hydrograph_impact(uh_name)#
Preview which objects reference a unit-hydrograph group by name.
- Parameters:
uh_name (str)
- Return type:
- analyze_inlet_impact(id_or_idx)#
Preview which inlet-usage rows reference an inlet design.
- Parameters:
- Return type:
- analyze_landuse_impact(id_or_idx)#
Preview which objects reference a land use.
- Parameters:
- Return type:
- analyze_lid_impact(id_or_idx)#
Preview which LID-usage rows reference a LID control.
- Parameters:
- Return type:
- analyze_link_impact(id_or_idx)#
Preview which objects reference a link, without deleting it.
- Parameters:
- Returns:
List of
ImpactEntrydescribing what would be affected.- Return type:
list[
ImpactEntry]- Raises:
KeyError – If
id_or_idxis 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:
- Returns:
List of
ImpactEntrydescribing what would be affected.- Return type:
list[
ImpactEntry]- Raises:
KeyError – If
id_or_idxis a name and the node is not found.EngineError – On C API failure.
- analyze_pattern_impact(id_or_idx)#
Preview which objects reference a time pattern.
- Parameters:
- Return type:
- analyze_pollutant_impact(id_or_idx)#
Preview which objects reference a pollutant.
- Parameters:
- Return type:
- analyze_snowpack_impact(id_or_idx)#
Preview which subcatchments reference a snowpack.
- Parameters:
- Return type:
- analyze_street_impact(id_or_idx)#
Preview which inlet-usage rows reference a street.
- Parameters:
- Return type:
- 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
ImpactEntrydescribing what would be affected.- Return type:
list[
ImpactEntry]- Raises:
KeyError – If
id_or_idxis 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:
- Returns:
List of
ImpactEntrydescribing what would be affected.- Return type:
list[
ImpactEntry]- Raises:
KeyError – If
id_or_idxis 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
ImpactEntrydescribing what would be affected.- Return type:
list[
ImpactEntry]- Raises:
EngineError – On C API failure.
- convert_link(id_or_idx, new_type)#
Convert a link to a different type in place.
- Parameters:
- Returns:
ConversionResultwith cleared fields and warnings.- Return type:
L{ConversionResult}
- Raises:
RuntimeError – If not in
BUILDINGorOPENEDstate, the type is invalid, ornew_typeequals the current type.KeyError – If
id_or_idxis 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:
- Returns:
ConversionResultwith cleared fields and warnings.- Return type:
L{ConversionResult}
- Raises:
RuntimeError – If not in
BUILDINGorOPENEDstate, the type is invalid, ornew_typeequals the current type.KeyError – If
id_or_idxis a name and the node is not found.EngineError – On C API failure.
@see: L{openswmm.engine.NodeType}
- convert_types(nodes, target, indices, apply=True, design=-1, capture=-1, placement=0)#
Preview or convert several nodes or links to one type.
- Parameters:
nodes (bool) –
Trueto convert nodes,Falseto convert links.target (int) – Target type code; for nodes 4 is a virtual junction and 5 an inlet junction.
indices (sequence of int) – Unique zero-based object indices.
apply (bool) –
Falseonly reports what would happen.design (int) – Inlet design index for target 5 (-2 previews topology).
capture (int) – Capture node index for target 5.
placement (int) – Inlet placement code for target 5.
- Returns:
One
TypeChangeper index, in order.- Return type:
list[
TypeChange]- Raises:
RuntimeError – If not in
BUILDINGorOPENEDstate.EngineError – On C API failure.
- delete_aquifer(id_or_idx)#
Delete an aquifer; referencing subcatchments lose groundwater.
- Parameters:
- Return type:
- delete_gage(id_or_idx)#
Delete a rain gage and nullify subcatchment gage references.
- Parameters:
- Returns:
List of
ImpactEntrydescribing what was affected.- Return type:
list[
ImpactEntry]- Raises:
RuntimeError – If not in
BUILDINGorOPENEDstate.KeyError – If
id_or_idxis a name and the gage is not found.EngineError – On C API failure.
- delete_gage_recorded(id_or_idx)#
Delete a rain gage as
delete_gagedoes, and record how to undo it, including the subcatchment references the delete cleared.- Parameters:
id_or_idx (int | str) – Gage name (
str) or zero-based index (int).- Returns:
(impacts, record), as fordelete_node_recorded.- Return type:
- delete_gages_recorded(keys)#
Delete a batch as
delete_gagesdoes, and record how to undo the whole batch. Seedelete_nodes_recorded.- Parameters:
- Return type:
- delete_hydrograph(uh_name)#
Delete a unit-hydrograph group by name.
- Parameters:
uh_name (str)
- Return type:
- delete_inlet(id_or_idx)#
Delete an inlet design; cascade-delete referencing inlet-usage rows.
- Parameters:
- Return type:
- delete_landuse(id_or_idx)#
Delete a land use; re-pack buildup/washoff and coverage columns.
- Parameters:
- Return type:
- delete_lid(id_or_idx)#
Delete a LID control; cascade-delete referencing LID-usage rows.
- Parameters:
- Return type:
- delete_link(id_or_idx)#
Delete a link and cascade-delete or nullify referencing objects.
- Parameters:
- Returns:
List of
ImpactEntrydescribing what was affected.- Return type:
list[
ImpactEntry]- Raises:
RuntimeError – If not in
BUILDINGorOPENEDstate.KeyError – If
id_or_idxis a name and the link is not found.EngineError – On C API failure.
- delete_link_recorded(id_or_idx)#
Delete a link as
delete_linkdoes, and record how to undo it.- Parameters:
id_or_idx (int | str) – Link name (
str) or zero-based index (int).- Returns:
(impacts, record), as fordelete_node_recorded.- Return type:
- delete_links_recorded(keys)#
Delete a batch as
delete_linksdoes, and record how to undo the whole batch. Seedelete_nodes_recorded.- Parameters:
- Return type:
- delete_node(id_or_idx)#
Delete a node and cascade-delete or nullify all referencing objects.
- Parameters:
- Returns:
List of
ImpactEntrydescribing what was affected.- Return type:
list[
ImpactEntry]- Raises:
RuntimeError – If not in
BUILDINGorOPENEDstate.KeyError – If
id_or_idxis a name and the node is not found.EngineError – On C API failure.
- delete_node_recorded(id_or_idx)#
Delete a node as
delete_nodedoes, and record how to undo it.The record covers the node’s row, subtype and 2D coupling rows, name and coordinates, every link it cascade-deletes, its inlet usages, inflow, DWF and RDII rows, treatment, reaction rows, initial quality, user flags and heat overrides, and every reference the delete cleared or renumbered.
- Parameters:
id_or_idx (int | str) – Node name (
str) or zero-based index (int).- Returns:
(impacts, record): the cascade report, as fromdelete_node, and theDeleteRecordthat undoes the delete.- Raises:
KeyError – If
id_or_idxis a name and the node is not found.EngineError – On C API failure, such as an engine that is not in
BUILDINGorOPENEDstate.
- Return type:
- delete_nodes_recorded(keys)#
Delete a batch as
delete_nodesdoes, and record how to undo the whole batch: oneDeleteRecordrestores every node at its original index. An empty batch returns a record whose restore does nothing.
- delete_pattern(id_or_idx)#
Delete a time pattern and clear all name-based references.
- Parameters:
- Return type:
- delete_pollutant(id_or_idx)#
Delete a pollutant and re-pack every per-pollutant matrix.
- Parameters:
- Return type:
- delete_snowpack(id_or_idx)#
Delete a snowpack; clear referencing subcatchments and renumber.
- Parameters:
- Return type:
- delete_street(id_or_idx)#
Delete a street; cascade-delete referencing inlet-usage rows.
- Parameters:
- Return type:
- 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
ImpactEntrydescribing what was affected.- Return type:
list[
ImpactEntry]- Raises:
RuntimeError – If not in
BUILDINGorOPENEDstate.KeyError – If
id_or_idxis a name and the subcatchment is not found.EngineError – On C API failure.
- delete_subcatch_recorded(id_or_idx)#
Delete a subcatchment as
delete_subcatchdoes, and record how to undo it.- Parameters:
id_or_idx (int | str) – Subcatchment name (
str) or zero-based index (int).- Returns:
(impacts, record), as fordelete_node_recorded.- Return type:
- delete_subcatchments_recorded(keys)#
Delete a batch as
delete_subcatchmentsdoes, and record how to undo the whole batch. Seedelete_nodes_recorded.- Parameters:
- Return type:
- delete_table(id_or_idx)#
Delete a time series or curve and nullify all referencing objects.
- Parameters:
- Returns:
List of
ImpactEntrydescribing what was affected.- Return type:
list[
ImpactEntry]- Raises:
RuntimeError – If not in
BUILDINGorOPENEDstate.KeyError – If
id_or_idxis a name and the table is not found.EngineError – On C API failure.
- delete_transect(idx)#
Delete a transect and reset referencing conduit cross-sections.
- Parameters:
idx (int) – Zero-based transect index.
- Returns:
List of
ImpactEntrydescribing what was affected.- Return type:
list[
ImpactEntry]- Raises:
RuntimeError – If not in
BUILDINGorOPENEDstate.EngineError – On C API failure.
- fuse_inlet_junction(id_or_idx)#
Re-fuse the two conduits of an inlet junction into one.
- Parameters:
- Returns:
Index of the surviving conduit AFTER deletions renumber.
- Return type:
- Raises:
KeyError – If
id_or_idxis a name and the node is not found.EngineError – If the node is not a two-conduit through junction, or on C API failure.
- fuse_virtual_junction(id_or_idx)#
Re-fuse the two conduits of a virtual junction into one.
- Parameters:
- Returns:
Index of the surviving conduit AFTER deletions renumber.
- Return type:
- Raises:
KeyError – If
id_or_idxis a name and the node is not found.EngineError – If the node is not a two-conduit through virtual junction, or on C API failure.
- property gage_count: int#
Current number of rain gages in the model.
- Returns:
Gage count.
- Return type:
- set_node_inlet(id_or_idx, make_inlet=True)#
Promote a node to an inlet junction, or demote it back.
- Parameters:
- Raises:
KeyError – If
id_or_idxis a name and the node is not found.EngineError – On a violated usage rule or C API failure.
- Return type:
None
- set_node_virtual(id_or_idx, make_virtual=True)#
Set or clear a node’s virtual-junction flag (validated).
- Parameters:
- Raises:
KeyError – If
id_or_idxis a name and the node is not found.EngineError – On a violated usage rule or C API failure.
- Return type:
None
- split_conduit(id_or_idx, t, new_node_name, new_link_name, make_virtual=False)#
Split a conduit at normalized position
t, inserting a new node.- Parameters:
- Returns:
(new_node_index, new_link_index).- Return type:
- Raises:
KeyError – If
id_or_idxis a name and the link is not found.EngineError – On invalid parameters or a rule failure.
- split_conduit_inlet(id_or_idx, t, new_node_name, new_link_name, inlet_id, capture_node)#
Split a street conduit, inserting an inlet junction.
- Parameters:
t (float) – Normalized split position, exclusive (0, 1).
new_node_name (str) – Unique name for the inserted inlet junction.
new_link_name (str) – Unique name for the new downstream conduit.
inlet_id (str) – Name of an existing
[INLETS]design.capture_node (str) – Name of the receiving (underdrain) node.
- Returns:
(new_node_index, new_link_index).- Return type:
- Raises:
KeyError – If
id_or_idxis a name and the link is not found.EngineError – On invalid parameters or a rule failure.
- property subcatch_count: int#
Current number of subcatchments in the model.
- Returns:
Subcatchment count.
- Return type:
- class TypeChange(source_type, status, dependency_node, details)#
Bases:
objectOne object’s outcome in a batch conversion.
- Variables:
source_type – Type before the call (nodes: 4 virtual, 5 inlet; -1 bad index).
status – 0, or the engine error code of the refusal.
dependency_node – Related node index behind a refusal, or -1.
details –
ConversionResultof an applied conversion.
- Parameters:
source_type (int)
status (int)
dependency_node (int)
details (ConversionResult)
- details: ConversionResult#
Nodes#
Node access (Pythonic v1 surface)#
- author:
Caleb Buahin
- copyright:
Copyright (c) 2026 Caleb Buahin
- license:
Apache-2.0
Type stubs for openswmm.engine._nodes.
- class Node(solver, index)#
Bases:
objectSingle-node wrapper. See
Nodesfor the collection.- set_quality_mass_flux(pollutant, mass_rate)#
- type: NodeType#
- stats: NodeStatsView#
- storage: StorageView#
- outfall: OutfallView#
- divider: DividerView#
- class Nodes(solver)#
Bases:
objectIndexable, iterable collection of
Nodewrappers.- Parameters:
solver (Solver)
Links#
Link access (Pythonic v1 surface)#
- author:
Caleb Buahin
- copyright:
Copyright (c) 2026 Caleb Buahin
- license:
Apache-2.0
Type stubs for openswmm.engine._links.
- class Link(solver, index)#
Bases:
objectSingle-link wrapper. See
Linksfor the collection.- set_nodes(from_node, to_node)#
- type: LinkType#
- stats: LinkStatsView#
- orifice: OrificeView#
- outlet: OutletView#
- class Links(solver)#
Bases:
objectIndexable, iterable collection of
Linkwrappers.- Parameters:
solver (Solver)
- get_xsect_info(key)#
- Parameters:
- Return type:
Cross-Section Geometry#
Type stubs for openswmm.engine._xsect.
- class XSectionGeometry(shape, geom1, geom2=Ellipsis, geom3=Ellipsis, geom4=Ellipsis, *, units)#
Bases:
object- Parameters:
- area(**kwds)#
Helper for @overload to raise when called.
- area_from_section_factor(**kwds)#
Helper for @overload to raise when called.
- critical_depth(**kwds)#
Helper for @overload to raise when called.
- depth_from_area(**kwds)#
Helper for @overload to raise when called.
- dsda(**kwds)#
Helper for @overload to raise when called.
- classmethod from_curve(full_depth, curve_depths, curve_widths, *, units)#
- classmethod from_street(width, curb_height, slope, roughness, *, gutter_depression=Ellipsis, gutter_width=Ellipsis, sides=Ellipsis, back_width=Ellipsis, back_slope=Ellipsis, back_roughness=Ellipsis, units)#
- classmethod from_transect(stations, elevations, *, left_bank, right_bank, n_channel, n_left=Ellipsis, n_right=Ellipsis, length_factor=Ellipsis, units)#
- hyd_radius(**kwds)#
Helper for @overload to raise when called.
- hyd_radius_from_area(**kwds)#
Helper for @overload to raise when called.
- section_factor(**kwds)#
Helper for @overload to raise when called.
- width(**kwds)#
Helper for @overload to raise when called.
- shape: XSectShape#
Cross-Section Geometry#
- author:
Caleb Buahin
- copyright:
Copyright (c) 2026 Caleb Buahin
- license:
Apache-2.0
Provides the CrossSection dataclass, which wraps the raw
(shape, geom1, geom2, geom3, geom4) tuple a link reports with
human-readable field labels and a shape_name derived from the
XSectShape enum.
Obtain one from Links.get_xsect_info() or link.xsect.info(). For the
hydraulic geometry of a section — area, top width, hydraulic radius, critical
depth — see XSectionGeometry instead.
Example:
from openswmm.engine import Solver, Links, CrossSection
with Solver("model.inp", "model.rpt", "model.out") as s:
links = Links(s)
xs = links.get_xsect_info(0)
print(xs.shape_name) # "CIRCULAR"
print(xs.geom_labels) # {"diameter": 1.2}
- class CrossSection(shape, shape_name, geom1, geom2, geom3, geom4)[source]#
Bases:
objectStructured cross-section geometry returned by
Links.get_xsect_info().All four
geomvalues are always present; unused parameters are0.0. Usegeom_labelsto get a{label: value}dict that filters out unused (zero) parameters and names each one meaningfully.- Variables:
shape – Integer cross-section shape code (see
XSectShape).shape_name – Human-readable name, e.g.
"CIRCULAR".geom1 – First geometry parameter (meaning depends on shape).
geom2 – Second geometry parameter (or 0.0 if unused).
geom3 – Third geometry parameter (or 0.0 if unused).
geom4 – Fourth geometry parameter (or 0.0 if unused).
- Parameters:
Subcatchments#
Subcatchment access (Pythonic v1 surface)#
- author:
Caleb Buahin
- copyright:
Copyright (c) 2026 Caleb Buahin
- license:
Apache-2.0
Type stubs for openswmm.engine._subcatchments.
- class Aquifers#
Bases:
objectName-keyed collection of
[AQUIFERS]entries (solver.aquifers).- get_param(aquifer, param)#
- set_evap_pattern(aquifer, name)#
- class CoverageView(sub)#
Bases:
MutableMapping[str,float]- Parameters:
sub (Subcatchment)
- class GroundwaterParams(surf_elev, a1, b1, a2, b2, a3, tw, hstar)#
Bases:
NamedTupleCreate new instance of GroundwaterParams(surf_elev, a1, b1, a2, b2, a3, tw, hstar)
- Parameters:
- class InfiltrationView#
Bases:
object- set_green_ampt(suction, conductivity, initial_deficit)#
- set_horton(f0, fmin, decay, dry_time)#
- model: InfilModel#
- class LoadingsView(sub)#
Bases:
MutableMapping[str,float]Pollutant or species id -> initial buildup on a subcatchment.
- Parameters:
sub (Subcatchment)
- class Snowpacks#
Bases:
objectName-keyed collection of
[SNOWPACKS]entries (solver.snowpacks).- set_impervious(snowpack, *, cmin, cmax, tbase, fwfrac, sd0, fw0, last)#
- set_pervious(snowpack, *, cmin, cmax, tbase, fwfrac, sd0, fw0, last)#
- set_plowable(snowpack, *, cmin, cmax, tbase, fwfrac, sd0, fw0, last)#
- set_removal(snowpack, *, dsnow, fout, fimp, fperv, fimelt, fsubcatch)#
- class Subcatchment(solver, index)#
Bases:
objectSingle-subcatchment wrapper. See
Subcatchments.- set_gw_params(surf_elev, a1, b1, a2, b2, a3, tw, hstar)#
- set_gw_state(theta=Ellipsis, lower_depth=Ellipsis)#
- set_outlet_subcatchment(sub)#
- Parameters:
sub (Subcatchment | int | str)
- Return type:
None
- set_ponded_quality(pollutant, mass)#
- set_snow_state(surface, swe=Ellipsis, fw=Ellipsis, ati=Ellipsis, coldc=Ellipsis)#
- loadings: LoadingsView#
- outlet: Node | Subcatchment | None#
- gw_params: GroundwaterParams#
- stats: SubcatchmentStatsView#
- infiltration: InfiltrationView#
- coverage: CoverageView#
Rain gages#
Rain gage access (Pythonic v1 surface)#
- author:
Caleb Buahin
- copyright:
Copyright (c) 2026 Caleb Buahin
- license:
Apache-2.0
Type stubs for openswmm.engine._gages.
- class Gage(solver, index)#
Bases:
object- set_file(path, station_id, column=Ellipsis)#
- rain_type: GageRainType#
- data_source: GageDataSource#
External inflows (DWF, RDII, time-series)#
Type stubs for openswmm.engine._inflows.
- class HydrographEntry(uh_name, month, response, r, t, k, dmax, drecov, dinit)#
Bases:
NamedTupleCreate new instance of HydrographEntry(uh_name, month, response, r, t, k, dmax, drecov, dinit)
- Parameters:
- class HydrographGageEntry(uh_name, gage_name)#
Bases:
NamedTupleCreate new instance of HydrographGageEntry(uh_name, gage_name)
- class Inflows(solver)#
Bases:
object- Parameters:
solver (Solver)
- add_dwf(node, constituent, *, avg_value=Ellipsis, monthly_pattern=Ellipsis, daily_pattern=Ellipsis, hourly_pattern=Ellipsis, weekend_pattern=Ellipsis)#
- add_external(node, constituent, *, ts_name=Ellipsis, type=Ellipsis, m_factor=Ellipsis, s_factor=Ellipsis, baseline=Ellipsis, pattern=Ellipsis)#
- add_hydrograph(uh_name, month, response, r, t, k, *, dmax=Ellipsis, drecov=Ellipsis, dinit=Ellipsis)#
- add_hydrograph_gage(uh_name, gage_name)#
- add_rdii(node, uh_name, area)#
- add_rdii_decay(uh_name, response, k_dep, k_0, k_T, T_ref, theta_rec, T_freeze, snow_on=Ellipsis, snow_T=Ellipsis, snow_ddf=Ellipsis)#
- get_dwf(entry_idx)#
- get_external(entry_idx)#
- remove_hydrograph_entry(uh_name, month, response)#
- set_dwf_baseline(entry_idx, avg_value)#
- set_external_baseline(entry_idx, baseline)#
- set_hydrograph_gage(uh_name, gage_name)#
- set_hydrograph_ia(uh_name, month, response, dmax, drecov, dinit)#
- set_hydrograph_rtk(uh_name, month, response, r, t, k)#
- set_rdii_decay(uh_name, response, k_dep, k_0, k_T, T_ref, theta_rec, T_freeze, snow_on=Ellipsis, snow_T=Ellipsis, snow_ddf=Ellipsis)#
- class RDIIDecayEntry(uh_name, response, k_dep, k_0, k_T, T_ref, theta_rec, T_freeze, snow_on, snow_T, snow_ddf)#
Bases:
NamedTupleCreate new instance of RDIIDecayEntry(uh_name, response, k_dep, k_0, k_T, T_ref, theta_rec, T_freeze, snow_on, snow_T, snow_ddf)
- Parameters:
Advanced forcing (mode + persistence)#
Type stubs for openswmm.engine._forcing.
- class Forcing(solver)#
Bases:
object- Parameters:
solver (Solver)
- clear_all()#
- Return type:
None
- climate_evap(value, *, mode=Ellipsis, persist=Ellipsis)#
- climate_temperature(value, *, mode=Ellipsis, persist=Ellipsis)#
- climate_wind(value, *, mode=Ellipsis, persist=Ellipsis)#
- element_climate(kind, element, variable, value, *, mode=Ellipsis, persist=Ellipsis)#
- element_climate_get(kind, element, variable)#
- gage_rainfall(gage, value, *, mode=Ellipsis, persist=Ellipsis)#
- link_flow(link, value, *, mode=Ellipsis, persist=Ellipsis)#
- link_quality(link, pollutant, value, *, mode=Ellipsis, persist=Ellipsis)#
- link_seepage(link, value, *, mode=Ellipsis, persist=Ellipsis)#
- link_setting(link, value, *, mode=Ellipsis, persist=Ellipsis)#
- node_age(node, value, *, mode=Ellipsis, persist=Ellipsis)#
- node_head_boundary(node, value, *, mode=Ellipsis, persist=Ellipsis)#
- node_lat_inflow(node, value, *, mode=Ellipsis, persist=Ellipsis)#
- node_quality(node, pollutant, mass_rate, *, mode=Ellipsis, persist=Ellipsis)#
- node_temperature(node, value, *, mode=Ellipsis, persist=Ellipsis)#
- subcatchment_evap(sub, value, *, mode=Ellipsis, persist=Ellipsis)#
- subcatchment_rainfall(sub, value, *, mode=Ellipsis, persist=Ellipsis)#
Climate (temperature, evaporation, wind, snowmelt, adjustments)#
Type stubs for openswmm.engine._climate.
Control rules#
Type stubs for openswmm.engine._controls.
- class ControlRule(id, text)#
Bases:
NamedTupleCreate new instance of ControlRule(id, text)
- class Controls(solver)#
Bases:
MutableSequence[ControlRule]- Parameters:
solver (Solver)
- append(value)#
S.append(value) – append value to the end of the sequence
- Parameters:
value (Any)
- Return type:
None
- clear() None -- remove all items from S#
- Return type:
None
- insert(idx, value)#
S.insert(index, value) – insert value before index
- replace_program(blocks, *, publish=Ellipsis)#
- Parameters:
blocks (Iterable[str | ControlRule])
publish (bool)
- Return type:
None
Pollutants#
Type stubs for openswmm.engine._pollutants.
- class Pollutant(solver, index)#
Bases:
object- set_co_pollutant(co, fraction)#
- units: ConcentrationUnits#
Water quality (landuse, buildup, washoff, treatment)#
Type stubs for openswmm.engine._quality.
- class Quality(solver)#
Bases:
object- Parameters:
solver (Solver)
- clear_treatment(node, pollutant)#
- get_buildup(landuse, pollutant)#
- get_washoff(landuse, pollutant)#
- set_buildup(landuse, pollutant, *, func, c1, c2, c3, normalizer=Ellipsis)#
- set_treatment(node, pollutant, expression)#
- set_washoff(landuse, pollutant, *, func, coeff, expon, sweep_effic=Ellipsis, bmp_effic=Ellipsis)#
- validate_treatment_expression(expression)#
Initial quality (per-element starting concentrations)#
Type stubs for openswmm.engine._initial_quality.
- class InitialQuality(solver)#
Bases:
object- Parameters:
solver (Solver)
- set(constituent, value, *, node=Ellipsis, link=Ellipsis)#
- class InitialQualityEntry(is_link, elem_index, constituent, value)#
Bases:
NamedTupleCreate new instance of InitialQualityEntry(is_link, elem_index, constituent, value)
Reactions (multi-species reaction system)#
Type stubs for openswmm.engine._reactions.
- class ExpressionDiagnostic(valid, message, column)#
Bases:
NamedTupleCreate new instance of ExpressionDiagnostic(valid, message, column)
- class ReactionFunction(name, arity)#
Bases:
NamedTupleCreate new instance of ReactionFunction(name, arity)
- class ReactionHydVar(name, description)#
Bases:
NamedTupleCreate new instance of ReactionHydVar(name, description)
- class ReactionInitialEntry(is_link, elem_index, species_index, value)#
Bases:
NamedTupleCreate new instance of ReactionInitialEntry(is_link, elem_index, species_index, value)
- class ReactionSpecies(solver, index)#
Bases:
object
- class Reactions(solver)#
Bases:
object- Parameters:
solver (Solver)
- static functions()#
- Return type:
- static hydraulic_variables()#
- Return type:
Tuple[ReactionHydVar, …]
- species: _SpeciesCollection#
- coefficients: _CoefficientCollection#
- terms: _TermCollection#
- initial: _InitialQualityRows#
Process components ([PROCESS_COMPONENTS] registrations)#
- class ComponentLibrary(id, caption, version, path, kind, stamp, load_error)#
Bases:
NamedTupleA HydroCouple component library the engine discovered.
Create new instance of ComponentLibrary(id, caption, version, path, kind, stamp, load_error)
- class KnownProcessComponent(id, description, implemented)#
Bases:
NamedTupleCreate new instance of KnownProcessComponent(id, description, implemented)
- class ProcessComponent(component_index, id, config, resolved)#
Bases:
NamedTupleCreate new instance of ProcessComponent(component_index, id, config, resolved)
- class ProcessComponents(solver)#
Bases:
object- Parameters:
solver (Solver)
- static add_search_path(directory)#
Scan directory for component libraries now, and keep it.
- static known()#
- Return type:
- static libraries()#
HydroCouple component libraries found on the search path, refused ones included (with the reason in
load_error).- Return type:
- register(component_id, config_path=Ellipsis)#
- Parameters:
- Return type:
Water age (source ages and node overrides)#
Type stubs for openswmm.engine._water_age.
- class WaterAge(solver)#
Bases:
object- Parameters:
solver (Solver)
- globals: _WaterAgeGlobals#
- node_overrides: _WaterAgeOverrides#
- class WaterAgeOverride(source, node_index, hours)#
Bases:
NamedTupleCreate new instance of WaterAgeOverride(source, node_index, hours)
- source: WaterAgeSource#
Alias for field number 0
Heat transport (fluxes, solar, cloud, heat sources)#
Type stubs for openswmm.engine._heat.
- class Heat(solver)#
Bases:
object- Parameters:
solver (Solver)
- channel_ground_values(kind, first_link, count)#
- effective_element(attr, scope, name)#
- ground_layers(cell, kind, first_layer, count)#
- ground_values(kind, first_cell, count)#
- property lid_material: HeatLidMaterial#
- mesh_values(kind, first_cell, count)#
- preview_channel_ground_map(link, *, first=Ellipsis, limit=Ellipsis, progress=Ellipsis)#
- modules: _HeatModules#
- radiative: _HeatRadiative#
- shortwave_mode: HeatShortwaveMode#
- solar: _HeatSolar#
- cloud: _HeatCloud#
- sources: _HeatSources#
- node_overrides: _HeatNodeOverrides#
- sediment: _HeatSediment#
- element_overrides: _HeatElementOverrides#
- class HeatElementOverride(attr, scope, name, value)#
Bases:
NamedTupleCreate new instance of HeatElementOverride(attr, scope, name, value)
- attr: HeatAttr#
Alias for field number 0
- scope: HeatOverrideScope#
Alias for field number 1
- class HeatElementValue(value, source, source_name)#
Bases:
NamedTupleCreate new instance of HeatElementValue(value, source, source_name)
- class HeatLidMaterial(water_conductivity, soil_conductivity, soil_density, soil_specific_heat)#
Bases:
NamedTupleCreate new instance of HeatLidMaterial(water_conductivity, soil_conductivity, soil_density, soil_specific_heat)
- Parameters:
- class HeatNodeOverride(source, node_index, temp_c)#
Bases:
NamedTupleCreate new instance of HeatNodeOverride(source, node_index, temp_c)
- source: HeatSourceKind#
Alias for field number 0
Tables (time series, curves, patterns)#
Type stubs for openswmm.engine._tables.
- class Curve(solver, index)#
Bases:
_PointTable
- class Tables(solver)#
Bases:
object- Parameters:
solver (Solver)
- add_curve(curve_id, curve_type=Ellipsis)#
- as_timeseries(key)#
- Parameters:
- Return type:
- get_type(key)#
The type of a table (time series vs. curve kind) as a
TableType.
- class TimeSeries(solver, index)#
Bases:
_PointTable
Infrastructure (transects, streets, inlets, LIDs)#
Type stubs for openswmm.engine._infrastructure.
- class Infrastructure(solver)#
Bases:
object- Parameters:
solver (Solver)
- inlet_usages: InletUsages#
- class InletUsages(solver)#
Bases:
object- Parameters:
solver (Solver)
- set(host_kind, host_idx, design_idx, capture_node_idx, *, num_inlets=Ellipsis, pct_clogged=Ellipsis, flow_limit=Ellipsis, local_depress=Ellipsis, local_width=Ellipsis, placement=Ellipsis)#
- class Inlets(solver)#
Bases:
object- Parameters:
solver (Solver)
- set_design(key, design=Ellipsis, **kwargs)#
- set_params(idx, *, length=Ellipsis, width=Ellipsis, grate_type=Ellipsis, open_area=Ellipsis, splash_veloc=Ellipsis)#
- class LIDs(solver)#
Bases:
object- Parameters:
solver (Solver)
- assign_node(node, control, *, initial_saturation=Ellipsis)#
- prepare_node(node, control, *, initial_saturation=Ellipsis, bottom=Ellipsis)#
- replace_node(node, snapshot)#
- replace_usages(subcatchment, records)#
- set_drain(idx, *, coeff, expon, offset)#
- set_drainmat(idx, *, thick, void_frac, roughness)#
- set_layers(key, layers, *, treatments=None, flow=None, materials=None)#
- set_outlet_anchor(link, layer, *, position=Ellipsis)#
- set_pavement(idx, *, thick, void_ratio, frac_imperv, ksat, clog_factor=Ellipsis, regen_days=Ellipsis, regen_degree=Ellipsis)#
- set_removal(idx, constituent, percent)#
- set_soil(idx, *, thick, porosity, fc, wp, ksat, kslope)#
- set_storage(idx, *, thick, void_frac, ksat)#
- set_surface(idx, *, storage, roughness, slope)#
- usage_add(subcatchment, lid, *, number, area, width, init_sat=Ellipsis, from_imperv=Ellipsis)#
- validate_layers(key, layers, *, flow, treatments=Ellipsis, materials=Ellipsis)#
- validate_node(node, snapshot)#
- class Streets(solver)#
Bases:
object- Parameters:
solver (Solver)
- get_params(idx)#
Read back a street cross-section’s geometric parameters.
- Returns:
Keys
t_crown,h_curb,sx,n_road,gutter_depres,gutter_width,sides,back_width,back_slope,back_n(the inverse ofset_params).- Return type:
- Parameters:
idx (int)
- set_params(idx, *, t_crown, h_curb, sx, n_road, gutter_depres=Ellipsis, gutter_width=Ellipsis, sides=Ellipsis, back_width=Ellipsis, back_slope=Ellipsis, back_n=Ellipsis)#
- class Transects(solver)#
Bases:
object- Parameters:
solver (Solver)
- add_station(idx, station, elevation)#
- get_station(idx, station_idx)#
- set_bank_stations(idx, left, right)#
- set_encroachment_stations(idx, left, right)#
- set_modifiers(idx, n_factor, x_factor, y_factor)#
- set_roughness(idx, n_left, n_right, n_channel)#
Hot start#
Hot start files (Pythonic v1 surface)#
Type stubs for openswmm.engine._hotstart.
- class HotStart#
Bases:
object- close()#
- Return type:
None
- property contents: tuple[str, ...]#
"SPECIES","GROUNDWATER","GW_TRANSPORT","SNOW","LID","SURFACE","ENGINE_CHECKPOINT"and"LEGACY".- Type:
State blocks the file holds
- property end_datetime: datetime | None#
End date and time of the saving run, or
Nonefor a legacy file.
- link_records()#
Every stored link record, in file order.
- Return type:
- node_records()#
Every stored node record, in file order.
- Return type:
- classmethod open_legacy(model, path)#
Open a legacy EPA SWMM 5 hot-start file for inspection.
The file is read against
model(OPENED or later): its subcatchment, node, link and pollutant counts must match, and records take the model’s names. The handle is read-only; the model is not changed. RaisesHotStartErrorwhen the file cannot be read, is not a legacy file or was written for another model.
- static save_from(solver, path)#
- set_link_state(link_id, flow, depth)#
Set a link’s flow (ft3/s) and depth (ft) so a restart derives its volume; written to the file on
close().
- set_node_state(node_id, depth)#
Set a node’s depth (ft) so a restart derives its head and volume; written to the file on
close().
- property sim_datetime: datetime#
the saving run’s start date plus the elapsed simulation time.
- Type:
Simulation moment at which the hot-start state was captured
- subcatchment_records()#
Every stored subcatchment record, in file order.
- Return type:
- class HotStartLinkRecord(id, flow, depth, volume, age, concentrations)#
Bases:
NamedTupleOne link record stored in a hot-start file, in internal units.
flowin ft3/s (signed in link orientation),depthin ft,volumein ft3 (NaN when not stored or marked to be derived byHotStart.set_link_state()),agein seconds (negative when not tracked).concentrationsholds one value perHotStart.species.Create new instance of HotStartLinkRecord(id, flow, depth, volume, age, concentrations)
- Parameters:
- class HotStartNodeRecord(id, depth, head, volume, age, concentrations)#
Bases:
NamedTupleOne node record stored in a hot-start file, in internal units.
depthandheadin ft,volumein ft3,agein seconds (negative when water age is not tracked).headandvolumeare NaN when the file does not store them (a legacy file) or whenHotStart.set_node_state()marked them to be derived at restart.concentrationsholds one value perHotStart.species.Create new instance of HotStartNodeRecord(id, depth, head, volume, age, concentrations)
- Parameters:
- class HotStartSubcatchmentRecord(id, runoff, gw_flow, gw_upper_moisture, gw_lower_depth)#
Bases:
NamedTupleOne subcatchment record stored in a hot-start file, in internal units.
runoffandgw_flowin ft3/s,gw_upper_moistureas a fraction,gw_lower_depthin ft. A value the file does not hold is NaN.Create new instance of HotStartSubcatchmentRecord(id, runoff, gw_flow, gw_upper_moisture, gw_lower_depth)
- Parameters:
- class SaveSchedule(solver)#
Bases:
MutableSequence[SaveScheduleEntry]- Parameters:
solver (Solver)
- append(value)#
S.append(value) – append value to the end of the sequence
- Parameters:
value (Any)
- Return type:
None
- clear() None -- remove all items from S#
- Return type:
None
- get_format(idx)#
File format of entry idx:
"AUTO","LEGACY"or"NATIVE".
- insert(idx, value)#
S.insert(index, value) – insert value before index
- legacy_omits()#
Model state a legacy SWMM5 file has no place for and NATIVE keeps.
Mass balance#
Mass balance & continuity (Pythonic v1 surface)#
Type stubs for openswmm.engine._massbalance.
- class MassBalance(solver)#
Bases:
object- Parameters:
solver (Solver)
- property routing_continuity_error: float#
Flow-routing continuity (mass-balance) error, as a percentage.
- property routing_diagnostics: RoutingDiagnostics#
Routing-solver time-step diagnostics (step sizes, Courant number, convergence counts) as a
RoutingDiagnosticsrecord.
Statistics#
Simulation statistics (Pythonic v1 surface)#
Type stubs for openswmm.engine._statistics.
- class ReportTable(table, title, columns, rows, values)#
Bases:
NamedTupleOne report summary table;
valuesis (rows, columns), NaN where blank.Create new instance of ReportTable(table, title, columns, rows, values)
- Parameters:
table (SummaryTable)
title (str)
columns (List[SummaryColumn])
rows (List[SummaryRow])
values (NDArray[Any])
- columns: List[SummaryColumn]#
Alias for field number 2
- rows: List[SummaryRow]#
Alias for field number 3
- table: SummaryTable#
Alias for field number 0
- class Statistics(solver)#
Bases:
object- Parameters:
solver (Solver)
- property node_max_overflow: NDArray[Any]#
Maximum overflow (flooding) rate at each node, in project units.
- property subcatchment_max_runoff: NDArray[Any]#
Peak runoff rate from each subcatchment, in project units.
- property subcatchment_precip: NDArray[Any]#
Cumulative precipitation depth per subcatchment, in project depth units (in for US, mm for SI). The only statistic without a C
_bulkcompanion; gathered scalar-wise in anogilloop.
- property subcatchment_runoff_vol: NDArray[Any]#
Cumulative runoff volume from each subcatchment, in project units.
- summary_row_at(table, row)#
Identify one row of a summary table.
- Parameters:
- Return type:
- summary_table(table)#
Read one report summary table (Node Depth, Outfall Loading, Pumping, …).
- Parameters:
table (SummaryTable | int)
- Return type:
- summary_tables()#
Read every report summary table, in report order.
- Return type:
- class SummaryColumn(name, units)#
Bases:
NamedTupleOne value column of a report summary table.
Create new instance of SummaryColumn(name, units)
- class SummaryRow(object_type, object_index, label)#
Bases:
NamedTupleThe object one summary-table row describes (
object_index-1 for SYSTEM).Create new instance of SummaryRow(object_type, object_index, label)
- object_type: SummaryObject#
Alias for field number 0
Offline flow tracing#
Flow tracing over hydraulic output or supplied hydraulic averages.
All dimensional quantities are SI. Travel times are passage-weighted estimates under frozen average flows, not particle arrival times. A handle owns its inputs and supports the context-manager protocol.
- class FlowTracer(nodes, links, *, options=None)#
Bases:
objectIndependent tracing handle; close explicitly or use a with block.
- Parameters:
nodes (Iterable[TraceNode])
links (Iterable[TraceLink])
options (TraceOptions | None)
- property averages: tuple[tuple[TraceNodeAverage, ...], tuple[TraceLinkAverage, ...]]#
- close()#
- Return type:
None
- static default_options()#
- Return type:
- estimate(seed, direction=TraceDirection.DOWNSTREAM, *, progress=None)#
- prepare(output_path, *, cache_path=None, fingerprint=None, progress=None)#
- prepare_live(output_path, *, progress=None)#
- set_averages(nodes, links, *, info=None)#
- Parameters:
nodes (Iterable[TraceNodeAverage])
links (Iterable[TraceLinkAverage])
info (TraceInfo | None)
- Return type:
None
- exception TraceError(code, message)#
Bases:
RuntimeError- Parameters:
code (TraceStatus)
message (str)
- Return type:
None
- code: TraceStatus#
- class TraceInfo(schema_version=0, algorithm_version=0, node_count=0, link_count=0, periods=0, source_flow_units=0, cache_loaded=0, first_report_date=0.0, last_report_date=0.0, duration_s=0.0)#
Bases:
objectScan metadata; report dates use the native OLE Automation day representation.
- Parameters:
- class TraceLink(id='', from_node=0, to_node=0, type=LinkType.CONDUIT, length_m=0.0)#
Bases:
objectTopology link; endpoint indices refer to the supplied node order.
- type: LinkType = 0#
- class TraceLinkAverage(net_flow_m3s=0.0, absolute_flow_m3s=0.0, absolute_velocity_mps=0.0, forward_volume_m3=0.0, reverse_volume_m3=0.0, travel_s=0.0, first_volume_m3=0.0, last_volume_m3=0.0, direction=0, flags=<TraceFlags: 0>)#
Bases:
objectImmutable hydraulic snapshot in SI units.
- Parameters:
- flags: TraceFlags = 0#
- class TraceNode(id='', type=NodeType.JUNCTION, flags=<TraceNodeFlags: 0>)#
Bases:
objectTopology node; flags describe ponding and external exchanges.
- Parameters:
id (str)
type (NodeType)
flags (TraceNodeFlags)
- flags: TraceNodeFlags = 0#
- type: NodeType = 0#
- class TraceNodeAverage(volume_m3=0.0, inflow_m3s=0.0, lateral_in_m3s=0.0, withdrawal_m3s=0.0, overflow_m3s=0.0, outgoing_m3s=0.0, residence_s=0.0, first_volume_m3=0.0, last_volume_m3=0.0, flags=<TraceFlags: 0>)#
Bases:
objectImmutable hydraulic snapshot in SI units.
- Parameters:
- flags: TraceFlags = 0#
- class TraceOptions(flow_epsilon_m3s=1e-09, velocity_epsilon_mps=1e-06, reversal_dominance=0.8, solver_tolerance=1e-11, max_iterations=10000)#
Bases:
objectNumerical thresholds in SI units; use FlowTracer.default_options for native defaults.
- Parameters:
- class TraceResult(nodes, links, summary)#
Bases:
objectResults in topology order, with terminal and continuity accounting.
- Parameters:
nodes (tuple[TraceValue, ...])
links (tuple[TraceValue, ...])
summary (TraceSummary)
- nodes: tuple[TraceValue, ...]#
- links: tuple[TraceValue, ...]#
- summary: TraceSummary#
- class TraceSummary(terminal=(0.0, 0.0, 0.0, 0.0, 0.0, 0.0), accounting_error=0.0, solver_residual=0.0, boundary_in_m3=0.0, boundary_out_m3=0.0, lateral_in_m3=0.0, withdrawal_m3=0.0, known_loss_m3=0.0, storage_change_m3=0.0, partial_balance_residual_m3=0.0, cyclic=0, reached_nodes=0, reached_links=0)#
Bases:
objectAccounting totals; index terminal fractions with TraceTerminal.
Output reader (binary .out file)#
Binary output file reader (Pythonic v1 surface)#
- author:
Caleb Buahin
- copyright:
Copyright (c) 2026 Caleb Buahin
- license:
Apache-2.0
Type stubs for openswmm.engine._output_reader.
- class OutputReader(path, *, live=Ellipsis)#
Bases:
objectRead a SWMM binary
.outfile.- Parameters:
path (_PathLike)
live (bool)
- close()#
- Return type:
None
- link_attributes(link, period)#
- link_series(link, var, *, start=Ellipsis, end=Ellipsis)#
- node_attributes(node, period)#
- node_series(node, var, *, start=Ellipsis, end=Ellipsis)#
- subcatchment_attributes(sub, period)#
- subcatchment_result(period, var)#
- subcatchment_series(sub, var, *, start=Ellipsis, end=Ellipsis)#
- system_series(var, *, start=Ellipsis, end=Ellipsis)#
- flow_units: FlowUnits#
Saved 1D/2D results#
Discoverable, lazy result fields over the native 1D and 2D readers.
- class ResultField[source]#
Bases:
objectA lazy numeric field. Inspect metadata, then call read() to load values.
Fields retain their reader; arrays returned by read() remain valid after close. Missing optional conversion packages raise ImportError on use only.
- class SeriesField(collection, name, code, units, object_index=None)[source]#
Bases:
ResultFieldOne recorded 1D variable, optionally bound to one object.
- Parameters:
collection (ResultCollection)
name (str)
code (int)
units (str | None)
object_index (int | None)
- class ResultCollection(reader, kind)[source]#
Bases:
Mapping[str,_ResultObject]Recorded objects and named variables; indexing accepts an ID or index.
- Parameters:
reader (OutputReader)
kind (str)
- class ResultMesh(vertices, cells, vertex_counts, crs, metres_per_model_unit, coordinate_units)[source]#
Bases:
objectStored mesh in SI coordinates. Cells retain native order and padding -1.
- Parameters:
- vertices: NDArray[float64]#
- cells: NDArray[int64]#
- vertex_counts: NDArray[int64]#
- class SurfaceField(surface, path, fixed=None)[source]#
Bases:
ResultFieldA stored 2D dataset with named axes and optional bound cell/species.
- Parameters:
surface (SurfaceResults)
path (str)
- class SurfaceResults(reader)[source]#
Bases:
objectSaved 2D results. Each recorded dataset is accessible through field().
- Parameters:
reader (Output2DReader)
- property variables: Mapping[str, SurfaceField]#
- field(path)[source]#
Access a full dataset path, including nested diagnostic groups.
- Parameters:
path (str)
- Return type:
- property period_times: NDArray[Any]#
Report dates from the file’s declared CF units, at microsecond precision.
- property mesh: ResultMesh#
- property species: Mapping[str, SurfaceField]#
- class Results(path=None, *, surface=None, live=False)[source]#
Bases:
objectOwn independent readers for a 1D output, a 2D output, or both.
Open explicitly named paths; their reporting clocks remain independent. Use a context manager or close(). 2D files must be closed/immutable; live=True applies only to the binary 1D output.
- output: OutputReader | None#
- surface: SurfaceResults | None#
Native saved 2D result access; independent of a running solver.
Spatial (CRS, coordinates, vertices, polygons)#
Type stubs for openswmm.engine._spatial.
- class Spatial(solver)#
Bases:
object- Parameters:
solver (Solver)
- property crs: str#
Coordinate reference system (EPSG token, WKT, or proj string). Reading a model with no CRS raises
CRSError; assigning sets it.
- set_link_vertices(link, vertices)#
- set_subcatchment_coord(sub, x, y)#
- set_subcatchment_polygon(sub, polygon)#
Engine catalog#
Machine-readable map of this API; see Engine catalog.
Machine-readable map of the Python engine API.
catalog.json is generated from the stubs, Cython sources and C headers by
python/scripts/gen_catalog.py; CI fails when it is stale. It lists every
target reachable from a Solver – services such as forcing and
surface2d.groundwater, element kinds such as node and link and
their sub-views such as node.stats – and every property and method on
them, with type, access, units, lifecycle phases and wrapped C symbols.
from openswmm.engine import catalog
catalog.lookup("node.stats.max_depth")["units"] # 'length'
obj = catalog.resolve(solver, "node.stats", "J1") # the live NodeStatsView
Paths are a compatibility contract. Paths through a shared view resolve to the
view’s target (surface2d.groundwater.cells is groundwater2d.cells).
revision() increases whenever a path is renamed or removed; renamed paths
keep working through lookup(), resolve() and members() with a
DeprecationWarning, and removed ones fail with the reason. Consumers state
the revision they were written against with require_revision().
- resolve(solver, target, key=None)[source]#
Return the live object behind target on solver.
Element targets (
node,link.pump,species…) need the element key (id or index). Standalone roots (builder,output, …) are not reachable from a solver and raiseKeyError.
- unit_label(kind, unit_system=None, flow_units=None)[source]#
Human-readable units for a catalog unit kind in a model’s unit system.
flowtakes the model’s flow units, as a token ("CFS","CMS"…) or asSolver.flow_unitsitself; other system-dependent kinds take"US"or"SI"and come back unchanged without one; literal units pass through.catalog.unit_label(catalog.lookup("link.length")["units"], "SI") # 'm'
- UNIT_KINDS = frozenset({'area', 'concentration', 'count', 'datetime', 'dimensionless', 'evap_rate', 'flow', 'fraction', 'land_area', 'length', 'length2/s', 'manning_n', 'percent', 'rain_depth', 'rain_rate', 'section_factor', 'shape_dependent', 'temperature', 'unverified', 'user_defined', 'user_temperature', 'velocity', 'volume', 'weir_coeff', 'wind_speed'})#
Every symbolic unit kind; any other
unitsvalue is a literal unit (“m3/s”, “s”).
- revision()[source]#
Catalog revision; it increases whenever a path is renamed or removed.
- Return type:
Enumerations#
Enumerations#
- author:
Caleb Buahin
- copyright:
Copyright (c) 2026 Caleb Buahin
- license:
Apache-2.0
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 AquiferParam(*values)
Bases:
IntEnumAquifer parameter codes for Aquifers.get_param / set_param.
- Variables:
POROSITY – Porosity (volumetric fraction).
WILTING_POINT – Wilting point (volumetric fraction).
FIELD_CAPACITY – Field capacity (volumetric fraction).
CONDUCTIVITY – Saturated hydraulic conductivity.
CONDUCT_SLOPE – Conductivity slope.
TENSION_SLOPE – Tension slope.
UPPER_EVAP_FRAC – Upper-zone evaporation fraction.
LOWER_EVAP_DEPTH – Lower-zone evaporation depth.
LOWER_LOSS_COEFF – Lower-zone seepage-loss coefficient.
BOTTOM_ELEV – Aquifer bottom elevation.
WATER_TABLE_ELEV – Initial water table elevation.
UPPER_MOISTURE – Initial upper-zone moisture.
- POROSITY = 0
- WILTING_POINT = 1
- FIELD_CAPACITY = 2
- CONDUCTIVITY = 3
- CONDUCT_SLOPE = 4
- TENSION_SLOPE = 5
- UPPER_EVAP_FRAC = 6
- LOWER_EVAP_DEPTH = 7
- LOWER_LOSS_COEFF = 8
- BOTTOM_ELEV = 9
- WATER_TABLE_ELEV = 10
- UPPER_MOISTURE = 11
- class BuildupFunc(*values)
Bases:
IntEnumPollutant 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 CellScope(*values)
Bases:
IntEnumNative SWMM_GW2D_SCOPE selectors.
- GLOBAL = 0
- TAG = 1
- CELL = 2
- class ChannelGroundValue(*values)
Bases:
IntEnumMapped channel/soil results returned by
Heat.channel_ground_values.- BED_TEMPERATURE = 0
- ATMOSPHERIC_ENERGY = 1
- TO_SOIL_ENERGY = 2
- WATER_INCREMENT = 3
- INTERVAL_COUNT = 4
- class ConcentrationUnits(*values)
Bases:
IntEnumPollutant 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 DividerType(*values)
Bases:
IntEnumFlow-diversion method for a DIVIDER node. Mirrors
SWMM_DividerType.- CUTOFF = 0
- OVERFLOW = 1
- TABULAR = 2
- WEIR = 3
- class EngineState(*values)
Bases:
IntEnumEngine lifecycle states.
Returned by the
stateproperty ofSolver. Values mirror theSWMM_EngineStateenum inopenswmm_engine.h.- Variables:
NONE – Uninitialised / fatal-error sentinel.
CREATED – Context allocated, no input loaded.
OPENED – Input file parsed, objects allocated.
INITIALIZED – Initial conditions applied.
STARTED – Simulation prepared to step (post-start, pre-first-step).
RUNNING – Simulation loop in progress.
ENDED – Simulation loop completed.
CLOSED – Resources released.
BUILDING – Programmatic model construction in progress (no .inp).
- NONE = 0
- CREATED = 1
- OPENED = 2
- INITIALIZED = 3
- STARTED = 4
- RUNNING = 5
- ENDED = 6
- CLOSED = 7
- BUILDING = 8
- class ErrorCode(*values)
Bases:
IntEnumSWMM 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
- DEPENDENCY = 15
- CANCELLED = 16
- BUFSIZE = 17
- INTERNAL = 99
- class EvapPreviewStatus(*values)
Bases:
IntEnumCodes matching native SWMM_EvapPreviewStatus.
- AVAILABLE = 0
- HELD = 1
- MISSING = 2
- ESTIMATED = 3
- class EvapType(*values)
Bases:
IntEnumCodes matching the native
SWMM_EvapTypeenumeration.- CONSTANT = 0
- MONTHLY = 1
- TIMESERIES = 2
- TEMPERATURE = 3
- FILE = 4
- class FilePathRole(*values)
Bases:
IntEnumExternal-file slot selector for
swmm_file_path_get/set.Mirrors
SWMM_FilePathRole. Scalar slots ignore theownerargument; vector slots useownerto select the entry (a decimal index for hot-start saves, the gage id for rain-gage data, the series id for time-series data).- Variables:
RAINFALL – Rainfall interface file (scalar).
RUNOFF – Runoff interface file (scalar).
RDII – RDII interface file (scalar).
INFLOWS – Routing inflows interface file (scalar).
OUTFLOWS – Routing outflows interface file (scalar).
HOTSTART_USE – Hot-start file to read (scalar).
CLIMATE_TEMP – Climate/temperature file (scalar).
HOTSTART_SAVE – Hot-start save slot (vector; owner = index).
RAINGAGE_DATA – Rain-gage data file (vector; owner = gage id).
TIMESERIES_DATA – Time-series data file (vector; owner = series id).
- RAINFALL = 1
- RUNOFF = 2
- RDII = 3
- INFLOWS = 4
- OUTFLOWS = 5
- HOTSTART_USE = 6
- CLIMATE_TEMP = 7
- HOTSTART_SAVE = 8
- RAINGAGE_DATA = 9
- TIMESERIES_DATA = 10
- MESH_2D = 11
- OUTPUT_2D = 12
- LID_REPORT = 13
- class FlowUnits(*values)
Bases:
IntEnumFlow 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:
IntEnumForcing application mode.
Determines how a forced value is combined with the model-computed value. Mirrors
SWMM_ForcingModeinopenswmm_forcing.h(OVERRIDE=1, ADD=2; 0 is the engine-internal “no forcing” state and is not exposed).- Variables:
REPLACE – Replace the computed value entirely.
ADD – Add the forced value to the computed value.
- REPLACE = 1
- ADD = 2
- class ForcingPersist(*values)
Bases:
IntEnumLifetime of a runtime forcing override. Mirrors
SWMM_ForcingPersist.- RESET = 0
- PERSIST = 1
- class ForcingTarget(*values)
Bases:
IntEnumObject 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.
CLIMATE – System-wide climate forcing target (temperature, wind).
- NODE = 0
- LINK = 1
- SUBCATCH = 2
- GAGE = 3
- CLIMATE = 4
- class ForcingType(*values)
Bases:
IntEnumForcing channel selected when injecting a runtime override.
Mirrors
SWMM_ForcingTypeinopenswmm_forcing.h. Distinct fromForcingTarget, which only names the object kind passed toForcing.clear.- Variables:
NODE_LAT_INFLOW – Lateral inflow at a node.
NODE_HEAD_BOUNDARY – Head boundary condition at a node.
NODE_QUALITY – Pollutant concentration at a node.
LINK_FLOW – Imposed flow on a link.
LINK_SETTING – Control setting on a link.
SUBCATCH_RAINFALL – Rainfall on a subcatchment.
SUBCATCH_EVAP – Evaporation on a subcatchment.
GAGE_RAINFALL – Rainfall at a rain gage.
CLIMATE_TEMPERATURE – System-wide air temperature.
CLIMATE_WIND – System-wide wind speed.
SUBCATCH_SNOWFALL – Snowfall on a subcatchment.
CLIMATE_EVAP – System-wide evaporation rate.
LINK_QUALITY – Pollutant quality on a link.
- NODE_LAT_INFLOW = 0
- NODE_HEAD_BOUNDARY = 1
- NODE_QUALITY = 2
- LINK_FLOW = 3
- LINK_SETTING = 4
- SUBCATCH_RAINFALL = 5
- SUBCATCH_EVAP = 6
- GAGE_RAINFALL = 7
- CLIMATE_TEMPERATURE = 8
- CLIMATE_WIND = 9
- SUBCATCH_SNOWFALL = 10
- CLIMATE_EVAP = 11
- LINK_QUALITY = 12
- ELEM_AIR_TEMPERATURE = 13
- ELEM_HUMIDITY = 14
- ELEM_WIND_SPEED = 15
- ELEM_SHORTWAVE = 16
- LINK_SEEPAGE = 17
- class GageDataSource(*values)
Bases:
IntEnumRain 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:
IntEnumRain 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 GrateType(*values)
Bases:
IntEnumGrate bar pattern (HEC-22 Table 4-6). Mirrors
SWMM_GrateType.- P_BAR_50 = 0
- P_BAR_50x100 = 1
- P_BAR_30 = 2
- CURVED_VANE = 3
- TILT_BAR_45 = 4
- TILT_BAR_30 = 5
- RETICULINE = 6
- GENERIC = 7
- class GroundHeatLayerValue(*values)
Bases:
IntEnumFixed-depth soil layer fields returned by
Heat.ground_layers.- TOP = 0
- BOTTOM = 1
- TEMPERATURE = 2
- ENERGY = 3
- CAPACITY = 4
- MOISTURE = 5
- CONDUCTIVITY = 6
- SATURATED_WATER = 7
- class GroundHeatValue(*values)
Bases:
IntEnumCanonical soil heat fields returned by
Heat.ground_values.- ENERGY = 0
- CAPACITY = 1
- TEMPERATURE = 2
- INITIAL_ENERGY = 3
- ADVECTIVE_ENERGY = 4
- SOURCE_ENERGY = 5
- SURFACE_ENERGY = 6
- DEEP_ENERGY = 7
- LATENT_ENERGY = 8
- LATERAL_ENERGY = 9
- WATER_CONTACT_ENERGY = 10
- RESIDUAL = 11
- NORMALIZED_RESIDUAL = 12
- PENDING_LATERAL = 13
- CHANNEL_CONTACT = 14
- LID_CONTACT = 15
- class GroundwaterClosure(*values)
Bases:
IntEnumNative SWMM_GW2D_CLOSURE selectors.
- AUTO = -1
- CLOSED_FORM = 0
- ENSLAVED = 1
- SIGMA = 2
- class GroundwaterLedger(*values)
Bases:
IntEnumNative SWMM_GW2D_LED selectors.
- RECHARGE = 0
- LATERAL = 1
- DEEP = 2
- NODE = 3
- DUNNE = 4
- CAPRISE = 5
- ET = 6
- INFIL_IN = 7
- INIT_STORAGE = 8
- STORAGE = 9
- LINK = 10
- SOURCE_IN = 11
- SOURCE_OUT = 12
- REJECT = 13
- BOUNDARY_IN = 14
- BOUNDARY_OUT = 15
- class GroundwaterSoil(*values)
Bases:
IntEnumNative SWMM_GW2D_SOIL selectors.
- RUSSO = 0
- GARDNER = 1
- BROOKS_COREY = 2
- VAN_GENUCHTEN = 3
- class GroundwaterSpeciesLedger(*values)
Bases:
IntEnumNative SWMM_GW2D_SPL selectors.
- INIT = 0
- STORAGE = 1
- INFIL_IN = 2
- NODE_IN = 3
- LINK_IN = 4
- LATERAL_NET = 5
- DEEP_OUT = 6
- NODE_OUT = 7
- LINK_OUT = 8
- DUNNE_OUT = 9
- ET_OUT = 10
- REACTED = 11
- RESIDUAL = 12
- SOURCE_IN = 13
- SOURCE_OUT = 14
- BOUNDARY_IN = 15
- BOUNDARY_OUT = 16
- BOUNDARY_FLUX_IN = 17
- BOUNDARY_FLUX_OUT = 18
- AGE_GENERATED = 19
- class GroundwaterTransportZone(*values)
Bases:
IntEnumAuthoring zones; LAYER uses an explicit one-based layer index.
- SAT = 0
- UNSAT = 1
- LAYER = 2
- class GroundwaterVariable(*values)
Bases:
IntEnumNative SWMM_GW2D_VAR selectors.
- HG = 0
- HU = 1
- TABLE_EL = 2
- Q0 = 3
- QLAT = 4
- QNODE = 5
- QDEEP = 6
- QET = 7
- DUNNE = 8
- QPLUS = 9
- DT_CELL = 10
- TIER = 11
- CLOSURE = 12
- QLINK = 13
- INFIL_CAPACITY = 14
- INFIL_REMAINING = 15
- INFIL_REFRESH = 16
- INFIL_PENDING = 17
- REJECT = 18
- REJECT_CUM = 19
- DUNNE_CUM = 20
- ET_PENDING = 21
- ET_POTENTIAL_CUM = 22
- ET_SURFACE_CUM = 23
- ET_SOIL_CUM = 24
- ET_UNUSED_CUM = 25
- ET_SURFACE = 26
- ET_POTENTIAL = 27
- ET_STRESS = 28
- ET_REFRESH = 29
- COMPLETED_TIME = 30
- PENDING_IN = 31
- PENDING_OUT = 32
- QX = 33
- QY = 34
- class GroundwaterZone(*values)
Bases:
IntEnumNative SWMM_GW2D_ZONE selectors.
- SAT = 0
- UNSAT = 1
- class GwfType(*values)
Bases:
IntEnumWhich of a subcatchment’s two [GWF] custom groundwater flow expressions.
- Variables:
LATERAL – Added to the standard A1/A2/A3 lateral groundwater flow.
DEEP – Replaces the standard deep-percolation term.
- LATERAL = 0
- DEEP = 1
- class Heat2DValue(*values)
Bases:
IntEnumCodes matching native SWMM_Heat2DValue.
- WATER_TEMPERATURE = 0
- BED_TEMPERATURE = 1
- BED_ENERGY = 2
- BED_CAPACITY = 3
- ATMOSPHERIC_ENERGY = 4
- RADIATIVE_ENERGY = 5
- SENSIBLE_ENERGY = 6
- LATENT_ENERGY = 7
- DEEP_ENERGY = 8
- WATER_TO_BED_ENERGY = 9
- WATER_THERMAL_INCREMENT = 10
- ACCEPTED_EVAPORATION = 11
- THERMAL_RESIDUAL = 12
- class HeatAttr(*values)
Bases:
IntEnumPer-element heat override attributes. Mirrors
SWMM_HeatAttr.- ALBEDO = 0
- SHADE_FACTOR = 1
- SKY_VIEW = 2
- EMISS_WATER = 3
- EMISS_LANDCOVER = 4
- LANDCOVER_TEMPERATURE = 5
- THERMAL_DIFFUSIVITY = 6
- SOLUTE_DIFFUSIVITY = 7
- BED_THICKNESS = 8
- GROUND_DEPTH = 9
- GROUND_TEMPERATURE = 10
- HYPORHEIC_VELOCITY = 11
- SEDIMENT_DENSITY = 12
- SEDIMENT_SPECIFIC_HEAT = 13
- MESH_POROSITY = 14
- GROUND_SOURCE = 15
- class HeatCloudParam(*values)
Bases:
IntEnum[CLOUD_COVER]parameters. MirrorsSWMM_HeatCloudParam.- FRACTION = 0
- SW_ATTEN_K = 1
- SW_ATTEN_N = 2
- LW_CLOUD_K = 3
- class HeatElemKind(*values)
Bases:
IntEnumCodes matching the native
SWMM_HeatElemKindenumeration.- NODE = 0
- LINK = 1
- class HeatFluxModule(*values)
Bases:
IntEnumIndependently toggleable heat-flux modules. Mirrors
SWMM_HeatFluxModule.- SURFACE_EXCHANGE = 0
- RADIATIVE_EXCHANGE = 1
- LAYER_CONDUCTION = 2
- SEDIMENT_EXCHANGE = 3
- class HeatOverrideScope(*values)
Bases:
IntEnumPer-element override scope. Mirrors
SWMM_HeatOverrideScope.- TAG = 1
- NODE = 2
- LINK = 3
- CELL2D = 6
- MESH_TAG = 7
- class HeatRadiativeParam(*values)
Bases:
IntEnum[RADIATIVE_FLUXES]scalar parameters. MirrorsSWMM_HeatRadiativeParam.- SHORTWAVE = 0
- ALBEDO = 1
- SHADE_FACTOR = 2
- SKY_VIEW = 3
- EMISS_WATER = 4
- EMISS_LANDCOVER = 5
- ATM_EMISS_COEFF = 6
- LW_REFLECTION = 7
- LANDCOVER_TEMPERATURE = 8
- class HeatSedimentParam(*values)
Bases:
IntEnum[SEDIMENT_EXCHANGE]GLOBAL parameters. MirrorsSWMM_HeatSedimentParam.- THERMAL_DIFFUSIVITY = 0
- SOLUTE_DIFFUSIVITY = 1
- BED_THICKNESS = 2
- GROUND_DEPTH = 3
- GROUND_TEMPERATURE = 4
- HYPORHEIC_VELOCITY = 5
- DENSITY = 6
- SPECIFIC_HEAT = 7
- INITIAL_TEMPERATURE = 8
- MESH_POROSITY = 9
- GROUND_SOURCE = 10
- class HeatShortwaveMode(*values)
Bases:
IntEnumSource of incoming shortwave radiation. Mirrors
SWMM_HeatShortwaveMode.- CONSTANT = 0
- TIMESERIES = 1
- COMPUTED = 2
- class HeatSolarParam(*values)
Bases:
IntEnum[SOLAR_RADIATION]parameters. MirrorsSWMM_HeatSolarParam.- LATITUDE = 0
- LONGITUDE = 1
- TIMEZONE = 2
- ELEVATION = 3
- TURBIDITY_380 = 4
- TURBIDITY_500 = 5
- PRECIP_WATER = 6
- OZONE = 7
- GROUND_ALBEDO = 8
- class HeatSourceKind(*values)
Bases:
IntEnum[HEAT_SOURCES]water sources. MirrorsSWMM_HeatSourceKind.- RAINFALL = 0
- DWF = 1
- GW = 2
- RDII = 3
- EXTERNAL_INFLOW = 4
- IFACE = 5
- INITIAL_STATE = 6
- class HumidityType(*values)
Bases:
IntEnumCodes matching the native
SWMM_HumidityTypeenumeration.- CONSTANT = 0
- MONTHLY = 1
- TIMESERIES = 2
- class HumidityVar(*values)
Bases:
IntEnumCodes matching the native
SWMM_HumidityVarenumeration.- RELATIVE = 0
- DEWPOINT = 1
- class InfilModel(*values)
Bases:
IntEnumInfiltration 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 InletCurveKind(*values)
Bases:
IntEnumCapture-curve kind of a
CUSTOMinlet. MirrorsSWMM_InletCurveKind.- NONE = 0
- DIVERSION = 1
- RATING = 2
- class InletHostKind(*values)
Bases:
IntEnumInlet-usage host kind. Mirrors
SWMM_InletHostKind.- LINK = 0
- NODE = 1
- class InletPlacement(*values)
Bases:
IntEnumInlet placement mode (
[INLET_USAGE]token 9). MirrorsSWMM_InletPlacement.- AUTOMATIC = 0
- ON_GRADE = 1
- ON_SAG = 2
- class InletType(*values)
Bases:
IntEnumStreet-inlet design type (
[INLETS]token 2). MirrorsSWMM_InletType.- GRATE = 0
- CURB = 1
- COMBO = 2
- SLOTTED = 3
- DROP_GRATE = 4
- DROP_CURB = 5
- CUSTOM = 6
- class InpProfile(*values)
Bases:
IntEnumCodes matching the native
SWMM_InpProfileenumeration.- FULL = 0
- SWMM5 = 1
- SWMM5_STOCK = 2
- class LidExtraField(*values)
Bases:
IntEnum- SURFACE_VEGETATION = 0
- SURFACE_SIDE_SLOPE = 1
- SOIL_SUCTION = 2
- STORAGE_CLOGGING = 3
- DRAIN_DELAY = 4
- DRAIN_OPEN = 5
- DRAIN_CLOSE = 6
- STORAGE_COVERED = 7
- class LidType(*values)
Bases:
IntEnumLow 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
- NODE = 8
- class LinkType(*values)
Bases:
IntEnumLink 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 NodeCoupling2DType(*values)
Bases:
IntEnumPer-node 1D-2D coupling structure type. Mirrors
SWMM_NodeCoupling2DType.- NONE = 0
- MANHOLE = 1
- GRATE = 2
- CURB = 3
- OPEN = 4
- OUTFALL = 5
- class NodeType(*values)
Bases:
IntEnumNode 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:
IntEnumSWMM 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 OrificeType(*values)
Bases:
IntEnumOrifice flow-attack classification.
Mirrors
SWMM_OrificeTypeinopenswmm_links.h.- SIDE = 0
- BOTTOM = 1
- class OutLinkVar(*values)
Bases:
IntEnumLink 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:
IntEnumNode 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:
IntEnumSubcatchment 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
- SNOW_SWE = 65536
- SNOW_ENERGY = 65537
- SNOW_SURFACE_TEMP = 65538
- SNOW_BULK_TEMP = 65539
- SNOW_ALBEDO = 65540
- SNOW_COVER = 65541
- SNOW_MELT = 65542
- SNOW_INPUT = 65543
- SNOW_SUBLIMATION = 65544
- SNOW_TIME = 65545
- class OutSystemVar(*values)
Bases:
IntEnumSystem-wide output result variable indices (the .out writer’s slot order).
- Variables:
TEMPERATURE – Air temperature.
RAINFALL – System-wide rainfall rate.
SNOW_DEPTH – Average snow depth.
INFIL – System-wide infiltration rate.
RUNOFF – System-wide runoff rate.
DW_INFLOW – Dry-weather inflow rate.
GW_INFLOW – Groundwater inflow rate.
RDII_INFLOW – RDII inflow rate.
EXT_INFLOW – External (direct) inflow rate.
TOTAL_INFLOW – Total lateral inflow rate.
FLOODING – Total flooding rate.
OUTFLOW – Total outfall outflow rate.
STORAGE – Total network storage volume.
EVAP – Evaporation rate.
PET – Potential evapotranspiration rate.
LAT_INFLOW – Deprecated alias of TOTAL_INFLOW.
- TEMPERATURE = 0
- RAINFALL = 1
- SNOW_DEPTH = 2
- INFIL = 3
- RUNOFF = 4
- DW_INFLOW = 5
- GW_INFLOW = 6
- RDII_INFLOW = 7
- EXT_INFLOW = 8
- TOTAL_INFLOW = 9
- FLOODING = 10
- OUTFLOW = 11
- STORAGE = 12
- EVAP = 13
- PET = 14
- LAT_INFLOW = 9
- class OutfallType(*values)
Bases:
IntEnumOutfall boundary condition type.
- FREE = 0
- NORMAL = 1
- FIXED = 2
- TIDAL = 3
- TIMESERIES = 4
- class OutletRatingType(*values)
Bases:
IntEnumOutlet rating-curve classification.
Mirrors
SWMM_OutletRatingTypeinopenswmm_links.h.- FUNCTIONAL_HEAD = 0
- FUNCTIONAL_DEPTH = 1
- TABULAR_HEAD = 2
- TABULAR_DEPTH = 3
- class PatternType(*values)
Bases:
IntEnumTime 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 ReactionExprForm(*values)
Bases:
IntEnumForm of a species’ reaction expression. Mirrors the
SWMM_RXN_FORM_*macros.- NONE = 0
- RATE = 1
- EQUIL = 2
- FORMULA = 3
- class ReactionScope(*values)
Bases:
IntEnumReaction-expression validation scope. Mirrors the
SWMM_RXN_SCOPE_*macros.- TERM = 0
- PIPE = 1
- TANK = 2
- SUBSURFACE = 3
- SUBCATCHMENT = 4
- class RefType(*values)
Bases:
IntEnumKind of object that holds a reference, used by the editing/impact API.
Mirrors
SWMM_RefTypeinopenswmm_edit.h.- Variables:
NODE – A node holds the reference.
LINK – A link holds the reference.
SUBCATCH – A subcatchment holds the reference.
GAGE – A rain gage holds the reference.
TABLE – A time series or curve holds the reference.
TRANSECT – A transect holds the reference.
INLET_USAGE – An inlet-usage entry holds the reference.
- NODE = 0
- LINK = 1
- SUBCATCH = 2
- GAGE = 3
- TABLE = 4
- TRANSECT = 5
- INLET_USAGE = 6
- EXT_INFLOW = 7
- DWF_INFLOW = 8
- RDII_ASSIGN = 9
- TREATMENT = 10
- LID_USAGE = 11
- SNOWPACK = 12
- HYDROGRAPH = 13
- POLLUTANT = 14
- PATTERN = 15
- AQUIFER = 16
- LID_CONTROL = 17
- STREET = 18
- INLET_DESIGN = 19
- LANDUSE = 20
- CONTROL_RULE = 21
- class RouteModel(*values)
Bases:
IntEnumHydraulic routing models.
- Variables:
STEADY – Steady-state routing.
KINWAVE – Kinematic wave routing.
DYNWAVE – Dynamic wave (full Saint-Venant), implicit. The default.
FV – Explicit conservative finite volume (Godunov). Conserves volume exactly and captures pressurization fronts and transcritical flow, at the cost of needing a resolved mesh — set
FV_CELL_LENGTH. See the Hydraulics Reference Manual, Chapter 8.
- STEADY = 0
- KINWAVE = 1
- DYNWAVE = 2
- FV = 3
- class RoutingTotal(*values)
Bases:
IntEnumRouting 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.
FORCING_INFLOW – Runtime-API forced lateral inflow (e.g. flow injected via Nodes.set_lateral_inflow / transient ForcingData). A subset of EXTERNAL, which also includes authored inflows, interface-file inflow, and 2D coupling inflow.
- 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
- FORCING_INFLOW = 11
- LINK_GW_INFLOW = 13
- COUPLING_OUT = 12
- class RunoffTotal(*values)
Bases:
IntEnumRunoff 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
- INITSNOW = 7
- FINALSNOW = 8
- class SplitPhase(*values)
Bases:
IntEnum- CONDUCTANCE = 1
- ADVANCE = 2
- FINISH = 3
- OUTFALL_PREPARE = 4
- SOURCE_PREPARE = 5
- LID_TRIAL = 6
- LID_ACCEPT = 7
- MATERIAL_REPORT = 8
- class SplitRole(*values)
Bases:
IntEnum- NETWORK = 1
- SURFACE = 2
- class StorageShape(*values)
Bases:
IntEnumStorage-unit surface-area relation codes.
- TABULAR = 0
- FUNCTIONAL = 1
- CYLINDRICAL = 2
- CONICAL = 3
- PARABOLOID = 4
- PYRAMIDAL = 5
- class SummaryObject(*values)
Bases:
IntEnum- SYSTEM = -1
- NODE = 0
- LINK = 1
- SUBCATCHMENT = 2
- class SummaryTable(*values)
Bases:
IntEnum- NODE_DEPTH = 0
- NODE_INFLOW = 1
- NODE_SURCHARGE = 2
- NODE_FLOODING = 3
- STORAGE_VOLUME = 4
- OUTFALL_LOADING = 5
- LINK_FLOW = 6
- FLOW_CLASSIFICATION = 7
- CONDUIT_SURCHARGE = 8
- PUMPING = 9
- LID_PERFORMANCE = 10
- class SurfaceBoundaryType(*values)
Bases:
IntEnum2D mesh edge boundary-condition type. Mirrors
openswmm::twoD::BoundaryType.- WALL = 0
- NORMAL_FLOW = 1
- SPECIFIED_STAGE = 2
- SPECIFIED_FLOW = 3
- RATING_CURVE = 4
- class SurfaceForcingMode(*values)
Bases:
IntEnum2D surface forcing mode. Mirrors
SWMM_ForcingMode(OVERRIDE=1, ADD=2).- NONE = 0
- OVERRIDE = 1
- ADD = 2
- class SurfaceInfilDest(*values)
Bases:
IntEnumDestination of 2D infiltrated water. Mirrors
SWMM_INFIL2D_DEST_*.- LOST = 0
- SUBCATCH_AQUIFER = 1
- AQUIFER_2D = 2
- class SurfaceInfilMethod(*values)
Bases:
IntEnumPer-cell 2D infiltration method. Mirrors
SWMM_INFIL2D_*.- HORTON = 0
- MOD_HORTON = 1
- GREEN_AMPT = 2
- MOD_GREEN_AMPT = 3
- CURVE_NUMBER = 4
- CONSTANT = 5
- class TableType(*values)
Bases:
IntEnumTable type code from
swmm_table_get_type. Mirrorsopenswmm::TableType.- TIMESERIES = 0
- CURVE_STORAGE = 1
- CURVE_DIVERSION = 2
- CURVE_RATING = 3
- CURVE_SHAPE = 4
- CURVE_CONTROL = 5
- CURVE_TIDAL = 6
- CURVE_PUMP1 = 7
- CURVE_PUMP2 = 8
- CURVE_PUMP3 = 9
- CURVE_PUMP4 = 10
- CURVE_PUMP5 = 11
- class TempSource(*values)
Bases:
IntEnumCodes matching the native
SWMM_TempSourceenumeration.- NONE = 0
- TIMESERIES = 1
- FILE = 2
- class ThroatType(*values)
Bases:
IntEnumCurb-opening throat orientation. Mirrors
SWMM_ThroatType.- HORIZONTAL = 0
- INCLINED = 1
- VERTICAL = 2
- class TraceDirection(*values)
Bases:
IntEnum- DOWNSTREAM = 0
- UPSTREAM = 1
- class TraceFlags(*values)
Bases:
IntFlag- UNREACHABLE = 1
- NO_DIRECTION = 2
- REVERSAL = 4
- UNKNOWN_TIME = 8
- PARTIAL_TIME = 16
- TRAPPED = 32
- APPROXIMATE = 64
- class TraceNodeFlags(*values)
Bases:
IntFlag- PONDING = 1
- EXTERNAL_EXCHANGE = 2
- ROUTED_OUTFALL = 4
- UNKNOWN_LOSSES = 8
- class TraceStatus(*values)
Bases:
IntEnumReturn codes for the independent tracing API.
- OK = 0
- INVALID = -1
- IO = -2
- MISMATCH = -3
- CANCELLED = -4
- SOLVER = -5
- NO_HDF5 = -6
- class TraceTerminal(*values)
Bases:
IntEnum- OUTFALL = 0
- LOSS = 1
- SOURCE = 2
- RETAINED = 3
- UNRESOLVED = 4
- CIRCULATION = 5
- class TransportClass(*values)
Bases:
IntEnumSpecies class axis of the engine transport capability matrix.
- POLLUTANTS = 0
- MSX = 1
- AGE = 2
- TEMPERATURE = 3
- class TransportDispersionMode(*values)
Bases:
IntEnumCodes matching the native
SWMM_TransportDispersionModeenumeration.- OFF = 0
- FISCHER = 1
- VALUE = 2
- class TransportDomain(*values)
Bases:
IntEnumDomain axis of the engine transport capability matrix.
- RUNOFF = 0
- GROUNDWATER = 1
- NETWORK_1D = 2
- SURFACE_2D = 3
- class TransportState(*values)
Bases:
IntEnumAvailability of a process, with a diagnostic reason when disabled.
- ENABLED = 0
- DISABLED_BY_USER = 1
- UNAVAILABLE = 2
- class UnitSystem(*values)
Bases:
IntEnumCodes matching the native
SWMM_UnitSystemenumeration.- UNITS_US = 0
- UNITS_SI = 1
- class UserFlagType(*values)
Bases:
IntEnumUser-flag schema value type for
swmm_userflag_define. Mirrorsopenswmm::UserFlagType.- BOOLEAN = 0
- INTEGER = 1
- REAL = 2
- STRING = 3
- class WarnCode(*values)
Bases:
IntEnumEngine 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:
IntEnumPollutant 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 WaterAgeSource(*values)
Bases:
IntEnum[WATER_AGE_SOURCES]pathways. MirrorsSWMM_WaterAgeSource(withoutCOUNT).- RAINFALL = 0
- DWF = 1
- GW = 2
- RDII = 3
- EXTERNAL_INFLOW = 4
- IFACE = 5
- INITIAL_STATE = 6
- class WeirType(*values)
Bases:
IntEnumWeir flow classification.
Mirrors
SWMM_WeirTypeinopenswmm_links.h.- TRANSVERSE = 0
- SIDEFLOW = 1
- VNOTCH = 2
- TRAPEZOIDAL = 3
- ROADWAY = 4
- class WindType(*values)
Bases:
IntEnumCodes matching the native
SWMM_WindTypeenumeration.- MONTHLY = 0
- FILE = 1
- class XSectShape(*values)
Bases:
IntEnumCross-section shape codes.
Mirrors the engine’s
SWMM_XSectShapestorage codes exactly.Warning
Renumbered in 6.0.
IRREGULAR,CUSTOMandFORCE_MAINpreviously carried 16/17/18, which the engine read asRECT_TRIANG/RECT_ROUND/HORIZ_ELLIPSE.- 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.
RECT_TRIANG – Rectangular-triangular channel.
RECT_ROUND – Rectangular-round channel.
HORIZ_ELLIPSE – Horizontal elliptical pipe.
VERT_ELLIPSE – Vertical elliptical pipe.
ARCH – Arch pipe.
IRREGULAR – Irregular (from transect data).
CUSTOM – Custom shape (from shape curve).
FORCE_MAIN – Force main (pressurized).
STREET_XSECT – Street cross-section.
DUMMY – Dummy — no geometry.
- 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
- RECT_TRIANG = 16
- RECT_ROUND = 17
- HORIZ_ELLIPSE = 18
- VERT_ELLIPSE = 19
- ARCH = 20
- IRREGULAR = 21
- CUSTOM = 22
- FORCE_MAIN = 23
- STREET_XSECT = 24
- DUMMY = 25
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:
Apache-2.0
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:
objectGeoPackage 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
.gpkgfile.- Raises:
GeoPackageError – If the file cannot be opened.
- __init__(path)#
Open a GeoPackage file.
- Parameters:
path (str) – Path to the
.gpkgfile.- Raises:
GeoPackageError – If the file cannot be opened.
- Return type:
None
- begin()#
Begin a transaction for bulk operations.
- Raises:
LifecycleError – If a transaction is already active.
GeoPackageError – If the transaction cannot be started.
- Return type:
None
- close()#
Close the database connection.
Calling
closemore than once is harmless.- Return type:
None
- commit()#
Commit the current transaction.
- Raises:
LifecycleError – If no transaction is active.
GeoPackageError – 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:
- Raises:
GeoPackageError – 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:
- object_counts(sim_id)#
Return model object counts for a simulation.
- observed_series_count()#
Return the number of observed-data series.
- Returns:
Observed-series count.
- Return type:
- observed_value_count(series_id)#
Return the number of values in an observed series.
- query_double(sql)#
Execute a read-only SQL query and return the first double result.
- Parameters:
sql (str) –
SELECTquery string.- Returns:
Double-precision result of the query.
- Return type:
- Raises:
GeoPackageError – If the query fails.
- query_int(sql)#
Execute a read-only SQL query and return the first integer result.
- read_observed_values(series_id)#
Read observed-timeseries values. GIL is released for the duration of the SQL read.
- read_result_ts(sim_id, obj_type, obj_id, variable)#
Read a result timeseries as NumPy arrays. GIL is released for the duration of the SQL execution.
- Parameters:
- Returns:
Tuple
(times, values)as NumPyfloat64arrays.- 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.
- result_ts_count(sim_id, obj_type, obj_id, variable)#
Return the number of result timeseries records for a query.
- rollback()#
Roll back the current transaction.
- Raises:
GeoPackageError – If the rollback fails.
- Return type:
None
- simulation_count()#
Return the number of simulation runs in the file.
- Returns:
Simulation count.
- Return type:
- 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.
- variable_count()#
Return the number of output variables defined.
- Returns:
Variable count.
- Return type:
- 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:
GeoPackageError – If the write fails.
- Return type:
None
- write_observed_values(series_id, timestamps, values, flags=None)#
Bulk-write observed data points. GIL is released for the duration of the bulk SQL insert.
For best performance wrap the call in a transaction:
gpkg.begin() gpkg.write_observed_values(sid, timestamps, values) gpkg.commit()
- Parameters:
- Raises:
GeoPackageError – If the bulk write fails.
MemoryError – If the C string-pointer arrays cannot be allocated.
- Return type:
None
- is_registered()#
Check whether the GeoPackage plugin is registered.
- Returns:
Trueif registered.- Return type:
- register(key='', org='', email='', deploy='')#
Register the GeoPackage plugin.
2-D surface routing (OPENSWMM_BUILD_2D=ON)#
- class BoundaryQuality2D(cell, edge, species, conc)#
Bases:
NamedTupleCreate new instance of BoundaryQuality2D(cell, edge, species, conc)
- class Infil2DCell(row, is_override)#
Bases:
NamedTupleThe infiltration specification in force at one cell.
Create new instance of Infil2DCell(row, is_override)
- Parameters:
row (Infil2DRow)
is_override (bool)
- row: Infil2DRow#
Alias for field number 0
- class Infil2DDefaults(owner)#
Bases:
MutableMapping[str,Infil2DRow]surface2d.infiltration.defaults— tag →Infil2DRowmapping.Mirrors
[2D_INFILTRATION_DEFAULTS]. The key"*"is the mesh-wide fallback.- Parameters:
owner (Solver | ModelBuilder | int)
- class Infil2DRow(method, params=(0.0, 0.0, 0.0, 0.0, 0.0), dest=SurfaceInfilDest.LOST)#
Bases:
NamedTupleOne infiltration specification.
methodisNonefor “no infiltration model”.paramscarries up to five POSITIONAL values in PROJECT UNITS (the same numbers a user types into a legacy[INFILTRATION]row). OnlySurfaceInfilDest.LOSTis routed in this release.Create new instance of Infil2DRow(method, params, dest)
- dest: SurfaceInfilDest#
Alias for field number 2
- class Infiltration2DView(owner)#
Bases:
objectsurface2d.infiltration— per-cell infiltration on the 2D mesh.Row parameters are in project units; every readback channel is SI. Writers raise
RuntimeErroronce the solver has been initialized.- Parameters:
owner (Solver | ModelBuilder | int)
- cumulative()#
Cumulative infiltrated depth (m), one entry per triangle.
- Return type:
NDArray[float64]
- property defaults: Infil2DDefaults#
The
[2D_INFILTRATION_DEFAULTS]tag → row mapping.
- rate()#
Held per-cell infiltration rate (m/s), one entry per triangle.
- Return type:
NDArray[float64]
- set_cell(tri, row)#
Set (
row) or clear (None) the per-cell override.- Parameters:
tri (int)
row (Infil2DRow | None)
- Return type:
None
- set_cells(tris, row)#
Assign one row to many triangles — all-or-nothing.
- Parameters:
row (Infil2DRow | None)
- Return type:
None
- class InitialQuality2D(scope, tag, cell, species, conc)#
Bases:
NamedTupleCreate new instance of InitialQuality2D(scope, tag, cell, species, conc)
- class Surface2D(owner)#
Bases:
objectRead/write interface to the optional 2D surface routing module.
The module solves the depth-averaged shallow-water equations on an unstructured mixed-cell mesh and is integrated in time with the explicit local-inertial finite-volume marcher. 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 = s.surface2d 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:
owner (Solver | ModelBuilder | int)
Construct an accessor retaining its engine owner. Raw registered pointers are deprecated; use
solver.surface2d.- Parameters:
owner (Solver | ModelBuilder | int) – The owning solver or model builder.
- __init__(owner)#
Construct an accessor retaining its engine owner. Raw registered pointers are deprecated; use
solver.surface2d.- Parameters:
owner (Solver | ModelBuilder | int) – The owning solver or model builder.
- Return type:
None
- add_triangle_coupling(tri_idx, node_name, cd, area)#
Append one node->cell coupling row for a triangle (
[2D_TRIANGLE_NODE_MAP]repeated-row form; appends, does not overwrite).
- property boundary_edge_count: int#
Number of boundary edges in the 2D mesh.
- Returns:
Boundary edge count.
- Return type:
- Raises:
EngineError – If the C API call fails.
- property boundary_quality: tuple[BoundaryQuality2D, ...]#
- clear_source(source_id=Ellipsis, cell=Ellipsis)#
- clear_triangle_couplings()#
Remove every authored node->cell coupling row; vertex couplings are untouched.
- Return type:
None
- concentrations(species)#
Per-cell concentration of one surface species (declared units; degC for temperature, seconds for age; dry cells report 0).
- Parameters:
species (int)
- Return type:
NDArray[float64]
- property continuity_error: float#
Global 2D surface continuity error.
- Returns:
M{(total_in - total_out) / total_in}, the domain mass-balance error as a fraction.
- Return type:
- Raises:
EngineError – If the 2D module did not run.
- property dry_depth: float#
Dry-depth threshold (m); triangles below this are treated as dry.
- Returns:
Threshold depth.
- Return type:
- Raises:
EngineError – If the C API call fails.
- edge_is_exterior(cell, edge)#
Inspect native exterior-edge classification after prepare_for_edit().
Invalid indices or unprepared storage raise EngineError. Does not initialize the solver, resolve neighbours or validate manifold topology.
- force_clear_all()#
Clear all 2D forcings.
- Raises:
EngineError – If the C API call fails.
- Return type:
None
- force_coupling_flux(idx, value, *, mode=Ellipsis, persist=Ellipsis)#
Force a coupling flux on a specific triangle.
- Parameters:
- Raises:
EngineError – If the C API rejects the forcing.
- Return type:
None
- force_evap(idx, value, *, mode=Ellipsis, persist=Ellipsis)#
Force evaporation on a specific triangle.
The rate is a demand: wet cells lose depth at this rate, shutting off smoothly as a cell dries (depths never go negative). The default rate is 0 unless forced. Negative values are treated as zero.
- Parameters:
- Raises:
EngineError – If the C API rejects the forcing.
- Return type:
None
- force_evap_uniform(value, *, mode=Ellipsis, persist=Ellipsis)#
Force uniform evaporation on all triangles.
- Parameters:
value (float) – Evaporation rate (m/s; same SI convention as rainfall).
mode (L{SurfaceForcingMode}) – How the value is applied (
OVERRIDEorADD).persist (L{ForcingPersist}) –
PERSISTto hold until cleared;RESETfor a single step.
- Raises:
EngineError – If the C API rejects the forcing.
- Return type:
None
- force_rainfall(idx, value, *, mode=Ellipsis, persist=Ellipsis)#
Force rainfall on a specific triangle.
- Parameters:
- Raises:
EngineError – If the C API rejects the forcing.
- Return type:
None
- force_rainfall_uniform(value, *, mode=Ellipsis, persist=Ellipsis)#
Force uniform rainfall on all triangles.
- Parameters:
value (float) – Rainfall rate (m/s).
mode (L{SurfaceForcingMode}) – How the value is applied (
OVERRIDEorADD).persist (L{ForcingPersist}) –
PERSISTto hold until cleared;RESETfor a single step.
- Raises:
EngineError – If the C API rejects the forcing.
- Return type:
None
- get_cell_neighbours(idx)#
Neighbour cell across each local edge (-1 = boundary), length 3 or 4.
- get_cell_vertex_count(idx)#
Vertices (== edges) of a cell: 3 or 4.
- get_cell_vertices(idx)#
Vertex indices of any cell (length 3 or 4).
- 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:
- Raises:
EngineError – If the C API call fails.
- get_coupling_fluxes()#
Return coupling fluxes for all triangles as a NumPy array. GIL is released during the C call.
- Returns:
Array of shape
(n_triangles,)with dtypefloat64. Positive values denote flux into the 2D surface.- Return type:
np.ndarray
- Raises:
EngineError – 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 (m).
- Return type:
- Raises:
EngineError – If the C API call fails.
- get_depths()#
Return depths for all triangles as a NumPy array. GIL is released during the C call.
- Returns:
Array of shape
(n_triangles,)with dtypefloat64, in m (the 2D solver runs in SI after initialize, whatever the flow units).- Return type:
np.ndarray
- Raises:
LifecycleError – Before
initialize()on a model with a 2D mesh.EngineError – If the C API call fails.
- get_edge_bc_cum_flux(tri_idx, edge)#
Return the cumulative boundary flux for a triangle edge.
- Parameters:
- Returns:
Cumulative boundary flux through the edge.
- Return type:
- Raises:
EngineError – If the C API call fails.
- get_edge_bc_flow(tri_idx, edge)#
Return the prescribed flow per metre for a SPECIFIED_FLOW edge.
- Parameters:
- Returns:
Prescribed flow per metre of edge (
m^3/s/m).- Return type:
- Raises:
EngineError – If the C API call fails.
- get_edge_bc_flow_tseries_name(tri_idx, edge)#
Return the timeseries name driving a SPECIFIED_FLOW edge.
- Parameters:
- Returns:
Timeseries name;
""when the slot is clear.- Return type:
- Raises:
EngineError – If the C API call fails.
- get_edge_bc_head(tri_idx, edge)#
Return the boundary head for a triangle edge.
- Parameters:
- Returns:
Boundary head value.
- Return type:
- Raises:
EngineError – If the C API call fails.
- get_edge_bc_rating_curve_name(tri_idx, edge)#
Return the rating-curve name driving a RATING_CURVE edge.
- Parameters:
- Returns:
Rating-curve name;
""when the slot is clear.- Return type:
- Raises:
EngineError – If the C API call fails.
- get_edge_bc_slope(tri_idx, edge)#
Return the boundary slope for a triangle edge.
- Parameters:
- Returns:
Boundary slope.
- Return type:
- Raises:
EngineError – If the C API call fails.
- get_edge_bc_tseries_name(tri_idx, edge)#
Return the timeseries name driving a SPECIFIED_STAGE edge.
- Parameters:
- Returns:
Timeseries name;
""when the slot is clear.- Return type:
- Raises:
EngineError – If the C API call fails.
- get_edge_bc_type(tri_idx, edge)#
Return the boundary condition type for a triangle edge.
- Parameters:
- Returns:
Boundary condition type.
- Return type:
L{SurfaceBoundaryType}
- Raises:
EngineError – If the C API call fails.
- get_edge_conveyance(tri, edge)#
Return the per-edge conveyance factor in
[0, 1].- Parameters:
- Returns:
Conveyance factor (1.0 = unrestricted, 0.0 = wall).
- Return type:
- Raises:
EngineError – If the C API call fails.
- get_edge_conveyance_bulk()#
Return a NumPy array of all per-edge conveyance factors.
Length is
triangle_count * 3, indexed[tri*3 + edge].- Return type:
np.ndarray
- get_edge_flux_bulk()#
Return normal edge fluxes for all triangle edges. GIL is released during the C call.
Indexed as
[tri*3 + localEdge].- Returns:
Array of shape
(n_triangles*3,)with dtypefloat64.- Return type:
NDArray[float64]
- get_edge_geometry_bulk()#
Return time-invariant edge lengths and outward unit normal components. GIL is released during the C call.
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[float64], NDArray[float64], NDArray[float64]]
- get_edge_wall_drag(tri_idx, edge)#
Return dimensionless tangential WALL Cw; zero means free slip.
- get_head(idx)#
Return the total head at a specific triangle.
- Parameters:
idx (int) – Triangle index.
- Returns:
Total head (m).
- Return type:
- Raises:
EngineError – If the C API call fails.
- get_heads()#
Return total heads for all triangles as a NumPy array. GIL is released during the C call.
- Returns:
Array of shape
(n_triangles,)with dtypefloat64, in m.- Return type:
np.ndarray
- Raises:
EngineError – If the C API call fails.
- get_mass_balance()#
Return the global 2D mass-balance terms.
- Returns:
Mapping with keys
init_storage,final_storage,rainfall_in,coupling_1d_to_2d_in,coupling_2d_to_1d_out,outfall_in,boundary_in,boundary_out, C{evap_out} (allm^3) andcontinuity_error(fraction).- Return type:
- Raises:
EngineError – If the 2D module did not run.
- get_net_source(idx)#
Return the net source term at a specific triangle.
- Parameters:
idx (int) – Triangle index.
- Returns:
Net source term.
- Return type:
- Raises:
EngineError – If the C API call fails.
- get_node_coupling_default_type(node_idx)#
Class default coupling type of a node.
- Parameters:
node_idx (int)
- Return type:
NodeCoupling2DType
- get_node_coupling_param(node_idx, key)#
Authored parameter token, or “” when not authored.
- get_node_coupling_type(node_idx)#
Effective coupling type and whether it is authored (else the class default).
- get_rainfall(idx)#
Return the current rainfall at a specific triangle.
- Parameters:
idx (int) – Triangle index.
- Returns:
Rainfall rate.
- Return type:
- Raises:
EngineError – If the C API call fails.
- get_stat_max_continuity_err()#
Return cumulative maximum M{abs(continuity residual)} envelope per triangle.
- Returns:
Array of shape
(n_triangles,)with dtypefloat64, inm^3/s.- Return type:
np.ndarray
- Raises:
EngineError – If the C API call fails.
- get_stat_max_depths()#
Return cumulative maximum-depth envelope for all triangles.
- Returns:
Array of shape
(n_triangles,)with dtypefloat64, in m.- Return type:
np.ndarray
- Raises:
EngineError – If the C API call fails.
- get_stat_max_velocities()#
Return cumulative maximum velocity-magnitude envelope per triangle.
- Returns:
Array of shape
(n_triangles,)with dtypefloat64, in m/s.- Return type:
np.ndarray
- Raises:
EngineError – If the C API call fails.
- get_surface_owners()#
- Return type:
NDArray[int32]
- get_triangle_area(idx)#
Return the area of a triangle.
- Parameters:
idx (int) – Triangle index.
- Returns:
Triangle area in project units squared.
- Return type:
- Raises:
EngineError – If the C API call fails.
- get_triangle_centroid(idx)#
Return the (cx, cy, cz) centroid coordinates for a triangle.
- 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
-1if no coupling exists.- Return type:
- Raises:
EngineError – If the C API call fails.
- get_triangle_coupling_row(row_idx)#
Read one authored row:
(tri_idx, node_idx, cd, area);node_idxis-1if unresolved.
- get_triangle_init_depth(idx)#
Return the initial water depth of a triangle, in mesh length units.
- get_triangle_init_hgl(idx)#
Return a cell’s prescribed initial water-surface elevation (NaN if unset).
- get_triangle_init_velocity(idx)#
Return the
(u, v)initial velocity of a triangle, in m/s.
- 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:
- Raises:
EngineError – If the C API call fails.
- get_triangle_neighbours(idx)#
Return the (n0, n1, n2) neighbour triangle indices.
- get_triangle_tag(idx)#
Return the descriptive tag of a triangle (
[2D_TRIANGLES]TAG).
- get_triangle_vertices(idx)#
Return the (v0, v1, v2) vertex indices for a triangle.
- get_velocities()#
Independent physical Cartesian X/Y velocity arrays in m/s.
Both float64 arrays have shape
(n_cells,)and match native output. FULL_SWE uses accepted momentum; other closures use native diagnostic reconstruction. Dry cells return zero; indeterminate wet cells retain paired NaNs. Refreshing does not advance hydraulics and releases the GIL. Requires an initialized surface; stale views are rejected.- Return type:
tuple[NDArray[float64], NDArray[float64]]
- get_vertex_coords()#
Return (x, y, z) NumPy arrays for all vertices. GIL is released during the C call.
- Returns:
Tuple
(x, y, z), each of shape(n_vertices,)with dtypefloat64.- Return type:
tuple[np.ndarray, np.ndarray, np.ndarray]
- Raises:
EngineError – 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
-1if no coupling exists.- Return type:
- Raises:
EngineError – If the C API call fails.
- get_vertex_coupling_area(vertex_idx)#
Return the coupling exchange area of a vertex.
Corresponds to the
[2D_VERTEX_NODE_MAP]AREA column in m^2 (default 1.0).- Parameters:
vertex_idx (int) – Vertex index (0-based).
- Returns:
Exchange area in m^2.
- Return type:
- Raises:
EngineError – If the C API call fails.
- get_vertex_coupling_cd(vertex_idx)#
Return the coupling discharge coefficient of a vertex.
Corresponds to the
[2D_VERTEX_NODE_MAP]CD column (default 0.65).- Parameters:
vertex_idx (int) – Vertex index (0-based).
- Returns:
Discharge coefficient.
- Return type:
- Raises:
EngineError – If the C API call fails.
- get_vertex_head(idx)#
Scalar water-surface head at one mesh vertex (project units).
- get_vertex_heads()#
Return reconstructed heads at all vertices as a NumPy array. GIL is released during the C call.
- Returns:
Array of shape
(n_vertices,)with dtypefloat64.- Return type:
np.ndarray
- Raises:
EngineError – If the C API call fails.
- get_vertex_render_depths()#
Return render-oriented signed water depths at all vertices.
The wet-masked, depth-weighted free-surface reconstruction
eta_v - z_v(m) that GUIs should interpolate for water-surface rendering. GIL is released during the C call.- Returns:
Array of shape
(n_vertices,)with dtypefloat64.- Return type:
np.ndarray
- Raises:
EngineError – If the C API call fails.
- get_vertex_tag(idx)#
Return the descriptive tag of a vertex (
[2D_VERTICES]TAG).
- get_vertex_xyz(idx)#
Scalar
(x, y, z)for one mesh vertex (project units).
- property groundwater: Groundwater#
- property infiltration: Infiltration2DView#
surface2d.infiltration— the per-cell infiltration sub-view.- Return type:
- property initial_bed_quality: tuple[InitialQuality2D, ...]#
- property initial_quality: tuple[InitialQuality2D, ...]#
- property is_active: bool#
Trueif the 2D module is active for this simulation.- Returns:
Activation flag.
- Return type:
- Raises:
EngineError – If the C API call fails.
- property max_depth: float#
Maximum depth across all triangles.
- Returns:
Maximum depth.
- Return type:
- Raises:
EngineError – If the C API call fails.
- property n_triangles: int#
Number of mesh triangles.
- Returns:
Triangle count.
- Return type:
- Raises:
EngineError – If the C API call fails.
- property n_vertices: int#
Number of mesh vertices.
- Returns:
Vertex count.
- Return type:
- Raises:
EngineError – If the C API call fails.
- prepare_for_edit()#
Make the parsed 2D mesh editable without a full
initialize().- Return type:
None
- preview_surface_owners(rows=Ellipsis)#
- property quality: SurfaceQuality#
- replace_node_coupling(node_idx, coupling_type, params=Ellipsis, *, authored=Ellipsis)#
- replace_surface_owners(rows, expected_token)#
- reset_edge_conveyance()#
Reset every edge’s conveyance factor to 1.0 (unrestricted).
- Return type:
None
- reset_node_coupling(node_idx)#
Remove a node’s [2D_NODE_COUPLING] row.
- Parameters:
node_idx (int)
- Return type:
None
- property run_stats: dict[str, Any]#
Cumulative marcher statistics and the backend of this 2D run.
Keys:
backend,momentum,lts_tiers,steps,face_evals,last_step,active_frac(min, mean, max) andtier_cells(one entry per populated LTS tier).The value type is
Anybecause the mapping is heterogeneous:strforbackend,strorintformomentum, C{int} counts,floatforlast_step, a 3-tuple foractive_fracand a list fortier_cells.- Returns:
Statistics dictionary.
- Return type:
- Raises:
EngineError – If the C API call fails.
- set_boundary_quality(cell, edge, species, conc)#
- set_edge_bc_concentrations(cell, edge, concentrations)#
- set_edge_bc_flow(tri_idx, edge, flow)#
Set the prescribed flow per metre for a SPECIFIED_FLOW edge.
- Parameters:
- Raises:
EngineError – If the C API rejects the assignment.
- Return type:
None
- set_edge_bc_flow_tseries_name(tri_idx, edge, name)#
Set the timeseries name driving a SPECIFIED_FLOW edge.
- Parameters:
- Raises:
EngineError – If the C API rejects the assignment.
- Return type:
None
- set_edge_bc_group(tri_idx, edge, group)#
Author or clear a UTF-8 group token in OPENED/BUILDING state.
Call
prepare_for_edit()first. Nonempty groups require an exterior edge and cannot contain whitespace, INP delimiters or NUL. Hydraulic boundary values are preserved; an empty name clears the group.
- set_edge_bc_head(tri_idx, edge, head)#
Set the boundary head for a triangle edge.
- Parameters:
- Raises:
EngineError – If the C API rejects the assignment.
- Return type:
None
- set_edge_bc_rating_curve_name(tri_idx, edge, name)#
Set the rating-curve name driving a RATING_CURVE edge.
- Parameters:
- Raises:
EngineError – 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:
- Raises:
EngineError – If the C API rejects the assignment.
- Return type:
None
- set_edge_bc_tseries_name(tri_idx, edge, name)#
Set the timeseries name driving a SPECIFIED_STAGE edge.
- Parameters:
- Raises:
EngineError – 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:
- Raises:
EngineError – If the C API rejects the assignment.
- Return type:
None
- set_edge_conveyance(tri, edge, conveyance)#
Set the per-edge conveyance factor in
[0, 1].For interior edges the value is mirrored to the partner slot on the neighbouring triangle so mass conservation is preserved.
- Parameters:
- Raises:
EngineError – If the C API rejects the assignment.
- Return type:
None
- set_edge_wall_drag(tri_idx, edge, cw)#
Author finite nonnegative WALL Cw in OPENED/BUILDING state.
Requires prepared storage and an exterior WALL edge for positive Cw. Positive drag runs with CPU FULL_SWE, one tier and uncoupled hydraulics.
- set_flow_boundary(cell, edge, flow_m3_s, concentrations=Ellipsis)#
- set_head_boundary(cell, edge, head_m, concentrations=Ellipsis)#
- set_heat_source(cells, heat_w, *, source_id=Ellipsis, until_seconds=Ellipsis)#
- set_initial_bed_quality(species, conc, *, tag=Ellipsis, cell=Ellipsis)#
- set_initial_quality(species, conc, *, tag=Ellipsis, cell=Ellipsis)#
- set_node_coupling_param(node_idx, key, value)#
Author a parameter from its token; None or “” clears it.
- set_node_coupling_type(node_idx, coupling_type)#
Author a node’s coupling type (drops parameters that do not apply).
- set_results_file(path)#
Bind a fresh absolute HDF5 destination before initialize; opens at start.
- Parameters:
path (str)
- Return type:
None
- set_species_source(cells, species_rates, *, source_id=Ellipsis, until_seconds=Ellipsis)#
- set_triangle_init_depth(idx, depth)#
Set the initial water depth of a triangle (mesh length units, M{>= 0}).
- set_triangle_init_hgl(idx, hgl)#
Prescribe a cell’s initial water-surface elevation (NaN clears it).
- set_triangle_init_velocity(idx, u, v)#
Set the
(u, v)initial velocity of a triangle (m/s, finite).
- set_triangle_mannings(idx, n)#
Set Manning’s M{n} for a triangle (must be strictly positive).
- set_triangle_tag(idx, tag)#
Set the descriptive tag of a triangle (empty string clears it).
- set_vertex_coupled_node(vertex_idx, node_name)#
Couple a mesh vertex to a 1D SWMM node by name (
""clears).
- set_vertex_coupling_area(vertex_idx, area)#
Set the coupling exchange area of a vertex in m^2 (must be > 0).
- set_vertex_coupling_cd(vertex_idx, cd)#
Set the coupling discharge coefficient of a vertex (must be > 0).
- set_vertex_tag(idx, tag)#
Set the descriptive tag of a vertex (empty string clears it).
- set_vertex_z(idx, z)#
Set the ground elevation of a mesh vertex.
Updates derived geometry for every triangle incident to this vertex (centroid Z, per-edge midpoint Z). XY-derived fields are unaffected. When called during a running simulation, solver state (head, depth) is intentionally not rewritten — the implied depth = head - bed therefore changes by the same amount as bed.
- Parameters:
- Raises:
EngineError – If the C API call fails.
- Return type:
None
- set_vertex_z_bulk(z)#
Set EVERY vertex ground elevation in one call.
Equivalent to calling
set_vertex_z()per vertex, but rescans the mesh once instead of once per vertex. GIL is released during the C call.- Parameters:
z (Sequence[float] | np.ndarray) – One ground elevation per vertex (project vertical units).
- Raises:
ValueError – If
len(z)does not equaln_vertices.EngineError – If the C API call fails.
- Return type:
None
- set_water_source(cells, flow_m3_s, **kwargs)#
- property snow: MeshSnow#
- property solver_last_step: float#
The explicit marcher’s last sub-step size in seconds.
Renamed from
cvode_last_stepwith the D2 CVODE/ARKODE retirement.- Returns:
Step size.
- Return type:
- Raises:
EngineError – If the C API call fails.
- property solver_steps: int#
Number of explicit-marcher sub-steps in the last advance.
Renamed from
cvode_stepswith the D2 CVODE/ARKODE retirement.- Returns:
Step count.
- Return type:
- Raises:
EngineError – If the C API call fails.
- source_receipt(source_id=Ellipsis, cell=Ellipsis)#
- property sources: DomainSources#
- property species: tuple[str, ...]#
pollutants, MSX species,
__WATER_AGE__,__TEMPERATURE__.- Type:
Surface-transported species names in native row order
- property total_exchange_flow: float#
Total exchange flow rate.
- Returns:
Exchange flow rate in
m^3/s(positive = into 1D network).- Return type:
- Raises:
EngineError – 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:
- Raises:
EngineError – If the C API call fails.
- property triangle_coupling_count: int#
Number of triangle-to-node coupling points.
- Returns:
Coupling count.
- Return type:
- Raises:
EngineError – If the C API call fails.
- validate_node_coupling(node_idx, coupling_type, params=Ellipsis, *, authored=Ellipsis)#
- property vertex_coupling_count: int#
Number of vertex-to-node coupling points.
- Returns:
Coupling count.
- Return type:
- Raises:
EngineError – 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:
EnumEnumeration 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#
- LINK = 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:
EnumEnumeration 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:
EnumEnumeration 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:
EnumEnumeration of SWMM raingage properties.
- Variables:
GAGE_TOTAL_PRECIPITATION – Total precipitation
GAGE_RAINFALL – Rainfall
GAGE_SNOWFALL – Snowfall
GAGE_SCALEFACTOR – Rainfall scaling factor (dimensionless, > 0)
- GAGE_TOTAL_PRECIPITATION = Ellipsis#
- GAGE_RAINFALL = Ellipsis#
- GAGE_SNOWFALL = Ellipsis#
- GAGE_SCALEFACTOR = Ellipsis#
- class SWMMSubcatchmentProperties(*values)#
Bases:
EnumEnumeration 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
API_PET – API prescribed potential evapotranspiration rate
- AREA = Ellipsis#
- RAINGAGE = Ellipsis#
- RAINFALL = Ellipsis#
- EVAPORATION = Ellipsis#
- INFILTRATION = Ellipsis#
- RUNOFF = Ellipsis#
- REPORT_FLAG = Ellipsis#
- WIDTH = Ellipsis#
- SLOPE = Ellipsis#
- OUTLET_TYPE = Ellipsis#
- OUTLET_INDEX = Ellipsis#
- INFILTRATION_MODEL = Ellipsis#
- FRACTION_IMPERVIOUS = Ellipsis#
- SUB_AREA_ROUTE_TO = Ellipsis#
- SUB_AREA_FRACTION_OUTLET = Ellipsis#
- SUB_AREA_MANNINGS_N = Ellipsis#
- SUB_AREA_FRACTION_AREA = Ellipsis#
- SUB_AREA_DEPRESSION_STORAGE = Ellipsis#
- SUB_AREA_INFLOW = Ellipsis#
- SUB_AREA_RUNOFF = Ellipsis#
- SUB_AREA_DEPTH = Ellipsis#
- LID_UNITS_COUNT = Ellipsis#
- LID_UNITS_PERV_AREA = Ellipsis#
- LID_UNITS_FLOW_TO_PERV_AREA = Ellipsis#
- LID_UNITS_DRAIN_FLOW = Ellipsis#
- LID_UNIT_REPLICATES = Ellipsis#
- LID_UNIT_AREA = Ellipsis#
- LID_UNIT_FULL_WIDTH = Ellipsis#
- LID_UNIT_BOTTOM_WIDTH = Ellipsis#
- LID_UNIT_INIT_SATURATION = Ellipsis#
- LID_UNIT_FROM_IMPERVIOUS = Ellipsis#
- LID_UNIT_FROM_PERVIOUS = Ellipsis#
- LID_UNIT_TO_PERVIOUS = Ellipsis#
- LID_UNIT_RECEIVING_OUTLET_TYPE = Ellipsis#
- LID_UNIT_RECEIVING_OUTLET_INDEX = Ellipsis#
- LID_UNIT_SURFACE_DEPTH = Ellipsis#
- LID_UNIT_SOIL_MOISTURE = Ellipsis#
- LID_UNIT_GREEN_AMPT_CAPILLARY_SUCTION = Ellipsis#
- LID_UNIT_GREEN_AMPT_SATURATED_CONDUCTIVITY = Ellipsis#
- LID_UNIT_GREEN_AMPT_MAX_SOIL_MOISTURE_DEFICIT = 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#
- API_PET = Ellipsis#
- GW_MOISTURE = Ellipsis#
- GW_LOWER_DEPTH = Ellipsis#
- SNOW_SWE = Ellipsis#
- SNOW_FW = Ellipsis#
- SNOW_ATI = Ellipsis#
- SNOW_COLDC = Ellipsis#
- RAIN_SCALE_FACTOR = Ellipsis#
- SNOW_SCALE_FACTOR = Ellipsis#
- class SWMMNodeProperties(*values)#
Bases:
EnumEnumeration 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
OUTFLOW – Total outflow through downstream links
- 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#
- STORAGE_AREA = Ellipsis#
- INITIAL_DEPTH = Ellipsis#
- POLLUTANT_CONCENTRATION = Ellipsis#
- POLLUTANT_LATERAL_MASS_FLUX = Ellipsis#
- OUTFLOW = Ellipsis#
- class SWMMLinkProperties(*values)#
Bases:
EnumEnumeration 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:
EnumEnumeration 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
EVAP_RATE – Current climate-derived evaporation rate (read-only)
TEMPERATURE – Current air temperature (read-only)
API_TEMPERATURE – API prescribed air temperature
WIND_SPEED – Current wind speed (read-only)
API_WIND_SPEED – API prescribed wind speed
- 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#
- EVAP_RATE = Ellipsis#
- TEMPERATURE = Ellipsis#
- API_TEMPERATURE = Ellipsis#
- WIND_SPEED = Ellipsis#
- API_WIND_SPEED = Ellipsis#
- API_EVAP = Ellipsis#
- EVAP_DRY_ONLY = Ellipsis#
- class SWMMPollutantProperties(*values)#
Bases:
EnumEnumeration of SWMM pollutant properties (runtime-settable source concentrations in pollutant units).
- Variables:
RAIN_CONCENTRATION – Rain (wet deposition) concentration
GW_CONCENTRATION – Groundwater inflow concentration
RDII_CONCENTRATION – RDII inflow concentration
DWF_CONCENTRATION – Dry weather sanitary flow concentration
KDECAY – First-order decay constant (1/day); live each step
CO_POLLUTANT – Co-pollutant index (-1 = none)
CO_FRACTION – Co-pollutant fraction (0-1)
SNOW_ONLY – Buildup-only-under-snow flag (0/1)
INIT_CONCENTRATION – Initial network concentration (pre-start only)
- RAIN_CONCENTRATION = Ellipsis#
- GW_CONCENTRATION = Ellipsis#
- RDII_CONCENTRATION = Ellipsis#
- DWF_CONCENTRATION = Ellipsis#
- KDECAY = Ellipsis#
- CO_POLLUTANT = Ellipsis#
- CO_FRACTION = Ellipsis#
- SNOW_ONLY = Ellipsis#
- INIT_CONCENTRATION = Ellipsis#
- class SWMMPatternProperties(*values)#
Bases:
EnumEnumeration of SWMM time-pattern properties (runtime-settable multiplier factors). For
FACTORpass the 0-based factor position as thesub_indexargument ofset_value/get_value.- Variables:
FACTOR – One multiplier factor (sub_index = factor position)
COUNT – Number of factors in the pattern (read-only)
TYPE – Pattern type code (read-only): 0 monthly/1 daily/2 hourly/3 weekend
- FACTOR = Ellipsis#
- COUNT = Ellipsis#
- TYPE = Ellipsis#
- class SWMMLandUseProperties(*values)#
Bases:
EnumEnumeration of SWMM land-use properties (runtime-settable street sweeping parameters).
Buildup/washoff parameters are per land use and pollutant; pass the 0-based pollutant index as the
sub_indexargument.- Variables:
SWEEP_INTERVAL – Street-sweeping interval (days)
SWEEP_REMOVAL – Fraction of buildup available for sweeping (0-1)
BUILDUP_FUNC – Buildup function type code (sub_index = pollutant)
BUILDUP_COEFF1 – Buildup coefficient c0 / max buildup
BUILDUP_COEFF2 – Buildup coefficient c1 / rate
BUILDUP_COEFF3 – Buildup coefficient c2 / exponent
BUILDUP_NORMALIZER – Buildup normalizer: 0 area, 1 curb length
WASHOFF_FUNC – Washoff function type code
WASHOFF_COEFF – Washoff coefficient
WASHOFF_EXPON – Washoff exponent
WASHOFF_SWEEP_EFFIC – Washoff street-sweeping efficiency (0-1)
WASHOFF_BMP_EFFIC – Washoff BMP efficiency (0-1)
- SWEEP_INTERVAL = Ellipsis#
- SWEEP_REMOVAL = Ellipsis#
- BUILDUP_FUNC = Ellipsis#
- BUILDUP_COEFF1 = Ellipsis#
- BUILDUP_COEFF2 = Ellipsis#
- BUILDUP_COEFF3 = Ellipsis#
- BUILDUP_NORMALIZER = Ellipsis#
- WASHOFF_FUNC = Ellipsis#
- WASHOFF_COEFF = Ellipsis#
- WASHOFF_EXPON = Ellipsis#
- WASHOFF_SWEEP_EFFIC = Ellipsis#
- WASHOFF_BMP_EFFIC = Ellipsis#
- class SWMMAquiferProperties(*values)#
Bases:
EnumEnumeration of SWMM aquifer properties (input-file units).
The flux-coefficient properties (conductivity, slopes, evap/loss coefficients) are read live each step and are settable both before the simulation starts and while it is running; the structural / initial-condition properties are pre-start-only.
- Variables:
POROSITY – Porosity (volumetric fraction, pre-start-only)
WILTING_POINT – Wilting point (volumetric fraction, pre-start-only)
FIELD_CAPACITY – Field capacity (volumetric fraction, pre-start-only)
CONDUCTIVITY – Saturated hydraulic conductivity (in/hr or mm/hr)
CONDUCT_SLOPE – Conductivity slope
TENSION_SLOPE – Tension slope (ft or m)
UPPER_EVAP_FRAC – Upper-zone evaporation fraction (0-1)
LOWER_EVAP_DEPTH – Lower-zone evaporation depth (ft or m)
LOWER_LOSS_COEFF – Lower-zone seepage-loss coefficient (in/hr or mm/hr)
BOTTOM_ELEV – Aquifer bottom elevation (ft or m, pre-start-only)
WATER_TABLE_ELEV – Initial water table elevation (ft or m, pre-start-only)
UPPER_MOISTURE – Initial upper-zone moisture (volumetric fraction, pre-start-only)
- POROSITY = Ellipsis#
- WILTING_POINT = Ellipsis#
- FIELD_CAPACITY = Ellipsis#
- CONDUCTIVITY = Ellipsis#
- CONDUCT_SLOPE = Ellipsis#
- TENSION_SLOPE = Ellipsis#
- UPPER_EVAP_FRAC = Ellipsis#
- LOWER_EVAP_DEPTH = Ellipsis#
- LOWER_LOSS_COEFF = Ellipsis#
- BOTTOM_ELEV = Ellipsis#
- WATER_TABLE_ELEV = Ellipsis#
- UPPER_MOISTURE = Ellipsis#
- class SWMMFlowUnits(*values)#
Bases:
EnumEnumeration 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:
EnumEnumeration 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:
- 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:
- 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:
- get_error_message(error_code)#
Get the error message for a SWMM error code.
- class SolverState(*values)#
Bases:
EnumAn 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:
EnumAn 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:
ExceptionException class for SWMM output file processing errors.
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:
objectConstructor to create a new SWMM solver.
- Parameters:
- __init__(inp_file, rpt_file=None, out_file=None, stride_step=300, save_results=True)#
Constructor to create a new SWMM solver.
- 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
- clear_treatment(node_index, pollutant_index)#
Remove the treatment expression for a node/pollutant pair.
Callable before the simulation starts or while it is running; zero removal applies from the next routing step on.
- 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:
- 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:
- property end_datetime: datetime#
Get the end date of the simulation.
- Returns:
End date
- Return type:
datetime
- finalize()#
Finalize the solver. Ends simulation, reports the results, and dispose objects.
- Return type:
- get_link_statistics(index)#
Per-link post-simulation statistics.
- get_mass_balance_error()#
Get the mass balance error.
- get_node_statistics(index)#
Per-node post-simulation statistics.
- 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:
- 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:
- 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:
- 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_pump_statistics(index)#
Per-pump post-simulation statistics.
- get_routing_totals()#
Get system-level flow routing mass balance totals.
- get_runoff_totals()#
Get system-level surface runoff mass balance totals.
- get_subcatchment_statistics(index)#
Per-subcatchment post-simulation statistics.
- get_value(object_type, property_type, index, sub_index=Ellipsis)#
Get a SWMM system property value.
- Parameters:
object_type (SWMMObjects) – SWMM object type (e.g., SWMMObjects.NODE)
property_type (Union[SWMMRainGageProperties, SWMMSubcatchmentProperties, SWMMNodeProperties, SWMMLinkProperties, SWMMSystemProperties]) – SWMM system property type (e.g., SWMMSystemProperties.START_DATE)
sub_index (int) – Sub-index (e.g., 0) for properties with sub-indexes. For example pollutant index for POLLUTANT properties.
- 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:
- 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:
- property progress_callbacks_per_second: int#
Get the number of progress callbacks per second.
- Returns:
Progress callbacks per second
- Return type:
- 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:
- 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.
- set_lid_drain(lid_index, coeff, expon, offset)#
Set the underdrain flow parameters of a LID process at runtime.
The drain parameters are read live each routing step, so a mid-run edit takes effect on the next step. Values use input-file units, matching the [LID_CONTROLS] DRAIN line.
- set_treatment(node_index, pollutant_index, expression)#
Set (or replace) the treatment expression for a node/pollutant pair.
Callable before the simulation starts or while it is running; a mid-run edit is evaluated from the next routing step on. A failed parse raises and leaves no treatment in place for the pair.
- set_value(object_type, property_type, index, value, sub_index=Ellipsis)#
Set a SWMM system property value.
- Parameters:
object_type (SWMMObjects) – SWMM object type (e.g., SWMMObjects.NODE)
property_type (Union[SWMMRainGageProperties, SWMMSubcatchmentProperties, SWMMNodeProperties, SWMMLinkProperties, SWMMSystemProperties]) – SWMM system property type (e.g., SWMMSystemProperties.START_DATE)
value (double) – Property value (e.g., 10.0)
sub_index (int) – Sub-index (e.g., 0) for properties with sub-indexes. For example pollutant index for POLLUTANT properties.
- Return type:
None
- property solver_state: SolverState#
Get the state of the solver.
- Returns:
Solver state
- Return type:
- 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:
- 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_stateor readcurrent_datetimefor per-step data.- Return type:
- class LegacyNodes(solver)[source]#
Bases:
objectIterable collection of all SWMM nodes in the model.
- Parameters:
solver (Solver)
- class LegacyNode(solver, index, name='')[source]#
Bases:
objectProperty-based access to a single SWMM node.
- property node_type: SWMMNodeTypes#
- 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:
flow (float) – Inflow rate in project flow units. Positive = inflow.
log (ExternalForcingLog | None) – Optional
ExternalForcingLogfor audit.
- 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:
value (float) – Mass flux in project mass/time units.
pollutant_index (int) – 0-based pollutant index.
log (ExternalForcingLog | None) – Optional
ExternalForcingLogfor audit.
- 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:
value (float) – Depth in project length units.
log (ExternalForcingLog | None) – Optional
ExternalForcingLogfor audit.
- Return type:
None
- class LegacyLinks(solver)[source]#
Bases:
objectIterable collection of all SWMM links in the model.
- Parameters:
solver (Solver)
- class LegacyLink(solver, index, name='')[source]#
Bases:
objectProperty-based access to a single SWMM link.
- property link_type: SWMMLinkTypes#
- 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:
value (float) – Setting value (typically 0-1).
log (ExternalForcingLog | None) – Optional
ExternalForcingLogfor audit.
- 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:
value (float) – Flow rate in project flow units.
log (ExternalForcingLog | None) – Optional
ExternalForcingLogfor audit.
- Return type:
None
- class LegacySubcatchments(solver)[source]#
Bases:
objectIterable collection of all SWMM subcatchments.
- Parameters:
solver (Solver)
- class LegacySubcatchment(solver, index, name='')[source]#
Bases:
objectProperty-based access to a single SWMM subcatchment.
- property rain_scale_factor: float#
Per-subcatchment rainfall scale factor (> 0; 1.0 = no scaling).
Optional [SUBCATCHMENTS] token 9. Multiplies the gage-derived rainfall, composing with the gage scale factor. Settable mid-run. Raises if <= 0.
- property snow_scale_factor: float#
Per-subcatchment snowfall scale factor (> 0; 1.0 = no scaling).
Optional [SUBCATCHMENTS] token 10. Composes with the gage snow catch factor (SCF). Settable mid-run. Raises if <= 0.
- property infiltration_model: int#
Infiltration model code (0=Horton, 1=ModHorton, 2=GreenAmpt, etc.).
- get_subarea_mannings_n(sub_index)[source]#
Manning’s n for a subarea. sub_index: 0=impervious, 1=pervious.
- get_pollutant_runoff_concentration(pollutant_index=0)[source]#
Current pollutant concentration in runoff.
- 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:
value (float) – Rainfall intensity in project rainfall units.
log (ExternalForcingLog | None) – Optional
ExternalForcingLogfor audit.
- 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:
value (float) – Snowfall rate in project units.
log (ExternalForcingLog | None) – Optional
ExternalForcingLogfor audit.
- Return type:
None
- set_api_pet(value, log=None)[source]#
Prescribe a potential evapotranspiration rate for this subcatchment.
Overrides the climate-derived evaporation rate for the subcatchment’s surface, LID, and groundwater upper-zone evaporation. The prescribed rate is applied as-is (it bypasses the DRY_ONLY option and monthly adjustments). Actual evaporation is capped to available water, so losses appear in the runoff totals under
evaporation. Persists until cleared withclear_api_pet.- Parameters:
value (float) – PET rate in user units (in/day or mm/day).
log (ExternalForcingLog or None) – Optional external forcing log for audit.
- Returns:
None
- Return type:
None
- get_api_pet()[source]#
Return the currently prescribed PET rate for this subcatchment.
- Returns:
Prescribed PET rate in user units (in/day or mm/day), or a negative value when no prescription is active.
- Return type:
- clear_api_pet(log=None)[source]#
Clear any prescribed PET rate, reverting to climate-derived evaporation.
- Parameters:
log (ExternalForcingLog or None) – Optional external forcing log for audit.
- Returns:
None
- 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:
value (float) – Mass to add in project mass units.
pollutant_index (int) – 0-based pollutant index.
log (ExternalForcingLog | None) – Optional
ExternalForcingLogfor audit.
- Return type:
None
- property gw_moisture: float#
Groundwater upper-zone moisture content (state injection).
Reading returns the current upper-zone moisture; setting injects it mid-run. The subcatchment must have groundwater. Mass balance reflects the resulting storage discontinuity (hotstart-equivalent semantics).
- property gw_lower_depth: float#
Groundwater saturated-zone depth above the aquifer bottom (project length units; state injection).
- set_snow_state(surface, swe=None, fw=None, ati=None, coldc=None)[source]#
Inject the snow-pack state on one snow surface (state assimilation).
- Parameters:
surface (int) – Snow subarea (0 plowable, 1 impervious, 2 pervious), passed through as the property
sub_index.swe (float or None) – Snow water equivalent in project depth units; omit to leave unchanged.
fw (float or None) – Free water in project depth units; omit to leave unchanged.
ati (float or None) – Antecedent temperature index (deg F US, deg C SI); omit to leave unchanged.
coldc (float or None) – Cold content in project depth units; omit to leave unchanged.
- Return type:
None
- class LegacyRainGages(solver)[source]#
Bases:
objectIterable collection of all SWMM rain gages.
- Parameters:
solver (Solver)
- class LegacyRainGage(solver, index, name='')[source]#
Bases:
objectProperty-based access to a single SWMM rain gage.
- 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:
value (float) – Rainfall rate in project rainfall units.
log (ExternalForcingLog | None) – Optional
ExternalForcingLogfor audit.
- Return type:
None
- class LegacySystem(solver)[source]#
Bases:
objectSystem-level properties, simulation settings, and mass balance totals.
Wraps a
Solverinstance 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.
- get_evap_rate()[source]#
Return the current climate-derived evaporation rate.
The rate the engine would apply in the absence of any PET prescription, including monthly adjustments (read-only). Intended for caller-side composition with
LegacySubcatchment.set_api_pet: read this rate, apply your own adjustment logic, and prescribe the result.- Returns:
Evaporation rate in user units (in/day or mm/day).
- Return type:
- get_temperature()[source]#
Return the current air temperature.
- Returns:
Air temperature in user units (deg F or deg C).
- Return type:
- set_api_temperature(value)[source]#
Prescribe the air temperature used for snowmelt and temperature-derived evaporation.
Overrides the climate data-source value (bypassing monthly adjustments) and keeps derived quantities (saturation vapor pressure) consistent. Persists until cleared with
clear_api_temperature.- Parameters:
value (float) – Air temperature in user units (deg F or deg C).
- Returns:
None
- Return type:
None
- get_api_temperature()[source]#
Return the prescribed air temperature.
- Returns:
Prescribed temperature in user units, or -999 when no prescription is active.
- Return type:
- clear_api_temperature()[source]#
Clear any prescribed air temperature, reverting to climate data.
- Returns:
None
- Return type:
None
- get_wind_speed()[source]#
Return the current wind speed.
- Returns:
Wind speed in user units (mph or km/hr).
- Return type:
- set_api_wind_speed(value)[source]#
Prescribe the wind speed used in rain-on-snow melt.
Overrides the monthly/climate-file value. Persists until cleared with
clear_api_wind_speed.- Parameters:
value (float) – Wind speed in user units (mph or km/hr), >= 0.
- Returns:
None
- Return type:
None
- get_api_wind_speed()[source]#
Return the prescribed wind speed.
- Returns:
Prescribed wind speed in user units, or a negative value when no prescription is active.
- Return type:
- clear_api_wind_speed()[source]#
Clear any prescribed wind speed, reverting to climate data.
- Returns:
None
- Return type:
None
- set_api_evap_rate(value)[source]#
Prescribe the system-wide evaporation rate.
Replaces the climate-derived rate (after monthly adjustments) for every consumer — subcatchments, LID units, groundwater, conduits and storage nodes. Per-subcatchment
LegacySubcatchment.set_api_petstill takes precedence. Persists until cleared withclear_api_evap_rate.- Parameters:
value (float) – Evaporation rate in user units (in/day or mm/day), >= 0.
- Returns:
None
- Return type:
None
- get_api_evap_rate()[source]#
Return the prescribed system-wide evaporation rate.
- Returns:
Prescribed rate in user units, or a negative value when no prescription is active.
- Return type:
- clear_api_evap_rate()[source]#
Clear any prescribed evaporation rate, reverting to climate data.
- Returns:
None
- Return type:
None
- set_evap_dry_only(flag)[source]#
Set the evaporation DRY_ONLY option at runtime.
- Parameters:
flag (bool) –
Truesuppresses evaporation during rainfall.- Returns:
None
- Return type:
None
- get_evap_dry_only()[source]#
Return the evaporation DRY_ONLY option.
- Returns:
Trueif evaporation is suppressed during rainfall.- Return type:
- property routing_totals: Dict[str, float]#
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
- class ExternalForcingLog[source]#
Bases:
objectAppend-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
- 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.
- Return type:
pd.DataFrame
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:
EnumEnumeration 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:
EnumEnumeration 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:
EnumEnumeration 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:
EnumEnumeration of the SWMM element types.
- Variables:
SUBCATCHMENT – Subcatchment.
NODE – Node.
LINK – Link.
SYS – System.
POLLUTANT – Pollutant.
- SUBCATCHMENT = Ellipsis#
- NODE = Ellipsis#
- LINK = Ellipsis#
- SYSTEM = Ellipsis#
- POLLUTANT = Ellipsis#
- class TimeAttribute(*values)#
Bases:
EnumEnumeration 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:
EnumEnumeration 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:
EnumEnumeration 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:
EnumEnumeration 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:
EnumEnumeration 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:
ExceptionException class for SWMM output file processing errors.
Constructor to initialize the exception message.
- Parameters:
message (str) – Error message.
- Return type:
None
- class Output(output_file)#
Bases:
objectClass 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:
- get_element_name(element_type, element_index)#
Method to get the name of an element in the SWMM output file.
- get_element_names(element_type)#
Method to get the names of all elements of a given type in the SWMM output file.
- get_link_timeseries(element_index, attribute, start_date_index=Ellipsis, end_date_index=Ellipsis, sub_index=Ellipsis)#
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]
- get_link_values_by_time_and_attribute(time_index, attribute, sub_index=Ellipsis)#
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:
- get_link_values_by_time_and_element_index(time_index, element_index)#
Method to get all attributes of a given link for specified time.
- 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:
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:
- get_node_values_by_time_and_element_index(time_index, element_index)#
Method to get all attributes of a given node for specified time.
- get_num_properties(element_type)#
Method to get the number of properties for an element type in the SWMM output file.
- get_num_variables(element_type)#
Method to get the number of variables for an element type in the SWMM output file.
- get_property_code(element_type, property_index)#
Method to get the property code for an element type in the SWMM output file.
- get_property_codes(element_type)#
Method to get the property codes for an element type in the SWMM output file.
- get_property_value(element_type, element_index, property_code)#
Method to get the property value for an element in the SWMM output file.
- get_property_values(element_type, element_index)#
Method to get the property values for an element type in the SWMM output file.
- 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:
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:
- get_subcatchment_values_by_time_and_element_index(time_index, element_index)#
Method to get all attributes of a given subcatchment for specified time.
- 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.
- 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:
- 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:
- get_variable_code(element_type, variable_index)#
Method to get the variable code for an element type in the SWMM output file.
- get_variable_codes(element_type)#
Method to get the variable codes for an element type in the SWMM output file.
- 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:
- 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]]]