Skip to content
Merged
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/update-policyengine-6.20.4.changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Updated policyengine.py from 6.20.0 to 6.20.4 in the simulation runtime. 6.20.4 ranks households with equal incomes in the order of their rows when it calculates the Gini coefficient and the top 10% and top 1% income shares, so the same rows give the same values on every host. numpy's default sort, used before, puts equal values in an order that depends on the CPU, so the same UK report could give different top shares on different hosts: in one check of 20 UK values they moved by up to 9.8e-5 relative. The update also brings in .py 6.20.1 to 6.20.3: policyengine-uk 2.179.2 (from 2.174.1), policyengine-core 3.34.10 (from 3.33.3) and newly certified UK national and local-area datasets, so UK results change. A UK national report's data version becomes `uk-frs-calibration-attempt-20261122T100732Z-b891aa69`, and the UK datasets' revisions are Hugging Face commit hashes instead of tag names. policyengine-us and the US data are unchanged, but policyengine-core's reform and caching fixes apply to US simulations too. API v1 sends its own .py version with each request, so its reports move to 6.20.4 only when API v1 raises its own pin.
4 changes: 2 additions & 2 deletions projects/policyengine-simulation-executor/pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ dependencies = [
"policyengine-stage12-persistence",
# PolicyEngine.py's models extra is the only selector for core, country
# models, and the SPM calculator. Do not duplicate those versions here.
"policyengine[models]==6.20.0",
"policyengine[models]==6.20.4",
"tables>=3.10.2",
# 1.6.4 is the first release whose containers reload Secret values when
# they restore from a memory snapshot. Every app deployed or run from this
Expand Down Expand Up @@ -58,7 +58,7 @@ packages = ["src/policyengine_simulation_executor"]
# certified datasets and writes their receipt.
[dependency-groups]
modal-simulation-image = [
"policyengine[models]==6.20.0",
"policyengine[models]==6.20.4",
"fastapi>=0.115.0",
"tables>=3.10.2",
"policyengine-observability[fastapi,google,otlp-grpc]>=3.0.7,<4",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,9 @@ def reported_data_version(
on the regional dataset, and a UK-wide or nation report on the local-area
dataset (``is_local_area_report``), which stands for API v1's local-area
breakdown run. Until policyengine.py 6.20.0 the default dataset's revision
was the release's data version; since then the US one is a Hugging Face
commit, while the release keeps its version name.
was the release's data version. Since then the US one is a Hugging Face
commit, and since 6.20.1 the UK national and local-area ones are too, while
each release keeps its version name.
"""
from policyengine_simulation_executor.release_bundle import ( # noqa: PLC0415 # resolved per call so tests can patch release_bundle.get_country_release_bundle
get_country_release_bundle,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,215 @@
"""The UK inequality output ranks households with equal incomes in row order.

A UK report's Gini coefficient and top 10% and top 1% income shares come from
.py's ``calculate_uk_inequality``, which the UK ``economic_impact_analysis``
calls for the baseline and the reform, and reach the result through
``build_inequality``. A household counts towards a top share only once its
cumulative weight share passes the cutoff, so when households with the same
income sit at a cutoff, the order they are ranked in decides which of them
count. The Gini's floating-point sums depend on that order too.

Stage 12 stores each entity's rows sorted by ``<entity>_id``, and API v1's
calculation keeps the dataset's order, which for the UK national dataset is the
same. These tests rebuild a UK dataset from stored frames as Stage 12's
aggregation does (``_dataset_from_frames`` and ``PrecomputedSimulation``) and
check that households with equal incomes are ranked in row order, so the same
rows give the same values on every host. Until .py sorted incomes with a stable
sort (PolicyEngine/policyengine.py#777), it used numpy's default sort, which
puts equal values in a different order on different CPUs.
"""

from __future__ import annotations

from types import SimpleNamespace
from typing import TYPE_CHECKING, NamedTuple

import numpy as np
import pandas as pd
import pytest
from policyengine.outputs.inequality import calculate_uk_inequality
from policyengine_simulation_executor.simulation_output_inequality import (
build_inequality,
)
from policyengine_simulation_executor.simulation_runtime import _country_module
from policyengine_simulation_executor.stage12_runtime.aggregation import (
PrecomputedSimulation,
_dataset_from_frames,
)

if TYPE_CHECKING:
from collections.abc import Sequence

INCOME_VARIABLE = "equiv_hbai_household_net_income"

# One poorer household and twenty copies of a richer one: ten copies weigh 1
# and ten weigh 3. The total weight is 110, so the top 10% cutoff (a
# cumulative weight above 99) and the top 1% cutoff (above 108.9) both fall
# among the copies. Twenty copies, because numpy's default sort has left
# smaller groups of equal values in row order on some CPUs.
POORER_INCOME = 10_000.0
POORER_WEIGHT = 70.0
RICHER_INCOME = 50_000.0
LIGHT_COPY_WEIGHT = 1.0
HEAVY_COPY_WEIGHT = 3.0
COPIES_PER_WEIGHT = 10
TOTAL_INCOME = POORER_INCOME * POORER_WEIGHT + RICHER_INCOME * COPIES_PER_WEIGHT * (
LIGHT_COPY_WEIGHT + HEAVY_COPY_WEIGHT
)

# Seeded households at a few income levels, so many households share each
# income and the cutoffs fall inside groups of equal incomes.
SEEDED_HOUSEHOLD_COUNT = 200
SEEDED_INCOME_LEVELS = np.arange(1, 9) * 10_000.0


class InequalityValues(NamedTuple):
"""The three values the inequality output reports for one simulation."""

gini: float
top_10_pct_share: float
top_1_pct_share: float


@pytest.fixture(scope="module")
def uk_model_version():
"""Return the installed UK model version, loaded once for this module."""
return _country_module("uk").model


def _uk_frames(
incomes: Sequence[float],
weights: Sequence[float],
household_ids: Sequence[int],
) -> dict[str, pd.DataFrame]:
"""Return stored UK frames with one person and benefit unit per household."""
household_id_column = list(household_ids)
return {
"person": pd.DataFrame(
{
"person_id": household_id_column,
"person_household_id": household_id_column,
"person_benunit_id": household_id_column,
"person_weight": list(weights),
}
),
"benunit": pd.DataFrame(
{"benunit_id": household_id_column, "benunit_weight": list(weights)}
),
"household": pd.DataFrame(
{
"household_id": household_id_column,
"household_weight": list(weights),
INCOME_VARIABLE: list(incomes),
}
),
}


def _service_inequality(
frames: dict[str, pd.DataFrame], uk_model_version: object
) -> InequalityValues:
"""Return the inequality output the service reports for these stored frames.

Rebuilds the dataset and the stand-in simulation as Stage 12's aggregation
does, runs the calculation the UK ``economic_impact_analysis`` runs for
each simulation, and reads the baseline values ``build_inequality``
reports.
"""
dataset = _dataset_from_frames(frames, country="uk", year=2026)
simulation = PrecomputedSimulation(
dataset=dataset, tax_benefit_model_version=uk_model_version
)
simulation.output_dataset = dataset
inequality = calculate_uk_inequality(simulation)
output = build_inequality(
SimpleNamespace(baseline_inequality=inequality, reform_inequality=inequality)
)
return InequalityValues(
gini=output.gini.baseline,
top_10_pct_share=output.top_10_pct_share.baseline,
top_1_pct_share=output.top_1_pct_share.baseline,
)


@pytest.mark.parametrize(
(
"first_copy_weight",
"second_copy_weight",
"top_10_copy_weight",
"top_1_copy_weight",
),
[
# Light copies first: the cumulative weight passes 99 at the seventh
# heavy copy (101), so four heavy copies (weight 12) are in the top
# 10%, and the last heavy copy (weight 3) is the top 1%.
pytest.param(LIGHT_COPY_WEIGHT, HEAVY_COPY_WEIGHT, 12.0, 3.0, id="light-first"),
# Heavy copies first: the last heavy copy (100) and the ten light
# copies (weight 13) are in the top 10%, and the last two light copies
# (109 and 110, weight 2) are the top 1%.
pytest.param(HEAVY_COPY_WEIGHT, LIGHT_COPY_WEIGHT, 13.0, 2.0, id="heavy-first"),
],
)
def test_top_income_shares_count_tied_households_in_row_order(
uk_model_version: object,
first_copy_weight: float,
second_copy_weight: float,
top_10_copy_weight: float,
top_1_copy_weight: float,
) -> None:
copy_count = 2 * COPIES_PER_WEIGHT
frames = _uk_frames(
incomes=[POORER_INCOME] + [RICHER_INCOME] * copy_count,
weights=[POORER_WEIGHT]
+ [first_copy_weight] * COPIES_PER_WEIGHT
+ [second_copy_weight] * COPIES_PER_WEIGHT,
household_ids=range(1, copy_count + 2),
)

reported = _service_inequality(frames, uk_model_version)

assert reported.top_10_pct_share == pytest.approx(
top_10_copy_weight * RICHER_INCOME / TOTAL_INCOME, rel=1e-12
)
assert reported.top_1_pct_share == pytest.approx(
top_1_copy_weight * RICHER_INCOME / TOTAL_INCOME, rel=1e-12
)


@pytest.mark.parametrize("seed", range(10))
def test_rows_in_id_order_give_the_values_of_rows_ranked_in_row_order(
uk_model_version: object, seed: int
) -> None:
random_generator = np.random.default_rng(seed)
frames = _uk_frames(
incomes=random_generator.choice(
SEEDED_INCOME_LEVELS, size=SEEDED_HOUSEHOLD_COUNT
).tolist(),
weights=random_generator.uniform(
0.5, 50.0, size=SEEDED_HOUSEHOLD_COUNT
).tolist(),
household_ids=range(1, SEEDED_HOUSEHOLD_COUNT + 1),
)
# The same households listed by income, with equal incomes kept in
# household_id order: what ranking the rows in row order gives.
ranked_households = frames["household"].sort_values(INCOME_VARIABLE, kind="stable")
ranked_frames = _uk_frames(
incomes=ranked_households[INCOME_VARIABLE].tolist(),
weights=ranked_households["household_weight"].tolist(),
household_ids=ranked_households["household_id"].tolist(),
)

reported = _service_inequality(frames, uk_model_version)
ranked_in_row_order = _service_inequality(ranked_frames, uk_model_version)

# The Gini is summed over the ranked households only, so it is exactly the
# same. Each share divides by the total income summed in the order the
# rows are given, which differs between the two lists in the last bits; a
# different ranking of tied households at a cutoff moves a share by about
# 1e-4 relative or more.
assert reported.gini == ranked_in_row_order.gini
assert reported.top_10_pct_share == pytest.approx(
ranked_in_row_order.top_10_pct_share, rel=1e-12
)
assert reported.top_1_pct_share == pytest.approx(
ranked_in_row_order.top_1_pct_share, rel=1e-12
)
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,9 @@ def test_the_installed_bundle_routes_area_regions_to_the_dense_dataset() -> None
assert uk_area_regions_routed() is True
assert uk_area_regions_routed() is area_regions_routed_to_local_release()
assert isinstance(revision, str)
assert revision.startswith("microcosm-uk-2024-25-dense-")
# Since .py 6.20.1 the UK release pins each file in Microcosm's build
# folders to the Hugging Face commit that published it.
assert re.fullmatch(r"[0-9a-f]{40}", revision)
assert revision == get_release_manifest("uk").datasets[name].revision


Expand Down
22 changes: 11 additions & 11 deletions projects/policyengine-simulation-executor/uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading