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:
@@ -220,6 +220,73 @@ class VectorFeatureService:
|
||||
source_metadata = dataset.source_metadata if isinstance(dataset.source_metadata, dict) else {}
|
||||
return isinstance(source_metadata.get("selection_aggregation"), dict) or VectorFeatureService._dataset_theme(dataset) is not None
|
||||
|
||||
@staticmethod
|
||||
def deduplicate_rows(rows: list[Any]) -> list[Any]:
|
||||
"""Collapse rows that describe one source feature across partitions.
|
||||
|
||||
Municipal partitions of one product overlap at their shared boundary,
|
||||
so a rectangle drawn across it returns the same building from both.
|
||||
An empty or missing ``source_feature_id`` is not a shared identity —
|
||||
two rows without one are two features, not a duplicate pair.
|
||||
"""
|
||||
|
||||
seen: set[str] = set()
|
||||
kept: list[Any] = []
|
||||
for row in rows:
|
||||
source_feature_id = getattr(row, "source_feature_id", None)
|
||||
identity = str(source_feature_id).strip() if source_feature_id is not None else ""
|
||||
if not identity:
|
||||
kept.append(row)
|
||||
continue
|
||||
if identity in seen:
|
||||
continue
|
||||
seen.add(identity)
|
||||
kept.append(row)
|
||||
return kept
|
||||
|
||||
@staticmethod
|
||||
def count_disclosure(
|
||||
*,
|
||||
total_feature_count: int,
|
||||
fully_covered_feature_count: int | None,
|
||||
) -> dict[str, Any]:
|
||||
"""Describe how much of the counted population the selection cuts.
|
||||
|
||||
A feature that merely touches the drawn rectangle is counted whole,
|
||||
while ``intersection_area`` clips it. Reporting both numbers without
|
||||
saying so puts two figures for different populations side by side. The
|
||||
count stays whole-feature — that is what an operator expects from
|
||||
"objecten" — but says how many of them the edge cuts, and is flagged as
|
||||
an estimate when it does.
|
||||
|
||||
``fully_covered_feature_count`` is ``None`` when the selection covers a
|
||||
pre-clipped whole work area, where no edge effect exists.
|
||||
"""
|
||||
|
||||
if fully_covered_feature_count is None:
|
||||
return {
|
||||
"partially_covered_feature_count": None,
|
||||
"is_estimate": False,
|
||||
"warning": None,
|
||||
}
|
||||
|
||||
partial = max(0, int(total_feature_count) - int(fully_covered_feature_count))
|
||||
if partial <= 0:
|
||||
return {
|
||||
"partially_covered_feature_count": 0,
|
||||
"is_estimate": False,
|
||||
"warning": None,
|
||||
}
|
||||
return {
|
||||
"partially_covered_feature_count": partial,
|
||||
"is_estimate": True,
|
||||
"warning": (
|
||||
f"{partial} van de {int(total_feature_count)} objecten liggen deels buiten de selectie en zijn "
|
||||
"aan de rand doorgesneden. Ze tellen volledig mee in het aantal; oppervlakte- en lengtematen "
|
||||
"gebruiken alleen het deel binnen de selectie."
|
||||
),
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def constrain_bbox_to_area(
|
||||
bbox: dict[str, Any],
|
||||
@@ -696,6 +763,11 @@ class VectorFeatureService:
|
||||
.limit(safe_limit + 1)
|
||||
.all()
|
||||
)
|
||||
if deduplicate_source_features:
|
||||
# ``total_feature_count`` is already distinct; without this the map
|
||||
# would draw a boundary feature once per partition and the returned
|
||||
# count would exceed the headline number beside it.
|
||||
rows = VectorFeatureService.deduplicate_rows(rows)
|
||||
truncated = total_feature_count > safe_limit
|
||||
selected_rows = rows[:safe_limit]
|
||||
features = [VectorFeatureService._row_to_geojson_feature(row) for row in selected_rows]
|
||||
@@ -767,6 +839,27 @@ class VectorFeatureService:
|
||||
if feature_count is None:
|
||||
feature_count = int(db.query(func.count(VectorFeature.id)).filter(*selection_filter).scalar() or 0)
|
||||
|
||||
# How many of the counted features the selection edge cuts. Skipped for
|
||||
# a pre-clipped whole-area selection, which has no edge to cut against.
|
||||
fully_covered_feature_count: int | None = None
|
||||
if not full_dataset_area and feature_count:
|
||||
try:
|
||||
fully_covered_feature_count = int(
|
||||
db.query(func.count(VectorFeature.id))
|
||||
.filter(*selection_filter)
|
||||
.filter(func.ST_CoveredBy(VectorFeature.geometry, selection_shape))
|
||||
.scalar()
|
||||
or 0
|
||||
)
|
||||
except Exception:
|
||||
# Lightweight unit-test sessions do not implement every spatial
|
||||
# predicate; the count then simply carries no edge disclosure.
|
||||
fully_covered_feature_count = None
|
||||
count_disclosure = VectorFeatureService.count_disclosure(
|
||||
total_feature_count=feature_count,
|
||||
fully_covered_feature_count=fully_covered_feature_count,
|
||||
)
|
||||
|
||||
source_metadata = dataset.source_metadata if isinstance(dataset.source_metadata, dict) else {}
|
||||
config = source_metadata.get("selection_aggregation")
|
||||
if not isinstance(config, dict):
|
||||
@@ -834,9 +927,17 @@ class VectorFeatureService:
|
||||
selection_shape=selection_shape,
|
||||
feature_count=feature_count,
|
||||
full_dataset_area=selection_is_preclipped,
|
||||
partially_covered_feature_count=count_disclosure["partially_covered_feature_count"],
|
||||
)
|
||||
for metric_config in metric_configs
|
||||
]
|
||||
# The whole-feature count carries the edge disclosure; a metric that
|
||||
# already clips to the selection (area, length) does not need it.
|
||||
for computed_metric in metrics:
|
||||
if computed_metric["aggregation_method"] == "feature_count" and count_disclosure["is_estimate"]:
|
||||
computed_metric["is_estimate"] = True
|
||||
computed_metric["warning"] = computed_metric.get("warning") or count_disclosure["warning"]
|
||||
|
||||
primary_metric = metrics[0]
|
||||
return {
|
||||
"metric_label": primary_metric["metric_label"],
|
||||
@@ -845,6 +946,9 @@ class VectorFeatureService:
|
||||
"aggregation_method": primary_metric["aggregation_method"],
|
||||
"primary_metric_key": primary_metric["metric_key"],
|
||||
"feature_count": feature_count,
|
||||
"fully_covered_feature_count": fully_covered_feature_count,
|
||||
"partially_covered_feature_count": count_disclosure["partially_covered_feature_count"],
|
||||
"selection_edge_warning": count_disclosure["warning"],
|
||||
"is_estimate": primary_metric["is_estimate"],
|
||||
"warning": primary_metric.get("warning"),
|
||||
"metrics": metrics,
|
||||
@@ -860,6 +964,7 @@ class VectorFeatureService:
|
||||
selection_shape: Any,
|
||||
feature_count: int,
|
||||
full_dataset_area: bool,
|
||||
partially_covered_feature_count: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
method = str(config.get("method") or "feature_count")
|
||||
unit = str(config.get("unit") or "objecten")
|
||||
@@ -950,12 +1055,16 @@ class VectorFeatureService:
|
||||
)
|
||||
metric_value = float(aggregate_value or 0.0)
|
||||
if method == "area_weighted_sum" and not full_dataset_area:
|
||||
partial_feature_count = (
|
||||
db.query(func.count(VectorFeature.id))
|
||||
.filter(*metric_filter)
|
||||
.filter(~covered_by_selection)
|
||||
.scalar()
|
||||
)
|
||||
# The selection-edge count was already established for the
|
||||
# feature count; a second query would ask the same question.
|
||||
partial_feature_count = partially_covered_feature_count
|
||||
if partial_feature_count is None:
|
||||
partial_feature_count = (
|
||||
db.query(func.count(VectorFeature.id))
|
||||
.filter(*metric_filter)
|
||||
.filter(~covered_by_selection)
|
||||
.scalar()
|
||||
)
|
||||
is_estimate = bool(config.get("is_estimate", False)) or bool(partial_feature_count)
|
||||
if not is_estimate and config.get("warning_only_when_estimate", True):
|
||||
warning = None
|
||||
|
||||
Reference in New Issue
Block a user