geolith-dataset-builder 0.5.0

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
//! `geolith dataset accuracy`: GDAL as an optional external oracle.
//!
//! Ported from the `accuracy` command of the former `scripts/datasets/refresh.ts`. The
//! engine and the oracle must agree on a district's value: the mean of the
//! raster cells inside it, weighted by `fraction × spherical cell area`.
//! GDAL computes the same number from a cell-area weights grid
//! (`gdal raster zonal-stats --pixels fractional --stat weighted_mean`), and
//! the two agree to about `1e-7 mm` on the India rainfall series.
//!
//! GDAL is a *gate dependency*, not a runtime one: an absent or broken `gdal`
//! is exit `3` naming the tool, never a pass.

use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;

use crate::error::{
    DatasetError, IoOp, IoResultExt as _, IoStepExt as _, JsonResultExt as _, NumberResultExt as _,
    Result,
};
use serde_json::Value;

use crate::cli::AccuracyArgs;
use crate::config::DatasetConfig;
use crate::exit::Exit;
use crate::layout::{boundaries_dir, build_prefix, settings};
use crate::rasters::{Status, discover};

/// Smallest rainfall tolerance, mm.
pub const RAINFALL_TOLERANCE_MM: f64 = 0.05;
/// Rainfall tolerance as a share of the reference value.
pub const RAINFALL_TOLERANCE_REL: f64 = 0.005;
/// NDVI tolerance, a ratio.
pub const NDVI_TOLERANCE: f64 = 1e-4;
/// Mean earth radius, m: the engine's cell-area formula.
pub const EARTH_RADIUS_M: f64 = 6_371_008.8;
/// Nodata of the CHIRPS rasters: they carry no nodata tag.
pub const CHIRPS_NODATA: f64 = -9999.0;

/// The tolerance of one comparison.
#[must_use]
pub fn tolerance(dataset: &str, reference: f64) -> f64 {
    if dataset == "ndvi" {
        NDVI_TOLERANCE
    } else {
        RAINFALL_TOLERANCE_MM.max(RAINFALL_TOLERANCE_REL * reference.abs())
    }
}

/// The result of comparing one build's values with the oracle's.
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub struct Report {
    /// Values both sides carry and the comparison covered.
    pub comparisons: usize,
    /// Largest absolute difference.
    pub max_abs_diff: f64,
    /// Largest difference relative to the reference.
    pub max_rel_diff: f64,
    /// Values our side carries and the oracle does not (a fallback cell).
    pub fallbacks: usize,
    /// One line per value outside tolerance or missing a side.
    pub failures: Vec<String>,
}

/// Compares `ours` with `refs` (area id → value), rainfall rules.
///
/// # Errors
///
/// Fails when an area's reference is present but not a number.
pub fn compare_rainfall(
    ours: &BTreeMap<String, f64>,
    refs: &BTreeMap<String, Option<f64>>,
) -> Result<Report> {
    let mut report = Report {
        comparisons: 0,
        max_abs_diff: 0.0,
        max_rel_diff: 0.0,
        fallbacks: 0,
        failures: Vec::new(),
    };
    for (area, value) in ours {
        let Some(reference) = refs.get(area) else {
            report.failures.push(format!(
                "{area}: no reference value (the oracle skipped it)"
            ));
            continue;
        };
        let Some(reference) = reference else {
            report.fallbacks += 1;
            continue;
        };
        report.comparisons += 1;
        let diff = (value - reference).abs();
        report.max_abs_diff = report.max_abs_diff.max(diff);
        if *reference != 0.0 {
            report.max_rel_diff = report.max_rel_diff.max(diff / reference.abs());
        }
        if diff > tolerance("rainfall", *reference) {
            report
                .failures
                .push(format!("{area}: ours {value} vs reference {reference}"));
        }
    }
    Ok(report)
}

/// Compares `ours` with `refs`, NDVI rules: a reference the oracle lacks is a
/// fallback cell of the engine, counted, not failed.
#[must_use]
pub fn compare_ndvi(ours: &BTreeMap<String, f64>, refs: &BTreeMap<String, Option<f64>>) -> Report {
    let mut report = Report {
        comparisons: 0,
        max_abs_diff: 0.0,
        max_rel_diff: 0.0,
        fallbacks: 0,
        failures: Vec::new(),
    };
    for (area, value) in ours {
        match refs.get(area) {
            Some(Some(reference)) => {
                report.comparisons += 1;
                let diff = (value - reference).abs();
                report.max_abs_diff = report.max_abs_diff.max(diff);
                if *reference != 0.0 {
                    report.max_rel_diff = report.max_rel_diff.max(diff / reference.abs());
                }
                if diff > NDVI_TOLERANCE {
                    report
                        .failures
                        .push(format!("{area}: ours {value} vs reference {reference}"));
                }
            }
            Some(None) | None => report.fallbacks += 1,
        }
    }
    report
}

/// The raster grid the oracle works on.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub struct Grid {
    /// Columns.
    pub width: u32,
    /// Rows.
    pub height: u32,
    /// Longitude of the upper-left corner.
    pub origin_x: f64,
    /// Latitude of the upper-left corner.
    pub origin_y: f64,
    /// Longitude step, degrees.
    pub pixel_width: f64,
    /// Latitude step, degrees (positive).
    pub pixel_height: f64,
}

impl Grid {
    /// The grid of a `gdalinfo -json` document.
    ///
    /// # Errors
    ///
    /// Fails when the document has no size or geotransform.
    pub fn from_gdalinfo(value: &Value) -> Result<Self> {
        let size = value
            .get("size")
            .and_then(Value::as_array)
            .ok_or_else(|| DatasetError::data("gdalinfo reports no raster size"))?;
        let (Some(width), Some(height)) = (
            size.first().and_then(Value::as_u64),
            size.get(1).and_then(Value::as_u64),
        ) else {
            return Err(DatasetError::data("gdalinfo reports no raster size"));
        };
        let transform = value
            .get("geoTransform")
            .and_then(Value::as_array)
            .ok_or_else(|| DatasetError::data("gdalinfo reports no geotransform"))?;
        let at = |index: usize| transform.get(index).and_then(Value::as_f64);
        let (Some(origin_x), Some(pixel_width), Some(origin_y), Some(pixel_height)) =
            (at(0), at(1), at(3), at(5))
        else {
            return Err(DatasetError::data("gdalinfo reports no geotransform"));
        };
        Ok(Self {
            width: u32::try_from(width).number_of("width does not fit a u32")?,
            height: u32::try_from(height).number_of("height does not fit a u32")?,
            origin_x,
            origin_y,
            pixel_width,
            pixel_height: pixel_height.abs(),
        })
    }

    /// Spherical area of one cell of `row`, m².
    #[must_use]
    pub fn cell_area_m2(&self, row: u32) -> f64 {
        let rad = std::f64::consts::PI / 180.0;
        let top = self.origin_y - f64::from(row) * self.pixel_height;
        let bottom = top - self.pixel_height;
        EARTH_RADIUS_M
            * EARTH_RADIUS_M
            * self.pixel_width
            * rad
            * ((top * rad).sin() - (bottom * rad).sin()).abs()
    }

    /// The ESRI ASCII grid header of this grid.
    #[must_use]
    pub fn ascii_header(&self) -> String {
        let cell = if (self.pixel_width - self.pixel_height).abs() <= 1e-9 {
            format!("cellsize {}\n", self.pixel_width)
        } else {
            format!("dx {}\ndy {}\n", self.pixel_width, self.pixel_height)
        };
        format!(
            "ncols {}\nnrows {}\nxllcorner {}\nyllcorner {}\n{cell}",
            self.width,
            self.height,
            self.origin_x,
            self.origin_y - f64::from(self.height) * self.pixel_height
        )
    }
}

/// Writes the cell-area weights grid of `grid` as an ESRI ASCII grid.
///
/// # Errors
///
/// Fails when the file cannot be written.
pub fn write_weights(path: &Path, grid: Grid) -> Result<()> {
    let mut text = grid.ascii_header();
    for row in 0..grid.height {
        let area = grid.cell_area_m2(row);
        let value = format!("{area:.4}");
        for column in 0..grid.width {
            if column > 0 {
                text.push(' ');
            }
            text.push_str(&value);
        }
        text.push('\n');
    }
    let partial = path.with_extension("asc.part");
    fs::write(&partial, text).io_at(IoOp::Write, &partial)?;
    fs::rename(&partial, path).io_at(IoOp::RenameTo, path)
}

/// The six geotransform values of a VRT's `<GeoTransform>`.
///
/// # Errors
///
/// Fails when the VRT has no six-number `<GeoTransform>`.
pub fn vrt_geotransform(xml: &str) -> Result<Vec<String>> {
    let start = xml
        .find("<GeoTransform>")
        .ok_or_else(|| DatasetError::data("the VRT has no <GeoTransform>"))?
        + "<GeoTransform>".len();
    let rest = &xml[start..];
    let end = rest
        .find("</GeoTransform>")
        .ok_or_else(|| DatasetError::data("the VRT has no </GeoTransform>"))?;
    let values: Vec<String> = rest[..end]
        .split(',')
        .map(|v| v.trim().to_owned())
        .collect();
    if values.len() != 6 || values.iter().any(|v| v.parse::<f64>().is_err()) {
        return Err(DatasetError::data(
            "the VRT's <GeoTransform> does not hold six numbers",
        ));
    }
    Ok(values)
}

/// Runs a command, returning its stdout.
fn run_tool(tool: &str, args: &[&str]) -> Result<String> {
    let output = Command::new(tool)
        .args(args)
        .output()
        .io_step(format!("running {tool} (install it: brew install gdal)"))?;
    if !output.status.success() {
        return Err(DatasetError::data(format!(
            "{tool} {} failed: {}",
            args.join(" "),
            String::from_utf8_lossy(&output.stderr).trim()
        )));
    }
    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// The `gdal` version, or [`Exit`] `3` naming the tool when it is absent.
///
/// # Errors
///
/// Fails with exit code `3` when `gdal` is missing or does not run.
pub fn gdal_version() -> Option<String> {
    let output = Command::new("gdal").arg("--version").output().ok()?;
    if !output.status.success() {
        return None;
    }
    String::from_utf8_lossy(&output.stdout)
        .split_whitespace()
        .nth(1)
        .map(str::to_owned)
}

/// The oracle's values of `raster` over `areas`, id → value.
///
/// # Errors
///
/// Fails when a GDAL step fails or its CSV cannot be read.
pub fn oracle(
    raster: &Path,
    areas: &Path,
    scratch: &Path,
    nodata: f64,
) -> Result<BTreeMap<String, Option<f64>>> {
    fs::create_dir_all(scratch).io_at(IoOp::Create, scratch)?;
    let value_vrt = scratch.join("value.vrt");
    let nodata_text = format!("{nodata}");
    run_tool(
        "gdal_translate",
        &[
            "-q",
            "-of",
            "VRT",
            "-a_nodata",
            &nodata_text,
            &raster.display().to_string(),
            &value_vrt.display().to_string(),
        ],
    )?;
    let xml = fs::read_to_string(&value_vrt).io_at(IoOp::Read, &value_vrt)?;
    let transform = vrt_geotransform(&xml)?;
    let info = run_tool("gdalinfo", &["-json", &raster.display().to_string()])?;
    let info: Value = serde_json::from_str(&info).json_of("gdalinfo did not print JSON")?;
    let grid = Grid::from_gdalinfo(&info)?;
    let weights_asc = scratch.join(format!("weights-{}x{}.asc", grid.width, grid.height));
    let weights_vrt = weights_asc.with_extension("vrt");
    if !weights_vrt.is_file() {
        write_weights(&weights_asc, grid)?;
        let mut args = vec![
            "-q",
            "-of",
            "VRT",
            "-oo",
            "DATATYPE=Float64",
            "-a_srs",
            "EPSG:4326",
            "-a_gt",
        ];
        for value in &transform {
            args.push(value);
        }
        let asc = weights_asc.display().to_string();
        let vrt = weights_vrt.display().to_string();
        args.push(&asc);
        args.push(&vrt);
        run_tool("gdal_translate", &args)?;
    }
    let csv = scratch.join("reference.csv");
    let csv_text = csv.display().to_string();
    let weights_text = weights_vrt.display().to_string();
    run_tool(
        "gdal",
        &[
            "raster",
            "zonal-stats",
            "--input",
            &value_vrt.display().to_string(),
            "--zones",
            &areas.display().to_string(),
            "--weights",
            &weights_text,
            "--pixels",
            "fractional",
            "--stat",
            "weighted_mean",
            "--stat",
            "count",
            "--include-field",
            "id",
            "-o",
            &csv_text,
            "--overwrite",
            "-q",
        ],
    )?;
    read_reference(&csv)
}

/// The id → weighted mean of a `zonal-stats` CSV.
///
/// # Errors
///
/// Fails when the CSV cannot be read or lacks the two columns.
pub fn read_reference(path: &Path) -> Result<BTreeMap<String, Option<f64>>> {
    let text = fs::read_to_string(path).io_at(IoOp::Read, path)?;
    let mut rows = crate::normals::parse_csv(&text)?;
    if rows.is_empty() {
        return Err(DatasetError::data(format!("{} is empty", path.display())));
    }
    let header = rows.remove(0);
    let column = |name: &str| header.iter().position(|cell| cell.as_str() == name);
    let (Some(id_at), Some(mean_at)) = (column("id"), column("weighted_mean")) else {
        return Err(DatasetError::data(format!(
            "{} needs the id and weighted_mean columns",
            path.display()
        )));
    };
    let mut values = BTreeMap::new();
    for row in rows {
        let Some(id) = row.get(id_at).filter(|id| !id.is_empty()) else {
            continue;
        };
        let cell = row.get(mean_at).map_or("", String::as_str).trim();
        let value = cell.parse::<f64>().ok().filter(|value| value.is_finite());
        values.insert(id.clone(), value);
    }
    Ok(values)
}

/// The values of one period from a stage's `numbers.csv`.
///
/// # Errors
///
/// Fails when the CSV has no header or lacks a column.
pub fn stage_values(csv: &str, period_end: &str) -> Result<BTreeMap<String, f64>> {
    let mut rows = crate::normals::parse_csv(csv)?;
    if rows.is_empty() {
        return Err(DatasetError::data("numbers.csv is empty"));
    }
    let header = rows.remove(0);
    let column = |name: &str| header.iter().position(|cell| cell.as_str() == name);
    let (Some(id_at), Some(end_at), Some(value_at)) =
        (column("area_id"), column("period_end"), column("value"))
    else {
        return Err(DatasetError::data(
            "numbers.csv needs area_id, period_end and value",
        ));
    };
    let mut values = BTreeMap::new();
    for row in rows {
        if row.get(end_at).map(String::as_str) != Some(period_end) {
            continue;
        }
        let cell = row.get(value_at).map_or("", String::as_str);
        if let Ok(value) = cell.parse::<f64>()
            && value.is_finite()
            && let Some(id) = row.get(id_at).filter(|id| !id.is_empty())
        {
            values.insert(id.clone(), value);
        }
    }
    Ok(values)
}

/// The newest raster of a dataset on disk.
///
/// # Errors
///
/// Fails when no raster is on disk or the config cannot be read.
pub fn newest_raster(s: &crate::layout::Settings) -> Result<(PathBuf, String)> {
    let config = DatasetConfig::load(&s.config_path)?;
    let stem = s.data_root.join("datasets").join(&s.dataset);
    let mut found = Vec::new();
    for dir in [stem.join("src"), stem.join("src").join(&s.cc)] {
        if dir.is_dir() {
            let prelim = config
                .prelim_file_template
                .as_deref()
                .unwrap_or(&config.file_template);
            found.extend(discover(&dir, &config.file_template, prelim)?);
        }
    }
    let mut newest: Option<((crate::rasters::Period, bool), _)> = None;
    for file in found {
        let rank = (file.period, file.status == Status::Final);
        if newest.as_ref().is_none_or(|(best, _)| rank > *best) {
            newest = Some((rank, file));
        }
    }
    let Some((_, file)) = newest else {
        return Err(DatasetError::data(format!(
            "no raster on disk under {}",
            stem.join("src").display()
        )));
    };
    Ok((file.path, file.period.end_iso()))
}

/// Run `geolith dataset accuracy`.
///
/// # Errors
///
/// Fails with exit code `3` when GDAL is absent, `1` when a value differs.
pub fn run(args: &AccuracyArgs) -> Result<()> {
    run_with(args, gdal_version().as_deref())
}

/// The accuracy gate, with the GDAL probe's answer injected: `None` is a
/// failed gate (exit 3), never a pass.
///
/// # Errors
///
/// Fails with [`Exit`] `3` when `gdal` is `None`, and with the comparison's
/// errors.
pub fn run_with(args: &AccuracyArgs, gdal: Option<&str>) -> Result<()> {
    let Some(version) = gdal else {
        eprintln!("accuracy: gdal not found: the gate needs it (brew install gdal)");
        return Err(DatasetError::Exit(Exit(3)));
    };
    let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
    let stage = s.stage_root.join(&args.build);
    let numbers_path = stage
        .join(build_prefix(&s, &args.build))
        .join("numbers.csv");
    let numbers = fs::read_to_string(&numbers_path).io_at(IoOp::Read, &numbers_path)?;
    let (raster, period_end) = newest_raster(&s)?;
    let areas = s
        .data_root
        .join("datasets/boundaries")
        .join(&s.cc)
        .join(boundaries_dir(&s))
        .join("areas.geojson");
    if !areas.is_file() {
        return Err(DatasetError::data(format!(
            "no areas of the boundaries in {}",
            areas.display()
        )));
    }
    let ours = stage_values(&numbers, &period_end)?;
    if ours.is_empty() {
        return Err(DatasetError::data(format!(
            "numbers.csv has no value for {period_end}"
        )));
    }
    // The weights grid is 200 MB of scratch, so it lives outside the data
    // root: the live refresh job's directories are never touched by a gate
    // run by hand.
    let scratch = std::env::temp_dir()
        .join("geolith-accuracy")
        .join(format!("{}-{}", s.dataset, args.build));
    let refs = oracle(&raster, &areas, &scratch, CHIRPS_NODATA)?;
    let report = if s.dataset == "ndvi" {
        compare_ndvi(&ours, &refs)
    } else {
        compare_rainfall(&ours, &refs)?
    };
    if s.dataset == "ndvi" {
        println!(
            "accuracy: {} areas, max_abs_diff {:.6}, tolerance {}",
            report.comparisons, report.max_abs_diff, NDVI_TOLERANCE
        );
    } else {
        println!(
            "accuracy: {} areas, max_abs_diff_mm {:.4}, max_rel_diff {:.6}, \
             tolerance max({RAINFALL_TOLERANCE_MM} mm, {}%)",
            report.comparisons,
            report.max_abs_diff,
            report.max_rel_diff,
            RAINFALL_TOLERANCE_REL * 100.0
        );
    }
    if report.fallbacks > 0 {
        println!(
            "accuracy: {} areas have no oracle value (the engine's nearest-cell fallback)",
            report.fallbacks
        );
    }
    if !report.failures.is_empty() {
        let shown: Vec<&str> = report.failures.iter().take(5).map(String::as_str).collect();
        return Err(DatasetError::data(format!(
            "accuracy: {} areas differ: {} (gdal {version})",
            report.failures.len(),
            shown.join("; ")
        )));
    }
    Ok(())
}

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

    fn ours(pairs: &[(&str, f64)]) -> BTreeMap<String, f64> {
        pairs
            .iter()
            .map(|(id, value)| ((*id).to_owned(), *value))
            .collect()
    }

    fn refs(pairs: &[(&str, Option<f64>)]) -> BTreeMap<String, Option<f64>> {
        pairs
            .iter()
            .map(|(id, value)| ((*id).to_owned(), *value))
            .collect()
    }

    #[test]
    fn a_five_millimetre_reference_allows_five_hundredths() {
        let report = compare_rainfall(
            &ours(&[("a", 5.049), ("b", 5.0)]),
            &refs(&[("a", Some(5.0)), ("b", Some(5.0))]),
        )
        .expect("compare");
        assert_eq!(report.comparisons, 2);
        assert!(report.failures.is_empty(), "{report:?}");
        let report =
            compare_rainfall(&ours(&[("a", 5.061)]), &refs(&[("a", Some(5.0))])).expect("compare");
        assert_eq!(report.failures.len(), 1);
    }

    #[test]
    fn a_hundred_millimetre_reference_widens_the_tolerance_to_half_a_percent() {
        // 0.5% of 100 mm is 0.5 mm, above the 0.05 mm floor.
        let report = compare_rainfall(&ours(&[("a", 100.49)]), &refs(&[("a", Some(100.0))]))
            .expect("compare");
        assert!(report.failures.is_empty(), "{report:?}");
        let report = compare_rainfall(&ours(&[("a", 100.51)]), &refs(&[("a", Some(100.0))]))
            .expect("compare");
        assert_eq!(report.failures.len(), 1);
    }

    #[test]
    fn ndvi_allows_its_ten_thousandths() {
        let report = compare_ndvi(&ours(&[("a", 0.500_099)]), &refs(&[("a", Some(0.5))]));
        assert_eq!(report.comparisons, 1);
        assert!(report.failures.is_empty(), "{report:?}");
        let report = compare_ndvi(&ours(&[("a", 0.500_11)]), &refs(&[("a", Some(0.5))]));
        assert_eq!(report.failures.len(), 1);
    }

    #[test]
    fn an_area_the_oracle_lacks_is_a_fallback_not_a_failure() {
        let report = compare_ndvi(&ours(&[("a", 0.4)]), &refs(&[("a", None)]));
        assert_eq!(report.fallbacks, 1);
        assert_eq!(report.comparisons, 0);
        assert!(report.failures.is_empty());
    }

    #[test]
    fn a_missing_reference_fails_a_rainfall_comparison() {
        let report = compare_rainfall(&ours(&[("a", 1.0)]), &refs(&[])).expect("compare");
        assert_eq!(report.failures.len(), 1);
        assert!(report.failures[0].contains("no reference value"));
    }

    #[test]
    fn the_grid_comes_from_the_gdalinfo_document() {
        let info = serde_json::json!({
            "size": [7200, 2400],
            "geoTransform": [-180.0, 0.0500000007450581, 0.0, 60.0, 0.0, -0.0500000007450581]
        });
        let grid = Grid::from_gdalinfo(&info).expect("grid");
        assert_eq!((grid.width, grid.height), (7200, 2400));
        assert_eq!(grid.origin_x, -180.0);
        assert_eq!(grid.pixel_height, 0.0500000007450581);
        let header = grid.ascii_header();
        assert_eq!(
            header,
            "ncols 7200\nnrows 2400\nxllcorner -180\nyllcorner -60.00000178813944\n\
             cellsize 0.0500000007450581\n"
        );
    }

    #[test]
    fn the_cell_area_at_the_equator_is_about_three_thousand_km_squared() {
        // 0.05° of latitude at the equator is 5 559.75 m, so a cell is
        // 30.91 km²: the plane approximation, not the formula under test.
        let grid = Grid {
            width: 1,
            height: 2400,
            origin_x: -180.0,
            origin_y: 0.05,
            pixel_width: 0.05,
            pixel_height: 0.05,
        };
        let area = grid.cell_area_m2(0);
        assert!((area - 30_910_000.0).abs() < 2000.0, "{area}");
        // One degree up, the same cell covers less ground.
        assert!(grid.cell_area_m2(20) < area);
    }

    #[test]
    fn a_vrt_geotransform_is_the_six_numbers_of_its_xml() {
        let xml =
            "<VRTDataset><GeoTransform>-180, 0.05, 0, 60, 0, -0.05</GeoTransform></VRTDataset>";
        assert_eq!(
            vrt_geotransform(xml).expect("six values"),
            ["-180", "0.05", "0", "60", "0", "-0.05"]
        );
        assert!(vrt_geotransform("<VRT/>").is_err());
    }

    #[test]
    fn the_reference_csv_keeps_a_quoted_id_and_a_null_mean() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = dir.path().join("reference.csv");
        fs::write(&path, "id,weighted_mean,count\n\"a-1\",1.5,100\nb-2,,0\n").expect("write");
        let refs = read_reference(&path).expect("reference");
        assert_eq!(refs["a-1"], Some(1.5));
        assert_eq!(refs["b-2"], None);
    }
}

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

    #[test]
    fn a_missing_gdal_is_a_failed_gate_not_a_pass() {
        let args = AccuracyArgs {
            build: "2026-11-15.20261119T0141Z".to_owned(),
            dataset: Some("rainfall".to_owned()),
            country: Some("in".to_owned()),
        };
        let error = run_with(&args, None).expect_err("gdal is absent");
        assert!(
            geolith::error::report(&error).contains("exit 3"),
            "{error:#}"
        );
    }
}