API Reference#
swmmer: a numpy-only toolkit for EPA SWMM file and engine I/O.
Write a SWMM .inp (:class:SWMMInputGenerator + element defaults), build an
NRCS design-storm rain .dat (:func:build_nrcs_hyetograph,
:func:write_rain_dat), run the runswmm engine and read the binary .out
(:func:run_swmm, :class:SWMMResults). numpy is the only third-party
dependency; the engine runner additionally needs the native runswmm /
libswmm-output artifacts on the system.
AquiferDefaults
dataclass
#
BuildupDefaults
dataclass
#
ConduitDefaults
dataclass
#
CoordinateDefaults
dataclass
#
EvaporationOptions
dataclass
#
SWMM evaporation options.
GroundwaterDefaults
dataclass
#
InfiltrationCurveNumberDefaults
dataclass
#
InfiltrationGreenAmptDefaults
dataclass
#
InfiltrationHortonDefaults
dataclass
#
Default values for Horton infiltration.
SWMM interprets units according to the FLOW_UNITS setting: - US units (CFS/GPM/MGD): in/hr for rates, inches for max_infil - SI units (CMS/LPS/MLD): mm/hr for rates, mm for max_infil
Defaults represent typical sandy/silty soils with moderate infiltration. Based on SWMM 5 Reference Manual Vol. I, Table 4-9.
InflowDefaults
dataclass
#
JunctionDefaults
dataclass
#
LanduseDefaults
dataclass
#
LossDefaults
dataclass
#
OrificeDefaults
dataclass
#
OrificeDefaults(
orifice_type="SIDE",
crest_height=0.0,
disch_coeff=0.65,
flap_gate="YES",
open_close_time=0.0,
)
Default values for orifice links.
flap_gate is "YES" by default, making the orifice a one-way
(controlled-release) outlet. With a SWMM SIDE orifice and
FlapGate=NO, a downstream junction that surcharges above the orifice's
water level drives flow backward through it into the upstream node;
FlapGate=YES clips that negative flow to zero. Override to "NO"
for a bidirectional orifice.
OutfallDefaults
dataclass
#
OutletDefaults
dataclass
#
PollutantDefaults
dataclass
#
PumpDefaults
dataclass
#
RaingageDefaults
dataclass
#
RaingageDefaults(
format="VOLUME",
interval="1:00",
scf=1.0,
source="FILE",
filename="",
station_id="",
rain_units="IN",
timeseries="",
)
Default values for rain gages.
Supports both FILE and TIMESERIES data sources: - FILE (default): Reads rainfall from external file - TIMESERIES: Uses time series defined in [TIMESERIES] section
For FILE source, provide: filename, station_id, rain_units For TIMESERIES source, provide: timeseries (name of the time series)
Example FILE usage: raingages={"RG1": {"filename": "rainfall.dat", "station_id": "12345", "rain_units": "IN"}}
Example TIMESERIES usage: raingages={"RG1": {"source": "TIMESERIES", "timeseries": "TS1"}}
to_inp_row #
Generate INP file row for a rain gage.
For FILE source, outputs: Name Format Interval SCF FILE "filename" station_id units For TIMESERIES source, outputs: Name Format Interval SCF TIMESERIES series_name
ReportOptions
dataclass
#
SWMM report options.
StorageDefaults
dataclass
#
StorageDefaults(
invert_elev=0.0,
max_depth=10.0,
init_depth=0.0,
storage_curve="FUNCTIONAL",
coefficient=1000.0,
exponent=0.0,
constant=0.0,
ponded_area=0.0,
evap_frac=0.0,
psi=0.0,
ksat=0.0,
imd=0.0,
)
Default values for storage units.
The field named ponded_area maps to SWMM's SurDepth column
(additional depth above MaxDepth where water can pond on the surface
before being lost to the flooding-loss term). The optional trailing
Green-Ampt columns (psi, ksat, imd) describe exfiltration
through the storage bottom, used when a storage unit drains by percolation
rather than gravity outflow. When any of these are non-zero, the row is
extended with their values.
to_inp_row #
Generate INP file row for a storage unit.
SWMM uses different field layouts depending on the curve type: - FUNCTIONAL: Name Elev MaxD InitD FUNCTIONAL Coeff Exp Const SurDepth Fevap (Psi Ksat IMD) - TABULAR: Name Elev MaxD InitD TABULAR CurveName SurDepth Fevap (Psi Ksat IMD)
The Green-Ampt tail (Psi/Ksat/IMD) is omitted when all three are zero, so junctions that don't use exfiltration produce the same rows as before.
SubareaDefaults
dataclass
#
SubareaDefaults(
n_imperv=0.015,
n_perv=0.15,
s_imperv=0.05,
s_perv=0.1,
pct_zero=25.0,
route_to="OUTLET",
pct_routed="",
)
Default values for subareas.
Units depend on SWMM FLOW_UNITS setting: - US units: inches for depression storage, Manning's n dimensionless - SI units: mm for depression storage
Defaults from SWMM 5 Reference Manual Vol. I, Table 4-2.
SubcatchmentDefaults
dataclass
#
SWMMOptions
dataclass
#
SWMMOptions(
flow_units="LPS",
infiltration="HORTON",
flow_routing="DYNWAVE",
link_offsets="DEPTH",
min_slope=0.001,
allow_ponding=False,
skip_steady_state=False,
start_date=None,
start_time=None,
report_start_date=None,
report_start_time=None,
end_date=None,
end_time=None,
sweep_start="01/01",
sweep_end="12/31",
dry_days=0,
report_step="00:15:00",
wet_step="00:05:00",
dry_step="01:00:00",
routing_step="00:00:05",
rule_step="00:00:00",
inertial_damping="PARTIAL",
normal_flow_limited="BOTH",
force_main_equation="H-W",
variable_step=0.75,
lengthening_step=0.0,
min_surfarea=1.167,
max_trials=20,
head_tolerance=0.0,
sys_flow_tol=5.0,
lat_flow_tol=5.0,
minimum_step=0.5,
threads=1,
surcharge_method="SLOT",
)
SWMM simulation options with defaults.
All parameters have sensible defaults and can be overridden as needed.
Dates may be unset at construction time; from_rain_data fills them
from the rain timeseries before INP generation.
from_rain_data
classmethod
#
Create SWMMOptions with the simulation window derived from rain timestamps.
START/END default to the rain's first/last timestamp; any start_date/
end_date in kwargs overrides (filled only when None). The
end is extended by sim_tail_hours so a post-storm recession (e.g.
a slow drawdown) is captured instead of truncated at the last rain step.
Parameters:
-
times(Sequence[datetime]) –Rain-gage timestamps (the hyetograph interval starts).
pandasTimestampobjects are accepted, since they subclassdatetime. -
sim_tail_hours(float, default:0.0) –Hours to extend END past the last rain timestamp.
-
validate_overlap(bool, default:False) –If True, raise when an explicit start/end window is supplied that does not overlap the rain (avoids silent zero-rain runs for a user-provided
.dat). Keyword-only. -
**kwargs(Any, default:{}) –Override any default option values.
Returns:
-
SWMMOptions–Options with START/END (and report start) populated.
Raises:
-
ValueError–If
timesis empty, orvalidate_overlapand the explicit window misses the rain.
WashoffDefaults
dataclass
#
WeirDefaults
dataclass
#
WeirDefaults(
weir_type="TRANSVERSE",
crest_height=0.0,
disch_coeff=1.84,
flap_gate="YES",
end_con=0.0,
end_coeff=0.0,
surcharge="YES",
)
Default values for weir links.
flap_gate defaults to "YES", making the weir one-way: flow over a
crest is physically gravity-driven, and SWMM with FlapGate=NO would
allow reverse flow whenever the downstream junction surcharges above the
crest. Override to "NO" for a bidirectional weir.
XSectionDefaults
dataclass
#
SWMMInputGenerator
dataclass
#
SWMMInputGenerator(
title="SWMM Model",
options=None,
evaporation=None,
report=None,
raingages=dict(),
subcatchments=dict(),
subareas=dict(),
infiltration=dict(),
junctions=dict(),
outfalls=dict(),
storage=dict(),
conduits=dict(),
pumps=dict(),
orifices=dict(),
weirs=dict(),
outlets=dict(),
xsections=dict(),
losses=dict(),
inflows=dict(),
dwf=dict(),
curves=dict(),
timeseries=dict(),
patterns=dict(),
coordinates=dict(),
vertices=dict(),
polygons=dict(),
tags=dict(),
controls="",
pollutants=dict(),
landuses=dict(),
coverages=dict(),
loadings=dict(),
buildup=dict(),
washoff=dict(),
aquifers=dict(),
groundwater=dict(),
map_settings=dict(),
)
Generator for SWMM input files (.inp).
Allows users to specify any section data, with defaults provided for unspecified values.
SWMMResults #
Reader for a SWMM binary .out file via libswmm-output (ctypes).
Open it as a context manager so the native file handle is always released.
Parameters:
-
out_path(str or Path) –Path to the SWMM binary output (
.out) file. -
output_lib(str or Path, default:None) –Path to the
libswmm-outputshared library; auto-located via :func:find_output_libwhen omitted.
Notes
All result arrays are SWMM's native 32-bit float (REAL4); dates are its
native 64-bit (REAL8). Reads are lazy and stream from disk: no method
loads the whole file, so an arbitrarily large .out reads in a few MB of
RAM (one element series, or one period snapshot, at a time). Two scale tips:
prefer times_hours / times64 over times for long runs (times
builds one Python datetime per period); and for bulk extraction across
many elements, iterate periods with the *_attribute snapshots (contiguous
reads) rather than calling *_series per element (one strided pass over the
file each). Materializing the full elements x periods matrix can exhaust
memory -- that is on the caller, not the reader.
Attributes:
-
n_subcatch, n_node, n_link(int) –Element counts in the output file.
-
flow_units(str) –Flow-unit label, one of
CFS/GPM/MGD/CMS/LPS/MLD. -
report_step(int) –Seconds between reporting periods.
-
n_periods(int) –Number of reporting periods.
-
start_date(datetime) –Simulation start time.
Examples:
times_hours
cached
property
#
Reporting times as hours from the simulation start (length n_periods).
Read from the file's stored per-period dates (SMO_getDateSeries), so it
reflects the actual reporting grid: SWMM interpolates its variable routing
step onto the fixed reporting step, so the grid is uniform, but this reads
it rather than assuming it. Cheap and cached -- prefer this (or
:attr:times64) over :attr:times for long simulations.
times64
cached
property
#
Reporting timestamps as a datetime64[s] array (length n_periods).
The low-memory, vectorized alternative to :attr:times: ~8 bytes per
period instead of a Python :class:~datetime.datetime object each.
times
cached
property
#
Reporting timestamps as :class:~datetime.datetime objects.
Read from the file's stored per-period dates (authoritative); the first
period is one report_step after the start. This materializes one
Python object per period -- for long runs prefer :attr:times_hours or
:attr:times64.
Returns:
-
list of datetime–One timestamp per reporting period.
subcatchment_names
cached
property
#
Subcatchment names in the output file, in element order.
node_series #
link_series #
subcatchment_series #
Return the time series of an attribute for a subcatchment.
Parameters:
-
name(str) –Subcatchment name as written in the
.inp. -
attr(SubcatchAttr) –Result attribute to read.
Returns:
-
NDArray[float32]–Series of length
n_periods.
Raises:
-
KeyError–If
nameis not a subcatchment in the output file.
system_series #
Return a system-wide attribute time series (e.g. total outfall flow).
Parameters:
-
attr(SystemAttr) –System-wide result attribute to read.
Returns:
-
NDArray[float32]–Series of length
n_periods.
subcatchment_attribute #
Every subcatchment's value of attr at reporting period.
Parameters:
-
attr(SubcatchAttr) –Result attribute to read.
-
period(int) –Reporting-period index in
[0, n_periods - 1].
Returns:
-
NDArray[float32]–One value per subcatchment, aligned to :attr:
subcatchment_names.
node_attribute #
link_attribute #
subcatchment_result #
node_result #
link_result #
system_result #
All system-wide attributes at period (in :class:SystemAttr order).
Parameters:
-
period(int) –Reporting-period index in
[0, n_periods - 1].
Returns:
-
NDArray[float32]–One value per system attribute.
node_volume #
Stored-volume series for a storage node.
Parameters:
-
node(str) –Storage-node name.
Returns:
-
NDArray[float32]–Stored volume per reporting period (flow-unit volume units).
node_inflow #
Total inflow (lateral + upstream) to a node.
Parameters:
-
node(str) –Node name.
Returns:
-
NDArray[float32]–Total inflow per reporting period (flow units).
node_flooding #
Surface flooding / overflow rate at a node.
Parameters:
-
node(str) –Node name.
Returns:
-
NDArray[float32]–Flooding rate per reporting period (flow units).
link_flow #
Flow rate through a link, e.g. a conduit, orifice, or weir.
Parameters:
-
link(str) –Link name.
Returns:
-
NDArray[float32]–Flow rate per reporting period (flow units).
to_pandas #
Tabulate one attribute as a pandas :class:~pandas.DataFrame.
Requires the optional pandas dependency. Materializes the full
n_periods x n_elements panel in memory.
Parameters:
-
attr(NodeAttr | LinkAttr | SubcatchAttr | SystemAttr) –Result attribute to read (must match
element_type). -
element_type(('node', 'link', 'subcatchment', 'system'), default:"node") –Element class to tabulate.
Returns:
-
DataFrame–Index is :attr:
times64; columns are the element names. For"system"(no elements) the result is a single-column frame.
to_xarray #
Export an element class as an xarray :class:~xarray.Dataset.
Requires the optional xarray dependency. One data variable per
attribute over dims (time, <element_type>); materializes one panel
per attribute in memory.
Parameters:
-
element_type(('node', 'link', 'subcatchment', 'system'), default:"node") –Element class to export.
-
attrs(sequence of attribute enums, default:None) –Attributes to include; defaults to every attribute of
element_type.
Returns:
-
Dataset–coordsaretime(:attr:times64) and the element names.
Hyetograph
dataclass
#
A rain-gage hyetograph: interval-start times and per-interval intensities.
Attributes:
-
times(list[datetime]) –Interval-start timestamps, length
n + 1(the last marks the storm end). -
intensity(NDArray[float64]) –Rainfall intensity per interval in depth-unit/hour, length
n + 1; the last value is0.0so rainfall stops cleanly. -
gage(int) –Rain-gage id written to the
.dat(default1).
find_engine #
Locate the runswmm executable.
Searches the engine bundled inside the installed package
(swmmer/_engine/bin, built into the wheel by scikit-build-core) first,
then falls back to PATH (e.g. a conda-provided engine).
Returns:
-
Path–Path to the
runswmmexecutable.
Raises:
-
FileNotFoundError–If
runswmmis neither bundled in the package nor onPATH.
find_output_lib #
Locate the libswmm-output shared library.
Parameters:
-
engine(Path, default:None) –Path to the
runswmmexecutable; auto-located via :func:find_enginewhen omitted. The library is looked up in../lib(Unix) and next to the engine (Windows) relative to it.
Returns:
-
Path–Path to the platform
libswmm-outputshared library.
Raises:
-
FileNotFoundError–If no matching library is found alongside the engine.
run_swmm #
Run a SWMM input file with the runswmm engine.
Parameters:
-
inp(str or Path) –Path to the SWMM input (
.inp) file. -
rpt(str or Path, default:None) –Report-file path; defaults to
inpwith a.rptsuffix. -
out(str or Path, default:None) –Binary-output path; defaults to
inpwith a.outsuffix. -
engine(str or Path, default:None) –Path to the
runswmmexecutable; auto-located via :func:find_enginewhen omitted. -
quiet(bool, default:True) –Capture the engine's stdout/stderr instead of streaming it.
Returns:
-
tuple of Path–The
(report, output)file paths.
Raises:
-
FileNotFoundError–If
inp(or an explicitengine) does not exist. -
IsADirectoryError–If
inpis a directory. -
RuntimeError–If the engine exits with a non-zero return code.
build_nrcs_hyetograph #
build_nrcs_hyetograph(
total_depth_mm,
*,
storm_type="III",
duration="24-hr",
dt_min=6,
start=None,
rain_dat_unit="MM",
)
Distribute a total depth into an SCS design-storm hyetograph.
The SCS Type II/III curves are defined over a 24-hour storm; for a
non-24-hour duration the dimensionless curve is stretched to that span
(exact for the standard "24-hr" case).
Parameters:
-
total_depth_mm(float) –Total storm depth (mm), e.g. the Atlas-14 point estimate.
-
storm_type(('II', 'III'), default:"II") –SCS distribution:
"II"(national) or"III"(coastal / Florida). -
duration(str, default:"24-hr") –Storm-duration label; sets the span the curve is stretched over.
-
dt_min(int, default:6) –Hyetograph time step (minutes); must divide the duration.
-
start(str or datetime, default:None) –Anchor for the series (ISO string or datetime); defaults to 2000-01-01.
-
rain_dat_unit(('MM', 'IN'), default:"MM") –Units for the returned intensities.
Returns:
-
Hyetograph–Interval-start times and INTENSITY (depth-unit/hour) per interval, with a trailing zero so rainfall stops cleanly. The total depth is conserved.
Raises:
-
ValueError–If
storm_typeis invalid ordt_mindoes not divide the duration.
duration_hours #
Parse an Atlas-14 duration label into hours.
Parameters:
-
duration(str) –Label such as
"24-hr","60-min", or"6-hr".
Returns:
-
float–The duration in hours.
Raises:
-
ValueError–If the label is unrecognized.
write_rain_dat #
Write a hyetograph to a SWMM .dat rain file (gage Y M D H M value).
Parameters:
-
hyeto(Hyetograph) –The hyetograph to write.
-
path(str or Path) –Output
.datpath. -
comment(str, default:'') –Header comment line (written as
;comment).
Returns:
-
Path–The written file path.
Raises:
-
IsADirectoryError–If
pathis an existing directory. -
OSError–If the parent directory cannot be created.