Collect Arizona education option evidence

This commit is contained in:
juvenal.diaz 2026-12-05 19:12:11 -06:00
parent b90c6fa0a8
commit c85000231c
5 changed files with 159 additions and 5 deletions

View File

@ -7,9 +7,35 @@ import (
)
type Snapshot struct {
Version string `json:"version"`
GeneratedAt string `json:"generated_at"`
Occupations map[string]Evidence `json:"occupations"`
Version string `json:"version"`
GeneratedAt string `json:"generated_at"`
Occupations map[string]Evidence `json:"occupations"`
EducationOptions map[string][]EducationOption `json:"education_options"`
ZIPCoordinates map[string]Coordinates `json:"zip_coordinates"`
}
type Coordinates struct {
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
}
type EducationOption struct {
UnitID string `json:"unit_id"`
Institution string `json:"institution"`
City string `json:"city"`
ZIPCode string `json:"zip_code"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
Website string `json:"website"`
CIP6 string `json:"cip6"`
AwardLevels []string `json:"award_levels"`
ProgramCompletions int `json:"program_completions"`
AnnualInStateTuition int `json:"annual_in_state_tuition"`
AdmissionRatePercent float64 `json:"admission_rate_percent"`
AdmissionBasis string `json:"admission_basis"`
InstitutionCompletionRatePercent int `json:"institution_completion_rate_percent"`
ProgramYear string `json:"program_year"`
CostAdmissionYear string `json:"cost_admission_year"`
}
// Load reads the latest complete snapshot. A missing cache is an expected

View File

@ -6020,7 +6020,7 @@ nextpath_action() {
case "${action}" in
refresh)
sudo systemctl start nextpath-opportunity-refresh.service
echo "NextPath labor evidence refreshed."
echo "NextPath labor and education evidence refreshed."
;;
status)
if sudo test -s "${opportunity_store}"; then
@ -6032,6 +6032,9 @@ with open(sys.argv[1], encoding="utf-8") as stream:
data = json.load(stream)
print(f"evidence generated: {data.get('generated_at', 'unknown')}")
print(f"occupations: {len(data.get('occupations', {}))}")
programs = sum(len(options) for options in data.get("education_options", {}).values())
print(f"Arizona education options: {programs}")
print(f"Arizona ZIP areas: {len(data.get('zip_coordinates', {}))}")
PY
else
echo "evidence: no successful snapshot"

View File

@ -26,6 +26,15 @@ IPEDS_URL = "https://nces.ed.gov/ipeds/datacenter/data"
IPEDS_YEARS = (2022, 2023, 2024)
PROJECTIONS_CENTRAL = "https://public.projectionscentral.org/Projections/LongTermRestJson"
AYLA_JOBS = "https://aylagov.com/api/jobs/search"
CENSUS_ZCTA = "https://www2.census.gov/geo/docs/maps-data/data/gazetteer/2024_Gazetteer/2024_Gaz_zcta_national.zip"
AWARD_LEVELS = {
"1": "certificate under one year", "20": "certificate under 12 weeks",
"21": "certificate 12 weeks to under one year", "2": "certificate one to two years",
"3": "associate degree", "4": "certificate two to four years",
"5": "bachelor degree", "6": "post-baccalaureate certificate",
"7": "master degree", "8": "post-master certificate",
"17": "research doctorate", "18": "professional doctorate", "19": "other doctorate",
}
def get_json(url: str, timeout: int = 45) -> dict[str, Any]:
@ -76,6 +85,105 @@ def ipeds_completion_history(cip6: set[str], cache_dir: Path) -> dict[str, int]:
return history
def integer(value: Any, default: int = -1) -> int:
try:
return int(value)
except (TypeError, ValueError):
return default
def decimal(value: Any, default: float = 0) -> float:
try:
return float(value)
except (TypeError, ValueError):
return default
def keyed_rows(path: Path) -> dict[str, dict[str, str]]:
return {row["UNITID"]: row for row in zip_rows(path) if row.get("UNITID")}
def arizona_education_options(mapping: dict[str, Any], cache_dir: Path) -> tuple[dict[str, Any], dict[str, Any]]:
directory_path = cached_download(f"{IPEDS_URL}/HD2024.zip", cache_dir / "HD2024.zip")
completion_path = cached_download(f"{IPEDS_URL}/C2024_A.zip", cache_dir / "C2024_A.zip")
tuition_path = cached_download(f"{IPEDS_URL}/IC2023_AY.zip", cache_dir / "IC2023_AY.zip")
admissions_path = cached_download(f"{IPEDS_URL}/ADM2023.zip", cache_dir / "ADM2023.zip")
characteristics_path = cached_download(f"{IPEDS_URL}/IC2023.zip", cache_dir / "IC2023.zip")
graduation_path = cached_download(f"{IPEDS_URL}/DRVGR2023.zip", cache_dir / "DRVGR2023.zip")
zcta_path = cached_download(CENSUS_ZCTA, cache_dir.parent / "census" / "2024_Gaz_zcta_national.zip")
directory = {row["UNITID"]: row for row in zip_rows(directory_path) if row.get("STABBR") == "AZ"}
tuition = keyed_rows(tuition_path)
admissions = keyed_rows(admissions_path)
characteristics = keyed_rows(characteristics_path)
graduation = keyed_rows(graduation_path)
cip_to_onet: dict[str, list[str]] = {}
for onet, spec in mapping["mappings"].items():
for cip in spec["cip6"]:
cip_to_onet.setdefault(cip, []).append(onet)
awards: dict[tuple[str, str], int] = {}
award_levels: dict[tuple[str, str], set[str]] = {}
for row in zip_rows(completion_path):
unit = row.get("UNITID", "")
cip = row.get("CIPCODE", "").replace(".", "")
count = integer(row.get("CTOTALT"))
if unit not in directory or cip not in cip_to_onet or row.get("MAJORNUM") != "1" or count <= 0:
continue
key = (unit, cip)
awards[key] = awards.get(key, 0) + count
award_levels.setdefault(key, set()).add(row.get("AWLEVEL", ""))
options: dict[str, list[dict[str, Any]]] = {onet: [] for onet in mapping["mappings"]}
for (unit, cip), completions in awards.items():
institution = directory[unit]
annual_tuition = integer(tuition.get(unit, {}).get("TUITION2"))
if annual_tuition < 0:
annual_tuition = 0
open_admission = characteristics.get(unit, {}).get("OPENADMP") == "1"
applications = integer(admissions.get(unit, {}).get("APPLCN"), 0)
admitted = integer(admissions.get(unit, {}).get("ADMSSN"), 0)
admission_rate = 100.0 if open_admission else (100 * admitted / applications if applications > 0 else 0)
admission_basis = "open admissions" if open_admission else ("reported admission rate" if applications > 0 else "admission rate not reported")
completion_rate = integer(graduation.get(unit, {}).get("GRRTTOT"), 0)
if completion_rate < 0:
completion_rate = 0
website = institution.get("WEBADDR", "").strip()
if website and not website.startswith(("http://", "https://")):
website = "https://" + website
record = {
"unit_id": unit,
"institution": institution.get("INSTNM", ""),
"city": institution.get("CITY", ""),
"zip_code": institution.get("ZIP", "").split("-", 1)[0],
"latitude": decimal(institution.get("LATITUDE")),
"longitude": decimal(institution.get("LONGITUD")),
"website": website,
"cip6": cip,
"award_levels": [AWARD_LEVELS.get(level, f"IPEDS award level {level}") for level in sorted(award_levels[(unit, cip)]) if level],
"program_completions": completions,
"annual_in_state_tuition": annual_tuition,
"admission_rate_percent": round(admission_rate, 1),
"admission_basis": admission_basis,
"institution_completion_rate_percent": completion_rate,
"program_year": "2024",
"cost_admission_year": "2023",
}
for onet in cip_to_onet[cip]:
options[onet].append(record)
zip_coordinates: dict[str, dict[str, float]] = {}
with zipfile.ZipFile(zcta_path) as archive:
with archive.open(archive.namelist()[0]) as raw:
reader = csv.DictReader(io.TextIOWrapper(raw, encoding="utf-8-sig"), delimiter="\t")
for original in reader:
row = {key.strip(): value.strip() for key, value in original.items()}
code = row.get("GEOID", "")
if code.startswith(("85", "86")):
zip_coordinates[code] = {"latitude": decimal(row.get("INTPTLAT")), "longitude": decimal(row.get("INTPTLONG"))}
return options, zip_coordinates
def projected_openings(body: dict[str, Any]) -> tuple[int, str, float]:
rows = body.get("rows") or []
row = next((item for item in rows if item.get("Area") == "Arizona"), rows[0] if rows else None)
@ -104,6 +212,7 @@ def refresh(mapping_path: Path, output_path: Path) -> None:
source_cache = output_path.parent / "source-cache" / "ipeds"
observed = datetime.now(timezone.utc)
occupations: dict[str, Any] = {}
education, zip_coordinates = arizona_education_options(mapping, source_cache)
for onet, spec in mapping["mappings"].items():
history = ipeds_completion_history(set(spec["cip6"]), source_cache)
graduates = history[str(IPEDS_YEARS[-1])]
@ -126,10 +235,16 @@ def refresh(mapping_path: Path, output_path: Path) -> None:
"posting_source_url": "https://aylagov.com/developers",
}
payload = {
"version": "nextpath-opportunity-cache-v1",
"version": "nextpath-opportunity-cache-v2",
"generated_at": observed.isoformat().replace("+00:00", "Z"),
"mapping_version": mapping["version"],
"occupations": occupations,
"education_options": education,
"zip_coordinates": zip_coordinates,
"education_sources": {
"institutions_programs_cost_access_quality": "https://nces.ed.gov/ipeds/use-the-data",
"zip_coordinates": "https://www.census.gov/geographies/reference-files/time-series/geo/gazetteer-files.2024.html",
},
}
output_path.parent.mkdir(parents=True, exist_ok=True)
fd, temporary = tempfile.mkstemp(prefix=".opportunity-", suffix=".json", dir=output_path.parent)

View File

@ -16,6 +16,10 @@ SPEC.loader.exec_module(MODULE)
class NextPathOpportunityRefreshTests(unittest.TestCase):
def test_award_level_labels_are_human_readable(self):
self.assertEqual(MODULE.AWARD_LEVELS["5"], "bachelor degree")
self.assertEqual(MODULE.AWARD_LEVELS["21"], "certificate 12 weeks to under one year")
def write_zip(self, path, member, fieldnames, rows):
output = io.StringIO()
writer = csv.DictWriter(output, fieldnames=fieldnames)

View File

@ -21,6 +21,12 @@ class NextPathPipelineTests(unittest.TestCase):
self.assertNotIn("CareerOneStop API token", pipeline)
self.assertNotIn("--token-file", pipeline)
self.assertIn("Projections Central", (ROOT / "scripts/nextpath-opportunity-refresh.py").read_text())
refresh = (ROOT / "scripts/nextpath-opportunity-refresh.py").read_text()
self.assertIn("arizona_education_options", refresh)
self.assertIn("2024_Gaz_zcta_national.zip", refresh)
self.assertIn("annual_in_state_tuition", refresh)
self.assertIn("institution_completion_rate_percent", refresh)
self.assertIn('print(f"Arizona education options: {programs}")', pipeline)
self.assertLess(
pipeline.index("systemctl start nextpath-opportunity-refresh.service"),
pipeline.index("systemctl restart nextpath.service"),