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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/732.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add `pe.us.prepare_flat_file` to validate person-level inputs and `pe.us.flat_file_microsimulation` to simulate them in an assigned state or in their recorded states. Include a simulated instruments recipe.
1 change: 1 addition & 0 deletions docs/_quarto.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ website:
- households.md
- reforms.md
- microsim.md
- simulated-instruments.md
- section: "Analyse"
contents:
- impact-analysis.md
Expand Down
106 changes: 106 additions & 0 deletions docs/simulated-instruments.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
---
title: "Simulated instruments"
---

A simulated eligibility instrument runs one fixed population under the modelled rules for each state. `pe.us.flat_file_microsimulation` keeps the people fixed and changes their assigned state. The results also reflect the model's geographic defaults, including its choice of county for a moved household.

## The recipe

```python
import pandas as pd
import policyengine as pe
from policyengine.countries.us.data import US_STATE_FIPS

people = pd.read_csv("your_survey.csv", dtype={"county_fips": str})

snap_eligible = {}
for state in US_STATE_FIPS:
sim = pe.us.flat_file_microsimulation(
people,
year=2024,
state=state,
spm={"geography_kind": "national"},
)
snap_eligible[state] = sim.calculate("is_snap_eligible", "2024-01").mean()
```

`US_STATE_FIPS` maps postal codes to FIPS codes for the 50 states and DC, so the loop runs 51 times. `state` takes a postal code or a FIPS code as an integer or numeric string.

`calculate` returns a weighted series, and `mean()` gives a weighted share of the variable's own entity: SPM units for `is_snap_eligible`, people for `is_medicaid_eligible`. A monthly variable such as `is_snap_eligible` takes a month, and an annual one such as `state_income_tax` takes a year.

Pass `reform=` to run a reform in every state, and read the baseline arm from `sim.baseline`.

To run each household in the state your file records, leave `state` out. The file then needs `state_fips`.

## What your file needs

The file holds one row per person. Name a column after a PolicyEngine variable, or `variable__period` to date it. A column with no period holds the value for `year`. Use calendar years for age and for the geography fields the helper validates. Group membership stays fixed across periods. The loader also reads `person_{group}_role` columns and uses a bare `role` column for groups without their own roles.

If several columns give roles for the same group entity, the loader uses the first one in file order. The pinned loader's unused-variable warning can list role columns it has already used to assign roles.

| Column | Needed | Notes |
| --- | --- | --- |
| `household_id`, `tax_unit_id`, `spm_unit_id`, `family_id`, `marital_unit_id` | Yes | Put each on every person's row, numbered across the whole file. |
| `age` | Yes | The helper refuses a file without it, which would otherwise run everyone as 40. |
| `state_fips` | Unless you pass `state` | Supply a value that covers the requested year and each year with age inputs. The model carries the most recent value forward. Supply corresponding local geography when a household moves. |
| `person_id` | No | The helper numbers the rows if you leave it out. |
| `household_weight` | No | Every household weighs 1 without it. |
| `employment_income` and other inputs | As your measure needs | Give each in its variable's period: `employment_income` holds annual dollars. Inputs you omit take their defaults, usually zero. |
| `county_fips` | No | Read it as text so that 06037 keeps its leading zero. The helper repairs 6037 either way, and reads a blank as no county. |

A survey that restarts a group's ID in each household needs one number per group first:

```python
for column in ["tax_unit_id", "spm_unit_id", "family_id", "marital_unit_id"]:
people[column] = people.groupby(["household_id", column]).ngroup()
```

You can inspect how the helper prepares inputs for the base US model.

```python
prepared = pe.us.prepare_flat_file(people, year=2024, state="MS")
```

Standalone preparation uses the base US variable registry. Pass the original frame directly to `pe.us.flat_file_microsimulation` for inputs added by `reform=` on the default system. With an explicit `tax_benefit_system`, register additional input variables on that system before calling the simulation helper.

`prepare_flat_file` refuses a file that:

- lacks a required column
- has a blank ID, a fractional numeric ID, a column that mixes Boolean and numeric IDs, a repeated `person_id` or conflicting group membership columns
- numbers groups within each household
- gives one group's rows different values for a group-level variable such as `household_weight`

With `state` left out, it also refuses a county, tract, block, congressional district or state label that contradicts the state in any year the file holds, including years with only inputs such as earnings. For years before the first `state_fips` input, it checks against the model's California default.

The helper warns about unused columns and well-formed county FIPS codes absent from the model's lookup. The county formula uses the first county in the state when it resolves an unmatched FIPS. A stored county can take precedence.

When the file records its own geography, preparation validates state and county inputs for every covered year. When no supplied county takes precedence, the active model's county formula infers the county. The simulation keeps inferred values out of county storage, including during input loading. A simulation that loads the prepared frame directly can carry a county it infers for one year into another. Pass the original frame to `pe.us.flat_file_microsimulation` for results.

Preparation puts `state_fips`, `county_fips`, `county` and `county_str` first. The simulation then loads ordinary inputs before variables whose custom period-conversion handlers will run. These variables keep their file order, so a handler that reads another handler's output needs the producing column first. The dataset year is the default calculation period during loading. The simulation discards provisional calculation state between inputs and retains values that handlers explicitly store as inputs. Compute results that depend on the completed US simulation, such as behavioral responses, after construction.

## Reading results back

Each person-level result follows the rows of your file. Group-level results come back in the order your file first names each group, so pass `map_to="person"` for one value per row:

```python
people["state_tax"] = sim.calculate("state_income_tax", 2024, map_to="person").values
```

`map_to="person"` repeats a group's value on each member's row, so a sum across rows counts it once per member. `sim.calculate("household_id", 2024)` holds the IDs from your file when the ID column contains whole numbers within the signed 32-bit range, including whole numbers stored as floats or in an object column. Other group ID columns use their model variables' own types. For example, `family_id` uses 32-bit floating-point storage, which cannot distinguish every integer beyond 16,777,216. The helper numbers text IDs and all-numeric columns that contain an ID the model cannot store exactly by first appearance. It warns with the column name when it recodes an all-numeric column. Use input row order or the prepared IDs to map back after recoding.

## What a state change clears

Passing `state` sets `state_fips` in every year your file holds. It clears county, ZIP code, congressional district, tract and other local geography for every household, including those already in the assigned state. It also clears location-based inputs such as `is_rural`, `in_la`, ACA rating areas, SNAP utility regions, child-care eligibility areas based on household residence and HUD rent lookups. State assignment preserves supplied child-care provider rate areas and county groups. A stored outcome such as eligibility or tax can override its formula.

Rules that read the county enum use the state's first county alphabetically when a county is missing. In Minnesota that is Aitkin County. The bundle defaults to county-based SPM thresholds. The recipe passes `{"geography_kind": "national"}` so every state uses the same national SPM thresholds for the same household inputs. To keep real counties, leave `state` out and run each household where the file records it.

With or without `state`, the helper removes stored copies of what the model derives from the state, such as `state_group`, so the model's formulas run.

## What to watch for

- **Years after your file.** The model can carry your latest input values forward and uprates inputs with an uprating rule. In this bundle, $20,000 of 2024 earnings reads as $20,987 in 2025, and a 2024 household weight of 1,000 reads as 1,009 in 2025, rounded to the nearest dollar and whole weight.
- **Years before your inputs.** The helper prepares the file for the supplied `year`. Calculate outcomes for years the file describes. When a simulation reads a year before the relevant inputs, values can fall back to model defaults, including California and age 40.
- **Medicaid dollars.** `medicaid` allocates each state's total spending across the people in your file who enrol, using their sample weights and Medicaid cost indices. A small sample can therefore produce very large amounts per person. `healthcare_benefit_value` includes those Medicaid amounts. Use `is_medicaid_eligible` to measure eligibility.
- **Deciles.** Income deciles rank households within your file.
- **Minors on their own.** The SPM calculation needs someone aged 18 or over in each SPM unit, or someone aged 15 to 17 with `is_household_head`, `is_household_spouse` or `is_spm_independent_minor_role` set. These inputs use `__ETERNITY`. Keep columns with this suffix when you filter `sim.to_input_dataframe()` to one year. If your file supplies `is_spm_independent_minor_role`, copy it from your source to the new flat file as `is_spm_independent_minor_role__ETERNITY`. The default export omits it.
- **Changing state after the build.** `sim.set_input("state_fips", ...)` leaves stored geography in place. Pass `state` so that the helper clears it first.
3 changes: 3 additions & 0 deletions src/policyengine/tax_benefit_models/us/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
load_managed_long_term_datasets,
validate_long_term_dataset_metadata,
)
from .flat_file import flat_file_microsimulation, prepare_flat_file
from .household import calculate_household
from .model import (
PolicyEngineUS,
Expand Down Expand Up @@ -81,6 +82,8 @@
"model",
"us_latest",
"calculate_household",
"flat_file_microsimulation",
"prepare_flat_file",
"SPMSelection",
"SPMProvenance",
"economic_impact_analysis",
Expand Down
Loading
Loading