Skip to main content

hydr_structures/structures/culvert/barrel/
mod.rs

1//! Closed-conduit barrel shapes and their admission.
2//!
3//! Elliptical, pipe-arch and flat-floor arch barrels are tangent circular arcs. Their
4//! constructors check the tangency rules of their dimensions. Every barrel, inlet and outlet
5//! query and the culvert law accept them.
6
7mod arcs;
8mod enclosure;
9mod floor;
10mod frame;
11
12pub use floor::CulvertFloor;
13
14use crate::structures::StructureError;
15
16/// Cross-section shape of a culvert barrel.
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18#[non_exhaustive]
19pub enum CulvertBarrelShape {
20    /// Circular pipe. Its span and rise both equal the diameter.
21    Circular,
22    /// Rectangular box of span `B` and rise `D`.
23    Box,
24    /// Four-arc ellipse with span above rise: invert and crown arcs of one radius, two side arcs.
25    HorizontalEllipse,
26    /// Four-arc ellipse with rise above span: two end arcs of one radius, two side arcs.
27    VerticalEllipse,
28    /// Corrugated metal pipe-arch: bottom arc, two corner arcs and a top arc.
29    PipeArch,
30    /// One arc on a flat floor whose chord is the span.
31    Arch,
32}
33
34impl CulvertBarrelShape {
35    /// True for the shapes built from tangent circular arcs.
36    pub(crate) fn arced(self) -> bool {
37        matches!(
38            self,
39            Self::HorizontalEllipse | Self::VerticalEllipse | Self::PipeArch | Self::Arch
40        )
41    }
42}
43
44/// Admitted culvert barrel cross-section, with dimensions in metres.
45#[derive(Clone, Copy, Debug, PartialEq)]
46pub struct CulvertBarrel {
47    shape: CulvertBarrelShape,
48    span_m: f64,
49    rise_m: f64,
50    /// Given radii in constructor order. Only the first `given` entries are set.
51    radii_m: [f64; 2],
52    given: usize,
53    /// Sediment bed or open floor, if declared.
54    floor: Option<CulvertFloor>,
55}
56
57/// Dimensions scaled by this factor stay finite, so area, perimeter and moment never overflow.
58const OVERFLOW_MARGIN: f64 = 64.0;
59
60/// `2^-30`. The depth `D 2^-30` must stay a normal F64.
61const FLOOR_FRACTION: f64 = crate::structures::numerics::culvert::constants::CRITICAL_FLOOR;
62
63impl CulvertBarrel {
64    /// Admits a circular barrel of diameter `diameter_m`.
65    ///
66    /// Rejects a nonfinite or nonpositive diameter, a diameter whose `2^-30` fraction is subnormal,
67    /// and a diameter whose cube, scaled by 64, overflows F64.
68    pub fn circular(diameter_m: f64) -> Result<Self, StructureError> {
69        dimension("diameter_m", "diameter", diameter_m)?;
70        let fields = format!("diameter_m={diameter_m:?}");
71        scales(diameter_m, diameter_m, &[], &fields)?;
72        Ok(Self::new(
73            CulvertBarrelShape::Circular,
74            diameter_m,
75            diameter_m,
76            &[],
77        ))
78    }
79
80    /// Admits a box barrel of span `span_m` and rise `rise_m`.
81    ///
82    /// Rejects a nonfinite or nonpositive span or rise, a rise whose `2^-30` fraction is
83    /// subnormal, and dimensions whose `B D`, `2 (B + D)` or `B D^2`, scaled by 64, overflow F64.
84    pub fn rectangular_box(span_m: f64, rise_m: f64) -> Result<Self, StructureError> {
85        dimension("span_m", "span", span_m)?;
86        dimension("rise_m", "rise", rise_m)?;
87        let fields = format!("span_m={span_m:?},rise_m={rise_m:?}");
88        scales(span_m, rise_m, &[], &fields)?;
89        Ok(Self::new(CulvertBarrelShape::Box, span_m, rise_m, &[]))
90    }
91
92    /// A barrel from checked dimensions and at most two given radii.
93    fn new(shape: CulvertBarrelShape, span_m: f64, rise_m: f64, given: &[f64]) -> Self {
94        let mut radii_m = [0.0; 2];
95        for (slot, radius) in radii_m.iter_mut().zip(given) {
96            *slot = *radius;
97        }
98        Self {
99            shape,
100            span_m,
101            rise_m,
102            radii_m,
103            given: given.len().min(2),
104            floor: None,
105        }
106    }
107
108    /// Barrel shape.
109    pub fn shape(&self) -> CulvertBarrelShape {
110        self.shape
111    }
112
113    /// Radii the caller gave, in metres and constructor order.
114    ///
115    /// A horizontal ellipse gives its side radius, a vertical ellipse its end radius, and a
116    /// pipe-arch its corner and bottom radius. `None` for a circle, a box and a flat-floor arch.
117    pub fn given_radius_m(&self) -> Option<&[f64]> {
118        self.radii_m
119            .get(..self.given)
120            .filter(|radii| !radii.is_empty())
121    }
122
123    /// Horizontal width `B` in metres. A circle reports its diameter.
124    pub fn span_m(&self) -> f64 {
125        self.span_m
126    }
127
128    /// Vertical height `D` from invert to crown in metres. A circle reports its diameter.
129    pub fn rise_m(&self) -> f64 {
130        self.rise_m
131    }
132}
133
134fn dimension(field: &str, what: &str, value: f64) -> Result<(), StructureError> {
135    if value.is_finite() && value > 0.0 {
136        return Ok(());
137    }
138    Err(StructureError::definition(format!(
139        "{field}={value:?}: supply a finite positive barrel {what} in metres"
140    )))
141}
142
143/// Rejects a rise whose `2^-30` fraction is subnormal, and dimensions or radii whose area,
144/// perimeter, moment or cubed radius scale, times 64, overflows F64.
145///
146/// `radii` pairs each radius with the name the message gives it.
147fn scales(
148    span_m: f64,
149    rise_m: f64,
150    radii: &[(&str, f64)],
151    fields: &str,
152) -> Result<(), StructureError> {
153    // 2^-992 = MIN_POSITIVE 2^30 is exact. Below it, D 2^-30 is subnormal or rounds.
154    let smallest = f64::MIN_POSITIVE / FLOOR_FRACTION;
155    if rise_m < smallest {
156        return Err(StructureError::definition(format!(
157            "{fields}: rise times 2^-30 is subnormal. Supply a rise of at least {smallest:?} m"
158        )));
159    }
160    let scales = [
161        ("B D", span_m * rise_m),
162        ("2 (B + D)", 2.0 * (span_m + rise_m)),
163        ("B D^2", span_m * rise_m * rise_m),
164    ];
165    for (name, scale) in scales {
166        if !(scale * OVERFLOW_MARGIN).is_finite() {
167            return Err(StructureError::definition(format!(
168                "{fields}: {name} times 64 overflows F64. Supply smaller barrel dimensions in metres"
169            )));
170        }
171    }
172    for (name, radius) in radii {
173        if !(radius * radius * radius * OVERFLOW_MARGIN).is_finite() {
174            return Err(StructureError::definition(format!(
175                "{fields}: the {name} radius cubed times 64 overflows F64. Supply smaller barrel dimensions in metres"
176            )));
177        }
178    }
179    Ok(())
180}
181
182#[cfg(test)]
183mod tests {
184    use super::*;
185    use crate::structures::StructureInputErrorKind;
186
187    fn message(result: Result<CulvertBarrel, StructureError>) -> Option<String> {
188        match result {
189            Err(StructureError::InvalidInput {
190                kind: StructureInputErrorKind::Definition,
191                context,
192                element: None,
193            }) => Some(context),
194            _ => None,
195        }
196    }
197
198    #[test]
199    fn admission_names_the_field_value_and_action() {
200        let cases = [
201            (
202                CulvertBarrel::rectangular_box(1.0, -0.5),
203                "rise_m=-0.5: supply a finite positive barrel rise in metres",
204            ),
205            (
206                CulvertBarrel::rectangular_box(f64::NAN, 1.0),
207                "span_m=NaN: supply a finite positive barrel span in metres",
208            ),
209            (
210                CulvertBarrel::circular(0.0),
211                "diameter_m=0.0: supply a finite positive barrel diameter in metres",
212            ),
213            (
214                CulvertBarrel::circular(f64::INFINITY),
215                "diameter_m=inf: supply a finite positive barrel diameter in metres",
216            ),
217            (
218                CulvertBarrel::circular(1e-300),
219                "diameter_m=1e-300: rise times 2^-30 is subnormal",
220            ),
221            (
222                CulvertBarrel::rectangular_box(1e300, 1e10),
223                "span_m=1e300,rise_m=10000000000.0: B D times 64 overflows F64",
224            ),
225            (
226                CulvertBarrel::circular(1e103),
227                "diameter_m=1e103: B D^2 times 64 overflows F64",
228            ),
229        ];
230        for (result, expected) in cases {
231            let text = message(result);
232            assert!(
233                text.as_deref().is_some_and(|t| t.contains(expected)),
234                "{text:?} lacks {expected:?}"
235            );
236        }
237    }
238
239    #[test]
240    fn admitted_barrels_report_their_dimensions() -> Result<(), StructureError> {
241        let circle = CulvertBarrel::circular(0.3)?;
242        assert_eq!(circle.shape(), CulvertBarrelShape::Circular);
243        assert_eq!((circle.span_m(), circle.rise_m()), (0.3, 0.3));
244        let rectangle = CulvertBarrel::rectangular_box(2.5, 0.8)?;
245        assert_eq!(rectangle.shape(), CulvertBarrelShape::Box);
246        assert_eq!((rectangle.span_m(), rectangle.rise_m()), (2.5, 0.8));
247        for barrel in [circle, rectangle] {
248            assert_eq!(barrel.given_radius_m(), None);
249            assert!(!barrel.shape().arced());
250        }
251        // The smallest admitted rise keeps D 2^-30 normal.
252        let smallest = f64::MIN_POSITIVE / FLOOR_FRACTION;
253        assert!(CulvertBarrel::circular(smallest).is_ok());
254        assert!(CulvertBarrel::circular(smallest.next_down()).is_err());
255        Ok(())
256    }
257}