From 0f5fc4a197f00c93b11507724228a0fbb3eab427 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:57:40 +0000 Subject: [PATCH 1/5] Give household situations no share of national totals unless one is set MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit shareholding, consumption_shareholding and the formulas that copy them took their weighted branch whenever a simulation held a dataset, which every policyengine_uk.Simulation(situation=...) has done since #1296. A household situation then divided its own key by itself and took every UK total: with £50,000 of pension wealth, all UK business rates and corporate SDLT, and a household_net_income of about -£40.77bn (#2896). - The weighted branches run only in simulations built from data (built_from_data), and give no share where the weighted total is 0. A household situation takes 0 unless the share is set as an input. - corporate_land_value, consumer_incident_tax_revenue_change and both employer NI responses read shareholding and consumption_shareholding rather than their own copies of the shares. Values on data are unchanged. - The employer NI responses' guard, which never fired, and the three public spending changes now use built_from_data, so situations take none of them; the spending changes' unreachable national branch goes, and the decile uses its fixed bounds in situations. - carbon_tax reads the published sector emissions in a situation, which matter only where the situation sets shareholding. - household.wealth.national_balance_sheet, read only by the old fallback, goes with its uprating-test exception. Co-Authored-By: Claude Opus 5.5 --- changelog.d/2896.fixed.md | 1 + changelog.d/2896.removed.md | 1 + policyengine_uk/data/fiscal_partition.yaml | 8 +- .../wealth/national_balance_sheet.yaml | 16 -- .../tests/test_corporate_land_value.py | 235 +++++++++-------- .../tests/test_population_shares.py | 244 ++++++++++++++++++ .../test_sdlt_counted_once_properties.py | 49 ++-- .../tests/test_september_cpi_uprating.py | 14 +- .../tests/test_weighted_incidence.py | 37 ++- policyengine_uk/utils/household_subset.py | 2 - .../consumer_incident_tax_revenue_change.py | 15 +- .../policyengine/education_budget_change.py | 10 +- .../employer_ni_response_capital_incidence.py | 32 +-- ...employer_ni_response_consumer_incidence.py | 33 ++- .../contrib/policyengine/nhs_budget_change.py | 10 +- .../other_public_spending_budget_change.py | 10 +- ...dget_change_ons_household_income_decile.py | 3 +- .../contrib/ubi_center/carbon_tax.py | 22 +- .../consumption/consumption_share.py | 22 +- .../household/wealth/corporate_land_value.py | 22 +- .../household/wealth/shareholding.py | 27 +- 21 files changed, 543 insertions(+), 270 deletions(-) create mode 100644 changelog.d/2896.fixed.md create mode 100644 changelog.d/2896.removed.md delete mode 100644 policyengine_uk/parameters/household/wealth/national_balance_sheet.yaml create mode 100644 policyengine_uk/tests/test_population_shares.py diff --git a/changelog.d/2896.fixed.md b/changelog.d/2896.fixed.md new file mode 100644 index 0000000000..d146df283e --- /dev/null +++ b/changelog.d/2896.fixed.md @@ -0,0 +1 @@ +A household situation no longer takes the whole UK total of business rates, corporate Stamp Duty Land Tax, corporate land and the other amounts shared out by shareholding, consumption_shareholding or income decile; whatever its weight or axes, it takes no share unless one is set. diff --git a/changelog.d/2896.removed.md b/changelog.d/2896.removed.md new file mode 100644 index 0000000000..92be009fae --- /dev/null +++ b/changelog.d/2896.removed.md @@ -0,0 +1 @@ +Removed the household financial net worth parameter (household.wealth.national_balance_sheet), whose only reader was the shareholding fallback for household situations. diff --git a/policyengine_uk/data/fiscal_partition.yaml b/policyengine_uk/data/fiscal_partition.yaml index e8507cb9e4..c8fb1103fb 100644 --- a/policyengine_uk/data/fiscal_partition.yaml +++ b/policyengine_uk/data/fiscal_partition.yaml @@ -818,10 +818,16 @@ overlap_guards: property: The level is only in gov_tax; the response incidence is only in household_tax. - id: corporate_incidence_allocations kind: shared_allocation_key - heads: [business_rates, sdlt_corporate, corporate_incident_tax_change, carbon_tax, land_value_tax] + heads: [business_rates, sdlt_corporate, corporate_incident_tax_change, carbon_tax, land_value_tax, employer_nics_response_capital] property: >- Each allocates a different receipt by shareholding; none reads another. corporate_tax_incidence sums two of them and is excluded. + - id: consumer_incidence_allocations + kind: shared_allocation_key + heads: [consumer_incident_tax_change, employer_nics_response_consumer] + property: >- + Each allocates a different amount by consumption_shareholding; neither + reads the other. - id: private_school_vat_level_and_change kind: level_and_change heads: [private_school_vat, private_school_vat_change] diff --git a/policyengine_uk/parameters/household/wealth/national_balance_sheet.yaml b/policyengine_uk/parameters/household/wealth/national_balance_sheet.yaml deleted file mode 100644 index 24dceb5dc7..0000000000 --- a/policyengine_uk/parameters/household/wealth/national_balance_sheet.yaml +++ /dev/null @@ -1,16 +0,0 @@ -description: ONS National Balance Sheet statistics on wealth. -household: - metadata: - uprating: gov.economic_assumptions.indices.obr.per_capita.gdp - financial_net_worth: - values: - 2019-01-01: 4_556_770_000_000 - 2020-01-01: 4_818_898_000_000 - 2021-01-01: 5_327_153_000_000 - metadata: - label: Total financial wealth -metadata: - unit: currency-GBP - reference: - - title: ONS National Balance Sheet - href: https://www.ons.gov.uk/economy/nationalaccounts/uksectoraccounts/datasets/nationalbalancesheet diff --git a/policyengine_uk/tests/test_corporate_land_value.py b/policyengine_uk/tests/test_corporate_land_value.py index 6abb0ad51d..94bbcd10c8 100644 --- a/policyengine_uk/tests/test_corporate_land_value.py +++ b/policyengine_uk/tests/test_corporate_land_value.py @@ -1,42 +1,70 @@ -from policyengine_uk import Simulation +"""Corporate land value is the household's shareholding of the land UK +corporations hold. + +Shares sum to one only over a population, so the allocation tests build small +datasets. A household situation has no population to take a share of: it +holds no corporate land unless shareholding is set (policyengine-uk#2896). +""" + +import pandas as pd import pytest +from policyengine_uk import Simulation +from policyengine_uk.data import UKSingleYearDataset + +YEAR = 2025 -def test_corporate_land_value_matches_aggregate_for_weighted_dataset(): - sim = Simulation( - situation={ - "people": { - "person_1": {"age": {2025: 40}}, - "person_2": {"age": {2025: 50}}, - }, - "benunits": { - "benunit_1": {"members": ["person_1"]}, - "benunit_2": {"members": ["person_2"]}, - }, - "households": { - "household_1": { - "members": ["person_1"], - "corporate_wealth": {2025: 100_000}, - "household_weight": {2025: 2}, - }, - "household_2": { - "members": ["person_2"], - "corporate_wealth": {2025: 300_000}, - "household_weight": {2025: 1}, - }, - }, - } - ) - corporate_land_value = sim.calculate( - "corporate_land_value", map_to="household", period=2025 +def dataset_simulation(households, people=None, reform=None): + """A simulation built from data, one person per household.""" + n = len(households) + people = people or [{} for _ in range(n)] + person = { + "person_id": list(range(1, n + 1)), + "person_benunit_id": list(range(1, n + 1)), + "person_household_id": list(range(1, n + 1)), + "age": [40 + 10 * i for i in range(n)], + } + for name in sorted(set().union(*people)): + person[name] = [p.get(name, 0) for p in people] + household = { + "household_id": list(range(1, n + 1)), + # Columns dataset uprating reads. + "region": ["LONDON"] * n, + "council_tax": [0.0] * n, + "rent": [0.0] * n, + "tenure_type": ["OWNED_OUTRIGHT"] * n, + "household_owns_tv": [False] * n, + } + for name in sorted(set().union(*households)): + household[name] = [h.get(name, 0) for h in households] + return Simulation( + dataset=UKSingleYearDataset( + person=pd.DataFrame(person), + benunit=pd.DataFrame({"benunit_id": list(range(1, n + 1))}), + household=pd.DataFrame(household), + fiscal_year=YEAR, + ), + reform=reform, ) - household_weight = sim.calculate( - "household_weight", map_to="household", period=2025 + + +def aggregate_corporate_land_value(sim): + land = sim.tax_benefit_system.parameters(str(YEAR)).household.wealth.land.value + return land.aggregate_corporate_land_value + + +def test_corporate_land_value_matches_aggregate_for_weighted_dataset(): + sim = dataset_simulation( + [ + {"corporate_wealth": 100_000, "household_weight": 2}, + {"corporate_wealth": 300_000, "household_weight": 1}, + ] ) - aggregate = sim.tax_benefit_system.parameters( - "2025" - ).household.wealth.land.value.aggregate_corporate_land_value + + corporate_land_value = sim.calculate("corporate_land_value", YEAR) + household_weight = sim.calculate("household_weight", YEAR) + aggregate = aggregate_corporate_land_value(sim) assert corporate_land_value[0] == pytest.approx(aggregate * 0.2) assert corporate_land_value[1] == pytest.approx(aggregate * 0.6) @@ -44,25 +72,9 @@ def test_corporate_land_value_matches_aggregate_for_weighted_dataset(): def test_corporate_land_value_is_zero_without_corporate_wealth(): - sim = Simulation( - situation={ - "people": {"person": {"age": {2025: 40}}}, - "benunits": {"benunit": {"members": ["person"]}}, - "households": { - "household": { - "members": ["person"], - "corporate_wealth": {2025: 0}, - "household_weight": {2025: 1}, - } - }, - } - ) - - corporate_land_value = sim.calculate( - "corporate_land_value", map_to="household", period=2025 - ) + sim = dataset_simulation([{"corporate_wealth": 0, "household_weight": 1}]) - assert corporate_land_value[0] == 0 + assert sim.calculate("corporate_land_value", YEAR)[0] == 0 def test_corporate_land_value_key_is_unchanged_by_the_pension_split(): @@ -70,44 +82,27 @@ def test_corporate_land_value_key_is_unchanged_by_the_pension_split(): move corporate land value: the allocation key is corporate_sector_wealth.""" def land_values(household_1: dict, household_2: dict): - sim = Simulation( - situation={ - "people": { - "person_1": {"age": {2025: 40}}, - "person_2": {"age": {2025: 50}}, - }, - "benunits": { - "benunit_1": {"members": ["person_1"]}, - "benunit_2": {"members": ["person_2"]}, - }, - "households": { - "household_1": { - "members": ["person_1"], - "household_weight": {2025: 2}, - **household_1, - }, - "household_2": { - "members": ["person_2"], - "household_weight": {2025: 1}, - **household_2, - }, - }, - } + sim = dataset_simulation( + [ + {"household_weight": 2, **household_1}, + {"household_weight": 1, **household_2}, + ] ) return ( - sim.calculate("corporate_land_value", map_to="household", period=2025), - sim.calculate("shareholding", map_to="household", period=2025), + sim.calculate("corporate_land_value", YEAR), + sim.calculate("shareholding", YEAR), ) folded_land, folded_share = land_values( - {"corporate_wealth": {2025: 100_000}}, - {"corporate_wealth": {2025: 300_000}}, + {"corporate_wealth": 100_000}, + {"corporate_wealth": 300_000}, ) split_land, split_share = land_values( - {"corporate_wealth": {2025: 20_000}, "private_pension_wealth": {2025: 80_000}}, - {"corporate_wealth": {2025: 50_000}, "private_pension_wealth": {2025: 250_000}}, + {"corporate_wealth": 20_000, "private_pension_wealth": 80_000}, + {"corporate_wealth": 50_000, "private_pension_wealth": 250_000}, ) + assert folded_share[0] > 0 assert split_land[0] == pytest.approx(folded_land[0]) assert split_land[1] == pytest.approx(folded_land[1]) assert split_share[0] == pytest.approx(folded_share[0]) @@ -119,54 +114,58 @@ def test_employer_ni_capital_incidence_is_unchanged_by_the_pension_split(): so moving wealth between corporate_wealth and private_pension_wealth must not move any household's incidence.""" reform = { - "gov.contrib.policyengine.employer_ni.employee_incidence": {"2025": 0.5}, - "gov.contrib.policyengine.employer_ni.capital_incidence": {"2025": 0.5}, + "gov.hmrc.national_insurance.class_1.employer_scale[1].rate": { + f"{YEAR}-01-01.{YEAR}-12-31": 0.25 + }, + "gov.contrib.policyengine.employer_ni.employee_incidence": {f"{YEAR}": 0.5}, + "gov.contrib.policyengine.employer_ni.capital_incidence": {f"{YEAR}": 0.5}, } + people = [{"employment_income": 30_000}, {"employment_income": 60_000}] def incidence(household_1: dict, household_2: dict): - sim = Simulation( + sim = dataset_simulation( + [ + {"household_weight": 2, **household_1}, + {"household_weight": 1, **household_2}, + ], + people=people, reform=reform, - situation={ - "people": { - "person_1": { - "age": {2025: 40}, - "employment_income": {2025: 30_000}, - }, - "person_2": { - "age": {2025: 50}, - "employment_income": {2025: 60_000}, - }, - }, - "benunits": { - "benunit_1": {"members": ["person_1"]}, - "benunit_2": {"members": ["person_2"]}, - }, - "households": { - "household_1": { - "members": ["person_1"], - "household_weight": {2025: 2}, - **household_1, - }, - "household_2": { - "members": ["person_2"], - "household_weight": {2025: 1}, - **household_2, - }, - }, - }, - ) - return sim.calculate( - "employer_ni_response_capital_incidence", map_to="household", period=2025 ) + return sim.calculate("employer_ni_response_capital_incidence", YEAR) folded = incidence( - {"corporate_wealth": {2025: 100_000}}, - {"corporate_wealth": {2025: 300_000}}, + {"corporate_wealth": 100_000}, + {"corporate_wealth": 300_000}, ) split = incidence( - {"corporate_wealth": {2025: 20_000}, "private_pension_wealth": {2025: 80_000}}, - {"corporate_wealth": {2025: 50_000}, "private_pension_wealth": {2025: 250_000}}, + {"corporate_wealth": 20_000, "private_pension_wealth": 80_000}, + {"corporate_wealth": 50_000, "private_pension_wealth": 250_000}, ) + assert folded[0] != 0 assert split[0] == pytest.approx(folded[0]) assert split[1] == pytest.approx(folded[1]) + + +def test_situation_holds_corporate_land_only_where_shareholding_is_set(): + def corporate_land(**household): + sim = Simulation( + situation={ + "people": {"person": {"age": {YEAR: 40}}}, + "benunits": {"benunit": {"members": ["person"]}}, + "households": { + "household": { + "members": ["person"], + "corporate_wealth": {YEAR: 300_000}, + **{name: {YEAR: value} for name, value in household.items()}, + } + }, + } + ) + return sim.calculate("corporate_land_value", YEAR)[0], sim + + unset, _ = corporate_land() + set_value, sim = corporate_land(shareholding=1e-6) + + assert unset == 0 + assert set_value == pytest.approx(1e-6 * aggregate_corporate_land_value(sim)) diff --git a/policyengine_uk/tests/test_population_shares.py b/policyengine_uk/tests/test_population_shares.py new file mode 100644 index 0000000000..7be4a0e61a --- /dev/null +++ b/policyengine_uk/tests/test_population_shares.py @@ -0,0 +1,244 @@ +"""A household's share of a national total does not depend on who is simulated. + +Business rates, corporate SDLT, corporate land, carbon tax's corporate part, +the reform lumps borne by capital and by consumers, employer National +Insurance's capital and consumer responses and the three public spending +changes each spread a national total over households by a population key. +A household situation has no population to take a share of, so each is 0 in a +situation, whatever the household's weight and however many axis points it +has, unless the share is set as an input (policyengine-uk#2896). +""" + +import copy + +import numpy as np +import pandas as pd +import pytest + +from policyengine_uk import Simulation +from policyengine_uk.data import UKSingleYearDataset + +YEAR = 2026 + +# The household in policyengine-uk#2896. +ISSUE_HOUSEHOLD = { + "people": {"adult": {"age": {YEAR: 45}, "employment_income": {YEAR: 40_000}}}, + "benunits": {"bu": {"members": ["adult"]}}, + "households": { + "hh": { + "members": ["adult"], + "region": {YEAR: "LONDON"}, + "private_pension_wealth": {YEAR: 50_000}, + } + }, +} + +# A household that holds both keys: corporate-sector wealth and consumption. +HOLDER = copy.deepcopy(ISSUE_HOUSEHOLD) +HOLDER["households"]["hh"].update( + { + "corporate_wealth": {YEAR: 20_000}, + "food_and_non_alcoholic_beverages_consumption": {YEAR: 5_000}, + "transport_consumption": {YEAR: 3_000}, + } +) + +EMPLOYER_NI = { + "gov.hmrc.national_insurance.class_1.employer_scale[1].rate": {YEAR: 0.25}, + "gov.contrib.policyengine.employer_ni.employee_incidence": {YEAR: 0}, +} + +# Each term, with a reform under which a household holding the keys takes a +# non-zero part of it as part of a population. +CASES = { + "shareholding": {}, + "consumption_shareholding": {}, + "corporate_land_value": {}, + "business_rates": {}, + "corporate_sdlt": {}, + "corporate_incident_tax_revenue_change": { + "gov.contrib.policyengine.budget.corporate_incident_tax_change": {YEAR: 1} + }, + "consumer_incident_tax_revenue_change": { + "gov.contrib.policyengine.budget.consumer_incident_tax_change": {YEAR: 1} + }, + # With no consumer incidence, all of the tax is the corporate part. + "carbon_tax": { + "gov.contrib.ubi_center.carbon_tax.rate": {YEAR: 100}, + "gov.contrib.ubi_center.carbon_tax.consumer_incidence": {YEAR: 0}, + }, + # The household owns no land of its own, so its tax is on corporate land. + "LVT": {"gov.contrib.ubi_center.land_value_tax.corporate_rate": {YEAR: 0.01}}, + "employer_ni_response_capital_incidence": EMPLOYER_NI, + "employer_ni_response_consumer_incidence": EMPLOYER_NI, + "nhs_budget_change": {"gov.contrib.policyengine.budget.nhs": {YEAR: 1}}, + "education_budget_change": {"gov.contrib.policyengine.budget.education": {YEAR: 1}}, + "other_public_spending_budget_change": { + "gov.contrib.policyengine.budget.other_public_spending": {YEAR: 1} + }, +} + + +def calculate(sim, variable): + return np.asarray(sim.calculate(variable, YEAR, map_to="household")) + + +def in_situation(situation, variable, reform=None): + return calculate(Simulation(situation=situation, reform=reform or None), variable) + + +def as_population(situation, variable, reform=None): + """The situation's household as a dataset in which it stands for ten million + households, so that its share of each total is small, as in the data. As + the whole UK it would bear every UK total and rank below the deciles.""" + household = situation["households"]["hh"] + adult = situation["people"]["adult"] + dataset = UKSingleYearDataset( + person=pd.DataFrame( + { + "person_id": [1], + "person_benunit_id": [1], + "person_household_id": [1], + **{name: [value[YEAR]] for name, value in adult.items()}, + } + ), + benunit=pd.DataFrame({"benunit_id": [1]}), + household=pd.DataFrame( + { + "household_id": [1], + "household_weight": [1e7], + # Columns dataset uprating reads. + "council_tax": [0.0], + "rent": [0.0], + "tenure_type": ["OWNED_OUTRIGHT"], + "household_owns_tv": [False], + **{ + name: [value[YEAR]] + for name, value in household.items() + if name != "members" + }, + } + ), + fiscal_year=YEAR, + ) + return calculate(Simulation(dataset=dataset, reform=reform or None), variable) + + +def copies(situation, weights): + """The situation's household once per weight, each with that weight.""" + household = situation["households"]["hh"] + adult = situation["people"]["adult"] + out = {"people": {}, "benunits": {}, "households": {}} + for i, weight in enumerate(weights): + out["people"][f"adult_{i}"] = copy.deepcopy(adult) + out["benunits"][f"bu_{i}"] = {"members": [f"adult_{i}"]} + out["households"][f"hh_{i}"] = { + **copy.deepcopy(household), + "members": [f"adult_{i}"], + "household_weight": {YEAR: weight}, + } + return out + + +def test_situation_with_pension_wealth_takes_no_corporate_share(): + """The reproducer in policyengine-uk#2896: one household with pension wealth + was handed every UK total and a household_net_income of about -£40.77bn.""" + sim = Simulation(situation=ISSUE_HOUSEHOLD) + for variable in ["shareholding", "business_rates", "corporate_sdlt"]: + assert calculate(sim, variable) == pytest.approx([0]) + without_pension_wealth = copy.deepcopy(ISSUE_HOUSEHOLD) + del without_pension_wealth["households"]["hh"]["private_pension_wealth"] + assert calculate(sim, "household_net_income") == pytest.approx( + in_situation(without_pension_wealth, "household_net_income") + ) + + # Under a 1% land value tax it pays nothing, since it owns no land. + land_value_tax = {"gov.contrib.ubi_center.land_value_tax.rate": {YEAR: 0.01}} + taxed = Simulation(situation=ISSUE_HOUSEHOLD, reform=land_value_tax) + assert calculate(taxed, "LVT") == pytest.approx([0]) + assert calculate(taxed, "hbai_household_net_income") == pytest.approx( + calculate(sim, "hbai_household_net_income") + ) + + +@pytest.mark.parametrize("variable", sorted(CASES)) +def test_situation_takes_no_share_whatever_its_weight(variable): + reform = CASES[variable] + # As part of a population, the household takes a part of the total. + assert as_population(HOLDER, variable, reform)[0] != 0 + # As situations, households of weight 1, 1,000 and 0 take none. + values = in_situation(copies(HOLDER, [1, 1_000, 0]), variable, reform) + assert values == pytest.approx([0, 0, 0]) + + +@pytest.mark.parametrize("variable", sorted(CASES)) +def test_situation_takes_no_share_at_any_axis_point(variable): + situation = copy.deepcopy(HOLDER) + situation["axes"] = [ + [ + { + "name": "employment_income", + "count": 9, + "min": 0, + "max": 80_000, + "period": YEAR, + } + ] + ] + assert in_situation(situation, variable, CASES[variable]) == pytest.approx( + np.zeros(9) + ) + + +# Synthetic totals make each allocation checkable by hand. +SYNTHETIC_TOTALS = { + "gov.hmrc.business_rates.statistics.revenue.ENGLAND": {YEAR: 100}, + "gov.hmrc.business_rates.statistics.revenue.ENGLAND_CENTRAL_LIST": {YEAR: 0}, + "gov.hmrc.business_rates.statistics.revenue.SCOTLAND": {YEAR: 0}, + "gov.hmrc.business_rates.statistics.revenue.WALES": {YEAR: 0}, + "gov.hmrc.business_rates.statistics.revenue.WALES_CENTRAL_LIST": {YEAR: 0}, + "gov.hmrc.business_rates.statistics.revenue.NORTHERN_IRELAND": {YEAR: 0}, + "gov.hmrc.stamp_duty.statistics.residential.corporate.revenue": {YEAR: 20}, + "gov.hmrc.stamp_duty.statistics.non_residential.corporate.revenue": {YEAR: 30}, + "household.wealth.land.value.aggregate_corporate_land_value": {YEAR: 1_000}, + **CASES["corporate_incident_tax_revenue_change"], + **CASES["consumer_incident_tax_revenue_change"], + **CASES["carbon_tax"], + **EMPLOYER_NI, +} + + +def test_situation_honours_a_set_share(): + situation = copy.deepcopy(HOLDER) + situation["households"]["hh"]["shareholding"] = {YEAR: 1e-6} + situation["households"]["hh"]["consumption_shareholding"] = {YEAR: 2e-6} + sim = Simulation(situation=situation, reform=SYNTHETIC_TOTALS) + + system = sim.tax_benefit_system + sector_emissions = system.parameters(f"{YEAR}-01-01").household.consumption.carbon + uk_emissions = sum( + sector_emissions.emissions[category.replace("_consumption", "")] + for category in system.get_variable("consumption").adds + ) + expected = { + "business_rates": 1e-6 * 100, + "corporate_sdlt": 1e-6 * (20 + 30), + "corporate_land_value": 1e-6 * 1_000, + "corporate_incident_tax_revenue_change": 1e-6 * 1e9, + "carbon_tax": 1e-6 * 100 * uk_emissions, + "consumer_incident_tax_revenue_change": 2e-6 * 1e9, + # Employer NI's total is the simulation's own, so a situation never + # takes a share of it. + "employer_ni_response_capital_incidence": 0, + "employer_ni_response_consumer_incidence": 0, + } + for variable, value in expected.items(): + assert calculate(sim, variable) == pytest.approx([value], rel=1e-5), variable + + +def test_situation_decile_uses_the_fixed_bounds_whatever_the_weight(): + deciles = in_situation( + copies(HOLDER, [1, 1_000, 0]), "pre_budget_change_ons_household_income_decile" + ) + assert deciles[0] == deciles[1] == deciles[2] + assert 1 <= deciles[0] <= 10 diff --git a/policyengine_uk/tests/test_sdlt_counted_once_properties.py b/policyengine_uk/tests/test_sdlt_counted_once_properties.py index 626f885ee2..7bfe871f32 100644 --- a/policyengine_uk/tests/test_sdlt_counted_once_properties.py +++ b/policyengine_uk/tests/test_sdlt_counted_once_properties.py @@ -8,7 +8,9 @@ appear in them exactly once, and ``gov.hmrc.stamp_duty.abolish`` must remove both. -Each example builds a two-household population and simulates it three ways: +Each example builds a two-household dataset and simulates it three ways. It +is built from data because shares of corporate SDLT sum to one only over a +population; a household situation takes none (policyengine-uk#2896). - B: the baseline; - A: with ``gov.hmrc.stamp_duty.abolish`` set; @@ -40,10 +42,12 @@ """ import numpy as np +import pandas as pd from hypothesis import HealthCheck, given, settings from hypothesis import strategies as st from policyengine_uk import Simulation +from policyengine_uk.data import UKSingleYearDataset from policyengine_uk.system import system ALWAYS = "2000-01-01.2100-12-31" @@ -81,28 +85,43 @@ ) -def situation(households: list, year: int) -> dict: - people, benunits, hh = {}, {}, {} - for i, inputs in enumerate(households): - person, benunit = f"person_{i}", f"benunit_{i}" - people[person] = { - "age": {year: 40 + 20 * i}, - "employment_income": {year: inputs["employment_income"]}, +def dataset(households: list, year: int) -> UKSingleYearDataset: + """One person per household, as a dataset for ``year``.""" + ids = list(range(1, len(households) + 1)) + person = pd.DataFrame( + { + "person_id": ids, + "person_benunit_id": ids, + "person_household_id": ids, + "age": [40 + 20 * i for i in range(len(households))], + "employment_income": [inputs["employment_income"] for inputs in households], } - benunits[benunit] = {"members": [person]} - hh[f"household_{i}"] = { - "members": [person], + ) + household = pd.DataFrame( + { + "household_id": ids, + # Columns dataset uprating reads. + "council_tax": [0.0] * len(ids), + "rent": [0.0] * len(ids), + "tenure_type": ["OWNED_OUTRIGHT"] * len(ids), + "household_owns_tv": [False] * len(ids), **{ - name: {year: value} - for name, value in inputs.items() + name: [inputs[name] for inputs in households] + for name in households[0] if name != "employment_income" }, } - return {"people": people, "benunits": benunits, "households": hh} + ) + return UKSingleYearDataset( + person=person, + benunit=pd.DataFrame({"benunit_id": ids}), + household=household, + fiscal_year=year, + ) def simulate(households: list, year: int, reform=None) -> dict: - sim = Simulation(situation=situation(households, year), reform=reform) + sim = Simulation(dataset=dataset(households, year), reform=reform) return { name: np.asarray(sim.calculate(name, year), dtype=np.float64) for name in VARIABLES diff --git a/policyengine_uk/tests/test_september_cpi_uprating.py b/policyengine_uk/tests/test_september_cpi_uprating.py index 1cacbab0d7..4855bb0d4a 100644 --- a/policyengine_uk/tests/test_september_cpi_uprating.py +++ b/policyengine_uk/tests/test_september_cpi_uprating.py @@ -137,16 +137,10 @@ def last_published_year(raw, name): return max(int(value.instant_str[:4]) for value in raw.get_child(name).values_list) -# An older, unrelated omission: the national financial wealth total is meant -# to project by GDP per capita, but its node metadata never reaches this leaf. -# Keep its existing corporate-incidence fallback unchanged in this benefit fix. -# Limit the exception to this exact leaf so new omissions still fail. -KNOWN_UNPROPAGATED_UPRATING = { - ( - "household.wealth.national_balance_sheet.household", - "household.wealth.national_balance_sheet.household.financial_net_worth", - ), -} +# Exceptions, each limited to an exact (node, leaf) pair so that new omissions +# still fail. None remain: the last, the national balance sheet's financial +# wealth total, went with shareholding's fallback (policyengine-uk#2896). +KNOWN_UNPROPAGATED_UPRATING = set() def test_node_uprating_reaches_every_leaf(): diff --git a/policyengine_uk/tests/test_weighted_incidence.py b/policyengine_uk/tests/test_weighted_incidence.py index 6619625342..bb0802e91f 100644 --- a/policyengine_uk/tests/test_weighted_incidence.py +++ b/policyengine_uk/tests/test_weighted_incidence.py @@ -12,9 +12,6 @@ # Synthetic totals make the existing allocation rules independently checkable: # corporate incidence is £150 times shareholding; consumer revenue is £7,000. REFORM = { - "household.wealth.national_balance_sheet.household.financial_net_worth": { - YEAR: 1_000_000, - }, "gov.hmrc.business_rates.statistics.revenue.ENGLAND": {YEAR: 100}, "gov.hmrc.business_rates.statistics.revenue.ENGLAND_CENTRAL_LIST": {YEAR: 0}, "gov.hmrc.business_rates.statistics.revenue.SCOTLAND": {YEAR: 0}, @@ -90,20 +87,21 @@ def incidence_simulation(weights, wealth, consumption, *, dataset=True): @pytest.mark.parametrize( - "variable, expected", + "variable", [ - ("shareholding", [0.01, 0]), - ("consumption_shareholding", [0, 0]), - # The fallback allocates £7,000 over existing aggregate consumption £846bn. - ("consumer_incident_tax_revenue_change", [21 / 846_000, 0]), - ("corporate_tax_incidence", [1.5, 0]), - ("household_tax", [1.5 + 21 / 846_000, 0]), + "shareholding", + "consumption_shareholding", + "consumer_incident_tax_revenue_change", + "corporate_tax_incidence", + "household_tax", ], ) -def test_zero_weight_holder_uses_existing_fallback(variable, expected): +def test_zero_weighted_total_gives_no_share(variable): + # The only holder of either key has no weight, so the weighted totals are + # zero and nobody takes a share (policyengine-uk#2896). sim = incidence_simulation([0, 1], [10_000, 0], [3_000, 0]) - assert sim.calculate(variable, YEAR) == pytest.approx(expected) + assert sim.calculate(variable, YEAR) == pytest.approx([0, 0]) @pytest.mark.parametrize( @@ -139,15 +137,16 @@ def test_zero_values_keep_zero_fallback(variable): @pytest.mark.parametrize( - "variable, expected", + "variable", [ - ("shareholding", [0.01, 0.03]), - ("consumption_shareholding", [0, 0]), - ("consumer_incident_tax_revenue_change", [21 / 846_000, 7 / 846_000]), - ("corporate_tax_incidence", [1.5, 4.5]), + "shareholding", + "consumption_shareholding", + "consumer_incident_tax_revenue_change", + "corporate_tax_incidence", ], ) -def test_situation_keeps_no_dataset_fallback(variable, expected): +def test_situation_takes_no_share(variable): + # A situation has no population to take a share of (policyengine-uk#2896). sim = incidence_simulation([2, 1], [10_000, 30_000], [3_000, 1_000], dataset=False) - assert sim.calculate(variable, YEAR) == pytest.approx(expected) + assert sim.calculate(variable, YEAR) == pytest.approx([0, 0]) diff --git a/policyengine_uk/utils/household_subset.py b/policyengine_uk/utils/household_subset.py index d8715d3ba1..99526551af 100644 --- a/policyengine_uk/utils/household_subset.py +++ b/policyengine_uk/utils/household_subset.py @@ -40,9 +40,7 @@ { "attends_private_school", "carbon_tax", - "consumer_incident_tax_revenue_change", "consumption_shareholding", - "corporate_land_value", "education_budget_change", "employer_ni_response_capital_incidence", "employer_ni_response_consumer_incidence", diff --git a/policyengine_uk/variables/contrib/policyengine/consumer_incident_tax_revenue_change.py b/policyengine_uk/variables/contrib/policyengine/consumer_incident_tax_revenue_change.py index 6ad6d0a1a7..f5d773773d 100644 --- a/policyengine_uk/variables/contrib/policyengine/consumer_incident_tax_revenue_change.py +++ b/policyengine_uk/variables/contrib/policyengine/consumer_incident_tax_revenue_change.py @@ -3,19 +3,20 @@ class consumer_incident_tax_revenue_change(Variable): label = "consumer-incident tax revenue change" + documentation = ( + "A lump-sum revenue change that a reform sets " + "(gov.contrib.policyengine.budget.consumer_incident_tax_change, in " + "£ billion), shared across households by consumption_shareholding. A " + "household situation takes no share unless consumption_shareholding " + "is set." + ) entity = Household definition_period = YEAR value_type = float unit = GBP def formula(household, period, parameters): - consumption = household("consumption", period) - share = consumption / 846e9 - if household.simulation.dataset is not None: - weight = household("household_weight", period) - weighted_total = (consumption * weight).sum() - if weighted_total != 0: - share = consumption / weighted_total + share = household("consumption_shareholding", period) revenue_change = parameters( period ).gov.contrib.policyengine.budget.consumer_incident_tax_change diff --git a/policyengine_uk/variables/contrib/policyengine/education_budget_change.py b/policyengine_uk/variables/contrib/policyengine/education_budget_change.py index 0d2897746b..cd6d86c309 100644 --- a/policyengine_uk/variables/contrib/policyengine/education_budget_change.py +++ b/policyengine_uk/variables/contrib/policyengine/education_budget_change.py @@ -1,4 +1,5 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.data_source import built_from_data class education_budget_change(Variable): @@ -13,6 +14,10 @@ def formula(household, period, parameters): ) if budget_increase == 0: return 0 + if not built_from_data(household.simulation): + # A household situation has no population to share the budget + # over, so it takes none of it. + return 0 decile = household("pre_budget_change_ons_household_income_decile", period) weight = household("household_weight", period) DECILE_INCIDENCE = { @@ -32,10 +37,7 @@ def formula(household, period, parameters): budget_increase_per_decile = { i: budget_increase * DECILE_INCIDENCE[i] for i in range(1, 11) } - if household.simulation.dataset is not None: - households_per_decile = pd.Series(weight).groupby(decile).sum().to_dict() - else: - households_per_decile = {i: 28e5 for i in range(1, 11)} + households_per_decile = pd.Series(weight).groupby(decile).sum().to_dict() # A decile with no weighted households in the data, as in a small # sample, has nobody to receive its share. diff --git a/policyengine_uk/variables/contrib/policyengine/employer_ni/employer_ni_response_capital_incidence.py b/policyengine_uk/variables/contrib/policyengine/employer_ni/employer_ni_response_capital_incidence.py index d50987b399..4c7751596b 100644 --- a/policyengine_uk/variables/contrib/policyengine/employer_ni/employer_ni_response_capital_incidence.py +++ b/policyengine_uk/variables/contrib/policyengine/employer_ni/employer_ni_response_capital_incidence.py @@ -1,8 +1,15 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.data_source import built_from_data class employer_ni_response_capital_incidence(Variable): label = "capital response to employer NI reform" + documentation = ( + "The part of a change in employer National Insurance that falls on " + "capital, shared by each household's shareholding and split equally " + "among its members. The change is the simulation's own total, which " + "a household situation cannot know for the UK, so a situation gets 0." + ) entity = Person definition_period = YEAR value_type = float @@ -11,11 +18,12 @@ class employer_ni_response_capital_incidence(Variable): def formula(person, period, parameters): emp_ni = parameters(period).gov.contrib.policyengine.employer_ni if emp_ni.capital_incidence == 0 or emp_ni.employee_incidence == 1: - # If capital incidence is zero, or if the employee incidence is 100%, then there is no capital incidence.: + # If capital incidence is zero, or if the employee incidence is 100%, then there is no capital incidence. return 0 - if not hasattr(person.simulation, "dataset"): - # In single-household simulations, we can't automatically put revenue into price increases because we don't know the revenue. + if not built_from_data(person.simulation): + # A household situation cannot know how much employers pay across + # the UK, so it takes no share of it. return 0 person_weight = person("person_weight", period) @@ -24,18 +32,6 @@ def formula(person, period, parameters): change_in_employer_cost = employer_cost - baseline_employer_cost amount_paid_by_employers = (person_weight * change_in_employer_cost).sum() - wealth = ( - person.household("corporate_sector_wealth", period) - / person.household.nb_persons() - ) - total_wealth = (wealth * person_weight).sum() - share_of_total_wealth = wealth / total_wealth - - value = ( - amount_paid_by_employers * share_of_total_wealth * emp_ni.capital_incidence - ) - - if total_wealth == 0: - return 0 - - return value + # Each member takes an equal part of the household's share. + share = person.household("shareholding", period) / person.household.nb_persons() + return amount_paid_by_employers * share * emp_ni.capital_incidence diff --git a/policyengine_uk/variables/contrib/policyengine/employer_ni/employer_ni_response_consumer_incidence.py b/policyengine_uk/variables/contrib/policyengine/employer_ni/employer_ni_response_consumer_incidence.py index 629de60fc0..6f731d423f 100644 --- a/policyengine_uk/variables/contrib/policyengine/employer_ni/employer_ni_response_consumer_incidence.py +++ b/policyengine_uk/variables/contrib/policyengine/employer_ni/employer_ni_response_consumer_incidence.py @@ -1,8 +1,16 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.data_source import built_from_data class employer_ni_response_consumer_incidence(Variable): label = "price response to employer NI reform" + documentation = ( + "The part of a change in employer National Insurance that falls on " + "consumers through prices, shared by each household's " + "consumption_shareholding and split equally among its members. The " + "change is the simulation's own total, which a household situation " + "cannot know for the UK, so a situation gets 0." + ) entity = Person definition_period = YEAR value_type = float @@ -14,8 +22,9 @@ def formula(person, period, parameters): # If consumer incidence is zero, or if the employee incidence is 100%, then there is no capital incidence.: return 0 - if not hasattr(person.simulation, "dataset"): - # In single-household simulations, we can't automatically put revenue into price increases because we don't know the revenue. + if not built_from_data(person.simulation): + # A household situation cannot know how much employers pay across + # the UK, so it takes no share of it. return 0 person_weight = person("person_weight", period) @@ -24,19 +33,9 @@ def formula(person, period, parameters): change_in_employer_cost = employer_cost - baseline_employer_cost amount_paid_by_employers = (person_weight * change_in_employer_cost).sum() - consumption = ( - person.household("consumption", period) / person.household.nb_persons() + # Each member takes an equal part of the household's share. + share = ( + person.household("consumption_shareholding", period) + / person.household.nb_persons() ) - total_consumption = (consumption * person_weight).sum() - share_of_total_consumption = consumption / total_consumption - - value = ( - amount_paid_by_employers - * share_of_total_consumption - * emp_ni.consumer_incidence - ) - - if total_consumption == 0: - return 0 - - return value + return amount_paid_by_employers * share * emp_ni.consumer_incidence diff --git a/policyengine_uk/variables/contrib/policyengine/nhs_budget_change.py b/policyengine_uk/variables/contrib/policyengine/nhs_budget_change.py index efb6a71363..de16624718 100644 --- a/policyengine_uk/variables/contrib/policyengine/nhs_budget_change.py +++ b/policyengine_uk/variables/contrib/policyengine/nhs_budget_change.py @@ -1,4 +1,5 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.data_source import built_from_data class nhs_budget_change(Variable): @@ -11,6 +12,10 @@ def formula(household, period, parameters): budget_increase = parameters(period).gov.contrib.policyengine.budget.nhs * 1e9 if budget_increase == 0: return 0 + if not built_from_data(household.simulation): + # A household situation has no population to share the budget + # over, so it takes none of it. + return 0 decile = household("pre_budget_change_ons_household_income_decile", period) weight = household("household_weight", period) DECILE_INCIDENCE = { @@ -31,10 +36,7 @@ def formula(household, period, parameters): budget_increase_per_decile = { i: budget_increase * DECILE_INCIDENCE[i] for i in range(1, 11) } - if household.simulation.dataset is not None: - households_per_decile = pd.Series(weight).groupby(decile).sum().to_dict() - else: - households_per_decile = {i: 28e5 for i in range(1, 11)} + households_per_decile = pd.Series(weight).groupby(decile).sum().to_dict() # A decile with no weighted households in the data, as in a small # sample, has nobody to receive its share. diff --git a/policyengine_uk/variables/contrib/policyengine/other_public_spending_budget_change.py b/policyengine_uk/variables/contrib/policyengine/other_public_spending_budget_change.py index 38612c1439..5c9855ff79 100644 --- a/policyengine_uk/variables/contrib/policyengine/other_public_spending_budget_change.py +++ b/policyengine_uk/variables/contrib/policyengine/other_public_spending_budget_change.py @@ -1,4 +1,5 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.data_source import built_from_data class other_public_spending_budget_change(Variable): @@ -14,6 +15,10 @@ def formula(household, period, parameters): ) if budget_increase == 0: return 0 + if not built_from_data(household.simulation): + # A household situation has no population to share the budget + # over, so it takes none of it. + return 0 decile = household("pre_budget_change_ons_household_income_decile", period) weight = household("household_weight", period) DECILE_INCIDENCE = { @@ -33,10 +38,7 @@ def formula(household, period, parameters): budget_increase_per_decile = { i: budget_increase * DECILE_INCIDENCE[i] for i in range(1, 11) } - if household.simulation.dataset is not None: - households_per_decile = pd.Series(weight).groupby(decile).sum().to_dict() - else: - households_per_decile = {i: 28e5 for i in range(1, 11)} + households_per_decile = pd.Series(weight).groupby(decile).sum().to_dict() # A decile with no weighted households in the data, as in a small # sample, has nobody to receive its share. diff --git a/policyengine_uk/variables/contrib/policyengine/pre_budget_change_ons_household_income_decile.py b/policyengine_uk/variables/contrib/policyengine/pre_budget_change_ons_household_income_decile.py index f3a96d489e..9e6b703cf0 100644 --- a/policyengine_uk/variables/contrib/policyengine/pre_budget_change_ons_household_income_decile.py +++ b/policyengine_uk/variables/contrib/policyengine/pre_budget_change_ons_household_income_decile.py @@ -1,4 +1,5 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.data_source import built_from_data class pre_budget_change_ons_household_income_decile(Variable): @@ -11,7 +12,7 @@ class pre_budget_change_ons_household_income_decile(Variable): def formula(household, period, parameters): income = household("pre_budget_change_household_net_income", period) equivalisation = household("household_equivalisation_bhc", period) - if household.simulation.dataset is not None: + if built_from_data(household.simulation): household_weight = household("household_weight", period) weighted_income = MicroSeries( income / equivalisation, weights=household_weight diff --git a/policyengine_uk/variables/contrib/ubi_center/carbon_tax.py b/policyengine_uk/variables/contrib/ubi_center/carbon_tax.py index 5df088aec7..02c83e2134 100644 --- a/policyengine_uk/variables/contrib/ubi_center/carbon_tax.py +++ b/policyengine_uk/variables/contrib/ubi_center/carbon_tax.py @@ -1,9 +1,19 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.data_source import built_from_data class carbon_tax(Variable): entity = Household label = "Carbon tax" + documentation = ( + "A tax on the carbon in household consumption. Consumers bear " + "consumer_incidence of it on their own emissions; the rest falls on " + "capital, shared by shareholding over the emissions of all UK " + "households. In a simulation built from data those emissions are the " + "weighted total; a household situation reads the published sector " + "totals carbon_consumption is built from, which matter only where " + "the situation sets shareholding." + ) definition_period = YEAR value_type = float unit = GBP @@ -14,7 +24,17 @@ def formula(household, period, parameters): emissions = household("carbon_consumption", period) # Household's share of total stocks and other corporate tax exposure. shareholding = household("shareholding", period) - total_emissions = (emissions * household("household_weight", period)).sum() + if built_from_data(household.simulation): + total_emissions = (emissions * household("household_weight", period)).sum() + else: + categories = household.simulation.tax_benefit_system.get_variable( + "consumption" + ).adds + sector_emissions = parameters(period).household.consumption.carbon.emissions + total_emissions = sum( + sector_emissions[category.replace("_consumption", "")] + for category in categories + ) consumer_incidence = carbon_tax.consumer_incidence * rate * emissions corporate_incidence = ( (1 - carbon_tax.consumer_incidence) * rate * total_emissions * shareholding diff --git a/policyengine_uk/variables/household/consumption/consumption_share.py b/policyengine_uk/variables/household/consumption/consumption_share.py index 42d151dd2e..0badc602d5 100644 --- a/policyengine_uk/variables/household/consumption/consumption_share.py +++ b/policyengine_uk/variables/household/consumption/consumption_share.py @@ -1,19 +1,27 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.data_source import built_from_data class consumption_shareholding(Variable): label = "share of UK consumption" - documentation = "Exposure to taxes on consumption" + documentation = ( + "The household's share of the consumption of all UK households, the " + "key that consumer-incident tax changes are allocated by. In a " + "simulation built from data it is the household's consumption over " + "the simulation's weighted total, so the shares sum to one, and 0 " + "where that total is 0. A household situation has no population to " + "take a share of, so its share is 0 unless set." + ) entity = Household definition_period = YEAR value_type = float unit = "/1" def formula(household, period, parameters): + if not built_from_data(household.simulation): + return 0 consumption = household("consumption", period) - if household.simulation.dataset is not None: - weight = household("household_weight", period) - weighted_total = (consumption * weight).sum() - if weighted_total != 0: - return consumption / weighted_total - return 0 + weighted_total = (consumption * household("household_weight", period)).sum() + if weighted_total == 0: + return 0 + return consumption / weighted_total diff --git a/policyengine_uk/variables/household/wealth/corporate_land_value.py b/policyengine_uk/variables/household/wealth/corporate_land_value.py index 8ada5e20d5..ef584538ec 100644 --- a/policyengine_uk/variables/household/wealth/corporate_land_value.py +++ b/policyengine_uk/variables/household/wealth/corporate_land_value.py @@ -4,24 +4,16 @@ class corporate_land_value(Variable): entity = Household label = "Land value" - documentation = "Estimated total land value indirectly owned by the household from corporate holdings" + documentation = ( + "Estimated total land value indirectly owned by the household from " + "corporate holdings: its shareholding of the land UK corporations " + "hold. A household situation holds none unless shareholding is set." + ) unit = GBP definition_period = YEAR value_type = float quantity_type = STOCK def formula(household, period, parameters): - corporate_wealth = household("corporate_sector_wealth", period) - household_weight = household("household_weight", period) - total_weighted_corporate_wealth = (corporate_wealth * household_weight).sum() - if total_weighted_corporate_wealth == 0: - return corporate_wealth * 0 - - aggregate_corporate_land_value = parameters( - period - ).household.wealth.land.value.aggregate_corporate_land_value - return ( - corporate_wealth - / total_weighted_corporate_wealth - * aggregate_corporate_land_value - ) + land = parameters(period).household.wealth.land.value + return household("shareholding", period) * land.aggregate_corporate_land_value diff --git a/policyengine_uk/variables/household/wealth/shareholding.py b/policyengine_uk/variables/household/wealth/shareholding.py index febd95d58d..097d44903d 100644 --- a/policyengine_uk/variables/household/wealth/shareholding.py +++ b/policyengine_uk/variables/household/wealth/shareholding.py @@ -1,23 +1,28 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.data_source import built_from_data class shareholding(Variable): label = "Share in the corporate sector" - documentation = "Exposure to taxes on corporations" + documentation = ( + "The household's share of the corporate_sector_wealth of all UK " + "households, the key that business rates, corporate Stamp Duty Land " + "Tax, corporate land and the other corporate-incident terms are " + "allocated by. In a simulation built from data it is the household's " + "corporate_sector_wealth over the simulation's weighted total, so the " + "shares sum to one, and 0 where that total is 0. A household situation " + "has no population to take a share of, so its share is 0 unless set." + ) entity = Household definition_period = YEAR value_type = float unit = "/1" def formula(household, period, parameters): + if not built_from_data(household.simulation): + return 0 wealth = household("corporate_sector_wealth", period) - if household.simulation.dataset is not None: - weight = household("household_weight", period) - weighted_total = (wealth * weight).sum() - if weighted_total != 0: - return wealth / weighted_total - wealth = parameters(period).household.wealth - nbs = wealth.national_balance_sheet - wealth = household("corporate_sector_wealth", period) - total_wealth = nbs.household.financial_net_worth - return wealth / total_wealth + weighted_total = (wealth * household("household_weight", period)).sum() + if weighted_total == 0: + return 0 + return wealth / weighted_total From d19d5bb396ef4892c3b8f9cabcf6a62f617cdcbc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:11:42 +0000 Subject: [PATCH 2/5] Let the data carry UK totals so part of the UK gets its national shares A simulation of part of the UK (a region filtered from the data, an extract, a household subset, one block of a larger build) cannot sum a key over all UK households, so its weighted branch handed the part every UK total. The data can now carry those totals instead (#2896). - Fourteen household inputs, uk_total_, hold the UK weighted totals of the components of corporate_sector_wealth and consumption, the same on every row, and 0 where not supplied. - shareholding and consumption_shareholding divide by the carried total where there is one, whichever households are simulated. A situation can carry the totals to opt in. - carbon_tax derives the UK's emissions from the carried spending totals at the run's own carbon intensities, which carbon_consumption and carbon_tax now share (utils/carbon.py). - Each total uprates like the column it sums, times population, through two growth series generated before the index pass (uk_totals.per_capita_gdp and uk_totals.consumer_price_index), so totals written at the dataset's year stay equal to the projected weighted totals. Co-Authored-By: Claude Opus 5.5 --- changelog.d/2896.added.md | 1 + policyengine_uk/data/uprating_indices.yaml | 18 ++ .../create_uk_total_growth.py | 59 +++++ policyengine_uk/tax_benefit_system.py | 5 + .../tests/test_population_shares.py | 214 ++++++++++++++++++ policyengine_uk/utils/carbon.py | 50 ++++ policyengine_uk/utils/uk_totals.py | 66 ++++++ .../contrib/ubi_center/carbon_tax.py | 26 +-- .../variables/household/consumption/carbon.py | 36 +-- .../consumption/consumption_share.py | 27 ++- .../household/wealth/shareholding.py | 23 +- ...k_total_alcohol_and_tobacco_consumption.py | 17 ++ ...total_clothing_and_footwear_consumption.py | 17 ++ .../uk_total_communication_consumption.py | 17 ++ .../uk_totals/uk_total_corporate_wealth.py | 18 ++ .../uk_total_education_consumption.py | 17 ++ ...and_non_alcoholic_beverages_consumption.py | 17 ++ .../uk_totals/uk_total_health_consumption.py | 17 ++ ...total_household_furnishings_consumption.py | 17 ++ ...using_water_and_electricity_consumption.py | 17 ++ .../uk_total_miscellaneous_consumption.py | 17 ++ .../uk_total_private_pension_wealth.py | 18 ++ .../uk_total_recreation_consumption.py | 17 ++ ...otal_restaurants_and_hotels_consumption.py | 17 ++ .../uk_total_transport_consumption.py | 17 ++ 25 files changed, 702 insertions(+), 63 deletions(-) create mode 100644 changelog.d/2896.added.md create mode 100644 policyengine_uk/parameters/gov/economic_assumptions/create_uk_total_growth.py create mode 100644 policyengine_uk/utils/carbon.py create mode 100644 policyengine_uk/utils/uk_totals.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_alcohol_and_tobacco_consumption.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_clothing_and_footwear_consumption.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_communication_consumption.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_corporate_wealth.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_education_consumption.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_food_and_non_alcoholic_beverages_consumption.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_health_consumption.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_household_furnishings_consumption.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_housing_water_and_electricity_consumption.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_miscellaneous_consumption.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_private_pension_wealth.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_recreation_consumption.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_restaurants_and_hotels_consumption.py create mode 100644 policyengine_uk/variables/input/uk_totals/uk_total_transport_consumption.py diff --git a/changelog.d/2896.added.md b/changelog.d/2896.added.md new file mode 100644 index 0000000000..3d2675fdab --- /dev/null +++ b/changelog.d/2896.added.md @@ -0,0 +1 @@ +Added inputs for the UK totals of the components of corporate_sector_wealth and consumption (uk_total_*): where the data carries them, shareholding, consumption_shareholding and carbon tax's corporate part give each household its national share in any simulation of part of the UK, such as a region, an extract or one block of a build. diff --git a/policyengine_uk/data/uprating_indices.yaml b/policyengine_uk/data/uprating_indices.yaml index ac650a2d71..28c4e25851 100644 --- a/policyengine_uk/data/uprating_indices.yaml +++ b/policyengine_uk/data/uprating_indices.yaml @@ -228,3 +228,21 @@ gov.economic_assumptions.yoy_growth.orr.per_capita.rail_passenger_journeys: - rail_usage gov.economic_assumptions.yoy_growth.ons.population: - household_weight +# UK totals of the keys' components, which grow like the column they sum, +# times population as household weights do (policyengine-uk#2896). +gov.economic_assumptions.yoy_growth.uk_totals.per_capita_gdp: +- uk_total_corporate_wealth +- uk_total_private_pension_wealth +gov.economic_assumptions.yoy_growth.uk_totals.consumer_price_index: +- uk_total_food_and_non_alcoholic_beverages_consumption +- uk_total_alcohol_and_tobacco_consumption +- uk_total_clothing_and_footwear_consumption +- uk_total_housing_water_and_electricity_consumption +- uk_total_household_furnishings_consumption +- uk_total_health_consumption +- uk_total_transport_consumption +- uk_total_communication_consumption +- uk_total_recreation_consumption +- uk_total_education_consumption +- uk_total_restaurants_and_hotels_consumption +- uk_total_miscellaneous_consumption diff --git a/policyengine_uk/parameters/gov/economic_assumptions/create_uk_total_growth.py b/policyengine_uk/parameters/gov/economic_assumptions/create_uk_total_growth.py new file mode 100644 index 0000000000..eefc76d3ce --- /dev/null +++ b/policyengine_uk/parameters/gov/economic_assumptions/create_uk_total_growth.py @@ -0,0 +1,59 @@ +"""Growth of the UK totals a dataset can carry (policyengine-uk#2896). + +A UK total sums a household column over all UK households at their weights. +Household weights grow with population, so the total grows with the column's +own growth and with population: (1 + column growth) x (1 + population growth) +- 1. The totals of corporate and private pension wealth, which grow with +per-capita GDP, therefore grow with nominal GDP; those of spending, which grows +with CPI, with CPI and population. Each series is generated before the index +pass, so it gets its index like any other. +""" + +from policyengine_core.parameters import Parameter, ParameterNode + +# Each generated series: the per-household growth it combines with population +# growth, and its label. +UK_TOTAL_GROWTH = { + "per_capita_gdp": ("obr.per_capita.gdp", "UK total growth with per-capita GDP"), + "consumer_price_index": ("obr.consumer_price_index", "UK total growth with CPI"), +} + + +def _years(parameter: Parameter) -> list: + return [int(value.instant_str[:4]) for value in parameter.values_list] + + +def add_uk_total_growth(parameters: ParameterNode) -> ParameterNode: + yoy_growth = parameters.gov.economic_assumptions.yoy_growth + population = yoy_growth.ons.population + node = ParameterNode(name="gov.economic_assumptions.yoy_growth.uk_totals", data={}) + for name, (path, label) in UK_TOTAL_GROWTH.items(): + per_household = yoy_growth.get_child(path) + # From the first year both series cover. A series that ends early holds + # its last rate, as the index pass reads it. + first = max(min(_years(per_household)), min(_years(population))) + last = max(max(_years(per_household)), max(_years(population))) + values = { + f"{year}-01-01": (1 + per_household(year)) * (1 + population(year)) - 1 + for year in range(first, last + 1) + } + node.add_child( + name, + Parameter( + f"gov.economic_assumptions.yoy_growth.uk_totals.{name}", + data={ + "description": ( + "Year-on-year growth of a UK total of a household " + f"column that grows with {path}: that growth and " + "population growth combined." + ), + "values": values, + "metadata": { + "unit": "/1", + "label": label, + }, + }, + ), + ) + yoy_growth.add_child("uk_totals", node) + return parameters diff --git a/policyengine_uk/tax_benefit_system.py b/policyengine_uk/tax_benefit_system.py index 90670bcea1..2233830e36 100644 --- a/policyengine_uk/tax_benefit_system.py +++ b/policyengine_uk/tax_benefit_system.py @@ -57,6 +57,9 @@ from policyengine_uk.parameters.gov.economic_assumptions.create_economic_assumption_indices import ( create_economic_assumption_indices, ) +from policyengine_uk.parameters.gov.economic_assumptions.create_uk_total_growth import ( + add_uk_total_growth, +) from policyengine_uk.parameters.gov.economic_assumptions.create_energy_price_indices import ( add_energy_price_indices, ) @@ -143,6 +146,7 @@ def _install_parameters(system, parameters: ParameterNode) -> None: add_earnings_uprating, add_triple_lock, add_september_cpi_uprating, + add_uk_total_growth, create_economic_assumption_indices, add_energy_price_indices, project_state_pension_rates, @@ -203,6 +207,7 @@ def process_parameter_tree( - statutory uprating inputs (September CPI, May-July earnings) - triple lock calculations for state pensions - earnings and September CPI uprating + - growth of the UK totals a dataset can carry (policyengine-uk#2896) - economic assumption indices - household energy price indices - State Pension weekly rates, projected each April from the year before diff --git a/policyengine_uk/tests/test_population_shares.py b/policyengine_uk/tests/test_population_shares.py index 7be4a0e61a..d14e70e4cc 100644 --- a/policyengine_uk/tests/test_population_shares.py +++ b/policyengine_uk/tests/test_population_shares.py @@ -242,3 +242,217 @@ def test_situation_decile_uses_the_fixed_bounds_whatever_the_weight(): ) assert deciles[0] == deciles[1] == deciles[2] assert 1 <= deciles[0] <= 10 + + +# Runs of part of the UK, with the UK totals carried by the data. + +# Four households in two regions, whose keys differ. Each stands for millions, +# as survey households do, so no one bears much of any UK total. +POPULATION = [ + { + "region": "LONDON", + "corporate_wealth": 100_000, + "private_pension_wealth": 50_000, + "food_and_non_alcoholic_beverages_consumption": 4_000, + "transport_consumption": 2_000, + "household_weight": 3e6, + "employment_income": 40_000, + }, + { + "region": "LONDON", + "corporate_wealth": 0, + "private_pension_wealth": 200_000, + "food_and_non_alcoholic_beverages_consumption": 6_000, + "transport_consumption": 1_000, + "household_weight": 5e6, + "employment_income": 20_000, + }, + { + "region": "WALES", + "corporate_wealth": 300_000, + "private_pension_wealth": 0, + "food_and_non_alcoholic_beverages_consumption": 3_000, + "transport_consumption": 4_000, + "household_weight": 2e6, + "employment_income": 60_000, + }, + { + "region": "WALES", + "corporate_wealth": 10_000, + "private_pension_wealth": 20_000, + "food_and_non_alcoholic_beverages_consumption": 5_000, + "transport_consumption": 500, + "household_weight": 4e6, + "employment_income": 30_000, + }, +] + +# Every term spread by a population key, under one reform. +SPREAD = [ + "shareholding", + "consumption_shareholding", + "corporate_land_value", + "business_rates", + "corporate_sdlt", + "corporate_incident_tax_revenue_change", + "consumer_incident_tax_revenue_change", + "carbon_tax", + "LVT", +] +SPREAD_REFORM = { + **CASES["corporate_incident_tax_revenue_change"], + **CASES["consumer_incident_tax_revenue_change"], + **CASES["LVT"], + "gov.contrib.ubi_center.carbon_tax.rate": {YEAR: 100}, + "gov.contrib.ubi_center.carbon_tax.consumer_incidence": {YEAR: 0.5}, +} + + +def hand_totals(rows): + """The UK total of each key component over ``rows``, at their weights.""" + from policyengine_uk.utils.uk_totals import KEYS, components, total_name + + return { + total_name(component): sum( + row.get(component, 0) * row["household_weight"] for row in rows + ) + for key in KEYS + for component in components(key) + } + + +def population_simulation(rows, carried=None, year=YEAR, reform=SPREAD_REFORM): + """A simulation built from ``rows``, one person per household, with the UK + totals ``carried`` written on every household.""" + n = len(rows) + ids = list(range(1, n + 1)) + household = { + "household_id": ids, + # Columns dataset uprating reads. + "council_tax": [0.0] * n, + "rent": [0.0] * n, + "tenure_type": ["OWNED_OUTRIGHT"] * n, + "household_owns_tv": [False] * n, + } + for name in rows[0]: + if name != "employment_income": + household[name] = [row[name] for row in rows] + for name, value in (carried or {}).items(): + household[name] = [value] * n + dataset = UKSingleYearDataset( + person=pd.DataFrame( + { + "person_id": ids, + "person_benunit_id": ids, + "person_household_id": ids, + "age": [45] * n, + "employment_income": [row["employment_income"] for row in rows], + } + ), + benunit=pd.DataFrame({"benunit_id": ids}), + household=pd.DataFrame(household), + fiscal_year=year, + ) + return Simulation(dataset=dataset, reform=reform) + + +def spread_values(sim, year=YEAR): + return {variable: calculate_at(sim, variable, year) for variable in SPREAD} + + +def calculate_at(sim, variable, year): + return np.asarray(sim.calculate(variable, year, map_to="household")) + + +def test_part_of_the_uk_carrying_the_uk_totals_gets_its_national_shares(): + whole = spread_values(population_simulation(POPULATION)) + # Wales on its own, as a region filtered from the data. + wales = spread_values( + population_simulation(POPULATION[2:], carried=hand_totals(POPULATION)) + ) + for variable in SPREAD: + assert whole[variable][2:].any(), variable + assert wales[variable] == pytest.approx(whole[variable][2:], rel=1e-5), variable + + +def test_blocks_carrying_the_pool_totals_match_the_unblocked_run(): + """As a build runs a pool in blocks, each block's weights scaled up to the + pool's mass: carrying the pool's totals, a block gives each household what + the whole pool gives it, whichever households the block holds.""" + pool = spread_values(population_simulation(POPULATION)) + totals = hand_totals(POPULATION) + pool_mass = sum(row["household_weight"] for row in POPULATION) + for block in (POPULATION[:2], POPULATION[2:]): + scale = pool_mass / sum(row["household_weight"] for row in block) + scaled = [ + {**row, "household_weight": row["household_weight"] * scale} + for row in block + ] + values = spread_values(population_simulation(scaled, carried=totals)) + start = POPULATION.index(block[0]) + for variable in SPREAD: + assert values[variable] == pytest.approx( + pool[variable][start : start + len(block)], rel=1e-5 + ), variable + + +def test_whole_uk_carrying_its_totals_matches_the_weighted_branch(): + without = spread_values(population_simulation(POPULATION)) + carrying = spread_values( + population_simulation(POPULATION, carried=hand_totals(POPULATION)) + ) + for variable in SPREAD: + assert carrying[variable] == pytest.approx(without[variable], rel=1e-5), ( + variable + ) + + +def test_carried_totals_project_with_the_data(): + """Totals written at the dataset's year grow as the weighted totals of the + projected data do, so a later year's shares still match.""" + base_year, later = 2024, 2027 + whole = population_simulation(POPULATION, year=base_year) + wales = population_simulation( + POPULATION[2:], carried=hand_totals(POPULATION), year=base_year + ) + for variable in ["shareholding", "consumption_shareholding", "carbon_tax"]: + assert calculate_at(wales, variable, later) == pytest.approx( + calculate_at(whole, variable, later)[2:], rel=1e-4 + ), variable + + +def test_situation_carrying_uk_totals_gets_its_share(): + situation = copies(HOLDER, [1, 1_000]) + totals = { + "uk_total_corporate_wealth": 4e12, + "uk_total_private_pension_wealth": 6e12, + "uk_total_food_and_non_alcoholic_beverages_consumption": 1e11, + "uk_total_transport_consumption": 9e10, + } + for household in situation["households"].values(): + household.update({name: {YEAR: value} for name, value in totals.items()}) + sim = Simulation(situation=situation) + assert calculate(sim, "shareholding") == pytest.approx([7e4 / 1e13] * 2) + assert calculate(sim, "consumption_shareholding") == pytest.approx( + [8e3 / 1.9e11] * 2 + ) + + +def test_every_key_component_has_a_uk_total_input(): + from policyengine_uk.system import system + from policyengine_uk.utils.carbon import CARBON_CATEGORIES + from policyengine_uk.utils.uk_totals import KEYS, components, total_name + + growth = { + "corporate_sector_wealth": "per_capita_gdp", + "consumption": "consumer_price_index", + } + for key in KEYS: + assert components(key) == list(system.get_variable(key).adds) + for component in components(key): + variable = system.get_variable(total_name(component)) + assert variable.entity.key == "household" + assert variable.uprating == ( + f"gov.economic_assumptions.indices.uk_totals.{growth[key]}" + ) + assert set(CARBON_CATEGORIES) == set(components("consumption")) diff --git a/policyengine_uk/utils/carbon.py b/policyengine_uk/utils/carbon.py new file mode 100644 index 0000000000..0bd062fafc --- /dev/null +++ b/policyengine_uk/utils/carbon.py @@ -0,0 +1,50 @@ +"""Carbon intensities of household spending.""" + +# The spending categories consumption adds, in the order carbon_consumption +# sums them. +CARBON_CATEGORIES = [ + "food_and_non_alcoholic_beverages_consumption", + "alcohol_and_tobacco_consumption", + "clothing_and_footwear_consumption", + "housing_water_and_electricity_consumption", + "household_furnishings_consumption", + "health_consumption", + "transport_consumption", + "communication_consumption", + "recreation_consumption", + "education_consumption", + "restaurants_and_hotels_consumption", + "miscellaneous_consumption", +] + + +def carbon_intensities(parameters, period) -> list: + """Tonnes of CO2 per pound spent in each of CARBON_CATEGORIES: the + published emissions of its sector over the published spending on it, or + the parameter intensity where that spending is zero.""" + consumption = parameters(period).household.consumption + aggregate_spending_by_sector = [ + consumption.total_by_category[category] for category in CARBON_CATEGORIES + ] + carbon = consumption.carbon + aggregate_emissions_by_sector = [ + carbon.emissions[category.replace("_consumption", "")] + for category in CARBON_CATEGORIES + ] + return [ + emissions / spending if spending > 0 else carbon.intensity[name] + for emissions, spending, name in zip( + aggregate_emissions_by_sector, + aggregate_spending_by_sector, + CARBON_CATEGORIES, + ) + ] + + +def published_emissions(parameters, period) -> float: + """The published emissions of all of CARBON_CATEGORIES' sectors.""" + carbon = parameters(period).household.consumption.carbon + return sum( + carbon.emissions[category.replace("_consumption", "")] + for category in CARBON_CATEGORIES + ) diff --git a/policyengine_uk/utils/uk_totals.py b/policyengine_uk/utils/uk_totals.py new file mode 100644 index 0000000000..100fcf3e5e --- /dev/null +++ b/policyengine_uk/utils/uk_totals.py @@ -0,0 +1,66 @@ +"""UK totals of the keys that shares of national totals are taken by. + +shareholding and consumption_shareholding give each household its share of a +UK total: of corporate_sector_wealth and of consumption, summed over all UK +households at their weights. A simulation of all UK households can sum them +itself. A simulation of part of the UK cannot, because the other households +are not in it: a region filtered from the data, an extract, a household subset +or one block of a larger build. So whoever holds the whole population writes +the totals into the data, as household columns the same on every row, and the +shares divide by them (policyengine-uk#2896). + +The columns hold the totals of each key's components, the variables the key +adds, so the formulas derive the key's total, and the UK's carbon emissions, +with the simulation's own definitions and parameters. Each column is uprated +like the column it sums, times population (create_uk_total_growth). +""" + +from typing import List + +import numpy as np + +from policyengine_uk.utils.carbon import CARBON_CATEGORIES, carbon_intensities + +PREFIX = "uk_total_" +KEYS = ("corporate_sector_wealth", "consumption") + + +def components(key: str) -> List[str]: + """The variables ``key`` adds, whose UK totals the data can carry.""" + if key == "corporate_sector_wealth": + from policyengine_uk.variables.household.wealth.corporate_sector_wealth import ( + corporate_sector_wealth as variable, + ) + elif key == "consumption": + from policyengine_uk.variables.input.consumption.consumption import ( + consumption as variable, + ) + else: + raise ValueError(f"{key} is not a key with UK totals.") + return list(variable.adds) + + +def total_name(component: str) -> str: + """The input holding the UK total of ``component``.""" + return PREFIX + component + + +def carried_uk_total(population, key: str, period) -> np.ndarray: + """Each household's carried UK total of ``key``: the sum of its + components' carried totals, 0 where the data carries none.""" + return sum( + population(total_name(component), period) for component in components(key) + ) + + +def carried_uk_emissions(population, period, parameters) -> np.ndarray: + """The carbon emissions of all UK households from the carried totals of + their spending, at this simulation's carbon intensities: each category's + UK total times its intensity, as carbon_consumption works out each + household's. 0 where the data carries no spending totals.""" + return sum( + population(total_name(category), period) * intensity + for category, intensity in zip( + CARBON_CATEGORIES, carbon_intensities(parameters, period) + ) + ) diff --git a/policyengine_uk/variables/contrib/ubi_center/carbon_tax.py b/policyengine_uk/variables/contrib/ubi_center/carbon_tax.py index 02c83e2134..d864ccfbde 100644 --- a/policyengine_uk/variables/contrib/ubi_center/carbon_tax.py +++ b/policyengine_uk/variables/contrib/ubi_center/carbon_tax.py @@ -1,5 +1,7 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.carbon import published_emissions from policyengine_uk.utils.data_source import built_from_data +from policyengine_uk.utils.uk_totals import carried_uk_emissions class carbon_tax(Variable): @@ -9,10 +11,11 @@ class carbon_tax(Variable): "A tax on the carbon in household consumption. Consumers bear " "consumer_incidence of it on their own emissions; the rest falls on " "capital, shared by shareholding over the emissions of all UK " - "households. In a simulation built from data those emissions are the " - "weighted total; a household situation reads the published sector " - "totals carbon_consumption is built from, which matter only where " - "the situation sets shareholding." + "households. Those emissions come from the UK spending totals the " + "data carries (policyengine_uk.utils.uk_totals), or else, in a " + "simulation built from data, from its weighted total. A household " + "situation that carries no totals reads the published sector " + "emissions, which matter only where it sets shareholding." ) definition_period = YEAR value_type = float @@ -25,16 +28,13 @@ def formula(household, period, parameters): # Household's share of total stocks and other corporate tax exposure. shareholding = household("shareholding", period) if built_from_data(household.simulation): - total_emissions = (emissions * household("household_weight", period)).sum() + simulated_emissions = ( + emissions * household("household_weight", period) + ).sum() else: - categories = household.simulation.tax_benefit_system.get_variable( - "consumption" - ).adds - sector_emissions = parameters(period).household.consumption.carbon.emissions - total_emissions = sum( - sector_emissions[category.replace("_consumption", "")] - for category in categories - ) + simulated_emissions = published_emissions(parameters, period) + carried = carried_uk_emissions(household, period, parameters) + total_emissions = where(carried > 0, carried, simulated_emissions) consumer_incidence = carbon_tax.consumer_incidence * rate * emissions corporate_incidence = ( (1 - carbon_tax.consumer_incidence) * rate * total_emissions * shareholding diff --git a/policyengine_uk/variables/household/consumption/carbon.py b/policyengine_uk/variables/household/consumption/carbon.py index 3b2973c117..37d6bc12a6 100644 --- a/policyengine_uk/variables/household/consumption/carbon.py +++ b/policyengine_uk/variables/household/consumption/carbon.py @@ -1,4 +1,5 @@ from policyengine_uk.model_api import * +from policyengine_uk.utils.carbon import CARBON_CATEGORIES, carbon_intensities class carbon_consumption(Variable): @@ -10,40 +11,9 @@ class carbon_consumption(Variable): value_type = float def formula(household, period, parameters): - CONSUMPTION_VARIABLES = [ - "food_and_non_alcoholic_beverages_consumption", - "alcohol_and_tobacco_consumption", - "clothing_and_footwear_consumption", - "housing_water_and_electricity_consumption", - "household_furnishings_consumption", - "health_consumption", - "transport_consumption", - "communication_consumption", - "recreation_consumption", - "education_consumption", - "restaurants_and_hotels_consumption", - "miscellaneous_consumption", - ] - consumption = parameters(period).household.consumption - aggregate_spending_by_sector = [ - consumption.total_by_category[category] - for category in CONSUMPTION_VARIABLES - ] - carbon = consumption.carbon - aggregate_emissions_by_sector = [ - carbon.emissions[category.replace("_consumption", "")] - for category in CONSUMPTION_VARIABLES - ] - carbon_intensity_by_sector = [ - emissions / spending if spending > 0 else carbon.intensity[name] - for emissions, spending, name in zip( - aggregate_emissions_by_sector, - aggregate_spending_by_sector, - CONSUMPTION_VARIABLES, - ) - ] + carbon_intensity_by_sector = carbon_intensities(parameters, period) spending_by_sector = [ - household(category, period) for category in CONSUMPTION_VARIABLES + household(category, period) for category in CARBON_CATEGORIES ] return sum( [ diff --git a/policyengine_uk/variables/household/consumption/consumption_share.py b/policyengine_uk/variables/household/consumption/consumption_share.py index 0badc602d5..7e5e9d9ecf 100644 --- a/policyengine_uk/variables/household/consumption/consumption_share.py +++ b/policyengine_uk/variables/household/consumption/consumption_share.py @@ -1,16 +1,20 @@ from policyengine_uk.model_api import * from policyengine_uk.utils.data_source import built_from_data +from policyengine_uk.utils.uk_totals import carried_uk_total class consumption_shareholding(Variable): label = "share of UK consumption" documentation = ( "The household's share of the consumption of all UK households, the " - "key that consumer-incident tax changes are allocated by. In a " - "simulation built from data it is the household's consumption over " - "the simulation's weighted total, so the shares sum to one, and 0 " - "where that total is 0. A household situation has no population to " - "take a share of, so its share is 0 unless set." + "key that consumer-incident tax changes are allocated by. Where the " + "data carries the UK total (policyengine_uk.utils.uk_totals), it is " + "the household's consumption over that total, whichever households " + "are simulated. Otherwise, in a simulation built from data, it is " + "over the simulation's weighted total, so the shares sum to one, and " + "0 where that total is 0. A household situation that carries no UK " + "total has no population to take a share of, so its share is 0 " + "unless set." ) entity = Household definition_period = YEAR @@ -18,10 +22,15 @@ class consumption_shareholding(Variable): unit = "/1" def formula(household, period, parameters): - if not built_from_data(household.simulation): - return 0 consumption = household("consumption", period) + uk_total = carried_uk_total(household, "consumption", period) + carried = uk_total > 0 + share = np.divide( + consumption, uk_total, out=np.zeros(len(consumption)), where=carried + ) + if carried.all() or not built_from_data(household.simulation): + return share weighted_total = (consumption * household("household_weight", period)).sum() if weighted_total == 0: - return 0 - return consumption / weighted_total + return share + return where(carried, share, consumption / weighted_total) diff --git a/policyengine_uk/variables/household/wealth/shareholding.py b/policyengine_uk/variables/household/wealth/shareholding.py index 097d44903d..26629a9d8a 100644 --- a/policyengine_uk/variables/household/wealth/shareholding.py +++ b/policyengine_uk/variables/household/wealth/shareholding.py @@ -1,5 +1,6 @@ from policyengine_uk.model_api import * from policyengine_uk.utils.data_source import built_from_data +from policyengine_uk.utils.uk_totals import carried_uk_total class shareholding(Variable): @@ -8,10 +9,13 @@ class shareholding(Variable): "The household's share of the corporate_sector_wealth of all UK " "households, the key that business rates, corporate Stamp Duty Land " "Tax, corporate land and the other corporate-incident terms are " - "allocated by. In a simulation built from data it is the household's " - "corporate_sector_wealth over the simulation's weighted total, so the " - "shares sum to one, and 0 where that total is 0. A household situation " - "has no population to take a share of, so its share is 0 unless set." + "allocated by. Where the data carries the UK total " + "(policyengine_uk.utils.uk_totals), it is the household's " + "corporate_sector_wealth over that total, whichever households are " + "simulated. Otherwise, in a simulation built from data, it is over the " + "simulation's weighted total, so the shares sum to one, and 0 where " + "that total is 0. A household situation that carries no UK total has " + "no population to take a share of, so its share is 0 unless set." ) entity = Household definition_period = YEAR @@ -19,10 +23,13 @@ class shareholding(Variable): unit = "/1" def formula(household, period, parameters): - if not built_from_data(household.simulation): - return 0 wealth = household("corporate_sector_wealth", period) + uk_total = carried_uk_total(household, "corporate_sector_wealth", period) + carried = uk_total > 0 + share = np.divide(wealth, uk_total, out=np.zeros(len(wealth)), where=carried) + if carried.all() or not built_from_data(household.simulation): + return share weighted_total = (wealth * household("household_weight", period)).sum() if weighted_total == 0: - return 0 - return wealth / weighted_total + return share + return where(carried, share, wealth / weighted_total) diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_alcohol_and_tobacco_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_alcohol_and_tobacco_consumption.py new file mode 100644 index 0000000000..7ea7866b42 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_alcohol_and_tobacco_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_alcohol_and_tobacco_consumption(Variable): + label = "UK total of alcohol and tobacco consumption" + documentation = ( + "alcohol_and_tobacco_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_clothing_and_footwear_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_clothing_and_footwear_consumption.py new file mode 100644 index 0000000000..91e0609027 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_clothing_and_footwear_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_clothing_and_footwear_consumption(Variable): + label = "UK total of clothing and footwear consumption" + documentation = ( + "clothing_and_footwear_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_communication_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_communication_consumption.py new file mode 100644 index 0000000000..b1d36112f0 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_communication_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_communication_consumption(Variable): + label = "UK total of communication consumption" + documentation = ( + "communication_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_corporate_wealth.py b/policyengine_uk/variables/input/uk_totals/uk_total_corporate_wealth.py new file mode 100644 index 0000000000..6e0908c119 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_corporate_wealth.py @@ -0,0 +1,18 @@ +from policyengine_uk.model_api import * + + +class uk_total_corporate_wealth(Variable): + label = "UK total of corporate wealth" + documentation = ( + "corporate_wealth summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of corporate_sector_wealth. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + quantity_type = STOCK + uprating = "gov.economic_assumptions.indices.uk_totals.per_capita_gdp" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_education_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_education_consumption.py new file mode 100644 index 0000000000..7b890b46b5 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_education_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_education_consumption(Variable): + label = "UK total of education consumption" + documentation = ( + "education_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_food_and_non_alcoholic_beverages_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_food_and_non_alcoholic_beverages_consumption.py new file mode 100644 index 0000000000..6ce21d0ce6 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_food_and_non_alcoholic_beverages_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_food_and_non_alcoholic_beverages_consumption(Variable): + label = "UK total of food and non alcoholic beverages consumption" + documentation = ( + "food_and_non_alcoholic_beverages_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_health_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_health_consumption.py new file mode 100644 index 0000000000..e0a81cc281 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_health_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_health_consumption(Variable): + label = "UK total of health consumption" + documentation = ( + "health_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_household_furnishings_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_household_furnishings_consumption.py new file mode 100644 index 0000000000..635ff30cd6 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_household_furnishings_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_household_furnishings_consumption(Variable): + label = "UK total of household furnishings consumption" + documentation = ( + "household_furnishings_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_housing_water_and_electricity_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_housing_water_and_electricity_consumption.py new file mode 100644 index 0000000000..40faf9f866 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_housing_water_and_electricity_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_housing_water_and_electricity_consumption(Variable): + label = "UK total of housing water and electricity consumption" + documentation = ( + "housing_water_and_electricity_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_miscellaneous_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_miscellaneous_consumption.py new file mode 100644 index 0000000000..025d5522c5 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_miscellaneous_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_miscellaneous_consumption(Variable): + label = "UK total of miscellaneous consumption" + documentation = ( + "miscellaneous_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_private_pension_wealth.py b/policyengine_uk/variables/input/uk_totals/uk_total_private_pension_wealth.py new file mode 100644 index 0000000000..32b298461f --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_private_pension_wealth.py @@ -0,0 +1,18 @@ +from policyengine_uk.model_api import * + + +class uk_total_private_pension_wealth(Variable): + label = "UK total of private pension wealth" + documentation = ( + "private_pension_wealth summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of corporate_sector_wealth. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + quantity_type = STOCK + uprating = "gov.economic_assumptions.indices.uk_totals.per_capita_gdp" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_recreation_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_recreation_consumption.py new file mode 100644 index 0000000000..743120bc0f --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_recreation_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_recreation_consumption(Variable): + label = "UK total of recreation consumption" + documentation = ( + "recreation_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_restaurants_and_hotels_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_restaurants_and_hotels_consumption.py new file mode 100644 index 0000000000..cac0b573e5 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_restaurants_and_hotels_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_restaurants_and_hotels_consumption(Variable): + label = "UK total of restaurants and hotels consumption" + documentation = ( + "restaurants_and_hotels_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" diff --git a/policyengine_uk/variables/input/uk_totals/uk_total_transport_consumption.py b/policyengine_uk/variables/input/uk_totals/uk_total_transport_consumption.py new file mode 100644 index 0000000000..e004a50ea2 --- /dev/null +++ b/policyengine_uk/variables/input/uk_totals/uk_total_transport_consumption.py @@ -0,0 +1,17 @@ +from policyengine_uk.model_api import * + + +class uk_total_transport_consumption(Variable): + label = "UK total of transport consumption" + documentation = ( + "transport_consumption summed over all UK households at their weights, the " + "same on every household. Whoever holds the whole population " + "supplies it (policyengine_uk.utils.uk_totals.add_uk_totals), so that " + "a simulation of part of the UK gives each household its share of " + "the UK total of consumption. 0 where not supplied." + ) + entity = Household + definition_period = YEAR + value_type = float + unit = GBP + uprating = "gov.economic_assumptions.indices.uk_totals.consumer_price_index" From 18a38c00a6c50012d3194207339c20dab173898b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:23:04 +0000 Subject: [PATCH 3/5] Add add_uk_totals, and carry the UK totals into filter_dataset's extracts Whoever holds every UK household writes the UK totals with one helper before taking part of the population: policyengine.py before filtering a region, Microcosm before slicing a pool into blocks, and filter_dataset before extracting a household (#2896). - utils/uk_totals.py gains uk_totals, the weighted totals of a household table (each household weighs 1 where the table has no weights, as household_weight's default does), and add_uk_totals, which writes them on a single-year or multi-year dataset, each year its own. - filter_dataset adds the totals over the whole dataset unless it carries them, so an extract keeps the shares it had rather than 1 over its weight. - The carbon tax page describes where E_total and shareholding's denominator now come from. Co-Authored-By: Claude Opus 5.5 --- changelog.d/2896.added.md | 2 +- .../contrib/ubi-center/carbon-tax.ipynb | 5 +- policyengine_uk/data/filter_dataset.py | 9 ++ .../tests/test_population_shares.py | 84 +++++++++++++++++-- policyengine_uk/utils/uk_totals.py | 57 ++++++++++++- 5 files changed, 148 insertions(+), 9 deletions(-) diff --git a/changelog.d/2896.added.md b/changelog.d/2896.added.md index 3d2675fdab..446d11d4d3 100644 --- a/changelog.d/2896.added.md +++ b/changelog.d/2896.added.md @@ -1 +1 @@ -Added inputs for the UK totals of the components of corporate_sector_wealth and consumption (uk_total_*): where the data carries them, shareholding, consumption_shareholding and carbon tax's corporate part give each household its national share in any simulation of part of the UK, such as a region, an extract or one block of a build. +Added inputs for the UK totals of the components of corporate_sector_wealth and consumption (uk_total_*), and policyengine_uk.utils.uk_totals.add_uk_totals to write them: where the data carries them, shareholding, consumption_shareholding and carbon tax's corporate part give each household its national share in any simulation of part of the UK, such as a region, an extract or one block of a build, and filter_dataset's extracts carry them. diff --git a/docs/book/programs/contrib/ubi-center/carbon-tax.ipynb b/docs/book/programs/contrib/ubi-center/carbon-tax.ipynb index af05368b97..c60f750754 100644 --- a/docs/book/programs/contrib/ubi-center/carbon-tax.ipynb +++ b/docs/book/programs/contrib/ubi-center/carbon-tax.ipynb @@ -35,11 +35,12 @@ "For a household with footprint `E_h`, the [`carbon_tax` formula](https://github.com/PolicyEngine/policyengine-uk/blob/main/policyengine_uk/variables/contrib/ubi_center/carbon_tax.py) is:\n", "\n", "```text\n", - "E_total = sum(household_weight_h * E_h)\n", "carbon_tax_h = c * r * E_h + (1 - c) * r * E_total * shareholding_h\n", "```\n", "\n", - "Here `r` is the hypothetical price per tonne and `c` is the consumer-incidence fraction, both set by the [carbon-tax parameters](https://github.com/PolicyEngine/policyengine-uk/blob/main/policyengine_uk/parameters/gov/contrib/ubi_center/carbon_tax.yaml). The first term allocates the consumer share by the household's footprint. The second allocates the remaining burden using [`shareholding`](https://github.com/PolicyEngine/policyengine-uk/blob/main/policyengine_uk/variables/household/wealth/shareholding.py), the household's modelled corporate-sector wealth exposure. With a dataset and nonzero corporate wealth, that exposure is normalised by weighted household corporate wealth; otherwise the formula uses the national-balance-sheet denominator.\n", + "`E_total` is the footprint of all UK households. Where the data carries the UK totals of spending by category ([`policyengine_uk.utils.uk_totals`](https://github.com/PolicyEngine/policyengine-uk/blob/main/policyengine_uk/utils/uk_totals.py)), it is each category's UK total times its intensity, so a simulation of part of the UK still uses the UK's footprint. Otherwise, in a simulation built from data, it is `sum(household_weight_h * E_h)` over the simulated households; in a household situation it is the published sector emissions.\n", + "\n", + "Here `r` is the hypothetical price per tonne and `c` is the consumer-incidence fraction, both set by the [carbon-tax parameters](https://github.com/PolicyEngine/policyengine-uk/blob/main/policyengine_uk/parameters/gov/contrib/ubi_center/carbon_tax.yaml). The first term allocates the consumer share by the household's footprint. The second allocates the remaining burden using [`shareholding`](https://github.com/PolicyEngine/policyengine-uk/blob/main/policyengine_uk/variables/household/wealth/shareholding.py), the household's modelled corporate-sector wealth exposure. Where the data carries the UK total of corporate-sector wealth, that exposure is the household's share of it, whichever households are simulated; otherwise, in a simulation built from data, it is normalised by the simulation's weighted corporate-sector wealth. A household situation takes no share unless `shareholding` is set, so its corporate term is zero (policyengine-uk#2896).\n", "\n", "This is an allocation assumption, not a calculation of sector-specific demand elasticities, international ownership or the legal incidence of an import tax. Changing the incidence fraction changes who bears the modelled burden, without adding a country-of-production breakdown.\n", "\n", diff --git a/policyengine_uk/data/filter_dataset.py b/policyengine_uk/data/filter_dataset.py index 09eac75ec3..550eb629ab 100644 --- a/policyengine_uk/data/filter_dataset.py +++ b/policyengine_uk/data/filter_dataset.py @@ -3,6 +3,8 @@ import numpy as np import pandas as pd +from policyengine_uk.utils.uk_totals import add_uk_totals, uk_total_columns + if typing.TYPE_CHECKING: from policyengine_uk import Microsimulation from policyengine_uk.data import UKSingleYearDataset @@ -27,6 +29,11 @@ def filter_dataset( the values it had in sim. Private school attendance ranks incomes, so the first extract from a simulation computes its taxes and benefits. + The extract also carries the UK totals its shares of national totals are + taken by (policyengine_uk.utils.uk_totals), worked out over the whole + dataset unless it carries them already, so it keeps the shares it had in + sim rather than taking every UK total. + Parameters ---------- sim : Microsimulation @@ -43,6 +50,8 @@ def filter_dataset( """ dataset: UKSingleYearDataset = sim.dataset[year] new_dataset = dataset.copy() + if not set(uk_total_columns()) <= set(new_dataset.household.columns): + new_dataset = add_uk_totals(new_dataset) person = new_dataset.person # These are imputed across the whole population: birthdays are spread over # the year, and private school attendance follows each household's income diff --git a/policyengine_uk/tests/test_population_shares.py b/policyengine_uk/tests/test_population_shares.py index d14e70e4cc..cc7527c073 100644 --- a/policyengine_uk/tests/test_population_shares.py +++ b/policyengine_uk/tests/test_population_shares.py @@ -321,9 +321,9 @@ def hand_totals(rows): } -def population_simulation(rows, carried=None, year=YEAR, reform=SPREAD_REFORM): - """A simulation built from ``rows``, one person per household, with the UK - totals ``carried`` written on every household.""" +def population_dataset(rows, carried=None, year=YEAR): + """A dataset of ``rows``, one person per household, with the UK totals + ``carried`` written on every household.""" n = len(rows) ids = list(range(1, n + 1)) household = { @@ -339,7 +339,7 @@ def population_simulation(rows, carried=None, year=YEAR, reform=SPREAD_REFORM): household[name] = [row[name] for row in rows] for name, value in (carried or {}).items(): household[name] = [value] * n - dataset = UKSingleYearDataset( + return UKSingleYearDataset( person=pd.DataFrame( { "person_id": ids, @@ -353,7 +353,11 @@ def population_simulation(rows, carried=None, year=YEAR, reform=SPREAD_REFORM): household=pd.DataFrame(household), fiscal_year=year, ) - return Simulation(dataset=dataset, reform=reform) + + +def population_simulation(rows, carried=None, year=YEAR, reform=SPREAD_REFORM): + """A simulation built from ``population_dataset``.""" + return Simulation(dataset=population_dataset(rows, carried, year), reform=reform) def spread_values(sim, year=YEAR): @@ -456,3 +460,73 @@ def test_every_key_component_has_a_uk_total_input(): f"gov.economic_assumptions.indices.uk_totals.{growth[key]}" ) assert set(CARBON_CATEGORIES) == set(components("consumption")) + + +# The helper whoever holds the whole population calls. + + +def test_add_uk_totals_writes_each_components_weighted_total(): + from policyengine_uk.utils.uk_totals import add_uk_totals, uk_total_columns + + carrying = add_uk_totals(population_dataset(POPULATION)).household + expected = hand_totals(POPULATION) + assert set(uk_total_columns()) == set(expected) + for name, value in expected.items(): + # The same total on every household; 0 for a component no household has. + assert carrying[name].to_numpy() == pytest.approx([value] * len(POPULATION)) + assert expected["uk_total_education_consumption"] == 0 + + +def test_a_region_taken_after_add_uk_totals_gets_its_national_shares(): + """As a regional run filters rows from a dataset that carries the totals.""" + from policyengine_uk.utils.uk_totals import add_uk_totals + + whole = spread_values(population_simulation(POPULATION)) + carrying = add_uk_totals(population_dataset(POPULATION)) + wales = carrying.copy() + wales.household = wales.household[wales.household.region == "WALES"] + kept = wales.household.household_id + wales.person = wales.person[wales.person.person_household_id.isin(kept)] + wales.benunit = wales.benunit[wales.benunit.benunit_id.isin(kept)] + values = spread_values(Simulation(dataset=wales, reform=SPREAD_REFORM)) + for variable in SPREAD: + assert values[variable] == pytest.approx(whole[variable][2:], rel=1e-5), ( + variable + ) + + +def test_add_uk_totals_gives_each_year_of_a_multi_year_dataset_its_own(): + from policyengine_uk.data import UKMultiYearDataset + from policyengine_uk.utils.uk_totals import add_uk_totals + + later = [ + {**row, "household_weight": 2 * row["household_weight"]} for row in POPULATION + ] + carrying = add_uk_totals( + UKMultiYearDataset( + datasets=[ + population_dataset(POPULATION, year=2025), + population_dataset(later, year=2026), + ] + ) + ) + for year, rows in [(2025, POPULATION), (2026, later)]: + household = carrying[year].household + assert household["uk_total_corporate_wealth"].iloc[0] == pytest.approx( + hand_totals(rows)["uk_total_corporate_wealth"] + ) + + +def test_filter_dataset_extract_keeps_its_national_share(): + """An extract of one household used to take every UK total: its share was + 1 over its own weight.""" + from policyengine_uk.data.filter_dataset import filter_dataset + + whole_sim = population_simulation(POPULATION) + whole = spread_values(whole_sim) + extract = filter_dataset(whole_sim, household_id=3, year=YEAR) + values = spread_values(Simulation(dataset=extract, reform=SPREAD_REFORM)) + for variable in SPREAD: + assert values[variable] == pytest.approx(whole[variable][2:3], rel=1e-5), ( + variable + ) diff --git a/policyengine_uk/utils/uk_totals.py b/policyengine_uk/utils/uk_totals.py index 100fcf3e5e..86b42a07d0 100644 --- a/policyengine_uk/utils/uk_totals.py +++ b/policyengine_uk/utils/uk_totals.py @@ -15,7 +15,7 @@ like the column it sums, times population (create_uk_total_growth). """ -from typing import List +from typing import Dict, List import numpy as np @@ -64,3 +64,58 @@ def carried_uk_emissions(population, period, parameters) -> np.ndarray: CARBON_CATEGORIES, carbon_intensities(parameters, period) ) ) + + +def uk_total_columns() -> List[str]: + """The inputs that carry the UK totals, in key order.""" + return [total_name(component) for key in KEYS for component in components(key)] + + +def uk_totals(household) -> Dict[str, float]: + """The UK total of each key component over a table of households, at its + ``household_weight``: the values add_uk_totals writes. A table without + weights weighs each household 1, as household_weight's default does. A + component the table lacks totals 0. The table must hold every UK + household.""" + weight = ( + np.asarray(household["household_weight"], dtype=float) + if "household_weight" in household + else np.ones(len(household)) + ) + totals = {} + for key in KEYS: + for component in components(key): + values = ( + np.asarray(household[component], dtype=float) + if component in household + else np.zeros_like(weight) + ) + totals[total_name(component)] = float(np.sum(values * weight)) + return totals + + +def add_uk_totals(dataset): + """A copy of ``dataset`` whose households carry their UK totals. + + Call it on a dataset holding every UK household, before taking any part + of it: a region, an extract, a household subset or a block of a build. + The totals are written at the dataset's year, and a simulation projects + them with the data. A multi-year dataset's years each carry their own. + """ + from policyengine_uk.data.dataset_schema import ( + UKMultiYearDataset, + UKSingleYearDataset, + ) + + if isinstance(dataset, UKMultiYearDataset): + return UKMultiYearDataset( + datasets=[add_uk_totals(dataset[year]) for year in dataset.years] + ) + if not isinstance(dataset, UKSingleYearDataset): + raise TypeError( + "add_uk_totals takes a UKSingleYearDataset or UKMultiYearDataset, " + f"not {type(dataset).__name__}." + ) + new = dataset.copy() + new.household = new.household.assign(**uk_totals(new.household)) + return new From 3a41107f184c03e3cba6bad0d7bb78b54af372de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:28:49 +0000 Subject: [PATCH 4/5] Test the shares and a nation's own run on the certified dataset On a whole UK dataset the weighted shares sum to one and corporate land is the shareholding of the land corporations hold. Scotland taken alone from the dataset after add_uk_totals gets the shares, corporate land, business rates and corporate SDLT it has in the UK run (#2896). Co-Authored-By: Claude Opus 5.5 --- .../test_population_shares_data.py | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 policyengine_uk/tests/microsimulation/test_population_shares_data.py diff --git a/policyengine_uk/tests/microsimulation/test_population_shares_data.py b/policyengine_uk/tests/microsimulation/test_population_shares_data.py new file mode 100644 index 0000000000..10f71d4564 --- /dev/null +++ b/policyengine_uk/tests/microsimulation/test_population_shares_data.py @@ -0,0 +1,70 @@ +"""Shares of national totals on the certified dataset (policyengine-uk#2896). + +Over a whole UK dataset, shareholding and consumption_shareholding sum to one +at the dataset's weights. A part of the UK taken from a dataset that carries +its UK totals (add_uk_totals) gets the same allocations as in the UK run. +""" + +import numpy as np +import pytest + +from policyengine_uk import Microsimulation +from policyengine_uk.utils.uk_totals import add_uk_totals + +YEAR = 2026 +ALLOCATIONS = [ + "shareholding", + "corporate_land_value", + "business_rates", + "corporate_sdlt", +] + + +@pytest.fixture(scope="module") +def uk(): + return Microsimulation() + + +@pytest.mark.microsimulation +def test_weighted_shares_sum_to_one(uk): + weight = np.asarray(uk.calculate("household_weight", YEAR)) + for variable in ["shareholding", "consumption_shareholding"]: + share = np.asarray(uk.calculate(variable, YEAR)) + assert np.sum(share * weight) == pytest.approx(1, rel=1e-6), variable + + +@pytest.mark.microsimulation +def test_corporate_land_value_is_the_shareholding_of_corporate_land(uk): + land = uk.tax_benefit_system.parameters(f"{YEAR}-01-01").household.wealth.land + expected = ( + np.asarray(uk.calculate("shareholding", YEAR)) + * land.value.aggregate_corporate_land_value + ) + assert np.asarray(uk.calculate("corporate_land_value", YEAR)) == pytest.approx( + expected, rel=1e-6 + ) + + +@pytest.mark.microsimulation +def test_a_nation_carrying_the_uk_totals_gets_its_uk_run_allocations(uk): + dataset = add_uk_totals(uk.dataset[YEAR]) + in_scotland = (dataset.household["region"].astype(str) == "SCOTLAND").to_numpy() + scotland = dataset.copy() + scotland.household = scotland.household[in_scotland] + kept = set(scotland.household.household_id) + scotland.person = scotland.person[scotland.person.person_household_id.isin(kept)] + scotland.benunit = scotland.benunit[ + scotland.benunit.benunit_id.isin(set(scotland.person.person_benunit_id)) + ] + alone = Microsimulation(dataset=scotland) + + position = { + household_id: i + for i, household_id in enumerate(np.asarray(uk.calculate("household_id", YEAR))) + } + rows = [position[i] for i in np.asarray(alone.calculate("household_id", YEAR))] + for variable in ALLOCATIONS: + in_uk_run = np.asarray(uk.calculate(variable, YEAR))[rows] + assert np.asarray(alone.calculate(variable, YEAR)) == pytest.approx( + in_uk_run, rel=1e-4 + ), variable From 703431849840239614206cd5b3e364480ea07884 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Mon, 9 Nov 2026 20:22:26 +0000 Subject: [PATCH 5/5] Rename the shard duration entry for the renamed zero-weight test test_zero_weight_holder_uses_existing_fallback became test_zero_weighted_total_gives_no_share in this PR, and test_ci_test_shards.py requires every listed node id to exist. Co-Authored-By: Claude Opus 5.5 --- policyengine_uk/tests/shard_durations.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/policyengine_uk/tests/shard_durations.toml b/policyengine_uk/tests/shard_durations.toml index 5e04dd9d37..a37d8e587d 100644 --- a/policyengine_uk/tests/shard_durations.toml +++ b/policyengine_uk/tests/shard_durations.toml @@ -506,7 +506,7 @@ "policyengine_uk/tests/test_lha_freeze.py::test_great_britain_lha_reforms_leave_northern_ireland_rates_unchanged" = 26 "policyengine_uk/tests/test_bonus_sacrifice_properties.py::test_bonus_sacrifice_scores_like_salary_sacrifice[split-2028]" = 26 "policyengine_uk/tests/test_legacy_carer_premium_properties.py::test_scottish_caring_hours_follow_carer_support_payment" = 26 -"policyengine_uk/tests/test_weighted_incidence.py::test_zero_weight_holder_uses_existing_fallback[shareholding-expected0]" = 26 +"policyengine_uk/tests/test_weighted_incidence.py::test_zero_weighted_total_gives_no_share[shareholding]" = 26 "policyengine_uk/tests/test_dated_reform_routes.py::test_a_dict_reform_reaches_the_uc_rebalancing_inputs" = 26 "policyengine_uk/tests/test_legacy_award_readers_properties.py::test_claimant_and_partner_awards_passport_housing_benefit_income" = 25 "policyengine_uk/tests/test_dataframe_dataset.py::test_spending_on_a_small_frame_goes_to_the_deciles_it_holds[nhs]" = 25