use crate::alpha::{
marks::{line_style, point_ink, push_point, ObservationAlpha},
AlphaTarget, AlphaUnitKind, ResolvedAlpha,
};
use crate::builder::PlotDescription;
use crate::data::{ObservedCollectives, PlotData};
use crate::decorations::legend::source::{LineRole, PointRole};
use crate::decorations::legend::GuideSourceKey;
use crate::layout::interior::MeasuredCoordinateMarks;
use crate::render::backend::{Backend, LineStyle, Point2D, PointStyle};
use crate::spec::PlotMeasureContext;
use crate::style::{LinePattern, PointShape};
use crate::theme::CategoryColors;
use crate::Error;
#[derive(Debug, Clone, Copy, Default)]
struct TraceStyle {
point_shape: PointShape,
line_pattern: LinePattern,
}
#[derive(Debug)]
struct Cell {
condition: usize,
estimate: f64,
lower: f64,
upper: f64,
alpha: ObservationAlpha,
}
#[derive(Debug)]
struct Trace {
identity: crate::data::CollectivePair,
style: TraceStyle,
cells: Vec<Cell>,
line_alpha: Option<ResolvedAlpha>,
}
mod result;
#[derive(Debug)]
pub(crate) struct PreparedInteraction {
pub(crate) range: (f64, f64),
traces: Vec<Trace>,
}
pub(crate) fn intrinsic_body_minimum(
chart: &PlotDescription,
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::Interaction(marks) => Some(marks),
_ => None,
})
.ok_or_else(|| {
Error::Render("Interaction intrinsic requires root-prepared traces".into())
})?;
let conditions = ®istered
.expect("prepared Interaction occurrence")
.axes
.categories(0)
.expect("prepared Interaction categories")
.raw;
if conditions.is_empty() || prepared.traces.is_empty() {
return Err(Error::Render(
"Interaction has no categorical slots or traces".into(),
));
}
let mut pitch = 1.0_f64 / 1024.0;
let mut numeric = 0.0_f64;
for trace in &prepared.traces {
let interval = crate::render::geometry::line_ink_width(&line_style(
trace.line_alpha,
theme
.marks
.get_data_lines()
.get_interaction_interval()
.backend_style((0, 0, 0)),
))?;
let marker = if chart.markers_visible() {
let point = chart
.point_style(
theme,
(0, 0, 0),
theme.marks.get_points().get_radii().get_interaction(),
)
.with_shape(trace.style.point_shape);
point_ink(
&point,
trace
.cells
.iter()
.map(|cell| (0.0, cell.estimate, cell.alpha)),
)?
.map(|ink| ink.bounds)
} else {
None
};
let connector = if chart.interaction_connectors_visible() && trace.cells.len() > 1 {
crate::render::geometry::line_ink_width(&line_style(
trace.line_alpha,
theme
.marks
.get_data_lines()
.get_interaction_connector()
.backend_style((0, 0, 0)),
))?
} else {
0.0
};
let stroke = interval.max(connector);
numeric = numeric.max(stroke);
pitch = pitch.max(stroke);
for cell in &trace.cells {
if cell.condition >= conditions.len() {
return Err(Error::Render(
"Interaction occupied condition exceeds prepared slots".into(),
));
}
if let Some(ink) = marker {
pitch = pitch.max(2.0 * (-ink.left).max(ink.right));
numeric = numeric.max(ink.top - ink.bottom);
}
}
}
let count = u32::try_from(conditions.len())
.map_err(|_| Error::Render("Interaction condition count exceeds spatial range".into()))?;
let categorical = pitch * f64::from(count);
if !categorical.is_finite() {
return Err(Error::Render(
"Interaction categorical hard span overflowed".into(),
));
}
Ok((
categorical,
if registered.expect("prepared occurrence").raw_windows()[1].is_none() {
numeric
} else {
0.0
},
))
}
impl PreparedInteraction {
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};
for trace in &self.traces {
let unit = AlphaUnit::series(chart, Some(&trace.identity))?;
let point = chart
.point_style(
theme,
(0, 0, 0),
theme.marks.get_points().get_radii().get_interaction(),
)
.with_shape(trace.style.point_shape);
if chart.markers_visible() {
for cell in &trace.cells {
guide.point(
AlphaGlyphRole::Primary,
cell.alpha,
point.clone(),
chart.interaction_styles_spec().is_some(),
)?;
}
}
guide.line(
AlphaGlyphRole::Summary,
AlphaUnitKind::Series,
unit.clone(),
trace.line_alpha,
theme
.marks
.get_data_lines()
.get_interaction_interval()
.backend_style((0, 0, 0)),
false,
)?;
if chart.interaction_connectors_visible() && trace.cells.len() > 1 {
let mut line = theme
.marks
.get_data_lines()
.get_interaction_connector()
.backend_style((0, 0, 0));
line.pattern = trace.style.line_pattern;
guide.line(
AlphaGlyphRole::Line,
AlphaUnitKind::Series,
unit,
trace.line_alpha,
line,
chart.interaction_styles_spec().is_some(),
)?;
}
}
Ok(())
}
pub(crate) fn color_keys(&self) -> impl Iterator<Item = &str> {
let has_hue = self.traces.iter().any(|trace| trace.identity.hue.is_some());
self.traces.iter().filter_map(move |trace| {
if has_hue {
trace.identity.hue.as_deref()
} else {
trace.identity.group.as_deref()
}
})
}
fn resolved_colors(
&self,
binding: &crate::orchestrator::registration::CategoricalBinding,
theme: &crate::theme::ResolvedTheme,
operation: &crate::font::canonical::OperationContext,
) -> Result<CategoryColors, Error> {
let keys = if let Some(levels) = binding.parent.as_deref() {
crate::data::source::collect_source(
levels.values().map(crate::data::source::copy_source_string),
)?
} else {
let mut observed = Vec::new();
crate::data::source::reserve_source(&mut observed, self.traces.len())?;
for raw in self.color_keys() {
observed.push(crate::data::source::copy_source_string(raw)?);
}
crate::data::source::source_levels(&observed)?
};
binding.resolve(keys.iter().map(String::as_str), theme, operation)
}
pub(crate) fn checked_primary_mark_count(&self) -> Result<u128, Error> {
self.traces.iter().try_fold(0_u128, |count, trace| {
count
.checked_add(trace.cells.len() as u128)
.ok_or_else(|| Error::Render("Interaction occupied mark count overflowed".into()))
})
}
pub(crate) fn guide_entries(
&self,
chart: &crate::builder::PlotDescription,
theme: &crate::theme::ResolvedTheme,
operation: &crate::font::canonical::OperationContext,
binding: &crate::orchestrator::registration::CategoricalBinding,
) -> Result<Vec<GuideSourceKey>, Error> {
let colors = self.resolved_colors(binding, theme, operation)?;
self.guide_entries_with_colors(chart, theme, &colors)
}
fn guide_entries_with_colors(
&self,
chart: &crate::builder::PlotDescription,
theme: &crate::theme::ResolvedTheme,
colors: &CategoryColors,
) -> Result<Vec<GuideSourceKey>, Error> {
let mut entries = Vec::new();
crate::data::source::reserve_source(&mut entries, self.traces.len())?;
for trace in &self.traces {
if trace.identity.hue.is_none() && chart.interaction_styles_spec().is_none() {
continue;
}
let key = trace
.identity
.hue
.as_deref()
.or(trace.identity.group.as_deref())
.ok_or_else(|| Error::Render("interaction trace has no color identity".into()))?;
let color = colors.color(key)?;
let identity = chart.collective_legend_identity(&trace.identity)?;
let point = chart
.point_style(
theme,
color,
theme.marks.get_points().get_radii().get_interaction(),
)
.with_shape(trace.style.point_shape);
let mut line = theme
.marks
.get_data_lines()
.get_interaction_connector()
.backend_style(color);
line.pattern = trace.style.line_pattern;
let mapped_styles = chart.interaction_styles_spec().is_some();
let mut key = GuideSourceKey::collective(identity, chart, mapped_styles)?;
if chart.markers_visible() {
key = key.with_point(point, PointRole::Primary);
}
if chart.interaction_connectors_visible() {
key = key.with_line(line, LineRole::InteractionConnector);
}
if mapped_styles {
key = key.with_interaction_group_style()?;
}
entries.push(key);
}
Ok(entries)
}
}
#[expect(
clippy::too_many_lines,
reason = "one admitted semantic preparation boundary"
)]
pub(crate) fn prepare(
chart: &crate::builder::PlotDescription,
data: PlotData<'_, '_>,
parent: Option<&ObservedCollectives>,
collectives: Option<&[crate::data::CollectivePair]>,
) -> Result<(PreparedInteraction, Vec<String>), Error> {
let _scientific = crate::operation::scientific_preparation();
data.validate_row_source()?;
let alpha = chart.prepare_alpha(AlphaTarget::Point, AlphaUnitKind::Observation, &[])?;
let x_col = chart
.x_col()
.ok_or_else(|| Error::Data("interaction: x factor column not set".into()))?;
let estimate_col = chart
.y_col()
.ok_or_else(|| Error::Data("interaction: estimate column not set".into()))?;
chart
.group_col()
.ok_or_else(|| Error::Data("interaction: graphical group column not set".into()))?;
let (lo, hi) = chart.interval_bound_cols().ok_or_else(|| {
Error::Data("interaction: complete precomputed interval columns are required".into())
})?;
let x = crate::data::strict_strings(data, x_col, "interaction")?;
let channels = crate::data::observed_collectives(
data,
chart.group_col(),
chart.hue_col(),
None,
"interaction",
)?;
let estimate = crate::data::strict_finite_f64(data, estimate_col, "interaction")?;
let lower = crate::data::strict_finite_f64(data, lo, "interaction")?;
let upper = crate::data::strict_finite_f64(data, hi, "interaction")?;
if x.is_empty()
|| [
channels.rows.len(),
estimate.len(),
lower.len(),
upper.len(),
]
.iter()
.any(|length| *length != x.len())
{
return Err(Error::Data(
"interaction: all channels must have equal non-zero lengths".into(),
));
}
let conditions = crate::data::source::source_levels(&x)?;
let domain = parent.unwrap_or(&channels);
let groups = &domain.group_levels;
let hues = &domain.hue_levels;
let identities = collectives.unwrap_or(&domain.identities);
let styles = resolve_trace_styles(chart, groups)?;
let line_alpha = chart.prepare_collective_alpha(
AlphaTarget::Line,
AlphaUnitKind::Series,
true,
data.facet_selector()?,
)?;
for row in 0..x.len() {
if lower[row] > estimate[row] || estimate[row] > upper[row] {
return Err(Error::Data(
format!(
"interaction: source row {} must satisfy lower <= estimate <= upper",
data.source_row(row)
)
.into(),
));
}
if (0..row).any(|prior| x[prior] == x[row] && channels.rows[prior] == channels.rows[row]) {
return Err(Error::Data(format!("interaction: duplicate (condition, group, hue) cell ({:?}, {:?}, {:?}) at source row {}", x[row], channels.rows[row].group, channels.rows[row].hue, data.source_row(row)).into()));
}
}
let mut traces = Vec::new();
crate::data::source::reserve_source(&mut traces, identities.len())?;
for identity in identities {
if !channels.rows.contains(identity) {
continue;
}
let group = identity.group.as_deref().ok_or_else(|| {
Error::Data("interaction: graphical group channel did not resolve".into())
})?;
let index = groups
.iter()
.position(|level| level == group)
.ok_or_else(|| {
Error::Data(
format!(
"interaction: graphical group {group:?} is absent from the resolved order"
)
.into(),
)
})?;
if let Some(hue) = &identity.hue {
if !hues.contains(hue) {
return Err(Error::Data(
format!("interaction: hue {hue:?} is absent from the resolved order").into(),
));
}
}
let mut cells = Vec::new();
let cell_count = channels.rows.iter().filter(|row| *row == identity).count();
crate::data::source::reserve_source(&mut cells, cell_count)?;
for (condition, level) in conditions.iter().enumerate() {
if let Some(row) =
(0..x.len()).find(|row| &x[*row] == level && &channels.rows[*row] == identity)
{
cells.push(Cell {
condition,
estimate: estimate[row],
lower: lower[row],
upper: upper[row],
alpha: ObservationAlpha::resolve(data, &alpha, row)?,
});
}
}
traces.push(Trace {
identity: crate::data::source::copy_source_pair(identity)?,
style: styles
.as_ref()
.map_or_else(TraceStyle::default, |styles| styles[index]),
cells,
line_alpha: line_alpha.collective(chart, identity)?,
});
}
chart.validate_categorical_colors(traces.iter().filter_map(|trace| {
trace
.identity
.hue
.as_deref()
.or(trace.identity.group.as_deref())
}))?;
Ok((
PreparedInteraction {
range: crate::data::min_max(lower.into_iter().chain(upper), "interaction")?,
traces,
},
conditions,
))
}
#[derive(Debug)]
pub(crate) struct InteractionPayload {
clip: crate::layout::PixelRect,
traces: Vec<TracePayload>,
pub(crate) domain_expansions: [Option<crate::layout::interior::DomainExpansion>; 2],
}
#[derive(Debug)]
struct TracePayload {
intervals: Vec<[Point2D; 2]>,
points: Vec<Point2D>,
interval: LineStyle,
connector: Option<LineStyle>,
markers: Vec<(Vec<Point2D>, PointStyle)>,
}
impl InteractionPayload {
fn measure_ink(
&mut self,
marks: &PreparedInteraction,
projection: &crate::layout::Projection,
context: &PlotMeasureContext<'_, '_>,
) -> Result<(), crate::layout::fit::PlanError> {
let mut full = crate::render::geometry::GeometrySnapshot::new();
for trace in &self.traces {
for interval in &trace.intervals {
full.line(interval, &trace.interval, None)?;
}
if let Some(style) = &trace.connector {
full.line(&trace.points, style, None)?;
}
for (points, style) in &trace.markers {
full.scatter_with_clip(points, style, None)?;
}
}
if let Some(bounds) = full
.bounds()
.iter()
.copied()
.reduce(crate::render::geometry::GeometryBox::union)
{
if bounds.left < self.clip.x0 || bounds.right > self.clip.x1 {
return Err(context
.fit_scope()
.failure(
crate::layout::fit::FitKind::SpecializedGeometry,
"Interaction painted ink exceeds its assigned condition panel",
)
.into());
}
if context.registered.raw_windows()[1].is_none() {
let count = u32::try_from(
context
.registered
.axes
.categories(0)
.expect("prepared Interaction categories")
.raw
.len(),
)
.map_err(|_| {
Error::Render("Interaction condition count exceeds spatial range".into())
})?;
self.domain_expansions =
crate::layout::interior::automatic_absolute_ink_expansions(
[(0.0, f64::from(count)), marks.range],
projection,
bounds,
[false, true],
context.fit_scope(),
)?;
}
}
Ok(())
}
pub(crate) fn draw(&self, backend: &mut dyn Backend) -> Result<(), Error> {
crate::render::backend::with_clip(backend, self.clip, |backend| {
for trace in &self.traces {
for interval in &trace.intervals {
backend.draw_line(interval, &trace.interval)?;
}
if let Some(style) = &trace.connector {
backend.draw_line(&trace.points, style)?;
}
for (points, style) in &trace.markers {
backend.draw_scatter(points, style)?;
}
}
Ok(())
})
}
}
#[expect(
clippy::cast_precision_loss,
clippy::too_many_lines,
reason = "selected bounded categories and ordered interval, connector and point paints share one frozen trace"
)]
pub(crate) fn measure_marks(
chart: &PlotDescription,
context: &PlotMeasureContext<'_, '_>,
request: &crate::text::TextRequestContext<'_, '_>,
layout: &crate::layout::Layout,
) -> Result<MeasuredCoordinateMarks, crate::layout::fit::PlanError> {
let marks = (match context.family()? {
crate::orchestrator::registration::FamilyRef::Interaction(marks) => Some(marks),
_ => None,
})
.ok_or_else(|| {
Error::Render("interaction measurement requires root-prepared semantics".into())
})?;
request.text.prepared_font_environment()?;
let data = context.data()?;
let mut payload = InteractionPayload {
clip: layout.projection.panel_box(),
traces: Vec::new(),
domain_expansions: [None; 2],
};
let colors = marks.resolved_colors(
context
.registered
.categorical
.as_ref()
.expect("prepared color binding"),
request,
data.source_resources(),
)?;
crate::data::source::reserve_source(&mut payload.traces, marks.traces.len())?;
let mut geometry = crate::render::geometry::GeometrySnapshot::new();
let clip = crate::render::backend::validate_clip_region(payload.clip)?.panel();
for trace in &marks.traces {
let key = trace
.identity
.hue
.as_deref()
.or(trace.identity.group.as_deref())
.ok_or_else(|| Error::Render("interaction trace has no color identity".into()))?;
let color = colors.color(key)?;
let point = chart
.point_style(
request,
color,
request.marks.get_points().get_radii().get_interaction(),
)
.with_shape(trace.style.point_shape);
let mut line = request
.marks
.get_data_lines()
.get_interaction_connector()
.backend_style(color);
line.pattern = trace.style.line_pattern;
let line = line_style(trace.line_alpha, line);
let mut selected = TracePayload {
intervals: Vec::new(),
points: Vec::new(),
interval: line_style(
trace.line_alpha,
request
.marks
.get_data_lines()
.get_interaction_interval()
.backend_style(color),
),
connector: (chart.interaction_connectors_visible() && trace.cells.len() > 1)
.then(|| line.clone()),
markers: Vec::new(),
};
crate::data::source::reserve_source(&mut selected.intervals, trace.cells.len())?;
crate::data::source::reserve_source(&mut selected.points, trace.cells.len())?;
for cell in &trace.cells {
let x = cell.condition as f64 + 0.5;
let (px, py) = layout.projection.project(x, cell.estimate);
let (_, low) = layout.projection.project(x, cell.lower);
let (_, high) = layout.projection.project(x, cell.upper);
layout.projection.validate_span(
crate::layout::AxisSide::Left,
(cell.lower, cell.upper),
(low, high),
cell.lower < cell.upper,
"interaction interval",
)?;
let interval = [Point2D::new(px, low), Point2D::new(px, high)];
geometry.line(&interval, &selected.interval, Some(clip))?;
selected.intervals.push(interval);
selected.points.push(Point2D::new(px, py));
if chart.markers_visible() {
push_point(
&mut selected.markers,
Point2D::new(px, py),
cell.alpha.point(point.clone()),
)?;
}
}
if let Some(style) = &selected.connector {
geometry.line(&selected.points, style, Some(clip))?;
}
for (points, style) in &selected.markers {
geometry.scatter(points, style, clip)?;
}
payload.traces.push(selected);
}
payload.measure_ink(marks, &layout.projection, context)?;
Ok(MeasuredCoordinateMarks::new(
crate::data::source::source_arc(crate::layout::interior::SelectedMarkPlan {
payload: crate::layout::interior::MarkPayload::Interaction(payload),
geometry,
})?,
))
}
fn resolve_trace_styles(
chart: &crate::builder::PlotDescription,
levels: &[String],
) -> Result<Option<Vec<TraceStyle>>, Error> {
let Some(configured) = chart.interaction_styles_spec() else {
return Ok(None);
};
let mut styles = crate::data::source::collect_source(levels.iter().map(|_| Ok(None)))?;
for configured in configured {
let index =
crate::data::source::source_position(levels, |level| level == configured.group())
.ok_or_else(|| {
Error::Data(
format!(
"interaction: style references unknown graphical group {:?}",
configured.group()
)
.into(),
)
})?;
if styles[index].is_some() {
return Err(Error::Data(
format!(
"interaction: graphical group {:?} has more than one configured style",
configured.group()
)
.into(),
));
}
styles[index] = Some(TraceStyle {
point_shape: configured.get_point_shape(),
line_pattern: configured.get_line_pattern(),
});
}
crate::data::source::collect_source(styles.into_iter().zip(levels).map(|(style, trace)| {
style.ok_or_else(|| {
Error::Data(
format!("interaction: graphical group {trace:?} has no configured style").into(),
)
})
}))
.map(Some)
}