diff --git a/Makefile b/Makefile index 5a5e25e16ec..866b0a06943 100644 --- a/Makefile +++ b/Makefile @@ -97,13 +97,14 @@ REST_SOCIAL_SECURITY_PIA_RATIO_INPUT_TESTS := $(TESTS)/core/test_ss_pia_ratio_in # a default Microsimulation only to read parameters. Release their heap before # the remaining policy tests, rather than stacking both in the 13.9 GB group. REST_POLICY_PARAMETER_TESTS := $(TESTS)/policy/baseline/parameters -# The first four files retain three independent full systems (the two CTC +# The first five files retain four independent full systems (the two CTC # files share one). The last two use transient TX simulations and balance # elapsed time without warming the NY/AL pinned-system cache. REST_REMAINING_HEAVY_TESTS := $(TESTS)/test_niit_section_911_magi.py \ $(TESTS)/test_ctc_foreign_earned_income_exclusion.py \ $(TESTS)/test_ctc_foreign_earned_income_exclusion_property.py \ $(TESTS)/unit/test_medicaid_abd_ssi_rate_standard_properties.py \ + $(TESTS)/test_spm_child_care_subsidy_invariants.py \ $(TESTS)/test_capital_gain_distributions_loss_limit.py \ $(TESTS)/test_schedule_d_filer_net_capital_gain.py REST_LISTED_TESTS := $(REST_CACHED_ARRAY_TESTS) $(REST_HEAVY_A_TESTS) $(REST_HEAVY_B_TESTS) \ diff --git a/changelog.d/spm-child-care-subsidies.fixed.md b/changelog.d/spm-child-care-subsidies.fixed.md new file mode 100644 index 00000000000..e90c1c08ccb --- /dev/null +++ b/changelog.d/spm-child-care-subsidies.fixed.md @@ -0,0 +1 @@ +Count every state child care subsidy in the Supplemental Poverty Measure from 2024 by netting it from the SPM child care expense in household calculations, keep the ASEC's reported spending as that expense over a dataset while a reform moves it by the change in subsidy, and add the District of Columbia, Tennessee and Texas subsidies to the 2024 program list. Rebuild a reform's baseline arm without the holders the reform built for its own definition of a variable in another entity or with other ETERNITY storage, as core's own branch does, and raise an error naming the variable when that rebuild would drop an input the caller gave. Give a subsampled branch of a reform simulation its own baseline arm on its sample, and raise an error when a simulation named "baseline" with a baseline arm subsamples, as core would give it baseline policy and drop its arm. Keep the dataset reading of the expense in a simulation built from a snapshot or extracted situation of a dataset simulation and in its baseline arm, which also gets the snapshot's overrides, and in a simulation restored from a dump of one. diff --git a/docs/social-security-benefit-levers.md b/docs/social-security-benefit-levers.md index c09263434b6..49aa5b9aa55 100644 --- a/docs/social-security-benefit-levers.md +++ b/docs/social-security-benefit-levers.md @@ -57,12 +57,46 @@ factors once, and perform their earnings test on the resulting payable amount. exports all recorded pure-input periods and entity memberships as `sources`, with supplied formula-variable values in a separate `overrides` payload. Cached calculations are excluded. `reload_source_inputs(payload, ...)` restores sources -before final overrides. Core's legacy `extract_person` retains every recorded -input period for the four benefit components and their reported twins, excluding -formula caches. This keeps later overrides final on reload and preserves their -source histories and future uprating. Other variables keep Core's usual first -known period. Neither interface settles the separate API/application metadata -and field-exposure contract. +before final overrides. A snapshot of a simulation over a dataset also carries +`"_dataset_inputs": true`, so the reloaded simulation, its baseline arm and its +later branches read `spm_unit_capped_work_childcare_expenses` as a dataset +simulation does; other dataset-only rules, such as county, read the reload as +a household. Core gives a dataset's values to a reform's baseline arm too, so a +marked reload sets each override on its arm as well. For a reform simulation +whose inputs came from a dataset, `export_source_inputs` compares each +override with the input its arm records. Where they differ, as they do for a +value a caller set on the reform after construction, the snapshot lists the +arm's input under `"_baseline_arm_overrides"`, or null where the arm records +none. A marked reload gives its arm each listed input in place of the +override and skips a null one. A pure input or a Social Security component +that a caller sets on a reform simulation after construction reaches both +sides of the reload, though the source's arm lacks it. The pure input travels +in `sources`, and the component travels in the provenance envelope even where +the snapshot lists it as null. A marked snapshot of a simulation with no arm +carries no `"_baseline_arm_overrides"`, so a reload with `reform=` gives its +arm every override. A marked reload skips a variable that baseline policy +doesn't define. It raises, naming the variable, when the arm would get a value +that the reform stores in another entity or with other ETERNITY storage, as a +reform built over the dataset does. A reload raises `ValueError` when the +snapshot's `_dataset_inputs` key holds anything but true or false. The payload +stays at version 1, and a snapshot without the key reloads as a household. +Core's legacy +`extract_person` retains every recorded input period for the four benefit +components and their reported twins, excluding formula caches. This keeps later +overrides final on reload and preserves their source histories and future +uprating. Other variables keep Core's usual first known period. A situation +extracted from a dataset simulation carries the same key, and like the +provenance envelope it loads only through this package's builders. A reform +rebuilt from a situation that `extract_person` or `sample_person` took from a +reform simulation gives its arm the reform side's values. So its arm also takes +a formula value a caller set on the reform after construction, where a marked +snapshot's arm keeps the source arm's value. Neither interface settles the +separate API/application metadata and field-exposure contract. A dump of a +dataset simulation through Core's `dump_simulation` holds the mark, as JSON +true, in `__entities__/dataset_inputs.json`. Core's +`restore_simulation` builds no baseline arm, so where a simulation it restores +from that dump calculates the expense, it reads it as a dataset simulation with +no arm does. An expense the dump already holds comes back as dumped. Annual benefit inputs retain Core's period normalization. For example, supplying `social_security_retirement: {"2024-07": 500}` through a PE-US constructor stores diff --git a/policyengine_us/parameters/gov/hhs/ccdf/child_care_subsidy_programs.yaml b/policyengine_us/parameters/gov/hhs/ccdf/child_care_subsidy_programs.yaml index 23ed336402b..6461d03490d 100644 --- a/policyengine_us/parameters/gov/hhs/ccdf/child_care_subsidy_programs.yaml +++ b/policyengine_us/parameters/gov/hhs/ccdf/child_care_subsidy_programs.yaml @@ -96,58 +96,9 @@ values: - nc_child_care_subsidies # North Carolina Subsidized Child Care Assistance - wy_child_care_subsidies # Wyoming Child Care, Purchase of Service - ny_child_care_subsidies # New York Child Care Assistance Program - 2025-01-01: - - ak_child_care_subsidies # Alaska Child Care Assistance Program (PASS) - - ar_child_care_subsidies # Arkansas School Readiness Assistance - - al_child_care_subsidies # Alabama Child Care Subsidy Program - - az_child_care_subsidies # Arizona Child Care Assistance Program - - ca_child_care_subsidies # California Child Care - - co_child_care_subsidies # Colorado Child Care Assistance Program - - ct_child_care_subsidies # Connecticut Care 4 Kids - - de_child_care_subsidies # Delaware Purchase of Care - - fl_child_care_subsidies # Florida School Readiness Program (SR) - - ga_child_care_subsidies # Georgia Childcare and Parent Services - - hi_child_care_subsidies # Hawaii Child Care Subsidy - - ia_child_care_subsidies # Iowa Child Care Assistance - - id_child_care_subsidies # Idaho Child Care Program - - il_child_care_subsidies # Illinois Child Care Assistance Program - - in_child_care_subsidies # Indiana Child Care and Development Fund Voucher Program - - ks_child_care_subsidies # Kansas Child Care Assistance Program - - ky_child_care_subsidies # Kentucky Child Care Assistance Program - - la_child_care_subsidies # Louisiana Child Care Assistance Program - - ma_child_care_subsidies # Massachusetts Child Care Financial Assistance - - md_child_care_subsidies # Maryland Child Care Scholarship - - me_child_care_subsidies # Maine Child Care Affordability Program - - mi_child_care_subsidies # Michigan Child Development and Care program - - mn_child_care_subsidies # Minnesota Child Care Assistance Program - - mo_child_care_subsidies # Missouri Child Care Subsidy - - ms_child_care_subsidies # Mississippi Child Care Payment Program (CCPP) - - mt_child_care_subsidies # Montana Best Beginnings Child Care Scholarship - - ne_child_care_subsidies # Nebraska Child Care Subsidy - - nm_child_care_subsidies # New Mexico Child Care Assistance Program - - vt_child_care_subsidies # Vermont Child Care Financial Assistance Program - - nh_child_care_subsidies # New Hampshire Child Care Scholarship Program - - pa_child_care_subsidies # Pennsylvania Child Care Works - - nj_child_care_subsidies # New Jersey Child Care Assistance Program - - oh_child_care_subsidies # Ohio Publicly Funded Child Care - - nv_child_care_subsidies # Nevada Child Care and Development Program (CCDP) - - or_child_care_subsidies # Oregon Employment Related Day Care - - ri_child_care_subsidies # Rhode Island Child Care Assistance Program - - sc_child_care_subsidies # South Carolina Child Care Scholarship Program - - ut_child_care_subsidies # Utah Child Care Assistance (CC) - - va_child_care_subsidies # Virginia Child Care Subsidy Program - - wa_child_care_subsidies # Washington Working Connections Child Care - - wi_child_care_subsidies # Wisconsin Shares Child Care Subsidy Program - - wv_child_care_subsidies # West Virginia Child Care Assistance Program - - nd_child_care_subsidies # North Dakota Child Care Assistance Program - - ok_child_care_subsidies # Oklahoma Child Care Subsidy Program - - sd_child_care_subsidies # South Dakota Child Care Assistance (CCA) - - nc_child_care_subsidies # North Carolina Subsidized Child Care Assistance - dc_child_care_subsidies # DC Child Care Subsidy Program - tn_child_care_subsidies # Tennessee Child Care Certificate Program (Smart Steps) - - wy_child_care_subsidies # Wyoming Child Care, Purchase of Service - tx_child_care_subsidies # Texas Child Care Services (CCS) - - ny_child_care_subsidies # New York Child Care Assistance Program metadata: unit: list diff --git a/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py b/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py index c1e40a448dd..12f112f52c2 100644 --- a/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py +++ b/policyengine_us/reforms/congress/tlaib/boost/boost_middle_class_tax_credit.py @@ -110,7 +110,6 @@ def formula(spm_unit, period, parameters): # California programs. "ca_cvrp", # California Clean Vehicle Rebate Project. # Colorado programs. - "co_ccap_subsidy", "co_state_supplement", "co_oap", "snap", @@ -148,6 +147,12 @@ def formula(spm_unit, period, parameters): BENEFITS.append("aca_ptc") if not parameters(period).gov.hud.abolition: BENEFITS.append("spm_unit_capped_housing_subsidy") + # From 2024, child care subsidies lower the expense in + # spm_unit_capped_work_childcare_expenses instead of adding to + # resources. That expense has no formula before 2024, so this one + # stays a resource until then. + if period.start.year < 2024: + BENEFITS.append("co_ccap_subsidy") p = parameters( period ).gov.contrib.congress.tlaib.boost.middle_class_tax_credit diff --git a/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py b/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py index 314b07e6203..82bfb1c8e4a 100644 --- a/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py +++ b/policyengine_us/reforms/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.py @@ -119,7 +119,6 @@ def formula(spm_unit, period, parameters): "ssi", "ma_state_supplement", "ca_cvrp", - "co_ccap_subsidy", "co_state_supplement", "co_oap", "snap", @@ -160,6 +159,12 @@ def formula(spm_unit, period, parameters): BENEFITS.append("aca_ptc") if not parameters(period).gov.hud.abolition: BENEFITS.append("spm_unit_capped_housing_subsidy") + # From 2024, child care subsidies lower the expense in + # spm_unit_capped_work_childcare_expenses instead of adding to + # resources. That expense has no formula before 2024, so this one + # stays a resource until then. + if period.start.year < 2024: + BENEFITS.append("co_ccap_subsidy") return add(spm_unit, period, BENEFITS) diff --git a/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py b/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py index c925dac718a..03f6035ce8b 100644 --- a/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py +++ b/policyengine_us/reforms/congress/tlaib/end_child_poverty_act.py @@ -138,7 +138,6 @@ def formula(spm_unit, period, parameters): # California programs. "ca_cvrp", # California Clean Vehicle Rebate Project. # Colorado programs. - "co_ccap_subsidy", "co_state_supplement", "co_oap", "snap", @@ -177,6 +176,12 @@ def formula(spm_unit, period, parameters): BENEFITS.append("aca_ptc") if not parameters(period).gov.hud.abolition: BENEFITS.append("spm_unit_capped_housing_subsidy") + # From 2024, child care subsidies lower the expense in + # spm_unit_capped_work_childcare_expenses instead of adding to + # resources. That expense has no formula before 2024, so this one + # stays a resource until then. + if period.start.year < 2024: + BENEFITS.append("co_ccap_subsidy") return add(spm_unit, period, BENEFITS) class income_tax_refundable_credits(Variable): diff --git a/policyengine_us/reforms/states/tx/rebate/tx_rebate.py b/policyengine_us/reforms/states/tx/rebate/tx_rebate.py index 4c2ccf257c4..933ca934203 100644 --- a/policyengine_us/reforms/states/tx/rebate/tx_rebate.py +++ b/policyengine_us/reforms/states/tx/rebate/tx_rebate.py @@ -77,19 +77,14 @@ def formula(spm_unit, period, parameters): # California programs. "ca_cvrp", # California Clean Vehicle Rebate Project. # Colorado programs. - "co_ccap_subsidy", "co_state_supplement", "co_oap", - # Washington programs. - "wa_child_care_subsidies", # New Mexico programs. "nm_ssi_state_supplement", # South Carolina programs. "sc_ssi_state_supplement", # Texas programs. "tx_ssi_state_supplement", - # West Virginia programs. - "wv_child_care_subsidies", "snap", "wic", "free_school_meals", @@ -132,6 +127,18 @@ def formula(spm_unit, period, parameters): BENEFITS.append("assigned_aca_ptc") if not parameters(period).gov.hud.abolition: BENEFITS.append("spm_unit_capped_housing_subsidy") + # From 2024, child care subsidies lower the expense in + # spm_unit_capped_work_childcare_expenses instead of adding to + # resources. That expense has no formula before 2024, so these + # three stay resources until then. + if period.start.year < 2024: + BENEFITS.extend( + [ + "co_ccap_subsidy", + "wa_child_care_subsidies", + "wv_child_care_subsidies", + ] + ) return add(spm_unit, period, BENEFITS) class reform(Reform): diff --git a/policyengine_us/spm.py b/policyengine_us/spm.py index a1629a3f8ff..1f2f0da61ea 100644 --- a/policyengine_us/spm.py +++ b/policyengine_us/spm.py @@ -769,6 +769,17 @@ def pin_spm_policy(system): ) +def _built_for_another_policy(variable, population, holder): + """Whether ``variable`` cannot use ``holder``, which sits in ``population``: + the holder is in another entity's population, or has storage for (or not + for) an ``ETERNITY`` variable.""" + return variable is not None and ( + variable.entity.key != population.entity.key + or (variable.definition_period == periods_.ETERNITY) + != holder._memory_storage.is_eternal + ) + + class SPMSimulationMixin: """Keep forecast selection and receipts private to each simulation.""" @@ -777,6 +788,7 @@ def __init__(self, *args, **kwargs): # Core switches the baseline system after cloning its populations. baseline = self.branches.get("baseline") if baseline is not None: + baseline._refuse_inputs_baseline_policy_drops() baseline._drop_holders_built_for_another_policy() self._rebind_holders() # Core sets ``trace`` before this simulation owns its policy state. @@ -857,20 +869,21 @@ def _drop_holders_built_for_another_policy(self): ``ETERNITY`` variable, therefore cannot hold the baseline's definition. Drop it with its recorded inputs, as core 3.32.21 and later do in ``_bind_to_tax_benefit_system``; core 3.32.8 keeps it. - - Only a baseline arm does this. ``apply_reform`` keeps a simulation's - own inputs, as core's does. + The arm then calculates such a variable. Where it would drop an input + it holds a key for, a baseline arm first refuses it + (``_refuse_inputs_baseline_policy_drops``); the behavioural-response + measurement branch drops it and calculates the variable, as on main. + + A simulation given a reform by ``apply_reform`` does not call this: + core's own ``_bind_to_tax_benefit_system`` drops a holder the new + definition cannot use, with its recorded inputs, and keeps every + other input. """ variables = self.tax_benefit_system.variables dropped = set() for population in self.populations.values(): for name, holder in list(population._holders.items()): - variable = variables.get(name) - if variable is not None and ( - variable.entity.key != population.entity.key - or (variable.definition_period == periods_.ETERNITY) - != holder._memory_storage.is_eternal - ): + if _built_for_another_policy(variables.get(name), population, holder): del population._holders[name] dropped.add(name) if dropped: @@ -881,6 +894,44 @@ def _drop_holders_built_for_another_policy(self): name for name in self.input_variables if name not in dropped ] + def _refuse_inputs_baseline_policy_drops(self): + """Raise, naming each variable, if this baseline arm drops an input. + + The arm drops each holder built for the reform's definition of a + variable that baseline policy's definition cannot use, with its + inputs, and calculates the variable + (``_drop_holders_built_for_another_policy``). Where the caller gave + that variable an input, the arm, and the S0 the dataset rule reads + from it, would rest on a value the caller never gave, so refuse it. + + This reads the arm's own holders and core's record of the arm's + inputs, ``_user_input_keys``, and matches a recorded input by + variable name alone: the keys the arm copied from the reform keep the + reform's branch name. Only the country simulations' rebuild of the arm + at the end of construction (``system._rebuild_baseline_branch``) + hands this an arm that still holds such a holder with its keys. Where + core builds the arm, in construction and in ``subsample``, its + ``_bind_to_tax_benefit_system`` has already dropped both, so an input + set after construction and then subsampled is dropped and calculated, + as on main. + """ + variables = self.tax_benefit_system.variables + recorded = {key[0] for key in getattr(self, "_user_input_keys", ())} + names = sorted( + name + for population in self.populations.values() + for name, holder in population._holders.items() + if name in recorded + and _built_for_another_policy(variables.get(name), population, holder) + ) + if names: + raise ValueError( + f"Baseline policy cannot hold the input given for {', '.join(names)}: " + "the reform defines it in another entity or with other ETERNITY " + "storage than baseline policy, so the reform's baseline arm would " + "calculate it in place of the input." + ) + def apply_reform(self, reform): policy = self.tax_benefit_system detaching = getattr(policy, "detaching_parameters", None) @@ -1123,7 +1174,46 @@ def _simulation_family(self): yield from branch._simulation_family() def subsample(self, *args, **kwargs): - result = super().subsample(*args, **kwargs) + if ( + self.branch_name == "baseline" + and getattr(self, "baseline", None) is not None + ): + # Core rebuilds the arm with get_branch("baseline"), which returns + # the simulation itself when that is its own name. A branch named + # "baseline" with an arm would then take baseline policy and lose + # its arm, so refuse before anything changes. + raise ValueError( + 'A simulation named "baseline" with a baseline arm cannot ' + 'subsample. Core rebuilds the arm as the branch named "baseline", ' + "and that name returns this simulation, so it would take " + "baseline policy and lose its arm. Name the branch something " + 'else, such as get_branch("trial"), and subsample that.' + ) + inherited = getattr(self, "baseline", None) + had_entry = "baseline" in self.branches + previous = self.branches.get("baseline") + arm_copy = None + if inherited is not None and previous is not inherited: + # Core rebuilds an arm only from ``branches["baseline"]``. A branch + # shares its parent's arm, on the parent's population, and holds + # nothing there or something other than its arm, such as a + # calculation branch the caller named "baseline". Hand core a copy + # of the arm, whose policy it gives the arm it builds on this + # branch's sample. Core's subsample drops every other calculation + # branch, and this drops whatever the copy replaces. + arm_copy = inherited.clone(clone_tax_benefit_system=False) + self.branches["baseline"] = arm_copy + try: + result = super().subsample(*args, **kwargs) + except BaseException: + # Where core raises with the copy still in place, put back what + # the branch held before, and leave the rest as core left it. + if arm_copy is not None and self.branches.get("baseline") is arm_copy: + if had_entry: + self.branches["baseline"] = previous + else: + del self.branches["baseline"] + raise baseline = self.branches.get("baseline") if baseline is not None: # Core rebuilds the baseline arm by branching this simulation, so @@ -1139,6 +1229,7 @@ def subsample(self, *args, **kwargs): # behavioural responses, holders bound to its own policy, and that # policy's tracing primed for this arm. baseline.baseline = None + baseline._refuse_inputs_baseline_policy_drops() baseline._drop_holders_built_for_another_policy() baseline._rebind_holders() baseline._isolate_parameter_tracing() diff --git a/policyengine_us/system.py b/policyengine_us/system.py index a732006d8ed..566d29fe61b 100644 --- a/policyengine_us/system.py +++ b/policyengine_us/system.py @@ -516,7 +516,11 @@ def _rebuild_baseline_branch(simulation): ``input_variables``. Its TANF counted no earnings, and the baseline marginal tax rate that labor supply responses compare against erased pre-response wages. Branching again from the simulation, as core's - ``subsample`` does, gives the baseline the same inputs as the reform. + ``subsample`` does, gives the baseline the same inputs as the reform, + except those the reform stored for its own definition of a variable in + another entity or with other ``ETERNITY`` storage, which core's branch + dropped too. Where it would drop such an input, it raises instead, + naming the variable (``_refuse_inputs_baseline_policy_drops``). """ baseline = simulation.branches.pop("baseline", None) if baseline is None: @@ -529,7 +533,15 @@ def _rebuild_baseline_branch(simulation): rebuilt.tracer = simulation.tracer rebuilt.tax_benefit_system = baseline.tax_benefit_system # Cloning bound holders to reform variables. Restoring policy must also - # restore those bindings and remove inputs that exist only in the reform. + # drop holders whose entity or storage the baseline's variables cannot + # use, restore the other bindings and remove inputs that exist only in + # the reform. A kept holder would hand the baseline the reform's input: + # under a reform that stores ``child_care_subsidies`` for all time, the + # baseline read that input in place of its own formula. A dropped holder + # takes its inputs with it, and the baseline would calculate one the + # caller gave, so it refuses such an input first. + rebuilt._refuse_inputs_baseline_policy_drops() + rebuilt._drop_holders_built_for_another_policy() rebuilt._rebind_holders() rebuilt._isolate_parameter_tracing() simulation.baseline = rebuilt diff --git a/policyengine_us/tests/core/test_employer_payroll_tax_incidence.py b/policyengine_us/tests/core/test_employer_payroll_tax_incidence.py index 48403dc9a4d..d54503858b0 100644 --- a/policyengine_us/tests/core/test_employer_payroll_tax_incidence.py +++ b/policyengine_us/tests/core/test_employer_payroll_tax_incidence.py @@ -29,10 +29,10 @@ fica_pre_tax_contributions, so a supplied total counts in both, and neutralizing or abolishing it moves pay with the components unchanged, as do reforms that keep the list but limit the total to children or give - a listed contribution a formula. A branch that was subsampled matches its - ancestor's baseline by person ID, among the IDs the baseline has once, so - a person whose ID axes repeated raises by name, and a formula for the - total that reads employment income is refused with core's CycleError. + a listed contribution a formula. A branch that was subsampled gets a + baseline of its own on the same sample, so its people align by position, + and a formula for the total that reads employment income is refused with + core's CycleError. Abolishing a variable a federal employer tax is calculated from zeroes the rate of exactly the taxes calculated from it. Neutralizing one changes no rate, so it moves no wages, and an employer tax formula the @@ -1151,13 +1151,14 @@ def numbered_situation(year, people, states): @pytest.mark.parametrize("removal", ["employee_rate", "neutralized"]) def test_a_subsampled_branch_matches_its_baseline_by_person(removal): - """A branch keeps its ancestor's baseline, with all of its people. - - Subsampling the branch to one of two households leaves that baseline at - two people, so the baseline's FICA pre-tax total is read for the person - the sample kept, matched by ID. Under an employee-only reform the two - totals are equal and the change is zero; with the total neutralized, - pay falls by the employer tax on the kept worker's premiums. + """A subsampled branch gets a baseline of its own, with the same people. + + Subsampling the branch to one of two households builds its baseline on + the same sample, so the baseline holds the one person the sample kept, + under the same ID, and its FICA pre-tax total lines up with that person. + Under an employee-only reform the two totals are equal and the change is + zero; with the total neutralized, pay falls by the employer tax on the + kept worker's premiums. """ if removal == "employee_rate": reform = Reform.from_dict( @@ -1180,7 +1181,8 @@ def test_a_subsampled_branch_matches_its_baseline_by_person(removal): branch = simulation.get_branch("sampled") branch.subsample(n=1, seed="sampled", time_period=YEAR) assert branch.persons.count == 1 - assert branch.baseline.persons.count == 2 + assert branch.baseline.persons.count == 1 + np.testing.assert_array_equal(branch.baseline.persons.ids, branch.persons.ids) kept = str(branch.persons.ids[0]) pay = branch.calculate("employment_income", YEAR) if removal == "employee_rate": @@ -1238,17 +1240,19 @@ def axes_situation(person_ids): def test_a_subsampled_branch_finds_its_person_among_repeated_axis_ids(): - """Axes can give two people one ID; a subsampled branch matches by ID. + """Axes can give two people one ID; a subsampled branch lines up by position. With the FICA pre-tax total neutralized, each worker's pay falls by the employer tax on their premiums: (pay * 1.0765 - 0.0765 * premiums) / 1.0765. Before the subsample both simulations list the same IDs, so the repeated "110" aligns by position. A branch subsampled to one household - reads the baseline's total for the person it kept, by an ID the baseline - has once, or raises naming an ID the baseline repeats. The test accepts - either outcome, whichever household the seed keeps; + gets a baseline of its own on the same sample, with the same IDs, so its + people align by position too. Where the kept person's ID is one the + parent has once, their pay is checked against the parent's; an ID the + parent repeats can't say which person was kept, so the test then checks + only the baseline's people. test_people_match_by_position_or_by_an_id_the_baseline_has_once covers - each path directly. + the lookup by ID directly. """ simulation = Simulation( situation=axes_situation(["1", "11"]), reform=NeutralizeFicaTotal @@ -1271,16 +1275,11 @@ def test_a_subsampled_branch_finds_its_person_among_repeated_axis_ids(): ) branch = simulation.get_branch("sampled") branch.subsample(n=1, seed="axes-collision", time_period=YEAR) - assert branch.baseline.persons.count == len(ids) kept = [str(pid) for pid in branch.persons.ids] + assert branch.baseline.persons.count == len(kept) + assert [str(pid) for pid in branch.baseline.persons.ids] == kept repeated = [pid for pid in kept if ids.count(pid) > 1] - if repeated: - with pytest.raises( - NotImplementedError, - match=f"more than one person with ID '{repeated[0]}'", - ): - branch.calculate("employment_income", YEAR) - else: + if not repeated: np.testing.assert_allclose( branch.calculate("employment_income", YEAR), [pay[ids.index(pid)] for pid in kept], diff --git a/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py new file mode 100644 index 00000000000..f303134ebc4 --- /dev/null +++ b/policyengine_us/tests/core/test_reform_baseline_arm_inputs.py @@ -0,0 +1,952 @@ +"""A reform's baseline arm reads the inputs a simulation with no reform reads. + +Core builds the arm inside its ``__init__``. The country simulations then move +the aggregates in ``PRE_RESPONSE_INPUTS``, such as ``employment_income`` and +``weekly_hours_worked``, to their pre-response variables and fill +``state_code`` from ``state_code_str``, and a branch keeps none of what its +parent stores later. Before PolicyEngine/policyengine-us#9698 the arm therefore +read 0 from the pre-response variables: under any reform it saw no hours +worked and paid no New York child care subsidy to a family that a simulation +with no reform paid one. Over a dataset the SPM expense moves by the change in +subsidy it reads from that arm, so the gap became a double count. +``system._rebuild_baseline_branch`` now branches the arm again after the +moves. Like core's branch, it drops each holder the reform built in another +entity or with other ``ETERNITY`` storage than the baseline's variable has: a +kept holder hands the arm the reform's input in place of its formula. A +dropped holder takes its inputs with it, so where the caller gave such a +variable an input, the rebuild raises a ``ValueError`` naming the variable +rather than calculate it in place of the input. + +Invariants: under a reform that changes nothing, the reform and its baseline +arm compute what a simulation with no reform computes, for every household, +whether a situation or a dataset of raw columns supplies the inputs. Under any +reform, each holder in either arm suits that arm's definition of its variable. +Under a reform that stores a variable apart from baseline policy, an input +given for it at construction, through a dataset or a situation, raises by +name. A branch that subsamples reads an arm built on its own sample, under +baseline policy, even where the caller named one of its calculation branches +"baseline". A subsample that raises before core rebuilds the arm leaves what +the branch held under that name as it was. A simulation that is itself named +"baseline" and has an arm raises when asked to subsample, before it changes +anything. A snapshot of a dataset simulation, from ``export_source_inputs`` or +``extract_person``, reloads with the dataset's rule for the SPM child care +expense, in the reform and in its arm, and a dump of one restores with it; a +snapshot or dump without the dataset mark reloads as a household, and a mark +other than true or false raises. A marked reload's arm holds what the +source's arm held for each override: the dataset's value, or, where a caller +set a value on the reform after construction, what the arm kept. + +One limit is pinned here too. Where core builds the arm, in ``subsample``, it +has already dropped such a holder and its recorded inputs, so an input set +after construction and then subsampled raises nothing: the new arm calculates +the variable, as on main. +""" + +import json +from itertools import product + +import numpy as np +import pandas as pd +import pytest +from policyengine_core.data import Dataset +from policyengine_core.periods import ETERNITY +from policyengine_core.reforms import Reform +from policyengine_core.tools import simulation_dumper +from policyengine_core.variables import Variable + +from policyengine_us import Microsimulation, Simulation +from policyengine_us.entities import Person, SPMUnit +from policyengine_us.tools.social_security_inputs import ( + export_source_inputs, + reload_source_inputs, +) + +YEAR = 2026 +TOLERANCE = 0.01 +# Every state and DC, as state_name reads them. +STATE_FIPS = ( + *(1, 2, 4, 5, 6, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 19, 20, 21, 22, 23), + *(24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41), + *(42, 44, 45, 46, 47, 48, 49, 50, 51, 53, 54, 55, 56), +) +NEW_YORK = 36 +# A parent and a child aged 3 in full-time care. Each tuple holds the parent's +# wages, self-employment income, long-term capital gains, weekly hours and +# Social Security retirement benefit, then what the unit paid for care. +FAMILIES = ( + (30_000, 0, 0, 40, 0, 14_000), + (15_000, 3_000, 1_000, 20, 1_200, 6_000), +) +PRE_RESPONSE = ( + "employment_income_before_lsr", + "self_employment_income_before_lsr", + "weekly_hours_worked_before_lsr", + "long_term_capital_gains_before_response", +) +OUTPUTS = ( + "child_care_subsidies", + "spm_unit_capped_work_childcare_expenses", + "social_security", + "snap", + "income_tax", + "spm_unit_net_income", + "household_net_income", +) + + +class NoChange(Reform): + def apply(self): + pass + + +class child_care_subsidies(Variable): + # Stored for all time, where baseline policy calculates it each year. + value_type = float + entity = SPMUnit + label = "Child care subsidies" + definition_period = ETERNITY + + +class StoreSubsidiesForAllTime(Reform): + def apply(self): + self.update_variable(child_care_subsidies) + + +def dataset( + states=STATE_FIPS, + families=FAMILIES, + eternal_subsidy=None, + yearly_subsidies=None, + weights=None, + given=None, +): + """A flat file with one household per state and family. ``yearly_subsidies`` + maps a year to each household's child care subsidy, ``weights`` gives + each household's weight, and ``given`` maps a variable to each household's + value of it in 2026.""" + columns = {} + + def add(name, parent, child): + columns.setdefault(name, []).extend([parent, child]) + + for unit, (fips, family) in enumerate(product(states, families)): + wages, self_employment, gains, hours, retirement, expenses = family + add("person_id", 2 * unit, 2 * unit + 1) + for entity in ("household", "tax_unit", "spm_unit", "family"): + add(f"{entity}_id", unit, unit) + add("marital_unit_id", 2 * unit, 2 * unit + 1) + add(f"age__{YEAR}", 30, 3) + add(f"employment_income__{YEAR}", wages, 0) + add(f"self_employment_income__{YEAR}", self_employment, 0) + add(f"long_term_capital_gains__{YEAR}", gains, 0) + add(f"weekly_hours_worked__{YEAR}", hours, 0) + add(f"social_security_retirement__{YEAR}", retirement, 0) + add(f"is_tax_unit_head__{YEAR}", True, False) + add(f"is_household_head__{YEAR}", True, False) + add(f"is_tax_unit_dependent__{YEAR}", False, True) + add(f"childcare_hours_per_day__{YEAR}", 0, 8) + add(f"childcare_days_per_week__{YEAR}", 0, 5) + add(f"childcare_attending_days_per_month__{YEAR}", 0, 21) + add(f"spm_unit_pre_subsidy_childcare_expenses__{YEAR}", expenses, expenses) + add(f"state_fips__{YEAR}", fips, fips) + weight = 1 if weights is None else weights[unit] + add(f"household_weight__{YEAR}", weight, weight) + if eternal_subsidy is not None: + add("child_care_subsidies__eternity", eternal_subsidy, eternal_subsidy) + for year, subsidies in (yearly_subsidies or {}).items(): + add(f"child_care_subsidies__{year}", subsidies[unit], subsidies[unit]) + for name, given_values in (given or {}).items(): + add(f"{name}__{YEAR}", given_values[unit], given_values[unit]) + return Dataset.from_dataframe(pd.DataFrame(columns), time_period=YEAR) + + +def situation(): + """The first family in New York, naming its state only through + state_code_str, with the second family's other income.""" + members = ["parent", "child"] + return { + "people": { + "parent": { + "age": {YEAR: 30}, + "employment_income": {YEAR: 30_000}, + "self_employment_income": {YEAR: 3_000}, + "long_term_capital_gains": {YEAR: 1_000}, + "weekly_hours_worked": {YEAR: 40}, + "social_security_retirement": {YEAR: 1_200}, + "is_tax_unit_head": {YEAR: True}, + "is_household_head": {YEAR: True}, + }, + "child": { + "age": {YEAR: 3}, + "childcare_hours_per_day": {YEAR: 8}, + "childcare_days_per_week": {YEAR: 5}, + "childcare_attending_days_per_month": {YEAR: 21}, + "is_tax_unit_dependent": {YEAR: True}, + }, + }, + "tax_units": {"tax_unit": {"members": members}}, + "families": {"family": {"members": members}}, + "marital_units": { + "parent_marital_unit": {"members": ["parent"]}, + "child_marital_unit": {"members": ["child"]}, + }, + "spm_units": { + "spm_unit": { + "members": members, + "spm_unit_pre_subsidy_childcare_expenses": {YEAR: 14_000}, + } + }, + "households": { + "household": {"members": members, "state_code_str": {YEAR: "NY"}} + }, + } + + +def value(simulation, variable, year=YEAR): + return np.asarray(simulation.calculate(variable, year), dtype=float) + + +def values(simulation): + return { + variable: value(simulation, variable) for variable in PRE_RESPONSE + OUTPUTS + } + + +def assert_holders_suit_their_variables(simulation): + """Each holder sits in its variable's entity, with ``ETERNITY`` storage + exactly when the simulation's own definition of the variable has it.""" + variables = simulation.tax_benefit_system.variables + for population in simulation.populations.values(): + for name, holder in population._holders.items(): + variable = variables.get(name) + assert holder.variable is variable, name + assert variable.entity.key == population.entity.key, name + assert holder._memory_storage.is_eternal == ( + variable.definition_period == ETERNITY + ), name + + +def assert_both_arms_match(plain, reformed): + arm = reformed.baseline + assert reformed.branches["baseline"] is arm + assert arm.parent_branch is reformed + assert arm.baseline is None + # The arm owns its policy, which names the arm rather than the one it + # replaced. + assert arm.tax_benefit_system is not reformed.tax_benefit_system + assert arm.tax_benefit_system.simulation is arm + # No calculation has run yet, so the arm holds only inputs, and no value + # the reform's policy produced. + assert arm.drop_computed_arrays() == 0 + for simulation in (reformed, arm): + assert_holders_suit_their_variables(simulation) + expected = values(plain) + for name, simulation in (("reform", reformed), ("baseline arm", arm)): + for variable, array in values(simulation).items(): + np.testing.assert_allclose( + array, + expected[variable], + atol=TOLERANCE, + err_msg=f"{name}: {variable}", + ) + return expected + + +def test_dataset_arms_match_a_simulation_with_no_reform(): + plain = Microsimulation(dataset=dataset()) + expected = assert_both_arms_match( + plain, Microsimulation(dataset=dataset(), reform=NoChange) + ) + states = plain.calculate("state_code", YEAR).values + assert len(set(states)) == len(STATE_FIPS) + # The comparison covers households these programs pay, New York's first + # family among them, which the arm used to pay nothing. + subsidies = expected["child_care_subsidies"] + assert (subsidies > 0).sum() >= 10 + assert subsidies[STATE_FIPS.index(NEW_YORK) * len(FAMILIES)] > 0 + assert (expected["social_security"] > 0).any() + + +def test_situation_arms_match_a_simulation_with_no_reform(): + plain = Simulation(situation=situation()) + reformed = Simulation(situation=situation(), reform=NoChange) + expected = assert_both_arms_match(plain, reformed) + assert expected["child_care_subsidies"].sum() > 0 + for simulation in (plain, reformed, reformed.baseline): + state = simulation.calculate("state_code", YEAR).decode_to_str() + assert state.tolist() == ["NY"] + + +SUBSIDY = "child_care_subsidies" +EXPENSE = "spm_unit_capped_work_childcare_expenses" +REFUSAL = f"Baseline policy cannot hold the input given for {SUBSIDY}" + + +def with_subsidy(subsidy): + """The situation, with a child care subsidy given on the SPM unit.""" + given = situation() + given["spm_units"]["spm_unit"][SUBSIDY] = subsidy + return given + + +def subsidy_for_all_time_from_a_dataset(): + return Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], eternal_subsidy=500), + reform=StoreSubsidiesForAllTime, + ) + + +def subsidy_for_the_year_from_a_dataset(): + return Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies={YEAR: [500]}), + reform=StoreSubsidiesForAllTime, + ) + + +def subsidy_for_all_time_in_a_situation(): + return Simulation( + situation=with_subsidy({"ETERNITY": 500}), reform=StoreSubsidiesForAllTime + ) + + +def subsidy_for_the_year_in_a_situation(): + return Simulation( + situation=with_subsidy({YEAR: 500}), reform=StoreSubsidiesForAllTime + ) + + +@pytest.mark.parametrize( + "build", + [ + subsidy_for_all_time_from_a_dataset, + subsidy_for_the_year_from_a_dataset, + subsidy_for_all_time_in_a_situation, + subsidy_for_the_year_in_a_situation, + ], +) +def test_the_arm_refuses_a_subsidy_the_reform_stores_for_all_time(build): + """New York's first family enters with a $500 subsidy, for all time or for + 2026, under a reform that stores ``child_care_subsidies`` for all time. + Baseline policy's yearly variable can't use the reform's holder, so the + arm would drop the input and calculate a subsidy in its place: given for + 2026, S0 would move from the $500 given to what baseline policy pays, + though the subsidy paid hadn't changed. So construction refuses either + input, naming the variable. The rebuild at the end of construction + raises: where core builds the arm, it has already dropped the holder and + its recorded input.""" + with pytest.raises(ValueError, match=REFUSAL) as refused: + build() + assert "_rebuild_baseline_branch" in [entry.name for entry in refused.traceback] + + +def test_an_input_set_after_construction_is_calculated_after_a_subsample(): + """The stated limit. Both runs read two New York families, and the sample + keeps the second, the family a plain run pays more than $500. After + construction the reform gets a $500 subsidy, which it stores for all + time. Its arm never sees an input set after construction, and the + subsample raises nothing: core drops the reform's holder from the arm it + builds, so that arm calculates the subsidy, as on main.""" + families = (FAMILIES[1], FAMILIES[0]) + simulations = [ + Microsimulation( + dataset=dataset((NEW_YORK,), families, weights=(0, 1)), reform=reform + ) + for reform in (None, StoreSubsidiesForAllTime) + ] + plain, reformed = simulations + for simulation in (reformed, reformed.baseline): + assert_holders_suit_their_variables(simulation) + reformed.set_input(SUBSIDY, YEAR, [500, 500]) + for simulation in simulations: + simulation.subsample(n=1) + arm = reformed.baseline + for simulation in (reformed, arm): + assert_holders_suit_their_variables(simulation) + assert simulation.calculate("household_id", YEAR).values.tolist() == [1] + calculated = value(plain, SUBSIDY) + assert calculated[0] > 500 + np.testing.assert_allclose(value(arm, SUBSIDY), calculated, atol=TOLERANCE) + np.testing.assert_allclose(value(reformed, SUBSIDY), [500]) + + +SSTB_INCOME = "sstb_self_employment_income" + + +class sstb_self_employment_income(Variable): + # Stored for all time, where baseline policy stores it each year. + value_type = float + entity = Person + label = "SSTB self-employment income" + definition_period = ETERNITY + + +class StoreSSTBIncomeForAllTime(Reform): + def apply(self): + self.update_variable(sstb_self_employment_income) + + +def test_the_rebuild_drops_a_holder_the_reform_built_with_no_input(): + """Construction moves ``sstb_self_employment_income`` to its pre-response + variable, so it asks the reform for that variable's holder even where the + caller gave no input. Under a reform that stores the variable for all + time, the reform then holds an empty holder for all time, and the arm + branched after the moves copies it. With no input recorded, the guard has + nothing to refuse, so the rebuild's own drop keeps that holder out of the + arm.""" + reformed = Microsimulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1]), reform=StoreSSTBIncomeForAllTime + ) + holder = reformed.populations["person"]._holders.get(SSTB_INCOME) + assert holder is not None and holder._memory_storage.is_eternal + assert SSTB_INCOME not in {key[0] for key in reformed._user_input_keys} + arm = reformed.baseline + assert SSTB_INCOME not in arm.populations["person"]._holders + assert_holders_suit_their_variables(arm) + + +STANDARD_DEDUCTION = Reform.from_dict( + {"gov.irs.deductions.standard.amount.SINGLE": {"2026-01-01.2100-12-31": 20_000}}, + country_id="us", +) + + +def two_new_york_earners(): + """Two single earners in New York who each paid $500 for care. Only the + second weighs anything, and each has its own subsidy.""" + columns = { + "person_id": [0, 1], + **{f"{entity}_id": [0, 1] for entity in ("household", "tax_unit")}, + **{f"{entity}_id": [0, 1] for entity in ("spm_unit", "family")}, + "marital_unit_id": [0, 1], + f"age__{YEAR}": [40, 40], + f"employment_income__{YEAR}": [80_000, 80_000], + f"is_tax_unit_head__{YEAR}": [True, True], + f"is_household_head__{YEAR}": [True, True], + f"state_fips__{YEAR}": [NEW_YORK, NEW_YORK], + f"household_weight__{YEAR}": [0.0, 1.0], + f"{SUBSIDY}__{YEAR}": [100.0, 200.0], + f"spm_unit_pre_subsidy_childcare_expenses__{YEAR}": [500.0, 500.0], + } + return Dataset.from_dataframe(pd.DataFrame(columns), time_period=YEAR) + + +def test_a_subsampled_branch_reads_an_arm_on_its_own_sample(): + """A branch shares its parent's arm, and core rebuilds only the arm a + simulation holds in ``branches["baseline"]``. So a branch that + subsampled kept the parent's arm, on both households, and the dataset + rule, which reads S0 from that arm, raised on the size mismatch. Now the + branch reads an arm on its own sample and gets the expense a subsample + of the reform itself gets, $500, while the parent keeps its arm.""" + top = Microsimulation(dataset=two_new_york_earners(), reform=STANDARD_DEDUCTION) + top.subsample(n=1, seed=0) + expected = value(top, EXPENSE) + np.testing.assert_allclose(expected, [500]) + + parent = Microsimulation(dataset=two_new_york_earners(), reform=STANDARD_DEDUCTION) + arm = parent.baseline + branch = parent.get_branch("trial") + assert branch.baseline is arm + branch.subsample(n=1, seed=0) + own_arm = branch.baseline + assert own_arm is not arm + assert own_arm is branch.branches["baseline"] + assert own_arm.baseline is None + assert own_arm.tax_benefit_system.simulation is own_arm + np.testing.assert_allclose(value(own_arm, SUBSIDY), [200]) + np.testing.assert_allclose(value(branch, EXPENSE), expected) + + assert parent.baseline is arm + assert arm.tax_benefit_system.simulation is arm + np.testing.assert_allclose(value(arm, SUBSIDY), [100, 200]) + np.testing.assert_allclose(value(parent, EXPENSE), [500, 500]) + + +REPEAL = Reform.from_dict( + {"gov.abolitions.child_care_subsidies": {"2026-01-01.2026-12-31": True}}, + country_id="us", +) +# What a subsample of the reform itself reads under REPEAL, keeping the second +# New York family: S0, and the expense, $6,000 reported plus the $6,000 lost. +SAMPLED_S0 = [6_000] +SAMPLED_EXPENSE = [12_000] + + +def new_york_families(): + """Both New York families. Only the second weighs anything.""" + return dataset((NEW_YORK,), FAMILIES, weights=(0, 1)) + + +def repeals_the_subsidy(simulation): + parameters = simulation.tax_benefit_system.parameters(f"{YEAR}-01-01") + return bool(parameters.gov.abolitions.child_care_subsidies) + + +def households(simulation): + return simulation.calculate("household_id", YEAR).values.tolist() + + +def test_a_branch_named_baseline_gives_way_to_the_arm_in_a_subsample(): + """Core rebuilds the arm from ``branches["baseline"]``. So where the + caller had named one of a branch's calculation branches "baseline", the + branch's subsample built its new arm from that one, under the reform: + with the subsidy repealed, S0 read $0 and the expense $6,000. Now the + subsample hands core a copy of the arm in its place, and the branch + reads what a subsample of the reform itself reads. The parent keeps its + arm, on both households.""" + top = Microsimulation(dataset=new_york_families(), reform=REPEAL) + top.subsample(n=1, seed=0) + assert households(top) == [1] + np.testing.assert_allclose(value(top, SUBSIDY), [0]) + np.testing.assert_allclose(value(top.baseline, SUBSIDY), SAMPLED_S0) + np.testing.assert_allclose(value(top, EXPENSE), SAMPLED_EXPENSE) + + parent = Microsimulation(dataset=new_york_families(), reform=REPEAL) + arm = parent.baseline + trial = parent.get_branch("trial") + named = trial.get_branch("baseline") + assert trial.baseline is arm and named is not arm + trial.subsample(n=1, seed=0) + own_arm = trial.baseline + assert own_arm is trial.branches["baseline"] + assert own_arm is not arm and own_arm is not named + assert repeals_the_subsidy(trial) and not repeals_the_subsidy(own_arm) + assert households(trial) == households(own_arm) == [1] + np.testing.assert_allclose(value(own_arm, SUBSIDY), SAMPLED_S0) + np.testing.assert_allclose(value(trial, EXPENSE), SAMPLED_EXPENSE) + + assert parent.baseline is arm + assert households(arm) == [0, 1] + + +def test_a_failed_branch_subsample_leaves_the_branch_as_it_found_it(): + """Core's subsample raises before it samples anything when given neither + ``n`` nor ``frac``. The branch then keeps what it held under "baseline": + nothing, for a branch that shares its parent's arm, or the calculation + branch the caller named "baseline", the same object. Each branch still + shares the parent's arm, and a retry reads what a subsample of the + reform itself reads.""" + parent = Microsimulation(dataset=new_york_families(), reform=REPEAL) + arm = parent.baseline + plain = parent.get_branch("plain") + trial = parent.get_branch("trial") + named = trial.get_branch("baseline") + for branch in (plain, trial): + with pytest.raises(ValueError, match="Either n or frac must be provided"): + branch.subsample() + assert branch.baseline is arm + assert "baseline" not in plain.branches + assert trial.branches["baseline"] is named + + for branch in (plain, trial): + branch.subsample(n=1, seed=0) + assert branch.baseline is not arm + assert households(branch) == households(branch.baseline) == [1] + np.testing.assert_allclose(value(branch.baseline, SUBSIDY), SAMPLED_S0) + np.testing.assert_allclose(value(branch, EXPENSE), SAMPLED_EXPENSE) + assert parent.baseline is arm + assert households(arm) == [0, 1] + + +NAMED_REFUSAL = 'A simulation named "baseline" with a baseline arm cannot subsample' + + +def test_a_simulation_named_baseline_with_an_arm_refuses_to_subsample(): + """Core rebuilds the arm with ``get_branch("baseline")``, which returns a + simulation itself when that is its own name. A branch named "baseline" + under another branch shares the parent's arm, so its subsample put + baseline policy on the branch and dropped its arm: the repeal read False + and the expense $14,000 in place of $27,916.40. Now ``subsample`` raises + before it changes anything, on that branch, a clone of it, a deeper + branch of that name and a reform simulation renamed "baseline", and each + keeps its policy, arm, branches and name.""" + parent = Microsimulation(dataset=new_york_families(), reform=REPEAL) + arm = parent.baseline + trial = parent.get_branch("trial") + named = trial.get_branch("baseline") + renamed = parent.clone() + renamed.branch_name = "baseline" + cases = ( + named, + named.clone(), + trial.get_branch("deeper").get_branch("baseline"), + renamed, + ) + before = [ + (case.baseline, dict(case.branches), case.tax_benefit_system) for case in cases + ] + for case, (own_arm, branches, system) in zip(cases, before): + assert case.branch_name == "baseline" and own_arm is not None + with pytest.raises(ValueError, match=NAMED_REFUSAL): + case.subsample(n=1, seed=0) + assert case.branch_name == "baseline" + assert case.baseline is own_arm + assert case.tax_benefit_system is system + assert case.branches.keys() == branches.keys() + assert all(case.branches[key] is branches[key] for key in branches) + assert repeals_the_subsidy(case) + assert households(case) == [0, 1] + assert named.baseline is arm + np.testing.assert_allclose(value(named, SUBSIDY), [0, 0]) + np.testing.assert_allclose( + value(named, EXPENSE), [27_916.40, 12_000], atol=TOLERANCE + ) + np.testing.assert_allclose(value(arm, SUBSIDY), [13_916.40, 6_000], atol=TOLERANCE) + assert trial.branches["baseline"] is named + assert parent.baseline is arm + assert households(arm) == [0, 1] + + +def test_a_failed_subsample_with_no_arm_raises_core_error(): + """A simulation with no reform has no arm and no "baseline" entry, so + ``subsample`` hands core no copy and has nothing to put back when core + raises. Core's own ``ValueError`` reaches the caller, rather than a + ``KeyError`` from removing an entry that was never there, and the + simulation still has no arm.""" + simulation = Microsimulation(dataset=new_york_families()) + assert simulation.baseline is None + assert "baseline" not in simulation.branches + with pytest.raises(ValueError, match="Either n or frac must be provided"): + simulation.subsample() + assert "baseline" not in simulation.branches + assert simulation.baseline is None + + +# What both New York families reported paying for care, which baseline policy +# keeps over a dataset; under REPEAL, that plus the subsidy lost, S0, which the +# reform reads from its arm. +REPORTED_EXPENSE = [14_000, 6_000] +REPEALED_EXPENSE = [27_916.40, 12_000] +NEW_YORK_S0 = [13_916.40, 6_000] +DATASET_INPUTS = "_dataset_inputs" +PROVENANCE = "_social_security_input_provenance" +BASELINE_ARM_OVERRIDES = "_baseline_arm_overrides" +DUMP_MARK_FILE = "dataset_inputs.json" +NOT_TRUE_OR_FALSE = "the mark must be true or false" + + +@pytest.fixture(scope="module") +def new_york_source(): + """Both New York families over a dataset, with no reform. The second + receives a Social Security benefit, so a snapshot carries the provenance + envelope beside the dataset mark.""" + return Simulation(dataset=dataset((NEW_YORK,), FAMILIES)) + + +def assert_dataset_reading(simulation, households=slice(None)): + """The expense a dataset simulation computes: the reported amount with no + reform, and under REPEAL that plus the subsidy lost, read from an arm + that keeps the reported amount.""" + reported = REPORTED_EXPENSE[households] + if simulation.baseline is None: + np.testing.assert_allclose(value(simulation, EXPENSE), reported, atol=TOLERANCE) + return + assert repeals_the_subsidy(simulation) + np.testing.assert_allclose(value(simulation, SUBSIDY), [0] * len(reported)) + np.testing.assert_allclose( + value(simulation, EXPENSE), REPEALED_EXPENSE[households], atol=TOLERANCE + ) + arm = simulation.baseline + assert not repeals_the_subsidy(arm) + np.testing.assert_allclose( + value(arm, SUBSIDY), NEW_YORK_S0[households], atol=TOLERANCE + ) + np.testing.assert_allclose(value(arm, EXPENSE), reported, atol=TOLERANCE) + + +def test_a_dataset_snapshot_reloads_with_the_dataset_reading(new_york_source): + """Over a dataset, the pre-subsidy input reads as what parents paid after + any subsidy; in a household, as the amount before it. A snapshot used to + reload as a household, so the first family's expense fell from $14,000 + to $83.60. Now the snapshot carries a mark, and the reload, a branch of + it and a second snapshot of it keep the dataset reading. The branch is + taken before the reload calculates anything, so it reads the expense + itself rather than copying the reload's.""" + payload = export_source_inputs(new_york_source) + assert_dataset_reading(new_york_source) + reloaded = reload_source_inputs(payload) + branch = reloaded.get_branch("trial") + assert not reloaded.is_over_dataset + assert_dataset_reading(branch) + np.testing.assert_allclose( + value(reloaded, EXPENSE), value(new_york_source, EXPENSE), atol=TOLERANCE + ) + assert_dataset_reading(reloaded) + again = export_source_inputs(reloaded) + assert_dataset_reading(reload_source_inputs(again)) + for snapshot in (payload, again): + assert snapshot["version"] == 1 and snapshot[DATASET_INPUTS] is True + assert snapshot[PROVENANCE] is not None + + +def test_a_dataset_snapshot_reloaded_under_a_reform_keeps_the_reading_in_its_arm( + new_york_source, +): + """Core builds a reform's arm inside ``__init__``, by cloning the + simulation, so the mark must be on the simulation before then. The + reform reads S0 from the arm, and the arm keeps the reported amount.""" + payload = export_source_inputs(new_york_source) + assert_dataset_reading(reload_source_inputs(payload, reform=REPEAL)) + + +def test_a_reform_over_a_dataset_keeps_the_reading_through_a_snapshot(): + """A source built with the reform exports the mark too, from the reform + and from its arm, and each reloads with the dataset reading.""" + source = Simulation(dataset=dataset((NEW_YORK,), FAMILIES), reform=REPEAL) + assert_dataset_reading(source) + payload = export_source_inputs(source) + assert payload[DATASET_INPUTS] is True + assert_dataset_reading(reload_source_inputs(payload, reform=REPEAL)) + arm_payload = export_source_inputs(source.baseline) + assert arm_payload[DATASET_INPUTS] is True + assert_dataset_reading(reload_source_inputs(arm_payload)) + + +def test_a_person_extracted_from_a_dataset_keeps_the_reading(new_york_source): + """``extract_person`` marks the situation it extracts from a dataset + simulation, and a simulation built from it, with or without a reform, + reads the expense as the dataset does.""" + for person, households in ((0, slice(0, 1)), (2, slice(1, 2))): + extracted = json.loads(json.dumps(new_york_source.extract_person(person))) + built = Simulation(situation=extracted) + assert not built.is_over_dataset + assert_dataset_reading(built, households) + assert_dataset_reading( + Simulation(situation=extracted, reform=REPEAL), households + ) + assert extracted[DATASET_INPUTS] is True + + +def test_an_unmarked_snapshot_reloads_as_a_household(new_york_source): + """A version 1 snapshot without the mark, as export wrote before it + recorded one, reloads as a household: each family's expense nets its + subsidy, $14,000 less $13,916.40 and $6,000 less $6,000. A snapshot of + that reload carries no mark either.""" + payload = export_source_inputs(new_york_source) + del payload[DATASET_INPUTS] + reloaded = reload_source_inputs(payload) + np.testing.assert_allclose(value(reloaded, EXPENSE), [83.60, 0], atol=TOLERANCE) + assert DATASET_INPUTS not in export_source_inputs(reloaded) + + +def test_a_mark_other_than_true_or_false_raises(new_york_source): + """The builder and the reload take the mark as true or false. JSON false + reads as no mark, so the first family's expense nets its subsidy, and + any other value raises before anything is built.""" + extracted = json.loads(json.dumps(new_york_source.extract_person(0))) + payload = export_source_inputs(new_york_source) + for mark in ("true", 1): + with pytest.raises(ValueError, match=NOT_TRUE_OR_FALSE): + Simulation(situation={**extracted, DATASET_INPUTS: mark}) + with pytest.raises(ValueError, match=NOT_TRUE_OR_FALSE): + reload_source_inputs({**payload, DATASET_INPUTS: mark}) + unmarked = ( + Simulation( + situation=json.loads(json.dumps({**extracted, DATASET_INPUTS: False})) + ), + reload_source_inputs( + json.loads(json.dumps({**payload, DATASET_INPUTS: False})) + ), + ) + for simulation in unmarked: + np.testing.assert_allclose(value(simulation, EXPENSE)[0], 83.60, atol=TOLERANCE) + + +# The dataset counts $40,000 of the first New York family's income for its +# child care program, where the program's formula counts $30,000, so baseline +# policy pays that family $100 less, and gives it $2,000 of other work +# expenses, W, where the formula gives none. +GIVEN = {"ny_ccap_countable_income": (40_000, 0), "spm_unit_work_expenses": (2_000, 0)} +GIVEN_S0 = [13_816.40, 6_000] +GIVEN_ARM_EXPENSE = [16_000, 6_000] +GIVEN_EXPENSE = [29_816.40, 12_000] + + +def given_source(): + return Simulation( + dataset=dataset((NEW_YORK,), FAMILIES, given=GIVEN), reform=REPEAL + ) + + +@pytest.fixture(scope="module") +def given_snapshot(): + """``given_source`` and its snapshot, which the tests below only read.""" + source = given_source() + return source, export_source_inputs(source) + + +def test_a_marked_reload_sets_the_snapshots_overrides_on_its_arm(given_snapshot): + """Over a dataset, core gives the reform and its arm each value the + dataset gives. Export lists a value given for a variable with a formula, + such as New York's countable income, among the overrides, and the reload + set those on the reform side only. Its arm then calculated S0 at + $13,916.40 where the source's arm reads $13,816.40, and the reform's + expense read $100 more than the source's. Now a marked reload sets each + override on its arm too.""" + source, payload = given_snapshot + assert GIVEN.keys() <= payload["overrides"].keys() + assert BASELINE_ARM_OVERRIDES not in payload + reloaded = reload_source_inputs(payload, reform=REPEAL) + np.testing.assert_allclose( + value(reloaded, EXPENSE), value(source, EXPENSE), atol=TOLERANCE + ) + np.testing.assert_allclose(value(source, EXPENSE), GIVEN_EXPENSE, atol=TOLERANCE) + arm = reloaded.baseline + for name in (SUBSIDY, EXPENSE, "ny_ccap_countable_income"): + np.testing.assert_allclose( + value(arm, name), value(source.baseline, name), atol=TOLERANCE + ) + np.testing.assert_allclose(value(arm, SUBSIDY), GIVEN_S0, atol=TOLERANCE) + + +def test_a_marked_reload_arm_keeps_the_datasets_work_expense(given_snapshot): + """The source's arm holds the $2,000 of work expenses the dataset gives, + so it reads $16,000 for the first family's expense. The reload's arm + calculated W at $0 and read $14,000.""" + source, payload = given_snapshot + arm = reload_source_inputs(payload, reform=REPEAL).baseline + np.testing.assert_allclose(value(arm, "spm_unit_work_expenses"), [2_000, 0]) + for simulation in (arm, source.baseline): + np.testing.assert_allclose( + value(simulation, EXPENSE), GIVEN_ARM_EXPENSE, atol=TOLERANCE + ) + + +def test_an_unmarked_reload_sets_overrides_on_the_reform_side_only(given_snapshot): + """Without the mark, the reload sets the overrides on the reform side + alone, as on main, and its arm calculates both variables.""" + _, payload = given_snapshot + unmarked = {key: item for key, item in payload.items() if key != DATASET_INPUTS} + reloaded = reload_source_inputs(unmarked, reform=REPEAL) + np.testing.assert_allclose(value(reloaded, "ny_ccap_countable_income"), [40_000, 0]) + np.testing.assert_allclose(value(reloaded, "spm_unit_work_expenses"), [2_000, 0]) + arm = reloaded.baseline + np.testing.assert_allclose(value(arm, "ny_ccap_countable_income"), [30_000, 19_200]) + np.testing.assert_allclose(value(arm, "spm_unit_work_expenses"), [0, 0]) + + +def test_a_marked_reload_keeps_values_set_on_the_reform_side_off_its_arm(): + """A caller who sets a value on the reform after construction sets it + there alone. The source's arm keeps the $2,000 of work expenses the + dataset gave under the $3,000 set, and calculates the earned cap set to + $20,000. Export lists what the arm holds for each override it doesn't + share, null where it holds nothing, and the reload's arm takes that, so + both sides match the source's, through a second snapshot too.""" + source = given_source() + source.set_input("spm_unit_work_expenses", YEAR, [3_000, 0]) + source.set_input("spm_unit_head_spouse_earned_cap", YEAR, [20_000, 20_000]) + payload = export_source_inputs(source) + reloaded = reload_source_inputs(payload, reform=REPEAL) + names = ("spm_unit_work_expenses", "spm_unit_head_spouse_earned_cap", EXPENSE) + for name in names: + for side, source_side in ( + (reloaded, source), + (reloaded.baseline, source.baseline), + ): + np.testing.assert_allclose( + value(side, name), value(source_side, name), atol=TOLERANCE + ) + np.testing.assert_allclose( + value(reloaded.baseline, "spm_unit_head_spouse_earned_cap"), [30_000, 18_000] + ) + assert payload[BASELINE_ARM_OVERRIDES] == { + "spm_unit_work_expenses": {str(YEAR): [2_000, 0]}, + "spm_unit_head_spouse_earned_cap": {str(YEAR): None}, + } + again = export_source_inputs(reloaded) + assert again[BASELINE_ARM_OVERRIDES] == payload[BASELINE_ARM_OVERRIDES] + + +def test_a_marked_reload_refuses_an_override_the_reform_stores_for_all_time(): + """A dataset with no reform gives New York's first family a $500 subsidy + for 2026, and export lists it among the overrides. Under a reform that + stores the subsidy for all time, baseline policy's yearly variable can't + use the reform's holder, so a reform built over that dataset refuses the + input. A marked reload refuses it the same way, by name, before it sets + anything on its arm. An unmarked reload builds, as on main, and its arm + calculates the subsidy.""" + source = Simulation( + dataset=dataset((NEW_YORK,), FAMILIES[:1], yearly_subsidies={YEAR: [500]}) + ) + payload = export_source_inputs(source) + assert SUBSIDY in payload["overrides"] + with pytest.raises(ValueError, match=REFUSAL) as refused: + reload_source_inputs(payload, reform=StoreSubsidiesForAllTime) + names = [entry.name for entry in refused.traceback] + assert "_set_overrides_on_the_arm" in names + assert "_rebuild_baseline_branch" not in names + unmarked = {key: item for key, item in payload.items() if key != DATASET_INPUTS} + reloaded = reload_source_inputs(unmarked, reform=StoreSubsidiesForAllTime) + np.testing.assert_allclose(value(reloaded, SUBSIDY), [500]) + np.testing.assert_allclose( + value(reloaded.baseline, SUBSIDY), NEW_YORK_S0[:1], atol=TOLERANCE + ) + + +class spm_unit_reform_only_amount(Variable): + value_type = float + entity = SPMUnit + label = "An amount only the reform defines" + definition_period = "year" + + def formula(spm_unit, period, parameters): + return spm_unit("spm_unit_pre_subsidy_childcare_expenses", period) * 0 + + +class AddAVariable(Reform): + def apply(self): + self.update_variable(spm_unit_reform_only_amount) + + +def test_a_marked_reload_skips_an_override_baseline_policy_does_not_define(): + """A dataset under a reform that adds a variable gives it a value, which + export lists among the overrides. Baseline policy has no such variable, + so the source's arm has none, and a marked reload sets it on the reform + side alone and raises nothing.""" + name = "spm_unit_reform_only_amount" + source = Simulation( + dataset=dataset((NEW_YORK,), FAMILIES, given={name: (250, 0)}), + reform=AddAVariable, + ) + payload = export_source_inputs(source) + assert name in payload["overrides"] and BASELINE_ARM_OVERRIDES not in payload + reloaded = reload_source_inputs(payload, reform=AddAVariable) + np.testing.assert_allclose(value(reloaded, name), [250, 0]) + assert name not in reloaded.baseline.tax_benefit_system.variables + assert name not in reloaded.baseline.populations["spm_unit"]._holders + np.testing.assert_allclose( + value(reloaded.baseline, EXPENSE), REPORTED_EXPENSE, atol=TOLERANCE + ) + + +def test_a_dump_of_a_dataset_simulation_restores_with_the_dataset_reading(tmp_path): + """Core's ``restore_simulation`` builds a plain core simulation, which read + the pre-subsidy input as a household's: the first family's expense fell + from $14,000 to $83.60. Now the dump holds the mark in ``__entities__``, + and the restore sets it, so the restored simulation reads the expense, + and the second family's Social Security benefit, as its source does. A + dump without the mark file, as earlier dumps are, restores as a + household, a mark other than true or false raises, and a household + simulation's dump holds no mark.""" + source = Simulation(dataset=dataset((NEW_YORK,), FAMILIES)) + directory = tmp_path / "dataset" + simulation_dumper.dump_simulation(source, str(directory)) + system = source.tax_benefit_system + restored = simulation_dumper.restore_simulation(str(directory), system) + np.testing.assert_allclose( + value(restored, EXPENSE), REPORTED_EXPENSE, atol=TOLERANCE + ) + np.testing.assert_allclose(value(restored, "social_security"), [0, 0, 1_200, 0]) + np.testing.assert_allclose( + value(source, "social_security"), value(restored, "social_security") + ) + mark = directory / "__entities__" / DUMP_MARK_FILE + assert json.loads(mark.read_text()) is True + mark.unlink() + unmarked = simulation_dumper.restore_simulation(str(directory), system) + np.testing.assert_allclose(value(unmarked, EXPENSE), [83.60, 0], atol=TOLERANCE) + mark.write_text("1") + with pytest.raises(ValueError, match=NOT_TRUE_OR_FALSE): + simulation_dumper.restore_simulation(str(directory), system) + household = tmp_path / "household" + simulation_dumper.dump_simulation(Simulation(situation=situation()), str(household)) + assert not (household / "__entities__" / DUMP_MARK_FILE).exists() diff --git a/policyengine_us/tests/core/test_shipped_reforms_store_no_variable_apart.py b/policyengine_us/tests/core/test_shipped_reforms_store_no_variable_apart.py new file mode 100644 index 00000000000..d8cf59cf3ec --- /dev/null +++ b/policyengine_us/tests/core/test_shipped_reforms_store_no_variable_apart.py @@ -0,0 +1,187 @@ +"""No shipped reform stores a variable apart from baseline policy. + +A reform's baseline arm drops each holder the reform built for its own +definition of a variable in another entity or with other ``ETERNITY`` +storage, and refuses an input the caller gave that variable +(``SPMSimulationMixin._refuse_inputs_baseline_policy_drops``). Only a reform +that redefines a variable that way reaches either path. This scan reads the +source of every reform under ``policyengine_us/reforms``, without importing +the package, and finds none that does. A new reform that changes a variable's +entity or all-time storage fails it, and so does one that passes +``update_variable``, ``add_variable`` or ``replace_variable`` anything other +than a class defined in its own file. + +A reform's class that leaves out ``entity`` or ``definition_period`` keeps +the baseline variable's, so a missing attribute counts as unchanged. The scan +reads two forms at the top level of a class body: a plain assignment +(``definition_period = ETERNITY``) and an annotated one with a value +(``definition_period: str = ETERNITY``). It doesn't read a tuple target +(``entity, definition_period = ...``), an augmented assignment, an assignment +inside an ``if`` or a loop in the class body, an attribute set on the class +after its ``class`` statement or through ``setattr``, or an attribute the +class inherits from a base other than ``Variable`` or a baseline variable. + +The second test checks that the scan flags the reforms this package's tests +build to store a variable apart, and the third that it reads the annotated +form. +""" + +import ast +import re +from functools import cache +from pathlib import Path + +PACKAGE = Path(__file__).resolve().parents[2] +ATTRIBUTES = ("entity", "definition_period") +CHANGES = re.compile( + r"\.(update_variable|add_variable|replace_variable)\(\s*([A-Za-z_][A-Za-z0-9_]*)" +) + + +def named(node): + """An entity or period expression as a name, or None if it isn't one.""" + if isinstance(node, ast.Constant) and isinstance(node.value, str): + # Core accepts "year" and "eternity" as well as YEAR and ETERNITY. + return node.value.upper() + if isinstance(node, ast.Name): + return node.id + if isinstance(node, ast.Attribute): + return node.attr + return None + + +def variable_classes(path): + """Each Variable class in ``path``, with the attributes its body sets. + + A class counts if it subclasses ``Variable`` or a baseline variable the + file imports from ``policyengine_us.variables``.""" + tree = ast.parse(path.read_text(), filename=str(path)) + baseline_names = { + alias.asname or alias.name + for node in ast.walk(tree) + if isinstance(node, ast.ImportFrom) + and (node.module or "").startswith("policyengine_us.variables") + for alias in node.names + } + for node in ast.walk(tree): + if not isinstance(node, ast.ClassDef): + continue + bases = { + base.id if isinstance(base, ast.Name) else getattr(base, "attr", None) + for base in node.bases + } + if "Variable" not in bases and not bases & baseline_names: + continue + attributes = {} + for statement in node.body: + if isinstance(statement, ast.Assign): + for target in statement.targets: + if isinstance(target, ast.Name) and target.id in ATTRIBUTES: + attributes[target.id] = statement.value + elif ( + isinstance(statement, ast.AnnAssign) + and statement.value is not None + and isinstance(statement.target, ast.Name) + and statement.target.id in ATTRIBUTES + ): + attributes[statement.target.id] = statement.value + yield node.name, attributes, node.lineno + + +def label(path): + """``path`` from the repository root, or in full outside it.""" + if path.is_relative_to(PACKAGE.parent): + return path.relative_to(PACKAGE.parent) + return path + + +@cache +def baseline_variables(): + found = {} + for path in sorted((PACKAGE / "variables").rglob("*.py")): + for name, attributes, _ in variable_classes(path): + found[name] = {key: named(value) for key, value in attributes.items()} + return found + + +def stored_apart(files): + """The classes in ``files`` that redefine a baseline variable in another + entity or with other all-time storage, and the comparisons the scan + can't make.""" + baseline = baseline_variables() + apart, unresolved = [], [] + for path in files: + for name, attributes, line in variable_classes(path): + if name not in baseline: + continue + where = f"{name} ({label(path)}:{line})" + for key, value in attributes.items(): + mine, theirs = named(value), baseline[name].get(key) + if mine is None or theirs is None: + unresolved.append(f"{where}: {key}") + elif key == "entity" and mine != theirs: + apart.append((name, where)) + elif key == "definition_period" and (mine == "ETERNITY") != ( + theirs == "ETERNITY" + ): + apart.append((name, where)) + return apart, unresolved + + +def changes_the_scan_cannot_see(files): + """Variable changes whose argument isn't a class defined in the same file, + or a loop variable over such classes.""" + found = [] + for path in files: + text = path.read_text() + defined = {name for name, _, _ in variable_classes(path)} + for node in ast.walk(ast.parse(text)): + if ( + isinstance(node, ast.For) + and isinstance(node.target, ast.Name) + and isinstance(node.iter, (ast.Tuple, ast.List)) + and all( + isinstance(element, ast.Name) and element.id in defined + for element in node.iter.elts + ) + ): + defined.add(node.target.id) + for match in CHANGES.finditer(text): + if match.group(2) not in defined: + found.append(f"{match.group(1)}({match.group(2)}) in {label(path)}") + return found + + +def test_no_shipped_reform_stores_a_variable_apart_from_baseline_policy(): + reforms = sorted((PACKAGE / "reforms").rglob("*.py")) + assert len(reforms) > 100 + apart, unresolved = stored_apart(reforms) + assert apart == [] + assert unresolved == [] + assert changes_the_scan_cannot_see(reforms) == [] + + +def test_the_scan_flags_reforms_built_to_store_a_variable_apart(): + tests = PACKAGE / "tests" / "core" + apart, _ = stored_apart( + [tests / "test_reform_baseline_arm_inputs.py", tests / "test_spm_system.py"] + ) + assert {"child_care_subsidies", "is_household_head"} <= {name for name, _ in apart} + + +def test_the_scan_reads_an_annotated_assignment(tmp_path): + """``definition_period: str = ETERNITY`` sets the class attribute as the + plain assignment does, so the scan flags a reform that stores + ``child_care_subsidies`` for all time that way.""" + reform = tmp_path / "annotated_reform.py" + reform.write_text( + "from policyengine_core.periods import ETERNITY\n" + "from policyengine_core.variables import Variable\n" + "\n" + "\n" + "class child_care_subsidies(Variable):\n" + " definition_period: str = ETERNITY\n" + ) + apart, unresolved = stored_apart([reform]) + assert [name for name, _ in apart] == ["child_care_subsidies"] + assert unresolved == [] diff --git a/policyengine_us/tests/core/test_spm_system.py b/policyengine_us/tests/core/test_spm_system.py index b81553bc242..e95a9e14521 100644 --- a/policyengine_us/tests/core/test_spm_system.py +++ b/policyengine_us/tests/core/test_spm_system.py @@ -856,7 +856,9 @@ def test_subsampling_never_changes_which_policy_a_holder_belongs_to( belongs to that policy. The rebuilt baseline arm has no baseline of its own, holds nothing that only the reform defines, and keeps no holder the reform built for its own definition of a variable: here, yearly storage - for the baseline's ``ETERNITY`` ``is_household_head``. + for the baseline's ``ETERNITY`` ``is_household_head``. Construction branches + the arm again after it moves inputs, and that arm holds to the same + invariant before any subsampling. Core 3.33.1 and later rebuild from recorded inputs without exporting calculated values as inputs; earlier versions also exported calculated @@ -872,6 +874,13 @@ def test_subsampling_never_changes_which_policy_a_holder_belongs_to( reform=SUBSAMPLED_REFORMS[reform], spm={"geography_kind": "national"}, ) + # The dataset gives no is_household_head, and after construction neither + # the reform nor its arm holds a holder for it, with or without the + # rebuild's drop. So this checks that both arms start bound to their own + # policy; test_the_rebuild_drops_a_holder_the_reform_built_with_no_input, + # in tests/core/test_reform_baseline_arm_inputs.py, pins that drop. + for simulation in (changed, changed.baseline): + assert_bound_to_own_policy(simulation) policies = { "reform": changed.tax_benefit_system, "baseline": changed.baseline.tax_benefit_system, diff --git a/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py b/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py new file mode 100644 index 00000000000..26bbe863841 --- /dev/null +++ b/policyengine_us/tests/microsimulation/test_spm_child_care_reported_expense.py @@ -0,0 +1,116 @@ +"""Over a dataset, the SPM subtracts what parents reported paying for child care. + +Datasets fill spm_unit_pre_subsidy_childcare_expenses from the ASEC's +SPM_CHILDCAREXPNS, what parents reported spending on child care, which the +rule reads as what they paid after any subsidy. So baseline policy keeps that +amount, and a reform moves it by the change in subsidy. These +tests run the rule over the shipped population rather than the situations in +test_spm_child_care_subsidy_invariants.py, so the dataset flag and the reform's +baseline arm come from loading a real file. +""" + +import numpy as np + +from policyengine_us.tests.microsimulation.microcosm_fixture import ( + default_population_sample, +) + +PERIOD = 2026 +TOLERANCE = 0.01 +FLAT_SUBSIDY = 1_000 + + +def spm_arrays(simulation): + return { + name: np.asarray(simulation.calculate(name, PERIOD), dtype=float) + for name in ( + "child_care_subsidies", + "spm_unit_capped_work_childcare_expenses", + "spm_unit_head_spouse_earned_cap", + "spm_unit_pre_subsidy_childcare_expenses", + "spm_unit_work_expenses", + ) + } + + +def test_baseline_expense_is_the_reported_amount_over_the_whole_population(): + from policyengine_us import Microsimulation + + simulation = Microsimulation() # populace_us_2024, full file + reported = simulation.calculate( + "spm_unit_pre_subsidy_childcare_expenses", PERIOD + ).values + work = simulation.calculate("spm_unit_work_expenses", PERIOD).values + cap = simulation.calculate("spm_unit_head_spouse_earned_cap", PERIOD).values + expense = simulation.calculate( + "spm_unit_capped_work_childcare_expenses", PERIOD + ).values + + # The identity would hold trivially if nobody reported paying. + assert (reported > 0).sum() > 1_000 + assert (expense == np.minimum(work + reported, cap)).all() + + +def test_reform_moves_the_reported_expense_by_the_change_in_subsidy(): + from policyengine_core.reforms import Reform + + from policyengine_us import Microsimulation + from policyengine_us.model_api import SPMUnit, USD, YEAR, Variable + + class child_care_subsidies(Variable): + value_type = float + entity = SPMUnit + definition_period = YEAR + label = "Child care subsidies" + unit = USD + + def formula(spm_unit, period, parameters): + return np.full(spm_unit.count, FLAT_SUBSIDY, dtype=float) + + class FlatSubsidy(Reform): + def apply(self): + self.update_variable(child_care_subsidies) + + dataset = default_population_sample() + baseline = spm_arrays(Microsimulation(dataset=dataset)) + simulation = Microsimulation(dataset=dataset, reform=FlatSubsidy) + reformed = spm_arrays(simulation) + arm = spm_arrays(simulation.baseline) + + # The reform's baseline arm matches a simulation with no reform. + for name, values in baseline.items(): + np.testing.assert_array_equal(arm[name], values, err_msg=name) + + reported = baseline["spm_unit_pre_subsidy_childcare_expenses"] + assert (reformed["child_care_subsidies"] == FLAT_SUBSIDY).all() + # The slice has to hold units the old rule got wrong: the model pays them a + # subsidy and they reported paying, so it netted one from the other. + paid = (baseline["child_care_subsidies"] > 0) & (reported > 0) + assert paid.any() + np.testing.assert_allclose( + baseline["spm_unit_capped_work_childcare_expenses"][paid], + np.minimum( + baseline["spm_unit_work_expenses"] + reported, + baseline["spm_unit_head_spouse_earned_cap"], + )[paid], + atol=TOLERANCE, + ) + # And units on each side of the floor. + assert ((reported > 0) & (reported < FLAT_SUBSIDY)).any() + assert (reported > FLAT_SUBSIDY).any() + + change = FLAT_SUBSIDY - baseline["child_care_subsidies"] + expected = np.minimum( + reformed["spm_unit_work_expenses"] + np.maximum(reported - change, 0), + reformed["spm_unit_head_spouse_earned_cap"], + ) + np.testing.assert_allclose( + reformed["spm_unit_capped_work_childcare_expenses"], + expected, + atol=TOLERANCE, + ) + # Some unit's expense has to move, or the comparison above proves nothing. + assert ( + reformed["spm_unit_capped_work_childcare_expenses"] + < baseline["spm_unit_capped_work_childcare_expenses"] + ).any() diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml new file mode 100644 index 00000000000..63b008130c9 --- /dev/null +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_child_care_subsidies_integration.yaml @@ -0,0 +1,372 @@ +# Real state programs through the SPM child care expense. New York, Texas and +# Alaska subsidies never reached the SPM before; Colorado, Washington and West +# Virginia reached it as resources, on top of pre-subsidy expenses. +# +# Each family is one working parent and a child aged 3. Unless a case says +# otherwise, the child is in care 8 hours a day, 5 days a week. The 2026 cases +# earn $30,000 and the 2024 cases earn $24,000. +# Without weeks_worked, work expenses are zero, so the SPM expense is the +# out-of-pocket amount. +# Each case gives earnings before labor supply responses, as a household +# simulation stores them. TANF reads that variable, and the YAML runner leaves +# it at zero when a case gives employment_income. TANF would then see no +# earnings: New York's Family Assistance would pay a grant that waives the CCAP +# family share, and Alaska, Washington, West Virginia and Tennessee would pay +# grants that a household simulation, which sees the earnings, does not. + +- name: New York, Manhattan family with a subsidy just below the expense + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income_before_lsr: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: NY + county_fips: "36061" + output: + child_care_subsidies: 13_916.40 + # 14,000 - 13,916.40. + spm_unit_capped_work_childcare_expenses: 83.60 + +- name: New York, a child with no reported care hours gets no subsidy, so the expense stays + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income_before_lsr: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: NY + county_fips: "36061" + output: + child_care_subsidies: 0 + spm_unit_capped_work_childcare_expenses: 14_000 + +- name: Texas, a subsidy the SPM left out before + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income_before_lsr: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: TX + output: + child_care_subsidies: 6_014.49 + # 14,000 - 6,014.49. + spm_unit_capped_work_childcare_expenses: 7_985.51 + +- name: Alaska, a subsidy the SPM left out before + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income_before_lsr: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: AK + output: + child_care_subsidies: 9_432 + # 14,000 - 9,432. + spm_unit_capped_work_childcare_expenses: 4_568 + +- name: Washington, a subsidy the SPM counted as a resource before + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income_before_lsr: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: WA + output: + child_care_subsidies: 13_220 + # 14,000 - 13,220. + spm_unit_capped_work_childcare_expenses: 780 + +- name: West Virginia, a subsidy the SPM counted as a resource before + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income_before_lsr: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: WV + output: + child_care_subsidies: 7_623 + # 14,000 - 7,623. + spm_unit_capped_work_childcare_expenses: 6_377 + +- name: Colorado, a subsidy the SPM counted as a resource before + period: 2026 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income_before_lsr: 30_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 14_000 + households: + household: + members: [parent, child] + state_code: CO + output: + child_care_subsidies: 12_482 + # 14,000 - 12,482. + spm_unit_capped_work_childcare_expenses: 1_518 + +- name: District of Columbia, a program the 2024 list left out + period: 2024 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income_before_lsr: 24_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 20_000 + households: + household: + members: [parent, child] + state_code: DC + output: + child_care_subsidies: 15_876 + # 20,000 - 15,876. + spm_unit_capped_work_childcare_expenses: 4_124 + +- name: Tennessee, paying from October 2024 + period: 2024 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income_before_lsr: 24_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 20_000 + households: + household: + members: [parent, child] + state_code: TN + output: + child_care_subsidies: 2_704 + # 20,000 - 2,704. + spm_unit_capped_work_childcare_expenses: 17_296 + +- name: Texas, a program the 2024 list left out + period: 2024 + absolute_error_margin: 0.01 + input: + people: + parent: + age: 30 + employment_income_before_lsr: 24_000 + weekly_hours_worked_before_lsr: 40 + is_tax_unit_head: true + is_household_head: true + child: + age: 3 + childcare_hours_per_day: 8 + childcare_days_per_week: 5 + childcare_attending_days_per_month: 21 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [parent, child] + families: + family: + members: [parent, child] + spm_units: + spm_unit: + members: [parent, child] + spm_unit_pre_subsidy_childcare_expenses: 20_000 + households: + household: + members: [parent, child] + state_code: TX + output: + child_care_subsidies: 5_793.01 + # 20,000 - 5,793.01. + spm_unit_capped_work_childcare_expenses: 14_206.99 diff --git a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml index cd2e0be8f63..48ee9b3ad5f 100644 --- a/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml +++ b/policyengine_us/tests/policy/baseline/household/expense/childcare/spm_unit_capped_work_childcare_expenses.yaml @@ -105,3 +105,296 @@ spm_unit_pre_subsidy_childcare_expenses: 2_000 output: spm_unit_capped_work_childcare_expenses: 2_000 + +- name: A child care subsidy lowers the out-of-pocket expense + period: 2026 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 30_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 13_916.40 + output: + # 1,000 + (14,000 - 13,916.40). + spm_unit_capped_work_childcare_expenses: 1_083.60 + +- name: A subsidy above the expense leaves only work expenses + period: 2026 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 30_000 + spm_unit_pre_subsidy_childcare_expenses: 1_200 + child_care_subsidies: 22_828 + output: + # The floor keeps the part of the subsidy above the expense out of the + # SPM, so it cannot offset work expenses. + spm_unit_capped_work_childcare_expenses: 1_000 + +- name: The earnings cap applies after the subsidy + period: 2026 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 5_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 2_000 + output: + # 1,000 + 12,000 exceeds the cap, so the subsidy leaves the expense at + # the cap. + spm_unit_capped_work_childcare_expenses: 5_000 + +- name: A subsidy can bring the expense below the earnings cap + period: 2026 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 5_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 13_000 + output: + spm_unit_capped_work_childcare_expenses: 2_000 + +- name: Expenses in a unit with no child are capped as before and take no subsidy + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 46 + employment_income: 9_000 + is_household_head: true + is_tax_unit_head: true + tax_units: + tax_unit: + members: [head] + spm_units: + spm_unit: + members: [head] + spm_unit_work_expenses: 0 + spm_unit_pre_subsidy_childcare_expenses: 4_000 + output: + child_care_subsidies: 0 + spm_unit_capped_work_childcare_expenses: 4_000 + +- name: A subsidy in a unit with no child still lowers the expense + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 46 + employment_income: 9_000 + is_household_head: true + is_tax_unit_head: true + tax_units: + tax_unit: + members: [head] + spm_units: + spm_unit: + members: [head] + spm_unit_work_expenses: 0 + spm_unit_pre_subsidy_childcare_expenses: 4_000 + child_care_subsidies: 1_500 + output: + spm_unit_capped_work_childcare_expenses: 2_500 + +- name: A subsidy above the expense of a unit with no child leaves only work expenses + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 46 + employment_income: 9_000 + is_household_head: true + is_tax_unit_head: true + tax_units: + tax_unit: + members: [head] + spm_units: + spm_unit: + members: [head] + spm_unit_work_expenses: 500 + spm_unit_pre_subsidy_childcare_expenses: 1_000 + child_care_subsidies: 1_500 + output: + # The floor keeps the 500 of subsidy above the expense from offsetting + # work expenses. + spm_unit_capped_work_childcare_expenses: 500 + +- name: A direct out-of-pocket amount replaces the amount net of subsidies + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 30 + employment_income: 30_000 + is_household_head: true + is_tax_unit_head: true + child: + age: 3 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [head, child] + spm_units: + spm_unit: + members: [head, child] + spm_unit_work_expenses: 0 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 10_000 + childcare_expenses: 6_000 + output: + spm_unit_capped_work_childcare_expenses: 6_000 + +- name: A unit with a child that gives only an out-of-pocket amount counts it + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 30 + employment_income: 30_000 + is_household_head: true + is_tax_unit_head: true + child: + age: 3 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [head, child] + spm_units: + spm_unit: + members: [head, child] + spm_unit_work_expenses: 0 + childcare_expenses: 6_000 + output: + # The pre-subsidy amount is left at 0. Main's formula read only that + # amount, so it gave 0 here. + spm_unit_capped_work_childcare_expenses: 6_000 + +- name: A unit with no child ignores an out-of-pocket amount + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 46 + employment_income: 9_000 + is_household_head: true + is_tax_unit_head: true + tax_units: + tax_unit: + members: [head] + spm_units: + spm_unit: + members: [head] + spm_unit_work_expenses: 0 + spm_unit_pre_subsidy_childcare_expenses: 4_000 + child_care_subsidies: 1_500 + childcare_expenses: 6_000 + output: + # 4,000 - 1,500; the 6,000 is ignored. + spm_unit_capped_work_childcare_expenses: 2_500 + +- name: A member's pre-subsidy amount replaces the unit's for a unit with a child + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 30 + employment_income: 30_000 + is_household_head: true + is_tax_unit_head: true + child: + age: 3 + is_tax_unit_dependent: true + pre_subsidy_childcare_expenses: 6_000 + tax_units: + tax_unit: + members: [head, child] + spm_units: + spm_unit: + members: [head, child] + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 20_000 + spm_unit_pre_subsidy_childcare_expenses: 10_000 + child_care_subsidies: 0 + output: + # childcare_expenses sums the members' pre-subsidy amounts, so the child's + # 6,000 replaces the unit's 10,000: 1,000 + 6,000. Main's formula read the + # unit's amount and gave 1,000 + 10,000 = 11,000. + spm_unit_capped_work_childcare_expenses: 7_000 + +- name: A pre-subsidy amount given for one of two children replaces the unit's amount + period: 2026 + absolute_error_margin: 0.001 + input: + people: + head: + age: 30 + employment_income: 30_000 + is_household_head: true + is_tax_unit_head: true + first_child: + age: 3 + is_tax_unit_dependent: true + pre_subsidy_childcare_expenses: 6_000 + second_child: + age: 5 + is_tax_unit_dependent: true + tax_units: + tax_unit: + members: [head, first_child, second_child] + spm_units: + spm_unit: + members: [head, first_child, second_child] + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 20_000 + spm_unit_pre_subsidy_childcare_expenses: 10_000 + child_care_subsidies: 0 + output: + # Given for one member, pre_subsidy_childcare_expenses is an input for + # every member, so the second child counts 0 rather than a share of the + # unit's 10,000. So childcare_expenses is 6,000, and the expense is + # 1,000 + 6,000 = 7,000, under the 20,000 cap. Main's formula read the + # unit's amount and gave 1,000 + 10,000 = 11,000. + pre_subsidy_childcare_expenses: [0, 6_000, 0] + childcare_expenses: 6_000 + spm_unit_capped_work_childcare_expenses: 7_000 + +- name: A subsidy lowers the expense in 2024, the formula's first year + period: 2024 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 50_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 2_000 + output: + spm_unit_capped_work_childcare_expenses: 13_000 + +- name: A subsidy lowers the expense in 2025 + period: 2025 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 50_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 2_000 + output: + spm_unit_capped_work_childcare_expenses: 13_000 + +- name: Before 2024 the expense has no formula, so a subsidy cannot lower it + period: 2023 + absolute_error_margin: 0.001 + input: + spm_unit_work_expenses: 1_000 + spm_unit_head_spouse_earned_cap: 50_000 + spm_unit_pre_subsidy_childcare_expenses: 14_000 + child_care_subsidies: 2_000 + output: + spm_unit_capped_work_childcare_expenses: 0 diff --git a/policyengine_us/tests/policy/baseline/household/income/spm_unit/spm_unit_benefits.yaml b/policyengine_us/tests/policy/baseline/household/income/spm_unit/spm_unit_benefits.yaml index 2c8a14090b0..acab06757a3 100644 --- a/policyengine_us/tests/policy/baseline/household/income/spm_unit/spm_unit_benefits.yaml +++ b/policyengine_us/tests/policy/baseline/household/income/spm_unit/spm_unit_benefits.yaml @@ -163,6 +163,52 @@ snap: 1_368 spm_unit_benefits: 11_586 +- name: Before 2024 three child care subsidies stay resources, because the SPM expense has no formula to lower. + period: 2023 + input: + co_ccap_subsidy: 1 + wa_child_care_subsidies: 2 + wv_child_care_subsidies: 4 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 1 + 2 + 4 + +- name: From 2024 child care subsidies leave resources and lower the SPM expense instead. + period: 2024 + input: + co_ccap_subsidy: 1 + wa_child_care_subsidies: 2 + wv_child_care_subsidies: 4 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 0 + # A one-adult household with enough earnings to rule out every means-tested # benefit, so each case isolates one payment. Each case also checks that # household_benefits counts the same payment. diff --git a/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml b/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml index b37e8c153b3..5758e3c9376 100644 --- a/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml +++ b/policyengine_us/tests/policy/contrib/congress/tlaib/boost/boost_middle_class_tax_credit.yaml @@ -211,3 +211,49 @@ output: household_benefits: 0 spm_unit_benefits: 0 + +- name: Before 2024 the Colorado subsidy stays a resource under this reform's list. + period: 2023 + reforms: policyengine_us.reforms.congress.tlaib.boost.boost_middle_class_tax_credit.boost_middle_class_tax_credit + input: + co_ccap_subsidy: 1 + boost_middle_class_tax_credit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 1 + +- name: From 2024 the Colorado subsidy leaves this reform's list and lowers the SPM expense instead. + period: 2024 + reforms: policyengine_us.reforms.congress.tlaib.boost.boost_middle_class_tax_credit.boost_middle_class_tax_credit + input: + co_ccap_subsidy: 1 + boost_middle_class_tax_credit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 0 diff --git a/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml b/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml index cf8c3331d02..2fc3b39667b 100644 --- a/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml +++ b/policyengine_us/tests/policy/contrib/congress/tlaib/economic_dignity_for_all_agenda/edaa_end_child_poverty_act.yaml @@ -263,3 +263,49 @@ output: household_benefits: 0 spm_unit_benefits: 0 + +- name: Before 2024 the Colorado subsidy stays a resource under this reform's list. + period: 2023 + reforms: policyengine_us.reforms.congress.tlaib.economic_dignity_for_all_agenda.end_child_poverty_act + input: + co_ccap_subsidy: 1 + ecpa_child_benefit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 1 + +- name: From 2024 the Colorado subsidy leaves this reform's list and lowers the SPM expense instead. + period: 2024 + reforms: policyengine_us.reforms.congress.tlaib.economic_dignity_for_all_agenda.end_child_poverty_act + input: + co_ccap_subsidy: 1 + ecpa_child_benefit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 0 diff --git a/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml b/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml index 1d9d3f1e04e..239e984cd8c 100644 --- a/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml +++ b/policyengine_us/tests/policy/contrib/congress/tlaib/end_child_poverty_act/integration.yaml @@ -159,3 +159,49 @@ output: household_benefits: 0 spm_unit_benefits: 0 + +- name: Before 2024 the Colorado subsidy stays a resource under this reform's list. + period: 2023 + reforms: policyengine_us.reforms.congress.tlaib.end_child_poverty_act.end_child_poverty_act + input: + co_ccap_subsidy: 1 + ecpa_child_benefit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 1 + +- name: From 2024 the Colorado subsidy leaves this reform's list and lowers the SPM expense instead. + period: 2024 + reforms: policyengine_us.reforms.congress.tlaib.end_child_poverty_act.end_child_poverty_act + input: + co_ccap_subsidy: 1 + ecpa_child_benefit: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 0 diff --git a/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml b/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml index b1e56bc9dde..f9a602be4ce 100644 --- a/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml +++ b/policyengine_us/tests/policy/contrib/states/tx/rebate/tx_rebate.yaml @@ -181,3 +181,53 @@ # not recur -- neither directly nor through the spm_unit_benefits path. tx_rebate: 0 spm_unit_benefits: 0 + +- name: Before 2024 these child care subsidies stay resources under this reform's list. + period: 2023 + reforms: policyengine_us.reforms.states.tx.rebate.tx_rebate.tx_rebate + input: + co_ccap_subsidy: 1 + wa_child_care_subsidies: 2 + wv_child_care_subsidies: 4 + tx_rebate: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 1 + 2 + 4 + +- name: From 2024 these child care subsidies leave this reform's list and lower the SPM expense instead. + period: 2024 + reforms: policyengine_us.reforms.states.tx.rebate.tx_rebate.tx_rebate + input: + co_ccap_subsidy: 1 + wa_child_care_subsidies: 2 + wv_child_care_subsidies: 4 + tx_rebate: 0 + spm_unit_capped_housing_subsidy: 0 + social_security: 0 + ssi: 0 + ca_cvrp: 0 + snap: 0 + wic: 0 + free_school_meals: 0 + reduced_price_school_meals: 0 + spm_unit_energy_subsidy: 0 + tanf: 0 + high_efficiency_electric_home_rebate: 0 + residential_efficiency_electrification_rebate: 0 + unemployment_compensation: 0 + basic_income: 0 + output: + spm_unit_benefits: 0 diff --git a/policyengine_us/tests/test_child_care_subsidies_household_benefits.py b/policyengine_us/tests/test_child_care_subsidies_household_benefits.py index e2742f0a3e6..77d7fab991d 100644 --- a/policyengine_us/tests/test_child_care_subsidies_household_benefits.py +++ b/policyengine_us/tests/test_child_care_subsidies_household_benefits.py @@ -56,9 +56,16 @@ def test_latest_blocks_list_every_state_program(): ) } assert len(defined) == 51 - for start, programs in blocks(PROGRAMS).items(): - if start >= "2025": - assert set(programs) == defined, start + # Every block from 2024 on lists all 51 programs. With no such block the + # loop would check nothing and pass. + latest = { + start: programs + for start, programs in blocks(PROGRAMS).items() + if start >= "2024" + } + assert latest + for start, programs in latest.items(): + assert set(programs) == defined, start def net_income_and_benefits(state, year, program, amount): diff --git a/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py new file mode 100644 index 00000000000..05188f32603 --- /dev/null +++ b/policyengine_us/tests/test_spm_child_care_subsidy_invariants.py @@ -0,0 +1,647 @@ +"""Invariants for child care subsidies in the Supplemental Poverty Measure. + +The Census Bureau's SPM technical documentation (last updated 2026-09-15): + +- Page 17 subtracts what parents paid for child care, combined with other work + expenses and capped at the earnings of the lower earner among the reference + person and spouse or partner. +- Section 4.3.1 lists the noncash benefits the SPM adds to resources: SNAP, + school lunch, WIC, energy assistance, internet assistance and housing + assistance. Child care is not among them. + +So a subsidy reaches the SPM once, as a lower expense. With E the pre-subsidy +expense, S the subsidy, W work expenses and C the earnings cap: + + expense(S) = min(W + max(E - S, 0), C) + +A unit with a child takes E from its members' pre_subsidy_childcare_expenses, +which an input can set apart from the unit's amount, and a direct +childcare_expenses input replaces max(E - S, 0) altogether. These properties +cover units that leave both to their formulas. + +For every SPM unit: + +1. The model's expense equals that reference, written from the documentation + rather than from the formula. +2. A subsidy never raises the expense and lowers it by at most the subsidy: + 0 <= expense(0) - expense(S) <= S. A larger subsidy never raises it either. +3. No double counting. With taxes and every other benefit held fixed, a + subsidy leaves spm_unit_benefits unchanged and raises spm_unit_net_income + by exactly expense(0) - expense(S). So this direct effect is never negative + and never exceeds the subsidy. +4. A subsidy of zero leaves the expense at min(W + max(E, 0), C), the formula + before this rule, in every state. +5. No program is counted twice. From 2024, no *_child_care_subsidies variable, + and no program one of them adds, appears in spm_unit_benefits or in a + reform's copy of that list, and all of them reach child_care_subsidies. + household_state_benefits counts them only through + household_child_care_subsidies. Before 2024 the expense has no formula, so Colorado's, Washington's and West + Virginia's subsidies stay resources and count once, as on main. The Tlaib + reform copies carry only Colorado's in those years, also as on main. +6. Differential. With real programs turned on and off, the expense falls by + the amount the reference gives for the subsidy the program paid, and the + SPM and household measures agree on what else changed: the change in SPM + net income is the change in household net income, less the subsidy the + household measure counts, plus the fall in the expense. + +Intended violation of "a subsidy never lowers SPM resources". Property 3 holds +taxes and other benefits fixed, and it has to. SNAP, TANF and tax credits read +out-of-pocket expenses, so a subsidy can cut them by more than the SPM expense +falls. A unit that stays at the earnings cap shows this most plainly, because +its expense does not move at all, and a benefit cliff can do it below the cap. +Household net income loses the same benefits but also counts the subsidy, so it +can rise while SPM income falls. test_subsidy_at_the_cap_can_lower_spm_income +pins one such case; the fall comes from those programs and not from this rule. + +The properties above read spm_unit_pre_subsidy_childcare_expenses as a +pre-subsidy price, which is what it means in a household calculation. Datasets +fill it from the ASEC, which asks parents how much they spent on child care, +and these properties read that amount as what parents paid after any subsidy. +So over a dataset, with E the reported amount, S0 the subsidy baseline policy +pays and S1 the subsidy the simulated policy pays: + + expense(S1) = min(W + max(E - (S1 - S0), 0), C) + +7. Baseline policy over a dataset leaves the expense at min(W + E, C), the + amount Census subtracts, whatever subsidy the model pays. +8. Under any policy over a dataset, the expense equals that reference, with or + without a child in the unit, and W and C come from the policy simulated. A + policy that pays the same subsidy and leaves W and C alone leaves the + expense where baseline policy put it. +9. Differential. Where the subsidy baseline policy pays does not exceed the + price, give a dataset the amount the household rule says a unit pays at + baseline policy. Then the two rules give the same expense under any + policy. A larger subsidy leaves the unit paying nothing, which hides the + price from the dataset rule. With the same input and real programs, + repealing a subsidy moves SPM net income by the same amount under both + rules, unless the earnings cap binds under either. +""" + +from functools import cache + +import numpy as np +import pytest +import yaml + +from policyengine_core.reforms import Reform +from policyengine_us import Simulation +from policyengine_us.system import CountryTaxBenefitSystem +from test_aggregate_list_integrity import ( + BASELINE_SPM_BENEFITS_SOURCE, + PACKAGE, + REFORM_AGGREGATE_OVERRIDES, + benefits_lists_in, + members_of, +) + +hypothesis = pytest.importorskip("hypothesis") +st = pytest.importorskip("hypothesis.strategies") +example, given, settings = hypothesis.example, hypothesis.given, hypothesis.settings + +YEAR = 2026 +TOLERANCE = 0.01 +# Income variables are float32, which rounds to about $0.03 at the $400,000 the +# fixtures below earn. Every input is a whole dollar, so this still catches a +# $1 error. +INCOME_TOLERANCE = 0.25 +PROGRAMS_LIST = "gov/hhs/ccdf/child_care_subsidy_programs.yaml" +STATE_SUBSIDIES = sorted(members_of(PROGRAMS_LIST)) +STATES = [name[:2].upper() for name in STATE_SUBSIDIES] + + +def reference_expense(pre_subsidy, subsidy, work, cap): + return min(work + max(pre_subsidy - subsidy, 0), cap) + + +def build_units(units): + """One SPM unit per entry. The parent's earnings are high enough that no + means-tested benefit pays, and taxes are an input, so only the child care + rule can move these units' SPM results.""" + people, tax_units, spm_units, families, households = {}, {}, {}, {}, {} + marital_units = {} + for i, unit in enumerate(units): + parent, child = f"parent_{i}", f"child_{i}" + people[parent] = { + "age": {YEAR: 35}, + "employment_income": {YEAR: 400_000}, + "is_tax_unit_head": {YEAR: True}, + "is_household_head": {YEAR: True}, + } + members = [parent] + marital_units[f"marital_unit_{i}"] = {"members": [parent]} + if unit.get("has_child", True): + people[child] = {"age": {YEAR: 4}, "is_tax_unit_dependent": {YEAR: True}} + members = [parent, child] + marital_units[f"child_marital_unit_{i}"] = {"members": [child]} + state = unit["state"] + tax_units[f"tax_unit_{i}"] = {"members": members} + families[f"family_{i}"] = {"members": members} + spm_units[f"spm_unit_{i}"] = { + "members": members, + "spm_unit_pre_subsidy_childcare_expenses": {YEAR: unit["expenses"]}, + "spm_unit_work_expenses": {YEAR: unit["work"]}, + "spm_unit_head_spouse_earned_cap": {YEAR: unit["cap"]}, + f"{state.lower()}_child_care_subsidies": {YEAR: unit["subsidy"]}, + "spm_unit_taxes": {YEAR: 0}, + } + households[f"household_{i}"] = { + "members": members, + "state_code": {YEAR: state}, + } + return { + "people": people, + "tax_units": tax_units, + "families": families, + "marital_units": marital_units, + "spm_units": spm_units, + "households": households, + } + + +amounts = st.integers(0, 40_000) +unit_strategy = st.fixed_dictionaries( + { + "state": st.sampled_from(STATES), + "expenses": amounts, + "subsidy": amounts, + "work": st.integers(0, 6_000), + "cap": st.integers(0, 60_000), + "extra_subsidy": st.integers(0, 10_000), + } +) + + +def spm_outputs(units): + simulation = Simulation(situation=build_units(units)) + return { + variable: np.asarray(simulation.calculate(variable, YEAR), dtype=float) + for variable in ( + "child_care_subsidies", + "spm_unit_capped_work_childcare_expenses", + "spm_unit_benefits", + "spm_unit_net_income", + ) + } + + +@settings(max_examples=25, deadline=None) +@given(st.lists(unit_strategy, min_size=1, max_size=4)) +def test_expense_nets_subsidies_exactly_once(units): + # Each unit runs three times in one simulation: as drawn, with no subsidy + # and with a larger subsidy. + without = [{**unit, "subsidy": 0} for unit in units] + larger = [{**u, "subsidy": u["subsidy"] + u["extra_subsidy"]} for u in units] + results = spm_outputs(units + without + larger) + expense = results["spm_unit_capped_work_childcare_expenses"] + benefits = results["spm_unit_benefits"] + net_income = results["spm_unit_net_income"] + + n = len(units) + for i, unit in enumerate(units): + reference = reference_expense( + unit["expenses"], unit["subsidy"], unit["work"], unit["cap"] + ) + no_subsidy = reference_expense(unit["expenses"], 0, unit["work"], unit["cap"]) + # 1. The expense matches the documented definition. + assert expense[i] == pytest.approx(reference, abs=TOLERANCE) + assert results["child_care_subsidies"][i] == pytest.approx( + unit["subsidy"], abs=TOLERANCE + ) + # 4. Without a subsidy the old formula still holds, in every state. + assert expense[n + i] == pytest.approx(no_subsidy, abs=TOLERANCE) + # 2. The fall is at least zero and at most the subsidy, and a larger + # subsidy never raises the expense. + fall = expense[n + i] - expense[i] + assert -TOLERANCE <= fall <= unit["subsidy"] + TOLERANCE + assert expense[2 * n + i] <= expense[i] + TOLERANCE + # 3. The subsidy is not a resource, so net income rises by the fall in + # the expense and by nothing else. + assert benefits[i] == pytest.approx(benefits[n + i], abs=TOLERANCE) + gain = net_income[i] - net_income[n + i] + assert gain == pytest.approx(fall, abs=INCOME_TOLERANCE) + + +def state_subsidy_adds(): + """{*_child_care_subsidies: the programs it adds}, from the model.""" + from policyengine_us.system import system + + return {name: list(system.variables[name].adds) for name in STATE_SUBSIDIES} + + +def all_subsidy_variables(): + """Every variable that pays a state subsidy or sums them.""" + variables = set(STATE_SUBSIDIES) | { + "child_care_subsidies", + "household_child_care_subsidies", + } + for programs in state_subsidy_adds().values(): + variables.update(programs) + return variables + + +def test_no_subsidy_is_a_spm_resource(): + subsidy_variables = all_subsidy_variables() + lists = { + "baseline spm_unit_benefits": benefits_lists_in(BASELINE_SPM_BENEFITS_SOURCE)[ + 0 + ][1] + } + for path, variable, members in REFORM_AGGREGATE_OVERRIDES: + if variable == "spm_unit_benefits": + lists[path] = members + assert len(lists) >= 5, f"expected the reform copies, found {sorted(lists)}" + counted_twice = { + name: sorted(subsidy_variables & set(members)) + for name, members in lists.items() + if subsidy_variables & set(members) + } + assert not counted_twice, ( + "Child care subsidies reach the SPM by lowering " + f"spm_unit_capped_work_childcare_expenses, not as resources: {counted_twice}" + ) + + +def test_household_measure_counts_each_subsidy_once(): + # Property 6 subtracts what household net income counts, so the household + # list has to count each subsidy once too. + others = all_subsidy_variables() - {"household_child_care_subsidies"} + blocks = yaml.load( + ( + PACKAGE / "parameters/gov/household/household_state_benefits.yaml" + ).read_text(), + yaml.BaseLoader, + )["values"] + assert "2024-01-01" in blocks + for start, members in blocks.items(): + if start >= "2024": + assert members.count("household_child_care_subsidies") == 1, start + assert not others & set(members), (start, sorted(others & set(members))) + + +def test_every_state_subsidy_is_in_the_programs_list(): + variables_dir = PACKAGE / "variables/gov/states" + defined = {path.stem for path in variables_dir.rglob("*_child_care_subsidies.py")} + blocks = yaml.load( + (PACKAGE / "parameters" / PROGRAMS_LIST).read_text(), yaml.BaseLoader + )["values"] + # The SPM expense reads the list from 2024, at the start of each year, so a + # program that starts paying during a year has to be in that year's block. + assert "2024-01-01" in blocks + for start, programs in blocks.items(): + if start >= "2024": + assert defined == set(programs), start + assert len(defined) == 51 + + +class NoSubsidies(Reform): + def apply(self): + for variable in STATE_SUBSIDIES: + self.neutralize_variable(variable) + + +@cache +def no_subsidy_system(): + return NoSubsidies(CountryTaxBenefitSystem()) + + +def family(state, earnings, expenses): + """A working parent and a child aged 3 in full-time care, with real + programs, taxes and benefits.""" + members = ["parent", "child"] + return { + "people": { + "parent": { + "age": {YEAR: 30}, + "employment_income": {YEAR: earnings}, + "weekly_hours_worked": {YEAR: 40}, + "weeks_worked": {YEAR: 52}, + "is_tax_unit_head": {YEAR: True}, + "is_household_head": {YEAR: True}, + }, + "child": { + "age": {YEAR: 3}, + "childcare_hours_per_day": {YEAR: 8}, + "childcare_days_per_week": {YEAR: 5}, + "childcare_attending_days_per_month": {YEAR: 21}, + "is_tax_unit_dependent": {YEAR: True}, + }, + }, + "tax_units": {"tax_unit": {"members": members}}, + "families": {"family": {"members": members}}, + "spm_units": { + "spm_unit": { + "members": members, + "spm_unit_pre_subsidy_childcare_expenses": {YEAR: expenses}, + "meets_ccdf_activity_test": {YEAR: True}, + } + }, + "households": {"household": {"members": members, "state_code": {YEAR: state}}}, + } + + +def with_and_without_subsidies(situation): + on = Simulation(situation=situation) + off = Simulation(situation=situation, tax_benefit_system=no_subsidy_system()) + + def change(variable): + return float(on.calculate(variable, YEAR).sum()) - float( + off.calculate(variable, YEAR).sum() + ) + + assert float(off.calculate("child_care_subsidies", YEAR).sum()) == 0 + return on, change + + +def subsidy_counted_by_household_measure(simulation, state): + """The subsidy household_state_benefits sums, through whichever variable it + lists: household_child_care_subsidies, the aggregate, the state's own + variable or a program that variable adds.""" + listed = simulation.tax_benefit_system.parameters( + f"{YEAR}-01-01" + ).gov.household.household_state_benefits + state_variable = f"{state.lower()}_child_care_subsidies" + candidates = { + "household_child_care_subsidies", + "child_care_subsidies", + state_variable, + *state_subsidy_adds()[state_variable], + } + counted = sorted(candidates & set(listed)) + # Listing two of them would count the subsidy twice. + assert len(counted) <= 1, counted + return sum(float(simulation.calculate(name, YEAR).sum()) for name in counted) + + +@settings(max_examples=12, deadline=None) +@given( + state=st.sampled_from(STATES), + earnings=st.integers(5_000, 60_000), + expenses=st.integers(0, 25_000), +) +# States that left the subsidy out before and states that counted it as a +# resource, at amounts where each program pays. +@example("NY", 30_000, 14_000) +@example("TX", 30_000, 14_000) +@example("AK", 30_000, 14_000) +@example("WA", 30_000, 14_000) +@example("WV", 30_000, 14_000) +@example("CO", 30_000, 14_000) +def test_spm_and_household_measures_agree(state, earnings, expenses): + on, change = with_and_without_subsidies(family(state, earnings, expenses)) + subsidy = float(on.calculate("child_care_subsidies", YEAR).sum()) + work = float(on.calculate("spm_unit_work_expenses", YEAR).sum()) + cap = float(on.calculate("spm_unit_head_spouse_earned_cap", YEAR).sum()) + fall = -change("spm_unit_capped_work_childcare_expenses") + assert fall == pytest.approx( + reference_expense(expenses, 0, work, cap) + - reference_expense(expenses, subsidy, work, cap), + abs=TOLERANCE, + ) + counted = subsidy_counted_by_household_measure(on, state) + assert change("spm_unit_net_income") == pytest.approx( + change("household_net_income") - counted + fall, abs=INCOME_TOLERANCE + ) + + +def test_new_york_subsidy_raises_both_measures_by_the_same_amount(): + # The Manhattan family from the report that prompted this rule. + situation = family("NY", 30_000, 14_000) + situation["households"]["household"]["county_fips"] = {YEAR: "36061"} + del situation["people"]["parent"]["weeks_worked"] + on, change = with_and_without_subsidies(situation) + subsidy = float(on.calculate("child_care_subsidies", YEAR).sum()) + assert subsidy > 13_000 + assert change("spm_unit_capped_work_childcare_expenses") == pytest.approx( + -subsidy, abs=TOLERANCE + ) + assert change("household_net_income") > 0 + assert change("spm_unit_net_income") == pytest.approx( + change("household_net_income"), abs=INCOME_TOLERANCE + ) + + +def test_subsidy_at_the_cap_can_lower_spm_income(): + # Intended: this unit stays at the earnings cap, so the SPM expense does + # not move, while the fall in out-of-pocket expenses cuts SNAP. See the + # module docstring. + on, change = with_and_without_subsidies(family("CA", 8_000, 25_000)) + assert float(on.calculate("child_care_subsidies", YEAR).sum()) > 0 + assert change("spm_unit_capped_work_childcare_expenses") == pytest.approx( + 0, abs=TOLERANCE + ) + assert change("snap") < 0 + assert change("spm_unit_net_income") == pytest.approx( + change("spm_unit_benefits") - change("spm_unit_taxes"), abs=INCOME_TOLERANCE + ) + assert change("spm_unit_net_income") < 0 + + +def with_baseline_arm(simulation): + """A branch named baseline, wired as a reform simulation wires its own. These + properties set each arm's subsidy directly, and a real reform builds a whole + tax-benefit system; the repeal test below and the microsimulation tests run + that path.""" + simulation.baseline = simulation.get_branch("baseline") + return simulation + + +def over_dataset(situation): + """A simulation that reads its inputs as a dataset's. Core sets this flag + when it loads a file; a situation lets these properties choose the inputs.""" + simulation = Simulation(situation=situation) + simulation.is_over_dataset = True + return simulation + + +def set_subsidies(simulation, baseline_subsidies, policy_subsidies): + simulation.baseline.set_input("child_care_subsidies", YEAR, baseline_subsidies) + simulation.set_input("child_care_subsidies", YEAR, policy_subsidies) + + +def capped_expense(simulation): + return np.asarray( + simulation.calculate("spm_unit_capped_work_childcare_expenses", YEAR), + dtype=float, + ) + + +dataset_units = st.lists( + st.fixed_dictionaries( + { + "state": st.sampled_from(STATES), + "expenses": amounts, + "subsidy": amounts, + "policy_subsidy": amounts, + "work": st.integers(0, 6_000), + "cap": st.integers(0, 60_000), + "policy_work": st.integers(0, 6_000), + "policy_cap": st.integers(0, 60_000), + "has_child": st.booleans(), + } + ), + min_size=1, + max_size=4, +) + + +@settings(max_examples=25, deadline=None) +@given(dataset_units) +def test_baseline_policy_over_a_dataset_keeps_the_reported_amount(units): + plain = over_dataset(build_units(units)) + simulation = with_baseline_arm(over_dataset(build_units(units))) + # 7. The subsidy input differs by unit and the expense ignores it. A + # simulation with no baseline and a baseline arm both hold baseline policy. + for baseline in (plain, simulation.baseline): + for unit, expense in zip(units, capped_expense(baseline)): + assert expense == pytest.approx( + min(unit["work"] + unit["expenses"], unit["cap"]), abs=TOLERANCE + ) + # 8. A policy that pays the same subsidy leaves the expense identical, with + # no rounding error from netting. + assert (capped_expense(simulation) == capped_expense(simulation.baseline)).all() + + +@settings(max_examples=25, deadline=None) +@given(dataset_units) +@example( + # A policy that pays more than the unit reported paying, so the floor binds. + [ + { + "state": "NY", + "expenses": 1_000, + "subsidy": 0, + "policy_subsidy": 5_000, + "work": 100, + "cap": 60_000, + "policy_work": 100, + "policy_cap": 60_000, + "has_child": True, + } + ] +) +@example( + # A repeal that takes a unit with no child to the earnings cap. + [ + { + "state": "TX", + "expenses": 5_000, + "subsidy": 8_000, + "policy_subsidy": 0, + "work": 100, + "cap": 6_000, + "policy_work": 100, + "policy_cap": 6_000, + "has_child": False, + } + ] +) +@example( + # A policy that pays the same subsidy but moves work expenses and the cap: + # 3,500 reads both from the policy, 3,100 would read W and 3,900 would read + # C from baseline policy. + [ + { + "state": "NY", + "expenses": 3_000, + "subsidy": 500, + "policy_subsidy": 500, + "work": 100, + "cap": 60_000, + "policy_work": 900, + "policy_cap": 3_500, + "has_child": True, + } + ] +) +def test_policy_over_a_dataset_moves_the_expense_by_the_subsidy_change(units): + # 8. Work expenses and the cap change on the policy's side only, which + # stores them after the baseline arm branches off. + simulation = with_baseline_arm(over_dataset(build_units(units))) + set_subsidies( + simulation, + [unit["subsidy"] for unit in units], + [unit["policy_subsidy"] for unit in units], + ) + simulation.set_input( + "spm_unit_work_expenses", YEAR, [unit["policy_work"] for unit in units] + ) + simulation.set_input( + "spm_unit_head_spouse_earned_cap", + YEAR, + [unit["policy_cap"] for unit in units], + ) + for unit, expense in zip(units, capped_expense(simulation)): + assert expense == pytest.approx( + reference_expense( + unit["expenses"], + unit["policy_subsidy"] - unit["subsidy"], + unit["policy_work"], + unit["policy_cap"], + ), + abs=TOLERANCE, + ) + + +@settings(max_examples=25, deadline=None) +@given(dataset_units) +def test_dataset_and_household_rules_agree_on_the_expense(units): + # 9. A subsidy no larger than the price keeps the floor out of the way at + # baseline policy, so the reported amount is the price less the subsidy. + baseline_subsidies = [min(u["subsidy"], u["expenses"]) for u in units] + policy_subsidies = [unit["policy_subsidy"] for unit in units] + reported = [ + {**unit, "expenses": unit["expenses"] - subsidy} + for unit, subsidy in zip(units, baseline_subsidies) + ] + household = with_baseline_arm(Simulation(situation=build_units(units))) + dataset = with_baseline_arm(over_dataset(build_units(reported))) + set_subsidies(household, baseline_subsidies, policy_subsidies) + set_subsidies(dataset, baseline_subsidies, policy_subsidies) + assert capped_expense(dataset) == pytest.approx( + capped_expense(household), abs=TOLERANCE + ) + assert capped_expense(dataset.baseline) == pytest.approx( + capped_expense(household.baseline), abs=TOLERANCE + ) + + +@pytest.mark.parametrize("state, county_fips", [("NY", "36061"), ("TX", None)]) +def test_repeal_moves_dataset_and_household_income_by_the_same_amount( + state, county_fips +): + # 9. Real programs and a real reform. The dataset reads $14,000 as what + # parents paid and the household calculation as the price. Neither rule's + # cap binds and both expenses rise by the subsidy, so SPM income falls by + # the same amount. The parent's earnings and hours stay raw inputs, which + # the simulation moves to their pre-response variables: the baseline arm + # has to read the moved values, or New York's arm sees no hours worked. + situation = family(state, 30_000, 14_000) + del situation["people"]["parent"]["weeks_worked"] + if county_fips: + situation["households"]["household"]["county_fips"] = {YEAR: county_fips} + _, household_change = with_and_without_subsidies(situation) + dataset = Simulation(situation=situation, reform=NoSubsidies) + dataset.is_over_dataset = True + dataset.baseline.is_over_dataset = True + + def dataset_change(variable): + return float(dataset.baseline.calculate(variable, YEAR).sum()) - float( + dataset.calculate(variable, YEAR).sum() + ) + + subsidy = float(dataset.baseline.calculate("child_care_subsidies", YEAR).sum()) + assert subsidy > 0 + assert float(dataset.calculate("child_care_subsidies", YEAR).sum()) == 0 + assert capped_expense(dataset.baseline).sum() == pytest.approx( + 14_000, abs=TOLERANCE + ) + assert dataset_change("spm_unit_capped_work_childcare_expenses") == pytest.approx( + -subsidy, abs=TOLERANCE + ) + assert household_change("spm_unit_capped_work_childcare_expenses") == pytest.approx( + -subsidy, abs=TOLERANCE + ) + assert household_change("spm_unit_net_income") != 0 + assert dataset_change("spm_unit_net_income") == pytest.approx( + household_change("spm_unit_net_income"), abs=INCOME_TOLERANCE + ) diff --git a/policyengine_us/tools/social_security_inputs.py b/policyengine_us/tools/social_security_inputs.py index 249a14a6a16..967d425dfb5 100644 --- a/policyengine_us/tools/social_security_inputs.py +++ b/policyengine_us/tools/social_security_inputs.py @@ -20,6 +20,7 @@ from pathlib import Path from weakref import WeakKeyDictionary, ref +import numpy as np from policyengine_core.data_storage.store_history import ( advance_sequence_past, next_sequence_number, @@ -41,6 +42,20 @@ # Keep the established envelope key so existing complete-snapshot callers # need not change; version two contains actual source values, never stamps. _PROVENANCE = "_social_security_input_provenance" +# A snapshot or extracted situation of a simulation over a dataset carries this +# key as true, and this package's builders turn it into the attribute below, +# so the simulation built from it still reads its inputs as a dataset's. +_DATASET_INPUTS = "_dataset_inputs" +_DATASET_INPUTS_ATTRIBUTE = "_inputs_from_dataset" +# A marked snapshot of a reform simulation lists here each formula override +# whose recorded input its baseline arm lacks or records differently, with the +# arm's recorded input (null for none). A reload gives its arm each listed +# input in place of the override and skips a null one. +_BASELINE_ARM_OVERRIDES = "_baseline_arm_overrides" +# A dump of a simulation whose inputs came from a dataset holds this file, with +# JSON true, in core's __entities__ directory, which core's restore reads only +# by the names it knows. +_DUMP_MARK_FILE = "dataset_inputs.json" _initial_social_security_ingress = ContextVar("initial_ss_ingress", default=False) _initial_social_security_writes = ContextVar("initial_ss_writes", default=None) @@ -67,6 +82,41 @@ class _Value: registered: bool +def holds_dataset_inputs(simulation): + """Whether a simulation's inputs came from a dataset: it runs over one, or + it was built from a snapshot (``export_source_inputs``) or an extracted + situation (``extract_person``) of a simulation that did, or core's + ``restore_simulation`` restored it from a dump of one. Core's ``clone`` + copies the attribute, so a branch, a clone and a reform's baseline arm + give the same answer as the simulation they copy.""" + return bool( + getattr(simulation, "is_over_dataset", False) + or getattr(simulation, _DATASET_INPUTS_ATTRIBUTE, False) + ) + + +def _dataset_mark(container, source): + """The dataset mark ``container`` carries: true or false, or false when it + has none. Any other value raises.""" + if _DATASET_INPUTS not in container: + return False + mark = container[_DATASET_INPUTS] + if not isinstance(mark, bool): + raise ValueError( + f"{source} holds {_DATASET_INPUTS} = {mark!r}: the mark must be true or " + "false." + ) + return mark + + +def _same_recorded_values(held, values): + try: + return np.array_equal(np.asarray(held), np.asarray(values), equal_nan=True) + except TypeError: + # Text has no NaN. + return np.array_equal(np.asarray(held), np.asarray(values)) + + def _enabled(simulation): return getattr( getattr(simulation, "tax_benefit_system", None), @@ -1067,12 +1117,16 @@ def load(first, *args, **kwargs): if not getattr(system, "_social_security_input_compatibility", False): return original(first, *args, **kwargs) metadata = None + from_dataset = False if not dataset: input_dict = args[1] if len(args) > 1 else kwargs["input_dict"] metadata = input_dict.get(_PROVENANCE) - if _PROVENANCE in input_dict: + from_dataset = _dataset_mark(input_dict, "The situation") + if _PROVENANCE in input_dict or _DATASET_INPUTS in input_dict: input_dict = { - k: v for k, v in input_dict.items() if k != _PROVENANCE + k: v + for k, v in input_dict.items() + if k not in (_PROVENANCE, _DATASET_INPUTS) } if len(args) > 1: args = (args[0], input_dict, *args[2:]) @@ -1095,6 +1149,11 @@ def load(first, *args, **kwargs): result = None try: result = original(first, *args, **kwargs) + if from_dataset: + # Inside core's __init__ the builder runs before core + # builds a reform's baseline arm, which clones this + # simulation and so keeps the mark too. + setattr(result, _DATASET_INPUTS_ATTRIBUTE, True) return result finally: _initial_social_security_writes.reset(writes_token) @@ -1190,6 +1249,8 @@ def extract_person(simulation, index=0, exclude_entities=("state",)): ) if metadata is not None: payload[_PROVENANCE] = metadata + if holds_dataset_inputs(simulation): + payload[_DATASET_INPUTS] = True return payload CoreSimulation.extract_person = extract_person @@ -1201,6 +1262,10 @@ def dump_holder(holder, directory): result = original_dump(holder, directory) if not _enabled(holder.simulation): return result + mark_path = Path(directory) / "__entities__" / _DUMP_MARK_FILE + if holds_dataset_inputs(holder.simulation) and not mark_path.exists(): + # Core makes __entities__ before it dumps any holder. + mark_path.write_text(json.dumps(True)) if holder.variable.name in (*SOCIAL_SECURITY_COMPONENTS, *_REPORTED_COMPONENTS): # A virtual source need not have a physically visible array. # Core creates the directory before discovering that; leave no @@ -1230,6 +1295,11 @@ def restore_holder( return original_restore( simulation, variable, directory, inputs, calculated_number ) + mark_path = Path(directory) / "__entities__" / _DUMP_MARK_FILE + if mark_path.exists() and _dataset_mark( + {_DATASET_INPUTS: json.loads(mark_path.read_text())}, str(mark_path) + ): + setattr(simulation, _DATASET_INPUTS_ATTRIBUTE, True) if not inputs and not getattr( simulation, "_social_security_source_data_restored", False ): @@ -1275,7 +1345,16 @@ def restore_holder( def export_source_inputs(simulation): - """Export all registered source periods and final overrides.""" + """Export all registered source periods and final overrides, and mark a + snapshot of a simulation whose inputs came from a dataset. For such a + simulation with a baseline arm, also list each formula override whose + recorded input the arm lacks or records differently, with the arm's + recorded input (null for none). A pure input or Social Security component + set on the reform after construction travels in ``sources`` or the + provenance envelope, so it reaches both sides of a reload.""" + marked = holds_dataset_inputs(simulation) + arm = simulation.baseline if marked else None + arm_overrides = {} names = { key: [str(name) for name in population.ids] for key, population in simulation.populations.items() @@ -1294,6 +1373,7 @@ def export_source_inputs(simulation): values = simulation._get_recorded_input_array(name, period) if values is None: continue + recorded = values if hasattr(values, "decode_to_str"): values = values.decode_to_str() if variable.is_input_variable(): @@ -1302,38 +1382,106 @@ def export_source_inputs(simulation): source.setdefault(name, {})[str(period)] = values[index] else: overrides.setdefault(name, {})[str(period)] = values - return json.loads( - json.dumps( - { - "version": 1, - "sources": sources, - "overrides": overrides, - _PROVENANCE: _automatic_reported_metadata(simulation), - "default_input_period": str(simulation.default_input_period), - "default_calculation_period": str( - simulation.default_calculation_period - ), - }, - cls=NpEncoder, - ) - ) + if arm is None or name not in arm.tax_benefit_system.variables: + continue + # Core gives the arm each value the dataset gave, so the arm + # lacks or differs from only what a caller set on this + # simulation after construction. + held = arm._get_recorded_input_array(name, period) + if held is None: + arm_overrides.setdefault(name, {})[str(period)] = None + elif not _same_recorded_values(held, recorded): + if hasattr(held, "decode_to_str"): + held = held.decode_to_str() + arm_overrides.setdefault(name, {})[str(period)] = held + payload = { + "version": 1, + "sources": sources, + "overrides": overrides, + _PROVENANCE: _automatic_reported_metadata(simulation), + "default_input_period": str(simulation.default_input_period), + "default_calculation_period": str(simulation.default_calculation_period), + } + if marked: + payload[_DATASET_INPUTS] = True + if arm_overrides: + payload[_BASELINE_ARM_OVERRIDES] = arm_overrides + return json.loads(json.dumps(payload, cls=NpEncoder)) def reload_source_inputs(payload, **simulation_kwargs): - """Reload complete snapshots, including legacy automatic projections.""" + """Reload complete snapshots, including legacy automatic projections. + + The overrides of a snapshot marked as a dataset's reach a reform's + baseline arm too, as core gives a dataset's values to both.""" from policyengine_us import Simulation if payload.get("version") != 1: raise ValueError("Unsupported source-input snapshot version") + marked = _dataset_mark(payload, "The snapshot") for period_name in ("default_input_period", "default_calculation_period"): simulation_kwargs.setdefault(period_name, payload[period_name]) metadata = payload.get(_PROVENANCE) sources = payload["sources"] if metadata is not None: sources = {**sources, _PROVENANCE: metadata} + if marked: + # The builder marks the simulation before core builds a reform's + # baseline arm, so the arm reads the snapshot as a dataset too. + sources = {**sources, _DATASET_INPUTS: True} simulation = Simulation(situation=sources, **simulation_kwargs) for name, periods in payload["overrides"].items(): for period, values in periods.items(): simulation.set_input(name, period, values) + if marked and simulation.baseline is not None: + _set_overrides_on_the_arm( + simulation, + payload["overrides"], + payload.get(_BASELINE_ARM_OVERRIDES) or {}, + ) _refresh_input_variables(simulation) return simulation + + +def _set_overrides_on_the_arm(simulation, overrides, arm_overrides): + """Set each override on ``simulation``'s baseline arm, or, where the + snapshot lists the source arm's recorded input, that input, and skip a + listed null. Skip a variable baseline policy doesn't define. Raise, naming + each variable, before setting anything, if the reform holds one in another + entity or with other ``ETERNITY`` storage than baseline policy: a dataset + giving it raises the same way.""" + from policyengine_us.spm import _built_for_another_policy + + arm = simulation.baseline + variables = arm.tax_benefit_system.variables + mirrored = {} + for name, periods in overrides.items(): + if name not in variables: + continue + held = arm_overrides.get(name, {}) + for period, values in periods.items(): + if period in held: + values = held[period] + if values is None: + continue + mirrored.setdefault(name, {})[period] = values + refused = sorted( + name + for name in mirrored + if _built_for_another_policy( + variables[name], + (holder := simulation.get_holder(name)).population, + holder, + ) + ) + if refused: + raise ValueError( + f"Baseline policy cannot hold the input given for {', '.join(refused)}: " + "the reform defines it in another entity or with other ETERNITY " + "storage than baseline policy, so the reform's baseline arm would " + "calculate it in place of the input." + ) + for name, periods in mirrored.items(): + for period, values in periods.items(): + arm.set_input(name, period, values) + _refresh_input_variables(arm) diff --git a/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py b/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py index 780033b204e..328d88cf0a3 100644 --- a/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py +++ b/policyengine_us/variables/gov/simulation/behavioral_response_measurements.py @@ -69,10 +69,8 @@ def _baseline_measurement_branch(simulation): - A branch shares its parent's baseline, and on policyengine-core before #587 so does a clone, so their baseline holds the parent's inputs. - - A reform simulation's baseline is a branch taken while it was built, - before this package moved ``employment_income`` and the other - pre-response inputs to their ``_before_lsr`` variables, so a household - baseline keeps them as overrides; later inputs never reach it. + - A reform simulation branches its baseline at the end of construction, + so inputs set on the simulation afterwards never reach it. ``simulation.get_branch("baseline")``, used before, was worse: for a branch or an early clone it made a new branch under the *reform* policy, so the diff --git a/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py b/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py index 672a93c41d3..4d536ed699e 100644 --- a/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py +++ b/policyengine_us/variables/gov/simulation/employer_payroll_tax_incidence/employer_payroll_tax_fixed_employer_cost_change.py @@ -340,13 +340,16 @@ def for_each_person(person, baseline_person, values): When both simulations list the same person IDs in the same order, they hold the same people, so values align by position, even where axes have - given two people one ID. Otherwise ``person`` belongs to a branch that - was subsampled: a branch shares its ancestor's baseline, and subsampling - the branch leaves that baseline's people in place. Core's ``subsample`` - keeps the rows of the chosen households (it selects them with ``isin``), - so each kept person appears once, with their ID, in their original - order, and a kept person's ID is unique in the baseline whenever the - ancestor's person IDs are. Axes can repeat a person ID, since they append + given two people one ID. A subsampled branch gets a baseline of its own + on the same sample, so it aligns by position too. Otherwise the baseline + lists other people than ``person``'s simulation, as where a branch's + subsample raised after core had resampled the branch but before it + rebuilt the baseline, and each person is looked up by ID. Where the + baseline stayed unsampled, core's ``subsample`` kept the rows of the + chosen households (it selects them with ``isin``), so each kept person + appears once, with their ID, in their original order, and a kept + person's ID is unique in the baseline whenever the ancestor's person IDs + are. Axes can repeat a person ID, since they append each cell's index to it (people "1" and "11" both get "110", in cells 10 and 0), so people are looked up only among the IDs the baseline has once. A person whose ID the baseline lacks or repeats raises @@ -394,11 +397,14 @@ def fica_pre_tax_totals(person, period, baseline): each apply to the side they belong to. Equal lists don't make equal totals, so the baseline's total always comes from the baseline simulation, matched to this simulation's people (``for_each_person``). - The baseline simulation holds the inputs this one was built with, or - rebuilt with by its own ``subsample``, and a branch keeps its ancestor's - baseline. So an input to the total or to a listed contribution, set on - this simulation after its baseline was built, counts as a change to - payroll wages. A formula for the total that reads employment_income is + The baseline simulation holds the inputs this one was built with, and a + branch shares its ancestor's baseline until its own ``subsample`` gives + it one. A ``subsample``, of a branch or of a reform simulation, rebuilds + the baseline on the same people from the inputs the simulation then + holds. So an input to the total or to a listed contribution, set on this + simulation after its baseline was built, counts as a change to payroll + wages until this simulation's own ``subsample`` rebuilds the baseline + with it. A formula for the total that reads employment_income is not supported: this variable is part of employment_income, so core raises a CycleError. """ @@ -504,12 +510,18 @@ class employer_payroll_tax_fixed_employer_cost_change(Variable): "simulation's, matched by person ID, so a reform to the total or to " "a listed contribution applies to the reform side alone, even when " "it keeps the list. The baseline simulation holds the inputs the " - "simulation was built with, or rebuilt with by its own subsample, " - "and a branch keeps its ancestor's baseline: an input to the total " - "or to a listed contribution, set on a reform simulation after its " - "baseline was built, counts as a change to payroll wages. A " - "subsampled branch raises for a person whose ID the baseline lacks " - "or repeats, as axes can. A formula for the total that reads " + "simulation was built with, and a branch shares its ancestor's " + "baseline until its own subsample gives it one. A subsample, of a " + "branch or of a reform simulation, rebuilds the baseline on the same " + "people from the inputs the simulation then holds. So an input to " + "the total or to a listed contribution, set on a reform simulation " + "after its baseline was built, counts as a change to payroll wages " + "until that simulation's own subsample rebuilds the baseline with " + "it. Where the baseline lists other people than the simulation, as " + "after a subsample that raised once core had resampled the " + "simulation, the variable matches each person by ID. It raises " + "NotImplementedError for a person whose ID the baseline lacks or " + "repeats, as axes can. A formula for the total that reads " "employment_income is not supported: core raises a CycleError. A " "simulation that supplies " "payroll_tax_gross_wages itself fixes payroll wages, so employer " diff --git a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py index f29e642e20b..353509a6ba7 100644 --- a/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py +++ b/policyengine_us/variables/household/expense/childcare/spm_unit_capped_work_childcare_expenses.py @@ -1,4 +1,5 @@ from policyengine_us.model_api import * +from policyengine_us.tools.social_security_inputs import holds_dataset_inputs class spm_unit_capped_work_childcare_expenses(Variable): @@ -7,9 +8,60 @@ class spm_unit_capped_work_childcare_expenses(Variable): label = "SPM unit work and childcare expenses" definition_period = YEAR unit = USD + documentation = ( + "Over a dataset, the child care part keeps the reported amount under " + "baseline policy and moves by the change in subsidy under a reform, " + "which it reads from the reform's baseline arm. Core builds that arm " + "only for a reform passed as reform=, and apply_reform builds none. A " + "simulation built with reform= keeps its arm, under baseline policy, " + "through any reform applied later. A reformed system passed as " + "tax_benefit_system=, or apply_reform on a simulation built without " + "reform=, leaves no arm, so the expense keeps the reported amount. " + "export_source_inputs marks a snapshot of a dataset simulation, " + "extract_person a situation extracted from one, and dump_simulation " + "a dump of one. A simulation built from a marked snapshot or " + "situation follows the same rule, as does its arm. One restored from " + "a marked dump follows it too, but core's restore_simulation builds " + "no arm, so where it calculates the expense it keeps the reported " + "amount. An unmarked snapshot, situation or dump reads as a household." + ) + reference = "https://www2.census.gov/programs-surveys/supplemental-poverty-measure/datasets/spm/spm_techdoc.pdf#page=17" def formula_2024(spm_unit, period, parameters): work_expenses = spm_unit("spm_unit_work_expenses", period) - childcare_expenses = spm_unit("spm_unit_pre_subsidy_childcare_expenses", period) + pre_subsidy_expenses = spm_unit( + "spm_unit_pre_subsidy_childcare_expenses", period + ) + # The SPM subtracts what parents paid for child care, and child care + # is not among its noncash benefits, so a subsidy lowers this expense + # rather than adding to resources. + simulation = spm_unit.simulation + if holds_dataset_inputs(simulation): + # Datasets fill the pre-subsidy input from the ASEC, which asks + # parents how much they spent on child care, and this rule reads + # that as what they paid after any subsidy. A snapshot, extracted + # situation or dump of a dataset simulation carries the same + # amounts, so a simulation rebuilt from one reads them the same + # way. Baseline policy keeps that amount, and a reform moves it by + # the change in subsidy. A baseline arm has no baseline of its + # own, so it keeps the amount. + out_of_pocket_expenses = pre_subsidy_expenses + if simulation.baseline is not None: + baseline_spm_unit = simulation.baseline.populations["spm_unit"] + subsidy_change = spm_unit( + "child_care_subsidies", period + ) - baseline_spm_unit("child_care_subsidies", period) + out_of_pocket_expenses = max_(pre_subsidy_expenses - subsidy_change, 0) + else: + # childcare_expenses holds the out-of-pocket amount, but it + # allocates expenses to children, so a unit with no child nets its + # own expenses here. + subsidies = spm_unit("child_care_subsidies", period) + has_child = add(spm_unit, period, ["is_child"]) > 0 + out_of_pocket_expenses = where( + has_child, + spm_unit("childcare_expenses", period), + max_(pre_subsidy_expenses - subsidies, 0), + ) earned_cap = spm_unit("spm_unit_head_spouse_earned_cap", period) - return min_(work_expenses + np.maximum(childcare_expenses, 0), earned_cap) + return min_(work_expenses + out_of_pocket_expenses, earned_cap) diff --git a/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py b/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py index 6d413264037..9cd621dac43 100644 --- a/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py +++ b/policyengine_us/variables/household/expense/childcare/spm_unit_pre_subsidy_childcare_expenses.py @@ -5,6 +5,13 @@ class spm_unit_pre_subsidy_childcare_expenses(Variable): value_type = float entity = SPMUnit label = "SPM unit pre subsidy child care expenses" + documentation = ( + "In a household calculation, the price of care before any subsidy. " + "Datasets fill it from the ASEC's SPM_CHILDCAREXPNS, what parents " + "reported spending on child care, which " + "spm_unit_capped_work_childcare_expenses reads as what they paid after " + "any subsidy." + ) definition_period = YEAR uprating = "gov.bls.cpi.cpi_u" unit = USD diff --git a/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py b/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py index ea833478b69..a3e7b44c108 100644 --- a/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py +++ b/policyengine_us/variables/household/income/spm_unit/spm_unit_benefits.py @@ -58,19 +58,14 @@ def formula(spm_unit, period, parameters): # summing it with ssi does not double-count. "ca_state_supplement", # Colorado programs. - "co_ccap_subsidy", "co_state_supplement", "co_oap", - # Washington programs. - "wa_child_care_subsidies", # New Mexico programs. "nm_ssi_state_supplement", # South Carolina programs. "sc_ssi_state_supplement", # Texas programs. "tx_ssi_state_supplement", - # West Virginia programs. - "wv_child_care_subsidies", "snap", "wic", "free_school_meals", @@ -112,4 +107,16 @@ def formula(spm_unit, period, parameters): BENEFITS.append("assigned_aca_ptc") if not parameters(period).gov.hud.abolition: BENEFITS.append("spm_unit_capped_housing_subsidy") + # From 2024, child care subsidies lower the expense in + # spm_unit_capped_work_childcare_expenses instead of adding to + # resources. That expense has no formula before 2024, so these three + # stay resources until then. + if period.start.year < 2024: + BENEFITS.extend( + [ + "co_ccap_subsidy", + "wa_child_care_subsidies", + "wv_child_care_subsidies", + ] + ) return add(spm_unit, period, BENEFITS)