mod arcs;
mod circular;
mod frame;
mod full;
mod range;
mod rectangular;
mod shallow;
pub(crate) use arcs::{Layers, band_at_depth, hull};
pub(crate) use full::full_constants;
pub(crate) use range::over_depth;
pub(crate) use shallow::sums;
use super::{Arithmetic, BarrelClient};
use crate::structures::tensor::codes;
use crate::structures::tensor::culvert::TensorBarrelContext;
use numr::dtype::DType;
use numr::ops::{BinaryOps, CompareOps, ConditionalOps};
use numr::runtime::Runtime;
use numr::tensor::Tensor;
use solvr::common::arithmetic::{ArithmeticResult, Interval};
pub(crate) struct Quantities<R: Runtime<DType = DType>> {
pub(crate) area: Interval<R>,
pub(crate) top_width: Interval<R>,
pub(crate) perimeter: Interval<R>,
pub(crate) radius: Interval<R>,
pub(crate) moment: Interval<R>,
}
pub(crate) struct SectionIntervals<R: Runtime<DType = DType>> {
pub(crate) state: Tensor<R>,
pub(crate) geometry: Quantities<R>,
}
pub(crate) fn at_depth<R>(
a: &mut Arithmetic<'_, R>,
barrel: &TensorBarrelContext<R>,
depth: &Tensor<R>,
) -> ArithmeticResult<SectionIntervals<R>>
where
R: Runtime<DType = DType>,
R::Client: BarrelClient<R>,
{
match &barrel.frame {
Some(rows) => frame::at_depth(a, barrel, rows, depth),
None => direct(a, barrel, depth),
}
}
fn direct<R>(
a: &mut Arithmetic<'_, R>,
barrel: &TensorBarrelContext<R>,
depth: &Tensor<R>,
) -> ArithmeticResult<SectionIntervals<R>>
where
R: Runtime<DType = DType>,
R::Client: BarrelClient<R>,
{
let c = a.client();
let valid = c.ge(depth, &barrel.zero)?;
let dry = c.eq(depth, &barrel.zero)?;
let full_rows = c.ge(depth, &barrel.rise)?;
let free = c.mul(&c.gt(depth, &barrel.zero)?, &c.lt(depth, &barrel.rise)?)?;
let circle = c.mul(&free, &barrel.circular)?;
let shallow_rows = c.mul(&circle, &c.lt(depth, &barrel.shallow_top)?)?;
let trig_rows = c.sub(&circle, &shallow_rows)?;
let box_rows = c.mul(&free, &barrel.boxed)?;
let shallow = shallow::evaluate(
a,
barrel,
&c.where_cond(&shallow_rows, depth, &barrel.shallow_operand)?,
)?;
let trig = circular::evaluate(
a,
barrel,
&c.where_cond(&trig_rows, depth, &barrel.half_rise)?,
)?;
let rectangle = rectangular::evaluate(
a,
barrel,
&c.where_cond(&box_rows, depth, &barrel.half_rise)?,
)?;
let full = full::at_depth(a, barrel, &c.where_cond(&full_rows, depth, &barrel.rise)?)?;
let mut edge = c.mul(&barrel.boxed, &barrel.span)?;
let mut layers = vec![(&trig_rows, &trig), (&shallow_rows, &shallow)];
let arcs = match &barrel.arcs {
Some(rows) => {
let free_arcs = c.mul(&free, &rows.arced)?;
edge = c.add(&edge, &rows.floor_width)?;
Some(arcs::evaluate(a, barrel, rows, depth, &free_arcs)?)
}
None => None,
};
if let Some(arcs) = &arcs {
layers.push((&arcs.banded, &arcs.bands));
layers.push((&arcs.shallow_rows, &arcs.shallow));
}
layers.push((&full_rows, &full));
let rows = Selection {
valid: &valid,
dry: &dry,
base: &rectangle,
layers: &layers,
};
let geometry = Quantities {
area: rows.select(a, barrel, |q| &q.area, &barrel.zero)?,
top_width: rows.select(a, barrel, |q| &q.top_width, &edge)?,
perimeter: rows.select(a, barrel, |q| &q.perimeter, &edge)?,
radius: rows.select(a, barrel, |q| &q.radius, &barrel.zero)?,
moment: rows.select(a, barrel, |q| &q.moment, &barrel.zero)?,
};
let state = c.where_cond(
&full_rows,
&barrel.constant(codes::BARREL_FULL)?,
&c.where_cond(
&dry,
&barrel.constant(codes::BARREL_DRY)?,
&barrel.constant(codes::BARREL_FREE)?,
)?,
)?;
Ok(SectionIntervals { state, geometry })
}
struct Selection<'s, R: Runtime<DType = DType>> {
valid: &'s Tensor<R>,
dry: &'s Tensor<R>,
base: &'s Quantities<R>,
layers: &'s [(&'s Tensor<R>, &'s Quantities<R>)],
}
impl<R: Runtime<DType = DType>> Selection<'_, R> {
fn select(
&self,
a: &mut Arithmetic<'_, R>,
barrel: &TensorBarrelContext<R>,
pick: fn(&Quantities<R>) -> &Interval<R>,
dry_value: &Tensor<R>,
) -> ArithmeticResult<Interval<R>>
where
R::Client: BarrelClient<R>,
{
let c = a.client();
let base = pick(self.base);
let mut lower = base.lower().clone();
let mut upper = base.upper().clone();
for (rows, branch) in self.layers {
let value = pick(branch);
lower = c.where_cond(rows, value.lower(), &lower)?;
upper = c.where_cond(rows, value.upper(), &upper)?;
}
let lower = c.where_cond(self.dry, dry_value, &lower)?;
let upper = c.where_cond(self.dry, dry_value, &upper)?;
let lower = c.where_cond(self.valid, &lower, &barrel.one)?;
let upper = c.where_cond(self.valid, &upper, &barrel.zero)?;
a.bounds(&lower, &upper)
}
}
fn top_width<R>(
a: &mut Arithmetic<'_, R>,
barrel: &TensorBarrelContext<R>,
y: &Interval<R>,
d: &Interval<R>,
) -> ArithmeticResult<Interval<R>>
where
R: Runtime<DType = DType>,
R::Client: BarrelClient<R>,
{
let gap = a.sub(d, y)?;
let product = a.mul(y, &gap)?;
let root = a.sqrt_nonnegative(&product)?;
let two = a.point(&barrel.constant(2.0)?)?;
a.mul(&two, &root)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::structures::{CulvertBarrel, StructureError};
use numr::runtime::cpu::{CpuDevice, CpuRuntime};
use solvr::common::arithmetic::with_interval_arithmetic;
type Ends = Vec<[Vec<f64>; 2]>;
fn ends(q: &Quantities<CpuRuntime>) -> Result<Ends, StructureError> {
[&q.area, &q.top_width, &q.perimeter, &q.radius, &q.moment]
.into_iter()
.map(|i| {
Ok([
i.lower().try_to_vec::<f64>()?,
i.upper().try_to_vec::<f64>()?,
])
})
.collect()
}
fn branches(rise: f64, depths: &[f64]) -> Result<(Ends, Ends), StructureError> {
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let barrels = vec![CulvertBarrel::circular(rise)?; depths.len()];
let barrel = TensorBarrelContext::<CpuRuntime>::new(client.clone(), &barrels)?;
let depth = Tensor::<CpuRuntime>::from_slice(depths, &[depths.len()], &device)?;
let pair = with_interval_arithmetic(&client, DType::F64, "seam", |a| {
let shallow = shallow::evaluate(a, &barrel, &depth)?;
let trig = circular::evaluate(a, &barrel, &depth)?;
Ok((shallow, trig))
})?;
Ok((ends(&pair.0)?, ends(&pair.1)?))
}
#[test]
fn shallow_and_trigonometric_enclosures_intersect_at_the_seam() -> Result<(), StructureError> {
for rise in [0.3, 1.0, 3.7] {
let seam: f64 = rise / 16.0;
let depths = [seam.next_down(), seam, seam.next_up()];
let (shallow, trig) = branches(rise, &depths)?;
for (quantity, (series, closed)) in shallow.iter().zip(&trig).enumerate() {
let rows = series[0]
.iter()
.zip(&series[1])
.zip(closed[0].iter().zip(&closed[1]));
for (row, ((&sl, &su), (&tl, &tu))) in rows.enumerate() {
assert!(sl <= su && tl <= tu, "rise={rise} row={row} q={quantity}");
assert!(
sl <= tu && tl <= su,
"rise={rise} row={row} quantity={quantity}: [{sl:e}, {su:e}] and [{tl:e}, {tu:e}] are disjoint"
);
}
}
}
Ok(())
}
#[test]
fn framed_rows_return_the_bits_of_the_metre_rows() -> Result<(), StructureError> {
let culverts = [
CulvertBarrel::circular(0.3)?,
CulvertBarrel::circular(7.3)?,
CulvertBarrel::rectangular_box(2.0, 0.8)?,
CulvertBarrel::rectangular_box(0.5, 3.1)?,
CulvertBarrel::horizontal_ellipse(1.524, 0.9652, 0.419_475_92)?,
CulvertBarrel::vertical_ellipse(0.9652 * 4.0, 1.524 * 4.0, 0.419_475_92 * 4.0)?,
CulvertBarrel::pipe_arch(1.8542 / 4.0, 1.397 / 4.0, 0.4572 / 4.0, 1.938_528 / 4.0)?,
CulvertBarrel::arch(3.048 * 2.0, 1.6002 * 2.0)?,
];
let fractions = [
0.0,
2f64.powi(-30),
1e-6,
0.03,
0.2,
0.5,
0.8,
0.999,
1.0,
1.5,
];
let mut barrels = Vec::new();
let mut depths = Vec::new();
for culvert in culverts {
for fraction in fractions {
barrels.push(culvert);
depths.push(fraction * culvert.rise_m());
}
}
let device = CpuDevice::new();
let client = CpuRuntime::default_client(&device);
let framed = TensorBarrelContext::<CpuRuntime>::new(client.clone(), &barrels)?;
assert!(framed.frame.is_some());
let metre = TensorBarrelContext::<CpuRuntime>::rows(client.clone(), &barrels, None)?;
let depth = Tensor::<CpuRuntime>::from_slice(&depths, &[depths.len()], &device)?;
let (through_frame, as_metre) =
with_interval_arithmetic(&client, DType::F64, "frame", |a| {
let first = at_depth(a, &framed, &depth)?;
let second = direct(a, &metre, &depth)?;
Ok((first, second))
})?;
let bits = |e: Ends| -> Vec<Vec<u64>> {
e.iter()
.flat_map(|[l, u]| [l, u])
.map(|v| v.iter().map(|x| x.to_bits()).collect())
.collect()
};
assert_eq!(
bits(ends(&through_frame.geometry)?),
bits(ends(&as_metre.geometry)?)
);
assert_eq!(
through_frame.state.try_to_vec::<f64>()?,
as_metre.state.try_to_vec::<f64>()?
);
Ok(())
}
#[test]
fn shallow_branch_is_tight_where_the_closed_forms_cancel() -> Result<(), StructureError> {
let depth = 2f64.powi(-20);
let (shallow, trig) = branches(1.0, &[depth])?;
let relative = |e: &Ends, q: usize| (e[q][1][0] - e[q][0][0]) / e[q][1][0];
for quantity in [0, 4] {
assert!(relative(&shallow, quantity) < 1e-14, "quantity={quantity}");
assert!(relative(&shallow, quantity) < relative(&trig, quantity) / 1e3);
}
Ok(())
}
}