Skip to main content

epanet_rs/model/network/
modify.rs

1//! `*Data` and `*Update` structs and methods for adding, modifying and removing network elements.
2/*!
3
4Modifying a network *must* be done using the update_* and add_* methods, as those will update all related properties, handle unit conversion and update the change tracking flags.
5
6Updating a network element uses an update struct with default None values for the fields that are not being updated. Sometimes a field needs to be set to None to clear an existing value, for example when clearing a pattern or curve, in which case the Some(None) variant is used.
7
8Example:
9
10```rust
11# use epanet_rs::model::network::{Network, JunctionUpdate, JunctionData, PatternData};
12# use epanet_rs::model::units::FlowUnits;
13# use epanet_rs::model::options::HeadlossFormula;
14let mut network = Network::new(FlowUnits::CFS, HeadlossFormula::DarcyWeisbach);
15
16network.add_pattern("P1", &PatternData {
17  multipliers: vec![1.0],
18}).unwrap();
19
20network.add_junction("J1", &JunctionData {
21  elevation: 100.0,
22  demands: vec![epanet_rs::model::demand::Demand {
23    basedemand: 10.0,
24    pattern: Some("P1".into()),
25    pattern_index: None,
26    name: None,
27  }],
28  emitter_coefficient: 0.0,
29  coordinates: Some((100.0, 200.0)),
30}).unwrap();
31
32// update the junciton by setting the elevation to 50.0 and clearing the pattern
33network.update_junction("J1", &JunctionUpdate {
34  elevation: Some(50.0),
35  basedemand: None,
36  emitter_coefficient: None,
37  pattern: Some(None),
38  demands: None,
39  coordinates: None,
40  disabled: None
41});
42*/
43
44use hashbrown::HashMap;
45
46use crate::error::InputError;
47use crate::model::control::ControlCondition;
48use crate::model::curve::{Curve, HeadCurve, ValveCurve};
49use crate::model::demand::Demand;
50use crate::model::junction::Junction;
51use crate::model::link::{Link, LinkStatus, LinkType};
52use crate::model::network::Network;
53use crate::model::node::{Node, NodeType};
54use crate::model::pattern::Pattern;
55use crate::model::pipe::Pipe;
56use crate::model::pump::Pump;
57use crate::model::reservoir::Reservoir;
58use crate::model::tank::Tank;
59use crate::model::units::UnitConversion;
60use crate::model::valve::{Valve, ValveType};
61
62/// Data for adding a new junction to the network.
63#[derive(Default)]
64pub struct JunctionData {
65    pub elevation: f64,
66    pub demands: Vec<Demand>,
67    pub emitter_coefficient: f64,
68    pub coordinates: Option<(f64, f64)>,
69}
70
71/// Data for updating an existing junction.
72#[derive(Default)]
73pub struct JunctionUpdate {
74    pub elevation: Option<f64>,
75    pub demands: Option<Vec<Demand>>,
76    pub basedemand: Option<f64>,
77    pub pattern: Option<Option<Box<str>>>,
78    pub emitter_coefficient: Option<f64>,
79    pub coordinates: Option<(f64, f64)>,
80    pub disabled: Option<bool>,
81}
82
83#[derive(Default)]
84pub struct TankData {
85    pub elevation: f64,
86    pub initial_level: f64,
87    pub min_level: f64,
88    pub max_level: f64,
89    pub diameter: f64,
90    pub min_volume: f64,
91    pub volume_curve_id: Option<Box<str>>,
92    pub overflow: bool,
93    pub coordinates: Option<(f64, f64)>,
94}
95
96#[derive(Default)]
97pub struct TankUpdate {
98    pub elevation: Option<f64>,
99    pub coordinates: Option<(f64, f64)>,
100    pub initial_level: Option<f64>,
101    pub min_level: Option<f64>,
102    pub max_level: Option<f64>,
103    pub diameter: Option<f64>,
104    pub min_volume: Option<f64>,
105    pub overflow: Option<bool>,
106}
107
108/// Data for adding a new reservoir to the network.
109#[derive(Default)]
110pub struct ReservoirData {
111    pub elevation: f64,
112    pub head_pattern: Option<Box<str>>,
113    pub coordinates: Option<(f64, f64)>,
114}
115
116/// Data for updating an existing reservoir.
117#[derive(Default)]
118pub struct ReservoirUpdate {
119    pub elevation: Option<f64>,
120    pub coordinates: Option<(f64, f64)>,
121    /// Head pattern id. `None` leaves the pattern untouched, `Some(None)`
122    /// clears an existing head pattern, `Some(Some(id))` sets the pattern.
123    pub head_pattern: Option<Option<Box<str>>>,
124}
125
126/// Generic update for any node. Only elevation and coordinates can be changed
127/// through this struct; type-specific properties must be updated via the
128/// corresponding `update_tank`/`update_reservoir`/`update_junction` methods.
129#[derive(Default)]
130pub struct NodeUpdate {
131    pub elevation: Option<f64>,
132    pub coordinates: Option<(f64, f64)>,
133    pub disabled: Option<bool>,
134}
135
136/// Data for adding a pipe. All fields are in the user's unit system.
137/// `minor_loss` is the dimensionless user-facing minor-loss coefficient (K).
138/// The headloss formula is derived from the network's configured options.
139#[derive(Default)]
140pub struct PipeData {
141    pub start_node: Box<str>,
142    pub end_node: Box<str>,
143    pub length: f64,
144    pub diameter: f64,
145    pub roughness: f64,
146    pub minor_loss: f64,
147    pub check_valve: bool,
148    pub initial_status: LinkStatus,
149    pub vertices: Option<Vec<(f64, f64)>>,
150}
151/// Data for updating a pipe.
152/// All units are in the user's unit system.
153#[derive(Default)]
154pub struct PipeUpdate {
155    pub length: Option<f64>,
156    pub diameter: Option<f64>,
157    pub roughness: Option<f64>,
158    /// User-facing minor-loss coefficient (K). Internally re-normalized against
159    /// the (possibly updated) diameter.
160    pub minor_loss: Option<f64>,
161    pub check_valve: Option<bool>,
162}
163
164/// Data for adding a pump. `head_curve_id` must reference an existing curve.
165/// All units are in the user's unit system.
166pub struct PumpData {
167    pub start_node: Box<str>,
168    pub end_node: Box<str>,
169    pub speed: f64,
170    pub head_curve_id: Option<Box<str>>,
171    pub power: f64,
172    pub initial_status: LinkStatus,
173    pub vertices: Option<Vec<(f64, f64)>>,
174}
175
176/// Data for updating a pump.
177/// All units are in the user's unit system.
178#[derive(Default)]
179pub struct PumpUpdate {
180    pub speed: Option<f64>,
181    pub power: Option<f64>,
182    /// Head curve id. `None` leaves the curve untouched, `Some(None)` clears
183    /// the existing head curve, `Some(Some(id))` sets the curve.
184    pub head_curve_id: Option<Option<Box<str>>>,
185}
186
187/// Data for adding a valve. `curve_id` must reference an existing curve and is
188/// only meaningful for GPV and PCV valves.
189pub struct ValveData {
190    pub start_node: Box<str>,
191    pub end_node: Box<str>,
192    pub diameter: f64,
193    pub valve_type: ValveType,
194    pub setting: f64,
195    pub curve_id: Option<Box<str>>,
196    pub minor_loss: f64,
197    pub initial_status: LinkStatus,
198    pub vertices: Option<Vec<(f64, f64)>>,
199}
200
201#[derive(Default)]
202pub struct ValveUpdate {
203    pub diameter: Option<f64>,
204    pub setting: Option<f64>,
205    pub minor_loss: Option<f64>,
206    /// Valve curve id. `None` leaves the curve untouched, `Some(None)` clears
207    /// the existing curve, `Some(Some(id))` sets the curve. GPV valves cannot
208    /// have their curve cleared.
209    pub curve_id: Option<Option<Box<str>>>,
210    /// Change the valve's kind. Because the stored `setting` is interpreted
211    /// differently per valve type, a new `setting` must be supplied whenever
212    /// the type is changed. If the new type is `GPV`, a `curve_id` must also
213    /// be supplied.
214    pub valve_type: Option<ValveType>,
215}
216
217/// Generic update for any link. Changing `start_node`/`end_node` is a topology change, forcing a complete solver and state re-initialization.
218/// changing `initial_status` or `vertices` is not.
219#[derive(Default)]
220pub struct LinkUpdate {
221    pub start_node: Option<Box<str>>,
222    pub end_node: Option<Box<str>>,
223    pub vertices: Option<Vec<(f64, f64)>>,
224    pub initial_status: Option<LinkStatus>,
225}
226
227/// Data for adding a new time pattern.
228#[derive(Default)]
229pub struct PatternData {
230    pub multipliers: Vec<f64>,
231}
232
233/// Data for updating an existing pattern. Only provided fields are changed.
234#[derive(Default)]
235pub struct PatternUpdate {
236    pub multipliers: Option<Vec<f64>>,
237}
238
239/// Data for adding a new curve. `x` and `y` must be non-empty and the same
240/// length; `x` must be strictly increasing.
241#[derive(Default)]
242pub struct CurveData {
243    pub x: Vec<f64>,
244    pub y: Vec<f64>,
245}
246
247/// Data for updating an existing curve. Any provided axis replaces the
248/// existing values; the resulting `x`/`y` pair must still satisfy the
249/// non-empty / same-length / monotonic-x invariants.
250#[derive(Default)]
251pub struct CurveUpdate {
252    pub x: Option<Vec<f64>>,
253    pub y: Option<Vec<f64>>,
254}
255
256impl Network {
257    /// Resets the change tracking flags by clearing the updated node and link sets.
258    pub fn reset_changes(&mut self) {
259        self.updated_nodes.clear();
260        self.updated_links.clear();
261    }
262
263    /// Add a new junction to the network.
264    pub fn add_junction(&mut self, id: &str, data: &JunctionData) -> Result<(), InputError> {
265        let mut demands = data.demands.clone();
266        Self::resolve_demand_patterns(&self.pattern_map, &mut demands)?;
267
268        let junction = Junction {
269            emitter_coefficient: data.emitter_coefficient,
270            demands,
271        };
272
273        let mut node = Node {
274            id: id.into(),
275            elevation: data.elevation,
276            node_type: NodeType::Junction(junction),
277            coordinates: data.coordinates,
278            disabled: false,
279        };
280
281        // convert the node to standard units
282        node.convert_to_standard(&self.options);
283        // add the node to the network
284        self.add_node(node)?;
285
286        Ok(())
287    }
288
289    /// Add a new tank to the network.
290    pub fn add_tank(&mut self, id: &str, data: &TankData) -> Result<(), InputError> {
291        // validate the volume curve id (if provided) exists
292        if let Some(curve_id) = &data.volume_curve_id
293            && !self.curve_map.contains_key(curve_id)
294        {
295            return Err(InputError::CurveNotFound {
296                curve_id: curve_id.clone(),
297            });
298        }
299
300        let tank = Tank {
301            elevation: data.elevation,
302            initial_level: data.initial_level,
303            min_level: data.min_level,
304            max_level: data.max_level,
305            diameter: data.diameter,
306            min_volume: data.min_volume,
307            volume_curve_id: data.volume_curve_id.clone(),
308            overflow: data.overflow,
309            volume_curve: None,
310            links_to: Vec::new(),
311            links_from: Vec::new(),
312        };
313        let mut node = Node {
314            id: id.into(),
315            elevation: data.elevation,
316            node_type: NodeType::Tank(tank),
317            coordinates: data.coordinates,
318            disabled: false,
319        };
320
321        // convert the tank node to standard units
322        node.convert_to_standard(&self.options);
323
324        // add the node to the network
325        self.add_node(node)?;
326
327        Ok(())
328    }
329
330    /// Add a new reservoir to the network.
331    pub fn add_reservoir(&mut self, id: &str, data: &ReservoirData) -> Result<(), InputError> {
332        // resolve the head pattern index
333        let head_pattern_index = if let Some(pattern) = &data.head_pattern {
334            Some(
335                *self
336                    .pattern_map
337                    .get(pattern)
338                    .ok_or(InputError::PatternNotFound {
339                        pattern_id: pattern.clone(),
340                    })?,
341            )
342        } else {
343            None
344        };
345
346        let reservoir = Reservoir {
347            head_pattern: data.head_pattern.clone(),
348            head_pattern_index,
349        };
350        let mut node = Node {
351            id: id.into(),
352            elevation: data.elevation,
353            node_type: NodeType::Reservoir(reservoir),
354            coordinates: data.coordinates,
355            disabled: false,
356        };
357
358        // convert the reservoir node to standard units
359        node.convert_to_standard(&self.options);
360        self.add_node(node)?;
361
362        Ok(())
363    }
364
365    pub fn update_junction(&mut self, id: &str, update: &JunctionUpdate) -> Result<(), InputError> {
366        // lookup the node index
367        let node_index = self
368            .node_map
369            .get(id)
370            .ok_or(InputError::NodeNotFound { node_id: id.into() })?;
371
372        // resolve the new pattern index up front (if a pattern change is
373        // requested) so we fail fast on an unknown pattern before mutating
374        // anything. `Some(Some(id))` sets the pattern; `Some(None)` clears it.
375        let pattern_change: Option<(Option<Box<str>>, Option<usize>)> = match &update.pattern {
376            None => None,                     // do nothing
377            Some(None) => Some((None, None)), // clear the pattern
378            Some(Some(pattern_id)) => {
379                let idx = *self.pattern_map.get(pattern_id).ok_or_else(|| {
380                    InputError::PatternNotFound {
381                        pattern_id: pattern_id.clone(),
382                    }
383                })?;
384                Some((Some(pattern_id.clone()), Some(idx))) // set the pattern and pattern index
385            }
386        };
387
388        let pattern_map = &self.pattern_map;
389        let node = &mut self.nodes[*node_index];
390        if !matches!(node.node_type, NodeType::Junction(_)) {
391            return Err(InputError::NodeNotAJunction { node_id: id.into() });
392        }
393
394        // convert to user units
395        node.convert_from_standard(&self.options);
396
397        if let NodeType::Junction(junction) = &mut node.node_type {
398            node.elevation = update.elevation.unwrap_or(node.elevation);
399
400            if let Some(coordinates) = update.coordinates {
401                node.coordinates = Some(coordinates);
402            }
403
404            junction.emitter_coefficient = update
405                .emitter_coefficient
406                .unwrap_or(junction.emitter_coefficient);
407
408            if let Some(demands) = &update.demands {
409                junction.demands = demands.clone();
410            }
411
412            if let Some(basedemand) = update.basedemand {
413                Self::primary_demand_mut(junction).basedemand = basedemand;
414            }
415
416            if let Some((new_pattern, new_index)) = pattern_change {
417                let demand = Self::primary_demand_mut(junction);
418                demand.pattern = new_pattern;
419                demand.pattern_index = new_index;
420            }
421
422            if let Some(disabled) = update.disabled {
423                if node.disabled != disabled {
424                    self.topology_version += 1; // set topology as stale
425                }
426                node.disabled = disabled;
427            }
428
429            Self::resolve_demand_patterns(pattern_map, &mut junction.demands)?;
430        }
431        // convert back to standard units
432        node.convert_to_standard(&self.options);
433
434        // add the node index to the updated nodes set, forcing state update
435        self.updated_nodes.insert(*node_index);
436        // increment the properties version
437        self.properties_version += 1;
438
439        Ok(())
440    }
441
442    /// Update the elevation and/or coordinates of any node (junction, tank, or reservoir).
443    /// For tanks, the tank's internal elevation is kept in sync with the node elevation.
444    pub fn update_node(&mut self, id: &str, update: &NodeUpdate) -> Result<(), InputError> {
445        let node_index = *self
446            .node_map
447            .get(id)
448            .ok_or(InputError::NodeNotFound { node_id: id.into() })?;
449
450        let node = &mut self.nodes[node_index];
451
452        if let Some(coordinates) = update.coordinates {
453            node.coordinates = Some(coordinates);
454        }
455
456        if let Some(disabled) = update.disabled {
457            if node.disabled != disabled {
458                self.topology_version += 1; // set topology as stale
459            }
460
461            node.disabled = disabled;
462        }
463
464        if let Some(new_elevation) = update.elevation {
465            node.convert_from_standard(&self.options);
466            node.elevation = new_elevation;
467            // if the node is a tank, update the tank's elevation as well
468            if let NodeType::Tank(tank) = &mut node.node_type {
469                tank.elevation = node.elevation;
470            }
471            node.convert_to_standard(&self.options);
472
473            // elevation affects the initial head of fixed-head nodes, so mark it as updated
474            self.updated_nodes.insert(node_index);
475            self.properties_version += 1;
476        }
477
478        Ok(())
479    }
480
481    /// Update a tank's properties. All fields are optional; only provided fields are changed.
482    pub fn update_tank(&mut self, id: &str, update: &TankUpdate) -> Result<(), InputError> {
483        let node_index = *self
484            .node_map
485            .get(id)
486            .ok_or(InputError::NodeNotFound { node_id: id.into() })?;
487
488        let node = &mut self.nodes[node_index];
489
490        // check if the node is a tank
491        if !matches!(node.node_type, NodeType::Tank(_)) {
492            return Err(InputError::NodeNotATank { node_id: id.into() });
493        }
494
495        if let Some(coordinates) = update.coordinates {
496            node.coordinates = Some(coordinates);
497        }
498
499        // convert to user units for in-place editing
500        node.convert_from_standard(&self.options);
501
502        if let Some(elevation) = update.elevation {
503            node.elevation = elevation;
504        }
505
506        if let NodeType::Tank(tank) = &mut node.node_type {
507            // keep tank.elevation in sync with node.elevation in user-unit space
508            // so convert_to_standard below converts both consistently
509            tank.elevation = node.elevation;
510            tank.initial_level = update.initial_level.unwrap_or(tank.initial_level);
511            tank.min_level = update.min_level.unwrap_or(tank.min_level);
512            tank.max_level = update.max_level.unwrap_or(tank.max_level);
513            tank.diameter = update.diameter.unwrap_or(tank.diameter);
514            tank.min_volume = update.min_volume.unwrap_or(tank.min_volume);
515            tank.overflow = update.overflow.unwrap_or(tank.overflow);
516        }
517
518        node.convert_to_standard(&self.options);
519
520        self.updated_nodes.insert(node_index);
521        self.properties_version += 1;
522
523        Ok(())
524    }
525
526    /// Update a reservoir's properties. `head_pattern` follows the
527    /// `Option<Option<_>>` convention: `None` leaves the pattern untouched,
528    /// `Some(None)` clears it, `Some(Some(id))` sets it.
529    pub fn update_reservoir(
530        &mut self,
531        id: &str,
532        update: &ReservoirUpdate,
533    ) -> Result<(), InputError> {
534        let node_index = *self
535            .node_map
536            .get(id)
537            .ok_or(InputError::NodeNotFound { node_id: id.into() })?;
538
539        // resolve the new pattern index up front (if a pattern change is
540        // requested) so we fail fast on an unknown pattern.
541        let pattern_change: Option<(Option<Box<str>>, Option<usize>)> = match &update.head_pattern {
542            None => None,                     // do nothing
543            Some(None) => Some((None, None)), // clear the pattern
544            Some(Some(pattern_id)) => {
545                let idx = *self.pattern_map.get(pattern_id).ok_or_else(|| {
546                    InputError::PatternNotFound {
547                        pattern_id: pattern_id.clone(),
548                    }
549                })?;
550                Some((Some(pattern_id.clone()), Some(idx))) // set the pattern and pattern index
551            }
552        };
553
554        let node = &mut self.nodes[node_index];
555
556        if !matches!(node.node_type, NodeType::Reservoir(_)) {
557            return Err(InputError::NodeNotAReservoir { node_id: id.into() });
558        }
559
560        if let Some(coordinates) = update.coordinates {
561            node.coordinates = Some(coordinates);
562        }
563
564        if let Some(elevation) = update.elevation {
565            node.convert_from_standard(&self.options);
566            node.elevation = elevation;
567            node.convert_to_standard(&self.options);
568        }
569
570        if let NodeType::Reservoir(reservoir) = &mut node.node_type
571            && let Some((new_pattern, new_index)) = pattern_change
572        {
573            reservoir.head_pattern = new_pattern;
574            reservoir.head_pattern_index = new_index;
575        }
576
577        self.updated_nodes.insert(node_index);
578        self.properties_version += 1;
579
580        Ok(())
581    }
582
583    // --- Link add/update methods ---
584
585    /// Add a new pipe to the network. Fails if either referenced node does not
586    /// exist or a link with the same id is already present.
587    pub fn add_pipe(&mut self, id: &str, data: &PipeData) -> Result<(), InputError> {
588        let start_node =
589            *self
590                .node_map
591                .get(&data.start_node)
592                .ok_or_else(|| InputError::NodeNotFound {
593                    node_id: data.start_node.clone(),
594                })?;
595        let end_node =
596            *self
597                .node_map
598                .get(&data.end_node)
599                .ok_or_else(|| InputError::NodeNotFound {
600                    node_id: data.end_node.clone(),
601                })?;
602
603        let pipe = Pipe {
604            diameter: data.diameter,
605            length: data.length,
606            roughness: data.roughness,
607            minor_loss: data.minor_loss,
608            check_valve: data.check_valve,
609            headloss_formula: self.options.headloss_formula,
610        };
611
612        let mut link = Link {
613            id: id.into(),
614            link_type: LinkType::Pipe(pipe),
615            start_node_id: data.start_node.clone(),
616            end_node_id: data.end_node.clone(),
617            initial_status: data.initial_status,
618            vertices: data.vertices.clone(),
619            start_node,
620            end_node,
621        };
622
623        // convert the link to internal units (feet, etc.)
624        link.convert_to_standard(&self.options);
625        // normalize the user-facing minor-loss coefficient against the internal diameter
626        if let LinkType::Pipe(pipe) = &mut link.link_type {
627            pipe.minor_loss = 0.02517 * pipe.minor_loss / pipe.diameter.powi(4);
628        }
629
630        self.add_link(link)
631    }
632
633    /// Add a new pump to the network. Any `head_curve_id` is resolved eagerly.
634    pub fn add_pump(&mut self, id: &str, data: &PumpData) -> Result<(), InputError> {
635        let start_node =
636            *self
637                .node_map
638                .get(&data.start_node)
639                .ok_or_else(|| InputError::NodeNotFound {
640                    node_id: data.start_node.clone(),
641                })?;
642        let end_node =
643            *self
644                .node_map
645                .get(&data.end_node)
646                .ok_or_else(|| InputError::NodeNotFound {
647                    node_id: data.end_node.clone(),
648                })?;
649
650        let head_curve = self.resolve_head_curve(data.head_curve_id.as_deref())?;
651
652        let pump = Pump {
653            speed: data.speed,
654            head_curve_id: data.head_curve_id.clone(),
655            power: data.power,
656            head_curve: None,
657        };
658
659        let mut link = Link {
660            id: id.into(),
661            link_type: LinkType::Pump(pump),
662            start_node_id: data.start_node.clone(),
663            end_node_id: data.end_node.clone(),
664            initial_status: data.initial_status,
665            vertices: data.vertices.clone(),
666            start_node,
667            end_node,
668        };
669
670        link.convert_to_standard(&self.options);
671        // assign the (already standard-units) head curve after unit conversion so
672        // it does not get double-converted by Pump::convert_to_standard
673        if let LinkType::Pump(pump) = &mut link.link_type {
674            pump.head_curve = head_curve;
675        }
676
677        self.add_link(link)
678    }
679
680    /// Add a new valve to the network. Any `curve_id` is resolved eagerly.
681    /// PSV/PRV valves store their setting as pressure (in feet of head) at
682    /// the anchor node; the solver adds the anchor's elevation at the point
683    /// of use, so the stored setting is independent of node elevation.
684    pub fn add_valve(&mut self, id: &str, data: &ValveData) -> Result<(), InputError> {
685        let start_node =
686            *self
687                .node_map
688                .get(&data.start_node)
689                .ok_or_else(|| InputError::NodeNotFound {
690                    node_id: data.start_node.clone(),
691                })?;
692        let end_node =
693            *self
694                .node_map
695                .get(&data.end_node)
696                .ok_or_else(|| InputError::NodeNotFound {
697                    node_id: data.end_node.clone(),
698                })?;
699
700        // // GPV valves are driven by their curve; require it up front
701        // if data.valve_type == ValveType::GPV && data.curve_id.is_none() {
702        //   return Err(InputError::new("GPV valves require a curve id"));
703        // }
704        // resolve the curve based on valve type. GPV curves are converted to
705        // standard units, while PCV curves are stored as-is because they
706        // represent dimensionless percentage relationships.
707        let (gpv_curve, pcv_curve) = match data.valve_type {
708            ValveType::GPV => (self.resolve_gpv_curve(data.curve_id.as_deref())?, None),
709            ValveType::PCV => (None, self.resolve_pcv_curve(data.curve_id.as_deref())?),
710            _ => (None, None),
711        };
712
713        let valve = Valve {
714            diameter: data.diameter,
715            setting: data.setting,
716            curve_id: data.curve_id.clone(),
717            valve_type: data.valve_type.clone(),
718            minor_loss: data.minor_loss,
719            gpv_curve: None,
720            pcv_curve: None,
721        };
722
723        let mut link = Link {
724            id: id.into(),
725            link_type: LinkType::Valve(valve),
726            start_node_id: data.start_node.clone(),
727            end_node_id: data.end_node.clone(),
728            initial_status: data.initial_status,
729            vertices: data.vertices.clone(),
730            start_node,
731            end_node,
732        };
733
734        link.convert_to_standard(&self.options);
735
736        // attach the curve and flag the network as containing PSV/PRV (no
737        // elevation offset is applied — the setting is stored as pressure).
738        if let LinkType::Valve(valve) = &mut link.link_type {
739            if matches!(valve.valve_type, ValveType::PSV | ValveType::PRV) {
740                self.contains_pressure_control_valve = true;
741            }
742            valve.gpv_curve = gpv_curve;
743            valve.pcv_curve = pcv_curve;
744        }
745
746        self.add_link(link)
747    }
748
749    /// Update properties of an existing pipe. Only provided fields are changed.
750    pub fn update_pipe(&mut self, id: &str, update: &PipeUpdate) -> Result<(), InputError> {
751        let link_index = *self
752            .link_map
753            .get(id)
754            .ok_or_else(|| InputError::LinkNotFound { link_id: id.into() })?;
755        let link = &mut self.links[link_index];
756
757        if !matches!(link.link_type, LinkType::Pipe(_)) {
758            return Err(InputError::LinkNotAPipe { link_id: id.into() });
759        }
760
761        link.convert_from_standard(&self.options);
762
763        if let LinkType::Pipe(pipe) = &mut link.link_type {
764            pipe.length = update.length.unwrap_or(pipe.length);
765            pipe.diameter = update.diameter.unwrap_or(pipe.diameter);
766            pipe.roughness = update.roughness.unwrap_or(pipe.roughness);
767            pipe.check_valve = update.check_valve.unwrap_or(pipe.check_valve);
768        }
769
770        link.convert_to_standard(&self.options);
771
772        // re-normalize the minor-loss coefficient against the (possibly new) diameter
773        if let LinkType::Pipe(pipe) = &mut link.link_type
774            && let Some(minor_loss) = update.minor_loss
775        {
776            // update the minor loss coefficient (this has to be done using standard units!)
777            pipe.minor_loss = 0.02517 * minor_loss / pipe.diameter.powi(4);
778        }
779
780        self.updated_links.insert(link_index);
781        self.properties_version += 1;
782        Ok(())
783    }
784
785    /// Update properties of an existing pump. `head_curve_id` follows the
786    /// `Option<Option<_>>` convention: `None` leaves the curve untouched,
787    /// `Some(None)` clears it (turning the pump into a constant-power or
788    /// open-valve pump depending on `power`), and `Some(Some(id))` attaches
789    /// the named head curve.
790    pub fn update_pump(&mut self, id: &str, update: &PumpUpdate) -> Result<(), InputError> {
791        let link_index = *self
792            .link_map
793            .get(id)
794            .ok_or_else(|| InputError::LinkNotFound { link_id: id.into() })?;
795
796        if !matches!(self.links[link_index].link_type, LinkType::Pump(_)) {
797            return Err(InputError::LinkNotAPump { link_id: id.into() });
798        }
799
800        // resolve the new head curve (if a curve change is requested) before we
801        // take a mutable borrow on the link.
802        let curve_change: Option<(Option<Box<str>>, Option<HeadCurve>)> =
803            match &update.head_curve_id {
804                None => None,                     // do nothing
805                Some(None) => Some((None, None)), // clear the curve
806                Some(Some(curve_id)) => {
807                    let resolved = self.resolve_head_curve(Some(curve_id.as_ref()))?;
808                    Some((Some(curve_id.clone()), resolved)) // set the curve and curve index
809                }
810            };
811
812        let link = &mut self.links[link_index];
813        link.convert_from_standard(&self.options);
814
815        if let LinkType::Pump(pump) = &mut link.link_type {
816            if let Some(speed) = update.speed {
817                pump.speed = speed;
818            }
819            if let Some(power) = update.power {
820                pump.power = power;
821            }
822        }
823
824        link.convert_to_standard(&self.options);
825
826        if let LinkType::Pump(pump) = &mut link.link_type
827            && let Some((new_curve_id, new_head_curve)) = curve_change
828        {
829            pump.head_curve_id = new_curve_id;
830            pump.head_curve = new_head_curve;
831        }
832
833        self.updated_links.insert(link_index);
834        self.properties_version += 1;
835        Ok(())
836    }
837
838    /// Update properties of an existing valve. `curve_id` follows the
839    /// `Option<Option<_>>` convention: `None` leaves the curve untouched,
840    /// `Some(None)` clears it, `Some(Some(id))` sets it (GPV valves cannot
841    /// have their curve cleared). PSV/PRV settings are stored as pressure
842    /// (in feet of head) and are independent of node elevation. Changing
843    /// `valve_type` requires a new `setting` (the stored value has no
844    /// meaning under a different type); switching to `GPV` also requires a
845    /// `curve_id` to be supplied.
846    pub fn update_valve(&mut self, id: &str, update: &ValveUpdate) -> Result<(), InputError> {
847        let link_index = *self
848            .link_map
849            .get(id)
850            .ok_or_else(|| InputError::LinkNotFound { link_id: id.into() })?;
851
852        if !matches!(self.links[link_index].link_type, LinkType::Valve(_)) {
853            return Err(InputError::LinkNotAValve { link_id: id.into() });
854        }
855
856        // capture the current valve_type and resolve the target valve_type so we
857        // can validate the update before mutating anything.
858        let (old_valve_type, old_curve_id) =
859            if let LinkType::Valve(valve) = &self.links[link_index].link_type {
860                (valve.valve_type.clone(), valve.curve_id.clone())
861            } else {
862                unreachable!()
863            };
864        let new_valve_type = update
865            .valve_type
866            .clone()
867            .unwrap_or_else(|| old_valve_type.clone());
868        let type_changed = new_valve_type != old_valve_type;
869
870        if type_changed && update.setting.is_none() {
871            return Err(InputError::new(format!(
872                "Changing valve_type on valve {} requires a new setting",
873                id
874            )));
875        }
876
877        // GPV valves always need a curve; the new rules for the tri-state
878        // `curve_id` field are:
879        //   * Some(None)         -> explicit clear is rejected for GPV
880        //   * type_changed=true  -> caller must provide Some(Some(_))
881        //   * type_changed=false -> keeping the existing curve (None) is fine
882        if new_valve_type == ValveType::GPV {
883            if matches!(update.curve_id, Some(None)) {
884                return Err(InputError::new(format!(
885                    "GPV valve {} requires a curve id",
886                    id
887                )));
888            }
889            if type_changed && !matches!(update.curve_id, Some(Some(_))) {
890                return Err(InputError::new(format!(
891                    "GPV valve {} requires a curve id",
892                    id
893                )));
894            }
895        }
896
897        // resolve the new curve (if a curve change is requested) before we take
898        // a mutable borrow on the link. The resolved curve type depends on the
899        // (possibly new) valve type: GPV uses a unit-converted ValveCurve,
900        // while PCV uses a raw Curve (its values are dimensionless percentages).
901        // When the valve type changes but curve_id is left unchanged, we still
902        // need to re-build the cached curve under the new type's semantics.
903        let curve_change: Option<(Option<Box<str>>, ResolvedValveCurve)> = match &update.curve_id {
904            None => {
905                if type_changed {
906                    let resolved = match (new_valve_type.clone(), old_curve_id.as_deref()) {
907                        (ValveType::GPV, Some(cid)) => {
908                            ResolvedValveCurve::Gpv(self.resolve_gpv_curve(Some(cid))?)
909                        }
910                        (ValveType::PCV, Some(cid)) => {
911                            ResolvedValveCurve::Pcv(self.resolve_pcv_curve(Some(cid))?)
912                        }
913                        _ => ResolvedValveCurve::None,
914                    };
915                    Some((old_curve_id.clone(), resolved))
916                } else {
917                    None
918                }
919            }
920            Some(None) => Some((None, ResolvedValveCurve::None)),
921            Some(Some(curve_id)) => {
922                let resolved = match new_valve_type {
923                    ValveType::GPV => {
924                        ResolvedValveCurve::Gpv(self.resolve_gpv_curve(Some(curve_id.as_ref()))?)
925                    }
926                    ValveType::PCV => {
927                        ResolvedValveCurve::Pcv(self.resolve_pcv_curve(Some(curve_id.as_ref()))?)
928                    }
929                    _ => ResolvedValveCurve::None,
930                };
931                Some((Some(curve_id.clone()), resolved))
932            }
933        };
934
935        let link = &mut self.links[link_index];
936
937        // PSV/PRV settings are stored as pressure (no elevation offset), so
938        // converting to/from user units is a straight unit conversion driven
939        // by the valve's current valve_type. We use the OLD type for the
940        // `from_standard` step below so the existing `setting` is interpreted
941        // correctly, and the NEW type for the `to_standard` step so the
942        // updated `setting` is interpreted in new-type semantics.
943        link.convert_from_standard(&self.options);
944
945        if let LinkType::Valve(valve) = &mut link.link_type {
946            if let Some(diameter) = update.diameter {
947                valve.diameter = diameter;
948            }
949            if let Some(setting) = update.setting {
950                valve.setting = setting;
951                // set the valve status to active
952                link.initial_status = LinkStatus::Active;
953            }
954            if let Some(minor_loss) = update.minor_loss {
955                valve.minor_loss = minor_loss;
956            }
957            valve.valve_type = new_valve_type.clone();
958        }
959
960        link.convert_to_standard(&self.options);
961
962        if let LinkType::Valve(valve) = &mut link.link_type
963            && let Some((new_curve_id, new_valve_curve)) = curve_change
964        {
965            valve.curve_id = new_curve_id;
966            // clear both caches and set whichever applies for the new type
967            valve.gpv_curve = None;
968            valve.pcv_curve = None;
969            match new_valve_curve {
970                ResolvedValveCurve::Gpv(c) => valve.gpv_curve = c,
971                ResolvedValveCurve::Pcv(c) => valve.pcv_curve = c,
972                ResolvedValveCurve::None => {}
973            }
974        }
975
976        // Recompute the PSV/PRV flag when the type changed (we may have added a
977        // pressure-control valve or removed the last one). Otherwise just make
978        // sure the flag is set for existing PSV/PRV valves.
979        if type_changed {
980            self.contains_pressure_control_valve = self.links.iter().any(|l| {
981                matches!(&l.link_type, LinkType::Valve(v)
982          if matches!(v.valve_type, ValveType::PSV | ValveType::PRV))
983            });
984        } else if matches!(new_valve_type, ValveType::PSV | ValveType::PRV) {
985            self.contains_pressure_control_valve = true;
986        }
987
988        self.updated_links.insert(link_index);
989        self.properties_version += 1;
990        Ok(())
991    }
992
993    /// Update the topology/display properties of any link: endpoints, vertices
994    /// and initial status. Type-specific properties must be edited via
995    /// [update_pipe], [update_pump] or [update_valve].
996    pub fn update_link(&mut self, id: &str, update: &LinkUpdate) -> Result<(), InputError> {
997        let link_index = *self
998            .link_map
999            .get(id)
1000            .ok_or_else(|| InputError::LinkNotFound { link_id: id.into() })?;
1001
1002        // resolve new endpoints up front so we fail fast on missing nodes
1003        let new_start = if let Some(start_id) = &update.start_node {
1004            Some((
1005                start_id.clone(),
1006                *self
1007                    .node_map
1008                    .get(start_id)
1009                    .ok_or_else(|| InputError::NodeNotFound {
1010                        node_id: start_id.clone(),
1011                    })?,
1012            ))
1013        } else {
1014            None
1015        };
1016        let new_end = if let Some(end_id) = &update.end_node {
1017            Some((
1018                end_id.clone(),
1019                *self
1020                    .node_map
1021                    .get(end_id)
1022                    .ok_or_else(|| InputError::NodeNotFound {
1023                        node_id: end_id.clone(),
1024                    })?,
1025            ))
1026        } else {
1027            None
1028        };
1029
1030        let link = &self.links[link_index];
1031        let old_start = link.start_node;
1032        let old_end = link.end_node;
1033
1034        let mut topology_changed = false;
1035
1036        if let Some((start_id, start_idx)) = new_start {
1037            // detach from old tank's links_from and attach to new tank's links_from
1038            remove_tank_link(
1039                &mut self.nodes[old_start],
1040                link_index,
1041                /*outgoing=*/ true,
1042            );
1043            attach_tank_link(
1044                &mut self.nodes[start_idx],
1045                link_index,
1046                /*outgoing=*/ true,
1047            );
1048
1049            let link = &mut self.links[link_index];
1050            link.start_node = start_idx;
1051            link.start_node_id = start_id;
1052
1053            // PSV/PRV settings are stored as pressure (independent of node
1054            // elevation), so swapping endpoints does not alter the setting.
1055            topology_changed = true;
1056        }
1057
1058        if let Some((end_id, end_idx)) = new_end {
1059            remove_tank_link(
1060                &mut self.nodes[old_end],
1061                link_index,
1062                /*outgoing=*/ false,
1063            );
1064            attach_tank_link(
1065                &mut self.nodes[end_idx],
1066                link_index,
1067                /*outgoing=*/ false,
1068            );
1069
1070            let link = &mut self.links[link_index];
1071            link.end_node = end_idx;
1072            link.end_node_id = end_id;
1073
1074            topology_changed = true;
1075        }
1076
1077        let link = &mut self.links[link_index];
1078        if let Some(vertices) = &update.vertices {
1079            link.vertices = Some(vertices.clone());
1080        }
1081
1082        let mut properties_changed = false;
1083        if let Some(status) = update.initial_status
1084            && link.initial_status != status
1085        {
1086            link.initial_status = status;
1087            properties_changed = true;
1088        }
1089
1090        if topology_changed {
1091            self.topology_version += 1;
1092        }
1093        if properties_changed {
1094            self.updated_links.insert(link_index);
1095            self.properties_version += 1;
1096        }
1097
1098        Ok(())
1099    }
1100
1101    // --- removal methods ---
1102
1103    /// Remove a link from the network. Fails if any control references the
1104    /// link. Uses `swap_remove` internally, so the last link in `links` takes
1105    /// the removed link's slot; `link_map`, tank link lists and `updated_links`
1106    /// are all kept in sync.
1107    /// `unconditional` is a boolean flag that indicates if the link should be removed if it is referenced by a control. If set to true, remove the link as well as any controls that reference it.
1108    pub fn remove_link(&mut self, id: &str, unconditional: bool) -> Result<(), InputError> {
1109        let link_index = *self
1110            .link_map
1111            .get(id)
1112            .ok_or_else(|| InputError::LinkNotFound { link_id: id.into() })?;
1113
1114        if !unconditional && self.controls.iter().any(|c| c.link_id.as_ref() == id) {
1115            return Err(InputError::new(format!(
1116                "Cannot remove link {}: referenced by a control",
1117                id
1118            )));
1119        }
1120
1121        let (start_node, end_node, was_pressure_control) = {
1122            let link = &self.links[link_index];
1123            let was_pc = matches!(&link.link_type, LinkType::Valve(v)
1124        if matches!(v.valve_type, ValveType::PSV | ValveType::PRV));
1125            (link.start_node, link.end_node, was_pc)
1126        };
1127
1128        // detach from tank link lists at both endpoints
1129        remove_tank_link(
1130            &mut self.nodes[start_node],
1131            link_index,
1132            /*outgoing=*/ true,
1133        );
1134        remove_tank_link(
1135            &mut self.nodes[end_node],
1136            link_index,
1137            /*outgoing=*/ false,
1138        );
1139
1140        self.link_map.remove(id);
1141        self.updated_links.remove(&link_index);
1142
1143        let last_index = self.links.len() - 1;
1144        self.links.swap_remove(link_index);
1145
1146        // if swap_remove moved a different link into `link_index`, reindex it
1147        if link_index != last_index {
1148            let (moved_id, moved_start, moved_end) = {
1149                let moved = &self.links[link_index];
1150                (moved.id.clone(), moved.start_node, moved.end_node)
1151            };
1152            self.link_map.insert(moved_id, link_index);
1153            retarget_tank_link(
1154                &mut self.nodes[moved_start],
1155                last_index,
1156                link_index,
1157                /*outgoing=*/ true,
1158            );
1159            retarget_tank_link(
1160                &mut self.nodes[moved_end],
1161                last_index,
1162                link_index,
1163                /*outgoing=*/ false,
1164            );
1165            if self.updated_links.remove(&last_index) {
1166                self.updated_links.insert(link_index);
1167            }
1168        }
1169
1170        if was_pressure_control {
1171            self.contains_pressure_control_valve = self.links.iter().any(|l| {
1172                matches!(&l.link_type, LinkType::Valve(v)
1173          if matches!(v.valve_type, ValveType::PSV | ValveType::PRV))
1174            });
1175        }
1176        // remove any controls that reference this link
1177        if unconditional {
1178            self.controls.retain(|c| c.link_id.as_ref() != id);
1179        }
1180
1181        self.topology_version += 1;
1182        Ok(())
1183    }
1184
1185    /// Remove a node from the network. Any links attached to the node are
1186    /// cascade-removed first via `remove_link` (so their controls must not
1187    /// block removal). Fails if a control still references the node itself.
1188    /// Uses `swap_remove` internally, so the last node in `nodes` takes the
1189    /// removed node's slot; `node_map`, link endpoint indices, control
1190    /// node/tank indices and `updated_nodes` are all kept in sync.
1191    /// `unconditional` is a boolean flag that indicates if the node should be removed if it is referenced by a control. If set to true, remove the node as well as any controls that reference it.
1192    pub fn remove_node(&mut self, id: &str, unconditional: bool) -> Result<(), InputError> {
1193        let node_index = *self
1194            .node_map
1195            .get(id)
1196            .ok_or_else(|| InputError::NodeNotFound { node_id: id.into() })?;
1197
1198        let referenced_by_control = self.controls.iter().any(|c| match &c.condition {
1199            ControlCondition::HighPressure { node_index: ni, .. }
1200            | ControlCondition::LowPressure { node_index: ni, .. } => *ni == node_index,
1201            ControlCondition::HighLevel { tank_index, .. }
1202            | ControlCondition::LowLevel { tank_index, .. } => *tank_index == node_index,
1203            _ => false,
1204        });
1205        if !unconditional && referenced_by_control {
1206            return Err(InputError::new(format!(
1207                "Cannot remove node {}: referenced by a control",
1208                id
1209            )));
1210        }
1211
1212        // cascade-remove every link attached to this node (at either endpoint).
1213        // ids are collected up front since `remove_link` uses `swap_remove` and
1214        // therefore invalidates positional link indices as it runs.
1215        let connected_link_ids: Vec<Box<str>> = self
1216            .links
1217            .iter()
1218            .filter(|l| l.start_node == node_index || l.end_node == node_index)
1219            .map(|l| l.id.clone())
1220            .collect();
1221
1222        // check if any of the connected links are referenced by a control
1223        if !unconditional
1224            && self
1225                .controls
1226                .iter()
1227                .any(|c| connected_link_ids.contains(&c.link_id))
1228        {
1229            return Err(InputError::new(format!(
1230                "Cannot remove node {}: referenced by a control",
1231                id
1232            )));
1233        }
1234
1235        for link_id in &connected_link_ids {
1236            self.remove_link(link_id, unconditional)?;
1237        }
1238
1239        // remove any controls that reference this node (by node or tank index).
1240        // must happen before `swap_remove` so the match is against the current
1241        // `node_index` rather than the post-swap slot.
1242        if unconditional {
1243            self.controls.retain(|c| match &c.condition {
1244                ControlCondition::HighPressure { node_index: ni, .. }
1245                | ControlCondition::LowPressure { node_index: ni, .. } => *ni != node_index,
1246                ControlCondition::HighLevel { tank_index, .. }
1247                | ControlCondition::LowLevel { tank_index, .. } => *tank_index != node_index,
1248                _ => true,
1249            });
1250        }
1251
1252        self.node_map.remove(id);
1253        self.updated_nodes.remove(&node_index);
1254
1255        let last_index = self.nodes.len() - 1;
1256        self.nodes.swap_remove(node_index);
1257
1258        if node_index != last_index {
1259            let moved_id = self.nodes[node_index].id.clone();
1260            self.node_map.insert(moved_id, node_index);
1261
1262            for link in self.links.iter_mut() {
1263                if link.start_node == last_index {
1264                    link.start_node = node_index;
1265                }
1266                if link.end_node == last_index {
1267                    link.end_node = node_index;
1268                }
1269            }
1270
1271            for control in self.controls.iter_mut() {
1272                match &mut control.condition {
1273                    ControlCondition::HighPressure { node_index: ni, .. }
1274                    | ControlCondition::LowPressure { node_index: ni, .. }
1275                        if *ni == last_index =>
1276                    {
1277                        *ni = node_index;
1278                    }
1279                    ControlCondition::HighLevel { tank_index, .. }
1280                    | ControlCondition::LowLevel { tank_index, .. }
1281                        if *tank_index == last_index =>
1282                    {
1283                        *tank_index = node_index;
1284                    }
1285                    _ => {}
1286                }
1287            }
1288
1289            if self.updated_nodes.remove(&last_index) {
1290                self.updated_nodes.insert(node_index);
1291            }
1292        }
1293
1294        self.topology_version += 1;
1295        Ok(())
1296    }
1297
1298    // --- pattern methods ---
1299
1300    /// Add a new time pattern to the network. Fails if a pattern with the same
1301    /// id already exists.
1302    pub fn add_pattern(&mut self, id: &str, data: &PatternData) -> Result<(), InputError> {
1303        if self.pattern_map.contains_key(id) {
1304            return Err(InputError::new(format!("Pattern {} already exists", id)));
1305        }
1306        let pattern = Pattern {
1307            id: id.into(),
1308            multipliers: data.multipliers.clone(),
1309        };
1310        self.pattern_map
1311            .insert(pattern.id.clone(), self.patterns.len());
1312        self.patterns.push(pattern);
1313        Ok(())
1314    }
1315
1316    /// Update an existing pattern's multipliers in place. Only provided fields
1317    /// are changed.
1318    pub fn update_pattern(&mut self, id: &str, update: &PatternUpdate) -> Result<(), InputError> {
1319        let pattern_index =
1320            *self
1321                .pattern_map
1322                .get(id)
1323                .ok_or_else(|| InputError::PatternNotFound {
1324                    pattern_id: id.into(),
1325                })?;
1326
1327        if let Some(multipliers) = &update.multipliers {
1328            self.patterns[pattern_index].multipliers = multipliers.clone();
1329            // pattern coefficients are re-read every timestep, so no per-node
1330            // invalidation is required; bump properties_version so callers can
1331            // still detect a change.
1332            self.properties_version += 1;
1333        }
1334        Ok(())
1335    }
1336
1337    /// Remove a pattern from the network. Fails if any junction or reservoir
1338    /// still references the pattern. Uses `swap_remove` internally, so the last
1339    /// pattern in `patterns` takes the removed pattern's slot; `pattern_map`
1340    /// and every cached `pattern_index`/`head_pattern_index` is kept in sync.
1341    pub fn remove_pattern(&mut self, id: &str) -> Result<(), InputError> {
1342        let pattern_index =
1343            *self
1344                .pattern_map
1345                .get(id)
1346                .ok_or_else(|| InputError::PatternNotFound {
1347                    pattern_id: id.into(),
1348                })?;
1349
1350        let referenced = self.nodes.iter().any(|n| match &n.node_type {
1351            NodeType::Junction(j) => j.demands.iter().any(|d| d.pattern.as_deref() == Some(id)),
1352            NodeType::Reservoir(r) => r.head_pattern.as_deref() == Some(id),
1353            _ => false,
1354        });
1355        if referenced {
1356            return Err(InputError::new(format!(
1357                "Cannot remove pattern {}: referenced by one or more nodes",
1358                id
1359            )));
1360        }
1361
1362        self.pattern_map.remove(id);
1363
1364        let last_index = self.patterns.len() - 1;
1365        self.patterns.swap_remove(pattern_index);
1366
1367        // if swap_remove moved a different pattern into this slot, rebind it in
1368        // the map and re-resolve every node's cached pattern_index so stale
1369        // `last_index` hits become `pattern_index`.
1370        if pattern_index != last_index {
1371            let moved_id = self.patterns[pattern_index].id.clone();
1372            self.pattern_map.insert(moved_id, pattern_index);
1373            self.resolve_pattern_indices();
1374        }
1375        Ok(())
1376    }
1377
1378    // --- curve methods ---
1379
1380    /// Add a new curve to the network. Fails if the id already exists or the
1381    /// x/y arrays are empty, of unequal length, or x is not strictly
1382    /// increasing.
1383    pub fn add_curve(&mut self, id: &str, data: &CurveData) -> Result<(), InputError> {
1384        if self.curve_map.contains_key(id) {
1385            return Err(InputError::new(format!("Curve {} already exists", id)));
1386        }
1387        validate_curve_axes(&data.x, &data.y)?;
1388        let curve = Curve {
1389            id: id.into(),
1390            x: data.x.clone(),
1391            y: data.y.clone(),
1392        };
1393        self.curve_map.insert(curve.id.clone(), self.curves.len());
1394        self.curves.push(curve);
1395        Ok(())
1396    }
1397
1398    /// Update an existing curve's axes. Any axis left `None` is preserved.
1399    /// Every pump/valve whose cached `HeadCurve`/`ValveCurve` was derived from
1400    /// this curve is rebuilt, and those links are marked as updated.
1401    pub fn update_curve(&mut self, id: &str, update: &CurveUpdate) -> Result<(), InputError> {
1402        let curve_index = *self
1403            .curve_map
1404            .get(id)
1405            .ok_or_else(|| InputError::CurveNotFound {
1406                curve_id: id.into(),
1407            })?;
1408
1409        // decide the new x/y up front so we can validate before mutating
1410        let new_x = update
1411            .x
1412            .clone()
1413            .unwrap_or_else(|| self.curves[curve_index].x.clone());
1414        let new_y = update
1415            .y
1416            .clone()
1417            .unwrap_or_else(|| self.curves[curve_index].y.clone());
1418        validate_curve_axes(&new_x, &new_y)?;
1419
1420        self.curves[curve_index].x = new_x;
1421        self.curves[curve_index].y = new_y;
1422
1423        // rebuild every derived HeadCurve/ValveCurve that references this curve
1424        // by id, and mark the owning link as updated so the solver picks up the
1425        // new coefficients.
1426        let curve = &self.curves[curve_index];
1427        for (i, link) in self.links.iter_mut().enumerate() {
1428            match &mut link.link_type {
1429                LinkType::Pump(pump) if pump.head_curve_id.as_deref() == Some(id) => {
1430                    pump.head_curve = Some(HeadCurve::new(
1431                        curve,
1432                        &self.options.flow_units,
1433                        &self.options.unit_system,
1434                    )?);
1435                    self.updated_links.insert(i);
1436                }
1437                LinkType::Valve(valve) if valve.curve_id.as_deref() == Some(id) => {
1438                    match valve.valve_type {
1439                        ValveType::GPV => {
1440                            valve.gpv_curve = Some(ValveCurve::new(
1441                                curve,
1442                                &self.options.flow_units,
1443                                &self.options.unit_system,
1444                            )?);
1445                        }
1446                        ValveType::PCV => {
1447                            valve.pcv_curve = Some(curve.clone());
1448                        }
1449                        _ => {}
1450                    }
1451                    self.updated_links.insert(i);
1452                }
1453                _ => {}
1454            }
1455        }
1456        self.properties_version += 1;
1457        Ok(())
1458    }
1459
1460    /// Remove a curve from the network. Fails if any pump, valve or tank still
1461    /// references the curve. Uses `swap_remove` internally; `curve_map` is
1462    /// kept in sync. Derived `HeadCurve`/`ValveCurve` caches are not tracked
1463    /// by index and therefore need no remapping.
1464    pub fn remove_curve(&mut self, id: &str) -> Result<(), InputError> {
1465        let curve_index = *self
1466            .curve_map
1467            .get(id)
1468            .ok_or_else(|| InputError::CurveNotFound {
1469                curve_id: id.into(),
1470            })?;
1471
1472        let referenced_by_link = self.links.iter().any(|l| match &l.link_type {
1473            LinkType::Pump(p) => p.head_curve_id.as_deref() == Some(id),
1474            LinkType::Valve(v) => v.curve_id.as_deref() == Some(id),
1475            _ => false,
1476        });
1477        let referenced_by_tank = self.nodes.iter().any(|n| match &n.node_type {
1478            NodeType::Tank(t) => t.volume_curve_id.as_deref() == Some(id),
1479            _ => false,
1480        });
1481        if referenced_by_link || referenced_by_tank {
1482            return Err(InputError::new(format!(
1483                "Cannot remove curve {}: referenced by one or more links or tanks",
1484                id
1485            )));
1486        }
1487
1488        self.curve_map.remove(id);
1489
1490        let last_index = self.curves.len() - 1;
1491        self.curves.swap_remove(curve_index);
1492
1493        if curve_index != last_index {
1494            let moved_id = self.curves[curve_index].id.clone();
1495            self.curve_map.insert(moved_id, curve_index);
1496        }
1497        Ok(())
1498    }
1499
1500    // --- private helpers ---
1501
1502    fn resolve_demand_patterns(
1503        pattern_map: &HashMap<Box<str>, usize>,
1504        demands: &mut [Demand],
1505    ) -> Result<(), InputError> {
1506        for demand in demands.iter_mut() {
1507            demand.pattern_index = demand
1508                .pattern
1509                .as_ref()
1510                .map(|pattern_id| {
1511                    pattern_map
1512                        .get(pattern_id)
1513                        .ok_or(InputError::PatternNotFound {
1514                            pattern_id: pattern_id.clone(),
1515                        })
1516                        .copied()
1517                })
1518                .transpose()?;
1519        }
1520        Ok(())
1521    }
1522
1523    fn primary_demand_mut(junction: &mut Junction) -> &mut Demand {
1524        if junction.demands.is_empty() {
1525            junction.demands.push(Demand {
1526                basedemand: 0.0,
1527                pattern: None,
1528                pattern_index: None,
1529                name: None,
1530            });
1531        }
1532        &mut junction.demands[0]
1533    }
1534
1535    fn resolve_head_curve(&self, curve_id: Option<&str>) -> Result<Option<HeadCurve>, InputError> {
1536        let Some(curve_id) = curve_id else {
1537            return Ok(None);
1538        };
1539        let curve_index =
1540            *self
1541                .curve_map
1542                .get(curve_id)
1543                .ok_or_else(|| InputError::CurveNotFound {
1544                    curve_id: curve_id.into(),
1545                })?;
1546        let curve = &self.curves[curve_index];
1547        Ok(Some(HeadCurve::new(
1548            curve,
1549            &self.options.flow_units,
1550            &self.options.unit_system,
1551        )?))
1552    }
1553
1554    /// Resolve a curve id to a unit-converted [`ValveCurve`] used by GPV
1555    /// valves. The curve x/y values are converted from user units to the
1556    /// internal CFS/feet representation.
1557    fn resolve_gpv_curve(&self, curve_id: Option<&str>) -> Result<Option<ValveCurve>, InputError> {
1558        let Some(curve_id) = curve_id else {
1559            return Ok(None);
1560        };
1561        let curve_index =
1562            *self
1563                .curve_map
1564                .get(curve_id)
1565                .ok_or_else(|| InputError::CurveNotFound {
1566                    curve_id: curve_id.into(),
1567                })?;
1568        let curve = &self.curves[curve_index];
1569        Ok(Some(ValveCurve::new(
1570            curve,
1571            &self.options.flow_units,
1572            &self.options.unit_system,
1573        )?))
1574    }
1575
1576    /// Resolve a curve id to a raw [`Curve`] used by PCV valves. PCV curves
1577    /// describe a dimensionless percent-open vs. flow-ratio relationship and
1578    /// are therefore stored unmodified.
1579    fn resolve_pcv_curve(&self, curve_id: Option<&str>) -> Result<Option<Curve>, InputError> {
1580        let Some(curve_id) = curve_id else {
1581            return Ok(None);
1582        };
1583        let curve_index =
1584            *self
1585                .curve_map
1586                .get(curve_id)
1587                .ok_or_else(|| InputError::CurveNotFound {
1588                    curve_id: curve_id.into(),
1589                })?;
1590        Ok(Some(self.curves[curve_index].clone()))
1591    }
1592}
1593
1594/// Result of resolving a curve id for a valve. The variant carried depends
1595/// on the valve's type because GPV and PCV valves cache different
1596/// representations of the underlying curve (see [`Valve::gpv_curve`] and
1597/// [`Valve::pcv_curve`]).
1598enum ResolvedValveCurve {
1599    Gpv(Option<ValveCurve>),
1600    Pcv(Option<Curve>),
1601    None,
1602}
1603
1604/// Validate a raw curve's x/y arrays: both must be non-empty, of equal
1605/// length, and `x` must be strictly increasing. Unit-specific validation
1606/// (e.g. pump curve monotonicity) happens later when the derived
1607/// `HeadCurve`/`ValveCurve` is built.
1608fn validate_curve_axes(x: &[f64], y: &[f64]) -> Result<(), InputError> {
1609    if x.is_empty() || y.is_empty() {
1610        return Err(InputError::new("Curve x/y arrays must be non-empty"));
1611    }
1612    if x.len() != y.len() {
1613        return Err(InputError::new(format!(
1614            "Curve x/y arrays must have the same length (got {} and {})",
1615            x.len(),
1616            y.len(),
1617        )));
1618    }
1619    for i in 1..x.len() {
1620        if x[i] <= x[i - 1] {
1621            return Err(InputError::new(
1622                "Curve x values must be strictly increasing",
1623            ));
1624        }
1625    }
1626    Ok(())
1627}
1628
1629/// Remove `link_index` from the tank's outgoing (`links_from`) or incoming
1630/// (`links_to`) list when the node happens to be a tank. No-op for other node
1631/// types.
1632fn remove_tank_link(node: &mut Node, link_index: usize, outgoing: bool) {
1633    if let NodeType::Tank(tank) = &mut node.node_type {
1634        let list = if outgoing {
1635            &mut tank.links_from
1636        } else {
1637            &mut tank.links_to
1638        };
1639        if let Some(pos) = list.iter().position(|&i| i == link_index) {
1640            list.swap_remove(pos);
1641        }
1642    }
1643}
1644
1645/// Append `link_index` to the tank's outgoing or incoming list when the node
1646/// happens to be a tank. No-op for other node types.
1647fn attach_tank_link(node: &mut Node, link_index: usize, outgoing: bool) {
1648    if let NodeType::Tank(tank) = &mut node.node_type {
1649        let list = if outgoing {
1650            &mut tank.links_from
1651        } else {
1652            &mut tank.links_to
1653        };
1654        list.push(link_index);
1655    }
1656}
1657
1658/// Replace `old_index` with `new_index` in the tank's outgoing (`links_from`)
1659/// or incoming (`links_to`) list. Used after `swap_remove` on `links` to
1660/// point tank link lists at the moved link's new slot. No-op for non-tank
1661/// nodes.
1662fn retarget_tank_link(node: &mut Node, old_index: usize, new_index: usize, outgoing: bool) {
1663    if let NodeType::Tank(tank) = &mut node.node_type {
1664        let list = if outgoing {
1665            &mut tank.links_from
1666        } else {
1667            &mut tank.links_to
1668        };
1669        for i in list.iter_mut() {
1670            if *i == old_index {
1671                *i = new_index;
1672            }
1673        }
1674    }
1675}
1676
1677#[cfg(test)]
1678mod tests {
1679    use super::*;
1680    use crate::constants::MperFT;
1681    use crate::model::options::HeadlossFormula;
1682    use crate::model::reservoir::Reservoir;
1683    use crate::model::tank::Tank;
1684    use crate::model::units::FlowUnits;
1685
1686    fn demands(basedemand: f64, pattern: Option<&str>) -> Vec<Demand> {
1687        vec![Demand {
1688            basedemand,
1689            pattern: pattern.map(Into::into),
1690            pattern_index: None,
1691            name: None,
1692        }]
1693    }
1694
1695    // --- helpers for tank/reservoir tests (no public add_tank/add_reservoir yet) ---
1696
1697    fn test_tank_node(id: &str, elevation: f64) -> Node {
1698        Node {
1699            id: id.into(),
1700            elevation,
1701            node_type: NodeType::Tank(Tank {
1702                elevation,
1703                initial_level: 10.0,
1704                min_level: 0.0,
1705                max_level: 20.0,
1706                diameter: 50.0,
1707                min_volume: 0.0,
1708                volume_curve_id: None,
1709                overflow: false,
1710                volume_curve: None,
1711                links_to: Vec::new(),
1712                links_from: Vec::new(),
1713            }),
1714            coordinates: None,
1715            disabled: false,
1716        }
1717    }
1718
1719    fn test_reservoir_node(id: &str, elevation: f64) -> Node {
1720        Node {
1721            id: id.into(),
1722            elevation,
1723            node_type: NodeType::Reservoir(Reservoir {
1724                head_pattern: None,
1725                head_pattern_index: None,
1726            }),
1727            coordinates: None,
1728            disabled: false,
1729        }
1730    }
1731
1732    // --- Junction tests ---
1733
1734    #[test]
1735    fn test_add_and_update_junction() {
1736        let mut network = Network::default();
1737        let data = JunctionData {
1738            elevation: 100.0,
1739            demands: demands(10.0, None),
1740            emitter_coefficient: 0.0,
1741            coordinates: None,
1742        };
1743        network.add_junction("J1", &data).unwrap();
1744
1745        assert_eq!(network.nodes.len(), 1);
1746        assert_eq!(network.nodes[0].id, "J1".into());
1747        assert_eq!(network.nodes[0].elevation, 100.0);
1748        assert_eq!(network.topology_version, 1);
1749        assert_eq!(network.properties_version, 0);
1750
1751        let update = JunctionUpdate {
1752            elevation: Some(200.0),
1753            demands: None,
1754            basedemand: Some(20.0),
1755            emitter_coefficient: Some(0.5),
1756            pattern: None,
1757            coordinates: None,
1758            disabled: None,
1759        };
1760        network.update_junction("J1", &update).unwrap();
1761        assert_eq!(network.nodes[0].elevation, 200.0);
1762        let NodeType::Junction(junction) = &network.nodes[0].node_type else {
1763            panic!("Expected Junction node type");
1764        };
1765        assert_eq!(junction.demands[0].basedemand, 20.0);
1766        assert!((junction.emitter_coefficient - 9.231479).abs() < 1e-6);
1767        assert_eq!(network.properties_version, 1);
1768    }
1769
1770    #[test]
1771    fn test_update_junction_none_pattern_leaves_existing_pattern() {
1772        let mut network = Network::default();
1773        network.patterns.push(Pattern {
1774            id: "P1".into(),
1775            multipliers: vec![1.0],
1776        });
1777        network.pattern_map.insert("P1".into(), 0);
1778        network
1779            .add_junction(
1780                "J1",
1781                &JunctionData {
1782                    elevation: 100.0,
1783                    demands: demands(10.0, Some("P1")),
1784                    emitter_coefficient: 0.0,
1785                    coordinates: None,
1786                },
1787            )
1788            .unwrap();
1789
1790        network
1791            .update_junction(
1792                "J1",
1793                &JunctionUpdate {
1794                    basedemand: Some(20.0),
1795                    pattern: None,
1796                    ..Default::default()
1797                },
1798            )
1799            .unwrap();
1800
1801        let NodeType::Junction(junction) = &network.nodes[0].node_type else {
1802            panic!("Expected Junction node type");
1803        };
1804        assert_eq!(junction.demands[0].pattern.as_deref(), Some("P1"));
1805        assert_eq!(junction.demands[0].pattern_index, Some(0));
1806        assert_eq!(junction.demands[0].basedemand, 20.0);
1807    }
1808
1809    #[test]
1810    fn test_update_junction_clears_pattern() {
1811        let mut network = Network::default();
1812        network.patterns.push(Pattern {
1813            id: "P1".into(),
1814            multipliers: vec![1.0],
1815        });
1816        network.pattern_map.insert("P1".into(), 0);
1817        network
1818            .add_junction(
1819                "J1",
1820                &JunctionData {
1821                    elevation: 100.0,
1822                    demands: demands(10.0, Some("P1")),
1823                    emitter_coefficient: 0.0,
1824                    coordinates: None,
1825                },
1826            )
1827            .unwrap();
1828
1829        network
1830            .update_junction(
1831                "J1",
1832                &JunctionUpdate {
1833                    pattern: Some(None),
1834                    ..Default::default()
1835                },
1836            )
1837            .unwrap();
1838
1839        let NodeType::Junction(junction) = &network.nodes[0].node_type else {
1840            panic!("Expected Junction node type");
1841        };
1842        assert!(junction.demands[0].pattern.is_none());
1843        assert!(junction.demands[0].pattern_index.is_none());
1844    }
1845
1846    #[test]
1847    fn test_update_junction_sets_pattern() {
1848        let mut network = Network::default();
1849        network.patterns.push(Pattern {
1850            id: "P1".into(),
1851            multipliers: vec![1.0],
1852        });
1853        network.pattern_map.insert("P1".into(), 0);
1854        network
1855            .add_junction(
1856                "J1",
1857                &JunctionData {
1858                    elevation: 100.0,
1859                    demands: demands(10.0, None),
1860                    emitter_coefficient: 0.0,
1861                    coordinates: None,
1862                },
1863            )
1864            .unwrap();
1865
1866        network
1867            .update_junction(
1868                "J1",
1869                &JunctionUpdate {
1870                    pattern: Some(Some("P1".into())),
1871                    ..Default::default()
1872                },
1873            )
1874            .unwrap();
1875
1876        let NodeType::Junction(junction) = &network.nodes[0].node_type else {
1877            panic!("Expected Junction node type");
1878        };
1879        assert_eq!(junction.demands[0].pattern.as_deref(), Some("P1"));
1880        assert_eq!(junction.demands[0].pattern_index, Some(0));
1881    }
1882
1883    #[test]
1884    fn test_update_junction_pattern_not_found() {
1885        let mut network = Network::default();
1886        network
1887            .add_junction(
1888                "J1",
1889                &JunctionData {
1890                    elevation: 100.0,
1891                    demands: demands(10.0, None),
1892                    emitter_coefficient: 0.0,
1893                    coordinates: None,
1894                },
1895            )
1896            .unwrap();
1897
1898        let err = network
1899            .update_junction(
1900                "J1",
1901                &JunctionUpdate {
1902                    pattern: Some(Some("missing".into())),
1903                    ..Default::default()
1904                },
1905            )
1906            .unwrap_err();
1907        assert!(matches!(err, InputError::PatternNotFound { .. }));
1908    }
1909
1910    #[test]
1911    fn test_add_junction_si() {
1912        let mut network = Network::new(FlowUnits::CMH, HeadlossFormula::HazenWilliams);
1913        let data = JunctionData {
1914            elevation: 100.0,
1915            demands: demands(10.0, None),
1916            emitter_coefficient: 0.0,
1917            coordinates: None,
1918        };
1919        network.add_junction("J1", &data).unwrap();
1920        assert_eq!(network.nodes[0].elevation, 100.0 / MperFT);
1921    }
1922
1923    // --- add_tank tests ---
1924
1925    fn test_tank_data(elevation: f64) -> TankData {
1926        TankData {
1927            elevation,
1928            initial_level: 10.0,
1929            min_level: 0.0,
1930            max_level: 20.0,
1931            diameter: 50.0,
1932            min_volume: 0.0,
1933            volume_curve_id: None,
1934            overflow: false,
1935            coordinates: None,
1936        }
1937    }
1938
1939    #[test]
1940    fn test_add_tank() {
1941        let mut network = Network::default();
1942        let data = TankData {
1943            coordinates: Some((1.0, 2.0)),
1944            ..test_tank_data(100.0)
1945        };
1946        network.add_tank("T1", &data).unwrap();
1947
1948        assert_eq!(network.nodes.len(), 1);
1949        assert_eq!(network.nodes[0].id, "T1".into());
1950        assert_eq!(network.nodes[0].elevation, 100.0);
1951        assert_eq!(network.nodes[0].coordinates, Some((1.0, 2.0)));
1952        let NodeType::Tank(tank) = &network.nodes[0].node_type else {
1953            panic!("Expected Tank node type");
1954        };
1955        assert_eq!(tank.elevation, 100.0);
1956        assert_eq!(tank.initial_level, 10.0);
1957        assert_eq!(tank.max_level, 20.0);
1958        assert_eq!(tank.diameter, 50.0);
1959        assert_eq!(network.topology_version, 1);
1960        assert_eq!(network.node_map.get("T1").copied(), Some(0));
1961    }
1962
1963    #[test]
1964    fn test_add_tank_si_units() {
1965        let mut network = Network::new(FlowUnits::CMH, HeadlossFormula::HazenWilliams);
1966        network.add_tank("T1", &test_tank_data(100.0)).unwrap();
1967
1968        // user-provided meters should be stored as feet internally; node and tank
1969        // elevations should stay in sync
1970        assert!((network.nodes[0].elevation - 100.0 / MperFT).abs() < 1e-9);
1971        let NodeType::Tank(tank) = &network.nodes[0].node_type else {
1972            panic!("Expected Tank node type");
1973        };
1974        assert!((tank.elevation - 100.0 / MperFT).abs() < 1e-9);
1975        assert!((tank.initial_level - 10.0 / MperFT).abs() < 1e-9);
1976        assert!((tank.diameter - 50.0 / MperFT).abs() < 1e-9);
1977    }
1978
1979    #[test]
1980    fn test_add_tank_duplicate_id() {
1981        let mut network = Network::default();
1982        network.add_tank("T1", &test_tank_data(100.0)).unwrap();
1983        let err = network.add_tank("T1", &test_tank_data(50.0)).unwrap_err();
1984        assert!(matches!(err, InputError::NodeExists { .. }));
1985    }
1986
1987    #[test]
1988    fn test_add_tank_unknown_volume_curve() {
1989        let mut network = Network::default();
1990        let data = TankData {
1991            volume_curve_id: Some("missing".into()),
1992            ..test_tank_data(100.0)
1993        };
1994        let err = network.add_tank("T1", &data).unwrap_err();
1995        assert!(matches!(err, InputError::CurveNotFound { .. }));
1996        assert_eq!(network.nodes.len(), 0);
1997        assert_eq!(network.topology_version, 0);
1998    }
1999
2000    // --- add_reservoir tests ---
2001
2002    #[test]
2003    fn test_add_reservoir() {
2004        let mut network = Network::default();
2005        let data = ReservoirData {
2006            elevation: 200.0,
2007            head_pattern: None,
2008            coordinates: Some((5.0, 6.0)),
2009        };
2010        network.add_reservoir("R1", &data).unwrap();
2011
2012        assert_eq!(network.nodes.len(), 1);
2013        assert_eq!(network.nodes[0].id, "R1".into());
2014        assert_eq!(network.nodes[0].elevation, 200.0);
2015        assert_eq!(network.nodes[0].coordinates, Some((5.0, 6.0)));
2016        let NodeType::Reservoir(reservoir) = &network.nodes[0].node_type else {
2017            panic!("Expected Reservoir node type");
2018        };
2019        assert!(reservoir.head_pattern.is_none());
2020        assert!(reservoir.head_pattern_index.is_none());
2021        assert_eq!(network.topology_version, 1);
2022    }
2023
2024    #[test]
2025    fn test_add_reservoir_with_head_pattern() {
2026        let mut network = Network::default();
2027        network.patterns.push(Pattern {
2028            id: "P1".into(),
2029            multipliers: vec![1.0, 2.0],
2030        });
2031        network.pattern_map.insert("P1".into(), 0);
2032
2033        let data = ReservoirData {
2034            elevation: 200.0,
2035            head_pattern: Some("P1".into()),
2036            coordinates: None,
2037        };
2038        network.add_reservoir("R1", &data).unwrap();
2039
2040        let NodeType::Reservoir(reservoir) = &network.nodes[0].node_type else {
2041            panic!("Expected Reservoir node type");
2042        };
2043        assert_eq!(reservoir.head_pattern.as_deref(), Some("P1"));
2044        assert_eq!(reservoir.head_pattern_index, Some(0));
2045    }
2046
2047    #[test]
2048    fn test_add_reservoir_si_units() {
2049        let mut network = Network::new(FlowUnits::CMH, HeadlossFormula::HazenWilliams);
2050        let data = ReservoirData {
2051            elevation: 100.0,
2052            head_pattern: None,
2053            coordinates: None,
2054        };
2055        network.add_reservoir("R1", &data).unwrap();
2056        assert!((network.nodes[0].elevation - 100.0 / MperFT).abs() < 1e-9);
2057    }
2058
2059    #[test]
2060    fn test_add_reservoir_unknown_pattern() {
2061        let mut network = Network::default();
2062        let data = ReservoirData {
2063            elevation: 200.0,
2064            head_pattern: Some("missing".into()),
2065            coordinates: None,
2066        };
2067        let err = network.add_reservoir("R1", &data).unwrap_err();
2068        assert!(matches!(err, InputError::PatternNotFound { .. }));
2069        assert_eq!(network.nodes.len(), 0);
2070        assert_eq!(network.topology_version, 0);
2071    }
2072
2073    #[test]
2074    fn test_add_reservoir_duplicate_id() {
2075        let mut network = Network::default();
2076        network
2077            .add_reservoir(
2078                "R1",
2079                &ReservoirData {
2080                    elevation: 100.0,
2081                    head_pattern: None,
2082                    coordinates: None,
2083                },
2084            )
2085            .unwrap();
2086        let err = network
2087            .add_reservoir(
2088                "R1",
2089                &ReservoirData {
2090                    elevation: 50.0,
2091                    head_pattern: None,
2092                    coordinates: None,
2093                },
2094            )
2095            .unwrap_err();
2096        assert!(matches!(err, InputError::NodeExists { .. }));
2097    }
2098
2099    // --- NodeUpdate tests ---
2100
2101    #[test]
2102    fn test_update_node_coordinates_only() {
2103        let mut network = Network::default();
2104        let data = JunctionData {
2105            elevation: 100.0,
2106            demands: demands(0.0, None),
2107            emitter_coefficient: 0.0,
2108            coordinates: None,
2109        };
2110        network.add_junction("J1", &data).unwrap();
2111        let props_before = network.properties_version;
2112
2113        network
2114            .update_node(
2115                "J1",
2116                &NodeUpdate {
2117                    elevation: None,
2118                    coordinates: Some((1.0, 2.0)),
2119                    disabled: None,
2120                },
2121            )
2122            .unwrap();
2123
2124        assert_eq!(network.nodes[0].coordinates, Some((1.0, 2.0)));
2125        assert_eq!(network.nodes[0].elevation, 100.0);
2126        // coordinates are not a solver-relevant property; properties_version should not change
2127        assert_eq!(network.properties_version, props_before);
2128        assert!(network.updated_nodes.is_empty());
2129    }
2130
2131    #[test]
2132    fn test_update_node_elevation() {
2133        let mut network = Network::default();
2134        let data = JunctionData {
2135            elevation: 100.0,
2136            demands: demands(0.0, None),
2137            emitter_coefficient: 0.0,
2138            coordinates: None,
2139        };
2140        network.add_junction("J1", &data).unwrap();
2141
2142        network
2143            .update_node(
2144                "J1",
2145                &NodeUpdate {
2146                    elevation: Some(250.0),
2147                    coordinates: None,
2148                    disabled: None,
2149                },
2150            )
2151            .unwrap();
2152
2153        assert_eq!(network.nodes[0].elevation, 250.0);
2154        assert_eq!(network.properties_version, 1);
2155        assert!(network.updated_nodes.contains(&0));
2156    }
2157
2158    #[test]
2159    fn test_update_node_elevation_keeps_tank_elevation_in_sync() {
2160        let mut network = Network::default();
2161        network.add_node(test_tank_node("T1", 100.0)).unwrap();
2162
2163        network
2164            .update_node(
2165                "T1",
2166                &NodeUpdate {
2167                    elevation: Some(150.0),
2168                    coordinates: None,
2169                    disabled: None,
2170                },
2171            )
2172            .unwrap();
2173
2174        assert_eq!(network.nodes[0].elevation, 150.0);
2175        let NodeType::Tank(tank) = &network.nodes[0].node_type else {
2176            panic!("Expected Tank node type");
2177        };
2178        assert_eq!(tank.elevation, 150.0);
2179    }
2180
2181    #[test]
2182    fn test_update_node_not_found() {
2183        let mut network = Network::default();
2184        let err = network
2185            .update_node(
2186                "missing",
2187                &NodeUpdate {
2188                    elevation: Some(1.0),
2189                    coordinates: None,
2190                    disabled: None,
2191                },
2192            )
2193            .unwrap_err();
2194        assert!(matches!(err, InputError::NodeNotFound { .. }));
2195    }
2196
2197    // --- TankUpdate tests ---
2198
2199    #[test]
2200    fn test_update_tank_all_fields() {
2201        let mut network = Network::default();
2202        network.add_node(test_tank_node("T1", 100.0)).unwrap();
2203        let props_before = network.properties_version;
2204
2205        network
2206            .update_tank(
2207                "T1",
2208                &TankUpdate {
2209                    elevation: Some(120.0),
2210                    coordinates: Some((3.0, 4.0)),
2211                    initial_level: Some(12.0),
2212                    min_level: Some(2.0),
2213                    max_level: Some(25.0),
2214                    diameter: Some(60.0),
2215                    min_volume: Some(5.0),
2216                    overflow: Some(true),
2217                },
2218            )
2219            .unwrap();
2220
2221        let node = &network.nodes[0];
2222        assert_eq!(node.elevation, 120.0);
2223        assert_eq!(node.coordinates, Some((3.0, 4.0)));
2224        let NodeType::Tank(tank) = &node.node_type else {
2225            panic!("Expected Tank node type");
2226        };
2227        assert_eq!(tank.elevation, 120.0);
2228        assert_eq!(tank.initial_level, 12.0);
2229        assert_eq!(tank.min_level, 2.0);
2230        assert_eq!(tank.max_level, 25.0);
2231        assert_eq!(tank.diameter, 60.0);
2232        assert_eq!(tank.min_volume, 5.0);
2233        assert!(tank.overflow);
2234        assert_eq!(network.properties_version, props_before + 1);
2235        assert!(network.updated_nodes.contains(&0));
2236    }
2237
2238    #[test]
2239    fn test_update_tank_partial_leaves_other_fields_unchanged() {
2240        let mut network = Network::default();
2241        network.add_node(test_tank_node("T1", 100.0)).unwrap();
2242
2243        network
2244            .update_tank(
2245                "T1",
2246                &TankUpdate {
2247                    elevation: None,
2248                    coordinates: None,
2249                    initial_level: Some(15.0),
2250                    min_level: None,
2251                    max_level: None,
2252                    diameter: None,
2253                    min_volume: None,
2254                    overflow: None,
2255                },
2256            )
2257            .unwrap();
2258
2259        let NodeType::Tank(tank) = &network.nodes[0].node_type else {
2260            panic!("Expected Tank node type");
2261        };
2262        assert_eq!(tank.initial_level, 15.0);
2263        assert_eq!(tank.min_level, 0.0);
2264        assert_eq!(tank.max_level, 20.0);
2265        assert_eq!(tank.diameter, 50.0);
2266        assert_eq!(network.nodes[0].elevation, 100.0);
2267    }
2268
2269    #[test]
2270    fn test_update_tank_si_units() {
2271        // In CMH / SI, tank levels are stored internally in feet; user values should round-trip.
2272        let mut network = Network::new(FlowUnits::CMH, HeadlossFormula::HazenWilliams);
2273        // add a tank directly in standard (ft) units so we have a known baseline
2274        network
2275            .add_node(test_tank_node("T1", 100.0 / MperFT))
2276            .unwrap();
2277
2278        network
2279            .update_tank(
2280                "T1",
2281                &TankUpdate {
2282                    elevation: Some(50.0),
2283                    coordinates: None,
2284                    initial_level: Some(10.0),
2285                    min_level: Some(0.0),
2286                    max_level: Some(20.0),
2287                    diameter: Some(20.0),
2288                    min_volume: None,
2289                    overflow: None,
2290                },
2291            )
2292            .unwrap();
2293
2294        // user-provided meters should be stored as feet internally
2295        assert!((network.nodes[0].elevation - 50.0 / MperFT).abs() < 1e-9);
2296        let NodeType::Tank(tank) = &network.nodes[0].node_type else {
2297            panic!("Expected Tank node type");
2298        };
2299        assert!((tank.elevation - 50.0 / MperFT).abs() < 1e-9);
2300        assert!((tank.initial_level - 10.0 / MperFT).abs() < 1e-9);
2301        assert!((tank.diameter - 20.0 / MperFT).abs() < 1e-9);
2302    }
2303
2304    #[test]
2305    fn test_update_tank_wrong_node_type() {
2306        let mut network = Network::default();
2307        let data = JunctionData {
2308            elevation: 0.0,
2309            demands: demands(0.0, None),
2310            emitter_coefficient: 0.0,
2311            coordinates: None,
2312        };
2313        network.add_junction("J1", &data).unwrap();
2314
2315        let err = network
2316            .update_tank(
2317                "J1",
2318                &TankUpdate {
2319                    elevation: None,
2320                    coordinates: None,
2321                    initial_level: Some(1.0),
2322                    min_level: None,
2323                    max_level: None,
2324                    diameter: None,
2325                    min_volume: None,
2326                    overflow: None,
2327                },
2328            )
2329            .unwrap_err();
2330        assert!(matches!(err, InputError::NodeNotATank { .. }));
2331    }
2332
2333    #[test]
2334    fn test_update_tank_not_found() {
2335        let mut network = Network::default();
2336        let err = network
2337            .update_tank(
2338                "missing",
2339                &TankUpdate {
2340                    elevation: None,
2341                    coordinates: None,
2342                    initial_level: None,
2343                    min_level: None,
2344                    max_level: None,
2345                    diameter: None,
2346                    min_volume: None,
2347                    overflow: None,
2348                },
2349            )
2350            .unwrap_err();
2351        assert!(matches!(err, InputError::NodeNotFound { .. }));
2352    }
2353
2354    // --- ReservoirUpdate tests ---
2355
2356    #[test]
2357    fn test_update_reservoir_elevation_and_coordinates() {
2358        let mut network = Network::default();
2359        network.add_node(test_reservoir_node("R1", 50.0)).unwrap();
2360        let props_before = network.properties_version;
2361
2362        network
2363            .update_reservoir(
2364                "R1",
2365                &ReservoirUpdate {
2366                    elevation: Some(75.0),
2367                    coordinates: Some((10.0, 20.0)),
2368                    head_pattern: None,
2369                },
2370            )
2371            .unwrap();
2372
2373        assert_eq!(network.nodes[0].elevation, 75.0);
2374        assert_eq!(network.nodes[0].coordinates, Some((10.0, 20.0)));
2375        assert_eq!(network.properties_version, props_before + 1);
2376        assert!(network.updated_nodes.contains(&0));
2377    }
2378
2379    #[test]
2380    fn test_update_reservoir_sets_head_pattern() {
2381        let mut network = Network::default();
2382        network.patterns.push(Pattern {
2383            id: "P1".into(),
2384            multipliers: vec![1.0, 2.0],
2385        });
2386        network.pattern_map.insert("P1".into(), 0);
2387        network.add_node(test_reservoir_node("R1", 50.0)).unwrap();
2388
2389        network
2390            .update_reservoir(
2391                "R1",
2392                &ReservoirUpdate {
2393                    elevation: None,
2394                    coordinates: None,
2395                    head_pattern: Some(Some("P1".into())),
2396                },
2397            )
2398            .unwrap();
2399
2400        let NodeType::Reservoir(reservoir) = &network.nodes[0].node_type else {
2401            panic!("Expected Reservoir node type");
2402        };
2403        assert_eq!(reservoir.head_pattern.as_deref(), Some("P1"));
2404        assert_eq!(reservoir.head_pattern_index, Some(0));
2405    }
2406
2407    #[test]
2408    fn test_update_reservoir_clears_head_pattern() {
2409        let mut network = Network::default();
2410        network.patterns.push(Pattern {
2411            id: "P1".into(),
2412            multipliers: vec![1.0],
2413        });
2414        network.pattern_map.insert("P1".into(), 0);
2415        let mut node = test_reservoir_node("R1", 50.0);
2416        if let NodeType::Reservoir(reservoir) = &mut node.node_type {
2417            reservoir.head_pattern = Some("P1".into());
2418            reservoir.head_pattern_index = Some(0);
2419        }
2420        network.add_node(node).unwrap();
2421
2422        network
2423            .update_reservoir(
2424                "R1",
2425                &ReservoirUpdate {
2426                    elevation: None,
2427                    coordinates: None,
2428                    head_pattern: Some(None),
2429                },
2430            )
2431            .unwrap();
2432
2433        let NodeType::Reservoir(reservoir) = &network.nodes[0].node_type else {
2434            panic!("Expected Reservoir node type");
2435        };
2436        assert!(reservoir.head_pattern.is_none());
2437        assert!(reservoir.head_pattern_index.is_none());
2438    }
2439
2440    #[test]
2441    fn test_update_reservoir_pattern_not_found() {
2442        let mut network = Network::default();
2443        network.add_node(test_reservoir_node("R1", 50.0)).unwrap();
2444
2445        let err = network
2446            .update_reservoir(
2447                "R1",
2448                &ReservoirUpdate {
2449                    elevation: None,
2450                    coordinates: None,
2451                    head_pattern: Some(Some("missing".into())),
2452                },
2453            )
2454            .unwrap_err();
2455        assert!(matches!(err, InputError::PatternNotFound { .. }));
2456    }
2457
2458    #[test]
2459    fn test_update_reservoir_none_head_pattern_leaves_existing_pattern() {
2460        // `head_pattern: None` must be a no-op, not a clear.
2461        let mut network = Network::default();
2462        network.patterns.push(Pattern {
2463            id: "P1".into(),
2464            multipliers: vec![1.0],
2465        });
2466        network.pattern_map.insert("P1".into(), 0);
2467        let mut node = test_reservoir_node("R1", 50.0);
2468        if let NodeType::Reservoir(reservoir) = &mut node.node_type {
2469            reservoir.head_pattern = Some("P1".into());
2470            reservoir.head_pattern_index = Some(0);
2471        }
2472        network.add_node(node).unwrap();
2473
2474        network
2475            .update_reservoir(
2476                "R1",
2477                &ReservoirUpdate {
2478                    elevation: Some(75.0),
2479                    coordinates: None,
2480                    head_pattern: None,
2481                },
2482            )
2483            .unwrap();
2484
2485        let NodeType::Reservoir(reservoir) = &network.nodes[0].node_type else {
2486            panic!("Expected Reservoir node type");
2487        };
2488        assert_eq!(reservoir.head_pattern.as_deref(), Some("P1"));
2489        assert_eq!(reservoir.head_pattern_index, Some(0));
2490        assert!((network.nodes[0].elevation - 75.0).abs() < 1e-9);
2491    }
2492
2493    #[test]
2494    fn test_update_reservoir_wrong_node_type() {
2495        let mut network = Network::default();
2496        let data = JunctionData {
2497            elevation: 0.0,
2498            demands: demands(0.0, None),
2499            emitter_coefficient: 0.0,
2500            coordinates: None,
2501        };
2502        network.add_junction("J1", &data).unwrap();
2503
2504        let err = network
2505            .update_reservoir(
2506                "J1",
2507                &ReservoirUpdate {
2508                    elevation: None,
2509                    coordinates: None,
2510                    head_pattern: None,
2511                },
2512            )
2513            .unwrap_err();
2514        assert!(matches!(err, InputError::NodeNotAReservoir { .. }));
2515    }
2516
2517    #[test]
2518    fn test_update_reservoir_not_found() {
2519        let mut network = Network::default();
2520        let err = network
2521            .update_reservoir(
2522                "missing",
2523                &ReservoirUpdate {
2524                    elevation: None,
2525                    coordinates: None,
2526                    head_pattern: None,
2527                },
2528            )
2529            .unwrap_err();
2530        assert!(matches!(err, InputError::NodeNotFound { .. }));
2531    }
2532
2533    #[test]
2534    fn test_reset_changes_clears_updated_sets() {
2535        let mut network = Network::default();
2536        network.add_node(test_tank_node("T1", 100.0)).unwrap();
2537        network
2538            .update_tank(
2539                "T1",
2540                &TankUpdate {
2541                    elevation: None,
2542                    coordinates: None,
2543                    initial_level: Some(5.0),
2544                    min_level: None,
2545                    max_level: None,
2546                    diameter: None,
2547                    min_volume: None,
2548                    overflow: None,
2549                },
2550            )
2551            .unwrap();
2552        assert!(!network.updated_nodes.is_empty());
2553
2554        network.reset_changes();
2555        assert!(network.updated_nodes.is_empty());
2556        assert!(network.updated_links.is_empty());
2557    }
2558
2559    // --- Link helpers ---
2560
2561    fn add_two_junctions(network: &mut Network) {
2562        for id in ["J1", "J2"] {
2563            network
2564                .add_junction(
2565                    id,
2566                    &JunctionData {
2567                        elevation: 100.0,
2568                        demands: demands(0.0, None),
2569                        emitter_coefficient: 0.0,
2570                        coordinates: None,
2571                    },
2572                )
2573                .unwrap();
2574        }
2575    }
2576
2577    fn sample_pipe_data() -> PipeData {
2578        PipeData {
2579            start_node: "J1".into(),
2580            end_node: "J2".into(),
2581            length: 1000.0,
2582            diameter: 12.0,
2583            roughness: 100.0,
2584            minor_loss: 0.0,
2585            check_valve: false,
2586            initial_status: LinkStatus::Open,
2587            vertices: None,
2588        }
2589    }
2590
2591    // --- add_pipe tests ---
2592
2593    #[test]
2594    fn test_add_pipe_basic() {
2595        let mut network = Network::default();
2596        add_two_junctions(&mut network);
2597        let topo_before = network.topology_version;
2598
2599        network.add_pipe("P1", &sample_pipe_data()).unwrap();
2600
2601        assert_eq!(network.links.len(), 1);
2602        assert_eq!(network.links[0].id, "P1".into());
2603        assert_eq!(network.links[0].start_node, 0);
2604        assert_eq!(network.links[0].end_node, 1);
2605        assert_eq!(network.link_map.get("P1").copied(), Some(0));
2606        // adding a link should bump the topology version
2607        assert_eq!(network.topology_version, topo_before + 1);
2608        let LinkType::Pipe(pipe) = &network.links[0].link_type else {
2609            panic!("Expected Pipe link type");
2610        };
2611        // diameter supplied in inches, stored internally in feet
2612        assert!((pipe.diameter - 1.0).abs() < 1e-9);
2613        assert_eq!(pipe.length, 1000.0);
2614        assert_eq!(pipe.headloss_formula, HeadlossFormula::HazenWilliams);
2615    }
2616
2617    #[test]
2618    fn test_add_pipe_normalizes_minor_loss() {
2619        let mut network = Network::default();
2620        add_two_junctions(&mut network);
2621
2622        network
2623            .add_pipe(
2624                "P1",
2625                &PipeData {
2626                    minor_loss: 2.0,
2627                    ..sample_pipe_data()
2628                },
2629            )
2630            .unwrap();
2631
2632        let LinkType::Pipe(pipe) = &network.links[0].link_type else {
2633            panic!("Expected Pipe link type");
2634        };
2635        // internal representation: 0.02517 * K / d_ft^4 (d = 12in = 1ft)
2636        assert!((pipe.minor_loss - 0.05034).abs() < 1e-6);
2637    }
2638
2639    #[test]
2640    fn test_add_pipe_si_units() {
2641        let mut network = Network::new(FlowUnits::CMH, HeadlossFormula::HazenWilliams);
2642        add_two_junctions(&mut network);
2643
2644        network
2645            .add_pipe(
2646                "P1",
2647                &PipeData {
2648                    length: 1000.0,
2649                    diameter: 300.0, // mm
2650                    ..sample_pipe_data()
2651                },
2652            )
2653            .unwrap();
2654
2655        let LinkType::Pipe(pipe) = &network.links[0].link_type else {
2656            panic!("Expected Pipe link type");
2657        };
2658        // 300 mm -> 0.3 m -> ft
2659        assert!((pipe.diameter - (0.3 / MperFT)).abs() < 1e-9);
2660        assert!((pipe.length - (1000.0 / MperFT)).abs() < 1e-9);
2661    }
2662
2663    #[test]
2664    fn test_add_pipe_unknown_node() {
2665        let mut network = Network::default();
2666        add_two_junctions(&mut network);
2667        let err = network
2668            .add_pipe(
2669                "P1",
2670                &PipeData {
2671                    start_node: "missing".into(),
2672                    ..sample_pipe_data()
2673                },
2674            )
2675            .unwrap_err();
2676        assert!(matches!(err, InputError::NodeNotFound { .. }));
2677        assert_eq!(network.links.len(), 0);
2678    }
2679
2680    #[test]
2681    fn test_add_pipe_duplicate_id() {
2682        let mut network = Network::default();
2683        add_two_junctions(&mut network);
2684        network.add_pipe("P1", &sample_pipe_data()).unwrap();
2685        let err = network.add_pipe("P1", &sample_pipe_data()).unwrap_err();
2686        assert!(matches!(err, InputError::LinkExists { .. }));
2687    }
2688
2689    #[test]
2690    fn test_add_pipe_updates_tank_link_lists() {
2691        let mut network = Network::default();
2692        network.add_node(test_tank_node("T1", 100.0)).unwrap();
2693        add_two_junctions(&mut network);
2694
2695        network
2696            .add_pipe(
2697                "P1",
2698                &PipeData {
2699                    start_node: "J1".into(),
2700                    end_node: "T1".into(),
2701                    ..sample_pipe_data()
2702                },
2703            )
2704            .unwrap();
2705
2706        let NodeType::Tank(tank) = &network.nodes[0].node_type else {
2707            panic!("Expected Tank node type");
2708        };
2709        assert_eq!(tank.links_to, vec![0]);
2710        assert!(tank.links_from.is_empty());
2711    }
2712
2713    // --- add_pump tests ---
2714
2715    fn push_head_curve(network: &mut Network) {
2716        network.curves.push(crate::model::curve::Curve {
2717            id: "C1".into(),
2718            x: vec![0.0, 500.0, 1000.0],
2719            y: vec![100.0, 80.0, 0.0],
2720        });
2721        network.curve_map.insert("C1".into(), 0);
2722    }
2723
2724    #[test]
2725    fn test_add_pump_constant_power() {
2726        let mut network = Network::default();
2727        add_two_junctions(&mut network);
2728
2729        network
2730            .add_pump(
2731                "PU1",
2732                &PumpData {
2733                    start_node: "J1".into(),
2734                    end_node: "J2".into(),
2735                    speed: 1.0,
2736                    head_curve_id: None,
2737                    power: 100.0,
2738                    initial_status: LinkStatus::Open,
2739                    vertices: None,
2740                },
2741            )
2742            .unwrap();
2743
2744        let LinkType::Pump(pump) = &network.links[0].link_type else {
2745            panic!("Expected Pump link type");
2746        };
2747        assert_eq!(pump.speed, 1.0);
2748        assert_eq!(pump.power, 100.0);
2749        assert!(pump.head_curve.is_none());
2750    }
2751
2752    #[test]
2753    fn test_add_pump_with_head_curve() {
2754        let mut network = Network::default();
2755        add_two_junctions(&mut network);
2756        push_head_curve(&mut network);
2757
2758        network
2759            .add_pump(
2760                "PU1",
2761                &PumpData {
2762                    start_node: "J1".into(),
2763                    end_node: "J2".into(),
2764                    speed: 1.0,
2765                    head_curve_id: Some("C1".into()),
2766                    power: 0.0,
2767                    initial_status: LinkStatus::Open,
2768                    vertices: None,
2769                },
2770            )
2771            .unwrap();
2772
2773        let LinkType::Pump(pump) = &network.links[0].link_type else {
2774            panic!("Expected Pump link type");
2775        };
2776        assert_eq!(pump.head_curve_id.as_deref(), Some("C1"));
2777        assert!(pump.head_curve.is_some());
2778    }
2779
2780    #[test]
2781    fn test_add_pump_unknown_curve() {
2782        let mut network = Network::default();
2783        add_two_junctions(&mut network);
2784        let err = network
2785            .add_pump(
2786                "PU1",
2787                &PumpData {
2788                    start_node: "J1".into(),
2789                    end_node: "J2".into(),
2790                    speed: 1.0,
2791                    head_curve_id: Some("missing".into()),
2792                    power: 0.0,
2793                    initial_status: LinkStatus::Open,
2794                    vertices: None,
2795                },
2796            )
2797            .unwrap_err();
2798        assert!(matches!(err, InputError::CurveNotFound { .. }));
2799        assert_eq!(network.links.len(), 0);
2800    }
2801
2802    // --- add_valve tests ---
2803
2804    #[test]
2805    fn test_add_prv_stores_pressure_setting() {
2806        // user adds a PRV with setting 50 psi (US units). Internal setting is
2807        // the pressure expressed in feet of head (no elevation offset — the
2808        // solver adds the anchor-node elevation at the point of use).
2809        let mut network = Network::default();
2810        // J1 at 100 ft, J2 at 200 ft
2811        network
2812            .add_junction(
2813                "J1",
2814                &JunctionData {
2815                    elevation: 100.0,
2816                    demands: demands(0.0, None),
2817                    emitter_coefficient: 0.0,
2818                    coordinates: None,
2819                },
2820            )
2821            .unwrap();
2822        network
2823            .add_junction(
2824                "J2",
2825                &JunctionData {
2826                    elevation: 200.0,
2827                    demands: demands(0.0, None),
2828                    emitter_coefficient: 0.0,
2829                    coordinates: None,
2830                },
2831            )
2832            .unwrap();
2833
2834        network
2835            .add_valve(
2836                "V1",
2837                &ValveData {
2838                    start_node: "J1".into(),
2839                    end_node: "J2".into(),
2840                    diameter: 12.0,
2841                    valve_type: ValveType::PRV,
2842                    setting: 50.0,
2843                    curve_id: None,
2844                    minor_loss: 0.0,
2845                    initial_status: LinkStatus::Active,
2846                    vertices: None,
2847                },
2848            )
2849            .unwrap();
2850
2851        let LinkType::Valve(valve) = &network.links[0].link_type else {
2852            panic!("Expected Valve link type");
2853        };
2854        // 50 psi -> 50 / PSIperFT ft (no elevation offset)
2855        let expected = 50.0 / crate::constants::PSIperFT;
2856        assert!((valve.setting - expected).abs() < 1e-6);
2857        assert!(network.contains_pressure_control_valve);
2858    }
2859
2860    #[test]
2861    fn test_add_tcv_no_elevation_offset() {
2862        let mut network = Network::default();
2863        add_two_junctions(&mut network);
2864
2865        network
2866            .add_valve(
2867                "V1",
2868                &ValveData {
2869                    start_node: "J1".into(),
2870                    end_node: "J2".into(),
2871                    diameter: 12.0,
2872                    valve_type: ValveType::TCV,
2873                    setting: 5.0,
2874                    curve_id: None,
2875                    minor_loss: 0.0,
2876                    initial_status: LinkStatus::Active,
2877                    vertices: None,
2878                },
2879            )
2880            .unwrap();
2881
2882        let LinkType::Valve(valve) = &network.links[0].link_type else {
2883            panic!("Expected Valve link type");
2884        };
2885        assert_eq!(valve.setting, 5.0);
2886        assert!(!network.contains_pressure_control_valve);
2887    }
2888
2889    // --- update_pipe tests ---
2890
2891    #[test]
2892    fn test_update_pipe_fields() {
2893        let mut network = Network::default();
2894        add_two_junctions(&mut network);
2895        network.add_pipe("P1", &sample_pipe_data()).unwrap();
2896        let props_before = network.properties_version;
2897
2898        network
2899            .update_pipe(
2900                "P1",
2901                &PipeUpdate {
2902                    length: Some(500.0),
2903                    diameter: Some(24.0), // inches -> 2 ft
2904                    roughness: Some(120.0),
2905                    minor_loss: Some(3.0),
2906                    check_valve: Some(true),
2907                },
2908            )
2909            .unwrap();
2910
2911        let LinkType::Pipe(pipe) = &network.links[0].link_type else {
2912            panic!("Expected Pipe link type");
2913        };
2914        assert_eq!(pipe.length, 500.0);
2915        assert!((pipe.diameter - 2.0).abs() < 1e-9);
2916        assert_eq!(pipe.roughness, 120.0);
2917        assert!(pipe.check_valve);
2918        // minor_loss = 0.02517 * 3 / 2^4
2919        assert!((pipe.minor_loss - (0.02517 * 3.0 / 16.0)).abs() < 1e-9);
2920        assert_eq!(network.properties_version, props_before + 1);
2921        assert!(network.updated_links.contains(&0));
2922    }
2923
2924    #[test]
2925    fn test_update_pipe_partial_preserves_minor_loss_coefficient() {
2926        let mut network = Network::default();
2927        add_two_junctions(&mut network);
2928        network
2929            .add_pipe(
2930                "P1",
2931                &PipeData {
2932                    minor_loss: 2.0,
2933                    ..sample_pipe_data()
2934                },
2935            )
2936            .unwrap();
2937        let k_expected = 0.02517 * 2.0 / 1.0_f64.powi(4);
2938
2939        // change only the length; K should remain equivalent to 2.0 despite the
2940        // round-trip through convert_from_standard/convert_to_standard
2941        network
2942            .update_pipe(
2943                "P1",
2944                &PipeUpdate {
2945                    length: Some(250.0),
2946                    diameter: None,
2947                    roughness: None,
2948                    minor_loss: None,
2949                    check_valve: None,
2950                },
2951            )
2952            .unwrap();
2953
2954        let LinkType::Pipe(pipe) = &network.links[0].link_type else {
2955            panic!("Expected Pipe link type");
2956        };
2957        assert!((pipe.minor_loss - k_expected).abs() < 1e-9);
2958        assert_eq!(pipe.length, 250.0);
2959    }
2960
2961    #[test]
2962    fn test_update_pipe_wrong_type() {
2963        let mut network = Network::default();
2964        add_two_junctions(&mut network);
2965        network
2966            .add_pump(
2967                "PU1",
2968                &PumpData {
2969                    start_node: "J1".into(),
2970                    end_node: "J2".into(),
2971                    speed: 1.0,
2972                    head_curve_id: None,
2973                    power: 10.0,
2974                    initial_status: LinkStatus::Open,
2975                    vertices: None,
2976                },
2977            )
2978            .unwrap();
2979
2980        let err = network
2981            .update_pipe(
2982                "PU1",
2983                &PipeUpdate {
2984                    length: Some(10.0),
2985                    diameter: None,
2986                    roughness: None,
2987                    minor_loss: None,
2988                    check_valve: None,
2989                },
2990            )
2991            .unwrap_err();
2992        assert!(matches!(err, InputError::LinkNotAPipe { .. }));
2993    }
2994
2995    #[test]
2996    fn test_update_pipe_not_found() {
2997        let mut network = Network::default();
2998        let err = network
2999            .update_pipe(
3000                "missing",
3001                &PipeUpdate {
3002                    length: None,
3003                    diameter: None,
3004                    roughness: None,
3005                    minor_loss: None,
3006                    check_valve: None,
3007                },
3008            )
3009            .unwrap_err();
3010        assert!(matches!(err, InputError::LinkNotFound { .. }));
3011    }
3012
3013    // --- update_pump tests ---
3014
3015    #[test]
3016    fn test_update_pump_speed_and_power() {
3017        let mut network = Network::default();
3018        add_two_junctions(&mut network);
3019        network
3020            .add_pump(
3021                "PU1",
3022                &PumpData {
3023                    start_node: "J1".into(),
3024                    end_node: "J2".into(),
3025                    speed: 1.0,
3026                    head_curve_id: None,
3027                    power: 100.0,
3028                    initial_status: LinkStatus::Open,
3029                    vertices: None,
3030                },
3031            )
3032            .unwrap();
3033
3034        network
3035            .update_pump(
3036                "PU1",
3037                &PumpUpdate {
3038                    speed: Some(1.5),
3039                    power: Some(200.0),
3040                    head_curve_id: None,
3041                },
3042            )
3043            .unwrap();
3044
3045        let LinkType::Pump(pump) = &network.links[0].link_type else {
3046            panic!("Expected Pump link type");
3047        };
3048        assert_eq!(pump.speed, 1.5);
3049        assert_eq!(pump.power, 200.0);
3050        assert!(pump.head_curve_id.is_none());
3051        assert!(pump.head_curve.is_none());
3052    }
3053
3054    #[test]
3055    fn test_update_pump_sets_head_curve() {
3056        let mut network = Network::default();
3057        add_two_junctions(&mut network);
3058        push_head_curve(&mut network);
3059        network
3060            .add_pump(
3061                "PU1",
3062                &PumpData {
3063                    start_node: "J1".into(),
3064                    end_node: "J2".into(),
3065                    speed: 1.0,
3066                    head_curve_id: None,
3067                    power: 10.0,
3068                    initial_status: LinkStatus::Open,
3069                    vertices: None,
3070                },
3071            )
3072            .unwrap();
3073
3074        network
3075            .update_pump(
3076                "PU1",
3077                &PumpUpdate {
3078                    speed: None,
3079                    power: None,
3080                    head_curve_id: Some(Some("C1".into())),
3081                },
3082            )
3083            .unwrap();
3084
3085        let LinkType::Pump(pump) = &network.links[0].link_type else {
3086            panic!("Expected Pump link type");
3087        };
3088        assert_eq!(pump.head_curve_id.as_deref(), Some("C1"));
3089        assert!(pump.head_curve.is_some());
3090    }
3091
3092    #[test]
3093    fn test_update_pump_wrong_type() {
3094        let mut network = Network::default();
3095        add_two_junctions(&mut network);
3096        network.add_pipe("P1", &sample_pipe_data()).unwrap();
3097
3098        let err = network
3099            .update_pump(
3100                "P1",
3101                &PumpUpdate {
3102                    speed: Some(1.0),
3103                    power: None,
3104                    head_curve_id: None,
3105                },
3106            )
3107            .unwrap_err();
3108        assert!(matches!(err, InputError::LinkNotAPump { .. }));
3109    }
3110
3111    #[test]
3112    fn test_update_pump_none_head_curve_leaves_existing_curve() {
3113        // `head_curve_id: None` must be a no-op, not a clear.
3114        let mut network = Network::default();
3115        add_two_junctions(&mut network);
3116        push_head_curve(&mut network);
3117        network
3118            .add_pump(
3119                "PU1",
3120                &PumpData {
3121                    start_node: "J1".into(),
3122                    end_node: "J2".into(),
3123                    speed: 1.0,
3124                    head_curve_id: Some("C1".into()),
3125                    power: 0.0,
3126                    initial_status: LinkStatus::Open,
3127                    vertices: None,
3128                },
3129            )
3130            .unwrap();
3131
3132        network
3133            .update_pump(
3134                "PU1",
3135                &PumpUpdate {
3136                    speed: Some(2.0),
3137                    power: None,
3138                    head_curve_id: None,
3139                },
3140            )
3141            .unwrap();
3142
3143        let LinkType::Pump(pump) = &network.links[0].link_type else {
3144            panic!("Expected Pump link type");
3145        };
3146        assert_eq!(pump.head_curve_id.as_deref(), Some("C1"));
3147        assert!(pump.head_curve.is_some());
3148        assert!((pump.speed - 2.0).abs() < 1e-9);
3149    }
3150
3151    #[test]
3152    fn test_update_pump_clears_head_curve_explicitly() {
3153        let mut network = Network::default();
3154        add_two_junctions(&mut network);
3155        push_head_curve(&mut network);
3156        network
3157            .add_pump(
3158                "PU1",
3159                &PumpData {
3160                    start_node: "J1".into(),
3161                    end_node: "J2".into(),
3162                    speed: 1.0,
3163                    head_curve_id: Some("C1".into()),
3164                    power: 0.0,
3165                    initial_status: LinkStatus::Open,
3166                    vertices: None,
3167                },
3168            )
3169            .unwrap();
3170
3171        network
3172            .update_pump(
3173                "PU1",
3174                &PumpUpdate {
3175                    speed: None,
3176                    power: Some(50.0),
3177                    head_curve_id: Some(None),
3178                },
3179            )
3180            .unwrap();
3181
3182        let LinkType::Pump(pump) = &network.links[0].link_type else {
3183            panic!("Expected Pump link type");
3184        };
3185        assert!(pump.head_curve_id.is_none());
3186        assert!(pump.head_curve.is_none());
3187    }
3188
3189    // --- update_valve tests ---
3190
3191    #[test]
3192    fn test_update_valve_setting_stores_pressure_for_prv() {
3193        let mut network = Network::default();
3194        network
3195            .add_junction(
3196                "J1",
3197                &JunctionData {
3198                    elevation: 100.0,
3199                    demands: demands(0.0, None),
3200                    emitter_coefficient: 0.0,
3201                    coordinates: None,
3202                },
3203            )
3204            .unwrap();
3205        network
3206            .add_junction(
3207                "J2",
3208                &JunctionData {
3209                    elevation: 200.0,
3210                    demands: demands(0.0, None),
3211                    emitter_coefficient: 0.0,
3212                    coordinates: None,
3213                },
3214            )
3215            .unwrap();
3216        network
3217            .add_valve(
3218                "V1",
3219                &ValveData {
3220                    start_node: "J1".into(),
3221                    end_node: "J2".into(),
3222                    diameter: 12.0,
3223                    valve_type: ValveType::PRV,
3224                    setting: 50.0,
3225                    curve_id: None,
3226                    minor_loss: 0.0,
3227                    initial_status: LinkStatus::Active,
3228                    vertices: None,
3229                },
3230            )
3231            .unwrap();
3232
3233        network
3234            .update_valve(
3235                "V1",
3236                &ValveUpdate {
3237                    diameter: None,
3238                    setting: Some(80.0),
3239                    minor_loss: None,
3240                    curve_id: None,
3241                    valve_type: None,
3242                },
3243            )
3244            .unwrap();
3245
3246        let LinkType::Valve(valve) = &network.links[0].link_type else {
3247            panic!("Expected Valve link type");
3248        };
3249        // 80 psi expressed in feet of head, no elevation offset
3250        let expected = 80.0 / crate::constants::PSIperFT;
3251        assert!((valve.setting - expected).abs() < 1e-6);
3252    }
3253
3254    #[test]
3255    fn test_update_valve_diameter_preserves_prv_setting_semantics() {
3256        // If only the diameter is updated, the PRV setting (user-facing pressure)
3257        // should round-trip unchanged.
3258        let mut network = Network::default();
3259        network
3260            .add_junction(
3261                "J1",
3262                &JunctionData {
3263                    elevation: 100.0,
3264                    demands: demands(0.0, None),
3265                    emitter_coefficient: 0.0,
3266                    coordinates: None,
3267                },
3268            )
3269            .unwrap();
3270        network
3271            .add_junction(
3272                "J2",
3273                &JunctionData {
3274                    elevation: 200.0,
3275                    demands: demands(0.0, None),
3276                    emitter_coefficient: 0.0,
3277                    coordinates: None,
3278                },
3279            )
3280            .unwrap();
3281        network
3282            .add_valve(
3283                "V1",
3284                &ValveData {
3285                    start_node: "J1".into(),
3286                    end_node: "J2".into(),
3287                    diameter: 12.0,
3288                    valve_type: ValveType::PRV,
3289                    setting: 50.0,
3290                    curve_id: None,
3291                    minor_loss: 0.0,
3292                    initial_status: LinkStatus::Active,
3293                    vertices: None,
3294                },
3295            )
3296            .unwrap();
3297        let setting_before = if let LinkType::Valve(valve) = &network.links[0].link_type {
3298            valve.setting
3299        } else {
3300            unreachable!()
3301        };
3302
3303        network
3304            .update_valve(
3305                "V1",
3306                &ValveUpdate {
3307                    diameter: Some(24.0),
3308                    setting: None,
3309                    minor_loss: None,
3310                    curve_id: None,
3311                    valve_type: None,
3312                },
3313            )
3314            .unwrap();
3315
3316        let LinkType::Valve(valve) = &network.links[0].link_type else {
3317            panic!("Expected Valve link type");
3318        };
3319        assert!((valve.setting - setting_before).abs() < 1e-9);
3320        assert!((valve.diameter - 2.0).abs() < 1e-9);
3321    }
3322
3323    #[test]
3324    fn test_update_valve_wrong_type() {
3325        let mut network = Network::default();
3326        add_two_junctions(&mut network);
3327        network.add_pipe("P1", &sample_pipe_data()).unwrap();
3328        let err = network
3329            .update_valve(
3330                "P1",
3331                &ValveUpdate {
3332                    diameter: None,
3333                    setting: None,
3334                    minor_loss: None,
3335                    curve_id: None,
3336                    valve_type: None,
3337                },
3338            )
3339            .unwrap_err();
3340        assert!(matches!(err, InputError::LinkNotAValve { .. }));
3341    }
3342
3343    #[test]
3344    fn test_update_valve_type_change_requires_setting() {
3345        let mut network = Network::default();
3346        add_two_junctions(&mut network);
3347        network
3348            .add_valve(
3349                "V1",
3350                &ValveData {
3351                    start_node: "J1".into(),
3352                    end_node: "J2".into(),
3353                    diameter: 12.0,
3354                    valve_type: ValveType::TCV,
3355                    setting: 5.0,
3356                    curve_id: None,
3357                    minor_loss: 0.0,
3358                    initial_status: LinkStatus::Active,
3359                    vertices: None,
3360                },
3361            )
3362            .unwrap();
3363
3364        let err = network
3365            .update_valve(
3366                "V1",
3367                &ValveUpdate {
3368                    diameter: None,
3369                    setting: None,
3370                    minor_loss: None,
3371                    curve_id: None,
3372                    valve_type: Some(ValveType::PRV),
3373                },
3374            )
3375            .unwrap_err();
3376        assert!(matches!(err, InputError::Parse { .. }));
3377    }
3378
3379    #[test]
3380    fn test_update_valve_type_change_to_gpv_requires_curve() {
3381        let mut network = Network::default();
3382        add_two_junctions(&mut network);
3383        network
3384            .add_valve(
3385                "V1",
3386                &ValveData {
3387                    start_node: "J1".into(),
3388                    end_node: "J2".into(),
3389                    diameter: 12.0,
3390                    valve_type: ValveType::TCV,
3391                    setting: 5.0,
3392                    curve_id: None,
3393                    minor_loss: 0.0,
3394                    initial_status: LinkStatus::Active,
3395                    vertices: None,
3396                },
3397            )
3398            .unwrap();
3399
3400        let err = network
3401            .update_valve(
3402                "V1",
3403                &ValveUpdate {
3404                    diameter: None,
3405                    setting: Some(0.0),
3406                    minor_loss: None,
3407                    curve_id: None,
3408                    valve_type: Some(ValveType::GPV),
3409                },
3410            )
3411            .unwrap_err();
3412        assert!(matches!(err, InputError::Parse { .. }));
3413    }
3414
3415    #[test]
3416    fn test_update_valve_gpv_cannot_clear_curve() {
3417        // `Some(None)` on a GPV valve must be rejected — GPVs always need a curve.
3418        let mut network = Network::default();
3419        add_two_junctions(&mut network);
3420        push_head_curve(&mut network);
3421        network
3422            .add_valve(
3423                "V1",
3424                &ValveData {
3425                    start_node: "J1".into(),
3426                    end_node: "J2".into(),
3427                    diameter: 12.0,
3428                    valve_type: ValveType::GPV,
3429                    setting: 0.0,
3430                    curve_id: Some("C1".into()),
3431                    minor_loss: 0.0,
3432                    initial_status: LinkStatus::Active,
3433                    vertices: None,
3434                },
3435            )
3436            .unwrap();
3437
3438        let err = network
3439            .update_valve(
3440                "V1",
3441                &ValveUpdate {
3442                    diameter: None,
3443                    setting: None,
3444                    minor_loss: None,
3445                    curve_id: Some(None),
3446                    valve_type: None,
3447                },
3448            )
3449            .unwrap_err();
3450        assert!(matches!(err, InputError::Parse { .. }));
3451    }
3452
3453    #[test]
3454    fn test_update_valve_gpv_none_curve_leaves_existing_curve() {
3455        // `curve_id: None` on a GPV valve without changing the type keeps the curve.
3456        let mut network = Network::default();
3457        add_two_junctions(&mut network);
3458        push_head_curve(&mut network);
3459        network
3460            .add_valve(
3461                "V1",
3462                &ValveData {
3463                    start_node: "J1".into(),
3464                    end_node: "J2".into(),
3465                    diameter: 12.0,
3466                    valve_type: ValveType::GPV,
3467                    setting: 0.0,
3468                    curve_id: Some("C1".into()),
3469                    minor_loss: 0.0,
3470                    initial_status: LinkStatus::Active,
3471                    vertices: None,
3472                },
3473            )
3474            .unwrap();
3475
3476        network
3477            .update_valve(
3478                "V1",
3479                &ValveUpdate {
3480                    diameter: Some(10.0),
3481                    setting: None,
3482                    minor_loss: None,
3483                    curve_id: None,
3484                    valve_type: None,
3485                },
3486            )
3487            .unwrap();
3488
3489        let LinkType::Valve(valve) = &network.links[0].link_type else {
3490            panic!("Expected Valve link type");
3491        };
3492        assert_eq!(valve.curve_id.as_deref(), Some("C1"));
3493        assert!(valve.gpv_curve.is_some());
3494        assert!(valve.pcv_curve.is_none());
3495    }
3496
3497    #[test]
3498    fn test_update_valve_tcv_none_curve_leaves_curve_none() {
3499        // Non-GPV case: `curve_id: None` is a no-op even when no curve is set.
3500        let mut network = Network::default();
3501        add_two_junctions(&mut network);
3502        network
3503            .add_valve(
3504                "V1",
3505                &ValveData {
3506                    start_node: "J1".into(),
3507                    end_node: "J2".into(),
3508                    diameter: 12.0,
3509                    valve_type: ValveType::TCV,
3510                    setting: 5.0,
3511                    curve_id: None,
3512                    minor_loss: 0.0,
3513                    initial_status: LinkStatus::Active,
3514                    vertices: None,
3515                },
3516            )
3517            .unwrap();
3518
3519        network
3520            .update_valve(
3521                "V1",
3522                &ValveUpdate {
3523                    diameter: None,
3524                    setting: Some(10.0),
3525                    minor_loss: None,
3526                    curve_id: None,
3527                    valve_type: None,
3528                },
3529            )
3530            .unwrap();
3531
3532        let LinkType::Valve(valve) = &network.links[0].link_type else {
3533            panic!("Expected Valve link type");
3534        };
3535        assert!(valve.curve_id.is_none());
3536        assert!(valve.gpv_curve.is_none());
3537        assert!(valve.pcv_curve.is_none());
3538    }
3539
3540    #[test]
3541    fn test_update_valve_type_change_tcv_to_prv_stores_pressure_setting() {
3542        let mut network = Network::default();
3543        network
3544            .add_junction(
3545                "J1",
3546                &JunctionData {
3547                    elevation: 100.0,
3548                    demands: demands(0.0, None),
3549                    emitter_coefficient: 0.0,
3550                    coordinates: None,
3551                },
3552            )
3553            .unwrap();
3554        network
3555            .add_junction(
3556                "J2",
3557                &JunctionData {
3558                    elevation: 200.0,
3559                    demands: demands(0.0, None),
3560                    emitter_coefficient: 0.0,
3561                    coordinates: None,
3562                },
3563            )
3564            .unwrap();
3565        network
3566            .add_valve(
3567                "V1",
3568                &ValveData {
3569                    start_node: "J1".into(),
3570                    end_node: "J2".into(),
3571                    diameter: 12.0,
3572                    valve_type: ValveType::TCV,
3573                    setting: 5.0,
3574                    curve_id: None,
3575                    minor_loss: 0.0,
3576                    initial_status: LinkStatus::Active,
3577                    vertices: None,
3578                },
3579            )
3580            .unwrap();
3581        assert!(!network.contains_pressure_control_valve);
3582
3583        network
3584            .update_valve(
3585                "V1",
3586                &ValveUpdate {
3587                    diameter: None,
3588                    setting: Some(50.0),
3589                    minor_loss: None,
3590                    curve_id: None,
3591                    valve_type: Some(ValveType::PRV),
3592                },
3593            )
3594            .unwrap();
3595
3596        let LinkType::Valve(valve) = &network.links[0].link_type else {
3597            panic!("Expected Valve link type");
3598        };
3599        assert_eq!(valve.valve_type, ValveType::PRV);
3600        // 50 psi expressed in feet of head (no elevation offset)
3601        let expected = 50.0 / crate::constants::PSIperFT;
3602        assert!((valve.setting - expected).abs() < 1e-6);
3603        assert!(network.contains_pressure_control_valve);
3604    }
3605
3606    #[test]
3607    fn test_update_valve_type_change_prv_to_tcv_clears_flag_and_offset() {
3608        let mut network = Network::default();
3609        network
3610            .add_junction(
3611                "J1",
3612                &JunctionData {
3613                    elevation: 100.0,
3614                    demands: demands(0.0, None),
3615                    emitter_coefficient: 0.0,
3616                    coordinates: None,
3617                },
3618            )
3619            .unwrap();
3620        network
3621            .add_junction(
3622                "J2",
3623                &JunctionData {
3624                    elevation: 200.0,
3625                    demands: demands(0.0, None),
3626                    emitter_coefficient: 0.0,
3627                    coordinates: None,
3628                },
3629            )
3630            .unwrap();
3631        network
3632            .add_valve(
3633                "V1",
3634                &ValveData {
3635                    start_node: "J1".into(),
3636                    end_node: "J2".into(),
3637                    diameter: 12.0,
3638                    valve_type: ValveType::PRV,
3639                    setting: 50.0,
3640                    curve_id: None,
3641                    minor_loss: 0.0,
3642                    initial_status: LinkStatus::Active,
3643                    vertices: None,
3644                },
3645            )
3646            .unwrap();
3647        assert!(network.contains_pressure_control_valve);
3648
3649        network
3650            .update_valve(
3651                "V1",
3652                &ValveUpdate {
3653                    diameter: None,
3654                    setting: Some(5.0),
3655                    minor_loss: None,
3656                    curve_id: None,
3657                    valve_type: Some(ValveType::TCV),
3658                },
3659            )
3660            .unwrap();
3661
3662        let LinkType::Valve(valve) = &network.links[0].link_type else {
3663            panic!("Expected Valve link type");
3664        };
3665        assert_eq!(valve.valve_type, ValveType::TCV);
3666        // TCV settings are stored verbatim (no PSI->ft or elevation offset)
3667        assert_eq!(valve.setting, 5.0);
3668        assert!(!network.contains_pressure_control_valve);
3669    }
3670
3671    // --- update_link tests ---
3672
3673    #[test]
3674    fn test_update_link_vertices_and_status() {
3675        let mut network = Network::default();
3676        add_two_junctions(&mut network);
3677        network.add_pipe("P1", &sample_pipe_data()).unwrap();
3678        let topo_before = network.topology_version;
3679        let props_before = network.properties_version;
3680
3681        network
3682            .update_link(
3683                "P1",
3684                &LinkUpdate {
3685                    start_node: None,
3686                    end_node: None,
3687                    vertices: Some(vec![(1.0, 2.0), (3.0, 4.0)]),
3688                    initial_status: Some(LinkStatus::Closed),
3689                },
3690            )
3691            .unwrap();
3692
3693        assert_eq!(
3694            network.links[0].vertices.as_deref().unwrap(),
3695            &[(1.0, 2.0), (3.0, 4.0)]
3696        );
3697        assert_eq!(network.links[0].initial_status, LinkStatus::Closed);
3698        // vertices alone are visual; status bumps properties_version
3699        assert_eq!(network.topology_version, topo_before);
3700        assert_eq!(network.properties_version, props_before + 1);
3701        assert!(network.updated_links.contains(&0));
3702    }
3703
3704    #[test]
3705    fn test_update_link_swap_endpoints_bumps_topology() {
3706        let mut network = Network::default();
3707        add_two_junctions(&mut network);
3708        network
3709            .add_junction(
3710                "J3",
3711                &JunctionData {
3712                    elevation: 100.0,
3713                    demands: demands(0.0, None),
3714                    emitter_coefficient: 0.0,
3715                    coordinates: None,
3716                },
3717            )
3718            .unwrap();
3719        network.add_pipe("P1", &sample_pipe_data()).unwrap();
3720        let topo_before = network.topology_version;
3721
3722        network
3723            .update_link(
3724                "P1",
3725                &LinkUpdate {
3726                    start_node: None,
3727                    end_node: Some("J3".into()),
3728                    vertices: None,
3729                    initial_status: None,
3730                },
3731            )
3732            .unwrap();
3733
3734        assert_eq!(network.links[0].end_node, 2);
3735        assert_eq!(network.links[0].end_node_id, "J3".into());
3736        assert_eq!(network.topology_version, topo_before + 1);
3737    }
3738
3739    #[test]
3740    fn test_update_link_moves_tank_link_list_entry() {
3741        let mut network = Network::default();
3742        network.add_node(test_tank_node("T1", 100.0)).unwrap();
3743        network.add_node(test_tank_node("T2", 100.0)).unwrap();
3744        network
3745            .add_junction(
3746                "J1",
3747                &JunctionData {
3748                    elevation: 0.0,
3749                    demands: demands(0.0, None),
3750                    emitter_coefficient: 0.0,
3751                    coordinates: None,
3752                },
3753            )
3754            .unwrap();
3755
3756        network
3757            .add_pipe(
3758                "P1",
3759                &PipeData {
3760                    start_node: "J1".into(),
3761                    end_node: "T1".into(),
3762                    ..sample_pipe_data()
3763                },
3764            )
3765            .unwrap();
3766
3767        network
3768            .update_link(
3769                "P1",
3770                &LinkUpdate {
3771                    start_node: None,
3772                    end_node: Some("T2".into()),
3773                    vertices: None,
3774                    initial_status: None,
3775                },
3776            )
3777            .unwrap();
3778
3779        let NodeType::Tank(t1) = &network.nodes[0].node_type else {
3780            panic!();
3781        };
3782        let NodeType::Tank(t2) = &network.nodes[1].node_type else {
3783            panic!();
3784        };
3785        assert!(
3786            t1.links_to.is_empty(),
3787            "T1 should no longer be a destination"
3788        );
3789        assert_eq!(t2.links_to, vec![0], "T2 should now be a destination");
3790    }
3791
3792    #[test]
3793    fn test_update_link_unknown_node() {
3794        let mut network = Network::default();
3795        add_two_junctions(&mut network);
3796        network.add_pipe("P1", &sample_pipe_data()).unwrap();
3797        let err = network
3798            .update_link(
3799                "P1",
3800                &LinkUpdate {
3801                    start_node: Some("missing".into()),
3802                    end_node: None,
3803                    vertices: None,
3804                    initial_status: None,
3805                },
3806            )
3807            .unwrap_err();
3808        assert!(matches!(err, InputError::NodeNotFound { .. }));
3809    }
3810
3811    #[test]
3812    fn test_update_link_not_found() {
3813        let mut network = Network::default();
3814        let err = network
3815            .update_link(
3816                "missing",
3817                &LinkUpdate {
3818                    start_node: None,
3819                    end_node: None,
3820                    vertices: None,
3821                    initial_status: None,
3822                },
3823            )
3824            .unwrap_err();
3825        assert!(matches!(err, InputError::LinkNotFound { .. }));
3826    }
3827
3828    // --- remove_link tests ---
3829
3830    #[test]
3831    fn test_remove_link_basic() {
3832        let mut network = Network::default();
3833        add_two_junctions(&mut network);
3834        network.add_pipe("P1", &sample_pipe_data()).unwrap();
3835        let topo_before = network.topology_version;
3836
3837        network.remove_link("P1", false).unwrap();
3838
3839        assert_eq!(network.links.len(), 0);
3840        assert!(network.link_map.get("P1").is_none());
3841        assert_eq!(network.topology_version, topo_before + 1);
3842    }
3843
3844    #[test]
3845    fn test_remove_link_reindexes_link_map_after_swap() {
3846        let mut network = Network::default();
3847        add_two_junctions(&mut network);
3848        network.add_pipe("P1", &sample_pipe_data()).unwrap();
3849        network.add_pipe("P2", &sample_pipe_data()).unwrap();
3850        network.add_pipe("P3", &sample_pipe_data()).unwrap();
3851
3852        // remove the middle link; swap_remove puts P3 into slot 1
3853        network.remove_link("P2", false).unwrap();
3854
3855        assert_eq!(network.links.len(), 2);
3856        assert_eq!(network.link_map.get("P1").copied(), Some(0));
3857        assert_eq!(network.link_map.get("P3").copied(), Some(1));
3858        assert!(network.link_map.get("P2").is_none());
3859        assert_eq!(network.links[1].id, "P3".into());
3860    }
3861
3862    #[test]
3863    fn test_remove_link_detaches_tank_links() {
3864        let mut network = Network::default();
3865        network.add_node(test_tank_node("T1", 100.0)).unwrap();
3866        add_two_junctions(&mut network);
3867
3868        network
3869            .add_pipe(
3870                "P1",
3871                &PipeData {
3872                    start_node: "J1".into(),
3873                    end_node: "T1".into(),
3874                    ..sample_pipe_data()
3875                },
3876            )
3877            .unwrap();
3878
3879        network.remove_link("P1", false).unwrap();
3880
3881        let NodeType::Tank(tank) = &network.nodes[0].node_type else {
3882            panic!("Expected Tank node type");
3883        };
3884        assert!(tank.links_to.is_empty());
3885        assert!(tank.links_from.is_empty());
3886    }
3887
3888    #[test]
3889    fn test_remove_link_retargets_moved_link_in_tank_lists() {
3890        // Two tank-terminating pipes; remove the first so swap_remove moves
3891        // the last one into slot 0 and the tank lists must be retargeted.
3892        let mut network = Network::default();
3893        network.add_node(test_tank_node("T1", 100.0)).unwrap();
3894        add_two_junctions(&mut network);
3895
3896        network
3897            .add_pipe(
3898                "P1",
3899                &PipeData {
3900                    start_node: "J1".into(),
3901                    end_node: "T1".into(),
3902                    ..sample_pipe_data()
3903                },
3904            )
3905            .unwrap();
3906        network
3907            .add_pipe(
3908                "P2",
3909                &PipeData {
3910                    start_node: "J2".into(),
3911                    end_node: "T1".into(),
3912                    ..sample_pipe_data()
3913                },
3914            )
3915            .unwrap();
3916
3917        network.remove_link("P1", false).unwrap();
3918
3919        let NodeType::Tank(tank) = &network.nodes[0].node_type else {
3920            panic!("Expected Tank node type");
3921        };
3922        // P2 is now at index 0
3923        assert_eq!(tank.links_to, vec![0]);
3924        assert_eq!(network.links[0].id, "P2".into());
3925    }
3926
3927    #[test]
3928    fn test_remove_link_clears_pressure_control_flag() {
3929        let mut network = Network::default();
3930        add_two_junctions(&mut network);
3931        network
3932            .add_valve(
3933                "V1",
3934                &ValveData {
3935                    start_node: "J1".into(),
3936                    end_node: "J2".into(),
3937                    diameter: 12.0,
3938                    valve_type: ValveType::PRV,
3939                    setting: 50.0,
3940                    curve_id: None,
3941                    minor_loss: 0.0,
3942                    initial_status: LinkStatus::Active,
3943                    vertices: None,
3944                },
3945            )
3946            .unwrap();
3947        assert!(network.contains_pressure_control_valve);
3948
3949        network.remove_link("V1", false).unwrap();
3950        assert!(!network.contains_pressure_control_valve);
3951    }
3952
3953    #[test]
3954    fn test_remove_link_referenced_by_control_fails() {
3955        use crate::model::control::{Control, ControlCondition};
3956        let mut network = Network::default();
3957        add_two_junctions(&mut network);
3958        network.add_pipe("P1", &sample_pipe_data()).unwrap();
3959        network.controls.push(Control {
3960            condition: ControlCondition::Time { seconds: 0 },
3961            link_id: "P1".into(),
3962            setting: None,
3963            status: Some(LinkStatus::Closed),
3964        });
3965
3966        let err = network.remove_link("P1", false).unwrap_err();
3967        assert!(matches!(err, InputError::Parse { .. }));
3968        assert_eq!(network.links.len(), 1);
3969    }
3970
3971    #[test]
3972    fn test_remove_link_not_found() {
3973        let mut network = Network::default();
3974        let err = network.remove_link("missing", false).unwrap_err();
3975        assert!(matches!(err, InputError::LinkNotFound { .. }));
3976    }
3977
3978    // --- remove_node tests ---
3979
3980    #[test]
3981    fn test_remove_node_basic() {
3982        let mut network = Network::default();
3983        network
3984            .add_junction(
3985                "J1",
3986                &JunctionData {
3987                    elevation: 0.0,
3988                    demands: demands(0.0, None),
3989                    emitter_coefficient: 0.0,
3990                    coordinates: None,
3991                },
3992            )
3993            .unwrap();
3994        let topo_before = network.topology_version;
3995
3996        network.remove_node("J1", false).unwrap();
3997
3998        assert_eq!(network.nodes.len(), 0);
3999        assert!(network.node_map.get("J1").is_none());
4000        assert_eq!(network.topology_version, topo_before + 1);
4001    }
4002
4003    #[test]
4004    fn test_remove_node_reindexes_links_after_swap() {
4005        // J1, J2, J3 with a pipe J1->J3. Remove J2; J3 is swapped into slot 1
4006        // and the pipe's end_node index must follow.
4007        let mut network = Network::default();
4008        add_two_junctions(&mut network);
4009        network
4010            .add_junction(
4011                "J3",
4012                &JunctionData {
4013                    elevation: 0.0,
4014                    demands: demands(0.0, None),
4015                    emitter_coefficient: 0.0,
4016                    coordinates: None,
4017                },
4018            )
4019            .unwrap();
4020        network
4021            .add_pipe(
4022                "P1",
4023                &PipeData {
4024                    start_node: "J1".into(),
4025                    end_node: "J3".into(),
4026                    ..sample_pipe_data()
4027                },
4028            )
4029            .unwrap();
4030
4031        network.remove_node("J2", false).unwrap();
4032
4033        assert_eq!(network.nodes.len(), 2);
4034        assert_eq!(network.node_map.get("J1").copied(), Some(0));
4035        assert_eq!(network.node_map.get("J3").copied(), Some(1));
4036        assert_eq!(network.links[0].start_node, 0);
4037        assert_eq!(network.links[0].end_node, 1);
4038    }
4039
4040    #[test]
4041    fn test_remove_node_cascade_removes_connected_links() {
4042        // J1 -P1- J2 -P2- J3 and a stray P3 (J1 -> J3). Removing J1 should
4043        // cascade-remove P1 and P3 but leave P2 alone.
4044        let mut network = Network::default();
4045        add_two_junctions(&mut network);
4046        network
4047            .add_junction(
4048                "J3",
4049                &JunctionData {
4050                    elevation: 0.0,
4051                    demands: demands(0.0, None),
4052                    emitter_coefficient: 0.0,
4053                    coordinates: None,
4054                },
4055            )
4056            .unwrap();
4057        network.add_pipe("P1", &sample_pipe_data()).unwrap();
4058        network
4059            .add_pipe(
4060                "P2",
4061                &PipeData {
4062                    start_node: "J2".into(),
4063                    end_node: "J3".into(),
4064                    ..sample_pipe_data()
4065                },
4066            )
4067            .unwrap();
4068        network
4069            .add_pipe(
4070                "P3",
4071                &PipeData {
4072                    start_node: "J1".into(),
4073                    end_node: "J3".into(),
4074                    ..sample_pipe_data()
4075                },
4076            )
4077            .unwrap();
4078
4079        network.remove_node("J1", false).unwrap();
4080
4081        assert_eq!(network.nodes.len(), 2);
4082        assert!(network.node_map.get("J1").is_none());
4083        assert_eq!(network.links.len(), 1);
4084        assert!(network.link_map.get("P1").is_none());
4085        assert!(network.link_map.get("P3").is_none());
4086        assert!(network.link_map.get("P2").is_some());
4087    }
4088
4089    #[test]
4090    fn test_remove_node_cascade_fails_if_link_referenced_by_control() {
4091        use crate::model::control::{Control, ControlCondition};
4092        let mut network = Network::default();
4093        add_two_junctions(&mut network);
4094        network.add_pipe("P1", &sample_pipe_data()).unwrap();
4095        network.controls.push(Control {
4096            condition: ControlCondition::Time { seconds: 0 },
4097            link_id: "P1".into(),
4098            setting: None,
4099            status: Some(LinkStatus::Closed),
4100        });
4101        let err = network.remove_node("J1", false).unwrap_err();
4102        assert!(matches!(err, InputError::Parse { .. }));
4103    }
4104
4105    #[test]
4106    fn test_remove_node_referenced_by_control_fails() {
4107        use crate::model::control::{Control, ControlCondition};
4108        let mut network = Network::default();
4109        network
4110            .add_junction(
4111                "J1",
4112                &JunctionData {
4113                    elevation: 0.0,
4114                    demands: demands(0.0, None),
4115                    emitter_coefficient: 0.0,
4116                    coordinates: None,
4117                },
4118            )
4119            .unwrap();
4120        network.controls.push(Control {
4121            condition: ControlCondition::HighPressure {
4122                node_index: 0,
4123                target: 50.0,
4124            },
4125            link_id: "dummy".into(),
4126            setting: None,
4127            status: Some(LinkStatus::Closed),
4128        });
4129
4130        let err = network.remove_node("J1", false).unwrap_err();
4131        assert!(matches!(err, InputError::Parse { .. }));
4132    }
4133
4134    #[test]
4135    fn test_remove_node_reindexes_control_node_index() {
4136        use crate::model::control::{Control, ControlCondition};
4137        let mut network = Network::default();
4138        network
4139            .add_junction(
4140                "J1",
4141                &JunctionData {
4142                    elevation: 0.0,
4143                    demands: demands(0.0, None),
4144                    emitter_coefficient: 0.0,
4145                    coordinates: None,
4146                },
4147            )
4148            .unwrap();
4149        network
4150            .add_junction(
4151                "J2",
4152                &JunctionData {
4153                    elevation: 0.0,
4154                    demands: demands(0.0, None),
4155                    emitter_coefficient: 0.0,
4156                    coordinates: None,
4157                },
4158            )
4159            .unwrap();
4160        // control targets J2 (index 1)
4161        network.controls.push(Control {
4162            condition: ControlCondition::HighPressure {
4163                node_index: 1,
4164                target: 50.0,
4165            },
4166            link_id: "dummy".into(),
4167            setting: None,
4168            status: Some(LinkStatus::Closed),
4169        });
4170
4171        // remove J1 (index 0); J2 gets swapped into slot 0, control must follow
4172        network.remove_node("J1", false).unwrap();
4173
4174        let ControlCondition::HighPressure { node_index, .. } = network.controls[0].condition
4175        else {
4176            panic!("expected HighPressure control");
4177        };
4178        assert_eq!(node_index, 0);
4179    }
4180
4181    #[test]
4182    fn test_remove_node_unconditional_drops_referencing_controls() {
4183        use crate::model::control::{Control, ControlCondition};
4184        let mut network = Network::default();
4185        add_two_junctions(&mut network);
4186        // unrelated control on J2 (index 1) must survive and get reindexed to 0
4187        network.controls.push(Control {
4188            condition: ControlCondition::HighPressure {
4189                node_index: 1,
4190                target: 50.0,
4191            },
4192            link_id: "dummy".into(),
4193            setting: None,
4194            status: Some(LinkStatus::Closed),
4195        });
4196        // two controls (HighPressure + LowPressure) targeting J1 must be dropped
4197        network.controls.push(Control {
4198            condition: ControlCondition::HighPressure {
4199                node_index: 0,
4200                target: 60.0,
4201            },
4202            link_id: "dummy".into(),
4203            setting: None,
4204            status: Some(LinkStatus::Closed),
4205        });
4206        network.controls.push(Control {
4207            condition: ControlCondition::LowPressure {
4208                node_index: 0,
4209                target: 10.0,
4210            },
4211            link_id: "dummy".into(),
4212            setting: None,
4213            status: Some(LinkStatus::Open),
4214        });
4215
4216        network.remove_node("J1", true).unwrap();
4217
4218        // only the J2-targeting control remains; its node_index is reindexed
4219        // from 1 to 0 because swap_remove moved J2 into J1's old slot.
4220        assert_eq!(network.controls.len(), 1);
4221        let ControlCondition::HighPressure { node_index, .. } = network.controls[0].condition
4222        else {
4223            panic!("expected HighPressure control");
4224        };
4225        assert_eq!(node_index, 0);
4226    }
4227
4228    #[test]
4229    fn test_remove_node_unconditional_drops_tank_level_controls() {
4230        use crate::model::control::{Control, ControlCondition};
4231        let mut network = Network::default();
4232        network.add_node(test_tank_node("T1", 100.0)).unwrap();
4233        network.controls.push(Control {
4234            condition: ControlCondition::HighLevel {
4235                tank_index: 0,
4236                target: 20.0,
4237            },
4238            link_id: "dummy".into(),
4239            setting: None,
4240            status: Some(LinkStatus::Closed),
4241        });
4242        network.controls.push(Control {
4243            condition: ControlCondition::LowLevel {
4244                tank_index: 0,
4245                target: 2.0,
4246            },
4247            link_id: "dummy".into(),
4248            setting: None,
4249            status: Some(LinkStatus::Open),
4250        });
4251
4252        network.remove_node("T1", true).unwrap();
4253
4254        assert!(network.controls.is_empty());
4255        assert!(network.node_map.get("T1").is_none());
4256    }
4257
4258    #[test]
4259    fn test_remove_node_not_found() {
4260        let mut network = Network::default();
4261        let err = network.remove_node("missing", false).unwrap_err();
4262        assert!(matches!(err, InputError::NodeNotFound { .. }));
4263    }
4264
4265    // --- pattern tests ---
4266
4267    #[test]
4268    fn test_add_pattern_basic() {
4269        let mut network = Network::default();
4270        network
4271            .add_pattern(
4272                "P1",
4273                &PatternData {
4274                    multipliers: vec![1.0, 1.2, 0.8],
4275                },
4276            )
4277            .unwrap();
4278        assert_eq!(network.patterns.len(), 1);
4279        assert_eq!(network.pattern_map.get("P1").copied(), Some(0));
4280        assert_eq!(network.patterns[0].multipliers, vec![1.0, 1.2, 0.8]);
4281    }
4282
4283    #[test]
4284    fn test_add_pattern_duplicate_fails() {
4285        let mut network = Network::default();
4286        network
4287            .add_pattern(
4288                "P1",
4289                &PatternData {
4290                    multipliers: vec![1.0],
4291                },
4292            )
4293            .unwrap();
4294        let err = network
4295            .add_pattern(
4296                "P1",
4297                &PatternData {
4298                    multipliers: vec![2.0],
4299                },
4300            )
4301            .unwrap_err();
4302        assert!(matches!(err, InputError::Parse { .. }));
4303    }
4304
4305    #[test]
4306    fn test_update_pattern_replaces_multipliers() {
4307        let mut network = Network::default();
4308        network
4309            .add_pattern(
4310                "P1",
4311                &PatternData {
4312                    multipliers: vec![1.0],
4313                },
4314            )
4315            .unwrap();
4316        let props_before = network.properties_version;
4317
4318        network
4319            .update_pattern(
4320                "P1",
4321                &PatternUpdate {
4322                    multipliers: Some(vec![0.5, 1.5]),
4323                },
4324            )
4325            .unwrap();
4326
4327        assert_eq!(network.patterns[0].multipliers, vec![0.5, 1.5]);
4328        assert_eq!(network.properties_version, props_before + 1);
4329    }
4330
4331    #[test]
4332    fn test_update_pattern_not_found() {
4333        let mut network = Network::default();
4334        let err = network
4335            .update_pattern("missing", &PatternUpdate::default())
4336            .unwrap_err();
4337        assert!(matches!(err, InputError::PatternNotFound { .. }));
4338    }
4339
4340    #[test]
4341    fn test_remove_pattern_basic() {
4342        let mut network = Network::default();
4343        network
4344            .add_pattern(
4345                "P1",
4346                &PatternData {
4347                    multipliers: vec![1.0],
4348                },
4349            )
4350            .unwrap();
4351        network.remove_pattern("P1").unwrap();
4352        assert!(network.patterns.is_empty());
4353        assert!(network.pattern_map.get("P1").is_none());
4354    }
4355
4356    #[test]
4357    fn test_remove_pattern_reindexes_junctions_and_reservoirs() {
4358        // two patterns P1, P2. Junction J1 uses P2; remove P1 and verify P2
4359        // now sits at index 0 AND J1's cached pattern_index points to 0.
4360        let mut network = Network::default();
4361        network
4362            .add_pattern(
4363                "P1",
4364                &PatternData {
4365                    multipliers: vec![1.0],
4366                },
4367            )
4368            .unwrap();
4369        network
4370            .add_pattern(
4371                "P2",
4372                &PatternData {
4373                    multipliers: vec![2.0],
4374                },
4375            )
4376            .unwrap();
4377        network
4378            .add_junction(
4379                "J1",
4380                &JunctionData {
4381                    elevation: 0.0,
4382                    demands: demands(1.0, Some("P2")),
4383                    emitter_coefficient: 0.0,
4384                    coordinates: None,
4385                },
4386            )
4387            .unwrap();
4388        network
4389            .add_reservoir(
4390                "R1",
4391                &ReservoirData {
4392                    elevation: 100.0,
4393                    head_pattern: Some("P2".into()),
4394                    coordinates: None,
4395                },
4396            )
4397            .unwrap();
4398
4399        network.remove_pattern("P1").unwrap();
4400
4401        assert_eq!(network.pattern_map.get("P2").copied(), Some(0));
4402        let NodeType::Junction(j) = &network.nodes[0].node_type else {
4403            panic!()
4404        };
4405        assert_eq!(j.demands[0].pattern_index, Some(0));
4406        let NodeType::Reservoir(r) = &network.nodes[1].node_type else {
4407            panic!()
4408        };
4409        assert_eq!(r.head_pattern_index, Some(0));
4410    }
4411
4412    #[test]
4413    fn test_remove_pattern_referenced_fails() {
4414        let mut network = Network::default();
4415        network
4416            .add_pattern(
4417                "P1",
4418                &PatternData {
4419                    multipliers: vec![1.0],
4420                },
4421            )
4422            .unwrap();
4423        network
4424            .add_junction(
4425                "J1",
4426                &JunctionData {
4427                    elevation: 0.0,
4428                    demands: demands(1.0, Some("P1")),
4429                    emitter_coefficient: 0.0,
4430                    coordinates: None,
4431                },
4432            )
4433            .unwrap();
4434        let err = network.remove_pattern("P1").unwrap_err();
4435        assert!(matches!(err, InputError::Parse { .. }));
4436        assert_eq!(network.patterns.len(), 1);
4437    }
4438
4439    #[test]
4440    fn test_remove_pattern_not_found() {
4441        let mut network = Network::default();
4442        let err = network.remove_pattern("missing").unwrap_err();
4443        assert!(matches!(err, InputError::PatternNotFound { .. }));
4444    }
4445
4446    // --- curve tests ---
4447
4448    #[test]
4449    fn test_add_curve_basic() {
4450        let mut network = Network::default();
4451        network
4452            .add_curve(
4453                "C1",
4454                &CurveData {
4455                    x: vec![0.0, 10.0, 20.0],
4456                    y: vec![100.0, 80.0, 40.0],
4457                },
4458            )
4459            .unwrap();
4460        assert_eq!(network.curves.len(), 1);
4461        assert_eq!(network.curve_map.get("C1").copied(), Some(0));
4462    }
4463
4464    #[test]
4465    fn test_add_curve_rejects_mismatched_lengths() {
4466        let mut network = Network::default();
4467        let err = network
4468            .add_curve(
4469                "C1",
4470                &CurveData {
4471                    x: vec![0.0, 10.0],
4472                    y: vec![100.0],
4473                },
4474            )
4475            .unwrap_err();
4476        assert!(matches!(err, InputError::Parse { .. }));
4477    }
4478
4479    #[test]
4480    fn test_add_curve_rejects_non_monotonic_x() {
4481        let mut network = Network::default();
4482        let err = network
4483            .add_curve(
4484                "C1",
4485                &CurveData {
4486                    x: vec![0.0, 10.0, 5.0],
4487                    y: vec![1.0, 2.0, 3.0],
4488                },
4489            )
4490            .unwrap_err();
4491        assert!(matches!(err, InputError::Parse { .. }));
4492    }
4493
4494    #[test]
4495    fn test_add_curve_rejects_empty() {
4496        let mut network = Network::default();
4497        let err = network
4498            .add_curve(
4499                "C1",
4500                &CurveData {
4501                    x: vec![],
4502                    y: vec![],
4503                },
4504            )
4505            .unwrap_err();
4506        assert!(matches!(err, InputError::Parse { .. }));
4507    }
4508
4509    #[test]
4510    fn test_add_curve_duplicate_fails() {
4511        let mut network = Network::default();
4512        network
4513            .add_curve(
4514                "C1",
4515                &CurveData {
4516                    x: vec![0.0, 1.0],
4517                    y: vec![1.0, 0.0],
4518                },
4519            )
4520            .unwrap();
4521        let err = network
4522            .add_curve(
4523                "C1",
4524                &CurveData {
4525                    x: vec![0.0, 1.0],
4526                    y: vec![1.0, 0.0],
4527                },
4528            )
4529            .unwrap_err();
4530        assert!(matches!(err, InputError::Parse { .. }));
4531    }
4532
4533    #[test]
4534    fn test_update_curve_rebuilds_pump_head_curve() {
4535        // a pump referencing C1 should have its cached HeadCurve refreshed when
4536        // C1's axes are updated, and the owning link marked as updated.
4537        let mut network = Network::default();
4538        add_two_junctions(&mut network);
4539        network
4540            .add_curve(
4541                "C1",
4542                &CurveData {
4543                    x: vec![0.0, 50.0, 100.0],
4544                    y: vec![100.0, 80.0, 40.0],
4545                },
4546            )
4547            .unwrap();
4548        network
4549            .add_pump(
4550                "PU1",
4551                &PumpData {
4552                    start_node: "J1".into(),
4553                    end_node: "J2".into(),
4554                    speed: 1.0,
4555                    head_curve_id: Some("C1".into()),
4556                    power: 0.0,
4557                    initial_status: LinkStatus::Open,
4558                    vertices: None,
4559                },
4560            )
4561            .unwrap();
4562        network.reset_changes();
4563        let props_before = network.properties_version;
4564
4565        network
4566            .update_curve(
4567                "C1",
4568                &CurveUpdate {
4569                    x: Some(vec![0.0, 25.0, 60.0]),
4570                    y: Some(vec![120.0, 90.0, 30.0]),
4571                },
4572            )
4573            .unwrap();
4574
4575        assert_eq!(network.curves[0].x, vec![0.0, 25.0, 60.0]);
4576        assert_eq!(network.curves[0].y, vec![120.0, 90.0, 30.0]);
4577        let LinkType::Pump(pump) = &network.links[0].link_type else {
4578            panic!()
4579        };
4580        assert!(pump.head_curve.is_some());
4581        // the refreshed shutoff head (in feet) should reflect the new y[0]
4582        let hc = pump.head_curve.as_ref().unwrap();
4583        assert!((hc.statistics.h_shutoff - 120.0).abs() < 1e-6);
4584        assert!(network.updated_links.contains(&0));
4585        assert_eq!(network.properties_version, props_before + 1);
4586    }
4587
4588    #[test]
4589    fn test_update_curve_partial_preserves_other_axis() {
4590        let mut network = Network::default();
4591        network
4592            .add_curve(
4593                "C1",
4594                &CurveData {
4595                    x: vec![0.0, 1.0, 2.0],
4596                    y: vec![10.0, 8.0, 5.0],
4597                },
4598            )
4599            .unwrap();
4600
4601        network
4602            .update_curve(
4603                "C1",
4604                &CurveUpdate {
4605                    x: None,
4606                    y: Some(vec![20.0, 15.0, 9.0]),
4607                },
4608            )
4609            .unwrap();
4610
4611        assert_eq!(network.curves[0].x, vec![0.0, 1.0, 2.0]);
4612        assert_eq!(network.curves[0].y, vec![20.0, 15.0, 9.0]);
4613    }
4614
4615    #[test]
4616    fn test_update_curve_rejects_invalid_combined_axes() {
4617        let mut network = Network::default();
4618        network
4619            .add_curve(
4620                "C1",
4621                &CurveData {
4622                    x: vec![0.0, 1.0, 2.0],
4623                    y: vec![10.0, 8.0, 5.0],
4624                },
4625            )
4626            .unwrap();
4627
4628        let err = network
4629            .update_curve(
4630                "C1",
4631                &CurveUpdate {
4632                    x: Some(vec![0.0, 2.0]), // shorter than existing y
4633                    y: None,
4634                },
4635            )
4636            .unwrap_err();
4637        assert!(matches!(err, InputError::Parse { .. }));
4638        // curve must be unchanged on failure
4639        assert_eq!(network.curves[0].x, vec![0.0, 1.0, 2.0]);
4640    }
4641
4642    #[test]
4643    fn test_update_curve_not_found() {
4644        let mut network = Network::default();
4645        let err = network
4646            .update_curve("missing", &CurveUpdate::default())
4647            .unwrap_err();
4648        assert!(matches!(err, InputError::CurveNotFound { .. }));
4649    }
4650
4651    #[test]
4652    fn test_remove_curve_basic() {
4653        let mut network = Network::default();
4654        network
4655            .add_curve(
4656                "C1",
4657                &CurveData {
4658                    x: vec![0.0, 1.0],
4659                    y: vec![1.0, 0.0],
4660                },
4661            )
4662            .unwrap();
4663        network.remove_curve("C1").unwrap();
4664        assert!(network.curves.is_empty());
4665        assert!(network.curve_map.get("C1").is_none());
4666    }
4667
4668    #[test]
4669    fn test_remove_curve_reindexes_curve_map() {
4670        let mut network = Network::default();
4671        network
4672            .add_curve(
4673                "C1",
4674                &CurveData {
4675                    x: vec![0.0, 1.0],
4676                    y: vec![1.0, 0.0],
4677                },
4678            )
4679            .unwrap();
4680        network
4681            .add_curve(
4682                "C2",
4683                &CurveData {
4684                    x: vec![0.0, 1.0],
4685                    y: vec![2.0, 1.0],
4686                },
4687            )
4688            .unwrap();
4689
4690        network.remove_curve("C1").unwrap();
4691        assert_eq!(network.curves.len(), 1);
4692        assert_eq!(network.curve_map.get("C2").copied(), Some(0));
4693    }
4694
4695    #[test]
4696    fn test_remove_curve_referenced_by_pump_fails() {
4697        let mut network = Network::default();
4698        add_two_junctions(&mut network);
4699        network
4700            .add_curve(
4701                "C1",
4702                &CurveData {
4703                    x: vec![0.0, 50.0, 100.0],
4704                    y: vec![100.0, 80.0, 40.0],
4705                },
4706            )
4707            .unwrap();
4708        network
4709            .add_pump(
4710                "PU1",
4711                &PumpData {
4712                    start_node: "J1".into(),
4713                    end_node: "J2".into(),
4714                    speed: 1.0,
4715                    head_curve_id: Some("C1".into()),
4716                    power: 0.0,
4717                    initial_status: LinkStatus::Open,
4718                    vertices: None,
4719                },
4720            )
4721            .unwrap();
4722
4723        let err = network.remove_curve("C1").unwrap_err();
4724        assert!(matches!(err, InputError::Parse { .. }));
4725        assert_eq!(network.curves.len(), 1);
4726    }
4727
4728    #[test]
4729    fn test_remove_curve_not_found() {
4730        let mut network = Network::default();
4731        let err = network.remove_curve("missing").unwrap_err();
4732        assert!(matches!(err, InputError::CurveNotFound { .. }));
4733    }
4734}