rainfall-thresholds 0.2.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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: rainfall-thresholds
3
- Version: 0.2.0
3
+ Version: 0.3.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
@@ -69,10 +71,13 @@ those storms fall below it. The red star is the storm from the
69
71
  - [1. From hourly rain to rainfall events](#1-from-hourly-rain-to-rainfall-events)
70
72
  - [2. Comparing an event with a threshold](#2-comparing-an-event-with-a-threshold)
71
73
  - [3. Fitting your own threshold](#3-fitting-your-own-threshold)
74
+ - [4. Measuring what it costs](#4-measuring-what-it-costs)
72
75
  - [Thresholds for Italy](#thresholds-for-italy)
73
76
  - [Recipe: check a rain gauge](#recipe-check-a-rain-gauge)
74
77
  - [API at a glance](#api-at-a-glance)
75
78
  - [Benchmark](#benchmark)
79
+ - [Notebooks and Docker](#notebooks-and-docker)
80
+ - [For assistants and agents](#for-assistants-and-agents)
76
81
  - [Good to know](#good-to-know)
77
82
  - [References](#references) · [Citing](#citing) · [Contributing](#contributing)
78
83
 
@@ -317,6 +322,50 @@ fitted to a kernel density of the residuals; this package takes it straight
317
322
  from the residuals. The two agree when the residuals are close to normal,
318
323
  and the empirical one makes no assumption about their shape.
319
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
+
320
369
  ## Thresholds for Italy
321
370
 
322
371
  `ITALICA_T5` holds four T5 thresholds fitted with `fit_threshold(percentile=5)`
@@ -410,6 +459,14 @@ rainfall part of a simple monitoring loop: a number to watch, not an alert.
410
459
  | `fit_threshold(events, *, percentile=5.0)` | function | `(D, I)` pairs → `ThresholdFit` |
411
460
  | `ThresholdFit` | frozen dataclass | `threshold`, `central`, `percentile`, `n_events` |
412
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` |
413
470
  | `ITALICA_T5` | read-only mapping | `"italy"`, `"northern"`, `"central"`, `"southern"` → `PowerLawThreshold` |
414
471
  | `MACROREGIONS` | read-only mapping | macroregion → set of region names (e-ITALICA spelling) |
415
472
  | `macroregion_of(region)` | function | region name → macroregion, or `None` |
@@ -431,6 +488,51 @@ construction. The details, and what is not there yet, are in
431
488
  uv run python -m benchmarks.run
432
489
  ```
433
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
+
434
536
  ## Good to know
435
537
 
436
538
  - **A threshold is not a forecast.** Rain above T5 means "conditions like
@@ -45,10 +45,13 @@ those storms fall below it. The red star is the storm from the
45
45
  - [1. From hourly rain to rainfall events](#1-from-hourly-rain-to-rainfall-events)
46
46
  - [2. Comparing an event with a threshold](#2-comparing-an-event-with-a-threshold)
47
47
  - [3. Fitting your own threshold](#3-fitting-your-own-threshold)
48
+ - [4. Measuring what it costs](#4-measuring-what-it-costs)
48
49
  - [Thresholds for Italy](#thresholds-for-italy)
49
50
  - [Recipe: check a rain gauge](#recipe-check-a-rain-gauge)
50
51
  - [API at a glance](#api-at-a-glance)
51
52
  - [Benchmark](#benchmark)
53
+ - [Notebooks and Docker](#notebooks-and-docker)
54
+ - [For assistants and agents](#for-assistants-and-agents)
52
55
  - [Good to know](#good-to-know)
53
56
  - [References](#references) · [Citing](#citing) · [Contributing](#contributing)
54
57
 
@@ -293,6 +296,50 @@ fitted to a kernel density of the residuals; this package takes it straight
293
296
  from the residuals. The two agree when the residuals are close to normal,
294
297
  and the empirical one makes no assumption about their shape.
295
298
 
299
+ ### 4. Measuring what it costs
300
+
301
+ T5 catches 95 % of past landslides by construction. What it does not say is
302
+ how often it is exceeded when nothing happens. The `measure` functions answer
303
+ both on the same scale, for any score that grows with danger (an exceedance,
304
+ a 24-hour total, a probability):
305
+
306
+ ```python
307
+ from rainfall_thresholds import auc, skill, skill_at_budget
308
+
309
+ # For each landslide, the highest score in the hours before it.
310
+ landslides = [0.62, 0.31, 0.05, -0.08, 0.44]
311
+ # For each unit you could alert on (cell-hours, municipality-days...).
312
+ ordinary = [-0.9, -0.4, -0.2, 0.1, -0.6, -0.3, 0.2, -1.1, -0.5, -0.7]
313
+
314
+ s = skill(landslides, ordinary, cutoff=0.0) # above the threshold = alert
315
+ print(f"caught {s.caught} of {s.landslides}, {s.alert_share:.0%} of units on alert")
316
+ print(f"discrimination {s.discrimination:.1f}, {s.alerts_per_caught:.1f} alerts per landslide")
317
+
318
+ fair = skill_at_budget(landslides, ordinary, budget=0.10) # 10 % of units on alert
319
+ print(f"at a 10 % budget: caught {fair.caught} of {fair.landslides}")
320
+ print(f"AUC {auc(landslides, ordinary):.2f}")
321
+ ```
322
+
323
+ ```
324
+ caught 4 of 5, 20% of units on alert
325
+ discrimination 4.0, 0.5 alerts per landslide
326
+ at a 10 % budget: caught 3 of 5
327
+ AUC 0.92
328
+ ```
329
+
330
+ To compare two scores, compare them **at the same budget**: counting at a
331
+ fixed level rewards the score that alerts more. `None` is a score that was
332
+ not measured: it is left out and counted in `unmeasured`, never read as
333
+ zero. The definitions are those of Limen's backtests, and on the same inputs
334
+ the results are identical.
335
+
336
+ What this gives on real data was measured in Limen
337
+ ([limen#243](https://github.com/agent-engineering-studio/limen/issues/243)),
338
+ with the national curve on model rain (ERA5): 40.7 % of the e-ITALICA
339
+ landslides above the threshold against 3.0 % of ordinary moments, and 0 of
340
+ 286 landslides caught in the regions held out. A threshold fitted on rain
341
+ gauges and applied to other rain is not the same threshold.
342
+
296
343
  ## Thresholds for Italy
297
344
 
298
345
  `ITALICA_T5` holds four T5 thresholds fitted with `fit_threshold(percentile=5)`
@@ -386,6 +433,14 @@ rainfall part of a simple monitoring loop: a number to watch, not an alert.
386
433
  | `fit_threshold(events, *, percentile=5.0)` | function | `(D, I)` pairs → `ThresholdFit` |
387
434
  | `ThresholdFit` | frozen dataclass | `threshold`, `central`, `percentile`, `n_events` |
388
435
  | `percentile_of(values, percentile)` | function | linear-interpolation percentile, same as NumPy's default |
436
+ | `skill(landslides, ordinary, cutoff)` | function | landslides caught and units on alert at a cutoff → `Skill` |
437
+ | `skill_at_budget(landslides, ordinary, budget, *, floor=None)` | function | the same at the cutoff that puts `budget` of the units on alert |
438
+ | `cutoff_at_budget(ordinary, budget, *, floor=None)` | function | that cutoff |
439
+ | `Skill` | frozen dataclass | `caught`, `landslides`, `alerts`, `ordinary`, `unmeasured`; `.hit_rate`, `.alert_share`, `.discrimination`, `.alerts_per_caught` |
440
+ | `auc(landslides, ordinary)` | function | Mann-Whitney AUC, ties count half |
441
+ | `facts.threshold_facts`, `assess_facts`, `fit_facts` | functions | the same answers as JSON-ready dicts, with units and the alert rule |
442
+ | `check.check_text(text, facts, *, question="")` | function | numbers of a text that are invented, rounded or in the wrong unit → `list[Misquote]` |
443
+ | `mcp_server.create_server()`, `rainfall-thresholds-mcp` | MCP (extra `mcp`) | tools `threshold`, `assess`, `fit`, `check` |
389
444
  | `ITALICA_T5` | read-only mapping | `"italy"`, `"northern"`, `"central"`, `"southern"` → `PowerLawThreshold` |
390
445
  | `MACROREGIONS` | read-only mapping | macroregion → set of region names (e-ITALICA spelling) |
391
446
  | `macroregion_of(region)` | function | region name → macroregion, or `None` |
@@ -407,6 +462,51 @@ construction. The details, and what is not there yet, are in
407
462
  uv run python -m benchmarks.run
408
463
  ```
409
464
 
465
+ ## Notebooks and Docker
466
+
467
+ Three [example notebooks](https://github.com/agent-engineering-studio/rainfall-thresholds/tree/main/notebooks)
468
+ need no network: the Italian thresholds over the e-ITALICA landslides, the
469
+ storm of Melito on the DPC radar, and fitting your own threshold. Open them
470
+ with uv, or with Docker alone:
471
+
472
+ ```bash
473
+ uv run --group examples jupyter lab notebooks/
474
+ docker compose up # http://localhost:8888
475
+ make docker-bench # the benchmark, in a container
476
+ ```
477
+
478
+ The compose file gives no fixed name to containers or images: Compose names
479
+ them after the project, so two copies run side by side.
480
+
481
+ ## For assistants and agents
482
+
483
+ A language model may word the numbers; it should never compute them. The
484
+ library gives them as data, and checks the words.
485
+
486
+ - **Facts.** `rainfall_thresholds.facts`: `threshold_facts`, `assess_facts`
487
+ and `fit_facts` return plain dicts, with the unit in every key (`_mm`,
488
+ `_mm_h`, `_h`, `_decades`), what the threshold was fitted on, and the rule
489
+ that a threshold exceeded is not an alert.
490
+ - **MCP server.** `pip install "rainfall-thresholds[mcp]"`, then
491
+ `rainfall-thresholds-mcp` on standard input and output. Four tools:
492
+ `threshold`, `assess`, `fit`, `check`. They compute only from what the call
493
+ gives them: no network, no live rain.
494
+ - **A check of the text.** `check_text(text, facts)` finds numbers invented,
495
+ rounded the wrong way, or in the wrong unit: 30.9 mm written as 30.9 mm/h,
496
+ the trap of every rainfall threshold. It knows that a number is a fact of
497
+ its unit, not that it is said of the right thing.
498
+ - **A faithfulness set.** `benchmarks/faithful.py`: questions, facts, and
499
+ answers written by hand, one faithful and one with known faults; in CI the
500
+ check must find exactly those faults (8 of 8 today). Answers of a model are
501
+ not in it yet.
502
+ - **For coding agents.** [`llms.txt`](https://agentengineering.it/rainfall-thresholds/llms.txt),
503
+ [`llms-full.txt`](https://agentengineering.it/rainfall-thresholds/llms-full.txt)
504
+ and an [agent skill](https://agentengineering.it/rainfall-thresholds/skills/rainfall-thresholds/SKILL.md)
505
+ with the traps a model falls into when it writes this code from memory.
506
+
507
+ The base package still has no dependencies: the MCP SDK comes only with the
508
+ `mcp` extra.
509
+
410
510
  ## Good to know
411
511
 
412
512
  - **A threshold is not a forecast.** Rain above T5 means "conditions like
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rainfall-thresholds"
3
- version = "0.2.0"
3
+ version = "0.3.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,18 @@ 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
+ ]
52
65
  docs = [
53
66
  "zensical>=0.1.0",
54
67
  "mkdocstrings-python>=1.18",
@@ -94,6 +107,8 @@ warn_redundant_casts = true
94
107
  [tool.pytest.ini_options]
95
108
  testpaths = ["tests"]
96
109
  addopts = "--strict-markers"
110
+ asyncio_mode = "auto"
111
+ asyncio_default_fixture_loop_scope = "function"
97
112
 
98
113
  [tool.coverage.run]
99
114
  source = ["rainfall_thresholds"]
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "rainfall-thresholds"
3
- version = "0.2.0"
3
+ version = "0.3.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,20 @@ 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
+ ]
57
+
43
58
  docs = [
44
59
  "zensical>=0.1.0",
45
60
  "mkdocstrings-python>=1.18",
@@ -65,6 +80,8 @@ warn_redundant_casts = true
65
80
  [tool.pytest.ini_options]
66
81
  testpaths = ["tests"]
67
82
  addopts = "--strict-markers"
83
+ asyncio_mode = "auto"
84
+ asyncio_default_fixture_loop_scope = "function"
68
85
 
69
86
  [tool.coverage.run]
70
87
  source = ["rainfall_thresholds"]
@@ -10,6 +10,7 @@ from rainfall_thresholds.events import (
10
10
  )
11
11
  from rainfall_thresholds.fit import ThresholdFit, fit_threshold, percentile_of
12
12
  from rainfall_thresholds.italy import ITALICA_T5, MACROREGIONS, macroregion_of
13
+ from rainfall_thresholds.measure import Skill, auc, cutoff_at_budget, skill, skill_at_budget
13
14
  from rainfall_thresholds.threshold import PowerLawThreshold
14
15
 
15
16
  __version__ = version("rainfall-thresholds")
@@ -19,12 +20,17 @@ __all__ = [
19
20
  "MACROREGIONS",
20
21
  "PowerLawThreshold",
21
22
  "RainfallEvent",
23
+ "Skill",
22
24
  "ThresholdFit",
23
25
  "__version__",
26
+ "auc",
27
+ "cutoff_at_budget",
24
28
  "fit_threshold",
25
29
  "latest_event",
26
30
  "macroregion_of",
27
31
  "percentile_of",
28
32
  "reconstruct_events",
33
+ "skill",
34
+ "skill_at_budget",
29
35
  "strongest_event",
30
36
  ]
@@ -0,0 +1,165 @@
1
+ """Check that a text quotes the facts: no number invented, none in the wrong unit.
2
+
3
+ A model turns the facts of :mod:`rainfall_thresholds.facts` into words. The
4
+ faults that matter here are three:
5
+
6
+ * **invented**: a number that is in no fact;
7
+ * **unit**: a number that is a fact, but of another unit. The classic one:
8
+ the 30.9 mm the threshold asks for over 35 hours, written as 30.9 mm/h.
9
+ A rainfall threshold is about both, and they differ by the duration;
10
+ * **rounded**: a number close to a fact, but not the fact rounded to the
11
+ decimals written (``118.1`` for 118.04).
12
+
13
+ A number may be written with fewer decimals than the fact (``31`` for
14
+ 30.9) or, from 100, as a round number (``1,600`` for 1,603). Dates, years and
15
+ clock times (``10/10``, ``10 October 2026``, ``2026-10-10``, ``03:00``) are
16
+ not checked, nor numbers that are in the question. The check knows that
17
+ a number is a fact of the right unit, not that it is said of the right
18
+ thing: "Melito got 30.9 mm" passes when 30.9 mm is the threshold.
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import math
24
+ import re
25
+ from collections.abc import Iterator
26
+ from dataclasses import dataclass
27
+ from typing import Any, Literal
28
+
29
+ Fault = Literal["invented", "unit", "rounded"]
30
+
31
+ #: Units as they are written in a text, and as they are named in fact keys.
32
+ _UNITS = {
33
+ "mm/h": "mm/h",
34
+ "mm h-1": "mm/h",
35
+ "millimetres per hour": "mm/h",
36
+ "mm": "mm",
37
+ "millimetres": "mm",
38
+ "millimeters": "mm",
39
+ "h": "h",
40
+ "hours": "h",
41
+ "hour": "h",
42
+ "ore": "h",
43
+ "decades": "decades",
44
+ "decade": "decades",
45
+ "decadi": "decades",
46
+ "%": "%",
47
+ }
48
+ _UNIT_RE = "|".join(re.escape(u) for u in sorted(_UNITS, key=len, reverse=True))
49
+ _NUMBER = re.compile(
50
+ rf"(?<![\w.])(?P<num>[-+\u2212]?\d+(?:[.,]\d+)*)(?:\s*(?P<unit>{_UNIT_RE})(?![\w/]))?",
51
+ re.IGNORECASE,
52
+ )
53
+ _MONTHS = (
54
+ "january|february|march|april|may|june|july|august|september|october|november|december|"
55
+ "gennaio|febbraio|marzo|aprile|maggio|giugno|luglio|agosto|settembre|ottobre|novembre|dicembre"
56
+ )
57
+ _DATES = re.compile(
58
+ r"\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2})?(?:[+-]\d{2}:\d{2}|Z)?)?"
59
+ r"|\b\d{1,2}:\d{2}\b|\b\d{1,2}/\d{1,2}(?:/\d{2,4})?\b"
60
+ rf"|\b\d{{1,2}}\s+(?:{_MONTHS})(?:\s+\d{{4}})?\b|\b(?:19|20)\d{{2}}\b",
61
+ re.IGNORECASE,
62
+ )
63
+
64
+
65
+ @dataclass(frozen=True, slots=True)
66
+ class Misquote:
67
+ """A number of the text that is not a fact as written."""
68
+
69
+ text: str
70
+ unit: str | None
71
+ fault: Fault
72
+ #: The nearest fact, as ``path = value unit``, when there is one.
73
+ nearest: str | None = None
74
+
75
+
76
+ def _unit_of(key: str) -> str | None:
77
+ if key.endswith("_mm_h"):
78
+ return "mm/h"
79
+ if key.endswith("_mm"):
80
+ return "mm"
81
+ if key.endswith(("_h", "_hours")):
82
+ return "h"
83
+ if key.endswith("_decades"):
84
+ return "decades"
85
+ if key.endswith(("_pct", "_percent")):
86
+ return "%"
87
+ return None
88
+
89
+
90
+ def facts_of(facts: Any, path: str = "") -> Iterator[tuple[str, float, str | None]]:
91
+ """Every number in ``facts``, with its path and the unit its key names."""
92
+ if isinstance(facts, dict):
93
+ for key, value in facts.items():
94
+ yield from facts_of(value, f"{path}.{key}" if path else str(key))
95
+ elif isinstance(facts, list | tuple):
96
+ for i, value in enumerate(facts):
97
+ yield from facts_of(value, f"{path}.{i}")
98
+ elif isinstance(facts, bool) or facts is None:
99
+ return
100
+ elif isinstance(facts, int | float) and math.isfinite(facts):
101
+ yield path, float(facts), _unit_of(path.rsplit(".", 1)[-1])
102
+
103
+
104
+ def parse_number(token: str) -> tuple[float, int]:
105
+ """A number as written -> its value and its decimals. ``1,603`` is 1603; ``2,5`` is 2.5."""
106
+ t = token.replace("\u2212", "-") # the minus sign
107
+ if re.fullmatch(r"[-+]?\d{1,3}(?:,\d{3})+(?:\.\d+)?", t):
108
+ t = t.replace(",", "")
109
+ elif re.fullmatch(r"[-+]?\d{1,3}(?:(?:\.\d{3}){2,}(?:,\d+)?|\.\d{3},\d+)", t):
110
+ # A dot for thousands only when it cannot be a decimal point:
111
+ # 1.234.567 or 1.603,5. "0.506" and "1.603" are decimals.
112
+ t = t.replace(".", "").replace(",", ".")
113
+ else:
114
+ t = t.replace(",", ".")
115
+ decimals = len(t.split(".", 1)[1]) if "." in t else 0
116
+ return float(t), decimals
117
+
118
+
119
+ def _agrees(written: float, decimals: int, fact: float) -> bool:
120
+ if round(fact, decimals) == written or round(abs(fact), decimals) == abs(written):
121
+ return True
122
+ if decimals == 0 and abs(written) >= 100:
123
+ # A round number: 1,600 for 1,603. Only from 100: below it, "20" for
124
+ # 15.3 would pass.
125
+ zeros = len(str(int(abs(written)))) - len(str(int(abs(written))).rstrip("0"))
126
+ return zeros > 0 and round(abs(fact), -zeros) == abs(written)
127
+ return False
128
+
129
+
130
+ def _close(written: float, decimals: int, fact: float) -> bool:
131
+ return abs(abs(fact) - abs(written)) <= 10.0 ** (-decimals) + 1e-9
132
+
133
+
134
+ def check_text(text: str, facts: Any, *, question: str = "") -> list[Misquote]:
135
+ """The numbers of ``text`` that are not facts of their unit. Empty: faithful."""
136
+ known = list(facts_of(facts))
137
+ asked = {parse_number(m.group("num"))[0] for m in _NUMBER.finditer(_DATES.sub(" ", question))}
138
+ found: list[Misquote] = []
139
+ for m in _NUMBER.finditer(_DATES.sub(" ", text)):
140
+ token = m.group("num")
141
+ written, decimals = parse_number(token)
142
+ unit = _UNITS[m.group("unit").lower()] if m.group("unit") else None
143
+ if written in asked:
144
+ continue
145
+ same_unit = [
146
+ k for k in known if unit is None or k[2] == unit or (unit == "%" and k[2] is None)
147
+ ]
148
+ if any(_agrees(written, decimals, v) for _, v, _ in same_unit):
149
+ continue
150
+ other = [k for k in known if k[2] not in (None, unit) and _agrees(written, decimals, k[1])]
151
+ if other:
152
+ path, value, u = other[0]
153
+ found.append(
154
+ Misquote(m.group(0), unit, "unit", f"{path} = {value:g} {u or ''}".strip())
155
+ )
156
+ continue
157
+ near = [k for k in known if k[2] == unit and _close(written, decimals, k[1])]
158
+ if near:
159
+ path, value, u = near[0]
160
+ found.append(
161
+ Misquote(m.group(0), unit, "rounded", f"{path} = {value:g} {u or ''}".strip())
162
+ )
163
+ continue
164
+ found.append(Misquote(m.group(0), unit, "invented"))
165
+ return found
@@ -0,0 +1,150 @@
1
+ """The same answers as data: what a tool, a report or a model can quote.
2
+
3
+ Every function returns a plain ``dict`` (JSON-ready) with the numbers, their
4
+ units in the key names (``_mm``, ``_mm_h``, ``_h``, ``_decades``), where the
5
+ threshold comes from, and the rule that goes with every answer:
6
+
7
+ A threshold exceeded is not an alert.
8
+
9
+ A language model may word these facts; it never computes them. The numbers
10
+ come from here, and :func:`rainfall_thresholds.check.check_text` checks a text
11
+ against them.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Iterable
17
+ from datetime import datetime
18
+ from typing import Any
19
+
20
+ from rainfall_thresholds.events import reconstruct_events, strongest_event
21
+ from rainfall_thresholds.fit import fit_threshold
22
+ from rainfall_thresholds.italy import ITALICA_T5, macroregion_of
23
+ from rainfall_thresholds.threshold import PowerLawThreshold
24
+
25
+ #: Where the official alert is. Every answer carries it.
26
+ ALERT_URL = "https://rischi.protezionecivile.gov.it/it/meteo-idro/allertamento/"
27
+
28
+ RULE = (
29
+ "A threshold exceeded is not an alert: it says the rain is like the rain that "
30
+ "triggered landslides before. The official alert in Italy is the criticality "
31
+ f"bulletin of the Dipartimento della Protezione Civile ({ALERT_URL})."
32
+ )
33
+
34
+ #: How many e-ITALICA landslides each Italian threshold was fitted on.
35
+ ITALICA_EVENTS = {"italy": 5974, "northern": 2659, "central": 1890, "southern": 1425}
36
+
37
+ _GAUGE = "e-ITALICA v4 rain gauges (Brunetti et al. 2024, doi:10.5281/zenodo.14204473)"
38
+
39
+
40
+ def resolve(region: str) -> str:
41
+ """``"italy"``, a macroregion, or an Italian region name -> the key of ITALICA_T5."""
42
+ if region in ITALICA_T5:
43
+ return region
44
+ found = macroregion_of(region)
45
+ if found is None:
46
+ raise ValueError(
47
+ f"unknown region {region!r}: use an Italian region as e-ITALICA spells it "
48
+ f"(for example 'Calabria', 'Emilia-Romagna'), or one of {sorted(ITALICA_T5)}"
49
+ )
50
+ return found
51
+
52
+
53
+ def _threshold(key: str, t: PowerLawThreshold) -> dict[str, Any]:
54
+ return {
55
+ "name": f"ITALICA_T5[{key!r}]",
56
+ "macroregion": key,
57
+ "alpha": t.alpha,
58
+ "beta": t.beta,
59
+ "percentile": 5,
60
+ "fitted_on": _GAUGE,
61
+ "landslides": ITALICA_EVENTS[key],
62
+ }
63
+
64
+
65
+ def threshold_facts(region: str, duration_h: float) -> dict[str, Any]:
66
+ """The rain the Italian T5 threshold asks for over ``duration_h`` hours."""
67
+ key = resolve(region)
68
+ t = ITALICA_T5[key]
69
+ return {
70
+ "region": region,
71
+ "threshold": _threshold(key, t),
72
+ "duration_h": duration_h,
73
+ "intensity_mm_h": round(t.intensity(duration_h), 2),
74
+ "cumulated_mm": round(t.cumulated(duration_h), 1),
75
+ "rule": RULE,
76
+ }
77
+
78
+
79
+ def _event(e: Any, t: PowerLawThreshold) -> dict[str, Any]:
80
+ return {
81
+ "start": e.start.isoformat(),
82
+ "end": e.end.isoformat(),
83
+ "duration_h": e.duration_hours,
84
+ "total_mm": round(e.total_mm, 1),
85
+ "intensity_mm_h": round(e.intensity_mm_h, 2),
86
+ "needed_mm": round(t.cumulated(e.duration_hours), 1),
87
+ "exceedance_decades": round(t.exceedance(e.intensity_mm_h, e.duration_hours), 2),
88
+ "unmeasured_h": e.unmeasured_hours,
89
+ }
90
+
91
+
92
+ def assess_facts(
93
+ series: Iterable[tuple[datetime, float | None]],
94
+ region: str,
95
+ *,
96
+ source: str | None = None,
97
+ no_rain_break_hours: int = 6,
98
+ min_event_mm: float = 2.0,
99
+ ) -> dict[str, Any]:
100
+ """The rainfall events of an hourly series, and where the strongest stands.
101
+
102
+ ``None`` in the series is an hour not measured. ``source`` says where the
103
+ rain comes from; the thresholds are fitted on rain gauges, so rain from a
104
+ radar or a model is flagged.
105
+ """
106
+ key = resolve(region)
107
+ t = ITALICA_T5[key]
108
+ events = reconstruct_events(
109
+ series, no_rain_break_hours=no_rain_break_hours, min_event_mm=min_event_mm, source=source
110
+ )
111
+ strongest = strongest_event(events, t)
112
+ found: dict[str, Any] = {
113
+ "region": region,
114
+ "threshold": _threshold(key, t),
115
+ "source": source,
116
+ "events": [_event(e, t) for e in events],
117
+ "strongest": None if strongest is None else _event(strongest, t),
118
+ "above_threshold": None
119
+ if strongest is None
120
+ else t.exceedance(strongest.intensity_mm_h, strongest.duration_hours) > 0,
121
+ "rule": RULE,
122
+ }
123
+ notes = []
124
+ if source is None or "gauge" not in source.lower():
125
+ notes.append(
126
+ "The threshold is fitted on rain gauges. Rain from a radar or a model is not "
127
+ "gauge rain: the comparison is not validated."
128
+ )
129
+ if strongest is not None and strongest.unmeasured_hours:
130
+ notes.append(
131
+ f"{strongest.unmeasured_hours} hours of the event were not measured: its total "
132
+ "is a lower bound."
133
+ )
134
+ found["notes"] = notes
135
+ return found
136
+
137
+
138
+ def fit_facts(events: Iterable[tuple[float, float]], *, percentile: float = 5.0) -> dict[str, Any]:
139
+ """A threshold fitted on ``(duration_h, total_mm)`` of landslide-triggering rain."""
140
+ pairs = [(d, mm / d) for d, mm in events if d > 0]
141
+ fit = fit_threshold(pairs, percentile=percentile)
142
+ t = fit.threshold
143
+ return {
144
+ "alpha": round(t.alpha, 3),
145
+ "beta": round(t.beta, 4),
146
+ "percentile": percentile,
147
+ "landslides": fit.n_events,
148
+ "needed": [{"duration_h": d, "cumulated_mm": round(t.cumulated(d), 1)} for d in (24, 72)],
149
+ "rule": RULE,
150
+ }
@@ -0,0 +1,126 @@
1
+ """The MCP server: the thresholds as tools an assistant can call.
2
+
3
+ pip install "rainfall-thresholds[mcp]"
4
+ rainfall-thresholds-mcp # on standard input and output
5
+
6
+ The tools compute only from what the call gives them: no network, no live
7
+ rain. Bring the rain from a gauge, a radar or a model; the answer says how
8
+ far it is from the threshold, and that a threshold exceeded is not an alert.
9
+ The tools are the functions of :mod:`rainfall_thresholds.facts`, and
10
+ ``check`` is :func:`rainfall_thresholds.check.check_text`.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from dataclasses import asdict
16
+ from datetime import datetime
17
+ from typing import Any
18
+
19
+ from mcp.server.mcpserver import MCPServer
20
+ from mcp.server.mcpserver.exceptions import ToolError
21
+
22
+ from rainfall_thresholds.check import check_text
23
+ from rainfall_thresholds.facts import RULE, assess_facts, fit_facts, threshold_facts
24
+
25
+ INSTRUCTIONS = f"""\
26
+ Rainfall thresholds for shallow landslides in Italy (Caine power law, T5
27
+ fitted on the e-ITALICA landslides, measured at rain gauges).
28
+
29
+ Rules for every answer:
30
+ - Quote numbers only from the tools, with their units. mm is a total, mm/h an
31
+ intensity: a threshold asks for both, and they differ by the duration.
32
+ - Exceedance is in decades: +0.3 is twice the threshold intensity, +1 ten
33
+ times, negative is below.
34
+ - The thresholds are fitted on rain gauges. On radar or model rain the
35
+ comparison is not validated: say so.
36
+ - An hour not measured is null, never 0. A total with hours not measured is
37
+ a lower bound.
38
+ - Abruzzo and Molise use the threshold of central Italy.
39
+ - {RULE} For danger to people, point to the bulletin, the regional civil
40
+ protection and 112.
41
+ - Before answering in words, you can pass your text and the facts to `check`.
42
+ """
43
+
44
+
45
+ def create_server() -> MCPServer[Any]:
46
+ """The MCP server with its four tools."""
47
+ from rainfall_thresholds import __version__
48
+
49
+ server: MCPServer[Any] = MCPServer(
50
+ name="rainfall-thresholds",
51
+ title="Rainfall thresholds for landslides (Italy)",
52
+ instructions=INSTRUCTIONS,
53
+ website_url="https://agentengineering.it/rainfall-thresholds/",
54
+ version=__version__,
55
+ )
56
+
57
+ @server.tool()
58
+ def threshold(region: str, duration_h: float) -> dict[str, Any]:
59
+ """The rain the Italian T5 threshold asks for over a duration.
60
+
61
+ ``region``: an Italian region as e-ITALICA spells it ("Calabria",
62
+ "Emilia-Romagna"), or "italy", "northern", "central", "southern".
63
+ ``duration_h``: hours, > 0. Answers the intensity (mm/h) and the total
64
+ (mm) of the threshold, and what it was fitted on.
65
+ """
66
+ return _guard(lambda: threshold_facts(region, duration_h))
67
+
68
+ @server.tool()
69
+ def assess(
70
+ series: list[tuple[str, float | None]], region: str, source: str | None = None
71
+ ) -> dict[str, Any]:
72
+ """The rainfall events of an hourly series and where the strongest stands.
73
+
74
+ ``series``: ``[[time, mm], ...]``, one per hour, time in ISO 8601;
75
+ mm ``null`` for an hour not measured (never 0). ``source``: where the
76
+ rain comes from ("rain gauge", "DPC SRT1", "ERA5"...). Answers each
77
+ event (start, end, duration, total, intensity, the total the threshold
78
+ asks for, exceedance in decades, hours not measured) and the strongest.
79
+ """
80
+ return _guard(
81
+ lambda: assess_facts(
82
+ [(datetime.fromisoformat(t.replace("Z", "+00:00")), mm) for t, mm in series],
83
+ region,
84
+ source=source,
85
+ )
86
+ )
87
+
88
+ @server.tool()
89
+ def fit(events: list[tuple[float, float]], percentile: float = 5.0) -> dict[str, Any]:
90
+ """A threshold fitted on your own landslides.
91
+
92
+ ``events``: ``[[duration_h, total_mm], ...]`` of the rain that
93
+ triggered each landslide, at least three. Answers alpha, beta and the
94
+ rain the threshold asks for in 24 and 72 hours.
95
+ """
96
+ return _guard(lambda: fit_facts(events, percentile=percentile))
97
+
98
+ @server.tool()
99
+ def check(text: str, facts: dict[str, Any], question: str = "") -> dict[str, Any]:
100
+ """Check a text against the facts of a tool: numbers invented, in the wrong unit, rounded.
101
+
102
+ ``facts``: the answer of ``threshold``, ``assess`` or ``fit``. Empty
103
+ ``misquotes`` means every number is a fact of its unit; it does not
104
+ prove the number is said of the right thing.
105
+ """
106
+ found = check_text(text, facts, question=question)
107
+ return {"misquotes": [asdict(m) for m in found], "faithful": not found}
108
+
109
+ return server
110
+
111
+
112
+ def _guard(call: Any) -> dict[str, Any]:
113
+ """What the library refuses, as an error the agent can read and act on."""
114
+ try:
115
+ found: dict[str, Any] = call()
116
+ return found
117
+ except ValueError as exc:
118
+ raise ToolError(str(exc)) from exc
119
+
120
+
121
+ def run() -> None:
122
+ """Serve on standard input and output, until the client hangs up."""
123
+ create_server().run("stdio")
124
+
125
+
126
+ __all__ = ["INSTRUCTIONS", "create_server", "run"]
@@ -0,0 +1,163 @@
1
+ """How good a threshold is: landslides caught, and the alerts it costs.
2
+
3
+ A threshold is only half an answer. T5 catches 95 % of past landslides by
4
+ construction; what it does not say is how often it is exceeded when nothing
5
+ happens. These functions measure both sides on the same scale, for any
6
+ score that grows with danger: the exceedance of a threshold in decades, a
7
+ 24-hour total in mm, a probability.
8
+
9
+ You bring two lists of scores:
10
+
11
+ * ``landslides``: one score per landslide, the **highest** in the hours
12
+ before it (the lead window is your choice: 24, 48, 72 hours);
13
+ * ``ordinary``: one score per unit of time and place you could alert on
14
+ (cell-hours, municipality-days...), with or without landslides, as your
15
+ alert budget is counted.
16
+
17
+ ``None`` is a score that was not measured. It is left out and counted,
18
+ never read as zero.
19
+
20
+ Definitions, as in Limen's backtests (limen#243, limen#352):
21
+
22
+ * a landslide is **caught** when its score reaches the cutoff (``>=``);
23
+ * the **alert share** is the share of ordinary units at or above the cutoff;
24
+ * **discrimination** is hit rate over alert share: 1 is chance;
25
+ * the **cutoff at a budget** is the score that puts that share of ordinary
26
+ units on alert. Ties can make the share a little higher than asked.
27
+ """
28
+
29
+ from __future__ import annotations
30
+
31
+ import math
32
+ from collections.abc import Iterable
33
+ from dataclasses import dataclass
34
+
35
+
36
+ @dataclass(frozen=True, slots=True)
37
+ class Skill:
38
+ """What a cutoff catches, and what it costs."""
39
+
40
+ cutoff: float
41
+ caught: int
42
+ landslides: int
43
+ alerts: int
44
+ ordinary: int
45
+ #: Scores left out because they were not measured (``None`` or NaN).
46
+ unmeasured: int = 0
47
+
48
+ @property
49
+ def hit_rate(self) -> float | None:
50
+ """Share of the landslides caught; ``None`` without landslides."""
51
+ return self.caught / self.landslides if self.landslides else None
52
+
53
+ @property
54
+ def alert_share(self) -> float | None:
55
+ """Share of the ordinary units on alert; ``None`` without units."""
56
+ return self.alerts / self.ordinary if self.ordinary else None
57
+
58
+ @property
59
+ def discrimination(self) -> float | None:
60
+ """Hit rate over alert share: 1 is chance. ``None`` when either is unknown or zero."""
61
+ hit, share = self.hit_rate, self.alert_share
62
+ if hit is None or not share:
63
+ return None
64
+ return hit / share
65
+
66
+ @property
67
+ def alerts_per_caught(self) -> float | None:
68
+ """Alerts paid for every landslide caught; ``None`` when none is caught."""
69
+ return self.alerts / self.caught if self.caught else None
70
+
71
+
72
+ def _measured(scores: Iterable[float | None]) -> tuple[list[float], int]:
73
+ kept: list[float] = []
74
+ dropped = 0
75
+ for s in scores:
76
+ if s is None or math.isnan(s):
77
+ dropped += 1
78
+ else:
79
+ kept.append(float(s))
80
+ return kept, dropped
81
+
82
+
83
+ def skill(
84
+ landslides: Iterable[float | None],
85
+ ordinary: Iterable[float | None],
86
+ cutoff: float,
87
+ ) -> Skill:
88
+ """Landslides caught and ordinary units on alert at ``cutoff``."""
89
+ pos, pos_missing = _measured(landslides)
90
+ neg, neg_missing = _measured(ordinary)
91
+ return Skill(
92
+ cutoff=cutoff,
93
+ caught=sum(s >= cutoff for s in pos),
94
+ landslides=len(pos),
95
+ alerts=sum(s >= cutoff for s in neg),
96
+ ordinary=len(neg),
97
+ unmeasured=pos_missing + neg_missing,
98
+ )
99
+
100
+
101
+ def cutoff_at_budget(
102
+ ordinary: Iterable[float | None], budget: float, *, floor: float | None = None
103
+ ) -> float:
104
+ """The cutoff that puts ``budget`` (0-1) of the ordinary units on alert.
105
+
106
+ It is the k-th highest score, ``k = max(1, round(budget * n))``. With
107
+ ``floor``, a score at or below it never alerts (for a score that is 0 when
108
+ nothing happens, ``floor=0``): the cutoff is then at least the lowest score
109
+ above it, or ``inf`` when there is none. Without measured scores, ``inf``.
110
+ """
111
+ if not 0.0 < budget <= 1.0:
112
+ raise ValueError(f"budget must be in (0, 1], got {budget}")
113
+ values, _ = _measured(ordinary)
114
+ if not values:
115
+ return math.inf
116
+ ranked = sorted(values, reverse=True)
117
+ k = max(1, round(budget * len(ranked)))
118
+ cutoff = ranked[k - 1]
119
+ if floor is not None and cutoff <= floor:
120
+ cutoff = min((x for x in ranked if x > floor), default=math.inf)
121
+ return cutoff
122
+
123
+
124
+ def skill_at_budget(
125
+ landslides: Iterable[float | None],
126
+ ordinary: Iterable[float | None],
127
+ budget: float,
128
+ *,
129
+ floor: float | None = None,
130
+ ) -> Skill:
131
+ """:func:`skill` at the cutoff of :func:`cutoff_at_budget`.
132
+
133
+ The fair way to compare two scores: at the same share of units on alert,
134
+ which catches more landslides? Counting at a fixed level instead rewards
135
+ the score that alerts more.
136
+ """
137
+ neg = list(ordinary)
138
+ return skill(landslides, neg, cutoff_at_budget(neg, budget, floor=floor))
139
+
140
+
141
+ def auc(landslides: Iterable[float | None], ordinary: Iterable[float | None]) -> float | None:
142
+ """The chance that a landslide scores higher than an ordinary unit (Mann-Whitney).
143
+
144
+ Ties count half. ``None`` without one of the two lists. Read it with
145
+ care when many scores are tied, for example at zero: it then measures the
146
+ order of the few that are not, and says nothing about the level.
147
+ """
148
+ pos, _ = _measured(landslides)
149
+ neg, _ = _measured(ordinary)
150
+ if not pos or not neg:
151
+ return None
152
+ values = sorted([(s, True) for s in pos] + [(s, False) for s in neg], key=lambda v: v[0])
153
+ rank_sum = 0.0
154
+ i = 0
155
+ while i < len(values):
156
+ j = i
157
+ while j + 1 < len(values) and values[j + 1][0] == values[i][0]:
158
+ j += 1
159
+ mean_rank = (i + j) / 2.0 + 1.0
160
+ rank_sum += mean_rank * sum(is_pos for _, is_pos in values[i : j + 1])
161
+ i = j + 1
162
+ n_pos, n_neg = len(pos), len(neg)
163
+ return (rank_sum - n_pos * (n_pos + 1) / 2.0) / (n_pos * n_neg)