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_joint_stratum_nk_lysis_pct',
'obs_l2_v3_joint_stratum_nk_lysis_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',
'syn_5xisre_cd200_in_design_y',
'has_intronic_mir_cd276_pvr',
'rnai_specific_benefit_claimed',
's11_replicate_n',
'per_locus_segmented_baf',
'post_edit_per_locus_segmented_baf',
'phasing_verified',
'cis_verified',
'wt_inducibility_verified',
'rnai_attribution_verified',
'ciita_locus2_genotype_copy_class',
'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',
}
unknown_keys = sorted(set(observations) - set(spec_by_mean) - set(spec_by_se) - allowed_boolean_and_meta_flags)
if unknown_keys:
raise ValueError(f'Unrecognized Stage-0 decision-tree observation keys: {unknown_keys}')
for _str_meta_k in (
'donor_seedline_id',
'device_assembly_id',
'physical_route_id',
'assay_campaign_id',
'reset_prior_safety_stop_target_category',
'submitter_id',
'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',
'background_id',
'mcb_id',
'l2_v3_donor_id',
'tier6b_presort_lineage_panel',
'tier6b_clonogenic_risk_unit',
):
if _str_meta_k in observations and observations[_str_meta_k] is not None:
_sv = observations[_str_meta_k]
if not isinstance(_sv, str) or not _sv.strip() or len(_sv) > 120:
raise ValueError(f'{_str_meta_k} must be a nonempty string of at most 120 characters (IIP-0024 / IIP-0028; DEC-103 / DEC-106)')
if 'bound_c1_c5_pair_sha256' in observations and observations['bound_c1_c5_pair_sha256'] is not None:
_bsha = observations['bound_c1_c5_pair_sha256']
if not isinstance(_bsha, str) or not re.fullmatch(r'[0-9a-f]{64}', _bsha.strip()):
raise ValueError('bound_c1_c5_pair_sha256 must be a lowercase 64-character SHA-256 hex digest (IIP-0026; DEC-105)')
# Pre-normalization strict integer check on count, scored-cell, donor, trial, and replicate denominators (IIP-0024; DEC-103):
non_integer_scored_cell_or_trial_denominator = False
for _int_k in STAGE0_STRICT_INTEGER_COUNT_AND_DENOMINATOR_KEYS:
if _int_k in observations and observations[_int_k] not in ('UNAVAILABLE', None):
_raw_iv = observations[_int_k]
if isinstance(_raw_iv, bool):
raise ValueError(f'{_int_k} must be an integer count, not boolean (IIP-0024; DEC-103)')
_dec_iv = finite_decimal(_raw_iv, _int_k)
if abs(_dec_iv - round(_dec_iv)) > 1e-9 or _dec_iv < 0.0:
non_integer_scored_cell_or_trial_denominator = True
if 'prior_variant_safety_status' in observations and observations['prior_variant_safety_status'] is not None:
pvs_val = observations['prior_variant_safety_status']
if not isinstance(pvs_val, str) or pvs_val.strip() not in ALLOWED_PRIOR_VARIANT_SAFETY_STATUSES:
raise ValueError(
f"Invalid prior_variant_safety_status {pvs_val!r}; must be one of {sorted(ALLOWED_PRIOR_VARIANT_SAFETY_STATUSES)} (AUDIT-REF; DEC-071)"
)
for _adj_k, _adj_allowed in (
('adjunct_conditioning_history_arm', ALLOWED_ADJUNCT_CONDITIONING_HISTORY_ARMS),
('adjunct_depletion_mode', ALLOWED_ADJUNCT_DEPLETION_MODES),
('adjunct_sa_fhl1_status', ALLOWED_ADJUNCT_SA_FHL1_STATUSES),
('adjunct_immune_responder_history', ALLOWED_ADJUNCT_IMMUNE_RESPONDER_HISTORIES),
('knockin_splice_challenger_arm', ALLOWED_KNOCKIN_SPLICE_CHALLENGER_ARMS),
('knockin_locus4_orientation', ALLOWED_KNOCKIN_LOCUS4_ORIENTATIONS),
('s10_hlae_floor_mode', ALLOWED_S10_HLAE_FLOOR_MODES),
('b2_tyk2_recipient_genotype_stratum', ALLOWED_B2_TYK2_RECIPIENT_GENOTYPE_STRATA),
('b2_tyk2_hlac_allele', ALLOWED_B2_TYK2_HLAC_ALLELES),
('s6_cluster_size_arm', ALLOWED_S6_CLUSTER_SIZE_ARMS),
('p05_barrier_slab_geometry_mode', ALLOWED_P05_BARRIER_SLAB_GEOMETRY_MODES),
('design_z_divider_arm', ALLOWED_DESIGN_Z_DIVIDER_ARMS),
('p05_catalase_uniprot_accession', ALLOWED_P05_CATALASE_UNIPROT_ACCESSIONS),
('cuff_bioconjugation_arm', ALLOWED_CUFF_BIOCONJUGATION_ARMS),
('cuff_serum_challenge_stratum', ALLOWED_CUFF_SERUM_CHALLENGE_STRATA),
('rest_ocr_coupon_arm', ALLOWED_REST_OCR_COUPON_ARMS),
('conditioning_4arm_arm', ALLOWED_CONDITIONING_4ARM_ARMS),
('conditioning_washout_analyte_scope', ALLOWED_CONDITIONING_WASHOUT_ANALYTE_SCOPES),
('track2_rescue_route', ALLOWED_TRACK2_RESCUE_ROUTES),
('design_y_integrase_modality', ALLOWED_DESIGN_Y_INTEGRASE_MODALITIES),
('design_y_silencing_modality', ALLOWED_DESIGN_Y_SILENCING_MODALITIES),
('design_y_payload_arm', ALLOWED_DESIGN_Y_PAYLOAD_ARMS),
('contrast_b1_geometry_arm', ALLOWED_CONTRAST_B1_GEOMETRY_ARMS),
('contrast_b2_perfusion_and_retrieval_arm', ALLOWED_CONTRAST_B2_ARMS),
('contrast_b3_donor_iec_arm', ALLOWED_CONTRAST_B3_DONOR_IEC_ARMS),
('tyk2_pe_modality', ALLOWED_TYK2_PE_MODALITIES),
('iip0026_schema_era', ALLOWED_IIP0026_SCHEMA_ERAS),
):
if _adj_k in observations and observations[_adj_k] is not None:
_adj_v = observations[_adj_k]
if not isinstance(_adj_v, str) or _adj_v.strip() not in _adj_allowed:
raise ValueError(
f"Invalid {_adj_k} {_adj_v!r}; must be one of {sorted(_adj_allowed)} (IIP-0012 / IIP-0015 / IIP-0016; DEC-091 / DEC-092 / DEC-094)"
)
defaulted_se_set = set(defaulted_se_keys or ())
validated_stage0: dict[str, float] = {}
validated_stage0_se: dict[str, float] = {}
se_provenance_by_mean: dict[str, str] = {}
for mk, (eid, _mk, sk, lo, hi, _unit) in spec_by_mean.items():
if mk in observations and observations[mk] != 'UNAVAILABLE' and observations[mk] is not None:
val = finite_decimal(observations[mk], mk)
if not lo <= val <= hi:
raise ValueError(f'{mk} ({eid}) must be in [{lo}, {hi}]')
validated_stage0[mk] = val
if sk in observations and observations[sk] not in ('UNAVAILABLE', None) and sk not in defaulted_se_set and mk not in defaulted_se_set:
se_val = finite_decimal(observations[sk], sk)
min_se = (
contract['minimum_se']
if mk in primary_spec_by_mean and primary_spec_by_mean[mk] and default_se_by_mean.get(mk) is None
else STAGE0_CUSTOM_MINIMUM_SE.get(mk, contract['minimum_se'])
)
if se_val < min_se:
raise ValueError(f'{sk} must be >= {min_se}')
validated_stage0_se[sk] = se_val
se_provenance_by_mean[mk] = 'EXPLICIT_SE_SUPPLIED'
else:
# Unified scale-aware SE fallback across direct evaluate_stage0_decision_tree and normalize_measurements (AUDIT-REF, AUDIT-REF, R7-AUDIT-REF & AUDIT-REF; DEC-041/050/062/071):
imp_se = (
finite_decimal(observations[sk], sk)
if (sk in observations and observations[sk] not in ('UNAVAILABLE', None))
else STAGE0_CUSTOM_DEFAULT_SE.get(
mk,
default_se_by_mean.get(mk, _scale_aware_stage0_default_se(mk, lo, hi)),
)
)
min_se_imp = (
contract['minimum_se']
if mk in primary_spec_by_mean and primary_spec_by_mean[mk] and default_se_by_mean.get(mk) is None
else STAGE0_CUSTOM_MINIMUM_SE.get(mk, contract['minimum_se'])
)
if imp_se < min_se_imp:
raise ValueError(f'{sk} must be >= {min_se_imp}')
validated_stage0_se[sk] = imp_se
se_provenance_by_mean[mk] = 'DEFAULT_SE_IMPUTED_NOT_EXPLICIT'
def _explicit_se(mean_key: str) -> float:
if mean_key not in validated_stage0 or se_provenance_by_mean.get(mean_key) != 'EXPLICIT_SE_SUPPLIED':
return 0.0
row = spec_by_mean.get(mean_key)
if not row:
return 0.0
return float(validated_stage0_se.get(row[2], 0.0))
def _validated_se(mean_key: str) -> float:
if mean_key not in validated_stage0:
return 0.0
row = spec_by_mean.get(mean_key)
if not row:
return 0.0
return float(validated_stage0_se.get(row[2], 0.0))
stage0_replicates_below_6_hold = False
crit_95_mult = 1.644854
if 'obs_stage0_independent_lot_replicates_n' in validated_stage0:
_n_rep_raw = validated_stage0['obs_stage0_independent_lot_replicates_n']
if abs(_n_rep_raw - round(_n_rep_raw)) > 1e-9 or int(round(_n_rep_raw)) < 6:
stage0_replicates_below_6_hold = True
else:
crit_95_mult = student_t_ppf_one_sided_95(float(int(round(_n_rep_raw)) - 1))
def _upper95(mean_key: str, default: float = 0.0) -> float:
if mean_key not in validated_stage0:
return default
return float(validated_stage0[mean_key]) + crit_95_mult * _validated_se(mean_key)
def _lower95(mean_key: str, default: float = 0.0) -> float:
if mean_key not in validated_stage0:
return default
return float(validated_stage0[mean_key]) - crit_95_mult * _validated_se(mean_key)
# Exact one-sided 95% Student-t multiplier defaulting to df = 5 (n = 6 minimum lot replicates) when replicate count is omitted (IIP-0025; DEC-104):
_student_t_mult_df5_default = (
crit_95_mult
if ('obs_stage0_independent_lot_replicates_n' in validated_stage0 and not stage0_replicates_below_6_hold)
else student_t_ppf_one_sided_95(5.0)
)
def _upper95_student_t(mean_key: str, default: float = 0.0) -> float:
if mean_key not in validated_stage0:
return default
return float(validated_stage0[mean_key]) + _student_t_mult_df5_default * _validated_se(mean_key)
def _lower95_student_t(mean_key: str, default: float = 0.0) -> float:
if mean_key not in validated_stage0:
return default
return float(validated_stage0[mean_key]) - _student_t_mult_df5_default * _validated_se(mean_key)
serpinb9_h0 = validated_stage0.get('obs_serpinb9_hour0_uM', validated_stage0.get('obs_gate0c_hour0_serpinb9_uM', 0.35))
serpinb9_h0_lower95 = (
_lower95('obs_serpinb9_hour0_uM', serpinb9_h0)
if 'obs_serpinb9_hour0_uM' in validated_stage0
else _lower95('obs_gate0c_hour0_serpinb9_uM', serpinb9_h0)
)
lysis_2h = validated_stage0.get('obs_regimeII_lysis_2h_pct', validated_stage0.get('obs_gate0c_2h_lysis_pct', 5.0))
lysis_2h_upper95 = (
_upper95('obs_regimeII_lysis_2h_pct', lysis_2h)
if 'obs_regimeII_lysis_2h_pct' in validated_stage0
else _upper95('obs_gate0c_2h_lysis_pct', lysis_2h)
)
chop_fold_candidates = []
if 'obs_chop_coincidence_fold' in validated_stage0:
chop_fold_candidates.append(validated_stage0['obs_chop_coincidence_fold'])
if 'obs_gate0e_chop_log2fc' in validated_stage0:
chop_fold_candidates.append(2.0 ** validated_stage0['obs_gate0e_chop_log2fc'])
chop_fold = max(chop_fold_candidates) if chop_fold_candidates else (2.0 ** 0.4)
hc10_fold_candidates = []
if 'obs_hc10_surface_fold_wt' in validated_stage0:
hc10_fold_candidates.append(validated_stage0['obs_hc10_surface_fold_wt'])
if 'obs_gate0e_hc10_surface_mfi_ratio' in validated_stage0:
hc10_fold_candidates.append(validated_stage0['obs_gate0e_hc10_surface_mfi_ratio'])
hc10_fold = max(hc10_fold_candidates) if hc10_fold_candidates else 1.1
# Default unmeasured capsule thickness to 10.0 um (<= 10.4 um) so S9_Chronic does not falsely fire on omission (AUDIT-REF; DEC-041):
has_chronic_capsule_obs = ('obs_capsule_dz_um' in validated_stage0) or ('obs_gate0f_capsule_thickness_um' in validated_stage0)
capsule_dz = validated_stage0.get('obs_capsule_dz_um', validated_stage0.get('obs_gate0f_capsule_thickness_um', 10.0))
capsule_dz_upper95 = (
_upper95('obs_capsule_dz_um', capsule_dz)
if 'obs_capsule_dz_um' in validated_stage0
else _upper95('obs_gate0f_capsule_thickness_um', capsule_dz)