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
//! The [`Axes::contour`] line-contour helper.
//!
//! Mirrors matplotlib's `Axes.contour` for the regular-grid case: it runs the
//! standard marching-squares algorithm over a row-major `nrows x ncols` scalar
//! field (corners at integer `x = 0..ncols-1`, `y = 0..nrows-1`), tracing the
//! level sets of a set of evenly-spaced contour levels. Each contour crossing of
//! a grid cell is emitted as a short [`Line2D`] segment colored by its level
//! through a [`LinearNorm`] and the default colormap, and the grid extent
//! folds into [`data_limits`](super::Axes::data_limits) for autoscaling.

use crate::artist::Line2D;
use crate::core::color::{Colormap, LinearNorm, Normalize, default_colormap};

use crate::figure::Axes;

/// Default number of contour levels for [`Axes::contour`].
const DEFAULT_N_LEVELS: usize = 7;

/// A removable contour segment selected as the label position for one level.
#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub(crate) struct ContourLabelCandidate {
    pub(crate) line_index: usize,
    pub(crate) position: (f64, f64),
    pub(crate) level: f64,
    pub(crate) color: crate::core::color::Rgba,
}

/// The finite min and max of `data`, or `(0.0, 1.0)` when there is no finite
/// value (empty or all-NaN input).
fn data_min_max(data: &[f64]) -> (f64, f64) {
    let mut min = f64::INFINITY;
    let mut max = f64::NEG_INFINITY;
    for &v in data {
        if v.is_finite() {
            min = min.min(v);
            max = max.max(v);
        }
    }
    if min <= max { (min, max) } else { (0.0, 1.0) }
}

/// Linearly interpolate the crossing fraction where the segment from value `a`
/// to value `b` equals `level`.
///
/// Returns the parameter `t in [0, 1]` with `a + t * (b - a) == level`. The
/// caller guarantees `a` and `b` straddle `level`, so `b != a`.
fn crossing(a: f64, b: f64, level: f64) -> f64 {
    (level - a) / (b - a)
}

/// Append the marching-squares line segment(s) for one grid cell to `segments`.
///
/// The cell's four corner values are passed as `corners` in the order
/// `[top_left, top_right, bottom_left, bottom_right]`, where "top" is row `r`
/// and "bottom" is row `r + 1`; `c` is the left column. Corner positions are at
/// integer grid coordinates. Each emitted segment is a pair of crossing points
/// in data space.
///
/// The ambiguous saddle cases (5 and 10) are resolved by comparing the cell's
/// average corner value against the level: this is the standard "midpoint"
/// convention and connects the crossings so the region above the level stays
/// connected through the saddle.
fn cell_segments(corners: [f64; 4], r: f64, c: f64, level: f64, segments: &mut Vec<[[f64; 2]; 2]>) {
    let [tl, tr, bl, br] = corners;
    // Classify each corner as above (1) or below/equal (0) the level. The bits
    // are ordered tl=8, tr=4, br=2, bl=1 (clockwise from the top-left) to match
    // the canonical marching-squares case table.
    let mut case = 0u8;
    if tl > level {
        case |= 8;
    }
    if tr > level {
        case |= 4;
    }
    if br > level {
        case |= 2;
    }
    if bl > level {
        case |= 1;
    }

    // Edge crossing points (when the bounding corners straddle the level):
    //   top:    between tl (x=c)   and tr (x=c+1) at y=r
    //   right:  between tr (y=r)   and br (y=r+1) at x=c+1
    //   bottom: between bl (x=c)   and br (x=c+1) at y=r+1
    //   left:   between tl (y=r)   and bl (y=r+1) at x=c
    let top = || [c + crossing(tl, tr, level), r];
    let right = || [c + 1.0, r + crossing(tr, br, level)];
    let bottom = || [c + crossing(bl, br, level), r + 1.0];
    let left = || [c, r + crossing(tl, bl, level)];

    match case {
        // No crossings.
        0 | 15 => {}
        // One corner differs: a single segment cutting off that corner.
        1 | 14 => segments.push([left(), bottom()]),
        2 | 13 => segments.push([bottom(), right()]),
        4 | 11 => segments.push([top(), right()]),
        8 | 7 => segments.push([left(), top()]),
        // Two adjacent corners: a single segment across the cell.
        3 | 12 => segments.push([left(), right()]),
        6 | 9 => segments.push([top(), bottom()]),
        // Saddles: two diagonal corners differ. Resolve by the cell average.
        5 | 10 => {
            let avg = (tl + tr + bl + br) / 4.0;
            if (case == 5) == (avg > level) {
                // Connect top-to-right and bottom-to-left.
                segments.push([top(), right()]);
                segments.push([left(), bottom()]);
            } else {
                // Connect top-to-left and bottom-to-right.
                segments.push([left(), top()]);
                segments.push([bottom(), right()]);
            }
        }
        _ => unreachable!("marching-squares case is a 4-bit value"),
    }
}

/// Collect the marching-squares contour segments of `z` at a single `level`.
///
/// `z` is row-major `nrows * ncols`; the returned segments are pairs of points
/// in grid/data space. Grids smaller than `2 x 2` produce no segments.
fn level_segments(z: &[f64], nrows: usize, ncols: usize, level: f64) -> Vec<[[f64; 2]; 2]> {
    let mut segments = Vec::new();
    if nrows < 2 || ncols < 2 {
        return segments;
    }
    for r in 0..nrows - 1 {
        for c in 0..ncols - 1 {
            let tl = z[r * ncols + c];
            let tr = z[r * ncols + c + 1];
            let bl = z[(r + 1) * ncols + c];
            let br = z[(r + 1) * ncols + c + 1];
            cell_segments([tl, tr, bl, br], r as f64, c as f64, level, &mut segments);
        }
    }
    segments
}

impl Axes {
    /// Draw line contours of row-major scalar `z` (`nrows x ncols`) at the
    /// default seven levels.
    ///
    /// Equivalent to [`contour_levels`](Axes::contour_levels) with
    /// `n_levels = 7`. The levels are evenly spaced strictly between the finite
    /// data minimum and maximum.
    ///
    /// # Panics
    ///
    /// Panics if `z.len()` is not exactly `nrows * ncols`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rizzma::core::Bbox;
    /// use rizzma::figure::Axes;
    ///
    /// let mut ax = Axes::new(Bbox::from_extents(0.0, 0.0, 1.0, 1.0));
    /// // A 3x3 ramp increasing along x; contours are vertical lines.
    /// let z = [0.0, 1.0, 2.0, 0.0, 1.0, 2.0, 0.0, 1.0, 2.0];
    /// ax.contour(&z, 3, 3);
    /// let limits = ax.data_limits().expect("contour provides data limits");
    /// // The grid spans x in [0, 2], y in [0, 2].
    /// assert_eq!((limits.xmin(), limits.xmax()), (0.0, 2.0));
    /// assert_eq!((limits.ymin(), limits.ymax()), (0.0, 2.0));
    /// ```
    pub fn contour(&mut self, z: &[f64], nrows: usize, ncols: usize) {
        self.contour_levels(z, nrows, ncols, DEFAULT_N_LEVELS);
    }

    /// Draw `n_levels` line contours of row-major scalar `z` (`nrows x ncols`).
    ///
    /// The grid corners sit at integer coordinates (`x = 0..ncols-1`,
    /// `y = 0..nrows-1`). The `n_levels` contour levels are evenly spaced
    /// strictly between the finite data minimum `zmin` and maximum `zmax`
    /// (level `k` is `zmin + (k + 1) / (n_levels + 1) * (zmax - zmin)`). For
    /// each level the standard 16-case marching-squares algorithm runs over
    /// every `2 x 2` cell: corners are classified above/below the level, edge
    /// crossings are found by linear interpolation, and the crossings are
    /// connected into one or two segments. The two ambiguous saddle cases are
    /// resolved by comparing the cell's mean corner value against the level
    /// (the midpoint convention). Each segment becomes a two-point [`Line2D`]
    /// colored by its level via a [`LinearNorm`] over `[zmin, zmax]` and the
    /// default colormap, and the grid extent folds into
    /// [`data_limits`](Axes::data_limits).
    ///
    /// A grid smaller than `2 x 2`, a flat field (`zmin == zmax`), or
    /// `n_levels == 0` draws no contour lines but still records the grid extent.
    ///
    // TODO: LineCollection batching — emitting one Line2D per segment is
    // correctness-first; a contour LineCollection would cut artist overhead for
    // large grids.
    ///
    /// # Panics
    ///
    /// Panics if `z.len()` is not exactly `nrows * ncols`.
    ///
    /// # Examples
    ///
    /// ```
    /// use rizzma::core::Bbox;
    /// use rizzma::figure::Axes;
    ///
    /// let mut ax = Axes::new(Bbox::from_extents(0.0, 0.0, 1.0, 1.0));
    /// let z = [0.0, 1.0, 2.0, 0.0, 1.0, 2.0, 0.0, 1.0, 2.0];
    /// ax.contour_levels(&z, 3, 3, 3);
    /// assert!(ax.data_limits().is_some());
    /// ```
    pub fn contour_levels(&mut self, z: &[f64], nrows: usize, ncols: usize, n_levels: usize) {
        assert_eq!(
            z.len(),
            nrows * ncols,
            "contour: z length {} must equal nrows * ncols = {}",
            z.len(),
            nrows * ncols
        );

        self.contour_label_candidates.clear();

        // Record the grid extent so autoscaling fits it even when no contour
        // crosses (flat field, sub-2x2 grid, or zero levels).
        if ncols >= 1 && nrows >= 1 {
            self.include_data_bbox(0.0, 0.0, (ncols - 1) as f64, (nrows - 1) as f64);
            // Contours are flush with their grid, like matplotlib's.
            self.sticky_x.push(0.0);
            self.sticky_x.push((ncols - 1) as f64);
            self.sticky_y.push(0.0);
            self.sticky_y.push((nrows - 1) as f64);
        }

        let (zmin, zmax) = data_min_max(z);
        if zmax <= zmin || n_levels == 0 {
            return;
        }

        let norm = LinearNorm::new(zmin, zmax);
        let cmap = default_colormap();
        let span = zmax - zmin;

        for k in 0..n_levels {
            let level = zmin + (k + 1) as f64 / (n_levels + 1) as f64 * span;
            let color = cmap.sample(norm.normalize(level));
            let segments = level_segments(z, nrows, ncols, level);
            let center = ((ncols - 1) as f64 / 2.0, (nrows - 1) as f64 / 2.0);
            let label_segment = segments
                .iter()
                .enumerate()
                .min_by(|(_, a), (_, b)| {
                    let distance = |segment: &&[[f64; 2]; 2]| {
                        let x = (segment[0][0] + segment[1][0]) / 2.0;
                        let y = (segment[0][1] + segment[1][1]) / 2.0;
                        (x - center.0).hypot(y - center.1)
                    };
                    distance(a).total_cmp(&distance(b))
                })
                .map(|(index, _)| index);
            for (segment_index, [p0, p1]) in segments.into_iter().enumerate() {
                let line_index = self.lines.len();
                self.add_line(
                    Line2D::new(vec![p0[0], p1[0]], vec![p0[1], p1[1]]).with_color(color),
                );
                if Some(segment_index) == label_segment {
                    self.contour_label_candidates.push(ContourLabelCandidate {
                        line_index,
                        position: ((p0[0] + p1[0]) / 2.0, (p0[1] + p1[1]) / 2.0),
                        level,
                        color,
                    });
                }
            }
        }
    }

    /// Label every level in the most recently drawn line contour set.
    ///
    /// One short contour segment is removed beneath each label, creating the
    /// same inline break used by matplotlib. Call this immediately after
    /// [`contour`](Axes::contour), [`contour_levels`](Axes::contour_levels),
    /// [`tricontour`](Axes::tricontour), or
    /// [`tricontour_levels`](Axes::tricontour_levels).
    ///
    /// ![contour labels](https://raw.githubusercontent.com/OrbitalCommons/rizzma/gh-pages/gallery_contour.png)
    ///
    /// ```no_run
    /// use rizzma::Figure;
    /// let mut fig = Figure::new(4.0, 3.0);
    /// let z = [0.0, 1.0, 2.0, 0.0, 1.0, 2.0, 0.0, 1.0, 2.0];
    /// let ax = fig.add_subplot(1, 1, 1);
    /// ax.contour(&z, 3, 3);
    /// ax.clabel();
    /// fig.save_png("contour_labels.png")?;
    /// # Ok::<(), Box<dyn std::error::Error>>(())
    /// ```
    pub fn clabel(&mut self) -> &mut Self {
        let mut candidates = std::mem::take(&mut self.contour_label_candidates);
        candidates.sort_by_key(|candidate| std::cmp::Reverse(candidate.line_index));
        for candidate in candidates {
            if candidate.line_index < self.lines.len() {
                self.lines.remove(candidate.line_index);
            }
            self.add_contour_label(
                format_contour_level(candidate.level),
                candidate.position,
                candidate.color,
            );
        }
        self
    }
}

fn format_contour_level(level: f64) -> String {
    let mut label = format!("{level:.3}");
    while label.contains('.') && label.ends_with('0') {
        label.pop();
    }
    if label.ends_with('.') {
        label.pop();
    }
    label
}

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

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

    #[test]
    fn ramp_field_produces_vertical_contours_at_expected_x() {
        // z = x: a 3-column, 3-row ramp. One level at x where z == level.
        let z = [0.0, 1.0, 2.0, 0.0, 1.0, 2.0, 0.0, 1.0, 2.0];
        // Level 1.0 sits at x = 1.0; level 1.5 sits at x = 1.5.
        for level in [1.0, 1.5] {
            let segs = level_segments(&z, 3, 3, level);
            assert!(!segs.is_empty(), "level {level} should cross the field");
            for seg in &segs {
                // Each crossing point lands on the expected vertical line x=level.
                approx(seg[0][0], level);
                approx(seg[1][0], level);
            }
        }
    }

    #[test]
    fn single_corner_above_yields_one_segment() {
        // Only the top-left corner exceeds the level → exactly one segment.
        let z = [2.0, 0.0, 0.0, 0.0];
        let segs = level_segments(&z, 2, 2, 1.0);
        assert_eq!(segs.len(), 1);
        // It cuts the top-left corner: a left-edge point to a top-edge point.
        let [a, b] = segs[0];
        // Both crossings are at the midpoint of their edges (linear interp of 2→0).
        approx(a[0], 0.0);
        approx(a[1], 0.5);
        approx(b[0], 0.5);
        approx(b[1], 0.0);
    }

    #[test]
    fn flat_field_draws_no_lines_but_records_limits() {
        let mut ax = Axes::new(Bbox::from_extents(0.0, 0.0, 1.0, 1.0));
        ax.contour(&[3.0, 3.0, 3.0, 3.0], 2, 2);
        assert!(ax.lines.is_empty());
        let e = ax.data_limits().expect("grid extent is recorded");
        approx(e.xmin(), 0.0);
        approx(e.xmax(), 1.0);
        approx(e.ymin(), 0.0);
        approx(e.ymax(), 1.0);
    }

    #[test]
    fn data_limits_cover_the_grid() {
        let mut ax = Axes::new(Bbox::from_extents(0.0, 0.0, 1.0, 1.0));
        // 4-row, 5-column ramp; the grid spans x in [0, 4], y in [0, 3].
        let (nr, nc) = (4usize, 5usize);
        let z: Vec<f64> = (0..nr * nc).map(|i| (i % nc) as f64).collect();
        ax.contour(&z, nr, nc);
        let e = ax.data_limits().expect("contour records data limits");
        approx(e.xmin(), 0.0);
        approx(e.xmax(), (nc - 1) as f64);
        approx(e.ymin(), 0.0);
        approx(e.ymax(), (nr - 1) as f64);
    }

    #[test]
    fn default_contour_uses_seven_levels() {
        // A ramp where every level crosses every row band exactly once.
        let mut ax = Axes::new(Bbox::from_extents(0.0, 0.0, 1.0, 1.0));
        // 2 rows, 9 columns: z = x in 0..8. The 7 default levels are
        // 1,2,...,7, each crossing the single row band once.
        let z: Vec<f64> = (0..2 * 9).map(|i| (i % 9) as f64).collect();
        ax.contour(&z, 2, 9);
        // 7 levels x 1 crossing each = 7 line segments.
        assert_eq!(ax.lines.len(), 7);
    }

    #[test]
    fn clabel_adds_one_label_and_break_per_level() {
        let mut ax = Axes::new(Bbox::unit());
        let z: Vec<f64> = (0..2 * 9).map(|i| (i % 9) as f64).collect();
        ax.contour_levels(&z, 2, 9, 3);
        let lines_before = ax.lines.len();
        assert_eq!(ax.contour_label_candidates.len(), 3);

        ax.clabel();
        assert_eq!(ax.lines.len(), lines_before - 3);
        assert_eq!(ax.annotation_count(), 3);
        assert!(ax.contour_label_candidates.is_empty());
    }

    #[test]
    fn contour_level_format_is_compact() {
        assert_eq!(format_contour_level(1.0), "1");
        assert_eq!(format_contour_level(1.25), "1.25");
    }
}