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…

    def _extract_scope_field(rec_d: Dict[str, Any], sc_d: Dict[str, Any], names: Tuple[str, ...]) -> Any:
        for k in names:
            if k in sc_d and sc_d[k] is not None:
                return sc_d[k]
        for k in names:
            if k in rec_d and rec_d[k] is not None:
                return rec_d[k]
        return None

    records_by_scope: Dict[Tuple[str, str, str], List[Tuple[Tuple[Any, ...], Dict[str, Any], bool, str | None]]] = {}
    incomplete_scope_records: List[Dict[str, Any]] = []
    ambiguous_scope_records: List[Dict[str, Any]] = []
    has_unattributable_malformed = False
    has_ambiguous_scope = False

    for idx, record in sorted(enumerate(records), key=_replay_sort_key):
        if not isinstance(record, dict):
            has_unattributable_malformed = True
            continue
        scope_is_malformed = "scope" in record and not isinstance(record["scope"], dict)
        sc = record["scope"] if isinstance(record.get("scope"), dict) else {}
        mol = record["iip0026_molecular_observations"] if isinstance(record.get("iip0026_molecular_observations"), dict) else {}
        if _conflicting_stage0_batch_scope(record, wc_helper, root_path):
            has_ambiguous_scope = True
            ambiguous_scope_records.append(record)
            continue
        raw_product = _extract_scope_field(record, sc, ("product_variant_id",))
        lot = _extract_scope_field(record, sc, ("lot_id", "current_lot_id"))
        campaign = _extract_scope_field(record, sc, ("campaign_id", "assay_campaign_id"))
        if not all(isinstance(v, str) and v.strip() for v in (raw_product, lot, campaign)):
            has_unattributable_malformed = True
            incomplete_scope_records.append(record)
            continue
        canonical_product, _ = wc_helper._canonicalize_product_id_iip0031(raw_product, root_path)
        scope_key = (canonical_product or raw_product.strip(), lot.strip(), campaign.strip())
        r_arm = sc.get(
            "adjunct_conditioning_history_arm",
            mol.get("adjunct_conditioning_history_arm", record.get("adjunct_conditioning_history_arm")),
        )
        arm_str = r_arm.strip() if isinstance(r_arm, str) and r_arm.strip() else None
        raw_seq = record.get("seq_index", idx)
        seq_i = raw_seq if (type(raw_seq) is int) else idx
        logical_tk = (_parse_replay_timestamp_iip0031(record.get("utc_timestamp")), seq_i)
        records_by_scope.setdefault(scope_key, []).append((logical_tk, record, scope_is_malformed, arm_str))

    # Evaluate incomplete-scope records independently (order-independent, non-overwriting S9 latch):
    incomplete_s9_eval: Dict[str, Any] | None = None
    incomplete_pvids: set[str] = set()
    incomplete_base_doc: Dict[str, Any] | None = None
    allowed_mol_inc = getattr(wc_helper, "IIP0026_ALLOWED_MOLECULAR_OBS_KEYS")
    bool_flags_inc = set(getattr(wc_helper, "STAGE0_DECISION_TREE_BOOLEAN_KEYS", ()))
    for inc_rec in incomplete_scope_records:
        inc_san, _, _ = _sanitize_stage0_envelope_iip0031(inc_rec)
        inc_ev = wc_helper.evaluate_stage0_product_contract(inc_san, root=root)
        sc_i = inc_san.get("scope") if isinstance(inc_san.get("scope"), dict) else {}
        rp_i = _extract_scope_field(inc_san, sc_i, ("product_variant_id",))
        if isinstance(rp_i, str) and rp_i.strip():
            cp_i, _ = wc_helper._canonicalize_product_id_iip0031(rp_i, root_path)
            incomplete_pvids.add(cp_i or rp_i.strip())
            if incomplete_base_doc is None:
                incomplete_base_doc = {
                    "product_variant_id": cp_i or rp_i.strip(),
                    "lot_id": _extract_scope_field(inc_san, sc_i, ("lot_id", "current_lot_id")),
                    "campaign_id": _extract_scope_field(inc_san, sc_i, ("campaign_id", "assay_campaign_id")),
                }
            flat_mf = {k: v for k, v in inc_san.items() if isinstance(k, str) and k.startswith("obs_") and v is not None}
            raw_mf = inc_san.get("measurements")
            merged_mf = {**flat_mf, **(raw_mf if isinstance(raw_mf, dict) else {})}
            if merged_mf:
                incomplete_base_doc.update(_extract_stage0_batch_measurements_preserving_explicit_se_iip0026(merged_mf, wc_helper))
            mol_f = inc_san.get("iip0026_molecular_observations")
            for src_inc_m in (inc_san, sc_i, mol_f if isinstance(mol_f, dict) else {}):
                for mk_f, mv_f in src_inc_m.items():
                    if isinstance(mk_f, str) and (mk_f in allowed_mol_inc or mk_f in bool_flags_inc) and mv_f is not None:
                        incomplete_base_doc[mk_f] = mv_f
        if (
            inc_ev.get("overall_status") == "HARD_SAFETY_STOP_REJECTED"
            and inc_ev.get("hard_stop_precedence_winner") == "S9_HARD_SAFETY_STOP"
            and incomplete_s9_eval is None
        ):
            incomplete_s9_eval = dict(inc_ev)

    if not records_by_scope:
        if incomplete_s9_eval is not None:
            if has_ambiguous_scope and "FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING" not in incomplete_s9_eval.get("iip0026_reasons", []):
                incomplete_s9_eval["iip0026_reasons"] = [*incomplete_s9_eval.get("iip0026_reasons", []), "FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING"]
            return incomplete_s9_eval
        if has_ambiguous_scope:
            p_mod = wc_helper._load_product_contract_module(root_path)
            prod_by_id = {str(p["product_variant_id"]): p for p in p_mod.load_product_contracts(root_path)["products"]}
            reg_state_amb = "UNREGISTERED"
            for amb_r in ambiguous_scope_records:
                sc_amb = amb_r.get("scope") if isinstance(amb_r.get("scope"), dict) else {}
                rp_amb = _extract_scope_field(amb_r, sc_amb, ("product_variant_id",))
                if isinstance(rp_amb, str) and rp_amb.strip():
                    cp_amb, _ = wc_helper._canonicalize_product_id_iip0031(rp_amb, root_path)
                    if cp_amb and str(cp_amb) in prod_by_id:
                        reg_state_amb = wc_helper._derive_versioned_product_registry_entry_iip0026(prod_by_id[str(cp_amb)])["lifecycle_state"]
                        break
            empty_s0 = wc_helper.evaluate_stage0_decision_tree({}, root=root)
            return {
                "overall_status": "FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING",
                "lot_release_readiness_tier": "FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING",
                "iip0026_reasons": ["FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING"],
                "hard_stop_precedence_winner": None,
                "lifecycle_state": reg_state_amb,
                "execution_supported": False,
                "effective_execution_permitted": False,
                "switch_decisions": empty_s0["switch_decisions"],
            }
        if len(incomplete_pvids) == 1 and incomplete_base_doc is not None:
            return wc_helper.evaluate_stage0_product_contract(incomplete_base_doc, root=root)
        return wc_helper.evaluate_stage0_product_contract({}, root=root)

    all_arms: set[str] = {
        arm_str
        for items in records_by_scope.values()
        for _, _, _, arm_str in items
        if arm_str is not None
    }
    has_cross_arm = len(all_arms) > 1
    has_cross_scope = (len(records_by_scope) > 1) or has_ambiguous_scope

    # Build exact `(scope_key, arm_key)` partitions (only splitting by arm when multiple conditioning arms appear):
    partitions: List[Tuple[Tuple[str, str, str], str | None, List[Tuple[Tuple[Any, ...], Dict[str, Any], bool]]]] = []
    for scope_key, items in records_by_scope.items():
        scope_arms = {arm_str for _, _, _, arm_str in items if arm_str is not None}
        if len(scope_arms) > 1:
            by_arm: Dict[str | None, List[Tuple[Tuple[Any, ...], Dict[str, Any], bool]]] = {}
            for tk, rec, sm, arm_str in items:
                by_arm.setdefault(arm_str, []).append((tk, rec, sm))
            for arm_k, arm_items in by_arm.items():
                partitions.append((scope_key, arm_k, arm_items))
        else:
            only_arm = next(iter(scope_arms)) if scope_arms else None
            partitions.append((scope_key, only_arm, [(tk, rec, sm) for tk, rec, sm, _ in items]))

    # Fast single-scope, single-arm, unambiguous path:
    if len(partitions) == 1 and not has_cross_scope and not has_cross_arm:
        scope_key, _, part_items = partitions[0]
        single_out = _replay_single_scope_iip0031(
            scope_key,
            part_items,
            has_external_malformed=has_unattributable_malformed,
            root=root,
            root_path=root_path,
            wc_helper=wc_helper,
        )
        if incomplete_s9_eval is not None and _hard_stop_rank_iip0031(single_out) > 0:
            single_out["overall_status"] = "HARD_SAFETY_STOP_REJECTED"
            single_out["lot_release_readiness_tier"] = "HARD_SAFETY_STOP_REJECTED"
            single_out["hard_stop_precedence_winner"] = "S9_HARD_SAFETY_STOP"
            if "HARD_SAFETY_STOP_S9" not in single_out.get("iip0026_reasons", []):
                single_out["iip0026_reasons"] = ["HARD_SAFETY_STOP_S9", *single_out.get("iip0026_reasons", [])]
            single_out["execution_supported"] = False
            single_out["effective_execution_permitted"] = False
        return single_out

    # Multi-scope / multi-arm / ambiguous-peer replay: evaluate each attributable partition independently
    # so cross-scope/cross-arm rejection NEVER erases an independently attributable hard safety stop:
    partition_evals: List[Tuple[Tuple[str, str, str], str | None, Dict[str, Any]]] = []
    for scope_key, arm_k, part_items in partitions:
        p_eval = _replay_single_scope_iip0031(
            scope_key,
            part_items,
            has_external_malformed=False,
            root=root,
            root_path=root_path,
            wc_helper=wc_helper,
        )
        partition_evals.append((scope_key, arm_k, p_eval))

    adverse_parts = [
        (scope_key, arm_k, ev)
        for scope_key, arm_k, ev in partition_evals
        if _is_hard_stop_result_iip0031(ev)
    ]
    if adverse_parts or incomplete_s9_eval is not None:
        if incomplete_s9_eval is not None and (not adverse_parts or min(_hard_stop_rank_iip0031(ev) for _, _, ev in adverse_parts) > 0):
            best_eval = dict(incomplete_s9_eval)
        else:
            adverse_parts.sort(key=lambda item: (_hard_stop_rank_iip0031(item[2]), item[0], item[1] or ""))
            best_eval = dict(adverse_parts[0][2])
        reasons = list(best_eval.get("iip0026_reasons", []))
        if has_cross_arm and "FAIL_CROSS_CONDITIONING_ARM_REPLAY_MIXING" not in reasons:
            reasons.append("FAIL_CROSS_CONDITIONING_ARM_REPLAY_MIXING")
        if has_cross_scope and "FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING" not in reasons:
            reasons.append("FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING")
        best_eval["iip0026_reasons"] = reasons
        best_eval["scoped_adverse_events"] = [
            {
                "product_variant_id": sk[0],
                "lot_id": sk[1],
                "campaign_id": sk[2],
                "adjunct_conditioning_history_arm": ak,
                "overall_status": ev.get("overall_status"),
                "hard_stop_precedence_winner": ev.get("hard_stop_precedence_winner"),
            }
            for sk, ak, ev in adverse_parts
        ]
        best_eval["execution_supported"] = False
        best_eval["effective_execution_permitted"] = False
        return best_eval

    # No partition had an independent hard safety stop -> return deterministic cross-arm or cross-scope rejection:
    first_pid = next(iter(records_by_scope.keys()))[0]
    p_mod = wc_helper._load_product_contract_module(root_path)
    prod_by_id = {str(p["product_variant_id"]): p for p in p_mod.load_product_contracts(root_path)["products"]}
    reg_state = (
        wc_helper._derive_versioned_product_registry_entry_iip0026(prod_by_id[str(first_pid)])["lifecycle_state"]
        if str(first_pid) in prod_by_id
        else "UNREGISTERED"
    )
    empty_s0 = wc_helper.evaluate_stage0_decision_tree({}, root=root)
    mix_code = "FAIL_CROSS_CONDITIONING_ARM_REPLAY_MIXING" if has_cross_arm else "FAIL_CROSS_LOT_OR_CAMPAIGN_REPLAY_MIXING"
    return {
        "overall_status": mix_code,
        "lot_release_readiness_tier": mix_code,
        "iip0026_reasons": [mix_code],
        "hard_stop_precedence_winner": None,
        "lifecycle_state": reg_state,
        "execution_supported": False,
        "effective_execution_permitted": False,
        "switch_decisions": empty_s0["switch_decisions"],
    }


def main() -> None:
    parser = argparse.ArgumentParser(description="Ingest wet-lab JSON readouts to update OpenIslet Bayesian priors.")
    parser.add_argument("--input-json", type=str, default="", help="Path to empirical wet-lab readout JSON")
    parser.add_argument("--prior-posterior-json", type=str, default="", help="Optional prior posterior JSON for sequential Bayesian updating")
    parser.add_argument(
        "--dry-run-calibration",
        "--synthetic-dry-run",
        dest="dry_run_calibration",
        action="store_true",
        help="Run synthetic dry-run pipeline verification",
    )
    parser.add_argument("--output", type=str, default=str(DEFAULT_OUT), help="Output JSON path")
    parser.add_argument(
        "--no-write",
        action="store_true",
        help="Validate and compute calibration report in-memory without writing output files to disk",
    )
    parser.add_argument(
        "--force-overwrite-empirical",
        action="store_true",
        help="Allow a synthetic dry-run to overwrite an existing EMPIRICAL_WETLAB_INGESTION artifact",
    )