use crate::errors::stats_error::StatsError;
use alloc::vec::Vec;
use deep_causality_algebra::RealField;
use deep_causality_num::{FromPrimitive, ToPrimitive};
pub fn bin_equal_width<T>(data: &[T], bins: usize) -> Result<Vec<T>, StatsError>
where
T: RealField + FromPrimitive,
{
let n = validate(data, bins)?;
let mut lo = data[0];
let mut hi = data[0];
for &x in data {
if x < lo {
lo = x;
}
if x > hi {
hi = x;
}
}
let span = hi - lo;
if span <= T::zero() {
return Ok(alloc::vec![T::zero(); n]);
}
let two = T::one() + T::one();
let halve = !span.is_finite();
let (origin, width) = if halve {
(lo / two, hi / two - lo / two)
} else {
(lo, span)
};
let bins_t = index::<T>(bins)?;
let last = index::<T>(bins - 1)?;
let mut out = alloc::vec::Vec::with_capacity(n);
for &x in data {
let scaled = if halve { x / two } else { x };
let q = ((scaled - origin) / width * bins_t).floor();
out.push(if q > last { last } else { q });
}
Ok(out)
}
fn validate<T>(data: &[T], bins: usize) -> Result<usize, StatsError>
where
T: RealField + FromPrimitive,
{
if data.is_empty() {
return Err(StatsError::EmptyInput("no observations to bin"));
}
if bins < 2 {
return Err(StatsError::InvalidBinCount(
"a bin count below two is not a partition",
));
}
if bins > data.len() {
return Err(StatsError::InvalidBinCount(
"more bins than observations: n observations support at most n non-empty bins",
));
}
if data.iter().any(|x| !x.is_finite()) {
return Err(StatsError::NonFiniteInput(
"a non-finite observation has no place on the range",
));
}
Ok(data.len())
}
fn index<T: FromPrimitive + ToPrimitive>(i: usize) -> Result<T, StatsError> {
let v = T::from_usize(i).ok_or_else(|| {
StatsError::ConversionFailed("a bin index is not representable in the working scalar")
})?;
if v.to_usize() == Some(i) {
Ok(v)
} else {
Err(StatsError::ConversionFailed(
"a bin index is not representable in the working scalar: it would round to a \
different count and partition the range differently",
))
}
}
pub fn bin_equal_frequency<T>(data: &[T], bins: usize) -> Result<Vec<T>, StatsError>
where
T: RealField + FromPrimitive,
{
let n = validate(data, bins)?;
let mut order: alloc::vec::Vec<usize> = (0..n).collect();
order.sort_by(|&a, &b| {
data[a]
.partial_cmp(&data[b])
.expect("non-finite observations are refused above")
});
let mut out = alloc::vec![T::zero(); n];
let mut start = 0usize;
while start < n {
let mut end = start;
while end + 1 < n && data[order[end + 1]] == data[order[start]] {
end += 1;
}
let mut bin = start * bins / n;
let mut share = 1usize;
let mut best_bin = bin;
let mut best_share = 1usize;
for rank in (start + 1)..=end {
let b = rank * bins / n;
if b == bin {
share += 1;
} else {
bin = b;
share = 1;
}
if share > best_share {
best_share = share;
best_bin = bin;
}
}
let value = index::<T>(best_bin)?;
for &idx in &order[start..=end] {
out[idx] = value;
}
start = end + 1;
}
Ok(out)
}