From 5ebbf94ac29a2bad2a122786038d0ad1b1f157a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mar=C3=ADa=20Juaristi?= <127882282+juaristi22@users.noreply.github.com> Date: Thu, 26 Nov 2026 12:46:12 +0000 Subject: [PATCH] Warn on omitted microsimulation take-up inputs --- changelog.d/2916.added.md | 1 + docs/book/usage/simulations.md | 19 +- docs/engineering/skills/dataset-sources.md | 12 + policyengine_uk/microsimulation.py | 29 ++ .../tests/test_missing_takeup_inputs.py | 372 ++++++++++++++++++ 5 files changed, 432 insertions(+), 1 deletion(-) create mode 100644 changelog.d/2916.added.md create mode 100644 policyengine_uk/tests/test_missing_takeup_inputs.py diff --git a/changelog.d/2916.added.md b/changelog.d/2916.added.md new file mode 100644 index 0000000000..ff6fb2b01c --- /dev/null +++ b/changelog.d/2916.added.md @@ -0,0 +1 @@ +Added a single, optional warning when dataset-built microsimulations omit formula-less take-up inputs that default to true, without changing calculation results or household simulation behavior. diff --git a/docs/book/usage/simulations.md b/docs/book/usage/simulations.md index ac11a0337a..52fdf7eec8 100644 --- a/docs/book/usage/simulations.md +++ b/docs/book/usage/simulations.md @@ -406,7 +406,24 @@ print(f"Total UK income tax revenue: £{total_income_tax:.1f}bn") ## Microsimulation analysis -The `Microsimulation` class extends `Simulation` with survey weights for population estimates: +The `Microsimulation` class extends `Simulation` with survey weights for population estimates. + +When constructed from a dataset, `Microsimulation` emits one `UserWarning` +listing omitted Boolean `would_claim_*` inputs that have no formula and default +to `True`, such as `would_claim_uc` and `would_claim_carers_allowance`. +These calculator defaults do not establish benefit eligibility or certify +population take-up rates. Supply take-up assumptions appropriate to the dataset, +or suppress the diagnostic explicitly: + +```python +sim = Microsimulation(dataset=dataset, warn_on_missing_takeup_inputs=False) +``` + +The check counts an input as supplied if it has at least one genuine input +period, including an explicit scenario override. It does not check every year +or record, and it does not verify calibration. The warning leaves inputs and +calculation results unchanged. Plain `Simulation` and situation-built +`Microsimulation` do not emit this diagnostic. ```python from policyengine_uk import Microsimulation diff --git a/docs/engineering/skills/dataset-sources.md b/docs/engineering/skills/dataset-sources.md index f9d7a2419d..decfaf3f16 100644 --- a/docs/engineering/skills/dataset-sources.md +++ b/docs/engineering/skills/dataset-sources.md @@ -328,6 +328,18 @@ with a reporting family, so Child Tax Credit, Working Tax Credit and Income Support take-up also follow reported claims there. Explicit inputs override these defaults, including a future calibrated dataset column (uk-data#448). +Dataset-built `Microsimulation` objects also emit one construction-time +`UserWarning` naming formula-less Boolean `would_claim_*` inputs that default +to `True` and have no genuine supplied input period. The check uses the final +variable registry and readable holder input periods, so formulas, neutralized +definitions, explicit scenario inputs and DataFrame period replays are +respected; calculated caches do not count as supplied inputs. One supplied +period is enough: this is an omission-by-variable diagnostic, not a check of +every year or record or a certification of take-up calibration. It changes no +defaults, inputs or results. Pass `warn_on_missing_takeup_inputs=False` to +`Microsimulation` to suppress it. Plain `Simulation` and situation-built +`Microsimulation` do not emit this diagnostic. + Do not rebuild an existing data-built simulation by calling core's `SimulationBuilder.build_from_dict` directly. In core 3.33.2 this leaves stale dataset provenance, which copies inherit. Use UK `build_from_situation` instead. diff --git a/policyengine_uk/microsimulation.py b/policyengine_uk/microsimulation.py index 1e5e6e45d6..4497a8ce88 100644 --- a/policyengine_uk/microsimulation.py +++ b/policyengine_uk/microsimulation.py @@ -1,4 +1,5 @@ # Standard library imports +import warnings from typing import List, Optional # Third-party imports @@ -9,6 +10,7 @@ from policyengine_core.tracers import SimpleTracer from .simulation import Simulation +from .utils.data_source import built_from_data class Microsimulation(Simulation): @@ -18,6 +20,33 @@ class Microsimulation(Simulation): estimates and statistics. """ + def __init__(self, *args, warn_on_missing_takeup_inputs: bool = True, **kwargs): + """Initialize a weighted simulation and its optional take-up diagnostic.""" + super().__init__(*args, **kwargs) + + if warn_on_missing_takeup_inputs and built_from_data(self): + missing_inputs = sorted( + name + for name, variable in self.tax_benefit_system.variables.items() + if name.startswith("would_claim_") + and variable.value_type is bool + and not variable.formulas + and variable.default_value is True + and not variable.is_neutralized + and not self.get_holder(name).get_input_periods(self.branch_name) + ) + if missing_inputs: + warnings.warn( + "Dataset-built Microsimulation is using calculator take-up " + "defaults of True for inputs without supplied input periods: " + f"{', '.join(missing_inputs)}. " + "These defaults do not establish benefit eligibility or " + "certify take-up rates. Supply take-up inputs or set " + "warn_on_missing_takeup_inputs=False to suppress this warning.", + UserWarning, + stacklevel=2, + ) + def get_weights( self, variable_name: str, period: str, map_to: Optional[str] = None ) -> np.ndarray: diff --git a/policyengine_uk/tests/test_missing_takeup_inputs.py b/policyengine_uk/tests/test_missing_takeup_inputs.py new file mode 100644 index 0000000000..c73a7e78ad --- /dev/null +++ b/policyengine_uk/tests/test_missing_takeup_inputs.py @@ -0,0 +1,372 @@ +"""Missing take-up inputs are diagnosed without changing calculator defaults. + +Issue #2916 defines a variable-level diagnostic, not a calibration or per-year +completeness check. All datasets here are synthetic, with one adult per family. +""" + +import re +import warnings + +import numpy as np +import pandas as pd +import pytest +from policyengine_core.periods import period + +from policyengine_uk import Microsimulation, Simulation +from policyengine_uk.data import UKMultiYearDataset, UKSingleYearDataset +from policyengine_uk.model_api import MONTH, YEAR, BenUnit, Person, Scenario, Variable + + +pytestmark = pytest.mark.usefixtures("cloned_uk_tax_benefit_system") +YEAR_VALUE = 2025 + + +def single_year( + year=YEAR_VALUE, *, person_inputs=None, benunit_inputs=None, household_inputs=None +): + return UKSingleYearDataset( + person=pd.DataFrame( + { + "person_id": [1], + "person_benunit_id": [1], + "person_household_id": [1], + "age": [35], + "employment_income": [20_000.0], + **(person_inputs or {}), + } + ), + benunit=pd.DataFrame({"benunit_id": [1], **(benunit_inputs or {})}), + household=pd.DataFrame( + { + "household_id": [1], + "household_weight": [1.0], + "region": ["LONDON"], + "tenure_type": ["OWNED_OUTRIGHT"], + "rent": [0.0], + "council_tax": [0.0], + **(household_inputs or {}), + } + ), + fiscal_year=year, + ) + + +def data(**kwargs): + # Explicit multi-year data avoids testing projection in every warning case. + return UKMultiYearDataset(datasets=[single_year(**kwargs)]) + + +def takeup_warnings(caught): + return [ + item + for item in caught + if issubclass(item.category, UserWarning) + and "would_claim_" in str(item.message) + ] + + +def warned_names(item): + return set(re.findall(r"\bwould_claim_[a-z0-9_]+\b", str(item.message))) + + +def capture_build(**kwargs): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + simulation = Microsimulation(**kwargs) + return simulation, takeup_warnings(caught) + + +def test_single_year_dataset_emits_one_aggregated_named_warning(): + _, caught = capture_build(dataset=single_year()) + + assert len(caught) == 1 + assert caught[0].category is UserWarning + assert { + "would_claim_uc", + "would_claim_pc", + "would_claim_uc_childcare", + "would_claim_carers_allowance", + } <= warned_names(caught[0]) + assert "would_claim_student_loan" not in warned_names(caught[0]) + assert "warn_on_missing_takeup_inputs=False" in str(caught[0].message) + assert caught[0].filename == __file__ + + +@pytest.mark.parametrize( + "value", [True, False], ids=["explicit-true", "explicit-false"] +) +def test_supplied_claim_input_is_omitted_regardless_of_its_value(value): + simulation, caught = capture_build( + dataset=data(benunit_inputs={"would_claim_uc": [value]}) + ) + + assert len(caught) == 1 + assert "would_claim_uc" not in warned_names(caught[0]) + assert "would_claim_pc" in warned_names(caught[0]) + np.testing.assert_array_equal( + simulation.calculate("would_claim_uc", YEAR_VALUE), [value] + ) + + +def test_opt_out_suppresses_only_the_diagnostic(): + simulation, caught = capture_build( + dataset=data(), warn_on_missing_takeup_inputs=False + ) + + assert caught == [] + np.testing.assert_array_equal( + simulation.calculate("would_claim_uc", YEAR_VALUE), [True] + ) + + +def test_explicit_inputs_for_all_claim_flags_are_quiet(): + # Supply every prefixed variable, including irrelevant false/formula defaults. + # This does not duplicate the production diagnostic's qualification predicate. + reference = Simulation(situation={"age": {YEAR_VALUE: 35}}) + tables = {"person": {}, "benunit": {}, "household": {}} + for name, variable in reference.tax_benefit_system.variables.items(): + if name.startswith("would_claim_"): + tables[variable.entity.key][name] = [False] + assert "would_claim_uc" in tables["benunit"] + _, caught = capture_build( + dataset=data( + person_inputs=tables["person"], + benunit_inputs=tables["benunit"], + household_inputs=tables["household"], + ) + ) + + assert caught == [] + + +@pytest.mark.parametrize("simulation_class", [Simulation, Microsimulation]) +def test_household_situations_remain_quiet(simulation_class): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + simulation = simulation_class(situation={"age": {YEAR_VALUE: 35}}) + + assert takeup_warnings(caught) == [] + np.testing.assert_array_equal( + simulation.calculate("would_claim_uc", YEAR_VALUE), [True] + ) + + +def test_plain_simulation_built_from_data_remains_quiet(): + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + Simulation(dataset=data()) + + assert takeup_warnings(caught) == [] + + +def test_scenario_overrides_are_supplied_before_the_single_warning(): + def supply(simulation): + simulation.set_input("would_claim_uc", YEAR_VALUE, [False]) + + simulation, caught = capture_build( + dataset=data(), scenario=Scenario(simulation_modifier=supply) + ) + + assert len(caught) == 1 + assert "would_claim_uc" not in warned_names(caught[0]) + assert "would_claim_pc" in warned_names(caught[0]) + np.testing.assert_array_equal( + simulation.calculate("would_claim_uc", YEAR_VALUE), [False] + ) + np.testing.assert_array_equal( + simulation.baseline.calculate("would_claim_uc", YEAR_VALUE), [True] + ) + + +def test_clone_branch_and_calculations_do_not_repeat_the_warning(): + simulation, caught = capture_build(dataset=data()) + assert len(caught) == 1 + + with warnings.catch_warnings(record=True) as later: + warnings.simplefilter("always") + for copy in (simulation.clone(), simulation.get_branch()): + np.testing.assert_array_equal( + copy.calculate("would_claim_uc", YEAR_VALUE), [True] + ) + + assert takeup_warnings(later) == [] + + +def test_one_supplied_period_is_enough_in_a_sparse_multiyear_dataset(): + source = UKMultiYearDataset( + datasets=[ + single_year(benunit_inputs={"would_claim_uc": [False]}), + single_year(YEAR_VALUE + 1), + ] + ) + simulation, caught = capture_build(dataset=source) + + assert len(caught) == 1 + assert "would_claim_uc" not in warned_names(caught[0]) + assert "would_claim_pc" in warned_names(caught[0]) + np.testing.assert_array_equal( + simulation.calculate("would_claim_uc", YEAR_VALUE), [False] + ) + + +def install_probe_variables(simulation): + """Independent cases distinguish names, types, defaults and final formulas.""" + + class would_claim_future_flag(Variable): + label = "Synthetic future take-up input" + value_type = bool + entity = BenUnit + definition_period = YEAR + default_value = True + + class would_claim_false_probe(Variable): + label = "Synthetic take-up input with a false default" + value_type = bool + entity = BenUnit + definition_period = YEAR + default_value = False + + class would_claim_formula_probe(Variable): + label = "Synthetic formula-backed take-up flag" + value_type = bool + entity = BenUnit + definition_period = YEAR + default_value = True + + def formula(benunit, period, parameters): + return True + + class would_claim_number_probe(Variable): + label = "Synthetic numeric prefixed input" + value_type = int + entity = BenUnit + definition_period = YEAR + default_value = 1 + + class unrelated_true_probe(Variable): + label = "Synthetic unrelated true-default input" + value_type = bool + entity = BenUnit + definition_period = YEAR + default_value = True + + class would_claim_neutralized_probe(Variable): + label = "Synthetic neutralized take-up input" + value_type = bool + entity = BenUnit + definition_period = YEAR + default_value = True + + for definition in ( + would_claim_future_flag, + would_claim_false_probe, + would_claim_formula_probe, + would_claim_number_probe, + unrelated_true_probe, + would_claim_neutralized_probe, + ): + simulation.tax_benefit_system.add_variable(definition) + simulation.tax_benefit_system.neutralize_variable("would_claim_neutralized_probe") + simulation.tax_benefit_system.neutralize_variable("would_claim_pc") + + +def test_final_registry_discovers_new_flags_and_excludes_inapplicable_definitions(): + _, caught = capture_build( + dataset=data(), + scenario=Scenario( + simulation_modifier=install_probe_variables, applied_before_data_load=True + ), + ) + + assert len(caught) == 1 + names = warned_names(caught[0]) + assert {"would_claim_future_flag", "would_claim_uc"} <= names + assert not names & { + "would_claim_false_probe", + "would_claim_formula_probe", + "would_claim_number_probe", + "would_claim_neutralized_probe", + "would_claim_pc", + } + assert "unrelated_true_probe" not in str(caught[0].message) + + +def test_dataframe_monthly_input_replay_counts_as_supplied(): + class would_claim_monthly_probe(Variable): + label = "Synthetic monthly take-up input" + value_type = bool + entity = Person + definition_period = MONTH + default_value = True + + def install(simulation): + simulation.tax_benefit_system.add_variable(would_claim_monthly_probe) + + frame = pd.DataFrame( + { + f"person_id__{YEAR_VALUE}": [1], + f"person_benunit_id__{YEAR_VALUE}": [1], + f"person_household_id__{YEAR_VALUE}": [1], + f"benunit_id__{YEAR_VALUE}": [1], + f"household_id__{YEAR_VALUE}": [1], + f"household_weight__{YEAR_VALUE}": [1.0], + f"age__{YEAR_VALUE}": [35], + f"would_claim_monthly_probe__{YEAR_VALUE}-07": [False], + } + ) + simulation, caught = capture_build( + dataset=frame, + scenario=Scenario(simulation_modifier=install, applied_before_data_load=True), + ) + + assert len(caught) == 1 + assert "would_claim_monthly_probe" not in warned_names(caught[0]) + assert "would_claim_uc" in warned_names(caught[0]) + np.testing.assert_array_equal( + simulation.calculate("would_claim_monthly_probe", f"{YEAR_VALUE}-07"), [False] + ) + + +@pytest.mark.parametrize("cache_kind", ["default", "derived"]) +def test_cached_values_do_not_conceal_missing_inputs(monkeypatch, cache_kind): + original_init = Simulation.__init__ + + def build_then_cache(simulation, *args, **kwargs): + original_init(simulation, *args, **kwargs) + if isinstance(simulation, Microsimulation): + if cache_kind == "default": + simulation.calculate("would_claim_uc", YEAR_VALUE) + else: + simulation.get_holder("would_claim_uc").put_in_cache( + np.array([False]), period(YEAR_VALUE), derived=True + ) + + # Install a cache after normal parent construction, before the public + # Microsimulation constructor returns and emits its diagnostic. + monkeypatch.setattr(Simulation, "__init__", build_then_cache) + _, caught = capture_build(dataset=data()) + + assert len(caught) == 1 + assert "would_claim_uc" in warned_names(caught[0]) + + +def test_warning_toggle_preserves_inputs_and_representative_outputs(): + source = data(benunit_inputs={"would_claim_uc": [False]}) + enabled, caught = capture_build(dataset=source) + disabled, quiet = capture_build(dataset=source, warn_on_missing_takeup_inputs=False) + assert len(caught) == 1 + assert quiet == [] + + for name in ( + "would_claim_uc", + "would_claim_pc", + "employment_income", + "income_tax", + "universal_credit", + "household_net_income", + ): + np.testing.assert_array_equal( + enabled.calculate(name, YEAR_VALUE), disabled.calculate(name, YEAR_VALUE) + ) + assert source[YEAR_VALUE].benunit["would_claim_uc"].tolist() == [False] + assert source[YEAR_VALUE].person["employment_income"].tolist() == [20_000.0]