suido 0.1.0

Typed water-supply balance and pipe-flow calculations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
//! Typed water-supply balance and pipe-flow calculations.
//!
//! `suido` keeps the units used by its small planning model explicit. A
//! [`WaterSupplyPlan`] combines available flow, stored volume, internal pipe
//! diameter, and fixture demands into an explainable [`SupplyReport`].

#![forbid(unsafe_code)]
#![warn(missing_docs)]

use std::error::Error;
use std::f64::consts::PI;
use std::fmt;

/// A water flow rate stored in liters per minute.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct FlowRate(f64);

impl FlowRate {
    /// Creates a non-negative, finite flow rate in liters per minute.
    pub fn liters_per_minute(value: f64) -> Result<Self, SuidoError> {
        validate_non_negative_finite(value, "flow rate")?;
        Ok(Self(value))
    }

    /// Returns this flow rate in liters per minute.
    pub const fn as_liters_per_minute(self) -> f64 {
        self.0
    }

    /// Calculates the volume delivered over a duration.
    pub fn volume_over(self, duration: Duration) -> Result<Volume, SuidoError> {
        let liters = self.0 * duration.as_seconds() / 60.0;
        ensure_finite(liters)?;
        Ok(Volume(liters))
    }
}

/// A signed difference between supply and demand, in liters per minute.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct FlowMargin(f64);

impl FlowMargin {
    /// Returns the signed margin in liters per minute.
    ///
    /// Positive values are surplus and negative values are deficit.
    pub const fn as_liters_per_minute(self) -> f64 {
        self.0
    }
}

/// A water volume stored in liters.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Volume(f64);

impl Volume {
    /// Creates a non-negative, finite volume in liters.
    pub fn liters(value: f64) -> Result<Self, SuidoError> {
        validate_non_negative_finite(value, "volume")?;
        Ok(Self(value))
    }

    /// Returns this volume in liters.
    pub const fn as_liters(self) -> f64 {
        self.0
    }
}

/// A non-negative duration stored in seconds.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct Duration(f64);

impl Duration {
    /// Creates a non-negative, finite duration in seconds.
    pub fn seconds(value: f64) -> Result<Self, SuidoError> {
        validate_non_negative_finite(value, "duration")?;
        Ok(Self(value))
    }

    /// Creates a non-negative, finite duration in minutes.
    pub fn minutes(value: f64) -> Result<Self, SuidoError> {
        validate_non_negative_finite(value, "duration")?;
        let seconds = value * 60.0;
        ensure_finite(seconds)?;
        Ok(Self(seconds))
    }

    /// Returns this duration in seconds.
    pub const fn as_seconds(self) -> f64 {
        self.0
    }
}

/// The positive internal diameter of a circular pipe.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)]
pub struct PipeDiameter(f64);

impl PipeDiameter {
    /// Creates a positive, finite internal diameter in millimeters.
    pub fn millimeters(value: f64) -> Result<Self, SuidoError> {
        validate_positive_finite(value, "pipe diameter")?;
        Ok(Self(value))
    }

    /// Returns the internal diameter in millimeters.
    pub const fn as_millimeters(self) -> f64 {
        self.0
    }

    /// Calculates mean velocity in meters per second for a flow rate.
    pub fn velocity_mps(self, flow: FlowRate) -> Result<f64, SuidoError> {
        let diameter_m = self.0 / 1_000.0;
        let area_m2 = PI * diameter_m * diameter_m / 4.0;
        let cubic_meters_per_second = flow.as_liters_per_minute() / 60_000.0;
        let velocity = cubic_meters_per_second / area_m2;
        ensure_finite(velocity)?;
        Ok(velocity)
    }
}

/// Maximum simultaneous demand for one kind of fixture.
#[derive(Debug, Clone, PartialEq)]
pub struct FixtureDemand {
    name: String,
    flow_per_unit: FlowRate,
    units: u32,
}

impl FixtureDemand {
    /// Creates a demand from a non-blank name, per-unit flow, and unit count.
    pub fn new(
        name: impl Into<String>,
        flow_per_unit: FlowRate,
        units: u32,
    ) -> Result<Self, SuidoError> {
        let name = name.into();
        if name.trim().is_empty() {
            return Err(SuidoError::EmptyFixtureName);
        }
        if units == 0 {
            return Err(SuidoError::ZeroFixtureUnits);
        }
        Ok(Self {
            name,
            flow_per_unit,
            units,
        })
    }

    /// Returns the fixture label.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns flow per fixture in liters per minute.
    pub const fn flow_per_unit(&self) -> FlowRate {
        self.flow_per_unit
    }

    /// Returns the number of simultaneously active fixtures.
    pub const fn units(&self) -> u32 {
        self.units
    }

    /// Returns the total demand of all units.
    pub fn total_flow(&self) -> Result<FlowRate, SuidoError> {
        let total = self.flow_per_unit.0 * f64::from(self.units);
        ensure_finite(total)?;
        Ok(FlowRate(total))
    }
}

/// A small water-supply plan evaluated at maximum simultaneous fixture demand.
#[derive(Debug, Clone, PartialEq)]
pub struct WaterSupplyPlan {
    supply: FlowRate,
    storage: Volume,
    pipe_diameter: PipeDiameter,
    demands: Vec<FixtureDemand>,
}

impl WaterSupplyPlan {
    /// Creates a plan without fixture demands.
    pub const fn new(supply: FlowRate, storage: Volume, pipe_diameter: PipeDiameter) -> Self {
        Self {
            supply,
            storage,
            pipe_diameter,
            demands: Vec::new(),
        }
    }

    /// Adds a fixture demand.
    pub fn add_demand(&mut self, demand: FixtureDemand) -> Result<(), SuidoError> {
        let _ = demand.total_flow()?;
        self.demands.push(demand);
        Ok(())
    }

    /// Returns all fixture demands in insertion order.
    pub fn demands(&self) -> &[FixtureDemand] {
        &self.demands
    }

    /// Evaluates supply, maximum demand, stored reserve, and pipe velocity.
    pub fn evaluate(&self) -> Result<SupplyReport, SuidoError> {
        let mut demand_lpm = 0.0;
        for demand in &self.demands {
            demand_lpm += demand.total_flow()?.as_liters_per_minute();
            ensure_finite(demand_lpm)?;
        }

        let margin_lpm = self.supply.0 - demand_lpm;
        ensure_finite(margin_lpm)?;
        let state = if margin_lpm > 0.0 {
            SupplyState::Surplus
        } else if margin_lpm < 0.0 {
            SupplyState::Deficit
        } else {
            SupplyState::Balanced
        };

        let storage_endurance_minutes = if state == SupplyState::Deficit {
            let minutes = self.storage.0 / -margin_lpm;
            ensure_finite(minutes)?;
            Some(minutes)
        } else {
            None
        };

        Ok(SupplyReport {
            state,
            supply: self.supply,
            demand: FlowRate(demand_lpm),
            margin: FlowMargin(margin_lpm),
            storage: self.storage,
            storage_endurance_minutes,
            pipe_velocity_mps: self.pipe_diameter.velocity_mps(self.supply)?,
        })
    }
}

/// Instantaneous supply condition.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SupplyState {
    /// Available flow exceeds demand.
    Surplus,
    /// Available flow exactly equals demand.
    Balanced,
    /// Demand exceeds available flow.
    Deficit,
}

/// An explainable result for a [`WaterSupplyPlan`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct SupplyReport {
    state: SupplyState,
    supply: FlowRate,
    demand: FlowRate,
    margin: FlowMargin,
    storage: Volume,
    storage_endurance_minutes: Option<f64>,
    pipe_velocity_mps: f64,
}

impl SupplyReport {
    /// Returns the supply condition.
    pub const fn state(self) -> SupplyState {
        self.state
    }

    /// Returns available flow.
    pub const fn supply(self) -> FlowRate {
        self.supply
    }

    /// Returns maximum simultaneous fixture demand.
    pub const fn demand(self) -> FlowRate {
        self.demand
    }

    /// Returns supply minus demand.
    pub const fn margin(self) -> FlowMargin {
        self.margin
    }

    /// Returns stored water included in the plan.
    pub const fn storage(self) -> Volume {
        self.storage
    }

    /// Returns minutes that storage covers the deficit, if there is a deficit.
    pub const fn storage_endurance_minutes(self) -> Option<f64> {
        self.storage_endurance_minutes
    }

    /// Returns mean pipe velocity at the available supply flow.
    pub const fn pipe_velocity_mps(self) -> f64 {
        self.pipe_velocity_mps
    }
}

/// Invalid input or a calculation outside finite floating-point range.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SuidoError {
    /// A named value was not finite.
    NonFinite(&'static str),
    /// A named value was negative.
    Negative(&'static str),
    /// A named value had to be positive but was zero.
    Zero(&'static str),
    /// A fixture name was blank.
    EmptyFixtureName,
    /// A fixture demand specified zero active units.
    ZeroFixtureUnits,
    /// Arithmetic produced a non-finite result.
    CalculationOverflow,
}

impl fmt::Display for SuidoError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::NonFinite(name) => write!(formatter, "{name} must be finite"),
            Self::Negative(name) => write!(formatter, "{name} must not be negative"),
            Self::Zero(name) => write!(formatter, "{name} must be greater than zero"),
            Self::EmptyFixtureName => formatter.write_str("fixture name must not be blank"),
            Self::ZeroFixtureUnits => {
                formatter.write_str("fixture units must be greater than zero")
            }
            Self::CalculationOverflow => formatter.write_str("calculation exceeded finite range"),
        }
    }
}

impl Error for SuidoError {}

fn validate_non_negative_finite(value: f64, name: &'static str) -> Result<(), SuidoError> {
    if !value.is_finite() {
        return Err(SuidoError::NonFinite(name));
    }
    if value < 0.0 {
        return Err(SuidoError::Negative(name));
    }
    Ok(())
}

fn validate_positive_finite(value: f64, name: &'static str) -> Result<(), SuidoError> {
    validate_non_negative_finite(value, name)?;
    if value == 0.0 {
        return Err(SuidoError::Zero(name));
    }
    Ok(())
}

fn ensure_finite(value: f64) -> Result<(), SuidoError> {
    if value.is_finite() {
        Ok(())
    } else {
        Err(SuidoError::CalculationOverflow)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn flow(value: f64) -> FlowRate {
        FlowRate::liters_per_minute(value).unwrap()
    }

    fn plan(supply: f64, storage: f64) -> WaterSupplyPlan {
        WaterSupplyPlan::new(
            flow(supply),
            Volume::liters(storage).unwrap(),
            PipeDiameter::millimeters(20.0).unwrap(),
        )
    }

    #[test]
    fn flow_over_time_produces_volume() {
        let volume = flow(12.0)
            .volume_over(Duration::minutes(2.5).unwrap())
            .unwrap();
        assert_eq!(volume.as_liters(), 30.0);
    }

    #[test]
    fn pipe_velocity_uses_internal_diameter() {
        let velocity = PipeDiameter::millimeters(20.0)
            .unwrap()
            .velocity_mps(flow(20.0))
            .unwrap();
        assert!((velocity - 1.061_032_953_945_969).abs() < 1e-12);
    }

    #[test]
    fn fixture_units_are_included_in_demand() {
        let mut plan = plan(20.0, 0.0);
        plan.add_demand(FixtureDemand::new("tap", flow(4.0), 3).unwrap())
            .unwrap();
        let report = plan.evaluate().unwrap();

        assert_eq!(report.demand().as_liters_per_minute(), 12.0);
        assert_eq!(report.margin().as_liters_per_minute(), 8.0);
        assert_eq!(report.state(), SupplyState::Surplus);
    }

    #[test]
    fn storage_covers_only_a_deficit() {
        let mut plan = plan(18.0, 120.0);
        plan.add_demand(FixtureDemand::new("fixtures", flow(22.0), 1).unwrap())
            .unwrap();
        let report = plan.evaluate().unwrap();

        assert_eq!(report.state(), SupplyState::Deficit);
        assert_eq!(report.storage_endurance_minutes(), Some(30.0));
    }

    #[test]
    fn exact_supply_is_balanced() {
        let mut plan = plan(10.0, 50.0);
        plan.add_demand(FixtureDemand::new("tap", flow(10.0), 1).unwrap())
            .unwrap();
        let report = plan.evaluate().unwrap();

        assert_eq!(report.state(), SupplyState::Balanced);
        assert_eq!(report.storage_endurance_minutes(), None);
    }

    #[test]
    fn invalid_quantities_and_fixtures_are_rejected() {
        assert_eq!(
            FlowRate::liters_per_minute(f64::NAN),
            Err(SuidoError::NonFinite("flow rate"))
        );
        assert_eq!(Volume::liters(-1.0), Err(SuidoError::Negative("volume")));
        assert_eq!(
            PipeDiameter::millimeters(0.0),
            Err(SuidoError::Zero("pipe diameter"))
        );
        assert_eq!(
            FixtureDemand::new("  ", flow(1.0), 1),
            Err(SuidoError::EmptyFixtureName)
        );
        assert_eq!(
            FixtureDemand::new("tap", flow(1.0), 0),
            Err(SuidoError::ZeroFixtureUnits)
        );
    }

    #[test]
    fn calculation_overflow_is_reported() {
        let demand = FixtureDemand::new("huge", flow(f64::MAX), 2).unwrap();
        assert_eq!(demand.total_flow(), Err(SuidoError::CalculationOverflow));
    }
}