Skip to main content

hydr_structures/structures/culvert/
output.rs

1//! Certified barrel geometry tensors and their explicit host projection.
2
3use crate::structures::StructureError;
4use crate::structures::numerics::culvert::BarrelClient;
5use crate::structures::numerics::culvert::floor::FloorSection;
6use crate::structures::numerics::culvert::section::SectionIntervals;
7use crate::structures::tensor::codes;
8use crate::structures::tensor::culvert::TensorBarrelContext;
9use numr::dtype::DType;
10use numr::ops::ConditionalOps;
11use numr::runtime::Runtime;
12use numr::tensor::Tensor;
13use solvr::common::arithmetic::Interval;
14
15/// Stored endpoints of `interval`.
16fn ends<R: Runtime<DType = DType>>(interval: &Interval<R>) -> [Tensor<R>; 2] {
17    [interval.lower().clone(), interval.upper().clone()]
18}
19
20/// Flow state of one barrel row.
21#[derive(Clone, Copy, Debug, PartialEq, Eq)]
22pub enum BarrelState {
23    /// Depth zero. Every quantity is an exact zero, except `T = P = B` for a box and a
24    /// flat-floor arch, and `T = P = b`, `P_n = rho^(3/2) b` above a floor.
25    Dry,
26    /// Free surface below the crown, `0 < y < D`, with `D` the open rise above a floor.
27    Free,
28    /// Full from the crown upward, `y >= D`. Depth above the crown is pressure head.
29    Full,
30}
31
32/// Certified barrel geometry per row, as lower and upper F64 tensors of shape `[m]`.
33///
34/// Every exact value lies inside its `[lower, upper]` pair.
35pub struct CulvertBarrelGeometry<R: Runtime<DType = DType>> {
36    state: Tensor<R>,
37    area: [Tensor<R>; 2],
38    top_width: [Tensor<R>; 2],
39    perimeter: [Tensor<R>; 2],
40    wall: [Tensor<R>; 2],
41    floor: [Tensor<R>; 2],
42    weighted: [Tensor<R>; 2],
43    radius: [Tensor<R>; 2],
44    moment: [Tensor<R>; 2],
45}
46
47/// One projected row of [`CulvertBarrelGeometry`], each quantity as `(lower, upper)`.
48#[derive(Clone, Copy, Debug, PartialEq)]
49pub struct CulvertBarrelGeometryRow {
50    /// Flow state of the row.
51    pub state: BarrelState,
52    /// Flow area `A`, in square metres.
53    pub area_m2: (f64, f64),
54    /// Free-surface width `T`, in metres. Zero in the full state.
55    pub top_width_m: (f64, f64),
56    /// Wetted perimeter `P`, in metres: walls and bed, `P_w + b`.
57    pub wetted_perimeter_m: (f64, f64),
58    /// Wall perimeter `P_w`, in metres: `P` without the bed. Equal to `P` without a floor.
59    pub wall_perimeter_m: (f64, f64),
60    /// Wetted bed width `b`, in metres, at every depth of a barrel with a floor. Zero without one.
61    pub floor_width_m: (f64, f64),
62    /// Weighted perimeter `P_n = P_w + rho^(3/2) b`, in metres, with `rho` the bed-to-wall
63    /// Manning ratio. Manning friction with the wall `n` and `P_n` equals HDS-5 composite
64    /// roughness. Equal to `P` without a floor.
65    pub weighted_perimeter_m: (f64, f64),
66    /// Hydraulic radius `A / P`, in metres.
67    pub hydraulic_radius_m: (f64, f64),
68    /// Hydrostatic moment `integral from 0 to y of (y - eta) T(eta) d eta`, in cubic metres.
69    /// In the full state it is `A_full (y - D/2)` for a circle or a box, and `M(D) + A_full (y - D)`
70    /// for an arc barrel or a barrel with a floor, with `D` its open rise.
71    pub hydrostatic_moment_m3: (f64, f64),
72}
73
74impl<R: Runtime<DType = DType>> CulvertBarrelGeometry<R> {
75    /// Rows without a floor: the wall perimeter and the weighted perimeter are `P`.
76    pub(crate) fn from_section(section: &SectionIntervals<R>) -> numr::error::Result<Self> {
77        let g = &section.geometry;
78        let like = g.area.lower();
79        let zero = Tensor::<R>::zeros(like.shape(), DType::F64, like.device())?;
80        let perimeter = ends(&g.perimeter);
81        Ok(Self {
82            state: section.state.clone(),
83            area: ends(&g.area),
84            top_width: ends(&g.top_width),
85            wall: perimeter.clone(),
86            floor: [zero.clone(), zero],
87            weighted: perimeter.clone(),
88            perimeter,
89            radius: ends(&g.radius),
90            moment: ends(&g.moment),
91        })
92    }
93
94    /// `section` on rows without a floor, and the open section `open` of the context's floored
95    /// rows.
96    pub(crate) fn combine(
97        context: &TensorBarrelContext<R>,
98        section: &SectionIntervals<R>,
99        open: Option<FloorSection<R>>,
100    ) -> numr::error::Result<Self>
101    where
102        R::Client: BarrelClient<R>,
103    {
104        let base = Self::from_section(section)?;
105        let (Some(open), Some(rows)) = (open, &context.floor) else {
106            return Ok(base);
107        };
108        let c = &context.client;
109        let floored = &rows.floored;
110        let g = &open.geometry;
111        let pick = |interval: &Interval<R>, [lower, upper]: &[Tensor<R>; 2]| {
112            Ok::<_, numr::error::Error>([
113                c.where_cond(floored, interval.lower(), lower)?,
114                c.where_cond(floored, interval.upper(), upper)?,
115            ])
116        };
117        Ok(Self {
118            state: c.where_cond(floored, &open.state, &base.state)?,
119            area: pick(&g.area, &base.area)?,
120            top_width: pick(&g.top_width, &base.top_width)?,
121            perimeter: pick(&g.perimeter, &base.perimeter)?,
122            wall: pick(&g.wall, &base.wall)?,
123            floor: pick(&g.bed, &base.floor)?,
124            weighted: pick(&g.weighted, &base.weighted)?,
125            radius: pick(&g.radius, &base.radius)?,
126            moment: pick(&g.moment, &base.moment)?,
127        })
128    }
129
130    /// Lower and upper flow area `A`, in square metres.
131    pub fn area(&self) -> (&Tensor<R>, &Tensor<R>) {
132        (&self.area[0], &self.area[1])
133    }
134
135    /// Lower and upper free-surface width `T`, in metres.
136    pub fn top_width(&self) -> (&Tensor<R>, &Tensor<R>) {
137        (&self.top_width[0], &self.top_width[1])
138    }
139
140    /// Lower and upper wetted perimeter `P`, in metres.
141    pub fn wetted_perimeter(&self) -> (&Tensor<R>, &Tensor<R>) {
142        (&self.perimeter[0], &self.perimeter[1])
143    }
144
145    /// Lower and upper wall perimeter `P_w`, in metres.
146    pub fn wall_perimeter(&self) -> (&Tensor<R>, &Tensor<R>) {
147        (&self.wall[0], &self.wall[1])
148    }
149
150    /// Lower and upper wetted bed width `b`, in metres. Zero on rows without a floor.
151    pub fn floor_width(&self) -> (&Tensor<R>, &Tensor<R>) {
152        (&self.floor[0], &self.floor[1])
153    }
154
155    /// Lower and upper weighted perimeter `P_n = P_w + rho^(3/2) b`, in metres.
156    pub fn weighted_perimeter(&self) -> (&Tensor<R>, &Tensor<R>) {
157        (&self.weighted[0], &self.weighted[1])
158    }
159
160    /// Lower and upper hydraulic radius `A / P`, in metres.
161    pub fn hydraulic_radius(&self) -> (&Tensor<R>, &Tensor<R>) {
162        (&self.radius[0], &self.radius[1])
163    }
164
165    /// Lower and upper hydrostatic moment, in cubic metres.
166    pub fn hydrostatic_moment(&self) -> (&Tensor<R>, &Tensor<R>) {
167        (&self.moment[0], &self.moment[1])
168    }
169
170    /// Copies every row to the host.
171    pub fn project(&self) -> Result<Vec<CulvertBarrelGeometryRow>, StructureError> {
172        let read =
173            |t: &Tensor<R>| -> Result<Vec<f64>, StructureError> { Ok(t.try_to_vec::<f64>()?) };
174        let pair = |[lower, upper]: &[Tensor<R>; 2]| -> Result<Vec<(f64, f64)>, StructureError> {
175            Ok(read(lower)?.into_iter().zip(read(upper)?).collect())
176        };
177        let states = read(&self.state)?;
178        let area = pair(&self.area)?;
179        let top_width = pair(&self.top_width)?;
180        let perimeter = pair(&self.perimeter)?;
181        let wall = pair(&self.wall)?;
182        let floor = pair(&self.floor)?;
183        let weighted = pair(&self.weighted)?;
184        let radius = pair(&self.radius)?;
185        let moment = pair(&self.moment)?;
186        states
187            .iter()
188            .enumerate()
189            .map(|(row, &code)| {
190                let state = if code == codes::BARREL_DRY {
191                    BarrelState::Dry
192                } else if code == codes::BARREL_FREE {
193                    BarrelState::Free
194                } else if code == codes::BARREL_FULL {
195                    BarrelState::Full
196                } else {
197                    return Err(StructureError::numerical(format!(
198                        "barrel state code={code}: report this row, the code is not a barrel state"
199                    ))
200                    .at(row));
201                };
202                Ok(CulvertBarrelGeometryRow {
203                    state,
204                    area_m2: area[row],
205                    top_width_m: top_width[row],
206                    wetted_perimeter_m: perimeter[row],
207                    wall_perimeter_m: wall[row],
208                    floor_width_m: floor[row],
209                    weighted_perimeter_m: weighted[row],
210                    hydraulic_radius_m: radius[row],
211                    hydrostatic_moment_m3: moment[row],
212                })
213            })
214            .collect()
215    }
216}