Skip to main content

hydr_structures/structures/numerics/culvert/
mod.rs

1//! Certified closed-conduit barrel geometry inside checked interval calls.
2//!
3//! Every quantity is a solvr `Interval`. Callers open one `with_interval_arithmetic` call and
4//! pass its context to these functions, so no function here adds a probe or a host read.
5
6pub(crate) mod arcs;
7#[cfg(test)]
8mod certificate_rows;
9pub(crate) mod certify;
10pub(crate) mod constants;
11pub(crate) mod critical;
12pub(crate) mod floor;
13pub(crate) mod inlet;
14mod inversion;
15pub(crate) mod normal;
16pub(crate) mod outlet;
17mod roots;
18pub(crate) mod section;
19
20pub(crate) use roots::BarrelDepths;
21
22use crate::structures::{CulvertBarrel, StructureError};
23use numr::dtype::DType;
24use numr::ops::{
25    BinaryOps, CompareOps, ConditionalOps, CorrectlyRoundedOps, NextRepresentableOps, ScalarOps,
26    TensorOps, TwoSumOps,
27};
28use numr::runtime::{Runtime, RuntimeClient};
29use numr::tensor::Tensor;
30use solvr::common::arithmetic::{ArithmeticResult, Interval, IntervalContext};
31use solvr::integrate::CertifiedSimpsonAlgorithms;
32use solvr::optimize::CertifiedBisectionAlgorithms;
33
34/// Interval context on the barrel batch's client.
35pub(crate) type Arithmetic<'a, R> = IntervalContext<'a, R, <R as Runtime>::Client>;
36
37/// Client operations that barrel geometry needs.
38pub trait BarrelClient<R: Runtime<DType = DType>>:
39    TensorOps<R>
40    + CompareOps<R>
41    + NextRepresentableOps<R>
42    + ScalarOps<R>
43    + TwoSumOps<R>
44    + CorrectlyRoundedOps<R>
45    + RuntimeClient<R>
46{
47}
48
49impl<R, C> BarrelClient<R> for C
50where
51    R: Runtime<DType = DType>,
52    C: TensorOps<R>
53        + CompareOps<R>
54        + NextRepresentableOps<R>
55        + ScalarOps<R>
56        + TwoSumOps<R>
57        + CorrectlyRoundedOps<R>
58        + RuntimeClient<R>,
59{
60}
61
62/// Host barrels that name rows in errors, through an optional device map of row indices.
63pub(crate) struct RowNames<'a, R: Runtime<DType = DType>> {
64    barrels: &'a [CulvertBarrel],
65    rows: Option<&'a Tensor<R>>,
66}
67
68impl<R: Runtime<DType = DType>> Clone for RowNames<'_, R> {
69    fn clone(&self) -> Self {
70        *self
71    }
72}
73
74impl<R: Runtime<DType = DType>> Copy for RowNames<'_, R> {}
75
76impl<'a, R: Runtime<DType = DType>> RowNames<'a, R> {
77    /// Row `i` is `barrels[i]`.
78    pub(crate) fn new(barrels: &'a [CulvertBarrel]) -> Self {
79        Self {
80            barrels,
81            rows: None,
82        }
83    }
84
85    /// Row `i` is `barrels[rows[i]]`, with `rows` an I64 tensor.
86    pub(crate) fn mapped(barrels: &'a [CulvertBarrel], rows: &'a Tensor<R>) -> Self {
87        Self {
88            barrels,
89            rows: Some(rows),
90        }
91    }
92
93    /// Barrel of `row`. A mapped list reads its map to the host, so only error paths call this.
94    pub(crate) fn barrel(&self, row: usize) -> Result<Option<CulvertBarrel>, StructureError> {
95        let index = match self.rows {
96            None => Some(row),
97            Some(rows) => rows
98                .try_to_vec::<i64>()?
99                .get(row)
100                .and_then(|&index| usize::try_from(index).ok()),
101        };
102        Ok(index.and_then(|index| self.barrels.get(index)).copied())
103    }
104}
105
106/// Client operations a structure batch needs beyond its scalar laws: the culvert law's barrel
107/// geometry, certified roots and certified quadrature.
108///
109/// Every client that implements those traits implements this one.
110pub trait CulvertClient<R: Runtime<DType = DType>>:
111    BarrelClient<R> + CertifiedBisectionAlgorithms<R> + CertifiedSimpsonAlgorithms<R>
112{
113}
114
115impl<R, C> CulvertClient<R> for C
116where
117    R: Runtime<DType = DType>,
118    C: BarrelClient<R> + CertifiedBisectionAlgorithms<R> + CertifiedSimpsonAlgorithms<R>,
119{
120}
121
122/// Intersects `x` with `[low, high]`, collapsing an interval wholly outside to the nearer end.
123pub(crate) fn clip<R>(
124    a: &mut Arithmetic<'_, R>,
125    x: &Interval<R>,
126    low: f64,
127    high: f64,
128) -> ArithmeticResult<Interval<R>>
129where
130    R: Runtime<DType = DType>,
131    R::Client: BarrelClient<R>,
132{
133    let c = a.client();
134    let like = x.lower();
135    let floor = Tensor::<R>::full_scalar(like.shape(), DType::F64, low, like.device())?;
136    let ceiling = Tensor::<R>::full_scalar(like.shape(), DType::F64, high, like.device())?;
137    let lower = c.minimum(&c.maximum(x.lower(), &floor)?, &ceiling)?;
138    let upper = c.maximum(&c.minimum(x.upper(), &ceiling)?, &floor)?;
139    a.bounds(&lower, &upper)
140}
141
142/// Takes `on` where `mask` is 1 and `off` where it is 0.
143pub(crate) fn choose<R>(
144    a: &mut Arithmetic<'_, R>,
145    mask: &Tensor<R>,
146    on: &Interval<R>,
147    off: &Interval<R>,
148) -> ArithmeticResult<Interval<R>>
149where
150    R: Runtime<DType = DType>,
151    R::Client: BarrelClient<R>,
152{
153    let c = a.client();
154    let lower = c.where_cond(mask, on.lower(), off.lower())?;
155    let upper = c.where_cond(mask, on.upper(), off.upper())?;
156    a.bounds(&lower, &upper)
157}