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        const MAX_SIDE: u32 = 16_384;
156        const MAX_PIXELS: u64 = 64_000_000;
157        if self.width > MAX_SIDE
158            || self.height > MAX_SIDE
159            || u64::from(self.width) * u64::from(self.height) > MAX_PIXELS
160        {
161            return Err(SpecError::TooLarge {
162                width: self.width,
163                height: self.height,
164            });
165        }
166        for range in [self.x_range, self.y_range].into_iter().flatten() {
167            if !range[0].is_finite() || !range[1].is_finite() || range[1] <= range[0] {
168                return Err(SpecError::Range(range));
169            }
170        }
171        for series in &self.series {
172            if series.points.is_empty() {
173                return Err(SpecError::EmptySeries(series.name.clone()));
174            }
175            if !series.points.iter().flatten().all(|value| value.is_finite()) {
176                return Err(SpecError::NonFinite(series.name.clone()));
177            }
178        }
179        Ok(())
180    }
181}
182
183/// A publication page preset.
184#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
185#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
186#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
187#[non_exhaustive]
188pub enum PagePreset {
189    /// A single journal column, 3.5 × 2.5 in.
190    #[default]
191    SingleColumn,
192    /// A double journal column, 7.16 × 4.5 in.
193    DoubleColumn,
194    /// US Letter, 8.5 × 11 in.
195    Letter,
196}
197
198impl PagePreset {
199    /// Width and height in inches.
200    pub const fn inches(self) -> (f32, f32) {
201        match self {
202            Self::SingleColumn => (3.5, 2.5),
203            Self::DoubleColumn => (7.16, 4.5),
204            Self::Letter => (8.5, 11.0),
205        }
206    }
207
208    /// Width and height in pixels at `dpi`.
209    pub fn pixels(self, dpi: u32) -> (u32, u32) {
210        let (width, height) = self.inches();
211        (
212            (width * dpi as f32).round() as u32,
213            (height * dpi as f32).round() as u32,
214        )
215    }
216}
217
218/// One series in a [`PlotSpec`].
219#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
220#[cfg_attr(feature = "serde", serde(default, rename_all = "snake_case"))]
221#[derive(Clone, Debug, PartialEq)]
222pub struct SeriesSpec {
223    /// Legend name.
224    pub name: String,
225    /// How the points are drawn.
226    pub kind: SeriesKind,
227    /// x/y points in data units.
228    pub points: Vec<[f64; 2]>,
229    /// Stroke or fill color; the spec palette when `None`.
230    pub color: Option<Rgba>,
231    /// Stroke width in pixels.
232    pub width: f32,
233    /// Marker for scatter, or for vertices of a line.
234    pub marker: Option<MarkerSpec>,
235    /// Fill opacity for areas and bars, 0–1.
236    pub fill_opacity: f32,
237    /// Axis the series is measured on.
238    pub y_axis: YAxis,
239    /// Whether the series appears in the legend.
240    pub legend: bool,
241    /// Baseline for bars.
242    pub baseline: f64,
243    /// Fixed bar width in data units; automatic when `None`.
244    pub bar_width: Option<f64>,
245}
246
247impl Default for SeriesSpec {
248    fn default() -> Self {
249        Self {
250            name: String::new(),
251            kind: SeriesKind::Line,
252            points: Vec::new(),
253            color: None,
254            width: 1.5,
255            marker: None,
256            fill_opacity: 0.2,
257            y_axis: YAxis::Left,
258            legend: true,
259            baseline: 0.0,
260            bar_width: None,
261        }
262    }
263}
264
265impl SeriesSpec {
266    /// A line series.
267    pub fn line(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
268        Self {
269            name: name.into(),
270            points,
271            ..Self::default()
272        }
273    }
274
275    /// A scatter series.
276    pub fn scatter(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
277        Self {
278            name: name.into(),
279            kind: SeriesKind::Scatter,
280            marker: Some(MarkerSpec::Circle),
281            points,
282            ..Self::default()
283        }
284    }
285
286    /// A filled area down to `baseline`.
287    pub fn area(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
288        Self {
289            name: name.into(),
290            kind: SeriesKind::Area,
291            points,
292            ..Self::default()
293        }
294    }
295
296    /// A staircase series.
297    pub fn step(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
298        Self {
299            name: name.into(),
300            kind: SeriesKind::Step,
301            points,
302            ..Self::default()
303        }
304    }
305
306    /// A bar series.
307    pub fn bars(name: impl Into<String>, points: Vec<[f64; 2]>) -> Self {
308        Self {
309            name: name.into(),
310            kind: SeriesKind::Bars,
311            points,
312            ..Self::default()
313        }
314    }
315
316    /// Set the color.
317    pub fn color(mut self, color: Rgba) -> Self {
318        self.color = Some(color);
319        self
320    }
321
322    /// Set the stroke width.
323    pub fn width(mut self, width: f32) -> Self {
324        self.width = width;
325        self
326    }
327
328    /// Set the marker.
329    pub fn marker(mut self, marker: MarkerSpec) -> Self {
330        self.marker = Some(marker);
331        self
332    }
333}
334
335/// How a [`SeriesSpec`] is drawn.
336#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
337#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
338#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
339#[non_exhaustive]
340pub enum SeriesKind {
341    /// A polyline.
342    #[default]
343    Line,
344    /// Unconnected markers.
345    Scatter,
346    /// A polygon down to the baseline.
347    Area,
348    /// A staircase that holds each value until the next x.
349    Step,
350    /// Vertical bars from the baseline.
351    Bars,
352}
353
354/// A marker shape.
355#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
356#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
357#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
358#[non_exhaustive]
359pub enum MarkerSpec {
360    /// Filled circle.
361    #[default]
362    Circle,
363    /// Filled square.
364    Square,
365    /// Filled diamond.
366    Diamond,
367    /// Filled upward triangle.
368    Triangle,
369    /// Diagonal cross.
370    Cross,
371    /// Plus sign.
372    Plus,
373    /// Circle outline.
374    Ring,
375}
376
377/// Theme colors for a headless chart.
378#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
379#[cfg_attr(feature = "serde", serde(default))]
380#[derive(Clone, Debug, PartialEq)]
381pub struct PlotTheme {
382    /// Canvas fill.
383    pub background: Rgba,
384    /// Plot area fill inside the axes.
385    pub plot_background: Rgba,
386    /// Title and label color.
387    pub text: Rgba,
388    /// Axis and frame color.
389    pub axis: Rgba,
390    /// Grid color.
391    pub grid: Rgba,
392    /// Series palette, used when a series has no color.
393    pub palette: Vec<Rgba>,
394}
395
396impl Default for PlotTheme {
397    fn default() -> Self {
398        Self {
399            background: Rgba::WHITE,
400            plot_background: Rgba::WHITE,
401            text: Rgba::from_rgb(0x1f, 0x23, 0x28),
402            axis: Rgba::from_rgb(0x6a, 0x73, 0x7d),
403            grid: Rgba::from_rgb(0xe1, 0xe4, 0xe8),
404            palette: vec![
405                Rgba::from_rgb(0x1f, 0x77, 0xb4),
406                Rgba::from_rgb(0xff, 0x7f, 0x0e),
407                Rgba::from_rgb(0x2c, 0xa0, 0x2c),
408                Rgba::from_rgb(0xd6, 0x27, 0x28),
409                Rgba::from_rgb(0x94, 0x67, 0xbd),
410                Rgba::from_rgb(0x8c, 0x56, 0x4b),
411            ],
412        }
413    }
414}
415
416impl PlotTheme {
417    /// The color for series `index`, wrapping around the palette.
418    pub fn series_color(&self, index: usize) -> Rgba {
419        if self.palette.is_empty() {
420            Rgba::BLACK
421        } else {
422            self.palette[index % self.palette.len()]
423        }
424    }
425}
426
427/// Why a [`PlotSpec`] is invalid.
428#[derive(Clone, Debug, PartialEq)]
429#[non_exhaustive]
430pub enum SpecError {
431    /// The spec was written for a newer version.
432    Version(u32),
433    /// Width or height is zero.
434    Size,
435    /// Width, height, or total area exceeds the renderer budget.
436    TooLarge {
437        /// Requested width.
438        width: u32,
439        /// Requested height.
440        height: u32,
441    },
442    /// A fixed range is reversed or non-finite.
443    Range([f64; 2]),
444    /// A series has no points.
445    EmptySeries(String),
446    /// A series has a non-finite coordinate.
447    NonFinite(String),
448}
449
450impl std::fmt::Display for SpecError {
451    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
452        match self {
453            Self::Version(version) => write!(
454                formatter,
455                "plot spec version {version} is newer than {PLOT_SPEC_VERSION}"
456            ),
457            Self::Size => write!(formatter, "plot width and height must be positive"),
458            Self::TooLarge { width, height } => write!(
459                formatter,
460                "plot {width}×{height} exceeds the 16384 px side or 64M-pixel budget"
461            ),
462            Self::Range(range) => write!(formatter, "invalid range {range:?}"),
463            Self::EmptySeries(name) => write!(formatter, "series `{name}` has no points"),
464            Self::NonFinite(name) => write!(formatter, "series `{name}` has a non-finite point"),
465        }
466    }
467}
468
469impl std::error::Error for SpecError {}
470
471#[cfg(test)]
472mod tests;