crisol-plot 1.11.0

Crisol plot: interactive 2D charts and a 3D sibling with SVG, PNG, and PDF export.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
//! The data a plot draws: lines, scatter, bars, areas, steps, and reference lines.

use std::borrow::Cow;
use std::sync::Arc;

use egui::Color32;

use super::axis::{Bounds, Scale};

/// Point markers for scatter series and line vertices.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Marker {
    /// Filled circle.
    #[default]
    Circle,
    /// Filled square.
    Square,
    /// Filled diamond.
    Diamond,
    /// Filled upward triangle.
    Triangle,
    /// Diagonal cross (stroke only).
    Cross,
    /// Plus sign (stroke only).
    Plus,
    /// Circle outline.
    Ring,
}

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
/// How a line is stroked.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum LineStyle {
    /// Continuous.
    #[default]
    Solid,
    /// 6 pt dashes, 4 pt gaps.
    Dashed,
    /// 1.5 pt dots, 3 pt gaps.
    Dotted,
}

pub use crisol_plot_core::transform::YAxis;

#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
/// How a line passes through its points.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub enum Smoothing {
    /// Straight segments between points.
    #[default]
    None,
    /// A centripetal Catmull–Rom spline through every point: smooth, no loops or
    /// cusps, works in any point order.
    Spline,
    /// A monotone cubic (Fritsch–Carlson): never overshoots between points, so peaks
    /// stay at the data. Needs increasing x; falls back to [`Smoothing::Spline`].
    Monotone,
}

#[derive(Clone, Debug, PartialEq)]
pub(super) enum Kind {
    Line {
        width: f32,
        style: LineStyle,
        fill_to: Option<f64>,
        step: bool,
        markers: Option<Marker>,
        smoothing: Smoothing,
    },
    Scatter {
        marker: Marker,
        radius: f32,
    },
    Bars {
        width: Option<f64>,
        base: f64,
    },
    HLine(f64),
    VLine(f64),
    /// One slice of a pie or donut. The series name is the slice label.
    Pie {
        value: f64,
    },
    /// Open–high–low–close candles; the projected close is the series' data.
    Candles {
        width: Option<f64>,
    },
    /// A regular x/y/value grid.
    Heatmap,
    /// A closed polygon over the configured radar axes.
    Radar,
    /// One gauge, with its own range.
    Gauge {
        value: f64,
        min: f64,
        max: f64,
    },
    /// A cumulative bar chart of signed changes.
    Waterfall {
        width: Option<f64>,
    },
}

/// One named data series. Build it with [`Series::line`], [`Series::scatter`],
/// [`Series::bars`], [`Series::area`], [`Series::step`], [`Series::function`],
/// [`Series::hline`], or [`Series::vline`], then add it to a [`super::Plot`].
///
/// Data is borrowed when possible (`&[[f64; 2]]`), so a million-point buffer is not
/// copied every frame. Non-finite points break a line into segments.
#[derive(Clone, Debug)]
pub struct Series<'a> {
    pub(super) name: String,
    pub(super) data: Cow<'a, [[f64; 2]]>,
    pub(super) kind: Kind,
    pub(super) color: Option<Color32>,
    pub(super) y_errors: Option<Cow<'a, [f64]>>,
    pub(super) legend: bool,
    pub(super) axis: YAxis,
    /// OHLC rows for [`Kind::Candles`].
    pub(super) ohlc: Option<Cow<'a, [[f64; 5]]>>,
    /// x, y, value rows for [`Kind::Heatmap`].
    pub(super) cells: Option<Cow<'a, [[f64; 3]]>>,
    /// A streaming source whose visible tiles are materialized each frame.
    pub(super) lod: Option<(Arc<crisol_core::data::MinMaxPyramid>, usize)>,
}

impl Series<'static> {
    /// A line from two numeric columns of a [`crisol_core::data::Dataset`].
    ///
    /// ```
    /// # use crisol_plot::plot::Series;
    /// # use crisol_core::data::{Column, Dataset};
    /// let data = Dataset::from_columns([
    ///     Column::floats("t", vec![0.0, 1.0]),
    ///     Column::floats("v", vec![1.0, 2.0]),
    /// ]);
    /// let series = Series::from_dataset(&data, "t", "v").expect("columns");
    /// ```
    pub fn from_dataset(data: &crisol_core::data::Dataset, x: &str, y: &str) -> Option<Self> {
        let points = data.xy_pairs(x, y)?;
        Some(Self::line(format!("{y} vs {x}"), points))
    }
}

impl<'a> Series<'a> {
    pub(super) fn new(name: impl Into<String>, data: Cow<'a, [[f64; 2]]>, kind: Kind) -> Self {
        Self {
            name: name.into(),
            data,
            kind,
            color: None,
            y_errors: None,
            legend: true,
            axis: YAxis::Left,
            ohlc: None,
            cells: None,
            lod: None,
        }
    }

    /// A line backed by a [`MinMaxPyramid`](crisol_core::data::MinMaxPyramid).
    ///
    /// The visible x range is fetched as tiles and decimated to `budget` tiles; changing
    /// the zoom fetches a different level. This is the streaming path for recordings
    /// with 10⁸–10⁹ points.
    pub fn lod(
        name: impl Into<String>,
        pyramid: Arc<crisol_core::data::MinMaxPyramid>,
        budget: usize,
    ) -> Series<'static> {
        let mut series = Series::line(name, Vec::new());
        series.lod = Some((pyramid, budget.max(1)));
        series
    }

    /// A 1.5 pt polyline through the points, in order.
    pub fn line(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
        Self::new(
            name,
            data.into(),
            Kind::Line {
                width: 1.5,
                style: LineStyle::Solid,
                fill_to: None,
                step: false,
                markers: None,
                smoothing: Smoothing::None,
            },
        )
    }

    /// A line drawn as a smooth spline through the points (see [`Series::smooth`]).
    pub fn spline(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
        Self::line(name, data).smooth(Smoothing::Spline)
    }

    /// A line filled down to `y = 0` with 18 % of its color.
    pub fn area(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
        Self::line(name, data).fill_to(0.0)
    }

    /// A staircase line: each value holds until the next x.
    pub fn step(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
        let mut series = Self::line(name, data);
        if let Kind::Line { step, .. } = &mut series.kind {
            *step = true;
        }
        series
    }

    /// Unconnected markers (3 pt radius circles by default).
    pub fn scatter(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
        Self::new(
            name,
            data.into(),
            Kind::Scatter {
                marker: Marker::Circle,
                radius: 3.0,
            },
        )
    }

    /// Vertical bars from `y = 0` to each point; the width defaults to 80 % of the
    /// smallest x spacing.
    pub fn bars(name: impl Into<String>, data: impl Into<Cow<'a, [[f64; 2]]>>) -> Self {
        Self::new(name, data.into(), Kind::Bars { width: None, base: 0.0 })
    }

    /// `f(x)` sampled `samples` times over `x_range`.
    pub fn function(
        name: impl Into<String>,
        x_range: std::ops::RangeInclusive<f64>,
        samples: usize,
        f: impl Fn(f64) -> f64,
    ) -> Series<'static> {
        let samples = samples.max(2);
        let (start, end) = (*x_range.start(), *x_range.end());
        let data: Vec<[f64; 2]> = (0..samples)
            .map(|index| {
                let x = start + (end - start) * index as f64 / (samples - 1) as f64;
                [x, f(x)]
            })
            .collect();
        Series::line(name, data)
    }

    /// A horizontal reference line across the whole plot.
    pub fn hline(name: impl Into<String>, y: f64) -> Series<'static> {
        Series::new(name, Cow::Owned(Vec::new()), Kind::HLine(y))
    }

    /// A vertical reference line across the whole plot.
    pub fn vline(name: impl Into<String>, x: f64) -> Series<'static> {
        Series::new(name, Cow::Owned(Vec::new()), Kind::VLine(x))
    }

    /// Explicit color; the theme palette is used in order otherwise.
    pub fn color(mut self, color: Color32) -> Self {
        self.color = Some(color);
        self
    }

    /// Line width in points (lines, steps, areas, reference lines).
    pub fn width(mut self, new_width: f32) -> Self {
        if let Kind::Line { width, .. } = &mut self.kind {
            *width = new_width.max(0.5);
        }
        self
    }

    /// Dashed or dotted lines.
    pub fn style(mut self, new_style: LineStyle) -> Self {
        if let Kind::Line { style, .. } = &mut self.kind {
            *style = new_style;
        }
        self
    }

    /// Fill between the line and `y = base`.
    pub fn fill_to(mut self, base: f64) -> Self {
        if let Kind::Line { fill_to, .. } = &mut self.kind {
            *fill_to = Some(base);
        }
        self
    }

    /// Smooth the line through its points (lines and areas; steps stay square).
    /// Dense lines (more than one point per 2 pt) are drawn straight: a spline would
    /// not change what you see.
    pub fn smooth(mut self, new_smoothing: Smoothing) -> Self {
        if let Kind::Line { smoothing, .. } = &mut self.kind {
            *smoothing = new_smoothing;
        }
        self
    }

    /// Measure the series against the left (default) or the right y axis.
    pub fn y_axis(mut self, axis: YAxis) -> Self {
        self.axis = axis;
        self
    }

    /// Draw a marker on every vertex of a line, or change the scatter marker.
    pub fn marker(mut self, new_marker: Marker) -> Self {
        match &mut self.kind {
            Kind::Line { markers, .. } => *markers = Some(new_marker),
            Kind::Scatter { marker, .. } => *marker = new_marker,
            _ => {}
        }
        self
    }

    /// Marker radius in points (scatter).
    pub fn radius(mut self, new_radius: f32) -> Self {
        if let Kind::Scatter { radius, .. } = &mut self.kind {
            *radius = new_radius.max(1.0);
        }
        self
    }

    /// Bar width in data units (bars, candles, and waterfall bars).
    pub fn bar_width(mut self, new_width: f64) -> Self {
        match &mut self.kind {
            Kind::Bars { width, .. } | Kind::Candles { width } | Kind::Waterfall { width } => {
                *width = Some(new_width);
            }
            _ => {}
        }
        self
    }

    /// Where bars start (default 0).
    pub fn base(mut self, new_base: f64) -> Self {
        if let Kind::Bars { base, .. } = &mut self.kind {
            *base = new_base;
        }
        self
    }

    /// Symmetric ±error per point, drawn as whiskers.
    pub fn y_errors(mut self, errors: impl Into<Cow<'a, [f64]>>) -> Self {
        self.y_errors = Some(errors.into());
        self
    }

    /// Leave the series out of the legend.
    pub fn hide_from_legend(mut self) -> Self {
        self.legend = false;
        self
    }

    /// The series name (also the legend label).
    pub fn name(&self) -> &str {
        &self.name
    }

    /// The points.
    pub fn data(&self) -> &[[f64; 2]] {
        &self.data
    }

    /// A copy with processed data. Filters keep the series kind; transforms force a
    /// line so the frequency-domain result is readable.
    pub(super) fn with_data(&self, data: Vec<[f64; 2]>, force_line: bool) -> Series<'static> {
        let kind = if force_line {
            Kind::Line {
                width: 1.5,
                style: LineStyle::Solid,
                fill_to: None,
                step: false,
                markers: None,
                smoothing: Smoothing::None,
            }
        } else {
            self.kind.clone()
        };
        Series {
            name: self.name.clone(),
            data: Cow::Owned(data),
            kind,
            color: self.color,
            y_errors: None,
            legend: self.legend,
            axis: self.axis,
            ohlc: if force_line {
                None
            } else {
                self.ohlc.as_ref().map(|rows| Cow::Owned(rows.to_vec()))
            },
            cells: if force_line {
                None
            } else {
                self.cells.as_ref().map(|cells| Cow::Owned(cells.to_vec()))
            },
            lod: None,
        }
    }

    pub(super) fn is_reference(&self) -> bool {
        matches!(self.kind, Kind::HLine(_) | Kind::VLine(_))
    }

    /// Candles, heatmaps, and waterfalls have their own cartesian renderer.
    pub(super) fn is_extra(&self) -> bool {
        matches!(self.kind, Kind::Candles { .. } | Kind::Heatmap | Kind::Waterfall { .. })
    }

    /// Whether this is a line-like series that can show a direction arrow.
    pub(super) fn has_direction(&self) -> bool {
        matches!(self.kind, Kind::Line { .. } | Kind::Candles { .. })
    }

    /// A cheap key for [`Self::bounds`]: the buffers' addresses and lengths, the kind, the
    /// scales, and 16 sampled values. A different buffer, length, or sampled value is a
    /// different key, so appended or replaced data refreshes the cached extent.
    pub(super) fn fingerprint(&self, x_scale: Scale, y_scale: Scale) -> u64 {
        use std::hash::{Hash, Hasher};
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        (self.data.as_ptr() as usize, self.data.len()).hash(&mut hasher);
        if let Some(errors) = &self.y_errors {
            (errors.as_ptr() as usize, errors.len()).hash(&mut hasher);
        }
        if let Some(rows) = &self.ohlc {
            (rows.as_ptr() as usize, rows.len()).hash(&mut hasher);
            let step = (rows.len() / 8).max(1);
            for row in rows.iter().step_by(step) {
                for value in row {
                    value.to_bits().hash(&mut hasher);
                }
            }
        }
        if let Some(cells) = &self.cells {
            (cells.as_ptr() as usize, cells.len()).hash(&mut hasher);
            let step = (cells.len() / 8).max(1);
            for cell in cells.iter().step_by(step) {
                for value in cell {
                    value.to_bits().hash(&mut hasher);
                }
            }
        }
        format!("{:?}{x_scale:?}{y_scale:?}", self.kind).hash(&mut hasher);
        let step = (self.data.len() / 16).max(1);
        for point in self.data.iter().step_by(step).chain(self.data.last()) {
            (point[0].to_bits(), point[1].to_bits()).hash(&mut hasher);
        }
        hasher.finish()
    }
}

/// Indices of the points of `data` inside `bounds` (data space), for selections.
pub fn points_in(data: &[[f64; 2]], bounds: &Bounds) -> Vec<usize> {
    data.iter()
        .enumerate()
        .filter(|(_, point)| bounds.contains(**point))
        .map(|(index, _)| index)
        .collect()
}