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
1 change: 1 addition & 0 deletions changelog.d/527.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Correct the survey-weighted Gini coefficient by weighting each income gap by the survey population on either side.
121 changes: 107 additions & 14 deletions src/policyengine/outputs/inequality.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Inequality analysis output types."""

from enum import Enum
from itertools import pairwise
from typing import Any, Optional, Union

import numpy as np
Expand All @@ -17,6 +18,83 @@ class USInequalityPreset(str, Enum):
CBO_COMPARABLE = "cbo_comparable"


_FLOAT64 = np.finfo(np.float64)


def _dyadic_integers(values: np.ndarray) -> tuple[list[int], int]:
"""Express finite binary floats as integers over a common denominator."""
ratios = [value.as_integer_ratio() for value in values.tolist()]
denominator = max((divisor for _, divisor in ratios), default=1)
integers = [numerator * (denominator // divisor) for numerator, divisor in ratios]
return integers, denominator


def _ratio_as_float(numerator: int, denominator: int) -> float:
try:
return numerator / denominator
except OverflowError:
return float("-inf") if (numerator < 0) != (denominator < 0) else float("inf")


def _weighted_income_total(
values: np.ndarray, weights: np.ndarray
) -> float | np.floating:
total: np.floating
if np.result_type(values, weights) != np.float64:
total = (values * weights).sum()
return total

with np.errstate(over="ignore", under="ignore", invalid="ignore"):
products = values * weights
total = products.sum()
if products.size == 0:
return total
absolute_total = float(np.abs(products).sum())

# Allow for product and addition rounding, including subnormal products.
error_bound = products.size * (
float(_FLOAT64.eps) * absolute_total + float(_FLOAT64.smallest_subnormal)
)
if abs(total) > error_bound or (
absolute_total == 0 and not np.any((values != 0) & (weights != 0))
):
return total
if not (np.isfinite(values).all() and np.isfinite(weights).all()):
return total

# Keep the exact exponents through multiplication and summation.
incomes, income_denominator = _dyadic_integers(values)
row_weights, weight_denominator = _dyadic_integers(weights)
numerator = sum(income * weight for income, weight in zip(incomes, row_weights))
return _ratio_as_float(numerator, income_denominator * weight_denominator)


def _outside_fast_gini_range(values: np.ndarray) -> bool:
# Values in this range are multiples of 2**-152. This leaves room in
# binary64 for gaps, weight fractions and products over up to 2**63 rows.
magnitudes = np.abs(values)
outside = (magnitudes > 2.0**100) | ((magnitudes < 2.0**-100) & (magnitudes != 0))
return bool(outside.any())


def _exact_gini(sorted_values: np.ndarray, sorted_weights: np.ndarray) -> float:
# The common scales cancel from the Gini ratio. Integer gaps and weight
# sums let us defer rounding until the final division.
values, _ = _dyadic_integers(sorted_values)
weights, _ = _dyadic_integers(sorted_weights)
total_weight = sum(weights)
total_income = sum(value * weight for value, weight in zip(values, weights))
if total_weight == 0 or total_income == 0:
return 0.0

lower_weight = 0
weighted_gaps = 0
for weight, (lower, upper) in zip(weights, pairwise(values)):
lower_weight += weight
weighted_gaps += (upper - lower) * lower_weight * (total_weight - lower_weight)
return _ratio_as_float(weighted_gaps, total_weight * total_income)


def _gini(values: np.ndarray, weights: np.ndarray) -> float:
"""Calculate weighted Gini coefficient.

Expand All @@ -25,35 +103,50 @@ def _gini(values: np.ndarray, weights: np.ndarray) -> float:
weights: Array of weights

Returns:
Gini coefficient between 0 (perfect equality) and 1 (perfect inequality)
The weighted Gini coefficient. For nonnegative incomes and survey
weights with positive totals, the mathematical coefficient lies in
[0, 1]. Signed incomes can give a value outside that interval. Empty
inputs, zero total weight, and zero weighted income return 0.0.
"""
# Handle edge cases
if len(values) == 0 or weights.sum() == 0:
if len(values) == 0:
return 0.0

# Sort by values
sorted_indices = np.argsort(values)
sorted_values = values[sorted_indices]
sorted_weights = weights[sorted_indices]

# Cumulative weights and weighted values
# Promote incomes before computing products and differences.
sorted_values = sorted_values.astype(
np.result_type(values.dtype, np.float64), copy=False
)
if (
sorted_values.dtype == sorted_weights.dtype == np.float64
and (
_outside_fast_gini_range(sorted_values)
or _outside_fast_gini_range(sorted_weights)
)
and np.isfinite(sorted_values).all()
and np.isfinite(sorted_weights).all()
):
return _exact_gini(sorted_values, sorted_weights)

if weights.sum() == 0:
return 0.0

cumulative_weights = np.cumsum(sorted_weights)
total_weight = cumulative_weights[-1]
cumulative_weighted_values = np.cumsum(sorted_values * sorted_weights)
total_weighted_value = cumulative_weighted_values[-1]
total_weighted_value = _weighted_income_total(sorted_values, sorted_weights)

if total_weighted_value == 0:
return 0.0

# Calculate Gini using the area formula
# Gini = 1 - 2 * (area under Lorenz curve)
lorenz_curve = cumulative_weighted_values / total_weighted_value
weight_fractions = sorted_weights / total_weight

# Area under Lorenz curve using trapezoidal rule
area = np.sum(weight_fractions * (lorenz_curve - weight_fractions / 2))

return float(1 - 2 * area)
# Each income gap contributes to pairs with one row on either side.
lower_weight_fractions = cumulative_weights[:-1] / total_weight
upper_weights = np.cumsum(sorted_weights[:0:-1])[::-1]
weighted_gaps = np.diff(sorted_values) * lower_weight_fractions * upper_weights
return float(np.sum(weighted_gaps) / total_weighted_value)


def _series_for_entity(
Expand Down
56 changes: 56 additions & 0 deletions tests/test_inequality.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
Inequality,
USInequalityPreset,
_gini,
_weighted_income_total,
calculate_uk_inequality,
calculate_us_inequality,
)
from policyengine.tax_benefit_models.uk import (
Expand Down Expand Up @@ -43,6 +45,60 @@ def _make_household_simulation(household_df: pd.DataFrame) -> Simulation:
)


def test_uk_inequality_gini_is_zero_when_weighted_incomes_cancel():
households = pd.DataFrame(
{
UK_INEQUALITY_INCOME_VARIABLE: [-11, 0, 0, 0, 0, 0, 4, 7],
"household_weight": [0.01] * 8,
}
)

assert calculate_uk_inequality(_make_household_simulation(households)).gini == 0.0


def test_uk_inequality_gini_preserves_a_subnormal_weighted_income_total():
smallest_subnormal = 2.0**-1074
income = 2.0**-1020
small_weight = 2.0**-56
values = np.array(
[
-income,
income,
2 * income - 8 * smallest_subnormal,
2 * income + 8 * smallest_subnormal,
]
)
weights = np.array([1.0, 1.0, small_weight, small_weight])
households = pd.DataFrame(
{UK_INEQUALITY_INCOME_VARIABLE: values, "household_weight": weights}
)

assert _weighted_income_total(values, weights) == smallest_subnormal
assert calculate_uk_inequality(_make_household_simulation(households)).gini == 2**54


@pytest.mark.parametrize(
("unit_incomes", "weights", "expected"),
[([-1.0, 1.0], [0.25, 0.5], 4 / 3), ([0.0, 1.0], [2.0, 2.0], 0.5)],
ids=["income-gap", "weighted-income"],
)
def test_uk_inequality_gini_with_income_sentinels(unit_incomes, weights, expected):
households = pd.DataFrame(
{
"custom_income": np.array(unit_incomes) * np.finfo(np.float64).max,
"household_weight": weights,
}
)

# Income shares still use the original weighted-income products.
with np.errstate(over="ignore", invalid="ignore"):
result = calculate_uk_inequality(
_make_household_simulation(households), income_variable="custom_income"
)

assert result.gini == pytest.approx(expected, rel=1e-15, abs=0)


def test_gini_perfect_equality():
"""Test Gini coefficient with perfect equality (all same income)."""
values = np.array([100.0, 100.0, 100.0, 100.0])
Expand Down
Loading