OpenIslet

scripts/wetlab_contract.py

One measurement contract for Python ingestion and generated MCP metadata.

script Release v0.8.0 gen-eb955f8266035aba 913 KB · 68 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/wetlab_contract.py · SHA-256: 6bb3955530f8f05d…

        gate_id='GATE0S_SHEDDING_VIABLE_OUTGROWTH',
        k=viable_k,
        n=viable_n,
        max_u95_fraction=1e-6,
        require_observed_zero=True,
        eta_spike_recovery_l95=viable_eta_l95,
        f_clonogenic=viable_f_clonogenic,
    )
    if vi_res['status'] != 'PASS':
        return {'gate_pass': False, 'status': vi_res['status'], 'failed_assay': 'viable_outgrowth', 'detail': vi_res}
    rec_l95: float | None = None
    if day90_recovery_mean is not None or day90_recovery_se is not None:
        if (
            not _is_strict_int_iip0024(day90_replicates_n)
            or day90_replicates_n < 6
            or not _is_strict_finite_number_iip0024(day90_recovery_mean)
            or not _is_strict_finite_number_iip0024(day90_recovery_se)
            or float(day90_recovery_se) <= 0.0
        ):
            return {'gate_pass': False, 'status': 'HOLD_INVALID_DAY90_EN_BLOC_RECOVERY_INPUT'}
        t95_r = student_t_ppf_one_sided_95(float(day90_replicates_n - 1))
        rec_l95 = float(day90_recovery_mean) - t95_r * float(day90_recovery_se)
        if rec_l95 < 0.99:
            return {
                'gate_pass': False,
                'status': 'HOLD_S9_EXPLANT_EN_BLOC_RECOVERY_BELOW_99PCT',
                'day90_recovery_lower95': rec_l95,
            }
    return {
        'gate_pass': True,
        'status': 'CLEARED_GATE0S_DUAL_SHEDDING_AND_SEPARATED_RECOVERY',
        'ddpcr_u95': dd_res['u95_binomial'],
        'viable_u95': vi_res['u95_binomial'],
        'day90_recovery_lower95': rec_l95,
    }


# ============================================================================
# Shared Registry-Bound Stage-0 Research & Molecular Guardrail Evaluator
# Decoupled from Bayesian Calibration Admission (IIP-0026; DEC-105)
# ============================================================================
DESIGN_B_FASTA_SHA256 = '4bb20389773c76b2705031ba675487825dfbd94d920a692cde75b7d56af22aa4'
DESIGN_B_C1_C5_PAIR_SHA256 = '82c351af082e0f97361e715c36e2ab5872b8d097efa1c9f59dfda53ea60496ea'

IIP0026_REQUIRED_CORE_S9_OBS_KEYS: tuple[str, ...] = (
    'obs_icasp9_log10_kill',
    'obs_icasp9_log10_kill_se',
    'obs_tp53_ppm1d_bcor_vaf',
    'obs_tp53_ppm1d_bcor_vaf_se',
    'obs_tp53_ppm1d_bcor_duplex_depth',
    'obs_castseq_translocation_freq',
    'obs_castseq_translocation_se',
    'obs_castseq_duplex_or_amplicon_depth',
    'obs_mcb_clonogenic_survivor_count_k',
    'obs_mcb_effective_clonogenic_trials',
)

IIP0026_FORBIDDEN_CALLER_OVERRIDE_KEYS: frozenset[str] = frozenset({
    'lifecycle_state',
    'iip0026_lifecycle_state',
    'execution_supported',
    'override_execution_supported',
    'force_state4_promotion',
    'bypass_hlac_phased_gate',
    'bypass_pe4max_msi_gate',
})

IIP0026_ALLOWED_MOLECULAR_OBS_KEYS: frozenset[str] = frozenset({
    'bound_c1_c5_pair_sha256',
    'donor_seed_gnomad_target_site_wgs_verified',
    'post_edit_per_locus_segmented_baf',
    'per_locus_segmented_baf',
    'obs_post_edit_segmented_baf_chr19q',
    'obs_post_edit_segmented_baf_chr11p15',
    'obs_post_edit_segmented_baf_chr6p21',
    'post_edit_reciprocal_mosaic_sv_or_clonal_zygosity_verified',
    'design_b_hlac_phased_guide_cfd_max',
    'obs_design_b_hlac_phased_guide_cfd_max',
    '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_dt9_matched_hlae_only_control_delta_ratio',
    'obs_design_b_hlac_dt9_matched_hlae_only_control_delta_ratio',
    'design_b_hlac_allele_specific_surface_or_phased_mrna_verified',
    'design_b_locus5_5prime_race_coord_bp',
    'obs_design_b_locus5_5prime_race_coord_bp',
    'design_b_locus5_3prime_race_coord_bp',
    'obs_design_b_locus5_3prime_race_coord_bp',
    'design_b_locus5_pdl1_5prime_race_coord_bp',
    'design_b_locus5_race_umi_n_eff',
    'obs_design_b_locus5_race_umi_n_eff',
    'design_b_locus5_aberrant_umi_k',
    'obs_design_b_locus5_aberrant_umi_k',
    'b_sct_ciita_exon5_and_trimer_verified',
    'tyk2_pe_modality',
    'tyk2_phased_haplotype_sap_verified',
    'tyk2_pe4max_pentaplex_msi_shifts_k',
    'obs_tyk2_pe4max_pentaplex_msi_shifts_k',
    'tyk2_pe4max_wgs_repeat_indels_clone',
    'obs_tyk2_pe4max_wgs_repeat_indels_clone',
    'tyk2_pe4max_wgs_repeat_indels_ctrl',
    'obs_tyk2_pe4max_wgs_repeat_indels_ctrl',
    'tyk2_pe4max_coding_or_splice_de_novo_indels',
    'obs_tyk2_pe4max_coding_or_splice_de_novo_indels',
    'schema_era',
    'iip0026_schema_era',
    'adjunct_conditioning_history_arm',
    'adjunct_depletion_mode',
    'adjunct_sa_fhl1_status',
    'adjunct_immune_responder_history',
    'device_assembly_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',
    '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',
    'iip0029_twoclock_record',
    'background_id',
    'mcb_id',
    'donor_seedline_id',
    'seed_line_id',
    'l2_v3_donor_id',
    'donor_id',
    'sample_id',
    'sample_unit_id',
    'replicates_n',
    'sample_n',
    's11_replicate_n',
    'tier6b_presort_lineage_panel',
    'tier6b_clonogenic_risk_unit',
    'tier6b_sorted_lot_observations',
    'iip0031_locus2_record',
    'rnai_specific_benefit_claimed',
    'phasing_verified',
    'cis_verified',
    'wt_inducibility_verified',
    'rnai_attribution_verified',
    'obs_l2_v3_chr16_ha_wgs_pass',
    'obs_l2_v3_chr16_ha_wgs_variant_count',
    'ciita_locus2_genotype_copy_class',
    'rnai_attribution_scramble_control_id',
    'rnai_attribution_scramble_background_id',
    'rnai_attribution_intronless_control_id',
    'rnai_attribution_intronless_background_id',
    'has_intronic_mir_cd276_pvr',
    'syn_5xisre_cd200_in_design_y',
})


def evaluate_pe4max_piecewise_repeat_indel_cap_iip0026(
    c_clone: Any,
    c_ctrl: Any,
    coding_or_splice_de_novo_indels: Any,
) -> str:
    """
    Evaluate held PE4max clonal WGS repeat-indel cap:
      - 0 coding/splice de novo indels,
      - C_clone <= C_ctrl + 5 for C_ctrl <= 25,
      - C_clone <= floor(1.2 * C_ctrl) for C_ctrl > 25 (IIP-0026; DEC-105).
    """
    for v in (c_clone, c_ctrl, coding_or_splice_de_novo_indels):
        if not _is_strict_int_iip0024(v) or v < 0:
            return 'HOLD_MISSING_PE4MAX_REPEAT_INDEL_EVIDENCE'
    if coding_or_splice_de_novo_indels != 0:
        return 'FAIL_PE4MAX_CODING_OR_SPLICE_DE_NOVO_INDEL_DETECTED'
    cap = (c_ctrl + 5) if c_ctrl <= 25 else int(math.floor(1.2 * c_ctrl))
    return 'PASS' if c_clone <= cap else 'FAIL_PE4MAX_REPEAT_INDEL_CAP_EXCEEDED'


def _is_integral_count_iip0026(val: Any) -> bool:
    return _is_strict_int_iip0024(val) or (
        isinstance(val, float) and math.isfinite(val) and val.is_integer()
    )


def _derive_versioned_product_registry_entry_iip0026(
    pdef: dict[str, Any],
) -> dict[str, Any]:
    pid = str(pdef['product_variant_id'])
    exec_sup = bool(pdef.get('execution_supported', False))
    lifecycle_state = str(
        pdef.get(
            'product_lifecycle_state',
            pdef.get(
                'lifecycle_state',
                (
                    'EXECUTION_SUPPORTED_QUALIFIED_PRODUCT'
                    if exec_sup
                    else (
                        'STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC'
                        if pid in ('ISLET1_B2_5LOCUS_BASE', 'ISLET1_B2_5LOCUS_TYK2_PE') or isinstance(pdef.get('staged_locus2_modeb_donor_binding'), dict)
                        else 'RESEARCH_COMPARATOR_UNSUPPORTED_VARIANT_HOLD'
                    )
                ),
            ),
        )
    )
    bound_sha: str | None = None
    binding_block = pdef.get('staged_design_b_donor_reference_binding')
    if isinstance(binding_block, dict) and isinstance(binding_block.get('bound_c1_c5_pair_sha256'), str):
        bound_sha = binding_block['bound_c1_c5_pair_sha256'].strip()
    elif pid in ('ISLET1_B2_5LOCUS_BASE', 'ISLET1_B2_5LOCUS_TYK2_PE'):
        bound_sha = DESIGN_B_C1_C5_PAIR_SHA256
    is_b_sct = pid.startswith('ISLET1_B_SCT_')
    is_endogenous_hlac_b = (pdef.get('family') == 'B') and (not is_b_sct)
    is_tyk2_pe = ('TYK2_PE' in pid) or ('Pro1104Ala' in json.dumps(pdef.get('alleles', {})))
    is_design_y = pid.startswith('ISLET1_Y_') or (pdef.get('family') == 'Y')
    return {
        'product_variant_id': pid,
        'family': pdef.get('family'),
        'execution_supported': exec_sup,
        'lifecycle_state': lifecycle_state,
        'bound_c1_c5_pair_sha256': bound_sha,
        'requires_endogenous_hlac_and_locus5_gates': is_endogenous_hlac_b,
        'requires_b_sct_gates': is_b_sct,
        'requires_tyk2_pe_gates': is_tyk2_pe,
        'is_held_design_y': is_design_y,
        'required_baf_loci': ('chr19q', 'chr11p15', 'chr6p21') if is_endogenous_hlac_b else ('chr19q', 'chr11p15'),
    }


_IIP0026_DESIGNB_TYK2_ALIAS_PAIRS: tuple[tuple[str, str, bool], ...] = (
    ('design_b_hlac_phased_guide_cfd_max', 'obs_design_b_hlac_phased_guide_cfd_max', False),
    ('design_b_hlac_dt9_matched_hlae_only_control_delta_ratio', 'obs_design_b_hlac_dt9_matched_hlae_only_control_delta_ratio', False),
    ('design_b_locus5_5prime_race_coord_bp', 'obs_design_b_locus5_5prime_race_coord_bp', True),
    ('design_b_locus5_3prime_race_coord_bp', 'obs_design_b_locus5_3prime_race_coord_bp', True),
    ('design_b_locus5_race_umi_n_eff', 'obs_design_b_locus5_race_umi_n_eff', True),
    ('design_b_locus5_aberrant_umi_k', 'obs_design_b_locus5_aberrant_umi_k', True),
    ('tyk2_pe4max_pentaplex_msi_shifts_k', 'obs_tyk2_pe4max_pentaplex_msi_shifts_k', True),
    ('tyk2_pe4max_wgs_repeat_indels_clone', 'obs_tyk2_pe4max_wgs_repeat_indels_clone', True),
    ('tyk2_pe4max_wgs_repeat_indels_ctrl', 'obs_tyk2_pe4max_wgs_repeat_indels_ctrl', True),
    ('tyk2_pe4max_coding_or_splice_de_novo_indels', 'obs_tyk2_pe4max_coding_or_splice_de_novo_indels', True),
)


def _baf_locus_discordant_iip0031(val: Any) -> bool:
    """Exact Decimal check for |BAF - 0.50| > 0.05 (inclusive at 0.45 and 0.55; IIP-0031; DEC-110)."""
    if not _is_strict_finite_number_iip0024(val):