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