rainfall-thresholds 0.1.0__tar.gz → 0.3.0__tar.gz

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.
@@ -0,0 +1,610 @@
1
+ Metadata-Version: 2.4
2
+ Name: rainfall-thresholds
3
+ Version: 0.3.0
4
+ Summary: Rainfall intensity-duration thresholds for shallow landslides (Caine power law, frequentist fitting)
5
+ Keywords: landslide,rainfall threshold,intensity-duration,caine,hydrology,natural hazards,italy,italica
6
+ Author: Giuseppe Zileni
7
+ Author-email: Giuseppe Zileni <giuseppe.zileni@gmail.com>
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
13
+ Classifier: Topic :: Scientific/Engineering :: Hydrology
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Programming Language :: Python :: 3.13
18
+ Classifier: Typing :: Typed
19
+ Requires-Dist: mcp>=2.3 ; extra == 'mcp'
20
+ Requires-Python: >=3.12
21
+ Project-URL: Homepage, https://github.com/agent-engineering-studio/rainfall-thresholds
22
+ Project-URL: Issues, https://github.com/agent-engineering-studio/rainfall-thresholds/issues
23
+ Project-URL: Changelog, https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/CHANGELOG.md
24
+ Provides-Extra: mcp
25
+ Description-Content-Type: text/markdown
26
+
27
+ # rainfall-thresholds
28
+
29
+ **How much rain does it take to set off a landslide?**
30
+ A small, dependency-free Python library that answers that question with the
31
+ rainfall thresholds used in landslide science: turn an hourly rain-gauge
32
+ series into rainfall events, compare them with a threshold, and fit your own
33
+ threshold from past landslides. It ships ready-to-use thresholds for Italy,
34
+ fitted on 5,974 real landslides.
35
+
36
+ > **A threshold exceeded is not an alert.** It says the rain is like the rain
37
+ > that triggered landslides before. The official alert in Italy is the
38
+ > criticality bulletin of the
39
+ > [Dipartimento della Protezione Civile](https://rischi.protezionecivile.gov.it/it/meteo-idro/allertamento/).
40
+
41
+ **What it does not do.** It does not fetch rain: you bring the series, from a
42
+ gauge, a radar or a model. It does not say where a landslide will happen, and
43
+ it does not issue warnings. It does not know whether your radar can see:
44
+ mark the hours it could not measure as `None`.
45
+
46
+ [![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)
47
+ [![PyPI](https://img.shields.io/pypi/v/rainfall-thresholds)](https://pypi.org/project/rainfall-thresholds/)
48
+ [![Python](https://img.shields.io/pypi/pyversions/rainfall-thresholds)](https://pypi.org/project/rainfall-thresholds/)
49
+ [![Dependencies: none](https://img.shields.io/badge/dependencies-none-brightgreen)](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/pyproject.toml)
50
+ [![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)
51
+
52
+ <picture>
53
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/agent-engineering-studio/rainfall-thresholds/main/docs/img/id-plane-dark.png">
54
+ <img alt="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." src="https://raw.githubusercontent.com/agent-engineering-studio/rainfall-thresholds/main/docs/img/id-plane-light.png">
55
+ </picture>
56
+
57
+ <sub>Every grey dot is a storm that triggered a landslide in Italy (e-ITALICA
58
+ catalogue). The blue line is the threshold this library fits: only 5 % of
59
+ those storms fall below it. The red star is the storm from the
60
+ [quick start](#quick-start).</sub>
61
+
62
+ ---
63
+
64
+ ## Contents
65
+
66
+ - [The idea in 30 seconds](#the-idea-in-30-seconds)
67
+ - [How it works](#how-it-works)
68
+ - [Install](#install)
69
+ - [Quick start](#quick-start)
70
+ - [Step by step](#step-by-step)
71
+ - [1. From hourly rain to rainfall events](#1-from-hourly-rain-to-rainfall-events)
72
+ - [2. Comparing an event with a threshold](#2-comparing-an-event-with-a-threshold)
73
+ - [3. Fitting your own threshold](#3-fitting-your-own-threshold)
74
+ - [4. Measuring what it costs](#4-measuring-what-it-costs)
75
+ - [Thresholds for Italy](#thresholds-for-italy)
76
+ - [Recipe: check a rain gauge](#recipe-check-a-rain-gauge)
77
+ - [API at a glance](#api-at-a-glance)
78
+ - [Benchmark](#benchmark)
79
+ - [Notebooks and Docker](#notebooks-and-docker)
80
+ - [For assistants and agents](#for-assistants-and-agents)
81
+ - [Good to know](#good-to-know)
82
+ - [References](#references) · [Citing](#citing) · [Contributing](#contributing)
83
+
84
+ ## The idea in 30 seconds
85
+
86
+ Shallow landslides start when the soil gets too wet. What makes it too wet
87
+ is a mix of **how hard** it rains and **for how long**:
88
+
89
+ - a short, violent downpour can do it: 30 mm in 2 hours;
90
+ - so can a long, gentle rain: 60 mm over three days.
91
+
92
+ In 1980 Nels Caine noticed that, on a log-log chart of *duration* against
93
+ *mean intensity*, the storms that triggered landslides sit above a straight
94
+ line. That line is the **rainfall threshold**:
95
+
96
+ ```
97
+ I = α · D^(-β)
98
+
99
+ I mean rainfall intensity (mm/h)
100
+ D rainfall duration (hours)
101
+ α how high the line sits β how fast it drops with duration
102
+ ```
103
+
104
+ Above the line: rain like the rain that triggered landslides in the past.
105
+ Below it: rain that very rarely did. That is all a threshold says, and it is
106
+ why thresholds are at the heart of many landslide early-warning systems.
107
+
108
+ This library gives you the three pieces around that line, in plain Python
109
+ with no dependencies.
110
+
111
+ ## How it works
112
+
113
+ ```mermaid
114
+ flowchart LR
115
+ A["🌧️ Hourly rain<br/>(timestamp, mm)"] -->|reconstruct_events| B["Rainfall events<br/>duration · total · intensity"]
116
+ B -->|strongest_event| C["Event that matters"]
117
+ C -->|"threshold.exceedance()"| D{"Above the<br/>threshold?"}
118
+ D -->|"> 0"| E["⚠️ Conditions like<br/>past landslides"]
119
+ D -->|"< 0"| F["✅ Below the line"]
120
+
121
+ G["📚 Past landslides<br/>(duration, intensity)"] -->|fit_threshold| H["PowerLawThreshold<br/>α, β"]
122
+ I["🇮🇹 ITALICA_T5<br/>ready-made for Italy"] --> H
123
+ H --> D
124
+ ```
125
+
126
+ | Step | What you have | What you call | What you get |
127
+ |---|---|---|---|
128
+ | 1 | an hourly rain series | `reconstruct_events`, `strongest_event` | rainfall events, each with duration, total and intensity |
129
+ | 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 |
130
+ | 3 | a catalogue of landslide-triggering events | `fit_threshold` | your own threshold |
131
+
132
+ ## Install
133
+
134
+ ```bash
135
+ pip install rainfall-thresholds
136
+ ```
137
+
138
+ Python 3.12 or newer. No dependencies: not even NumPy.
139
+
140
+ ## Quick start
141
+
142
+ A storm over Calabria, southern Italy: 82 mm in about ten hours. Is it
143
+ landslide weather?
144
+
145
+ ```python
146
+ from datetime import UTC, datetime, timedelta
147
+
148
+ from rainfall_thresholds import ITALICA_T5, macroregion_of, reconstruct_events, strongest_event
149
+
150
+ # Hourly rain from a gauge, in mm
151
+ start = datetime(2026, 10, 10, tzinfo=UTC)
152
+ hourly_mm = [0, 2, 8, 15, 22, 18, 9, 4, 0, 1, 3, 0, 0]
153
+ series = [(start + timedelta(hours=h), mm) for h, mm in enumerate(hourly_mm)]
154
+
155
+ # 1. Pick the threshold for the region
156
+ threshold = ITALICA_T5[macroregion_of("Calabria") or "italy"] # "southern"
157
+
158
+ # 2. Cut the series into rainfall events and take the one that matters
159
+ events = reconstruct_events(series, no_rain_break_hours=6, min_event_mm=2.0)
160
+ event = strongest_event(events, threshold)
161
+ assert event is not None
162
+
163
+ # 3. Compare
164
+ print(f"{event.total_mm:.0f} mm in {event.duration_hours:.0f} h = {event.intensity_mm_h:.1f} mm/h")
165
+ print(f"T5 at that duration: {threshold.intensity(event.duration_hours):.1f} mm/h")
166
+ print(f"{threshold.exceedance(event.intensity_mm_h, event.duration_hours):+.2f} decades")
167
+ ```
168
+
169
+ ```
170
+ 82 mm in 10 h = 8.2 mm/h
171
+ T5 at that duration: 2.0 mm/h
172
+ +0.62 decades
173
+ ```
174
+
175
+ The storm is about four times as intense as the threshold (10^0.62 ≈ 4.2):
176
+ it is the red star in the chart at the top.
177
+
178
+ ## Step by step
179
+
180
+ ### 1. From hourly rain to rainfall events
181
+
182
+ A rain gauge gives you one number per hour. A threshold needs *events*: a
183
+ start, an end, a total. `reconstruct_events` cuts the series with two
184
+ simple rules:
185
+
186
+ - **`no_rain_break_hours`**: this many dry hours in a row end an event;
187
+ - **`min_event_mm`**: events with less rain than this are dropped as noise.
188
+
189
+ An event runs from its first to its last wet hour, so short dry spells
190
+ inside a storm stay in the same event.
191
+
192
+ <picture>
193
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/agent-engineering-studio/rainfall-thresholds/main/docs/img/event-reconstruction-dark.png">
194
+ <img alt="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." src="https://raw.githubusercontent.com/agent-engineering-studio/rainfall-thresholds/main/docs/img/event-reconstruction-light.png">
195
+ </picture>
196
+
197
+ ```python
198
+ threshold = ITALICA_T5["southern"]
199
+ events = reconstruct_events(series, no_rain_break_hours=6, min_event_mm=2.0)
200
+ for e in events:
201
+ print(e.start, e.end, e.duration_hours, e.total_mm, e.intensity_mm_h)
202
+
203
+ current = strongest_event(events, threshold) # the event furthest above the threshold
204
+ ```
205
+
206
+ **Which event?** A storm, six dry hours and then a little drizzle are two
207
+ events. `latest_event` gives the drizzle; `strongest_event` gives the storm.
208
+ For monitoring, pass the events of the window you watch (for example the last
209
+ 48 hours) to `strongest_event`, so an old storm does not stay forever.
210
+
211
+ Each event is a frozen `RainfallEvent` with `start`, `end`,
212
+ `duration_hours`, `total_mm`, `unmeasured_hours`, `source` and the
213
+ `intensity_mm_h` and `fully_measured` properties.
214
+
215
+ > **Not measured is not dry.** The series should be hourly and without gaps:
216
+ > a dry hour is `0`, an hour that was not measured (a missing frame, a gauge
217
+ > that did not report, a place the radar cannot see) is `None`. A `None` hour
218
+ > adds no rain and does not count towards the dry break, so a gap never splits
219
+ > an event. The event counts it in `unmeasured_hours`, and its total is then a
220
+ > lower bound. If your gauge skips dry hours, fill them in with `0`.
221
+
222
+ Give the events a `source` (`reconstruct_events(..., source="DPC SRT1")`):
223
+ the Italian thresholds are fitted on rain gauges, and radar rain is not gauge
224
+ rain. The label is carried, never interpreted.
225
+
226
+ ### 2. Comparing an event with a threshold
227
+
228
+ A `PowerLawThreshold` answers three questions for an event of a given
229
+ duration:
230
+
231
+ | Method | Question | Unit |
232
+ |---|---|---|
233
+ | `intensity(D)` | How intense must rain be, on average, to reach the line? | mm/h |
234
+ | `cumulated(D)` | How much rain in total must fall to reach the line? | mm |
235
+ | `exceedance(I, D)` | How far above (+) or below (−) the line is this event? | decades |
236
+
237
+ `cumulated` is usually the easiest to talk about. With the threshold for
238
+ northern Italy:
239
+
240
+ ```python
241
+ from rainfall_thresholds import ITALICA_T5
242
+
243
+ t = ITALICA_T5["northern"]
244
+ for d in (1, 6, 24, 72):
245
+ print(f"{d:>3} h {t.cumulated(d):5.1f} mm {t.intensity(d):5.2f} mm/h")
246
+ ```
247
+
248
+ ```
249
+ 1 h 6.4 mm 6.40 mm/h
250
+ 6 h 15.3 mm 2.55 mm/h
251
+ 24 h 30.0 mm 1.25 mm/h
252
+ 72 h 51.3 mm 0.71 mm/h
253
+ ```
254
+
255
+ Longer rain needs more water in total, but less per hour.
256
+
257
+ **Reading `exceedance`.** It is `log10(I / I(D))`, so it is scale-free and
258
+ easy to put on a dashboard. Four 24-hour events against the national
259
+ threshold (28 mm in 24 h):
260
+
261
+ | Rain in 24 h | Mean intensity | `exceedance` | In words |
262
+ |---:|---:|---:|---|
263
+ | 12 mm | 0.5 mm/h | −0.37 | well below the line |
264
+ | 24 mm | 1.0 mm/h | −0.07 | just below |
265
+ | 58 mm | 2.4 mm/h | +0.31 | twice the threshold intensity |
266
+ | 288 mm | 12 mm/h | +1.01 | ten times: an extreme event |
267
+
268
+ A dry event (zero intensity) gives `-inf`.
269
+
270
+ ### 3. Fitting your own threshold
271
+
272
+ Have a list of landslides and the rain that triggered them? Fit a threshold
273
+ for your own area:
274
+
275
+ ```python
276
+ from rainfall_thresholds import fit_threshold
277
+
278
+ # (duration in hours, mean intensity in mm/h) of rain that triggered landslides
279
+ triggering_events = [
280
+ (3, 9.0),
281
+ (5, 4.0),
282
+ (6, 6.5),
283
+ (10, 5.5),
284
+ (12, 3.1),
285
+ (24, 2.4),
286
+ (30, 1.4),
287
+ (48, 1.1),
288
+ (72, 1.0),
289
+ (96, 0.6),
290
+ ]
291
+
292
+ fit = fit_threshold(triggering_events, percentile=5)
293
+ t = fit.threshold
294
+ print(f"T5: I = {t.alpha:.2f} · D^-{t.beta:.3f} ({fit.n_events} events)")
295
+ print(f"at 24 h: {t.intensity(24):.2f} mm/h, i.e. {t.cumulated(24):.0f} mm")
296
+ ```
297
+
298
+ ```
299
+ T5: I = 14.78 · D^-0.737 (10 events)
300
+ at 24 h: 1.42 mm/h, i.e. 34 mm
301
+ ```
302
+
303
+ (Ten events are enough for an example, not for a real threshold: published
304
+ thresholds use hundreds.)
305
+
306
+ What `fit_threshold` does, in two steps:
307
+
308
+ 1. **Best-fit line.** Least squares on `log I` against `log D` through all
309
+ the events: the orange line below, returned as `fit.central`.
310
+ 2. **Lower it.** Slide the line down, keeping its slope, until only
311
+ `percentile` % of the events sit beneath it: the blue line, returned as
312
+ `fit.threshold`. With `percentile=5` this is the **T5** threshold.
313
+
314
+ <picture>
315
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/agent-engineering-studio/rainfall-thresholds/main/docs/img/fitting-dark.png">
316
+ <img alt="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." src="https://raw.githubusercontent.com/agent-engineering-studio/rainfall-thresholds/main/docs/img/fitting-light.png">
317
+ </picture>
318
+
319
+ This is the frequentist method of Brunetti et al. (2010) and Peruccacci et
320
+ al. (2012), with one difference: they take the percentile from a Gaussian
321
+ fitted to a kernel density of the residuals; this package takes it straight
322
+ from the residuals. The two agree when the residuals are close to normal,
323
+ and the empirical one makes no assumption about their shape.
324
+
325
+ ### 4. Measuring what it costs
326
+
327
+ T5 catches 95 % of past landslides by construction. What it does not say is
328
+ how often it is exceeded when nothing happens. The `measure` functions answer
329
+ both on the same scale, for any score that grows with danger (an exceedance,
330
+ a 24-hour total, a probability):
331
+
332
+ ```python
333
+ from rainfall_thresholds import auc, skill, skill_at_budget
334
+
335
+ # For each landslide, the highest score in the hours before it.
336
+ landslides = [0.62, 0.31, 0.05, -0.08, 0.44]
337
+ # For each unit you could alert on (cell-hours, municipality-days...).
338
+ ordinary = [-0.9, -0.4, -0.2, 0.1, -0.6, -0.3, 0.2, -1.1, -0.5, -0.7]
339
+
340
+ s = skill(landslides, ordinary, cutoff=0.0) # above the threshold = alert
341
+ print(f"caught {s.caught} of {s.landslides}, {s.alert_share:.0%} of units on alert")
342
+ print(f"discrimination {s.discrimination:.1f}, {s.alerts_per_caught:.1f} alerts per landslide")
343
+
344
+ fair = skill_at_budget(landslides, ordinary, budget=0.10) # 10 % of units on alert
345
+ print(f"at a 10 % budget: caught {fair.caught} of {fair.landslides}")
346
+ print(f"AUC {auc(landslides, ordinary):.2f}")
347
+ ```
348
+
349
+ ```
350
+ caught 4 of 5, 20% of units on alert
351
+ discrimination 4.0, 0.5 alerts per landslide
352
+ at a 10 % budget: caught 3 of 5
353
+ AUC 0.92
354
+ ```
355
+
356
+ To compare two scores, compare them **at the same budget**: counting at a
357
+ fixed level rewards the score that alerts more. `None` is a score that was
358
+ not measured: it is left out and counted in `unmeasured`, never read as
359
+ zero. The definitions are those of Limen's backtests, and on the same inputs
360
+ the results are identical.
361
+
362
+ What this gives on real data was measured in Limen
363
+ ([limen#243](https://github.com/agent-engineering-studio/limen/issues/243)),
364
+ with the national curve on model rain (ERA5): 40.7 % of the e-ITALICA
365
+ landslides above the threshold against 3.0 % of ordinary moments, and 0 of
366
+ 286 landslides caught in the regions held out. A threshold fitted on rain
367
+ gauges and applied to other rain is not the same threshold.
368
+
369
+ ## Thresholds for Italy
370
+
371
+ `ITALICA_T5` holds four T5 thresholds fitted with `fit_threshold(percentile=5)`
372
+ on the 5,974 events of [e-ITALICA](https://doi.org/10.5281/zenodo.14204473)
373
+ v4 with a positive duration and cumulated rainfall:
374
+
375
+ | Key | α (mm/h) | β | Events | Rain needed in 24 h | in 72 h |
376
+ |---|---:|---:|---:|---:|---:|
377
+ | `"italy"` | 7.193 | 0.5685 | 5,974 | 28.3 mm | 45.5 mm |
378
+ | `"northern"` | 6.400 | 0.5134 | 2,659 | 30.0 mm | 51.3 mm |
379
+ | `"central"` | 7.953 | 0.6085 | 1,890 | 27.6 mm | 42.4 mm |
380
+ | `"southern"` | 8.754 | 0.6449 | 1,425 | 27.1 mm | 40.0 mm |
381
+
382
+ <picture>
383
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/agent-engineering-studio/rainfall-thresholds/main/docs/img/macroregions-dark.png">
384
+ <img alt="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." src="https://raw.githubusercontent.com/agent-engineering-studio/rainfall-thresholds/main/docs/img/macroregions-light.png">
385
+ </picture>
386
+
387
+ For short bursts the regions behave alike; over days, the north needs
388
+ noticeably more rain than the south before landslides start.
389
+
390
+ Pick the threshold from the region name with `macroregion_of`:
391
+
392
+ ```python
393
+ from rainfall_thresholds import ITALICA_T5, macroregion_of
394
+
395
+ macroregion_of("Liguria") # "northern"
396
+ macroregion_of("Abruzzo") # "central"
397
+ macroregion_of("Bavaria") # None: not an Italian region
398
+
399
+ threshold = ITALICA_T5[macroregion_of("Sicilia") or "italy"]
400
+ ```
401
+
402
+ > **Abruzzo and Molise are in the centre**, unlike the ISTAT "Sud". Use
403
+ > `macroregion_of` (or `MACROREGIONS`) rather than an ISTAT table, or the
404
+ > threshold will not be the one fitted on that region's landslides.
405
+
406
+ These numbers are **reproducible, not copied**: the catalogue ships with the
407
+ tests and `tests/test_italy.py` refits all four thresholds from it on every
408
+ run. They are not the thresholds published by the e-ITALICA authors, who use
409
+ their own method and partitions; they are what this package's method gives
410
+ on their data.
411
+
412
+ ## Recipe: check a rain gauge
413
+
414
+ Read an hourly CSV, find the current rainfall event and see where it stands:
415
+
416
+ ```python
417
+ import csv
418
+ from datetime import datetime
419
+
420
+ from rainfall_thresholds import ITALICA_T5, macroregion_of, reconstruct_events, strongest_event
421
+
422
+ with open("gauge.csv", encoding="utf-8") as f: # columns: time, rain_mm (empty: not measured)
423
+ series = [
424
+ (datetime.fromisoformat(r["time"]), float(r["rain_mm"]) if r["rain_mm"] else None)
425
+ for r in csv.DictReader(f)
426
+ ]
427
+
428
+ threshold = ITALICA_T5[macroregion_of("Liguria") or "italy"]
429
+ events = reconstruct_events(series, no_rain_break_hours=6, min_event_mm=2.0, source="rain gauge")
430
+ event = strongest_event(events, threshold)
431
+
432
+ if event is None:
433
+ print("No rain event in the window")
434
+ else:
435
+ e = threshold.exceedance(event.intensity_mm_h, event.duration_hours)
436
+ needed = threshold.cumulated(event.duration_hours)
437
+ print(
438
+ f"{event.start:%d %b %H:%M} → {event.end:%H:%M}: {event.total_mm:.0f} mm "
439
+ f"(T5 needs {needed:.0f} mm in {event.duration_hours:.0f} h) → {e:+.2f}"
440
+ )
441
+ ```
442
+
443
+ ```
444
+ 10 Oct 01:00 → 07:00: 78 mm (T5 needs 16 mm in 7 h) → +0.67
445
+ ```
446
+
447
+ Run it every hour on the last two or three days of data and you have the
448
+ rainfall part of a simple monitoring loop: a number to watch, not an alert.
449
+
450
+ ## API at a glance
451
+
452
+ | Name | Kind | What it is |
453
+ |---|---|---|
454
+ | `PowerLawThreshold(alpha, beta)` | frozen dataclass | `I = α·D^(-β)`, with `.intensity(D)`, `.cumulated(D)`, `.exceedance(I, D)` |
455
+ | `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 |
456
+ | `strongest_event(events, threshold)` | function | the event furthest above the threshold, or `None` |
457
+ | `latest_event(events)` | function | the event that ended last, or `None` |
458
+ | `RainfallEvent` | frozen dataclass | `start`, `end`, `duration_hours`, `total_mm`, `unmeasured_hours`, `source`, `.intensity_mm_h`, `.fully_measured` |
459
+ | `fit_threshold(events, *, percentile=5.0)` | function | `(D, I)` pairs → `ThresholdFit` |
460
+ | `ThresholdFit` | frozen dataclass | `threshold`, `central`, `percentile`, `n_events` |
461
+ | `percentile_of(values, percentile)` | function | linear-interpolation percentile, same as NumPy's default |
462
+ | `skill(landslides, ordinary, cutoff)` | function | landslides caught and units on alert at a cutoff → `Skill` |
463
+ | `skill_at_budget(landslides, ordinary, budget, *, floor=None)` | function | the same at the cutoff that puts `budget` of the units on alert |
464
+ | `cutoff_at_budget(ordinary, budget, *, floor=None)` | function | that cutoff |
465
+ | `Skill` | frozen dataclass | `caught`, `landslides`, `alerts`, `ordinary`, `unmeasured`; `.hit_rate`, `.alert_share`, `.discrimination`, `.alerts_per_caught` |
466
+ | `auc(landslides, ordinary)` | function | Mann-Whitney AUC, ties count half |
467
+ | `facts.threshold_facts`, `assess_facts`, `fit_facts` | functions | the same answers as JSON-ready dicts, with units and the alert rule |
468
+ | `check.check_text(text, facts, *, question="")` | function | numbers of a text that are invented, rounded or in the wrong unit → `list[Misquote]` |
469
+ | `mcp_server.create_server()`, `rainfall-thresholds-mcp` | MCP (extra `mcp`) | tools `threshold`, `assess`, `fit`, `check` |
470
+ | `ITALICA_T5` | read-only mapping | `"italy"`, `"northern"`, `"central"`, `"southern"` → `PowerLawThreshold` |
471
+ | `MACROREGIONS` | read-only mapping | macroregion → set of region names (e-ITALICA spelling) |
472
+ | `macroregion_of(region)` | function | region name → macroregion, or `None` |
473
+
474
+ Everything is fully typed (`py.typed`) and checked with `mypy --strict`.
475
+
476
+ ## Benchmark
477
+
478
+ A fixed set of known cases runs in CI: the storm of Melito di Porto Salvo on
479
+ 10 October 2026 on the DPC radar, six e-ITALICA landslides, and two cases
480
+ built to test one rule each. 0.1.0 passed **9 of 16** checks: it forgot a
481
+ storm when a little drizzle followed it, and could not take an hour that was
482
+ not measured. With `strongest_event` and `None` the library passes **13 of
483
+ 16**. The three it misses are landslides under T5, as T5 allows by
484
+ construction. The details, and what is not there yet, are in
485
+ [`benchmarks/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/benchmarks).
486
+
487
+ ```bash
488
+ uv run python -m benchmarks.run
489
+ ```
490
+
491
+ ## Notebooks and Docker
492
+
493
+ Three [example notebooks](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/notebooks)
494
+ need no network: the Italian thresholds over the e-ITALICA landslides, the
495
+ storm of Melito on the DPC radar, and fitting your own threshold. Open them
496
+ with uv, or with Docker alone:
497
+
498
+ ```bash
499
+ uv run --group examples jupyter lab notebooks/
500
+ docker compose up # http://localhost:8888
501
+ make docker-bench # the benchmark, in a container
502
+ ```
503
+
504
+ The compose file gives no fixed name to containers or images: Compose names
505
+ them after the project, so two copies run side by side.
506
+
507
+ ## For assistants and agents
508
+
509
+ A language model may word the numbers; it should never compute them. The
510
+ library gives them as data, and checks the words.
511
+
512
+ - **Facts.** `rainfall_thresholds.facts`: `threshold_facts`, `assess_facts`
513
+ and `fit_facts` return plain dicts, with the unit in every key (`_mm`,
514
+ `_mm_h`, `_h`, `_decades`), what the threshold was fitted on, and the rule
515
+ that a threshold exceeded is not an alert.
516
+ - **MCP server.** `pip install "rainfall-thresholds[mcp]"`, then
517
+ `rainfall-thresholds-mcp` on standard input and output. Four tools:
518
+ `threshold`, `assess`, `fit`, `check`. They compute only from what the call
519
+ gives them: no network, no live rain.
520
+ - **A check of the text.** `check_text(text, facts)` finds numbers invented,
521
+ rounded the wrong way, or in the wrong unit: 30.9 mm written as 30.9 mm/h,
522
+ the trap of every rainfall threshold. It knows that a number is a fact of
523
+ its unit, not that it is said of the right thing.
524
+ - **A faithfulness set.** `benchmarks/faithful.py`: questions, facts, and
525
+ answers written by hand, one faithful and one with known faults; in CI the
526
+ check must find exactly those faults (8 of 8 today). Answers of a model are
527
+ not in it yet.
528
+ - **For coding agents.** [`llms.txt`](https://agentengineering.it/rainfall-thresholds/llms.txt),
529
+ [`llms-full.txt`](https://agentengineering.it/rainfall-thresholds/llms-full.txt)
530
+ and an [agent skill](https://agentengineering.it/rainfall-thresholds/skills/rainfall-thresholds/SKILL.md)
531
+ with the traps a model falls into when it writes this code from memory.
532
+
533
+ The base package still has no dependencies: the MCP SDK comes only with the
534
+ `mcp` extra.
535
+
536
+ ## Good to know
537
+
538
+ - **A threshold is not a forecast.** Rain above T5 means "conditions like
539
+ those that triggered landslides before", not "a landslide will happen
540
+ here". Slope, soil, vegetation and antecedent wetness all matter. Use it
541
+ as one input to a warning system, alongside expert judgement.
542
+ - **T5 is deliberately low.** By construction, 95 % of past triggering
543
+ events sit above it: it favours catching events over avoiding false
544
+ alarms.
545
+ - **Event reconstruction is simplified.** It follows Melillo et al. (2018),
546
+ whose CTRL-T tool also varies the dry gap with the season. The e-ITALICA
547
+ durations come from that fuller procedure, so applying the Italian
548
+ thresholds to events from `reconstruct_events` mixes the two: fine for
549
+ monitoring, worth knowing for a study.
550
+ - **Units are fixed:** hours, millimetres, millimetres per hour.
551
+
552
+ ## Where it's used
553
+
554
+ Extracted from [Limen](https://github.com/agent-engineering-studio/limen),
555
+ which uses it for the rainfall component of its landslide score. Using it
556
+ somewhere else? [Open an issue](https://github.com/agent-engineering-studio/rainfall-thresholds/issues)
557
+ and tell us: we'd love to list it here.
558
+
559
+ ## References
560
+
561
+ - Caine N. (1980). The rainfall intensity-duration control of shallow
562
+ landslides and debris flows. *Geografiska Annaler A* 62, 23-27.
563
+ - Brunetti M.T. et al. (2010). Rainfall thresholds for the possible
564
+ occurrence of landslides in Italy. *NHESS* 10, 447-458.
565
+ - Peruccacci S. et al. (2012). Lithological and seasonal control on
566
+ rainfall thresholds for the possible initiation of landslides in central
567
+ Italy. *Geomorphology* 139-140, 79-90.
568
+ - Melillo M. et al. (2018). A tool for the automatic calculation of
569
+ rainfall thresholds for landslide occurrence. *Environmental Modelling &
570
+ Software* 105, 230-243.
571
+ - Peruccacci S. et al. (2023). ITALICA: an ITAlian rainfall-induced
572
+ LandslIdes CAtalogue. *ESSD* 15, 2863-2877.
573
+ - Brunetti M.T. et al. (2024). e-ITALICA (enhanced ITAlian rainfall-induced
574
+ LandslIdes CAtalogue), v4. Zenodo,
575
+ [doi:10.5281/zenodo.14204473](https://doi.org/10.5281/zenodo.14204473).
576
+
577
+ ## Citing
578
+
579
+ If this library helps your work, please cite the method and data papers
580
+ above, and link to this repository:
581
+
582
+ ```
583
+ Zileni G. rainfall-thresholds: rainfall intensity-duration thresholds for
584
+ shallow landslides (Python). https://github.com/agent-engineering-studio/rainfall-thresholds
585
+ ```
586
+
587
+ ## Contributing
588
+
589
+ Issues and pull requests are welcome: new regional thresholds, better event
590
+ reconstruction, examples from other countries. See
591
+ [CONTRIBUTING.md](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/CONTRIBUTING.md). To set up and run the checks:
592
+
593
+ ```bash
594
+ uv sync
595
+ make check # ruff, mypy --strict, pytest with 100 % coverage
596
+ make figures # redraw the README charts (docs/make_figures.py)
597
+ ```
598
+
599
+ ⭐ If you find it useful, a star helps others find it.
600
+
601
+ ## Data licence
602
+
603
+ The test fixture `tests/fixtures/italica_v4_dur_rain.csv` is e-ITALICA v4
604
+ (Brunetti et al. 2024), [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/),
605
+ reduced to four columns (id, region, duration, cumulated rainfall). The
606
+ charts in `docs/img/` are drawn from it.
607
+
608
+ ## License
609
+
610
+ Code: [Apache-2.0](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/LICENSE).