diff --git a/src/limen/data/repos/fire_events_repo.py b/src/limen/data/repos/fire_events_repo.py index c19af030..6234f54a 100644 --- a/src/limen/data/repos/fire_events_repo.py +++ b/src/limen/data/repos/fire_events_repo.py @@ -8,8 +8,11 @@ from __future__ import annotations +import json +from collections.abc import Iterable, Mapping from dataclasses import dataclass -from datetime import date +from datetime import date, timedelta +from typing import Any from limen.core.logging import get_logger from limen.data.db import acquire @@ -134,18 +137,10 @@ async def refresh_density( #: durata tipica senza raccogliere l'incendio successivo. FRP_WINDOW_DAYS = 5 -#: Somma di FRP e sua densità per perimetro, in una passata. -#: -#: Solo hotspot di vegetazione (`detection_type = 0`): un'acciaieria dentro il -#: perimetro sommerebbe potenza radiativa che non viene da quel rogo. -#: -#: `NULLIF(area_ha, 0)`: un perimetro con area nulla o assente lascia la -#: densità a NULL invece di dividere per zero — e NULL qui significa "non -#: misurabile", che è la cosa giusta da propagare al motore. -#: -#: Sulla vista `v_fire_perimeters`, che è aggiornabile: solo i perimetri del -#: layer di Limen. Le righe dell'altro layer tengono i valori che avevano. -_REFRESH_FRP_SQL = """ +#: L'SQL che faceva lo stesso calcolo prima di limen-core (#714). Non lo usa +#: più nessuno: resta come riferimento del test di parità, che lo esegue +#: accanto a `refresh_perimeter_frp` sulle stesse righe. +_REFRESH_FRP_SQL_LEGACY = """ WITH agg AS ( SELECT fp.id, sum(h.frp_mw) AS frp_sum, @@ -168,21 +163,123 @@ async def refresh_density( WHERE fp.id = agg.id """ +_PERIMETERS_SQL = """ +SELECT id, layer, fire_date, area_ha, ST_AsGeoJSON(geom) AS geometry +FROM v_fire_perimeters +WHERE fire_date IS NOT NULL +""" + +#: Solo gli hotspot che possono contare, nei giorni e nel riquadro dei +#: perimetri di un anno: la regola vera la applica `seen_inside_all`. +_HOTSPOTS_SQL = """ +SELECT longitude, latitude, acq_date, frp_mw, detection_type +FROM fire_hotspots +WHERE detection_type = 0 + AND frp_mw IS NOT NULL + AND acq_date BETWEEN $1 AND $2 + AND geom && ST_MakeEnvelope($3, $4, $5, $6, 4326) +""" + +#: Scrive solo dove il valore cambia: `updated_at` resta quello vero. +_WRITE_FRP_SQL = """ +UPDATE v_fire_perimeters +SET frp_sum_mw = $2, + frp_hotspots = $3, + frp_density_mw_per_ha = $4, + updated_at = now() +WHERE id = $1 + AND (frp_sum_mw, frp_hotspots, frp_density_mw_per_ha) IS DISTINCT FROM ($2, $3, $4) +""" + async def refresh_perimeter_frp( *, window_days: int = FRP_WINDOW_DAYS, timeout: float | None = None ) -> int: - """Ricalcola FRP e densità su tutti i perimetri. Idempotente. + """Ricalcola FRP e densità su tutti i perimetri del layer di Limen. Idempotente. Va chiamata quando arriva *uno dei due* dataset: un perimetro nuovo o hotspot nuovi cambiano la stessa risposta, quindi sia il sync EFFIS sia l'ingest della storia del fuoco la invocano. + + Il conto è `limen_core.wildfire.seen_inside_all`, la stessa regola dell'SQL + di prima (#714): hotspot di vegetazione con una potenza, entro + ``window_days`` giorni dalla data del rogo, dentro il perimetro o sul suo + bordo. Qui restano la lettura e la scrittura. Un perimetro in cui nessun + hotspot conta ha somma, conteggio e densità NULL: non misurato, non zero. + Un anno di perimetri alla volta, per non portare in memoria tutti gli + hotspot d'Italia. + + Restituisce quanti perimetri hanno almeno un hotspot che conta. """ + from limen_core.wildfire import Detection, Perimeter, seen_inside_all + async with acquire() as conn: - status = await conn.execute(_REFRESH_FRP_SQL, window_days, timeout=timeout) - written = int(status.split()[-1]) if status else 0 - log.info("fire_perimeters.frp_refreshed", perimeters=written, window_days=window_days) - return written + rows = await conn.fetch(_PERIMETERS_SQL, timeout=timeout) + by_year: dict[int, list[Perimeter]] = {} + for r in rows: + perimeter = Perimeter( + id=str(r["id"]), + geometry=json.loads(r["geometry"]), + fire_date=r["fire_date"], + area_ha=None if r["area_ha"] is None else float(r["area_ha"]), + layer=str(r["layer"]), + ) + by_year.setdefault(r["fire_date"].year, []).append(perimeter) + + measured = 0 + span = timedelta(days=window_days) + for perimeters in by_year.values(): + west, south, east, north = _extent(p.geometry for p in perimeters) + first = min(p.fire_date for p in perimeters if p.fire_date) - span + last = max(p.fire_date for p in perimeters if p.fire_date) + span + hotspots = await conn.fetch( + _HOTSPOTS_SQL, first, last, west, south, east, north, timeout=timeout + ) + detections = [ + Detection( + lon=float(h["longitude"]), + lat=float(h["latitude"]), + day=h["acq_date"], + frp_mw=float(h["frp_mw"]), + detection_type=int(h["detection_type"]), + ) + for h in hotspots + ] + seen = seen_inside_all(perimeters, detections, window_days=window_days) + measured += sum(1 for f in seen if f.detections) + await conn.executemany( + _WRITE_FRP_SQL, + [ + ( + f.perimeter, + f.frp_total_mw, + f.detections or None, + f.frp_density_mw_per_ha, + ) + for f in seen + ], + timeout=timeout, + ) + log.info("fire_perimeters.frp_refreshed", perimeters=measured, window_days=window_days) + return measured + + +def _extent(geometries: Iterable[Mapping[str, Any]]) -> tuple[float, float, float, float]: + """Il riquadro che contiene tutte le geometrie GeoJSON date.""" + lons: list[float] = [] + lats: list[float] = [] + + def walk(coordinates: Any) -> None: + if coordinates and isinstance(coordinates[0], int | float): + lons.append(float(coordinates[0])) + lats.append(float(coordinates[1])) + return + for part in coordinates: + walk(part) + + for geometry in geometries: + walk(geometry["coordinates"]) + return min(lons), min(lats), max(lons), max(lats) async def perimeter_severity_at(aoi_id: str, *, on_or_before: date) -> float | None: diff --git a/tests/integration/test_frp_parity.py b/tests/integration/test_frp_parity.py new file mode 100644 index 00000000..17c953e5 --- /dev/null +++ b/tests/integration/test_frp_parity.py @@ -0,0 +1,184 @@ +"""The FRP refresh through limen-core gives what the SQL gave (#714). + +`refresh_perimeter_frp` was one SQL statement; now the rule lives in +`limen_core.wildfire.seen_inside_all` and Limen only reads and writes. This +runs both on the same rows, on the cases where two implementations of "inside +the perimeter, around its day" can disagree: a point on the edge, on a +vertex, in a hole, the last day of the window and the first day out, a +second part of a MultiPolygon, a perimeter with no area, one with no date, +and detections that do not count (another type, no power). +""" + +from __future__ import annotations + +import datetime as dt +import math + +import pytest + +from limen.data.db import acquire +from limen.data.repos.fire_events_repo import ( + _REFRESH_FRP_SQL_LEGACY, + FRP_WINDOW_DAYS, + refresh_perimeter_frp, +) +from limen.data.repos.fire_repo import FireHotspot, upsert_hotspots + +pytestmark = pytest.mark.integration + +DAY = dt.date(2025, 7, 20) +SQUARE = "ST_Multi(ST_MakeEnvelope(16.0, 41.0, 16.1, 41.1, 4326))" +HOLED = ( + "ST_Multi(ST_GeomFromText('POLYGON((15.0 40.0, 15.2 40.0, 15.2 40.2, 15.0 40.2, 15.0 40.0)," + "(15.05 40.05, 15.15 40.05, 15.15 40.15, 15.05 40.15, 15.05 40.05))', 4326))" +) +TWO_PARTS = ( + "ST_GeomFromText('MULTIPOLYGON(((17.0 39.0, 17.1 39.0, 17.1 39.1, 17.0 39.1, 17.0 39.0))," + "((17.3 39.0, 17.4 39.0, 17.4 39.1, 17.3 39.1, 17.3 39.0)))', 4326)" +) + +PERIMETERS = [ + ("square", DAY, 100.0, SQUARE), + ("holed", DAY, 300.0, HOLED), + ("two-parts", DAY, 200.0, TWO_PARTS), + ("no-area", DAY, None, "ST_Multi(ST_MakeEnvelope(14.0, 38.0, 14.1, 38.1, 4326))"), + ("zero-area", DAY, 0.0, "ST_Multi(ST_MakeEnvelope(14.5, 38.0, 14.6, 38.1, 4326))"), + ("no-date", None, 50.0, "ST_Multi(ST_MakeEnvelope(13.0, 37.0, 13.1, 37.1, 4326))"), + ("nothing-seen", DAY, 80.0, "ST_Multi(ST_MakeEnvelope(12.0, 42.0, 12.1, 42.1, 4326))"), +] + + +def spot( + lon: float, + lat: float, + *, + day: dt.date = DAY, + frp: float | None = 10.0, + kind: int | None = 0, + t: int = 1200, +) -> FireHotspot: + return FireHotspot( + source="TEST", + acq_date=day, + acq_time=t, + latitude=lat, + longitude=lon, + frp_mw=frp, + detection_type=kind, + ) + + +W = dt.timedelta(days=FRP_WINDOW_DAYS) +HOTSPOTS = [ + spot(16.05, 41.05, frp=12.0), # inside + spot(16.1, 41.05, frp=3.0, t=1201), # on the east edge + spot(16.0, 41.0, frp=2.0, t=1202), # on a vertex + spot(16.05, 41.05, day=DAY + W, frp=4.0, t=1203), # last day of the window + spot(16.05, 41.05, day=DAY - W, frp=5.0, t=1204), # first day of the window + spot(16.05, 41.05, day=DAY + W + dt.timedelta(days=1), frp=99.0), # a day out + spot(16.05, 41.05, kind=2, frp=500.0, t=1205), # a steelworks + spot(16.05, 41.05, frp=None, t=1206), # no power + spot(16.11, 41.05, frp=77.0, t=1207), # just outside + spot(15.1, 40.1, frp=40.0), # in the hole + spot(15.02, 40.1, frp=6.0), # in the ring around the hole + spot(15.05, 40.1, frp=7.0, t=1208), # on the edge of the hole + spot(17.05, 39.05, frp=8.0), # first part + spot(17.35, 39.05, frp=9.0), # second part + spot(17.2, 39.05, frp=88.0), # between the parts + spot(14.05, 38.05, frp=11.0), # no area + spot(14.55, 38.05, frp=13.0), # zero area + spot(13.05, 37.05, frp=14.0), # no date +] + + +async def _seed() -> None: + async with acquire() as conn: + for pid, day, area, geom in PERIMETERS: + await conn.execute( + "INSERT INTO fire_perimeters (layer, id, fire_date, area_ha, geom) " + f"VALUES ('ms:modis.ba.poly', $1, $2, $3, {geom})", + pid, + day, + area, + ) + # A perimeter of the other layer, on the same place: never touched. + await conn.execute( + "INSERT INTO fire_perimeters (layer, id, fire_date, area_ha, geom) " + f"VALUES ('nrt.ba.poly', 'square', $1, 100, {SQUARE})", + DAY, + ) + await upsert_hotspots(HOTSPOTS) + + +async def _read() -> dict[str, tuple[float | None, int | None, float | None]]: + async with acquire() as conn: + rows = await conn.fetch( + "SELECT id, frp_sum_mw, frp_hotspots, frp_density_mw_per_ha FROM v_fire_perimeters" + ) + return {r["id"]: (r["frp_sum_mw"], r["frp_hotspots"], r["frp_density_mw_per_ha"]) for r in rows} + + +def _same(a: tuple[float | None, ...], b: tuple[float | None, ...]) -> bool: + return all( + (x is None and y is None) + or (x is not None and y is not None and math.isclose(x, y, rel_tol=1e-12)) + for x, y in zip(a, b, strict=True) + ) + + +async def test_limen_core_gives_what_the_sql_gave(reset_db: None) -> None: + await _seed() + async with acquire() as conn: + await conn.execute(_REFRESH_FRP_SQL_LEGACY, FRP_WINDOW_DAYS) + legacy = await _read() + async with acquire() as conn: + await conn.execute( + "UPDATE fire_perimeters SET frp_sum_mw = NULL, frp_hotspots = NULL, " + "frp_density_mw_per_ha = NULL" + ) + measured = await refresh_perimeter_frp() + core = await _read() + + assert set(core) == set(legacy) + differ = {pid: (legacy[pid], core[pid]) for pid in core if not _same(legacy[pid], core[pid])} + assert differ == {} + # The cases themselves, so that a shared mistake is not a parity. + assert core["square"] == (26.0, 5, 0.26) # inside, edge, vertex, both window ends + assert core["holed"] == (13.0, 2, 13.0 / 300) # ring and the hole's edge, not the hole + assert core["two-parts"] == (17.0, 2, 17.0 / 200) + assert core["no-area"] == (11.0, 1, None) + assert core["zero-area"] == (13.0, 1, None) + assert core["no-date"] == (None, None, None) + assert core["nothing-seen"] == (None, None, None) + assert measured == 5 + + +async def test_the_other_layer_is_not_touched(reset_db: None) -> None: + await _seed() + await refresh_perimeter_frp() + async with acquire() as conn: + other = await conn.fetchrow( + "SELECT frp_sum_mw FROM fire_perimeters WHERE layer = 'nrt.ba.poly' AND id = 'square'" + ) + assert other is not None and other["frp_sum_mw"] is None + + +async def test_a_second_run_writes_nothing(reset_db: None) -> None: + await _seed() + await refresh_perimeter_frp() + async with acquire() as conn: + before = await conn.fetchval("SELECT max(updated_at) FROM fire_perimeters") + await refresh_perimeter_frp() + async with acquire() as conn: + after = await conn.fetchval("SELECT max(updated_at) FROM fire_perimeters") + assert after == before + + +async def test_a_perimeter_no_longer_seen_goes_back_to_not_measured(reset_db: None) -> None: + """The SQL left an old value where no detection counted any more; this clears it.""" + await _seed() + await refresh_perimeter_frp() + async with acquire() as conn: + await conn.execute("DELETE FROM fire_hotspots WHERE latitude = 38.05") + await refresh_perimeter_frp() + assert (await _read())["no-area"] == (None, None, None)