1use std::borrow::Cow;
4use std::sync::Arc;
5
6use egui::Color32;
7
8use super::axis::{Bounds, Scale};
9
10#[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 #[default]
18 Circle,
19 Square,
21 Diamond,
23 Triangle,
25 Cross,
27 Plus,
29 Ring,
31}
32
33#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
34#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
35#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
37#[non_exhaustive]
38pub enum LineStyle {
39 #[default]
41 Solid,
42 Dashed,
44 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
54#[non_exhaustive]
55pub enum Smoothing {
56 #[default]
58 None,
59 Spline,
62 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 Pie {
89 value: f64,
90 },
91 Candles {
93 width: Option<f64>,
94 },
95 Heatmap,
97 Radar,
99 Gauge {
101 value: f64,
102 min: f64,
103 max: f64,
104 },
105 Waterfall {
107 width: Option<f64>,
108 },
109}
110
111#[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 pub(super) ohlc: Option<Cow<'a, [[f64; 5]]>>,
128 pub(super) cells: Option<Cow<'a, [[f64; 3]]>>,
130 pub(super) lod: Option<(Arc<crisol_core::data::MinMaxPyramid>, usize)>,
132}
133
134impl Series<'static> {
135 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 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 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 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 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 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 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 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 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 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 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 pub fn color(mut self, color: Color32) -> Self {
266 self.color = Some(color);
267 self
268 }
269
270 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 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 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 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 pub fn y_axis(mut self, axis: YAxis) -> Self {
306 self.axis = axis;
307 self
308 }
309
310 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 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 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 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 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 pub fn hide_from_legend(mut self) -> Self {
355 self.legend = false;
356 self
357 }
358
359 pub fn name(&self) -> &str {
361 &self.name
362 }
363
364 pub fn data(&self) -> &[[f64; 2]] {
366 &self.data
367 }
368
369 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 pub(super) fn is_extra(&self) -> bool {
412 matches!(self.kind, Kind::Candles { .. } | Kind::Heatmap | Kind::Waterfall { .. })
413 }
414
415 pub(super) fn has_direction(&self) -> bool {
417 matches!(self.kind, Kind::Line { .. } | Kind::Candles { .. })
418 }
419
420 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
457pub 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}