Skip to main content

hydr_structures/structures/culvert/
batch.rs

1//! Public barrel geometry batch over compact `[m]` tensors.
2
3use super::input::{check_depths, check_discharges, check_gravity, check_manning, check_range};
4use super::{
5    CriticalDepthStatus, CulvertBarrel, CulvertBarrelDepth, CulvertBarrelGeometry,
6    NormalDepthStatus,
7};
8use crate::structures::StructureError;
9use crate::structures::numerics::culvert::{RowNames, critical, floor, normal, section};
10use crate::structures::tensor::culvert::TensorBarrelContext;
11use numr::dtype::DType;
12use numr::ops::{
13    CompareOps, CorrectlyRoundedOps, NextRepresentableOps, ScalarOps, TensorOps, TwoSumOps,
14};
15use numr::runtime::{Runtime, RuntimeClient};
16use numr::tensor::Tensor;
17use solvr::common::arithmetic::with_interval_arithmetic;
18use solvr::optimize::CertifiedBisectionAlgorithms;
19use std::fmt;
20use std::sync::Arc;
21
22/// Culvert barrels, one row each, with certified geometry queries.
23///
24/// Every quantity is an enclosure: the exact value at each represented depth lies inside its
25/// `[lower, upper]` pair. CPU and CUDA give bit-identical bounds.
26/// The free-surface domain is `[0, D)`. The crown `y = D` and every depth above it are full.
27/// Geometry, critical depth and normal depth cover every shape.
28#[derive(Clone)]
29pub struct CulvertBarrelBatch<R: Runtime<DType = DType>> {
30    barrels: Arc<[CulvertBarrel]>,
31    context: Arc<TensorBarrelContext<R>>,
32    /// Unit-rise rows of the same width, for the depth residuals in `s = y/D`.
33    unit: Arc<TensorBarrelContext<R>>,
34}
35
36impl<R: Runtime<DType = DType>> fmt::Debug for CulvertBarrelBatch<R> {
37    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38        f.debug_struct("CulvertBarrelBatch")
39            .field("barrels", &self.barrels)
40            .finish_non_exhaustive()
41    }
42}
43
44impl<R: Runtime<DType = DType>> CulvertBarrelBatch<R> {
45    /// Uploads the barrels, encloses their full-state constants and certifies the depth slope
46    /// floors and conveyance peak of each elliptical, pipe-arch and flat-floor arch barrel once,
47    /// and of the open section of each floored barrel other than a box.
48    ///
49    /// Rejects an empty barrel list and a runtime without F64 IEEE basic arithmetic,
50    /// fused multiply-add, correctly rounded elementary functions, or square roots rounded
51    /// to nearest. Rejects, naming its row, an arc or floored barrel whose certificate cannot be
52    /// established: its dimensions scaled to a unit rise fail admission, or its conveyance has
53    /// no certified single peak below the crown.
54    pub fn new(client: R::Client, barrels: Vec<CulvertBarrel>) -> Result<Self, StructureError>
55    where
56        R::Client: TensorOps<R>
57            + CompareOps<R>
58            + NextRepresentableOps<R>
59            + ScalarOps<R>
60            + TwoSumOps<R>
61            + CorrectlyRoundedOps<R>
62            + RuntimeClient<R>,
63    {
64        let context = TensorBarrelContext::new(client, &barrels)?;
65        let unit = context.unit()?;
66        Ok(Self {
67            barrels: barrels.into(),
68            context: Arc::new(context),
69            unit: Arc::new(unit),
70        })
71    }
72
73    /// Barrels in row order.
74    pub fn barrels(&self) -> &[CulvertBarrel] {
75        &self.barrels
76    }
77
78    /// Encloses the geometry at one depth per barrel, in metres above the invert, or above the
79    /// bed of a barrel with a floor.
80    ///
81    /// `depth_m` is an F64 `[m]` tensor on the batch device. A depth at or above the open rise is
82    /// full. A barrel with a floor reports the open section above its bed.
83    /// Rejects a negative or nonfinite depth, naming its row.
84    /// Returns `Numerical` when a bound overflows F64, as the full-state moment can for huge depths.
85    pub fn geometry(&self, depth_m: &Tensor<R>) -> Result<CulvertBarrelGeometry<R>, StructureError>
86    where
87        R::Client: TensorOps<R>
88            + CompareOps<R>
89            + NextRepresentableOps<R>
90            + ScalarOps<R>
91            + TwoSumOps<R>
92            + CorrectlyRoundedOps<R>
93            + RuntimeClient<R>,
94    {
95        let context = &*self.context;
96        check_depths(context, "depth_m", depth_m)?;
97        Ok(with_interval_arithmetic(
98            &context.client,
99            DType::F64,
100            "culvert barrel geometry",
101            |a| {
102                let section = section::at_depth(a, context, depth_m)?;
103                let open = match &context.floor {
104                    Some(rows) => Some(floor::at_depth(a, context, rows, depth_m)?),
105                    None => None,
106                };
107                Ok(CulvertBarrelGeometry::combine(context, &section, open)?)
108            },
109        )?)
110    }
111
112    /// Encloses the geometry over every depth in `[lower_m, upper_m]` per barrel.
113    ///
114    /// Each range lies inside the free-surface domain: `0 <= lower_m <= upper_m < D`, with `D`
115    /// the open rise and depths from the bed above a floor.
116    /// Rejects a range that reaches the crown. Split such a range at the crown.
117    /// The hydraulic radius bound divides the area range by the perimeter range, so it widens
118    /// with the range.
119    pub fn geometry_over(
120        &self,
121        lower_m: &Tensor<R>,
122        upper_m: &Tensor<R>,
123    ) -> Result<CulvertBarrelGeometry<R>, StructureError>
124    where
125        R::Client: TensorOps<R>
126            + CompareOps<R>
127            + NextRepresentableOps<R>
128            + ScalarOps<R>
129            + TwoSumOps<R>
130            + CorrectlyRoundedOps<R>
131            + RuntimeClient<R>,
132    {
133        let context = &*self.context;
134        check_range(&self.barrels, context, lower_m, upper_m)?;
135        Ok(with_interval_arithmetic(
136            &context.client,
137            DType::F64,
138            "culvert barrel range geometry",
139            |a| {
140                let section = section::over_depth(a, context, lower_m, upper_m)?;
141                let open = match &context.floor {
142                    Some(rows) => Some(floor::over_depth(a, context, rows, lower_m, upper_m)?),
143                    None => None,
144                };
145                Ok(CulvertBarrelGeometry::combine(context, &section, open)?)
146            },
147        )?)
148    }
149
150    /// Encloses the full-state geometry at the crown `y = D` of every barrel, with `D` the open
151    /// rise above a floor.
152    ///
153    /// Area, perimeter and radius hold for every full depth. The moment is `A_full D / 2` for a
154    /// circle and a box, and the crown moment `M(D)` for an arc barrel or a barrel with a floor.
155    pub fn full_geometry(&self) -> Result<CulvertBarrelGeometry<R>, StructureError>
156    where
157        R::Client: TensorOps<R>
158            + CompareOps<R>
159            + NextRepresentableOps<R>
160            + ScalarOps<R>
161            + TwoSumOps<R>
162            + CorrectlyRoundedOps<R>
163            + RuntimeClient<R>,
164    {
165        let context = &*self.context;
166        Ok(with_interval_arithmetic(
167            &context.client,
168            DType::F64,
169            "culvert barrel full geometry",
170            |a| {
171                let section = section::at_depth(a, context, &context.rise)?;
172                let open = match &context.floor {
173                    Some(rows) => Some(floor::at_depth(a, context, rows, &rows.top)?),
174                    None => None,
175                };
176                Ok(CulvertBarrelGeometry::combine(context, &section, open)?)
177            },
178        )?)
179    }
180
181    /// Encloses the critical depth `Q^2 T = g A^3` of every barrel, in metres above the invert,
182    /// or above the bed of a barrel with a floor.
183    ///
184    /// `discharge_m3_per_s` is an F64 `[m]` tensor of per-barrel discharge magnitudes on the
185    /// batch device. [`CriticalDepthStatus`] states what each row's enclosure holds. A barrel
186    /// with a floor solves on its open section of rise `D' = D - h`.
187    /// Rejects a negative or nonfinite discharge, naming its row, and a nonfinite or nonpositive
188    /// gravity.
189    pub fn critical_depth(
190        &self,
191        discharge_m3_per_s: &Tensor<R>,
192        gravity_m_per_s2: f64,
193    ) -> Result<CulvertBarrelDepth<R, CriticalDepthStatus>, StructureError>
194    where
195        R::Client: TensorOps<R>
196            + CompareOps<R>
197            + NextRepresentableOps<R>
198            + ScalarOps<R>
199            + TwoSumOps<R>
200            + CorrectlyRoundedOps<R>
201            + RuntimeClient<R>
202            + CertifiedBisectionAlgorithms<R>,
203    {
204        let context = &*self.context;
205        check_gravity(gravity_m_per_s2)?;
206        check_discharges(context, "discharge_m3_per_s", discharge_m3_per_s)?;
207        let gravity = context.constant(gravity_m_per_s2)?;
208        let depths = critical::solve(
209            RowNames::new(&self.barrels),
210            context,
211            &self.unit,
212            discharge_m3_per_s,
213            &gravity,
214        )?;
215        Ok(CulvertBarrelDepth::from_depths(depths))
216    }
217
218    /// Encloses the Manning normal depth `Q = (1/n) A R^(2/3) sqrt(S)` of every barrel, in metres
219    /// above the invert, or above the bed of a barrel with a floor.
220    ///
221    /// `discharge_m3_per_s` holds per-barrel discharge magnitudes, `manning_n` the roughness in
222    /// `s/m^(1/3)` and `slope` the barrel slope, positive downstream. All are F64 `[m]` tensors on
223    /// the batch device. The normal depth is the root on the rising limb of the conveyance.
224    /// [`NormalDepthStatus`] states what each row's enclosure holds. A zero or adverse slope
225    /// reports `NonPositiveSlope` whatever the discharge.
226    /// A barrel with a floor solves on its open section with `manning_n` the wall `n` and the
227    /// weighted perimeter `P_n = P_w + rho^(3/2) b` in place of `P`: `Q = (1/n) A^(5/3)
228    /// P_n^(-2/3) sqrt(S)`.
229    /// Rejects a negative or nonfinite discharge, a nonpositive or nonfinite `n` and a nonfinite
230    /// slope, naming the row.
231    pub fn normal_depth(
232        &self,
233        discharge_m3_per_s: &Tensor<R>,
234        manning_n: &Tensor<R>,
235        slope: &Tensor<R>,
236    ) -> Result<CulvertBarrelDepth<R, NormalDepthStatus>, StructureError>
237    where
238        R::Client: TensorOps<R>
239            + CompareOps<R>
240            + NextRepresentableOps<R>
241            + ScalarOps<R>
242            + TwoSumOps<R>
243            + CorrectlyRoundedOps<R>
244            + RuntimeClient<R>
245            + CertifiedBisectionAlgorithms<R>,
246    {
247        let context = &*self.context;
248        check_manning(
249            context,
250            [
251                ("discharge_m3_per_s", discharge_m3_per_s),
252                ("manning_n", manning_n),
253                ("slope", slope),
254            ],
255        )?;
256        let depths = normal::solve(
257            RowNames::new(&self.barrels),
258            context,
259            &self.unit,
260            discharge_m3_per_s,
261            manning_n,
262            slope,
263        )?;
264        Ok(CulvertBarrelDepth::from_depths(depths))
265    }
266
267    /// Depth certificates of every row, copied to the host, for reference checks.
268    #[doc(hidden)]
269    pub fn depth_certificates(&self) -> Result<Vec<BarrelDepthCertificate>, StructureError> {
270        let context = &*self.context;
271        let read = |t: &Tensor<R>| t.try_to_vec::<f64>();
272        let [peak_lower, peak_upper] = &context.conveyance_peak;
273        let [log_lower, log_upper] = &context.log_peak;
274        let columns = [
275            read(&context.critical_top)?,
276            read(&context.critical_slope)?,
277            read(&context.normal_top)?,
278            read(&context.normal_slope)?,
279            read(peak_lower)?,
280            read(peak_upper)?,
281            read(log_lower)?,
282            read(log_upper)?,
283        ];
284        let knots = context
285            .limb
286            .iter()
287            .flatten()
288            .map(|[knot, floor]| Ok((read(knot)?, read(floor)?)))
289            .collect::<Result<Vec<_>, numr::error::Error>>()?;
290        let at = |column: &[f64], row: usize| column.get(row).copied().unwrap_or(f64::NAN);
291        Ok((0..context.width())
292            .map(|row| {
293                let [
294                    critical_top,
295                    critical_slope,
296                    normal_top,
297                    normal_slope,
298                    low,
299                    high,
300                    log_low,
301                    log_high,
302                ] = columns.each_ref().map(|column| at(column, row));
303                BarrelDepthCertificate {
304                    critical_top,
305                    critical_slope,
306                    normal_top,
307                    normal_slope,
308                    peak: (low, high),
309                    log_peak: (log_low, log_high),
310                    limb: knots
311                        .iter()
312                        .map(|(knot, floor)| (at(knot, row), at(floor, row)))
313                        .collect(),
314                }
315            })
316            .collect())
317    }
318}
319
320/// Depth certificate of one barrel row, in `s = y/D` or `s = y/D'` above a floor.
321#[doc(hidden)]
322#[derive(Clone, Debug, PartialEq)]
323pub struct BarrelDepthCertificate {
324    /// Upper end of the critical-depth domain.
325    pub critical_top: f64,
326    /// Lower bound of `d r_c / ds` on the critical domain.
327    pub critical_slope: f64,
328    /// Upper end `s_N` of the normal-depth domain.
329    pub normal_top: f64,
330    /// Lower bound of `d r_n / ds` on the normal domain.
331    pub normal_slope: f64,
332    /// Enclosure of the conveyance peak.
333    pub peak: (f64, f64),
334    /// Enclosure of the log peak conveyance: unit geometry without a floor, frame geometry
335    /// above one.
336    pub log_peak: (f64, f64),
337    /// `(s_j, kappa_j)` per rising-limb knot: `kappa_j` bounds `d r_n / ds` below on
338    /// `[2^-30, s_j]`. Empty when no row of the batch is an arc barrel or a floored circle.
339    pub limb: Vec<(f64, f64)>,
340}