From f8032073603b11505b8471376f28ca5671b601a3 Mon Sep 17 00:00:00 2001 From: Sebastian Cadavid Sanchez Date: Fri, 27 Nov 2026 22:02:23 -0600 Subject: [PATCH 1/5] read a worker's peak as VmHWM on Linux and ru_maxrss on macOS On Linux ru_maxrss survives an exec, so a spawned worker read the peak of the process that started it. VmHWM of /proc/self/status is the high-water mark of the process's own address space. On a Midway3 compute node it started at the worker's own resident memory under spawn, fork and forkserver and grew by exactly what the worker touched. macOS keeps ru_maxrss. The aggregate stage reads its workers' peaks the same way, where it took Linux's kibibytes for thousands of bytes. --- CHANGELOG.md | 47 +++++--- README.md | 42 ++++--- cil_regionalization/pipelines/montecarlo.py | 11 +- cil_regionalization/reduce/pandas_blocks.py | 59 +++++----- cil_regionalization/resident.py | 61 ++++++++++ tests/integration/test_montecarlo_pipeline.py | 19 ++-- tests/unit/test_block_sizing.py | 51 ++------- tests/unit/test_resident.py | 106 ++++++++++++++++++ 8 files changed, 276 insertions(+), 120 deletions(-) create mode 100644 cil_regionalization/resident.py create mode 100644 tests/unit/test_resident.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2c914fe..bba3268 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,28 @@ ## Unreleased +**On Linux a worker's peak resident memory is read as VmHWM of +`/proc/self/status`, where it was `ru_maxrss`.** On Linux `ru_maxrss` +survives an exec, so a worker started by spawn read the peak of the +process that started it, and a block below that peak read nothing. Fork +starts it afresh, so runs on the cluster, which fork, were measured +right already, and what read blind was a test that asked for spawn. +VmHWM is the high-water mark of the process's own address space. On a +Midway3 compute node, RHEL 8 with kernel 4.18 and Python 3.11.12, it +started at the worker's own resident memory under spawn, fork and +forkserver, equal to VmRSS, and grew by the 150 MB a worker touched, +150.0, 150.3 and 150.0 MB. There the spawned worker's `ru_maxrss` +started at the parent's 419.9 MB and grew by nothing. macOS keeps +`ru_maxrss`, which a new worker starts afresh there. A first block whose +peak did not rise is still recorded as unmeasured, and on Linux that +should now be rare. Under fork the peaks a worker records count the +pages it shares with the process that started it, 319.8 MB at the start +of a worker whose parent held 300 MB, so they overstate what the worker +alone holds. That errs on the side of the budget, and the growth is +unaffected, 150.2 MB there. The manifest's measure says which reading +was taken. The aggregate stage reads its workers' peaks the same way, +where it took Linux's kibibytes for thousands of bytes. + **A worker that dies stops the aggregate stage at once, naming the leaves in flight and how the workers ended.** The leaves ran on a `multiprocessing.Pool` that renewed each worker after 16 leaves, and a @@ -48,19 +70,18 @@ by side under `reduce.block_size`. A first block that keeps 100,000 rows or more and takes more than twice the estimate stops the run before any other block, with nothing written, and one that keeps fewer is recorded and not judged. Twice is a tolerance on a measure with known noise, not -a correction of the estimate. One synthetic first block, measured in one -fresh worker after another, read from a fifth of the estimate to nine -tenths of it, and memory sampled through the block peaked where the -measure did, so the spread is in what the block holds resident and not -in the reading. The manifest records the factor beside the measure. On -one worker the block runs in the process that planned the run, whose -peak cannot be put down to it, and a worker whose peak did not rise, as -a forked one can when the block weighs less than what it inherited, says -nothing of the block either. Neither has a measurement or a judgement, -and the manifest says why, and which start method the workers had. The -peak a worker logs is read in bytes on macOS and kibibytes on Linux, -where Linux's was taken as thousands of bytes. New: -`[reduce.pandas] targets_per_block` declares the size of a block in +a correction of the estimate. One synthetic first block, measured on +macOS in one fresh worker after another, read from a fifth of the +estimate to nine tenths of it, and memory sampled through the block +peaked where the measure did, so the spread is in what the block holds +resident and not in the reading. The manifest records the factor beside +the measure. On one worker the block runs in the process that planned +the run, whose peak cannot be put down to it, and a worker whose peak +did not rise over the block says nothing of it either. Neither has a +measurement or a judgement, and the manifest says why, and which start +method the workers had. The peak a worker logs is read in bytes on macOS +and kibibytes on Linux, where Linux's was taken as thousands of bytes. +New: `[reduce.pandas] targets_per_block` declares the size of a block in place of `memory_gb`. It warns, and the manifest records the size as declared. diff --git a/README.md b/README.md index 1d1d11c..09daf8e 100644 --- a/README.md +++ b/README.md @@ -622,24 +622,30 @@ memory_gb = 128 # for all the workers together n_workers = 16 # run.n_workers unless set ``` -`--dry-run` prints the blocks and the number of file opens that -budget gives. The blocks are sized from an estimate of the bytes a -kept row takes, calibrated on resident memory. The first block is built -alone in a worker of its own, and measured as the growth of that -worker's peak resident memory over the block, from the peak once the -worker has set itself up. The manifest records the estimate and the -measurement side by side under `reduce.block_size`, and the setup peak, -which every worker holds before its first block. A first block that -keeps 100,000 rows or more and takes more than twice the estimate stops -the run, with nothing written, since its blocks could take more than -the budget. Twice, and not once, because the measure is noisy. The same -block, measured in one fresh worker after another, can read from a -fifth of the estimate to nearly all of it. On one worker the blocks -run in the process that planned the run, whose peak includes what it -did before. A forked worker starts from what it inherited, and a block -lighter than that leaves its peak where it was. In both cases the -manifest says there is no measurement and why, and the run is not -judged. +`--dry-run` prints the blocks and the number of file opens that budget +gives. The blocks are sized from an estimate of the bytes a kept row +takes, calibrated on resident memory. The first block is built alone in +a worker of its own, and measured as the growth of that worker's peak +resident memory over the block, from the peak once the worker has set +itself up. The manifest records the estimate and the measurement side by +side under `reduce.block_size`, and the setup peak, which every worker +holds before its first block. A first block that keeps 100,000 rows or +more and takes more than twice the estimate stops the run, with nothing +written, since its blocks could take more than the budget. Twice, and +not once, because the measure is noisy. The same block, measured on +macOS in one fresh worker after another, can read from a fifth of the +estimate to nearly all of it. On one worker the blocks run in the +process that planned the run, whose peak includes what it did before. A +block that fits in memory the worker already held leaves its peak where +it was. In both cases the manifest says there is no measurement and why, +and the run is not judged. The peak is read as each platform keeps it, +as VmHWM of `/proc/self/status` on Linux and as `ru_maxrss` on macOS. On +Linux `ru_maxrss` survives an exec, so a spawned worker's would start +from the peak of the process that started it. Under fork a worker counts +the pages it shares with that process as its own, so the peaks under +`reduce.block_size` and `max_worker_peak_gb` overstate what a worker +alone holds, which errs on the side of the budget. The growth, the +difference of two peaks that both count those pages, is exact. Someone who has measured their own runs can declare the size of a block instead, in targets, a whole number of the leaves' row groups: diff --git a/cil_regionalization/pipelines/montecarlo.py b/cil_regionalization/pipelines/montecarlo.py index 0b9ff78..469af77 100644 --- a/cil_regionalization/pipelines/montecarlo.py +++ b/cil_regionalization/pipelines/montecarlo.py @@ -122,6 +122,7 @@ ReduceRequest, get_backend, ) +from cil_regionalization.resident import peak_resident_bytes from cil_regionalization.stats import ( _quantile_label, _warn_if_unweighted_models, @@ -2325,12 +2326,10 @@ def _ordered(frame: pd.DataFrame, cfg: MonteCarloPipelineConfig) -> pd.DataFrame def _peak_rss_gb() -> float: - """This process's peak resident memory in GB.""" - import resource - - peak = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss - # ru_maxrss is kilobytes on Linux, bytes on macOS - return peak / 1e6 if sys.platform.startswith("linux") else peak / 1e9 + """This process's peak resident memory in GB, read as + `resident.peak_resident_bytes` reads it, or NaN where it is not.""" + peak = peak_resident_bytes() + return float("nan") if peak is None else peak / 1e9 def _current_rss_gb() -> Optional[float]: diff --git a/cil_regionalization/reduce/pandas_blocks.py b/cil_regionalization/reduce/pandas_blocks.py index 2cee5d6..16cd8d5 100644 --- a/cil_regionalization/reduce/pandas_blocks.py +++ b/cil_regionalization/reduce/pandas_blocks.py @@ -36,12 +36,14 @@ import pandas as pd from cil_regionalization import leaves as leaf_format +from cil_regionalization import resident from cil_regionalization.manifest import collect_package_versions from cil_regionalization.reduce.base import ( PandasReduceOptions, ReduceBackend, ReduceRequest, ) +from cil_regionalization.resident import peak_resident_bytes as _peak_resident_bytes from cil_regionalization.stats import ( GroupError, UnweightedModelWeightsWarning, @@ -70,16 +72,13 @@ # A first block is refused when it takes more than this many times the # estimate a kept row. It is a tolerance on a measure with known noise, # not a correction of the estimate. One synthetic first block, measured -# in one fresh worker after another, read from a fifth of the estimate -# to nine tenths of it. Memory sampled through the block peaked where -# the measure did, so the spread is in what the block holds resident and -# not in the reading. Twice refuses a block far heavier than the -# estimate and not that spread. The manifest records the measure of -# every run, so runs on real data can tighten it. +# on macOS in one fresh worker after another, read from a fifth of the +# estimate to nine tenths of it. Memory sampled through the block peaked +# where the measure did, so the spread is in what the block holds +# resident and not in the reading. Twice refuses a block far heavier +# than the estimate and not that spread. The manifest records the +# measure of every run, so runs on real data can tighten it. REFUSED_ABOVE = 2 -# The unit ru_maxrss counts in, bytes on macOS and kibibytes on Linux. -# On a platform not listed the peak is not read, rather than guessed. -_RU_MAXRSS_UNIT = {"darwin": 1, "linux": 1024} # Why a first block run in the process that planned the run has no # measurement. _SHARED_PEAK = ( @@ -87,13 +86,13 @@ "resident memory includes what it did before, so the block's share of " "the peak cannot be told" ) -# Why a worker whose peak did not rise has none either. A forked worker -# starts from what it inherited, and a block lighter than that leaves -# the peak where it was. +# Why a worker whose peak did not rise has none either. A block that +# fits in memory the worker already held, as a small one can in what the +# worker's setup freed, leaves the peak where it was. _FLAT_PEAK = ( - "the worker's peak resident memory did not rise above the peak it " - "started from, so the block weighed less than what the worker inherited " - "and the peak says nothing of it" + "the worker's peak resident memory did not rise over the block, so the " + "block fit in memory the worker already held and the peak says nothing " + "of it" ) @@ -369,14 +368,22 @@ def _block_size_record(request: ReduceRequest, plan: dict, first: dict) -> dict: "measured_bytes_per_row": measured, "measured_rows": rows, "measured_growth_bytes": growth, + # Under fork a worker counts the pages it shares with the process + # that started it as its own, so its peaks overstate what it alone + # holds. That errs on the side of the budget, and the growth, the + # difference of two peaks that both count them, is exact. "worker_setup_peak_bytes": first["worker_setup_peak_bytes"], "peak_after_block_bytes": first["peak_after_block_bytes"], "measured_block": list(first["block"]), "start_method": first["start_method"], "measure": ( - "the growth of the peak resident memory, ru_maxrss, of the worker " - "that built the first block, from the peak once it had set itself " - "up and before it read the block, to the end of the block" + f"the growth of the peak resident memory of the worker that built " + f"the first block, read as {resident.reading() or 'nothing'} on " + f"{sys.platform}, from the peak once it had set itself up and " + f"before it read the block, to the end of the block. Under fork " + f"both peaks count the pages the worker shares with the process " + f"that started it, so they overstate what it alone holds, and the " + f"growth is unaffected" ), "unavailable": unavailable, "judged": judged, @@ -511,7 +518,7 @@ def _growth( if not own_process: return None, _SHARED_PEAK if started is None or peak is None: - return None, f"the unit of ru_maxrss on {sys.platform} is not known here" + return None, resident.why_not_read() if peak <= started: return None, _FLAT_PEAK return peak - started, None @@ -546,20 +553,6 @@ def _init_worker(request: ReduceRequest, own_process: bool = True) -> None: _STATE.update(request=request, targets=targets) -def _peak_resident_bytes() -> int | None: - """This process's peak resident memory in bytes, from ru_maxrss, or - None on a platform whose unit of it is not in `_RU_MAXRSS_UNIT`.""" - import resource - - unit = next( - (u for name, u in _RU_MAXRSS_UNIT.items() if sys.platform.startswith(name)), - None, - ) - if unit is None: - return None - return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss * unit - - def _peak_gb() -> float: peak = _peak_resident_bytes() return float("nan") if peak is None else peak / 1e9 diff --git a/cil_regionalization/resident.py b/cil_regionalization/resident.py new file mode 100644 index 0000000..3a7c7d6 --- /dev/null +++ b/cil_regionalization/resident.py @@ -0,0 +1,61 @@ +"""This process's peak resident memory, read as each platform keeps it. + +On Linux it is VmHWM of ``/proc/self/status``, the high-water mark of +the process's own address space. ``ru_maxrss`` there survives an exec, +so a worker started by spawn would read the peak of the process that +started it. On macOS it is ``ru_maxrss``, which a new worker starts +afresh. Elsewhere it is not read, rather than guessed. +""" + +from __future__ import annotations + +import sys +from pathlib import Path + +_PROC_STATUS = Path("/proc/self/status") + + +def peak_resident_bytes() -> int | None: + """This process's peak resident memory in bytes, or None where it is + not read. Under fork it counts the pages the process shares with its + parent as its own.""" + if sys.platform.startswith("linux"): + try: + return vmhwm_bytes(_PROC_STATUS.read_text()) + except OSError: + return None + if sys.platform == "darwin": + import resource + + # bytes on macOS + return resource.getrusage(resource.RUSAGE_SELF).ru_maxrss + return None + + +def vmhwm_bytes(status: str) -> int | None: + """VmHWM of the text of a ``/proc`` status file in bytes, or None if + the text has no VmHWM counted in kB, which there are kibibytes.""" + for line in status.splitlines(): + key, _, value = line.partition(":") + if key == "VmHWM": + number, _, unit = value.strip().partition(" ") + if number.isdigit() and unit.strip() == "kB": + return int(number) * 1024 + return None + return None + + +def reading() -> str | None: + """What `peak_resident_bytes` reads on this platform, or None.""" + if sys.platform.startswith("linux"): + return "VmHWM of /proc/self/status" + if sys.platform == "darwin": + return "ru_maxrss" + return None + + +def why_not_read() -> str: + """Why `peak_resident_bytes` gave None on this platform.""" + if sys.platform.startswith("linux"): + return "VmHWM could not be read from /proc/self/status" + return f"the peak resident memory of a process is not read on {sys.platform}" diff --git a/tests/integration/test_montecarlo_pipeline.py b/tests/integration/test_montecarlo_pipeline.py index 2d04028..dfb5a57 100644 --- a/tests/integration/test_montecarlo_pipeline.py +++ b/tests/integration/test_montecarlo_pipeline.py @@ -2781,10 +2781,8 @@ def run(*flags): @pytest.fixture def spawned_workers(): """Workers started by spawn, for the test that reads a worker's real - peak resident memory over its first block. On macOS such a worker's - peak starts from its own setup. On Linux it starts from the peak of - the process that started it, so a small block reads nothing there. - Runs keep the platform's own start method.""" + peak resident memory over its first block. Runs keep the platform's + own start method.""" import multiprocessing before = multiprocessing.get_start_method(allow_none=True) @@ -2819,8 +2817,8 @@ def forked_workers_with_a_rising_peak(monkeypatch): @pytest.fixture def forked_workers_with_a_flat_peak(monkeypatch): - """A peak that never rises, as on Linux over a block lighter than the - peak of the process the worker came from.""" + """A peak that never rises, as over a block that fits in memory the + worker already held.""" yield from _forked_workers(monkeypatch, lambda: 10**9) @@ -3102,11 +3100,11 @@ def test_the_estimate_and_the_measurement_are_recorded_side_by_side( ): """The first block is built alone in a worker and measured as the growth of its peak resident memory over the block. A block this - small can leave the peak where it was, at the worker's setup or on - Linux at the peak of the process that started it, and then the - record says so. Either way it is below what is + small can leave the peak where the worker's setup put it, and then + the record says so. Either way it is below what is judged, so it is recorded and not judged. It went red with nothing measured.""" + from cil_regionalization import resident from cil_regionalization.reduce.pandas_blocks import _FLAT_PEAK raw, whole, out = self._aggregated(weights_dir, tmp_path) @@ -3118,7 +3116,8 @@ def test_the_estimate_and_the_measurement_are_recorded_side_by_side( assert sizing["by"] == "estimate" and sizing["targets_per_block"] is None assert sizing["estimate_bytes_per_row"] == 280 assert sizing["measured_rows"] == 24 and sizing["measured_block"] == [0, 1] - assert sizing["start_method"] == "spawn" and "ru_maxrss" in sizing["measure"] + assert sizing["start_method"] == "spawn" + assert f"read as {resident.reading()} on " in sizing["measure"] setup = sizing["worker_setup_peak_bytes"] after = sizing["peak_after_block_bytes"] assert after >= setup > 0 diff --git a/tests/unit/test_block_sizing.py b/tests/unit/test_block_sizing.py index 2ca1807..64d4691 100644 --- a/tests/unit/test_block_sizing.py +++ b/tests/unit/test_block_sizing.py @@ -45,40 +45,6 @@ def test_a_budget_or_a_declared_size_is_needed(self): PandasBlocks(PandasReduceOptions())._plan(_request([10])) -class TestPeakResidentMemory: - """ru_maxrss counts bytes on macOS and kibibytes on Linux.""" - - @pytest.mark.parametrize( - "platform, expected", - [("darwin", 1000), ("linux", 1_024_000), ("freebsd14", None)], - ) - def test_the_unit_is_the_platform_s(self, monkeypatch, platform, expected): - """It went red on a peak taken as bytes everywhere, and on Linux - as thousands of bytes, a factor of 1.024 off.""" - import resource - import sys - - from cil_regionalization.reduce import pandas_blocks - - monkeypatch.setattr(sys, "platform", platform) - monkeypatch.setattr( - resource, "getrusage", lambda who: SimpleNamespace(ru_maxrss=1000) - ) - assert pandas_blocks._peak_resident_bytes() == expected - - def test_the_peak_logged_in_gigabytes_is_of_the_same_bytes(self, monkeypatch): - import resource - import sys - - from cil_regionalization.reduce import pandas_blocks - - monkeypatch.setattr(sys, "platform", "linux") - monkeypatch.setattr( - resource, "getrusage", lambda who: SimpleNamespace(ru_maxrss=1_000_000) - ) - assert pandas_blocks._peak_gb() == 1.024 - - class TestGrowth: """When the growth of a peak says something of the first block.""" @@ -88,23 +54,28 @@ def test_a_peak_that_rose_gives_its_growth(self): assert _growth(10**9, 10**9 + 5, own_process=True) == (5, None) def test_a_peak_that_did_not_rise_gives_no_measure(self): - """As under fork, when the block weighs less than what the worker - inherited. It went red with a growth of zero recorded.""" + """As when the block fits in memory the worker already held. It + went red with a growth of zero recorded.""" from cil_regionalization.reduce.pandas_blocks import _FLAT_PEAK, _growth assert _growth(10**9, 10**9, own_process=True) == (None, _FLAT_PEAK) - assert "did not rise above the peak it started from" in _FLAT_PEAK + assert "did not rise over the block" in _FLAT_PEAK def test_the_process_that_planned_the_run_gives_no_measure(self): from cil_regionalization.reduce.pandas_blocks import _SHARED_PEAK, _growth assert _growth(10**9, 2 * 10**9, own_process=False) == (None, _SHARED_PEAK) - def test_an_unknown_unit_gives_no_measure(self): + def test_a_peak_not_read_gives_no_measure_and_says_why(self, monkeypatch): + import sys + from cil_regionalization.reduce.pandas_blocks import _growth - growth, why = _growth(None, None, own_process=True) - assert growth is None and "unit of ru_maxrss" in why + monkeypatch.setattr(sys, "platform", "freebsd14") + assert _growth(None, None, own_process=True) == ( + None, + "the peak resident memory of a process is not read on freebsd14", + ) def test_the_growth_leaves_out_what_the_worker_set_up(self, monkeypatch): """The setup raises the peak by 100 and the block by 10, and the diff --git a/tests/unit/test_resident.py b/tests/unit/test_resident.py new file mode 100644 index 0000000..931c38d --- /dev/null +++ b/tests/unit/test_resident.py @@ -0,0 +1,106 @@ +"""This process's peak resident memory, read as each platform keeps it.""" + +from __future__ import annotations + +import sys +from types import SimpleNamespace + +import pytest + +from cil_regionalization import resident + +# The lines of /proc/self/status around VmHWM as a Linux kernel writes +# them, with the peak of the address space's size, VmPeak, before it. +STATUS = ( + "Name:\tpython\n" + "VmPeak:\t 512000 kB\n" + "VmSize:\t 498000 kB\n" + "VmHWM:\t 17600 kB\n" + "VmRSS:\t 17200 kB\n" +) + + +def _on(monkeypatch, platform, *, status=None, ru_maxrss=419_900): + """The platform given, a status file of ``status``, and a ru_maxrss + that is never the answer on Linux.""" + import resource + + monkeypatch.setattr(sys, "platform", platform) + monkeypatch.setattr( + resource, "getrusage", lambda who: SimpleNamespace(ru_maxrss=ru_maxrss) + ) + if status is not None: + monkeypatch.setattr(resident, "_PROC_STATUS", status) + + +class TestVmHWM: + def test_the_high_water_mark_in_bytes(self): + """Its kB are kibibytes. It went red on thousands of bytes.""" + assert resident.vmhwm_bytes(STATUS) == 17600 * 1024 + + @pytest.mark.parametrize( + "text", + [ + "Name:\tpython\nVmRSS:\t 17200 kB\n", + "VmHWM:\t 17600 MB\n", + "VmHWM:\t\n", + "", + ], + ) + def test_a_status_without_a_vmhwm_in_kb_gives_none(self, text): + """Rather than a number guessed. It went red with any unit read + as kB.""" + assert resident.vmhwm_bytes(text) is None + + +class TestPlatforms: + def test_linux_reads_vmhwm_and_not_ru_maxrss(self, monkeypatch, tmp_path): + """ru_maxrss on Linux keeps the peak of the process that started a + spawned worker. It went red with ru_maxrss read there.""" + status = tmp_path / "status" + status.write_text(STATUS) + _on(monkeypatch, "linux", status=status) + assert resident.peak_resident_bytes() == 17600 * 1024 + assert resident.reading() == "VmHWM of /proc/self/status" + + def test_linux_without_the_file_gives_none_and_says_why( + self, monkeypatch, tmp_path + ): + _on(monkeypatch, "linux", status=tmp_path / "absent") + assert resident.peak_resident_bytes() is None + assert resident.why_not_read() == ( + "VmHWM could not be read from /proc/self/status" + ) + + def test_macos_reads_ru_maxrss_in_bytes(self, monkeypatch): + _on(monkeypatch, "darwin", ru_maxrss=1000) + assert resident.peak_resident_bytes() == 1000 + assert resident.reading() == "ru_maxrss" + + def test_elsewhere_nothing_is_read(self, monkeypatch): + _on(monkeypatch, "freebsd14") + assert resident.peak_resident_bytes() is None + assert resident.reading() is None + assert resident.why_not_read() == ( + "the peak resident memory of a process is not read on freebsd14" + ) + + +@pytest.mark.parametrize( + "module, name", + [ + ("cil_regionalization.reduce.pandas_blocks", "_peak_gb"), + ("cil_regionalization.pipelines.montecarlo", "_peak_rss_gb"), + ], +) +def test_both_stages_log_the_same_reading_in_gigabytes( + monkeypatch, tmp_path, module, name +): + """The reduce stage read ru_maxrss and went red on that. The + aggregate stage also took Linux's kibibytes for thousands of bytes.""" + import importlib + + status = tmp_path / "status" + status.write_text("VmHWM:\t 1000000 kB\n") + _on(monkeypatch, "linux", status=status) + assert getattr(importlib.import_module(module), name)() == 1.024 From adb950e2e9a62322733add081b8b065efc223bd2 Mon Sep 17 00:00:00 2001 From: Sebastian Cadavid Sanchez Date: Fri, 27 Nov 2026 22:22:06 -0600 Subject: [PATCH 2/5] measure and record every block, and judge only the first Each block is read the same way as the first, and the manifest records each block's own growth, with a summary of the spread of the measured blocks, the heaviest over the estimate and the first over the heaviest. On Linux a later block's growth is taken from the resident memory before it, VmRSS, since the peak before it is that of an earlier block. Only the first block is judged, so nothing is refused that was not before. --- CHANGELOG.md | 19 +++ README.md | 14 ++ cil_regionalization/reduce/pandas_blocks.py | 121 ++++++++++++++++-- cil_regionalization/resident.py | 31 +++-- tests/integration/test_montecarlo_pipeline.py | 43 +++++++ tests/unit/test_block_sizing.py | 88 +++++++++++++ tests/unit/test_resident.py | 15 ++- 7 files changed, 309 insertions(+), 22 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index bba3268..02e1a99 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,25 @@ ## Unreleased +**Every block of a reduce is measured and recorded, and only the first +is judged.** Nothing is refused that was not before. A run then shows +how much blocks of one size vary from worker to worker and how far the +first block sits from the heaviest, which is what the tolerance of twice +the estimate is to be set from, where one measured first block could say +neither. Each block's entry under `reduce.block_size.every_block` gives +the readings around it and its own growth, and `over_every_block` the +spread of the measured blocks' bytes a kept row, the heaviest over the +estimate and the first over the heaviest. A block's growth is read off +its process's peak after it, so only a block that took its process to a +new peak has one. On Linux it is taken from the resident memory before +the block, VmRSS of `/proc/self/status`, because the peak before a later +block is that of an earlier one. On macOS, which does not read the +resident memory of the moment, only a worker's first block has one. Each +worker's first block and each block that took its worker higher than +before are measured, and a block lighter than one its worker built +earlier is recorded without a growth, saying why. The log line of each +block gives its bytes a kept row. + **On Linux a worker's peak resident memory is read as VmHWM of `/proc/self/status`, where it was `ru_maxrss`.** On Linux `ru_maxrss` survives an exec, so a worker started by spawn read the peak of the diff --git a/README.md b/README.md index 09daf8e..8f33140 100644 --- a/README.md +++ b/README.md @@ -647,6 +647,20 @@ the pages it shares with that process as its own, so the peaks under alone holds, which errs on the side of the budget. The growth, the difference of two peaks that both count those pages, is exact. +Every block is measured and recorded under +`reduce.block_size.every_block`, and only the first is judged. A block's +own growth is read off its process's peak after it, so only a block that +took its process to a new peak has one. On Linux it is taken from the +resident memory before the block, VmRSS of `/proc/self/status`. On +macOS, where that is not read, only a worker's first block has one, from +the peak once the worker had set itself up. So each worker's first block +is measured, and so is each block that took its worker higher than +before, while a block lighter than one its worker built earlier has no +growth and the record says why. `reduce.block_size.over_every_block` +gives the spread of the measured blocks' bytes a kept row, the heaviest +over the estimate, and the first over the heaviest. That is what the +tolerance of twice the estimate is to be set from. + Someone who has measured their own runs can declare the size of a block instead, in targets, a whole number of the leaves' row groups: diff --git a/cil_regionalization/reduce/pandas_blocks.py b/cil_regionalization/reduce/pandas_blocks.py index 16cd8d5..5a28ee4 100644 --- a/cil_regionalization/reduce/pandas_blocks.py +++ b/cil_regionalization/reduce/pandas_blocks.py @@ -26,6 +26,7 @@ import multiprocessing import os +import statistics import sys import warnings from concurrent.futures import ProcessPoolExecutor, as_completed @@ -44,6 +45,7 @@ ReduceRequest, ) from cil_regionalization.resident import peak_resident_bytes as _peak_resident_bytes +from cil_regionalization.resident import resident_bytes as _resident_bytes from cil_regionalization.stats import ( GroupError, UnweightedModelWeightsWarning, @@ -333,6 +335,14 @@ def judge(first: dict) -> None: raise ValueError("reduce: the leaves hold no row inside any window") stats = pd.concat(frames, ignore_index=True) sizing.pop("refused", None) + # every block measured and recorded, and none of it judged + every = sorted( + (_block_reading(r) for r in results), key=lambda e: e["block"][0] + ) + sizing.update( + every_block=every, + over_every_block=_over_every_block(every, plan["row_bytes"]), + ) report = { **{k: v for k, v in self.describe(request).items() if k != "text"}, "block_size": sizing, @@ -439,7 +449,7 @@ def _run_blocks(request: ReduceRequest, blocks, n_workers: int, judge) -> list[d judge(results[0]) _log_block(results, len(blocks)) for block in rest: - results.append(_reduce_block(block)) + results.append(_read_block(block)) _log_block(results, len(blocks)) return results results = [] @@ -458,7 +468,7 @@ def _run_blocks(request: ReduceRequest, blocks, n_workers: int, judge) -> list[d results[0]["start_method"] = context.get_start_method() judge(results[0]) _log_block(results, len(blocks)) - futures = {executor.submit(_reduce_block, block): block for block in rest} + futures = {executor.submit(_read_block, block): block for block in rest} for future in as_completed(futures): results.append(_collect(future, futures[future], executor)) _log_block(results, len(blocks)) @@ -491,15 +501,15 @@ def _collect(future, block, executor) -> dict: def _measured_block(block: tuple[int, int]) -> dict: - """`_reduce_block`, with the growth of the process's peak resident + """`_read_block`, with the growth of the process's peak resident memory over the block under 'resident_growth_bytes', or None and the reason under 'measure_unavailable'. The growth is taken from the peak once the worker has set itself up and before it reads the block, so what the worker holds for every block, its imports and its target table, is outside it.""" - setup = _peak_resident_bytes() - result = _reduce_block(block) - peak = _peak_resident_bytes() + result = _read_block(block) + setup = result["reading"]["peak_before_bytes"] + peak = result["reading"]["peak_after_bytes"] growth, unavailable = _growth(setup, peak, _STATE["own_process"]) result.update( worker_setup_peak_bytes=setup, @@ -510,6 +520,98 @@ def _measured_block(block: tuple[int, int]) -> dict: return result +def _read_block(block: tuple[int, int]) -> dict: + """`_reduce_block`, with the process's peak resident memory before and + after the block and its resident memory before it under 'reading'.""" + peak_before = _peak_resident_bytes() + resident_before = _resident_bytes() + result = _reduce_block(block) + peak_after = _peak_resident_bytes() + _STATE["blocks_read"] = _STATE.get("blocks_read", 0) + 1 + result["reading"] = { + "peak_before_bytes": peak_before, + "resident_before_bytes": resident_before, + "peak_after_bytes": peak_after, + "nth_in_process": _STATE["blocks_read"], + "own_process": _STATE["own_process"], + } + return result + + +def _block_reading(result: dict) -> dict: + """A block's entry in the manifest, with what the block itself grew + the resident memory by, or None and why. The growth is read off the + peak after the block, so only a block that raised its process's peak + has one. It is taken from the resident memory before the block where + that is read. Elsewhere only a worker's first block has a growth, + from the peak once the worker had set itself up.""" + reading, rows = result["reading"], result["rows"] + before = reading["peak_before_bytes"] + resident_before = reading["resident_before_bytes"] + after = reading["peak_after_bytes"] + growth = base = unavailable = None + if not rows: + unavailable = "the block kept no rows" + elif before is None or after is None: + unavailable = resident.why_not_read() + elif after <= before: + unavailable = _FLAT_PEAK + elif resident_before is not None: + growth, base = after - resident_before, "the resident memory before it" + elif reading["nth_in_process"] == 1 and reading["own_process"]: + growth, base = after - before, "the peak once the worker had set itself up" + else: + unavailable = ( + f"the resident memory before the block is not read on " + f"{sys.platform}, and the peak before it is that of what the " + f"process did earlier" + ) + return { + "block": list(result["block"]), + "rows": rows, + "pid": result.get("pid"), + "nth_in_process": reading["nth_in_process"], + "peak_before_bytes": before, + "resident_before_bytes": resident_before, + "peak_after_bytes": after, + "growth_bytes": growth, + "bytes_per_row": growth / rows if growth is not None else None, + "growth_from": base, + "unavailable": unavailable, + } + + +def _over_every_block(entries: list[dict], estimate: float) -> dict: + """What the measured blocks of a run say beside the estimate, the + spread of their bytes a kept row and how far the first block sits + from the heaviest. None of it is judged.""" + measured = [e for e in entries if e["bytes_per_row"] is not None] + summary = { + "blocks": len(entries), + "measured": len(measured), + "bytes_per_row_min": None, + "bytes_per_row_median": None, + "bytes_per_row_max": None, + "heaviest_block": None, + "heaviest_over_estimate": None, + "first_over_heaviest": None, + } + if not measured: + return summary + per_row = sorted(e["bytes_per_row"] for e in measured) + heaviest = max(measured, key=lambda e: e["bytes_per_row"]) + first = entries[0]["bytes_per_row"] + summary.update( + bytes_per_row_min=per_row[0], + bytes_per_row_median=statistics.median(per_row), + bytes_per_row_max=per_row[-1], + heaviest_block=heaviest["block"], + heaviest_over_estimate=per_row[-1] / estimate if estimate else None, + first_over_heaviest=first / per_row[-1] if first is not None else None, + ) + return summary + + def _growth( started: int | None, peak: int | None, own_process: bool ) -> tuple[int | None, str | None]: @@ -526,10 +628,12 @@ def _growth( def _log_block(results: list[dict], n_blocks: int) -> None: last = results[-1] + per_row = _block_reading(last)["bytes_per_row"] + grew = "" if per_row is None else f", {per_row:.0f} bytes a kept row" print( f"reduce: block {len(results)}/{n_blocks}, row groups " f"{last['block'][0]}-{last['block'][1] - 1}, {last['rows']:,} rows, " - f"worker peak {last['peak_gb']:.2f}G", + f"worker peak {last['peak_gb']:.2f}G{grew}", flush=True, ) @@ -541,7 +645,8 @@ def _init_worker(request: ReduceRequest, own_process: bool = True) -> None: """Load what every block needs. ``own_process`` is False where the blocks run in the process that planned the run, whose peak resident memory is not the worker's own.""" - _STATE.update(own_process=own_process) + # a forked worker starts with the state of the process it came from + _STATE.update(own_process=own_process, blocks_read=0) targets = leaf_format.TargetTable.read( Path(request.leaves_root) / request.targets_file ) diff --git a/cil_regionalization/resident.py b/cil_regionalization/resident.py index 3a7c7d6..8ba70f1 100644 --- a/cil_regionalization/resident.py +++ b/cil_regionalization/resident.py @@ -4,7 +4,8 @@ the process's own address space. ``ru_maxrss`` there survives an exec, so a worker started by spawn would read the peak of the process that started it. On macOS it is ``ru_maxrss``, which a new worker starts -afresh. Elsewhere it is not read, rather than guessed. +afresh. Elsewhere it is not read, rather than guessed. The resident +memory of the moment, VmRSS, is read on Linux alone. """ from __future__ import annotations @@ -20,10 +21,7 @@ def peak_resident_bytes() -> int | None: not read. Under fork it counts the pages the process shares with its parent as its own.""" if sys.platform.startswith("linux"): - try: - return vmhwm_bytes(_PROC_STATUS.read_text()) - except OSError: - return None + return _from_status("VmHWM") if sys.platform == "darwin": import resource @@ -32,12 +30,20 @@ def peak_resident_bytes() -> int | None: return None -def vmhwm_bytes(status: str) -> int | None: - """VmHWM of the text of a ``/proc`` status file in bytes, or None if - the text has no VmHWM counted in kB, which there are kibibytes.""" +def resident_bytes() -> int | None: + """This process's resident memory at this moment in bytes, read as + VmRSS of ``/proc/self/status`` on Linux, or None elsewhere.""" + if sys.platform.startswith("linux"): + return _from_status("VmRSS") + return None + + +def status_bytes(status: str, field: str) -> int | None: + """A field of the text of a ``/proc`` status file in bytes, or None if + the text has no such field counted in kB, which there are kibibytes.""" for line in status.splitlines(): key, _, value = line.partition(":") - if key == "VmHWM": + if key == field: number, _, unit = value.strip().partition(" ") if number.isdigit() and unit.strip() == "kB": return int(number) * 1024 @@ -45,6 +51,13 @@ def vmhwm_bytes(status: str) -> int | None: return None +def _from_status(field: str) -> int | None: + try: + return status_bytes(_PROC_STATUS.read_text(), field) + except OSError: + return None + + def reading() -> str | None: """What `peak_resident_bytes` reads on this platform, or None.""" if sys.platform.startswith("linux"): diff --git a/tests/integration/test_montecarlo_pipeline.py b/tests/integration/test_montecarlo_pipeline.py index dfb5a57..7c16f92 100644 --- a/tests/integration/test_montecarlo_pipeline.py +++ b/tests/integration/test_montecarlo_pipeline.py @@ -2815,6 +2815,13 @@ def forked_workers_with_a_rising_peak(monkeypatch): yield from _forked_workers(monkeypatch, lambda: 10**9 + 10**4 * next(readings)) +@pytest.fixture +def forked_workers_with_a_slow_peak(monkeypatch): + """A peak that rises a byte with every reading.""" + readings = itertools.count(1) + yield from _forked_workers(monkeypatch, lambda: 10**9 + next(readings)) + + @pytest.fixture def forked_workers_with_a_flat_peak(monkeypatch): """A peak that never rises, as over a block that fits in memory the @@ -3214,6 +3221,42 @@ def test_a_first_block_within_the_estimate_is_judged_and_runs( # the peak the fixture puts in, read in the worker assert sizing["measured_growth_bytes"] % 10**4 == 0 + @pytest.mark.parametrize("n_workers, judged", [(1, False), (2, True)]) + @pytest.mark.usefixtures("forked_workers_with_a_slow_peak") + def test_every_block_is_measured_and_recorded_and_only_the_first_judged( + self, weights_dir, tmp_path, monkeypatch, n_workers, judged + ): + """The peak rises a byte with every reading, so the first block is + judged well within an estimate of a byte a row where it has a + worker of its own. Each block's own growth, from a resident memory + put far below the peak, is far above the estimate, and it is + recorded and refuses nothing. It went red with the first block + alone recorded.""" + from cil_regionalization.reduce import pandas_blocks + + raw, whole, out = self._aggregated(weights_dir, tmp_path) + monkeypatch.setattr(pandas_blocks, "JUDGED_ROWS", 1) + monkeypatch.setattr(pandas_blocks, "BYTES_PER_ROW", 1) + monkeypatch.setattr(pandas_blocks, "BYTES_PER_DIMENSION", 0) + monkeypatch.setattr(pandas_blocks, "_resident_bytes", lambda: 10**6) + # a row group of 24 rows at a byte a row fits a worker of 30 bytes, + # and two do not, so there are two blocks + got = self._reduce(raw, memory_gb=n_workers * 30e-9, n_workers=n_workers) + _same_frames(got.stats, whole.stats) + sizing = json.loads((out / "again.manifest.json").read_text())["reduce"][ + "block_size" + ] + assert sizing["judged"] is judged + every = sizing["every_block"] + assert [e["block"] for e in every] == [[0, 1], [1, 2]] + assert [e["growth_from"] for e in every] == [ + "the resident memory before it" + ] * 2 + assert all(e["growth_bytes"] > 10**8 for e in every) + over = sizing["over_every_block"] + assert over["blocks"] == over["measured"] == 2 + assert over["heaviest_over_estimate"] > 10**5 + @pytest.mark.usefixtures("forked_workers_with_a_flat_peak") def test_a_forked_worker_whose_peak_did_not_rise_is_not_judged( self, weights_dir, tmp_path, monkeypatch diff --git a/tests/unit/test_block_sizing.py b/tests/unit/test_block_sizing.py index 64d4691..93f73bc 100644 --- a/tests/unit/test_block_sizing.py +++ b/tests/unit/test_block_sizing.py @@ -109,6 +109,94 @@ def block(rows): assert got["resident_growth_bytes"] == 10 +def _result(rows=100, before=1000, resident=None, after=1600, nth=2, own=True): + return { + "block": (4, 5), + "rows": rows, + "pid": 7, + "reading": { + "peak_before_bytes": before, + "resident_before_bytes": resident, + "peak_after_bytes": after, + "nth_in_process": nth, + "own_process": own, + }, + } + + +class TestEveryBlock: + """What `_block_reading` records of each block, none of it judged.""" + + def test_a_block_that_raised_the_peak_grew_from_the_resident_memory(self): + """Not from the peak before it, which an earlier block set. It went + red with the growth taken from that peak, 600 here.""" + from cil_regionalization.reduce.pandas_blocks import _block_reading + + got = _block_reading(_result(resident=400)) + assert got["growth_bytes"] == 1200 and got["bytes_per_row"] == 12 + assert got["growth_from"] == "the resident memory before it" + assert got["unavailable"] is None and got["block"] == [4, 5] + + def test_a_block_that_did_not_raise_the_peak_has_no_growth(self): + from cil_regionalization.reduce.pandas_blocks import _FLAT_PEAK, _block_reading + + got = _block_reading(_result(resident=400, after=1000)) + assert got["growth_bytes"] is None and got["unavailable"] == _FLAT_PEAK + + def test_without_the_resident_memory_a_worker_s_first_block_alone(self): + """As on macOS. A later block there would have been read from the + peak an earlier one set.""" + from cil_regionalization.reduce.pandas_blocks import _block_reading + + first = _block_reading(_result(nth=1)) + assert first["growth_bytes"] == 600 + assert first["growth_from"] == "the peak once the worker had set itself up" + later = _block_reading(_result(nth=2)) + assert later["growth_bytes"] is None + assert ( + "the resident memory before the block is not read" in (later["unavailable"]) + ) + planned_in = _block_reading(_result(nth=1, own=False)) + assert planned_in["growth_bytes"] is None + + def test_a_block_without_rows_or_without_a_reading_has_no_growth(self): + from cil_regionalization.reduce.pandas_blocks import _block_reading + + assert _block_reading(_result(rows=0))["unavailable"] == ( + "the block kept no rows" + ) + assert _block_reading(_result(before=None))["growth_bytes"] is None + + def test_the_summary_of_every_block(self): + """Over the measured blocks only, the first being the one that + starts the run. The median is not the mean here.""" + from cil_regionalization.reduce.pandas_blocks import _over_every_block + + entries = [ + {"block": [0, 1], "bytes_per_row": 100.0}, + {"block": [1, 2], "bytes_per_row": None}, + {"block": [2, 3], "bytes_per_row": 400.0}, + {"block": [3, 4], "bytes_per_row": 200.0}, + ] + assert _over_every_block(entries, 250) == { + "blocks": 4, + "measured": 3, + "bytes_per_row_min": 100.0, + "bytes_per_row_median": 200.0, + "bytes_per_row_max": 400.0, + "heaviest_block": [2, 3], + "heaviest_over_estimate": 1.6, + "first_over_heaviest": 0.25, + } + + def test_a_summary_with_nothing_measured_says_so(self): + from cil_regionalization.reduce.pandas_blocks import _over_every_block + + got = _over_every_block([{"block": [0, 1], "bytes_per_row": None}], 250) + assert got["blocks"] == 1 and got["measured"] == 0 + assert got["heaviest_over_estimate"] is None + + class TestJudged: """What `_block_size_record` makes of a first block.""" diff --git a/tests/unit/test_resident.py b/tests/unit/test_resident.py index 931c38d..a20e7a8 100644 --- a/tests/unit/test_resident.py +++ b/tests/unit/test_resident.py @@ -33,10 +33,11 @@ def _on(monkeypatch, platform, *, status=None, ru_maxrss=419_900): monkeypatch.setattr(resident, "_PROC_STATUS", status) -class TestVmHWM: - def test_the_high_water_mark_in_bytes(self): - """Its kB are kibibytes. It went red on thousands of bytes.""" - assert resident.vmhwm_bytes(STATUS) == 17600 * 1024 +class TestStatus: + def test_the_high_water_mark_and_the_resident_memory_in_bytes(self): + """Their kB are kibibytes. It went red on thousands of bytes.""" + assert resident.status_bytes(STATUS, "VmHWM") == 17600 * 1024 + assert resident.status_bytes(STATUS, "VmRSS") == 17200 * 1024 @pytest.mark.parametrize( "text", @@ -50,7 +51,7 @@ def test_the_high_water_mark_in_bytes(self): def test_a_status_without_a_vmhwm_in_kb_gives_none(self, text): """Rather than a number guessed. It went red with any unit read as kB.""" - assert resident.vmhwm_bytes(text) is None + assert resident.status_bytes(text, "VmHWM") is None class TestPlatforms: @@ -62,20 +63,24 @@ def test_linux_reads_vmhwm_and_not_ru_maxrss(self, monkeypatch, tmp_path): _on(monkeypatch, "linux", status=status) assert resident.peak_resident_bytes() == 17600 * 1024 assert resident.reading() == "VmHWM of /proc/self/status" + assert resident.resident_bytes() == 17200 * 1024 def test_linux_without_the_file_gives_none_and_says_why( self, monkeypatch, tmp_path ): _on(monkeypatch, "linux", status=tmp_path / "absent") assert resident.peak_resident_bytes() is None + assert resident.resident_bytes() is None assert resident.why_not_read() == ( "VmHWM could not be read from /proc/self/status" ) def test_macos_reads_ru_maxrss_in_bytes(self, monkeypatch): + """The resident memory of the moment is not read there.""" _on(monkeypatch, "darwin", ru_maxrss=1000) assert resident.peak_resident_bytes() == 1000 assert resident.reading() == "ru_maxrss" + assert resident.resident_bytes() is None def test_elsewhere_nothing_is_read(self, monkeypatch): _on(monkeypatch, "freebsd14") From 32d54cbd0c80fec3730d2246d6c1b27e6ddb41eb Mon Sep 17 00:00:00 2001 From: Sebastian Cadavid Sanchez Date: Fri, 27 Nov 2026 23:00:22 -0600 Subject: [PATCH 3/5] state every weights-config choice whose wrong value gives another number normalization, weights[].fallback and kind, backend.coverage, regions and source on_invalid_geometry, grid.offset and grid.lon_convention have no default, and a config that leaves one out is refused naming it. The library's own copies of the normalization default follow the caller, and a weights manifest without it is refused. The implicit-fallback warning goes with the fallback default. A BigQuery weight declares the column of its table, where pop was read from population. Every config and example here states the values its defaults gave, so no number moves. --- CHANGELOG.md | 52 ++++ cil_regionalization/apply.py | 11 +- cil_regionalization/backends/bigquery.py | 13 +- cil_regionalization/backends/local.py | 4 +- cil_regionalization/config.py | 69 +++++- cil_regionalization/fallback.py | 44 +--- cil_regionalization/manifest.py | 11 +- cil_regionalization/schema.py | 4 +- cil_regionalization/weights.py | 21 +- docs/reference.md | 29 ++- examples/climate/README.md | 6 +- .../climate/degree_days_from_daily_grid.ipynb | 2 + examples/climate/grid025_to_ir_phl_deu.toml | 1 + examples/climate/prepare_data.py | 6 +- examples/climate/quickstart.ipynb | 1 + examples/france/france.py | 4 + examples/france/synthetic_data.py | 4 + examples/gadm20/ir_to_adm1_full.toml | 2 + .../ir_to_adm1_full_per_destination.toml | 2 + examples/gadm20/ir_to_adm1_subset.toml | 2 + examples/gadm20/ir_to_adm2_full.toml | 2 + .../ir_to_adm2_full_per_destination.toml | 2 + .../gadm41/ir_to_adm1_per_destination.toml | 2 + examples/gadm41/ir_to_adm1_per_source.toml | 2 + .../gadm41/ir_to_adm2_per_destination.toml | 2 + examples/gadm41/ir_to_adm2_per_source.toml | 2 + examples/s51/grid1deg_to_ir.toml | 1 + examples/s51/s51_canonical.toml | 1 + examples/s51/s51_supplement.toml | 1 + tests/integration/test_apply.py | 4 +- tests/integration/test_bigquery_backend.py | 44 +++- tests/integration/test_cross_backend.py | 23 +- tests/integration/test_from_table.py | 123 ++++++++-- tests/integration/test_local_backend.py | 30 ++- tests/integration/test_montecarlo_pipeline.py | 4 +- tests/integration/test_netcdf_grid.py | 10 +- tests/integration/test_polygon_mode.py | 32 ++- tests/integration/test_regions_find.py | 9 + tests/unit/test_config.py | 228 +++++++++++++++--- tests/unit/test_daily_grid_cells.py | 6 +- tests/unit/test_fallback.py | 165 ++++--------- tests/unit/test_legacy_export.py | 7 +- tests/unit/test_manifest.py | 30 ++- tests/unit/test_mass_balance.py | 2 + tests/unit/test_merge.py | 6 +- tests/unit/test_regions.py | 59 ++++- tests/unit/test_schema.py | 48 +++- tests/unit/test_validate.py | 36 ++- 48 files changed, 857 insertions(+), 312 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02e1a99..9c840eb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,58 @@ ## Unreleased +**A weights config states every choice whose wrong value gives another +number, as the quantile method and the summation already do.** The rule: +a default that fails loudly when it is wrong is fine, and a default that +silently produces a different number is not. So these have no default +any more, and a config that leaves one out is refused naming it: +`normalization`, which was `"per_destination"`; `weights[].fallback`, +which was `"area"`; `weights[].kind`, which was `"point_sum"`; +`backend.coverage`, which was `"exact_fraction"`; +`regions.on_invalid_geometry` and `source.on_invalid_geometry`, which +were `"repair"`; and `grid.offset` and `grid.lon_convention`, which were +`"center"` and `"[-180,180)"`. The last two matter most. A grid at the +wrong offset or longitude origin still covers the regions, so the +weights came out on other cells with nothing said, the error the +BigQuery backend has refused for an edge-offset grid since #34. The area +weight takes neither `fallback` nor `kind`, since its total is the +region's own area and it reads no raster, and it refuses them as it +refuses a raster or table. + +The library's own copies of the normalization default follow what the +caller says. `WeightsArtifact.from_table`, `compute_native_weights`, +`apply_fallback`, `Manifest` and `OutputSchema` take it with no default, +and `WeightsArtifact.load` refuses a weights manifest that does not +record it, where it read one as `"per_destination"`. The warning when +the fallback fired often under a policy left unstated goes with that +default, `_IMPLICIT_DEFAULT_FRAC` and `_IMPLICIT_DEFAULT_MIN` too. It +announced that an unstated default had fired, and `weight_share` +measures how much of a target's basis contributed, which is the same +information. The BigQuery backend read a weight named `pop` from the +column `population` of its table and any other weight from the column of +its own name. That was one table's layout and not a rule, so a BigQuery +weight now declares `weights[].column` beside `weights[].table`, and a +local weight refuses one. + +Left alone, and why. `read_gmst` and `[stats.warming_levels]` keep +`time_col`, `value_col` and `sep`, because a wrong value there fails to +find a column and stops. `from_table` keeps recognising coordinate +columns by name, because it refuses ambiguity and checks the values +against the grid. And every default that refuses stays, +`on_null_geometry`, `on_unknown_id`, `on_zero_overlap`, `on_unmatched`, +`on_zero_weight` and `on_absent_from_data`, because a default that +refuses chooses nothing in silence. + +This breaks every weights config that relied on one of the defaults. The +configs and examples of this repository state the values their defaults +gave them, so none of their numbers moves. The recipes repository, +pinned on v0.5.0, needs the same keys when its pin moves, where it +already changes for the quantile method, the summation, the declared +members and the model weight names. The config hash a weights manifest +records changes for every config, the same values included, since a +weight now holds its column and the area weight no fallback or kind, so +a hash from an earlier run does not match one written now. + **Every block of a reduce is measured and recorded, and only the first is judged.** Nothing is refused that was not before. A run then shows how much blocks of one size vary from worker to worker and how far the diff --git a/cil_regionalization/apply.py b/cil_regionalization/apply.py index 9d07394..95a729c 100644 --- a/cil_regionalization/apply.py +++ b/cil_regionalization/apply.py @@ -134,7 +134,12 @@ def load(cls, output_dir: str | Path, stem: str = "weights") -> "WeightsArtifact missing = [ k - for k in ("id_fields", "source_key_columns", "weight_names") + for k in ( + "id_fields", + "source_key_columns", + "weight_names", + "normalization", + ) if manifest.get(k) is None ] if missing: @@ -151,7 +156,7 @@ def load(cls, output_dir: str | Path, stem: str = "weights") -> "WeightsArtifact id_fields=tuple(manifest["id_fields"]), weight_names=tuple(manifest["weight_names"]), source_units=source_units, - normalization=manifest.get("normalization", "per_destination"), + normalization=manifest["normalization"], ) return cls( frame=frame, @@ -169,8 +174,8 @@ def from_table( id_fields: Sequence[str], weights: Mapping[str, str], source: str, + normalization: str, source_keys: Sequence[str] | None = None, - normalization: str = "per_destination", regions_version: str | None = None, check: bool = True, tolerance: float = 1e-6, diff --git a/cil_regionalization/backends/bigquery.py b/cil_regionalization/backends/bigquery.py index ef34e6a..d53f369 100644 --- a/cil_regionalization/backends/bigquery.py +++ b/cil_regionalization/backends/bigquery.py @@ -995,7 +995,15 @@ def _build_main_sql( return sql def _weight_value_column(self, weight: WeightSpec) -> str: - return {"pop": "population"}.get(weight.name, weight.name) + """The column of the weight's table that holds its values, as + ``weights[].column`` declares it.""" + if weight.column is None: + raise ValueError( + f"weights.{weight.name}.column is required for the bigquery " + f"backend: the column of weights.{weight.name}.table that holds " + f"the weight's values" + ) + return weight.column # ----- BigQuery execution ---------------------------------------------- @@ -1048,6 +1056,7 @@ def _assemble_result( id_fields, "area", raw_col="raw", + normalization=cfg.normalization, ) pieces: list[pd.DataFrame] = [area_native] @@ -1062,7 +1071,7 @@ def _assemble_result( spec.name, spec.fallback, id_fields, - policy_explicit=spec.fallback_explicit, + normalization=cfg.normalization, ) pieces.append(piece) final = self._join_pieces(pieces, id_fields) diff --git a/cil_regionalization/backends/local.py b/cil_regionalization/backends/local.py index 620bdb1..4022288 100644 --- a/cil_regionalization/backends/local.py +++ b/cil_regionalization/backends/local.py @@ -149,6 +149,7 @@ def _compute_grid( id_fields, "area", raw_col="raw", + normalization=cfg.normalization, ) per_weight_frames: list[pd.DataFrame] = [area_native] @@ -163,7 +164,7 @@ def _compute_grid( spec.name, spec.fallback, id_fields, - policy_explicit=spec.fallback_explicit, + normalization=cfg.normalization, ) per_weight_frames.append(piece) @@ -325,7 +326,6 @@ def _compute_polygons( spec.name, spec.fallback, id_fields, - policy_explicit=spec.fallback_explicit, source_units=source_units, normalization=cfg.normalization, ) diff --git a/cil_regionalization/config.py b/cil_regionalization/config.py index 5790333..bf8d60a 100644 --- a/cil_regionalization/config.py +++ b/cil_regionalization/config.py @@ -85,7 +85,9 @@ class RegionsConfig(_Strict): version: Optional[str] = None keep: Optional[dict[str, list[Any]]] = None drop: Optional[dict[str, list[Any]]] = None - on_invalid_geometry: InvalidGeomPolicy = "repair" + # No default: repair changes a region's geometry and skip leaves it + # out, so a wrong choice gives other weights with nothing said. + on_invalid_geometry: InvalidGeomPolicy # NULL geometries in BQ regions tables: error (default, abort and list # the offending hierids) or skip (exclude them, record in the manifest # under null_geometry_regions). Measured 17 NULL hierids in the s51 IR @@ -122,8 +124,11 @@ def _one_source(self) -> "RegionsConfig": class GridConfig(_Strict): mode: GridMode resolution: Optional[float] = None - offset: GridOffset = "center" - lon_convention: LonConvention = "[-180,180)" + # No default for either: a grid at the wrong offset or longitude + # origin still covers the regions, so the weights come out on cells + # half a cell or a hemisphere from the data's, with nothing said. + offset: GridOffset + lon_convention: LonConvention path: Optional[str] = None table: Optional[str] = None @@ -179,7 +184,7 @@ class SourceConfig(_Strict): path: str = Field(min_length=1) id_fields: list[str] = Field(min_length=1) version: str = Field(min_length=1) - on_invalid_geometry: InvalidGeomPolicy = "repair" + on_invalid_geometry: InvalidGeomPolicy on_zero_overlap: Literal["error", "skip"] = "error" # A source unit whose intersected geodesic area falls below this # share of the unit's own total area is partially covered by the @@ -196,11 +201,18 @@ class SourceConfig(_Strict): class WeightConfig(_Strict): + """One weight of the run. Every weight but ``area`` needs its + ``fallback`` and its ``kind``, which have no default, and the area + weight takes neither, since its total is the region's own area and it + reads no raster. A BigQuery weight names the ``column`` of its + ``table`` that holds its values.""" + name: str = Field(min_length=1) raster: Optional[str] = None table: Optional[str] = None - fallback: FallbackPolicy = "area" - kind: WeightKind = "point_sum" + column: Optional[str] = Field(default=None, min_length=1) + fallback: Optional[FallbackPolicy] = None + kind: Optional[WeightKind] = None class LocalBackendOptions(_Strict): @@ -316,7 +328,8 @@ class BigQueryBackendOptions(_Strict): class BackendConfig(_Strict): kind: BackendKind - coverage: CoverageMode = "exact_fraction" + # No default: the two ways of covering a cell give other weights. + coverage: CoverageMode local: LocalBackendOptions = Field(default_factory=LocalBackendOptions) bigquery: BigQueryBackendOptions = Field(default_factory=BigQueryBackendOptions) @@ -373,12 +386,13 @@ class Config(_Strict): backend: BackendConfig output: OutputConfig validation: ValidationConfig = Field(default_factory=ValidationConfig) - # Top-level TOML key. Existing configs omit it and keep the - # per_destination behavior they were written for. The grid backends - # support per_destination only; polygon mode supports both directions + # Top-level TOML key, with no default: the two directions are + # transposes over the same geometry, and either gives plausible + # numbers where the other was meant. The grid backends support + # per_destination only; polygon mode supports both directions # (per_source is the allocation direction weight files for extensive # quantities need). - normalization: Normalization = "per_destination" + normalization: Normalization @model_validator(mode="after") def _geometry_mode(self) -> "Config": @@ -450,18 +464,47 @@ def _weights_match_backend(self) -> "Config": raise ValueError( f"weights.{w.name}: 'area' weight does not accept raster or table" ) + given = [ + key + for key in ("fallback", "kind", "column") + if getattr(w, key) is not None + ] + if given: + raise ValueError( + f"weights.area takes no {_listed(given)}: its total is " + f"the region's own area, which is never zero where the " + f"region has cells, and it reads no raster or table" + ) continue + missing = [key for key in ("fallback", "kind") if getattr(w, key) is None] + if missing: + raise ValueError( + f"weights.{w.name} needs " + f"{_listed([f'weights.{w.name}.{key}' for key in missing])}. " + f"fallback says what a region whose {w.name} total is zero " + f"gets, one of area, zero, error or nan, and kind how the " + f"raster is summed, point_sum or area_weighted_sum. Neither " + f"has a default, since a wrong one gives other weights with " + f"nothing said." + ) if self.backend.kind == "local": if w.raster is None: raise ValueError( f"weights.{w.name}: backend.kind='local' requires " f"weights.{w.name}.raster" ) + if w.column is not None: + raise ValueError( + f"weights.{w.name}.column names a column of a BigQuery " + f"table, and backend.kind='local' reads weights.{w.name}" + f".raster" + ) else: # bigquery - if w.table is None: + if w.table is None or w.column is None: raise ValueError( f"weights.{w.name}: backend.kind='bigquery' requires " - f"weights.{w.name}.table" + f"weights.{w.name}.table and weights.{w.name}.column, the " + f"column of the table that holds the weight's values" ) return self diff --git a/cil_regionalization/fallback.py b/cil_regionalization/fallback.py index bff3ee2..04b635b 100644 --- a/cil_regionalization/fallback.py +++ b/cil_regionalization/fallback.py @@ -14,16 +14,10 @@ them weight NaN and the method ``"nan"``, and the sum-to-one check passes the group over. ``"error"`` raises, naming the groups. A group whose total area is zero raises under every policy. - -When the policy was not set in the config and the fallback fires for at -least max(5, 5% of the groups), `apply_fallback` logs a warning naming the -default and the alternatives. """ from __future__ import annotations -import logging - import pandas as pd from cil_regionalization.config import FallbackPolicy, Normalization @@ -36,13 +30,6 @@ ) -logger = logging.getLogger(__name__) - - -_IMPLICIT_DEFAULT_FRAC = 0.05 -_IMPLICIT_DEFAULT_MIN = 5 - - def _group_fields( id_fields: list[str], source_units: SourceUnits, @@ -64,8 +51,8 @@ def compute_native_weights( weight_name: str, raw_col: str = "raw", *, + normalization: Normalization, source_units: SourceUnits = GRID_CELLS, - normalization: Normalization = "per_destination", ) -> pd.DataFrame: """Each row's ``raw_col`` divided by its group's total, as the weight, raw and method columns of ``weight_name``, with every method @@ -114,9 +101,8 @@ def apply_fallback( id_fields: list[str], raw_col: str = "raw", *, - policy_explicit: bool = True, + normalization: Normalization, source_units: SourceUnits = GRID_CELLS, - normalization: Normalization = "per_destination", ) -> pd.DataFrame: """Weights for ``weight_name``, each raw value divided by its group's total, with the groups whose total is zero handled by ``policy``. @@ -124,9 +110,8 @@ def apply_fallback( The output has one row per row of ``area_weights``, which holds the id fields, the source columns, ``areawt`` and ``area_raw``. ``raw_per_cell`` holds the id fields, the source key columns and - ``raw_col``, and a row it leaves out counts as raw 0. - ``policy_explicit`` says whether the config set the policy. Only an - unset policy logs the warning. Raises if a column is missing, if + ``raw_col``, and a row it leaves out counts as raw 0. Raises if a + column is missing, if ``raw_per_cell`` has a group that ``area_weights`` lacks, if a group's total area is zero, or if a group falls back under ``"error"``. """ @@ -213,27 +198,6 @@ def apply_fallback( else: # pragma: no cover raise ValueError(f"unhandled fallback policy: {policy}") - n_fallback_groups = len(fallback_group_ids) - n_total_groups = group_totals.shape[0] - if ( - n_fallback_groups > 0 - and not policy_explicit - and n_fallback_groups - >= max(_IMPLICIT_DEFAULT_MIN, int(_IMPLICIT_DEFAULT_FRAC * n_total_groups)) - ): - logger.warning( - "weights.%s: fallback policy %r fired for %d of %d groups " - "(%.1f%%); this is the library default. Alternatives: " - "[area | zero | error | nan]. Set weights.%s.fallback " - "explicitly in the config to silence this warning.", - weight_name, - policy, - n_fallback_groups, - n_total_groups, - 100.0 * n_fallback_groups / max(1, n_total_groups), - weight_name, - ) - out = pd.concat([native, fb], ignore_index=True) out = out.rename( columns={ diff --git a/cil_regionalization/manifest.py b/cil_regionalization/manifest.py index 0af91f0..580d99d 100644 --- a/cil_regionalization/manifest.py +++ b/cil_regionalization/manifest.py @@ -47,6 +47,11 @@ class Manifest: grid_resolution: float | None package_versions: dict[str, str] python_version: str + # Which side of the intersection the weights sum to 1 within + # (per_destination or per_source). Consumers check this against the + # operation they intend via `schema.require_normalization`. A manifest + # that does not record it is refused rather than read as either. + normalization: str # "grid" or "polygons": which geometry supplied the source units. source_mode: str = "grid" # The config's project name and description, carried verbatim so a @@ -75,12 +80,6 @@ class Manifest: # partially covered unit's weights sum to 1 over a sliver, and # sum-to-one gives no warning. partial_coverage: dict[str, Any] | None = None - # Which side of the intersection the weights sum to 1 within - # (per_destination or per_source). Consumers check this against the - # operation they intend via `schema.require_normalization`; manifests - # written before the field existed default to per_destination, which - # is the behavior every earlier run had. - normalization: str = "per_destination" inputs: dict[str, str] = field(default_factory=dict) # SHA256 of each written output file, keyed by filename, recorded by # the writer after the file lands. The fetch layer verifies a diff --git a/cil_regionalization/schema.py b/cil_regionalization/schema.py index eb8b26d..5f640d9 100644 --- a/cil_regionalization/schema.py +++ b/cil_regionalization/schema.py @@ -106,12 +106,12 @@ def weight_dtypes(name: str) -> dict[str, str]: class OutputSchema: """Resolved column layout for one run, the id fields, then the source units, then three columns for each weight. By default the source - units are grid cells and the normalization is per_destination.""" + units are grid cells. The normalization has no default.""" id_fields: tuple[str, ...] weight_names: tuple[str, ...] + normalization: Normalization source_units: SourceUnits = GRID_CELLS - normalization: Normalization = "per_destination" @property def columns(self) -> tuple[str, ...]: diff --git a/cil_regionalization/weights.py b/cil_regionalization/weights.py index 3970d6f..ed9ea90 100644 --- a/cil_regionalization/weights.py +++ b/cil_regionalization/weights.py @@ -15,18 +15,17 @@ @dataclass(frozen=True) class WeightSpec: name: str - fallback: FallbackPolicy + # None for the area weight alone, which has no fallback. + fallback: FallbackPolicy | None raster: str | None table: str | None - # True if the user wrote `fallback = "..."` in the TOML; False if the - # value came from the WeightConfig default. Drives the implicit- - # default warning in `apply_fallback`; a fallback firing for many - # regions on a defaulted policy probably surprises the user. - fallback_explicit: bool = False - # How the raster is integrated. "point_sum" (default) sums raw pixel - # values; "area_weighted_sum" sums (pixel value * geodesic pixel - # area in m^2) and is the crop weight's canonical integration. - kind: WeightKind = "point_sum" + # How the raster is integrated. "point_sum" sums raw pixel values; + # "area_weighted_sum" sums (pixel value * geodesic pixel area in m^2) + # and is the crop weight's canonical integration. None for the area + # weight alone, which reads no raster. + kind: WeightKind | None + # The column of the BigQuery table that holds the weight's values. + column: str | None = None @classmethod def from_config(cls, cfg: WeightConfig) -> "WeightSpec": @@ -35,8 +34,8 @@ def from_config(cls, cfg: WeightConfig) -> "WeightSpec": fallback=cfg.fallback, raster=cfg.raster, table=cfg.table, - fallback_explicit="fallback" in cfg.model_fields_set, kind=cfg.kind, + column=cfg.column, ) @property diff --git a/docs/reference.md b/docs/reference.md index 0b3de09..35db2e4 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -124,8 +124,8 @@ WeightsArtifact.from_table( id_fields: Sequence[str], weights: Mapping[str, str], source: str, + normalization: str, source_keys: Sequence[str] | None = None, - normalization: str = 'per_destination', regions_version: str | None = None, check: bool = True, tolerance: float = 1e-06, @@ -283,13 +283,13 @@ cell is masked in some slices and not others. class OutputSchema: id_fields: tuple[str, ...] weight_names: tuple[str, ...] + normalization: Normalization source_units: SourceUnits = GRID_CELLS - normalization: Normalization = 'per_destination' ``` Resolved column layout for one run, the id fields, then the source units, then three columns for each weight. By default the source -units are grid cells and the normalization is per_destination. +units are grid cells. The normalization has no default. #### `OutputSchema.columns` @@ -1126,7 +1126,7 @@ written. | key | type | default | | --- | --- | --- | -| `normalization` | "per_destination" or "per_source" | "per_destination" | +| `normalization` | "per_destination" or "per_source" | required | ### `[project]` @@ -1149,7 +1149,7 @@ Required. | `version` | str | not set | | `keep` | dict[str, list[any]] | not set | | `drop` | dict[str, list[any]] | not set | -| `on_invalid_geometry` | "repair" or "skip" or "error" | "repair" | +| `on_invalid_geometry` | "repair" or "skip" or "error" | required | | `on_null_geometry` | "error" or "skip" | "error" | | `on_unknown_id` | "error" or "skip" | "error" | @@ -1161,8 +1161,8 @@ Can be left out. | --- | --- | --- | | `mode` | "generate" or "prebuilt" | required | | `resolution` | float | not set | -| `offset` | "center" or "edge" | "center" | -| `lon_convention` | "[-180,180)" or "[0,360)" | "[-180,180)" | +| `offset` | "center" or "edge" | required | +| `lon_convention` | "[-180,180)" or "[0,360)" | required | | `path` | str | not set | | `table` | str | not set | @@ -1191,7 +1191,7 @@ regional subset of targets should expect such units and set "skip". | `path` | str, not empty | required | | `id_fields` | list[str], not empty | required | | `version` | str, not empty | required | -| `on_invalid_geometry` | "repair" or "skip" or "error" | "repair" | +| `on_invalid_geometry` | "repair" or "skip" or "error" | required | | `on_zero_overlap` | "error" or "skip" | "error" | | `coverage_threshold` | float, above 0, at most 1 | 0.999 | @@ -1199,13 +1199,20 @@ regional subset of targets should expect such units and set "skip". A list of tables, each with these keys. +One weight of the run. Every weight but ``area`` needs its +``fallback`` and its ``kind``, which have no default, and the area +weight takes neither, since its total is the region's own area and it +reads no raster. A BigQuery weight names the ``column`` of its +``table`` that holds its values. + | key | type | default | | --- | --- | --- | | `name` | str, not empty | required | | `raster` | str | not set | | `table` | str | not set | -| `fallback` | "area" or "zero" or "error" or "nan" | "area" | -| `kind` | "point_sum" or "area_weighted_sum" | "point_sum" | +| `column` | str, not empty | not set | +| `fallback` | "area" or "zero" or "error" or "nan" | not set | +| `kind` | "point_sum" or "area_weighted_sum" | not set | ### `[backend]` @@ -1214,7 +1221,7 @@ Required. | key | type | default | | --- | --- | --- | | `kind` | "local" or "bigquery" | required | -| `coverage` | "exact_fraction" or "pixel_centroid" | "exact_fraction" | +| `coverage` | "exact_fraction" or "pixel_centroid" | required | ### `[backend.local]` diff --git a/examples/climate/README.md b/examples/climate/README.md index a46416b..440ead1 100644 --- a/examples/climate/README.md +++ b/examples/climate/README.md @@ -74,7 +74,11 @@ table = table.groupby(["hierid", "pix_cent_x", "pix_cent_y"], as_index=False)[ ["popwt"] ].sum(min_count=1) weights = cilreg.WeightsArtifact.from_table( - table, id_fields=["hierid"], weights={"pop": "popwt"}, source=BCSD_GRID + table, + id_fields=["hierid"], + weights={"pop": "popwt"}, + source=BCSD_GRID, + normalization="per_destination", ) out = cilreg.apply_weights( diff --git a/examples/climate/degree_days_from_daily_grid.ipynb b/examples/climate/degree_days_from_daily_grid.ipynb index 2fed22f..eeb7b57 100644 --- a/examples/climate/degree_days_from_daily_grid.ipynb +++ b/examples/climate/degree_days_from_daily_grid.ipynb @@ -681,6 +681,7 @@ " id_fields=[\"ISO\", \"ID_1\"],\n", " weights={\"pop\": \"popwt\", \"area\": \"areawt\"},\n", " source=BCSD_GRID,\n", + " normalization=\"per_destination\",\n", ")\n", "for weight, a in ((\"pop\", by_pop), (\"area\", by_area)):\n", " # from_table reads ids from a CSV as strings; compare them as numbers\n", @@ -763,6 +764,7 @@ " id_fields=[\"hierid\"],\n", " weights={\"pop\": \"popwt\", \"area\": \"areawt\"},\n", " source=BCSD_GRID,\n", + " normalization=\"per_destination\",\n", ")\n", "by_ir = aggregate(ir_weights, \"pop\")\n", "blank = sorted(set(impact_regions[\"hierid\"]) - set(by_ir[\"hierid\"]))\n", diff --git a/examples/climate/grid025_to_ir_phl_deu.toml b/examples/climate/grid025_to_ir_phl_deu.toml index a95ccc5..f292fa4 100644 --- a/examples/climate/grid025_to_ir_phl_deu.toml +++ b/examples/climate/grid025_to_ir_phl_deu.toml @@ -44,6 +44,7 @@ name = "pop" # location; replace it with the path to your copy. raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/climate/prepare_data.py b/examples/climate/prepare_data.py index 53dda84..5d6d32e 100644 --- a/examples/climate/prepare_data.py +++ b/examples/climate/prepare_data.py @@ -149,7 +149,11 @@ def export_csv(rows: pd.DataFrame) -> None: def _ir_weights(table): return cilreg.WeightsArtifact.from_table( - table, id_fields=["hierid"], weights=WEIGHT_COLUMNS, source=BCSD_GRID + table, + id_fields=["hierid"], + weights=WEIGHT_COLUMNS, + source=BCSD_GRID, + normalization="per_destination", ) diff --git a/examples/climate/quickstart.ipynb b/examples/climate/quickstart.ipynb index f1257db..f0f48df 100644 --- a/examples/climate/quickstart.ipynb +++ b/examples/climate/quickstart.ipynb @@ -175,6 +175,7 @@ " id_fields=[\"hierid\"],\n", " weights={\"pop\": \"popwt\", \"area\": \"areawt\"},\n", " source=BCSD_GRID,\n", + " normalization=\"per_destination\",\n", ")\n", "print(f\"{len(weights.frame)} rows, {weights.frame['hierid'].nunique()} impact regions\")" ] diff --git a/examples/france/france.py b/examples/france/france.py index 8184678..38c5afb 100644 --- a/examples/france/france.py +++ b/examples/france/france.py @@ -271,20 +271,24 @@ def weights_config(level, normalization): path = "{relative(DATA / file, _configs)}" id_fields = ["{key}"] version = "{TARGETS_VERSION}" + on_invalid_geometry = "repair" [source] path = "{relative(DATA / "impact_regions.parquet", _configs)}" id_fields = ["hierid"] version = "{SOURCE_VERSION}" + on_invalid_geometry = "repair" on_zero_overlap = "skip" [[weights]] name = "pop" raster = "{relative(DATA / "population_2015_30ss.tif", _configs)}" fallback = "area" + kind = "point_sum" [backend] kind = "local" + coverage = "exact_fraction" [output] dir = "{relative(OUT / "weights" / name, _configs)}" diff --git a/examples/france/synthetic_data.py b/examples/france/synthetic_data.py index cceb4f2..dce1ba2 100644 --- a/examples/france/synthetic_data.py +++ b/examples/france/synthetic_data.py @@ -215,19 +215,23 @@ def _write_published(data: Path, work: Path) -> None: path = "{work / "gadm.parquet"}" id_fields = ["ISO", "ID_1", "ID_2"] version = "gadm-2.0-impactmap-copy-2025" +on_invalid_geometry = "repair" [source] path = "{data / "impact_regions.parquet"}" id_fields = ["hierid"] version = "world-combo-201710" +on_invalid_geometry = "repair" [[weights]] name = "pop" raster = "{data / "population_2015_30ss.tif"}" fallback = "area" +kind = "point_sum" [backend] kind = "local" +coverage = "exact_fraction" [output] dir = "{data / "published" / "gadm20-adm2-per-source"}" diff --git a/examples/gadm20/ir_to_adm1_full.toml b/examples/gadm20/ir_to_adm1_full.toml index 111e471..b723b0f 100644 --- a/examples/gadm20/ir_to_adm1_full.toml +++ b/examples/gadm20/ir_to_adm1_full.toml @@ -22,6 +22,7 @@ description = "IR to GADM 2.0 ADM1 allocation weights, full global run" path = "../../data/targets/gadm20/adm1.parquet" id_fields = ["ISO", "ID_1"] version = "gadm-2.0-impactmap-copy-2025" +on_invalid_geometry = "repair" [source] @@ -41,6 +42,7 @@ name = "pop" # it with the path to your copy. raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/gadm20/ir_to_adm1_full_per_destination.toml b/examples/gadm20/ir_to_adm1_full_per_destination.toml index 10c7ec5..960bc93 100644 --- a/examples/gadm20/ir_to_adm1_full_per_destination.toml +++ b/examples/gadm20/ir_to_adm1_full_per_destination.toml @@ -22,6 +22,7 @@ description = "IR to GADM 2.0 ADM1 allocation weights, full global run" path = "../../data/targets/gadm20/adm1.parquet" id_fields = ["ISO", "ID_1"] version = "gadm-2.0-impactmap-copy-2025" +on_invalid_geometry = "repair" [source] @@ -41,6 +42,7 @@ name = "pop" # it with the path to your copy. raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/gadm20/ir_to_adm1_subset.toml b/examples/gadm20/ir_to_adm1_subset.toml index 6d73f20..531b971 100644 --- a/examples/gadm20/ir_to_adm1_subset.toml +++ b/examples/gadm20/ir_to_adm1_subset.toml @@ -38,6 +38,7 @@ description = "IR to GADM 2.0 ADM1 allocation weights, five-country subset" path = "../../data/targets/gadm20/adm1.parquet" id_fields = ["ISO", "ID_1"] version = "gadm-2.0-impactmap-copy-2025" +on_invalid_geometry = "repair" [regions.keep] ISO = ["THA", "BRA", "MDV", "FJI", "NPL"] @@ -59,6 +60,7 @@ name = "pop" # it with the path to your copy. raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/gadm20/ir_to_adm2_full.toml b/examples/gadm20/ir_to_adm2_full.toml index 90c6361..4f89c2c 100644 --- a/examples/gadm20/ir_to_adm2_full.toml +++ b/examples/gadm20/ir_to_adm2_full.toml @@ -18,6 +18,7 @@ description = "IR to GADM 2.0 ADM2 allocation weights, full global run" path = "../../data/targets/gadm20/adm2.parquet" id_fields = ["ISO", "ID_1", "ID_2"] version = "gadm-2.0-impactmap-copy-2025" +on_invalid_geometry = "repair" [source] @@ -37,6 +38,7 @@ name = "pop" # it with the path to your copy. raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/gadm20/ir_to_adm2_full_per_destination.toml b/examples/gadm20/ir_to_adm2_full_per_destination.toml index 241c2ba..a1b79df 100644 --- a/examples/gadm20/ir_to_adm2_full_per_destination.toml +++ b/examples/gadm20/ir_to_adm2_full_per_destination.toml @@ -18,6 +18,7 @@ description = "IR to GADM 2.0 ADM2 allocation weights, full global run" path = "../../data/targets/gadm20/adm2.parquet" id_fields = ["ISO", "ID_1", "ID_2"] version = "gadm-2.0-impactmap-copy-2025" +on_invalid_geometry = "repair" [source] @@ -37,6 +38,7 @@ name = "pop" # it with the path to your copy. raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/gadm41/ir_to_adm1_per_destination.toml b/examples/gadm41/ir_to_adm1_per_destination.toml index c04529e..841e7fb 100644 --- a/examples/gadm41/ir_to_adm1_per_destination.toml +++ b/examples/gadm41/ir_to_adm1_per_destination.toml @@ -18,6 +18,7 @@ description = "IR to GADM 4.1 adm1 weights, per_destination; not interchangeable path = "../../data/targets/gadm41/adm1.parquet" id_fields = ["GID_0", "GID_1"] version = "gadm-4.10-impactmap-copy-2022" +on_invalid_geometry = "repair" [source] # The impact region shapefile, published at 10.5281/zenodo.21934131. @@ -36,6 +37,7 @@ name = "pop" # it with the path to your copy. raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/gadm41/ir_to_adm1_per_source.toml b/examples/gadm41/ir_to_adm1_per_source.toml index 9fc5bcc..b336292 100644 --- a/examples/gadm41/ir_to_adm1_per_source.toml +++ b/examples/gadm41/ir_to_adm1_per_source.toml @@ -18,6 +18,7 @@ description = "IR to GADM 4.1 adm1 weights, per_source; not interchangeable with path = "../../data/targets/gadm41/adm1.parquet" id_fields = ["GID_0", "GID_1"] version = "gadm-4.10-impactmap-copy-2022" +on_invalid_geometry = "repair" [source] # The impact region shapefile, published at 10.5281/zenodo.21934131. @@ -36,6 +37,7 @@ name = "pop" # it with the path to your copy. raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/gadm41/ir_to_adm2_per_destination.toml b/examples/gadm41/ir_to_adm2_per_destination.toml index da0ed2d..f10aef3 100644 --- a/examples/gadm41/ir_to_adm2_per_destination.toml +++ b/examples/gadm41/ir_to_adm2_per_destination.toml @@ -18,6 +18,7 @@ description = "IR to GADM 4.1 adm2 weights, per_destination; not interchangeable path = "../../data/targets/gadm41/adm2.parquet" id_fields = ["GID_0", "GID_1", "GID_2"] version = "gadm-4.10-impactmap-copy-2022" +on_invalid_geometry = "repair" [source] # The impact region shapefile, published at 10.5281/zenodo.21934131. @@ -36,6 +37,7 @@ name = "pop" # it with the path to your copy. raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/gadm41/ir_to_adm2_per_source.toml b/examples/gadm41/ir_to_adm2_per_source.toml index 046778e..cd81b42 100644 --- a/examples/gadm41/ir_to_adm2_per_source.toml +++ b/examples/gadm41/ir_to_adm2_per_source.toml @@ -18,6 +18,7 @@ description = "IR to GADM 4.1 adm2 weights, per_source; not interchangeable with path = "../../data/targets/gadm41/adm2.parquet" id_fields = ["GID_0", "GID_1", "GID_2"] version = "gadm-4.10-impactmap-copy-2022" +on_invalid_geometry = "repair" [source] # The impact region shapefile, published at 10.5281/zenodo.21934131. @@ -36,6 +37,7 @@ name = "pop" # it with the path to your copy. raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/s51/grid1deg_to_ir.toml b/examples/s51/grid1deg_to_ir.toml index da9fd96..43e9109 100644 --- a/examples/s51/grid1deg_to_ir.toml +++ b/examples/s51/grid1deg_to_ir.toml @@ -26,6 +26,7 @@ name = "pop" # GPW v4 rev 10, 2015, 30 arc second, UN WPP adjusted raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/s51/s51_canonical.toml b/examples/s51/s51_canonical.toml index 46f0107..850a8e0 100644 --- a/examples/s51/s51_canonical.toml +++ b/examples/s51/s51_canonical.toml @@ -48,6 +48,7 @@ name = "pop" # GPW v4 rev 10, 2015, 30 arc second, UN WPP adjusted raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/examples/s51/s51_supplement.toml b/examples/s51/s51_supplement.toml index 7accc99..1706ee2 100644 --- a/examples/s51/s51_supplement.toml +++ b/examples/s51/s51_supplement.toml @@ -48,6 +48,7 @@ name = "pop" # GPW v4 rev 10, 2015, 30 arc second, UN WPP adjusted raster = "/project/cil/gcp/social/population/gpw_v4r10_unwpp_2015/raster_geotiff/gpw_v4r10_unwpp_2015_30ss.tif" fallback = "area" +kind = "point_sum" [[weights]] name = "area" diff --git a/tests/integration/test_apply.py b/tests/integration/test_apply.py index 96f3a61..7f8ed76 100644 --- a/tests/integration/test_apply.py +++ b/tests/integration/test_apply.py @@ -657,14 +657,16 @@ def test_written_artifact_applies(self, tmp_path): "path": str(tp), "id_fields": ["target_id"], "version": "targets-v1", + "on_invalid_geometry": "repair", }, "source": { "path": str(sp), "id_fields": ["unit_id"], "version": SOURCE_VERSION, + "on_invalid_geometry": "repair", }, "weights": [{"name": "area"}], - "backend": {"kind": "local"}, + "backend": {"kind": "local", "coverage": "exact_fraction"}, "output": {"dir": str(tmp_path / "out")}, "normalization": "per_source", } diff --git a/tests/integration/test_bigquery_backend.py b/tests/integration/test_bigquery_backend.py index b9196db..dd96958 100644 --- a/tests/integration/test_bigquery_backend.py +++ b/tests/integration/test_bigquery_backend.py @@ -64,6 +64,7 @@ def _bq_cfg(**overrides) -> Config: "table": _IR_TABLE, "id_fields": ["hierid"], "keep": {"hierid": ["ABW", "BHS"]}, + "on_invalid_geometry": "repair", }, "grid": { "mode": "generate", @@ -72,7 +73,13 @@ def _bq_cfg(**overrides) -> Config: "lon_convention": "[-180,180)", }, "weights": [ - {"name": "pop", "table": _POP_TABLE, "fallback": "area"}, + { + "name": "pop", + "table": _POP_TABLE, + "column": "population", + "fallback": "area", + "kind": "point_sum", + }, {"name": "area"}, ], "backend": { @@ -85,6 +92,7 @@ def _bq_cfg(**overrides) -> Config: }, }, "output": {"dir": "/tmp/cilreg_bq_test"}, + "normalization": "per_destination", } for key, val in overrides.items(): d[key] = val @@ -357,6 +365,25 @@ def test_weight_table_appears(self): sql, _ = self._build() assert _POP_TABLE in sql + def test_a_weight_is_read_from_the_column_it_declares(self): + """Not from a column its name maps to. It went red on the map that + read a weight named pop from the column population.""" + cfg = _bq_cfg( + weights=[ + { + "name": "pop", + "table": _POP_TABLE, + "column": "people_2015", + "fallback": "area", + "kind": "point_sum", + }, + {"name": "area"}, + ] + ) + sql, _ = self._build(cfg) + assert "people_2015" in sql + assert "population" not in sql.replace(_POP_TABLE, "") + def test_floor_cell_binning(self): sql, _ = self._build() assert "FLOOR((p.longitude - -180.0) / 1.0)" in sql @@ -1353,7 +1380,11 @@ def test_accepts_regions_path_shapefile_source(self, tmp_path): ).to_parquet(p) d = _bq_cfg().model_dump() - d["regions"] = {"path": str(p), "id_fields": ["hierid"]} + d["regions"] = { + "path": str(p), + "id_fields": ["hierid"], + "on_invalid_geometry": "repair", + } cfg = Config.model_validate(d) regions = RegionSet.from_config(cfg.regions) assert regions.gdf is not None @@ -1674,7 +1705,13 @@ def test_can5_spherical_invalid_supplement_end_to_end(self, bq_client, tmp_path) "lon_convention": "[-180,180)", }, "weights": [ - {"name": "pop", "table": _POP_TABLE, "fallback": "area"}, + { + "name": "pop", + "table": _POP_TABLE, + "column": "population", + "fallback": "area", + "kind": "point_sum", + }, {"name": "area"}, ], "backend": { @@ -1682,6 +1719,7 @@ def test_can5_spherical_invalid_supplement_end_to_end(self, bq_client, tmp_path) "coverage": "pixel_centroid", }, "output": {"dir": str(tmp_path), "confirm_cost": False}, + "normalization": "per_destination", } ) regions = RegionSet.from_config(cfg.regions) diff --git a/tests/integration/test_cross_backend.py b/tests/integration/test_cross_backend.py index 1448509..910cedc 100644 --- a/tests/integration/test_cross_backend.py +++ b/tests/integration/test_cross_backend.py @@ -51,7 +51,11 @@ def _local_cfg( return Config.model_validate( { "project": {"name": "stage4_mode"}, - "regions": {"path": str(regions_path), "id_fields": ["region_id"]}, + "regions": { + "path": str(regions_path), + "id_fields": ["region_id"], + "on_invalid_geometry": "repair", + }, "grid": { "mode": "generate", "resolution": 1.0, @@ -59,11 +63,17 @@ def _local_cfg( "lon_convention": "[-180,180)", }, "weights": [ - {"name": "pop", "raster": str(raster_path), "fallback": "area"}, + { + "name": "pop", + "raster": str(raster_path), + "fallback": "area", + "kind": "point_sum", + }, {"name": "area"}, ], "backend": {"kind": "local", "coverage": coverage}, "output": {"dir": str(out_dir)}, + "normalization": "per_destination", } ) @@ -214,7 +224,11 @@ def _area_only_local_cfg(regions_path: Path, out_dir: Path) -> Config: return Config.model_validate( { "project": {"name": "stage4_cross_local"}, - "regions": {"path": str(regions_path), "id_fields": ["hierid"]}, + "regions": { + "path": str(regions_path), + "id_fields": ["hierid"], + "on_invalid_geometry": "repair", + }, "grid": { "mode": "generate", "resolution": 1.0, @@ -224,6 +238,7 @@ def _area_only_local_cfg(regions_path: Path, out_dir: Path) -> Config: "weights": [{"name": "area"}], "backend": {"kind": "local", "coverage": "pixel_centroid"}, "output": {"dir": str(out_dir)}, + "normalization": "per_destination", } ) @@ -236,6 +251,7 @@ def _area_only_bq_cfg(out_dir: Path) -> Config: "table": _IR_TABLE, "id_fields": ["hierid"], "keep": {"hierid": _CROSS_HIERIDS}, + "on_invalid_geometry": "repair", }, "grid": { "mode": "generate", @@ -246,6 +262,7 @@ def _area_only_bq_cfg(out_dir: Path) -> Config: "weights": [{"name": "area"}], "backend": {"kind": "bigquery", "coverage": "pixel_centroid"}, "output": {"dir": str(out_dir)}, + "normalization": "per_destination", } ) diff --git a/tests/integration/test_from_table.py b/tests/integration/test_from_table.py index 7be103a..6e71cae 100644 --- a/tests/integration/test_from_table.py +++ b/tests/integration/test_from_table.py @@ -32,7 +32,12 @@ def _from_fixture(**kwargs) -> WeightsArtifact: - opts = dict(id_fields=["hierid"], weights={"pop": "popwt"}, source=GRID) + opts = dict( + id_fields=["hierid"], + weights={"pop": "popwt"}, + source=GRID, + normalization="per_destination", + ) opts.update(kwargs) return WeightsArtifact.from_table(FIXTURE, **opts) @@ -70,7 +75,14 @@ def test_cells_derived_from_pix_cent_with_wrap(self): def test_derived_cells_match_grid_math(self): f = _from_fixture().frame - spec = GridSpec.from_config(GridConfig(mode="generate", resolution=0.25)) + spec = GridSpec.from_config( + GridConfig( + mode="generate", + resolution=0.25, + offset="center", + lon_convention="[-180,180)", + ) + ) lon = np.where( f["pix_cent_x"] >= 180.0, f["pix_cent_x"] - 360.0, f["pix_cent_x"] ) @@ -91,7 +103,11 @@ def test_other_centroid_spellings(self, lon_name, lat_name): columns={"pix_cent_x": lon_name, "pix_cent_y": lat_name} ) art = WeightsArtifact.from_table( - df, id_fields=["hierid"], weights={"pop": "popwt"}, source=GRID + df, + id_fields=["hierid"], + weights={"pop": "popwt"}, + source=GRID, + normalization="per_destination", ) ref = _from_fixture().frame assert art.frame["cell_ix"].tolist() == ref["cell_ix"].tolist() @@ -106,6 +122,7 @@ def test_weight_columns_renamed_to_schema_form(self): id_fields=["hierid"], weights={"pop": "pop_share", "area": "area_share"}, source=GRID, + normalization="per_destination", ) assert art.schema.weight_names == ("pop", "area") assert {"popwt", "areawt"} <= set(art.frame.columns) @@ -115,14 +132,22 @@ def test_rename_refuses_to_overwrite(self): df = pd.read_csv(FIXTURE).assign(pop_share=lambda d: d["popwt"]) with pytest.raises(ValueError, match="would overwrite"): WeightsArtifact.from_table( - df, id_fields=["hierid"], weights={"pop": "pop_share"}, source=GRID + df, + id_fields=["hierid"], + weights={"pop": "pop_share"}, + source=GRID, + normalization="per_destination", ) def test_parquet_reads_the_same(self, tmp_path): p = tmp_path / "w.parquet" pd.read_csv(FIXTURE).to_parquet(p, index=False) a = WeightsArtifact.from_table( - p, id_fields=["hierid"], weights={"pop": "popwt"}, source=GRID + p, + id_fields=["hierid"], + weights={"pop": "popwt"}, + source=GRID, + normalization="per_destination", ) b = _from_fixture() cols = ["hierid", "cell_ix", "cell_iy", "popwt"] @@ -141,7 +166,11 @@ def test_ids_read_as_strings(self, tmp_path): } ).to_csv(p, index=False) art = WeightsArtifact.from_table( - p, id_fields=["code"], weights={"pop": "w"}, source=GRID + p, + id_fields=["code"], + weights={"pop": "w"}, + source=GRID, + normalization="per_destination", ) assert art.frame["code"].tolist() == ["001", "002"] @@ -150,7 +179,11 @@ def test_unknown_extension_rejected(self, tmp_path): p.write_text("x") with pytest.raises(ValueError, match="cannot tell the format"): WeightsArtifact.from_table( - p, id_fields=["hierid"], weights={"pop": "popwt"}, source=GRID + p, + id_fields=["hierid"], + weights={"pop": "popwt"}, + source=GRID, + normalization="per_destination", ) def test_indices_alone_are_taken_on_trust(self): @@ -166,7 +199,11 @@ def test_indices_alone_are_taken_on_trust(self): } ) art = WeightsArtifact.from_table( - df, id_fields=["r"], weights={"pop": "w"}, source=GRID + df, + id_fields=["r"], + weights={"pop": "w"}, + source=GRID, + normalization="per_destination", ) assert art.frame["cell_ix"].tolist() == [720, 1439] assert "cell_lon" not in art.frame.columns @@ -192,7 +229,11 @@ def test_zero_360_indices_with_centroids_rejected(self): assert df["cell_ix"].tolist() == [0, 720, 1439] with pytest.raises(ValueError, match="likely built on a different grid") as e: WeightsArtifact.from_table( - df, id_fields=["r"], weights={"pop": "w"}, source=GRID + df, + id_fields=["r"], + weights={"pop": "w"}, + source=GRID, + normalization="per_destination", ) assert "3 rows" in str(e.value) @@ -202,6 +243,7 @@ def test_zero_360_indices_accepted_on_their_own_grid(self): id_fields=["r"], weights={"pop": "w"}, source="grid-0.25deg-center-[0,360)", + normalization="per_destination", ) assert art.frame["cell_ix"].tolist() == [0, 720, 1439] @@ -210,7 +252,11 @@ def test_indices_matching_wrapped_centroids_accepted(self): # wrapping makes them agree, so the table passes df = self._zero_360_table().assign(cell_ix=[720, 0, 1439 - 720]) art = WeightsArtifact.from_table( - df, id_fields=["r"], weights={"pop": "w"}, source=GRID + df, + id_fields=["r"], + weights={"pop": "w"}, + source=GRID, + normalization="per_destination", ) assert art.frame["cell_ix"].tolist() == [720, 0, 719] @@ -228,25 +274,41 @@ def test_latitude_descending_indices_rejected(self): ) with pytest.raises(ValueError, match=r"\['lat'\]"): WeightsArtifact.from_table( - df, id_fields=["r"], weights={"pop": "w"}, source=GRID + df, + id_fields=["r"], + weights={"pop": "w"}, + source=GRID, + normalization="per_destination", ) ok = df.assign(cell_iy=[719, 0]) WeightsArtifact.from_table( - ok, id_fields=["r"], weights={"pop": "w"}, source=GRID + ok, + id_fields=["r"], + weights={"pop": "w"}, + source=GRID, + normalization="per_destination", ) def test_explicit_cell_indices_outside_grid_rejected(self): df = pd.DataFrame({"r": ["A"], "cell_ix": [1440], "cell_iy": [5], "w": [1.0]}) with pytest.raises(ValueError, match="outside the 1440 x 720 grid"): WeightsArtifact.from_table( - df, id_fields=["r"], weights={"pop": "w"}, source=GRID + df, + id_fields=["r"], + weights={"pop": "w"}, + source=GRID, + normalization="per_destination", ) def test_points_off_centroids_rejected(self): df = pd.DataFrame({"r": ["A"], "lon": [0.2], "lat": [0.125], "w": [1.0]}) with pytest.raises(ValueError, match="not cell centroids"): WeightsArtifact.from_table( - df, id_fields=["r"], weights={"pop": "w"}, source=GRID + df, + id_fields=["r"], + weights={"pop": "w"}, + source=GRID, + normalization="per_destination", ) def test_ambiguous_or_missing_centroid_columns(self): @@ -261,7 +323,11 @@ def test_ambiguous_or_missing_centroid_columns(self): ) with pytest.raises(ValueError, match="several longitude columns"): WeightsArtifact.from_table( - df, id_fields=["r"], weights={"pop": "w"}, source=GRID + df, + id_fields=["r"], + weights={"pop": "w"}, + source=GRID, + normalization="per_destination", ) with pytest.raises(ValueError, match="no longitude column"): WeightsArtifact.from_table( @@ -269,6 +335,7 @@ def test_ambiguous_or_missing_centroid_columns(self): id_fields=["r"], weights={"pop": "w"}, source=GRID, + normalization="per_destination", ) def test_zero_360_grid_wraps_negative_longitudes(self): @@ -285,6 +352,7 @@ def test_zero_360_grid_wraps_negative_longitudes(self): id_fields=["r"], weights={"pop": "w"}, source="grid-0.25deg-center-[0,360)", + normalization="per_destination", ) assert art.frame["cell_lon"].tolist() == [180.125, 0.125] assert art.frame["cell_ix"].tolist() == [720, 0] @@ -306,7 +374,11 @@ def test_sum_to_one_failure_names_group(self): df.loc[df["hierid"] == "AAA", "popwt"] = [0.6, 0.6] with pytest.raises(ValueError, match="do not sum to 1") as e: WeightsArtifact.from_table( - df, id_fields=["hierid"], weights={"pop": "popwt"}, source=GRID + df, + id_fields=["hierid"], + weights={"pop": "popwt"}, + source=GRID, + normalization="per_destination", ) assert "AAA" in str(e.value) assert "BBB" not in str(e.value) @@ -317,7 +389,11 @@ def test_duplicates_rejected_naming_key(self): df.loc[df["hierid"] == "BBB", "popwt"] = 0.5 with pytest.raises(ValueError, match="share a \\(region, source") as e: WeightsArtifact.from_table( - df, id_fields=["hierid"], weights={"pop": "popwt"}, source=GRID + df, + id_fields=["hierid"], + weights={"pop": "popwt"}, + source=GRID, + normalization="per_destination", ) assert "BBB" in str(e.value) @@ -325,7 +401,12 @@ def test_check_false_skips_both(self): df = pd.read_csv(FIXTURE) df = pd.concat([df, df.iloc[[2]]], ignore_index=True) art = WeightsArtifact.from_table( - df, id_fields=["hierid"], weights={"pop": "popwt"}, source=GRID, check=False + df, + id_fields=["hierid"], + weights={"pop": "popwt"}, + source=GRID, + check=False, + normalization="per_destination", ) assert len(art.frame) == 6 @@ -437,7 +518,11 @@ def test_polygon_source_application(self): class TestPackageRoot: def test_one_import_suffices(self): art = cilreg.WeightsArtifact.from_table( - FIXTURE, id_fields=["hierid"], weights={"pop": "popwt"}, source=GRID + FIXTURE, + id_fields=["hierid"], + weights={"pop": "popwt"}, + source=GRID, + normalization="per_destination", ) assert isinstance(art, cilreg.WeightsArtifact) diff --git a/tests/integration/test_local_backend.py b/tests/integration/test_local_backend.py index 5da8488..4de2cf3 100644 --- a/tests/integration/test_local_backend.py +++ b/tests/integration/test_local_backend.py @@ -44,7 +44,11 @@ def _cfg( return Config.model_validate( { "project": {"name": "test"}, - "regions": {"path": str(regions_path), "id_fields": ["region_id"]}, + "regions": { + "path": str(regions_path), + "id_fields": ["region_id"], + "on_invalid_geometry": "repair", + }, "grid": { "mode": "generate", "resolution": 1.0, @@ -56,11 +60,13 @@ def _cfg( "name": "pop", "raster": str(raster_path), "fallback": pop_fallback, + "kind": "point_sum", }, {"name": "area"}, ], "backend": {"kind": "local", "coverage": coverage}, "output": {"dir": str(output_dir)}, + "normalization": "per_destination", } ) @@ -85,7 +91,11 @@ def test_schema_matches_canonical( ): cfg = _cfg(three_region_geoparquet, synthetic_raster, tmp_path) result = _run(cfg) - expected = OutputSchema(id_fields=("region_id",), weight_names=("pop", "area")) + expected = OutputSchema( + id_fields=("region_id",), + weight_names=("pop", "area"), + normalization="per_destination", + ) assert list(result.frame.columns) == list(expected.columns) expected.validate_frame(result.frame) @@ -260,6 +270,7 @@ def _cfg_with_crop( "regions": { "path": str(regions_path), "id_fields": ["region_id"], + "on_invalid_geometry": "repair", }, "grid": { "mode": "generate", @@ -278,6 +289,7 @@ def _cfg_with_crop( ], "backend": {"kind": "local", "coverage": "exact_fraction"}, "output": {"dir": str(out_dir)}, + "normalization": "per_destination", } ) @@ -413,6 +425,7 @@ def _cfg(self, regions_path, raster_path, out_dir): "regions": { "path": str(regions_path), "id_fields": ["region_id"], + "on_invalid_geometry": "repair", }, "grid": { "mode": "generate", @@ -425,11 +438,13 @@ def _cfg(self, regions_path, raster_path, out_dir): "name": "pop", "raster": str(raster_path), "fallback": "area", + "kind": "point_sum", }, {"name": "area"}, ], "backend": {"kind": "local", "coverage": "exact_fraction"}, "output": {"dir": str(out_dir)}, + "normalization": "per_destination", } ) @@ -901,12 +916,15 @@ def test_legacy_csv_written_alongside_parquet( cfg_path = tmp_path / "cfg.toml" cfg_path.write_text( f""" +normalization = "per_destination" + [project] name = "legacy_csv_test" [regions] path = "{regions_path}" id_fields = ["hierid"] +on_invalid_geometry = "repair" [grid] mode = "generate" @@ -924,6 +942,7 @@ def test_legacy_csv_written_alongside_parquet( name = "pop" raster = "{synthetic_raster}" fallback = "area" +kind = "point_sum" [[weights]] name = "area" @@ -960,11 +979,13 @@ def test_legacy_csv_written_alongside_parquet( def _write_toml(path: Path, cfg: Config) -> None: """Render a Config back to a minimal TOML so the CLI can load it.""" lines: list[str] = [] + lines.append(f'normalization = "{cfg.normalization}"') lines.append("[project]") lines.append(f'name = "{cfg.project.name}"') lines.append("[regions]") lines.append(f'path = "{cfg.regions.path}"') lines.append(f"id_fields = {list(cfg.regions.id_fields)!r}") + lines.append(f'on_invalid_geometry = "{cfg.regions.on_invalid_geometry}"') lines.append("[grid]") lines.append(f'mode = "{cfg.grid.mode}"') lines.append(f"resolution = {cfg.grid.resolution}") @@ -975,8 +996,9 @@ def _write_toml(path: Path, cfg: Config) -> None: lines.append(f'name = "{w.name}"') if w.raster is not None: lines.append(f'raster = "{w.raster}"') - if w.fallback != "area": - lines.append(f'fallback = "{w.fallback}"') + for key in ("fallback", "kind"): + if getattr(w, key) is not None: + lines.append(f'{key} = "{getattr(w, key)}"') lines.append("[backend]") lines.append(f'kind = "{cfg.backend.kind}"') lines.append(f'coverage = "{cfg.backend.coverage}"') diff --git a/tests/integration/test_montecarlo_pipeline.py b/tests/integration/test_montecarlo_pipeline.py index 7c16f92..3ccbf26 100644 --- a/tests/integration/test_montecarlo_pipeline.py +++ b/tests/integration/test_montecarlo_pipeline.py @@ -71,14 +71,16 @@ def weights_dir(tmp_path: Path) -> Path: "path": str(tp), "id_fields": ["target_id"], "version": "targets-v1", + "on_invalid_geometry": "repair", }, "source": { "path": str(sp), "id_fields": ["unit_id"], "version": SOURCE_VERSION, + "on_invalid_geometry": "repair", }, "weights": [{"name": "area"}], - "backend": {"kind": "local"}, + "backend": {"kind": "local", "coverage": "exact_fraction"}, "output": {"dir": str(out)}, "normalization": "per_source", } diff --git a/tests/integration/test_netcdf_grid.py b/tests/integration/test_netcdf_grid.py index de7966e..1a3217c 100644 --- a/tests/integration/test_netcdf_grid.py +++ b/tests/integration/test_netcdf_grid.py @@ -146,7 +146,14 @@ def test_a_prebuilt_gridspec_is_refused(self, tmp_path): from cil_regionalization.config import GridConfig path = self._east(tmp_path) - spec = GridSpec.from_config(GridConfig(mode="prebuilt", path="x.parquet")) + spec = GridSpec.from_config( + GridConfig( + mode="prebuilt", + path="x.parquet", + offset="center", + lon_convention="[-180,180)", + ) + ) with pytest.raises(ValueError, match="generated grid"): cilreg.read_netcdf_grid(path, ["tas"], grid=spec) @@ -234,6 +241,7 @@ def _weights(self, grid): id_fields=["region"], weights={"pop": "popwt"}, source=grid, + normalization="per_destination", ) def test_weighted_mean_of_the_file(self, tmp_path): diff --git a/tests/integration/test_polygon_mode.py b/tests/integration/test_polygon_mode.py index 230fbde..16cb0eb 100644 --- a/tests/integration/test_polygon_mode.py +++ b/tests/integration/test_polygon_mode.py @@ -112,16 +112,23 @@ def _cfg( "path": str(targets_path), "id_fields": target_id_fields, "version": "synthetic-targets-v1", + "on_invalid_geometry": "repair", }, "source": { "path": str(source_path), "id_fields": ["unit_id"], "version": "synthetic-units-v1", "on_zero_overlap": on_zero_overlap, + "on_invalid_geometry": "repair", }, "weights": weights or [ - {"name": "pop", "raster": str(_POP_RASTER), "fallback": "area"}, + { + "name": "pop", + "raster": str(_POP_RASTER), + "fallback": "area", + "kind": "point_sum", + }, {"name": "area"}, ], "backend": {"kind": "local", "coverage": coverage}, @@ -268,7 +275,12 @@ def _weights(self, fraction_raster: Path) -> list[dict]: "kind": "area_weighted_sum", "fallback": "nan", }, - {"name": "pop", "raster": str(_POP_RASTER), "fallback": "area"}, + { + "name": "pop", + "raster": str(_POP_RASTER), + "fallback": "area", + "kind": "point_sum", + }, {"name": "area"}, ] @@ -423,20 +435,28 @@ def _base(self, targets_level1, source_units) -> dict: "path": str(targets_level1), "id_fields": ["target_id"], "version": "v1", + "on_invalid_geometry": "repair", }, "source": { "path": str(source_units), "id_fields": ["unit_id"], "version": "v1", + "on_invalid_geometry": "repair", }, "weights": [{"name": "area"}], - "backend": {"kind": "local"}, + "backend": {"kind": "local", "coverage": "exact_fraction"}, "output": {"dir": "unused"}, + "normalization": "per_destination", } def test_grid_and_source_mutually_exclusive(self, targets_level1, source_units): data = self._base(targets_level1, source_units) - data["grid"] = {"mode": "generate", "resolution": 1.0} + data["grid"] = { + "mode": "generate", + "resolution": 1.0, + "offset": "center", + "lon_convention": "[-180,180)", + } with pytest.raises(ValueError, match="mutually exclusive"): Config.model_validate(data) @@ -478,23 +498,27 @@ def test_run_end_to_end_from_toml( path = "{targets_level1}" id_fields = ["target_id"] version = "synthetic-targets-v1" +on_invalid_geometry = "repair" [source] path = "{source_units}" id_fields = ["unit_id"] version = "synthetic-units-v1" +on_invalid_geometry = "repair" on_zero_overlap = "skip" [[weights]] name = "pop" raster = "{_POP_RASTER}" fallback = "area" +kind = "point_sum" [[weights]] name = "area" [backend] kind = "local" +coverage = "exact_fraction" [output] dir = "{out_dir}" diff --git a/tests/integration/test_regions_find.py b/tests/integration/test_regions_find.py index 0883cff..55de6ad 100644 --- a/tests/integration/test_regions_find.py +++ b/tests/integration/test_regions_find.py @@ -55,11 +55,13 @@ def _write_local_cfg(tmp_path: Path) -> Path: cfg_path = tmp_path / "cfg.toml" cfg_path.write_text( f""" +normalization = "per_destination" [project] name = "find_test" [regions] path = "{regions_path}" id_fields = ["hierid"] +on_invalid_geometry = "repair" [grid] mode = "generate" resolution = 1.0 @@ -68,6 +70,8 @@ def _write_local_cfg(tmp_path: Path) -> Path: [[weights]] name = "pop" raster = "{raster_path}" +fallback = "area" +kind = "point_sum" [[weights]] name = "area" [backend] @@ -173,11 +177,13 @@ def test_issues_parameterized_like_query(self, tmp_path, monkeypatch, capsys): cfg_path = tmp_path / "cfg.toml" cfg_path.write_text( f""" +normalization = "per_destination" [project] name = "find_bq_test" [regions] table = "compute-impactlab.spatial_aggregation.test_table" id_fields = ["hierid"] +on_invalid_geometry = "repair" [grid] mode = "generate" resolution = 1.0 @@ -186,6 +192,9 @@ def test_issues_parameterized_like_query(self, tmp_path, monkeypatch, capsys): [[weights]] name = "pop" table = "x.y.pop" +column = "population" +fallback = "area" +kind = "point_sum" [[weights]] name = "area" [backend] diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 0909e18..c6e5324 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -18,14 +18,29 @@ def _local_cfg() -> dict: return { "project": {"name": "test"}, - "regions": {"path": "/tmp/regions.shp", "id_fields": ["hierid"]}, - "grid": {"mode": "generate", "resolution": 1.0}, + "regions": { + "path": "/tmp/regions.shp", + "id_fields": ["hierid"], + "on_invalid_geometry": "repair", + }, + "grid": { + "mode": "generate", + "resolution": 1.0, + "offset": "center", + "lon_convention": "[-180,180)", + }, "weights": [ - {"name": "pop", "raster": "/tmp/pop.tif"}, + { + "name": "pop", + "raster": "/tmp/pop.tif", + "fallback": "area", + "kind": "point_sum", + }, {"name": "area"}, ], - "backend": {"kind": "local"}, + "backend": {"kind": "local", "coverage": "exact_fraction"}, "output": {"dir": "/tmp/out"}, + "normalization": "per_destination", } @@ -35,10 +50,22 @@ def _bq_cfg() -> dict: "regions": { "table": "compute-impactlab.spatial_aggregation.regions", "id_fields": ["hierid"], + "on_invalid_geometry": "repair", + }, + "grid": { + "mode": "generate", + "resolution": 1.0, + "lon_convention": "[0,360)", + "offset": "center", }, - "grid": {"mode": "generate", "resolution": 1.0, "lon_convention": "[0,360)"}, "weights": [ - {"name": "pop", "table": "compute-impactlab.gpw.pop"}, + { + "name": "pop", + "table": "compute-impactlab.gpw.pop", + "column": "population", + "fallback": "area", + "kind": "point_sum", + }, {"name": "area"}, ], "backend": { @@ -48,22 +75,92 @@ def _bq_cfg() -> dict: "temp_dataset": "temp_workspace", "staging_uri": "gs://example-staging/segment-weights/", }, + "coverage": "exact_fraction", }, "output": {"dir": "gs://impactlab-data-scratch/test"}, + "normalization": "per_destination", + } + + +def _polygon_cfg() -> dict: + d = _local_cfg() + del d["grid"] + d["regions"]["version"] = "targets-v1" + d["source"] = { + "path": "/tmp/units.parquet", + "id_fields": ["unit_id"], + "version": "units-v1", + "on_invalid_geometry": "repair", } + return d + + +def _without(d: dict, path: str) -> dict: + """``d`` with the key at the dotted ``path`` deleted, a weight named + in brackets.""" + d = copy.deepcopy(d) + *parents, key = path.split(".") + node = d + for part in parents: + if part.startswith("weights["): + name = part[len("weights[") : -1] + node = next(w for w in node["weights"] if w["name"] == name) + else: + node = node[part] + del node[key] + return d + + +class TestRequired: + """Keys whose wrong value would give another number in silence, which + a config states and which are refused by name when left out. Each + went red with the key defaulted.""" + + @pytest.mark.parametrize( + "config, path, named", + [ + (_local_cfg, "normalization", "normalization"), + (_local_cfg, "regions.on_invalid_geometry", "regions.on_invalid_geometry"), + (_polygon_cfg, "source.on_invalid_geometry", "source.on_invalid_geometry"), + (_local_cfg, "grid.offset", "grid.offset"), + (_local_cfg, "grid.lon_convention", "grid.lon_convention"), + (_local_cfg, "backend.coverage", "backend.coverage"), + (_local_cfg, "weights[pop].fallback", "weights.pop.fallback"), + (_local_cfg, "weights[pop].kind", "weights.pop.kind"), + (_bq_cfg, "weights[pop].column", "weights.pop.column"), + ], + ) + def test_a_config_without_the_key_is_refused_naming_it(self, config, path, named): + assert Config.model_validate(config()) + with pytest.raises(ValidationError) as exc: + Config.model_validate(_without(config(), path)) + assert named in str(exc.value) + + @pytest.mark.parametrize( + "key, value", [("fallback", "area"), ("kind", "point_sum")] + ) + def test_the_area_weight_takes_neither_fallback_nor_kind(self, key, value): + """Its total is the region's own area and it reads no raster, so + either would claim a choice that is never made.""" + d = _local_cfg() + d["weights"][1][key] = value + with pytest.raises(ValidationError, match=f"weights.area takes no {key}"): + Config.model_validate(d) + + def test_a_local_weight_with_a_column_is_refused(self): + d = _local_cfg() + d["weights"][0]["column"] = "population" + with pytest.raises(ValidationError, match="names a column of a BigQuery"): + Config.model_validate(d) class TestValidConfigs: def test_minimal_local_applies_defaults(self): cfg = Config.model_validate(_local_cfg()) assert cfg.backend.kind == "local" - assert cfg.grid.offset == "center" - assert cfg.grid.lon_convention == "[-180,180)" - assert cfg.backend.coverage == "exact_fraction" assert cfg.backend.local.dask == "off" assert cfg.output.format == "parquet" assert cfg.validation.sum_tolerance == 1e-6 - assert cfg.regions.on_invalid_geometry == "repair" def test_minimal_bigquery_applies_defaults(self): cfg = Config.model_validate(_bq_cfg()) @@ -84,12 +181,6 @@ def test_minimal_bigquery_applies_defaults(self): assert cfg.backend.bigquery.use_bqstorage is False assert cfg.grid.lon_convention == "[0,360)" - def test_weight_kind_default_is_point_sum(self): - cfg = Config.model_validate(_local_cfg()) - # Existing pop configs default cleanly to point_sum (legacy - # behaviour); no migration needed. - assert all(w.kind == "point_sum" for w in cfg.weights) - def test_weight_kind_area_weighted_sum_allowed(self): data = _local_cfg() data["weights"] = [ @@ -163,19 +254,31 @@ def test_dry_run_byte_ceiling_overridable(self): def test_prebuilt_grid_from_path(self): d = _local_cfg() - d["grid"] = {"mode": "prebuilt", "path": "/tmp/grid.parquet"} + d["grid"] = { + "mode": "prebuilt", + "path": "/tmp/grid.parquet", + "offset": "center", + "lon_convention": "[-180,180)", + } cfg = Config.model_validate(d) assert cfg.grid.mode == "prebuilt" assert cfg.grid.path == "/tmp/grid.parquet" def test_prebuilt_grid_from_table(self): d = _bq_cfg() - d["grid"] = {"mode": "prebuilt", "table": "compute-impactlab.foo.grid"} + d["grid"] = { + "mode": "prebuilt", + "table": "compute-impactlab.foo.grid", + "offset": "center", + "lon_convention": "[-180,180)", + } cfg = Config.model_validate(d) assert cfg.grid.table == "compute-impactlab.foo.grid" def test_load_from_toml(self, tmp_path): toml_text = """ +normalization = "per_destination" + [project] name = "demo" description = "exercise" @@ -183,21 +286,26 @@ def test_load_from_toml(self, tmp_path): [regions] path = "/tmp/regions.shp" id_fields = ["hierid"] +on_invalid_geometry = "repair" [grid] mode = "generate" resolution = 0.25 offset = "edge" +lon_convention = "[-180,180)" [[weights]] name = "pop" raster = "/tmp/pop.tif" +fallback = "area" +kind = "point_sum" [[weights]] name = "area" [backend] kind = "local" +coverage = "exact_fraction" [backend.local] dask = "local" @@ -230,7 +338,13 @@ def test_load_config_missing_file_raises(self, tmp_path): class TestGridErrors: def test_generate_with_path_is_ambiguous(self): d = _local_cfg() - d["grid"] = {"mode": "generate", "resolution": 1.0, "path": "/tmp/g.shp"} + d["grid"] = { + "mode": "generate", + "resolution": 1.0, + "path": "/tmp/g.shp", + "offset": "center", + "lon_convention": "[-180,180)", + } with pytest.raises(ValidationError) as exc: Config.model_validate(d) msg = str(exc.value) @@ -239,7 +353,13 @@ def test_generate_with_path_is_ambiguous(self): def test_generate_with_table_is_ambiguous(self): d = _bq_cfg() - d["grid"] = {"mode": "generate", "resolution": 1.0, "table": "x.y.z"} + d["grid"] = { + "mode": "generate", + "resolution": 1.0, + "table": "x.y.z", + "offset": "center", + "lon_convention": "[-180,180)", + } with pytest.raises(ValidationError) as exc: Config.model_validate(d) msg = str(exc.value) @@ -248,14 +368,24 @@ def test_generate_with_table_is_ambiguous(self): def test_generate_without_resolution(self): d = _local_cfg() - d["grid"] = {"mode": "generate"} + d["grid"] = { + "mode": "generate", + "offset": "center", + "lon_convention": "[-180,180)", + } with pytest.raises(ValidationError) as exc: Config.model_validate(d) assert "grid.resolution" in str(exc.value) def test_prebuilt_with_resolution_is_ambiguous(self): d = _local_cfg() - d["grid"] = {"mode": "prebuilt", "resolution": 1.0, "path": "/tmp/g.shp"} + d["grid"] = { + "mode": "prebuilt", + "resolution": 1.0, + "path": "/tmp/g.shp", + "offset": "center", + "lon_convention": "[-180,180)", + } with pytest.raises(ValidationError) as exc: Config.model_validate(d) msg = str(exc.value) @@ -264,7 +394,11 @@ def test_prebuilt_with_resolution_is_ambiguous(self): def test_prebuilt_without_source(self): d = _local_cfg() - d["grid"] = {"mode": "prebuilt"} + d["grid"] = { + "mode": "prebuilt", + "offset": "center", + "lon_convention": "[-180,180)", + } with pytest.raises(ValidationError) as exc: Config.model_validate(d) msg = str(exc.value) @@ -273,7 +407,13 @@ def test_prebuilt_without_source(self): def test_prebuilt_with_both_path_and_table(self): d = _local_cfg() - d["grid"] = {"mode": "prebuilt", "path": "/tmp/g.shp", "table": "x.y.z"} + d["grid"] = { + "mode": "prebuilt", + "path": "/tmp/g.shp", + "table": "x.y.z", + "offset": "center", + "lon_convention": "[-180,180)", + } with pytest.raises(ValidationError) as exc: Config.model_validate(d) msg = str(exc.value) @@ -283,7 +423,12 @@ def test_prebuilt_with_both_path_and_table(self): def test_negative_resolution(self): d = _local_cfg() - d["grid"] = {"mode": "generate", "resolution": -1.0} + d["grid"] = { + "mode": "generate", + "resolution": -1.0, + "offset": "center", + "lon_convention": "[-180,180)", + } with pytest.raises(ValidationError) as exc: Config.model_validate(d) assert "grid.resolution" in str(exc.value) or "resolution" in str(exc.value) @@ -299,7 +444,10 @@ def test_unknown_lon_convention(self): class TestWeightErrors: def test_local_non_area_without_raster(self): d = _local_cfg() - d["weights"] = [{"name": "pop"}, {"name": "area"}] + d["weights"] = [ + {"name": "pop", "fallback": "area", "kind": "point_sum"}, + {"name": "area"}, + ] with pytest.raises(ValidationError) as exc: Config.model_validate(d) msg = str(exc.value) @@ -309,7 +457,10 @@ def test_local_non_area_without_raster(self): def test_bigquery_non_area_without_table(self): d = _bq_cfg() - d["weights"] = [{"name": "pop"}, {"name": "area"}] + d["weights"] = [ + {"name": "pop", "fallback": "area", "kind": "point_sum"}, + {"name": "area"}, + ] with pytest.raises(ValidationError) as exc: Config.model_validate(d) msg = str(exc.value) @@ -336,8 +487,18 @@ def test_area_weight_rejects_table(self): def test_duplicate_weight_names(self): d = _local_cfg() d["weights"] = [ - {"name": "pop", "raster": "/tmp/p1.tif"}, - {"name": "pop", "raster": "/tmp/p2.tif"}, + { + "name": "pop", + "raster": "/tmp/p1.tif", + "fallback": "area", + "kind": "point_sum", + }, + { + "name": "pop", + "raster": "/tmp/p2.tif", + "fallback": "area", + "kind": "point_sum", + }, ] with pytest.raises(ValidationError) as exc: Config.model_validate(d) @@ -360,6 +521,7 @@ def test_both_path_and_table(self): "path": "/tmp/r.shp", "table": "x.y.z", "id_fields": ["hierid"], + "on_invalid_geometry": "repair", } with pytest.raises(ValidationError) as exc: Config.model_validate(d) @@ -370,7 +532,7 @@ def test_both_path_and_table(self): def test_neither_path_nor_table(self): d = _local_cfg() - d["regions"] = {"id_fields": ["hierid"]} + d["regions"] = {"id_fields": ["hierid"], "on_invalid_geometry": "repair"} with pytest.raises(ValidationError) as exc: Config.model_validate(d) msg = str(exc.value) @@ -379,7 +541,11 @@ def test_neither_path_nor_table(self): def test_empty_id_fields(self): d = _local_cfg() - d["regions"] = {"path": "/tmp/r.shp", "id_fields": []} + d["regions"] = { + "path": "/tmp/r.shp", + "id_fields": [], + "on_invalid_geometry": "repair", + } with pytest.raises(ValidationError) as exc: Config.model_validate(d) assert "id_fields" in str(exc.value) diff --git a/tests/unit/test_daily_grid_cells.py b/tests/unit/test_daily_grid_cells.py index 80d4136..366d9b1 100644 --- a/tests/unit/test_daily_grid_cells.py +++ b/tests/unit/test_daily_grid_cells.py @@ -114,7 +114,11 @@ def test_feeds_apply_weights_on_the_right_regions(): } ) weights = cilreg.WeightsArtifact.from_table( - table, id_fields=["region"], weights={"w": "share"}, source=BCSD_GRID + table, + id_fields=["region"], + weights={"w": "share"}, + source=BCSD_GRID, + normalization="per_destination", ) out = cilreg.apply_weights( weights, diff --git a/tests/unit/test_fallback.py b/tests/unit/test_fallback.py index b93aaf5..29e2b13 100644 --- a/tests/unit/test_fallback.py +++ b/tests/unit/test_fallback.py @@ -60,7 +60,9 @@ def test_native_normalization_to_one(self): raw = raw.loc[raw["region_id"] != "B"].copy() raw["region_id"] = pd.Categorical(raw["region_id"], categories=["A"]) area = area.loc[area["region_id"] == "A"].copy() - out = apply_fallback(raw, area, "pop", "area", ["region_id"]) + out = apply_fallback( + raw, area, "pop", "area", ["region_id"], normalization="per_destination" + ) sums = out.groupby("region_id")["popwt"].sum() assert sums.loc["A"] == pytest.approx(1.0) assert (out["pop_method"] == "native").all() @@ -69,7 +71,9 @@ def test_native_zero_cell_kept_with_zero_weight(self): raw = _raw_frame_AB_only() area = _area_frame() # A has cell (1,0) with raw=0; should appear in output with weight 0 - out = apply_fallback(raw, area, "pop", "area", ["region_id"]) + out = apply_fallback( + raw, area, "pop", "area", ["region_id"], normalization="per_destination" + ) a_rows = out.loc[out["region_id"] == "A"].sort_values(["cell_ix", "cell_iy"]) assert len(a_rows) == 3 # raw values 100, 100, 0 → weights 0.5, 0.5, 0 @@ -82,6 +86,7 @@ def test_compute_native_weights_for_area(self): ["region_id"], "area", raw_col="raw", + normalization="per_destination", ) sums = out.groupby("region_id")["areawt"].sum() for region in ["A", "B", "C"]: @@ -93,7 +98,9 @@ class TestFallbackArea: def test_zero_raw_region_falls_back_to_area(self): raw = _raw_frame_AB_only() area = _area_frame() - out = apply_fallback(raw, area, "pop", "area", ["region_id"]) + out = apply_fallback( + raw, area, "pop", "area", ["region_id"], normalization="per_destination" + ) c_rows = out.loc[out["region_id"] == "C"] # C has no raw at all → falls back to area weights (0.5, 0.5) assert (c_rows["pop_method"] == "area_fallback").all() @@ -103,7 +110,9 @@ def test_zero_raw_region_falls_back_to_area(self): def test_native_and_fallback_in_same_output(self): raw = _raw_frame_AB_only() area = _area_frame() - out = apply_fallback(raw, area, "pop", "area", ["region_id"]) + out = apply_fallback( + raw, area, "pop", "area", ["region_id"], normalization="per_destination" + ) # A, B: native; C: area_fallback methods = out.groupby("region_id")["pop_method"].first() assert methods.loc["A"] == "native" @@ -115,7 +124,9 @@ class TestFallbackZero: def test_zero_raw_region_gets_zero_weights(self): raw = _raw_frame_AB_only() area = _area_frame() - out = apply_fallback(raw, area, "pop", "zero", ["region_id"]) + out = apply_fallback( + raw, area, "pop", "zero", ["region_id"], normalization="per_destination" + ) c_rows = out.loc[out["region_id"] == "C"] assert (c_rows["pop_method"] == "zero").all() assert (c_rows["popwt"] == 0.0).all() @@ -128,7 +139,9 @@ class TestFallbackNan: def test_zero_raw_region_gets_nan_weights(self): raw = _raw_frame_AB_only() area = _area_frame() - out = apply_fallback(raw, area, "pop", "nan", ["region_id"]) + out = apply_fallback( + raw, area, "pop", "nan", ["region_id"], normalization="per_destination" + ) c_rows = out.loc[out["region_id"] == "C"] assert (c_rows["pop_method"] == "nan").all() assert c_rows["popwt"].isna().all() @@ -161,130 +174,30 @@ def test_nan_regions_invisible_to_sum_to_one_validator(self): "pop_method", ], ) - schema = OutputSchema(id_fields=("region_id",), weight_names=("pop",)) + schema = OutputSchema( + id_fields=("region_id",), + weight_names=("pop",), + normalization="per_destination", + ) report = check_sum_to_one(df, schema) assert report.ok, ( f"NaN regions must not be flagged; failures: {report.failures}" ) -class TestImplicitDefaultWarning: - def test_implicit_default_warns_when_threshold_crossed(self, caplog): - """When the fallback fires for >= max(5, 5% of regions) and the - policy was not set explicitly in TOML, log a WARN naming the - applied default + alternatives.""" - # Build 20 regions; 10 of them have zero raw. - area_rows = [] - raw_rows = [] - for i in range(20): - rid = f"R{i:02d}" - area_rows.append((rid, i, 0, float(i), float(0), 1.0, 1e9)) - if i < 10: - # zero raw -> fallback fires - pass - else: - raw_rows.append((rid, i, 0, 100.0)) - area = pd.DataFrame( - area_rows, - columns=[ - "region_id", - "cell_ix", - "cell_iy", - "cell_lon", - "cell_lat", - "areawt", - "area_raw", - ], - ) - raw = pd.DataFrame( - raw_rows, - columns=["region_id", "cell_ix", "cell_iy", "raw"], - ) - - with caplog.at_level("WARNING", logger="cil_regionalization.fallback"): - apply_fallback( - raw, - area, - "pop", - "area", - ["region_id"], - policy_explicit=False, - ) - msgs = [r.message for r in caplog.records if r.levelname == "WARNING"] - assert any("library default" in m for m in msgs) - assert any("[area | zero | error | nan]" in m for m in msgs) - assert any("weights.pop" in m for m in msgs) - assert any("Set weights.pop.fallback" in m for m in msgs) - - def test_explicit_policy_does_not_warn(self, caplog): - """If the user wrote `fallback = "area"` in TOML, no warning - even with the same fallback-fire pattern.""" - area = pd.DataFrame( - [(f"R{i}", i, 0, float(i), 0.0, 1.0, 1e9) for i in range(20)], - columns=[ - "region_id", - "cell_ix", - "cell_iy", - "cell_lon", - "cell_lat", - "areawt", - "area_raw", - ], - ) - raw = pd.DataFrame( - [(f"R{i}", i, 0, 100.0) for i in range(10, 20)], - columns=["region_id", "cell_ix", "cell_iy", "raw"], - ) - with caplog.at_level("WARNING", logger="cil_regionalization.fallback"): - apply_fallback( - raw, - area, - "pop", - "area", - ["region_id"], - policy_explicit=True, - ) - warn_msgs = [r.message for r in caplog.records if r.levelname == "WARNING"] - assert not any("library default" in m for m in warn_msgs) - - def test_implicit_default_below_threshold_does_not_warn(self, caplog): - """1 fallback region out of 20 is below the max(5, 5%) threshold.""" - area = pd.DataFrame( - [(f"R{i}", i, 0, float(i), 0.0, 1.0, 1e9) for i in range(20)], - columns=[ - "region_id", - "cell_ix", - "cell_iy", - "cell_lon", - "cell_lat", - "areawt", - "area_raw", - ], - ) - # 19 regions with raw, only R0 falls back - raw = pd.DataFrame( - [(f"R{i}", i, 0, 100.0) for i in range(1, 20)], - columns=["region_id", "cell_ix", "cell_iy", "raw"], - ) - with caplog.at_level("WARNING", logger="cil_regionalization.fallback"): +class TestFallbackError: + def test_zero_raw_region_raises_with_id(self): + raw = _raw_frame_AB_only() + area = _area_frame() + with pytest.raises(ValueError) as exc: apply_fallback( raw, area, "pop", - "area", + "error", ["region_id"], - policy_explicit=False, + normalization="per_destination", ) - warn_msgs = [r.message for r in caplog.records if r.levelname == "WARNING"] - assert not any("library default" in m for m in warn_msgs) - - -class TestFallbackError: - def test_zero_raw_region_raises_with_id(self): - raw = _raw_frame_AB_only() - area = _area_frame() - with pytest.raises(ValueError) as exc: - apply_fallback(raw, area, "pop", "error", ["region_id"]) msg = str(exc.value) assert "pop" in msg assert "C" in msg @@ -302,7 +215,9 @@ def test_zero_area_region_always_raises(self): columns=["region_id", "cell_ix", "cell_iy", "raw"], ) with pytest.raises(ValueError) as exc: - apply_fallback(raw, area, "pop", "area", ["region_id"]) + apply_fallback( + raw, area, "pop", "area", ["region_id"], normalization="per_destination" + ) assert "zero total area" in str(exc.value) assert "C" in str(exc.value) @@ -325,14 +240,22 @@ def test_compute_native_zero_total_raises(self): ], ) with pytest.raises(ValueError, match="B"): - compute_native_weights(area, ["region_id"], "area", raw_col="raw") + compute_native_weights( + area, + ["region_id"], + "area", + raw_col="raw", + normalization="per_destination", + ) class TestCountMethods: def test_method_counts_per_region(self): raw = _raw_frame_AB_only() area = _area_frame() - out = apply_fallback(raw, area, "pop", "area", ["region_id"]) + out = apply_fallback( + raw, area, "pop", "area", ["region_id"], normalization="per_destination" + ) counts = count_methods(out, "pop") # 2 native regions (A, B), 1 area_fallback (C) assert counts == {"native": 2, "area_fallback": 1} diff --git a/tests/unit/test_legacy_export.py b/tests/unit/test_legacy_export.py index 0b30e9a..f82d0b4 100644 --- a/tests/unit/test_legacy_export.py +++ b/tests/unit/test_legacy_export.py @@ -146,7 +146,11 @@ def _three_region_frame() -> pd.DataFrame: def _result_for(weight_names: tuple[str, ...]) -> _StubResult: return _StubResult( frame=_three_region_frame(), - schema=OutputSchema(id_fields=("hierid",), weight_names=weight_names), + schema=OutputSchema( + id_fields=("hierid",), + weight_names=weight_names, + normalization="per_destination", + ), ) @@ -226,6 +230,7 @@ def test_non_hierid_id_field_rejected(self): schema=OutputSchema( id_fields=("region_id",), weight_names=("area", "crop", "pop"), + normalization="per_destination", ), ) with pytest.raises(ValueError, match="hierid"): diff --git a/tests/unit/test_manifest.py b/tests/unit/test_manifest.py index 75b1f61..f50dc19 100644 --- a/tests/unit/test_manifest.py +++ b/tests/unit/test_manifest.py @@ -19,14 +19,29 @@ def _cfg() -> Config: return Config.model_validate( { "project": {"name": "test"}, - "regions": {"path": "/tmp/r.shp", "id_fields": ["hierid"]}, - "grid": {"mode": "generate", "resolution": 1.0}, + "regions": { + "path": "/tmp/r.shp", + "id_fields": ["hierid"], + "on_invalid_geometry": "repair", + }, + "grid": { + "mode": "generate", + "resolution": 1.0, + "offset": "center", + "lon_convention": "[-180,180)", + }, "weights": [ - {"name": "pop", "raster": "/tmp/pop.tif"}, + { + "name": "pop", + "raster": "/tmp/pop.tif", + "fallback": "area", + "kind": "point_sum", + }, {"name": "area"}, ], - "backend": {"kind": "local"}, + "backend": {"kind": "local", "coverage": "exact_fraction"}, "output": {"dir": "/tmp/out"}, + "normalization": "per_destination", } ) @@ -44,7 +59,12 @@ def test_config_hash_changes_with_content(self): cfg2 = Config.model_validate( { **cfg.model_dump(), - "grid": {"mode": "generate", "resolution": 0.25}, + "grid": { + "mode": "generate", + "resolution": 0.25, + "offset": "center", + "lon_convention": "[-180,180)", + }, } ) assert hash_config(cfg) != hash_config(cfg2) diff --git a/tests/unit/test_mass_balance.py b/tests/unit/test_mass_balance.py index c0010fe..0aa8075 100644 --- a/tests/unit/test_mass_balance.py +++ b/tests/unit/test_mass_balance.py @@ -225,6 +225,7 @@ def test_skip_records_in_manifest_and_continues(self, caplog): grid_resolution=1.0, package_versions={}, python_version="3", + normalization="per_destination", ) policies = SourceUnitPolicies( on_unmatched="skip", on_zero_weight="skip", on_absent_from_data="skip" @@ -249,6 +250,7 @@ def test_manifest_recorded_even_when_erroring(self): grid_resolution=1.0, package_versions={}, python_version="3", + normalization="per_destination", ) with pytest.raises(ValueError): enforce_source_policies(self._coverage(), SourceUnitPolicies(), manifest) diff --git a/tests/unit/test_merge.py b/tests/unit/test_merge.py index 11b87db..82ac21d 100644 --- a/tests/unit/test_merge.py +++ b/tests/unit/test_merge.py @@ -58,7 +58,11 @@ def _manifest(**extra) -> dict: def _schema() -> OutputSchema: - return OutputSchema(id_fields=("hierid",), weight_names=("pop", "area")) + return OutputSchema( + id_fields=("hierid",), + weight_names=("pop", "area"), + normalization="per_destination", + ) class TestHappyPath: diff --git a/tests/unit/test_regions.py b/tests/unit/test_regions.py index e0c6687..6dec228 100644 --- a/tests/unit/test_regions.py +++ b/tests/unit/test_regions.py @@ -15,7 +15,11 @@ class TestLocalLoad: def test_load_geoparquet(self, three_region_geoparquet: Path): - cfg = RegionsConfig(path=str(three_region_geoparquet), id_fields=["region_id"]) + cfg = RegionsConfig( + path=str(three_region_geoparquet), + id_fields=["region_id"], + on_invalid_geometry="repair", + ) rs = RegionSet.from_config(cfg) assert rs.is_local assert len(rs) == 3 @@ -23,13 +27,19 @@ def test_load_geoparquet(self, three_region_geoparquet: Path): assert sorted(ids) == ["A", "B", "C"] def test_missing_path_raises(self, tmp_path: Path): - cfg = RegionsConfig(path=str(tmp_path / "nope.parquet"), id_fields=["x"]) + cfg = RegionsConfig( + path=str(tmp_path / "nope.parquet"), + id_fields=["x"], + on_invalid_geometry="repair", + ) with pytest.raises(FileNotFoundError, match="regions.path"): RegionSet.from_config(cfg) def test_missing_id_field_raises(self, three_region_geoparquet: Path): cfg = RegionsConfig( - path=str(three_region_geoparquet), id_fields=["missing_col"] + path=str(three_region_geoparquet), + id_fields=["missing_col"], + on_invalid_geometry="repair", ) with pytest.raises(ValueError, match="missing_col"): RegionSet.from_config(cfg) @@ -41,6 +51,7 @@ def test_keep_filter(self, three_region_geoparquet: Path): path=str(three_region_geoparquet), id_fields=["region_id"], keep={"label": ["alpha", "gamma"]}, + on_invalid_geometry="repair", ) rs = RegionSet.from_config(cfg) ids = sorted(d["region_id"] for d, _ in rs.iter_regions()) @@ -51,6 +62,7 @@ def test_drop_filter(self, three_region_geoparquet: Path): path=str(three_region_geoparquet), id_fields=["region_id"], drop={"region_id": ["B"]}, + on_invalid_geometry="repair", ) rs = RegionSet.from_config(cfg) ids = sorted(d["region_id"] for d, _ in rs.iter_regions()) @@ -61,6 +73,7 @@ def test_filter_unknown_column_raises(self, three_region_geoparquet: Path): path=str(three_region_geoparquet), id_fields=["region_id"], keep={"no_such_col": ["A"]}, + on_invalid_geometry="repair", ) with pytest.raises(ValueError, match="no_such_col"): RegionSet.from_config(cfg) @@ -71,6 +84,7 @@ def test_unknown_keep_and_drop_values_reported(self, three_region_geoparquet: Pa id_fields=["region_id"], keep={"label": ["alpha", "gamma", "no_such_label"]}, drop={"region_id": ["C", "Z"]}, + on_invalid_geometry="repair", ) rs = RegionSet.from_config(cfg) assert [d["region_id"] for d, _ in rs.iter_regions()] == ["A"] @@ -85,6 +99,7 @@ def test_matching_values_report_nothing(self, three_region_geoparquet: Path): id_fields=["region_id"], keep={"region_id": ["A", "C"]}, drop={"region_id": ["B"]}, + on_invalid_geometry="repair", ) rs = RegionSet.from_config(cfg) assert rs.unknown_keep_ids == {} @@ -160,19 +175,24 @@ def test_bq_table_holds_reference_only(self): cfg = RegionsConfig( table="compute-impactlab.foo.regions", id_fields=["hierid"], + on_invalid_geometry="repair", ) rs = RegionSet.from_config(cfg) assert not rs.is_local assert rs.table == "compute-impactlab.foo.regions" def test_bq_iter_regions_refuses(self): - cfg = RegionsConfig(table="ci.foo.bar", id_fields=["hierid"]) + cfg = RegionsConfig( + table="ci.foo.bar", id_fields=["hierid"], on_invalid_geometry="repair" + ) rs = RegionSet.from_config(cfg) with pytest.raises(ValueError, match="BigQuery"): next(rs.iter_regions()) def test_bq_len_refuses(self): - cfg = RegionsConfig(table="ci.foo.bar", id_fields=["hierid"]) + cfg = RegionsConfig( + table="ci.foo.bar", id_fields=["hierid"], on_invalid_geometry="repair" + ) rs = RegionSet.from_config(cfg) with pytest.raises(ValueError, match="BigQuery"): len(rs) @@ -217,11 +237,18 @@ def test_a_gs_path_passes_the_input_check(self): "regions": { "path": "gs://bucket/regions.parquet", "id_fields": ["region_id"], + "on_invalid_geometry": "repair", + }, + "grid": { + "mode": "generate", + "resolution": 1.0, + "offset": "center", + "lon_convention": "[-180,180)", }, - "grid": {"mode": "generate", "resolution": 1.0}, "weights": [{"name": "area"}], - "backend": {"kind": "local"}, + "backend": {"kind": "local", "coverage": "exact_fraction"}, "output": {"dir": "out"}, + "normalization": "per_destination", } ) assert check_inputs_exist(cfg) == [] @@ -244,7 +271,11 @@ def test_a_gs_file_is_read_and_hashed(self, tmp_path, monkeypatch, name): gdf.to_file(bucket / name) _fake_gcsfs(monkeypatch, tmp_path) rs = RegionSet.from_config( - RegionsConfig(path=f"gs://bucket/{name}", id_fields=["region_id"]) + RegionsConfig( + path=f"gs://bucket/{name}", + id_fields=["region_id"], + on_invalid_geometry="repair", + ) ) assert sorted(rs.gdf["region_id"]) == ["a", "b"] assert rs.source_uri == f"gs://bucket/{name}" @@ -256,7 +287,11 @@ 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"]) + RegionsConfig( + path=str(three_region_geoparquet), + id_fields=["region_id"], + on_invalid_geometry="repair", + ) ) assert rs.source_sha256 is None @@ -266,5 +301,9 @@ def test_without_gcsfs_the_extra_that_installs_it_is_named(self, monkeypatch): 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"]) + RegionsConfig( + path="gs://bucket/regions.parquet", + id_fields=["id"], + on_invalid_geometry="repair", + ) ) diff --git a/tests/unit/test_schema.py b/tests/unit/test_schema.py index 03ed10a..b82373c 100644 --- a/tests/unit/test_schema.py +++ b/tests/unit/test_schema.py @@ -35,7 +35,11 @@ def test_cell_columns_in_order(self): class TestOutputSchema: def test_columns_ordered_ids_cell_weights(self): - s = OutputSchema(id_fields=("region_id",), weight_names=("pop", "area")) + s = OutputSchema( + id_fields=("region_id",), + weight_names=("pop", "area"), + normalization="per_destination", + ) assert s.columns == ( "region_id", "cell_ix", @@ -51,7 +55,11 @@ def test_columns_ordered_ids_cell_weights(self): ) def test_multi_id_fields_ordered(self): - s = OutputSchema(id_fields=("country", "admin1"), weight_names=("pop",)) + s = OutputSchema( + id_fields=("country", "admin1"), + weight_names=("pop",), + normalization="per_destination", + ) assert s.columns[:5] == ( "country", "admin1", @@ -61,7 +69,11 @@ def test_multi_id_fields_ordered(self): ) def test_dtypes_match_columns(self): - s = OutputSchema(id_fields=("region_id",), weight_names=("pop",)) + s = OutputSchema( + id_fields=("region_id",), + weight_names=("pop",), + normalization="per_destination", + ) d = s.dtypes assert set(d.keys()) == set(s.columns) assert d["cell_ix"] == "int64" @@ -70,7 +82,11 @@ def test_dtypes_match_columns(self): assert d["pop_method"] == "string" def test_empty_frame_has_schema(self): - s = OutputSchema(id_fields=("region_id",), weight_names=("pop",)) + s = OutputSchema( + id_fields=("region_id",), + weight_names=("pop",), + normalization="per_destination", + ) df = s.empty_frame() assert list(df.columns) == list(s.columns) assert len(df) == 0 @@ -78,7 +94,11 @@ def test_empty_frame_has_schema(self): class TestValidateFrame: def test_well_formed_frame_passes(self): - s = OutputSchema(id_fields=("region_id",), weight_names=("pop",)) + s = OutputSchema( + id_fields=("region_id",), + weight_names=("pop",), + normalization="per_destination", + ) df = pd.DataFrame( { "region_id": pd.array(["A", "B"], dtype="string"), @@ -94,13 +114,21 @@ def test_well_formed_frame_passes(self): s.validate_frame(df) def test_missing_column_raises(self): - s = OutputSchema(id_fields=("region_id",), weight_names=("pop",)) + s = OutputSchema( + id_fields=("region_id",), + weight_names=("pop",), + normalization="per_destination", + ) df = pd.DataFrame({"region_id": ["A"]}) with pytest.raises(ValueError, match="missing columns"): s.validate_frame(df) def test_dtype_mismatch_raises(self): - s = OutputSchema(id_fields=("region_id",), weight_names=("pop",)) + s = OutputSchema( + id_fields=("region_id",), + weight_names=("pop",), + normalization="per_destination", + ) df = pd.DataFrame( { "region_id": ["A"], @@ -138,7 +166,11 @@ def test_string_ids_require_at_least_one_column(self): class TestNormalizationDirection: def test_default_is_per_destination_over_id_fields(self): - s = OutputSchema(id_fields=("region_id",), weight_names=("pop",)) + s = OutputSchema( + id_fields=("region_id",), + weight_names=("pop",), + normalization="per_destination", + ) assert s.normalization == "per_destination" assert s.normalization_group == ("region_id",) diff --git a/tests/unit/test_validate.py b/tests/unit/test_validate.py index 089b96e..6d74ae1 100644 --- a/tests/unit/test_validate.py +++ b/tests/unit/test_validate.py @@ -29,7 +29,11 @@ def _clean_frame() -> pd.DataFrame: class TestCleanFrame: def test_clean_frame_passes(self): - schema = OutputSchema(id_fields=("region_id",), weight_names=("pop", "area")) + schema = OutputSchema( + id_fields=("region_id",), + weight_names=("pop", "area"), + normalization="per_destination", + ) report = check_sum_to_one(_clean_frame(), schema, tolerance=1e-9) assert report.ok assert report.n_regions == 2 @@ -42,7 +46,11 @@ def test_corrupt_one_region_one_weight(self): df = _clean_frame() # break region A's pop sum df.loc[0, "popwt"] = 0.5 # was 0.4; A now sums to 1.1 - schema = OutputSchema(id_fields=("region_id",), weight_names=("pop", "area")) + schema = OutputSchema( + id_fields=("region_id",), + weight_names=("pop", "area"), + normalization="per_destination", + ) report = check_sum_to_one(df, schema, tolerance=1e-6) assert not report.ok assert len(report.failures) == 1 @@ -55,14 +63,22 @@ def test_corrupt_one_region_one_weight(self): def test_tolerance_accepts_small_drift(self): df = _clean_frame() df.loc[0, "popwt"] = 0.4 + 1e-12 - schema = OutputSchema(id_fields=("region_id",), weight_names=("pop",)) + schema = OutputSchema( + id_fields=("region_id",), + weight_names=("pop",), + normalization="per_destination", + ) report = check_sum_to_one(df, schema, tolerance=1e-6) assert report.ok def test_zero_weight_region_fails(self): df = _clean_frame() df.loc[df["region_id"] == "A", "popwt"] = 0.0 - schema = OutputSchema(id_fields=("region_id",), weight_names=("pop",)) + schema = OutputSchema( + id_fields=("region_id",), + weight_names=("pop",), + normalization="per_destination", + ) report = check_sum_to_one(df, schema, tolerance=1e-6) assert not report.ok assert any(report.failures["region_id"] == "A") @@ -90,7 +106,11 @@ def _grid(self): def _schema(self): from cil_regionalization.schema import OutputSchema - return OutputSchema(id_fields=("region_id",), weight_names=("pop",)) + return OutputSchema( + id_fields=("region_id",), + weight_names=("pop",), + normalization="per_destination", + ) def _clean_row(self) -> dict: return { @@ -156,7 +176,11 @@ def test_summary_lists_invariant_counts(self): class TestMissingColumn: def test_missing_weight_column_raises(self): df = _clean_frame().drop(columns=["popwt"]) - schema = OutputSchema(id_fields=("region_id",), weight_names=("pop",)) + schema = OutputSchema( + id_fields=("region_id",), + weight_names=("pop",), + normalization="per_destination", + ) with pytest.raises(ValueError, match="popwt"): check_sum_to_one(df, schema) From 83561fec300aa98dc3e90f1313610426f1c84c6f Mon Sep 17 00:00:00 2001 From: Sebastian Cadavid Sanchez Date: Fri, 27 Nov 2026 23:05:45 -0600 Subject: [PATCH 4/5] record that the weights are regenerated before any product A product's run manifest records the SHA-256 of the weights files it loaded, the weights manifest among them, and a regenerated weights manifest records another config hash. Regenerating the GADM weights needs the target layers, rebuilt from the GADM sources by the prepare_gadm*_targets.py scripts. --- CHANGELOG.md | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c840eb..f202484 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -54,6 +54,17 @@ records changes for every config, the same values included, since a weight now holds its column and the area weight no fallback or kind, so a hash from an earlier run does not match one written now. +Regenerating the weights artifacts gives the same weights with new +manifests, since each config states the value its default gave. They are +regenerated before any product, because a product's run manifest records +the SHA-256 of both files of the weights it loaded, the manifest among +them, and a regenerated manifest records another config hash, so a +product made from the old weights would name a manifest that is no +longer published. Regenerating the GADM weights needs the GADM target +layers, which are not distributed and are rebuilt from the GADM sources +with `examples/gadm20/prepare_gadm20_targets.py` and +`examples/gadm41/prepare_gadm41_targets.py`. + **Every block of a reduce is measured and recorded, and only the first is judged.** Nothing is refused that was not before. A run then shows how much blocks of one size vary from worker to worker and how far the From 32f09887234dde45e9d7d6a739a925bce81d8e19 Mon Sep 17 00:00:00 2001 From: Sebastian Cadavid Sanchez Date: Fri, 27 Nov 2026 23:12:26 -0600 Subject: [PATCH 5/5] say that a weights manifest's config is found with the version that wrote it The config hash changes for every weights config, so hashing candidate configs with this version cannot find the config of an earlier manifest. The published GADM weights name the version that wrote them as segment_weights 0.1.0. --- CHANGELOG.md | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f202484..6e5b12e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,7 +52,13 @@ already changes for the quantile method, the summation, the declared members and the model weight names. The config hash a weights manifest records changes for every config, the same values included, since a weight now holds its column and the area weight no fallback or kind, so -a hash from an earlier run does not match one written now. +a hash from an earlier run does not match one written now. So the config +an earlier weights manifest came from can no longer be found by hashing +candidate configs with this version, which refuses an old config for its +missing keys and hashes a completed one differently. It takes the +version that wrote the manifest, named in its package_versions, which +the published GADM weights give as segment_weights 0.1.0, the package's +former name. Regenerating the weights artifacts gives the same weights with new manifests, since each config states the value its default gave. They are