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
//! Per-district numbers of one period.
//!
//! Each area's value is the mean of its valid cells weighted by
//! `fraction × spherical cell area` ([`cell_weights`]). Nodata cells lower
//! `coverage_pct`, never the value. An area with no valid cell takes the
//! nearest valid cell within [`FALLBACK_REACH`] cells of its centroid.

use std::path::Path;

use crate::error::{DatasetError, Result, WithinExt as _};
use geo::Centroid as _;
use rayon::prelude::*;
use serde::{Deserialize, Serialize};

use crate::areas::Area;
use crate::config::DatasetConfig;
use crate::coverage::{CellWeight, Grid, cell_weights, has_finite_vertices};
use crate::source::{Raster, ReadStats, area_values_windowed};
use geolith::terrain::dem::Dem;

/// Smallest fraction at which a cell counts as contributing (in `cells` and for
/// the fallback decision).
///
/// The exact clip can emit float slivers (about 1e-16) for cells that only
/// touch the boundary; they still weigh in.
pub const MIN_CONTRIBUTING_FRACTION: f64 = 1e-9;

/// How many cells from the centroid's cell the nearest-valid fallback looks.
pub const FALLBACK_REACH: i64 = 2;

/// The cells of one area, computed once per grid.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AreaCoverage {
    /// `id` of the [`Area`].
    pub area_id: String,
    /// Centroid of the area, lon/lat (NaN for an empty shape).
    pub centroid: (f64, f64),
    /// Every cell with part of the area in it, sorted by `(row, col)`.
    pub cells: Vec<CellWeight>,
}

/// The cells of every area on one grid, reused for every raster on it.
#[derive(Debug, Clone, PartialEq)]
pub struct CoverageTable {
    /// The grid every raster must match.
    pub grid: Grid,
    /// One entry per area, in the order of the input areas.
    pub areas: Vec<AreaCoverage>,
}

impl CoverageTable {
    /// Cell weights of every area on `grid`, computed in parallel. An area
    /// with a NaN or infinite vertex gets no cells (so no value) and a
    /// warning naming it.
    #[must_use]
    pub fn build(areas: &[Area], grid: Grid) -> Self {
        let areas = areas
            .par_iter()
            .inspect(|area| {
                if !has_finite_vertices(&area.shape) {
                    tracing::warn!(area = %area.id, "a vertex is NaN or infinite: the area gets no cells");
                }
            })
            .map(|area| AreaCoverage {
                area_id: area.id.clone(),
                centroid: area
                    .shape
                    .centroid()
                    .map_or((f64::NAN, f64::NAN), |c| (c.x(), c.y())),
                cells: cell_weights(&area.shape, &grid),
            })
            .collect();
        Self { grid, areas }
    }
}

/// The number of one area for one raster.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AreaValue {
    /// `id` of the [`Area`].
    pub area_id: String,
    /// Weighted mean of the valid cells; `None` when no valid cell is near.
    pub value: Option<f64>,
    /// Share of the area's weight on valid cells, in percent.
    pub coverage_pct: f64,
    /// Valid cells with a fraction of at least [`MIN_CONTRIBUTING_FRACTION`].
    pub cells: u32,
    /// Valid weight below the full area of one cell on the centroid's row.
    pub sparse: bool,
    /// The value comes from the nearest valid cell outside the area.
    pub fallback: bool,
    /// Centre `[lon, lat]` of that nearest valid cell when `fallback`.
    pub fallback_cell: Option<[f64; 2]>,
}

/// The number of every area of `table` for `raster` read from `source`:
/// a whole raster in memory, a windowed one with one window per area on
/// `rayon::current_num_threads()` readers.
///
/// # Errors
///
/// Fails, naming `source`, when the raster is not EPSG:4326, its grid
/// differs from `table.grid` or a window cannot be read.
pub fn area_values(
    table: &CoverageTable,
    raster: &Raster,
    config: &DatasetConfig,
    source: &Path,
) -> Result<Vec<AreaValue>> {
    area_values_read(table, raster, config, source).map(|(values, _)| values)
}

/// [`area_values`] with what it read: no window for a whole raster.
///
/// # Errors
///
/// As [`area_values`].
pub fn area_values_read(
    table: &CoverageTable,
    raster: &Raster,
    config: &DatasetConfig,
    source: &Path,
) -> Result<(Vec<AreaValue>, ReadStats)> {
    match raster {
        Raster::Whole(dem) => {
            whole_area_values(table, dem, config, source).map(|v| (v, ReadStats::default()))
        }
        Raster::Windowed(windowed) => {
            area_values_windowed(table, windowed, config, rayon::current_num_threads())
        }
    }
}

/// [`area_values`] of a raster decoded whole.
fn whole_area_values(
    table: &CoverageTable,
    dem: &Dem,
    config: &DatasetConfig,
    source: &Path,
) -> Result<Vec<AreaValue>> {
    let grid = Grid::from_dem(dem).within(source.display().to_string())?;
    if !grid.matches(&table.grid) {
        return Err(DatasetError::data(format!(
            "{}: raster grid differs from the first raster",
            source.display()
        )));
    }
    let decoded = |col: i64, row: i64| dem.value_at(col, row).and_then(|raw| config.decode(raw));
    Ok(table
        .areas
        .par_iter()
        .map(|area| area_value(area, &table.grid, &decoded))
        .collect())
}

/// The number of one area, with `decoded(col, row)` giving the decoded value
/// of a cell (`None` for an invalid cell or one outside the raster).
pub(crate) fn area_value(
    area: &AreaCoverage,
    grid: &Grid,
    decoded: &(impl Fn(i64, i64) -> Option<f64> + Sync),
) -> AreaValue {
    let (mut total, mut valid, mut weighted, mut cells) = (0.0, 0.0, 0.0, 0_u32);
    for cell in &area.cells {
        let w = cell.fraction * cell.area_m2;
        total += w;
        if let Some(v) = decoded(i64::from(cell.col), i64::from(cell.row)) {
            valid += w;
            weighted += w * v;
            if cell.fraction >= MIN_CONTRIBUTING_FRACTION {
                cells += 1;
            }
        }
    }
    // Divide first: `valid / total` is exactly 1 when every cell is valid,
    // while `100 * valid / total` can round to 99.99999999999999.
    let coverage_pct = if total > 0.0 {
        valid / total * 100.0
    } else {
        0.0
    };
    let centroid_cell = centroid_cell(area.centroid, grid);
    if cells == 0 {
        let nearest = centroid_cell.and_then(|c| nearest_valid(area.centroid, c, grid, decoded));
        return AreaValue {
            area_id: area.area_id.clone(),
            value: nearest.map(|(v, _)| v),
            coverage_pct,
            cells: u32::from(nearest.is_some()),
            sparse: true,
            fallback: nearest.is_some(),
            fallback_cell: nearest.map(|(_, centre)| centre),
        };
    }
    let row = centroid_cell.map_or(0, |(_, row)| row.clamp(0, i64::from(grid.height) - 1));
    let one_cell = grid.cell_area_m2(u32::try_from(row).unwrap_or(0));
    AreaValue {
        area_id: area.area_id.clone(),
        value: Some(weighted / valid),
        coverage_pct,
        cells,
        sparse: valid < one_cell,
        fallback: false,
        fallback_cell: None,
    }
}

/// The `(col, row)` holding `centroid`, unclamped; `None` when it is not
/// finite.
pub(crate) fn centroid_cell((lon, lat): (f64, f64), grid: &Grid) -> Option<(i64, i64)> {
    let (x, y) = grid.transform.to_pixel(lon, lat);
    let (col, row) = ((x + 0.5).floor(), (y + 0.5).floor());
    (col.is_finite() && row.is_finite()).then_some((col as i64, row as i64))
}

/// Value and centre `[lon, lat]` of the valid cell whose centre is nearest
/// `centroid`, among the cells at most [`FALLBACK_REACH`] columns and rows
/// from `(col, row)`. Ties go to the smaller `(row, col)`.
fn nearest_valid(
    centroid: (f64, f64),
    (col, row): (i64, i64),
    grid: &Grid,
    decoded: &impl Fn(i64, i64) -> Option<f64>,
) -> Option<(f64, [f64; 2])> {
    let mut best: Option<(f64, f64, [f64; 2])> = None;
    for r in row - FALLBACK_REACH..=row + FALLBACK_REACH {
        for c in col - FALLBACK_REACH..=col + FALLBACK_REACH {
            let Some(v) = decoded(c, r) else { continue };
            let (x, y) = grid.transform.pixel_center(c as f64, r as f64);
            let d = (x - centroid.0).hypot(y - centroid.1);
            if best.is_none_or(|(bd, _, _)| d < bd) {
                best = Some((d, v, [x, y]));
            }
        }
    }
    best.map(|(_, v, centre)| (v, centre))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::areas::Area;
    use crate::config::DatasetConfig;
    use crate::coverage::{Grid, cell_weights};
    use geo::{MultiPolygon, Polygon, polygon};
    use geolith::terrain::crs::Crs;
    use geolith::terrain::dem::{Dem, GeoTransform};
    use std::path::Path;

    const NODATA: f32 = -9999.0;

    fn transform(origin_x: f64, origin_y: f64) -> GeoTransform {
        GeoTransform {
            origin_x,
            origin_y,
            pixel_width: 0.05,
            pixel_height: 0.05,
        }
    }

    fn grid_at(origin_x: f64, origin_y: f64) -> Grid {
        Grid {
            width: 20,
            height: 20,
            transform: transform(origin_x, origin_y),
        }
    }

    fn grid() -> Grid {
        grid_at(0.0, 1.0)
    }

    /// A 20 × 20 raster on `grid_at(origin_x, origin_y)` filled with `fill`.
    fn dem_at(origin_x: f64, origin_y: f64, fill: f32) -> Dem {
        Dem {
            width: 20,
            height: 20,
            values: vec![fill; 400],
            transform: transform(origin_x, origin_y),
            crs: Crs::Wgs84,
        }
    }

    fn dem(fill: f32) -> Dem {
        dem_at(0.0, 1.0, fill)
    }

    fn set(dem: &mut Dem, col: usize, row: usize, value: f32) {
        dem.values[row * 20 + col] = value;
    }

    fn config() -> DatasetConfig {
        DatasetConfig::from_json_str(
            r##"{"id": "t", "name": "T", "unit": "mm", "period": "pentad",
                "scale": 1.0, "offset": 0.0, "valid_min": 0.0, "valid_max": 5000.0,
                "nodata": -9999.0, "crs_epsg": 4326, "file_template": "t.{year}.{month}.{pentad}.tif",
                "max_zoom": 6, "tile_size": 256, "season_start": "06-01",
                "stale_after_days": 18, "attribution": "a", "source_url": "https://example.org",
                "licence": "CC BY 4.0",
                "ramp": [{"value": 0.0, "color": "#ffffd9"},
                         {"value": 5.0, "color": "#0c2c84"}]}"##,
        )
        .expect("test config is valid")
    }

    fn rect(x0: f64, y0: f64, x1: f64, y1: f64) -> Polygon<f64> {
        polygon![(x: x0, y: y0), (x: x1, y: y0), (x: x1, y: y1), (x: x0, y: y1), (x: x0, y: y0)]
    }

    fn area(id: &str, parts: Vec<Polygon<f64>>) -> Area {
        Area {
            code: None,
            id: id.to_owned(),
            name: id.to_owned(),
            country: "IN".to_owned(),
            level: "county".to_owned(),
            parent_id: None,
            parent_name: None,
            region_code: None,
            shape: MultiPolygon::new(parts),
        }
    }

    /// The value of the one area `id` over `dem`.
    fn value_of(areas: &[Area], grid: Grid, dem: &Dem, id: &str) -> AreaValue {
        let table = CoverageTable::build(areas, grid);
        area_values(
            &table,
            &Raster::Whole(dem.clone()),
            &config(),
            Path::new("x.tif"),
        )
        .expect("grids match")
        .into_iter()
        .find(|v| v.area_id == id)
        .expect("the area has a value")
    }

    #[test]
    fn a_fully_valid_area_has_exactly_full_coverage() {
        // Real run: 50 inland districts came out at 99.99999999999999, which
        // made them look partly covered (and coastal) to every consumer.
        let dem = dem(7.5);
        for i in 0..200_u32 {
            let d = f64::from(i) * 0.0037;
            let shape = rect(0.011 + d, 0.013 + d, 0.317 + d, 0.291 + 0.7 * d);
            let v = value_of(&[area("a", vec![shape])], grid(), &dem, "a");
            assert_eq!(v.coverage_pct, 100.0, "rect {i}");
        }
    }

    #[test]
    fn a_constant_raster_gives_its_constant() {
        let shape = polygon![
            (x: 0.013, y: 0.31), (x: 0.71, y: 0.42), (x: 0.52, y: 0.66),
            (x: 0.2, y: 0.97), (x: 0.08, y: 0.55)
        ];
        let v = value_of(&[area("a", vec![shape])], grid(), &dem(7.5), "a");
        let value = v.value.expect("a value");
        assert!((value - 7.5).abs() < 1e-12, "{value}");
        assert!((v.coverage_pct - 100.0).abs() < 1e-12, "{}", v.coverage_pct);
        assert!(!v.fallback);
    }

    #[test]
    fn values_are_weighted_by_fraction() {
        let mut d = dem(0.0);
        set(&mut d, 0, 0, 10.0);
        set(&mut d, 1, 0, 30.0);
        let v = value_of(
            &[area("a", vec![rect(0.0, 0.95, 0.0625, 1.0)])],
            grid(),
            &d,
            "a",
        );
        let value = v.value.expect("a value");
        assert!((value - 14.0).abs() < 1e-9, "{value}");
        assert_eq!(v.cells, 2);
    }

    #[test]
    fn rows_are_weighted_by_cell_area() {
        let mut d = dem_at(0.0, 60.0, 0.0);
        set(&mut d, 0, 1, 100.0);
        // Row 0 spans 60.00..59.95 N, row 1 spans 59.95..59.90 N.
        let r2 = 6_371_008.8_f64 * 6_371_008.8;
        let width = 0.05_f64.to_radians();
        let a0 = r2 * width * (60.0_f64.to_radians().sin() - 59.95_f64.to_radians().sin());
        let a1 = r2 * width * (59.95_f64.to_radians().sin() - 59.9_f64.to_radians().sin());
        let expected = 100.0 * a1 / (a0 + a1);
        let v = value_of(
            &[area("a", vec![rect(0.0, 59.9, 0.05, 60.0)])],
            grid_at(0.0, 60.0),
            &d,
            "a",
        );
        let value = v.value.expect("a value");
        assert!((value - expected).abs() < 1e-9, "{value} vs {expected}");
        // The weighting is not the plain mean of the two rows.
        assert!((value - 50.0).abs() > 0.01, "{value}");
    }

    #[test]
    fn nodata_cells_lower_coverage_not_the_value() {
        let mut d = dem(0.0);
        set(&mut d, 0, 0, 4.0);
        set(&mut d, 1, 0, NODATA);
        let v = value_of(
            &[area("a", vec![rect(0.0, 0.95, 0.1, 1.0)])],
            grid(),
            &d,
            "a",
        );
        let value = v.value.expect("a value");
        assert!((value - 4.0).abs() < 1e-12, "{value}");
        assert!((v.coverage_pct - 50.0).abs() < 1e-9, "{}", v.coverage_pct);
        assert_eq!(v.cells, 1);
    }

    #[test]
    fn a_multipart_area_combines_its_parts() {
        let mut d = dem(0.0);
        set(&mut d, 0, 0, 2.0);
        set(&mut d, 5, 0, 6.0);
        let parts = vec![rect(0.0, 0.95, 0.05, 1.0), rect(0.25, 0.95, 0.3, 1.0)];
        let v = value_of(&[area("a", parts)], grid(), &d, "a");
        let value = v.value.expect("a value");
        assert!((value - 4.0).abs() < 1e-12, "{value}");
        assert_eq!(v.cells, 2);
    }

    #[test]
    fn a_tiny_area_is_sparse_but_has_a_cell() {
        let mut d = dem(1.0);
        set(&mut d, 2, 3, 5.5);
        let v = value_of(
            &[area("a", vec![rect(0.12, 0.82, 0.13, 0.83)])],
            grid(),
            &d,
            "a",
        );
        assert_eq!(v.cells, 1);
        assert!(v.sparse);
        assert!(!v.fallback);
        let value = v.value.expect("a value");
        assert!((value - 5.5).abs() < 1e-12, "{value}");
    }

    #[test]
    fn an_all_nodata_area_falls_back_to_the_nearest_valid_cell() {
        let mut d = dem(NODATA);
        set(&mut d, 3, 3, 3.0);
        let v = value_of(
            &[area("a", vec![rect(0.11, 0.81, 0.14, 0.84)])],
            grid(),
            &d,
            "a",
        );
        assert_eq!(v.value, Some(3.0));
        assert!(v.fallback);
        assert!(v.sparse);
        assert_eq!(v.cells, 1);
    }

    #[test]
    fn the_fallback_looks_no_further_than_two_cells() {
        let mut d = dem(NODATA);
        // Cell (2, 3) holds the area; (5, 3) is three cells east.
        set(&mut d, 5, 3, 3.0);
        let v = value_of(
            &[area("a", vec![rect(0.11, 0.81, 0.14, 0.84)])],
            grid(),
            &d,
            "a",
        );
        assert_eq!(v.value, None);
        assert_eq!(v.cells, 0);
        assert!(v.sparse);
    }

    #[test]
    fn an_area_with_a_nan_vertex_has_no_value_and_spares_the_others() {
        // A finite square plus a part with a NaN vertex.
        let broken = polygon![
            (x: 0.1, y: 0.8), (x: f64::NAN, y: 0.8), (x: 0.2, y: 0.9), (x: 0.1, y: 0.8)
        ];
        let areas = [
            area("bad", vec![rect(0.1, 0.7, 0.2, 0.8), broken]),
            area("good", vec![rect(0.5, 0.5, 0.6, 0.6)]),
        ];
        let d = dem(4.0);
        let bad = value_of(&areas, grid(), &d, "bad");
        assert_eq!(bad.value, None);
        assert_eq!(bad.cells, 0);
        let good = value_of(&areas, grid(), &d, "good");
        assert_eq!(good.value, Some(4.0));
    }

    #[test]
    fn a_raster_on_another_grid_is_an_error_naming_the_file() {
        let table = CoverageTable::build(&[area("a", vec![rect(0.0, 0.95, 0.05, 1.0)])], grid());
        let err = area_values(
            &table,
            &Raster::Whole(dem_at(0.05, 1.0, 1.0)),
            &config(),
            Path::new("/rasters/x.tif"),
        )
        .expect_err("the grids differ");
        let text = geolith::error::report(&err);
        assert!(text.contains("x.tif"), "{text}");
        assert!(text.contains("grid differs"), "{text}");
    }

    #[test]
    fn a_sliver_touch_does_not_count_as_a_cell() {
        // The polygon starts at 0.15 while cell 2 ends at 0.0 + 3 * 0.05 =
        // 0.15000000000000002, so cell 2 gets a float sliver.
        let shape = MultiPolygon::new(vec![rect(0.15, 0.95, 0.25, 1.0)]);
        let weights = cell_weights(&shape, &grid());
        let sliver = weights
            .iter()
            .find(|w| w.col == 2 && w.row == 0)
            .expect("the clip emits a sliver for cell (2, 0)");
        assert!(sliver.fraction < 1e-9, "{sliver:?}");

        let mut d = dem(1.0);
        set(&mut d, 2, 0, 1000.0);
        let v = value_of(&[area("a", shape.0)], grid(), &d, "a");
        assert_eq!(v.cells, 2);
        let value = v.value.expect("a value");
        assert!((value - 1.0).abs() < 1e-9, "{value}");
    }
}