use crate::error::AxisError;
use super::{Axis, BinInterval, Uniform};
use std::fmt::{Debug, Display};
use num_traits::{Float, Num, NumCast, NumOps};
#[derive(Default, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct UniformNoFlow<T = f64> {
axis: Uniform<T>,
}
impl<T> UniformNoFlow<T>
where
T: PartialOrd + NumCast + NumOps + Copy,
{
pub fn new(num: usize, low: T, high: T) -> Result<Self, AxisError>
where
T: Float,
{
Ok(Self {
axis: Uniform::new(num, low, high)?,
})
}
pub fn with_step_size(num: usize, low: T, step: T) -> Result<Self, AxisError>
where
T: Num,
{
Ok(Self {
axis: Uniform::with_step_size(num, low, step)?,
})
}
}
impl<T> UniformNoFlow<T> {
pub fn low(&self) -> &T {
self.axis.low()
}
pub fn high(&self) -> &T {
self.axis.high()
}
}
impl<T> Axis for UniformNoFlow<T>
where
T: PartialOrd + NumCast + NumOps + Copy,
{
type Coordinate = T;
type BinInterval = BinInterval<T>;
#[inline]
fn index(&self, coordinate: &Self::Coordinate) -> Option<usize> {
let index = self.axis.index(coordinate)?;
if index == 0 || index + 1 == self.axis.num_bins() {
return None;
}
Some(index - 1)
}
fn num_bins(&self) -> usize {
self.axis.num_bins() - 2
}
fn bin(&self, index: usize) -> Option<Self::BinInterval> {
let bin = self.axis.bin(index + 1)?;
match bin {
BinInterval::Underflow { end: _ } => None,
BinInterval::Overflow { start: _ } => None,
BinInterval::Bin { start: _, end: _ } => Some(bin),
}
}
}
impl<'a, T> IntoIterator for &'a UniformNoFlow<T>
where
T: PartialOrd + NumCast + NumOps + Copy,
{
type Item = (usize, <Uniform<T> as Axis>::BinInterval);
type IntoIter = Box<dyn Iterator<Item = Self::Item> + 'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<T> Display for UniformNoFlow<T>
where
T: PartialOrd + NumCast + NumOps + Copy + Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Axis{{# bins={}, range=[{}, {}), class={}}}",
self.num_bins(),
self.axis.low(),
self.axis.high(),
stringify!(UniformNoFlow)
)
}
}