Repository navigation
Conversation
Co-Authored-By: GPT-6.2 Sol <noreply@openai.com> Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Round 3 found that recomputing a cancelled total could erase a nonzero subnormal result, and that finite sentinel inputs overflowed the public helper. The weighted total now sums exact integer products and rounds once, and the weighted-gap ratio is exact for extreme finite inputs. Tests cover the subnormal total, both overflow sentinels and the unequal-weight cancellation case. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The public Gini sentinels reach the exact pairwise path before this function runs, so its overflow branch had no test. Direct asserts now check that cancelling maximum-float products sum to 4 exactly, and that products overflowing in one direction give plus or minus infinity. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Every case uses unit weights, so only the sums overflow. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxGhenis
marked this pull request as ready for review
December 3, 2026 12:53
Contributor
Author
|
Merging at
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #527
Correct the survey-weighted Gini coefficient. The new estimator weights each gap between adjacent sorted incomes by the survey population below the gap times the population above it. It then divides the sum of those weighted gaps by total weight times total weighted income, which gives the exact weighted pairwise Gini. The microdf dependency update and proportional income-share cutoffs in #527 stay open.
What changes for users
Inequality.ginican change when survey weights differ across rows. So canbaseline_inequality.giniandreform_inequality.ginifromeconomic_impact_analysisinpolicyengine.tax_benefit_models.uk, and inpolicyengine.tax_benefit_models.usunder bothinequality_presetvalues, standard and CBO-comparable. This PR contains no change to the income-share calculation.Sort rows by income. Let$f_k$ be row $k$ 's population share, $s_k$ its income share, and $L_k$ the cumulative income share through row $k$ . The old code took the area under the Lorenz curve as $\sum_k f_k (L_k - f_k/2)$ . The trapezoid rule needs $\sum_k f_k (L_k - s_k/2)$ , and the new estimator matches it. The Gini is 1 minus twice that area, so the old Gini minus the new one equals $\sum_k f_k (f_k - s_k)$ . With equal weights that sum is zero, so the old and new formulas agree in exact arithmetic. With unequal weights it can take either sign, so the change on a country baseline depends on how weights vary with income. This PR doesn't measure that change on UK or US baseline data.
Each commit's
_ginigives these values on synthetic inputs, and each value matches the exact fraction in parentheses:The CBO-comparable preset multiplies each household weight by household size and divides income by the square root of size. The third row is therefore the Gini of incomes [20000, 50000, 120000] with weights [2, 4, 3]. Each "After" value equals the exact weighted pairwise Gini,$\sum_i \sum_j w_i w_j \lvert x_i - x_j \rvert / (2 W^2 \mu)$ , where $W$ is the total weight and $\mu$ the weighted mean income. At f9b9f04e,
_ginicomputes these three examples with the same arithmetic as at 728ccf5.Inequality.ginican also change for finite incomes and weights when any of them has a nonzero magnitude outside [2^-100, 2^100]._gininow computes the Gini for those inputs from exact integers and rounds once, at the final division. For example, let M be the float64 maximum.calculate_uk_inequalitygives a Gini of nan on main and 0.5 with this PR for household incomes [0, M] with weights [2, 2].Numerical handling
_giniconverts incomes to at least float64 before it takes differences, so integer incomes can't overflow a gap._weighted_income_totalguards the denominator. A floating-point sum can turn weighted incomes that cancel exactly into a tiny nonzero total, and dividing by it gives a huge Gini. Main at ddfef2a returns about 9.6e15 for incomes [-3, 1, 2] with equal weights 0.01, where 728ccf5 returns 0.0. An earlier commit in this PR, 2c68350f, returned about 1.3e16 for an eight-rowcalculate_uk_inequalitycase. The function checks the NumPy sum against a bound on its rounding error: rows × (float64 epsilon × the sum of absolute weighted incomes + the smallest subnormal). The subnormal term covers products that underflow. When the sum falls inside that bound, or a product or sum overflows, the function recomputes the total from finite inputs. It writes the incomes as integers over one common power-of-two denominator and the weights over another. It then sums the integer products exactly and rounds the total once to the nearest float64. When it recomputes, the function returns any total that float64 can represent exactly, subnormal totals included, and returns inf or -inf for a total too large for float64. For inputs that contain inf or nan, it returns the NumPy total. If the exact total is zero,_ginireturns 0.0.Inequality.run()passes float64 arrays to_gini. When every income and weight is finite and any of them has a nonzero magnitude outside [2^-100, 2^100],_ginicalls_exact_gini. That function keeps the income gaps, cumulative weights and weighted income total as integers and rounds the Gini once, at the final division._ginihandles other float64 inputs with the vectorized path and the cancellation check above.Tests
tests/test_inequality_properties.pyadds Hypothesis properties. Integer weights match replicated unit-weight rows. Splitting a row's weight, reordering rows, or scaling incomes or weights leaves the Gini unchanged. Nonnegative integer incomes with integer weights give values in [0, 1). Equal incomes give 0. A population share p at zero income, with the rest sharing one positive income, gives p. An exactFractionoracle checks signed integer incomes, including replicated and split rows.Fixed cases cover int16 gaps beyond the dtype range and a scaled copy of the UK example above (169/230). Incomes [-3, 1, 2] with equal weights cancel at five scales, and incomes [-2, 1, 1] cancel before and after a split. Two float-step cases move the 2 in [-3, 1, 2] to the next float up or down, so the total is tiny but nonzero.
tests/test_inequality.pyadds acalculate_uk_inequalitycase whose weighted incomes cancel.Ten more cases cover another cancellation and values near the float64 limits. Let q be 2^-1074, the smallest float64 subnormal.
tests/test_inequality.py, onecalculate_uk_inequalitycase has an exact weighted income total of q. The test asserts that_weighted_income_totalreturns q and that the Gini equals 2^54. Two more cases pass incomes built from M throughcalculate_uk_inequality: [-M, M] with weights [0.25, 0.5] must give 4/3, and [0, M] with weights [2, 2] must give 0.5. Each of the three has an income outside [2^-100, 2^100], so_ginisends all three to_exact_gini.tests/test_inequality_properties.py, incomes [-3, 1, 4] with weights [0.01, 0.01, 0.005] must give 0.0. Incomes [-q, -q, -q, -q, q] with weights [0.5, 0.5, 0.5, 0.5, 0.75] have products that underflow. Their total must be -q, the nearest float64 to the exact -1.25q, and their Gini must match -48/55. A direct test of_weighted_income_totalchecks that [-M, 4, M] with unit weights sums to exactly 4.0, and that [M, M] and [-M, -M] give inf and -inf. Four extreme finite cases must match theFractionoracle with NumPy set to raise on overflow or invalid operations: an income gap, a weight total and a weighted income beyond M, and a sum of absolute weighted incomes beyond M. Each has an income or weight above 2^100, so_ginisends all four to_exact_gini.Known gaps
#778 tracks eight inputs that
_ginimishandled at 728ccf5: income gaps, weight totals, or weighted incomes beyond the float64 maximum (about 1.8e308), integer weights whose sum wraps, adjacent integer incomes above 2^53, and float32 weights. Main's_ginimishandles seven of the eight. For the eighth, two incomes that differ by more than the float64 maximum, main returns 0.5 where_giniat 728ccf5 returned inf. When a weighted income overflowed,_giniat 728ccf5 also returned 0.0 where main returns nan.At f9b9f04,
_ginisends all three float64 overflow cases to_exact_gini, which returns the pairwise Gini for each._ginistill mishandles the other five, as main does. The public helpers convert incomes to float64 and can round adjacent int64 or uint64 incomes above 2^53 to the same value. Callers can therefore hit the two large-integer income cases through the public helpers. Callers hit the integer-weight wraparound and float32-weight cases only through direct_ginicalls that keep those weight dtypes. This section previously said that callers could hit only the float64 cases through the public helpers.Changes since 728ccf5
_weighted_income_totalnow sums exact integer products and rounds the total once. At 728ccf5, it restored each partial product's exponent beforemath.fsumand could round a partial product to zero there. In the subnormal test case above, it returned 0.0 for an exact total of q, andcalculate_uk_inequalityreported a Gini of 0.0 instead of 2^54. When products underflowed, it could also compute an error bound of zero and return a tiny NumPy total with the wrong sign. It now adds one smallest subnormal per row to the bound._gininow sends finite float64 inputs with any nonzero income or weight outside [2^-100, 2^100] in magnitude to a new function,_exact_gini. At 728ccf5,calculate_uk_inequalitygave inf for incomes [-M, M] with weights [0.25, 0.5] and 0.0 for incomes [0, M] with weights [2, 2], where the pairwise values are 4/3 and 0.5._weighted_income_totalthat runs when the total or the sum of absolute weighted incomes overflows._ginisends finite float64 inputs that large to_exact_giniand never passes them to_weighted_income_total.test_weighted_income_total_sums_exactly_when_reductions_overflow. Every case uses unit weights, so only the sums overflow.Verification
The local checks at 161977b were static:
py_compile,git diff --check,ruff format --checkandruff check. GitHub CI passed all 13 checks at 161977b, including all 12 jobs in Code changes (Test on Python 3.11 to 3.14 included, run) and the Agent notes check. The pytest counts below are from 728ccf5, before the ten new cases.Eight of the tests added in 728ccf5 failed at 2c68350f: the UK cancellation case, four of the five scale cases, the split case, and both float-step cases. All of them passed at 728ccf5. All pytest runs used CPython 3.14.10 with the locked dependencies and at most four pytest workers, except where noted below.
tests/test_inequality.pytests/test_inequality_properties.pytests/test_decile_grouping.pytests/test_poverty.pyThe other 141 test files at 728ccf5 gave 4,875 passed, 0 failed, and 6 skipped. That total counts each case's final outcome. 123 of the passes came from second runs:
test_wheels.py, all 11 intest_us_native_alignment.py, and four single cases.The six skips need inputs the locked environment lacks: the certified UK 1.58.0 dataset (one), the unpublished microcosm-frame source, alone or with rules-engine and RuleSpec checkouts (four), and a US history helper newer than the pinned policyengine-us (one).
At 728ccf5, these CI jobs in run 46652366403 passed: Lint (whole-tree
ruff format --checkandruff checkwith Ruff 0.17.6, which the job installs unpinned), the changelog-fragment check, the install smoke imports on Python 3.11 to 3.14, the four Test jobs on Python 3.11 to 3.14, and the credentialed "Verify release inputs and bundle packages" job. The separate agent-notes check also passed. The Mypy job only reports errors and never fails. At 728ccf5, it found 217 errors in 42 files, and two of them came from this PR:no-any-returnat lines 28 and 33 ofsrc/policyengine/outputs/inequality.py, both in_weighted_income_total. The locked Ruff 0.12.11 passed on the changed files at 728ccf5 and reported 67 UP038 findings in untouched files.Not run: UK and US baselines from release data.
axiom: n/a: output metric computation, no policy change
🤖 Generated with Claude Code