use crate::error::AxisError;
use super::{Axis, BinInterval, UniformNoFlow};
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 UniformCyclic<T = f64> {
#[cfg_attr(feature = "serde", serde(flatten))]
axis: UniformNoFlow<T>,
}
impl<T> UniformCyclic<T>
where
T: PartialOrd + Num + NumCast + NumOps + Copy,
{
pub fn new(nbins: usize, low: T, high: T) -> Result<Self, AxisError>
where
T: Float,
{
Ok(Self {
axis: UniformNoFlow::new(nbins, low, high)?,
})
}
pub fn with_step_size(nbins: usize, low: T, step: T) -> Result<Self, AxisError> {
Ok(Self {
axis: UniformNoFlow::with_step_size(nbins, low, step)?,
})
}
}
impl<T> UniformCyclic<T> {
#[inline]
pub fn low(&self) -> &T {
self.axis.low()
}
#[inline]
pub fn high(&self) -> &T {
self.axis.high()
}
}
impl<T: PartialOrd + Num + NumCast + NumOps + Copy> Axis for UniformCyclic<T> {
type Coordinate = T;
type BinInterval = BinInterval<T>;
#[inline]
fn index(&self, coordinate: &Self::Coordinate) -> Option<usize> {
let (mut x, hi, lo) = (*coordinate, *self.axis.high(), *self.axis.low());
let range = hi - lo;
x = (x - lo) % range;
if x < T::zero() {
x = range + x;
}
x = x + lo;
self.axis.index(&x)
}
#[inline]
fn num_bins(&self) -> usize {
self.axis.num_bins()
}
#[inline]
fn bin(&self, index: usize) -> Option<<Self as Axis>::BinInterval> {
self.axis.bin(index)
}
}
impl<T> Display for UniformCyclic<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.axis.num_bins(),
self.axis.low(),
self.axis.high(),
stringify!(UniformCyclic)
)
}
}
impl<'a, T> IntoIterator for &'a UniformCyclic<T>
where
UniformCyclic<T>: Axis,
{
type Item = (usize, <UniformCyclic<T> as Axis>::BinInterval);
type IntoIter = Box<dyn Iterator<Item = Self::Item> + 'a>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}