# rainfall-thresholds > A small Python library with no dependencies for the rainfall thresholds of shallow landslides (Caine intensity-duration power law): rainfall events from an hourly series, how far an event is above a threshold, fitting a threshold on past landslides, measuring its cost in false alarms, and T5 thresholds for Italy fitted on the 5,974 landslides of e-ITALICA. It also gives the answers as facts, an MCP server and a check that a text quotes the numbers right. Source: https://agentengineering.it/rainfall-thresholds/ # rainfall-thresholds **How much rain does it take to set off a landslide?** A small, dependency-free Python library that answers that question with the rainfall thresholds used in landslide science: turn an hourly rain-gauge series into rainfall events, compare them with a threshold, and fit your own threshold from past landslides. It ships ready-to-use thresholds for Italy, fitted on 5,974 real landslides. > **A threshold exceeded is not an alert.** It says the rain is like the rain > that triggered landslides before. The official alert in Italy is the > criticality bulletin of the > [Dipartimento della Protezione Civile](https://rischi.protezionecivile.gov.it/it/meteo-idro/allertamento/). **What it does not do.** It does not fetch rain: you bring the series, from a gauge, a radar or a model. It does not say where a landslide will happen, and it does not issue warnings. It does not know whether your radar can see: mark the hours it could not measure as `None`. [![ci](https://github.com/agent-engineering-studio/rainfall-thresholds/actions/workflows/ci.yml/badge.svg)](https://github.com/agent-engineering-studio/rainfall-thresholds/actions/workflows/ci.yml) [![PyPI](https://img.shields.io/pypi/v/rainfall-thresholds)](https://pypi.org/project/rainfall-thresholds/) [![docs](https://img.shields.io/badge/docs-agentengineering.it-blue)](https://agentengineering.it/rainfall-thresholds/) [![Python](https://img.shields.io/pypi/pyversions/rainfall-thresholds)](https://pypi.org/project/rainfall-thresholds/) [![Dependencies: none](https://img.shields.io/badge/dependencies-none-brightgreen)](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/pyproject.toml) [![License: Apache-2.0](https://img.shields.io/badge/license-Apache--2.0-blue)](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/LICENSE) Log-log chart of rainfall duration against mean intensity. Thousands of grey dots, each a rainfall event that triggered a landslide in Italy, sit above a blue line, the T5 threshold. A red star marks an example storm of 82 mm in 10 hours, well above the line. Every grey dot is a storm that triggered a landslide in Italy (e-ITALICA catalogue). The blue line is the threshold this library fits: only 5 % of those storms fall below it. The red star is the storm from the [quick start](#quick-start). **Read the story:** [Basta questa pioggia per far franare?](https://agentengineering.it/blog/soglie-pioggia-frane-rainfall-thresholds/) ([English](https://agentengineering.it/en/blog/soglie-pioggia-frane-rainfall-thresholds/)), the last episode of the Open Data series, after [dpc-radar](https://agentengineering.it/blog/pioggia-radar-protezione-civile-dpc-radar/) and [ispra-idrogeo](https://agentengineering.it/blog/frane-pericolo-idrogeologico-ispra-idrogeo/). **Try it** in the browser: [the intensity-duration plane](https://agentengineering.it/rainfall-thresholds/explainer/). --- ## Contents - [The idea in 30 seconds](#the-idea-in-30-seconds) - [How it works](#how-it-works) - [Install](#install) - [Quick start](#quick-start) - [Step by step](#step-by-step) - [1. From hourly rain to rainfall events](#1-from-hourly-rain-to-rainfall-events) - [2. Comparing an event with a threshold](#2-comparing-an-event-with-a-threshold) - [3. Fitting your own threshold](#3-fitting-your-own-threshold) - [4. Measuring what it costs](#4-measuring-what-it-costs) - [Thresholds for Italy](#thresholds-for-italy) - [Recipe: check a rain gauge](#recipe-check-a-rain-gauge) - [API at a glance](#api-at-a-glance) - [Benchmark](#benchmark) - [Notebooks and Docker](#notebooks-and-docker) - [A calibration bench for public bodies](#a-calibration-bench-for-public-bodies) - [For assistants and agents](#for-assistants-and-agents) - [Roadmap: what is measured, what is open](#roadmap-what-is-measured-what-is-open) - [Good to know](#good-to-know) - [References](#references) · [Citing](#citing) · [Contributing](#contributing) ## The idea in 30 seconds Shallow landslides start when the soil gets too wet. What makes it too wet is a mix of **how hard** it rains and **for how long**: - a short, violent downpour can do it: 30 mm in 2 hours; - so can a long, gentle rain: 60 mm over three days. In 1980 Nels Caine noticed that, on a log-log chart of *duration* against *mean intensity*, the storms that triggered landslides sit above a straight line. That line is the **rainfall threshold**: ``` I = α · D^(-β) I mean rainfall intensity (mm/h) D rainfall duration (hours) α how high the line sits β how fast it drops with duration ``` Above the line: rain like the rain that triggered landslides in the past. Below it: rain that very rarely did. That is all a threshold says, and it is why thresholds are at the heart of many landslide early-warning systems. This library gives you the three pieces around that line, in plain Python with no dependencies. ## How it works ```mermaid flowchart LR A["🌧️ Hourly rain
(timestamp, mm)"] -->|reconstruct_events| B["Rainfall events
duration · total · intensity"] B -->|strongest_event| C["Event that matters"] C -->|"threshold.exceedance()"| D{"Above the
threshold?"} D -->|"> 0"| E["⚠️ Conditions like
past landslides"] D -->|"< 0"| F["✅ Below the line"] G["📚 Past landslides
(duration, intensity)"] -->|fit_threshold| H["PowerLawThreshold
α, β"] I["🇮🇹 ITALICA_T5
ready-made for Italy"] --> H H --> D ``` | Step | What you have | What you call | What you get | |---|---|---|---| | 1 | an hourly rain series | `reconstruct_events`, `strongest_event` | rainfall events, each with duration, total and intensity | | 2 | an event and a threshold | `PowerLawThreshold.intensity` / `.cumulated` / `.exceedance` | how much rain the threshold needs, and how far above or below it you are | | 3 | a catalogue of landslide-triggering events | `fit_threshold` | your own threshold | ## Install ```bash pip install rainfall-thresholds ``` Python 3.12 or newer. No dependencies: not even NumPy. ## Quick start A storm over Calabria, southern Italy: 82 mm in about ten hours. Is it landslide weather? ```python from datetime import UTC, datetime, timedelta from rainfall_thresholds import ITALICA_T5, macroregion_of, reconstruct_events, strongest_event # Hourly rain from a gauge, in mm start = datetime(2026, 10, 10, tzinfo=UTC) hourly_mm = [0, 2, 8, 15, 22, 18, 9, 4, 0, 1, 3, 0, 0] series = [(start + timedelta(hours=h), mm) for h, mm in enumerate(hourly_mm)] # 1. Pick the threshold for the region threshold = ITALICA_T5[macroregion_of("Calabria") or "italy"] # "southern" # 2. Cut the series into rainfall events and take the one that matters events = reconstruct_events(series, no_rain_break_hours=6, min_event_mm=2.0) event = strongest_event(events, threshold) assert event is not None # 3. Compare print(f"{event.total_mm:.0f} mm in {event.duration_hours:.0f} h = {event.intensity_mm_h:.1f} mm/h") print(f"T5 at that duration: {threshold.intensity(event.duration_hours):.1f} mm/h") print(f"{threshold.exceedance(event.intensity_mm_h, event.duration_hours):+.2f} decades") ``` ``` 82 mm in 10 h = 8.2 mm/h T5 at that duration: 2.0 mm/h +0.62 decades ``` The storm is about four times as intense as the threshold (10^0.62 ≈ 4.2): it is the red star in the chart at the top. ## Step by step ### 1. From hourly rain to rainfall events A rain gauge gives you one number per hour. A threshold needs *events*: a start, an end, a total. `reconstruct_events` cuts the series with two simple rules: - **`no_rain_break_hours`**: this many dry hours in a row end an event; - **`min_event_mm`**: events with less rain than this are dropped as noise. An event runs from its first to its last wet hour, so short dry spells inside a storm stay in the same event. Bar chart of 36 hours of rain. Hours 1 to 9 form event 1, 30 mm in 9 hours, despite a 2-hour dry gap. Eight dry hours close it. A 1 mm drizzle at hours 18 and 19 is dropped. Hours 28 to 33 form event 2, 33 mm in 6 hours. ```python threshold = ITALICA_T5["southern"] events = reconstruct_events(series, no_rain_break_hours=6, min_event_mm=2.0) for e in events: print(e.start, e.end, e.duration_hours, e.total_mm, e.intensity_mm_h) current = strongest_event(events, threshold) # the event furthest above the threshold ``` **Which event?** A storm, six dry hours and then a little drizzle are two events. `latest_event` gives the drizzle; `strongest_event` gives the storm. For monitoring, pass the events of the window you watch (for example the last 48 hours) to `strongest_event`, so an old storm does not stay forever. Each event is a frozen `RainfallEvent` with `start`, `end`, `duration_hours`, `total_mm`, `unmeasured_hours`, `source` and the `intensity_mm_h` and `fully_measured` properties. > **Not measured is not dry.** The series should be hourly and without gaps: > a dry hour is `0`, an hour that was not measured (a missing frame, a gauge > that did not report, a place the radar cannot see) is `None`. A `None` hour > adds no rain and does not count towards the dry break, so a gap never splits > an event. The event counts it in `unmeasured_hours`, and its total is then a > lower bound. If your gauge skips dry hours, fill them in with `0`. Give the events a `source` (`reconstruct_events(..., source="DPC SRT1")`): the Italian thresholds are fitted on rain gauges, and radar rain is not gauge rain. The label is carried, never interpreted. ### 2. Comparing an event with a threshold A `PowerLawThreshold` answers three questions for an event of a given duration: | Method | Question | Unit | |---|---|---| | `intensity(D)` | How intense must rain be, on average, to reach the line? | mm/h | | `cumulated(D)` | How much rain in total must fall to reach the line? | mm | | `exceedance(I, D)` | How far above (+) or below (−) the line is this event? | decades | `cumulated` is usually the easiest to talk about. With the threshold for northern Italy: ```python from rainfall_thresholds import ITALICA_T5 t = ITALICA_T5["northern"] for d in (1, 6, 24, 72): print(f"{d:>3} h {t.cumulated(d):5.1f} mm {t.intensity(d):5.2f} mm/h") ``` ``` 1 h 6.4 mm 6.40 mm/h 6 h 15.3 mm 2.55 mm/h 24 h 30.0 mm 1.25 mm/h 72 h 51.3 mm 0.71 mm/h ``` Longer rain needs more water in total, but less per hour. **Reading `exceedance`.** It is `log10(I / I(D))`, so it is scale-free and easy to put on a dashboard. Four 24-hour events against the national threshold (28 mm in 24 h): | Rain in 24 h | Mean intensity | `exceedance` | In words | |---:|---:|---:|---| | 12 mm | 0.5 mm/h | −0.37 | well below the line | | 24 mm | 1.0 mm/h | −0.07 | just below | | 58 mm | 2.4 mm/h | +0.31 | twice the threshold intensity | | 288 mm | 12 mm/h | +1.01 | ten times: an extreme event | A dry event (zero intensity) gives `-inf`. ### 3. Fitting your own threshold Have a list of landslides and the rain that triggered them? Fit a threshold for your own area: ```python from rainfall_thresholds import fit_threshold # (duration in hours, mean intensity in mm/h) of rain that triggered landslides triggering_events = [ (3, 9.0), (5, 4.0), (6, 6.5), (10, 5.5), (12, 3.1), (24, 2.4), (30, 1.4), (48, 1.1), (72, 1.0), (96, 0.6), ] fit = fit_threshold(triggering_events, percentile=5) t = fit.threshold print(f"T5: I = {t.alpha:.2f} · D^-{t.beta:.3f} ({fit.n_events} events)") print(f"at 24 h: {t.intensity(24):.2f} mm/h, i.e. {t.cumulated(24):.0f} mm") ``` ``` T5: I = 14.78 · D^-0.737 (10 events) at 24 h: 1.42 mm/h, i.e. 34 mm ``` (Ten events are enough for an example, not for a real threshold: published thresholds use hundreds.) What `fit_threshold` does, in two steps: 1. **Best-fit line.** Least squares on `log I` against `log D` through all the events: the orange line below, returned as `fit.central`. 2. **Lower it.** Slide the line down, keeping its slope, until only `percentile` % of the events sit beneath it: the blue line, returned as `fit.threshold`. With `percentile=5` this is the **T5** threshold. Left: the e-ITALICA events on a log-log chart with an orange best-fit line and a parallel blue line lower down, the T5 threshold. Right: a histogram of the distance of each event from the best-fit line; the lowest 5 percent, left of -0.45, are highlighted in blue. This is the frequentist method of Brunetti et al. (2010) and Peruccacci et al. (2012), with one difference: they take the percentile from a Gaussian fitted to a kernel density of the residuals; this package takes it straight from the residuals. The two agree when the residuals are close to normal, and the empirical one makes no assumption about their shape. ### 4. Measuring what it costs T5 catches 95 % of past landslides by construction. What it does not say is how often it is exceeded when nothing happens. The `measure` functions answer both on the same scale, for any score that grows with danger (an exceedance, a 24-hour total, a probability): ```python from rainfall_thresholds import auc, skill, skill_at_budget # For each landslide, the highest score in the hours before it. landslides = [0.62, 0.31, 0.05, -0.08, 0.44] # For each unit you could alert on (cell-hours, municipality-days...). ordinary = [-0.9, -0.4, -0.2, 0.1, -0.6, -0.3, 0.2, -1.1, -0.5, -0.7] s = skill(landslides, ordinary, cutoff=0.0) # above the threshold = alert print(f"caught {s.caught} of {s.landslides}, {s.alert_share:.0%} of units on alert") print(f"discrimination {s.discrimination:.1f}, {s.alerts_per_caught:.1f} alerts per landslide") fair = skill_at_budget(landslides, ordinary, budget=0.10) # 10 % of units on alert print(f"at a 10 % budget: caught {fair.caught} of {fair.landslides}") print(f"AUC {auc(landslides, ordinary):.2f}") ``` ``` caught 4 of 5, 20% of units on alert discrimination 4.0, 0.5 alerts per landslide at a 10 % budget: caught 3 of 5 AUC 0.92 ``` To compare two scores, compare them **at the same budget**: counting at a fixed level rewards the score that alerts more. `None` is a score that was not measured: it is left out and counted in `unmeasured`, never read as zero. The definitions are those of Limen's backtests, and on the same inputs the results are identical. What this gives on real data was measured in Limen ([limen#243](https://github.com/agent-engineering-studio/limen/issues/243)), with the national curve on model rain (ERA5): 40.7 % of the e-ITALICA landslides above the threshold against 3.0 % of ordinary moments, and 0 of 286 landslides caught in the regions held out. A threshold fitted on rain gauges and applied to other rain is not the same threshold. ## Thresholds for Italy `ITALICA_T5` holds four T5 thresholds fitted with `fit_threshold(percentile=5)` on the 5,974 events of [e-ITALICA](https://doi.org/10.5281/zenodo.14204473) v4 with a positive duration and cumulated rainfall: | Key | α (mm/h) | β | Events | Rain needed in 24 h | in 72 h | |---|---:|---:|---:|---:|---:| | `"italy"` | 7.193 | 0.5685 | 5,974 | 28.3 mm | 45.5 mm | | `"northern"` | 6.400 | 0.5134 | 2,659 | 30.0 mm | 51.3 mm | | `"central"` | 7.953 | 0.6085 | 1,890 | 27.6 mm | 42.4 mm | | `"southern"` | 8.754 | 0.6449 | 1,425 | 27.1 mm | 40.0 mm | Line chart of the rain needed to reach T5 against duration, up to 168 hours, for Italy and its three macroregions. The lines overlap up to about 12 hours; after that the northern threshold needs the most rain, about 78 mm in a week, and the southern the least, about 54 mm. For short bursts the regions behave alike; over days, the north needs noticeably more rain than the south before landslides start. Pick the threshold from the region name with `macroregion_of`: ```python from rainfall_thresholds import ITALICA_T5, macroregion_of macroregion_of("Liguria") # "northern" macroregion_of("Abruzzo") # "central" macroregion_of("Bavaria") # None: not an Italian region threshold = ITALICA_T5[macroregion_of("Sicilia") or "italy"] ``` > **Abruzzo and Molise are in the centre**, unlike the ISTAT "Sud". Use > `macroregion_of` (or `MACROREGIONS`) rather than an ISTAT table, or the > threshold will not be the one fitted on that region's landslides. These numbers are **reproducible, not copied**: the catalogue ships with the tests and `tests/test_italy.py` refits all four thresholds from it on every run. They are not the thresholds published by the e-ITALICA authors, who use their own method and partitions; they are what this package's method gives on their data. ## Recipe: check a rain gauge Read an hourly CSV, find the current rainfall event and see where it stands: ```python import csv from datetime import datetime from rainfall_thresholds import ITALICA_T5, macroregion_of, reconstruct_events, strongest_event with open("gauge.csv", encoding="utf-8") as f: # columns: time, rain_mm (empty: not measured) series = [ (datetime.fromisoformat(r["time"]), float(r["rain_mm"]) if r["rain_mm"] else None) for r in csv.DictReader(f) ] threshold = ITALICA_T5[macroregion_of("Liguria") or "italy"] events = reconstruct_events(series, no_rain_break_hours=6, min_event_mm=2.0, source="rain gauge") event = strongest_event(events, threshold) if event is None: print("No rain event in the window") else: e = threshold.exceedance(event.intensity_mm_h, event.duration_hours) needed = threshold.cumulated(event.duration_hours) print( f"{event.start:%d %b %H:%M} → {event.end:%H:%M}: {event.total_mm:.0f} mm " f"(T5 needs {needed:.0f} mm in {event.duration_hours:.0f} h) → {e:+.2f}" ) ``` ``` 10 Oct 01:00 → 07:00: 78 mm (T5 needs 16 mm in 7 h) → +0.67 ``` Run it every hour on the last two or three days of data and you have the rainfall part of a simple monitoring loop: a number to watch, not an alert. ## API at a glance | Name | Kind | What it is | |---|---|---| | `PowerLawThreshold(alpha, beta)` | frozen dataclass | `I = α·D^(-β)`, with `.intensity(D)`, `.cumulated(D)`, `.exceedance(I, D)`, `.scaled(factor)` | | `reconstruct_events(series, *, no_rain_break_hours, min_event_mm, source=None)` | function | hourly `(datetime, mm or None)` pairs → `list[RainfallEvent]`; `None` is not measured | | `strongest_event(events, threshold)` | function | the event furthest above the threshold, or `None` | | `latest_event(events)` | function | the event that ended last, or `None` | | `RainfallEvent` | frozen dataclass | `start`, `end`, `duration_hours`, `total_mm`, `unmeasured_hours`, `source`, `.intensity_mm_h`, `.fully_measured` | | `fit_threshold(events, *, percentile=5.0)` | function | `(D, I)` pairs → `ThresholdFit` | | `ThresholdFit` | frozen dataclass | `threshold`, `central`, `percentile`, `n_events` | | `percentile_of(values, percentile)` | function | linear-interpolation percentile, same as NumPy's default | | `skill(landslides, ordinary, cutoff)` | function | landslides caught and units on alert at a cutoff → `Skill` | | `skill_at_budget(landslides, ordinary, budget, *, floor=None)` | function | the same at the cutoff that puts `budget` of the units on alert | | `cutoff_at_budget(ordinary, budget, *, floor=None)` | function | that cutoff | | `Skill` | frozen dataclass | `caught`, `landslides`, `alerts`, `ordinary`, `unmeasured`; `.hit_rate`, `.alert_share`, `.discrimination`, `.alerts_per_caught` | | `auc(landslides, ordinary)` | function | Mann-Whitney AUC, ties count half | | `facts.threshold_facts`, `assess_facts`, `fit_facts`, `trust_facts`, `margin_facts`, `published_facts` | functions | the same answers as JSON-ready dicts, with units and the alert rule | | `check.check_text(text, facts, *, question="")` | function | numbers of a text that are invented, rounded or in the wrong unit → `list[Misquote]` | | `mcp_server.create_server()`, `rainfall-thresholds-mcp` | MCP (extra `mcp`) | tools `threshold`, `assess`, `fit`, `trust`, `margin`, `published`, `check`; stdio or HTTP | | `ITALICA_T5` | read-only mapping | `"italy"`, `"northern"`, `"central"`, `"southern"` → `PowerLawThreshold` | | `MACROREGIONS` | read-only mapping | macroregion → set of region names (e-ITALICA spelling) | | `macroregion_of(region)` | function | region name or ISTAT region code (`8`, `"08"`) → macroregion, or `None` | | `ISTAT_REGIONS` | read-only mapping | ISTAT region code → region name | | `threshold_for(macroregion, thresholds=ITALICA_T5, *, default="italy")` | function | the threshold of a macroregion, or the default one | | `event_against_threshold(hours, threshold, *, no_rain_break_hours, min_event_mm, choice="latest", source=None, radar_gauge_factor=1.0)` | function | `{datetime: mm or None}` → `EventAssessment` or `None` | | `EventAssessment` | frozen dataclass | `event`, `threshold`, `borders_unmeasured`; `.threshold_mm_h`, `.threshold_mm`, `.ratio`, `.excess_decades`, `.at_least` | | `cumulate(hours, end, *, windows_hours)` | function | the totals of the last N hours → `{N: WindowTotal}`; no total when an hour is not measured | | `caine_excess(event, threshold, *, radar_gauge_factor=1.0)` | function | decades above the line, zero on or below it | | `api_kohler_linsley(daily_precip_mm, *, decay_k, initial=0.0)` | function | the Antecedent Precipitation Index, mm | | `api_factor(api_mm, *, fallback_baseline_mm, fallback_sigma_mm, sigma_min_mm, baseline_mm=None, sigma_mm=None)` | function | an API as a wetness factor in 0..1; 0.5 when not known | | `rain_to_threshold(event, threshold, *, more_hours, radar_gauge_factor=1.0)` | function | the rain still needed to reach the line if the event goes on → `{hours: mm}`; not a forecast | | `relative_total(hours, end, *, window_hours, reference_mm, saturation, reduction=0.0, longer_references_mm=None)` | function | the last hours against the place's own climatological reference, 0..1; `None` when no hour was read | | `EventAssessment.as_record(*, where, licence)` | method | the assessment as a fact of `opendata-record/v2`, a plain dict | | `CALIBRATION`, `calibration_of(region)` | mapping, function | how the line sits on the landslides of each region → `Calibration`: `events`, `below`, `.below_share`, `.interval()`, `.position` (`"high"`, `"low"`, `"as fitted"`), `duration_hours` | | `load_regional_catalogue()` | function | published regional thresholds with their sources → `RegionalCatalogue` of `RegionalThreshold` and `Source` | | `RainSource` | `typing.Protocol` | `hourly(points, start, end) -> dict[datetime, list[float or None]]`: what can feed the package | | `point_series(rain, index)` | function | the series of one point out of `RainSource.hourly` | Everything is fully typed (`py.typed`) and checked with `mypy --strict`. ## Benchmark A fixed set of known cases runs in CI: the storm of Melito di Porto Salvo on 10 October 2026 on the DPC radar, six e-ITALICA landslides, and two cases built to test one rule each. 0.1.0 passed **9 of 16** checks: it forgot a storm when a little drizzle followed it, and could not take an hour that was not measured. With `strongest_event` and `None` the library passes **13 of 16**. The three it misses are landslides under T5, as T5 allows by construction. The details, and what is not there yet, are in [`benchmarks/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/benchmarks). ```bash uv run python -m benchmarks.run ``` ## Notebooks and Docker Five [example notebooks](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/notebooks): the Italian thresholds over the e-ITALICA landslides, the storm of Melito on the DPC radar, fitting your own threshold, and how much to trust the line in each region with the rain still missing during a storm, with no network; and the join with the sister libraries, landslides dated by [ispra-idrogeo](https://agentengineering.it/ispra-idrogeo/) against radar rain from [dpc-radar](https://agentengineering.it/dpc-radar/). Open them with uv, or with Docker alone: ```bash uv run --group examples jupyter lab notebooks/ make docker # the bench (3001), the MCP server (8775), the notebooks (8881) docker compose up notebooks # the notebooks alone: http://localhost:8881 make docker-bench # the benchmark, in a container make down # stop and remove the containers ``` `make help` lists every command. The containers are named after the library (`rainfall-thresholds-ui`, `-mcp`, `-notebooks`) and the ports clash with no sister library, so all of them run on one machine; for a second copy of this one, change the prefix and the ports (`make docker NAME=rt-dev TARATURA_PORT=3101 ...`). ## A calibration bench for public bodies [`app/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/app) is a page in Italian, with Bootstrap Italia, for a public body: it opens on the e-ITALICA landslides of its region, fits a threshold on the ones that matter, compares it with the national one, measures its cost in false alarms on the body's own rain gauge, and exports it. It is not a warning system and reads no live rain. `docker compose up taratura`, then http://localhost:3001. [Riuso nella PA](https://agentengineering.it/rainfall-thresholds/riuso/) says, in Italian, what it does and what stays with the body. To explain what a threshold is, the docs site has [Try it](https://agentengineering.it/rainfall-thresholds/explainer/): an interactive intensity-duration plane that runs in the browser. ## For assistants and agents A language model may word the numbers; it should never compute them. The library gives them as data, and checks the words. - **Facts.** `rainfall_thresholds.facts`: `threshold_facts`, `assess_facts`, `fit_facts`, `trust_facts` (how the line sits on the landslides of a region), `margin_facts` (the rain still needed if the rain goes on) and `published_facts` (the thresholds of the literature for a region, with their sources) return plain dicts, with the unit in every key (`_mm`, `_mm_h`, `_h`, `_decades`), what the threshold was fitted on, and the rule that a threshold exceeded is not an alert. - **MCP server.** `pip install "rainfall-thresholds[mcp]"`, then `rainfall-thresholds-mcp` on standard input and output, or over HTTP (`--transport streamable-http`, port 8775, `/mcp`; `docker compose up mcp`). Seven tools: `threshold`, `assess`, `fit`, `trust`, `margin`, `published`, `check`. They compute only from what the call gives them: no network, no live rain. - **A check of the text.** `check_text(text, facts)` finds numbers invented, rounded the wrong way, or in the wrong unit: 30.9 mm written as 30.9 mm/h, the trap of every rainfall threshold. It knows that a number is a fact of its unit, not that it is said of the right thing. - **A faithfulness set.** `benchmarks/faithful.py`: questions, facts, and answers written by hand, one faithful and one with known faults; in CI the check must find exactly those faults (10 of 10 today). Answers of a model are not in it yet. - **For coding agents.** [`llms.txt`](https://agentengineering.it/rainfall-thresholds/llms.txt), [`llms-full.txt`](https://agentengineering.it/rainfall-thresholds/llms-full.txt) and an [agent skill](https://agentengineering.it/rainfall-thresholds/skills/rainfall-thresholds/SKILL.md) with the traps a model falls into when it writes this code from memory. The base package still has no dependencies: the MCP SDK comes only with the `mcp` extra. ## Roadmap: what is measured, what is open The plan is in [#4](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/4), and the [roadmap page](https://agentengineering.it/rainfall-thresholds/roadmap/) says what each phase measured. - **Done:** the benchmark (#5), the strongest event and hours not measured (#6), the functions to measure a threshold (#7), the AI layer (#9), the calibration bench, Try it and `publiccode.yml` (#10), notebooks and Docker (#14), the rule that the package depends on no sister library (#21). - **A pilot on 2026** ([`benchmarks/measures/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/benchmarks/measures)): on 9 dated landslides and Limen's archive of DPC frames, the «Merging» caught 7 of 9 with 9.4 alerts per landslide caught; the radar alone 8 of 9 with 12.25. Nine landslides: a first look, not a validation. - **The measure from 2018 to 2025** ([`benchmarks/measures/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/benchmarks/measures)): on the radar history and 4,200 dated landslides, the rain is above T5 at the gauge for 95.6 % of the same landslides and on the radar for 66.0 %. The threshold still separates on radar rain (AUC 0.85 and 0.73), and a threshold fitted on radar rain does not hold: none goes in. - **Open, and measured in Limen, not here:** the numbers of [limen#243](https://github.com/agent-engineering-studio/limen/issues/243) recomputed with `measure` (#7); `strongest_event` against the last event on the twelve backtest windows of Limen, before it is switched on there. ## Good to know - **A threshold is not a forecast.** Rain above T5 means "conditions like those that triggered landslides before", not "a landslide will happen here". Slope, soil, vegetation and antecedent wetness all matter. Use it as one input to a warning system, alongside expert judgement. - **The line is not equally good everywhere.** A T5 line leaves 5 % of the landslides of its macroregion below it; region by region the share goes from 1.3 % in Calabria (4 of 298) to 16.2 % in Valle d'Aosta (11 of 68). `calibration_of(region)` says where it sits high, where low, and where the landslides are too few to tell (Molise has 17). - **A landslide with a day and no hour takes the end of its day.** When you pair a dated landslide with hourly rain, the convention of this family of libraries is the next local midnight in Europe/Rome after its day, as UTC: 1 January 2010 is 2010-01-01T23:00Z, 1 July 2010 is 2010-07-01T22:00Z. An hour is labelled by its end, so the last hour before the landslide is the one ending at that midnight. ispra-idrogeo gives the instant; notebook 04 shows it. - **T5 is deliberately low.** By construction, 95 % of past triggering events sit above it: it favours catching events over avoiding false alarms. - **Event reconstruction is simplified.** It follows Melillo et al. (2018), whose CTRL-T tool also varies the dry gap with the season. The e-ITALICA durations come from that fuller procedure, so applying the Italian thresholds to events from `reconstruct_events` mixes the two: fine for monitoring, worth knowing for a study. - **Units are fixed:** hours, millimetres, millimetres per hour. - **No sister library inside.** The package imports neither dpc-radar nor ispra-idrogeo, and a test keeps it so: [Limen](https://github.com/agent-engineering-studio/limen) pins all three, and a library that imported another would tie their releases together. The join lives in Limen, in notebook 04 and in `app/`. ## Where it's used - **[Limen](https://github.com/agent-engineering-studio/limen)**, an open early-warning system for landslides, floods and wildfires in Italy, from which the library was extracted. It pins `rainfall-thresholds~=0.3.0` for the rainfall trigger of its landslide score; the choice of the strongest event is in its `landslide.yaml`, off until its backtest measures it. - **The Open Data series** of Agent Engineering Studio, with its sister libraries [dpc-radar](https://agentengineering.it/dpc-radar/) and [ispra-idrogeo](https://agentengineering.it/ispra-idrogeo/). - **The calibration bench** in `app/`, for public bodies. Using it somewhere else? [Open an issue](https://github.com/agent-engineering-studio/rainfall-thresholds/issues) and tell us: we'd love to list it here. ## References - Caine N. (1980). The rainfall intensity-duration control of shallow landslides and debris flows. *Geografiska Annaler A* 62, 23-27. - Brunetti M.T. et al. (2010). Rainfall thresholds for the possible occurrence of landslides in Italy. *NHESS* 10, 447-458. - Peruccacci S. et al. (2012). Lithological and seasonal control on rainfall thresholds for the possible initiation of landslides in central Italy. *Geomorphology* 139-140, 79-90. - Melillo M. et al. (2018). A tool for the automatic calculation of rainfall thresholds for landslide occurrence. *Environmental Modelling & Software* 105, 230-243. - Peruccacci S. et al. (2023). ITALICA: an ITAlian rainfall-induced LandslIdes CAtalogue. *ESSD* 15, 2863-2877. - Brunetti M.T. et al. (2024). e-ITALICA (enhanced ITAlian rainfall-induced LandslIdes CAtalogue), v4. Zenodo, [doi:10.5281/zenodo.14204473](https://doi.org/10.5281/zenodo.14204473). ## Citing If this library helps your work, please cite the method and data papers above, and link to this repository: ``` Zileni G. rainfall-thresholds: rainfall intensity-duration thresholds for shallow landslides (Python). https://github.com/agent-engineering-studio/rainfall-thresholds ``` ## Contributing Issues and pull requests are welcome: new regional thresholds, better event reconstruction, examples from other countries. See [CONTRIBUTING.md](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/CONTRIBUTING.md). To set up and run the checks: ```bash uv sync make check # ruff, mypy --strict, pytest with 100 % coverage make figures # redraw the README charts (docs/make_figures.py) ``` ⭐ If you find it useful, a star helps others find it. ## Data licence The test fixture `tests/fixtures/italica_v4_dur_rain.csv` is e-ITALICA v4 (Brunetti et al. 2024), [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/), reduced to four columns (id, region, duration, cumulated rainfall). The charts in `docs/img/` are drawn from it. ## License Code: [Apache-2.0](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/LICENSE). # Try it: the intensity-duration plane How much rain does it take? Pick a region, a duration and the rain that fell, and see where it stands against the Italian threshold and against the landslides of the past. Everything runs in your browser: no data leave it. !!! warning "A threshold exceeded is not an alert" It says the rain is like the rain that triggered landslides before. The official alert in Italy is the [criticality bulletin](https://rischi.protezionecivile.gov.it/it/meteo-idro/allertamento/) of the Dipartimento della Protezione Civile.
**How to read it.** Each grey dot is a landslide of the macroregion, placed by the duration and mean intensity of the rain that triggered it (e-ITALICA, measured at rain gauges). The blue line is the T5 threshold: 5 % of those landslides sit under it. The star is your rain. Its distance from the line is the exceedance, in decades: +0.3 is twice the threshold intensity, +1 ten times. **What it does not say.** Whether a landslide will happen, or where: slope, soil and the wetness of the weeks before matter as much as the rain. How often the threshold is passed when nothing happens: that is the [cost in false alarms](api/measure.md), and it is not in a landslide catalogue. The thresholds and the landslides come from the library and from e-ITALICA v4 (Brunetti et al. 2024, [doi:10.5281/zenodo.14204473](https://doi.org/10.5281/zenodo.14204473), CC BY 4.0), written by `docs/make_explainer_data.py`. # Examples ## Notebooks Five notebooks in [`notebooks/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/notebooks), saved with their outputs. - [**1 · The Italian thresholds**](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/notebooks/01_italian_thresholds.ipynb): the four T5 thresholds in millimetres, which region gets which, and the 5,974 e-ITALICA landslides under the lines (299 below the national one, 5.0 %). - [**2 · The Melito storm**](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/notebooks/02_melito_storm.ipynb): 10 October 2026 on the DPC radar, 165.7 mm in 35 hours, +0.73 decades; the strongest event and the last one; hours not measured. - [**3 · Fit your own threshold**](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/notebooks/03_fit_your_threshold.ipynb): T5 on the 1,603 landslides of Liguria (32.5 mm in 24 hours), and how the percentile moves it. - [**4 · Radar rain on dated landslides**](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/notebooks/04_radar_on_dated_landslides.ipynb): the join with the sister libraries, ispra-idrogeo and dpc-radar, as Limen does it. A landslide dated to the day takes the end of its day (the next local midnight in Europe/Rome). Needs the network. - [**5 · How much to trust the line, and how much rain is still missing**](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/notebooks/05_trust_and_margin.ipynb): the share of each region's landslides below the line, from 1.3 % in Calabria to 16.2 % in Valle d'Aosta, with the interval; the rain still missing hour by hour during the storm of Melito; the published thresholds of Calabria, Abruzzo-Marche-Umbria and Sicilia; the record. All but the fourth need no network and run in CI. ```bash uv run --group examples jupyter lab notebooks/ docker compose up notebooks # the same, with Docker alone: http://localhost:8881 ``` ## The calibration bench A page in Italian for a public body, in [`app/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/app): it fits a threshold on the e-ITALICA landslides of its region, or on its own, compares it with the national one, measures its cost on the body's own rain gauge and exports it. [Riuso nella PA](riuso.md) says what it does and what stays with the body. ```bash TARATURA_ENTE="Comune di Gioia del Colle" TARATURA_REGIONE=Puglia docker compose up taratura # http://localhost:3001 ``` ![The calibration bench open on Apulia: the threshold fitted on 140 landslides and the rain it asks from 1 to 72 hours](https://raw.githubusercontent.com/agent-engineering-studio/rainfall-thresholds/main/docs/img/blog/banco-di-taratura-puglia.jpg) ## Try it [An interactive intensity-duration plane](explainer.md), in the browser. # Benchmark: known cases A small, fixed set of cases where we already know the answer. Every change to how an event is read, or compared with a threshold, runs here first. Without it, every improvement is an opinion. Tracked in [#5](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/5). ```bash uv run python -m benchmarks.run # the table uv run python -m benchmarks.run --check # CI: fails if an outcome changed uv run python -m benchmarks.run --write # accept the new outcomes (results.json) ``` > **A threshold exceeded is not an alert.** The official alert is the > criticality bulletin of the Dipartimento della Protezione Civile. A case > here says whether the rain was like the rain of past landslides, nothing > more. ## The cases | Case | What happened | What a method must do | |---|---|---| | **Melito di Porto Salvo, 10 October 2026** | landslides in the Reggio Calabria area; the radar alone read 166 mm in 48 h at Melito | read the storm, above T5 | | **Bagaladi, same storm** | 104 mm in 48 h, 13 km north | above T5 | | **Melito, the day after** | nothing | no event | | **The storm, then drizzle** *(constructed)* | Melito's storm hours, six dry hours, 2.5 mm | keep the storm: do not forget it because it drizzled after | | **The storm with a gap** *(constructed)* | Melito's storm hours, three of them not measured | do not read the gap as dry; what was measured is still above T5 | | **Six e-ITALICA landslides** | in each macroregion, the landslide at the median of T5's exceedance and the one at the 2nd percentile | above T5 | The expected answer is **what happened**, not what a threshold can do. The three e-ITALICA landslides at the 2nd percentile sit under T5: T5 leaves 5 % of past landslides below it by construction. They fail for every method that uses T5, and they are there to say so. The radar series are the DPC product SRT1 (rain over the last hour, radar only), read at the point as the median of the valid 3×3 pixels, the hour labelled by its end. They were cut from Limen's archive of the DPC radar: the DPC deletes its frames after about five months, so once here, a case keeps working. The two constructed cases are made from those hours, and their files say how. ## Today's score `v0.1` is what 0.1.0 does, and what Limen does with it: `reconstruct_events` with a 6-hour dry break and 2 mm minimum, then `latest_event`. `v0.2` (#6) takes hours not measured (`None`) and the strongest event of the window, `strongest_event`. | Check | v0.1 | v0.2 | |---|---|---| | Melito and Bagaladi above T5 (4 checks) | ✓ ✓ ✓ ✓ | ✓ ✓ ✓ ✓ | | Melito's event includes the peak hour | ✓ | ✓ | | The day after: no event | ✓ | ✓ | | Storm then drizzle: above T5 | ✗ (−0.65: it reads the drizzle) | ✓ (+0.78) | | Storm then drizzle: event includes the storm | ✗ | ✓ | | Storm with a gap (2 checks) | ! (cannot take hours not measured) | ✓ ✓ (59.6 mm measured, +0.51) | | e-ITALICA, median landslides (3) | ✓ ✓ ✓ | ✓ ✓ ✓ | | e-ITALICA, 2nd-percentile landslides (3) | ✗ ✗ ✗ | ✗ ✗ ✗ (under T5, by construction) | | **Total** | **9 of 16** | **13 of 16** | On the real Melito series both do well: the rain from the afternoon of the 9th to the night of the 10th is one event (166 mm in 35 h, +0.73 decades), so the drizzle fault does not show there. It shows as soon as six dry hours separate the storm from a little more rain. ## What is not there - **Heavy rain with no landslide.** The cases that measure false alarms. A day of heavy rain with no landslide on record is not a day with no landslide: the candidates come from the rare-rain catalogue of the DPC radar, and only Limen checks them in the news. Until then, none. - **The «Merging».** The series are radar only. The «Merging» (CUM3) is closer to the rain gauges the thresholds are fitted on, but comes every three hours, too coarse for an hourly series. It is quoted in the sources as a check. - **Lipari, 10 October 2026.** A cloudburst the radar did not see. Its series would read zero, not "not measured": telling the two apart needs a reliability map, which is not this library's job. The caller passes `None`. - **More events.** Melito is one storm. The landslides of the radar era (IdroGEO, from 2018) are for [#8](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/8). ## Data licence Radar series © Dipartimento della Protezione Civile, [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). e-ITALICA v4 (Brunetti et al. 2024, doi:10.5281/zenodo.14204473), [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). # Roadmap Where rainfall-thresholds goes, and what each step measured. The plan is tracked in [#4](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/4); every phase has its issue. !!! warning "Ground rule" A threshold exceeded is not an alert. The official alert in Italy is the [criticality bulletin](https://rischi.protezionecivile.gov.it/it/meteo-idro/allertamento/) of the Dipartimento della Protezione Civile. Where nothing was measured, the answer is "not measured", never zero. ## Where it started The library came out of [Limen](https://github.com/agent-engineering-studio/limen), an open early-warning system for landslides, floods and wildfires in Italy, which uses it for the rainfall trigger of its landslide score. Limen's backtests ([limen#243](https://github.com/agent-engineering-studio/limen/issues/243)) said what the threshold does there, with model rain (ERA5): 40.7 % of the e-ITALICA landslides above the threshold against 3.0 % of ordinary moments, and 0 of 286 landslides caught by the engine in the regions held out. The 24-hour total ranked better than the engine's score (AUC 0.75 against 0.60). That is where this plan starts. ## Rules that hold for every phase - **The package depends on no sister library.** It imports neither [dpc-radar](https://agentengineering.it/dpc-radar/) nor [ispra-idrogeo](https://agentengineering.it/ispra-idrogeo/) nor Limen, and a test keeps it so. Limen pins all three: a library that imported another would tie their releases together. The join lives in Limen, in notebook 04 and in `app/` ([#21](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/21)). - **Data come in as data.** A measure that needs other libraries runs in Limen; its result comes here as a small file with its source, and the tests recompute from it. - **Data first, then conclusions.** ## Phase 0 · Benchmark of known cases · [#5](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/5) · ✅ Sixteen checks in [`benchmarks/`](benchmark.md): the Melito di Porto Salvo storm of 10 October 2026 on the DPC radar, the day after, six e-ITALICA landslides picked by a rule, and two cases built from Melito's hours. **Check:** 0.1.0 passed 9 of 16. ## Phase 1 · The right event, and rain that was not measured · [#6](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/6) · ✅ `strongest_event` instead of the last event, `None` for an hour not measured, a `source` label, and the README rule that a threshold is not an alert. **Check:** 13 of 16. The storm followed by drizzle went from −0.65 to +0.78; the storm with three hours missing reads +0.51 on the 59.6 mm measured. The three still missed are landslides under T5, as T5 allows by construction. **For Limen:** `caine.event_reconstruction.scelta_evento` in `landslide.yaml` ([limen#660](https://github.com/agent-engineering-studio/limen/pull/660)), **off** (`ultimo`) until the backtest of the twelve windows of limen#122 measures `piu_forte`. ## Phase 2 · The cost in false alarms · [#7](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/7) · functions ✅, measure open `skill`, `skill_at_budget`, `cutoff_at_budget`, `auc`: landslides caught, alert share, discrimination, alerts per landslide caught. **Check:** on 2,000 random inputs, the same results as Limen's own cutoff and both of its AUC functions, with no difference. **What is not there:** the numbers of limen#243 recomputed with these functions. The ordinary moments are in Limen's archive: it runs on Limen's server. ## Phase 3 · Rain that does not come from a rain gauge · [#8](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/8) · pilot ✅, measure from 2018 ✅ The Italian thresholds are fitted on rain gauges; the DPC radar alone read about 20 % more than the gauge-corrected «Merging» in 2026, and not the same everywhere. Is a gauge threshold valid on radar rain? The data are ready: IdroGEO has 1,710 landslides dated to the day since 2018, 1,608 with the point within 1 km (counted on 23/11/2026, `dated_landslides` of ispra-idrogeo). They are uneven: Emilia-Romagna 305, Apulia 2. The measure runs in Limen, region by region; a result does not stand for Italy. **Pilot on 2026** ([the data and how they were made](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/benchmarks/measures)): the 9 IdroGEO slides and flows dated to the day between June and November 2026, point within 1 km, on Limen's archive of DPC frames. With the «Merging» (gauges and radar), 7 of 9 caught and 66 of 338 rainfall events above T5 at those points: 9.4 alerts per landslide caught. With the radar alone, 8 of 9 caught and 98 of 382 events above T5: 12.25 alerts per landslide caught. One landslide more, 32 alerts more. **Measure from 2018 to 2025** ([the data and how they were made](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/benchmarks/measures), [limen#677](https://github.com/agent-engineering-studio/limen/issues/677)): the radar history at 4,200 dated landslides, 1,057 of e-ITALICA (with the rain at the gauge) and 3,143 of IdroGEO. - On the same 971 landslides the rain is above T5 at the gauge for 95.6 % and on the radar for 66.0 % (37.2 % without Liguria). On the triggering events the radar reads 0.68 times the gauge. - Against 388,063 ordinary moments at the same points, the gauge threshold still separates on radar rain: AUC 0.85 on e-ITALICA, 0.73 on IdroGEO. - The bias factor of dpc-radar lowers the rain and does not change the order: the same landslides caught at the same alert share. - A threshold fitted on radar rain does not hold: alpha between 0.35 and 1.96 from one set and one macroregion to another. **No radar threshold goes into the library.** **What is not there:** a comparison at the same place (the radar is read at the landslide, the gauge is the nearest one), and samples that are not mostly one region: e-ITALICA from 2018 is 74 % Liguria, IdroGEO 47 % Trentino-Alto Adige. ## Phase 4 · AI layer · [#9](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/9) · ✅ Facts as JSON-ready dicts with the unit in every key, `check_text` (numbers invented, rounded the wrong way, or in the wrong unit), an MCP server as the optional extra `mcp`, `llms.txt` and an agent skill. **Check:** the faithfulness set, four questions with a faithful and a faulty hand answer each: 8 of 8 scored as expected. Writing it found a wrong number in a hand answer and two faults of the check, all fixed. **What is not there:** answers of a model in the set; calls to a paid model only after an explicit yes. ## Phase 5 · A tool for public bodies · [#10](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/10) · ✅ A calibration bench in `app/`, in Italian, with Bootstrap Italia and no CDN; [Try it](explainer.md); `publiccode.yml` checked in CI; [Riuso nella PA](riuso.md). It does not compete with Limen: no real time, no score, no alerts. **What is not there:** the cost in false alarms on real data, which needs a body's own gauge series; English texts in the bench. ## Also done Four [notebooks](examples.md) and Docker with no fixed container names ([#14](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/14)). The story, in Italian: [Basta questa pioggia per far franare?](https://agentengineering.it/blog/soglie-pioggia-frane-rainfall-thresholds/) ([English](https://agentengineering.it/en/blog/soglie-pioggia-frane-rainfall-thresholds/)). # Threshold ## `rainfall_thresholds.threshold` The power-law rainfall intensity-duration threshold (Caine 1980). I(D) = alpha * D^(-beta) I in mm/h, D in hours A rainfall event of mean intensity `I` lasting `D` hours is above the threshold when `I > I(D)`. Equivalently, in cumulated rainfall, `E(D) = alpha * D^(1 - beta)` mm. ### `class PowerLawThreshold(alpha: float, beta: float)` `I(D) = alpha * D^(-beta)`, with `alpha` in mm/h and `D` in hours. #### `PowerLawThreshold.intensity(duration_hours: float) -> float` The threshold mean intensity for an event of this duration, in mm/h. #### `PowerLawThreshold.cumulated(duration_hours: float) -> float` The threshold cumulated rainfall for an event of this duration, in mm. #### `PowerLawThreshold.exceedance(intensity_mm_h: float, duration_hours: float) -> float` `log10(I / I(D))`: decades above (positive) or below (negative) the line. Negative infinity for a dry event (zero intensity). #### `PowerLawThreshold.scaled(factor: float) -> PowerLawThreshold` The same slope with `alpha` multiplied by `factor`. A lower line (`factor < 1`) for rain that reads less than the rain the threshold was fitted on, or for ground that needs less of it. # Rainfall events ## `rainfall_thresholds.events` Rainfall events from an hourly series, after Melillo et al. (2018). The series is split wherever `no_rain_break_hours` or more consecutive dry hours occur; an event whose cumulated rainfall is below `min_event_mm` is dropped. An event runs from its first to its last wet hour, both included, so a single wet hour is a one-hour event. An hour can be **not measured** (`None`): a missing frame, a gauge that did not report, a place the radar cannot see. Not measured is not dry. Such an hour adds no rain and does not count towards the dry break, so a gap never splits an event on its own; the event counts it in `unmeasured_hours`, and its total is then a lower bound. This is a simplified reconstruction: Melillo et al. also vary the dry gap with the season and separate sub-events within a rainfall period. Use their CTRL-T tool when the reconstruction itself is what you are studying. ### `class RainfallEvent(start: datetime, end: datetime, duration_hours: float, total_mm: float, unmeasured_hours: int = 0, source: str | None = None)` One rainfall event: first and last wet hour, duration and total. `unmeasured_hours` counts the hours inside the event that were not measured: when it is above zero, `total_mm` is what was measured, a lower bound. `source` is the label given to `reconstruct_events` (for example `"rain gauge"` or `"DPC SRT1"`), carried as it is. #### `RainfallEvent.intensity_mm_h: float` Mean intensity over the event. #### `RainfallEvent.fully_measured: bool` `True` when every hour of the event was measured. ### `reconstruct_events(series: Iterable[tuple[datetime, float | None]], *, no_rain_break_hours: int, min_event_mm: float, source: str | None = None) -> list[RainfallEvent]` Split an hourly `(timestamp, mm)` series into rainfall events. The series is sorted by timestamp first. It is expected to be hourly and without gaps: a dry hour must be in the series as `0`, an hour not measured as `None`. `source` labels the events (the Italian thresholds are fitted on rain gauges, so it matters where the rain comes from); it is carried, never interpreted. ### `latest_event(events: Iterable[RainfallEvent]) -> RainfallEvent | None` The event that ended last, or `None`. For monitoring, prefer `strongest_event`: the last event can be a little drizzle after a storm. ### `strongest_event(events: Iterable[RainfallEvent], threshold: PowerLawThreshold) -> RainfallEvent | None` The event furthest above (or least below) `threshold`, or `None`. A storm followed by six dry hours and a little drizzle is two events: the last one is the drizzle, the strongest is the storm. Which events count is the caller's choice: pass the events of the window you monitor (for example the last 48 hours), so an old storm does not stay forever. Ties go to the event that ended last. # Fitting ## `rainfall_thresholds.fit` Fitting a threshold to the rainfall conditions that triggered landslides. The frequentist approach of Brunetti et al. (2010) and Peruccacci et al. (2012): fit `log10 I = log10 alpha - beta log10 D` by least squares over the (D, I) pairs of known landslide-triggering events, then lower the line until a chosen share of the events sits below it. The threshold at the 5th percentile, `T5`, leaves 5 % of the triggering events beneath. Where Peruccacci et al. take the percentile from a Gaussian fitted to a kernel density of the residuals, this module takes it from the residuals themselves (linear interpolation between order statistics). The two agree when the residuals are close to normal; the empirical one needs no assumption about their shape. ### `class ThresholdFit(threshold: PowerLawThreshold, percentile: float, n_events: int, central: PowerLawThreshold)` A fitted threshold and what it was fitted on. ### `fit_threshold(events: Iterable[tuple[float, float]], *, percentile: float = 5.0) -> ThresholdFit` Fit `I = alpha * D^(-beta)` at `percentile` to `(duration_h, intensity_mm_h)` pairs. Pairs with a non-positive duration or intensity are skipped: they have no logarithm. At least three usable pairs are needed. ### `percentile_of(values: list[float], percentile: float) -> float` The `percentile`-th percentile, interpolating linearly between order statistics. The same definition as NumPy's default (`method="linear"`). # Italy (T5 thresholds) ## `rainfall_thresholds.italy` T5 thresholds for Italy, fitted on the e-ITALICA catalogue. e-ITALICA v4 (Brunetti et al. 2024, doi:10.5281/zenodo.14204473, CC BY 4.0) lists rainfall-induced landslides with the duration and cumulated rainfall of the triggering event, measured at a rain gauge. The 5,974 events with both values positive were fitted with `rainfall_thresholds.fit.fit_threshold` at the 5th percentile, nationally and for three macroregions. `tests/test_italy.py` refits them from the catalogue, so these numbers are reproducible, not transcribed. They are not the thresholds published by the e-ITALICA authors, who use a kernel-density estimate of the residuals and their own regional partitions: they are what this package's method gives on their data. ### `macroregion_of(region: str | int) -> str | None` The macroregion of an Italian region, or `None`. `region` is the name as e-ITALICA spells it (`"Emilia-Romagna"`) or the ISTAT region code, as a number or as text (`8`, `"08"`). ### `threshold_for(macroregion: str | None, thresholds: Mapping[str, PowerLawThreshold] = ITALICA_T5, *, default: str = 'italy') -> PowerLawThreshold` The threshold of a macroregion, or the `default` one when it has none. `thresholds` are the caller's own if given (a calibration, a configuration file); it must have the `default` key. # A series against a threshold ## `rainfall_thresholds.assess` A measured hourly series against a threshold: windows, the event, the excess. The series is a mapping from the hour to its rain in mm, with `None` for an hour **not measured**. Not measured is never read as zero: * a window with an unmeasured hour has no total, and says how many are missing; * an event with unmeasured hours inside, or bordered by them (the archive stops before the dry break closes it, or starts after it began), is a lower bound: `EventAssessment.at_least`. The Italian thresholds are fitted on rain gauges. Rain from a radar is not the same quantity: where the two were measured together, pass their ratio as `radar_gauge_factor` and the threshold is lowered by it. The factor is a plain number of the caller's, with no default other than 1 (no correction): it depends on the radar product, the place and the years (`benchmarks/measures` has one measure of it, 0.68 on triggering events, 2018-2025). Moved from Limen (`core/pioggia_frane.py`, `core/scoring/caine.py`); parity tests keep the numbers the same. ### `class WindowTotal(hours: int, total_mm: float | None, unmeasured_hours: int)` The rain of the last `hours` hours: `None` if any was not measured. ### `cumulate(hours: Mapping[datetime, float | None], end: datetime, *, windows_hours: Iterable[int]) -> dict[int, WindowTotal]` The totals of the windows that end at `end`, by window length. A window is the `n` hours up to `end` included. One that starts before the first hour of the series is left out; an hour missing from the series counts as not measured, like one that is `None`. Totals are not rounded. ### `caine_excess(event: RainfallEvent | None, threshold: PowerLawThreshold, *, radar_gauge_factor: float = 1.0) -> float` `max(0, log10(I_event / I_threshold(D_event)))`: decades above the line. Zero with no event and for an event on or below the threshold. To lower or raise the threshold for another reason (after an earthquake, say), pass `threshold.scaled(factor)`. ### `class EventAssessment(event: RainfallEvent, threshold: PowerLawThreshold, borders_unmeasured: bool)` A rainfall event and the threshold at its duration. `threshold` is the one applied, already lowered by the radar/gauge factor if one was given. `borders_unmeasured` says that an hour within the dry break before or after the event was not measured (or is not in the series): the event may have begun earlier or not be over. #### `EventAssessment.threshold_mm_h: float` The threshold mean intensity at the event's duration. #### `EventAssessment.threshold_mm: float` The threshold cumulated rainfall at the event's duration. #### `EventAssessment.ratio: float` Event intensity over threshold intensity: above 1 is above the line. #### `EventAssessment.excess_decades: float` `log10` of `ratio`, negative below the line. #### `EventAssessment.at_least: bool` `True` when the measured rain is a lower bound of the real one. #### `EventAssessment.as_record(*, where: Mapping[str, Any] | None, licence: str) -> dict[str, Any]` The assessment as a fact of `opendata-record/v2`, a plain dict. The record format the libraries of the family exchange. `where` is a GeoJSON geometry (or `None`) and `licence` the licence of the rain: an assessment knows neither. The source of the record is the event's `source` label, which must be there. An hour is labelled by its end, so the record's time begins an hour before the event's first. No name in it says more than a measure against a line. ### `event_against_threshold(hours: Mapping[datetime, float | None], threshold: PowerLawThreshold, *, no_rain_break_hours: int, min_event_mm: float, choice: Literal['latest', 'strongest'] = 'latest', source: str | None = None, radar_gauge_factor: float = 1.0) -> EventAssessment | None` The rainfall event of an hourly series, against the threshold at its duration. The events are those of `rainfall_thresholds.events.reconstruct_events` with the same `no_rain_break_hours`, `min_event_mm` and `source`; `choice` takes the one that ended last or the one furthest above the threshold (`rainfall_thresholds.events.strongest_event`). `None` when the series has no event. ### `rain_to_threshold(event: RainfallEvent | None, threshold: PowerLawThreshold, *, more_hours: Iterable[float], radar_gauge_factor: float = 1.0) -> dict[float, float]` The rain still needed to reach the threshold if the event goes on, in mm. For each `h` of `more_hours`: what the threshold asks of an event `h` hours longer, less what has already fallen; zero when the event is already there. It supposes the event does not stop: a dry break closes it and the count starts again. With no event (`None`) it is the rain a new event of `h` hours needs. Compare it with a forecast, or read it as the margin left. The line asks more of a longer event, so an event above it now can be below it later if it goes on with little rain. ### `relative_total(hours: Mapping[datetime, float | None], end: datetime, *, window_hours: int, reference_mm: float, saturation: float, reduction: float = 0.0, longer_references_mm: Mapping[int, float] | None = None) -> float | None` The rain of the last hours against the place's own climate, from 0 to 1. A threshold in millimetres is not the same everywhere: 60 mm in a day are ordinary in Liguria and rare in Sardegna. Here the total of the `window_hours` up to `end` is divided by `reference_mm`, a high quantile of that same total **at that place** (the caller's climatology), and is 1 at `saturation` times the reference. `reduction` (0 to 1, excluded) lowers the bar, for ground that needs less rain. `longer_references_mm` adds longer windows, each with its reference: the answer is the highest of all. The window is `(end - window_hours, end]`. Only measured hours are summed, so with hours missing the answer is a lower bound; with no measured hour in the first window it is `None`: rain not read is not no rain. Moved from Limen's engine (limen#243), with a parity test. # Antecedent precipitation ## `rainfall_thresholds.antecedent` The Antecedent Precipitation Index (Kohler & Linsley 1951) and a wetness factor. API_t = k * API_(t-1) + P_t P in mm per day, 0 < k < 1 How wet the ground already is when the rain comes: every day keeps a share `k` of the day before and adds its own rain. `api_factor` reads an API against a baseline as a number between 0 and 1. There are no defaults for `k`, the baseline or the sigma: they depend on the place and on what the factor is used for, and are the caller's configuration. Moved from Limen (`core/scoring/api.py`); a parity test keeps the numbers the same. ### `api_kohler_linsley(daily_precip_mm: Iterable[float], *, decay_k: float, initial: float = 0.0) -> float` The API at the end of a series of daily totals, in mm. Args: daily_precip_mm: Daily totals in chronological order. decay_k: Daily decay coefficient, `0 < k < 1`. initial: API at the start of the series. ### `api_factor(api_mm: float | None, *, fallback_baseline_mm: float, fallback_sigma_mm: float, sigma_min_mm: float, baseline_mm: float | None = None, sigma_mm: float | None = None) -> float` An API as a wetness factor between 0 and 1. The logistic of the standardised anomaly, `(API - baseline) / sigma`: 0.5 at the baseline, towards 1 when wetter. `baseline_mm` and `sigma_mm` are the place's own climatology for the month; a place without one is read against `fallback_baseline_mm` and `fallback_sigma_mm`. A place's own sigma is never taken below `sigma_min_mm`: where the rain of a month varies by a few millimetres, an ordinary storm would read as an anomaly of ten sigma. `None` (no API known) gives 0.5, neutral: not knowing moves the factor neither up nor down. # How much to trust, per region ## `rainfall_thresholds.trust` How well the Italian threshold is calibrated, region by region. A T5 threshold is fitted so that 5 % of the landslides of its macroregion sit below it. A macroregion is not one place: inside it, a region can have many more of its landslides below the line (the line is high for it, and misses more of them there) or many fewer (the line is low for it, and rain crosses it more easily there). And a region with seventeen landslides cannot tell either way. `CALIBRATION` counts, for each region, the e-ITALICA landslides the thresholds were fitted on, how many are below the threshold of their macroregion, and the durations they cover. `tests/test_trust.py` counts them again from the catalogue. `Calibration.interval` is the range the real share can be in, given how many landslides there are (a Wilson score interval), and `Calibration.position` reads it against the 5 %. This says how the line sits on the landslides of the past, at rain gauges. It does not say how often it is crossed without a landslide: that is `rainfall_thresholds.measure`, on the caller's own rain. ### `class Calibration(region: str, macroregion: str, events: int, below: int, duration_hours: tuple[float, float])` The landslides of a region against the threshold of its macroregion. `events` landslides of e-ITALICA v4, `below` of them under the line. `duration_hours` are the 5th and 95th percentile of the durations of their rain: outside that range the line is extrapolated. #### `Calibration.below_share: float` The share of the region's landslides below the line. #### `Calibration.interval(z: float = 1.96) -> tuple[float, float]` The range of the real share, as a Wilson score interval. `z` is the normal quantile of the confidence wanted: 1.96, the default, is the usual 95 %. #### `Calibration.position: Literal['as fitted', 'high', 'low']` Where the line sits for this region, at 95 %. `"high"`: more than 5 % of its landslides are below, beyond what chance gives. `"low"`: fewer. `"as fitted"`: the 5 % is within the interval, which with few landslides is wide and says little. ### `calibration_of(region: str | int) -> Calibration | None` The calibration of a region, by name or ISTAT region code, or `None`. # Published regional thresholds ## `rainfall_thresholds.regional` Published regional rainfall thresholds for Italy, with their sources. `regional_thresholds.toml` collects thresholds published by the literature for a region, a physiographic area or an alert zone, each with its citation and licence. They are data to compare with, not what this package fits (`rainfall_thresholds.italy.ITALICA_T5`), and nothing here applies them: a threshold for a zone needs the zone's geometry, which the caller has. Moved from Limen (`core/scoring/soglie_regionali.py` and its YAML), with Limen's area ids replaced by region names; a parity test compares the file with Limen's, entry by entry. ### `class Source(citation: str, url: str, license: str)` Where a threshold was published, and under which licence. ### `class RegionalThreshold(id: str, form: Literal['E-D', 'I-D'], alpha: float, source: str, gamma: float | None = None, beta: float | None = None, regions: tuple[str, ...] = (), zone: str | None = None, duration_hours: tuple[float, float] | None = None, level: str | None = None, no_rain_gap_hours: float | None = None, note: str | None = None)` One published threshold. `form` is `"E-D"` (`E = alpha * D^gamma`, mm and hours) or `"I-D"` (`I = alpha * D^(-beta)`, mm/h and hours). `regions` are the Italian regions it covers whole, as e-ITALICA spells them; a threshold for an alert zone or a physiographic area has `zone` instead. `source` is a key of `RegionalCatalogue.sources`. #### `RegionalThreshold.as_intensity() -> PowerLawThreshold` The threshold as `I = alpha * D^(-beta)`, mm/h. ### `class RegionalCatalogue(sources: MappingProxyType[str, Source], thresholds: tuple[RegionalThreshold, ...])` The thresholds and their sources. A region has one threshold at most. #### `RegionalCatalogue.by_region() -> dict[str, RegionalThreshold]` The threshold of each region that has one of its own. ### `load_regional_catalogue() -> RegionalCatalogue` The catalogue shipped with the package (read once, immutable). # Rain sources ## `rainfall_thresholds.sources` The shape of a rain source, so that any archive can feed this package. This package reads no rain: it takes hourly series. `RainSource` is the shape of what gives them for a list of points, written down so that code joining a rain library with this one can be typed without either importing the other. dpc-radar's `MergingArchive` and `SriHistory` have this shape; so can a table of rain gauges. ### `class RainSource()` Hourly rain at lon/lat points. #### `RainSource.hourly(points: list[tuple[float, float]], start: datetime, end: datetime) -> dict[datetime, list[float | None]]` The rain of every hour in `(start, end]`, in mm, one value per point. The key is the end of the hour; the list follows `points`. `None` is an hour not measured at that point, never zero. ### `point_series(rain: Mapping[datetime, Sequence[float | None]], index: int) -> dict[datetime, float | None]` The series of one point, out of what `RainSource.hourly` returns. Ready for `rainfall_thresholds.assess.event_against_threshold`, `rainfall_thresholds.assess.cumulate` and, as `.items()`, `rainfall_thresholds.events.reconstruct_events`. # Measuring a threshold ## `rainfall_thresholds.measure` How good a threshold is: landslides caught, and the alerts it costs. A threshold is only half an answer. T5 catches 95 % of past landslides by construction; what it does not say is how often it is exceeded when nothing happens. These functions measure both sides on the same scale, for any score that grows with danger: the exceedance of a threshold in decades, a 24-hour total in mm, a probability. You bring two lists of scores: * `landslides`: one score per landslide, the **highest** in the hours before it (the lead window is your choice: 24, 48, 72 hours); * `ordinary`: one score per unit of time and place you could alert on (cell-hours, municipality-days...), with or without landslides, as your alert budget is counted. `None` is a score that was not measured. It is left out and counted, never read as zero. Definitions, as in Limen's backtests (limen#243, limen#352): * a landslide is **caught** when its score reaches the cutoff (`>=`); * the **alert share** is the share of ordinary units at or above the cutoff; * **discrimination** is hit rate over alert share: 1 is chance; * the **cutoff at a budget** is the score that puts that share of ordinary units on alert. Ties can make the share a little higher than asked. ### `class Skill(cutoff: float, caught: int, landslides: int, alerts: int, ordinary: int, unmeasured: int = 0)` What a cutoff catches, and what it costs. #### `Skill.hit_rate: float | None` Share of the landslides caught; `None` without landslides. #### `Skill.alert_share: float | None` Share of the ordinary units on alert; `None` without units. #### `Skill.discrimination: float | None` Hit rate over alert share: 1 is chance. `None` when either is unknown or zero. #### `Skill.alerts_per_caught: float | None` Alerts paid for every landslide caught; `None` when none is caught. ### `skill(landslides: Iterable[float | None], ordinary: Iterable[float | None], cutoff: float) -> Skill` Landslides caught and ordinary units on alert at `cutoff`. ### `cutoff_at_budget(ordinary: Iterable[float | None], budget: float, *, floor: float | None = None) -> float` The cutoff that puts `budget` (0-1) of the ordinary units on alert. It is the k-th highest score, `k = max(1, round(budget * n))`. With `floor`, a score at or below it never alerts (for a score that is 0 when nothing happens, `floor=0`): the cutoff is then at least the lowest score above it, or `inf` when there is none. Without measured scores, `inf`. ### `skill_at_budget(landslides: Iterable[float | None], ordinary: Iterable[float | None], budget: float, *, floor: float | None = None) -> Skill` `skill` at the cutoff of `cutoff_at_budget`. The fair way to compare two scores: at the same share of units on alert, which catches more landslides? Counting at a fixed level instead rewards the score that alerts more. ### `auc(landslides: Iterable[float | None], ordinary: Iterable[float | None]) -> float | None` The chance that a landslide scores higher than an ordinary unit (Mann-Whitney). Ties count half. `None` without one of the two lists. Read it with care when many scores are tied, for example at zero: it then measures the order of the few that are not, and says nothing about the level. # Facts ## `rainfall_thresholds.facts` The same answers as data: what a tool, a report or a model can quote. Every function returns a plain `dict` (JSON-ready) with the numbers, their units in the key names (`_mm`, `_mm_h`, `_h`, `_decades`), where the threshold comes from, and the rule that goes with every answer: A threshold exceeded is not an alert. A language model may word these facts; it never computes them. The numbers come from here, and `rainfall_thresholds.check.check_text` checks a text against them. ### `resolve(region: str) -> str` `"italy"`, a macroregion, or an Italian region name -> the key of ITALICA_T5. ### `threshold_facts(region: str, duration_h: float) -> dict[str, Any]` The rain the Italian T5 threshold asks for over `duration_h` hours. ### `assess_facts(series: Iterable[tuple[datetime, float | None]], region: str, *, source: str | None = None, no_rain_break_hours: int = 6, min_event_mm: float = 2.0) -> dict[str, Any]` The rainfall events of an hourly series, and where the strongest stands. `None` in the series is an hour not measured. `source` says where the rain comes from; the thresholds are fitted on rain gauges, so rain from a radar or a model is flagged. ### `fit_facts(events: Iterable[tuple[float, float]], *, percentile: float = 5.0) -> dict[str, Any]` A threshold fitted on `(duration_h, total_mm)` of landslide-triggering rain. ### `trust_facts(region: str) -> dict[str, Any]` How well the threshold is calibrated in an Italian region. `region` is a region name (e-ITALICA spelling) or its ISTAT code. The facts are those of `rainfall_thresholds.trust.calibration_of`: the landslides the threshold was fitted on in the region, how many are below it, and the range the real share can be in. ### `margin_facts(series: Iterable[tuple[datetime, float | None]], region: str, *, more_hours: Iterable[int] = (1, 3, 6), source: str | None = None, no_rain_break_hours: int = 6, min_event_mm: float = 2.0) -> dict[str, Any]` The rain still needed to reach the threshold if the rain goes on. The event still going at the end of the series (its last wet hour is less than `no_rain_break_hours` before the last hour), or none: then the count starts from nothing. For each of `more_hours`, what the threshold asks of the longer event and how much of it is still missing. Compare it with a forecast; it is not one. ### `published_facts(region: str) -> dict[str, Any]` The thresholds the literature published for a region, next to this package's. From `rainfall_thresholds.regional.load_regional_catalogue`: only thresholds for the whole region, each with its citation and licence, and the rain each asks for in 24 hours. # Checking a text ## `rainfall_thresholds.check` Check that a text quotes the facts: no number invented, none in the wrong unit. A model turns the facts of `rainfall_thresholds.facts` into words. The faults that matter here are three: * **invented**: a number that is in no fact; * **unit**: a number that is a fact, but of another unit. The classic one: the 30.9 mm the threshold asks for over 35 hours, written as 30.9 mm/h. A rainfall threshold is about both, and they differ by the duration; * **rounded**: a number close to a fact, but not the fact rounded to the decimals written (`118.1` for 118.04). A number may be written with fewer decimals than the fact (`31` for 30.9) or, from 100, as a round number (`1,600` for 1,603). Dates, years and clock times (`10/10`, `10 October 2026`, `2026-10-10`, `03:00`) are not checked, nor numbers that are in the question. The check knows that a number is a fact of the right unit, not that it is said of the right thing: "Melito got 30.9 mm" passes when 30.9 mm is the threshold. ### `class Misquote(text: str, unit: str | None, fault: Fault, nearest: str | None = None)` A number of the text that is not a fact as written. ### `facts_of(facts: Any, path: str = '') -> Iterator[tuple[str, float, str | None]]` Every number in `facts`, with its path and the unit its key names. ### `parse_number(token: str) -> tuple[float, int]` A number as written -> its value and its decimals. `1,603` is 1603; `2,5` is 2.5. ### `check_text(text: str, facts: Any, *, question: str = '') -> list[Misquote]` The numbers of `text` that are not facts of their unit. Empty: faithful. # MCP server ## `rainfall_thresholds.mcp_server` The MCP server: the thresholds as tools an assistant can call. pip install "rainfall-thresholds[mcp]" rainfall-thresholds-mcp # on standard input and output rainfall-thresholds-mcp --transport streamable-http --host 0.0.0.0 --port 8775 Over HTTP the MCP endpoint is `/mcp` and `GET /health` answers `{"status": "ok"}` for container healthchecks. Every option also reads an environment variable (`RAINFALL_THRESHOLDS_MCP_TRANSPORT`, `_HOST`, `_PORT`, `_ALLOWED_HOSTS`), so a compose file needs no command line. The tools compute only from what the call gives them: no network, no live rain. Bring the rain from a gauge, a radar or a model; the answer says how far it is from the threshold, and that a threshold exceeded is not an alert. The tools are the functions of `rainfall_thresholds.facts`, and `check` is `rainfall_thresholds.check.check_text`. ### `create_server() -> MCPServer[Any]` The MCP server with its tools. ### `options(argv: Sequence[str] | None = None, environ: Mapping[str, str] = os.environ) -> argparse.Namespace` The command line of the server, each default from its environment variable. ### `http_options(args: argparse.Namespace) -> dict[str, Any]` The keyword arguments of `MCPServer.run` for the HTTP transport. ### `run(argv: Sequence[str] | None = None) -> None` Entry point of `rainfall-thresholds-mcp`: stdio, or HTTP when asked. # Riuso nella Pubblica Amministrazione rainfall-thresholds è una libreria per le soglie di pioggia che innescano le frane superficiali. Questa pagina è per un ente che vuole usarla: che cosa trova pronto, che cosa resta a lui. !!! warning "Una soglia superata non è un'allerta" Dice che la pioggia somiglia a quella che in passato ha innescato frane. L'allerta ufficiale è il [bollettino di criticità](https://rischi.protezionecivile.gov.it/it/meteo-idro/allertamento/) del Dipartimento della Protezione Civile e, sul territorio, la protezione civile regionale. ## Il banco di taratura Una pagina pronta, in italiano, con [Bootstrap Italia](https://italia.github.io/bootstrap-italia/) servito dalla pagina stessa, senza CDN: - si apre sul catalogo e-ITALICA già caricato, con la regione dell'ente selezionata; - tara una soglia sulle frane scelte (regione, mese, tipo di frana) o su quelle dell'ente; - la confronta con la soglia nazionale e mostra la pioggia che chiede da 1 a 72 ore; - ne misura il costo in falsi allarmi sulla serie oraria di un pluviometro dell'ente e sulle date delle sue frane; - la esporta come blocco YAML. ```bash TARATURA_ENTE="Comune di Gioia del Colle" TARATURA_REGIONE=Puglia docker compose up taratura ``` Le istruzioni sono in [`app/README.md`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/app). ## Che cosa non fa - **Non è un sistema di allerta**, e non legge pioggia dal vivo. Il monitoraggio con la pioggia di adesso è un altro progetto, [Limen](https://github.com/agent-engineering-studio/limen). - **Non dice dove cadrà una frana.** Pendenza, suolo, vegetazione e umidità contano quanto la pioggia. - **Non valida la soglia sulla pioggia radar o di modello.** Le soglie di e-ITALICA sono tarate sui pluviometri. ## Che cosa resta all'ente - **I dati della sua pioggia.** Senza una serie oraria di pluviometro, il costo in falsi allarmi resta «non misurato»: la pagina non lo scrive mai come zero. - **Le sue frane**, con la data, se vuole una soglia locale. Con meno di un centinaio di frane una soglia cambia molto con il campione, e la pagina lo dice. - **La decisione.** Che soglia usare, e per che cosa, è una scelta tecnica dell'ente e del suo centro funzionale: la pagina dà i numeri, non la scelta. - **La pubblicazione.** La pagina ascolta solo su `127.0.0.1`: per metterla sul sito va dietro il proxy dell'ente. ## La spiegazione, per tutti [Try it](explainer.md) è una pagina interattiva, senza server: si sceglie una regione, una durata e la pioggia caduta, e si vede dove cade rispetto alla soglia italiana e alle frane del passato. Serve a spiegare che cos'è una soglia, per esempio a una scuola o in un incontro pubblico. La pagina è in inglese, come il resto della documentazione. ## Il Catalogo di Developers Italia Il file [`publiccode.yml`](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/publiccode.yml) descrive il progetto per il [Catalogo del software](https://developers.italia.it/it/software) di Developers Italia, in italiano e in inglese, ed è controllato a ogni modifica con `italia/publiccode-parser-action`. Il campo `codiceIPA` resta vuoto finché il software non appartiene a una pubblica amministrazione: un ente che lo adotta può chiederne l'inserimento nel Catalogo. ## Fonti - e-ITALICA v4, Brunetti M.T. et al. (2024), [doi:10.5281/zenodo.14204473](https://doi.org/10.5281/zenodo.14204473), CC BY 4.0. - Caine N. (1980); Brunetti M.T. et al. (2010); Peruccacci S. et al. (2012). # Contributing Issues and pull requests are welcome. - Run `make check` before pushing: ruff, `mypy --strict` and pytest must be clean, the same gate CI runs. - `app/` runs on the library of this repository (a path dependency), so its lock file holds the library's metadata: after changing the root `pyproject.toml`, run `uv lock` in `app/` too, or the `app` job fails. - The package imports no sister library (dpc-radar, ispra-idrogeo, Limen); a test checks it. Notebooks and `app/` may use them (see the README). - Commits follow [Conventional Commits](https://www.conventionalcommits.org/). - Contributions are accepted under the project's license, Apache-2.0 (section 5 of the license: inbound = outbound). No separate CLA. --- name: rainfall-thresholds description: Compare rainfall with the landslide rainfall thresholds of Italy (Caine intensity-duration, T5 fitted on the e-ITALICA landslides) in Python with the rainfall-thresholds library - rainfall events from an hourly series, how far an event is above the threshold, fitting your own threshold, measuring a threshold's cost in false alarms, checking that a text quotes the numbers right. Use when code or an answer asks whether rain is enough to trigger landslides, or mentions rainfall thresholds, Caine, ITALICA, e-ITALICA, T5 or rainfall-thresholds. --- # rainfall-thresholds `rainfall-thresholds` answers one question: **is this rain like the rain that triggered landslides before?** It has no dependencies. It does not fetch rain: the caller brings an hourly series from a gauge, a radar or a model. Full documentation: https://agentengineering.it/rainfall-thresholds/ · everything as plain text: https://agentengineering.it/rainfall-thresholds/llms-full.txt ## The rule that goes with every answer **A threshold exceeded is not an alert.** The official alert in Italy is the criticality bulletin of the Dipartimento della Protezione Civile (https://rischi.protezionecivile.gov.it/it/meteo-idro/allertamento/). For danger to people, point to the bulletin, the regional civil protection and 112. Never write "alert", "warning" or "risk of landslide here" from a threshold alone. ## Setup ```bash pip install rainfall-thresholds # the library, no dependencies pip install "rainfall-thresholds[mcp]" # + the MCP server: rainfall-thresholds-mcp ``` ## Recipe ```python from datetime import datetime from rainfall_thresholds import ITALICA_T5, macroregion_of, reconstruct_events, strongest_event series: list[tuple[datetime, float | None]] = ... # hourly; 0 = dry, None = not measured threshold = ITALICA_T5[macroregion_of("Calabria") or "italy"] events = reconstruct_events(series, no_rain_break_hours=6, min_event_mm=2.0, source="rain gauge") event = strongest_event(events, threshold) # not latest_event: see the traps if event is not None: print(event.total_mm, event.duration_hours, threshold.cumulated(event.duration_hours)) print(threshold.exceedance(event.intensity_mm_h, event.duration_hours)) # decades ``` The same as data, for an answer in words: `rainfall_thresholds.facts` (`threshold_facts`, `assess_facts`, `fit_facts`, `trust_facts`, `margin_facts`, `published_facts`), and before you send the text, `rainfall_thresholds.check.check_text(text, facts)`. From a mapping `{hour: mm or None}`, `event_against_threshold(hours, threshold, no_rain_break_hours=6, min_event_mm=2.0, choice="strongest")` gives the event with `.ratio`, `.excess_decades` and `.at_least` (the rain is a lower bound: hours not measured inside the event or at its edges). `rain_to_threshold(event, threshold, more_hours=(1, 3, 6))` is the rain still needed if the event goes on: arithmetic on the line, not a forecast. `calibration_of("Valle d'Aosta")` says how the line sits on the landslides of a region (`.position`: `"high"`, `"low"`, `"as fitted"`); `macroregion_of` and `calibration_of` take the ISTAT region code too. ## The traps - **mm is not mm/h.** `cumulated(D)` is a total in mm, `intensity(D)` a mean intensity in mm/h. Over 35 hours T5 asks 30.9 mm, not 30.9 mm/h. - **The line is not equally good everywhere.** 16.2 % of Valle d'Aosta's landslides are below it, 1.3 % of Calabria's, where 5 % is expected. Say it (`trust_facts`), and say when the landslides are too few to tell. - **A landslide with a day and no hour** takes the end of its day: the next local midnight in Europe/Rome, as UTC. Not noon, not 00:00, not +24 h. - **Exceedance is in decades**, `log10(I / I(D))`: +0.3 is twice the threshold intensity, +1 ten times; below zero is below. A dry event is `-inf`. - **The last event is not the one that matters.** A storm, six dry hours and 2.5 mm of drizzle are two events; `latest_event` gives the drizzle. Use `strongest_event` over the window you watch. - **Not measured is not dry.** A missing hour is `None`, never `0`: a zero can split an event and hide a storm. With `unmeasured_hours > 0` the total is a lower bound. - **Gauge, not radar.** The Italian thresholds are fitted on rain gauges. On radar or model rain the comparison is not validated: say so. In 2026 the DPC radar alone read about 20 % more than the gauge-corrected «Merging», and differently from place to place. - **Abruzzo and Molise are central**, not southern: use `macroregion_of`, not the ISTAT macroareas. Region names as e-ITALICA spells them ("Emilia-Romagna", "Trentino-Alto Adige"). - **T5 misses 5 % of past landslides by construction**, and says nothing of false alarms. To measure them: `rainfall_thresholds.measure` (`skill_at_budget`, `auc`), comparing two scores at the same alert budget. - **These are not the published e-ITALICA thresholds**: they are this library's fit on the e-ITALICA data. - **Units are fixed:** hours, mm, mm/h. The series must be hourly. Data: e-ITALICA v4 (Brunetti et al. 2024, doi:10.5281/zenodo.14204473), CC BY 4.0.