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 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#[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 #[default]
191 SingleColumn,
192 DoubleColumn,
194 Letter,
196}
197
198impl PagePreset {
199 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 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#[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 pub name: String,
225 pub kind: SeriesKind,
227 pub points: Vec<[f64; 2]>,
229 pub color: Option<Rgba>,
231 pub width: f32,
233 pub marker: Option<MarkerSpec>,
235 pub fill_opacity: f32,
237 pub y_axis: YAxis,
239 pub legend: bool,
241 pub baseline: f64,
243 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 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 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 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 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 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 pub fn color(mut self, color: Rgba) -> Self {
318 self.color = Some(color);
319 self
320 }
321
322 pub fn width(mut self, width: f32) -> Self {
324 self.width = width;
325 self
326 }
327
328 pub fn marker(mut self, marker: MarkerSpec) -> Self {
330 self.marker = Some(marker);
331 self
332 }
333}
334
335#[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 #[default]
343 Line,
344 Scatter,
346 Area,
348 Step,
350 Bars,
352}
353
354#[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 #[default]
362 Circle,
363 Square,
365 Diamond,
367 Triangle,
369 Cross,
371 Plus,
373 Ring,
375}
376
377#[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 pub background: Rgba,
384 pub plot_background: Rgba,
386 pub text: Rgba,
388 pub axis: Rgba,
390 pub grid: Rgba,
392 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 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#[derive(Clone, Debug, PartialEq)]
429#[non_exhaustive]
430pub enum SpecError {
431 Version(u32),
433 Size,
435 TooLarge {
437 width: u32,
439 height: u32,
441 },
442 Range([f64; 2]),
444 EmptySeries(String),
446 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;