Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/781.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
US simulations built from a dataset (`Simulation(dataset=...)`) list every stored ID and dataset column in the country simulation's `input_variables`, for the reform simulation and its baseline. Since 6.0.0 the US model constructs the country simulation empty and stores the dataset afterwards, and policyengine-core fills the list only at construction, so it held none of the dataset's ordinary columns: only mapped legacy inputs and legacy SPM declarations were listed, plus, in the reform simulation, the five behavioral-response inputs policyengine-us always adds (such as `employment_income_before_lsr`). `marginal_tax_rate` calculates in a copy of the simulation after deleting every value whose variable is not listed, so its copies lost age, location, Social Security and the other dataset inputs. A 67-year-old in Wake County, North Carolina, with $15,000 of earnings and $24,000 of Social Security in 2026 had a `marginal_tax_rate` of 23.64 and a `cliff_gap` of $22,645, against policyengine-us's 0.1174 and $0. A 40-year-old there with $40,000 of earnings, under a reform that raises the 12 % rate to 17 % with a labor-supply substitution elasticity of 0.25, had a labor-supply response of -$591.09, against policyengine-us's -$655.38. Both households now get policyengine-us's values. The federal, state and FICA marginal rates, `marginal_tax_rate_including_health_benefits`, and the variables that attribute income tax revenue to the Social Security and Medicare trust funds (`tob_revenue_total` and the others) delete unlisted values in the same way, so they change too.
8 changes: 5 additions & 3 deletions src/policyengine/tax_benefit_models/us/legacy_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -633,12 +633,14 @@ def _periods_of_year(year: int, definition_period: Any, context: str) -> list[st


def _record_input_variables(simulation, live_names: Iterable[str]) -> None:
"""List mapped inputs as inputs, as if the dataset had stored them.
"""List inputs stored after construction in ``input_variables``.

A country Microsimulation lists ``input_variables`` once, at construction.
Dataset extraction (``create_datasets``) exports that list, and
policyengine-core's ``derivative`` keeps only those inputs in its clone, so
a mapped input must join it.
policyengine-us formulas that calculate in a copy of the simulation (such
as ``marginal_tax_rate``) delete values whose variables are not in it from
the copy. So an input stored later (a mapped input, an SPM declaration, or
a dataset column stored by ``PolicyEngineUSLatest.run``) must join it.
"""
input_variables = getattr(simulation, "input_variables", None)
if not isinstance(input_variables, list):
Expand Down
15 changes: 15 additions & 0 deletions src/policyengine/tax_benefit_models/us/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
from .datasets import PolicyEngineUSDataset, USYearData, _validate_entity_ids
from .legacy_inputs import (
RENAMES_RECORD_KEY,
_record_input_variables,
apply_legacy_input_renames,
apply_legacy_input_renames_to_microsimulation,
)
Expand Down Expand Up @@ -393,6 +394,10 @@ def _build_simulation_from_dataset(self, microsim, dataset, system):
Stored columns the engine has since renamed are mapped onto their
live inputs (see ``legacy_inputs.LEGACY_INPUT_RENAMES``).

Every ID and dataset column it stores is added to
``microsim.input_variables``, which policyengine-core fills only at
construction, before any of them is stored.

Returns:
The legacy input renames applied, ``{legacy: live}``.
"""
Expand Down Expand Up @@ -517,6 +522,7 @@ def _build_simulation_from_dataset(self, microsim, dataset, system):
}

stored_tables = {}
stored_inputs: list[str] = []
for entity_name, entity_df in [
("person", dataset.data.person),
("household", dataset.data.household),
Expand All @@ -543,9 +549,18 @@ def _build_simulation_from_dataset(self, microsim, dataset, system):
for live_name, column in live_ids.items():
if live_name in system.variables:
microsim.set_input(live_name, dataset.year, df[column].values)
stored_inputs.append(live_name)
for column in df.columns:
if column not in id_columns and column in system.variables:
microsim.set_input(column, dataset.year, df[column].values)
stored_inputs.append(column)

# policyengine-core lists ``input_variables`` only at construction, and
# this simulation was constructed empty. ``marginal_tax_rate`` (and
# through it ``cliff_gap`` and the labor-supply response) calculates
# in a copy of the simulation after deleting every value whose
# variable is not listed, so list what was stored (#781).
_record_input_variables(microsim, stored_inputs)

# The loop above skips columns the engine does not define, including
# stored inputs it has since renamed. The tables are already in the
Expand Down
241 changes: 241 additions & 0 deletions tests/test_us_dataset_input_variables.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
"""US simulations built from a dataset list the dataset's columns as inputs.

policyengine-core fills ``Simulation.input_variables`` once, at construction,
from the variables that hold values then. ``PolicyEngineUSLatest.run``
constructs the country simulation empty and stores the dataset's columns
afterwards, so it has to list them itself. Several policyengine-us formulas
(``marginal_tax_rate``, and through it ``cliff_gap`` and the labor-supply
response) calculate in a copy of the simulation, after deleting from the copy
every stored value whose variable is not listed
(PolicyEngine/policyengine.py#781).

Each test builds one single adult living alone in Wake County, North
Carolina, in 2026, and runs it through ``Simulation(dataset=...)``. The first
checks the country simulations' ``input_variables`` directly. The others
compare the results with policyengine-us's own ``Simulation(situation=...)``
for the same inputs, which lists every input at construction.
"""

from __future__ import annotations

import pandas as pd
import pytest
from microdf import MicroDataFrame

pytest.importorskip("policyengine_us")
pytest.importorskip("spm_calculator.policyengine_adapter")

import policyengine as pe # noqa: E402
from policyengine.core import Simulation # noqa: E402
from policyengine.tax_benefit_models.us.datasets import ( # noqa: E402
PolicyEngineUSDataset,
USYearData,
)
from policyengine.tax_benefit_models.us.model import ( # noqa: E402
PolicyEngineUSLatest,
)

YEAR = 2026
NORTH_CAROLINA_STATE_FIPS = 37
WAKE_COUNTY_FIPS = "37183"
GROUP_ENTITIES = ("household", "tax_unit", "spm_unit", "family", "marital_unit")
ENTITIES = ("person", *GROUP_ENTITIES)

#: A retiree who still works: Social Security is most of the household's
#: income, so a copy of the simulation that loses it shows a large cliff.
RETIREE = {
"age": 67,
"employment_income_before_lsr": 15_000.0,
"social_security_retirement": 24_000.0,
}
#: A worker whose top dollar of earnings pays the 12 % federal rate.
WORKER = {
"age": 40,
"employment_income_before_lsr": 40_000.0,
"taxable_interest_income": 10_000.0,
}

REFORM_PERIOD = f"{YEAR}-01-01.2100-12-31"
#: Raises the 12 % federal income tax rate to 17 %.
HIGHER_RATE = {"gov.irs.income.bracket.rates.2": {REFORM_PERIOD: 0.17}}
#: The same, with labor-supply responses turned on: a substitution
#: elasticity of 0.25 for everyone.
HIGHER_RATE_WITH_LABOR_SUPPLY_RESPONSES = {
**HIGHER_RATE,
"gov.simulation.labor_supply_responses.elasticities.substitution.all": {
REFORM_PERIOD: 0.25
},
}
#: Inputs policyengine-us's ``Microsimulation.__init__`` adds to a
#: simulation's ``input_variables`` whether or not anything stores them.
POLICYENGINE_US_ADDED_INPUTS = {
"employment_income_before_lsr",
"self_employment_income_before_lsr",
"sstb_self_employment_income_before_lsr",
"weekly_hours_worked_before_lsr",
"long_term_capital_gains_before_response",
}


def _one_adult_dataset(person_inputs: dict[str, float]) -> PolicyEngineUSDataset:
"""Native entity tables for one adult who is every group's only member."""
person = pd.DataFrame(
{
"person_id": [1],
**{f"person_{entity}_id": [1] for entity in GROUP_ENTITIES},
"person_weight": [1.0],
**{name: [value] for name, value in person_inputs.items()},
}
)
household = pd.DataFrame(
{
"household_id": [1],
"household_weight": [1.0],
"state_fips": [NORTH_CAROLINA_STATE_FIPS],
"county_fips": [WAKE_COUNTY_FIPS],
}
)
tables = {
"person": MicroDataFrame(person, weights="person_weight"),
"household": MicroDataFrame(household, weights="household_weight"),
}
for entity in GROUP_ENTITIES[1:]:
tables[entity] = MicroDataFrame(
pd.DataFrame({f"{entity}_id": [1], f"{entity}_weight": [1.0]}),
weights=f"{entity}_weight",
)
return PolicyEngineUSDataset(
id="one-adult-wake-county",
name="one-adult-wake-county",
description="One adult living alone in Wake County, North Carolina",
filepath=None,
year=YEAR,
data=USYearData(**tables),
)


def _dataset_person_values(
person_inputs: dict[str, float],
person_outputs: tuple[str, ...],
policy: dict | None = None,
) -> dict[str, float]:
"""The adult's outputs through .py's ``Simulation(dataset=...)``."""
simulation = Simulation(
dataset=_one_adult_dataset(person_inputs),
tax_benefit_model_version=pe.us.model,
policy=policy,
extra_variables={"person": list(person_outputs)},
)
simulation.run()
person = pd.DataFrame(simulation.output_dataset.data.person)
return {name: float(person[name].iloc[0]) for name in person_outputs}


def _situation_person_values(
person_inputs: dict[str, float],
person_outputs: tuple[str, ...],
reform: dict | None = None,
) -> dict[str, float]:
"""The adult's outputs through policyengine-us's ``Simulation(situation=...)``."""
from policyengine_us import Simulation as CountrySimulation

situation = {
"people": {
"adult": {name: {YEAR: value} for name, value in person_inputs.items()}
},
"tax_units": {"tax_unit": {"members": ["adult"]}},
"spm_units": {"spm_unit": {"members": ["adult"]}},
"families": {"family": {"members": ["adult"]}},
"marital_units": {"marital_unit": {"members": ["adult"]}},
"households": {
"household": {
"members": ["adult"],
"state_fips": {YEAR: NORTH_CAROLINA_STATE_FIPS},
"county_fips": {YEAR: WAKE_COUNTY_FIPS},
}
},
}
country_simulation = CountrySimulation(situation=situation, reform=reform)
return {
name: float(country_simulation.calculate(name, YEAR)[0])
for name in person_outputs
}


def test_reform_and_baseline_list_every_stored_dataset_column_as_an_input(
monkeypatch,
):
built_simulations = []
build_simulation_from_dataset = PolicyEngineUSLatest._build_simulation_from_dataset

def build_and_keep(self, microsim, dataset, system):
renames = build_simulation_from_dataset(self, microsim, dataset, system)
built_simulations.append(microsim)
return renames

monkeypatch.setattr(
PolicyEngineUSLatest, "_build_simulation_from_dataset", build_and_keep
)
simulation = Simulation(
dataset=_one_adult_dataset(RETIREE),
tax_benefit_model_version=pe.us.model,
policy=HIGHER_RATE,
)
simulation.run()

# ``run`` builds the reform's baseline first, then the reform.
baseline, reform = built_simulations
assert baseline is reform.baseline
# Recording the dataset's columns keeps what the list already held.
assert POLICYENGINE_US_ADDED_INPUTS <= set(reform.input_variables)
for country_simulation in (baseline, reform):
variables = country_simulation.tax_benefit_system.variables
stored_columns = {
column
for entity in ENTITIES
for column in pd.DataFrame(getattr(simulation.dataset.data, entity))
if column in variables
}
assert {
"person_id",
"person_household_id",
"household_weight",
"age",
"employment_income_before_lsr",
"social_security_retirement",
"state_fips",
"county_fips",
} <= stored_columns
missing = stored_columns - set(country_simulation.input_variables)
assert not missing, (
f"{country_simulation.branch_name}: stored dataset columns missing "
f"from input_variables: {sorted(missing)}"
)


def test_retiree_cliff_gap_and_marginal_tax_rate_match_policyengine_us():
outputs = ("marginal_tax_rate", "cliff_gap")
from_situation = _situation_person_values(RETIREE, outputs)
from_dataset = _dataset_person_values(RETIREE, outputs)

assert from_situation["cliff_gap"] == 0
assert from_dataset["cliff_gap"] == pytest.approx(0, abs=0.01)
assert from_dataset["marginal_tax_rate"] == pytest.approx(
from_situation["marginal_tax_rate"], abs=1e-4
)


def test_labor_supply_response_matches_policyengine_us():
outputs = ("employment_income_behavioral_response",)
from_situation = _situation_person_values(
WORKER, outputs, reform=HIGHER_RATE_WITH_LABOR_SUPPLY_RESPONSES
)
from_dataset = _dataset_person_values(
WORKER, outputs, policy=HIGHER_RATE_WITH_LABOR_SUPPLY_RESPONSES
)

response = "employment_income_behavioral_response"
# A higher marginal rate with a positive substitution elasticity lowers
# earnings.
assert from_situation[response] < 0
assert from_dataset[response] == pytest.approx(from_situation[response], abs=0.01)