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…

        "observed_se_exact": float(ose),
        "posterior_mean": round(post_mean, 4),
        "posterior_sd": _safe_round_positive_sd(post_sd),
        "posterior_mean_exact": float(post_mean),
        "posterior_sd_exact": float(post_sd),
        "posterior_precision_tau_exact": float(tau_post),
        "posterior_95ci_low": round(ci_low_raw, 4),
        "posterior_95ci_high": round(ci_high_raw, 4),
        "posterior_95ci_low_physical_clipped_v80_071": round(max(min_valid, ci_low_raw), 4),
        "posterior_95ci_high_physical_clipped_v80_071": round(min(max_valid, ci_high_raw), 4),
        "student_t_df5_conflict_robust_posterior_mean_v80_087": round(robust_t_post_mean, 4),
        "conflict_attenuated_heuristic_mean": round(robust_t_post_mean, 4),
        "interval_and_robustness_qualification": {
            "posterior": "UNBOUNDED_NORMAL_NORMAL_CONJUGATE_MODEL",
            "physical_clipped_fields": "DISPLAY_INTERSECTION_ONLY_NOT_A_95PCT_TRUNCATED_NORMAL_CREDIBLE_INTERVAL",
            "student_t_df5_legacy_field": "DEPRECATED_ALIAS_FOR_ONE_STEP_PRECISION_ATTENUATION_HEURISTIC_NOT_A_STUDENT_T_POSTERIOR",
        },
        "kl_divergence_post_vs_prior_nats": round(kl_nats, 4),
        "kl_divergence_post_vs_prior_bits": round(kl_bits, 4),
        "precision_gain_ratio": round(precision_gain_ratio, 4),
        "shannon_entropy_reduction_bits": round(shannon_entropy_reduction_bits, 4),
        "z_conflict": round(conflict_z, 4),
        "prior_data_conflict_z": round(conflict_z, 4),
        "prior_data_conflict_p_twosided": round(conflict_p, 4),
        "prior_data_conflict_flag_p_lt_0p05": bool(conflict_z >= 1.959964),
        "prior_data_conflict_detected": bool(conflict_z > PRIOR_DATA_CONFLICT_Z_THRESHOLD),
    }


def _calibration_state_sha256(report: Dict[str, Any]) -> str:
    """Bind all eight endpoint states and replay histories; integrity is not source authentication."""
    keys = ("calibration_state_version", "calibration_mode", "epistemic_lineage_status", "batch_id",
            "batch_payload_sha256", "ingested_batch_ids", "ingested_batch_payload_sha256s",
            "parent_report_sha256", "conjugate_posterior_updates", "optional_pouch_and_36run_screen_updates_v80_070")
    if any(k not in report for k in keys):
        raise ValueError("Incomplete calibration state; regenerate legacy reports from original observations")
    state_obj = {k: report[k] for k in keys}
    if "ordered_batch_observation_ledger" in report:
        state_obj["ordered_batch_observation_ledger"] = report["ordered_batch_observation_ledger"]
    if "stage0_decision_tree_evaluation" in report:
        state_obj["stage0_decision_tree_evaluation"] = report["stage0_decision_tree_evaluation"]
    for opt_lineage_key in ("contains_synthetic_records", "calibration_lineage_class"):
        if opt_lineage_key in report:
            state_obj[opt_lineage_key] = report[opt_lineage_key]
    return hashlib.sha256(json.dumps(state_obj, sort_keys=True, allow_nan=False).encode()).hexdigest()


def _verify_endpoint_algebraic_integrity(ep_name: str, ep_obj: Dict[str, Any], pm: float, psd: float, *, min_valid: float, max_valid: float) -> None:
    """
    Verify that a prior report's `posterior_mean_exact` and `posterior_sd_exact` match the exact
    algebraic Normal-Normal conjugate update of its recorded `prior_*` and `observed_*` fields
    so tampered `posterior_mean_exact` values or forged status strings are rejected even if hashes
    are recomputed (AUDIT-REF, AUDIT-REF, & AUDIT-REF).
    """
    required_exact = {"prior_mean_exact", "prior_sd_exact", "observed_mean_exact", "observed_se_exact",
                      "posterior_mean_exact", "posterior_sd_exact", "posterior_precision_tau_exact"}
    if not required_exact <= ep_obj.keys():
        raise ValueError(f"Prior endpoint {ep_name!r} integrity requires complete exact machine state")
    status = ep_obj.get("status")
    if status == "UPDATED_FROM_OBSERVED_READOUT":
        pm0 = _require_finite_float(ep_obj["prior_mean_exact"], f"prior.{ep_name}.prior_mean_exact")
        psd0 = _require_finite_float(ep_obj["prior_sd_exact"], f"prior.{ep_name}.prior_sd_exact")
        om0 = _require_finite_float(ep_obj["observed_mean_exact"], f"prior.{ep_name}.observed_mean_exact")
        ose0 = _require_finite_float(ep_obj["observed_se_exact"], f"prior.{ep_name}.observed_se_exact")
        if not (min_valid <= pm0 <= max_valid and min_valid <= om0 <= max_valid):
            raise ValueError(f"Prior endpoint {ep_name!r} contains a prior/observed mean outside its declared physical domain")
        if psd0 <= MIN_PRIOR_SD_POSITIVITY_FLOOR or ose0 < MIN_BIOLOGICAL_SE_FLOOR:
            raise ValueError(f"Prior endpoint {ep_name!r} has invalid prior_sd={psd0} or observed_se={ose0}")
        expected = conjugate_normal_update(pm0, psd0, om0, ose0, min_valid=min_valid, max_valid=max_valid)
        expected.pop("unit_and_support")
    elif status == "UNAVAILABLE_PRIOR_RETAINED":
        pm0 = _require_finite_float(ep_obj["prior_mean_exact"], f"prior.{ep_name}.prior_mean_exact")
        psd0 = _require_finite_float(ep_obj["prior_sd_exact"], f"prior.{ep_name}.prior_sd_exact")
        if not min_valid <= pm0 <= max_valid:
            raise ValueError(f"Prior endpoint {ep_name!r} contains a prior mean outside its declared physical domain")
        if psd0 <= MIN_PRIOR_SD_POSITIVITY_FLOOR:
            raise ValueError(f"Prior endpoint {ep_name!r} has invalid retained prior_sd")
        expected = {
            "prior_mean": round(pm0, 4), "prior_sd": _safe_round_positive_sd(psd0),
            "posterior_mean_exact": pm0, "posterior_sd_exact": psd0,
            "posterior_mean": round(pm0, 4), "posterior_sd": _safe_round_positive_sd(psd0),
            "observed_mean": None, "observed_se": None, "observed_mean_exact": None, "observed_se_exact": None,
            "posterior_precision_tau_exact": (1.0 / psd0) ** 2,
            "posterior_95ci_low": round(pm0 - 1.96 * psd0, 4),
            "posterior_95ci_high": round(pm0 + 1.96 * psd0, 4),
            "kl_divergence_post_vs_prior_nats": 0.0, "kl_divergence_post_vs_prior_bits": 0.0,
            "precision_gain_ratio": 1.0, "shannon_entropy_reduction_bits": 0.0,
            "z_conflict": 0.0, "prior_data_conflict_z": 0.0, "prior_data_conflict_p_twosided": 1.0,
            "prior_data_conflict_flag_p_lt_0p05": False, "prior_data_conflict_detected": False,
        }
    else:
        raise ValueError(
            f"Prior report integrity violation on {ep_name!r}: invalid or unrecognized endpoint status {status!r}; "
            "must be 'UPDATED_FROM_OBSERVED_READOUT' or 'UNAVAILABLE_PRIOR_RETAINED' (AUDIT-REF)"
        )
    # Exact fields use relative arithmetic tolerance without an absolute SD budget:
    # 1e-7 absolute error can dominate small positive SDs and change sequential precision.
    for key, expected_value in expected.items():
        value = ep_obj.get(key)
        if isinstance(expected_value, bool):
            matches = type(value) is bool and value == expected_value
        elif isinstance(expected_value, (int, float)):
            numeric = _require_finite_float(value, f"prior.{ep_name}.{key}")
            matches = (math.isclose(numeric, expected_value, rel_tol=1e-12, abs_tol=0.0)
                       if key.endswith("_exact") else numeric == expected_value)
        else:
            matches = value == expected_value
        if not matches:
            raise ValueError(f"Prior endpoint {ep_name!r} integrity mismatch in {key!r}: {value!r} != {expected_value!r}")


# Single authoritative 35-flag persisted Stage-0 boolean registry shared across writer, helper replay, and production replay (R7S2-F02, IIP-0012 & IIP-0015; DEC-057/091/092):
STAGE0_PERSISTED_BOOLEAN_FLAGS: tuple[str, ...] = (
    "require_full_5endpoint_s9_panel",
    "require_full_7metric_combined_stress_panel",
    "s1_gzmb_kass_or_pdl1_scar_failed",
    "s1_l3_bfb_replacement_qualified",
    "s2_arm1x_clears_15k_resting_hlae_and_cd47_c15g_noninferior",
    "s3_arm1b_and_arm1x_below_15k_and_arm1c_splicing_ge_0p95",
    "s4_rnls_wt_clears_gsis_shutoff_and_ocr_and_er_gate",
    "s5_fasl_delta_tunel_gt_5pp",
    "s5_sa_thbd_fhl1_only_replacement_qualified",
    "s6_er_rescue_genotype_requalified",
    "b_prime_sct_recipient_cd8_mlc_cleared",
    "s8_fasting_leak_or_ucn3_failed",
    "s8_staged_dose_and_omental_portal_drainage_qualified",
    "s9_mineral_pore_occlusion_gt_15pct",
    "s9_chronic_80um_lowload_or_omental_scaffold_qualified",
    "s9_chronic_80um_lowload_qualified",
    "s9_omental_revascularization_qualified",
    "obs_masked_perfusion_confirmed",
    "s10_sct_selectivity_coupon_cleared_kc_ka_ge_4_and_lysis_le_8pct",
    "combined_stress_coupon_cleared_lysis_le_8pct_and_si_ge_2p5",
    "track2_b_sct_or_hlag1_lilrb1_rescue_qualified",
    "track2_b_sct_or_hlag1_product_switched",
    "cd47_playbook_200k_and_5pct_phago_waiver_approved",
    "s9_staged_cassette_excision_and_d10w_clamp_qualified",
    "periimplant_closed_suction_drain_verified",
    "obs_vascularized_explant_en_bloc_recovery_verified",
    "obs_ap1903_pulsed_pk_washout_regimen_verified",
    "obs_arm2_bound_and_supernatant_fasl_bioactivity_depleted_verified",
    "obs_arm2_sa_thbd_bioactivity_depleted_verified",
    "obs_arm2_contemporaneous_sham_handling_matched",
    "obs_arm3_ongoing_adjunct_bioactivity_verified",
    "obs_challenger_ivt_rna_recovery_standard_verified",
    "obs_challenger_pam_seed_shield_coconversion_verified",
    "obs_challenger_host_isoforms_above_loq_verified",
    "obs_challenger_sv40pa_and_host_3prime_cleavage_checked",
    "s10_is_replacement_challenger_lot",
    "s10_race_5p_3p_junction_verified",
    "hla_a2_d227k_t228a_positive_control_spr_verified",
    "b2_tyk2_saptkflel_allele_assigned_ms_detected",
    "b2_tyk2_peptide_pulsed_positive_control_verified",
    "b2_tyk2_hlac_blockade_abrogation_verified",
    "l3_multimir_pre_aav6_2x2_transient_kd_falsifier_cleared",
    "l3_multimir_low_ifn_and_resting_shield_retention_verified",
    "l3_multimir_arm6_c341s_hlac_and_dq2_dq8_peptide_screen_cleared",
    "s6_dose_matched_1500_ieq_verified",
    "s6_divider_iso10993_leachables_cleared",
    "p05_full_336h_coupled_o2_h2o2_ca_ph_qualified",
    "design_z_empty_lumen_14d_persistence_verified",
    "design_z_loaded_closed_state_confirmed",
    "require_full_iip0020_biomaterial_and_humoral_panel",
    "p05_recombinant_human_catalase_verified",
    "cuff_dpr_ring_hydrolysis_lcms_verified",
    "cuff_conjugate_disulfide_and_site_occupancy_lcms_verified",
    "cuff_hexafasl_inventory_within_provisional_cap_verified",
    "require_full_iip0021_ocr_and_conditioning_panel",
    "rest_120h_longitudinal_simultaneous_coverage_verified",
    "rest_120h_viable_lineage_yield_and_during_exposure_function_verified",
    "conditioning_pellet_loq_and_extraction_recovery_verified",
    "conditioning_orthogonal_pathway_controls_verified",
    "track2_b_sct_kir_rescue_qualified",
    "track2_hlag1_lilrb1_rescue_qualified",
    "require_full_iip0022_track2_and_guardrail_panel",
    "lineage_necroptosis_time_resolved_viability_and_rescue_verified",
    "design_y_attlr_outside_orf_5p3p_race_verified",
    "design_y_zero_2a_scar_proteomics_verified",
    "design_y_dpcpx_adora1_antagonist_control_run",
    "design_y_anti_cd200_blockade_reversal_verified",
    "design_y_y04_full_coculture_and_clonogenic_confirmed",
    "require_full_iip0024_atomic_provenance_and_bank_panel",
    "cd16_adcc_igg_depletion_paired_control_verified",
    "iapp_age_matched_reference_above_loq_verified",
    "mcb_imprinting_ic1_ic2_igdmr_conjunctive_cleared",
    "stage7_lot_imprinting_ic1_ic2_igdmr_conjunctive_cleared",
    "mcb_and_lot_xci_46xx_3axis_cleared_or_46xy",
    "mcb_and_lot_mtdna_1000x_numt_filtered_cleared",
    "require_full_iip0025_hurdle4_transport_and_challenger_panel",
    "p05_two_timepoint_same_lot_envelope_verified",
    "contrast_b2_route_qualification_distinct_from_portfolio_credit_verified",
    "contrast_b3_zero_primate_host_ingrowth_verified",
    "require_full_iip0026_molecular_provenance_panel",
    "donor_seed_gnomad_target_site_wgs_verified",
    "post_edit_reciprocal_mosaic_sv_or_clonal_zygosity_verified",
    "design_b_hla_ab_separated_pass_delivery_verified",
    "design_b_chr6p21_1p41mb_loh_sv_cleared",
    "design_b_hlac_dt9_positive",
    "design_b_hlae_3d12_positive",
    "design_b_hlac_allele_specific_surface_or_phased_mrna_verified",
    "b_sct_ciita_exon5_and_trimer_verified",
    "tyk2_phased_haplotype_sap_verified",
    "require_full_iip0028_postdepletion_adcc_mixture_and_iapp_panel",
    "washout_and_natural_decay_unpooled_verified",
    "carrier_and_soluble_adjunct_below_lod_verified",
    "fcr_effector_fcgr3a_158v_typed_verified",
    "dec084_measured_starting_composition_and_fresh_equal_output_verified",
    "iapp_sister_visit_lot_and_viable_beta_mass_concordance_verified",
    "require_full_iip0027_promoter_origin_and_itr_panel",
    "cxcl10_insert_matched_comparator_control_verified",
    "cxcl10_resting_expression_below_loq_confirmed",
    "bio06_itr_rna_origin_attribution_verified",
    "require_full_iip0029_twoclock_maturation_panel",
    "obs_alk5i_free_maturation_applied",
    "terminal_alk5i_tgfb_inhibitor_continued",
    "stage7_t3_10nM_and_nac_1mM_retained",
    "zm447439_washout_verified_pre_iec",
    "pre_coassembly_iec_vascular_function_verified",
    "readout2_both_40_and_100mmhg_tracer_aligned_verified",
    "require_full_iip0031_locus2_and_tier6b_panel",
    "ciita_ki_allele_informative_transcript_recovery_verified",
    "ciita_ko_allele_informative_transcript_recovery_verified",
    "ciita_cis_sentinels_socs1_dexi_clec16a_tost_verified",
    "lineage_matched_wt_stage7_hla_dr_dp_dq_inducibility_verified",
    "l2_v3_same_background_intronless_control_linked_to_cargo",
    "l2_v3_same_background_scramble_control_linked_to_cargo",
    "phasing_verified",
    "cis_verified",
    "wt_inducibility_verified",
    "rnai_attribution_verified",
    "obs_l2_v3_chr16_ha_wgs_pass",
)

HISTORICAL_LEDGER_BOOLEAN_METADATA_KEYS: tuple[str, ...] = (
    *STAGE0_PERSISTED_BOOLEAN_FLAGS,
    "prior_batch_sticky_s9_safety_stop",
    "reset_prior_safety_stop_after_investigation",
    "allow_cross_clone_pooling_for_exploratory_research",
    "oos_retest_investigation_approved",
)

ALLOWED_ORDERED_BATCH_LEDGER_KEYS: frozenset[str] = frozenset({
    "batch_id",
    "batch_payload_sha256",
    "measurements",
    "defaulted_se_keys",
    "product_variant_id",
    "estimand_scale",
    "s8b_epistasis_estimand_scale",
    "obs_beta_x1_x4_epistasis_scale",