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/4378.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Stored UK reports read their tax and benefit budget figures from the `gov_tax` and `gov_spending` rows the simulation service writes from PolicyEngine/policyengine-sim-api#1171, which count employer National Insurance, and fall back to `household_tax` and `household_benefits` for reports stored before it.
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,10 @@
- ``budget`` from ``budget_summary``'s household totals: the tax, benefit and
US state income tax changes, the baseline net income and the household
count. ``budgetary_impact`` is tax minus benefits, and a country with no
state income tax row reports 0.
state income tax row reports 0. A UK report's tax and benefit rows are
``gov_tax`` and ``gov_spending``, or ``household_tax`` and
``household_benefits`` in one stored before the simulation service
renamed them (``BUDGET_TOTAL_VARIABLES``).
- ``detailed_budget`` from ``program_statistics``, one program per row.
- ``decile`` and ``wealth_decile`` from ``decile_impacts``: income deciles
name no ranking variable, wealth deciles ``household_wealth_decile``. The
Expand Down Expand Up @@ -74,7 +77,7 @@
from policyengine_api.spm import SPMComparisonProvenance

if TYPE_CHECKING:
from collections.abc import Iterable, Sequence
from collections.abc import Iterable, Mapping, Sequence
from uuid import UUID

from pydantic import JsonValue
Expand Down Expand Up @@ -114,6 +117,17 @@
"Gain more than 5%": "gain_more_than_5pct",
}
STATE_INCOME_TAX_VARIABLE = "household_state_income_tax"
# The budget summary rows each country's tax and benefit figures come from, as
# (tax, benefits), the current naming first. The simulation service names each
# row after the variable its figure totals. Since
# PolicyEngine/policyengine-sim-api#1171 a UK report's are the model's
# government accounts, gov_tax and gov_spending, which count employer National
# Insurance; UK reports stored before it hold household_tax and
# household_benefits, as every other country's do.
HOUSEHOLD_BUDGET_TOTAL_VARIABLES = ("household_tax", "household_benefits")
BUDGET_TOTAL_VARIABLES: dict[str, tuple[tuple[str, str], ...]] = {
"uk": (("gov_tax", "gov_spending"), HOUSEHOLD_BUDGET_TOTAL_VARIABLES),
}
# The Census FIPS code of each state and the District of Columbia, which a
# district row stores in place of the state's abbreviation.
US_STATE_ABBREVIATIONS_BY_FIPS = {
Expand Down Expand Up @@ -280,8 +294,11 @@ def figure(variable: str, column: Literal["change", "baseline_total"]) -> float:
raise EconomyResultUnreadableError(msg)
return _figure(getattr(row, column), name=f"{variable} {column}")

tax = figure("household_tax", "change")
benefits = figure("household_benefits", "change")
tax_variable, benefit_variable = _budget_total_variables(
country_id, household_totals
)
tax = figure(tax_variable, "change")
benefits = figure(benefit_variable, "change")
state_income_tax = (
figure(STATE_INCOME_TAX_VARIABLE, "change")
if country_id == "us" or STATE_INCOME_TAX_VARIABLE in household_totals
Expand All @@ -297,6 +314,24 @@ def figure(variable: str, column: Literal["change", "baseline_total"]) -> float:
)


def _budget_total_variables(
country_id: str, household_totals: Mapping[str, BudgetSummaryRow]
) -> tuple[str, str]:
"""Return the rows a report's tax and benefit figures come from.

That is the first of the country's namings whose tax row the report
holds. A report holding none reads the current naming, so the error names
the row it lacks.
"""
namings = BUDGET_TOTAL_VARIABLES.get(
country_id, (HOUSEHOLD_BUDGET_TOTAL_VARIABLES,)
)
return next(
(naming for naming in namings if naming[0] in household_totals),
namings[0],
)


def _detailed_budget(rows: EconomyResultRows) -> dict[str, ProgramBudget]:
return {
row.program_name: ProgramBudget(
Expand Down
17 changes: 14 additions & 3 deletions tests/fixtures/economy_results.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,11 @@
its rows is tested against the same mapping. Its ``withheld_area_codes`` rows
follow the writer as PolicyEngine/policyengine-sim-api#1068 changes it
(``46c38f07``): one row per code a result's ``constituency_withheld_codes``
and ``local_authority_withheld_codes`` list. A result's ``cliff_impact`` is
and ``local_authority_withheld_codes`` list. Its budget rows follow the
writer as PolicyEngine/policyengine-sim-api#1171 changes it (``a1643ae3``): a
UK report's tax and benefit rows are ``gov_tax`` and ``gov_spending``; the
golden rows keep the earlier ``household_tax`` and ``household_benefits``.
A result's ``cliff_impact`` is
the one exception: the four cliff columns that writer stored on the report
run are left out, since revision 4e30076d4b9f drops them, and it becomes a
succeeded ``cliff_impacts`` row for each side's simulation run, the rows API
Expand Down Expand Up @@ -485,9 +489,16 @@ def _labor_supply_decile_rows(
def _budget_rows(
output: dict[str, Any], keys: dict[str, Any], country: str
) -> list[dict[str, Any]]:
# As PolicyEngine/policyengine-sim-api#1171 names them: a UK report's tax
# and benefit rows are the government accounts it totals.
tax, benefits = (
("gov_tax", "gov_spending")
if country == "uk"
else ("household_tax", "household_benefits")
)
figures = (
("tax_revenue_impact", "household_tax", "change"),
("benefit_spending_impact", "household_benefits", "change"),
("tax_revenue_impact", tax, "change"),
("benefit_spending_impact", benefits, "change"),
("state_tax_revenue_impact", "household_state_income_tax", "change"),
("baseline_net_income", "household_net_income", "baseline_total"),
("households", "household_weight", "baseline_total"),
Expand Down
73 changes: 73 additions & 0 deletions tests/unit/v2/test_economy_result_rebuild.py
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,79 @@ def test_a_uk_result_without_a_state_income_tax_row_reports_none_collected() ->
)


# A UK report's tax and benefit rows, by the names the simulation service gave
# them before PolicyEngine/policyengine-sim-api#1171.
EARLIER_UK_BUDGET_NAMES = {
"gov_tax": "household_tax",
"gov_spending": "household_benefits",
}


def _renamed_uk_budget_rows(rows: EconomyResultRows) -> tuple[Any, ...]:
"""Return a UK report's tax and benefit rows by their earlier names."""
return tuple(
row.model_copy(
update={"variable_name": EARLIER_UK_BUDGET_NAMES[row.variable_name]}
)
for row in rows.budget_summary
if row.variable_name in EARLIER_UK_BUDGET_NAMES
)


def test_a_uk_result_reads_its_tax_and_benefits_from_the_government_accounts() -> None:
output = uk_economy_result()
rows = stored_rows(output, country="uk")

stored_names = {row.variable_name for row in rows.budget_summary}
assert {"gov_tax", "gov_spending"} <= stored_names
assert not {"household_tax", "household_benefits"} & stored_names
budget = result_transformations.economy_result(rows).budget
assert budget.model_dump(mode="json") == output["budget"]


def test_a_uk_result_stored_before_the_rename_reads_its_household_rows() -> None:
output = uk_economy_result()
rows = stored_rows(output, country="uk")
earlier = replace(
rows,
budget_summary=(
*(
row
for row in rows.budget_summary
if row.variable_name not in EARLIER_UK_BUDGET_NAMES
),
*_renamed_uk_budget_rows(rows),
),
)

budget = result_transformations.economy_result(earlier).budget
assert budget.model_dump(mode="json") == output["budget"]


def test_a_uk_result_holding_both_namings_reads_the_government_accounts() -> None:
output = uk_economy_result()
rows = stored_rows(output, country="uk")
household_rows = tuple(
row.model_copy(update={"change": row.change + 1_000.0})
for row in _renamed_uk_budget_rows(rows)
)
both = replace(rows, budget_summary=(*rows.budget_summary, *household_rows))

budget = result_transformations.economy_result(both).budget
assert budget.model_dump(mode="json") == output["budget"]


def test_a_uk_result_without_its_tax_row_is_unreadable_and_names_gov_tax() -> None:
rows = _without(
stored_rows(uk_economy_result(), country="uk"),
"budget_summary",
lambda row: row.variable_name != "gov_tax",
)

with pytest.raises(EconomyResultUnreadableError, match="no gov_tax row"):
result_transformations.economy_result(rows)


def test_an_intra_decile_breakdown_without_rows_has_empty_categories() -> None:
rows = stored_rows(us_economy_result(), country="us")
rows = replace(
Expand Down
Loading