OpenIslet

scripts/verify_iip0041_clinical_h1_cd64t_siglec.py

EXP-028 (CAND-031 / Target IIP-0041 — Bucket 2A) Remediated Verification Suite

script Release v0.8.0 gen-eb955f8266035aba 984 KB · 69 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0041_clinical_h1_cd64t_siglec.py · SHA-256: f004cf6d8259b8b4…

            "source_verification_attestation_verified": source_verified,
            "parallel_cmc_ledger_verified": cmc_ledger_verified,
            "icc_sensitivity_report_attached": False,
            "icc_sensitivity_report": None,
            "boundary_sensitive_under_high_icc": False,
            "icc_sensitivity_review_status": None,
            "self_attested_inline_records_rejected": self_attested_inline_rejected,
            "trusted_clinical_store_resolution_source": trusted_store_source,
            "authenticated_store_record_sha256": authenticated_store_digests,
            "authenticated_store_issuer_authorities": authenticated_store_issuers,
            "parallel_cmc_readiness_summary": parallel_cmc_summary,
            "trusted_clinical_store_deployment_dependency": TRUSTED_CLINICAL_STORE_DEPLOYMENT_DEPENDENCY,
            "k": k,
            "n": n,
            "observed_rate_pct": round(100.0 * k / n, 4),
            "clopper_pearson_95_ci_pct": [round(100.0 * cp_lo, 2), round(100.0 * cp_hi, 2)],
            "clopper_pearson_95_ci_scope": "NOMINAL_IID_UNADJUSTED_RECIPIENT_COUNTS_ONLY_NOT_CLUSTER_ADJUSTED",
            "distinct_gmp_lots_n": distinct_gmp_lots_n,
            "distinct_mcb_n": distinct_mcb_n,
            "max_single_lot_n": max_single_lot_n,
            "max_single_lot_share": round(float(max_single_lot_share_frac), 6),
            "rho_lot": float(rho_lot_dec) if rho_lot_dec is not None else None,
            "rho_bank": float(rho_bank_dec) if rho_bank_dec is not None else None,
            "icc_variance_component_sum": (
                round(float(Fraction(rho_lot_dec) + Fraction(rho_bank_dec)), 6)
                if (rho_lot_dec is not None and rho_bank_dec is not None)
                else None
            ),
            "icc_convention": "SEPARATE_VARIANCE_COMPONENTS_RHO_LOT_PLUS_RHO_BANK_LE_1",
            "deff": None,
            "n_eff": None,
            "k_eff": None,
            "uniform_cluster_adjusted_p_ge_90": None,
            "anchored_cluster_adjusted_p_ge_90": None,
            "intercurrent_event_counts": ie_counts,
            "secondary_steroid_exposed_c2b_count_excluded_from_primary": secondary_steroid_exposed_c2b,
            "failure_reasons": failure_reasons,
        }

    m_eff_lot = sum(m * m for m in lot_counts.values()) / float(n)
    m_eff_bank = sum(b * b for b in bank_counts.values()) / float(n)
    deff = 1.0 + rho_lot * (m_eff_lot - 1.0) + rho_bank * (m_eff_bank - 1.0)
    n_eff = float(n) / deff
    k_eff = n_eff * (float(k) / float(n))

    p_unif_eff_ge_90 = 1.0 - beta_cdf(0.90, 1.0 + k_eff, 1.0 + (n_eff - k_eff))
    p_anch_eff_ge_90 = 1.0 - beta_cdf(0.90, 8.8 + k_eff, 1.2 + (n_eff - k_eff))
    p_unif_nom_ge_90 = 1.0 - beta_cdf(0.90, 1.0 + k, 1.0 + (n - k))
    cp_lo, cp_hi = clopper_pearson_ci(k, n)

    icc_sensitivity_report, boundary_sensitive_under_high_icc, icc_sensitivity_review_status = (
        _compute_gate28a_icc_sensitivity_report(k, n, m_eff_lot, m_eff_bank)
    )
    icc_sensitivity_report_attached = True

    if p_unif_eff_ge_90 < 0.90:
        failure_reasons.append(
            f"Cluster-adjusted Uniform Beta(1,1) P(H1>=0.90)={p_unif_eff_ge_90:.6f} < 0.90 "
            f"(k={k}, n={n}, DEFF={deff:.4f}, k_eff={k_eff:.4f}, n_eff={n_eff:.4f})."
        )
    if p_anch_eff_ge_90 < 0.85:
        failure_reasons.append(
            f"Cluster-adjusted non-Reichman Beta(8.8,1.2) P(H1>=0.90)={p_anch_eff_ge_90:.6f} < 0.85 "
            f"(k_eff={k_eff:.4f}, n_eff={n_eff:.4f})."
        )
    if icc_sensitivity_review_status == "HOLD_FAILS_PRIMARY_ICC_FLOOR":
        pf = icc_sensitivity_report["primary_floor"]
        failure_reasons.append(
            f"HOLD_FAILS_PRIMARY_ICC_FLOOR: prespecified primary ICC floor (rho_lot=0.05, rho_mcb=0.02) "
            f"fails Gate 28-A reanchor bar (DEFF={pf['deff_cluster']:.6f}, n_eff={pf['n_eff']:.6f}, "
            f"Uniform P(H1>=0.90)={pf['posterior_p_ge_090']:.6f}, Anchored P(H1>=0.90)={pf['anchored_posterior_p_ge_090']:.6f})."
        )
    elif icc_sensitivity_review_status == "HOLD_FAILS_MODERATE_ICC_SENSITIVITY":
        ms = icc_sensitivity_report["moderate_sensitivity"]
        failure_reasons.append(
            f"HOLD_FAILS_MODERATE_ICC_SENSITIVITY: prespecified moderate ICC sensitivity scenario "
            f"(rho_lot=0.10, rho_mcb=0.05) fails Gate 28-A reanchor bar (DEFF={ms['deff_cluster']:.6f}, "
            f"n_eff={ms['n_eff']:.6f}, Uniform P(H1>=0.90)={ms['posterior_p_ge_090']:.6f}, "
            f"Anchored P(H1>=0.90)={ms['anchored_posterior_p_ge_090']:.6f}); promotion blocked."
        )

    external_clinical_store_verified = (
        prespec_verified and source_verified and store_manifest_verified and cmc_ledger_verified
    )
    icc_sensitivity_allows_promotion = icc_sensitivity_review_status in (
        "ROBUST_ACROSS_ALL_THREE_PRESPECIFIED_ICC_SCENARIOS",
        "BOUNDARY_SENSITIVE_DISCLOSED_CLEARS_PRIMARY_AND_MODERATE",
    )
    promoted = (
        (len(failure_reasons) == 0)
        and external_clinical_store_verified
        and icc_sensitivity_report_attached
        and icc_sensitivity_allows_promotion
    )
    return {
        "status": "PROMOTE_H1_88_TO_90" if promoted else "HOLD_H1_AT_88PCT",
        "promotion_authorized": promoted,
        "external_clinical_store_verified": external_clinical_store_verified,
        "cohort_id": cohort_id,
        "cohort_canonical_sha256": cohort_canonical_sha256,
        "cohort_ledger_sha256": cohort_canonical_sha256,
        "lot_bank_hierarchy_valid": True,
        "lot_to_mcb_manifest_verified": store_manifest_verified,
        "lot_to_wcb_manifest_verified": store_wcb_verified,
        "prespecification_attestation_verified": prespec_verified,
        "source_verification_attestation_verified": source_verified,
        "parallel_cmc_ledger_verified": cmc_ledger_verified,
        "icc_sensitivity_report_attached": icc_sensitivity_report_attached,
        "icc_sensitivity_report": icc_sensitivity_report,
        "boundary_sensitive_under_high_icc": boundary_sensitive_under_high_icc,
        "icc_sensitivity_review_status": icc_sensitivity_review_status,
        "self_attested_inline_records_rejected": self_attested_inline_rejected,
        "trusted_clinical_store_resolution_source": trusted_store_source,
        "authenticated_store_record_sha256": authenticated_store_digests,
        "authenticated_store_issuer_authorities": authenticated_store_issuers,
        "parallel_cmc_readiness_summary": parallel_cmc_summary,
        "trusted_clinical_store_deployment_dependency": TRUSTED_CLINICAL_STORE_DEPLOYMENT_DEPENDENCY,
        "k": k,
        "n": n,
        "observed_rate_pct": round(100.0 * k / n, 4),
        "clopper_pearson_95_ci_pct": [round(100.0 * cp_lo, 2), round(100.0 * cp_hi, 2)],
        "clopper_pearson_95_ci_scope": "NOMINAL_IID_UNADJUSTED_RECIPIENT_COUNTS_ONLY_NOT_CLUSTER_ADJUSTED",
        "distinct_gmp_lots_n": distinct_gmp_lots_n,
        "distinct_mcb_n": distinct_mcb_n,
        "max_single_lot_n": max_single_lot_n,
        "max_single_lot_share": round(float(max_single_lot_share_frac), 6),
        "rho_lot": rho_lot,
        "rho_bank": rho_bank,
        "icc_variance_component_sum": round(float(Fraction(rho_lot_dec) + Fraction(rho_bank_dec)), 6) if (rho_lot_dec is not None and rho_bank_dec is not None) else round(rho_lot + rho_bank, 6),
        "icc_convention": "SEPARATE_VARIANCE_COMPONENTS_RHO_LOT_PLUS_RHO_BANK_LE_1",
        "m_eff_lot": round(m_eff_lot, 6),
        "m_eff_bank": round(m_eff_bank, 6),
        "deff": round(deff, 6),
        "n_eff": round(n_eff, 6),
        "k_eff": round(k_eff, 6),
        "uniform_nominal_p_ge_90": round(p_unif_nom_ge_90, 6),
        "uniform_cluster_adjusted_p_ge_90": round(p_unif_eff_ge_90, 6),
        "anchored_cluster_adjusted_p_ge_90": round(p_anch_eff_ge_90, 6),
        "cluster_adjusted_probability_scope": (
            "PRESPECIFIED_DECISION_MODEL_QUANTITIES_CONDITIONAL_ON_ASSUMED_ICC_VARIANCE_COMPONENTS_NOT_INDEPENDENT_CALIBRATION"
        ),
        "intercurrent_event_counts": ie_counts,
        "secondary_steroid_exposed_c2b_count_excluded_from_primary": secondary_steroid_exposed_c2b,
        "glycemic_safety_companion_bpr19": (
            evaluate_h1_glycemic_safety_companion_bpr19(recipients)
            if any(
                any(
                    k_cgm in r
                    for k_cgm in (
                        "cgm_readings_mg_dL_weights",
                        "tbr_lt70_pct",
                        "tbr_lt54_pct",
                        "tar_gt250_pct",
                        "cgm_coverage_pct",
                        "adjudicated_level3_she_count",
                    )
                )
                for r in recipients
                if isinstance(r, dict)
            )
            else {
                "companion_metrics_provided": False,
                "status": "NOT_PROVIDED_IN_LEGACY_COHORT_PAYLOAD",
                "note": (
                    "Prespecified H1 efficacy decision is preserved unchanged; attach per-window CGM safety "
                    "fields (tbr_lt70_pct, tbr_lt54_pct, tar_gt250_pct, cgm_coverage_pct, "
                    "adjudicated_level3_she_count) when interpreting net glycemic safety (BPR-19)."
                ),
            }
        ),
        "failure_reasons": failure_reasons,
    }


def evaluate_h1_glycemic_safety_companion_bpr19(
    records: list[dict[str, Any]],
    *,
    min_cgm_coverage_pct: float = 70.0,
) -> dict[str, Any]:
    """
    BPR-19 companion net glycemic safety reporter for H1 cohorts (Battelino 2019, PMID:31177185;
    ADA Standards Section 6 / Table 6.3).

    Design invariants:
      - Preserves the prespecified H1 efficacy benchmark (HbA1c < 7.0%, TIR 70-180 mg/dL > 70%,
        0 clinician-adjudicated Level-3 assisted SHEs, quantitative positive stimulated C-peptide,
        >= 180 d follow-up) and its historical numerator unchanged.
      - Separately reports time below 70 mg/dL (< 4.0% target), Level-2 biochemical hypoglycemia
        below 54 mg/dL (< 1.0% target), time above 250 mg/dL (< 5.0% target), CGM sensor coverage
        (explicit incomplete sensor follow-up flag when missing or < 70.0%), and clinician-adjudicated
        Level-3 assisted severe hypoglycemic events for the exact same window.
      - An independently observed clinician-adjudicated Level-3 assisted SHE ALWAYS fails both
        H1 efficacy and net glycemic safety, even if the CGM reading distribution appears normal.
    """
    if not isinstance(records, list) or len(records) == 0:
        raise ValueError("records must be a non-empty list of participant records")

    per_record: list[dict[str, Any]] = []
    for idx, raw in enumerate(records):
        if not isinstance(raw, dict):
            raise ValueError(f"record[{idx}] must be a dict")
        rid = str(raw.get("recipient_id", f"REC-{idx + 1:03d}"))

        # Optional discrete reading distribution: list of (glucose_mg_dL, weight) pairs
        mean_mg_dl: float | None = None
        tir_pct = raw.get("tir_70_180_pct")
        tbr70_pct = raw.get("tbr_lt70_pct")
        tbr54_pct = raw.get("tbr_lt54_pct")
        tar180_pct = raw.get("tar_gt180_pct")
        tar250_pct = raw.get("tar_gt250_pct")

        dist_pairs = raw.get("cgm_readings_mg_dL_weights")
        if dist_pairs is not None:
            if not isinstance(dist_pairs, list) or len(dist_pairs) == 0:
                raise ValueError(f"{rid}: cgm_readings_mg_dL_weights must be a non-empty list")
            total_w = 0.0
            mean_acc = 0.0
            w_tir = w_lt70 = w_lt54 = w_gt180 = w_gt250 = 0.0
            for pair in dist_pairs:
                g_val = float(pair[0])
                w_val = float(pair[1])
                if not (math.isfinite(g_val) and math.isfinite(w_val)) or w_val < 0.0:
                    raise ValueError(f"{rid}: invalid (glucose, weight) pair {pair!r}")
                total_w += w_val
                mean_acc += g_val * w_val
                if 70.0 <= g_val <= 180.0:
                    w_tir += w_val
                if g_val < 70.0:
                    w_lt70 += w_val
                if g_val < 54.0:
                    w_lt54 += w_val
                if g_val > 180.0:
                    w_gt180 += w_val
                if g_val > 250.0:
                    w_gt250 += w_val
            if total_w <= 0.0:
                raise ValueError(f"{rid}: cgm_readings_mg_dL_weights sum must be > 0")
            mean_mg_dl = mean_acc / total_w
            tir_pct = 100.0 * w_tir / total_w
            tbr70_pct = 100.0 * w_lt70 / total_w
            tbr54_pct = 100.0 * w_lt54 / total_w
            tar180_pct = 100.0 * w_gt180 / total_w
            tar250_pct = 100.0 * w_gt250 / total_w

        hba1c_pct = raw.get("hba1c_pct")
        cpep_pos = raw.get("stimulated_c_peptide_positive")
        followup_days = raw.get("followup_days", 180.0)
        she_raw = raw.get("adjudicated_level3_she_count")
        she_count = int(she_raw) if (she_raw is not None and type(she_raw) is not bool) else None
        cov_raw = raw.get("cgm_coverage_pct")