Files
stack/src/cli/load.py
kert 63e9c0029a
Some checks failed
CI / lint (push) Successful in 58s
CI / notebooks-smoke (push) Successful in 1m44s
CI / test (push) Failing after 3m3s
Infra CI / notebooks (push) Successful in 1m13s
Infra CI / docs (push) Successful in 1m46s
Infra CI / llm (push) Successful in 49s
Infra CI / mc (push) Failing after 36s
Infra CI / zotero (push) Successful in 27s
Infra CI / api (push) Successful in 1m9s
Infra CI / bcda (push) Successful in 1m37s
CI / lint (pull_request) Successful in 41s
CI / notebooks-smoke (pull_request) Successful in 1m49s
CI / test (pull_request) Failing after 2m50s
Infra CI / docs (pull_request) Successful in 17s
Infra CI / notebooks (pull_request) Successful in 59s
Infra CI / api (pull_request) Successful in 14s
Infra CI / bcda (pull_request) Successful in 14s
Infra CI / llm (pull_request) Successful in 20s
Infra CI / zotero (pull_request) Successful in 14s
Infra CI / mc (pull_request) Failing after 34s
feat(cms): vendor the institutional provider universe (CCN ↔ NPI ↔ TIN) from data.cms.gov; give carrier lines their billed TIN
"No TIN available" is a fact about the data, not a bug in ours.
Institutional claims never carry a TIN: the real Large-entity v3 pull has
0 billing TINs on every claim type and 0 CCNs on every institutional
claim (the dictionary's NamingSystem/CCN identifier is not emitted and
half the institutional claims have no billing provider at all), and
CCLF1 has an OSCAR/CCN and NPIs but no TIN either. The only TIN on
claims is the carrier/DME CLM_RNDRG_PRVDR_TAX_NUM, the TIN the line was
billed under, so the connector now gives professional and DME lines that
value as billing_tin too (institutional stays NULL; the facility is its
NPI and CCN). CMS publishes no provider TIN or EIN on data.cms.gov —
checked every enrollment, ownership, change-of-ownership, Provider of
Services and cost-report family in the catalog.

What can be vendored is CCN ↔ NPI ↔ organization. cms.datacms resolves
a dataset family to its newest version in the data.cms.gov catalog,
downloads the CSV (or pages the API) and names columns like the
generated cms.table models. `stack load cms` (aco.load.cms) loads the
institutional universe — hospital, SNF, HHA, hospice, FQHC and RHC
enrollments, the Provider of Services file and the three cost reports —
as cms.* with provenance columns and ingest_log rows, then derives
cms.institutional_provider, cms.ccn_crosswalk (PECOS ∪ POS-only CCNs,
65,161 rows today), cms.provider_tin_observed (NPI → TIN as seen on our
own claims) and cms.ccn_tin (CCN → NPI → TIN, with cms.aco_participant_tin
as the authoritative hook when a participant list is loaded). The
command prints facility-NPI → CCN → TIN coverage; the Data page gets the
same query. On the sandbox nothing resolves — its 8 facility NPIs are
synthetic — which is the expected answer there.

refs #1139
2026-10-25 17:33:13 -04:00

160 lines
5.4 KiB
Python

"""stack load — ingest data sources into DuckDB."""
from __future__ import annotations
from pathlib import Path
import typer
app = typer.Typer(no_args_is_help=True)
@app.command()
def cclf(
path: Path = typer.Option(..., help="Directory containing CCLF files."),
database: str = typer.Option(None, help="DuckDB database path (default: config)."),
no_pipeline: bool = typer.Option(
False, "--no-pipeline", help="Load raw tables only, skip CCLF pipeline."
),
) -> None:
"""Ingest CCLF claim files into DuckDB.
Reads fixed-width CCLF files (plain or ZIP) from the given directory,
parses them into the ``cclf`` schema, then runs the 19-step CCLF
pipeline to produce ``input_layer`` tables.
"""
from aco.load.cclf import load_cclf_directory
typer.echo(f"Loading CCLF files from {path} ...")
try:
stats = load_cclf_directory(
path,
database=database,
run_pipeline=not no_pipeline,
)
except FileNotFoundError as e:
typer.echo(f"Error: {e}", err=True)
raise typer.Exit(1) from None
for table, count in sorted(stats.items()):
typer.echo(f" {table}: {count:,} rows")
typer.echo("Done.")
@app.command()
def bcda(
ndjson_dir: Path = typer.Option(
None, help="Directory containing FHIR ndjson files."
),
database: str = typer.Option(None, help="DuckDB database path (default: config)."),
skip_flatten: bool = typer.Option(
False,
"--skip-flatten",
help="Skip flattening, load existing Parquet.",
),
run_pipeline: bool = typer.Option(
False,
"--run-pipeline",
help="Also run the bcda connector pipeline into input_layer.*",
),
) -> None:
"""Flatten BCDA FHIR exports and load into DuckDB.
Reads Patient/EOB/Coverage ndjson files (v2 or v3 payloads, any
number of parts), flattens them to Parquet, and loads into the
``bcda`` schema. Without --ndjson-dir, uses the newest export per
resource type under the BCDA store (a v3 pull is three jobs).
"""
from aco.load.bcda import load_bcda
typer.echo("Loading BCDA data ...")
try:
stats = load_bcda(
ndjson_dir=ndjson_dir,
database=database,
skip_flatten=skip_flatten,
run_pipeline=run_pipeline,
)
except FileNotFoundError as e:
typer.echo(f"Error: {e}", err=True)
raise typer.Exit(1) from None
for table, count in sorted(stats.items()):
typer.echo(f" {table}: {count:,} rows")
typer.echo("Done.")
@app.command()
def cms(
table: list[str] = typer.Option(
None, "--table", "-t", help="cms.<table> (default: the institutional universe)."
),
database: str = typer.Option(None, help="DuckDB database path (default: config)."),
refresh: bool = typer.Option(
False, "--refresh", help="Re-download even if the CSV is on disk."
),
derive: bool = typer.Option(
True,
"--derive/--no-derive",
help="Rebuild institutional_provider / ccn_crosswalk / provider_tin_observed / ccn_tin.",
),
) -> None:
"""Vendor the institutional provider universe from data.cms.gov: CCN ↔ NPI ↔ TIN.
PECOS enrollments (hospital, SNF, HHA, hospice, FQHC, RHC), the
Provider of Services file and the cost reports, loaded as ``cms.*``
with their models' column names, then the crosswalk tables. CMS
publishes no TIN; ``cms.ccn_tin`` carries one only where our own
claims or ``cms.aco_participant_tin`` know it.
"""
import duckdb
from aco.load.cms import coverage, load_cms
from conf import path
typer.echo("Loading data.cms.gov institutional datasets ...")
stats = load_cms(table or None, database=database, refresh=refresh, derive=derive)
for t, n in stats.items():
typer.echo(f" {t}: {n:,} rows")
con = duckdb.connect(database or str(path("db.aco")), read_only=True)
try:
cov = coverage(con)
finally:
con.close()
if cov.get("available"):
typer.echo(
f"coverage: {cov['facility_npis']:,} facility NPIs on institutional claims — "
f"{cov['npis_with_ccn']:,} resolve to a CCN ({cov['claims_with_ccn']:,} of {cov['claims']:,} claims), "
f"{cov['npis_with_tin']:,} to a TIN ({cov['claims_with_tin']:,} claims); "
f"{cov['institutional_claims_without_facility_npi']:,} institutional claims carry no facility NPI at all; "
f"CCN universe {cov['ccn_universe']:,}; observed NPI→TIN pairs {cov['observed_tins']:,}"
)
typer.echo("Done.")
@app.command()
def seed(
seed_dir: Path = typer.Option(None, help="Directory containing seed files."),
database: str = typer.Option(None, help="DuckDB database path (default: config)."),
schema: str = typer.Option(
"reference_data", help="Target DuckDB schema for seed tables."
),
) -> None:
"""Load seed/reference data (CSV, Excel, Parquet) into DuckDB."""
from aco.load.seed import load_seeds
typer.echo("Loading seed data ...")
try:
stats = load_seeds(
seed_dir=seed_dir,
database=database,
schema=schema,
)
except FileNotFoundError as e:
typer.echo(f"Error: {e}", err=True)
raise typer.Exit(1) from None
for table, count in sorted(stats.items()):
typer.echo(f" {table}: {count:,} rows")
typer.echo("Done.")