Skip to content

Run a researcher's flat file through each state's rules - #733

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

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

Conversation

@MaxGhenis

@MaxGhenis MaxGhenis commented Nov 1, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #732

Adds pe.us.prepare_flat_file, which validates a researcher's person-level flat file, and pe.us.flat_file_microsimulation, which runs the same people through one assigned state's rules or through their recorded states. The simulated instruments recipe is at docs/simulated-instruments.md.

Why here

policyengine.py gives researchers one interface for validating flat files and running the bundled models. PolicyEngine/policyengine-core#646 and PolicyEngine/policyengine-us#10574 address direct loading and geography in the models. The helpers work at this package's existing pins (policyengine-core==3.34.10, policyengine-us==2.2.2, spm-calculator==1.1.0). No pin moves in this PR, and no bundled number changes.

What it does

The pinned loader accepts bare IDs and reads each group's values from its first member. prepare_flat_file adds periods to variable columns and keeps the bare role column. It puts every ID on each person's row and numbers group memberships by first appearance.

  • It keeps whole-number IDs that the model can store exactly. It recodes text and Boolean labels, and any all-numeric column that holds an ID the model can't store exactly, by first appearance, and it warns with the column name when it recodes an all-numeric column. The model stores family_id as a 32-bit float. Use the prepared IDs or person row order to map recoded results back.
  • It pads county_fips to five digits. For recorded states, it requires coherent geography in every covered year and accepts geographic enum names, valid indices and members of the expected enum classes, including members from another system with the same qualified class name and source file. It refuses a member of another enum, even one with a matching index.
  • It writes no county inputs of its own. In flat_file_microsimulation, when no supplied county takes precedence, the active model's county formula infers the county. Preparation puts state FIPS and county inputs first. The simulation loads ordinary inputs before custom period handlers, keeps inferred counties out of county storage, and discards provisional calculation state between inputs, so a handler sees the file's geography and the formula can't reuse a county it inferred for one year in another.
  • It warns about a well-formed county FIPS code that names no county in the lookup. For an unmatched FIPS, the county formula uses the state's first county, and a stored county can take precedence.
  • With state=, it sets state_fips in every covered year and clears household geography, including residence flags and location-based ACA, housing, child care and SNAP inputs. State assignment preserves supplied child-care provider rate areas and county groups: Oregon's or_erdc_provider_area, Mississippi's ms_ccpp_facility_location, New York's ny_ccap_county_group and Ohio's oh_ccap_county_rate_category. In either mode, it clears state-derived fields such as state_group.
  • It keeps the first role column for each group entity, the one the pinned loader reads. It logs and drops other columns that name no variable before it checks for duplicate variable periods. prepare_flat_file looks variables up in the base US registry. flat_file_microsimulation looks them up in the registry of the system it loads into, which on the default system includes variables that reform= adds. With an explicit tax_benefit_system, register any input that reform= adds on that system before calling the helper.

It refuses empty files, missing required columns, blank or fractional IDs, columns that mix Boolean and numeric IDs, repeated person IDs, conflicting group memberships, and rows of one group that disagree on a group-level input.

flat_file_microsimulation records the resolved SPM selection and marks the runtime dataset as flat_file in policyengine_bundle. The record holds the input year, the assigned state when supplied, and a SHA-256 fingerprint of the typed prepared frame and the model's stored inputs. For a stored enum input, the fingerprint also covers the enum and the names of its selected members.

Decisions

  • The recipe passes spm={"geography_kind": "national"}, so the same people get the same national SPM thresholds in every state. After a move, model rules that read the county enum use the assigned state's first county by default.
  • With state=, the helper clears household location inputs for every household, including those already in the assigned state. It preserves those provider inputs because a child care provider's location can differ from the household's. To keep the recorded geography, leave state unset.
  • The helpers store no inferred county. With a stored county, the model never calls first_county_in_state, so it would ignore a reform to that fallback. The pinned county formula also returns the latest stored county for any year without its own county input. A simulation that loads the prepared frame directly stores the counties it infers, so pass the original frame to flat_file_microsimulation for results.
  • The pinned loader warns and skips an unknown variable with one period separator, and can fail to parse a header with several. The helper drops unused survey columns before it checks periods, and keeps the role metadata the loader reads.

Invariants

  • Preparing a file leaves the caller's frame unchanged. Preparing a prepared file, or moving a file to the same final state twice, gives the same inputs.
  • Numeric and text forms of a county FIPS agree. A simulation from flat_file_microsimulation returns the same county and benefits for each covered year in any calculation order.
  • Person results follow input row order. Group results follow first appearance, and row order leaves group membership unchanged.
  • A moved file and a clean file in the assigned state agree on the tested household location inputs. With state=, the helper keeps a supplied child care provider location that differs from the one a clean run infers.
  • The fingerprint differs for changed household weights, changed input types, different allocations of overlapping input periods, and stored enum inputs whose selected members carry different names.

Changes since cda0744c6

In c53060e6a:

  • For recorded states, prepare_flat_file no longer stores a county for each covered year when the file has county FIPS or changes states. The pinned county formula returns the latest stored county for any year without its own county input, so the model could give a year between two recorded years the later year's stored county. With a stored fallback county, the model also never called a reformed first_county_in_state. New tests cover a household in Vermont in 2024 and Mississippi in 2026, in both calculation orders, and a reformed fallback county. Two existing county tests now run through flat_file_microsimulation instead of loading the prepared frame directly.
  • With state=, the helper keeps Oregon's or_erdc_provider_area and Mississippi's ms_ccpp_facility_location. A new test supplies an Oregon AREA_A provider and expects the $1,041 maximum monthly infant rate.
  • The helper checks the enum of each member in state_code, state_name and county before encoding it. The pinned encoder reads only a member's index. County.BETHEL_CENSUS_AREA_AK and StateCode.CA both have index 4, so the helper had accepted that county in state_code as CA.
  • The helper keeps the first role column for each group entity, the one the pinned loader reads, and drops later ones. It had refused two dated role columns for one entity as a duplicate.
  • The fingerprint now covers the enum and selected member names of each stored enum input. A new test gives one stored index different names under two reforms and expects different fingerprints. The overlapping-period test now runs for SSI as well as SNAP.
  • The guide and docstrings now describe the base registry for standalone preparation, the bare role column, the first-role-column rule, the loader's role warning and the county-enum fallback.

In 97a6fee04, the helper also keeps New York's ny_ccap_county_group and Ohio's oh_ccap_county_rate_category under state=. The model derives both from household county as a proxy for the provider's county. A parametrized test supplies a Mississippi, New York or Ohio value that a clean run would not infer and expects it back. The prepare_flat_file docstring and the guide now say that a simulation loading the prepared frame directly can carry an inferred county across years.

#785 tracks a fingerprint that can change between processes when a reform replaces an enum variable whose enum lives in another file.

Tests

At ee4052d1e, local checks cover only py_compile, git diff --check and ruff format; GitHub CI runs the full suite on this head. At the earlier head 97a6fee04, the code CI passed, including Test on Python 3.11 through 3.14, and the separate documentation build passed.

At cda0744c6 (CPython 3.14.10, the locked dev environment), tests/test_us_flat_file.py passed all 200 tests. The same file with the new tests overlaid at 45ef535fa gave 107 passes and 93 failures. The rest of tests/ at cda0744c6 gave 4,896 passes and 20 skips. Four UK qualification cases failed there because they read a release index that needs a credential, and they fail the same way at 45ef535fa. At cda0744c6, a hand-built CSV ran through all 50 states and DC with identical national SPM thresholds.

Real-data check

The PR author ran this check at an earlier head and has not repeated it at cda0744c6 or 97a6fee04.

A 300-household Microcosm US sample with 822 people, read back from CSV, ran through the helper for CA, MS, MN, DC and NY, and through its own states. state_code was right in each, and national SPM thresholds matched across states. It logged five columns the pinned model does not know, as designed.

Differential at the versions then pinned: the helper with state="MN" gives the same SNAP eligibility, Medicaid eligibility, income, state tax and net income as the same file loaded directly with geography dropped by hand. Means match, and values match once sorted, because group results follow file order.

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

🤖 Generated with Claude Code

MaxGhenis and others added 3 commits November 1, 2026 17:25
Fixes #732

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Group IDs numbered within households merge strangers, and rows of one group
that disagree lose all but the first person's value. Neither raises at load.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxGhenis and others added 10 commits November 2, 2026 03:37
The pinned loader sorts groups by ID but reads a one-row-per-group column in
row order, so one-person groups in any other order took each other's values.
Number memberships in file order, and keep the file's own IDs in {group}_id so
results merge back on them.

Check geography across every year the file holds, including county names and
tract, block and district columns, and drop stored copies of what the model
derives from the state. Record the year, state and a digest with the run, and
rewrite the recipe around what the trial found unclear.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…mber IDs

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

Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: GPT-6.2 Sol <noreply@openai.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Round 3 found that stored county inputs leaked a future county into earlier years and masked county reforms; that state assignment dropped the Oregon child-care provider area; that a member of the wrong enum passed geography checks; that dated role headers collided; and that stored enum inputs with different members could share a fingerprint. The helper no longer writes county inputs: inferred counties come from the active model formula and stay out of cross-year lookups. State assignment keeps the Oregon provider area and the Mississippi facility location. Geography checks the enum class before encoding. The first role column per entity is kept before periods are added. The fingerprint now includes the enum and its member names. The guide and module text now match the base-registry path, the bare role column, the loader's role warning and the county fallback. Tests cover each case, and the overlapping-period test now runs for SNAP and SSI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The model uses household county as a proxy for the child care provider's location in four rate inputs: Oregon's provider area and the Mississippi, New York and Ohio county categories. State assignment now keeps all four when a file supplies them, and a parametrized test checks Mississippi, New York and Ohio against a value the clean run would not infer. The prepare_flat_file docstring and the guide now say that loading the prepared frame directly can carry an inferred county across years. Two new test calls are wrapped to the 88-character line limit.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
MaxGhenis and others added 2 commits December 2, 2026 23:15
- Set the county holder's no-store flag before Core loads inputs, and drop
  values that load-time input handlers computed, so a handler that runs
  before or after geography never caches a stale county.
- Stop state assignment from clearing 23 child-care provider rate selectors;
  a supplied rate area or county group now survives and sets the rate.
- Accept a state_code, state_name or county member from another US system
  when its enum class has the same qualified name and source file, instead
  of refusing it.
- Describe county inference during loading and the provider selectors that
  state assignment keeps in docs/simulated-instruments.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A flat-file load now clears simulation branches, the fast cache and the
behavioural-response cache after each load-time input, and restores a
registered baseline when loading ends. Branches are snapshots, so a
handler's calculation on one could otherwise outlive the partial input
set it saw. When a handler starts a calculation, the loader also drops
computed arrays, snapshots the SPM forecast provider and re-records
county input types.

Preparation puts state FIPS and the county fields first, and variables
with custom period-conversion handlers load after ordinary inputs, so a
handler sees the file's geography rather than California's default.
New tests cover the stale-branch case and four state and county cases;
docs/simulated-instruments.md describes the load order.

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.

Run a researcher's own flat file through each state's rules

2 participants