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…

    "obs_beta_x3_x4_epistasis_scale",
    "specimen_or_clone_ids",
    "prior_variant_safety_status",
    "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",
    "mcb_clone_id",
    "donor_seedline_id",
    "device_assembly_id",
    "physical_route_id",
    "assay_campaign_id",
    "oos_retest_assignable_cause_code",
    "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",
    "construct_sha256",
    "post_sort_endocrine_zm447439_regimen",
    "stage7_start_utc",
    "sort_reaggregation_utc",
    "assay_harvest_utc",
    "registered_mixture_id",
    "locked_analysis_plan_id",
    "gate0s_elevated_store_scope_matched_device_lot_id",
    "iip0029_twoclock_record",
    "background_id",
    "mcb_id",
    "l2_v3_donor_id",
    "donor_id",
    "sample_id",
    "sample_unit_id",
    "scope_type",
    "tier6b_presort_lineage_panel",
    "tier6b_clonogenic_risk_unit",
    "tier6b_sorted_lot_observations",
    "iip0031_locus2_record",
    *HISTORICAL_LEDGER_BOOLEAN_METADATA_KEYS,
})

MCB_SCOPED_POOLED_KEYS: frozenset[str] = frozenset({
    "product_variant_id",
    "estimand_scale",
    "mcb_clone_id",
    "donor_seedline_id",
    "s10_construct_id",
    "s10_construct_donor_sha256",
    "bound_c1_c5_pair_sha256",
    "mcb_imprinting_ic1_ic2_igdmr_conjunctive_cleared",
})

DEVICE_SCOPED_POOLED_PREFIXES: tuple[str, ...] = (
    "p05_",
    "obs_p05_",
    "design_z_",
    "obs_design_z_",
    "cuff_",
    "obs_cuff_",
    "s6_",
    "obs_s6_",
    "obs_pouch_",
    "obs_chronic_capsule_",
    "obs_capsule_",
    "obs_d_o2_gel_",
    "obs_outer_band_",
    "obs_periimplant_",
    "periimplant_",
    "obs_assembled_cassette_chandler_",
    "obs_gate0s_",
    "obs_explant_",
    "obs_vascularized_explant_",
    "s9_",
    "obs_masked_perfusion_confirmed",
    "contrast_b",
    "obs_contrast_b",
)


def _clean_optional_id_str(raw_v: Any) -> str | None:
    if isinstance(raw_v, str) and raw_v.strip():
        return raw_v.strip()
    return None


def _apply_provenance_scope_isolation(
    pooled: Dict[str, Any],
    pooled_def_se: set[str],
    *,
    prev_lot_id: str | None,
    new_lot_id: str | None,
    prev_device_id: str | None,
    new_device_id: str | None,
    is_subsequent_batch: bool,
    invalidated_keys: set[str],
    prior_failed_noncore_keys: set[str] | None = None,
) -> tuple[str | None, str | None]:
    """
    Prevent cross-lot LOT_SCOPE/DEVICE_SCOPE evidence borrowing and cross-device
    ASSEMBLED_DEVICE_LOT_SCOPE evidence borrowing across sequential batches (IIP-0024; DEC-103).
    """
    if is_subsequent_batch:
        if (prev_lot_id is not None or new_lot_id is not None) and new_lot_id != prev_lot_id:
            for k in list(pooled.keys()):
                if k not in MCB_SCOPED_POOLED_KEYS and not k.startswith("obs_mcb_"):
                    pooled.pop(k, None)
                    pooled_def_se.discard(k)
                    if k.startswith("obs_") and not k.endswith("_se"):
                        invalidated_keys.add(k)
            pooled_def_se.difference_update({sk for sk in list(pooled_def_se) if not sk.startswith("obs_mcb_")})
            if prior_failed_noncore_keys is not None:
                prior_failed_noncore_keys.clear()
            return new_lot_id, new_device_id
        if (prev_device_id is not None or new_device_id is not None) and new_device_id != prev_device_id:
            for k in list(pooled.keys()):
                if k.startswith(DEVICE_SCOPED_POOLED_PREFIXES) or k == "device_assembly_id":
                    pooled.pop(k, None)
                    pooled_def_se.discard(k)
                    if k.startswith("obs_") and not k.endswith("_se"):
                        invalidated_keys.add(k)
            return new_lot_id, new_device_id
    return new_lot_id, new_device_id


def _merge_batch_measurements_atomic_mean_se(
    pooled: Dict[str, Any],
    pooled_def_se: set[str],
    batch_meas: Dict[str, Any],
    batch_def_se: set[str],
    se_to_mean: Dict[str, str],
    *,
    skip_keys: tuple[str, ...] = (),
) -> None:
    """
    Merge batch observations into pooled Stage-0 state while strictly binding each meanKey
    to its same-batch seKey so a newer batch mean can NEVER silently inherit a prior batch's
    explicit SE (IIP-0024; DEC-103).
    """
    mean_to_se = {mk: sk for sk, mk in se_to_mean.items()}
    skip_set = set(skip_keys)
    for k, v in batch_meas.items():
        if k in skip_set or v in ("UNAVAILABLE", None):
            continue
        if k in se_to_mean:
            paired_mk = se_to_mean[k]
            if batch_meas.get(paired_mk) in ("UNAVAILABLE", None):
                continue
        pooled[k] = v
        if k in mean_to_se:
            paired_sk = mean_to_se[k]
            if batch_meas.get(paired_sk) in ("UNAVAILABLE", None) or paired_sk in batch_def_se or k in batch_def_se:
                if batch_meas.get(paired_sk) in ("UNAVAILABLE", None):
                    pooled.pop(paired_sk, None)
                pooled_def_se.add(paired_sk)
            else:
                pooled_def_se.discard(paired_sk)
                pooled_def_se.discard(k)
        elif k in se_to_mean:
            if k in batch_def_se or se_to_mean[k] in batch_def_se:
                pooled_def_se.add(k)
            else:
                pooled_def_se.discard(k)
                pooled_def_se.discard(se_to_mean[k])


def _explant_recovery_clears_student_t_0p99(meas_dict: Dict[str, Any]) -> bool:
    """
    Enforce exact one-sided 95% Student-t (df = n - 1, n >= 6, defaulting to df = 5 when n is omitted)
    lower95 >= 0.99 across explant en-bloc recovery endpoints so raw mean >= 0.99 with wide SE
    never clears EXPLANT_RECOVERY (IIP-0025; DEC-104).
    """
    _get_stage0_decision_tree_specs()
    t_ppf = getattr(_MEASUREMENT_CONTRACT_MODULE, "student_t_ppf_one_sided_95")
    n_raw = meas_dict.get("obs_stage0_independent_lot_replicates_n")
    if n_raw not in ("UNAVAILABLE", None):
        n_f = float(n_raw)
        if abs(n_f - round(n_f)) > 1e-9 or int(round(n_f)) < 6:
            return False
        t_mult = float(t_ppf(float(int(round(n_f)) - 1)))
    else:
        t_mult = float(t_ppf(5.0))
    any_present = False
    for mk, sk, def_se in (
        ("obs_explant_en_bloc_recovery_fraction", "obs_explant_en_bloc_recovery_se", 0.01),
        ("obs_gate0s_day30_en_bloc_recovery_fraction", "obs_gate0s_day30_en_bloc_recovery_se", 0.002),
        ("obs_gate0s_day90_en_bloc_recovery_fraction", "obs_gate0s_day90_en_bloc_recovery_se", 0.002),
    ):
        mv = meas_dict.get(mk)
        if mv not in ("UNAVAILABLE", None):
            any_present = True
            sv_raw = meas_dict.get(sk)
            sv = float(sv_raw) if sv_raw not in ("UNAVAILABLE", None) else def_se
            if float(mv) - t_mult * sv < 0.99:
                return False
    return any_present


def _extra_iip0024_stop_categories_cleared(
    stop_cats: set[str],
    meas_dict: Dict[str, Any],
) -> bool:
    if "CNV_1Q32_MDM4" in stop_cats:
        if (
            meas_dict.get("obs_mcb_1q32_mdm4_cnv_ratio") in ("UNAVAILABLE", None)
            and meas_dict.get("obs_1q32_mdm4_cnv_ratio") in ("UNAVAILABLE", None)
        ):
            return False
    if "SINGLE_CELL_MOSAIC_1Q32_MDM4" in stop_cats:
        has_mcb_mdm4 = (
            meas_dict.get("obs_mcb_1q32_mdm4_single_cell_mosaic_fraction") not in ("UNAVAILABLE", None)
            and float(meas_dict.get("obs_mcb_1q32_mdm4_single_cell_mosaic_cells_scored") or 0.0) >= 299.0