ruviz 0.6.0

High-performance 2D plotting library for Rust
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
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
//! Heatmap visualization for 2D array data
//!
//! Provides color-mapped grid visualization with colorbars and annotations.
//!
//! # Colorbar Configuration
//!
//! Heatmaps support configurable colorbar labels and font sizes. Both font
//! sizes default to the theme's tick and axis-label sizes — see
//! [`ColorbarFontSizes`] — so a colorbar never has to be re-tuned after a
//! `.theme(..)` call:
//!
//! ```rust,ignore
//! use ruviz::prelude::{AxisScale, HeatmapConfig};
//!
//! let config = HeatmapConfig::default()
//!     .value_scale(AxisScale::Log)
//!     .colorbar(true)
//!     .colorbar_log_subticks(true)
//!     .cell_borders(false)
//!     .colorbar_label("Temperature (°C)")
//!     .colorbar_tick_font_size(10.0)    // Overrides the theme's tick size
//!     .colorbar_label_font_size(11.0);  // Overrides the theme's label size
//! ```
//!
//! When using `AxisScale::Log`, the effective `vmin`/`vmax` range must remain
//! strictly positive.
//!
//! # Trait-Based API
//!
//! Heatmap plots implement the core plot traits:
//! - [`PlotConfig`] for `HeatmapConfig`
//! - [`PlotData`] for `HeatmapData`
//! - [`PlotRender`] for `HeatmapData`

use crate::axes::AxisScale;
use crate::core::Result as PlotResult;
use crate::core::plot::PlotBuilder;
use crate::core::style_utils::StyleResolver;
use crate::plots::traits::{PlotArea, PlotConfig, PlotData, PlotRender};
use crate::render::skia::SkiaRenderer;
use crate::render::{Color, ColorMap, ColorMapSpec, Theme};

/// The two text sizes a colorbar is drawn at, in points.
///
/// Every colorbar in the crate resolves its fonts here — the heatmap colorbar,
/// the contour colorbar and the 3D surface colorbar — so the library has one
/// answer to "how big is colorbar text?" rather than three sets of literals.
/// Before this existed, heatmap hardcoded 12/14 pt, contour 10/11 pt and 3D
/// went straight to the theme, so [`Theme::ieee`](crate::render::Theme::ieee)'s
/// 8 pt axis ticks were drawn beside a 12 pt colorbar.
///
/// An unset (`None`) size follows the theme; that is the default for every
/// colorbar in the crate. Setting one is an explicit override and is honoured
/// verbatim.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct ColorbarFontSizes {
    /// Tick label size in points, defaulting to `Theme::tick_label_font_size`.
    pub tick: f32,
    /// Caption size in points, defaulting to `Theme::axis_label_font_size`.
    pub label: f32,
}

impl ColorbarFontSizes {
    /// Fill in each unset size from `theme`.
    ///
    /// The colorbar's ticks track the axis ticks and its caption tracks the
    /// axis labels, because that is what the two texts *are*: a value axis
    /// beside the plot.
    pub fn resolve(tick: Option<f32>, label: Option<f32>, theme: &Theme) -> Self {
        Self {
            tick: tick.unwrap_or(theme.tick_label_font_size),
            label: label.unwrap_or(theme.axis_label_font_size),
        }
    }
}

/// Interpolation method for heatmap rendering
#[allow(deprecated)] // the derives touch the deprecated `Bilinear` variant
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Interpolation {
    /// Each cell is a solid rectangle with no smoothing
    #[default]
    Nearest,
    /// Colors are smoothly interpolated between cell centers
    ///
    /// Not implemented: selecting it only disables the pixel-aligned fast path,
    /// and the resulting image is byte-identical to
    /// [`Interpolation::Nearest`].
    #[deprecated(
        since = "0.6.0",
        note = "not yet implemented; tracked for a future release. Renders identically to Interpolation::Nearest"
    )]
    Bilinear,
}

/// Physical Y extent used for heatmap row 0.
///
/// This policy is independent of the displayed Y-axis direction: reversing
/// `ylim` changes where the physical extent appears on screen, not which data
/// row occupies it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HeatmapOrigin {
    /// Place row 0 adjacent to the upper (`y_extent.1`) edge.
    #[default]
    Upper,
    /// Place row 0 adjacent to the lower (`y_extent.0`) edge.
    Lower,
}

/// Configuration for heatmap rendering
#[allow(deprecated)] // the derives touch the deprecated fields below
#[derive(Debug, Clone)]
pub struct HeatmapConfig {
    /// Colormap to use for value-to-color mapping
    pub colormap: ColorMap,
    /// Minimum value for color mapping (None = auto from data)
    pub vmin: Option<f64>,
    /// Maximum value for color mapping (None = auto from data)
    pub vmax: Option<f64>,
    /// Value scale for color mapping and colorbar ticks
    pub value_scale: AxisScale,
    /// Whether to show a colorbar
    pub colorbar: bool,
    /// Label for the colorbar
    pub colorbar_label: Option<String>,
    /// Font size for colorbar tick labels, in points
    ///
    /// `None` follows the theme; see [`ColorbarFontSizes`].
    pub colorbar_tick_font_size: Option<f32>,
    /// Font size for the colorbar label, in points
    ///
    /// `None` follows the theme; see [`ColorbarFontSizes`].
    pub colorbar_label_font_size: Option<f32>,
    /// Whether logarithmic colorbars draw minor subticks
    pub colorbar_log_subticks: bool,
    /// Custom labels for X axis ticks
    ///
    /// Not implemented: axis ticks are generated by the plot pipeline, which
    /// never consults this field.
    #[deprecated(
        since = "0.6.0",
        note = "not yet implemented; tracked for a future release. There is no replacement yet: x tick labels come from the axis, via HeatmapConfig::extent"
    )]
    pub xticklabels: Option<Vec<String>>,
    /// Custom labels for Y axis ticks
    ///
    /// Not implemented: axis ticks are generated by the plot pipeline, which
    /// never consults this field.
    #[deprecated(
        since = "0.6.0",
        note = "not yet implemented; tracked for a future release. There is no replacement yet: y tick labels come from the axis, via HeatmapConfig::extent"
    )]
    pub yticklabels: Option<Vec<String>>,
    /// Interpolation method
    pub interpolation: Interpolation,
    /// Whether to annotate cells with values
    pub annotate: bool,
    /// Format string for cell annotations
    ///
    /// See [`HeatmapConfig::annotation_format`] for the supported syntax and
    /// [`HeatmapData::format_annotation`] for the formatter itself.
    pub annotation_format: String,
    /// Aspect ratio (None = auto, Some(1.0) = square cells)
    ///
    /// Not implemented: the heatmap fills whatever plot area the layout gives
    /// it, so cells are never forced square.
    #[deprecated(
        since = "0.6.0",
        note = "not yet implemented; tracked for a future release. Size the figure so the plot area has the ratio you want (Plot::size_px)"
    )]
    pub aspect: Option<f64>,
    /// Alpha transparency for the heatmap (0.0 - 1.0)
    pub alpha: f32,
    /// Whether heatmap cells should draw visible borders
    pub cell_borders: bool,
    /// Whether SymLog heatmaps should derive linthresh from the smallest positive finite value
    pub symlog_auto_linthresh: bool,
    /// Physical extent for the heatmap grid as (xmin, xmax, ymin, ymax)
    pub extent: Option<(f64, f64, f64, f64)>,
    /// Physical Y edge adjacent to row 0
    pub origin: HeatmapOrigin,
}

impl Default for HeatmapConfig {
    // `aspect`/`xticklabels`/`yticklabels` still have to be populated while they exist
    #[allow(deprecated)]
    fn default() -> Self {
        Self {
            colormap: ColorMap::viridis(),
            vmin: None,
            vmax: None,
            value_scale: AxisScale::Linear,
            colorbar: true,
            colorbar_label: None,
            // Unset: the theme's tick and axis-label sizes. See `ColorbarFontSizes`.
            colorbar_tick_font_size: None,
            colorbar_label_font_size: None,
            colorbar_log_subticks: true,
            xticklabels: None,
            yticklabels: None,
            interpolation: Interpolation::Nearest,
            annotate: false,
            annotation_format: "{:.2}".to_string(),
            aspect: None,
            alpha: 1.0,
            cell_borders: false,
            symlog_auto_linthresh: false,
            extent: None,
            origin: HeatmapOrigin::Upper,
        }
    }
}

impl HeatmapConfig {
    /// Create a new HeatmapConfig with default settings
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the colormap.
    ///
    /// Accepts a [`ColorMap`] value or a name such as `"viridis"`.
    pub fn cmap(mut self, cmap: impl Into<ColorMapSpec>) -> Self {
        self.colormap = cmap.into().resolve();
        self
    }

    /// Set the colormap
    #[deprecated(
        since = "0.6.0",
        note = "renamed: use `cmap(colormap)`, which also accepts a name such as `cmap(\"viridis\")`"
    )]
    pub fn colormap(self, colormap: ColorMap) -> Self {
        self.cmap(colormap)
    }

    /// Set the minimum value for color mapping
    pub fn vmin(mut self, vmin: f64) -> Self {
        self.vmin = Some(vmin);
        self
    }

    /// Set the maximum value for color mapping
    pub fn vmax(mut self, vmax: f64) -> Self {
        self.vmax = Some(vmax);
        self
    }

    /// Set the value scale used for color normalization and colorbar ticks.
    ///
    /// `AxisScale::Log` requires the effective `vmin` and `vmax` range to be
    /// strictly positive.
    pub fn value_scale(mut self, scale: AxisScale) -> Self {
        self.value_scale = scale;
        self
    }

    /// Enable or disable colorbar
    pub fn colorbar(mut self, show: bool) -> Self {
        self.colorbar = show;
        self
    }

    /// Set the colorbar label
    pub fn colorbar_label<S: Into<String>>(mut self, label: S) -> Self {
        self.colorbar_label = Some(label.into());
        self
    }

    /// Set the colorbar tick font size, in points.
    ///
    /// Unset by default, which follows the theme's tick label size.
    pub fn colorbar_tick_font_size(mut self, size: f32) -> Self {
        self.colorbar_tick_font_size = Some(size.max(1.0));
        self
    }

    /// Set the colorbar label font size, in points.
    ///
    /// Unset by default, which follows the theme's axis label size.
    pub fn colorbar_label_font_size(mut self, size: f32) -> Self {
        self.colorbar_label_font_size = Some(size.max(1.0));
        self
    }

    /// The font sizes this colorbar is drawn at, with unset sizes taken from
    /// `theme`.
    ///
    /// The single resolution point shared with [`ContourConfig`] and the 3D
    /// surface colorbar.
    ///
    /// [`ContourConfig`]: crate::plots::continuous::contour::ContourConfig
    pub fn colorbar_font_sizes(&self, theme: &Theme) -> ColorbarFontSizes {
        ColorbarFontSizes::resolve(
            self.colorbar_tick_font_size,
            self.colorbar_label_font_size,
            theme,
        )
    }

    /// Enable or disable logarithmic colorbar subticks.
    ///
    /// This only affects `AxisScale::Log` colorbars.
    pub fn colorbar_log_subticks(mut self, show: bool) -> Self {
        self.colorbar_log_subticks = show;
        self
    }

    /// Set custom X axis tick labels
    ///
    /// Currently inert; see [`HeatmapConfig::xticklabels`].
    #[deprecated(
        since = "0.6.0",
        note = "not yet implemented; tracked for a future release. There is no replacement yet: x tick labels come from the axis, via HeatmapConfig::extent"
    )]
    #[allow(deprecated)]
    pub fn xticklabels(mut self, labels: Vec<String>) -> Self {
        self.xticklabels = Some(labels);
        self
    }

    /// Set custom Y axis tick labels
    ///
    /// Currently inert; see [`HeatmapConfig::yticklabels`].
    #[deprecated(
        since = "0.6.0",
        note = "not yet implemented; tracked for a future release. There is no replacement yet: y tick labels come from the axis, via HeatmapConfig::extent"
    )]
    #[allow(deprecated)]
    pub fn yticklabels(mut self, labels: Vec<String>) -> Self {
        self.yticklabels = Some(labels);
        self
    }

    /// Set interpolation method
    ///
    /// Only [`Interpolation::Nearest`] is implemented.
    pub fn interpolation(mut self, method: Interpolation) -> Self {
        self.interpolation = method;
        self
    }

    /// Enable or disable cell value annotations
    pub fn annotate(mut self, show: bool) -> Self {
        self.annotate = show;
        self
    }

    /// Set the annotation format string
    ///
    /// The string is a literal with at most one `{...}` placeholder, which is
    /// replaced by the cell value. Everything outside the braces is copied
    /// verbatim, so `"{:.1} °C"` renders `23.4 °C`.
    ///
    /// Supported placeholder specs (a subset of `std::fmt`, chosen so the
    /// format string means what a Rust user expects):
    ///
    /// | Spec | Meaning | `12.3456` renders as |
    /// | --- | --- | --- |
    /// | `{}` | shortest round-trip | `12.3456` |
    /// | `{:.N}` / `{:.Nf}` | `N` decimals | `{:.2}` → `12.35` |
    /// | `{:.Ne}` / `{:.NE}` | scientific | `{:.2e}` → `1.23e1` |
    /// | `{:+.N}` | force a sign | `{:+.1}` → `+12.3` |
    ///
    /// An unrecognised spec falls back to `{}` rather than to a silently
    /// different precision. A string with no placeholder is used as-is, which
    /// is how you label every cell with the same fixed text.
    ///
    /// The default is `"{:.2}"`.
    pub fn annotation_format<S: Into<String>>(mut self, format: S) -> Self {
        self.annotation_format = format.into();
        self
    }

    /// Set aspect ratio (1.0 = square cells)
    ///
    /// Currently inert; see [`HeatmapConfig::aspect`].
    #[deprecated(
        since = "0.6.0",
        note = "not yet implemented; tracked for a future release. Size the figure so the plot area has the ratio you want (Plot::size_px)"
    )]
    #[allow(deprecated)]
    pub fn aspect(mut self, ratio: f64) -> Self {
        self.aspect = Some(ratio);
        self
    }

    /// Set alpha transparency
    pub fn alpha(mut self, alpha: f32) -> Self {
        self.alpha = alpha.clamp(0.0, 1.0);
        self
    }

    /// Enable or disable visible cell borders.
    ///
    /// Borders are disabled by default so heatmaps render as continuous tiles.
    pub fn cell_borders(mut self, enabled: bool) -> Self {
        self.cell_borders = enabled;
        self
    }

    /// Derive `SymLog` linthresh from the smallest positive finite heatmap value.
    ///
    /// When enabled, the configured `AxisScale::SymLog { .. }` linthresh is
    /// replaced during heatmap processing.
    pub fn symlog_auto_linthresh(mut self, enabled: bool) -> Self {
        self.symlog_auto_linthresh = enabled;
        self
    }

    /// Set the physical extent covered by the heatmap grid.
    ///
    /// The extent is interpreted as `(xmin, xmax, ymin, ymax)` and must be
    /// strictly increasing on both axes. Use `xlim`/`ylim` separately when you
    /// want to reverse the visible axis direction.
    pub fn extent(mut self, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> Self {
        self.extent = Some((xmin, xmax, ymin, ymax));
        self
    }

    /// Set the physical Y edge adjacent to row 0.
    ///
    /// [`HeatmapOrigin::Upper`] maps row 0 next to `ymax`, while
    /// [`HeatmapOrigin::Lower`] maps it next to `ymin`. Reversing the displayed
    /// Y axis does not change row identity.
    pub fn origin(mut self, origin: HeatmapOrigin) -> Self {
        self.origin = origin;
        self
    }
}

// Implement PlotConfig marker trait
impl PlotConfig for HeatmapConfig {}

/// Heatmap configuration reachable straight from [`Plot::heatmap`].
///
/// [`Plot::heatmap`] returns `PlotBuilder<HeatmapConfig>`, exactly like the
/// other series methods return their own `PlotBuilder<C>`, so these mirror
/// [`HeatmapConfig`]'s own setters and can be interleaved freely with the
/// shared styling and plot-level methods on the builder.
///
/// Two config knobs are renamed here because the generic builder already spells
/// those names for the whole plot: `HeatmapConfig::alpha` is
/// [`Self::heatmap_alpha`] (the builder's `alpha()` sets the series alpha, and
/// the two multiply), and `HeatmapConfig::annotate` is [`Self::annotate_cells`]
/// (the builder's `annotate()` adds a plot annotation).
///
/// ```rust,no_run
/// use ruviz::prelude::*;
///
/// let data: Vec<Vec<f64>> = (0..8)
///     .map(|i| (0..8).map(|j| (i * j) as f64).collect())
///     .collect();
///
/// Plot::new()
///     .heatmap(&data)
///     .cmap("viridis")
///     .colorbar(true)
///     .colorbar_label("Intensity")
///     .save("heatmap.png")?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// [`Plot::heatmap`]: crate::core::Plot::heatmap
impl PlotBuilder<HeatmapConfig> {
    /// Set the colormap by name (`"viridis"`) or [`ColorMap`] value.
    pub fn cmap(mut self, cmap: impl Into<ColorMapSpec>) -> Self {
        self.config = std::mem::take(&mut self.config).cmap(cmap);
        self
    }

    /// Set the colormap from a [`ColorMap`] value.
    #[deprecated(
        since = "0.6.0",
        note = "renamed: use `cmap(colormap)`, which also accepts a name such as `cmap(\"viridis\")`"
    )]
    pub fn colormap(self, colormap: ColorMap) -> Self {
        self.cmap(colormap)
    }

    /// Set the lower bound of the value-to-colour mapping.
    pub fn vmin(mut self, vmin: f64) -> Self {
        self.config = std::mem::take(&mut self.config).vmin(vmin);
        self
    }

    /// Set the upper bound of the value-to-colour mapping.
    pub fn vmax(mut self, vmax: f64) -> Self {
        self.config = std::mem::take(&mut self.config).vmax(vmax);
        self
    }

    /// Set the scale used for the colour mapping and colorbar ticks.
    pub fn value_scale(mut self, scale: AxisScale) -> Self {
        self.config = std::mem::take(&mut self.config).value_scale(scale);
        self
    }

    // `colorbar`, `colorbar_label`, `colorbar_tick_font_size` and
    // `colorbar_label_font_size` come from `impl_colorbar_builder_methods!`,
    // which every plot type that draws a colour key shares.

    /// Draw minor subticks on logarithmic colorbars.
    pub fn colorbar_log_subticks(mut self, show: bool) -> Self {
        self.config = std::mem::take(&mut self.config).colorbar_log_subticks(show);
        self
    }

    /// Set the cell interpolation method.
    pub fn interpolation(mut self, method: Interpolation) -> Self {
        self.config = std::mem::take(&mut self.config).interpolation(method);
        self
    }

    /// Write each cell's value inside the cell.
    ///
    /// Named apart from the builder's `annotate()`, which adds a plot-level
    /// annotation.
    pub fn annotate_cells(mut self, show: bool) -> Self {
        self.config = std::mem::take(&mut self.config).annotate(show);
        self
    }

    /// Set the format string used for cell annotations.
    pub fn annotation_format<S: Into<String>>(mut self, format: S) -> Self {
        self.config = std::mem::take(&mut self.config).annotation_format(format);
        self
    }

    /// Set the heatmap's own opacity (0.0-1.0).
    ///
    /// Named apart from the builder's `alpha()`, which sets the series alpha;
    /// the two multiply.
    pub fn heatmap_alpha(mut self, alpha: f32) -> Self {
        self.config = std::mem::take(&mut self.config).alpha(alpha);
        self
    }

    /// Draw visible borders around heatmap cells.
    pub fn cell_borders(mut self, enabled: bool) -> Self {
        self.config = std::mem::take(&mut self.config).cell_borders(enabled);
        self
    }

    /// Derive a SymLog `linthresh` from the smallest positive finite value.
    pub fn symlog_auto_linthresh(mut self, enabled: bool) -> Self {
        self.config = std::mem::take(&mut self.config).symlog_auto_linthresh(enabled);
        self
    }

    /// Set the physical extent covered by the grid as `(xmin, xmax, ymin, ymax)`.
    pub fn extent(mut self, xmin: f64, xmax: f64, ymin: f64, ymax: f64) -> Self {
        self.config = std::mem::take(&mut self.config).extent(xmin, xmax, ymin, ymax);
        self
    }

    /// Set the physical Y edge adjacent to row 0.
    pub fn origin(mut self, origin: HeatmapOrigin) -> Self {
        self.config = std::mem::take(&mut self.config).origin(origin);
        self
    }

    /// Set the cell aspect ratio (height / width).
    ///
    /// Currently inert; see [`HeatmapConfig::aspect`].
    #[deprecated(
        since = "0.6.0",
        note = "not yet implemented; tracked for a future release. Size the figure so the plot area has the ratio you want (Plot::size_px)"
    )]
    #[allow(deprecated)]
    pub fn aspect(mut self, ratio: f64) -> Self {
        self.config = std::mem::take(&mut self.config).aspect(ratio);
        self
    }

    /// Set custom X axis tick labels, one per column.
    ///
    /// Currently inert; see [`HeatmapConfig::xticklabels`].
    #[deprecated(
        since = "0.6.0",
        note = "not yet implemented; tracked for a future release. There is no replacement yet: x tick labels come from the axis, via HeatmapConfig::extent"
    )]
    #[allow(deprecated)]
    pub fn xticklabels(mut self, labels: Vec<String>) -> Self {
        self.config = std::mem::take(&mut self.config).xticklabels(labels);
        self
    }

    /// Set custom Y axis tick labels, one per row.
    ///
    /// Currently inert; see [`HeatmapConfig::yticklabels`].
    #[deprecated(
        since = "0.6.0",
        note = "not yet implemented; tracked for a future release. There is no replacement yet: y tick labels come from the axis, via HeatmapConfig::extent"
    )]
    #[allow(deprecated)]
    pub fn yticklabels(mut self, labels: Vec<String>) -> Self {
        self.config = std::mem::take(&mut self.config).yticklabels(labels);
        self
    }
}

/// Processed heatmap data ready for rendering
#[derive(Debug, Clone)]
pub struct HeatmapData {
    /// 2D array of values (row-major order)
    pub values: Vec<Vec<f64>>,
    /// Number of rows
    pub n_rows: usize,
    /// Number of columns
    pub n_cols: usize,
    /// Minimum value in data
    pub data_min: f64,
    /// Maximum value in data
    pub data_max: f64,
    /// Effective minimum for color mapping
    pub vmin: f64,
    /// Effective maximum for color mapping
    pub vmax: f64,
    /// Physical x extent covered by the heatmap grid
    pub x_extent: (f64, f64),
    /// Physical y extent covered by the heatmap grid
    pub y_extent: (f64, f64),
    /// Configuration
    pub config: HeatmapConfig,
}

impl HeatmapData {
    pub(crate) fn can_use_pixel_aligned_grid_fast_path(&self, alpha: f32) -> bool {
        matches!(self.config.interpolation, Interpolation::Nearest) && alpha >= 1.0
    }

    fn x_step(&self) -> f64 {
        (self.x_extent.1 - self.x_extent.0) / self.n_cols.max(1) as f64
    }

    fn y_step(&self) -> f64 {
        (self.y_extent.1 - self.y_extent.0) / self.n_rows.max(1) as f64
    }

    fn row_boundary_data_y(&self, boundary: usize) -> f64 {
        let offset = boundary.min(self.n_rows) as f64 * self.y_step();
        match self.config.origin {
            HeatmapOrigin::Upper => self.y_extent.1 - offset,
            HeatmapOrigin::Lower => self.y_extent.0 + offset,
        }
    }

    pub(crate) fn row_data_bounds(&self, row: usize) -> (f64, f64) {
        let first = self.row_boundary_data_y(row);
        let second = self.row_boundary_data_y(row + 1);
        (first.min(second), first.max(second))
    }

    pub(crate) fn row_at_data_y(&self, y: f64) -> Option<usize> {
        if self.n_rows == 0 || !y.is_finite() || y < self.y_extent.0 || y > self.y_extent.1 {
            return None;
        }

        let distance_from_origin = match self.config.origin {
            HeatmapOrigin::Upper => self.y_extent.1 - y,
            HeatmapOrigin::Lower => y - self.y_extent.0,
        };
        Some(
            (distance_from_origin / self.y_step())
                .floor()
                .clamp(0.0, self.n_rows.saturating_sub(1) as f64) as usize,
        )
    }

    pub(crate) fn cell_at_data_position(&self, x: f64, y: f64) -> Option<(usize, usize)> {
        if self.n_cols == 0 || !x.is_finite() || x < self.x_extent.0 || x > self.x_extent.1 {
            return None;
        }

        let col = ((x - self.x_extent.0) / self.x_step())
            .floor()
            .clamp(0.0, self.n_cols.saturating_sub(1) as f64) as usize;
        Some((self.row_at_data_y(y)?, col))
    }

    pub(crate) fn cell_data_bounds(&self, row: usize, col: usize) -> ((f64, f64), (f64, f64)) {
        let dx = self.x_step();
        let x1 = self.x_extent.0 + col as f64 * dx;
        let x2 = self.x_extent.0 + (col + 1) as f64 * dx;
        let (y1, y2) = self.row_data_bounds(row);
        ((x1, x2), (y1, y2))
    }

    pub(crate) fn cell_screen_rect(
        &self,
        area: &PlotArea,
        row: usize,
        col: usize,
    ) -> (f32, f32, f32, f32) {
        let ((x1, x2), (y1, y2)) = self.cell_data_bounds(row, col);
        // Cell corners are image edges: an extent that starts at zero on a log
        // axis is clipped by the axis, not dropped.
        let (sx1, sy1) = area.edge_data_to_screen(x1, y2);
        let (sx2, sy2) = area.edge_data_to_screen(x2, y1);
        let x = sx1.min(sx2);
        let y = sy1.min(sy2);
        let width = (sx2 - sx1).abs();
        let height = (sy2 - sy1).abs();
        (x, y, width, height)
    }

    fn normalized_value(&self, value: f64) -> f64 {
        self.config
            .value_scale
            .normalized_position(value, self.vmin, self.vmax)
    }

    pub fn should_mask_value(&self, value: f64) -> bool {
        !self.config.value_scale.is_valid_value(value)
    }

    /// Colour used for a cell [`Self::should_mask_value`] rejects.
    ///
    /// Fully transparent, matching the draw paths that skip masked cells
    /// outright.
    pub const MASKED_COLOR: Color = Color::from_rgba(0, 0, 0, 0);

    /// Get color for a specific cell value
    ///
    /// A value [`Self::should_mask_value`] rejects — non-finite, or
    /// non-positive on a [`AxisScale::Log`] value scale — has no position on
    /// the colour ramp, so it renders as the masked colour rather than
    /// whatever `sample(NaN)` happens to produce.
    pub fn get_color(&self, value: f64) -> Color {
        let normalized = self.normalized_value(value);
        if !normalized.is_finite() {
            return Self::MASKED_COLOR;
        }
        self.config.colormap.sample(normalized.clamp(0.0, 1.0))
    }

    /// Render `value` through [`HeatmapConfig::annotation_format`].
    ///
    /// This is the single place the annotation text is produced; renderers must
    /// call it instead of hardcoding a precision, otherwise
    /// `annotation_format` is a silent no-op.
    ///
    /// ```
    /// use ruviz::plots::heatmap::{HeatmapConfig, process_heatmap};
    ///
    /// let data = vec![vec![12.3456, 0.5]];
    /// let heatmap =
    ///     process_heatmap(&data, HeatmapConfig::new().annotation_format("{:.1} °C")).unwrap();
    /// assert_eq!(heatmap.format_annotation(12.3456), "12.3 °C");
    /// ```
    pub fn format_annotation(&self, value: f64) -> String {
        format_with_template(&self.config.annotation_format, value)
    }

    /// Get a contrasting text color for annotations
    pub fn get_text_color(&self, background: Color) -> Color {
        // Calculate relative luminance
        let luminance = 0.299 * (background.r as f64)
            + 0.587 * (background.g as f64)
            + 0.114 * (background.b as f64);
        if luminance > 128.0 {
            Color::BLACK
        } else {
            Color::WHITE
        }
    }

    pub(crate) fn pixel_aligned_screen_edges(&self, area: &PlotArea) -> (Vec<i32>, Vec<i32>) {
        let x_min = area.x;
        let x_max = area.x + area.width;
        let y_min = area.y;
        let y_max = area.y + area.height;
        let x_step = self.x_step();

        let x_edges = (0..=self.n_cols)
            .map(|index| {
                let x = self.x_extent.0 + index as f64 * x_step;
                area.edge_data_to_screen(x, self.y_extent.0)
                    .0
                    .clamp(x_min, x_max)
                    .round() as i32
            })
            .collect();
        let y_edges = (0..=self.n_rows)
            .map(|index| {
                let y = self.row_boundary_data_y(index);
                area.edge_data_to_screen(self.x_extent.0, y)
                    .1
                    .clamp(y_min, y_max)
                    .round() as i32
            })
            .collect();

        (x_edges, y_edges)
    }

    fn draw_cells_pixel_aligned_grid(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        alpha: f32,
    ) -> PlotResult<()> {
        let (x_edges, y_edges) = self.pixel_aligned_screen_edges(area);

        for row in 0..self.n_rows {
            let top = y_edges[row].min(y_edges[row + 1]);
            let bottom = y_edges[row].max(y_edges[row + 1]);
            if bottom <= top {
                continue;
            }

            for col in 0..self.n_cols {
                let value = self.values[row][col];
                if self.should_mask_value(value) {
                    continue;
                }

                let left = x_edges[col].min(x_edges[col + 1]);
                let right = x_edges[col].max(x_edges[col + 1]);
                if right <= left {
                    continue;
                }

                let cell_color = self.get_color(value).with_alpha(alpha);
                let x = left as f32;
                let y = top as f32;
                let width = (right - left) as f32;
                let height = (bottom - top) as f32;

                renderer.draw_pixel_aligned_solid_rectangle(x, y, width, height, cell_color)?;

                if self.config.cell_borders {
                    renderer.draw_pixel_aligned_rectangle_outline(
                        x,
                        y,
                        width,
                        height,
                        cell_color.darken(0.2),
                    )?;
                }
            }
        }

        Ok(())
    }

    fn draw_cells_legacy(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        alpha: f32,
    ) -> PlotResult<()> {
        for row in 0..self.n_rows {
            for col in 0..self.n_cols {
                let value = self.values[row][col];
                if self.should_mask_value(value) {
                    continue;
                }

                let cell_color = self.get_color(value).with_alpha(alpha);

                let (x, y, width, height) = self.cell_screen_rect(area, row, col);
                let left = x.max(area.x);
                let top = y.max(area.y);
                let right = (x + width).min(area.x + area.width);
                let bottom = (y + height).min(area.y + area.height);
                if right <= left || bottom <= top {
                    continue;
                }
                let width = right - left;
                let height = bottom - top;

                renderer
                    .draw_pixel_aligned_solid_rectangle(left, top, width, height, cell_color)?;

                if self.config.cell_borders {
                    renderer.draw_pixel_aligned_rectangle_outline(
                        left,
                        top,
                        width,
                        height,
                        cell_color.darken(0.2),
                    )?;
                }
            }
        }

        Ok(())
    }

    pub(crate) fn draw_cells_batch(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        alpha: f32,
    ) -> PlotResult<()> {
        if self.can_use_pixel_aligned_grid_fast_path(alpha) {
            return self.draw_cells_pixel_aligned_grid(renderer, area, alpha);
        }

        self.draw_cells_legacy(renderer, area, alpha)
    }
}

/// Apply a `{...}`-style template to one `f64`.
///
/// `std::fmt` needs its format string at compile time, so a runtime template
/// has to be interpreted. This handles the subset documented on
/// [`HeatmapConfig::annotation_format`]: literal text plus at most one
/// placeholder of the form `{[:][+][.precision][f|e|E]}`.
fn format_with_template(template: &str, value: f64) -> String {
    let Some(open) = template.find('{') else {
        // No placeholder at all: the caller wants fixed literal text.
        return template.to_string();
    };
    let Some(close) = template[open..].find('}').map(|offset| open + offset) else {
        return template.to_string();
    };

    let prefix = &template[..open];
    let suffix = &template[close + 1..];
    let inner = &template[open + 1..close];
    let spec = inner.strip_prefix(':').unwrap_or(inner);

    format!("{prefix}{}{suffix}", format_value(spec, value))
}

/// Format one value against a `std::fmt`-style spec body (the part after `:`).
fn format_value(spec: &str, value: f64) -> String {
    if spec.is_empty() {
        return format!("{value}");
    }

    let (plus, rest) = match spec.strip_prefix('+') {
        Some(rest) => (true, rest),
        None => (false, spec),
    };

    let (digits, kind) = if let Some(digits) = rest.strip_suffix('e') {
        (digits, 'e')
    } else if let Some(digits) = rest.strip_suffix('E') {
        (digits, 'E')
    } else if let Some(digits) = rest.strip_suffix('f') {
        (digits, 'f')
    } else {
        (rest, 'f')
    };

    // Anything that is not `.<digits>` is not a spec we understand (widths,
    // fill/align, `#`, …). Falling back to Display is honest; guessing a
    // precision would not be.
    let precision = if digits.is_empty() {
        None
    } else if let Some(number) = digits.strip_prefix('.')
        && !number.is_empty()
        && number.bytes().all(|byte| byte.is_ascii_digit())
    {
        match number.parse::<usize>() {
            Ok(precision) => Some(precision),
            Err(_) => return format!("{value}"),
        }
    } else {
        return format!("{value}");
    };

    match (kind, precision, plus) {
        ('e', Some(precision), true) => format!("{value:+.precision$e}"),
        ('e', Some(precision), false) => format!("{value:.precision$e}"),
        ('e', None, true) => format!("{value:+e}"),
        ('e', None, false) => format!("{value:e}"),
        ('E', Some(precision), true) => format!("{value:+.precision$E}"),
        ('E', Some(precision), false) => format!("{value:.precision$E}"),
        ('E', None, true) => format!("{value:+E}"),
        ('E', None, false) => format!("{value:E}"),
        (_, Some(precision), true) => format!("{value:+.precision$}"),
        (_, Some(precision), false) => format!("{value:.precision$}"),
        (_, None, true) => format!("{value:+}"),
        (_, None, false) => format!("{value}"),
    }
}

/// Process a 2D array into HeatmapData
pub fn process_heatmap(data: &[Vec<f64>], config: HeatmapConfig) -> Result<HeatmapData, String> {
    if data.is_empty() {
        return Err("Heatmap data is empty".to_string());
    }

    let n_rows = data.len();
    let n_cols = data[0].len();

    // Verify all rows have the same length
    for (i, row) in data.iter().enumerate() {
        if row.len() != n_cols {
            return Err(format!(
                "Row {} has {} columns, expected {}",
                i,
                row.len(),
                n_cols
            ));
        }
    }

    let mut config = config;
    let (x_extent, y_extent) = match config.extent {
        Some((xmin, xmax, ymin, ymax)) => {
            if !xmin.is_finite() || !xmax.is_finite() || !ymin.is_finite() || !ymax.is_finite() {
                return Err("Heatmap extent must contain only finite values".to_string());
            }
            if xmax <= xmin || ymax <= ymin {
                return Err("Heatmap extent must satisfy xmin < xmax and ymin < ymax".to_string());
            }
            ((xmin, xmax), (ymin, ymax))
        }
        None => ((0.0, n_cols as f64), (0.0, n_rows as f64)),
    };

    // Calculate data range
    let mut data_min = f64::INFINITY;
    let mut data_max = f64::NEG_INFINITY;
    let mut positive_min = f64::INFINITY;
    let mut positive_max = f64::NEG_INFINITY;

    for row in data {
        for &value in row {
            if value.is_finite() {
                data_min = data_min.min(value);
                data_max = data_max.max(value);
                if value > 0.0 {
                    positive_min = positive_min.min(value);
                    positive_max = positive_max.max(value);
                }
            }
        }
    }

    if !data_min.is_finite() || !data_max.is_finite() {
        return Err("Heatmap data contains only non-finite values".to_string());
    }

    if config.symlog_auto_linthresh
        && let AxisScale::SymLog { .. } = config.value_scale
    {
        if !positive_min.is_finite() {
            return Err(
                "SymLog auto linthresh requires at least one positive finite value.".to_string(),
            );
        }
        config.value_scale = AxisScale::SymLog {
            linthresh: positive_min,
        };
    }

    // Use config overrides or data range
    let (vmin, vmax) = match config.value_scale {
        AxisScale::Log => {
            let vmin = if let Some(vmin) = config.vmin {
                vmin
            } else if positive_min.is_finite() {
                positive_min
            } else {
                return Err(
                    "Logarithmic heatmaps require at least one positive finite value.".to_string(),
                );
            };
            let vmax = if let Some(vmax) = config.vmax {
                vmax
            } else if positive_max.is_finite() {
                positive_max
            } else {
                return Err(
                    "Logarithmic heatmaps require at least one positive finite value.".to_string(),
                );
            };
            (vmin, vmax)
        }
        _ => (
            config.vmin.unwrap_or(data_min),
            config.vmax.unwrap_or(data_max),
        ),
    };
    config.value_scale.validate_range(vmin, vmax)?;

    Ok(HeatmapData {
        values: data.to_vec(),
        n_rows,
        n_cols,
        data_min,
        data_max,
        vmin,
        vmax,
        x_extent,
        y_extent,
        config,
    })
}

/// Process a flat array with dimensions into HeatmapData
pub fn process_heatmap_flat(
    data: &[f64],
    n_rows: usize,
    n_cols: usize,
    config: HeatmapConfig,
) -> Result<HeatmapData, String> {
    if data.len() != n_rows * n_cols {
        return Err(format!(
            "Data length {} does not match dimensions {}x{}",
            data.len(),
            n_rows,
            n_cols
        ));
    }

    // Convert to 2D array
    let values: Vec<Vec<f64>> = (0..n_rows)
        .map(|r| data[r * n_cols..(r + 1) * n_cols].to_vec())
        .collect();

    process_heatmap(&values, config)
}

// =============================================================================
// PlotData and PlotRender implementations
// =============================================================================

impl PlotData for HeatmapData {
    fn data_bounds(&self) -> ((f64, f64), (f64, f64)) {
        (
            (
                self.x_extent.0.min(self.x_extent.1),
                self.x_extent.0.max(self.x_extent.1),
            ),
            (
                self.y_extent.0.min(self.y_extent.1),
                self.y_extent.0.max(self.y_extent.1),
            ),
        )
    }

    fn is_empty(&self) -> bool {
        self.values.is_empty() || self.values[0].is_empty()
    }
}

impl PlotRender for HeatmapData {
    fn render(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        _theme: &Theme,
        _color: Color, // Heatmaps use colormap, not single color
    ) -> PlotResult<()> {
        if self.is_empty() {
            return Ok(());
        }

        let config = &self.config;
        self.draw_cells_batch(renderer, area, config.alpha)
    }

    fn render_styled(
        &self,
        renderer: &mut SkiaRenderer,
        area: &PlotArea,
        theme: &Theme,
        _color: Color,
        alpha: f32,
        _line_width: Option<f32>,
    ) -> PlotResult<()> {
        if self.is_empty() {
            return Ok(());
        }

        let config = &self.config;
        let _resolver = StyleResolver::new(theme);

        let effective_alpha = config.alpha * alpha.clamp(0.0, 1.0);

        self.draw_cells_batch(renderer, area, effective_alpha)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::plot::Image;

    fn mean_normalized_rgba_diff(reference: &Image, candidate: &Image) -> f64 {
        assert_eq!(reference.width, candidate.width);
        assert_eq!(reference.height, candidate.height);

        reference
            .pixels
            .iter()
            .zip(candidate.pixels.iter())
            .map(|(lhs, rhs)| (*lhs as f64 - *rhs as f64).abs() / 255.0)
            .sum::<f64>()
            / reference.pixels.len() as f64
    }

    fn fraction_pixels_within_channel_delta(
        reference: &Image,
        candidate: &Image,
        max_delta: u8,
    ) -> f64 {
        assert_eq!(reference.width, candidate.width);
        assert_eq!(reference.height, candidate.height);

        let mut matching = 0usize;
        for (lhs, rhs) in reference
            .pixels
            .chunks_exact(4)
            .zip(candidate.pixels.chunks_exact(4))
        {
            if lhs
                .iter()
                .zip(rhs.iter())
                .all(|(left, right)| (*left as i16 - *right as i16).abs() <= max_delta as i16)
            {
                matching += 1;
            }
        }
        matching as f64 / (reference.width * reference.height) as f64
    }

    fn non_background_fraction(image: &Image) -> f64 {
        let total = image.pixels.chunks_exact(4).len() as f64;
        let ink = image
            .pixels
            .chunks_exact(4)
            .filter(|pixel| pixel[3] > 0 && (pixel[0] < 248 || pixel[1] < 248 || pixel[2] < 248))
            .count() as f64;
        ink / total.max(1.0)
    }

    fn assert_heatmap_parity(reference: &Image, candidate: &Image) {
        let mean_diff = mean_normalized_rgba_diff(reference, candidate);
        let within_delta = fraction_pixels_within_channel_delta(reference, candidate, 24);
        let reference_ink = non_background_fraction(reference);
        let candidate_ink = non_background_fraction(candidate);

        assert!(
            mean_diff <= 0.015,
            "heatmap drifted too far from legacy cells: mean_diff={mean_diff:.6}"
        );
        assert!(
            within_delta >= 0.99,
            "heatmap has too many per-pixel outliers relative to legacy cells: within_delta={within_delta:.4}"
        );
        assert!(
            (reference_ink - candidate_ink).abs() <= 0.10,
            "heatmap changed visible ink coverage too much: reference_ink={reference_ink:.4} candidate_ink={candidate_ink:.4}"
        );
    }

    fn render_heatmap_cells(
        data: &HeatmapData,
        area: &PlotArea,
        use_legacy: bool,
    ) -> crate::core::Result<Image> {
        let mut renderer = SkiaRenderer::new(120, 120, Theme::default())?;
        if use_legacy {
            data.draw_cells_legacy(&mut renderer, area, data.config.alpha)?;
        } else {
            data.draw_cells_batch(&mut renderer, area, data.config.alpha)?;
        }
        Ok(renderer.into_image())
    }

    #[test]
    fn test_heatmap_config_defaults() {
        let config = HeatmapConfig::default();
        assert!(config.colorbar);
        assert!(!config.annotate);
        assert_eq!(config.interpolation, Interpolation::Nearest);
        assert!(config.vmin.is_none());
        assert!(config.vmax.is_none());
        assert_eq!(config.value_scale, AxisScale::Linear);
        assert!(config.colorbar_log_subticks);
        assert!(!config.cell_borders);
        assert!(!config.symlog_auto_linthresh);
        assert!(config.extent.is_none());
        assert_eq!(config.origin, HeatmapOrigin::Upper);
        assert_eq!(HeatmapOrigin::default(), HeatmapOrigin::Upper);
        // Unset by default, so the theme decides. Hardcoded 12/14 pt was why
        // `Theme::ieee()`'s 8 pt ticks sat beside a 12 pt colorbar.
        assert!(config.colorbar_tick_font_size.is_none());
        assert!(config.colorbar_label_font_size.is_none());
    }

    /// The colorbar's ticks track the axis ticks and its caption tracks the
    /// axis labels, for every theme, with no per-plot-type literals in between.
    #[test]
    fn colorbar_fonts_follow_the_theme_by_default() {
        for theme in [Theme::default(), Theme::dark(), Theme::ieee()] {
            let sizes = HeatmapConfig::default().colorbar_font_sizes(&theme);
            assert_eq!(sizes.tick, theme.tick_label_font_size);
            assert_eq!(sizes.label, theme.axis_label_font_size);
        }
    }

    #[test]
    fn explicit_colorbar_fonts_win_over_the_theme() {
        let theme = Theme::ieee();
        let sizes = HeatmapConfig::default()
            .colorbar_tick_font_size(18.0)
            .colorbar_label_font_size(24.0)
            .colorbar_font_sizes(&theme);
        assert_eq!(sizes.tick, 18.0);
        assert_eq!(sizes.label, 24.0);
        // Sizes below 1 pt would render nothing; they are clamped, not taken.
        let clamped = HeatmapConfig::default().colorbar_tick_font_size(-3.0);
        assert_eq!(clamped.colorbar_font_sizes(&theme).tick, 1.0);
    }

    #[test]
    fn test_explicit_upper_origin_is_pixel_compatible_with_default() {
        let values = vec![vec![0.0, 1.0], vec![2.0, 3.0], vec![4.0, 5.0]];
        let default = process_heatmap(&values, HeatmapConfig::new().colorbar(false))
            .expect("default heatmap should process");
        let explicit = process_heatmap(
            &values,
            HeatmapConfig::new()
                .colorbar(false)
                .origin(HeatmapOrigin::Upper),
        )
        .expect("explicit upper heatmap should process");
        let area = PlotArea::new(7.0, 11.0, 91.0, 89.0, 0.0, 2.0, 0.0, 3.0);

        let default_image = render_heatmap_cells(&default, &area, false).unwrap();
        let explicit_image = render_heatmap_cells(&explicit, &area, false).unwrap();

        assert_eq!(default_image.pixels, explicit_image.pixels);
    }

    #[test]
    fn test_opaque_nearest_heatmap_fast_path_stays_in_parity_with_legacy_cells() {
        let rows = 48usize;
        let cols = 256usize;
        let stripe_start = cols / 2 - 4;
        let stripe_end = stripe_start + 8;
        let mut values = vec![vec![0.0; cols]; rows];
        for row in &mut values {
            for cell in &mut row[stripe_start..stripe_end] {
                *cell = 1.0;
            }
        }

        let area = PlotArea::new(8.0, 10.0, 90.0, 92.0, 0.0, cols as f64, 0.0, rows as f64);

        for origin in [HeatmapOrigin::Upper, HeatmapOrigin::Lower] {
            let data =
                process_heatmap(&values, HeatmapConfig::new().colorbar(false).origin(origin))
                    .expect("heatmap data should process");
            let reference =
                render_heatmap_cells(&data, &area, true).expect("legacy heatmap render");
            let candidate = render_heatmap_cells(&data, &area, false).expect("fast heatmap render");

            assert_heatmap_parity(&reference, &candidate);
        }
    }

    #[test]
    fn test_translucent_heatmap_keeps_legacy_cell_renderer() {
        let values = vec![
            vec![0.1, 0.4, 0.7],
            vec![0.2, 0.5, 0.8],
            vec![0.3, 0.6, 0.9],
        ];
        let data = process_heatmap(&values, HeatmapConfig::new().colorbar(false).alpha(0.5))
            .expect("heatmap data should process");
        let area = PlotArea::new(8.0, 10.0, 90.0, 92.0, 0.0, 3.0, 0.0, 3.0);

        let reference = render_heatmap_cells(&data, &area, true).expect("legacy heatmap render");
        let candidate =
            render_heatmap_cells(&data, &area, false).expect("translucent heatmap render");

        assert_eq!(reference.pixels, candidate.pixels);
    }

    #[test]
    fn test_heatmap_config_builder() {
        let config = HeatmapConfig::new()
            .cmap(ColorMap::plasma())
            .vmin(0.0)
            .vmax(100.0)
            .value_scale(AxisScale::Log)
            .colorbar(true)
            .colorbar_label("Temperature")
            .colorbar_log_subticks(false)
            .cell_borders(true)
            .symlog_auto_linthresh(true)
            .extent(0.0, 3.0, 0.0, 2.0)
            .origin(HeatmapOrigin::Lower)
            .annotate(true);

        assert_eq!(config.vmin, Some(0.0));
        assert_eq!(config.vmax, Some(100.0));
        assert_eq!(config.value_scale, AxisScale::Log);
        assert!(config.colorbar);
        assert_eq!(config.colorbar_label, Some("Temperature".to_string()));
        assert!(!config.colorbar_log_subticks);
        assert!(config.cell_borders);
        assert!(config.symlog_auto_linthresh);
        assert_eq!(config.extent, Some((0.0, 3.0, 0.0, 2.0)));
        assert_eq!(config.origin, HeatmapOrigin::Lower);
        assert!(config.annotate);
    }

    #[test]
    fn test_row_mapping_uses_physical_extent_and_consistent_boundaries() {
        let values = vec![vec![0.0], vec![1.0], vec![2.0]];

        let upper =
            process_heatmap(&values, HeatmapConfig::new().extent(10.0, 14.0, 20.0, 26.0)).unwrap();
        assert_eq!(upper.row_data_bounds(0), (24.0, 26.0));
        assert_eq!(upper.row_data_bounds(2), (20.0, 22.0));
        assert_eq!(upper.row_at_data_y(26.0), Some(0));
        assert_eq!(upper.row_at_data_y(24.0), Some(1));
        assert_eq!(upper.row_at_data_y(20.0), Some(2));
        assert_eq!(upper.cell_at_data_position(14.0, 26.0), Some((0, 0)));

        let lower = process_heatmap(
            &values,
            HeatmapConfig::new()
                .extent(10.0, 14.0, 20.0, 26.0)
                .origin(HeatmapOrigin::Lower),
        )
        .unwrap();
        assert_eq!(lower.row_data_bounds(0), (20.0, 22.0));
        assert_eq!(lower.row_data_bounds(2), (24.0, 26.0));
        assert_eq!(lower.row_at_data_y(20.0), Some(0));
        assert_eq!(lower.row_at_data_y(22.0), Some(1));
        assert_eq!(lower.row_at_data_y(26.0), Some(2));
        assert_eq!(lower.cell_at_data_position(10.0, 20.0), Some((0, 0)));

        for data in [&upper, &lower] {
            assert_eq!(data.row_at_data_y(19.999), None);
            assert_eq!(data.row_at_data_y(26.001), None);
            assert_eq!(data.cell_at_data_position(9.999, 23.0), None);
            assert_eq!(data.cell_at_data_position(14.001, 23.0), None);
        }
    }

    #[test]
    fn test_reversed_displayed_y_axis_changes_screen_position_not_row_identity() {
        let values = vec![vec![0.0], vec![1.0], vec![2.0]];
        let normal_area = PlotArea::new(0.0, 0.0, 30.0, 90.0, 10.0, 14.0, 20.0, 26.0);
        let reversed_area = PlotArea::new(0.0, 0.0, 30.0, 90.0, 10.0, 14.0, 26.0, 20.0);

        for (origin, normal_y, reversed_y) in [
            (HeatmapOrigin::Upper, 0.0, 60.0),
            (HeatmapOrigin::Lower, 60.0, 0.0),
        ] {
            let data = process_heatmap(
                &values,
                HeatmapConfig::new()
                    .extent(10.0, 14.0, 20.0, 26.0)
                    .origin(origin),
            )
            .unwrap();

            assert_eq!(
                data.cell_at_data_position(12.0, 25.0),
                match origin {
                    HeatmapOrigin::Upper => Some((0, 0)),
                    HeatmapOrigin::Lower => Some((2, 0)),
                }
            );
            let (_, y, _, height) = data.cell_screen_rect(&normal_area, 0, 0);
            let (_, reversed_y_actual, _, reversed_height) =
                data.cell_screen_rect(&reversed_area, 0, 0);
            assert!((y - normal_y).abs() < 1e-4);
            assert!((reversed_y_actual - reversed_y).abs() < 1e-4);
            assert!((height - 30.0).abs() < 1e-4);
            assert!((reversed_height - 30.0).abs() < 1e-4);
        }
    }

    #[test]
    fn test_process_heatmap() {
        let data = vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]];
        let config = HeatmapConfig::default();
        let result = process_heatmap(&data, config).unwrap();

        assert_eq!(result.n_rows, 2);
        assert_eq!(result.n_cols, 3);
        assert!((result.data_min - 1.0).abs() < f64::EPSILON);
        assert!((result.data_max - 6.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_process_heatmap_with_vmin_vmax() {
        let data = vec![vec![1.0, 2.0], vec![3.0, 4.0]];
        let config = HeatmapConfig::new().vmin(0.0).vmax(10.0);
        let result = process_heatmap(&data, config).unwrap();

        assert!((result.vmin - 0.0).abs() < f64::EPSILON);
        assert!((result.vmax - 10.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_process_heatmap_uses_custom_extent() {
        let data = vec![vec![1.0, 2.0], vec![3.0, 4.0]];
        let config = HeatmapConfig::new().extent(10.0, 14.0, 20.0, 24.0);
        let result = process_heatmap(&data, config).unwrap();

        assert_eq!(result.x_extent, (10.0, 14.0));
        assert_eq!(result.y_extent, (20.0, 24.0));
    }

    #[test]
    fn test_process_heatmap_rejects_invalid_extent() {
        let data = vec![vec![1.0, 2.0], vec![3.0, 4.0]];
        let config = HeatmapConfig::new().extent(1.0, 1.0, 0.0, 2.0);
        assert!(process_heatmap(&data, config).is_err());
    }

    #[test]
    fn test_process_heatmap_empty() {
        let data: Vec<Vec<f64>> = vec![];
        let config = HeatmapConfig::default();
        assert!(process_heatmap(&data, config).is_err());
    }

    #[test]
    fn test_process_heatmap_jagged() {
        let data = vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0]]; // Jagged array
        let config = HeatmapConfig::default();
        assert!(process_heatmap(&data, config).is_err());
    }

    #[test]
    fn test_heatmap_get_color() {
        let data = vec![vec![0.0, 1.0]];
        let config = HeatmapConfig::new().vmin(0.0).vmax(1.0);
        let heatmap = process_heatmap(&data, config).unwrap();

        // At vmin, should get first color of colormap
        let color_min = heatmap.get_color(0.0);
        // At vmax, should get last color of colormap
        let color_max = heatmap.get_color(1.0);

        // Colors should be different
        assert!(color_min != color_max);
    }

    #[test]
    fn test_heatmap_get_color_uses_log_value_scale() {
        let data = vec![vec![1.0, 10.0, 100.0]];
        let config = HeatmapConfig::new()
            .vmin(1.0)
            .vmax(100.0)
            .value_scale(AxisScale::Log);
        let heatmap = process_heatmap(&data, config).unwrap();

        let log_mid = heatmap.get_color(10.0);
        let expected_mid = heatmap.config.colormap.sample(0.5);
        assert_eq!(log_mid, expected_mid);
    }

    #[test]
    fn test_process_heatmap_log_scale_ignores_nonpositive_cells_for_auto_range() {
        let data = vec![vec![0.0, 1.0], vec![10.0, 100.0]];
        let config = HeatmapConfig::new().value_scale(AxisScale::Log);
        let result = process_heatmap(&data, config).unwrap();

        assert_eq!(result.vmin, 1.0);
        assert_eq!(result.vmax, 100.0);
    }

    #[test]
    fn test_process_heatmap_rejects_invalid_explicit_log_bounds() {
        let data = vec![vec![0.0, 1.0], vec![10.0, 100.0]];
        let config = HeatmapConfig::new().value_scale(AxisScale::Log).vmin(0.0);
        assert!(process_heatmap(&data, config).is_err());
    }

    #[test]
    fn test_process_heatmap_log_scale_rejects_missing_positive_values() {
        let data = vec![vec![0.0, -1.0], vec![f64::NEG_INFINITY, f64::NAN]];
        let config = HeatmapConfig::new().value_scale(AxisScale::Log);
        assert!(process_heatmap(&data, config).is_err());
    }

    #[test]
    fn test_process_heatmap_symlog_auto_linthresh_uses_smallest_positive_value() {
        let data = vec![vec![0.0, 0.01], vec![1.0, 10.0]];
        let config = HeatmapConfig::new()
            .value_scale(AxisScale::symlog(1.0))
            .symlog_auto_linthresh(true);
        let result = process_heatmap(&data, config).unwrap();

        assert_eq!(
            result.config.value_scale,
            AxisScale::SymLog { linthresh: 0.01 }
        );
    }

    #[test]
    fn test_process_heatmap_symlog_auto_linthresh_rejects_missing_positive_values() {
        let data = vec![vec![0.0, -1.0], vec![-10.0, f64::NAN]];
        let config = HeatmapConfig::new()
            .value_scale(AxisScale::symlog(1.0))
            .symlog_auto_linthresh(true);

        assert!(process_heatmap(&data, config).is_err());
    }

    #[test]
    fn test_get_text_color() {
        let data = vec![vec![0.0, 1.0]];
        let config = HeatmapConfig::default();
        let heatmap = process_heatmap(&data, config).unwrap();

        // Dark background should get white text
        let white_text = heatmap.get_text_color(Color::BLACK);
        assert_eq!(white_text, Color::WHITE);

        // Light background should get black text
        let black_text = heatmap.get_text_color(Color::WHITE);
        assert_eq!(black_text, Color::BLACK);
    }

    #[test]
    fn test_process_heatmap_flat() {
        let flat_data = vec![1.0, 2.0, 3.0, 4.0, 5.0, 6.0];
        let config = HeatmapConfig::default();
        let result = process_heatmap_flat(&flat_data, 2, 3, config).unwrap();

        assert_eq!(result.n_rows, 2);
        assert_eq!(result.n_cols, 3);
        assert_eq!(result.values[0], vec![1.0, 2.0, 3.0]);
        assert_eq!(result.values[1], vec![4.0, 5.0, 6.0]);
    }

    #[test]
    fn test_interpolation_enum() {
        assert_eq!(Interpolation::default(), Interpolation::Nearest);
    }

    // ------------------------------------------------------------------
    // annotation_format (plan item 2.4)
    // ------------------------------------------------------------------

    fn formatted(template: &str, value: f64) -> String {
        let heatmap = process_heatmap(
            &[vec![value]],
            HeatmapConfig::new().annotation_format(template),
        )
        .unwrap();
        heatmap.format_annotation(value)
    }

    #[test]
    fn test_annotation_format_default_is_two_decimals() {
        assert_eq!(formatted("{:.2}", 12.3456), "12.35");
        assert_eq!(HeatmapConfig::default().annotation_format, "{:.2}");
    }

    #[test]
    fn test_annotation_format_honours_precision() {
        assert_eq!(formatted("{:.0}", 12.3456), "12");
        assert_eq!(formatted("{:.1}", 12.3456), "12.3");
        assert_eq!(formatted("{:.4}", 12.3456), "12.3456");
        assert_eq!(formatted("{:.3f}", 12.3456), "12.346");
    }

    #[test]
    fn test_annotation_format_supports_scientific_and_sign() {
        assert_eq!(formatted("{:.2e}", 12345.0), "1.23e4");
        assert_eq!(formatted("{:.1E}", 12345.0), "1.2E4");
        assert_eq!(formatted("{:+.1}", 12.34), "+12.3");
        assert_eq!(formatted("{:+.1}", -12.34), "-12.3");
    }

    #[test]
    fn test_annotation_format_keeps_literal_text_around_the_placeholder() {
        assert_eq!(formatted("{:.1} °C", 23.44), "23.4 °C");
        assert_eq!(formatted("~{:.0}%", 61.2), "~61%");
    }

    #[test]
    fn test_annotation_format_without_a_placeholder_is_a_fixed_label() {
        assert_eq!(formatted("n/a", 12.34), "n/a");
    }

    #[test]
    fn test_annotation_format_falls_back_to_display_on_an_unsupported_spec() {
        // A width or an unknown flag must not silently become some other
        // precision.
        assert_eq!(formatted("{:8.2}", 12.5), "12.5");
        assert_eq!(formatted("{:?}", 12.5), "12.5");
        assert_eq!(formatted("{}", 12.5), "12.5");
        assert_eq!(formatted("{:.}", 12.5), "12.5");
    }

    #[test]
    fn test_annotation_format_survives_an_unterminated_placeholder() {
        assert_eq!(formatted("{:.2", 12.5), "{:.2");
    }

    #[test]
    fn test_annotation_format_is_actually_reachable_from_the_config() {
        // The whole point of the item: two different format strings must
        // produce two different annotation strings.
        assert_ne!(formatted("{:.0}", 12.3456), formatted("{:.3}", 12.3456));
    }

    #[test]
    fn test_heatmap_config_implements_plot_config() {
        fn assert_plot_config<T: PlotConfig>() {}
        assert_plot_config::<HeatmapConfig>();
    }

    #[test]
    fn test_heatmap_plot_data_trait() {
        let data = vec![vec![1.0, 2.0, 3.0], vec![4.0, 5.0, 6.0]];
        let config = HeatmapConfig::default();
        let heatmap = process_heatmap(&data, config).unwrap();

        // Test data_bounds
        let ((x_min, x_max), (y_min, y_max)) = heatmap.data_bounds();
        assert!((x_min - 0.0).abs() < 0.001);
        assert!((x_max - 3.0).abs() < 0.001);
        assert!((y_min - 0.0).abs() < 0.001);
        assert!((y_max - 2.0).abs() < 0.001);

        // Test is_empty
        assert!(!heatmap.is_empty());
    }

    #[test]
    fn test_heatmap_plot_data_trait_uses_extent_bounds() {
        let data = vec![vec![1.0, 2.0], vec![3.0, 4.0]];
        let config = HeatmapConfig::new().extent(0.0, 8.0, 0.0, 4.0);
        let heatmap = process_heatmap(&data, config).unwrap();

        let ((x_min, x_max), (y_min, y_max)) = heatmap.data_bounds();
        assert_eq!((x_min, x_max), (0.0, 8.0));
        assert_eq!((y_min, y_max), (0.0, 4.0));
    }
}