#![allow(
clippy::cast_possible_truncation,
clippy::cast_precision_loss,
clippy::cast_sign_loss
)]
use crate::alpha::{
marks::{fill_ink_outset, fill_style, line_style},
AlphaTarget, AlphaUnitKind, ResolvedAlpha,
};
use crate::data::PlotData;
use crate::geometry::finite;
use crate::{Error, NumericValues};
use crate::layout::interior::MeasuredCoordinateMarks;
use crate::render::backend::{with_clip, Backend, FillStyle, LineStyle, Point2D};
use crate::spec::{
HistogramBins, HistogramComposite, HistogramKde, HistogramStat, PlotMeasureContext,
};
#[cfg(test)]
use crate::Plot;
mod result;
pub use result::HistogramResult;
const MAX_AUTO_BINS: usize = 512;
const MAX_EXPLICIT_BINS: usize = 1_000_000;
const KDE_GRID_POINTS: usize = 128;
#[derive(Debug, Clone, Copy, PartialEq)]
struct Bin {
lower: f64,
upper: f64,
height: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct KdePoint {
x: f64,
y: f64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
struct RugSegment {
x: f64,
baseline: f64,
top: f64,
}
#[derive(Debug)]
pub(crate) struct HistogramSemantics {
source_ranges: [(f64, f64); 2],
bins: Vec<Bin>,
bin_alphas: Vec<Option<ResolvedAlpha>>,
curve: Option<Vec<KdePoint>>,
curve_alpha: Option<ResolvedAlpha>,
rugs: Vec<RugSegment>,
contributions: Option<HistogramContributions>,
kde_bandwidth: Option<f64>,
}
pub(crate) fn intrinsic_body_minimum(
registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
theme: &crate::text::TextRequestContext<'_, '_>,
) -> Result<(f64, f64), Error> {
let prepared = registered
.map(|registered| registered.family.as_ref())
.and_then(|family| match family {
crate::orchestrator::registration::FamilyRef::Histogram(marks) => Some(marks),
_ => None,
})
.ok_or_else(|| Error::Render("Histogram intrinsic requires root-prepared bins".into()))?;
if prepared.bins.is_empty() {
return Err(Error::Render(
"Histogram has no prepared primary bins".into(),
));
}
let style = theme
.marks
.get_fills()
.get_bodies()
.get_histogram_bin()
.backend_style((0, 0, 0));
let fill = fill_ink_outset(&style, prepared.bin_alphas.iter().copied())?;
let curve = if prepared
.curve
.as_ref()
.is_some_and(|points| points.len() >= 2)
{
crate::render::geometry::line_ink_width(&line_style(
prepared.curve_alpha,
theme
.marks
.get_strokes()
.get_curves()
.get_histogram_curve()
.backend_style(),
))?
} else {
0.0
};
let rug = if prepared.rugs.is_empty() {
0.0
} else {
crate::render::geometry::line_ink_width(
&theme
.marks
.get_strokes()
.get_curves()
.get_histogram_rug()
.backend_style(),
)?
};
let span = (fill.0.max(fill.1) + 1.0 / 1024.0).max(curve).max(rug);
let raw_windows = registered.expect("prepared occurrence").raw_windows();
Ok((
if raw_windows[0].is_none() { span } else { 0.0 },
if raw_windows[1].is_none() { span } else { 0.0 },
))
}
impl HistogramSemantics {
pub(crate) fn alpha_guide(
&self,
_chart: &crate::builder::PlotDescription,
theme: &crate::theme::ResolvedTheme,
guide: &mut crate::decorations::legend::alpha::AlphaGuideBuilder<'_>,
) -> crate::Result<()> {
use crate::decorations::legend::alpha::{AlphaGlyphRole, AlphaUnit};
let fill = theme.marks.get_fills().get_bodies().get_histogram_bin();
for (bin, &alpha) in self.bins.iter().zip(&self.bin_alphas) {
guide.fill(
AlphaGlyphRole::Fill,
AlphaUnitKind::Bin,
AlphaUnit::bin((bin.lower, bin.upper)),
alpha,
fill.backend_style((0, 0, 0)),
fill.get_outline()
.is_some_and(|outline| outline.mapped_width().is_some()),
)?;
}
if self.curve.as_ref().is_some_and(|curve| curve.len() >= 2) {
guide.line(
AlphaGlyphRole::Line,
AlphaUnitKind::Single,
AlphaUnit::Single,
self.curve_alpha,
theme
.marks
.get_strokes()
.get_curves()
.get_histogram_curve()
.backend_style(),
false,
)?;
}
Ok(())
}
pub(crate) fn primary_mark_count(&self) -> u128 {
self.bins.len() as u128
}
#[expect(
clippy::too_many_lines,
reason = "preserve the original bin, KDE, rug and seed production order"
)]
pub(crate) fn new(
source: &crate::builder::PlotDescription,
data: PlotData<'_, '_>,
owner: &crate::theme::Theme,
) -> Result<(Self, [(f64, f64); 2]), Error> {
let _scientific = crate::operation::scientific_preparation();
data.validate_row_source()?;
let curve_alpha = source
.prepare_alpha(AlphaTarget::Line, AlphaUnitKind::Single, &[])?
.single()?;
let mut contributions = None;
let mut kde_bandwidth = None;
let (range, bins, curve, rugs) = if let Some(input) = source.histogram_geometry_input() {
let range = input.validate()?;
(
range,
supplied_bins(input.get_bins())?,
input
.get_kde()
.and_then(HistogramKde::get_precomputed)
.map(|(x, y)| supplied_curve(x, y))
.transpose()?,
input
.get_rug()
.map(supplied_rugs)
.transpose()?
.unwrap_or_default(),
)
} else {
if let Some(hue) = source.hue_col() {
return Err(Error::Data(format!("histogram: hue column {hue:?} is not supported yet; render separate single-series histograms").into()));
}
let column = source
.x_col()
.ok_or_else(|| Error::Data("histogram: value column not set".into()))?;
let values = crate::data::strict_finite_f64(data, column, "histogram")?;
let prepared = prepare_histogram(
&values,
source.histogram_bins_spec(),
source.histogram_stat_spec(),
data.source_resources().captures_results(),
)?;
contributions = prepared.contributions;
let range = (prepared.edges[0], prepared.edges[prepared.edges.len() - 1]);
let (curve, bandwidth) =
prepare_density_curve(source.histogram_composite_spec(), &values, range)?;
kde_bandwidth = bandwidth;
let bins = crate::data::source::collect_source(
prepared.heights.iter().enumerate().map(|(i, height)| {
Ok(Bin {
lower: prepared.edges[i],
upper: prepared.edges[i + 1],
height: *height,
})
}),
)?;
let mut maximum = prepared.heights.iter().copied().fold(0.0_f64, f64::max);
if let Some(curve) = &curve {
maximum = curve.iter().map(|p| p.y).fold(maximum, f64::max);
}
let rugs = if curve.is_some() {
let top = maximum
* owner
.marks()
.get_extents()
.get_sampled_rug_height()
.as_f64();
if !top.is_finite() {
return Err(Error::Render(
"sampled rug height exceeds finite geometry".into(),
));
}
if top > 0.0 {
crate::geometry::validate_rug_count(values.len())?;
crate::data::source::collect_source(values.iter().map(|x| {
Ok(RugSegment {
x: *x,
baseline: 0.0,
top,
})
}))?
} else {
Vec::new()
}
} else {
Vec::new()
};
(range, bins, curve, rugs)
};
let alpha = source.prepare_scoped_alpha(
AlphaTarget::Fill,
AlphaUnitKind::Bin,
&[],
data.facet_selector()?,
)?;
let bin_alphas = crate::data::source::collect_source(
bins.iter().map(|bin| alpha.bin((bin.lower, bin.upper))),
)?;
let maximum = bins
.iter()
.map(|b| b.height)
.chain(curve.iter().flatten().map(|p| p.y))
.chain(rugs.iter().map(|r| r.top))
.fold(0.0_f64, f64::max);
let ranges = [
source
.x_axis_spec()
.window
.map_or(range, crate::layout::RawWindow::pair),
crate::layout::anchored_auto_range(
(0.0, maximum),
source
.y_axis_spec()
.window
.map(crate::layout::RawWindow::pair),
0.0,
)?,
];
Ok((
Self {
source_ranges: [range, (0.0, maximum)],
bins,
bin_alphas,
curve,
curve_alpha,
rugs,
contributions,
kde_bandwidth,
},
ranges,
))
}
}
#[derive(Debug)]
pub(crate) struct HistogramPayload {
clip: crate::layout::PixelRect,
pub(crate) bins: Vec<([Point2D; 4], FillStyle)>,
curve: Option<Vec<Point2D>>,
rugs: Vec<[Point2D; 2]>,
curve_style: LineStyle,
rug_style: LineStyle,
pub(crate) domain_expansions: [Option<crate::layout::interior::DomainExpansion>; 2],
}
impl HistogramPayload {
fn geometry(
&self,
clip: Option<crate::layout::PixelRect>,
) -> Result<crate::render::geometry::GeometrySnapshot, Error> {
let mut geometry = crate::render::geometry::GeometrySnapshot::new();
for (bin, fill) in &self.bins {
geometry.polygon(bin, fill, clip)?;
}
if let Some(curve) = &self.curve {
geometry.line(curve, &self.curve_style, clip)?;
}
for rug in &self.rugs {
geometry.line(rug, &self.rug_style, clip)?;
}
Ok(geometry)
}
pub(crate) fn draw(&self, backend: &mut dyn Backend) -> Result<(), Error> {
with_clip(backend, self.clip, |backend| {
for (bin, fill) in &self.bins {
backend.draw_polygon(bin, fill)?;
}
if let Some(curve) = &self.curve {
backend.draw_line(curve, &self.curve_style)?;
}
for rug in &self.rugs {
backend.draw_line(rug, &self.rug_style)?;
}
Ok(())
})
}
}
pub(crate) fn measure_marks(
context: &PlotMeasureContext<'_, '_>,
request: &crate::text::TextRequestContext<'_, '_>,
layout: &crate::layout::Layout,
) -> Result<MeasuredCoordinateMarks, crate::layout::fit::PlanError> {
let prepared = (match context.family()? {
crate::orchestrator::registration::FamilyRef::Histogram(marks) => Some(marks),
_ => None,
})
.ok_or_else(|| {
Error::Render(
"Histogram measurement requires root-prepared semantics for its component".into(),
)
})?;
let theme = request;
let projection = layout.projection.clone();
let mut result = project(prepared, layout, theme)?;
let crate::layout::interior::MarkPayload::Histogram(payload) = &result.marks.payload else {
unreachable!("Histogram selected its own mark payload")
};
let full = payload.geometry(None)?;
let raw_windows = context.registered.raw_windows();
if let Some(ink) = full
.bounds()
.iter()
.copied()
.reduce(crate::render::geometry::GeometryBox::union)
{
let requests = crate::layout::interior::automatic_absolute_ink_expansions(
prepared.source_ranges,
&projection,
ink,
[raw_windows[0].is_none(), raw_windows[1].is_none()],
context.fit_scope(),
)?;
let marks = std::sync::Arc::get_mut(&mut result.marks)
.expect("newly selected Histogram marks have one owner");
let crate::layout::interior::MarkPayload::Histogram(payload) = &mut marks.payload else {
unreachable!("Histogram selected its own mark payload")
};
payload.domain_expansions = requests;
}
Ok(result)
}
pub(crate) fn project(
prepared: &HistogramSemantics,
layout: &crate::layout::Layout,
theme: &crate::text::TextRequestContext<'_, '_>,
) -> Result<MeasuredCoordinateMarks, Error> {
let project = |x, y| {
let (x, y) = layout.projection.project(x, y);
Point2D::new(x, y)
};
let fill = theme
.marks
.get_fills()
.get_bodies()
.get_histogram_bin()
.backend_style(
crate::theme::AccentColors::resolve(theme.marks.get_accents(), 1)?.color(0)?,
);
let payload = HistogramPayload {
clip: layout.projection.panel_box(),
bins: crate::data::source::collect_source(
prepared
.bins
.iter()
.zip(&prepared.bin_alphas)
.map(|(bin, &alpha)| {
let left = project(bin.lower, 0.0);
let right = project(bin.upper, bin.height);
layout.projection.validate_span(
crate::layout::AxisSide::Bottom,
(bin.lower, bin.upper),
(left.x, right.x),
bin.lower < bin.upper,
"histogram polygon width",
)?;
layout.projection.validate_span(
crate::layout::AxisSide::Left,
(0.0, bin.height),
(left.y, right.y),
bin.height != 0.0,
"histogram polygon height",
)?;
Ok((
[
left,
Point2D::new(right.x, left.y),
right,
Point2D::new(left.x, right.y),
],
fill_style(alpha, fill.clone()),
))
}),
)?,
curve: prepared
.curve
.as_ref()
.map(|curve| {
crate::data::source::collect_source(curve.iter().map(|p| Ok(project(p.x, p.y))))
})
.transpose()?,
rugs: crate::data::source::collect_source(prepared.rugs.iter().map(|r| {
let points = [project(r.x, r.baseline), project(r.x, r.top)];
layout.projection.validate_span(
crate::layout::AxisSide::Left,
(r.baseline, r.top),
(points[0].y, points[1].y),
r.baseline < r.top,
"histogram rug interval",
)?;
Ok(points)
}))?,
curve_style: line_style(
prepared.curve_alpha,
theme
.marks
.get_strokes()
.get_curves()
.get_histogram_curve()
.backend_style(),
),
rug_style: theme
.marks
.get_strokes()
.get_curves()
.get_histogram_rug()
.backend_style(),
domain_expansions: [None; 2],
};
let clip = crate::render::backend::validate_clip_region(payload.clip)?.panel();
let geometry = payload.geometry(Some(clip))?;
Ok(MeasuredCoordinateMarks::new(
crate::data::source::source_arc(crate::layout::interior::SelectedMarkPlan {
payload: crate::layout::interior::MarkPayload::Histogram(payload),
geometry,
})?,
))
}
#[derive(Debug)]
struct PreparedHistogram {
edges: Vec<f64>,
heights: Vec<f64>,
contributions: Option<HistogramContributions>,
}
#[derive(Debug)]
struct HistogramContributions {
counts: Vec<usize>,
members: Vec<Vec<usize>>,
total: usize,
}
fn prepare_density_curve(
composite: &HistogramComposite,
values: &[f64],
x_range: (f64, f64),
) -> Result<(Option<Vec<KdePoint>>, Option<f64>), Error> {
let HistogramComposite::KdeAndRug(kde) = composite else {
return Ok((None, None));
};
let mut actual_bandwidth = None;
let curve = match kde {
HistogramKde::Internal => {
let bandwidth = crate::stats::distribution::strict_scott_bandwidth(values)
.map_err(|error| error.with_prefix("histogram KDE"))?;
actual_bandwidth = Some(bandwidth);
let grid = crate::stats::distribution::representable_grid(x_range, KDE_GRID_POINTS)?;
let densities = crate::stats::distribution::gaussian_kde(values, &grid, bandwidth)
.map_err(|error| error.with_prefix("histogram KDE"))?;
let mut curve = Vec::new();
crate::data::source::reserve_source(&mut curve, grid.len())?;
curve.extend(
grid.into_iter()
.zip(densities)
.map(|(x, y)| KdePoint { x, y }),
);
curve
}
HistogramKde::Precomputed { x, y } => {
crate::geometry::validate_kde(x, y, x_range)?;
supplied_curve(x, y)?
}
};
Ok((Some(curve), actual_bandwidth))
}
fn supplied_curve(x: &NumericValues, y: &NumericValues) -> Result<Vec<KdePoint>, Error> {
crate::data::source::collect_source((0..x.len()).map(|row| {
Ok(KdePoint {
x: finite(x, row, "histogram KDE finite x")?,
y: finite(y, row, "histogram KDE density")?,
})
}))
}
fn supplied_bins(input: &crate::plots::HistogramBinsData) -> Result<Vec<Bin>, Error> {
crate::data::source::collect_source((0..input.bin_lower().len()).map(|row| {
Ok(Bin {
lower: finite(input.bin_lower(), row, "histogram bin lower")?,
upper: finite(input.bin_upper(), row, "histogram bin upper")?,
height: finite(input.bin_height(), row, "histogram bin height")?,
})
}))
}
fn supplied_rugs(input: &crate::plots::HistogramRugData) -> Result<Vec<RugSegment>, Error> {
crate::data::source::collect_source((0..input.rug_x().len()).map(|row| {
Ok(RugSegment {
x: finite(input.rug_x(), row, "histogram rug x")?,
baseline: finite(input.rug_baseline(), row, "histogram rug baseline")?,
top: finite(input.rug_top(), row, "histogram rug top")?,
})
}))
}
fn prepare_histogram(
values: &[f64],
bins: HistogramBins,
stat: HistogramStat,
capture: bool,
) -> Result<PreparedHistogram, Error> {
finish_histogram(values, prepare_edges(values, bins)?, stat, capture)
}
fn prepare_edges(values: &[f64], bins: HistogramBins) -> Result<Vec<f64>, Error> {
if values.is_empty() {
return Err(Error::Data(
"histogram: value column contains no observations".into(),
));
}
for (index, value) in values.iter().enumerate() {
if !value.is_finite() {
return Err(Error::Data(
format!("histogram: non-finite value {value} at row {index}").into(),
));
}
}
validate_bins(bins)?;
let (minimum, maximum) = crate::data::min_max(values.iter().copied(), "histogram")?;
if minimum.total_cmp(&maximum).is_eq() {
return constant_edges(minimum, bins);
}
let range = maximum - minimum;
if !range.is_finite() || range <= 0.0 {
return Err(Error::Data(
format!("histogram: numeric range {minimum}..{maximum} is too large to bin safely")
.into(),
));
}
match bins {
HistogramBins::Auto => {
let count = automatic_bin_count(values, range)?;
equal_edges(minimum, maximum, count)
}
HistogramBins::Count(count) => equal_edges(minimum, maximum, count),
HistogramBins::Width(width) => requested_width_edges(minimum, maximum, width),
}
}
fn validate_bins(bins: HistogramBins) -> Result<(), Error> {
match bins {
HistogramBins::Count(0) => Err(Error::Data(
"histogram: bin count must be greater than zero".into(),
)),
HistogramBins::Count(count) if count > MAX_EXPLICIT_BINS => Err(Error::Data(
format!("histogram: bin count {count} exceeds the safety limit of {MAX_EXPLICIT_BINS}")
.into(),
)),
HistogramBins::Width(width) if !width.is_finite() || width <= 0.0 => Err(Error::Data(
format!("histogram: bin width must be positive and finite; got {width}").into(),
)),
HistogramBins::Auto | HistogramBins::Count(_) | HistogramBins::Width(_) => Ok(()),
}
}
fn automatic_bin_count(values: &[f64], range: f64) -> Result<usize, Error> {
let mut sorted = Vec::new();
crate::data::source::reserve_source(&mut sorted, values.len())?;
sorted.extend_from_slice(values);
crate::data::source::sort_numeric_source(&mut sorted)?;
let q1 = crate::stats::distribution::sorted_quantile(&sorted, 0.25);
let q3 = crate::stats::distribution::sorted_quantile(&sorted, 0.75);
let iqr = q3 - q1;
let width = 2.0 * iqr * (values.len() as f64).powf(-1.0 / 3.0);
if width.is_finite() && width > 0.0 {
let raw_count = range / width;
let count = if raw_count.is_finite() {
raw_count.ceil().max(1.0) as usize
} else {
MAX_AUTO_BINS
};
return Ok(count.clamp(1, MAX_AUTO_BINS));
}
Ok(sturges_bin_count(values.len()).min(MAX_AUTO_BINS))
}
fn sturges_bin_count(sample_count: usize) -> usize {
((sample_count as f64).log2() + 1.0).ceil().max(1.0) as usize
}
fn constant_edges(value: f64, bins: HistogramBins) -> Result<Vec<f64>, Error> {
match bins {
HistogramBins::Auto => constant_auto_edges(value),
HistogramBins::Count(count) => constant_count_edges(value, count),
HistogramBins::Width(width) => constant_width_edges(value, width),
}
}
fn constant_auto_edges(value: f64) -> Result<Vec<f64>, Error> {
let mut edges = Vec::new();
crate::data::source::reserve_source(&mut edges, 2)?;
let preferred = [value - 0.5, value + 0.5];
if valid_edges(&preferred) {
edges.extend_from_slice(&preferred);
return Ok(edges);
}
let adjacent = [value.next_down(), value.next_up()];
if valid_edges(&adjacent) {
edges.extend_from_slice(&adjacent);
return Ok(edges);
}
Err(Error::Data(format!(
"histogram: constant value {value} is too large to construct a finite centered automatic bin"
).into()))
}
fn constant_count_edges(value: f64, count: usize) -> Result<Vec<f64>, Error> {
let lower_ulp = value - value.next_down();
let upper_ulp = value.next_up() - value;
let required_padding = lower_ulp.max(upper_ulp) * count as f64 / 2.0;
let mut padding = 0.5_f64.max(required_padding);
for _ in 0..8 {
let lower = value - padding;
let upper = value + padding;
if let Some(edges) = try_equal_edges(lower, upper, count)? {
return Ok(edges);
}
padding *= 2.0;
}
Err(Error::Data(format!(
"histogram: Count({count}) cannot produce distinct finite centered bins around constant value {value}; use fewer bins"
).into()))
}
fn constant_width_edges(value: f64, width: f64) -> Result<Vec<f64>, Error> {
let half_width = width / 2.0;
let edges = [value - half_width, value + half_width];
if half_width > 0.0 && edges[0] < value && edges[1] > value && valid_edges(&edges) {
let mut retained = Vec::new();
crate::data::source::reserve_source(&mut retained, edges.len())?;
retained.extend_from_slice(&edges);
return Ok(retained);
}
Err(Error::Data(format!(
"histogram: Width({width}) cannot produce distinct finite centered edges around constant value {value}; use a wider bin"
).into()))
}
fn equal_edges(lower: f64, upper: f64, count: usize) -> Result<Vec<f64>, Error> {
try_equal_edges(lower, upper, count)?.ok_or_else(|| {
Error::Data(
"histogram: equal-width bin edges are not distinct and finite at this numeric scale; use fewer bins or a wider range"
.into(),
)
})
}
fn try_equal_edges(lower: f64, upper: f64, count: usize) -> Result<Option<Vec<f64>>, Error> {
if count == 0 || count > MAX_EXPLICIT_BINS || !lower.is_finite() || !upper.is_finite() {
return Ok(None);
}
let range = upper - lower;
let width = range / count as f64;
if !range.is_finite() || !width.is_finite() || width <= 0.0 {
return Ok(None);
}
let mut edges = Vec::new();
crate::data::source::reserve_source(&mut edges, count + 1)?;
for index in 0..=count {
edges.push(lower + width * index as f64);
}
edges[count] = upper;
Ok(valid_edges(&edges).then_some(edges))
}
fn requested_width_edges(minimum: f64, maximum: f64, width: f64) -> Result<Vec<f64>, Error> {
let range = maximum - minimum;
let first_upper = minimum + width;
if !first_upper.is_finite() || first_upper <= minimum {
return Err(Error::Data(format!(
"histogram: width {width} cannot produce a distinct finite edge above minimum {minimum}; use a wider bin or Count"
).into()));
}
let raw_count = range / width;
if !raw_count.is_finite() || raw_count.ceil() > MAX_EXPLICIT_BINS as f64 + 1.0 {
return Err(Error::Data(
format!(
"histogram: width {width} would require too many bins for range {minimum}..{maximum}; use a larger width or Count"
).into(),
));
}
let mut count = raw_count.ceil().max(1.0) as usize;
while count > 1 {
let prior = minimum + width * (count - 1) as f64;
if prior.is_finite() && prior >= maximum {
count -= 1;
} else {
break;
}
}
loop {
let upper = minimum + width * count as f64;
if !upper.is_finite() {
return Err(Error::Data(format!(
"histogram: width {width} cannot produce a finite upper edge from minimum {minimum}; use a smaller width or Count"
).into()));
}
if upper >= maximum {
break;
}
count = count.checked_add(1).ok_or_else(|| {
Error::Data("histogram: bin count overflow for requested width".into())
})?;
if count > MAX_EXPLICIT_BINS {
return Err(Error::Data(format!(
"histogram: width {width} requires more than {MAX_EXPLICIT_BINS} bins; use a larger width or Count"
).into()));
}
}
if count > MAX_EXPLICIT_BINS {
return Err(Error::Data(format!(
"histogram: width {width} requires {count} bins, exceeding the safety limit of {MAX_EXPLICIT_BINS}"
).into()));
}
let mut edges = Vec::new();
crate::data::source::reserve_source(&mut edges, count + 1)?;
for index in 0..=count {
edges.push(minimum + width * index as f64);
}
if !valid_edges(&edges) {
return Err(Error::Data(format!(
"histogram: width {width} cannot produce distinct finite edges at this numeric scale; use a wider bin or Count"
).into()));
}
Ok(edges)
}
fn valid_edges(edges: &[f64]) -> bool {
edges.len() >= 2
&& edges.iter().all(|edge| edge.is_finite())
&& edges.windows(2).all(|window| window[1] > window[0])
}
#[cfg(test)]
thread_local! {
static BIN_PREPARATIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn finish_histogram(
values: &[f64],
edges: Vec<f64>,
stat: HistogramStat,
capture: bool,
) -> Result<PreparedHistogram, Error> {
#[cfg(test)]
BIN_PREPARATIONS.with(|count| count.set(count.get() + 1));
if !valid_edges(&edges) {
return Err(Error::Data(
"histogram: computed bin edges are not distinct and finite".into(),
));
}
let count = edges.len() - 1;
let lower = edges[0];
let upper = edges[count];
let mut counts = Vec::new();
crate::data::source::reserve_source(&mut counts, count)?;
counts.resize(count, 0_usize);
let mut members = if capture {
let mut slots = Vec::new();
crate::data::source::reserve_source(&mut slots, count)?;
slots.resize_with(count, Vec::new);
Some(slots)
} else {
None
};
for (index, value) in values.iter().enumerate() {
if index.is_multiple_of(1024) {
crate::operation::checkpoint()?;
}
crate::operation::scientific_work(1)?;
if *value < lower || *value > upper {
return Err(Error::Data(
format!("histogram: value {value} falls outside computed edges {lower}..{upper}")
.into(),
));
}
let mut left = 0;
let mut right = edges.len();
while left < right {
let middle = left + (right - left) / 2;
if edges[middle] <= *value {
left = middle + 1;
} else {
right = middle;
}
}
let insertion = left;
let bin = insertion.saturating_sub(1).min(count - 1);
counts[bin] += 1;
if let Some(members) = &mut members {
crate::data::source::reserve_source(&mut members[bin], 1)?;
members[bin].push(index);
}
}
let sample_count = values.len() as f64;
let mut heights = Vec::new();
crate::data::source::reserve_source(&mut heights, count)?;
for (index, count) in counts.iter().copied().enumerate() {
let actual_width = edges[index + 1] - edges[index];
let height = match stat {
HistogramStat::Count => count as f64,
HistogramStat::Probability => count as f64 / sample_count,
HistogramStat::Density => (count as f64 / sample_count) / actual_width,
};
if !height.is_finite() {
let message = match stat {
HistogramStat::Density => format!(
"histogram: density overflow for representable bin width {actual_width}; use wider or fewer bins"
),
HistogramStat::Count | HistogramStat::Probability => {
"histogram: normalized bin height is not finite".to_string()
}
};
return Err(Error::Data(message.into()));
}
heights.push(height);
}
let contributions = members.map(|members| HistogramContributions {
counts,
members,
total: values.len(),
});
Ok(PreparedHistogram {
edges,
heights,
contributions,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scientific_readback_does_not_repeat_bin_preparation() {
use crate::plots::HistogramInput;
BIN_PREPARATIONS.with(|count| count.set(0));
let plot = Plot::histogram(HistogramInput::samples(NumericValues::new(
"value",
[0., 1., 2.],
)))
.bins(HistogramBins::Count(2));
let first = plot.stat_result().unwrap();
assert_eq!(BIN_PREPARATIONS.with(std::cell::Cell::get), 1);
let run = plot.render_with_results().unwrap();
assert_eq!(BIN_PREPARATIONS.with(std::cell::Cell::get), 2);
let crate::stats::ScientificResult::Histogram(result) = run.results()[0].value() else {
panic!("histogram result")
};
assert_eq!(result.geometry().get_bins(), first.geometry().get_bins());
assert!(run.output().width() > 0.0);
Plot::histogram(HistogramInput::geometry(result.geometry().clone()))
.stat_result()
.unwrap();
assert_eq!(BIN_PREPARATIONS.with(std::cell::Cell::get), 2);
let ordinary =
prepare_histogram(&[0., 1., 2.], HistogramBins::Count(2), HistogramStat::Count)
.unwrap();
assert!(ordinary.contributions.is_none());
}
#[test]
fn supplied_bins_and_optional_components_keep_their_scientific_values() {
use crate::plots::{HistogramGeometry, HistogramInput};
let base = HistogramGeometry::bins(
NumericValues::new("lo", [0., 1., 3.]),
NumericValues::new("hi", [1., 3., 4.]),
NumericValues::new("", [0.25; 3]),
HistogramStat::Density,
);
let theme = crate::Theme::publication().resolve().unwrap();
let text = crate::text::TextService::default();
let theme = crate::text::TextRequestContext::new(&theme, &text);
for (kde, rug) in [(false, false), (true, false), (false, true), (true, true)] {
let mut geometry = base.clone();
if kde {
geometry = geometry.kde(
NumericValues::new("curve x", [0., 1., 2., 3., 4.]),
NumericValues::new("curve density", [0.1, 0.3, 0.4, 0.2, 0.1]),
);
}
if rug {
geometry = geometry.rug(
NumericValues::new("residual", [2., 2.]),
NumericValues::new("base", [0., 0.01]),
NumericValues::new("top", [0.02, 0.03]),
);
}
assert_eq!(geometry.get_height_dimension(), "density");
assert_eq!(
geometry.get_value_dimension(),
if rug { "residual" } else { "value" }
);
assert_eq!(geometry.get_kde().is_some(), kde);
assert_eq!(geometry.get_rug().is_some(), rug);
let plot = Plot::histogram(HistogramInput::geometry(geometry)).erase();
crate::orchestrator::with_prepared_plot_for_test(
&plot,
&theme,
|_| Ok(()),
|source, registrations, _, _, _| {
assert_eq!(source.row_count(), 0);
let crate::orchestrator::registration::PreparedFamily::Histogram(prepared) =
®istrations.plots[0].family
else {
panic!("expected prepared histogram");
};
assert_eq!(prepared.bins.len(), 3);
let area = prepared
.bins
.iter()
.map(|bin| (bin.upper - bin.lower) * bin.height)
.sum::<f64>();
assert_eq!(area.to_bits(), 1.0_f64.to_bits());
assert_eq!(prepared.curve.as_ref().map(Vec::len), kde.then_some(5));
assert_eq!(prepared.rugs.len(), if rug { 2 } else { 0 });
if rug {
assert_eq!(prepared.rugs[0].x.to_bits(), prepared.rugs[1].x.to_bits());
}
},
)
.unwrap();
}
let plot = Plot::histogram(HistogramInput::geometry(base));
assert!(plot
.clone()
.stat(HistogramStat::Count)
.preflight()
.unwrap_err()
.to_string()
.contains("declared statistic"));
let count = HistogramGeometry::bins(
NumericValues::new("lo", [0., 1.]),
NumericValues::new("hi", [1., 2.]),
NumericValues::new("counts", [2., 5.]),
HistogramStat::Count,
);
let plot = Plot::histogram(HistogramInput::geometry(count.clone()));
plot.preflight().unwrap();
let invalid = plot
.kde(
NumericValues::new("x", [0., 2.]),
NumericValues::new("density", [0.5, 0.5]),
)
.unwrap();
assert!(invalid
.preflight()
.unwrap_err()
.to_string()
.contains("density bin heights"));
}
fn prepare_histogram(
values: &[f64],
bins: HistogramBins,
stat: HistogramStat,
) -> Result<PreparedHistogram, Error> {
super::prepare_histogram(values, bins, stat, false)
}
fn finish_histogram(
values: &[f64],
edges: Vec<f64>,
stat: HistogramStat,
) -> Result<PreparedHistogram, Error> {
super::finish_histogram(values, edges, stat, false)
}
#[test]
#[expect(
clippy::too_many_lines,
reason = "one exact-bin contract retains independent prepared intervals, actual facet paint and pre-font completeness"
)]
fn actual_bin_alpha_uses_exact_edges_and_facet_keys_without_sample_aggregation() {
let source = Plot::histogram(crate::plots::HistogramInput::samples(
crate::NumericValues::new("sample", (1..=8).chain(11..=18).map(f64::from)),
))
.facet(crate::layout::FacetSpec::column(
crate::CategoryValues::new(
"panel",
std::iter::repeat_n("left", 8).chain(std::iter::repeat_n("right", 8)),
)
.unwrap(),
))
.with_alpha(
AlphaTarget::Fill,
crate::alpha::AlphaEncoding::bins(
crate::data::Bounds::new(
crate::NumericValues::new("lower", [14.5, 1.0, 11.0, 4.5, 100.0]),
crate::NumericValues::new("upper", [18.0, 4.5, 14.5, 8.0, 200.0]),
),
[crate::CategoryValues::new(
"panel",
["right", "left", "right", "left", "\u{10ffff}"],
)
.unwrap()],
crate::alpha::AlphaValues::new(
"bin confidence",
[
0.0,
128.0 / 255.0,
230.0 / 255.0,
64.0 / 255.0,
99.0 / 255.0,
],
)
.unwrap(),
)
.unwrap(),
)
.erase();
let theme = crate::Theme::publication().resolve().unwrap();
let text = crate::text::TextService::default();
let theme = crate::text::TextRequestContext::new(&theme, &text);
crate::orchestrator::with_prepared_plot_for_test(
&source,
&theme,
|_| Ok(()),
|chart, inputs, _theme, _operation, round| {
let panels = &inputs.plots;
assert_eq!(panels.len(), 2);
for (registered, (edges, alphas)) in panels.iter().zip([
([1.0_f64, 4.5, 8.0], [128.0 / 255.0, 64.0 / 255.0]),
([11.0_f64, 14.5, 18.0], [230.0 / 255.0, 0.0]),
]) {
let crate::orchestrator::registration::PreparedFamily::Histogram(prepared) =
®istered.family
else {
panic!("prepared Histogram")
};
assert_eq!(
prepared
.bins
.iter()
.map(|bin| (
bin.lower.to_bits(),
bin.upper.to_bits(),
bin.height.to_bits()
))
.collect::<Vec<_>>(),
[
(edges[0].to_bits(), edges[1].to_bits(), 4.0_f64.to_bits()),
(edges[1].to_bits(), edges[2].to_bits(), 4.0_f64.to_bits()),
]
);
assert_eq!(
prepared
.bin_alphas
.iter()
.map(|alpha| alpha.unwrap().alpha)
.collect::<Vec<_>>(),
alphas
);
let measurement = inputs.assignment_factory().assign(
chart
.sizing_request()
.assigned_size()
.unwrap_or(crate::layout::RootSize::new(1, 1)),
);
let factory = inputs
.plot_assignment_factory(&measurement, ®istered.scope.id)
.unwrap();
let selected = crate::layout::interior::measure_for_test(
&factory,
crate::layout::PixelRect::new(20.0, 600.0, 20.0, 420.0),
round,
)
.unwrap();
let crate::layout::interior::MarkPayload::Histogram(payload) =
&selected.marks.as_ref().unwrap().payload
else {
panic!("Histogram payload")
};
assert_eq!(
payload
.bins
.iter()
.map(|(_, fill)| fill.color.get_alpha())
.collect::<Vec<_>>(),
alphas
);
}
let calls = crate::font::canonical::FONT_DISCOVERY_CALLS.with(std::cell::Cell::get);
let incomplete = source.clone().with_alpha(
AlphaTarget::Fill,
crate::alpha::AlphaEncoding::bins(
crate::data::Bounds::new(
crate::NumericValues::new("lower", [1.0]),
crate::NumericValues::new("upper", [4.5]),
),
[crate::CategoryValues::new("panel", ["left"]).unwrap()],
crate::alpha::AlphaValues::new("bin confidence", [0.0]).unwrap(),
)
.unwrap(),
);
assert!(matches!(
incomplete.preflight().unwrap_err(),
Error::Data(_)
));
assert_eq!(
crate::font::canonical::FONT_DISCOVERY_CALLS.with(std::cell::Cell::get),
calls
);
},
)
.unwrap();
}
#[test]
fn values_around_internal_edge_follow_half_open_ulp_boundaries() {
let edge = 1.0_f64;
let histogram = finish_histogram(
&[0.0, edge.next_down(), edge, edge.next_up(), 2.0],
vec![0.0, edge, 2.0],
HistogramStat::Count,
)
.unwrap();
assert_eq!(histogram.heights, [2.0, 3.0]);
}
#[test]
fn density_uses_each_uneven_representable_width_at_large_scale() {
let base = 1e16_f64;
let histogram = prepare_histogram(
&[base, base + 2.0, base + 4.0, base + 6.0, base + 8.0],
HistogramBins::Count(3),
HistogramStat::Density,
)
.unwrap();
let widths = histogram
.edges
.windows(2)
.map(|window| window[1] - window[0])
.collect::<Vec<_>>();
assert_eq!(widths, [2.0, 4.0, 2.0]);
assert!((density_integral(&histogram) - 1.0).abs() < 1e-12);
}
#[test]
fn unsafe_bin_allocations_and_extreme_ranges_are_rejected() {
assert!(prepare_histogram(
&[0.0, 1.0],
HistogramBins::Count(MAX_EXPLICIT_BINS + 1),
HistogramStat::Count
)
.is_err());
assert!(prepare_histogram(
&[0.0, 1.0],
HistogramBins::Width(f64::MIN_POSITIVE),
HistogramStat::Count
)
.is_err());
assert!(prepare_histogram(
&[-f64::MAX, f64::MAX],
HistogramBins::Count(2),
HistogramStat::Count
)
.is_err());
}
fn density_integral(histogram: &PreparedHistogram) -> f64 {
histogram
.heights
.iter()
.zip(histogram.edges.windows(2))
.map(|(height, edge)| height * (edge[1] - edge[0]))
.sum()
}
}