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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 27 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,32 @@ If a version bump takes the function past 225 MiB, the install comes back, and t

An install that stops partway leaves its temporary files in `/tmp`. If a complete install no longer fits beside them, every request on that instance fails with "No space left on device" until the platform replaces it. `tests/test_deploy_footprint.py` fails when the function passes 225 MiB, and when a complete install stops fitting on top of a stopped one. If the first fails after a version bump, trim another package, or accept the install and update this section. If the second fails, trim another package or give one a URL source. `main` requires no checks, so a failing run warns the author of a bump and doesn't block its merge.

## County from ZIP

The form asks for a ZIP and no county. The API resolves the county, so the form, share links, direct API calls and the Modal fallback all follow one rule:

1. An explicit `county`, such as a share link's `county=MIDDLESEX_COUNTY_MA`, always wins.
2. Otherwise the household gets the ZIP's first county in its state. A ZIP that spans counties lists the county with the most 2020 Census residents first, and a tie goes to the lower county code.
3. A ZIP code tabulation area (ZCTA) with no residents ranks its counties by land area.
4. A ZIP with no ZCTA of its own, such as a post-office-box ZIP, uses GeoNames' county, or else the first county in its state of the ZCTA the crosswalk gives it.
5. A ZIP with no county in the household's state resolves to nothing. policyengine-us then uses the state's first county alphabetically, and the results page says so.

A series response carries a `location` block saying which county the calculation used and why (`source` is `explicit`, `zip` or `none`). When a ZIP spans counties, the results page shows each county's share of the ZIP's residents and lets the user pick another. The choice goes in the share link, and editing the ZIP clears it. The API also sends the ZIP to policyengine-us, because Los Angeles County's rating area reads it.

The small-area rent variables read the ZIP too, but no household takes up housing assistance. CliffWatch has no input for whether a household holds a voucher (#30), and its rent field also takes mortgage payments, so wherever the ZIP carries a payment standard the engine would otherwise pay a voucher's subsidy to renters and homeowners alike.

policyengine-us finds a county's ACA rating area by joining the county's code to its `aca_rating_areas.csv`, and it gives rating area 1 to any county the join misses. That file spells 31 counties differently from their codes: `BAYLOR_TX` for `BAYLOR_COUNTY_TX`, `DONA_ANA_NM` for `DOÑA_ANA_COUNTY_NM`, and the former Valdez-Cordova and Wade Hampton rows for the census areas that replaced them. `RATING_AREA_OVERRIDES` in `cliff_watch/zip_county.py` sends those counties' rating areas with the county. Oglala Lakota County, South Dakota, has no row under any name and keeps rating area 1. `tests/test_zip_county_engine.py` fails when an engine update changes those rows or fixes the names, so the list goes when the gap does.

policyengine-us has no benchmark premium for three counties: Calhoun and Edgefield in South Carolina, and Gulf in Florida. A household there reads no premium tax credit, so `location.has_benchmark_premium` turns false and the results page says so. `tests/test_zip_county_engine.py` compares that list with the engine and fails when an engine update adds those rating areas, so the note goes when the gap does.

`scripts/build_zip_county.py` builds `cliff_watch/data/zip_county.json.gz`. It reads the [Census 2020 ZCTA-county relationship file](https://www.census.gov/geographies/reference-files/time-series/geo/relationship-files.html), [2020 DHC table P1](https://api.census.gov/data/2020/dec/dhc) at summary level 881, [GeoNames US postal codes](https://www.geonames.org/) ([CC BY 4.0](https://creativecommons.org/licenses/by/4.0/); the table keeps each ZIP's county and drops the rest) and the UDS Mapper ZIP-to-ZCTA crosswalk as `policyengine-us-data` stored it. The script's docstring lists the sources, and the table's `meta` block records each downloaded file's hash.

Rebuild the table when `policyengine-us` renames a county; `tests/test_zip_county.py` fails if a code stops being an engine county.

```bash
CENSUS_API_KEY=... uv run python scripts/build_zip_county.py --cache-dir /tmp/zip-county
```

## Quick CLI Smoke Test

You can also run the calculator without the frontend:
Expand All @@ -189,7 +215,7 @@ python3 -m cliff_watch.calculator examples/sample_household.json --mode series
- Household inputs are person-based in v1, with each family member entered individually by type and age.
- Earnings are assigned to the first adult and held constant over the year.
- A second adult is treated as a spouse, and later adults are modeled as additional household members in the same household unit.
- County-specific refinements are not exposed in the UI yet.
- The form has no county field. The API resolves the county from the ZIP, as [County from ZIP](#county-from-zip) describes.
- The modeled bundle is intentionally narrower than every possible administrative program.

## License
Expand Down
2 changes: 2 additions & 0 deletions api/_shared.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
calculate_household_types,
calculate_income_series,
household_input_from_dict,
household_location,
)
from cliff_watch.config import (
CCDF_MODELED_STATES,
Expand Down Expand Up @@ -141,6 +142,7 @@ def compute_series(
(item["net_resources"] for item in data),
default=0,
),
"location": household_location(payload),
}


Expand Down
1 change: 1 addition & 0 deletions changelog.d/zip-to-county.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Read each household's county from its ZIP, so premium tax credits and the other county rules use the household's own county instead of its state's first county alphabetically. An explicit `county` in a share link still wins. A ZIP that spans counties takes the county with the most 2020 Census residents, and the results page names that county, quotes its share of the ZIP's residents and offers the others. The page also says when policyengine-us holds no benchmark premium for a county. CliffWatch now sends the ACA rating area for the 31 counties that the engine's rating-area file spells differently from their codes, which its name join had priced as rating area 1. Links that named Los Angeles County no longer show a housing voucher subsidy: CliffWatch has no input for whether a household holds a voucher (#30), and its rent field also takes mortgage payments, so no household takes one up.
46 changes: 43 additions & 3 deletions cliff_watch/calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@
STATE_PROGRAM_OVERRIDES,
STATE_TANF_VARIABLES,
)
from cliff_watch.zip_county import (
county_for_zip,
describe_location,
normalize_zip,
rating_area_override,
)


class CalculatorDependencyError(RuntimeError):
Expand All @@ -60,6 +66,7 @@ class HouseholdInput:
earned_income: float
year: int = DEFAULT_YEAR
county: str | None = None
zip: str | None = None
people: tuple[HouseholdMemberInput, ...] = ()
household_type: str | None = None
filing_status: str | None = None
Expand Down Expand Up @@ -285,7 +292,7 @@ def _filtered_program_value(


def _normalize_county(county: str | None, state: str) -> str | None:
if county is None:
if county is None or not county.strip():
return None

normalized = (
Expand All @@ -301,6 +308,22 @@ def _normalize_county(county: str | None, state: str) -> str | None:
return f"{normalized}_{state}"


def resolved_county(payload: HouseholdInput) -> str | None:
"""The county the engine gets: the explicit one, or else the ZIP's."""
return _normalize_county(payload.county, payload.state) or county_for_zip(
payload.zip, payload.state
)


def household_location(payload: HouseholdInput) -> dict[str, Any]:
"""The county a calculation uses and where it came from, for the page to show."""
return describe_location(
payload.zip,
payload.state,
_normalize_county(payload.county, payload.state),
)


def _compat_people_from_template(
household_type: str,
) -> tuple[HouseholdMemberInput, ...]:
Expand Down Expand Up @@ -633,9 +656,17 @@ def _base_household_groups(
"state_name": {year: payload.state},
}

county = _normalize_county(payload.county, payload.state)
county = resolved_county(payload)
if county:
household["county"] = {year: county}
# The engine's rating-area file names these counties differently from
# its county codes, so its join misses them (see RATING_AREA_OVERRIDES).
rating_area = rating_area_override(county)
if rating_area is not None:
household["slcsp_rating_area"] = {year: rating_area}
zip_code = normalize_zip(payload.zip)
if zip_code:
household["zip_code"] = {year: zip_code}

tax_unit = {
"members": member_ids,
Expand All @@ -661,6 +692,13 @@ def _base_household_groups(
"receives_housing_assistance": {
year: _program_included(payload, "housing_assistance")
},
# CliffWatch has no input for whether a household holds a housing
# voucher (#30), and its rent field also takes mortgage payments. With
# housing assistance among its programs, receives_housing_assistance
# makes a household eligible, so wherever the ZIP or county carries a
# payment standard the engine would pay a voucher's subsidy to renters
# and homeowners alike. No household takes it up until that input exists.
"takes_up_housing_assistance_if_eligible": {year: False},
}
if childcare_expenses > 0:
spm_unit["childcare_expenses"] = {year: childcare_expenses}
Expand Down Expand Up @@ -1246,7 +1284,8 @@ def _simulate_core(payload: HouseholdInput) -> dict[str, Any]:
"state": payload.state,
"earned_income": payload.earned_income,
"year": payload.year,
"county": payload.county,
"county": resolved_county(payload),
"zip": normalize_zip(payload.zip),
"household_type": payload.household_type,
"filing_status": _effective_filing_status(payload),
"people": [
Expand Down Expand Up @@ -2071,6 +2110,7 @@ def numeric(field: str) -> float:
earned_income=numeric("earned_income"),
year=int(data.get("year", DEFAULT_YEAR)),
county=data.get("county"),
zip=normalize_zip(data.get("zip")),
people=people,
household_type=data.get("household_type"),
filing_status=data.get("filing_status"),
Expand Down
Binary file added cliff_watch/data/zip_county.json.gz
Binary file not shown.
13 changes: 12 additions & 1 deletion cliff_watch/variable_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,11 @@
"when a subsidy pays part of it. Kept as before; a follow-up weighs "
"dropping it."
),
"county": "The household's county as entered.",
"county": (
"The household's county as entered, or else the county its ZIP resolves "
"to (cliff_watch/zip_county.py). The formula would give the state's "
"first county alphabetically. The JS builder sends only an entered county."
),
"filing_status": (
"The household's filing status as entered, or as derived from the "
"household when none is entered."
Expand All @@ -77,6 +81,13 @@
"is_full_time_student": (
"Entered for each person; the formula infers it from school enrollment."
),
"slcsp_rating_area": (
"Set only for the 31 counties in RATING_AREA_OVERRIDES, to the rating "
"area the engine's aca_rating_areas.csv holds for them under another "
"name. The formula joins the county's code to that file, misses these "
"names and gives rating area 1. Python only: the JS builder doesn't "
"carry this map."
),
"ssi": "An SSI amount the household reports receiving replaces the computed one.",
"state_name": "The household's state as entered.",
}
Expand Down
201 changes: 201 additions & 0 deletions cliff_watch/zip_county.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,201 @@
"""Map a household's ZIP code to its county.

The form asks for a ZIP and no county, and policyengine-us gives a household with
no county its state's first county. This module closes that gap. It reads
`data/zip_county.json.gz`, which `scripts/build_zip_county.py` builds from Census
and GeoNames data, and resolves a county by this rule:

1. An explicit county, such as a share link's `county=`, always wins.
2. Otherwise the household gets the ZIP's first county in the household's state.
A ZIP with several counties lists the one with the most 2020 Census residents
first, ties going to the lower county code.
3. A ZIP with no county in that state resolves to nothing, and the engine then
uses the state's first county. `describe_location` reports this as "none", so
the page can say so.

It also lists two engine gaps by county: the counties whose benchmark premium the
engine lacks, and the counties whose ACA rating area its name join misses.

This module imports no engine code, so a request pays only for reading the table.
"""

from __future__ import annotations

import gzip
import json
import re
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from typing import Any

DATA_PATH = Path(__file__).resolve().parent / "data" / "zip_county.json.gz"

# policyengine-us's `gov.aca.state_rating_area_cost` has no row for these counties'
# rating areas (South Carolina 9 and 19, Florida 22), so a household there reads a
# $0 benchmark premium and no premium tax credit. The page says so. A test compares
# this set with the engine, so an engine update that adds the rows fails until the
# set shrinks.
COUNTIES_WITHOUT_BENCHMARK = frozenset(
{"CALHOUN_COUNTY_SC", "EDGEFIELD_COUNTY_SC", "GULF_COUNTY_FL"}
)

# policyengine-us finds a county's ACA rating area by joining the county's name to
# `gov/hhs/medicaid/geography/aca_rating_areas.csv`, and gives rating area 1 to any
# county the join misses. That file names these counties differently from the
# engine's `County` codes, so the calculator sends each one's rating area as an
# input. Each entry gives the file's row and the rating area that row holds. Most
# rows drop a word or a letter (`BAYLOR_TX`, `DONA_ANA_NM`). Chugach and Copper
# River read the row of Valdez-Cordova, the census area the Census Bureau split
# into them in 2019, and Kusilvak reads Wade Hampton's, its name until 2015. The
# file has no row for Oglala Lakota County, South Dakota, under that name or under
# Shannon County, its name until 2015, so it keeps the engine's rating area 1.
# Tests compare this map with the engine, so an engine update that renames a row
# fails until the entry goes.
RATING_AREA_OVERRIDES = {
"ADAMS_COUNTY_MS": ("ADAMS_MS", 6),
"BAYLOR_COUNTY_TX": ("BAYLOR_TX", 24),
"BEN_HILL_COUNTY_GA": ("BEN_HILL_GA", 15),
"BRYAN_COUNTY_GA": ("BRYAN_GA", 14),
"CHOCTAW_COUNTY_MS": ("CHOCTAW_MS", 6),
"CHUGACH_CENSUS_AREA_AK": ("VALDEZCORDOVA_AK", 1),
"CHURCHILL_COUNTY_NV": ("CHURCHILL_NV", 4),
"CLARK_COUNTY_KY": ("CLARK_KY", 5),
"COPPER_RIVER_CENSUS_AREA_AK": ("VALDEZCORDOVA_AK", 1),
"CUMBERLAND_COUNTY_KY": ("CUMBERLAND_KY", 4),
"DAWSON_COUNTY_GA": ("DAWSON_GA", 10),
"DEUEL_COUNTY_NE": ("DEUEL_NE", 4),
"DOÑA_ANA_COUNTY_NM": ("DONA_ANA_NM", 3),
"HAINES_BOROUGH_AK": ("HAINES_AK", 3),
"HARDEMAN_COUNTY_TX": ("HARDEMAN_TX", 24),
"HEMPHILL_COUNTY_TX": ("HEMPHILL_TX", 2),
"JIM_HOGG_COUNTY_TX": ("JIM_HOGG_TX", 12),
"JOHNSON_COUNTY_GA": ("JOHNSON_GA", 11),
"KIMBLE_COUNTY_TX": ("KIMBLE_TX", 17),
"KUSILVAK_CENSUS_AREA_AK": ("WADE_HAMPTON_AK", 2),
"LASALLE_PARISH_LA": ("LA_SALLE_LA", 6),
"LOGAN_COUNTY_NE": ("LOGAN_NE", 4),
"LOS_ALAMOS_COUNTY_NM": ("LOS_ALAMOS_NM", 5),
"MITCHELL_COUNTY_NC": ("MITCHELL_NC", 1),
"NESHOBA_COUNTY_MS": ("NESHOBA_MS", 6),
"PASQUOTANK_COUNTY_NC": ("PASQUOTANK_NC", 12),
"PETERSBURG_BOROUGH_AK": ("PETERSBURG_AK", 3),
"PRINCE_OF_WALES_HYDER_CENSUS_AREA_AK": ("PRINCE_OF_WALESHYDER_AK", 3),
"REAGAN_COUNTY_TX": ("REAGAN_TX", 17),
"TOOMBS_COUNTY_GA": ("TOOMBS_GA", 11),
"WALTHALL_COUNTY_MS": ("WALTHALL_MS", 6),
}
COUNTIES_WITHOUT_RATING_AREA_ROW = frozenset({"OGLALA_LAKOTA_COUNTY_SD"})


def rating_area_override(county: str | None) -> int | None:
"""The ACA rating area to send for a county the engine's join misses, if any."""
entry = RATING_AREA_OVERRIDES.get(county) if county else None
return entry[1] if entry else None


_NON_DIGITS = re.compile(r"[^0-9]")


@dataclass(frozen=True)
class CountyOption:
code: str
name: str
residents: int | None
resident_share: float | None


@dataclass(frozen=True)
class _Table:
names_by_code: dict[str, str]
codes: tuple[str, ...]
zips: dict[str, list[list[int | None]]]


@lru_cache(maxsize=1)
def _table() -> _Table:
with gzip.open(DATA_PATH, "rt", encoding="utf-8") as file:
document = json.load(file)
counties = document["counties"]
return _Table(
names_by_code={code: name for code, name in counties},
codes=tuple(code for code, _ in counties),
zips=document["zips"],
)


def normalize_zip(value: Any) -> str | None:
"""Return the first five digits, as the form does, or None if there are fewer."""
digits = _NON_DIGITS.sub("", "" if value is None else str(value))[:5]
return digits if len(digits) == 5 else None


def counties_for_zip(zip_code: Any, state: str | None) -> tuple[CountyOption, ...]:
"""The ZIP's counties in `state`, in resolution order.

`resident_share` is the county's share of everyone in the ZIP, across state
lines. It is None where the table records no residents.
"""
normalized = normalize_zip(zip_code)
if normalized is None or not state:
return ()
table = _table()
rows = table.zips.get(normalized)
if not rows:
return ()
total_residents = sum(residents or 0 for _, residents in rows)
suffix = f"_{state}"
options = []
for index, residents in rows:
code = table.codes[index]
if code.endswith(suffix):
options.append(
CountyOption(
code=code,
name=table.names_by_code[code],
residents=residents,
resident_share=(
residents / total_residents
if residents is not None and total_residents
else None
),
)
)
return tuple(options)


def county_for_zip(zip_code: Any, state: str | None) -> str | None:
"""The county code a household in this ZIP and state resolves to, if any."""
options = counties_for_zip(zip_code, state)
return options[0].code if options else None


def describe_location(
zip_code: Any,
state: str | None,
explicit_county: str | None = None,
) -> dict[str, Any]:
"""Say which county a calculation uses and why, for the page to show."""
options = counties_for_zip(zip_code, state)
if explicit_county:
county, source = explicit_county, "explicit"
elif options:
county, source = options[0].code, "zip"
else:
county, source = None, "none"
return {
"zip": normalize_zip(zip_code),
"county": county,
"county_name": _table().names_by_code.get(county) if county else None,
"source": source,
"has_benchmark_premium": county not in COUNTIES_WITHOUT_BENCHMARK,
"counties": [
{
"code": option.code,
"name": option.name,
"residents": option.residents,
"resident_share": option.resident_share,
}
for option in options
],
}
Loading
Loading