rainfall-thresholds 0.2.0__tar.gz → 0.4.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.
Files changed (21) hide show
  1. {rainfall_thresholds-0.2.0 → rainfall_thresholds-0.4.0}/PKG-INFO +184 -6
  2. {rainfall_thresholds-0.2.0 → rainfall_thresholds-0.4.0}/README.md +181 -5
  3. {rainfall_thresholds-0.2.0 → rainfall_thresholds-0.4.0}/pyproject.toml +19 -1
  4. {rainfall_thresholds-0.2.0 → rainfall_thresholds-0.4.0}/pyproject.toml.orig +23 -1
  5. rainfall_thresholds-0.4.0/src/rainfall_thresholds/__init__.py +72 -0
  6. rainfall_thresholds-0.4.0/src/rainfall_thresholds/antecedent.py +79 -0
  7. rainfall_thresholds-0.4.0/src/rainfall_thresholds/assess.py +176 -0
  8. rainfall_thresholds-0.4.0/src/rainfall_thresholds/check.py +165 -0
  9. rainfall_thresholds-0.4.0/src/rainfall_thresholds/facts.py +150 -0
  10. {rainfall_thresholds-0.2.0 → rainfall_thresholds-0.4.0}/src/rainfall_thresholds/italy.py +63 -3
  11. rainfall_thresholds-0.4.0/src/rainfall_thresholds/mcp_server.py +126 -0
  12. rainfall_thresholds-0.4.0/src/rainfall_thresholds/measure.py +163 -0
  13. rainfall_thresholds-0.4.0/src/rainfall_thresholds/regional.py +115 -0
  14. rainfall_thresholds-0.4.0/src/rainfall_thresholds/regional_thresholds.toml +443 -0
  15. rainfall_thresholds-0.4.0/src/rainfall_thresholds/sources.py +41 -0
  16. {rainfall_thresholds-0.2.0 → rainfall_thresholds-0.4.0}/src/rainfall_thresholds/threshold.py +10 -0
  17. rainfall_thresholds-0.2.0/src/rainfall_thresholds/__init__.py +0 -30
  18. {rainfall_thresholds-0.2.0 → rainfall_thresholds-0.4.0}/LICENSE +0 -0
  19. {rainfall_thresholds-0.2.0 → rainfall_thresholds-0.4.0}/src/rainfall_thresholds/events.py +0 -0
  20. {rainfall_thresholds-0.2.0 → rainfall_thresholds-0.4.0}/src/rainfall_thresholds/fit.py +0 -0
  21. {rainfall_thresholds-0.2.0 → rainfall_thresholds-0.4.0}/src/rainfall_thresholds/py.typed +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rainfall-thresholds
3
- Version: 0.2.0
3
+ Version: 0.4.0
4
4
  Summary: Rainfall intensity-duration thresholds for shallow landslides (Caine power law, frequentist fitting)
5
5
  Keywords: landslide,rainfall threshold,intensity-duration,caine,hydrology,natural hazards,italy,italica
6
6
  Author: Giuseppe Zileni
@@ -16,10 +16,12 @@ Classifier: Programming Language :: Python :: 3
16
16
  Classifier: Programming Language :: Python :: 3.12
17
17
  Classifier: Programming Language :: Python :: 3.13
18
18
  Classifier: Typing :: Typed
19
+ Requires-Dist: mcp>=2.3 ; extra == 'mcp'
19
20
  Requires-Python: >=3.12
20
21
  Project-URL: Homepage, https://github.com/agent-engineering-studio/rainfall-thresholds
21
22
  Project-URL: Issues, https://github.com/agent-engineering-studio/rainfall-thresholds/issues
22
23
  Project-URL: Changelog, https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/CHANGELOG.md
24
+ Provides-Extra: mcp
23
25
  Description-Content-Type: text/markdown
24
26
 
25
27
  # rainfall-thresholds
@@ -43,6 +45,7 @@ mark the hours it could not measure as `None`.
43
45
 
44
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)
45
47
  [![PyPI](https://img.shields.io/pypi/v/rainfall-thresholds)](https://pypi.org/project/rainfall-thresholds/)
48
+ [![docs](https://img.shields.io/badge/docs-agentengineering.it-blue)](https://agentengineering.it/rainfall-thresholds/)
46
49
  [![Python](https://img.shields.io/pypi/pyversions/rainfall-thresholds)](https://pypi.org/project/rainfall-thresholds/)
47
50
  [![Dependencies: none](https://img.shields.io/badge/dependencies-none-brightgreen)](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/pyproject.toml)
48
51
  [![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)
@@ -57,6 +60,13 @@ catalogue). The blue line is the threshold this library fits: only 5 % of
57
60
  those storms fall below it. The red star is the storm from the
58
61
  [quick start](#quick-start).</sub>
59
62
 
63
+ **Read the story:** [Basta questa pioggia per far franare?](https://agentengineering.it/blog/soglie-pioggia-frane-rainfall-thresholds/)
64
+ ([English](https://agentengineering.it/en/blog/soglie-pioggia-frane-rainfall-thresholds/)),
65
+ the last episode of the Open Data series, after
66
+ [dpc-radar](https://agentengineering.it/blog/pioggia-radar-protezione-civile-dpc-radar/)
67
+ and [ispra-idrogeo](https://agentengineering.it/blog/frane-pericolo-idrogeologico-ispra-idrogeo/).
68
+ **Try it** in the browser: [the intensity-duration plane](https://agentengineering.it/rainfall-thresholds/explainer/).
69
+
60
70
  ---
61
71
 
62
72
  ## Contents
@@ -69,10 +79,15 @@ those storms fall below it. The red star is the storm from the
69
79
  - [1. From hourly rain to rainfall events](#1-from-hourly-rain-to-rainfall-events)
70
80
  - [2. Comparing an event with a threshold](#2-comparing-an-event-with-a-threshold)
71
81
  - [3. Fitting your own threshold](#3-fitting-your-own-threshold)
82
+ - [4. Measuring what it costs](#4-measuring-what-it-costs)
72
83
  - [Thresholds for Italy](#thresholds-for-italy)
73
84
  - [Recipe: check a rain gauge](#recipe-check-a-rain-gauge)
74
85
  - [API at a glance](#api-at-a-glance)
75
86
  - [Benchmark](#benchmark)
87
+ - [Notebooks and Docker](#notebooks-and-docker)
88
+ - [A calibration bench for public bodies](#a-calibration-bench-for-public-bodies)
89
+ - [For assistants and agents](#for-assistants-and-agents)
90
+ - [Roadmap: what is measured, what is open](#roadmap-what-is-measured-what-is-open)
76
91
  - [Good to know](#good-to-know)
77
92
  - [References](#references) · [Citing](#citing) · [Contributing](#contributing)
78
93
 
@@ -317,6 +332,50 @@ fitted to a kernel density of the residuals; this package takes it straight
317
332
  from the residuals. The two agree when the residuals are close to normal,
318
333
  and the empirical one makes no assumption about their shape.
319
334
 
335
+ ### 4. Measuring what it costs
336
+
337
+ T5 catches 95 % of past landslides by construction. What it does not say is
338
+ how often it is exceeded when nothing happens. The `measure` functions answer
339
+ both on the same scale, for any score that grows with danger (an exceedance,
340
+ a 24-hour total, a probability):
341
+
342
+ ```python
343
+ from rainfall_thresholds import auc, skill, skill_at_budget
344
+
345
+ # For each landslide, the highest score in the hours before it.
346
+ landslides = [0.62, 0.31, 0.05, -0.08, 0.44]
347
+ # For each unit you could alert on (cell-hours, municipality-days...).
348
+ ordinary = [-0.9, -0.4, -0.2, 0.1, -0.6, -0.3, 0.2, -1.1, -0.5, -0.7]
349
+
350
+ s = skill(landslides, ordinary, cutoff=0.0) # above the threshold = alert
351
+ print(f"caught {s.caught} of {s.landslides}, {s.alert_share:.0%} of units on alert")
352
+ print(f"discrimination {s.discrimination:.1f}, {s.alerts_per_caught:.1f} alerts per landslide")
353
+
354
+ fair = skill_at_budget(landslides, ordinary, budget=0.10) # 10 % of units on alert
355
+ print(f"at a 10 % budget: caught {fair.caught} of {fair.landslides}")
356
+ print(f"AUC {auc(landslides, ordinary):.2f}")
357
+ ```
358
+
359
+ ```
360
+ caught 4 of 5, 20% of units on alert
361
+ discrimination 4.0, 0.5 alerts per landslide
362
+ at a 10 % budget: caught 3 of 5
363
+ AUC 0.92
364
+ ```
365
+
366
+ To compare two scores, compare them **at the same budget**: counting at a
367
+ fixed level rewards the score that alerts more. `None` is a score that was
368
+ not measured: it is left out and counted in `unmeasured`, never read as
369
+ zero. The definitions are those of Limen's backtests, and on the same inputs
370
+ the results are identical.
371
+
372
+ What this gives on real data was measured in Limen
373
+ ([limen#243](https://github.com/agent-engineering-studio/limen/issues/243)),
374
+ with the national curve on model rain (ERA5): 40.7 % of the e-ITALICA
375
+ landslides above the threshold against 3.0 % of ordinary moments, and 0 of
376
+ 286 landslides caught in the regions held out. A threshold fitted on rain
377
+ gauges and applied to other rain is not the same threshold.
378
+
320
379
  ## Thresholds for Italy
321
380
 
322
381
  `ITALICA_T5` holds four T5 thresholds fitted with `fit_threshold(percentile=5)`
@@ -402,7 +461,7 @@ rainfall part of a simple monitoring loop: a number to watch, not an alert.
402
461
 
403
462
  | Name | Kind | What it is |
404
463
  |---|---|---|
405
- | `PowerLawThreshold(alpha, beta)` | frozen dataclass | `I = α·D^(-β)`, with `.intensity(D)`, `.cumulated(D)`, `.exceedance(I, D)` |
464
+ | `PowerLawThreshold(alpha, beta)` | frozen dataclass | `I = α·D^(-β)`, with `.intensity(D)`, `.cumulated(D)`, `.exceedance(I, D)`, `.scaled(factor)` |
406
465
  | `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 |
407
466
  | `strongest_event(events, threshold)` | function | the event furthest above the threshold, or `None` |
408
467
  | `latest_event(events)` | function | the event that ended last, or `None` |
@@ -410,9 +469,28 @@ rainfall part of a simple monitoring loop: a number to watch, not an alert.
410
469
  | `fit_threshold(events, *, percentile=5.0)` | function | `(D, I)` pairs → `ThresholdFit` |
411
470
  | `ThresholdFit` | frozen dataclass | `threshold`, `central`, `percentile`, `n_events` |
412
471
  | `percentile_of(values, percentile)` | function | linear-interpolation percentile, same as NumPy's default |
472
+ | `skill(landslides, ordinary, cutoff)` | function | landslides caught and units on alert at a cutoff → `Skill` |
473
+ | `skill_at_budget(landslides, ordinary, budget, *, floor=None)` | function | the same at the cutoff that puts `budget` of the units on alert |
474
+ | `cutoff_at_budget(ordinary, budget, *, floor=None)` | function | that cutoff |
475
+ | `Skill` | frozen dataclass | `caught`, `landslides`, `alerts`, `ordinary`, `unmeasured`; `.hit_rate`, `.alert_share`, `.discrimination`, `.alerts_per_caught` |
476
+ | `auc(landslides, ordinary)` | function | Mann-Whitney AUC, ties count half |
477
+ | `facts.threshold_facts`, `assess_facts`, `fit_facts` | functions | the same answers as JSON-ready dicts, with units and the alert rule |
478
+ | `check.check_text(text, facts, *, question="")` | function | numbers of a text that are invented, rounded or in the wrong unit → `list[Misquote]` |
479
+ | `mcp_server.create_server()`, `rainfall-thresholds-mcp` | MCP (extra `mcp`) | tools `threshold`, `assess`, `fit`, `check` |
413
480
  | `ITALICA_T5` | read-only mapping | `"italy"`, `"northern"`, `"central"`, `"southern"` → `PowerLawThreshold` |
414
481
  | `MACROREGIONS` | read-only mapping | macroregion → set of region names (e-ITALICA spelling) |
415
- | `macroregion_of(region)` | function | region name → macroregion, or `None` |
482
+ | `macroregion_of(region)` | function | region name or ISTAT region code (`8`, `"08"`) → macroregion, or `None` |
483
+ | `ISTAT_REGIONS` | read-only mapping | ISTAT region code → region name |
484
+ | `threshold_for(macroregion, thresholds=ITALICA_T5, *, default="italy")` | function | the threshold of a macroregion, or the default one |
485
+ | `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` |
486
+ | `EventAssessment` | frozen dataclass | `event`, `threshold`, `borders_unmeasured`; `.threshold_mm_h`, `.threshold_mm`, `.ratio`, `.excess_decades`, `.at_least` |
487
+ | `cumulate(hours, end, *, windows_hours)` | function | the totals of the last N hours → `{N: WindowTotal}`; no total when an hour is not measured |
488
+ | `caine_excess(event, threshold, *, radar_gauge_factor=1.0)` | function | decades above the line, zero on or below it |
489
+ | `api_kohler_linsley(daily_precip_mm, *, decay_k, initial=0.0)` | function | the Antecedent Precipitation Index, mm |
490
+ | `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 |
491
+ | `load_regional_catalogue()` | function | published regional thresholds with their sources → `RegionalCatalogue` of `RegionalThreshold` and `Source` |
492
+ | `RainSource` | `typing.Protocol` | `hourly(points, start, end) -> dict[datetime, list[float or None]]`: what can feed the package |
493
+ | `point_series(rain, index)` | function | the series of one point out of `RainSource.hourly` |
416
494
 
417
495
  Everything is fully typed (`py.typed`) and checked with `mypy --strict`.
418
496
 
@@ -431,6 +509,94 @@ construction. The details, and what is not there yet, are in
431
509
  uv run python -m benchmarks.run
432
510
  ```
433
511
 
512
+ ## Notebooks and Docker
513
+
514
+ Four [example notebooks](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/notebooks):
515
+ the Italian thresholds over the e-ITALICA landslides, the storm of Melito on
516
+ the DPC radar, and fitting your own threshold, with no network; and the join
517
+ with the sister libraries, landslides dated by
518
+ [ispra-idrogeo](https://agentengineering.it/ispra-idrogeo/) against radar rain
519
+ from [dpc-radar](https://agentengineering.it/dpc-radar/). Open them with uv, or
520
+ with Docker alone:
521
+
522
+ ```bash
523
+ uv run --group examples jupyter lab notebooks/
524
+ docker compose up # http://localhost:8888
525
+ make docker-bench # the benchmark, in a container
526
+ ```
527
+
528
+ The compose file gives no fixed name to containers or images: Compose names
529
+ them after the project, so two copies run side by side.
530
+
531
+ ## A calibration bench for public bodies
532
+
533
+ [`app/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/app)
534
+ is a page in Italian, with Bootstrap Italia, for a public body: it opens on
535
+ the e-ITALICA landslides of its region, fits a threshold on the ones that
536
+ matter, compares it with the national one, measures its cost in false alarms
537
+ on the body's own rain gauge, and exports it. It is not a warning system and
538
+ reads no live rain. `docker compose up taratura`, then http://localhost:3001.
539
+ [Riuso nella PA](https://agentengineering.it/rainfall-thresholds/riuso/)
540
+ says, in Italian, what it does and what stays with the body.
541
+
542
+ To explain what a threshold is, the docs site has
543
+ [Try it](https://agentengineering.it/rainfall-thresholds/explainer/): an
544
+ interactive intensity-duration plane that runs in the browser.
545
+
546
+ ## For assistants and agents
547
+
548
+ A language model may word the numbers; it should never compute them. The
549
+ library gives them as data, and checks the words.
550
+
551
+ - **Facts.** `rainfall_thresholds.facts`: `threshold_facts`, `assess_facts`
552
+ and `fit_facts` return plain dicts, with the unit in every key (`_mm`,
553
+ `_mm_h`, `_h`, `_decades`), what the threshold was fitted on, and the rule
554
+ that a threshold exceeded is not an alert.
555
+ - **MCP server.** `pip install "rainfall-thresholds[mcp]"`, then
556
+ `rainfall-thresholds-mcp` on standard input and output. Four tools:
557
+ `threshold`, `assess`, `fit`, `check`. They compute only from what the call
558
+ gives them: no network, no live rain.
559
+ - **A check of the text.** `check_text(text, facts)` finds numbers invented,
560
+ rounded the wrong way, or in the wrong unit: 30.9 mm written as 30.9 mm/h,
561
+ the trap of every rainfall threshold. It knows that a number is a fact of
562
+ its unit, not that it is said of the right thing.
563
+ - **A faithfulness set.** `benchmarks/faithful.py`: questions, facts, and
564
+ answers written by hand, one faithful and one with known faults; in CI the
565
+ check must find exactly those faults (8 of 8 today). Answers of a model are
566
+ not in it yet.
567
+ - **For coding agents.** [`llms.txt`](https://agentengineering.it/rainfall-thresholds/llms.txt),
568
+ [`llms-full.txt`](https://agentengineering.it/rainfall-thresholds/llms-full.txt)
569
+ and an [agent skill](https://agentengineering.it/rainfall-thresholds/skills/rainfall-thresholds/SKILL.md)
570
+ with the traps a model falls into when it writes this code from memory.
571
+
572
+ The base package still has no dependencies: the MCP SDK comes only with the
573
+ `mcp` extra.
574
+
575
+ ## Roadmap: what is measured, what is open
576
+
577
+ The plan is in [#4](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/4),
578
+ and the [roadmap page](https://agentengineering.it/rainfall-thresholds/roadmap/)
579
+ says what each phase measured.
580
+
581
+ - **Done:** the benchmark (#5), the strongest event and hours not measured
582
+ (#6), the functions to measure a threshold (#7), the AI layer (#9), the
583
+ calibration bench, Try it and `publiccode.yml` (#10), notebooks and Docker
584
+ (#14), the rule that the package depends on no sister library (#21).
585
+ - **A pilot on 2026** ([`benchmarks/measures/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/benchmarks/measures)):
586
+ on 9 dated landslides and Limen's archive of DPC frames, the «Merging»
587
+ caught 7 of 9 with 9.4 alerts per landslide caught; the radar alone 8 of 9
588
+ with 12.25. Nine landslides: a first look, not a validation.
589
+ - **The measure from 2018 to 2025** ([`benchmarks/measures/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/benchmarks/measures)):
590
+ on the radar history and 4,200 dated landslides, the rain is above T5 at
591
+ the gauge for 95.6 % of the same landslides and on the radar for 66.0 %.
592
+ The threshold still separates on radar rain (AUC 0.85 and 0.73), and a
593
+ threshold fitted on radar rain does not hold: none goes in.
594
+ - **Open, and measured in Limen, not here:** the numbers of
595
+ [limen#243](https://github.com/agent-engineering-studio/limen/issues/243)
596
+ recomputed with `measure` (#7); `strongest_event` against the
597
+ last event on the twelve backtest windows of Limen, before it is switched
598
+ on there.
599
+
434
600
  ## Good to know
435
601
 
436
602
  - **A threshold is not a forecast.** Rain above T5 means "conditions like
@@ -446,12 +612,24 @@ uv run python -m benchmarks.run
446
612
  thresholds to events from `reconstruct_events` mixes the two: fine for
447
613
  monitoring, worth knowing for a study.
448
614
  - **Units are fixed:** hours, millimetres, millimetres per hour.
615
+ - **No sister library inside.** The package imports neither dpc-radar nor
616
+ ispra-idrogeo, and a test keeps it so: [Limen](https://github.com/agent-engineering-studio/limen)
617
+ pins all three, and a library that imported another would tie their
618
+ releases together. The join lives in Limen, in notebook 04 and in `app/`.
449
619
 
450
620
  ## Where it's used
451
621
 
452
- Extracted from [Limen](https://github.com/agent-engineering-studio/limen),
453
- which uses it for the rainfall component of its landslide score. Using it
454
- somewhere else? [Open an issue](https://github.com/agent-engineering-studio/rainfall-thresholds/issues)
622
+ - **[Limen](https://github.com/agent-engineering-studio/limen)**, an open
623
+ early-warning system for landslides, floods and wildfires in Italy, from
624
+ which the library was extracted. It pins `rainfall-thresholds~=0.3.0` for
625
+ the rainfall trigger of its landslide score; the choice of the strongest
626
+ event is in its `landslide.yaml`, off until its backtest measures it.
627
+ - **The Open Data series** of Agent Engineering Studio, with its sister
628
+ libraries [dpc-radar](https://agentengineering.it/dpc-radar/) and
629
+ [ispra-idrogeo](https://agentengineering.it/ispra-idrogeo/).
630
+ - **The calibration bench** in `app/`, for public bodies.
631
+
632
+ Using it somewhere else? [Open an issue](https://github.com/agent-engineering-studio/rainfall-thresholds/issues)
455
633
  and tell us: we'd love to list it here.
456
634
 
457
635
  ## References
@@ -19,6 +19,7 @@ mark the hours it could not measure as `None`.
19
19
 
20
20
  [![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)
21
21
  [![PyPI](https://img.shields.io/pypi/v/rainfall-thresholds)](https://pypi.org/project/rainfall-thresholds/)
22
+ [![docs](https://img.shields.io/badge/docs-agentengineering.it-blue)](https://agentengineering.it/rainfall-thresholds/)
22
23
  [![Python](https://img.shields.io/pypi/pyversions/rainfall-thresholds)](https://pypi.org/project/rainfall-thresholds/)
23
24
  [![Dependencies: none](https://img.shields.io/badge/dependencies-none-brightgreen)](https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/pyproject.toml)
24
25
  [![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)
@@ -33,6 +34,13 @@ catalogue). The blue line is the threshold this library fits: only 5 % of
33
34
  those storms fall below it. The red star is the storm from the
34
35
  [quick start](#quick-start).</sub>
35
36
 
37
+ **Read the story:** [Basta questa pioggia per far franare?](https://agentengineering.it/blog/soglie-pioggia-frane-rainfall-thresholds/)
38
+ ([English](https://agentengineering.it/en/blog/soglie-pioggia-frane-rainfall-thresholds/)),
39
+ the last episode of the Open Data series, after
40
+ [dpc-radar](https://agentengineering.it/blog/pioggia-radar-protezione-civile-dpc-radar/)
41
+ and [ispra-idrogeo](https://agentengineering.it/blog/frane-pericolo-idrogeologico-ispra-idrogeo/).
42
+ **Try it** in the browser: [the intensity-duration plane](https://agentengineering.it/rainfall-thresholds/explainer/).
43
+
36
44
  ---
37
45
 
38
46
  ## Contents
@@ -45,10 +53,15 @@ those storms fall below it. The red star is the storm from the
45
53
  - [1. From hourly rain to rainfall events](#1-from-hourly-rain-to-rainfall-events)
46
54
  - [2. Comparing an event with a threshold](#2-comparing-an-event-with-a-threshold)
47
55
  - [3. Fitting your own threshold](#3-fitting-your-own-threshold)
56
+ - [4. Measuring what it costs](#4-measuring-what-it-costs)
48
57
  - [Thresholds for Italy](#thresholds-for-italy)
49
58
  - [Recipe: check a rain gauge](#recipe-check-a-rain-gauge)
50
59
  - [API at a glance](#api-at-a-glance)
51
60
  - [Benchmark](#benchmark)
61
+ - [Notebooks and Docker](#notebooks-and-docker)
62
+ - [A calibration bench for public bodies](#a-calibration-bench-for-public-bodies)
63
+ - [For assistants and agents](#for-assistants-and-agents)
64
+ - [Roadmap: what is measured, what is open](#roadmap-what-is-measured-what-is-open)
52
65
  - [Good to know](#good-to-know)
53
66
  - [References](#references) · [Citing](#citing) · [Contributing](#contributing)
54
67
 
@@ -293,6 +306,50 @@ fitted to a kernel density of the residuals; this package takes it straight
293
306
  from the residuals. The two agree when the residuals are close to normal,
294
307
  and the empirical one makes no assumption about their shape.
295
308
 
309
+ ### 4. Measuring what it costs
310
+
311
+ T5 catches 95 % of past landslides by construction. What it does not say is
312
+ how often it is exceeded when nothing happens. The `measure` functions answer
313
+ both on the same scale, for any score that grows with danger (an exceedance,
314
+ a 24-hour total, a probability):
315
+
316
+ ```python
317
+ from rainfall_thresholds import auc, skill, skill_at_budget
318
+
319
+ # For each landslide, the highest score in the hours before it.
320
+ landslides = [0.62, 0.31, 0.05, -0.08, 0.44]
321
+ # For each unit you could alert on (cell-hours, municipality-days...).
322
+ ordinary = [-0.9, -0.4, -0.2, 0.1, -0.6, -0.3, 0.2, -1.1, -0.5, -0.7]
323
+
324
+ s = skill(landslides, ordinary, cutoff=0.0) # above the threshold = alert
325
+ print(f"caught {s.caught} of {s.landslides}, {s.alert_share:.0%} of units on alert")
326
+ print(f"discrimination {s.discrimination:.1f}, {s.alerts_per_caught:.1f} alerts per landslide")
327
+
328
+ fair = skill_at_budget(landslides, ordinary, budget=0.10) # 10 % of units on alert
329
+ print(f"at a 10 % budget: caught {fair.caught} of {fair.landslides}")
330
+ print(f"AUC {auc(landslides, ordinary):.2f}")
331
+ ```
332
+
333
+ ```
334
+ caught 4 of 5, 20% of units on alert
335
+ discrimination 4.0, 0.5 alerts per landslide
336
+ at a 10 % budget: caught 3 of 5
337
+ AUC 0.92
338
+ ```
339
+
340
+ To compare two scores, compare them **at the same budget**: counting at a
341
+ fixed level rewards the score that alerts more. `None` is a score that was
342
+ not measured: it is left out and counted in `unmeasured`, never read as
343
+ zero. The definitions are those of Limen's backtests, and on the same inputs
344
+ the results are identical.
345
+
346
+ What this gives on real data was measured in Limen
347
+ ([limen#243](https://github.com/agent-engineering-studio/limen/issues/243)),
348
+ with the national curve on model rain (ERA5): 40.7 % of the e-ITALICA
349
+ landslides above the threshold against 3.0 % of ordinary moments, and 0 of
350
+ 286 landslides caught in the regions held out. A threshold fitted on rain
351
+ gauges and applied to other rain is not the same threshold.
352
+
296
353
  ## Thresholds for Italy
297
354
 
298
355
  `ITALICA_T5` holds four T5 thresholds fitted with `fit_threshold(percentile=5)`
@@ -378,7 +435,7 @@ rainfall part of a simple monitoring loop: a number to watch, not an alert.
378
435
 
379
436
  | Name | Kind | What it is |
380
437
  |---|---|---|
381
- | `PowerLawThreshold(alpha, beta)` | frozen dataclass | `I = α·D^(-β)`, with `.intensity(D)`, `.cumulated(D)`, `.exceedance(I, D)` |
438
+ | `PowerLawThreshold(alpha, beta)` | frozen dataclass | `I = α·D^(-β)`, with `.intensity(D)`, `.cumulated(D)`, `.exceedance(I, D)`, `.scaled(factor)` |
382
439
  | `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 |
383
440
  | `strongest_event(events, threshold)` | function | the event furthest above the threshold, or `None` |
384
441
  | `latest_event(events)` | function | the event that ended last, or `None` |
@@ -386,9 +443,28 @@ rainfall part of a simple monitoring loop: a number to watch, not an alert.
386
443
  | `fit_threshold(events, *, percentile=5.0)` | function | `(D, I)` pairs → `ThresholdFit` |
387
444
  | `ThresholdFit` | frozen dataclass | `threshold`, `central`, `percentile`, `n_events` |
388
445
  | `percentile_of(values, percentile)` | function | linear-interpolation percentile, same as NumPy's default |
446
+ | `skill(landslides, ordinary, cutoff)` | function | landslides caught and units on alert at a cutoff → `Skill` |
447
+ | `skill_at_budget(landslides, ordinary, budget, *, floor=None)` | function | the same at the cutoff that puts `budget` of the units on alert |
448
+ | `cutoff_at_budget(ordinary, budget, *, floor=None)` | function | that cutoff |
449
+ | `Skill` | frozen dataclass | `caught`, `landslides`, `alerts`, `ordinary`, `unmeasured`; `.hit_rate`, `.alert_share`, `.discrimination`, `.alerts_per_caught` |
450
+ | `auc(landslides, ordinary)` | function | Mann-Whitney AUC, ties count half |
451
+ | `facts.threshold_facts`, `assess_facts`, `fit_facts` | functions | the same answers as JSON-ready dicts, with units and the alert rule |
452
+ | `check.check_text(text, facts, *, question="")` | function | numbers of a text that are invented, rounded or in the wrong unit → `list[Misquote]` |
453
+ | `mcp_server.create_server()`, `rainfall-thresholds-mcp` | MCP (extra `mcp`) | tools `threshold`, `assess`, `fit`, `check` |
389
454
  | `ITALICA_T5` | read-only mapping | `"italy"`, `"northern"`, `"central"`, `"southern"` → `PowerLawThreshold` |
390
455
  | `MACROREGIONS` | read-only mapping | macroregion → set of region names (e-ITALICA spelling) |
391
- | `macroregion_of(region)` | function | region name → macroregion, or `None` |
456
+ | `macroregion_of(region)` | function | region name or ISTAT region code (`8`, `"08"`) → macroregion, or `None` |
457
+ | `ISTAT_REGIONS` | read-only mapping | ISTAT region code → region name |
458
+ | `threshold_for(macroregion, thresholds=ITALICA_T5, *, default="italy")` | function | the threshold of a macroregion, or the default one |
459
+ | `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` |
460
+ | `EventAssessment` | frozen dataclass | `event`, `threshold`, `borders_unmeasured`; `.threshold_mm_h`, `.threshold_mm`, `.ratio`, `.excess_decades`, `.at_least` |
461
+ | `cumulate(hours, end, *, windows_hours)` | function | the totals of the last N hours → `{N: WindowTotal}`; no total when an hour is not measured |
462
+ | `caine_excess(event, threshold, *, radar_gauge_factor=1.0)` | function | decades above the line, zero on or below it |
463
+ | `api_kohler_linsley(daily_precip_mm, *, decay_k, initial=0.0)` | function | the Antecedent Precipitation Index, mm |
464
+ | `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 |
465
+ | `load_regional_catalogue()` | function | published regional thresholds with their sources → `RegionalCatalogue` of `RegionalThreshold` and `Source` |
466
+ | `RainSource` | `typing.Protocol` | `hourly(points, start, end) -> dict[datetime, list[float or None]]`: what can feed the package |
467
+ | `point_series(rain, index)` | function | the series of one point out of `RainSource.hourly` |
392
468
 
393
469
  Everything is fully typed (`py.typed`) and checked with `mypy --strict`.
394
470
 
@@ -407,6 +483,94 @@ construction. The details, and what is not there yet, are in
407
483
  uv run python -m benchmarks.run
408
484
  ```
409
485
 
486
+ ## Notebooks and Docker
487
+
488
+ Four [example notebooks](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/notebooks):
489
+ the Italian thresholds over the e-ITALICA landslides, the storm of Melito on
490
+ the DPC radar, and fitting your own threshold, with no network; and the join
491
+ with the sister libraries, landslides dated by
492
+ [ispra-idrogeo](https://agentengineering.it/ispra-idrogeo/) against radar rain
493
+ from [dpc-radar](https://agentengineering.it/dpc-radar/). Open them with uv, or
494
+ with Docker alone:
495
+
496
+ ```bash
497
+ uv run --group examples jupyter lab notebooks/
498
+ docker compose up # http://localhost:8888
499
+ make docker-bench # the benchmark, in a container
500
+ ```
501
+
502
+ The compose file gives no fixed name to containers or images: Compose names
503
+ them after the project, so two copies run side by side.
504
+
505
+ ## A calibration bench for public bodies
506
+
507
+ [`app/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/app)
508
+ is a page in Italian, with Bootstrap Italia, for a public body: it opens on
509
+ the e-ITALICA landslides of its region, fits a threshold on the ones that
510
+ matter, compares it with the national one, measures its cost in false alarms
511
+ on the body's own rain gauge, and exports it. It is not a warning system and
512
+ reads no live rain. `docker compose up taratura`, then http://localhost:3001.
513
+ [Riuso nella PA](https://agentengineering.it/rainfall-thresholds/riuso/)
514
+ says, in Italian, what it does and what stays with the body.
515
+
516
+ To explain what a threshold is, the docs site has
517
+ [Try it](https://agentengineering.it/rainfall-thresholds/explainer/): an
518
+ interactive intensity-duration plane that runs in the browser.
519
+
520
+ ## For assistants and agents
521
+
522
+ A language model may word the numbers; it should never compute them. The
523
+ library gives them as data, and checks the words.
524
+
525
+ - **Facts.** `rainfall_thresholds.facts`: `threshold_facts`, `assess_facts`
526
+ and `fit_facts` return plain dicts, with the unit in every key (`_mm`,
527
+ `_mm_h`, `_h`, `_decades`), what the threshold was fitted on, and the rule
528
+ that a threshold exceeded is not an alert.
529
+ - **MCP server.** `pip install "rainfall-thresholds[mcp]"`, then
530
+ `rainfall-thresholds-mcp` on standard input and output. Four tools:
531
+ `threshold`, `assess`, `fit`, `check`. They compute only from what the call
532
+ gives them: no network, no live rain.
533
+ - **A check of the text.** `check_text(text, facts)` finds numbers invented,
534
+ rounded the wrong way, or in the wrong unit: 30.9 mm written as 30.9 mm/h,
535
+ the trap of every rainfall threshold. It knows that a number is a fact of
536
+ its unit, not that it is said of the right thing.
537
+ - **A faithfulness set.** `benchmarks/faithful.py`: questions, facts, and
538
+ answers written by hand, one faithful and one with known faults; in CI the
539
+ check must find exactly those faults (8 of 8 today). Answers of a model are
540
+ not in it yet.
541
+ - **For coding agents.** [`llms.txt`](https://agentengineering.it/rainfall-thresholds/llms.txt),
542
+ [`llms-full.txt`](https://agentengineering.it/rainfall-thresholds/llms-full.txt)
543
+ and an [agent skill](https://agentengineering.it/rainfall-thresholds/skills/rainfall-thresholds/SKILL.md)
544
+ with the traps a model falls into when it writes this code from memory.
545
+
546
+ The base package still has no dependencies: the MCP SDK comes only with the
547
+ `mcp` extra.
548
+
549
+ ## Roadmap: what is measured, what is open
550
+
551
+ The plan is in [#4](https://github.com/agent-engineering-studio/rainfall-thresholds/issues/4),
552
+ and the [roadmap page](https://agentengineering.it/rainfall-thresholds/roadmap/)
553
+ says what each phase measured.
554
+
555
+ - **Done:** the benchmark (#5), the strongest event and hours not measured
556
+ (#6), the functions to measure a threshold (#7), the AI layer (#9), the
557
+ calibration bench, Try it and `publiccode.yml` (#10), notebooks and Docker
558
+ (#14), the rule that the package depends on no sister library (#21).
559
+ - **A pilot on 2026** ([`benchmarks/measures/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/benchmarks/measures)):
560
+ on 9 dated landslides and Limen's archive of DPC frames, the «Merging»
561
+ caught 7 of 9 with 9.4 alerts per landslide caught; the radar alone 8 of 9
562
+ with 12.25. Nine landslides: a first look, not a validation.
563
+ - **The measure from 2018 to 2025** ([`benchmarks/measures/`](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/benchmarks/measures)):
564
+ on the radar history and 4,200 dated landslides, the rain is above T5 at
565
+ the gauge for 95.6 % of the same landslides and on the radar for 66.0 %.
566
+ The threshold still separates on radar rain (AUC 0.85 and 0.73), and a
567
+ threshold fitted on radar rain does not hold: none goes in.
568
+ - **Open, and measured in Limen, not here:** the numbers of
569
+ [limen#243](https://github.com/agent-engineering-studio/limen/issues/243)
570
+ recomputed with `measure` (#7); `strongest_event` against the
571
+ last event on the twelve backtest windows of Limen, before it is switched
572
+ on there.
573
+
410
574
  ## Good to know
411
575
 
412
576
  - **A threshold is not a forecast.** Rain above T5 means "conditions like
@@ -422,12 +586,24 @@ uv run python -m benchmarks.run
422
586
  thresholds to events from `reconstruct_events` mixes the two: fine for
423
587
  monitoring, worth knowing for a study.
424
588
  - **Units are fixed:** hours, millimetres, millimetres per hour.
589
+ - **No sister library inside.** The package imports neither dpc-radar nor
590
+ ispra-idrogeo, and a test keeps it so: [Limen](https://github.com/agent-engineering-studio/limen)
591
+ pins all three, and a library that imported another would tie their
592
+ releases together. The join lives in Limen, in notebook 04 and in `app/`.
425
593
 
426
594
  ## Where it's used
427
595
 
428
- Extracted from [Limen](https://github.com/agent-engineering-studio/limen),
429
- which uses it for the rainfall component of its landslide score. Using it
430
- somewhere else? [Open an issue](https://github.com/agent-engineering-studio/rainfall-thresholds/issues)
596
+ - **[Limen](https://github.com/agent-engineering-studio/limen)**, an open
597
+ early-warning system for landslides, floods and wildfires in Italy, from
598
+ which the library was extracted. It pins `rainfall-thresholds~=0.3.0` for
599
+ the rainfall trigger of its landslide score; the choice of the strongest
600
+ event is in its `landslide.yaml`, off until its backtest measures it.
601
+ - **The Open Data series** of Agent Engineering Studio, with its sister
602
+ libraries [dpc-radar](https://agentengineering.it/dpc-radar/) and
603
+ [ispra-idrogeo](https://agentengineering.it/ispra-idrogeo/).
604
+ - **The calibration bench** in `app/`, for public bodies.
605
+
606
+ Using it somewhere else? [Open an issue](https://github.com/agent-engineering-studio/rainfall-thresholds/issues)
431
607
  and tell us: we'd love to list it here.
432
608
 
433
609
  ## References
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rainfall-thresholds"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  description = "Rainfall intensity-duration thresholds for shallow landslides (Caine power law, frequentist fitting)"
5
5
  readme = "README.md"
6
6
  keywords = [
@@ -33,6 +33,12 @@ dependencies = []
33
33
  name = "Giuseppe Zileni"
34
34
  email = "giuseppe.zileni@gmail.com"
35
35
 
36
+ [project.optional-dependencies]
37
+ mcp = ["mcp>=2.3"]
38
+
39
+ [project.scripts]
40
+ rainfall-thresholds-mcp = "rainfall_thresholds.mcp_server:run"
41
+
36
42
  [project.urls]
37
43
  Homepage = "https://github.com/agent-engineering-studio/rainfall-thresholds"
38
44
  Issues = "https://github.com/agent-engineering-studio/rainfall-thresholds/issues"
@@ -44,11 +50,20 @@ build-backend = "uv_build"
44
50
 
45
51
  [dependency-groups]
46
52
  dev = [
53
+ "mcp>=2.3",
47
54
  "mypy>=1.13",
48
55
  "pytest>=8.3",
56
+ "pytest-asyncio>=0.24",
49
57
  "pytest-cov>=6.0",
50
58
  "ruff>=0.8",
51
59
  ]
60
+ examples = [
61
+ "jupyterlab>=4.2",
62
+ "nbconvert>=7.16",
63
+ "matplotlib>=3.9",
64
+ "dpc-radar~=0.3.0",
65
+ "ispra-idrogeo~=0.10.0",
66
+ ]
52
67
  docs = [
53
68
  "zensical>=0.1.0",
54
69
  "mkdocstrings-python>=1.18",
@@ -79,6 +94,7 @@ select = [
79
94
  "ARG",
80
95
  "B018",
81
96
  ]
97
+ "docs/make_blog_figures.py" = ["E501"]
82
98
 
83
99
  [tool.mypy]
84
100
  strict = true
@@ -94,6 +110,8 @@ warn_redundant_casts = true
94
110
  [tool.pytest.ini_options]
95
111
  testpaths = ["tests"]
96
112
  addopts = "--strict-markers"
113
+ asyncio_mode = "auto"
114
+ asyncio_default_fixture_loop_scope = "function"
97
115
 
98
116
  [tool.coverage.run]
99
117
  source = ["rainfall_thresholds"]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rainfall-thresholds"
3
- version = "0.2.0"
3
+ version = "0.4.0"
4
4
  description = "Rainfall intensity-duration thresholds for shallow landslides (Caine power law, frequentist fitting)"
5
5
  readme = "README.md"
6
6
  keywords = ["landslide", "rainfall threshold", "intensity-duration", "caine", "hydrology", "natural hazards", "italy", "italica"]
@@ -23,6 +23,13 @@ classifiers = [
23
23
  ]
24
24
  dependencies = []
25
25
 
26
+ [project.optional-dependencies]
27
+ # The MCP server (rainfall-thresholds-mcp). The package itself needs nothing.
28
+ mcp = ["mcp>=2.3"]
29
+
30
+ [project.scripts]
31
+ rainfall-thresholds-mcp = "rainfall_thresholds.mcp_server:run"
32
+
26
33
  [project.urls]
27
34
  Homepage = "https://github.com/agent-engineering-studio/rainfall-thresholds"
28
35
  Issues = "https://github.com/agent-engineering-studio/rainfall-thresholds/issues"
@@ -34,12 +41,24 @@ build-backend = "uv_build"
34
41
 
35
42
  [dependency-groups]
36
43
  dev = [
44
+ "mcp>=2.3",
37
45
  "mypy>=1.13",
38
46
  "pytest>=8.3",
47
+ "pytest-asyncio>=0.24",
39
48
  "pytest-cov>=6.0",
40
49
  "ruff>=0.8",
41
50
  ]
42
51
 
52
+ examples = [
53
+ "jupyterlab>=4.2",
54
+ "nbconvert>=7.16",
55
+ "matplotlib>=3.9",
56
+ # Only for notebooks/04: the sister libraries, joined in a notebook as Limen
57
+ # joins them. The package itself never imports them (tests/test_package.py).
58
+ "dpc-radar~=0.3.0",
59
+ "ispra-idrogeo~=0.10.0",
60
+ ]
61
+
43
62
  docs = [
44
63
  "zensical>=0.1.0",
45
64
  "mkdocstrings-python>=1.18",
@@ -54,6 +73,7 @@ select = ["E", "F", "W", "I", "N", "UP", "B", "C4", "SIM", "ARG", "PTH", "RUF"]
54
73
 
55
74
  [tool.ruff.lint.per-file-ignores]
56
75
  "tests/**" = ["ARG", "B018"]
76
+ "docs/make_blog_figures.py" = ["E501"] # labels in two languages
57
77
 
58
78
  [tool.mypy]
59
79
  strict = true
@@ -65,6 +85,8 @@ warn_redundant_casts = true
65
85
  [tool.pytest.ini_options]
66
86
  testpaths = ["tests"]
67
87
  addopts = "--strict-markers"
88
+ asyncio_mode = "auto"
89
+ asyncio_default_fixture_loop_scope = "function"
68
90
 
69
91
  [tool.coverage.run]
70
92
  source = ["rainfall_thresholds"]