OpenSWMM Engine  6.0.0-alpha.4
Data-oriented, plugin-extensible SWMM Engine (6.0.0-alpha.4)
Loading...
Searching...
No Matches
openswmm_trace_impl.cpp File Reference

Public C API implementation for flow tracing and travel-time analysis. More...

#include "FlowTracer.hpp"
#include <algorithm>
#include <cmath>
#include <exception>
#include <memory>
#include <unordered_set>
Include dependency graph for openswmm_trace_impl.cpp:

Classes

class  FlowTracer
 Own topology, SI hydraulic averages and steady-flow trace preparation state. The C API validates topology/options and supplies aligned arrays. Direct C++ callers must preserve those invariants: valid endpoint indices, finite lengths, na.size()==nodes.size(), la.size()==links.size(), and valid positive solver tolerances/iteration limits. Serialize all access to one tracer; methods can mutate error/state and invoke synchronous callbacks. No internal transaction or C++ exception boundary is supplied; C wrappers catch most analysis exceptions. More...
 

Functions

void swmm_trace_default_options (SWMM_TraceOptions *o)
 Fill the standard SI flow-tracing solver tolerances.
 
int swmm_trace_create (const SWMM_TraceNodeInput *ns, int nn, const SWMM_TraceLinkInput *ls, int nl, const SWMM_TraceOptions *o, SWMM_Trace *out)
 Copy model topology and options into an independent offline trace handle.
 
void swmm_trace_close (SWMM_Trace h)
 Release a trace handle and all copied analysis data.
 
const char * swmm_trace_error (SWMM_Trace h)
 Borrow the current trace diagnostic.
 
int swmm_trace_prepare (SWMM_Trace h, const char *out, const char *cache, const char *digest, SWMM_TraceProgress cb, void *u)
 Build hydraulic averages from a completed output, optionally using a content-bound cache.
 
int swmm_trace_prepare_live (SWMM_Trace h, const char *out, SWMM_TraceProgress cb, void *u)
 Average complete reporting periods already present in a growing output.
 
int swmm_trace_set_averages (SWMM_Trace h, const SWMM_TraceNodeAverage *n, int nn, const SWMM_TraceLinkAverage *l, int nl, const SWMM_TraceInfo *info)
 Copy supplied SI hydraulic averages and recompute derived trace fields.
 
int swmm_trace_get_info (SWMM_Trace h, SWMM_TraceInfo *i)
 Copy current topology/reporting metadata.
 
int swmm_trace_get_averages (SWMM_Trace h, SWMM_TraceNodeAverage *n, int nn, SWMM_TraceLinkAverage *l, int nl)
 Copy prepared SI node/link averages in topology order.
 
const char * swmm_trace_node_id (SWMM_Trace h, int i)
 Borrow a copied topology node ID.
 
const char * swmm_trace_link_id (SWMM_Trace h, int i)
 Borrow a copied topology link ID.
 
int swmm_trace_get_topology (SWMM_Trace h, SWMM_TraceNodeInput *n, int nn, SWMM_TraceLinkInput *l, int nl)
 Copy topology records while borrowing their stable ID strings.
 
int swmm_trace_estimate (SWMM_Trace h, int dir, int seed, SWMM_TraceValue *n, int nn, SWMM_TraceValue *l, int nl, SWMM_TraceSummary *s, SWMM_TraceProgress cb, void *u)
 Estimate upstream/downstream passage ratios and frozen-average travel times from a node.
 

Detailed Description

Public C API implementation for flow tracing and travel-time analysis.

Author
Caleb Buahin caleb.nosp@m..bua.nosp@m.hin@g.nosp@m.mail.nosp@m..com
License
Apache-2.0

Function Documentation

◆ swmm_trace_close()

void swmm_trace_close ( SWMM_Trace handle)

Release a trace handle and all copied analysis data.

Parameters
[in]handleCaller-owned trace handle, or NULL for a no-op. Do not use afterward, destroy twice or close during another operation/callback.

◆ swmm_trace_create()

int swmm_trace_create ( const SWMM_TraceNodeInput * nodes,
int node_count,
const SWMM_TraceLinkInput * links,
int link_count,
const SWMM_TraceOptions * options,
SWMM_Trace * handle )

Copy model topology and options into an independent offline trace handle.

No editable engine is retained. Close every successful handle exactly once. Call prepare/prepare_live/set_averages before estimating; initial info has schema/algorithm version 2 and zero periods.

Parameters
[in]nodesNon-null array of node_count nodes. IDs must be nonempty and unique within nodes; node type must be 0..3. IDs and topology are copied.
[in]node_countPositive number of nodes.
[in]linksArray of link_count links, or NULL when count=0. IDs must be nonempty/unique within links, endpoints must index nodes, and lengths must be finite and nonnegative in m.
[in]link_countNonnegative number of links.
[in]optionsOptional borrowed options; NULL selects defaults. Positive finite flow/velocity epsilons, finite reversal_dominance in [0,1], finite tolerance in (0,0.01] and max_iterations>=1 are required.
[out]handleNon-null output slot, cleared to NULL before validation. Success transfers ownership of a new handle; any previous value in this variable is not freed.
Returns
SWMM_TRACE_OK on success or SWMM_TRACE_INVALID for invalid inputs or caught construction exceptions.
Here is the call graph for this function:

◆ swmm_trace_default_options()

void swmm_trace_default_options ( SWMM_TraceOptions * options)

Fill the standard SI flow-tracing solver tolerances.

Writes flow_epsilon_m3s=1e-9, velocity_epsilon_mps=1e-6, reversal_dominance=0.8, solver_tolerance=1e-11 and max_iterations=10000.

Parameters
[out]optionsCaller-owned options destination, or NULL for a no-op.
Here is the caller graph for this function:

◆ swmm_trace_error()

const char * swmm_trace_error ( SWMM_Trace handle)

Borrow the current trace diagnostic.

Successful calls do not uniformly clear every diagnostic; an empty/nonempty error string is not a substitute for the operation return code.

Parameters
[in]handleLive trace handle, or NULL to read the thread-local diagnostic for handle-less guarded failures.
Returns
Borrowed NUL-terminated string; never free it. Copy before another operation changes its storage or before closing a non-null handle.

◆ swmm_trace_estimate()

int swmm_trace_estimate ( SWMM_Trace handle,
int direction,
int seed,
SWMM_TraceValue * nodes,
int node_capacity,
SWMM_TraceValue * links,
int link_capacity,
SWMM_TraceSummary * summary,
SWMM_TraceProgress progress,
void * user )

Estimate upstream/downstream passage ratios and frozen-average travel times from a node.

Ratios are expected passages per unit and can exceed 1 in circulation; node terminal_fraction is absorption, not a sum of incident ratios. Time is passage-weighted over frozen report averages, with NaN for unknown time and time_coverage reporting known-time fraction. Outputs are not promised unchanged on cancellation/solver failure; inspect only on success. Reads copied analysis data without mutating a live model.

Parameters
[in]handleNon-null live trace handle, used by one thread at a time; caller retains ownership until swmm_trace_close().
[in]directionSWMM_TRACE_DOWNSTREAM (0) or SWMM_TRACE_UPSTREAM (1).
[in]seedZero-based node index for unit release (downstream) or traced receipt (upstream).
[out]nodesNon-null caller-owned array of node_capacity results in topology order.
[in]node_capacityAt least the full copied node count.
[out]linksCaller-owned array of link_capacity results; may be NULL only when topology has zero links.
[in]link_capacityAt least the full copied link count, even when suppressing an empty topology.
[out]summaryNon-null caller-owned terminal/accounting/solver summary destination.
[in]progressOptional synchronous progress callback on the calling thread. Any nonzero result cancels; must not throw, reenter or close the trace handle.
[in]userBorrowed callback context, passed through unchanged; may be NULL and need only remain valid during this synchronous call.
Returns
SWMM_TRACE_OK on solved results; SWMM_TRACE_INVALID for invalid handle/arguments or unprepared state, SWMM_TRACE_CANCELLED for callback cancellation, or SWMM_TRACE_SOLVER when solver convergence fails.

◆ swmm_trace_get_averages()

int swmm_trace_get_averages ( SWMM_Trace handle,
SWMM_TraceNodeAverage * nodes,
int node_capacity,
SWMM_TraceLinkAverage * links,
int link_capacity )

Copy prepared SI node/link averages in topology order.

Checks preparation and both requested capacities before copying either array. Values use SI m/m3/m3/s/m/s and seconds; unknown derived times may be NaN.

Parameters
[in]handleNon-null live trace handle, used by one thread at a time; caller retains ownership until swmm_trace_close().
[out]nodesOptional caller-owned node array; NULL suppresses node output.
[in]node_capacityCapacity in node records, at least the node count when nodes is non-null.
[out]linksOptional caller-owned link array; NULL suppresses link output.
[in]link_capacityCapacity in link records, at least the link count when links is non-null.
Returns
SWMM_TRACE_OK; SWMM_TRACE_INVALID for null handle, unprepared state or a short requested output array.

◆ swmm_trace_get_info()

int swmm_trace_get_info ( SWMM_Trace handle,
SWMM_TraceInfo * info )

Copy current topology/reporting metadata.

Does not require prepared averages; initial/failed-preparation metadata is not a certificate that estimation is ready.

Parameters
[in]handleNon-null live trace handle, used by one thread at a time; caller retains ownership until swmm_trace_close().
[out]infoNon-null caller-owned metadata destination.
Returns
SWMM_TRACE_OK, or SWMM_TRACE_INVALID for null handle/info.

◆ swmm_trace_get_topology()

int swmm_trace_get_topology ( SWMM_Trace handle,
SWMM_TraceNodeInput * nodes,
int node_capacity,
SWMM_TraceLinkInput * links,
int link_capacity )

Copy topology records while borrowing their stable ID strings.

Does not require prepared averages. Checks both requested capacities before copying; caller owns array storage but must not free the borrowed id pointers.

Parameters
[in]handleNon-null live trace handle, used by one thread at a time; caller retains ownership until swmm_trace_close().
[out]nodesOptional caller-owned node array; record id pointers refer to handle-owned storage, valid until close.
[in]node_capacityCapacity in node records, at least the copied node count when nodes is non-null.
[out]linksOptional caller-owned link array; IDs remain handle-owned and lengths are m.
[in]link_capacityCapacity in link records, at least the copied link count when links is non-null.
Returns
SWMM_TRACE_OK; SWMM_TRACE_INVALID for null handle or insufficient requested capacity.

◆ swmm_trace_link_id()

const char * swmm_trace_link_id ( SWMM_Trace handle,
int index )

Borrow a copied topology link ID.

Parameters
[in]handleNon-null live trace handle, used by one thread at a time; caller retains ownership until swmm_trace_close().
[in]indexZero-based link index.
Returns
Handle-owned NUL-terminated ID, or NULL for null handle/out-of-range index. Never free it; valid until handle destruction.

◆ swmm_trace_node_id()

const char * swmm_trace_node_id ( SWMM_Trace handle,
int index )

Borrow a copied topology node ID.

Parameters
[in]handleNon-null live trace handle, used by one thread at a time; caller retains ownership until swmm_trace_close().
[in]indexZero-based node index.
Returns
Handle-owned NUL-terminated ID, or NULL for null handle/out-of-range index. Never free it; valid until handle destruction.

◆ swmm_trace_prepare()

int swmm_trace_prepare ( SWMM_Trace handle,
const char * output_path,
const char * cache_path,
const char * fingerprint,
SWMM_TraceProgress progress,
void * user )

Build hydraulic averages from a completed output, optionally using a content-bound cache.

Binds cache identity to copied topology/options and verifies file size/mtime across scanning. Cache writes are atomic. Preparation invalidates the prior state before deriving new averages. Missing cache digest or cache-write failure can return INVALID/IO after deriving usable prepared averages; those late failures do not clear the prepared flag. Cancellation at the 0.9 pre-cache progress checkpoint explicitly clears preparation. The final 1.0 completion notification ignores its callback return value. Use the return code to distinguish a fully completed prepare/cache operation from these partial outcomes.

Parameters
[in]handleNon-null live trace handle, used by one thread at a time; caller retains ownership until swmm_trace_close().
[in]output_pathNon-null, nonempty NUL-terminated completed successful binary-output path; IDs/counts must match copied topology, independent of row order.
[in]cache_pathOptional NUL-terminated HDF5 cache destination/source; NULL/empty disables cache. A nonempty cache is refused when HDF5 support is unavailable.
[in]fingerprintCaller-verified NUL-terminated digest of output CONTENTS. Required for a reusable cache; NULL/empty cannot identify reusable cache data. Must change whenever output bytes change; path/mtime alone is insufficient.
[in]progressOptional synchronous progress callback on the calling thread. Any nonzero result cancels; must not throw, reenter or close the trace handle.
[in]userBorrowed callback context, passed through unchanged; may be NULL and need only remain valid during this synchronous call.
Returns
SWMM_TRACE_OK on prepared averages; SWMM_TRACE_INVALID for invalid input/averages or caught exceptions, SWMM_TRACE_IO for read/cache IO, SWMM_TRACE_MISMATCH for topology/file changes, SWMM_TRACE_CANCELLED for callback cancellation, or SWMM_TRACE_NO_HDF5 for an unsupported requested cache.

◆ swmm_trace_prepare_live()

int swmm_trace_prepare_live ( SWMM_Trace handle,
const char * output_path,
SWMM_TraceProgress progress,
void * user )

Average complete reporting periods already present in a growing output.

Scans the complete reporting periods present at open time, ignores subsequent appends and writes no cache. Truncation during the scan is a mismatch. swmm_trace_get_info() reports the periods used; the result is a frozen average, not a live particle simulation.

Parameters
[in]handleNon-null live trace handle, used by one thread at a time; caller retains ownership until swmm_trace_close().
[in]output_pathNon-null, nonempty NUL-terminated running/cancelled output path; no closing success footer is required.
[in]progressOptional synchronous progress callback on the calling thread. Any nonzero result cancels; must not throw, reenter or close the trace handle.
[in]userBorrowed callback context, passed through unchanged; may be NULL and need only remain valid during this synchronous call.
Returns
SWMM_TRACE_OK; SWMM_TRACE_INVALID for invalid inputs/averages or caught exceptions, SWMM_TRACE_IO for unreadable output, SWMM_TRACE_MISMATCH for topology/truncation changes, or SWMM_TRACE_CANCELLED.

◆ swmm_trace_set_averages()

int swmm_trace_set_averages ( SWMM_Trace handle,
const SWMM_TraceNodeAverage * nodes,
int node_count,
const SWMM_TraceLinkAverage * links,
int link_count,
const SWMM_TraceInfo * info )

Copy supplied SI hydraulic averages and recompute derived trace fields.

Derived link direction/travel time/flags and node outgoing flow/residence time/flags are recomputed. The operation copies arrays before validating all metadata/averages, so refusal can change stored data and clear preparation; a successful retry is required before estimation.

Parameters
[in]handleNon-null live trace handle, used by one thread at a time; caller retains ownership until swmm_trace_close().
[in]nodesNon-null node_count array in copied topology order. Base node volume/inflow/lateral-in/withdrawal/overflow values must be finite and nonnegative.
[in]node_countMust equal the copied topology node count exactly.
[in]linkslink_count array in topology order, or NULL when count=0. Net flow must be finite; absolute flow/velocity must be finite/nonnegative and absolute flow must cover absolute net flow within tolerance.
[in]link_countMust equal copied link count exactly.
[in]infoOptional metadata to copy, with finite nonnegative duration_s. Node/link counts are overwritten from topology and schema/algorithm versions forced to 2; NULL keeps existing metadata.
Returns
SWMM_TRACE_OK when derived state is ready, otherwise SWMM_TRACE_INVALID.