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/1170.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
The UK budget headline now totals the government's accounts instead of `household_tax` and `household_benefits`. Its tax is `gov_tax`, which counts employer National Insurance: a cut in the employer NI rate showed as a saving because `household_tax` saw only the extra tax on the higher pay the model passes the cut into. Its spending is `household_benefits` plus the two terms the model's `gov_spending` adds to it, the Lifetime ISA bonus and `other_public_spending_budget_change`. UK reports store their tax and benefit budget rows as `gov_tax` and `gov_spending`.
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

from types import MappingProxyType
from typing import Generic, Literal, TypeVar

from pydantic import BaseModel, ConfigDict, Field, RootModel
Expand Down Expand Up @@ -41,6 +42,35 @@ class BudgetaryImpact(MacroOutputModel):

BudgetaryOutput = BudgetaryImpact

# The household variables whose reform-minus-baseline totals are a country's
# ``tax_revenue_impact`` and ``benefit_spending_impact``. The UK's are
# policyengine-uk's government accounts, whose difference is its
# ``gov_balance``. Its ``household_tax`` holds only the taxes households pay,
# so it leaves out employer National Insurance: under the model's default
# incidence an employer NI change moves gross pay, and ``household_tax`` sees
# only the income tax and employee NI on that pay change, which has the
# opposite sign to the change in receipts. The benefit figure is the
# government's spending, which the executor totals from its terms
# (``UK_SPENDING_TERMS``) because ``gov_spending`` leaves out the benefit
# uprating reforms.
HOUSEHOLD_BUDGET_TOTAL_VARIABLES = ("household_tax", "household_benefits")
BUDGET_TOTAL_VARIABLES = MappingProxyType(
{
"us": HOUSEHOLD_BUDGET_TOTAL_VARIABLES,
"uk": ("gov_tax", "gov_spending"),
}
)


def budget_total_variables(country: str) -> tuple[str, str]:
"""Return the household variables a country's tax and benefit figures total.

The pair is (tax revenue, benefit spending). A country without an entry
in ``BUDGET_TOTAL_VARIABLES`` totals ``household_tax`` and
``household_benefits``.
"""
return BUDGET_TOTAL_VARIABLES.get(country.lower(), HOUSEHOLD_BUDGET_TOTAL_VARIABLES)


class DetailedBudgetProgramOutput(MacroOutputModel):
"""Baseline and reform totals for one program.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,10 @@
from typing import TYPE_CHECKING, Any, Literal, NamedTuple
from uuid import uuid4

from policyengine_simulation_contract.macro_output import SingleYearMacroOutput
from policyengine_simulation_contract.macro_output import (
SingleYearMacroOutput,
budget_total_variables,
)
from policyengine_simulation_persistence.result_tables import (
BudgetSummary,
CongressionalDistrictImpact,
Expand Down Expand Up @@ -56,7 +59,10 @@

# The household variable each headline budget figure totals, and the column
# its figure goes in. ``budgetary_impact`` is tax minus benefits, as the
# economy output computes it, so it needs no row of its own.
# economy output computes it, so it needs no row of its own. The tax and
# benefit figures total the country's ``budget_total_variables``, which
# replace the names here where they differ: the UK's are ``gov_tax`` and
# ``gov_spending``.
BUDGET_FIGURES = (
("tax_revenue_impact", "household_tax", "change"),
("benefit_spending_impact", "household_benefits", "change"),
Expand Down Expand Up @@ -409,14 +415,21 @@ def _budget_rows(
) -> tuple[dict[str, Any], ...]:
"""Return the headline budget figures; state income tax only for the US.

Today's output reports 0.0 state income tax for a country without it, so a
reader without that row reports 0.0 again.
Each row names the variable its figure totals, so a UK report's tax and
benefit rows are ``gov_tax`` and ``gov_spending``. Today's output reports
0.0 state income tax for a country without it, so a reader without that
row reports 0.0 again.
"""
tax_variable, benefit_variable = budget_total_variables(country)
variables = {
"tax_revenue_impact": tax_variable,
"benefit_spending_impact": benefit_variable,
}
return tuple(
{
"id": uuid4(),
**keys,
"variable_name": variable,
"variable_name": variables.get(figure, variable),
"entity": "household",
column: getattr(economy.budget, figure),
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
uk_output_with_withheld_codes,
us_output_with_every_part,
)
from policyengine_simulation_contract.macro_output import budget_total_variables
from policyengine_simulation_contract.stage12_execution import ReportRunIds
from policyengine_simulation_persistence import CliffImpact
from policyengine_simulation_persistence.result_tables import BudgetSummary
Expand Down Expand Up @@ -100,13 +101,15 @@ def _rebuilt_district(row):
return f"{state}-{number:02d}"


def _rebuilt_budget(seeder, report_run_id):
def _rebuilt_budget(seeder, report_run_id, country="us"):
rows = {
row["variable_name"]: row
for row in seeder.rows("budget_summary", report_run_id=report_run_id)
}
tax = rows["household_tax"]["change"]
benefits = rows["household_benefits"]["change"]
# Each country's tax and benefit rows name the variables they total.
tax_variable, benefit_variable = budget_total_variables(country)
tax = rows[tax_variable]["change"]
benefits = rows[benefit_variable]["change"]
# Only the US models state income tax; today's output reports 0.0 elsewhere.
state_tax = rows.get("household_state_income_tax", {"change": 0.0})["change"]
return {
Expand Down Expand Up @@ -421,12 +424,17 @@ def test_the_uk_output_uses_its_own_poverty_types_and_wealth_deciles(
rebuilt = _rebuilt_deciles(rows)
assert rebuilt["average"] == output[part]["average"]
assert rebuilt["relative"] == pytest.approx(output[part]["relative"], rel=1e-12)
assert "household_state_income_tax" not in {
budget_variables = {
row["variable_name"]
for row in seeder.rows("budget_summary", report_run_id=run_ids.report_run_id)
}
assert "household_state_income_tax" not in budget_variables
# The UK's tax and benefit figures total the model's government accounts,
# which count employer National Insurance; household_tax does not.
assert {"gov_tax", "gov_spending"} <= budget_variables
assert not {"household_tax", "household_benefits"} & budget_variables
assert (
_rebuilt_budget(seeder, run_ids.report_run_id)
_rebuilt_budget(seeder, run_ids.report_run_id, country="uk")
== (uk_economy_output()["budget"])
)
(inequality,) = seeder.rows(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
import math
from typing import TYPE_CHECKING

from policyengine_simulation_contract.macro_output import budget_total_variables

from policyengine_simulation_executor.simulation_macro_output import (
BudgetaryImpact,
DetailedBudgetOutput,
Expand All @@ -28,6 +30,20 @@
# households in the UK 2023).
MAX_PLAUSIBLE_HOUSEHOLDS = {"us": 2e8, "uk": 6e7}

# The terms a UK report's ``gov_spending`` row totals, with the entity each is
# on. policyengine-uk's ``gov_spending`` leaves out what the benefit uprating
# reforms pay (``gov.contrib.benefit_uprating``), which ``household_benefits``
# counts, so a benefit uprating reform would cost nothing. Until it counts them,
# this totals the same spending itself: the household benefits, plus the two
# terms ``gov_spending`` adds to them. A test checks that those are all it
# adds, so once ``gov_spending`` counts the uprating this is ``gov_spending``
# and can read it instead.
UK_SPENDING_TERMS = (
("household", "household_benefits"),
("person", "lifetime_isa_bonus"),
("household", "other_public_spending_budget_change"),
)


class ImplausibleEntityCountError(ValueError):
"""A published entity count is negative, not finite or above its bound."""
Expand Down Expand Up @@ -85,22 +101,58 @@ def _require_plausible_households(country: str, households: float) -> None:
raise ImplausibleEntityCountError(msg)


def configure_budget_total_variables(country: str, *simulations: Simulation) -> None:
"""Add the UK's budget totals to each simulation's output variables.

Other countries total ``household_tax`` and ``household_benefits``, which
are policyengine's default outputs. The UK totals ``gov_tax`` and
``UK_SPENDING_TERMS``, of which only ``household_benefits`` is a default
output. Call this before the simulations run (``ensure()``), as
policyengine's own ``configure_budgetary_impact_variables`` is called for
the US.
"""
if country.lower() != "uk":
return
from policyengine.outputs.extra_variables import ( # noqa: PLC0415 # policyengine stays out of this module's import-time imports
add_extra_variables,
)

extras: dict[str, list[str]] = {"household": ["gov_tax"]}
for entity, variable in UK_SPENDING_TERMS:
if variable != "household_benefits":
extras.setdefault(entity, []).append(variable)
for simulation in simulations:
add_extra_variables(simulation, extras)


def build_budgetary_impact(
country: str, baseline: Simulation, reform: Simulation
) -> BudgetaryImpact:
"""Compute headline budget figures from household tax and benefit changes.
"""Compute headline budget figures from the country's tax and benefit totals.

``tax_revenue_impact`` and ``benefit_spending_impact`` are the changes in
the household variables ``budget_total_variables`` names for the country:
``household_tax`` and ``household_benefits`` for the US. For the UK, they
are the model's government accounts: ``gov_tax``, which counts employer
National Insurance, and the government's spending (``UK_SPENDING_TERMS``).
``budgetary_impact`` is the tax revenue change minus the benefit spending
change. State income tax is only modelled for the US; elsewhere its impact
is 0.0. A household count outside the country's plausible range raises
``ImplausibleEntityCountError``.
"""
tax_variable, benefit_variable = budget_total_variables(country)
tax_revenue_impact = _change_output_variable(
baseline, reform, "household_tax", entity="household"
)
benefit_spending_impact = _change_output_variable(
baseline, reform, "household_benefits", entity="household"
baseline, reform, tax_variable, entity="household"
)
if country.lower() == "uk":
benefit_spending_impact = sum(
_change_output_variable(baseline, reform, variable, entity=entity)
for entity, variable in UK_SPENDING_TERMS
)
else:
benefit_spending_impact = _change_output_variable(
baseline, reform, benefit_variable, entity="household"
)
state_tax_revenue_impact = (
_change_output_variable(
baseline,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@
parse_year,
wrapper_policy,
)
from policyengine_simulation_executor.simulation_output_budget import (
configure_budget_total_variables,
)
from policyengine_simulation_executor.simulation_output_builder import (
SimulationOutputBuilder,
)
Expand Down Expand Up @@ -610,6 +613,8 @@ def _run_simulation_impl_core(
policy=reform_policy,
region=region_resolution,
)
# Before either runs: the UK's budget totals are not default outputs.
configure_budget_total_variables(country, baseline, reform)

_report_calculation_start(baseline, progress, JobStage.BASELINE)
_report_calculation_start(reform, progress, JobStage.REFORM)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@

from policyengine.core.scoping_strategy import RegionGroupStrategy

from policyengine_simulation_executor.simulation_output_budget import (
configure_budget_total_variables,
)
from policyengine_simulation_executor.stage12_cache.levels import (
BaselineScope,
BaselineTarget,
Expand Down Expand Up @@ -167,7 +170,12 @@ def uk_level_of(run: RunScope) -> DatasetLevel | None:


def _prepare_uk_baseline_outputs(baseline: Simulation) -> None:
"""Add nothing: UK analyses request no extra baseline outputs."""
"""Add the budget totals every UK request adds before ``ensure()``.

A precomputed baseline must carry them, or every request would fail the
artifact's column check and recompute.
"""
configure_budget_total_variables(UK, baseline)


def uk_prebuilt() -> CountryPrebuilt:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@
)
from policyengine_simulation_observability.stages import Stage

from policyengine_simulation_executor.simulation_output_budget import (
configure_budget_total_variables,
)
from policyengine_simulation_executor.uk_local_authority_metadata import (
UK_AREA_DATASET_COLUMNS,
uk_area_codes_required,
Expand Down Expand Up @@ -199,6 +202,7 @@ def _configure_country_outputs(
)

configure_budgetary_impact_variables(baseline, reform)
configure_budget_total_variables(country, baseline, reform)
return labor_supply_active


Expand Down
Loading
Loading