dpc-radar 0.1.0__py3-none-any.whl

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.
dpc_radar/__init__.py ADDED
@@ -0,0 +1,49 @@
1
+ """dpc-radar: the Italian Civil Protection (DPC) open radar data, from Python."""
2
+
3
+ from importlib.metadata import version
4
+
5
+ from dpc_radar.client import ABSENT, Absent, RadarClient
6
+ from dpc_radar.errors import DpcRadarError
7
+ from dpc_radar.grid import FrameCheck, RainGrid
8
+ from dpc_radar.products import (
9
+ API_BASE,
10
+ CUM3,
11
+ CUM6,
12
+ CUM12,
13
+ CUM24,
14
+ PRODUCTS,
15
+ SRI,
16
+ SRT1,
17
+ LastProduct,
18
+ Product,
19
+ is_expired,
20
+ parse_download,
21
+ parse_last_product,
22
+ product,
23
+ )
24
+
25
+ __version__ = version("dpc-radar")
26
+
27
+ __all__ = [
28
+ "ABSENT",
29
+ "API_BASE",
30
+ "CUM3",
31
+ "CUM6",
32
+ "CUM12",
33
+ "CUM24",
34
+ "PRODUCTS",
35
+ "SRI",
36
+ "SRT1",
37
+ "Absent",
38
+ "DpcRadarError",
39
+ "FrameCheck",
40
+ "LastProduct",
41
+ "Product",
42
+ "RadarClient",
43
+ "RainGrid",
44
+ "__version__",
45
+ "is_expired",
46
+ "parse_download",
47
+ "parse_last_product",
48
+ "product",
49
+ ]
dpc_radar/client.py ADDED
@@ -0,0 +1,181 @@
1
+ """An async client for the DPC radar API: the latest frame, or the frame at a time.
2
+
3
+ Give it your ``httpx.AsyncClient`` and timeouts, proxies and pooling stay
4
+ yours; give it none and it opens (and closes) its own. Network errors and
5
+ 429/5xx are retried ``retries`` times with exponential backoff, except the one
6
+ answer that must never be retried: a frame the DPC no longer keeps (a 500 with
7
+ S3's 403 in the body), which comes back as :data:`ABSENT`.
8
+
9
+ To route every request through your own HTTP layer (a shared retry policy, a
10
+ rate limiter, a cache), pass ``send``: an ``async (method, url, **kwargs) ->
11
+ httpx.Response``. The client then uses it for every call and does no retrying
12
+ of its own. The hook must *return* error responses rather than raise on them,
13
+ or the client cannot tell a frame that is gone from a failure.
14
+
15
+ The client keeps no state between calls: no cache, no logging. Holding on to
16
+ the last frame, and deciding what a failure means, is the caller's job.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import asyncio
22
+ from collections.abc import Awaitable, Callable
23
+ from datetime import datetime
24
+ from types import TracebackType
25
+ from typing import Any, Final, final
26
+
27
+ import httpx
28
+
29
+ from dpc_radar.errors import DpcRadarError
30
+ from dpc_radar.grid import RainGrid
31
+ from dpc_radar.products import (
32
+ API_BASE,
33
+ HEADERS,
34
+ LastProduct,
35
+ Product,
36
+ download_body,
37
+ download_url,
38
+ is_expired,
39
+ last_product_url,
40
+ parse_download,
41
+ parse_last_product,
42
+ product,
43
+ )
44
+
45
+ Send = Callable[..., Awaitable[httpx.Response]]
46
+ _RETRY_STATUS = frozenset({429, 500, 502, 503, 504})
47
+
48
+
49
+ @final
50
+ class Absent:
51
+ """A frame the DPC no longer keeps (older than about five months)."""
52
+
53
+ _instance: Absent | None = None
54
+
55
+ def __new__(cls) -> Absent:
56
+ if cls._instance is None:
57
+ cls._instance = super().__new__(cls)
58
+ return cls._instance
59
+
60
+ def __repr__(self) -> str:
61
+ return "ABSENT"
62
+
63
+ def __bool__(self) -> bool:
64
+ return False
65
+
66
+
67
+ #: The answer for a frame that is gone for good: never worth a retry.
68
+ ABSENT: Final = Absent()
69
+
70
+
71
+ class RadarClient:
72
+ """The open DPC radar API (``radar-api.protezionecivile.it``)."""
73
+
74
+ def __init__(
75
+ self,
76
+ client: httpx.AsyncClient | None = None,
77
+ *,
78
+ send: Send | None = None,
79
+ retries: int = 3,
80
+ backoff_s: float = 2.0,
81
+ timeout_s: float = 60.0,
82
+ base: str = API_BASE,
83
+ sleep: Callable[[float], Awaitable[Any]] = asyncio.sleep,
84
+ ) -> None:
85
+ self._own = client is None and send is None
86
+ self._client = client or (
87
+ None if send is not None else httpx.AsyncClient(follow_redirects=True)
88
+ )
89
+ self._send_hook = send
90
+ self._retries = retries
91
+ self._backoff_s = backoff_s
92
+ self._timeout_s = timeout_s
93
+ self._base = base.rstrip("/")
94
+ self._sleep = sleep
95
+
96
+ async def __aenter__(self) -> RadarClient:
97
+ return self
98
+
99
+ async def __aexit__(
100
+ self,
101
+ exc_type: type[BaseException] | None,
102
+ exc: BaseException | None,
103
+ tb: TracebackType | None,
104
+ ) -> None:
105
+ await self.aclose()
106
+
107
+ async def aclose(self) -> None:
108
+ """Close the HTTP client if this instance opened it."""
109
+ if self._own and self._client is not None:
110
+ await self._client.aclose()
111
+
112
+ async def last_product(self, name: str | Product) -> LastProduct | None:
113
+ """Time and period of the newest frame; ``None`` if the API lists none."""
114
+ url, params = last_product_url(name, base=self._base)
115
+ response = await self._send("GET", url, params=params, headers=HEADERS)
116
+ response.raise_for_status()
117
+ return parse_last_product(response.json())
118
+
119
+ async def latest(self, name: str | Product, *, cached: RainGrid | None = None) -> RainGrid:
120
+ """The newest frame of a product.
121
+
122
+ Pass the frame you already hold as ``cached``: if it is still the
123
+ newest, it comes back as is and nothing is downloaded (a CUM frame is
124
+ about 2 MB and changes every 30 minutes).
125
+ """
126
+ last = await self.last_product(name)
127
+ if last is None:
128
+ raise DpcRadarError(f"the API lists no frame of {product(name).name}")
129
+ if cached is not None and cached.product == last.product and cached.time == last.time:
130
+ return cached
131
+ grid = await self.at(last.product, last.time)
132
+ if isinstance(grid, Absent): # pragma: no cover - the newest frame is never gone
133
+ raise DpcRadarError(f"the newest {last.product.name} frame is not available")
134
+ return grid
135
+
136
+ async def at(self, name: str | Product, time: datetime) -> RainGrid | Absent:
137
+ """The frame of a product issued at ``time`` (aware), or :data:`ABSENT`."""
138
+ raw = await self.download(name, time)
139
+ if isinstance(raw, Absent):
140
+ return raw
141
+ return RainGrid.from_geotiff(raw, name, time)
142
+
143
+ async def download(self, name: str | Product, time: datetime) -> bytes | Absent:
144
+ """The GeoTIFF of a frame as published, or :data:`ABSENT` (to archive it as is)."""
145
+ response = await self._send(
146
+ "POST",
147
+ download_url(self._base),
148
+ json=download_body(name, time),
149
+ headers=HEADERS,
150
+ )
151
+ if response.status_code >= 400:
152
+ if is_expired(response.status_code, response.text):
153
+ return ABSENT
154
+ response.raise_for_status()
155
+ link = parse_download(response.json())
156
+ tiff = await self._send("GET", link, timeout=self._timeout_s)
157
+ tiff.raise_for_status()
158
+ return tiff.content
159
+
160
+ async def _send(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
161
+ if self._send_hook is not None:
162
+ return await self._send_hook(method, url, **kwargs)
163
+ assert self._client is not None
164
+ for attempt in range(self._retries + 1):
165
+ try:
166
+ response = await self._client.request(method, url, **kwargs)
167
+ except httpx.TransportError:
168
+ if attempt == self._retries:
169
+ raise
170
+ else:
171
+ if response.status_code not in _RETRY_STATUS:
172
+ return response
173
+ if is_expired(response.status_code, response.text):
174
+ return response # gone for good: retrying cannot help
175
+ if attempt == self._retries:
176
+ return response
177
+ await self._sleep(self._backoff_s * 2**attempt)
178
+ raise AssertionError("unreachable") # pragma: no cover
179
+
180
+
181
+ __all__ = ["ABSENT", "Absent", "RadarClient", "Send"]
dpc_radar/errors.py ADDED
@@ -0,0 +1,10 @@
1
+ """The one exception this package raises."""
2
+
3
+ from __future__ import annotations
4
+
5
+
6
+ class DpcRadarError(Exception):
7
+ """An answer of the DPC radar API that this package cannot read, or a bad argument."""
8
+
9
+
10
+ __all__ = ["DpcRadarError"]
dpc_radar/grid.py ADDED
@@ -0,0 +1,197 @@
1
+ """One radar frame as an array, and what to trust in it.
2
+
3
+ A :class:`RainGrid` is a DPC frame read from its GeoTIFF: rain in mm (CUM,
4
+ SRT1) or mm/h (SRI), ``NaN`` where the radar has no data. Two grids exist and
5
+ must not be mixed: SRI and SRT1 are 1 km in a Transverse Mercator projection,
6
+ the CUM products 0.01° in EPSG:4326. Every method takes lon/lat in degrees and
7
+ converts them to the grid's own projection.
8
+
9
+ Read a place with :meth:`RainGrid.sample`: the median of the 3x3 pixels around
10
+ it, never one pixel. Check a frame against the one before it with
11
+ :meth:`RainGrid.check` before trusting it: on 9-11 October 2026 and again from
12
+ 21 October to 3 November the DPC published every CUM24 frame at :30 with a
13
+ bell of up to 20,584 mm over Abruzzo, while the :00 frames were right.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass, replace
19
+ from datetime import datetime
20
+ from typing import Literal
21
+
22
+ import numpy as np
23
+ from affine import Affine
24
+ from rasterio.crs import CRS
25
+ from rasterio.io import MemoryFile
26
+ from rasterio.transform import rowcol
27
+ from rasterio.warp import transform as warp_points
28
+ from rasterio.warp import transform_bounds
29
+ from rasterio.windows import from_bounds
30
+
31
+ from dpc_radar.errors import DpcRadarError
32
+ from dpc_radar.products import NODATA, Product, product
33
+
34
+ BBox = tuple[float, float, float, float]
35
+ """west, south, east, north, in degrees (EPSG:4326)."""
36
+
37
+ Verdict = Literal["consistent", "pixels_masked", "previous_wrong", "rejected", "not_comparable"]
38
+
39
+
40
+ @dataclass(frozen=True, slots=True)
41
+ class RainGrid:
42
+ """One frame: ``data`` in mm or mm/h, ``NaN`` where there is no data."""
43
+
44
+ product: Product
45
+ time: datetime
46
+ data: np.ndarray
47
+ transform: Affine
48
+ crs: CRS
49
+
50
+ @classmethod
51
+ def from_geotiff(cls, raw: bytes, name: str | Product, time: datetime) -> RainGrid:
52
+ """A frame from the bytes of its GeoTIFF; ``-9999`` becomes ``NaN``."""
53
+ try:
54
+ with MemoryFile(raw) as mem, mem.open() as ds:
55
+ data = ds.read(1).astype("float64")
56
+ grid_transform, crs = ds.transform, ds.crs
57
+ except Exception as exc: # rasterio raises its own hierarchy
58
+ raise DpcRadarError(f"not a readable GeoTIFF: {exc}") from exc
59
+ data[data <= NODATA] = np.nan
60
+ return cls(product(name), time, data, grid_transform, crs)
61
+
62
+ def sample(self, points: list[tuple[float, float]]) -> list[float | None]:
63
+ """The value at each lon/lat point: the median of the valid 3x3 pixels.
64
+
65
+ The median and not the pixel, so that one wrong pixel never becomes a
66
+ flood on one cell. Outside the frame, or where the 3x3 window holds no
67
+ data, the answer is ``None``: not measured, which is not the same as
68
+ dry.
69
+ """
70
+ if not points:
71
+ return []
72
+ xs, ys = warp_points("EPSG:4326", self.crs, [p[0] for p in points], [p[1] for p in points])
73
+ rows, cols = rowcol(self.transform, xs, ys)
74
+ h, w = self.data.shape
75
+ out: list[float | None] = []
76
+ for r, c in zip(rows, cols, strict=True):
77
+ if not (0 <= r < h and 0 <= c < w):
78
+ out.append(None)
79
+ continue
80
+ tile = self.data[max(0, r - 1) : r + 2, max(0, c - 1) : c + 2]
81
+ valid = tile[np.isfinite(tile)]
82
+ out.append(float(np.median(valid)) if valid.size else None)
83
+ return out
84
+
85
+ def peak(self, bbox: BBox, *, threshold: float) -> tuple[float, int]:
86
+ """The highest value inside ``bbox``, and how many pixels reach ``threshold``.
87
+
88
+ ``(0.0, 0)`` outside the frame or where there is no data: Limen's radar
89
+ trigger asks "is it raining hard enough, on enough km², here?".
90
+ """
91
+ tile = self._window(bbox)
92
+ valid = tile[np.isfinite(tile)]
93
+ if valid.size == 0:
94
+ return 0.0, 0
95
+ return float(valid.max()), int((valid >= threshold).sum())
96
+
97
+ def crop(self, bbox: BBox) -> RainGrid:
98
+ """The part of the frame inside ``bbox`` (plus the pixel on each edge)."""
99
+ r0, r1, c0, c1 = self._bounds(bbox)
100
+ if r0 >= r1 or c0 >= c1:
101
+ raise DpcRadarError(f"bbox {bbox} is outside the frame")
102
+ data = self.data[r0:r1, c0:c1]
103
+ return replace(self, data=data, transform=self.transform @ Affine.translation(c0, r0))
104
+
105
+ def check(self, previous: RainGrid, *, max_step: float, min_pixels: int = 5) -> FrameCheck:
106
+ """Whether to trust this frame, given the one before it.
107
+
108
+ Two accumulations of the same length, one period apart, differ by the
109
+ rain that entered the window minus the rain that left it: never more
110
+ than one period of rain. Where they differ by more than ``max_step``,
111
+ one of the two is wrong, and the sign says which: every corruption
112
+ seen so far *adds* rain.
113
+
114
+ * no pixel jumps: ``consistent``, the frame as it is;
115
+ * fewer than ``min_pixels`` jump: ``pixels_masked``, those pixels set
116
+ to ``NaN``;
117
+ * more jump, and this frame is the higher: ``rejected``, use the
118
+ previous frame instead;
119
+ * more jump, and this frame is the lower: ``previous_wrong``, this frame
120
+ as it is (it is the previous one that was corrupted);
121
+ * different grids: ``not_comparable``, the frame as it is.
122
+
123
+ ``max_step`` is the caller's choice (Limen uses 150 mm for CUM
124
+ frames 30 minutes apart). Measured on the benchmark of known cases, this
125
+ rule passes 17 of 18 checks and, on 96 pairs of whole frames, rejects
126
+ the 44 corrupted ones and no clean one. It cannot see an artefact that
127
+ does not move between frames.
128
+ """
129
+ if previous.data.shape != self.data.shape or previous.transform != self.transform:
130
+ return FrameCheck("not_comparable", self, 0)
131
+ diff = self.data - previous.data # NaN where either has no data
132
+ bad = np.isfinite(diff) & (np.abs(diff) > max_step)
133
+ jumps = int(bad.sum())
134
+ if jumps == 0:
135
+ return FrameCheck("consistent", self, 0)
136
+ if jumps < min_pixels:
137
+ data = self.data.copy()
138
+ data[bad] = np.nan
139
+ return FrameCheck("pixels_masked", replace(self, data=data), jumps)
140
+ if float(np.median(diff[bad])) < 0:
141
+ return FrameCheck("previous_wrong", self, jumps)
142
+ return FrameCheck("rejected", None, jumps)
143
+
144
+ def discard_inconsistent(self, previous: RainGrid, *, max_step: float) -> tuple[RainGrid, int]:
145
+ """This frame without the pixels that moved more than ``max_step``.
146
+
147
+ Limen's rule from October 2026, kept for comparison: it cannot tell
148
+ which of the two frames is wrong, so it masks the pixels in both cases,
149
+ and it lets through the edges of a corrupted bell (jumps under
150
+ ``max_step``). Prefer :meth:`check`.
151
+ """
152
+ if previous.data.shape != self.data.shape or previous.transform != self.transform:
153
+ return self, 0
154
+ bad = np.isfinite(self.data) & np.isfinite(previous.data)
155
+ bad &= np.abs(self.data - previous.data) > max_step
156
+ n = int(bad.sum())
157
+ if n == 0:
158
+ return self, 0
159
+ data = self.data.copy()
160
+ data[bad] = np.nan
161
+ return replace(self, data=data), n
162
+
163
+ def _bounds(self, bbox: BBox) -> tuple[int, int, int, int]:
164
+ west, south, east, north = transform_bounds("EPSG:4326", self.crs, *bbox)
165
+ window = from_bounds(west, south, east, north, transform=self.transform)
166
+ r0 = max(0, int(window.row_off))
167
+ c0 = max(0, int(window.col_off))
168
+ r1 = min(self.data.shape[0], int(window.row_off + window.height) + 1)
169
+ c1 = min(self.data.shape[1], int(window.col_off + window.width) + 1)
170
+ return r0, r1, c0, c1
171
+
172
+ def _window(self, bbox: BBox) -> np.ndarray:
173
+ r0, r1, c0, c1 = self._bounds(bbox)
174
+ if r0 >= r1 or c0 >= c1:
175
+ return self.data[:0, :0]
176
+ return self.data[r0:r1, c0:c1]
177
+
178
+
179
+ @dataclass(frozen=True, slots=True)
180
+ class FrameCheck:
181
+ """The answer of :meth:`RainGrid.check`.
182
+
183
+ ``grid`` is the frame to use (with masked pixels for ``pixels_masked``),
184
+ or ``None`` when the frame is ``rejected``. ``jumps`` is how many pixels
185
+ moved more than ``max_step``.
186
+ """
187
+
188
+ verdict: Verdict
189
+ grid: RainGrid | None
190
+ jumps: int
191
+
192
+ @property
193
+ def usable(self) -> bool:
194
+ return self.grid is not None
195
+
196
+
197
+ __all__ = ["BBox", "FrameCheck", "RainGrid", "Verdict"]
dpc_radar/products.py ADDED
@@ -0,0 +1,189 @@
1
+ """The DPC radar products, and the requests and answers of the open radar API.
2
+
3
+ Pure: nothing here does I/O. A client sends the requests built here and hands
4
+ the answers back to the parsers.
5
+
6
+ The API (``radar-api.protezionecivile.it``) has two calls that matter:
7
+
8
+ * ``GET /findLastProductByType?type=<product>`` gives the time of the latest
9
+ frame and its period;
10
+ * ``POST /downloadProduct`` with ``{"productType", "productDate"}`` gives a
11
+ short-lived S3 link to the GeoTIFF of one frame.
12
+
13
+ A frame the DPC no longer keeps (about five months back) does not answer 404:
14
+ it answers **500** with S3's ``403 Forbidden`` in the body. :func:`is_expired`
15
+ tells the two failures apart, because an expired frame must not be retried.
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import re
21
+ from dataclasses import dataclass
22
+ from datetime import UTC, datetime, timedelta
23
+ from typing import Any, Final
24
+
25
+ from dpc_radar.errors import DpcRadarError
26
+
27
+ API_BASE: Final = "https://radar-api.protezionecivile.it"
28
+
29
+ #: Sent on every request. The API answered without it in November 2026, but the
30
+ #: DPC's own viewer sends it, and an API that starts checking it again would
31
+ #: otherwise fail every call.
32
+ HEADERS: Final = {"origin": "https://radar.protezionecivile.gov.it"}
33
+
34
+ #: Pixels with no data in every product.
35
+ NODATA: Final = -9999.0
36
+
37
+
38
+ @dataclass(frozen=True, slots=True)
39
+ class Product:
40
+ """One DPC radar product."""
41
+
42
+ name: str
43
+ #: Accumulation window: ``None`` for an intensity (SRI, mm/h).
44
+ hours: int | None
45
+ #: ``True`` for the «Merging» of radar and rain gauges, ``False`` for radar only.
46
+ merging: bool
47
+ description: str
48
+
49
+ @property
50
+ def period(self) -> timedelta:
51
+ """How often a new frame comes out: 30 minutes for the «Merging», 5 for radar only.
52
+
53
+ The same as the ``period`` the API returns (``PT30M``, ``PT5M``): the
54
+ frame before one issued at ``t`` is the one issued at ``t - period``.
55
+ """
56
+ return timedelta(minutes=30 if self.merging else 5)
57
+
58
+
59
+ #: Surface Rainfall Intensity: radar only, mm/h, a frame every 5 minutes.
60
+ SRI: Final = Product("SRI", None, False, "rain intensity, radar only (mm/h)")
61
+ #: Surface Rainfall Total over the last hour: radar only, mm, every 5 minutes.
62
+ SRT1: Final = Product("SRT1", 1, False, "rain over the last hour, radar only (mm)")
63
+ CUM3: Final = Product("CUM3", 3, True, "rain over 3 hours, radar + rain gauges (mm)")
64
+ CUM6: Final = Product("CUM6", 6, True, "rain over 6 hours, radar + rain gauges (mm)")
65
+ CUM12: Final = Product("CUM12", 12, True, "rain over 12 hours, radar + rain gauges (mm)")
66
+ CUM24: Final = Product("CUM24", 24, True, "rain over 24 hours, radar + rain gauges (mm)")
67
+
68
+ #: Every product this package knows, by name. There is no ``CUM1``: the API
69
+ #: answers it with an empty list.
70
+ PRODUCTS: Final = {p.name: p for p in (SRI, SRT1, CUM3, CUM6, CUM12, CUM24)}
71
+
72
+
73
+ def product(name: str | Product) -> Product:
74
+ """The :class:`Product` called ``name``."""
75
+ if isinstance(name, Product):
76
+ return name
77
+ try:
78
+ return PRODUCTS[name.upper()]
79
+ except KeyError:
80
+ known = ", ".join(PRODUCTS)
81
+ raise DpcRadarError(f"unknown DPC radar product {name!r}; known: {known}") from None
82
+
83
+
84
+ @dataclass(frozen=True, slots=True)
85
+ class LastProduct:
86
+ """What ``findLastProductByType`` says about the latest frame."""
87
+
88
+ product: Product
89
+ time: datetime
90
+ period: timedelta
91
+
92
+
93
+ def last_product_url(name: str | Product, *, base: str = API_BASE) -> tuple[str, dict[str, str]]:
94
+ """URL and query parameters of the latest-frame request."""
95
+ return f"{base}/findLastProductByType", {"type": product(name).name}
96
+
97
+
98
+ def download_url(base: str = API_BASE) -> str:
99
+ """URL of the download-link request (a ``POST``)."""
100
+ return f"{base}/downloadProduct"
101
+
102
+
103
+ def download_body(name: str | Product, at: datetime) -> dict[str, Any]:
104
+ """JSON body of the download-link request for the frame issued ``at``."""
105
+ return {"productType": product(name).name, "productDate": to_epoch_ms(at)}
106
+
107
+
108
+ def to_epoch_ms(at: datetime) -> int:
109
+ """``at`` as the API's milliseconds since the epoch; ``at`` must be aware."""
110
+ if at.tzinfo is None:
111
+ raise DpcRadarError("naive datetime: pass an aware one (UTC)")
112
+ return round(at.timestamp() * 1000)
113
+
114
+
115
+ def from_epoch_ms(ms: int | float | str) -> datetime:
116
+ """The API's milliseconds since the epoch as an aware UTC datetime."""
117
+ return datetime.fromtimestamp(int(ms) / 1000, tz=UTC)
118
+
119
+
120
+ _PERIOD = re.compile(r"^PT(?:(\d+)H)?(?:(\d+)M)?$")
121
+
122
+
123
+ def parse_period(text: str) -> timedelta:
124
+ """An ISO 8601 period of hours and minutes (``PT5M``, ``PT30M``, ``PT1H``)."""
125
+ m = _PERIOD.match(text)
126
+ if m is None or not any(m.groups()):
127
+ raise DpcRadarError(f"unexpected period {text!r}")
128
+ return timedelta(hours=int(m[1] or 0), minutes=int(m[2] or 0))
129
+
130
+
131
+ def parse_last_product(payload: dict[str, Any]) -> LastProduct | None:
132
+ """The latest frame, or ``None`` when the API lists none."""
133
+ rows = payload.get("lastProducts")
134
+ if not isinstance(rows, list):
135
+ raise DpcRadarError(f"no 'lastProducts' in the answer: {payload!r}")
136
+ if not rows:
137
+ return None
138
+ row = rows[0]
139
+ try:
140
+ return LastProduct(
141
+ product=product(str(row["productType"])),
142
+ time=from_epoch_ms(row["time"]),
143
+ period=parse_period(str(row["period"])),
144
+ )
145
+ except (KeyError, TypeError, ValueError) as exc:
146
+ raise DpcRadarError(f"unexpected latest-frame answer: {row!r}") from exc
147
+
148
+
149
+ def parse_download(payload: dict[str, Any]) -> str:
150
+ """The S3 link of a frame, from the download-link answer."""
151
+ url = payload.get("url")
152
+ if not isinstance(url, str) or not url.startswith("https://"):
153
+ raise DpcRadarError(f"no download link in the answer: {payload!r}")
154
+ return url
155
+
156
+
157
+ def is_expired(status: int, body: str) -> bool:
158
+ """``True`` when the API says the frame is no longer kept.
159
+
160
+ That is a 500 carrying S3's 403 in the body, not a 404. Any other failure
161
+ is worth retrying; this one never is.
162
+ """
163
+ return status >= 400 and ("Forbidden" in body or "(403)" in body)
164
+
165
+
166
+ __all__ = [
167
+ "API_BASE",
168
+ "CUM3",
169
+ "CUM6",
170
+ "CUM12",
171
+ "CUM24",
172
+ "HEADERS",
173
+ "NODATA",
174
+ "PRODUCTS",
175
+ "SRI",
176
+ "SRT1",
177
+ "LastProduct",
178
+ "Product",
179
+ "download_body",
180
+ "download_url",
181
+ "from_epoch_ms",
182
+ "is_expired",
183
+ "last_product_url",
184
+ "parse_download",
185
+ "parse_last_product",
186
+ "parse_period",
187
+ "product",
188
+ "to_epoch_ms",
189
+ ]
dpc_radar/py.typed ADDED
File without changes
@@ -0,0 +1,484 @@
1
+ Metadata-Version: 2.4
2
+ Name: dpc-radar
3
+ Version: 0.1.0
4
+ Summary: Async Python client for the Italian Civil Protection (DPC) open radar data: SRI, Merging (CUM), history and criticality bulletins
5
+ Author: Giuseppe Zileni
6
+ Author-email: Giuseppe Zileni <giuseppe.zileni@gmail.com>
7
+ License-Expression: Apache-2.0
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.12
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Typing :: Typed
16
+ Requires-Dist: httpx>=0.27
17
+ Requires-Dist: numpy>=2.0
18
+ Requires-Dist: rasterio>=1.4
19
+ Requires-Python: >=3.12
20
+ Project-URL: Homepage, https://github.com/agent-engineering-studio/dpc-radar
21
+ Project-URL: Issues, https://github.com/agent-engineering-studio/dpc-radar/issues
22
+ Project-URL: Documentation, https://agentengineering.it/dpc-radar/
23
+ Project-URL: Changelog, https://github.com/agent-engineering-studio/dpc-radar/blob/main/CHANGELOG.md
24
+ Description-Content-Type: text/markdown
25
+
26
+ <p align="center">
27
+ <img src="https://raw.githubusercontent.com/agent-engineering-studio/dpc-radar/main/docs/images/banner.png" alt="dpc-radar: rain over Italy from the Civil Protection radar, in a few lines of Python" width="100%">
28
+ </p>
29
+
30
+ <p align="center">
31
+ <a href="https://github.com/agent-engineering-studio/dpc-radar/actions/workflows/ci.yml"><img src="https://github.com/agent-engineering-studio/dpc-radar/actions/workflows/ci.yml/badge.svg" alt="ci"></a>
32
+ <a href="https://pypi.org/project/dpc-radar/"><img src="https://img.shields.io/pypi/v/dpc-radar" alt="PyPI"></a>
33
+ <a href="https://agentengineering.it/dpc-radar/"><img src="https://img.shields.io/badge/docs-site-informational" alt="docs"></a>
34
+ <img src="https://img.shields.io/badge/python-3.12%20%7C%203.13-blue" alt="Python 3.12 | 3.13">
35
+ <img src="https://img.shields.io/badge/typing-mypy%20strict-informational" alt="mypy strict">
36
+ <img src="https://img.shields.io/badge/coverage-100%25-brightgreen" alt="coverage 100%">
37
+ <a href="https://github.com/agent-engineering-studio/dpc-radar/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache--2.0-green" alt="Apache-2.0"></a>
38
+ </p>
39
+
40
+ **dpc-radar** is a small, typed Python library for the open radar data of
41
+ the Italian **Civil Protection Department** (*Dipartimento della Protezione
42
+ Civile*, DPC). A national network of weather radars, together with
43
+ thousands of rain gauges, measures rain over all of Italy, and the DPC
44
+ publishes a new map **every 5 minutes**, free for anyone. This library lets
45
+ you use those maps from a script: which frame is the latest, how to download
46
+ it, and how to read the API's answers, including its surprises.
47
+
48
+ ```python
49
+ async with RadarClient() as radar:
50
+ rain = await radar.latest("CUM24") # the last 24 hours of rain, all of Italy
51
+ print(rain.sample([(15.78, 37.92)])) # mm at Melito di Porto Salvo (184.9 on 10 October 2026)
52
+ ```
53
+
54
+ > **Work in progress.** dpc-radar is being extracted from
55
+ > [Limen](https://github.com/agent-engineering-studio/limen). Today it holds
56
+ > the products, the rain grid and the client. The archive, the 2010–2025
57
+ > history and the criticality bulletins follow, one pull request at a time:
58
+ > see the [roadmap](https://agentengineering.it/dpc-radar/roadmap/).
59
+
60
+ ---
61
+
62
+ ## Contents
63
+
64
+ - [The radar of Italy, in 30 seconds](#the-radar-of-italy-in-30-seconds)
65
+ - [What a storm looks like](#what-a-storm-looks-like)
66
+ - [The products](#the-products)
67
+ - [Who is it for](#who-is-it-for)
68
+ - [Quick start](#quick-start)
69
+ - [How it works](#how-it-works)
70
+ - [The traps we already fell into](#the-traps-we-already-fell-into)
71
+ - [API at a glance](#api-at-a-glance)
72
+ - [Roadmap, and where AI helps](#roadmap-and-where-ai-helps)
73
+ - [Contributing](#contributing)
74
+ - [Data licence and credits](#data-licence-and-credits)
75
+
76
+ ---
77
+
78
+ ## The radar of Italy, in 30 seconds
79
+
80
+ A weather radar sends out a pulse of microwaves and listens for the echo.
81
+ Raindrops reflect it: the stronger the echo, the heavier the rain. The DPC
82
+ joins the radars that cover Italy into **one national map**, and then
83
+ corrects the radar with what the **rain gauges** on the ground really
84
+ collected. The correction is called the **«Merging»**.
85
+
86
+ ```mermaid
87
+ flowchart LR
88
+ R["📡 Weather radars<br/>all over Italy"] --> M1["National mosaic<br/>every 5 minutes"]
89
+ G["🌧️ Rain gauges<br/>thousands on the ground"] --> MG
90
+ M1 --> P1["SRI · SRT1<br/>radar only, 1 km"]
91
+ M1 --> MG["«Merging»<br/>radar corrected with gauges"]
92
+ MG --> P2["CUM3 · 6 · 12 · 24<br/>radar + gauges, 0.01°"]
93
+ P1 & P2 -->|"radar-api.protezionecivile.it"| D["dpc-radar"]
94
+ D --> U["📁 Your analysis<br/>maps · alerts · models"]
95
+ ```
96
+
97
+ What you can do with it, for example:
98
+
99
+ - know **how much it has rained** in a place in the last 3, 6, 12 or 24 hours;
100
+ - see a **storm arriving**, 5 minutes at a time;
101
+ - feed **flood and landslide models** with rain that was measured, not forecast;
102
+ - keep your own **archive**: the DPC keeps only about five months.
103
+
104
+ ## What a storm looks like
105
+
106
+ On **10 October 2026** a storm hit the area around Reggio Calabria, in the
107
+ toe of Italy. This is the rain of those 24 hours, from one frame of the
108
+ «Merging» CUM24 product:
109
+
110
+ <p align="center">
111
+ <img src="https://raw.githubusercontent.com/agent-engineering-studio/dpc-radar/main/docs/images/rain-24h.png" alt="Map of the rain over Italy on 10 October 2026 from the DPC Merging CUM24 product, with a zoom on the Reggio Calabria area" width="100%">
112
+ </p>
113
+
114
+ The radar sees the storm **while it happens**. Here is the rain intensity
115
+ (SRI, in mm per hour) at four moments of the same day:
116
+
117
+ <p align="center">
118
+ <img src="https://raw.githubusercontent.com/agent-engineering-studio/dpc-radar/main/docs/images/storm.png" alt="Four maps of rain intensity (SRI) over Italy on 10 October 2026, at 06, 10, 14 and 18 UTC" width="100%">
119
+ </p>
120
+
121
+ > Look at the arcs west of Sardinia at 06:00. Rings centred on a single
122
+ > radar usually mean an artefact, not a storm: the radar picks up echoes from
123
+ > the sea or from bent beams. Check a frame against the one before it before
124
+ > you trust it ([the traps](#the-traps-we-already-fell-into)).
125
+
126
+ And this is the same storm in **one place**, hour by hour. At Melito di
127
+ Porto Salvo most of the rain fell before dawn, between midnight and 05:00
128
+ UTC, with up to **21 mm in a single hour**:
129
+
130
+ <p align="center">
131
+ <img src="https://raw.githubusercontent.com/agent-engineering-studio/dpc-radar/main/docs/images/cell.svg" alt="Bar chart of the hourly radar rain at Melito di Porto Salvo on 10 October 2026" width="100%">
132
+ </p>
133
+
134
+ Radar alone, or radar corrected with the gauges? At Melito the gauges
135
+ («Merging») measured **185 mm** in the day, and the radar alone saw only
136
+ **115 mm**. Over the whole box, though, the radar read about **12 % more**
137
+ than the gauges. The radar is wrong in both directions, depending on the
138
+ place. That is why the «Merging» exists: it keeps the radar's picture and
139
+ corrects it to what the gauges collected.
140
+
141
+ <p align="center">
142
+ <img src="https://raw.githubusercontent.com/agent-engineering-studio/dpc-radar/main/docs/images/radar-vs-merging.png" alt="Two maps of the Reggio Calabria area on 10 October 2026: rain from the radar alone (24 SRT1 frames) and from the Merging CUM24" width="100%">
143
+ </p>
144
+
145
+ Zoom out, and five months of frames tell the story of a season. Averaged
146
+ over all of Italy's land, 10 October was not even the wettest day of the
147
+ autumn: 21 October was (19.4 mm on average against 7.1). A storm that
148
+ devastates one valley can be a small bar on a national chart.
149
+
150
+ <p align="center">
151
+ <img src="https://raw.githubusercontent.com/agent-engineering-studio/dpc-radar/main/docs/images/season.svg" alt="Bar chart: average daily rain over Italy's land for the last 150 days, from the CUM24 product" width="100%">
152
+ </p>
153
+
154
+ Every image above is made from real DPC frames by
155
+ [`docs/make_images.py`](https://github.com/agent-engineering-studio/dpc-radar/blob/main/docs/make_images.py),
156
+ with the functions of this library.
157
+
158
+ ## The products
159
+
160
+ <p align="center">
161
+ <img src="https://raw.githubusercontent.com/agent-engineering-studio/dpc-radar/main/docs/images/products.svg" alt="The time window of each product: SRI is the intensity now, SRT1 the last hour, CUM3 to CUM24 the last 3 to 24 hours" width="100%">
162
+ </p>
163
+
164
+ | Product | What it measures | Source | Grid | New frame |
165
+ |---|---|---|---|---|
166
+ | `SRI` | rain intensity right now (mm/h) | radar only | 1 km | every 5 min |
167
+ | `SRT1` | rain in the last hour (mm) | radar only | 1 km | every 5 min |
168
+ | `CUM3`, `CUM6`, `CUM12`, `CUM24` | rain in the last 3–24 hours (mm) | «Merging»: radar + rain gauges | 0.01°, EPSG:4326 | every 30 min |
169
+
170
+ **Which one should I use?**
171
+
172
+ - *Is it raining now, and how hard?* → `SRI`.
173
+ - *How much rain fell in the last hour?* → `SRT1`.
174
+ - *How much rain fell in the last day?* → `CUM24` (or `CUM3`–`CUM12` for shorter windows). The gauges make it the most accurate, but it arrives every 30 minutes, not every 5.
175
+
176
+ ## Who is it for
177
+
178
+ - **Researchers and students** in hydrology, meteorology and geology who
179
+ want measured rain in a notebook or a pipeline.
180
+ - **Civil protection, utilities and engineers** who watch rivers, slopes,
181
+ roads or drains and need rain totals that are repeatable.
182
+ - **Data journalists and developers** who want to show what fell during a
183
+ storm, with a source anyone can check.
184
+
185
+ It started inside [Limen](https://github.com/agent-engineering-studio/limen),
186
+ where the radar decides *when* to re-run the risk model (heavy rain on the
187
+ radar starts a run at once) and the «Merging» totals feed the flood score.
188
+
189
+ ---
190
+
191
+ ## Quick start
192
+
193
+ ### 1. Install
194
+
195
+ ```bash
196
+ pip install dpc-radar
197
+ ```
198
+
199
+ Python 3.12 or newer. It depends on `httpx`, `numpy` and `rasterio`.
200
+
201
+ No account and no key: the DPC data are open.
202
+
203
+ ### 2. Get the latest frame
204
+
205
+ ```python
206
+ import asyncio
207
+
208
+ from dpc_radar import RadarClient
209
+
210
+
211
+ async def main() -> None:
212
+ async with RadarClient() as radar:
213
+ rain = await radar.latest("CUM24")
214
+ print(rain.product.name, rain.time) # CUM24 2026-11-04 14:00:00+00:00
215
+ print(rain.data.shape) # (1233, 1341): 0.01° pixels, NaN where the radar does not see
216
+
217
+
218
+ asyncio.run(main())
219
+ ```
220
+
221
+ ### 3. Read the rain at a place
222
+
223
+ ```python
224
+ melito, reggio = (15.78, 37.92), (15.65, 38.11) # lon, lat in degrees
225
+ print(rain.sample([melito, reggio])) # mm in the last 24 hours, or None if not measured
226
+ print(rain.peak((15.25, 37.75, 17.25, 39.45), threshold=50)) # (highest mm, pixels >= 50)
227
+ ```
228
+
229
+ `sample` reads the **median of the 3×3 pixels** around each point, never one
230
+ pixel, and answers `None` where the radar has no data: not measured is not
231
+ the same as dry.
232
+
233
+ ### 4. Check a frame before you trust it
234
+
235
+ ```python
236
+ async with RadarClient() as radar:
237
+ now = await radar.latest("CUM24")
238
+ before = await radar.at("CUM24", now.time - now.product.period) # 30 minutes earlier
239
+
240
+ check = now.check(before, max_step=150) # mm: more than half an hour of rain
241
+ if check.grid is None:
242
+ rain = before # rejected: this frame jumped up where no rain can fall that fast
243
+ else:
244
+ rain = check.grid # consistent, or the frame before was the wrong one
245
+ print(check.verdict, check.jumps)
246
+ ```
247
+
248
+ A frame older than about five months is gone: `radar.at(...)` returns
249
+ `ABSENT` instead of raising, and never retries it.
250
+
251
+ ### 5. Look at it
252
+
253
+ With `pip install matplotlib`:
254
+
255
+ ```python
256
+ import matplotlib.pyplot as plt
257
+
258
+ h, w = rain.data.shape
259
+ left, top = rain.transform.c, rain.transform.f
260
+ right, bottom = left + w * rain.transform.a, top + h * rain.transform.e
261
+ plt.imshow(rain.data, extent=(left, right, bottom, top), cmap="Blues", vmin=0, vmax=50)
262
+ plt.colorbar(label="rain in the last 24 hours (mm)")
263
+ plt.show()
264
+ ```
265
+
266
+ ### Without the client
267
+
268
+ Every step is also a plain function, if you have your own HTTP stack:
269
+ `products.last_product_url`, `parse_last_product`, `products.download_body`,
270
+ `parse_download`, `is_expired`, then `RainGrid.from_geotiff(raw, product, time)`.
271
+
272
+ ---
273
+
274
+ ## How it works
275
+
276
+ ### Two calls, and one surprise
277
+
278
+ The open API at `radar-api.protezionecivile.it` has two calls that matter.
279
+ The first says which frame is the newest; the second gives a short-lived
280
+ download link for one frame.
281
+
282
+ ```mermaid
283
+ sequenceDiagram
284
+ autonumber
285
+ participant You as Your script
286
+ participant L as dpc_radar
287
+ participant A as DPC radar API
288
+ participant S as S3 storage
289
+
290
+ You->>L: last_product_url(CUM24)
291
+ L-->>You: URL + params
292
+ You->>A: GET /findLastProductByType?type=CUM24
293
+ A-->>You: {"lastProducts": [{"time": 1793790000000, "period": "PT30M"}]}
294
+ You->>L: parse_last_product(answer)
295
+ L-->>You: LastProduct(time, period = 30 min)
296
+ You->>L: download_body(CUM24, time)
297
+ You->>A: POST /downloadProduct {"productType", "productDate"}
298
+ A-->>You: {"url": "https://…s3…"} (a signed link)
299
+ You->>S: GET the link
300
+ S-->>You: GeoTIFF
301
+ ```
302
+
303
+ ### What a frame request can answer
304
+
305
+ ```mermaid
306
+ flowchart TD
307
+ q(["POST /downloadProduct<br/>(product, time)"]) --> c1{"status 200?"}
308
+ c1 -- yes --> ok(["parse_download → S3 link<br/>download the GeoTIFF"])
309
+ c1 -- no --> c2{"is_expired(status, body)?<br/>a 500 with S3's 403 inside"}
310
+ c2 -- yes --> gone(["the frame is gone<br/>(older than ~5 months)<br/>never retry"])
311
+ c2 -- no --> retry(["a real failure<br/>retry later"])
312
+ ```
313
+
314
+ ### The building blocks
315
+
316
+ Three layers. `products` is **pure**: it builds requests and reads answers,
317
+ with no network. `grid` turns a GeoTIFF into an array you can sample and
318
+ check. `client` wires them to **your** `httpx.AsyncClient`, so timeouts,
319
+ retries and proxies stay under your control.
320
+
321
+ ```mermaid
322
+ flowchart LR
323
+ subgraph yours["Your code"]
324
+ H["httpx.AsyncClient<br/>or a send= hook"]
325
+ end
326
+ subgraph lib["dpc_radar"]
327
+ direction TB
328
+ CL["client.py<br/>RadarClient · latest · at · ABSENT"]
329
+ PR["products.py<br/>SRI · SRT1 · CUM3–24<br/>requests · parsers · is_expired"]
330
+ GR["grid.py<br/>RainGrid · sample · peak · crop · check"]
331
+ ER["errors.py<br/>DpcRadarError"]
332
+ NX["archive · history · bulletins<br/>(coming from Limen)"]:::next
333
+ end
334
+ H --> CL
335
+ CL --> PR
336
+ CL --> GR
337
+ classDef next stroke-dasharray: 5 5
338
+ ```
339
+
340
+ ---
341
+
342
+ ## The traps we already fell into
343
+
344
+ Every line below cost a bug in Limen. The library handles the ones it can;
345
+ the others are here so you don't have to find them yourself.
346
+
347
+ | Trap | What happens | What to do |
348
+ |---|---|---|
349
+ | **No `CUM1`** | asking for it gives an empty list, not an error | the shortest «Merging» is `CUM3`; for one hour use `SRT1` |
350
+ | **"Gone" looks like a crash** | a frame older than ~5 months answers **500**, with S3's `403 Forbidden` in the body, not 404 | `is_expired(status, body)`: never retry those |
351
+ | **The «Merging» disappears** | the DPC keeps about five months, and there is no public archive of it | save the frames you need (the `archive` module is coming) |
352
+ | **Two grids** | `SRI`/`SRT1` are 1 km in a Transverse Mercator projection; `CUM*` are 0.01° in EPSG:4326 | never mix the arrays: reproject one onto the other |
353
+ | **A corrupted series** | in October 2026 every CUM24 frame at :30 carried a smooth bell of up to 20,584 mm over Abruzzo, for days (the :00 frames were right) | never trust one frame alone: compare it with its neighbours, and read a place with the median of the 3×3 pixels around it |
354
+ | **Not every echo is rain** | sea clutter or a radar with a problem can paint rain where there is none, often as a disk around one radar, and it can stay still for hours | a jump between frames does not catch it: see the [benchmark](https://agentengineering.it/dpc-radar/benchmark/) |
355
+ | **Radar alone is not the truth** | the radar-only history read between 10 % and 80 % of the gauges in Apulia in 2016 | use the «Merging» when you can; compare on your area |
356
+ | **Times are in UTC, in milliseconds** | the API speaks epoch milliseconds | `to_epoch_ms` / `from_epoch_ms`, and always aware datetimes |
357
+ | **The `origin` header** | the API once refused requests without it; in November 2026 it no longer does | `products.HEADERS` sends it anyway |
358
+
359
+ Every trap above is a case in the **[benchmark](https://agentengineering.it/dpc-radar/benchmark/)**:
360
+ real frames where we know the answer, and how each cleaning rule scores on
361
+ them. Limen's rule today passes 8 of 18 checks; a first frame-level check
362
+ (`jump-sign`) passes 17.
363
+
364
+ ---
365
+
366
+ ## API at a glance
367
+
368
+ | Name | What it is |
369
+ |---|---|
370
+ | `RadarClient(client=None, send=None, retries=3)` | the client: `async with`, your `httpx.AsyncClient` or a `send` hook |
371
+ | `radar.latest(p, cached=None)` | the newest frame as a `RainGrid`; `cached` skips the download if it is still the newest |
372
+ | `radar.at(p, time)` / `radar.download(p, time)` | the frame issued at `time` as a grid / as GeoTIFF bytes, or `ABSENT` |
373
+ | `radar.last_product(p)` | time and period of the newest frame |
374
+ | `RainGrid` | one frame: `product`, `time`, `data` (NaN = no data), `transform`, `crs` |
375
+ | `grid.sample(points)` | the value at lon/lat points: median of the 3×3 pixels, `None` if not measured |
376
+ | `grid.peak(bbox, threshold=)` / `grid.crop(bbox)` | highest value and pixels above a threshold in a box / the box as a grid |
377
+ | `grid.check(previous, max_step=)` | `FrameCheck(verdict, grid, jumps)`: whether to trust a frame, given the one before |
378
+ | `ABSENT` | a frame the DPC no longer keeps |
379
+ | `SRI`, `SRT1`, `CUM3`, `CUM6`, `CUM12`, `CUM24` | the products: `name`, `hours` (`None` for an intensity), `merging`, `description` |
380
+ | `PRODUCTS`, `product(name)` | every product by name; `product("cum24")` → `CUM24` |
381
+ | `products.last_product_url(p)` | URL and params of the "latest frame" request (a `GET`) |
382
+ | `products.download_url()`, `products.download_body(p, at)` | URL and JSON body of the "download link" request (a `POST`) |
383
+ | `parse_last_product(answer)` | `LastProduct(product, time, period)`, or `None` if the API lists none |
384
+ | `parse_download(answer)` | the signed S3 link of a frame |
385
+ | `is_expired(status, body)` | `True` when the frame is gone for good |
386
+ | `products.HEADERS`, `products.NODATA` | the `origin` header; `-9999.0`, the no-data value of every product |
387
+ | `products.to_epoch_ms`, `from_epoch_ms`, `parse_period` | the API's times and periods (`PT5M`, `PT30M`) |
388
+ | `DpcRadarError` | an answer the library cannot read, or a bad argument |
389
+
390
+ Full reference: **https://agentengineering.it/dpc-radar/api/client/**
391
+
392
+ ---
393
+
394
+ ## Roadmap, and where AI helps
395
+
396
+ The plan is on the [roadmap](https://agentengineering.it/dpc-radar/roadmap/)
397
+ and tracked in [#10](https://github.com/agent-engineering-studio/dpc-radar/issues/10).
398
+ Each idea is measured against one goal of
399
+ [Limen](https://github.com/agent-engineering-studio/limen): anticipate within
400
+ 72 hours 90 % of the events in the news, with at most 10 % of
401
+ municipality-days on alert.
402
+
403
+ ```mermaid
404
+ flowchart LR
405
+ B["Benchmark<br/>known cases"] --> P0["Phase 0<br/>reliability map<br/>climatology<br/>storm catalogue"]
406
+ P0 --> P1["Phase 1<br/>learned frame check"]
407
+ P1 --> P2["Phase 2<br/>nowcasting<br/>radar–gauge bias"]
408
+ P2 --> P3["Phase 3<br/>MCP · llms.txt<br/>event reports"]
409
+ P0 & P1 & P2 & P3 -.-> L["Limen<br/>fewer false alarms ·<br/>more events anticipated"]
410
+ ```
411
+
412
+ | Idea | In plain words | What Limen gains | Issue |
413
+ |---|---|---|---|
414
+ | **Benchmark** | a fixed set of storms and faults where we know the answer | every change measurable | [#2](https://github.com/agent-engineering-studio/dpc-radar/issues/2) |
415
+ | **Reliability map** | where the radar sees well, and where it is blind | a blind spot is no longer read as "dry" | [#3](https://github.com/agent-engineering-studio/dpc-radar/issues/3) |
416
+ | **Rain climatology** | how rare is this rain *here*, from 15 years of radar | alerts on unusual rain, not on one national threshold | [#4](https://github.com/agent-engineering-studio/dpc-radar/issues/4) |
417
+ | **Storm catalogue** | every storm as an object, and the extreme ones as events to check in the news | many more verified events to measure against | [#5](https://github.com/agent-engineering-studio/dpc-radar/issues/5) |
418
+ | **Learned frame check** | a model that tells a real storm from a broken frame or clutter | fewer false alarms | [#6](https://github.com/agent-engineering-studio/dpc-radar/issues/6) |
419
+ | **Nowcasting** | the rain field moved forward along its motion, 0–2 hours | a trigger on rain that is *coming* | [#7](https://github.com/agent-engineering-studio/dpc-radar/issues/7) |
420
+ | **Radar–gauge bias** | learn how wrong the radar alone is, and correct it | a history worth backtesting on | [#8](https://github.com/agent-engineering-studio/dpc-radar/issues/8) |
421
+ | **AI for agents** | an MCP server, `llms.txt`, reports that cite their frames | the same facts for Limen's assistant | [#9](https://github.com/agent-engineering-studio/dpc-radar/issues/9) |
422
+
423
+ One rule holds for every AI feature: **the numbers come from the frames**,
424
+ computed by tested code. A language model may read the news and explain the
425
+ numbers, never invent them, and nothing here replaces the official DPC alert.
426
+
427
+ ---
428
+
429
+ ## Contributing
430
+
431
+ Contributions of every size are welcome, from a typo to a new module. You
432
+ don't need to be a meteorologist: most of the code is plain Python, HTTP and
433
+ arrays.
434
+
435
+ ```bash
436
+ git clone https://github.com/agent-engineering-studio/dpc-radar
437
+ cd dpc-radar
438
+ uv sync # install everything, dev tools included
439
+ make check # ruff + mypy --strict + pytest, the same gate as CI
440
+ make docs # build this site locally
441
+ ```
442
+
443
+ The tests **need no network**: they run against answers recorded from the
444
+ real API.
445
+
446
+ ```text
447
+ dpc-radar/
448
+ ├── src/dpc_radar/
449
+ │ ├── products.py # products, requests, parsers, is_expired: pure functions
450
+ │ ├── grid.py # RainGrid: read a frame, sample, peak, crop, check
451
+ │ ├── client.py # RadarClient: latest, at, download, ABSENT
452
+ │ └── errors.py # DpcRadarError
453
+ ├── tests/ # offline: synthetic GeoTIFFs and a fake API
454
+ │ └── live/ # the same on the real API: uv run pytest -m live
455
+ ├── benchmarks/ # known cases, and how each cleaning rule scores
456
+ └── docs/
457
+ ├── make_images.py # the images of this README, from real frames
458
+ └── roadmap.md # what comes next, and where AI helps
459
+ ```
460
+
461
+ Good first issues: a notebook with a storm you remember, a recipe for your
462
+ favourite HTTP library, a check of the radar against a rain gauge near you.
463
+ See [CONTRIBUTING.md](https://github.com/agent-engineering-studio/dpc-radar/blob/main/CONTRIBUTING.md).
464
+
465
+ ---
466
+
467
+ ## Data licence and credits
468
+
469
+ - **Radar data** (SRI, SRT1, «Merging» CUM): © *Dipartimento della
470
+ Protezione Civile*, open data under
471
+ [CC BY-SA 4.0](https://creativecommons.org/licenses/by-sa/4.0/). Credit the
472
+ DPC and share data you derive from it under the same licence.
473
+ - **Criticality bulletins**: DPC, [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/).
474
+ - **IT-DPC-SRI** (the 2010–2025 history, coming in the `history` module):
475
+ Fondazione Bruno Kessler on DPC data, CC BY-SA 4.0,
476
+ [doi:10.5281/zenodo.18637608](https://doi.org/10.5281/zenodo.18637608).
477
+ - **Country borders** in the images: [Natural Earth](https://www.naturalearthdata.com/), public domain.
478
+
479
+ This library is not affiliated with the DPC. It is not an alert system:
480
+ for official warnings, see the
481
+ [DPC criticality bulletin](https://rischi.protezionecivile.gov.it/it/meteo-idro/allertamento/)
482
+ and your regional civil protection.
483
+
484
+ The code is released under the [Apache-2.0](https://github.com/agent-engineering-studio/dpc-radar/blob/main/LICENSE) licence.
@@ -0,0 +1,10 @@
1
+ dpc_radar/__init__.py,sha256=mLj8JkAGCQELfaQ3BOug3EO41rN-a-if__VOvwpnclg,890
2
+ dpc_radar/client.py,sha256=Kkt4bgcJmEk8OMTdVhTp1VPwqRS5qW3ApVD7TAJqAU0,6650
3
+ dpc_radar/errors.py,sha256=q2pKpM8lTSxKU6tpjMuAp9-LMNhsOuG5kEnAW-3qcpI,236
4
+ dpc_radar/grid.py,sha256=uKvvd1N2D44AhrwNqSr4d4sPQtHi7ovW0TMODVA_Fik,8481
5
+ dpc_radar/products.py,sha256=hOdoRQX-_G6e6KZhPVsNc5ui3AShkb7VawpyXGX_TW0,6516
6
+ dpc_radar/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ dpc_radar-0.1.0.dist-info/licenses/LICENSE,sha256=yVuuHRzgI17MzTVgt3LsHvuX80innw--CmNPDCzO_iw,11358
8
+ dpc_radar-0.1.0.dist-info/WHEEL,sha256=MWx7psoF7KNST9G72pGtiBYuaXRXQXBk9pw5R6FzYko,80
9
+ dpc_radar-0.1.0.dist-info/METADATA,sha256=nlifHun429ZIenq176z2P8qeEtGJAl1bKH9vH_yoSh0,23736
10
+ dpc_radar-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.7
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -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
+