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…

        elif key == 'design_y_silencing_modality':
            if not isinstance(payload[key], str) or payload[key].strip() not in ALLOWED_DESIGN_Y_SILENCING_MODALITIES:
                raise ValueError(f'design_y_silencing_modality must be one of {sorted(ALLOWED_DESIGN_Y_SILENCING_MODALITIES)} (IIP-0023; DEC-102)')
            result[key] = payload[key].strip()
        elif key == 'design_y_payload_arm':
            if not isinstance(payload[key], str) or payload[key].strip() not in ALLOWED_DESIGN_Y_PAYLOAD_ARMS:
                raise ValueError(f'design_y_payload_arm must be one of {sorted(ALLOWED_DESIGN_Y_PAYLOAD_ARMS)} (IIP-0023; DEC-102)')
            result[key] = payload[key].strip()
        elif key == 'contrast_b1_geometry_arm':
            if not isinstance(payload[key], str) or payload[key].strip() not in ALLOWED_CONTRAST_B1_GEOMETRY_ARMS:
                raise ValueError(f'contrast_b1_geometry_arm must be one of {sorted(ALLOWED_CONTRAST_B1_GEOMETRY_ARMS)} (IIP-0025; DEC-104)')
            result[key] = payload[key].strip()
        elif key == 'contrast_b2_perfusion_and_retrieval_arm':
            if not isinstance(payload[key], str) or payload[key].strip() not in ALLOWED_CONTRAST_B2_ARMS:
                raise ValueError(f'contrast_b2_perfusion_and_retrieval_arm must be one of {sorted(ALLOWED_CONTRAST_B2_ARMS)} (IIP-0025; DEC-104)')
            result[key] = payload[key].strip()
        elif key == 'contrast_b3_donor_iec_arm':
            if not isinstance(payload[key], str) or payload[key].strip() not in ALLOWED_CONTRAST_B3_DONOR_IEC_ARMS:
                raise ValueError(f'contrast_b3_donor_iec_arm must be one of {sorted(ALLOWED_CONTRAST_B3_DONOR_IEC_ARMS)} (IIP-0025; DEC-104)')
            result[key] = payload[key].strip()
        elif key == 'tyk2_pe_modality':
            if not isinstance(payload[key], str) or payload[key].strip() not in ALLOWED_TYK2_PE_MODALITIES:
                raise ValueError(f'tyk2_pe_modality must be one of {sorted(ALLOWED_TYK2_PE_MODALITIES)} (IIP-0026; DEC-105)')
            result[key] = payload[key].strip()
        elif key == 'iip0026_schema_era':
            if not isinstance(payload[key], str) or payload[key].strip() not in ALLOWED_IIP0026_SCHEMA_ERAS:
                raise ValueError(f'iip0026_schema_era must be one of {sorted(ALLOWED_IIP0026_SCHEMA_ERAS)} (IIP-0026; DEC-105)')
            result[key] = payload[key].strip()
        elif key == 'bound_c1_c5_pair_sha256':
            if not isinstance(payload[key], str) or not re.fullmatch(r'[0-9a-f]{64}', payload[key].strip()):
                raise ValueError('bound_c1_c5_pair_sha256 must be a lowercase 64-character SHA-256 hex digest (IIP-0026; DEC-105)')
            result[key] = payload[key].strip()
        elif key == 'product_variant_id':
            if not isinstance(payload[key], str) or not payload[key].strip() or payload[key] != payload[key].strip() or len(payload[key]) > 120:
                raise ValueError('product_variant_id must be a canonical non-whitespace-padded nonempty string of at most 120 characters (IIP-0024; DEC-103)')
            result[key] = payload[key]
        else:
            if not isinstance(payload[key], str) or not payload[key].strip() or len(payload[key]) > 120:
                raise ValueError(f'{key} must be a nonempty string of at most 120 characters')
            result[key] = payload[key].strip()
    if 'specimen_or_clone_id' in result and 'specimen_or_clone_ids' in result:
        sid_scalar = result['specimen_or_clone_id']
        for mk, sv in result['specimen_or_clone_ids'].items():
            if sv != sid_scalar:
                raise ValueError(
                    f'Conflicting specimen_or_clone_id ({sid_scalar!r}) and specimen_or_clone_ids[{mk!r}] ({sv!r}) in measurement payload (AUDIT-REF)'
                )
    observed = []; defaulted = []
    for endpoint in endpoints:
        mk, sk = endpoint['meanKey'], endpoint['seKey']
        mean, se = payload.get(mk, 'UNAVAILABLE'), payload.get(sk, 'UNAVAILABLE')
        if mean == 'UNAVAILABLE':
            if se != 'UNAVAILABLE':
                raise ValueError(f'{sk} has no observed {mk}')
            result[mk] = 'UNAVAILABLE'
            continue
        number = finite_decimal(mean, mk)
        if not endpoint['min'] <= number <= endpoint['max']:
            raise ValueError(f'{mk} must be in [{endpoint["min"]}, {endpoint["max"]}]')
        if sk not in payload and not endpoint['se_required']:
            se = endpoint['default_se']; defaulted.append(sk)
        error = finite_decimal(se, sk)
        if error < contract['minimum_se']:
            raise ValueError(f'{sk} must be >= {contract["minimum_se"]}')
        result[mk] = number; result[sk] = error; observed.append(mk)
    for endpoint in stage0_endpoints:
        mk, sk = endpoint['meanKey'], endpoint['seKey']
        mean, se = payload.get(mk, 'UNAVAILABLE'), payload.get(sk, 'UNAVAILABLE')
        if mean == 'UNAVAILABLE':
            if se != 'UNAVAILABLE':
                raise ValueError(f'{sk} has no observed {mk}')
            continue
        number = finite_decimal(mean, mk)
        if not endpoint['min'] <= number <= endpoint['max']:
            raise ValueError(f'{mk} must be in [{endpoint["min"]}, {endpoint["max"]}]')
        if sk not in payload or se == 'UNAVAILABLE':
            se = endpoint['default_se']; defaulted.append(sk)
        error = finite_decimal(se, sk)
        min_se = endpoint.get('minimum_se', STAGE0_CUSTOM_MINIMUM_SE.get(mk, contract['minimum_se']))
        if error < min_se:
            raise ValueError(f'{sk} must be >= {min_se}')
        result[mk] = number; result[sk] = error; observed.append(mk)
    if require_observation and not observed:
        raise ValueError('At least one endpoint must be observed')
    validate_product_and_estimand_compatibility(
        result.get('product_variant_id'),
        result.get('estimand_scale'),
        observed,
        root=root,
    )
    return result, {'validated_endpoints': observed, 'defaulted_standard_error_keys': defaulted,
                    'default_se_status': 'DECLARED_ASSUMPTION_NOT_MEASURED' if defaulted else 'NOT_USED'}


def evaluate_s10_functional_and_replacement_gate_v3(
    obs: dict,
    construct_registry: dict[str, dict[str, object]] | None = None,
    *,
    defaulted_se_keys: list[str] | set[str] | None = None,
) -> dict:
    """Fail-closed Stage-0 Gate 0A (Rule S10) functional selectivity & comparator gate v3 (IIP-0016; DEC-094).

    Enforces:
      - Exact 20-construct registry lookup and hard block on calibration controls (VMAPRTLFL, QMRPVSRVL).
      - Unconditional cryptographic donor SHA-256 (s10_construct_donor_sha256) and lot-identity binding
        (current_lot_id == s10_qualified_lot_id), plus strict s10_is_replacement_challenger_lot class match
        and Stage-0 5'/3'-RACE junction verification (s10_race_5p_3p_junction_verified == True).
      - Explicit SE bounds on all continuous endpoints, positive covalent-SCT SPR K_D bounds, and paired
        resting (Regime II) + 24h IFN-gamma (Regime I) NK subset lysis/CD107a, pooled 3-subset lysis,
        NKG2C CD107a fold vs B2M-KO, and HCMV UL40 / HLA-E CD8+ CTL 4h lysis across n >= 6 donors (0 failing).
      - Mode-specific resting HLA-E floor ('GATE_0A_SCREENING_15K' -> >= 15,000 vs 'LOT_RELEASE_25K' ->
        >= 25,000 plus 72h hypoxic p10 >= 15,000).
      - Full Layer-3 D227K/T228A biophysics, parallel HLA-A*02:01 WT vs D227K/T228A SPR positive control,
        CD8+ Treg suppression retention (>= 80% of WT and delta >= -10.0 pp), and UL40 CTL delta vs WT (<= +2.0 pp).
      - Unfiltered non-self seam / alpha3 indirect DQ2/DQ8 APC CD4 SI <= 1.5 and host Class-I CTL lysis <= 5.0%.
    """
    registry = STAGE0_S10_V3_CONSTRUCT_REGISTRY if construct_registry is None else construct_registry
    defaulted_set = set(defaulted_se_keys or ())
    z95 = 1.6448536269514722

    cid = obs.get('s10_construct_id')
    if not isinstance(cid, str) or cid not in registry:
        return {
            'gate_pass': False,
            'status': 'HOLD_INVALID_OR_UNREGISTERED_S10_CONSTRUCT_ID',
            'failed_checks': ['s10_construct_id'],
        }
    meta = registry[cid]
    if meta['promotion_eligibility'] == 'CALIBRATION_CONTROL_NEVER_PROMOTE':
        return {
            'gate_pass': False,
            'status': 'HOLD_CALIBRATION_CONTROL_NEVER_ELIGIBLE_FOR_CLINICAL_PROMOTION',
            'failed_checks': ['calibration_control_hard_block'],
        }

    sha_in = obs.get('s10_construct_donor_sha256')
    lot_id = obs.get('current_lot_id')
    qual_lot_id = obs.get('s10_qualified_lot_id')
    is_repl = obs.get('s10_is_replacement_challenger_lot')
    race_ok = obs.get('s10_race_5p_3p_junction_verified')
    floor_mode = obs.get('s10_hlae_floor_mode', 'GATE_0A_SCREENING_15K')

    if (
        type(is_repl) is not bool
        or type(race_ok) is not bool
        or not isinstance(floor_mode, str)
        or floor_mode not in ALLOWED_S10_HLAE_FLOOR_MODES
    ):
        return {
            'gate_pass': False,
            'status': 'HOLD_INVALID_BOOLEAN_OR_FLOOR_MODE_METADATA',
            'failed_checks': ['s10_boolean_or_floor_mode_typecheck'],
        }

    spec_lookup: dict[str, tuple[float, float, float]] = {
        mk: (lo, hi, STAGE0_CUSTOM_MINIMUM_SE.get(mk, 0.001))
        for _eid, mk, _sk, lo, hi, _u in STAGE0_DECISION_TREE_ENDPOINT_SPECS
        if mk in STAGE0_S10_V3_MEAN_KEYS
    }
    spec_lookup['obs_hlae_hour0_molecules'] = (0.0, 1000000.0, 1.0)
    spec_lookup['obs_hypoxic_72h_hlae_p10_single_cell_molecules'] = (0.0, 1000000.0, 1.0)

    def _read_pair(mk: str, sk: str) -> tuple[float, float] | None:
        if mk in defaulted_set or sk in defaulted_set:
            return None
        v = obs.get(mk)
        s = obs.get(sk)
        if isinstance(v, bool) or isinstance(s, bool) or not isinstance(v, (int, float)) or not isinstance(s, (int, float)):
            return None
        vf, sf = float(v), float(s)
        if not math.isfinite(vf) or not math.isfinite(sf):
            return None
        lo, hi, min_se = spec_lookup[mk]
        if not (lo <= vf <= hi) or sf < min_se:
            return None
        return vf, sf

    def _read_exact_nonneg_int(mk: str, sk: str) -> int | None:
        v = obs.get(mk)
        s = obs.get(sk, 1e-12)
        if isinstance(v, bool) or isinstance(s, bool) or not isinstance(v, (int, float)) or not isinstance(s, (int, float)):
            return None
        vf, sf = float(v), float(s)
        if not math.isfinite(vf) or not math.isfinite(sf) or vf < 0.0 or vf > 1000.0 or abs(vf - round(vf)) > 1e-9 or sf < 1e-12:
            return None
        return int(round(vf))

    req_continuous_pairs = (
        ('obs_hlae_sct_nkg2a_kd_uM', 'obs_hlae_sct_nkg2a_kd_se_uM'),
        ('obs_hlae_sct_nkg2c_kd_uM', 'obs_hlae_sct_nkg2c_kd_se_uM'),
        ('obs_hlae_hour0_molecules', 'obs_hlae_hour0_molecules_se'),
        ('obs_nkg2a_pos_resting_nk_lysis_pct', 'obs_nkg2a_pos_resting_nk_lysis_se'),
        ('obs_nkg2a_pos_ifng24h_nk_lysis_pct', 'obs_nkg2a_pos_ifng24h_nk_lysis_se'),
        ('obs_nkg2a_pos_resting_cd107a_pct', 'obs_nkg2a_pos_resting_cd107a_se'),
        ('obs_nkg2a_pos_ifng24h_cd107a_pct', 'obs_nkg2a_pos_ifng24h_cd107a_se'),
        ('obs_nkg2c_kir_pos_resting_lysis_pct', 'obs_nkg2c_kir_pos_resting_lysis_se'),
        ('obs_nkg2c_kir_pos_ifng24h_lysis_pct', 'obs_nkg2c_kir_pos_ifng24h_lysis_se'),
        ('obs_nkg2a_neg_kir2dl_neg_nkg2c_pos_resting_lysis_pct', 'obs_nkg2a_neg_kir2dl_neg_nkg2c_pos_resting_lysis_se'),
        ('obs_nkg2a_neg_kir2dl_neg_nkg2c_pos_ifng24h_lysis_pct', 'obs_nkg2a_neg_kir2dl_neg_nkg2c_pos_ifng24h_lysis_se'),
        ('obs_hcmv_pooled_3subset_resting_nk_lysis_pct', 'obs_hcmv_pooled_3subset_resting_nk_lysis_se'),
        ('obs_hcmv_pooled_3subset_ifng24h_nk_lysis_pct', 'obs_hcmv_pooled_3subset_ifng24h_nk_lysis_se'),
        ('obs_nkg2c_cd107a_degranulation_fold_vs_b2m_ko', 'obs_nkg2c_cd107a_degranulation_fold_se'),
        ('obs_cmv_ul40_hlae_cd8_lysis_pct', 'obs_cmv_ul40_hlae_cd8_lysis_se'),
    )
    vals: dict[str, tuple[float, float]] = {}
    for mk, sk in req_continuous_pairs:
        pr = _read_pair(mk, sk)
        if pr is None:
            return {
                'gate_pass': False,
                'status': 'HOLD_MISSING_OR_OUT_OF_DOMAIN_S10_ENDPOINT_OR_SE',
                'failed_checks': [f'{mk}/{sk}'],
            }
        vals[mk] = pr

    donor_n = _read_exact_nonneg_int('obs_hcmv_pos_donor_count', 'obs_hcmv_pos_donor_count_se')
    nk_fail_n = _read_exact_nonneg_int('obs_s10_nk_failing_donor_count', 'obs_s10_nk_failing_donor_count_se')
    ul40_resp_n = _read_exact_nonneg_int('obs_ul40_reactive_donor_count', 'obs_ul40_reactive_donor_count_se')
    ul40_fail_n = _read_exact_nonneg_int('obs_ul40_ctl_failing_donor_count', 'obs_ul40_ctl_failing_donor_count_se')
    if donor_n is None or nk_fail_n is None or ul40_resp_n is None or ul40_fail_n is None:
        return {
            'gate_pass': False,
            'status': 'HOLD_MISSING_OR_INVALID_DONOR_COUNT_PANEL',
            'failed_checks': ['donor_panel_integer_counts'],
        }

    def _u95(mk: str) -> float:
        m, s = vals[mk]
        return m + z95 * s

    def _l95(mk: str) -> float:
        m, s = vals[mk]
        return m - z95 * s

    ka_u95 = _u95('obs_hlae_sct_nkg2a_kd_uM')
    kc_l95 = max(0.0, _l95('obs_hlae_sct_nkg2c_kd_uM'))
    sct_ratio_mean = vals['obs_hlae_sct_nkg2c_kd_uM'][0] / vals['obs_hlae_sct_nkg2a_kd_uM'][0]
    hlae_h0_l95 = _l95('obs_hlae_hour0_molecules')
    req_h0_floor = 25000.0 if floor_mode == 'LOT_RELEASE_25K' else 15000.0

    checks: dict[str, bool] = {
        'unconditional_construct_sha256_and_lot_identity_bound': (
            isinstance(sha_in, str)
            and sha_in == meta['donor_sha256']
            and isinstance(lot_id, str)
            and 0 < len(lot_id.strip()) <= 120
            and lot_id == qual_lot_id
        ),
        'replacement_challenger_flag_matches_construct_class': (
            is_repl is bool(meta['is_replacement_challenger'])