rizzma 1.13.7

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
537
538
//! The [`Patch`] artist: a filled and/or stroked closed shape.
//!
//! Mirrors matplotlib's `patches.Patch` hierarchy (`Rectangle`, `Polygon`,
//! `Circle`, `Ellipse`, `RegularPolygon`, `Wedge`, `Arc`) collapsed into a
//! single type parameterized by its data-space [`Path`]. The shape constructors
//! bake the position and size into the path's vertices, so a [`Patch`] carries
//! data-space geometry directly and is drawn by filling with its `facecolor`
//! and stroking with its `edgecolor`.
//!
//! Overlaying shapes on data (aperture rings on an image, region boxes on a
//! scatter) is the gallery's `patches` case:
//!
//! ![patches](https://raw.githubusercontent.com/OrbitalCommons/rizzma/gh-pages/gallery_patches.png)

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

use crate::artist::Artist;

/// matplotlib's default patch face color, a muted light blue (`C0` at the
/// lightened patch tint), used when [`Patch`] constructors are not given an
/// explicit face color.
const DEFAULT_FACECOLOR: Rgba = Rgba::new(0.121_568_63, 0.466_666_67, 0.705_882_35, 1.0);

/// Number of straight-line samples used to approximate the arc of a [`wedge`].
///
/// [`Patch::wedge`]: Patch::wedge
const WEDGE_ARC_SAMPLES: usize = 60;

/// A filled and/or stroked closed shape in data coordinates.
///
/// The `path` is stored in data space; the shape constructors
/// ([`rectangle`](Patch::rectangle), [`circle`](Patch::circle), …) bake the
/// requested position and size into it. Drawing fills the path with
/// `facecolor` (matplotlib's `rgbFace`) and strokes its edge with `edgecolor`.
///
/// Defaults mirror matplotlib: a muted light-blue face, opaque black edge,
/// `1.0`-point edge width, butt caps, miter joins, visible, and zorder `1.0`.
#[derive(Debug, Clone, PartialEq)]
pub struct Patch {
    /// The shape outline in data space.
    path: Path,
    /// Fill color, or `None` for an unfilled patch.
    facecolor: Option<Rgba>,
    /// Edge (stroke) color, or `None` for no edge.
    edgecolor: Option<Rgba>,
    /// Edge width in points.
    linewidth: f64,
    /// Optional dash pattern as `(offset, on_off_lengths)` in points.
    dashes: Option<(f64, Vec<f64>)>,
    /// Line cap style for the edge.
    cap: CapStyle,
    /// Line join style for the edge.
    join: JoinStyle,
    /// Whether the patch 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 patch.
    label: Option<String>,
}

impl Patch {
    /// Construct a [`Patch`] from a data-space `path` with matplotlib-ish
    /// defaults: a muted light-blue face, opaque black edge, `1.0`-point edge
    /// width, butt caps, miter joins, visible, and zorder `1.0`.
    #[must_use]
    pub fn new(path: Path) -> Self {
        Self {
            path,
            facecolor: Some(DEFAULT_FACECOLOR),
            edgecolor: Some(Rgba::BLACK),
            linewidth: 1.0,
            dashes: None,
            cap: CapStyle::Butt,
            join: JoinStyle::Miter,
            visible: true,
            zorder: 1.0,
            label: None,
        }
    }

    /// An axis-aligned rectangle with its lower-left corner at `(x, y)` and the
    /// given `w`idth and `h`eight, as a closed five-point polyline.
    #[must_use]
    pub fn rectangle(x: f64, y: f64, w: f64, h: f64) -> Self {
        let points = [[x, y], [x + w, y], [x + w, y + h], [x, y + h], [x, y]];
        Self::new(Path::from_polyline(&points))
    }

    /// A closed polygon through `points` in data space.
    ///
    /// The polygon is closed by appending the first point when it does not
    /// already repeat, matching matplotlib's `Polygon(closed=True)`.
    #[must_use]
    pub fn polygon(points: &[[f64; 2]]) -> Self {
        let mut verts = points.to_vec();
        if let Some(first) = verts
            .first()
            .copied()
            .filter(|first| verts.last() != Some(first))
        {
            verts.push(first);
        }
        Self::new(Path::from_polyline(&verts))
    }

    /// A circle of radius `r` centered at `center`.
    ///
    /// Built from [`Path::unit_circle`] scaled by `r` and translated to
    /// `center`, so the data-space path traces the circle directly.
    #[must_use]
    pub fn circle(center: [f64; 2], r: f64) -> Self {
        let [cx, cy] = center;
        let transform = Affine2D::from_scale(r, r).translate(cx, cy);
        Self::new(Path::unit_circle().transformed(&transform))
    }

    /// An axis-aligned ellipse centered at `center` with the given full `width`
    /// and `height` (matching matplotlib's `Ellipse`, which takes diameters).
    #[must_use]
    pub fn ellipse(center: [f64; 2], width: f64, height: f64) -> Self {
        let [cx, cy] = center;
        let transform = Affine2D::from_scale(width / 2.0, height / 2.0).translate(cx, cy);
        Self::new(Path::unit_circle().transformed(&transform))
    }

    /// A regular polygon with `num_sides` sides, circumscribed by a circle of
    /// `radius` centered at `center` and rotated `rotation_rad` radians.
    ///
    /// # Panics
    ///
    /// Panics if `num_sides` is zero (via [`Path::unit_regular_polygon`]).
    #[must_use]
    pub fn regular_polygon(
        center: [f64; 2],
        num_sides: usize,
        radius: f64,
        rotation_rad: f64,
    ) -> Self {
        let [cx, cy] = center;
        let transform = Affine2D::from_rotation(rotation_rad)
            .scale(radius, radius)
            .translate(cx, cy);
        Self::new(Path::unit_regular_polygon(num_sides).transformed(&transform))
    }

    /// A filled circular sector ("pie slice") of radius `r` centered at
    /// `center`, sweeping from `theta1_deg` to `theta2_deg` (degrees,
    /// counter-clockwise).
    ///
    /// The path runs from the center out to the start of the arc, samples the
    /// arc, and closes back to the center.
    #[must_use]
    pub fn wedge(center: [f64; 2], r: f64, theta1_deg: f64, theta2_deg: f64) -> Self {
        let [cx, cy] = center;
        let theta1 = theta1_deg.to_radians();
        let theta2 = theta2_deg.to_radians();
        let mut verts = Vec::with_capacity(WEDGE_ARC_SAMPLES + 2);
        verts.push([cx, cy]);
        for i in 0..=WEDGE_ARC_SAMPLES {
            let t = theta1 + (theta2 - theta1) * (i as f64 / WEDGE_ARC_SAMPLES as f64);
            verts.push([cx + r * t.cos(), cy + r * t.sin()]);
        }
        verts.push([cx, cy]);
        Self::new(Path::from_polyline(&verts))
    }

    /// An open circular arc of radius `r` centered at `center`, swept from
    /// `theta1_deg` to `theta2_deg` (degrees, counter-clockwise).
    ///
    /// Unlike [`wedge`](Patch::wedge) the path is not closed back through the
    /// center, and the patch defaults to **unfilled** — an arc is a stroked
    /// curve (matplotlib's `Arc` is likewise never filled). Style the stroke
    /// with [`edgecolor`](Patch::edgecolor)/[`linewidth`](Patch::linewidth).
    ///
    /// ```
    /// use rizzma::Figure;
    /// use rizzma::artist::Patch;
    ///
    /// let mut fig = Figure::new(3.0, 3.0);
    /// let ax = fig.add_axes(0.1, 0.1, 0.8, 0.8);
    /// ax.set_xlim(-2.0, 2.0);
    /// ax.set_ylim(-2.0, 2.0);
    /// // A 90-degree arc over the first quadrant.
    /// ax.add_patch(Patch::arc([0.0, 0.0], 1.5, 0.0, 90.0));
    /// assert!(!fig.encode_png().unwrap().is_empty());
    /// ```
    #[must_use]
    pub fn arc(center: [f64; 2], r: f64, theta1_deg: f64, theta2_deg: f64) -> Self {
        let [cx, cy] = center;
        let theta1 = theta1_deg.to_radians();
        let theta2 = theta2_deg.to_radians();
        let verts: Vec<[f64; 2]> = (0..=WEDGE_ARC_SAMPLES)
            .map(|i| {
                let t = theta1 + (theta2 - theta1) * (i as f64 / WEDGE_ARC_SAMPLES as f64);
                [cx + r * t.cos(), cy + r * t.sin()]
            })
            .collect();
        Self::new(Path::from_polyline(&verts)).facecolor(None)
    }

    /// The fill color, or `None` when unfilled (matplotlib's `get_facecolor`).
    #[must_use]
    pub fn face(&self) -> Option<Rgba> {
        self.facecolor
    }

    /// Set the fill color (or `None` for unfilled), returning `self` for
    /// chaining.
    #[must_use]
    pub fn facecolor(mut self, facecolor: Option<Rgba>) -> Self {
        self.facecolor = facecolor;
        self
    }

    /// Set the edge color (or `None` for no edge), returning `self` for
    /// chaining.
    #[must_use]
    pub fn edgecolor(mut self, edgecolor: Option<Rgba>) -> Self {
        self.edgecolor = edgecolor;
        self
    }

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

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

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

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

    /// Set the legend label, returning `self` for chaining. Labels are
    /// collected by [`Axes::legend_auto`](crate::figure::Axes::legend_auto),
    /// which keys the entry on the face color (or the edge color when
    /// unfilled); a label starting with `_` is never shown, as in matplotlib.
    #[must_use]
    pub fn with_label(mut self, label: impl Into<String>) -> Self {
        self.set_label(label);
        self
    }

    /// Set the legend label in place; see [`with_label`](Patch::with_label).
    pub fn set_label(&mut self, label: impl Into<String>) -> &mut Self {
        self.label = Some(label.into());
        self
    }

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

    /// The edge (stroke) color, or `None` when the patch has no edge.
    #[must_use]
    pub fn edge(&self) -> Option<Rgba> {
        self.edgecolor
    }

    /// The data-space path traced by this patch.
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }

    /// Draw this patch's fill and stroke style against an already-built path.
    ///
    /// This lets an owning axes pre-transform nonlinear-scale geometry while
    /// reusing the patch's face, edge, width, dash, cap, and join settings.
    pub fn draw_path(&self, renderer: &mut dyn Renderer, path: &Path, transform: &Affine2D) {
        if !self.visible {
            return;
        }
        let gc = GraphicsContext {
            line_width: self.linewidth,
            dashes: self.dashes.clone(),
            cap: self.cap,
            join: self.join,
            stroke: self.edgecolor,
            ..GraphicsContext::new()
        };
        renderer.draw_path(&gc, path, transform, self.facecolor);
    }
}

impl Artist for Patch {
    fn draw(&self, renderer: &mut dyn Renderer, transform: &Affine2D) {
        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> {
        Some(self.path.get_extents())
    }
}

#[cfg(feature = "portable")]
impl Patch {
    /// Flatten this patch into its wire form, banking the outline as
    /// accessors.
    pub(crate) fn to_portable(
        &self,
        bank: &mut crate::portable::data::BankWriter,
    ) -> crate::portable::spec::PatchSpec {
        crate::portable::spec::PatchSpec {
            path: self.path.to_portable(bank),
            facecolor: self.facecolor,
            edgecolor: self.edgecolor,
            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 patch from its wire form during portable-figure import.
    pub(crate) fn from_portable(
        spec: &crate::portable::spec::PatchSpec,
        reader: &crate::portable::data::BankReader<'_>,
    ) -> Result<Patch, crate::portable::PortableError> {
        Ok(Patch {
            path: Path::from_portable(&spec.path, reader)?,
            facecolor: spec.facecolor,
            edgecolor: spec.edgecolor,
            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::*;

    /// A [`Renderer`] that records, per `draw_path` call, the path's vertex
    /// count and the fill (face) color.
    #[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(), fill));
        }

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

    fn approx(a: f64, b: f64) {
        assert!((a - b).abs() < 1e-9, "expected {b}, got {a}");
    }

    #[test]
    fn red_rectangle_draws_once_with_fill() {
        let patch = Patch::rectangle(0.0, 0.0, 2.0, 2.0).facecolor(Some(Rgba::RED));
        let mut r = MockRenderer::default();
        patch.draw(&mut r, &Affine2D::identity());
        // A closed rectangle is five vertices, filled red.
        assert_eq!(r.calls, vec![(5, Some(Rgba::RED))]);
    }

    #[test]
    fn rectangle_data_extents() {
        let patch = Patch::rectangle(0.0, 0.0, 2.0, 2.0);
        let e = patch.data_extents().expect("non-empty");
        approx(e.xmin(), 0.0);
        approx(e.ymin(), 0.0);
        approx(e.xmax(), 2.0);
        approx(e.ymax(), 2.0);
    }

    #[test]
    fn rectangle_is_closed() {
        let patch = Patch::rectangle(1.0, 2.0, 3.0, 4.0);
        let verts = patch.path().vertices();
        assert_eq!(verts.len(), 5);
        assert_eq!(verts.first(), verts.last());
    }

    #[test]
    fn invisible_patch_draws_nothing() {
        let patch = Patch::rectangle(0.0, 0.0, 1.0, 1.0).with_visible(false);
        let mut r = MockRenderer::default();
        patch.draw(&mut r, &Affine2D::identity());
        assert!(r.calls.is_empty());
    }

    #[test]
    fn default_zorder_is_one() {
        let patch = Patch::rectangle(0.0, 0.0, 1.0, 1.0);
        assert_eq!(patch.zorder(), 1.0);
    }

    #[test]
    fn with_zorder_sets_trait_zorder() {
        let patch = Patch::rectangle(0.0, 0.0, 1.0, 1.0).with_zorder(7.0);
        assert_eq!(patch.zorder(), 7.0);
    }

    #[test]
    fn polygon_closes_open_input() {
        let patch = Patch::polygon(&[[0.0, 0.0], [1.0, 0.0], [0.5, 1.0]]);
        let verts = patch.path().vertices();
        // Three corners plus the appended closing vertex.
        assert_eq!(verts.len(), 4);
        assert_eq!(verts.first(), verts.last());
    }

    #[test]
    fn circle_extents_match_center_and_radius() {
        let patch = Patch::circle([50.0, 50.0], 30.0);
        let e = patch.data_extents().expect("non-empty");
        approx(e.xmin(), 20.0);
        approx(e.xmax(), 80.0);
        approx(e.ymin(), 20.0);
        approx(e.ymax(), 80.0);
    }

    #[test]
    fn ellipse_uses_full_width_and_height() {
        let patch = Patch::ellipse([0.0, 0.0], 4.0, 2.0);
        let e = patch.data_extents().expect("non-empty");
        approx(e.xmin(), -2.0);
        approx(e.xmax(), 2.0);
        approx(e.ymin(), -1.0);
        approx(e.ymax(), 1.0);
    }

    #[test]
    fn regular_polygon_square_has_four_distinct_corners() {
        // A square: 4 sides, no rotation.
        let patch = Patch::regular_polygon([0.0, 0.0], 4, 1.0, 0.0);
        let verts = patch.path().vertices();
        // unit_regular_polygon(4) yields 5 vertices (4 corners + closing dup).
        assert_eq!(verts.len(), 5);
        // The first four are the distinct corners.
        let corners = &verts[..4];
        for i in 0..corners.len() {
            for j in (i + 1)..corners.len() {
                let d = (corners[i][0] - corners[j][0]).hypot(corners[i][1] - corners[j][1]);
                assert!(d > 1e-6, "corners {i} and {j} coincide");
            }
        }
    }

    #[test]
    fn wedge_stays_within_bounding_quadrant() {
        // 0..90 degrees, radius 10, centered at origin: the sector lives in the
        // first quadrant, bounded by [0, 10] x [0, 10].
        let patch = Patch::wedge([0.0, 0.0], 10.0, 0.0, 90.0);
        let e = patch.data_extents().expect("non-empty");
        approx(e.xmin(), 0.0);
        approx(e.ymin(), 0.0);
        approx(e.xmax(), 10.0);
        approx(e.ymax(), 10.0);
        // Every vertex is inside the radius-10 disk (center plus arc samples).
        for &[x, y] in patch.path().vertices() {
            assert!(
                x.hypot(y) <= 10.0 + 1e-9,
                "vertex ({x}, {y}) outside radius"
            );
        }
    }

    #[test]
    fn arc_vertices_lie_on_the_radius_and_span_the_sweep() {
        let patch = Patch::arc([2.0, -1.0], 3.0, 45.0, 180.0);
        let verts = patch.path().vertices();
        // Open arc: no center point, no closure back to the start.
        for &[x, y] in verts {
            approx((x - 2.0).hypot(y + 1.0), 3.0);
        }
        let first = verts.first().copied().unwrap();
        let last = verts.last().copied().unwrap();
        approx(first[0], 2.0 + 3.0 * 45f64.to_radians().cos());
        approx(first[1], -1.0 + 3.0 * 45f64.to_radians().sin());
        approx(last[0], 2.0 - 3.0); // 180 degrees
        approx(last[1], -1.0);
    }

    #[test]
    fn arc_defaults_to_unfilled_stroke_only() {
        let patch = Patch::arc([0.0, 0.0], 1.0, 0.0, 90.0);
        let mut r = MockRenderer::default();
        patch.draw(&mut r, &Affine2D::identity());
        // Exactly one draw call, and it carries no fill color.
        assert_eq!(r.calls.len(), 1);
        assert_eq!(r.calls[0].1, None);
    }
}