use crate::structures::numerics::culvert::constants::CRITICAL_FLOOR;
use crate::structures::numerics::culvert::{Arithmetic, BarrelClient};
use crate::structures::tensor::culvert::TensorBarrelContext;
use numr::dtype::DType;
use numr::ops::{BinaryOps, CompareOps, UnaryOps};
use numr::runtime::Runtime;
use numr::tensor::Tensor;
use solvr::common::arithmetic::{ArithmeticResult, Interval};
pub(crate) struct Signs<R: Runtime<DType = DType>> {
pub(crate) below: Tensor<R>,
pub(crate) straddle: Tensor<R>,
pub(crate) solved: Tensor<R>,
pub(crate) near_top: Tensor<R>,
pub(crate) above: Tensor<R>,
pub(crate) past: Tensor<R>,
pub(crate) start: Tensor<R>,
}
pub(crate) fn classify<R>(
a: &mut Arithmetic<'_, R>,
barrel: &TensorBarrelContext<R>,
wet: &Tensor<R>,
[bottom, crown]: [&Interval<R>; 2],
top: &Tensor<R>,
slope: &Tensor<R>,
) -> ArithmeticResult<Signs<R>>
where
R: Runtime<DType = DType>,
R::Client: BarrelClient<R>,
{
let floor = barrel.constant(CRITICAL_FLOOR)?;
let c = a.client();
let zero = &barrel.zero;
let below = c.mul(wet, &c.gt(bottom.lower(), zero)?)?;
let rising = c.mul(wet, &c.le(bottom.upper(), zero)?)?;
let straddle = c.sub(&c.sub(wet, &below)?, &rising)?;
let above = c.mul(&rising, &c.lt(crown.upper(), zero)?)?;
let solved = c.mul(&rising, &c.ge(crown.lower(), zero)?)?;
let near_top = c.sub(&c.sub(&rising, &above)?, &solved)?;
let deficit = a.point(&c.neg(bottom.lower())?)?;
let reach = a.div_positive(&deficit, slope)?;
let floor_point = a.point(&floor)?;
let past = a.add(&floor_point, &reach)?;
let excess = a.point(crown.upper())?;
let drop = a.div_positive(&excess, slope)?;
let top_point = a.point(top)?;
let start = a.sub(&top_point, &drop)?;
let start = c.maximum(start.lower(), &floor)?;
Ok(Signs {
below,
straddle,
solved,
near_top,
above,
past: past.upper().clone(),
start,
})
}