OpenIslet

scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py

IIP-0042 / DEC-121 (CAND-033 / EXP-030): Master Exact 2^20 Multi-Layer Portfolio

script Release v0.8.0 gen-eb955f8266035aba 881 KB · 63 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_iip0042_master_multilayer_portfolio_crosswalk.py · SHA-256: 16964a158458b5cf…

    contradiction-guarded gy018_independence_justification, exact GY-018 design_effect_deff == 1.0 (zero
    tolerance, preserved as exact Decimal through JSON decoding), suppression assay acceptance range [-1000.0, 100.0]%
    with overflow-immune non-authorizing Student-t diagnostic, mandatory cryptographically hash-pinned
    outcome-blind preregistered_donor_family_roster (100% reconciled on ALL raw submitted donor IDs BEFORE
    deduplication/quarantine filtering; unverified/unpinned/incomplete/unrostered rosters fail closed to
    HOLD_INVALID_OR_MISSING_INPUT for overall PASS and donor-based FAIL, while independent valid non-donor
    SPR failures remain fail-first FAIL tagged failure_domain='INDEPENDENT_NON_DONOR_SPR' and out-of-spec
    physicochemical SEC-MALS/DLS measurements hold as unqualified material inputs with failure_domain=None),
    cluster-conservative distribution-free exact one-sided Clopper-Pearson suppression inference across donor,
    expression-batch, assay-run, and joint (batch U run) connected components (confirmatory PASS requires
    >= 9 disjoint batch/run clusters and L95_CP >= 70.0% + anti-enhancement min >= 0.0% + mean >= 70.0%;
    suppression FAIL requires L95_CP(k_lt_40) > 60.0% across >= 6 disjoint batch/run clusters; Student-t is
    strictly non-authorizing; only one-sided lower bounds drive adjudication while U95 is descriptive only),
    100%-measured full-roster cytotoxicity requirement for confirmatory PASS
    (len(excluded_donor_records) == 0 and valid_donor_records_n == N_roster), and distribution-free fixed
    pre-exclusion roster Bonferroni-calibrated FWER <= 0.05 cytotoxicity FAIL rule under H0_all:
    max_{i=1..N_roster} p_i <= 5.0% using alpha_donor = 0.05 / N_roster (scoped strictly to the fixed-roster
    donor cytotoxicity family, conditional on external outcome-blind custody & pre-readout receipt; cohort
    Student-t lower bound is strictly non-authorizing). Two-pass order-independent canonical key uniqueness
    runs BEFORE biological threshold adjudication across ALL evidence lists (expression_batches,
    on_target_analytes, off_target_controls, comp2_comparators_screened, donors), and derived_summary emits
    machine-checked trackb_shield_trigger_state distinguishing SHIELD-1-only Comp2 failure vs overall SHIELD
    failure while excluding all non-FAIL, held, invalid, and partial-FAIL states.
    """
    if not isinstance(observation, dict):
        raise ValueError("Gate 30-SHIELD-SPR observation must be a JSON object")
    _shield_reject_nonfinite_tree(observation, "observation")

    reasons: list[str] = []
    worst_state = "PASS"
    spr_bio_fail = False
    comp1_spr_bio_fail = False
    comp2_spr_bio_fail = False
    comp1_on_target_passed_analytes: set[str] = set()
    comp1_off_target_passed_controls: set[str] = set()
    donor_based_bio_fail = False
    derived_summary: dict[str, Any] = {}

    def _escalate(state: str, reason: str) -> None:
        nonlocal worst_state
        reasons.append(f"[{state}] {reason}")
        if _SHIELD_SPR_PRECEDENCE[state] > _SHIELD_SPR_PRECEDENCE[worst_state]:
            worst_state = state

    # 1. Expression batches (R08 B3: two-pass order-independent uniqueness BEFORE accepting passing batches;
    #    >= 3 distinct passing batches per cocktail lead; non-empty construct_ids required on EVERY batch)
    batches = observation.get("expression_batches")
    passing_batch_constructs: dict[str, frozenset[str]] = {}
    referenced_batches: set[str] = set()
    comp1_assay_batches: set[str] = set()
    comp2_assay_batches: set[str] = set()
    cocktail_comp1_batches: set[str] = set()
    cocktail_comp2_batches: set[str] = set()
    conflicted_batch_ids: set[str] = set()
    if not isinstance(batches, list) or len(batches) == 0:
        _escalate("HOLD_INVALID_OR_MISSING_INPUT", "Missing typed expression_batches list (>= 3 distinct batches required)")
    else:
        batch_id_counts: dict[str, int] = {}
        for b in batches:
            if isinstance(b, dict):
                bid = b.get("batch_id")
                if type(bid) is str and bid.strip():
                    bid_c = bid.strip()
                    batch_id_counts[bid_c] = batch_id_counts.get(bid_c, 0) + 1
        conflicted_batch_ids = {k for k, cnt in batch_id_counts.items() if cnt > 1}
        for cbid in sorted(conflicted_batch_ids):
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Duplicate/conflicting expression batch_id: {cbid!r} (count={batch_id_counts[cbid]}); all occurrences excluded",
            )

        lead_batch_counts: dict[str, int] = {ld: 0 for ld in _SHIELD_COCKTAIL_LEADS}
        for idx, b in enumerate(batches):
            if not isinstance(b, dict):
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"expression_batches[{idx}] must be an object")
                continue
            bid = b.get("batch_id")
            if type(bid) is not str or not bid.strip():
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"expression_batches[{idx}] missing non-empty batch_id")
                continue
            bid_clean = bid.strip()
            if bid_clean in conflicted_batch_ids:
                continue
            if b.get("qc_passed") is not True:
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", f"Expression batch {bid_clean!r} failed qc_passed")
                continue
            c_set, c_err = _shield_parse_batch_construct_ids(b, bid_clean)
            if c_err is not None or c_set is None:
                _escalate("HOLD_INVALID_OR_MISSING_INPUT", c_err or f"Invalid construct_ids on batch {bid_clean!r}")
                continue
            passing_batch_constructs[bid_clean] = c_set
            for ld in _SHIELD_COCKTAIL_LEADS:
                if ld in c_set:
                    lead_batch_counts[ld] += 1
        if len(passing_batch_constructs) < _SHIELD_MIN_BATCHES_N:
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"Under-replicated passing expression_batches: {len(passing_batch_constructs)} < {_SHIELD_MIN_BATCHES_N}",
            )
        for ld, cnt in lead_batch_counts.items():
            if cnt < _SHIELD_MIN_BATCHES_N:
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"Construct {ld} covered by only {cnt} passing batches (< {_SHIELD_MIN_BATCHES_N})",
                )

    # 2. Register QC records (R12 0039-B1 + R14 0039-B2 + R17 0044-B1/B2: validated and reconciled STRICTLY BEFORE
    #    on-target/off-target SPR biological adjudication and batch-linkage credit! Cocktail-bound batches covering
    #    BOTH Comp1 HIP11 and Comp2 WT15/6DFX validate parent coverage ONLY and NEVER credit comp1_assay_batches or
    #    comp2_assay_batches (which count ONLY validated SPR/comparator rows). Mandatory pairwise-distinct peptide
    #    reagent lot IDs are enforced across HIP11, 15-aa WT InsB:9-23, 12-aa 6DFX, and optional 14-aa 1JK8 if present
    #    BEFORE granting dependent records biological or batch credit, while retaining independent qualified evidence!)
    rqc = observation.get("register_qc_records")
    hip11_exchange_qc_valid = False
    r6dfx_qc_valid = False
    wt15_register_qc_valid = False
    r1jk8_qc_valid = False
    rqc_hip11_lot: str | None = None
    rqc_wt_lot: str | None = None
    rqc_6dfx_lot: str | None = None
    rqc_1jk8_lot: str | None = None
    rqc_comp1_batches: set[str] = set()
    rqc_comp2_batches: set[str] = set()
    collided_reagents: set[str] = set()
    if not isinstance(rqc, dict):
        _escalate("HOLD_INVALID_OR_MISSING_INPUT", "Missing typed register_qc_records object")
        derived_summary["optional_1jk8_physical_control_present"] = False
    else:
        tmp_ref_rqc: set[str] = set()
        tmp_c1_rqc: set[str] = set()
        tmp_c2_rqc: set[str] = set()
        rqc_b_err = _shield_validate_batch_ids(
            rqc.get("expression_batch_ids"),
            "register_qc_records",
            passing_batch_constructs,
            tmp_ref_rqc,
            require_cocktail_both_leads=True,
            role_comp1_batches=tmp_c1_rqc,
            role_comp2_batches=tmp_c2_rqc,
        )
        rqc_batch_valid = rqc_b_err is None
        if rqc_b_err is not None:
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", rqc_b_err)
        else:
            rqc_comp1_batches = set(tmp_c1_rqc)
            rqc_comp2_batches = set(tmp_c2_rqc)
        raw_rqc_hip11_lot = rqc.get("hip11_peptide_reagent_lot_id")
        if (
            type(raw_rqc_hip11_lot) is not str
            or not raw_rqc_hip11_lot
            or raw_rqc_hip11_lot != raw_rqc_hip11_lot.strip()
            or not _SHIELD_STRICT_ID_RE.match(raw_rqc_hip11_lot)
        ):
            _escalate(
                "HOLD_INVALID_OR_MISSING_INPUT",
                f"register_qc_records missing valid unpadded hip11_peptide_reagent_lot_id "
                f"(got {raw_rqc_hip11_lot!r})",
            )
        else:
            rqc_hip11_lot = raw_rqc_hip11_lot
        hip11_flag_ok = rqc.get("hip11_dq25_dq8t_dq22_exchange_qc_passed") is True
        if not hip11_flag_ok:
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", "HIP11 peptide-exchange QC across DQ2.5/DQ8-trans/DQ2.2 not passed")
        wt15_rec = rqc.get("native_wt_insb9_23_15aa")
        wt15_rec_metrics_ok = False
        if (
            not isinstance(wt15_rec, dict)
            or wt15_rec.get("sequence") != "SHLVEALYLVCGERG"
            or wt15_rec.get("lcms_identity_passed") is not True
            or wt15_rec.get("register2_occupancy_qc_passed") is not True
        ):
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", "Native 15-aa WT InsB:9-23 (SHLVEALYLVCGERG) LC-MS & Register-2 QC missing or failed")
        else:
            raw_rqc_wt_lot = wt15_rec.get("peptide_reagent_lot_id")
            if (
                type(raw_rqc_wt_lot) is not str
                or not raw_rqc_wt_lot
                or raw_rqc_wt_lot != raw_rqc_wt_lot.strip()
                or not _SHIELD_STRICT_ID_RE.match(raw_rqc_wt_lot)
            ):
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"register_qc_records.native_wt_insb9_23_15aa missing valid unpadded peptide_reagent_lot_id "
                    f"(got {raw_rqc_wt_lot!r})",
                )
            else:
                rqc_wt_lot = raw_rqc_wt_lot
                wt15_rec_metrics_ok = True
        r6dfx_rec = rqc.get("engineered_6dfx_p8e9e_12aa")
        r6dfx_rec_metrics_ok = False
        if (
            not isinstance(r6dfx_rec, dict)
            or r6dfx_rec.get("sequence") != "VEELYLVAGEEG"
            or r6dfx_rec.get("qc_passed") is not True
        ):
            _escalate("HOLD_INVALID_OR_MISSING_INPUT", "12-aa PDB 6DFX p8E9E Register-3 comparator (VEELYLVAGEEG) QC record missing or failed")
        else:
            raw_rqc_6dfx_lot = r6dfx_rec.get("peptide_reagent_lot_id")
            if (
                type(raw_rqc_6dfx_lot) is not str
                or not raw_rqc_6dfx_lot
                or raw_rqc_6dfx_lot != raw_rqc_6dfx_lot.strip()
                or not _SHIELD_STRICT_ID_RE.match(raw_rqc_6dfx_lot)
            ):
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    f"register_qc_records.engineered_6dfx_p8e9e_12aa missing valid unpadded peptide_reagent_lot_id "
                    f"(got {raw_rqc_6dfx_lot!r})",
                )
            else:
                rqc_6dfx_lot = raw_rqc_6dfx_lot
                r6dfx_rec_metrics_ok = True
        r1jk8_present = False
        r1jk8_metrics_ok = False
        r1jk8_lot_syntax_ok = True
        r1jk8_batch_ok = False
        parsed_rqc_1jk8_lot: str | None = None
        tmp_ref_1jk8: set[str] = set()
        if "crystal_ref_1jk8_14aa" in rqc and rqc["crystal_ref_1jk8_14aa"] is not None:
            r1jk8_present = True
            derived_summary["optional_1jk8_physical_control_present"] = True
            r1jk8_rec = rqc["crystal_ref_1jk8_14aa"]
            if (
                not isinstance(r1jk8_rec, dict)
                or r1jk8_rec.get("sequence") != "LVEALYLVCGERGG"
                or r1jk8_rec.get("qc_passed") is not True
            ):
                _escalate(
                    "HOLD_INVALID_OR_MISSING_INPUT",
                    "Optional 14-aa PDB 1JK8 physical control was supplied but failed sequence (LVEALYLVCGERGG) or qc_passed validation",
                )
                if isinstance(r1jk8_rec, dict) and "peptide_reagent_lot_id" in r1jk8_rec:
                    raw_rqc_1jk8_lot = r1jk8_rec["peptide_reagent_lot_id"]
                    if (
                        type(raw_rqc_1jk8_lot) is str
                        and bool(raw_rqc_1jk8_lot)
                        and raw_rqc_1jk8_lot == raw_rqc_1jk8_lot.strip()
                        and bool(_SHIELD_STRICT_ID_RE.match(raw_rqc_1jk8_lot))
                    ):
                        parsed_rqc_1jk8_lot = raw_rqc_1jk8_lot
            else:
                r1jk8_metrics_ok = True
                if "peptide_reagent_lot_id" in r1jk8_rec:
                    raw_rqc_1jk8_lot = r1jk8_rec["peptide_reagent_lot_id"]
                    if (
                        type(raw_rqc_1jk8_lot) is not str
                        or not raw_rqc_1jk8_lot
                        or raw_rqc_1jk8_lot != raw_rqc_1jk8_lot.strip()
                        or not _SHIELD_STRICT_ID_RE.match(raw_rqc_1jk8_lot)
                    ):