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…

        "s6_cluster_size_arm",
        "p05_barrier_slab_geometry_mode",
        "design_z_divider_arm",
        "p05_catalase_uniprot_accession",
        "cuff_bioconjugation_arm",
        "cuff_serum_challenge_stratum",
        "rest_ocr_coupon_arm",
        "conditioning_4arm_arm",
        "conditioning_washout_analyte_scope",
        "track2_rescue_route",
        "design_y_integrase_modality",
        "design_y_silencing_modality",
        "design_y_payload_arm",
        "contrast_b1_geometry_arm",
        "contrast_b2_perfusion_and_retrieval_arm",
        "contrast_b3_donor_iec_arm",
        "bound_c1_c5_pair_sha256",
        "tyk2_pe_modality",
        "iip0026_schema_era",
        "recipient_serum_pair_id",
        "intact_serum_sample_id",
        "igg_depleted_serum_sample_id",
        "positive_adcc_control_id",
        "isotype_adcc_control_id",
        "arm2_depleted_sample_id",
        "contemporaneous_arm3_control_sample_id",
        "sister_assembly_id",
        "cxcl10_tss_donor_id",
        "cxcl10_tss_transcription_unit_id",
        *stage0_persisted_boolean_flags,
    ):
        if qp_meta_k in input_payload and input_payload[qp_meta_k] is not None:
            current_obs_entry[qp_meta_k] = input_payload[qp_meta_k]
    if require_full_5endpoint_s9_panel is True:
        current_obs_entry["require_full_5endpoint_s9_panel"] = True
    if batch_specimen_map:
        current_obs_entry["specimen_or_clone_ids"] = batch_specimen_map

    # Pool historical Stage-0 endpoint observations across chained batches and latch any prior S9 hard safety stop, cross-clone pooling mismatch, cross-lot/device provenance isolation, or uninvestigated non-S9 OOS overwrite (AUDIT-REF & IIP-0024; DEC-041/043/044/047/050/103):
    pooled_stage0_payload: Dict[str, Any] = {}
    pooled_defaulted_se_set: set[str] = set()
    prior_sticky_s9 = False
    stop_required_mcb_clonogenic_clearance = False
    stop_required_5endpoint_er_clearance = False
    stop_required_s9_categories: set[str] = set()
    prior_s9_history_retained_across_ledger = False
    post_stop_passing_s9_batch_ids: list[str] = []
    seen_mcb_clone_ids: set[str] = set()
    any_batch_omitted_mcb_clone_id = False
    prior_failed_stage0_gate_keys: set[str] = set()
    uninvestigated_non_s9_oos_overwrite_hold = False
    active_pooled_lot_id: str | None = None
    active_pooled_device_id: str | None = None
    cross_lot_invalidated_keys: set[str] = set()
    s9_3_endpoint_keys = {
        "obs_icasp9_log10_kill",
        "obs_icasp9_log10_kill_se",
        "obs_tp53_ppm1d_bcor_vaf",
        "obs_tp53_ppm1d_bcor_vaf_se",
        "obs_castseq_translocation_freq",
        "obs_castseq_translocation_se",
    }
    se_to_mean_lookup = {
        **{
            se_k: mean_k
            for _eid, _pm0, _psd0, mean_k, se_k, _lo, _hi, _u in ENDPOINT_SPECS
        },
        **{
            se_k: mean_k
            for _eid, _pm0, _psd0, mean_k, se_k, _dse, _lo, _hi, _u in EXTENDED_STAGE0_STAGE1_SPECS
        },
        **{
            se_k: mean_k
            for _eid, mean_k, se_k, _lo, _hi, _u in _get_stage0_decision_tree_specs()
        },
    }
    for hist_idx, hist_entry in enumerate(prev_obs_ledger):
        if isinstance(hist_entry.get("mcb_clone_id"), str) and hist_entry["mcb_clone_id"].strip():
            seen_mcb_clone_ids.add(hist_entry["mcb_clone_id"].strip())
        else:
            any_batch_omitted_mcb_clone_id = True
        hist_lot_id = _clean_optional_id_str(hist_entry.get("current_lot_id"))
        hist_dev_id = _clean_optional_id_str(hist_entry.get("device_assembly_id"))
        if hist_idx > 0 and (active_pooled_lot_id is not None or hist_lot_id is not None) and hist_lot_id != active_pooled_lot_id:
            post_stop_passing_s9_batch_ids.clear()
        active_pooled_lot_id, active_pooled_device_id = _apply_provenance_scope_isolation(
            pooled_stage0_payload,
            pooled_defaulted_se_set,
            prev_lot_id=active_pooled_lot_id,
            new_lot_id=hist_lot_id,
            prev_device_id=active_pooled_device_id,
            new_device_id=hist_dev_id,
            is_subsequent_batch=(hist_idx > 0),
            invalidated_keys=cross_lot_invalidated_keys,
            prior_failed_noncore_keys=prior_failed_stage0_gate_keys,
        )
        hist_meas = dict(hist_entry.get("measurements") or {})
        for bf_k in stage0_persisted_boolean_flags:
            if bf_k in hist_entry and hist_entry[bf_k] is not None:
                if type(hist_entry[bf_k]) is not bool:
                    raise ValueError(
                        f"{bf_k} must be a boolean when provided in ordered_batch_observation_ledger (R7S2-F02; DEC-057)"
                    )
                hist_meas[bf_k] = hist_entry[bf_k]
        hist_def_se = set(hist_entry.get("defaulted_se_keys") or [])
        hist_stage0_noncore_keys = {
            k for k, v in hist_meas.items()
            if k not in s9_3_endpoint_keys and not k.endswith("_se") and v not in ("UNAVAILABLE", None)
        }
        if hist_stage0_noncore_keys & prior_failed_stage0_gate_keys:
            if not (
                hist_entry.get("oos_retest_investigation_approved") is True
                and isinstance(hist_entry.get("oos_retest_assignable_cause_code"), str)
                and hist_entry["oos_retest_assignable_cause_code"].strip()
            ):
                uninvestigated_non_s9_oos_overwrite_hold = True
            else:
                prior_failed_stage0_gate_keys -= hist_stage0_noncore_keys
        _drop_unpaired_rare_event_members(pooled_stage0_payload, hist_meas)
        _merge_batch_measurements_atomic_mean_se(
            pooled_stage0_payload,
            pooled_defaulted_se_set,
            hist_meas,
            hist_def_se,
            se_to_mean_lookup,
        )
        for meta_k in (
            "product_variant_id",
            "estimand_scale",
            "donor_seedline_id",
            "device_assembly_id",
            "physical_route_id",
            "assay_campaign_id",
            "adjunct_conditioning_history_arm",
            "adjunct_depletion_mode",
            "adjunct_sa_fhl1_status",
            "adjunct_immune_responder_history",
            "knockin_splice_challenger_arm",
            "knockin_locus4_orientation",
            "s10_construct_id",
            "s10_construct_donor_sha256",
            "current_lot_id",
            "s10_qualified_lot_id",
            "s10_hlae_floor_mode",
            "b2_tyk2_recipient_genotype_stratum",
            "b2_tyk2_hlac_allele",
            "s6_cluster_size_arm",
            "p05_barrier_slab_geometry_mode",
            "design_z_divider_arm",
            "p05_catalase_uniprot_accession",
            "cuff_bioconjugation_arm",
            "cuff_serum_challenge_stratum",
            "rest_ocr_coupon_arm",
            "conditioning_4arm_arm",
            "conditioning_washout_analyte_scope",
            "track2_rescue_route",
            "design_y_integrase_modality",
            "design_y_silencing_modality",
            "design_y_payload_arm",
            "contrast_b1_geometry_arm",
            "contrast_b2_perfusion_and_retrieval_arm",
            "contrast_b3_donor_iec_arm",
            "bound_c1_c5_pair_sha256",
            "tyk2_pe_modality",
            "iip0026_schema_era",
            "recipient_serum_pair_id",
            "intact_serum_sample_id",
            "igg_depleted_serum_sample_id",
            "positive_adcc_control_id",
            "isotype_adcc_control_id",
            "arm2_depleted_sample_id",
            "contemporaneous_arm3_control_sample_id",
            "sister_assembly_id",
            "cxcl10_tss_donor_id",
            "cxcl10_tss_transcription_unit_id",
        ):
            if hist_entry.get(meta_k) is not None:
                pooled_stage0_payload[meta_k] = hist_entry[meta_k]
                # Preserve product_variant_id and estimand_scale in per-batch historical Stage-0 replay (IIP-0026; DEC-105):
                hist_meas[meta_k] = hist_entry[meta_k]
        if hist_entry.get("s8b_epistasis_estimand_scale") is not None:
            pooled_stage0_payload["s8b_epistasis_estimand_scale"] = hist_entry["s8b_epistasis_estimand_scale"]
        else:
            pooled_stage0_payload.pop("s8b_epistasis_estimand_scale", None)
        if "obs_beta_x1_x4_epistasis" in hist_meas and hist_meas.get("obs_beta_x1_x4_epistasis") not in ("UNAVAILABLE", None):
            ep_sc_14 = hist_entry.get("obs_beta_x1_x4_epistasis_scale") or hist_entry.get("s8b_epistasis_estimand_scale")
            if ep_sc_14 is not None:
                pooled_stage0_payload["obs_beta_x1_x4_epistasis_scale"] = ep_sc_14
            else:
                pooled_stage0_payload.pop("obs_beta_x1_x4_epistasis_scale", None)
        if "obs_beta_x3_x4_epistasis" in hist_meas and hist_meas.get("obs_beta_x3_x4_epistasis") not in ("UNAVAILABLE", None):
            ep_sc_34 = hist_entry.get("obs_beta_x3_x4_epistasis_scale") or hist_entry.get("s8b_epistasis_estimand_scale")
            if ep_sc_34 is not None:
                pooled_stage0_payload["obs_beta_x3_x4_epistasis_scale"] = ep_sc_34
            else:
                pooled_stage0_payload.pop("obs_beta_x3_x4_epistasis_scale", None)
        single_hist_s0 = evaluate_stage0_decision_tree(
            dict(hist_meas),
            defaulted_se_keys=sorted(hist_def_se),
            prior_batch_sticky_s9_safety_stop=False,
        )
        single_hist_mat_status = str(single_hist_s0.get("resolved_architecture_assignments", {}).get("lot_maturation_status", ""))
        if (
            single_hist_s0.get("any_fallback_switch_triggered") is True
            or single_hist_s0.get("primary_biological_or_pouch_gate_failed") is True
            or single_hist_mat_status.startswith("NO_GO_")
            or (
                single_hist_mat_status.startswith("HOLD_")
                and single_hist_mat_status not in ("HOLD_INCOMPLETE_SAFETY_PANEL", "HOLD_UNMEASURED_MANDATORY_SAFETY_PANEL")
            )
            or hist_entry.get("combined_stress_coupon_cleared_lysis_le_8pct_and_si_ge_2p5") is False
            or hist_entry.get("obs_vascularized_explant_en_bloc_recovery_verified") is False
            or hist_entry.get("obs_ap1903_pulsed_pk_washout_regimen_verified") is False
        ):
            prior_failed_stage0_gate_keys.update(hist_stage0_noncore_keys)
        if single_hist_s0.get("safety_kill_s9_triggered") is True:
            post_stop_passing_s9_batch_ids.clear()
            for cat in (single_hist_s0.get("s9_causal_failed_categories") or []):
                stop_required_s9_categories.add(str(cat))
            if (
                single_hist_s0.get("resolved_architecture_assignments", {}).get("mcb_clonogenic_escape_qualification_status")
                == "HARD_SAFETY_STOP_MCB_CLONOGENIC_SURVIVOR_DETECTED"
                or "MCB_CLONOGENIC" in stop_required_s9_categories
            ):
                stop_required_mcb_clonogenic_clearance = True
            if (
                "ER_CHOP_HC10" in stop_required_s9_categories
                or any(
                    "obs_chop_coincidence_fold" in r
                    or "obs_gate0e_chop_log2fc" in r
                    or "obs_hc10_surface_fold_wt" in r
                    or "obs_gate0e_hc10_surface_mfi_ratio" in r
                    for r in (single_hist_s0.get("triggered_rule_ids") or [])
                )
            ):
                stop_required_5endpoint_er_clearance = True
        elif (
            prior_sticky_s9
            and single_hist_s0.get("mandatory_s9_safety_panel_complete") is True
            and single_hist_s0.get("safety_kill_s9_triggered") is False
            and single_hist_s0.get("safety_kill_s9_status") == "CLEARED"
            and (
                "CORE_S9_VAF_OR_CASTSEQ" not in stop_required_s9_categories
                or (
                    float(hist_meas.get("obs_tp53_ppm1d_bcor_duplex_depth") or hist_meas.get("obs_tp53_duplex_depth") or 0.0) >= 62958.0
                    and float(hist_meas.get("obs_castseq_duplex_or_amplicon_depth") or 0.0) >= 62958.0
                )
            )
            and (
                not stop_required_mcb_clonogenic_clearance