OpenSWMM Engine  6.0.0-alpha.4
Data-oriented, plugin-extensible SWMM Engine (6.0.0-alpha.4)
Loading...
Searching...
No Matches
openswmm::Router Class Reference

Top-level routing orchestrator. More...

#include <Routing.hpp>

Collaboration diagram for openswmm::Router:

Classes

struct  RestartState
 

Public Member Functions

void restoreFvClassicState (SimulationContext &ctx)
 
void init (SimulationContext &ctx, RouteModel model)
 Initialize routing groups, solver state and the selected model dispatch.
 
void acceptedQualityWater (const SimulationContext &ctx, double dt, quality::FvTransportWater &out) const
 Dispatch one prepared hydraulic routing interval and publish its current state.
 
int step (SimulationContext &ctx, double dt, double evap_rate=0.0, dynwave::DWSolver::NonConduitFlowFunc non_conduit_fn=nullptr)
 
void enableCheckpointing (SimulationContext &ctx)
 Attach the internal accepted-boundary hydraulic checkpoint profile at initial time.
 
void beginCheckpointStep (SimulationContext &ctx, double dt)
 Reserve the next chronological tracked routing boundary before preparation mutates state.
 
void acceptCheckpointBoundary (SimulationContext &ctx)
 Validate and accept a fully postprocessed tracked step at its advanced clock.
 
std::string saveCheckpoint (const SimulationContext &ctx, const std::string &path) const
 Serialize and publish an accepted internal hydraulic checkpoint file.
 
std::string loadCheckpoint (SimulationContext &ctx, const std::string &path)
 Validate a stored hydraulic checkpoint privately, then install its selected state.
 
double getAdaptiveStep (SimulationContext &ctx, double fixed_step, double courant)
 Select an outer routing interval from the active model telemetry.
 
const XSectGroups & xsectGroups () const
 Access the shape-grouped xsect manager.
 
bool hasCycle () const
 Report the topological cycle diagnostic from the most recent initialization.
 
void setDWNumThreads (int n, std::vector< std::string > *warnings=nullptr)
 Configure the owned dynamic-wave solver worker count.
 
dynwave::DWSolver & dwSolver ()
 Access the DW solver (for non-conduit node state scatter).
 
void setStructureSolver (hydstruct::StructureSolver *s)
 Attach the borrowed structure-equation provider for tree routing.
 
std::unique_ptr< Router > privateDynamicWaveWindow () const
 Create private DW numerical history/group scratch for a restricted internal routing trial.
 
void publishDynamicWaveWindow (Router &r) noexcept
 Exchange accepted private DW history and grouped scratch into this router.
 
bool lastStepConverged () const
 Report the selected routing model legacy convergence statistic.
 
bool enableLinkStepStats (SimulationContext &ctx)
 Enable conduit-step reporting when the selected solver can provide it.
 
bool linkStepStatsEnabled () const
 Whether enableLinkStepStats() succeeded.
 
void accumulateLinkStepStats (SimulationContext &ctx, double dt, bool in_window)
 Keep or discard the just-completed interval conduit-step report samples.
 
const fv::INetworkSolver * fvSolver () const
 Borrow the currently owned FV backend interface.
 
const fv::NetworkMeshData & fvMesh () const
 The FV mesh built at init (empty unless FLOW_ROUTING FV).
 
const std::string & fvBackend () const
 Backend label chosen by the FV factory ("cpu (...)", "omp (...)", ...).
 
const std::vector< std::string > & fvWarnings () const
 Borrow accumulated FV initialization warnings.
 
const std::vector< std::string > & fvErrors () const
 Borrow accumulated FV mesh initialization errors.
 

Friends

class twoD::SurfaceRouter2D
 
class SWMMEngine
 

Detailed Description

Top-level routing orchestrator.

Owns the XSectGroups (shape-grouped batch xsect), KWSolver, and DWSolver. Initialised once after the model is built; then step() is called each routing timestep.

Member Function Documentation

◆ acceptCheckpointBoundary()

void openswmm::Router::acceptCheckpointBoundary ( SimulationContext & ctx)

Validate and accept a fully postprocessed tracked step at its advanced clock.

Requires step_finished and not-ready, validates profile/model and complete RestartState invariants, then marks the boundary saveable and updates accepted time. A DW return with Picard nonconvergence is still an accepted legacy interval. Throws on any mismatch and leaves an unaccepted boundary; caller owns all paired producer/clock state.

Parameters
[in,out]ctxSame attached context after successful Router::step, LID finish/postprocessing and caller clock advance to scheduled end.
Here is the call graph for this function:

◆ acceptedQualityWater()

void openswmm::Router::acceptedQualityWater ( const SimulationContext & ctx,
double dt,
quality::FvTransportWater & out ) const

Dispatch one prepared hydraulic routing interval and publish its current state.

Caller snapshots old node/link state and assembles lateral/external forcing before entry; this routine deliberately does not save old state a second time. Initializes node/storage loss flows, evaluates non-DW conduit losses/outfall boundaries, executes the model and publishes final states. FV preserves signed piezometric head. Caller advances clocks, finishes LID/postprocessing and updates global mass/report ledgers. Tracked checkpoints require beginCheckpointStep beforehand and acceptance afterward. General failures/nonconvergence do not roll back ordinary routing state; inspect lastStepConverged and upstream error handling.

Parameters
[in,out]ctxResolved matching native-ft simulation context with stable node/link/subtype/profile dimensions; caller owns storage, clocks and run-level ledgers.
[in]dtPositive finite routing interval in seconds, consistent with saved old state and forcing.
[in]evap_rateFinite nonnegative evaporation rate in native ft/s.
[in]non_conduit_fnOptional synchronous structure callback(ctx,dt,Picard index). DW invokes per Picard iteration; FV invokes initially and optionally each substep with index zero. Must not throw/reenter, change topology or retain transient borrowed state.
Returns
DW Picard iteration count, KW effort, one for steady flow, or FV internal operator-step count; zero can indicate an absent FV solver. Publish an accepted native CPU FV water graph for conservative quality.
Here is the call graph for this function:

◆ accumulateLinkStepStats()

void openswmm::Router::accumulateLinkStepStats ( SimulationContext & ctx,
double dt,
bool in_window )

Keep or discard the just-completed interval conduit-step report samples.

No-op unless enabled. DW samples current final convergence/CFL state only in-window. FV merges pending per-link min/max/time-weighted/bin totals when in-window, then clears them either way. Invoke once per completed routing interval to avoid double-counting or mixing windows; no hydraulic changes.

Parameters
[in,out]ctxResolved matching native-ft simulation context with stable node/link/subtype/profile dimensions; caller owns storage, clocks and run-level ledgers.
[in]dtCompleted outer interval seconds; DW weights samples by this value.
[in]in_windowTrue only within the active reporting/event window; false discards pending FV samples.

◆ beginCheckpointStep()

void openswmm::Router::beginCheckpointStep ( SimulationContext & ctx,
double dt )

Reserve the next chronological tracked routing boundary before preparation mutates state.

Revalidates supported profile and exact serialized model identity. Sets scheduled end, clears ready/finished and marks prepared before old-state/LID/forcing preparation. A later preparation exception therefore cannot leave a falsely saveable boundary. Throws on mismatched identity/time/model/limits; there is no automatic rollback here.

Parameters
[in,out]ctxSame attached context at its currently accepted time.
[in]dtFinite positive seconds with a representably later finite endpoint within configured duration.

◆ dwSolver()

dynwave::DWSolver & openswmm::Router::dwSolver ( )
inline

Access the DW solver (for non-conduit node state scatter).

◆ enableCheckpointing()

void openswmm::Router::enableCheckpointing ( SimulationContext & ctx)

Attach the internal accepted-boundary hydraulic checkpoint profile at initial time.

Requires no prior attached context, validates supported model/state and stores serialized model identity, then marks time-zero boundary accepted. Ordinary standalone scope is native DW water-only conduits, ordinary junctions/non-tabular storage including initialized node LIDs, and FREE/NORMAL/FIXED outfalls. Engine-owned sessions can qualify paired structure/control/quality/heat or aquifer state via their separate ownership flags. Unsupported profile throws; external producers/writers require their paired state. Attachment requires the context address/lifetime to remain stable; init resets it.

Parameters
[in,out]ctxInitialized matching router/LID context with current_time exactly zero, retained by nonowning identity for the checkpoint session.
Here is the call graph for this function:

◆ enableLinkStepStats()

bool openswmm::Router::enableLinkStepStats ( SimulationContext & ctx)

Enable conduit-step reporting when the selected solver can provide it.

Call after successful init. Stores nominal routing-step bin edges and, on native FV, allocates/zeroes pending per-link sample buffers and installs a synchronous sink retaining this Router address. Router must therefore remain at a stable address while the sink is active. Allocation exceptions propagate; no hydraulic state changes.

Parameters
[in,out]ctxResolved matching native-ft simulation context with stable node/link/subtype/profile dimensions; caller owns storage, clocks and run-level ledgers.
Returns
True for DW or the native ExplicitFvSolver backend; false for KW/STEADY/unsupported FV backends.
Here is the call graph for this function:

◆ fvBackend()

const std::string & openswmm::Router::fvBackend ( ) const
inline

Backend label chosen by the FV factory ("cpu (...)", "omp (...)", ...).

◆ fvErrors()

const std::vector< std::string > & openswmm::Router::fvErrors ( ) const
inline

Borrow accumulated FV mesh initialization errors.

Messages/storage can change on subsequent initialization and expire at Router destruction. Caller surfaces them through context/UI diagnostics; this accessor does not clear or throw them.

Returns
Const owned error vector; nonempty means the built FV state was not initialized for stepping.

◆ fvMesh()

const fv::NetworkMeshData & openswmm::Router::fvMesh ( ) const
inline

The FV mesh built at init (empty unless FLOW_ROUTING FV).

◆ fvSolver()

const fv::INetworkSolver * openswmm::Router::fvSolver ( ) const
inline

Borrow the currently owned FV backend interface.

No ownership transfers. Read diagnostics only outside mutation/advance; caller checks successful FV initialization before treating a non-null backend as usable.

Returns
Const backend pointer, possibly nullptr; valid until backend replacement or Router destruction.

◆ fvWarnings()

const std::vector< std::string > & openswmm::Router::fvWarnings ( ) const
inline

Borrow accumulated FV initialization warnings.

Messages/storage can change on subsequent initialization and expire at Router destruction. Caller surfaces them through context/UI diagnostics; this accessor does not clear or throw them.

Returns
Const owned message vector; includes mesh/backend/inert-option diagnostics.

◆ getAdaptiveStep()

double openswmm::Router::getAdaptiveStep ( SimulationContext & ctx,
double fixed_step,
double courant )

Select an outer routing interval from the active model telemetry.

A model with no links always returns fixed_step. DW may update critical-element counters and first-call minimum-step state. FV subcycles internally, so this is a forcing/reporting cadence hint rather than its actual stability timestep. Requires successful matching init.

Parameters
[in,out]ctxResolved matching native-ft simulation context with stable node/link/subtype/profile dimensions; caller owns storage, clocks and run-level ledgers.
[in]fixed_stepPositive nominal interval in seconds.
[in]courantPositive variable-step factor or <=0 for fixed cadence.
Returns
Seconds: DW CFL selection, FV min(fixed_step,max(fixed_step*courant,suggested_substep)) when enabled, otherwise fixed_step.
Here is the call graph for this function:

◆ hasCycle()

bool openswmm::Router::hasCycle ( ) const
inline

Report the topological cycle diagnostic from the most recent initialization.

Returns
True if KW/STEADY topological ordering detected a cycle; DW does not use this tree-order check.

◆ init()

void openswmm::Router::init ( SimulationContext & ctx,
RouteModel model )

Initialize routing groups, solver state and the selected model dispatch.

Resets checkpoint attachment, builds complete scalar/grouped native geometry with borrowed stable profile tables, applies conduit lengthening and initializes model-specific work. KW/STEADY use topological order/cycle diagnostics; DW configures iteration/surcharge/UF state; FV builds its own mesh/backend. Allocations/solver failures can leave partially initialized context/router. FV mesh validation diagnostics are retained for the caller to inspect; init does not itself turn every report error into an exception. Reinitialize after topology/model edits and serialize execution on an instance.

Parameters
[in,out]ctxResolved matching native-ft simulation context with stable node/link/subtype/profile dimensions; caller owns storage, clocks and run-level ledgers.
[in]modelRequested STEADY, KINWAVE, DYNWAVE or FV route model; must agree with relevant ctx.options routing settings.
Here is the call graph for this function:

◆ lastStepConverged()

bool openswmm::Router::lastStepConverged ( ) const
inline

Report the selected routing model legacy convergence statistic.

FV true means no Picard convergence loop is used, not a certificate against short advance/divergence/backend failure. Those are checked by the FV advance wrapper/error path.

Returns
DW final Picard flag for DYNWAVE; true for every other model.

◆ linkStepStatsEnabled()

bool openswmm::Router::linkStepStatsEnabled ( ) const
inline

Whether enableLinkStepStats() succeeded.

◆ loadCheckpoint()

std::string openswmm::Router::loadCheckpoint ( SimulationContext & ctx,
const std::string & path )

Validate a stored hydraulic checkpoint privately, then install its selected state.

Reads a bounded complete file, validates framing/version/model/checksum and native invariants before no-throw installation. Accepts supported versions 3..5 subject to missing thermal/ground-contact-state restrictions. Validation/read failure preserves live hydraulic state. Restore may recover an unaccepted boundary; no current-ready requirement is imposed. External paired session state is the caller responsibility.

Parameters
[in,out]ctxSame checkpoint-enabled matching context/model; installation replaces selected native runtime state, clocks and checkpoint readiness.
[in]pathNative narrow readable checkpoint filename.
Returns
Empty on success, otherwise caught std::exception diagnostic.

◆ privateDynamicWaveWindow()

std::unique_ptr< Router > openswmm::Router::privateDynamicWaveWindow ( ) const

Create private DW numerical history/group scratch for a restricted internal routing trial.

Requires initialized DYNWAVE outside a checkpoint session; otherwise throws runtime_error. Does not copy external structure/control sessions or a full SimulationContext. Geometry profile table references still borrow the underlying stable model storage; no pointer into the source router own group object is retained. Allocations can throw without mutating the source. Caller validates the restricted transaction profile and supplies a compatible private context.

Returns
Owning Router containing copied DW/group and selected link-step scratch, with its DW group pointer rebound to the copy.

◆ publishDynamicWaveWindow()

void openswmm::Router::publishDynamicWaveWindow ( Router & r)
noexcept

Exchange accepted private DW history and grouped scratch into this router.

No-throw swaps only groups_ and dw_solver_, clears their bypass masks and rebinds each solver to its own group object. The donor receives the previous numerical history. Does not publish context state, checkpoint/session fields or every copied reporting buffer; caller owns the surrounding transaction. No validity check is performed.

Parameters
[in,out]rCompatible private DW window created from this same initialized model; must be exclusively owned and validated before publication.

◆ restoreFvClassicState()

void openswmm::Router::restoreFvClassicState ( SimulationContext & ctx)

Project classic restart volumes/flows onto the existing FV mesh once. Preserves conduit inventory; does not restore subgrid transient history.

◆ saveCheckpoint()

std::string openswmm::Router::saveCheckpoint ( const SimulationContext & ctx,
const std::string & path ) const

Serialize and publish an accepted internal hydraulic checkpoint file.

Writes version 5 framed state/model/checksum bytes with a 64-MiB limit. Existing targets must have hydraulic magic before replacement; stages bytes then renames to publish. No fsync durability guarantee or Windows UTF-8/long-path adaptation is supplied. This component file does not replace paired runoff/control/2D/output checkpoints.

Parameters
[in]ctxSame attached context at an accepted boundary, unchanged model/profile and valid current state.
[in]pathNonempty native narrow filesystem path; temporary exclusive staging is placed alongside the target.
Returns
Empty string on success, otherwise a caught std::exception diagnostic; no hydraulic state changes.

◆ setDWNumThreads()

void openswmm::Router::setDWNumThreads ( int n,
std::vector< std::string > * warnings = nullptr )
inline

Configure the owned dynamic-wave solver worker count.

Delegates to DWSolver::setNumThreads. Configure outside an active routing call; affects DW loops, not the FV backend thread policy.

Parameters
[in]nRequested count; zero selects its automatic policy and environment overrides may apply.
[in,out]warningsOptional vector receiving policy warnings, or nullptr.

◆ setStructureSolver()

void openswmm::Router::setStructureSolver ( hydstruct::StructureSolver * s)
inline

Attach the borrowed structure-equation provider for tree routing.

Must be set before KW/STEADY stepping when structures are present. DW/FV receive their structure work through the callback instead. Provider/model lifetime must cover all routing calls; replacing it does not release its memory. Checkpoint qualification accounts for enclosing engine ownership separately.

Parameters
[in]sLive initialized StructureSolver or nullptr; never deleted by Router.

◆ step()

int openswmm::Router::step ( SimulationContext & ctx,
double dt,
double evap_rate = 0.0,
dynwave::DWSolver::NonConduitFlowFunc non_conduit_fn = nullptr )

◆ xsectGroups()

const XSectGroups & openswmm::Router::xsectGroups ( ) const
inline

Access the shape-grouped xsect manager.

Friends And Related Symbol Documentation

◆ SWMMEngine

friend class SWMMEngine
friend

◆ twoD::SurfaceRouter2D

friend class twoD::SurfaceRouter2D
friend

The documentation for this class was generated from the following files: