OpenIslet

scripts/ingest_wetlab_results.py

Closed-Loop Wet-Lab Results Ingestor & Bayesian Posterior Updater (`scripts/ingest_wetlab_results.py`, v0.8.0)

script Release v0.8.0 gen-eb955f8266035aba 228 KB · 18 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/ingest_wetlab_results.py · SHA-256: e050593675170515…

        "obs_post_edit_segmented_baf_chr19q",
        "obs_post_edit_segmented_baf_chr11p15",
        "obs_post_edit_segmented_baf_chr6p21",
    })
    mol_excl_replay = all_s9_rep_keys | all_alias_keys | frozenset({
        "tier6b_sorted_lot_observations",
        "iip0031_locus2_record",
        "iip0029_twoclock_record",
    })

    accum: Dict[str, Any] = {
        "product_variant_id": s_pid,
        "lot_id": s_lot,
        "campaign_id": s_camp,
    }
    accum_tier6b_obs: list[Any] = []
    has_any_tier6b_field = False
    if has_external_malformed:
        has_any_tier6b_field = True
        accum_tier6b_obs.append(None)
        accum["tier6b_sorted_lot_observations"] = list(accum_tier6b_obs)

    latched_other_fails: list[str] = []
    latched_s9_hard_stop = False
    latched_tier6b_hard_stop = False
    latched_tier6b_eval: Dict[str, Any] | None = None
    s11_fail_records: List[Tuple[Tuple[Any, ...], Dict[str, Any]]] = []
    latched_switch_decisions: Dict[str, Any] | None = None
    locked_iip0029_source_fp: tuple[Any, ...] | None = None
    locked_iip0029_flat_clocks: Dict[str, Any] = {}
    latched_iip0029_store_gt_138p3 = False
    latched_iip0029_alk5i_continued = False
    malformed_replay = bool(has_external_malformed)
    latched_s9_rep_conflict = False
    latched_meas_conflict = False

    def _add_other_fail(code: str) -> None:
        if code.startswith("FAIL_") and not code.startswith("FAIL_S11_") and code != "FAIL_TIER6B_OUTGROWTH_DETECTED":
            if code not in latched_other_fails:
                latched_other_fails.append(code)

    immutable_lot_keys = (
        "construct_sha256",
        "background_id",
        "donor_seedline_id",
        "seed_line_id",
        "mcb_id",
        "l2_v3_donor_id",
        "donor_id",
    )
    per_record_meta_keys = (
        "scope_type",
        "sample_id",
        "sample_unit_id",
        "device_assembly_id",
        "schema_era",
        "iip0026_schema_era",
    )

    for logical_tk, rec, scope_is_malformed in scoped_items:
        rec_san, bad_struct_names, had_nf = _sanitize_stage0_envelope_iip0031(rec)
        if rec.get("malformed_record") is True or scope_is_malformed or bad_struct_names or had_nf:
            malformed_replay = True
            has_any_tier6b_field = True
            accum_tier6b_obs.append(None)
            accum["tier6b_sorted_lot_observations"] = list(accum_tier6b_obs)

        sc = rec_san.get("scope") if isinstance(rec_san.get("scope"), dict) else {}
        mol = rec_san.get("iip0026_molecular_observations") if isinstance(rec_san.get("iip0026_molecular_observations"), dict) else {}
        raw_m_dict = rec_san.get("measurements") if isinstance(rec_san.get("measurements"), dict) else {}

        # Reconcile immutable lot-level provenance keys from BOTH nested `scope` and flat record:
        rec_has_immutable_conflict = False
        for ik in immutable_lot_keys:
            vals_ik = []
            if ik in sc and sc[ik] is not None:
                vals_ik.append(sc[ik])
            if ik in rec_san and rec_san[ik] is not None:
                vals_ik.append(rec_san[ik])
            for iv in vals_ik:
                if not isinstance(iv, str) or not iv.strip():
                    malformed_replay = True
                    continue
                if ik in accum and accum[ik] != iv:
                    rec_has_immutable_conflict = True
                    if ik == "construct_sha256":
                        _add_other_fail("FAIL_IIP0029_IMMUTABLE_SOURCE_OR_THRESHOLD_REPLACEMENT_DETECTED")
                    else:
                        _add_other_fail("FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING")
                elif ik not in accum:
                    accum[ik] = iv

        # Check per-record / per-specimen metadata without letting malformed fields poison later records:
        for mk in per_record_meta_keys:
            for src_m in (sc, rec_san):
                if mk in src_m and src_m[mk] is not None:
                    mv = src_m[mk]
                    if not isinstance(mv, str) or not mv.strip():
                        malformed_replay = True
                    else:
                        accum[mk] = mv

        # Build an isolated per-record evaluation document carrying valid lot provenance + THIS record's own fields:
        rec_eval_doc = dict(rec_san)
        rec_eval_scope = dict(sc) if isinstance(rec_san.get("scope"), dict) else {}
        rec_eval_scope.setdefault("product_variant_id", s_pid)
        rec_eval_scope.setdefault("lot_id", s_lot)
        rec_eval_scope.setdefault("campaign_id", s_camp)
        if not rec_has_immutable_conflict:
            for ik in immutable_lot_keys:
                if ik in accum and ik not in rec_eval_scope and ik not in rec_eval_doc:
                    rec_eval_scope[ik] = accum[ik]
        if isinstance(rec_san.get("scope"), dict):
            rec_eval_doc["scope"] = rec_eval_scope
        else:
            for k_s, v_s in rec_eval_scope.items():
                rec_eval_doc.setdefault(k_s, v_s)

        rec_eval = wc_helper.evaluate_stage0_product_contract(rec_eval_doc, root=root)
        if (
            rec_eval.get("overall_status") == "HARD_SAFETY_STOP_REJECTED"
            and rec_eval.get("hard_stop_precedence_winner") == "S9_HARD_SAFETY_STOP"
        ):
            latched_s9_hard_stop = True
            latched_switch_decisions = dict(rec_eval["switch_decisions"])
        if (
            rec_eval.get("tier6b_disposition") == "FAIL_HARD_STOP"
            or rec_eval.get("hard_stop_precedence_winner") == "FAIL_TIER6B_OUTGROWTH_DETECTED"
        ):
            latched_tier6b_hard_stop = True
            if isinstance(rec_eval.get("tier6b_sorted_lot_evaluation"), dict):
                latched_tier6b_eval = dict(rec_eval["tier6b_sorted_lot_evaluation"])
        rec_s11 = rec_eval.get("s11_evaluation")
        if isinstance(rec_s11, dict) and str(rec_s11.get("status", "")).startswith("FAIL_"):
            s11_fail_records.append((logical_tk, dict(rec_s11)))
        for r_code in rec_eval.get("iip0026_reasons", []):
            _add_other_fail(str(r_code))

        # Replicate counts across all 4 sanitized containers:
        _rec_s9_containers = (raw_m_dict, sc, rec_san, mol)
        _rec_s9_resolved, _rec_s9_conflict_groups, _rec_s9_any_conflict = wc_helper._resolve_s9_replicate_counts_detailed_iip0031(
            _rec_s9_containers,
            flag_explicit_none=True,
        )
        if _rec_s9_any_conflict:
            latched_s9_rep_conflict = True
            accum["_s9_replicate_count_conflict"] = True

        # A replacement assay carries its own uncertainty and depth; skip mutating S9 accum on immutable conflict:
        if not rec_has_immutable_conflict:
            _rec_s9_all_ctrs = (rec_san, sc, mol, raw_m_dict)
            s9_se_keys = {
                r[1]: r[2]
                for r in wc_helper.STAGE0_DECISION_TREE_ENDPOINT_SPECS
                if r[1] in wc_helper.S9_CORE_LOT_ENDPOINT_IDS
            }
            for eid, se_key in s9_se_keys.items():
                n_keys = wc_helper.S9_REPLICATE_KEYS[eid]
                assay_keys = (eid, se_key, *wc_helper.S9_FREQUENCY_ASSAY_KEYS.get(eid, ()))
                if any(any(key in _c for _c in _rec_s9_all_ctrs) for key in (*assay_keys, *n_keys)):
                    for key in (*assay_keys, *n_keys):
                        if not any(key in _c and _c[key] is not None and _c[key] != "UNAVAILABLE" for _c in _rec_s9_all_ctrs):
                            accum.pop(key, None)
                    if _rec_s9_resolved.get(eid) is not None:
                        accum[n_keys[0]] = _rec_s9_resolved[eid]
                    elif not any(any(key in _c for _c in _rec_s9_all_ctrs) for key in n_keys):
                        accum[n_keys[0]] = _rec_s9_resolved["default"] if _rec_s9_resolved.get("default") is not None else 6
            if _rec_s9_any_conflict:
                for _rk in all_s9_rep_keys:
                    accum.pop(_rk, None)
                for _grp, _grp_keys in wc_helper.S9_REPLICATE_KEYS.items():
                    if _rec_s9_resolved.get(_grp) is not None:
                        accum[_grp_keys[0]] = _rec_s9_resolved[_grp]
            else:
                for _grp, _grp_keys in wc_helper.S9_REPLICATE_KEYS.items():
                    if any(_rk in _src_nr and _src_nr[_rk] is not None for _rk in _grp_keys for _src_nr in _rec_s9_containers):
                        for _rk in _grp_keys:
                            accum.pop(_rk, None)
                        for _nk_r in _grp_keys:
                            for _src_nr in _rec_s9_containers:
                                if _nk_r in _src_nr and _src_nr[_nk_r] is not None:
                                    accum[_nk_r] = _src_nr[_nk_r]
                                    break

        for k, v in {**rec_san, **sc, **mol}.items():
            if isinstance(k, str) and (
                (k in forbidden_ovr) or k.endswith("_lifecycle_state") or k.endswith("_execution_supported")
            ):
                accum[k] = v

        # Reconcile Design B, TYK2, and BAF aliases identically across all 4 containers:
        _r_clean_aliases, _, _r_clean_baf, _, _r_alias_conflict = wc_helper._reconcile_iip0026_aliases_and_baf_iip0031(
            (rec_san, sc, raw_m_dict, mol)
        )
        if _r_alias_conflict:
            latched_meas_conflict = True
            accum["_stage0_conflicting_measurement"] = True
        if _r_clean_aliases:
            accum.update(_r_clean_aliases)
        if _r_clean_baf is not None:
            existing_baf = accum.get("post_edit_per_locus_segmented_baf")
            merged_baf = dict(existing_baf) if isinstance(existing_baf, dict) else {}
            merged_baf.update(_r_clean_baf)
            accum["post_edit_per_locus_segmented_baf"] = merged_baf

        # Merge non-alias obs_* and molecular observations into cumulative `accum`:
        flat_m_all = {k: v for k, v in rec_san.items() if isinstance(k, str) and k.startswith("obs_") and k not in all_s9_rep_keys and k not in all_alias_keys}
        raw_m_obs_all = {k: v for k, v in raw_m_dict.items() if isinstance(k, str) and k.startswith("obs_") and k not in all_s9_rep_keys and k not in all_alias_keys}
        sc_m_all = {k: v for k, v in sc.items() if isinstance(k, str) and k.startswith("obs_") and k not in all_s9_rep_keys and k not in all_alias_keys}
        mol_m_all = {k: v for k, v in mol.items() if isinstance(k, str) and k.startswith("obs_") and k not in all_s9_rep_keys and k not in all_alias_keys}
        non_obs_raw_m = {
            k: v
            for k, v in raw_m_dict.items()
            if isinstance(k, str)
            and not k.startswith("obs_")
            and k not in mol_excl_replay
            and k not in allowed_mol
            and k not in bool_flags
        }
        clean_m_rec, meas_probes_rec, has_m_conflict_rec = wc_helper._merge_stage0_container_fields_iip0031(
            (flat_m_all, raw_m_obs_all, sc_m_all, mol_m_all),
            excluded_keys=all_s9_rep_keys | all_alias_keys,
            key_predicate=lambda k: k.startswith("obs_"),
        )
        all_rec_obs_keys = set(flat_m_all) | set(raw_m_obs_all) | set(sc_m_all) | set(mol_m_all)
        if not rec_has_immutable_conflict:
            for _obs_k in all_rec_obs_keys:
                if _obs_k not in clean_m_rec:
                    accum.pop(_obs_k, None)

        def _is_mol_key_replay(k: str) -> bool:
            return (k in allowed_mol or k in bool_flags) and not k.startswith("obs_") and k not in mol_excl_replay

        flat_mol_r = {k: v for k, v in rec_san.items() if isinstance(k, str) and _is_mol_key_replay(k)}
        nested_mol_r = {k: v for k, v in mol.items() if isinstance(k, str) and _is_mol_key_replay(k)}
        sc_mol_r = {k: v for k, v in sc.items() if isinstance(k, str) and _is_mol_key_replay(k)}
        meas_mol_r = {k: v for k, v in raw_m_dict.items() if isinstance(k, str) and _is_mol_key_replay(k)}
        clean_mol_rec, mol_probes_rec, has_mol_conflict_rec = wc_helper._merge_stage0_container_fields_iip0031(
            (flat_mol_r, nested_mol_r, sc_mol_r, meas_mol_r),
            excluded_keys=mol_excl_replay,
            key_predicate=_is_mol_key_replay,
        )
        all_rec_mol_keys = set(flat_mol_r) | set(nested_mol_r) | set(sc_mol_r) | set(meas_mol_r)
        for _mol_k in all_rec_mol_keys:
            if _mol_k not in clean_mol_rec:
                accum.pop(_mol_k, None)

        if has_m_conflict_rec or has_mol_conflict_rec:
            latched_meas_conflict = True
            accum["_stage0_conflicting_measurement"] = True