geolith-dataset-builder 0.4.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
//! `geolith dataset slots`: the measured per-slot table the bounds gate reads.
//!
//! Ported from the former `scripts/datasets/slots.ts`. It aggregates the values cache of
//! `geolith dataset values` — one CSV per baseline raster, named
//! `<product>.<year>.<MM>.<n>.values.csv` — into one row per calendar slot: the
//! national mean of every baseline year, its minimum, median and maximum, and,
//! for rainfall, the share of areas under 1 mm and the largest area value.
//! A year outside the baseline is a different measurement (the NDVI source
//! changed in 2019) and never enters the table.
//!
//! The table is committed data: India keeps `<dataset>-slots.json`, a country
//! sits beside it as `<dataset>-slots-<cc>.json`.

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

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

use crate::cli::SlotsArgs;
use crate::layout::settings;

/// Decimals of the stored values: rainfall in mm, NDVI a ratio.
pub const DECIMALS: &[(&str, usize)] = &[("rainfall", 3), ("ndvi", 4)];

/// One slot's measured history.
#[derive(Debug, Clone, PartialEq)]
pub struct SlotHistory {
    /// Years the slot was measured over.
    pub years: u32,
    /// Smallest national mean.
    pub mean_min: f64,
    /// Median national mean.
    pub mean_median: f64,
    /// Largest national mean.
    pub mean_max: f64,
    /// Smallest district median.
    pub median_min: f64,
    /// Largest district median.
    pub median_max: f64,
    /// Rainfall: the smallest share of areas under 1 mm over the years, the
    /// wettest year.
    pub min_share_under_1mm: Option<f64>,
    /// Rainfall: the largest share of areas under 1 mm.
    pub max_share_under_1mm: Option<f64>,
    /// Rainfall: the largest value of any area.
    pub max_area_mm: Option<f64>,
    /// The national mean of every year, oldest first.
    pub yearly_means: Vec<f64>,
}

/// The committed slot table of a dataset and country.
#[derive(Debug, Clone, PartialEq)]
pub struct SlotTable {
    /// Dataset id.
    pub dataset: String,
    /// Unit of the values.
    pub unit: String,
    /// Slot (`MM-P` / `MM-D`) → its history.
    pub slots: BTreeMap<String, SlotHistory>,
    /// What was measured, over how many areas.
    pub source: String,
}

/// One baseline raster's values.
#[derive(Debug, Clone, PartialEq)]
pub struct Sample {
    /// Year of the raster.
    pub year: u32,
    /// Slot (`MM-P` / `MM-D`).
    pub slot: String,
    /// The value of every area the raster covers.
    pub values: Vec<f64>,
}

/// The year and slot of a cache file name, when it is one.
#[must_use]
pub fn parse_name(name: &str) -> Option<(u32, String)> {
    let stem = name.strip_suffix(".values.csv")?;
    let mut parts = stem.rsplit('.');
    let index: u32 = parts.next()?.parse().ok()?;
    let month = parts.next()?;
    let year: u32 = parts.next()?.parse().ok()?;
    if year < 1000 || month.len() != 2 || index > 9 {
        return None;
    }
    Some((year, format!("{month}-{index}")))
}

/// The area values of one cache CSV: the last column, skipping an empty value.
#[must_use]
pub fn parse_values(text: &str) -> Vec<f64> {
    let mut values = Vec::new();
    for line in text.lines() {
        if line.is_empty() || line.starts_with('#') || line.starts_with("area_id,") {
            continue;
        }
        let cell = line.rsplit_once(',').map_or(line, |(_, cell)| cell).trim();
        if cell.is_empty() {
            continue;
        }
        if let Ok(value) = cell.parse::<f64>()
            && value.is_finite()
        {
            values.push(value);
        }
    }
    values
}

/// The median of `values`: the middle value, or the mean of the two middles.
#[must_use]
pub fn median(values: &[f64]) -> f64 {
    let mut sorted = values.to_vec();
    sorted.sort_by(f64::total_cmp);
    let middle = sorted.len() / 2;
    if sorted.len() % 2 == 1 {
        sorted[middle]
    } else {
        (sorted[middle - 1] + sorted[middle]) / 2.0
    }
}

/// Rounds `value` to `digits` decimals, as JavaScript's `Number(toFixed())`.
fn round(value: f64, digits: usize) -> f64 {
    format!("{value:.digits$}").parse::<f64>().unwrap_or(value)
}

/// The decimals of `dataset`'s table.
#[must_use]
pub fn decimals(dataset: &str) -> usize {
    DECIMALS
        .iter()
        .find(|(id, _)| *id == dataset)
        .map_or(4, |(_, digits)| *digits)
}

/// The table of `samples` over the baseline years `from`..=`to`.
///
/// # Errors
///
/// Fails on a slot measured twice for one year.
pub fn slot_table(
    dataset: &str,
    samples: &[Sample],
    source: &str,
    baseline: (u32, u32),
) -> Result<SlotTable> {
    let digits = decimals(dataset);
    // Slot → year → the area values of that raster.
    let mut by_slot: BTreeMap<String, BTreeMap<u32, Vec<f64>>> = BTreeMap::new();
    for sample in samples {
        if sample.values.is_empty() || sample.year < baseline.0 || sample.year > baseline.1 {
            continue;
        }
        let years = by_slot.entry(sample.slot.clone()).or_default();
        if years.insert(sample.year, sample.values.clone()).is_some() {
            return Err(DatasetError::data(format!(
                "slot {} has two samples of one year",
                sample.slot
            )));
        }
    }
    let mut slots = BTreeMap::new();
    for (slot, years) in by_slot {
        let mut means = Vec::with_capacity(years.len());
        let mut medians = Vec::with_capacity(years.len());
        let mut shares = Vec::with_capacity(years.len());
        let mut max_area: f64 = 0.0;
        for values in years.values() {
            means.push(values.iter().sum::<f64>() / values.len() as f64);
            medians.push(median(values));
            let dry = values.iter().filter(|value| **value < 1.0).count();
            shares.push(dry as f64 / values.len() as f64);
            for value in values {
                max_area = max_area.max(*value);
            }
        }
        let history = SlotHistory {
            years: u32::try_from(means.len()).unwrap_or(u32::MAX),
            mean_min: round(min_of(&means), digits),
            mean_median: round(median(&means), digits),
            mean_max: round(max_of(&means), digits),
            median_min: round(min_of(&medians), digits),
            median_max: round(max_of(&medians), digits),
            min_share_under_1mm: (dataset == "rainfall").then(|| round(min_of(&shares), 3)),
            max_share_under_1mm: (dataset == "rainfall").then(|| round(max_of(&shares), 3)),
            max_area_mm: (dataset == "rainfall").then(|| round(max_area, 1)),
            yearly_means: means.iter().map(|mean| round(*mean, digits)).collect(),
        };
        slots.insert(slot, history);
    }
    Ok(SlotTable {
        dataset: dataset.to_owned(),
        unit: if dataset == "ndvi" { "ndvi" } else { "mm" }.to_owned(),
        slots,
        source: source.to_owned(),
    })
}

fn min_of(values: &[f64]) -> f64 {
    values.iter().copied().fold(f64::INFINITY, f64::min)
}

fn max_of(values: &[f64]) -> f64 {
    values.iter().copied().fold(f64::NEG_INFINITY, f64::max)
}

/// Every sample of the values cache `dir`, in file name order.
///
/// # Errors
///
/// Fails when the directory cannot be read or a cache file cannot be read.
pub fn read_cache(dir: &Path) -> Result<Vec<Sample>> {
    let entries = fs::read_dir(dir).io_at(IoOp::Read, dir)?;
    let mut names: Vec<PathBuf> = entries
        .filter_map(|entry| entry.ok().map(|entry| entry.path()))
        .collect();
    names.sort();
    let mut samples = Vec::new();
    for path in names {
        let name = path
            .file_name()
            .and_then(|name| name.to_str())
            .unwrap_or_default();
        let Some((year, slot)) = parse_name(name) else {
            continue;
        };
        let text = fs::read_to_string(&path).io_at(IoOp::Read, &path)?;
        samples.push(Sample {
            year,
            slot,
            values: parse_values(&text),
        });
    }
    Ok(samples)
}

/// The source line of the table: what was measured, over how many areas.
#[must_use]
pub fn source_line(dataset: &str, areas: usize, baseline: &str) -> String {
    let years = baseline
        .split_once('-')
        .and_then(|(from, to)| Some((from.parse::<i64>().ok()?, to.parse::<i64>().ok()?)))
        .map_or(0, |(from, to)| to - from + 1);
    let product = if dataset == "ndvi" {
        "CLMS NDVI 300 m dekads"
    } else {
        "CHIRPS v3.0 pentads"
    };
    format!(
        "{product} {baseline} ({years} years): the area values of every baseline raster \
         (`geolith dataset values`, the reading of the build), the national mean over the \
         {areas} areas that carry a value; min_share_under_1mm is the smallest share of areas \
         under 1 mm over the years (the wettest year)."
    )
}

/// The committed table of `dataset` and `cc`.
#[must_use]
pub fn slot_table_path(repo: &Path, dataset: &str, cc: &str) -> PathBuf {
    let name = if cc == "in" {
        format!("{dataset}-slots.json")
    } else {
        format!("{dataset}-slots-{cc}.json")
    };
    repo.join("packages/dataset-builder/data/datasets")
        .join(name)
}

/// Reads a slot table, failing on a slot that has no number.
///
/// # Errors
///
/// Fails when the file cannot be read, is not a table, or has a slot without
/// numeric `mean_min` and `mean_max`.
pub fn read_slots(path: &Path) -> Result<SlotTable> {
    let text = fs::read_to_string(path).io_at(IoOp::Read, path)?;
    let value: Value =
        serde_json::from_str(&text).json_of(format!("{} is not JSON", path.display()))?;
    let dataset = value
        .get("dataset")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_owned();
    let unit = value
        .get("unit")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_owned();
    let source = value
        .get("source")
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_owned();
    let mut slots = BTreeMap::new();
    let entries = value.get("slots").and_then(Value::as_object);
    for (slot, history) in entries.into_iter().flatten() {
        let number = |key: &str| history.get(key).and_then(Value::as_f64);
        let (Some(mean_min), Some(mean_max)) = (number("mean_min"), number("mean_max")) else {
            return Err(DatasetError::data(format!(
                "{}: slot {slot} needs numeric mean_min and mean_max",
                path.display()
            )));
        };
        if !mean_min.is_finite() || !mean_max.is_finite() {
            return Err(DatasetError::data(format!(
                "{}: slot {slot} needs numeric mean_min and mean_max",
                path.display()
            )));
        }
        slots.insert(
            slot.clone(),
            SlotHistory {
                years: history
                    .get("years")
                    .and_then(Value::as_u64)
                    .and_then(|years| u32::try_from(years).ok())
                    .unwrap_or_default(),
                mean_min,
                mean_median: number("mean_median").unwrap_or(mean_min),
                mean_max,
                median_min: number("median_min").unwrap_or_default(),
                median_max: number("median_max").unwrap_or_default(),
                min_share_under_1mm: number("min_share_under_1mm"),
                max_share_under_1mm: number("max_share_under_1mm"),
                max_area_mm: number("max_area_mm"),
                yearly_means: history
                    .get("yearly_means")
                    .and_then(Value::as_array)
                    .map(|values| values.iter().filter_map(Value::as_f64).collect())
                    .unwrap_or_default(),
            },
        );
    }
    Ok(SlotTable {
        dataset,
        unit,
        slots,
        source,
    })
}

/// The slot key `MM-P` (pentad) or `MM-D` (dekad) of the period ending `end`.
///
/// # Errors
///
/// Fails when `end` is not a `YYYY-MM-DD` date.
pub fn slot_key(end: &str, dataset: &str) -> Result<String> {
    let bytes = end.as_bytes();
    let date = bytes.len() == 10
        && bytes[4] == b'-'
        && bytes[7] == b'-'
        && [0, 1, 2, 3, 5, 6, 8, 9]
            .iter()
            .all(|index| bytes[*index].is_ascii_digit());
    let day: u32 = end
        .get(8..10)
        .and_then(|day| day.parse().ok())
        .filter(|_| date)
        .ok_or_else(|| DatasetError::data(format!("not a date YYYY-MM-DD: {end}")))?;
    let month = &end[5..7];
    let index = if dataset == "ndvi" {
        match day {
            10 => 1,
            20 => 2,
            _ => 3,
        }
    } else if day.is_multiple_of(5) && day <= 25 {
        day / 5
    } else {
        6
    };
    Ok(format!("{month}-{index}"))
}

/// A JSON number as JavaScript's `JSON.stringify` writes it: `2`, not `2.0`.
fn js_number(value: f64, digits: usize) -> Value {
    let mut text = format!("{value:.digits$}");
    if let Some(dot) = text.find('.') {
        while text.ends_with('0') {
            text.pop();
        }
        if text.len() == dot + 1 {
            text.pop();
        }
    }
    if text
        .chars()
        .all(|char| char == '0' || char == '.' || char == '-')
    {
        return Value::from(0);
    }
    serde_json::from_str(&text).unwrap_or_else(|_| Value::from(0))
}

/// The table as `JSON.stringify(table, null, 2)` plus a newline.
#[derive(Serialize)]
struct TableJson<'a> {
    dataset: &'a str,
    unit: &'a str,
    slots: BTreeMap<&'a str, HistoryJson>,
    source: &'a str,
}

/// One slot row, in the field order the script writes.
#[derive(Serialize)]
struct HistoryJson {
    years: u32,
    mean_min: Value,
    mean_median: Value,
    mean_max: Value,
    median_min: Value,
    median_max: Value,
    yearly_means: Vec<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    min_share_under_1mm: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_share_under_1mm: Option<Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_area_mm: Option<Value>,
}

/// Renders `table` in the committed file's layout.
///
/// # Errors
///
/// Fails when the table cannot be serialized.
pub fn render(table: &SlotTable) -> Result<String> {
    let digits = decimals(&table.dataset);
    let slots = table
        .slots
        .iter()
        .map(|(slot, history)| {
            (
                slot.as_str(),
                HistoryJson {
                    years: history.years,
                    mean_min: js_number(history.mean_min, digits),
                    mean_median: js_number(history.mean_median, digits),
                    mean_max: js_number(history.mean_max, digits),
                    median_min: js_number(history.median_min, digits),
                    median_max: js_number(history.median_max, digits),
                    yearly_means: history
                        .yearly_means
                        .iter()
                        .map(|mean| js_number(*mean, digits))
                        .collect(),
                    min_share_under_1mm: history
                        .min_share_under_1mm
                        .map(|value| js_number(value, 3)),
                    max_share_under_1mm: history
                        .max_share_under_1mm
                        .map(|value| js_number(value, 3)),
                    max_area_mm: history.max_area_mm.map(|value| js_number(value, 1)),
                },
            )
        })
        .collect();
    let text = serde_json::to_string_pretty(&TableJson {
        dataset: &table.dataset,
        unit: &table.unit,
        slots,
        source: &table.source,
    })
    .json_of("serializing the slot table")?;
    Ok(format!("{text}\n"))
}

/// Writes the table of a dataset and country from its values cache.
///
/// # Errors
///
/// Fails when the cache is missing or empty, or the table cannot be written.
pub fn write_slots(dataset: &str, cc: &str, cache: &Path, out: &Path) -> Result<usize> {
    if !cache.is_dir() {
        return Err(DatasetError::data(format!(
            "no values cache in {}",
            cache.display()
        )));
    }
    let samples = read_cache(cache)?;
    if samples.is_empty() {
        return Err(DatasetError::data(format!(
            "{} holds no <product>.<year>.<MM>.<n>.values.csv",
            cache.display()
        )));
    }
    let s = settings(Some(dataset), Some(cc))?;
    let areas = s
        .country_config()
        .and_then(|config| config.boundaries.invariants.areas)
        .unwrap_or(0);
    let (from, to) = baseline_years(&s.baseline);
    let table = slot_table(
        dataset,
        &samples,
        &source_line(dataset, areas, &s.baseline),
        (from, to),
    )?;
    let text = render(&table)?;
    if let Some(parent) = out.parent() {
        fs::create_dir_all(parent).io_at(IoOp::Create, parent)?;
    }
    fs::write(out, text).io_at(IoOp::Write, out)?;
    println!(
        "slots: {} slots from {} rasters -> {}",
        table.slots.len(),
        samples.len(),
        out.display()
    );
    Ok(table.slots.len())
}

/// The `from`..`to` years of a `FIRST-LAST` baseline.
#[must_use]
pub fn baseline_years(baseline: &str) -> (u32, u32) {
    match baseline.split_once('-') {
        Some((from, to)) => match (from.parse::<u32>(), to.parse::<u32>()) {
            (Ok(from), Ok(to)) => (from, to),
            _ => (0, u32::MAX),
        },
        None => (0, u32::MAX),
    }
}

/// Run `geolith dataset slots`.
///
/// # Errors
///
/// Fails when the table cannot be measured or written.
pub fn run(args: &SlotsArgs) -> Result<()> {
    let dataset = args.dataset.as_deref().unwrap_or("rainfall");
    let cc = args.country.as_deref().unwrap_or("in");
    let out = match &args.out {
        Some(out) => out.clone(),
        None => {
            let s = settings(Some(dataset), Some(cc))?;
            slot_table_path(&s.repo, dataset, cc)
        }
    };
    let cache = &args.cache;
    write_slots(dataset, cc, cache, &out)?;
    Ok(())
}

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

    #[test]
    fn a_cache_name_gives_its_year_and_slot() {
        assert_eq!(
            parse_name("chirps-v3.0.1991.01.1.values.csv"),
            Some((1991, "01-1".to_owned()))
        );
        assert_eq!(
            parse_name("ndvi300-v3.2014.12.3.values.csv"),
            Some((2014, "12-3".to_owned()))
        );
        assert_eq!(parse_name("notes.csv"), None);
        // A slot is one digit: three is the last dekad, not a year.
        assert_eq!(parse_name("v.2026.01.10.values.csv"), None);
    }

    #[test]
    fn values_skip_an_empty_cell_and_a_comment() {
        let text = "area_id,value\n# a comment\na,1.5\nb,\nc,2\n";
        assert_eq!(parse_values(text), vec![1.5, 2.0]);
    }

    #[test]
    fn the_median_of_an_even_list_is_the_mean_of_its_middles() {
        assert_eq!(median(&[3.0, 1.0, 2.0]), 2.0);
        assert_eq!(median(&[4.0, 1.0, 3.0, 2.0]), 2.5);
        assert_eq!(median(&[7.0]), 7.0);
    }

    fn sample(year: u32, slot: &str, values: &[f64]) -> Sample {
        Sample {
            year,
            slot: slot.to_owned(),
            values: values.to_vec(),
        }
    }

    #[test]
    fn a_slot_carries_one_mean_per_year_and_its_extremes() {
        let samples = [
            sample(1991, "01-1", &[1.0, 3.0]),
            sample(1992, "01-1", &[2.0, 2.0]),
            sample(1993, "01-1", &[0.0, 0.0]),
        ];
        let table = slot_table("rainfall", &samples, "source", (1991, 2020)).expect("table");
        let history = &table.slots["01-1"];
        assert_eq!(history.years, 3);
        assert_eq!(history.yearly_means, vec![2.0, 2.0, 0.0]);
        assert_eq!(history.mean_min, 0.0);
        assert_eq!(history.mean_max, 2.0);
        assert_eq!(history.mean_median, 2.0);
        // The wettest year (1991/1992) has no area under 1 mm; the driest
        // (1993) has every area under 1 mm.
        assert_eq!(history.min_share_under_1mm, Some(0.0));
        assert_eq!(history.max_share_under_1mm, Some(1.0));
        assert_eq!(history.max_area_mm, Some(3.0));
        assert_eq!(table.unit, "mm");
    }

    #[test]
    fn a_year_outside_the_baseline_never_enters_the_table() {
        let samples = [
            sample(1990, "01-1", &[5.0]),
            sample(1991, "01-1", &[1.0]),
            sample(2021, "01-1", &[9.0]),
        ];
        let table = slot_table("rainfall", &samples, "source", (1991, 2020)).expect("table");
        assert_eq!(table.slots["01-1"].years, 1);
        assert_eq!(table.slots["01-1"].mean_min, 1.0);
        assert_eq!(table.slots["01-1"].yearly_means, vec![1.0]);
    }

    #[test]
    fn ndvi_keeps_four_decimals_and_no_dry_share() {
        // A 3-decimal table would store 0.346, so four decimals is visible.
        let samples = [sample(2019, "01-1", &[0.1234, 0.5678])];
        let table = slot_table("ndvi", &samples, "source", (2019, 2025)).expect("table");
        let history = &table.slots["01-1"];
        assert_eq!(table.unit, "ndvi");
        assert_eq!(history.mean_min, 0.3456);
        assert_eq!(history.min_share_under_1mm, None);
        assert_eq!(history.max_area_mm, None);
    }

    #[test]
    fn the_rendered_file_is_the_script_layout() {
        let table = SlotTable {
            dataset: "rainfall".to_owned(),
            unit: "mm".to_owned(),
            slots: BTreeMap::from([(
                "01-1".to_owned(),
                SlotHistory {
                    years: 2,
                    mean_min: 1.5,
                    mean_median: 2.0,
                    mean_max: 2.5,
                    median_min: 1.0,
                    median_max: 3.0,
                    min_share_under_1mm: Some(0.5),
                    max_share_under_1mm: Some(0.25),
                    max_area_mm: Some(12.3),
                    yearly_means: vec![1.5, 2.5],
                },
            )]),
            source: "CHIRPS".to_owned(),
        };
        let text = render(&table).expect("render");
        let expected = r#"{
  "dataset": "rainfall",
  "unit": "mm",
  "slots": {
    "01-1": {
      "years": 2,
      "mean_min": 1.5,
      "mean_median": 2,
      "mean_max": 2.5,
      "median_min": 1,
      "median_max": 3,
      "yearly_means": [
        1.5,
        2.5
      ],
      "min_share_under_1mm": 0.5,
      "max_share_under_1mm": 0.25,
      "max_area_mm": 12.3
    }
  },
  "source": "CHIRPS"
}
"#;
        assert_eq!(text, expected);
    }

    #[test]
    fn a_slot_key_is_the_pentad_or_the_dekad_of_its_end() {
        assert_eq!(slot_key("2026-11-15", "rainfall").expect("date"), "11-3");
        assert_eq!(slot_key("2026-11-30", "rainfall").expect("date"), "11-6");
        assert_eq!(slot_key("2026-11-10", "ndvi").expect("date"), "11-1");
        assert_eq!(slot_key("2026-11-25", "ndvi").expect("date"), "11-3");
        assert!(slot_key("2026-11", "rainfall").is_err());
    }

    #[test]
    fn india_keeps_the_short_table_name_and_a_country_does_not() {
        let repo = Path::new("/r");
        assert_eq!(
            slot_table_path(repo, "rainfall", "in"),
            PathBuf::from("/r/packages/dataset-builder/data/datasets/rainfall-slots.json")
        );
        assert_eq!(
            slot_table_path(repo, "rainfall", "us"),
            PathBuf::from("/r/packages/dataset-builder/data/datasets/rainfall-slots-us.json")
        );
    }

    #[test]
    fn the_source_line_names_the_product_the_years_and_the_areas() {
        assert_eq!(
            source_line("rainfall", 787, "1991-2020"),
            "CHIRPS v3.0 pentads 1991-2020 (30 years): the area values of every baseline raster \
             (`geolith dataset values`, the reading of the build), the national mean over the 787 \
             areas that carry a value; min_share_under_1mm is the smallest share of areas under \
             1 mm over the years (the wettest year)."
        );
    }

    #[test]
    fn a_table_without_a_numeric_mean_is_refused_naming_the_slot() {
        let dir = tempfile::tempdir().expect("a temp dir");
        let path = dir.path().join("rainfall-slots.json");
        fs::write(&path, r#"{"slots":{"01-1":{"years":1}}}"#).expect("write");
        let err = read_slots(&path).expect_err("no mean_min");
        assert!(
            err.to_string()
                .contains("slot 01-1 needs numeric mean_min and mean_max"),
            "{err}"
        );
    }
}