use super::partition::LANES;
use super::quadrature::{LEVEL_RATIO, PANELS};
use super::trig::fill;
use crate::structures::numerics::culvert::BarrelClient;
use crate::structures::numerics::culvert::roots::RELATIVE_TOLERANCE;
use numr::dtype::DType;
use numr::ops::{BinaryOps, CompareOps, ReduceOps, ScalarOps};
use numr::runtime::Runtime;
use numr::tensor::Tensor;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Accuracy {
Fine,
Coarse,
}
impl Accuracy {
pub(crate) fn budget(self) -> f64 {
match self {
Self::Fine => FINE_BUDGET,
Self::Coarse => COARSE_BUDGET,
}
}
pub(crate) fn root_tolerance(self) -> f64 {
match self {
Self::Fine => RELATIVE_TOLERANCE,
Self::Coarse => COARSE_ROOT_TOLERANCE,
}
}
pub(crate) fn depth_tolerance(self) -> f64 {
match self {
Self::Fine => FINE_DEPTH_TOLERANCE,
Self::Coarse => COARSE_ROOT_TOLERANCE,
}
}
}
const COARSE_ROOT_TOLERANCE: f64 = 1.0 / 4_294_967_296.0;
const FINE_DEPTH_TOLERANCE: f64 = 1.0 / 70_368_744_177_664.0;
const FINE_BUDGET: f64 = 1.0 / 1_125_899_906_842_624.0;
const COARSE_BUDGET: f64 = 1.0 / 1_048_576.0;
pub(crate) fn level_for<R>(
c: &R::Client,
remainder: &Tensor<R>,
budget: &Tensor<R>,
) -> numr::error::Result<Tensor<R>>
where
R: Runtime<DType = DType>,
R::Client: BarrelClient<R>,
{
let mut level = fill(budget, 0.0)?;
let mut threshold = budget.clone();
for _ in 1..PANELS.len() {
level = c.add(&level, &c.gt(remainder, &threshold)?)?;
threshold = c.mul_scalar(&threshold, LEVEL_RATIO)?;
}
Ok(level)
}
pub(crate) fn span_level<R>(
c: &R::Client,
levels: &Tensor<R>,
low: &Tensor<R>,
high: &Tensor<R>,
) -> numr::error::Result<Tensor<R>>
where
R: Runtime<DType = DType>,
R::Client: BarrelClient<R>,
{
let p = low.numel();
let lanes = levels.shape().get(1).copied().unwrap_or(LANES);
let index: Vec<f64> = (0..lanes).map(|k| k as f64).collect();
let index = Tensor::<R>::from_slice(&index, &[1, lanes], low.device())?
.broadcast_to(&[p, lanes])?
.contiguous()?;
let wide = |value: &Tensor<R>| -> numr::error::Result<Tensor<R>> {
value
.reshape(&[p, 1])?
.broadcast_to(&[p, lanes])?
.contiguous()
};
let first = c.minimum(low, &fill(low, (lanes - 1) as f64)?)?;
let end = c.maximum(high, &c.add_scalar(&first, 1.0)?)?;
let inside = c.mul(&c.ge(&index, &wide(&first)?)?, &c.lt(&index, &wide(&end)?)?)?;
c.max(&c.mul(levels, &inside)?, &[1], false)
}