use std::path::Path;
use anyhow::{Context as _, bail};
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;
pub const MIN_CONTRIBUTING_FRACTION: f64 = 1e-9;
pub const FALLBACK_REACH: i64 = 2;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AreaCoverage {
pub area_id: String,
pub centroid: (f64, f64),
pub cells: Vec<CellWeight>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CoverageTable {
pub grid: Grid,
pub areas: Vec<AreaCoverage>,
}
impl CoverageTable {
#[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 }
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AreaValue {
pub area_id: String,
pub value: Option<f64>,
pub coverage_pct: f64,
pub cells: u32,
pub sparse: bool,
pub fallback: bool,
pub fallback_cell: Option<[f64; 2]>,
}
pub fn area_values(
table: &CoverageTable,
raster: &Raster,
config: &DatasetConfig,
source: &Path,
) -> anyhow::Result<Vec<AreaValue>> {
area_values_read(table, raster, config, source).map(|(values, _)| values)
}
pub fn area_values_read(
table: &CoverageTable,
raster: &Raster,
config: &DatasetConfig,
source: &Path,
) -> anyhow::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())
}
}
}
fn whole_area_values(
table: &CoverageTable,
dem: &Dem,
config: &DatasetConfig,
source: &Path,
) -> anyhow::Result<Vec<AreaValue>> {
let grid = Grid::from_dem(dem).with_context(|| source.display().to_string())?;
if !grid.matches(&table.grid) {
bail!(
"{}: 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())
}
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;
}
}
}
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,
}
}
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))
}
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)
}
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),
}
}
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() {
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);
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}");
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);
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() {
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 = format!("{err:#}");
assert!(text.contains("x.tif"), "{text}");
assert!(text.contains("grid differs"), "{text}");
}
#[test]
fn a_sliver_touch_does_not_count_as_a_cell() {
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}");
}
}