Skip to content

Correct the Gini coefficient for unequal survey weights - #774

Draft
MaxGhenis wants to merge 6 commits into
mainfrom
codex/4397-policyengine-py-audit-property-test-the-weighted-gini-in-outpu
Draft

MaxGhenis wants to merge 6 commits into
mainfrom
codex/4397-policyengine-py-audit-property-test-the-weighted-gini-in-outpu

Conversation

@MaxGhenis

@MaxGhenis MaxGhenis commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

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.gini can change when survey weights differ across rows. So can baseline_inequality.gini and reform_inequality.gini from economic_impact_analysis in policyengine.tax_benefit_models.uk, and in policyengine.tax_benefit_models.us under both inequality_preset values, 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 _gini gives these values on synthetic inputs, and each value matches the exact fraction in parentheses:

Example Inputs Before: main at ddfef2a8 After: 728ccf502
UK Equivalized net incomes [0, 10000, 100000], household weights [5, 3, 2] 0.901739 (1037/1150) 0.734783 (169/230)
US standard Net incomes [20000, 100000, 120000], household weights [2, 1, 3] 0.242222 (109/450) 0.273333 (41/150)
US CBO-comparable Same US inputs, household sizes [1, 4, 1] 0.306173 (124/405) 0.311111 (14/45)

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, _gini computes these three examples with the same arithmetic as at 728ccf5.

Inequality.gini can also change for finite incomes and weights when any of them has a nonzero magnitude outside [2^-100, 2^100]. _gini now 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_inequality gives a Gini of nan on main and 0.5 with this PR for household incomes [0, M] with weights [2, 2].

Numerical handling

  • _gini converts incomes to at least float64 before it takes differences, so integer incomes can't overflow a gap.
  • _weighted_income_total guards 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-row calculate_uk_inequality case. 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. 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, _gini returns 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], _gini calls _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. _gini handles other float64 inputs with the vectorized path and the cancellation check above.
  • The docstring now gives the [0, 1] range only for nonnegative incomes with positive weight totals. Signed incomes can give values outside that range, on main and here. The docstring also lists the three inputs that return 0.0: empty inputs, zero total weight, and zero weighted income.

Tests

tests/test_inequality_properties.py adds 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 exact Fraction oracle 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.py adds a calculate_uk_inequality case 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.

  • In tests/test_inequality.py, one calculate_uk_inequality case has an exact weighted income total of q. The test asserts that _weighted_income_total returns q and that the Gini equals 2^54. Two more cases pass incomes built from M through calculate_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 _gini sends all three to _exact_gini.
  • In 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_total checks 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 the Fraction oracle 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 _gini sends all four to _exact_gini.

Known gaps

#778 tracks eight inputs that _gini mishandled 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 _gini mishandles seven of the eight. For the eighth, two incomes that differ by more than the float64 maximum, main returns 0.5 where _gini at 728ccf5 returned inf. When a weighted income overflowed, _gini at 728ccf5 also returned 0.0 where main returns nan.

At f9b9f04, _gini sends all three float64 overflow cases to _exact_gini, which returns the pairwise Gini for each. _gini still 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 _gini calls that keep those weight dtypes. This section previously said that callers could hit only the float64 cases through the public helpers.

Changes since 728ccf5

  • 2cee69b6: _weighted_income_total now sums exact integer products and rounds the total once. At 728ccf5, it restored each partial product's exponent before math.fsum and could round a partial product to zero there. In the subnormal test case above, it returned 0.0 for an exact total of q, and calculate_uk_inequality reported 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. _gini now 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_inequality gave 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.
  • f9b9f04e: a direct test now covers the branch of _weighted_income_total that runs when the total or the sum of absolute weighted incomes overflows. _gini sends finite float64 inputs that large to _exact_gini and never passes them to _weighted_income_total.

Verification

The local checks at f9b9f04 were static: py_compile, git diff --check, ruff format --check and ruff check. GitHub CI passed all 13 checks at f9b9f04, including Test on Python 3.11 to 3.14 (run). 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.

File 2c68350f plus the tests from 728ccf5 728ccf502
tests/test_inequality.py 11 passed, 1 failed 12 passed, 0 failed
tests/test_inequality_properties.py 12 passed, 7 failed 19 passed, 0 failed
tests/test_decile_grouping.py 23 passed, 0 failed 23 passed, 0 failed
tests/test_poverty.py 5 passed, 0 failed 5 passed, 0 failed
Total 51 passed, 8 failed 59 passed, 0 failed

The 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:

  • 105 reruns after the first pass hit test-environment problems: all 90 cases in test_wheels.py, all 11 in test_us_native_alignment.py, and four single cases.
  • 6 cases on Python 3.13.5 that skip on 3.14.
  • 3 cases with the public policyengine-uk 2.134.7 wheel.
  • 5 cases with a temporary local-wheel manifest built from the pinned public wheels.
  • 4 cases with a local fixture in place of the private release index. These four don't exercise the private index.

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 --check and ruff check with 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-return at lines 28 and 33 of src/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

MaxGhenis and others added 3 commits December 2, 2026 16:02
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>

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.

2 participants