lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
//! Validation and rendering for supplemental numeric geometry.

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> {
        // All input coordinates are exact units of 2^-1074. Interpolate in
        // that same lattice, then round the resulting scientific coordinate once.
        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));
    }

    // Exact parameter clipping avoids overflowing extrapolations or losing
    // the intersection of a very long finite segment with a small exact window.
    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(_))));
    }
}