icon2i 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.
icon2i-0.1.0/LICENSE ADDED
@@ -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
+
icon2i-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,136 @@
1
+ Metadata-Version: 2.4
2
+ Name: icon2i
3
+ Version: 0.1.0
4
+ Summary: The rain of the next hours over Italy from ICON-2I, the weather model of the Agenzia ItaliaMeteo, read from its open data on MeteoHub
5
+ Keywords: icon-2i,weather model,precipitation,forecast,open data,italy,italiameteo,meteohub,grib
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 :: 3 - Alpha
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
17
+ Classifier: Typing :: Typed
18
+ Requires-Dist: httpx>=0.27
19
+ Requires-Dist: limen-common[http]>=0.1.1
20
+ Requires-Dist: numpy>=2.0
21
+ Requires-Dist: rasterio>=1.4
22
+ Requires-Python: >=3.12
23
+ Project-URL: Homepage, https://github.com/agent-engineering-studio/icon2i
24
+ Project-URL: Issues, https://github.com/agent-engineering-studio/icon2i/issues
25
+ Project-URL: Documentation, https://agentengineering.it/icon2i/
26
+ Project-URL: Changelog, https://github.com/agent-engineering-studio/icon2i/blob/main/CHANGELOG.md
27
+ Description-Content-Type: text/markdown
28
+
29
+ # icon2i
30
+
31
+ [![ci](https://github.com/agent-engineering-studio/icon2i/actions/workflows/ci.yml/badge.svg)](https://github.com/agent-engineering-studio/icon2i/actions/workflows/ci.yml)
32
+ [![PyPI](https://img.shields.io/pypi/v/icon2i)](https://pypi.org/project/icon2i/)
33
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
34
+
35
+ The rain of the next hours over Italy from **ICON-2I**, the weather model of
36
+ the [Agenzia ItaliaMeteo](https://www.agenziaitaliameteo.it/), read from its
37
+ open data on [MeteoHub](https://meteohub.agenziaitaliameteo.it/nwp/ICON-2I_SURFACE_PRESSURE_LEVELS/).
38
+
39
+ ICON-2I is the national model: 2.2 km over Italy, run at 00 and 12 UTC, 72
40
+ hours ahead. Its runs are open data, CC BY 4.0, with no key and no account.
41
+ This library downloads a run and reads the rain of its hours, as grids or at
42
+ points.
43
+
44
+ ```bash
45
+ pip install icon2i
46
+ ```
47
+
48
+ ```python
49
+ from datetime import UTC, datetime, timedelta
50
+
51
+ from icon2i import MeteoHub, Run
52
+
53
+ async with MeteoHub() as hub:
54
+ file = await hub.newest() # the newest TOT_PREC, about 80 MB, downloaded once
55
+
56
+ run = Run(file)
57
+ run.start, run.last # 2026-12-02 12:00 UTC, 2026-12-05 12:00 UTC
58
+
59
+ hour = run.rain(run.start + timedelta(hours=9)) # the rain of 20:00-21:00 UTC, a grid in mm
60
+ hour.sample([(15.29, 37.08)]) # [0.8] Siracusa
61
+
62
+ run.hourly([(15.29, 37.08)], run.start, run.start + timedelta(hours=24))
63
+ # {13:00: [0.0], 14:00: [0.0], ..., 21:00: [0.8], ...}: hour by hour, mm, per point
64
+ ```
65
+
66
+ From the shell:
67
+
68
+ ```bash
69
+ icon2i runs # the runs MeteoHub keeps, the newest first
70
+ icon2i fetch # download the newest run, print where it is
71
+ icon2i rain 15.29 37.08 # the rain of every hour of the newest run there, as CSV
72
+ ```
73
+
74
+ ## What it reads
75
+
76
+ MeteoHub keeps the runs of the last few days, one folder each
77
+ (`2026120212/`), and in it one folder a variable with one GRIB2 file holding
78
+ every hour of the run. The library reads `TOT_PREC`: the precipitation since
79
+ the start of the run, in kg/m², which is mm. The rain of a window is the
80
+ difference of two totals:
81
+
82
+ | Call | Gives |
83
+ |---|---|
84
+ | `MeteoHub().runs()` | the runs MeteoHub keeps, newest first |
85
+ | `MeteoHub().fetch(run)` / `.newest()` | the file of a run on disk, downloaded if missing / of the newest run that has it, keeping two |
86
+ | `Run(file).rain(end, window=1 h)` | the rain of `(end - window, end]`, a `Field` in mm |
87
+ | `Run(file).total(time)` | the precipitation from the start of the run to `time` |
88
+ | `Run(file).fields(start, end)` | the rain of every hour in `(start, end]` |
89
+ | `Run(file).hourly(points, start, end)` | the same at lon/lat points: `{hour: [mm or None, ...]}` |
90
+ | `Field.sample(points)` | a field at points: the pixel each falls in |
91
+
92
+ `Run.hourly` has the signature of `dpc_radar`'s readers
93
+ (`MergingArchive.hourly(points, start, end)`): the radar for the hours gone,
94
+ the model for the hours to come, the same shape.
95
+
96
+ The file is read with [rasterio](https://rasterio.readthedocs.io/) (the GRIB
97
+ driver of GDAL), so no eccodes to install. The time of each band comes from
98
+ the file itself (`GRIB_REF_TIME`, `GRIB_VALID_TIME`).
99
+
100
+ ## What it does not do
101
+
102
+ - **It is a forecast, not a measure.** For the rain that fell, a radar
103
+ ([dpc-radar](https://github.com/agent-engineering-studio/dpc-radar)) or a
104
+ rain gauge ([regional-raingauges](https://github.com/agent-engineering-studio/regional-raingauges)).
105
+ - **It is not an alert.** The official alert in Italy is the criticality
106
+ bulletin of the Dipartimento della Protezione Civile and of the Regions.
107
+ - **`None` is "the run does not say"**: a time before its start or after its
108
+ last hour, a point outside its grid. Never zero, which is "no rain".
109
+ - **It does not read the clock.** "The newest run" is the newest MeteoHub
110
+ lists; "from now" is the caller's.
111
+ - **It reads one variable today**, `TOT_PREC`. `MeteoHub.fetch(run, "T_2M")`
112
+ downloads any other, but `Run` only knows precipitation.
113
+
114
+ ## Where the files go
115
+
116
+ `MeteoHub.fetch` and `newest` write to the folder you pass, else
117
+ `$ICON2I_DATA_DIR`, else `$DATA_ROOT/icon2i` (the root shared with
118
+ [Limen](https://github.com/agent-engineering-studio/limen) and the other
119
+ libraries), else `./data/icon2i`: the rule of
120
+ [limen-common](https://github.com/agent-engineering-studio/limen-common). A
121
+ file is written through a temporary one and a rename: a crash never leaves
122
+ half a file. `newest` keeps the last two runs.
123
+
124
+ ## Credit and licence
125
+
126
+ The data: **Agenzia ItaliaMeteo, ICON-2I, CC BY 4.0** (`icon2i.CREDIT`).
127
+ Credit it wherever they are shown. The code: Apache-2.0.
128
+
129
+ ## Develop
130
+
131
+ ```bash
132
+ make check # ruff, mypy --strict, pytest: the gate CI runs
133
+ uv run pytest -m live # also the test against the real MeteoHub (downloads ~80 MB)
134
+ ```
135
+
136
+ See [CONTRIBUTING.md](CONTRIBUTING.md) and the [CHANGELOG](CHANGELOG.md).
icon2i-0.1.0/README.md ADDED
@@ -0,0 +1,108 @@
1
+ # icon2i
2
+
3
+ [![ci](https://github.com/agent-engineering-studio/icon2i/actions/workflows/ci.yml/badge.svg)](https://github.com/agent-engineering-studio/icon2i/actions/workflows/ci.yml)
4
+ [![PyPI](https://img.shields.io/pypi/v/icon2i)](https://pypi.org/project/icon2i/)
5
+ [![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
6
+
7
+ The rain of the next hours over Italy from **ICON-2I**, the weather model of
8
+ the [Agenzia ItaliaMeteo](https://www.agenziaitaliameteo.it/), read from its
9
+ open data on [MeteoHub](https://meteohub.agenziaitaliameteo.it/nwp/ICON-2I_SURFACE_PRESSURE_LEVELS/).
10
+
11
+ ICON-2I is the national model: 2.2 km over Italy, run at 00 and 12 UTC, 72
12
+ hours ahead. Its runs are open data, CC BY 4.0, with no key and no account.
13
+ This library downloads a run and reads the rain of its hours, as grids or at
14
+ points.
15
+
16
+ ```bash
17
+ pip install icon2i
18
+ ```
19
+
20
+ ```python
21
+ from datetime import UTC, datetime, timedelta
22
+
23
+ from icon2i import MeteoHub, Run
24
+
25
+ async with MeteoHub() as hub:
26
+ file = await hub.newest() # the newest TOT_PREC, about 80 MB, downloaded once
27
+
28
+ run = Run(file)
29
+ run.start, run.last # 2026-12-02 12:00 UTC, 2026-12-05 12:00 UTC
30
+
31
+ hour = run.rain(run.start + timedelta(hours=9)) # the rain of 20:00-21:00 UTC, a grid in mm
32
+ hour.sample([(15.29, 37.08)]) # [0.8] Siracusa
33
+
34
+ run.hourly([(15.29, 37.08)], run.start, run.start + timedelta(hours=24))
35
+ # {13:00: [0.0], 14:00: [0.0], ..., 21:00: [0.8], ...}: hour by hour, mm, per point
36
+ ```
37
+
38
+ From the shell:
39
+
40
+ ```bash
41
+ icon2i runs # the runs MeteoHub keeps, the newest first
42
+ icon2i fetch # download the newest run, print where it is
43
+ icon2i rain 15.29 37.08 # the rain of every hour of the newest run there, as CSV
44
+ ```
45
+
46
+ ## What it reads
47
+
48
+ MeteoHub keeps the runs of the last few days, one folder each
49
+ (`2026120212/`), and in it one folder a variable with one GRIB2 file holding
50
+ every hour of the run. The library reads `TOT_PREC`: the precipitation since
51
+ the start of the run, in kg/m², which is mm. The rain of a window is the
52
+ difference of two totals:
53
+
54
+ | Call | Gives |
55
+ |---|---|
56
+ | `MeteoHub().runs()` | the runs MeteoHub keeps, newest first |
57
+ | `MeteoHub().fetch(run)` / `.newest()` | the file of a run on disk, downloaded if missing / of the newest run that has it, keeping two |
58
+ | `Run(file).rain(end, window=1 h)` | the rain of `(end - window, end]`, a `Field` in mm |
59
+ | `Run(file).total(time)` | the precipitation from the start of the run to `time` |
60
+ | `Run(file).fields(start, end)` | the rain of every hour in `(start, end]` |
61
+ | `Run(file).hourly(points, start, end)` | the same at lon/lat points: `{hour: [mm or None, ...]}` |
62
+ | `Field.sample(points)` | a field at points: the pixel each falls in |
63
+
64
+ `Run.hourly` has the signature of `dpc_radar`'s readers
65
+ (`MergingArchive.hourly(points, start, end)`): the radar for the hours gone,
66
+ the model for the hours to come, the same shape.
67
+
68
+ The file is read with [rasterio](https://rasterio.readthedocs.io/) (the GRIB
69
+ driver of GDAL), so no eccodes to install. The time of each band comes from
70
+ the file itself (`GRIB_REF_TIME`, `GRIB_VALID_TIME`).
71
+
72
+ ## What it does not do
73
+
74
+ - **It is a forecast, not a measure.** For the rain that fell, a radar
75
+ ([dpc-radar](https://github.com/agent-engineering-studio/dpc-radar)) or a
76
+ rain gauge ([regional-raingauges](https://github.com/agent-engineering-studio/regional-raingauges)).
77
+ - **It is not an alert.** The official alert in Italy is the criticality
78
+ bulletin of the Dipartimento della Protezione Civile and of the Regions.
79
+ - **`None` is "the run does not say"**: a time before its start or after its
80
+ last hour, a point outside its grid. Never zero, which is "no rain".
81
+ - **It does not read the clock.** "The newest run" is the newest MeteoHub
82
+ lists; "from now" is the caller's.
83
+ - **It reads one variable today**, `TOT_PREC`. `MeteoHub.fetch(run, "T_2M")`
84
+ downloads any other, but `Run` only knows precipitation.
85
+
86
+ ## Where the files go
87
+
88
+ `MeteoHub.fetch` and `newest` write to the folder you pass, else
89
+ `$ICON2I_DATA_DIR`, else `$DATA_ROOT/icon2i` (the root shared with
90
+ [Limen](https://github.com/agent-engineering-studio/limen) and the other
91
+ libraries), else `./data/icon2i`: the rule of
92
+ [limen-common](https://github.com/agent-engineering-studio/limen-common). A
93
+ file is written through a temporary one and a rename: a crash never leaves
94
+ half a file. `newest` keeps the last two runs.
95
+
96
+ ## Credit and licence
97
+
98
+ The data: **Agenzia ItaliaMeteo, ICON-2I, CC BY 4.0** (`icon2i.CREDIT`).
99
+ Credit it wherever they are shown. The code: Apache-2.0.
100
+
101
+ ## Develop
102
+
103
+ ```bash
104
+ make check # ruff, mypy --strict, pytest: the gate CI runs
105
+ uv run pytest -m live # also the test against the real MeteoHub (downloads ~80 MB)
106
+ ```
107
+
108
+ See [CONTRIBUTING.md](CONTRIBUTING.md) and the [CHANGELOG](CHANGELOG.md).
@@ -0,0 +1,122 @@
1
+ [project]
2
+ name = "icon2i"
3
+ version = "0.1.0"
4
+ description = "The rain of the next hours over Italy from ICON-2I, the weather model of the Agenzia ItaliaMeteo, read from its open data on MeteoHub"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ keywords = [
10
+ "icon-2i",
11
+ "weather model",
12
+ "precipitation",
13
+ "forecast",
14
+ "open data",
15
+ "italy",
16
+ "italiameteo",
17
+ "meteohub",
18
+ "grib",
19
+ ]
20
+ classifiers = [
21
+ "Development Status :: 3 - Alpha",
22
+ "Intended Audience :: Science/Research",
23
+ "Operating System :: OS Independent",
24
+ "Programming Language :: Python :: 3",
25
+ "Programming Language :: Python :: 3.12",
26
+ "Programming Language :: Python :: 3.13",
27
+ "Topic :: Scientific/Engineering :: Atmospheric Science",
28
+ "Typing :: Typed",
29
+ ]
30
+ dependencies = [
31
+ "httpx>=0.27",
32
+ "limen-common[http]>=0.1.1",
33
+ "numpy>=2.0",
34
+ "rasterio>=1.4",
35
+ ]
36
+
37
+ [[project.authors]]
38
+ name = "Giuseppe Zileni"
39
+ email = "giuseppe.zileni@gmail.com"
40
+
41
+ [project.scripts]
42
+ icon2i = "icon2i.cli:main"
43
+
44
+ [project.urls]
45
+ Homepage = "https://github.com/agent-engineering-studio/icon2i"
46
+ Issues = "https://github.com/agent-engineering-studio/icon2i/issues"
47
+ Documentation = "https://agentengineering.it/icon2i/"
48
+ Changelog = "https://github.com/agent-engineering-studio/icon2i/blob/main/CHANGELOG.md"
49
+
50
+ [build-system]
51
+ requires = ["uv_build>=0.13.6,<0.14"]
52
+ build-backend = "uv_build"
53
+
54
+ [dependency-groups]
55
+ dev = [
56
+ "mypy>=1.13",
57
+ "pytest>=8.3",
58
+ "pytest-asyncio>=0.24",
59
+ "pytest-cov>=6.0",
60
+ "ruff>=0.8",
61
+ ]
62
+ docs = [
63
+ "zensical>=0.1.0",
64
+ "mkdocstrings[python]>=0.26",
65
+ ]
66
+
67
+ [tool.ruff]
68
+ line-length = 100
69
+ target-version = "py312"
70
+
71
+ [tool.ruff.lint]
72
+ select = [
73
+ "E",
74
+ "F",
75
+ "W",
76
+ "I",
77
+ "N",
78
+ "UP",
79
+ "B",
80
+ "C4",
81
+ "SIM",
82
+ "ARG",
83
+ "PTH",
84
+ "RUF",
85
+ ]
86
+
87
+ [tool.ruff.lint.per-file-ignores]
88
+ "tests/**" = [
89
+ "ARG",
90
+ "B018",
91
+ ]
92
+
93
+ [tool.mypy]
94
+ strict = true
95
+ python_version = "3.12"
96
+ files = [
97
+ "src",
98
+ "tests",
99
+ ]
100
+ warn_unused_ignores = true
101
+ warn_redundant_casts = true
102
+
103
+ [[tool.mypy.overrides]]
104
+ module = [
105
+ "rasterio.*",
106
+ "affine.*",
107
+ ]
108
+ ignore_missing_imports = true
109
+
110
+ [tool.pytest.ini_options]
111
+ testpaths = ["tests"]
112
+ addopts = "--strict-markers -m 'not live'"
113
+ asyncio_mode = "auto"
114
+ asyncio_default_fixture_loop_scope = "function"
115
+ markers = ["live: calls the real MeteoHub (run with -m live)"]
116
+
117
+ [tool.coverage.run]
118
+ source = ["icon2i"]
119
+
120
+ [tool.coverage.report]
121
+ fail_under = 90
122
+ show_missing = true
@@ -0,0 +1,89 @@
1
+ [project]
2
+ name = "icon2i"
3
+ version = "0.1.0"
4
+ description = "The rain of the next hours over Italy from ICON-2I, the weather model of the Agenzia ItaliaMeteo, read from its open data on MeteoHub"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = "Apache-2.0"
8
+ license-files = ["LICENSE"]
9
+ authors = [
10
+ { name = "Giuseppe Zileni", email = "giuseppe.zileni@gmail.com" },
11
+ ]
12
+ keywords = ["icon-2i", "weather model", "precipitation", "forecast", "open data", "italy", "italiameteo", "meteohub", "grib"]
13
+ classifiers = [
14
+ "Development Status :: 3 - Alpha",
15
+ "Intended Audience :: Science/Research",
16
+ "Operating System :: OS Independent",
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.12",
19
+ "Programming Language :: Python :: 3.13",
20
+ "Topic :: Scientific/Engineering :: Atmospheric Science",
21
+ "Typing :: Typed",
22
+ ]
23
+ dependencies = [
24
+ "httpx>=0.27",
25
+ "limen-common[http]>=0.1.1",
26
+ "numpy>=2.0",
27
+ "rasterio>=1.4",
28
+ ]
29
+
30
+ [project.scripts]
31
+ icon2i = "icon2i.cli:main"
32
+
33
+ [project.urls]
34
+ Homepage = "https://github.com/agent-engineering-studio/icon2i"
35
+ Issues = "https://github.com/agent-engineering-studio/icon2i/issues"
36
+ Documentation = "https://agentengineering.it/icon2i/"
37
+ Changelog = "https://github.com/agent-engineering-studio/icon2i/blob/main/CHANGELOG.md"
38
+
39
+ [build-system]
40
+ requires = ["uv_build>=0.13.6,<0.14"]
41
+ build-backend = "uv_build"
42
+
43
+ [dependency-groups]
44
+ dev = [
45
+ "mypy>=1.13",
46
+ "pytest>=8.3",
47
+ "pytest-asyncio>=0.24",
48
+ "pytest-cov>=6.0",
49
+ "ruff>=0.8",
50
+ ]
51
+ docs = [
52
+ "zensical>=0.1.0",
53
+ "mkdocstrings[python]>=0.26",
54
+ ]
55
+
56
+ [tool.ruff]
57
+ line-length = 100
58
+ target-version = "py312"
59
+
60
+ [tool.ruff.lint]
61
+ select = ["E", "F", "W", "I", "N", "UP", "B", "C4", "SIM", "ARG", "PTH", "RUF"]
62
+
63
+ [tool.ruff.lint.per-file-ignores]
64
+ "tests/**" = ["ARG", "B018"]
65
+
66
+ [tool.mypy]
67
+ strict = true
68
+ python_version = "3.12"
69
+ files = ["src", "tests"]
70
+ warn_unused_ignores = true
71
+ warn_redundant_casts = true
72
+
73
+ [[tool.mypy.overrides]]
74
+ module = ["rasterio.*", "affine.*"]
75
+ ignore_missing_imports = true
76
+
77
+ [tool.pytest.ini_options]
78
+ testpaths = ["tests"]
79
+ addopts = "--strict-markers -m 'not live'"
80
+ asyncio_mode = "auto"
81
+ asyncio_default_fixture_loop_scope = "function"
82
+ markers = ["live: calls the real MeteoHub (run with -m live)"]
83
+
84
+ [tool.coverage.run]
85
+ source = ["icon2i"]
86
+
87
+ [tool.coverage.report]
88
+ fail_under = 90
89
+ show_missing = true
@@ -0,0 +1,33 @@
1
+ """icon2i: the rain of the next hours over Italy from ICON-2I, the model of the Agenzia ItaliaMeteo.
2
+
3
+ ICON-2I is the national weather model: 2.2 km over Italy, run at 00 and 12
4
+ UTC, 72 hours ahead. Its runs are open data on MeteoHub (CC BY 4.0, no key).
5
+ This library downloads them (:class:`MeteoHub`) and reads the rain of their
6
+ hours, as grids or at points (:class:`Run`). It is a forecast, not a
7
+ measure: for the rain that fell, a radar or a rain gauge.
8
+ """
9
+
10
+ from importlib.metadata import PackageNotFoundError, version
11
+
12
+ from icon2i.errors import Icon2iError
13
+ from icon2i.local import default_directory
14
+ from icon2i.meteohub import BASE, CREDIT, TOT_PREC, MeteoHub
15
+ from icon2i.run import HOUR, Field, Run
16
+
17
+ try:
18
+ __version__ = version("icon2i")
19
+ except PackageNotFoundError: # pragma: no cover - a source checkout without metadata
20
+ __version__ = "0.0.0"
21
+
22
+ __all__ = [
23
+ "BASE",
24
+ "CREDIT",
25
+ "HOUR",
26
+ "TOT_PREC",
27
+ "Field",
28
+ "Icon2iError",
29
+ "MeteoHub",
30
+ "Run",
31
+ "__version__",
32
+ "default_directory",
33
+ ]
@@ -0,0 +1,86 @@
1
+ """The command line: ``icon2i runs``, ``icon2i fetch``, ``icon2i rain LON LAT``.
2
+
3
+ icon2i runs the runs MeteoHub keeps, the newest first
4
+ icon2i fetch [--folder DIR] download the newest TOT_PREC, print its path
5
+ icon2i rain 15.29 37.08 the rain of every hour of the newest run there, as CSV
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import asyncio
12
+ import csv
13
+ import sys
14
+ from collections.abc import Sequence
15
+ from datetime import datetime
16
+ from pathlib import Path
17
+
18
+ import httpx
19
+
20
+ from icon2i.errors import Icon2iError
21
+ from icon2i.meteohub import CREDIT, MeteoHub
22
+ from icon2i.run import HOUR, Run
23
+
24
+
25
+ def _time(text: str) -> datetime:
26
+ value = datetime.fromisoformat(text)
27
+ if value.tzinfo is None:
28
+ raise argparse.ArgumentTypeError("a time with its zone, such as 2026-12-02T18:00Z")
29
+ return value
30
+
31
+
32
+ def _parser() -> argparse.ArgumentParser:
33
+ parser = argparse.ArgumentParser(prog="icon2i", description=__doc__.splitlines()[0])
34
+ sub = parser.add_subparsers(dest="command", required=True)
35
+ sub.add_parser("runs", help="the runs MeteoHub keeps, the newest first")
36
+ fetch = sub.add_parser("fetch", help="download the newest TOT_PREC and print its path")
37
+ fetch.add_argument("--folder", type=Path, help="where to keep it (default: the library's)")
38
+ rain = sub.add_parser("rain", help="the rain of every hour at a point, as CSV")
39
+ rain.add_argument("lon", type=float)
40
+ rain.add_argument("lat", type=float)
41
+ rain.add_argument("--file", type=Path, help="a TOT_PREC file; default: the newest run")
42
+ rain.add_argument("--folder", type=Path, help="where to keep the newest run")
43
+ rain.add_argument("--start", type=_time, help="from this time (default: the start of the run)")
44
+ rain.add_argument("--hours", type=int, default=72, help="how many hours (default 72)")
45
+ return parser
46
+
47
+
48
+ async def _newest(folder: Path | None) -> Path:
49
+ async with MeteoHub() as hub:
50
+ found = await hub.newest(folder=folder)
51
+ if found is None:
52
+ raise Icon2iError("MeteoHub lists no run with TOT_PREC right now")
53
+ return found
54
+
55
+
56
+ async def _run(args: argparse.Namespace) -> int:
57
+ if args.command == "runs":
58
+ async with MeteoHub() as hub:
59
+ for one in await hub.runs():
60
+ print(f"{one:%Y-%m-%dT%H:%MZ}")
61
+ return 0
62
+ if args.command == "fetch":
63
+ print(await _newest(args.folder))
64
+ return 0
65
+ run = Run(args.file if args.file else await _newest(args.folder))
66
+ start = args.start or run.start
67
+ rows = run.hourly([(args.lon, args.lat)], start, start + HOUR * args.hours)
68
+ out = csv.writer(sys.stdout)
69
+ out.writerow(["time", "rain_mm"])
70
+ for time, (mm,) in rows.items():
71
+ out.writerow([f"{time:%Y-%m-%dT%H:%MZ}", "" if mm is None else f"{mm:.2f}"])
72
+ print(f"# run {run.start:%Y-%m-%dT%H}Z · {CREDIT}", file=sys.stderr)
73
+ return 0
74
+
75
+
76
+ def main(argv: Sequence[str] | None = None) -> int:
77
+ args = _parser().parse_args(argv)
78
+ try:
79
+ return asyncio.run(_run(args))
80
+ except (Icon2iError, httpx.HTTPError) as exc:
81
+ print(f"icon2i: {exc}", file=sys.stderr)
82
+ return 1
83
+
84
+
85
+ if __name__ == "__main__": # pragma: no cover
86
+ sys.exit(main())
@@ -0,0 +1,10 @@
1
+ """The one error of the library."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class Icon2iError(Exception):
7
+ """Something the library cannot answer: a run without the file, a file it cannot read."""
8
+
9
+
10
+ __all__ = ["Icon2iError"]
@@ -0,0 +1,24 @@
1
+ """Where the library keeps the files it downloads.
2
+
3
+ The rule of the Limen libraries (:func:`limen_common.data_dir`): the folder the
4
+ caller passes; else ``$ICON2I_DATA_DIR``; else ``$DATA_ROOT/icon2i``, the root
5
+ shared with Limen and the other libraries; else ``./data/icon2i``. Nothing is
6
+ created until a file is written.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ from pathlib import Path
12
+ from typing import Final
13
+
14
+ from limen_common import data_dir
15
+
16
+ PACKAGE: Final = "icon2i"
17
+
18
+
19
+ def default_directory(directory: Path | None = None) -> Path:
20
+ """The library's folder: see the module."""
21
+ return data_dir(PACKAGE, directory).expanduser()
22
+
23
+
24
+ __all__ = ["PACKAGE", "default_directory"]
@@ -0,0 +1,177 @@
1
+ """MeteoHub, where the Agenzia ItaliaMeteo publishes the runs of ICON-2I as open data.
2
+
3
+ The runs are folders ``YYYYMMDDHH`` under :data:`BASE`, one a run (00 and 12
4
+ UTC), each with one folder a variable holding one GRIB2 file with every hour of
5
+ the run. No key, no account: the data are CC BY 4.0, credit
6
+ "Agenzia ItaliaMeteo". MeteoHub keeps the runs of the last few days.
7
+
8
+ :class:`MeteoHub` lists the runs, lists the files of a variable and downloads
9
+ them, with the retry policy of the Limen libraries
10
+ (:func:`limen_common.http.send`). It does not read the clock: "the newest run"
11
+ is the newest one MeteoHub lists.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from datetime import UTC, datetime
18
+ from pathlib import Path
19
+ from types import TracebackType
20
+ from typing import Final
21
+
22
+ import httpx
23
+ from limen_common import atomic_write
24
+ from limen_common.http import RetryPolicy, send
25
+
26
+ from icon2i.errors import Icon2iError
27
+ from icon2i.local import default_directory
28
+
29
+ #: The open data of ICON-2I on MeteoHub: surface fields and pressure levels.
30
+ BASE: Final = "https://meteohub.agenziaitaliameteo.it/nwp/ICON-2I_SURFACE_PRESSURE_LEVELS"
31
+ #: The precipitation since the start of the run, in kg/m² (mm).
32
+ TOT_PREC: Final = "TOT_PREC"
33
+ #: Who to credit wherever the data are shown.
34
+ CREDIT: Final = "Agenzia ItaliaMeteo, ICON-2I, CC BY 4.0"
35
+
36
+ _RUN = re.compile(r'href="(\d{10})/"')
37
+ _GRIB = re.compile(r'href="([^"/]+\.grib2?)"')
38
+ _VARIABLE = re.compile(r"^[A-Z0-9_]+$")
39
+
40
+
41
+ def run_name(run: datetime) -> str:
42
+ """The folder of a run: ``2026120212``."""
43
+ return f"{run.astimezone(UTC):%Y%m%d%H}"
44
+
45
+
46
+ def parse_runs(html: str) -> list[datetime]:
47
+ """The runs in a MeteoHub folder listing, the newest first."""
48
+ found = {datetime.strptime(m, "%Y%m%d%H").replace(tzinfo=UTC) for m in _RUN.findall(html)}
49
+ return sorted(found, reverse=True)
50
+
51
+
52
+ def parse_files(html: str) -> list[str]:
53
+ """The GRIB files in a MeteoHub folder listing, in the order listed."""
54
+ return list(dict.fromkeys(_GRIB.findall(html)))
55
+
56
+
57
+ def file_name(run: datetime, variable: str) -> str:
58
+ """Where :meth:`MeteoHub.fetch` keeps a variable of a run: ``TOT_PREC_2026120212.grib``."""
59
+ return f"{variable}_{run_name(run)}.grib"
60
+
61
+
62
+ class MeteoHub:
63
+ """The ICON-2I open data on MeteoHub.
64
+
65
+ Give it your ``httpx.AsyncClient`` and timeouts and proxies stay yours;
66
+ give it none and it opens (and closes) its own.
67
+ """
68
+
69
+ def __init__(
70
+ self,
71
+ client: httpx.AsyncClient | None = None,
72
+ *,
73
+ base: str = BASE,
74
+ policy: RetryPolicy | None = None,
75
+ timeout_s: float = 600.0,
76
+ ) -> None:
77
+ self._own = client is None
78
+ self._client = client or httpx.AsyncClient(follow_redirects=True)
79
+ self._base = base.rstrip("/")
80
+ self._policy = policy or RetryPolicy()
81
+ self._timeout_s = timeout_s
82
+
83
+ async def __aenter__(self) -> MeteoHub:
84
+ return self
85
+
86
+ async def __aexit__(
87
+ self,
88
+ exc_type: type[BaseException] | None,
89
+ exc: BaseException | None,
90
+ tb: TracebackType | None,
91
+ ) -> None:
92
+ await self.aclose()
93
+
94
+ async def aclose(self) -> None:
95
+ """Close the HTTP client if this instance opened it."""
96
+ if self._own:
97
+ await self._client.aclose()
98
+
99
+ async def _get(self, url: str, timeout: float = 30.0) -> httpx.Response:
100
+ response = await send(self._client, "GET", url, policy=self._policy, timeout=timeout)
101
+ response.raise_for_status()
102
+ return response
103
+
104
+ async def runs(self) -> list[datetime]:
105
+ """The runs MeteoHub keeps, the newest first."""
106
+ return parse_runs((await self._get(f"{self._base}/")).text)
107
+
108
+ def url(self, run: datetime, variable: str = TOT_PREC) -> str:
109
+ """The folder of a variable of a run."""
110
+ if not _VARIABLE.match(variable):
111
+ raise Icon2iError(f"a variable is a short name such as TOT_PREC, not {variable!r}")
112
+ return f"{self._base}/{run_name(run)}/{variable}/"
113
+
114
+ async def files(self, run: datetime, variable: str = TOT_PREC) -> list[str]:
115
+ """The GRIB files of a variable of a run; empty while the run is being written."""
116
+ try:
117
+ listing = await self._get(self.url(run, variable))
118
+ except httpx.HTTPStatusError as exc:
119
+ if exc.response.status_code == 404:
120
+ return []
121
+ raise
122
+ return parse_files(listing.text)
123
+
124
+ async def download(self, run: datetime, variable: str = TOT_PREC) -> bytes:
125
+ """The GRIB file of a variable of a run, as published.
126
+
127
+ :class:`Icon2iError` if the run has no file for it (yet).
128
+ """
129
+ names = await self.files(run, variable)
130
+ if not names:
131
+ raise Icon2iError(f"MeteoHub has no {variable} for the run {run_name(run)} (yet)")
132
+ response = await self._get(self.url(run, variable) + names[0], timeout=self._timeout_s)
133
+ return response.content
134
+
135
+ async def fetch(
136
+ self, run: datetime, variable: str = TOT_PREC, *, folder: Path | None = None
137
+ ) -> Path:
138
+ """The file of a variable of a run on disk, downloaded if it is not there yet.
139
+
140
+ Written through a temporary file and a rename: a crash never leaves
141
+ half a file. ``folder`` defaults to the library's
142
+ (:func:`icon2i.local.default_directory`).
143
+ """
144
+ target = (folder if folder is not None else default_directory()) / file_name(run, variable)
145
+ if not target.exists():
146
+ atomic_write(target, await self.download(run, variable))
147
+ return target
148
+
149
+ async def newest(
150
+ self, variable: str = TOT_PREC, *, folder: Path | None = None, keep: int = 2
151
+ ) -> Path | None:
152
+ """The newest run that has the variable, on disk; the older files beyond ``keep`` go.
153
+
154
+ A run still being written is skipped for the one before. ``None`` if
155
+ no run listed has the file.
156
+ """
157
+ where = folder if folder is not None else default_directory()
158
+ for run in await self.runs():
159
+ if not await self.files(run, variable):
160
+ continue
161
+ found = await self.fetch(run, variable, folder=where)
162
+ for old in sorted(where.glob(f"{variable}_*.grib"), reverse=True)[max(keep, 1) :]:
163
+ old.unlink(missing_ok=True)
164
+ return found
165
+ return None
166
+
167
+
168
+ __all__ = [
169
+ "BASE",
170
+ "CREDIT",
171
+ "TOT_PREC",
172
+ "MeteoHub",
173
+ "file_name",
174
+ "parse_files",
175
+ "parse_runs",
176
+ "run_name",
177
+ ]
File without changes
@@ -0,0 +1,193 @@
1
+ """One run of ICON-2I on disk: the rain of its hours, as grids and at points.
2
+
3
+ The ``TOT_PREC`` file of a run holds, one band an hour, the precipitation
4
+ since the start of the run (kg/m², which is mm), from the start (0) to the
5
+ last hour (72 for ICON-2I). The rain of a window is the difference of two of
6
+ its totals: :meth:`Run.rain` for one window, :meth:`Run.fields` for every hour
7
+ of a span, :meth:`Run.hourly` for the same at points, with the signature of
8
+ ``dpc_radar``'s readers (``hourly(points, start, end)``) so the two can be
9
+ swapped.
10
+
11
+ The file is read with rasterio, the GRIB driver of GDAL: no eccodes. The time
12
+ of each band is read from the file (``GRIB_REF_TIME``, ``GRIB_VALID_TIME``);
13
+ a file without them is read as one band an hour from the run in its name.
14
+
15
+ ``None`` means "the run does not say": a time before its start or after its
16
+ last hour, a point outside its grid. Never zero, which is "no rain".
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import math
22
+ import re
23
+ from dataclasses import dataclass
24
+ from datetime import UTC, datetime, timedelta
25
+ from pathlib import Path
26
+ from typing import Any, Final
27
+
28
+ import numpy as np
29
+ import rasterio
30
+ import rasterio.errors
31
+ from affine import Affine
32
+ from rasterio.warp import transform as warp_points
33
+
34
+ from icon2i.errors import Icon2iError
35
+
36
+ HOUR: Final = timedelta(hours=1)
37
+ _STAMP = re.compile(r"(\d{10})")
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Field:
42
+ """Rain on the grid of the model, in mm.
43
+
44
+ ``window`` is the span it fell in, ending at ``time``; ``None`` for the
45
+ total since the start of the run. ``NaN`` is "not known".
46
+ """
47
+
48
+ start: datetime
49
+ time: datetime
50
+ window: timedelta | None
51
+ data: np.ndarray
52
+ transform: Affine
53
+ crs: Any
54
+
55
+ @property
56
+ def lead(self) -> timedelta:
57
+ """How long after the start of the run ``time`` is."""
58
+ return self.time - self.start
59
+
60
+ def sample(self, points: list[tuple[float, float]]) -> list[float | None]:
61
+ """The value at each lon/lat point: the pixel it falls in; ``None`` outside the grid."""
62
+ return _sample(self.data, self.transform, self.crs, points)
63
+
64
+
65
+ def _sample(
66
+ data: np.ndarray, transform: Affine, crs: Any, points: list[tuple[float, float]]
67
+ ) -> list[float | None]:
68
+ if not points:
69
+ return []
70
+ lons, lats = [p[0] for p in points], [p[1] for p in points]
71
+ if crs is not None and not crs.is_geographic:
72
+ lons, lats = warp_points("EPSG:4326", crs, lons, lats)
73
+ inv = ~transform
74
+ out: list[float | None] = []
75
+ for x, y in zip(lons, lats, strict=True):
76
+ col, row = inv.a * x + inv.b * y + inv.c, inv.d * x + inv.e * y + inv.f
77
+ r, c = math.floor(row), math.floor(col)
78
+ if not (0 <= r < data.shape[0] and 0 <= c < data.shape[1]):
79
+ out.append(None)
80
+ continue
81
+ value = float(data[r, c])
82
+ out.append(None if math.isnan(value) else value)
83
+ return out
84
+
85
+
86
+ def _epoch(value: str | None) -> datetime | None:
87
+ if value is None:
88
+ return None
89
+ try:
90
+ return datetime.fromtimestamp(int(value.split()[0]), UTC)
91
+ except (ValueError, IndexError):
92
+ return None
93
+
94
+
95
+ class Run:
96
+ """The ``TOT_PREC`` file of one run, read band by band when asked."""
97
+
98
+ def __init__(self, path: Path) -> None:
99
+ self.path = Path(path)
100
+ try:
101
+ with rasterio.open(self.path) as src:
102
+ tags = [src.tags(b) for b in range(1, src.count + 1)]
103
+ self.transform: Affine = src.transform
104
+ self.crs: Any = src.crs
105
+ self.shape: tuple[int, int] = (src.height, src.width)
106
+ except rasterio.errors.RasterioError as exc:
107
+ raise Icon2iError(f"{self.path.name} is not a readable GRIB file: {exc}") from exc
108
+ if not tags:
109
+ raise Icon2iError(f"{self.path.name} holds no band")
110
+ start = _epoch(tags[0].get("GRIB_REF_TIME"))
111
+ valid = [_epoch(t.get("GRIB_VALID_TIME")) for t in tags]
112
+ if start is None or any(v is None for v in valid):
113
+ start = _start_from_name(self.path)
114
+ valid = [start + HOUR * k for k in range(len(tags))]
115
+ #: The start of the run.
116
+ self.start: datetime = start
117
+ #: The time of each band, in order: the total since the start, at that time.
118
+ self.times: list[datetime] = [v for v in valid if v is not None]
119
+ self._band = {t: k + 1 for k, t in enumerate(self.times)}
120
+
121
+ def __repr__(self) -> str:
122
+ return f"Run({self.start:%Y-%m-%dT%H}Z, {len(self.times)} hours, {self.path.name})"
123
+
124
+ @property
125
+ def last(self) -> datetime:
126
+ """The last time the run reaches."""
127
+ return self.times[-1]
128
+
129
+ def _total(self, time: datetime) -> np.ndarray | None:
130
+ band = self._band.get(time)
131
+ if band is None:
132
+ return None
133
+ with rasterio.open(self.path) as src:
134
+ data: np.ndarray = src.read(band).astype("float32")
135
+ nodata = src.nodatavals[band - 1]
136
+ if nodata is not None:
137
+ data[data == nodata] = np.nan
138
+ return data
139
+
140
+ def total(self, time: datetime) -> Field | None:
141
+ """The precipitation from the start of the run to ``time``; ``None`` if not a band of it."""
142
+ data = self._total(time)
143
+ if data is None:
144
+ return None
145
+ return Field(self.start, time, None, data, self.transform, self.crs)
146
+
147
+ def rain(self, end: datetime, window: timedelta = HOUR) -> Field | None:
148
+ """The rain of ``(end - window, end]``.
149
+
150
+ ``None`` if the run does not hold both ends: before its start, after
151
+ its last hour, or not on a band (whole hours). A total that went down
152
+ by rounding is read as zero, not as negative rain.
153
+ """
154
+ if window <= timedelta(0):
155
+ raise Icon2iError(f"a window is longer than zero, not {window}")
156
+ after, before = self._total(end), self._total(end - window)
157
+ if after is None or before is None:
158
+ return None
159
+ data = np.clip(after - before, 0.0, None)
160
+ return Field(self.start, end, window, data, self.transform, self.crs)
161
+
162
+ def hours(self, start: datetime, end: datetime) -> list[datetime]:
163
+ """The ends of the hours ``(h-1, h]`` in ``(start, end]`` that the run holds."""
164
+ return [t for t in self.times[1:] if start < t <= end]
165
+
166
+ def fields(self, start: datetime, end: datetime) -> list[Field]:
167
+ """The rain of every hour ``(h-1, h]`` in ``(start, end]``, oldest first."""
168
+ out = []
169
+ for hour in self.hours(start, end):
170
+ field = self.rain(hour)
171
+ if field is not None:
172
+ out.append(field)
173
+ return out
174
+
175
+ def hourly(
176
+ self, points: list[tuple[float, float]], start: datetime, end: datetime
177
+ ) -> dict[datetime, list[float | None]]:
178
+ """Rain of every hour ``(h-1, h]`` in ``(start, end]``, per lon/lat point (mm).
179
+
180
+ The same signature as ``dpc_radar``'s ``MergingArchive.hourly``: the
181
+ radar for the hours gone, the model for the hours to come.
182
+ """
183
+ return {f.time: f.sample(points) for f in self.fields(start, end)}
184
+
185
+
186
+ def _start_from_name(path: Path) -> datetime:
187
+ found = _STAMP.search(path.name)
188
+ if found is None:
189
+ raise Icon2iError(f"{path.name}: no run time in the file nor in its name (YYYYMMDDHH)")
190
+ return datetime.strptime(found.group(1), "%Y%m%d%H").replace(tzinfo=UTC)
191
+
192
+
193
+ __all__ = ["HOUR", "Field", "Run"]