rainfall-thresholds 0.1.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,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1,176 @@
1
+ Metadata-Version: 2.4
2
+ Name: rainfall-thresholds
3
+ Version: 0.1.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-Python: >=3.12
20
+ Project-URL: Homepage, https://github.com/agent-engineering-studio/rainfall-thresholds
21
+ Project-URL: Issues, https://github.com/agent-engineering-studio/rainfall-thresholds/issues
22
+ Project-URL: Changelog, https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/CHANGELOG.md
23
+ Description-Content-Type: text/markdown
24
+
25
+ # rainfall-thresholds
26
+
27
+ Rainfall intensity-duration thresholds for shallow landslides: the Caine
28
+ power law, the reconstruction of rainfall events from an hourly series, and
29
+ the frequentist fit of a threshold to the events that triggered landslides.
30
+ Pure Python, no dependencies.
31
+
32
+ [![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)
33
+ [![PyPI](https://img.shields.io/pypi/v/rainfall-thresholds)](https://pypi.org/project/rainfall-thresholds/)
34
+
35
+ ## What it does
36
+
37
+ A shallow landslide is triggered when rain is intense enough for long
38
+ enough. The usual empirical model (Caine 1980) is a line in log-log space:
39
+
40
+ ```
41
+ I(D) = alpha * D^(-beta) I: mean intensity (mm/h), D: duration (h)
42
+ ```
43
+
44
+ An event above the line is in the conditions that triggered landslides
45
+ before. The package covers the three steps around that line:
46
+
47
+ | Step | Function |
48
+ |---|---|
49
+ | Hourly rain → events | `reconstruct_events`, `latest_event` |
50
+ | Event → threshold → how far above | `PowerLawThreshold.intensity` / `.cumulated` / `.exceedance` |
51
+ | Catalogue of triggering events → threshold | `fit_threshold` |
52
+
53
+ It also ships T5 thresholds for Italy refitted on the e-ITALICA catalogue,
54
+ with a test that refits them from the data.
55
+
56
+ ## Install
57
+
58
+ ```bash
59
+ pip install rainfall-thresholds
60
+ ```
61
+
62
+ ## Use
63
+
64
+ ```python
65
+ from datetime import UTC, datetime, timedelta
66
+
67
+ from rainfall_thresholds import ITALICA_T5, latest_event, reconstruct_events
68
+
69
+ start = datetime(2026, 10, 10, tzinfo=UTC)
70
+ hourly_mm = [0, 2, 8, 15, 22, 18, 9, 4, 0, 1, 3, 0, 0]
71
+ series = [(start + timedelta(hours=h), mm) for h, mm in enumerate(hourly_mm)]
72
+
73
+ event = latest_event(reconstruct_events(series, no_rain_break_hours=6, min_event_mm=2.0))
74
+ assert event is not None
75
+ threshold = ITALICA_T5["southern"]
76
+
77
+ print(f"{event.total_mm:.0f} mm in {event.duration_hours:.0f} h = {event.intensity_mm_h:.1f} mm/h")
78
+ print(f"T5 at that duration: {threshold.intensity(event.duration_hours):.1f} mm/h")
79
+ print(f"{threshold.exceedance(event.intensity_mm_h, event.duration_hours):+.2f} decades")
80
+ ```
81
+
82
+ ```
83
+ 82 mm in 10 h = 8.2 mm/h
84
+ T5 at that duration: 2.0 mm/h
85
+ +0.62 decades
86
+ ```
87
+
88
+ `exceedance` is `log10(I / I(D))`: 0 on the line, +1 at ten times the
89
+ threshold intensity, negative below.
90
+
91
+ ### Fitting your own threshold
92
+
93
+ ```python
94
+ from rainfall_thresholds import fit_threshold
95
+
96
+ # (duration_h, intensity_mm_h) of rainfall events that triggered landslides
97
+ fit = fit_threshold(triggering_events, percentile=5)
98
+ fit.threshold # PowerLawThreshold: 5 % of the events sit below it
99
+ fit.central # the least-squares line before it is lowered
100
+ ```
101
+
102
+ The method is the frequentist one of Brunetti et al. (2010) and
103
+ Peruccacci et al. (2012): least squares on `log I` against `log D`, then
104
+ the line is lowered by the chosen percentile of the residuals. One
105
+ difference: they take the percentile from a Gaussian fitted to a kernel
106
+ density of the residuals; this package takes it from the residuals
107
+ themselves. The two agree when the residuals are close to normal.
108
+
109
+ ## Thresholds for Italy
110
+
111
+ Fitted with `fit_threshold(percentile=5)` on the 5,974 events of e-ITALICA
112
+ v4 with a positive duration and cumulated rainfall:
113
+
114
+ | Macroregion | alpha (mm/h) | beta | Events | E at 24 h | E at 72 h |
115
+ |---|---|---|---|---|---|
116
+ | `italy` | 7.193 | 0.5685 | 5,974 | 28.3 mm | 45.5 mm |
117
+ | `northern` | 6.400 | 0.5134 | 2,659 | 30.0 mm | 51.3 mm |
118
+ | `central` | 7.953 | 0.6085 | 1,890 | 27.6 mm | 42.4 mm |
119
+ | `southern` | 8.754 | 0.6449 | 1,425 | 27.1 mm | 40.0 mm |
120
+
121
+ `MACROREGIONS` lists the regions in each group. **Abruzzo and Molise are in
122
+ the centre**, unlike the ISTAT "Sud": use `macroregion_of(region)` rather
123
+ than an ISTAT table, or the threshold will not be the one fitted on that
124
+ region's events.
125
+
126
+ These are not the thresholds published by the e-ITALICA authors, who use
127
+ their own method and partitions: they are what this package's method gives
128
+ on their data, and `tests/test_italy.py` checks that they still do.
129
+
130
+ ### Event reconstruction
131
+
132
+ An event runs from its first to its last wet hour; `no_rain_break_hours`
133
+ dry hours in a row end it, and an event below `min_event_mm` is dropped.
134
+ This is a simplified form of Melillo et al. (2018), whose CTRL-T tool also
135
+ varies the dry gap with the season. The e-ITALICA durations come from that
136
+ fuller procedure, so a threshold fitted on them and applied to events from
137
+ `reconstruct_events` mixes the two: fine for monitoring, worth knowing for
138
+ a study.
139
+
140
+ ## References
141
+
142
+ - Caine N. (1980). The rainfall intensity-duration control of shallow
143
+ landslides and debris flows. *Geografiska Annaler A* 62, 23-27.
144
+ - Brunetti M.T. et al. (2010). Rainfall thresholds for the possible
145
+ occurrence of landslides in Italy. *NHESS* 10, 447-458.
146
+ - Peruccacci S. et al. (2012). Lithological and seasonal control on
147
+ rainfall thresholds for the possible initiation of landslides in central
148
+ Italy. *Geomorphology* 139-140, 79-90.
149
+ - Melillo M. et al. (2018). A tool for the automatic calculation of
150
+ rainfall thresholds for landslide occurrence. *Environmental Modelling &
151
+ Software* 105, 230-243.
152
+ - Peruccacci S. et al. (2023). ITALICA: an ITAlian rainfall-induced
153
+ LandslIdes CAtalogue. *ESSD* 15, 2863-2877.
154
+ - Brunetti M.T. et al. (2024). e-ITALICA (enhanced ITAlian rainfall-induced
155
+ LandslIdes CAtalogue), v4. Zenodo,
156
+ [doi:10.5281/zenodo.14204473](https://doi.org/10.5281/zenodo.14204473).
157
+
158
+ ## Data licence
159
+
160
+ The test fixture `tests/fixtures/italica_v4_dur_rain.csv` is e-ITALICA v4
161
+ (Brunetti et al. 2024), [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/),
162
+ reduced to four columns (id, region, duration, cumulated rainfall).
163
+
164
+ Extracted from [Limen](https://github.com/agent-engineering-studio/limen),
165
+ which uses it for the rainfall component of its landslide score.
166
+
167
+ ## Development
168
+
169
+ ```bash
170
+ uv sync
171
+ make check
172
+ ```
173
+
174
+ ## License
175
+
176
+ Code: [Apache-2.0](./LICENSE).
@@ -0,0 +1,152 @@
1
+ # rainfall-thresholds
2
+
3
+ Rainfall intensity-duration thresholds for shallow landslides: the Caine
4
+ power law, the reconstruction of rainfall events from an hourly series, and
5
+ the frequentist fit of a threshold to the events that triggered landslides.
6
+ Pure Python, no dependencies.
7
+
8
+ [![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)
9
+ [![PyPI](https://img.shields.io/pypi/v/rainfall-thresholds)](https://pypi.org/project/rainfall-thresholds/)
10
+
11
+ ## What it does
12
+
13
+ A shallow landslide is triggered when rain is intense enough for long
14
+ enough. The usual empirical model (Caine 1980) is a line in log-log space:
15
+
16
+ ```
17
+ I(D) = alpha * D^(-beta) I: mean intensity (mm/h), D: duration (h)
18
+ ```
19
+
20
+ An event above the line is in the conditions that triggered landslides
21
+ before. The package covers the three steps around that line:
22
+
23
+ | Step | Function |
24
+ |---|---|
25
+ | Hourly rain → events | `reconstruct_events`, `latest_event` |
26
+ | Event → threshold → how far above | `PowerLawThreshold.intensity` / `.cumulated` / `.exceedance` |
27
+ | Catalogue of triggering events → threshold | `fit_threshold` |
28
+
29
+ It also ships T5 thresholds for Italy refitted on the e-ITALICA catalogue,
30
+ with a test that refits them from the data.
31
+
32
+ ## Install
33
+
34
+ ```bash
35
+ pip install rainfall-thresholds
36
+ ```
37
+
38
+ ## Use
39
+
40
+ ```python
41
+ from datetime import UTC, datetime, timedelta
42
+
43
+ from rainfall_thresholds import ITALICA_T5, latest_event, reconstruct_events
44
+
45
+ start = datetime(2026, 10, 10, tzinfo=UTC)
46
+ hourly_mm = [0, 2, 8, 15, 22, 18, 9, 4, 0, 1, 3, 0, 0]
47
+ series = [(start + timedelta(hours=h), mm) for h, mm in enumerate(hourly_mm)]
48
+
49
+ event = latest_event(reconstruct_events(series, no_rain_break_hours=6, min_event_mm=2.0))
50
+ assert event is not None
51
+ threshold = ITALICA_T5["southern"]
52
+
53
+ print(f"{event.total_mm:.0f} mm in {event.duration_hours:.0f} h = {event.intensity_mm_h:.1f} mm/h")
54
+ print(f"T5 at that duration: {threshold.intensity(event.duration_hours):.1f} mm/h")
55
+ print(f"{threshold.exceedance(event.intensity_mm_h, event.duration_hours):+.2f} decades")
56
+ ```
57
+
58
+ ```
59
+ 82 mm in 10 h = 8.2 mm/h
60
+ T5 at that duration: 2.0 mm/h
61
+ +0.62 decades
62
+ ```
63
+
64
+ `exceedance` is `log10(I / I(D))`: 0 on the line, +1 at ten times the
65
+ threshold intensity, negative below.
66
+
67
+ ### Fitting your own threshold
68
+
69
+ ```python
70
+ from rainfall_thresholds import fit_threshold
71
+
72
+ # (duration_h, intensity_mm_h) of rainfall events that triggered landslides
73
+ fit = fit_threshold(triggering_events, percentile=5)
74
+ fit.threshold # PowerLawThreshold: 5 % of the events sit below it
75
+ fit.central # the least-squares line before it is lowered
76
+ ```
77
+
78
+ The method is the frequentist one of Brunetti et al. (2010) and
79
+ Peruccacci et al. (2012): least squares on `log I` against `log D`, then
80
+ the line is lowered by the chosen percentile of the residuals. One
81
+ difference: they take the percentile from a Gaussian fitted to a kernel
82
+ density of the residuals; this package takes it from the residuals
83
+ themselves. The two agree when the residuals are close to normal.
84
+
85
+ ## Thresholds for Italy
86
+
87
+ Fitted with `fit_threshold(percentile=5)` on the 5,974 events of e-ITALICA
88
+ v4 with a positive duration and cumulated rainfall:
89
+
90
+ | Macroregion | alpha (mm/h) | beta | Events | E at 24 h | E at 72 h |
91
+ |---|---|---|---|---|---|
92
+ | `italy` | 7.193 | 0.5685 | 5,974 | 28.3 mm | 45.5 mm |
93
+ | `northern` | 6.400 | 0.5134 | 2,659 | 30.0 mm | 51.3 mm |
94
+ | `central` | 7.953 | 0.6085 | 1,890 | 27.6 mm | 42.4 mm |
95
+ | `southern` | 8.754 | 0.6449 | 1,425 | 27.1 mm | 40.0 mm |
96
+
97
+ `MACROREGIONS` lists the regions in each group. **Abruzzo and Molise are in
98
+ the centre**, unlike the ISTAT "Sud": use `macroregion_of(region)` rather
99
+ than an ISTAT table, or the threshold will not be the one fitted on that
100
+ region's events.
101
+
102
+ These are not the thresholds published by the e-ITALICA authors, who use
103
+ their own method and partitions: they are what this package's method gives
104
+ on their data, and `tests/test_italy.py` checks that they still do.
105
+
106
+ ### Event reconstruction
107
+
108
+ An event runs from its first to its last wet hour; `no_rain_break_hours`
109
+ dry hours in a row end it, and an event below `min_event_mm` is dropped.
110
+ This is a simplified form of Melillo et al. (2018), whose CTRL-T tool also
111
+ varies the dry gap with the season. The e-ITALICA durations come from that
112
+ fuller procedure, so a threshold fitted on them and applied to events from
113
+ `reconstruct_events` mixes the two: fine for monitoring, worth knowing for
114
+ a study.
115
+
116
+ ## References
117
+
118
+ - Caine N. (1980). The rainfall intensity-duration control of shallow
119
+ landslides and debris flows. *Geografiska Annaler A* 62, 23-27.
120
+ - Brunetti M.T. et al. (2010). Rainfall thresholds for the possible
121
+ occurrence of landslides in Italy. *NHESS* 10, 447-458.
122
+ - Peruccacci S. et al. (2012). Lithological and seasonal control on
123
+ rainfall thresholds for the possible initiation of landslides in central
124
+ Italy. *Geomorphology* 139-140, 79-90.
125
+ - Melillo M. et al. (2018). A tool for the automatic calculation of
126
+ rainfall thresholds for landslide occurrence. *Environmental Modelling &
127
+ Software* 105, 230-243.
128
+ - Peruccacci S. et al. (2023). ITALICA: an ITAlian rainfall-induced
129
+ LandslIdes CAtalogue. *ESSD* 15, 2863-2877.
130
+ - Brunetti M.T. et al. (2024). e-ITALICA (enhanced ITAlian rainfall-induced
131
+ LandslIdes CAtalogue), v4. Zenodo,
132
+ [doi:10.5281/zenodo.14204473](https://doi.org/10.5281/zenodo.14204473).
133
+
134
+ ## Data licence
135
+
136
+ The test fixture `tests/fixtures/italica_v4_dur_rain.csv` is e-ITALICA v4
137
+ (Brunetti et al. 2024), [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/),
138
+ reduced to four columns (id, region, duration, cumulated rainfall).
139
+
140
+ Extracted from [Limen](https://github.com/agent-engineering-studio/limen),
141
+ which uses it for the rainfall component of its landslide score.
142
+
143
+ ## Development
144
+
145
+ ```bash
146
+ uv sync
147
+ make check
148
+ ```
149
+
150
+ ## License
151
+
152
+ Code: [Apache-2.0](./LICENSE).
@@ -0,0 +1,98 @@
1
+ [project]
2
+ name = "rainfall-thresholds"
3
+ version = "0.1.0"
4
+ description = "Rainfall intensity-duration thresholds for shallow landslides (Caine power law, frequentist fitting)"
5
+ readme = "README.md"
6
+ keywords = [
7
+ "landslide",
8
+ "rainfall threshold",
9
+ "intensity-duration",
10
+ "caine",
11
+ "hydrology",
12
+ "natural hazards",
13
+ "italy",
14
+ "italica",
15
+ ]
16
+ requires-python = ">=3.12"
17
+ license = "Apache-2.0"
18
+ license-files = ["LICENSE"]
19
+ classifiers = [
20
+ "Development Status :: 4 - Beta",
21
+ "Intended Audience :: Science/Research",
22
+ "Topic :: Scientific/Engineering :: Atmospheric Science",
23
+ "Topic :: Scientific/Engineering :: Hydrology",
24
+ "Operating System :: OS Independent",
25
+ "Programming Language :: Python :: 3",
26
+ "Programming Language :: Python :: 3.12",
27
+ "Programming Language :: Python :: 3.13",
28
+ "Typing :: Typed",
29
+ ]
30
+ dependencies = []
31
+
32
+ [[project.authors]]
33
+ name = "Giuseppe Zileni"
34
+ email = "giuseppe.zileni@gmail.com"
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/agent-engineering-studio/rainfall-thresholds"
38
+ Issues = "https://github.com/agent-engineering-studio/rainfall-thresholds/issues"
39
+ Changelog = "https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/CHANGELOG.md"
40
+
41
+ [build-system]
42
+ requires = ["uv_build>=0.13.6,<0.14"]
43
+ build-backend = "uv_build"
44
+
45
+ [dependency-groups]
46
+ dev = [
47
+ "mypy>=1.13",
48
+ "pytest>=8.3",
49
+ "pytest-cov>=6.0",
50
+ "ruff>=0.8",
51
+ ]
52
+
53
+ [tool.ruff]
54
+ line-length = 100
55
+ target-version = "py312"
56
+
57
+ [tool.ruff.lint]
58
+ select = [
59
+ "E",
60
+ "F",
61
+ "W",
62
+ "I",
63
+ "N",
64
+ "UP",
65
+ "B",
66
+ "C4",
67
+ "SIM",
68
+ "ARG",
69
+ "PTH",
70
+ "RUF",
71
+ ]
72
+
73
+ [tool.ruff.lint.per-file-ignores]
74
+ "tests/**" = [
75
+ "ARG",
76
+ "B018",
77
+ ]
78
+
79
+ [tool.mypy]
80
+ strict = true
81
+ python_version = "3.12"
82
+ files = [
83
+ "src",
84
+ "tests",
85
+ ]
86
+ warn_unused_ignores = true
87
+ warn_redundant_casts = true
88
+
89
+ [tool.pytest.ini_options]
90
+ testpaths = ["tests"]
91
+ addopts = "--strict-markers"
92
+
93
+ [tool.coverage.run]
94
+ source = ["rainfall_thresholds"]
95
+
96
+ [tool.coverage.report]
97
+ fail_under = 90
98
+ show_missing = true
@@ -0,0 +1,69 @@
1
+ [project]
2
+ name = "rainfall-thresholds"
3
+ version = "0.1.0"
4
+ description = "Rainfall intensity-duration thresholds for shallow landslides (Caine power law, frequentist fitting)"
5
+ readme = "README.md"
6
+ keywords = ["landslide", "rainfall threshold", "intensity-duration", "caine", "hydrology", "natural hazards", "italy", "italica"]
7
+ requires-python = ">=3.12"
8
+ license = "Apache-2.0"
9
+ license-files = ["LICENSE"]
10
+ authors = [
11
+ { name = "Giuseppe Zileni", email = "giuseppe.zileni@gmail.com" },
12
+ ]
13
+ classifiers = [
14
+ "Development Status :: 4 - Beta",
15
+ "Intended Audience :: Science/Research",
16
+ "Topic :: Scientific/Engineering :: Atmospheric Science",
17
+ "Topic :: Scientific/Engineering :: Hydrology",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Typing :: Typed",
23
+ ]
24
+ dependencies = []
25
+
26
+ [project.urls]
27
+ Homepage = "https://github.com/agent-engineering-studio/rainfall-thresholds"
28
+ Issues = "https://github.com/agent-engineering-studio/rainfall-thresholds/issues"
29
+ Changelog = "https://github.com/agent-engineering-studio/rainfall-thresholds/blob/main/CHANGELOG.md"
30
+
31
+ [build-system]
32
+ requires = ["uv_build>=0.13.6,<0.14"]
33
+ build-backend = "uv_build"
34
+
35
+ [dependency-groups]
36
+ dev = [
37
+ "mypy>=1.13",
38
+ "pytest>=8.3",
39
+ "pytest-cov>=6.0",
40
+ "ruff>=0.8",
41
+ ]
42
+
43
+ [tool.ruff]
44
+ line-length = 100
45
+ target-version = "py312"
46
+
47
+ [tool.ruff.lint]
48
+ select = ["E", "F", "W", "I", "N", "UP", "B", "C4", "SIM", "ARG", "PTH", "RUF"]
49
+
50
+ [tool.ruff.lint.per-file-ignores]
51
+ "tests/**" = ["ARG", "B018"]
52
+
53
+ [tool.mypy]
54
+ strict = true
55
+ python_version = "3.12"
56
+ files = ["src", "tests"]
57
+ warn_unused_ignores = true
58
+ warn_redundant_casts = true
59
+
60
+ [tool.pytest.ini_options]
61
+ testpaths = ["tests"]
62
+ addopts = "--strict-markers"
63
+
64
+ [tool.coverage.run]
65
+ source = ["rainfall_thresholds"]
66
+
67
+ [tool.coverage.report]
68
+ fail_under = 90
69
+ show_missing = true
@@ -0,0 +1,24 @@
1
+ """Rainfall intensity-duration thresholds for shallow landslides."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from rainfall_thresholds.events import RainfallEvent, latest_event, reconstruct_events
6
+ from rainfall_thresholds.fit import ThresholdFit, fit_threshold, percentile_of
7
+ from rainfall_thresholds.italy import ITALICA_T5, MACROREGIONS, macroregion_of
8
+ from rainfall_thresholds.threshold import PowerLawThreshold
9
+
10
+ __version__ = version("rainfall-thresholds")
11
+
12
+ __all__ = [
13
+ "ITALICA_T5",
14
+ "MACROREGIONS",
15
+ "PowerLawThreshold",
16
+ "RainfallEvent",
17
+ "ThresholdFit",
18
+ "__version__",
19
+ "fit_threshold",
20
+ "latest_event",
21
+ "macroregion_of",
22
+ "percentile_of",
23
+ "reconstruct_events",
24
+ ]
@@ -0,0 +1,80 @@
1
+ """Rainfall events from an hourly series, after Melillo et al. (2018).
2
+
3
+ The series is split wherever ``no_rain_break_hours`` or more consecutive
4
+ dry hours occur; an event whose cumulated rainfall is below ``min_event_mm``
5
+ is dropped. An event runs from its first to its last wet hour, both
6
+ included, so a single wet hour is a one-hour event.
7
+
8
+ This is a simplified reconstruction: Melillo et al. also vary the dry gap
9
+ with the season and separate sub-events within a rainfall period. Use their
10
+ CTRL-T tool when the reconstruction itself is what you are studying.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from collections.abc import Iterable
16
+ from dataclasses import dataclass
17
+ from datetime import datetime
18
+
19
+
20
+ @dataclass(frozen=True, slots=True)
21
+ class RainfallEvent:
22
+ """One rainfall event: first and last wet hour, duration and total."""
23
+
24
+ start: datetime
25
+ end: datetime
26
+ duration_hours: float
27
+ total_mm: float
28
+
29
+ @property
30
+ def intensity_mm_h(self) -> float:
31
+ """Mean intensity over the event."""
32
+ return self.total_mm / self.duration_hours
33
+
34
+
35
+ def reconstruct_events(
36
+ series: Iterable[tuple[datetime, float]],
37
+ *,
38
+ no_rain_break_hours: int,
39
+ min_event_mm: float,
40
+ ) -> list[RainfallEvent]:
41
+ """Split an hourly ``(timestamp, mm)`` series into rainfall events.
42
+
43
+ The series is sorted by timestamp first. Dry hours are counted as
44
+ samples, so the series is expected to be hourly and without gaps.
45
+ """
46
+ if no_rain_break_hours < 1:
47
+ raise ValueError(f"no_rain_break_hours must be >= 1, got {no_rain_break_hours}")
48
+ samples = sorted(series, key=lambda s: s[0])
49
+ events: list[RainfallEvent] = []
50
+ first: datetime | None = None
51
+ last: datetime | None = None
52
+ total = 0.0
53
+ dry = 0
54
+
55
+ def close() -> None:
56
+ if first is not None and last is not None and total >= min_event_mm:
57
+ hours = max(1.0, (last - first).total_seconds() / 3600.0 + 1.0)
58
+ events.append(RainfallEvent(first, last, hours, total))
59
+
60
+ for when, mm in samples:
61
+ if mm < 0:
62
+ raise ValueError(f"negative rainfall at {when.isoformat()}: {mm}")
63
+ if mm > 0:
64
+ if first is None:
65
+ first = when
66
+ total += mm
67
+ last = when
68
+ dry = 0
69
+ else:
70
+ dry += 1
71
+ if dry >= no_rain_break_hours and first is not None:
72
+ close()
73
+ first, last, total = None, None, 0.0
74
+ close()
75
+ return events
76
+
77
+
78
+ def latest_event(events: Iterable[RainfallEvent]) -> RainfallEvent | None:
79
+ """The event that ended last, or ``None``."""
80
+ return max(events, key=lambda e: e.end, default=None)
@@ -0,0 +1,77 @@
1
+ """Fitting a threshold to the rainfall conditions that triggered landslides.
2
+
3
+ The frequentist approach of Brunetti et al. (2010) and Peruccacci et al.
4
+ (2012): fit ``log10 I = log10 alpha - beta log10 D`` by least squares over
5
+ the (D, I) pairs of known landslide-triggering events, then lower the line
6
+ until a chosen share of the events sits below it. The threshold at the 5th
7
+ percentile, ``T5``, leaves 5 % of the triggering events beneath.
8
+
9
+ Where Peruccacci et al. take the percentile from a Gaussian fitted to a
10
+ kernel density of the residuals, this module takes it from the residuals
11
+ themselves (linear interpolation between order statistics). The two agree
12
+ when the residuals are close to normal; the empirical one needs no
13
+ assumption about their shape.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import math
19
+ import statistics
20
+ from collections.abc import Iterable
21
+ from dataclasses import dataclass
22
+
23
+ from rainfall_thresholds.threshold import PowerLawThreshold
24
+
25
+
26
+ @dataclass(frozen=True, slots=True)
27
+ class ThresholdFit:
28
+ """A fitted threshold and what it was fitted on."""
29
+
30
+ threshold: PowerLawThreshold
31
+ percentile: float
32
+ n_events: int
33
+ #: The least-squares line before it is lowered (the 50 % threshold is
34
+ #: close to it, but not equal when the residuals are skewed).
35
+ central: PowerLawThreshold
36
+
37
+
38
+ def fit_threshold(
39
+ events: Iterable[tuple[float, float]],
40
+ *,
41
+ percentile: float = 5.0,
42
+ ) -> ThresholdFit:
43
+ """Fit ``I = alpha * D^(-beta)`` at ``percentile`` to ``(duration_h, intensity_mm_h)`` pairs.
44
+
45
+ Pairs with a non-positive duration or intensity are skipped: they have
46
+ no logarithm. At least three usable pairs are needed.
47
+ """
48
+ if not 0 < percentile < 100:
49
+ raise ValueError(f"percentile must be in (0, 100), got {percentile}")
50
+ pairs = [(d, i) for d, i in events if d > 0 and i > 0]
51
+ if len(pairs) < 3:
52
+ raise ValueError(f"need at least 3 events with D > 0 and I > 0, got {len(pairs)}")
53
+ x = [math.log10(d) for d, _ in pairs]
54
+ y = [math.log10(i) for _, i in pairs]
55
+ if len(set(x)) < 2:
56
+ raise ValueError("all events have the same duration: the slope is undefined")
57
+ slope, intercept = statistics.linear_regression(x, y)
58
+ residuals = [yi - (intercept + slope * xi) for xi, yi in zip(x, y, strict=True)]
59
+ shift = percentile_of(residuals, percentile)
60
+ return ThresholdFit(
61
+ threshold=PowerLawThreshold(alpha=10 ** (intercept + shift), beta=-slope),
62
+ percentile=percentile,
63
+ n_events=len(pairs),
64
+ central=PowerLawThreshold(alpha=10**intercept, beta=-slope),
65
+ )
66
+
67
+
68
+ def percentile_of(values: list[float], percentile: float) -> float:
69
+ """The ``percentile``-th percentile, interpolating linearly between order statistics.
70
+
71
+ The same definition as NumPy's default (``method="linear"``).
72
+ """
73
+ ordered = sorted(values)
74
+ position = (len(ordered) - 1) * percentile / 100.0
75
+ below = math.floor(position)
76
+ above = min(below + 1, len(ordered) - 1)
77
+ return ordered[below] + (ordered[above] - ordered[below]) * (position - below)
@@ -0,0 +1,59 @@
1
+ """T5 thresholds for Italy, fitted on the e-ITALICA catalogue.
2
+
3
+ e-ITALICA v4 (Brunetti et al. 2024, doi:10.5281/zenodo.14204473,
4
+ CC BY 4.0) lists rainfall-induced landslides with the duration and
5
+ cumulated rainfall of the triggering event, measured at a rain gauge.
6
+ The 5,974 events with both values positive were fitted with
7
+ :func:`~rainfall_thresholds.fit.fit_threshold` at the 5th percentile,
8
+ nationally and for three macroregions. ``tests/test_italy.py`` refits them
9
+ from the catalogue, so these numbers are reproducible, not transcribed.
10
+
11
+ They are not the thresholds published by the e-ITALICA authors, who use a
12
+ kernel-density estimate of the residuals and their own regional
13
+ partitions: they are what this package's method gives on their data.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from types import MappingProxyType
19
+
20
+ from rainfall_thresholds.threshold import PowerLawThreshold
21
+
22
+ #: The regions in each macroregion, as named in e-ITALICA. Abruzzo and Molise
23
+ #: are in the centre (unlike the ISTAT "Sud").
24
+ MACROREGIONS: MappingProxyType[str, frozenset[str]] = MappingProxyType(
25
+ {
26
+ "northern": frozenset(
27
+ {
28
+ "Piemonte",
29
+ "Valle d'Aosta",
30
+ "Liguria",
31
+ "Lombardia",
32
+ "Trentino-Alto Adige",
33
+ "Veneto",
34
+ "Friuli-Venezia Giulia",
35
+ "Emilia-Romagna",
36
+ }
37
+ ),
38
+ "central": frozenset({"Toscana", "Umbria", "Marche", "Lazio", "Abruzzo", "Molise"}),
39
+ "southern": frozenset(
40
+ {"Campania", "Puglia", "Basilicata", "Calabria", "Sicilia", "Sardegna"}
41
+ ),
42
+ }
43
+ )
44
+
45
+ #: T5 thresholds, ``I = alpha * D^(-beta)`` (mm/h, hours). ``"italy"`` is the
46
+ #: national fit; the others use the regions in :data:`MACROREGIONS`.
47
+ ITALICA_T5: MappingProxyType[str, PowerLawThreshold] = MappingProxyType(
48
+ {
49
+ "italy": PowerLawThreshold(alpha=7.193, beta=0.5685), # 5,974 events
50
+ "northern": PowerLawThreshold(alpha=6.400, beta=0.5134), # 2,659 events
51
+ "central": PowerLawThreshold(alpha=7.953, beta=0.6085), # 1,890 events
52
+ "southern": PowerLawThreshold(alpha=8.754, beta=0.6449), # 1,425 events
53
+ }
54
+ )
55
+
56
+
57
+ def macroregion_of(region: str) -> str | None:
58
+ """The macroregion of an Italian region (e-ITALICA spelling), or ``None``."""
59
+ return next((name for name, regions in MACROREGIONS.items() if region in regions), None)
@@ -0,0 +1,51 @@
1
+ """The power-law rainfall intensity-duration threshold (Caine 1980).
2
+
3
+ I(D) = alpha * D^(-beta) I in mm/h, D in hours
4
+
5
+ A rainfall event of mean intensity ``I`` lasting ``D`` hours is above the
6
+ threshold when ``I > I(D)``. Equivalently, in cumulated rainfall,
7
+ ``E(D) = alpha * D^(1 - beta)`` mm.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import math
13
+ from dataclasses import dataclass
14
+
15
+
16
+ @dataclass(frozen=True, slots=True)
17
+ class PowerLawThreshold:
18
+ """``I(D) = alpha * D^(-beta)``, with ``alpha`` in mm/h and ``D`` in hours."""
19
+
20
+ alpha: float
21
+ beta: float
22
+
23
+ def __post_init__(self) -> None:
24
+ if self.alpha <= 0:
25
+ raise ValueError(f"alpha must be > 0, got {self.alpha}")
26
+
27
+ def intensity(self, duration_hours: float) -> float:
28
+ """The threshold mean intensity for an event of this duration, in mm/h."""
29
+ _check_duration(duration_hours)
30
+ return float(self.alpha * duration_hours ** (-self.beta))
31
+
32
+ def cumulated(self, duration_hours: float) -> float:
33
+ """The threshold cumulated rainfall for an event of this duration, in mm."""
34
+ _check_duration(duration_hours)
35
+ return float(self.alpha * duration_hours ** (1.0 - self.beta))
36
+
37
+ def exceedance(self, intensity_mm_h: float, duration_hours: float) -> float:
38
+ """``log10(I / I(D))``: decades above (positive) or below (negative) the line.
39
+
40
+ Negative infinity for a dry event (zero intensity).
41
+ """
42
+ if intensity_mm_h < 0:
43
+ raise ValueError(f"intensity_mm_h must be >= 0, got {intensity_mm_h}")
44
+ if intensity_mm_h == 0:
45
+ return -math.inf
46
+ return math.log10(intensity_mm_h) - math.log10(self.intensity(duration_hours))
47
+
48
+
49
+ def _check_duration(duration_hours: float) -> None:
50
+ if duration_hours <= 0:
51
+ raise ValueError(f"duration_hours must be > 0, got {duration_hours}")