use super::over_depth;
use super::point::FloorQuantities;
use crate::structures::numerics::culvert::{Arithmetic, BarrelClient};
use crate::structures::tensor::culvert::{Bounds, FloorRows, TensorBarrelContext};
use numr::dtype::DType;
use numr::ops::{BinaryOps, CompareOps, ConditionalOps, NextRepresentableOps};
use numr::runtime::Runtime;
use numr::tensor::Tensor;
use solvr::common::arithmetic::{ArithmeticResult, Interval};
pub(crate) struct OpenDepth<R: Runtime<DType = DType>> {
pub(crate) rows: Tensor<R>,
pub(crate) geometry: FloorQuantities<R>,
}
pub(crate) fn at_fraction<R>(
a: &mut Arithmetic<'_, R>,
barrel: &TensorBarrelContext<R>,
floor: &FloorRows<R>,
fraction: &Tensor<R>,
) -> ArithmeticResult<OpenDepth<R>>
where
R: Runtime<DType = DType>,
R::Client: BarrelClient<R>,
{
let c = a.client();
let rows = c.sub(&floor.floored, &floor.boxed)?;
let framed = barrel.frame.as_ref().map_or(barrel, |frame| &frame.context);
let Some(open) = framed.floor.as_deref() else {
return Err(numr::error::Error::InvalidArgument {
arg: "barrel",
reason: "the barrel frame lost its floor rows".into(),
}
.into());
};
let operand = c.where_cond(&rows, fraction, &barrel.constant(0.5)?)?;
let [lower, upper] = frame_depths(a, open, &operand, &operand)?;
let geometry = over_depth(a, framed, open, &lower, &upper)?.geometry;
Ok(OpenDepth { rows, geometry })
}
pub(crate) fn frame_depths<R>(
a: &mut Arithmetic<'_, R>,
open: &FloorRows<R>,
lower: &Tensor<R>,
upper: &Tensor<R>,
) -> ArithmeticResult<Bounds<R>>
where
R: Runtime<DType = DType>,
R::Client: BarrelClient<R>,
{
let c = a.client();
let top = a.point(&open.top)?;
let low = a.point(lower)?;
let high = a.point(upper)?;
let from = a.mul(&low, &top)?;
let to = a.mul(&high, &top)?;
let below_crown = c.next_down(&open.top)?;
Ok([from.lower().clone(), c.minimum(to.upper(), &below_crown)?])
}
pub(crate) fn log_scale<R>(
a: &mut Arithmetic<'_, R>,
barrel: &TensorBarrelContext<R>,
) -> ArithmeticResult<Interval<R>>
where
R: Runtime<DType = DType>,
R::Client: BarrelClient<R>,
{
let Some(frame) = &barrel.frame else {
return a.point(&barrel.zero);
};
let c = a.client();
let scale = a.point(&frame.scale)?;
let log = a.log_positive(&scale)?;
let unit = c.eq(&frame.scale, &barrel.one)?;
let lower = c.where_cond(&unit, &barrel.zero, log.lower())?;
let upper = c.where_cond(&unit, &barrel.zero, log.upper())?;
a.bounds(&lower, &upper)
}