diff --git a/changelog.d/527.fixed.md b/changelog.d/527.fixed.md new file mode 100644 index 000000000..f5ee7708e --- /dev/null +++ b/changelog.d/527.fixed.md @@ -0,0 +1 @@ +Correct the survey-weighted Gini coefficient by weighting each income gap by the survey population on either side. diff --git a/src/policyengine/outputs/inequality.py b/src/policyengine/outputs/inequality.py index 4b16f7a97..0a3a48b6d 100644 --- a/src/policyengine/outputs/inequality.py +++ b/src/policyengine/outputs/inequality.py @@ -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 @@ -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. @@ -25,10 +103,13 @@ 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 @@ -36,24 +117,36 @@ def _gini(values: np.ndarray, weights: np.ndarray) -> float: 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( diff --git a/tests/test_inequality.py b/tests/test_inequality.py index f7ef6ee47..63a5f575f 100644 --- a/tests/test_inequality.py +++ b/tests/test_inequality.py @@ -16,6 +16,8 @@ Inequality, USInequalityPreset, _gini, + _weighted_income_total, + calculate_uk_inequality, calculate_us_inequality, ) from policyengine.tax_benefit_models.uk import ( @@ -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]) diff --git a/tests/test_inequality_properties.py b/tests/test_inequality_properties.py new file mode 100644 index 000000000..c61b9baad --- /dev/null +++ b/tests/test_inequality_properties.py @@ -0,0 +1,200 @@ +"""Properties of the survey-weighted Gini coefficient.""" + +from fractions import Fraction +from itertools import combinations + +import numpy as np +import pytest +from hypothesis import given, settings +from hypothesis import strategies as st + +from policyengine.outputs.inequality import _gini, _weighted_income_total + +INCOMES = st.floats(min_value=0, max_value=10_000, allow_subnormal=False) +WEIGHTS = st.floats(min_value=0.125, max_value=32) + + +@st.composite +def weighted_incomes(draw, incomes=INCOMES, weights=WEIGHTS): + rows = draw(st.lists(st.tuples(incomes, weights), min_size=1, max_size=16)) + values, row_weights = zip(*rows) + return np.array(values, dtype=float), np.array(row_weights) + + +@given(weighted_incomes(weights=st.integers(min_value=1, max_value=10))) +def test_gini_integer_weights_match_unit_weight_copies(sample): + values, weights = sample + replicated = np.repeat(values, weights) + + assert _gini(values, weights) == pytest.approx( + _gini(replicated, np.ones_like(replicated)), abs=1e-12, rel=0 + ) + + +@given(weighted_incomes(), st.floats(min_value=0.125, max_value=0.875)) +def test_gini_is_invariant_to_splitting_a_weight(sample, fraction): + values, weights = sample + first_weight = weights[0] * fraction + split_values = np.insert(values, 0, values[0]) + split_weights = np.insert(weights, 0, first_weight) + split_weights[1] -= first_weight + + assert _gini(split_values, split_weights) == pytest.approx( + _gini(values, weights), abs=1e-12, rel=0 + ) + + +@given( + weighted_incomes( + incomes=st.integers(min_value=0, max_value=10_000), + weights=st.integers(min_value=1, max_value=32), + ) +) +def test_gini_is_in_range(sample): + # Small integers avoid estimator-dependent roundoff at exactly zero. + assert 0 <= _gini(*sample) < 1 + + +@pytest.mark.parametrize("scale_income", [True, False], ids=["income", "weight"]) +@given(weighted_incomes(), st.floats(min_value=0.125, max_value=32)) +def test_gini_is_scale_invariant(scale_income, sample, factor): + values, weights = sample + scaled = (values * factor, weights) if scale_income else (values, weights * factor) + + assert _gini(*scaled) == pytest.approx(_gini(values, weights), abs=1e-12, rel=0) + + +@given(weighted_incomes(), st.data()) +def test_gini_is_row_order_invariant(sample, data): + values, weights = sample + order = data.draw(st.permutations(range(len(values)))) + indices = np.array(order) + + assert _gini(values[indices], weights[indices]) == pytest.approx( + _gini(values, weights), abs=1e-12, rel=0 + ) + + +@given(INCOMES, st.lists(WEIGHTS, min_size=1, max_size=16)) +def test_gini_is_zero_for_equal_incomes(income, weights): + assert _gini(np.full(len(weights), income), np.array(weights)) == pytest.approx( + 0, abs=1e-12, rel=0 + ) + + +@given(WEIGHTS, WEIGHTS) +def test_gini_equals_zero_income_population_share(zero_weight, positive_weight): + weights = np.array([zero_weight, positive_weight]) + expected = zero_weight / weights.sum() + + assert _gini(np.array([0.0, 1.0]), weights) == pytest.approx( + expected, abs=1e-12, rel=0 + ) + + +def test_gini_handles_income_gaps_larger_than_integer_dtype(): + values = np.array([-10_000, 25_000, 25_000], dtype=np.int16) + + assert _gini(values, np.ones(3)) == pytest.approx(7 / 12) + + +def test_gini_with_multiple_weighted_income_gaps(): + values = np.array([0.0, 1.0, 10.0]) + weights = np.array([5.0, 3.0, 2.0]) + + assert _gini(values, weights) == pytest.approx(169 / 230) + + +@pytest.mark.parametrize("scale", [0.5, 1, 2, 3, 10]) +def test_gini_is_zero_at_each_scale_when_weighted_incomes_cancel(scale): + assert _gini(scale * np.array([-3, 1, 2]), np.full(3, 0.01)) == 0.0 + + +def test_gini_is_zero_after_splitting_a_weight_when_weighted_incomes_cancel(): + assert _gini(np.array([-2, 1, 1]), np.full(3, 0.01)) == 0.0 + assert _gini(np.array([-2, 1, 1, 1]), np.array([0.01, 0.005, 0.005, 0.01])) == 0.0 + + +def test_gini_is_zero_when_distinct_incomes_and_unequal_weights_cancel(): + assert _gini(np.array([-3.0, 1.0, 4.0]), np.array([0.01, 0.01, 0.005])) == 0.0 + + +def test_gini_retains_weighted_income_sign_when_products_underflow(): + smallest_subnormal = 2.0**-1074 + values = np.array([-smallest_subnormal] * 4 + [smallest_subnormal]) + weights = np.array([0.5] * 4 + [0.75]) + + assert _weighted_income_total(values, weights) == -smallest_subnormal + assert _gini(values, weights) == pytest.approx(-48 / 55, rel=1e-15, abs=0) + + +def test_weighted_income_total_sums_exactly_when_reductions_overflow(): + largest = np.finfo(np.float64).max + + assert _weighted_income_total(np.array([-largest, 4.0, largest]), np.ones(3)) == 4.0 + assert _weighted_income_total(np.array([largest, largest]), np.ones(2)) == np.inf + assert _weighted_income_total(np.array([-largest, -largest]), np.ones(2)) == -np.inf + + +def _exact_gini(values, weights): + rows = list(zip(map(Fraction, values.tolist()), map(Fraction, weights.tolist()))) + total_weight = sum(weight for _, weight in rows) + total_income = sum(value * weight for value, weight in rows) + if total_weight == 0 or total_income == 0: + return Fraction(0) + + pairwise_differences = sum( + left_weight * right_weight * abs(left - right) + for (left, left_weight), (right, right_weight) in combinations(rows, 2) + ) + return pairwise_differences / (total_weight * total_income) + + +@pytest.mark.parametrize( + ("values", "weights"), + [ + ([-9.9792015476736e291, np.finfo(np.float64).max], [1.0, 1.0]), + ([0.0, 1.0], [2.0**1023] * 2), + ([0.0, 4.0], [2.0**1022] * 2), + ([-np.finfo(np.float64).max, 4.0, np.finfo(np.float64).max], [1.0] * 3), + ], + ids=["income-gap", "weight-sum", "weighted-income", "absolute-income-sum"], +) +def test_gini_matches_pairwise_oracle_for_extreme_finite_values(values, weights): + values = np.array(values) + weights = np.array(weights) + expected = float(_exact_gini(values, weights)) + + with np.errstate(over="raise", invalid="raise"): + assert _gini(values, weights) == pytest.approx(expected, rel=1e-15, abs=0) + + +@pytest.mark.parametrize("direction", [-np.inf, np.inf], ids=["negative", "positive"]) +def test_gini_preserves_a_small_nonzero_weighted_income(direction): + values = np.array([-3, 1, np.nextafter(2.0, direction)]) + weights = np.full(3, 0.01) + expected = float(_exact_gini(values, weights)) + + assert _gini(values, weights) == pytest.approx(expected, rel=1e-12) + + +@settings(deadline=None) +@given(st.lists(st.tuples(st.integers(-10, 10), st.integers(0, 5)), max_size=10)) +def test_gini_matches_exact_pairwise_oracle(rows): + values, weights = np.array(rows, dtype=int).reshape(-1, 2).T + expected = float(_exact_gini(values, weights)) + replicated_values = np.repeat(values, weights) + samples = [(values, weights), (replicated_values, np.ones_like(replicated_values))] + if rows: + middle = len(rows) // 2 + half_weight = weights[middle] / 2 + split_values = np.insert(values, middle, values[middle]) + split_weights = np.insert(weights.astype(float), middle, half_weight) + split_weights[middle + 1] = half_weight + samples.append((split_values, split_weights)) + + for sample in samples: + if expected == 0: + assert _gini(*sample) == 0.0 + else: + assert _gini(*sample) == pytest.approx(expected, rel=1e-12, abs=0)