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
//! Axis scales: mappings from data coordinates to scaled (display) coordinates.
//!
//! Each [`Scale`] provides a forward [`Scale::transform`] and its
//! [`Scale::inverse`], plus an optional [`Scale::limit_range_for_scale`] hook
//! that clamps an axis range to the domain supported by the scale (mirroring
//! matplotlib's behaviour for log/logit scales).
//!
//! Ported from matplotlib's `lib/matplotlib/scale.py`.

use crate::portable::PortableScale;
use crate::portable::spec::ScaleWire;

/// A separable transformation acting on a single axis dimension.
///
/// Implementations map data coordinates to scaled coordinates via
/// [`transform`](Scale::transform) and back via [`inverse`](Scale::inverse).
/// The two functions must round-trip over the scale's valid domain.
pub trait Scale: Send + Sync {
    /// Map a data coordinate to a scaled (display) coordinate.
    fn transform(&self, x: f64) -> f64;

    /// Map a scaled coordinate back to a data coordinate.
    ///
    /// This is the inverse of [`transform`](Scale::transform).
    fn inverse(&self, x: f64) -> f64;

    /// Restrict `(vmin, vmax)` to the domain supported by this scale.
    ///
    /// `minpos` is the smallest positive value in the data, used by scales
    /// (such as log) whose domain excludes non-positive numbers. The default
    /// implementation imposes no restriction.
    fn limit_range_for_scale(&self, vmin: f64, vmax: f64, _minpos: f64) -> (f64, f64) {
        (vmin, vmax)
    }

    /// The closed wire form of this scale for portable-figure export, or
    /// `None` when the scale has no wire representation (in which case export
    /// fails loudly rather than substitute a different scale).
    ///
    /// Only rizzma's built-in scales can construct a [`PortableScale`], so
    /// the default — correct for any third-party implementation — is `None`.
    fn portable_spec(&self) -> Option<PortableScale> {
        None
    }
}

/// The default linear scale: an identity transform.
#[derive(Debug, Clone, Copy, Default)]
pub struct LinearScale;

impl LinearScale {
    /// Construct a new linear scale.
    pub fn new() -> Self {
        LinearScale
    }
}

impl Scale for LinearScale {
    fn transform(&self, x: f64) -> f64 {
        x
    }

    fn inverse(&self, x: f64) -> f64 {
        x
    }

    fn portable_spec(&self) -> Option<PortableScale> {
        Some(PortableScale(ScaleWire::Linear))
    }
}

/// A standard logarithmic scale.
///
/// The transform is `log(x) / log(base)`; the domain is `x > 0`. For the
/// common bases 10 and 2 the dedicated [`f64::log10`]/[`f64::log2`] (and
/// `powi`-free) routines are used to avoid the floating-point error that
/// `log(x) / log(base)` would otherwise introduce.
#[derive(Debug, Clone, Copy)]
pub struct LogScale {
    /// The base of the logarithm. Must be `> 0` and `!= 1`.
    pub base: f64,
}

impl LogScale {
    /// Construct a logarithmic scale with the given `base`.
    pub fn new(base: f64) -> Self {
        LogScale { base }
    }
}

impl Scale for LogScale {
    fn portable_spec(&self) -> Option<PortableScale> {
        Some(PortableScale(ScaleWire::Log { base: self.base }))
    }

    fn transform(&self, x: f64) -> f64 {
        if self.base == 10.0 {
            x.log10()
        } else if self.base == 2.0 {
            x.log2()
        } else {
            x.ln() / self.base.ln()
        }
    }

    fn inverse(&self, x: f64) -> f64 {
        if self.base == 2.0 {
            x.exp2()
        } else {
            (x * self.base.ln()).exp()
        }
    }

    /// Clamp the domain to positive values, replacing non-positive bounds with
    /// `minpos` (a tiny positive fallback when `minpos` is not finite).
    fn limit_range_for_scale(&self, vmin: f64, vmax: f64, minpos: f64) -> (f64, f64) {
        let minpos = if minpos.is_finite() { minpos } else { 1e-300 };
        (
            if vmin <= 0.0 { minpos } else { vmin },
            if vmax <= 0.0 { minpos } else { vmax },
        )
    }
}

/// The symmetrical logarithmic ("symlog") scale.
///
/// The scale is linear within `[-linthresh, linthresh]` and logarithmic
/// beyond it, joining continuously at `±linthresh`. The `linscale` parameter
/// stretches the linear region relative to the logarithmic range; internally
/// it is applied as `linscale_adj = linscale / (1 - 1/base)`.
#[derive(Debug, Clone, Copy)]
pub struct SymlogScale {
    /// The base of the logarithm. Must be `> 1`.
    pub base: f64,
    /// Half-width of the linear region around zero. Must be `> 0`.
    pub linthresh: f64,
    /// Stretch factor for the linear region. Must be `> 0`.
    pub linscale: f64,
}

impl SymlogScale {
    /// Construct a symlog scale with the given `base`, `linthresh`, and
    /// `linscale`.
    pub fn new(base: f64, linthresh: f64, linscale: f64) -> Self {
        SymlogScale {
            base,
            linthresh,
            linscale,
        }
    }

    /// The adjusted linear-scale factor, `linscale / (1 - 1/base)`.
    fn linscale_adj(&self) -> f64 {
        self.linscale / (1.0 - 1.0 / self.base)
    }
}

impl Scale for SymlogScale {
    fn portable_spec(&self) -> Option<PortableScale> {
        Some(PortableScale(ScaleWire::Symlog {
            base: self.base,
            linthresh: self.linthresh,
            linscale: self.linscale,
        }))
    }

    fn transform(&self, x: f64) -> f64 {
        let linscale_adj = self.linscale_adj();
        let abs_x = x.abs();
        if abs_x <= self.linthresh {
            x * linscale_adj
        } else {
            let log_base = self.base.ln();
            x.signum()
                * self.linthresh
                * (linscale_adj - self.linthresh.ln() / log_base + abs_x.ln() / log_base)
        }
    }

    fn inverse(&self, x: f64) -> f64 {
        let linscale_adj = self.linscale_adj();
        // The scaled coordinate of `linthresh` under the forward transform.
        let invlinthresh = self.linthresh * linscale_adj;
        let abs_x = x.abs();
        if abs_x <= invlinthresh {
            x / linscale_adj
        } else {
            x.signum()
                * self.linthresh
                * ((abs_x / self.linthresh - linscale_adj) * self.base.ln()).exp()
        }
    }
}

/// The inverse-hyperbolic-sine scale.
///
/// The transform is `asinh(x / linear_width)`, which is approximately linear
/// around zero and logarithmic in both tails. Unlike [`LogScale`] and
/// [`LogitScale`], the asinh scale accepts the entire real line.
#[derive(Debug, Clone, Copy)]
pub struct AsinhScale {
    /// Width of the quasi-linear region around zero. Must be finite and
    /// positive.
    pub linear_width: f64,
}

impl AsinhScale {
    /// Construct an asinh scale with the given positive linear-region width.
    pub fn new(linear_width: f64) -> Self {
        assert!(
            linear_width.is_finite() && linear_width > 0.0,
            "asinh scale linear_width must be finite and > 0"
        );
        AsinhScale { linear_width }
    }
}

impl Default for AsinhScale {
    /// Default to a unit-width linear region.
    fn default() -> Self {
        Self::new(1.0)
    }
}

impl Scale for AsinhScale {
    fn transform(&self, x: f64) -> f64 {
        (x / self.linear_width).asinh()
    }

    fn inverse(&self, x: f64) -> f64 {
        self.linear_width * x.sinh()
    }

    fn portable_spec(&self) -> Option<PortableScale> {
        Some(PortableScale(ScaleWire::Asinh {
            linear_width: self.linear_width,
        }))
    }
}

/// The logit scale for probabilities in the open interval `(0, 1)`.
///
/// The transform is `log(x / (1 - x))`, mapping `(0, 1)` onto the whole real
/// line; the inverse is the logistic function `1 / (1 + exp(-y))`.
#[derive(Debug, Clone, Copy, Default)]
pub struct LogitScale;

impl LogitScale {
    /// Construct a new logit scale.
    pub fn new() -> Self {
        LogitScale
    }
}

impl Scale for LogitScale {
    fn portable_spec(&self) -> Option<PortableScale> {
        Some(PortableScale(ScaleWire::Logit))
    }

    fn transform(&self, x: f64) -> f64 {
        (x / (1.0 - x)).ln()
    }

    fn inverse(&self, x: f64) -> f64 {
        1.0 / (1.0 + (-x).exp())
    }

    /// Clamp the domain to `(minpos, 1 - minpos)`, using a tiny positive
    /// fallback when `minpos` is not finite.
    fn limit_range_for_scale(&self, vmin: f64, vmax: f64, minpos: f64) -> (f64, f64) {
        let minpos = if minpos.is_finite() { minpos } else { 1e-7 };
        (
            if vmin <= 0.0 { minpos } else { vmin },
            if vmax >= 1.0 { 1.0 - minpos } else { vmax },
        )
    }
}

#[cfg(feature = "portable")]
impl ScaleWire {
    /// Reconstruct the boxed [`Scale`] this wire form describes.
    pub(crate) fn into_scale(self) -> Box<dyn Scale> {
        match self {
            ScaleWire::Linear => Box::new(LinearScale::new()),
            ScaleWire::Log { base } => Box::new(LogScale::new(base)),
            ScaleWire::Symlog {
                base,
                linthresh,
                linscale,
            } => Box::new(SymlogScale::new(base, linthresh, linscale)),
            ScaleWire::Logit => Box::new(LogitScale::new()),
            ScaleWire::Asinh { linear_width } => Box::new(AsinhScale::new(linear_width)),
        }
    }
}

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

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

    #[test]
    fn linear_is_identity() {
        let s = LinearScale::new();
        for &x in &[-3.5, 0.0, 1.0, 42.0] {
            approx(s.transform(x), x);
            approx(s.inverse(x), x);
        }
    }

    #[test]
    fn log10_maps_powers() {
        let s = LogScale::new(10.0);
        approx(s.transform(1.0), 0.0);
        approx(s.transform(10.0), 1.0);
        approx(s.transform(100.0), 2.0);
        for &x in &[0.5, 1.0, 10.0, 12345.0] {
            approx(s.inverse(s.transform(x)), x);
        }
    }

    #[test]
    fn log2_maps_eight() {
        let s = LogScale::new(2.0);
        approx(s.transform(8.0), 3.0);
        approx(s.inverse(3.0), 8.0);
    }

    #[test]
    fn log_arbitrary_base_round_trips() {
        let s = LogScale::new(7.0);
        for &x in &[0.1, 1.0, 7.0, 49.0, 1000.0] {
            approx(s.inverse(s.transform(x)), x);
        }
    }

    #[test]
    fn log_limit_clamps_nonpositive() {
        let s = LogScale::new(10.0);
        let (lo, hi) = s.limit_range_for_scale(-5.0, 0.0, 1e-3);
        approx(lo, 1e-3);
        approx(hi, 1e-3);
        let (lo, hi) = s.limit_range_for_scale(2.0, 50.0, 1e-3);
        approx(lo, 2.0);
        approx(hi, 50.0);
    }

    #[test]
    fn symlog_continuous_at_linthresh() {
        let s = SymlogScale::new(10.0, 2.0, 1.0);
        let eps = 1e-7;
        let below = s.transform(s.linthresh - eps);
        let above = s.transform(s.linthresh + eps);
        assert!(
            (below - above).abs() < 1e-5,
            "discontinuity: {below} vs {above}"
        );
    }

    #[test]
    fn symlog_round_trips() {
        let s = SymlogScale::new(10.0, 2.0, 1.0);
        for &x in &[-1000.0, -50.0, -2.0, -0.3, 0.0, 0.1, 2.0, 37.0, 5000.0] {
            approx(s.inverse(s.transform(x)), x);
        }
    }

    #[test]
    fn symlog_round_trips_other_params() {
        let s = SymlogScale::new(2.0, 0.5, 2.0);
        for &x in &[-100.0, -0.5, -0.01, 0.0, 0.01, 0.5, 8.0, 64.0] {
            approx(s.inverse(s.transform(x)), x);
        }
    }

    #[test]
    fn asinh_maps_zero_and_is_odd() {
        let s = AsinhScale::new(2.0);

        approx(s.transform(0.0), 0.0);
        approx(s.inverse(0.0), 0.0);
        approx(s.transform(-10.0), -s.transform(10.0));
        approx(s.inverse(-2.0), -s.inverse(2.0));
    }

    #[test]
    fn asinh_is_linear_near_zero() {
        let s = AsinhScale::new(4.0);

        let x = 1e-6;
        assert!((s.transform(x) - x / s.linear_width).abs() < 1e-18);
    }

    #[test]
    fn asinh_has_logarithmic_tails() {
        let s = AsinhScale::new(2.0);

        let x = 1e12;
        let expected = (2.0 * x / s.linear_width).ln();
        assert!((s.transform(x) - expected).abs() < 1e-10);
    }

    #[test]
    fn asinh_round_trips_whole_real_line() {
        let s = AsinhScale::new(0.5);
        for &x in &[-1e6, -10.0, -0.1, 0.0, 0.1, 10.0, 1e6] {
            approx(s.inverse(s.transform(x)), x);
        }
    }

    #[test]
    fn logit_maps_half_and_round_trips() {
        let s = LogitScale::new();
        approx(s.transform(0.5), 0.0);
        for &x in &[0.01, 0.25, 0.5, 0.75, 0.99] {
            approx(s.inverse(s.transform(x)), x);
        }
    }

    #[test]
    fn logit_limit_clamps() {
        let s = LogitScale::new();
        let (lo, hi) = s.limit_range_for_scale(0.0, 1.0, 1e-7);
        approx(lo, 1e-7);
        approx(hi, 1.0 - 1e-7);
    }
}