lichtung-plot 0.3.0

Strongly typed scientific plotting with deterministic SVG and PNG output
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
//! Private semantic value access shared by plot renderers.

pub use crate::input::AxisValues;
pub use crate::spec::{Bounds, EstimateStatus};
pub use crate::values::SourceRows;
pub use arrays::{ArrayElementType, ArrayValueType, ArrayValues, NdArray};
#[doc(hidden)]
/// The actual native collection capture, for source-free adapter restoration.
#[doc(hidden)]
pub enum CapturedCollection<'a> {
    /// A wide expansion whose original column projection is retained.
    Wide(&'a DataSourceInfo),
    /// A rectangular heatmap's actual positional coordinates.
    Grid {
        /// Original selected cell rectangle.
        source: &'a DataSourceInfo,
        /// Actual column coordinates.
        x: &'a crate::CategoryValues,
        /// Actual row coordinates.
        y: &'a crate::CategoryValues,
    },
    /// Ordered native Matrix variables.
    Matrix(&'a VariableValues),
}

pub use binding::CapturedValue;
pub(crate) use binding::VectorSource;
pub use binding::{
    BindingGeneration, BindingSelector, BindingSelectorKind, BindingSlice, DataSourceInfo,
    DataSourceRef,
};
#[doc(hidden)]
pub use binding::{ColumnKeyLookup, ColumnKeySource, GeneratedColumns};
pub(crate) use identity::InstanceId;
pub use integer::{ExactInteger, IntegerValues};
pub(crate) use key::key_bytes;
pub use key::{
    IntervalClosed, IntervalKey, KeyColumns, KeyValues, NamedKeyValues, RawKey, RawKeyValues,
    UnavailableKey,
};
pub use payload::{DataPayload, DataValueType};
pub(crate) use protocol::{select_value, DomainSlot};
pub use protocol::{
    AxisValueType, ComponentPathPart, DataComponentInfo, DataDomainInfo, DataDomainRef,
    DataRoleInfo, DataRoleRef, DataSelector, DataValue, MemberAddress, SourceMember, SourceMembers,
    SourceMembersEntry,
};
pub use roles::DataRole;
pub use status::EstimateStatusBinding;
pub use temporal::{
    Date, DateValues, Duration, DurationUnit, DurationValues, LocalTimestamp, TimeValues, TimeZone,
    Timestamp,
};
pub use variables::{NamedNumericValues, VariableValues};

use crate::{BooleanValues, CategoryValues, Error, NumericValues};

mod arrays;
pub(crate) mod binding;
pub(crate) mod category;
pub(crate) mod group_key;
mod identity;
mod integer;
mod key;
mod payload;
pub use group_key::{GroupDimension, GroupDimensionRef, GroupKey, GroupKeys};
mod grouped;
pub use grouped::GroupedObservations;
mod protocol;
mod roles;
pub(crate) mod source;
mod status;
mod temporal;
mod variables;

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

    #[test]
    fn original_source_selection_survives_projection_and_alpha_materialization() {
        let reference = DataSourceRef::capture();
        let next = reference.recapture();
        assert_ne!(reference, next);
        assert!(reference.same_source(&next));
        assert!(!reference.same_source(&DataSourceRef::capture()));
        let key = RawKey::Tuple(vec![
            RawKey::from("measurement"),
            RawKey::Integer(17.into()),
        ]);
        let source = DataSourceInfo::selected(
            reference.clone(),
            BindingSelector::Key(key.clone()),
            Some(vec![key.clone()]),
            vec![4],
            vec![3, 7],
            vec![3],
        );
        let values = NumericValues::new("internal", [-0., -0., 0.5, 0.5, 1., 1.])
            .with_field_key(key.clone(), "measurement")
            .with_repeated_source(source, 2)
            .unwrap();
        let mapped = crate::scales::AlphaValues::linear(values, (0., 1.), (0., 1.)).unwrap();
        let selected = mapped.select([3, 0, 5, 0]).unwrap();
        let raw = selected.get_numeric_source().unwrap();
        assert_eq!(raw.name(), "measurement");
        assert_eq!(raw.field_key(), Some(&key));
        assert_eq!(raw.get_source().reference(), &reference);
        assert_eq!(raw.get_source().selected_indices(), Some(&[4][..]));
        assert_eq!(raw.get_source().source_shape(), &[3, 7]);
        assert_eq!(raw.get_source().selected_shape(), &[3]);
        assert_eq!(
            (0..raw.len())
                .map(|index| raw.source_slot(index))
                .collect::<Vec<_>>(),
            [Some(1), Some(0), Some(2), Some(0)]
        );
        assert_eq!(
            raw.get(1).flatten().unwrap().to_bits(),
            (-0.0_f64).to_bits()
        );
    }

    #[test]
    fn direct_alpha_preserves_authored_values_and_checked_source_relations() {
        let source = DataSourceInfo::direct(vec![2]);
        let values = NumericValues::new("opacity", [-0., 0.75]);
        assert!(values
            .clone()
            .with_repeated_source(source.clone(), 0)
            .is_err());
        assert!(values
            .clone()
            .with_repeated_source(source.clone(), 2)
            .is_err());
        assert!(values
            .clone()
            .with_source_slots(source.clone(), vec![0, 2])
            .is_err());
        let values = values.with_source(source.clone()).unwrap();
        let alpha = crate::scales::AlphaValues::try_from(values).unwrap();
        assert_eq!(alpha.get(0).unwrap().to_bits(), 0.0_f64.to_bits());
        let selected = alpha.select([1, 0, 1]).unwrap();
        let original = selected.get_numeric_source().unwrap();
        assert_eq!(original.get_source(), &source);
        assert_eq!(
            original.get(1).flatten().unwrap().to_bits(),
            (-0.0_f64).to_bits()
        );
        assert_eq!(original.source_slot(2), Some(1));
    }

    #[test]
    fn original_values_distinguish_validity_from_finiteness_and_identity() {
        let numbers = NumericValues::nullable(
            "numeric",
            [Some(f64::NAN), None, Some(-0.), Some(f64::INFINITY)],
        );
        assert!(numbers.get(0).flatten().unwrap().is_nan());
        assert_eq!(numbers.get(1), Some(None));
        assert_eq!(
            numbers.get(2).flatten().unwrap().to_bits(),
            (-0.0_f64).to_bits()
        );
        assert_eq!(numbers.get(3).flatten(), Some(f64::INFINITY));
        assert_eq!(numbers.is_valid(0), Some(true));
        assert_eq!(numbers.is_valid(1), Some(false));
        assert_eq!(numbers.is_valid(4), None);
        let categories = CategoryValues::nullable("category", [Some(""), None, Some("A")]).unwrap();
        assert_eq!(
            categories.iter().collect::<Vec<_>>(),
            [Some(""), None, Some("A")]
        );
        assert_eq!(categories.levels(), ["", "A"]);
        let booleans = BooleanValues::nullable("boolean", [Some(false), None, Some(true)]);
        assert_eq!(
            booleans.iter().collect::<Vec<_>>(),
            [Some(false), None, Some(true)]
        );
    }

    #[test]
    fn exact_keys_keep_arbitrary_magnitude_and_temporal_fields() {
        let huge = ExactInteger::from_parts(false, &[1; 24]).unwrap();
        assert!(huge.to_u128().is_none());
        assert_eq!(ExactInteger::from(i128::MIN).to_i128(), Some(i128::MIN));
        assert_eq!(ExactInteger::from(u128::MAX).to_u128(), Some(u128::MAX));
        assert_eq!(
            ExactInteger::from_parts(true, &[0, 0]).unwrap(),
            ExactInteger::from(0)
        );
        assert!(
            ExactInteger::from_parts(true, huge.magnitude_be()).unwrap()
                < ExactInteger::from(i128::MIN)
        );
        let values =
            IntegerValues::nullable("counts", [Some(huge.clone()), None, Some(2.into())]).unwrap();
        assert_eq!(values.get(0), Some(Some(&huge)));
        assert_eq!(values.is_valid(1), Some(false));
        assert_eq!(values.get(3), None);
        assert!(Date::new(1900, 2, 29).is_err());
        let date = Date::new(2000, 2, 29).unwrap();
        let instant = Timestamp::new(
            -1,
            999_999_999,
            Some(TimeZone::FixedOffset(0)),
            Some(0),
            None,
        )
        .unwrap();
        assert_eq!(instant.unix_ns(), -1);
        let local = LocalTimestamp::new(date, 1, 2, 3, 7).unwrap();
        let key = RawKey::Tuple(vec![RawKey::Integer(huge), RawKey::LocalTimestamp(local)]);
        let keys = RawKeyValues::nullable(
            "raw",
            [
                Some(key.clone()),
                None,
                Some(key.clone()),
                Some(RawKey::Instant(instant)),
            ],
        )
        .unwrap();
        assert_eq!(keys.levels().len(), 2);
        assert_eq!(keys.get(2), Some(Some(&key)));
        assert_eq!(keys.is_valid(1), Some(false));
        assert_ne!(RawKey::Float(-0.), RawKey::Float(0.));
    }
}

pub(crate) const X: &str = "__x";
pub(crate) const Y: &str = "__y";
pub(crate) const HUE: &str = "__hue";
pub(crate) const GROUP: &str = "__group";
pub(crate) const SERIES: &str = "__series";
pub(crate) const COLOR: &str = "__color";
pub(crate) const INTERVAL_LOWER: &str = "__interval_lower";
pub(crate) const INTERVAL_UPPER: &str = "__interval_upper";
pub(crate) const BAR_INTERVAL_LOWER: &str = "__bar_interval_lower";
pub(crate) const BAR_INTERVAL_UPPER: &str = "__bar_interval_upper";
pub(crate) const BAR_UNITS: &str = "__bar_units";
pub(crate) const HIGHLIGHT_CELLS: &str = "__highlight_cells";
pub(crate) const DUMBBELL_RIGHT: &str = "__dumbbell_right";
pub(crate) const FACET_ROW: &str = "__facet_row";
pub(crate) const FACET_COLUMN: &str = "__facet_column";
pub(crate) const FACET_WRAP: &str = "__facet_wrap";

#[derive(Debug, Clone, Copy)]
pub(crate) enum DataColumn<'a> {
    Numeric(&'a NumericValues),
    Category(&'a CategoryValues),
    Boolean(&'a BooleanValues),
}

impl<'a> DataColumn<'a> {
    pub(crate) const fn is_numeric(self) -> bool {
        matches!(self, Self::Numeric(_))
    }

    pub(crate) fn name(self) -> &'a str {
        match self {
            Self::Numeric(values) => values.name(),
            Self::Category(values) => values.name(),
            Self::Boolean(values) => values.name(),
        }
    }

    pub(crate) fn len(self) -> usize {
        match self {
            Self::Numeric(values) => values.len(),
            Self::Category(values) => values.len(),
            Self::Boolean(values) => values.len(),
        }
    }
}

/// Global axis inputs normally installed on a generic facet child Plot.
#[derive(Clone, Copy)]
pub(crate) struct FacetAxisSources<'a> {
    pub(crate) hues: Option<&'a [String]>,
    pub(crate) groups: Option<&'a [String]>,
    pub(crate) conditions: Option<&'a [String]>,
}

/// A borrowed semantic plot view, optionally restricted to selected source rows.
#[derive(Clone, Copy)]
pub(crate) struct PlotData<'src, 'op> {
    source: &'src crate::builder::PlotDescription,
    rows: Option<&'op [usize]>,
    diagnostic_rows: DiagnosticRows<'src, 'op>,
    numeric_facet: Option<&'op crate::layout::FacetCell>,
    scope: &'op crate::orchestrator::registration::Scope,
    operation: &'op crate::font::canonical::OperationContext,
    row_source: &'op source::RowSourceContext<'src>,
}

#[derive(Clone, Copy)]
pub(crate) enum DiagnosticRows<'src, 'op> {
    Native(Option<&'src crate::data::SourceRows>),
    Selected(&'op [usize]),
}

impl std::fmt::Debug for PlotData<'_, '_> {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        formatter
            .debug_struct("PlotData")
            .field("height", &self.height())
            .field("is_full_plot", &self.is_full_plot())
            .finish_non_exhaustive()
    }
}

impl<'src, 'op> PlotData<'src, 'op> {
    pub(crate) fn checked(
        source: &'src crate::builder::PlotDescription,
        scope: &'op crate::orchestrator::registration::Scope,
        row_source: &'op source::RowSourceContext<'src>,
        operation: &'op crate::font::canonical::OperationContext,
    ) -> Result<Self, Error> {
        row_source.check(source, scope, operation)?;
        let (rows, diagnostic_rows) = scope.rows.selected().map_or_else(
            || (None, DiagnosticRows::Native(source.source_row_map())),
            |(rows, diagnostic_rows)| (Some(rows), DiagnosticRows::Selected(diagnostic_rows)),
        );
        Ok(Self {
            source,
            rows,
            diagnostic_rows,
            numeric_facet: scope.numeric_owner.facet.as_ref(),
            scope,
            operation,
            row_source,
        })
    }

    pub(crate) const fn numeric_facet(self) -> Option<&'op crate::layout::FacetCell> {
        self.numeric_facet
    }

    pub(crate) fn facet_selector(
        self,
    ) -> Result<Option<crate::orchestrator::registration::FacetSelector<'src, 'op>>, Error> {
        if self.height() == 0 {
            return Ok(None);
        }
        self.source
            .facet_spec()
            .zip(self.numeric_facet())
            .map(|(schema, levels)| {
                crate::orchestrator::registration::FacetSelector::checked(schema, levels)
            })
            .transpose()
    }

    pub(crate) const fn source_resources(self) -> &'op crate::font::canonical::OperationContext {
        self.operation
    }

    #[cfg(test)]
    pub(crate) const fn plot_id(self) -> &'op crate::orchestrator::registration::PlotOccurrenceId {
        self.row_source.owner()
    }

    pub(crate) fn column(self, key: &str) -> Result<DataColumn<'src>, Error> {
        #[cfg(test)]
        SOURCE_COLUMN_READS.with(|calls| calls.set(calls.get() + 1));
        self.source
            .data_column(key)
            .ok_or_else(|| Error::Data(format!("unknown semantic value {key:?}").into()))
    }

    pub(crate) fn height(self) -> usize {
        self.rows
            .map_or_else(|| self.source.row_count(), <[usize]>::len)
    }

    pub(crate) const fn is_full_plot(self) -> bool {
        self.rows.is_none()
    }

    fn member_context(
        self,
        row: usize,
        binding: RawKey,
        column: &str,
    ) -> crate::errors::ErrorContext {
        use crate::{
            elements::LayerSlot,
            errors::{ErrorContext, OperationPhase},
            layout::PanelPath,
        };
        let mut panel = PanelPath::root();
        if let Some((row, column)) = self.scope.numeric_owner.canvas {
            panel = panel.panel(row, column);
        }
        if let Some(facet) = self.numeric_facet {
            panel = panel.facet(facet.clone());
        }
        let member = if self.source.source_row_map().is_some() {
            MemberAddress::RowId(self.source_row(row))
        } else {
            MemberAddress::Slot(self.row_index(row))
        };
        let mut context = ErrorContext::new()
            .with_operation(OperationPhase::Prepare)
            .with_panel(panel)
            .with_layer(LayerSlot::Primary)
            .with_member(member)
            .with_binding(binding);
        if let Some(role) = self.source.column_role(column) {
            context = context.with_role(role);
        }
        context
    }

    pub(crate) fn source_row(self, local_row: usize) -> usize {
        let diagnostic = match self.diagnostic_rows {
            DiagnosticRows::Native(rows) => rows.and_then(|rows| rows.as_slice().get(local_row)),
            DiagnosticRows::Selected(rows) => rows.get(local_row),
        };
        diagnostic
            .copied()
            .unwrap_or_else(|| self.row_index(local_row))
    }

    pub(crate) fn estimate_statuses(
        self,
    ) -> Result<Option<Vec<crate::data::EstimateStatus>>, Error> {
        let Some(statuses) = self.source.estimate_status_values() else {
            return Ok(None);
        };
        crate::data::source::collect_source((0..self.height())
            .map(|row| {

                statuses.get(self.row_index(row)).copied().ok_or_else(|| {
                    Error::Data(format!(
                        "estimate status values are shorter than the aligned plot input at source row {}",
                        self.source_row(row)
                    ).into())
                })
            }))
            .map(Some)
    }

    pub(crate) fn row_index(self, local_row: usize) -> usize {
        self.rows
            .and_then(|rows| rows.get(local_row))
            .copied()
            .unwrap_or(local_row)
    }

    /// Alpha arrays align with complete original input slots, not public row IDs.
    pub(crate) fn observation_alpha(
        self,
        alpha: &crate::alpha::PreparedAlpha,
        local_row: usize,
    ) -> Result<Option<crate::alpha::ResolvedAlpha>, Error> {
        if local_row >= self.height() {
            return Err(Error::Data(
                format!("alpha local row {local_row} is outside the selected input").into(),
            ));
        }
        alpha.observation(self.row_index(local_row), self.source_row(local_row))
    }
}

/// Isolated scientific fixtures borrow the same build binding as production.
/// No prepared owner or operation-backed view can escape the callback.
#[cfg(test)]
pub(crate) fn with_source_data_for_test<'src, T>(
    source: &'src crate::Plot,
    operation: &crate::font::canonical::OperationContext,
    rows: crate::orchestrator::registration::RowSelection,
    visit: impl FnOnce(PlotData<'src, '_>) -> T,
) -> Result<T, Error> {
    let scope = crate::orchestrator::registration::Scope::new(
        source.description(),
        operation,
        0,
        crate::layout::ComponentAddress::root().child(crate::layout::AddressRole::PlotBody, 0)?,
        rows,
        None,
        None,
    )?;
    let mut registry =
        crate::orchestrator::registration::PlotRegistryBuilder::new(operation.root_identity());
    let policy = crate::orchestrator::registration::PlotScopePolicy::for_source(
        source.description(),
        scope.numeric_owner.facet.as_ref(),
    );
    let id = registry.reserve(
        source.description(),
        scope.address,
        scope.numeric_owner,
        scope.axis_numeric_owner,
        scope.rows,
        scope.render_name,
        policy,
        source.description().resolve_theme()?,
        operation,
    )?;
    Ok(visit(registry.data(&id, operation)?))
}

pub(crate) fn strict_finite_f64(
    data: PlotData<'_, '_>,
    column: &str,
    plot: &str,
) -> Result<Vec<f64>, Error> {
    let DataColumn::Numeric(values) = data.column(column)? else {
        return Err(Error::Data(
            format!(
                "{plot}: value {:?} must be numeric",
                data.column(column)?.name()
            )
            .into(),
        ));
    };
    crate::data::source::collect_source((0..data.height()).map(|row| {
        match values.get(data.row_index(row)) {
            Some(Some(value)) if value.is_finite() => Ok(value),
            Some(value) => {
                use crate::errors::{Diagnostic, DiagnosticKind};
                let status = value.map_or_else(
                    || "null".to_owned(),
                    |value| format!("non-finite value {value}"),
                );
                let binding = values
                    .field_key()
                    .cloned()
                    .unwrap_or_else(|| RawKey::from(values.name()));
                Err(Error::Data(
                    Diagnostic::new(
                        DiagnosticKind::InvalidValue {
                            value: value.map(RawKey::Float),
                            constraint: "present finite numeric value".to_owned(),
                        },
                        format!(
                            "{plot}: value {:?} contains {status} at source row {}",
                            values.name(),
                            data.source_row(row)
                        ),
                    )
                    .with_context(data.member_context(row, binding, column)),
                ))
            }
            None => Err(length_error(plot, values.name(), row)),
        }
    }))
}

#[cfg(test)]
thread_local! {
    pub(crate) static SOURCE_COLUMN_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

pub(crate) fn strict_numeric_value(
    values: &NumericValues,
    row: usize,
    plot: &str,
) -> Result<f64, Error> {
    match values.get(row) {
        Some(Some(value)) if value.is_finite() => Ok(value),
        Some(Some(value)) => Err(Error::Data(
            format!(
                "{plot}: value {:?} contains non-finite value {value} at source row {}",
                values.name(),
                row
            )
            .into(),
        )),
        Some(None) => Err(Error::Data(
            format!(
                "{plot}: value {:?} contains null at source row {}",
                values.name(),
                row
            )
            .into(),
        )),
        None => unreachable!("row is bounded by NumericValues::len"),
    }
}

pub(crate) fn strict_category_at<'a>(
    values: &'a CategoryValues,
    input_slot: usize,
    diagnostic_row: usize,
    context: &str,
) -> Result<&'a str, Error> {
    match values.get(input_slot) {
        Some(Some(value)) => Ok(value),
        Some(None) => Err(Error::Data(
            format!(
                "{context}: value {:?} contains null at source row {diagnostic_row}",
                values.name()
            )
            .into(),
        )),
        None => Err(length_error(context, values.name(), input_slot)),
    }
}

pub(crate) fn strict_numeric_at(
    values: &NumericValues,
    input_slot: usize,
    diagnostic_row: usize,
    context: &str,
) -> Result<f64, Error> {
    match values.get(input_slot) {
        Some(Some(value)) if value.is_finite() => Ok(value),
        Some(Some(value)) => Err(Error::Data(format!(
            "{context}: value {:?} contains non-finite value {value} at source row {diagnostic_row}",
            values.name()
        ).into())),
        Some(None) => Err(Error::Data(format!(
            "{context}: value {:?} contains null at source row {diagnostic_row}",
            values.name()
        ).into())),
        None => Err(length_error(context, values.name(), input_slot)),
    }
}

pub(crate) fn strict_source_strings(
    values: &CategoryValues,
    rows: Option<&crate::data::SourceRows>,
    context: &str,
) -> Result<Vec<String>, Error> {
    source::collect_source((0..values.len()).map(|slot| {
        let diagnostic = rows
            .and_then(|rows| rows.as_slice().get(slot))
            .copied()
            .unwrap_or(slot);
        source::copy_source_string(strict_category_at(values, slot, diagnostic, context)?)
    }))
}

pub(crate) fn strict_source_f64(
    values: &NumericValues,
    rows: Option<&crate::data::SourceRows>,
    context: &str,
) -> Result<Vec<f64>, Error> {
    source::collect_source((0..values.len()).map(|slot| {
        let diagnostic = rows
            .and_then(|rows| rows.as_slice().get(slot))
            .copied()
            .unwrap_or(slot);
        strict_numeric_at(values, slot, diagnostic, context)
    }))
}

pub(crate) fn strict_source_normalized_strings(
    values: &CategoryValues,
    rows: Option<&crate::data::SourceRows>,
    context: &str,
    role: &str,
) -> Result<Vec<String>, Error> {
    source::collect_source(strict_source_strings(values, rows, context)?.into_iter().enumerate().map(|(slot, value)| {
        let normalized = source::normalize_source_string(&value)?;
        if normalized.is_empty() {
            let diagnostic = rows.and_then(|rows| rows.as_slice().get(slot)).copied().unwrap_or(slot);
            Err(Error::Data(format!("{context}: {role} label is empty after whitespace normalization at source row {diagnostic}").into()))
        } else {
            Ok(normalized)
        }
    }))
}

pub(crate) fn nullable_finite_f64(
    data: PlotData<'_, '_>,
    column: &str,
    plot: &str,
) -> Result<Vec<Option<f64>>, Error> {
    let DataColumn::Numeric(values) = data.column(column)? else {
        return Err(Error::Data(
            format!(
                "{plot}: value {:?} must be numeric",
                data.column(column)?.name()
            )
            .into(),
        ));
    };
    crate::data::source::collect_source((0..data.height()).map(|row| {
        match values.get(data.row_index(row)) {
            Some(Some(value)) if value.is_finite() => Ok(Some(value)),
            Some(Some(value)) => Err(Error::Data(
                format!(
                    "{plot}: value {:?} contains non-finite value {value} at source row {}",
                    values.name(),
                    data.source_row(row)
                )
                .into(),
            )),
            Some(None) => Ok(None),
            None => Err(length_error(plot, values.name(), row)),
        }
    }))
}

pub(crate) fn strict_bool(
    data: PlotData<'_, '_>,
    column: &str,
    plot: &str,
) -> Result<Vec<bool>, Error> {
    let DataColumn::Boolean(values) = data.column(column)? else {
        return Err(Error::Data(
            format!(
                "{plot}: value {:?} must be Boolean",
                data.column(column)?.name()
            )
            .into(),
        ));
    };
    crate::data::source::collect_source((0..data.height()).map(|row| {
        match values.get(data.row_index(row)) {
            Some(Some(value)) => Ok(value),
            Some(None) => Err(Error::Data(
                format!(
                    "{plot}: value {:?} contains null at source row {}",
                    values.name(),
                    data.source_row(row)
                )
                .into(),
            )),
            None => Err(length_error(plot, values.name(), row)),
        }
    }))
}

pub(crate) fn aligned_finite_rows(
    data: PlotData<'_, '_>,
    x_column: &str,
    y_column: &str,
    plot: &str,
) -> Result<Vec<(usize, f64, f64)>, Error> {
    let x = optional_finite_f64(data, x_column, plot)?;
    let y = optional_finite_f64(data, y_column, plot)?;
    if x.len() != y.len() {
        return Err(Error::Data(
            format!(
                "{plot}: aligned value length mismatch {} vs {}",
                x.len(),
                y.len()
            )
            .into(),
        ));
    }
    let mut rows = Vec::new();
    crate::data::source::reserve_source(&mut rows, x.len())?;

    rows.extend(
        x.into_iter()
            .zip(y)
            .enumerate()
            .filter_map(|(row, (x, y))| Some((row, x?, y?))),
    );
    Ok(rows)
}

fn optional_finite_f64(
    data: PlotData<'_, '_>,
    column: &str,
    plot: &str,
) -> Result<Vec<Option<f64>>, Error> {
    let DataColumn::Numeric(values) = data.column(column)? else {
        return Err(Error::Data(
            format!(
                "{plot}: value {:?} must be numeric",
                data.column(column)?.name()
            )
            .into(),
        ));
    };
    crate::data::source::collect_source((0..data.height()).map(|row| {
        match values.get(data.row_index(row)) {
            Some(Some(value)) if value.is_infinite() => Err(Error::Data(
                format!(
                    "{plot}: value {:?} contains infinite value {value} at source row {}",
                    values.name(),
                    data.source_row(row)
                )
                .into(),
            )),
            Some(Some(value)) if value.is_nan() => Ok(None),
            Some(value) => Ok(value),
            None => Err(length_error(plot, values.name(), row)),
        }
    }))
}

#[derive(Debug)]
pub(crate) struct CollectiveChannels {
    pub(crate) groups: Option<Vec<String>>,
    pub(crate) hues: Option<Vec<String>>,
    pub(crate) group_levels: Vec<String>,
    pub(crate) hue_levels: Vec<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub(crate) struct CollectivePair {
    pub(crate) group: Option<String>,
    pub(crate) hue: Option<String>,
}

impl CollectivePair {
    pub(crate) fn description(&self, collapsed: bool) -> String {
        match (&self.group, &self.hue, collapsed) {
            (Some(group), _, true) | (Some(group), None, false) => {
                format!("graphical group {group:?}")
            }
            (Some(group), Some(hue), false) => {
                format!("graphical group {group:?} with hue {hue:?}")
            }
            (None, Some(hue), _) => format!("hue {hue:?}"),
            (None, None, _) => "ungrouped series".to_string(),
        }
    }
}

#[derive(Debug)]
pub(crate) struct ObservedCollectives {
    pub(crate) rows: Vec<CollectivePair>,
    pub(crate) identities: Vec<CollectivePair>,
    pub(crate) group_levels: Vec<String>,
    pub(crate) hue_levels: Vec<String>,
    pub(crate) collapsed: bool,
}

pub(crate) fn observed_collectives(
    data: PlotData<'_, '_>,
    group_column: Option<&str>,
    hue_column: Option<&str>,
    retained_rows: Option<&[usize]>,
    plot: &str,
) -> Result<ObservedCollectives, Error> {
    let mut row_indices = Vec::new();
    crate::data::source::reserve_source(
        &mut row_indices,
        retained_rows.map_or(data.height(), <[usize]>::len),
    )?;
    if let Some(rows) = retained_rows {
        row_indices.extend_from_slice(rows);
    } else {
        row_indices.extend(0..data.height());
    }
    let groups = group_column
        .map(|column| strict_strings_for_rows(data, column, &row_indices, plot))
        .transpose()?;
    let hues = hue_column
        .map(|column| strict_strings_for_rows(data, column, &row_indices, plot))
        .transpose()?;
    finish_observed_collectives(
        groups,
        hues,
        data.source,
        row_indices.len(),
        |index| data.source_row(row_indices[index]),
        plot,
    )
}

#[expect(
    clippy::needless_pass_by_value,
    reason = "the decoded source arrays belong to this reduction and are not retained by its callers"
)]
fn finish_observed_collectives(
    groups: Option<Vec<String>>,
    hues: Option<Vec<String>>,
    source: &crate::builder::PlotDescription,
    row_count: usize,
    diagnostic_row: impl Fn(usize) -> usize,
    plot: &str,
) -> Result<ObservedCollectives, Error> {
    let collapsed = source.same_group_hue_field();
    if collapsed {
        let group = source.legend_group_values().expect("actual group field");
        let hue = source.legend_hue_values().expect("actual hue field");
        let (Some(groups), Some(hues)) = (groups.as_ref(), hues.as_ref()) else {
            return Err(Error::Data(
                format!(
                    "{plot}: equal graphical group and hue names require both categorical channels"
                )
                .into(),
            ));
        };
        if let Some(index) = groups
            .iter()
            .zip(hues)
            .position(|(group_level, hue_level)| !group.same_level_key(group_level, hue, hue_level))
        {
            return Err(Error::Data(format!(
                "{plot}: graphical group and hue share semantic name {:?} but differ at source row {}",
                group.original_name(),
                diagnostic_row(index)
            ).into()));
        }
    }

    let rows = crate::data::source::collect_source((0..row_count).map(|index| {
        Ok(CollectivePair {
            group: groups
                .as_ref()
                .map(|values| crate::data::source::copy_source_string(&values[index]))
                .transpose()?,
            hue: hues
                .as_ref()
                .map(|values| crate::data::source::copy_source_string(&values[index]))
                .transpose()?,
        })
    }))?;
    let group_levels = groups.as_ref().map_or_else(
        || Ok(Vec::new()),
        |values| crate::data::source::source_levels(values),
    )?;
    let hue_levels = hues.as_ref().map_or_else(
        || Ok(Vec::new()),
        |values| crate::data::source::source_levels(values),
    )?;
    let mut identities = Vec::new();
    crate::data::source::reserve_source(&mut identities, rows.len())?;
    if groups.is_some() {
        for group in &group_levels {
            for identity in &rows {
                if identity.group.as_ref() != Some(group) {
                    continue;
                }
                if crate::data::source::source_position(&identities, |seen| seen == identity)
                    .is_none()
                {
                    identities.push(crate::data::source::copy_source_pair(identity)?);
                }
            }
        }
    } else {
        for identity in &rows {
            if crate::data::source::source_position(&identities, |seen| seen == identity).is_none()
            {
                identities.push(crate::data::source::copy_source_pair(identity)?);
            }
        }
    }

    Ok(ObservedCollectives {
        rows,
        identities,
        group_levels,
        hue_levels,
        collapsed,
    })
}

fn strict_strings_for_rows(
    data: PlotData<'_, '_>,
    column: &str,
    rows: &[usize],
    plot: &str,
) -> Result<Vec<String>, Error> {
    let DataColumn::Category(values) = data.column(column)? else {
        return Err(Error::Data(
            format!(
                "{plot}: value {:?} must be categorical",
                data.column(column)?.name()
            )
            .into(),
        ));
    };
    crate::data::source::collect_source(rows.iter().map(|row| {
        match values.get(data.row_index(*row)) {
            Some(Some(value)) => crate::data::source::copy_source_string(value),
            Some(None) => Err(Error::Data(
                format!(
                    "{plot}: value {:?} contains null at source row {}",
                    values.name(),
                    data.source_row(*row)
                )
                .into(),
            )),
            None => Err(length_error(plot, values.name(), *row)),
        }
    }))
}

pub(crate) fn collective_channels(
    data: PlotData<'_, '_>,
    group_column: Option<&str>,
    hue_column: Option<&str>,
    cells: Option<&[String]>,
    plot: &str,
) -> Result<CollectiveChannels, Error> {
    let groups = group_column
        .map(|column| strict_strings(data, column, plot))
        .transpose()?;
    let hues = hue_column
        .map(|column| strict_strings(data, column, plot))
        .transpose()?;
    let row_count = data.height();
    finish_collective_channels(
        groups,
        hues,
        cells,
        row_count,
        |row| data.source_row(row),
        plot,
    )
}

pub(crate) fn finish_collective_channels(
    groups: Option<Vec<String>>,
    hues: Option<Vec<String>>,
    cells: Option<&[String]>,
    row_count: usize,
    diagnostic_row: impl Fn(usize) -> usize,
    plot: &str,
) -> Result<CollectiveChannels, Error> {
    if groups
        .as_ref()
        .is_some_and(|values| values.len() != row_count)
        || hues
            .as_ref()
            .is_some_and(|values| values.len() != row_count)
        || cells.is_some_and(|values| values.len() != row_count)
    {
        return Err(Error::Data(
            format!(
                "{plot}: graphical group, hue, and mark-cell values must align with the plot input"
            )
            .into(),
        ));
    }

    if let Some(hues_ref) = hues.as_ref() {
        let mut marks: Vec<(Option<&str>, Option<&str>, &str)> = Vec::new();
        crate::data::source::reserve_source(&mut marks, row_count)?;
        for row in 0..row_count {
            let cell = cells.map(|values| values[row].as_str());
            let group = groups.as_ref().map(|values| values[row].as_str());
            let hue = hues_ref[row].as_str();
            if let Some(index) =
                crate::data::source::source_position(&marks, |(seen_cell, seen_group, _)| {
                    *seen_cell == cell && *seen_group == group
                })
            {
                let (_, _, seen_hue) = &marks[index];
                if *seen_hue != hue {
                    return Err(Error::Data(format!(
                        "{plot}: each collective mark must have exactly one hue; found {seen_hue:?} and {hue:?} at source row {}",
                        diagnostic_row(row)
                    ).into()));
                }
            } else {
                marks.push((cell, group, hue));
            }
        }
    }

    Ok(CollectiveChannels {
        group_levels: groups.as_ref().map_or_else(
            || Ok(Vec::new()),
            |values| crate::data::source::source_levels(values),
        )?,
        hue_levels: hues.as_ref().map_or_else(
            || Ok(Vec::new()),
            |values| crate::data::source::source_levels(values),
        )?,
        groups,
        hues,
    })
}

pub(crate) fn source_collective_channels(
    source: &crate::builder::PlotDescription,
    cells: Option<&[String]>,
    context: &str,
) -> Result<CollectiveChannels, Error> {
    let strings = |key: &str| {
        let column = source
            .data_column(key)
            .ok_or_else(|| Error::Data(format!("unknown semantic value {key:?}").into()))?;
        let DataColumn::Category(values) = column else {
            return Err(Error::Data(
                format!("{context}: value {:?} must be categorical", column.name()).into(),
            ));
        };
        strict_source_strings(values, None, context)
    };
    let groups = source.group_col().map(strings).transpose()?;
    let hues = source.hue_col().map(strings).transpose()?;
    finish_collective_channels(groups, hues, cells, source.row_count(), |row| row, context)
}

pub(crate) fn observed_source_collectives(
    source: &crate::builder::PlotDescription,
    context: &str,
) -> Result<ObservedCollectives, Error> {
    let rows = source.source_row_map();
    let mut row_indices = Vec::new();
    self::source::reserve_source(&mut row_indices, source.row_count())?;
    row_indices.extend(0..source.row_count());
    let strings = |key: &str| {
        let column = source
            .data_column(key)
            .ok_or_else(|| Error::Data(format!("unknown semantic value {key:?}").into()))?;
        let DataColumn::Category(values) = column else {
            return Err(Error::Data(
                format!("{context}: value {:?} must be categorical", column.name()).into(),
            ));
        };
        strict_source_strings(values, rows, context)
    };
    let groups = source.group_col().map(strings).transpose()?;
    let hues = source.hue_col().map(strings).transpose()?;
    finish_observed_collectives(
        groups,
        hues,
        source,
        row_indices.len(),
        |slot| {
            let slot = row_indices[slot];
            rows.and_then(|rows| rows.as_slice().get(slot))
                .copied()
                .unwrap_or(slot)
        },
        context,
    )
}

pub(crate) fn stable_levels(values: &[String]) -> Vec<String> {
    let mut levels = Vec::new();
    for value in values {
        if !levels.contains(value) {
            levels.push(value.clone());
        }
    }
    levels
}

pub(crate) fn explicit_category_order(
    observed: &[String],
    requested: &[String],
    context: &str,
    allow_unobserved: bool,
) -> Result<Vec<String>, Error> {
    let mut seen = Vec::new();
    crate::data::source::reserve_source(&mut seen, requested.len())?;
    for level in requested {
        if seen.contains(level) {
            return Err(Error::Data(
                format!("{context}: explicit category order contains duplicate level {level:?}")
                    .into(),
            ));
        }

        if !allow_unobserved && !observed.contains(level) {
            return Err(Error::Data(
                format!("{context}: explicit category order contains unknown level {level:?}")
                    .into(),
            ));
        }
        seen.push(crate::data::source::copy_source_string(level)?);
    }
    for level in observed {
        if !seen.contains(level) {
            return Err(Error::Data(
                format!("{context}: explicit category order omits observed level {level:?}").into(),
            ));
        }
    }
    if allow_unobserved {
        seen.retain(|level| observed.contains(level));
    }
    Ok(seen)
}

pub(crate) fn strict_strings(
    data: PlotData<'_, '_>,
    column: &str,
    plot: &str,
) -> Result<Vec<String>, Error> {
    let DataColumn::Category(values) = data.column(column)? else {
        return Err(Error::Data(
            format!(
                "{plot}: value {:?} must be categorical",
                data.column(column)?.name()
            )
            .into(),
        ));
    };
    crate::data::source::collect_source((0..data.height()).map(|row| {
        match values.get(data.row_index(row)) {
            Some(Some(value)) => crate::data::source::copy_source_string(value),
            Some(None) => {
                use crate::errors::{Diagnostic, DiagnosticKind};
                let binding = values
                    .field_key()
                    .cloned()
                    .unwrap_or_else(|| RawKey::from(values.name()));
                Err(Error::Data(
                    Diagnostic::new(
                        DiagnosticKind::InvalidValue {
                            value: None,
                            constraint: "present category".to_owned(),
                        },
                        format!(
                            "{plot}: value {:?} contains null at source row {}",
                            values.name(),
                            data.source_row(row)
                        ),
                    )
                    .with_context(data.member_context(row, binding, column)),
                ))
            }
            None => Err(length_error(plot, values.name(), row)),
        }
    }))
}

pub(crate) fn strict_normalized_strings(
    data: PlotData<'_, '_>,
    column: &str,
    plot: &str,
    role: &str,
) -> Result<Vec<String>, Error> {
    crate::data::source::collect_source(
        strict_strings(data, column, plot)?
            .into_iter()
            .enumerate()
            .map(|(row, value)| {
                let normalized = crate::data::source::normalize_source_string(&value)?;
                if normalized.is_empty() {
                    Err(Error::Data(
                        format!(
                    "{plot}: {role} label is empty after whitespace normalization at source row {}",
                    data.source_row(row)
                )
                        .into(),
                    ))
                } else {
                    Ok(normalized)
                }
            }),
    )
}

pub(crate) fn collapse_whitespace(value: &str) -> String {
    value.split_whitespace().collect::<Vec<_>>().join(" ")
}

pub(crate) fn min_max(
    values: impl IntoIterator<Item = f64>,
    plot: &str,
) -> Result<(f64, f64), Error> {
    let mut range: Option<(f64, f64)> = None;
    for value in values {
        if !value.is_finite() {
            return Err(Error::Data(
                format!("{plot}: cannot compute range from non-finite value {value}").into(),
            ));
        }
        range = Some(range.map_or((value, value), |(lo, hi)| (lo.min(value), hi.max(value))));
    }
    range.ok_or_else(|| Error::Data(format!("{plot}: cannot compute range from no values").into()))
}

fn length_error(plot: &str, name: &str, row: usize) -> Error {
    Error::Data(
        format!("{plot}: value {name:?} is shorter than the aligned plot input at row {row}")
            .into(),
    )
}

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

    #[test]
    fn typed_source_reads_keep_full_read_precedence_and_diagnostic_rows() {
        let values = CategoryValues::nullable("category", [Some("   "), None]).unwrap();
        let rows = crate::data::SourceRows::new([70, 901]).unwrap();
        let error = strict_source_normalized_strings(&values, Some(&rows), "source", "category")
            .unwrap_err();
        assert_eq!(
            error.to_string(),
            "data error: source: value \"category\" contains null at source row 901"
        );
        let values = CategoryValues::new("category", ["  ", "valid"]).unwrap();
        let error = strict_source_normalized_strings(&values, Some(&rows), "source", "category")
            .unwrap_err();
        assert_eq!(error.to_string(), "data error: source: category label is empty after whitespace normalization at source row 70");
        let numbers = NumericValues::new("value", [3.0, f64::INFINITY]);
        assert_eq!(
            strict_numeric_at(&numbers, 0, 901, "source")
                .unwrap()
                .to_bits(),
            3.0_f64.to_bits()
        );
        assert_eq!(
            strict_source_f64(&numbers, Some(&rows), "source")
                .unwrap_err()
                .to_string(),
            "data error: source: value \"value\" contains non-finite value inf at source row 901"
        );
    }
}