Files
stack/src/pay/bounds.py
kert 1aa288c344
Some checks failed
CI / lint (push) Failing after 48s
CI / notebooks-smoke (push) Successful in 2m0s
Deploy / changes (push) Successful in 18s
CI / test (push) Successful in 4m23s
Infra CI / notebooks (push) Successful in 1m5s
Infra CI / zotero (push) Successful in 16s
Infra CI / docs (push) Successful in 19s
Infra CI / api (push) Successful in 1m19s
Infra CI / bcda (push) Successful in 1m48s
Infra CI / mc (push) Successful in 18s
Infra CI / llm (push) Successful in 56s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Deploy / api (push) Successful in 2m34s
Lean Pay / pay (push) Successful in 3m22s
Deploy / llm (push) Successful in 1m43s
Deploy / mc (push) Has been skipped
Deploy / bcda (push) Successful in 2m10s
Deploy / report (push) Successful in 16s
feat(pay): load the published numbers the fence was missing
The wage index, pass-through rates, the missing APC years, the CY2027
work GPCI, equipment usage, IPPS standardized amounts, MS-DRG weights,
and the MSSP and REACH financial results now come from the CMS files.
The snapshot records those observed ranges. Maintenance stays the
published 5/100. There is still no IPPS or LEAD pricer.
2026-11-17 17:04:51 -05:00

1137 lines
34 KiB
Python

"""The fence around Medicare payment inputs.
Three kinds of number stay apart.
* A published constant (a year's conversion factor, ASP + 6%, the
limiting-charge factor) is a point. It is not a knob.
* An observed row is the min and max, in one period, of a column the
formula reads. A global span is not stored beside it.
* A knob is a real search dimension: tag confidence, a REACH quality
score, an MPPR rank.
:func:`allows` rejects anything outside that fence. Proposed NPRM
numbers, an unstated null, a missing series, and a calculated output
are recorded so the hole is visible, and then rejected. Nothing is
imputed.
"""
from __future__ import annotations
import json
import math
from collections.abc import Iterator
from dataclasses import dataclass
from fractions import Fraction
from pathlib import Path
from types import NoneType, UnionType
from typing import Any, Union, get_args, get_origin
import duckdb
from pydantic import BaseModel
from opps.rules import RULES as OPPS_RULES
from pfs.rules import PROPOSED
from pfs.rules import RULES as PFS_RULES
from qpp import QPP
SCHEMA = 1
SNAPSHOT = Path(__file__).with_name("bounds.json")
REPLICA = Path(__file__).resolve().parents[2] / "data" / "replica" / "aco.ro.duckdb"
# Closed policy strings. Other strings on the rule models are labels.
CATEGORICAL = frozenset({"skin_sub_payment_method"})
_INFORMATIONAL = frozenset(
{
"budget_neutrality_adjustor",
"clinical_labor_rate_update",
"supply_equipment_price_update",
}
)
_CONSTRAINT = frozenset({"work_gpci_floor", "pe_gpci_floor"})
_REJECT_KINDS = frozenset(
{
"proposed",
"unobserved",
"absent",
"unstated",
"derived",
"rejected",
"published_table",
}
)
_REJECT_ROLES = frozenset({"proposed", "outside", "output"})
# (name, numerator, denominator, note). The fraction is the Lean literal,
# not a reduced float.
_CONSTANTS = (
("parReduction", 5, 100, "Non-PAR fee is the PAR fee times (1 - 5/100)."),
("nonParMarkup", 15, 100, "Limiting-charge markup over the non-PAR fee."),
(
"limitingChargeFactor",
10925,
10000,
"(1 - 5/100) x (1 + 15/100).",
),
("aspAddOn", 6, 100, "Part B drug add-on. The limit is ASP times (1 + 6/100)."),
(
"reachQualityWithhold",
2,
100,
"Share of benchmark withheld for REACH quality.",
),
("paymentYearOffset", 2, 1, "payment_year = performance_year + 2."),
(
"missingWageIndex",
1,
1,
"Fill used when the wage index is missing. Not an observed index.",
),
(
"maintenanceDefault",
0,
1,
"Fill used by the straight-line equipment function when"
" maintenance_factor is absent. This is not the CMS factor."
" CMS publishes maintenanceFactor.",
),
(
"maintenanceFactor",
5,
100,
"CMS maintenance factor for every equipment item. The PUF has"
" no per-item column. The straight-line function does not apply"
" this factor.",
),
("mpprReduction", 1, 2, "Default PE reduction for rank 2 and later."),
("laborShare", 3, 5, "Default OPPS labor share, 0.60."),
("passThroughDrugs", 106, 100, "ASP times 1.06. Equals 1 + aspAddOn."),
)
# Lean Pay.ceiling. The value is the only legal label for that method.
_CEILINGS = (
("pfs", "formula"),
("opps", "formula"),
("partBAsp", "formula"),
("qpp", "formula"),
("mssp", "published_table"),
("reach", "published_table"),
("ipps", "absent"),
("lead", "absent"),
)
@dataclass(frozen=True)
class _Spec:
"""One observed scan: a table, the period columns, the measures."""
table: str
period: tuple[str, ...]
columns: tuple[str, ...]
role: str
# Columns the formulas read, plus the other numerics on those same
# tables. ``outside`` is recorded and then rejected by allows().
SPECS = (
_Spec(
"pfs.rvu",
("year",),
("work_rvu", "non_fac_pe_rvu", "fac_pe_rvu", "mp_rvu"),
"payment",
),
_Spec(
"pfs.rvu",
("year",),
("pre_op", "intra_op", "post_op"),
"outside",
),
_Spec("pfs.gpci", ("year",), ("work_gpci", "pe_gpci", "mp_gpci"), "payment"),
_Spec(
"pfs.gpci_proposed",
("cms_rule_id", "gpci_year"),
("work_gpci", "pe_gpci", "mp_gpci"),
"proposed",
),
_Spec(
"pfs.rvu_proposed",
("cms_rule_id",),
("work_rvu", "non_fac_pe_rvu", "fac_pe_rvu", "mp_rvu"),
"proposed",
),
_Spec(
"pfs.medical_equipment",
("year",),
(
"unit_price",
"useful_life",
"minutes_per_year",
"nf_minutes",
"f_minutes",
"maintenance_factor",
"utilization_rate",
),
"payment",
),
_Spec(
"opps.addendum_b",
("year",),
("payment_rate", "relative_weight"),
"payment",
),
_Spec(
"opps.addendum_b",
("year",),
("minimum_unadjusted_copayment",),
"outside",
),
_Spec(
"opps.apc_weight",
("year",),
("payment_rate", "relative_weight"),
"payment",
),
_Spec(
"opps.apc_weight",
("year",),
("minimum_unadjusted_copayment",),
"outside",
),
_Spec(
"opps.skin_sub_addendum_b",
("year",),
("payment_rate", "relative_weight"),
"payment",
),
_Spec(
"opps.skin_sub_addendum_b",
("year",),
("minimum_unadjusted_copayment",),
"outside",
),
_Spec("opps.wage_index", ("year",), ("wage_index",), "payment"),
_Spec(
"opps.wage_index",
("year",),
("reclassified_wage_index",),
"outside",
),
_Spec(
"opps.pass_through",
("year",),
("payment_rate", "asp_per_unit"),
"payment",
),
_Spec(
"skin_subs.asp_quarterly",
("quarter",),
("asp_per_unit", "payment_limit"),
"payment",
),
_Spec("drugs.asp_payment", ("quarter",), ("payment_limit",), "payment"),
_Spec("drugs.asp_payment", ("quarter",), ("coinsurance_pct",), "outside"),
_Spec("drugs.asp_noc", ("quarter",), ("payment_limit",), "payment"),
_Spec("ipps.drg_weight", ("fiscal_year",), ("relative_weight",), "payment"),
_Spec(
"ipps.drg_weight",
("fiscal_year",),
("geometric_mean_los", "arithmetic_mean_los"),
"outside",
),
_Spec(
"ipps.standardized_amount",
("fiscal_year", "table_code", "component"),
("amount",),
"payment",
),
_Spec(
"cms.performance_year_financial_quality_results",
("perf_year",),
(
"earnsaveloss",
"gensaveloss",
"abtotbnchmk",
"abtotexp",
"updatedbnchmk",
"histbnchmk",
"sav_rate",
"qualscore",
"finalsharerate",
),
"payment",
),
_Spec(
"cms.aco_reach_financial_quality_results",
("perf_year",),
(
"shared_savings",
"gross_savings",
"final_benchmark",
"unadj_benchmark",
"tot_cost_care",
"tot_cost_care_net",
"sav_rate",
),
"payment",
),
)
# Output tables and the derived ASP trajectory. Named so a new numeric
# column fails the column test, and stored without a range so they are
# not a second fence.
DERIVED = (
(
"skin_subs.asp_trajectories",
"quarter",
(
"asp_per_unit",
"payment_limit",
"total_quarters",
"qoq_pct_change",
"cumulative_pct_change",
"flat_rate_delta",
"anomalous_spike",
),
"Derived from skin_subs.asp_quarterly. Not a second fence.",
),
(
"opps.adjusted_payment",
"year",
("relative_weight", "payment_rate", "wage_index", "adjusted_payment"),
"Output of opps.calcs.payment.payment. Not an input.",
),
(
"opps.skin_sub_impact",
"year",
(
"units",
"paid_amount",
"asp_per_unit",
"payment_limit",
"old_payment",
"new_payment",
"payment_delta",
"pct_change",
),
"Output of the skin-substitute impact step. Not an input.",
),
)
_MISSING_NOTES = {
("opps.wage_index", "wage_index"): (
"No opps.wage_index table. oppsAdjusted fills a missing index with 1."
" Do not sample an index."
),
("opps.wage_index", "reclassified_wage_index"): (
"No opps.wage_index table. oppsAdjusted does not read this column."
),
("pfs.medical_equipment", "maintenance_factor"): (
"The PUF has no maintenance column. CMS applies 5/100 to every"
" item (lean.maintenanceFactor). The straight-line function fills"
" a missing factor with 0, which is not that factor."
),
("opps.pass_through", "payment_rate"): (
"No opps.pass_through table. Rates are Addendum B status"
" indicators G and H. Do not invent a rate."
),
("opps.pass_through", "asp_per_unit"): (
"No opps.pass_through table. Do not divide a payment rate by 1.06."
),
}
# SBA interest rates CMS reprints for the equipment annuity. Unchanged
# since CY2013 (77 FR 68902). The CY2027 final rule uses the same six
# rates. Percents, so 7.50% is 750/10000. Price band, then life band.
_INTEREST_RATES = (
("<25000", "<7", 750, 10000),
("25000-50000", "<7", 650, 10000),
(">50000", "<7", 550, 10000),
("<25000", "7+", 800, 10000),
("25000-50000", "7+", 700, 10000),
(">50000", "7+", 600, 10000),
)
_NUMERIC_TYPES = frozenset(
{
"DOUBLE",
"FLOAT",
"REAL",
"DECIMAL",
"INTEGER",
"BIGINT",
"HUGEINT",
"SMALLINT",
"TINYINT",
"UBIGINT",
"UINTEGER",
"BOOLEAN",
}
)
def num(value: object) -> str:
"""Format a bound the same way on both sides of a snapshot compare."""
number = float(value) # type: ignore[arg-type]
if not math.isfinite(number):
raise ValueError(f"non-finite bound: {value!r}")
return format(number, ".12g")
def element(
*,
item: str,
name: str,
kind: str,
role: str,
period: str = "",
low: str | None = None,
high: str | None = None,
value: object = None,
rows: int | None = None,
note: str = "",
integer: bool = False,
) -> dict[str, Any]:
"""One fence row. Floats are already formatted; bools stay bools."""
return {
"high": high,
"integer": integer,
"item": item,
"kind": kind,
"low": low,
"name": name,
"note": note,
"period": period,
"role": role,
"rows": rows,
"value": value,
}
def canonical(doc: dict[str, Any]) -> str:
"""Deterministic JSON. Key order and element order are both fixed."""
return json.dumps(doc, indent=2, sort_keys=True) + "\n"
def load(path: Path | None = None) -> dict[str, Any]:
"""Read the committed snapshot."""
return json.loads((path or SNAPSHOT).read_text())
def build(con: Any = None) -> dict[str, Any]:
"""Rebuild the snapshot from the rule registries and a replica.
Opens :data:`REPLICA` read-only when ``con`` is omitted. A missing
file raises ``FileNotFoundError``. The caller keeps a connection it
passed in.
"""
own = con is None
if own:
if not REPLICA.is_file():
raise FileNotFoundError(REPLICA)
con = duckdb.connect(str(REPLICA), read_only=True)
try:
rows = [
*registry_rows(),
*constant_rows(),
*interest_rows(),
*ceiling_rows(),
*hole_rows(),
*observed_rows(con),
*derived_rows(con),
]
_reject_dupes(rows)
rows.sort(key=lambda row: (row["item"], row["name"], row["period"]))
return {"schema": SCHEMA, "elements": rows}
finally:
if own:
con.close()
def allows(
item: str,
name: str,
value: object,
period: str | int | None = None,
*,
doc: dict[str, Any] | None = None,
) -> bool:
"""True when ``value`` is inside the one fence row for this input.
A name that spans several periods requires ``period``. Proposed
numbers, unstated nulls, missing series, and calculated outputs
are inside the file and still return False.
"""
rows = _rows_for(doc or load(), item, name, period)
if len(rows) != 1:
return False
return _admits(rows[0], value)
def registry_rows() -> list[dict[str, Any]]:
"""One row per numeric, bool, null, and categorical rule field."""
rows: list[dict[str, Any]] = []
for year, rule in sorted(PFS_RULES.items()):
rows.extend(_model_rows("pfs.rules.RuleYear", str(year), rule, "payment"))
for year, rule in sorted(PROPOSED.items()):
rows.extend(_model_rows("pfs.rules.ProposedRule", str(year), rule, "proposed"))
for year, rule in sorted(OPPS_RULES.items()):
rows.extend(_model_rows("opps.rules.RuleYear", str(year), rule, "payment"))
for year, rule in sorted(QPP.items()):
rows.extend(_model_rows("qpp.QppYear", str(year), rule, "payment"))
return rows
def constant_rows() -> list[dict[str, Any]]:
"""Lean rationals. ``value`` keeps the unreduced fraction."""
rows = []
for name, numerator, denominator, note in _CONSTANTS:
point = num(float(Fraction(numerator, denominator)))
rows.append(
element(
item="lean",
name=name,
kind="constant",
role="payment",
low=point,
high=point,
value=f"{numerator}/{denominator}",
note=note,
)
)
return rows
def interest_rows() -> list[dict[str, Any]]:
"""The six published SBA interest rates. Points, not a sampled range."""
rows = []
for price, life, numerator, denominator in _INTEREST_RATES:
point = num(float(Fraction(numerator, denominator)))
rows.append(
element(
item="pfs.equipment.interest",
name="rate",
period=f"{price}:{life}",
kind="published",
role="payment",
low=point,
high=point,
value=f"{numerator}/{denominator}",
note=(
"SBA interest rate for this purchase-price band and"
" useful life. Unchanged since CY2013 (77 FR 68902)."
" The straight-line equipment function does not apply it."
),
)
)
return rows
def ceiling_rows() -> list[dict[str, Any]]:
"""The eight Lean methods and the only legal label for each."""
return [
element(
item="lean.ceiling",
name=name,
kind="category",
role="payment",
value=value,
note="Lean Pay.ceiling for this method.",
)
for name, value in _CEILINGS
]
def hole_rows() -> list[dict[str, Any]]:
"""Elements the formulas name and the replica must not invent."""
return [
element(
item="pfs.limiting_charge",
name="fee",
kind="derived",
role="output",
note=(
"Output of pfsPayment times the limiting-charge factor."
" Do not sample a fee."
),
),
element(
item="pfs.rvu",
name="conv_factor",
kind="rejected",
role="informational",
note=(
"Not a payment input. Use pfs.rules.RuleYear.conversion_factor"
" and each CfSegment."
),
),
element(
item="pfs.rvu",
name="non_fac_total",
kind="derived",
role="output",
note="Sum of work, non-facility PE, and MP. pfsPayment does not read it.",
),
element(
item="pfs.rvu",
name="fac_total",
kind="derived",
role="output",
note="Sum of work, facility PE, and MP. pfsPayment does not read it.",
),
element(
item="pfs.mppr",
name="rank",
kind="knob",
role="knob",
low="1",
integer=True,
note=(
"Rank 1 keeps the PE RVU. Later ranks keep 1 minus the"
" reduction. An integer, at least 1."
),
),
element(
item="reach",
name="total_quality",
kind="knob",
role="knob",
low="0",
high="1",
note=(
"Quality score as a fraction from 0 to 1."
" Earn-back is this score times 2/100."
),
),
element(
item="reach",
name="settlement",
kind="published_table",
role="payment",
note=(
"Shared savings are the published CMS table"
" cms.aco_reach_financial_quality_results."
" There is no savings function to sample."
),
),
element(
item="mssp",
name="settlement",
kind="published_table",
role="payment",
note=(
"Shared savings are the published CMS table"
" cms.performance_year_financial_quality_results."
" There is no savings function to sample."
),
),
element(
item="ipps",
name="payment",
kind="absent",
role="payment",
note=(
"No IPPS pricer in this repo. Claim-level IME, DSH, and"
" outliers are not priced. Published standardized amounts"
" and MS-DRG weights are separate rows."
),
),
element(
item="lead",
name="pricer",
kind="absent",
role="payment",
note="src/lead is the review application, not a payment model.",
),
element(
item="lead.tag",
name="confidence",
kind="knob",
role="knob",
low="0",
high="1",
note="Theme-tag confidence. The only tagging knob.",
),
]
def observed_rows(con: Any) -> list[dict[str, Any]]:
"""Per-period min, max, and non-null count. Missing tables stay blank."""
present = _table_names(con)
rows: list[dict[str, Any]] = []
for spec in SPECS:
rows.extend(_spec_rows(con, spec, present))
return rows
def derived_rows(con: Any) -> list[dict[str, Any]]:
"""Name every numeric column of a derived table, with no range."""
present = _table_names(con)
rows: list[dict[str, Any]] = []
for table, period_col, columns, note in DERIVED:
names = list(columns)
if table in present:
extra = _measure_columns(con, table) - set(columns) - {period_col}
names.extend(sorted(extra))
for name in names:
rows.append(
element(
item=table,
name=name,
kind="derived",
role="output",
note=note,
)
)
return rows
def _model_rows(
item: str, period: str, obj: BaseModel, role: str
) -> list[dict[str, Any]]:
return [_leaf_row(item, period, leaf) for leaf in _leaves(obj, role)]
def _leaves(
obj: BaseModel, role: str, prefix: str = "", period: str | None = None
) -> Iterator[_Leaf]:
for fname, field in type(obj).model_fields.items():
ann = _peel(field.annotation)
path = f"{prefix}.{fname}" if prefix else fname
value = getattr(obj, fname)
child = "proposed" if role == "proposed" or fname == "proposed" else role
if _is_model(ann):
if value is None:
yield _Leaf(path, None, child, period, "unstated")
else:
yield from _leaves(value, child, path, period)
continue
if _is_model_list(ann):
for item in value or []:
span = f"{item.start.isoformat()}/{item.end.isoformat()}"
yield from _leaves(item, child, path, span)
continue
if ann is bool or ann in (int, float):
kind = "unstated" if value is None else "scalar"
yield _Leaf(path, value, _leaf_role(fname, child), period, kind)
continue
if fname in CATEGORICAL:
kind = "unstated" if value is None else "category"
yield _Leaf(path, value, child, period, kind)
@dataclass(frozen=True)
class _Leaf:
name: str
value: object
role: str
period: str | None
kind: str
def _leaf_row(item: str, default_period: str, leaf: _Leaf) -> dict[str, Any]:
period = leaf.period or default_period
note = _leaf_note(leaf.name, leaf.role, leaf.value)
if leaf.kind == "unstated" or leaf.value is None:
return element(
item=item,
name=leaf.name,
period=period,
kind="unstated",
role=leaf.role,
note=note,
)
if leaf.kind == "category":
return element(
item=item,
name=leaf.name,
period=period,
kind="category",
role=leaf.role,
value=leaf.value,
note=note,
)
if isinstance(leaf.value, bool):
return element(
item=item,
name=leaf.name,
period=period,
kind="published",
role=leaf.role,
value=leaf.value,
note=note,
)
point = num(leaf.value)
kind = "proposed" if leaf.role == "proposed" else "published"
return element(
item=item,
name=leaf.name,
period=period,
kind=kind,
role=leaf.role,
low=point,
high=point,
value=point,
note=note,
)
def _leaf_role(fname: str, role: str) -> str:
if role == "proposed":
return "proposed"
if fname in _INFORMATIONAL:
return "informational"
if fname in _CONSTRAINT:
return "constraint"
return "payment"
def _leaf_note(name: str, role: str, value: object) -> str:
leaf = name.rsplit(".", 1)[-1]
if role == "proposed" and value is None:
if name == "proposed":
return "No NPRM block captured for this year."
return "The NPRM proposed no numeric change. Do not invent one."
if role == "proposed" and value is not None:
if leaf == "budget_neutrality_adjustor":
return (
"NPRM adjustor, already inside the proposed conversion factor."
" Not a payment input."
)
return "NPRM value. Not a payment input."
if leaf == "budget_neutrality_adjustor":
return (
"Already inside conversion_factor. Do not multiply payment by this again."
)
if leaf == "work_gpci_floor":
return (
"Legal minimum on the final work GPCI."
" An observed GPCI below it stays in the catalog."
)
if value is None and leaf == "benchmark_nominal_pct":
return "Not stated in the Federal Register corpus. Do not impute it."
if value is None and leaf == "apm_incentive_pct":
return "No APM incentive payment this payment year. Do not impute zero."
if value is None and leaf == "cf_qp":
return "No QP conversion factor this year."
if value is None and leaf == "anesthesia_cf":
return "No separate anesthesia conversion factor transcribed for this year."
if value is None and leaf == "skin_sub_flat_rate":
return "No flat rate this year."
if value is None and leaf == "packaging_threshold":
return "Not transcribed. Do not impute it."
if value is None and leaf == "telehealth_originating_site_fee":
return "Not transcribed for this year."
return ""
def _spec_rows(con: Any, spec: _Spec, present: set[str]) -> list[dict[str, Any]]:
if spec.table not in present:
return [_missing(spec, column) for column in spec.columns]
have = _column_names(con, spec.table)
rows = [_missing(spec, column) for column in spec.columns if column not in have]
present_cols = tuple(column for column in spec.columns if column in have)
if not present_cols:
return rows
scanned = _scan(con, spec.table, spec.period, present_cols)
if not scanned:
for column in present_cols:
rows.append(
element(
item=spec.table,
name=column,
kind="unstated",
role=spec.role,
rows=0,
note="Table has no rows. No range is invented.",
)
)
return rows
width = len(spec.period)
for record in scanned:
period = ":".join(_cell(value) for value in record[:width])
for index, column in enumerate(present_cols):
low, high, count = record[width + 3 * index : width + 3 * index + 3]
rows.append(_observed(spec, column, period, low, high, count))
return rows
def _missing(spec: _Spec, column: str) -> dict[str, Any]:
return element(
item=spec.table,
name=column,
kind="unobserved",
role=spec.role,
note=_MISSING_NOTES.get(
(spec.table, column),
"Not in the replica. No range is invented.",
),
)
def _observed(
spec: _Spec,
column: str,
period: str,
low: object,
high: object,
count: object,
) -> dict[str, Any]:
seen = int(count or 0)
if low is None or high is None or seen == 0:
note = "No non-null values in this period. No range is invented."
if spec.table == "opps.pass_through" and column == "asp_per_unit":
note = (
"No ASP is joined. payment_rate is the published"
" pass-through amount. Do not divide it by 1.06."
)
return element(
item=spec.table,
name=column,
period=period,
kind="unstated",
role=spec.role,
rows=seen,
note=note,
)
kind = "proposed" if spec.role == "proposed" else "observed"
return element(
item=spec.table,
name=column,
period=period,
kind=kind,
role=spec.role,
low=num(low),
high=num(high),
rows=seen,
note=_observed_note(spec, column, kind, num(low), period),
)
def _observed_note(spec: _Spec, column: str, kind: str, low: str, period: str) -> str:
notes: list[str] = []
if spec.table == "skin_subs.asp_quarterly" and column == "asp_per_unit":
notes.append(
"Back-calculated as payment_limit / 1.06."
" The CMS allowance is payment_limit."
)
elif spec.table == "skin_subs.asp_quarterly" and column == "payment_limit":
notes.append(
"CMS payment allowance. asp_per_unit is this value divided by 1.06."
)
elif spec.table == "drugs.asp_payment" and column == "payment_limit":
notes.append("CMS payment allowance (ASP + 6%), not the ASP itself.")
elif spec.table == "drugs.asp_noc" and column == "payment_limit":
notes.append("CMS payment allowance for a not-otherwise-classified drug.")
elif spec.table == "opps.pass_through" and column == "payment_rate":
notes.append(
"Addendum B status indicator G (drug) or H (device). Not Addendum D."
)
elif spec.table == "opps.wage_index" and column == "wage_index":
notes.append(
"IPPS final-rule Table 3 pre-reclassification wage index."
" FY2014 and FY2015 use Table 4A and 4B."
" Calendar year N uses fiscal year N."
)
elif spec.table == "ipps.drg_weight" and column == "relative_weight":
notes.append(
"Paid MS-DRG weight. The 10% cap-applied weight when CMS publishes both."
)
elif spec.table == "ipps.standardized_amount":
notes.append("One published dollar. The row is that point.")
if period.split(":")[1:2] == ["1E"]:
notes.append(
"LTCH PPS standard federal rate. Not an IPPS operating amount."
)
elif (
spec.table == "cms.performance_year_financial_quality_results"
and column == "qualscore"
):
notes.append(
"Published score on the file's scale. Not the REACH total_quality knob."
)
elif spec.table == "pfs.medical_equipment" and column == "utilization_rate":
notes.append(
"CMS equipment usage rate. The straight-line function does not read it."
)
if column == "work_gpci" and kind in {"observed", "proposed"}:
year = _year(period)
floor = PFS_RULES[year].work_gpci_floor if year in PFS_RULES else 1.0
if float(low) < floor:
if spec.role == "proposed":
notes.append(
"Published without the statutory work GPCI floor."
" Observed min is below it. The row stays."
)
else:
notes.append(
f"Observed min is below the {num(floor)} work GPCI floor."
" The floor is a separate constraint and this row stays."
)
elif spec.role == "proposed":
notes.append("Published without the statutory work GPCI floor.")
if spec.role == "outside":
notes.append("On the file, and not an input of the payment formula.")
return " ".join(notes)
def _scan(
con: Any, table: str, period: tuple[str, ...], columns: tuple[str, ...]
) -> list[tuple[Any, ...]]:
chosen = ", ".join(_ident(column) for column in period)
aggs: list[str] = []
for column in columns:
quoted = _ident(column)
aggs.append(f"min({quoted})")
aggs.append(f"max({quoted})")
aggs.append(f"count({quoted})")
sql = (
f"SELECT {chosen}, {', '.join(aggs)} FROM {_table(table)}"
f" GROUP BY {chosen} ORDER BY {chosen}"
)
return con.execute(sql).fetchall()
def _rows_for(
doc: dict[str, Any], item: str, name: str, period: str | int | None
) -> list[dict[str, Any]]:
rows = [
row for row in doc["elements"] if row["item"] == item and row["name"] == name
]
if period is None:
return rows
key = str(period)
return [row for row in rows if row["period"] == key]
def _admits(row: dict[str, Any], value: object) -> bool:
if row["kind"] in _REJECT_KINDS or row["role"] in _REJECT_ROLES:
return False
if isinstance(value, bool) or isinstance(row["value"], bool):
return isinstance(value, bool) and value is row["value"]
if row["integer"]:
if not isinstance(value, int):
return False
return _in_range(float(value), row["low"], row["high"])
if row["low"] is None and row["high"] is None:
return isinstance(value, str) and value == row["value"]
number = _number(value)
if number is None:
return False
return _in_range(number, row["low"], row["high"])
def _in_range(number: float, low: str | None, high: str | None) -> bool:
if not math.isfinite(number):
return False
if low is not None and _cmp(number, float(low)) < 0:
return False
if high is not None and _cmp(number, float(high)) > 0:
return False
return low is not None or high is not None
def _cmp(left: float, right: float) -> int:
"""Compare after the same ``.12g`` rounding the snapshot stores."""
a = float(format(left, ".12g"))
b = float(format(right, ".12g"))
return (a > b) - (a < b)
def _number(value: object) -> float | None:
if isinstance(value, bool) or isinstance(value, str):
return None
if isinstance(value, Fraction):
return float(value)
if isinstance(value, int | float):
return float(value)
return None
def _reject_dupes(rows: list[dict[str, Any]]) -> None:
seen: set[tuple[str, str, str]] = set()
for row in rows:
key = (row["item"], row["name"], row["period"])
if key in seen:
raise ValueError(f"duplicate fence row: {key}")
seen.add(key)
def _year(period: str) -> int | None:
part = period.split(":")[-1]
if len(part) == 4 and part.isdigit():
return int(part)
return None
def _cell(value: object) -> str:
if value is None:
return "null"
if isinstance(value, float) and value.is_integer():
return str(int(value))
return str(value)
def _peel(ann: Any) -> Any:
origin = get_origin(ann)
if origin in (Union, UnionType):
args = [arg for arg in get_args(ann) if arg is not NoneType]
if len(args) == 1:
return args[0]
return ann
def _is_model(ann: Any) -> bool:
return isinstance(ann, type) and issubclass(ann, BaseModel)
def _is_model_list(ann: Any) -> bool:
return (
get_origin(ann) is list
and len(args := get_args(ann)) == 1
and _is_model(args[0])
)
def _ident(name: str) -> str:
if not name.isidentifier():
raise ValueError(name)
return f'"{name}"'
def _table(name: str) -> str:
schema, table = name.split(".")
if not schema.isidentifier() or not table.isidentifier():
raise ValueError(name)
return f"{schema}.{table}"
def _table_names(con: Any) -> set[str]:
rows = con.execute(
"SELECT table_schema, table_name FROM information_schema.tables"
).fetchall()
return {f"{schema}.{table}" for schema, table in rows}
def _column_names(con: Any, table: str) -> set[str]:
schema, name = table.split(".")
rows = con.execute(
"""
SELECT column_name FROM information_schema.columns
WHERE table_schema = ? AND table_name = ?
""",
[schema, name],
).fetchall()
return {row[0] for row in rows}
def _measure_columns(con: Any, table: str) -> set[str]:
schema, name = table.split(".")
rows = con.execute(
"""
SELECT column_name, data_type FROM information_schema.columns
WHERE table_schema = ? AND table_name = ?
""",
[schema, name],
).fetchall()
return {column for column, data_type in rows if data_type in _NUMERIC_TYPES}