Skip to main content

hydr_structures/structures/culvert/
parameters.rs

1//! Culvert law definition: barrel, alignment, roughness, barrel count and one end per direction.
2
3use crate::structures::{
4    BlockageFraction, CulvertApplicability, CulvertBarrel, CulvertBarrelShape, CulvertBlockage,
5    CulvertFloor, CulvertInlet, CulvertInletRow, CulvertOutletRow, StructureError,
6};
7
8/// Inlet of the culvert end that flow enters: an HDS-5 inlet and its entrance loss `ke`.
9#[derive(Clone, Copy, Debug, PartialEq)]
10pub struct CulvertEnd {
11    inlet: CulvertInlet,
12    entrance_loss: f64,
13}
14
15impl CulvertEnd {
16    /// Admits an inlet and a finite nonnegative entrance loss coefficient `ke`.
17    pub fn new(inlet: CulvertInlet, entrance_loss: f64) -> Result<Self, StructureError> {
18        if !(entrance_loss.is_finite() && entrance_loss >= 0.0) {
19            return Err(StructureError::definition(format!(
20                "{},entrance_loss={entrance_loss:?}: supply a finite nonnegative entrance loss coefficient",
21                inlet.describe()
22            )));
23        }
24        Ok(Self {
25            inlet,
26            entrance_loss,
27        })
28    }
29
30    /// HDS-5 inlet of this end.
31    pub fn inlet(&self) -> CulvertInlet {
32        self.inlet
33    }
34
35    /// Entrance loss coefficient `ke`.
36    pub fn entrance_loss(&self) -> f64 {
37        self.entrance_loss
38    }
39}
40
41/// Barrel length and the invert elevation at each endpoint, in metres on the structure datum.
42#[derive(Clone, Copy, Debug, PartialEq)]
43pub struct CulvertAlignment {
44    /// Barrel length `L` in metres.
45    pub length_m: f64,
46    /// Invert elevation at endpoint A.
47    pub invert_a_m: f64,
48    /// Invert elevation at endpoint B.
49    pub invert_b_m: f64,
50}
51
52/// One culvert end per admitted flow direction.
53#[derive(Clone, Copy, Debug, PartialEq)]
54pub struct CulvertEnds {
55    /// Inlet at endpoint A, entered by A-to-B flow.
56    pub a: Option<CulvertEnd>,
57    /// Inlet at endpoint B, entered by B-to-A flow.
58    pub b: Option<CulvertEnd>,
59}
60
61/// Complete checked HDS-5 culvert: identical parallel barrels between two endpoints.
62///
63/// The law holds no water. A roadway over the culvert is a separate weir on the same endpoints.
64#[derive(Clone, Debug, PartialEq)]
65pub struct CulvertParameters {
66    barrel: CulvertBarrel,
67    alignment: CulvertAlignment,
68    manning_n: f64,
69    floor_manning_n: Option<f64>,
70    barrel_count: u32,
71    ends: CulvertEnds,
72    gravity_m_per_s2: f64,
73    applicability: CulvertApplicability,
74}
75
76impl CulvertParameters {
77    /// Checks the alignment, roughness, barrel count, ends, gravity and applicability evidence.
78    ///
79    /// Rejects a nonfinite or nonpositive length, Manning `n` or gravity, a nonfinite invert, a
80    /// zero barrel count, and a definition without an end. Rejects an end whose coded inlet is
81    /// for another barrel shape. Rejects an end whose barrel rises toward the far invert by more
82    /// than half the rise. Monotone inlet admission runs when a batch uploads the culvert.
83    pub fn new(
84        barrel: CulvertBarrel,
85        alignment: CulvertAlignment,
86        manning_n: f64,
87        barrel_count: u32,
88        ends: CulvertEnds,
89        gravity_m_per_s2: f64,
90        applicability: CulvertApplicability,
91    ) -> Result<Self, StructureError> {
92        applicability.check()?;
93        if let Some(floor) = barrel.floor() {
94            return Err(StructureError::definition(format!(
95                "sediment_depth_m={:?},roughness_ratio={:?}: CulvertParameters holds the unblocked barrel. Supply CulvertBarrel::base, set an open floor with CulvertParameters::with_floor_manning_n, or declare sediment with StructureBlockage::culvert",
96                floor.sediment_depth_m, floor.roughness_ratio
97            )));
98        }
99        let CulvertAlignment {
100            length_m,
101            invert_a_m,
102            invert_b_m,
103        } = alignment;
104        let fields = format!(
105            "length_m={length_m:?},invert_a_m={invert_a_m:?},invert_b_m={invert_b_m:?},manning_n={manning_n:?},barrel_count={barrel_count},gravity_m_per_s2={gravity_m_per_s2:?}"
106        );
107        if !(invert_a_m.is_finite() && invert_b_m.is_finite()) {
108            return Err(StructureError::definition(format!(
109                "{fields}: supply finite invert elevations on the structure datum"
110            )));
111        }
112        if barrel_count == 0 {
113            return Err(StructureError::definition(format!(
114                "{fields}: supply at least one barrel"
115            )));
116        }
117        if ends.a.is_none() && ends.b.is_none() {
118            return Err(StructureError::definition(format!(
119                "{fields}: supply the culvert end of at least one flow direction"
120            )));
121        }
122        let parameters = Self {
123            barrel,
124            alignment,
125            manning_n,
126            floor_manning_n: None,
127            barrel_count,
128            ends,
129            gravity_m_per_s2,
130            applicability,
131        };
132        for side in [CulvertSide::A, CulvertSide::B] {
133            if let Some((inlet, outlet)) = parameters.rows(side) {
134                outlet.check()?;
135                inlet.check()?;
136            }
137        }
138        Ok(parameters)
139    }
140
141    /// Sets the Manning roughness `n_floor` of the own floor of a box or flat-floor arch barrel.
142    ///
143    /// A sediment bed declared in [`CulvertBlockage`] replaces this floor roughness. Rejects
144    /// barrels without their own floor and nonfinite or nonpositive roughness values.
145    pub fn with_floor_manning_n(mut self, floor_manning_n: f64) -> Result<Self, StructureError> {
146        if !matches!(
147            self.barrel.shape(),
148            CulvertBarrelShape::Box | CulvertBarrelShape::Arch
149        ) {
150            return Err(StructureError::definition(format!(
151                "floor_manning_n={floor_manning_n:?},barrel_shape={:?}: only a box or flat-floor arch barrel has its own floor. Declare sediment through StructureBlockage::culvert instead",
152                self.barrel.shape()
153            )));
154        }
155        if !(floor_manning_n.is_finite() && floor_manning_n > 0.0) {
156            return Err(StructureError::definition(format!(
157                "floor_manning_n={floor_manning_n:?}: supply a finite positive floor Manning n in s/m^(1/3)"
158            )));
159        }
160        self.barrel.with_floor(CulvertFloor {
161            sediment_depth_m: 0.0,
162            roughness_ratio: floor_manning_n / self.manning_n,
163        })?;
164        self.floor_manning_n = Some(floor_manning_n);
165        Ok(self)
166    }
167
168    /// Barrel cross-section of every barrel.
169    pub fn barrel(&self) -> CulvertBarrel {
170        self.barrel
171    }
172
173    /// Barrel length and both inverts.
174    pub fn alignment(&self) -> CulvertAlignment {
175        self.alignment
176    }
177
178    /// Manning roughness `n` in `s/m^(1/3)`.
179    pub fn manning_n(&self) -> f64 {
180        self.manning_n
181    }
182
183    /// Declared floor Manning roughness `n_floor` of an open-bottom box or flat-floor arch.
184    pub fn floor_manning_n(&self) -> Option<f64> {
185        self.floor_manning_n
186    }
187
188    /// Number of identical parallel barrels.
189    pub fn barrel_count(&self) -> u32 {
190        self.barrel_count
191    }
192
193    /// End of each flow direction.
194    pub fn ends(&self) -> CulvertEnds {
195        self.ends
196    }
197
198    /// Gravity in metres per second squared.
199    pub fn gravity_m_per_s2(&self) -> f64 {
200        self.gravity_m_per_s2
201    }
202
203    /// Complete immutable applicability evidence.
204    pub fn applicability(&self) -> &CulvertApplicability {
205        &self.applicability
206    }
207
208    /// Inlet and outlet query rows of A-to-B flow, or `None` without an A end.
209    ///
210    /// The slope is `(z_a - z_b) / L`.
211    pub fn forward_rows(&self) -> Option<(CulvertInletRow, CulvertOutletRow)> {
212        self.rows(CulvertSide::A)
213    }
214
215    /// Inlet and outlet query rows of B-to-A flow, or `None` without a B end.
216    ///
217    /// The slope is `(z_b - z_a) / L`.
218    pub fn reverse_rows(&self) -> Option<(CulvertInletRow, CulvertOutletRow)> {
219        self.rows(CulvertSide::B)
220    }
221
222    /// Inlet and outlet rows of flow that enters at `side`, or `None` without that end.
223    ///
224    /// The slope is `(z_in - z_out) / L`, so the two directions carry opposite slopes.
225    pub(crate) fn rows(&self, side: CulvertSide) -> Option<(CulvertInletRow, CulvertOutletRow)> {
226        let CulvertAlignment {
227            length_m,
228            invert_a_m,
229            invert_b_m,
230        } = self.alignment;
231        let (end, fall) = match side {
232            CulvertSide::A => (self.ends.a?, invert_a_m - invert_b_m),
233            CulvertSide::B => (self.ends.b?, invert_b_m - invert_a_m),
234        };
235        let barrel = match self.floor_manning_n {
236            Some(floor_n) => self
237                .barrel
238                .with_floor(CulvertFloor {
239                    sediment_depth_m: 0.0,
240                    roughness_ratio: floor_n / self.manning_n,
241                })
242                .unwrap_or(self.barrel),
243            None => self.barrel,
244        };
245        let slope = fall / length_m;
246        Some((
247            CulvertInletRow {
248                barrel,
249                inlet: end.inlet,
250                slope,
251                gravity_m_per_s2: self.gravity_m_per_s2,
252                face_blockage: BlockageFraction::NONE,
253            },
254            CulvertOutletRow {
255                barrel,
256                length_m,
257                manning_n: self.manning_n,
258                entrance_loss: end.entrance_loss,
259                slope,
260                gravity_m_per_s2: self.gravity_m_per_s2,
261                face_blockage: BlockageFraction::NONE,
262            },
263        ))
264    }
265
266    /// Effective barrel under `blockage`, applying sediment or the declared open floor.
267    pub(crate) fn effective_barrel(
268        &self,
269        blockage: Option<&CulvertBlockage>,
270    ) -> Result<CulvertBarrel, StructureError> {
271        if let Some(sediment) = blockage.and_then(|b| b.sediment) {
272            if !(sediment.bed_manning_n.is_finite() && sediment.bed_manning_n > 0.0) {
273                return Err(StructureError::definition(format!(
274                    "bed_manning_n={:?}: supply a finite positive sediment bed Manning n in s/m^(1/3)",
275                    sediment.bed_manning_n
276                )));
277            }
278            return self.barrel.with_floor(CulvertFloor {
279                sediment_depth_m: sediment.depth_m,
280                roughness_ratio: sediment.bed_manning_n / self.manning_n,
281            });
282        }
283        if let Some(floor_n) = self.floor_manning_n {
284            return self.barrel.with_floor(CulvertFloor {
285                sediment_depth_m: 0.0,
286                roughness_ratio: floor_n / self.manning_n,
287            });
288        }
289        Ok(self.barrel)
290    }
291
292    /// Effective inlet and outlet rows of flow entering at `side` under `blockage`.
293    pub(crate) fn effective_rows(
294        &self,
295        side: CulvertSide,
296        blockage: Option<&CulvertBlockage>,
297    ) -> Result<Option<(CulvertInletRow, CulvertOutletRow)>, StructureError> {
298        let Some((mut inlet, mut outlet)) = self.rows(side) else {
299            return Ok(None);
300        };
301        let barrel = self.effective_barrel(blockage)?;
302        let face = match (side, blockage) {
303            (CulvertSide::A, Some(b)) => b.face_a,
304            (CulvertSide::B, Some(b)) => b.face_b,
305            (_, None) => BlockageFraction::NONE,
306        };
307        inlet.barrel = barrel;
308        inlet.face_blockage = face;
309        outlet.barrel = barrel;
310        outlet.face_blockage = face;
311        outlet.check()?;
312        inlet.check()?;
313        Ok(Some((inlet, outlet)))
314    }
315
316    /// Invert at `side`.
317    pub(crate) fn invert(&self, side: CulvertSide) -> f64 {
318        match side {
319            CulvertSide::A => self.alignment.invert_a_m,
320            CulvertSide::B => self.alignment.invert_b_m,
321        }
322    }
323
324    /// Bed elevation `fl(z + h)` at `side` under `blockage`, with `h` the admitted sediment depth.
325    pub(crate) fn bed_elevation(
326        &self,
327        side: CulvertSide,
328        blockage: Option<&CulvertBlockage>,
329    ) -> Result<f64, StructureError> {
330        let barrel = self.effective_barrel(blockage)?;
331        let depth = barrel.floor().map_or(0.0, |floor| floor.sediment_depth_m);
332        let invert = self.invert(side);
333        let bed = if depth == 0.0 { invert } else { invert + depth };
334        if !bed.is_finite() {
335            return Err(StructureError::definition(format!(
336                "invert_m={invert:?},sediment_depth_m={depth:?}: bed elevation overflows F64. Supply finite inverts with room for the sediment depth"
337            )));
338        }
339        Ok(bed)
340    }
341}
342
343/// Endpoint of a culvert, which is the inlet of the flow that enters there.
344#[derive(Clone, Copy, Debug, PartialEq, Eq)]
345pub(crate) enum CulvertSide {
346    A,
347    B,
348}
349
350#[cfg(test)]
351mod tests {
352    use super::*;
353    use crate::structures::StructureInputErrorKind;
354
355    fn applicability() -> CulvertApplicability {
356        CulvertApplicability {
357            coefficient_provenance: "HDS-5 Table A.1".into(),
358            barrel_condition_assertion: "Clean barrel".into(),
359        }
360    }
361
362    fn end(code: u8) -> Result<CulvertEnd, StructureError> {
363        CulvertEnd::new(CulvertInlet::hds5(code)?, 0.5)
364    }
365
366    fn culvert(
367        alignment: CulvertAlignment,
368        manning_n: f64,
369        count: u32,
370        ends: CulvertEnds,
371    ) -> Result<CulvertParameters, StructureError> {
372        CulvertParameters::new(
373            CulvertBarrel::circular(1.2)?,
374            alignment,
375            manning_n,
376            count,
377            ends,
378            9.81,
379            applicability(),
380        )
381    }
382
383    fn message(result: Result<CulvertParameters, StructureError>) -> Option<String> {
384        match result {
385            Err(StructureError::InvalidInput {
386                kind: StructureInputErrorKind::Definition,
387                context,
388                element: None,
389            }) => Some(context),
390            _ => None,
391        }
392    }
393
394    #[test]
395    fn rows_carry_opposite_slopes_and_their_own_end() -> Result<(), StructureError> {
396        let alignment = CulvertAlignment {
397            length_m: 40.0,
398            invert_a_m: 10.3,
399            invert_b_m: 10.1,
400        };
401        let parameters = culvert(
402            alignment,
403            0.012,
404            2,
405            CulvertEnds {
406                a: Some(end(1)?),
407                b: Some(CulvertEnd::new(CulvertInlet::hds5(3)?, 0.2)?),
408            },
409        )?;
410        let forward = parameters.rows(CulvertSide::A);
411        let reverse = parameters.rows(CulvertSide::B);
412        let (Some((inlet_a, outlet_a)), Some((inlet_b, outlet_b))) = (forward, reverse) else {
413            return Err(StructureError::definition("both ends exist"));
414        };
415        assert_eq!(inlet_a.slope.to_bits(), (-inlet_b.slope).to_bits());
416        assert_eq!(outlet_a.slope.to_bits(), inlet_a.slope.to_bits());
417        assert_eq!(inlet_a.inlet.code(), Some(1));
418        assert_eq!(inlet_b.inlet.code(), Some(3));
419        assert_eq!((outlet_a.entrance_loss, outlet_b.entrance_loss), (0.5, 0.2));
420        assert_eq!(parameters.invert(CulvertSide::B), 10.1);
421        Ok(())
422    }
423
424    #[test]
425    fn admission_names_the_value_and_action() -> Result<(), StructureError> {
426        let level = CulvertAlignment {
427            length_m: 20.0,
428            invert_a_m: 0.0,
429            invert_b_m: 0.0,
430        };
431        let one = CulvertEnds {
432            a: Some(end(1)?),
433            b: None,
434        };
435        let cases = [
436            (
437                culvert(level, 0.013, 0, one),
438                "barrel_count=0,gravity_m_per_s2=9.81: supply at least one barrel",
439            ),
440            (
441                culvert(level, 0.013, 1, CulvertEnds { a: None, b: None }),
442                "supply the culvert end of at least one flow direction",
443            ),
444            (
445                culvert(
446                    CulvertAlignment {
447                        invert_b_m: f64::NAN,
448                        ..level
449                    },
450                    0.013,
451                    1,
452                    one,
453                ),
454                "invert_b_m=NaN",
455            ),
456            (
457                culvert(level, -0.013, 1, one),
458                "manning_n=-0.013,entrance_loss=0.5,slope=0.0,gravity_m_per_s2=9.81: supply a finite positive Manning n",
459            ),
460            (
461                culvert(
462                    CulvertAlignment {
463                        invert_b_m: 0.7,
464                        ..level
465                    },
466                    0.013,
467                    1,
468                    one,
469                ),
470                "Supply an adverse fall of at most rise/2",
471            ),
472            (
473                culvert(
474                    level,
475                    0.013,
476                    1,
477                    CulvertEnds {
478                        a: Some(end(9)?),
479                        b: None,
480                    },
481                ),
482                "the code is for Box barrels",
483            ),
484        ];
485        for (result, expected) in cases {
486            let text = message(result);
487            assert!(
488                text.as_deref().is_some_and(|t| t.contains(expected)),
489                "{text:?} lacks {expected:?}"
490            );
491        }
492        let text = match CulvertEnd::new(CulvertInlet::hds5(1)?, -0.1) {
493            Err(StructureError::InvalidInput { context, .. }) => context,
494            Ok(_) => String::new(),
495            Err(other) => other.to_string(),
496        };
497        assert!(text.contains("entrance_loss=-0.1: supply a finite nonnegative"));
498        Ok(())
499    }
500}