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…

    *,
    validated_stage0: dict[str, float] | None = None,
    non_integer_denominator_flagged: bool = False,
) -> dict[str, Any]:
    """
    Fail-closed Stage-0 resting (0 h) + interferon-stimulated (24 h) CXCL10 promoter-of-origin
    5'-RACE TSS attribution and conditional BIO-06 AAV-ITR RNA-origin evaluator (IIP-0027; DEC-107).

    Enforces:
      - Named donor (cxcl10_tss_donor_id) and transcription unit (cxcl10_tss_transcription_unit_id);
      - Insert-matched comparator control verification (Giannakis et al. 2003 PMID:12951775);
      - Separate resting (0 h) AND interferon-stimulated (24 h) 5'-RACE TSS attribution classifying
        expected host / designed internal vs unexpected internal (k == 0) and unresolved (k == 0)
        origins, with recovery-adjusted N_UMI_eff >= 3,689 wherever expressed (3,688 exact two-sided
        95% Clopper-Pearson minimum for < 0.10% at k = 0; Kivioja et al. 2011 PMID:22101854);
      - Conditional Readout 1 BIO-06 AAV-ITR RNA-origin attribution (Earley et al. 2020 PMID:31914802;
        Haberman et al. 2000 PMID:10954575; Flotte et al. 1993 PMID:7679117) whenever locus-specific
        junction sequencing documents retained ITR DNA (obs_bio06_retained_aav_itr_dna_pct > 0%,
        alongside the < 0.5% DNA capture ceiling from Hanlon et al. 2019 PMID:31570731).
    """
    if not isinstance(observations, dict):
        raise ValueError('IIP-0027 promoter-origin observations must be a dictionary (IIP-0027; DEC-107)')

    def _get_num(key: str) -> float | None:
        if validated_stage0 is not None and key in validated_stage0:
            return float(validated_stage0[key])
        raw = observations.get(key)
        if raw is None or raw == 'UNAVAILABLE':
            return None
        if isinstance(raw, bool) or not isinstance(raw, (int, float)):
            return None
        val = float(raw)
        return val if math.isfinite(val) else None

    def _get_nonneg_int(key: str) -> tuple[bool, int | None]:
        raw = observations.get(key)
        if raw is None or raw == 'UNAVAILABLE':
            if validated_stage0 is not None and key in validated_stage0:
                vf = float(validated_stage0[key])
                if vf >= 0.0 and abs(vf - round(vf)) <= 1e-9:
                    return True, int(round(vf))
                return False, None
            return True, None
        if isinstance(raw, bool):
            return False, None
        if isinstance(raw, int):
            return (raw >= 0), (raw if raw >= 0 else None)
        if isinstance(raw, float) and math.isfinite(raw) and raw >= 0.0 and abs(raw - round(raw)) <= 1e-9:
            return True, int(round(raw))
        return False, None

    def _unpadded_id(val: object) -> bool:
        return isinstance(val, str) and val == val.strip() and 3 <= len(val) <= 120

    def _result(status: str, gate_pass: bool, **extra: Any) -> dict[str, Any]:
        return {
            'gate_pass': gate_pass,
            'hold_status': None if gate_pass else status,
            'status': status,
            'cxcl10_tss_donor_id': observations.get('cxcl10_tss_donor_id'),
            'cxcl10_tss_transcription_unit_id': observations.get('cxcl10_tss_transcription_unit_id'),
            'oq011_closed_by_computational_motif_count': False,
            'requires_empirical_race_per_condition_and_unit': True,
            **extra,
        }

    # Conditional BIO-06 ITR checks can also fire independently if retained ITR DNA or ITR RNA is observed:
    itr_dna_pct = _get_num('obs_bio06_retained_aav_itr_dna_pct')
    itr_rna_ok, itr_rna_k = _get_nonneg_int('obs_bio06_itr_origin_rna_umi_k')
    if not itr_rna_ok:
        return _result('HOLD_IIP0027_INVALID_NON_INTEGER_UMI_COUNT', False)
    if itr_dna_pct is not None and itr_dna_pct >= 0.5:
        return _result('HOLD_FAIL_BIO06_AAV_ITR_DNA_CAPTURE_GE_0P5PCT', False, retained_itr_dna_pct=itr_dna_pct)
    if itr_rna_k is not None and itr_rna_k > 0:
        return _result('HOLD_FAIL_IIP0027_AAV_ITR_ORIGIN_TRANSCRIPT_DETECTED', False, itr_origin_rna_umi_k=itr_rna_k)
    if itr_dna_pct is not None and itr_dna_pct > 0.0:
        if observations.get('bio06_itr_rna_origin_attribution_verified') is not True or itr_rna_k is None:
            return _result(
                'HOLD_IIP0027_RETAINED_AAV_ITR_DNA_REQUIRES_RNA_ORIGIN_ATTRIBUTION',
                False,
                retained_itr_dna_pct=itr_dna_pct,
            )

    # Check if only clean BIO-06 ITR check (0% DNA or verified 0 ITR RNA) was supplied without CXCL10 promoter-origin fields:
    cxcl10_keys_present = any(
        observations.get(k) is not None or (validated_stage0 is not None and k in validated_stage0)
        for k in (
            'require_full_iip0027_promoter_origin_and_itr_panel',
            'cxcl10_insert_matched_comparator_control_verified',
            'cxcl10_resting_expression_below_loq_confirmed',
            'cxcl10_tss_donor_id',
            'cxcl10_tss_transcription_unit_id',
            'obs_cxcl10_resting_race_umi_n_eff',
            'obs_cxcl10_resting_unexpected_tss_umi_k',
            'obs_cxcl10_resting_unresolved_origin_umi_k',
            'obs_cxcl10_ifng24h_race_umi_n_eff',
            'obs_cxcl10_ifng24h_unexpected_tss_umi_k',
            'obs_cxcl10_ifng24h_unresolved_origin_umi_k',
        )
    )
    if not cxcl10_keys_present:
        return _result('CLEARED_IIP0027_BIO06_CONDITIONAL_AAV_ITR_ORIGIN_CHECK', True, retained_itr_dna_pct=itr_dna_pct, itr_origin_rna_umi_k=itr_rna_k)

    if non_integer_denominator_flagged:
        return _result('HOLD_IIP0027_INVALID_NON_INTEGER_UMI_COUNT', False)
    if not (_unpadded_id(observations.get('cxcl10_tss_donor_id')) and _unpadded_id(observations.get('cxcl10_tss_transcription_unit_id'))):
        return _result('HOLD_IIP0027_MISSING_NAMED_DONOR_OR_TRANSCRIPTION_UNIT', False)
    if observations.get('cxcl10_insert_matched_comparator_control_verified') is not True:
        return _result('HOLD_IIP0027_MISSING_INSERT_MATCHED_COMPARATOR_CONTROL', False)

    r_n_ok, r_n = _get_nonneg_int('obs_cxcl10_resting_race_umi_n_eff')
    r_u_ok, r_u = _get_nonneg_int('obs_cxcl10_resting_unexpected_tss_umi_k')
    r_q_ok, r_q = _get_nonneg_int('obs_cxcl10_resting_unresolved_origin_umi_k')
    s_n_ok, s_n = _get_nonneg_int('obs_cxcl10_ifng24h_race_umi_n_eff')
    s_u_ok, s_u = _get_nonneg_int('obs_cxcl10_ifng24h_unexpected_tss_umi_k')
    s_q_ok, s_q = _get_nonneg_int('obs_cxcl10_ifng24h_unresolved_origin_umi_k')
    if not (r_n_ok and r_u_ok and r_q_ok and s_n_ok and s_u_ok and s_q_ok):
        return _result('HOLD_IIP0027_INVALID_NON_INTEGER_UMI_COUNT', False)

    if r_n is None or r_u is None or r_q is None:
        return _result('HOLD_IIP0027_MISSING_RESTING_0H_PROMOTER_ORIGIN_5PRIME_RACE', False)
    if s_n is None or s_u is None or s_q is None:
        return _result('HOLD_IIP0027_MISSING_IFNG24H_STIMULATED_PROMOTER_ORIGIN_5PRIME_RACE', False)

    if r_u > 0:
        return _result('HOLD_FAIL_IIP0027_RESTING_UNEXPECTED_INTERNAL_TSS_DETECTED', False, resting_unexpected_tss_umi_k=r_u)
    if s_u > 0:
        return _result('HOLD_FAIL_IIP0027_IFNG24H_UNEXPECTED_INTERNAL_TSS_DETECTED', False, ifng24h_unexpected_tss_umi_k=s_u)
    if r_q > 0:
        return _result('HOLD_IIP0027_RESTING_UNRESOLVED_TSS_ORIGIN', False, resting_unresolved_origin_umi_k=r_q)
    if s_q > 0:
        return _result('HOLD_IIP0027_IFNG24H_UNRESOLVED_TSS_ORIGIN', False, ifng24h_unresolved_origin_umi_k=s_q)

    resting_below_loq = observations.get('cxcl10_resting_expression_below_loq_confirmed') is True
    if not resting_below_loq and r_n < 3689:
        return _result('HOLD_IIP0027_RESTING_UMI_BELOW_3689', False, resting_race_umi_n_eff=r_n)
    if s_n < 3689:
        return _result('HOLD_IIP0027_IFNG24H_UMI_BELOW_3689', False, ifng24h_race_umi_n_eff=s_n)

    return _result(
        'CLEARED_IIP0027_RESTING_AND_STIMULATED_PROMOTER_ORIGIN_AND_ITR_GATES',
        True,
        resting_race_umi_n_eff=r_n,
        resting_below_loq_confirmed=resting_below_loq,
        ifng24h_race_umi_n_eff=s_n,
        retained_itr_dna_pct=itr_dna_pct,
        itr_origin_rna_umi_k=itr_rna_k,
    )


# ============================================================================
# Stage-0 ALK5i-Free Two-Clock Maturation, Two-Pulse Readout 2 with Adult-Islet
# Reference Floor, Inert-Tracer tau_chamber, and Non-Bypassable >138.3 IU Gate 0S
# Atomic-Ledger Escalation (IIP-0029; DEC-108)
# ============================================================================
_HEX64_RE_IIP0029 = re.compile(r'^[0-9a-fA-F]{64}$')

STAGE0_IIP0029_CONSTANTS: MappingProxyType = _deep_freeze_iip0024({
    'MIN_INDEPENDENT_LOTS_N': 6,
    'MIN_DEC084_MIXTURE_LOTS_N': 8,
    'MIN_PILOT_SELECTION_LOTS_N': 3,
    'STAGE7_MIN_TOTAL_DAYS': 7.0,
    'STAGE7_MAX_TOTAL_DAYS': 49.0,
    'SORTED_MIN_SORT_DAY': 7.0,
    'SORTED_MIN_POST_SORT_DAYS': 5.0,
    'BASELINE_WINDOW_MAX_STAGE7_DAYS': 28.0,
    'BASELINE_WINDOW_MAX_POST_SORT_DAYS': 14.0,
    'TIMESTAMP_DAY_TOLERANCE': 0.25,
    'SORTED_ETA_MIN': 0.05,
    'SORTED_ETA_MAX_EXCLUSIVE': 0.95,
    'CONTINUOUS_ZM447439_MIN_UM': 0.45,
    'CONTINUOUS_ZM447439_MAX_UM': 0.55,
    'PRE_IEC_ZM447439_MAX_LLOQ_UM': 0.005,
    'PRE_IEC_MIN_WASH_CYCLES': 3,
    'PRE_IEC_SPIKE_RECOVERY_MIN_PCT': 80.0,
    'PRE_IEC_SPIKE_RECOVERY_MAX_PCT': 120.0,
    'ALLOWED_ASSAY_PO2_MMHG': (40.0, 100.0),
    'INTEGRATED_SI1_MIN': 3.0,
    'DYNAMIC_PEAK1_OVER_BASAL1_MIN': 4.5,
    'DYNAMIC_TIME_TO_PEAK1_MAX_MIN': 8.0,
    'GATE0M_BASAL1_FRAC_PEAK1_MAX': 0.15,
    'DYNAMIC_LOW2_FRAC_PEAK1_MAX': 0.15,
    'LOW2_OVER_LOW1_WASHOUT_MAX': 1.50,
    'STATIC_LOW_OVER_KCL_MAX': 0.25,
    'GATE0M_GLUCAGON_FOLD_MIN': 2.0,
    'GATE0M_GLUCOSE_THRESHOLD_MIN_MM': 4.5,
    'GATE0M_UCN3_RATIO_MIN': 0.70,
    'GATE0M_COUNTERREG_GAIN_MIN': 0.80,
    'TRACER_TAU_CHAMBER_MAX_MIN': 0.50,
    'MIN_UNCENSORED_LOW2_DURATION_MIN': 10.0,
    'READOUT2_T50_MAX_MIN': 3.0,
    'GATE0M_T90_MAX_MIN': 3.0,
    'ADULT_ISLET_REF_PULSE2_MIN_FRACTION': 0.50,
    'REGISTERED_HORMONE_UNIT_SPECS': {
        'pmol_cpep_per_1e6_presort_cells_per_min': {
            'z_min_floor': 0.50,
            'required_denominator': '1e6_presort_viable_endocrine_cells',
        },
        'uIU_insulin_per_ug_dna_per_min': {
            'z_min_floor': 0.50,
            'required_denominator': 'ug_presort_viable_endocrine_dna',
        },
        'ng_insulin_per_1e5_presort_cells_per_30min': {
            'z_min_floor': 0.50,
            'required_denominator': '1e5_presort_viable_endocrine_cells',
        },
    },
    'REGISTERED_MIXTURES': {
        'REF_60_30_10': {'beta': 0.60, 'alpha': 0.30, 'delta': 0.10, 'is_reference': True},
        'DEC084_M1_70_20_10': {'beta': 0.70, 'alpha': 0.20, 'delta': 0.10, 'is_reference': False},
        'DEC084_M2_70_25_5': {'beta': 0.70, 'alpha': 0.25, 'delta': 0.05, 'is_reference': False},
        'DEC084_M3_80_15_5': {'beta': 0.80, 'alpha': 0.15, 'delta': 0.05, 'is_reference': False},
        'DEC084_M4_80_10_10': {'beta': 0.80, 'alpha': 0.10, 'delta': 0.10, 'is_reference': False},
    },
    'STORED_INSULIN_FLOOR_AT_300K_BETA_IU': 41.5,
    'GATE0S_ABSOLUTE_STORED_INSULIN_CEILING_IU': 138.3,
    'PROINSULIN_TO_CPEPTIDE_CONTENT_MOLAR_MAX': 0.10,
    'S8_WITHIN_RECIPE_FIELLER_THETA0': 0.85,
})

_FORBIDDEN_IIP0029_OVERRIDE_KEYS: frozenset[str] = frozenset({
    'execution_supported',
    'clinical_release_eligible',
    'gate0s_elevated_stored_insulin_clamp_reverified',
    'override_gate0s_ceiling',
    'bypass_atomic_ledger_gate0s',
})


def _strict_finite_float_iip0029(val: Any) -> float | None:
    if isinstance(val, bool) or not isinstance(val, (int, float)):
        return None
    fv = float(val)
    return fv if math.isfinite(fv) else None


def _strict_pos_int_iip0029(val: Any) -> int | None:
    if isinstance(val, bool) or not isinstance(val, int) or val <= 0:
        return None
    return int(val)


def _strict_unpadded_str_iip0029(val: Any, min_len: int = 1) -> str | None:
    if not isinstance(val, str):
        return None
    if len(val) < min_len or val != val.strip() or not val.strip():
        return None
    return val