use super::{aligned, dimension, finite};
use crate::{plots::HistogramKde, stats::HistogramStat, Error, NumericValues};
const MAX_BINS: usize = 1_000_000;
const MAX_KDE_POINTS: usize = 2_048;
const MAX_RUGS: usize = 1_000_000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistogramBinsData {
lower: NumericValues,
upper: NumericValues,
height: NumericValues,
stat: HistogramStat,
}
impl HistogramBinsData {
pub const fn bin_lower(&self) -> &NumericValues {
&self.lower
}
pub const fn bin_upper(&self) -> &NumericValues {
&self.upper
}
pub const fn bin_height(&self) -> &NumericValues {
&self.height
}
pub const fn bin_stat(&self) -> HistogramStat {
self.stat
}
fn validate(&self) -> Result<(f64, f64), Error> {
aligned(
"histogram bins",
self.lower.len(),
&[
("bin_upper", self.upper.len()),
("bin_height", self.height.len()),
],
)?;
if self.lower.is_empty() || self.lower.len() > MAX_BINS {
return Err(Error::Data(
format!("histogram geometry requires 1..={MAX_BINS} bins").into(),
));
}
let mut previous = None;
for row in 0..self.lower.len() {
let lower = finite(&self.lower, row, "histogram bin lower")?;
let upper = finite(&self.upper, row, "histogram bin upper")?;
let height = finite(&self.height, row, "histogram bin height")?;
if lower >= upper || height < 0.0 {
return Err(Error::Data(
format!("histogram bin {row} requires lower < upper and nonnegative height")
.into(),
));
}
if previous.is_some_and(|previous| {
lower.partial_cmp(&previous) != Some(std::cmp::Ordering::Equal)
}) {
return Err(Error::Data(
format!("histogram bins must be ordered and contiguous at bin {row}").into(),
));
}
previous = Some(upper);
}
Ok((
finite(&self.lower, 0, "histogram bin lower")?,
finite(&self.upper, self.upper.len() - 1, "histogram bin upper")?,
))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HistogramRugData {
x: NumericValues,
baseline: NumericValues,
top: NumericValues,
}
impl HistogramRugData {
pub const fn rug_x(&self) -> &NumericValues {
&self.x
}
pub const fn rug_baseline(&self) -> &NumericValues {
&self.baseline
}
pub const fn rug_top(&self) -> &NumericValues {
&self.top
}
fn validate(&self, range: (f64, f64)) -> Result<(), Error> {
aligned(
"histogram rug",
self.x.len(),
&[
("rug_baseline", self.baseline.len()),
("rug_top", self.top.len()),
],
)?;
validate_rug_count(self.x.len())?;
for row in 0..self.x.len() {
let x = finite(&self.x, row, "histogram rug x")?;
let baseline = finite(&self.baseline, row, "histogram rug baseline")?;
let top = finite(&self.top, row, "histogram rug top")?;
if !(range.0..=range.1).contains(&x) || baseline < 0.0 || baseline >= top {
return Err(Error::Data(
format!(
"histogram rug {row} requires x within bin support and 0 <= baseline < top"
)
.into(),
));
}
}
Ok(())
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct HistogramGeometry {
bins: HistogramBinsData,
kde: Option<HistogramKde>,
rug: Option<HistogramRugData>,
value_dimension: Option<String>,
height_dimension: Option<String>,
}
impl HistogramGeometry {
pub(crate) fn authored_value_dimension(&self) -> Option<&str> {
self.value_dimension.as_deref()
}
pub(crate) fn authored_height_dimension(&self) -> Option<&str> {
self.height_dimension.as_deref()
}
#[must_use]
pub fn bins(
lower: NumericValues,
upper: NumericValues,
height: NumericValues,
stat: HistogramStat,
) -> Self {
Self {
bins: HistogramBinsData {
lower,
upper,
height,
stat,
},
kde: None,
rug: None,
value_dimension: None,
height_dimension: None,
}
}
#[must_use]
pub fn kde(mut self, x: NumericValues, density: NumericValues) -> Self {
self.set_kde(x, density);
self
}
pub(crate) fn set_kde(&mut self, x: NumericValues, density: NumericValues) {
self.kde = Some(HistogramKde::Precomputed { x, y: density });
}
#[must_use]
pub fn rug(mut self, x: NumericValues, baseline: NumericValues, top: NumericValues) -> Self {
self.set_rug(x, baseline, top);
self
}
pub(crate) fn set_rug(
&mut self,
x: NumericValues,
baseline: NumericValues,
top: NumericValues,
) {
self.rug = Some(HistogramRugData { x, baseline, top });
}
#[must_use]
pub fn value_dimension(mut self, name: impl Into<String>) -> Self {
self.set_value_dimension(name.into());
self
}
pub(crate) fn set_value_dimension(&mut self, name: String) {
self.value_dimension = Some(name);
}
#[must_use]
pub fn height_dimension(mut self, name: impl Into<String>) -> Self {
self.set_height_dimension(name.into());
self
}
pub(crate) fn set_height_dimension(&mut self, name: String) {
self.height_dimension = Some(name);
}
pub const fn get_bins(&self) -> &HistogramBinsData {
&self.bins
}
pub const fn get_kde(&self) -> Option<&HistogramKde> {
self.kde.as_ref()
}
pub const fn get_rug(&self) -> Option<&HistogramRugData> {
self.rug.as_ref()
}
pub fn get_value_dimension(&self) -> &str {
self.value_dimension.as_deref().unwrap_or_else(|| {
self.rug
.as_ref()
.map(|rug| rug.x.name())
.filter(|name| !name.trim().is_empty())
.unwrap_or("value")
})
}
pub fn get_height_dimension(&self) -> &str {
self.height_dimension.as_deref().unwrap_or_else(|| {
let name = self.bins.height.name();
if name.trim().is_empty() {
self.bins.stat.name()
} else {
name
}
})
}
pub(crate) fn validate(&self) -> Result<(f64, f64), Error> {
dimension(self.get_value_dimension(), "histogram value dimension")?;
dimension(self.get_height_dimension(), "histogram height dimension")?;
let range = self.bins.validate()?;
if let Some(kde) = self.get_kde() {
if self.bins.stat != HistogramStat::Density {
return Err(Error::Data(
"histogram: a supplied KDE density curve requires density bin heights".into(),
));
}
let (x, y) = kde
.get_precomputed()
.expect("supplied curve always owns its columns");
validate_kde(x, y, range)?;
}
if let Some(rug) = self.get_rug() {
rug.validate(range)?;
}
Ok(range)
}
}
pub(crate) fn validate_kde(
x: &NumericValues,
y: &NumericValues,
range: (f64, f64),
) -> Result<(), Error> {
aligned("histogram KDE", x.len(), &[("y", y.len())])?;
if x.len() < 2 {
return Err(Error::Data(
"histogram KDE: a precomputed curve requires at least two points".into(),
));
}
if x.len() > MAX_KDE_POINTS {
return Err(Error::Data(
format!("histogram supplied KDE exceeds its {MAX_KDE_POINTS} point limit").into(),
));
}
let mut previous = None;
let mut positive = false;
for row in 0..x.len() {
let x = finite(x, row, "histogram KDE finite x")?;
let y = finite(y, row, "histogram KDE nonnegative finite density")?;
if y < 0.0 {
return Err(Error::Data(
format!(
"histogram KDE: precomputed point {row} requires nonnegative finite density"
)
.into(),
));
}
if !(range.0..=range.1).contains(&x) {
return Err(Error::Data(format!("histogram KDE: precomputed x {x} at point {row} lies outside histogram bin range {}..{}", range.0, range.1).into()));
}
if previous.is_some_and(|previous| x <= previous) {
return Err(Error::Data(
"histogram KDE: precomputed x values must be strictly increasing".into(),
));
}
previous = Some(x);
positive |= y > 0.0;
}
if !positive {
return Err(Error::Data(
"histogram KDE: a precomputed density curve must contain a positive density".into(),
));
}
Ok(())
}
pub(crate) fn validate_rug_count(count: usize) -> Result<(), Error> {
if count == 0 || count > MAX_RUGS {
return Err(Error::Data(
format!("histogram rug requires 1..={MAX_RUGS} segments").into(),
));
}
Ok(())
}