Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .claude/policyengine-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 1 addition & 0 deletions changelog.d/768.fixed.md
Original file line number Diff line number Diff line change
@@ -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.
236 changes: 208 additions & 28 deletions src/policyengine/core/dataset.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -102,29 +192,53 @@ 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
source_entity: The source entity name
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
Expand All @@ -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
Expand Down Expand Up @@ -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}")
Expand All @@ -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:
Expand Down
Loading
Loading