use crate::application::linalg::thresholds;
use crate::domain::real::RealScalar;
use leto::{Array2, ArrayView2, LetoError, Result};
pub(crate) fn largest_magnitude<T: RealScalar>(values: impl IntoIterator<Item = T>) -> Option<T> {
let mut largest = T::ZERO;
for value in values {
if !value.is_finite() {
return None;
}
let magnitude = value.abs();
if magnitude > largest {
largest = magnitude;
}
}
if largest == T::ZERO {
None
} else {
Some(largest)
}
}
fn minimal_exponent_to_range<T: RealScalar>(largest: T, rmin: T, rmax: T) -> i32 {
if largest > rmax {
let mut k = largest.binary_exponent().unwrap_or(0) - rmax.binary_exponent().unwrap_or(0);
if k < 1 {
k = 1;
}
while largest.scale_binary(-k) > rmax {
k += 1;
}
while k > 1 && largest.scale_binary(-(k - 1)) <= rmax {
k -= 1;
}
k
} else {
let mut k = largest.binary_exponent().unwrap_or(0) - rmin.binary_exponent().unwrap_or(0);
if k > -1 {
k = -1;
}
while largest.scale_binary(-k) < rmin {
k -= 1;
}
while k < -1 && largest.scale_binary(-(k + 1)) >= rmin {
k += 1;
}
k
}
}
pub(crate) fn balancing_exponent<T: RealScalar>(largest: T, range: (T, T)) -> Option<i32> {
let (rmin, rmax) = range;
if largest >= rmin && largest <= rmax {
return None;
}
Some(minimal_exponent_to_range(largest, rmin, rmax))
}
pub(crate) fn scale_by_power_of_two<T: RealScalar>(values: &mut [T], exponent: i32) {
for value in values {
*value = value.scale_binary(exponent);
}
}
#[derive(Clone, Copy)]
pub(crate) struct GateBound {
pub(crate) factor_log2: i32,
pub(crate) floor_log2: i32,
}
impl GateBound {
pub(crate) fn factor(factor_log2: i32) -> Self {
Self {
factor_log2,
floor_log2: 0,
}
}
}
pub(crate) fn gate_exponent<T: RealScalar>(
values: &[T],
degree: u32,
bound: impl FnOnce(&[T], T) -> GateBound,
) -> Result<Option<i32>> {
let Some(largest) = largest_magnitude(values.iter().copied()) else {
return Ok(None);
};
let GateBound {
factor_log2,
floor_log2,
} = bound(values, largest);
let range = thresholds::homogeneous_safe_range::<T>(degree, factor_log2, floor_log2).map_err(
|empty| LetoError::Overflow {
reason: match empty {
thresholds::EmptyRange::Intermediates => "the matrix order exceeds the scalar's exponent range: its bounded intermediates cannot be kept finite",
thresholds::EmptyRange::DeflationFloor => "the matrix order exceeds the scalar's exponent range: no scaling keeps the absolute deflation floor 2^ceil(log2 n)*safmin at or below eps*||A||_F",
},
},
)?;
Ok(balancing_exponent(largest, range))
}
pub(crate) fn balanced<T: RealScalar>(
matrix: &ArrayView2<'_, T>,
degree: u32,
bound: impl FnOnce(&[T], T) -> GateBound,
) -> Result<Option<(Array2<T>, i32)>> {
let mut values = match matrix.as_slice() {
Some(slice) => slice.to_vec(),
None => matrix.iter().copied().collect(),
};
let Some(exponent) = gate_exponent(&values, degree, bound)? else {
return Ok(None);
};
scale_by_power_of_two(&mut values, -exponent);
let array = Array2::from_shape_vec(matrix.shape(), values)
.expect("invariant: a copy of a view keeps its shape and length");
Ok(Some((array, exponent)))
}
pub(crate) fn restore<T: RealScalar>(
values: &mut [T],
exponent: i32,
what: &'static str,
) -> Result<()> {
scale_by_power_of_two(values, exponent);
if values.iter().all(|value| value.is_finite()) {
Ok(())
} else {
Err(LetoError::Overflow { reason: what })
}
}