scripts/wetlab_contract.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/wetlab_contract.py · SHA-256: 6bb3955530f8f05d…
('obs_l2_v3_exact_stack_effero_pct_of_wt', 'obs_l2_v3_exact_stack_effero_pct_of_wt_se'),
('obs_l2_v3_pericyte_coverage_pct', 'obs_l2_v3_pericyte_coverage_se'),
('obs_l2_v3_plvap_iec_network_t50_h', 'obs_l2_v3_plvap_iec_network_t50_se'),
('obs_l2_v3_plvap_iec_viability_pct', 'obs_l2_v3_plvap_iec_viability_se'),
('obs_l2_v3_tandem_polya_readthrough_fold', 'obs_l2_v3_tandem_polya_readthrough_se'),
('obs_l2_v3_cfh_stp_gpi_quantibrite_molecules', 'obs_l2_v3_cfh_stp_gpi_quantibrite_se'),
('obs_l2_v3_unit2_copy_expression_quantibrite_or_fold', 'obs_l2_v3_unit2_copy_expression_se'),
('obs_ciita_ki_allele1_ex4_ex6_aberrant_skip_pct', 'obs_ciita_ki_allele1_ex4_ex6_aberrant_skip_se'),
('obs_ciita_allele1_ex4_ex6_aberrant_skip_pct', 'obs_ciita_allele1_ex4_ex6_aberrant_skip_se'),
('obs_ciita_ki_allele2_ex4_ex6_aberrant_skip_pct', 'obs_ciita_ki_allele2_ex4_ex6_aberrant_skip_se'),
('obs_ciita_allele2_ex4_ex6_aberrant_skip_pct', 'obs_ciita_allele2_ex4_ex6_aberrant_skip_se'),
('obs_ciita_ki_ex4_ex6_aberrant_skip_pct', 'obs_ciita_ki_ex4_ex6_aberrant_skip_se'),
('obs_ciita_ko_ex4_ex6_aberrant_skip_pct', 'obs_ciita_ko_ex4_ex6_aberrant_skip_se'),
('obs_edited_72h_ifng_hla_dr_dp_dq_pos_pct', 'obs_edited_72h_ifng_hla_dr_dp_dq_pos_se'),
('obs_wt_lineage_matched_72h_ifng_hla_dr_dp_dq_pos_pct', 'obs_wt_lineage_matched_72h_ifng_hla_dr_dp_dq_pos_se'),
('obs_l2_v3_stage0_eef1a1_cpg_methylation_pct', 'obs_l2_v3_stage0_eef1a1_cpg_methylation_se'),
('obs_l2_v3_stage0_chs4_cpg_methylation_pct', 'obs_l2_v3_stage0_chs4_cpg_methylation_se'),
('obs_l2_v3_stage0_dm1_cpg_methylation_pct', 'obs_l2_v3_stage0_dm1_cpg_methylation_se'),
('obs_l2_v3_stage7_eef1a1_cpg_methylation_pct', 'obs_l2_v3_stage7_eef1a1_cpg_methylation_se'),
('obs_l2_v3_stage7_chs4_cpg_methylation_pct', 'obs_l2_v3_stage7_chs4_cpg_methylation_se'),
('obs_l2_v3_stage7_dm1_cpg_methylation_pct', 'obs_l2_v3_stage7_dm1_cpg_methylation_se'),
('obs_l2_v3_stage0_chs4_ctcf_chip_fold_enrichment', 'obs_l2_v3_stage0_chs4_ctcf_chip_fold_enrichment_se'),
('obs_l2_v3_stage0_dm1_ctcf_chip_fold_enrichment', 'obs_l2_v3_stage0_dm1_ctcf_chip_fold_enrichment_se'),
('obs_l2_v3_stage7_chs4_ctcf_chip_fold_enrichment', 'obs_l2_v3_stage7_chs4_ctcf_chip_fold_enrichment_se'),
('obs_l2_v3_stage7_dm1_ctcf_chip_fold_enrichment', 'obs_l2_v3_stage7_dm1_ctcf_chip_fold_enrichment_se'),
('obs_l2_v3_barrier_matched_80bp_stage7_eef1a1_cpg_methylation_pct', 'obs_l2_v3_barrier_matched_80bp_stage7_eef1a1_cpg_methylation_se'),
('obs_l2_v3_barrier_matched_80bp_stage7_chs4_ctcf_chip_fold_enrichment', 'obs_l2_v3_barrier_matched_80bp_stage7_chs4_ctcf_chip_fold_enrichment_se'),
('obs_l2_v3_manf_locus3_nfkb_suppression_ratio', 'obs_l2_v3_manf_locus3_nfkb_suppression_se'),
('obs_l2_v3_manf_ki67_prolif_pct', 'obs_l2_v3_manf_ki67_prolif_se'),
('obs_l2_v3_manf_ocr_ratio_vs_ctrl', 'obs_l2_v3_manf_ocr_ratio_vs_ctrl_se'),
('obs_l2_v3_ccl22_treg_to_effector_chemotaxis_ratio', 'obs_l2_v3_ccl22_treg_to_effector_chemotaxis_se'),
('obs_l2_v3_ccl22_effector_chemotaxis_fold_ctrl', 'obs_l2_v3_ccl22_effector_chemotaxis_fold_se'),
('obs_l2_v3_small_rnaseq_mir375_retention_pct', 'obs_l2_v3_small_rnaseq_mir375_retention_se'),
('obs_l2_v3_intron_splicing_efficiency_pct', 'obs_l2_v3_intron_splicing_efficiency_se'),
('obs_l2_v3_cd276_kd_pct', 'obs_l2_v3_cd276_kd_se'),
('obs_l2_v3_pvr_kd_pct', 'obs_l2_v3_pvr_kd_se'),
('obs_l2_v3_joint_stratum_nk_lysis_pct', 'obs_l2_v3_joint_stratum_nk_lysis_se'),
)
def _merge_stage0_container_fields_iip0031(
containers: tuple[dict[str, Any], ...] | list[dict[str, Any]],
*,
excluded_keys: frozenset[str] = frozenset(),
key_predicate: Any = None,
) -> tuple[dict[str, Any], list[dict[str, Any]], bool]:
"""
Conflict-aware, null-safe Stage-0 field merger shared across Direct, Serialized Ingestion,
and Chronological Replay (IIP-0031; DEC-110).
- Never lets an explicit `None` / `'UNAVAILABLE'` overwrite a non-null measurement.
- Flags ANY key where `None`/`'UNAVAILABLE'` co-occurs with a non-null value OR where
multiple containers supply distinct non-null values (strict JSON wire-type signature),
OR where any container contains a non-string dictionary key.
- Builds strictly per-container S9 probe candidates (NEVER cross-synthesizing `mean` from
container A with `se` from container B when their `mean`s disagree, while pairing a bare
repeated `mean` with an explicit valid `se` from another container that reported the exact
same `mean`).
"""
all_keys: list[str] = []
seen_k: set[str] = set()
has_conflict = False
for c in containers:
if not isinstance(c, dict):
continue
for raw_k in c:
if not isinstance(raw_k, str):
has_conflict = True
continue
ks = raw_k
if ks in excluded_keys or ks in seen_k:
continue
if key_predicate is not None and not key_predicate(ks):
continue
seen_k.add(ks)
all_keys.append(ks)
clean_merged: dict[str, Any] = {}
conflict_cands_by_key: dict[str, list[Any]] = {}
for k in all_keys:
vals = [c[k] for c in containers if isinstance(c, dict) and k in c]
has_null = any(v is None or v == 'UNAVAILABLE' for v in vals)
non_null = [v for v in vals if v is not None and v != 'UNAVAILABLE']
distinct_non_null: list[Any] = []
seen_sigs: set[str] = set()
malformed_val = False
for v in non_null:
if _is_strict_int_iip0024(v) and abs(v).bit_length() > 53:
malformed_val = True
continue
try:
sv = json.dumps(v, sort_keys=True, separators=(',', ':'), allow_nan=False)
except (TypeError, ValueError, OverflowError, RecursionError):
malformed_val = True
distinct_non_null.append(v)
continue
if sv not in seen_sigs:
seen_sigs.add(sv)
distinct_non_null.append(v)
if malformed_val or (has_null and bool(non_null)) or len(distinct_non_null) > 1:
has_conflict = True
if distinct_non_null:
conflict_cands_by_key[k] = distinct_non_null
elif distinct_non_null:
clean_merged[k] = distinct_non_null[0]
_all_mean_se_pairs = (
('obs_icasp9_log10_kill', 'obs_icasp9_log10_kill_se'),
('obs_tp53_ppm1d_bcor_vaf', 'obs_tp53_ppm1d_bcor_vaf_se'),
('obs_castseq_translocation_freq', 'obs_castseq_translocation_se'),
('obs_chop_coincidence_fold', 'obs_chop_coincidence_se'),
('obs_gate0e_chop_log2fc', 'obs_gate0e_chop_log2fc_se'),
('obs_hc10_surface_fold_wt', 'obs_hc10_surface_fold_se'),
('obs_gate0e_hc10_surface_mfi_ratio', 'obs_gate0e_hc10_surface_mfi_se'),
*_S11_MEAN_SE_PAIRS_IIP0031,
)
probe_candidates: list[dict[str, Any]] = []
if conflict_cands_by_key:
for c in containers:
if not isinstance(c, dict):
continue
cand_c = dict(clean_merged)
c_contributed = False
for k in conflict_cands_by_key:
if k in c and c[k] is not None and c[k] != 'UNAVAILABLE':
if _is_strict_int_iip0024(c[k]) and abs(c[k]).bit_length() > 53:
continue
cand_c[k] = c[k]
c_contributed = True
if not c_contributed:
continue
# Never cross-breed mean from container A with SE from container B when means disagree,
# and do not impute a default SE onto a bare repeated mean when another container already
# supplied an explicit valid SE for that exact same mean (or a mean-free shared SE) (Finding #9):
for mk, sk in _all_mean_se_pairs:
if mk not in conflict_cands_by_key and sk not in conflict_cands_by_key:
continue
if mk in cand_c and sk not in c:
if _is_strict_finite_number_iip0024(cand_c[mk]):
m_f = float(cand_c[mk])
matching_ses = [
c_other[sk]
for c_other in containers
if isinstance(c_other, dict)
and mk in c_other
and _is_strict_finite_number_iip0024(c_other[mk])
and float(c_other[mk]) == m_f
and sk in c_other
and _is_strict_finite_number_iip0024(c_other[sk])
and float(c_other[sk]) > 0.0
]
mean_free_ses = [
c_other[sk]
for c_other in containers
if isinstance(c_other, dict)
and mk not in c_other
and sk in c_other
and _is_strict_finite_number_iip0024(c_other[sk])
and float(c_other[sk]) > 0.0
]
if matching_ses:
cand_c[sk] = max(matching_ses, key=float)
elif mean_free_ses:
cand_c[sk] = max(mean_free_ses, key=float)
else:
cand_c.pop(sk, None)
else:
cand_c.pop(sk, None)
elif sk in cand_c and mk not in cand_c and mk in conflict_cands_by_key:
# Standalone SE without its mean in a container when mean is conflicted across containers:
# drop orphan SE so it cannot attach to a non-existent mean.
cand_c.pop(sk, None)
probe_candidates.append(cand_c)
return clean_merged, probe_candidates, has_conflict
def _eval_stage0_tree_preserving_s9_iip0031(
safe_obs: dict[str, Any],
*,
root_path: Path,
) -> tuple[dict[str, Any], bool]:
"""
Evaluate `evaluate_stage0_decision_tree` while isolating unrelated co-supported Stage-0 alias
collisions (e.g. `obs_regimeII_lysis_2h_pct` vs `obs_gate0c_2h_lysis_pct`, CHOP fold vs `2**log2FC`,
or SERPINB9 `k_ass` vs `10**log10_kass`) so valid S9 hard stops ALWAYS survive without `ValueError`
while any alias collision forces a non-clearing `HOLD_CONFLICTING_STAGE0_MEASUREMENT` (Finding #18).
"""
try:
return evaluate_stage0_decision_tree(safe_obs, root=root_path), False
except ValueError:
pass
conflict_pairs: list[tuple[str, str]] = []
for ak, ck in STAGE0_JSON_TRIGGER_KEY_ALIASES.items():
if ak in safe_obs and ck in safe_obs:
conflict_pairs.append((ak, ck))
for k1, k2 in CO_SUPPORTED_STAGE0_EQUIVALENT_KEY_PAIRS:
if k1 in safe_obs and k2 in safe_obs:
conflict_pairs.append((k1, k2))
for k1, k2 in (
('obs_chop_coincidence_fold', 'obs_gate0e_chop_log2fc'),
('obs_serpinb9_kass_M_s', 'obs_serpinb9_log10_kass'),
):
if k1 in safe_obs and k2 in safe_obs:
conflict_pairs.append((k1, k2))
# Strip non-S9 conflicted pairs and probe both sides of any S9-relevant conflicted pair (CHOP / HC10):
s9_pair_keys = {
('obs_chop_coincidence_fold', 'obs_gate0e_chop_log2fc'),
('obs_hc10_surface_fold_wt', 'obs_gate0e_hc10_surface_mfi_ratio'),
}
stripped = dict(safe_obs)
active_s9_pairs: list[tuple[str, str]] = []
for k1, k2 in conflict_pairs:
if (k1, k2) in s9_pair_keys or (k2, k1) in s9_pair_keys:
active_s9_pairs.append((k1, k2))
else:
stripped.pop(k1, None)
stripped.pop(k2, None)
variants: list[dict[str, Any]] = [stripped]
for k1, k2 in active_s9_pairs:
next_v: list[dict[str, Any]] = []
for d in variants:
d1 = dict(d)
d1.pop(k2, None)
d2 = dict(d)
d2.pop(k1, None)
next_v.extend((d1, d2))
variants = next_v
fallback_tree: dict[str, Any] | None = None
for vd in variants:
try:
te = evaluate_stage0_decision_tree(vd, root=root_path)
except ValueError:
continue
if te['safety_kill_s9_triggered']:
return te, True
if fallback_tree is None:
fallback_tree = te
if fallback_tree is not None:
return fallback_tree, True
# Final minimal S9-only projection if another non-S9 metadata field caused ValueError:
s9_only_keys = set(IIP0026_REQUIRED_CORE_S9_OBS_KEYS) | set(
k for ks in S9_REPLICATE_KEYS.values() for k in ks
) | {
'product_variant_id', 'current_lot_id', 'assay_campaign_id',
'obs_tp53_ppm1d_bcor_mutant_molecules_k', 'obs_castseq_mutant_junctions_k',
'obs_hazard_state_prolif_survivor_count_k', 'obs_hazard_state_prolif_effective_trials',
'obs_ap1903_step1_survivor_count_k', 'obs_ap1903_step1_effective_trials',
'obs_residual_psc_effective_fraction', 'obs_residual_psc_effective_trials',