Skip to main content

crisol_plot/plot/
series.rs

1//! The data a plot draws: lines, scatter, bars, areas, steps, and reference lines.
2
3use std::borrow::Cow;
4use std::sync::Arc;
5
6use egui::Color32;
7
8use super::axis::{Bounds, Scale};
9
10/// Point markers for scatter series and line vertices.
11#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
12#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
13#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
14#[non_exhaustive]
15pub enum Marker {
16    /// Filled circle.
17    #[default]
18    Circle,
19    /// Filled square.
20    Square,
21    /// Filled diamond.
22    Diamond,
23    /// Filled upward triangle.
24    Triangle,
25    /// Diagonal cross (stroke only).
26    Cross,
27    /// Plus sign (stroke only).
28    Plus,
29    /// Circle outline.
30    Ring,
31}
32
33#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
35/// How a line is stroked.
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum LineStyle {
39    /// Continuous.
40    #[default]
41    Solid,
42    /// 6 pt dashes, 4 pt gaps.
43    Dashed,
44    /// 1.5 pt dots, 3 pt gaps.
45    Dotted,
46}
47
48pub use crisol_plot_core::transform::YAxis;
49
50#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
51#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
52/// How a line passes through its points.
53#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
54#[non_exhaustive]
55pub enum Smoothing {
56    /// Straight segments between points.
57    #[default]
58    None,
59    /// A centripetal Catmull–Rom spline through every point: smooth, no loops or
60    /// cusps, works in any point order.
61    Spline,
62    /// A monotone cubic (Fritsch–Carlson): never overshoots between points, so peaks
63    /// stay at the data. Needs increasing x; falls back to [`Smoothing::Spline`].
64    Monotone,
65}
66
67#[derive(Clone, Debug, PartialEq)]
68pub(super) enum Kind {
69    Line {
70        width: f32,
71        style: LineStyle,
72        fill_to: Option<f64>,
73        step: bool,
74        markers: Option<Marker>,
75        smoothing: Smoothing,
76    },
77    Scatter {
78        marker: Marker,
79        radius: f32,
80    },
81    Bars {
82        width: Option<f64>,
83        base: f64,
84    },
85    HLine(f64),
86    VLine(f64),
87    /// One slice of a pie or donut. The series name is the slice label.
88    Pie {
89        value: f64,
90    },
91    /// Open–high–low–close candles; the projected close is the series' data.
92    Candles {
93        width: Option<f64>,
94    },
95    /// A regular x/y/value grid.
96    Heatmap,
97    /// A closed polygon over the configured radar axes.
98    Radar,
99    /// One gauge, with its own range.
100    Gauge {
101        value: f64,
102        min: f64,
103        max: f64,
104    },
105    /// A cumulative bar chart of signed changes.
106    Waterfall {
107        width: Option<f64>,
108    },
109}
110
111/// One named data series. Build it with [`Series::line`], [`Series::scatter`],
112/// [`Series::bars`], [`Series::area`], [`Series::step`], [`Series::function`],
113/// [`Series::hline`], or [`Series::vline`], then add it to a [`super::Plot`].
114///
115/// Data is borrowed when possible (`&[[f64; 2]]`), so a million-point buffer is not
116/// copied every frame. Non-finite points break a line into segments.
117#[derive(Clone, Debug)]
118pub struct Series<'a> {
119    pub(super) name: String,
120    pub(super) data: Cow<'a, [[f64; 2]]>,
121    pub(super) kind: Kind,
122    pub(super) color: Option<Color32>,
123    pub(super) y_errors: Option<Cow<'a, [f64]>>,
124    pub(super) legend: bool,
125    pub(super) axis: YAxis,
126    /// OHLC rows for [`Kind::Candles`].
127    pub(super) ohlc: Option<Cow<'a, [[f64; 5]]>>,
128    /// x, y, value rows for [`Kind::Heatmap`].
129    pub(super) cells: Option<Cow<'a, [[f64; 3]]>>,
130    /// A streaming source whose visible tiles are materialized each frame.
131    pub(super) lod: Option<(Arc<crisol_core::data::MinMaxPyramid>, usize)>,
132}
133
134impl Series<'static> {
135    /// A line from two numeric columns of a [`crisol_core::data::Dataset`].
136    ///
137    /// ```
138    /// # use crisol_plot::plot::Series;
139    /// # use crisol_core::data::{Column, Dataset};
140    /// let data = Dataset::from_columns([
141    ///     Column::floats("t", vec![0.0, 1.0]),
142    ///     Column::floats("v", vec![1.0, 2.0]),
143    /// ]);
144    /// let series = Series::from_dataset(&data, "t", "v").expect("columns");
145    /// ```
146    pub fn from_dataset(data: &crisol_core::data::Dataset, x: &str, y: &str) -> Option<Self> {
147        let points = data.xy_pairs(x, y)?;
148        Some(Self::line(format!("{y} vs {x}"), points))
149    }
150}
151
152impl<'a> Series<'a> {
153    pub(super) fn new(name: impl Into<String>, data: Cow<'a, [[f64; 2]]>, kind: Kind) -> Self {
154        Self {
155            name: name.into(),
156            data,
157            kind,
158            color: None,
159            y_errors: None,
160            legend: true,
161            axis: YAxis::Left,
162            ohlc: None,
163            cells: None,
164            lod: None,
165        }
166    }
167
168    /// A line backed by a [`MinMaxPyramid`](crisol_core::data::MinMaxPyramid).
169    ///
170    /// The visible x range is fetched as tiles and decimated to `budget` tiles; changing
171    /// the zoom fetches a different level. This is the streaming path for recordings
172    /// with 10⁸–10⁹ points.
173    pub fn lod(
174        name: impl Into<String>,
175        pyramid: Arc<crisol_core::data::MinMaxPyramid>,
176        budget: usize,
177    ) -> Series<'static> {
178        let mut series = Series::line(name, Vec::new());
179        series.lod = Some((pyramid, budget.max(1)));
180        series
181    }
182
183    /// A 1.5 pt polyline through the points, in order.
184    pub fn line(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
185        Self::new(
186            name,
187            data.into(),
188            Kind::Line {
189                width: 1.5,
190                style: LineStyle::Solid,
191                fill_to: None,
192                step: false,
193                markers: None,
194                smoothing: Smoothing::None,
195            },
196        )
197    }
198
199    /// A line drawn as a smooth spline through the points (see [`Series::smooth`]).
200    pub fn spline(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
201        Self::line(name, data).smooth(Smoothing::Spline)
202    }
203
204    /// A line filled down to `y = 0` with 18 % of its color.
205    pub fn area(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
206        Self::line(name, data).fill_to(0.0)
207    }
208
209    /// A staircase line: each value holds until the next x.
210    pub fn step(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
211        let mut series = Self::line(name, data);
212        if let Kind::Line { step, .. } = &mut series.kind {
213            *step = true;
214        }
215        series
216    }
217
218    /// Unconnected markers (3 pt radius circles by default).
219    pub fn scatter(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
220        Self::new(
221            name,
222            data.into(),
223            Kind::Scatter {
224                marker: Marker::Circle,
225                radius: 3.0,
226            },
227        )
228    }
229
230    /// Vertical bars from `y = 0` to each point; the width defaults to 80 % of the
231    /// smallest x spacing.
232    pub fn bars(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
233        Self::new(name, data.into(), Kind::Bars { width: None, base: 0.0 })
234    }
235
236    /// `f(x)` sampled `samples` times over `x_range`.
237    pub fn function(
238        name: impl Into<String>,
239        x_range: std::ops::RangeInclusive<f64>,
240        samples: usize,
241        f: impl Fn(f64) -> f64,
242    ) -> Series<'static> {
243        let samples = samples.max(2);
244        let (start, end) = (*x_range.start(), *x_range.end());
245        let data: Vec<[f64; 2]> = (0..samples)
246            .map(|index| {
247                let x = start + (end - start) * index as f64 / (samples - 1) as f64;
248                [x, f(x)]
249            })
250            .collect();
251        Series::line(name, data)
252    }
253
254    /// A horizontal reference line across the whole plot.
255    pub fn hline(name: impl Into<String>, y: f64) -> Series<'static> {
256        Series::new(name, Cow::Owned(Vec::new()), Kind::HLine(y))
257    }
258
259    /// A vertical reference line across the whole plot.
260    pub fn vline(name: impl Into<String>, x: f64) -> Series<'static> {
261        Series::new(name, Cow::Owned(Vec::new()), Kind::VLine(x))
262    }
263
264    /// Explicit color; the theme palette is used in order otherwise.
265    pub fn color(mut self, color: Color32) -> Self {
266        self.color = Some(color);
267        self
268    }
269
270    /// Line width in points (lines, steps, areas, reference lines).
271    pub fn width(mut self, new_width: f32) -> Self {
272        if let Kind::Line { width, .. } = &mut self.kind {
273            *width = new_width.max(0.5);
274        }
275        self
276    }
277
278    /// Dashed or dotted lines.
279    pub fn style(mut self, new_style: LineStyle) -> Self {
280        if let Kind::Line { style, .. } = &mut self.kind {
281            *style = new_style;
282        }
283        self
284    }
285
286    /// Fill between the line and `y = base`.
287    pub fn fill_to(mut self, base: f64) -> Self {
288        if let Kind::Line { fill_to, .. } = &mut self.kind {
289            *fill_to = Some(base);
290        }
291        self
292    }
293
294    /// Smooth the line through its points (lines and areas; steps stay square).
295    /// Dense lines (more than one point per 2 pt) are drawn straight: a spline would
296    /// not change what you see.
297    pub fn smooth(mut self, new_smoothing: Smoothing) -> Self {
298        if let Kind::Line { smoothing, .. } = &mut self.kind {
299            *smoothing = new_smoothing;
300        }
301        self
302    }
303
304    /// Measure the series against the left (default) or the right y axis.
305    pub fn y_axis(mut self, axis: YAxis) -> Self {
306        self.axis = axis;
307        self
308    }
309
310    /// Draw a marker on every vertex of a line, or change the scatter marker.
311    pub fn marker(mut self, new_marker: Marker) -> Self {
312        match &mut self.kind {
313            Kind::Line { markers, .. } => *markers = Some(new_marker),
314            Kind::Scatter { marker, .. } => *marker = new_marker,
315            _ => {}
316        }
317        self
318    }
319
320    /// Marker radius in points (scatter).
321    pub fn radius(mut self, new_radius: f32) -> Self {
322        if let Kind::Scatter { radius, .. } = &mut self.kind {
323            *radius = new_radius.max(1.0);
324        }
325        self
326    }
327
328    /// Bar width in data units (bars, candles, and waterfall bars).
329    pub fn bar_width(mut self, new_width: f64) -> Self {
330        match &mut self.kind {
331            Kind::Bars { width, .. } | Kind::Candles { width } | Kind::Waterfall { width } => {
332                *width = Some(new_width);
333            }
334            _ => {}
335        }
336        self
337    }
338
339    /// Where bars start (default 0).
340    pub fn base(mut self, new_base: f64) -> Self {
341        if let Kind::Bars { base, .. } = &mut self.kind {
342            *base = new_base;
343        }
344        self
345    }
346
347    /// Symmetric ±error per point, drawn as whiskers.
348    pub fn y_errors(mut self, errors: impl Into<Cow<'a, [f64]>>) -> Self {
349        self.y_errors = Some(errors.into());
350        self
351    }
352
353    /// Leave the series out of the legend.
354    pub fn hide_from_legend(mut self) -> Self {
355        self.legend = false;
356        self
357    }
358
359    /// The series name (also the legend label).
360    pub fn name(&self) -> &str {
361        &self.name
362    }
363
364    /// The points.
365    pub fn data(&self) -> &[[f64; 2]] {
366        &self.data
367    }
368
369    /// A copy with processed data. Filters keep the series kind; transforms force a
370    /// line so the frequency-domain result is readable.
371    pub(super) fn with_data(&self, data: Vec<[f64; 2]>, force_line: bool) -> Series<'static> {
372        let kind = if force_line {
373            Kind::Line {
374                width: 1.5,
375                style: LineStyle::Solid,
376                fill_to: None,
377                step: false,
378                markers: None,
379                smoothing: Smoothing::None,
380            }
381        } else {
382            self.kind.clone()
383        };
384        Series {
385            name: self.name.clone(),
386            data: Cow::Owned(data),
387            kind,
388            color: self.color,
389            y_errors: None,
390            legend: self.legend,
391            axis: self.axis,
392            ohlc: if force_line {
393                None
394            } else {
395                self.ohlc.as_ref().map(|rows| Cow::Owned(rows.to_vec()))
396            },
397            cells: if force_line {
398                None
399            } else {
400                self.cells.as_ref().map(|cells| Cow::Owned(cells.to_vec()))
401            },
402            lod: None,
403        }
404    }
405
406    pub(super) fn is_reference(&self) -> bool {
407        matches!(self.kind, Kind::HLine(_) | Kind::VLine(_))
408    }
409
410    /// Candles, heatmaps, and waterfalls have their own cartesian renderer.
411    pub(super) fn is_extra(&self) -> bool {
412        matches!(self.kind, Kind::Candles { .. } | Kind::Heatmap | Kind::Waterfall { .. })
413    }
414
415    /// Whether this is a line-like series that can show a direction arrow.
416    pub(super) fn has_direction(&self) -> bool {
417        matches!(self.kind, Kind::Line { .. } | Kind::Candles { .. })
418    }
419
420    /// A cheap key for [`Self::bounds`]: the buffers' addresses and lengths, the kind, the
421    /// scales, and 16 sampled values. A different buffer, length, or sampled value is a
422    /// different key, so appended or replaced data refreshes the cached extent.
423    pub(super) fn fingerprint(&self, x_scale: Scale, y_scale: Scale) -> u64 {
424        use std::hash::{Hash, Hasher};
425        let mut hasher = std::collections::hash_map::DefaultHasher::new();
426        (self.data.as_ptr() as usize, self.data.len()).hash(&mut hasher);
427        if let Some(errors) = &self.y_errors {
428            (errors.as_ptr() as usize, errors.len()).hash(&mut hasher);
429        }
430        if let Some(rows) = &self.ohlc {
431            (rows.as_ptr() as usize, rows.len()).hash(&mut hasher);
432            let step = (rows.len() / 8).max(1);
433            for row in rows.iter().step_by(step) {
434                for value in row {
435                    value.to_bits().hash(&mut hasher);
436                }
437            }
438        }
439        if let Some(cells) = &self.cells {
440            (cells.as_ptr() as usize, cells.len()).hash(&mut hasher);
441            let step = (cells.len() / 8).max(1);
442            for cell in cells.iter().step_by(step) {
443                for value in cell {
444                    value.to_bits().hash(&mut hasher);
445                }
446            }
447        }
448        format!("{:?}{x_scale:?}{y_scale:?}", self.kind).hash(&mut hasher);
449        let step = (self.data.len() / 16).max(1);
450        for point in self.data.iter().step_by(step).chain(self.data.last()) {
451            (point[0].to_bits(), point[1].to_bits()).hash(&mut hasher);
452        }
453        hasher.finish()
454    }
455}
456
457/// Indices of the points of `data` inside `bounds` (data space), for selections.
458pub fn points_in(data: &[[f64; 2]], bounds: &Bounds) -> Vec<usize> {
459    data.iter()
460        .enumerate()
461        .filter(|(_, point)| bounds.contains(**point))
462        .map(|(index, _)| index)
463        .collect()
464}