Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

fix(map): fail loudly on bad precip stations, land-only hex precip, hex-biome acceptance test

eyalgolan3c94b8e8f052
diff --git a/docs/superpowers/plans/2026-10-09-statecraft-m0-m2.md b/docs/superpowers/plans/2026-10-09-statecraft-m0-m2.md
index 1b74a17fa..8b9deebc8 100644
--- a/docs/superpowers/plans/2026-10-09-statecraft-m0-m2.md
+++ b/docs/superpowers/plans/2026-10-09-statecraft-m0-m2.md
@@ -5488,8 +5488,9 @@ if __name__ == "__main__":
- [ ] **Step 4: Run the tests to verify they pass.**
Run: the shared test command.
-Expected: `73 passed` (44 when Task 22 first landed. Task 24's fix rounds added the Dead Sea basin / Arava biome cases,
-the precipitation rule, the CHELSA clip, IMS normals, bias-correction, real-place, station-reproduction and determinism tests.)
+Expected: `88 passed` (44 when Task 22 first landed. Task 24's fix rounds added the Dead Sea basin / Arava biome cases,
+the precipitation rule, the CHELSA clip, IMS normals, bias-correction, bad-station, land-only hex precipitation,
+real-place (field and committed hex biome), station-reproduction and determinism tests.)
- [ ] **Step 5: Render the image and check the geography by eye.** This is the M2 gate. Do not accept the map data until every item passes.
diff --git a/tools/README.md b/tools/README.md
index 894604bbe..b6a095c19 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -19,7 +19,7 @@ Run from the repo root; this installs every pinned dependency (rasterio included
uv run --with pytest==9.1.1 --with rasterio==1.5.2 --with numpy==2.5.3 --with pyyaml==6.0.3 --with pillow==12.3.0 --with requests==2.32.5 pytest tools/tests -q
```
-Expected: `73 passed`. Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
+Expected: `88 passed`. Omitting a dependency (e.g. rasterio) silently drops tests or fails collection.
## Required attribution (Copernicus DEM licence, modified data)
diff --git a/tools/hexgrid.py b/tools/hexgrid.py
index c3d48ec9a..ddbeb073a 100644
--- a/tools/hexgrid.py
+++ b/tools/hexgrid.py
@@ -16,10 +16,11 @@ Biome rules, first match wins (per hex, over the heightmap pixels / precipitatio
basin and northern Arava), otherwise "valley" (Jordan rift, Beit She'an, Hula)
4 mountains median >= 700 m
5 desert mean annual precipitation < 200 mm (the standard arid boundary): the mean, over the clip cells
- whose centres fall inside the hex, of CHELSA V2.1 bio12 (1981-2010, content/map/precip_bio12.*)
+ whose centres fall inside the hex and on land (the heightmap there is not sea, as in rule 1; CHELSA
+ is extrapolated over the sea), of CHELSA V2.1 bio12 (1981-2010, content/map/precip_bio12.*)
bias-corrected with IMS rain-gauge normals (1981-2010, content/map/precip_stations.json): IDW
- (power 2) of log(station / CHELSA) applied as a multiplicative correction. A hex with no valid cell
- uses the nearest valid cell to its centre. Inputs are written by tools/precip_clip.py and
+ (power 2) of log(station / CHELSA) applied as a multiplicative correction. A hex with no valid land
+ cell uses the nearest valid cell to its centre. Inputs are written by tools/precip_clip.py and
tools/ims_normals.py; this build reads only the committed files
6 hills median >= 200 m
7 coastal_plain everything else
@@ -42,6 +43,7 @@ DEAD_SEA_NORTH_TIP_LAT = 31.77
ARID_MM = 200.0 # mean annual precipitation below which land is desert (arid)
PRECIP_NODATA = 65535
STATIONS_NAME = "precip_stations.json"
+SEA_EPS_M = 0.5 # Copernicus sea is exactly 0 m
IDW_MIN_D2_KM2 = 1e-6 # a station on a cell centre gets (almost) all the weight there
HEX_SIZE_KM = 5.0 # circumradius (centre to corner)
SQRT3 = math.sqrt(3)
@@ -139,6 +141,21 @@ def load_stations(d: Path) -> list[dict]:
return json.loads((Path(d) / STATIONS_NAME).read_text())["stations"]
+def station_log_ratio(i: int, s: dict, pr: dict) -> float:
+ """log(station mm / CHELSA mm at the station). Raises ValueError rather than letting a NaN or infinite ratio
+ spread through the IDW to every cell."""
+ ids = s.get("ids") or ([s["id"]] if "id" in s else None)
+ who = f"station {ids} ({s.get('name', '?')})" if ids else f"station index {i} ({s.get('name', '?')})"
+ chelsa = precip_at(s["lon"], s["lat"], pr)
+ if not chelsa > 0: # NaN or <= 0
+ raise ValueError(f"{who}: CHELSA value at the station is {chelsa}; need a finite value > 0")
+ with np.errstate(divide="ignore", invalid="ignore"):
+ lr = float(np.log(s["mm"] / chelsa))
+ if not math.isfinite(lr):
+ raise ValueError(f"{who}: station/CHELSA ratio {s['mm']}/{chelsa} has log {lr}; not finite")
+ return lr
+
+
def correct_precip(pr: dict, stations: list[dict]) -> dict:
"""Bias-correct the CHELSA field with station normals: at each station ratio = station mm / CHELSA mm (bilinear);
log(ratio) is interpolated to every cell by inverse-distance weighting (power 2, km on the map projection) and
@@ -149,7 +166,7 @@ def correct_precip(pr: dict, stations: list[dict]) -> dict:
mid = pr["meta"]["lat1"] - pr["meta"]["height"] * pr["meta"]["cell_deg"] / 2
kx = KM_PER_DEG_LON_EQ * math.cos(math.radians(mid))
sx = np.array([s["lon"] for s in stations]); sy = np.array([s["lat"] for s in stations])
- log_ratio = np.log(np.array([s["mm"] / precip_at(s["lon"], s["lat"], pr) for s in stations]))
+ log_ratio = np.array([station_log_ratio(i, s, pr) for i, s in enumerate(stations)])
num = np.zeros(lons.shape); den = np.zeros(lons.shape)
for x, y, lr in zip(sx, sy, log_ratio): # station by station: fixed order, modest memory
w = 1.0 / np.maximum(((lons - x) * kx) ** 2 + ((lats - y) * KM_PER_DEG_LAT) ** 2, IDW_MIN_D2_KM2)
@@ -191,12 +208,25 @@ def nearest_precip(lon: float, lat: float, pr: dict) -> float:
return float(pr["mm"][ok][np.argmin(d)])
-def hex_precip_means(pr: dict, meta: dict, size: float) -> dict:
- """Mean precipitation of the valid clip cells whose centres fall inside each hex, keyed (q, r)."""
+def is_sea(elev_m: np.ndarray) -> np.ndarray:
+ """Copernicus sea is exactly 0 m: the sea test of biome rule 1."""
+ return np.abs(elev_m) < SEA_EPS_M
+
+
+def hex_precip_means(pr: dict, elev: np.ndarray, meta: dict, size: float) -> dict:
+ """Mean precipitation of the valid clip cells whose centres fall inside each hex and on land, keyed (q, r).
+ A cell is land when the nearest heightmap pixel to its centre (clamped to the map) is not sea: over the sea
+ CHELSA is extrapolated, so sea cells would bias shore hexes."""
lons, lats = precip_cell_centres(pr)
- ok = ~np.isnan(pr["mm"])
- x = (lons[ok] - meta["lon0"]) * km_per_deg_lon(meta)
- y = (meta["lat1"] - lats[ok]) * KM_PER_DEG_LAT
+ h, w = elev.shape
+ width_km = (meta["lon1"] - meta["lon0"]) * km_per_deg_lon(meta)
+ length_km = (meta["lat1"] - meta["lat0"]) * KM_PER_DEG_LAT
+ x = (lons - meta["lon0"]) * km_per_deg_lon(meta)
+ y = (meta["lat1"] - lats) * KM_PER_DEG_LAT
+ col = np.clip(np.round(x / width_km * (w - 1)), 0, w - 1).astype(int)
+ row = np.clip(np.round(y / length_km * (h - 1)), 0, h - 1).astype(int)
+ ok = ~np.isnan(pr["mm"]) & ~is_sea(elev[row, col])
+ x, y = x[ok], y[ok]
q, r = point_to_hex(x, y, size)
sums, counts = {}, {}
for k, v in zip(zip(q, r), pr["mm"][ok]):
@@ -214,7 +244,7 @@ def load_elevation(map_dir: Path) -> tuple[np.ndarray, dict]:
def build(map_dir: Path, size: float = HEX_SIZE_KM, precip_dir: Path = PRECIP_DIR) -> dict:
elev, meta = load_elevation(map_dir)
pr = load_corrected_precip(precip_dir)
- precip = hex_precip_means(pr, meta, size)
+ precip = hex_precip_means(pr, elev, meta, size)
h, w = elev.shape
width_km = (meta["lon1"] - meta["lon0"]) * km_per_deg_lon(meta)
length_km = (meta["lat1"] - meta["lat0"]) * KM_PER_DEG_LAT
@@ -235,7 +265,7 @@ def build(map_dir: Path, size: float = HEX_SIZE_KM, precip_dir: Path = PRECIP_DI
lon = meta["lon0"] + cx / km_per_deg_lon(meta)
lat = meta["lat1"] - cy / KM_PER_DEG_LAT
mm = precip.get((hq, hr))
- st = {"sea_share": float(np.mean(np.abs(v) < 0.5)), "water_share": water_share(v),
+ st = {"sea_share": float(np.mean(is_sea(v))), "water_share": water_share(v),
"median": float(np.median(v)), "precip_mm": mm if mm is not None else nearest_precip(lon, lat, pr)}
biome = classify(st, lat)
hexes.append({"q": hq, "r": hr, "lon": round(lon, 5), "lat": round(lat, 5), "elev_m": round(st["median"], 1),
diff --git a/tools/tests/test_hexgrid.py b/tools/tests/test_hexgrid.py
index 0277052e6..cd4abaef6 100644
--- a/tools/tests/test_hexgrid.py
+++ b/tools/tests/test_hexgrid.py
@@ -110,6 +110,31 @@ def test_build_marks_dry_land_desert_wherever_it_is(tmp_path):
assert south and all(x["biome"] == "desert" for x in south)
+def test_hex_precip_averages_only_land_cells(tmp_path):
+ # West half sea (0 m), east half land at 300 m. CHELSA is "extrapolated" to a dry 20 mm over the sea and is
+ # 220 mm over land. The shore land hexes hold ~18% sea cells, so counting them gives ~184 mm (desert); with
+ # land cells only every land hex is 220 mm -> hills.
+ n = 201
+ elev = np.zeros((n, n), dtype="float32")
+ elev[:, n // 2:] = 300.0
+ meta = {"width": n, "height": n, "lon0": 35.0, "lon1": 35.5, "lat0": 32.2, "lat1": 32.7,
+ "elev_min_m": 0.0, "elev_max_m": 300.0}
+ (tmp_path / "heightmap.json").write_text(json.dumps(meta))
+ np.round(elev / 300.0 * 65535).astype("<u2").tofile(tmp_path / "heightmap.r16")
+ cell = 0.01
+ w = round(0.5 / cell) + 2; h = round(0.5 / cell) + 2
+ lons = 35.0 - cell + (np.arange(w) + 0.5) * cell
+ mm = np.where(lons[None, :] < 35.25, 20.0, 220.0) * np.ones((h, 1))
+ hg.write_precip(mm, 35.0 - cell, 32.7 + cell, cell, tmp_path, {"source": "synthetic"})
+ write_no_stations(tmp_path)
+ out = hg.build(tmp_path, 5.0, precip_dir=tmp_path)
+ land = [x for x in out["hexes"] if x["land"]]
+ coastal = [x for x in land if x["lon"] < 35.28] # land hexes touching the shore
+ assert coastal, "fixture has no coastal land hex"
+ assert land and all(x["biome"] == "hills" for x in land), [(x["q"], x["r"], x["biome"]) for x in land
+ if x["biome"] != "hills"]
+
+
# --- Station bias correction (synthetic) ---
def test_correction_scales_field_by_idw_of_station_log_ratio(tmp_path):
@@ -126,6 +151,25 @@ def test_correction_scales_field_by_idw_of_station_log_ratio(tmp_path):
assert hg.correct_precip(pr, [])["mm"] is not pr["mm"] and np.array_equal(hg.correct_precip(pr, [])["mm"], pr["mm"])
[email protected]("bad, station_mm, label", [
+ (np.nan, 300.0, "nan"), # CHELSA has no data at the station
+ (0.0, 300.0, "0"), # CHELSA zero: ratio would be infinite
+ (-5.0, 300.0, "-5"), # CHELSA negative
+ (400.0, 0.0, "ratio"), # station 0 mm: log(0) is not finite
+])
+def test_correction_fails_loudly_on_a_bad_station(tmp_path, bad, station_mm, label):
+ mm = np.full((4, 4), 400.0)
+ mm[0, 0] = bad # the cell holding the second station
+ pr = {"meta": {"lon0": 35.0, "lat1": 32.0, "cell_deg": 0.25, "width": 4, "height": 4}, "mm": mm}
+ st = [{"ids": [7], "name": "OK", "lon": 35.875, "lat": 31.125, "mm": 400.0, "years": 30},
+ {"ids": [246950], "name": "BAD", "lon": 35.125, "lat": 31.875, "mm": station_mm, "years": 30}]
+ with pytest.raises(ValueError, match=f"246950.*{label}"):
+ hg.correct_precip(pr, st)
+ st[1].pop("ids") # no id: the message names the index
+ with pytest.raises(ValueError, match=f"index 1.*{label}"):
+ hg.correct_precip(pr, st)
+
+
# --- Real inputs: CHELSA clip + IMS station normals (content/map/precip_*) ---
MAP_INPUTS = ROOT / "content" / "map"
HAVE_REAL = (MAP_INPUTS / "precip_bio12.json").exists() and (MAP_INPUTS / "precip_stations.json").exists()
@@ -176,3 +220,17 @@ def test_build_is_deterministic(tmp_path):
b = json.dumps(hg.build(hg.MAP_DIR), separators=(",", ":"))
assert a == b
assert a == (ROOT / "content" / "map" / "hexes.json").read_text(), "hexes.json is stale: run uv run tools/hexgrid.py"
+
+
+HEXES = ROOT / "content" / "map" / "hexes.json"
+
+
[email protected]("place, dry", [("eilat", True), ("mitzpe_ramon", True), ("dimona", True), ("arad", True),
+ ("tel_aviv", False), ("ashkelon", False), ("gaza_city", False),
+ ("jerusalem", False), ("hebron", False), ("haifa", False)])
+def test_committed_hex_biome_matches_arid_boundary(place, dry):
+ grid = json.loads(HEXES.read_text())
+ lon, lat = PLACES[place]
+ q, r = hg.settlement_hex(lon, lat, grid)
+ biome = next(h["biome"] for h in grid["hexes"] if (h["q"], h["r"]) == (q, r))
+ assert (biome == "desert") == dry, f"{place} hex ({q}, {r}) is {biome}"