Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
3 changes: 2 additions & 1 deletion src/ingv_shakemap/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -47,4 +47,5 @@
"parse_stations",
"shakemap_grid_url",
"shakemap_product_url",
"shaken_points",
]
89 changes: 83 additions & 6 deletions src/ingv_shakemap/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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]
Expand All @@ -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:
Expand All @@ -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
Expand Down Expand Up @@ -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",
]
110 changes: 110 additions & 0 deletions tests/test_grid_points.py
Original file line number Diff line number Diff line change
@@ -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]
35 changes: 35 additions & 0 deletions tests/test_package.py
Original file line number Diff line number Diff line change
@@ -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 == []
Loading