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…

                or single_hist_s0.get("resolved_architecture_assignments", {}).get("mcb_clonogenic_escape_qualification_status")
                == "CLEARED_MCB_CLONOGENIC_EFFECTIVE_TRIALS_GE_299573228"
            )
            and (
                not stop_required_5endpoint_er_clearance
                or single_hist_s0.get("s9_5endpoint_er_safety_panel_complete") is True
                or single_hist_s0.get("full_5endpoint_s9_panel_complete") is True
            )
            and (
                "RESIDUAL_PSC" not in stop_required_s9_categories
                or (
                    hist_meas.get("obs_residual_psc_effective_fraction") not in ("UNAVAILABLE", None)
                    and float(hist_meas.get("obs_residual_psc_effective_trials") or 0.0) >= 299573228.0
                )
            )
            and (
                "CNV_20Q11" not in stop_required_s9_categories
                or hist_meas.get("obs_20q11_bcl2l1_cnv_ratio") not in ("UNAVAILABLE", None)
            )
            and (
                "SINGLE_CELL_MOSAIC_20Q11" not in stop_required_s9_categories
                or hist_meas.get("obs_20q11_bcl2l1_single_cell_mosaic_fraction") not in ("UNAVAILABLE", None)
            )
            and (
                "POST_STRESS_20Q11_OUTGROWTH" not in stop_required_s9_categories
                or hist_meas.get("obs_post_stress_20q11_bcl2l1_outgrowth_fold") not in ("UNAVAILABLE", None)
            )
            and (
                "FUNCTIONAL_P53_NUTLIN3A" not in stop_required_s9_categories
                or hist_meas.get("obs_nutlin3a_p21_mdm2_fold_induction") not in ("UNAVAILABLE", None)
            )
            and (
                "HAZARD_PROLIF_SURVIVOR" not in stop_required_s9_categories
                or (
                    hist_meas.get("obs_hazard_state_prolif_survivor_count_k") not in ("UNAVAILABLE", None)
                    and float(hist_meas.get("obs_hazard_state_prolif_effective_trials") or 0.0) >= 299573228.0
                )
            )
            and (
                "PULSED_PK_KILL" not in stop_required_s9_categories
                or (
                    hist_meas.get("obs_ap1903_pulsed_pk_log10_kill") not in ("UNAVAILABLE", None)
                    and hist_entry.get("obs_ap1903_pulsed_pk_washout_regimen_verified") is not False
                )
            )
            and (
                "MONOTHERAPY_PULSED_PK_KILL" not in stop_required_s9_categories
                or (
                    hist_meas.get("obs_ap1903_monotherapy_pulsed_pk_log10_kill") not in ("UNAVAILABLE", None)
                    and hist_entry.get("obs_ap1903_pulsed_pk_washout_regimen_verified") is not False
                )
            )
            and (
                "STEP1_SUBLETHAL_SURVIVOR" not in stop_required_s9_categories
                or (
                    hist_meas.get("obs_ap1903_step1_sublethal_survivor_count_k") not in ("UNAVAILABLE", None)
                    and float(hist_meas.get("obs_ap1903_step1_effective_trials") or 0.0) >= 29957322.8
                )
            )
            and (
                "EXPLANT_RECOVERY" not in stop_required_s9_categories
                or (
                    hist_entry.get("obs_vascularized_explant_en_bloc_recovery_verified") is True
                    and _explant_recovery_clears_student_t_0p99(hist_meas)
                )
            )
            and _extra_iip0024_stop_categories_cleared(stop_required_s9_categories, hist_meas)
            and isinstance(hist_entry.get("batch_id"), str)
            and hist_entry["batch_id"].strip()
        ):
            post_stop_passing_s9_batch_ids.append(hist_entry["batch_id"].strip())
        step_hist_payload = dict(pooled_stage0_payload)
        if isinstance(hist_entry.get("batch_id"), str) and hist_entry["batch_id"].strip():
            step_hist_payload["batch_id"] = hist_entry["batch_id"].strip()
        _req_tcat_p = _clean_optional_id_str(hist_entry.get("reset_prior_safety_stop_target_category"))
        if _req_tcat_p is not None and stop_required_s9_categories and stop_required_s9_categories != {_req_tcat_p}:
            step_hist_payload["verified_ledger_passing_s9_batch_ids"] = []
        else:
            step_hist_payload["verified_ledger_passing_s9_batch_ids"] = list(post_stop_passing_s9_batch_ids)
        for qp_k in (
            "prior_batch_sticky_s9_safety_stop",
            "prior_variant_safety_status",
            "reset_prior_safety_stop_after_investigation",
            "reset_prior_safety_stop_reason",
            "reset_prior_safety_stop_reason_code",
            "reset_prior_safety_stop_repeat_batch_ids",
            "reset_prior_safety_stop_independent_qp_approver_id",
            "reset_prior_safety_stop_target_category",
            "submitter_id",
        ):
            if hist_entry.get(qp_k) is not None:
                step_hist_payload[qp_k] = hist_entry[qp_k]
        hist_s0_eval = evaluate_stage0_decision_tree(
            step_hist_payload,
            defaulted_se_keys=sorted(pooled_defaulted_se_set),
            prior_batch_sticky_s9_safety_stop=prior_sticky_s9,
        )
        prior_sticky_s9 = bool(hist_s0_eval.get("safety_kill_s9_triggered") is True) or bool(single_hist_s0.get("safety_kill_s9_triggered") is True)
        if not prior_sticky_s9:
            stop_required_mcb_clonogenic_clearance = False
            stop_required_5endpoint_er_clearance = False
            stop_required_s9_categories.clear()
        if hist_s0_eval.get("resolved_architecture_assignments", {}).get("prior_s9_safety_stop_history_retained") is True:
            prior_s9_history_retained_across_ledger = True
    if (
        isinstance((prior_posterior_report or {}).get("stage0_decision_tree_evaluation"), dict)
        and prior_posterior_report["stage0_decision_tree_evaluation"].get("safety_kill_s9_triggered") is True
    ):
        prior_sticky_s9 = True
    if isinstance(input_payload.get("mcb_clone_id"), str) and input_payload["mcb_clone_id"].strip():
        seen_mcb_clone_ids.add(input_payload["mcb_clone_id"].strip())
    elif prev_obs_ledger:
        any_batch_omitted_mcb_clone_id = True
    curr_lot_id = _clean_optional_id_str(input_payload.get("current_lot_id"))
    curr_dev_id = _clean_optional_id_str(input_payload.get("device_assembly_id"))
    if prev_obs_ledger and (active_pooled_lot_id is not None or curr_lot_id is not None) and curr_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=curr_lot_id,
        prev_device_id=active_pooled_device_id,
        new_device_id=curr_dev_id,
        is_subsequent_batch=bool(prev_obs_ledger),
        invalidated_keys=cross_lot_invalidated_keys,
        prior_failed_noncore_keys=prior_failed_stage0_gate_keys,
    )
    curr_meas_for_oos = dict(current_obs_entry.get("measurements") or {})
    for bf_k in stage0_persisted_boolean_flags:
        if bf_k in input_payload and input_payload[bf_k] is not None:
            curr_meas_for_oos[bf_k] = input_payload[bf_k]
    curr_stage0_noncore_keys = {
        k for k, v in curr_meas_for_oos.items()
        if k not in s9_3_endpoint_keys and not k.endswith("_se") and v not in ("UNAVAILABLE", None)
    }
    if curr_stage0_noncore_keys & prior_failed_stage0_gate_keys:
        if not (
            input_payload.get("oos_retest_investigation_approved") is True
            and isinstance(input_payload.get("oos_retest_assignable_cause_code"), str)
            and input_payload["oos_retest_assignable_cause_code"].strip()
        ):
            uninvestigated_non_s9_oos_overwrite_hold = True
    multi_batch_clone_unverified_or_mixed = bool(
        len(seen_mcb_clone_ids) > 1
        or (len(prev_obs_ledger) >= 1 and (any_batch_omitted_mcb_clone_id or len(seen_mcb_clone_ids) == 0))
    )
    cross_clone_pooling_hold = bool(
        multi_batch_clone_unverified_or_mixed
        and input_payload.get("allow_cross_clone_pooling_for_exploratory_research") is not True
    )
    curr_def_se = set(measurement_validation.get("defaulted_standard_error_keys") or [])
    _drop_unpaired_rare_event_members(pooled_stage0_payload, input_payload)
    saved_x14_scale = pooled_stage0_payload.get("obs_beta_x1_x4_epistasis_scale")
    saved_x34_scale = pooled_stage0_payload.get("obs_beta_x3_x4_epistasis_scale")
    pooled_stage0_payload.pop("s8b_epistasis_estimand_scale", None)
    _merge_batch_measurements_atomic_mean_se(
        pooled_stage0_payload,
        pooled_defaulted_se_set,
        input_payload,
        curr_def_se,
        se_to_mean_lookup,
        skip_keys=("obs_beta_x1_x4_epistasis_scale", "obs_beta_x3_x4_epistasis_scale"),
    )
    if "obs_beta_x1_x4_epistasis" in input_payload and input_payload.get("obs_beta_x1_x4_epistasis") not in ("UNAVAILABLE", None):
        curr_sc_14 = input_payload.get("obs_beta_x1_x4_epistasis_scale") or input_payload.get("s8b_epistasis_estimand_scale")
        if curr_sc_14 is not None:
            pooled_stage0_payload["obs_beta_x1_x4_epistasis_scale"] = curr_sc_14
        else:
            pooled_stage0_payload.pop("obs_beta_x1_x4_epistasis_scale", None)
    elif saved_x14_scale is not None:
        pooled_stage0_payload["obs_beta_x1_x4_epistasis_scale"] = saved_x14_scale
    if "obs_beta_x3_x4_epistasis" in input_payload and input_payload.get("obs_beta_x3_x4_epistasis") not in ("UNAVAILABLE", None):
        curr_sc_34 = input_payload.get("obs_beta_x3_x4_epistasis_scale") or input_payload.get("s8b_epistasis_estimand_scale")
        if curr_sc_34 is not None:
            pooled_stage0_payload["obs_beta_x3_x4_epistasis_scale"] = curr_sc_34
        else:
            pooled_stage0_payload.pop("obs_beta_x3_x4_epistasis_scale", None)
    elif saved_x34_scale is not None:
        pooled_stage0_payload["obs_beta_x3_x4_epistasis_scale"] = saved_x34_scale
    seen_active_adjunct_history_arms: set[str] = set()
    seen_active_adjunct_depletion_modes: set[str] = set()
    for _dm_entry in [*prev_obs_ledger, current_obs_entry]:
        _ha_val = _dm_entry.get("adjunct_conditioning_history_arm")
        if isinstance(_ha_val, str) and _ha_val.strip():
            seen_active_adjunct_history_arms.add(_ha_val.strip())
        _dm_val = _dm_entry.get("adjunct_depletion_mode")
        if isinstance(_dm_val, str) and _dm_val.strip() in ("NATURAL_AGING_DECAY", "PHYSICAL_WASHOUT"):
            seen_active_adjunct_depletion_modes.add(_dm_val.strip())
    if len(seen_active_adjunct_history_arms) > 1:
        raise ValueError(
            "Cannot pool distinct adjunct_conditioning_history_arm conditioning histories across calibration batches (IIP-0028; DEC-106)"
        )
    if len(seen_active_adjunct_depletion_modes) > 1:
        raise ValueError(
            "Cannot pool NATURAL_AGING_DECAY and PHYSICAL_WASHOUT adjunct_depletion_mode batches without separate comparability qualification (IIP-0012; DEC-091)"
        )
    seen_active_splice_challenger_arms: set[str] = set()
    seen_active_locus4_orientations: set[str] = set()
    for _sc_entry in [*prev_obs_ledger, current_obs_entry]:
        _sc_arm = _sc_entry.get("knockin_splice_challenger_arm")
        if isinstance(_sc_arm, str) and _sc_arm.strip() != "PARENTAL_REFERENCE":
            seen_active_splice_challenger_arms.add(_sc_arm.strip())
        _sc_ori = _sc_entry.get("knockin_locus4_orientation")
        if isinstance(_sc_ori, str) and _sc_ori.strip() in ("CO_DIRECTIONAL_MINUS", "CONVERGENT_PLUS"):
            seen_active_locus4_orientations.add(_sc_ori.strip())
    if len(seen_active_splice_challenger_arms) > 1:
        raise ValueError(
            "Cannot pool distinct knockin_splice_challenger_arm conditions across calibration batches (IIP-0015; DEC-092)"
        )
    if len(seen_active_locus4_orientations) > 1:
        raise ValueError(
            "Cannot pool CO_DIRECTIONAL_MINUS and CONVERGENT_PLUS knockin_locus4_orientation batches (IIP-0015; DEC-092)"
        )
    seen_active_s10_construct_ids: set[str] = set()
    for _s10_entry in [*prev_obs_ledger, current_obs_entry]:
        _s10_cid = _s10_entry.get("s10_construct_id")
        if isinstance(_s10_cid, str) and _s10_cid.strip():
            seen_active_s10_construct_ids.add(_s10_cid.strip())
    if len(seen_active_s10_construct_ids) > 1:
        raise ValueError(
            "Cannot pool distinct s10_construct_id conditions across calibration batches (IIP-0016; DEC-094)"
        )
    seen_b2_tyk2_strata: set[str] = set()
    seen_b2_tyk2_alleles: set[str] = set()
    for _b2_entry in [*prev_obs_ledger, current_obs_entry]:
        _b2_st = _b2_entry.get("b2_tyk2_recipient_genotype_stratum")
        if isinstance(_b2_st, str) and _b2_st.strip():
            seen_b2_tyk2_strata.add(_b2_st.strip())
        _b2_al = _b2_entry.get("b2_tyk2_hlac_allele")
        if isinstance(_b2_al, str) and _b2_al.strip():
            seen_b2_tyk2_alleles.add(_b2_al.strip())
    if len(seen_b2_tyk2_strata) > 1:
        raise ValueError(
            "Cannot pool distinct b2_tyk2_recipient_genotype_stratum conditions across calibration batches (IIP-0017; DEC-095)"
        )
    if len(seen_b2_tyk2_alleles) > 1:
        raise ValueError(
            "Cannot pool distinct b2_tyk2_hlac_allele conditions across calibration batches (IIP-0017; DEC-095)"
        )
    seen_s6_arms: set[str] = set()
    seen_p05_geom_modes: set[str] = set()
    seen_dz_arms: set[str] = set()
    for _t3d_entry in [*prev_obs_ledger, current_obs_entry]:
        _s6_a = _t3d_entry.get("s6_cluster_size_arm")
        if isinstance(_s6_a, str) and _s6_a.strip():
            seen_s6_arms.add(_s6_a.strip())
        _p05_g = _t3d_entry.get("p05_barrier_slab_geometry_mode")
        if isinstance(_p05_g, str) and _p05_g.strip():
            seen_p05_geom_modes.add(_p05_g.strip())