rizzma 1.13.5

A Rust reimplementation of the good parts of matplotlib/pyplot, with first-class wasm support.
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
//! The [`Line2D`] artist: a stroked polyline through `(x, y)` data points.
//!
//! Mirrors matplotlib's `Line2D` for the stroke-only case (markers are deferred
//! to a follow-up). Drawing zips the `x`/`y` data into points, builds a
//! [`Path`] via [`Line2D::path`] — one subpath per run of finite points, so a
//! `NaN` is a gap in the stroke rather than a joined vertex — and strokes it
//! through the [`Renderer`].

use crate::core::{Affine2D, Bbox, Path, PathCode, color::Rgba};
use crate::render::{CapStyle, GraphicsContext, JoinStyle, Renderer};

use crate::artist::Artist;

/// A 2D line: a stroked polyline through paired `x`/`y` data.
///
/// Constructed with [`Line2D::new`], then customized either with the
/// consuming `with_*` builders (`Line2D::new(x, y).with_color(c)`) or, on a
/// line that already lives on an axes, with the `&mut self` `set_*` setters
/// (`ax.plot(&x, &y).set_color(c)`). Each `with_*` delegates to its `set_*`
/// twin, so the two families are always in sync. The defaults mirror
/// matplotlib: opaque black, `1.5`-point width, butt caps, miter joins,
/// visible, and zorder `2.0`.
#[derive(Debug, Clone, PartialEq)]
pub struct Line2D {
    /// X coordinates of the data points, in data space.
    xdata: Vec<f64>,
    /// Y coordinates of the data points, in data space.
    ydata: Vec<f64>,
    /// Stroke color.
    color: Rgba,
    /// Stroke width in points.
    linewidth: f64,
    /// Optional dash pattern as `(offset, on_off_lengths)` in points.
    dashes: Option<(f64, Vec<f64>)>,
    /// Line cap style for open ends.
    cap: CapStyle,
    /// Line join style for corners.
    join: JoinStyle,
    /// Whether the line is drawn.
    visible: bool,
    /// Stacking order; higher draws on top.
    zorder: f64,
    /// Legend label, collected by
    /// [`Axes::legend_auto`](crate::figure::Axes::legend_auto); `None` for an
    /// anonymous line.
    label: Option<String>,
}

impl Line2D {
    /// Construct a [`Line2D`] from `xdata` and `ydata` with matplotlib-ish
    /// defaults: opaque black, `1.5`-point width, butt caps, miter joins,
    /// visible, and zorder `2.0`.
    ///
    /// The `x` and `y` vectors are paired index-wise at draw time; only the
    /// common prefix is drawn if they differ in length. A non-finite `x` or `y`
    /// (`NaN`, `±inf`) breaks the stroke: the points before and after it are
    /// not joined, matplotlib's idiom for a series with missing samples.
    #[must_use]
    pub fn new(xdata: Vec<f64>, ydata: Vec<f64>) -> Self {
        Self {
            xdata,
            ydata,
            color: Rgba::BLACK,
            linewidth: 1.5,
            dashes: None,
            cap: CapStyle::Butt,
            join: JoinStyle::Miter,
            visible: true,
            zorder: 2.0,
            label: None,
        }
    }

    /// The legend label, if any.
    #[must_use]
    pub fn label(&self) -> Option<&str> {
        self.label.as_deref()
    }

    /// The stroke color.
    #[must_use]
    pub fn color(&self) -> Rgba {
        self.color
    }

    /// Replace the line's data in place (for live/streaming updates), keeping
    /// every style property. The `x` and `y` slices are paired index-wise at
    /// draw time exactly as at construction.
    pub fn set_data(&mut self, x: &[f64], y: &[f64]) -> &mut Self {
        self.xdata = x.to_vec();
        self.ydata = y.to_vec();
        self
    }

    /// Set the stroke color in place.
    pub fn set_color(&mut self, color: Rgba) -> &mut Self {
        self.color = color;
        self
    }

    /// Set the stroke width in points in place.
    pub fn set_linewidth(&mut self, linewidth: f64) -> &mut Self {
        self.linewidth = linewidth;
        self
    }

    /// Set the dash pattern as `(offset, on_off_lengths)` in points in place;
    /// `None` draws a solid stroke.
    pub fn set_dashes(&mut self, dashes: Option<(f64, Vec<f64>)>) -> &mut Self {
        self.dashes = dashes;
        self
    }

    /// Set the line cap style in place.
    pub fn set_cap(&mut self, cap: CapStyle) -> &mut Self {
        self.cap = cap;
        self
    }

    /// Set the line join style in place.
    pub fn set_join(&mut self, join: JoinStyle) -> &mut Self {
        self.join = join;
        self
    }

    /// Show or hide the line in place.
    pub fn set_visible(&mut self, visible: bool) -> &mut Self {
        self.visible = visible;
        self
    }

    /// Set the stacking order in place; higher draws on top.
    pub fn set_zorder(&mut self, zorder: f64) -> &mut Self {
        self.zorder = zorder;
        self
    }

    /// Set the legend label in place. Labels are collected by
    /// [`Axes::legend_auto`](crate::figure::Axes::legend_auto); a label
    /// starting with `_` is kept on the line but never shown in a legend, as
    /// in matplotlib.
    pub fn set_label(&mut self, label: impl Into<String>) -> &mut Self {
        self.label = Some(label.into());
        self
    }

    /// Set the stroke color, returning `self` for chaining.
    #[must_use]
    pub fn with_color(mut self, color: Rgba) -> Self {
        self.set_color(color);
        self
    }

    /// Set the stroke width in points, returning `self` for chaining.
    #[must_use]
    pub fn with_linewidth(mut self, linewidth: f64) -> Self {
        self.set_linewidth(linewidth);
        self
    }

    /// Set the dash pattern as `(offset, on_off_lengths)` in points, returning
    /// `self` for chaining.
    #[must_use]
    pub fn with_dashes(mut self, dashes: Option<(f64, Vec<f64>)>) -> Self {
        self.set_dashes(dashes);
        self
    }

    /// Set the line cap style, returning `self` for chaining.
    #[must_use]
    pub fn with_cap(mut self, cap: CapStyle) -> Self {
        self.set_cap(cap);
        self
    }

    /// Set the line join style, returning `self` for chaining.
    #[must_use]
    pub fn with_join(mut self, join: JoinStyle) -> Self {
        self.set_join(join);
        self
    }

    /// Set whether the line is drawn, returning `self` for chaining.
    #[must_use]
    pub fn with_visible(mut self, visible: bool) -> Self {
        self.set_visible(visible);
        self
    }

    /// Set the stacking order, returning `self` for chaining.
    #[must_use]
    pub fn with_zorder(mut self, zorder: f64) -> Self {
        self.set_zorder(zorder);
        self
    }

    /// Set the legend label, returning `self` for chaining; see
    /// [`set_label`](Line2D::set_label).
    #[must_use]
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.set_label(label);
        self
    }

    /// The `(x, y)` data points zipped into a `Vec<[f64; 2]>`.
    #[must_use]
    pub fn points(&self) -> Vec<[f64; 2]> {
        self.xdata
            .iter()
            .zip(self.ydata.iter())
            .map(|(&x, &y)| [x, y])
            .collect()
    }

    /// The data-space stroke path: one subpath per run of two or more
    /// consecutive finite points.
    ///
    /// A non-finite `x` or `y` ends the current run without adding a vertex,
    /// so the stroke lifts across the gap instead of joining its neighbours
    /// (matplotlib treats `NaN` as a break). Isolated finite points between
    /// gaps have no stroke and are dropped. Without gaps the result is the
    /// plain implicit polyline (`codes` is `None`); with gaps every vertex is
    /// coded, each run opening with a [`PathCode::MoveTo`].
    #[must_use]
    pub fn path(&self) -> Path {
        let points = self.points();
        if points.iter().all(|[x, y]| x.is_finite() && y.is_finite()) {
            return Path::from_polyline(&points);
        }

        let mut vertices: Vec<[f64; 2]> = Vec::with_capacity(points.len());
        let mut codes: Vec<PathCode> = Vec::with_capacity(points.len());
        for run in points
            .split(|[x, y]| !x.is_finite() || !y.is_finite())
            .filter(|run| run.len() >= 2)
        {
            vertices.extend_from_slice(run);
            codes.push(PathCode::MoveTo);
            codes.extend(std::iter::repeat_n(PathCode::LineTo, run.len() - 1));
        }
        Path::new(vertices, Some(codes))
    }

    /// Draw this line's stroke style against an already-built data-space path.
    ///
    /// This lets an owning axes pre-transform nonlinear-scale geometry while
    /// reusing the line's color, width, dash, cap, and join settings.
    pub fn draw_path(&self, renderer: &mut dyn Renderer, path: &Path, transform: &Affine2D) {
        if !self.visible || path.vertices().len() < 2 {
            return;
        }
        let gc = GraphicsContext {
            line_width: self.linewidth,
            dashes: self.dashes.clone(),
            cap: self.cap,
            join: self.join,
            stroke: Some(self.color),
            ..GraphicsContext::new()
        };
        renderer.draw_path(&gc, path, transform, None);
    }
}

impl Artist for Line2D {
    fn draw(&self, renderer: &mut dyn Renderer, transform: &Affine2D) {
        if !self.visible {
            return;
        }
        self.draw_path(renderer, &self.path(), transform);
    }

    fn zorder(&self) -> f64 {
        self.zorder
    }

    fn visible(&self) -> bool {
        self.visible
    }

    fn data_extents(&self) -> Option<Bbox> {
        let mut xmin = f64::INFINITY;
        let mut ymin = f64::INFINITY;
        let mut xmax = f64::NEG_INFINITY;
        let mut ymax = f64::NEG_INFINITY;
        let mut any = false;
        for (&x, &y) in self.xdata.iter().zip(self.ydata.iter()) {
            if !x.is_finite() || !y.is_finite() {
                continue;
            }
            xmin = xmin.min(x);
            ymin = ymin.min(y);
            xmax = xmax.max(x);
            ymax = ymax.max(y);
            any = true;
        }
        if any {
            Some(Bbox::from_extents(xmin, ymin, xmax, ymax))
        } else {
            None
        }
    }
}

#[cfg(feature = "portable")]
impl Line2D {
    /// Flatten this line into its wire form, banking the data as accessors.
    pub(crate) fn to_portable(
        &self,
        bank: &mut crate::portable::data::BankWriter,
    ) -> crate::portable::spec::LineSpec {
        crate::portable::spec::LineSpec {
            x: bank.push_f64(&self.xdata),
            y: bank.push_f64(&self.ydata),
            color: self.color,
            linewidth: self.linewidth,
            dashes: self.dashes.clone(),
            cap: self.cap,
            join: self.join,
            visible: self.visible,
            zorder: self.zorder,
            label: self.label.clone(),
        }
    }

    /// Reconstruct a line from its wire form during portable-figure import.
    pub(crate) fn from_portable(
        spec: &crate::portable::spec::LineSpec,
        reader: &crate::portable::data::BankReader<'_>,
    ) -> Result<Line2D, crate::portable::PortableError> {
        Ok(Line2D {
            xdata: reader.f64s(&spec.x)?,
            ydata: reader.f64s(&spec.y)?,
            color: spec.color,
            linewidth: spec.linewidth,
            dashes: spec.dashes.clone(),
            cap: spec.cap,
            join: spec.join,
            visible: spec.visible,
            zorder: spec.zorder,
            label: spec.label.clone(),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn path_without_gaps_is_the_implicit_polyline() {
        let line = Line2D::new(vec![0.0, 1.0, 2.0], vec![0.0, 1.0, 0.5]);
        let path = line.path();
        assert_eq!(path.vertices(), &[[0.0, 0.0], [1.0, 1.0], [2.0, 0.5]]);
        assert!(path.codes().is_none());
    }

    #[test]
    fn nan_splits_the_stroke_into_subpaths() {
        // 0-1 joined, gap, 3-4 joined: the stroke must not bridge 1.0 -> 3.0.
        let line = Line2D::new(
            vec![0.0, 1.0, 2.0, 3.0, 4.0],
            vec![0.0, 1.0, f64::NAN, 3.0, 4.0],
        );
        let path = line.path();
        assert_eq!(
            path.vertices(),
            &[[0.0, 0.0], [1.0, 1.0], [3.0, 3.0], [4.0, 4.0]]
        );
        assert_eq!(
            path.codes(),
            Some(
                [
                    PathCode::MoveTo,
                    PathCode::LineTo,
                    PathCode::MoveTo,
                    PathCode::LineTo,
                ]
                .as_slice()
            )
        );
        let subpaths = path.flatten(0.1);
        assert_eq!(subpaths.len(), 2, "one flattened polyline per finite run");
    }

    #[test]
    fn non_finite_x_and_isolated_points_are_gaps_too() {
        // inf in x breaks the run; the lone finite point at index 3 has no
        // stroke and is dropped; the trailing pair survives.
        let line = Line2D::new(
            vec![0.0, 1.0, f64::INFINITY, 3.0, f64::NAN, 5.0, 6.0],
            vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0],
        );
        let path = line.path();
        assert_eq!(
            path.vertices(),
            &[[0.0, 0.0], [1.0, 1.0], [5.0, 5.0], [6.0, 6.0]]
        );
        // Extents still ignore only the non-finite samples themselves.
        let e = line.data_extents().unwrap();
        assert_eq!((e.xmin(), e.xmax()), (0.0, 6.0));
    }

    #[test]
    fn all_gaps_draws_nothing() {
        let line = Line2D::new(vec![0.0, 1.0], vec![f64::NAN, f64::NAN]);
        assert!(line.path().vertices().is_empty());
        let mut r = MockRenderer::default();
        line.draw(&mut r, &Affine2D::identity());
        assert!(r.calls.is_empty());
    }

    #[test]
    fn gapped_line_strokes_only_finite_vertices() {
        let line = Line2D::new(
            vec![0.0, 1.0, 2.0, 3.0, 4.0],
            vec![0.0, 1.0, f64::NAN, 3.0, 4.0],
        );
        let mut r = MockRenderer::default();
        line.draw(&mut r, &Affine2D::identity());
        // One draw_path call carrying the four finite vertices (two runs).
        assert_eq!(r.calls.len(), 1);
        assert_eq!(r.calls[0].0, 4);
    }

    /// The `set_*` setters and the `with_*` builders must produce identical
    /// lines, so styling through a `&mut Line2D` handle is never a second-class
    /// path.
    #[test]
    fn set_and_with_setters_agree() {
        let built = Line2D::new(vec![0.0, 1.0], vec![0.0, 1.0])
            .with_color(Rgba::RED)
            .with_linewidth(3.0)
            .with_dashes(Some((0.0, vec![4.0, 2.0])))
            .with_cap(CapStyle::Round)
            .with_join(JoinStyle::Round)
            .with_visible(false)
            .with_zorder(7.0)
            .with_label("p50");

        let mut set = Line2D::new(vec![0.0, 1.0], vec![0.0, 1.0]);
        set.set_color(Rgba::RED)
            .set_linewidth(3.0)
            .set_dashes(Some((0.0, vec![4.0, 2.0])))
            .set_cap(CapStyle::Round)
            .set_join(JoinStyle::Round)
            .set_visible(false)
            .set_zorder(7.0)
            .set_label("p50");

        assert_eq!(built, set);
        assert_eq!(set.color(), Rgba::RED);
        assert!(!set.visible());
        assert_eq!(set.label(), Some("p50"));
        assert_eq!(Line2D::new(vec![], vec![]).label(), None);
    }

    /// A [`Renderer`] that records, per `draw_path` call, the path's vertex
    /// count and the stroke color from the [`GraphicsContext`].
    #[derive(Default)]
    struct MockRenderer {
        calls: Vec<(usize, Option<Rgba>)>,
    }

    impl Renderer for MockRenderer {
        fn draw_path(
            &mut self,
            gc: &GraphicsContext,
            path: &Path,
            _transform: &Affine2D,
            _fill: Option<Rgba>,
        ) {
            self.calls.push((path.vertices().len(), gc.stroke));
        }

        fn canvas_size(&self) -> (f64, f64) {
            (100.0, 100.0)
        }
    }

    #[test]
    fn three_point_line_draws_once_with_color() {
        let line = Line2D::new(vec![0.0, 1.0, 2.0], vec![0.0, 1.0, 0.0]).with_color(Rgba::RED);
        let mut r = MockRenderer::default();
        line.draw(&mut r, &Affine2D::identity());
        assert_eq!(r.calls, vec![(3, Some(Rgba::RED))]);
    }

    #[test]
    fn invisible_line_draws_nothing() {
        let line = Line2D::new(vec![0.0, 1.0], vec![0.0, 1.0]).with_visible(false);
        let mut r = MockRenderer::default();
        line.draw(&mut r, &Affine2D::identity());
        assert!(r.calls.is_empty());
    }

    #[test]
    fn single_point_line_draws_nothing() {
        let line = Line2D::new(vec![0.0], vec![0.0]);
        let mut r = MockRenderer::default();
        line.draw(&mut r, &Affine2D::identity());
        assert!(r.calls.is_empty());
    }

    #[test]
    fn data_extents_bounds_finite_points() {
        let line = Line2D::new(vec![1.0, 3.0, 2.0], vec![-1.0, 4.0, 0.0]);
        let e = line.data_extents().expect("non-empty");
        assert_eq!(e.xmin(), 1.0);
        assert_eq!(e.xmax(), 3.0);
        assert_eq!(e.ymin(), -1.0);
        assert_eq!(e.ymax(), 4.0);
    }

    #[test]
    fn data_extents_ignores_nan_point() {
        let line = Line2D::new(vec![1.0, f64::NAN, 2.0], vec![1.0, 5.0, 2.0]);
        let e = line.data_extents().expect("non-empty");
        // The NaN x-point is skipped, so x stays in [1, 2] and y in [1, 2].
        assert_eq!(e.xmin(), 1.0);
        assert_eq!(e.xmax(), 2.0);
        assert_eq!(e.ymin(), 1.0);
        assert_eq!(e.ymax(), 2.0);
    }

    #[test]
    fn data_extents_empty_is_none() {
        let line = Line2D::new(vec![], vec![]);
        assert!(line.data_extents().is_none());
    }

    #[test]
    fn default_zorder_is_two() {
        let line = Line2D::new(vec![0.0, 1.0], vec![0.0, 1.0]);
        assert_eq!(line.zorder(), 2.0);
    }
}