1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
use super::*;
use crate::io::{FlowBalance, FlowBalanceSummary, MassBalance, PumpEnergy};
/// Global min/max across all timesteps for each display variable.
///
/// All values are in the internal SI unit system: pressure in metres of head,
/// head in metres, demand and flow in m³/s, velocity in m/s.
#[derive(Debug, Clone, Default)]
pub struct ResultRanges {
/// Minimum gauge pressure observed at any node across all timesteps (m).
pub pressure_min: f64,
/// Maximum gauge pressure observed at any node across all timesteps (m).
pub pressure_max: f64,
/// Minimum hydraulic head observed at any node across all timesteps (m).
pub head_min: f64,
/// Maximum hydraulic head observed at any node across all timesteps (m).
pub head_max: f64,
/// Minimum demand observed at any node across all timesteps (m³/s).
pub demand_min: f64,
/// Maximum demand observed at any node across all timesteps (m³/s).
pub demand_max: f64,
/// Minimum flow observed at any link across all timesteps (m³/s).
pub flow_min: f64,
/// Maximum flow observed at any link across all timesteps (m³/s).
pub flow_max: f64,
/// Minimum velocity observed at any link across all timesteps (m/s).
pub velocity_min: f64,
/// Maximum velocity observed at any link across all timesteps (m/s).
pub velocity_max: f64,
}
/// Per-node result at a single timestep.
///
/// All values are in the internal SI unit system.
#[derive(Debug, Clone)]
pub struct NodeResult {
/// Total hydraulic head at the node (m above datum).
pub head: f64,
/// Gauge pressure at the node (m of water column = head − elevation).
pub pressure: f64,
/// Net demand delivered at or extracted from the node (m³/s).
pub demand: f64,
}
/// Per-link result at a single timestep.
///
/// All values are in the internal SI unit system.
#[derive(Debug, Clone)]
pub struct LinkResult {
/// Volumetric flow rate through the link (m³/s; positive = from-node → to-node).
pub flow: f64,
/// Mean flow velocity in the link (m/s).
pub velocity: f64,
/// Head loss across the link (m; positive = from-node head > to-node head).
pub head_loss: f64,
/// Dimensionless link status flag (0.0 = closed/inactive, 1.0 = open/active).
pub status: f64,
}
impl Simulation {
/// Query a single scalar result for a node at (or near) simulation time `t`.
///
/// Returns `Err(SessionError::UnknownId)` if `node_id` is not in the network
/// and `Err(SessionError::NoSnapshotAtTime)` if no hydraulic snapshot was
/// recorded at or near `t`. All returned values are in the internal SI unit
/// system (head/pressure in m, demand in m³/s, quality in mg/L or h or %).
pub fn get_node_result(
&self,
node_id: &str,
quantity: NodeQuantity,
t: f64,
) -> Result<f64, SessionError> {
let network = self.require_loaded_network()?;
let node_index = node_index_by_id(network, node_id)
.ok_or_else(|| SessionError::UnknownId(node_id.to_string()))?;
let snapshot = self
.snapshot_near(t)
.ok_or(SessionError::NoSnapshotAtTime { requested_t: t })?;
let node_state = &snapshot.node_states[node_index];
let node = &network.nodes[node_index];
let elevation = node.base.elevation;
Ok(match quantity {
NodeQuantity::Head => node_state.head,
NodeQuantity::GaugePressure => {
// For tanks, elevation has been adjusted by +min_level during
// import (so that head = elevation + level works). Physical
// elevation for pressure is elevation − min_level.
let physical_elevation = match &node.kind {
NodeKind::Tank(tank) => elevation - tank.min_level,
_ => elevation,
};
node_state.head - physical_elevation
}
NodeQuantity::Demand => {
// Junctions report total demand: consumption + emitter + leakage
// (matches EPANET NodeDemand = DemandFlow + EmitterFlow + LeakageFlow).
// Tanks and reservoirs report their net inflow (net_flow):
// positive = inflow (filling), negative = outflow (supply).
match &node.kind {
NodeKind::Junction(_) => {
node_state.demand_flow + node_state.emitter_flow + node_state.leakage_flow
}
NodeKind::Reservoir(_) | NodeKind::Tank(_) => node_state.net_flow,
}
}
NodeQuantity::Quality => node_state.quality,
})
}
/// Return a link result quantity at the specified simulation time (§8.2.1).
pub fn get_link_result(
&self,
link_id: &str,
quantity: LinkQuantity,
t: f64,
) -> Result<f64, SessionError> {
let network = self.require_loaded_network()?;
let link_index = link_index_by_id(network, link_id)
.ok_or_else(|| SessionError::UnknownId(link_id.to_string()))?;
let snapshot = self
.snapshot_near(t)
.ok_or(SessionError::NoSnapshotAtTime { requested_t: t })?;
let link_state = &snapshot.link_states[link_index];
let link = &network.links[link_index];
// EPANET forces flow to zero for closed links at output time
// (Status <= CLOSED means XHEAD, TEMPCLOSED, CLOSED).
let is_closed = matches!(
link_state.status,
LinkStatus::Closed | LinkStatus::XHead | LinkStatus::TempClosed
);
Ok(match quantity {
LinkQuantity::Flow => {
if is_closed {
0.0
} else {
link_state.flow
}
}
LinkQuantity::MeanVelocity => {
if let LinkKind::Pipe(pipe) = &link.kind {
let area = std::f64::consts::PI * (pipe.diameter / 2.0).powi(2);
if area > 0.0 {
link_state.flow.abs() / area
} else {
0.0
}
} else {
0.0
}
}
LinkQuantity::UnitHeadLoss => {
if let LinkKind::Pipe(pipe) = &link.kind {
let from_node_index = link.base.from_idx();
let to_node_index = link.base.to_idx();
let head_drop = (snapshot.node_states[from_node_index].head
- snapshot.node_states[to_node_index].head)
.abs();
if pipe.length > 0.0 {
head_drop / pipe.length
} else {
0.0
}
} else {
0.0
}
}
LinkQuantity::FrictionFactor => {
// Only meaningful for DW; return 0 for other formulae or non-pipes.
use crate::HeadLossFormula;
if network.options.head_loss_formula != HeadLossFormula::DarcyWeisbach {
return Ok(0.0);
}
if let LinkKind::Pipe(pipe) = &link.kind {
let from_node_index = link.base.from_idx();
let to_node_index = link.base.to_idx();
let head_drop = (snapshot.node_states[from_node_index].head
- snapshot.node_states[to_node_index].head)
.abs();
// f = dh * D * 2g / (L * v²) where v = Q/A.
// Guard: flows below Q_CLOSED (1e-6 m³/s) are
// within solver convergence noise — treat as zero.
const Q_CLOSED: f64 = 1.0e-6;
let area = std::f64::consts::PI * (pipe.diameter / 2.0).powi(2);
let velocity = if area > 0.0 && link_state.flow.abs() >= Q_CLOSED {
link_state.flow.abs() / area
} else {
0.0
};
if velocity > 0.0 && pipe.length > 0.0 {
// Friction factor from the DW definition:
// f = Δh · D · 2g / (L · v²)
// G_DW is 9.81 m/s² (SI); result is dimensionless.
let two_g = 2.0 * crate::hydraulics::G_DW;
(head_drop * pipe.diameter * two_g) / (pipe.length * velocity * velocity)
} else {
0.0
}
} else {
0.0
}
}
LinkQuantity::Quality => link_state.quality,
LinkQuantity::Status => link_status_to_f64(link_state.status),
LinkQuantity::Setting => link_state.setting,
})
}
/// Return the times at which hydraulic snapshots were recorded (§8.2.1).
///
/// The returned `Vec<f64>` is in ascending order and contains one entry per
/// reporting timestep that was stored during `run_hydraulics()` or
/// successive `step_hydraulics()` calls.
pub fn snapshot_times(&self) -> Vec<f64> {
self.hyd_snapshots.iter().map(|s| s.t).collect()
}
/// Compute global min/max for each display quantity across all snapshots.
///
/// Iterates directly over snapshot arrays by index — O(snapshots × elements)
/// with zero string lookups.
pub fn result_ranges(&self) -> Result<ResultRanges, SessionError> {
let network = self.require_loaded_network()?;
if self.hyd_snapshots.is_empty() {
return Err(SessionError::InvalidPhase {
expected: "HydraulicsDone".into(),
actual: self.phase.name().to_string(),
});
}
let mut r = ResultRanges {
pressure_min: f64::INFINITY,
pressure_max: f64::NEG_INFINITY,
head_min: f64::INFINITY,
head_max: f64::NEG_INFINITY,
demand_min: f64::INFINITY,
demand_max: f64::NEG_INFINITY,
flow_min: f64::INFINITY,
flow_max: f64::NEG_INFINITY,
velocity_min: f64::INFINITY,
velocity_max: f64::NEG_INFINITY,
};
// Pre-compute pipe areas for velocity calculation.
let pipe_areas: Vec<f64> = network
.links
.iter()
.map(|link| {
if let LinkKind::Pipe(pipe) = &link.kind {
std::f64::consts::PI * (pipe.diameter / 2.0).powi(2)
} else {
0.0
}
})
.collect();
for snap in &self.hyd_snapshots {
// Nodes
for (i, ns) in snap.node_states.iter().enumerate() {
let node = &network.nodes[i];
let elevation = node.base.elevation;
// Head
let h = ns.head;
if h < r.head_min {
r.head_min = h;
}
if h > r.head_max {
r.head_max = h;
}
// Gauge pressure
let physical_elevation = match &node.kind {
NodeKind::Tank(tank) => elevation - tank.min_level,
_ => elevation,
};
let p = h - physical_elevation;
if p < r.pressure_min {
r.pressure_min = p;
}
if p > r.pressure_max {
r.pressure_max = p;
}
// Demand
let d = match &node.kind {
NodeKind::Junction(_) => ns.demand_flow + ns.emitter_flow + ns.leakage_flow,
NodeKind::Reservoir(_) | NodeKind::Tank(_) => ns.net_flow,
};
if d < r.demand_min {
r.demand_min = d;
}
if d > r.demand_max {
r.demand_max = d;
}
}
// Links
for (i, ls) in snap.link_states.iter().enumerate() {
let is_closed = matches!(
ls.status,
LinkStatus::Closed | LinkStatus::XHead | LinkStatus::TempClosed
);
// Flow
let f = if is_closed { 0.0 } else { ls.flow };
if f < r.flow_min {
r.flow_min = f;
}
if f > r.flow_max {
r.flow_max = f;
}
// Velocity (pipes only)
let area = pipe_areas[i];
if area > 0.0 {
let v = ls.flow.abs() / area;
if v < r.velocity_min {
r.velocity_min = v;
}
if v > r.velocity_max {
r.velocity_max = v;
}
}
}
}
// Sanitise: if no pipes existed, velocity range stays infinite.
if r.velocity_min == f64::INFINITY {
r.velocity_min = 0.0;
r.velocity_max = 0.0;
}
Ok(r)
}
/// Return all node results at a given simulation time, indexed by position.
///
/// Returns one `NodeResult` per node in the same order as `node_ids()`.
/// Uses direct index access — O(N) with no string lookups.
pub fn all_node_results_at(&self, t: f64) -> Result<Vec<NodeResult>, SessionError> {
let network = self.require_loaded_network()?;
let snapshot = self
.snapshot_near(t)
.ok_or(SessionError::NoSnapshotAtTime { requested_t: t })?;
let mut results = Vec::with_capacity(network.nodes.len());
for (i, ns) in snapshot.node_states.iter().enumerate() {
let node = &network.nodes[i];
let elevation = node.base.elevation;
let pressure = {
let physical_elevation = match &node.kind {
NodeKind::Tank(tank) => elevation - tank.min_level,
_ => elevation,
};
ns.head - physical_elevation
};
let demand = match &node.kind {
NodeKind::Junction(_) => ns.demand_flow + ns.emitter_flow + ns.leakage_flow,
NodeKind::Reservoir(_) | NodeKind::Tank(_) => ns.net_flow,
};
results.push(NodeResult {
head: ns.head,
pressure,
demand,
});
}
Ok(results)
}
/// Return all link results at a given simulation time, indexed by position.
///
/// Returns one `LinkResult` per link in the same order as `link_ids()`.
/// Uses direct index access — O(L) with no string lookups.
pub fn all_link_results_at(&self, t: f64) -> Result<Vec<LinkResult>, SessionError> {
let network = self.require_loaded_network()?;
let snapshot = self
.snapshot_near(t)
.ok_or(SessionError::NoSnapshotAtTime { requested_t: t })?;
let mut results = Vec::with_capacity(network.links.len());
for (i, ls) in snapshot.link_states.iter().enumerate() {
let link = &network.links[i];
let is_closed = matches!(
ls.status,
LinkStatus::Closed | LinkStatus::XHead | LinkStatus::TempClosed
);
let flow = if is_closed { 0.0 } else { ls.flow };
let velocity = if let LinkKind::Pipe(pipe) = &link.kind {
let area = std::f64::consts::PI * (pipe.diameter / 2.0).powi(2);
if area > 0.0 {
ls.flow.abs() / area
} else {
0.0
}
} else {
0.0
};
let head_loss = if let LinkKind::Pipe(pipe) = &link.kind {
let from_idx = link.base.from_idx();
let to_idx = link.base.to_idx();
let head_drop =
(snapshot.node_states[from_idx].head - snapshot.node_states[to_idx].head).abs();
if pipe.length > 0.0 {
head_drop / pipe.length
} else {
0.0
}
} else {
0.0
};
let status = link_status_to_f64(ls.status);
results.push(LinkResult {
flow,
velocity,
head_loss,
status,
});
}
Ok(results)
}
/// Return the node IDs in the order they were indexed at load time.
pub fn node_ids(&self) -> Vec<&str> {
match &self.network {
Some(n) => n.nodes.iter().map(|nd| nd.base.id.as_str()).collect(),
None => vec![],
}
}
/// Return the link IDs in the order they were indexed at load time.
pub fn link_ids(&self) -> Vec<&str> {
match &self.network {
Some(n) => n.links.iter().map(|lk| lk.base.id.as_str()).collect(),
None => vec![],
}
}
/// Return the pump link IDs in the order they appear in the network.
pub fn pump_ids(&self) -> Vec<&str> {
match &self.network {
Some(n) => n
.links
.iter()
.filter(|l| matches!(l.kind, LinkKind::Pump(_)))
.map(|l| l.base.id.as_str())
.collect(),
None => vec![],
}
}
/// Return the declared `FlowUnits` of the loaded network.
pub fn flow_units(&self) -> Option<FlowUnits> {
self.network.as_ref().map(|n| n.options.flow_units)
}
/// Return energy statistics for a pump link (§8.2.1).
pub fn get_pump_energy(&self, pump_id: &str) -> Result<&PumpEnergy, SessionError> {
let network = self.require_loaded_network()?;
let link_index = link_index_by_id(network, pump_id)
.ok_or_else(|| SessionError::UnknownId(pump_id.to_string()))?;
// Verify it is a pump.
if !matches!(network.links[link_index].kind, LinkKind::Pump(_)) {
return Err(SessionError::UnknownId(pump_id.to_string()));
}
let accounting_state =
self.accounting
.as_ref()
.ok_or_else(|| SessionError::InvalidPhase {
expected: "HydraulicsDone".into(),
actual: self.phase.name().to_string(),
})?;
Ok(&accounting_state.pump_energy[link_index])
}
/// Return the global mass balance from the quality engine (§8.2.1).
pub fn get_mass_balance(&self) -> Result<&MassBalance, SessionError> {
let qs = self
.quality_state
.as_ref()
.ok_or_else(|| SessionError::InvalidPhase {
expected: "QualityDone".into(),
actual: self.phase.name().to_string(),
})?;
Ok(&qs.mass_balance)
}
/// Return the global volumetric flow balance from accounting (§8.2.1).
pub fn get_flow_balance(&self) -> Result<&FlowBalance, SessionError> {
let acc = self
.accounting
.as_ref()
.ok_or_else(|| SessionError::InvalidPhase {
expected: "Loaded".into(),
actual: self.phase.name().to_string(),
})?;
Ok(&acc.flow_balance)
}
/// Return the total tank volume at the end of the simulation (m³).
///
/// Sums `NodeState::volume` from the live state vector for all tank nodes.
pub fn final_tank_volume(&self) -> Result<f64, SessionError> {
let network = self.require_loaded_network()?;
let vol: f64 = network
.nodes
.iter()
.enumerate()
.filter_map(|(i, n)| {
if matches!(n.kind, NodeKind::Tank(_)) {
Some(self.node_states[i].volume)
} else {
None
}
})
.sum();
Ok(vol)
}
/// Return the complete flow balance summary with derived values.
pub fn flow_balance_summary(&self) -> Result<FlowBalanceSummary, SessionError> {
let fb = self.get_flow_balance()?;
let final_vol = self.final_tank_volume()?;
Ok(fb.summarize(final_vol))
}
/// Borrow the list of simulation warnings.
pub fn warnings(&self) -> &[SimWarning] {
&self.warnings
}
}