#![allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_lossless,
clippy::cast_precision_loss,
clippy::too_many_lines
)]
use crate::Error;
use crate::builder::PlotDescription;
use crate::data::PlotData;
use crate::layout::interior::MeasuredCoordinateMarks;
use crate::plots::categorical_distribution::{self, DistributionPayload, PreparedDistribution};
use crate::plots::RawOverlay;
use crate::render::backend::Point2D;
use crate::spec::PlotMeasureContext;
mod result;
#[derive(Debug, PartialEq)]
struct BoxStatistics {
lo_fence: f64,
hi_fence: f64,
lo_whisker: f64,
q1: f64,
median: f64,
q3: f64,
hi_whisker: f64,
}
#[derive(Debug)]
struct BoxStats {
lo_fence: f64,
hi_fence: f64,
x_index: usize,
group_index: usize,
lo_whisker: f64,
q1: f64,
median: f64,
q3: f64,
hi_whisker: f64,
fliers: Vec<crate::plots::distribution_sample::DistributionObservation>,
}
#[derive(Debug)]
pub(crate) struct PreparedBoxplot {
pub(crate) sample: crate::plots::distribution_sample::DistributionSample,
stats: Vec<BoxStats>,
pub(crate) range: (f64, f64),
}
pub(crate) fn intrinsic_body_minimum(
chart: &PlotDescription,
registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
theme: &crate::text::TextRequestContext<'_, '_>,
) -> Result<(f64, f64), Error> {
let PreparedDistribution::Boxplot(prepared) = categorical_distribution::retained(
registered.map(|registered| registered.family.as_ref()),
)?
else {
return Err(Error::Render(
"Boxplot intrinsic requires prepared summaries".into(),
));
};
let sample = &prepared.sample;
let x_levels = ®istered
.expect("prepared Boxplot occurrence")
.axes
.categories(0)
.expect("prepared distribution categories")
.raw;
if x_levels.is_empty() || prepared.stats.len() != sample.groups.len() {
return Err(Error::Render(
"Boxplot summary and populated groups differ".into(),
));
}
let group_count = sample.group_levels.len();
let thickness = if group_count > 0 {
(0.72 / group_count as f64).min(0.32)
} else {
0.5
};
let fill = theme
.marks
.get_fills()
.get_bodies()
.get_box_body()
.backend_style((0, 0, 0));
let overlay = chart.raw_overlay_spec();
let point_style = if overlay.is_visible() {
chart.distribution_point_style(theme.marks.get_points().get_raw_overlay(), (0, 0, 0))
} else {
chart.point_style(
theme,
theme.marks.get_neutral_paints().get_box_flier().as_rgb(),
theme.marks.get_points().get_radii().get_box_flier(),
)
};
let mut pitch = 1.0_f64 / 1024.0;
let mut numeric = 0.0_f64;
for (stat, group) in prepared.stats.iter().zip(&sample.groups) {
let fill = crate::alpha::marks::fill_style(group.fill_alpha, fill.clone());
let body = crate::render::geometry::rectangular_fill_ink_bounds(&fill)?;
let (_, out_y) = crate::render::geometry::rectangular_fill_ink_outset(&fill)?;
let summary = crate::render::geometry::line_ink_width(&crate::alpha::marks::line_style(
group.line_alpha,
theme
.marks
.get_strokes()
.get_summaries()
.get_summary()
.backend_style(),
))?;
numeric = numeric.max(summary).max(out_y);
if stat.x_index != group.x_index
|| stat.group_index != group.group_index
|| group.x_index >= x_levels.len()
{
return Err(Error::Render(
"Boxplot summary is outside its prepared category slot".into(),
));
}
let center = crate::plots::distribution_sample::center(group, group_count);
let offset = center - (group.x_index as f64 + 0.5);
let half = thickness / 2.0;
let left_room = 0.5 + offset - half;
let right_room = 0.5 - offset - half;
if left_room <= 0.0 || right_room <= 0.0 {
return Err(Error::Render(
"Boxplot body exceeds prepared category slot".into(),
));
}
pitch = pitch.max((1.0 / 1024.0) / thickness);
if let Some(ink) = body {
pitch = pitch.max((-ink.left).max(0.0) / left_room);
pitch = pitch.max(ink.right.max(0.0) / right_room);
}
if summary > 0.0 {
pitch = pitch.max((summary / 2.0) / left_room);
pitch = pitch.max((summary / 2.0) / right_room);
}
let observations = if overlay.is_visible() {
&group.observations
} else {
&stat.fliers
};
if let Some(ink) = crate::alpha::marks::point_ink(
&point_style,
observations.iter().map(|observation| {
let x = crate::plots::distribution_sample::overlay_x(
overlay,
center,
thickness,
observation.alpha.source_row,
);
(x, observation.value, observation.alpha)
}),
)? {
let left = ink.ranges[0].0 - (group.x_index as f64 + 0.5);
let right = ink.ranges[0].1 - (group.x_index as f64 + 0.5);
pitch = pitch.max((-ink.bounds.left).max(0.0) / (0.5 + left));
pitch = pitch.max(ink.bounds.right.max(0.0) / (0.5 - right));
numeric = numeric.max(ink.dimensions().1);
}
}
let count = u32::try_from(x_levels.len())
.map_err(|_| Error::Render("Boxplot category count exceeds coordinate range".into()))?;
let category_span = pitch * f64::from(count);
if !category_span.is_finite() {
return Err(Error::Render(
"Boxplot category hard span overflowed".into(),
));
}
Ok((
category_span,
if registered.expect("prepared occurrence").raw_windows()[1].is_none() {
numeric
} else {
0.0
},
))
}
pub(crate) fn prepare(
chart: &crate::builder::PlotDescription,
data: PlotData<'_, '_>,
facet: Option<crate::data::FacetAxisSources<'_>>,
) -> Result<(PreparedBoxplot, Vec<String>, Vec<String>), Error> {
let (sample, categories, hue_levels) =
crate::plots::distribution_sample::prepare_scoped(chart, data, "boxplot", facet)?;
let stats = crate::data::source::collect_source(sample.groups.iter().map(
|group| -> Result<BoxStats, Error> {
let mut ys = crate::data::source::collect_source(
group.observations.iter().map(|o| Ok(o.value)),
)?;
let summary = box_summary_with_source(&mut ys)?;
let mut fliers = Vec::new();
crate::data::source::reserve_source(&mut fliers, group.observations.len())?;
fliers.extend(group.observations.iter().copied().filter(|observation| {
observation.value < summary.lo_whisker || observation.value > summary.hi_whisker
}));
crate::data::source::sort_source_by(&mut fliers, |a, b| {
a.value
.total_cmp(&b.value)
.then_with(|| a.alpha.slot.cmp(&b.alpha.slot))
})?;
Ok(BoxStats {
lo_fence: summary.lo_fence,
hi_fence: summary.hi_fence,
x_index: group.x_index,
group_index: group.group_index,
lo_whisker: summary.lo_whisker,
q1: summary.q1,
median: summary.median,
q3: summary.q3,
hi_whisker: summary.hi_whisker,
fliers,
})
},
))?;
let y_min = stats.iter().fold(f64::INFINITY, |min, stat| {
stat.fliers
.iter()
.map(|observation| observation.value)
.fold(min.min(stat.lo_whisker), f64::min)
});
let y_max = stats.iter().fold(f64::NEG_INFINITY, |max, stat| {
stat.fliers
.iter()
.map(|observation| observation.value)
.fold(max.max(stat.hi_whisker), f64::max)
});
Ok((
PreparedBoxplot {
sample,
stats,
range: (y_min, y_max),
},
categories,
hue_levels,
))
}
impl PreparedBoxplot {
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::alpha::AlphaUnitKind;
use crate::decorations::legend::alpha::{AlphaGlyphRole, AlphaUnit};
let fill = theme.marks.get_fills().get_bodies().get_box_body();
let overlay = chart.raw_overlay_spec();
for (group, stat) in self.sample.groups.iter().zip(&self.stats) {
let unit = AlphaUnit::aggregate(chart, &group.label, group.group_label.as_deref())?;
guide.fill(
AlphaGlyphRole::Fill,
AlphaUnitKind::Aggregate,
unit.clone(),
group.fill_alpha,
fill.backend_style((0, 0, 0)),
fill.get_outline()
.is_some_and(|outline| outline.mapped_width().is_some()),
)?;
guide.line(
AlphaGlyphRole::Summary,
AlphaUnitKind::Aggregate,
unit,
group.line_alpha,
theme
.marks
.get_strokes()
.get_summaries()
.get_summary()
.backend_style(),
false,
)?;
if overlay == RawOverlay::Hidden {
let point = chart.point_style(
theme,
(0, 0, 0),
theme.marks.get_points().get_radii().get_box_flier(),
);
for observation in &stat.fliers {
guide.point(
AlphaGlyphRole::Outlier,
observation.alpha,
point.clone(),
false,
)?;
}
} else {
let point = chart.distribution_point_style(
theme.marks.get_points().get_raw_overlay(),
(0, 0, 0),
);
for observation in &group.observations {
guide.point(
AlphaGlyphRole::RawOverlay,
observation.alpha,
point.clone(),
false,
)?;
}
}
}
Ok(())
}
}
pub(crate) fn measure_marks(
chart: &PlotDescription,
context: &PlotMeasureContext<'_, '_>,
request: &crate::text::TextRequestContext<'_, '_>,
layout: &crate::layout::Layout,
) -> Result<MeasuredCoordinateMarks, crate::layout::fit::PlanError> {
let PreparedDistribution::Boxplot(prepared) =
categorical_distribution::retained(Some(context.family()?))?
else {
return Err(Error::Render("boxplot requires retained box summaries".into()).into());
};
let theme = request;
theme.text.prepared_font_environment()?;
let data = context.data()?;
let sample = &prepared.sample;
let stats = &prepared.stats;
let x_levels = &context
.registered
.axes
.categories(0)
.expect("prepared distribution categories")
.raw;
let group_levels = &sample.group_levels;
let group_active = !group_levels.is_empty();
let base_y_range = layout.projection.y_range();
let mut rendered_maxima =
crate::data::source::collect_source((0..x_levels.len()).map(|_| Ok(f64::NEG_INFINITY)))?;
let mut grouped_maxima = crate::data::source::collect_source((0..x_levels.len()).map(|_| {
crate::data::source::collect_source(
(0..group_levels.len().max(1)).map(|_| Ok(f64::NEG_INFINITY)),
)
}))?;
for stat in stats {
let maximum = stat
.fliers
.iter()
.map(|observation| observation.value)
.fold(stat.hi_whisker, f64::max);
rendered_maxima[stat.x_index] = rendered_maxima[stat.x_index].max(maximum);
grouped_maxima[stat.x_index][stat.group_index] = maximum;
}
let overlay = chart.raw_overlay_spec();
let panel = context.assignment.local.body;
let colors = {
let retained = categorical_distribution::retained(Some(context.family()?))?;
retained.resolved_colors(
chart,
&context.registered.axes,
context
.registered
.categorical
.as_ref()
.expect("prepared color binding"),
theme,
data.source_resources(),
false,
)?
};
let significance = if group_levels.is_empty() {
crate::significance::plan(
context.registered,
context.registered.significance_annotations(),
x_levels,
&rendered_maxima,
base_y_range,
panel,
theme,
context.fit_scope(),
)?
} else {
crate::significance::plan_grouped(
context.registered,
context.registered.significance_annotations(),
x_levels,
group_levels,
&grouped_maxima,
0.72,
base_y_range,
panel,
false,
theme,
context.fit_scope(),
)?
};
let proj = &layout.projection;
let box_w_data = if group_active {
(0.72 / group_levels.len() as f64).min(0.32)
} else {
0.5
};
let mut payload = DistributionPayload::new(layout.projection.panel_box());
for (i, stat) in stats.iter().enumerate() {
let group = &sample.groups[i];
let color = colors.color(group.hue_label.as_deref().unwrap_or(&group.label))?;
let fill = crate::alpha::marks::fill_style(
group.fill_alpha,
theme
.marks
.get_fills()
.get_bodies()
.get_box_body()
.backend_style(color),
);
let style = crate::alpha::marks::line_style(
group.line_alpha,
theme
.marks
.get_strokes()
.get_summaries()
.get_summary()
.backend_style(),
);
let x_center_data =
crate::plots::distribution_sample::center(&sample.groups[i], group_levels.len());
let (xc, _) = proj.project(x_center_data, 0.0);
let box_w_px = (proj.project(box_w_data, 0.0).0 - proj.project(0.0, 0.0).0).abs();
let (_, y_lo) = proj.project(x_center_data, stat.lo_whisker);
let (_, y_q1) = proj.project(x_center_data, stat.q1);
let (_, y_med) = proj.project(x_center_data, stat.median);
let (_, y_q3) = proj.project(x_center_data, stat.q3);
let (_, y_hi) = proj.project(x_center_data, stat.hi_whisker);
for (source, projected, context) in [
((stat.q1, stat.q3), (y_q1, y_q3), "boxplot polygon"),
(
(stat.lo_whisker, stat.q1),
(y_lo, y_q1),
"boxplot lower whisker",
),
(
(stat.q3, stat.hi_whisker),
(y_q3, y_hi),
"boxplot upper whisker",
),
] {
proj.validate_span(
crate::layout::AxisSide::Left,
source,
projected,
source.0 < source.1,
context,
)?;
}
let pts = crate::data::source::collect_source(
[
Point2D::new(xc - box_w_px / 2.0, y_q1),
Point2D::new(xc - box_w_px / 2.0, y_q3),
Point2D::new(xc + box_w_px / 2.0, y_q3),
Point2D::new(xc + box_w_px / 2.0, y_q1),
]
.into_iter()
.map(Ok),
)?;
payload.polygon(pts, fill)?;
payload.line(
&[
Point2D::new(xc - box_w_px / 2.0, y_med),
Point2D::new(xc + box_w_px / 2.0, y_med),
],
&style,
)?;
payload.line(&[Point2D::new(xc, y_q3), Point2D::new(xc, y_hi)], &style)?;
payload.line(&[Point2D::new(xc, y_q1), Point2D::new(xc, y_lo)], &style)?;
let cap = box_w_px * 0.3;
payload.line(
&[Point2D::new(xc - cap, y_hi), Point2D::new(xc + cap, y_hi)],
&style,
)?;
payload.line(
&[Point2D::new(xc - cap, y_lo), Point2D::new(xc + cap, y_lo)],
&style,
)?;
if overlay == RawOverlay::Hidden {
let flier_style = chart.point_style(
theme,
theme.marks.get_neutral_paints().get_box_flier().as_rgb(),
theme.marks.get_points().get_radii().get_box_flier(),
);
let flier_points =
crate::data::source::collect_source(stat.fliers.iter().map(|observation| {
let (x_px, y_px) = proj.project(x_center_data, observation.value);
Ok(Point2D::new(x_px, y_px))
}))?;
if !flier_points.is_empty() {
payload.scatter(
flier_points,
&flier_style,
stat.fliers.iter().map(|observation| observation.alpha),
)?;
}
}
}
if overlay.is_visible() {
for group in &sample.groups {
let center = crate::plots::distribution_sample::center(group, group_levels.len());
let points = crate::data::source::collect_source(group.observations.iter().map(
|observation| {
let x = crate::plots::distribution_sample::overlay_x(
overlay,
center,
box_w_data,
observation.alpha.source_row,
);
let (x, y) = proj.project(x, observation.value);
Ok(Point2D::new(x, y))
},
))?;
payload.scatter(
points,
&chart.distribution_point_style(
theme.marks.get_points().get_raw_overlay(),
colors.color(group.hue_label.as_deref().unwrap_or(&group.label))?,
),
group
.observations
.iter()
.map(|observation| observation.alpha),
)?;
}
}
let mut result = payload.retain(layout, context)?;
result.significance = Some(significance);
Ok(result)
}
fn box_summary_with_source(values: &mut [f64]) -> Result<BoxStatistics, Error> {
if values.is_empty() || values.iter().any(|v| !v.is_finite()) {
return Err(Error::Data(
"boxplot: samples must be finite and nonempty".into(),
));
}
crate::data::source::sort_numeric_source(values)?;
let q1 = crate::stats::distribution::sorted_quantile(values, 0.25);
let median = crate::stats::distribution::sorted_quantile(values, 0.5);
let q3 = crate::stats::distribution::sorted_quantile(values, 0.75);
let (lo_fence, hi_fence) = crate::stats::distribution::tukey_fences(q1, q3)?;
let lo_whisker = values
.iter()
.copied()
.find(|value| *value >= lo_fence)
.unwrap_or(q1);
let hi_whisker = values
.iter()
.rev()
.copied()
.find(|value| *value <= hi_fence)
.unwrap_or(q3);
Ok(BoxStatistics {
lo_fence,
hi_fence,
lo_whisker,
q1,
median,
q3,
hi_whisker,
})
}