report what an area selection actually measured

Four ways a selection produced a confident number about a different area than
the operator drew:

Flood hazard divided the inundated cells by every cell in the drawn rectangle,
including cells the VMM raster does not model at all. A selection reaching
past the modelled extent therefore reported a diluted risk share, turning
missing data into an implied absence of risk. Terrain, bathymetry and thematic
raster already divided by valid cells; flood hazard was the outlier. It now
reports the three populations separately, states model coverage next to the
drawn area, and returns a null fraction rather than a zero when nothing was
modelled.

geometry_mask selects a cell when its centre falls inside the geometry, so a
rectangle smaller than one cell — or one landing between four centres —
selected nothing and the analysis returned zeros indistinguishable on screen
from "we looked and there is nothing here". On a 100 m population raster a
40 m rectangle over a city block reported no inhabitants. Selection now falls
back to the touched cells and says that it did, since the answer then covers
more ground than was requested. rasterio.mask applies the same centre rule
when cropping, so that call is widened too; the cells that count are still
decided by the centre rule wherever it selects anything.

The object count treated any feature touching the selection as whole, while
intersection_area clipped it — two headline numbers on one panel describing
different populations. The count stays whole-feature, which is what "objecten"
means to an operator, but now reports how many the edge cuts and is marked an
estimate when it does. The area_weighted_sum branch reuses that same count
instead of issuing its own near-identical query.

Partitioned selection de-duplicated the count on source_feature_id but
returned the raw rows, so a building on a municipal boundary was counted once
and drawn twice.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Jens
2026-08-22 14:33:19 +02:00
co-authored by Claude Opus 5
parent 08188005bd
commit dd87a62e8f
20 changed files with 1037 additions and 82 deletions
@@ -2,8 +2,10 @@ from __future__ import annotations
import io
import math
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
from uuid import UUID
from geoalchemy2.shape import to_shape
@@ -13,6 +15,7 @@ from shapely.ops import transform as shapely_transform
from app.core.config import Settings, get_settings
from app.core.errors import AppError
from app.services.raster_cell_selection import select_cells
from app.models import Area, Dataset
from app.schemas.flood_hazard import (
FloodHazardMetric,
@@ -25,6 +28,83 @@ from app.services.flood_hazard_acquisition_service import FloodHazardAcquisition
from app.services.raster_partition_analysis_service import RasterPartitionAnalysisService
@dataclass(frozen=True)
class FloodHazardCellStatistics:
"""Cell populations behind one flood-hazard selection.
Three populations, deliberately kept apart:
``selected``
every cell whose centre falls inside the drawn selection;
``valid``
the subset the VMM raster actually models — finite, not nodata;
``inundated``
the subset of valid cells with a positive modelled depth.
Risk is a share of what was modelled. Dividing by the selected cells
instead silently reports "no data" as "no risk", which for a selection
reaching past the modelled extent understates the hazard by whatever
fraction of the rectangle the model never covered.
"""
selected_cell_count: int
valid_cell_count: int
inundated_cell_count: int
depth_values: Any
@property
def no_data_cell_count(self) -> int:
return max(0, self.selected_cell_count - self.valid_cell_count)
@property
def data_coverage_ratio(self) -> float:
if self.selected_cell_count <= 0:
return 0.0
return self.valid_cell_count / self.selected_cell_count
@property
def inundated_fraction(self) -> float | None:
"""``None`` when nothing was modelled: absence of data is not a zero."""
if self.valid_cell_count <= 0:
return None
return self.inundated_cell_count / self.valid_cell_count
def inundated_area_ha(self, cell_area_m2: float) -> float:
return self.inundated_cell_count * cell_area_m2 / 10_000.0
def analysed_area_ha(self, cell_area_m2: float) -> float:
"""Area the model actually covers inside the selection."""
return self.valid_cell_count * cell_area_m2 / 10_000.0
def selected_area_ha(self, cell_area_m2: float) -> float:
"""Area of the selection as rasterised, model coverage aside."""
return self.selected_cell_count * cell_area_m2 / 10_000.0
@classmethod
def from_cells(cls, values: Any, selected: Any, *, nodata: float | None) -> "FloodHazardCellStatistics":
import numpy as np
raw = np.asarray(values, dtype="float64")
selected_mask = np.asarray(selected, dtype=bool)
has_data = selected_mask & np.isfinite(raw)
if nodata is not None:
has_data &= ~np.isclose(raw, float(nodata))
# A modelled zero or negative depth is data: it says "dry here", which
# is a different statement from "not modelled here".
inundated = has_data & (raw > 0.0)
return cls(
selected_cell_count=int(selected_mask.sum()),
valid_cell_count=int(has_data.sum()),
inundated_cell_count=int(inundated.sum()),
depth_values=raw[inundated],
)
class FloodHazardAnalysisService:
UNSUPPORTED_METRICS = [
"bathymetry_depth_m",
@@ -36,6 +116,77 @@ class FloodHazardAnalysisService:
"gemodelleerde maxima op en is geen gelijktijdig opgeslagen watervolume, actuele waterstand of bathymetrie."
)
@staticmethod
def _coverage_metrics(stats: "FloodHazardCellStatistics", cell_area_m2: float, metric) -> list[FloodHazardMetric]:
"""Headline metrics, each stating which population it is a share of.
The analysed area is reported next to the drawn area so an operator can
see immediately how much of the rectangle the flood model covers. A
selection with no model data reports 0% coverage rather than 0% risk.
"""
metrics = [
metric(
"modelled_inundated_area_ha",
"Gemodelleerd overstroomd oppervlak",
stats.inundated_area_ha(cell_area_m2),
"ha",
"positive_depth_cells_times_cell_area",
),
metric(
"modelled_inundated_share_pct",
"Aandeel gemodelleerd gebied met diepte",
0.0 if stats.inundated_fraction is None else stats.inundated_fraction * 100.0,
"%",
"positive_depth_cells_divided_by_modelled_cells",
),
metric(
"modelled_area_ha",
"Oppervlak met overstromingsmodel",
stats.analysed_area_ha(cell_area_m2),
"ha",
"modelled_cells_times_cell_area",
),
metric(
"selection_area_ha",
"Oppervlak van de selectie",
stats.selected_area_ha(cell_area_m2),
"ha",
"selected_cells_times_cell_area",
),
metric(
"model_coverage_pct",
"Deel van de selectie met een model",
stats.data_coverage_ratio * 100.0,
"%",
"modelled_cells_divided_by_selected_cells",
),
]
return metrics
@staticmethod
def _combined_warning(stats: "FloodHazardCellStatistics", cell_selection_warning: str | None) -> str | None:
parts = [
part
for part in (cell_selection_warning, FloodHazardAnalysisService._coverage_warning(stats))
if part
]
return " ".join(parts) if parts else None
@staticmethod
def _coverage_warning(stats: "FloodHazardCellStatistics") -> str | None:
if stats.valid_cell_count <= 0:
return (
"Voor deze selectie bestaat geen VMM-overstromingsmodel. Er is dus geen overstromingsrisico "
"gemeten; dit is geen bevestiging dat het risico nul is."
)
if stats.data_coverage_ratio < 0.999:
return (
f"Het VMM-model dekt {stats.data_coverage_ratio * 100:.1f}% van deze selectie. Percentages gelden "
"voor het gemodelleerde deel, niet voor de volledige selectie."
)
return None
@staticmethod
def _load_dataset(db, project_id: UUID, dataset_id: UUID) -> Dataset:
dataset = db.get(Dataset, dataset_id)
@@ -110,17 +261,32 @@ class FloodHazardAnalysisService:
details={"pixel_count": expected_cells, "max_pixels": resolved_settings.flood_hazard_max_pixels},
status_code=422,
)
clipped, clipped_transform = mask(source, [mapping(analysis_geometry)], crop=True, filled=False, indexes=[1])
# ``all_touched`` keeps the values of cells the selection only
# clips, so a selection finer than one cell still has data to
# read. Which of those cells actually count is decided by
# ``select_cells`` below, so the normal result is unchanged.
clipped, clipped_transform = mask(
source,
[mapping(analysis_geometry)],
crop=True,
filled=False,
indexes=[1],
all_touched=True,
)
depth = np.ma.asarray(clipped[0], dtype="float64")
raw = depth.filled(np.nan)
selected_cells = geometry_mask([mapping(analysis_geometry)], out_shape=depth.shape, transform=clipped_transform, invert=True)
nodata = source.nodata
valid = selected_cells & ~np.ma.getmaskarray(depth) & np.isfinite(raw) & (raw > 0.0)
if nodata is not None:
valid &= raw != float(nodata)
values = raw[valid]
selected_cell_count = int(selected_cells.sum())
inundated_cell_count = int(values.size)
cell_selection = select_cells(
analysis_geometry,
out_shape=depth.shape,
transform=clipped_transform,
cell_area_m2=abs(float(source.res[0])) * abs(float(source.res[1])),
)
selected_cells = cell_selection.mask
# A masked cell carries no model value, so fold the mask into
# the raw array before the populations are separated.
raw = np.where(np.ma.getmaskarray(depth), np.nan, raw)
stats = FloodHazardCellStatistics.from_cells(raw, selected_cells, nodata=source.nodata)
values = stats.depth_values
resolution_x = abs(float(source.res[0]))
resolution_y = abs(float(source.res[1]))
cell_area_m2 = resolution_x * resolution_y
@@ -143,18 +309,8 @@ class FloodHazardAnalysisService:
aggregation_method=method,
)
inundated_area_ha = inundated_cell_count * cell_area_m2 / 10_000.0
metrics = [
metric("modelled_inundated_area_ha", "Gemodelleerd overstroomd oppervlak", inundated_area_ha, "ha", "positive_depth_cells_times_cell_area"),
metric(
"modelled_inundated_share_pct",
"Aandeel selectie met gemodelleerde diepte",
inundated_cell_count / max(1, selected_cell_count) * 100.0,
"%",
"positive_depth_cells_divided_by_selected_cells",
),
]
if inundated_cell_count:
metrics = FloodHazardAnalysisService._coverage_metrics(stats, cell_area_m2, metric)
if stats.inundated_cell_count:
metrics.extend(
[
metric("modelled_depth_mean_m", "Gemiddelde gemodelleerde maximumdiepte", values.mean(), "m", "mean_positive_depth_cells"),
@@ -181,9 +337,14 @@ class FloodHazardAnalysisService:
return_period_years=product.return_period_years,
selection_bbox=payload.bbox,
selection_area_id=payload.area_id,
selected_cell_count=selected_cell_count,
inundated_cell_count=inundated_cell_count,
inundated_fraction=round(inundated_cell_count / max(1, selected_cell_count), 6),
selected_cell_count=stats.selected_cell_count,
valid_cell_count=stats.valid_cell_count,
no_data_cell_count=stats.no_data_cell_count,
data_coverage_ratio=round(stats.data_coverage_ratio, 6),
inundated_cell_count=stats.inundated_cell_count,
inundated_fraction=(
None if stats.inundated_fraction is None else round(stats.inundated_fraction, 6)
),
resolution_m=round(max(resolution_x, resolution_y), 4),
summary=FloodHazardSelectionSummary(
metric_label=primary.metric_label,
@@ -193,6 +354,7 @@ class FloodHazardAnalysisService:
primary_metric_key=primary.metric_key,
metrics=metrics,
),
coverage_warning=FloodHazardAnalysisService._combined_warning(stats, cell_selection.warning),
unsupported_metrics=FloodHazardAnalysisService.UNSUPPORTED_METRICS,
limitation_message=FloodHazardAnalysisService.LIMITATION,
generated_at=datetime.now(UTC).isoformat(),
@@ -236,16 +398,12 @@ class FloodHazardAnalysisService:
status_code=503,
) from exc
raw = partition.values
valid = (
partition.selected_cells
& np.isfinite(raw)
& (raw != FloodHazardAcquisitionService.NODATA)
& (raw > 0.0)
stats = FloodHazardCellStatistics.from_cells(
partition.values,
partition.selected_cells,
nodata=FloodHazardAcquisitionService.NODATA,
)
values = raw[valid]
selected_cell_count = int(partition.selected_cells.sum())
inundated_cell_count = int(values.size)
values = stats.depth_values
cell_area_m2 = partition.resolution_x * partition.resolution_y
def metric(key: str, label: str, value: float, unit: str, method: str) -> FloodHazardMetric:
@@ -257,24 +415,8 @@ class FloodHazardAnalysisService:
aggregation_method=method,
)
inundated_area_ha = inundated_cell_count * cell_area_m2 / 10_000.0
metrics = [
metric(
"modelled_inundated_area_ha",
"Gemodelleerd overstroomd oppervlak",
inundated_area_ha,
"ha",
"positive_depth_cells_times_cell_area",
),
metric(
"modelled_inundated_share_pct",
"Aandeel selectie met gemodelleerde diepte",
inundated_cell_count / max(1, selected_cell_count) * 100.0,
"%",
"positive_depth_cells_divided_by_selected_cells",
),
]
if inundated_cell_count:
metrics = FloodHazardAnalysisService._coverage_metrics(stats, cell_area_m2, metric)
if stats.inundated_cell_count:
metrics.extend(
[
metric("modelled_depth_mean_m", "Gemiddelde gemodelleerde maximumdiepte", values.mean(), "m", "mean_positive_depth_cells"),
@@ -302,9 +444,14 @@ class FloodHazardAnalysisService:
return_period_years=product.return_period_years,
selection_bbox=payload.bbox,
selection_area_id=payload.area_id,
selected_cell_count=selected_cell_count,
inundated_cell_count=inundated_cell_count,
inundated_fraction=round(inundated_cell_count / max(1, selected_cell_count), 6),
selected_cell_count=stats.selected_cell_count,
valid_cell_count=stats.valid_cell_count,
no_data_cell_count=stats.no_data_cell_count,
data_coverage_ratio=round(stats.data_coverage_ratio, 6),
inundated_cell_count=stats.inundated_cell_count,
inundated_fraction=(
None if stats.inundated_fraction is None else round(stats.inundated_fraction, 6)
),
resolution_m=round(max(partition.resolution_x, partition.resolution_y), 4),
summary=FloodHazardSelectionSummary(
metric_label=primary.metric_label,
@@ -314,6 +461,7 @@ class FloodHazardAnalysisService:
primary_metric_key=primary.metric_key,
metrics=metrics,
),
coverage_warning=FloodHazardAnalysisService._combined_warning(stats, partition.cell_selection_warning),
unsupported_metrics=FloodHazardAnalysisService.UNSUPPORTED_METRICS,
limitation_message=(
f"{FloodHazardAnalysisService.LIMITATION} De selectie werd exact berekend over "