1use crate::Color;
10use crate::ui::types::PixelRect;
11
12#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
19pub enum Scale {
20 #[default]
22 Linear,
23 Log10,
27 Symlog,
31}
32
33pub const SYMLOG_LINTHRESH: f32 = 1.0;
35
36pub(super) fn scale_value(value: f32, scale: Scale) -> f32 {
38 match scale {
39 Scale::Linear => value,
40 Scale::Log10 => {
41 if value > 0.0 && value.is_finite() {
42 value.log10()
43 } else {
44 f32::NAN
45 }
46 }
47 Scale::Symlog => {
48 if !value.is_finite() {
49 return f32::NAN;
50 }
51 let magnitude = value.abs();
52 if magnitude <= SYMLOG_LINTHRESH {
53 value
54 } else {
55 value.signum() * SYMLOG_LINTHRESH * (1.0 + (magnitude / SYMLOG_LINTHRESH).log10())
56 }
57 }
58 }
59}
60
61pub(super) fn unscale_value(value: f32, scale: Scale) -> f32 {
63 match scale {
64 Scale::Linear => value,
65 Scale::Log10 => 10f32.powf(value),
66 Scale::Symlog => {
67 let magnitude = value.abs();
68 if magnitude <= SYMLOG_LINTHRESH {
69 value
70 } else {
71 value.signum() * SYMLOG_LINTHRESH * 10f32.powf(magnitude / SYMLOG_LINTHRESH - 1.0)
72 }
73 }
74 }
75}
76
77fn scaled_axis(lo: f32, hi: f32, scale: Scale, positive_min: Option<f32>) -> (f32, f32) {
83 match scale {
84 Scale::Linear => (lo, hi),
85 Scale::Log10 => {
86 let lo = if lo.is_finite() && lo > 0.0 {
87 lo
88 } else if let Some(min) = positive_min {
89 min
90 } else {
91 return (0.0, 1.0);
92 };
93 let hi = if hi.is_finite() && hi > lo {
94 hi
95 } else {
96 lo * 10.0
97 };
98 (lo.log10(), hi.log10())
99 }
100 Scale::Symlog => {
101 let lo = scale_value(lo, scale);
102 let hi = scale_value(hi, scale);
103 if lo.is_finite() && hi.is_finite() && lo < hi {
104 (lo, hi)
105 } else {
106 (-SYMLOG_LINTHRESH, SYMLOG_LINTHRESH)
107 }
108 }
109 }
110}
111
112#[derive(Clone, Debug, Default)]
117pub enum TickFormat {
118 #[default]
120 Auto,
121 Decimals(usize),
123 Scientific,
125 Labels(Vec<String>),
127}
128
129#[derive(Clone, Debug)]
133pub struct LineStyle {
134 pub color: Color,
136 pub label: String,
137 pub width: f32,
138 pub antialias_samples: u32,
139 pub step: bool,
142 pub hidden: bool,
144}
145
146impl Default for LineStyle {
147 fn default() -> Self {
148 Self {
149 color: Color::new(0.0, 0.0, 0.0, 0.0), label: String::new(),
151 width: 1.35,
152 antialias_samples: 4,
153 step: false,
154 hidden: false,
155 }
156 }
157}
158
159#[derive(Clone, Debug)]
161pub struct ScatterStyle {
162 pub color: Color,
163 pub label: String,
164 pub radius: f32,
165 pub hidden: bool,
167}
168
169impl Default for ScatterStyle {
170 fn default() -> Self {
171 Self {
172 color: Color::new(0.0, 0.0, 0.0, 0.0),
173 label: String::new(),
174 radius: 3.0,
175 hidden: false,
176 }
177 }
178}
179
180#[derive(Clone, Debug)]
182pub struct BarStyle {
183 pub color: Color,
184 pub label: String,
185 pub gap: f32,
187 pub hidden: bool,
189}
190
191impl Default for BarStyle {
192 fn default() -> Self {
193 Self {
194 color: Color::new(0.0, 0.0, 0.0, 0.0),
195 label: String::new(),
196 gap: 0.18,
197 hidden: false,
198 }
199 }
200}
201
202#[derive(Clone, Debug)]
206pub struct HeatmapStyle {
207 pub v_min: f32,
208 pub v_max: f32,
209 pub colormap: u32,
213 pub auto_scale: bool,
218 pub show_grid: bool,
220 pub colorbar: bool,
223}
224
225#[derive(Clone, Debug)]
227pub struct BoxStyle {
228 pub color: Color,
230 pub label: String,
231 pub width: f32,
233 pub whisk: f32,
235 pub hidden: bool,
237}
238
239impl Default for BoxStyle {
240 fn default() -> Self {
241 Self {
242 color: Color::new(0.0, 0.0, 0.0, 0.0),
243 label: String::new(),
244 width: 0.5,
245 whisk: 1.5,
246 hidden: false,
247 }
248 }
249}
250
251impl Default for HeatmapStyle {
252 fn default() -> Self {
253 Self {
254 v_min: 0.0,
255 v_max: 1.0,
256 colormap: 1, auto_scale: true,
258 show_grid: true,
259 colorbar: false,
260 }
261 }
262}
263
264#[derive(Clone, Copy, Debug, PartialEq, Eq)]
268pub(super) enum ArtistKind {
269 Line,
270 Scatter,
271 Bar,
272 LineMatrix,
274 Stream,
276 Band,
278 BoxPlot,
280}
281
282#[derive(Default, Clone)]
284pub(super) struct AxesCommands {
285 pub(super) title: String,
286 pub(super) title_color: Color,
287 pub(super) caption: String,
288 pub(super) caption_color: Color,
289 pub(super) x_label: String,
290 pub(super) y_label: String,
291 pub(super) imshow: Option<ImshowCmd>,
292 pub(super) heatmap: Option<Heatmap>,
293 pub(super) heatmap_matrix: Option<HeatmapMatrixCmd>,
294 pub(super) lines: Vec<LineCmd>,
295 pub(super) scatters: Vec<ScatterCmd>,
296 pub(super) bars: Vec<BarCmd>,
297 pub(super) line_matrices: Vec<LineMatrixCmd>,
298 pub(super) streams: Vec<StreamCmd>,
299 pub(super) bands: Vec<BandCmd>,
300 pub(super) boxes: Vec<BoxCmd>,
301 pub(super) annotations: Vec<AnnotationCmd>,
302 pub(super) artists: Vec<ArtistKind>,
304 pub(super) limits: Option<LimitsCmd>,
305 pub(super) x_scale: Scale,
306 pub(super) y_scale: Scale,
307 pub(super) x_ticks: Option<Vec<f32>>,
309 pub(super) y_ticks: Option<Vec<f32>>,
310 pub(super) x_tick_format: TickFormat,
311 pub(super) y_tick_format: TickFormat,
312 pub(super) categories: Vec<String>,
313 pub(super) show_grid: bool,
314 pub(super) show_legend: bool,
315 pub(super) border_color: Option<Color>,
316}
317
318impl AxesCommands {
319 pub(super) fn new() -> Self {
320 Self {
321 show_grid: true,
322 show_legend: true,
323 ..Default::default()
324 }
325 }
326}
327
328#[derive(Clone)]
329pub(super) struct ImshowCmd {
330 pub(super) texture: crate::Texture,
331}
332
333#[derive(Clone)]
334pub(super) struct Heatmap {
335 pub(super) values: Vec<f32>,
336 pub(super) rows: i32,
337 pub(super) cols: i32,
338 pub(super) style: HeatmapStyle,
339}
340
341#[derive(Clone)]
343pub(super) struct HeatmapMatrixCmd {
344 pub(super) values: crate::Matrix,
345 pub(super) style: HeatmapStyle,
346}
347
348#[derive(Clone)]
349pub(super) struct LineCmd {
350 pub(super) x: Vec<f32>,
351 pub(super) y: Vec<f32>,
352 pub(super) style: LineStyle,
353}
354
355#[derive(Clone)]
356pub(super) struct ScatterCmd {
357 pub(super) x: Vec<f32>,
358 pub(super) y: Vec<f32>,
359 pub(super) style: ScatterStyle,
360}
361
362#[derive(Clone)]
363pub(super) struct BarCmd {
364 pub(super) y: Vec<f32>,
365 pub(super) group: Option<(usize, usize)>,
367 pub(super) stack_base: Option<Vec<f32>>,
369 pub(super) style: BarStyle,
370}
371
372#[derive(Clone)]
378pub(super) struct LineMatrixCmd {
379 pub(super) values: crate::Matrix,
380 pub(super) xy: bool,
381 pub(super) style: LineStyle,
382}
383
384#[derive(Clone)]
390pub(super) struct StreamCmd {
391 pub(super) values: Vec<f32>,
392 pub(super) head: usize,
393 pub(super) len: usize,
394 pub(super) style: LineStyle,
395}
396
397impl StreamCmd {
398 fn push(&mut self, value: f32) {
400 let capacity = self.values.len();
401 if self.len < capacity {
402 self.values[(self.head + self.len) % capacity] = value;
403 self.len += 1;
404 } else {
405 self.values[self.head] = value;
406 self.head = (self.head + 1) % capacity;
407 }
408 }
409
410 pub(super) fn ordered(&self) -> impl Iterator<Item = f32> + '_ {
412 let capacity = self.values.len();
413 (0..self.len).map(move |index| self.values[(self.head + index) % capacity])
414 }
415}
416
417#[derive(Clone)]
422pub(super) struct BoxCmd {
423 pub(super) summaries: Vec<(f32, f32, f32, f32, f32, f32)>,
425 pub(super) style: BoxStyle,
426}
427
428#[derive(Clone)]
433pub(super) struct BandCmd {
434 pub(super) y_lo: Vec<f32>,
435 pub(super) y_hi: Vec<f32>,
436 pub(super) style: LineStyle,
437}
438
439#[derive(Clone)]
441pub(super) struct AnnotationCmd {
442 pub(super) text: String,
443 pub(super) x: f32,
444 pub(super) y: f32,
445}
446
447#[derive(Clone, Debug)]
448pub(super) struct LimitsCmd {
449 pub(super) x_min: f32,
450 pub(super) x_max: f32,
451 pub(super) y_min: f32,
452 pub(super) y_max: f32,
453}
454
455pub(super) struct LegendEntry {
461 pub(super) artist: usize,
462 pub(super) label: String,
463 pub(super) color: Color,
464 pub(super) hidden: bool,
465 pub(super) row: usize,
466}
467
468pub(super) const COLORBAR_RESERVE: u32 = 46;
470
471pub(super) struct AxesLayout {
473 pub(super) plot: PixelRect,
474 pub(super) title: PixelRect,
475 pub(super) caption: PixelRect,
476 pub(super) x_ticks: PixelRect,
477 pub(super) y_ticks: PixelRect,
478 pub(super) x_label: PixelRect,
479 pub(super) y_label: PixelRect,
480}
481
482const LEGEND_WIDTH: u32 = 124;
483const LEGEND_INSET: u32 = 6;
484const LEGEND_ROW_HEIGHT: u32 = 15;
485
486pub(super) fn legend_row_rect(rect: PixelRect, row: usize) -> PixelRect {
488 let w = rect.w.saturating_sub(2 * LEGEND_INSET).min(LEGEND_WIDTH);
489 let h = rect.h.saturating_sub(2 * LEGEND_INSET);
490 let offset = row.saturating_mul(LEGEND_ROW_HEIGHT as usize);
491 if w < 38 || offset.saturating_add(LEGEND_ROW_HEIGHT as usize) > h as usize {
492 return PixelRect::default();
493 }
494 PixelRect::new(
495 rect.x + (rect.w - w - LEGEND_INSET) as i32,
496 rect.y + LEGEND_INSET as i32 + offset as i32,
497 w,
498 LEGEND_ROW_HEIGHT,
499 )
500}
501
502#[derive(Clone)]
506pub struct Axes {
507 pub(super) cmds: AxesCommands,
508 pub(super) highlight: Option<usize>,
511}
512
513impl Default for Axes {
514 fn default() -> Self {
515 Self {
516 cmds: AxesCommands::new(),
517 highlight: None,
518 }
519 }
520}
521
522impl Axes {
523 pub fn title(&mut self, text: &str) {
527 self.title_color(text, Color::new(0.0, 0.0, 0.0, 0.0));
528 }
529
530 pub fn title_color(&mut self, text: &str, color: Color) {
532 self.cmds.title = text.to_owned();
533 self.cmds.title_color = color;
534 }
535
536 pub fn caption(&mut self, text: &str) {
541 self.cmds.caption = text.to_owned();
542 self.cmds.caption_color = Color::new(0.0, 0.0, 0.0, 0.0);
543 }
544
545 pub fn caption_color(&mut self, text: &str, color: Color) {
547 self.cmds.caption = text.to_owned();
548 self.cmds.caption_color = color;
549 }
550
551 pub fn x_label(&mut self, text: &str) {
553 self.cmds.x_label = text.to_owned();
554 }
555
556 pub fn y_label(&mut self, text: &str) {
558 self.cmds.y_label = text.to_owned();
559 }
560
561 pub fn imshow(&mut self, texture: crate::Texture) {
564 self.cmds.imshow = Some(ImshowCmd { texture });
565 }
566
567 pub fn heatmap(&mut self, values: &[f32], rows: i32, cols: i32, style: HeatmapStyle) {
569 let Some(count) = usize::try_from(rows).ok().and_then(|rows| {
570 usize::try_from(cols)
571 .ok()
572 .and_then(|cols| rows.checked_mul(cols))
573 }) else {
574 return;
575 };
576 if count == 0 || values.len() < count {
577 return;
578 }
579 self.cmds.heatmap = Some(Heatmap {
580 values: values[..count].to_vec(),
581 rows,
582 cols,
583 style,
584 });
585 }
586
587 pub fn heatmap_matrix(&mut self, values: crate::Matrix, style: HeatmapStyle) {
594 if values.dtype() != crate::DType::F32 || values.shape().len() != 2 {
595 return;
596 }
597 self.cmds.heatmap_matrix = Some(HeatmapMatrixCmd { values, style });
598 }
599
600 pub fn plot(&mut self, y: &[f32], style: LineStyle) {
602 if y.is_empty() {
603 return;
604 }
605 let x: Vec<f32> = (0..y.len()).map(|i| i as f32).collect();
606 self.cmds.lines.push(LineCmd {
607 x,
608 y: y.to_vec(),
609 style,
610 });
611 self.cmds.artists.push(ArtistKind::Line);
612 }
613
614 pub fn plot_xy(&mut self, x: &[f32], y: &[f32], style: LineStyle) {
616 if x.is_empty() || x.len() != y.len() {
617 return;
618 }
619 self.cmds.lines.push(LineCmd {
620 x: x.to_vec(),
621 y: y.to_vec(),
622 style,
623 });
624 self.cmds.artists.push(ArtistKind::Line);
625 }
626
627 pub fn plot_matrix(&mut self, values: &crate::Matrix, style: LineStyle) {
636 let shape = values.shape();
637 if values.dtype() != crate::DType::F32 || shape.len() != 2 || shape[0] != 2 || shape[1] == 0 {
638 return;
639 }
640 self.cmds.line_matrices.push(LineMatrixCmd {
641 values: values.clone(),
642 xy: true,
643 style,
644 });
645 self.cmds.artists.push(ArtistKind::LineMatrix);
646 }
647
648 pub fn plot_matrix_y(&mut self, values: &crate::Matrix, style: LineStyle) {
654 if values.dtype() != crate::DType::F32 || values.shape().len() != 1 || values.shape()[0] == 0 {
655 return;
656 }
657 self.cmds.line_matrices.push(LineMatrixCmd {
658 values: values.clone(),
659 xy: false,
660 style,
661 });
662 self.cmds.artists.push(ArtistKind::LineMatrix);
663 }
664
665 pub fn annotate(&mut self, text: &str, x: f32, y: f32) {
670 if text.is_empty() {
671 return;
672 }
673 self.cmds.annotations.push(AnnotationCmd {
674 text: text.to_owned(),
675 x,
676 y,
677 });
678 }
679
680 pub fn categories(&mut self, labels: &[&str]) {
684 self.cmds.categories = labels.iter().map(|label| (*label).to_owned()).collect();
685 }
686
687 pub fn xscale(&mut self, scale: Scale) {
689 self.cmds.x_scale = scale;
690 }
691
692 pub fn yscale(&mut self, scale: Scale) {
694 self.cmds.y_scale = scale;
695 }
696
697 pub fn xticks(&mut self, values: &[f32]) {
703 self.cmds.x_ticks = if values.is_empty() {
704 None
705 } else {
706 Some(values.to_vec())
707 };
708 }
709
710 pub fn yticks(&mut self, values: &[f32]) {
712 self.cmds.y_ticks = if values.is_empty() {
713 None
714 } else {
715 Some(values.to_vec())
716 };
717 }
718
719 pub fn xformat(&mut self, format: TickFormat) {
721 self.cmds.x_tick_format = format;
722 }
723
724 pub fn yformat(&mut self, format: TickFormat) {
726 self.cmds.y_tick_format = format;
727 }
728
729 pub fn scatter(&mut self, x: &[f32], y: &[f32], style: ScatterStyle) {
731 if x.is_empty() || x.len() != y.len() {
732 return;
733 }
734 self.cmds.scatters.push(ScatterCmd {
735 x: x.to_vec(),
736 y: y.to_vec(),
737 style,
738 });
739 self.cmds.artists.push(ArtistKind::Scatter);
740 }
741
742 pub fn bar(&mut self, y: &[f32], style: BarStyle) {
744 if y.is_empty() {
745 return;
746 }
747 self.cmds.bars.push(BarCmd {
748 y: y.to_vec(),
749 group: None,
750 stack_base: None,
751 style,
752 });
753 self.cmds.artists.push(ArtistKind::Bar);
754 }
755
756 pub fn bar_grouped(&mut self, series: &[&[f32]], styles: &[BarStyle]) {
762 let size = series.len();
763 if size == 0 || series.iter().any(|layer| layer.is_empty()) {
764 return;
765 }
766 for (index, layer) in series.iter().enumerate() {
767 self.cmds.bars.push(BarCmd {
768 y: (*layer).to_vec(),
769 group: Some((index, size)),
770 stack_base: None,
771 style: styles.get(index).cloned().unwrap_or_default(),
772 });
773 self.cmds.artists.push(ArtistKind::Bar);
774 }
775 }
776
777 pub fn bar_stacked(&mut self, series: &[&[f32]], styles: &[BarStyle]) {
783 if series.is_empty() || series.iter().any(|layer| layer.is_empty()) {
784 return;
785 }
786 let count = series[0].len();
787 if series.iter().any(|layer| layer.len() != count) {
788 return;
789 }
790 let mut base = vec![0.0_f32; count];
791 for (index, layer) in series.iter().enumerate() {
792 self.cmds.bars.push(BarCmd {
793 y: (*layer).to_vec(),
794 group: None,
795 stack_base: Some(base.clone()),
796 style: styles.get(index).cloned().unwrap_or_default(),
797 });
798 self.cmds.artists.push(ArtistKind::Bar);
799 for (acc, &value) in base.iter_mut().zip(layer.iter()) {
800 *acc += if value.is_finite() { value } else { 0.0 };
801 }
802 }
803 }
804
805 pub fn stream(&mut self, capacity: usize, style: LineStyle) -> usize {
811 let index = self.cmds.streams.len();
812 self.cmds.streams.push(StreamCmd {
813 values: vec![0.0; capacity.max(1)],
814 head: 0,
815 len: 0,
816 style,
817 });
818 self.cmds.artists.push(ArtistKind::Stream);
819 index
820 }
821
822 pub fn stream_push(&mut self, series: usize, values: &[f32]) {
827 if let Some(stream) = self.cmds.streams.get_mut(series) {
828 for &value in values {
829 stream.push(value);
830 }
831 }
832 }
833
834 pub fn band(&mut self, y_lo: &[f32], y_hi: &[f32], style: LineStyle) {
840 if y_lo.is_empty() || y_lo.len() != y_hi.len() {
841 return;
842 }
843 self.cmds.bands.push(BandCmd {
844 y_lo: y_lo.to_vec(),
845 y_hi: y_hi.to_vec(),
846 style,
847 });
848 self.cmds.artists.push(ArtistKind::Band);
849 }
850
851 pub fn boxplot(&mut self, datasets: &[&[f32]], style: BoxStyle) {
857 if datasets.is_empty() {
858 return;
859 }
860 let mut summaries = Vec::with_capacity(datasets.len());
861 for (index, dataset) in datasets.iter().enumerate() {
862 let mut sorted: Vec<f32> = dataset.iter().copied().filter(|v| v.is_finite()).collect();
863 if sorted.is_empty() {
864 continue;
865 }
866 sorted.sort_by(f32::total_cmp);
867 let q1 = percentile(&sorted, 0.25);
868 let median = percentile(&sorted, 0.5);
869 let q3 = percentile(&sorted, 0.75);
870 let iqr = (q3 - q1) * style.whisk;
871 let lo = sorted
872 .iter()
873 .copied()
874 .find(|&v| v >= q1 - iqr)
875 .unwrap_or(sorted[0]);
876 let hi = sorted
877 .iter()
878 .copied()
879 .rev()
880 .find(|&v| v <= q3 + iqr)
881 .unwrap_or(sorted[sorted.len() - 1]);
882 summaries.push((index as f32, q1, median, q3, lo, hi));
883 }
884 if summaries.is_empty() {
885 return;
886 }
887 self.cmds.boxes.push(BoxCmd { summaries, style });
888 self.cmds.artists.push(ArtistKind::BoxPlot);
889 }
890
891 pub fn histogram(&mut self, values: &[f32], bins: i32, style: BarStyle) {
893 if bins <= 0 || values.is_empty() {
894 return;
895 }
896 let bins = (bins as usize).min(4096);
897 let finite: Vec<f32> = values.iter().copied().filter(|v| v.is_finite()).collect();
898 if finite.is_empty() {
899 return;
900 }
901 let v_min = finite.iter().cloned().fold(f32::INFINITY, f32::min);
902 let v_max = finite.iter().cloned().fold(f32::NEG_INFINITY, f32::max);
903 let range = (v_max - v_min).max(1e-8);
904 let mut counts = vec![0.0f32; bins];
905 for &v in &finite {
906 let idx = (((v - v_min) / range) * bins as f32) as usize;
907 counts[idx.min(bins - 1)] += 1.0;
908 }
909 self.bar(&counts, style);
910 }
911
912 pub fn limits(&mut self, x_min: f32, x_max: f32, y_min: f32, y_max: f32) {
914 if [x_min, x_max, y_min, y_max]
915 .iter()
916 .all(|value| value.is_finite())
917 && x_min < x_max
918 && y_min < y_max
919 {
920 self.cmds.limits = Some(LimitsCmd {
921 x_min,
922 x_max,
923 y_min,
924 y_max,
925 });
926 } else {
927 self.auto_limits();
928 }
929 }
930
931 pub fn auto_limits(&mut self) {
933 self.cmds.limits = None;
934 }
935
936 pub fn grid(&mut self, visible: bool) {
938 self.cmds.show_grid = visible;
939 }
940
941 pub fn legend(&mut self, visible: bool) {
943 self.cmds.show_legend = visible;
944 }
945
946 pub fn border_color(&mut self, color: Color) {
948 self.cmds.border_color = Some(color);
949 }
950
951 pub fn clear(&mut self) {
953 self.cmds = AxesCommands::new();
954 }
955
956 pub fn artist_count(&self) -> usize {
958 self.cmds.artists.len()
959 }
960
961 pub fn artist_hidden(&self, index: usize) -> Option<bool> {
963 let (mut line, mut scatter, mut bar, mut matrix, mut stream, mut band, mut bx) =
964 (0usize, 0usize, 0usize, 0usize, 0usize, 0usize, 0usize);
965 for (position, kind) in self.cmds.artists.iter().enumerate() {
966 let hidden = match kind {
967 ArtistKind::Line => self.cmds.lines.get(line).map(|cmd| cmd.style.hidden),
968 ArtistKind::Scatter => self.cmds.scatters.get(scatter).map(|cmd| cmd.style.hidden),
969 ArtistKind::Bar => self.cmds.bars.get(bar).map(|cmd| cmd.style.hidden),
970 ArtistKind::LineMatrix => self
971 .cmds
972 .line_matrices
973 .get(matrix)
974 .map(|cmd| cmd.style.hidden),
975 ArtistKind::Stream => self.cmds.streams.get(stream).map(|cmd| cmd.style.hidden),
976 ArtistKind::Band => self.cmds.bands.get(band).map(|cmd| cmd.style.hidden),
977 ArtistKind::BoxPlot => self.cmds.boxes.get(bx).map(|cmd| cmd.style.hidden),
978 };
979 if position == index {
980 return hidden;
981 }
982 match kind {
983 ArtistKind::Line => line += 1,
984 ArtistKind::Scatter => scatter += 1,
985 ArtistKind::Bar => bar += 1,
986 ArtistKind::LineMatrix => matrix += 1,
987 ArtistKind::Stream => stream += 1,
988 ArtistKind::Band => band += 1,
989 ArtistKind::BoxPlot => bx += 1,
990 }
991 }
992 None
993 }
994
995 pub fn set_artist_hidden(&mut self, index: usize, hidden: bool) {
1000 let (mut line, mut scatter, mut bar, mut matrix, mut stream, mut band, mut bx) =
1001 (0usize, 0usize, 0usize, 0usize, 0usize, 0usize, 0usize);
1002 for (position, kind) in self.cmds.artists.iter().enumerate() {
1003 if position == index {
1004 match kind {
1005 ArtistKind::Line => {
1006 if let Some(cmd) = self.cmds.lines.get_mut(line) {
1007 cmd.style.hidden = hidden;
1008 }
1009 }
1010 ArtistKind::Scatter => {
1011 if let Some(cmd) = self.cmds.scatters.get_mut(scatter) {
1012 cmd.style.hidden = hidden;
1013 }
1014 }
1015 ArtistKind::Bar => {
1016 if let Some(cmd) = self.cmds.bars.get_mut(bar) {
1017 cmd.style.hidden = hidden;
1018 }
1019 }
1020 ArtistKind::LineMatrix => {
1021 if let Some(cmd) = self.cmds.line_matrices.get_mut(matrix) {
1022 cmd.style.hidden = hidden;
1023 }
1024 }
1025 ArtistKind::Stream => {
1026 if let Some(cmd) = self.cmds.streams.get_mut(stream) {
1027 cmd.style.hidden = hidden;
1028 }
1029 }
1030 ArtistKind::Band => {
1031 if let Some(cmd) = self.cmds.bands.get_mut(band) {
1032 cmd.style.hidden = hidden;
1033 }
1034 }
1035 ArtistKind::BoxPlot => {
1036 if let Some(cmd) = self.cmds.boxes.get_mut(bx) {
1037 cmd.style.hidden = hidden;
1038 }
1039 }
1040 }
1041 return;
1042 }
1043 match kind {
1044 ArtistKind::Line => line += 1,
1045 ArtistKind::Scatter => scatter += 1,
1046 ArtistKind::Bar => bar += 1,
1047 ArtistKind::LineMatrix => matrix += 1,
1048 ArtistKind::Stream => stream += 1,
1049 ArtistKind::Band => band += 1,
1050 ArtistKind::BoxPlot => bx += 1,
1051 }
1052 }
1053 }
1054
1055 pub fn set_series_highlight(&mut self, index: Option<usize>) {
1059 self.highlight = index;
1060 }
1061
1062 pub(super) fn has_ticks(&self) -> bool {
1066 !self.cmds.artists.is_empty()
1067 || !self.cmds.annotations.is_empty()
1068 || self.cmds.limits.is_some()
1069 || self.cmds.x_ticks.is_some()
1070 || self.cmds.y_ticks.is_some()
1071 || !self.cmds.categories.is_empty()
1072 }
1073
1074 pub(super) fn layout(&self, cell: PixelRect) -> AxesLayout {
1079 let colorbar = self
1080 .cmds
1081 .heatmap
1082 .as_ref()
1083 .is_some_and(|heatmap| heatmap.style.colorbar)
1084 || self
1085 .cmds
1086 .heatmap_matrix
1087 .as_ref()
1088 .is_some_and(|heatmap| heatmap.style.colorbar);
1089 let reserve = |budget: &mut u32, pixels: u32| {
1092 let pixels = pixels.min(*budget);
1093 *budget -= pixels;
1094 pixels
1095 };
1096 let mut width_budget = cell.w / 2;
1097 let mut height_budget = cell.h / 2;
1098 let ticks = self.has_ticks() && cell.w >= 64 && cell.h >= 36;
1099 let colorbar_w = reserve(
1100 &mut width_budget,
1101 if colorbar { COLORBAR_RESERVE } else { 0 },
1102 );
1103 let y_label_w = reserve(
1104 &mut width_budget,
1105 if self.cmds.y_label.is_empty() { 0 } else { 19 },
1106 );
1107 let right = reserve(&mut width_budget, if ticks && !colorbar { 15 } else { 0 });
1108 let y_ticks_w = reserve(&mut width_budget, if ticks { 48 } else { 0 });
1109 let top = reserve(
1110 &mut height_budget,
1111 if !self.cmds.title.is_empty() {
1112 22
1113 } else if ticks {
1114 8
1115 } else {
1116 0
1117 },
1118 );
1119 let x_label_h = reserve(
1120 &mut height_budget,
1121 if self.cmds.x_label.is_empty() { 0 } else { 19 },
1122 );
1123 let x_ticks_h = reserve(&mut height_budget, if ticks { 18 } else { 0 });
1124 let caption_h = reserve(
1125 &mut height_budget,
1126 if self.cmds.caption.is_empty() { 0 } else { 18 },
1127 );
1128 let x = cell.x + (y_label_w + y_ticks_w) as i32;
1129 let y = cell.y + top as i32;
1130 let w = cell.w - y_label_w - y_ticks_w - right - colorbar_w;
1131 let h = cell.h - top - x_ticks_h - x_label_h - caption_h;
1132 let bottom = y + h as i32;
1133 AxesLayout {
1134 plot: PixelRect::new(x, y, w, h),
1135 title: PixelRect::new(x, cell.y, w, top),
1136 caption: PixelRect::new(x, bottom + (x_ticks_h + x_label_h) as i32, w, caption_h),
1137 x_ticks: PixelRect::new(cell.x, bottom, cell.w - colorbar_w, x_ticks_h),
1138 y_ticks: PixelRect::new(
1139 cell.x + y_label_w as i32,
1140 cell.y,
1141 y_ticks_w,
1142 top + h + x_ticks_h,
1143 ),
1144 x_label: PixelRect::new(x, bottom + x_ticks_h as i32, w, x_label_h),
1145 y_label: PixelRect::new(cell.x, y, y_label_w, h),
1146 }
1147 }
1148
1149 pub(super) fn legend_entries(&self, palette: &[crate::Color]) -> Vec<LegendEntry> {
1155 let mut entries = Vec::new();
1156 let (mut line, mut scatter, mut bar, mut matrix, mut stream, mut band, mut bx) =
1157 (0usize, 0usize, 0usize, 0usize, 0usize, 0usize, 0usize);
1158 let mut palette_idx = 0usize;
1159 for (position, kind) in self.cmds.artists.iter().enumerate() {
1160 let (label, color, hidden) = match kind {
1161 ArtistKind::Line => {
1162 let Some(cmd) = self.cmds.lines.get(line) else {
1163 continue;
1164 };
1165 line += 1;
1166 (&cmd.style.label, cmd.style.color, cmd.style.hidden)
1167 }
1168 ArtistKind::Scatter => {
1169 let Some(cmd) = self.cmds.scatters.get(scatter) else {
1170 continue;
1171 };
1172 scatter += 1;
1173 (&cmd.style.label, cmd.style.color, cmd.style.hidden)
1174 }
1175 ArtistKind::Bar => {
1176 let Some(cmd) = self.cmds.bars.get(bar) else {
1177 continue;
1178 };
1179 bar += 1;
1180 (&cmd.style.label, cmd.style.color, cmd.style.hidden)
1181 }
1182 ArtistKind::LineMatrix => {
1183 let Some(cmd) = self.cmds.line_matrices.get(matrix) else {
1184 continue;
1185 };
1186 matrix += 1;
1187 (&cmd.style.label, cmd.style.color, cmd.style.hidden)
1188 }
1189 ArtistKind::Stream => {
1190 let Some(cmd) = self.cmds.streams.get(stream) else {
1191 continue;
1192 };
1193 stream += 1;
1194 (&cmd.style.label, cmd.style.color, cmd.style.hidden)
1195 }
1196 ArtistKind::Band => {
1197 let Some(cmd) = self.cmds.bands.get(band) else {
1198 continue;
1199 };
1200 band += 1;
1201 (&cmd.style.label, cmd.style.color, cmd.style.hidden)
1202 }
1203 ArtistKind::BoxPlot => {
1204 let Some(cmd) = self.cmds.boxes.get(bx) else {
1205 continue;
1206 };
1207 bx += 1;
1208 (&cmd.style.label, cmd.style.color, cmd.style.hidden)
1209 }
1210 };
1211 let color = if color.a == 0.0 {
1212 let resolved = palette[palette_idx % palette.len()];
1213 palette_idx += 1;
1214 resolved
1215 } else {
1216 color
1217 };
1218 entries.push(LegendEntry {
1219 artist: position,
1220 label: label.clone(),
1221 color,
1222 hidden,
1223 row: usize::MAX,
1224 });
1225 }
1226 let mut row = 0usize;
1227 for entry in &mut entries {
1228 if !entry.label.is_empty() {
1229 entry.row = row;
1230 row += 1;
1231 }
1232 }
1233 entries
1234 }
1235
1236 pub(super) fn data_y_range(&self) -> (f32, f32) {
1240 let mut y_min = f32::INFINITY;
1241 let mut y_max = f32::NEG_INFINITY;
1242 for line in &self.cmds.lines {
1243 for &v in &line.y {
1244 if v.is_finite() {
1245 y_min = y_min.min(v);
1246 y_max = y_max.max(v);
1247 }
1248 }
1249 }
1250 for scatter in &self.cmds.scatters {
1251 for &value in &scatter.y {
1252 if value.is_finite() {
1253 y_min = y_min.min(value);
1254 y_max = y_max.max(value);
1255 }
1256 }
1257 }
1258 for bar in &self.cmds.bars {
1259 for (index, &v) in bar.y.iter().enumerate() {
1260 if v.is_finite() {
1261 let base = bar.stack_base.as_ref().map_or(0.0, |bases| bases[index]);
1262 y_min = y_min.min((base + v).min(base.min(0.0)));
1263 y_max = y_max.max((base + v).max(base.max(0.0)));
1264 }
1265 }
1266 }
1267 for stream in &self.cmds.streams {
1268 for value in stream.ordered() {
1269 if value.is_finite() {
1270 y_min = y_min.min(value);
1271 y_max = y_max.max(value);
1272 }
1273 }
1274 }
1275 for band in &self.cmds.bands {
1276 for &value in band.y_lo.iter().chain(&band.y_hi) {
1277 if value.is_finite() {
1278 y_min = y_min.min(value);
1279 y_max = y_max.max(value);
1280 }
1281 }
1282 }
1283 for boxes in &self.cmds.boxes {
1284 for &(_, _, _, _, lo, hi) in &boxes.summaries {
1285 y_min = y_min.min(lo);
1286 y_max = y_max.max(hi);
1287 }
1288 }
1289 if !y_min.is_finite() || !y_max.is_finite() {
1290 return (0.0, 1.0);
1291 }
1292 if (y_max - y_min).abs() < 1e-6 {
1293 return (y_min - 1.0, y_max + 1.0);
1294 }
1295 (y_min, y_max)
1296 }
1297
1298 pub fn data_limits(&self) -> [f32; 4] {
1302 let limits = self.effective_limits();
1303 [limits.x_min, limits.x_max, limits.y_min, limits.y_max]
1304 }
1305
1306 pub fn explicit_limits(&self) -> Option<[f32; 4]> {
1308 self
1309 .cmds
1310 .limits
1311 .as_ref()
1312 .map(|l| [l.x_min, l.x_max, l.y_min, l.y_max])
1313 }
1314
1315 pub(super) fn effective_limits(&self) -> LimitsCmd {
1317 if let Some(lim) = &self.cmds.limits {
1318 return lim.clone();
1319 }
1320 let (y_min, y_max) = self.data_y_range();
1321 let mut x_min = f32::INFINITY;
1322 let mut x_max = f32::NEG_INFINITY;
1323 for value in self
1324 .cmds
1325 .lines
1326 .iter()
1327 .flat_map(|line| line.x.iter())
1328 .chain(
1329 self
1330 .cmds
1331 .scatters
1332 .iter()
1333 .flat_map(|scatter| scatter.x.iter()),
1334 )
1335 .copied()
1336 .filter(|value| value.is_finite())
1337 {
1338 x_min = x_min.min(value);
1339 x_max = x_max.max(value);
1340 }
1341 for bar in &self.cmds.bars {
1342 x_min = x_min.min(0.0);
1343 x_max = x_max.max(bar.y.len().saturating_sub(1) as f32);
1344 }
1345 for matrix in &self.cmds.line_matrices {
1346 if !matrix.xy {
1347 let count = matrix.values.shape().first().copied().unwrap_or(0);
1348 x_min = x_min.min(0.0);
1349 x_max = x_max.max(count.saturating_sub(1) as f32);
1350 }
1351 }
1352 for stream in &self.cmds.streams {
1353 if stream.len == 0 {
1354 continue;
1355 }
1356 x_min = x_min.min(0.0);
1357 x_max = x_max.max(stream.values.len().saturating_sub(1) as f32);
1358 }
1359 for band in &self.cmds.bands {
1360 x_min = x_min.min(0.0);
1361 x_max = x_max.max(band.y_lo.len().saturating_sub(1) as f32);
1362 }
1363 for boxes in &self.cmds.boxes {
1364 x_min = x_min.min(0.0);
1365 x_max = x_max.max(boxes.summaries.len().saturating_sub(1) as f32);
1366 }
1367 if !x_min.is_finite() || !x_max.is_finite() || (x_max - x_min).abs() < 1e-6 {
1368 x_min = 0.0;
1369 x_max = 1.0;
1370 }
1371 LimitsCmd {
1372 x_min,
1373 x_max,
1374 y_min,
1375 y_max,
1376 }
1377 }
1378
1379 pub(super) fn scaled_limits(&self) -> LimitsCmd {
1384 let raw = self.effective_limits();
1385 let (x_min, x_max) = scaled_axis(
1386 raw.x_min,
1387 raw.x_max,
1388 self.cmds.x_scale,
1389 self.min_positive_x(),
1390 );
1391 let (y_min, y_max) = scaled_axis(
1392 raw.y_min,
1393 raw.y_max,
1394 self.cmds.y_scale,
1395 self.min_positive_y(),
1396 );
1397 LimitsCmd {
1398 x_min,
1399 x_max,
1400 y_min,
1401 y_max,
1402 }
1403 }
1404
1405 fn min_positive_x(&self) -> Option<f32> {
1407 let mut min = f32::INFINITY;
1408 for value in self.cmds.lines.iter().flat_map(|line| line.x.iter()).chain(
1409 self
1410 .cmds
1411 .scatters
1412 .iter()
1413 .flat_map(|scatter| scatter.x.iter()),
1414 ) {
1415 if value.is_finite() && *value > 0.0 {
1416 min = min.min(*value);
1417 }
1418 }
1419 for bars in &self.cmds.bars {
1420 if bars.y.len() > 1 {
1421 min = min.min(1.0);
1422 }
1423 }
1424 min.is_finite().then_some(min)
1425 }
1426
1427 fn min_positive_y(&self) -> Option<f32> {
1429 let mut min = f32::INFINITY;
1430 for value in self
1431 .cmds
1432 .lines
1433 .iter()
1434 .flat_map(|line| line.y.iter())
1435 .chain(
1436 self
1437 .cmds
1438 .scatters
1439 .iter()
1440 .flat_map(|scatter| scatter.y.iter()),
1441 )
1442 .chain(self.cmds.bars.iter().flat_map(|bars| bars.y.iter()))
1443 {
1444 if value.is_finite() && *value > 0.0 {
1445 min = min.min(*value);
1446 }
1447 }
1448 min.is_finite().then_some(min)
1449 }
1450}
1451
1452fn percentile(sorted: &[f32], q: f32) -> f32 {
1454 let pos = q * (sorted.len() - 1) as f32;
1455 let lo = pos.floor() as usize;
1456 let hi = (lo + 1).min(sorted.len() - 1);
1457 sorted[lo] + (sorted[hi] - sorted[lo]) * (pos - lo as f32)
1458}