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
//! `geolith dataset bounds`: the sanity gate of a staged build's new period.
//!
//! Ported from `boundsFailures` of the former `scripts/datasets/refresh.ts`. The guard is
//! the *measured* history of the same calendar slot, not a fixed class share:
//! a real dry season has most districts under 1 mm, so a share rule would fail
//! it. A build fails when
//!
//! - the areas it names disagree with the series or the published pointer,
//! - too few areas carry a value of the new period (95% rainfall, 90% NDVI),
//! - a value is outside the physical range (0–3000 mm, −0.08–0.92),
//! - every area is identical (rainfall all-zero only when the slot's own table
//!   shows the wettest year had at least 80% of areas under 1 mm),
//! - the national mean is outside the slot's widened range (`max(2 mm, 3 × the
//!   slot's maximum)` for rainfall, ±0.15 for NDVI),
//! - the stage names another boundary release or tiles revision than this run.

use std::fs;

use anyhow::{Context, Result, bail};
use serde_json::Value;

use crate::cli::BoundsArgs;
use crate::layout::{build_prefix, current_key, read_json, settings};
use crate::remote::connect;
use crate::slots::{SlotTable, slot_key, slot_table_path};
use crate::stage::{Pointer, parse_pointer};

/// Largest rainfall of one pentad, mm: the wettest slot (07-6) is 1553 mm, so
/// 3000 leaves headroom and still catches a ×100 unit error.
pub const RAINFALL_MAX_MM: f64 = 3000.0;
/// Smallest NDVI of an area.
pub const NDVI_MIN: f64 = -0.08;
/// Largest NDVI of an area.
pub const NDVI_MAX: f64 = 0.92;
/// A rainfall national mean may be this many times the slot's measured maximum.
pub const RAINFALL_MEAN_FACTOR: f64 = 3.0;
/// Smallest ceiling of a rainfall national mean, mm.
pub const RAINFALL_MEAN_FLOOR_MM: f64 = 2.0;
/// Half-width of the NDVI national mean's allowed band around the slot range.
pub const NDVI_MEAN_MARGIN: f64 = 0.15;
/// The share of a slot's wettest year under 1 mm that makes an all-zero
/// period a dry season rather than a broken build.
pub const DRY_SLOT_SHARE: f64 = 0.8;
/// The share of areas that must carry a value, per dataset.
pub const MIN_AREAS_WITH_VALUE_RAINFALL: f64 = 0.95;
/// The share of areas that must carry a value of an NDVI period.
pub const MIN_AREAS_WITH_VALUE_NDVI: f64 = 0.9;

/// Everything the gate decides over.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct BoundsInput<'a> {
    /// Dataset id.
    pub dataset: &'a str,
    /// The staged build.
    pub build_id: &'a str,
    /// Number of areas of the build (`index.json` `areas`).
    pub areas: usize,
    /// The staged `series.json`.
    pub series: &'a Value,
    /// The staged `index.json`.
    pub index: &'a Value,
    /// The values of the new period, one per area.
    pub values: &'a [f64],
    /// The committed slot table, or `None` when it is missing.
    pub slots: Option<&'a SlotTable>,
    /// The published pointer, `None` on a first publish.
    pub pointer: Option<&'a Pointer>,
    /// Boundary release and tiles revision this run builds.
    pub boundaries: (&'a str, u8),
    /// The staged `current.json`.
    pub current: &'a Value,
}

/// The share of areas that must carry a value of `dataset`.
#[must_use]
pub fn min_areas_with_value(dataset: &str) -> f64 {
    if dataset == "rainfall" {
        MIN_AREAS_WITH_VALUE_RAINFALL
    } else if dataset == "ndvi" {
        MIN_AREAS_WITH_VALUE_NDVI
    } else {
        0.9
    }
}

/// The text of a JSON string field, or `""`.
fn text(value: &Value, key: &str) -> String {
    value
        .get(key)
        .and_then(Value::as_str)
        .unwrap_or_default()
        .to_owned()
}

/// What is wrong with a build's latest period, one line each; empty is good.
///
/// # Errors
///
/// Fails when the period end of the index is not a date the slot key can read.
pub fn bounds_failures(input: &BoundsInput<'_>) -> Result<Vec<String>> {
    let mut failures: Vec<String> = Vec::new();
    let periods = input
        .series
        .get("periods")
        .and_then(Value::as_array)
        .map(Vec::as_slice)
        .unwrap_or_default();
    let Some(latest) = periods.last() else {
        return Ok(vec!["the staged series.json lists no period".to_owned()]);
    };
    let named = text(input.index, "build_id");
    if named != input.build_id {
        failures.push(format!(
            "index.json names build {}, not {}",
            if named.is_empty() { "none" } else { &named },
            input.build_id
        ));
    }
    let latest_end = text(latest, "period_end");
    let index_end = text(input.index, "period_end");
    let end = if index_end.is_empty() {
        latest_end.clone()
    } else {
        index_end
    };
    if latest_end != end {
        failures.push(format!(
            "the latest series period ends {latest_end}, index.json {end}"
        ));
    }
    if let Some(pointer) = input.pointer
        && end < pointer.period_end
    {
        failures.push(format!(
            "the new period {end} is before the published {}",
            pointer.period_end
        ));
    }
    let share = min_areas_with_value(input.dataset);
    #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
    let floor = (input.areas as f64 * share).floor() as usize;
    if input.values.len() < floor {
        failures.push(format!(
            "only {} of {} areas carry a value of the new period (floor {floor})",
            input.values.len(),
            input.areas
        ));
    }
    if input.values.is_empty() {
        return Ok(failures);
    }
    let min = input.values.iter().copied().fold(f64::INFINITY, f64::min);
    let max = input
        .values
        .iter()
        .copied()
        .fold(f64::NEG_INFINITY, f64::max);
    let mean = input.values.iter().sum::<f64>() / input.values.len() as f64;
    let first = input.values[0];
    let all_same = input.values.iter().all(|value| *value == first);
    let slot = slot_key(&end, input.dataset)?;
    let history = input.slots.and_then(|table| table.slots.get(&slot));
    if history.is_none() {
        failures.push(format!(
            "no historical slot {slot} in {}-slots.json (the gate cannot judge the period)",
            input.dataset
        ));
    }
    if input.dataset == "rainfall" {
        if min < 0.0 {
            failures.push(format!("rainfall min {min} is below 0"));
        }
        if max > RAINFALL_MAX_MM {
            failures.push(format!(
                "rainfall max {max} is above {RAINFALL_MAX_MM} mm in a pentad"
            ));
        }
        if all_same && first != 0.0 {
            failures.push(format!("every area has the same rainfall ({first} mm)"));
        }
        if all_same && first == 0.0 {
            let wettest = history
                .and_then(|history| history.min_share_under_1mm)
                .unwrap_or(0.0);
            if wettest < DRY_SLOT_SHARE {
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                let percent = (wettest * 100.0).round() as i64;
                failures.push(format!(
                    "all {} areas are 0 mm in slot {slot}, whose wettest 1991-2020 year still \
                     had only {percent}% of areas under 1 mm",
                    input.values.len()
                ));
            }
        }
        if let Some(history) = history {
            let ceiling = RAINFALL_MEAN_FLOOR_MM.max(RAINFALL_MEAN_FACTOR * history.mean_max);
            if mean > ceiling {
                failures.push(format!(
                    "the national mean {mean:.2} mm is above {ceiling:.2} mm ({} x the slot's \
                     1991-2020 maximum {:.2} mm)",
                    RAINFALL_MEAN_FACTOR, history.mean_max
                ));
            }
        }
    } else if input.dataset == "ndvi" {
        if min < NDVI_MIN {
            failures.push(format!("ndvi min {min} is below {NDVI_MIN}"));
        }
        if max > NDVI_MAX {
            failures.push(format!("ndvi max {max} is above {NDVI_MAX}"));
        }
        if all_same {
            failures.push(format!("every area has the same NDVI ({first})"));
        }
        if let Some(history) = history {
            if mean < history.mean_min - NDVI_MEAN_MARGIN {
                failures.push(format!(
                    "the national mean NDVI {mean:.3} is below {:.3} (the slot's 2019-2025 \
                     minimum {:.3} - {NDVI_MEAN_MARGIN})",
                    history.mean_min - NDVI_MEAN_MARGIN,
                    history.mean_min
                ));
            }
            if mean > history.mean_max + NDVI_MEAN_MARGIN {
                failures.push(format!(
                    "the national mean NDVI {mean:.3} is above {:.3} (the slot's 2019-2025 \
                     maximum {:.3} + {NDVI_MEAN_MARGIN})",
                    history.mean_max + NDVI_MEAN_MARGIN,
                    history.mean_max
                ));
            }
        }
    }
    let release = text(input.current, "boundary_release");
    let release = if release.is_empty() {
        None
    } else {
        Some(release)
    };
    if release.as_deref() != Some(input.boundaries.0) {
        failures.push(format!(
            "the stage names boundary release {}, this run builds {}",
            release.as_deref().unwrap_or("none"),
            input.boundaries.0
        ));
    }
    let revision = input
        .current
        .get("boundary_tiles_revision")
        .and_then(Value::as_u64)
        .and_then(|value| u8::try_from(value).ok());
    if revision != Some(input.boundaries.1) {
        failures.push(format!(
            "the stage names boundary tiles revision {}, this run builds {}",
            revision.map_or_else(|| "none".to_owned(), |value| value.to_string()),
            input.boundaries.1
        ));
    }
    Ok(failures)
}

/// The values of the new period from a `numbers.csv`.
///
/// # Errors
///
/// Fails when the CSV has no header or lacks a column the gate needs.
pub fn period_values(csv: &str, period_end: &str) -> Result<Vec<f64>> {
    let mut rows = crate::normals::parse_csv(csv)?;
    if rows.is_empty() {
        bail!("numbers.csv is empty");
    }
    let header = rows.remove(0);
    let column = |name: &str| header.iter().position(|cell| cell.as_str() == name);
    let (Some(end_at), Some(value_at)) = (column("period_end"), column("value")) else {
        bail!("numbers.csv needs area_id, period_end and value");
    };
    let mut values = Vec::new();
    for row in rows {
        if row.get(end_at).map(String::as_str) != Some(period_end) {
            continue;
        }
        let value = row.get(value_at).map_or("", String::as_str);
        if value.is_empty() {
            continue;
        }
        if let Ok(number) = value.parse::<f64>()
            && number.is_finite()
        {
            values.push(number);
        }
    }
    Ok(values)
}

/// The published pointer of `s`, `None` when the bucket has none.
///
/// # Errors
///
/// Fails when the bucket cannot be read or the pointer lacks its fields.
pub fn published_pointer(s: &crate::layout::Settings) -> Result<Option<Pointer>> {
    let s3 = connect(None)?;
    let key = current_key(s);
    if s3.head(&key)?.is_none() {
        return Ok(None);
    }
    let bytes = s3.get(&key)?;
    let text = String::from_utf8(bytes).with_context(|| format!("{key} is not UTF-8"))?;
    if text.trim().is_empty() {
        return Ok(None);
    }
    let value: Value = serde_json::from_str(&text).with_context(|| {
        format!("the pointer {key} has no build_id or period_end: fix it by hand")
    })?;
    let pointer = parse_pointer(&value).with_context(|| {
        format!("the pointer {key} has no build_id or period_end: fix it by hand")
    })?;
    Ok(Some(pointer))
}

/// Run `geolith dataset bounds`.
///
/// # Errors
///
/// Fails with exit code `1` when the build fails a check, naming each failure.
pub fn run(args: &BoundsArgs) -> Result<()> {
    let s = settings(args.dataset.as_deref(), args.country.as_deref())?;
    let stage = s.stage_root.join(&args.build);
    let prefix = build_prefix(&s, &args.build);
    let dir = stage.join(&prefix);
    let read = |name: &str| -> Result<Value> {
        let path = dir.join(name);
        read_json(&path).with_context(|| format!("reading {}", path.display()))
    };
    let series = read("series.json")?;
    let index = read("index.json")?;
    let current_path = stage.join(current_key(&s));
    let current =
        read_json(&current_path).with_context(|| format!("reading {}", current_path.display()))?;
    let numbers_path = dir.join("numbers.csv");
    let numbers = fs::read_to_string(&numbers_path)
        .with_context(|| format!("reading {}", numbers_path.display()))?;
    let end = text(&index, "period_end");
    let values = period_values(&numbers, &end)?;
    let slots_path = slot_table_path(&s.repo, &s.dataset, &s.cc);
    if !slots_path.is_file() {
        bail!(
            "no {} in {}: the bounds gate needs the measured slot history of {} \
             (geolith dataset slots)",
            slots_path
                .file_name()
                .and_then(|name| name.to_str())
                .unwrap_or_default(),
            slots_path
                .parent()
                .map(|path| path.to_string_lossy().into_owned())
                .unwrap_or_default(),
            s.cc
        );
    }
    let slots = crate::slots::read_slots(&slots_path)?;
    let pointer = published_pointer(&s)?;
    let areas = index
        .get("areas")
        .and_then(Value::as_array)
        .map_or(0, Vec::len);
    let failures = bounds_failures(&BoundsInput {
        dataset: &s.dataset,
        build_id: &args.build,
        areas,
        series: &series,
        index: &index,
        values: &values,
        slots: Some(&slots),
        pointer: pointer.as_ref(),
        boundaries: (&s.boundary_release, s.boundary_tiles_revision),
        current: &current,
    })?;
    for failure in &failures {
        eprintln!("bounds: {failure}");
    }
    if !failures.is_empty() {
        bail!("{} fails {} bounds checks", args.build, failures.len());
    }
    println!("bounds: {} passes", args.build);
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::slots::{SlotHistory, SlotTable};
    use std::collections::BTreeMap;

    fn history(mean_min: f64, mean_max: f64, wettest: Option<f64>) -> SlotHistory {
        SlotHistory {
            years: 30,
            mean_min,
            mean_median: (mean_min + mean_max) / 2.0,
            mean_max,
            median_min: mean_min,
            median_max: mean_max,
            min_share_under_1mm: wettest,
            max_share_under_1mm: wettest,
            max_area_mm: Some(200.0),
            yearly_means: vec![mean_min, mean_max],
        }
    }

    fn table(dataset: &str, slot: &str, history: SlotHistory) -> SlotTable {
        SlotTable {
            dataset: dataset.to_owned(),
            unit: "mm".to_owned(),
            slots: BTreeMap::from([(slot.to_owned(), history)]),
            source: "test".to_owned(),
        }
    }

    /// A build whose series, index and pointer agree, over `values`.
    fn input<'a>(
        dataset: &'a str,
        values: &'a [f64],
        slots: &'a SlotTable,
        series: &'a Value,
        index: &'a Value,
        current: &'a Value,
    ) -> BoundsInput<'a> {
        BoundsInput {
            dataset,
            build_id: "2026-11-20.20261120T0000Z",
            areas: 4,
            series,
            index,
            values,
            slots: Some(slots),
            pointer: None,
            boundaries: ("2026-10-21.0", 1),
            current,
        }
    }

    fn fixtures() -> (Value, Value, Value) {
        let series = serde_json::json!({"periods":[
            {"period_end":"2026-11-10"},
            {"period_end":"2026-11-15"}
        ]});
        let index = serde_json::json!({
            "build_id":"2026-11-20.20261120T0000Z",
            "period_end":"2026-11-15"
        });
        let current = serde_json::json!({
            "boundary_release":"2026-10-21.0",
            "boundary_tiles_revision":1
        });
        (series, index, current)
    }

    #[test]
    fn a_real_dry_season_passes() {
        // Slot 01-1's wettest year had 95% of areas under 1 mm: an all-zero
        // period really is that dry season, so the gate accepts it.
        let slots = table("rainfall", "11-3", history(0.0, 3.0, Some(0.95)));
        let (series, index, current) = fixtures();
        let values = [0.0, 0.0, 0.0, 0.0];
        let failures = bounds_failures(&input(
            "rainfall", &values, &slots, &series, &index, &current,
        ))
        .expect("bounds");
        assert!(failures.is_empty(), "{failures:?}");
    }

    #[test]
    fn all_zeros_in_a_monsoon_slot_fails() {
        // The wettest year of a monsoon slot still had only 25% under 1 mm.
        let slots = table("rainfall", "07-2", history(20.0, 60.0, Some(0.25)));
        let series = serde_json::json!({"periods":[{"period_end":"2026-07-10"}]});
        let index = serde_json::json!({
            "build_id":"2026-11-20.20261120T0000Z",
            "period_end":"2026-07-10"
        });
        let current = serde_json::json!({
            "boundary_release":"2026-10-21.0",
            "boundary_tiles_revision":1
        });
        let values = [0.0, 0.0, 0.0, 0.0];
        let failures = bounds_failures(&input(
            "rainfall", &values, &slots, &series, &index, &current,
        ))
        .expect("bounds");
        assert!(
            failures
                .iter()
                .any(|failure| failure.contains("whose wettest 1991-2020 year still had only 25%")),
            "{failures:?}"
        );
    }

    #[test]
    fn values_a_hundred_times_too_large_fail_the_ceiling() {
        // A ×100 unit error on a 2 mm slot: the mean 250 mm is above
        // max(2, 3 × 3 mm) = 9 mm.
        let slots = table("rainfall", "11-3", history(1.0, 3.0, Some(0.5)));
        let (series, index, current) = fixtures();
        let values = [250.0, 250.0, 250.0, 250.0];
        let failures = bounds_failures(&input(
            "rainfall", &values, &slots, &series, &index, &current,
        ))
        .expect("bounds");
        assert!(
            failures
                .iter()
                .any(|failure| failure.contains("is above 9.00 mm")),
            "{failures:?}"
        );
        assert!(
            failures
                .iter()
                .any(|failure| failure.contains("same rainfall")),
            "{failures:?}"
        );
    }

    #[test]
    fn half_the_areas_missing_fails_the_floor() {
        let slots = table("rainfall", "11-3", history(1.0, 3.0, Some(0.5)));
        let (series, index, current) = fixtures();
        let values = [1.0, 2.0];
        let failures = bounds_failures(&input(
            "rainfall", &values, &slots, &series, &index, &current,
        ))
        .expect("bounds");
        assert!(
            failures
                .iter()
                .any(|failure| failure.contains("only 2 of 4 areas carry a value")),
            "{failures:?}"
        );
    }

    #[test]
    fn a_slot_without_history_fails_the_gate() {
        let slots = table("rainfall", "11-1", history(1.0, 3.0, Some(0.5)));
        let (series, index, current) = fixtures();
        let values = [1.0, 2.0, 1.5, 2.5];
        let failures = bounds_failures(&input(
            "rainfall", &values, &slots, &series, &index, &current,
        ))
        .expect("bounds");
        assert!(
            failures
                .iter()
                .any(|failure| failure.contains("no historical slot 11-3")),
            "{failures:?}"
        );
    }

    #[test]
    fn ndvi_outside_its_physical_range_fails() {
        let slots = table("ndvi", "11-3", history(0.4, 0.6, None));
        let (series, index, current) = fixtures();
        let values = [0.95, 0.5, 0.45, 0.55];
        let failures = bounds_failures(&input("ndvi", &values, &slots, &series, &index, &current))
            .expect("bounds");
        assert!(
            failures
                .iter()
                .any(|failure| failure.contains("ndvi max 0.95 is above 0.92")),
            "{failures:?}"
        );
    }

    #[test]
    fn a_stage_of_another_boundary_release_fails() {
        let slots = table("rainfall", "11-3", history(1.0, 3.0, Some(0.5)));
        let (series, index, _) = fixtures();
        let current = serde_json::json!({
            "boundary_release":"2026-06-17.0",
            "boundary_tiles_revision":2
        });
        let values = [1.0, 2.0, 1.5, 2.5];
        let failures = bounds_failures(&input(
            "rainfall", &values, &slots, &series, &index, &current,
        ))
        .expect("bounds");
        assert!(
            failures
                .iter()
                .any(|failure| failure.contains("names boundary release 2026-06-17.0")),
            "{failures:?}"
        );
        assert!(
            failures
                .iter()
                .any(|failure| failure.contains("boundary tiles revision 2")),
            "{failures:?}"
        );
    }

    #[test]
    fn a_period_before_the_published_one_fails() {
        let slots = table("rainfall", "11-3", history(1.0, 3.0, Some(0.5)));
        let (series, index, current) = fixtures();
        let values = [1.0, 2.0, 1.5, 2.5];
        let pointer = Pointer {
            build_id: "2026-12-20.20261220T0000Z".to_owned(),
            period_end: "2026-12-15".to_owned(),
        };
        let mut input = input("rainfall", &values, &slots, &series, &index, &current);
        input.pointer = Some(&pointer);
        let failures = bounds_failures(&input).expect("bounds");
        assert!(
            failures
                .iter()
                .any(|failure| failure.contains("is before the published 2026-12-15")),
            "{failures:?}"
        );
    }

    #[test]
    fn the_new_periods_values_come_from_its_own_rows_only() {
        let csv = "area_id,period_end,value\na,2026-11-10,1\nb,2026-11-15,2\nc,2026-11-15,\n\
                   d,2026-11-15,3\n";
        assert_eq!(
            period_values(csv, "2026-11-15").expect("values"),
            vec![2.0, 3.0]
        );
    }
}