Skip to content

Let state_fips decide a dataset household's state - #10574

Draft
MaxGhenis wants to merge 8 commits into
mainfrom
simulated-instrument-flat-file
Draft

MaxGhenis wants to merge 8 commits into
mainfrom
simulated-instrument-flat-file

Conversation

@MaxGhenis

@MaxGhenis MaxGhenis commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Lets a researcher run one flat file through each state by setting state_fips. Depends on PolicyEngine/policyengine-core#646, which has to ship first. Stays a draft until that release lands and the core pin moves here.

people = pd.read_csv("your_survey.csv")
for fips in STATE_FIPS.values():
    people["state_fips__2024"] = fips
    data = Dataset.from_dataframe(people, 2024)
    sim = Microsimulation(dataset=data, spm={"geography_kind": "national"})
    snap = sim.calculate("is_snap_eligible", "2024-01")

What was wrong

A file can place a household through several columns, and this loop changes one of them. What the file still said about the old state then contradicted it:

  • A stored county_fips kept the old county's SPM thresholds under the new state's rules, and crashed county-keyed parameters such as Minnesota's CCAP rates with ParameterNotFoundError.
  • A stored state_code kept the old state's rules altogether, with no error.
  • An integer county_fips, which is what read_csv gives for 06037, quietly became the first county in the state. A five-digit one such as 36061 resolved to its county in any state.
  • A county stored for another year still applied: county_fips__2023 with state_fips__2024 kept Los Angeles in Mississippi, and so did a state that changed between two years of one file.
  • county read "the latest known period", which includes values the simulation had calculated. So 2025 took 2024's county when 2024 ran first, and the answer depended on calculation order.
  • A stored state_group kept Alaska on the contiguous poverty guideline.
  • A flat file with no classified adult failed with an SPM error that did not name the columns that fix it.

What changes

  • state_fips decides the state (policyengine_us/tools/geography/state_assignment.py). Both simulation classes reconcile dataset geography after building the baseline. Each arm uses its own formulas to recompute stale geography.
    • Each year answers for what it reads, including what it carries from another year.
    • A stored state_code, state_name or state_code_str that disagrees takes the value state_fips implies.
    • A stored copy of what the model derives from the state (state_group, state_group_str, tax_unit_state, spm_unit_state_fips, the in-state flags) goes if it disagrees, so its formula runs. Agreeing labels and copies stay recorded as inputs.
    • The step clears each local field that names another state, for that household only, and keeps agreeing county observations. County-keyed rules use the first county in the state when no county is known. That fallback cannot establish Alameda residence (in_ala). SPM county thresholds still require a valid text county_fips.
    • For the affected rows, each arm recomputes what the model derives from local geography (in_nyc, in_ny_mctd_zone_2, medicaid_rating_area, three_digit_zip_code) under its own policy. The other rows keep their stored values.
    • A logged warning names the stale fields and, when no valid county_fips remains, points to {"geography_kind": "national"} for SPM thresholds. It goes through logging because this package silences the warnings module.
  • county reads recorded inputs. latest_readable_county prefers the latest input in force, so a calculated county stays in its own year. When reconciliation replaces a later input, an earlier year keeps the county it read.
  • Clear refusals and warnings. A state_fips with no state in the model, such as a territory other than Puerto Rico, raises a ValueError at load that says what the model covers. A county_fips that holds numbers logs what that costs, a text code that names no county logs its fallback, and a state_fips that differs between a file's years logs a warning.
  • The SPM composition error names its columns, including the __ETERNITY suffix that a filter on one year's columns drops. The error code stays the same.
  • source_input_variables declares the SPM source role (is_spm_independent_minor_role) and the observed county and county_str, so the export with core from Make flat-file datasets safe to load, map and round-trip policyengine-core#646 keeps them (needs the core release). The period export follows core's selection rules.

Decisions

Each failure in the slide's path, and what this PR does with it:

Failure Decision
Stored formula variables drop out of exports Fixed in core. The SPM source role, county and county_str are declared here
__ETERNITY columns get lost, then SPM fails Clearer error here. Core's period= export keeps them. Roles stay unsynthesized, as spm.py requires
State swap with a stale county crashes Fixed here
state_fips covers one year of a multi-year export Warning here. The policyengine.py helper sets every year
map_to on text variables fails Fixed in core

Treating contradicting geography as unknown, rather than refusing the file, is a judgment call. A refusal would make the slide's loop fail on any file that holds a county. The warning covers the case where the contradiction means a damaged file.

This PR does not repair numeric counties. test_spm_system.py pins that SPM refuses them, and a bare 5 can be a legacy CPS within-state code, so zero-filling it would invent a county. Numbers count only as evidence of a contradiction: 36061 or 6037 in Minnesota names another state. The policyengine.py helper does repair them, because its caller has told it the column holds county FIPS codes.

A household already in the target state keeps its real county. So on a sample through the loop, New York's five NYC households differ from the same file with county dropped by hand, and they should.

Invariants

  • For any dataset, after load, stored state labels equal the label state_fips implies, in every year with a state.
  • No household reads local geography that names another state, in any year. Property tests over pairs of states in test_state_fips_always_decides_the_state, and over two-year files with a county in any of three years in test_every_year_reads_a_county_in_its_own_state.
  • county for a year does not depend on which years ran first.
  • Agreeing geography with a stable state timeline stays recorded.
  • Differential: with no surviving county observation, a stale county and an absent county use the same county-keyed fallback.

Tests

  • test_state_assignment.py: nine household regressions pass against both the locked core (3.37.2) and core from Make flat-file datasets safe to load, map and round-trip policyengine-core#646.
  • test_local_sales_tax_county_carryover.py: four carryover tests pass against the locked core.
  • 149 YAML cases pass on the branch and on a merge with main, in the new state_assignment.yaml and the 13 other test files that mention in_ala or county_is_imputed.
  • Against the local core, reading the file from a CSV end to end, test_flat_file_state_swap.py, test_county_branch_reuse.py, test_county_from_dataset.py, test_local_sales_tax_county_carryover.py and test_spm_system.py gave 186 passes. That run predates commit 1f05698533 and has not been rerun.

Real-data checks

These checks predate commit 1f05698533, which keeps agreeing county observations and stops the county fallback from establishing Alameda residence, and have not been rerun. They ran against core at this branch's companion head, on Populace US populace-us-2024-spm-20260909:

  • Loading Populace (166,321 people, 57,240 households) logs no state warnings. The new step took 0.5 seconds on a heavily loaded host.
  • A 300-household sample read back from CSV ran through all 51 states with its stored county, tract, block and congressional district kept, as the slide's loop would. No state failed, and state_code was right in all 51. SNAP eligibility took 26 distinct values, Medicaid eligibility 46, state income tax 45, and national SPM thresholds exactly one. Each state took about 6.6 seconds.
  • Stale geography kept versus dropped by hand, for MN, MS and NY, on household_net_income, state_income_tax, is_snap_eligible, is_medicaid_eligible and mn_child_care_subsidies: no differences except the five NYC households above.

Follow-ups

axiom: n/a: dataset input handling, no policy change

🤖 Generated with Claude Code

A simulated instrument keeps each family and sets state_fips to one state
after another, so whatever else the file says about the old state has to
yield. Stored state labels now follow state_fips, and local geography that
contradicts it becomes unknown for that household with a logged warning.
Warnings go through logging because this package silences the warnings
module.

The SPM composition error now names the columns that clear it, and
is_spm_independent_minor_role declares itself a source input so exports
keep it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A county stored for another year escaped the check, because it compared only
periods that stored geography, and only text values. Compare what each year
reads, carried values included, and read numbers as evidence of a state without
rewriting them: spm.py refuses numeric counties on purpose, and a bare 5 can be
a CPS within-state code.

county took the latest known period, which includes values the simulation
calculated, so 2025 inherited 2024's county when 2024 ran first. Only inputs
count now. Stored copies of what the model derives from the state or from
stale local geography go, so their formulas run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxGhenis and others added 3 commits November 30, 2026 18:28
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Restore matching observations across state changes, retain county provenance and preserve unaffected rows. Clarify input diagnostics and route flat-file integration tests to the microsimulation suite.

Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov

codecov Bot commented Nov 30, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (8999568) to head (ac72e6d).
⚠️ Report is 410 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main    #10574   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            1         1           
  Lines           24       117   +93     
=========================================
+ Hits            24       117   +93     
Flag Coverage Δ
unittests 100.00% <100.00%> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

MaxGhenis and others added 2 commits December 1, 2026 07:23
Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant