Skip to main content

hydr_structures/structures/culvert/outlet/
batch.rs

1//! Public outlet-control batch over compact `[m]` tensors.
2
3use super::{CulvertOutletHeadwater, CulvertOutletJump, CulvertOutletRow};
4use crate::structures::culvert::input::{check_depths, check_discharges};
5use crate::structures::numerics::culvert::RowNames;
6use crate::structures::numerics::culvert::outlet::{self, Accuracy, jump};
7use crate::structures::tensor::culvert::{TensorBarrelContext, TensorOutletContext};
8use crate::structures::{CulvertBarrel, StructureError};
9use numr::dtype::DType;
10use numr::ops::{
11    CompareOps, CorrectlyRoundedOps, NextRepresentableOps, ScalarOps, TensorOps, TwoSumOps,
12};
13use numr::runtime::{Runtime, RuntimeClient};
14use numr::tensor::Tensor;
15use solvr::integrate::CertifiedSimpsonAlgorithms;
16use solvr::optimize::CertifiedBisectionAlgorithms;
17use std::fmt;
18use std::sync::Arc;
19
20/// Outlet-control rows, one barrel each, with certified headwater and jump queries.
21///
22/// Every bound is an enclosure: the exact value of the outlet-control model at each represented
23/// input lies inside its `[lower, upper]` pair. CPU and CUDA give bit-identical bounds.
24#[derive(Clone)]
25pub struct CulvertOutletBatch<R: Runtime<DType = DType>> {
26    rows: Arc<[CulvertOutletRow]>,
27    barrels: Arc<[CulvertBarrel]>,
28    barrel: Arc<TensorBarrelContext<R>>,
29    unit: Arc<TensorBarrelContext<R>>,
30    outlet: Arc<TensorOutletContext<R>>,
31}
32
33impl<R: Runtime<DType = DType>> fmt::Debug for CulvertOutletBatch<R> {
34    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35        f.debug_struct("CulvertOutletBatch")
36            .field("rows", &self.rows)
37            .finish_non_exhaustive()
38    }
39}
40
41impl<R: Runtime<DType = DType>> CulvertOutletBatch<R> {
42    /// Uploads and admits the rows.
43    ///
44    /// Rejects an empty row list, a nonfinite or nonpositive length, Manning `n` or gravity, a
45    /// nonfinite or negative entrance loss, a nonfinite slope, and an adverse barrel whose
46    /// outlet invert sits more than `D/2` above its inlet invert. Each rejection names the row.
47    /// Rejects a runtime without the barrel batch's F64 contracts.
48    pub fn new(client: R::Client, rows: Vec<CulvertOutletRow>) -> Result<Self, StructureError>
49    where
50        R::Client: TensorOps<R>
51            + CompareOps<R>
52            + NextRepresentableOps<R>
53            + ScalarOps<R>
54            + TwoSumOps<R>
55            + CorrectlyRoundedOps<R>
56            + RuntimeClient<R>,
57    {
58        if rows.is_empty() {
59            return Err(StructureError::definition(
60                "rows=[]: supply at least one culvert outlet row",
61            ));
62        }
63        for (index, row) in rows.iter().enumerate() {
64            row.check().map_err(|error| error.at(index))?;
65        }
66        let barrels: Arc<[CulvertBarrel]> = rows.iter().map(|row| row.barrel).collect();
67        let barrel = TensorBarrelContext::new(client, &barrels)?;
68        let unit = barrel.unit()?;
69        let outlet = outlet::prepare(&barrel, &rows)?;
70        Ok(Self {
71            rows: rows.into(),
72            barrels,
73            barrel: Arc::new(barrel),
74            unit: Arc::new(unit),
75            outlet: Arc::new(outlet),
76        })
77    }
78
79    /// Rows in order.
80    pub fn rows(&self) -> &[CulvertOutletRow] {
81        &self.rows
82    }
83
84    fn check(&self, discharge: &Tensor<R>, tailwater: &Tensor<R>) -> Result<(), StructureError>
85    where
86        R::Client: TensorOps<R>
87            + CompareOps<R>
88            + NextRepresentableOps<R>
89            + ScalarOps<R>
90            + TwoSumOps<R>
91            + CorrectlyRoundedOps<R>
92            + RuntimeClient<R>,
93    {
94        check_discharges(&self.barrel, "discharge_m3_per_s", discharge)?;
95        check_depths(&self.barrel, "tailwater_m", tailwater)
96    }
97
98    /// Encloses the outlet-control headwater per row at one discharge and tailwater per barrel.
99    ///
100    /// `discharge_m3_per_s` holds per-barrel discharge magnitudes and `tailwater_m` the
101    /// tailwater depth above the outlet invert. Both are F64 `[m]` tensors on the batch device.
102    /// Rejects a negative or nonfinite value, naming its row. Rows whose march does not resolve
103    /// report `Unresolved` with NaN bounds.
104    pub fn headwater(
105        &self,
106        discharge_m3_per_s: &Tensor<R>,
107        tailwater_m: &Tensor<R>,
108    ) -> Result<CulvertOutletHeadwater<R>, StructureError>
109    where
110        R::Client: TensorOps<R>
111            + CompareOps<R>
112            + NextRepresentableOps<R>
113            + ScalarOps<R>
114            + TwoSumOps<R>
115            + CorrectlyRoundedOps<R>
116            + RuntimeClient<R>
117            + CertifiedBisectionAlgorithms<R>
118            + CertifiedSimpsonAlgorithms<R>,
119    {
120        self.check(discharge_m3_per_s, tailwater_m)?;
121        let march = outlet::march(
122            RowNames::new(&self.barrels),
123            &self.barrel,
124            &self.unit,
125            &self.outlet,
126            discharge_m3_per_s,
127            tailwater_m,
128            Accuracy::Fine,
129        )?;
130        Ok(CulvertOutletHeadwater::from_headwater(march.headwater))
131    }
132
133    /// Classifies the hydraulic jump of every inlet-critical row and encloses its position.
134    ///
135    /// Takes the inputs of [`CulvertOutletBatch::headwater`] and runs the same march first. The
136    /// result carries that march's headwater too.
137    pub fn jump(
138        &self,
139        discharge_m3_per_s: &Tensor<R>,
140        tailwater_m: &Tensor<R>,
141    ) -> Result<CulvertOutletJump<R>, StructureError>
142    where
143        R::Client: TensorOps<R>
144            + CompareOps<R>
145            + NextRepresentableOps<R>
146            + ScalarOps<R>
147            + TwoSumOps<R>
148            + CorrectlyRoundedOps<R>
149            + RuntimeClient<R>
150            + CertifiedBisectionAlgorithms<R>
151            + CertifiedSimpsonAlgorithms<R>,
152    {
153        self.check(discharge_m3_per_s, tailwater_m)?;
154        let march = outlet::march(
155            RowNames::new(&self.barrels),
156            &self.barrel,
157            &self.unit,
158            &self.outlet,
159            discharge_m3_per_s,
160            tailwater_m,
161            Accuracy::Fine,
162        )?;
163        let found = jump::jump(
164            &self.barrel,
165            &self.outlet,
166            &march,
167            discharge_m3_per_s,
168            tailwater_m,
169        )?;
170        Ok(CulvertOutletJump::from_jump(
171            found,
172            CulvertOutletHeadwater::from_headwater(march.headwater),
173        ))
174    }
175}