1use std::borrow::Cow;
4
5use egui::Color32;
6
7use super::axis::{Bounds, Scale};
8
9#[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 #[default]
17 Circle,
18 Square,
20 Diamond,
22 Triangle,
24 Cross,
26 Plus,
28 Ring,
30}
31
32#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
33#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
34#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
36#[non_exhaustive]
37pub enum LineStyle {
38 #[default]
40 Solid,
41 Dashed,
43 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
53#[non_exhaustive]
54pub enum Smoothing {
55 #[default]
57 None,
58 Spline,
61 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 Pie {
88 value: f64,
89 },
90 Candles {
92 width: Option<f64>,
93 },
94 Heatmap,
96 Radar,
98 Gauge {
100 value: f64,
101 min: f64,
102 max: f64,
103 },
104 Waterfall {
106 width: Option<f64>,
107 },
108}
109
110#[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 pub(super) ohlc: Option<Cow<'a, [[f64; 5]]>>,
127 pub(super) cells: Option<Cow<'a, [[f64; 3]]>>,
129}
130
131impl Series<'static> {
132 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 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 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 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 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 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 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 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 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 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 pub fn color(mut self, color: Color32) -> Self {
247 self.color = Some(color);
248 self
249 }
250
251 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 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 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 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 pub fn y_axis(mut self, axis: YAxis) -> Self {
287 self.axis = axis;
288 self
289 }
290
291 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 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 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 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 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 pub fn hide_from_legend(mut self) -> Self {
336 self.legend = false;
337 self
338 }
339
340 pub fn name(&self) -> &str {
342 &self.name
343 }
344
345 pub fn data(&self) -> &[[f64; 2]] {
347 &self.data
348 }
349
350 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 pub(super) fn is_extra(&self) -> bool {
392 matches!(self.kind, Kind::Candles { .. } | Kind::Heatmap | Kind::Waterfall { .. })
393 }
394
395 pub(super) fn has_direction(&self) -> bool {
397 matches!(self.kind, Kind::Line { .. } | Kind::Candles { .. })
398 }
399
400 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
437pub 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}