Skip to content

Fix precision and missing values in group-to-group divide - #772

Draft
MaxGhenis wants to merge 10 commits into
mainfrom
codex/2137-policyengine-py-pr770-draft-keep-each-value-whole-in-gro
Draft

MaxGhenis wants to merge 10 commits into
mainfrom
codex/2137-policyengine-py-pr770-draft-keep-each-value-whole-in-gro

Conversation

@MaxGhenis

@MaxGhenis MaxGhenis commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #768

This pull request combines #770 and its follow-up for a single merge into main and supersedes #770.

Group-to-group map_to_entity(how="divide") allocates each source value by member count. Each linked target receives the fraction of the source value that matches the members it holds, so the $100 tax unit in #768 contributes $100 to the household that contains both members. A target that holds every member receives the whole contribution before output dtype conversion and target aggregation. Members without a target link still count in the denominator. Empty sources and null source IDs contribute nothing.

For integer and boolean columns, map_to_entity returns floating-point shares. It computes the intermediate product of NumPy integer scalars in object columns with Python integers.
It keeps each pair share of a finite float64 or complex value finite. For NumPy floats in object columns, it builds each split share from the base scalar type of the source dtype before target aggregation. It rounds the exact share of a finite float16 or float32 scalar once, to the nearest value in that dtype, with ties to even. It computes the shares of other NumPy floats in at least float64. For Python floats, including float enum members, it uses native floating-point division.
It scales the coefficient of a split Decimal exactly and computes the quotient in the caller's context.
It truncates split pandas and NumPy timedeltas towards zero in their stored unit. It keeps the unit of a native timedelta column and fills unmatched targets with a timedelta zero at that resolution. In a NumPy timedelta object column, it keeps each pair share in its source scalar's unit. When one target receives NumPy timedeltas in different units, NumPy adds them in a common unit if one exists. It fills unmatched targets in these object columns with integer zero.
It scales split Python datetime.timedelta values in integer microseconds and rounds once to the nearest microsecond, with ties to even.
It skips share arithmetic for missing object values. Pandas may infer an output dtype while it fills other object columns.

In exact arithmetic, the shares of a non-empty source add to its amount when every member links to a target. With the same valid links, the direct route and the route through people compute the same allocation in exact arithmetic, and rounding per person can change the result. Shares can round or underflow, and target totals can round or overflow. The result carries the target weights. In exact arithmetic, weighted totals agree for non-empty sources when every member links to a target and every contribution has the same weight at its source and target. The row-order tests shuffle IDs under a RangeIndex.

For columns, map_to_entity returns a MicroDataFrame. For values= in source-row order, it returns a weighted MicroSeries.

Since d0cbdabf1, the Python float branch of map_to_entity divides subclasses directly, so it splits a float enum member into plain float shares. At 23272c5c2, it passed each share to the subclass constructor. For an enum whose only value is 1.0, the constructor raised ValueError on a share of 0.5.
Since d0cbdab, map_to_entity also computes the exact share of each finite float16 or float32 value in an object column and rounds it once. At 23272c5, it computed the share in float64 and rounded three times: at the divisor, at the quotient and at the cast to the narrow dtype. For example, a tax unit of 30 members has a float16 value of 15 * 2**-24, and a household holds 13 of those members. The household's exact share is 6.5 * 2**-24. At 23272c5, map_to_entity rounded that share to 7 * 2**-24, and since d0cbdab it rounds it to the even 6 * 2**-24.
New tests at d0cbdab cover both cases. They also cover a Python timedelta whose halves exceed 2**53 microseconds. Where the platform's np.longdouble has a wider exponent range than float64, a test checks that the share helper _split_scalar_share returns a finite np.longdouble half of a value above the float64 range. The 1:69,999 float16 test now checks each pair share's dtype at _split_scalar_share and compares values end to end. The changelog entry and the map_to_entity docstring now describe the ties-to-even rounding of finite narrow NumPy floats in object columns.
Since f60241e70, map_to_entity builds each split NumPy float share from the base scalar type of its dtype. At d0cbdab, it passed the share to the input scalar's class, so a NumPy float subclass whose constructor accepts only one value raised ValueError, and a np.float64 subclass took that path too. Since f60241e, Python and NumPy complex shares also divide by the source-to-pair member ratio instead of multiplying first. At d0cbdab, a finite complex value near the top of its range overflowed before the division.
New tests at f60241e cover NumPy float subclasses of float16, float32 and float64, finite complex values in object columns, the float32 midpoint beside the float16 one, an unsigned NumPy integer in an object column beside the signed one, and seconds-resolution zero fill in a native timedelta column. Where the platform's np.longdouble has a wider exponent range than float64, the share-helper tests also cover np.clongdouble values above the float64 range, including a two-of-three split.

Under the lock, the focused tests from 23272c5c2 passed 76 cases and failed three against the 1f40fa209 implementation.
At 23272c5, the locked focused tests passed all 79 cases, including all 42 group-mapping tests.
The full run at 23272c5 passed 4,937 tests, failed none and skipped 25 for unavailable prerequisites or Python-version gates.
At 23272c5, locked Ruff formatting and lint checks passed on the changed files, and the changelog and agent-notes checks passed. Repository-wide Ruff reported 67 existing UP038 diagnostics at 23272c5, down from 68 at 1f40fa2.
At d0cbdabf1, py_compile, git diff --check, ruff format --check and ruff check ran locally. GitHub CI then passed all 13 checks at d0cbdab, including Test on Python 3.11 to 3.14 (run).
At f60241e, py_compile, git diff --check, ruff format --check and ruff check ran locally. This pull request now targets main.

axiom: n/a: shared entity mapping infrastructure

Opened by a Codex cloud task (queue file 2137-policyengine-py-pr770-draft-keep-each-value-whole-in-gro).

MaxGhenis and others added 10 commits November 26, 2026 11:20
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
…olumns

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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@anthropic.com>
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 <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
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 <noreply@anthropic.com>
- 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 <noreply@anthropic.com>
@MaxGhenis
MaxGhenis changed the base branch from fix/map-to-entity-group-divide to main December 3, 2026 04:16

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Group-to-group map_to_entity(how="divide") keeps only part of each value

2 participants