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…

                        f"Prior endpoint {ep_name!r} posterior state is inconsistent with its ordered batch observation history (AUDIT-REF)"
                    )
        if isinstance(prior_stage0_eval, dict):
            allowed_stage0_eval_keys = {
                "schema_version",
                "strict_precedence_order",
                "mandatory_s9_safety_panel_complete",
                "full_5endpoint_s9_panel_complete",
                "s9_5endpoint_er_safety_panel_complete",
                "s9_causal_failed_categories",
                "s9_frequency_assay_holds",
                "s9_panel_completeness_tier",
                "lot_release_readiness_tier",
                "safety_kill_s9_triggered",
                "sticky_cross_batch_s9_stop_active",
                "primary_biological_or_pouch_gate_failed",
                "has_explicit_original_primary_obs",
                "has_explicit_release_critical_molecule_and_rate_se",
                "missing_original_primary_endpoints",
                "any_fallback_switch_triggered",
                "safety_kill_s9_status",
                "resolved_architecture_assignments",
                "validated_stage0_endpoints",
                "validated_stage0_se_endpoints",
                "stage0_se_provenance",
                "switch_decisions",
                "canonical_json_switch_id_map",
                "pivotal_combined_stress_coupon_gate",
                "prior_s9_safety_stop_cleared_after_investigation",
                "zero_event_proportion_missing_denominator_or_explicit_se",
                "iip0031_locus2_and_tier6b_evaluation",
                "s9_point_estimate_fallback_se_policy",
                "s9_se_imputed_endpoints",
            }
            unknown_stage0_eval_keys = sorted(set(prior_stage0_eval.keys()) - allowed_stage0_eval_keys)
            if unknown_stage0_eval_keys:
                raise ValueError(
                    f"Prior report stage0_decision_tree_evaluation contains unsupported keys {unknown_stage0_eval_keys} (ING-Q1; DEC-059)"
                )
            for s0_bool_k in (
                "safety_kill_s9_triggered",
                "mandatory_s9_safety_panel_complete",
                "full_5endpoint_s9_panel_complete",
                "s9_5endpoint_er_safety_panel_complete",
                "has_explicit_original_primary_obs",
                "has_explicit_release_critical_molecule_and_rate_se",
                "prior_s9_safety_stop_cleared_after_investigation",
                "zero_event_proportion_missing_denominator_or_explicit_se",
            ):
                if s0_bool_k in prior_stage0_eval and prior_stage0_eval[s0_bool_k] is not None and type(prior_stage0_eval[s0_bool_k]) is not bool:
                    raise ValueError(
                        f"Prior report stage0_decision_tree_evaluation.{s0_bool_k} must be a boolean when provided (R7S2-F02; DEC-057)"
                    )
            running_sticky_s9 = False
            stop_required_mcb_clonogenic_clearance = False
            stop_required_5endpoint_er_clearance = False
            stop_required_s9_categories: set[str] = set()
            post_stop_passing_s9_batch_ids: list[str] = []
            pooled_hist_for_s0: Dict[str, Any] = {}
            pooled_hist_def_se: set[str] = set()
            se_to_mean_hist = {
                **{
                    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()
                },
            }
            helper_persisted_boolean_flags = STAGE0_PERSISTED_BOOLEAN_FLAGS
            helper_active_lot_id: str | None = None
            helper_active_device_id: str | None = None
            helper_invalidated_keys: set[str] = set()
            for h_idx, entry in enumerate(obs_ledger):
                entry_lot_id = _clean_optional_id_str(entry.get("current_lot_id"))
                entry_dev_id = _clean_optional_id_str(entry.get("device_assembly_id"))
                if h_idx > 0 and (helper_active_lot_id is not None or entry_lot_id is not None) and entry_lot_id != helper_active_lot_id:
                    post_stop_passing_s9_batch_ids.clear()
                helper_active_lot_id, helper_active_device_id = _apply_provenance_scope_isolation(
                    pooled_hist_for_s0,
                    pooled_hist_def_se,
                    prev_lot_id=helper_active_lot_id,
                    new_lot_id=entry_lot_id,
                    prev_device_id=helper_active_device_id,
                    new_device_id=entry_dev_id,
                    is_subsequent_batch=(h_idx > 0),
                    invalidated_keys=helper_invalidated_keys,
                )
                hist_meas_for_s0 = dict(entry["measurements"])
                for bf_k in helper_persisted_boolean_flags:
                    if bf_k in entry and entry[bf_k] is not None:
                        if type(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_for_s0[bf_k] = entry[bf_k]
                hist_def_se = set(entry.get("defaulted_se_keys") or [])
                _drop_unpaired_rare_event_members(pooled_hist_for_s0, hist_meas_for_s0)
                _merge_batch_measurements_atomic_mean_se(
                    pooled_hist_for_s0,
                    pooled_hist_def_se,
                    hist_meas_for_s0,
                    hist_def_se,
                    se_to_mean_hist,
                )
                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 entry.get(meta_k) is not None:
                        pooled_hist_for_s0[meta_k] = entry[meta_k]
                        # Preserve product_variant_id and estimand_scale in per-batch historical Stage-0 replay (IIP-0026; DEC-105):
                        hist_meas_for_s0[meta_k] = entry[meta_k]
                if entry.get("s8b_epistasis_estimand_scale") is not None:
                    pooled_hist_for_s0["s8b_epistasis_estimand_scale"] = entry["s8b_epistasis_estimand_scale"]
                else:
                    pooled_hist_for_s0.pop("s8b_epistasis_estimand_scale", None)
                if "obs_beta_x1_x4_epistasis" in hist_meas_for_s0 and hist_meas_for_s0.get("obs_beta_x1_x4_epistasis") not in ("UNAVAILABLE", None):
                    ep_sc_14 = entry.get("obs_beta_x1_x4_epistasis_scale") or entry.get("s8b_epistasis_estimand_scale")
                    if ep_sc_14 is not None:
                        pooled_hist_for_s0["obs_beta_x1_x4_epistasis_scale"] = ep_sc_14
                    else:
                        pooled_hist_for_s0.pop("obs_beta_x1_x4_epistasis_scale", None)
                if "obs_beta_x3_x4_epistasis" in hist_meas_for_s0 and hist_meas_for_s0.get("obs_beta_x3_x4_epistasis") not in ("UNAVAILABLE", None):
                    ep_sc_34 = entry.get("obs_beta_x3_x4_epistasis_scale") or entry.get("s8b_epistasis_estimand_scale")
                    if ep_sc_34 is not None:
                        pooled_hist_for_s0["obs_beta_x3_x4_epistasis_scale"] = ep_sc_34
                    else:
                        pooled_hist_for_s0.pop("obs_beta_x3_x4_epistasis_scale", None)
                single_batch_s0 = evaluate_stage0_decision_tree(
                    dict(hist_meas_for_s0),
                    defaulted_se_keys=sorted(hist_def_se),
                    prior_batch_sticky_s9_safety_stop=False,
                )
                if single_batch_s0.get("safety_kill_s9_triggered") is True:
                    post_stop_passing_s9_batch_ids.clear()
                    for cat in (single_batch_s0.get("s9_causal_failed_categories") or []):
                        stop_required_s9_categories.add(str(cat))
                    if (
                        single_batch_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_batch_s0.get("triggered_rule_ids") or [])
                        )
                    ):
                        stop_required_5endpoint_er_clearance = True
                elif (
                    running_sticky_s9
                    and single_batch_s0.get("mandatory_s9_safety_panel_complete") is True
                    and single_batch_s0.get("safety_kill_s9_triggered") is False
                    and single_batch_s0.get("safety_kill_s9_status") == "CLEARED"
                    and (
                        "CORE_S9_VAF_OR_CASTSEQ" not in stop_required_s9_categories
                        or (
                            float(hist_meas_for_s0.get("obs_tp53_ppm1d_bcor_duplex_depth") or hist_meas_for_s0.get("obs_tp53_duplex_depth") or 0.0) >= 62958.0
                            and float(hist_meas_for_s0.get("obs_castseq_duplex_or_amplicon_depth") or 0.0) >= 62958.0
                        )
                    )
                    and (
                        not stop_required_mcb_clonogenic_clearance
                        or single_batch_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_batch_s0.get("s9_5endpoint_er_safety_panel_complete") is True
                        or single_batch_s0.get("full_5endpoint_s9_panel_complete") is True
                    )
                    and (
                        "RESIDUAL_PSC" not in stop_required_s9_categories
                        or (
                            hist_meas_for_s0.get("obs_residual_psc_effective_fraction") not in ("UNAVAILABLE", None)
                            and float(hist_meas_for_s0.get("obs_residual_psc_effective_trials") or 0.0) >= 299573228.0
                        )
                    )
                    and (
                        "CNV_20Q11" not in stop_required_s9_categories
                        or hist_meas_for_s0.get("obs_20q11_bcl2l1_cnv_ratio") not in ("UNAVAILABLE", None)
                    )
                    and (
                        "SINGLE_CELL_MOSAIC_20Q11" not in stop_required_s9_categories
                        or hist_meas_for_s0.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_for_s0.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_for_s0.get("obs_nutlin3a_p21_mdm2_fold_induction") not in ("UNAVAILABLE", None)