From 1fa7a74f8fc43de3958f5b0cf7e9264ccd24b194 Mon Sep 17 00:00:00 2001 From: Sebastian Cadavid Sanchez Date: Wed, 2 Dec 2026 14:22:55 -0600 Subject: [PATCH] give a country no total when one of its states has none --- CHANGELOG.md | 2 + README.md | 14 ++- cil_regionalization/regroup.py | 53 ++++++++---- docs/reference.md | 23 +++-- tests/unit/test_regroup.py | 152 ++++++++++++++++++++++++++++++++- 5 files changed, 215 insertions(+), 29 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4d92ff2..df9c9cf 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## Unreleased +- `regroup` gives NaN for an extensive group in a window and member where one of its targets has no value, so a country made from a reduced frame that holds a NaN changes when made again. +- New: an intensive `regroup` writes `weight_share`, the share of each group's basis its mean rests on, exactly 1 for a complete group. - `window_means`, `pooled_statistics` and `summarize_samples` take a `weight_share` column as a share rather than as part of the group key, and give each value the smallest share of what it was taken over, so statistics taken of a frame that holds the column change when taken again. - The mass balance sums both sides in float64, so a leaf read as float32, as a NetCDF leaf without a histclim difference is, is no longer failed by the rounding of its own total. - New: a config with `[combine]` sums extensive runs, or takes one run from another, member by member, target and year before the statistics, and records each input by the hash of its leaves manifest. Warming levels are not built for it yet. diff --git a/README.md b/README.md index 35b8fde..c39469f 100644 --- a/README.md +++ b/README.md @@ -524,10 +524,16 @@ stats = cilreg.pooled_statistics( ) ``` -`"extensive"` sums the states. `"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. The regroup is exact when every impact +`"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 diff --git a/cil_regionalization/regroup.py b/cil_regionalization/regroup.py index b10ecf1..62a6e0a 100644 --- a/cil_regionalization/regroup.py +++ b/cil_regionalization/regroup.py @@ -14,7 +14,7 @@ import numpy as np import pandas as pd -from cil_regionalization.apply import WeightsArtifact +from cil_regionalization.apply import SHARE_COLUMN, WeightsArtifact from cil_regionalization.schema import raw_column from cil_regionalization.statistics_input import refuse_statistics @@ -56,14 +56,21 @@ def regroup( value a group and every other column, so that a country is the sum or the mean of its states in each window and sample member. - "extensive" sums the values and takes no ``basis``. "intensive" - takes the mean weighted by each target's basis, the frame - `target_basis` gives, over the targets with a value. A group with no - value is NaN, and so is an intensive group whose targets with a - value have a basis of zero. ``summation`` is "fast" or "exact", as - for the statistics. Raises if ``by`` is not among ``id_fields``, if - ``basis`` is given for "extensive" or left out for "intensive", if - a row's target has no basis, or if ``reduced`` holds statistics.""" + "extensive" sums the values and takes no ``basis``. A group in which + a target has no value is NaN in that window and member, since a sum + over fewer targets is not the group's total, and that NaN is its + record. "intensive" takes the mean weighted by each target's basis, + the frame `target_basis` gives, over the targets with a value, and + writes 'weight_share', the share of the group's basis the mean rests + on. It is exactly 1 where every target has a value, 0 where none + has, and NaN where the group's basis is zero, and + `pooled_statistics` carries the smallest of a statistic's members + into it. A group with no value is NaN, and so is an intensive group + whose targets with a value have a basis of zero. ``summation`` is + "fast" or "exact", as for the statistics. Raises if ``by`` is not + among ``id_fields``, if ``basis`` is given for "extensive" or left + out for "intensive", if a row's target has no basis, or if + ``reduced`` holds statistics.""" from cil_regionalization.stats import check_summation check_summation(summation) @@ -99,18 +106,32 @@ def regroup( weights = pd.Series(found.to_numpy(dtype="float64"), index=reduced.index) has = values.notna() work = reduced[keys].assign( - _wx=(weights * values).where(has), _w=weights.where(has, 0.0) + _wx=(weights * values).where(has), + _w=weights.where(has, 0.0), + _missing=(~has).astype(np.int64), ) + summed = ["_wx", "_w"] + if kind == "intensive": + # the basis of every target, with a value or not, which the share + # of the mean is taken of + work["_basis"] = weights + summed.append("_basis") grouped = work.groupby(keys, sort=False, observed=True, dropna=False) if summation == "exact": - sums = grouped[["_wx", "_w"]].agg( + sums = grouped[summed].agg( lambda part: math.fsum(part.dropna()) if part.notna().any() else np.nan ) else: - sums = grouped[["_wx", "_w"]].sum(min_count=1) + sums = grouped[summed].sum(min_count=1) + sums["_missing"] = grouped["_missing"].sum() sums = sums.reset_index() if kind == "extensive": - sums[value_col] = sums["_wx"] - else: - sums[value_col] = sums["_wx"] / sums["_w"].where(sums["_w"] != 0.0) - return sums[keys + [value_col]] + # a total of the targets with a value would be the total of + # another group + sums[value_col] = sums["_wx"].where(sums["_missing"] == 0) + return sums[keys + [value_col]] + sums[value_col] = sums["_wx"] / sums["_w"].where(sums["_w"] != 0.0) + total = sums["_basis"] + share = (sums["_w"] / total.where(total != 0.0)).where(sums["_missing"] != 0, 1.0) + sums[SHARE_COLUMN] = share.where(total != 0.0) + return sums[keys + [value_col, SHARE_COLUMN]] diff --git a/docs/reference.md b/docs/reference.md index 7c602bc..ed1a75e 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -698,14 +698,21 @@ regroup( value a group and every other column, so that a country is the sum or the mean of its states in each window and sample member. -"extensive" sums the values and takes no ``basis``. "intensive" -takes the mean weighted by each target's basis, the frame -`target_basis` gives, over the targets with a value. A group with no -value is NaN, and so is an intensive group whose targets with a -value have a basis of zero. ``summation`` is "fast" or "exact", as -for the statistics. Raises if ``by`` is not among ``id_fields``, if -``basis`` is given for "extensive" or left out for "intensive", if -a row's target has no basis, or if ``reduced`` holds statistics. +"extensive" sums the values and takes no ``basis``. A group in which +a target has no value is NaN in that window and member, since a sum +over fewer targets is not the group's total, and that NaN is its +record. "intensive" takes the mean weighted by each target's basis, +the frame `target_basis` gives, over the targets with a value, and +writes 'weight_share', the share of the group's basis the mean rests +on. It is exactly 1 where every target has a value, 0 where none +has, and NaN where the group's basis is zero, and +`pooled_statistics` carries the smallest of a statistic's members +into it. A group with no value is NaN, and so is an intensive group +whose targets with a value have a basis of zero. ``summation`` is +"fast" or "exact", as for the statistics. Raises if ``by`` is not +among ``id_fields``, if ``basis`` is given for "extensive" or left +out for "intensive", if a row's target has no basis, or if +``reduced`` holds statistics. ### `target_basis` diff --git a/tests/unit/test_regroup.py b/tests/unit/test_regroup.py index 17a71fc..a3cc4e1 100644 --- a/tests/unit/test_regroup.py +++ b/tests/unit/test_regroup.py @@ -3,11 +3,13 @@ from __future__ import annotations +import math + import numpy as np import pandas as pd import pytest -from cil_regionalization.apply import WeightsArtifact +from cil_regionalization.apply import SHARE_COLUMN, WeightsArtifact from cil_regionalization.regroup import regroup, target_basis from cil_regionalization.schema import OutputSchema, SourceUnits from cil_regionalization.stats import pooled_statistics @@ -167,6 +169,154 @@ def test_regrouped_then_pooled_is_the_country_statistics(self): assert a["value"].item() == 31.5 +class TestAStateWithNoValue: + """A sum over fewer states is not the country's total, so under + "extensive" a country is NaN in a member and window where a state of + it has no value, and only there.""" + + KEYS = ["ISO", "window", "batch", "gcm"] + + @staticmethod + def _of(frame, summation): + return regroup( + frame, + id_fields=ID, + by=["ISO"], + kind="extensive", + value_col="value", + summation=summation, + ) + + @pytest.mark.parametrize("summation", ["fast", "exact"]) + def test_the_country_is_nan_in_that_member_and_window(self, summation): + """It went red with A the value of its other state, 10.""" + frame = _reduced() + hole = ( + (frame["ISO"] == "A") + & (frame["ID_1"] == 2) + & (frame["batch"] == "b0") + & (frame["gcm"] == "CCSM4") + ) + frame.loc[hole, "value"] = np.nan + out = self._of(frame, summation).set_index(self.KEYS)["value"] + assert np.isnan(out[("A", "2080-2099", "b0", "CCSM4")]) + assert out[("A", "2080-2099", "b1", "CCSM4")] == 10.5 + 20.5 + assert out[("B", "2080-2099", "b0", "CCSM4")] == 40.0 + + @pytest.mark.parametrize("summation", ["fast", "exact"]) + def test_a_country_whose_states_all_have_values_is_unchanged(self, summation): + """To the bit, beside a country that has a NaN. B has three states + of values whose sum depends on the order they are added in.""" + rng = np.random.default_rng(0) + rows = [ + { + "ISO": iso, + "ID_1": state, + "window": "2080-2099", + "batch": f"b{b}", + "gcm": gcm, + "value": float(rng.normal()) * 10.0 ** int(rng.integers(-3, 4)), + } + for iso, states in (("A", 2), ("B", 3)) + for state in range(1, states + 1) + for b in range(3) + for gcm in ("CCSM4", "MIROC5") + ] + frame = pd.DataFrame(rows) + frame.loc[(frame["ISO"] == "A") & (frame["ID_1"] == 1), "value"] = np.nan + got = self._of(frame, summation) + got_b = got[got["ISO"] == "B"].reset_index(drop=True) + alone = self._of(frame[frame["ISO"] == "B"], summation).reset_index(drop=True) + pd.testing.assert_frame_equal(got_b, alone, check_exact=True) + b = frame[frame["ISO"] == "B"] + if summation == "fast": + want = b.groupby(self.KEYS, sort=False)["value"].sum(min_count=1) + else: + want = b.groupby(self.KEYS, sort=False)["value"].agg( + lambda part: math.fsum(part) + ) + assert got_b["value"].to_numpy().tobytes() == want.to_numpy().tobytes() + assert got.loc[got["ISO"] == "A", "value"].isna().all() + + +class TestTheShareOfAnIntensiveGroup: + """An intensive country is the mean over its states with a value, and + weight_share says how much of its basis that is. A's states hold 1 + and 3 of its basis of 4, and B's one state all of its.""" + + KEYS = ["ISO", "window", "batch", "gcm"] + + @staticmethod + def _of(frame, summation="exact", kind="intensive"): + return regroup( + frame, + id_fields=ID, + by=["ISO"], + kind=kind, + value_col="value", + summation=summation, + basis=BASIS if kind == "intensive" else None, + ) + + @staticmethod + def _hole(frame, states=(2,)): + at = ( + (frame["ISO"] == "A") + & frame["ID_1"].isin(states) + & (frame["batch"] == "b0") + & (frame["gcm"] == "CCSM4") + ) + frame.loc[at, "value"] = np.nan + return frame + + @pytest.mark.parametrize("summation", ["fast", "exact"]) + def test_a_complete_group_rests_on_exactly_all_of_it(self, summation): + """It went red with no column.""" + out = self._of(_reduced(), summation) + assert list(out.columns) == self.KEYS + ["value", SHARE_COLUMN] + assert out[SHARE_COLUMN].tolist() == [1.0] * len(out) + + @pytest.mark.parametrize("summation", ["fast", "exact"]) + def test_a_state_with_no_value_takes_its_basis_out(self, summation): + """Without state 2, A is state 1 and rests on a quarter of its + basis, and only in that member.""" + out = self._of(self._hole(_reduced()), summation).set_index(self.KEYS) + hole = ("A", "2080-2099", "b0", "CCSM4") + assert out.loc[hole, "value"] == 10.0 + assert out.loc[hole, SHARE_COLUMN] == 0.25 + assert out.loc[("A", "2080-2099", "b1", "CCSM4"), SHARE_COLUMN] == 1.0 + + def test_a_group_with_no_value_rests_on_none_of_it(self): + out = self._of(self._hole(_reduced(), states=(1, 2))).set_index(self.KEYS) + hole = ("A", "2080-2099", "b0", "CCSM4") + assert np.isnan(out.loc[hole, "value"]) + assert out.loc[hole, SHARE_COLUMN] == 0.0 + + def test_an_extensive_group_has_no_share(self): + """Its NaN is the record.""" + out = self._of(_reduced(), kind="extensive") + assert SHARE_COLUMN not in out.columns + + def test_pooled_after_it_a_country_is_one_row_with_its_smallest_share(self): + """The statistics are those of the frame without the share, and A + carries the quarter its one partial member rests on.""" + out = self._of(self._hole(_reduced())) + options = dict( + sample_dims=["batch", "gcm"], + value_col="value", + quantiles=[0.5], + quantile_method="inverted_cdf", + summation="exact", + ) + stats = pooled_statistics(out, **options) + plain = pooled_statistics(out.drop(columns=SHARE_COLUMN), **options) + pd.testing.assert_frame_equal( + stats.drop(columns=SHARE_COLUMN), plain, check_exact=True + ) + shares = stats.groupby("ISO")[SHARE_COLUMN].unique() + assert shares["A"].tolist() == [0.25] and shares["B"].tolist() == [1.0] + + class TestTargetBasis: @staticmethod def _artifact(frame) -> WeightsArtifact: