diff --git a/CHANGELOG.md b/CHANGELOG.md index 023051b..4230cc0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,844 +2,78 @@ ## Unreleased -**A block whose peak did not rise above the resident memory before it no -longer counts as measured with a growth of zero.** The peak and the -resident memory before a block were read from `/proc/self/status` one -after the other. A process at its peak can show resident memory above -the peak read a moment before, and a block that then added nothing ended -with its peak equal to that resident memory, so it passed as having -raised the peak and was recorded with 0 bytes a kept row. Over a run of -such blocks the summary divided by that zero. The floors job met it in a -test whose single block ran in the test process, which was at its peak. -The two are now read at once, so the resident memory is never above the -peak it is read with, and a block has a growth only when its peak after -rose above both readings before it. - -**A leaf file keeps the target ids in the type the weights artifact -gives them, where it took strings alone.** The aggregate stage refused -every leaf of a product whose artifact has integer ids, with "id field -'ID_1' has dtype int64. A leaf file needs string ids", and those are the -GADM 2.0 artifacts behind every ADM1 and ADM2 product: `ir_adm1_full` -has `ID_1` as int64, `ir_adm2_full` and `ir_adm2_croparea_corn` `ID_1` -and `ID_2`. A stage check on the cluster met it in 22 seconds. Leaf -format version 2 takes ids that are strings or integers. An integer -keeps its width in the target table and in the leaf files, the ordinal -sorts integers by value and strings by code point, and the reduce stage -gives the ids back in the artifact's type, so its statistics have the -dtypes and the row order of stage all. The target digest is over the -field names, their types and the ids, so an integer 1 and a string "1" -are different targets and a leaf written from one is refused against the -other. The storage of a string is not part of it: `ir_adm1_full` stores -its strings as `large_string` and `ir_adm2_croparea_corn` as `string`, -and identical ids give one digest either way, where taking the storage -as the type would have refused a leaf of one against the other for -nothing anyone could act on. An integer's width is part of it, since an -int32 and an int64 id are different identities once the values outgrow -int32. Other id types, floats, booleans, categoricals, datetimes and -nullable integers among them, are refused. Leaves and target tables of -version 1 are refused with a message to write them again, and no product -wrote any, since every production config has `write_leaves = false`. - -**A weights config states every choice whose wrong value gives another -number, as the quantile method and the summation already do.** The rule: -a default that fails loudly when it is wrong is fine, and a default that -silently produces a different number is not. So these have no default -any more, and a config that leaves one out is refused naming it: -`normalization`, which was `"per_destination"`; `weights[].fallback`, -which was `"area"`; `weights[].kind`, which was `"point_sum"`; -`backend.coverage`, which was `"exact_fraction"`; -`regions.on_invalid_geometry` and `source.on_invalid_geometry`, which -were `"repair"`; and `grid.offset` and `grid.lon_convention`, which were -`"center"` and `"[-180,180)"`. The last two matter most. A grid at the -wrong offset or longitude origin still covers the regions, so the -weights came out on other cells with nothing said, the error the -BigQuery backend has refused for an edge-offset grid since #34. The area -weight takes neither `fallback` nor `kind`, since its total is the -region's own area and it reads no raster, and it refuses them as it -refuses a raster or table. - -The library's own copies of the normalization default follow what the -caller says. `WeightsArtifact.from_table`, `compute_native_weights`, -`apply_fallback`, `Manifest` and `OutputSchema` take it with no default, -and `WeightsArtifact.load` refuses a weights manifest that does not -record it, where it read one as `"per_destination"`. The warning when -the fallback fired often under a policy left unstated goes with that -default, `_IMPLICIT_DEFAULT_FRAC` and `_IMPLICIT_DEFAULT_MIN` too. It -announced that an unstated default had fired, and `weight_share` -measures how much of a target's basis contributed, which is the same -information. The BigQuery backend read a weight named `pop` from the -column `population` of its table and any other weight from the column of -its own name. That was one table's layout and not a rule, so a BigQuery -weight now declares `weights[].column` beside `weights[].table`, and a -local weight refuses one. - -Left alone, and why. `read_gmst` and `[stats.warming_levels]` keep -`time_col`, `value_col` and `sep`, because a wrong value there fails to -find a column and stops. `from_table` keeps recognising coordinate -columns by name, because it refuses ambiguity and checks the values -against the grid. And every default that refuses stays, -`on_null_geometry`, `on_unknown_id`, `on_zero_overlap`, `on_unmatched`, -`on_zero_weight` and `on_absent_from_data`, because a default that -refuses chooses nothing in silence. - -This breaks every weights config that relied on one of the defaults. The -configs and examples of this repository state the values their defaults -gave them, so none of their numbers moves. The recipes repository, -pinned on v0.5.0, needs the same keys when its pin moves, where it -already changes for the quantile method, the summation, the declared -members and the model weight names. The config hash a weights manifest -records changes for every config, the same values included, since a -weight now holds its column and the area weight no fallback or kind, so -a hash from an earlier run does not match one written now. So the config -an earlier weights manifest came from can no longer be found by hashing -candidate configs with this version, which refuses an old config for its -missing keys and hashes a completed one differently. It takes the -version that wrote the manifest, named in its package_versions, which -the published GADM weights give as segment_weights 0.1.0, the package's -former name. - -Regenerating the weights artifacts gives the same weights with new -manifests, since each config states the value its default gave. They are -regenerated before any product, because a product's run manifest records -the SHA-256 of both files of the weights it loaded, the manifest among -them, and a regenerated manifest records another config hash, so a -product made from the old weights would name a manifest that is no -longer published. Regenerating the GADM weights needs the GADM target -layers, which are not distributed and are rebuilt from the GADM sources -with `examples/gadm20/prepare_gadm20_targets.py` and -`examples/gadm41/prepare_gadm41_targets.py`. - -**Every block of a reduce is recorded, each worker's first block is -measured, and only the run's first block is judged, on Linux alone.** -Nothing is refused that was not before. A run then shows how much blocks -of one size vary from worker to worker, where one measured first block -could not. Each block's entry under `reduce.block_size.every_block` -gives the readings around it and its own growth or why it has none, and -`over_every_block` the spread of the measured blocks' bytes a kept row, -the heaviest measured block over the estimate and -`first_over_heaviest_measured`, the run's first block over the heaviest -measured one. A first block's growth is taken on Linux from the resident -memory before it, VmRSS of `/proc/self/status`, and on macOS from the -peak once the worker had set itself up. A worker's later block is -recorded without a growth, because a later block reuses memory its -worker already holds, so its growth is what it needed beyond an earlier -block and not its own footprint, and so is a block run in the process -that planned the run. Measured as they first were, such blocks gave -numbers that look like light blocks and are not, and a cluster run's -lowest, 52.2 bytes a kept row against a median of 220.0, was of that -kind. Whether the first block resembles the heaviest of all cannot be -answered by this measure, since the heaviest may be a block it cannot -measure. `first_over_heaviest_measured` says no more than the spread -between workers. The log line of each block gives its bytes a kept row -where it has them. - -**On Linux a worker's peak resident memory is read as VmHWM of -`/proc/self/status`, where it was `ru_maxrss`.** On Linux `ru_maxrss` -survives an exec, so a worker started by spawn read the peak of the -process that started it, and a block below that peak read nothing. Fork -starts it afresh, so runs on the cluster, which fork, were measured -right already, and what read blind was a test that asked for spawn. -VmHWM is the high-water mark of the process's own address space. On a -Midway3 compute node, RHEL 8 with kernel 4.18 and Python 3.11.12, it -started at the worker's own resident memory under spawn, fork and -forkserver, equal to VmRSS, and grew by the 150 MB a worker touched, -150.0, 150.3 and 150.0 MB. There the spawned worker's `ru_maxrss` -started at the parent's 419.9 MB and grew by nothing. macOS keeps -`ru_maxrss`, which a new worker starts afresh there. A first block whose -peak did not rise is still recorded as unmeasured, and on Linux that -should now be rare. Under fork the peaks a worker records count the -pages it shares with the process that started it, 319.8 MB at the start -of a worker whose parent held 300 MB, so they overstate what the worker -alone holds. That errs on the side of the budget, and the growth is -unaffected, 150.2 MB there. The manifest's measure says which reading -was taken. The aggregate stage reads its workers' peaks the same way, -where it took Linux's kibibytes for thousands of bytes. - -**A worker that dies stops the aggregate stage at once, naming the -leaves in flight and how the workers ended.** The leaves ran on a -`multiprocessing.Pool` that renewed each worker after 16 leaves, and a -worker that died outright, killed by a signal such as the kernel's for -memory or ending as its setup raised, left the pool waiting for ever for -the leaf it held. The leaves now run on a `ProcessPoolExecutor` under -the platform's own start method, fork on Linux, in waves of 16 leaves a -worker with new workers for each wave, and no more leaves are handed out -than there are workers. A death raises with the leaves in flight and the -workers' exit codes, and no statistics are written. Leaf files already -written are kept, and the leaves manifest is left incomplete. Any other -error that stops the run, such as a leaf written with other columns, now -waits for the leaves in flight to finish, where the pool killed them. -The reduce stage said a dead worker was most likely killed for memory, -whatever ended it. It now gives the exit codes, and speaks of the memory -budget only when a worker was killed by SIGKILL. A worker whose setup -raised exits with code 0 and logs the traceback, and is said to. The -waves cost half a second to a second on the leaf benchmark, 384 leaves -at an eighth of the size on 8 workers under spawn on macOS. Over two -runs of it, the wall time not spent on leaves, the wall less the leaves' -own seconds over the workers, was 3.5 to 5.1 s with the pool and 4.4 to -6.2 s in waves, on walls of 23 to 69 s that moved more than that from -run to run. Fork on Linux was not measured. - -`window_means` takes the rows of each window once, looks for an -infinite value without copying the rows of the windows, and builds the -frame of the group keys once, where it did all three for every window. -On the benchmark leaf of 4.26 million rows it takes 11% less as the -pipeline calls it, and up to 29% less with the level labels on the -frame. No number moves. Every call the test suite and the benchmarks -make gives what the former code gave, to the bit, with the same row -order and dtypes, and every refusal the same text. - -**The first block of a reduce is measured, and on Linux a run sized by -the estimate is refused when the measurement is more than 1.25 times -it.** The blocks are sized from an estimate of the bytes a kept row -takes, 240 and 40 for each dimension of a leaf, calibrated once on the -resident memory of a worker on macOS. On real data on Linux, in the -stage check's reduce of labor ADM1 under rcp45, whose leaves have no -dimension, the first blocks of sixteen workers read 218.62 to 223.05 -bytes a kept row, so 240 covers them by 1.076. The first block is now -built alone in a worker of its own and measured as the growth of the -worker's peak resident memory over the block, from the peak once the -worker has set itself up, so that what a worker holds for every block is -left out. The manifest records the estimate, the measurement and the -setup peak side by side under `reduce.block_size`. On Linux a first -block that keeps 100,000 rows or more and takes more than 1.25 times the -estimate stops the run before any other block, with nothing written, and -one that keeps fewer is recorded and not judged. It is a tolerance on -the first block standing for the others, not a correction of the -estimate. Every block is of one size and does the same work, and on real -data, on Linux, the first blocks of sixteen workers read 218.6 to 223.1 -bytes a kept row, within 2% of one another. On macOS one synthetic first -block, measured in one fresh worker after another, read from a fifth of -the estimate to nine tenths of it, for a cause not found, and memory -sampled through the block peaked where the measure did, so the spread is -in what the block holds resident and not in the reading. So on macOS the -measurement is recorded and not judged, and -`reduce.block_size.not_judged_here` says why, since a refusal there -would be one against noise. The manifest records the factor beside the -measure. On one worker the block runs in the process that planned the -run, whose peak cannot be put down to it, and a worker whose peak did -not rise over the block says nothing of it either. Neither has a -measurement or a judgement, and the manifest says why, and which start -method the workers had. The peak a worker logs is read in bytes on macOS -and kibibytes on Linux, where Linux's was taken as thousands of bytes. -New: `[reduce.pandas] targets_per_block` declares the size of a block in -place of `memory_gb`. It warns, and the manifest records the size as -declared. - -**A histclim file with rows its leaf does not have is refused, naming -the first row and the regions or years the file alone has.** The two -are one projection under two climates, so a row in one alone means the -other is incomplete. The rows were dropped with nothing said, while a -leaf row the histclim file lacked was refused already. - -**A region left out for an invalid geometry is recorded as skipped, -apart from the regions repaired.** Under `on_invalid_geometry = "skip"` -the manifest listed the regions it left out as `repaired_geometry_regions`. -It now lists them as `skipped_invalid_geometry_regions`, with -`skipped_invalid_geometry_count`, and the source units as -`skipped_invalid_geometry_source_units`, and `RegionSet` carries them as -`skipped_invalid_ids`. In the four published artifacts checked, every -region listed as repaired has its rows. - -**A `gs://` regions path passes the input check, and its bytes are -hashed into the manifest as a local file's are.** The reader took such a -path already, and the check refused it. The manifest had no hash of a -remote regions file. Reading one needs gcsfs, which the `[bigquery]` -extra installs, and a remote file in a format other than Parquet is -copied to a temporary directory first. - -**`aggregate_gradient` takes `weight` with no default, and finds the -regions in the weight file's source key column.** It defaulted to -population, and read a column called `hierid` whatever the artifact's -source key was. The resident memory the pipeline logs counts pages of -the size the machine reports, where it took them as 4096 bytes. - -**A model takes the row of its own name in a model weights table, -letter for letter, or the row declared for it, and a model with -neither is refused.** Before, the library dropped `surrogate_` from the -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 -holds. `"lower_step"` reproduces the historical extraction tool, one -member below `"inverted_cdf"`, and is biased low. - -New: `fetch_model_weights(rcp)` gives the published climate model -weights of an rcp from their Zenodo record, checked and cached, so -products stop reading the table from paths of their own. New: -`regroup` takes a reduced frame to coarser targets, a sum or a mean -weighted by `target_basis`, before the statistics are pooled, as the -country files are made from the states. - -**Where the statistics carry their counts they carry two, the samples -behind a row in `n_members` and the climate models among them in -`n_models`.** A warming level bin of four models over fifteen batches -holds 60 samples, and the file now says both. `n_models` is the -distinct values of `model_dims`, which `summarize_samples` and -`pooled_statistics` take beside `include_n_members` and a pipeline -config sets as `stats.model_dims`. It has no default and is required -wherever counts are written, warming levels and a reduce of fewer -leaves than were aggregated among them. - -The mortality paper's temperature table and the Inequality Paper's bins -are under `data/external/`. The warming level settings of the CMIP5 -models are `examples/warming_levels/ar5_cmip5_smme.toml`, with a README -that says where each number comes from. The test of the paper's bins -and the France example both read that file, and `load_warming_levels` -reads such a file on its own. The example's section 8 reads it unless -`FRANCE_WARMING` names another, and always runs. - -**A run declares which members join a warming level, and nothing in -the library reads a member's name.** `assign_warming_levels` takes -`members`, the members that join, with no default, and -`[stats.warming_levels]` takes `join`, `"declared"` for every member -the tree declares or a table of member columns to the values that -join, also with no default. `members_that_join` turns one into the -other. A member of the table that does not join is at no level, and -the record lists it under `excluded` with the reason. A value listed -to join that no member of the tree holds is refused by name, and so -are a member that joins with no row or short of a year, and a member -the tree declares with no row. A member of the table with no values -that does not join no longer stops a run. - -**An infinite member value is refused under every quantile method and -`summation`, and a statistic is refused when it comes out infinite, -other than the `-inf` of `"lower_step"` at or below its first step, -which is now written under either sum.** Before, `summation="exact"` -and `"inverted_cdf"` refused every infinite statistic, the step's -`-inf` among them, while `"linear"` and `"lower_step"` with the fast -sum returned infinities that came from the data. `summation` now says -how a mean is summed and nothing else. `window_means` refuses an -infinite value in a window, where it passed an infinite mean on. - -**Every row `apply_weights` returns carries `weight_share`, the share -of its target's weight basis behind the value, and the targets the -weights have that are not in the output are listed with their reason -in `AppliedResult.targets`.** Before, a target with no weight, such as -a unit with no crop area for a crop, was absent from the output with -nothing saying so, and a target short of a source region was averaged -over what it had with nothing on the row. A pipeline statistics file -has the column too, and its manifest and the leaves manifest list the -targets under `target_coverage`. A leaves manifest written before is -not reduced, and its leaves have to be aggregated again. A target whose -rows all have a weight of zero is now left out for "no weight", where -it came out as NaN. An extensive sum over no value is NaN, where it was -0. The warning for skipped source units said they were recorded in the -manifest, and `apply_weights` is given none. It now says they are in -the coverage of the result. - -**`stats.model_weights` and `stats.warming_levels.gmst` given as -relative paths now resolve against the directory of the pipeline -config, as `weights.dir`, `tree.root` and `output.dir` do.** They -resolved against the directory the run was started in, so a config -that relied on that has to give the path from its own directory. - -**The rows of a pipeline statistics file, and of the reduced file, -come in a new order. No value changed.** **`quantile_method` and -`summation` are new, have no default, and have to be given: in every -call of `summarize_samples` and `pooled_statistics`, in every call of -`window_means` for `summation`, and under `[stats]` in every pipeline -config.** Files made before v0.6.0 are reproduced by -`quantile_method = "lower_step"` if the run had model weights and -`"linear"` if it had none, with `summation = "fast"`, those without -weights to the last bit in about 99 quantiles in a hundred. -`window_means` and `summarize_samples` compute in float64 and return -float64 whatever the dtype of the value column. That changes their -result for a float32 or a nullable column under every setting. -A model weights table with two rows for one model is now refused, and -the pipeline manifest records the weights each run used. -A tree level named like a column the pipeline writes itself is refused -before any leaf is read. -**`output.write_leaves` now defaults to false, and an aggregated leaf -is written in a new layout under a new name.** Leaf files of the old -layout are left where they are and are not read. -A new stage, `reduce`, takes the statistics from leaves written before. -A new option, `stats.time_reduction`, says what is done with the years -of a member: averaged over a window first, pooled with the models and -the draws, or kept, one row a year. -New: `assign_warming_levels` gives each member of a temperature table -its warming level in a calendar period. - -- Changed: the pipeline sorts the statistics rows before writing them: - by statistic in the order requested (the mean, then the quantiles as - listed), then by each tree level that is not pooled, in the order - `tree.expect` declares its values, then by window in the order of - `stats.windows`, then by the remaining id columns ascending. The - reduced file of `output.write_reduced` is sorted the same way, over - all its tree levels. Before, the rows of both followed the order the - leaves were pooled in, which with several workers is the order the - workers finish in, so two runs of one config could list the same - rows differently. A run with one worker usually listed them this way - already. The frame `run_pipeline` returns is sorted the same. -- New: `quantile_method` on `summarize_samples` and - `pooled_statistics`, and `stats.quantile_method` in a pipeline - config. It names a computation. `"linear"` interpolates between - members, as pandas does, and is refused with weights. - `"lower_step"` returns the member just before the one whose - cumulative weight share reaches q, one member below the standard - inverse, as the historical extraction tool did. Without weights - every member counts the same, which is what that tool did when told - to use no model weights. `"inverted_cdf"` is the standard inverse of - the empirical distribution (Hyndman and Fan type 1): the smallest - member value whose cumulative weight share reaches q. It is one - definition with or without weights, and every quantile is the value - of a member with positive weight. - It has no default. Earlier releases had no such option and used - `"lower_step"` with weights and `"linear"` without. A pipeline - manifest records the value. - Three things follow from `"lower_step"`. A quantile is `-inf` when - the first member already reaches q. The value of a member with - weight zero can come back as a quantile, although the mean leaves - that member out: with one such model among 33, about 3% of the cells - of each quantile on synthetic samples. And at 0.5 with equal weights - it switches to the midpoint of the two middle members. -- New: `summation` on the same two functions and on `window_means`, - and `stats.summation` in a pipeline config. It has no default. - `"fast"` is the vectorised sum of pandas and numpy, which is what - earlier releases used. `"exact"` takes the window means and the - pooled mean from exactly rounded sums (`math.fsum`), so the order of - the rows cannot change them. Under `"fast"` the order can change the - means, and in a pipeline run with several - workers it does, because the leaves are pooled in the order the - workers finish. Two runs of one config over a synthetic tree (240 - leaves, 8 workers, model weights) disagreed in the last bits of - about a third of the means, 119 to 133 of 388, by at most 8.9e-16 on - values of order 1. Without model weights 2 of 388 differed. No - quantile differed. -- Under `"inverted_cdf"` or `"exact"` a statistic that comes out infinite raises - instead of being returned or written: in impact data an infinity - means something upstream broke. It is the statistic that is checked, - so an infinity in a year no window covers does not fail a run, and - one that a quantile selects does. NaN is left alone; a group with no - value has no statistic. Under `"exact"` a sum over infinities of - both signs, or one that overflows, raises too. `"linear"` and `"lower_step"` - with the fast sum return whatever comes out, `-inf` included, as before. -- Changed: `window_means` and `summarize_samples` take the window mean - in float64 and return the value column as float64, under every - setting and whatever the column's dtype. A float64 column gives what - it gave, to the last bit. Two things change for other columns, under - every setting: - - A nullable `Float64` column used to come back nullable. It now - comes back as float64 with NaN where it had no value: the mask is - gone. A caller that tested the result for `pd.NA` has to test for - NaN. - - A float32 column is widened before the mean, so its results differ - from the old ones from the seventh or eighth digit (by up to 9e-7 - of the value on synthetic samples). The pair that reproduces - earlier releases therefore no longer does so bit for bit for a - float32 column. The - other choice was to keep seven digits, and under `"exact"` to round - an exactly rounded sum back to float32. - - Before, the dtype and the precision followed the column, the pandas - version and, on the newest pandas, the data. `window_means` returned - a float32 column as float32 through pandas 3.0 (seen on 2.3.3 and - 3.0.3). On pandas 3.1.1 with the fast sum it returned float64 for a - column with no missing value and float32 for one with a missing - value, in the cases tried, and float32 under `"exact"`. - `summarize_samples` took its window means in float32 where - `window_means` returned float32, and under `"exact"` on every - version. - - This reaches callers of the library, not the pipeline's published - files. A pipeline run that applies weights or subtracts a second - file (`tree.subtract_filename`) already hands `window_means` - float64. Only a passthrough run with no subtraction hands over the - leaf's own dtype, and no production config is one: of the 110 - pipeline configs in the impactmap-data-gen repository 42 are - passthrough runs (the impact-region products of agriculture, labor - and mortality), and all 110 subtract a histclim file. - - One published product changes on a rerun: energy as a share of GDP - at ADM0, `energy/adm0/energy_valued_pctgdp_rcp45.parquet` and - `energy_valued_pctgdp_rcp85.parquet`. The script that makes it, - `energy/run_energy_regionalization.py` in impactmap-data-gen, calls - `window_means` itself on its denominator: GDP stored as float32, - summed by country and year, still float32. In the pinned cluster - environment (pandas 3.0.3) the window mean of those sums came back - float32; it is now taken in float64. Of the 1,012 denominators (253 - countries, four windows) 703 move, by 1.5e-8 of their value at the - median and 9.1e-8 at most, and the shares move by as much. The - one-year window does not move. This is float32 rounding in a mean - of twenty numbers, not the repair of a large error: the sums by - country are compensated, were within 9.4e-8 of the exact sums, and - are float32 before and after. -- The pipeline manifest records `quantile_method` and `summation`. -- New: `read_model_weights` reads a climate model weights table and - returns a `ModelWeights`. The file is read once, and the SHA256 it - 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. - 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 - 16 leaves, so the file was read all through a run. A file edited - during a run can no longer give different leaves different weights. -- The pipeline manifest gains `model_weights_record`, next to the - `model_weights` path it already had. It holds the path, the SHA256 of - the file, `members`, and `unmatched_rows`. `members` has each model - that a leaf was actually given the weight of, with the table row it - matched, the weight and the number of leaves. That is what ran, not - what the config declares, so a model whose leaves were all excluded - is not in it. `unmatched_rows` has the rows no leaf matched, with - their weights. The two together are the whole table, so a run can be - repeated from its manifest when the file is gone. A run without - model weights records `null`. No statistic changes. -- Changed: the pipeline puts the tree level labels on a leaf's rows - after the window means are taken. Before, it put them on the leaf - first, where `apply_weights` and `window_means` grouped every row by - them. On the benchmark leaf (4.26 million rows after the weights) - `apply_weights` took 2.7 s with the labels and 1.1 s without, and - `window_means` 0.46 s against 0.24 s. No file changes for it. The - statistics, the reduced file and the leaf files keep their columns, - column order and values. -- Changed: a tree level named `window`, `statistic`, `n_members` or - `model_weight`, or like an id field of the weights artifact, is - refused before any leaf is read. A level becomes a column of the - output, and those names are columns the pipeline writes itself. - Before, `window` and `statistic` were refused leaf by leaf, after - every leaf had been read, and the name of an id field failed every - leaf with an error that gave only the name. A level named `n_members` - or `model_weight` ran when `stats.include_n_members` and the model - weights were off, and its values sat in a column of that name. -- Changed: `output.write_leaves` defaults to false. It defaulted to - true, so a config that did not set it wrote every aggregated leaf, - about 35 MB for the benchmark ADM2 leaf. A config that wants the - leaves has to say so. The four `mortality_adm{1,2}_rcp{45,85}` configs under - `examples/montecarlo/runs` set it to true and now write the new - layout. -- Changed: an aggregated leaf is written as - `leaves//.aggregated.parquet`, where `` is - `tree.filename` without its extension. Before, it was - `aggregated_`, parquet whatever the extension said. - The new file is plain parquet with a fixed Arrow schema and no - pandas metadata: - - Its columns are an int32 `target_ordinal`, the id fields, the - leaf's own dimensions and the value. The tree level labels are no - longer columns. They are in the path and in the footer. - - Its rows are sorted by target and cut into row groups of 128 - targets. A group holds the same targets in every leaf and is empty - where a leaf has none of them. `leaves/targets..parquet` - gives the target of each ordinal, which is its rank among the - artifact's id tuples sorted ascending. - - Its footer holds, under the key `cil_regionalization.leaf`, the - layout and what made the leaf: weight, kind, data version, value - column, policies, file names, level names, the versions and the - SHA256 of the two files of the weights artifact, the leaf's level - values and its source files. - Files of the old layout are not deleted, rewritten or read. A - passthrough run keeps writing the file it wrote, labels included, - because without weights there are no targets to lay a leaf out by. -- New: `leaves/.leaves.manifest.json`, written when - leaves are. It lists every leaf in the order the config declares - them, with its source files, rows, coverage, mass balance, size and - SHA256, the rows in each row group summed over the leaves, and the - rows at each value of each numeric dimension. It holds what made the - leaves and nothing from `[stats]`. It is written before the first - leaf with `"complete": false` and again when every leaf has - succeeded. A run that would write a leaf listed in the manifest of - another stem in the same directory is refused, whether that other - run finished or not. Before, two such runs wrote over each other's - leaves without a word. -- New: `--stage aggregate` on `cilreg pipeline` and on - `python -m cil_regionalization.pipelines.montecarlo`, and `stage=` on - `run_pipeline`. It writes the leaves and their manifest and stops. - It needs `output.write_leaves = true` and `[weights]`, reads nothing - from `[stats]`, and returns a result whose `stats` is `None`. The - default, `all`, runs everything as before. -- Changed: when leaves are written, a leaf's own dimension has to be - an integer, a float, a boolean or a plain string, and the id fields - have to be strings. A categorical, datetime or nullable dimension is - refused by name, because pandas 2 and pandas 3 write those - differently. A tree level named `target_ordinal` is refused like the - other names the pipeline uses. -- New: the pipeline hashes the two files of the weights artifact when - it loads them, in the parent and in every worker. A worker that - loaded other bytes than the run started with fails its leaves. The - statistics manifest gains `artifact_sha256`, `stage` and - `leaves_manifest`. -- New: `--stage reduce`, and `stage="reduce"` on `run_pipeline`. It - takes the statistics from the leaf files a run of `aggregate` or - `all` wrote, and opens neither the source tree nor the weights. - Everything under `[stats]` can differ from the run that wrote the - leaves, so other windows cost one pass over the leaf files. - - It pools one block of targets at a time. `[reduce.pandas] - memory_gb` is what all its workers may hold together and has no - default. `[reduce.pandas] n_workers` defaults to `run.n_workers`. - The dry run prints the blocks and the file opens the budget gives. - A budget that does not fit one row group a worker is refused, with - the smallest that would run. - - It gives the same bits whatever the number of workers, under - the `"fast"` sum too, because a block pools its leaves in the - order the config declares them. `all` with several workers still - pools them in the order the workers finish. - - Under `summation = "exact"` it gives what `all` gives on one - worker, to the last bit, whatever the size of the blocks, with - any `quantile_method` and with or without model weights. - - Under the `"fast"` sum it gives the same, to the last bit, on - leaves without missing values. On leaves with them it can differ - from `all`, and between two block sizes, in the last bit of a - window mean. The cause is pandas' own mean, which `"fast"` is: - on pandas 3.1.1 a missing value in one group of a frame changes - the mean of other groups (92 of 400 groups in a test, by 4e-17), - and a block holds part of a leaf where `all` holds all of it. - pandas 2.3.3 and 3.0.3 do not do this. `"exact"` does not depend - on what else is in the frame. - - `output.leaves_stem` names the leaves to reduce. It is - `output.stem` unless set, and it also names the leaves manifest - the other stages write. - - Before any work the leaves are checked against their manifest. - What aggregated them has to be what the config says, field by - field, and a difference is refused by name. The weights artifact - is hashed if it is where the config says, and refused if it is not - the one the leaves were made with. A path that differs is not a - reason to refuse: the run warns and records it. Each leaf file is - checked by its size before work and by its footer, its row groups - and its ordinals at every open. - - `--verify-leaves` hashes every leaf file against the manifest - first. It is off by default because it reads every byte of every - leaf. Without it a file changed in place, with the same size and - footer, is not noticed. - - Fewer leaves than were aggregated can be reduced, with a narrower - `tree.expect` or a longer `tree.exclude`. The manifest lists the - leaves left out, and `n_members` is then written whether - `stats.include_n_members` asks for it or not. - - `output.write_reduced` is refused under `reduce`, and so is a - config without `[weights]`. - - The statistics manifest records the stage, the backend with its - options and the versions of pandas, numpy and pyarrow, the blocks, - the SHA256 of the leaves manifest, and whether the leaves were - verified. -- New: the `reduce` package. The pipeline asks a backend for the - statistics of a set of leaves with a `ReduceRequest`, and - `[reduce] kind` picks the backend. `"pandas"` is the only one. A - request gives each leaf its own windows, a label with a first and a - last time value, so two leaves can give one label different spans. - Every config gives every leaf the same list today. If the windows of - a request do differ between leaves, `n_members` is written. - `tests/integration/test_reduce_parity.py` holds the comparison a - second backend has to pass. -- Changed: a leaf whose columns differ from the first leaf's stops the - run when it arrives. Before, the run wrote every leaf and found out - at the end. -- New: a run that writes leaves prints how many files under `leaves/` - are in no leaves manifest there, with their total size, and `reduce` - prints it too. Nothing is deleted. -- Fixed: the row sort of the statistics picked rows by the label of - their index, so a frame whose index repeated came out with rows - repeated. No run of the pipeline built such a frame. -- The pipeline writes a statistics file and its manifest under a - temporary name and renames them, the manifest last. -- New: `stats.time_reduction` in a pipeline config, with no default: - `"window_mean"`, `"pooled"` or `"per_year"`. `"window_mean"` is what - every release so far has done. Under `"pooled"` no window mean is - taken. Every year of a member - inside a window is a member of the sample, so the statistics are - over models, draws and years together, and a year inside two windows - is pooled in both. A model weight applies to each member-year. A - member that lacks years has fewer rows and counts for less. On a - tree where every member has every year, the mean is the mean of the - window means up to rounding, and the quantiles differ. - The pooled rows are the leaves' own rows, so the statistics come - from the leaf files by blocks under every stage. Stage `all` then - writes the leaves and reduces them. It needs - `output.write_leaves = true` and `[reduce.pandas] memory_gb`, and - refuses to start without them. If its second pass fails, the leaves - stay and `--stage reduce` runs from them. `output.write_reduced` and - a run without `[weights]` are refused, and so is `stats.time_col` - among `stats.sample_dims`. -- New: under `"per_year"` no window mean is taken and the year is - kept. The statistics are over the members within each year from the - first to the last of `stats.years`, which replaces `stats.windows`, - and the file has an integer `year` column where the others have - `window`, sorted where the window is. A year a member lacks is left - out of that year's statistics and shows in `n_members`. It runs from - the leaf files under every stage, as `"pooled"` does, and is refused - with warming levels, since a level is reached over a period. With one - window a year, `"window_mean"` gives the same statistics, to the bit, - under another column name. -- New: with `"pooled"` and `stats.include_n_members` the statistics - file has an `n_sample` column after `n_members`. `n_sample` is the - member-years behind a statistic. `n_members` keeps its meaning, the - members behind it: those with a value in the window and, with model - weights, a weight above zero. Without `"pooled"` no file gains a - column. -- A config with `stats.pool_years`, a boolean an earlier build of this - release had, is refused with the value of `stats.time_reduction` to - write. -- Changed: a tree level named `n_sample` is refused before any leaf is - read, as `n_members` is. -- The pipeline manifest records `time_reduction`, and `years` for a - product per year. A run of stage `all` that pools or keeps the years - writes the manifest the reduce stage writes, with `"stage": "all"`. -- New: `ReduceRequest.time_reduction`, and `ReduceBackend.check_options`, - which the pipeline calls before it aggregates anything. -- Changed: the pandas reduce backend plans a block at 240 bytes for a - row it keeps and 40 more for each dimension the leaf has of its own, - where it planned 130 for any leaf. For one memory budget the blocks - hold about half the rows they held, or fewer for a leaf with - dimensions, so a reduce opens each leaf about twice as often. The - resident memory of a worker grew by up to 155 bytes a kept row on - leaves with no dimension and by 168, 194 and 218 with one, two and - three, on synthetic leaves on macOS, and 130 left nothing over that. - The new figures cover each by half again or more on macOS. On real - data on Linux a kept row of a leaf with no dimension later took up to - 223.05 bytes, which 240 covers by 1.076, not by half again. The dry - run prints the figure it used, and the manifest has it as - `reduce.bytes_per_row` next to `reduce.max_worker_peak_gb`. -- New: `read_gmst`, `assign_warming_levels`, `GMSTTable`, `Period`, - `WarmingLevels` and `LevelWindow`, in `cil_regionalization.warming_levels` - and at the package root. A member is one series of global mean - temperature, named by any columns of the table. Its series is - rebased to a reference period, an offset is added, and its mean over - a period's years picks the level whose band holds it, both ends of a - band included. A mean in no band gives no level. Two bands may share - an end, where the level declared first wins, and may not overlap. - The reference period, the offset, the levels, the half-width, the - periods and a statement of how the series was smoothed have no - default, and a call without one of them fails. A period carries the - years the temperature is averaged over and the years of the impacts - separately. Nothing is smoothed. Names are matched as written. - `WarmingLevels.record` is the manifest - entry: the table's hash, every setting, each member's mean and level, - the count at each declared level and the members with none. The - pipeline does not use any of this yet. -- New: a cell of `tree.exclude` takes `"*"` for every value of a - level, so a model that one scenario lacks is one line and not one - line for each batch, socioeconomic model and scenario. A cell of - stars alone is refused. The manifest records the cells as written. -- New: `[stats.warming_levels]` in a pipeline config, in place of - `stats.windows`. The statistics are over the members at a warming - level in a period, with the levels from `assign_warming_levels`. A - leaf's member is read off the tree levels named in `member`, so no - level name is built in. Each period gives the years the temperature - is averaged over and the years of the impacts separately. The - statistics file gains a `warming_level` column next to `window`, and - two counts on every row: `n_members`, the draws behind a statistic, - and `n_bin_members`, the distinct members of the temperature table - behind it. A level nobody is at has no row and is in the manifest - with a zero. The statistics come from the leaf files under every - stage, so stage `all` writes the leaves and then reduces, and the - reduce stage gives other levels, periods or the other reduction - from the same leaves. `stats.time_reduction` chooses between - collapsing each member's window first and pooling its years, and - `"per_year"` is refused with warming levels. - Refused: a config without `reference_period`, `offset`, `levels`, - `half_width`, `smoothing` or `periods`; `stats.windows` or - `stats.model_weights` next to it; a member column that is not a tree - level or is not pooled; a run without `[weights]`; - `output.write_reduced`; a declared member with no row in the table, - before any leaf is read; and a leaf that lacks a year of an impact - span its member is pooled over, as a row or as a value. The manifest - has the whole record under `warming_levels`. A run without warming - levels writes `"warming_levels": null` and is otherwise unchanged. -- New: `LeafRequest.bin_member`, `ReduceRequest.include_n_bin_members` - and `ReduceRequest.whole_spans` in the `reduce` package. -- Changed: a tree level named `warming_level` or `n_bin_members` is - refused before any leaf is read. -- Changed: `stats.windows` may be left out when `[stats.warming_levels]` - is set. A config with neither is refused, as it was. -- Changed: `quantile_method="linear"` is computed by numpy, so its - quantiles are those of `numpy.quantile(method="linear")` and of - xarray's `.quantile` to the last bit, and so those of the Inequality - Paper's valued path. Before, pandas computed them. The definition is - the same, and pandas' arithmetic differs from numpy's in the last - bit of about one quantile in a hundred on synthetic samples, up to - 256 units in the last place next to zero. Where numpy's - interpolation meets an infinite member it gives NaN, even for the - median of 1, 2 and an infinity, where pandas gave 2. Such a quantile - is refused, naming the group, rather than written as a NaN that - would read as a group with no value. -- Changed: under `summation="exact"` the weighted quantiles of - `"lower_step"` and `"inverted_cdf"` take their cumulative weight - shares from exact sums, each share their ratio rounded once, and - `"lower_step"` takes equal values in order of weight, as - `"inverted_cdf"` already did. Before, a share that equals q in exact - arithmetic could land a bit either side of it, depending on the order - the weights were added in, and then decide the quantile: about one in - a few hundred on weights of 0.1 to 0.7. And within equal values the - step depended on which member came first, so on the order of the rows, - 1 in one order and `-inf` in another on six members. Without weights - nothing changes. On 2,880 members a group the step costs what it did - under `"exact"`, about 1.3 ms, and the weighted standard inverse 1.2 ms - where it took 0.6 ms. `summation="fast"` is unchanged. -- Changed: `"lower_step"` sorts a group once for all its quantiles, - where it sorted it once a quantile. The values are the same, and under - `"fast"` the step is about three times faster on large groups. -- Fixed: a refusal raised while a reduce block is pooled named the - target by its ordinal in the leaf file. It names it by its id fields, - as the statistics file does. -- Changed: the lowest pandas the package declares is 2.1, up from 2.0. - On pandas 2.0 a grouped sum or mean of an infinite value is NaN, so a - statistic that is infinite came back as NaN, and a refusal of an - infinite statistic was never reached. The lowest version of every - dependency the package declares is now installed and tested on every - push, on Python 3.10. -- Fixed: `cross_backend_compare` and `legacy_compare` needed pandas 2.2 - to classify a region, although the package declared 2.0. -- Fixed: the data scripts of `examples/energy` and `examples/labor` - failed with a NameError when they copied the SMME weights. -- New: `examples/france/`, the whole chain in one marimo notebook, for - mortality in metropolitan France. It builds weights on ADMIN EXPRESS - boundaries, compares them with the published GADM weights, applies - them three ways, and runs the pipeline for the three time reductions - and the warming levels. The test suite runs it on synthetic data. - The `[examples]` extra adds marimo, and CI installs it. -- New: `docs/reference.md` lists every public name with its signature - and its docstring, and every key of the weights config and of the - pipeline config with its type and its default. `docs/make_reference.py` - writes it from the package, and the test suite fails when it is out of - date. The README opens with what the library does and where each task - is described, and installing comes before the first example. +- Every statistics file has a `plain_median` column, true where `lower_step` took an ordinary median at the 50th percentile because every member counts the same. + A reader that takes the columns by position has to take them by name. +- Statistics whose quantiles are out of order are refused and never written. +- The reduce measures the memory of each worker's first block from VmHWM on Linux and records every block in its manifest. +- Leaf files keep integer target ids as integers instead of refusing them. + Leaves and target tables written in leaf format version 1 are refused and have to be written again. +- A weights config has to state `normalization`, `weights[].fallback`, `weights[].kind`, `backend.coverage`, `on_invalid_geometry`, `grid.offset`, `grid.lon_convention` and a BigQuery weight's `weights[].column` because none of them has a default now. + Weights made before have to be regenerated and a call to a library function that takes a normalization has to pass it. +- A worker that dies stops the aggregate stage at once and names the leaves it held. +- `window_means`, the labelling of a leaf in the pipeline and the quantiles of `lower_step` take less time and give the same results. +- On Linux a reduce is refused when its first block takes more than 1.25 times the memory it was planned at. +- New: `[reduce.pandas] targets_per_block` sets the size of a block in place of `memory_gb`. +- A histclim file with rows its leaf does not have is refused. +- A region left out for an invalid geometry is listed as skipped instead of repaired. + A reader of the manifest has to read it under `skipped_invalid_geometry_regions`. +- A `gs://` regions path passes the input check and its bytes are hashed into the manifest. +- `aggregate_gradient` takes `weight` with no default and finds the regions in the weight file's source key column. +- The memory the pipeline logs counts pages of the size the machine reports. +- A model takes the row of its own name in a model weights table or the row declared for it and a table that names a model twice is refused. + The published SMME tables need their rows declared as `examples/model_weights/` does. +- A model at weight zero is left out of every quantile as it was left out of the mean. +- `UnweightedModelWeightsWarning` is given when `model_dims` names the climate model and no weights are set. +- No setting of one cluster or one cloud account has a default. + A config for SLURM or BigQuery has to state its queue, cores, memory, walltime, project and dataset. +- The BigQuery backend refuses a grid with the edge offset. +- New: `read_model_weights` reads a climate model weights table and `fetch_model_weights(rcp)` gives the published one from its Zenodo record. +- New: `regroup` takes a reduced frame to coarser targets before the statistics are pooled. +- Statistics with counts have `n_members` for the samples, `n_models` for the climate models among them and `n_sample` for the member-years when the years are pooled. + `stats.model_dims` has to be set wherever counts are written. +- New: warming levels, with `[stats.warming_levels]` in place of `stats.windows`, `read_gmst` and `assign_warming_levels` in `cil_regionalization.warming_levels`, and the CMIP5 settings in `examples/warming_levels/` and `data/external/`. +- A run declares which members join a warming level and the library reads no member's name. + `assign_warming_levels` takes `members` and `[stats.warming_levels]` takes `join` with no default. +- An infinite member value and an infinite statistic are refused under every setting apart from the `-inf` of `lower_step` at or below its first step. +- Every row `apply_weights` returns has `weight_share` and the targets left out are listed with their reason, a target with no weight among them. + Leaves aggregated before have to be aggregated again. +- An extensive sum over no value is NaN where it was 0. +- `stats.model_weights` and `stats.warming_levels.gmst` given as relative paths resolve against the directory of the pipeline config. + A config that relied on the directory the run started in has to give the path from its own directory. +- The pipeline sorts the rows of the statistics file and of the reduced file before writing them. +- New: `quantile_method` with `"linear"`, `"lower_step"` or `"inverted_cdf"` and `summation` with `"fast"` or `"exact"` on `summarize_samples`, `pooled_statistics`, `window_means` and under `[stats]`, with documentation that says which method estimates a quantile. + Every call and every pipeline config has to give both. +- `window_means` and `summarize_samples` take the window mean in float64 and return float64 whatever the column's dtype. + A caller that tested the result for `pd.NA` has to test for NaN. +- The pipeline manifest records `quantile_method`, `summation`, `time_reduction`, `years`, the weights each run used under `model_weights_record`, `artifact_sha256`, `stage` and `leaves_manifest`. +- The pipeline reads the model weights file once and hands its rows to the workers. +- A tree level named `window`, `statistic`, `plain_median`, `n_members`, `n_sample`, `n_models`, `n_bin_members`, `warming_level`, `weight_share`, `model_weight`, `target_ordinal` or like an id field of the weights artifact is refused before any leaf is read. + A config with such a level has to rename it. +- `output.write_leaves` defaults to false. + A config that wants the leaves has to set it. +- An aggregated leaf is written as `leaves//.aggregated.parquet` in a new layout listed in `leaves/.leaves.manifest.json`. + Leaves of the old layout are not read and have to be aggregated again. +- New: `--stage aggregate` writes the leaves and their manifest and stops. +- When leaves are written a leaf's own dimension has to be an integer, a float, a boolean or a plain string. +- The pipeline hashes the two files of the weights artifact in the parent and in every worker. +- New: `--stage reduce` takes the statistics from leaf files written before through the new `reduce` package and its `"pandas"` backend. +- A leaf whose columns differ from the first leaf's stops the run when it arrives. +- A run that writes leaves prints how many files under `leaves/` no leaves manifest lists. +- Fixed: the row sort of the statistics no longer repeats rows when the index repeats. +- The pipeline writes a statistics file and its manifest under a temporary name and renames them. +- New: `stats.time_reduction` takes each member's window mean with `"window_mean"`, pools its years with the models and draws with `"pooled"` and keeps each year of `stats.years` with `"per_year"`. + Every pipeline config has to give it in place of `stats.pool_years`. +- The pandas reduce backend plans a block at 240 bytes for each row it keeps and 40 more for each dimension of the leaf. +- New: a cell of `tree.exclude` takes `"*"` for every value of a level. +- `quantile_method="linear"` is computed by numpy and gives the quantiles of `numpy.quantile` to the last bit. +- Under `summation="exact"` the weighted quantiles take their cumulative shares from exact sums. +- Fixed: a refusal raised while a reduce block is pooled names the target by its id fields. +- The lowest pandas the package declares is 2.1. + An environment on pandas 2.0 has to upgrade. +- Fixed: `cross_backend_compare` and `legacy_compare` no longer need pandas 2.2. +- Fixed: the data scripts of `examples/energy` and `examples/labor` no longer fail with a NameError. +- New: `examples/france/` runs the whole chain in one marimo notebook for mortality in metropolitan France. +- New: `docs/reference.md` lists every public name and every config key and the test suite fails when it is out of date. ## v0.5.0 diff --git a/README.md b/README.md index 23e598f..17c2272 100644 --- a/README.md +++ b/README.md @@ -351,12 +351,37 @@ written, and the member count beside it says why. Any other infinite statistic is the arithmetic passing the largest float, and is refused. A NaN is a group with no value, and is written. +A group whose quantile is below one at a lower level is refused under +every method and sum, before anything is written, and the refusal names +the group and the pair with their values. It has no setting and no +tolerance. Equal quantiles are in order, the NaN quantiles of a group +with no value pass, the levels go in their own order and not in the +order asked for, and the mean is not one of them. The one level left out +is the 0.5 quantile of `"lower_step"`, which for members that count +equally is their plain median, as the historical tool defined it, and +not a point of the step. It can sit above the step quantile just over +0.5, and above the `-inf` that every step quantile of a single member +is. Its row says so. Every statistics file has a `plain_median` column, +true on such a q50 and false on every other row and under every other +method, so the schema does not change with the settings, and the +manifest records what the column means. + Files made before v0.6.0 had no such options. They are reproduced by `"lower_step"` if the run had weights and `"linear"` if it had none, with `"fast"`. Those without weights took their quantiles from pandas, whose arithmetic for the same interpolation differs from numpy's in the last bit of about one quantile in a hundred. +`"lower_step"` reproduces the historical extraction tool except where a +member is left out for a weight of zero, a missing weight or a missing +value. The tool asks whether a group's weights are equal with such a +member among them at weight zero, and the library asks it of the members +kept. So there, and only at q50, the library can give the plain median +where the tool gives the step value, never the other way. Anyone +comparing a q50 with a number the tool published meets it there. The +library drops such a member on purpose, since a member that does not +count must not decide anything else either. + ## Country values from state values A country value is not a statistic of its states' statistics, since a @@ -631,35 +656,34 @@ n_workers = 16 # run.n_workers unless set `--dry-run` prints the blocks and the number of file opens that budget gives. The blocks are sized from an estimate of the bytes a kept row takes, 240 for a leaf with no dimension and 40 more for each dimension, -set from resident memory on macOS. On real data on Linux, in the one run -measured there, a kept row of a leaf with no dimension took up to 223.05 -bytes, so the estimate covers it by 1.076. The first block is built -alone in a worker of its own, and measured as the growth of that -worker's peak resident memory over the block, from the peak once the -worker has set itself up. The manifest records the estimate and the -measurement side by side under `reduce.block_size`, and the setup peak, -which every worker holds before its first block. On Linux a first block -that keeps 100,000 rows or more and takes more than 1.25 times the -estimate stops the run, with nothing written, since its blocks could -take more than the budget. The first block stands for the others because -every block is of one size and does the same work, and on real data, on -Linux, the first blocks of sixteen workers agreed within 2%. On macOS -the first block is measured and recorded and not judged, and -`reduce.block_size.not_judged_here` says why. The same synthetic block -read there from 50 to 212 bytes a kept row from one fresh worker to the -next, for a cause not found, and a refusal against that would be one -against noise. On one worker the blocks run in the process that planned -the run, whose peak includes what it did before. A block that fits in -memory the worker already held leaves its peak where it was. In both -cases the manifest says there is no measurement and why, and the run is -not judged. The peak is read as each platform keeps it, as VmHWM of -`/proc/self/status` on Linux and as `ru_maxrss` on macOS. On Linux -`ru_maxrss` survives an exec, so a spawned worker's would start from the -peak of the process that started it. Under fork a worker counts the -pages it shares with that process as its own, so the peaks under -`reduce.block_size` and `max_worker_peak_gb` overstate what a worker -alone holds, which errs on the side of the budget. The growth, the -difference of two peaks that both count those pages, is exact. +set from resident memory on macOS. The first block is built alone in a +worker of its own, and measured as the growth of that worker's peak +resident memory over the block, from the peak once the worker has set +itself up. The manifest records the estimate and the measurement side by +side under `reduce.block_size`, and the setup peak, which every worker +holds before its first block. On Linux a first block that keeps 100,000 +rows or more and takes more than 1.25 times the estimate stops the run, +with nothing written, since its blocks could take more than the budget. +The first block stands for the others because every block of a run is +sized to the same budget and does the same work, so a first block well +above the estimate says the estimate is wrong for that data, and the +tolerance can be tight. Each run's manifest has what its blocks took. On +macOS the first block is measured and recorded and not judged, and +`reduce.block_size.not_judged_here` says why. The same block has read +there several times more from one fresh worker to the next, for a cause +not found, and a refusal against that would be one against noise. On one +worker the blocks run in the process that planned the run, whose peak +includes what it did before. A block that fits in memory the worker +already held leaves its peak where it was. In both cases the manifest +says there is no measurement and why, and the run is not judged. The +peak is read as each platform keeps it, as VmHWM of `/proc/self/status` +on Linux and as `ru_maxrss` on macOS. On Linux `ru_maxrss` survives an +exec, so a spawned worker's would start from the peak of the process +that started it. Under fork a worker counts the pages it shares with +that process as its own, so the peaks under `reduce.block_size` and +`max_worker_peak_gb` overstate what a worker alone holds, which errs on +the side of the budget. The growth, the difference of two peaks that +both count those pages, is exact. Every block is recorded under `reduce.block_size.every_block`, each worker's first block is measured, and only the run's first block is diff --git a/benchmarks/README.md b/benchmarks/README.md index 27280c5..bab0a6b 100644 --- a/benchmarks/README.md +++ b/benchmarks/README.md @@ -93,6 +93,6 @@ workers mute the warning the library logs for every leaf. | `BENCH_WORKERS` | cores, at most 8 | pool size | | `BENCH_LEAVES` | 48 | leaves in one coarse pool task | -A full-size leaf peaks at about 2 GiB in one process. The pool test -uses smaller leaves by default because eight full-size workers swap on -a 16 GB machine, and then the run measures swapping. +The pool test uses smaller leaves by default because eight full-size +workers swap on a laptop, and then the run measures swapping. The +benchmark prints its times and not its memory. diff --git a/benchmarks/test_bench_leaf.py b/benchmarks/test_bench_leaf.py index c3c5e97..2859c6f 100644 --- a/benchmarks/test_bench_leaf.py +++ b/benchmarks/test_bench_leaf.py @@ -39,7 +39,7 @@ _KW = dict(time_col="year", windows=WINDOWS, value_col="pct", summation="fast") _COLUMNS = ID_FIELDS + list(LABELS) + ["window", "pct"] -# Eight full-size workers need about 16 GiB, so the pool runs on leaves +# Eight full-size workers swap on a laptop, so the pool runs on leaves # an eighth of the size unless told otherwise. POOL_SCALE = int(os.environ.get("BENCH_POOL_SCALE", "8")) POOL_WORKERS = int(os.environ.get("BENCH_WORKERS", min(8, os.cpu_count() or 1))) diff --git a/cil_regionalization/apply.py b/cil_regionalization/apply.py index 95a729c..ca92f5b 100644 --- a/cil_regionalization/apply.py +++ b/cil_regionalization/apply.py @@ -903,8 +903,8 @@ def _first_rows(codes: np.ndarray, card: int) -> np.ndarray: def _rows_in(frame: pd.DataFrame, keys: list[str], ids: set[tuple]) -> np.ndarray: """Boolean mask of the rows whose ``keys`` tuple is in ``ids``, the same as ``frame[keys].apply(tuple, axis=1).isin(ids)``.""" - # This builds no Python tuple per row. Building one per row cost - # minutes and about 16 GiB at 100M rows. + # This builds no Python tuple per row. One per row is far slower and + # far larger at a hundred million rows. return pd.MultiIndex.from_frame(frame[keys]).isin(ids) diff --git a/cil_regionalization/backends/bigquery.py b/cil_regionalization/backends/bigquery.py index d53f369..509fbee 100644 --- a/cil_regionalization/backends/bigquery.py +++ b/cil_regionalization/backends/bigquery.py @@ -682,8 +682,8 @@ def _upload_temp_table( # NEVER fail on geometry content; parsing is deferred to SQL # where we run ``ST_GEOGFROMTEXT(geometry, make_valid => TRUE)`` # so spherical-invalid polygons (planar-valid but with edges - # that cross as geodesics, the exact failure mode of the 17 - # 2022 NULLs) get repaired in the spherical domain at parse time. + # that cross as geodesics, the exact failure mode of the NULLs of + # 2022) get repaired in the spherical domain at parse time. # No SAFE. wrapper: if make_valid cannot repair we want the loud # named error, not a silent NULL. job_config = self._bq.LoadJobConfig( diff --git a/cil_regionalization/config.py b/cil_regionalization/config.py index bf8d60a..59cce56 100644 --- a/cil_regionalization/config.py +++ b/cil_regionalization/config.py @@ -90,8 +90,8 @@ class RegionsConfig(_Strict): on_invalid_geometry: InvalidGeomPolicy # NULL geometries in BQ regions tables: error (default, abort and list # the offending hierids) or skip (exclude them, record in the manifest - # under null_geometry_regions). Measured 17 NULL hierids in the s51 IR - # table inherited from the legacy pipeline's SAFE.ST_GEOGFROMTEXT. + # under null_geometry_regions). The s51 IR table has such NULLs, + # inherited from the legacy pipeline's SAFE.ST_GEOGFROMTEXT. on_null_geometry: Literal["error", "skip"] = "error" # Requested ids in `regions.keep` that do not exist in the regions # table: error (default, abort and list them) or skip (exclude, @@ -193,10 +193,10 @@ class SourceConfig(_Strict): # manifest under partial_coverage and the application layer refuses # the artifact unless the caller explicitly allows it. The default # tolerates boundary digitization noise between geometry products - # (well under 0.1 percent for interior units) while catching subset - # border slivers, which sit near zero coverage. Coastline mismatch - # between products may legitimately exceed the default for coastal - # units; the recording exists to measure that, not hide it. + # while catching subset border slivers, which sit near zero coverage. + # Coastline mismatch between products may legitimately exceed the + # default for coastal units; the recording exists to measure that, + # not hide it. coverage_threshold: float = Field(default=0.999, gt=0, le=1) @@ -229,19 +229,16 @@ class LocalBackendOptions(_Strict): 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 - # point slivers where source boundaries run along target boundaries), - # then a natural gap with almost nothing between 1 m2 and a hectare, - # with real segments starting around the hectare scale. The largest - # share of any source unit's area carried by a sub-1 m2 segment is - # 8e-9, nine orders of magnitude below the sum tolerance, so the - # exact number is not delicate. Degenerate slivers are also what - # crashes exactextract's traversal. Set 0 to restore the exact - # positive-area filter. Every run records what the threshold dropped - # in the manifest under min_segment_area, so the "nothing real is - # being eaten" claim stays inspectable per run rather than trusted - # from the one measurement above. + # On the global IR-to-ADM1 intersection the segments below 1 m2 are + # floating point slivers where source boundaries run along target + # boundaries, with a gap above them before real segments start around + # the hectare scale, and none carries a share of its source unit's + # area anywhere near the sum tolerance, so the exact number is not + # delicate. Degenerate slivers are also what crashes exactextract's + # traversal. Set 0 to restore the exact positive-area filter. Every + # run records what the threshold dropped in the manifest under + # min_segment_area, so the "nothing real is being eaten" claim stays + # inspectable per run rather than trusted. min_segment_area_m2: float = Field(default=1.0, ge=0) @model_validator(mode="after") @@ -281,12 +278,13 @@ class BigQueryBackendOptions(_Strict): # 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 - # ~6 GB is the real cost of any run, not an estimate artifact of big - # ones. Larger runs must override explicitly in config; a - # defense-in-depth default ships before the code that needs it. + # The default sits above the worst full-table scan of the GPW + # population table measured for s51, with headroom. The ST_CONTAINS + # join scans the full GPW table regardless of how few regions are + # requested, so that scan is the real cost of any run, not an + # estimate artifact of big ones. Larger runs must override explicitly + # in config; a defense-in-depth default ships before the code that + # needs it. dry_run_byte_ceiling: int = Field(default=10_000_000_000, ge=0) # GCS staging URI for the geometry load job. The IR geometries table is # in us-west1 and GPW is in US; we fetch geometries client-side and diff --git a/cil_regionalization/pipelines/montecarlo.py b/cil_regionalization/pipelines/montecarlo.py index ca875e7..2c908ec 100644 --- a/cil_regionalization/pipelines/montecarlo.py +++ b/cil_regionalization/pipelines/montecarlo.py @@ -80,12 +80,11 @@ # same, which a test pins, and the pooled frame shrinks by the ratio of # years to windows. # -# Memory at scale, measured: a full mortality ADM2 run (about 4,000 -# leaves by 42,726 targets, roughly 500 million member rows) peaked at -# 188.3 GB resident in the parent process at the pooled-statistics -# stage, and requests of 128 GB died three times at that scale. Size -# ADM2-scale requests at 224 GB or more, and read the memory[...] lines -# the run prints before trusting any smaller figure. +# Memory at scale is far above what a small run suggests. The pooled +# statistics stage holds the most, in the parent process, and a full +# ADM2 run needs a much larger request than an ADM1 one. Read the +# memory[...] lines the run prints, its own measure, before trusting +# any figure. from __future__ import annotations @@ -890,6 +889,17 @@ def _leaves_stem(cfg: MonteCarloPipelineConfig) -> str: return cfg.output.leaves_stem or cfg.output.stem +# What the plain_median column of the statistics says, recorded in every +# manifest beside the method. +_PLAIN_MEDIAN_MEANING = ( + 'true on a q50 row that "lower_step" gives as the plain median of ' + "members that count equally, as WeightedECDF.inverse of the historical " + "extraction tool gives it, and not a point of the step, so it can sit " + "above the quantile at the next level and is left out of the check of " + "the quantiles' order. False on every other row." +) + + def run_pipeline( cfg: MonteCarloPipelineConfig, *, @@ -1194,6 +1204,7 @@ def take(outcome: dict) -> None: "windows": [_window_label(lo, hi) for lo, hi in cfg.stats.windows], "quantiles": cfg.stats.quantiles, "quantile_method": cfg.stats.quantile_method, + "plain_median": _PLAIN_MEDIAN_MEANING, "summation": cfg.stats.summation, "time_reduction": cfg.stats.time_reduction, "years": None, @@ -2168,6 +2179,7 @@ def _run_reduce( ), "quantiles": cfg.stats.quantiles, "quantile_method": cfg.stats.quantile_method, + "plain_median": _PLAIN_MEDIAN_MEANING, "summation": cfg.stats.summation, "time_reduction": cfg.stats.time_reduction, "years": list(cfg.stats.years) if cfg.stats.years else None, @@ -2240,6 +2252,7 @@ def _check_level_names(levels: list[str], id_fields: list[str]) -> None: **{name: "an id field of the weights artifact" for name in id_fields}, "window": "the column of window labels", "statistic": "the column of statistic labels", + "plain_median": "the column that marks a plain median", "n_members": "the column stats.include_n_members writes", "n_models": "the column of the climate models behind a statistic", "n_sample": "the column of pooled rows stats.time_reduction writes", @@ -2316,6 +2329,7 @@ def _ordered(frame: pd.DataFrame, cfg: MonteCarloPipelineConfig) -> pd.DataFrame for column in frame.columns: if column in declared or column in ( cfg.data.value_col, + "plain_median", "n_members", "n_sample", "n_models", diff --git a/cil_regionalization/reduce/base.py b/cil_regionalization/reduce/base.py index 39d2fb3..74a2974 100644 --- a/cil_regionalization/reduce/base.py +++ b/cil_regionalization/reduce/base.py @@ -148,7 +148,7 @@ def columns(self) -> list[str]: + kept_dims + kept_levels + ([self.time_col] if self.time_reduction == "per_year" else ["window"]) - + ["statistic", self.value_col] + + ["statistic", self.value_col, "plain_median"] + (["n_members"] if self.include_n_members else []) + ( ["n_sample"] diff --git a/cil_regionalization/reduce/pandas_blocks.py b/cil_regionalization/reduce/pandas_blocks.py index 925be9b..56fd477 100644 --- a/cil_regionalization/reduce/pandas_blocks.py +++ b/cil_regionalization/reduce/pandas_blocks.py @@ -14,9 +14,9 @@ measurement side by side. On Linux a run sized by the estimate is refused when the measurement of a block large enough to judge is more than 1.25 times the estimate. On macOS the measurement is recorded and -not judged, since the same block reads there from a fifth of the -estimate to nine tenths of it from one fresh worker to the next. In a -single process that has already done other work the peak +not judged, since the same block has read there several times more +from one fresh worker to the next, for a cause not found. In a single +process that has already done other work the peak cannot be put down to the block, so there is no measurement and no judgement. """ @@ -59,21 +59,10 @@ from cil_regionalization.workers import WorkerDied, shut_down_broken # What a block is planned to take for a row it keeps, and for each -# dimension that row has of its own. They were set from the resident -# memory of a worker on macOS, which grew by at most 155 bytes a kept -# row on synthetic leaves with no dimension, and by 168, 194 and 218 -# with one, two and three. That is the largest over window means and -# pooled years, the four method pairs, with and without model weights, -# blocks of 1,300 to 41,000 kept rows a leaf, and pandas 2.3.3 and -# 3.1.1, and the figures cover each by half again or more. Real data on -# Linux comes much nearer. The stage check's reduce of labor ADM1 under -# rcp45, labor_valued_rcp45.manifest.json, run on a Midway3 compute node -# on the night of 2026-11-27 with memory_gb = 6 over 16 workers, has -# leaves with no dimension. Its sixteen workers' first blocks read -# 218.62 to 223.05 bytes a kept row, so 240 covers it by 1.076, not by -# half again. Leaves with dimensions have no measurement on Linux. A -# worker killed for memory costs the pass, and a block that is smaller -# than it had to be costs opens. +# dimension that row has of its own, set from a calibration on macOS. +# Every run records what its blocks took in its manifest under +# reduce.block_size. A worker killed for memory costs the pass, and a +# block that is smaller than it had to be costs opens. BYTES_PER_ROW = 240 BYTES_PER_DIMENSION = 40 # The kept rows a first block needs for its measurement to be judged. @@ -82,10 +71,12 @@ JUDGED_ROWS = 100_000 # A first block is refused when it takes more than this many times the # estimate a kept row. It is a tolerance on the judged block standing for -# the others, not a correction of the estimate. Every block is of one -# size and does the same work, and in the run named above the first -# blocks of sixteen workers read within 2% of one another, the heaviest -# at 0.929 of the estimate. A first block is judged on Linux alone, as +# the others, not a correction of the estimate. Every block of a run is +# sized to the same budget and does the same work, so a first block well +# above the estimate says the estimate is wrong for that data, not that +# one block was unusual. That is why the tolerance can be tight, with +# room for the spread between workers' first blocks and not for an +# estimate that is wrong. A first block is judged on Linux alone, as # `_not_judged_here` says. REFUSED_ABOVE = 1.25 # Why a first block run in the process that planned the run has no @@ -114,17 +105,16 @@ def _not_judged_here() -> str | None: """Why a first block is not judged where this runs, or None on - Linux, where it is. On macOS the same synthetic block, measured in - one fresh worker after another, read from 50 to 212 bytes a kept - row, for a cause not found, so a refusal there would be one against - noise.""" + Linux, where it is. On macOS the same block has read several times + more from one fresh worker to the next, for a cause not found, so a + refusal there would be one against noise.""" if sys.platform.startswith("linux"): return None return ( f"a first block is judged only on Linux, and this ran on " - f"{sys.platform}. On macOS the same synthetic block, measured in one " - f"fresh worker after another, read from 50 to 212 bytes a kept row, " - f"for a cause not found, so its measurement is recorded and not judged" + f"{sys.platform}. On macOS the same block has read several times more " + f"from one fresh worker to the next, for a cause not found, so its " + f"measurement is recorded and not judged" ) @@ -827,7 +817,14 @@ def _with_counts( c for c in stats.columns if c - not in ("statistic", request.value_col, "n_members", "n_sample", "n_models") + not in ( + "statistic", + request.value_col, + "plain_median", + "n_members", + "n_sample", + "n_models", + ) ] grouped = _plain_labels(pd.concat(members, ignore_index=True)).groupby( identity, sort=False, observed=True diff --git a/cil_regionalization/stats.py b/cil_regionalization/stats.py index f471384..85217c5 100644 --- a/cil_regionalization/stats.py +++ b/cil_regionalization/stats.py @@ -32,7 +32,9 @@ Neither has a default. An infinite member value is refused under every method and summation. The one infinity a statistic can have is the -``-inf`` of "lower_step" at or below its first step. +``-inf`` of "lower_step" at or below its first step. A group whose +quantile is below one at a lower level is refused too, other than the +plain median "lower_step" gives at 0.5 to members that count equally. """ # Each draw is aggregated across space first, then averaged over the @@ -90,6 +92,10 @@ def _warn_if_unweighted_models( _STATISTIC_COLUMN = "statistic" _N_MEMBERS_COLUMN = "n_members" _N_MODELS_COLUMN = "n_models" +# True on the 0.5 quantile of "lower_step" where it is the plain median +# of members that count equally, as the historical extraction tool's +# WeightedECDF.inverse gives it, and False on every other row. +_PLAIN_MEDIAN_COLUMN = "plain_median" # The computations of a quantile and of a sum, each under the name of # what it does. Neither option has a default. @@ -191,11 +197,15 @@ def summarize_samples( 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', - 'q2.5'). + Returns a long frame with the identity columns, 'statistic', + ``value_col`` and 'plain_median'. Labels are 'mean' and 'qNN' in + percent ('q05', 'q95', 'q2.5'). 'plain_median' is True on the q50 of + "lower_step" where the members count equally, which is then their + plain median, as the historical extraction tool gives it, and not a + point of the step, so it can sit above the next quantile. It is + False on every other row, under every method. - ``include_n_members`` adds two integer columns after ``value_col``. + ``include_n_members`` adds two integer columns after 'plain_median'. 'n_members' is the samples behind a statistic, the members with a window mean that is not NaN and, when weighted, a weight above zero, so each batch of a model counts once. 'n_models' is the climate @@ -214,13 +224,21 @@ def summarize_samples( returns, so it is biased low at every quantile, except at 0.5 with members that count equally, where it is the plain median. A quantile at or below the first member's share is ``-inf``, and with - ``weight_col`` unset every member counts the same. + ``weight_col`` unset every member counts the same. It reproduces the + tool except where a member is left out for a weight of zero, a + missing weight or a missing value. The tool asks whether the weights + are equal with such a member among them at weight zero, and this + function asks it of the members kept, so there q50 can be the plain + median where the tool gives the step value. Only q50 differs, and + only that way. ``summation`` is "fast" or "exact", and has no default. "fast" is the vectorised sum, whose last bits depend on the order of the rows. "exact" takes the means from exactly rounded sums, whatever the order. An infinite member value raises, and so does a statistic - that comes out infinite other than the step's ``-inf``. + that comes out infinite other than the step's ``-inf``. So does a + group whose quantile is below one at a lower level, other than the + step's plain median at 0.5, naming the group and the pair. The statistics are float64 whatever the dtype of ``value_col``. A column of another dtype is widened before the window mean, and a @@ -346,6 +364,14 @@ def summarize_samples( if identity == ["_all"]: out = out.drop(columns=["_all"]) _refuse_infinite_statistics(out, value_col, quantile_method) + _refuse_crossing_quantiles( + out, + value_col, + quantiles, + include_mean, + [] if identity == ["_all"] else identity, + quantile_method, + ) return out.reset_index(drop=True) @@ -557,6 +583,7 @@ def by_group(result: np.ndarray) -> pd.Series: # .array, not .to_numpy(): a nullable value dtype stays nullable piece[value_col] = compute().reindex(range(n_groups)).array piece[_STATISTIC_COLUMN] = label + piece[_PLAIN_MEDIAN_COLUMN] = False if count_members: piece[_N_MEMBERS_COLUMN] = counts pieces.append(piece) @@ -567,6 +594,8 @@ def by_group(result: np.ndarray) -> pd.Series: ] rows: dict[str, list[tuple]] = {label: [] for label in labels} member_counts: list[int] = [] + # whether each group's 0.5 quantile is the plain median + plain_medians: list[bool] = [] order, starts, ends = _group_order(gid, n_groups) if weight_col is None: # the step with no weights given: every member counts the same @@ -591,6 +620,7 @@ def by_group(result: np.ndarray) -> pd.Series: rows[label].append((*key_tuple, float("nan"))) if count_members: member_counts.append(0) + plain_medians.append(False) continue if len(values) == 0 or weights.sum() == 0: raise GroupError( @@ -615,12 +645,19 @@ def by_group(result: np.ndarray) -> pd.Series: picked = _inverted_cdf_quantiles(values, weights, quantiles, exact=exact) else: picked = _step_quantiles(values, weights, quantiles, exact=exact) + plain_medians.append( + quantile_method == "lower_step" and _counts_equally(weights) + ) for q, value in zip(quantiles, picked): rows[_quantile_label(q)].append((*key_tuple, value)) pieces = [] for label in labels: piece = pd.DataFrame(rows[label], columns=identity + [value_col]) piece[_STATISTIC_COLUMN] = label + if label == _quantile_label(0.5) and 0.5 in quantiles: + piece[_PLAIN_MEDIAN_COLUMN] = np.asarray(plain_medians, dtype=bool) + else: + piece[_PLAIN_MEDIAN_COLUMN] = False if count_members: piece[_N_MEMBERS_COLUMN] = np.asarray(member_counts, dtype=np.int64) pieces.append(piece) @@ -630,7 +667,7 @@ def by_group(result: np.ndarray) -> pd.Series: def _output_columns( identity: list[str], value_col: str, include_n_members: bool ) -> list[str]: - columns = identity + [_STATISTIC_COLUMN, value_col] + columns = identity + [_STATISTIC_COLUMN, value_col, _PLAIN_MEDIAN_COLUMN] if include_n_members: columns.append(_N_MEMBERS_COLUMN) return columns @@ -661,7 +698,7 @@ def _step_quantiles( # which member comes first. if not len(quantiles): return [] - equal = bool((weights == weights[0]).all()) + equal = _counts_equally(weights) order = ( np.lexsort((weights, values)) if exact else np.argsort(values, kind="stable") ) @@ -681,6 +718,16 @@ def _step_quantiles( return out +def _counts_equally(weights: np.ndarray) -> bool: + """Whether every member of a group carries the same weight, which is + when "lower_step" gives the plain median at 0.5. The weights are + those of the members kept, with a value and a weight above zero, + where the historical tool counts a member left out at weight zero, + so a group with such a member can get the median here and the step + value there.""" + return bool((weights == weights[0]).all()) + + def _exact_shares(weights: np.ndarray) -> np.ndarray: """The share of the total weight that each running sum of ``weights`` reaches, the exact running sum over the exact total, @@ -843,6 +890,71 @@ def _refuse_infinite_statistics( ) +def _refuse_crossing_quantiles( + out: pd.DataFrame, + value_col: str, + quantiles: Sequence[float], + include_mean: bool, + identity: list[str], + quantile_method: str, +) -> None: + """Raise if a group's quantile is below one at a lower level, naming + the group and the pair that cross. Equal quantiles are in order, and + so is a group with no value, whose quantiles are NaN. The levels are + taken in their order and not in the order asked for, and the mean is + not one of them. Under "lower_step" neither is the 0.5 quantile.""" + # Under "lower_step" the 0.5 quantile of members that count equally + # is their plain median, as the historical tool defined it, and not a + # point of the step, which every other level is. So it sits above the + # step quantile just over 0.5, and above the -inf every step quantile + # of a single member is. + checked = [ + i + for i, q in enumerate(quantiles) + if not (quantile_method == "lower_step" and q == 0.5) + ] + if len(checked) < 2: + return + labels = (["mean"] if include_mean else []) + [ + _quantile_label(q) for q in quantiles + ] + n_groups, rest = divmod(len(out), len(labels)) + if ( + rest + or not (out[_STATISTIC_COLUMN].to_numpy() == np.repeat(labels, n_groups)).all() + ): + raise RuntimeError( + "the statistics are not one block of rows a statistic, in the " + "order asked for, which the check of the quantiles' order reads" + ) + # Every statistic is a block of one row a group, in one group order, + # as `_statistic_pieces` builds them. + values = _float_values(out[value_col]) + first = len(labels) - len(quantiles) + by_level = sorted(checked, key=lambda i: quantiles[i]) + table = np.stack( + [values[(first + i) * n_groups : (first + i + 1) * n_groups] for i in by_level] + ) + # the highest quantile at a lower level, a NaN left out + below = np.fmax.accumulate(table, axis=0)[:-1] + crossed = table[1:] < below + if not crossed.any(): + return + group, step = (int(x) for x in np.argwhere(crossed.T)[0]) + higher = by_level[step + 1] + lower = by_level[int(np.nanargmax(table[: step + 1, group]))] + row = out.iloc[(first + higher) * n_groups + group] + raise GroupError( + f"{int(crossed.any(axis=0).sum())} groups have quantiles out of order (first: ", + row[identity].to_dict(), + f", where {_quantile_label(quantiles[higher])} = " + f"{float(values[(first + higher) * n_groups + group])!r} is below " + f"{_quantile_label(quantiles[lower])} = " + f"{float(values[(first + lower) * n_groups + group])!r}). A quantile " + f"never falls as its level rises, so these statistics are wrong.", + ) + + def _refuse_infinite_values( data: pd.DataFrame, value_col: str, rows: np.ndarray | None = None ) -> None: @@ -1012,8 +1124,9 @@ def _with_model_counts( def _reject_presummarized(data: pd.DataFrame, value_col: str) -> None: problems: list[str] = [] - if _STATISTIC_COLUMN in data.columns: - problems.append(f"a {_STATISTIC_COLUMN!r} column") + for column in (_STATISTIC_COLUMN, _PLAIN_MEDIAN_COLUMN): + if column in data.columns: + problems.append(f"a {column!r} column") quantile_like = [c for c in data.columns if _QUANTILE_NAME_RE.search(str(c))] if quantile_like: problems.append(f"quantile-named columns {quantile_like}") @@ -1197,8 +1310,8 @@ def pooled_statistics( ordinary identity column here. ``weight_col``, ``include_n_members``, ``model_dims``, ``quantile_method`` and ``summation`` behave the same, and the same input is refused. - Returns identity columns, 'statistic', ``value_col``, then - 'n_members' and 'n_models' if asked for. + Returns identity columns, 'statistic', ``value_col``, + 'plain_median', then 'n_members' and 'n_models' if asked for. """ check_quantile_method(quantile_method, weighted=weight_col is not None) check_summation(summation) @@ -1270,6 +1383,14 @@ def pooled_statistics( if identity == ["_all"]: out = out.drop(columns=["_all"]) _refuse_infinite_statistics(out, value_col, quantile_method) + _refuse_crossing_quantiles( + out, + value_col, + quantiles, + include_mean, + [] if identity == ["_all"] else identity, + quantile_method, + ) return out.reset_index(drop=True) diff --git a/cil_regionalization/web_json.py b/cil_regionalization/web_json.py index 78edd95..e2b8f26 100644 --- a/cil_regionalization/web_json.py +++ b/cil_regionalization/web_json.py @@ -164,8 +164,7 @@ def write_document( """ # Every sibling, including other products staged for the same rsync, # is left alone, as the comment at the top of the module says. - # Whitespace is about a tenth of the uncompressed document and - # survives gzip badly, hence the compact separators. + # Whitespace survives gzip badly, hence the compact separators. out = Path(out_dir) out.mkdir(parents=True, exist_ok=True) path = out / filename diff --git a/docs/reference.md b/docs/reference.md index 35db2e4..059e063 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -407,11 +407,15 @@ model, so in an unbalanced sample a model's total weight grows with 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', -'q2.5'). - -``include_n_members`` adds two integer columns after ``value_col``. +Returns a long frame with the identity columns, 'statistic', +``value_col`` and 'plain_median'. Labels are 'mean' and 'qNN' in +percent ('q05', 'q95', 'q2.5'). 'plain_median' is True on the q50 of +"lower_step" where the members count equally, which is then their +plain median, as the historical extraction tool gives it, and not a +point of the step, so it can sit above the next quantile. It is +False on every other row, under every method. + +``include_n_members`` adds two integer columns after 'plain_median'. 'n_members' is the samples behind a statistic, the members with a window mean that is not NaN and, when weighted, a weight above zero, so each batch of a model counts once. 'n_models' is the climate @@ -430,13 +434,21 @@ quantile. It returns the member one below the one "inverted_cdf" returns, so it is biased low at every quantile, except at 0.5 with members that count equally, where it is the plain median. A quantile at or below the first member's share is ``-inf``, and with -``weight_col`` unset every member counts the same. +``weight_col`` unset every member counts the same. It reproduces the +tool except where a member is left out for a weight of zero, a +missing weight or a missing value. The tool asks whether the weights +are equal with such a member among them at weight zero, and this +function asks it of the members kept, so there q50 can be the plain +median where the tool gives the step value. Only q50 differs, and +only that way. ``summation`` is "fast" or "exact", and has no default. "fast" is the vectorised sum, whose last bits depend on the order of the rows. "exact" takes the means from exactly rounded sums, whatever the order. An infinite member value raises, and so does a statistic -that comes out infinite other than the step's ``-inf``. +that comes out infinite other than the step's ``-inf``. So does a +group whose quantile is below one at a lower level, other than the +step's plain median at 0.5, naming the group and the pair. The statistics are float64 whatever the dtype of ``value_col``. A column of another dtype is widened before the window mean, and a @@ -501,8 +513,8 @@ The second half of `summarize_samples`. The window column is an ordinary identity column here. ``weight_col``, ``include_n_members``, ``model_dims``, ``quantile_method`` and ``summation`` behave the same, and the same input is refused. -Returns identity columns, 'statistic', ``value_col``, then -'n_members' and 'n_models' if asked for. +Returns identity columns, 'statistic', ``value_col``, +'plain_median', then 'n_members' and 'n_models' if asked for. ### `mixture_quantile` diff --git a/tests/integration/test_bigquery_backend.py b/tests/integration/test_bigquery_backend.py index dd96958..657edfd 100644 --- a/tests/integration/test_bigquery_backend.py +++ b/tests/integration/test_bigquery_backend.py @@ -1432,7 +1432,8 @@ def _cfg(self, tmp_path): return Config.model_validate(d) def test_dry_run_under_ceiling(self, bq_client, tmp_path): - """The combined query scans GPW (~6 GB); 10 GB ceiling admits it.""" + """The combined query scans the whole GPW table, which the default + ceiling admits.""" from cil_regionalization.backends.bigquery import BigQueryBackend backend = BigQueryBackend() @@ -1540,7 +1541,7 @@ def test_null_geometry_error_default(self, bq_client, tmp_path): from cil_regionalization.regions import RegionSet from cil_regionalization.weights import from_config_list - # CAN.5 is one of the 17 NULL hierids the user measured. Include + # CAN.5 is one of the NULL hierids of the s51 table. Include # ABW (valid) so the failure must be NULL-driven, not "no hierids". d = _bq_cfg().model_dump() d["regions"]["keep"] = {"hierid": ["ABW", "CAN.5"]} diff --git a/tests/integration/test_cross_backend.py b/tests/integration/test_cross_backend.py index 910cedc..5f50a49 100644 --- a/tests/integration/test_cross_backend.py +++ b/tests/integration/test_cross_backend.py @@ -324,8 +324,8 @@ class TestCrossBackendArea: - **Spheroid vs ellipsoid.** ``pyproj.Geod(ellps='WGS84')`` uses a true ellipsoid (Vincenty / Karney). BigQuery ``ST_AREA(GEOGRAPHY)`` - uses a sphere of fixed radius. The local backend produces areas - that are 0.05-0.3% smaller than the BQ equivalent in mid-latitudes. + uses a sphere of fixed radius. The local backend produces areas a + little smaller than the BQ equivalent in mid-latitudes. *Normalized* weights cancel this out almost completely (both numerator and denominator move the same way), but the cancellation is not exact across non-uniform cells. diff --git a/tests/integration/test_montecarlo_pipeline.py b/tests/integration/test_montecarlo_pipeline.py index ad399fe..fdaea7c 100644 --- a/tests/integration/test_montecarlo_pipeline.py +++ b/tests/integration/test_montecarlo_pipeline.py @@ -290,6 +290,7 @@ def test_generation_application_statistics(self, weights_dir, tmp_path): "target_id", "statistic", "value", + "plain_median", "window", "weight_share", } @@ -326,6 +327,7 @@ def test_include_n_members_adds_the_count(self, weights_dir, tmp_path): "target_id", "statistic", "value", + "plain_median", "window", "n_members", "n_models", @@ -784,6 +786,7 @@ def test_every_file_is_what_labelling_the_leaf_first_gave( "window", "statistic", "value", + "plain_median", "weight_share", ] @@ -934,7 +937,7 @@ def test_a_passthrough_leaf_of_the_year_and_the_value_alone_still_runs( } ) stats = run_pipeline(cfg).stats - assert list(stats.columns) == ["window", "statistic", "value"] + assert list(stats.columns) == ["window", "statistic", "value", "plain_median"] # the six leaves average 100 + 10 i + 0.5 and 100 + 10 i + 30.5 assert stats["value"].tolist() == [125.5, 155.5] reduced = pd.read_parquet(tmp_path / "out" / "statistics.reduced.parquet") @@ -989,6 +992,7 @@ def test_three_level_layout_with_other_names(self, weights_dir, tmp_path): "flavor", "statistic", "value", + "plain_median", "window", "weight_share", } @@ -1877,7 +1881,13 @@ def test_parquet_statistics_per_unit(self, tmp_path): assert report["mass_balance_rel_error"] is None stats = result.stats - assert set(stats.columns) == {"unit_id", "statistic", "value", "window"} + assert set(stats.columns) == { + "unit_id", + "statistic", + "value", + "plain_median", + "window", + } # 2 units x 2 windows x 3 statistics assert len(stats) == 12 @@ -1911,7 +1921,13 @@ def test_netcdf_region_col_and_single_year_window(self, tmp_path): result = run_pipeline(cfg) stats = result.stats - assert set(stats.columns) == {"hierid", "statistic", "value", "window"} + assert set(stats.columns) == { + "hierid", + "statistic", + "value", + "plain_median", + "window", + } assert set(stats["hierid"]) == {"u1", "u2"} # the single-year window is labeled by the year alone assert set(stats["window"]) == {"2050-2051", "2081"} @@ -3134,6 +3150,7 @@ def test_it_gives_what_a_run_with_one_worker_gives( "window", "statistic", "value", + "plain_median", "n_members", "n_models", "weight_share", @@ -3281,6 +3298,71 @@ def test_a_first_block_heavier_than_the_estimate_is_refused( ) assert not (out / "again.parquet").exists() + def test_both_routes_mark_the_step_median_alike(self, weights_dir, tmp_path): + """ "lower_step" without weights, as a warming-level product runs + it, so every q50 is the plain median of members that count + equally. The run and the reduce write the same column, True on + q50 and False elsewhere, and both manifests say what it means. It + went red with the column left out of the reduce's columns.""" + tree, out = tmp_path / "tree", tmp_path / "out" + TestLabelPlacement._build_tree(tree) + raw = self._raw(weights_dir, tree, out, methods=("lower_step", "exact")) + raw["stats"]["quantiles"] = [0.5, 0.75] + whole = run_pipeline(MonteCarloPipelineConfig.model_validate(raw)) + got = self._reduce(raw) + _same_frames(got.stats, whole.stats) + written = pd.read_parquet(out / "statistics.parquet") + assert written["plain_median"].dtype == bool + assert (written["plain_median"] == (written["statistic"] == "q50")).all() + for stem in ("statistics", "again"): + manifest = json.loads((out / f"{stem}.manifest.json").read_text()) + assert manifest["plain_median"].startswith( + 'true on a q50 row that "lower_step" gives as the plain median ' + "of members that count equally" + ) + + @pytest.mark.parametrize("stage", ["all", "reduce"]) + def test_quantiles_out_of_order_are_never_written( + self, weights_dir, tmp_path, monkeypatch, stage + ): + """Neither route writes statistics whose quantiles cross, and the + refusal names the target by its id. Here q75 and q95 of one group + are swapped where q95 is the higher. It went red with the check + not called, when both routes wrote them.""" + from cil_regionalization import stats as statistics + + if stage == "reduce": + raw, _, out = self._aggregated(weights_dir, tmp_path) + real = statistics._statistic_pieces + + def crossed(*args, **kwargs): + pieces = real(*args, **kwargs) + by = {piece["statistic"].iloc[0]: piece for piece in pieces} + low, high = by["q75"], by["q95"] + i = low.index[(high["value"] > low["value"]).to_numpy()][0] + low.at[i, "value"], high.at[i, "value"] = ( + high.at[i, "value"], + low.at[i, "value"], + ) + return pieces + + monkeypatch.setattr(statistics, "_statistic_pieces", crossed) + with pytest.raises(ValueError) as error: + if stage == "all": + self._aggregated(weights_dir, tmp_path) + else: + # one worker, the process that planned the run, so the + # swap above is the one the block meets + self._reduce(raw, n_workers=1) + message = str(error.value) + assert message.startswith( + "1 groups have quantiles out of order (first: {'target_id': " + ), message + assert "where q95 = " in message and " is below q75 = " in message + # the file each route writes its statistics to + stem = "statistics" if stage == "all" else "again" + assert not (tmp_path / "out" / f"{stem}.parquet").exists() + @pytest.mark.usefixtures("forked_workers_with_a_rising_peak") def test_off_linux_a_heavy_first_block_is_recorded_and_the_run_goes_on( self, weights_dir, tmp_path, monkeypatch @@ -3989,6 +4071,7 @@ def test_stage_all_writes_the_leaves_and_pools_their_years( "window", "statistic", "value", + "plain_median", "n_members", "n_sample", "n_models", @@ -4012,6 +4095,7 @@ def test_the_counts_are_written_only_if_asked_for(self, weights_dir, tmp_path): "window", "statistic", "value", + "plain_median", "weight_share", ] @@ -4520,6 +4604,7 @@ def test_stage_all_writes_the_leaves_and_keeps_every_year( "year", "statistic", "value", + "plain_median", "n_members", "n_models", "weight_share", @@ -4921,7 +5006,15 @@ def test_the_statistics_are_over_the_members_at_each_level( cfg = MonteCarloPipelineConfig.model_validate(raw) result = run_pipeline(cfg) assert list(result.stats.columns) == ( - ["target_id", "warming_level", "window", "statistic", "value", "n_members"] + [ + "target_id", + "warming_level", + "window", + "statistic", + "value", + "plain_median", + "n_members", + ] + (["n_sample"] if pooled else []) + ["n_models", "n_bin_members", "weight_share"] ) diff --git a/tests/integration/test_reduce_parity.py b/tests/integration/test_reduce_parity.py index 8e9b6e2..b5ca542 100644 --- a/tests/integration/test_reduce_parity.py +++ b/tests/integration/test_reduce_parity.py @@ -831,6 +831,7 @@ def test_a_balanced_tree_keeps_its_mean_and_moves_its_quantiles( "band", "window", "value", + "plain_median", "n_members", "n_sample", "n_models", diff --git a/tests/unit/test_block_sizing.py b/tests/unit/test_block_sizing.py index e365390..5278928 100644 --- a/tests/unit/test_block_sizing.py +++ b/tests/unit/test_block_sizing.py @@ -340,9 +340,9 @@ def test_off_linux_the_reason_names_the_platform(self, monkeypatch, platform): monkeypatch.setattr(sys, "platform", platform) assert _not_judged_here() == ( f"a first block is judged only on Linux, and this ran on {platform}. " - "On macOS the same synthetic block, measured in one fresh worker " - "after another, read from 50 to 212 bytes a kept row, for a cause " - "not found, so its measurement is recorded and not judged" + "On macOS the same block has read several times more from one " + "fresh worker to the next, for a cause not found, so its " + "measurement is recorded and not judged" ) def test_on_linux_there_is_no_reason(self, monkeypatch): diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py index c6e5324..915ae6c 100644 --- a/tests/unit/test_config.py +++ b/tests/unit/test_config.py @@ -237,12 +237,10 @@ def test_confirm_cost_false_allowed(self): assert cfg.output.confirm_cost is False def test_dry_run_byte_ceiling_default_is_10gb(self): - # Default must protect: the s51 case's worst-case GPW scan is ~6 GB, - # so 10 GB is the smallest ceiling that lets the s51 workload through - # without an override. Anything larger (the previous 500 GB) is a - # defense-in-depth regression. The measurement justifying the number - # is recorded in examples/configs/s51.toml: 5,257,870,075 bytes - # dry-run estimate for the full 24,361-valid-region GPW scan. + # Default must protect: it is the smallest round ceiling that lets + # the s51 workload's full GPW scan through without an override. + # Anything larger (the previous 500 GB) is a defense-in-depth + # regression. cfg = Config.model_validate(_bq_cfg()) assert cfg.backend.bigquery.dry_run_byte_ceiling == 10_000_000_000 diff --git a/tests/unit/test_stats.py b/tests/unit/test_stats.py index fafb430..6cb6816 100644 --- a/tests/unit/test_stats.py +++ b/tests/unit/test_stats.py @@ -195,7 +195,13 @@ def test_identity_dims_pass_through(self): quantile_method="linear", summation="fast", ) - assert set(out.columns) == {"target", "flavor", "statistic", "value"} + assert set(out.columns) == { + "target", + "flavor", + "statistic", + "value", + "plain_median", + } assert set(out["statistic"]) == {"mean", "q05", "q95"} # 2 targets x 2 flavors x 3 statistics assert len(out) == 12 @@ -262,7 +268,7 @@ def test_no_identity_dims_yields_single_group(self): quantile_method="linear", summation="fast", ) - assert list(out.columns) == ["statistic", "value"] + assert list(out.columns) == ["statistic", "value", "plain_median"] assert float(out["value"].iloc[0]) == pytest.approx(2.0) def test_nan_sample_member_excluded(self): @@ -643,7 +649,7 @@ def test_matches_summarize_samples_shape(self): quantile_method="linear", summation="fast", ) - assert list(out.columns) == ["target", "statistic", "value"] + assert list(out.columns) == ["target", "statistic", "value", "plain_median"] assert set(out["statistic"]) == {"mean", "q50"} @@ -672,7 +678,7 @@ def test_off_by_default(self): quantile_method="linear", summation="fast", ) - assert list(out.columns) == ["target", "statistic", "value"] + assert list(out.columns) == ["target", "statistic", "value", "plain_median"] def test_nan_member_is_not_counted(self): from cil_regionalization.stats import pooled_statistics @@ -690,6 +696,7 @@ def test_nan_member_is_not_counted(self): "target", "statistic", "value", + "plain_median", "n_members", "n_models", ] @@ -721,6 +728,7 @@ def test_zero_weight_member_is_not_counted(self): "target", "statistic", "value", + "plain_median", "n_members", "n_models", ] @@ -776,6 +784,7 @@ def test_summarize_samples_agrees_with_staged_path(self): "target", "statistic", "value", + "plain_median", "n_members", "n_models", ] @@ -825,7 +834,13 @@ def test_existing_n_members_column_refused(self): quantile_method="linear", summation="fast", ) - assert list(out.columns) == ["target", "n_members", "statistic", "value"] + assert list(out.columns) == [ + "target", + "n_members", + "statistic", + "value", + "plain_median", + ] class TestIdentityGroups: diff --git a/tests/unit/test_stats_methods.py b/tests/unit/test_stats_methods.py index 5428ed0..dad10a6 100644 --- a/tests/unit/test_stats_methods.py +++ b/tests/unit/test_stats_methods.py @@ -1061,6 +1061,265 @@ def test_the_error_says_where(self): assert "summation" not in message +def _swapped(monkeypatch, lower="q05", higher="q95", row=1, missing=None): + """`_statistic_pieces` with two quantiles of one group swapped, as a + broken quantile would give them, and ``missing`` made NaN there.""" + real = stats._statistic_pieces + + def pieces(*args, **kwargs): + out = real(*args, **kwargs) + by = {piece["statistic"].iloc[0]: piece for piece in out} + i = by[lower].index[row] + a, b = by[lower].at[i, "value"], by[higher].at[i, "value"] + by[lower].at[i, "value"], by[higher].at[i, "value"] = b, a + if missing is not None: + by[missing].at[i, "value"] = np.nan + return out + + monkeypatch.setattr(stats, "_statistic_pieces", pieces) + + +def _two_targets(weighted: bool, years: bool = False) -> pd.DataFrame: + """Targets a and b of five members each, every value distinct.""" + frame = pd.concat( + [ + _members([3.0, 1.0, 4.0, 1.5, 9.0], target="a"), + _members([2.0, 7.0, 1.8, 8.0, 2.8], target="b"), + ], + ignore_index=True, + ) + if weighted: + frame["w"] = [0.1, 0.3, 0.2, 0.25, 0.15] * 2 + if years: + frame = pd.concat( + [frame.assign(year=2040), frame.assign(year=2041)], ignore_index=True + ) + return frame + + +def _stats_of(function, frame, quantiles, options): + weight_col = "w" if "w" in frame.columns else None + if function == "summarize_samples": + out = summarize_samples( + frame, + sample_dims=["draw"], + time_col="year", + window=(2040, 2041), + quantiles=quantiles, + weight_col=weight_col, + **options, + ) + else: + out = pooled_statistics( + frame, + sample_dims=["draw"], + quantiles=quantiles, + weight_col=weight_col, + **options, + ) + return out + + +class TestQuantileOrder: + """A group whose quantile is below one at a lower level is refused, + naming the group and the pair, under every method and sum and in + both functions that finish the statistics. What a crossing check + could take for a crossing and is not passes.""" + + SETTINGS = TestInfiniteStatistics.SETTINGS + + @pytest.mark.parametrize("function", ["pooled_statistics", "summarize_samples"]) + @pytest.mark.parametrize("options", SETTINGS) + @pytest.mark.parametrize("weighted", [False, True]) + def test_a_quantile_below_a_lower_level_is_refused( + self, monkeypatch, function, options, weighted + ): + """The message names the group and both quantiles with their + values. It went red with the check not called.""" + if weighted and options["quantile_method"] == "linear": + pytest.skip("linear quantiles are refused with weights") + frame = _two_targets(weighted, years=function == "summarize_samples") + good = _stats_of(function, frame, [0.05, 0.95], options) + b = good[good["target"] == "b"].set_index("statistic")["value"] + _swapped(monkeypatch) + with pytest.raises(stats.GroupError) as error: + _stats_of(function, frame, [0.05, 0.95], options) + assert str(error.value) == ( + f"1 groups have quantiles out of order (first: {{'target': 'b'}}, " + f"where q95 = {float(b['q05'])!r} is below q05 = {float(b['q95'])!r})." + f" A quantile never falls as its level rises, so these statistics " + f"are wrong." + ) + assert error.value.group == {"target": "b"} + + def test_a_crossing_past_a_missing_quantile_is_found(self, monkeypatch): + """q05 above q95 with q50 NaN between them. It went red with the + running highest quantile taken with NaN, which hid the pair.""" + frame = _two_targets(False) + _swapped(monkeypatch, missing="q50") + with pytest.raises(stats.GroupError, match=r"where q95 = .* is below q05 = "): + _pooled(frame, [0.05, 0.5, 0.95]) + + @pytest.mark.parametrize("summation", ["fast", "exact"]) + @pytest.mark.parametrize("weights", [None, [1.0, 1.0, 1.0, 1.0]]) + def test_the_step_median_above_the_step_just_over_it_passes( + self, summation, weights + ): + """One of the two cases. Under "lower_step" the 0.5 quantile of + members that count equally is their plain median, and the step + at 0.6 is the member one below, so q50 sits above q60. It went + red with the 0.5 quantile of the step checked.""" + got = _pooled( + _members([1.0, 2.0, 3.0, 4.0], weights), + [0.5, 0.6], + quantile_method="lower_step", + summation=summation, + ) + assert got["q50"] == 2.5 and got["q60"] == 2.0 + + @pytest.mark.parametrize("summation", ["fast", "exact"]) + @pytest.mark.parametrize("weights", [None, [1.0]]) + def test_the_step_median_of_one_member_passes(self, summation, weights): + """The other case. One member is the whole first step, so every + quantile of the step is -inf, and the plain median at 0.5 is the + member. It went red with the 0.5 quantile of the step checked.""" + got = _pooled( + _members([7.0], weights), + [0.05, 0.5, 0.95], + quantile_method="lower_step", + summation=summation, + ) + assert got["q05"] == got["q95"] == -np.inf and got["q50"] == 7.0 + + @pytest.mark.parametrize("options", SETTINGS) + def test_equal_quantiles_pass(self, options): + """Members of one value give one quantile at every level. It went + red with equal quantiles taken for a crossing.""" + got = _pooled(_members([2.0, 2.0, 2.0, 2.0]), [0.25, 0.5, 0.75], **options) + assert got["q75"] == 2.0 + + @pytest.mark.parametrize("options", SETTINGS) + def test_a_group_with_no_value_passes(self, options): + """Its quantiles are NaN, as is its mean. It went red with a NaN + quantile taken for a crossing.""" + frame = pd.concat( + [ + _members([1.0, 2.0, 3.0], target="a"), + _members([np.nan, np.nan, np.nan], target="b"), + ], + ignore_index=True, + ) + out = pooled_statistics( + frame, sample_dims=["draw"], quantiles=[0.25, 0.75], **options + ) + assert out.loc[out["target"] == "b", "value"].isna().all() + + def test_the_levels_go_in_their_order_and_the_mean_is_not_one(self): + """Quantiles asked for highest first, and a mean far above q95. + It went red with the levels taken in the order asked for.""" + got = _pooled(_members(list(range(20)) + [1e6]), [0.95, 0.05]) + assert got["q05"] == 1.0 and got["q95"] == 19.0 and got["mean"] > 19.0 + + +class TestPlainMedian: + """Every output has a 'plain_median' column, True on the 0.5 + quantile of "lower_step" where its members count equally, which is + then their plain median, and False on every other row.""" + + SETTINGS = TestInfiniteStatistics.SETTINGS + + @staticmethod + def _marked(out: pd.DataFrame) -> set[tuple[str, str]]: + rows = out.loc[out["plain_median"], ["target", "statistic"]] + return set(rows.itertuples(index=False, name=None)) + + @pytest.mark.parametrize("function", ["pooled_statistics", "summarize_samples"]) + @pytest.mark.parametrize("options", SETTINGS) + @pytest.mark.parametrize("weighted", [False, True]) + def test_only_the_step_median_of_members_counting_equally_is_marked( + self, function, options, weighted + ): + """Without weights every member counts the same, so under + "lower_step" both targets' q50 is the plain median. Their weights + here are not equal, so with them nothing is. It went red with + nothing marked, and with every method's q50 marked.""" + if weighted and options["quantile_method"] == "linear": + pytest.skip("linear quantiles are refused with weights") + frame = _two_targets(weighted, years=function == "summarize_samples") + out = _stats_of(function, frame, [0.05, 0.5, 0.95], options) + assert out["plain_median"].dtype == bool + step = options["quantile_method"] == "lower_step" and not weighted + assert self._marked(out) == ({("a", "q50"), ("b", "q50")} if step else set()) + + @pytest.mark.parametrize("summation", ["fast", "exact"]) + @pytest.mark.parametrize("method", ["lower_step", "inverted_cdf"]) + def test_equal_weights_mark_it_and_unequal_ones_do_not(self, summation, method): + """Target t's kept weights are equal once its member of weight + zero is left out, and b's are not. Under "inverted_cdf" equal + weights give no median, so nothing is marked. It went red with + every q50 of the step marked, and with "inverted_cdf"'s q50 of + equal weights marked.""" + frame = pd.concat( + [ + _members([1.0, 2.0, 3.0, 4.0, 9.0], [2.0, 2.0, 2.0, 2.0, 0.0]), + _members([1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 1.0, 1.0], target="b"), + ], + ignore_index=True, + ) + out = pooled_statistics( + frame, + sample_dims=["draw"], + quantiles=[0.5, 0.75], + weight_col="w", + quantile_method=method, + summation=summation, + ) + if method == "lower_step": + assert self._marked(out) == {("t", "q50")} + assert out.loc[out["plain_median"], "value"].tolist() == [2.5] + else: + assert self._marked(out) == set() + + def test_a_group_with_no_value_is_not_marked(self): + """Its q50 is NaN and no median of anything. It went red with such + a group marked.""" + frame = pd.concat( + [ + _members([1.0, 2.0, 3.0], target="a"), + _members([np.nan, np.nan, np.nan], target="b"), + ], + ignore_index=True, + ) + out = pooled_statistics( + frame, + sample_dims=["draw"], + quantiles=[0.5], + quantile_method="lower_step", + summation="fast", + ) + assert self._marked(out) == {("a", "q50")} + + @pytest.mark.parametrize("function", ["pooled_statistics", "window_means"]) + def test_data_with_the_column_is_refused(self, function): + """It is a column of statistics, so the data is already + summarized. It went red with the column taken as an identity + column.""" + frame = _timed().assign(plain_median=False) + with pytest.raises(ValueError, match=r"a 'plain_median' column"): + if function == "window_means": + window_means( + frame, time_col="year", windows=[(2040, 2049)], summation="fast" + ) + else: + pooled_statistics( + frame.drop(columns="year"), + sample_dims=["draw", "year"], + quantiles=[0.5], + quantile_method="linear", + summation="fast", + ) + + class TestBothHalves: @pytest.mark.parametrize("weighted", [False, True]) def test_summarize_samples_is_the_two_steps(self, weighted):