scripts/ingest_wetlab_results.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/ingest_wetlab_results.py · SHA-256: e050593675170515…
"obs_tp53_duplex_depth",
"obs_tp53_mutant_molecules_k",
),
(
"obs_castseq_translocation_freq",
"obs_castseq_duplex_or_amplicon_depth",
"obs_castseq_mutant_junctions_k",
),
(
"obs_mcb_effective_clonogenic_trials",
"obs_mcb_clonogenic_survivor_count_k",
),
(
"obs_residual_psc_effective_fraction",
"obs_residual_psc_effective_trials",
),
(
"obs_hazard_state_prolif_survivor_count_k",
"obs_hazard_state_prolif_effective_trials",
),
(
"obs_ap1903_step1_sublethal_survivor_count_k",
"obs_ap1903_step1_effective_trials",
),
(
"obs_dxs_locus4_joint_retention_fraction",
"obs_dxs_cd47low_icasp9low_fraction",
"obs_dxs_ap1903_cd47high_escape_fraction",
"obs_dxs_screened_cell_count",
"obs_dxs_clonogenic_fraction",
"obs_dxs_spike_in_detection_efficiency",
),
(
"obs_20q11_bcl2l1_single_cell_mosaic_fraction",
"obs_20q11_bcl2l1_single_cell_mosaic_cells_scored",
),
(
"obs_gate0v_day28_persistent_vp1_ie1_positive_cell_pct",
"obs_gate0v_day28_persistent_vp1_ie1_cells_scored",
),
(
"obs_assembled_cluster_ki67_progenitor_pct",
"obs_assembled_cluster_ki67_progenitor_cells_scored",
),
(
"obs_ductal_sox9_krt19_double_pos_pct",
"obs_ductal_sox9_krt19_double_pos_cells_scored",
),
(
"obs_assembled_cluster_slc18a1_enterochromaffin_pct",
"obs_assembled_cluster_slc18a1_enterochromaffin_cells_scored",
),
(
"obs_senescent_p16_sasp_positive_cell_pct",
"obs_senescent_p16_sasp_cells_scored",
),
(
"obs_challenger_ivt_relative_recovery_eta",
"obs_challenger_umi_molecules_profiled",
"obs_challenger_aberrant_splice_umi_count_k",
),
(
"obs_mcb_1q32_mdm4_single_cell_mosaic_fraction",
"obs_mcb_1q32_mdm4_single_cell_mosaic_cells_scored",
),
(
"obs_1q32_mdm4_single_cell_mosaic_fraction",
"obs_1q32_mdm4_single_cell_mosaic_cells_scored",
),
(
"obs_gate0s_shedding_ddpcr_events_k",
"obs_gate0s_shedding_ddpcr_trials_n",
"obs_gate0s_shedding_viable_events_k",
"obs_gate0s_shedding_viable_trials_n",
),
)
def _drop_unpaired_rare_event_members(pooled: Dict[str, Any], batch_meas: Dict[str, Any]) -> None:
"""When any member of a rare-event count/rate/denominator assay group is updated in batch_meas, drop any stale sibling members from prior batches that were not re-supplied in the same batch."""
mean_to_se = {r[1]: r[2] for r in _get_stage0_decision_tree_specs()}
for grp in RARE_EVENT_ASSAY_GROUPS:
supplied_in_batch = {
k for k in grp if k in batch_meas and batch_meas.get(k) not in ("UNAVAILABLE", None)
}
if supplied_in_batch:
# Keep TP53 aliases synchronized if either canonical or alias key was supplied:
if grp[0] == "obs_tp53_ppm1d_bcor_vaf":
vaf_supplied = bool({"obs_tp53_ppm1d_bcor_vaf", "obs_tp53_vaf"} & supplied_in_batch)
depth_supplied = bool({"obs_tp53_ppm1d_bcor_duplex_depth", "obs_tp53_duplex_depth"} & supplied_in_batch)
k_supplied = bool({"obs_tp53_ppm1d_bcor_mutant_molecules_k", "obs_tp53_mutant_molecules_k"} & supplied_in_batch)
if not vaf_supplied:
for k_drop in ("obs_tp53_ppm1d_bcor_vaf", "obs_tp53_vaf"):
pooled.pop(k_drop, None)
pooled.pop(mean_to_se.get(k_drop, ""), None)
if not depth_supplied:
for k_drop in ("obs_tp53_ppm1d_bcor_duplex_depth", "obs_tp53_duplex_depth"):
pooled.pop(k_drop, None)
pooled.pop(mean_to_se.get(k_drop, ""), None)
if not k_supplied:
for k_drop in ("obs_tp53_ppm1d_bcor_mutant_molecules_k", "obs_tp53_mutant_molecules_k"):
pooled.pop(k_drop, None)
pooled.pop(mean_to_se.get(k_drop, ""), None)
else:
for k in grp:
if k not in supplied_in_batch:
pooled.pop(k, None)
if k in mean_to_se:
pooled.pop(mean_to_se[k], None)
def _extract_canonical_measurements(input_payload: Dict[str, Any]) -> Dict[str, Any]:
measurement_canonical: Dict[str, Any] = {}
primary_means = {r[3] for r in ENDPOINT_SPECS} | {r[3] for r in EXTENDED_STAGE0_STAGE1_SPECS}
for _ep_name, _def_m, _def_sd, mean_key, se_key, _min_v, _max_v, _unit in ENDPOINT_SPECS:
m_val = input_payload.get(mean_key)
s_val = input_payload.get(se_key)
if m_val in ("UNAVAILABLE", None):
measurement_canonical[mean_key] = "UNAVAILABLE"
measurement_canonical[se_key] = "UNAVAILABLE"
else:
measurement_canonical[mean_key] = float(m_val) if isinstance(m_val, (int, float)) and not isinstance(m_val, bool) else m_val
measurement_canonical[se_key] = float(s_val) if isinstance(s_val, (int, float)) and not isinstance(s_val, bool) else s_val
for _ep_name, _def_m, _def_sd, mean_key, se_key, default_se, _min_v, _max_v, _unit in EXTENDED_STAGE0_STAGE1_SPECS:
if mean_key in input_payload and input_payload.get(mean_key) not in ("UNAVAILABLE", None):
m_val = input_payload.get(mean_key)
s_val = input_payload.get(se_key, default_se)
measurement_canonical[mean_key] = float(m_val) if isinstance(m_val, (int, float)) and not isinstance(m_val, bool) else m_val
measurement_canonical[se_key] = float(s_val) if isinstance(s_val, (int, float)) and not isinstance(s_val, bool) else s_val
stage0_custom_defaults = getattr(_MEASUREMENT_CONTRACT_MODULE, "STAGE0_CUSTOM_DEFAULT_SE", {})
_scale_aware_s0_se = getattr(
_MEASUREMENT_CONTRACT_MODULE,
"_scale_aware_stage0_default_se",
lambda mk, l_b, h_b: stage0_custom_defaults.get(mk, max(1e-3, (h_b - l_b) * 0.01)),
)
for _eid, mean_key, se_key, lo, hi, _unit in _get_stage0_decision_tree_specs():
if mean_key in primary_means:
continue
if mean_key in input_payload and input_payload.get(mean_key) not in ("UNAVAILABLE", None):
m_val = input_payload.get(mean_key)
default_se = _scale_aware_s0_se(mean_key, lo, hi)
s_val = input_payload.get(se_key, default_se)
measurement_canonical[mean_key] = float(m_val) if isinstance(m_val, (int, float)) and not isinstance(m_val, bool) else m_val
measurement_canonical[se_key] = float(s_val) if isinstance(s_val, (int, float)) and not isinstance(s_val, bool) else s_val
return {
key: (0.0 if isinstance(value, (int, float)) and not isinstance(value, bool) and value == 0.0 else value)
for key, value in measurement_canonical.items()
}
def compute_measurement_payload_sha256(input_payload: Dict[str, Any]) -> str:
"""
Compute content-based SHA-256 over the canonical measurement fields only (excluding
`batch_id`/`assay_id` label strings) so content-identical measurement replays under a
new `batch_id` are deterministically detected and rejected (closing AUDIT-REF
and AUDIT-REF across all 8 canonical Stage-0/Stage-1 endpoints).
"""
measurement_canonical = _extract_canonical_measurements(input_payload)
raw_measurement_bytes = json.dumps(measurement_canonical, sort_keys=True, allow_nan=False).encode("utf-8")
return hashlib.sha256(raw_measurement_bytes).hexdigest()
def _convex_mean(left: float, right: float, left_weight: float, right_weight: float) -> float:
"""Preserve the exact convex hull, including equal physical-boundary means."""
# Retain the previous arithmetic for in-hull values so existing version-2
# reports at display-rounding ties remain valid continuation inputs.
mean = left_weight * left + right_weight * right
if not math.isfinite(mean):
mean = left + right_weight * (right - left)
if not math.isfinite(mean):
raise ValueError("Normal update mean is outside representable numeric range")
return min(max(left, right), max(min(left, right), mean))
def _normal_normal_moments(pm: float, psd: float, om: float, ose: float) -> tuple[float, float, float, float, float]:
"""Finite precision arithmetic without squaring a potentially huge finite SE."""
tau_prior = (1.0 / psd) ** 2
tau_obs = (1.0 / ose) ** 2
tau_post = tau_prior + tau_obs
if tau_prior <= 0.0 or tau_post <= 0.0 or not all(math.isfinite(v) for v in (tau_prior, tau_obs, tau_post)):
raise ValueError("Normal update precision is outside representable numeric range")
post_mean = _convex_mean(pm, om, tau_prior / tau_post, tau_obs / tau_post)
post_sd = 1.0 / math.sqrt(tau_post)
if not math.isfinite(post_mean) or not math.isfinite(post_sd) or post_sd <= 0.0:
raise ValueError("Normal update moments are outside representable numeric range")
return post_mean, post_sd, tau_prior, tau_obs, tau_post
def conjugate_normal_update(
prior_mean: float,
prior_sd: float,
obs_mean: float,
obs_se: float,
unit_and_support: str = "",
min_valid: float = 0.0,
max_valid: float = 100.0,
) -> Dict[str, Any]:
"""
Exact Normal-Normal conjugate Bayesian update with strict finite & biological SE-floor
validation (`obs_se >= 1e-3`, `prior_sd > 1e-12`), 3-sigma prior-data conflict detection (`z_conflict > 3.0`),
explicitly labeled clipping display (`[min_valid, max_valid]`, not a truncated-Normal posterior),
heuristic conflict attenuation comparator (not a fitted Student-t posterior), and full-precision machine state
preservation (closing AUDIT-REF, AUDIT-REF, 087, 103, and AUDIT-REF).
"""
pm = _require_finite_float(prior_mean, "prior_mean")
psd = _require_finite_float(prior_sd, "prior_sd")
om = _require_finite_float(obs_mean, "obs_mean")
ose = _require_finite_float(obs_se, "obs_se")
lower = _require_finite_float(min_valid, "min_valid")
upper = _require_finite_float(max_valid, "max_valid")
if lower >= upper or not lower <= om <= upper or not lower <= pm <= upper:
raise ValueError("prior and observed means must lie in the declared ordered physical domain")
if psd <= MIN_PRIOR_SD_POSITIVITY_FLOOR:
raise ValueError(
f"prior_sd must be > positivity floor {MIN_PRIOR_SD_POSITIVITY_FLOOR}, got {psd} (AUDIT-REF)"
)
if ose < MIN_BIOLOGICAL_SE_FLOOR:
raise ValueError(
f"obs_se must be >= biological floor {MIN_BIOLOGICAL_SE_FLOOR}, got {ose} (AUDIT-REF)"
)
post_mean, post_sd, tau_prior, tau_obs, tau_post = _normal_normal_moments(pm, psd, om, ose)
kl_nats = math.log(psd / post_sd) + 0.5 * ((post_sd / psd) ** 2 + ((post_mean - pm) / psd) ** 2 - 1.0)
kl_bits = kl_nats / math.log(2.0)
precision_gain_ratio = tau_post / tau_prior
shannon_entropy_reduction_bits = 0.5 * math.log2(precision_gain_ratio)
pred_sd = math.hypot(psd, ose)
conflict_z = abs(om - pm) / pred_sd
conflict_p = math.erfc(conflict_z / math.sqrt(2.0))
# Student-t (df=5) likelihood weight attenuation under prior-data conflict (AUDIT-REF):
t_weight_obs = tau_obs / (1.0 + (conflict_z ** 2) / 5.0)
robust_tau = tau_prior + t_weight_obs
robust_t_post_mean = _convex_mean(pm, om, tau_prior / robust_tau, t_weight_obs / robust_tau)
diagnostics = (kl_nats, kl_bits, precision_gain_ratio, shannon_entropy_reduction_bits,
pred_sd, conflict_z, conflict_p, robust_t_post_mean)
if not all(math.isfinite(value) for value in diagnostics):
raise ValueError("Normal update diagnostics are outside representable numeric range")
ci_low_raw = post_mean - 1.96 * post_sd
ci_high_raw = post_mean + 1.96 * post_sd
return {
"status": "UPDATED_FROM_OBSERVED_READOUT",
"unit_and_support": unit_and_support,
"minimum_biological_se_floor_enforced": MIN_BIOLOGICAL_SE_FLOOR,
"prior_mean": round(pm, 4),
"prior_sd": _safe_round_positive_sd(psd),
"prior_mean_exact": float(pm),
"prior_sd_exact": float(psd),
"observed_mean": round(om, 4),
"observed_se": _safe_round_positive_sd(ose),
"observed_mean_exact": float(om),