From 2d825eaa29bae77659195cbacd593d3b020751e8 Mon Sep 17 00:00:00 2001 From: Sebastian Cadavid Sanchez Date: Fri, 27 Nov 2026 07:26:13 -0600 Subject: [PATCH 1/3] refuse extra histclim rows and record skipped regions --- CHANGELOG.md | 15 ++++ cil_regionalization/backends/bigquery.py | 6 +- cil_regionalization/backends/local.py | 14 +++- cil_regionalization/merge.py | 6 ++ cil_regionalization/pipelines/montecarlo.py | 27 ++++++- cil_regionalization/regions.py | 44 +++++++---- tests/integration/test_local_backend.py | 26 +++++++ tests/integration/test_montecarlo_pipeline.py | 78 +++++++++++++++++++ tests/unit/test_regions.py | 6 ++ 9 files changed, 199 insertions(+), 23 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2bb766c..a77538b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,21 @@ ## Unreleased +**A histclim file with rows its leaf does not have is refused, naming +the first row and the regions or years the file alone has.** The two +are one projection under two climates, so a row in one alone means the +other is incomplete. The rows were dropped with nothing said, while a +leaf row the histclim file lacked was refused already. + +**A region left out for an invalid geometry is recorded as skipped, +apart from the regions repaired.** Under `on_invalid_geometry = "skip"` +the manifest listed the regions it left out as `repaired_geometry_regions`. +It now lists them as `skipped_invalid_geometry_regions`, with +`skipped_invalid_geometry_count`, and the source units as +`skipped_invalid_geometry_source_units`, and `RegionSet` carries them as +`skipped_invalid_ids`. In the four published artifacts checked, every +region listed as repaired has its rows. + **A model takes the row of its own name in a model weights table, letter for letter, or the row declared for it, and a model with neither is refused.** Before, the library dropped `surrogate_` from the diff --git a/cil_regionalization/backends/bigquery.py b/cil_regionalization/backends/bigquery.py index c02ab94..ef34e6a 100644 --- a/cil_regionalization/backends/bigquery.py +++ b/cil_regionalization/backends/bigquery.py @@ -55,7 +55,7 @@ from cil_regionalization.grid import GridSpec from cil_regionalization.manifest import build_manifest, record_schema from cil_regionalization.nearest_cell import find_missing_regions, synthesize_rows -from cil_regionalization.regions import RegionSet +from cil_regionalization.regions import RegionSet, _geometry_record from cil_regionalization.schema import OutputSchema from cil_regionalization.validate import check_grid_invariants, check_sum_to_one from cil_regionalization.weights import WeightSpec @@ -1118,9 +1118,7 @@ def _assemble_result( manifest.inputs["regions_table"] = regions.table if regions.source_uri is not None: manifest.inputs["regions_path"] = regions.source_uri - if regions.repaired_ids: - manifest.extra["repaired_geometry_count"] = len(regions.repaired_ids) - manifest.extra["repaired_geometry_regions"] = list(regions.repaired_ids) + manifest.extra.update(_geometry_record(regions)) for w in non_area: if w.table is not None: manifest.inputs[f"weight:{w.name}"] = w.table diff --git a/cil_regionalization/backends/local.py b/cil_regionalization/backends/local.py index b9fe9a4..50df033 100644 --- a/cil_regionalization/backends/local.py +++ b/cil_regionalization/backends/local.py @@ -69,7 +69,7 @@ from cil_regionalization.grid import GridSpec from cil_regionalization.manifest import build_manifest, hash_file, record_schema from cil_regionalization.nearest_cell import find_missing_regions, synthesize_rows -from cil_regionalization.regions import RegionSet +from cil_regionalization.regions import RegionSet, _geometry_record from cil_regionalization.schema import OutputSchema, SourceUnits from cil_regionalization.validate import ( check_grid_invariants, @@ -215,9 +215,7 @@ def _compute_grid( ) manifest.inputs.update(_input_checksums(regions, weights)) manifest.extra["min_segment_area"] = drop_stats - if regions.repaired_ids: - manifest.extra["repaired_geometry_count"] = len(regions.repaired_ids) - manifest.extra["repaired_geometry_regions"] = list(regions.repaired_ids) + manifest.extra.update(_geometry_record(regions)) manifest.extra.update(_unknown_id_record(regions)) manifest.timing_seconds["compute_total"] = time.perf_counter() - t0 @@ -417,8 +415,16 @@ def _compute_polygons( manifest.extra.update(_unknown_id_record(regions)) if regions.repaired_ids: manifest.extra["repaired_geometry_regions"] = regions.repaired_ids + if regions.skipped_invalid_ids: + manifest.extra["skipped_invalid_geometry_regions"] = ( + regions.skipped_invalid_ids + ) if source_set.repaired_ids: manifest.extra["repaired_geometry_source_units"] = source_set.repaired_ids + if source_set.skipped_invalid_ids: + manifest.extra["skipped_invalid_geometry_source_units"] = ( + source_set.skipped_invalid_ids + ) if near_edge_regions: manifest.extra["near_domain_edge_regions"] = near_edge_regions if near_edge_sources: diff --git a/cil_regionalization/merge.py b/cil_regionalization/merge.py index 58aa649..8c79eaa 100644 --- a/cil_regionalization/merge.py +++ b/cil_regionalization/merge.py @@ -168,6 +168,12 @@ def _build_merged_manifest( "repaired_geometry_regions": supplement.get("extra", {}).get( "repaired_geometry_regions", [] ), + "skipped_invalid_geometry_count": supplement.get("extra", {}).get( + "skipped_invalid_geometry_count", 0 + ), + "skipped_invalid_geometry_regions": supplement.get("extra", {}).get( + "skipped_invalid_geometry_regions", [] + ), "bq_compute_location": supplement.get("extra", {}).get( "bq_compute_location" ), diff --git a/cil_regionalization/pipelines/montecarlo.py b/cil_regionalization/pipelines/montecarlo.py index 6a2f3ea..6a91d72 100644 --- a/cil_regionalization/pipelines/montecarlo.py +++ b/cil_regionalization/pipelines/montecarlo.py @@ -2409,8 +2409,9 @@ def _subtract_leaf( for row, in a float64 value column. In the projection trees this is the scenario file minus its histclim sibling, before any weighting. Raises if the two files differ in columns, if a key repeats in - either, or if a row of ``frame`` has no match in the file. Rows of - the file with no match in ``frame`` are dropped. + either, or if a row of either has no match in the other. They are + one projection under two climates, so a row in one alone means the + other is incomplete. """ other = _read_leaf(path, data_cfg, artifact) keys = [c for c in frame.columns if c != data_cfg.value_col] @@ -2427,6 +2428,28 @@ def _subtract_leaf( f"subtract file {path} covers {len(merged)} of {len(frame)} " f"rows; the two files must cover the same regions and years" ) + if len(other) != len(merged): + # each row of the file matched at most one row of frame + flagged = other[keys].merge(frame[keys], on=keys, how="left", indicator=True) + alone = flagged.loc[flagged["_merge"] == "left_only", keys] + first = { + k: v.item() if hasattr(v, "item") else v for k, v in alone.iloc[0].items() + } + only = [] + for key in keys: + values = sorted(set(alone[key]) - set(frame[key]), key=str) + if values: + shown = ", ".join(str(v) for v in values[:3]) + more = f" and {len(values) - 3} more" if len(values) > 3 else "" + only.append(f"{key} {shown}{more}") + where = f" The subtract file alone has {'; '.join(only)}." if only else "" + raise ValueError( + f"subtract file {path} has {len(alone)} " + f"{'row' if len(alone) == 1 else 'rows'} the leaf does not " + f"have (first: {first}); the two files must cover the same " + f"regions and years.{where} They are one projection under two " + f"climates, so a row in one alone means the other is incomplete." + ) merged[data_cfg.value_col] = merged[data_cfg.value_col].astype("float64") - merged[ f"{data_cfg.value_col}_subtract" ].astype("float64") diff --git a/cil_regionalization/regions.py b/cil_regionalization/regions.py index 6db2961..553916d 100644 --- a/cil_regionalization/regions.py +++ b/cil_regionalization/regions.py @@ -41,12 +41,15 @@ class RegionSet: on_invalid_geometry: InvalidGeomPolicy table: str | None = None gdf: gpd.GeoDataFrame | None = None - # Filled in by from_config for path-loaded gdfs whose geometries were - # repaired by `shapely.make_valid` under the `repair` policy. The - # backends record this in the manifest under `repaired_geometry_regions` - # so a future reader of the parquet knows which regions' shapes were - # mutated relative to the source. + # Filled in by from_config for path-loaded gdfs. The ids whose + # geometries `shapely.make_valid` repaired under the "repair" policy, + # which stay with their shapes changed, and the ids of the invalid + # geometries the "skip" policy left out. The backends record them + # apart in the manifest, under `repaired_geometry_regions` and + # `skipped_invalid_geometry_regions`, since a region left out is not a + # region repaired. repaired_ids: list[dict[str, Any]] = field(default_factory=list) + skipped_invalid_ids: list[dict[str, Any]] = field(default_factory=list) # Values listed in `regions.keep` and `regions.drop` that match no row # of the file as read, by filter column. The local backend applies # `on_unknown_id` to them and records them in the manifest. @@ -74,7 +77,7 @@ def from_config(cls, cfg: RegionsConfig) -> "RegionSet": # downstream geodesic / spatial ops have a definite frame. if gdf.crs is None: gdf = gdf.set_crs("EPSG:4326") - gdf, repaired = _handle_invalid_geometries( + gdf, repaired, skipped = _handle_invalid_geometries( gdf, cfg.on_invalid_geometry, list(cfg.id_fields) ) gdf = gdf.reset_index(drop=True) @@ -84,6 +87,7 @@ def from_config(cls, cfg: RegionsConfig) -> "RegionSet": table=None, gdf=gdf, repaired_ids=repaired, + skipped_invalid_ids=skipped, unknown_keep_ids=unknown_keep, unknown_drop_ids=unknown_drop, source_uri=str(source_uri), @@ -209,18 +213,32 @@ def _absent_values(column, listed: list[Any]) -> list[str]: ) +def _geometry_record(regions: "RegionSet") -> dict[str, Any]: + """The manifest entries of the invalid region geometries, the repaired + and the skipped apart, each only if there are any.""" + out: dict[str, Any] = {} + if regions.repaired_ids: + out["repaired_geometry_count"] = len(regions.repaired_ids) + out["repaired_geometry_regions"] = list(regions.repaired_ids) + if regions.skipped_invalid_ids: + out["skipped_invalid_geometry_count"] = len(regions.skipped_invalid_ids) + out["skipped_invalid_geometry_regions"] = list(regions.skipped_invalid_ids) + return out + + def _handle_invalid_geometries( gdf: gpd.GeoDataFrame, policy: InvalidGeomPolicy, id_fields: list[str], -) -> tuple[gpd.GeoDataFrame, list[dict[str, Any]]]: - """Apply the invalid-geometry policy. Returns ``(gdf, bad_ids)``, the - ids of the invalid geometries whether they were repaired or skipped. - Raises under "error" if any geometry is invalid.""" +) -> tuple[gpd.GeoDataFrame, list[dict[str, Any]], list[dict[str, Any]]]: + """Apply the invalid-geometry policy. Returns ``(gdf, repaired, + skipped)``, the ids of the invalid geometries that were repaired and + kept, and of those left out. One of the two is always empty. Raises + under "error" if any geometry is invalid.""" invalid_mask = ~gdf.geometry.is_valid n_invalid = int(invalid_mask.sum()) if n_invalid == 0: - return gdf, [] + return gdf, [], [] bad_ids = gdf.loc[invalid_mask, id_fields].to_dict(orient="records") if policy == "repair": @@ -233,12 +251,12 @@ def _handle_invalid_geometries( ) out = gdf.copy() out = out.set_geometry(repaired) - return out, bad_ids + return out, bad_ids, [] if policy == "skip": logger.info( "regions: skipping %d invalid geometries; ids=%s", n_invalid, bad_ids ) - return gdf.loc[~invalid_mask].copy(), bad_ids + return gdf.loc[~invalid_mask].copy(), [], bad_ids raise ValueError( f"regions: {n_invalid} invalid geometries with on_invalid_geometry='error'; " f"ids={bad_ids}" diff --git a/tests/integration/test_local_backend.py b/tests/integration/test_local_backend.py index ae27f9f..bf204fd 100644 --- a/tests/integration/test_local_backend.py +++ b/tests/integration/test_local_backend.py @@ -652,12 +652,38 @@ def test_repaired_region_recorded(self, synthetic_raster, tmp_path): assert extra["repaired_geometry_count"] == 1 assert extra["repaired_geometry_regions"] == [{"region_id": "bad"}] + def test_a_skipped_region_is_recorded_as_skipped_not_repaired( + self, synthetic_raster, tmp_path + ): + """It went red on the manifest that listed it under the repaired + regions although it has no row in the weights.""" + import geopandas as gpd + from shapely.geometry import Polygon, box + + bowtie = Polygon([(0, 0), (1, 1), (1, 0), (0, 1), (0, 0)]) + gdf = gpd.GeoDataFrame( + {"region_id": ["bad", "good"], "geometry": [bowtie, box(2, 2, 3, 3)]}, + crs="EPSG:4326", + ) + regions_path = tmp_path / "invalid.parquet" + gdf.to_parquet(regions_path) + raw = _cfg(regions_path, synthetic_raster, tmp_path / "out").model_dump() + raw["regions"]["on_invalid_geometry"] = "skip" + result = _run(Config.model_validate(raw)) + extra = result.manifest.extra + assert "repaired_geometry_count" not in extra + assert "repaired_geometry_regions" not in extra + assert extra["skipped_invalid_geometry_count"] == 1 + assert extra["skipped_invalid_geometry_regions"] == [{"region_id": "bad"}] + assert set(result.frame["region_id"]) == {"good"} + def test_nothing_recorded_without_repairs( self, three_region_geoparquet, synthetic_raster, tmp_path ): result = _run(_cfg(three_region_geoparquet, synthetic_raster, tmp_path / "out")) assert "repaired_geometry_count" not in result.manifest.extra assert "repaired_geometry_regions" not in result.manifest.extra + assert "skipped_invalid_geometry_count" not in result.manifest.extra class TestUnknownIds: diff --git a/tests/integration/test_montecarlo_pipeline.py b/tests/integration/test_montecarlo_pipeline.py index 6888ba2..09e2a91 100644 --- a/tests/integration/test_montecarlo_pipeline.py +++ b/tests/integration/test_montecarlo_pipeline.py @@ -1286,6 +1286,84 @@ def test_difference_flows_through_to_statistics(self, weights_dir, tmp_path): t1 = result.stats[result.stats["target_id"] == "T1"] assert (t1["value"].round(9) == 10.5).all() + def _refused(self, weights_dir, tmp_path, edit) -> str: + tree = tmp_path / "tree" + _build_subtract_tree(tree, _LEVELS) + for name in ("damages.parquet", "histclim.parquet"): + path = tree / "k0" / "z1" / name + frame = edit(name, pd.read_parquet(path)) + frame.to_parquet(path, index=False) + raw = _pipeline_cfg( + weights_dir, tree, tmp_path / "out", levels=_LEVELS + ).model_dump() + raw["tree"]["subtract_filename"] = "histclim.parquet" + with pytest.raises(ValueError, match="partial run") as error: + run_pipeline(MonteCarloPipelineConfig.model_validate(raw)) + assert "5 of 6 leaves succeeded" in str(error.value) + assert "k0/z1" in str(error.value) + assert not (tmp_path / "out" / "statistics.parquet").exists() + return str(error.value) + + def test_a_histclim_file_with_a_year_more_is_refused_by_name( + self, weights_dir, tmp_path + ): + """The leaf lacks a year its histclim sibling has. Its row was + dropped with nothing said, and this went red on that.""" + + def edit(name, frame): + if name == "damages.parquet": + return frame + extra = frame[frame["year"] == 2081].assign(year=2082) + return pd.concat([frame, extra], ignore_index=True) + + message = self._refused(weights_dir, tmp_path, edit) + assert ( + "has 2 rows the leaf does not have (first: {'unit_id': 'u1', " + "'year': 2082}); the two files must cover the same regions and " + "years. The subtract file alone has year 2082." + ) in message + + def test_a_histclim_file_with_a_region_more_is_refused_by_name( + self, weights_dir, tmp_path + ): + def edit(name, frame): + if name == "damages.parquet": + return frame + extra = frame[frame["unit_id"] == "u1"].assign(unit_id="u9") + return pd.concat([frame, extra], ignore_index=True) + + message = self._refused(weights_dir, tmp_path, edit) + assert "has 4 rows the leaf does not have" in message + assert "The subtract file alone has unit_id u9." in message + + def test_a_leaf_short_of_one_of_its_rows_is_refused(self, weights_dir, tmp_path): + """Every value of the row is elsewhere in the leaf, so only the + row is named.""" + + def edit(name, frame): + if name == "histclim.parquet": + return frame + gone = (frame["unit_id"] == "u2") & (frame["year"] == 2051) + return frame[~gone] + + message = self._refused(weights_dir, tmp_path, edit) + assert ( + "has 1 row the leaf does not have (first: {'unit_id': 'u2', " + "'year': 2051}); the two files must cover the same regions and " + "years. They are one projection" + ) in message + + def test_a_histclim_file_short_of_a_row_is_refused(self, weights_dir, tmp_path): + """The other way round, which was refused already.""" + + def edit(name, frame): + if name == "damages.parquet": + return frame + return frame.iloc[1:] + + message = self._refused(weights_dir, tmp_path, edit) + assert "covers 7 of 8 rows" in message + def test_missing_subtract_file_counts_as_missing(self, weights_dir, tmp_path): tree = tmp_path / "tree" _build_tree(tree, _LEVELS) # no histclim siblings diff --git a/tests/unit/test_regions.py b/tests/unit/test_regions.py index 7db6bde..fb818ea 100644 --- a/tests/unit/test_regions.py +++ b/tests/unit/test_regions.py @@ -116,6 +116,8 @@ def test_repair_policy_fixes_and_logs(self, tmp_path: Path, caplog): rs = RegionSet.from_config(cfg) assert len(rs) == 2 # both kept assert rs.gdf.geometry.is_valid.all() + assert rs.repaired_ids == [{"region_id": "bad"}] + assert rs.skipped_invalid_ids == [] assert any( "repairing" in r.message and "bad" in r.message for r in caplog.records ) @@ -132,6 +134,10 @@ def test_skip_policy_drops_and_logs(self, tmp_path: Path, caplog): assert len(rs) == 1 kept = next(rs.iter_regions())[0]["region_id"] assert kept == "good" + # left out, not repaired. It went red on the record that listed + # it as repaired. + assert rs.repaired_ids == [] + assert rs.skipped_invalid_ids == [{"region_id": "bad"}] assert any( "skipping" in r.message and "bad" in r.message for r in caplog.records ) From faa6bfbc9ca5c2784c9f16aad0b57f55fc2f31b4 Mon Sep 17 00:00:00 2001 From: Sebastian Cadavid Sanchez Date: Fri, 27 Nov 2026 07:26:13 -0600 Subject: [PATCH 2/3] read and hash a gs:// regions path --- CHANGELOG.md | 7 ++ cil_regionalization/backends/local.py | 7 +- cil_regionalization/generate.py | 11 ++- cil_regionalization/regions.py | 53 +++++++++----- tests/integration/test_local_backend.py | 33 +++++++++ tests/unit/test_regions.py | 92 +++++++++++++++++++++++++ 6 files changed, 182 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a77538b..4851da1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,13 @@ It now lists them as `skipped_invalid_geometry_regions`, with `skipped_invalid_ids`. In the four published artifacts checked, every region listed as repaired has its rows. +**A `gs://` regions path passes the input check, and its bytes are +hashed into the manifest as a local file's are.** The reader took such a +path already, and the check refused it. The manifest had no hash of a +remote regions file. Reading one needs gcsfs, which the `[bigquery]` +extra installs, and a remote file in a format other than Parquet is +copied to a temporary directory first. + **A model takes the row of its own name in a model weights table, letter for letter, or the row declared for it, and a model with neither is refused.** Before, the library dropped `surrogate_` from the diff --git a/cil_regionalization/backends/local.py b/cil_regionalization/backends/local.py index 50df033..620bdb1 100644 --- a/cil_regionalization/backends/local.py +++ b/cil_regionalization/backends/local.py @@ -1084,10 +1084,13 @@ def _input_checksums( regions: RegionSet, weights: list[WeightSpec], ) -> dict[str, str]: - """Hash the regions file and each weight raster for the manifest.""" + """Hash the regions file and each weight raster for the manifest. A + `gs://` regions file has the hash of the bytes it was read from.""" inputs: dict[str, str] = {} path = regions.source_uri - if path is not None and not str(path).startswith("gs://") and Path(path).exists(): + if regions.source_sha256 is not None: + inputs["geometry:regions"] = regions.source_sha256 + elif path is not None and not str(path).startswith("gs://") and Path(path).exists(): inputs["geometry:regions"] = hash_file(path) for w in weights: if w.is_area: diff --git a/cil_regionalization/generate.py b/cil_regionalization/generate.py index fa12cf3..fc1f796 100644 --- a/cil_regionalization/generate.py +++ b/cil_regionalization/generate.py @@ -35,10 +35,15 @@ def __init__(self, report: SumToOneReport, result: WeightsResult): def check_inputs_exist(cfg: Config) -> list[str]: """A message for each input of ``cfg`` that is not on the local disk. - The inputs checked are regions.path, source.path unless it is a - ``gs://`` URI, and each weight raster on the local backend.""" + The inputs checked are regions.path and source.path unless they are + ``gs://`` URIs, which are read and hashed when the run reads them, and + each weight raster on the local backend.""" problems: list[str] = [] - if cfg.regions.path is not None and not Path(cfg.regions.path).exists(): + if ( + cfg.regions.path is not None + and not cfg.regions.path.startswith("gs://") + and not Path(cfg.regions.path).exists() + ): problems.append(f"regions.path does not exist: {cfg.regions.path}") if ( cfg.source is not None diff --git a/cil_regionalization/regions.py b/cil_regionalization/regions.py index 553916d..caa3421 100644 --- a/cil_regionalization/regions.py +++ b/cil_regionalization/regions.py @@ -21,6 +21,8 @@ from __future__ import annotations +import hashlib +import io import logging from dataclasses import dataclass, field from pathlib import Path @@ -58,6 +60,9 @@ class RegionSet: # Resolved on-disk-or-remote URI of the source. For local paths this is # the absolute path; for `gs://` paths it stays a URI. source_uri: str | None = None + # The SHA256 of the bytes read from a `gs://` source, for the manifest, + # which hashes a local file from its path instead. + source_sha256: str | None = None @classmethod def from_config(cls, cfg: RegionsConfig) -> "RegionSet": @@ -69,7 +74,7 @@ def from_config(cls, cfg: RegionsConfig) -> "RegionSet": gdf=None, ) source_uri = cfg.path # type: ignore[assignment] - gdf = _read_regions(source_uri) + gdf, source_sha256 = _read_regions(source_uri) _check_id_fields(gdf, cfg.id_fields) gdf, unknown_keep, unknown_drop = _apply_filters(gdf, cfg.keep, cfg.drop) # Shapefiles without a .prj file lack a CRS; the canonical IR @@ -91,6 +96,7 @@ def from_config(cls, cfg: RegionsConfig) -> "RegionSet": unknown_keep_ids=unknown_keep, unknown_drop_ids=unknown_drop, source_uri=str(source_uri), + source_sha256=source_sha256, ) @property @@ -117,13 +123,15 @@ def iter_regions(self) -> Iterator[tuple[dict[str, Any], Any]]: yield ids, row.geometry -def _read_regions(source: str | Path) -> gpd.GeoDataFrame: - """Read regions from a local path or a `gs://` URI. +def _read_regions(source: str | Path) -> tuple[gpd.GeoDataFrame, str | None]: + """Regions from a local path or a `gs://` URI, with the SHA256 of the + bytes read from a `gs://` one, None for a local path. A ``.parquet`` or ``.geoparquet`` file is read with `gpd.read_parquet` - and anything else with `gpd.read_file`. A remote shapefile and its - companions are copied to a temporary directory and read there. Raises - `FileNotFoundError` if a local path does not exist. + and anything else with `gpd.read_file`. Any other remote file, and a + remote shapefile with its companions, is copied to a temporary + directory and read there, and the hash is of the copy of the main + file. Raises `FileNotFoundError` if a local path does not exist. """ # A remote shapefile is staged locally because GDAL's `/vsigs/` needs # explicit credentials, which pyogrio's default config does not pick @@ -136,23 +144,32 @@ def _read_regions(source: str | Path) -> gpd.GeoDataFrame: raise FileNotFoundError(f"regions.path not found: {path}") suffix = path.suffix.lower() if suffix in (".parquet", ".geoparquet"): - return gpd.read_parquet(path) - return gpd.read_file(path) + return gpd.read_parquet(path), None + return gpd.read_file(path), None -def _read_remote_regions(uri: str) -> gpd.GeoDataFrame: - """Stream shapefile companions from GCS to a temp dir, then read.""" - import gcsfs +def _read_remote_regions(uri: str) -> tuple[gpd.GeoDataFrame, str]: + """The regions at a `gs://` URI and the SHA256 of the bytes read.""" import tempfile + try: + import gcsfs + except ImportError as error: + raise ImportError( + f"regions.path {uri} is read with gcsfs, which the [bigquery] " + f"extra installs" + ) from error + fs = gcsfs.GCSFileSystem() suffix = uri.lower().rsplit(".", 1)[-1] if "." in uri else "" if suffix in ("parquet", "geoparquet"): - with fs.open(uri, "rb") as f: - return gpd.read_parquet(f) + data = fs.cat(uri) + return gpd.read_parquet(io.BytesIO(data)), hashlib.sha256(data).hexdigest() + tmp = Path(tempfile.mkdtemp(prefix="cilreg-regions-")) if suffix != "shp": - # GeoParquet/GeoPackage etc.: let geopandas attempt a remote read. - return gpd.read_file(uri) + local = tmp / Path(uri).name + fs.get(uri, str(local)) + return gpd.read_file(local), _sha256(local) # Shapefiles: download .shp + .dbf + .shx + .prj (if present). base = uri[:-4] # strip ".shp" tmp = Path(tempfile.mkdtemp(prefix="cilreg-regions-")) @@ -166,7 +183,11 @@ def _read_remote_regions(uri: str) -> gpd.GeoDataFrame: # .prj is optional; absence means downstream sets EPSG:4326. local_shp = tmp / Path(uri).name logger.info("regions: staged %s to %s for local read", uri, tmp) - return gpd.read_file(local_shp) + return gpd.read_file(local_shp), _sha256(local_shp) + + +def _sha256(path: Path) -> str: + return hashlib.sha256(path.read_bytes()).hexdigest() def _check_id_fields(gdf: gpd.GeoDataFrame, id_fields: list[str]) -> None: diff --git a/tests/integration/test_local_backend.py b/tests/integration/test_local_backend.py index bf204fd..5da8488 100644 --- a/tests/integration/test_local_backend.py +++ b/tests/integration/test_local_backend.py @@ -686,6 +686,39 @@ def test_nothing_recorded_without_repairs( assert "skipped_invalid_geometry_count" not in result.manifest.extra +class TestRemoteRegions: + def test_a_gs_regions_file_is_hashed_in_the_manifest( + self, three_region_geoparquet, synthetic_raster, tmp_path, monkeypatch + ): + """As a local file is. A gs:// regions file had no hash in the + manifest, and this went red on that.""" + import hashlib + import shutil + import sys + import types + + bucket = tmp_path / "bucket" + bucket.mkdir() + shutil.copy(three_region_geoparquet, bucket / "regions.parquet") + + class GCSFileSystem: + def cat(self, uri): + return (tmp_path / uri.removeprefix("gs://")).read_bytes() + + module = types.ModuleType("gcsfs") + module.GCSFileSystem = GCSFileSystem + monkeypatch.setitem(sys.modules, "gcsfs", module) + + local = _run(_cfg(three_region_geoparquet, synthetic_raster, tmp_path / "a")) + remote = _run( + _cfg("gs://bucket/regions.parquet", synthetic_raster, tmp_path / "b") + ) + expected = hashlib.sha256((bucket / "regions.parquet").read_bytes()).hexdigest() + assert remote.manifest.inputs["geometry:regions"] == expected + assert local.manifest.inputs["geometry:regions"] == expected + pd.testing.assert_frame_equal(remote.frame, local.frame) + + class TestUnknownIds: def _cfg(self, regions_path, raster_path, out_dir, **regions) -> Config: d = _cfg(regions_path, raster_path, out_dir).model_dump() diff --git a/tests/unit/test_regions.py b/tests/unit/test_regions.py index fb818ea..e0c6687 100644 --- a/tests/unit/test_regions.py +++ b/tests/unit/test_regions.py @@ -176,3 +176,95 @@ def test_bq_len_refuses(self): rs = RegionSet.from_config(cfg) with pytest.raises(ValueError, match="BigQuery"): len(rs) + + +def _fake_gcsfs(monkeypatch, root: Path) -> None: + """A stand-in for gcsfs that serves gs:// from ``root``.""" + import shutil + import sys + import types + + class GCSFileSystem: + def _local(self, uri: str) -> Path: + return root / uri.removeprefix("gs://") + + def cat(self, uri: str) -> bytes: + return self._local(uri).read_bytes() + + def get(self, uri: str, dest: str) -> None: + local = self._local(uri) + if not local.exists(): + raise FileNotFoundError(uri) + shutil.copy(local, dest) + + module = types.ModuleType("gcsfs") + module.GCSFileSystem = GCSFileSystem + monkeypatch.setitem(sys.modules, "gcsfs", module) + + +class TestRemoteRegions: + """A gs:// regions path is read, and hashed from the bytes read.""" + + def test_a_gs_path_passes_the_input_check(self): + """It is read when the run reads it. It went red on the check + that looked for it on the local disk.""" + from cil_regionalization.config import Config + from cil_regionalization.generate import check_inputs_exist + + cfg = Config.model_validate( + { + "project": {"name": "test"}, + "regions": { + "path": "gs://bucket/regions.parquet", + "id_fields": ["region_id"], + }, + "grid": {"mode": "generate", "resolution": 1.0}, + "weights": [{"name": "area"}], + "backend": {"kind": "local"}, + "output": {"dir": "out"}, + } + ) + assert check_inputs_exist(cfg) == [] + + @pytest.mark.parametrize("name", ["regions.parquet", "regions.shp", "regions.gpkg"]) + def test_a_gs_file_is_read_and_hashed(self, tmp_path, monkeypatch, name): + """The hash is of the main file as fetched. It went red with no + hash kept.""" + import hashlib + + gdf = gpd.GeoDataFrame( + {"region_id": ["a", "b"], "geometry": [box(0, 0, 1, 1), box(1, 0, 2, 1)]}, + crs="EPSG:4326", + ) + bucket = tmp_path / "bucket" + bucket.mkdir() + if name.endswith(".parquet"): + gdf.to_parquet(bucket / name) + else: + gdf.to_file(bucket / name) + _fake_gcsfs(monkeypatch, tmp_path) + rs = RegionSet.from_config( + RegionsConfig(path=f"gs://bucket/{name}", id_fields=["region_id"]) + ) + assert sorted(rs.gdf["region_id"]) == ["a", "b"] + assert rs.source_uri == f"gs://bucket/{name}" + assert ( + rs.source_sha256 == hashlib.sha256((bucket / name).read_bytes()).hexdigest() + ) + + def test_a_local_path_is_hashed_where_the_manifest_is_written( + self, three_region_geoparquet + ): + rs = RegionSet.from_config( + RegionsConfig(path=str(three_region_geoparquet), id_fields=["region_id"]) + ) + assert rs.source_sha256 is None + + def test_without_gcsfs_the_extra_that_installs_it_is_named(self, monkeypatch): + import sys + + monkeypatch.setitem(sys.modules, "gcsfs", None) + with pytest.raises(ImportError, match=r"which the \[bigquery\] extra installs"): + RegionSet.from_config( + RegionsConfig(path="gs://bucket/regions.parquet", id_fields=["id"]) + ) From dc62d70c2f020353926909cd84ca04a5e5b65d98 Mon Sep 17 00:00:00 2001 From: Sebastian Cadavid Sanchez Date: Fri, 27 Nov 2026 07:26:13 -0600 Subject: [PATCH 3/3] take the gradient region and page size from the data --- CHANGELOG.md | 6 ++ cil_regionalization/gradients.py | 26 ++++--- cil_regionalization/pipelines/montecarlo.py | 7 +- docs/reference.md | 13 ++-- examples/energy/compute.py | 6 +- .../energy_percentiles.ipynb | 6 +- examples/energy_percentiles/prepare_data.py | 12 +++- tests/unit/test_gradients.py | 71 ++++++++++++++++--- tests/unit/test_memory_reading.py | 24 +++++++ 9 files changed, 140 insertions(+), 31 deletions(-) create mode 100644 tests/unit/test_memory_reading.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 4851da1..127be75 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,12 @@ remote regions file. Reading one needs gcsfs, which the `[bigquery]` extra installs, and a remote file in a format other than Parquet is copied to a temporary directory first. +**`aggregate_gradient` takes `weight` with no default, and finds the +regions in the weight file's source key column.** It defaulted to +population, and read a column called `hierid` whatever the artifact's +source key was. The resident memory the pipeline logs counts pages of +the size the machine reports, where it took them as 4096 bytes. + **A model takes the row of its own name in a model weights table, letter for letter, or the row declared for it, and a model with neither is refused.** Before, the library dropped `surrogate_` from the diff --git a/cil_regionalization/gradients.py b/cil_regionalization/gradients.py index 77c7471..1465781 100644 --- a/cil_regionalization/gradients.py +++ b/cil_regionalization/gradients.py @@ -113,7 +113,7 @@ def aggregate_gradient( regions: list[str], gradient: np.ndarray, *, - weight: str = "pop", + weight: str, scale: np.ndarray | None = None, normalize: bool = False, ) -> tuple[pd.DataFrame, np.ndarray]: @@ -121,7 +121,9 @@ def aggregate_gradient( file's targets, target by coefficient. ``gradient`` is coefficient by region, in the order of ``regions``, - and the shares are the column ``wt``. Weight rows for other + and the shares are the column ``wt``, which has no default. + A region is a value of the artifact's one source key column. Weight + rows for other regions are ignored, as with ``restrict_to_sources``. For a total, an extensive value, leave ``scale`` and ``normalize`` alone, and each region's gradient is split by the weight shares and summed. For @@ -131,9 +133,10 @@ def aggregate_gradient( a difference of gradients, such as one against histclim, equals differencing the aggregated ones. - Raises if the share column is missing, if a region has no weight - rows, if ``scale`` is not one value per region, or if a target has - zero total weight under ``normalize``. + Raises if the share column is missing, if the artifact's source key + is not one column, if a region has no weight rows, if ``scale`` is not + one value per region, or if a target has zero total weight under + ``normalize``. """ frame = weights.frame key_cols = list(weights.schema.id_fields) @@ -143,9 +146,16 @@ def aggregate_gradient( f"weight file has no {share_col!r} column " f"(columns: {sorted(frame.columns)})" ) + source_keys = list(weights.schema.source_units.key_columns) + if len(source_keys) != 1: + raise ValueError( + f"a gradient region is one value of the source key, and this " + f"weight file's source key is {source_keys}" + ) + (region_col,) = source_keys index = {r: i for i, r in enumerate(regions)} - rows = frame[frame["hierid"].isin(index)] - covered = set(rows["hierid"]) + rows = frame[frame[region_col].isin(index)] + covered = set(rows[region_col]) absent = [r for r in regions if r not in covered] if absent: raise ValueError( @@ -167,7 +177,7 @@ def aggregate_gradient( f"scale has shape {scale_vec.shape}; expected ({len(regions)},)" ) for row in rows.itertuples(index=False): - r = index[row.hierid] + r = index[getattr(row, region_col)] t = tindex[tuple(getattr(row, c) for c in key_cols)] w = getattr(row, share_col) * scale_vec[r] out[t] += w * gradient[:, r] diff --git a/cil_regionalization/pipelines/montecarlo.py b/cil_regionalization/pipelines/montecarlo.py index 6a91d72..5378d21 100644 --- a/cil_regionalization/pipelines/montecarlo.py +++ b/cil_regionalization/pipelines/montecarlo.py @@ -2308,11 +2308,14 @@ def _peak_rss_gb() -> float: def _current_rss_gb() -> Optional[float]: - """This process's current resident memory in GB (Linux only).""" + """This process's current resident memory in GB (Linux only). The + count is in pages, of the size the machine reports.""" + import resource + try: with open("/proc/self/statm") as f: pages = int(f.read().split()[1]) - return pages * 4096 / 1e9 + return pages * resource.getpagesize() / 1e9 except OSError: return None diff --git a/docs/reference.md b/docs/reference.md index 20308ff..0470e72 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1004,7 +1004,7 @@ aggregate_gradient( regions: list[str], gradient: np.ndarray, *, - weight: str = 'pop', + weight: str, scale: np.ndarray | None = None, normalize: bool = False, ) -> tuple[pd.DataFrame, np.ndarray] @@ -1014,7 +1014,9 @@ The target key frame and the gradient aggregated to the weight file's targets, target by coefficient. ``gradient`` is coefficient by region, in the order of ``regions``, -and the shares are the column ``wt``. Weight rows for other +and the shares are the column ``wt``, which has no default. +A region is a value of the artifact's one source key column. Weight +rows for other regions are ignored, as with ``restrict_to_sources``. For a total, an extensive value, leave ``scale`` and ``normalize`` alone, and each region's gradient is split by the weight shares and summed. For @@ -1024,9 +1026,10 @@ of its regions' gradients. The aggregation is linear, so aggregating a difference of gradients, such as one against histclim, equals differencing the aggregated ones. -Raises if the share column is missing, if a region has no weight -rows, if ``scale`` is not one value per region, or if a target has -zero total weight under ``normalize``. +Raises if the share column is missing, if the artifact's source key +is not one column, if a region has no weight rows, if ``scale`` is not +one value per region, or if a target has zero total weight under +``normalize``. ### `delta_method` diff --git a/examples/energy/compute.py b/examples/energy/compute.py index ffd8732..6a3f4c7 100644 --- a/examples/energy/compute.py +++ b/examples/energy/compute.py @@ -69,7 +69,9 @@ def load_weights() -> "cilreg.WeightsArtifact": def valued_states(weights, regions, gradient, vcv, gammas, factor): """Mean and sd of the valued effect per state, repaired dollars.""" - targets, G = cilreg.aggregate_gradient(weights, regions, gradient * factor[None, :]) + targets, G = cilreg.aggregate_gradient( + weights, regions, gradient * factor[None, :], weight="pop" + ) stats = cilreg.delta_method(G, vcv, coefficients=gammas) out = pd.concat([targets, stats * DOLLARS_2019 / GJ_PER_KWH], axis=1) return out @@ -78,7 +80,7 @@ def valued_states(weights, regions, gradient, vcv, gammas, factor): def physical_states(weights, regions, gradient, vcv, gammas, population): """Mean and sd of the per-capita effect per state, GJ per capita.""" targets, G = cilreg.aggregate_gradient( - weights, regions, gradient, scale=population, normalize=True + weights, regions, gradient, weight="pop", scale=population, normalize=True ) stats = cilreg.delta_method(G, vcv, coefficients=gammas) return pd.concat([targets, stats], axis=1) diff --git a/examples/energy_percentiles/energy_percentiles.ipynb b/examples/energy_percentiles/energy_percentiles.ipynb index 0b3175f..e572fd5 100644 --- a/examples/energy_percentiles/energy_percentiles.ipynb +++ b/examples/energy_percentiles/energy_percentiles.ipynb @@ -798,8 +798,8 @@ "source": [ "province = {}\n", "for g in GCMS:\n", - " targets, G = cilreg.aggregate_gradient(weights, regions, window_grad[g])\n", - " _, M = cilreg.aggregate_gradient(weights, regions, window_mean[g])\n", + " targets, G = cilreg.aggregate_gradient(weights, regions, window_grad[g], weight=\"pop\")\n", + " _, M = cilreg.aggregate_gradient(weights, regions, window_mean[g], weight=\"pop\")\n", " province[g] = (G * DOLLARS, M[:, 0] * DOLLARS)\n", "\n", "members = targets.groupby(\"ISO\").indices # ISO -> rows of targets\n", @@ -1737,7 +1737,7 @@ " levels = {\"impact_region\": pd.DataFrame({\"hierid\": map_regions, \"dollars\": both[0],\n", " \"people\": both[1]})}\n", " for level in (\"adm1\", \"adm2\"):\n", - " t, A = cilreg.aggregate_gradient(map_weights[level], map_regions, both)\n", + " t, A = cilreg.aggregate_gradient(map_weights[level], map_regions, both, weight=\"pop\")\n", " levels[level] = t.assign(dollars=A[:, 0], people=A[:, 1])\n", " levels[\"adm0\"] = levels[\"adm1\"].groupby(\"ISO\", as_index=False)[[\"dollars\", \"people\"]].sum()\n", " for level, f in levels.items():\n", diff --git a/examples/energy_percentiles/prepare_data.py b/examples/energy_percentiles/prepare_data.py index 0084147..486f8ac 100644 --- a/examples/energy_percentiles/prepare_data.py +++ b/examples/energy_percentiles/prepare_data.py @@ -371,8 +371,12 @@ def compute() -> pd.DataFrame: g = cilreg.window_gradient(grad * scale[:, None, :], YEARS, (lo, hi)) m = cilreg.window_gradient((mean * scale)[:, None, :], YEARS, (lo, hi)) for level in ("adm1", "adm2"): - targets, G = cilreg.aggregate_gradient(weights[level], regions, g) - _, M = cilreg.aggregate_gradient(weights[level], regions, m) + targets, G = cilreg.aggregate_gradient( + weights[level], regions, g, weight="pop" + ) + _, M = cilreg.aggregate_gradient( + weights[level], regions, m, weight="pop" + ) G, M = G * dollars, M[:, 0] * dollars parts = [(level, targets, G, M)] if level == "adm1": @@ -431,7 +435,9 @@ def compute_map(regions) -> dict: for lo, hi in data.WINDOWS: m = cilreg.window_gradient(valued[:, None, :], YEARS, (lo, hi)) for level in ("adm1", "adm2"): - targets, M = cilreg.aggregate_gradient(weights[level], regions, m) + targets, M = cilreg.aggregate_gradient( + weights[level], regions, m, weight="pop" + ) out[(level, f"{lo}-{hi}")] = pd.DataFrame( {"mean": M[:, 0]}, index=pd.MultiIndex.from_frame(targets) ) diff --git a/tests/unit/test_gradients.py b/tests/unit/test_gradients.py index d471ba9..a32b1ee 100644 --- a/tests/unit/test_gradients.py +++ b/tests/unit/test_gradients.py @@ -54,23 +54,71 @@ def _two_region_setup(): class TestAggregateGradient: + def test_the_region_column_is_the_artifact_s_source_key(self): + """Not a column called hierid, which the code named. It went red on + that, with a KeyError.""" + art, regions, gradient = _two_region_setup() + renamed = _artifact( + art.frame.rename(columns={"hierid": "region"}).to_dict("records") + ) + renamed = WeightsArtifact( + frame=renamed.frame, + schema=OutputSchema( + id_fields=("ISO", "ID_1"), + weight_names=("pop",), + source_units=SourceUnits.from_string_ids(["region"]), + normalization="per_source", + ), + regions_version="test-targets", + source_version="test-regions", + partial_coverage={}, + ) + want = aggregate_gradient(art, regions, gradient, weight="pop") + got = aggregate_gradient(renamed, regions, gradient, weight="pop") + pd.testing.assert_frame_equal(got[0], want[0]) + np.testing.assert_array_equal(got[1], want[1]) + + def test_the_weight_has_no_default(self): + """Which weight splits a region is a choice. It went red on the + default of population.""" + art, regions, gradient = _two_region_setup() + with pytest.raises(TypeError, match="weight"): + aggregate_gradient(art, regions, gradient) + + def test_a_source_key_of_two_columns_is_refused(self): + art, regions, gradient = _two_region_setup() + two = WeightsArtifact( + frame=art.frame.assign(part="x"), + schema=OutputSchema( + id_fields=("ISO", "ID_1"), + weight_names=("pop",), + source_units=SourceUnits.from_string_ids(["hierid", "part"]), + normalization="per_source", + ), + regions_version="test-targets", + source_version="test-regions", + partial_coverage={}, + ) + with pytest.raises(ValueError, match=r"source key is \['hierid', 'part'\]"): + aggregate_gradient(two, regions, gradient, weight="pop") + def test_extensive_shares_split_the_gradient(self): art, regions, gradient = _two_region_setup() - targets, agg = aggregate_gradient(art, regions, gradient) + targets, agg = aggregate_gradient(art, regions, gradient, weight="pop") got = {tuple(t): agg[i] for i, t in enumerate(targets.itertuples(index=False))} assert np.allclose(got[("T", 1)], [0.75 * 1.0, 0.75 * 2.0]) assert np.allclose(got[("T", 2)], [0.25 * 1.0 + 3.0, 0.25 * 2.0 + 4.0]) def test_targets_sum_to_the_total(self): art, regions, gradient = _two_region_setup() - _, agg = aggregate_gradient(art, regions, gradient) + _, agg = aggregate_gradient(art, regions, gradient, weight="pop") assert np.allclose(agg.sum(axis=0), gradient.sum(axis=1)) def test_rate_normalization_is_weighted_mean(self): art, regions, gradient = _two_region_setup() pop = np.array([100.0, 300.0]) targets, agg = aggregate_gradient( - art, regions, gradient, scale=pop, normalize=True + art, regions, gradient, weight="pop", scale=pop, normalize=True ) got = {tuple(t): agg[i] for i, t in enumerate(targets.itertuples(index=False))} # target 2: weights a=0.25*100=25, b=1.0*300=300 @@ -83,13 +131,18 @@ def test_region_without_weight_rows_raises(self): art, regions, gradient = _two_region_setup() with pytest.raises(ValueError, match="no weight rows"): aggregate_gradient( - art, regions + ["c"], np.hstack([gradient, [[5.0], [6.0]]]) + art, + regions + ["c"], + np.hstack([gradient, [[5.0], [6.0]]]), + weight="pop", ) def test_wrong_scale_shape_raises(self): art, regions, gradient = _two_region_setup() with pytest.raises(ValueError, match="scale has shape"): - aggregate_gradient(art, regions, gradient, scale=np.ones(3), normalize=True) + aggregate_gradient( + art, regions, gradient, weight="pop", scale=np.ones(3), normalize=True + ) class TestWindowGradient: @@ -118,9 +171,11 @@ def test_commutes_with_aggregation(self): rng = np.random.default_rng(0) g = rng.normal(size=(3, 2, 2)) first = aggregate_gradient( - art, regions, window_gradient(g, years, (2000, 2002)) + art, regions, window_gradient(g, years, (2000, 2002)), weight="pop" )[1] - stacked = np.stack([aggregate_gradient(art, regions, gy)[1] for gy in g]) + stacked = np.stack( + [aggregate_gradient(art, regions, gy, weight="pop")[1] for gy in g] + ) after = window_gradient(stacked, years, (2000, 2002)) assert np.allclose(first, after) @@ -174,7 +229,7 @@ def test_correlation_changes_the_aggregate_spread(self): ) g = np.array([[1.0, 1.0]]) V = np.array([[1.0]]) - _, agg = aggregate_gradient(art, ["a", "b"], g) + _, agg = aggregate_gradient(art, ["a", "b"], g, weight="pop") correct = float(delta_method(agg, V)["sd"].iloc[0]) per_region_var = np.einsum("cr,cd,dr->r", g, V, g) naive = float(np.sqrt(per_region_var.sum())) diff --git a/tests/unit/test_memory_reading.py b/tests/unit/test_memory_reading.py new file mode 100644 index 0000000..4089478 --- /dev/null +++ b/tests/unit/test_memory_reading.py @@ -0,0 +1,24 @@ +"""The pipeline's memory readings, without a Linux /proc.""" + +from __future__ import annotations + +import builtins +import io +import resource + +from cil_regionalization.pipelines import montecarlo + + +def test_the_resident_pages_are_of_the_size_the_machine_reports(monkeypatch): + """/proc/self/statm counts pages, and a page is 16 KiB on some + machines. It went red on the 4096 bytes written in the code.""" + real_open = builtins.open + + def fake_open(path, *args, **kwargs): + if path == "/proc/self/statm": + return io.StringIO("1000 250 10 1 0 200 0\n") + return real_open(path, *args, **kwargs) + + monkeypatch.setattr(builtins, "open", fake_open) + monkeypatch.setattr(resource, "getpagesize", lambda: 16384) + assert montecarlo._current_rss_gb() == 250 * 16384 / 1e9