geolith-dataset-builder 0.2.2

Raster datasets for geolith: district areas, normals, numbers and a map layer per period, and the steps that stage, verify and publish them to any S3-compatible bucket
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
//! Per-district baseline normals (`geolith dataset normals`).
//!
//! For every chosen pentad slot, an area's normal is the mean over the
//! baseline years of its value ([`area_values`]). Rasters are read one at a
//! time in period order. The result is `normals.csv`, with
//! `normals-stats.json` beside it. An area with no value in any baseline year
//! of a slot fails a `normal` dataset; an `average` dataset gives it no row
//! and lists it in the stats' `empty`.
//!
//! A values cache (`--cache <dir>`, and `geolith dataset values` for one
//! raster) keeps each raster's area values in `<dir>/<raster file
//! stem>.values.csv`: a `# areas <count> <FNV-1a 64 hex of the sorted area
//! ids joined by \n>` line, then `area_id,value` rows sorted by area id (an
//! empty value is no value). A baseline can then be computed with its
//! rasters deleted, and a cache of other areas is refused.

use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::time::Instant;

use anyhow::{Context as _, bail};
use serde::{Deserialize, Serialize};

use crate::areas::{Area, read_areas_geojson};
use crate::cli::{NormalsArgs, ValuesArgs};
use crate::config::{Comparison, DatasetConfig, PeriodKind, Reader};
use crate::coverage::Grid;
use crate::numbers::{CoverageTable, area_values};
use crate::rasters::{Period, RasterFile, discover, match_template};
use crate::source::Raster;

/// Header line of `normals.csv`.
const HEADER: &str = "area_id,slot,normal,years,baseline,attribution";

/// Number of columns of `normals.csv`.
const COLUMNS: usize = 6;

/// The normal of one area for one slot.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Normal {
    /// `id` of the area.
    pub area_id: String,
    /// Period slot `MM-P`.
    pub slot: String,
    /// Mean over the counted years of the area value.
    pub normal: f64,
    /// Baseline years that gave the area a value.
    pub years: u32,
    /// Baseline `FIRST-LAST`.
    pub baseline: String,
}

/// Timing and inputs of one `dataset normals` run (`normals-stats.json`).
#[derive(Debug, Serialize)]
struct NormalsStats {
    files: usize,
    ms_total: f64,
    ms_per_file: f64,
    slots: Vec<String>,
    baseline: String,
    attribution: String,
    /// `<area_id> <slot>` pairs with no value in any baseline year, for an
    /// `average` dataset (absent for a `normal` one, which fails instead).
    #[serde(skip_serializing_if = "Option::is_none")]
    empty: Option<Vec<String>>,
}

/// Write `normals` as CSV: header `area_id,slot,normal,years,baseline,attribution`,
/// rows sorted by `(area_id, slot)`, `normal` at full `f64` precision and
/// `attribution` on every row.
///
/// # Errors
///
/// Fails, naming `path`, when the file cannot be written.
pub fn write_normals_csv(path: &Path, normals: &[Normal], attribution: &str) -> anyhow::Result<()> {
    let mut rows: Vec<&Normal> = normals.iter().collect();
    rows.sort_by(|a, b| (&a.area_id, &a.slot).cmp(&(&b.area_id, &b.slot)));
    let attribution = csv_field(attribution);
    let mut text = String::with_capacity((rows.len() + 1) * (64 + attribution.len()));
    text.push_str(HEADER);
    text.push('\n');
    for n in rows {
        text.push_str(&format!(
            "{},{},{},{},{},{attribution}\n",
            csv_field(&n.area_id),
            csv_field(&n.slot),
            n.normal,
            n.years,
            csv_field(&n.baseline),
        ));
    }
    std::fs::write(path, text).with_context(|| format!("writing {}", path.display()))
}

/// `field` as a CSV field: quoted, with inner quotes doubled, when it holds a
/// comma, a quote or a line break.
pub(crate) fn csv_field(field: &str) -> Cow<'_, str> {
    if field.contains([',', '"', '\n', '\r']) {
        Cow::Owned(format!("\"{}\"", field.replace('"', "\"\"")))
    } else {
        Cow::Borrowed(field)
    }
}

/// Read a normals CSV written by [`write_normals_csv`].
///
/// The `attribution` column is checked to be present on every row and then
/// dropped: the config carries it.
///
/// # Errors
///
/// Fails, naming `path`, when the file cannot be read, the header differs,
/// a row has the wrong number of fields, or `normal` / `years` do not parse.
pub fn read_normals_csv(path: &Path) -> anyhow::Result<Vec<Normal>> {
    let text =
        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let records = parse_csv(&text).with_context(|| format!("parsing {}", path.display()))?;
    let mut records = records.into_iter();
    let header = records.next().unwrap_or_default();
    if header.join(",") != HEADER {
        bail!(
            "{}: header is {:?}, expected {HEADER:?}",
            path.display(),
            header.join(",")
        );
    }
    let mut normals = Vec::with_capacity(records.len());
    for (index, record) in records.enumerate() {
        let row = index + 2;
        let [area_id, slot, normal, years, baseline, _attribution]: [String; COLUMNS] =
            record.try_into().map_err(|r: Vec<String>| {
                anyhow::anyhow!(
                    "{} row {row}: {} fields, expected {COLUMNS}",
                    path.display(),
                    r.len()
                )
            })?;
        normals.push(Normal {
            normal: normal
                .parse()
                .with_context(|| format!("{} row {row}: normal {normal:?}", path.display()))?,
            years: years
                .parse()
                .with_context(|| format!("{} row {row}: years {years:?}", path.display()))?,
            area_id,
            slot,
            baseline,
        });
    }
    Ok(normals)
}

/// The records of CSV `text`: fields split on commas, double-quoted fields
/// may hold commas, line breaks and doubled quotes. A final line break is
/// optional.
pub(crate) fn parse_csv(text: &str) -> anyhow::Result<Vec<Vec<String>>> {
    let mut records = Vec::new();
    let mut record = Vec::new();
    let mut field = String::new();
    let mut in_quotes = false;
    let mut chars = text.chars().peekable();
    while let Some(c) = chars.next() {
        if in_quotes {
            match c {
                '"' if chars.peek() == Some(&'"') => {
                    chars.next();
                    field.push('"');
                }
                '"' => in_quotes = false,
                _ => field.push(c),
            }
            continue;
        }
        match c {
            '"' if field.is_empty() => in_quotes = true,
            ',' => record.push(std::mem::take(&mut field)),
            '\r' if chars.peek() == Some(&'\n') => {}
            '\n' => {
                record.push(std::mem::take(&mut field));
                records.push(std::mem::take(&mut record));
            }
            _ => field.push(c),
        }
    }
    if in_quotes {
        bail!("unterminated quoted field");
    }
    if !field.is_empty() || !record.is_empty() {
        record.push(field);
        records.push(record);
    }
    Ok(records)
}

/// `(first, last)` of a baseline `YYYY-YYYY` with `first <= last`.
fn parse_baseline(text: &str) -> anyhow::Result<(i32, i32)> {
    let year = |s: &str| {
        (s.len() == 4 && s.bytes().all(|b| b.is_ascii_digit()))
            .then(|| s.parse::<i32>().ok())
            .flatten()
    };
    let parsed = text
        .split_once('-')
        .and_then(|(a, b)| Some((year(a)?, year(b)?)));
    match parsed {
        Some((first, last)) if first <= last => Ok((first, last)),
        _ => bail!("--baseline {text:?} is not YYYY-YYYY with the first year first"),
    }
}

/// The distinct slots of a comma-separated `MM-I` list, sorted; `I` is a
/// pentad (1-6) or a dekad (1-3) by `kind`.
fn parse_slots(text: &str, kind: PeriodKind) -> anyhow::Result<BTreeSet<String>> {
    let mut slots = BTreeSet::new();
    let last = b'0'.saturating_add(kind.periods_per_month());
    for slot in text.split(',').map(str::trim) {
        let b = slot.as_bytes();
        let valid = b.len() == 4
            && b[2] == b'-'
            && matches!(slot[..2].parse::<u8>(), Ok(1..=12))
            && b[..2].iter().all(u8::is_ascii_digit)
            && (b'1'..=last).contains(&b[3]);
        if !valid {
            match kind {
                PeriodKind::Pentad => {
                    bail!("--slots: {slot:?} is not a slot MM-P (month 01-12, pentad 1-6)")
                }
                PeriodKind::Dekad => {
                    bail!("--slots: {slot:?} is not a slot MM-D (month 01-12, dekad 1-3)")
                }
            }
        }
        slots.insert(slot.to_owned());
    }
    Ok(slots)
}

/// Name suffix of a values cache file: `<raster file stem>.values.csv`.
const CACHE_SUFFIX: &str = ".values.csv";

/// Column header of a values cache file, after its `# areas` line.
const CACHE_HEADER: &str = "area_id,value";

/// FNV-1a 64 offset basis.
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;

/// FNV-1a 64 state `hash` continued over `bytes`.
fn fnv1a_extend(mut hash: u64, bytes: &[u8]) -> u64 {
    for &b in bytes {
        hash ^= u64::from(b);
        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
    }
    hash
}

/// FNV-1a 64 of `bytes`.
#[must_use]
pub(crate) fn fnv1a_64(bytes: &[u8]) -> u64 {
    fnv1a_extend(FNV_OFFSET, bytes)
}

/// FNV-1a 64 of the area shapes in id order: per area its id, a 0 byte, the
/// polygon count, and per polygon the ring count and per ring (exterior,
/// then holes) the point count and each point's `x`, `y` as `f64` bits
/// (counts as `u64`, all little-endian).
fn geometry_hash(areas: &[Area]) -> u64 {
    let mut order: Vec<&Area> = areas.iter().collect();
    order.sort_by(|a, b| a.id.cmp(&b.id));
    let count = |n: usize| (n as u64).to_le_bytes();
    let mut hash = FNV_OFFSET;
    for area in order {
        hash = fnv1a_extend(hash, area.id.as_bytes());
        hash = fnv1a_extend(hash, &[0]);
        hash = fnv1a_extend(hash, &count(area.shape.0.len()));
        for polygon in &area.shape.0 {
            hash = fnv1a_extend(hash, &count(1 + polygon.interiors().len()));
            for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
                hash = fnv1a_extend(hash, &count(ring.0.len()));
                for c in &ring.0 {
                    hash = fnv1a_extend(hash, &c.x.to_bits().to_le_bytes());
                    hash = fnv1a_extend(hash, &c.y.to_bits().to_le_bytes());
                }
            }
        }
    }
    hash
}

/// What the values of a cache file depend on, written as its first line
/// `# areas <count> <ids> release=<boundary release> config=<config> grid=<grid>
/// geometry=<geometry>` (one line; hashes FNV-1a 64, 16 lower-case hex digits).
#[derive(Debug, Clone, PartialEq, Eq)]
struct CacheKey {
    /// Area count.
    count: usize,
    /// Hash of the sorted area ids joined by `\n`.
    ids: u64,
    /// Boundary release of the areas.
    release: String,
    /// Hash of the config fields that change values ([`config_hash`]).
    config: u64,
    /// Hash of the raster grid ([`grid_hash`]).
    grid: u64,
    /// Hash of the area shapes ([`geometry_hash`]).
    geometry: u64,
}

impl CacheKey {
    /// The key of `areas` (of `release`) under `config` on the grid of hash
    /// `grid`.
    fn new(areas: &[Area], release: &str, config: &DatasetConfig, grid: u64) -> Self {
        let mut ids: Vec<&str> = areas.iter().map(|a| a.id.as_str()).collect();
        ids.sort_unstable();
        CacheKey {
            count: ids.len(),
            ids: fnv1a_64(ids.join("\n").as_bytes()),
            release: release.to_owned(),
            config: config_hash(config),
            grid,
            geometry: geometry_hash(areas),
        }
    }

    /// This key on the grid of hash `grid`.
    fn with_grid(&self, grid: u64) -> Self {
        CacheKey {
            grid,
            ..self.clone()
        }
    }

    /// The header line.
    fn line(&self) -> String {
        format!(
            "# areas {} {:016x} release={} config={:016x} grid={:016x} geometry={:016x}",
            self.count, self.ids, self.release, self.config, self.grid, self.geometry
        )
    }

    /// Parse a header line written by [`CacheKey::line`].
    fn parse(line: &str) -> Option<Self> {
        let rest = line.strip_prefix("# areas ")?;
        let (count, rest) = rest.split_once(' ')?;
        let (ids, rest) = rest.split_once(' ')?;
        let (rest, geometry) = rest.rsplit_once(" geometry=")?;
        let (rest, grid) = rest.rsplit_once(" grid=")?;
        let (release, config) = rest.rsplit_once(" config=")?;
        let hex = |s: &str| (s.len() == 16).then(|| u64::from_str_radix(s, 16).ok())?;
        Some(CacheKey {
            count: count.parse().ok()?,
            ids: hex(ids)?,
            release: release.strip_prefix("release=")?.to_owned(),
            config: hex(config)?,
            grid: hex(grid)?,
            geometry: hex(geometry)?,
        })
    }
}

/// FNV-1a 64 of the config fields that change area values: `id`, `scale`,
/// `offset`, `valid_min`, `valid_max`, `nodata`, `flags` and `reader`
/// (numbers as their `f64` bits).
fn config_hash(config: &DatasetConfig) -> u64 {
    let mut bytes = Vec::with_capacity(config.id.len() + 64 + config.flags.len() * 8);
    bytes.extend(config.id.as_bytes());
    bytes.push(0);
    for v in [
        config.scale,
        config.offset,
        config.valid_min,
        config.valid_max,
    ] {
        bytes.extend(v.to_bits().to_le_bytes());
    }
    match config.nodata {
        Some(v) => {
            bytes.push(1);
            bytes.extend(v.to_bits().to_le_bytes());
        }
        None => bytes.push(0),
    }
    bytes.extend((config.flags.len() as u64).to_le_bytes());
    for v in &config.flags {
        bytes.extend(v.to_bits().to_le_bytes());
    }
    bytes.push(match config.reader {
        Reader::Whole => 0,
        Reader::Windowed => 1,
    });
    fnv1a_64(&bytes)
}

/// FNV-1a 64 of a grid: width, height, origin and pixel size (`f64` bits).
fn grid_hash(grid: &Grid) -> u64 {
    let t = &grid.transform;
    let mut bytes = Vec::with_capacity(40);
    bytes.extend(grid.width.to_le_bytes());
    bytes.extend(grid.height.to_le_bytes());
    for v in [t.origin_x, t.origin_y, t.pixel_width, t.pixel_height] {
        bytes.extend(v.to_bits().to_le_bytes());
    }
    fnv1a_64(&bytes)
}

/// Check that every cache file read (`(path, grid hash)`) is on `grid`, the
/// grid of the rasters read; without a raster, on the grid of the first.
///
/// # Errors
///
/// Fails naming the first cache file on another grid.
fn check_cache_grids(read: &[(&Path, u64)], grid: Option<u64>) -> anyhow::Result<()> {
    let (expected, of) = match (grid, read.first()) {
        (Some(g), _) => (g, "the rasters give"),
        (None, Some((_, g))) => (*g, "the other cache files give"),
        (None, None) => return Ok(()),
    };
    if let Some((path, found)) = read.iter().find(|(_, g)| *g != expected) {
        bail!(
            "{}: values cache of another grid ({found:016x}, {of} {expected:016x}); delete it \
             to recompute",
            path.display()
        );
    }
    Ok(())
}

/// The cache file of `raster` in `dir`.
fn cache_path(dir: &Path, raster: &Path) -> anyhow::Result<PathBuf> {
    let stem = raster
        .file_stem()
        .and_then(|s| s.to_str())
        .with_context(|| format!("{} has no file name", raster.display()))?;
    Ok(dir.join(format!("{stem}{CACHE_SUFFIX}")))
}

/// Write the values cache `path` with header `key` for `areas` and their
/// `values` (in area order): `.partial` first, then renamed, so a killed run
/// leaves no file.
fn write_cache(
    path: &Path,
    key: &CacheKey,
    areas: &[Area],
    values: &[Option<f64>],
) -> anyhow::Result<()> {
    let mut rows: Vec<(&str, Option<f64>)> = areas
        .iter()
        .map(|a| a.id.as_str())
        .zip(values.iter().copied())
        .collect();
    rows.sort_by(|a, b| a.0.cmp(b.0));
    let header = key.line();
    let mut text = String::with_capacity(header.len() + 16 + rows.len() * 48);
    text.push_str(&header);
    text.push('\n');
    text.push_str(CACHE_HEADER);
    text.push('\n');
    for (id, value) in rows {
        let value = value.map(|v| v.to_string()).unwrap_or_default();
        text.push_str(&format!("{},{value}\n", csv_field(id)));
    }
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating {}", parent.display()))?;
    }
    let mut partial = path.as_os_str().to_owned();
    partial.push(".partial");
    let partial = PathBuf::from(partial);
    std::fs::write(&partial, text).with_context(|| format!("writing {}", partial.display()))?;
    std::fs::rename(&partial, path)
        .with_context(|| format!("renaming {} to {}", partial.display(), path.display()))
}

/// Why a cache header `found` does not fit `expected`, naming the first
/// differing part; the grid is compared only when `check_grid`.
fn key_mismatch(found: &CacheKey, expected: &CacheKey, check_grid: bool) -> Option<String> {
    if (found.count, found.ids) != (expected.count, expected.ids) {
        return Some(format!(
            "values cache of other areas ({} areas {:016x}, the areas give {} {:016x})",
            found.count, found.ids, expected.count, expected.ids
        ));
    }
    if found.geometry != expected.geometry {
        return Some(format!(
            "values cache of other area shapes (geometry {:016x}, the areas give {:016x})",
            found.geometry, expected.geometry
        ));
    }
    if found.release != expected.release {
        return Some(format!(
            "values cache of another boundary release ({:?}, the areas are {:?})",
            found.release, expected.release
        ));
    }
    if found.config != expected.config {
        return Some(format!(
            "values cache of another config ({:016x}, the config gives {:016x})",
            found.config, expected.config
        ));
    }
    if check_grid && found.grid != expected.grid {
        return Some(format!(
            "values cache of another grid ({:016x}, the rasters give {:016x})",
            found.grid, expected.grid
        ));
    }
    None
}

/// The values of `areas` (in area order) from the cache file `path`, and
/// its header. Its areas, release and config must be those of `expected`,
/// its grid too when `check_grid`.
///
/// # Errors
///
/// Fails, naming `path` and the differing part, when it cannot be read, its
/// header is not one of [`CacheKey::line`] or differs from `expected`, or
/// its rows are not exactly one per area with a number or nothing.
fn read_cache(
    path: &Path,
    expected: &CacheKey,
    check_grid: bool,
    areas: &[Area],
) -> anyhow::Result<(Vec<Option<f64>>, CacheKey)> {
    let text =
        std::fs::read_to_string(path).with_context(|| format!("reading {}", path.display()))?;
    let (first, rest) = text.split_once('\n').unwrap_or((text.as_str(), ""));
    let Some(found) = CacheKey::parse(first) else {
        if first.starts_with("# areas ") && !first.contains(" geometry=") {
            bail!(
                "{}: values cache without an area geometry hash (made before it was added); \
                 delete it to recompute",
                path.display()
            );
        }
        bail!(
            "{}: first line {first:?} is not a values cache header; delete it to recompute",
            path.display()
        );
    };
    if let Some(why) = key_mismatch(&found, expected, check_grid) {
        bail!("{}: {why}; delete it to recompute", path.display());
    }
    let records = parse_csv(rest).with_context(|| format!("parsing {}", path.display()))?;
    let mut records = records.into_iter();
    if records.next().unwrap_or_default().join(",") != CACHE_HEADER {
        bail!("{}: second line is not {CACHE_HEADER:?}", path.display());
    }
    let mut by_id: HashMap<String, Option<f64>> = HashMap::with_capacity(areas.len());
    for (index, record) in records.enumerate() {
        let row = index + 3;
        let [id, value]: [String; 2] = record.try_into().map_err(|r: Vec<String>| {
            anyhow::anyhow!(
                "{} row {row}: {} fields, expected 2",
                path.display(),
                r.len()
            )
        })?;
        let value = if value.is_empty() {
            None
        } else {
            Some(
                value
                    .parse::<f64>()
                    .with_context(|| format!("{} row {row}: value {value:?}", path.display()))?,
            )
        };
        if by_id.insert(id.clone(), value).is_some() {
            bail!("{} row {row}: area {id:?} appears twice", path.display());
        }
    }
    if by_id.len() != areas.len() {
        bail!(
            "{}: {} rows for {} areas",
            path.display(),
            by_id.len(),
            areas.len()
        );
    }
    let values = areas
        .iter()
        .map(|a| {
            by_id
                .get(&a.id)
                .copied()
                .with_context(|| format!("{}: no row for area {:?}", path.display(), a.id))
        })
        .collect::<anyhow::Result<_>>()?;
    Ok((values, found))
}

/// The area values (in area order) of the raster at `path`, on the grid of
/// `table`, which the first raster read builds.
fn raster_values(
    path: &Path,
    areas: &[Area],
    config: &DatasetConfig,
    table: &mut Option<CoverageTable>,
) -> anyhow::Result<Vec<Option<f64>>> {
    let source = Raster::open(path, config)?;
    let current = match table.take() {
        Some(t) => t,
        None => {
            let grid = source.grid().with_context(|| path.display().to_string())?;
            CoverageTable::build(areas, grid)
        }
    };
    let values = area_values(&current, &source, config, path);
    *table = Some(current);
    Ok(values?.into_iter().map(|v| v.value).collect())
}

/// The values cache files in `dir` by period: names `<stem>.values.csv`
/// whose stem matches the stem of the config's final or prelim template. A
/// missing `dir` holds none.
///
/// # Errors
///
/// Fails when `dir` exists but cannot be listed, or two files name one
/// period (naming both).
fn discover_cache(dir: &Path, config: &DatasetConfig) -> anyhow::Result<BTreeMap<Period, PathBuf>> {
    let entries = match std::fs::read_dir(dir) {
        Ok(entries) => entries,
        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(BTreeMap::new()),
        Err(e) => return Err(e).with_context(|| format!("listing {}", dir.display())),
    };
    let mut paths = entries
        .map(|entry| entry.map(|e| e.path()))
        .collect::<Result<Vec<_>, _>>()
        .with_context(|| format!("listing {}", dir.display()))?;
    paths.sort();
    let stems: BTreeSet<&str> = [config.file_template.as_str(), config.prelim_template()]
        .into_iter()
        .filter_map(|t| Path::new(t).file_stem().and_then(|s| s.to_str()))
        .collect();
    let mut found: BTreeMap<Period, PathBuf> = BTreeMap::new();
    for path in paths {
        let period = path
            .file_name()
            .and_then(|n| n.to_str())
            .and_then(|n| n.strip_suffix(CACHE_SUFFIX))
            .and_then(|stem| stems.iter().find_map(|t| match_template(t, stem)));
        let Some(period) = period else { continue };
        if let Some(first) = found.insert(period, path.clone()) {
            bail!(
                "{} and {} both hold period {}",
                first.display(),
                path.display(),
                period.start_iso()
            );
        }
    }
    Ok(found)
}

/// The period of `slot` (`MM-I`, already validated) in `year`.
fn slot_period(year: i32, slot: &str, kind: PeriodKind) -> Option<Period> {
    let (month, index) = slot.split_once('-')?;
    Some(Period {
        year,
        month: month.parse().ok()?,
        index: index.parse().ok()?,
        kind,
    })
}

/// Where one baseline period's values come from.
struct BaselineSource<'a> {
    raster: Option<&'a RasterFile>,
    cache: Option<PathBuf>,
}

/// Run `geolith dataset normals`.
///
/// With `--cache`, each period's area values come from its cache file when
/// present, else from its raster, written to the cache before use. A period
/// counts as present when its raster or its cache file exists; periods
/// starting before the config's `record_start` are not required. The
/// attribution's `{year}` is the baseline range.
///
/// # Errors
///
/// Fails when `--baseline` or `--slots` is malformed, no raster (nor cache
/// file) matches the config template, a baseline year is missing for a
/// requested slot (every missing `YYYY MM-P` is listed), a raster cannot be
/// read or is on another grid, a cache file holds other areas (naming it),
/// an area of a `normal` dataset gets no value in any baseline year of a
/// slot, or an output cannot be written. For an `average` dataset such an
/// area and slot gets no normals row and is listed in `normals-stats.json`
/// `empty` (`<area_id> <slot>`); the build then writes a null normal.
pub fn run(args: &NormalsArgs) -> anyhow::Result<()> {
    let config = DatasetConfig::load(&args.config)?;
    let (first, last) = parse_baseline(&args.baseline)?;
    let baseline = format!("{first}-{last}");
    let attribution = config.attribution_for((first, last));
    let slots = parse_slots(&args.slots, config.period)?;

    let found = discover(
        &args.rasters,
        &config.file_template,
        config.prelim_template(),
    )?;
    let cached = match &args.cache {
        Some(dir) => discover_cache(dir, &config)?,
        None => BTreeMap::new(),
    };
    if found.is_empty() && cached.is_empty() {
        bail!(
            "no raster in {} matches the template {} (final/) or {} (prelim/)",
            args.rasters.display(),
            config.file_template,
            config.prelim_template()
        );
    }
    let wanted = |p: &Period| (first..=last).contains(&p.year) && slots.contains(&p.slot());
    let mut selected: BTreeMap<Period, BaselineSource<'_>> = BTreeMap::new();
    for raster in found.iter().filter(|r| wanted(&r.period)) {
        let cache = match &args.cache {
            Some(dir) => Some(cache_path(dir, &raster.path)?),
            None => None,
        };
        selected.insert(
            raster.period,
            BaselineSource {
                raster: Some(raster),
                cache,
            },
        );
    }
    for (period, path) in cached.into_iter().filter(|(p, _)| wanted(p)) {
        selected
            .entry(period)
            .and_modify(|s| s.cache = Some(path.clone()))
            .or_insert(BaselineSource {
                raster: None,
                cache: Some(path),
            });
    }
    let before_record = |year: i32, slot: &str| {
        let start = slot_period(year, slot, config.period).map(|p| p.start_iso());
        matches!((start, config.record_start.as_deref()), (Some(s), Some(r)) if s.as_str() < r)
    };
    let present: BTreeSet<(i32, String)> = selected.keys().map(|p| (p.year, p.slot())).collect();
    let missing: Vec<String> = (first..=last)
        .flat_map(|year| slots.iter().map(move |slot| (year, slot)))
        .filter(|(year, slot)| !present.contains(&(*year, (*slot).clone())))
        .filter(|(year, slot)| !before_record(*year, slot))
        .map(|(year, slot)| format!("{year} {slot}"))
        .collect();
    if !missing.is_empty() {
        bail!(
            "baseline {baseline} is missing rasters in {}: {}",
            args.rasters.display(),
            missing.join(", ")
        );
    }

    let areas_file = read_areas_geojson(&args.areas)?;
    let areas = &areas_file.areas;
    let base = CacheKey::new(areas, &areas_file.boundary_release, &config, 0);
    let key_on = |grid: u64| base.with_grid(grid);
    let started = Instant::now();
    let mut table: Option<CoverageTable> = None;
    let mut sums: BTreeMap<String, Vec<(f64, u32)>> = BTreeMap::new();
    // The grid of every cache file read, checked once the grid is known.
    let mut cache_grids: Vec<(&Path, u64)> = Vec::new();
    for (period, source) in &selected {
        let values = match (&source.cache, source.raster) {
            (Some(cache), _) if cache.is_file() => {
                let (values, found) = read_cache(cache, &key_on(0), false, areas)?;
                cache_grids.push((cache.as_path(), found.grid));
                values
            }
            (cache, Some(raster)) => {
                let values = raster_values(&raster.path, areas, &config, &mut table)?;
                if let (Some(cache), Some(t)) = (cache, &table) {
                    write_cache(cache, &key_on(grid_hash(&t.grid)), areas, &values)?;
                }
                values
            }
            (_, None) => bail!(
                "period {} has neither a raster nor a cache file",
                period.start_iso()
            ),
        };
        let acc = sums
            .entry(period.slot())
            .or_insert_with(|| vec![(0.0, 0); areas.len()]);
        for (slot_sum, value) in acc.iter_mut().zip(&values) {
            if let Some(v) = value {
                slot_sum.0 += v;
                slot_sum.1 += 1;
            }
        }
    }
    let ms_total = started.elapsed().as_secs_f64() * 1000.0;
    let from_cache = cache_grids.len();
    check_cache_grids(&cache_grids, table.as_ref().map(|t| grid_hash(&t.grid)))?;

    let mut normals = Vec::with_capacity(areas.len() * sums.len());
    let mut empty = Vec::new();
    for (slot, acc) in &sums {
        for (area, &(sum, years)) in areas.iter().zip(acc) {
            if years == 0 {
                empty.push(format!("{} {slot}", area.id));
                continue;
            }
            normals.push(Normal {
                area_id: area.id.clone(),
                slot: slot.clone(),
                normal: sum / f64::from(years),
                years,
                baseline: baseline.clone(),
            });
        }
    }
    // An area the baseline never reaches is data, not a defect, when the
    // country declares a coverage floor (`--allow-empty`): the floor is what
    // excludes it from the build. An average comparison has always read it
    // that way (a dekad with no clear sky is normal); a total does not.
    let tolerated = matches!(config.comparison, Comparison::Average) || args.allow_empty;
    let empty = if tolerated {
        if !empty.is_empty() {
            tracing::warn!(
                count = empty.len(),
                first = empty.first().map_or("", String::as_str),
                "no baseline year gives a value: no normal for these areas and slots"
            );
        }
        Some(empty)
    } else if empty.is_empty() {
        None
    } else {
        bail!(
            "no baseline year gives a value for area and slot: {}",
            empty.join(", ")
        )
    };

    if let Some(parent) = args.out.parent().filter(|p| !p.as_os_str().is_empty()) {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating {}", parent.display()))?;
    }
    write_normals_csv(&args.out, &normals, &attribution)?;
    let files = selected.len();
    let stats = NormalsStats {
        files,
        ms_total,
        ms_per_file: if files == 0 {
            0.0
        } else {
            ms_total / files as f64
        },
        slots: slots.into_iter().collect(),
        baseline,
        attribution,
        empty,
    };
    let stats_path = args.out.with_file_name("normals-stats.json");
    let json = serde_json::to_string_pretty(&stats).context("encoding normals stats")?;
    std::fs::write(&stats_path, json)
        .with_context(|| format!("writing {}", stats_path.display()))?;
    tracing::info!(
        files = stats.files,
        from_cache,
        normals = normals.len(),
        out = %args.out.display(),
        "dataset normals written"
    );
    Ok(())
}

/// Run `geolith dataset values`: compute the area values of one raster and
/// write its cache file `<cache>/<raster file stem>.values.csv`, the per-file
/// step of a streamed baseline.
///
/// A cache file of the same areas is kept as it is. Prints the cache file.
///
/// # Errors
///
/// Fails when the raster's name matches neither config template, the cache
/// file exists for other areas (naming it), or the raster or areas cannot be
/// read or the cache file written.
pub fn run_values(args: &ValuesArgs) -> anyhow::Result<()> {
    let config = DatasetConfig::load(&args.config)?;
    let name = args
        .raster
        .file_name()
        .and_then(|n| n.to_str())
        .unwrap_or_default();
    if match_template(&config.file_template, name).is_none()
        && match_template(config.prelim_template(), name).is_none()
    {
        bail!(
            "{}: the name matches neither {} nor {}",
            args.raster.display(),
            config.file_template,
            config.prelim_template()
        );
    }
    let areas_file = read_areas_geojson(&args.areas)?;
    let areas = &areas_file.areas;
    let base = CacheKey::new(areas, &areas_file.boundary_release, &config, 0);
    let key_on = |grid: &Grid| base.with_grid(grid_hash(grid));
    let path = cache_path(&args.cache, &args.raster)?;
    if path.is_file() {
        let grid = Raster::open(&args.raster, &config)?
            .grid()
            .with_context(|| args.raster.display().to_string())?;
        read_cache(&path, &key_on(&grid), true, areas)?;
        tracing::info!(cache = %path.display(), "dataset values cached already");
    } else {
        let mut table = None;
        let values = raster_values(&args.raster, areas, &config, &mut table)?;
        let grid = table.map(|t| t.grid).context("the raster gave no grid")?;
        write_cache(&path, &key_on(&grid), areas, &values)?;
        tracing::info!(cache = %path.display(), "dataset values written");
    }
    println!("{}", path.display());
    Ok(())
}

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

    const CHIRPS: &str = "Rainfall: CHIRPS v3.0, Climate Hazards Center, UC Santa Barbara. \
                          CC BY 4.0. DOI 10.15780/G2JQ0P";

    fn normal(area_id: &str, slot: &str, normal: f64, years: u32) -> Normal {
        Normal {
            area_id: area_id.to_owned(),
            slot: slot.to_owned(),
            normal,
            years,
            baseline: "1991-2020".to_owned(),
        }
    }

    fn sample() -> Vec<Normal> {
        vec![
            normal("div-b", "07-2", 0.1 + 0.2, 30),
            normal("div-a", "07-2", 12.345_678_901_234_567, 29),
            normal("div-a", "06-1", 0.0, 30),
            normal("div \"q\", x", "06-1", 1e-12, 1),
        ]
    }

    #[test]
    fn the_csv_round_trips() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("normals.csv");
        write_normals_csv(&path, &sample(), CHIRPS).unwrap();
        let read = read_normals_csv(&path).unwrap();
        let key = |n: &Normal| (n.area_id.clone(), n.slot.clone(), n.years);
        let written: BTreeSet<_> = sample().iter().map(key).collect();
        let back: BTreeSet<_> = read.iter().map(key).collect();
        assert_eq!(back, written);
        let a = read
            .iter()
            .find(|n| n.area_id == "div-a" && n.slot == "07-2")
            .unwrap();
        assert_eq!(a.normal.to_bits(), 12.345_678_901_234_567_f64.to_bits());
        let b = read.iter().find(|n| n.area_id == "div-b").unwrap();
        assert_eq!(b.normal.to_bits(), (0.1_f64 + 0.2).to_bits());
        assert_eq!(b.baseline, "1991-2020");
    }

    #[test]
    fn the_csv_header_is_fixed() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("normals.csv");
        write_normals_csv(&path, &sample(), CHIRPS).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        let mut lines = text.lines();
        assert_eq!(
            lines.next(),
            Some("area_id,slot,normal,years,baseline,attribution")
        );
        let row = text
            .lines()
            .find(|l| l.starts_with("div-b,"))
            .expect("a row for div-b");
        assert!(row.ends_with(&format!(",\"{CHIRPS}\"")), "{row}");
    }

    #[test]
    fn rows_are_sorted_by_area_then_slot() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("normals.csv");
        write_normals_csv(&path, &sample(), CHIRPS).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        let keys: Vec<(String, String)> = text
            .lines()
            .skip(1)
            .filter(|l| l.starts_with("div-"))
            .map(|l| {
                let mut f = l.split(',');
                (f.next().unwrap().to_owned(), f.next().unwrap().to_owned())
            })
            .collect();
        assert_eq!(keys.len(), 3);
        assert!(keys.windows(2).all(|w| w[0] < w[1]), "{keys:?}");
    }

    #[test]
    fn a_bad_baseline_is_an_error() {
        for text in [
            "1991",
            "1991-20",
            "2020-1991",
            "abcd-efgh",
            "1991-2020-2030",
        ] {
            assert!(parse_baseline(text).is_err(), "{text}");
        }
        assert_eq!(parse_baseline("1991-2020").unwrap(), (1991, 2020));
    }

    #[test]
    fn dekad_slots_parse() {
        let slots = parse_slots("01-1,12-3", PeriodKind::Dekad).expect("dekad slots");
        assert_eq!(
            slots,
            BTreeSet::from(["01-1".to_owned(), "12-3".to_owned()])
        );
        let err = parse_slots("01-4", PeriodKind::Dekad).expect_err("no dekad 4");
        assert!(format!("{err:#}").contains("dekad 1-3"), "{err:#}");
        // Pentad configs keep their P1 behaviour and error text.
        let pentads = parse_slots("01-4, 12-6", PeriodKind::Pentad).expect("pentad slots");
        assert!(
            pentads.contains("01-4") && pentads.contains("12-6"),
            "{pentads:?}"
        );
        let err = parse_slots("01-7", PeriodKind::Pentad).expect_err("no pentad 7");
        assert_eq!(
            format!("{err:#}"),
            "--slots: \"01-7\" is not a slot MM-P (month 01-12, pentad 1-6)"
        );
    }

    #[test]
    fn fnv1a_matches_the_reference_vectors() {
        // Test vectors of the FNV reference suite (isthe.com/chongo/tech/comp/fnv).
        assert_eq!(fnv1a_64(b""), 0xcbf2_9ce4_8422_2325);
        assert_eq!(fnv1a_64(b"a"), 0xaf63_dc4c_8601_ec8c);
        assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8);
    }

    fn area(id: &str) -> Area {
        Area {
            code: None,
            id: id.to_owned(),
            name: id.to_owned(),
            country: "ZZ".to_owned(),
            level: "county".to_owned(),
            parent_id: None,
            parent_name: None,
            region_code: None,
            shape: geo::MultiPolygon::new(vec![]),
        }
    }

    #[test]
    fn the_cache_header_hashes_the_sorted_ids() {
        // "a\nfoobar" is not a reference vector; the sort is checked by the
        // two orders giving one header, the hash by the one-id case.
        let config = rainfall();
        let key = |list: &[Area]| CacheKey::new(list, "r1", &config, 0xabc).line();
        let one = key(&[area("a")]);
        assert!(
            one.starts_with("# areas 1 af63dc4c8601ec8c release=r1 config="),
            "{one}"
        );
        assert!(one.contains(" grid=0000000000000abc geometry="), "{one}");
        assert_eq!(
            key(&[area("foobar"), area("a")]),
            key(&[area("a"), area("foobar")])
        );
        assert_ne!(key(&[area("a"), area("b")]), key(&[area("a"), area("c")]));
        // A release with spaces still parses back.
        let spaced = CacheKey::new(&[area("a")], "r 2 config=x", &config, 7);
        assert_eq!(CacheKey::parse(&spaced.line()), Some(spaced));
    }

    fn square_area(id: &str, x0: f64, y0: f64, size: f64) -> Area {
        let ring = vec![
            (x0, y0),
            (x0 + size, y0),
            (x0 + size, y0 + size),
            (x0, y0 + size),
            (x0, y0),
        ];
        Area {
            shape: geo::MultiPolygon::new(vec![geo::Polygon::new(ring.into(), vec![])]),
            ..area(id)
        }
    }

    #[test]
    fn the_geometry_hash_follows_the_shapes_not_the_order() {
        let a = square_area("a", 0.0, 0.0, 1.0);
        let b = square_area("b", 2.0, 0.0, 1.0);
        let base = geometry_hash(&[a.clone(), b.clone()]);
        assert_eq!(geometry_hash(&[b.clone(), a.clone()]), base, "area order");
        let moved = square_area("b", 2.0, 0.0, 1.000_000_1);
        assert_ne!(geometry_hash(&[a.clone(), moved]), base, "a moved vertex");
        // The same shapes under swapped ids are other areas.
        let swapped = [
            square_area("a", 2.0, 0.0, 1.0),
            square_area("b", 0.0, 0.0, 1.0),
        ];
        assert_ne!(geometry_hash(&swapped), base, "shapes swapped between ids");
        // A hole is part of the shape.
        let mut holed = a.clone();
        holed.shape.0[0].interiors_push(vec![(0.2, 0.2), (0.4, 0.2), (0.4, 0.4), (0.2, 0.2)]);
        assert_ne!(geometry_hash(&[holed, b.clone()]), base, "a hole");
        // One polygon split in two is another shape with the same vertices.
        let mut split = a.clone();
        let first = split.shape.0[0].clone();
        split.shape.0 = vec![
            geo::Polygon::new(
                geo::LineString::from(first.exterior().0[..3].to_vec()),
                vec![],
            ),
            geo::Polygon::new(
                geo::LineString::from(first.exterior().0[3..].to_vec()),
                vec![],
            ),
        ];
        assert_ne!(geometry_hash(&[split, b]), base, "ring boundaries count");
    }

    #[test]
    fn the_config_hash_follows_the_value_fields_only() {
        let config = rainfall();
        let base = config_hash(&config);
        let mut other = config.clone();
        other.name = "another name".to_owned();
        other.max_zoom = 3;
        assert_eq!(config_hash(&other), base, "display fields do not count");
        let changed: [fn(&mut DatasetConfig); 8] = [
            |c| c.id.push('x'),
            |c| c.scale = 2.0,
            |c| c.offset = 0.5,
            |c| c.valid_min = -1.0,
            |c| c.valid_max = 10.0,
            |c| c.nodata = None,
            |c| c.flags.push(1.0),
            |c| c.reader = Reader::Windowed,
        ];
        for (i, change) in changed.iter().enumerate() {
            let mut c = config.clone();
            change(&mut c);
            assert_ne!(config_hash(&c), base, "field change {i}");
        }
    }

    #[test]
    fn a_cache_on_another_grid_is_refused() {
        let a = Path::new("/c/a.values.csv");
        let b = Path::new("/c/b.values.csv");
        check_cache_grids(&[(a, 1), (b, 1)], Some(1)).unwrap();
        check_cache_grids(&[(a, 1), (b, 1)], None).unwrap();
        let err = check_cache_grids(&[(a, 1), (b, 2)], Some(1)).expect_err("b on grid 2");
        assert_eq!(
            format!("{err:#}"),
            "/c/b.values.csv: values cache of another grid (0000000000000002, the rasters \
             give 0000000000000001); delete it to recompute"
        );
        let err = check_cache_grids(&[(a, 3), (b, 2)], None).expect_err("b differs from a");
        assert_eq!(
            format!("{err:#}"),
            "/c/b.values.csv: values cache of another grid (0000000000000002, the other cache \
             files give 0000000000000003); delete it to recompute"
        );
        let grid = |x: f64| Grid {
            width: 4,
            height: 4,
            transform: geolith::terrain::dem::GeoTransform {
                origin_x: x,
                origin_y: 1.0,
                pixel_width: 0.5,
                pixel_height: 0.5,
            },
        };
        assert_ne!(grid_hash(&grid(0.0)), grid_hash(&grid(1e-12)));
    }

    fn rainfall() -> DatasetConfig {
        DatasetConfig::load(
            &Path::new(env!("CARGO_MANIFEST_DIR")).join("data/datasets/rainfall.json"),
        )
        .unwrap()
    }

    #[test]
    fn a_cache_round_trips_and_rejects_a_short_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("sub").join("r.values.csv");
        let areas = [area("z"), area("a, b"), area("m")];
        let values = [Some(0.1 + 0.2), None, Some(-0.0015)];
        let key = CacheKey::new(&areas, "r1", &rainfall(), 9);
        write_cache(&path, &key, &areas, &values).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        let rows: Vec<&str> = text.lines().skip(2).collect();
        assert_eq!(rows, ["\"a, b\",", "m,-0.0015", "z,0.30000000000000004"]);
        let (back, found) = read_cache(&path, &key, true, &areas).unwrap();
        assert_eq!(back, values);
        assert_eq!(found, key);
        let short: String = text.lines().take(3).map(|l| format!("{l}\n")).collect();
        std::fs::write(&path, short).unwrap();
        let err = read_cache(&path, &key, true, &areas).expect_err("one row for three areas");
        assert!(format!("{err:#}").contains("1 rows for 3 areas"), "{err:#}");
    }

    #[test]
    fn a_csv_with_another_header_is_rejected() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("normals.csv");
        std::fs::write(
            &path,
            "area_id,slot,normal,years,baseline\na,06-1,1,1,1991-2020\n",
        )
        .unwrap();
        let err = read_normals_csv(&path).expect_err("old header");
        assert!(format!("{err:#}").contains("header"), "{err:#}");
    }
}