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…

        'stored_insulin_max_lot_iu': round(max_lot_store_iu, 4),
        'proinsulin_to_cpeptide_u95': round(proins_u95, 4),
        'proinsulin_to_cpeptide_marker_classification': 'EXPLORATORY_STAGE0_IN_VITRO_PROCESSING_MARKER_PENDING_CALIBRATION',
        'proinsulin_provenance_note': (
            'Keymeulen et al. 2024 (PMID:38012450) measured post-hoc plasma proinsulin:C-peptide in a selected responder '
            'and does not validate 0.10 as a universal in-vitro cutoff; retained strictly as an exploratory Stage-0 processing marker.'
        ),
        's8_fieller_diff_l95': None if s8_fieller_l95 is None else round(s8_fieller_l95, 4),
        'post_sort_endocrine_zm447439_regimen': zm_regimen,
        'basal_peak_statistics_and_windows': basal_peak_stats,
        'diagnostic_high2_over_high1_mean_nonblocking': round(sum(h2 / max(1e-12, h1) for h2, h1 in zip(high2_v, high1_v)) / float(n_lots), 4),
    }
    if fluidics == 'STATIC_BATCH_BENCHMARK' or proc_mode == 'UNSORTED_CONTROL':
        common_payload['status'] = 'COMPARATIVE_BENCHMARK_QUALIFIED_NON_RELEASE'
        return common_payload
    if not registry_exec_supported:
        common_payload['status'] = 'RESEARCH_COMPARATOR_QUALIFIED_NON_EXECUTABLE'
        return common_payload
    common_payload['status'] = 'QUALIFIED_TWOCLOCK_REPEATED_CHALLENGE_SUBGATE_EVIDENCE_ONLY'
    return common_payload


def evaluate_stage0_twoclock_flat_or_structured_iip_0029(
    observations: dict[str, Any],
    *,
    validated_stage0: dict[str, float],
    se_provenance_by_mean: dict[str, str],
    upper95_fn: Any,
    lower95_fn: Any,
    root: Path | str | None = None,
    product_def: dict[str, Any] | None = None,
) -> dict[str, Any]:
    """
    Unified Stage-0 IIP-0029 evaluator wired identically into evaluate_stage0_decision_tree,
    evaluate_stage0_research_and_molecular_guardrails, ingest_stage0_research_or_wetlab_batch,
    and replay_stage0_chronological_batches (DEC-108).
    Enforces identical fail-closed handling for missing records, ALK5i/washout violations,
    wrong-lot scope mismatches, and non-overridable >138.3 IU Gate 0S escalations.
    """
    C = STAGE0_IIP0029_CONSTANTS

    def _res(status: str, gate_pass: bool, **extra: Any) -> dict[str, Any]:
        out: dict[str, Any] = {
            'gate_pass': gate_pass,
            'status': status,
            'release_authority': 'DELEGATED_TO_LIVE_ATOMIC_STAGE0_LEDGER',
            'decision_id': 'DEC-108',
            'contribution_id': 'IIP-0029',
        }
        out.update(extra)
        return out

    def _check_scope_matched_gate0s_escalation() -> tuple[bool, str]:
        req_g0s = (
            'obs_gate0s_ap1903_1h_insulin_burst_iu',
            'obs_gate0s_ap1903_supernatant_insulin_dump_fraction_24h',
            'obs_explant_en_bloc_recovery_fraction',
        )
        if not all(k in validated_stage0 and se_provenance_by_mean.get(k) == 'EXPLICIT_SE_SUPPLIED' for k in req_g0s):
            return False, 'HOLD_STORED_INSULIN_EXCEEDS_138P3_IU_REQUIRES_FULL_LINKED_GATE0S_LEDGER_REVIEW'
        outer_lot = observations.get('current_lot_id', observations.get('lot_id'))
        outer_dev = observations.get('device_assembly_id')
        matched_tag = observations.get('gate0s_elevated_store_scope_matched_device_lot_id')
        if outer_lot is not None or outer_dev is not None:
            if not isinstance(matched_tag, str) or not matched_tag.strip():
                return False, 'HOLD_STORED_INSULIN_EXCEEDS_138P3_IU_REQUIRES_FULL_LINKED_GATE0S_LEDGER_REVIEW'
            if outer_lot is not None and str(outer_lot) not in matched_tag:
                return False, 'FAIL_IIP0029_WRONG_LOT_OR_PRODUCT_SCOPE_MISMATCH'
            if outer_dev is not None and str(outer_dev) not in matched_tag:
                return False, 'FAIL_IIP0029_WRONG_LOT_OR_PRODUCT_SCOPE_MISMATCH'
        if upper95_fn('obs_gate0s_ap1903_1h_insulin_burst_iu') > 2.8:
            return False, 'FAIL_GATE0S_ELEVATED_STORE_BURST_OR_DUMP_BREACHED'
        if upper95_fn('obs_gate0s_ap1903_supernatant_insulin_dump_fraction_24h') > 0.15:
            return False, 'FAIL_GATE0S_ELEVATED_STORE_BURST_OR_DUMP_BREACHED'
        if lower95_fn('obs_explant_en_bloc_recovery_fraction') < 0.99:
            return False, 'FAIL_GATE0S_ELEVATED_STORE_BURST_OR_DUMP_BREACHED'
        return True, 'CLEARED_ESCALATED_SCOPE_MATCHED_GATE0S_REVIEW'

    structured = observations.get('iip0029_twoclock_record')
    if structured is not None:
        if not isinstance(structured, (dict, MappingProxyType)):
            return _res('HOLD_INVALID_RECORD_TYPE', False)
        # Verify lot & product provenance match outer payload scope (rejects wrong-lot borrowing!):
        rec_sk = _coerce_lot_scope_key_iip0029(structured.get('lot_scope_key'))
        if rec_sk is not None:
            outer_pvid = product_def.get('product_variant_id') if isinstance(product_def, dict) else observations.get('product_variant_id')
            outer_lot = observations.get('current_lot_id', observations.get('lot_id'))
            outer_csha = observations.get('construct_sha256')
            if outer_pvid is not None and rec_sk.product_variant_id != str(outer_pvid):
                return _res('FAIL_IIP0029_WRONG_LOT_OR_PRODUCT_SCOPE_MISMATCH', False)
            if outer_lot is not None and rec_sk.lot_id != str(outer_lot):
                return _res('FAIL_IIP0029_WRONG_LOT_OR_PRODUCT_SCOPE_MISMATCH', False)
            if outer_csha is not None and rec_sk.construct_sha256 != str(outer_csha):
                return _res('FAIL_IIP0029_WRONG_LOT_OR_PRODUCT_SCOPE_MISMATCH', False)

        sub = evaluate_stage0_twoclock_and_repeated_challenge_iip_0029(structured, root=root)
        if sub.get('gate0s_escalation_required') is True and sub.get('all_non_store_ceiling_checks_passed') is True:
            g0s_ok, g0s_status = _check_scope_matched_gate0s_escalation()
            if not g0s_ok:
                return _res(g0s_status, False, subgate=sub, gate0s_escalation_required=True)
            return _res(
                'CLEARED_IIP0029_WITH_ESCALATED_SCOPE_MATCHED_GATE0S_REVIEW',
                True,
                subgate=sub,
                gate0s_escalation_required=True,
                gate0s_escalation_status=g0s_status,
            )
        return _res(
            str(sub['status']),
            bool(sub['subgate_pass']),
            subgate=sub,
            gate0s_escalation_required=bool(sub.get('gate0s_escalation_required', False)),
        )

    # Flat endpoint evaluation path (identical fail-closed rules when structured record is omitted):
    if observations.get('obs_alk5i_free_maturation_applied') is not True or observations.get('terminal_alk5i_tgfb_inhibitor_continued') is not False:
        return _res('HOLD_PROHIBITED_OR_UNVERIFIED_ALK5I_FREE_MATURATION', False)
    if observations.get('stage7_t3_10nM_and_nac_1mM_retained') is not True:
        return _res('HOLD_STAGE7_MISSING_REQUIRED_10NM_T3_OR_1MM_NAC', False)

    zm_reg = observations.get('post_sort_endocrine_zm447439_regimen')
    if zm_reg not in ('S7W0_ONLY_0UM_POST_SORT', 'CONTINUOUS_0P5UM_BALBOA_S7'):
        return _res('HOLD_MISSING_OR_UNREGISTERED_ZM447439_COVARIATE', False)
    if (
        observations.get('zm447439_washout_verified_pre_iec') is not True
        or observations.get('pre_coassembly_iec_vascular_function_verified') is not True
        or 'obs_stage7_pre_iec_zm447439_residual_uM' not in validated_stage0
        or upper95_fn('obs_stage7_pre_iec_zm447439_residual_uM') > float(C['PRE_IEC_ZM447439_MAX_LLOQ_UM'])
    ):
        return _res('HOLD_UNWASHED_OR_UNVERIFIED_LLOQ_ZM447439_OR_VASCULAR_FUNCTION_PRE_IEC', False)

    if observations.get('readout2_both_40_and_100mmhg_tracer_aligned_verified') is not True:
        return _res('HOLD_MISSING_MATCHED_100MMHG_OXYGEN_COVERAGE_OR_TRACER_ALIGNMENT', False)
    if _strict_unpadded_str_iip0029(observations.get('locked_analysis_plan_id'), 4) is None:
        return _res('HOLD_MISSING_LOCKED_ANALYSIS_PLAN_ID', False)
    reg_mix = observations.get('registered_mixture_id')
    if not isinstance(reg_mix, str) or reg_mix not in C['REGISTERED_MIXTURES']:
        return _res('HOLD_MISSING_OR_UNREGISTERED_MIXTURE_ID', False)

    dt_s = _parse_utc_iso_iip0029(observations.get('stage7_start_utc'))
    dt_r = _parse_utc_iso_iip0029(observations.get('sort_reaggregation_utc'))
    dt_h = _parse_utc_iso_iip0029(observations.get('assay_harvest_utc'))
    if dt_s is None or dt_r is None or dt_h is None or not (dt_s <= dt_r <= dt_h):
        return _res('HOLD_MISSING_OR_INVALID_LOCKED_CLOCK_TIMESTAMPS', False)

    req_flat_means = (
        'obs_stage7_total_maturation_days',
        'obs_stage7_days_post_sort_reaggregation',
        'obs_stage7_eta_sort_viable_recovery',
        'obs_readout2_inert_tracer_tau_chamber_min',
        'obs_readout2_pulse2_net_increment_z2',
        'obs_readout2_adult_islet_ref_z2',
        'obs_readout2_low2_frac_peak1',
        'obs_readout2_low2_over_low1_ratio',
        'obs_stage7_stored_mature_insulin_iu_implanted',
        'obs_stage7_stored_mature_insulin_max_lot_iu',
        'obs_stage7_proinsulin_to_cpeptide_molar_ratio',
    )
    if any(k not in validated_stage0 or se_provenance_by_mean.get(k) != 'EXPLICIT_SE_SUPPLIED' for k in req_flat_means):
        return _res('HOLD_IIP0029_INCOMPLETE_OR_DEFAULT_SE_FLAT_PANEL', False)

    if upper95_fn('obs_readout2_inert_tracer_tau_chamber_min') > float(C['TRACER_TAU_CHAMBER_MAX_MIN']):
        return _res('HOLD_CHAMBER_DISPERSION_TAU_EXCEEDED_REQUIRES_FAST_CHIP', False)
    if lower95_fn('obs_readout2_pulse2_net_increment_z2') < 0.50 or lower95_fn('obs_readout2_adult_islet_ref_z2') < 0.50:
        return _res('HOLD_NET_INCREMENT_PER_PRESORT_CELL_L95_INSUFFICIENT', False)
    if lower95_fn('obs_readout2_pulse2_net_increment_z2') < float(C['ADULT_ISLET_REF_PULSE2_MIN_FRACTION']) * validated_stage0['obs_readout2_adult_islet_ref_z2']:
        return _res('HOLD_SECOND_PULSE_BELOW_ADULT_ISLET_REFERENCE_FLOOR', False)
    if upper95_fn('obs_readout2_low2_frac_peak1') > float(C['DYNAMIC_LOW2_FRAC_PEAK1_MAX']) or upper95_fn('obs_readout2_low2_over_low1_ratio') > float(C['LOW2_OVER_LOW1_WASHOUT_MAX']):
        return _res('HOLD_GATE0M_BASAL_FRAC_PEAK_OR_LOW2_WASHOUT_FAILED', False)

    is_ext_flat = (
        validated_stage0['obs_stage7_total_maturation_days'] > float(C['BASELINE_WINDOW_MAX_STAGE7_DAYS'])
        or validated_stage0['obs_stage7_days_post_sort_reaggregation'] > float(C['BASELINE_WINDOW_MAX_POST_SORT_DAYS'])
    )
    if is_ext_flat:
        if 'obs_stage7_s8_fieller_z2_diff' not in validated_stage0 or se_provenance_by_mean.get('obs_stage7_s8_fieller_z2_diff') != 'EXPLICIT_SE_SUPPLIED':
            return _res('HOLD_S8_EXTENDED_CLOCK_REQUIRES_SOURCE_LINKED_EARLIER_WINDOW', False)
        if lower95_fn('obs_stage7_s8_fieller_z2_diff') < 0.0:
            return _res('HOLD_S8_EXTENDED_MATURATION_FIELLER_DEGRADED_KEEP_EARLIER_WINDOW', False)

    if lower95_fn('obs_stage7_stored_mature_insulin_iu_implanted') < float(C['STORED_INSULIN_FLOOR_AT_300K_BETA_IU']):
        return _res('HOLD_STORED_INSULIN_L95_BELOW_PHYSIOLOGICAL_OR_MASS_FLOOR', False)
    if upper95_fn('obs_stage7_proinsulin_to_cpeptide_molar_ratio') > float(C['PROINSULIN_TO_CPEPTIDE_CONTENT_MOLAR_MAX']):
        return _res('HOLD_ELEVATED_PROINSULIN_TO_CPEPTIDE_CONTENT_RATIO', False)

    u95_store_flat = upper95_fn('obs_stage7_stored_mature_insulin_iu_implanted')
    max_lot_flat = validated_stage0['obs_stage7_stored_mature_insulin_max_lot_iu']
    ceiling_iu = float(C['GATE0S_ABSOLUTE_STORED_INSULIN_CEILING_IU'])
    if u95_store_flat > ceiling_iu or max_lot_flat > ceiling_iu:
        g0s_ok, g0s_status = _check_scope_matched_gate0s_escalation()
        if not g0s_ok:
            return _res(
                g0s_status,
                False,
                gate0s_escalation_required=True,
                stored_insulin_u95_iu=round(u95_store_flat, 4),
                stored_insulin_max_lot_iu=round(max_lot_flat, 4),
            )
        return _res(
            'CLEARED_IIP0029_WITH_ESCALATED_SCOPE_MATCHED_GATE0S_REVIEW',
            True,
            gate0s_escalation_required=True,
            gate0s_escalation_status=g0s_status,
            stored_insulin_u95_iu=round(u95_store_flat, 4),
            stored_insulin_max_lot_iu=round(max_lot_flat, 4),
        )

    return _res(
        'CLEARED_IIP0029_TWOCLOCK_REPEATED_CHALLENGE_FLAT_PANEL',
        True,
        gate0s_escalation_required=False,
        is_extended_s8_exposure=is_ext_flat,
        stored_insulin_u95_iu=round(u95_store_flat, 4),
        stored_insulin_max_lot_iu=round(max_lot_flat, 4),
        proinsulin_to_cpeptide_marker_classification='EXPLORATORY_STAGE0_IN_VITRO_PROCESSING_MARKER_PENDING_CALIBRATION',
    )


# ============================================================================
# Stage-0 Locus-2 CIITA Mode-B v3 Comparators, Rule S11, & Auditable GY-018
# Per-Fraction Binomial-Thinning Tier 6B Evaluator (IIP-0031; DEC-110)
# ============================================================================
TIER6B_PER_FRACTION_LOT_CAP_IIP0031: float = 3.0e-7
TIER6B_DETECTION_FLOOR_IIP0031: float = 0.50
TIER6B_ALLOWED_PRESORT_LINEAGE_PANEL_IIP0031: str = 'CD31_NEG_CD144_NEG_ENDOCRINE_PRE_ASSEMBLY'
TIER6B_ALLOWED_ENDOGENOUS_BASES_IIP0031: frozenset[str] = frozenset({
    'MATCHED_UNTREATED_CLONOGENIC_CONTROL',
    'VALIDATED_CONSERVATIVE_BOUND',
})
TIER6B_ALLOWED_RISK_UNITS_IIP0031: frozenset[str] = frozenset({
    'SORTED_SINGLE_CELL_EQUIVALENT_CLONOGENIC_OPPORTUNITY',
    'CD31_NEG_CD144_NEG_CLONOGENIC_OPPORTUNITY',
})
TIER6B_ALLOWED_TIMEPOINTS_IIP0031: frozenset[str] = frozenset({
    'STAGE7_PRE_ASSEMBLY',
    'PRE_ASSEMBLY_STAGE7',
    'STAGE0_PRE_ASSEMBLY_STAGE7',
    'STAGE0_STAGE7_PRE_ASSEMBLY',
})
TIER6B_ALLOWED_STAGE_LABELS_IIP0031: frozenset[str] = frozenset({
    'STAGE7_PRE_ASSEMBLY',
    'PRE_ASSEMBLY_STAGE7',
    'STAGE0_PRE_ASSEMBLY_STAGE7',
    'STAGE0_STAGE7_PRE_ASSEMBLY',
})
TIER6B_ALLOWED_ASSAY_VERSIONS_IIP0031: frozenset[str] = frozenset({
    'STAGE0_IIP0031_V1',
    'STAGE0_IIP0031_TIER6B_V1',
    'TIER6B_SORTED_LOT_V1',
})