From e69b5b05c79577ca41f1d6734f7e1898ff225d90 Mon Sep 17 00:00:00 2001 From: Sebastian Cadavid Sanchez Date: Fri, 27 Nov 2026 02:52:15 -0600 Subject: [PATCH] require exact or declared names for model weights --- CHANGELOG.md | 62 ++++- README.md | 70 ++++-- cil_regionalization/backends/bigquery.py | 4 +- cil_regionalization/cli.py | 5 + cil_regionalization/compute.py | 41 ++-- cil_regionalization/config.py | 83 +++++-- cil_regionalization/cross_backend_compare.py | 5 - cil_regionalization/fetch.py | 13 +- cil_regionalization/legacy_compare.py | 5 - cil_regionalization/legacy_export.py | 5 - cil_regionalization/model_weights.py | 191 ++++++++++++---- cil_regionalization/pipelines/montecarlo.py | 77 +++++-- cil_regionalization/stats.py | 78 ++++--- docs/reference.md | 67 ++++-- examples/aggregation/run_example.py | 22 +- examples/energy_percentiles/prepare_data.py | 17 +- examples/france/france.py | 43 +++- examples/france/synthetic_data.py | 3 +- examples/model_weights/README.md | 47 ++++ examples/model_weights/smme_rcp45_names.toml | 38 ++++ examples/model_weights/smme_rcp85_names.toml | 39 ++++ .../montecarlo/runs/run_valued_mortality.py | 38 ++-- tests/integration/test_bigquery_backend.py | 30 ++- tests/integration/test_fetch.py | 24 +- tests/integration/test_montecarlo_pipeline.py | 104 ++++++--- tests/integration/test_regions_find.py | 2 + tests/integration/test_xarray_parity.py | 7 +- tests/unit/test_compute.py | 24 ++ tests/unit/test_config.py | 99 +++++++- tests/unit/test_model_weights.py | 213 ++++++++++++------ tests/unit/test_no_site_facts.py | 47 ++++ tests/unit/test_stats.py | 81 +++++-- tests/unit/test_stats_methods.py | 46 +++- 33 files changed, 1245 insertions(+), 385 deletions(-) create mode 100644 examples/model_weights/README.md create mode 100644 examples/model_weights/smme_rcp45_names.toml create mode 100644 examples/model_weights/smme_rcp85_names.toml create mode 100644 tests/unit/test_no_site_facts.py diff --git a/CHANGELOG.md b/CHANGELOG.md index b836920..2bb766c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,55 @@ ## Unreleased +**A model takes the row of its own name in a model weights table, +letter for letter, or the row declared for it, and a model with +neither is refused.** Before, the library dropped `surrogate_` from the +tree's names and `*` from the table's and lowercased both, a rule +nobody saw that could put a weight on the wrong model. The refusal +names each model as the tree spells it with the row it comes closest +to, and says the two ways out: write the trees' names into the table, +or declare each model's row, model name to table name, under +`[stats.model_weight_names]` of a pipeline config or as `table_names` +of `read_model_weights` and `fetch_model_weights`. The manifest records +the rows declared. **The published SMME tables do not pass as they +stand.** They name the models in lower case, some with a trailing `*`, +and the surrogates without the prefix, so of the 32 models under +rcp45 and the 33 under rcp85 only `bcc-csm1-1` matches. Until the +tables are rewritten, every run that reads them declares the rows. +`examples/model_weights/` holds the pairs for both tables, written out, +and `load_model_weight_names` reads them. Two models declared to one +row, or taking one row between them, are refused. `ModelWeights` loses +`keys` and gains `check`, and `read_model_weights` takes `sep`. The +France, aggregation, energy percentiles and valued mortality examples +declare their rows. + +**A model at weight zero is dropped before every quantile, as it was +from the mean.** `"lower_step"` could return the value of such a model, +since its weight did not move the running share. The published SMME +tables have no row at weight zero. + +**`UnweightedModelWeightsWarning` is given when `model_dims` names the +climate model and no weights are set, and no longer when a sample +dimension is called `gcm`.** Its message names no lab. +`summarize_samples` and `pooled_statistics` take `model_dims` without +`include_n_members`, for the warning, where it was refused. + +**No fact of one cluster or one cloud account is a default.** With +`backend.local.dask = "slurm"` the queue, the cores, memory and +walltime of a job and the number of jobs, `slurm_queue`, the new +`slurm_cores` and `slurm_memory`, `slurm_walltime` and `n_workers`, are +required. They defaulted to one cluster's partition. With +`backend.kind = "bigquery"`, `backend.bigquery.project` and +`temp_dataset` are required, where they defaulted to one cloud +account's. The docstrings that named a cluster's paths no longer do, +and a test reads every module of the package for such facts, where it +read the pipeline alone. + +**The BigQuery backend refuses an edge-offset grid.** Its SQL places +the cells for the centre offset, so it returned the weights of an +edge-offset grid half a cell off. The config and the backend both +refuse it. + The documentation of `quantile_method` says which value estimates a quantile. `"inverted_cdf"` is the estimator and returns a value a member has. `"linear"` interpolates and can return a number no member @@ -214,14 +263,11 @@ its warming level in a calendar period. carries is of the bytes the rows were parsed from. `attach` returns the weight of each row's model and raises if a model has no row. `record` returns the entry a manifest should keep, described below. - Names match as they did before: a `*` is dropped from the table - name, `surrogate_` is dropped from the member, and both are - lowercased. -- Changed: a weights table in which two rows match the same model is - refused, with both rows named. Before, the last of the two rows was - applied and nothing was said. Neither published SMME table has such - rows (32 names in the rcp45 table, 33 in the rcp85 one, all - distinct after matching), so no run that worked is refused. + A model takes the row of its own name or the row declared for it, + as the first entry of this section says. +- Changed: a weights table with a name in it twice is refused, with + the name given. Before, the last of the two rows was applied and + nothing was said. - Changed: the pipeline reads the model weights file once, in the parent, and hands those rows to the workers. Before, every worker read the file again when it started, and workers are replaced every diff --git a/README.md b/README.md index 5551f9a..cca78a3 100644 --- a/README.md +++ b/README.md @@ -228,7 +228,10 @@ product reads the same table. `attach` gives every draw the weight of its model, so the weight repeats across batches: ```python -weights = cilreg.fetch_model_weights("rcp85") +from cil_regionalization.pipelines.montecarlo import load_model_weight_names + +names = load_model_weight_names("examples/model_weights/smme_rcp85_names.toml") +weights = cilreg.fetch_model_weights("rcp85", table_names=names) draws["weight"] = weights.attach(draws["gcm"]) stats = cilreg.summarize_samples( draws, @@ -242,34 +245,51 @@ stats = cilreg.summarize_samples( ) ``` -The naming rule: weight file names are lowercase, a trailing `*` is -bookkeeping and drops out, and an underscore suffix (`gfdl-cm3_94`) -marks a surrogate, which the projection trees spell with a prefix -(`surrogate_GFDL-CM3_94`). Strip the prefix and lowercase, and every -model in the trees matches exactly one weight row. - -`read_model_weights` applies that rule to a file on disk. It reads the -file once and refuses a table in which two rows match the same model. +A model takes the row of its own name, letter for letter, or the row +declared for it, and a model with neither is refused. Nothing reads a +name to decide what it means, so a weight cannot land on the wrong +model by a rule nobody sees. The published tables do not pass as they +stand. They name the models in lower case, some with a trailing `*`, +and the surrogates without the `surrogate_` prefix of the trees, so +`ACCESS1-0` is the row `access1-0*` and `surrogate_GFDL-CM3_94` the row +`gfdl-cm3_94`. Until the tables are rewritten with the trees' names, a +run declares each model's row, model name to table name, written out. +`examples/model_weights/` holds the pairs for both published tables, +which the code above reads. The refusal names the row a model comes +closest to, and the two ways out, fixing the table or declaring the +row. + +`read_model_weights` does the same for a file on disk. It reads the +file once and refuses a table that has a name twice, and two models +declared to one row. ```python -weights = cilreg.read_model_weights("rcp85_SMME_weights.tsv") +weights = cilreg.read_model_weights("rcp85_SMME_weights.tsv", table_names=names) draws["weight"] = weights.attach(draws["gcm"]) entry = weights.record(leaf_models) # one model name per leaf pooled ``` -`attach` raises if a model has no row. `record` returns what a manifest -should keep about the run: the file's path and SHA256, each model that -was given a weight with that weight and its number of leaves, and the -rows no model matched with their weights. The two lists together are -the whole table, so the statistics can be rerun from the manifest if -the file is lost. A pipeline run writes this entry to its manifest as -`model_weights_record`. +`attach` raises if a model has no row, or two models take one row. +`record` returns what a manifest should keep about the run: the file's +path and SHA256, the rows declared, each model that was given a weight +with its row, that weight and its number of leaves, and the rows no +model took with their weights. The two lists together are the whole +table, so the statistics can be rerun from the manifest if the file is +lost. A pipeline run writes this entry to its manifest as +`model_weights_record`, and takes the declared rows as +`[stats.model_weight_names]`: + +```toml +[stats.model_weight_names] +"ACCESS1-0" = "access1-0*" +"surrogate_GFDL-CM3_94" = "gfdl-cm3_94" +``` Weighted quantiles follow the historical extraction tool: the left step inverse of the weighted empirical distribution, not the -interpolated quantiles of the unweighted path. Pooling a sample -dimension named `gcm` without weights warns once; filter -`UnweightedModelWeightsWarning` to silence it. On the Mexico sample +interpolated quantiles of the unweighted path. Pooling without +weights while `model_dims` names the climate model warns once. Filter +`UnweightedModelWeightsWarning` where equal weights are meant. On the Mexico sample (`examples/rates`) the weights barely move the median and pull the 95th percentile down by about a fifth. @@ -279,8 +299,8 @@ the computation: - `"inverted_cdf"` is the estimator of a quantile, the standard inverse of the empirical distribution (Hyndman and Fan type 1), the smallest member value whose cumulative weight share reaches q. It is - the same with or without weights, always returns the value of a - member, and never that of a member whose weight is zero. + the same with or without weights, and always returns the value of a + member. - `"linear"` interpolates between two members, so it can return a number no member holds. It is computed by numpy, so it is `numpy.quantile(method="linear")` and xarray's `.quantile` to the @@ -291,10 +311,12 @@ the computation: except the median of members that count equally. Without weights every member counts the same, which is what that tool did when it was told to use no model weights. A quantile at or below the first - member's share is `-inf`, and the value of a member with weight zero - can come back. + member's share is `-inf`. The names say what each computes, so pick by that, not by the name. +A member with weight zero is dropped before any of them, and before +the mean and the counts, so no quantile returns the value of a member +that weighs nothing. With four members that count equally the three give three different 95th percentiles. `"inverted_cdf"` gives the fourth member, `"linear"` diff --git a/cil_regionalization/backends/bigquery.py b/cil_regionalization/backends/bigquery.py index cc38a78..c02ab94 100644 --- a/cil_regionalization/backends/bigquery.py +++ b/cil_regionalization/backends/bigquery.py @@ -46,7 +46,7 @@ from cil_regionalization.backends.base import WeightsBackend, WeightsResult -from cil_regionalization.config import Config +from cil_regionalization.config import BIGQUERY_CENTRE_ONLY, Config from cil_regionalization.fallback import ( apply_fallback, compute_native_weights, @@ -317,6 +317,8 @@ def _validate_inputs( "BigQueryBackend Stage 3 supports grid.mode='generate' only. " "Prebuilt grids land later." ) + if grid.offset != "center": + raise ValueError(BIGQUERY_CENTRE_ONLY.format(offset=grid.offset)) for w in weights: if w.is_area: continue diff --git a/cil_regionalization/cli.py b/cil_regionalization/cli.py index 236a77c..3147866 100644 --- a/cil_regionalization/cli.py +++ b/cil_regionalization/cli.py @@ -373,6 +373,11 @@ def _cmd_regions_find(config_path: str, *, pattern: str, limit: int) -> int: def _regions_find_bq(cfg: Config, primary: str, pattern: str, limit: int) -> int: from google.cloud import bigquery + if cfg.backend.bigquery.project is None: + raise ValueError( + "regions.table is read through BigQuery, which needs " + "backend.bigquery.project, the billing project. It has no default." + ) client = bigquery.Client(project=cfg.backend.bigquery.project) table = cfg.regions.table project, dataset, _ = table.split(".", 2) diff --git a/cil_regionalization/compute.py b/cil_regionalization/compute.py index 9a543a0..2b1fe4e 100644 --- a/cil_regionalization/compute.py +++ b/cil_regionalization/compute.py @@ -5,9 +5,10 @@ with dask_client_for(cfg.backend.local) as client: ... # `client` is None when dask = "off" -The config's `n_workers`, `threads_per_worker`, `slurm_queue` and -`slurm_walltime` override the defaults. The cores and memory of a SLURM -job are fixed to the CIL 'cil' partition. +The config's `n_workers` and `threads_per_worker` override the local +defaults. A SLURM cluster takes its queue, the cores, memory and +walltime of a job and the number of jobs from the config alone, which +has no default for any of them. """ from __future__ import annotations @@ -22,15 +23,6 @@ logger = logging.getLogger(__name__) -# CIL 'cil' partition reference shape: 64 cores, 251 GB RAM per node, -# typical run uses 2 nodes. One Dask worker per node by default so -# in-process geometry caches are shared across threads. -_SLURM_DEFAULT_QUEUE = "cil" -_SLURM_DEFAULT_CORES = 64 -_SLURM_DEFAULT_MEMORY = "251GB" -_SLURM_DEFAULT_WALLTIME = "02:00:00" -_SLURM_DEFAULT_N_WORKERS = 2 - # LocalCluster reference shape: one worker per process so each gets # its own Python interpreter (geometry ops release the GIL only # partially); single thread per worker keeps the scheduler simple. @@ -46,9 +38,10 @@ def dask_client_for(opts: LocalBackendOptions) -> Iterator[Optional[object]]: Under ``"off"`` the caller runs serially and Dask is not imported, so this works without the optional dependency. ``"local"`` starts a ``LocalCluster`` on this machine. ``"slurm"`` starts a - ``dask_jobqueue.SLURMCluster`` on the CIL 'cil' partition and scales it - to ``opts.n_workers`` jobs. The client and cluster are closed when the - ``with`` block exits. Raises if ``opts.dask`` is any other value. + ``dask_jobqueue.SLURMCluster`` with the queue, cores, memory and + walltime of ``opts`` and scales it to ``opts.n_workers`` jobs. The + client and cluster are closed when the ``with`` block exits. Raises + if ``opts.dask`` is any other value, or a SLURM setting is missing. """ if opts.dask == "off": yield None @@ -79,23 +72,25 @@ def dask_client_for(opts: LocalBackendOptions) -> Iterator[Optional[object]]: return if opts.dask == "slurm": + # checked again, before anything is imported, for options built + # without the model's check + type(opts).model_validate(opts.model_dump()) from dask.distributed import Client from dask_jobqueue import SLURMCluster - n_workers = opts.n_workers or _SLURM_DEFAULT_N_WORKERS cluster = SLURMCluster( - queue=opts.slurm_queue or _SLURM_DEFAULT_QUEUE, - cores=_SLURM_DEFAULT_CORES, - memory=_SLURM_DEFAULT_MEMORY, - walltime=opts.slurm_walltime or _SLURM_DEFAULT_WALLTIME, + queue=opts.slurm_queue, + cores=opts.slurm_cores, + memory=opts.slurm_memory, + walltime=opts.slurm_walltime, processes=opts.threads_per_worker or 1, ) - cluster.scale(jobs=n_workers) + cluster.scale(jobs=opts.n_workers) client = Client(cluster) logger.info( "dask SLURMCluster requested: %d jobs on queue %r", - n_workers, - opts.slurm_queue or _SLURM_DEFAULT_QUEUE, + opts.n_workers, + opts.slurm_queue, ) try: yield client diff --git a/cil_regionalization/config.py b/cil_regionalization/config.py index 5e92d0d..5790333 100644 --- a/cil_regionalization/config.py +++ b/cil_regionalization/config.py @@ -24,6 +24,13 @@ LonConvention = Literal["[-180,180)", "[0,360)"] GridOffset = Literal["center", "edge"] +# The BigQuery backend's SQL places every cell for the centre offset. +BIGQUERY_CENTRE_ONLY = ( + "backend.kind = 'bigquery' takes grid.offset = 'center' only, and got " + "{offset!r}. Its SQL handles centre offsets only, so the weights of an " + "edge-offset grid would come out half a cell off. Use backend.kind = " + "'local' for an edge-offset grid." +) GridMode = Literal["generate", "prebuilt"] CoverageMode = Literal["exact_fraction", "pixel_centroid"] BackendKind = Literal["local", "bigquery"] @@ -198,10 +205,17 @@ class WeightConfig(_Strict): class LocalBackendOptions(_Strict): dask: DaskMode = "off" + # Under "slurm" the number of jobs, and under "local" the number of + # processes, four unless set. n_workers: Optional[int] = Field(default=None, ge=1) threads_per_worker: Optional[int] = Field(default=None, ge=1) - slurm_queue: Optional[str] = None - slurm_walltime: Optional[str] = None + # The queue, the cores and memory of one job, and its walltime, as + # dask_jobqueue takes them. Facts of a cluster, so none has a + # default, and dask = "slurm" needs every one of them and n_workers. + slurm_queue: Optional[str] = Field(default=None, min_length=1) + slurm_cores: Optional[int] = Field(default=None, ge=1) + slurm_memory: Optional[str] = Field(default=None, min_length=1) + slurm_walltime: Optional[str] = Field(default=None, min_length=1) # Segments below this geodesic area are dropped as boundary residue. # The default is justified by the measured global IR-to-ADM1 # distribution: 3,410 of 28,646 segments fall below 1 m2 (floating @@ -218,15 +232,43 @@ class LocalBackendOptions(_Strict): # from the one measurement above. min_segment_area_m2: float = Field(default=1.0, ge=0) + @model_validator(mode="after") + def _slurm_is_declared(self) -> "LocalBackendOptions": + if self.dask != "slurm": + return self + missing = [ + name + for name in ( + "slurm_queue", + "slurm_cores", + "slurm_memory", + "slurm_walltime", + "n_workers", + ) + if getattr(self, name) is None + ] + if missing: + raise ValueError( + f"backend.local.dask = 'slurm' needs " + f"{_listed(['backend.local.' + name for name in missing])}. " + f"The queue, the cores, memory and walltime of a job and the " + f"number of jobs belong to a cluster, so none has a default." + ) + return self + + +def _listed(names: list[str]) -> str: + """a, b and c.""" + return names[0] if len(names) == 1 else ", ".join(names[:-1]) + " and " + names[-1] + class BigQueryBackendOptions(_Strict): - project: str = "compute-impactlab" - # Confirmed on cilresearch (2026-06-10): `temp_workspace` is the temp - # dataset that exists in `compute-impactlab` and is in the same location - # (US) as the GPW weight table. Earlier inspection of legacy scripts - # surfaced `workflow_scratch_tables` which is not present on this - # project; never create a dataset to "make it work". - temp_dataset: str = "temp_workspace" + # The billing project and the dataset temp tables go in, which has to + # be in the location of the weight tables. Facts of one cloud + # account, so neither has a default, and backend.kind = "bigquery" + # needs both. No dataset is ever created. + project: Optional[str] = Field(default=None, min_length=1) + temp_dataset: Optional[str] = Field(default=None, min_length=1) # 10 GB matches the confirmed worst-case s51 full-table scan of the GPW # population table (~6 GB) with headroom. The ST_CONTAINS join scans # the full GPW table regardless of how few regions are requested, so @@ -366,16 +408,29 @@ def _geometry_mode(self) -> "Config": return self @model_validator(mode="after") - def _bigquery_requires_staging_uri(self) -> "Config": - if ( - self.backend.kind == "bigquery" - and self.backend.bigquery.staging_uri is None - ): + def _bigquery_is_declared(self) -> "Config": + if self.backend.kind != "bigquery": + return self + missing = [ + f"backend.bigquery.{name}" + for name in ("project", "temp_dataset") + if getattr(self.backend.bigquery, name) is None + ] + if missing: + raise ValueError( + f"backend.kind = 'bigquery' needs {' and '.join(missing)}, the " + f"billing project and the dataset in the location of the " + f"weight tables that temp tables go in. They belong to a cloud " + f"account, so neither has a default." + ) + if self.backend.bigquery.staging_uri is None: raise ValueError( "backend.bigquery.staging_uri is required: a gs:// prefix the " "run may write geometry staging files to. It is a site fact " "with no defensible library default." ) + if self.grid.offset != "center": + raise ValueError(BIGQUERY_CENTRE_ONLY.format(offset=self.grid.offset)) return self @model_validator(mode="after") diff --git a/cil_regionalization/cross_backend_compare.py b/cil_regionalization/cross_backend_compare.py index 7d2aa42..c39e3bf 100644 --- a/cil_regionalization/cross_backend_compare.py +++ b/cil_regionalization/cross_backend_compare.py @@ -15,11 +15,6 @@ ST_INTERSECTION). The local intersection is planar shapely, which differs mostly in boundary cells. Population is a GPW raster sum locally and a GPW point sum in BigQuery, on the same pixel footprint. - -On the RCC, run it in this environment:: - - module load python - source activate /project/cil/home_dirs/rcc/envs/climate_data_aggregation/ """ from __future__ import annotations diff --git a/cil_regionalization/fetch.py b/cil_regionalization/fetch.py index 22b79b7..4d12a96 100644 --- a/cil_regionalization/fetch.py +++ b/cil_regionalization/fetch.py @@ -38,7 +38,7 @@ import urllib.request from dataclasses import dataclass from pathlib import Path -from typing import Any +from typing import Any, Mapping if sys.version_info >= (3, 11): @@ -364,12 +364,15 @@ def fetch_model_weights( base_url: str | None = None, cache_dir: str | Path | None = None, refresh: bool = False, + table_names: Mapping[str, str] | None = None, ): """The published climate model weights of ``rcp``, as - `read_model_weights` reads them, from the file + `read_model_weights` reads them with ``table_names``, from the file ``_SMME_weights.tsv`` of their Zenodo record. The download is checked against the md5 the record declares and cached with it, and - a cached copy that no longer matches raises.""" + a cached copy that no longer matches raises. The published tables + do not spell their rows as the trees spell the members, so until + they are rewritten every member but one needs its row declared.""" from cil_regionalization.model_weights import read_model_weights entry = RegistryEntry( @@ -386,7 +389,7 @@ def fetch_model_weights( f"the md5 their record declared. Fetch them again with " f"refresh=True." ) - return read_model_weights(path) + return read_model_weights(path, table_names=table_names) files = _record_files(entry) if name not in files: tables = sorted(k for k in files if k.endswith("_SMME_weights.tsv")) @@ -403,7 +406,7 @@ def fetch_model_weights( partial.replace(path) finally: partial.unlink(missing_ok=True) - return read_model_weights(path) + return read_model_weights(path, table_names=table_names) def list_cached(cache_dir: str | Path | None = None) -> list[dict[str, Any]]: diff --git a/cil_regionalization/legacy_compare.py b/cil_regionalization/legacy_compare.py index b5faeed..101285a 100644 --- a/cil_regionalization/legacy_compare.py +++ b/cil_regionalization/legacy_compare.py @@ -11,11 +11,6 @@ the same cell. A moved maximum-weight cell is the sign of a real spatial disagreement. The report describes the differences and is not a pass or fail check. - -On the RCC, run it in this environment:: - - module load python - source activate /project/cil/home_dirs/rcc/envs/climate_data_aggregation/ """ from __future__ import annotations diff --git a/cil_regionalization/legacy_export.py b/cil_regionalization/legacy_export.py index 72aa589..9c7c8c7 100644 --- a/cil_regionalization/legacy_export.py +++ b/cil_regionalization/legacy_export.py @@ -12,11 +12,6 @@ ``cropwt`` is NaN for a region with no cropland, the outcome of the ``fallback = "nan"`` policy, as in the legacy files. Downstream aggregation fills it per pixel from ``areawt``. - -On the RCC, run it in this environment:: - - module load python - source activate /project/cil/home_dirs/rcc/envs/climate_data_aggregation/ """ from __future__ import annotations diff --git a/cil_regionalization/model_weights.py b/cil_regionalization/model_weights.py index 53b7c5c..7c512ab 100644 --- a/cil_regionalization/model_weights.py +++ b/cil_regionalization/model_weights.py @@ -1,70 +1,141 @@ """Climate model weights, read once and recorded with the run. -A weights table is tab separated and has a ``model`` and a ``weight`` -column, as the SMME files do. A table name matches a member of a -projection tree after a ``*`` is dropped from the name, the -``surrogate_`` prefix is dropped from the member, and both are -lowercased. +A weights table has a ``model`` and a ``weight`` column, as the SMME +files do. A member of a projection tree takes the row whose name is +the member's own, letter for letter, or the row declared for it in +``table_names``. Nothing reads a name to decide what it means, so a +member with neither is refused. + +The published SMME tables do not pass as they stand. They name the +models in lower case, some with a trailing ``*``, and the surrogates +without the ``surrogate_`` prefix of the trees, so ``ACCESS1-0`` is +the row ``access1-0*`` and ``surrogate_GFDL-CM3_89`` the row +``gfdl-cm3_89``. Until the tables are rewritten with the members' +names, a run that reads them declares each member's row. """ from __future__ import annotations +import difflib import hashlib import io from collections import Counter -from dataclasses import dataclass +from dataclasses import dataclass, field from pathlib import Path -from typing import Iterable +from typing import Iterable, Mapping, Optional import numpy as np import pandas as pd -def _member_key(member: str) -> str: - return member.replace("surrogate_", "").lower() +def _listed(items: list[str], quote: bool = True) -> str: + """'a', 'b' and 'c'.""" + shown = [repr(item) if quote else item for item in items] + return shown[0] if len(shown) == 1 else ", ".join(shown[:-1]) + " and " + shown[-1] @dataclass(frozen=True) class ModelWeights: """The rows of a weights table, in file order, with the SHA256 of the bytes they were parsed from. ``names`` are as written in the - file and ``keys`` are what a member is matched on.""" + file, and ``table_names`` the rows declared for members whose names + are not those of their rows.""" path: str sha256: str names: tuple[str, ...] - keys: tuple[str, ...] weights: tuple[float, ...] + table_names: Mapping[str, str] = field(default_factory=dict) def _row_of(self, member: str) -> int | None: - key = _member_key(member) - return self.keys.index(key) if key in self.keys else None + name = self.table_names.get(member, member) + return self.names.index(name) if name in self.names else None + + def _closest(self, name: str) -> Optional[str]: + # for the message only, nothing is matched by it + if not self.names: + return None + folded = name.casefold() + return max( + self.names, + key=lambda row: difflib.SequenceMatcher( + None, folded, row.casefold() + ).ratio(), + ) def missing(self, members: Iterable[str]) -> list[str]: """The members that have no row in the table, sorted.""" return sorted(m for m in set(members) if self._row_of(m) is None) + def check(self, members: Iterable[str]) -> None: + """Raises if a member has no row in the table, naming the row + each one comes closest to, or if two members take one row.""" + members = list(dict.fromkeys(members)) + absent = self.missing(members) + if absent: + raise ValueError(self._unmatched(absent)) + taken: dict[int, list[str]] = {} + for member in members: + taken.setdefault(self._row_of(member), []).append(member) + shared = [(row, names) for row, names in taken.items() if len(names) > 1] + if shared: + row, names = shared[0] + more = f", and {len(shared) - 1} more rows" if len(shared) > 1 else "" + raise ValueError( + f"The model weights file {self.path} would give one row to " + f"more than one member, the row {self.names[row]!r} to " + f"{_listed(names)}{more}. Each member needs a row of its own." + ) + + def _unmatched(self, absent: list[str]) -> str: + shown = [] + for member in absent[:5]: + declared = self.table_names.get(member) + closest = self._closest(member if declared is None else declared) + near = ( + "the table has no rows" + if closest is None + else f"closest row {closest!r}" + ) + shown.append( + f"{member!r} ({near})" + if declared is None + else f"{member!r} declared as {declared!r} ({near})" + ) + if len(absent) > 5: + shown.append(f"{len(absent) - 5} more") + first = absent[0] + example = self._closest(self.table_names.get(first, first)) or "its row" + counted = "1 member has" if len(absent) == 1 else f"{len(absent)} members have" + return ( + f"{counted} no row in the model weights file " + f"{self.path}: {_listed(shown, quote=False)}. A member takes the " + f"row of its own name, letter for letter, or the row declared for " + f"it. Write the members' names into the table, or declare each " + f"member's row in stats.model_weight_names, or in table_names of " + f'read_model_weights, as in "{first}" = "{example}".' + ) + def weight_of(self, member: str) -> float: """The weight of one member. Raises if it has no row.""" row = self._row_of(member) if row is None: - raise ValueError( - f"{member!r} has no row in the model weights file {self.path}" - ) + raise ValueError(self._unmatched([member])) return self.weights[row] def attach(self, members: pd.Series) -> pd.Series: """The weight of each row's member, as float64 on the index of - ``members``. Raises if a member has no row in the table, or a - row names no member.""" + ``members``. Raises if a member has no row in the table, if two + members take one row, or if a row names no member.""" codes, distinct = pd.factorize(members) - absent = self.missing(distinct) - if absent or (codes < 0).any(): + if (codes < 0).any(): + n = int((codes < 0).sum()) raise ValueError( - f"{len(absent)} members have no row in the model weights " - f"file {self.path} (first: {absent[:5]}), and " - f"{int((codes < 0).sum())} rows name no member" + f"{n} {'row names' if n == 1 else 'rows name'} no member, so " + f"{'it takes' if n == 1 else 'they take'} no weight from the " + f"model weights file {self.path}" ) + self.check(distinct) per_member = np.array([self.weight_of(m) for m in distinct], dtype=np.float64) return pd.Series(per_member[codes], index=members.index, name="model_weight") @@ -72,15 +143,12 @@ def record(self, members: Iterable[str]) -> dict: """The manifest entry of a run, given the member of each leaf that was pooled. Its 'members' holds each member with its table row, its weight and its number of leaves, and 'unmatched_rows' - the weight of every row no member matched, so the two together - cover the whole table. Raises if a member has no row.""" + the weight of every row no member took, so the two together + cover the whole table. 'table_names' are the rows declared, and + 'table_names_unused' those declared for a member the run does + not have. Raises as `check` does.""" counts = Counter(members) - absent = self.missing(counts) - if absent: - raise ValueError( - f"{len(absent)} members have no row in the model weights " - f"file {self.path} (first: {absent[:5]})" - ) + self.check(counts) attached = { member: { "row": self.names[self._row_of(member)], @@ -93,6 +161,12 @@ def record(self, members: Iterable[str]) -> dict: return { "path": self.path, "sha256": self.sha256, + "table_names": dict(self.table_names), + "table_names_unused": { + member: row + for member, row in self.table_names.items() + if member not in counts + }, "members": attached, "unmatched_rows": { name: weight @@ -102,32 +176,57 @@ def record(self, members: Iterable[str]) -> dict: } -def read_model_weights(path: str | Path) -> ModelWeights: +def read_model_weights( + path: str | Path, + *, + table_names: Optional[Mapping[str, str]] = None, + sep: str = "\t", +) -> ModelWeights: """Read a weights table. The file is read once, and the hash is of - the bytes the rows were parsed from. Raises if two rows match the - same member.""" + the bytes the rows were parsed from. ``table_names`` declares the + row of each member whose name is not that of its row, member name to + table name, and is checked where a member takes its row. The + published SMME tables need it until they carry the members' names. + Raises if a name is in the table twice, or if two members are + declared to one row.""" raw = Path(path).read_bytes() - table = pd.read_csv(io.BytesIO(raw), sep="\t") + table = pd.read_csv(io.BytesIO(raw), sep=sep) if not {"model", "weight"}.issubset(table.columns): raise ValueError( f"model weights file {path} needs 'model' and 'weight' " f"columns; found {sorted(table.columns)}" ) - keys = table["model"].str.replace("*", "", regex=False).str.lower() - repeated = keys[keys.duplicated(keep=False)] - if len(repeated): - groups = [ - table.loc[repeated.index[repeated == key], "model"].tolist() - for key in repeated.unique() - ] + names = table["model"].astype(str) + repeated = sorted(names[names.duplicated()].unique()) + if repeated: + raise ValueError( + f"model weights file {path} has the " + f"{'row' if len(repeated) == 1 else 'rows'} {_listed(repeated)} more " + f"than once. Each model needs exactly one row." + ) + declared = dict(table_names or {}) + for member, row in declared.items(): + if not isinstance(member, str) or not isinstance(row, str) or not row: + raise ValueError( + f"table_names maps a member name to a table name, both " + f"strings; got {member!r} = {row!r}" + ) + rows: dict[str, list[str]] = {} + for member, row in declared.items(): + rows.setdefault(row, []).append(member) + shared = {row: members for row, members in rows.items() if len(members) > 1} + if shared: + row, members = next(iter(shared.items())) + more = f", and {len(shared) - 1} more rows" if len(shared) > 1 else "" raise ValueError( - f"model weights file {path} has rows that match the same " - f"member: {groups}. Each model needs exactly one row." + f"table_names declares one row of the model weights file {path} " + f"for more than one member, the row {row!r} for " + f"{_listed(members)}{more}. Each member needs a row of its own." ) return ModelWeights( path=str(path), sha256=hashlib.sha256(raw).hexdigest(), - names=tuple(table["model"]), - keys=tuple(keys), + names=tuple(names), weights=tuple(float(w) for w in table["weight"]), + table_names=declared, ) diff --git a/cil_regionalization/pipelines/montecarlo.py b/cil_regionalization/pipelines/montecarlo.py index e9f6085..6a2f3ea 100644 --- a/cil_regionalization/pipelines/montecarlo.py +++ b/cil_regionalization/pipelines/montecarlo.py @@ -116,6 +116,7 @@ from cil_regionalization.config import SourceUnitPolicies, _Strict from cil_regionalization.manifest import collect_package_versions from cil_regionalization.model_weights import ModelWeights, read_model_weights +from cil_regionalization.model_weights import _listed as _quoted_list from cil_regionalization.reduce import ( LeafRequest, ReduceConfig, @@ -124,7 +125,7 @@ ) from cil_regionalization.stats import ( _quantile_label, - _warn_if_unweighted_gcm, + _warn_if_unweighted_models, _window_label, check_quantile_method, check_summation, @@ -393,6 +394,12 @@ class StatsConfig(_Strict): years: Optional[tuple[int, int]] = None model_weights: Optional[str] = None model_weight_level: Optional[str] = None + # The row of each member of the weight level whose name is not that + # of its row, member name to table name, written out. A member takes + # the row of its own name otherwise, and nothing reads a name to + # decide what it means. The published SMME tables need it until they + # carry the members' names. The manifest records it. + model_weight_names: dict[str, str] = Field(default_factory=dict) # The sample dimensions of the climate model, such as ["gcm"], which # the count of models beside the count of samples is taken over. # Required wherever the statistics carry their counts. @@ -453,6 +460,31 @@ def _weights_come_together(self) -> "StatsConfig": "together: the file says what the weights are, the level " "says which sample dimension they attach to" ) + if self.model_weight_names and self.model_weights is None: + raise ValueError( + "stats.model_weight_names declares rows of a model weights " + "file, and stats.model_weights names none" + ) + empty = [m for m, row in self.model_weight_names.items() if not m or not row] + if empty: + raise ValueError( + f"stats.model_weight_names maps a member name to a table name, " + f"and {empty[0]!r} = {self.model_weight_names[empty[0]]!r} " + f"leaves one empty" + ) + rows: dict[str, list[str]] = {} + for member, row in self.model_weight_names.items(): + rows.setdefault(row, []).append(member) + shared = [(row, members) for row, members in rows.items() if len(members) > 1] + if shared: + row, members = shared[0] + more = f", and {len(shared) - 1} more rows" if len(shared) > 1 else "" + raise ValueError( + f"stats.model_weight_names declares one row for more than one " + f"member, the row {row!r} for " + f"{_quoted_list(members)}{more}. Each member needs " + f"a row of its own." + ) # "linear" with model weights is refused here, when the config is # read, and not after the leaves check_quantile_method( @@ -684,6 +716,26 @@ def _resolved(value: str, base: Path) -> str: return str((base / value).resolve()) +def load_model_weight_names(path: str | Path) -> dict[str, str]: + """The ``[stats.model_weight_names]`` table of a TOML file, member + name to table name, so that a run and a script can declare the same + rows. Raises if the file has no such table, or a name is not a + string.""" + p = Path(path).resolve() + with p.open("rb") as f: + data = tomllib.load(f) + names = data.get("stats", {}).get("model_weight_names") + if not isinstance(names, dict): + raise ValueError(f"{p} has no [stats.model_weight_names] table") + bad = [(k, v) for k, v in names.items() if not isinstance(v, str) or not v] + if bad: + raise ValueError( + f"{p} maps a member name to a table name, both strings; got " + f"{bad[0][0]!r} = {bad[0][1]!r}" + ) + return dict(names) + + def load_warming_levels(path: str | Path) -> WarmingLevelsConfig: """The ``[stats.warming_levels]`` table of a TOML file, validated, so that a run and a test can read the same settings. A relative @@ -1055,7 +1107,7 @@ def collect(outcome: dict) -> None: include_mean=cfg.stats.include_mean, weight_col=weight_col, include_n_members=cfg.stats.include_n_members, - model_dims=cfg.stats.model_dims if cfg.stats.include_n_members else None, + model_dims=cfg.stats.model_dims, quantile_method=cfg.stats.quantile_method, summation=cfg.stats.summation, ) @@ -1123,6 +1175,7 @@ def collect(outcome: dict) -> None: "reduced": str(reduced_path) if reduced_path else None, "model_weights": cfg.stats.model_weights, "model_weight_level": cfg.stats.model_weight_level, + "model_weight_names": cfg.stats.model_weight_names, "model_dims": cfg.stats.model_dims, "model_weights_record": _model_weights_record( cfg, model_weights, [o["leaf"] for o in outcomes] @@ -1274,17 +1327,12 @@ def _model_weights(cfg: MonteCarloPipelineConfig) -> Optional[ModelWeights]: # The file is read here and nowhere else. The workers get these # rows, so a file edited during the run cannot give different # leaves different weights. - model_weights = read_model_weights(cfg.stats.model_weights) + model_weights = read_model_weights( + cfg.stats.model_weights, table_names=cfg.stats.model_weight_names + ) # fail before the run, not after it: every declared value of the - # weight level must have a row in the table - declared = cfg.tree.expect[cfg.stats.model_weight_level] - unmatched = model_weights.missing(declared) - if unmatched: - raise ValueError( - f"{len(unmatched)} values of " - f"{cfg.stats.model_weight_level!r} have no row in the model " - f"weights file (first: {unmatched[:5]})" - ) + # weight level must have a row in the table, and one of its own + model_weights.check(cfg.tree.expect[cfg.stats.model_weight_level]) return model_weights @@ -2014,8 +2062,8 @@ def _run_reduce( _verify_leaves(leaves_dir, entries, cfg.run.n_workers) if warming is None: # the members at a warming level count equally by design - _warn_if_unweighted_gcm( - list(cfg.stats.sample_dims), "model_weight" if model_weights else None + _warn_if_unweighted_models( + cfg.stats.model_dims, model_weights is not None, "stats.model_weights" ) _log_memory("reduce start") stats, report = backend.run(request) @@ -2102,6 +2150,7 @@ def _run_reduce( "reduced": None, "model_weights": cfg.stats.model_weights, "model_weight_level": cfg.stats.model_weight_level, + "model_weight_names": cfg.stats.model_weight_names, "model_dims": cfg.stats.model_dims, "model_weights_record": _model_weights_record( cfg, model_weights, [entry["leaf"] for entry in entries] diff --git a/cil_regionalization/stats.py b/cil_regionalization/stats.py index 49c2264..95080ac 100644 --- a/cil_regionalization/stats.py +++ b/cil_regionalization/stats.py @@ -49,7 +49,7 @@ import math import re import warnings -from typing import NamedTuple, Sequence +from typing import NamedTuple, Optional, Sequence import numpy as np import pandas as pd @@ -66,13 +66,19 @@ class UnweightedModelWeightsWarning(UserWarning): """ -def _warn_if_unweighted_gcm(sample_dims: list[str], weight_col: str | None) -> None: - if weight_col is None and "gcm" in sample_dims: +def _warn_if_unweighted_models( + model_dims: Optional[Sequence[str]], + weighted: bool, + setting: str = "weight_col", +) -> None: + """Warns when the climate model is named and pooled with no weights. + ``setting`` is what gives the weights where the call comes from.""" + if model_dims and not weighted: warnings.warn( - "sample_dims includes 'gcm' and weight_col is not set. This " - "weights every climate model equally, which is not the " - "convention Climate Impact Lab projections use. See 'Climate " - "model weights' in the README.", + f"model_dims {list(model_dims)} names the climate model and " + f"{setting} is not set, so every climate model counts the same. " + f"Set {setting} to weight them, or filter " + f"UnweightedModelWeightsWarning where equal weights are meant.", UnweightedModelWeightsWarning, stacklevel=3, ) @@ -177,11 +183,13 @@ def summarize_samples( ``time_col``. ``weight_col`` names a per-member weight, constant across the - member's time rows. Weights must be finite and non-negative, and a - zero weight drops the member. Weights are not renormalized within a + member's time rows. Weights must be finite and non-negative. A zero + weight drops the member before the mean, the counts and the + quantiles, under every method, so no quantile returns the value of + a member that weighs nothing. Weights are not renormalized within a model, so in an unbalanced sample a model's total weight grows with - how often it appears. Leaving ``weight_col`` unset with a ``gcm`` - sample dimension warns with `UnweightedModelWeightsWarning`. + how often it appears. Leaving ``weight_col`` unset with + ``model_dims`` given warns with `UnweightedModelWeightsWarning`. Returns a long frame with the identity columns, 'statistic' and ``value_col``. Labels are 'mean' and 'qNN' in percent ('q05', 'q95', @@ -234,7 +242,7 @@ def summarize_samples( raise ValueError(f"data is missing required column {col!r}") if weight_col is not None: _check_weight_column(data, weight_col, sample_dims, [time_col, value_col]) - _warn_if_unweighted_gcm(sample_dims, weight_col) + _warn_if_unweighted_models(model_dims, weight_col is not None) quantiles = list(quantiles) if not include_mean and not quantiles: @@ -572,7 +580,9 @@ def by_group(result: np.ndarray) -> pd.Series: for key_tuple, start, end in zip(key_tuples, starts, ends): values = all_values[start:end] weights = all_weights[start:end] - keep = ~np.isnan(values) + # a member with weight zero is not in the sample, so no method + # can return its value + keep = ~np.isnan(values) & (weights > 0) values, weights = values[keep], weights[keep] if len(values) == 0 and weight_col is None: # no member has a value, so the group has no statistic, as @@ -589,7 +599,7 @@ def by_group(result: np.ndarray) -> pd.Series: ", so no member carries any weight", ) if count_members: - member_counts.append(int(np.count_nonzero(weights))) + member_counts.append(len(values)) if include_mean: if summation == "exact": # each product is rounded once, whatever the order, and @@ -602,11 +612,7 @@ def by_group(result: np.ndarray) -> pd.Series: rows["mean"].append((*key_tuple, mean)) exact = summation == "exact" if quantile_method == "inverted_cdf": - # a member with weight zero is not in the sample - positive = weights > 0 - picked = _inverted_cdf_quantiles( - values[positive], weights[positive], quantiles, exact=exact - ) + picked = _inverted_cdf_quantiles(values, weights, quantiles, exact=exact) else: picked = _step_quantiles(values, weights, quantiles, exact=exact) for q, value in zip(quantiles, picked): @@ -933,30 +939,28 @@ def _check_counts( model_dims: Sequence[str] | None, sample_dims: Sequence[str], ) -> list[str] | None: - """``model_dims`` as a list, checked against the request for counts. - Raises if counts are asked for without it, or it without them, or - it names a column that is not a sample dimension, or ``data`` - already has a column of a count.""" - if not include_n_members: - if model_dims is not None: + """``model_dims`` as a list, or None. It names the climate model, for + its count and for the warning when models are pooled without + weights. Raises if counts are asked for without it, if it names a + column that is not a sample dimension, or if ``data`` already has a + column of a count.""" + if model_dims is not None: + model_dims = list(model_dims) + stray = [d for d in model_dims if d not in sample_dims] + if stray: raise ValueError( - "model_dims names the columns of the climate model for its " - "count, which only include_n_members writes" + f"model_dims {stray} are not among sample_dims " + f"{list(sample_dims)}; a climate model is counted among the " + f"members it pools" ) - return None - if model_dims is None or not list(model_dims): + if not include_n_members: + return model_dims or None + if not model_dims: raise ValueError( "include_n_members counts the samples and the climate models " "behind each statistic, so model_dims has to name the sample " "dimensions of the climate model, such as ['gcm']" ) - model_dims = list(model_dims) - stray = [d for d in model_dims if d not in sample_dims] - if stray: - raise ValueError( - f"model_dims {stray} are not among sample_dims {list(sample_dims)}; " - f"a climate model is counted among the members it pools" - ) for column in (_N_MEMBERS_COLUMN, _N_MODELS_COLUMN): if column in data.columns: raise ValueError( @@ -1203,7 +1207,7 @@ def pooled_statistics( raise ValueError(f"data is missing required column {col!r}") if weight_col is not None: _check_weight_column(data, weight_col, sample_dims, [value_col]) - _warn_if_unweighted_gcm(sample_dims, weight_col) + _warn_if_unweighted_models(model_dims, weight_col is not None) quantiles = list(quantiles) if not include_mean and not quantiles: diff --git a/docs/reference.md b/docs/reference.md index b196e3a..20308ff 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -399,11 +399,13 @@ columns pass through. ``window`` is an inclusive (start, end) pair on ``time_col``. ``weight_col`` names a per-member weight, constant across the -member's time rows. Weights must be finite and non-negative, and a -zero weight drops the member. Weights are not renormalized within a +member's time rows. Weights must be finite and non-negative. A zero +weight drops the member before the mean, the counts and the +quantiles, under every method, so no quantile returns the value of +a member that weighs nothing. Weights are not renormalized within a model, so in an unbalanced sample a model's total weight grows with -how often it appears. Leaving ``weight_col`` unset with a ``gcm`` -sample dimension warns with `UnweightedModelWeightsWarning`. +how often it appears. Leaving ``weight_col`` unset with +``model_dims`` given warns with `UnweightedModelWeightsWarning`. Returns a long frame with the identity columns, 'statistic' and ``value_col``. Labels are 'mean' and 'qNN' in percent ('q05', 'q95', @@ -527,12 +529,21 @@ and otherwise the smallest or largest point mass. ### `read_model_weights` ```python -read_model_weights(path: str | Path) -> ModelWeights +read_model_weights( + path: str | Path, + *, + table_names: Optional[Mapping[str, str]] = None, + sep: str = '\t', +) -> ModelWeights ``` Read a weights table. The file is read once, and the hash is of -the bytes the rows were parsed from. Raises if two rows match the -same member. +the bytes the rows were parsed from. ``table_names`` declares the +row of each member whose name is not that of its row, member name to +table name, and is checked where a member takes its row. The +published SMME tables need it until they carry the members' names. +Raises if a name is in the table twice, or if two members are +declared to one row. ### `fetch_model_weights` @@ -544,14 +555,17 @@ fetch_model_weights( base_url: str | None = None, cache_dir: str | Path | None = None, refresh: bool = False, + table_names: Mapping[str, str] | None = None, ) ``` The published climate model weights of ``rcp``, as -`read_model_weights` reads them, from the file +`read_model_weights` reads them with ``table_names``, from the file ``_SMME_weights.tsv`` of their Zenodo record. The download is checked against the md5 the record declares and cached with it, and -a cached copy that no longer matches raises. +a cached copy that no longer matches raises. The published tables +do not spell their rows as the trees spell the members, so until +they are rewritten every member but one needs its row declared. ### `ModelWeights` @@ -560,13 +574,14 @@ class ModelWeights: path: str sha256: str names: tuple[str, ...] - keys: tuple[str, ...] weights: tuple[float, ...] + table_names: Mapping[str, str] = field(default_factory=dict) ``` The rows of a weights table, in file order, with the SHA256 of the bytes they were parsed from. ``names`` are as written in the -file and ``keys`` are what a member is matched on. +file, and ``table_names`` the rows declared for members whose names +are not those of their rows. #### `ModelWeights.missing` @@ -576,6 +591,15 @@ ModelWeights.missing(members: Iterable[str]) -> list[str] The members that have no row in the table, sorted. +#### `ModelWeights.check` + +```python +ModelWeights.check(members: Iterable[str]) -> None +``` + +Raises if a member has no row in the table, naming the row +each one comes closest to, or if two members take one row. + #### `ModelWeights.weight_of` ```python @@ -591,8 +615,8 @@ ModelWeights.attach(members: pd.Series) -> pd.Series ``` The weight of each row's member, as float64 on the index of -``members``. Raises if a member has no row in the table, or a -row names no member. +``members``. Raises if a member has no row in the table, if two +members take one row, or if a row names no member. #### `ModelWeights.record` @@ -603,8 +627,10 @@ ModelWeights.record(members: Iterable[str]) -> dict The manifest entry of a run, given the member of each leaf that was pooled. Its 'members' holds each member with its table row, its weight and its number of leaves, and 'unmatched_rows' -the weight of every row no member matched, so the two together -cover the whole table. Raises if a member has no row. +the weight of every row no member took, so the two together +cover the whole table. 'table_names' are the rows declared, and +'table_names_unused' those declared for a member the run does +not have. Raises as `check` does. ### `regroup` @@ -1196,8 +1222,10 @@ Can be left out. | `dask` | "off" or "local" or "slurm" | "off" | | `n_workers` | int, at least 1 | not set | | `threads_per_worker` | int, at least 1 | not set | -| `slurm_queue` | str | not set | -| `slurm_walltime` | str | not set | +| `slurm_queue` | str, not empty | not set | +| `slurm_cores` | int, at least 1 | not set | +| `slurm_memory` | str, not empty | not set | +| `slurm_walltime` | str, not empty | not set | | `min_segment_area_m2` | float, at least 0 | 1.0 | ### `[backend.bigquery]` @@ -1206,8 +1234,8 @@ Can be left out. | key | type | default | | --- | --- | --- | -| `project` | str | "compute-impactlab" | -| `temp_dataset` | str | "temp_workspace" | +| `project` | str, not empty | not set | +| `temp_dataset` | str, not empty | not set | | `dry_run_byte_ceiling` | int, at least 0 | 10000000000 | | `staging_uri` | str | not set | | `cache_temp_tables` | bool | false | @@ -1331,6 +1359,7 @@ run, or a run of the reduce stage over leaves that were kept. | `years` | tuple[int, int] | not set | | `model_weights` | str | not set | | `model_weight_level` | str | not set | +| `model_weight_names` | dict[str, str] | {} | | `model_dims` | list[str] | not set | ### `[stats.warming_levels]` diff --git a/examples/aggregation/run_example.py b/examples/aggregation/run_example.py index 00fc32a..9c34d64 100644 --- a/examples/aggregation/run_example.py +++ b/examples/aggregation/run_example.py @@ -45,7 +45,9 @@ sys.path.insert(0, str(_HERE.parents[1])) from cil_regionalization.apply import WeightsArtifact, apply_weights +from cil_regionalization.model_weights import read_model_weights from cil_regionalization.netcdf_io import read_netcdf_leaf +from cil_regionalization.pipelines.montecarlo import load_model_weight_names from cil_regionalization.stats import summarize_samples DATA = _HERE / "data" @@ -252,17 +254,17 @@ def main(argv: list[str] | None = None) -> int: # happened first, above; the window mean and pooled statistics come # last. The 33 climate models are the draws, each with its SMME # weight. - smme = pd.read_csv(DATA / "smme_weights_rcp85.csv") - smme_weight = dict( - zip(smme["model"].str.replace("*", "", regex=False).str.lower(), smme["weight"]) + # Each model takes the row declared for it, since the table does not + # spell its rows as the trees spell the models, and one with no row + # is refused. + smme = read_model_weights( + DATA / "smme_weights_rcp85.csv", + sep=",", + table_names=load_model_weight_names( + _HERE.parent / "model_weights" / "smme_rcp85_names.toml" + ), ) - damages["weight"] = ( - damages["gcm"] - .str.replace("surrogate_", "", regex=False) - .str.lower() - .map(smme_weight) - ) - assert damages["weight"].notna().all() + damages["weight"] = smme.attach(damages["gcm"]) stats = summarize_samples( damages, sample_dims=["gcm"], diff --git a/examples/energy_percentiles/prepare_data.py b/examples/energy_percentiles/prepare_data.py index abfdcd2..0084147 100644 --- a/examples/energy_percentiles/prepare_data.py +++ b/examples/energy_percentiles/prepare_data.py @@ -48,6 +48,7 @@ import cil_regionalization as cilreg from cil_regionalization.fetch import default_cache_dir, load_registry +from cil_regionalization.pipelines.montecarlo import load_model_weight_names import data @@ -64,6 +65,13 @@ f"/project/cil/gcp/climate/BCSD/SMME/SMME-weights/{data.RCP}_SMME_weights.tsv" ) IMPACT_MAP = Path("/project/cil/gcp/impact_map/energy") +# the row of each member in the SMME table, written out, until the table +# carries the members' names +SMME_NAMES = ( + Path(__file__).resolve().parents[1] + / "model_weights" + / f"smme_{data.RCP}_names.toml" +) TARGETS = Path("/project/cil/gcp/impact_map_inputs/targets/gadm20") IR_SHAPES = Path( "/project/cil/gcp/regions/world-combo-201710/agglomerated-world-new.shp" @@ -332,9 +340,8 @@ def inputs(): price = pd.read_parquet(data.PRICE).pivot( index="year", columns="country", values="price" ) - smme = pd.read_csv(data.SMME) - smme = dict( - zip(smme["model"].str.replace("*", "", regex=False).str.lower(), smme["weight"]) + smme = cilreg.read_model_weights( + data.SMME, sep=",", table_names=load_model_weight_names(SMME_NAMES) ) return weights, pop, price, smme @@ -394,7 +401,7 @@ def compute() -> pd.DataFrame: for (level, window), part in long.groupby(["level", "window"]): part = part.set_index(KEYS[level] + ["gcm"]) M, V = part["mean"].unstack("gcm"), part["variance"].unstack("gcm") - w = np.array([smme[g.replace("surrogate_", "").lower()] for g in M.columns]) + w = np.array([smme.weight_of(g) for g in M.columns]) res = pd.DataFrame( cilreg.mixture_quantile( w, M.to_numpy(), V.to_numpy(), list(QUANTILES.values()) @@ -411,7 +418,7 @@ def compute_map(regions) -> dict: """The map's means for Chile and Austria, from the median leaves only.""" weights, pop, price, smme = inputs() gcms = data.gcms() - w = np.array([smme[g.replace("surrogate_", "").lower()] for g in gcms]) + w = np.array([smme.weight_of(g) for g in gcms]) mixed = sum(wi * median_effect(g, regions) for wi, g in zip(w, gcms)) / w.sum() valued = ( mixed diff --git a/examples/france/france.py b/examples/france/france.py index 588a1ac..8184678 100644 --- a/examples/france/france.py +++ b/examples/france/france.py @@ -828,18 +828,29 @@ def _(mo): The projections weight each climate model by the SMME weights, which give the 21 models and the 12 surrogates their share of the distribution of warming. `read_model_weights` reads the table and - `attach` gives every draw the weight of its model. A surrogate is - named `surrogate_GFDL-CM3_89` in the tree and `gfdl-cm3_89` in the - table, and a model can carry a `*` in the table, and `attach` matches - them. Without weights every draw counts the same. + `attach` gives every draw the weight of its model. A member takes the + row of its own name, letter for letter, or the row declared for it. + The published table spells its rows otherwise, `gfdl-cm3_89` for the + tree's `surrogate_GFDL-CM3_89` and `miroc5*` for `MIROC5`, so the rows + are declared, member name to table name, in + `examples/model_weights/smme_rcp85_names.toml` until the table carries + the members' names. Without weights every draw counts the same. """ ) return @app.cell -def _(DATA, STATISTICS, cilreg, members, pd, plt, warnings): - model_weights = cilreg.read_model_weights(DATA / "smme" / "rcp85_SMME_weights.tsv") +def _(DATA, HERE, STATISTICS, cilreg, members, pd, plt, warnings): + from cil_regionalization.pipelines.montecarlo import load_model_weight_names + + # the row of each member in the published table, written out + SMME_NAMES = load_model_weight_names( + HERE.parent / "model_weights" / "smme_rcp85_names.toml" + ) + model_weights = cilreg.read_model_weights( + DATA / "smme" / "rcp85_SMME_weights.tsv", table_names=SMME_NAMES + ) _weighted = members.assign(weight=model_weights.attach(members["gcm"])) _options = dict( sample_dims=["batch", "gcm"], @@ -865,7 +876,7 @@ def _(DATA, STATISTICS, cilreg, members, pd, plt, warnings): _ax.set_xlabel("percent moved by the model weights, across departments") _ax.legend() _fig - return (model_weights,) + return SMME_NAMES, model_weights @app.cell @@ -999,7 +1010,17 @@ def pipeline_config(name, *, tree, data, stats, output, reduce=True): @app.cell -def _(DATA, OUT, cilreg_cli, mo, pipeline_config, relative, shown, tree_section): +def _( + DATA, + OUT, + SMME_NAMES, + cilreg_cli, + mo, + pipeline_config, + relative, + shown, + tree_section, +): _deaths = 'format = "parquet"\nvalue_col = "deaths"\nkind = "extensive"\nversion = "world-combo-201710"\n' _stats = ( 'sample_dims = ["batch", "gcm"]\nmodel_dims = ["gcm"]\ntime_col = "year"\nquantiles = [0.05, 0.5, 0.95]\n' @@ -1009,6 +1030,10 @@ def _(DATA, OUT, cilreg_cli, mo, pipeline_config, relative, shown, tree_section) f'model_weights = "{relative(DATA / "smme" / "rcp85_SMME_weights.tsv", OUT / "configs")}"\n' 'model_weight_level = "gcm"\n' ) + # a table of stats, so after every key of it + _names = "\n[stats.model_weight_names]\n" + "".join( + f'"{_member}" = "{_row}"\n' for _member, _row in SMME_NAMES.items() + ) aggregate_deaths = pipeline_config( "deaths_aggregate", tree=tree_section( @@ -1027,7 +1052,7 @@ def _(DATA, OUT, cilreg_cli, mo, pipeline_config, relative, shown, tree_section) f"deaths_{_name}", tree=_rcp85, data=_deaths, - stats=_stats + _weights + _time, + stats=_stats + _weights + _time + _names, output=f'stem = "deaths_{_name}"\nleaves_stem = "deaths"\n', ) for _name, _time in { diff --git a/examples/france/synthetic_data.py b/examples/france/synthetic_data.py index 77626c3..cceb4f2 100644 --- a/examples/france/synthetic_data.py +++ b/examples/france/synthetic_data.py @@ -170,9 +170,10 @@ def _write_tree(data: Path, hierids: list[str]) -> None: def _write_smme(data: Path) -> None: (data / "smme").mkdir(parents=True, exist_ok=True) rows = { + # spelt as the published tables spell these rows "rcp85": [ ("ccsm4", 0.3), - ("gfdl-cm3", 0.2), + ("gfdl-cm3*", 0.2), ("miroc5*", 0.4), ("gfdl-cm3_89", 0.1), ], diff --git a/examples/model_weights/README.md b/examples/model_weights/README.md new file mode 100644 index 0000000..ea572d5 --- /dev/null +++ b/examples/model_weights/README.md @@ -0,0 +1,47 @@ +# Declared rows of the published SMME tables + +The two pair files here are a bridge, not part of the library. The +library matches a member of a projection tree to a row of a model +weights table by its exact name, or by the row declared for it, and +refuses a member with neither. These files declare the rows because +the published SMME tables (Zenodo record 22003542) spell the models +differently from the trees. They go away when those tables are +rewritten with the trees' names. The pairs that real runs use belong +beside the tables, in the recipes repository, not in this repository's +examples. + +## Why the published tables need them + +The published SMME tables do not pass as they stand. They name the +models in lower case, some with a trailing `*`, and the surrogates +without the `surrogate_` prefix of the trees, so `ACCESS1-0` is the row +`access1-0*` and `surrogate_GFDL-CM3_89` the row `gfdl-cm3_89`. Of the +32 members under rcp45 and the 33 under rcp85, only `bcc-csm1-1` is +spelt the same on both sides. Until the tables are rewritten, a run +that reads them declares the row of each member. + +## The files + +Each holds the `[stats.model_weight_names]` block of one rcp, member +name to table name, for every member that needs one. + +- `smme_rcp45_names.toml`, 31 pairs for `rcp45_SMME_weights.tsv`. +- `smme_rcp85_names.toml`, 32 pairs for `rcp85_SMME_weights.tsv`. + +A pipeline config takes the block as it is. A script passes it to +`read_model_weights` or `fetch_model_weights` as `table_names`, read +with `load_model_weight_names`: + +```python +from cil_regionalization.pipelines.montecarlo import load_model_weight_names + +names = load_model_weight_names("examples/model_weights/smme_rcp85_names.toml") +weights = cilreg.fetch_model_weights("rcp85", table_names=names) +``` + +The members are those the configs under `examples/montecarlo/runs` +declare for each rcp. Each was paired once with the row the library +used to match it to, by dropping `surrogate_` and `*` and lowercasing +both sides. The pairs are written out so that nothing reads a name to +decide what it means. Every member has one row, and every row of the +two tables is the row of one member. diff --git a/examples/model_weights/smme_rcp45_names.toml b/examples/model_weights/smme_rcp45_names.toml new file mode 100644 index 0000000..184d20b --- /dev/null +++ b/examples/model_weights/smme_rcp45_names.toml @@ -0,0 +1,38 @@ +# The row of each member of the projection trees in rcp45_SMME_weights.tsv +# of Zenodo record 22003542, written out for stats.model_weight_names until +# the table carries the members' names. README.md beside this file says how +# the pairs were made. bcc-csm1-1 is spelt the same on both sides and +# needs no entry. + +[stats.model_weight_names] +"ACCESS1-0" = "access1-0*" +"BNU-ESM" = "bnu-esm*" +"CanESM2" = "canesm2" +"CCSM4" = "ccsm4" +"CESM1-BGC" = "cesm1-bgc*" +"CNRM-CM5" = "cnrm-cm5" +"CSIRO-Mk3-6-0" = "csiro-mk3-6-0" +"GFDL-CM3" = "gfdl-cm3" +"GFDL-ESM2G" = "gfdl-esm2g" +"GFDL-ESM2M" = "gfdl-esm2m" +"inmcm4" = "inmcm4*" +"IPSL-CM5A-LR" = "ipsl-cm5a-lr" +"IPSL-CM5A-MR" = "ipsl-cm5a-mr" +"MIROC-ESM" = "miroc-esm" +"MIROC-ESM-CHEM" = "miroc-esm-chem*" +"MIROC5" = "miroc5*" +"MPI-ESM-LR" = "mpi-esm-lr" +"MPI-ESM-MR" = "mpi-esm-mr*" +"MRI-CGCM3" = "mri-cgcm3*" +"NorESM1-M" = "noresm1-m" +"surrogate_CanESM2_89" = "canesm2_89" +"surrogate_CanESM2_94" = "canesm2_94" +"surrogate_CanESM2_99" = "canesm2_99" +"surrogate_GFDL-CM3_89" = "gfdl-cm3_89" +"surrogate_GFDL-CM3_94" = "gfdl-cm3_94" +"surrogate_GFDL-CM3_99" = "gfdl-cm3_99" +"surrogate_GFDL-ESM2G_01" = "gfdl-esm2g_01" +"surrogate_GFDL-ESM2G_11" = "gfdl-esm2g_11" +"surrogate_MRI-CGCM3_01" = "mri-cgcm3_01" +"surrogate_MRI-CGCM3_06" = "mri-cgcm3_06" +"surrogate_MRI-CGCM3_11" = "mri-cgcm3_11" diff --git a/examples/model_weights/smme_rcp85_names.toml b/examples/model_weights/smme_rcp85_names.toml new file mode 100644 index 0000000..52f2b0a --- /dev/null +++ b/examples/model_weights/smme_rcp85_names.toml @@ -0,0 +1,39 @@ +# The row of each member of the projection trees in rcp85_SMME_weights.tsv +# of Zenodo record 22003542, written out for stats.model_weight_names until +# the table carries the members' names. README.md beside this file says how +# the pairs were made. bcc-csm1-1 is spelt the same on both sides and +# needs no entry. + +[stats.model_weight_names] +"ACCESS1-0" = "access1-0*" +"BNU-ESM" = "bnu-esm*" +"CanESM2" = "canesm2*" +"CCSM4" = "ccsm4" +"CESM1-BGC" = "cesm1-bgc*" +"CNRM-CM5" = "cnrm-cm5" +"CSIRO-Mk3-6-0" = "csiro-mk3-6-0" +"GFDL-CM3" = "gfdl-cm3*" +"GFDL-ESM2G" = "gfdl-esm2g*" +"GFDL-ESM2M" = "gfdl-esm2m" +"inmcm4" = "inmcm4*" +"IPSL-CM5A-LR" = "ipsl-cm5a-lr" +"IPSL-CM5A-MR" = "ipsl-cm5a-mr*" +"MIROC-ESM" = "miroc-esm*" +"MIROC-ESM-CHEM" = "miroc-esm-chem*" +"MIROC5" = "miroc5*" +"MPI-ESM-LR" = "mpi-esm-lr" +"MPI-ESM-MR" = "mpi-esm-mr*" +"MRI-CGCM3" = "mri-cgcm3*" +"NorESM1-M" = "noresm1-m*" +"surrogate_CanESM2_89" = "canesm2_89" +"surrogate_CanESM2_94" = "canesm2_94" +"surrogate_CanESM2_99" = "canesm2_99" +"surrogate_GFDL-CM3_89" = "gfdl-cm3_89" +"surrogate_GFDL-CM3_94" = "gfdl-cm3_94" +"surrogate_GFDL-CM3_99" = "gfdl-cm3_99" +"surrogate_GFDL-ESM2G_01" = "gfdl-esm2g_01" +"surrogate_GFDL-ESM2G_06" = "gfdl-esm2g_06" +"surrogate_GFDL-ESM2G_11" = "gfdl-esm2g_11" +"surrogate_MRI-CGCM3_01" = "mri-cgcm3_01" +"surrogate_MRI-CGCM3_06" = "mri-cgcm3_06" +"surrogate_MRI-CGCM3_11" = "mri-cgcm3_11" diff --git a/examples/montecarlo/runs/run_valued_mortality.py b/examples/montecarlo/runs/run_valued_mortality.py index 084d9bc..e546b3a 100644 --- a/examples/montecarlo/runs/run_valued_mortality.py +++ b/examples/montecarlo/runs/run_valued_mortality.py @@ -29,6 +29,7 @@ import xarray as xr import cil_regionalization as cilreg +from cil_regionalization.pipelines.montecarlo import load_model_weight_names from cil_regionalization.stats import pooled_statistics, window_means ZARRS = Path( @@ -36,6 +37,11 @@ ) WEIGHTS = "/project/cil/home_dirs/scadavidsanchez/repos/climate-and-damages-aggregations/data/weights/ir_{adm}_full" SMME = "/project/cil/gcp/climate/SMME-weights/{rcp}_SMME_weights.tsv" +# the row of each member in the SMME table of an rcp, written out, until +# the tables carry the members' names +SMME_NAMES = ( + Path(__file__).resolve().parents[2] / "model_weights" / "smme_{rcp}_names.toml" +) OUT = "/project/cil/gcp/impact_map/mortality" BATCHES = [f"batch{i}" for i in range(15)] SSPS = ["SSP2", "SSP3", "SSP4"] @@ -46,17 +52,25 @@ IAMS = {"IIASA GDP": "low", "OECD Env-Growth": "high"} +def model_weights(rcp: str) -> cilreg.ModelWeights: + """The SMME table of the rcp, with the row of each member declared.""" + return cilreg.read_model_weights( + SMME.format(rcp=rcp), + table_names=load_model_weight_names(str(SMME_NAMES).format(rcp=rcp)), + ) + + def weighted_gcms(rcp: str, gcms: list[str]) -> list[str]: """The gcms the rcp's SMME table declares, in zarr naming. The zarrs carry one gcm dimension shared by both rcps, padded with NaN where an rcp was not run: rcp45 holds 32 real models plus an all-NaN surrogate_GFDL-ESM2G_06 slice. The weight table is the - declaration of the rcp's ensemble, so it decides what aggregates. + declaration of the rcp's ensemble, so it decides what aggregates. A + gcm takes its row by its own name or the row declared for it. """ - smme = pd.read_csv(SMME.format(rcp=rcp), sep="\t")["model"] - declared = set(smme.str.replace("*", "", regex=False).str.lower()) - kept = [g for g in gcms if g.replace("surrogate_", "").lower() in declared] + absent = set(model_weights(rcp).missing(gcms)) + kept = [g for g in gcms if g not in absent] dropped = sorted(set(gcms) - set(kept)) if dropped: print(f"{rcp}: not in the SMME table, skipped: {dropped}", flush=True) @@ -115,20 +129,8 @@ def batch_frames(task) -> list[pd.DataFrame]: def weighted_stats(reduced: pd.DataFrame, rcp: str) -> pd.DataFrame: - smme = pd.read_csv(SMME.format(rcp=rcp), sep="\t")[["model", "weight"]] - smme["key"] = smme["model"].str.replace("*", "", regex=False).str.lower() - frame = ( - reduced.assign( - key=reduced["gcm"].str.replace("surrogate_", "", regex=False).str.lower() - ) - .merge( - smme[["key", "weight"]].rename(columns={"weight": "model_weight"}), - on="key", - ) - .drop(columns="key") - ) - if len(frame) != len(reduced): - raise ValueError("a climate model has no SMME weight row") + # refuses a gcm with no row, so no climate model is dropped + frame = reduced.assign(model_weight=model_weights(rcp).attach(reduced["gcm"])) return pooled_statistics( frame, sample_dims=["batch", "gcm"], diff --git a/tests/integration/test_bigquery_backend.py b/tests/integration/test_bigquery_backend.py index 73696d8..b9196db 100644 --- a/tests/integration/test_bigquery_backend.py +++ b/tests/integration/test_bigquery_backend.py @@ -78,7 +78,11 @@ def _bq_cfg(**overrides) -> Config: "backend": { "kind": "bigquery", "coverage": "pixel_centroid", - "bigquery": {"staging_uri": "gs://example-staging/segment-weights/"}, + "bigquery": { + "project": "compute-impactlab", + "temp_dataset": "temp_workspace", + "staging_uri": "gs://example-staging/segment-weights/", + }, }, "output": {"dir": "/tmp/cilreg_bq_test"}, } @@ -302,6 +306,30 @@ def test_changes_with_content(self): ) != backend._geometry_content_hash(df2, "hierid") +class TestGridOffset: + def test_the_backend_refuses_an_edge_offset_grid(self): + """Its SQL places every cell for the centre offset, so an edge + grid would get weights half a cell off. The config refuses it + too; this is the backend's own check, for a grid built by hand. + It went red with the edge grid accepted.""" + import dataclasses + + from cil_regionalization.backends.bigquery import BigQueryBackend + from cil_regionalization.grid import GridSpec + from cil_regionalization.regions import RegionSet + from cil_regionalization.weights import from_config_list + + cfg = _bq_cfg() + grid = dataclasses.replace(GridSpec.from_config(cfg.grid), offset="edge") + with pytest.raises(ValueError, match="takes grid.offset = 'center' only"): + BigQueryBackend()._validate_inputs( + RegionSet.from_config(cfg.regions), + grid, + from_config_list(cfg.weights), + cfg, + ) + + class TestMainSql: def _build(self, cfg: Config | None = None): from cil_regionalization.backends.bigquery import BigQueryBackend diff --git a/tests/integration/test_fetch.py b/tests/integration/test_fetch.py index 8ca10fe..8e57c92 100644 --- a/tests/integration/test_fetch.py +++ b/tests/integration/test_fetch.py @@ -374,17 +374,25 @@ def smme(self): yield server server.stop() - def test_it_reads_the_table_of_the_rcp_and_matches_the_names(self, smme, tmp_path): + def test_it_reads_the_table_of_the_rcp_with_the_rows_declared(self, smme, tmp_path): + """The published rows are not spelt as the trees spell the + members, so they are declared, and without them the members are + refused.""" from cil_regionalization.fetch import fetch_model_weights - weights = fetch_model_weights( - "rcp85", record=RECORD_ID, base_url=smme.base_url, cache_dir=tmp_path - ) - attached = weights.attach( - pd.Series(["CCSM4", "MIROC5", "surrogate_GFDL-CM3_89"]) - ) - assert attached.tolist() == [0.25, 0.5, 0.25] + options = dict(record=RECORD_ID, base_url=smme.base_url, cache_dir=tmp_path) + members = pd.Series(["CCSM4", "MIROC5", "surrogate_GFDL-CM3_89"]) + names = { + "CCSM4": "ccsm4", + "MIROC5": "miroc5*", + "surrogate_GFDL-CM3_89": "gfdl-cm3_89", + } + weights = fetch_model_weights("rcp85", table_names=names, **options) + assert weights.attach(members).tolist() == [0.25, 0.5, 0.25] assert weights.sha256 == hashlib.sha256(self.TSV).hexdigest() + # from the cache, as it was fetched + with pytest.raises(ValueError, match="3 members have no row"): + fetch_model_weights("rcp85", **options).attach(members) def test_a_second_call_reads_the_cache(self, smme, tmp_path): from cil_regionalization.fetch import fetch_model_weights diff --git a/tests/integration/test_montecarlo_pipeline.py b/tests/integration/test_montecarlo_pipeline.py index 8be5acb..6888ba2 100644 --- a/tests/integration/test_montecarlo_pipeline.py +++ b/tests/integration/test_montecarlo_pipeline.py @@ -17,6 +17,7 @@ import itertools import json import math +import re from pathlib import Path import geopandas as gpd @@ -1113,26 +1114,6 @@ def test_the_tables_of_stats_resolve_against_config(self, tmp_path, table): assert found == str(tmp_path / "configs" / "tables" / name) -class TestNoSiteFactsInCode: - def test_pipeline_code_carries_no_absolute_paths_or_environments(self): - import cil_regionalization.pipelines.montecarlo as module - - source = Path(module.__file__).read_text() - for forbidden in ( - "/project/", - "/" + "Volumes/", # split so test_no_mount_paths.py does not match it - "/shares/", - "/home/", - "conda", - "sbatch", - "battuta", - "caslake", - ): - assert forbidden not in source, ( - f"pipeline code contains site-specific string {forbidden!r}" - ) - - def _build_netcdf_tree( root: Path, levels: dict[str, list[str]], @@ -1412,6 +1393,7 @@ def test_weighted_mean_uses_the_weights(self, weights_dir, tmp_path): cfg = _pipeline_cfg(weights_dir, tree, tmp_path / "out", levels=_LEVELS) raw = cfg.model_dump() raw["stats"]["model_weights"] = str(self._weights_file(tmp_path)) + raw["stats"]["model_weight_names"] = {"z0": "Z0*"} raw["stats"]["quantile_method"] = "lower_step" raw["stats"]["model_weight_level"] = "zeppelin" raw["stats"]["quantiles"] = [] @@ -1444,12 +1426,75 @@ def test_unmatched_model_is_rejected(self, weights_dir, tmp_path): raw["stats"]["quantile_method"] = "lower_step" raw["stats"]["model_weight_level"] = "zeppelin" cfg = MonteCarloPipelineConfig.model_validate(raw) - # the check of the values the tree declares, not the lookup of - # one leaf's weight, which says "has no row" + # the check of the values the tree declares, before any leaf with pytest.raises( - ValueError, match=r"values of 'zeppelin' have no row in the model" + ValueError, + match=r"2 members have no row in the model weights file .*: 'z1' " + r"\(closest row 'z0'\) and 'z2' \(closest row 'z0'\)", ): run_pipeline(cfg) + assert not (tmp_path / "out").exists() + + def test_a_model_spelt_otherwise_than_its_row_is_refused_by_both_names( + self, weights_dir, tmp_path + ): + """Z0* was the row of z0 to the rule that lowercased both and + dropped the star. It went red on that rule. Nothing is written.""" + tree = tmp_path / "tree" + _build_tree(tree, _LEVELS) + cfg = self._weighted_cfg( + weights_dir, tree, tmp_path / "out", self._weights_file(tmp_path) + ) + raw = cfg.model_dump() + raw["stats"]["model_weight_names"] = {} + with pytest.raises( + ValueError, + match=r"1 member has no row in the model weights file .*: 'z0' " + r"\(closest row 'Z0\*'\)\..*stats.model_weight_names.*" + r'as in "z0" = "Z0\*"', + ): + run_pipeline(MonteCarloPipelineConfig.model_validate(raw)) + assert not (tmp_path / "out").exists() + + @pytest.mark.parametrize( + "names, message", + [ + ( + {"z0": "Z0*", "Z0": "Z0*", "z1": "z1"}, + "stats.model_weight_names declares one row for more than one " + "member, the row 'Z0*' for 'z0' and 'Z0'. Each member needs a " + "row of its own.", + ), + ( + {"z0": ""}, + "stats.model_weight_names maps a member name to a table name, " + "and 'z0' = '' leaves one empty", + ), + ], + ) + def test_declared_rows_are_refused_by_the_name_they_came_under( + self, weights_dir, tmp_path, names, message + ): + """The refusal of read_model_weights named its table_names, + which a config does not have. It went red on that.""" + raw = self._weighted_cfg( + weights_dir, tmp_path / "tree", tmp_path / "out", tmp_path / "w.tsv" + ).model_dump() + raw["stats"]["model_weight_names"] = names + with pytest.raises(ValueError, match=re.escape(message)): + MonteCarloPipelineConfig.model_validate(raw) + + def test_declared_rows_without_a_table_are_refused(self, weights_dir, tmp_path): + raw = _pipeline_cfg( + weights_dir, tmp_path / "t", tmp_path / "o", levels=_LEVELS + ).model_dump() + raw["stats"]["model_weight_names"] = {"z0": "Z0*"} + with pytest.raises( + ValueError, + match="stats.model_weight_names declares rows of a model weights " + "file, and stats.model_weights names none", + ): + MonteCarloPipelineConfig.model_validate(raw) def test_weight_level_must_be_sample_dim(self, weights_dir, tmp_path): cfg = _pipeline_cfg(weights_dir, tmp_path / "t", tmp_path / "o", levels=_LEVELS) @@ -1466,6 +1511,7 @@ def _weighted_cfg( cfg = _pipeline_cfg(weights_dir, tree, out, levels=_LEVELS, n_workers=n_workers) raw = cfg.model_dump() raw["stats"]["model_weights"] = str(weights_file) + raw["stats"]["model_weight_names"] = {"z0": "Z0*"} raw["stats"]["quantile_method"] = "lower_step" raw["stats"]["model_weight_level"] = "zeppelin" raw["tree"]["exclude"] = [list(cell) for cell in exclude] @@ -1478,12 +1524,11 @@ def test_two_rows_for_one_model_are_refused(self, weights_dir, tmp_path): _build_tree(tree, _LEVELS) p = tmp_path / "weights.tsv" pd.DataFrame( - {"model": ["Z0*", "z1", "z2", "z0"], "weight": [0.6, 0.3, 0.1, 0.2]} + {"model": ["Z0*", "z1", "z2", "z1"], "weight": [0.6, 0.3, 0.1, 0.2]} ).to_csv(p, sep="\t", index=False) cfg = self._weighted_cfg(weights_dir, tree, tmp_path / "out", p) - with pytest.raises(ValueError) as error: + with pytest.raises(ValueError, match="has the row 'z1' more than once"): run_pipeline(cfg) - assert "['Z0*', 'z0']" in str(error.value) assert not (tmp_path / "out").exists() @pytest.mark.parametrize("n_workers", [1, 2]) @@ -1550,9 +1595,12 @@ def test_the_manifest_records_the_members_attached(self, weights_dir, tmp_path): manifest = json.loads(Path(result.paths["manifest"]).read_text()) assert manifest["model_weights"] == str(p) + assert manifest["model_weight_names"] == {"z0": "Z0*"} assert manifest["model_weights_record"] == { "path": str(p), "sha256": hashlib.sha256(p.read_bytes()).hexdigest(), + "table_names": {"z0": "Z0*"}, + "table_names_unused": {}, "members": { "z0": {"row": "Z0*", "weight": 0.6, "n_leaves": 2}, "z1": {"row": "z1", "weight": 0.3, "n_leaves": 2}, @@ -3587,9 +3635,9 @@ def window_means(*args, **kwargs): real, reads = montecarlo.read_model_weights, [] - def read_model_weights(path): + def read_model_weights(path, **options): reads.append(path) - return real(path) + return real(path, **options) monkeypatch.setattr(montecarlo, "window_means", window_means) monkeypatch.setattr(montecarlo, "read_model_weights", read_model_weights) diff --git a/tests/integration/test_regions_find.py b/tests/integration/test_regions_find.py index d3e66d7..0883cff 100644 --- a/tests/integration/test_regions_find.py +++ b/tests/integration/test_regions_find.py @@ -192,6 +192,8 @@ def test_issues_parameterized_like_query(self, tmp_path, monkeypatch, capsys): kind = "bigquery" coverage = "pixel_centroid" [backend.bigquery] +project = "example-project" +temp_dataset = "example_temp" staging_uri = "gs://example-staging/segment-weights/" [output] dir = "{tmp_path}/out" diff --git a/tests/integration/test_xarray_parity.py b/tests/integration/test_xarray_parity.py index 3325444..1c2ca65 100644 --- a/tests/integration/test_xarray_parity.py +++ b/tests/integration/test_xarray_parity.py @@ -141,7 +141,12 @@ def _raw( if weighted: table = tmp_path / "model_weights.tsv" table.write_text("model\tweight\nm0\t0.5\nm1\t0.375\nm0_06\t0.125\n") - raw["stats"].update(model_weights=str(table), model_weight_level="gcm") + # the table spells the surrogate as the published tables do + raw["stats"].update( + model_weights=str(table), + model_weight_level="gcm", + model_weight_names={"surrogate_m0_06": "m0_06"}, + ) return raw, out diff --git a/tests/unit/test_compute.py b/tests/unit/test_compute.py index da254cd..43a5c56 100644 --- a/tests/unit/test_compute.py +++ b/tests/unit/test_compute.py @@ -35,6 +35,30 @@ def boom(*a, **k): with dask_client_for(opts) as client: assert client is None + def test_slurm_without_its_settings_is_refused_before_dask_is_imported( + self, monkeypatch + ): + """For options built without the model's check, as a caller can. + It went red on the defaults of one cluster's partition.""" + import pydantic + + def boom(*a, **k): + raise AssertionError("dask was imported before the settings were checked") + + real_import = __import__ + monkeypatch.setattr( + "builtins.__import__", + lambda name, *a, **k: ( + boom() + if name.startswith(("dask", "distributed")) + else real_import(name, *a, **k) + ), + ) + opts = LocalBackendOptions.model_construct(dask="slurm", slurm_queue="general") + with pytest.raises(pydantic.ValidationError, match="slurm_cores"): + with dask_client_for(opts): + pass + def test_default_is_off(self): opts = LocalBackendOptions() assert opts.dask == "off" diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index 7fe199a..0909e18 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -12,7 +12,7 @@ import pytest from pydantic import ValidationError -from cil_regionalization.config import Config, load_config +from cil_regionalization.config import Config, LocalBackendOptions, load_config def _local_cfg() -> dict: @@ -43,7 +43,11 @@ def _bq_cfg() -> dict: ], "backend": { "kind": "bigquery", - "bigquery": {"staging_uri": "gs://example-staging/segment-weights/"}, + "bigquery": { + "project": "compute-impactlab", + "temp_dataset": "temp_workspace", + "staging_uri": "gs://example-staging/segment-weights/", + }, }, "output": {"dir": "gs://impactlab-data-scratch/test"}, } @@ -64,10 +68,8 @@ def test_minimal_local_applies_defaults(self): def test_minimal_bigquery_applies_defaults(self): cfg = Config.model_validate(_bq_cfg()) assert cfg.backend.kind == "bigquery" + # the project and the temp dataset are declared, as the fixture does assert cfg.backend.bigquery.project == "compute-impactlab" - # Confirmed on cilresearch: temp_workspace is the existing dataset. - # workflow_scratch_tables (from the legacy scripts) is not present - # on this project; never create a dataset to "make it work". assert cfg.backend.bigquery.temp_dataset == "temp_workspace" assert cfg.backend.bigquery.cache_temp_tables is False # staging_uri has no default (a writable bucket is a site fact); @@ -428,7 +430,7 @@ def test_missing_section_named(self, key): class TestBigQueryStagingUri: def test_missing_staging_uri_rejected(self): d = _bq_cfg() - del d["backend"]["bigquery"] + del d["backend"]["bigquery"]["staging_uri"] with pytest.raises(ValidationError) as exc: Config.model_validate(d) assert "staging_uri" in str(exc.value) @@ -439,6 +441,91 @@ def test_local_backend_needs_no_staging_uri(self): assert cfg.backend.bigquery.staging_uri is None +class TestSiteFactsAreDeclared: + """A queue, the shape of a job, a billing project and a dataset belong + to one cluster or one cloud account, and the config says them.""" + + @pytest.mark.parametrize( + "missing", [["project"], ["temp_dataset"], ["project", "temp_dataset"]] + ) + def test_bigquery_needs_its_project_and_temp_dataset(self, missing): + """They defaulted to one cloud account's, and this went red on + that.""" + d = _bq_cfg() + for key in missing: + del d["backend"]["bigquery"][key] + named = " and ".join(f"backend.bigquery.{key}" for key in missing) + with pytest.raises(ValidationError) as exc: + Config.model_validate(d) + assert ( + f"backend.kind = 'bigquery' needs {named}, the billing project " + f"and the dataset in the location of the weight tables that temp " + f"tables go in. They belong to a cloud account, so neither has a " + f"default." + ) in str(exc.value) + + def test_the_local_backend_needs_neither(self): + cfg = Config.model_validate(_local_cfg()) + assert cfg.backend.bigquery.project is None + assert cfg.backend.bigquery.temp_dataset is None + + def test_slurm_needs_every_setting_of_its_jobs(self): + """They defaulted to one cluster's partition, and this went red + on that.""" + with pytest.raises(ValidationError) as exc: + LocalBackendOptions(dask="slurm") + assert ( + "backend.local.dask = 'slurm' needs backend.local.slurm_queue, " + "backend.local.slurm_cores, backend.local.slurm_memory, " + "backend.local.slurm_walltime and backend.local.n_workers. The " + "queue, the cores, memory and walltime of a job and the number of " + "jobs belong to a cluster, so none has a default." + ) in str(exc.value) + + @pytest.mark.parametrize( + "left_out", + ["slurm_queue", "slurm_cores", "slurm_memory", "slurm_walltime", "n_workers"], + ) + def test_slurm_needs_each_of_them(self, left_out): + settings = dict( + dask="slurm", + slurm_queue="general", + slurm_cores=8, + slurm_memory="32GB", + slurm_walltime="01:00:00", + n_workers=3, + ) + LocalBackendOptions(**settings) + del settings[left_out] + with pytest.raises(ValidationError, match=f"needs backend.local.{left_out}"): + LocalBackendOptions(**settings) + + def test_the_other_dask_modes_need_none_of_them(self): + for mode in ("off", "local"): + assert LocalBackendOptions(dask=mode).slurm_queue is None + + +class TestBigQueryGridOffset: + def test_an_edge_offset_grid_is_refused(self): + """The SQL places cells for the centre offset. It went red with + the edge offset accepted.""" + d = _bq_cfg() + d["grid"]["offset"] = "edge" + with pytest.raises(ValidationError) as exc: + Config.model_validate(d) + assert ( + "backend.kind = 'bigquery' takes grid.offset = 'center' only, and " + "got 'edge'. Its SQL handles centre offsets only, so the weights of " + "an edge-offset grid would come out half a cell off. Use " + "backend.kind = 'local' for an edge-offset grid." + ) in str(exc.value) + + def test_the_local_backend_takes_an_edge_offset_grid(self): + d = _local_cfg() + d["grid"]["offset"] = "edge" + assert Config.model_validate(d).grid.offset == "edge" + + class TestUnknownKeys: def test_typo_in_grid_rejected(self): d = _local_cfg() diff --git a/tests/unit/test_model_weights.py b/tests/unit/test_model_weights.py index fafdded..24d5b56 100644 --- a/tests/unit/test_model_weights.py +++ b/tests/unit/test_model_weights.py @@ -1,4 +1,5 @@ -"""Model weights are read once, refused when ambiguous, and recorded. +"""Model weights are read once, matched by the exact name or a declared +row, refused when a member has none, and recorded. The tables are synthetic. Every test here fails without the module, because the import fails. The tests that name a mutation in their @@ -10,6 +11,7 @@ import hashlib import json import pickle +import re from pathlib import Path import pandas as pd @@ -27,7 +29,8 @@ "mri-cgcm3*", ] WEIGHTS = [0.1, 1 / 3, 0.036, 0.2, 0.0, 0.3306666666666667] -# the tree has no leaf of the last model but one +# spelt as the trees spell them, which the rows above are not, and the +# tree has no leaf of the last model but one MEMBERS = [ "surrogate_MRI-CGCM3_01", "GFDL-ESM2G", @@ -35,6 +38,15 @@ "inmcm4", "MRI-CGCM3", ] +# the row of each member, written out, and of a model the tree lacks +NAMES = { + "surrogate_MRI-CGCM3_01": "mri-cgcm3_01", + "GFDL-ESM2G": "gfdl-esm2g", + "surrogate_GFDL-ESM2G_01": "gfdl-esm2g_01", + "inmcm4": "inmcm4*", + "MRI-CGCM3": "mri-cgcm3*", + "ACCESS1-0": "access1-0*", +} def _table(tmp_path: Path, models=MODELS, weights=WEIGHTS) -> Path: @@ -58,20 +70,14 @@ def _draws(members: list[str], n_batch: int = 3) -> pd.DataFrame: class TestRead: def test_rows_come_back_as_written(self, tmp_path): path = _table(tmp_path) - got = read_model_weights(path) + got = read_model_weights(path, table_names=NAMES) assert isinstance(got, ModelWeights) assert got.path == str(path) assert got.names == tuple(MODELS) - assert got.keys == ( - "mri-cgcm3_01", - "gfdl-esm2g", - "gfdl-esm2g_01", - "inmcm4", - "access1-0", - "mri-cgcm3", - ) assert got.weights == tuple(WEIGHTS) assert all(type(w) is float for w in got.weights) + assert got.table_names == NAMES + assert read_model_weights(path).table_names == {} def test_a_table_laid_out_like_the_published_files(self, tmp_path): """The published tables have a leading column, year columns @@ -87,6 +93,12 @@ def test_a_table_laid_out_like_the_published_files(self, tmp_path): assert got.names == tuple(MODELS) assert got.weights == tuple(WEIGHTS) + def test_another_separator(self, tmp_path): + """As the copies of the examples keep the two columns.""" + path = tmp_path / "weights.csv" + pd.DataFrame({"model": MODELS, "weight": WEIGHTS}).to_csv(path, index=False) + assert read_model_weights(path, sep=",").weights == tuple(WEIGHTS) + def test_the_hash_is_of_the_bytes_parsed(self, tmp_path, monkeypatch): """The file is rewritten as soon as it has been read once. Both the rows and the hash are those of the first bytes. Failed with @@ -110,26 +122,50 @@ def read_then_edit(self): assert got.sha256 == hashlib.sha256(original).hexdigest() assert got.weights == tuple(WEIGHTS) - def test_two_rows_for_one_model_are_refused(self, tmp_path): - """Both rows are named as written. Failed with the check taken - out, which lets the last row win.""" + def test_a_name_in_the_table_twice_is_refused(self, tmp_path): + """Failed with the check taken out, which lets the last row + win.""" path = _table( tmp_path, - ["access1-0*", "inmcm4", "ACCESS1-0", "Inmcm4*", "ccsm4"], + ["access1-0*", "inmcm4", "access1-0*", "ccsm4", "ccsm4"], [0.0, 0.2, 0.4, 0.3, 0.1], ) - with pytest.raises(ValueError) as error: + with pytest.raises( + ValueError, + match=re.escape( + "has the rows 'access1-0*' and 'ccsm4' more than once. Each " + "model needs exactly one row." + ), + ): read_model_weights(path) - message = str(error.value) - assert "['access1-0*', 'ACCESS1-0']" in message - assert "['inmcm4', 'Inmcm4*']" in message - assert "ccsm4" not in message - - def test_a_surrogate_suffix_keeps_two_names_apart(self, tmp_path): - """The published tables hold both mri-cgcm3* and mri-cgcm3_01, - and both gfdl-esm2g and gfdl-esm2g_01.""" - got = read_model_weights(_table(tmp_path)) - assert len(set(got.keys)) == len(MODELS) + + def test_names_that_differ_by_a_letter_are_two_rows(self, tmp_path): + """access1-0* and ACCESS1-0 were one model to the rule that + lowercased both and dropped the star, which refused the table. + It went red on that rule.""" + path = _table(tmp_path, ["access1-0*", "ACCESS1-0"], [0.25, 0.75]) + got = read_model_weights(path) + assert got.weight_of("ACCESS1-0") == 0.75 + assert got.weight_of("access1-0*") == 0.25 + + def test_two_members_declared_to_one_row_are_refused(self, tmp_path): + with pytest.raises( + ValueError, + match=re.escape( + "table_names declares one row of the model weights file " + f"{tmp_path / 'weights.tsv'} for more than one member, the row " + "'inmcm4*' for 'inmcm4' and 'INMCM4'. Each member needs a row " + "of its own." + ), + ): + read_model_weights( + _table(tmp_path), table_names={"inmcm4": "inmcm4*", "INMCM4": "inmcm4*"} + ) + + @pytest.mark.parametrize("row", ["", 3]) + def test_a_declared_row_that_is_not_a_name_is_refused(self, tmp_path, row): + with pytest.raises(ValueError, match="both strings"): + read_model_weights(_table(tmp_path), table_names={"inmcm4": row}) def test_a_table_without_the_two_columns_is_refused(self, tmp_path): path = tmp_path / "weights.tsv" @@ -143,53 +179,100 @@ def test_it_is_exported(self): class TestMatching: - def test_members_match_as_the_pipeline_matched_them(self, tmp_path): - """The lookup the pipeline did before, written out here.""" - path = _table(tmp_path) - table = pd.read_csv(path, sep="\t") - keys = table["model"].str.replace("*", "", regex=False).str.lower() - before = dict(zip(keys, table["weight"].astype(float))) + def test_a_member_takes_the_row_of_its_own_name_and_no_other(self, tmp_path): + """Not lowercased, not without its prefix, not without the + table's star. It went red on the rule that did all three.""" + got = read_model_weights(_table(tmp_path)) + assert got.weight_of("inmcm4*") == 0.2 + assert got.missing(MEMBERS + ["ACCESS1-0", "inmcm4*"]) == sorted( + MEMBERS + ["ACCESS1-0"] + ) - got = read_model_weights(path) - for member in MEMBERS + ["ACCESS1-0"]: - expected = before[member.replace("surrogate_", "").lower()] - assert got.weight_of(member) == expected - assert got.missing(MEMBERS + ["ACCESS1-3", "surrogate_CCSM4_01"]) == [ - "ACCESS1-3", - "surrogate_CCSM4_01", - ] + def test_a_declared_row_is_the_member_s_row(self, tmp_path): + got = read_model_weights(_table(tmp_path), table_names=NAMES) + weight = dict(zip(MODELS, WEIGHTS)) + for member, row in NAMES.items(): + assert got.weight_of(member) == weight[row] + assert got.missing(MEMBERS + ["ACCESS1-3"]) == ["ACCESS1-3"] - @pytest.mark.parametrize("dtype", ["object", "category"]) - def test_attach_gives_the_column_the_merge_gave(self, tmp_path, dtype): - """The merge is the one the README shows. A model at weight zero - gets 0.0 like any other.""" - path = _table(tmp_path) - draws = _draws(MEMBERS + ["ACCESS1-0"]) + def test_the_refusal_names_both_sides_and_the_ways_out(self, tmp_path): + """The member as the tree spells it, the row it comes closest + to, what to change, and why the published tables fail.""" + weights = read_model_weights(_table(tmp_path)) + with pytest.raises(ValueError) as error: + weights.attach(_draws(["ACCESS1-0", "surrogate_GFDL-ESM2G_01"])["gcm"]) + assert str(error.value) == ( + f"2 members have no row in the model weights file " + f"{tmp_path / 'weights.tsv'}: 'ACCESS1-0' (closest row " + f"'access1-0*') and 'surrogate_GFDL-ESM2G_01' (closest row " + f"'gfdl-esm2g_01'). A member takes the row of its own name, letter " + f"for letter, or the row declared for it. Write the members' " + f"names into the table, or declare each member's row in " + f"stats.model_weight_names, or in table_names of " + f'read_model_weights, as in "ACCESS1-0" = "access1-0*".' + ) - table = pd.read_csv(path, sep="\t")[["model", "weight"]] - table["key"] = table["model"].str.replace("*", "", regex=False).str.lower() - merged = draws.assign( - key=draws["gcm"].str.replace("surrogate_", "", regex=False).str.lower() - ).merge(table[["key", "weight"]], on="key", how="left") + def test_a_declared_row_the_table_lacks_is_named_with_its_closest(self, tmp_path): + weights = read_model_weights( + _table(tmp_path), table_names={"ACCESS1-0": "acess1-0*"} + ) + with pytest.raises( + ValueError, + match=re.escape( + "'ACCESS1-0' declared as 'acess1-0*' (closest row 'access1-0*')" + ), + ): + weights.weight_of("ACCESS1-0") + + def test_past_five_the_refusal_counts_the_rest(self, tmp_path): + weights = read_model_weights(_table(tmp_path)) + with pytest.raises(ValueError, match=r"\(closest row '[^']+'\) and 2 more\."): + weights.check(MEMBERS + ["ACCESS1-0", "ACCESS1-3"]) + + def test_two_members_on_one_row_are_refused(self, tmp_path): + """One by its own name and one by a declared row. Failed with + both given the row's weight.""" + weights = read_model_weights( + _table(tmp_path), table_names={"INMCM4": "inmcm4*"} + ) + with pytest.raises( + ValueError, + match=re.escape( + "would give one row to more than one member, the row " + "'inmcm4*' to 'inmcm4*' and 'INMCM4'. Each member needs a row " + "of its own." + ), + ): + weights.attach(_draws(["inmcm4*", "INMCM4"])["gcm"]) + @pytest.mark.parametrize("dtype", ["object", "category"]) + def test_attach_gives_each_draw_the_weight_of_its_row(self, tmp_path, dtype): + """A model at weight zero gets 0.0 like any other.""" + weight = dict(zip(MODELS, WEIGHTS)) + draws = _draws(MEMBERS + ["ACCESS1-0"]) members = draws["gcm"].astype(dtype) members.index = range(100, 100 + len(members)) - got = read_model_weights(path).attach(members) + got = read_model_weights(_table(tmp_path), table_names=NAMES).attach(members) assert got.dtype == "float64" assert got.index.equals(members.index) - assert got.tolist() == merged["weight"].tolist() + assert got.tolist() == [weight[NAMES[m]] for m in draws["gcm"]] assert 0.0 in got.tolist() def test_attach_refuses_a_member_with_no_row(self, tmp_path): """Failed with the weight of such a member left as NaN.""" - weights = read_model_weights(_table(tmp_path)) + weights = read_model_weights(_table(tmp_path), table_names=NAMES) draws = _draws(MEMBERS + ["ACCESS1-3"]) - with pytest.raises(ValueError, match=r"1 members have no row.*ACCESS1-3"): + with pytest.raises(ValueError, match=r"1 member has no row.*'ACCESS1-3'"): weights.attach(draws["gcm"]) + def test_attach_refuses_a_draw_with_no_member(self, tmp_path): + weights = read_model_weights(_table(tmp_path), table_names=NAMES) + with pytest.raises(ValueError, match="1 row names no member"): + weights.attach(pd.Series(["inmcm4", None])) + def test_weight_of_refuses_a_member_with_no_row(self, tmp_path): - weights = read_model_weights(_table(tmp_path)) - with pytest.raises(ValueError, match="'ACCESS1-3' has no row"): + weights = read_model_weights(_table(tmp_path), table_names=NAMES) + with pytest.raises(ValueError, match="1 member has no row.*'ACCESS1-3'"): weights.weight_of("ACCESS1-3") @@ -198,7 +281,7 @@ def test_it_counts_leaves_and_lists_the_rows_left_over(self, tmp_path): """Failed with each member counted once, and with the rows left over listed without their weights.""" path = _table(tmp_path) - weights = read_model_weights(path) + weights = read_model_weights(path, table_names=NAMES) leaves = MEMBERS * 15 + ["inmcm4"] record = weights.record(leaves) assert record["path"] == str(path) @@ -224,11 +307,15 @@ def test_it_counts_leaves_and_lists_the_rows_left_over(self, tmp_path): } assert record["unmatched_rows"] == {"access1-0*": 0.0} + def test_it_lists_the_rows_declared_and_those_no_member_used(self, tmp_path): + record = read_model_weights(_table(tmp_path), table_names=NAMES).record(MEMBERS) + assert record["table_names"] == NAMES + assert record["table_names_unused"] == {"ACCESS1-0": "access1-0*"} + def test_the_record_gives_the_table_back(self, tmp_path): """The weights read back from JSON are the floats that were used, to the last bit.""" - path = _table(tmp_path) - weights = read_model_weights(path) + weights = read_model_weights(_table(tmp_path), table_names=NAMES) record = json.loads(json.dumps(weights.record(MEMBERS), sort_keys=True)) rebuilt = { entry["row"]: entry["weight"] for entry in record["members"].values() @@ -239,10 +326,10 @@ def test_the_record_gives_the_table_back(self, tmp_path): } def test_a_member_with_no_row_is_refused(self, tmp_path): - weights = read_model_weights(_table(tmp_path)) - with pytest.raises(ValueError, match=r"1 members have no row.*ACCESS1-3"): + weights = read_model_weights(_table(tmp_path), table_names=NAMES) + with pytest.raises(ValueError, match=r"1 member has no row.*'ACCESS1-3'"): weights.record(MEMBERS + ["ACCESS1-3"]) def test_the_rows_survive_the_trip_to_a_worker(self, tmp_path): - weights = read_model_weights(_table(tmp_path)) + weights = read_model_weights(_table(tmp_path), table_names=NAMES) assert pickle.loads(pickle.dumps(weights)) == weights diff --git a/tests/unit/test_no_site_facts.py b/tests/unit/test_no_site_facts.py new file mode 100644 index 0000000..1cfede0 --- /dev/null +++ b/tests/unit/test_no_site_facts.py @@ -0,0 +1,47 @@ +"""The package carries no fact of one cluster or one cloud account. A +queue, a core count, a project and a path are what a caller declares.""" + +from __future__ import annotations + +from pathlib import Path + +import pytest + +import cil_regionalization + +PACKAGE = Path(cil_regionalization.__file__).resolve().parent +MODULES = sorted(PACKAGE.rglob("*.py")) +FORBIDDEN = ( + "/project/", + "/" + "Volumes/", # split so test_no_mount_paths.py does not match it + "/shares/", + "/home/", + "conda", + "sbatch", + "battuta", + "caslake", + "midway", + "compute-impactlab", + "cilresearch", + "temp_workspace", + '"cil"', + "'cil'", +) + + +def test_every_module_is_read(): + """So that a module the search misses cannot pass by being left out.""" + assert len(MODULES) > 30 + assert PACKAGE / "compute.py" in MODULES + assert PACKAGE / "pipelines" / "montecarlo.py" in MODULES + + +@pytest.mark.parametrize("module", MODULES, ids=lambda p: str(p.relative_to(PACKAGE))) +def test_no_module_names_a_site(module): + """It went red on compute.py, config.py, legacy_compare.py, + cross_backend_compare.py and legacy_export.py, which named a + cluster's queue and paths and a cloud account's project. It checked + montecarlo.py alone before.""" + source = module.read_text() + found = [word for word in FORBIDDEN if word in source] + assert not found, f"{module.relative_to(PACKAGE)} names {found}" diff --git a/tests/unit/test_stats.py b/tests/unit/test_stats.py index 36be9a5..fafb430 100644 --- a/tests/unit/test_stats.py +++ b/tests/unit/test_stats.py @@ -7,6 +7,7 @@ from __future__ import annotations import itertools +from pathlib import Path from statistics import NormalDist import numpy as np @@ -1225,7 +1226,10 @@ def test_missing_weight_column_raises(self): ) -class TestUnweightedGcmWarning: +class TestUnweightedModelWarning: + """Pooling with ``model_dims`` named and no weights warns, keyed on + the declaration and on no name of a column.""" + def _gcm_frame(self): return _frame( [ @@ -1234,7 +1238,10 @@ def _gcm_frame(self): ] ) - def test_unweighted_gcm_warns(self): + @pytest.mark.parametrize("name", ["gcm", "zeppelin"]) + def test_unweighted_models_warn_under_any_name(self, name): + """It went red on the check of a column named gcm, under + zeppelin, and on the message that named a lab.""" import warnings from cil_regionalization.stats import ( @@ -1242,17 +1249,42 @@ def test_unweighted_gcm_warns(self): pooled_statistics, ) - with pytest.warns(UnweightedModelWeightsWarning, match="convention"): + frame = self._gcm_frame().rename(columns={"gcm": name}) + with pytest.warns(UnweightedModelWeightsWarning) as caught: with warnings.catch_warnings(): warnings.simplefilter("always") pooled_statistics( - self._gcm_frame(), - sample_dims=["gcm"], + frame, + sample_dims=[name], + model_dims=[name], quantile_method="linear", summation="fast", ) + assert str(caught[0].message) == ( + f"model_dims ['{name}'] names the climate model and weight_col is " + f"not set, so every climate model counts the same. Set weight_col " + f"to weight them, or filter UnweightedModelWeightsWarning where " + f"equal weights are meant." + ) + + def test_the_first_half_warns_too(self): + from cil_regionalization.stats import ( + UnweightedModelWeightsWarning, + summarize_samples, + ) + + with pytest.warns(UnweightedModelWeightsWarning, match="model_dims"): + summarize_samples( + self._gcm_frame().assign(year=2050), + sample_dims=["gcm"], + model_dims=["gcm"], + time_col="year", + window=(2050, 2050), + quantile_method="linear", + summation="fast", + ) - def test_weighted_gcm_does_not_warn(self): + def test_weighted_models_do_not_warn(self): import warnings from cil_regionalization.stats import pooled_statistics @@ -1263,22 +1295,23 @@ def test_weighted_gcm_does_not_warn(self): pooled_statistics( df, sample_dims=["gcm"], + model_dims=["gcm"], weight_col="w", quantile_method="lower_step", summation="fast", ) - def test_other_sample_dims_do_not_warn(self): + def test_no_model_dims_do_not_warn_whatever_the_columns_are_called(self): + """A column named gcm is a column like any other.""" import warnings from cil_regionalization.stats import pooled_statistics - df = self._gcm_frame().rename(columns={"gcm": "zeppelin"}) with warnings.catch_warnings(): warnings.simplefilter("error") pooled_statistics( - df, - sample_dims=["zeppelin"], + self._gcm_frame(), + sample_dims=["gcm"], quantile_method="linear", summation="fast", ) @@ -1297,10 +1330,17 @@ def test_warning_is_suppressible(self): pooled_statistics( self._gcm_frame(), sample_dims=["gcm"], + model_dims=["gcm"], quantile_method="linear", summation="fast", ) + def test_the_module_names_no_lab(self): + """It went red on the message that named one.""" + import cil_regionalization.stats as module + + assert "Climate Impact Lab" not in Path(module.__file__).read_text() + class TestSingleYearWindow: """A window whose start equals its end is labeled by the year alone.""" @@ -1632,15 +1672,18 @@ def test_counts_without_the_model_columns_are_refused(self): summation="fast", ) - def test_model_columns_without_the_counts_are_refused(self): - with pytest.raises(ValueError, match="only include_n_members writes"): - pooled_statistics( - self._draws(), - sample_dims=["batch", "gcm"], - model_dims=["gcm"], - quantile_method="lower_step", - summation="fast", - ) + def test_model_columns_without_the_counts_add_no_count(self): + """They name the climate model for the warning as well. They were + refused without the counts, and this went red on that.""" + out = pooled_statistics( + self._draws(), + sample_dims=["batch", "gcm"], + model_dims=["gcm"], + weight_col=None, + quantile_method="lower_step", + summation="fast", + ) + assert "n_models" not in out.columns and "n_members" not in out.columns def test_model_columns_that_are_not_pooled_are_refused(self): with pytest.raises(ValueError, match=r"model_dims \['target'\] are not among"): diff --git a/tests/unit/test_stats_methods.py b/tests/unit/test_stats_methods.py index 04613c5..5428ed0 100644 --- a/tests/unit/test_stats_methods.py +++ b/tests/unit/test_stats_methods.py @@ -292,29 +292,55 @@ def test_q0_and_q1_are_the_extremes_with_weight(self): ) assert list(got.values()) == [1.0, 3.0] - def test_a_member_with_weight_zero_is_never_returned(self): + @pytest.mark.parametrize("summation", ["fast", "exact"]) + @pytest.mark.parametrize( + "method, at_q64", [("lower_step", 20.0), ("inverted_cdf", 22.0)] + ) + def test_a_member_with_weight_zero_is_never_returned( + self, method, at_q64, summation + ): """A weights table can carry a model at weight zero to leave it - out. Of the members 1 to 33 the 21st has weight zero and the - 22nd reaches q = 0.64. "lower_step" returns the one before it, - 21.0, which the mean leaves out.""" + out. Of the members 1 to 33 the 21st has weight zero. Without it + the 22nd reaches q = 0.64, and "lower_step" returns the one + before, 20.0. "lower_step" returned 21.0, the member at weight + zero, which did not move the running share, and went red on it. + "inverted_cdf" left the member out before, and cannot go red by + reverting.""" values = np.arange(1.0, 34.0) weights = np.full(33, 1 / 32) weights[20] = 0.0 frame = _members(values, weights) + options = dict(quantile_method=method, summation=summation) - step = _pooled(frame, [0.64], include_mean=False) - assert step == {"q64": 21.0} - - got = _pooled(frame, [0.64], quantile_method="inverted_cdf", include_mean=False) - assert got == {"q64": 22.0} + got = _pooled(frame, [0.64], include_mean=False, **options) + assert got == {"q64": at_q64} # at no q, and exactly as if the member were not in the frame qs = [round(q, 3) for q in np.linspace(0.0, 1.0, 201)] - options = dict(quantile_method="inverted_cdf", include_mean=False) every = _pooled(frame, qs, **options) assert 21.0 not in every.values() assert every == _pooled(frame.drop(index=20), qs, **options) + @pytest.mark.parametrize("method", ["lower_step", "inverted_cdf"]) + def test_both_halves_drop_a_member_with_weight_zero(self, method): + """`summarize_samples` takes the window mean first and then the + same statistics.""" + weights = np.full(33, 1 / 32) + weights[20] = 0.0 + frame = _members(np.arange(1.0, 34.0), weights).assign(year=2050) + out = summarize_samples( + frame, + sample_dims=["draw"], + time_col="year", + window=(2050, 2050), + quantiles=[0.64], + weight_col="w", + include_mean=False, + quantile_method=method, + summation="fast", + ) + assert 21.0 not in out["value"].tolist() + def test_n_members_leaves_out_the_weight_zero_member(self): weights = np.full(33, 1 / 32) weights[20] = 0.0