use crate::Error;
use crate::builder::PlotDescription;
use crate::elements::{GuideGeometry, GuideSpec};
use crate::layout::AxisTick;
use crate::render::backend::{with_clip, Backend, Point2D};
use crate::spec::{AxisScale, PlotKind, PlotRenderResult};
use num_bigint::BigInt;
impl PlotDescription {
pub(crate) fn projected_explicit_x_ticks(&self) -> Result<Option<Vec<f64>>, Error> {
self.explicit_x_ticks()
.map(|ticks| projected_x_ticks(self, ticks))
.transpose()
}
pub(crate) fn validate_supplemental_configuration(&self, kind: PlotKind) -> Result<(), Error> {
let configured = self.explicit_x_ticks().is_some()
|| self.explicit_y_ticks().is_some()
|| !self.guides().is_empty()
|| !self.point_layers().is_empty()
|| !self.bar_point_layers().is_empty();
if configured && self.has_facets() {
return Err(Error::Data(
"explicit numeric ticks, guides, and point layers are not supported with faceting in this focused phase"
.into(),
));
}
let (numeric_x, numeric_y) = numeric_axes(self, kind);
if self.explicit_x_ticks().is_some() && !numeric_x {
return Err(Error::Data(
format!("{kind:?}: explicit numeric x ticks require a numeric x axis").into(),
));
}
if self.explicit_y_ticks().is_some() && !numeric_y {
return Err(Error::Data(
format!("{kind:?}: explicit numeric y ticks require a numeric y axis").into(),
));
}
for guide in self.guides() {
match guide.geometry() {
GuideGeometry::Horizontal { .. } if !numeric_y => {
return Err(Error::Data(
format!("{kind:?}: a horizontal guide requires a numeric y axis").into(),
));
}
GuideGeometry::Vertical { .. } if !numeric_x => {
return Err(Error::Data(
format!("{kind:?}: a vertical guide requires a numeric x axis").into(),
));
}
GuideGeometry::Segment { .. } if !numeric_x || !numeric_y => {
return Err(Error::Data(
format!("{kind:?}: a finite segment guide requires numeric x and y axes")
.into(),
));
}
_ => {}
}
}
if !self.point_layers().is_empty() && kind != PlotKind::Line {
return Err(Error::Data(
format!("{kind:?}: borrowed point layers are supported only by Line").into(),
));
}
if !self.bar_point_layers().is_empty()
&& !matches!(kind, PlotKind::Bar | PlotKind::HorizontalBar)
{
return Err(Error::Data(
format!(
"{kind:?}: bar point layers are supported only by ordinary Bar and HorizontalBar"
)
.into(),
));
}
Ok(())
}
}
#[derive(Debug)]
pub(crate) struct GuideSnapshot {
clip: crate::layout::PixelRect,
lines: Vec<([Point2D; 2], crate::render::backend::LineStyle)>,
}
impl GuideSnapshot {
pub(crate) fn validate_sources(
chart: &PlotDescription,
ranges: [(f64, f64); 2],
) -> Result<(), Error> {
for (index, guide) in chart.guides().iter().enumerate() {
guide_endpoints(chart, guide, index, ranges[0], ranges[1])?;
}
Ok(())
}
pub(crate) fn measure(
chart: &PlotDescription,
result: &PlotRenderResult,
theme: &crate::Theme,
geometry: &mut crate::render::geometry::GeometrySnapshot,
) -> Result<Self, Error> {
let projection = &result.layout.projection;
if chart.explicit_x_ticks().is_some() {
crate::layout::Axis::validate_ticks(
&result.layout.x_axis.ticks,
projection.x_range(),
"x-axis",
)?;
}
if chart.explicit_y_ticks().is_some() {
crate::layout::Axis::validate_ticks(
&result.layout.y_axis.ticks,
projection.y_range(),
"y-axis",
)?;
}
let clip = projection.panel_box();
let canonical_clip = crate::render::backend::validate_clip_region(clip)?.panel();
let lines =
crate::data::source::collect_source(chart.guides().iter().enumerate().filter_map(
|(index, guide)| project_guide(chart, guide, index, projection, theme).transpose(),
))?;
for (points, style) in &lines {
geometry.line(points, style, Some(canonical_clip))?;
}
Ok(Self { clip, lines })
}
pub(crate) fn draw(&self, backend: &mut dyn Backend) -> Result<(), Error> {
if self.lines.is_empty() {
return Ok(());
}
with_clip(backend, self.clip, |backend| {
for (points, style) in &self.lines {
backend.draw_line(points, style)?;
}
Ok(())
})
}
}
fn projected_x_ticks(chart: &PlotDescription, ticks: &[AxisTick]) -> Result<Vec<f64>, Error> {
crate::data::source::collect_source(ticks
.iter()
.enumerate()
.map(|(index, tick)| {
let position = if chart.axis_scale_spec() == AxisScale::Linear {
tick.position
} else {
if tick.position <= 0.0 {
return Err(Error::Data(format!(
"x-axis explicit tick {index} position must be strictly positive on a logarithmic scale; got {}",
tick.position
).into()));
}
crate::numeric::log10(tick.position)?
};
Ok(position)
}))
}
type Segment = [(f64, f64); 2];
fn project_guide(
chart: &PlotDescription,
guide: &GuideSpec,
index: usize,
projection: &crate::layout::Projection,
theme: &crate::Theme,
) -> Result<Option<([Point2D; 2], crate::render::backend::LineStyle)>, Error> {
let x_range = projection.x_range();
let y_range = projection.y_range();
let endpoints = guide_endpoints(chart, guide, index, x_range, y_range)?;
let Some(clipped) = clip_segment(endpoints, [x_range, y_range])? else {
return Ok(None);
};
let points = clipped.map(|(x, y)| {
let point = projection.project(x, y);
Point2D::new(point.0, point.1)
});
if same_coordinate(points[0].x, points[1].x) && same_coordinate(points[0].y, points[1].y) {
return Err(Error::Render(
format!("guide {index}: nonzero clipped segment collapses at 1/1024 CSS-pixel coordinate precision").into(),
));
}
Ok(Some((points, guide.line_style(theme))))
}
fn guide_endpoints(
chart: &PlotDescription,
guide: &GuideSpec,
index: usize,
x_range: (f64, f64),
y_range: (f64, f64),
) -> Result<Segment, Error> {
let transform_x = |x: f64| {
if !x.is_finite() {
return Err(Error::Data(
format!("guide {index} requires finite x coordinates").into(),
));
}
if chart.axis_scale_spec() == AxisScale::Log10 {
if x <= 0.0 {
return Err(Error::Data(
format!(
"guide {index} x coordinate must be strictly positive on a logarithmic scale"
)
.into(),
));
}
crate::numeric::log10(x)
} else {
Ok(x)
}
};
let endpoints = match *guide.geometry() {
GuideGeometry::Horizontal { y } => [(x_range.0, y), (x_range.1, y)],
GuideGeometry::Vertical { x } => {
let x = transform_x(x)?;
[(x, y_range.0), (x, y_range.1)]
}
GuideGeometry::Segment { start, end } => [
(transform_x(start.0)?, start.1),
(transform_x(end.0)?, end.1),
],
};
if endpoints
.iter()
.any(|&(x, y)| !x.is_finite() || !y.is_finite())
{
return Err(Error::Data(
format!("guide {index} endpoints must contain finite coordinates").into(),
));
}
if same_coordinate(endpoints[0].0, endpoints[1].0)
&& same_coordinate(endpoints[0].1, endpoints[1].1)
{
return Err(Error::Data(
format!("guide {index} endpoints must be distinct").into(),
));
}
Ok(endpoints)
}
struct SegmentParameter {
numerator: BigInt,
denominator: BigInt,
}
impl SegmentParameter {
fn new(mut numerator: BigInt, mut denominator: BigInt) -> Self {
if denominator < BigInt::ZERO {
numerator = -numerator;
denominator = -denominator;
}
Self {
numerator,
denominator,
}
}
fn compare(&self, other: &Self) -> std::cmp::Ordering {
(&self.numerator * &other.denominator).cmp(&(&other.numerator * &self.denominator))
}
fn interpolate(&self, first: &BigInt, delta: &BigInt) -> Result<f64, Error> {
let numerator = first * &self.denominator + delta * &self.numerator;
crate::numeric::binary::signed_ratio(numerator, self.denominator.magnitude() << 1074_usize)
}
}
fn clip_segment(endpoints: Segment, ranges: [(f64, f64); 2]) -> Result<Option<Segment>, Error> {
let coordinates = [
[endpoints[0].0, endpoints[1].0],
[endpoints[0].1, endpoints[1].1],
];
if coordinates.iter().zip(ranges).any(|(axis, (low, high))| {
axis.iter().all(|&value| value < low) || axis.iter().all(|&value| value > high)
}) {
return Ok(None);
}
if coordinates
.iter()
.zip(ranges)
.all(|(axis, (low, high))| axis.iter().all(|&value| (low..=high).contains(&value)))
{
return Ok(Some(endpoints));
}
let mut start = SegmentParameter::new(0.into(), 1.into());
let mut end = SegmentParameter::new(1.into(), 1.into());
let mut axes = Vec::with_capacity(2);
for (axis, (low, high)) in coordinates.into_iter().zip(ranges) {
let first = crate::numeric::binary::units(axis[0])?;
let delta = crate::numeric::binary::units(axis[1])? - &first;
if delta != BigInt::ZERO {
let mut lower =
SegmentParameter::new(crate::numeric::binary::units(low)? - &first, delta.clone());
let mut upper =
SegmentParameter::new(crate::numeric::binary::units(high)? - &first, delta.clone());
if lower.compare(&upper).is_gt() {
std::mem::swap(&mut lower, &mut upper);
}
if lower.compare(&start).is_gt() {
start = lower;
}
if upper.compare(&end).is_lt() {
end = upper;
}
}
axes.push((first, delta));
}
if start.compare(&end).is_ge() {
return Ok(None);
}
let point = |parameter: &SegmentParameter| -> Result<(f64, f64), Error> {
Ok((
parameter.interpolate(&axes[0].0, &axes[0].1)?,
parameter.interpolate(&axes[1].0, &axes[1].1)?,
))
};
Ok(Some([point(&start)?, point(&end)?]))
}
fn same_coordinate(left: f64, right: f64) -> bool {
left.to_bits() == right.to_bits() || (left == 0.0 && right == 0.0)
}
fn numeric_axes(chart: &PlotDescription, kind: PlotKind) -> (bool, bool) {
match kind {
PlotKind::Scatter
| PlotKind::Histogram
| PlotKind::Density
| PlotKind::Qq
| PlotKind::Regression
| PlotKind::Marginal
| PlotKind::Line
| PlotKind::LinePath => (true, true),
PlotKind::Trajectory => {
let numeric_x = chart
.x_col()
.and_then(|column| chart.data_column(column))
.is_some_and(crate::data::DataColumn::is_numeric);
(numeric_x, true)
}
PlotKind::PointInterval
| PlotKind::Coefficient
| PlotKind::Forest
| PlotKind::Dumbbell
| PlotKind::HorizontalBar
| PlotKind::StackedHorizontalBar
| PlotKind::Beeswarm
| PlotKind::Waterfall => (true, false),
PlotKind::Interaction
| PlotKind::Bar
| PlotKind::StackedBar
| PlotKind::Boxplot
| PlotKind::Violin
| PlotKind::Raincloud => (false, true),
PlotKind::Heatmap | PlotKind::Matrix => (false, false),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn exact_guide_clipping_handles_finite_extreme_endpoints() {
let diagonal = clip_segment(
[(-f64::MAX, -f64::MAX), (f64::MAX, f64::MAX)],
[(-1., 1.), (-2., 2.)],
)
.unwrap()
.unwrap();
assert_eq!(diagonal, [(-1., -1.), (1., 1.)]);
let horizontal =
clip_segment([(-f64::MAX, 0.5), (f64::MAX, 0.5)], [(0., 1.), (0., 1.)]).unwrap();
assert_eq!(horizontal, Some([(0., 0.5), (1., 0.5)]));
assert!(
clip_segment([(0., f64::MAX), (1., f64::MAX)], [(0., 1.), (0., 1.)])
.unwrap()
.is_none()
);
assert!(clip_segment([(-1., 2.), (2., 5.)], [(0., 1.), (0., 1.)])
.unwrap()
.is_none());
}
#[test]
fn authored_optional_layer_properties_and_series_length_are_validated() {
use crate::{
elements::BarPointLayer, plots::BarInput, CategoryValues, Color, NumericValues, Plot,
};
let guide = GuideSpec::horizontal(1.);
assert!(
guide.get_color().is_none()
&& guide.get_width().is_none()
&& guide.get_pattern().is_none()
);
assert!(guide.width(f32::INFINITY).is_err());
let layer = BarPointLayer::new(
CategoryValues::new("category", ["A"]).unwrap(),
NumericValues::new("value", [1.5]),
);
assert!(layer.get_color().is_none() && layer.get_radius().is_none());
let layer = layer
.color(Color::rgba(5, 6, 7, 0.).unwrap())
.radius(3)
.unwrap();
assert_eq!(
layer.get_color().unwrap().get_alpha().to_bits(),
0.0_f64.to_bits()
);
let plot = Plot::bar(
CategoryValues::new("category", ["A", "A"]).unwrap(),
BarInput::estimates(NumericValues::new("value", [1., 2.])),
)
.series(CategoryValues::new("series", ["S1", "S2"]).unwrap())
.point_layer(layer.series(CategoryValues::new("series", ["S1", "S2"]).unwrap()));
assert!(matches!(plot.preflight(), Err(Error::Data(_))));
}
}