bland 0.2.0

Pure-Rust library for paper-ready, monochrome, hatch-patterned technical plots in the visual tradition of 1960s-80s engineering reports.
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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
//! Series data structures and per-series option builders.
//!
//! Each series type carries data plus optional style overrides. The
//! renderer fills in cycling defaults (stroke / hatch / marker) for
//! anything left unset.

use crate::hatch::Hatch;
use crate::markers::Marker;
use crate::stats::{boxplot_stats, BoxStats};
use crate::strokes::Stroke;

#[derive(Debug, Clone)]
pub(crate) enum Series {
    Line(LineSeries),
    Scatter(ScatterSeries),
    Bar(BarSeries),
    Area(AreaSeries),
    Polygon(PolygonSeries),
    ErrorBar(ErrorBarSeries),
    BoxPlot(BoxPlotSeries),
    Stem(StemSeries),
    Quiver(QuiverSeries),
    Contour(ContourSeries),
    Histogram(HistogramSeries),
    Heatmap(HeatmapSeries),
    Hline(HlineSeries),
    Vline(VlineSeries),
}

// --- Line ----------------------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct LineSeries {
    pub xs: Vec<f64>,
    pub ys: Vec<f64>,
    pub label: Option<String>,
    pub stroke: Option<Stroke>,
    pub stroke_width: Option<f64>,
    pub markers: bool,
    pub marker: Option<Marker>,
    pub marker_size: Option<f64>,
}

/// Per-call options for [`Figure::line`](crate::Figure::line).
#[derive(Debug, Default)]
pub struct LineOpts {
    pub(crate) label: Option<String>,
    pub(crate) stroke: Option<Stroke>,
    pub(crate) stroke_width: Option<f64>,
    pub(crate) markers: bool,
    pub(crate) marker: Option<Marker>,
    pub(crate) marker_size: Option<f64>,
}

impl LineOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    pub fn stroke(mut self, s: Stroke) -> Self {
        self.stroke = Some(s);
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
    pub fn markers(mut self) -> Self {
        self.markers = true;
        self
    }
    pub fn marker(mut self, m: Marker) -> Self {
        self.markers = true;
        self.marker = Some(m);
        self
    }
    pub fn marker_size(mut self, sz: f64) -> Self {
        self.marker_size = Some(sz);
        self
    }
}

// --- Scatter -------------------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct ScatterSeries {
    pub xs: Vec<f64>,
    pub ys: Vec<f64>,
    pub label: Option<String>,
    pub marker: Option<Marker>,
    pub marker_size: Option<f64>,
    pub stroke_width: Option<f64>,
}

#[derive(Debug, Default)]
pub struct ScatterOpts {
    pub(crate) label: Option<String>,
    pub(crate) marker: Option<Marker>,
    pub(crate) marker_size: Option<f64>,
    pub(crate) stroke_width: Option<f64>,
}

impl ScatterOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    pub fn marker(mut self, m: Marker) -> Self {
        self.marker = Some(m);
        self
    }
    pub fn marker_size(mut self, sz: f64) -> Self {
        self.marker_size = Some(sz);
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
}

// --- Bar -----------------------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct BarSeries {
    pub categories: Vec<String>,
    pub values: Vec<f64>,
    pub label: Option<String>,
    pub hatch: Option<Hatch>,
    pub group: u32,
    pub stroke_width: Option<f64>,
}

#[derive(Debug, Default)]
pub struct BarOpts {
    pub(crate) label: Option<String>,
    pub(crate) hatch: Option<Hatch>,
    pub(crate) group: u32,
    pub(crate) stroke_width: Option<f64>,
}

impl BarOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    pub fn hatch(mut self, h: Hatch) -> Self {
        self.hatch = Some(h);
        self
    }
    pub fn group(mut self, g: u32) -> Self {
        self.group = g;
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
}

// --- Area ----------------------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct AreaSeries {
    pub xs: Vec<f64>,
    pub ys: Vec<f64>,
    pub label: Option<String>,
    pub hatch: Option<Hatch>,
    pub baseline: f64,
    pub stroke: Option<Stroke>,
    pub stroke_width: Option<f64>,
}

#[derive(Debug)]
pub struct AreaOpts {
    pub(crate) label: Option<String>,
    pub(crate) hatch: Option<Hatch>,
    pub(crate) baseline: f64,
    pub(crate) stroke: Option<Stroke>,
    pub(crate) stroke_width: Option<f64>,
}

impl Default for AreaOpts {
    fn default() -> Self {
        Self {
            label: None,
            hatch: None,
            baseline: 0.0,
            stroke: None,
            stroke_width: None,
        }
    }
}

impl AreaOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    pub fn hatch(mut self, h: Hatch) -> Self {
        self.hatch = Some(h);
        self
    }
    pub fn baseline(mut self, b: f64) -> Self {
        self.baseline = b;
        self
    }
    pub fn stroke(mut self, s: Stroke) -> Self {
        self.stroke = Some(s);
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
}

// --- Polygon -------------------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct PolygonSeries {
    pub xs: Vec<f64>,
    pub ys: Vec<f64>,
    pub label: Option<String>,
    pub hatch: Option<Hatch>,
    pub stroke: Stroke,
    pub stroke_width: Option<f64>,
}

#[derive(Debug)]
pub struct PolygonOpts {
    pub(crate) label: Option<String>,
    pub(crate) hatch: Option<Hatch>,
    pub(crate) stroke: Stroke,
    pub(crate) stroke_width: Option<f64>,
}

impl Default for PolygonOpts {
    fn default() -> Self {
        Self {
            label: None,
            hatch: None,
            stroke: Stroke::Solid,
            stroke_width: None,
        }
    }
}

impl PolygonOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    pub fn hatch(mut self, h: Hatch) -> Self {
        self.hatch = Some(h);
        self
    }
    pub fn stroke(mut self, s: Stroke) -> Self {
        self.stroke = s;
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
}

// --- ErrorBar ------------------------------------------------------------

/// Per-point error: either symmetric half-width or `(lower, upper)`.
#[derive(Debug, Clone, Copy)]
pub enum Err {
    Symmetric(f64),
    Asymmetric(f64, f64),
}

#[derive(Debug, Clone)]
pub(crate) struct ErrorBarSeries {
    pub xs: Vec<f64>,
    pub ys: Vec<f64>,
    pub yerr: Option<Vec<Err>>,
    pub xerr: Option<Vec<Err>>,
    pub marker: Option<Marker>,
    pub marker_size: Option<f64>,
    pub cap_width: f64,
    pub stroke_width: Option<f64>,
    pub label: Option<String>,
}

#[derive(Debug)]
pub struct ErrorBarOpts {
    pub(crate) yerr: Option<Vec<Err>>,
    pub(crate) xerr: Option<Vec<Err>>,
    pub(crate) marker: Option<Marker>,
    pub(crate) marker_size: Option<f64>,
    pub(crate) cap_width: f64,
    pub(crate) stroke_width: Option<f64>,
    pub(crate) label: Option<String>,
}

impl Default for ErrorBarOpts {
    fn default() -> Self {
        Self {
            yerr: None,
            xerr: None,
            marker: Some(Marker::CircleFilled),
            marker_size: None,
            cap_width: 8.0,
            stroke_width: None,
            label: None,
        }
    }
}

impl ErrorBarOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    /// Symmetric y error: `yerr[i]` is the half-width above and below.
    pub fn yerr(mut self, e: &[f64]) -> Self {
        self.yerr = Some(e.iter().map(|v| Err::Symmetric(*v)).collect());
        self
    }
    /// Asymmetric y error: each entry is `(lower, upper)` half-widths.
    pub fn yerr_asym(mut self, e: &[(f64, f64)]) -> Self {
        self.yerr = Some(e.iter().map(|(l, u)| Err::Asymmetric(*l, *u)).collect());
        self
    }
    pub fn xerr(mut self, e: &[f64]) -> Self {
        self.xerr = Some(e.iter().map(|v| Err::Symmetric(*v)).collect());
        self
    }
    pub fn xerr_asym(mut self, e: &[(f64, f64)]) -> Self {
        self.xerr = Some(e.iter().map(|(l, u)| Err::Asymmetric(*l, *u)).collect());
        self
    }
    pub fn marker(mut self, m: Marker) -> Self {
        self.marker = Some(m);
        self
    }
    pub fn no_marker(mut self) -> Self {
        self.marker = None;
        self
    }
    pub fn marker_size(mut self, sz: f64) -> Self {
        self.marker_size = Some(sz);
        self
    }
    pub fn cap_width(mut self, w: f64) -> Self {
        self.cap_width = w;
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
}

// --- BoxPlot -------------------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct BoxPlotSeries {
    pub categories: Vec<String>,
    pub stats: Vec<BoxStats>,
    pub label: Option<String>,
    pub hatch: Option<Hatch>,
    pub box_width: f64,
    pub stroke_width: Option<f64>,
}

#[derive(Debug)]
pub struct BoxPlotOpts {
    pub(crate) label: Option<String>,
    pub(crate) hatch: Option<Hatch>,
    pub(crate) box_width: f64,
    pub(crate) whisker_iqr: f64,
    pub(crate) stroke_width: Option<f64>,
}

impl Default for BoxPlotOpts {
    fn default() -> Self {
        Self {
            label: None,
            hatch: None,
            box_width: 0.6,
            whisker_iqr: 1.5,
            stroke_width: None,
        }
    }
}

impl BoxPlotOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    pub fn hatch(mut self, h: Hatch) -> Self {
        self.hatch = Some(h);
        self
    }
    pub fn box_width(mut self, w: f64) -> Self {
        self.box_width = w;
        self
    }
    pub fn whisker_iqr(mut self, k: f64) -> Self {
        self.whisker_iqr = k;
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
}

pub(crate) fn build_boxplot_series(
    samples_by_category: &[(String, Vec<f64>)],
    opts: BoxPlotOpts,
) -> BoxPlotSeries {
    let mut categories = Vec::with_capacity(samples_by_category.len());
    let mut stats = Vec::with_capacity(samples_by_category.len());
    for (cat, samples) in samples_by_category {
        categories.push(cat.clone());
        stats.push(boxplot_stats(samples, opts.whisker_iqr));
    }
    BoxPlotSeries {
        categories,
        stats,
        label: opts.label,
        hatch: opts.hatch,
        box_width: opts.box_width,
        stroke_width: opts.stroke_width,
    }
}

// --- Stem ----------------------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct StemSeries {
    pub xs: Vec<f64>,
    pub ys: Vec<f64>,
    pub baseline: f64,
    pub label: Option<String>,
    pub stroke: Stroke,
    pub stroke_width: Option<f64>,
    pub marker: Option<Marker>,
    pub marker_size: Option<f64>,
}

#[derive(Debug)]
pub struct StemOpts {
    pub(crate) baseline: f64,
    pub(crate) label: Option<String>,
    pub(crate) stroke: Stroke,
    pub(crate) stroke_width: Option<f64>,
    pub(crate) marker: Option<Marker>,
    pub(crate) marker_size: Option<f64>,
}

impl Default for StemOpts {
    fn default() -> Self {
        Self {
            baseline: 0.0,
            label: None,
            stroke: Stroke::Solid,
            stroke_width: None,
            marker: Some(Marker::CircleFilled),
            marker_size: None,
        }
    }
}

impl StemOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    pub fn baseline(mut self, b: f64) -> Self {
        self.baseline = b;
        self
    }
    pub fn stroke(mut self, s: Stroke) -> Self {
        self.stroke = s;
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
    pub fn marker(mut self, m: Marker) -> Self {
        self.marker = Some(m);
        self
    }
    pub fn no_marker(mut self) -> Self {
        self.marker = None;
        self
    }
    pub fn marker_size(mut self, sz: f64) -> Self {
        self.marker_size = Some(sz);
        self
    }
}

// --- Quiver --------------------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct QuiverSeries {
    pub xs: Vec<f64>,
    pub ys: Vec<f64>,
    pub us: Vec<f64>,
    pub vs: Vec<f64>,
    pub scale: f64,
    pub head_size: f64,
    pub label: Option<String>,
    pub stroke: Stroke,
    pub stroke_width: Option<f64>,
}

#[derive(Debug)]
pub struct QuiverOpts {
    pub(crate) scale: f64,
    pub(crate) head_size: f64,
    pub(crate) label: Option<String>,
    pub(crate) stroke: Stroke,
    pub(crate) stroke_width: Option<f64>,
}

impl Default for QuiverOpts {
    fn default() -> Self {
        Self {
            scale: 1.0,
            head_size: 6.0,
            label: None,
            stroke: Stroke::Solid,
            stroke_width: None,
        }
    }
}

impl QuiverOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    pub fn scale(mut self, s: f64) -> Self {
        self.scale = s;
        self
    }
    pub fn head_size(mut self, h: f64) -> Self {
        self.head_size = h;
        self
    }
    pub fn stroke(mut self, s: Stroke) -> Self {
        self.stroke = s;
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
}

// --- Contour -------------------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct ContourSeries {
    pub data: Vec<Vec<f64>>,
    pub x_edges: Vec<f64>,
    pub y_edges: Vec<f64>,
    pub levels: Vec<f64>,
    pub origin: Origin,
    pub stroke: Stroke,
    pub stroke_width: Option<f64>,
    pub label: Option<String>,
}

#[derive(Debug)]
pub struct ContourOpts {
    pub(crate) x_edges: Option<Vec<f64>>,
    pub(crate) y_edges: Option<Vec<f64>>,
    pub(crate) levels: Option<Vec<f64>>,
    pub(crate) origin: Origin,
    pub(crate) stroke: Stroke,
    pub(crate) stroke_width: Option<f64>,
    pub(crate) label: Option<String>,
}

impl Default for ContourOpts {
    fn default() -> Self {
        Self {
            x_edges: None,
            y_edges: None,
            levels: None,
            origin: Origin::default(),
            stroke: Stroke::Solid,
            stroke_width: None,
            label: None,
        }
    }
}

impl ContourOpts {
    pub fn x_edges(mut self, e: Vec<f64>) -> Self {
        self.x_edges = Some(e);
        self
    }
    pub fn y_edges(mut self, e: Vec<f64>) -> Self {
        self.y_edges = Some(e);
        self
    }
    pub fn levels(mut self, l: Vec<f64>) -> Self {
        self.levels = Some(l);
        self
    }
    pub fn origin(mut self, o: Origin) -> Self {
        self.origin = o;
        self
    }
    pub fn stroke(mut self, s: Stroke) -> Self {
        self.stroke = s;
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
}

// --- Histogram -----------------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct HistogramSeries {
    pub bin_edges: Vec<f64>,
    pub values: Vec<f64>,
    pub label: Option<String>,
    pub hatch: Option<Hatch>,
    pub stroke_width: Option<f64>,
}

#[derive(Debug, Default)]
pub struct HistogramOpts {
    pub(crate) label: Option<String>,
    pub(crate) hatch: Option<Hatch>,
    pub(crate) stroke_width: Option<f64>,
    pub(crate) bins: Option<BinStrategy>,
    pub(crate) bin_edges: Option<Vec<f64>>,
    pub(crate) normalize: Normalize,
}

/// Normalization mode for histogram bin values.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Normalize {
    /// Raw integer counts per bin.
    #[default]
    Count,
    /// Probability mass: `count / total`. Σ values = 1.
    Pmf,
    /// Density: `count / (total · width)`. ∫ values dx = 1.
    Density,
    /// Cumulative mass (empirical CDF). Rendered as a staircase line
    /// rather than bars.
    Cmf,
}

/// Strategy for picking the number of bins when `bin_edges` is not set.
#[derive(Debug, Clone, Copy)]
pub enum BinStrategy {
    Fixed(usize),
    Sturges,
    Sqrt,
    Scott,
    FreedmanDiaconis,
}

impl HistogramOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    pub fn hatch(mut self, h: Hatch) -> Self {
        self.hatch = Some(h);
        self
    }
    pub fn bins(mut self, n: usize) -> Self {
        self.bins = Some(BinStrategy::Fixed(n));
        self
    }
    pub fn bin_strategy(mut self, s: BinStrategy) -> Self {
        self.bins = Some(s);
        self
    }
    pub fn bin_edges(mut self, edges: Vec<f64>) -> Self {
        self.bin_edges = Some(edges);
        self
    }
    pub fn normalize(mut self, n: Normalize) -> Self {
        self.normalize = n;
        self
    }
    pub fn density(mut self) -> Self {
        self.normalize = Normalize::Density;
        self
    }
}

// --- Heatmap -------------------------------------------------------------

#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Origin {
    #[default]
    BottomLeft,
    TopLeft,
}

#[derive(Debug, Clone)]
pub(crate) struct HeatmapSeries {
    pub data: Vec<Vec<f64>>,
    pub x_edges: Vec<f64>,
    pub y_edges: Vec<f64>,
    pub ramp: Vec<Hatch>,
    pub range: Option<(f64, f64)>,
    pub origin: Origin,
    #[allow(dead_code)]
    pub label: Option<String>,
}

// --- Reference lines -----------------------------------------------------

#[derive(Debug, Clone)]
pub(crate) struct HlineSeries {
    pub y: f64,
    pub label: Option<String>,
    pub stroke: Stroke,
    pub stroke_width: f64,
}

#[derive(Debug, Default)]
pub struct HlineOpts {
    pub(crate) label: Option<String>,
    pub(crate) stroke: Option<Stroke>,
    pub(crate) stroke_width: Option<f64>,
}

impl HlineOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    pub fn stroke(mut self, s: Stroke) -> Self {
        self.stroke = Some(s);
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
}

#[derive(Debug, Clone)]
pub(crate) struct VlineSeries {
    pub x: f64,
    pub label: Option<String>,
    pub stroke: Stroke,
    pub stroke_width: f64,
}

#[derive(Debug, Default)]
pub struct VlineOpts {
    pub(crate) label: Option<String>,
    pub(crate) stroke: Option<Stroke>,
    pub(crate) stroke_width: Option<f64>,
}

impl VlineOpts {
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
    pub fn stroke(mut self, s: Stroke) -> Self {
        self.stroke = Some(s);
        self
    }
    pub fn stroke_width(mut self, w: f64) -> Self {
        self.stroke_width = Some(w);
        self
    }
}

// --- Histogram binning helpers ------------------------------------------

pub(crate) fn bin_observations(
    observations: &[f64],
    opts: &HistogramOpts,
) -> (Vec<f64>, Vec<f64>) {
    let edges = match &opts.bin_edges {
        Some(e) if e.len() >= 2 => e.clone(),
        _ => auto_edges(observations, opts.bins.unwrap_or(BinStrategy::Sturges)),
    };
    let counts = count_in(observations, &edges);
    let values = normalize_counts(&counts, &edges, opts.normalize);
    (edges, values)
}

fn auto_edges(observations: &[f64], strategy: BinStrategy) -> Vec<f64> {
    if observations.is_empty() {
        return vec![0.0, 1.0];
    }
    let (mut lo, mut hi) = min_max(observations);
    if lo == hi {
        if lo == 0.0 {
            lo = -0.5;
            hi = 0.5;
        } else {
            let pad = lo.abs() * 0.1;
            lo -= pad;
            hi += pad;
        }
    }
    let n = observations.len();
    let k = resolve_bin_count(observations, strategy, n, lo, hi).max(1);
    let step = (hi - lo) / k as f64;
    (0..=k).map(|i| lo + i as f64 * step).collect()
}

fn resolve_bin_count(obs: &[f64], strategy: BinStrategy, n: usize, lo: f64, hi: f64) -> usize {
    match strategy {
        BinStrategy::Fixed(k) => k.max(1),
        BinStrategy::Sturges => ((n as f64).log2() + 1.0).ceil() as usize,
        BinStrategy::Sqrt => (n as f64).sqrt().ceil() as usize,
        BinStrategy::Scott => {
            let sigma = stddev(obs);
            if sigma <= 0.0 {
                return (n as f64).sqrt().ceil() as usize;
            }
            let h = 3.49 * sigma * (n as f64).powf(-1.0 / 3.0);
            if h <= 0.0 {
                (n as f64).sqrt().ceil() as usize
            } else {
                ((hi - lo) / h).ceil() as usize
            }
        }
        BinStrategy::FreedmanDiaconis => {
            let q = iqr(obs);
            if q <= 0.0 {
                return (n as f64).sqrt().ceil() as usize;
            }
            let h = 2.0 * q * (n as f64).powf(-1.0 / 3.0);
            if h <= 0.0 {
                (n as f64).sqrt().ceil() as usize
            } else {
                ((hi - lo) / h).ceil() as usize
            }
        }
    }
}

fn count_in(observations: &[f64], edges: &[f64]) -> Vec<usize> {
    let n_bins = edges.len() - 1;
    let mut counts = vec![0usize; n_bins];
    let last = n_bins - 1;
    for &v in observations {
        if v.is_nan() {
            continue;
        }
        for i in 0..n_bins {
            let lo = edges[i];
            let hi = edges[i + 1];
            let in_bin = if i == last {
                v >= lo && v <= hi
            } else {
                v >= lo && v < hi
            };
            if in_bin {
                counts[i] += 1;
                break;
            }
        }
    }
    counts
}

fn normalize_counts(counts: &[usize], edges: &[f64], mode: Normalize) -> Vec<f64> {
    match mode {
        Normalize::Count => counts.iter().map(|c| *c as f64).collect(),
        Normalize::Pmf => {
            let total: usize = counts.iter().sum();
            if total == 0 {
                return counts.iter().map(|c| *c as f64).collect();
            }
            counts.iter().map(|c| *c as f64 / total as f64).collect()
        }
        Normalize::Density => {
            let total: usize = counts.iter().sum();
            counts
                .iter()
                .enumerate()
                .map(|(i, c)| {
                    let w = edges[i + 1] - edges[i];
                    if total == 0 || w == 0.0 {
                        0.0
                    } else {
                        *c as f64 / (total as f64 * w)
                    }
                })
                .collect()
        }
        Normalize::Cmf => {
            let total: usize = counts.iter().sum();
            if total == 0 {
                return counts.iter().map(|c| *c as f64).collect();
            }
            let mut acc = 0.0;
            counts
                .iter()
                .map(|c| {
                    acc += *c as f64 / total as f64;
                    acc
                })
                .collect()
        }
    }
}

/// Convert `(bin_edges, cumulative)` into a staircase polyline `(xs, ys)`
/// suitable for rendering as a line series. Starts at `(edges[0], 0)`,
/// holds at the previous level across each bin, then steps up at the
/// right edge.
pub fn staircase(edges: &[f64], cumulative: &[f64]) -> (Vec<f64>, Vec<f64>) {
    if edges.is_empty() {
        return (Vec::new(), Vec::new());
    }
    if cumulative.is_empty() {
        let xs = edges.to_vec();
        let ys = vec![0.0; edges.len()];
        return (xs, ys);
    }
    let mut xs = Vec::with_capacity(2 * cumulative.len() + 1);
    let mut ys = Vec::with_capacity(2 * cumulative.len() + 1);
    xs.push(edges[0]);
    ys.push(0.0);
    let mut prev = 0.0;
    for (i, &cum) in cumulative.iter().enumerate() {
        let edge = edges[i + 1];
        xs.push(edge);
        ys.push(prev);
        xs.push(edge);
        ys.push(cum);
        prev = cum;
    }
    (xs, ys)
}

fn min_max(values: &[f64]) -> (f64, f64) {
    let mut lo = f64::INFINITY;
    let mut hi = f64::NEG_INFINITY;
    for &v in values {
        if v < lo {
            lo = v;
        }
        if v > hi {
            hi = v;
        }
    }
    (lo, hi)
}

fn stddev(values: &[f64]) -> f64 {
    let n = values.len();
    if n == 0 {
        return 0.0;
    }
    let mean = values.iter().sum::<f64>() / n as f64;
    let var = values.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / n as f64;
    var.sqrt()
}

fn iqr(values: &[f64]) -> f64 {
    let mut sorted: Vec<f64> = values.iter().copied().filter(|v| !v.is_nan()).collect();
    sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
    if sorted.len() < 2 {
        return 0.0;
    }
    let q1 = percentile(&sorted, 0.25);
    let q3 = percentile(&sorted, 0.75);
    q3 - q1
}

fn percentile(sorted: &[f64], p: f64) -> f64 {
    let n = sorted.len();
    let rank = p * (n - 1) as f64;
    let lo = rank.trunc() as usize;
    let hi = (lo + 1).min(n - 1);
    let frac = rank - lo as f64;
    sorted[lo] + frac * (sorted[hi] - sorted[lo])
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pmf_sums_to_one() {
        let opts = HistogramOpts::default()
            .bins(3)
            .normalize(Normalize::Pmf);
        let (_, vs) = bin_observations(&[1.0, 2.0, 2.0, 3.0, 3.0, 3.0], &opts);
        let sum: f64 = vs.iter().sum();
        assert!((sum - 1.0).abs() < 1e-9);
    }

    #[test]
    fn fixed_bins_returns_correct_edge_count() {
        let opts = HistogramOpts::default().bins(4);
        let (edges, vs) = bin_observations(&[0.0, 1.0, 2.0, 3.0, 4.0], &opts);
        assert_eq!(edges.len(), 5);
        assert_eq!(vs.len(), 4);
    }
}