OpenIslet

scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py

IIP-0043 / DEC-122 (CAND-034 / EXP-031 — Bucket 1 Closure, Stage S3-R2 Remediated)

script Release v0.8.0 gen-eb955f8266035aba 1008 KB · 76 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_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…

                        sampling_unit_class=sampling_unit_class,
                        indep_units_n=indep_units,
                        sampling_tracker=sampling_tracker,
                    )
                    reg_lineage_details[str(extra_lin)] = extra_detail
            ap_summary[reg] = {"passed": reg_pass, "lineages": reg_lineage_details}

        # R03-B1 / B6: Apply FULL consistent fail-closed adjudication to EVERY submitted supplemental stress regime!
        for extra_reg, extra_rblock in ap_data.items():
            if extra_reg not in required_kill_regimes:
                supplemental_ap_summary[extra_reg] = _adjudicate_supplemental_kill_regime_adverse_data(
                    extra_reg,
                    extra_rblock,
                    deff=deff,
                    hard_stops=hard_stops,
                    holds=holds,
                    adjudicated_log=supplemental_adjudicated,
                    sampling_spec_valid=sampling_spec_valid,
                    sampling_unit_class=sampling_unit_class,
                    indep_units_n=indep_units,
                    sampling_tracker=sampling_tracker,
                )

    # B6: Explicit tested-vs-inherited scope & tier-distinct PASS codes!
    inherited_pathogens = [p for p in GATE0V_PATHOGENS if p not in required_pathogens]
    inherited_kill_regimes = [r for r in STRESS_AP1903_REGIMES if r not in required_kill_regimes]
    tested_vs_inherited_scope = {
        "operational_tier": qual_tier if isinstance(qual_tier, str) else None,
        "tested_current_lot_pathogens": list(required_pathogens),
        "inherited_from_trusted_store_pathogens": inherited_pathogens,
        "tested_current_lot_kill_regimes": list(required_kill_regimes),
        "inherited_from_trusted_store_kill_regimes": inherited_kill_regimes,
        "edited_genotype_noninferiority_enforced_current_lot": bool(isinstance(geno, str) and geno in EDITED_ANTIVIRAL_GENOTYPES),
        "supplemental_submitted_data_adjudicated": supplemental_adjudicated,
        "inheritance_policy": (
            "BANK_QUALIFICATION tests full 3-pathogen x 5-lineage + 5-regime matrix directly (zero inheritance). "
            "LOT_RELEASE_SURROGATE inherits CVB3/HCMV persistence and ER/infected AP1903 regimes strictly from an "
            "externally verified MCB BANK_QUALIFICATION record while testing current-lot CVB4-E2 + 2-regime AP1903 "
            "and applying full consistent fail-closed adjudication to ALL submitted supplemental data. "
            "AUTOLOGOUS_D1B_PROCESS_QUAL inherits platform viral challenge strictly from an externally verified "
            "process-qualification record while enforcing current-lot adventitious-agent screening, Gate 0V-A, "
            "2-regime AP1903, edited-genotype non-inferiority, and full consistent fail-closed adjudication of ALL submitted supplemental data."
        ),
    }

    numerical_evidence_provenance_scope = {
        "supplied_assay_interval_and_replicate_summaries": (
            "Gate 0V-Geno paired edited-vs-WT antiviral non-inferiority (`edited_minus_wt_day14_log10_reduction_l95`, "
            "`paired_noninferiority_replicates_n >= 6`) and Gate 0V-B acute 72-h titer U95 / Day-14 log10 reduction L95 "
            "fields consume caller-supplied assay interval and replicate summaries rather than recomputing confidence "
            "intervals from raw replicate titers."
        ),
        "raw_count_recomputed_decimal_clopper_pearson_bounds": (
            "Gate 0V-B Day-28 viral persistence U_lin, uninfected negative-control U95 (<= 0.15% on n >= 20,000), "
            "dual healthy + fragile spike-calibrant recovery lower bounds (eta >= 0.80), dual-target latent/defective-genome "
            "ddPCR bounds, powered CD46/CD55 persistence bounds, and ALL Gate 0V-Kill 24-h, 72-h, vehicle survival, "
            "calibrant, Estimand 1, and Estimand 2 erasure bounds are independently recomputed from raw integer counts "
            "via outward-directed Decimal Clopper-Pearson interval arithmetic."
        ),
    }

    # R12-B1: Reconcile global per-estimand sampling-unit basis BEFORE finalizing confidence certification!
    is_clustered_deff_gt_1 = bool(deff is not None and deff > Decimal("1.0"))
    if (
        sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT"
        and sampling_tracker["max_binomial_denominator_n"] >= 1
        and (not indep_units_valid or indep_units is None or indep_units < sampling_tracker["max_binomial_denominator_n"])
    ):
        sampling_tracker["all_partitions_reconciled"] = False
        if "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" not in holds:
            holds.append("HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS")

    all_sampling_units_reconciled = bool(
        sampling_spec_valid
        and sampling_tracker["all_partitions_reconciled"]
        and (
            (
                sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT"
                and indep_units is not None
                and sampling_tracker["max_binomial_denominator_n"] >= 1
                and indep_units >= max(MIN_INDEPENDENT_BIOLOGICAL_UNITS_N, sampling_tracker["max_binomial_denominator_n"])
            )
            or (
                sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION"
                and sampling_tracker["partitions_checked"] > 0
                and sampling_tracker["partitions_reconciled"] == sampling_tracker["partitions_checked"]
            )
        )
    )

    # R13-M2: NEVER retain an unvalidated numeric `deff` inside `clustering_design_effect_deff`
    # when `clustering_and_independence_spec` is invalid, has < 6 units, or lacks reconciled partitions!
    validated_deff: Decimal | None = deff if (sampling_spec_valid and all_sampling_units_reconciled) else None
    deff_unvalidated_out: str | None = None if validated_deff is not None else submitted_deff_unvalidated_safe

    if not sampling_spec_valid or deff is None:
        is_exact_independent = False
        top_confidence_scope = "UNCERTIFIED_MISSING_OR_INVALID_SAMPLING_SPEC"
    elif not all_sampling_units_reconciled:
        is_exact_independent = False
        top_confidence_scope = "UNCERTIFIED_SAMPLING_UNIT_PARTITION_MISMATCH"
        if (
            "HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS" not in holds
            and "HOLD_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION" not in holds
            and "HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE" not in holds
        ):
            holds.append("HOLD_SAMPLING_UNIT_PARTITION_MISMATCH_OR_INSUFFICIENT_UNITS")
    elif is_clustered_deff_gt_1:
        is_exact_independent = False
        top_confidence_scope = "NON_AUTHORIZING_VARIANCE_ADJUSTED_DIAGNOSTIC_ONLY"
    elif sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT":
        is_exact_independent = True
        top_confidence_scope = "EXACT_INDEPENDENT_BINOMIAL_BONFERRONI_DEFF_EQ_1_UNIT_MATCHED"
    else:
        is_exact_independent = True
        top_confidence_scope = "CONDITIONAL_ON_EXTERNALLY_VALIDATED_WITHIN_WELL_INDEPENDENCE_DEFF_EQ_1"

    # Ensure NO nested Gate 0V-Kill arm or alpha-budget dict retains `exact_directional_confidence_certified = True`
    # when top-level certification is False, AND scrub unvalidated nested `clustering_design_effect_deff` to None!
    if not is_exact_independent or validated_deff is None:
        _scrub_stack: List[Any] = [ap_summary, supplemental_ap_summary]
        while _scrub_stack:
            _cur = _scrub_stack.pop()
            if isinstance(_cur, dict):
                if not is_exact_independent:
                    if _cur.get("exact_directional_confidence_certified") is True:
                        _cur["exact_directional_confidence_certified"] = False
                    if "confidence_scope" in _cur:
                        _cur["confidence_scope"] = top_confidence_scope
                    if "joint_confidence_lower_bound" in _cur:
                        _cur["joint_confidence_lower_bound"] = None
                    if _cur.get("estimand2_release_authorizing_eligible") is True:
                        _cur["estimand2_release_authorizing_eligible"] = False
                if validated_deff is None and "clustering_design_effect_deff" in _cur:
                    _cur["clustering_design_effect_deff"] = None
                for _v in _cur.values():
                    if isinstance(_v, (dict, list, tuple)):
                        _scrub_stack.append(_v)
            elif isinstance(_cur, (list, tuple)):
                for _item in _cur:
                    if isinstance(_item, (dict, list, tuple)):
                        _scrub_stack.append(_item)

    sampling_unit_basis = {
        "clustering_and_independence_spec_valid": sampling_spec_valid,
        "clustering_design_effect_deff": format(validated_deff, "f") if validated_deff is not None else None,
        "submitted_clustering_design_effect_deff_unvalidated": deff_unvalidated_out,
        "independent_sampling_unit_class": sampling_unit_class if sampling_unit_class_valid else None,
        "independent_biological_units_n": indep_units if indep_units_valid else None,
        "supplied_independent_biological_units_n": indep_units,
        "min_required_independent_biological_units_n": MIN_INDEPENDENT_BIOLOGICAL_UNITS_N,
        "unit_definition": unit_def if unit_def_valid else None,
        "max_binomial_denominator_n": sampling_tracker["max_binomial_denominator_n"],
        "estimand_partitions_checked": sampling_tracker["partitions_checked"],
        "estimand_partitions_reconciled": sampling_tracker["partitions_reconciled"],
        "all_sampling_units_reconciled": all_sampling_units_reconciled,
        "within_well_independence_externally_validated_required": bool(
            sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION"
        ),
        "external_qa_disclaimer": (
            "JSON unit-partition reconciliation verifies per-unit arithmetic traceability across "
            ">= 6 declared independent biological units but does NOT by itself prove physical "
            "within-well statistical independence (deff == 1.0) or equal per-unit event probability "
            "(common-probability binomial model); external assay QA must verify zero intra-well "
            "clustering and homogeneous event probabilities, otherwise cluster-level or heterogeneous-unit "
            "inference is required."
            if sampling_unit_class == "RECONCILED_MULTI_WELL_CELL_ASSAY_WITH_UNIT_PARTITION"
            else (
                "Declared single-cell / limiting-dilution sampling basis matches independent unit count "
                "to the maximum evaluated binomial denominator (independent_biological_units_n >= max_n); "
                "unit-count declaration and arithmetic reconciliation do NOT physically prove representative "
                "sampling or a common Bernoulli event probability across units."
                if sampling_unit_class == "INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT" and all_sampling_units_reconciled
                else "Sampling-unit basis is missing, invalid, clustered (deff > 1.0), or unreconciled; exact directional confidence is NOT certified."
            )
        ),
        "probability_model_assumptions": (
            "Exact per-estimand directional one-sided Clopper-Pearson bounds assume representative, "
            "independent binary trials sharing a common event probability p within each component "
            "(standard Binomial(n, p) model). Independent sampling with unequal / heterogeneous unit "
            "event probabilities falls outside the standard common-probability binomial model. "
            "Gate 0V-Kill evaluates acute 24-h/72-h stressed AP1903 viability/erasure separately from "
            "long-horizon pan-lineage clonogenic eradication (which is owned by Blueprint Gate 5 / "
            "legacy MCB clonogenic trials in wetlab_contract.py & ISLET-1-BLUEPRINT.md §1.2/§4.5)."
        ),
    }

    # Hard stops ALWAYS take precedence over power/completeness holds!
    if hard_stops:
        verdict = "FAIL_HARD_STOP"
    elif holds:
        if holds == ["HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION"]:
            verdict = "HOLD_NW08_REQUIRED_OCR_NOT_PERMITTED_ON_BANK_QUALIFICATION"
        elif holds == ["HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"]:
            verdict = "HOLD_NW08_REQUIRED_OCR_RECORD_MISSING"
        elif (
            sampling_spec_valid
            and all_sampling_units_reconciled
            and is_clustered_deff_gt_1
            and "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE" in holds
        ):
            verdict = "HOLD_CLUSTERED_DEFF_GT_1_REQUIRES_CLUSTER_LEVEL_INFERENCE"
        else:
            verdict = "HOLD_INCOMPLETE_OR_UNDERPOWERED"
    else:
        verdict = (
            GATE0V_PASS_VERDICTS_BY_TIER.get(str(qual_tier), "HOLD_INCOMPLETE_OR_UNDERPOWERED")
            if is_exact_independent
            else "HOLD_INCOMPLETE_OR_UNDERPOWERED"
        )

    return {
        "verdict": verdict,
        "release_authorizing": False,
        "gate0v_component_passed": bool(verdict in GATE0V_ALL_PASS_VERDICTS and is_exact_independent),
        "qualification_scope": QUALIFICATION_SCOPE_MODELED_PENDING_PHYSICAL,
        "physical_qualification_complete": False,
        "exact_directional_confidence_certified": is_exact_independent,
        "confidence_scope": top_confidence_scope,
        "sampling_unit_basis": sampling_unit_basis,
        "lot_binding": lot_binding,
        "tested_vs_inherited_scope": tested_vs_inherited_scope,
        "numerical_evidence_provenance_scope": numerical_evidence_provenance_scope,
        "ectopic_viral_receptors_evaluated": sorted(effective_ectopic),
        "clustering_design_effect_deff": format(validated_deff, "f") if validated_deff is not None else None,
        "submitted_clustering_design_effect_deff_unvalidated": deff_unvalidated_out,
        "hard_stops": hard_stops,
        "holds": holds,
        "global_3pathogen_fwer_alpha_per_test": format(alpha_3p, "f")[:24],
        "negative_control_u95_cap_pct": "0.15",
        "all_required_pathogens_and_5_lineages_calibrated": all_pathogens_ok,
        "pathogen_results": pathogen_results,
        "cd46_addendum_results": cd46_results,
        "cd55_addendum_results": cd55_results,
        "stress_ap1903_regimes": ap_summary,
        "supplemental_stress_ap1903_regimes": supplemental_ap_summary,
    }


# ---------------------------------------------------------------------------
# Part B (NW-08): True 3D FVM Vascular-Voxel Replay & Margin+Uncertainty Triggers
# ---------------------------------------------------------------------------
def _passes_unrounded_diagnostic_floor(raw_face_min_mmhg: float, custom_floor_mmhg: float) -> bool:
    """
    Strictly evaluate a non-authorizing diagnostic floor against the native UNROUNDED float64
    FV interface minimum. NEVER governs canonical 15.0 mmHg release pass/verdict!
    """
    try:
        val = _safe_finite_float(raw_face_min_mmhg, "raw_face_min_mmhg")
        fl = _safe_finite_float(custom_floor_mmhg, "custom_floor_mmhg")