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…

    _, _s9_rep_conflict_groups, _s9_rep_has_conflict = _resolve_s9_replicate_counts_detailed_iip0031(
        _direct_containers,
        flag_explicit_none=True,
    )
    s9_replicate_count_conflict = bool(payload.get('_s9_replicate_count_conflict') is True or _s9_rep_has_conflict)
    stage0_conflicting_measurement = bool(
        payload.get('_stage0_conflicting_measurement') is True
        or _direct_meas_conflict
        or _direct_malformed_container
        or _direct_nonstring_key
        or _alias_or_baf_conflict_d
        or _tree_alias_conflict
    )
    if stage0_conflicting_measurement:
        _confl_reasons: list[str] = list(_cand_iip0026_fails)
        if 'HOLD_CONFLICTING_STAGE0_MEASUREMENT' not in _confl_reasons:
            _confl_reasons.append('HOLD_CONFLICTING_STAGE0_MEASUREMENT')
        if s9_replicate_count_conflict and 'HOLD_S9_INVALID_OR_CONFLICTING_REPLICATE_COUNT' not in _confl_reasons:
            _confl_reasons.append('HOLD_S9_INVALID_OR_CONFLICTING_REPLICATE_COUNT')
        _confl_status = _cand_iip0026_fails[0] if _cand_iip0026_fails else 'HOLD_CONFLICTING_STAGE0_MEASUREMENT'
        return {
            'overall_status': _confl_status,
            'lot_release_readiness_tier': _confl_status,
            'iip0026_reasons': _confl_reasons,
            'hard_stop_precedence_winner': None,
            'lifecycle_state': lifecycle_state,
            'execution_supported': False,
            'effective_execution_permitted': False,
            'switch_decisions': switch_decisions,
            **_t6b_common,
        }
    missing_obs = [k for k in IIP0026_REQUIRED_CORE_S9_OBS_KEYS if k not in safe_s0_obs]
    if (
        missing_obs
        or float(canonical_payload['obs_tp53_ppm1d_bcor_duplex_depth']) <= 0.0
        or float(canonical_payload['obs_castseq_duplex_or_amplicon_depth']) <= 0.0
        or not _is_integral_count_iip0026(canonical_payload['obs_mcb_clonogenic_survivor_count_k'])
        or not _is_integral_count_iip0026(canonical_payload['obs_mcb_effective_clonogenic_trials'])
        or int(canonical_payload['obs_mcb_effective_clonogenic_trials']) <= 0
    ):
        _missing_s9_status = (
            'HOLD_S9_INVALID_OR_CONFLICTING_REPLICATE_COUNT'
            if s9_replicate_count_conflict
            else 'HOLD_MISSING_CORE_S9_MOLECULAR_OBSERVATIONS'
        )
        _missing_s9_reasons = (
            ['HOLD_S9_INVALID_OR_CONFLICTING_REPLICATE_COUNT', 'HOLD_MISSING_CORE_S9_MOLECULAR_OBSERVATIONS']
            if s9_replicate_count_conflict
            else ['HOLD_MISSING_CORE_S9_MOLECULAR_OBSERVATIONS']
        )
        return {
            'overall_status': _missing_s9_status,
            'lot_release_readiness_tier': _missing_s9_status,
            'iip0026_reasons': _missing_s9_reasons,
            'hard_stop_precedence_winner': None,
            'lifecycle_state': lifecycle_state,
            'execution_supported': False,
            'effective_execution_permitted': False,
            'switch_decisions': switch_decisions,
            **_t6b_common,
        }

    reasons: list[str] = list(tree_eval['s9_frequency_assay_holds'])
    for _, count_key in S9_FREQUENCY_ASSAY_KEYS.values():
        if any(isinstance(_c, dict) and count_key in _c for _c in _direct_containers) and count_key not in safe_s0_obs:
            reasons.append('HOLD_S9_INVALID_OR_CONFLICTING_EVENT_COUNT')
            break
    if s9_replicate_count_conflict:
        reasons.append('HOLD_S9_INVALID_OR_CONFLICTING_REPLICATE_COUNT')
    sera_val = canonical_payload.get('iip0026_schema_era', canonical_payload.get('schema_era'))
    if isinstance(sera_val, str) and sera_val.startswith('LEGACY_PRE_'):
        reasons.append('HOLD_PROVISIONAL_LEGACY_SCHEMA_MISSING_IIP0026_EVIDENCE')

    if canonical_payload.get('donor_seed_gnomad_target_site_wgs_verified') is not True:
        reasons.append('HOLD_MISSING_DONOR_TARGET_WGS')

    per_locus_baf = _clean_baf_d if _clean_baf_d is not None else _extract_per_locus_baf_dict_iip0026(canonical_payload)
    sv_recip = canonical_payload.get('post_edit_reciprocal_mosaic_sv_or_clonal_zygosity_verified')
    req_loci = reg['required_baf_loci']
    if (
        not isinstance(per_locus_baf, dict)
        or any(loc not in per_locus_baf or not _is_strict_finite_number_iip0024(per_locus_baf[loc]) for loc in req_loci)
        or sv_recip is not True
    ):
        reasons.append('HOLD_MISSING_SEGMENTED_PHASED_BAF_SURVEILLANCE')
    else:
        if any(_baf_locus_discordant_iip0031(per_locus_baf[loc]) for loc in req_loci):
            reasons.append('FAIL_DISCORDANT_PER_LOCUS_SEGMENTED_BAF')

    if reg['requires_endogenous_hlac_and_locus5_gates']:
        cfd_max = canonical_payload.get('obs_design_b_hlac_phased_guide_cfd_max', canonical_payload.get('design_b_hlac_phased_guide_cfd_max'))
        sep_pass = canonical_payload.get('design_b_hla_ab_separated_pass_delivery_verified')
        chr6_loh = canonical_payload.get('design_b_chr6p21_1p41mb_loh_sv_cleared')
        if (
            not _is_strict_finite_number_iip0024(cfd_max)
            or not (Decimal('0') <= Decimal(str(cfd_max)) < Decimal('0.05'))
            or sep_pass is not True
            or chr6_loh is not True
        ):
            reasons.append('HOLD_MISSING_ENDOGENOUS_DESIGNB_HLAC_PHASED_CLEARANCE')

        dt9_pos = canonical_payload.get('design_b_hlac_dt9_positive')
        hlae_3d12_pos = canonical_payload.get('design_b_hlae_3d12_positive')
        dt9_delta = canonical_payload.get(
            'obs_design_b_hlac_dt9_matched_hlae_only_control_delta_ratio',
            canonical_payload.get('design_b_hlac_dt9_matched_hlae_only_control_delta_ratio'),
        )
        hlac_orth = canonical_payload.get('design_b_hlac_allele_specific_surface_or_phased_mrna_verified')
        if dt9_pos is not True or hlae_3d12_pos is not True:
            if 'HOLD_MISSING_ENDOGENOUS_DESIGNB_HLAC_PHASED_CLEARANCE' not in reasons:
                reasons.append('HOLD_MISSING_ENDOGENOUS_DESIGNB_HLAC_PHASED_CLEARANCE')
        elif dt9_delta is None and hlac_orth is not True:
            reasons.append('HOLD_MISSING_HLAC_SPECIFICITY_CONTROL_FOR_DT9_HLAE_CROSSREACTIVITY')
        elif dt9_delta is not None:
            if not _is_strict_finite_number_iip0024(dt9_delta) or Decimal(str(dt9_delta)) <= Decimal('0'):
                reasons.append('HOLD_MISSING_HLAC_SPECIFICITY_CONTROL_FOR_DT9_HLAE_CROSSREACTIVITY')
            elif Decimal(str(dt9_delta)) < Decimal('2') and hlac_orth is not True:
                reasons.append('FAIL_HLAC_SURFACE_LOSS_MASKED_BY_DT9_HLAE_CROSSREACTIVITY')

        r5_bp = canonical_payload.get('obs_design_b_locus5_5prime_race_coord_bp', canonical_payload.get('design_b_locus5_5prime_race_coord_bp'))
        r3_bp = canonical_payload.get('obs_design_b_locus5_3prime_race_coord_bp', canonical_payload.get('design_b_locus5_3prime_race_coord_bp'))
        max_donor_bp = 4078 if reg['bound_c1_c5_pair_sha256'] == DESIGN_B_C1_C5_PAIR_SHA256 else 10000
        if r5_bp is None or r3_bp is None:
            reasons.append('HOLD_MISSING_DESIGNB_LOCUS5_RACE_COORDINATES')
        elif not (
            _is_strict_int_iip0024(r5_bp)
            and _is_strict_int_iip0024(r3_bp)
            and 0 < r5_bp < r3_bp <= max_donor_bp
        ):
            reasons.append('FAIL_INVALID_RACE_COORDINATES')

        pdl1_r5 = canonical_payload.get('design_b_locus5_pdl1_5prime_race_coord_bp')
        if reg['bound_c1_c5_pair_sha256'] == DESIGN_B_C1_C5_PAIR_SHA256 and (pdl1_r5 is None or pdl1_r5 == 'UNRESOLVED'):
            reasons.append('HOLD_PENDING_5PRIME_RACE_TSS')
        elif pdl1_r5 == 'UNRESOLVED':
            reasons.append('HOLD_PENDING_5PRIME_RACE_TSS')
        elif pdl1_r5 is not None:
            if not _is_strict_int_iip0024(pdl1_r5) or pdl1_r5 <= 0 or pdl1_r5 > 2381:
                reasons.append('FAIL_INVALID_RACE_COORDINATES')
            elif pdl1_r5 <= 2308:
                reasons.append('FAIL_MATURE_TRANSCRIPT_INCLUDES_UPSTREAM_OUT_OF_FRAME_KOZAK_ORF')

        b_umi_n = canonical_payload.get('obs_design_b_locus5_race_umi_n_eff', canonical_payload.get('design_b_locus5_race_umi_n_eff'))
        b_umi_k = canonical_payload.get('obs_design_b_locus5_aberrant_umi_k', canonical_payload.get('design_b_locus5_aberrant_umi_k'))
        if not _is_strict_int_iip0024(b_umi_n) or b_umi_n < 3689 or not _is_strict_int_iip0024(b_umi_k) or b_umi_k < 0:
            reasons.append('HOLD_MISSING_DESIGNB_LOCUS5_TRANSCRIPT_UMI_3689')
        elif b_umi_k > 0:
            reasons.append('FAIL_DESIGNB_LOCUS5_CHIMERIC_TRANSCRIPT_DETECTED')
    elif reg['requires_b_sct_gates']:
        if canonical_payload.get('b_sct_ciita_exon5_and_trimer_verified') is not True:
            reasons.append('HOLD_MISSING_BSCT_CIITA_EXON5_AND_TRIMER_EVIDENCE')

    if reg['requires_tyk2_pe_gates']:
        pe_mod = canonical_payload.get('tyk2_pe_modality')
        if not isinstance(pe_mod, str) or pe_mod not in ALLOWED_TYK2_PE_MODALITIES or canonical_payload.get('tyk2_phased_haplotype_sap_verified') is not True:
            reasons.append('HOLD_MISSING_TYK2_PE_MODALITY_OR_PHASED_HAPLOTYPE')
        elif pe_mod == 'PE4MAX_MSI_GATED':
            msi_k = canonical_payload.get('obs_tyk2_pe4max_pentaplex_msi_shifts_k', canonical_payload.get('tyk2_pe4max_pentaplex_msi_shifts_k'))
            if msi_k is None or not _is_strict_int_iip0024(msi_k) or msi_k < 0:
                reasons.append('HOLD_MISSING_MSI')
            elif msi_k > 0:
                reasons.append('FAIL_MSI_DETECTED')
            pe_st = evaluate_pe4max_piecewise_repeat_indel_cap_iip0026(
                canonical_payload.get('obs_tyk2_pe4max_wgs_repeat_indels_clone', canonical_payload.get('tyk2_pe4max_wgs_repeat_indels_clone')),
                canonical_payload.get('obs_tyk2_pe4max_wgs_repeat_indels_ctrl', canonical_payload.get('tyk2_pe4max_wgs_repeat_indels_ctrl')),
                canonical_payload.get('obs_tyk2_pe4max_coding_or_splice_de_novo_indels', canonical_payload.get('tyk2_pe4max_coding_or_splice_de_novo_indels')),
            )
            if pe_st != 'PASS':
                if not (msi_k is None and pe_st == 'HOLD_MISSING_PE4MAX_REPEAT_INDEL_EVIDENCE'):
                    reasons.append(pe_st)

    for _cf in _cand_iip0026_fails:
        if _cf not in reasons:
            reasons.append(_cf)

    if reg['is_held_design_y']:
        reasons.append('HOLD_DESIGNY_EXPLORATORY_UNBIASED_CAPTURE_AND_63K_OR_90K_LOD_REQUIRED')

    # Propagate IIP-0029 two-clock/two-pulse & >138.3 IU Gate 0S escalation holds identically on all variants:
    _iip0029_tree_eval = tree_eval.get('iip0029_twoclock_maturation_and_repeated_challenge_evaluation')
    if isinstance(_iip0029_tree_eval, dict) and _iip0029_tree_eval.get('gate_pass') is not True:
        _r29 = str(_iip0029_tree_eval.get('status', 'HOLD_IIP0029_SUBGATE_FAILED'))
        if _r29 not in reasons:
            reasons.append(_r29)

    # Propagate IIP-0031 Rule S11 holds and mandatory sorted-lot Tier 6B per-fraction thinning qualification:
    if s11_eval.get('gate_pass') is not True:
        _r31_s11 = str(s11_eval.get('status', 'HOLD_S11_LOCUS2_GATE_FAILED'))
        if _r31_s11 not in reasons:
            reasons.append(_r31_s11)
    if tier6b_eval.get('gate_pass') is not True:
        _r31_6b = str(tier6b_eval.get('status', 'HOLD_TIER6B_UNQUALIFIED_FRACTION'))
        if _r31_6b not in reasons:
            reasons.append(_r31_6b)

    # Preserve stricter applicable Stage-0 tree holds on non-research-comparator executable variants:
    tree_tier = str(tree_eval['lot_release_readiness_tier'])
    if (
        not reasons
        and lifecycle_state != 'STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC'
        and registry_exec_supported
        and tree_tier.startswith(('HOLD_', 'NO_GO_', 'HARD_SAFETY_STOP'))
    ):
        reasons.append(str(tree_eval['resolved_architecture_assignments'].get('lot_maturation_status', tree_tier)))

    fails = [r for r in reasons if r.startswith('FAIL_')]
    if fails:
        status = fails[0]
    elif reasons:
        status = reasons[0]
    else:
        status = (
            'RESEARCH_COMPARATOR_STAGE0_PANEL_CLEARED_PENDING_STATE4_PROMOTION'
            if lifecycle_state == 'STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC'
            else 'STAGE0_IIP0026_MOLECULAR_GUARDRAILS_CLEARED'
        )
    effective_exec = bool(
        registry_exec_supported
        and len(reasons) == 0
        and lifecycle_state != 'STAGE0_RESEARCH_COMPARATOR_PENDING_ALLELE_QC'
    )
    return {
        'overall_status': status,
        'lot_release_readiness_tier': tree_tier if status.startswith('STAGE0_') else status,
        'iip0026_reasons': reasons,
        'hard_stop_precedence_winner': None,
        'lifecycle_state': lifecycle_state,
        'execution_supported': registry_exec_supported if len(reasons) == 0 else False,
        'effective_execution_permitted': effective_exec,
        'endogenous_hlac_gate_applied': reg['requires_endogenous_hlac_and_locus5_gates'],
        'b_sct_route_separated': reg['requires_b_sct_gates'],
        'switch_decisions': switch_decisions,
        **_t6b_common,
        **(
            {'iip0029_twoclock_maturation_and_repeated_challenge_evaluation': _iip0029_tree_eval}
            if isinstance(_iip0029_tree_eval, dict)
            else {}
        ),
    }


# ============================================================================
# Post-Depletion Gate 0d, Paired Intact-Plus-Increment CD16+ ADCC, Upstream B2
# Research-Comparator Authorization, Measured-Potency DEC-084 Mixture, and
# Visit/Lot/Sister-Bound 72h/d28/d84 Dual-Modality IAPP Evaluators
# (IIP-0028; DEC-106)
# ============================================================================
ITM2B_NM021999_5_CDS_SHA256 = '6fc8d3d7a9b4851a9b50c026d44f02e7d2539e122a0b727d2a5cc4ee93df8903'
ITM2B_NM021999_5_FASTA_SHA256 = '4a4cb15d0544884a62d86ebf4137c5284edad8210b6e32e74c2eb0aff005d13e'