Skip to content

About

Aggregate impact region results to GADM administrative units, with published weight files

Resources

Stars

1 star

Watchers

0 watching

Forks

Repository files navigation

CIL-regionalization

Python GADM 2.0 weights GADM 4.1 weights SMME weights

Climate impact results come at impact region level, but most analyses need them at country, state, or district level. This package does that aggregation step. Published weight files describe how impact regions overlap administrative units, and the library applies them to your data and takes the statistics over the Monte Carlo draws. It does four things.

Every public function, class and config key is in the reference, with its signature, its default and its docstring. The worked examples are whole runs on real projections, with their outputs committed.

Installation

Straight from GitHub:

pip install "git+https://github.com/ClimateImpactLab/cil_regionalization.git"
pip install "cil_regionalization[netcdf] @ git+https://github.com/ClimateImpactLab/cil_regionalization.git"

or from a clone:

pip install .                # library and CLI
pip install '.[netcdf]'      # also read NetCDF Monte Carlo trees

uv pip install . works too. The geospatial stack (geopandas, shapely, rasterio, exactextract) installs with it and ships wheels on Linux and macOS. [netcdf] reads the NetCDF Monte Carlo trees, [examples] adds what the example notebooks need (the NetCDF readers, jupyter and matplotlib), [bigquery] adds the BigQuery generation backend, [dev] adds pytest. Python 3.10 or newer. A pipeline config that needs an extra the environment does not have is refused before the tree is walked, by the dry run as well.

To run the examples from a clone at the versions in uv.lock (on Python 3.11 and newer, the versions in envs/requirements-cluster.freeze.txt, which the test suite passed against):

uv sync --extra examples

The envs/ directory and examples/montecarlo/runs/ exist to reproduce the runs behind the published results on the University of Chicago RCC cluster; they are not part of installing or using the package.

Quick example

import cil_regionalization as cilreg

weights = cilreg.fetch_weights("gadm20-adm1-per-source")
result = cilreg.apply_weights(
    weights,
    my_draws,
    kind="extensive",
    weight="pop",
    data_version="world-combo-201710",
    # drop this line if the draws cover every impact region
    restrict_to_sources={(h,) for h in my_draws["hierid"].unique()},
)
stats = cilreg.summarize_samples(
    result.frame,
    sample_dims=["batch", "gcm"],
    time_col="year",
    window=(2080, 2099),
    quantiles=[0.05, 0.5, 0.95],
    quantile_method="linear",
    summation="fast",
)

my_draws is a long table: one row per impact region and year (plus batch, model, and whatever other columns your sample has), with the region id in a hierid column and the numbers in a value column (another name works via value_col=). restrict_to_sources limits the aggregation to the regions the draws cover; leave it out only when they cover all 24,378. data_version names the impact region set the draws are keyed to; draws built on the published shapefile record below use world-combo-201710, and a mismatch with the weight file raises before any numbers are produced. fetch_weights downloads the file from its Zenodo record, verifies its checksum, and caches it under ~/.cache/cil_regionalization.

The same works from the command line: cilreg fetch --list shows every published weight file name, cilreg fetch <name> downloads and prints the cached path, cilreg cache list and cilreg cache clear manage the cache, and cilreg pipeline <config.toml> runs a whole Monte Carlo tree from one config file.

How it works

The pipeline: geometries and rasters go into weight generation, which produces weight files; weight files plus impact region draws go through application, then statistics, then results.

The top lane happens once per pair of geometries: intersect the administrative boundaries, the impact regions, and a population raster, and record what share of each intersection carries. The result is a weights parquet plus a manifest that says exactly what produced it, published on Zenodo. The bottom lane is what you do day to day: fetch the weight file, apply it to your Monte Carlo draws, compute statistics at the end.

Both aggregation operations are the same multiply and add; what differs is which way the weights are normalized. For a total (dollars, deaths), each region's value is split between the units it touches, and the pieces must add back up:

value(u) = sum over r of w(r, u) * value(r),
where the w(r, u) for one region r sum to 1

For an average (a death rate, a temperature), each unit's value is the population weighted mean over the regions inside it:

value(u) = sum over r of w(r, u) * value(r),
where the w(r, u) for one unit u sum to 1

Quantiles do not pass through sums: the 95th percentile of a sum is not the sum of 95th percentiles, because that would need every region to hit its worst draw together. The pipeline aggregates each Monte Carlo draw separately, takes quantiles at the end, and rejects input that already contains quantiles.

What the output says about its targets

Every row apply_weights returns carries weight_share, the share of its target's weight basis behind the value. The basis is the raw column of the weight in the file, the population or the crop area of each piece of the target. A row is 1.0 when every piece with basis had a value, and below 1.0 when a source region was missing from the data or had no value there. A piece with no crop area carries no basis, so a unit whose corn is all in some of its regions is whole. A filter on the column keeps the partial targets out.

A target the weights have and the output lacks is listed in AppliedResult.targets with its reason. "no weight" is a target none of whose pieces has a weight, a unit with no crop area for that crop. "no data" is one whose weighted regions are none of them in the data. "zero denominator" is a ratio's target whose denominator sums to zero in every row, which has no ratio. A row of a target whose denominator sums to zero in that row alone is left out and the target is not. apply_weights logs how many of each it found, naming the denominator.

A pipeline run writes weight_share on every row of its statistics, the smallest share any pooled leaf gave the target. Its manifest lists under target_coverage the targets left out of every pooled leaf, by reason, and the partial ones with their shares. The leaves manifest records the same for each leaf.

window_means, pooled_statistics and summarize_samples do not group by a weight_share column. A window mean carries the smallest share of its years with a value, and a statistic the smallest of the members n_members counts, since a statistic is only as good as its weakest draw.

Choosing the right type of weights

Ask one question: does adding your variable across regions produce a meaningful total?

Variable Weight file kind Why
Dollars, deaths, counts ...-per-source extensive A total is split between the units it touches
Rates, temperatures, shares ...-per-destination intensive An average is taken over the regions in each unit
A ratio needed at the target level, like percent of GDP ...-per-source ratio Sum the numerator and denominator separately, divide after

A file built one way cannot do the other's job. The library checks the kind you declare against the direction the file records and raises on a mismatch.

Reading the Monte Carlo trees

In the mortality, labor, and energy trees, the effect of climate change is a file's rebased variable minus the same variable of its -histclim sibling, whatever the file stem; rebased on its own is not it. No adaptation is the exception and stands alone. The Climate Impact Lab memo "The art of rebasing and histclim" has the reasoning.

Energy adds two traps of its own. The physical values are GJ per capita, although the files say kWh/pc. The dollar -price...-levels files understate by exactly 0.0036, because a GJ quantity was multiplied by a per-kWh price; divide by 0.0036 to repair. Energy also has no Monte Carlo draws: its uncertainty lives in delta-method trees, where rebased holds the variance and rebased_bcde the gradient per regression coefficient. Aggregate the gradients with the weights and take one quadratic form against the embedded covariance matrix (aggregate_gradient and delta_method); summing independently drawn region values understates the aggregate spread.

Joining a table

A [[join]] adds one column from a table to each leaf's rows, under the name it gives, and a use names that column: data.denominator_col, a step's by, or the keys of a later join. A join at "source" is made after the histclim difference and before the weights, where a row is one source region in one year, so a ratio is one of totals. A join at "file" is made on each file before the difference, for the steps there, and is gone before it.

[[join]]
name = "pop"
path = "tables/population.parquet"
format = "parquet"           # parquet, csv or netcdf
value = "people"
keys = { region = "hierid", yr = "year", scenario = "ssp" }
fixed = { sex = "all" }
at = "source"
on_missing = "error"         # "nan" lets the rows the table lacks through

[data]
kind = "ratio"
denominator_col = "pop"

keys maps a column of the table to a dimension of the run, which is a leaf column, a tree level, or the column of an earlier join. fixed holds a column of the table at one value. at has no default, and "file" and "source" are built. reduce = { over = ["region"], by = "max" } reduces the table over those columns before it joins, so a cap over regions arrives as one value for each of the keys left, and a NaN in the reduced rows leaves that value NaN. Two joins compose. A table of region to country adds a country column that only the next join keys on, so a national table reaches a run without weights.

Before the tree is walked, the dry run as well, a table is refused if it holds statistics, if a key repeats, if a value a use computes with is not a number, if a key column holds another kind of value than its dimension, or if a key column matches none of the run's values. A row the run declares and the table lacks or holds as NaN is refused under "error" and counted under "nan". Without weights the regions are known only in the leaves, and each leaf refuses its own. In a ratio a row left NaN takes its source out of both sums, and weight_share says so. The path is local. The manifest records each join with the hash of its table, the values that match nothing and the rows it lacked, and a reduce refuses leaves joined with another table.

Transforming each cell

A [[step]] transforms each cell's value in the leaf pass, in the order the steps are listed. At "file" a step acts on the leaf and on its histclim sibling apart, before the difference, so a level is transformed before it is differenced. At "source" it acts on the difference, before the weights. The steps below make a level of each file and then bound it, so the difference is one of levels.

[[step]]
op = "exp"
at = "file"

[[step]]
op = "multiply"
by = "baseline"        # a join made at "file"
at = "file"

[[step]]
op = "min"
by = "cap"             # a join made at "file", reduced over regions
at = "file"

exp takes no operand. add, multiply and min take a joined column by or a constant, divide takes by and runs only at "source" in a run without weights, which is how an impact-region share is made, and recentre subtracts the mean over a window of years, which every group of a leaf has to have in full. op and at have no default, and a step that names the operand its op does not take is refused.

The steps and the joins are each listed in the order the pass reaches their points, "file" before "source", and a step reads only a join made at its own point. A list out of that order is refused with the step and the point it should come after, before the tree is walked. In a run with weights a divide is refused, and kind = "ratio" divides the totals instead. The manifest records the steps and, for each min, the cells its bound took, and a reduce refuses leaves made with other steps. data.factor_cols is gone, and a config that names it is refused with the multiply step that replaces it.

Climate model weights

Climate Impact Lab projections weight climate models by the SMME weights. summarize_samples and pooled_statistics take weight_col, a column with one weight per sample member. The default is unweighted; use the weights when the numbers will sit next to results from these projections.

The weight files are published as their own Zenodo record (doi:10.5281/zenodo.22003542), one per RCP (rcp45_SMME_weights.tsv, rcp85_SMME_weights.tsv; columns quantile, model, weight). fetch_model_weights downloads the table of an rcp from that record, checks it against the md5 the record declares, and caches it, so every product reads the same table. attach gives every draw the weight of its model, so the weight repeats across batches:

from cil_regionalization.pipelines.montecarlo import load_model_weight_names

names = load_model_weight_names("examples/model_weights/smme_rcp85_names.toml")
weights = cilreg.fetch_model_weights("rcp85", table_names=names)
draws["weight"] = weights.attach(draws["gcm"])
stats = cilreg.summarize_samples(
    draws,
    sample_dims=["batch", "gcm"],
    time_col="year",
    window=(2080, 2099),
    quantiles=[0.05, 0.5, 0.95],
    weight_col="weight",
    quantile_method="lower_step",
    summation="fast",
)

A model takes the row of its own name, letter for letter, or the row declared for it, and a model with neither is refused. Nothing reads a name to decide what it means, so a weight cannot land on the wrong model by a rule nobody sees. The published tables do not pass as they stand. They name the models in lower case, some with a trailing *, and the surrogates without the surrogate_ prefix of the trees, so ACCESS1-0 is the row access1-0* and surrogate_GFDL-CM3_94 the row gfdl-cm3_94. Until the tables are rewritten with the trees' names, a run declares each model's row, model name to table name, written out. examples/model_weights/ holds the pairs for both published tables, which the code above reads. The refusal names the row a model comes closest to, and the two ways out, fixing the table or declaring the row.

read_model_weights does the same for a file on disk. It reads the file once and refuses a table that has a name twice, and two models declared to one row.

weights = cilreg.read_model_weights("rcp85_SMME_weights.tsv", table_names=names)
draws["weight"] = weights.attach(draws["gcm"])
entry = weights.record(leaf_models)  # one model name per leaf pooled

attach raises if a model has no row, or two models take one row. record returns what a manifest should keep about the run: the file's path and SHA256, the rows declared, each model that was given a weight with its row, that weight and its number of leaves, and the rows no model took with their weights. The two lists together are the whole table, so the statistics can be rerun from the manifest if the file is lost. A pipeline run writes this entry to its manifest as model_weights_record, and takes the declared rows as [stats.model_weight_names]:

[stats.model_weight_names]
"ACCESS1-0" = "access1-0*"
"surrogate_GFDL-CM3_94" = "gfdl-cm3_94"

Weighted quantiles follow the historical extraction tool: the left step inverse of the weighted empirical distribution, not the interpolated quantiles of the unweighted path. Pooling without weights while model_dims names the climate model warns once. Filter UnweightedModelWeightsWarning where equal weights are meant. On the Mexico sample (examples/rates) the weights barely move the median and pull the 95th percentile down by about a fifth.

quantile_method says how a quantile is computed, by the name of the computation:

  • "inverted_cdf" is the estimator of a quantile, the standard inverse of the empirical distribution (Hyndman and Fan type 1), the smallest member value whose cumulative weight share reaches q. It is the same with or without weights, and always returns the value of a member.
  • "linear" interpolates between two members, so it can return a number no member holds. It is computed by numpy, so it is numpy.quantile(method="linear") and xarray's .quantile to the last bit. It has no weighted form and is refused with weights.
  • "lower_step" is for reproducing the historical extraction tool, not for estimating a quantile. It returns the member one below the one "inverted_cdf" returns, so it is biased low at every quantile, except the median of members that count equally. Without weights every member counts the same, which is what that tool did when it was told to use no model weights. A quantile at or below the first member's share is -inf.

The names say what each computes, so pick by that, not by the name. A member with weight zero is dropped before any of them, and before the mean and the counts, so no quantile returns the value of a member that weighs nothing.

With four members that count equally the three give three different 95th percentiles. "inverted_cdf" gives the fourth member, "linear" a value between the third and the fourth, and "lower_step" the third.

summation says how a mean is summed:

  • "fast" is the vectorised sum of pandas and numpy. Its last bits depend on the order the rows arrive in, which in a pipeline run with several workers is the order the workers finish in.
  • "exact" takes the window means and the pooled mean from exactly rounded sums, so the order cannot change them. With weights it also takes the cumulative weight shares of "lower_step" and "inverted_cdf" from exact sums, and takes equal values in order of weight. A share that equals q in exact arithmetic is then decided by the rule and not by the order the weights were added in, and the row order cannot move a quantile.

Neither option has a default. summarize_samples and pooled_statistics take both, window_means takes summation, and a pipeline config sets them under [stats]. The manifest records both. summation says how a mean is summed and decides nothing else.

An infinite member value is refused under every quantile method and sum, naming where it is, because an infinity in impact data means something upstream broke. A value in a year no window covers is not looked at. The one infinity a statistic can have is the -inf of "lower_step" at or below its first step, which it is by definition: with equal weights a quantile at or below 1/n of the members. It is 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.

Statistics are not taken in again. A leaf or a histclim file that holds statistics is refused by its name. A frame of them is refused by apply_weights, regroup and the statistics. Rows hold statistics when they have a statistic, plain_median or quantile column, or a column named for a quantile or a mean such as q05 or tas_mean. A NetCDF file's dimensions and coordinates count as columns, so a file of xarray quantiles is refused by its quantile coordinate. A difference, an aggregation or a window mean has to be formed from the draws before the statistics are taken. Taken of statistics it gives something like a ratio of quantiles or a mean of medians, which is not a statistic of anything. The refusal has no setting.

Country values from state values

A country value is not a statistic of its states' statistics, since a 95th percentile of a sum is not the sum of 95th percentiles. regroup takes a reduced frame, one value a target, window and draw, as a pipeline run writes it with output.write_reduced = true, to coarser targets, and the statistics are pooled after.

reduced = pd.read_parquet("mortality_adm1.reduced.parquet")
country = cilreg.regroup(
    reduced,
    id_fields=["ISO", "ID_1"],
    by=["ISO"],
    kind="extensive",
    value_col="rebased",
    summation="exact",
)
stats = cilreg.pooled_statistics(
    country.assign(weight=weights.attach(country["gcm"])),
    sample_dims=["batch", "gcm"],
    value_col="rebased",
    quantiles=[0.05, 0.5, 0.95],
    weight_col="weight",
    quantile_method="lower_step",
    summation="exact",
)

"extensive" sums the states. A country is NaN in a window and member where one of its states has no value, since a sum over fewer states is not the country's total, and its statistics take the members where it has one. "intensive" takes the mean weighted by each state's basis, which target_basis(artifact, "croparea") gives from the weights the states were aggregated with, the crop area or the population of each, over the states with a value. It writes weight_share, the share of the country's basis that mean rests on, exactly 1 for a country whose states all have a value, and pooled_statistics carries the smallest of its members' into each statistic. The regroup is exact when every impact region lies in one country, as they do.

Combining runs

A total over crops is the sum of each crop's run, and a change is one tree's run less another's. Neither is a sum of statistics, so a combine config adds the runs' leaves member by member, target by target and year by year inside the windows, and the statistics are taken after, as stage reduce takes them.

[combine]
op = "sum"

[[combine.input]]
name = "corn"
leaves_manifest = "corn/leaves/corn.leaves.manifest.json"

[[combine.input]]
name = "rice"
leaves_manifest = "rice/leaves/rice.leaves.manifest.json"

[stats]  # as in a pipeline config

[output]
dir = "all_crops"

[reduce.pandas]
memory_gb = 6

cilreg pipeline combine.toml runs it, and writes the statistics and their manifest and nothing else. An input is named by the leaves manifest its run wrote with output.write_leaves = true. A statistics file is never an input. "sum" adds two or more extensive runs, since a sum of rates is not a rate of anything. "difference" takes the second of two runs of one kind from the first. A NaN in any run makes the member's value NaN at that target and year. Under "exact" summation a sum of three or more runs is exactly rounded, so the order of the inputs does not change it, and under "fast" they are added in the order given.

Warming levels are a limitation of this version. A combine config with [stats.warming_levels] is refused, since the path that would take each member's periods from the declared GMST table, with whole windows and the members counted at each level, has no test yet. Nothing in the runs' leaves stands in the way, since they hold every year, so the limitation lifts once that path is tested.

The runs have to share their tree levels, their target table and their leaf columns. A member is the leaves of the runs with the same level values. members = "same", the default, refuses runs whose members differ, and members = "common" combines the members every run has and records those left out of each run. Pairing members by their level values is asserted and not checked, and the manifest says so in words. Where a level such as the batch indexes draws each run made on its own, the combination pairs independent draws.

A target an extensive run leaves out for "no weight" holds none of that run's quantity, so it counts as zero there. A target a run leaves out for any other reason is left out of the combination as "left out of an input", and one every run leaves out for "no weight" is left out for that reason. A run that lacks a row another has inside a window is refused, since a window mean over fewer years is another quantity.

The manifest records each input by the SHA256 of its leaves manifest, with its sign, its aggregation digest, its kind and the targets it counts as zero, and a digest of the operation and the inputs in order. So two combinations of different runs, or of the same runs in another order, are told apart. cilreg.combine is the same arithmetic on frames a script holds.

Warming levels

assign_warming_levels gives each member of a temperature table the warming level it is at in a calendar period. A member is one series of global mean temperature, named by the columns of the table that are not the year or the value: a model and an rcp, a model and an ssp, or whatever the table has.

table = cilreg.read_gmst("gmst.csv", member_cols=["gcm", "rcp"])
levels = cilreg.assign_warming_levels(
    table,
    reference_period=(1986, 2005),
    offset=0.61,
    levels=[1.5, 2, 3, 4, 5],
    half_width=0.25,
    periods=[
        cilreg.Period(gmst_span=(2040, 2059), impact_span=(2040, 2058)),
        cilreg.Period(gmst_span=(2080, 2099), impact_span=(2080, 2099)),
    ],
    smoothing="unknown",
    members=cilreg.members_that_join(
        {"gcm": ["CCSM4", "MIROC5"]}, table.members, table.member_cols
    ),
)
levels.windows_of(("MIROC5", "rcp85"))
levels.record()

For each member the series is rebased by taking off its own mean over reference_period and adding offset. The mean of the rebased series over a period's gmst_span picks the level. A level holds a mean from half_width below it to half_width above it, both ends included. A mean in no band gives the member no level in that period, so with a half-width of 0.25 a member at 2.5 belongs to neither 2 nor 3. Two bands may share an end, as 1.5 and 2 share 1.75, and a mean exactly there goes to the level declared first. Bands that overlap are refused.

None of reference_period, offset, levels, half_width, periods, smoothing and members has a default. The offset is the warming from a pre-industrial baseline to the reference period, and it is only right for that pair: 0.61 goes with 1986 to 2005 in AR5 (WG1 TS.2.2.1), and AR6 gives another figure against another period. A call that leaves one out fails.

A period has two spans, both including their first and last year. The gmst_span is the years the temperature is averaged over, and the impact_span the years of the impacts that go under the level, which is also what the period is labelled by. They are separate because a product may average its impacts over other years than its temperature.

Nothing is smoothed. The series is taken as it is in the table, and smoothing says in words how it was smoothed before, "unknown" if nobody knows. It goes into the record as written.

members are the members that join. A member of the table that does not join is at no level, and the record lists it under excluded with the reason. A member that joins and has no row, or lacks a year of the reference period or of a gmst_span, is refused by name. One that does not join is not looked at, so a table may hold a member with no values, as the mortality paper's does under rcp45. A name is matched as it is written, and nothing reads a name to decide what a member is.

members_that_join turns a declaration into the members. "declared" is every member declared. A mapping of member columns to values takes each member whose value in every column named is listed, so a list of models joins under each scenario there is. A value listed that no member declared holds is refused by name, since it is most likely a name written wrong.

In a pipeline config the same settings go under [stats.warming_levels], in place of stats.windows, and join is the declaration, over the members the tree declares. It has no default. examples/warming_levels/ar5_cmip5_smme.toml is the block for the CMIP5 models, which the test of the paper's bins reads too, and its README says where each number comes from. load_warming_levels reads such a file on its own. The example here is a physical product as the Inequality Paper makes one: each member's window is collapsed to its mean first, over nineteen impact years, and the quantile is the extraction tool's step.

[stats]
sample_dims = ["batch", "rcp", "gcm"]
model_dims = ["gcm"]
time_col = "year"
quantiles = [0.05, 0.5, 0.95]
quantile_method = "lower_step"
summation = "fast"
time_reduction = "window_mean"

[stats.warming_levels]
gmst = "gmst.csv"
member = ["gcm", "rcp"]      # columns of the table, each a tree level
reference_period = [1986, 2005]
offset = 0.61
levels = [1.5, 2, 3, 4, 5]
half_width = 0.25
smoothing = "unknown"

[stats.warming_levels.join]
gcm = ["CCSM4", "MIROC5"]    # or join = "declared", above this table

[[stats.warming_levels.periods]]
gmst_span = [2040, 2059]
impact_span = [2040, 2058]

[[stats.warming_levels.periods]]
gmst_span = [2080, 2099]
impact_span = [2080, 2098]

[output]
dir = "out"
write_leaves = true

[reduce.pandas]
memory_gb = 128

A leaf's member is read off its level values, here its gcm and its rcp, so the tree declares both scenarios and the statistics pool them. A leaf is pooled under the level its member has in a period and left out of the periods in which it has none. The statistics file has a warming_level column next to window, which stays the period, and three counts on every row. n_members is the draws behind the statistic, a batch of a model counting as one. n_models is the distinct values of stats.model_dims among them, the climate models, and n_bin_members the distinct members of the temperature table, a model under an rcp. Those are the numbers to read a 95th percentile over four models by. A level nobody is at in a period has no row, and the manifest records it with a zero.

The statistics come from the leaf files under every stage, as when the years are pooled, so stage all writes the leaves and then reduces them, and --stage reduce gives other levels, other periods or the other reduction from the same leaves. time_reduction = "window_mean" collapses each member's window first and "pooled" pools its years. "per_year" is refused with warming levels, since a level is reached over a period. The span is what is written: [2040, 2058] is nineteen years.

A config that leaves out reference_period, offset, levels, half_width, smoothing or periods is refused. So is one that sets stats.windows or stats.model_weights as well: the members at a warming level count equally.

The paper's two families differ in both settings. Its physical products collapse each member's window first and take the extraction tool's step, so quantile_method = "lower_step", as in the example. Its valued products pool the years with the models and the draws over twenty years and take xarray's quantile, so time_reduction = "pooled" with quantile_method = "linear" and periods whose impact span is twenty years. A member the tree declares that has no row in the table is refused before any leaf is read. A leaf that lacks a year of an impact span its member is pooled over, as a row or as a value, is refused by name, since its mean would be over fewer years than the span says. The manifest carries the whole record under warming_levels.

windows_of gives, for one member, the periods in which it has a level, each with the level, the period's label and its impact years. record returns what a manifest should keep: the table's path and SHA256, every setting above, the rule for a shared end, each member's mean and level in each period, the number of members at each declared level with a zero where nobody is, and the members with no level.

Keeping the aggregated leaves

A pipeline run keeps nothing between the weights and the statistics unless output.write_leaves = true. With it, every leaf is written after the weights are applied, with its years, to leaves/<level values>/<name>.aggregated.parquet under the output directory. It is off by default because the leaves of a product take far more disk than its statistics.

A leaf file is plain parquet. Its columns are target_ordinal, the id fields, the leaf's own dimensions and the value. Its rows are sorted by target and cut into row groups of 128 targets, the same targets in the same group of every leaf, with an empty group where a leaf has none of them. So the rows of a range of targets can be read from every leaf without reading the rest. leaves/targets.<digest>.parquet gives the target of each ordinal. The ids keep the type the weights artifact gives them, strings or integers of their width, as the GADM 2.0 artifacts give ID_1 and ID_2 as int64, and the statistics carry them in that type on every route. The digest is over the field names, their types and the ids, so an integer 1 and a string "1" are different targets. How a string is stored, as string or large_string, is not part of it.

The footer of a leaf file says what made it, as JSON under the key cil_regionalization.leaf: the weight, the kind, the versions, the SHA256 of the two files of the weights artifact, the leaf's level values and its source file. No path is part of that identity. Paths are recorded and never compared.

leaves/<output.stem>.leaves.manifest.json lists the leaves of a run with their accounting, sizes and hashes. It is written before the first leaf with "complete": false and again when every leaf has succeeded, so a run that was killed leaves a manifest that says so. Runs under different stems can share an output directory when their leaves differ, as one stem a scenario does. A run that would write a leaf another stem's manifest lists is refused.

cilreg pipeline config.toml --stage aggregate

writes the leaves and their manifest and stops before the statistics.

cilreg pipeline config.toml --stage reduce

takes the statistics from leaves written before, without opening the source tree or the weights. Everything under [stats] can differ from the run that wrote the leaves, so other windows or quantiles cost one pass over the leaf files and no aggregation. A product with other windows takes its own output.stem and names the leaves it reduces with output.leaves_stem. It gives the same bits whatever the number of workers. Under summation = "exact" those are the bits all gives on one worker, whatever the size of the blocks. Under "fast" they are too when the leaves have no missing values. With missing values the last bit of a window mean can depend on the block, because on some pandas versions the mean of one group changes with what else is in the frame.

Reducing pools one block of targets at a time, so it needs to be told how much memory it may use:

[reduce.pandas]
memory_gb = 128   # for all the workers together
n_workers = 16    # run.n_workers unless set

--dry-run prints the blocks and the number of file opens that budget gives. The blocks are sized from an estimate of the bytes a kept row takes, 240 for a leaf with no dimension and 40 more for each dimension, 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. What a block takes follows the threads Arrow's readers decode with, so each process that reads sets them to its share of the CPUs the job was allotted, at least one, and to one where the platform does not say, whatever the shell that submitted the run had set. reduce.block_size.threads records the count beside the measurement, and aggregate_threads the aggregate's. The allocator Arrow takes its memory from is recorded there too and is not set. It is the one ARROW_DEFAULT_MEMORY_POOL names where the run was launched, or else the build's default, so the readings of two runs compare only when their memory_pool is the same. 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 judged, and that on Linux alone. A first block's growth is taken on Linux from the resident memory before it, VmRSS of /proc/self/status read at once with the peak, and on macOS from the peak once the worker had set itself up, and only a block whose peak rose above both readings before it has one, so a growth is never zero. A worker's later block is recorded without a growth. 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. So is a block run in the process that planned the run, which reuses what the planning freed. reduce.block_size.over_every_block gives the spread of the measured blocks' bytes a kept row, which is the spread between workers, the heaviest measured block over the estimate, and first_over_heaviest_measured, the run's first block over the heaviest measured one. That last says no more than the spread does. Whether the first block resembles the heaviest of all the blocks cannot be answered by this measure, since the heaviest may be one that could not be measured. A tolerance on the judged first block rests instead on every block being of one size and doing the same work, and on how closely the workers' first blocks agree.

Someone who has measured their own runs can declare the size of a block instead, in targets, a whole number of the leaves' row groups:

[reduce.pandas]
targets_per_block = 4096   # in place of memory_gb

A declared size warns, since it overrides the estimate, and the manifest records it as declared, with the first block's measurement beside it and not judged.

Before any work the leaves are checked against their manifest: what aggregated them has to be what the config says, field by field, and every file has to be there with its size. A path is not part of that. If the weights or the tree have moved, the run says so and goes on, because the hashes in the manifest say what they were. --verify-leaves also hashes every leaf file against the manifest, which reads all of them and is the way to rule out a file changed in place.

A cell of tree.exclude has one value for each level, and "*" stands for every value of its level, so ["*", "rcp85", "ACCESS1-0"] leaves that model out of that scenario in every batch.

Reducing fewer leaves than were aggregated is allowed, with a narrower tree.expect or a longer tree.exclude. The statistics file then has an n_members column whether the config asks for it or not, so that the smaller sample shows in the file. output.write_reduced is not available under reduce.

A leaf's own dimension has to be an integer, a float, a boolean or a plain string when leaves are written. A categorical, datetime or nullable column is refused, because pandas 2 and pandas 3 write those differently.

What happens to the years

stats.time_reduction says what is done with the years of a member, and has no default:

  • "window_mean" averages each member's years inside a window first, and the statistics are over those means, one value a model and draw.
  • "pooled" takes no window mean. Every year of a member inside a window is a member of the sample, so a quantile is over models, draws and years together and carries the spread from year to year. A year inside two windows is pooled in both.
  • "per_year" takes no window mean either and keeps the year. The statistics are over the members within each year from the first to the last of stats.years, which takes the place of stats.windows, and the file has a year column where the others have window. It is a time series, one row a target, year and statistic.
[stats]
time_reduction = "per_year"
years = [2020, 2099]

[output]
write_leaves = true

[reduce.pandas]
memory_gb = 128

The rows of "pooled" and "per_year" are the leaves' own rows, far more than one process can hold, so their statistics always come from the leaf files, one block of targets at a time. Stage all writes the leaves and then reduces them. It asks for output.write_leaves = true and for the memory budget before it reads a leaf. The blocks are sized after the leaves are written, so a budget too small for one row group is found then. The leaves stay, and --stage reduce takes the statistics from them with a larger budget. output.write_reduced is refused, and so is a run without [weights]. A config that still has stats.pool_years is refused and told which value to write.

Per year, a year a member lacks is left out of that year's statistics, and n_members shows the smaller sample. Nothing is refused for it.

What pooling changes:

  • The mean is over member-years. When every member has every year of the window it is the mean of the window means, up to rounding. A member that lacks years has fewer rows in the sample and so counts for less than a member with all of them.
  • A model weight applies to each member-year.
  • quantile_method and summation work as before. No window mean is taken, so summation acts on the pooled mean alone.
  • With include_n_members the file has three counts. n_members is what it is without pooling, the members behind a statistic: those with a value in the window and, with model weights, a weight above zero. n_sample is the member-years behind it, and n_models the climate models among them.
  • The manifest records time_reduction, next to quantile_method and summation, and years for a product per year.

Your own NetCDF

A file on a regular lat-lon grid, with 1-D lat and lon coordinates, becomes a cell table in one call:

cells, grid = cilreg.read_netcdf_grid("tas.nc", ["tas"])
out = cilreg.apply_weights(
    weights, cells, kind="intensive", weight="pop", value_col="tas", data_version=grid
)

The grid identity comes from the coordinates (resolution, cell centres or edges, longitude convention), and every coordinate is mapped to its cell index and back to a centroid; a value that is not a cell centre raises. A file with a longitude beyond 180 or below 0 needs nothing more. A subset in the east hemisphere, with every longitude in 0 to 180, always needs grid=: the same coordinates are valid on both conventions, so the file cannot say which one your weights use. The error prints the two calls that work, for example grid="grid-0.25deg- center-[-180,180)" or the [0,360) one, which also wraps a 0 to 360 file onto the other. grid takes the string or a GridSpec. Nothing is regridded: coordinates that sit on no grid are an error, and so are cells that are not square. Cells masked in every slice are left out, so apply_weights reports a weighted cell that has no data; a cell masked in only some slices raises.

Worked example

examples/france/ is the whole chain in one notebook, for mortality in metropolitan France. It builds weights on boundaries of its own with cilreg run, fetches the published ones, applies them three ways, takes the statistics with and without the climate model weights, runs cilreg pipeline over a Monte Carlo tree for the three time reductions and the warming levels, and checks the manifests against the files. Each of the other examples covers one piece.

examples/aggregation/ aggregates one batch of Monte Carlo mortality projections, all 33 climate models, for Colombia. Its notebook maps a single draw next to a pooled quantile, shows percent of GDP with the ratio kind, and plots the spread of draws; run_example.py adds municipalities and rates from the command line. examples/rates/ aggregates the effect of climate change on Mexican mortality rates to municipalities on both GADM versions. examples/labor/ aggregates the effect of climate change on labor supply to Indian states, physical in minutes per worker per day and valued in 2005 PPP USD. examples/energy/ aggregates the effect of climate change on energy use to United States states with delta-method uncertainty: gradient aggregation, the quadratic form, and the spread that independent draws would lose. examples/climate/ starts from raw daily BCSD temperature for the Philippines and Germany and aggregates heating and cooling degree days to impact regions, through segment weights read with from_table, and to provinces with the grid weights. Notebook outputs are committed, so they read without running.

Generating new weights

A TOML config names the target geometry, the source geometry or grid, the weighting rasters, and the normalization direction. cilreg run <config.toml> writes the weights parquet plus a manifest that records where everything came from, with checksums. cilreg validate <config.toml> checks a config without computing anything. From Python, cilreg.generate_weights(config) does the same as run; it takes a Config or a TOML path and returns the result. Polygons held in memory go through a GeoParquet file first (gdf.to_parquet(path)), so the manifest can record the file's hash. A run whose weights fail the sum-to-one check writes nothing and raises SumToOneError, whichever way it was started. Worked configurations, including the GADM target preparation and the full generation runs, live under examples/.

GADM 2.0 and GADM 4.1 have different unit universes and different keys, so results built on one cannot be compared with the other. Each geometry version is its own record, and every manifest states which version it was built against.

Four records are published on Zenodo:

  • the impact region shapefile, world-combo-201710 (doi:10.5281/zenodo.21934131)
  • the SMME climate model weights (doi:10.5281/zenodo.22003542): rcp45_SMME_weights.tsv and rcp85_SMME_weights.tsv, used by the statistics stage rather than the spatial aggregation
  • GADM 2.0 weights (doi:10.5281/zenodo.21934155): gadm20-adm1-per-source, gadm20-adm1-per-destination, gadm20-adm2-per-source, gadm20-adm2-per-destination
  • GADM 4.1 weights (doi:10.5281/zenodo.21935431), keyed by GADM's GID codes: gadm41-adm1-per-source, gadm41-adm1-per-destination, gadm41-adm2-per-source, gadm41-adm2-per-destination. GADM 4.1 draws coastlines differently from the impact region geometry, so 1,178 coastal regions are partially covered; the manifests record this, and apply_weights needs allow_partial_coverage=True to proceed

The weights were built against two GADM versions, recorded in every manifest by their version labels: GADM 2.0 (label gadm-2.0-impactmap-copy-2025, a processed copy of the combined GADM 2.0 shapefile) and GADM 4.1 (label gadm-4.10-impactmap-copy-2022, the gadm_410.gpkg GeoPackage as distributed by GADM). You can obtain the same versions from GADM directly. The dissolved target layers are large (840 MB for GADM 2.0, about 2 GB for GADM 4.1) and are not distributed, since GADM restricts redistribution; regenerate them with the dissolve scripts under examples/gadm20/ and examples/gadm41/. The targets manifest records the source file's checksum, so you can confirm a regenerated set started from the same input.

Reference

docs/reference.md lists every name that import cil_regionalization as cilreg gives, 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. A name that is not in it is internal and may change. cilreg --help and cilreg <command> --help describe the command line.

About

Aggregate impact region results to GADM administrative units, with published weight files

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages