Skip to main content

crisol_plot_core/
spec.rs

1//! A declarative, serializable chart description shared by Rust, the host spec,
2//! Python, and wasm.
3//!
4//! [`PlotSpec`] is deliberately independent of egui: the same value drives the desktop
5//! plot, the headless renderer, and every binding. The `version` field freezes the
6//! meaning of the rest; new optional fields are additive.
7
8use crisol_core::color::Rgba;
9
10use crate::axis::Scale;
11use crate::transform::YAxis;
12
13/// The current [`PlotSpec`] version.
14pub const PLOT_SPEC_VERSION: u32 = 1;
15
16/// A complete chart as data.
17///
18/// ```
19/// use crisol_plot_core::spec::{PlotSpec, SeriesKind, SeriesSpec};
20///
21/// let spec = PlotSpec::new(640, 360)
22///     .title("Signal")
23///     .series(SeriesSpec::line("v", vec![[0.0, 1.0], [1.0, 2.0]]));
24/// assert_eq!(spec.series[0].kind, SeriesKind::Line);
25/// ```
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27#[cfg_attr(feature = "serde", serde(default, rename_all = "snake_case"))]
28#[derive(Clone, Debug, PartialEq)]
29pub struct PlotSpec {
30    /// The schema version; [`PLOT_SPEC_VERSION`] for new charts.
31    pub version: u32,
32    /// Chart title.
33    pub title: Option<String>,
34    /// Horizontal axis title.
35    pub x_label: Option<String>,
36    /// Left vertical axis title.
37    pub y_label: Option<String>,
38    /// Image width in pixels.
39    pub width: u32,
40    /// Image height in pixels.
41    pub height: u32,
42    /// Horizontal scale.
43    pub x_scale: Scale,
44    /// Left vertical scale.
45    pub y_scale: Scale,
46    /// Fixed x range in data units; automatic when `None`.
47    pub x_range: Option<[f64; 2]>,
48    /// Fixed y range in data units; automatic when `None`.
49    pub y_range: Option<[f64; 2]>,
50    /// The series, drawn in order.
51    pub series: Vec<SeriesSpec>,
52    /// Draw the legend.
53    pub legend: bool,
54    /// Draw major grid lines.
55    pub grid: bool,
56    /// Canvas and text colors; the renderer defaults when `None`.
57    pub theme: Option<PlotTheme>,
58}
59
60impl Default for PlotSpec {
61    fn default() -> Self {
62        Self {
63            version: PLOT_SPEC_VERSION,
64            title: None,
65            x_label: None,
66            y_label: None,
67            width: 900,
68            height: 600,
69            x_scale: Scale::Linear,
70            y_scale: Scale::Linear,
71            x_range: None,
72            y_range: None,
73            series: Vec::new(),
74            legend: true,
75            grid: true,
76            theme: None,
77        }
78    }
79}
80
81impl PlotSpec {
82    /// An empty specification at `width × height`.
83    pub fn new(width: u32, height: u32) -> Self {
84        Self {
85            width,
86            height,
87            ..Self::default()
88        }
89    }
90
91    /// Set the title.
92    pub fn title(mut self, title: impl Into<String>) -> Self {
93        self.title = Some(title.into());
94        self
95    }
96
97    /// Set the horizontal axis title.
98    pub fn x_label(mut self, label: impl Into<String>) -> Self {
99        self.x_label = Some(label.into());
100        self
101    }
102
103    /// Set the left vertical axis title.
104    pub fn y_label(mut self, label: impl Into<String>) -> Self {
105        self.y_label = Some(label.into());
106        self
107    }
108
109    /// Set both scales.
110    pub fn scale(mut self, x: Scale, y: Scale) -> Self {
111        self.x_scale = x;
112        self.y_scale = y;
113        self
114    }
115
116    /// Set both fixed ranges.
117    pub fn range(mut self, x: [f64; 2], y: [f64; 2]) -> Self {
118        self.x_range = Some(x);
119        self.y_range = Some(y);
120        self
121    }
122
123    /// Append a series.
124    pub fn series(mut self, series: SeriesSpec) -> Self {
125        self.series.push(series);
126        self
127    }
128
129    /// Set the size from a publication preset at `dpi`.
130    pub fn preset(mut self, preset: PagePreset, dpi: u32) -> Self {
131        let (width, height) = preset.pixels(dpi);
132        self.width = width;
133        self.height = height;
134        self
135    }
136
137    /// Set the theme.
138    pub fn theme(mut self, theme: PlotTheme) -> Self {
139        self.theme = Some(theme);
140        self
141    }
142
143    /// Validate the structural rules that serialization cannot express.
144    ///
145    /// # Errors
146    /// When the size is zero, the version is newer than this crate, a range is
147    /// reversed, or a series has no finite points.
148    pub fn validate(&self) -> Result<(), SpecError> {
149        if self.version > PLOT_SPEC_VERSION {
150            return Err(SpecError::Version(self.version));
151        }
152        if self.width == 0 || self.height == 0 {
153            return Err(SpecError::Size);
154        }
155        for range in [self.x_range, self.y_range].into_iter().flatten() {
156            if !range[0].is_finite() || !range[1].is_finite() || range[1] <= range[0] {
157                return Err(SpecError::Range(range));
158            }
159        }
160        for series in &self.series {
161            if series.points.is_empty() {
162                return Err(SpecError::EmptySeries(series.name.clone()));
163            }
164            if !series.points.iter().flatten().all(|value| value.is_finite()) {
165                return Err(SpecError::NonFinite(series.name.clone()));
166            }
167        }
168        Ok(())
169    }
170}
171
172/// A publication page preset.
173#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
174#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
175#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
176#[non_exhaustive]
177pub enum PagePreset {
178    /// A single journal column, 3.5 × 2.5 in.
179    #[default]
180    SingleColumn,
181    /// A double journal column, 7.16 × 4.5 in.
182    DoubleColumn,
183    /// US Letter, 8.5 × 11 in.
184    Letter,
185}
186
187impl PagePreset {
188    /// Width and height in inches.
189    pub const fn inches(self) -> (f32, f32) {
190        match self {
191            Self::SingleColumn => (3.5, 2.5),
192            Self::DoubleColumn => (7.16, 4.5),
193            Self::Letter => (8.5, 11.0),
194        }
195    }
196
197    /// Width and height in pixels at `dpi`.
198    pub fn pixels(self, dpi: u32) -> (u32, u32) {
199        let (width, height) = self.inches();
200        (
201            (width * dpi as f32).round() as u32,
202            (height * dpi as f32).round() as u32,
203        )
204    }
205}
206
207/// One series in a [`PlotSpec`].
208#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
209#[cfg_attr(feature = "serde", serde(default, rename_all = "snake_case"))]
210#[derive(Clone, Debug, PartialEq)]
211pub struct SeriesSpec {
212    /// Legend name.
213    pub name: String,
214    /// How the points are drawn.
215    pub kind: SeriesKind,
216    /// x/y points in data units.
217    pub points: Vec<[f64; 2]>,
218    /// Stroke or fill color; the spec palette when `None`.
219    pub color: Option<Rgba>,
220    /// Stroke width in pixels.
221    pub width: f32,
222    /// Marker for scatter, or for vertices of a line.
223    pub marker: Option<MarkerSpec>,
224    /// Fill opacity for areas and bars, 0–1.
225    pub fill_opacity: f32,
226    /// Axis the series is measured on.
227    pub y_axis: YAxis,
228    /// Whether the series appears in the legend.
229    pub legend: bool,
230    /// Baseline for bars.
231    pub baseline: f64,
232    /// Fixed bar width in data units; automatic when `None`.
233    pub bar_width: Option<f64>,
234}
235
236impl Default for SeriesSpec {
237    fn default() -> Self {
238        Self {
239            name: String::new(),
240            kind: SeriesKind::Line,
241            points: Vec::new(),
242            color: None,
243            width: 1.5,
244            marker: None,
245            fill_opacity: 0.2,
246            y_axis: YAxis::Left,
247            legend: true,
248            baseline: 0.0,
249            bar_width: None,
250        }
251    }
252}
253
254impl SeriesSpec {
255    /// A line series.
256    pub fn line(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
257        Self {
258            name: name.into(),
259            points,
260            ..Self::default()
261        }
262    }
263
264    /// A scatter series.
265    pub fn scatter(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
266        Self {
267            name: name.into(),
268            kind: SeriesKind::Scatter,
269            marker: Some(MarkerSpec::Circle),
270            points,
271            ..Self::default()
272        }
273    }
274
275    /// A filled area down to `baseline`.
276    pub fn area(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
277        Self {
278            name: name.into(),
279            kind: SeriesKind::Area,
280            points,
281            ..Self::default()
282        }
283    }
284
285    /// A staircase series.
286    pub fn step(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
287        Self {
288            name: name.into(),
289            kind: SeriesKind::Step,
290            points,
291            ..Self::default()
292        }
293    }
294
295    /// A bar series.
296    pub fn bars(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
297        Self {
298            name: name.into(),
299            kind: SeriesKind::Bars,
300            points,
301            ..Self::default()
302        }
303    }
304
305    /// Set the color.
306    pub fn color(mut self, color: Rgba) -> Self {
307        self.color = Some(color);
308        self
309    }
310
311    /// Set the stroke width.
312    pub fn width(mut self, width: f32) -> Self {
313        self.width = width;
314        self
315    }
316
317    /// Set the marker.
318    pub fn marker(mut self, marker: MarkerSpec) -> Self {
319        self.marker = Some(marker);
320        self
321    }
322}
323
324/// How a [`SeriesSpec`] is drawn.
325#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
326#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
327#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
328#[non_exhaustive]
329pub enum SeriesKind {
330    /// A polyline.
331    #[default]
332    Line,
333    /// Unconnected markers.
334    Scatter,
335    /// A polygon down to the baseline.
336    Area,
337    /// A staircase that holds each value until the next x.
338    Step,
339    /// Vertical bars from the baseline.
340    Bars,
341}
342
343/// A marker shape.
344#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
345#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
346#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
347#[non_exhaustive]
348pub enum MarkerSpec {
349    /// Filled circle.
350    #[default]
351    Circle,
352    /// Filled square.
353    Square,
354    /// Filled diamond.
355    Diamond,
356    /// Filled upward triangle.
357    Triangle,
358    /// Diagonal cross.
359    Cross,
360    /// Plus sign.
361    Plus,
362    /// Circle outline.
363    Ring,
364}
365
366/// Theme colors for a headless chart.
367#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
368#[cfg_attr(feature = "serde", serde(default))]
369#[derive(Clone, Debug, PartialEq)]
370pub struct PlotTheme {
371    /// Canvas fill.
372    pub background: Rgba,
373    /// Plot area fill inside the axes.
374    pub plot_background: Rgba,
375    /// Title and label color.
376    pub text: Rgba,
377    /// Axis and frame color.
378    pub axis: Rgba,
379    /// Grid color.
380    pub grid: Rgba,
381    /// Series palette, used when a series has no color.
382    pub palette: Vec<Rgba>,
383}
384
385impl Default for PlotTheme {
386    fn default() -> Self {
387        Self {
388            background: Rgba::WHITE,
389            plot_background: Rgba::WHITE,
390            text: Rgba::from_rgb(0x1f, 0x23, 0x28),
391            axis: Rgba::from_rgb(0x6a, 0x73, 0x7d),
392            grid: Rgba::from_rgb(0xe1, 0xe4, 0xe8),
393            palette: vec![
394                Rgba::from_rgb(0x1f, 0x77, 0xb4),
395                Rgba::from_rgb(0xff, 0x7f, 0x0e),
396                Rgba::from_rgb(0x2c, 0xa0, 0x2c),
397                Rgba::from_rgb(0xd6, 0x27, 0x28),
398                Rgba::from_rgb(0x94, 0x67, 0xbd),
399                Rgba::from_rgb(0x8c, 0x56, 0x4b),
400            ],
401        }
402    }
403}
404
405impl PlotTheme {
406    /// The color for series `index`, wrapping around the palette.
407    pub fn series_color(&self, index: usize) -> Rgba {
408        if self.palette.is_empty() {
409            Rgba::BLACK
410        } else {
411            self.palette[index % self.palette.len()]
412        }
413    }
414}
415
416/// Why a [`PlotSpec`] is invalid.
417#[derive(Clone, Debug, PartialEq)]
418#[non_exhaustive]
419pub enum SpecError {
420    /// The spec was written for a newer version.
421    Version(u32),
422    /// Width or height is zero.
423    Size,
424    /// A fixed range is reversed or non-finite.
425    Range([f64; 2]),
426    /// A series has no points.
427    EmptySeries(String),
428    /// A series has a non-finite coordinate.
429    NonFinite(String),
430}
431
432impl std::fmt::Display for SpecError {
433    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
434        match self {
435            Self::Version(version) => write!(
436                formatter,
437                "plot spec version {version} is newer than {PLOT_SPEC_VERSION}"
438            ),
439            Self::Size => write!(formatter, "plot width and height must be positive"),
440            Self::Range(range) => write!(formatter, "invalid range {range:?}"),
441            Self::EmptySeries(name) => write!(formatter, "series `{name}` has no points"),
442            Self::NonFinite(name) => write!(formatter, "series `{name}` has a non-finite point"),
443        }
444    }
445}
446
447impl std::error::Error for SpecError {}
448
449#[cfg(test)]
450mod tests {
451    use super::*;
452
453    #[test]
454    fn a_minimal_spec_is_valid() {
455        let spec = PlotSpec::new(320, 200).series(SeriesSpec::line("v", vec![[0.0, 1.0], [1.0, 2.0]]));
456        assert_eq!(spec.validate(), Ok(()));
457        assert_eq!(spec.version, PLOT_SPEC_VERSION);
458    }
459
460    #[test]
461    fn invalid_specs_are_rejected() {
462        let mut spec = PlotSpec::new(0, 200);
463        assert_eq!(spec.validate(), Err(SpecError::Size));
464        spec.width = 200;
465        spec.x_range = Some([2.0, 1.0]);
466        assert!(matches!(spec.validate(), Err(SpecError::Range(_))));
467        spec.x_range = None;
468        spec.series.push(SeriesSpec::default());
469        assert!(matches!(spec.validate(), Err(SpecError::EmptySeries(_))));
470    }
471
472    #[test]
473    fn page_presets_scale_with_dpi() {
474        assert_eq!(PagePreset::SingleColumn.pixels(300), (1050, 750));
475        assert_eq!(PagePreset::DoubleColumn.pixels(300), (2148, 1350));
476        assert_eq!(PlotSpec::new(1, 1).preset(PagePreset::Letter, 72).width, 612);
477    }
478
479    #[test]
480    fn the_palette_wraps() {
481        let theme = PlotTheme::default();
482        assert_eq!(theme.series_color(0), theme.palette[0]);
483        assert_eq!(theme.series_color(theme.palette.len()), theme.palette[0]);
484    }
485
486    #[cfg(feature = "serde")]
487    #[test]
488    fn a_spec_round_trips_through_json() {
489        let spec = PlotSpec::new(640, 360)
490            .title("Signal")
491            .series(SeriesSpec::scatter("s", vec![[0.0, 1.0], [1.0, 2.0]]));
492        let json = serde_json::to_string(&spec).expect("serialize");
493        let restored: PlotSpec = serde_json::from_str(&json).expect("deserialize");
494        assert_eq!(restored, spec);
495    }
496}