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…

        cov_pct = float(cov_raw) if (cov_raw is not None and type(cov_raw) is not bool) else None

        # Prespecified H1 efficacy composite (preserved untouched)
        if "meets_h1_efficacy_override" in raw:
            meets_h1_eff = bool(raw["meets_h1_efficacy_override"]) and (she_count == 0)
        else:
            meets_h1_eff = (
                (hba1c_pct is not None and float(hba1c_pct) < 7.0)
                and (tir_pct is not None and float(tir_pct) > 70.0)
                and (she_count is not None and she_count == 0)
                and (cpep_pos is True)
                and (float(followup_days) >= 180.0)
            )

        incomplete_sensor_followup = (
            cov_pct is None
            or not math.isfinite(cov_pct)
            or cov_pct < float(min_cgm_coverage_pct)
            or tbr70_pct is None
            or tbr54_pct is None
            or tar250_pct is None
        )

        safety_flags: list[str] = []
        if she_count is None:
            safety_flags.append("MISSING_LEVEL3_SHE_ADJUDICATION")
        elif she_count > 0:
            safety_flags.append(f"CLINICIAN_ADJUDICATED_LEVEL3_ASSISTED_SHE_COUNT={she_count}")

        if incomplete_sensor_followup:
            safety_flags.append(
                f"INCOMPLETE_SENSOR_FOLLOWUP(coverage={cov_pct!r}<{min_cgm_coverage_pct:.1f}%_or_missing_cgm_safety_fields)"
            )
        else:
            if float(tbr70_pct) >= 4.0:
                safety_flags.append(f"TBR_LT70_EXCEEDS_ADA_4PCT({float(tbr70_pct):.2f}%)")
            if float(tbr54_pct) >= 1.0:
                safety_flags.append(f"LEVEL2_BIOCHEMICAL_HYPO_TBR_LT54_EXCEEDS_ADA_1PCT({float(tbr54_pct):.2f}%)")
            if float(tar250_pct) >= 5.0:
                safety_flags.append(f"TAR_GT250_EXCEEDS_ADA_5PCT({float(tar250_pct):.2f}%)")

        # Strict precedence: Level-3 assisted SHE ALWAYS fails safety regardless of normal CGM
        if she_count is not None and she_count > 0:
            safety_status = "FAIL_LEVEL3_ASSISTED_SHE"
            passes_net_safety = False
        elif incomplete_sensor_followup or she_count is None:
            safety_status = "INCOMPLETE_SENSOR_FOLLOWUP"
            passes_net_safety = False
        elif len(safety_flags) > 0:
            safety_status = "FAIL_BIOCHEMICAL_HYPO_OR_HYPERGLYCEMIA"
            passes_net_safety = False
        else:
            safety_status = "PASS_ADA_CGM_SAFETY_COMPANION"
            passes_net_safety = True

        per_record.append({
            "recipient_id": rid,
            "meets_h1_efficacy_benchmark": meets_h1_eff,
            "passes_net_glycemic_safety_companion": passes_net_safety,
            "net_glycemic_safety_status": safety_status,
            "incomplete_sensor_followup": incomplete_sensor_followup,
            "mean_glucose_mg_dL": round(mean_mg_dl, 4) if mean_mg_dl is not None else None,
            "hba1c_pct": round(float(hba1c_pct), 4) if hba1c_pct is not None else None,
            "tir_70_180_pct": round(float(tir_pct), 4) if tir_pct is not None else None,
            "tbr_lt70_pct": round(float(tbr70_pct), 4) if tbr70_pct is not None else None,
            "tbr_lt54_pct": round(float(tbr54_pct), 4) if tbr54_pct is not None else None,
            "tar_gt180_pct": round(float(tar180_pct), 4) if tar180_pct is not None else None,
            "tar_gt250_pct": round(float(tar250_pct), 4) if tar250_pct is not None else None,
            "cgm_coverage_pct": round(cov_pct, 4) if cov_pct is not None else None,
            "adjudicated_level3_she_count": she_count,
            "safety_flags": safety_flags,
        })

    n_tot = len(per_record)
    n_h1 = sum(1 for r in per_record if r["meets_h1_efficacy_benchmark"])
    n_safe = sum(1 for r in per_record if r["passes_net_glycemic_safety_companion"])
    n_inc = sum(1 for r in per_record if r["incomplete_sensor_followup"])
    n_she = sum(1 for r in per_record if (r["adjudicated_level3_she_count"] or 0) > 0)
    return {
        "audit_id": "BPR-19",
        "companion_metrics_provided": True,
        "preserves_prespecified_h1_efficacy_benchmark": True,
        "min_cgm_coverage_pct_required": float(min_cgm_coverage_pct),
        "ada_adult_consensus_targets": {
            "tbr_lt70_pct_lt": 4.0,
            "tbr_lt54_level2_biochemical_hypo_pct_lt": 1.0,
            "tar_gt250_pct_lt": 5.0,
            "adjudicated_level3_assisted_she_count_eq": 0,
        },
        "n_records": n_tot,
        "n_meeting_h1_efficacy_benchmark": n_h1,
        "n_passing_net_glycemic_safety_companion": n_safe,
        "n_h1_efficacy_pass_but_safety_fail_or_incomplete": sum(
            1 for r in per_record if r["meets_h1_efficacy_benchmark"] and not r["passes_net_glycemic_safety_companion"]
        ),
        "n_incomplete_sensor_followup": n_inc,
        "n_with_clinician_adjudicated_level3_she": n_she,
        "records": per_record,
    }


def evaluate_bpr06_baseline_attribution(record: dict[str, Any]) -> dict[str, Any]:
    """
    BPR-06 clinical baseline and graft-benefit attribution evaluator (Igls consensus & Stage 5
    indication separation between early-onset insulin-deficient T1D and early/longstanding LADA).

    Rules:
      - Requires explicit declaration of age_at_implantation_years, baseline endogenous C-peptide
        status, baseline insulin use, baseline severe hypoglycemia history, and background care.
      - When pre-implant endogenous C-peptide is measurable and ONLY post-implant positive
        C-peptide (without graft-attributed change from baseline) is supplied, returns
        `attribution_status = "ATTRIBUTION_UNRESOLVED"` ("attribution unresolved").
      - In an insulin-deficient recipient (undetectable baseline C-peptide), improved glycemic
        control (e.g., delta_tir_pct > 0 or delta_hba1c_pct < 0) with continued exogenous insulin
        is explicitly recognized as partial clinical benefit rather than zero benefit.
    """
    if not isinstance(record, dict):
        raise ValueError("record must be a dict")
    required_baseline_fields = (
        "age_at_implantation_years",
        "baseline_endogenous_c_peptide_measurable",
        "baseline_exogenous_insulin_u_per_day",
        "baseline_severe_hypo_events_prior_12mo",
        "background_care_regimen",
    )
    missing_fields = [f for f in required_baseline_fields if record.get(f) is None]
    base_cpep_meas = record.get("baseline_endogenous_c_peptide_measurable")
    post_cpep_pos = record.get("post_implant_c_peptide_positive")
    delta_cpep = record.get("delta_stimulated_c_peptide_ng_ml")
    delta_tir = record.get("delta_tir_pct")
    delta_hba1c = record.get("delta_hba1c_pct")
    continued_insulin = bool(record.get("post_implant_continued_exogenous_insulin", False))

    if missing_fields:
        status = "ATTRIBUTION_UNRESOLVED"
        label = "attribution unresolved"
        reason = f"Missing required baseline stratification fields: {', '.join(missing_fields)}."
    elif base_cpep_meas is True:
        # Measurable pre-implant C-peptide (e.g., early LADA): post-implant positivity alone proves nothing
        has_verified_change = (
            (delta_cpep is not None and float(delta_cpep) > 0.0 and record.get("graft_specific_attribution_verified") is True)
            and (
                (delta_tir is not None and float(delta_tir) > 0.0)
                or (delta_hba1c is not None and float(delta_hba1c) < 0.0)
            )
        )
        if not has_verified_change:
            status = "ATTRIBUTION_UNRESOLVED"
            label = "attribution unresolved"
            reason = (
                "Pre-implant endogenous C-peptide is measurable; post-implant positive C-peptide or "
                "insulin freedom alone cannot separate graft function from residual native beta cells "
                "without verified graft-attributed change from baseline."
            )
        else:
            status = "GRAFT_ATTRIBUTED_CHANGE_FROM_BASELINE"
            label = "graft-attributed improvement over measurable baseline"
            reason = "Verified graft-attributed C-peptide increment accompanied by improved glycemic outcomes."
    else:
        # Insulin-deficient baseline (undetectable baseline C-peptide)
        improved_glycemic = (
            (delta_tir is not None and float(delta_tir) > 0.0)
            or (delta_hba1c is not None and float(delta_hba1c) < 0.0)
        )
        if post_cpep_pos is True and improved_glycemic and continued_insulin:
            status = "PARTIAL_CLINICAL_BENEFIT_RECOGNIZED_WITH_CONTINUED_INSULIN"
            label = "partial clinical benefit with continued insulin"
            reason = (
                "Insulin-deficient recipient achieved graft-derived C-peptide and improved glycemic control "
                "while continuing reduced exogenous insulin (recognized as genuine clinical benefit per BPR-06/Igls)."
            )
        elif post_cpep_pos is True and improved_glycemic and not continued_insulin:
            status = "INSULIN_INDEPENDENT_CLINICAL_BENEFIT_FROM_DEFICIENT_BASELINE"
            label = "insulin-independent clinical benefit from insulin-deficient baseline"
            reason = "Insulin-deficient recipient achieved graft-derived C-peptide and improved glycemia without exogenous insulin."
        else:
            status = "ATTRIBUTION_UNRESOLVED"
            label = "attribution unresolved"
            reason = "Insufficient post-implant change-from-baseline glycemic or C-peptide evidence."

    return {
        "audit_id": "BPR-06",
        "attribution_status": status,
        "attribution_label": label,
        "missing_baseline_fields": missing_fields,
        "baseline_endogenous_c_peptide_measurable": base_cpep_meas,
        "post_implant_c_peptide_positive": post_cpep_pos,
        "continued_exogenous_insulin": continued_insulin,
        "reason": reason,
    }


def _run_gate28a_and_cmc_unit_tests() -> dict[str, Any]:
    """Executable unit & adversarial tests for B1 (CMC attempted-lot readiness, pooled reconciliation, order-independence, orphan rescue rejection) and B2 (Gate 28-A lot->MCB hierarchy, manifest, cohort-bound attestations, clustering, context independence)."""
    cases: list[dict[str, Any]] = []

    def _expect_cmc_value_error(label: str, bad_ledger: list[dict[str, Any]]) -> None:
        try:
            res = evaluate_cmc_attempted_lot_readiness(bad_ledger)
        except ValueError:
            cases.append({"case": label, "passed": True, "rejected_with_value_error": True})
            return
        raise ValueError(f"CMC negative test {label} unexpectedly succeeded: {res}")

    # 1. B1 exact worked example: P_release=0.80, P_infuse_given_released=0.50, H1=0.88 -> projected 0.352 (35.2%), measured 0.40!
    ledger_ex: list[dict[str, Any]] = []
    for i in range(1, 3):
        ledger_ex.append({
            "lot_id": f"LOT-FAIL-{i}", "mcb_id": "MCB-1", "lot_type": "SINGLE_RECIPIENT",
            "disposition": "FAILED_RELEASE", "planned_doses_n": 1, "infused_doses_n": 0,
            "c2b_responder_doses_n": 0, "recipient_ids": [], "recipient_outcomes": {},
        })
    for i in range(1, 5):
        ledger_ex.append({
            "lot_id": f"LOT-UNINF-{i}", "mcb_id": "MCB-1", "lot_type": "SINGLE_RECIPIENT",
            "disposition": "RELEASED_UNINFUSED", "planned_doses_n": 1, "infused_doses_n": 0,
            "c2b_responder_doses_n": 0, "recipient_ids": [], "recipient_outcomes": {},
        })
    for i in range(1, 5):
        ledger_ex.append({
            "lot_id": f"LOT-INF-{i}", "mcb_id": "MCB-1", "lot_type": "SINGLE_RECIPIENT",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 1, "infused_doses_n": 1,
            "c2b_responder_doses_n": 1, "recipient_ids": [f"REC-EX-{i}"],
            "recipient_outcomes": {f"REC-EX-{i}": 1},
        })
    cmc_ex = evaluate_cmc_attempted_lot_readiness(ledger_ex, h1_blueprint_override=0.88)
    if not (
        abs(cmc_ex["p_release_cmc"] - 0.80) < 1e-9
        and abs(cmc_ex["p_infuse_given_released"] - 0.50) < 1e-9
        and abs(cmc_ex["projected_cmc_attempted_lot_readiness"] - 0.352) < 1e-9
        and abs(cmc_ex["h1_cmc_attempted_lot_readiness"] - 0.352) < 1e-9
        and abs(cmc_ex["measured_weighted_cmc_readiness"] - 0.40) < 1e-9
        and abs(cmc_ex["diagnostic_omitted_infusion_product"] - 0.704) < 1e-9
        and cmc_ex["uninfused_released_lots_n"] == 4
        and cmc_ex["unique_clinical_recipients_n"] == 4
    ):
        raise ValueError(f"B1 CMC worked example check failed: {cmc_ex}")
    cases.append({"case": "b1_cmc_worked_example_0p80_0p50_0p88_equals_0p352", "passed": True, "projected": cmc_ex["projected_cmc_attempted_lot_readiness"], "measured": cmc_ex["measured_weighted_cmc_readiness"]})

    # 2. B1 split-lot recipient-weighted infusion & unused aliquot=0 (projected vs measured separated!)
    cmc_split = evaluate_cmc_attempted_lot_readiness([
        {
            "lot_id": "LOT-SPLIT-1", "mcb_id": "MCB-1", "lot_type": "SPLIT_LOT",
            "disposition": "RELEASED_INFUSED", "planned_doses_n": 4, "infused_doses_n": 3,
            "c2b_responder_doses_n": 3, "recipient_ids": ["REC-S1", "REC-S2", "REC-S3"],
            "recipient_outcomes": {"REC-S1": 1, "REC-S2": 1, "REC-S3": 1},
        }
    ])
    if not (
        abs(cmc_split["p_release_cmc"] - 1.0) < 1e-9