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…

            _intact_d = Decimal(str(view['obs_l2_v3_intact_serum_adcc_lysis_pct']))
            _inc_d = Decimal(str(view['obs_l2_v3_igg_increment_adcc_lysis_pct']))
            _implied_dep_d = _intact_d - _inc_d
            if _implied_dep_d < Decimal('0') or _implied_dep_d > Decimal('100'):
                adcc_pair_invalid = True
                _add_h('HOLD_S11_INVALID_SE_OR_OUT_OF_RANGE_PHYSIOLOGICAL_READOUT')
            _dep_sup = view.get('obs_l2_v3_igg_depleted_serum_adcc_lysis_pct')
            _adcc_pair_id = view.get('obs_l2_v3_adcc_serum_donor_pair_id')
            _adcc_intact_sid = view.get('obs_l2_v3_adcc_intact_specimen_id')
            _adcc_dep_sid = view.get('obs_l2_v3_adcc_igg_depleted_specimen_id')
            if (
                not num_adep
                or _dep_sup is None
                or not _is_strict_finite_number_iip0024(_dep_sup)
                or Decimal(str(_dep_sup)) < Decimal('0')
                or Decimal(str(_dep_sup)) > Decimal('100')
                or Decimal(str(_dep_sup)) != _implied_dep_d
                or not isinstance(_adcc_pair_id, str)
                or not _adcc_pair_id.strip()
                or _adcc_pair_id != _adcc_pair_id.strip()
                or not isinstance(_adcc_intact_sid, str)
                or not _adcc_intact_sid.strip()
                or _adcc_intact_sid != _adcc_intact_sid.strip()
                or not isinstance(_adcc_dep_sid, str)
                or not _adcc_dep_sid.strip()
                or _adcc_dep_sid != _adcc_dep_sid.strip()
                or _adcc_intact_sid == _adcc_dep_sid
            ):
                adcc_pair_invalid = True
                _add_h('HOLD_S11_UNVERIFIED_PAIRED_GY023_ADCC_SPECIMENS')
        if num_atot and num_adep and num_ainc and not _paired_difference_se_consistent(
            view['obs_l2_v3_intact_serum_adcc_lysis_se'],
            view['obs_l2_v3_igg_depleted_serum_adcc_lysis_se'],
            view['obs_l2_v3_igg_increment_adcc_lysis_se'],
        ):
            adcc_se_invalid = True
            _add_h('HOLD_S11_IMPOSSIBLE_PAIRED_ADCC_UNCERTAINTY')
        adcc_pair_valid = bool(ok_atot and ok_adep and ok_ainc and not adcc_pair_invalid and not adcc_se_invalid)

        ok_eabs, eff_abs_l95, _ea_u95 = _interval_t('obs_l2_v3_exact_stack_effero_abs_pct', 'obs_l2_v3_exact_stack_effero_abs_se')
        ok_ewt, eff_wt_l95, _ew_u95 = _interval_t('obs_l2_v3_exact_stack_effero_pct_of_wt', 'obs_l2_v3_exact_stack_effero_pct_of_wt_se', lo_dom=0.0, hi_dom=200.0)
        ok_peri, peri_l95, _pe_u95 = _interval_t('obs_l2_v3_pericyte_coverage_pct', 'obs_l2_v3_pericyte_coverage_se')
        ok_t50, t50_l95, t50_u95 = _interval_t('obs_l2_v3_plvap_iec_network_t50_h', 'obs_l2_v3_plvap_iec_network_t50_se', lo_dom=0.1, hi_dom=240.0)
        ok_ivia, ivia_l95, ivia_u95 = _interval_t('obs_l2_v3_plvap_iec_viability_pct', 'obs_l2_v3_plvap_iec_viability_se')

        if ok_ap and ap_u95 is not None and ap_u95 > 5.0:
            _add_f('FAIL_S11_POST_CUFF_AP_C5B9_EXCEEDS_5PCT')
        if ok_cls and cls_l95 is not None and cls_u95 is not None:
            if cls_l95 > 10.0:
                _add_f('FAIL_S11_POST_CUFF_CLASSICAL_C4B2A_LYSIS_EXCEEDS_10PCT')
            elif cls_u95 > 10.0:
                _add_h('HOLD_S11_INCONCLUSIVE_CLASSICAL_C4B2A_STRADDLES_10PCT')
        if ok_lec and lec_l95 is not None and lec_u95 is not None:
            if lec_l95 > 10.0:
                _add_f('FAIL_S11_POST_CUFF_LECTIN_C4B2A_LYSIS_EXCEEDS_10PCT')
            elif lec_u95 > 10.0:
                _add_h('HOLD_S11_INCONCLUSIVE_LECTIN_C4B2A_STRADDLES_10PCT')
        if ok_nhs and nhs_u95 is not None and nhs_u95 > 5.0:
            _add_f('FAIL_S11_PLAYBOOK_OVERALL_20PCT_NHS_LYSIS_EXCEEDS_5PCT')
        if (ok_atot and adcc_tot_u95 is not None and adcc_tot_u95 > 5.0) or (
            adcc_pair_valid and adcc_inc_u95 is not None and adcc_inc_u95 > 5.0
        ):
            _add_f('FAIL_S11_CONJUNCTIVE_GY023_ADCC_EXCEEDS_5PCT')
        if (ok_eabs and eff_abs_l95 is not None and eff_abs_l95 < 80.0) or (ok_ewt and eff_wt_l95 is not None and eff_wt_l95 < 70.0):
            _add_f('FAIL_S11_EXACT_STACK_EFFEROCYTOSIS_BELOW_80ABS_OR_70WT')
        if ok_peri and peri_l95 is not None and peri_l95 < 70.0:
            _add_f('FAIL_S11_GATE0G_PERICYTE_COVERAGE_BELOW_70PCT')
        if ok_t50 and t50_l95 is not None and t50_u95 is not None:
            if t50_l95 > 36.0:
                _add_f('FAIL_S11_PLVAP_IEC_NETWORK_MORPHOGENESIS_EXCEEDS_36H')
            elif t50_u95 > 36.0:
                _add_h('HOLD_S11_INCONCLUSIVE_PLVAP_IEC_NETWORK_T50_STRADDLES_36H')
        if ok_ivia and ivia_l95 is not None and ivia_u95 is not None:
            if ivia_u95 < 85.0:
                _add_f('FAIL_S11_PLVAP_IEC_VIABILITY_BELOW_85PCT')
            elif ivia_l95 < 85.0:
                _add_h('HOLD_S11_INCONCLUSIVE_PLVAP_IEC_VIABILITY_STRADDLES_85PCT')

        if not all((ok_ap, ok_cls, ok_lec, ok_nhs, ok_atot, ok_ainc, ok_eabs, ok_ewt, ok_peri, ok_t50, ok_ivia)):
            _add_h('HOLD_S11_INCOMPLETE_COMPLEMENT_ADCC_VASCULAR_EFFEROCYTOSIS_OR_PERICYTE_PANEL')

        # 5. Reconciled AAV6 species fractions & quantitative chr16 HA WGS + tandem poly(A) readthrough + copy-specific expression:
        aav_m = view.get('obs_l2_v3_aav6_full_length_monomer_pct')
        aav_t = view.get('obs_l2_v3_aav6_truncated_species_pct')
        aav_d = view.get('obs_l2_v3_aav6_dimeric_or_intermediate_pct')
        if any(x is None for x in (aav_m, aav_t, aav_d)):
            if any(x is not None for x in (aav_m, aav_t, aav_d)):
                _add_h('HOLD_S11_AAV6_SPECIES_DENOMINATOR_UNRECONCILED')
            else:
                _add_h('HOLD_S11_MISSING_RECONCILED_AAV6_SPECIES_FRACTIONS')
        elif not all(_is_strict_finite_number_iip0024(x) for x in (aav_m, aav_t, aav_d)):
            _add_h('HOLD_S11_AAV6_SPECIES_DENOMINATOR_UNRECONCILED')
        else:
            fm, ft, fd = float(aav_m), float(aav_t), float(aav_d)
            if fm < 0.0 or ft < 0.0 or fd < 0.0 or fm > 100.0 or ft > 100.0 or fd > 100.0 or abs((fm + ft + fd) - 100.0) > 1e-6:
                _add_h('HOLD_S11_AAV6_SPECIES_DENOMINATOR_UNRECONCILED')
            elif fm < 80.0 or ft >= 10.0 or fd > 15.0:
                _add_f('FAIL_S11_AAV6_HOMOGENEITY_SPEC_BREACHED')

        wgs_pass = view.get('obs_l2_v3_chr16_ha_wgs_pass')
        wgs_vcount = view.get('obs_l2_v3_chr16_ha_wgs_variant_count')
        if wgs_pass is False or (_is_strict_int_iip0024(wgs_vcount) and wgs_vcount > 0):
            _add_f('FAIL_S11_CHR16_HA_WGS_VARIANT_DETECTED')
        elif wgs_pass is not True or not _is_strict_int_iip0024(wgs_vcount) or wgs_vcount != 0:
            _add_h('HOLD_S11_MISSING_CHR16_HA_WGS')

        ok_rt, rt_l95, rt_u95 = _interval_t('obs_l2_v3_tandem_polya_readthrough_fold', 'obs_l2_v3_tandem_polya_readthrough_se', lo_dom=0.0, hi_dom=100.0)
        if not ok_rt:
            _add_h('HOLD_S11_MISSING_TANDEM_POLYA_READTHROUGH_EVIDENCE')
        elif rt_l95 is not None and rt_l95 > 2.0:
            _add_f('FAIL_S11_TANDEM_POLYA_READTHROUGH_EXCEEDS_2X')
        elif rt_u95 is not None and rt_u95 > 2.0:
            _add_h('HOLD_S11_INCONCLUSIVE_TANDEM_POLYA_READTHROUGH_STRADDLES_2X')

        geno_class = view.get('ciita_locus2_genotype_copy_class')
        if geno_class not in ('KI/KO', '1x', '1X', 'KI/KI', '2x', '2X'):
            _add_h('HOLD_S11_MISSING_OR_INVALID_CIITA_GENOTYPE_COPY_CLASS')
            is_2x_kiki = False
        else:
            is_2x_kiki = geno_class in ('KI/KI', '2x', '2X')

        cfh_qb_min = 15000.0 if is_2x_kiki else 10000.0
        ok_cfh_qb, cfh_qb_l95, cfh_qb_u95 = _interval_t('obs_l2_v3_cfh_stp_gpi_quantibrite_molecules', 'obs_l2_v3_cfh_stp_gpi_quantibrite_se', lo_dom=0.0, hi_dom=2000000.0)
        ok_u2_qb, u2_qb_l95, _u2_qb_u95 = _interval_t('obs_l2_v3_unit2_copy_expression_quantibrite_or_fold', 'obs_l2_v3_unit2_copy_expression_se', lo_dom=0.0, hi_dom=2000000.0)
        if not ok_cfh_qb or not ok_u2_qb:
            _add_h('HOLD_S11_MISSING_COPY_SPECIFIC_QUANTIBRITE_EXPRESSION')
        elif (cfh_qb_l95 is not None and cfh_qb_l95 < cfh_qb_min) or (cfh_qb_u95 is not None and cfh_qb_u95 > 500000.0) or (u2_qb_l95 is not None and u2_qb_l95 < 1.0):
            _add_f('FAIL_S11_COPY_SPECIFIC_QUANTIBRITE_EXPRESSION_OUT_OF_BOUNDS')

        # 6. Quantitative phased biallelic CIITA Ex4->Ex6: independent per-allele exact CP validation,
        #    full KI/KI vs KI/KO field binding, `bit_length() <= 53` overflow guard, and modern/legacy alias conflict preservation:
        has_kiko_fields = any(k in view for k in _S11_KIKO_ONLY_FIELDS)
        has_kiki_fields = any(k in view for k in _S11_KIKI_ONLY_FIELDS)

        def _collect_alias_vals(keys: tuple[str, ...]) -> tuple[list[Any], bool]:
            vals = [view[k] for k in keys if k in view]
            if not vals:
                return [], False
            sigs: list[str] = []
            distinct: list[Any] = []
            bad_alias = False
            for v in vals:
                if _is_strict_int_iip0024(v) and abs(v).bit_length() > 53:
                    bad_alias = True
                    continue
                try:
                    sv = json.dumps(v, sort_keys=True, allow_nan=False)
                except (TypeError, ValueError, OverflowError):
                    bad_alias = True
                    continue
                if sv not in sigs:
                    sigs.append(sv)
                    distinct.append(v)
            return distinct, bool(bad_alias or len(distinct) > 1)

        allele_specs: list[tuple[list[Any], list[Any], list[str]]] = []
        if is_2x_kiki:
            if has_kiko_fields or not has_kiki_fields:
                _add_h('HOLD_S11_GENOTYPE_CLASS_ALLELE_FIELD_MISMATCH')
            for idx_a in (1, 2):
                n_vals, n_conf = _collect_alias_vals((f'obs_ciita_ki_allele{idx_a}_informative_reads_n', f'obs_ciita_allele{idx_a}_informative_reads_n'))
                k_vals, k_conf = _collect_alias_vals((f'obs_ciita_ki_allele{idx_a}_ex4_ex6_aberrant_skip_reads_k', f'obs_ciita_allele{idx_a}_ex4_ex6_aberrant_skip_reads_k'))
                if n_conf or k_conf:
                    _add_h('HOLD_S11_CONFLICTING_CIITA_ALLELE_ALIASES')
                pct_ks = [pk for pk in (f'obs_ciita_ki_allele{idx_a}_ex4_ex6_aberrant_skip_pct', f'obs_ciita_allele{idx_a}_ex4_ex6_aberrant_skip_pct') if pk in view]
                allele_specs.append((k_vals, n_vals, pct_ks))
            ok_a1_m, a1_l_m, a1_u_m = _interval_t('obs_ciita_ki_allele1_ex4_ex6_aberrant_skip_pct', 'obs_ciita_ki_allele1_ex4_ex6_aberrant_skip_se')
            ok_a1_l, a1_l_l, a1_u_l = _interval_t('obs_ciita_allele1_ex4_ex6_aberrant_skip_pct', 'obs_ciita_allele1_ex4_ex6_aberrant_skip_se')
            ok_a2_m, a2_l_m, a2_u_m = _interval_t('obs_ciita_ki_allele2_ex4_ex6_aberrant_skip_pct', 'obs_ciita_ki_allele2_ex4_ex6_aberrant_skip_se')
            ok_a2_l, a2_l_l, a2_u_l = _interval_t('obs_ciita_allele2_ex4_ex6_aberrant_skip_pct', 'obs_ciita_allele2_ex4_ex6_aberrant_skip_se')
            t_sk_intervals = [(ok_a1_m, a1_l_m, a1_u_m), (ok_a1_l, a1_l_l, a1_u_l), (ok_a2_m, a2_l_m, a2_u_m), (ok_a2_l, a2_l_l, a2_u_l)]
            ok_a1_sk = ok_a1_m or ok_a1_l
            ok_a2_sk = ok_a2_m or ok_a2_l
        else:
            if has_kiki_fields:
                _add_h('HOLD_S11_GENOTYPE_CLASS_ALLELE_FIELD_MISMATCH')
            a1_n_v = [view['obs_ciita_ki_allele_informative_reads_n']] if 'obs_ciita_ki_allele_informative_reads_n' in view else []
            a1_k_v = [view['obs_ciita_ki_ex4_ex6_aberrant_skip_reads_k']] if 'obs_ciita_ki_ex4_ex6_aberrant_skip_reads_k' in view else []
            a2_n_v = [view['obs_ciita_ko_allele_informative_reads_n']] if 'obs_ciita_ko_allele_informative_reads_n' in view else []
            a2_k_v = [view['obs_ciita_ko_ex4_ex6_aberrant_skip_reads_k']] if 'obs_ciita_ko_ex4_ex6_aberrant_skip_reads_k' in view else []
            allele_specs = [
                (a1_k_v, a1_n_v, ['obs_ciita_ki_ex4_ex6_aberrant_skip_pct'] if 'obs_ciita_ki_ex4_ex6_aberrant_skip_pct' in view else []),
                (a2_k_v, a2_n_v, ['obs_ciita_ko_ex4_ex6_aberrant_skip_pct'] if 'obs_ciita_ko_ex4_ex6_aberrant_skip_pct' in view else []),
            ]
            ok_a1_sk, a1_sk_l95, a1_sk_u95 = _interval_t('obs_ciita_ki_ex4_ex6_aberrant_skip_pct', 'obs_ciita_ki_ex4_ex6_aberrant_skip_se')
            ok_a2_sk, a2_sk_l95, a2_sk_u95 = _interval_t('obs_ciita_ko_ex4_ex6_aberrant_skip_pct', 'obs_ciita_ko_ex4_ex6_aberrant_skip_se')
            t_sk_intervals = [(ok_a1_sk, a1_sk_l95, a1_sk_u95), (ok_a2_sk, a2_sk_l95, a2_sk_u95)]

        ok_ed_hla, ed_hla_l95, ed_hla_u95 = _interval_t('obs_edited_72h_ifng_hla_dr_dp_dq_pos_pct', 'obs_edited_72h_ifng_hla_dr_dp_dq_pos_se')
        ok_wt_hla, wt_hla_l95, _wt_hla_u95 = _interval_t('obs_wt_lineage_matched_72h_ifng_hla_dr_dp_dq_pos_pct', 'obs_wt_lineage_matched_72h_ifng_hla_dr_dp_dq_pos_se')

        if any(ok_i and l_i is not None and l_i > 1.0 for ok_i, l_i, _u_i in t_sk_intervals):
            _add_f('FAIL_S11_CIITA_ABERRANT_EX4_EX6_SKIP_EXCEEDS_1PCT')
        elif any(ok_i and u_i is not None and u_i > 1.0 for ok_i, _l_i, u_i in t_sk_intervals):
            _add_h('HOLD_S11_INCONCLUSIVE_CIITA_EX4_EX6_SKIP_STRADDLES_1PCT')

        if ok_ed_hla and ed_hla_l95 is not None and ed_hla_l95 > 1.0:
            _add_f('FAIL_S11_EDITED_CELL_HLA_II_ESCAPE_DETECTED')
        elif ok_ed_hla and ed_hla_u95 is not None and ed_hla_u95 > 1.0:
            _add_h('HOLD_S11_INCONCLUSIVE_EDITED_CELL_HLA_II_STRADDLES_1PCT')

        # Evaluate EACH allele's exact binomial counts independently BEFORE checking full-panel completeness:
        all_alleles_counts_complete = True
        for k_cands, n_cands, pct_keys in allele_specs:
            valid_pairs: list[tuple[int, int]] = []
            allele_any_invalid = False
            for kv in k_cands:
                for nv in n_cands:
                    if (
                        _is_strict_int_iip0024(nv)
                        and nv >= 300
                        and nv.bit_length() <= 53
                        and _is_strict_int_iip0024(kv)
                        and 0 <= kv <= nv
                    ):
                        valid_pairs.append((kv, nv))
                    else:
                        allele_any_invalid = True
            if not valid_pairs or allele_any_invalid or len(k_cands) != 1 or len(n_cands) != 1:
                all_alleles_counts_complete = False
            for _sk_k, _rn_k in valid_pairs:
                _emp_pct_d = (Decimal(_sk_k) * Decimal('100')) / Decimal(_rn_k)
                for _pk_name in pct_keys:
                    _raw_p = view.get(_pk_name)
                    if _is_strict_finite_number_iip0024(_raw_p):
                        if abs(Decimal(str(_raw_p)) - _emp_pct_d) > Decimal('0.05'):
                            _add_h('HOLD_S11_CIITA_SKIP_COUNT_PERCENTAGE_MISMATCH')
                _cp_l95_pct = 100.0 * _exact_one_sided_cp_lower_iip0031(_sk_k, _rn_k, 0.05)
                _cp_u95_pct = 100.0 * clopper_pearson_upper95_independent(_sk_k, _rn_k, alpha=0.05)
                if _cp_l95_pct > 1.0:
                    _add_f('FAIL_S11_CIITA_ABERRANT_EX4_EX6_SKIP_EXCEEDS_1PCT')
                elif _cp_u95_pct > 1.0:
                    _add_h('HOLD_S11_INCONCLUSIVE_CIITA_EX4_EX6_SKIP_STRADDLES_1PCT')

        if not all_alleles_counts_complete or not all((ok_a1_sk, ok_a2_sk, ok_ed_hla, ok_wt_hla)):
            _add_h('HOLD_S11_MISSING_QUANTITATIVE_CIITA_BIALLELIC_SPLICE_OR_HLAII_EVIDENCE')
        elif wt_hla_l95 is None or wt_hla_l95 < 50.0:
            _add_h('HOLD_S11_UNINDUCIBLE_WT_HLAII_POSITIVE_CONTROL')

        for cis_gene in ('socs1', 'dexi', 'clec16a'):
            lo_g = view.get(f'obs_cis_{cis_gene}_tost90_ratio_lo')
            hi_g = view.get(f'obs_cis_{cis_gene}_tost90_ratio_hi')
            if (
                not _is_strict_finite_number_iip0024(lo_g)
                or not _is_strict_finite_number_iip0024(hi_g)
                or float(lo_g) <= 0.0
                or float(lo_g) >= float(hi_g)
            ):
                _add_h('HOLD_S11_MISSING_OR_INVALID_16P13_CIS_SENTINEL_TOST')
            else: