scripts/verify_iip0035_d1b_auto_and_portfolio.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0035_d1b_auto_and_portfolio.py · SHA-256: fedb990aeaedd116…
else:
cov_regime = (
"OBSERVATION_LEVEL_95PCT_UNIT_RECOVERY_AND_ELIGIBILITY_ASSUMED"
if a_obs_d == Decimal("0.05")
else f"OBSERVATION_LEVEL_GE_{cov_floor:.2f}PCT_UNIT_RECOVERY_AND_ELIGIBILITY_ASSUMED"
)
cov_cat = "UNIT_ASSUMED"
if cap_cmp is True:
cp_status = "PASS"
elif cap_cmp is False:
cp_status = "HOLD_INCONCLUSIVE_INSUFFICIENT_INDEPENDENT_DENOMINATOR"
else:
cp_status = "HOLD_ZERO_EVENT_CAP_COMPARISON_UNRESOLVED_WITHIN_BUDGET"
res_cp: Dict[str, Any] = {
"gate_id": gate_id,
"status": cp_status,
"empirical_clearance_status": (
"MATHEMATICAL_COUNT_SUBGATE_ONLY_CONDITIONAL_ON_CALIBRATION_NO_EMPIRICAL_SAFETY_CLEARANCE"
if passed
else "HOLD_MATHEMATICAL_COUNT_SUBGATE_AND_EMPIRICAL_SAFETY_PENDING"
),
"coverage_regime": cov_regime,
"coverage_category": cov_cat,
"default_calibration_assumptions": default_cal_assumptions,
"sampling_independence_provenance": sampling_independence_provenance,
"calibration_sources": calibration_sources,
"k": 0,
"n_raw": n_raw,
"alpha_obs_str": alpha_obs_fmt,
"alpha_joint_total_str": joint_alpha_str,
"effective_detection_factor_str": eff_det_fmt,
"u95_exact_sound_decimal_str": u95_str,
"u95_exact_sound_decimal_pct_str": u95_pct_str,
"u95_math_lower_pct_str": u95_math_lower_pct_str,
"u95_math_upper_pct_exact_str": u95_math_upper_pct_exact_str,
"cap_fraction_str": cap_str,
}
if rep_meets_exact is not None:
res_cp["reported_u95_meets_exact_bound"] = rep_meets_exact
return res_cp
_SP1C2C_VL9_COMPETENT_HLAC_ALLELES = frozenset({
# Lin et al. 2023 (PMID:37264229, PMC10690437 Table 1): SP-1C (15 alleles) & SP-2C (3 alleles)
"HLA-C*01:02", "HLA-C*03:02", "HLA-C*03:03", "HLA-C*03:04", "HLA-C*04:01",
"HLA-C*04:03", "HLA-C*05:01", "HLA-C*06:02", "HLA-C*08:01", "HLA-C*08:02",
"HLA-C*12:02", "HLA-C*12:03", "HLA-C*14:02", "HLA-C*16:01", "HLA-C*16:02",
"HLA-C*02:02", "HLA-C*15:02", "HLA-C*15:05",
})
_SP3C4C_NONFUNC_HLAC_ALLELES = frozenset({
# Lin et al. 2023 (PMID:37264229, PMC10690437 Table 1): SP-3C (4 alleles) & SP-4C (1 allele)
"HLA-C*07:01", "HLA-C*07:02", "HLA-C*07:04", "HLA-C*17:01", "HLA-C*18:01",
})
_PINNED_KNOWN_HLAC_TWO_FIELD_INVENTORY = _SP1C2C_VL9_COMPETENT_HLAC_ALLELES | _SP3C4C_NONFUNC_HLAC_ALLELES
CANONICAL_INDEPENDENT_SAMPLING_DESIGNS = frozenset({
"INDEPENDENT_BIOLOGICAL_OPPORTUNITIES",
"INDEPENDENT",
"IID",
"INDEPENDENT_TRIALS",
"INDEPENDENT_REPLICATES",
"INDEPENDENT_BIOLOGICAL_REPLICATES",
})
def _reconcile_sampling_independence_flags(
primary_map: Dict[str, Any],
*,
prefix: str | None = None,
panel_map: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
"""Fail-closed reconciliation of sampling-independence keys across assay and panel scopes.
Separates clustering assertions (`clustered_sampling`/`is_clustered`) from independence assertions
(`independent_trials`/`independent_sample_units`/`sampling_independence_model`/`sampling_design`),
rejects non-ASCII spellings BEFORE normalization, and reports malformed values distinctly.
"""
scopes: List[tuple[Any, str | None]] = [(primary_map, prefix)]
if panel_map is not None:
scopes.append((panel_map, None))
elif prefix is not None:
scopes.append((primary_map, None))
clustered_true = False
clustered_false = False
indep_true = False
indep_false = False
malformed_flag = False
for src, pfx in scopes:
if not isinstance(src, dict):
continue
for key in ("clustered_sampling", "is_clustered", "independent_trials", "independent_sample_units", "sampling_independence_model", "sampling_design"):
full_k = f"{pfx}_{key}" if pfx else key
if full_k not in src:
continue
val = src[full_k]
if key in ("clustered_sampling", "is_clustered"):
if val is True:
clustered_true = True
elif val is False:
clustered_false = True
else:
malformed_flag = True
elif key in ("independent_trials", "independent_sample_units"):
if val is False:
indep_false = True
elif val is True:
indep_true = True
else:
malformed_flag = True
elif key == "sampling_independence_model":
if isinstance(val, str) and val.isascii() and val == "INDEPENDENT_BIOLOGICAL_OPPORTUNITIES":
indep_true = True
elif isinstance(val, str) and val.isascii() and val == val.strip() and val:
indep_false = True
else:
malformed_flag = True
elif key == "sampling_design":
if isinstance(val, str) and val.isascii() and val == val.strip() and val:
norm_sd = re.sub(r"[ -]+", "_", val, flags=re.ASCII).upper()
if norm_sd in CANONICAL_INDEPENDENT_SAMPLING_DESIGNS:
indep_true = True
else:
indep_false = True
else:
malformed_flag = True
conflict = bool(
(clustered_true and clustered_false)
or (indep_true and indep_false)
or (clustered_true and indep_true)
)
non_independent = bool(clustered_true or indep_false)
if conflict:
prov = "CONFLICTING_INDEPENDENT_AND_NON_INDEPENDENT_DECLARATIONS"
elif malformed_flag:
prov = "MALFORMED_OR_NON_ASCII_SAMPLING_DECLARATION"
elif clustered_true:
prov = "EXPLICIT_CLUSTERED_SAMPLING"
elif indep_false and clustered_false:
prov = "EXPLICIT_UNCLUSTERED_BUT_DEPENDENT_SAMPLING"
elif indep_false:
prov = "EXPLICIT_NON_INDEPENDENT_OR_UNRECOGNIZED"
elif indep_true:
prov = "EXPLICIT_INDEPENDENT"
elif clustered_false:
prov = "EXPLICIT_NON_CLUSTERED_ONLY_INDEPENDENCE_ASSUMED"
else:
prov = "UNSPECIFIED_DEFAULT_ASSUMED_INDEPENDENT"
return {
"sampling_independence_model": (
"NON_INDEPENDENT_OR_CLUSTERED"
if (non_independent or malformed_flag)
else "INDEPENDENT_BIOLOGICAL_OPPORTUNITIES"
),
"clustered_sampling": bool(non_independent or malformed_flag),
"sampling_independence_conflict": conflict,
"sampling_malformed": bool(malformed_flag and not conflict),
"sampling_independence_provenance": prov,
}
_CAL_PARAM_DEFAULTS: Dict[str, Any] = {
"eta_recovery_l95": Decimal(1),
"f_eligible": Decimal(1),
"f_eligible_provenance": "KNOWN_OR_CONSERVATIVELY_ESTABLISHED",
"alpha_obs": None,
"alpha_eta_recovery": None,
"alpha_f_eligible": None,
}
def _resolve_assay_calibration(
local_map: Dict[str, Any],
*,
local_prefix: str | None = None,
panel_map: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
"""Shared typed calibration resolver across D1-04, D1-08, L2/L3 components, and Gate-0V Day-28.
Uses explicit key presence distinct from JSON null:
- Omitted local key inherits the panel value (or built-in default if panel omitted).
- Explicit JSON null (`key in src and src[key] is None`) is rejected as malformed/invalid override (HOLD).
- Conflicting values across panel and local scopes for the SAME parameter are rejected (HOLD).
- Bound parameter groups ({eta_recovery_l95, alpha_eta_recovery} and {f_eligible, f_eligible_provenance,
alpha_f_eligible}) cannot be split partially across local and panel scopes (HOLD).
"""
p_src = panel_map if isinstance(panel_map, dict) else (local_map if local_prefix is not None else None)
resolved: Dict[str, Any] = {}
sources: Dict[str, str] = {}
local_present_keys: set[str] = set()
panel_present_keys: set[str] = set()
hold_reason: str | None = None
for param, default_val in _CAL_PARAM_DEFAULTS.items():
lk = f"{local_prefix}_{param}" if local_prefix else param
has_local = isinstance(local_map, dict) and (lk in local_map)
has_panel = isinstance(p_src, dict) and (param in p_src) and (local_prefix is not None or panel_map is not None)
if has_local:
local_present_keys.add(param)
if has_panel:
panel_present_keys.add(param)
l_val = local_map.get(lk) if has_local else _MISSING_ARG
p_val = p_src.get(param) if has_panel else _MISSING_ARG
if has_local and l_val is None:
hold_reason = hold_reason or "HOLD_EXPLICIT_NULL_CALIBRATION_PARAMETER"
resolved[param] = default_val
sources[param] = "local_explicit_null_rejected"
continue
if has_panel and p_val is None:
hold_reason = hold_reason or "HOLD_EXPLICIT_NULL_CALIBRATION_PARAMETER"
resolved[param] = default_val
sources[param] = "panel_explicit_null_rejected"
continue
if has_local and has_panel:
# Check strict value equivalence (using Decimal for numeric values, exact str for provenance)
if param == "f_eligible_provenance":
same = isinstance(l_val, str) and isinstance(p_val, str) and l_val == p_val
else:
dl = _safe_exact_decimal(l_val)
dp = _safe_exact_decimal(p_val)
same = (dl is not None and dp is not None and dl == dp)
if not same:
hold_reason = hold_reason or "HOLD_CONFLICTING_PANEL_AND_LOCAL_CALIBRATION"
resolved[param] = l_val
sources[param] = "local_and_panel_matched" if same else "local_panel_conflict"
elif has_local:
resolved[param] = l_val
sources[param] = "local"
elif has_panel:
resolved[param] = p_val
sources[param] = "panel"
else:
resolved[param] = default_val
sources[param] = "default"
# Enforce bound parameter groups: never combine a local factor with a panel-scoped sibling alpha/provenance
for grp in (
("eta_recovery_l95", "alpha_eta_recovery"),
("f_eligible", "f_eligible_provenance", "alpha_f_eligible"),
):
g_loc = {k for k in grp if k in local_present_keys}
g_pan = {k for k in grp if k in panel_present_keys}
if g_loc and g_pan and (g_loc != g_pan):
hold_reason = hold_reason or "HOLD_PARTIAL_LOCAL_CALIBRATION_SPLITS_BOUND_GROUP"