Skip to main content

hydr_structures/structures/culvert/outlet/
output.rs

1//! Certified outlet headwater and jump tensors, their status per row and their host projection.
2
3use crate::structures::StructureError;
4use crate::structures::numerics::culvert::outlet::OutletHeadwater;
5use crate::structures::numerics::culvert::outlet::jump::OutletJump;
6use crate::structures::tensor::codes;
7use numr::dtype::DType;
8use numr::runtime::Runtime;
9use numr::tensor::Tensor;
10
11/// Outlet-control flow state of one row.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum OutletRegime {
14    /// Zero discharge. The headwater is the still level `max(TW - S L, 0)`.
15    NoFlow,
16    /// The barrel flows full from the outlet to the inlet.
17    Full,
18    /// A free-surface profile occupies part or all of the barrel.
19    PartlyFull,
20    /// A steep barrel runs at critical depth at the inlet: `HW_o = yc + (1 + ke) Vc^2 / (2 g)`.
21    /// Critical depth is capped at the crown. A crown tie row holds the hull of this value and
22    /// the full-barrel value.
23    InletCritical,
24    /// A certified comparison of the march did not resolve. Bounds are NaN.
25    Unresolved,
26}
27
28impl OutletRegime {
29    fn from_code(code: f64) -> Option<Self> {
30        [
31            (codes::OUTLET_NO_FLOW, Self::NoFlow),
32            (codes::OUTLET_FULL, Self::Full),
33            (codes::OUTLET_PARTLY_FULL, Self::PartlyFull),
34            (codes::OUTLET_INLET_CRITICAL, Self::InletCritical),
35            (codes::OUTLET_UNRESOLVED, Self::Unresolved),
36        ]
37        .into_iter()
38        .find_map(|(value, regime)| (value == code).then_some(regime))
39    }
40}
41
42/// Certified outlet-control headwater per row, as regime codes and lower and upper F64 `[m]`
43/// tensors in metres above the inlet invert.
44pub struct CulvertOutletHeadwater<R: Runtime<DType = DType>> {
45    status: Tensor<R>,
46    inlet: [Tensor<R>; 2],
47    headwater: [Tensor<R>; 2],
48}
49
50/// One projected row of a [`CulvertOutletHeadwater`].
51#[derive(Clone, Copy, Debug, PartialEq)]
52pub struct CulvertOutletHeadwaterRow {
53    /// Flow state of the row.
54    pub regime: OutletRegime,
55    /// `(lower, upper)` inlet head `h_in` in metres above the inlet invert: the depth, or the
56    /// pressure head of a full inlet.
57    pub inlet_head_m: (f64, f64),
58    /// `(lower, upper)` headwater `HW_o = h_in + (1 + ke) V_in^2 / (2 g)` in metres above the
59    /// inlet invert.
60    pub headwater_m: (f64, f64),
61}
62
63fn regime_error(code: f64, row: usize) -> StructureError {
64    StructureError::numerical(format!(
65        "outlet regime code={code}: report this row, the code is not an outlet regime"
66    ))
67    .at(row)
68}
69
70impl<R: Runtime<DType = DType>> CulvertOutletHeadwater<R> {
71    pub(crate) fn from_headwater(headwater: OutletHeadwater<R>) -> Self {
72        Self {
73            status: headwater.status,
74            inlet: headwater.inlet,
75            headwater: headwater.headwater,
76        }
77    }
78
79    /// Lower and upper headwater in metres above the inlet invert.
80    pub fn headwater_m(&self) -> (&Tensor<R>, &Tensor<R>) {
81        (&self.headwater[0], &self.headwater[1])
82    }
83
84    /// Lower and upper inlet head in metres above the inlet invert.
85    pub fn inlet_head_m(&self) -> (&Tensor<R>, &Tensor<R>) {
86        (&self.inlet[0], &self.inlet[1])
87    }
88
89    /// Copies every row to the host.
90    pub fn project(&self) -> Result<Vec<CulvertOutletHeadwaterRow>, StructureError> {
91        let status = self.status.try_to_vec::<f64>()?;
92        let inlet = [
93            self.inlet[0].try_to_vec::<f64>()?,
94            self.inlet[1].try_to_vec::<f64>()?,
95        ];
96        let headwater = [
97            self.headwater[0].try_to_vec::<f64>()?,
98            self.headwater[1].try_to_vec::<f64>()?,
99        ];
100        status
101            .iter()
102            .enumerate()
103            .map(|(row, &code)| {
104                let regime =
105                    OutletRegime::from_code(code).ok_or_else(|| regime_error(code, row))?;
106                let at = |values: &[Vec<f64>; 2]| -> (f64, f64) {
107                    (
108                        values[0].get(row).copied().unwrap_or(f64::NAN),
109                        values[1].get(row).copied().unwrap_or(f64::NAN),
110                    )
111                };
112                Ok(CulvertOutletHeadwaterRow {
113                    regime,
114                    inlet_head_m: at(&inlet),
115                    headwater_m: at(&headwater),
116                })
117            })
118            .collect()
119    }
120}
121
122/// Hydraulic jump state of one row.
123#[derive(Clone, Copy, Debug, PartialEq, Eq)]
124pub enum JumpStatus {
125    /// The row is not inlet-critical, so no supercritical profile leaves the inlet.
126    NotSteep,
127    /// Supercritical flow leaves the outlet. Any jump lies downstream of the barrel.
128    Supercritical,
129    /// A jump sits inside the barrel.
130    InBarrel,
131    /// A certified comparison did not resolve, the subcritical profile includes a full outlet
132    /// segment, or the row is a crown tie.
133    Unresolved,
134}
135
136impl JumpStatus {
137    fn from_code(code: f64) -> Option<Self> {
138        [
139            (codes::JUMP_NOT_STEEP, Self::NotSteep),
140            (codes::JUMP_SUPERCRITICAL, Self::Supercritical),
141            (codes::JUMP_IN_BARREL, Self::InBarrel),
142            (codes::JUMP_UNRESOLVED, Self::Unresolved),
143        ]
144        .into_iter()
145        .find_map(|(value, status)| (value == code).then_some(status))
146    }
147}
148
149/// Certified jump position and depths per row, as status codes and F64 `[m]` bound tensors.
150///
151/// It also carries the headwater of the march it ran on.
152pub struct CulvertOutletJump<R: Runtime<DType = DType>> {
153    headwater: CulvertOutletHeadwater<R>,
154    status: Tensor<R>,
155    position: [Tensor<R>; 2],
156    upstream: [Tensor<R>; 2],
157    downstream: [Tensor<R>; 2],
158    outlet: [Tensor<R>; 2],
159}
160
161/// One projected row of a [`CulvertOutletJump`]. Fields that do not apply hold NaN.
162#[derive(Clone, Copy, Debug, PartialEq)]
163pub struct CulvertOutletJumpRow {
164    /// Jump state of the row.
165    pub status: JumpStatus,
166    /// `(lower, upper)` jump position in metres downstream of the inlet, for `InBarrel`.
167    pub position_m: (f64, f64),
168    /// `(lower, upper)` supercritical depth just upstream of the jump, for `InBarrel`.
169    pub upstream_depth_m: (f64, f64),
170    /// `(lower, upper)` subcritical depth just downstream of the jump, for `InBarrel`.
171    pub downstream_depth_m: (f64, f64),
172    /// `(lower, upper)` supercritical depth at the outlet, for `Supercritical`.
173    pub outlet_depth_m: (f64, f64),
174}
175
176impl<R: Runtime<DType = DType>> CulvertOutletJump<R> {
177    pub(crate) fn from_jump(jump: OutletJump<R>, headwater: CulvertOutletHeadwater<R>) -> Self {
178        Self {
179            headwater,
180            status: jump.status,
181            position: jump.position,
182            upstream: jump.upstream,
183            downstream: jump.downstream,
184            outlet: jump.outlet,
185        }
186    }
187
188    /// Outlet-control headwater of the same rows and inputs.
189    pub fn headwater(&self) -> &CulvertOutletHeadwater<R> {
190        &self.headwater
191    }
192
193    /// Lower and upper jump position in metres downstream of the inlet.
194    pub fn position_m(&self) -> (&Tensor<R>, &Tensor<R>) {
195        (&self.position[0], &self.position[1])
196    }
197
198    /// Copies every row to the host.
199    pub fn project(&self) -> Result<Vec<CulvertOutletJumpRow>, StructureError> {
200        let status = self.status.try_to_vec::<f64>()?;
201        let read = |pair: &[Tensor<R>; 2]| -> Result<[Vec<f64>; 2], StructureError> {
202            Ok([pair[0].try_to_vec::<f64>()?, pair[1].try_to_vec::<f64>()?])
203        };
204        let position = read(&self.position)?;
205        let upstream = read(&self.upstream)?;
206        let downstream = read(&self.downstream)?;
207        let outlet = read(&self.outlet)?;
208        status
209            .iter()
210            .enumerate()
211            .map(|(row, &code)| {
212                let status = JumpStatus::from_code(code).ok_or_else(|| {
213                    StructureError::numerical(format!(
214                        "jump status code={code}: report this row, the code is not a jump status"
215                    ))
216                    .at(row)
217                })?;
218                let at = |values: &[Vec<f64>; 2]| -> (f64, f64) {
219                    (
220                        values[0].get(row).copied().unwrap_or(f64::NAN),
221                        values[1].get(row).copied().unwrap_or(f64::NAN),
222                    )
223                };
224                Ok(CulvertOutletJumpRow {
225                    status,
226                    position_m: at(&position),
227                    upstream_depth_m: at(&upstream),
228                    downstream_depth_m: at(&downstream),
229                    outlet_depth_m: at(&outlet),
230                })
231            })
232            .collect()
233    }
234}