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…
10.513034914451096,
11.842395658958893,
13.148113796999684,
14.434649711103376,
15.705216422284304,
16.96221923565611,
18.207514641439424,
19.442569331048507,
20.668569076007206,
21.886485907105575,
23.097129760760103,
)
def _regularized_gamma_q_iip0031(a: float, x: float) -> float:
"""Exact regularized upper incomplete gamma Q(a, x) = P(Poisson(x) <= a - 1) for a >= 1, x > 0."""
if x <= 0.0:
return 1.0
gln = math.lgamma(a)
if x < a + 1.0:
ap = a
term = 1.0 / a
total = term
for _ in range(50000):
ap += 1.0
term *= x / ap
total += term
if abs(term) <= abs(total) * 1e-15:
break
p = total * math.exp(-x + a * math.log(x) - gln)
return max(0.0, min(1.0, 1.0 - p))
fpmin = 1e-300
b = x + 1.0 - a
c = 1.0 / fpmin
d = 1.0 / b
h = d
for i in range(1, 50000):
an = -i * (i - a)
b += 2.0
d = an * d + b
if abs(d) < fpmin:
d = fpmin
c = b + an / c
if abs(c) < fpmin:
c = fpmin
d = 1.0 / d
delta = d * c
h *= delta
if abs(delta - 1.0) <= 1e-15:
break
q = math.exp(-x + a * math.log(x) - gln) * h
return max(0.0, min(1.0, q))
def _poisson_exact_upper95_lambda(k_int: int, alpha: float = 0.05) -> float:
"""Exact one-sided (1 - alpha) Poisson upper mean lambda solving P(Poisson(lambda) <= k_int) = alpha."""
if k_int <= 0:
return -math.log(alpha)
a = float(k_int + 1)
if k_int > 10_000_000:
# High-order Cornish-Fisher expansion (relative error < 1e-13 for a > 1e7):
z = 1.6448536269514722
return a + z * math.sqrt(a) + (z * z - 1.0) / 3.0 + (z * z * z - 7.0 * z) / (36.0 * math.sqrt(a))
lo = float(k_int)
hi = max(a + 4.0 * math.sqrt(a) + 10.0, a * 1.5)
while _regularized_gamma_q_iip0031(a, hi) > alpha:
hi *= 2.0
for _ in range(90):
mid = 0.5 * (lo + hi)
if mid == lo or mid == hi:
break
if _regularized_gamma_q_iip0031(a, mid) > alpha:
lo = mid
else:
hi = mid
return hi
def _poisson_exact_upper95_rate(k_events: float, n_trials: float) -> float:
"""Return exact one-sided 95% Poisson upper rate bound lambda_upper95(k) / n_trials for all k >= 0."""
if n_trials <= 0.0:
return 1.0
k_int = max(0, int(round(k_events)))
lam_u95 = _poisson_exact_upper95_lambda(k_int, alpha=0.05)
return lam_u95 / n_trials
# Co-supported equivalent Stage-0 endpoint pairs that must never disagree in the same payload (AUDIT-REF & AUDIT-REF; DEC-041):
# Note: obs_hc10_surface_fold_wt (fold over WT) and obs_gate0e_hc10_surface_mfi_ratio (MFI fold over isotype) are distinct physical denominators and are not forced equal.
CO_SUPPORTED_STAGE0_EQUIVALENT_KEY_PAIRS: tuple[tuple[str, str], ...] = (
('obs_serpinb9_hour0_uM', 'obs_gate0c_hour0_serpinb9_uM'),
('obs_serpinb9_hour0_se', 'obs_gate0c_hour0_serpinb9_se'),
('obs_pdl1_hour0_mols', 'obs_gate0c_hour0_pdl1_molecules_per_cell'),
('obs_pdl1_hour0_se', 'obs_gate0c_hour0_pdl1_molecules_se'),
('obs_regimeII_lysis_2h_pct', 'obs_gate0c_2h_lysis_pct'),
('obs_regimeII_lysis_2h_se', 'obs_gate0c_2h_lysis_se'),
('obs_capsule_dz_um', 'obs_gate0f_capsule_thickness_um'),
('obs_capsule_dz_se', 'obs_gate0f_capsule_thickness_se'),
('obs_d_o2_gel_aged_cm2_s', 'obs_capsule_d_o2_cm2_s'),
('obs_d_o2_gel_aged_se', 'obs_capsule_d_o2_se'),
)
# Bidirectional alias map between stage0_decision_tree_v1.json switch trigger strings and canonical contract meanKey/seKey (AUDIT-REF & AUDIT-REF):
STAGE0_JSON_TRIGGER_KEY_ALIASES: dict[str, str] = {
'obs_regimeII_nkg2a_lysis_pct': 'obs_nkg2a_lysis_pct',
'obs_regimeII_nkg2a_lysis_se': 'obs_nkg2a_lysis_se',
'obs_astar_control_cd8_lysis_pct': 'obs_plan_a_star_cd8_lysis_pct',
'obs_astar_control_cd8_lysis_se': 'obs_plan_a_star_cd8_lysis_se',
'obs_immaturity_corner_min_g_mM': 'obs_immaturity_corner_min_glucose_mM',
'obs_immaturity_corner_min_g_se': 'obs_immaturity_corner_min_glucose_se',
'obs_hc10_surface_mfi_ratio': 'obs_gate0e_hc10_surface_mfi_ratio',
'obs_hc10_surface_mfi_se': 'obs_gate0e_hc10_surface_mfi_se',
'obs_granzyme_b_2h_lysis_pct': 'obs_regimeII_lysis_2h_pct',
'obs_granzyme_b_2h_lysis_se': 'obs_regimeII_lysis_2h_se',
'obs_chronic_capsule_thickness_um': 'obs_capsule_dz_um',
'obs_chronic_capsule_thickness_se': 'obs_capsule_dz_se',
'X1:X4': 'obs_beta_x1_x4_epistasis',
'X1:X4_se': 'obs_beta_x1_x4_epistasis_se',
'X3:X4': 'obs_beta_x3_x4_epistasis',
'X3:X4_se': 'obs_beta_x3_x4_epistasis_se',
}
def _canonicalize_stage0_alias_keys(raw_dict: dict) -> dict:
"""Translate stage0_decision_tree_v1.json trigger alias keys to canonical contract meanKey/seKey, rejecting conflicting duplicates (AUDIT-REF, AUDIT-REF, & AUDIT-REF)."""
out = dict(raw_dict)
for alias_key, canon_key in STAGE0_JSON_TRIGGER_KEY_ALIASES.items():
if alias_key in out:
alias_val = out.pop(alias_key)
if canon_key in out and out[canon_key] not in ('UNAVAILABLE', None) and alias_val not in ('UNAVAILABLE', None):
if finite_decimal(out[canon_key], canon_key) != finite_decimal(alias_val, alias_key):
raise ValueError(
f'Conflicting Stage-0 observation values for alias {alias_key!r} ({alias_val!r}) '
f'and canonical key {canon_key!r} ({out[canon_key]!r}) (AUDIT-REF)'
)
elif canon_key not in out or out[canon_key] in ('UNAVAILABLE', None):
out[canon_key] = alias_val
for k_primary, k_secondary in CO_SUPPORTED_STAGE0_EQUIVALENT_KEY_PAIRS:
if (
k_primary in out
and k_secondary in out
and out[k_primary] not in ('UNAVAILABLE', None)
and out[k_secondary] not in ('UNAVAILABLE', None)
):
if finite_decimal(out[k_primary], k_primary) != finite_decimal(out[k_secondary], k_secondary):
raise ValueError(
f'Conflicting co-supported Stage-0 observation values for {k_primary!r} ({out[k_primary]!r}) '
f'and {k_secondary!r} ({out[k_secondary]!r}) (AUDIT-REF)'
)
# Cross-scale consistency checks for CHOP (fold vs 2**log2fc) and SERPINB9 k_ass (M^-1 s^-1 vs 10**log10_kass) (AUDIT-REF):
if (
'obs_chop_coincidence_fold' in out
and 'obs_gate0e_chop_log2fc' in out
and out['obs_chop_coincidence_fold'] not in ('UNAVAILABLE', None)
and out['obs_gate0e_chop_log2fc'] not in ('UNAVAILABLE', None)
):
chop_f = finite_decimal(out['obs_chop_coincidence_fold'], 'obs_chop_coincidence_fold')
chop_l2 = finite_decimal(out['obs_gate0e_chop_log2fc'], 'obs_gate0e_chop_log2fc')
if not math.isclose(chop_f, 2.0 ** chop_l2, rel_tol=1e-2, abs_tol=1e-2):
raise ValueError(
f"Conflicting CHOP fold ({chop_f}) and 2**log2FC ({2.0 ** chop_l2:.4f}) in Stage-0 observations (AUDIT-REF)"
)
if (
'obs_serpinb9_kass_M_s' in out
and 'obs_serpinb9_log10_kass' in out
and out['obs_serpinb9_kass_M_s'] not in ('UNAVAILABLE', None)
and out['obs_serpinb9_log10_kass'] not in ('UNAVAILABLE', None)
):
kass_lin = finite_decimal(out['obs_serpinb9_kass_M_s'], 'obs_serpinb9_kass_M_s')
kass_l10 = finite_decimal(out['obs_serpinb9_log10_kass'], 'obs_serpinb9_log10_kass')
if not math.isclose(kass_lin, 10.0 ** kass_l10, rel_tol=1e-2, abs_tol=1.0):
raise ValueError(
f"Conflicting SERPINB9 k_ass ({kass_lin}) and 10**log10_kass ({10.0 ** kass_l10:.1f}) in Stage-0 observations (AUDIT-REF)"
)
return out
ARM1B_LOCUS1_COMPATIBLE_FAMILY_A_IDS = frozenset({
'ISLET1_A4_ARM1B',
'ISLET1_A4_ARM1B_TYK2_PE',
'ISLET1_A4_X_MOL_RNLS_WT',
'ISLET1_Z_X_MOL_140UM_ZERO_CAO2',
'ISLET1_A4_L3_SCARFREE_3799',
'ISLET1_A4_L3_BFB_BASALFLOOR',
'ISLET1_COMP_R4_X_BFB_DXB_LOWLOAD1500',
'ISLET1_B_SCT_C1_CIITA',
'ISLET1_B_SCT_C2_CIITA',
'ISLET1_B_SCT_C1C2_CIITA',
'ISLET1_B_SCT_C1_CIITA_TYK2_PE',
'ISLET1_B_SCT_C2_CIITA_TYK2_PE',
'ISLET1_B_SCT_C1C2_CIITA_TYK2_PE',
})
ARM1B_SCOPED_MEAN_KEYS = frozenset({
'obs_stage7_yield_ratio',
'obs_cd47_fold',
'obs_ifng_hla_dr_dq_negative_pct',
})
GLOBAL_CANONICAL_ESTIMAND_SCALES = frozenset({
'canonical_endpoint_contract_units_v0.8.0',
'canonical_v0.8.0',
})
ALLOWED_ESTIMAND_SCALES_BY_MEAN_KEY = {
'obs_stage7_yield_ratio': frozenset({
'normalized_ratio_to_unedited_wt_control_closed_interval_[0.0, 2.0]',
'normalized_ratio_to_unedited_wt_control',
'ratio_to_wt_control',
}) | GLOBAL_CANONICAL_ESTIMAND_SCALES,
'obs_cd47_fold': frozenset({
'fold_over_endogenous_baseline_closed_interval_[0.0, 100.0]',
'fold_over_endogenous_baseline',
'fold_over_wt_baseline',
}) | GLOBAL_CANONICAL_ESTIMAND_SCALES,
'obs_serpinb9_log10_kass': frozenset({
'log10_second_order_rate_constant_M_inv_s_inv_closed_interval_[0.0, 10.0]',
'log10_second_order_rate_constant_M_inv_s_inv',
'log10_kass_M_inv_s_inv',
}) | GLOBAL_CANONICAL_ESTIMAND_SCALES,
'obs_icasp9_log10_kill': frozenset({
'log10_clonal_depletion_kill_depth_closed_interval_[0.0, 10.0]',
'log10_clonal_depletion_kill_depth',
'log10_kill_depth',
}) | GLOBAL_CANONICAL_ESTIMAND_SCALES,
'obs_pouch_min_po2_mmhg': frozenset({
'min_14d_slab_po2_mmhg_closed_interval_[0.0, 160.0]',
'min_14d_slab_po2_mmhg',
'mmHg',
}) | GLOBAL_CANONICAL_ESTIMAND_SCALES,
'obs_pouch_max_h2o2_uM': frozenset({
'max_14d_slab_h2o2_uM_closed_interval_[0.0, 100.0]',
'max_14d_slab_h2o2_uM',
'uM',
}) | GLOBAL_CANONICAL_ESTIMAND_SCALES,
'obs_pouch_max_ph': frozenset({
'max_14d_pouch_alkaline_ph_closed_interval_[6.0, 9.0]',
'max_14d_pouch_alkaline_ph',
'pH',
}) | GLOBAL_CANONICAL_ESTIMAND_SCALES,
'obs_ifng_hla_dr_dq_negative_pct': frozenset({
'ifng_48h_hla_dr_dq_negative_cell_percentage_closed_interval_[0.0, 100.0]',
'ifng_48h_hla_dr_dq_negative_cell_percentage',
'percentage_0_to_100',
}) | GLOBAL_CANONICAL_ESTIMAND_SCALES,
}
ALL_ALLOWED_ESTIMAND_SCALES = frozenset().union(*ALLOWED_ESTIMAND_SCALES_BY_MEAN_KEY.values())
_PRODUCT_CONTRACT_MODULE_CACHE: dict[tuple[str, Any, Any], Any] = {}