1use crisol_core::color::Rgba;
9
10use crate::axis::Scale;
11use crate::transform::YAxis;
12
13pub const PLOT_SPEC_VERSION: u32 = 1;
15
16#[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 pub version: u32,
32 pub title: Option<String>,
34 pub x_label: Option<String>,
36 pub y_label: Option<String>,
38 pub width: u32,
40 pub height: u32,
42 pub x_scale: Scale,
44 pub y_scale: Scale,
46 pub x_range: Option<[f64; 2]>,
48 pub y_range: Option<[f64; 2]>,
50 pub series: Vec<SeriesSpec>,
52 pub legend: bool,
54 pub grid: bool,
56 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 pub fn new(width: u32, height: u32) -> Self {
84 Self {
85 width,
86 height,
87 ..Self::default()
88 }
89 }
90
91 pub fn title(mut self, title: impl Into<String>) -> Self {
93 self.title = Some(title.into());
94 self
95 }
96
97 pub fn x_label(mut self, label: impl Into<String>) -> Self {
99 self.x_label = Some(label.into());
100 self
101 }
102
103 pub fn y_label(mut self, label: impl Into<String>) -> Self {
105 self.y_label = Some(label.into());
106 self
107 }
108
109 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 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 pub fn series(mut self, series: SeriesSpec) -> Self {
125 self.series.push(series);
126 self
127 }
128
129 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 pub fn theme(mut self, theme: PlotTheme) -> Self {
139 self.theme = Some(theme);
140 self
141 }
142
143 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#[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 #[default]
180 SingleColumn,
181 DoubleColumn,
183 Letter,
185}
186
187impl PagePreset {
188 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 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#[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 pub name: String,
214 pub kind: SeriesKind,
216 pub points: Vec<[f64; 2]>,
218 pub color: Option<Rgba>,
220 pub width: f32,
222 pub marker: Option<MarkerSpec>,
224 pub fill_opacity: f32,
226 pub y_axis: YAxis,
228 pub legend: bool,
230 pub baseline: f64,
232 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 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 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 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 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 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 pub fn color(mut self, color: Rgba) -> Self {
307 self.color = Some(color);
308 self
309 }
310
311 pub fn width(mut self, width: f32) -> Self {
313 self.width = width;
314 self
315 }
316
317 pub fn marker(mut self, marker: MarkerSpec) -> Self {
319 self.marker = Some(marker);
320 self
321 }
322}
323
324#[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 #[default]
332 Line,
333 Scatter,
335 Area,
337 Step,
339 Bars,
341}
342
343#[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 #[default]
351 Circle,
352 Square,
354 Diamond,
356 Triangle,
358 Cross,
360 Plus,
362 Ring,
364}
365
366#[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 pub background: Rgba,
373 pub plot_background: Rgba,
375 pub text: Rgba,
377 pub axis: Rgba,
379 pub grid: Rgba,
381 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 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#[derive(Clone, Debug, PartialEq)]
418#[non_exhaustive]
419pub enum SpecError {
420 Version(u32),
422 Size,
424 Range([f64; 2]),
426 EmptySeries(String),
428 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}