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
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! Fraction of each raster cell inside an area polygon, weighted by cell area.
//!
//! A cell whose rectangle meets the polygon boundary gets the exact fraction
//! `area(cell ∩ shape) / area(cell)` in planar degrees, from an exact
//! cell-rectangle clip; every other cell is
//! wholly in or out, decided by its centre. Cell areas are spherical.

use crate::error::{DatasetError, Result};
use geo::{BoundingRect, Coord, CoordsIter, LineString, MultiPolygon, Rect, coord};
use serde::{Deserialize, Serialize};

use geolith::terrain::cog::Cog;
use geolith::terrain::crs::Crs;
use geolith::terrain::dem::{Dem, GeoTransform};

/// Mean earth radius in metres used for spherical cell areas.
pub const EARTH_RADIUS_M: f64 = 6_371_008.8;

/// Largest shift, as a share of one pixel, of a grid's origin or far edge at
/// which two grids count as equal (prelim and final rasters store 0.05
/// differently).
const GRID_TOLERANCE_PIXELS: f64 = 1e-3;

/// The cell layout of an EPSG:4326 raster.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Grid {
    /// Raster width in cells.
    pub width: u32,
    /// Raster height in cells.
    pub height: u32,
    /// Cell-to-degree affine transform.
    pub transform: GeoTransform,
}

impl Grid {
    /// The grid of `dem`.
    ///
    /// # Errors
    ///
    /// Fails unless the raster is in EPSG:4326.
    pub fn from_dem(dem: &Dem) -> Result<Grid> {
        if !(dem.crs == Crs::Wgs84) {
            return Err(DatasetError::data(
                "area numbers need an EPSG:4326 raster in this version",
            ));
        }
        Ok(Grid {
            width: dem.width,
            height: dem.height,
            transform: dem.transform,
        })
    }

    /// The full-resolution (level 0) grid of `cog`.
    ///
    /// # Errors
    ///
    /// Fails unless the raster is in EPSG:4326 and has a level 0.
    pub fn from_cog(cog: &Cog) -> Result<Grid> {
        if !(cog.crs() == Crs::Wgs84) {
            return Err(DatasetError::data(
                "area numbers need an EPSG:4326 raster in this version",
            ));
        }
        let (width, height) = cog
            .size(0)
            .ok_or_else(|| DatasetError::data("the raster has no level 0"))?;
        let transform = cog
            .geo_transform(0)
            .ok_or_else(|| DatasetError::data("the raster has no level 0"))?;
        Ok(Grid {
            width,
            height,
            transform,
        })
    }

    /// Whether `other` has the same cells: equal size, and on each axis the
    /// origin and the far edge (pixel difference times the larger of width
    /// and height) within 1e-3 of a pixel.
    #[must_use]
    pub fn matches(&self, other: &Grid) -> bool {
        let (a, b) = (&self.transform, &other.transform);
        let cells = f64::from(self.width.max(self.height));
        let axis = |origin_a: f64, origin_b: f64, pixel_a: f64, pixel_b: f64| {
            let limit = GRID_TOLERANCE_PIXELS * pixel_a.abs();
            (origin_a - origin_b).abs() <= limit && (pixel_a - pixel_b).abs() * cells <= limit
        };
        self.width == other.width
            && self.height == other.height
            && axis(a.origin_x, b.origin_x, a.pixel_width, b.pixel_width)
            && axis(a.origin_y, b.origin_y, a.pixel_height, b.pixel_height)
    }

    /// Spherical area in square metres of one cell in `row`.
    #[must_use]
    pub fn cell_area_m2(&self, row: u32) -> f64 {
        let t = &self.transform;
        let top = t.origin_y - f64::from(row) * t.pixel_height;
        let bottom = top - t.pixel_height;
        EARTH_RADIUS_M
            * EARTH_RADIUS_M
            * t.pixel_width.to_radians()
            * (top.to_radians().sin() - bottom.to_radians().sin()).abs()
    }

    /// Degree rectangle of cell `(col, row)`.
    fn cell_rect(&self, col: u32, row: u32) -> Rect<f64> {
        let t = &self.transform;
        let x0 = t.origin_x + f64::from(col) * t.pixel_width;
        let y0 = t.origin_y - f64::from(row) * t.pixel_height;
        Rect::new(
            coord! { x: x0, y: y0 },
            coord! { x: x0 + t.pixel_width, y: y0 - t.pixel_height },
        )
    }
}

/// The share of one cell inside an area.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct CellWeight {
    /// Cell column.
    pub col: u32,
    /// Cell row.
    pub row: u32,
    /// Fraction of the cell inside the area, in `(0, 1]`.
    pub fraction: f64,
    /// Spherical area of the whole cell in square metres.
    pub area_m2: f64,
}

/// Half-open cell index range `[start, end)` covering `lo..hi` along one axis
/// whose cells start at `origin` and step by `step`, clamped to `0..len`.
fn cell_range(lo: f64, hi: f64, origin: f64, step: f64, len: u32) -> (u32, u32) {
    let clamp = |v: f64| v.clamp(0.0, f64::from(len)) as u32;
    (
        clamp(((lo - origin) / step).floor()),
        clamp(((hi - origin) / step).ceil()),
    )
}

/// Area of `ring ∩ cell`, measured from the cell's lower-left corner.
///
/// Sutherland-Hodgman clips the ring against the four cell edges; for a
/// simple ring and a convex window the clipped ring's shoelace area is the
/// exact intersection area (the degenerate edges it leaves on the window
/// border add nothing). Unlike `BooleanOps`, which snaps to an integer grid
/// (about 1e-9 of a cell), this keeps full `f64` precision.
fn clipped_ring_area(ring: &LineString<f64>, cell: &Rect<f64>) -> f64 {
    let (min, max) = (cell.min(), cell.max());
    let mut points: Vec<Coord<f64>> = ring.0.iter().map(|c| *c - min).collect();
    // A closed ring repeats its first point; the clip treats it as implicit.
    if points.len() > 1 && points.first() == points.last() {
        points.pop();
    }
    let (w, h) = (max.x - min.x, max.y - min.y);
    // (clip on x, edge position, keep the side above the edge)
    let edges = [
        (true, 0.0, true),
        (true, w, false),
        (false, 0.0, true),
        (false, h, false),
    ];
    for (on_x, bound, keep_above) in edges {
        let axis = |c: Coord<f64>| if on_x { c.x } else { c.y };
        if points.is_empty() {
            return 0.0;
        }
        let inside = |c: Coord<f64>| {
            if keep_above {
                axis(c) >= bound
            } else {
                axis(c) <= bound
            }
        };
        let mut out = Vec::with_capacity(points.len() + 4);
        let mut prev = points[points.len() - 1];
        for &cur in &points {
            let (cur_in, prev_in) = (inside(cur), inside(prev));
            if cur_in != prev_in {
                let t = (bound - axis(prev)) / (axis(cur) - axis(prev));
                out.push(prev + (cur - prev) * t);
            }
            if cur_in {
                out.push(cur);
            }
            prev = cur;
        }
        points = out;
    }
    if points.len() < 3 {
        return 0.0;
    }
    let mut twice = 0.0;
    let mut prev = points[points.len() - 1];
    for &cur in &points {
        twice += prev.x * cur.y - cur.x * prev.y;
        prev = cur;
    }
    (twice / 2.0).abs()
}

/// Area of `shape ∩ cell` in planar degrees: each part's exterior minus its
/// holes.
fn clipped_area(shape: &MultiPolygon<f64>, cell: &Rect<f64>) -> f64 {
    shape
        .iter()
        .map(|p| {
            let holes: f64 = p
                .interiors()
                .iter()
                .map(|r| clipped_ring_area(r, cell))
                .sum();
            (clipped_ring_area(p.exterior(), cell) - holes).max(0.0)
        })
        .sum()
}

/// `floor(v)` clamped to `lo..=hi`, as a cell index.
fn clamped_index(v: f64, lo: u32, hi: u32) -> u32 {
    v.floor().clamp(f64::from(lo), f64::from(hi)) as u32
}

/// One ring edge that crosses the centre line of a row.
#[derive(Debug, Clone, Copy)]
struct Crossing {
    /// Smaller x of the edge: a cell centre off the edge's box sees the edge
    /// to its right exactly when the centre is left of this.
    x: f64,
    /// Winding contribution: +1 for an upward edge, −1 for a downward one.
    delta: i32,
    /// Index of the ring in [`Rings`].
    ring: u32,
}

/// The rings of a shape, numbered part by part (exterior, then holes).
struct Rings<'a> {
    /// Every ring with its part index and whether it is the exterior.
    rings: Vec<(&'a LineString<f64>, usize, bool)>,
    /// Index in `rings` of each part's exterior.
    exteriors: Vec<usize>,
}

impl<'a> Rings<'a> {
    fn new(shape: &'a MultiPolygon<f64>) -> Self {
        let mut rings = Vec::with_capacity(shape.iter().map(|p| 1 + p.interiors().len()).sum());
        let mut exteriors = Vec::with_capacity(shape.0.len());
        for (part, p) in shape.iter().enumerate() {
            exteriors.push(rings.len());
            rings.push((p.exterior(), part, true));
            rings.extend(p.interiors().iter().map(|r| (r, part, false)));
        }
        Self { rings, exteriors }
    }
}

/// Winding state of one row's sweep from east to west: the winding number of
/// every ring around the current centre, as `coord_pos_relative_to_ring`
/// counts it, and from that whether `Contains` holds.
struct Sweep<'r, 'a> {
    rings: &'r Rings<'a>,
    winding: Vec<i32>,
    holes_around: Vec<u32>,
    part_inside: Vec<bool>,
    parts_inside: usize,
}

impl<'r, 'a> Sweep<'r, 'a> {
    fn new(rings: &'r Rings<'a>) -> Self {
        Self {
            rings,
            winding: vec![0; rings.rings.len()],
            holes_around: vec![0; rings.exteriors.len()],
            part_inside: vec![false; rings.exteriors.len()],
            parts_inside: 0,
        }
    }

    /// Count `c`, which now lies east of the centre.
    fn apply(&mut self, c: &Crossing) {
        let ring = c.ring as usize;
        let (_, part, exterior) = self.rings.rings[ring];
        let before = self.winding[ring] != 0;
        self.winding[ring] += c.delta;
        let after = self.winding[ring] != 0;
        if before != after && !exterior {
            if after {
                self.holes_around[part] += 1;
            } else {
                self.holes_around[part] -= 1;
            }
        }
        let inside = self.winding[self.rings.exteriors[part]] != 0 && self.holes_around[part] == 0;
        if inside != self.part_inside[part] {
            self.part_inside[part] = inside;
            if inside {
                self.parts_inside += 1;
            } else {
                self.parts_inside -= 1;
            }
        }
    }

    /// Back to no ring around the centre, touching only `crossings`' rings.
    fn reset(&mut self, crossings: &[Crossing]) {
        for c in crossings {
            self.winding[c.ring as usize] = 0;
            let part = self.rings.rings[c.ring as usize].1;
            self.holes_around[part] = 0;
            self.part_inside[part] = false;
        }
        self.parts_inside = 0;
    }
}

/// Whether every vertex of `shape` has finite coordinates.
#[must_use]
pub fn has_finite_vertices(shape: &MultiPolygon<f64>) -> bool {
    shape
        .coords_iter()
        .all(|c| c.x.is_finite() && c.y.is_finite())
}

/// Every cell of `grid` with part of `shape` in it, sorted by `(row, col)`.
///
/// A cell meets the boundary when its closed rectangle meets the closed
/// bounding box of a boundary segment; it gets the exact clipped fraction.
/// Any other cell is inside when `shape.contains(centre)`, decided for a
/// whole row at once: its centre lies off every segment's box, so a segment
/// crossing the centre line (upward edges include their start, downward
/// edges their end) is wholly east or west of it, and the winding number of
/// each ring is the sum over the segments east of it.
///
/// A shape with a NaN or infinite vertex has no cells ([`has_finite_vertices`]).
#[must_use]
pub fn cell_weights(shape: &MultiPolygon<f64>, grid: &Grid) -> Vec<CellWeight> {
    if !has_finite_vertices(shape) {
        return Vec::new();
    }
    let Some(bbox) = shape.bounding_rect() else {
        return Vec::new();
    };
    let t = &grid.transform;
    let (col0, col1) = cell_range(
        bbox.min().x,
        bbox.max().x,
        t.origin_x,
        t.pixel_width,
        grid.width,
    );
    // Rows grow southward, so the top of the box gives the first row.
    let (row0, row1) = cell_range(
        -bbox.max().y,
        -bbox.min().y,
        -t.origin_y,
        t.pixel_height,
        grid.height,
    );
    if col0 >= col1 || row0 >= row1 {
        return Vec::new();
    }
    let (cols, rows) = ((col1 - col0) as usize, (row1 - row0) as usize);
    // Cell edges and centres per column and per row, as `cell_rect` and
    // `Rect::center` give them.
    let col_cells: Vec<Rect<f64>> = (col0..col1).map(|c| grid.cell_rect(c, row0)).collect();
    let row_cells: Vec<Rect<f64>> = (row0..row1).map(|r| grid.cell_rect(col0, r)).collect();
    let centre_x: Vec<f64> = col_cells.iter().map(|c| c.center().x).collect();
    let centre_y: Vec<f64> = row_cells.iter().map(|c| c.center().y).collect();

    let rings = Rings::new(shape);
    let mut boundary = vec![false; cols * rows];
    let mut per_row = vec![0_usize; rows + 1];
    let edges: usize = rings.rings.iter().map(|(r, _, _)| r.0.len()).sum();
    let mut crossing_rows: Vec<(u32, Crossing)> = Vec::with_capacity(edges);
    let mut hit_cols: Vec<u32> = Vec::new();
    for (index, (ring, _, _)) in rings.rings.iter().enumerate() {
        for line in ring.lines() {
            let (x_lo, x_hi) = (line.start.x.min(line.end.x), line.start.x.max(line.end.x));
            let (y_lo, y_hi) = (line.start.y.min(line.end.y), line.start.y.max(line.end.y));
            // Candidate cells one beyond the estimate on each side; the
            // exact closed-box test below picks the ones that meet.
            let c_lo = clamped_index((x_lo - t.origin_x) / t.pixel_width - 1.0, col0, col1);
            let c_hi = clamped_index((x_hi - t.origin_x) / t.pixel_width + 2.0, col0, col1);
            let r_lo = clamped_index((t.origin_y - y_hi) / t.pixel_height - 1.0, row0, row1);
            let r_hi = clamped_index((t.origin_y - y_lo) / t.pixel_height + 2.0, row0, row1);
            hit_cols.clear();
            hit_cols.extend((c_lo..c_hi).filter(|&c| {
                let cell = &col_cells[(c - col0) as usize];
                cell.min().x <= x_hi && cell.max().x >= x_lo
            }));
            for r in r_lo..r_hi {
                let ri = (r - row0) as usize;
                let cell = &row_cells[ri];
                if cell.min().y <= y_hi && cell.max().y >= y_lo {
                    for &c in &hit_cols {
                        boundary[ri * cols + (c - col0) as usize] = true;
                    }
                }
                if y_lo <= centre_y[ri] && centre_y[ri] < y_hi {
                    let delta = if line.start.y < line.end.y { 1 } else { -1 };
                    let ring = u32::try_from(index).expect("fewer than 2^32 rings");
                    per_row[ri] += 1;
                    crossing_rows.push((
                        r,
                        Crossing {
                            x: x_lo,
                            delta,
                            ring,
                        },
                    ));
                }
            }
        }
    }
    // Group the crossings by row, each row sorted from east to west.
    let mut start = 0;
    for count in &mut per_row {
        let n = *count;
        *count = start;
        start += n;
    }
    let mut crossings = vec![
        Crossing {
            x: 0.0,
            delta: 0,
            ring: 0
        };
        crossing_rows.len()
    ];
    let mut next = per_row.clone();
    for (r, c) in crossing_rows {
        let ri = (r - row0) as usize;
        crossings[next[ri]] = c;
        next[ri] += 1;
    }

    let planar_cell = t.pixel_width * t.pixel_height;
    let window = cols * rows;
    let mut weights = Vec::with_capacity(window);
    let mut sweep = Sweep::new(&rings);
    let mut inside = vec![false; cols];
    for (ri, row) in (row0..row1).enumerate() {
        let row_crossings = &mut crossings[per_row[ri]..per_row[ri + 1]];
        row_crossings.sort_by(|a, b| b.x.total_cmp(&a.x));
        let mut k = 0;
        for ci in (0..cols).rev() {
            while k < row_crossings.len() && row_crossings[k].x > centre_x[ci] {
                sweep.apply(&row_crossings[k]);
                k += 1;
            }
            inside[ci] = sweep.parts_inside > 0;
        }
        sweep.reset(row_crossings);
        let area_m2 = grid.cell_area_m2(row);
        for (ci, col) in (col0..col1).enumerate() {
            let fraction = if boundary[ri * cols + ci] {
                let cell = grid.cell_rect(col, row);
                (clipped_area(shape, &cell) / planar_cell).min(1.0)
            } else if inside[ci] {
                1.0
            } else {
                0.0
            };
            if fraction > 0.0 {
                weights.push(CellWeight {
                    col,
                    row,
                    fraction,
                    area_m2,
                });
            }
        }
    }
    weights.shrink_to_fit();
    weights
}

#[cfg(test)]
mod tests {
    use super::*;
    use geo::{Area, LineString, MultiPolygon, Polygon, polygon};
    use geolith::terrain::crs::Crs;
    use geolith::terrain::dem::{Dem, GeoTransform};

    fn grid() -> Grid {
        Grid {
            width: 40,
            height: 20,
            transform: GeoTransform {
                origin_x: 0.0,
                origin_y: 1.0,
                pixel_width: 0.05,
                pixel_height: 0.05,
            },
        }
    }

    fn global() -> Grid {
        Grid {
            width: 7200,
            height: 3600,
            transform: GeoTransform {
                origin_x: -180.0,
                origin_y: 90.0,
                pixel_width: 0.05,
                pixel_height: 0.05,
            },
        }
    }

    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 total_fraction(weights: &[CellWeight]) -> f64 {
        weights.iter().map(|w| w.fraction).sum()
    }

    /// Index of the bounding boxes of every boundary segment of `shape` (P1).
    fn boundary_index(
        shape: &MultiPolygon<f64>,
    ) -> rstar::RTree<rstar::primitives::Rectangle<[f64; 2]>> {
        let segments = shape
            .iter()
            .flat_map(|p| std::iter::once(p.exterior()).chain(p.interiors()))
            .flat_map(LineString::lines)
            .map(|l| {
                rstar::primitives::Rectangle::from_corners(
                    [l.start.x, l.start.y],
                    [l.end.x, l.end.y],
                )
            })
            .collect();
        rstar::RTree::bulk_load(segments)
    }

    /// The P1 per-cell method, copied verbatim: an R-tree query per cell and
    /// `contains(centre)` for every cell off the boundary.
    fn reference_cell_weights(shape: &MultiPolygon<f64>, grid: &Grid) -> Vec<CellWeight> {
        use geo::{Contains, Point};
        use rstar::AABB;
        let Some(bbox) = shape.bounding_rect() else {
            return Vec::new();
        };
        let t = &grid.transform;
        let (col0, col1) = cell_range(
            bbox.min().x,
            bbox.max().x,
            t.origin_x,
            t.pixel_width,
            grid.width,
        );
        let (row0, row1) = cell_range(
            -bbox.max().y,
            -bbox.min().y,
            -t.origin_y,
            t.pixel_height,
            grid.height,
        );
        let boundary = boundary_index(shape);
        let planar_cell = t.pixel_width * t.pixel_height;
        let window = (col1 - col0) as usize * (row1 - row0) as usize;
        let mut weights = Vec::with_capacity(window);
        for row in row0..row1 {
            let area_m2 = grid.cell_area_m2(row);
            for col in col0..col1 {
                let cell = grid.cell_rect(col, row);
                let envelope =
                    AABB::from_corners([cell.min().x, cell.min().y], [cell.max().x, cell.max().y]);
                let on_boundary = boundary
                    .locate_in_envelope_intersecting(envelope)
                    .next()
                    .is_some();
                let fraction = if on_boundary {
                    (clipped_area(shape, &cell) / planar_cell).min(1.0)
                } else if shape.contains(&Point::from(cell.center())) {
                    1.0
                } else {
                    0.0
                };
                if fraction > 0.0 {
                    weights.push(CellWeight {
                        col,
                        row,
                        fraction,
                        area_m2,
                    });
                }
            }
        }
        weights
    }

    /// The 1/336° NDVI grid (CDSE `proj:transform`, `proj:shape`).
    fn ndvi() -> Grid {
        Grid {
            width: 120_960,
            height: 47_040,
            transform: GeoTransform {
                origin_x: -180.001_488_095_238_1,
                origin_y: 80.001_488_095_238_09,
                pixel_width: 0.002_976_190_476_204,
                pixel_height: 0.002_976_190_476_204,
            },
        }
    }

    /// The test shapes on `grid`, placed from cell `(col, row)` with
    /// coordinates in cells (east, south) from that cell's corner.
    fn scanline_shapes(grid: &Grid, col: u32, row: u32) -> Vec<(&'static str, MultiPolygon<f64>)> {
        let t = grid.transform;
        let corner = grid.cell_rect(col, row);
        let (x0, y0) = (corner.min().x, corner.max().y);
        let at = |u: f64, v: f64| coord! { x: x0 + u * t.pixel_width, y: y0 - v * t.pixel_height };
        let ring = |points: &[(f64, f64)]| {
            let mut coords: Vec<Coord<f64>> = points.iter().map(|&(u, v)| at(u, v)).collect();
            coords.push(coords[0]);
            LineString::new(coords)
        };
        let boxed =
            |u0: f64, v0: f64, u1: f64, v1: f64| ring(&[(u0, v0), (u1, v0), (u1, v1), (u0, v1)]);
        let centre = |c: u32, r: u32| grid.cell_rect(col + c, row + r).center();
        let on_centre = centre(10, 10);
        let mut vertex_on_centre = vec![at(1.3, 2.2), on_centre, at(21.7, 3.4), at(12.2, 19.6)];
        vertex_on_centre.push(vertex_on_centre[0]);
        let centre_row = centre(0, 12).y;
        let mut horizontal = vec![
            coord! { x: at(3.1, 0.0).x, y: centre_row },
            coord! { x: at(22.9, 0.0).x, y: centre_row },
            at(18.4, 2.6),
            at(9.7, 1.2),
        ];
        horizontal.push(horizontal[0]);
        // Corners on cell corners, so edges run along cell edges.
        let (nw, se) = (
            grid.cell_rect(col + 3, row + 4),
            grid.cell_rect(col + 17, row + 21),
        );
        let aligned = Rect::new(
            coord! { x: nw.min().x, y: nw.max().y },
            coord! { x: se.max().x, y: se.min().y },
        );
        vec![
            (
                "cell-aligned square",
                MultiPolygon::new(vec![aligned.to_polygon()]),
            ),
            (
                "square",
                MultiPolygon::new(vec![Polygon::new(boxed(2.3, 2.7, 20.6, 18.2), vec![])]),
            ),
            (
                "hole",
                MultiPolygon::new(vec![Polygon::new(
                    boxed(1.1, 1.4, 25.9, 24.2),
                    vec![boxed(6.5, 7.25, 15.75, 16.1)],
                )]),
            ),
            (
                "part in a hole",
                MultiPolygon::new(vec![
                    Polygon::new(
                        boxed(1.1, 1.4, 25.9, 24.2),
                        vec![boxed(5.5, 6.25, 18.75, 19.1)],
                    ),
                    Polygon::new(ring(&[(8.2, 9.1), (16.3, 8.4), (12.6, 17.7)]), vec![]),
                ]),
            ),
            (
                "sliver",
                MultiPolygon::new(vec![Polygon::new(
                    ring(&[(0.2, 0.3), (28.7, 25.1), (28.75, 25.0), (0.25, 0.2)]),
                    vec![],
                )]),
            ),
            (
                "vertex on a centre",
                MultiPolygon::new(vec![Polygon::new(
                    LineString::new(vertex_on_centre),
                    vec![],
                )]),
            ),
            (
                "edge on a centre row",
                MultiPolygon::new(vec![Polygon::new(LineString::new(horizontal), vec![])]),
            ),
        ]
    }

    #[test]
    fn scanline_and_point_in_polygon_agree() {
        let ndvi = ndvi();
        // 77°E 20°N on the NDVI grid; cell (2, 2) on the 0.05° grid.
        let ndvi_col = ((77.0 - ndvi.transform.origin_x) / ndvi.transform.pixel_width) as u32;
        let ndvi_row = ((ndvi.transform.origin_y - 20.0) / ndvi.transform.pixel_height) as u32;
        let coarse = Grid {
            width: 40,
            height: 40,
            ..grid()
        };
        for (grid, col, row) in [(coarse, 2, 2), (ndvi, ndvi_col, ndvi_row)] {
            for (name, shape) in scanline_shapes(&grid, col, row) {
                let expected = reference_cell_weights(&shape, &grid);
                assert!(!expected.is_empty(), "{name}: the reference has cells");
                // The sliver is thinner than a cell; every other shape has
                // whole cells.
                assert_eq!(
                    expected.iter().any(|w| w.fraction == 1.0),
                    name != "sliver",
                    "{name}: whole cells"
                );
                assert!(
                    cell_weights(&shape, &grid) == expected,
                    "{name} on {grid:?}"
                );
            }
        }
    }

    #[test]
    fn a_cell_fully_inside_has_fraction_one() {
        let shape = MultiPolygon::new(vec![rect(0.0, 0.9, 0.1, 1.0)]);
        let weights = cell_weights(&shape, &grid());
        assert_eq!(weights.len(), 4);
        for w in &weights {
            assert!((w.fraction - 1.0).abs() < 1e-12, "{w:?}");
        }
    }

    #[test]
    fn half_a_cell_has_fraction_one_half() {
        let shape = MultiPolygon::new(vec![rect(0.0, 0.95, 0.025, 1.0)]);
        let weights = cell_weights(&shape, &grid());
        assert_eq!(weights.len(), 1);
        let w = weights
            .iter()
            .find(|w| w.col == 0 && w.row == 0)
            .expect("cell (0, 0) is covered");
        assert!((w.fraction - 0.5).abs() < 1e-12, "{w:?}");
    }

    #[test]
    fn a_polygon_smaller_than_a_cell_gets_one_cell() {
        let shape = MultiPolygon::new(vec![rect(0.12, 0.82, 0.13, 0.83)]);
        let weights = cell_weights(&shape, &grid());
        assert_eq!(weights.len(), 1);
        let w = weights
            .iter()
            .find(|w| w.col == 2 && w.row == 3)
            .expect("cell (2, 3) is covered");
        assert!((w.fraction - 0.04).abs() < 1e-12, "{w:?}");
    }

    #[test]
    fn fractions_add_up_to_the_planar_area() {
        let triangle = polygon![(x: 0.013, y: 0.31), (x: 0.71, y: 0.42), (x: 0.2, y: 0.97)];
        let expected = triangle.unsigned_area();
        let weights = cell_weights(&MultiPolygon::new(vec![triangle]), &grid());
        let covered = total_fraction(&weights) * 0.0025;
        assert!((covered - expected).abs() < 1e-9, "{covered} vs {expected}");
    }

    #[test]
    fn holes_are_excluded() {
        let outer = rect(0.0, 0.0, 0.2, 0.2).exterior().clone();
        let hole: LineString<f64> = rect(0.05, 0.05, 0.15, 0.15).exterior().clone();
        let shape = MultiPolygon::new(vec![Polygon::new(outer, vec![hole])]);
        let weights = cell_weights(&shape, &grid());
        let total = total_fraction(&weights);
        assert!((total - 12.0).abs() < 1e-9, "{total}");
    }

    #[test]
    fn cell_areas_cover_the_sphere() {
        let g = global();
        let sum: f64 = (0..g.height).map(|row| g.cell_area_m2(row) * 7200.0).sum();
        let sphere = 4.0 * std::f64::consts::PI * EARTH_RADIUS_M * EARTH_RADIUS_M;
        assert!(((sum - sphere) / sphere).abs() < 1e-9, "{sum} vs {sphere}");
    }

    #[test]
    fn a_cell_at_sixty_degrees_is_half_the_equator_cell() {
        let g = global();
        // Row 600 spans 60.00..59.95 N, row 1800 spans 0.00..0.05 S.
        let ratio = g.cell_area_m2(600) / g.cell_area_m2(1800);
        assert!((ratio - 0.5).abs() < 0.001, "{ratio}");
    }

    #[test]
    fn grid_match_tolerates_stored_pixel_rounding() {
        let final_grid = global();
        let mut prelim = global();
        prelim.transform.pixel_width = 0.050_000_000_745_058;
        prelim.transform.pixel_height = 0.050_000_000_745_058;
        assert!(final_grid.matches(&prelim));

        let mut shifted = global();
        shifted.transform.origin_x += 0.05;
        assert!(!final_grid.matches(&shifted));

        let mut wider = global();
        wider.width = 7201;
        assert!(!final_grid.matches(&wider));
    }

    #[test]
    fn grid_tolerance_scales_with_width() {
        let base = global();
        let mut rounded = global();
        rounded.transform.pixel_width = 0.050_000_000_745_058;
        assert!(
            base.matches(&rounded),
            "stored rounding moves the edge 5.4e-6°"
        );

        // 1e-6 per cell moves the far edge of 7200 cells by 0.0072°.
        let mut drifted = global();
        drifted.transform.pixel_width = 0.05 + 1e-6;
        assert!(!base.matches(&drifted));
        let mut drifted_y = global();
        drifted_y.transform.pixel_height = 0.05 + 1e-6;
        assert!(!base.matches(&drifted_y));

        // Over 2 cells the same difference moves the edge only 2e-6°.
        let small = |pixel: f64| Grid {
            width: 2,
            height: 1,
            transform: GeoTransform {
                origin_x: 70.0,
                origin_y: 30.0,
                pixel_width: pixel,
                pixel_height: 0.05,
            },
        };
        assert!(small(0.05).matches(&small(0.05 + 1e-6)));

        // The origin may move 1e-3 of a pixel, no more.
        let mut nudged = global();
        nudged.transform.origin_y += 4e-5;
        assert!(base.matches(&nudged));
        nudged.transform.origin_y += 2e-5;
        assert!(!base.matches(&nudged));
    }

    #[test]
    fn a_non_wgs84_dem_is_rejected() {
        let dem = Dem {
            width: 2,
            height: 2,
            values: vec![0.0; 4],
            transform: GeoTransform {
                origin_x: 0.0,
                origin_y: 0.0,
                pixel_width: 10.0,
                pixel_height: 10.0,
            },
            crs: Crs::WebMercator,
        };
        let err = Grid::from_dem(&dem).expect_err("web mercator is rejected");
        assert!(format!("{err}").contains("EPSG:4326"), "{err}");
    }

    #[test]
    fn a_non_finite_vertex_gives_no_cells() {
        // A finite square inside the grid that alone covers cells.
        let square = rect(0.5, 0.2, 0.7, 0.4);
        assert!(!cell_weights(&MultiPolygon::new(vec![square.clone()]), &grid()).is_empty());
        for bad in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
            let broken = polygon![
                (x: 0.5, y: 0.2), (x: bad, y: 0.2), (x: 0.7, y: 0.4), (x: 0.5, y: 0.4), (x: 0.5, y: 0.2)
            ];
            let shape = MultiPolygon::new(vec![square.clone(), broken]);
            assert!(cell_weights(&shape, &grid()).is_empty(), "x = {bad}");
            let flipped = polygon![
                (x: 0.5, y: 0.2), (x: 0.7, y: bad), (x: 0.7, y: 0.4), (x: 0.5, y: 0.2)
            ];
            let shape = MultiPolygon::new(vec![flipped]);
            assert!(cell_weights(&shape, &grid()).is_empty(), "y = {bad}");
        }
    }
}