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…

        )
        if v is not None
    ]
    if any(not isinstance(v, str) or not v.strip() or v != v.strip() for v in _all_s11_sids):
        return _out('HOLD_S11_MISSING_LOT_OR_SAMPLE_BINDING', False, ['HOLD_S11_MISSING_LOT_OR_SAMPLE_BINDING'])
    if len(set(_all_s11_sids)) > 1:
        return _out('FAIL_S11_NESTED_PROVENANCE_SCOPE_MISMATCH', False, ['FAIL_S11_NESTED_PROVENANCE_SCOPE_MISMATCH'])
    _all_s11_lids = [
        v for v in (
            outer_only.get('lot_id'),
            outer_only.get('current_lot_id'),
            rec_in.get('lot_id'),
            rec_in.get('current_lot_id'),
        )
        if v is not None
    ]
    if any(not isinstance(v, str) or not v.strip() or v != v.strip() for v in _all_s11_lids):
        return _out('HOLD_S11_MISSING_LOT_OR_SAMPLE_BINDING', False, ['HOLD_S11_MISSING_LOT_OR_SAMPLE_BINDING'])
    if len(set(_all_s11_lids)) > 1:
        return _out('FAIL_S11_NESTED_PROVENANCE_SCOPE_MISMATCH', False, ['FAIL_S11_NESTED_PROVENANCE_SCOPE_MISMATCH'])
    _all_s11_cids = [
        v for v in (
            outer_only.get('campaign_id'),
            outer_only.get('assay_campaign_id'),
            rec_in.get('campaign_id'),
            rec_in.get('assay_campaign_id'),
        )
        if v is not None
    ]
    if any(not isinstance(v, str) or not v.strip() or v != v.strip() for v in _all_s11_cids) or len(set(_all_s11_cids)) > 1:
        return _out('HOLD_S11_CONFLICTING_NESTED_EVIDENCE', False, ['HOLD_S11_CONFLICTING_NESTED_EVIDENCE'])
    _all_s11_seeds = [
        v for v in (
            outer_only.get('donor_seedline_id'),
            outer_only.get('seed_line_id'),
            rec_in.get('donor_seedline_id'),
            rec_in.get('seed_line_id'),
        )
        if v is not None
    ]
    if any(not isinstance(v, str) or not v.strip() or v != v.strip() for v in _all_s11_seeds):
        return _out('HOLD_S11_MALFORMED_RECORD', False, ['HOLD_S11_MALFORMED_RECORD'])
    if len(set(_all_s11_seeds)) > 1:
        return _out('FAIL_S11_NESTED_PROVENANCE_SCOPE_MISMATCH', False, ['FAIL_S11_NESTED_PROVENANCE_SCOPE_MISMATCH'])
    _all_s11_dids = [
        v for v in (
            outer_only.get('l2_v3_donor_id'),
            outer_only.get('donor_id'),
            rec_in.get('l2_v3_donor_id'),
            rec_in.get('donor_id'),
        )
        if v is not None
    ]
    if any(not isinstance(v, str) or not v.strip() or v != v.strip() for v in _all_s11_dids):
        return _out('HOLD_S11_MALFORMED_RECORD', False, ['HOLD_S11_MALFORMED_RECORD'])
    if len(set(_all_s11_dids)) > 1:
        return _out('FAIL_S11_NESTED_PROVENANCE_SCOPE_MISMATCH', False, ['FAIL_S11_NESTED_PROVENANCE_SCOPE_MISMATCH'])
    for _prov_k in ('construct_sha256', 'background_id', 'mcb_id', 'product_variant_id'):
        for _prov_v in (outer_only.get(_prov_k), rec_in.get(_prov_k)):
            if _prov_v is not None and (not isinstance(_prov_v, str) or not _prov_v.strip() or _prov_v != _prov_v.strip()):
                return _out('HOLD_S11_MALFORMED_RECORD', False, ['HOLD_S11_MALFORMED_RECORD'])

    # Omitted S11 evidence on an L2_V3_* comparator MUST NEVER clear:
    if not has_any_s11_fields:
        return _out('HOLD_S11_INCOMPLETE_EVIDENCE', False, ['HOLD_S11_INCOMPLETE_EVIDENCE'])

    if 'LOT_SCOPE' not in (payload.get('scope_type'), rec_in.get('scope_type')):
        return _out('HOLD_S11_PANEL_REQUIRES_LOT_SCOPE', False, ['HOLD_S11_PANEL_REQUIRES_LOT_SCOPE'])

    # Endpoint-granular outer/nested conflict detection (#4, s11_extra.py):
    # Preserve independently attributable quantitative FAIL_S11_* stops while flagging conflicting fields as HOLD_S11_CONFLICTING_NESTED_EVIDENCE.
    conflicting_overlap_keys: set[str] = set()
    for key in sorted((payload.keys() & rec_in.keys()) - {'product_variant_id'}):
        try:
            outer_value = json.dumps(payload[key], sort_keys=True, allow_nan=False)
            nested_value = json.dumps(rec_in[key], sort_keys=True, allow_nan=False)
        except (TypeError, ValueError, OverflowError):
            return _out('HOLD_S11_MALFORMED_RECORD', False, ['HOLD_S11_MALFORMED_RECORD'])
        if outer_value != nested_value:
            conflicting_overlap_keys.add(key)

    eff_lot_id = _all_s11_lids[0] if _all_s11_lids else None
    eff_sample_id = _all_s11_sids[0] if _all_s11_sids else None

    def _eval_s11_quantitative_view(view: dict[str, Any]) -> tuple[list[str], list[str]]:
        v_fails: list[str] = []
        v_holds: list[str] = []

        def _add_f(code: str) -> None:
            if code not in v_fails:
                v_fails.append(code)

        def _add_h(code: str) -> None:
            if code not in v_holds:
                v_holds.append(code)

        if isinstance(l2_binding, dict) and outer_only.get('construct_sha256') is None and rec_in.get('construct_sha256') is None:
            _add_h('HOLD_S11_MISSING_OUTER_CONSTRUCT_SHA256')

        if (
            not isinstance(eff_lot_id, str)
            or not eff_lot_id.strip()
            or eff_lot_id != eff_lot_id.strip()
            or not isinstance(eff_sample_id, str)
            or not eff_sample_id.strip()
            or eff_sample_id != eff_sample_id.strip()
        ):
            _add_h('HOLD_S11_MISSING_LOT_OR_SAMPLE_BINDING')

        geno_class_pre = view.get('ciita_locus2_genotype_copy_class')
        _is_kiki_pre = geno_class_pre in ('KI/KI', '2x', '2X')
        _is_kiko_pre = geno_class_pre in ('KI/KO', '1x', '1X')

        phasing_any_bad = any(
            _pflag in view and view[_pflag] is not True
            for _pflag in (
                'phasing_verified',
                'ciita_ki_allele_informative_transcript_recovery_verified',
                'ciita_ko_allele_informative_transcript_recovery_verified',
                'ciita_ki_allele1_informative_transcript_recovery_verified',
                'ciita_ki_allele2_informative_transcript_recovery_verified',
            )
        )
        has_kiko_recov_keys = any(
            k in view
            for k in (
                'ciita_ki_allele_informative_transcript_recovery_verified',
                'ciita_ko_allele_informative_transcript_recovery_verified',
            )
        )
        has_kiki_recov_keys = any(
            k in view
            for k in (
                'ciita_ki_allele1_informative_transcript_recovery_verified',
                'ciita_ki_allele2_informative_transcript_recovery_verified',
            )
        )
        if _is_kiki_pre:
            if has_kiko_recov_keys:
                _add_h('HOLD_S11_GENOTYPE_CLASS_ALLELE_FIELD_MISMATCH')
            allele_recovery_attested = (
                view.get('ciita_ki_allele1_informative_transcript_recovery_verified') is True
                and view.get('ciita_ki_allele2_informative_transcript_recovery_verified') is True
            )
        elif _is_kiko_pre:
            if has_kiki_recov_keys:
                _add_h('HOLD_S11_GENOTYPE_CLASS_ALLELE_FIELD_MISMATCH')
            allele_recovery_attested = (
                view.get('ciita_ki_allele_informative_transcript_recovery_verified') is True
                and view.get('ciita_ko_allele_informative_transcript_recovery_verified') is True
            )
        else:
            allele_recovery_attested = False
        phasing_attested = (view.get('phasing_verified') is True) and allele_recovery_attested
        if phasing_any_bad or not phasing_attested:
            _add_h('HOLD_S11_CIITA_BIALLELIC_PHASING_UNVERIFIED')

        cis_any_bad = any(
            _cflag in view and view[_cflag] is not True
            for _cflag in ('cis_verified', 'ciita_cis_sentinels_socs1_dexi_clec16a_tost_verified')
        )
        cis_attested = (
            view.get('cis_verified') is True
            or view.get('ciita_cis_sentinels_socs1_dexi_clec16a_tost_verified') is True
        )
        if cis_any_bad or not cis_attested:
            _add_h('HOLD_S11_16P13_CIS_SENTINELS_UNVERIFIED')

        wt_any_bad = any(
            _wflag in view and view[_wflag] is not True
            for _wflag in ('wt_inducibility_verified', 'lineage_matched_wt_stage7_hla_dr_dp_dq_inducibility_verified')
        )
        wt_attested = (
            view.get('wt_inducibility_verified') is True
            or view.get('lineage_matched_wt_stage7_hla_dr_dp_dq_inducibility_verified') is True
        )
        if wt_any_bad or not wt_attested:
            _add_h('HOLD_S11_WT_HLAII_INDUCIBILITY_UNVERIFIED')

        if (
            ('rnai_attribution_verified' in view and view['rnai_attribution_verified'] is not True)
            or (has_mir_active and view.get('rnai_attribution_verified') is not True)
        ):
            _add_h('HOLD_S11_RNAI_ATTRIBUTION_UNVERIFIED')

        # 3. Strict replicate count validation across ALL 3 supported aliases (including `s11_replicate_n`):
        _rep_alias_keys = ('obs_stage0_independent_lot_replicates_n', 'replicates_n', 's11_replicate_n')
        replicate_aliases = [view[k] for k in _rep_alias_keys if k in view]
        t95: float | None = None
        rep_n_raw = replicate_aliases[0] if replicate_aliases else None
        if not replicate_aliases or any(
            not _is_strict_int_iip0024(v) or not 3 <= v <= STAGE0_MAX_INDEPENDENT_LOT_REPLICATES or v != rep_n_raw
            for v in replicate_aliases
        ):
            _add_h('HOLD_S11_INVALID_OR_MISSING_REPLICATES_N')
        else:
            t95 = student_t_ppf_one_sided_95(float(rep_n_raw - 1))
            if rep_n_raw < 6:
                _add_h('HOLD_S11_REPLICATES_BELOW_6_LOT_MINIMUM')

        def _interval_t(
            mean_k: str,
            se_k: str,
            *,
            lo_dom: float = 0.0,
            hi_dom: float = 100.0,
        ) -> tuple[bool, float | None, float | None]:
            mv, sv = view.get(mean_k), view.get(se_k)
            if mv is None and sv is None:
                return False, None, None
            if (
                not _is_strict_finite_number_iip0024(mv)
                or not _is_strict_finite_number_iip0024(sv)
                or float(sv) <= 0.0
                or float(sv) > (hi_dom - lo_dom)
                or not (lo_dom <= float(mv) <= hi_dom)
            ):
                _add_h('HOLD_S11_INVALID_SE_OR_OUT_OF_RANGE_PHYSIOLOGICAL_READOUT')
                return False, None, None
            if t95 is None:
                return False, None, None
            mf, sf = float(mv), float(sv)
            return True, mf - t95 * sf, mf + t95 * sf

        def _pair_num_ok(mean_k: str, se_k: str, lo_dom: float, hi_dom: float) -> bool:
            mv, sv = view.get(mean_k), view.get(se_k)
            return bool(
                _is_strict_finite_number_iip0024(mv)
                and _is_strict_finite_number_iip0024(sv)
                and float(sv) > 0.0
                and float(sv) <= (hi_dom - lo_dom)
                and (lo_dom <= float(mv) <= hi_dom)
            )

        # 4. Post-cuff complement, conjunctive GY-023 ADCC, PLVAP+ iEC, efferocytosis & Gate 0G pericytes:
        ok_ap, ap_l95, ap_u95 = _interval_t('obs_l2_v3_ap_c5b9_pct', 'obs_l2_v3_ap_c5b9_se')
        ok_cls, cls_l95, cls_u95 = _interval_t('obs_l2_v3_classical_c4b2a_lysis_pct', 'obs_l2_v3_classical_c4b2a_lysis_se')
        ok_lec, lec_l95, lec_u95 = _interval_t('obs_l2_v3_lectin_c4b2a_lysis_pct', 'obs_l2_v3_lectin_c4b2a_lysis_se')
        ok_nhs, _nhs_l95, nhs_u95 = _interval_t('obs_l2_v3_overall_20pct_nhs_lysis_pct', 'obs_l2_v3_overall_20pct_nhs_lysis_se')
        ok_atot, _at_l95, adcc_tot_u95 = _interval_t('obs_l2_v3_intact_serum_adcc_lysis_pct', 'obs_l2_v3_intact_serum_adcc_lysis_se')
        ok_adep, _ad_l95, _ad_u95 = _interval_t('obs_l2_v3_igg_depleted_serum_adcc_lysis_pct', 'obs_l2_v3_igg_depleted_serum_adcc_lysis_se')
        ok_ainc, _ai_l95, adcc_inc_u95 = _interval_t('obs_l2_v3_igg_increment_adcc_lysis_pct', 'obs_l2_v3_igg_increment_adcc_lysis_se', lo_dom=-100.0, hi_dom=100.0)

        # Validate paired GY-023 ADCC mean equality (exact Decimal) and Cauchy-Schwarz SE bounds EVEN WHEN t95 is None (#20, #30):
        num_atot = _pair_num_ok('obs_l2_v3_intact_serum_adcc_lysis_pct', 'obs_l2_v3_intact_serum_adcc_lysis_se', 0.0, 100.0)
        num_adep = _pair_num_ok('obs_l2_v3_igg_depleted_serum_adcc_lysis_pct', 'obs_l2_v3_igg_depleted_serum_adcc_lysis_se', 0.0, 100.0)
        num_ainc = _pair_num_ok('obs_l2_v3_igg_increment_adcc_lysis_pct', 'obs_l2_v3_igg_increment_adcc_lysis_se', -100.0, 100.0)
        adcc_pair_invalid = False
        adcc_se_invalid = False
        if num_atot and num_ainc: