From 08704c276fb49e9f41468dd0a55f3c931bc9a07b Mon Sep 17 00:00:00 2001 From: Giuseppe Zileni Date: Sat, 28 Nov 2026 15:25:58 +0100 Subject: [PATCH] feat: shaken_points, ShakeGrid.points, index_of and require_g (0.3.0) Limen's single-domain ShakeMap logic moves into the library as pure functions: the points shaken above a threshold the caller passes (Limen's celle_scosse), the coordinates of every grid point and the nearest grid index of many positions (hand-written in Limen's co-seismic backtest). sample() now reads through index_of. Parity tests against Limen's code at commit 89e1932, frozen into the tests. A test bans imports of the sister libraries, limen and limen_core. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 19 ++++++ README.md | 3 + pyproject.toml | 2 +- src/ingv_shakemap/__init__.py | 3 +- src/ingv_shakemap/grid.py | 89 +++++++++++++++++++++++++-- tests/test_grid_points.py | 110 ++++++++++++++++++++++++++++++++++ tests/test_package.py | 35 +++++++++++ tests/test_shaken_points.py | 101 +++++++++++++++++++++++++++++++ uv.lock | 2 +- 9 files changed, 355 insertions(+), 9 deletions(-) create mode 100644 tests/test_grid_points.py create mode 100644 tests/test_shaken_points.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 0a63fb1..3ea756b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,25 @@ All notable changes to this project are documented here. The format follows ## [Unreleased] +## [0.3.0] - 2026-11-28 + +### Added + +- `shaken_points(grid, points, min_pga_g, *, method="nearest")`: the + `(key, PGA in g)` of the points shaken at least `min_pga_g`, in one NumPy + call. `points` are `(key, longitude, latitude)` with the caller's own keys; + a point outside the grid is not shaken; the threshold has no default. Moved + from Limen (`celle_scosse`), with a parity test against Limen's code. +- `ShakeGrid.points()`: the longitude and latitude of every grid point, each + `(nlat, nlon)` like `column`. +- `ShakeGrid.index_of(longitudes, latitudes)` → `(rows, cols, inside)`: the + nearest grid point of many positions, the one `sample` reads (which now + calls it), ties to even. Both replace code Limen's co-seismic backtest wrote + by hand, with parity tests against it. +- `ShakeGrid.require_g(name="PGA")`: raises `GridError` unless the column + exists and is in percent of g or g, to refuse a grid as soon as it is parsed. +- A test that the package imports neither a sister library nor Limen. + ### Changed - Documentation site built with [Zensical](https://zensical.org) instead of diff --git a/README.md b/README.md index e343ca6..8ab6f0a 100644 --- a/README.md +++ b/README.md @@ -225,6 +225,9 @@ ingv = IngvClient(send=send) | `parse_grid(xml)` → `ShakeGrid` | pure parser; raises only `GridError` | | `ShakeGrid.pga_g` / `.pgv_cm_s` / `.mmi` / `.value_at` | values at a point | | `ShakeGrid.sample` / `.sample_g` | values at many points, nearest or bilinear | +| `shaken_points(grid, points, min_pga_g)` | `(key, PGA in g)` of your points shaken at least a threshold you choose | +| `ShakeGrid.require_g(name="PGA")` | `GridError` unless the column reads in g | +| `ShakeGrid.points()` / `.index_of(lons, lats)` | the coordinates of every grid point; the nearest grid point of your positions | | `ShakeGrid.column` / `.bbox` | the whole grid as arrays | | `parse_info(json)`, `parse_stations(json)` | pure parsers of `info.json` and `stationlist.json` | | `ShakeGrid.event`, `.map_status`, `.version`, `.process_time`, `.fields` | the map's metadata | diff --git a/pyproject.toml b/pyproject.toml index 64c496a..8af2390 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ingv-shakemap" -version = "0.2.0" +version = "0.3.0" description = "Async Python client for INGV earthquakes and ShakeMap grids: FDSN events, grid.xml parsing, ground shaking (PGA, PGV, MMI) at any point" readme = "README.md" requires-python = ">=3.12" diff --git a/src/ingv_shakemap/__init__.py b/src/ingv_shakemap/__init__.py index e0b36cb..4e1f7ad 100644 --- a/src/ingv_shakemap/__init__.py +++ b/src/ingv_shakemap/__init__.py @@ -13,7 +13,7 @@ shakemap_grid_url, shakemap_product_url, ) -from ingv_shakemap.grid import GridEvent, GridField, ShakeGrid, parse_grid +from ingv_shakemap.grid import GridEvent, GridField, ShakeGrid, parse_grid, shaken_points from ingv_shakemap.products import ( GroundMotionSummary, MapRun, @@ -47,4 +47,5 @@ "parse_stations", "shakemap_grid_url", "shakemap_product_url", + "shaken_points", ] diff --git a/src/ingv_shakemap/grid.py b/src/ingv_shakemap/grid.py index 5a69a98..891e100 100644 --- a/src/ingv_shakemap/grid.py +++ b/src/ingv_shakemap/grid.py @@ -30,6 +30,7 @@ import math import re import xml.etree.ElementTree as ET +from collections.abc import Sequence from dataclasses import dataclass, field from datetime import UTC, datetime from typing import Any, Final, Literal @@ -137,6 +138,38 @@ def column(self, name: str) -> npt.NDArray[np.float64]: raise GridError(f"no {name!r} column; the grid has {', '.join(self.fields)}") return self.values[:, :, self.fields[name].index] + def points(self) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]: + """Longitude and latitude of every grid point, each ``(nlat, nlon)``. + + Laid out as :meth:`column`: north row first, longitude growing along a + row. ``.ravel()`` gives the order of the file's rows, where point + ``row * nlon + col`` is ``[row, col]`` here. + """ + cols, rows = np.meshgrid(np.arange(self.nlon), np.arange(self.nlat)) + lons = np.asarray(self.lon_min + cols * self.lon_step, dtype=np.float64) + lats = np.asarray(self.lat_max - rows * self.lat_step, dtype=np.float64) + return lons, lats + + def index_of( + self, longitudes: npt.ArrayLike, latitudes: npt.ArrayLike + ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp], npt.NDArray[np.bool_]]: + """``(rows, cols, inside)`` of the grid point nearest to each position. + + The point :meth:`sample` reads with ``nearest`` (it calls this), ties + rounding half to even. ``inside`` is false for a position outside the + grid or not finite; its row and column are then -1, which NumPy would + read as the last one: index with ``rows[inside], cols[inside]``. + """ + lon = np.asarray(longitudes, dtype=float) + lat = np.asarray(latitudes, dtype=float) + lon, lat = np.broadcast_arrays(lon, lat) + col = np.rint((lon - self.lon_min) / self.lon_step) + row = np.rint((self.lat_max - lat) / self.lat_step) + inside = (col >= 0) & (col < self.nlon) & (row >= 0) & (row < self.nlat) + rows = np.where(inside, row, -1).astype(np.intp) + cols = np.where(inside, col, -1).astype(np.intp) + return rows, cols, inside + def sample( self, name: str, @@ -156,16 +189,15 @@ def sample( lon = np.asarray(longitudes, dtype=float) lat = np.asarray(latitudes, dtype=float) lon, lat = np.broadcast_arrays(lon, lat) - x = (lon - self.lon_min) / self.lon_step - y = (self.lat_max - lat) / self.lat_step out = np.full(lon.shape, np.nan) if method == "nearest": - col, row = np.rint(x), np.rint(y) - inside = (col >= 0) & (col < self.nlon) & (row >= 0) & (row < self.nlat) - out[inside] = grid[row[inside].astype(int), col[inside].astype(int)] + rows, cols, inside = self.index_of(lon, lat) + out[inside] = grid[rows[inside], cols[inside]] return out if method != "bilinear": raise GridError(f"unknown method {method!r}: nearest or bilinear") + x = (lon - self.lon_min) / self.lon_step + y = (self.lat_max - lat) / self.lat_step eps = 1e-9 inside = (x >= -eps) & (x <= self.nlon - 1 + eps) & (y >= -eps) & (y <= self.nlat - 1 + eps) xi, yi = x[inside], y[inside] @@ -189,6 +221,16 @@ def sample_g( """An acceleration column (``PGA``, ``PSA03``...) at many positions, in **g**.""" return self.sample(name, longitudes, latitudes, method=method) / self._g_divisor(name) + def require_g(self, name: str = "PGA") -> None: + """Raise :class:`GridError` unless column ``name`` exists and reads in g. + + The check :meth:`sample_g` makes, without sampling: for refusing a grid + as soon as it is parsed. + """ + if name not in self.fields: + raise GridError(f"no {name!r} column; the grid has {', '.join(self.fields)}") + self._g_divisor(name) + def _g_divisor(self, name: str) -> float: units = self.fields[name].units if units in PERCENT_G: @@ -198,6 +240,33 @@ def _g_divisor(self, name: str) -> float: raise GridError(f"{name} in {units!r}: expected percent of g or g") +def shaken_points[K]( + grid: ShakeGrid, + points: Sequence[tuple[K, float, float]], + min_pga_g: float, + *, + method: Literal["nearest", "bilinear"] = "nearest", +) -> list[tuple[K, float]]: + """``(key, PGA in g)`` of the points shaken at least ``min_pga_g``, in input order. + + ``points`` are ``(key, longitude, latitude)``: the centres of your cells, + your stations, your landslides, with whatever key you use for them. A + point outside the grid is not shaken. ``min_pga_g`` is yours to choose: the + library has no default for it. + + Raises :class:`GridError` if the grid has no ``PGA`` column or it is not + in percent of g or g (never with no points: nothing is read then). + """ + if not points: + return [] + lons = np.fromiter((p[1] for p in points), dtype=float, count=len(points)) + lats = np.fromiter((p[2] for p in points), dtype=float, count=len(points)) + pga = grid.sample_g("PGA", lons, lats, method=method) + # NaN outside the grid: the comparison is false, the point is left out. + shaken = np.flatnonzero(pga >= min_pga_g) + return [(points[int(i)][0], float(pga[i])) for i in shaken] + + def _float(value: str | None) -> float | None: try: return float(value) if value not in (None, "") else None @@ -297,4 +366,12 @@ def _parse(xml: bytes) -> ShakeGrid: ) -__all__ = ["PERCENT_G", "GridError", "GridEvent", "GridField", "ShakeGrid", "parse_grid"] +__all__ = [ + "PERCENT_G", + "GridError", + "GridEvent", + "GridField", + "ShakeGrid", + "parse_grid", + "shaken_points", +] diff --git a/tests/test_grid_points.py b/tests/test_grid_points.py new file mode 100644 index 0000000..6dc82a5 --- /dev/null +++ b/tests/test_grid_points.py @@ -0,0 +1,110 @@ +"""`ShakeGrid.points` and `ShakeGrid.index_of` against Limen's backtest, on fixed inputs. + +The two references below are the snippets of ``valuta`` in +``src/limen/cli/backtest_cosismico.py`` at Limen commit ``89e1932``, copied +here, not imported: the library's tests do not depend on Limen. +""" + +from __future__ import annotations + +import numpy as np +import numpy.typing as npt +from conftest import make_grid_xml + +from ingv_shakemap import ShakeGrid, parse_grid + + +def _limen_punti( + griglia: ShakeGrid, +) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]: + nlat, nlon = griglia.nlat, griglia.nlon + cols, rows = np.meshgrid(np.arange(nlon), np.arange(nlat)) + lons = np.asarray(griglia.lon_min + cols.ravel() * griglia.lon_step, dtype=np.float64) + lats = np.asarray(griglia.lat_max - rows.ravel() * griglia.lat_step, dtype=np.float64) + return lons, lats + + +def _limen_indici( + griglia: ShakeGrid, f_lon: npt.NDArray[np.float64], f_lat: npt.NDArray[np.float64] +) -> tuple[npt.NDArray[np.bool_], npt.NDArray[np.int_]]: + """``dentro`` and the flat indices of the points inside, before the land mask.""" + nlat, nlon = griglia.nlat, griglia.nlon + c = np.rint((f_lon - griglia.lon_min) / griglia.lon_step) + r = np.rint((griglia.lat_max - f_lat) / griglia.lat_step) + dentro = (c >= 0) & (c < nlon) & (r >= 0) & (r < nlat) + indici = (r[dentro] * nlon + c[dentro]).astype(int) + return dentro, indici + + +def _positions(n: int, seed: int) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]: + rng = np.random.default_rng(seed) + return rng.uniform(13.98, 14.07, n), rng.uniform(38.94, 39.02, n) + + +def test_points_parity_with_limen() -> None: + for grid in ( + parse_grid(make_grid_xml(nlon=6, nlat=5)), + parse_grid(make_grid_xml(nlon=7, nlat=3, step=0.0083, lon_min=12.31, lat_max=42.77)), + ): + lons, lats = grid.points() + ref_lons, ref_lats = _limen_punti(grid) + assert lons.shape == lats.shape == (grid.nlat, grid.nlon) + assert np.array_equal(lons.ravel(), ref_lons) + assert np.array_equal(lats.ravel(), ref_lats) + + +def test_points_are_laid_out_as_column_and_span_bbox() -> None: + grid = parse_grid(make_grid_xml(nlon=6, nlat=5)) + lons, lats = grid.points() + west, south, east, north = grid.bbox + assert (lons[0, 0], lats[0, 0]) == (west, north) + assert (lons[-1, -1], lats[-1, -1]) == (east, south) + # Sampling the grid on its own points gives the column back. + assert np.array_equal(grid.sample("PGA", lons, lats), grid.column("PGA")) + rows, cols, inside = grid.index_of(lons, lats) + assert inside.all() + assert np.array_equal(rows * grid.nlon + cols, np.arange(30).reshape(5, 6)) + + +def test_index_of_parity_with_limen() -> None: + grid = parse_grid(make_grid_xml(nlon=6, nlat=5)) + lon, lat = _positions(500, seed=287) + rows, cols, inside = grid.index_of(lon, lat) + dentro, indici = _limen_indici(grid, lon, lat) + assert 0 < inside.sum() < 500 + assert np.array_equal(inside, dentro) + assert np.array_equal(rows[inside] * grid.nlon + cols[inside], indici) + assert (rows[~inside] == -1).all() and (cols[~inside] == -1).all() + + +def test_index_of_parity_with_limen_on_ties() -> None: + grid = parse_grid(make_grid_xml(step=0.5, lon_min=0.0, lat_max=10.0)) + lon = np.array([0.25, 0.75, 1.25, -0.25, -0.26, 1.75, 1.76]) + lat = np.array([10.0, 9.75, 9.25, 10.25, 10.0, 8.75, 9.0]) + rows, cols, inside = grid.index_of(lon, lat) + dentro, indici = _limen_indici(grid, lon, lat) + assert np.array_equal(inside, dentro) + assert np.array_equal(rows[inside] * grid.nlon + cols[inside], indici) + # Half to even: 0.5 steps -> 0, 1.5 -> 2, 2.5 -> 2, as round() in value_at. + assert cols.tolist() == [0, 2, 2, 0, -1, -1, -1] + assert rows.tolist() == [0, 0, 2, 0, -1, -1, -1] + + +def test_index_of_agrees_with_sample_and_value_at() -> None: + grid = parse_grid(make_grid_xml(nlon=6, nlat=5)) + lon, lat = _positions(400, seed=0) + rows, cols, inside = grid.index_of(lon, lat) + sampled = grid.sample("PGA", lon, lat) + assert np.array_equal(np.isnan(sampled), ~inside) + assert np.array_equal(sampled[inside], grid.column("PGA")[rows[inside], cols[inside]]) + for x, y, r, c, ok in zip(lon, lat, rows, cols, inside, strict=True): + at = grid._index(float(x), float(y)) + assert at == ((int(r), int(c)) if ok else None) + + +def test_index_of_broadcasts_and_leaves_out_what_is_not_finite() -> None: + grid = parse_grid(make_grid_xml()) + rows, cols, inside = grid.index_of(np.array([[14.0, 14.03]]), 38.98) + assert rows.tolist() == [[2, 2]] and cols.tolist() == [[0, 3]] and inside.all() + rows, cols, inside = grid.index_of([np.nan, np.inf, 14.0, 1e300], [39.0, 39.0, np.nan, 39.0]) + assert not inside.any() and rows.tolist() == cols.tolist() == [-1, -1, -1, -1] diff --git a/tests/test_package.py b/tests/test_package.py index b18e148..f22fcee 100644 --- a/tests/test_package.py +++ b/tests/test_package.py @@ -1,7 +1,42 @@ from __future__ import annotations +import ast +from pathlib import Path + import ingv_shakemap +SRC = Path(ingv_shakemap.__file__).parent + +#: Sister libraries, Limen and limen-core. limen-core pins all of them: if one +#: imported another, it would get a circular dependency and pins in conflict. +FORBIDDEN = { + "copernicus_ems", + "dpc_radar", + "effis_client", + "egms_client", + "firms_client", + "fwi_chain", + "glofas_ewds", + "ispra_idrogeo", + "limen", + "limen_core", + "rainfall_thresholds", +} + def test_version_is_exposed() -> None: assert ingv_shakemap.__version__ + + +def test_the_package_imports_no_sister_library() -> None: + found = [] + for path in SRC.rglob("*.py"): + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): + if isinstance(node, ast.Import): + names = [a.name for a in node.names] + elif isinstance(node, ast.ImportFrom): + names = [node.module or ""] + else: + continue + found += [f"{path.name}: {n}" for n in names if n.split(".")[0] in FORBIDDEN] + assert found == [] diff --git a/tests/test_shaken_points.py b/tests/test_shaken_points.py new file mode 100644 index 0000000..61c059b --- /dev/null +++ b/tests/test_shaken_points.py @@ -0,0 +1,101 @@ +"""`shaken_points` against Limen's `celle_scosse`, on fixed inputs. + +The reference below is Limen's code, frozen from +``src/limen/integrations/ingv/shakemap_grid.py`` at Limen commit ``89e1932`` +(the file last changed in ``c5e3519``). It is copied here, not imported: the +library's tests do not depend on Limen. +""" + +from __future__ import annotations + +from collections.abc import Sequence + +import numpy as np +import pytest +from conftest import make_grid_xml + +from ingv_shakemap import GridError, ShakeGrid, parse_grid, shaken_points + + +def _limen_celle_scosse[K]( + griglia: ShakeGrid, + celle: Sequence[tuple[K, float, float]], + pga_min_g: float, +) -> list[tuple[K, float]]: + if not celle: + return [] + lons = np.fromiter((c[1] for c in celle), dtype=float, count=len(celle)) + lats = np.fromiter((c[2] for c in celle), dtype=float, count=len(celle)) + pga = griglia.sample_g("PGA", lons, lats) + scosse = np.flatnonzero(pga >= pga_min_g) + return [(celle[int(i)][0], float(pga[i])) for i in scosse] + + +def _points(n: int, seed: int) -> list[tuple[str, float, float]]: + """Points in and around the 6 x 5 grid, about a third of them outside.""" + rng = np.random.default_rng(seed) + lons = rng.uniform(13.98, 14.07, n) + lats = rng.uniform(38.94, 39.02, n) + return [ + (f"c{i}", float(lon), float(lat)) + for i, (lon, lat) in enumerate(zip(lons, lats, strict=True)) + ] + + +@pytest.mark.parametrize("pga_units", ["%g", "pctg", "g"]) +@pytest.mark.parametrize("min_pga_g", [0.0, 0.05, 0.11, 0.23, 0.45, 50.0]) +def test_parity_with_limen_on_fixed_points(pga_units: str, min_pga_g: float) -> None: + grid = parse_grid(make_grid_xml(nlon=6, nlat=5, pga_units=pga_units)) + points = _points(500, seed=284) + got = shaken_points(grid, points, min_pga_g) + assert got == _limen_celle_scosse(grid, points, min_pga_g) + + +def test_parity_is_not_vacuous() -> None: + grid = parse_grid(make_grid_xml(nlon=6, nlat=5)) + points = _points(500, seed=284) + assert 0 < len(shaken_points(grid, points, 0.23)) < len(shaken_points(grid, points, 0.0)) < 500 + + +def test_parity_with_limen_on_ties_and_no_points() -> None: + grid = parse_grid(make_grid_xml(step=0.5, lon_min=0.0, lat_max=10.0)) + points = [(i, x, 10.0) for i, x in enumerate((0.25, 0.75, 1.25, -0.25, -0.26))] + assert shaken_points(grid, points, 0.0) == _limen_celle_scosse(grid, points, 0.0) + assert shaken_points(grid, [], 0.1) == _limen_celle_scosse(grid, [], 0.1) == [] + + +def test_keeps_points_at_or_above_the_threshold_in_input_order() -> None: + grid = parse_grid(make_grid_xml()) + # PGA = 10*row + col percent of g: 0.23 g, 0.11 g, 0.0 g, and one outside. + points = [("a", 14.03, 38.98), ("b", 14.01, 38.99), ("c", 14.0, 39.0), ("out", 15.0, 39.0)] + got = shaken_points(grid, points, 0.11) + assert [k for k, _ in got] == ["a", "b"] + assert [v for _, v in got] == pytest.approx([0.23, 0.11]) + assert [k for k, _ in shaken_points(grid, points, 0.0)] == ["a", "b", "c"] + assert shaken_points(grid, points, 0.5) == [] + + +def test_bilinear_reads_between_grid_points() -> None: + grid = parse_grid(make_grid_xml()) + points = [("mid", 14.005, 38.995)] + ((key, pga),) = shaken_points(grid, points, 0.0, method="bilinear") + assert key == "mid" and pga == pytest.approx(0.055) + assert shaken_points(grid, points, 0.0) != shaken_points(grid, points, 0.0, method="bilinear") + + +def test_a_grid_without_pga_in_g_is_refused() -> None: + points = [("a", 14.0, 39.0)] + bad_units = parse_grid(make_grid_xml(pga_units="m/s2")) + no_pga = parse_grid(make_grid_xml().replace(b'name="PGA"', b'name="XGA"')) + with pytest.raises(GridError, match="percent of g"): + shaken_points(bad_units, points, 0.1) + with pytest.raises(GridError, match="no 'PGA' column"): + shaken_points(no_pga, points, 0.1) + with pytest.raises(GridError, match="percent of g"): + bad_units.require_g() + with pytest.raises(GridError, match="no 'PGA' column"): + no_pga.require_g("PGA") + with pytest.raises(GridError, match="percent of g"): + parse_grid(make_grid_xml()).require_g("PGV") + parse_grid(make_grid_xml()).require_g() + parse_grid(make_grid_xml(pga_units="g")).require_g("PGA") diff --git a/uv.lock b/uv.lock index 1be66a1..480ecb1 100644 --- a/uv.lock +++ b/uv.lock @@ -442,7 +442,7 @@ wheels = [ [[package]] name = "ingv-shakemap" -version = "0.2.0" +version = "0.3.0" source = { editable = "." } dependencies = [ { name = "httpx" },