From e659595554ad48d0f19fdd274607d580d71d569a Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 11:20:29 +0100 Subject: [PATCH 01/10] Keep each value whole in group-to-group map_to_entity(how="divide") The group-to-group divide branch divided each (source, target) pair row by the source's member count, so a source whose n members touched k targets kept k/n of its value. It now weights each pair row by the members that pair holds, value * pair_count / source_count, so a source's shares add up to its value. Hypothesis properties cover crossing and nested tax units, SPM units and households in both person-link layouts. Fixes #768 Co-Authored-By: Claude Opus 5.5 --- changelog.d/768.fixed.md | 1 + src/policyengine/core/dataset.py | 22 ++- tests/test_entity_mapping_group_properties.py | 181 ++++++++++++++++++ 3 files changed, 199 insertions(+), 5 deletions(-) create mode 100644 changelog.d/768.fixed.md create mode 100644 tests/test_entity_mapping_group_properties.py diff --git a/changelog.d/768.fixed.md b/changelog.d/768.fixed.md new file mode 100644 index 000000000..f9bcbd092 --- /dev/null +++ b/changelog.d/768.fixed.md @@ -0,0 +1 @@ +Split each source value among its members in group-to-group `map_to_entity(how="divide")`, so the shares add up to the value instead of part of it. diff --git a/src/policyengine/core/dataset.py b/src/policyengine/core/dataset.py index 87f94b00f..35eab87b4 100644 --- a/src/policyengine/core/dataset.py +++ b/src/policyengine/core/dataset.py @@ -348,23 +348,35 @@ def map_to_entity( target_link_key, as_index=False )[agg_cols].first() elif how == "divide": - # Count persons in each source group + # Split each source value equally among the source's members, + # then sum those per-person shares within each target group. + # source_with_target has one row per (source, target) pair, so + # each row carries the shares of the members that pair holds: + # value * pair_count / source_count. A source's shares then + # add up to its value, whichever targets its members are in. source_group_counts = ( person_df.groupby(source_link_key, as_index=False) .size() .rename(columns={"size": "__source_count"}) ) + pair_counts = ( + person_df.groupby( + [source_link_key, target_link_key], as_index=False + ) + .size() + .rename(columns={"size": "__pair_count"}) + ) source_with_target = source_with_target.merge( source_group_counts, on=source_link_key, how="left" - ) + ).merge(pair_counts, on=[source_link_key, target_link_key], how="left") - # Divide values by source group count (per-person share) for col in agg_cols: source_with_target[col] = ( - source_with_target[col] / source_with_target["__source_count"] + source_with_target[col] + * source_with_target["__pair_count"] + / source_with_target["__source_count"] ) - # Now aggregate (sum of per-person shares) to target level aggregated = source_with_target.groupby( target_link_key, as_index=False )[agg_cols].sum() diff --git a/tests/test_entity_mapping_group_properties.py b/tests/test_entity_mapping_group_properties.py new file mode 100644 index 000000000..f42a32f71 --- /dev/null +++ b/tests/test_entity_mapping_group_properties.py @@ -0,0 +1,181 @@ +"""Properties of map_to_entity between two group entities. + +Every case links each person to a household and to two group entities inside +it, ``tax_unit`` and ``spm_unit``. In the crossing cases the two are drawn +independently within each household, so one tax unit's members can sit in +several SPM units and the reverse. In the nested cases every tax unit sits +inside one SPM unit. + +These tests use the module-level function on plain tables, so they need no +country model. +""" + +from itertools import permutations + +import pandas as pd +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st +from microdf import MicroDataFrame + +from policyengine.core import map_to_entity + +GROUPS = ("tax_unit", "spm_unit", "household") + + +def _build(people: list[tuple[int, int, int]], prefixed: bool, values: dict): + """Build entity tables from (household, spm_unit, tax_unit) id triples. + + ``values`` maps a group entity to {group id: value}; groups without a value + get 0. ``prefixed`` stores person links as ``person__id`` instead of + ``_id``, the two layouts map_to_entity accepts. + """ + link = (lambda e: f"person_{e}_id") if prefixed else (lambda e: f"{e}_id") + person = pd.DataFrame( + { + "person_id": range(len(people)), + link("household"): [h for h, _, _ in people], + link("spm_unit"): [s for _, s, _ in people], + link("tax_unit"): [t for _, _, t in people], + "person_weight": 1.0, + } + ) + data = {"person": MicroDataFrame(person, weights="person_weight")} + for entity in GROUPS: + ids = sorted(person[link(entity)].unique()) + table = pd.DataFrame( + { + f"{entity}_id": ids, + f"{entity}_weight": 1.0, + "value": [float(values.get(entity, {}).get(i, 0)) for i in ids], + } + ) + data[entity] = MicroDataFrame(table, weights=f"{entity}_weight") + return data + + +@st.composite +def entity_data(draw, nested: bool): + """Random households of 1-5 people with tax units and SPM units in them.""" + people = [] + for h in range(draw(st.integers(1, 4))): + for _ in range(draw(st.integers(1, 5))): + spm = draw(st.integers(0, 2)) + if nested: + # Each tax unit id belongs to exactly one SPM unit. + tax = spm * 3 + draw(st.integers(0, 2)) + else: + tax = draw(st.integers(0, 2)) + people.append((h, h * 100 + spm, h * 100 + tax)) + values = {} + for entity in GROUPS: + index = {"household": 0, "spm_unit": 1, "tax_unit": 2}[entity] + ids = sorted({p[index] for p in people}) + amounts = draw( + st.lists(st.integers(-1_000, 100_000), min_size=len(ids), max_size=len(ids)) + ) + values[entity] = dict(zip(ids, amounts)) + return _build(people, draw(st.booleans()), values), values + + +def _mapped(data, source, target, how) -> pd.DataFrame: + """Map the value column, as a plain (unweighted) DataFrame.""" + return pd.DataFrame(map_to_entity(data, source, target, columns=["value"], how=how)) + + +@settings(max_examples=200, deadline=None) +@given(entity_data(nested=False)) +def test_divide_keeps_each_total(case): + data, values = case + for source, target in permutations(GROUPS, 2): + mapped = _mapped(data, source, target, "divide") + assert len(mapped) == len(data[target]) + assert mapped["value"].to_numpy().sum() == pytest.approx( + sum(values[source].values()) + ), (source, target) + + +@settings(max_examples=200, deadline=None) +@given(entity_data(nested=False)) +def test_divide_matches_the_route_through_persons(case): + """Group-to-group divide equals group->person divide, then person->group sum.""" + data, _ = case + for source, target in permutations(GROUPS, 2): + per_person = _mapped(data, source, "person", "divide") + through_persons = pd.Series( + map_to_entity( + data, + "person", + target, + values=per_person["value"].to_numpy(), + how="sum", + ) + ) + direct = _mapped(data, source, target, "divide") + assert direct["value"].to_numpy() == pytest.approx( + through_persons.to_numpy() + ), (source, target) + + +@settings(max_examples=200, deadline=None) +@given(entity_data(nested=True)) +def test_sum_keeps_the_total_when_sources_nest_in_targets(case): + data, values = case + for source, target in [ + ("tax_unit", "spm_unit"), + ("tax_unit", "household"), + ("spm_unit", "household"), + ]: + mapped = _mapped(data, source, target, "sum") + assert mapped["value"].to_numpy().sum() == pytest.approx( + sum(values[source].values()) + ), (source, target) + # When every source sits in one target, sum and divide agree. + assert mapped["value"].to_numpy() == pytest.approx( + _mapped(data, source, target, "divide")["value"].to_numpy() + ), (source, target) + + +@settings(max_examples=200, deadline=None) +@given(entity_data(nested=True)) +def test_sum_from_a_containing_group_gives_each_member_group_its_value(case): + """Mapping a group onto the smaller groups inside it repeats its value. + + This pins the current coarse-to-fine behaviour, which the UK + household-to-benunit test checks only for one benunit per household. + """ + data, values = case + person = pd.DataFrame(data["person"]) + link = "person_tax_unit_id" if "person_tax_unit_id" in person else "tax_unit_id" + spm_link = "person_spm_unit_id" if "person_spm_unit_id" in person else "spm_unit_id" + spm_of_tax = person.groupby(link)[spm_link].first() + mapped = _mapped(data, "spm_unit", "tax_unit", "sum") + for tax_id, value in zip(mapped["tax_unit_id"], mapped["value"]): + assert value == values["spm_unit"][spm_of_tax[tax_id]] + + +def test_divide_keeps_a_two_person_unit_whole_inside_one_household(): + """A $100 tax unit whose two members share a household maps to $100. + + Before the fix, divide split the value by the unit's two members but added + it once per (tax unit, household) pair, so the household received $50. + """ + data = _build( + [(1, 10, 100), (1, 10, 100)], + prefixed=False, + values={"tax_unit": {100: 100}}, + ) + mapped = _mapped(data, "tax_unit", "household", "divide") + assert mapped["value"].tolist() == [100.0] + + +def test_divide_splits_a_unit_across_targets_by_member_share(): + """Two of a tax unit's three members are in SPM unit 10, one in SPM unit 11.""" + data = _build( + [(1, 10, 100), (1, 10, 100), (1, 11, 100)], + prefixed=True, + values={"tax_unit": {100: 300}}, + ) + mapped = _mapped(data, "tax_unit", "spm_unit", "divide") + by_spm = dict(zip(mapped["spm_unit_id"], mapped["value"])) + assert by_spm == pytest.approx({10: 200.0, 11: 100.0}) From 6d9efe69200a84fce975f63b0d7aa5e66a0958ce Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 12:22:42 +0100 Subject: [PATCH 02/10] Strengthen the group-mapping properties and describe the divide split Round-1 review and a mutation sweep found test gaps. The random cases now shuffle every table, add memberless groups, draw household weights and map two value columns. New properties check weighted totals, each target's share against a person-by-person count, and the values= return type. The coarse-to-fine sum pin covers household and SPM unit sources, and a fixed case pins a member with no target link. Totals compare with an absolute tolerance so exact zeros pass. The map_to_entity docstrings, the divide comment and the guide now say how group-to-group divide splits a value and what happens to unlinked members and memberless groups. Co-Authored-By: Claude Opus 5.5 --- .claude/policyengine-guide.md | 2 +- src/policyengine/core/dataset.py | 13 +- tests/test_entity_mapping_group_properties.py | 340 ++++++++++++++---- 3 files changed, 286 insertions(+), 69 deletions(-) diff --git a/.claude/policyengine-guide.md b/.claude/policyengine-guide.md index e7523bd70..7ea13456b 100644 --- a/.claude/policyengine-guide.md +++ b/.claude/policyengine-guide.md @@ -466,7 +466,7 @@ gov.usda.snap.normal_allotment.max[1] # 1 person - `how='sum'`: Aggregate by summing (person → group default) - `how='first'`: Take first value in group - `how='project'`: Broadcast group value to members (group → person default) -- `how='divide'`: Split equally among members +- `how='divide'`: Split equally among members; between groups, each member's share goes to the target group that member is in ## Response patterns diff --git a/src/policyengine/core/dataset.py b/src/policyengine/core/dataset.py index 35eab87b4..ebc933d4f 100644 --- a/src/policyengine/core/dataset.py +++ b/src/policyengine/core/dataset.py @@ -45,7 +45,8 @@ def map_to_entity( target_entity (str): The target entity name. columns (list[str], optional): List of column names to map. If None, maps all columns. values (list, optional): List of values to use instead of column data. - how (str): Aggregation method ('sum' or 'first') when mapping to higher-level entities (default 'sum'). + how (str): Aggregation method (default 'sum'). See the module-level + map_to_entity for the methods each direction accepts. Returns: MicroDataFrame: The mapped data at the target entity level. @@ -120,8 +121,11 @@ def map_to_entity( values: List of values to use instead of column data. If provided, creates a single unnamed column how: Aggregation method (default 'sum') - For person → group: 'sum' (aggregate), 'first' (take first value) - - For group → person: 'project' (broadcast), 'divide' (split equally) - - For group → group: 'sum', 'first', 'project', 'divide' + - For group → person: 'project' (broadcast; the default 'sum' maps to + it), 'divide' (split equally) + - For group → group: 'sum', 'first', 'project', 'divide' (split + equally among the source's members, each share going to the + target group that member is in) Returns: MicroDataFrame: The mapped data at the target entity level @@ -354,6 +358,9 @@ def map_to_entity( # each row carries the shares of the members that pair holds: # value * pair_count / source_count. A source's shares then # add up to its value, whichever targets its members are in. + # A member with no target link keeps its share out of every + # target, and a source with no members adds nothing, as in + # group -> person divide followed by person -> group sum. source_group_counts = ( person_df.groupby(source_link_key, as_index=False) .size() diff --git a/tests/test_entity_mapping_group_properties.py b/tests/test_entity_mapping_group_properties.py index f42a32f71..b476833ea 100644 --- a/tests/test_entity_mapping_group_properties.py +++ b/tests/test_entity_mapping_group_properties.py @@ -1,64 +1,103 @@ """Properties of map_to_entity between two group entities. -Every case links each person to a household and to two group entities inside -it, ``tax_unit`` and ``spm_unit``. In the crossing cases the two are drawn -independently within each household, so one tax unit's members can sit in -several SPM units and the reverse. In the nested cases every tax unit sits -inside one SPM unit. - -These tests use the module-level function on plain tables, so they need no -country model. +The random cases link each person to a household and to two group entities +inside it, ``tax_unit`` and ``spm_unit``. In the crossing cases the two are +drawn independently within each household, so one tax unit's members can sit +in several SPM units and the reverse. In the nested cases every tax unit sits +inside one SPM unit. Each random group table may also hold one group with no +members, every random table lists its rows in a shuffled order, and each +household draws a weight that its people and groups share. Every group carries +two value columns, ``value`` and ``other``. + +These tests call the module-level function on plain tables, so they run +without a country model under ``pytest --noconftest``. """ +from collections import Counter, namedtuple from itertools import permutations +import numpy as np import pandas as pd import pytest from hypothesis import given, settings from hypothesis import strategies as st -from microdf import MicroDataFrame +from microdf import MicroDataFrame, MicroSeries from policyengine.core import map_to_entity GROUPS = ("tax_unit", "spm_unit", "household") +COLUMNS = ("value", "other") +# Position of each group's id in a person's (household, spm_unit, tax_unit) triple. +INDEX = {"household": 0, "spm_unit": 1, "tax_unit": 2} +# Ids for groups with no members; person-drawn ids stay below 1,000. +EMPTY_ID = {"household": 9_001, "spm_unit": 9_002, "tax_unit": 9_003} +# Shares are sums of quotients, so exact totals of 0 need an absolute tolerance. +ABS = 1e-6 + +Case = namedtuple("Case", "data amounts people weights") -def _build(people: list[tuple[int, int, int]], prefixed: bool, values: dict): +def _build( + people: list[tuple[int, int, int]], + prefixed: bool, + amounts: dict, + empty: frozenset = frozenset(), + rng=None, + weights: dict | None = None, +): """Build entity tables from (household, spm_unit, tax_unit) id triples. - ``values`` maps a group entity to {group id: value}; groups without a value - get 0. ``prefixed`` stores person links as ``person__id`` instead of - ``_id``, the two layouts map_to_entity accepts. + ``amounts`` maps a column to {group entity: {group id: amount}}; groups + without an amount get 0. ``prefixed`` stores person links as + ``person__id`` instead of ``_id``, the two layouts + map_to_entity accepts. Each entity in ``empty`` gets one more group, with + no members. ``rng`` shuffles the rows of every table. ``weights`` maps a + household id to the weight its people and groups share (default 1.0). """ + weights = weights or {} link = (lambda e: f"person_{e}_id") if prefixed else (lambda e: f"{e}_id") + rows = list(people) + if rng is not None: + rng.shuffle(rows) person = pd.DataFrame( { - "person_id": range(len(people)), - link("household"): [h for h, _, _ in people], - link("spm_unit"): [s for _, s, _ in people], - link("tax_unit"): [t for _, _, t in people], - "person_weight": 1.0, + "person_id": range(len(rows)), + link("household"): [p[INDEX["household"]] for p in rows], + link("spm_unit"): [p[INDEX["spm_unit"]] for p in rows], + link("tax_unit"): [p[INDEX["tax_unit"]] for p in rows], + "person_weight": [weights.get(p[INDEX["household"]], 1.0) for p in rows], } ) data = {"person": MicroDataFrame(person, weights="person_weight")} for entity in GROUPS: - ids = sorted(person[link(entity)].unique()) + household_of = {p[INDEX[entity]]: p[INDEX["household"]] for p in people} + ids = sorted(household_of) + if entity in empty: + ids.append(EMPTY_ID[entity]) + if rng is not None: + rng.shuffle(ids) table = pd.DataFrame( { f"{entity}_id": ids, - f"{entity}_weight": 1.0, - "value": [float(values.get(entity, {}).get(i, 0)) for i in ids], + f"{entity}_weight": [ + weights.get(household_of.get(i), 1.0) for i in ids + ], } ) + for column in COLUMNS: + by_id = amounts.get(column, {}).get(entity, {}) + table[column] = [float(by_id.get(i, 0)) for i in ids] data[entity] = MicroDataFrame(table, weights=f"{entity}_weight") return data @st.composite -def entity_data(draw, nested: bool): +def entity_data(draw, nested: bool) -> Case: """Random households of 1-5 people with tax units and SPM units in them.""" people = [] + weights = {} for h in range(draw(st.integers(1, 4))): + weights[h] = draw(st.sampled_from([0.5, 1.0, 2.0, 7.0])) for _ in range(draw(st.integers(1, 5))): spm = draw(st.integers(0, 2)) if nested: @@ -67,72 +106,199 @@ def entity_data(draw, nested: bool): else: tax = draw(st.integers(0, 2)) people.append((h, h * 100 + spm, h * 100 + tax)) - values = {} - for entity in GROUPS: - index = {"household": 0, "spm_unit": 1, "tax_unit": 2}[entity] - ids = sorted({p[index] for p in people}) - amounts = draw( - st.lists(st.integers(-1_000, 100_000), min_size=len(ids), max_size=len(ids)) - ) - values[entity] = dict(zip(ids, amounts)) - return _build(people, draw(st.booleans()), values), values + empty = frozenset(e for e in GROUPS if draw(st.booleans())) + amounts = {} + for column in COLUMNS: + amounts[column] = {} + for entity in GROUPS: + ids = sorted({p[INDEX[entity]] for p in people}) + if entity in empty: + ids.append(EMPTY_ID[entity]) + drawn = draw( + st.lists( + st.integers(-1_000, 100_000), + min_size=len(ids), + max_size=len(ids), + ) + ) + amounts[column][entity] = dict(zip(ids, drawn)) + data = _build( + people, + draw(st.booleans()), + amounts, + empty=empty, + rng=draw(st.randoms(use_true_random=False)), + weights=weights, + ) + return Case(data, amounts, people, weights) + + +def _mapped(data, source, target, how, columns=COLUMNS) -> pd.DataFrame: + """Map value columns, as a plain (unweighted) DataFrame.""" + return pd.DataFrame( + map_to_entity(data, source, target, columns=list(columns), how=how) + ) + + +def _target_ids(data, target) -> list: + return pd.DataFrame(data[target])[f"{target}_id"].tolist() + + +def _assert_target_order(mapped: pd.DataFrame, data, target) -> None: + """The result lists the target table's groups in the table's row order. + Every table here has a RangeIndex; map_to_entity restores row order by + sorting on the index labels. + """ + assert mapped[f"{target}_id"].tolist() == _target_ids(data, target) + + +def _member_total(case: Case, column, entity, weighted=False) -> float: + """Sum of the amounts of the groups that have members.""" + household_of = {p[INDEX[entity]]: p[INDEX["household"]] for p in case.people} + return sum( + amount * (case.weights[household_of[i]] if weighted else 1.0) + for i, amount in case.amounts[column][entity].items() + if i in household_of + ) -def _mapped(data, source, target, how) -> pd.DataFrame: - """Map the value column, as a plain (unweighted) DataFrame.""" - return pd.DataFrame(map_to_entity(data, source, target, columns=["value"], how=how)) + +def _expected_divide(case: Case, column, source, target) -> dict: + """Each target group's share of the source amounts, counted person by person. + + Each source amount splits equally among the source's members, and each + member's share goes to that member's target group. Target groups with no + members get 0. + """ + size = Counter(p[INDEX[source]] for p in case.people) + expected = {t: 0.0 for t in _target_ids(case.data, target)} + for p in case.people: + s, t = p[INDEX[source]], p[INDEX[target]] + expected[t] += case.amounts[column][source][s] / size[s] + return expected @settings(max_examples=200, deadline=None) @given(entity_data(nested=False)) def test_divide_keeps_each_total(case): - data, values = case + """A source's shares add up to its amount, so column totals match. + + A group with no members has nobody to pass its amount to, so it adds + nothing. + """ for source, target in permutations(GROUPS, 2): - mapped = _mapped(data, source, target, "divide") - assert len(mapped) == len(data[target]) - assert mapped["value"].to_numpy().sum() == pytest.approx( - sum(values[source].values()) - ), (source, target) + mapped = _mapped(case.data, source, target, "divide") + _assert_target_order(mapped, case.data, target) + for column in COLUMNS: + assert mapped[column].to_numpy().sum() == pytest.approx( + _member_total(case, column, source), abs=ABS + ), (source, target, column) + + +@settings(max_examples=200, deadline=None) +@given(entity_data(nested=False)) +def test_divide_keeps_each_weighted_total(case): + """The result carries the target weights, so weighted totals match too. + + People and groups in a household share its weight, so each share keeps + its source's weight. + """ + for source, target in permutations(GROUPS, 2): + mapped = map_to_entity( + case.data, source, target, columns=list(COLUMNS), how="divide" + ) + target_weights = pd.DataFrame(case.data[target])[f"{target}_weight"] + for column in COLUMNS: + plain = pd.DataFrame(mapped)[column].to_numpy() + assert float(mapped[column].sum()) == pytest.approx( + float((plain * target_weights.to_numpy()).sum()), abs=ABS + ), (source, target, column) + assert float(mapped[column].sum()) == pytest.approx( + _member_total(case, column, source, weighted=True), abs=ABS + ), (source, target, column) + + +@settings(max_examples=200, deadline=None) +@given(entity_data(nested=False)) +def test_divide_gives_each_target_its_members_shares(case): + """Each target receives the shares of the members it holds, in every + column, and a target with no members receives 0.""" + for source, target in permutations(GROUPS, 2): + # columns=None maps every non-id, non-weight column. + mapped = pd.DataFrame(map_to_entity(case.data, source, target, how="divide")) + assert set(COLUMNS) <= set(mapped.columns) + for column in COLUMNS: + got = dict(zip(mapped[f"{target}_id"], mapped[column])) + assert got == pytest.approx( + _expected_divide(case, column, source, target), abs=ABS + ), (source, target, column) @settings(max_examples=200, deadline=None) @given(entity_data(nested=False)) def test_divide_matches_the_route_through_persons(case): """Group-to-group divide equals group->person divide, then person->group sum.""" - data, _ = case for source, target in permutations(GROUPS, 2): - per_person = _mapped(data, source, "person", "divide") + per_person = _mapped(case.data, source, "person", "divide", ["value"]) through_persons = pd.Series( map_to_entity( - data, + case.data, "person", target, values=per_person["value"].to_numpy(), how="sum", ) ) - direct = _mapped(data, source, target, "divide") + direct = _mapped(case.data, source, target, "divide", ["value"]) assert direct["value"].to_numpy() == pytest.approx( - through_persons.to_numpy() + through_persons.to_numpy(), abs=ABS + ), (source, target) + + +@settings(max_examples=100, deadline=None) +@given(entity_data(nested=False)) +def test_divide_with_values_matches_the_column_path(case): + """Passing the amounts as an array returns a weighted series that matches + naming the column.""" + for source, target in permutations(GROUPS, 2): + from_values = map_to_entity( + case.data, + source, + target, + values=pd.DataFrame(case.data[source])["value"].to_numpy(), + how="divide", + ) + from_column = map_to_entity( + case.data, source, target, columns=["value"], how="divide" + ) + assert isinstance(from_values, MicroSeries) + assert len(from_values) == len(case.data[target]) + assert pd.Series(from_values).to_numpy() == pytest.approx( + pd.DataFrame(from_column)["value"].to_numpy(), abs=ABS + ), (source, target) + assert float(from_values.sum()) == pytest.approx( + float(from_column["value"].sum()), abs=ABS ), (source, target) @settings(max_examples=200, deadline=None) @given(entity_data(nested=True)) def test_sum_keeps_the_total_when_sources_nest_in_targets(case): - data, values = case for source, target in [ ("tax_unit", "spm_unit"), ("tax_unit", "household"), ("spm_unit", "household"), ]: - mapped = _mapped(data, source, target, "sum") - assert mapped["value"].to_numpy().sum() == pytest.approx( - sum(values[source].values()) - ), (source, target) + mapped = _mapped(case.data, source, target, "sum") + _assert_target_order(mapped, case.data, target) + for column in COLUMNS: + assert mapped[column].to_numpy().sum() == pytest.approx( + _member_total(case, column, source), abs=ABS + ), (source, target, column) # When every source sits in one target, sum and divide agree. - assert mapped["value"].to_numpy() == pytest.approx( - _mapped(data, source, target, "divide")["value"].to_numpy() + assert mapped[list(COLUMNS)].to_numpy() == pytest.approx( + _mapped(case.data, source, target, "divide")[list(COLUMNS)].to_numpy(), + abs=ABS, ), (source, target) @@ -142,16 +308,28 @@ def test_sum_from_a_containing_group_gives_each_member_group_its_value(case): """Mapping a group onto the smaller groups inside it repeats its value. This pins the current coarse-to-fine behaviour, which the UK - household-to-benunit test checks only for one benunit per household. + household-to-benunit test checks only for one benunit per household. A + group with no members sits in no containing group and gets 0. """ - data, values = case - person = pd.DataFrame(data["person"]) - link = "person_tax_unit_id" if "person_tax_unit_id" in person else "tax_unit_id" - spm_link = "person_spm_unit_id" if "person_spm_unit_id" in person else "spm_unit_id" - spm_of_tax = person.groupby(link)[spm_link].first() - mapped = _mapped(data, "spm_unit", "tax_unit", "sum") - for tax_id, value in zip(mapped["tax_unit_id"], mapped["value"]): - assert value == values["spm_unit"][spm_of_tax[tax_id]] + for source, target in [ + ("spm_unit", "tax_unit"), + ("household", "tax_unit"), + ("household", "spm_unit"), + ]: + container = {p[INDEX[target]]: p[INDEX[source]] for p in case.people} + mapped = _mapped(case.data, source, target, "sum") + _assert_target_order(mapped, case.data, target) + for column in COLUMNS: + for target_id, value in zip(mapped[f"{target}_id"], mapped[column]): + if target_id in container: + expected = case.amounts[column][source][container[target_id]] + else: + expected = 0 + assert value == expected, (source, target, column, target_id) + + +def _one_column(column_amounts: dict) -> dict: + return {"value": column_amounts} def test_divide_keeps_a_two_person_unit_whole_inside_one_household(): @@ -163,9 +341,9 @@ def test_divide_keeps_a_two_person_unit_whole_inside_one_household(): data = _build( [(1, 10, 100), (1, 10, 100)], prefixed=False, - values={"tax_unit": {100: 100}}, + amounts=_one_column({"tax_unit": {100: 100}}), ) - mapped = _mapped(data, "tax_unit", "household", "divide") + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) assert mapped["value"].tolist() == [100.0] @@ -174,8 +352,40 @@ def test_divide_splits_a_unit_across_targets_by_member_share(): data = _build( [(1, 10, 100), (1, 10, 100), (1, 11, 100)], prefixed=True, - values={"tax_unit": {100: 300}}, + amounts=_one_column({"tax_unit": {100: 300}}), ) - mapped = _mapped(data, "tax_unit", "spm_unit", "divide") + mapped = _mapped(data, "tax_unit", "spm_unit", "divide", ["value"]) by_spm = dict(zip(mapped["spm_unit_id"], mapped["value"])) assert by_spm == pytest.approx({10: 200.0, 11: 100.0}) + + +def test_divide_leaves_out_the_share_of_a_member_with_no_target_link(): + """A $100 tax unit has two members, and only one has a household link. + + The linked member's household gets that member's $50 share. The other + share has no target to go to, as in the route through persons. This + case has no SPM units. + """ + person = pd.DataFrame( + { + "person_id": [0, 1], + "household_id": [1, np.nan], + "tax_unit_id": [100, 100], + "person_weight": 1.0, + } + ) + data = { + "person": MicroDataFrame(person, weights="person_weight"), + "tax_unit": MicroDataFrame( + pd.DataFrame( + {"tax_unit_id": [100], "tax_unit_weight": 1.0, "value": 100.0} + ), + weights="tax_unit_weight", + ), + "household": MicroDataFrame( + pd.DataFrame({"household_id": [1], "household_weight": 1.0}), + weights="household_weight", + ), + } + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [50.0] From faea7ff0f15a4bec99f3c9ad183d93174079d263 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Thu, 26 Nov 2026 12:59:57 +0100 Subject: [PATCH 03/10] Keep group-to-group divide exact for large, Decimal and oddly named columns Round-2 review found three regressions against main in the divide branch. value * pair_count overflowed int64 and turned large floats into inf; merging the counts into the source rows collided with source columns of the same name; and a NaN pair count for an unlinked member made the counts float, so Decimal amounts raised TypeError. The branch now drops rows without a target first, looks the integer counts up on a frame of keys alone, and divides before it multiplies. All three groupbys pass observed=True, so categorical links on pandas 2.x no longer build every category pair. New tests pin each counterexample, check that reweighting people changes no share, and check categorical links against plain ones. The changelog now says a group passes on its whole value when all its members link to target groups. Co-Authored-By: Claude Opus 5.5 --- changelog.d/768.fixed.md | 2 +- src/policyengine/core/dataset.py | 60 +++++---- tests/test_entity_mapping_group_properties.py | 116 ++++++++++++++++++ 3 files changed, 153 insertions(+), 25 deletions(-) diff --git a/changelog.d/768.fixed.md b/changelog.d/768.fixed.md index f9bcbd092..efc5feee2 100644 --- a/changelog.d/768.fixed.md +++ b/changelog.d/768.fixed.md @@ -1 +1 @@ -Split each source value among its members in group-to-group `map_to_entity(how="divide")`, so the shares add up to the value instead of part of it. +Split each source value among its members in group-to-group `map_to_entity(how="divide")`, so a group whose members all link to target groups passes on its whole value instead of part of it. diff --git a/src/policyengine/core/dataset.py b/src/policyengine/core/dataset.py index ebc933d4f..b00d2c98c 100644 --- a/src/policyengine/core/dataset.py +++ b/src/policyengine/core/dataset.py @@ -353,39 +353,51 @@ def map_to_entity( )[agg_cols].first() elif how == "divide": # Split each source value equally among the source's members, - # then sum those per-person shares within each target group. - # source_with_target has one row per (source, target) pair, so - # each row carries the shares of the members that pair holds: - # value * pair_count / source_count. A source's shares then - # add up to its value, whichever targets its members are in. - # A member with no target link keeps its share out of every + # then give each target group the shares of the members it + # holds: value / source_count * pair_count for each (source, + # target) row of source_with_target. A source whose members + # all link to target groups passes on its whole value. A + # member with no target link keeps its share out of every # target, and a source with no members adds nothing, as in # group -> person divide followed by person -> group sum. - source_group_counts = ( - person_df.groupby(source_link_key, as_index=False) + # Rows without a target carry no share, so they drop out here + # and every remaining row has integer counts. Dividing before + # multiplying keeps large values finite, and integer counts + # keep Decimal and other object values working. + linked = source_with_target[source_with_target[target_link_key].notna()] + pair_keys = [source_link_key, target_link_key] + pair_counts = ( + person_df.groupby(pair_keys, observed=True) .size() - .rename(columns={"size": "__source_count"}) + .rename("__pair_count") + .reset_index() ) - pair_counts = ( - person_df.groupby( - [source_link_key, target_link_key], as_index=False - ) + source_counts = ( + person_df.groupby(source_link_key, observed=True) .size() - .rename(columns={"size": "__pair_count"}) + .rename("__source_count") + .reset_index() + ) + # Look the counts up on a frame of keys alone, so no source + # column can collide with the count names. + counts = ( + linked[pair_keys] + .merge(pair_counts, on=pair_keys, how="left") + .merge(source_counts, on=source_link_key, how="left") + ) + source_n = pd.Series( + counts["__source_count"].to_numpy(), index=linked.index + ) + pair_n = pd.Series( + counts["__pair_count"].to_numpy(), index=linked.index ) - source_with_target = source_with_target.merge( - source_group_counts, on=source_link_key, how="left" - ).merge(pair_counts, on=[source_link_key, target_link_key], how="left") + shares = linked[[target_link_key]].copy() for col in agg_cols: - source_with_target[col] = ( - source_with_target[col] - * source_with_target["__pair_count"] - / source_with_target["__source_count"] - ) + shares[col] = linked[col] / source_n * pair_n - aggregated = source_with_target.groupby( - target_link_key, as_index=False + aggregated = shares.groupby( + target_link_key, as_index=False, observed=True )[agg_cols].sum() else: raise ValueError(f"Unsupported aggregation method: {how}") diff --git a/tests/test_entity_mapping_group_properties.py b/tests/test_entity_mapping_group_properties.py index b476833ea..2b9bcb8ca 100644 --- a/tests/test_entity_mapping_group_properties.py +++ b/tests/test_entity_mapping_group_properties.py @@ -14,6 +14,7 @@ """ from collections import Counter, namedtuple +from decimal import Decimal from itertools import permutations import numpy as np @@ -234,6 +235,24 @@ def test_divide_gives_each_target_its_members_shares(case): ), (source, target, column) +@settings(max_examples=100, deadline=None) +@given(entity_data(nested=False), st.randoms(use_true_random=False)) +def test_divide_counts_members_whatever_their_weights(case, rng): + """Divide splits by head count, so reweighting people changes no share.""" + person = pd.DataFrame(case.data["person"]).copy() + person["person_weight"] = [rng.choice([0.5, 1.0, 3.0, 7.0]) for _ in person.index] + reweighted = { + **case.data, + "person": MicroDataFrame(person, weights="person_weight"), + } + for source, target in permutations(GROUPS, 2): + assert _mapped( + reweighted, source, target, "divide" + ).to_numpy() == pytest.approx( + _mapped(case.data, source, target, "divide").to_numpy(), abs=ABS + ), (source, target) + + @settings(max_examples=200, deadline=None) @given(entity_data(nested=False)) def test_divide_matches_the_route_through_persons(case): @@ -389,3 +408,100 @@ def test_divide_leaves_out_the_share_of_a_member_with_no_target_link(): } mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) assert mapped["value"].tolist() == [50.0] + + +def _one_tax_unit(households, values: dict, weights=None) -> dict: + """Tables for tax unit 7, whose members link to ``households``. + + ``values`` maps a column name to the tax unit's amount, kept as given so + integer, Decimal and other dtypes reach map_to_entity unchanged. A + household link of None leaves that member without a household. + """ + person = pd.DataFrame( + { + "person_id": range(len(households)), + "household_id": list(households), + "tax_unit_id": [7] * len(households), + "person_weight": weights or [1.0] * len(households), + } + ) + tax_unit = pd.DataFrame({"tax_unit_id": [7], "tax_unit_weight": 1.0}) + for column, amount in values.items(): + tax_unit[column] = pd.Series( + [amount], dtype=object if isinstance(amount, Decimal) else None + ) + linked = sorted({h for h in households if h is not None}) + household = pd.DataFrame({"household_id": linked, "household_weight": 1.0}) + return { + "person": MicroDataFrame(person, weights="person_weight"), + "tax_unit": MicroDataFrame(tax_unit, weights="tax_unit_weight"), + "household": MicroDataFrame(household, weights="household_weight"), + } + + +def test_divide_keeps_large_values_finite(): + """Dividing before multiplying keeps the largest int64 and float64 values + in range: two members in one household pass on the whole amount.""" + big_int = _mapped( + _one_tax_unit([1, 1], {"value": np.int64(2**62)}), + "tax_unit", + "household", + "divide", + ["value"], + ) + assert big_int["value"].tolist() == pytest.approx([float(2**62)]) + big_float = _mapped( + _one_tax_unit([1, 1], {"value": 1e308}), + "tax_unit", + "household", + "divide", + ["value"], + ) + assert big_float["value"].tolist() == [1e308] + + +def test_divide_maps_columns_named_like_its_counts(): + """Source columns may share the names divide uses for its counts.""" + data = _one_tax_unit([1], {"__pair_count": 100.0, "__source_count": 200.0}) + mapped = _mapped( + data, "tax_unit", "household", "divide", ["__pair_count", "__source_count"] + ) + assert mapped[["__pair_count", "__source_count"]].values.tolist() == [ + [100.0, 200.0] + ] + + +def test_divide_keeps_decimal_amounts_when_a_member_has_no_target(): + """A Decimal $100.00 split between a linked and an unlinked member gives + the linked member's household Decimal $50.00.""" + data = _one_tax_unit([1, None], {"value": Decimal("100.00")}) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [Decimal("50.00")] + + +def test_divide_counts_members_not_their_weights(): + """A $100 unit with one member in each of two households, weighted 1 and + 3, gives each household $50.""" + data = _one_tax_unit([1, 2], {"value": 100.0}, weights=[1.0, 3.0]) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert dict(zip(mapped["household_id"], mapped["value"])) == {1: 50.0, 2: 50.0} + + +@settings(max_examples=50, deadline=None) +@given(entity_data(nested=False)) +def test_divide_with_categorical_links_matches_plain_links(case): + """Categorical person links give the same shares as plain ones.""" + person = pd.DataFrame(case.data["person"]).copy() + for column in person.columns: + if column.endswith("_id") and column != "person_id": + person[column] = person[column].astype("category") + categorical = { + **case.data, + "person": MicroDataFrame(person, weights="person_weight"), + } + for source, target in permutations(GROUPS, 2): + assert _mapped( + categorical, source, target, "divide" + ).to_numpy() == pytest.approx( + _mapped(case.data, source, target, "divide").to_numpy(), abs=ABS + ), (source, target) From 7aaa2619e5a666d2c8be2b1275811e656597fe52 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 29 Nov 2026 12:14:54 -0500 Subject: [PATCH 04/10] Pass whole group values through divide unchanged and skip null ids A target holding every member of a source now gets the source's value with no arithmetic, so Decimal amounts, subnormal floats and 1 ns timedeltas keep their exact value and the largest float stays finite. A split share multiplies by pair_count / source_count, a ratio below 1; object columns multiply by the pair count and divide once, except for floats, which take the ratio. Rows with a null source or target id belong to no group, so every counted row has integer counts. Co-Authored-By: Claude Opus 5.5 --- src/policyengine/core/dataset.py | 77 ++++++-- tests/test_entity_mapping_group_properties.py | 187 +++++++++++++++++- 2 files changed, 246 insertions(+), 18 deletions(-) diff --git a/src/policyengine/core/dataset.py b/src/policyengine/core/dataset.py index b00d2c98c..f7fc37bcd 100644 --- a/src/policyengine/core/dataset.py +++ b/src/policyengine/core/dataset.py @@ -95,6 +95,18 @@ class MyDataset(Dataset): data: Optional[BaseModel] = None +def _split_object_share(value, pair_count: int, source_count: int): + """Return pair_count / source_count of one value in an object column. + + Decimal, Fraction and integer values multiply by the pair count before + dividing, so they round at most once. A float multiplies by the ratio, + which stays below 1, so its share cannot overflow. + """ + if isinstance(value, (float, np.floating)): + return value * (pair_count / source_count) + return value * pair_count / source_count + + def map_to_entity( entity_data: dict[str, MicroDataFrame], source_entity: str, @@ -127,6 +139,17 @@ def map_to_entity( equally among the source's members, each share going to the target group that member is in) + Group → group 'divide' gives a target holding every member of a + source that source's value unchanged. A target holding some of + the members gets value * (members it holds / source members): a + float multiplier below 1 for numeric and timedelta columns, so no + share overflows, and an integer multiply then one division for + object columns such as Decimal. Integer and boolean columns come + out as float. A share smaller than its dtype can hold, such as + half of 1 ns, rounds. Members with no target link keep their + shares out of every target, and a source or member with a null id + belongs to no group. + Returns: MicroDataFrame: The mapped data at the target entity level @@ -354,17 +377,19 @@ def map_to_entity( elif how == "divide": # Split each source value equally among the source's members, # then give each target group the shares of the members it - # holds: value / source_count * pair_count for each (source, - # target) row of source_with_target. A source whose members - # all link to target groups passes on its whole value. A - # member with no target link keeps its share out of every - # target, and a source with no members adds nothing, as in - # group -> person divide followed by person -> group sum. - # Rows without a target carry no share, so they drop out here - # and every remaining row has integer counts. Dividing before - # multiplying keeps large values finite, and integer counts - # keep Decimal and other object values working. - linked = source_with_target[source_with_target[target_link_key].notna()] + # holds, as in group -> person divide followed by + # person -> group sum. Each (source, target) row of + # source_with_target holds pair_count of the source's + # source_count members. A member with no target link keeps + # its share out of every target, and a source with no members + # adds nothing. Rows with a null source or target id belong + # to no group, so they drop out here, and every remaining row + # has integer counts of at least 1. + has_ids = ( + source_with_target[source_link_key].notna() + & source_with_target[target_link_key].notna() + ) + linked = source_with_target[has_ids] pair_keys = [source_link_key, target_link_key] pair_counts = ( person_df.groupby(pair_keys, observed=True) @@ -392,9 +417,37 @@ def map_to_entity( counts["__pair_count"].to_numpy(), index=linked.index ) + # A target holding every member of a source gets its value + # unchanged, with no arithmetic to round or overflow. Other + # rows get value * pair_count / source_count. + split = pair_n != source_n shares = linked[[target_link_key]].copy() for col in agg_cols: - shares[col] = linked[col] / source_n * pair_n + values = linked[col] + if pd.api.types.is_object_dtype(values.dtype): + share = values.copy() + part = pd.Series( + [ + _split_object_share(value, pair, source) + for value, pair, source in zip( + values[split].tolist(), + pair_n[split].tolist(), + source_n[split].tolist(), + ) + ], + index=values.index[split], + dtype=object, + ) + else: + # The ratio stays below 1, so no share overflows. The + # output dtype is that of values times the ratio + # (float for integer and boolean columns), whether or + # not any row splits. + ratio = pair_n[split] / source_n[split] + share = values.astype((values.iloc[:0] * ratio.iloc[:0]).dtype) + part = values[split] * ratio + share.loc[part.index] = part + shares[col] = share aggregated = shares.groupby( target_link_key, as_index=False, observed=True diff --git a/tests/test_entity_mapping_group_properties.py b/tests/test_entity_mapping_group_properties.py index 2b9bcb8ca..5a170a410 100644 --- a/tests/test_entity_mapping_group_properties.py +++ b/tests/test_entity_mapping_group_properties.py @@ -13,6 +13,8 @@ without a country model under ``pytest --noconftest``. """ +import decimal +import math from collections import Counter, namedtuple from decimal import Decimal from itertools import permutations @@ -410,12 +412,13 @@ def test_divide_leaves_out_the_share_of_a_member_with_no_target_link(): assert mapped["value"].tolist() == [50.0] -def _one_tax_unit(households, values: dict, weights=None) -> dict: +def _one_tax_unit(households, values: dict, weights=None, as_object=False) -> dict: """Tables for tax unit 7, whose members link to ``households``. ``values`` maps a column name to the tax unit's amount, kept as given so - integer, Decimal and other dtypes reach map_to_entity unchanged. A - household link of None leaves that member without a household. + integer, Decimal and other dtypes reach map_to_entity unchanged; Decimal + amounts, and every amount when ``as_object`` is set, sit in object + columns. A household link of None leaves that member without a household. """ person = pd.DataFrame( { @@ -428,7 +431,8 @@ def _one_tax_unit(households, values: dict, weights=None) -> dict: tax_unit = pd.DataFrame({"tax_unit_id": [7], "tax_unit_weight": 1.0}) for column, amount in values.items(): tax_unit[column] = pd.Series( - [amount], dtype=object if isinstance(amount, Decimal) else None + [amount], + dtype=object if as_object or isinstance(amount, Decimal) else None, ) linked = sorted({h for h in households if h is not None}) household = pd.DataFrame({"household_id": linked, "household_weight": 1.0}) @@ -440,8 +444,11 @@ def _one_tax_unit(households, values: dict, weights=None) -> dict: def test_divide_keeps_large_values_finite(): - """Dividing before multiplying keeps the largest int64 and float64 values - in range: two members in one household pass on the whole amount.""" + """No share of a large int64 or float64 amount overflows. + + Members who share one household pass on the whole amount, and a split of + the largest float gives finite shares. + """ big_int = _mapped( _one_tax_unit([1, 1], {"value": np.int64(2**62)}), "tax_unit", @@ -458,6 +465,23 @@ def test_divide_keeps_large_values_finite(): ["value"], ) assert big_float["value"].tolist() == [1e308] + largest = np.finfo(np.float64).max + whole = _mapped( + _one_tax_unit([1, 1, 1], {"value": largest}), + "tax_unit", + "household", + "divide", + ["value"], + ) + assert whole["value"].tolist() == [largest] + split = _mapped( + _one_tax_unit([1, 1, 2], {"value": largest}), + "tax_unit", + "household", + "divide", + ["value"], + ) + assert split["value"].tolist() == pytest.approx([largest / 3 * 2, largest / 3]) def test_divide_maps_columns_named_like_its_counts(): @@ -487,6 +511,157 @@ def test_divide_counts_members_not_their_weights(): assert dict(zip(mapped["household_id"], mapped["value"])) == {1: 50.0, 2: 50.0} +def test_divide_passes_a_whole_value_through_unchanged(): + """A household holding every member of a tax unit gets its exact value. + + The value passes through with no arithmetic, so it does not round, even + when Decimal traps inexact results or the amount is the smallest float or + 1 ns. + """ + with decimal.localcontext() as context: + context.traps[decimal.Inexact] = True + mapped = _mapped( + _one_tax_unit([1, 1, 1], {"value": Decimal("100.00")}), + "tax_unit", + "household", + "divide", + ["value"], + ) + assert mapped["value"].tolist() == [Decimal("100.00")] + for households, amount in [ + ([1, 1], 5e-324), + ([1, 1], pd.Timedelta(1, "ns")), + ]: + mapped = _mapped( + _one_tax_unit(households, {"value": amount}), + "tax_unit", + "household", + "divide", + ["value"], + ) + assert mapped["value"].tolist() == [amount] + + +def test_divide_rounds_a_split_decimal_once(): + """Two of three members in household 1 give it Decimal 200.00 / 3. + + Multiplying before dividing rounds each Decimal share once, so the + shares add back to 100.00. + """ + mapped = _mapped( + _one_tax_unit([1, 1, 2], {"value": Decimal("100.00")}), + "tax_unit", + "household", + "divide", + ["value"], + ) + assert mapped["value"].tolist() == [ + Decimal("200.00") / 3, + Decimal("100.00") / 3, + ] + assert sum(mapped["value"]) == Decimal("100.00") + + +# pandas 2 warns when map_to_entity's closing fillna downcasts an object +# column of floats; pandas 3 keeps the column as object. +@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") +def test_divide_keeps_floats_in_object_columns_finite(): + """The largest float, held in an object column, splits into finite shares.""" + largest = np.finfo(np.float64).max + mapped = _mapped( + _one_tax_unit([1, 1, 2], {"value": largest}, as_object=True), + "tax_unit", + "household", + "divide", + ["value"], + ) + assert mapped["value"].tolist() == pytest.approx([largest / 3 * 2, largest / 3]) + + +def test_divide_gives_integer_columns_float_shares_either_way(): + """An integer column maps to float whether or not any unit splits.""" + whole = _mapped( + _one_tax_unit([1, 1], {"value": np.int64(10)}), + "tax_unit", + "household", + "divide", + ["value"], + ) + split = _mapped( + _one_tax_unit([1, 2], {"value": np.int64(10)}), + "tax_unit", + "household", + "divide", + ["value"], + ) + assert whole["value"].dtype == np.float64 + assert split["value"].dtype == np.float64 + assert whole["value"].tolist() == [10.0] + assert split["value"].tolist() == [5.0, 5.0] + + +def test_divide_gives_nothing_from_a_source_with_no_id(): + """Rows with a null tax unit id belong to no tax unit. + + Tax unit 7 has two members, one in household 1 and one with no + household. A tax unit row with a null id and a person with a null tax + unit link add nothing, so household 1 gets only tax unit 7's $50 share. + """ + person = pd.DataFrame( + { + "person_id": [0, 1, 2], + "tax_unit_id": [7, 7, None], + "household_id": [1, None, 1], + "person_weight": 1.0, + } + ) + household = pd.DataFrame({"household_id": [1], "household_weight": 1.0}) + for amounts, expected in [ + ([Decimal("100.00"), Decimal("80.00")], Decimal("50.00")), + ([100.0, 80.0], 50.0), + ]: + tax_unit = pd.DataFrame({"tax_unit_id": [7, None], "tax_unit_weight": 1.0}) + tax_unit["value"] = pd.Series( + amounts, dtype=object if isinstance(expected, Decimal) else None + ) + data = { + "person": MicroDataFrame(person, weights="person_weight"), + "tax_unit": MicroDataFrame(tax_unit, weights="tax_unit_weight"), + "household": MicroDataFrame(household, weights="household_weight"), + } + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [expected] + + +@settings(max_examples=200, deadline=None) +@given( + st.floats(allow_nan=False, allow_infinity=False), + st.lists(st.integers(1, 3), min_size=1, max_size=6), +) +def test_divide_splits_any_finite_float_into_finite_shares(amount, households): + """Any finite float splits into finite shares that add back to it. + + Tax unit 7's members link to households drawn from 1 to 3. A household + holding every member gets the amount exactly, from the largest floats to + the smallest. + """ + mapped = _mapped( + _one_tax_unit(households, {"value": amount}), + "tax_unit", + "household", + "divide", + ["value"], + ) + shares = mapped["value"].tolist() + assert all(math.isfinite(share) for share in shares) + if len(set(households)) == 1: + assert shares == [amount] + # Quarter each share so the total cannot overflow near the largest float. + assert math.fsum(share / 4 for share in shares) == pytest.approx( + amount / 4, rel=1e-12, abs=1e-320 + ) + + @settings(max_examples=50, deadline=None) @given(entity_data(nested=False)) def test_divide_with_categorical_links_matches_plain_links(case): From 1e4dc6e40313e91cc0be714c67388dcf415b8288 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Sun, 29 Nov 2026 12:22:21 -0500 Subject: [PATCH 05/10] Divide split shares by source over pair counts and keep timedeltas exact value / (source_count / pair_count) rounds once whenever that divisor is exact, as with 2 of 3 members (1.5), so 100 split three ways gives the correctly rounded 33.333333333333336, as before; the divisor is at least 1, so no share overflows. Timedelta columns divide by the integer source count and then multiply by the pair count, so a 2**62 ns split stays exact to the nanosecond. Co-Authored-By: Claude Opus 5.5 --- src/policyengine/core/dataset.py | 52 ++++++++++++------- tests/test_entity_mapping_group_properties.py | 20 +++++++ 2 files changed, 53 insertions(+), 19 deletions(-) diff --git a/src/policyengine/core/dataset.py b/src/policyengine/core/dataset.py index f7fc37bcd..daf8cd8e5 100644 --- a/src/policyengine/core/dataset.py +++ b/src/policyengine/core/dataset.py @@ -99,11 +99,12 @@ def _split_object_share(value, pair_count: int, source_count: int): """Return pair_count / source_count of one value in an object column. Decimal, Fraction and integer values multiply by the pair count before - dividing, so they round at most once. A float multiplies by the ratio, - which stays below 1, so its share cannot overflow. + dividing, so they round at most once. A float divides by + source_count / pair_count, which is at least 1, so its share cannot + overflow. """ if isinstance(value, (float, np.floating)): - return value * (pair_count / source_count) + return value / (source_count / pair_count) return value * pair_count / source_count @@ -141,14 +142,17 @@ def map_to_entity( Group → group 'divide' gives a target holding every member of a source that source's value unchanged. A target holding some of - the members gets value * (members it holds / source members): a - float multiplier below 1 for numeric and timedelta columns, so no - share overflows, and an integer multiply then one division for - object columns such as Decimal. Integer and boolean columns come - out as float. A share smaller than its dtype can hold, such as - half of 1 ns, rounds. Members with no target link keep their - shares out of every target, and a source or member with a null id - belongs to no group. + the members gets value / (source members / members it holds) in + numeric and float object columns; that divisor is at least 1, so + no share overflows. Timedelta columns divide by the source member + count and then multiply by the members the target holds. Other + object columns, such as Decimal, take value * members it holds / + source members, which rounds once. Integer and boolean columns + come out as float. A share smaller than its dtype can hold, such + as half of 1 ns, rounds, and a target's total can still overflow + when several sources add up past the dtype's range. Members with + no target link keep their shares out of every target, and a + source or member with a null id belongs to no group. Returns: MicroDataFrame: The mapped data at the target entity level @@ -419,7 +423,7 @@ def map_to_entity( # A target holding every member of a source gets its value # unchanged, with no arithmetic to round or overflow. Other - # rows get value * pair_count / source_count. + # rows get pair_count / source_count of the value. split = pair_n != source_n shares = linked[[target_link_key]].copy() for col in agg_cols: @@ -438,14 +442,24 @@ def map_to_entity( index=values.index[split], dtype=object, ) + elif pd.api.types.is_timedelta64_dtype(values.dtype): + # Timedeltas count whole nanoseconds. Dividing by the + # integer source count rounds each share to the + # nanosecond once, and multiplying by the smaller + # pair count keeps it within range. + share = values.copy() + part = values[split] / source_n[split] * pair_n[split] else: - # The ratio stays below 1, so no share overflows. The - # output dtype is that of values times the ratio - # (float for integer and boolean columns), whether or - # not any row splits. - ratio = pair_n[split] / source_n[split] - share = values.astype((values.iloc[:0] * ratio.iloc[:0]).dtype) - part = values[split] * ratio + # The divisor is at least 1, so no share overflows, + # and it is exact when the pair count divides the + # source count or is a power of 2. The output dtype is + # that of values over the divisor (float for integer + # and boolean columns), whether or not any row splits. + divisor = source_n[split] / pair_n[split] + share = values.astype( + (values.iloc[:0] / divisor.iloc[:0]).dtype + ) + part = values[split] / divisor share.loc[part.index] = part shares[col] = share diff --git a/tests/test_entity_mapping_group_properties.py b/tests/test_entity_mapping_group_properties.py index 5a170a410..892d34686 100644 --- a/tests/test_entity_mapping_group_properties.py +++ b/tests/test_entity_mapping_group_properties.py @@ -542,6 +542,26 @@ def test_divide_passes_a_whole_value_through_unchanged(): assert mapped["value"].tolist() == [amount] +def test_divide_splits_a_long_timedelta_to_the_nanosecond(): + """A 2**62 ns timedelta split 2:1 keeps each share to the nanosecond. + + Each share divides by the three members and then multiplies by the + members its household holds, so it never passes through a float. + """ + mapped = _mapped( + _one_tax_unit([1, 1, 2], {"value": pd.Timedelta(2**62, "ns")}), + "tax_unit", + "household", + "divide", + ["value"], + ) + third = 1_537_228_672_809_129_301 # 2**62 // 3 + assert mapped["value"].tolist() == [ + pd.Timedelta(2 * third, "ns"), + pd.Timedelta(third, "ns"), + ] + + def test_divide_rounds_a_split_decimal_once(): """Two of three members in household 1 give it Decimal 200.00 / 3. From 17d4beef5674bbb9d1002cb0efdfac75b3015158 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 19:08:31 -0500 Subject: [PATCH 06/10] Fix rounding and missing values in group-to-group divide --- changelog.d/768.fixed.md | 2 +- src/policyengine/core/dataset.py | 85 ++++++++++--------- tests/test_entity_mapping_group_properties.py | 49 +++++++++-- 3 files changed, 86 insertions(+), 50 deletions(-) diff --git a/changelog.d/768.fixed.md b/changelog.d/768.fixed.md index efc5feee2..c8acb48c1 100644 --- a/changelog.d/768.fixed.md +++ b/changelog.d/768.fixed.md @@ -1 +1 @@ -Split each source value among its members in group-to-group `map_to_entity(how="divide")`, so a group whose members all link to target groups passes on its whole value instead of part of it. +In group-to-group `map_to_entity(how="divide")`, give each target its share of a source value based on how many source members it holds. A target holding every member receives the whole source value, subject to output dtype precision. diff --git a/src/policyengine/core/dataset.py b/src/policyengine/core/dataset.py index daf8cd8e5..386b8aff2 100644 --- a/src/policyengine/core/dataset.py +++ b/src/policyengine/core/dataset.py @@ -1,3 +1,4 @@ +from decimal import MAX_EMAX, MIN_EMIN, Decimal, localcontext from typing import Optional from uuid import uuid4 @@ -95,16 +96,25 @@ class MyDataset(Dataset): data: Optional[BaseModel] = None -def _split_object_share(value, pair_count: int, source_count: int): - """Return pair_count / source_count of one value in an object column. - - Decimal, Fraction and integer values multiply by the pair count before - dividing, so they round at most once. A float divides by - source_count / pair_count, which is at least 1, so its share cannot - overflow. - """ +def _split_scalar_share(value, pair_count: int, source_count: int): + """Scale an object or timedelta value by the target's member fraction.""" if isinstance(value, (float, np.floating)): return value / (source_count / pair_count) + if isinstance(value, Decimal): + # Keep the intermediate product exact under a wider context. Apply + # the caller's precision, exponent limits and traps to the quotient. + precision = len(value.as_tuple().digits) + len(str(pair_count)) + with localcontext(prec=precision, Emax=MAX_EMAX, Emin=MIN_EMIN, clamp=0): + numerator = value * pair_count + return numerator / source_count + if isinstance(value, pd.Timedelta): + # Use Python integers to preserve the timedelta's resolution and + # truncate toward zero once, even when the product exceeds int64. + ticks = int(value.asm8.astype("int64")) + share = abs(ticks) * pair_count // source_count + return pd.Timedelta(-share if ticks < 0 else share, unit=value.unit) + if isinstance(value, np.integer) and value.dtype.kind in "iu": + value = int(value) return value * pair_count / source_count @@ -140,19 +150,15 @@ def map_to_entity( equally among the source's members, each share going to the target group that member is in) - Group → group 'divide' gives a target holding every member of a - source that source's value unchanged. A target holding some of - the members gets value / (source members / members it holds) in - numeric and float object columns; that divisor is at least 1, so - no share overflows. Timedelta columns divide by the source member - count and then multiply by the members the target holds. Other - object columns, such as Decimal, take value * members it holds / - source members, which rounds once. Integer and boolean columns - come out as float. A share smaller than its dtype can hold, such - as half of 1 ns, rounds, and a target's total can still overflow - when several sources add up past the dtype's range. Members with - no target link keep their shares out of every target, and a - source or member with a null id belongs to no group. + Group → group 'divide' passes through a whole source value when a + target holds all its members, subject to output dtype conversion. + Integer and boolean columns return floats. A target holding some + members gets their fraction of the source value. Decimal shares + round under the caller's context. Timedelta shares truncate toward + zero at the column's resolution. Rounding can affect the sum of + shares, and a target's total can overflow when adding several + sources. Members with no target link keep their shares out of + every target. Null source ids and links contribute nothing. Returns: MicroDataFrame: The mapped data at the target entity level @@ -381,9 +387,7 @@ def map_to_entity( elif how == "divide": # Split each source value equally among the source's members, # then give each target group the shares of the members it - # holds, as in group -> person divide followed by - # person -> group sum. Each (source, target) row of - # source_with_target holds pair_count of the source's + # holds. Each (source, target) row holds pair_count of the source's # source_count members. A member with no target link keeps # its share out of every target, and a source with no members # adds nothing. Rows with a null source or target id belong @@ -428,27 +432,23 @@ def map_to_entity( shares = linked[[target_link_key]].copy() for col in agg_cols: values = linked[col] - if pd.api.types.is_object_dtype(values.dtype): + if pd.api.types.is_object_dtype( + values.dtype + ) or pd.api.types.is_timedelta64_dtype(values.dtype): share = values.copy() + present = split & values.notna() part = pd.Series( [ - _split_object_share(value, pair, source) + _split_scalar_share(value, pair, source) for value, pair, source in zip( - values[split].tolist(), - pair_n[split].tolist(), - source_n[split].tolist(), + values[present].tolist(), + pair_n[present].tolist(), + source_n[present].tolist(), ) ], - index=values.index[split], - dtype=object, + index=values.index[present], + dtype=values.dtype, ) - elif pd.api.types.is_timedelta64_dtype(values.dtype): - # Timedeltas count whole nanoseconds. Dividing by the - # integer source count rounds each share to the - # nanosecond once, and multiplying by the smaller - # pair count keeps it within range. - share = values.copy() - part = values[split] / source_n[split] * pair_n[split] else: # The divisor is at least 1, so no share overflows, # and it is exact when the pair count divides the @@ -483,8 +483,13 @@ def map_to_entity( result.sort_values("index").drop("index", axis=1).reset_index(drop=True) ) - # Fill NaN with 0 - result[agg_cols] = result[agg_cols].fillna(0) + fill_values = { + col: pd.Timedelta(0) + if how == "divide" and pd.api.types.is_timedelta64_dtype(result[col]) + else 0 + for col in agg_cols + } + result[agg_cols] = result[agg_cols].fillna(fill_values) result_df = MicroDataFrame(result, weights=target_weight) if return_series: diff --git a/tests/test_entity_mapping_group_properties.py b/tests/test_entity_mapping_group_properties.py index 892d34686..857f10052 100644 --- a/tests/test_entity_mapping_group_properties.py +++ b/tests/test_entity_mapping_group_properties.py @@ -543,22 +543,29 @@ def test_divide_passes_a_whole_value_through_unchanged(): def test_divide_splits_a_long_timedelta_to_the_nanosecond(): - """A 2**62 ns timedelta split 2:1 keeps each share to the nanosecond. - - Each share divides by the three members and then multiplies by the - members its household holds, so it never passes through a float. - """ + """A large timedelta split 2:1 keeps each share to the nanosecond.""" + ticks = 2**62 + 1 mapped = _mapped( - _one_tax_unit([1, 1, 2], {"value": pd.Timedelta(2**62, "ns")}), + _one_tax_unit([1, 1, 2], {"value": pd.Timedelta(ticks, "ns")}), "tax_unit", "household", "divide", ["value"], ) - third = 1_537_228_672_809_129_301 # 2**62 // 3 assert mapped["value"].tolist() == [ - pd.Timedelta(2 * third, "ns"), - pd.Timedelta(third, "ns"), + pd.Timedelta(2 * ticks // 3, "ns"), + pd.Timedelta(ticks // 3, "ns"), + ] + + +def test_divide_rounds_a_timedelta_share_once_and_fills_empty_targets(): + data = _one_tax_unit([1, 1, 2], {"value": pd.Timedelta(-2, "ns")}) + data["household"].loc[2] = {"household_id": 3, "household_weight": 1.0} + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [ + pd.Timedelta(-1, "ns"), + pd.Timedelta(0), + pd.Timedelta(0), ] @@ -582,6 +589,30 @@ def test_divide_rounds_a_split_decimal_once(): assert sum(mapped["value"]) == Decimal("100.00") +@pytest.mark.parametrize( + "amount, shares", [("9.99", ["6.66", "3.33"]), ("900", ["600", "300"])] +) +def test_divide_rounds_only_the_final_decimal_share(amount, shares): + data = _one_tax_unit([1, 1, 2], {"value": Decimal(amount)}) + with decimal.localcontext(prec=3, Emax=2) as context: + context.traps[decimal.Inexact] = True + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [Decimal(share) for share in shares] + + +def test_divide_ignores_missing_object_values_in_split_groups(): + data = _one_tax_unit([1, 1, 2], {"value": None}, as_object=True) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [0, 0] + + +def test_divide_keeps_numpy_integers_in_object_columns_from_wrapping(): + amount = 2**62 + data = _one_tax_unit([1, 1, 2], {"value": np.int64(amount)}, as_object=True) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [2 * amount / 3, amount / 3] + + # pandas 2 warns when map_to_entity's closing fillna downcasts an object # column of floats; pandas 3 keeps the column as object. @pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") From 1f40fa209b1a58b715cc82c9cc68084f3cf252db Mon Sep 17 00:00:00 2001 From: Codex Date: Mon, 30 Nov 2026 21:42:46 -0500 Subject: [PATCH 07/10] Preserve timedelta units and Decimal precision in group shares --- src/policyengine/core/dataset.py | 99 ++++++++++++------- tests/test_entity_mapping_group_properties.py | 30 ++++++ 2 files changed, 95 insertions(+), 34 deletions(-) diff --git a/src/policyengine/core/dataset.py b/src/policyengine/core/dataset.py index 386b8aff2..e9215e09f 100644 --- a/src/policyengine/core/dataset.py +++ b/src/policyengine/core/dataset.py @@ -1,4 +1,4 @@ -from decimal import MAX_EMAX, MIN_EMIN, Decimal, localcontext +from decimal import MAX_EMAX, Decimal, localcontext from typing import Optional from uuid import uuid4 @@ -96,23 +96,51 @@ class MyDataset(Dataset): data: Optional[BaseModel] = None +def _split_decimal_share(value: Decimal, pair_count: int, source_count: int) -> Decimal: + if not value.is_finite(): + return value / source_count + + # Multiply only the coefficient so the intermediate cannot become subnormal. + parts = value.as_tuple() + precision = len(parts.digits) + len(str(pair_count)) + with localcontext(prec=precision, Emax=MAX_EMAX, clamp=0): + product = Decimal((0, parts.digits, 0)) * pair_count + + digits = product.as_tuple().digits + exponent = int(parts.exponent) + # Scale both operands down equally if the numerator's adjusted exponent + # would be too large to represent. Only the final division uses the + # caller's precision, exponent limits and traps. + shift = max(0, exponent + len(digits) - 1 - MAX_EMAX) + numerator = Decimal((parts.sign, digits, exponent - shift)) + denominator = Decimal(source_count) + if shift: + denominator = Decimal((0, denominator.as_tuple().digits, -shift)) + return numerator / denominator + + +def _split_timedelta_share( + value: np.timedelta64, pair_count: int, source_count: int +) -> np.timedelta64: + # Python integers keep the product in range. Rebuild in the same unit so + # coarse-resolution values can stay outside the nanosecond range. + ticks = int(value.astype(np.int64)) + share = abs(ticks) * pair_count // source_count + return np.array(-share if ticks < 0 else share, dtype=value.dtype)[()] + + def _split_scalar_share(value, pair_count: int, source_count: int): """Scale an object or timedelta value by the target's member fraction.""" if isinstance(value, (float, np.floating)): return value / (source_count / pair_count) if isinstance(value, Decimal): - # Keep the intermediate product exact under a wider context. Apply - # the caller's precision, exponent limits and traps to the quotient. - precision = len(value.as_tuple().digits) + len(str(pair_count)) - with localcontext(prec=precision, Emax=MAX_EMAX, Emin=MIN_EMIN, clamp=0): - numerator = value * pair_count - return numerator / source_count + return _split_decimal_share(value, pair_count, source_count) if isinstance(value, pd.Timedelta): - # Use Python integers to preserve the timedelta's resolution and - # truncate toward zero once, even when the product exceeds int64. - ticks = int(value.asm8.astype("int64")) - share = abs(ticks) * pair_count // source_count - return pd.Timedelta(-share if ticks < 0 else share, unit=value.unit) + return pd.Timedelta( + _split_timedelta_share(value.asm8, pair_count, source_count) + ) + if isinstance(value, np.timedelta64): + return _split_timedelta_share(value, pair_count, source_count) if isinstance(value, np.integer) and value.dtype.kind in "iu": value = int(value) return value * pair_count / source_count @@ -435,20 +463,17 @@ def map_to_entity( if pd.api.types.is_object_dtype( values.dtype ) or pd.api.types.is_timedelta64_dtype(values.dtype): - share = values.copy() - present = split & values.notna() - part = pd.Series( - [ - _split_scalar_share(value, pair, source) - for value, pair, source in zip( - values[present].tolist(), - pair_n[present].tolist(), - source_n[present].tolist(), - ) - ], - index=values.index[present], - dtype=values.dtype, - ) + present = (split & values.notna()).to_numpy() + array = values.to_numpy(copy=True) + array[present] = [ + _split_scalar_share(value, pair, source) + for value, pair, source in zip( + array[present], + pair_n[present].tolist(), + source_n[present].tolist(), + ) + ] + share = pd.Series(array, index=values.index, dtype=values.dtype) else: # The divisor is at least 1, so no share overflows, # and it is exact when the pair count divides the @@ -459,8 +484,7 @@ def map_to_entity( share = values.astype( (values.iloc[:0] / divisor.iloc[:0]).dtype ) - part = values[split] / divisor - share.loc[part.index] = part + share.loc[split] = values[split] / divisor shares[col] = share aggregated = shares.groupby( @@ -483,12 +507,19 @@ def map_to_entity( result.sort_values("index").drop("index", axis=1).reset_index(drop=True) ) - fill_values = { - col: pd.Timedelta(0) - if how == "divide" and pd.api.types.is_timedelta64_dtype(result[col]) - else 0 - for col in agg_cols - } + fill_values: dict[str, int | pd.Timedelta] = dict.fromkeys(agg_cols, 0) + if how == "divide": + for col in agg_cols: + column = result[col] + if pd.api.types.is_timedelta64_dtype(column.dtype): + fill_values[col] = pd.Timedelta(0) + elif pd.api.types.is_object_dtype(column.dtype) and any( + isinstance(value, np.timedelta64) for value in column + ): + # Pandas 2 can discard a NumPy timedelta's unit + # multiplier when fillna infers a timedelta dtype. + result[col] = column.where(column.notna(), 0) + del fill_values[col] result[agg_cols] = result[agg_cols].fillna(fill_values) result_df = MicroDataFrame(result, weights=target_weight) diff --git a/tests/test_entity_mapping_group_properties.py b/tests/test_entity_mapping_group_properties.py index 857f10052..5b52d54af 100644 --- a/tests/test_entity_mapping_group_properties.py +++ b/tests/test_entity_mapping_group_properties.py @@ -558,6 +558,25 @@ def test_divide_splits_a_long_timedelta_to_the_nanosecond(): ] +def test_divide_preserves_timedelta_seconds_outside_nanosecond_range(): + data = _one_tax_unit([1, 1, 2], {"value": 0}) + data["tax_unit"]["value"] = np.array([15_000_000_000], dtype="timedelta64[s]") + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + result = mapped["value"].to_numpy() + assert result.dtype == np.dtype("timedelta64[s]") + assert result.astype(np.int64).tolist() == [10_000_000_000, 5_000_000_000] + + +@pytest.mark.parametrize("unit, ticks", [("ns", 2**62 + 1), ("2s", 9)]) +def test_divide_preserves_numpy_timedeltas_in_object_columns(unit, ticks): + amount = np.timedelta64(ticks, unit) + data = _one_tax_unit([1, 1, 2], {"value": amount}, as_object=True) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + shares = mapped["value"].tolist() + assert [share.dtype for share in shares] == [amount.dtype] * 2 + assert [share.astype(np.int64) for share in shares] == [2 * ticks // 3, ticks // 3] + + def test_divide_rounds_a_timedelta_share_once_and_fills_empty_targets(): data = _one_tax_unit([1, 1, 2], {"value": pd.Timedelta(-2, "ns")}) data["household"].loc[2] = {"household_id": 3, "household_weight": 1.0} @@ -600,6 +619,17 @@ def test_divide_rounds_only_the_final_decimal_share(amount, shares): assert mapped["value"].tolist() == [Decimal(share) for share in shares] +@pytest.mark.parametrize("exponent", [decimal.MIN_EMIN - 2, decimal.MAX_EMAX]) +def test_divide_keeps_decimal_shares_exact_at_exponent_limits(exponent): + data = _one_tax_unit([1, 1, 2], {"value": Decimal((0, (6,), exponent))}) + with decimal.localcontext(prec=10, Emax=decimal.MAX_EMAX, Emin=decimal.MIN_EMIN): + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [ + Decimal((0, (4,), exponent)), + Decimal((0, (2,), exponent)), + ] + + def test_divide_ignores_missing_object_values_in_split_groups(): data = _one_tax_unit([1, 1, 2], {"value": None}, as_object=True) mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) From 23272c5c2fa1dbea10817e6329872cbb8498299a Mon Sep 17 00:00:00 2001 From: Codex Date: Tue, 1 Dec 2026 07:03:32 -0500 Subject: [PATCH 08/10] Preserve narrow float and Python timedelta group shares Compute NumPy float shares in a wider type and round Python timedelta shares in integer microseconds. Check categorical links with numeric column comparisons and document the return types, rounding and missing values. Co-Authored-By: GPT-6.2 Sol Co-Authored-By: Claude Opus 5.5 --- .claude/policyengine-guide.md | 2 +- changelog.d/768.fixed.md | 2 +- src/policyengine/core/dataset.py | 67 +++++++----- tests/test_entity_mapping_group_properties.py | 103 ++++++++++++++++-- 4 files changed, 136 insertions(+), 38 deletions(-) diff --git a/.claude/policyengine-guide.md b/.claude/policyengine-guide.md index 7ea13456b..de906dd46 100644 --- a/.claude/policyengine-guide.md +++ b/.claude/policyengine-guide.md @@ -466,7 +466,7 @@ gov.usda.snap.normal_allotment.max[1] # 1 person - `how='sum'`: Aggregate by summing (person → group default) - `how='first'`: Take first value in group - `how='project'`: Broadcast group value to members (group → person default) -- `how='divide'`: Split equally among members; between groups, each member's share goes to the target group that member is in +- `how='divide'` splits by member count. Between groups, each linked source and target pair gets its share before rounding and target aggregation. ## Response patterns diff --git a/changelog.d/768.fixed.md b/changelog.d/768.fixed.md index c8acb48c1..d875cc70a 100644 --- a/changelog.d/768.fixed.md +++ b/changelog.d/768.fixed.md @@ -1 +1 @@ -In group-to-group `map_to_entity(how="divide")`, give each target its share of a source value based on how many source members it holds. A target holding every member receives the whole source value, subject to output dtype precision. +Group-to-group `map_to_entity(how="divide")` allocates each source value by member count. A target holding every member receives the whole contribution before output dtype conversion and aggregation. Split shares retain native pandas and NumPy timedelta units, avoid intermediate overflow for Python timedeltas and preserve representable narrow NumPy float shares in object columns. The split skips missing object values. Rounding and underflow can affect totals, and target aggregation can overflow. diff --git a/src/policyengine/core/dataset.py b/src/policyengine/core/dataset.py index e9215e09f..0e5189fc6 100644 --- a/src/policyengine/core/dataset.py +++ b/src/policyengine/core/dataset.py @@ -1,10 +1,12 @@ +from datetime import timedelta from decimal import MAX_EMAX, Decimal, localcontext +from fractions import Fraction from typing import Optional from uuid import uuid4 import numpy as np import pandas as pd -from microdf import MicroDataFrame +from microdf import MicroDataFrame, MicroSeries from pydantic import BaseModel, ConfigDict, Field from .tax_benefit_model import TaxBenefitModel @@ -38,19 +40,20 @@ def map_to_entity( columns: list[str] = None, values: list = None, how: str = "sum", - ) -> MicroDataFrame: + ) -> MicroDataFrame | MicroSeries: """Map data from source entity to target entity using join keys. Args: source_entity (str): The source entity name. target_entity (str): The target entity name. columns (list[str], optional): List of column names to map. If None, maps all columns. - values (list, optional): List of values to use instead of column data. + values (list, optional): Values to map in source-row order. how (str): Aggregation method (default 'sum'). See the module-level map_to_entity for the methods each direction accepts. Returns: - MicroDataFrame: The mapped data at the target entity level. + A weighted MicroSeries when passing values, or a MicroDataFrame + when mapping columns. Raises: ValueError: If source or target entity is invalid. @@ -131,8 +134,13 @@ def _split_timedelta_share( def _split_scalar_share(value, pair_count: int, source_count: int): """Scale an object or timedelta value by the target's member fraction.""" - if isinstance(value, (float, np.floating)): - return value / (source_count / pair_count) + if isinstance(value, np.floating): + # Widen narrow NumPy floats so the divisor stays in range. + wide_float = np.result_type(value.dtype, np.float64).type + divisor = wide_float(source_count) / wide_float(pair_count) + return type(value)(wide_float(value) / divisor) + if isinstance(value, float): + return type(value)(value / (source_count / pair_count)) if isinstance(value, Decimal): return _split_decimal_share(value, pair_count, source_count) if isinstance(value, pd.Timedelta): @@ -141,6 +149,11 @@ def _split_scalar_share(value, pair_count: int, source_count: int): ) if isinstance(value, np.timedelta64): return _split_timedelta_share(value, pair_count, source_count) + if isinstance(value, timedelta): + # Scale in integer microseconds and round the exact share to even at ties. + microseconds = value // timedelta(microseconds=1) + share = round(Fraction(microseconds * pair_count, source_count)) + return timedelta(microseconds=share) if isinstance(value, np.integer) and value.dtype.kind in "iu": value = int(value) return value * pair_count / source_count @@ -154,14 +167,14 @@ def map_to_entity( columns: Optional[list[str]] = None, values: Optional[np.ndarray] = None, how: str = "sum", -) -> MicroDataFrame: +) -> MicroDataFrame | MicroSeries: """Map data from source entity to target entity using join keys. This is a generic entity mapping utility that handles: - Same entity mapping (returns as is) - Person to group entity mapping (aggregates values) - Group to person entity mapping (expands values) - - Group to group entity mapping (aggregates through person entity) + - Group to group entity mapping (links groups through their members) Args: entity_data: Dictionary mapping entity names to their MicroDataFrame data @@ -169,7 +182,7 @@ def map_to_entity( target_entity: The target entity name person_entity: The name of the person entity (default "person") columns: List of column names to map. If None, maps all columns - values: List of values to use instead of column data. If provided, creates a single unnamed column + values: Values to map in source-row order how: Aggregation method (default 'sum') - For person → group: 'sum' (aggregate), 'first' (take first value) - For group → person: 'project' (broadcast; the default 'sum' maps to @@ -181,15 +194,22 @@ def map_to_entity( Group → group 'divide' passes through a whole source value when a target holds all its members, subject to output dtype conversion. Integer and boolean columns return floats. A target holding some - members gets their fraction of the source value. Decimal shares - round under the caller's context. Timedelta shares truncate toward - zero at the column's resolution. Rounding can affect the sum of - shares, and a target's total can overflow when adding several - sources. Members with no target link keep their shares out of - every target. Null source ids and links contribute nothing. + members gets their fraction of the source value. Split Decimal + shares round under the caller's context. Split pandas and NumPy + timedelta shares truncate toward zero in the column's unit or, + for object columns, in the scalar's unit. Python timedelta + shares round to the nearest microsecond, with ties to even. + + With the same valid links, the direct and person-level routes + agree in exact arithmetic. Rounding per person can change the + result. Floating-point shares can round or underflow, and target + totals can round or overflow. Members with no target link keep + their shares out of every target. Null source IDs and links + contribute nothing. Returns: - MicroDataFrame: The mapped data at the target entity level + A weighted MicroSeries when passing values, or a MicroDataFrame + when mapping columns. Raises: ValueError: If source or target entity is invalid or unsupported aggregation method @@ -208,7 +228,7 @@ def map_to_entity( # Get source data (convert to plain DataFrame to avoid weighted operations during mapping) source_df = pd.DataFrame(entity_data[source_entity]) - # Track if we should return a MicroSeries (values is a numpy array, not a list) + # Return a MicroSeries when the caller supplies values. return_series = values is not None # Handle values parameter - create a temporary column with the provided values @@ -453,9 +473,8 @@ def map_to_entity( counts["__pair_count"].to_numpy(), index=linked.index ) - # A target holding every member of a source gets its value - # unchanged, with no arithmetic to round or overflow. Other - # rows get pair_count / source_count of the value. + # Copy whole shares before any output dtype conversion. + # Compute each split share once per source and target pair. split = pair_n != source_n shares = linked[[target_link_key]].copy() for col in agg_cols: @@ -475,11 +494,9 @@ def map_to_entity( ] share = pd.Series(array, index=values.index, dtype=values.dtype) else: - # The divisor is at least 1, so no share overflows, - # and it is exact when the pair count divides the - # source count or is a power of 2. The output dtype is - # that of values over the divisor (float for integer - # and boolean columns), whether or not any row splits. + # The divisor is at least 1. Floating-point shares can + # round or underflow. Derive the division dtype even + # for whole shares so integers and booleans yield floats. divisor = source_n[split] / pair_n[split] share = values.astype( (values.iloc[:0] / divisor.iloc[:0]).dtype diff --git a/tests/test_entity_mapping_group_properties.py b/tests/test_entity_mapping_group_properties.py index 5b52d54af..38458ce6a 100644 --- a/tests/test_entity_mapping_group_properties.py +++ b/tests/test_entity_mapping_group_properties.py @@ -16,6 +16,7 @@ import decimal import math from collections import Counter, namedtuple +from datetime import timedelta from decimal import Decimal from itertools import permutations @@ -184,7 +185,7 @@ def _expected_divide(case: Case, column, source, target) -> dict: @settings(max_examples=200, deadline=None) @given(entity_data(nested=False)) def test_divide_keeps_each_total(case): - """A source's shares add up to its amount, so column totals match. + """Column totals agree within tolerance when every member has a target link. A group with no members has nobody to pass its amount to, so it adds nothing. @@ -201,7 +202,7 @@ def test_divide_keeps_each_total(case): @settings(max_examples=200, deadline=None) @given(entity_data(nested=False)) def test_divide_keeps_each_weighted_total(case): - """The result carries the target weights, so weighted totals match too. + """Weighted totals agree within tolerance for these shared weights. People and groups in a household share its weight, so each share keeps its source's weight. @@ -258,7 +259,11 @@ def test_divide_counts_members_whatever_their_weights(case, rng): @settings(max_examples=200, deadline=None) @given(entity_data(nested=False)) def test_divide_matches_the_route_through_persons(case): - """Group-to-group divide equals group->person divide, then person->group sum.""" + """With the same valid links, both routes agree in exact arithmetic. + + Rounding per person can change the result. These floats agree within + the test's tolerance. + """ for source, target in permutations(GROUPS, 2): per_person = _mapped(case.data, source, "person", "divide", ["value"]) through_persons = pd.Series( @@ -577,6 +582,61 @@ def test_divide_preserves_numpy_timedeltas_in_object_columns(unit, ticks): assert [share.astype(np.int64) for share in shares] == [2 * ticks // 3, ticks // 3] +def test_divide_fills_an_unmatched_target_in_a_numpy_timedelta_object_column(): + amount = np.timedelta64(9, "2s") + data = _one_tax_unit([1, 1, 2], {"value": amount}, as_object=True) + data["household"].loc[2] = {"household_id": 3, "household_weight": 1.0} + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + first, second, unmatched = mapped["value"].tolist() + assert mapped["household_id"].tolist() == [1, 2, 3] + assert mapped["value"].dtype == object + assert isinstance(first, np.timedelta64) and first.dtype == amount.dtype + assert isinstance(second, np.timedelta64) and second.dtype == amount.dtype + assert [first.astype(np.int64), second.astype(np.int64)] == [6, 3] + assert type(unmatched) is int and unmatched == 0 + + +@pytest.mark.parametrize( + "amount, households, shares", + [ + ( + timedelta(days=600_000_000), + [1, 1, 2], + [timedelta(days=400_000_000), timedelta(days=200_000_000)], + ), + ( + timedelta(microseconds=-1), + [1, 1, 2], + [timedelta(microseconds=-1), timedelta()], + ), + (timedelta(microseconds=1), [1, 2], [timedelta()] * 2), + (timedelta(microseconds=3), [1, 2], [timedelta(microseconds=2)] * 2), + (timedelta(microseconds=-3), [1, 2], [timedelta(microseconds=-2)] * 2), + ], + ids=["large", "negative", "half-to-zero", "half-to-even", "negative-half-to-even"], +) +def test_divide_rounds_python_timedelta_shares_to_even(amount, households, shares): + data = _one_tax_unit(households, {"value": amount}, as_object=True) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == shares + + +def test_divide_rounds_timedeltas_per_target_pair(): + data = _one_tax_unit([1, 1, 2], {"value": pd.Timedelta(2, "ns")}) + direct = _mapped(data, "tax_unit", "household", "divide", ["value"]) + per_person = _mapped(data, "tax_unit", "person", "divide", ["value"]) + assert per_person["value"].tolist() == [pd.Timedelta(0)] * 3 + through_people = _mapped( + {**data, "person": MicroDataFrame(per_person, weights="person_weight")}, + "person", + "household", + "sum", + ["value"], + ) + assert direct["value"].tolist() == [pd.Timedelta(1, "ns"), pd.Timedelta(0)] + assert through_people["value"].tolist() == [pd.Timedelta(0)] * 2 + + def test_divide_rounds_a_timedelta_share_once_and_fills_empty_targets(): data = _one_tax_unit([1, 1, 2], {"value": pd.Timedelta(-2, "ns")}) data["household"].loc[2] = {"household_id": 3, "household_weight": 1.0} @@ -591,8 +651,8 @@ def test_divide_rounds_a_timedelta_share_once_and_fills_empty_targets(): def test_divide_rounds_a_split_decimal_once(): """Two of three members in household 1 give it Decimal 200.00 / 3. - Multiplying before dividing rounds each Decimal share once, so the - shares add back to 100.00. + The quotient rounds in the active context. These particular shares + add back to 100.00. """ mapped = _mapped( _one_tax_unit([1, 1, 2], {"value": Decimal("100.00")}), @@ -659,6 +719,14 @@ def test_divide_keeps_floats_in_object_columns_finite(): assert mapped["value"].tolist() == pytest.approx([largest / 3 * 2, largest / 3]) +def test_divide_preserves_a_representable_float16_share_in_an_object_column(): + data = _one_tax_unit([1] + [2] * 69_999, {"value": np.float16(1)}, as_object=True) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + shares = mapped["value"].tolist() + assert all(isinstance(share, np.float16) for share in shares) + assert shares == [np.float16(1 / 70_000), np.float16(69_999 / 70_000)] + + def test_divide_gives_integer_columns_float_shares_either_way(): """An integer column maps to float whether or not any unit splits.""" whole = _mapped( @@ -720,7 +788,9 @@ def test_divide_gives_nothing_from_a_source_with_no_id(): st.lists(st.integers(1, 3), min_size=1, max_size=6), ) def test_divide_splits_any_finite_float_into_finite_shares(amount, households): - """Any finite float splits into finite shares that add back to it. + """Finite float64 inputs produce finite pair shares. + + Rounding and underflow can change their sum. Tax unit 7's members link to households drawn from 1 to 3. A household holding every member gets the amount exactly, from the largest floats to @@ -743,6 +813,12 @@ def test_divide_splits_any_finite_float_into_finite_shares(amount, households): ) +def test_divide_can_underflow_when_splitting_the_smallest_float64(): + data = _one_tax_unit([1, 2], {"value": math.ulp(0.0)}) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [0.0, 0.0] + + @settings(max_examples=50, deadline=None) @given(entity_data(nested=False)) def test_divide_with_categorical_links_matches_plain_links(case): @@ -756,8 +832,13 @@ def test_divide_with_categorical_links_matches_plain_links(case): "person": MicroDataFrame(person, weights="person_weight"), } for source, target in permutations(GROUPS, 2): - assert _mapped( - categorical, source, target, "divide" - ).to_numpy() == pytest.approx( - _mapped(case.data, source, target, "divide").to_numpy(), abs=ABS - ), (source, target) + categorical_result = _mapped(categorical, source, target, "divide") + plain_result = _mapped(case.data, source, target, "divide") + target_id = f"{target}_id" + assert ( + categorical_result[target_id].tolist() == plain_result[target_id].tolist() + ) + for column in (f"{target}_weight", *COLUMNS): + assert categorical_result[column].to_numpy() == pytest.approx( + plain_result[column].to_numpy(), abs=ABS + ), (source, target, column) From d0cbdabf14ab8f5303b2ca862e591d32f8902f57 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 16:02:27 -0500 Subject: [PATCH 09/10] Keep float subclasses and narrow-float midpoints exact in group shares Round 3 found that a float Enum subclass raised when its share was rebuilt, and that a float16 share at a midpoint rounded to the wrong tick. Python float subclasses now divide directly, and finite float16 and float32 shares round once from the exact ratio, ties to even. New tests cover both cases, timedelta halves above 2**53, longdouble halves and the float16 dtype after pandas inference. Co-Authored-By: Claude Opus 5.5 --- changelog.d/768.fixed.md | 2 +- src/policyengine/core/dataset.py | 25 +++++++- tests/test_entity_mapping_group_properties.py | 63 +++++++++++++++++-- 3 files changed, 82 insertions(+), 8 deletions(-) diff --git a/changelog.d/768.fixed.md b/changelog.d/768.fixed.md index d875cc70a..cd82476f5 100644 --- a/changelog.d/768.fixed.md +++ b/changelog.d/768.fixed.md @@ -1 +1 @@ -Group-to-group `map_to_entity(how="divide")` allocates each source value by member count. A target holding every member receives the whole contribution before output dtype conversion and aggregation. Split shares retain native pandas and NumPy timedelta units, avoid intermediate overflow for Python timedeltas and preserve representable narrow NumPy float shares in object columns. The split skips missing object values. Rounding and underflow can affect totals, and target aggregation can overflow. +Group-to-group `map_to_entity(how="divide")` allocates each source value by member count. A target holding every member receives the whole contribution before output dtype conversion and aggregation. Pair shares retain native pandas and NumPy timedelta units and avoid intermediate overflow for Python timedeltas. Finite narrow NumPy floats in object columns round to the nearest representable pair share, with ties to even. The split skips missing object values. Rounding and underflow can affect totals, and target aggregation can overflow. diff --git a/src/policyengine/core/dataset.py b/src/policyengine/core/dataset.py index 0e5189fc6..0b56e5d92 100644 --- a/src/policyengine/core/dataset.py +++ b/src/policyengine/core/dataset.py @@ -1,6 +1,7 @@ from datetime import timedelta from decimal import MAX_EMAX, Decimal, localcontext from fractions import Fraction +from math import copysign, ldexp from typing import Optional from uuid import uuid4 @@ -132,15 +133,33 @@ def _split_timedelta_share( return np.array(-share if ticks < 0 else share, dtype=value.dtype)[()] +def _split_narrow_float_share( + value: np.floating, pair_count: int, source_count: int +) -> np.floating: + # Express the value in units of its dtype's smallest subnormal. + info = np.finfo(value.dtype) + tick_exponent = int(info.minexp - info.nmant) + ticks = int(ldexp(abs(float(value)), -tick_exponent)) + numerator = ticks * pair_count + + # The exact share's magnitude determines how far apart representable + # values are. Round once to that spacing, with ties to even. + significand_bits = int(info.nmant) + 1 + shift = max(0, (numerator // source_count).bit_length() - significand_bits) + units = round(Fraction(numerator, source_count << shift)) + return type(value)(copysign(ldexp(units, tick_exponent + shift), value)) + + def _split_scalar_share(value, pair_count: int, source_count: int): """Scale an object or timedelta value by the target's member fraction.""" if isinstance(value, np.floating): - # Widen narrow NumPy floats so the divisor stays in range. + if value.dtype.itemsize < np.dtype(np.float64).itemsize and np.isfinite(value): + return _split_narrow_float_share(value, pair_count, source_count) wide_float = np.result_type(value.dtype, np.float64).type divisor = wide_float(source_count) / wide_float(pair_count) return type(value)(wide_float(value) / divisor) if isinstance(value, float): - return type(value)(value / (source_count / pair_count)) + return value / (source_count / pair_count) if isinstance(value, Decimal): return _split_decimal_share(value, pair_count, source_count) if isinstance(value, pd.Timedelta): @@ -199,6 +218,8 @@ def map_to_entity( timedelta shares truncate toward zero in the column's unit or, for object columns, in the scalar's unit. Python timedelta shares round to the nearest microsecond, with ties to even. + Finite narrow NumPy floats in object columns round each pair share + to the nearest value in their scalar dtype, with ties to even. With the same valid links, the direct and person-level routes agree in exact arithmetic. Rounding per person can change the diff --git a/tests/test_entity_mapping_group_properties.py b/tests/test_entity_mapping_group_properties.py index 38458ce6a..b9ba71d58 100644 --- a/tests/test_entity_mapping_group_properties.py +++ b/tests/test_entity_mapping_group_properties.py @@ -18,6 +18,7 @@ from collections import Counter, namedtuple from datetime import timedelta from decimal import Decimal +from enum import Enum from itertools import permutations import numpy as np @@ -28,6 +29,7 @@ from microdf import MicroDataFrame, MicroSeries from policyengine.core import map_to_entity +from policyengine.core.dataset import _split_scalar_share GROUPS = ("tax_unit", "spm_unit", "household") COLUMNS = ("value", "other") @@ -604,6 +606,11 @@ def test_divide_fills_an_unmatched_target_in_a_numpy_timedelta_object_column(): [1, 1, 2], [timedelta(days=400_000_000), timedelta(days=200_000_000)], ), + ( + timedelta(microseconds=2**54 + 2), + [1, 2], + [timedelta(microseconds=2**53 + 1)] * 2, + ), ( timedelta(microseconds=-1), [1, 1, 2], @@ -613,7 +620,14 @@ def test_divide_fills_an_unmatched_target_in_a_numpy_timedelta_object_column(): (timedelta(microseconds=3), [1, 2], [timedelta(microseconds=2)] * 2), (timedelta(microseconds=-3), [1, 2], [timedelta(microseconds=-2)] * 2), ], - ids=["large", "negative", "half-to-zero", "half-to-even", "negative-half-to-even"], + ids=[ + "large", + "above-float-precision", + "negative", + "half-to-zero", + "half-to-even", + "negative-half-to-even", + ], ) def test_divide_rounds_python_timedelta_shares_to_even(amount, households, shares): data = _one_tax_unit(households, {"value": amount}, as_object=True) @@ -719,12 +733,51 @@ def test_divide_keeps_floats_in_object_columns_finite(): assert mapped["value"].tolist() == pytest.approx([largest / 3 * 2, largest / 3]) +@pytest.mark.skipif( + np.finfo(np.longdouble).maxexp <= np.finfo(np.float64).maxexp, + reason="np.longdouble has no wider exponent range on this platform", +) +def test_divide_keeps_longdouble_pair_shares_finite(): + amount = np.longdouble("1e400") + share = _split_scalar_share(amount, pair_count=1, source_count=2) + assert isinstance(share, np.longdouble) + assert np.isfinite(share) + assert share == amount / np.longdouble(2) + + +@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") def test_divide_preserves_a_representable_float16_share_in_an_object_column(): - data = _one_tax_unit([1] + [2] * 69_999, {"value": np.float16(1)}, as_object=True) + amount = np.float16(1) + pair_counts = (1, 69_999) + expected = [np.float16(count / 70_000) for count in pair_counts] + pair_shares = [_split_scalar_share(amount, count, 70_000) for count in pair_counts] + assert all(isinstance(share, np.float16) for share in pair_shares) + assert pair_shares == expected + + data = _one_tax_unit([1] + [2] * 69_999, {"value": amount}, as_object=True) mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) - shares = mapped["value"].tolist() - assert all(isinstance(share, np.float16) for share in shares) - assert shares == [np.float16(1 / 70_000), np.float16(69_999 / 70_000)] + assert [float(share) for share in mapped["value"]] == [float(s) for s in expected] + + +@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") +def test_divide_rounds_a_float16_midpoint_to_even(): + tick = 2**-24 + data = _one_tax_unit( + [1] * 13 + [None] * 17, {"value": np.float16(15 * tick)}, as_object=True + ) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + # The linked share is 15 * 13 / 30 = 6.5 ticks. + assert [float(share) for share in mapped["value"]] == [6 * tick] + + +@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") +def test_divide_accepts_float_enum_members_in_object_columns(): + class Rate(float, Enum): + FULL = 1.0 + + data = _one_tax_unit([1, 2], {"value": Rate.FULL}, as_object=True) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [0.5, 0.5] def test_divide_gives_integer_columns_float_shares_either_way(): From f60241e704ceafc5bb1e5fc8170b33216897bd13 Mon Sep 17 00:00:00 2001 From: Max Ghenis Date: Wed, 2 Dec 2026 22:57:22 -0500 Subject: [PATCH 10/10] Build NumPy float shares from the base scalar type; divide complex first - Cast split shares through value.dtype.type, so a NumPy float subclass with its own constructor splits into plain base-type shares instead of calling the subclass constructor. - Divide Python and NumPy complex shares by the source-to-pair member ratio instead of multiplying first, so a finite complex input never overflows mid-split. - Add regressions for NumPy float subclasses, complex object columns, the float32 midpoint, unsigned integer wraparound and timedelta seconds zero fill, and scope the changelog's narrow-float rounding to object columns. Co-Authored-By: Claude Opus 5.5 --- changelog.d/768.fixed.md | 2 +- src/policyengine/core/dataset.py | 20 ++++-- tests/test_entity_mapping_group_properties.py | 61 +++++++++++++++---- 3 files changed, 64 insertions(+), 19 deletions(-) diff --git a/changelog.d/768.fixed.md b/changelog.d/768.fixed.md index cd82476f5..5dc8ca479 100644 --- a/changelog.d/768.fixed.md +++ b/changelog.d/768.fixed.md @@ -1 +1 @@ -Group-to-group `map_to_entity(how="divide")` allocates each source value by member count. A target holding every member receives the whole contribution before output dtype conversion and aggregation. Pair shares retain native pandas and NumPy timedelta units and avoid intermediate overflow for Python timedeltas. Finite narrow NumPy floats in object columns round to the nearest representable pair share, with ties to even. The split skips missing object values. Rounding and underflow can affect totals, and target aggregation can overflow. +Group-to-group `map_to_entity(how="divide")` allocates each source value by member count. A target holding every member receives the whole contribution before output dtype conversion and aggregation. Pair shares retain native pandas and NumPy timedelta units and avoid intermediate overflow for Python timedeltas and complex scalars. Split NumPy floats in object columns use the base scalar type of the input dtype, and finite narrow ones round to the nearest representable pair share, with ties to even. The split skips missing object values. Rounding and underflow can affect totals, and target aggregation can overflow. diff --git a/src/policyengine/core/dataset.py b/src/policyengine/core/dataset.py index 0b56e5d92..5109d6aa8 100644 --- a/src/policyengine/core/dataset.py +++ b/src/policyengine/core/dataset.py @@ -147,18 +147,24 @@ def _split_narrow_float_share( significand_bits = int(info.nmant) + 1 shift = max(0, (numerator // source_count).bit_length() - significand_bits) units = round(Fraction(numerator, source_count << shift)) - return type(value)(copysign(ldexp(units, tick_exponent + shift), value)) + return value.dtype.type(copysign(ldexp(units, tick_exponent + shift), value)) def _split_scalar_share(value, pair_count: int, source_count: int): """Scale an object or timedelta value by the target's member fraction.""" - if isinstance(value, np.floating): - if value.dtype.itemsize < np.dtype(np.float64).itemsize and np.isfinite(value): + # For floating-point shares, division by a ratio of at least one keeps + # each finite component in range. + if isinstance(value, np.floating | np.complexfloating): + if ( + isinstance(value, np.floating) + and value.dtype.itemsize < np.dtype(np.float64).itemsize + and np.isfinite(value) + ): return _split_narrow_float_share(value, pair_count, source_count) - wide_float = np.result_type(value.dtype, np.float64).type + wide_float = np.result_type(value.real.dtype, np.float64).type divisor = wide_float(source_count) / wide_float(pair_count) - return type(value)(wide_float(value) / divisor) - if isinstance(value, float): + return value.dtype.type(value / divisor) + if isinstance(value, float | complex): return value / (source_count / pair_count) if isinstance(value, Decimal): return _split_decimal_share(value, pair_count, source_count) @@ -220,6 +226,8 @@ def map_to_entity( shares round to the nearest microsecond, with ties to even. Finite narrow NumPy floats in object columns round each pair share to the nearest value in their scalar dtype, with ties to even. + Complex shares divide by the ratio of source members to target + members to keep finite shares in range. With the same valid links, the direct and person-level routes agree in exact arithmetic. Rounding per person can change the diff --git a/tests/test_entity_mapping_group_properties.py b/tests/test_entity_mapping_group_properties.py index b9ba71d58..55b5d617e 100644 --- a/tests/test_entity_mapping_group_properties.py +++ b/tests/test_entity_mapping_group_properties.py @@ -568,10 +568,11 @@ def test_divide_splits_a_long_timedelta_to_the_nanosecond(): def test_divide_preserves_timedelta_seconds_outside_nanosecond_range(): data = _one_tax_unit([1, 1, 2], {"value": 0}) data["tax_unit"]["value"] = np.array([15_000_000_000], dtype="timedelta64[s]") + data["household"].loc[2] = {"household_id": 3, "household_weight": 1.0} mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) result = mapped["value"].to_numpy() assert result.dtype == np.dtype("timedelta64[s]") - assert result.astype(np.int64).tolist() == [10_000_000_000, 5_000_000_000] + assert result.astype(np.int64).tolist() == [10_000_000_000, 5_000_000_000, 0] @pytest.mark.parametrize("unit, ticks", [("ns", 2**62 + 1), ("2s", 9)]) @@ -710,9 +711,11 @@ def test_divide_ignores_missing_object_values_in_split_groups(): assert mapped["value"].tolist() == [0, 0] -def test_divide_keeps_numpy_integers_in_object_columns_from_wrapping(): - amount = 2**62 - data = _one_tax_unit([1, 1, 2], {"value": np.int64(amount)}, as_object=True) +@pytest.mark.parametrize( + "dtype, amount", [(np.int64, 2**62), (np.uint64, 2**63)], ids=["signed", "unsigned"] +) +def test_divide_keeps_numpy_integers_in_object_columns_from_wrapping(dtype, amount): + data = _one_tax_unit([1, 1, 2], {"value": dtype(amount)}, as_object=True) mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) assert mapped["value"].tolist() == [2 * amount / 3, amount / 3] @@ -733,16 +736,35 @@ def test_divide_keeps_floats_in_object_columns_finite(): assert mapped["value"].tolist() == pytest.approx([largest / 3 * 2, largest / 3]) +@pytest.mark.parametrize("dtype", [np.longdouble, np.clongdouble]) +@pytest.mark.parametrize("pair_count, source_count", [(1, 2), (2, 3)]) @pytest.mark.skipif( np.finfo(np.longdouble).maxexp <= np.finfo(np.float64).maxexp, reason="np.longdouble has no wider exponent range on this platform", ) -def test_divide_keeps_longdouble_pair_shares_finite(): - amount = np.longdouble("1e400") - share = _split_scalar_share(amount, pair_count=1, source_count=2) - assert isinstance(share, np.longdouble) +def test_divide_keeps_longdouble_pair_shares_finite(dtype, pair_count, source_count): + exponent = int(np.finfo(np.longdouble).maxexp) - 2 + # Two times this amount exceeds even the longdouble range. + real_amount = np.ldexp(np.longdouble(3), exponent) + share = _split_scalar_share(dtype(real_amount), pair_count, source_count) + assert type(share) is dtype assert np.isfinite(share) - assert share == amount / np.longdouble(2) + assert share == (real_amount / np.longdouble(source_count)) * pair_count + + +@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") +@pytest.mark.parametrize( + "amount", + [complex(1e308), np.complex64(complex(2e38, -2e38)), np.complex128(1e308 - 1e308j)], + ids=["python", "complex64", "complex128"], +) +def test_divide_keeps_complex_values_in_object_columns_finite(amount): + data = _one_tax_unit([1, 1, 2], {"value": amount}, as_object=True) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + shares = mapped["value"].tolist() + assert all(np.isfinite(share) for share in shares) + one_third = complex(amount) / 3 + assert shares == pytest.approx([2 * one_third, one_third]) @pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") @@ -760,10 +782,10 @@ def test_divide_preserves_a_representable_float16_share_in_an_object_column(): @pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") -def test_divide_rounds_a_float16_midpoint_to_even(): - tick = 2**-24 +@pytest.mark.parametrize("dtype, tick", [(np.float16, 2**-24), (np.float32, 2**-149)]) +def test_divide_rounds_a_narrow_float_midpoint_to_even(dtype, tick): data = _one_tax_unit( - [1] * 13 + [None] * 17, {"value": np.float16(15 * tick)}, as_object=True + [1] * 13 + [None] * 17, {"value": dtype(15 * tick)}, as_object=True ) mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) # The linked share is 15 * 13 / 30 = 6.5 ticks. @@ -780,6 +802,21 @@ class Rate(float, Enum): assert mapped["value"].tolist() == [0.5, 0.5] +@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") +@pytest.mark.parametrize("dtype", [np.float16, np.float32, np.float64]) +def test_divide_accepts_numpy_float_subclasses_in_object_columns(dtype): + class FullAmount(dtype): + def __init__(self, amount): + if amount != 1.0: + raise ValueError("FullAmount requires a value of 1.0") + + amount = FullAmount(1.0) + data = _one_tax_unit([1, 2], {"value": amount}, as_object=True) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [0.5, 0.5] + assert type(_split_scalar_share(amount, 1, 2)) is dtype + + def test_divide_gives_integer_columns_float_shares_either_way(): """An integer column maps to float whether or not any unit splits.""" whole = _mapped(