crisol-plot-core 1.8.0

Crisol plot core: the egui-free math behind the plot, axis ticks, analysis, filters, and decimation.
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
//! A declarative, serializable chart description shared by Rust, the host spec,
//! Python, and wasm.
//!
//! [`PlotSpec`] is deliberately independent of egui: the same value drives the desktop
//! plot, the headless renderer, and every binding. The `version` field freezes the
//! meaning of the rest; new optional fields are additive.

use crisol_core::color::Rgba;

use crate::axis::Scale;
use crate::transform::YAxis;

/// The current [`PlotSpec`] version.
pub const PLOT_SPEC_VERSION: u32 = 1;

/// A complete chart as data.
///
/// ```
/// use crisol_plot_core::spec::{PlotSpec, SeriesKind, SeriesSpec};
///
/// let spec = PlotSpec::new(640, 360)
///     .title("Signal")
///     .series(SeriesSpec::line("v", vec![[0.0, 1.0], [1.0, 2.0]]));
/// assert_eq!(spec.series[0].kind, SeriesKind::Line);
/// ```
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default, rename_all = "snake_case"))]
#[derive(Clone, Debug, PartialEq)]
pub struct PlotSpec {
    /// The schema version; [`PLOT_SPEC_VERSION`] for new charts.
    pub version: u32,
    /// Chart title.
    pub title: Option<String>,
    /// Horizontal axis title.
    pub x_label: Option<String>,
    /// Left vertical axis title.
    pub y_label: Option<String>,
    /// Image width in pixels.
    pub width: u32,
    /// Image height in pixels.
    pub height: u32,
    /// Horizontal scale.
    pub x_scale: Scale,
    /// Left vertical scale.
    pub y_scale: Scale,
    /// Fixed x range in data units; automatic when `None`.
    pub x_range: Option<[f64; 2]>,
    /// Fixed y range in data units; automatic when `None`.
    pub y_range: Option<[f64; 2]>,
    /// The series, drawn in order.
    pub series: Vec<SeriesSpec>,
    /// Draw the legend.
    pub legend: bool,
    /// Draw major grid lines.
    pub grid: bool,
    /// Canvas and text colors; the renderer defaults when `None`.
    pub theme: Option<PlotTheme>,
}

impl Default for PlotSpec {
    fn default() -> Self {
        Self {
            version: PLOT_SPEC_VERSION,
            title: None,
            x_label: None,
            y_label: None,
            width: 900,
            height: 600,
            x_scale: Scale::Linear,
            y_scale: Scale::Linear,
            x_range: None,
            y_range: None,
            series: Vec::new(),
            legend: true,
            grid: true,
            theme: None,
        }
    }
}

impl PlotSpec {
    /// An empty specification at `width × height`.
    pub fn new(width: u32, height: u32) -> Self {
        Self {
            width,
            height,
            ..Self::default()
        }
    }

    /// Set the title.
    pub fn title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Set the horizontal axis title.
    pub fn x_label(mut self, label: impl Into<String>) -> Self {
        self.x_label = Some(label.into());
        self
    }

    /// Set the left vertical axis title.
    pub fn y_label(mut self, label: impl Into<String>) -> Self {
        self.y_label = Some(label.into());
        self
    }

    /// Set both scales.
    pub fn scale(mut self, x: Scale, y: Scale) -> Self {
        self.x_scale = x;
        self.y_scale = y;
        self
    }

    /// Set both fixed ranges.
    pub fn range(mut self, x: [f64; 2], y: [f64; 2]) -> Self {
        self.x_range = Some(x);
        self.y_range = Some(y);
        self
    }

    /// Append a series.
    pub fn series(mut self, series: SeriesSpec) -> Self {
        self.series.push(series);
        self
    }

    /// Set the size from a publication preset at `dpi`.
    pub fn preset(mut self, preset: PagePreset, dpi: u32) -> Self {
        let (width, height) = preset.pixels(dpi);
        self.width = width;
        self.height = height;
        self
    }

    /// Set the theme.
    pub fn theme(mut self, theme: PlotTheme) -> Self {
        self.theme = Some(theme);
        self
    }

    /// Validate the structural rules that serialization cannot express.
    ///
    /// # Errors
    /// When the size is zero, the version is newer than this crate, a range is
    /// reversed, or a series has no finite points.
    pub fn validate(&self) -> Result<(), SpecError> {
        if self.version > PLOT_SPEC_VERSION {
            return Err(SpecError::Version(self.version));
        }
        if self.width == 0 || self.height == 0 {
            return Err(SpecError::Size);
        }
        for range in [self.x_range, self.y_range].into_iter().flatten() {
            if !range[0].is_finite() || !range[1].is_finite() || range[1] <= range[0] {
                return Err(SpecError::Range(range));
            }
        }
        for series in &self.series {
            if series.points.is_empty() {
                return Err(SpecError::EmptySeries(series.name.clone()));
            }
            if !series.points.iter().flatten().all(|value| value.is_finite()) {
                return Err(SpecError::NonFinite(series.name.clone()));
            }
        }
        Ok(())
    }
}

/// A publication page preset.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum PagePreset {
    /// A single journal column, 3.5 × 2.5 in.
    #[default]
    SingleColumn,
    /// A double journal column, 7.16 × 4.5 in.
    DoubleColumn,
    /// US Letter, 8.5 × 11 in.
    Letter,
}

impl PagePreset {
    /// Width and height in inches.
    pub const fn inches(self) -> (f32, f32) {
        match self {
            Self::SingleColumn => (3.5, 2.5),
            Self::DoubleColumn => (7.16, 4.5),
            Self::Letter => (8.5, 11.0),
        }
    }

    /// Width and height in pixels at `dpi`.
    pub fn pixels(self, dpi: u32) -> (u32, u32) {
        let (width, height) = self.inches();
        (
            (width * dpi as f32).round() as u32,
            (height * dpi as f32).round() as u32,
        )
    }
}

/// One series in a [`PlotSpec`].
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default, rename_all = "snake_case"))]
#[derive(Clone, Debug, PartialEq)]
pub struct SeriesSpec {
    /// Legend name.
    pub name: String,
    /// How the points are drawn.
    pub kind: SeriesKind,
    /// x/y points in data units.
    pub points: Vec<[f64; 2]>,
    /// Stroke or fill color; the spec palette when `None`.
    pub color: Option<Rgba>,
    /// Stroke width in pixels.
    pub width: f32,
    /// Marker for scatter, or for vertices of a line.
    pub marker: Option<MarkerSpec>,
    /// Fill opacity for areas and bars, 0–1.
    pub fill_opacity: f32,
    /// Axis the series is measured on.
    pub y_axis: YAxis,
    /// Whether the series appears in the legend.
    pub legend: bool,
    /// Baseline for bars.
    pub baseline: f64,
    /// Fixed bar width in data units; automatic when `None`.
    pub bar_width: Option<f64>,
}

impl Default for SeriesSpec {
    fn default() -> Self {
        Self {
            name: String::new(),
            kind: SeriesKind::Line,
            points: Vec::new(),
            color: None,
            width: 1.5,
            marker: None,
            fill_opacity: 0.2,
            y_axis: YAxis::Left,
            legend: true,
            baseline: 0.0,
            bar_width: None,
        }
    }
}

impl SeriesSpec {
    /// A line series.
    pub fn line(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
        Self {
            name: name.into(),
            points,
            ..Self::default()
        }
    }

    /// A scatter series.
    pub fn scatter(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
        Self {
            name: name.into(),
            kind: SeriesKind::Scatter,
            marker: Some(MarkerSpec::Circle),
            points,
            ..Self::default()
        }
    }

    /// A filled area down to `baseline`.
    pub fn area(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
        Self {
            name: name.into(),
            kind: SeriesKind::Area,
            points,
            ..Self::default()
        }
    }

    /// A staircase series.
    pub fn step(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
        Self {
            name: name.into(),
            kind: SeriesKind::Step,
            points,
            ..Self::default()
        }
    }

    /// A bar series.
    pub fn bars(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
        Self {
            name: name.into(),
            kind: SeriesKind::Bars,
            points,
            ..Self::default()
        }
    }

    /// Set the color.
    pub fn color(mut self, color: Rgba) -> Self {
        self.color = Some(color);
        self
    }

    /// Set the stroke width.
    pub fn width(mut self, width: f32) -> Self {
        self.width = width;
        self
    }

    /// Set the marker.
    pub fn marker(mut self, marker: MarkerSpec) -> Self {
        self.marker = Some(marker);
        self
    }
}

/// How a [`SeriesSpec`] is drawn.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum SeriesKind {
    /// A polyline.
    #[default]
    Line,
    /// Unconnected markers.
    Scatter,
    /// A polygon down to the baseline.
    Area,
    /// A staircase that holds each value until the next x.
    Step,
    /// Vertical bars from the baseline.
    Bars,
}

/// A marker shape.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum MarkerSpec {
    /// Filled circle.
    #[default]
    Circle,
    /// Filled square.
    Square,
    /// Filled diamond.
    Diamond,
    /// Filled upward triangle.
    Triangle,
    /// Diagonal cross.
    Cross,
    /// Plus sign.
    Plus,
    /// Circle outline.
    Ring,
}

/// Theme colors for a headless chart.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default))]
#[derive(Clone, Debug, PartialEq)]
pub struct PlotTheme {
    /// Canvas fill.
    pub background: Rgba,
    /// Plot area fill inside the axes.
    pub plot_background: Rgba,
    /// Title and label color.
    pub text: Rgba,
    /// Axis and frame color.
    pub axis: Rgba,
    /// Grid color.
    pub grid: Rgba,
    /// Series palette, used when a series has no color.
    pub palette: Vec<Rgba>,
}

impl Default for PlotTheme {
    fn default() -> Self {
        Self {
            background: Rgba::WHITE,
            plot_background: Rgba::WHITE,
            text: Rgba::from_rgb(0x1f, 0x23, 0x28),
            axis: Rgba::from_rgb(0x6a, 0x73, 0x7d),
            grid: Rgba::from_rgb(0xe1, 0xe4, 0xe8),
            palette: vec![
                Rgba::from_rgb(0x1f, 0x77, 0xb4),
                Rgba::from_rgb(0xff, 0x7f, 0x0e),
                Rgba::from_rgb(0x2c, 0xa0, 0x2c),
                Rgba::from_rgb(0xd6, 0x27, 0x28),
                Rgba::from_rgb(0x94, 0x67, 0xbd),
                Rgba::from_rgb(0x8c, 0x56, 0x4b),
            ],
        }
    }
}

impl PlotTheme {
    /// The color for series `index`, wrapping around the palette.
    pub fn series_color(&self, index: usize) -> Rgba {
        if self.palette.is_empty() {
            Rgba::BLACK
        } else {
            self.palette[index % self.palette.len()]
        }
    }
}

/// Why a [`PlotSpec`] is invalid.
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum SpecError {
    /// The spec was written for a newer version.
    Version(u32),
    /// Width or height is zero.
    Size,
    /// A fixed range is reversed or non-finite.
    Range([f64; 2]),
    /// A series has no points.
    EmptySeries(String),
    /// A series has a non-finite coordinate.
    NonFinite(String),
}

impl std::fmt::Display for SpecError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Version(version) => write!(
                formatter,
                "plot spec version {version} is newer than {PLOT_SPEC_VERSION}"
            ),
            Self::Size => write!(formatter, "plot width and height must be positive"),
            Self::Range(range) => write!(formatter, "invalid range {range:?}"),
            Self::EmptySeries(name) => write!(formatter, "series `{name}` has no points"),
            Self::NonFinite(name) => write!(formatter, "series `{name}` has a non-finite point"),
        }
    }
}

impl std::error::Error for SpecError {}

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

    #[test]
    fn a_minimal_spec_is_valid() {
        let spec = PlotSpec::new(320, 200).series(SeriesSpec::line("v", vec![[0.0, 1.0], [1.0, 2.0]]));
        assert_eq!(spec.validate(), Ok(()));
        assert_eq!(spec.version, PLOT_SPEC_VERSION);
    }

    #[test]
    fn invalid_specs_are_rejected() {
        let mut spec = PlotSpec::new(0, 200);
        assert_eq!(spec.validate(), Err(SpecError::Size));
        spec.width = 200;
        spec.x_range = Some([2.0, 1.0]);
        assert!(matches!(spec.validate(), Err(SpecError::Range(_))));
        spec.x_range = None;
        spec.series.push(SeriesSpec::default());
        assert!(matches!(spec.validate(), Err(SpecError::EmptySeries(_))));
    }

    #[test]
    fn page_presets_scale_with_dpi() {
        assert_eq!(PagePreset::SingleColumn.pixels(300), (1050, 750));
        assert_eq!(PagePreset::DoubleColumn.pixels(300), (2148, 1350));
        assert_eq!(PlotSpec::new(1, 1).preset(PagePreset::Letter, 72).width, 612);
    }

    #[test]
    fn the_palette_wraps() {
        let theme = PlotTheme::default();
        assert_eq!(theme.series_color(0), theme.palette[0]);
        assert_eq!(theme.series_color(theme.palette.len()), theme.palette[0]);
    }

    #[cfg(feature = "serde")]
    #[test]
    fn a_spec_round_trips_through_json() {
        let spec = PlotSpec::new(640, 360)
            .title("Signal")
            .series(SeriesSpec::scatter("s", vec![[0.0, 1.0], [1.0, 2.0]]));
        let json = serde_json::to_string(&spec).expect("serialize");
        let restored: PlotSpec = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(restored, spec);
    }
}