limen-core 0.4.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. limen_core/__init__.py +20 -0
  2. limen_core/agreement.py +142 -0
  3. limen_core/calibration.py +78 -0
  4. limen_core/cascades/__init__.py +16 -0
  5. limen_core/cascades/attention.py +76 -0
  6. limen_core/cascades/config.py +140 -0
  7. limen_core/cascades/rules.py +124 -0
  8. limen_core/cases.py +137 -0
  9. limen_core/flood.py +178 -0
  10. limen_core/landslide.py +118 -0
  11. limen_core/models/__init__.py +40 -0
  12. limen_core/models/context.py +182 -0
  13. limen_core/models/hazard.py +30 -0
  14. limen_core/models/risk.py +703 -0
  15. limen_core/models/sensor.py +64 -0
  16. limen_core/post_fire.py +135 -0
  17. limen_core/py.typed +0 -0
  18. limen_core/scoring/__init__.py +34 -0
  19. limen_core/scoring/api.py +69 -0
  20. limen_core/scoring/base.py +80 -0
  21. limen_core/scoring/caine.py +163 -0
  22. limen_core/scoring/engine.py +469 -0
  23. limen_core/scoring/exposure.py +136 -0
  24. limen_core/scoring/flood/__init__.py +6 -0
  25. limen_core/scoring/flood/climatologia.py +85 -0
  26. limen_core/scoring/flood/engine.py +175 -0
  27. limen_core/scoring/flood/trigger.py +122 -0
  28. limen_core/scoring/flood_forecast.py +59 -0
  29. limen_core/scoring/kinematic.py +101 -0
  30. limen_core/scoring/post_fire.py +85 -0
  31. limen_core/scoring/regional_thresholds.py +1339 -0
  32. limen_core/scoring/seismic_decay.py +101 -0
  33. limen_core/scoring/soglie_regionali.py +129 -0
  34. limen_core/scoring/wildfire/__init__.py +5 -0
  35. limen_core/scoring/wildfire/climatology.py +54 -0
  36. limen_core/scoring/wildfire/confronto.py +80 -0
  37. limen_core/scoring/wildfire/engine.py +95 -0
  38. limen_core/seismic.py +176 -0
  39. limen_core/wildfire.py +272 -0
  40. limen_core-0.4.1.dist-info/METADATA +195 -0
  41. limen_core-0.4.1.dist-info/RECORD +43 -0
  42. limen_core-0.4.1.dist-info/WHEEL +4 -0
  43. limen_core-0.4.1.dist-info/licenses/LICENSE +202 -0
limen_core/__init__.py ADDED
@@ -0,0 +1,20 @@
1
+ """The joins of Limen: what the open-data libraries mean together.
2
+
3
+ Each library reads one source and stops there. What two of them say together
4
+ (a burn seen by satellite inside a mapped perimeter, an earthquake and the
5
+ rain that follows it, a computed index next to the official one) is a join,
6
+ and it lives here. Pure functions over plain values: no I/O, no database, no
7
+ network.
8
+
9
+ * :mod:`limen_core.seismic`: how long a slope stays shaken, and how much the
10
+ rain threshold is lowered after an earthquake;
11
+ * :mod:`limen_core.post_fire`: for how long, and how much, a burnt slope is
12
+ more ready to fail;
13
+ * :mod:`limen_core.agreement`: two measures of the same thing, side by side.
14
+ """
15
+
16
+ from importlib.metadata import version
17
+
18
+ __version__ = version("limen-core")
19
+
20
+ __all__ = ["__version__"]
@@ -0,0 +1,142 @@
1
+ """Two measures of the same thing, side by side: how far apart they are.
2
+
3
+ Made for the fire weather index: the one computed with ``fwi-chain`` next to
4
+ the official ones (the EFFIS rasters read by ``effis-client``, the Copernicus
5
+ reanalysis read by ``glofas-ewds``). Each library gives its own numbers; the
6
+ pairing of the two, and what the difference means, is a join and lives here.
7
+ It works for any two series of numbers.
8
+
9
+ :func:`pair` joins two sets by key (a place and a day, say); :func:`compare`
10
+ gives, for each component, the mean difference, the absolute and the squared
11
+ error, the correlation and, when a ``classify`` is given, how often the two
12
+ fall in the same class and how often ours is above.
13
+
14
+ It measures agreement, not truth: an official value is a reference, and two
15
+ models that agree can both be wrong. Pure functions, no I/O.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import math
21
+ from collections.abc import Callable, Collection, Hashable, Mapping, Sequence
22
+ from dataclasses import dataclass
23
+ from itertools import pairwise
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class Agreement:
28
+ """How one component of ours stands against the reference."""
29
+
30
+ component: str
31
+ #: How many pairs.
32
+ n: int
33
+ #: The mean of ours minus the reference: positive means ours is higher.
34
+ bias: float
35
+ #: The mean absolute difference.
36
+ mae: float
37
+ #: The root of the mean squared difference.
38
+ rmse: float
39
+ #: Pearson's correlation; ``None`` with fewer than three pairs or no variance.
40
+ r: float | None
41
+ #: The share of pairs in the same class; ``None`` when the component is not classified.
42
+ same_class: float | None = None
43
+ #: The share of pairs with ours at least one class above: the direction that alarms.
44
+ above: float | None = None
45
+
46
+
47
+ def pearson(xs: Sequence[float], ys: Sequence[float]) -> float | None:
48
+ """Pearson's correlation; ``None`` with fewer than three pairs or no variance."""
49
+ n = len(xs)
50
+ if n < 3:
51
+ return None
52
+ mean_x, mean_y = sum(xs) / n, sum(ys) / n
53
+ sxy = sum((x - mean_x) * (y - mean_y) for x, y in zip(xs, ys, strict=True))
54
+ sxx = sum((x - mean_x) ** 2 for x in xs)
55
+ syy = sum((y - mean_y) ** 2 for y in ys)
56
+ if sxx == 0 or syy == 0:
57
+ return None
58
+ return sxy / math.sqrt(sxx * syy)
59
+
60
+
61
+ def bands(lower_bounds: Sequence[float]) -> Callable[[float], int]:
62
+ """A ``classify`` for :func:`compare`: the rank of the band a value falls in.
63
+
64
+ ``lower_bounds`` are the lower edges of the bands above the lowest, in
65
+ growing order: a value below the first is in band 0, one at or above the
66
+ last is in the highest.
67
+ """
68
+ edges = tuple(lower_bounds)
69
+ if any(b <= a for a, b in pairwise(edges)):
70
+ raise ValueError(f"lower_bounds must grow, got {edges}")
71
+
72
+ def classify(value: float) -> int:
73
+ return sum(1 for edge in edges if value >= edge)
74
+
75
+ return classify
76
+
77
+
78
+ def pair[K: Hashable](
79
+ ours: Mapping[K, Mapping[str, float | None]],
80
+ reference: Mapping[K, Mapping[str, float | None]],
81
+ ) -> dict[str, list[tuple[float, float]]]:
82
+ """The pairs ``(ours, reference)`` of each component, on the keys both have.
83
+
84
+ A key is whatever tells two values to be the same thing: a place and a
85
+ day. A component missing or ``None`` on either side gives no pair: not
86
+ measured is not zero. The pairs follow the order of ``ours``.
87
+ """
88
+ out: dict[str, list[tuple[float, float]]] = {}
89
+ for key, values in ours.items():
90
+ other = reference.get(key)
91
+ if other is None:
92
+ continue
93
+ for component, value in values.items():
94
+ against = other.get(component)
95
+ if value is None or against is None:
96
+ continue
97
+ out.setdefault(component, []).append((value, against))
98
+ return out
99
+
100
+
101
+ def compare(
102
+ pairs: Mapping[str, Sequence[tuple[float, float]]],
103
+ *,
104
+ classify: Callable[[float], int] | None = None,
105
+ classified: Collection[str] = ("fwi",),
106
+ ) -> list[Agreement]:
107
+ """The agreement of each component, in the order of ``pairs``; one with no pairs is left out.
108
+
109
+ ``classify`` turns a value into the rank of its class (0 the lowest): with
110
+ it, the components named in ``classified`` also get ``same_class`` and
111
+ ``above``. The classes are the caller's: the danger classes of a service,
112
+ or the bands of a score.
113
+ """
114
+ out: list[Agreement] = []
115
+ for component, values in pairs.items():
116
+ if not values:
117
+ continue
118
+ mine = [a for a, _ in values]
119
+ theirs = [b for _, b in values]
120
+ diff = [a - b for a, b in values]
121
+ n = len(values)
122
+ same = above = None
123
+ if classify is not None and component in classified:
124
+ classes = [(classify(a), classify(b)) for a, b in values]
125
+ same = sum(1 for a, b in classes if a == b) / n
126
+ above = sum(1 for a, b in classes if a > b) / n
127
+ out.append(
128
+ Agreement(
129
+ component=component,
130
+ n=n,
131
+ bias=sum(diff) / n,
132
+ mae=sum(abs(d) for d in diff) / n,
133
+ rmse=math.sqrt(sum(d * d for d in diff) / n),
134
+ r=pearson(mine, theirs),
135
+ same_class=same,
136
+ above=above,
137
+ )
138
+ )
139
+ return out
140
+
141
+
142
+ __all__ = ["Agreement", "bands", "compare", "pair", "pearson"]
@@ -0,0 +1,78 @@
1
+ """Where the calibration lives: a folder the application names.
2
+
3
+ The scoring engines read their thresholds, weights and class cut-offs from
4
+ YAML files. Those numbers are calibration: they belong to whoever measured
5
+ them, so this package ships none. The application says once where they are:
6
+
7
+ from limen_core import calibration
8
+ calibration.use("/path/to/config")
9
+
10
+ and inside that folder the engines look for ``hazards/<hazard>.yaml``
11
+ (``landslide``, ``flood``, ``wildfire``), ``hazards/cascades.yaml`` and
12
+ ``soglie_frane_regionali.yaml``. Without :func:`use`, the folder named by the
13
+ environment variable ``LIMEN_CALIBRATION_DIR`` is taken.
14
+
15
+ A loader given an explicit path never looks here.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import os
21
+ from pathlib import Path
22
+ from typing import Final
23
+
24
+ #: The environment variable read when :func:`use` was not called.
25
+ ENV: Final = "LIMEN_CALIBRATION_DIR"
26
+ #: The folder of the per-hazard files, inside the calibration folder.
27
+ HAZARDS_DIR: Final = "hazards"
28
+
29
+ _directory: Path | None = None
30
+
31
+
32
+ class CalibrationMissingError(RuntimeError):
33
+ """No calibration folder was named: neither :func:`use` nor the environment variable."""
34
+
35
+
36
+ def use(directory: Path | str) -> None:
37
+ """Name the folder of the calibration files, and forget what was loaded from another one."""
38
+ global _directory
39
+ _directory = Path(directory)
40
+ clear()
41
+
42
+
43
+ def clear() -> None:
44
+ """Forget the files already read, so that the next load reads them again."""
45
+ from limen_core.cascades import config as cascades
46
+ from limen_core.scoring import regional_thresholds
47
+
48
+ regional_thresholds._load_cached.cache_clear()
49
+ cascades._load_cached.cache_clear()
50
+
51
+
52
+ def directory() -> Path:
53
+ """The calibration folder; :class:`CalibrationMissingError` when none was named."""
54
+ if _directory is not None:
55
+ return _directory
56
+ named = os.environ.get(ENV)
57
+ if named:
58
+ return Path(named)
59
+ raise CalibrationMissingError(
60
+ "no calibration folder: call limen_core.calibration.use(folder), "
61
+ f"or set {ENV}; the engines ship no thresholds of their own"
62
+ )
63
+
64
+
65
+ def hazard_file(name: str) -> Path:
66
+ """The file ``name`` of the per-hazard folder (``landslide.yaml``, ``cascades.yaml``)."""
67
+ return directory() / HAZARDS_DIR / name
68
+
69
+
70
+ __all__ = [
71
+ "ENV",
72
+ "HAZARDS_DIR",
73
+ "CalibrationMissingError",
74
+ "clear",
75
+ "directory",
76
+ "hazard_file",
77
+ "use",
78
+ ]
@@ -0,0 +1,16 @@
1
+ """Regole di cascata fra pericoli (#58): configurazione e funzioni pure."""
2
+
3
+ from limen_core.cascades.config import CascadeRules, load_cascades
4
+ from limen_core.cascades.rules import (
5
+ JointCell,
6
+ joint_rain_cells,
7
+ post_fire_flood_multiplier,
8
+ )
9
+
10
+ __all__ = [
11
+ "CascadeRules",
12
+ "JointCell",
13
+ "joint_rain_cells",
14
+ "load_cascades",
15
+ "post_fire_flood_multiplier",
16
+ ]
@@ -0,0 +1,76 @@
1
+ """I tre pericoli di un comune diventano un numero solo.
2
+
3
+ La colonna della dashboard mostra i pericoli affiancati — ognuno con il suo
4
+ punteggio e la sua classe — e accanto un numero che dice quali comuni
5
+ guardare per primi. Questo modulo è quel numero, ed è una funzione pura:
6
+ nessun accesso al database, nessuna soglia scritta qui dentro.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from collections.abc import Mapping
12
+ from typing import NamedTuple
13
+
14
+ from limen_core.cascades.config import AttentionRule
15
+ from limen_core.models.risk import RiskLevel
16
+
17
+ #: Ordine delle classi, per confrontare una soglia con una classe.
18
+ _ORDINE: tuple[RiskLevel, ...] = (
19
+ RiskLevel.None_,
20
+ RiskLevel.Low,
21
+ RiskLevel.Moderate,
22
+ RiskLevel.High,
23
+ RiskLevel.VeryHigh,
24
+ )
25
+
26
+
27
+ def at_or_above(level: RiskLevel, floor: RiskLevel) -> bool:
28
+ return _ORDINE.index(level) >= _ORDINE.index(floor)
29
+
30
+
31
+ class HazardStanding(NamedTuple):
32
+ """Come sta un pericolo su un comune, per comporre il numero unico."""
33
+
34
+ #: `punteggio per uno piu l'esposizione`, la stessa formula degli alert.
35
+ priority: float
36
+ level: RiskLevel
37
+ #: Falso quando il segnale dinamico non è arrivato (#143). Un pericolo
38
+ #: non misurato vale zero *per costruzione*, e quello zero non è una
39
+ #: buona notizia da mettere in media con le altre.
40
+ measured: bool = True
41
+
42
+
43
+ def attention_index(
44
+ per_hazard: Mapping[str, HazardStanding],
45
+ *,
46
+ rule: AttentionRule,
47
+ ) -> float | None:
48
+ """Un numero per comune, dai pericoli che lo riguardano.
49
+
50
+ Il risultato è il massimo delle priorità, aumentato quando i pericoli
51
+ oltre soglia sono più di uno. Non è una somma, e la ragione si vede con
52
+ due numeri: sommando, un comune con tre pericoli a 0,40 (totale 1,20)
53
+ passerebbe davanti a uno con un versante a 0,80, che è l'unico dei due
54
+ dove sta per succedere qualcosa.
55
+
56
+ **I pericoli non misurati restano fuori**, dal massimo e dal conteggio.
57
+ Un incendio senza catena FWI vale zero per costruzione: contarlo come
58
+ «sotto soglia» abbassa il comune due volte, una perché non alza il
59
+ massimo e una perché non conta come pericolo concomitante. E il secondo
60
+ effetto è il peggiore — due pericoli su tre misurati e concomitanti
61
+ perderebbero l'incremento per colpa del terzo, di cui non sappiamo
62
+ niente.
63
+
64
+ ``None`` quando non c'è **niente** di misurato: è l'unica risposta vera,
65
+ e chi la mostra deve dire «non misurato», non «zero».
66
+ """
67
+ noti = {h: s for h, s in per_hazard.items() if s.measured}
68
+ if not noti:
69
+ return None
70
+ massimo = max(s.priority for s in noti.values())
71
+ if not rule.enabled or rule.multi_hazard_bump <= 0.0:
72
+ return massimo
73
+ oltre = sum(1 for s in noti.values() if at_or_above(s.level, rule.min_level))
74
+ if oltre < 2:
75
+ return massimo
76
+ return massimo * (1.0 + rule.multi_hazard_bump * (oltre - 1))
@@ -0,0 +1,140 @@
1
+ """Schema della configurazione delle cascate (#58).
2
+
3
+ Un file a sé, `config/hazards/cascades.yaml`, e non un blocco dentro un
4
+ pericolo: una cascata non appartiene a nessuno dei due, dice cosa un pericolo
5
+ passato fa a un pericolo futuro e vive fra i due.
6
+
7
+ Caricato e validato come le soglie dei pericoli, con lo stesso schema strict:
8
+ un refuso in una regola di cascata deve fermare l'avvio, non scoprirsi come
9
+ un moltiplicatore silenziosamente a zero.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from functools import cache
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import yaml
19
+ from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
20
+
21
+ from limen_core import calibration
22
+ from limen_core.models.risk import RiskLevel
23
+
24
+ CASCADES_DIR = calibration.HAZARDS_DIR
25
+ CASCADES_FILE = "cascades.yaml"
26
+
27
+
28
+ def cascades_path() -> Path:
29
+ """Il file delle cascate, risolto come le soglie dei pericoli."""
30
+ return calibration.hazard_file(CASCADES_FILE)
31
+
32
+
33
+ class _Strict(BaseModel):
34
+ model_config = ConfigDict(extra="forbid", strict=True, frozen=True)
35
+
36
+
37
+ class PostFireFloodRule(_Strict):
38
+ """Incendio → alluvione: suolo idrofobico che amplifica il ramo pluviale.
39
+
40
+ Una campana gaussiana come il post-incendio delle frane, e con numeri
41
+ suoi: l'idrofobicità del suolo si esaurisce prima della perdita di
42
+ radici, quindi la finestra è più corta.
43
+ """
44
+
45
+ enabled: bool
46
+ window_months: float = Field(..., gt=0.0)
47
+ peak_months: float = Field(..., ge=0.0)
48
+ curve_denominator: float = Field(..., gt=0.0)
49
+ max_multiplier: float = Field(..., ge=1.0)
50
+
51
+ @model_validator(mode="after")
52
+ def _peak_inside_window(self) -> PostFireFloodRule:
53
+ if self.peak_months > self.window_months:
54
+ raise ValueError(
55
+ f"post_fire_flood.peak_months ({self.peak_months}) cade fuori dalla "
56
+ f"finestra ({self.window_months}): l'amplificazione non arriverebbe "
57
+ "mai al massimo"
58
+ )
59
+ return self
60
+
61
+
62
+ class JointRainRule(_Strict):
63
+ """Pioggia estrema → un solo messaggio con due rischi."""
64
+
65
+ enabled: bool
66
+ min_level: RiskLevel
67
+ window_hours: float = Field(..., gt=0.0)
68
+
69
+ # In YAML la classe è una stringa e lo schema è strict, che pretende
70
+ # l'istanza dell'enum: la conversione va fatta prima della validazione.
71
+ # Un nome di classe inesistente resta un errore, ed è ciò che serve —
72
+ # una soglia scritta male non deve diventare silenziosamente "None".
73
+ @field_validator("min_level", mode="before")
74
+ @classmethod
75
+ def _coerce_level(cls, v: object) -> object:
76
+ return RiskLevel(v) if isinstance(v, str) else v
77
+
78
+
79
+ class AttentionRule(_Strict):
80
+ """Come i tre pericoli diventano **un** numero per comune.
81
+
82
+ Non una somma. Sommare i tre punteggi inverte le priorità in modo
83
+ dimostrabile — 0,40+0,40+0,40 supererebbe 0,80+0+0, cioè tre pericoli
84
+ blandi passerebbero davanti a un versante sopra la soglia alta — e i tre
85
+ numeri non sono nemmeno commensurabili: hanno calibrazioni diverse, e
86
+ 0,4 di incendio non è la stessa quantità di pericolo di 0,4 di frana.
87
+
88
+ Si prende il **massimo** della priorità già definita per gli alert
89
+ (`punteggio per uno piu l'esposizione`), e si aggiunge un incremento quando più
90
+ di un pericolo è oltre soglia: due pericoli insieme sullo stesso comune
91
+ sono una notizia diversa da uno solo, ma non il doppio.
92
+ """
93
+
94
+ enabled: bool = True
95
+ #: Da quale classe un pericolo "conta" per l'incremento.
96
+ min_level: RiskLevel = RiskLevel.Moderate
97
+ #: Moltiplicativo, come l'esposizione: `per (1 + bump)` per ogni pericolo
98
+ #: oltre il primo. 0 = nessun incremento, cioè il solo massimo.
99
+ multi_hazard_bump: float = Field(default=0.15, ge=0.0, le=1.0)
100
+
101
+ # Stessa ragione della regola sulla pioggia congiunta: in YAML la classe
102
+ # è una stringa e lo schema è strict, quindi la conversione va fatta
103
+ # prima della validazione.
104
+ @field_validator("min_level", mode="before")
105
+ @classmethod
106
+ def _coerce_level(cls, v: object) -> object:
107
+ return RiskLevel(v) if isinstance(v, str) else v
108
+
109
+
110
+ class CascadeRules(_Strict):
111
+ """Tutte le regole di cascata."""
112
+
113
+ post_fire_flood: PostFireFloodRule
114
+ joint_rain: JointRainRule
115
+ # Assente ⇒ i valori di default, che sono il comportamento più prudente:
116
+ # il massimo, con un incremento piccolo quando i pericoli sono più di uno.
117
+ attention: AttentionRule = Field(default_factory=lambda: AttentionRule())
118
+
119
+
120
+ def load_cascades(path: Path | str | None = None) -> CascadeRules:
121
+ """Carica e valida le regole. ``path`` esplicito scavalca la cache."""
122
+ if path is None:
123
+ return _load_cached()
124
+ raw: dict[str, Any] = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {}
125
+ return CascadeRules.model_validate(raw)
126
+
127
+
128
+ @cache
129
+ def _load_cached() -> CascadeRules:
130
+ raw: dict[str, Any] = yaml.safe_load(cascades_path().read_text(encoding="utf-8")) or {}
131
+ return CascadeRules.model_validate(raw)
132
+
133
+
134
+ __all__ = [
135
+ "CascadeRules",
136
+ "JointRainRule",
137
+ "PostFireFloodRule",
138
+ "cascades_path",
139
+ "load_cascades",
140
+ ]
@@ -0,0 +1,124 @@
1
+ """Le regole di cascata, come funzioni pure (#58).
2
+
3
+ Nessuna delle due decide da sé: prendono la configurazione come argomento e
4
+ non leggono né database né orologio. È la stessa disciplina dei motori di
5
+ scoring, per la stessa ragione — una cascata che dipendesse dall'ambiente non
6
+ sarebbe riproducibile in un backtest.
7
+
8
+ Il differenziatore di Limen rispetto a un sistema mono-rischio sta qui: le
9
+ interazioni fra pericoli. Ma sono interazioni *asimmetriche* e vanno lette
10
+ come tali. Un incendio cambia il suolo e quindi l'alluvione futura; una
11
+ pioggia estrema colpisce frana e alluvione insieme senza che l'una causi
12
+ l'altra. Regole diverse, forme diverse.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import math
18
+ from dataclasses import dataclass
19
+ from datetime import datetime, timedelta
20
+
21
+ from limen_core.cascades.config import JointRainRule, PostFireFloodRule
22
+ from limen_core.models.hazard import HazardType
23
+ from limen_core.models.risk import RiskLevel
24
+
25
+ __all__ = ["JointCell", "joint_rain_cells", "post_fire_flood_multiplier"]
26
+
27
+ _LEVEL_ORDER: tuple[RiskLevel, ...] = (
28
+ RiskLevel.None_,
29
+ RiskLevel.Low,
30
+ RiskLevel.Moderate,
31
+ RiskLevel.High,
32
+ RiskLevel.VeryHigh,
33
+ )
34
+
35
+
36
+ def _at_least(level: RiskLevel, threshold: RiskLevel) -> bool:
37
+ return _LEVEL_ORDER.index(level) >= _LEVEL_ORDER.index(threshold)
38
+
39
+
40
+ def post_fire_flood_multiplier(
41
+ months_since_fire: float | None, *, rule: PostFireFloodRule
42
+ ) -> float:
43
+ """Amplificazione del ramo pluviale su un suolo percorso dal fuoco.
44
+
45
+ Restituisce un moltiplicatore in ``[1.0, rule.max_multiplier]``. Vale
46
+ esattamente 1.0 — nessuna amplificazione — quando non c'è un incendio
47
+ recente, quando la regola è spenta, o quando la finestra è chiusa.
48
+
49
+ La curva è una campana centrata su ``peak_months``: l'effetto non è
50
+ massimo subito perché serve che la pioggia trovi la crosta idrofobica
51
+ ancora intatta, e decade con la ricrescita della vegetazione.
52
+
53
+ ``None`` significa "nessun incendio noto", che non è "incendio molto
54
+ vecchio": entrambi danno 1.0, ma sono fatti diversi e il chiamante che
55
+ volesse distinguerli ha il dato a monte.
56
+ """
57
+ if not rule.enabled or months_since_fire is None:
58
+ return 1.0
59
+ if months_since_fire < 0.0 or months_since_fire > rule.window_months:
60
+ return 1.0
61
+ bell = math.exp(-((months_since_fire - rule.peak_months) ** 2) / rule.curve_denominator)
62
+ return 1.0 + (rule.max_multiplier - 1.0) * bell
63
+
64
+
65
+ @dataclass(frozen=True, slots=True)
66
+ class JointCell:
67
+ """Una cella che supera la soglia di due pericoli nella stessa finestra."""
68
+
69
+ cell_id: str
70
+ #: I pericoli coinvolti, con la classe raggiunta da ciascuno.
71
+ levels: dict[HazardType, RiskLevel]
72
+ #: Il punteggio più alto fra i pericoli coinvolti, per ordinare la lista.
73
+ worst_score: float
74
+
75
+ @property
76
+ def hazards(self) -> tuple[HazardType, ...]:
77
+ """I pericoli, in ordine stabile: due esecuzioni danno la stessa lista."""
78
+ return tuple(sorted(self.levels, key=lambda h: h.value))
79
+
80
+
81
+ def joint_rain_cells(
82
+ per_hazard: dict[HazardType, dict[str, tuple[RiskLevel, float, datetime]]],
83
+ *,
84
+ rule: JointRainRule,
85
+ now: datetime,
86
+ ) -> list[JointCell]:
87
+ """Le celle che meritano **un** messaggio invece di due.
88
+
89
+ ``per_hazard`` mappa ogni pericolo alle sue celle:
90
+ ``{cell_id: (classe, punteggio, momento della valutazione)}``.
91
+
92
+ Una cella entra quando almeno due pericoli la portano a
93
+ ``rule.min_level`` o oltre, **e** le rispettive valutazioni cadono entro
94
+ ``rule.window_hours`` da ``now``. La finestra serve perché gli sweep dei
95
+ pericoli girano in momenti diversi: senza, la lettura di ieri di un
96
+ pericolo si combinerebbe con quella di adesso dell'altro e produrrebbe un
97
+ allarme congiunto che non è mai esistito in nessun istante.
98
+
99
+ Ordinate per punteggio peggiore decrescente, con il cell_id a spareggio:
100
+ la lista finisce in un messaggio, e un ordine instabile la farebbe
101
+ sembrare cambiata a ogni ciclo.
102
+ """
103
+ if not rule.enabled:
104
+ return []
105
+
106
+ cutoff = now - timedelta(hours=rule.window_hours)
107
+ by_cell: dict[str, dict[HazardType, tuple[RiskLevel, float]]] = {}
108
+ for hazard, cells in per_hazard.items():
109
+ for cell_id, (level, score, seen_at) in cells.items():
110
+ if seen_at < cutoff or not _at_least(level, rule.min_level):
111
+ continue
112
+ by_cell.setdefault(cell_id, {})[hazard] = (level, score)
113
+
114
+ joint = [
115
+ JointCell(
116
+ cell_id=cell_id,
117
+ levels={h: lvl for h, (lvl, _) in found.items()},
118
+ worst_score=max(score for _, score in found.values()),
119
+ )
120
+ for cell_id, found in by_cell.items()
121
+ if len(found) >= 2
122
+ ]
123
+ joint.sort(key=lambda j: (-j.worst_score, j.cell_id))
124
+ return joint