Skip to main content

hydr_structures/structures/culvert/
depth.rs

1//! Certified barrel depth tensors, their typed statuses and their explicit host projection.
2
3use crate::structures::StructureError;
4use crate::structures::numerics::culvert::BarrelDepths;
5use crate::structures::tensor::codes;
6use numr::dtype::DType;
7use numr::runtime::Runtime;
8use numr::tensor::Tensor;
9use std::fmt::Debug;
10use std::marker::PhantomData;
11
12mod sealed {
13    /// Decodes a per-row status code. Implemented only by the barrel depth status enums.
14    pub trait Sealed: Sized {
15        fn from_code(code: f64) -> Option<Self>;
16    }
17}
18
19/// Typed status of one row of a [`CulvertBarrelDepth`].
20pub trait BarrelDepthStatus: sealed::Sealed + Copy + Debug + PartialEq {}
21
22/// Outcome of a critical-depth query, `Q^2 T = g A^3`, for one barrel.
23///
24/// The search domain is `[D 2^-30, top]`, with `top = D (1 - 2^-53)` for a circle and `D` for
25/// a box. A circle has one critical depth below the crown for every `Q > 0`. A box has one only
26/// for `Q <= sqrt(g) B D^(3/2)`. Above a floor the open rise `D'` replaces `D`, depths run up
27/// from the bed, and a circle or arc barrel ends its domain at `D' (1 - 2^-52)`.
28#[derive(Clone, Copy, Debug, PartialEq, Eq)]
29pub enum CriticalDepthStatus {
30    /// Zero discharge. The depth is exactly `[0, 0]`.
31    Dry,
32    /// Certified root inside the search domain.
33    Solved,
34    /// The root lies at or below the floor `D 2^-30`. The enclosure starts at 0.
35    BelowFloor,
36    /// The residual at the domain top contains zero. A circle root lies in the enclosure, which
37    /// ends at `D`. A box root lies in it when `Q` does not exceed the crown limit.
38    AtCrown,
39    /// Certified above the domain top. A circle root lies within `2^-53 D` of the crown, in the
40    /// enclosure `[D (1 - 2^-53), D]`. Above a floor the enclosure is `[D' (1 - 2^-52), D']`.
41    /// A box has no free-surface critical depth and no enclosure.
42    AboveCrown,
43}
44
45impl sealed::Sealed for CriticalDepthStatus {
46    fn from_code(code: f64) -> Option<Self> {
47        [
48            (codes::CRITICAL_DRY, Self::Dry),
49            (codes::CRITICAL_SOLVED, Self::Solved),
50            (codes::CRITICAL_BELOW_FLOOR, Self::BelowFloor),
51            (codes::CRITICAL_AT_CROWN, Self::AtCrown),
52            (codes::CRITICAL_ABOVE_CROWN, Self::AboveCrown),
53        ]
54        .into_iter()
55        .find_map(|(value, status)| (value == code).then_some(status))
56    }
57}
58
59impl BarrelDepthStatus for CriticalDepthStatus {}
60
61/// Outcome of a Manning normal-depth query, `Q = (1/n) A R^(2/3) sqrt(S)`, for one barrel.
62///
63/// The normal depth is the root on the rising limb of the conveyance `K = A^(5/3) / P^(2/3)`.
64/// The search domain is `[D 2^-30, top]`, with `top = 0.93818 D` for a circle and `D` for a box.
65/// Circle conveyance peaks at `s_K D`, `s_K = 0.9381812`, above the full-barrel conveyance,
66/// and falls from there to the crown. Box conveyance rises up to its open-section limit at the
67/// crown, which exceeds the full-barrel conveyance. Full-barrel flow is the caller's branch.
68/// Above a floor the open rise `D'` replaces `D`, depths run up from the bed, and the
69/// conveyance is `A^(5/3) / P_n^(2/3)` with the wall `n`.
70#[derive(Clone, Copy, Debug, PartialEq, Eq)]
71pub enum NormalDepthStatus {
72    /// Zero discharge on a positive slope. The depth is exactly `[0, 0]`.
73    Dry,
74    /// Certified root inside the search domain.
75    Solved,
76    /// The root lies at or below the floor `D 2^-30`. The enclosure starts at 0.
77    BelowFloor,
78    /// The target lies near the top of the rising limb. A rising-limb root, when one exists,
79    /// lies in the enclosure. The enclosure ends at `s_K D` rounded up for a circle or an arc
80    /// barrel, with `s_K` the upper end of its conveyance peak enclosure, and at `D` for a box.
81    NearCapacity,
82    /// The target exceeds the peak conveyance of a circle or an arc barrel, or the box crown
83    /// limit. No free-surface uniform flow exists and the row has no enclosure.
84    AboveCapacity,
85    /// The slope is zero or adverse. No normal depth exists and the row has no enclosure.
86    NonPositiveSlope,
87}
88
89impl sealed::Sealed for NormalDepthStatus {
90    fn from_code(code: f64) -> Option<Self> {
91        [
92            (codes::NORMAL_DRY, Self::Dry),
93            (codes::NORMAL_SOLVED, Self::Solved),
94            (codes::NORMAL_BELOW_FLOOR, Self::BelowFloor),
95            (codes::NORMAL_NEAR_CAPACITY, Self::NearCapacity),
96            (codes::NORMAL_ABOVE_CAPACITY, Self::AboveCapacity),
97            (codes::NORMAL_NON_POSITIVE_SLOPE, Self::NonPositiveSlope),
98        ]
99        .into_iter()
100        .find_map(|(value, status)| (value == code).then_some(status))
101    }
102}
103
104impl BarrelDepthStatus for NormalDepthStatus {}
105
106/// Certified depth per barrel row, as status codes and lower and upper F64 `[m]` tensors.
107///
108/// Every exact root that the status places in an enclosure lies inside its `[lower, upper]`
109/// pair, in metres above the invert, or above the bed of a barrel with a floor. Rows without an
110/// enclosure hold NaN endpoints.
111pub struct CulvertBarrelDepth<R: Runtime<DType = DType>, S: BarrelDepthStatus> {
112    status: Tensor<R>,
113    lower: Tensor<R>,
114    upper: Tensor<R>,
115    marker: PhantomData<S>,
116}
117
118/// One projected row of a [`CulvertBarrelDepth`].
119#[derive(Clone, Copy, Debug, PartialEq)]
120pub struct CulvertBarrelDepthRow<S: BarrelDepthStatus> {
121    /// Outcome of the row.
122    pub status: S,
123    /// `(lower, upper)` depth in metres, or `None` when the status carries no enclosure.
124    pub depth_m: Option<(f64, f64)>,
125}
126
127impl<R: Runtime<DType = DType>, S: BarrelDepthStatus> CulvertBarrelDepth<R, S> {
128    /// Wraps solver output whose codes decode as `S`.
129    pub(crate) fn from_depths(depths: BarrelDepths<R>) -> Self {
130        Self {
131            status: depths.status,
132            lower: depths.lower,
133            upper: depths.upper,
134            marker: PhantomData,
135        }
136    }
137
138    /// Lower and upper depth in metres. Rows without an enclosure hold NaN.
139    pub fn depth_m(&self) -> (&Tensor<R>, &Tensor<R>) {
140        (&self.lower, &self.upper)
141    }
142
143    /// Copies every row to the host.
144    pub fn project(&self) -> Result<Vec<CulvertBarrelDepthRow<S>>, StructureError> {
145        let status = self.status.try_to_vec::<f64>()?;
146        let lower = self.lower.try_to_vec::<f64>()?;
147        let upper = self.upper.try_to_vec::<f64>()?;
148        status
149            .iter()
150            .zip(lower.iter().zip(&upper))
151            .enumerate()
152            .map(|(row, (&code, (&low, &high)))| {
153                let status = <S as sealed::Sealed>::from_code(code).ok_or_else(|| {
154                    StructureError::numerical(format!(
155                        "depth status code={code}: report this row, the code is not a depth status"
156                    ))
157                    .at(row)
158                })?;
159                let depth_m = (!low.is_nan()).then_some((low, high));
160                Ok(CulvertBarrelDepthRow { status, depth_m })
161            })
162            .collect()
163    }
164}