#![allow(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
clippy::cast_lossless,
clippy::cast_precision_loss,
clippy::too_many_lines,
clippy::similar_names,
clippy::many_single_char_names,
clippy::redundant_closure_for_method_calls,
clippy::unnecessary_cast
)]
use crate::alpha::{
marks::{
fill_ink_outset, fill_style, point_ink, push_point, require_aligned_points,
ObservationAlpha,
},
AlphaTarget, AlphaUnitKind, ResolvedAlpha,
};
use crate::builder::PlotDescription;
use crate::decorations::legend::source::{FillRole, PointRole};
use crate::decorations::legend::GuideSourceKey;
use crate::layout::fit::PlanError;
use crate::layout::{self, AuthoredAxisSpec, PixelRect};
use crate::orchestrator::registration::{
AxisSlot, AxisSourceWitness, AxisSpace, DisplayExtent, MarginalStrip, PlotOccurrenceId,
PreparedAxesOwner, PreparedAxisSource,
};
use crate::render::backend::{with_clip, Backend, FillStyle, Point2D};
use crate::spec::{PlotMeasureContext, PlotRenderResult};
use crate::stats::distribution::{gaussian_kde, representable_grid, strict_scott_bandwidth};
use crate::theme::{AccentColors, CategoryColors};
use crate::Error;
#[cfg(test)]
use crate::Plot;
pub(crate) mod result;
const MARGINAL_KDE_CUT: f64 = 3.0;
const MARGINAL_KDE_GRID_POINTS: usize = 256;
const MARGINAL_KDE_VISIBLE_FRACTION: f64 = 0.02;
const MARGINAL_DATA_MARGIN_FRACTION: f64 = 0.06;
#[derive(Debug)]
struct HueGroup {
identity: crate::data::CollectivePair,
collapsed: bool,
x: Vec<f64>,
y: Vec<f64>,
alphas: Vec<ObservationAlpha>,
fill_alpha: Option<ResolvedAlpha>,
bandwidths: [Option<f64>; 2],
}
impl HueGroup {
fn distribution(&self, side: usize) -> (&[f64], f64) {
let values = if side == 0 { &self.x } else { &self.y };
(
values,
self.bandwidths[side].expect("prepared marginal bandwidth"),
)
}
}
#[derive(Debug)]
pub(crate) struct PreparedMarginal {
groups: Vec<HueGroup>,
curves: MarginalCurves,
}
impl PreparedMarginal {
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 point = chart.point_style(
theme,
(0, 0, 0),
theme.marks.get_points().get_radii().get_marginal(),
);
let fill = theme
.marks
.get_fills()
.get_densities()
.get_marginal_density();
for group in &self.groups {
for &alpha in &group.alphas {
guide.point(AlphaGlyphRole::Primary, alpha, point.clone(), false)?;
}
guide.fill(
AlphaGlyphRole::Fill,
AlphaUnitKind::Series,
AlphaUnit::series(chart, Some(&group.identity))?,
group.fill_alpha,
fill.backend_style((0, 0, 0)),
fill.get_outline()
.is_some_and(|outline| outline.mapped_width().is_some()),
)?;
}
Ok(())
}
pub(crate) fn checked_primary_mark_count(&self) -> Result<u128, Error> {
let mut count = 0_u128;
for group in &self.groups {
count = count
.checked_add(group.x.len() as u128)
.ok_or_else(|| Error::Render("Marginal mark count overflow".into()))?;
}
Ok(count)
}
fn resolved_colors(
&self,
binding: &crate::orchestrator::registration::CategoricalBinding,
theme: &crate::theme::ResolvedTheme,
resources: &crate::font::canonical::OperationContext,
) -> Result<(CategoryColors, AccentColors), Error> {
let colors = binding.resolve(binding.values(), theme, resources)?;
let accents = AccentColors::resolve(
theme.marks.get_accents(),
usize::from(self.groups.iter().any(|group| group.identity.hue.is_none())),
)?;
Ok((colors, accents))
}
fn group_color(
group: &HueGroup,
colors: &CategoryColors,
accents: &AccentColors,
) -> Result<(u8, u8, u8), Error> {
if let Some(hue) = &group.identity.hue {
colors.color(hue)
} else {
accents.color(0)
}
}
pub(crate) fn hue_levels(&self) -> impl Iterator<Item = &str> {
self.groups
.iter()
.filter_map(|group| group.identity.hue.as_deref())
}
pub(crate) fn guide_entries(
&self,
chart: &crate::builder::PlotDescription,
binding: &crate::orchestrator::registration::CategoricalBinding,
theme: &crate::theme::ResolvedTheme,
operation: &crate::font::canonical::OperationContext,
) -> Result<Vec<GuideSourceKey>, Error> {
let (colors, accents) = self.resolved_colors(binding, theme, operation)?;
self.guide_entries_with_colors(chart, theme, &colors, &accents)
}
fn guide_entries_with_colors(
&self,
chart: &crate::builder::PlotDescription,
theme: &crate::theme::ResolvedTheme,
colors: &CategoryColors,
accents: &AccentColors,
) -> Result<Vec<GuideSourceKey>, Error> {
let mut entries = Vec::new();
crate::data::source::reserve_source(&mut entries, self.groups.len())?;
for group in &self.groups {
if group.identity.hue.is_none() {
continue;
}
let color = Self::group_color(group, colors, accents)?;
entries.push(
GuideSourceKey::collective(
chart.collective_legend_identity(&group.identity)?,
chart,
false,
)?
.with_point(
chart.point_style(
theme,
color,
theme.marks.get_points().get_radii().get_marginal(),
),
PointRole::Primary,
)
.with_fill(
theme
.marks
.get_fills()
.get_densities()
.get_marginal_density(),
color,
FillRole::MarginalDensity,
),
);
}
Ok(entries)
}
}
pub(crate) fn intrinsic_body_minimum(
chart: &PlotDescription,
registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
intrinsic: &crate::orchestrator::root::PlotIntrinsics,
operation: &crate::font::canonical::OperationContext,
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::Marginal(marks) => Some(marks),
_ => None,
})
.ok_or_else(|| Error::Render("marginal intrinsic requires prepared groups".into()))?;
let mut central = crate::orchestrator::root::coordinate_intrinsic(
intrinsic,
&crate::orchestrator::root::intrinsic_inputs(registered, theme, operation)?,
)?
.minimum(crate::orchestrator::registration::axis_tick_labels_visible(
registered, 1,
));
for group in &prepared.groups {
let style = chart.point_style(
theme,
(0, 0, 0),
theme.marks.get_points().get_radii().get_marginal(),
);
require_aligned_points(group.x.len(), group.alphas.len())?;
if let Some(ink) = point_ink(
&style,
group
.x
.iter()
.zip(&group.y)
.zip(&group.alphas)
.map(|((&x, &y), &alpha)| (x, y, alpha)),
)? {
let (x, y) = ink.dimensions();
central.0 = central.0.max(x);
central.1 = central.1.max(y);
}
}
let (out_x, out_y) = density_ink(registered, theme)?;
Ok((
central.0 + theme.marginal_gaps()?.column + (1.0 / 1024.0_f64).max(2.0 * out_x),
central.1 + theme.marginal_gaps()?.row + (1.0 / 1024.0_f64).max(2.0 * out_y),
))
}
fn density_ink(
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::Marginal(marks) => Some(marks),
_ => None,
})
.ok_or_else(|| Error::Render("Marginal density ink requires prepared groups".into()))?;
fill_ink_outset(
&theme
.marks
.get_fills()
.get_densities()
.get_marginal_density()
.backend_style((0, 0, 0)),
prepared.groups.iter().map(|group| group.fill_alpha),
)
}
#[derive(Debug, Default)]
struct MarginalCurves {
x_grid: Vec<f64>,
y_grid: Vec<f64>,
x_densities: Vec<Vec<f64>>,
y_densities: Vec<Vec<f64>>,
}
impl MarginalCurves {
fn region(&self, side: usize) -> (&[f64], &[Vec<f64>]) {
if side == 0 {
(&self.x_grid, &self.x_densities)
} else {
(&self.y_grid, &self.y_densities)
}
}
}
fn display_maximum(densities: &[Vec<f64>]) -> f64 {
densities
.iter()
.flat_map(|density| crate::stats::distribution::closed_density(density))
.fold(0.0_f64, f64::max)
}
#[derive(Debug)]
struct MarginalGroupPayload {
point_batches: Vec<(Vec<Point2D>, crate::render::backend::PointStyle)>,
source_rows: Vec<usize>,
top: Vec<Point2D>,
right: Vec<Point2D>,
fill: FillStyle,
}
#[derive(Debug)]
struct MarginalRegionProjection {
address: crate::layout::ComponentAddress,
projection: layout::Projection,
}
fn measure_linked_panel(
panel: PixelRect,
ranges: [(f64, f64); 2],
role: layout::AddressRole,
context: &PlotMeasureContext<'_, '_>,
) -> Result<MarginalRegionProjection, crate::layout::fit::PlanError> {
if ![panel.x0, panel.x1, panel.y0, panel.y1]
.into_iter()
.all(f64::is_finite)
|| ranges
.iter()
.any(|range| !range.0.is_finite() || !range.1.is_finite() || range.0 >= range.1)
{
return Err(Error::Render(
"Marginal linked subpanel assignment/domain is not finite and ordered".into(),
)
.into());
}
let address = context.fit_scope().address.child(role, 0)?;
if panel.width() <= 0.0 || panel.height() <= 0.0 {
return Err(crate::layout::fit::FitScope::new(&address, 0)
.failure(
crate::layout::fit::FitKind::AssignedChild,
"Marginal linked subpanel has no positive assigned extent",
)
.into());
}
Ok(MarginalRegionProjection {
address,
projection: layout::Projection::new(ranges[0], ranges[1], panel.as_tuple()),
})
}
#[derive(Debug)]
pub(crate) struct MarginalPayload {
panels: [MarginalRegionProjection; 3],
ticks: Vec<[Point2D; 2]>,
tick_style: Option<crate::render::backend::LineStyle>,
groups: Vec<MarginalGroupPayload>,
pub(crate) domain_expansions: [Option<crate::layout::interior::DomainExpansion>; 2],
}
impl MarginalPayload {
pub(crate) fn layout_regions(
&self,
) -> impl Iterator<Item = (crate::layout::MarginalRegion, PixelRect)> + '_ {
[
crate::layout::MarginalRegion::Joint,
crate::layout::MarginalRegion::Top,
crate::layout::MarginalRegion::Right,
]
.into_iter()
.zip(self.panels.iter().map(|panel| panel.projection.panel_box()))
}
fn clips(&self) -> [PixelRect; 3] {
self.panels
.each_ref()
.map(|panel| panel.projection.panel_box())
}
pub(crate) fn observe_subpanels(
&self,
round: &mut layout::kernel::FeedbackRound,
) -> Result<(), Error> {
for panel in &self.panels {
round.begin_owner(&panel.address)?;
round.observe_box(panel.projection.panel_box())?;
let ranges = [panel.projection.x_range(), panel.projection.y_range()];
for (lower, upper) in ranges {
round.observe_number(lower)?;
round.observe_number(upper)?;
}
}
round.begin_owner(&self.panels[0].address)?;
for group in &self.groups {
for row in &group.source_rows {
round.observe_count(*row)?;
}
}
Ok(())
}
pub(crate) fn draw(
&self,
owner: &layout::PanelPath,
backend: &mut dyn Backend,
) -> Result<(), Error> {
use crate::{
elements::LayerSlot,
layout::{MarginalRegion, PaintRole},
render::backend::with_paint,
};
if let Some(style) = &self.tick_style {
with_paint(backend, owner, PaintRole::Axes, None, |backend| {
for tick in &self.ticks {
backend.draw_line(tick, style)?;
}
Ok(())
})?;
}
let [joint, top, right] = [
MarginalRegion::Joint,
MarginalRegion::Top,
MarginalRegion::Right,
]
.map(|region| owner.clone().marginal(region));
for group in &self.groups {
with_paint(
backend,
&joint,
PaintRole::Primary,
Some(LayerSlot::Primary),
|backend| {
with_clip(backend, self.clips()[0], |backend| {
for (points, style) in &group.point_batches {
backend.draw_scatter(points, style)?;
}
Ok(())
})
},
)?;
with_paint(
backend,
&top,
PaintRole::Primary,
Some(LayerSlot::Primary),
|backend| {
with_clip(backend, self.clips()[1], |backend| {
backend.draw_polygon(&group.top, &group.fill)
})
},
)?;
with_paint(
backend,
&right,
PaintRole::Primary,
Some(LayerSlot::Primary),
|backend| {
with_clip(backend, self.clips()[2], |backend| {
backend.draw_polygon(&group.right, &group.fill)
})
},
)?;
}
Ok(())
}
}
pub(crate) fn natural_body_preference(
chart: &PlotDescription,
registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
intrinsic: &crate::orchestrator::root::PlotIntrinsics,
operation: &crate::font::canonical::OperationContext,
theme: &crate::text::TextRequestContext<'_, '_>,
) -> Result<(f64, f64), Error> {
let hard = intrinsic_body_minimum(chart, registered, intrinsic, operation, theme)?;
let gaps = theme.marginal_gaps()?;
let ink = density_ink(registered, theme)?;
let axes = crate::orchestrator::root::coordinate_intrinsic(
intrinsic,
&crate::orchestrator::root::intrinsic_inputs(registered, theme, operation)?,
)?
.minimum(crate::orchestrator::registration::axis_tick_labels_visible(
registered, 1,
));
let central = (
(hard.0 - gaps.column - (2.0 * ink.0).max(1.0 / 1024.0)).max(axes.0),
(hard.1 - gaps.row - (2.0 * ink.1).max(1.0 / 1024.0)).max(axes.1),
);
let preference = layout::interior::preference::mark_preference(
registered.expect("prepared Marginal preference"),
crate::builder::RootFrameDomainInput::Prepared,
theme,
central,
)?;
let width = preference.body_quanta.0 as f64 / 1024.0;
let height = preference.body_quanta.1 as f64 / 1024.0;
let quarter = |value: i64| -> Result<f64, Error> {
let quanta = i64::try_from((i128::from(value) + 3) / 4)
.map_err(|_| Error::Render("Marginal quarter preference overflowed".into()))?;
Ok(quanta as f64 / 1024.0)
};
Ok((
width + quarter(preference.body_quanta.0)?.max(2.0 * ink.0) + gaps.column,
height + quarter(preference.body_quanta.1)?.max(2.0 * ink.1) + gaps.row,
))
}
pub(crate) fn natural_body_height(
chart: &PlotDescription,
registered: Option<&crate::orchestrator::registration::PlotRegistration<'_>>,
intrinsic: &crate::orchestrator::root::PlotIntrinsics,
operation: &crate::font::canonical::OperationContext,
theme: &crate::text::TextRequestContext<'_, '_>,
width: f64,
) -> Result<f64, Error> {
let gaps = theme.marginal_gaps()?;
let hard = intrinsic_body_minimum(chart, registered, intrinsic, operation, theme)?;
let ink = density_ink(registered, theme)?;
let right_hard = (2.0 * ink.0).max(1.0 / 1024.0);
let top_hard = (2.0 * ink.1).max(1.0 / 1024.0);
let axes = crate::orchestrator::root::coordinate_intrinsic(
intrinsic,
&crate::orchestrator::root::intrinsic_inputs(registered, theme, operation)?,
)?
.minimum(crate::orchestrator::registration::axis_tick_labels_visible(
registered, 1,
));
let central_hard = (
(hard.0 - gaps.column - right_hard).max(axes.0),
(hard.1 - gaps.row - top_hard).max(axes.1),
);
let preference = layout::interior::preference::mark_preference(
registered.expect("prepared Marginal preference"),
crate::builder::RootFrameDomainInput::Prepared,
theme,
central_hard,
)?;
let track = |min: f64, preferred: i64| -> Result<_, Error> {
let min = layout::kernel::ceil_spatial_quanta(min)?;
Ok(layout::kernel::TrackSpec {
min,
preferred: preferred.max(min),
max: None,
flexible: true,
})
};
let quarter = i64::try_from((i128::from(preference.body_quanta.0) + 3) / 4)
.map_err(|_| Error::Render("Marginal quarter width overflowed".into()))?;
let columns = layout::interior::tracks::assign(
&[
track(central_hard.0, preference.body_quanta.0)?,
track(right_hard, quarter)?,
],
(0.0, width),
gaps.column,
false,
&layout::fit::FitScope::root(),
)
.map_err(layout::fit::PlanError::into_error)?;
let central_width = columns[0].1 - columns[0].0;
let quarter_height = i64::try_from((i128::from(preference.body_quanta.1) + 3) / 4)
.map_err(|_| Error::Render("Marginal quarter height overflowed".into()))?;
let top = (quarter_height as f64 / 1024.0).max(top_hard);
Ok(central_hard
.1
.max(3.0 * central_width / 4.0)
.max(preference.density_side)
+ top
+ gaps.row)
}
pub(crate) fn measure(
chart: &PlotDescription,
context: &PlotMeasureContext<'_, '_>,
request: &crate::text::TextRequestContext<'_, '_>,
) -> Result<PlotRenderResult, crate::layout::fit::PlanError> {
let theme = request;
let prepared = (match context.family()? {
crate::orchestrator::registration::FamilyRef::Marginal(marks) => Some(marks),
_ => None,
})
.ok_or_else(|| Error::Render("marginal requires root-prepared semantics".into()))?;
let groups = &prepared.groups;
let registered = context.registered;
let base_ranges = registered.axes.ranges();
theme.text.prepared_font_environment()?;
let data = context.data()?;
let outer = context.assignment.local.body;
let gaps = theme.marginal_gaps()?;
let hard = intrinsic_body_minimum(
chart,
Some(context.registered),
context.intrinsic(),
context.operation,
theme,
)?;
if outer.width() < hard.0 || outer.height() < hard.1 {
return Err(context.fit_scope().failure(
crate::layout::fit::FitKind::SpecializedGeometry,
"marginal linked strips leave less than the prepared central mark and density ink minimum",
).into());
}
let ink = density_ink(Some(context.registered), theme)?;
let right_hard = (2.0 * ink.0).max(1.0 / 1024.0);
let top_hard = (2.0 * ink.1).max(1.0 / 1024.0);
let axes_hard = crate::orchestrator::root::coordinate_intrinsic(
context.intrinsic(),
&crate::orchestrator::root::intrinsic_inputs(
Some(context.registered),
theme,
context.operation,
)?,
)?
.minimum(registered.policy.axis_text.tick_labels[1]);
let central_hard = (
(hard.0 - gaps.column - right_hard).max(axes_hard.0),
(hard.1 - gaps.row - top_hard).max(axes_hard.1),
);
let preference = layout::interior::preference::mark_preference(
context.registered,
crate::builder::RootFrameDomainInput::Selected(context.assignment.local),
theme,
central_hard,
)?;
let track = |min: f64, preferred: i64| -> Result<_, Error> {
let min = layout::kernel::ceil_spatial_quanta(min)?;
Ok(layout::kernel::TrackSpec {
min,
preferred: preferred.max(min),
max: None,
flexible: true,
})
};
let quarter = |value: i64| -> Result<i64, Error> {
i64::try_from((i128::from(value) + 3) / 4)
.map_err(|_| Error::Render("Marginal quarter preference overflow".into()))
};
let columns = layout::interior::tracks::assign(
&[
track(central_hard.0, preference.body_quanta.0)?,
track(right_hard, quarter(preference.body_quanta.0)?)?,
],
(outer.x0, outer.x1),
gaps.column,
false,
context.fit_scope(),
)?;
let rows = layout::interior::tracks::assign(
&[
track(top_hard, quarter(preference.body_quanta.1)?)?,
track(central_hard.1, preference.body_quanta.1)?,
],
(outer.y0, outer.y1),
gaps.row,
true,
context.fit_scope(),
)?;
let (central_x0, central_x1) = columns[0];
let (central_y0, central_y1) = rows[1];
let (top_y0, top_y1) = rows[0];
let (right_x0, right_x1) = columns[1];
let (x_low, x_high) = context.axis_range(layout::AxisSide::Bottom)?;
let (y_low, y_high) = context.axis_range(layout::AxisSide::Left)?;
let ranges = [(x_low, x_high), (y_low, y_high)];
let curves = &prepared.curves;
let axes = registered
.axes
.coordinate()
.ok_or_else(|| Error::Render("Marginal axes missing".into()))?;
let labels = [
axes.copy_label(registered, 0)?,
axes.copy_label(registered, 1)?,
];
let specs = [chart.x_axis_spec(), chart.y_axis_spec()];
let numeric = registered.axis_numeric_binding(context.operation)?;
let central_ranges = [
layout::continuous_auto_range((x_low, x_high), Some((x_low, x_high)))?,
layout::continuous_auto_range((y_low, y_high), Some((y_low, y_high)))?,
];
let projection = layout::Projection::new(
central_ranges[0],
central_ranges[1],
(central_x0, central_x1, central_y0, central_y1),
);
let assigned = context
.axis_pair(crate::orchestrator::assignment::AxisPairScope::MarginalCentral)?
.axes;
let ticks = [layout::AxisSide::Bottom, layout::AxisSide::Left].map(|side| {
let index = usize::from(side == layout::AxisSide::Left);
assigned[index].layout_ticks(
Vec::new(),
&projection,
side,
theme,
context.fit_scope(),
numeric,
)
});
let [x_ticks, y_ticks] = ticks;
let (x_ticks, y_ticks) = match (x_ticks, y_ticks) {
(Err(error @ PlanError::Fatal(_)), _)
| (_, Err(error @ PlanError::Fatal(_)))
| (Err(error), Ok(_))
| (Ok(_), Err(error)) => return Err(error),
(Err(PlanError::Fit(x)), Err(PlanError::Fit(y))) => {
return Err(PlanError::Fit(if x.reason <= y.reason { x } else { y }));
}
(Ok(x), Ok(y)) => (x, y),
};
let make_axis = |spec: &AuthoredAxisSpec, label, ticks: layout::NumericTickPlan| layout::Axis {
label,
ticks: ticks.ticks,
tick_labels_visible: true,
category_labels: spec.category_labels.clone(),
explicit_ticks: spec.exact_ticks.is_some(),
assigned_tick_width: None,
assigned_cells: None,
source: ticks.source,
numeric: ticks.numeric,
};
let [x_label, y_label] = labels;
let x_axis = make_axis(specs[0], x_label, x_ticks);
let y_axis = make_axis(specs[1], y_label, y_ticks);
let layout = layout::Layout {
projection,
x_axis,
y_axis,
};
let proj = &layout.projection;
let tick_len = theme
.axes
.ticks
.as_ref()
.map_or(0.0, |appearance| f64::from(appearance.length));
let tick_style = theme
.axes
.ticks
.as_ref()
.map(|appearance| appearance.stroke.backend_style());
let mut ticks = Vec::new();
crate::data::source::reserve_source(
&mut ticks,
layout.x_axis.ticks.len() + layout.y_axis.ticks.len(),
)?;
if tick_style.is_some() {
for tick in &layout.x_axis.ticks {
let (x_px, _) = proj.project(tick.position, y_low);
if x_px >= central_x0 && x_px <= central_x1 {
ticks.push([
Point2D::new(x_px, top_y0),
Point2D::new(x_px, top_y0 - tick_len),
]);
}
}
for tick in &layout.y_axis.ticks {
let (_, y_px) = proj.project(x_low, tick.position);
if y_px >= central_y0 && y_px <= central_y1 {
ticks.push([
Point2D::new(right_x0, y_px),
Point2D::new(right_x0 - tick_len, y_px),
]);
}
}
}
let x_densities = &curves.x_densities;
let y_densities = &curves.y_densities;
let y_grid = &curves.y_grid;
let x_dens_max = display_maximum(x_densities);
let y_dens_max = display_maximum(y_densities);
if !x_dens_max.is_finite() || !y_dens_max.is_finite() || x_dens_max <= 0.0 || y_dens_max <= 0.0
{
return Err(context
.fit_scope()
.failure(
crate::layout::fit::FitKind::SpecializedGeometry,
"marginal KDE has no positive representable density in a required linked strip",
)
.into());
}
let central_panel = PixelRect::new(central_x0, central_x1, central_y0, central_y1);
let top_panel = PixelRect::new(central_x0, central_x1, top_y0, top_y1);
let right_panel = PixelRect::new(right_x0, right_x1, central_y0, central_y1);
let panels = [
measure_linked_panel(
central_panel,
ranges,
layout::AddressRole::MarginalCentral,
context,
)?,
measure_linked_panel(
top_panel,
[
ranges[0],
context
.axis_pair(crate::orchestrator::assignment::AxisPairScope::MarginalTop)?
.axes[1]
.domain
.extent
.pair(),
],
layout::AddressRole::MarginalTop,
context,
)?,
measure_linked_panel(
right_panel,
[
context
.axis_pair(crate::orchestrator::assignment::AxisPairScope::MarginalRight)?
.axes[0]
.domain
.extent
.pair(),
ranges[1],
],
layout::AddressRole::MarginalRight,
context,
)?,
];
let mut selected = Vec::new();
crate::data::source::reserve_source(&mut selected, groups.len())?;
let (colors, accents) = prepared.resolved_colors(
registered
.categorical
.as_ref()
.expect("prepared color binding"),
theme,
data.source_resources(),
)?;
let mut source = [(f64::INFINITY, f64::NEG_INFINITY); 2];
let mut point_bounds: Option<crate::render::geometry::GeometryBox> = None;
for (gi, group) in groups.iter().enumerate() {
let color = PreparedMarginal::group_color(group, &colors, &accents)?;
let point_style = chart.point_style(
theme,
color,
theme.marks.get_points().get_radii().get_marginal(),
);
require_aligned_points(group.x.len(), group.alphas.len())?;
if let Some(ink) = point_ink(
&point_style,
group
.x
.iter()
.zip(&group.y)
.zip(&group.alphas)
.map(|((&x, &y), &alpha)| (x, y, alpha)),
)? {
point_bounds =
Some(point_bounds.map_or(ink.bounds, |previous| previous.union(ink.bounds)));
for (source, range) in source.iter_mut().zip(ink.ranges) {
source.0 = source.0.min(range.0);
source.1 = source.1.max(range.1);
}
}
let mut point_batches = Vec::new();
for ((&x, &y), &alpha) in group.x.iter().zip(&group.y).zip(&group.alphas) {
let (x, y) = panels[0].projection.project(x, y);
push_point(
&mut point_batches,
Point2D::new(x, y),
alpha.point(point_style.clone()),
)?;
}
let mut top_poly = Vec::new();
let mut right_poly = Vec::new();
crate::data::source::reserve_source(&mut top_poly, curves.x_grid.len() + 2)?;
crate::data::source::reserve_source(&mut right_poly, curves.y_grid.len() + 2)?;
let (top_start, _) = panels[1].projection.project(curves.x_grid[0], 0.0);
let (_, right_start) = panels[2].projection.project(0.0, curves.y_grid[0]);
let baseline_y = top_y0 + ink.1 + 2.0 / 1024.0;
let baseline_x = right_x0 + ink.0 + 2.0 / 1024.0;
let top_span = top_panel.height() - 2.0 * ink.1 - 4.0 / 1024.0;
let right_span = right_panel.width() - 2.0 * ink.0 - 4.0 / 1024.0;
if top_span <= 0.0 || right_span <= 0.0 {
return Err(context
.fit_scope()
.failure(
layout::fit::FitKind::SpecializedGeometry,
"Marginal density outline reserve leaves no representable strip",
)
.into());
}
top_poly.push(Point2D::new(top_start, baseline_y));
right_poly.push(Point2D::new(baseline_x, right_start));
let x_display = crate::stats::distribution::closed_density(&x_densities[gi]);
let y_display = crate::stats::distribution::closed_density(&y_densities[gi]);
for (&coordinate, dx) in curves.x_grid.iter().zip(x_display) {
let (x, _) = panels[1].projection.project(coordinate, 0.0);
let y = baseline_y
+ dx / x_dens_max
* theme
.marks
.get_extents()
.get_marginal_density_fraction()
.as_f64()
* top_span;
top_poly.push(Point2D::new(x, y));
}
for (&coordinate, dy) in y_grid.iter().zip(y_display) {
let (_, y) = panels[2].projection.project(0.0, coordinate);
let x = baseline_x
+ dy / y_dens_max
* theme
.marks
.get_extents()
.get_marginal_density_fraction()
.as_f64()
* right_span;
right_poly.push(Point2D::new(x, y));
}
let (top_end, _) = panels[1]
.projection
.project(*curves.x_grid.last().expect("evaluated grid"), 0.0);
let (_, right_end) = panels[2]
.projection
.project(0.0, *curves.y_grid.last().expect("evaluated grid"));
top_poly.push(Point2D::new(top_end, baseline_y));
right_poly.push(Point2D::new(baseline_x, right_end));
let fill = fill_style(
group.fill_alpha,
theme
.marks
.get_fills()
.get_densities()
.get_marginal_density()
.backend_style(color),
);
selected.push(MarginalGroupPayload {
point_batches,
source_rows: crate::data::source::collect_source(
group.alphas.iter().map(|alpha| Ok(alpha.source_row)),
)?,
top: top_poly,
right: right_poly,
fill,
});
}
let raw_windows = registered.raw_windows();
let mut domain_expansions = if let Some(ink) = point_bounds {
crate::layout::interior::automatic_mark_ink_expansions(
source,
proj,
ink,
[raw_windows[0].is_none(), raw_windows[1].is_none()],
context.fit_scope(),
)?
} else {
[None; 2]
};
for (side, panel) in [(0, &panels[1]), (1, &panels[2])] {
let mut full = crate::render::geometry::GeometrySnapshot::new();
for group in &selected {
full.polygon(
if side == 0 { &group.top } else { &group.right },
&group.fill,
None,
)?;
}
if let Some(bounds) = full
.bounds()
.iter()
.copied()
.reduce(crate::render::geometry::GeometryBox::union)
{
let assigned = panel.projection.panel_box();
if (side == 0 && (bounds.bottom < assigned.y0 || bounds.top > assigned.y1))
|| (side == 1 && (bounds.left < assigned.x0 || bounds.right > assigned.x1))
{
return Err(layout::fit::FitScope::new(&panel.address, 0)
.failure(
layout::fit::FitKind::SpecializedGeometry,
"Marginal density outline exceeds its assigned amplitude reserve",
)
.into());
}
let requests = crate::layout::interior::automatic_absolute_ink_expansions(
if side == 0 {
[base_ranges[0], (0.0, 1.0)]
} else {
[(0.0, 1.0), base_ranges[1]]
},
&panel.projection,
bounds,
[
side == 0 && raw_windows[0].is_none(),
side == 1 && raw_windows[1].is_none(),
],
context.fit_scope(),
)?;
domain_expansions =
crate::layout::interior::merge_mark_domain_expansions(domain_expansions, requests);
}
}
let payload = MarginalPayload {
panels,
ticks,
tick_style,
groups: selected,
domain_expansions,
};
let mut geometry = crate::render::geometry::GeometrySnapshot::new();
if let Some(style) = &payload.tick_style {
for tick in &payload.ticks {
geometry.line(tick, style, None)?;
}
}
for group in &payload.groups {
for (points, style) in &group.point_batches {
geometry.scatter(points, style, central_panel)?;
}
geometry.polygon(&group.top, &group.fill, Some(top_panel))?;
geometry.polygon(&group.right, &group.fill, Some(right_panel))?;
}
let mut result = PlotRenderResult::new(
layout,
crate::orchestrator::registration::guide_descriptor(Some(context.registered))?,
);
result.axes = Some(result.layout.measure_axes_with_inputs(
theme,
context.fit_scope(),
std::array::from_fn(|side| {
let mut input = assigned[side].semantic_inputs();
input
.text_layout
.clone_from(&theme.text_layouts.ticks[side]);
input
}),
|| layout::CoordinateLayoutInputs::new(theme),
)?);
result.marks = Some(crate::data::source::source_arc(
crate::layout::interior::SelectedMarkPlan {
payload: crate::layout::interior::MarkPayload::Marginal(payload),
geometry,
},
)?);
Ok(result)
}
pub(crate) fn prepare(
chart: &crate::builder::PlotDescription,
data: crate::data::PlotData<'_, '_>,
plot_id: &PlotOccurrenceId,
) -> Result<(PreparedMarginal, PreparedAxesOwner, Vec<String>), Error> {
let (mut groups, hues) = build_groups(chart, data, None)?;
let fill_alpha = chart.prepare_collective_alpha(
AlphaTarget::Fill,
AlphaUnitKind::Series,
true,
data.facet_selector()?,
)?;
for group in &mut groups {
group.fill_alpha = fill_alpha.collective(chart, &group.identity)?;
}
chart.validate_categorical_colors(hues.iter().map(String::as_str))?;
let ranges = ranges_from_groups(chart, &groups)?;
let axis_source = |slot, range, range_policy, base_provenance, label| PreparedAxisSource {
witness: AxisSourceWitness {
plot_id: plot_id.clone(),
slot,
space: AxisSpace::Continuous(crate::coordinates::AxisScale::Linear),
},
range_policy,
base_seed: Some(range),
base_provenance,
categories: None,
projected_exact_positions: None,
label,
};
let central = std::array::from_fn(|side| {
axis_source(
AxisSlot::MarginalCentral(if side == 0 {
layout::AxisSide::Bottom
} else {
layout::AxisSide::Left
}),
DisplayExtent {
lower: ranges[side].0,
upper: ranges[side].1,
},
layout::RangePolicy::MarginalSupport,
if (if side == 0 {
chart.x_axis_spec()
} else {
chart.y_axis_spec()
})
.window
.is_some()
{
layout::RangeProvenance::Configured
} else {
layout::RangeProvenance::Automatic
},
std::sync::OnceLock::new(),
)
});
let strip_density = [MarginalStrip::Top, MarginalStrip::Right].map(|strip| {
axis_source(
AxisSlot::MarginalStripDensity(strip),
DisplayExtent {
lower: 0.0,
upper: 1.0,
},
layout::RangePolicy::ContinuousMargin,
layout::RangeProvenance::Automatic,
std::sync::OnceLock::from(crate::Text::UNSET),
)
});
Ok((
PreparedMarginal {
groups,
curves: MarginalCurves::default(),
},
PreparedAxesOwner::Marginal {
central,
strip_density,
},
hues,
))
}
pub(crate) fn finish(
mut prepared: PreparedMarginal,
axes: &mut PreparedAxesOwner,
x_limits: Option<(f64, f64)>,
) -> Result<PreparedMarginal, Error> {
if let Some(limits) = x_limits {
axes.sources_mut()[0].base_seed = Some(DisplayExtent {
lower: limits.0,
upper: limits.1,
});
}
prepared.curves = render_curves(&prepared.groups, axes.ranges())?;
Ok(prepared)
}
fn render_curves(groups: &[HueGroup], ranges: [(f64, f64); 2]) -> Result<MarginalCurves, Error> {
let (x_grid, x_densities) = region_curves(groups, ranges[0], 0)?;
let (y_grid, y_densities) = region_curves(groups, ranges[1], 1)?;
Ok(MarginalCurves {
x_grid,
y_grid,
x_densities,
y_densities,
})
}
fn region_curves(
groups: &[HueGroup],
range: (f64, f64),
side: usize,
) -> Result<(Vec<f64>, Vec<Vec<f64>>), Error> {
let grid = representable_grid(range, 80)?;
let channel = if side == 0 { "x" } else { "y" };
let densities = crate::data::source::collect_source(groups.iter().map(|group| {
let (samples, bandwidth) = group.distribution(side);
gaussian_kde(samples, &grid, bandwidth).map_err(|error| {
error.with_prefix(&format!(
"marginal: {channel} distribution for {}",
group.identity.description(group.collapsed)
))
})
}))?;
if display_maximum(&densities) <= 0.0 {
return Err(Error::Data(
format!("marginal: {channel} strip has no positive representable density").into(),
));
}
Ok((grid, densities))
}
fn ranges_from_groups(
chart: &PlotDescription,
groups: &[HueGroup],
) -> Result<[(f64, f64); 2], Error> {
Ok([
range_from_groups(chart, groups, 0)?,
range_from_groups(chart, groups, 1)?,
])
}
fn range_from_groups(
chart: &PlotDescription,
groups: &[HueGroup],
side: usize,
) -> Result<(f64, f64), Error> {
let spec = if side == 0 {
chart.x_axis_spec()
} else {
chart.y_axis_spec()
};
let range = crate::data::min_max(
groups
.iter()
.flat_map(|group| group.distribution(side).0.iter().copied()),
"marginal",
)?;
let range = marginal_display_range(groups, side, range, spec)?;
if !range.0.is_finite() || !range.1.is_finite() || range.0 >= range.1 {
let channel = if side == 0 { "x" } else { "y" };
return Err(Error::Data(
format!("marginal: {channel} support/grid is not representable at this numeric scale")
.into(),
));
}
Ok(range)
}
fn build_groups(
chart: &crate::builder::PlotDescription,
data: crate::data::PlotData<'_, '_>,
selected_side: Option<usize>,
) -> Result<(Vec<HueGroup>, Vec<String>), Error> {
let alpha = chart.prepare_alpha(AlphaTarget::Point, AlphaUnitKind::Observation, &[])?;
let x_col = chart
.x_col()
.ok_or_else(|| Error::Data("marginal: x column not set".into()))?;
let y_col = chart
.y_col()
.ok_or_else(|| Error::Data("marginal: y column not set".into()))?;
let rows = crate::data::aligned_finite_rows(data, x_col, y_col, "marginal")?;
data.validate_row_source()?;
let retained_rows =
crate::data::source::collect_source(rows.iter().map(|(row, _, _)| Ok(*row)))?;
let channels = crate::data::observed_collectives(
data,
chart.group_col(),
chart.hue_col(),
Some(&retained_rows),
"marginal",
)?;
let hue_levels = crate::data::source::collect_source(
channels
.hue_levels
.iter()
.map(|level| crate::data::source::copy_source_string(level)),
)?;
let mut groups = Vec::new();
crate::data::source::reserve_source(&mut groups, channels.identities.len())?;
for identity in &channels.identities {
let count = channels.rows.iter().filter(|row| *row == identity).count();
let selected = rows
.iter()
.zip(&channels.rows)
.filter(|(_, row_identity)| *row_identity == identity);
let mut x = Vec::new();
let mut y = Vec::new();
let mut alphas = Vec::new();
crate::data::source::reserve_source(&mut x, count)?;
crate::data::source::reserve_source(&mut y, count)?;
crate::data::source::reserve_source(&mut alphas, count)?;
for ((row, x_value, y_value), _) in selected {
x.push(*x_value);
y.push(*y_value);
alphas.push(ObservationAlpha::resolve(data, &alpha, *row)?);
}
if x.is_empty() {
continue;
}
let mut bandwidths = [None; 2];
for (side, (samples, channel)) in [(&x, "x"), (&y, "y")].into_iter().enumerate() {
if selected_side.is_none_or(|selected| selected == side) {
bandwidths[side] = Some(strict_scott_bandwidth(samples).map_err(|error| {
error.with_prefix(&format!(
"marginal: {channel} distribution for {}",
identity.description(channels.collapsed)
))
})?);
}
}
if let Some(hue) = &identity.hue {
if !hue_levels.contains(hue) {
return Err(Error::Data(
format!("marginal: hue {hue:?} is absent from the prepared domain").into(),
));
}
}
groups.push(HueGroup {
identity: crate::data::source::copy_source_pair(identity)?,
collapsed: channels.collapsed,
x,
y,
alphas,
fill_alpha: None,
bandwidths,
});
}
Ok((groups, hue_levels))
}
fn marginal_display_range(
groups: &[HueGroup],
side: usize,
data_range: (f64, f64),
spec: &AuthoredAxisSpec,
) -> Result<(f64, f64), Error> {
let data_display_range = marginal_data_display_range(data_range, spec);
if spec.window.is_some() {
return Ok(data_display_range);
}
let Some(visible_kde_range) = kde_visible_support_range(groups, side)? else {
return Ok(data_display_range);
};
Ok((
data_display_range.0.min(visible_kde_range.0),
data_display_range.1.max(visible_kde_range.1),
))
}
fn marginal_data_display_range(data_range: (f64, f64), spec: &AuthoredAxisSpec) -> (f64, f64) {
if let Some(limits) = spec.window.map(crate::layout::RawWindow::pair) {
return limits;
}
let lo = data_range.0.min(data_range.1);
let hi = data_range.0.max(data_range.1);
if !(lo.is_finite() && hi.is_finite()) {
return data_range;
}
if hi <= lo {
return (lo - 1.0, hi + 1.0);
}
let span = hi - lo;
let pad = if span.is_finite() {
span * MARGINAL_DATA_MARGIN_FRACTION
} else {
hi * MARGINAL_DATA_MARGIN_FRACTION - lo * MARGINAL_DATA_MARGIN_FRACTION
};
(lo - pad, hi + pad)
}
fn kde_visible_support_range(
groups: &[HueGroup],
side: usize,
) -> Result<Option<(f64, f64)>, Error> {
let mut support_low = f64::INFINITY;
let mut support_high = f64::NEG_INFINITY;
for group in groups {
let (samples, bandwidth) = group.distribution(side);
let (low, high) = crate::data::min_max(samples.iter().copied(), "marginal")?;
let lower = low - MARGINAL_KDE_CUT * bandwidth;
let upper = high + MARGINAL_KDE_CUT * bandwidth;
if !lower.is_finite() || !upper.is_finite() || lower >= upper {
let channel = if side == 0 { "x" } else { "y" };
return Err(Error::Data(format!(
"marginal: {channel} distribution for {}: support/grid is not representable at this numeric scale",
group.identity.description(group.collapsed)
).into()));
}
support_low = support_low.min(lower);
support_high = support_high.max(upper);
}
let grid = representable_grid((support_low, support_high), MARGINAL_KDE_GRID_POINTS)?;
let mut low = f64::INFINITY;
let mut high = f64::NEG_INFINITY;
for group in groups {
let (samples, bandwidth) = group.distribution(side);
let densities = gaussian_kde(samples, &grid, bandwidth)?;
let max_density = densities.iter().fold(0.0_f64, |acc, value| acc.max(*value));
if max_density <= 0.0 {
continue;
}
let threshold = max_density * MARGINAL_KDE_VISIBLE_FRACTION;
for (&x, &density) in grid.iter().zip(densities.iter()) {
if density >= threshold {
low = low.min(x);
high = high.max(x);
}
}
}
Ok((low.is_finite() && high.is_finite() && low < high).then_some((low, high)))
}
#[cfg(test)]
mod tests;