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…

        u95_bin = clopper_pearson_upper95_independent(k, n)
        u95_pois = u95_bin
    u95_eval = u95_pois if use_poisson_protocol_floor else u95_bin
    exceeds = (u95_eval >= max_u95_fraction) if gate_id.startswith('GATE0S_SHEDDING_') else (u95_eval > max_u95_fraction)
    if exceeds:
        if k == 0:
            return {
                'status': 'HOLD_INCONCLUSIVE_INSUFFICIENT_INDEPENDENT_DENOMINATOR',
                'gate_id': gate_id,
                'k': 0,
                'n_nominal': n,
                'effective_detection_factor': eff_prob,
                'u95_binomial': u95_bin,
                'u95_poisson': u95_pois,
                'cap_fraction': max_u95_fraction,
            }
        return {
            'status': 'FAIL_HARD_STOP',
            'reason': 'CONFIRMED_COUNT_UPPER95_EXCEEDS_CAP',
            'gate_id': gate_id,
            'k': k,
            'n_nominal': n,
            'u95_binomial': u95_bin,
            'cap_fraction': max_u95_fraction,
        }
    return {
        'status': 'PASS',
        'gate_id': gate_id,
        'k': k,
        'n_nominal': n,
        'effective_detection_factor': eff_prob,
        'u95_binomial': u95_bin,
        'u95_poisson': u95_pois,
        'cap_fraction': max_u95_fraction,
    }


REGISTERED_DMR_PANEL_SPECS_IIP0024: MappingProxyType = _deep_freeze_iip0024({
    'IC1': {
        'panel_version_id': 'IC1_H19_CTCF_CORE_V1',
        'dmr_class': 'PRIMARY_GERMLINE_DMR',
        'expected_methylated_parent': 'PATERNAL',
        'grch38_window': 'chr11:1999500-2003500',
    },
    'IC2': {
        'panel_version_id': 'IC2_KVDMR1_PROMOTER_CORE_V1',
        'dmr_class': 'PRIMARY_GERMLINE_DMR',
        'expected_methylated_parent': 'MATERNAL',
        'grch38_window': 'chr11:2698800-2701199',
    },
    'IG_DMR': {
        'panel_version_id': 'IG_DMR_KAGAMI_CG4_6CPG_CG6_19CPG_V1',
        'dmr_class': 'PRIMARY_GERMLINE_DMR',
        'expected_methylated_parent': 'PATERNAL',
        'grch38_window': 'chr14:100809350-100811900',
        'amplicon_cpg_counts': {'CG4': 6, 'CG6': 19},
    },
    'MEG3_DMR': {
        'panel_version_id': 'MEG3_DMR_SOMATIC_STAGE7_V1',
        'dmr_class': 'SECONDARY_SOMATIC_DMR',
        'expected_methylated_parent': 'PATERNAL',
        'grch38_window': 'chr14:100824100-100828299',
    },
})


def evaluate_conjunctive_imprinting_dmr_iip0024(
    *,
    endpoint_scope: str,
    dmr_id: Any,
    panel_version_id: Any,
    per_cpg_callable_verified: Any,
    assay_controls_valid: Any,
    bulk_beta: Any,
    phased: Any,
    beta_paternal: Any = None,
    beta_maternal: Any = None,
    min_allele_molecule_depth: Any = None,
    mosaic_discordant_epiallele_frac: Any = None,
    stage7_meg3_dlk1_rtqpcr_and_perifusion_cleared: Any = None,
) -> dict[str, Any]:
    """NaN-safe conjunctive DMR validator for IC1, IC2/KvDMR1, IG-DMR (CG4/CG6), and Stage-7 MEG3-DMR diagnostic HOLD (IIP-0024; DEC-103)."""
    if endpoint_scope not in ('MCB_SCOPE', 'LOT_SCOPE'):
        return {'status': 'HOLD_INVALID_ENDPOINT_SCOPE'}
    if not isinstance(dmr_id, str) or dmr_id not in REGISTERED_DMR_PANEL_SPECS_IIP0024:
        return {'status': 'HOLD_UNKNOWN_DMR_ID', 'dmr_id': dmr_id}
    spec = REGISTERED_DMR_PANEL_SPECS_IIP0024[dmr_id]
    if panel_version_id != spec['panel_version_id'] or per_cpg_callable_verified is not True:
        return {'status': 'HOLD_UNQUALIFIED_OR_MISMATCHED_DMR_PANEL_VERSION', 'dmr_id': dmr_id}
    if assay_controls_valid is not True:
        return {'status': 'HOLD_INVALID_OR_MISSING_DMR_ASSAY_CONTROLS', 'dmr_id': dmr_id}
    if not _is_strict_finite_number_iip0024(bulk_beta) or not (0.0 <= float(bulk_beta) <= 1.0):
        return {'status': 'HOLD_NONFINITE_OR_OUT_OF_RANGE_BULK_BETA', 'dmr_id': dmr_id}
    if not isinstance(phased, bool):
        return {'status': 'HOLD_INVALID_PHASED_FLAG', 'dmr_id': dmr_id}
    b_bulk = float(bulk_beta)
    if dmr_id == 'MEG3_DMR':
        aberrant = not (0.35 <= b_bulk <= 0.65)
        if phased:
            if (
                not _is_strict_int_iip0024(min_allele_molecule_depth)
                or min_allele_molecule_depth < 30
                or not _is_strict_finite_number_iip0024(beta_paternal)
                or not _is_strict_finite_number_iip0024(beta_maternal)
                or not (0.0 <= float(beta_paternal) <= 1.0)
                or not (0.0 <= float(beta_maternal) <= 1.0)
            ):
                return {'status': 'HOLD_MEG3_DMR_INCOMPLETE_PHASED_METRICS', 'dmr_id': dmr_id}
            if (float(beta_paternal) - float(beta_maternal)) < 0.60:
                aberrant = True
        if aberrant:
            if endpoint_scope == 'LOT_SCOPE' and stage7_meg3_dlk1_rtqpcr_and_perifusion_cleared is False:
                return {'status': 'FAIL_HARD_STOP', 'dmr_id': dmr_id, 'reason': 'STAGE7_MEG3_SILENCING_AND_PERIFUSION_FAILED'}
            return {
                'status': 'HOLD_STAGE7_MEG3_DMR_REQUIRES_MEG3_DLK1_EXPRESSION_AND_PERIFUSION_CHECK',
                'dmr_id': dmr_id,
                'endpoint_scope': endpoint_scope,
            }
        return {'status': 'PASS', 'dmr_id': dmr_id, 'endpoint_scope': endpoint_scope}
    if b_bulk < 0.35 or b_bulk > 0.65:
        return {'status': 'FAIL_HARD_STOP', 'dmr_id': dmr_id, 'reason': 'BULK_METHYLATION_OUTSIDE_0P35_0P65'}
    if not phased or not _is_strict_int_iip0024(min_allele_molecule_depth) or min_allele_molecule_depth < 30:
        return {'status': 'HOLD_UNPHASED_OR_LOW_ALLELE_DEPTH', 'dmr_id': dmr_id}
    if (
        not _is_strict_finite_number_iip0024(beta_paternal)
        or not _is_strict_finite_number_iip0024(beta_maternal)
        or not (0.0 <= float(beta_paternal) <= 1.0)
        or not (0.0 <= float(beta_maternal) <= 1.0)
    ):
        return {'status': 'HOLD_NONFINITE_OR_MISSING_PARENTAL_ALLELE_BETA', 'dmr_id': dmr_id}
    if not _is_strict_finite_number_iip0024(mosaic_discordant_epiallele_frac) or not (0.0 <= float(mosaic_discordant_epiallele_frac) <= 1.0):
        return {'status': 'HOLD_MISSING_OR_INVALID_MOSAIC_EPIALLELE_FRACTION', 'dmr_id': dmr_id}
    b_pat, b_mat, mos = float(beta_paternal), float(beta_maternal), float(mosaic_discordant_epiallele_frac)
    b_meth = b_mat if spec['expected_methylated_parent'] == 'MATERNAL' else b_pat
    b_unmeth = b_pat if spec['expected_methylated_parent'] == 'MATERNAL' else b_mat
    signed_delta = b_meth - b_unmeth
    if signed_delta < 0.60 or b_meth < 0.75 or b_unmeth > 0.25 or mos > 0.10:
        return {
            'status': 'FAIL_HARD_STOP',
            'dmr_id': dmr_id,
            'signed_parental_delta': round(signed_delta, 4),
            'mosaic_discordant_epiallele_frac': mos,
        }
    return {'status': 'PASS', 'dmr_id': dmr_id, 'endpoint_scope': endpoint_scope, 'signed_parental_delta': round(signed_delta, 4)}


def evaluate_conjunctive_xci_46xx_iip0024(
    *,
    endpoint_scope: str,
    donor_sex_karyotype: Any,
    assay_controls_valid: Any,
    xci_promoter_panel_id: Any = None,
    xist_pos_k: Any = None,
    xist_nuclei_n: Any = None,
    xci_subject_promoter_cpg_retention: Any = None,
    allele_specific_x_rna_informative_genes: Any = None,
    allele_specific_x_rna_monoallelic_fraction: Any = None,
) -> dict[str, Any]:
    """Fail-closed 3-axis 46,XX XCI erosion validator (n >= 300 nuclei, k >= 279 -> L95 >= 0.90, promoter CpG >= 0.85, X-RNA >= 0.90 across >= 10 genes; IIP-0024; DEC-103)."""
    if endpoint_scope not in ('MCB_SCOPE', 'LOT_SCOPE'):
        return {'status': 'HOLD_INVALID_ENDPOINT_SCOPE'}
    if donor_sex_karyotype == '46,XY':
        return {'status': 'NOT_APPLICABLE_46XY', 'endpoint_scope': endpoint_scope}
    if donor_sex_karyotype != '46,XX':
        return {'status': 'HOLD_MISSING_OR_UNRECOGNIZED_KARYOTYPE'}
    if assay_controls_valid is not True:
        return {'status': 'HOLD_INVALID_OR_MISSING_XCI_ASSAY_CONTROLS'}
    if xci_promoter_panel_id != 'XCI_SUBJECT_PROMOTER_CPG_PANEL_V1':
        return {'status': 'HOLD_MISSING_OR_UNKNOWN_XCI_PROMOTER_PANEL_ID'}
    if not _is_strict_int_iip0024(xist_pos_k) or not _is_strict_int_iip0024(xist_nuclei_n) or xist_pos_k < 0 or xist_pos_k > xist_nuclei_n:
        return {'status': 'HOLD_NON_INTEGER_OR_OUT_OF_BOUNDS_XIST_COUNTS'}
    if xist_nuclei_n < 300:
        return {'status': 'HOLD_INSUFFICIENT_XIST_NUCLEI_REQUIRES_GE_300'}
    if not _is_strict_finite_number_iip0024(xci_subject_promoter_cpg_retention) or not (0.0 <= float(xci_subject_promoter_cpg_retention) <= 1.0):
        return {'status': 'HOLD_NONFINITE_OR_OUT_OF_RANGE_XCI_PROMOTER_RETENTION'}
    xist_l95 = clopper_pearson_lower95_independent(xist_pos_k, xist_nuclei_n)
    if xist_l95 < 0.90 or float(xci_subject_promoter_cpg_retention) < 0.85:
        return {'status': 'FAIL_HARD_STOP', 'xist_lower95': round(xist_l95, 6), 'promoter_cpg_retention': float(xci_subject_promoter_cpg_retention)}
    if not _is_strict_int_iip0024(allele_specific_x_rna_informative_genes) or allele_specific_x_rna_informative_genes < 10:
        return {'status': 'HOLD_INSUFFICIENT_INFORMATIVE_X_RNA_SNPS_REQUIRES_GE_10'}
    if not _is_strict_finite_number_iip0024(allele_specific_x_rna_monoallelic_fraction) or not (0.0 <= float(allele_specific_x_rna_monoallelic_fraction) <= 1.0):
        return {'status': 'HOLD_NONFINITE_OR_MISSING_X_RNA_MONOALLELIC_FRACTION'}
    if float(allele_specific_x_rna_monoallelic_fraction) < 0.90:
        return {'status': 'FAIL_HARD_STOP', 'reason': 'BIALLELIC_X_LINKED_RNA_REACTIVATION_DETECTED'}
    return {
        'status': 'PASS',
        'endpoint_scope': endpoint_scope,
        'xist_lower95': round(xist_l95, 6),
        'promoter_cpg_retention': float(xci_subject_promoter_cpg_retention),
        'monoallelic_rna_fraction': float(allele_specific_x_rna_monoallelic_fraction),
    }


def evaluate_scoped_mtdna_gate_iip0024(
    *,
    endpoint_scope: str,
    min_unique_chrm_molecule_depth: Any,
    numt_filter_and_snv_del_spikes_validated: Any,
    variants: Any,
    deletion_vaf_max: Any = None,
    seahorse_coupled_respiration_pass: Any = None,
) -> dict[str, Any]:
    """Fail-closed >= 1,000x NUMT-filtered chrM heteroplasmy, deletion, and respiration validator (IIP-0024; DEC-103)."""
    if endpoint_scope not in ('MCB_SCOPE', 'LOT_SCOPE'):
        return {'status': 'HOLD_INVALID_ENDPOINT_SCOPE'}
    if not _is_strict_int_iip0024(min_unique_chrm_molecule_depth) or min_unique_chrm_molecule_depth < 1000:
        return {'status': 'HOLD_CHRM_UNIQUE_DEPTH_BELOW_1000X'}
    if numt_filter_and_snv_del_spikes_validated is not True:
        return {'status': 'HOLD_NUMT_FILTER_OR_SNV_DEL_SPIKE_CONTROLS_UNVALIDATED'}
    if not _is_strict_finite_number_iip0024(deletion_vaf_max) or not (0.0 <= float(deletion_vaf_max) <= 1.0):
        return {'status': 'HOLD_MISSING_OR_INVALID_MTDNA_DELETION_VAF_CONTROL'}
    if not isinstance(seahorse_coupled_respiration_pass, bool):
        return {'status': 'HOLD_MISSING_MTDNA_SEAHORSE_RESPIRATION_CONTROL'}
    if not isinstance(variants, list):
        return {'status': 'HOLD_INVALID_MTDNA_VARIANTS_LIST'}
    if seahorse_coupled_respiration_pass is False or float(deletion_vaf_max) > 0.02:
        return {'status': 'FAIL_HARD_STOP', 'reason': 'MTDNA_DELETION_GT_2PCT_OR_RESPIRATION_FAILURE'}
    borderline_hold = False
    for v in variants:
        if not isinstance(v, dict):
            return {'status': 'HOLD_MALFORMED_MTDNA_VARIANT_RECORD'}
        vid = v.get('variant_id')
        vaf_raw = v.get('vaf')
        if not isinstance(vid, str) or not vid.strip() or not _is_strict_finite_number_iip0024(vaf_raw) or not (0.0 <= float(vaf_raw) <= 1.0):
            return {'status': 'HOLD_INVALID_MTDNA_VARIANT_ID_OR_VAF'}
        vaf = float(vaf_raw)
        b_hap = v.get('verified_benign_donor_germline_haplogroup_polymorphism')
        b_path = v.get('known_pathogenic_mitomap_clinvar')
        b_acq = v.get('acquired_denovo_or_private_coding_trna_rrna')
        if any(x is not None and not isinstance(x, bool) for x in (b_hap, b_path, b_acq)):
            return {'status': 'HOLD_NON_BOOLEAN_MTDNA_CLASSIFICATION_FLAG', 'variant_id': vid}
        is_hap = b_hap is True
        is_path = b_path is True
        is_acq = b_acq is True
        if is_hap and (is_path or is_acq):
            return {'status': 'HOLD_CONTRADICTORY_MTDNA_BENIGN_AND_ACQUIRED_OR_PATHOGENIC_FLAGS', 'variant_id': vid}
        if not (is_hap or is_path or is_acq):
            return {'status': 'HOLD_UNCLASSIFIED_MTDNA_VARIANT_REQUIRES_CURATION', 'variant_id': vid}
        if vid.strip() == 'm.3243A>G' and vaf > 0.01:
            return {'status': 'FAIL_HARD_STOP', 'reason': 'M3243AG_EXCEEDS_1PCT_CAP', 'vaf': vaf}
        if is_hap:
            continue
        if vaf > 0.05:
            return {'status': 'FAIL_HARD_STOP', 'reason': 'SCOPED_MTDNA_HETEROPLASMY_EXCEEDS_5PCT_CAP', 'variant_id': vid, 'vaf': vaf}
        if 0.03 <= vaf <= 0.05:
            borderline_hold = True
    if borderline_hold:
        return {'status': 'HOLD_BORDERLINE_3_TO_5PCT_ACQUIRED_MTDNA_REQUIRES_ORTHOGONAL_DDPCR'}
    return {'status': 'PASS', 'endpoint_scope': endpoint_scope}