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…

        _dz_a = _t3d_entry.get("design_z_divider_arm")
        if isinstance(_dz_a, str) and _dz_a.strip():
            seen_dz_arms.add(_dz_a.strip())
    if len(seen_s6_arms) > 1:
        raise ValueError(
            "Cannot pool distinct s6_cluster_size_arm conditions across calibration batches (IIP-0019; DEC-097)"
        )
    if len(seen_p05_geom_modes) > 1:
        raise ValueError(
            "Cannot pool distinct p05_barrier_slab_geometry_mode conditions across calibration batches (IIP-0019; DEC-097)"
        )
    if len(seen_dz_arms) > 1:
        raise ValueError(
            "Cannot pool distinct design_z_divider_arm conditions across calibration batches (IIP-0019; DEC-097)"
        )
    seen_p05_cat_accs: set[str] = set()
    seen_cuff_arms: set[str] = set()
    seen_cuff_strata: set[str] = set()
    for _b20_entry in [*prev_obs_ledger, current_obs_entry]:
        _ca = _b20_entry.get("p05_catalase_uniprot_accession")
        if isinstance(_ca, str) and _ca.strip():
            seen_p05_cat_accs.add(_ca.strip())
        _cba = _b20_entry.get("cuff_bioconjugation_arm")
        if isinstance(_cba, str) and _cba.strip():
            seen_cuff_arms.add(_cba.strip())
        _css = _b20_entry.get("cuff_serum_challenge_stratum")
        if isinstance(_css, str) and _css.strip():
            seen_cuff_strata.add(_css.strip())
    if len(seen_p05_cat_accs) > 1:
        raise ValueError(
            "Cannot pool distinct p05_catalase_uniprot_accession conditions across calibration batches (IIP-0020; DEC-099)"
        )
    if len(seen_cuff_arms) > 1:
        raise ValueError(
            "Cannot pool distinct cuff_bioconjugation_arm conditions across calibration batches (IIP-0020; DEC-099)"
        )
    if len(seen_cuff_strata) > 1:
        raise ValueError(
            "Cannot pool distinct cuff_serum_challenge_stratum conditions across calibration batches (IIP-0020; DEC-099)"
        )
    seen_rest_arms: set[str] = set()
    seen_cond_arms: set[str] = set()
    seen_cond_scopes: set[str] = set()
    for _b21_entry in [*prev_obs_ledger, current_obs_entry]:
        _ra = _b21_entry.get("rest_ocr_coupon_arm")
        if isinstance(_ra, str) and _ra.strip():
            seen_rest_arms.add(_ra.strip())
        _cda = _b21_entry.get("conditioning_4arm_arm")
        if isinstance(_cda, str) and _cda.strip():
            seen_cond_arms.add(_cda.strip())
        _cds = _b21_entry.get("conditioning_washout_analyte_scope")
        if isinstance(_cds, str) and _cds.strip():
            seen_cond_scopes.add(_cds.strip())
    if len(seen_rest_arms) > 1:
        raise ValueError("Cannot pool distinct rest_ocr_coupon_arm conditions across calibration batches (IIP-0021; DEC-100)")
    if len(seen_cond_arms) > 1:
        raise ValueError("Cannot pool distinct conditioning_4arm_arm conditions across calibration batches (IIP-0021; DEC-100)")
    if len(seen_cond_scopes) > 1:
        raise ValueError("Cannot pool distinct conditioning_washout_analyte_scope conditions across calibration batches (IIP-0021; DEC-100)")
    seen_t2_routes: set[str] = set()
    for _b22_entry in [*prev_obs_ledger, current_obs_entry]:
        _t2r = _b22_entry.get("track2_rescue_route")
        if isinstance(_t2r, str) and _t2r.strip():
            seen_t2_routes.add(_t2r.strip())
    if len(seen_t2_routes) > 1:
        raise ValueError("Cannot pool distinct track2_rescue_route conditions across calibration batches (IIP-0022; DEC-101)")
    for _dy_mk in ("design_y_integrase_modality", "design_y_silencing_modality", "design_y_payload_arm"):
        _seen_dy = {
            _e[_dy_mk].strip()
            for _e in [*prev_obs_ledger, current_obs_entry]
            if isinstance(_e.get(_dy_mk), str) and _e[_dy_mk].strip()
        }
        if len(_seen_dy) > 1:
            raise ValueError(f"Cannot pool distinct {_dy_mk} conditions across calibration batches (IIP-0023; DEC-102)")
    for _cb_mk in ("contrast_b1_geometry_arm", "contrast_b2_perfusion_and_retrieval_arm", "contrast_b3_donor_iec_arm"):
        _seen_cb = {
            _e[_cb_mk].strip()
            for _e in [*prev_obs_ledger, current_obs_entry]
            if isinstance(_e.get(_cb_mk), str) and _e[_cb_mk].strip()
        }
        if len(_seen_cb) > 1:
            raise ValueError(f"Cannot pool distinct {_cb_mk} conditions across calibration batches (IIP-0025; DEC-104)")
    for _m26_mk in ("bound_c1_c5_pair_sha256", "tyk2_pe_modality"):
        _seen_m26 = {
            _e[_m26_mk].strip()
            for _e in [*prev_obs_ledger, current_obs_entry]
            if isinstance(_e.get(_m26_mk), str) and _e[_m26_mk].strip()
        }
        if len(_seen_m26) > 1:
            raise ValueError(f"Cannot pool distinct {_m26_mk} conditions across calibration batches (IIP-0026; DEC-105)")
    seen_donor_seedline_ids: set[str] = {
        _e["donor_seedline_id"].strip()
        for _e in [*prev_obs_ledger, current_obs_entry]
        if isinstance(_e.get("donor_seedline_id"), str) and _e["donor_seedline_id"].strip()
    }
    if len(seen_donor_seedline_ids) > 1 and input_payload.get("allow_cross_clone_pooling_for_exploratory_research") is not True:
        raise ValueError("Cannot pool distinct donor_seedline_id lineages across calibration batches (IIP-0024; DEC-103)")
    seen_physical_route_ids: set[str] = {
        _e["physical_route_id"].strip()
        for _e in [*prev_obs_ledger, current_obs_entry]
        if isinstance(_e.get("physical_route_id"), str) and _e["physical_route_id"].strip()
    }
    if len(seen_physical_route_ids) > 1:
        raise ValueError("Cannot pool distinct physical_route_id routes across calibration batches (IIP-0024; DEC-103)")
    same_lot_campaign_ids: set[str] = {
        _e["assay_campaign_id"].strip()
        for _e in [*prev_obs_ledger, current_obs_entry]
        if (
            _clean_optional_id_str(_e.get("current_lot_id")) == active_pooled_lot_id
            and isinstance(_e.get("assay_campaign_id"), str)
            and _e["assay_campaign_id"].strip()
        )
    }
    unlinked_campaign_hold = bool(
        len(same_lot_campaign_ids) > 1
        and input_payload.get("oos_retest_investigation_approved") is not True
        and input_payload.get("reset_prior_safety_stop_after_investigation") is not True
    )
    pooled_stage0_payload["batch_id"] = batch_id
    _req_tcat_curr = _clean_optional_id_str(input_payload.get("reset_prior_safety_stop_target_category"))
    if _req_tcat_curr is not None and stop_required_s9_categories and stop_required_s9_categories != {_req_tcat_curr}:
        pooled_stage0_payload["verified_ledger_passing_s9_batch_ids"] = []
    else:
        pooled_stage0_payload["verified_ledger_passing_s9_batch_ids"] = list(post_stop_passing_s9_batch_ids)
    stage0_eval_report = evaluate_stage0_decision_tree(
        pooled_stage0_payload,
        require_full_5endpoint_s9_panel=require_full_5endpoint_s9_panel,
        defaulted_se_keys=sorted(pooled_defaulted_se_set),
        prior_batch_sticky_s9_safety_stop=prior_sticky_s9,
    )
    if (
        prior_s9_history_retained_across_ledger
        and stage0_eval_report.get("safety_kill_s9_triggered") is False
        and isinstance(stage0_eval_report.get("resolved_architecture_assignments"), dict)
    ):
        stage0_eval_report["resolved_architecture_assignments"]["prior_s9_safety_stop_history_retained"] = True
        if stage0_eval_report["resolved_architecture_assignments"].get("lot_maturation_status") == "READY_FOR_ENCAPSULATION":
            stage0_eval_report["resolved_architecture_assignments"]["lot_maturation_status"] = (
                "READY_WITH_RETAINED_PRIOR_S9_INVESTIGATION_HISTORY"
            )
        if stage0_eval_report.get("lot_release_readiness_tier") == "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE":
            stage0_eval_report["lot_release_readiness_tier"] = "READY_WITH_RETAINED_PRIOR_S9_INVESTIGATION_HISTORY"
            stage0_eval_report["resolved_architecture_assignments"]["lot_release_readiness_tier"] = (
                "READY_WITH_RETAINED_PRIOR_S9_INVESTIGATION_HISTORY"
            )
        elif stage0_eval_report.get("lot_release_readiness_tier") == "PROVISIONAL_CORE_14_PANEL_CLEARED_EXTENDED_NK_PHAGO_DEPTH_CHRONIC_UNMEASURED":
            stage0_eval_report["lot_release_readiness_tier"] = "PROVISIONAL_CORE_14_PANEL_CLEARED_WITH_RETAINED_PRIOR_S9_HISTORY"
            stage0_eval_report["resolved_architecture_assignments"]["lot_release_readiness_tier"] = (
                "PROVISIONAL_CORE_14_PANEL_CLEARED_WITH_RETAINED_PRIOR_S9_HISTORY"
            )
        elif stage0_eval_report.get("lot_release_readiness_tier") == "PROVISIONAL_S9_AND_MATURITY_CLEARED_IMMUNE_AND_OCR_GATES_UNMEASURED":
            stage0_eval_report["lot_release_readiness_tier"] = "PROVISIONAL_S9_AND_MATURITY_CLEARED_WITH_RETAINED_PRIOR_S9_HISTORY"
            stage0_eval_report["resolved_architecture_assignments"]["lot_release_readiness_tier"] = (
                "PROVISIONAL_S9_AND_MATURITY_CLEARED_WITH_RETAINED_PRIOR_S9_HISTORY"
            )
        elif stage0_eval_report.get("lot_release_readiness_tier") == "PROVISIONAL_CORE_S9_CLEARED_UNMEASURED_GATES_PENDING":
            stage0_eval_report["lot_release_readiness_tier"] = "PROVISIONAL_CORE_S9_CLEARED_WITH_RETAINED_PRIOR_S9_HISTORY"
            stage0_eval_report["resolved_architecture_assignments"]["lot_release_readiness_tier"] = (
                "PROVISIONAL_CORE_S9_CLEARED_WITH_RETAINED_PRIOR_S9_HISTORY"
            )
    if cross_lot_invalidated_keys and isinstance(stage0_eval_report.get("resolved_architecture_assignments"), dict):
        stage0_eval_report["resolved_architecture_assignments"]["invalidated_prior_lot_or_device_keys"] = sorted(cross_lot_invalidated_keys)
        stage0_eval_report["resolved_architecture_assignments"]["cross_lot_evidence_isolation_status"] = (
            "CLEARED_INDEPENDENT_LOT_EVIDENCE_COMPLETE"
            if stage0_eval_report.get("lot_release_readiness_tier") == "READY_FOR_ENCAPSULATION_COMPLETE_STAGE0_EVIDENCE"
            else "HOLD_LOT_OR_DEVICE_SCOPED_EVIDENCE_MISSING_AFTER_PROVENANCE_CHANGE"
        )
    if unlinked_campaign_hold and isinstance(stage0_eval_report.get("resolved_architecture_assignments"), dict):
        stage0_eval_report["resolved_architecture_assignments"]["assay_campaign_isolation_status"] = (
            "HOLD_UNLINKED_ASSAY_CAMPAIGN_ACROSS_POOLED_BATCHES"
        )
        if not stage0_eval_report.get("safety_kill_s9_triggered"):
            stage0_eval_report["resolved_architecture_assignments"]["lot_maturation_status"] = (
                "HOLD_UNLINKED_ASSAY_CAMPAIGN_ACROSS_POOLED_BATCHES"
            )
            stage0_eval_report["lot_release_readiness_tier"] = "HOLD_FAILED_OR_INCOMPLETE_GATE"
            stage0_eval_report["resolved_architecture_assignments"]["lot_release_readiness_tier"] = "HOLD_FAILED_OR_INCOMPLETE_GATE"
    if cross_clone_pooling_hold and isinstance(stage0_eval_report.get("resolved_architecture_assignments"), dict):
        stage0_eval_report["resolved_architecture_assignments"]["cross_clone_pooled_evidence_status"] = (
            "HOLD_CROSS_CLONE_POOLED_EVIDENCE_REQUIRES_SINGLE_CLONE_LOT_QUALIFICATION"
        )
        if not stage0_eval_report.get("safety_kill_s9_triggered"):
            stage0_eval_report["resolved_architecture_assignments"]["lot_maturation_status"] = (
                "HOLD_CROSS_CLONE_POOLED_EVIDENCE_REQUIRES_SINGLE_CLONE_LOT_QUALIFICATION"
            )
            stage0_eval_report["lot_release_readiness_tier"] = "HOLD_FAILED_OR_INCOMPLETE_GATE"
            stage0_eval_report["resolved_architecture_assignments"]["lot_release_readiness_tier"] = "HOLD_FAILED_OR_INCOMPLETE_GATE"
    elif (
        multi_batch_clone_unverified_or_mixed
        and input_payload.get("allow_cross_clone_pooling_for_exploratory_research") is True
        and isinstance(stage0_eval_report.get("resolved_architecture_assignments"), dict)
    ):
        stage0_eval_report["resolved_architecture_assignments"]["cross_clone_pooled_evidence_status"] = (
            "EXPLORATORY_CROSS_CLONE_POOLED_EVIDENCE_NON_RELEASE_ONLY"
        )
        if not stage0_eval_report.get("safety_kill_s9_triggered"):
            stage0_eval_report["resolved_architecture_assignments"]["lot_maturation_status"] = (
                "EXPLORATORY_CROSS_CLONE_POOLED_NON_RELEASE"
            )
            stage0_eval_report["lot_release_readiness_tier"] = "EXPLORATORY_CROSS_CLONE_POOLED_NON_RELEASE"
            stage0_eval_report["resolved_architecture_assignments"]["lot_release_readiness_tier"] = (
                "EXPLORATORY_CROSS_CLONE_POOLED_NON_RELEASE"
            )
    if uninvestigated_non_s9_oos_overwrite_hold and isinstance(stage0_eval_report.get("resolved_architecture_assignments"), dict):
        stage0_eval_report["resolved_architecture_assignments"]["non_s9_oos_retest_governance_status"] = (
            "HOLD_UNINVESTIGATED_PRIOR_BATCH_OOS_OVERWRITE"
        )
        if not stage0_eval_report.get("safety_kill_s9_triggered"):
            stage0_eval_report["resolved_architecture_assignments"]["lot_maturation_status"] = (
                "HOLD_UNINVESTIGATED_PRIOR_BATCH_OOS_OVERWRITE"
            )
            stage0_eval_report["lot_release_readiness_tier"] = "HOLD_FAILED_OR_INCOMPLETE_GATE"
            stage0_eval_report["resolved_architecture_assignments"]["lot_release_readiness_tier"] = "HOLD_FAILED_OR_INCOMPLETE_GATE"
    result_report = {
        "schema_version": "0.8.0",
        "calibration_state_version": CALIBRATION_STATE_VERSION,
        "ingestor": "OpenIslet Closed-Loop Wet-Lab Conjugate Bayesian Updater",
        "calibration_mode": (
            "SYNTHETIC_DRY_RUN_VERIFICATION_DO_NOT_CLAIM_AS_WETLAB_DATA"
            if is_dry_run
            else "EMPIRICAL_WETLAB_INGESTION"
        ),
        "epistemic_lineage_status": (
            "SYNTHETIC_DRY_RUN_LINEAGE"
            if is_dry_run
            else "PURE_EMPIRICAL_WETLAB_LINEAGE"
        ),
        "batch_id": batch_id,
        "ingested_batch_ids": prev_batches + [batch_id],
        "batch_payload_sha256": batch_payload_sha256,
        "ingested_batch_payload_sha256s": prev_payload_hashes + [batch_payload_sha256],
        "ordered_batch_observation_ledger": prev_obs_ledger + [current_obs_entry],
        "parent_report_sha256": parent_report_sha256,
        "observed_endpoints_updated_count": observed_count,
        "minimum_biological_se_floor_enforced": MIN_BIOLOGICAL_SE_FLOOR,
        "minimum_prior_sd_positivity_floor_enforced": MIN_PRIOR_SD_POSITIVITY_FLOOR,
        "prior_data_conflict_z_threshold": PRIOR_DATA_CONFLICT_Z_THRESHOLD,
        "any_prior_data_conflict_detected_gt_3sigma": any(
            bool(u.get("prior_data_conflict_detected", False))
            for u in list(updates.values()) + list(optional_pouch_and_screen_updates.values())
        ),
        "supported_8_canonical_endpoints_v80": [
            "obs_stage7_yield_ratio",
            "obs_cd47_fold",
            "obs_serpinb9_log10_kass",
            "obs_icasp9_log10_kill",
            "obs_pouch_min_po2_mmhg",
            "obs_pouch_max_h2o2_uM",
            "obs_pouch_max_ph",
            "obs_ifng_hla_dr_dq_negative_pct",