bland 0.2.1

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
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
//! Figure: the plot document.
//!
//! A `Figure` holds canvas dimensions, axis configuration, the list of
//! series, and ornaments (legend, title block). Builder methods take
//! ownership and return `Self` so plots compose with `.method()` chains.

use crate::hatch::Hatch;
use crate::scale::ScaleKind;
use crate::series::{
    bin_observations, build_boxplot_series, staircase, AreaOpts, AreaSeries, BarOpts, BarSeries,
    BoxPlotOpts, ContourOpts, ContourSeries, ErrorBarOpts, ErrorBarSeries, HeatmapSeries,
    HistogramOpts, HistogramSeries, HlineOpts, HlineSeries, LineOpts, LineSeries, Normalize,
    Origin, PolygonOpts, PolygonSeries, QuiverOpts, QuiverSeries, ScatterOpts, ScatterSeries,
    Series, StemOpts, StemSeries, VlineOpts, VlineSeries,
};
use crate::strokes::Stroke;
use crate::theme::Theme;
use crate::title_block::TitleBlock;

/// Built-in paper presets (dimensions in pixels at 96 DPI).
#[derive(Debug, Clone, Copy)]
pub enum PaperSize {
    A4,
    A4Landscape,
    A5,
    A5Landscape,
    Letter,
    LetterLandscape,
    Legal,
    LegalLandscape,
    Square,
    Custom(f64, f64),
}

impl PaperSize {
    pub fn dimensions(self) -> (f64, f64) {
        match self {
            PaperSize::A4 => (794.0, 1123.0),
            PaperSize::A4Landscape => (1123.0, 794.0),
            PaperSize::A5 => (559.0, 794.0),
            PaperSize::A5Landscape => (794.0, 559.0),
            PaperSize::Letter => (816.0, 1056.0),
            PaperSize::LetterLandscape => (1056.0, 816.0),
            PaperSize::Legal => (816.0, 1344.0),
            PaperSize::LegalLandscape => (1344.0, 816.0),
            PaperSize::Square => (600.0, 600.0),
            PaperSize::Custom(w, h) => (w, h),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum LegendPosition {
    TopRight,
    TopLeft,
    BottomRight,
    BottomLeft,
    Manual(f64, f64),
}

/// Coordinate projection applied to series points before scaling.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Projection {
    #[default]
    None,
    /// `(θ, r) → (r·cos θ, r·sin θ)`. θ in radians.
    Polar,
    /// Web-Mercator. Inputs are `(lon, lat)` in degrees.
    Mercator,
    /// Equirectangular (plate carrée). Inputs are `(lon, lat)` in degrees.
    Equirect,
}

/// Plot-area clip shape.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Clip {
    #[default]
    Rect,
    /// Inscribed circle inside the plot rectangle. Used by polar and
    /// Smith chart figures.
    Circle,
}

/// Whether the figure draws axis lines / ticks at all.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum AxesStyle {
    #[default]
    Both,
    /// Suppress axis frame and ticks. Used by polar / Smith / map figures.
    None,
}

/// Position for a colorbar attached to a heatmap.
#[derive(Debug, Clone, Copy)]
pub enum ColorbarPosition {
    Right,
    Left,
    Bottom,
    Manual(f64, f64),
}

#[derive(Debug, Clone)]
pub(crate) struct ColorbarConfig {
    pub position: ColorbarPosition,
    pub label: Option<String>,
    pub levels: usize,
    pub ramp: Option<Vec<Hatch>>,
    pub range: Option<(f64, f64)>,
}

#[derive(Debug, Clone)]
pub(crate) enum Annotation {
    Text {
        x: f64,
        y: f64,
        text: String,
        font_size: Option<f64>,
        anchor: TextAnchor,
        halo: bool,
    },
    Arrow {
        from: (f64, f64),
        to: (f64, f64),
    },
}

#[derive(Debug, Clone, Copy, Default)]
pub enum TextAnchor {
    #[default]
    Start,
    Middle,
    End,
}

impl TextAnchor {
    pub(crate) fn as_str(self) -> &'static str {
        match self {
            TextAnchor::Start => "start",
            TextAnchor::Middle => "middle",
            TextAnchor::End => "end",
        }
    }
}

#[derive(Debug, Clone, Copy, Default)]
pub enum GridStyle {
    None,
    #[default]
    Major,
    Both,
}

#[derive(Debug, Clone)]
pub(crate) struct LegendConfig {
    pub position: LegendPosition,
    pub title: Option<String>,
}

#[derive(Debug, Clone, Copy)]
pub enum Limit {
    Auto,
    Manual(f64, f64),
}

/// The plot document. Build with `Figure::new()` and chain methods.
#[derive(Debug, Clone)]
pub struct Figure {
    pub(crate) width: f64,
    pub(crate) height: f64,
    /// `(top, right, bottom, left)` margin inside the page border.
    pub(crate) margins: (f64, f64, f64, f64),
    pub(crate) title: Option<String>,
    pub(crate) subtitle: Option<String>,
    pub(crate) xlabel: Option<String>,
    pub(crate) ylabel: Option<String>,
    pub(crate) xlim: Limit,
    pub(crate) ylim: Limit,
    pub(crate) xscale: ScaleKind,
    pub(crate) yscale: ScaleKind,
    pub(crate) grid: GridStyle,
    pub(crate) series: Vec<Series>,
    pub(crate) annotations: Vec<Annotation>,
    pub(crate) legend: Option<LegendConfig>,
    pub(crate) colorbar: Option<ColorbarConfig>,
    pub(crate) title_block: Option<TitleBlock>,
    pub(crate) theme: Theme,
    pub(crate) projection: Projection,
    pub(crate) clip: Clip,
    pub(crate) axes_style: AxesStyle,
}

impl Figure {
    pub fn new() -> Self {
        let (w, h) = PaperSize::LetterLandscape.dimensions();
        Self {
            width: w,
            height: h,
            margins: (80.0, 60.0, 80.0, 90.0),
            title: None,
            subtitle: None,
            xlabel: None,
            ylabel: None,
            xlim: Limit::Auto,
            ylim: Limit::Auto,
            xscale: ScaleKind::Linear,
            yscale: ScaleKind::Linear,
            grid: GridStyle::Major,
            series: Vec::new(),
            annotations: Vec::new(),
            legend: None,
            colorbar: None,
            title_block: None,
            theme: Theme::report_1972(),
            projection: Projection::None,
            clip: Clip::Rect,
            axes_style: AxesStyle::Both,
        }
    }

    pub fn size(mut self, paper: PaperSize) -> Self {
        let (w, h) = paper.dimensions();
        self.width = w;
        self.height = h;
        self
    }

    pub fn dimensions(mut self, width: f64, height: f64) -> Self {
        self.width = width;
        self.height = height;
        self
    }

    pub fn theme(mut self, theme: Theme) -> Self {
        self.theme = theme;
        self
    }

    pub fn margins(mut self, top: f64, right: f64, bottom: f64, left: f64) -> Self {
        self.margins = (top, right, bottom, left);
        self
    }

    pub fn title(mut self, t: impl Into<String>) -> Self {
        self.title = Some(t.into());
        self
    }

    pub fn subtitle(mut self, t: impl Into<String>) -> Self {
        self.subtitle = Some(t.into());
        self
    }

    pub fn xlabel(mut self, t: impl Into<String>) -> Self {
        self.xlabel = Some(t.into());
        self
    }

    pub fn ylabel(mut self, t: impl Into<String>) -> Self {
        self.ylabel = Some(t.into());
        self
    }

    pub fn xlim(mut self, lo: f64, hi: f64) -> Self {
        self.xlim = Limit::Manual(lo, hi);
        self
    }

    pub fn ylim(mut self, lo: f64, hi: f64) -> Self {
        self.ylim = Limit::Manual(lo, hi);
        self
    }

    pub fn xlog(mut self) -> Self {
        self.xscale = ScaleKind::Log;
        self
    }

    pub fn ylog(mut self) -> Self {
        self.yscale = ScaleKind::Log;
        self
    }

    pub fn grid(mut self, g: GridStyle) -> Self {
        self.grid = g;
        self
    }

    // --- series ---------------------------------------------------------

    /// Add a connected line series. The closure receives a [`LineOpts`]
    /// builder for per-series style overrides; pass `|s| s` for defaults.
    pub fn line<F>(mut self, xs: &[f64], ys: &[f64], f: F) -> Self
    where
        F: FnOnce(LineOpts) -> LineOpts,
    {
        let o = f(LineOpts::default());
        self.series.push(Series::Line(LineSeries {
            xs: xs.to_vec(),
            ys: ys.to_vec(),
            label: o.label,
            stroke: o.stroke,
            stroke_width: o.stroke_width,
            markers: o.markers,
            marker: o.marker,
            marker_size: o.marker_size,
        }));
        self
    }

    pub fn scatter<F>(mut self, xs: &[f64], ys: &[f64], f: F) -> Self
    where
        F: FnOnce(ScatterOpts) -> ScatterOpts,
    {
        let o = f(ScatterOpts::default());
        self.series.push(Series::Scatter(ScatterSeries {
            xs: xs.to_vec(),
            ys: ys.to_vec(),
            label: o.label,
            marker: o.marker,
            marker_size: o.marker_size,
            stroke_width: o.stroke_width,
        }));
        self
    }

    pub fn bar<F, S>(mut self, categories: &[S], values: &[f64], f: F) -> Self
    where
        F: FnOnce(BarOpts) -> BarOpts,
        S: AsRef<str>,
    {
        let o = f(BarOpts::default());
        self.series.push(Series::Bar(BarSeries {
            categories: categories.iter().map(|c| c.as_ref().to_string()).collect(),
            values: values.to_vec(),
            label: o.label,
            hatch: o.hatch,
            group: o.group,
            stroke_width: o.stroke_width,
        }));
        self
    }

    pub fn area<F>(mut self, xs: &[f64], ys: &[f64], f: F) -> Self
    where
        F: FnOnce(AreaOpts) -> AreaOpts,
    {
        let o = f(AreaOpts::default());
        self.series.push(Series::Area(AreaSeries {
            xs: xs.to_vec(),
            ys: ys.to_vec(),
            label: o.label,
            hatch: o.hatch,
            baseline: o.baseline,
            stroke: o.stroke,
            stroke_width: o.stroke_width,
        }));
        self
    }

    /// Add a histogram of `observations`. Bins are computed based on the
    /// strategy in [`HistogramOpts`]; the default is Sturges' rule. With
    /// `Normalize::Cmf`, the series is rendered as a staircase line
    /// instead of bars.
    pub fn histogram<F>(mut self, observations: &[f64], f: F) -> Self
    where
        F: FnOnce(HistogramOpts) -> HistogramOpts,
    {
        let o = f(HistogramOpts::default());
        let label = o.label.clone();
        let hatch = o.hatch;
        let stroke_width = o.stroke_width;
        let normalize = o.normalize;
        let (edges, values) = bin_observations(observations, &o);

        if matches!(normalize, Normalize::Cmf) {
            let (xs, ys) = staircase(&edges, &values);
            self.series.push(Series::Line(LineSeries {
                xs,
                ys,
                label,
                stroke: Some(Stroke::Solid),
                stroke_width,
                markers: false,
                marker: None,
                marker_size: None,
            }));
        } else {
            self.series.push(Series::Histogram(HistogramSeries {
                bin_edges: edges,
                values,
                label,
                hatch,
                stroke_width,
            }));
        }
        self
    }

    /// Add a closed polygon. `xs` and `ys` are the vertices in order;
    /// the renderer connects the last point back to the first.
    pub fn polygon<F>(mut self, xs: &[f64], ys: &[f64], f: F) -> Self
    where
        F: FnOnce(PolygonOpts) -> PolygonOpts,
    {
        let o = f(PolygonOpts::default());
        self.series.push(Series::Polygon(PolygonSeries {
            xs: xs.to_vec(),
            ys: ys.to_vec(),
            label: o.label,
            hatch: o.hatch,
            stroke: o.stroke,
            stroke_width: o.stroke_width,
        }));
        self
    }

    /// Add an error-bar series. Configure errors via `ErrorBarOpts::yerr`
    /// (symmetric) or `yerr_asym` (lower/upper tuples).
    pub fn errorbar<F>(mut self, xs: &[f64], ys: &[f64], f: F) -> Self
    where
        F: FnOnce(ErrorBarOpts) -> ErrorBarOpts,
    {
        let o = f(ErrorBarOpts::default());
        self.series.push(Series::ErrorBar(ErrorBarSeries {
            xs: xs.to_vec(),
            ys: ys.to_vec(),
            yerr: o.yerr,
            xerr: o.xerr,
            marker: o.marker,
            marker_size: o.marker_size,
            cap_width: o.cap_width,
            stroke_width: o.stroke_width,
            label: o.label,
        }));
        self
    }

    /// Add a box-and-whisker plot. Each tuple pairs a category label
    /// with the raw observations for that category; quartiles, Tukey
    /// fences, and outliers are computed automatically.
    pub fn boxplot<S, F>(mut self, samples_by_category: &[(S, Vec<f64>)], f: F) -> Self
    where
        S: AsRef<str>,
        F: FnOnce(BoxPlotOpts) -> BoxPlotOpts,
    {
        let o = f(BoxPlotOpts::default());
        let pairs: Vec<(String, Vec<f64>)> = samples_by_category
            .iter()
            .map(|(c, s)| (c.as_ref().to_string(), s.clone()))
            .collect();
        let series = build_boxplot_series(&pairs, o);
        self.series.push(Series::BoxPlot(series));
        self
    }

    /// Add a stem plot — the discrete-signal staple from DSP. Each
    /// point renders as a vertical line from `baseline` (default 0) to
    /// `(x, y)`, with a marker at the tip.
    pub fn stem<F>(mut self, xs: &[f64], ys: &[f64], f: F) -> Self
    where
        F: FnOnce(StemOpts) -> StemOpts,
    {
        let o = f(StemOpts::default());
        self.series.push(Series::Stem(StemSeries {
            xs: xs.to_vec(),
            ys: ys.to_vec(),
            baseline: o.baseline,
            label: o.label,
            stroke: o.stroke,
            stroke_width: o.stroke_width,
            marker: o.marker,
            marker_size: o.marker_size,
        }));
        self
    }

    /// Add a 2D vector field. Each `(xs[i], ys[i])` gets an arrow with
    /// components `(us[i], vs[i])`.
    pub fn quiver<F>(mut self, xs: &[f64], ys: &[f64], us: &[f64], vs: &[f64], f: F) -> Self
    where
        F: FnOnce(QuiverOpts) -> QuiverOpts,
    {
        let o = f(QuiverOpts::default());
        self.series.push(Series::Quiver(QuiverSeries {
            xs: xs.to_vec(),
            ys: ys.to_vec(),
            us: us.to_vec(),
            vs: vs.to_vec(),
            scale: o.scale,
            head_size: o.head_size,
            label: o.label,
            stroke: o.stroke,
            stroke_width: o.stroke_width,
        }));
        self
    }

    /// Add iso-level contours over a 2D scalar grid.
    pub fn contour<F>(mut self, data: Vec<Vec<f64>>, f: F) -> Self
    where
        F: FnOnce(ContourOpts) -> ContourOpts,
    {
        let rows = data.len();
        let cols = data.first().map(|r| r.len()).unwrap_or(0);
        let mut o = ContourOpts::default();
        o.x_edges = Some((0..=cols).map(|i| i as f64).collect());
        o.y_edges = Some((0..=rows).map(|i| i as f64).collect());
        let o = f(o);

        let levels = o.levels.unwrap_or_else(|| default_levels(&data));
        self.series.push(Series::Contour(ContourSeries {
            data,
            x_edges: o.x_edges.unwrap(),
            y_edges: o.y_edges.unwrap(),
            levels,
            origin: o.origin,
            stroke: o.stroke,
            stroke_width: o.stroke_width,
            label: o.label,
        }));
        self
    }

    /// Place a free-form text annotation in data coordinates.
    pub fn annotate_text(
        mut self,
        x: f64,
        y: f64,
        text: impl Into<String>,
        anchor: TextAnchor,
    ) -> Self {
        self.annotations.push(Annotation::Text {
            x,
            y,
            text: text.into(),
            font_size: None,
            anchor,
            halo: true,
        });
        self
    }

    /// Place a free-form text annotation with an explicit font size.
    pub fn annotate_text_sized(
        mut self,
        x: f64,
        y: f64,
        text: impl Into<String>,
        anchor: TextAnchor,
        font_size: f64,
    ) -> Self {
        self.annotations.push(Annotation::Text {
            x,
            y,
            text: text.into(),
            font_size: Some(font_size),
            anchor,
            halo: true,
        });
        self
    }

    /// Draw an arrow between two data-space points.
    pub fn annotate_arrow(mut self, from: (f64, f64), to: (f64, f64)) -> Self {
        self.annotations.push(Annotation::Arrow { from, to });
        self
    }

    /// Attach a colorbar describing the most recent heatmap added.
    pub fn colorbar(mut self, position: ColorbarPosition) -> Self {
        self.colorbar = Some(ColorbarConfig {
            position,
            label: None,
            levels: 5,
            ramp: None,
            range: None,
        });
        self
    }

    pub fn colorbar_with(
        mut self,
        position: ColorbarPosition,
        label: Option<String>,
        levels: usize,
    ) -> Self {
        self.colorbar = Some(ColorbarConfig {
            position,
            label,
            levels,
            ramp: None,
            range: None,
        });
        self
    }

    pub fn projection(mut self, p: Projection) -> Self {
        self.projection = p;
        self
    }

    pub fn clip(mut self, c: Clip) -> Self {
        self.clip = c;
        self
    }

    pub fn no_axes(mut self) -> Self {
        self.axes_style = AxesStyle::None;
        self
    }

    /// Build a polar figure: square canvas, polar projection, circular
    /// clip, no axes. Series data is interpreted as `(θ, r)` pairs in
    /// radians. Pair with [`Figure::polar_grid`] for the reference rings.
    pub fn polar(rmax: f64) -> Self {
        Self::new()
            .size(PaperSize::Square)
            .projection(Projection::Polar)
            .clip(Clip::Circle)
            .no_axes()
            .grid(GridStyle::None)
            .xlim(-rmax, rmax)
            .ylim(-rmax, rmax)
    }

    /// Add concentric reference rings + radial spokes to a polar figure.
    pub fn polar_grid(self, opts: PolarGridOpts) -> Self {
        let rmax = match (self.xlim, self.ylim) {
            (Limit::Manual(x0, x1), _) => x0.abs().max(x1.abs()),
            (_, Limit::Manual(y0, y1)) => y0.abs().max(y1.abs()),
            _ => 1.0,
        };

        let r_ticks = opts.r_ticks.unwrap_or_else(|| {
            let step = rmax / 4.0;
            (1..=4).map(|i| i as f64 * step).collect()
        });
        let theta_step_deg = opts.theta_step_deg;
        let stroke = opts.stroke;
        let sw = opts.stroke_width;
        let samples = opts.samples;

        let mut fig = self;
        for r in &r_ticks {
            let (thetas, rs) = crate::polar::circle(*r, samples);
            fig = fig.line(&thetas, &rs, |s| s.stroke(stroke).stroke_width(sw));
        }

        let mut deg = 0i32;
        while deg < 360 {
            let theta = deg as f64 * std::f64::consts::PI / 180.0;
            fig = fig.line(&[theta, theta], &[0.0, rmax], |s| {
                s.stroke(stroke).stroke_width(sw)
            });
            deg += theta_step_deg;
        }

        if opts.labels {
            let label_radius = rmax * 1.07;
            let mut deg = 0i32;
            while deg < 360 {
                let theta = deg as f64 * std::f64::consts::PI / 180.0;
                fig = fig.annotate_text_sized(
                    theta,
                    label_radius,
                    format!("{}°", deg),
                    TextAnchor::Middle,
                    9.0,
                );
                deg += theta_step_deg;
            }
        }

        if opts.r_labels {
            for r in &r_ticks {
                fig = fig.annotate_text_sized(
                    0.0,
                    *r,
                    crate::ticks::format(*r),
                    TextAnchor::Start,
                    8.0,
                );
            }
        }
        fig
    }

    /// Build a Smith chart figure: square canvas, no projection (Γ is
    /// already in Cartesian Re/Im), circular clip, no axes. Pair with
    /// [`Figure::smith_grid`] for the resistance/reactance grid.
    pub fn smith() -> Self {
        Self::new()
            .size(PaperSize::Square)
            .clip(Clip::Circle)
            .no_axes()
            .grid(GridStyle::None)
            .xlim(-1.08, 1.08)
            .ylim(-1.08, 1.08)
    }

    /// Add the classical Smith chart grid: unit-circle boundary, real
    /// axis, constant-R circles, constant-X arcs.
    pub fn smith_grid(self, opts: SmithGridOpts) -> Self {
        let r_values = opts
            .r_values
            .unwrap_or_else(|| crate::smith::DEFAULT_R_VALUES.to_vec());
        let x_values = opts
            .x_values
            .unwrap_or_else(|| crate::smith::DEFAULT_X_VALUES.to_vec());
        let stroke = opts.stroke;
        let sw = opts.stroke_width;
        let boundary_sw = opts.boundary_stroke_width;
        let samples = opts.samples;

        let mut fig = self;

        // Unit circle (|Γ| = 1)
        let (uxs, uys) = crate::smith::r_circle(0.0, samples);
        fig = fig.line(&uxs, &uys, |s| {
            s.stroke(Stroke::Solid).stroke_width(boundary_sw)
        });
        // Real axis
        fig = fig.line(&[-1.0, 1.0], &[0.0, 0.0], |s| {
            s.stroke(Stroke::Solid).stroke_width(boundary_sw)
        });
        // Constant-R circles
        for r in &r_values {
            let (xs, ys) = crate::smith::r_circle(*r, samples);
            fig = fig.line(&xs, &ys, |s| s.stroke(stroke).stroke_width(sw));
        }
        // Constant-X arcs
        for x_mag in &x_values {
            let (xs_p, ys_p) = crate::smith::x_arc(*x_mag, samples);
            let (xs_n, ys_n) = crate::smith::x_arc(-*x_mag, samples);
            fig = fig.line(&xs_p, &ys_p, |s| s.stroke(stroke).stroke_width(sw));
            fig = fig.line(&xs_n, &ys_n, |s| s.stroke(stroke).stroke_width(sw));
        }

        if opts.labels {
            for r in &r_values {
                let x_pos = (r - 1.0) / (r + 1.0);
                fig = fig.annotate_text_sized(
                    x_pos,
                    0.0,
                    crate::ticks::format(*r),
                    TextAnchor::Middle,
                    7.0,
                );
            }
            for x_mag in &x_values {
                let denom = x_mag * x_mag + 1.0;
                let gre = (x_mag * x_mag - 1.0) / denom;
                let gim_top = 2.0 * x_mag / denom;
                fig = fig.annotate_text_sized(
                    gre,
                    gim_top * 1.05,
                    format!("+{}", crate::ticks::format(*x_mag)),
                    TextAnchor::Middle,
                    7.0,
                );
                fig = fig.annotate_text_sized(
                    gre,
                    -gim_top * 1.05,
                    format!("-{}", crate::ticks::format(*x_mag)),
                    TextAnchor::Middle,
                    7.0,
                );
            }
        }
        fig
    }

    /// Add a built-in basemap layer (Earth coastlines, borders,
    /// reference parallels, or lunar maria). The closure configures
    /// resolution, stroke style, optional hatch fill, and feature
    /// filtering. See [`crate::basemaps`] for the full layer list.
    pub fn basemap<F>(self, layer: crate::basemaps::Basemap, f: F) -> Self
    where
        F: FnOnce(crate::basemaps::BasemapOpts) -> crate::basemaps::BasemapOpts,
    {
        let opts = f(crate::basemaps::BasemapOpts::default());
        let features = crate::basemaps::features(layer, opts.resolution);
        let features = crate::basemaps::filter_features(features, &opts.only, &opts.except);

        let mut fig = self;
        for feature in features {
            let xs: Vec<f64> = feature.points.iter().map(|p| p.0).collect();
            let ys: Vec<f64> = feature.points.iter().map(|p| p.1).collect();
            if feature.closed {
                let stroke = opts.stroke;
                let stroke_width = opts.stroke_width;
                let hatch = opts.hatch;
                fig = fig.polygon(&xs, &ys, |p| {
                    let p = p.stroke(stroke).stroke_width(stroke_width);
                    match hatch {
                        Some(h) => p.hatch(h),
                        None => p,
                    }
                });
            } else {
                let stroke = opts.stroke;
                let stroke_width = opts.stroke_width;
                fig = fig.line(&xs, &ys, |s| s.stroke(stroke).stroke_width(stroke_width));
            }
        }
        fig
    }

    /// Add a lat/lon graticule as a series of dotted reference lines.
    /// Only meaningful when [`Figure::projection`] is set to a
    /// geographic projection.
    pub fn graticule(self, opts: crate::geo::GraticuleOpts) -> Self {
        let lines = crate::geo::graticule(opts);
        let mut fig = self;
        for (xs, ys) in &lines {
            fig = fig.line(xs, ys, |s| s.stroke(Stroke::Dotted).stroke_width(0.5));
        }
        fig
    }

    /// Add a heatmap. `data` is a `rows × cols` grid of numeric values;
    /// each cell maps to one level of the ramp's hatch sequence.
    /// Configure via the closure on a [`HeatmapOpts`] builder.
    pub fn heatmap<F>(mut self, data: Vec<Vec<f64>>, f: F) -> Self
    where
        F: FnOnce(HeatmapOpts) -> HeatmapOpts,
    {
        let rows = data.len();
        let cols = data.first().map(|r| r.len()).unwrap_or(0);
        let mut o = HeatmapOpts::default();
        o.x_edges = Some((0..=cols).map(|i| i as f64).collect());
        o.y_edges = Some((0..=rows).map(|i| i as f64).collect());
        let o = f(o);
        self.series.push(Series::Heatmap(HeatmapSeries {
            data,
            x_edges: o.x_edges.unwrap(),
            y_edges: o.y_edges.unwrap(),
            ramp: o.ramp.unwrap_or_else(|| Hatch::DEFAULT_RAMP.to_vec()),
            range: o.range,
            origin: o.origin,
            label: o.label,
        }));
        self
    }

    pub fn hline<F>(mut self, y: f64, f: F) -> Self
    where
        F: FnOnce(HlineOpts) -> HlineOpts,
    {
        let o = f(HlineOpts::default());
        self.series.push(Series::Hline(HlineSeries {
            y,
            label: o.label,
            stroke: o.stroke.unwrap_or(Stroke::Dashed),
            stroke_width: o.stroke_width.unwrap_or(self.theme.series_stroke_width),
        }));
        self
    }

    pub fn vline<F>(mut self, x: f64, f: F) -> Self
    where
        F: FnOnce(VlineOpts) -> VlineOpts,
    {
        let o = f(VlineOpts::default());
        self.series.push(Series::Vline(VlineSeries {
            x,
            label: o.label,
            stroke: o.stroke.unwrap_or(Stroke::Dashed),
            stroke_width: o.stroke_width.unwrap_or(self.theme.series_stroke_width),
        }));
        self
    }

    // --- ornaments ------------------------------------------------------

    pub fn legend(mut self, position: LegendPosition) -> Self {
        self.legend = Some(LegendConfig {
            position,
            title: None,
        });
        self
    }

    pub fn legend_top_right(self) -> Self {
        self.legend(LegendPosition::TopRight)
    }
    pub fn legend_top_left(self) -> Self {
        self.legend(LegendPosition::TopLeft)
    }
    pub fn legend_bottom_right(self) -> Self {
        self.legend(LegendPosition::BottomRight)
    }
    pub fn legend_bottom_left(self) -> Self {
        self.legend(LegendPosition::BottomLeft)
    }

    pub fn legend_with_title(mut self, position: LegendPosition, title: impl Into<String>) -> Self {
        self.legend = Some(LegendConfig {
            position,
            title: Some(title.into()),
        });
        self
    }

    pub fn title_block(mut self, tb: TitleBlock) -> Self {
        self.title_block = Some(tb);
        self
    }

    // --- output ---------------------------------------------------------

    pub fn to_svg(&self) -> String {
        crate::renderer::render(self)
    }

    /// Open a blocking native-webview window that displays the figure.
    /// matplotlib-style `plt.show()`. The window has Save SVG and zoom
    /// buttons; it returns when the user closes the window.
    ///
    /// Available only when the `gui` cargo feature is enabled.
    #[cfg(feature = "gui")]
    pub fn show(&self) {
        crate::gui::show(self);
    }

    /// [`Figure::show`] with explicit window/save options.
    #[cfg(feature = "gui")]
    pub fn show_with_options(&self, opts: crate::gui::ShowOptions) {
        crate::gui::show_with_options(self, opts);
    }

    /// Rasterize the figure to a pre-multiplied RGBA pixmap of size
    /// `width × height` pixels. The figure is scaled to fit while preserving
    /// aspect ratio; unused area is filled white.
    ///
    /// Returned `Vec<u8>` has length `width * height * 4`, row-major,
    /// pre-multiplied RGBA — directly compatible with
    /// [`egui::ColorImage::from_rgba_premultiplied`].
    ///
    /// Available only when the `raster` cargo feature is enabled.
    #[cfg(feature = "raster")]
    pub fn to_pixmap(&self, width: u32, height: u32) -> Vec<u8> {
        crate::raster::to_pixmap(self, width, height)
    }

    pub(crate) fn plot_rect(&self) -> (f64, f64, f64, f64) {
        let (t, r, b, l) = self.margins;
        let pw = (self.width - l - r).max(1.0);
        let ph = (self.height - t - b).max(1.0);
        (l, t, pw, ph)
    }
}

impl Default for Figure {
    fn default() -> Self {
        Self::new()
    }
}

/// Per-call options for [`Figure::heatmap`].
#[derive(Debug, Default)]
pub struct HeatmapOpts {
    pub(crate) x_edges: Option<Vec<f64>>,
    pub(crate) y_edges: Option<Vec<f64>>,
    pub(crate) ramp: Option<Vec<Hatch>>,
    pub(crate) range: Option<(f64, f64)>,
    pub(crate) origin: Origin,
    pub(crate) label: Option<String>,
}

impl HeatmapOpts {
    pub fn x_edges(mut self, edges: Vec<f64>) -> Self {
        self.x_edges = Some(edges);
        self
    }
    pub fn y_edges(mut self, edges: Vec<f64>) -> Self {
        self.y_edges = Some(edges);
        self
    }
    pub fn ramp(mut self, ramp: Vec<Hatch>) -> Self {
        self.ramp = Some(ramp);
        self
    }
    /// Use a `n`-level ramp sampled from the default light-to-dark sequence.
    pub fn ramp_levels(mut self, n: usize) -> Self {
        self.ramp = Some(sample_ramp(n));
        self
    }
    pub fn range(mut self, lo: f64, hi: f64) -> Self {
        self.range = Some((lo, hi));
        self
    }
    pub fn origin(mut self, origin: Origin) -> Self {
        self.origin = origin;
        self
    }
    pub fn label(mut self, s: impl Into<String>) -> Self {
        self.label = Some(s.into());
        self
    }
}

fn sample_ramp(n: usize) -> Vec<Hatch> {
    if n <= 1 {
        return vec![Hatch::Crosshatch];
    }
    let steps = Hatch::DEFAULT_RAMP.len() - 1;
    (0..n)
        .map(|i| {
            let idx = (i as f64 * steps as f64 / (n - 1) as f64).round() as usize;
            Hatch::DEFAULT_RAMP[idx]
        })
        .collect()
}

fn default_levels(grid: &[Vec<f64>]) -> Vec<f64> {
    let (lo, hi) = crate::hatch::extent(grid);
    let step = (hi - lo) / 8.0;
    (1..=7).map(|i| lo + i as f64 * step).collect()
}

/// Options for [`Figure::polar_grid`].
#[derive(Debug, Clone)]
pub struct PolarGridOpts {
    pub r_ticks: Option<Vec<f64>>,
    pub theta_step_deg: i32,
    pub stroke: Stroke,
    pub stroke_width: f64,
    pub samples: usize,
    pub labels: bool,
    pub r_labels: bool,
}

impl Default for PolarGridOpts {
    fn default() -> Self {
        Self {
            r_ticks: None,
            theta_step_deg: 30,
            stroke: Stroke::Dotted,
            stroke_width: 0.4,
            samples: 120,
            labels: true,
            r_labels: false,
        }
    }
}

/// Options for [`Figure::smith_grid`].
#[derive(Debug, Clone)]
pub struct SmithGridOpts {
    pub r_values: Option<Vec<f64>>,
    pub x_values: Option<Vec<f64>>,
    pub stroke: Stroke,
    pub stroke_width: f64,
    pub boundary_stroke_width: f64,
    pub samples: usize,
    pub labels: bool,
}

impl Default for SmithGridOpts {
    fn default() -> Self {
        Self {
            r_values: None,
            x_values: None,
            stroke: Stroke::Dotted,
            stroke_width: 0.4,
            boundary_stroke_width: 0.8,
            samples: 120,
            labels: true,
        }
    }
}