diff --git a/.claude/policyengine-guide.md b/.claude/policyengine-guide.md index e7523bd70..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 +- `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 new file mode 100644 index 000000000..5dc8ca479 --- /dev/null +++ b/changelog.d/768.fixed.md @@ -0,0 +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 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 87f94b00f..5109d6aa8 100644 --- a/src/policyengine/core/dataset.py +++ b/src/policyengine/core/dataset.py @@ -1,9 +1,13 @@ +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 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 @@ -37,18 +41,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. - how (str): Aggregation method ('sum' or 'first') when mapping to higher-level entities (default 'sum'). + 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. @@ -94,6 +100,90 @@ 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_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 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.""" + # 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.real.dtype, np.float64).type + divisor = wide_float(source_count) / wide_float(pair_count) + 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) + if isinstance(value, pd.Timedelta): + 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, 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 + + def map_to_entity( entity_data: dict[str, MicroDataFrame], source_entity: str, @@ -102,14 +192,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 @@ -117,14 +207,38 @@ 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), '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) + + 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. 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. + 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 + 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 @@ -143,7 +257,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 @@ -348,25 +462,79 @@ def map_to_entity( target_link_key, as_index=False )[agg_cols].first() elif how == "divide": - # Count persons in each source group - source_group_counts = ( - person_df.groupby(source_link_key, as_index=False) + # Split each source value equally among the source's members, + # then give each target group the shares of the members it + # 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 + # 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) + .size() + .rename("__pair_count") + .reset_index() + ) + source_counts = ( + person_df.groupby(source_link_key, observed=True) .size() - .rename(columns={"size": "__source_count"}) + .rename("__source_count") + .reset_index() ) - source_with_target = source_with_target.merge( - source_group_counts, on=source_link_key, how="left" + # 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 ) - # Divide values by source group count (per-person share) + # 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: - source_with_target[col] = ( - source_with_target[col] / 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 + values = linked[col] + if pd.api.types.is_object_dtype( + values.dtype + ) or pd.api.types.is_timedelta64_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. 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 + ) + share.loc[split] = values[split] / divisor + shares[col] = share + + aggregated = shares.groupby( + target_link_key, as_index=False, observed=True )[agg_cols].sum() else: raise ValueError(f"Unsupported aggregation method: {how}") @@ -385,8 +553,20 @@ 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: 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) if return_series: diff --git a/tests/test_entity_mapping_group_properties.py b/tests/test_entity_mapping_group_properties.py new file mode 100644 index 000000000..55b5d617e --- /dev/null +++ b/tests/test_entity_mapping_group_properties.py @@ -0,0 +1,934 @@ +"""Properties of map_to_entity between two group entities. + +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``. +""" + +import decimal +import math +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 +import pandas as pd +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st +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") +# 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, + amounts: dict, + empty: frozenset = frozenset(), + rng=None, + weights: dict | None = None, +): + """Build entity tables from (household, spm_unit, tax_unit) id triples. + + ``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(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: + 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": [ + 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) -> 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: + # 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)) + 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 _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): + """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. + """ + for source, target in permutations(GROUPS, 2): + 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): + """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. + """ + 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=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): + """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( + map_to_entity( + case.data, + "person", + target, + values=per_person["value"].to_numpy(), + how="sum", + ) + ) + direct = _mapped(case.data, source, target, "divide", ["value"]) + assert direct["value"].to_numpy() == pytest.approx( + 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): + for source, target in [ + ("tax_unit", "spm_unit"), + ("tax_unit", "household"), + ("spm_unit", "household"), + ]: + 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[list(COLUMNS)].to_numpy() == pytest.approx( + _mapped(case.data, source, target, "divide")[list(COLUMNS)].to_numpy(), + abs=ABS, + ), (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. A + group with no members sits in no containing group and gets 0. + """ + 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(): + """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, + amounts=_one_column({"tax_unit": {100: 100}}), + ) + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + 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, + amounts=_one_column({"tax_unit": {100: 300}}), + ) + 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] + + +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; 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( + { + "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 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}) + 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(): + """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", + "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] + 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(): + """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} + + +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_splits_a_long_timedelta_to_the_nanosecond(): + """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(ticks, "ns")}), + "tax_unit", + "household", + "divide", + ["value"], + ) + assert mapped["value"].tolist() == [ + pd.Timedelta(2 * ticks // 3, "ns"), + pd.Timedelta(ticks // 3, "ns"), + ] + + +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, 0] + + +@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_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=2**54 + 2), + [1, 2], + [timedelta(microseconds=2**53 + 1)] * 2, + ), + ( + 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", + "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) + 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} + mapped = _mapped(data, "tax_unit", "household", "divide", ["value"]) + assert mapped["value"].tolist() == [ + pd.Timedelta(-1, "ns"), + pd.Timedelta(0), + pd.Timedelta(0), + ] + + +def test_divide_rounds_a_split_decimal_once(): + """Two of three members in household 1 give it Decimal 200.00 / 3. + + 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")}), + "tax_unit", + "household", + "divide", + ["value"], + ) + assert mapped["value"].tolist() == [ + Decimal("200.00") / 3, + Decimal("100.00") / 3, + ] + 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] + + +@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"]) + assert mapped["value"].tolist() == [0, 0] + + +@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] + + +# 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]) + + +@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(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 == (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") +def test_divide_preserves_a_representable_float16_share_in_an_object_column(): + 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"]) + assert [float(share) for share in mapped["value"]] == [float(s) for s in expected] + + +@pytest.mark.filterwarnings("ignore:Downcasting object dtype arrays:FutureWarning") +@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": dtype(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] + + +@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( + _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): + """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 + 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 + ) + + +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): + """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): + 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)