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…

        return _hold('HOLD_ZM447439_CONCENTRATION_REGIMEN_MISMATCH')
    if zm_regimen == 'CONTINUOUS_0P5UM_BALBOA_S7' and not (
        float(C['CONTINUOUS_ZM447439_MIN_UM']) <= zm_uM <= float(C['CONTINUOUS_ZM447439_MAX_UM'])
    ):
        return _hold('HOLD_ZM447439_CONCENTRATION_REGIMEN_MISMATCH')

    iec_coassembled = record.get('vascular_iec_coassembled')
    if type(iec_coassembled) is not bool:
        return _hold('HOLD_MISSING_VASCULAR_IEC_COASSEMBLY_DECLARATION')
    if iec_coassembled is True:
        coassembly_zm = _strict_finite_float_iip0029(record.get('coassembly_zm447439_uM'))
        coassembly_lloq = _strict_finite_float_iip0029(record.get('coassembly_zm447439_lloq_uM'))
        wash_method = _strict_unpadded_str_iip0029(record.get('zm447439_washout_assay_method'), 3)
        wash_cycles = _strict_pos_int_iip0029(record.get('zm447439_wash_cycles'))
        spike_rec = _strict_finite_float_iip0029(record.get('zm447439_matrix_spike_recovery_pct'))
        if (
            coassembly_zm is None
            or coassembly_lloq is None
            or wash_method is None
            or wash_cycles is None
            or spike_rec is None
            or wash_cycles < int(C['PRE_IEC_MIN_WASH_CYCLES'])
            or not (0.0 < coassembly_lloq <= float(C['PRE_IEC_ZM447439_MAX_LLOQ_UM']))
            or not (0.0 <= coassembly_zm <= coassembly_lloq)
            or not (float(C['PRE_IEC_SPIKE_RECOVERY_MIN_PCT']) <= spike_rec <= float(C['PRE_IEC_SPIKE_RECOVERY_MAX_PCT']))
            or record.get('zm447439_washout_verified_pre_iec') is not True
            or record.get('pre_coassembly_iec_vascular_function_verified') is not True
        ):
            return _hold('HOLD_UNWASHED_OR_UNVERIFIED_LLOQ_ZM447439_OR_VASCULAR_FUNCTION_PRE_IEC')

    # 8. Integrated SI_1, KCl Reserve, Separate Readout 2 vs Gate 0M Basal/Peak/Shutoff & Full Gate 0M Paracrine (Sol Fix #2):
    _, low1_l95, _ = _one_sided_t_bounds_iip0029(low1_v, t_crit)
    _, si1_l95, _ = _one_sided_t_bounds_iip0029([h - float(C['INTEGRATED_SI1_MIN']) * lo for h, lo in zip(high1_v, low1_v)], t_crit)
    _, kcl_vs_h2_l95, _ = _one_sided_t_bounds_iip0029([k - h2 for k, h2 in zip(kcl_v, high2_v)], t_crit)
    _, kcl_vs_l2_l95, _ = _one_sided_t_bounds_iip0029([k - l2 for k, l2 in zip(kcl_v, low2_v)], t_crit)
    if low1_l95 <= 0.0 or si1_l95 < 0.0 or kcl_vs_h2_l95 <= 0.0 or kcl_vs_l2_l95 <= 0.0:
        return _hold('HOLD_INTEGRATED_SI1_OR_KCL_RESERVE_FAILED')

    basal_peak_stats: dict[str, Any] | None = None
    if fluidics == 'DYNAMIC_PERIFUSION':
        _, _, tau_ch_u95 = _one_sided_t_bounds_iip0029(tau_ch_v, t_crit)
        _, _, tau_100_u95 = _one_sided_t_bounds_iip0029(tau_100_v, t_crit)
        if tau_ch_u95 > float(C['TRACER_TAU_CHAMBER_MAX_MIN']) or tau_100_u95 > float(C['TRACER_TAU_CHAMBER_MAX_MIN']):
            return _hold('HOLD_CHAMBER_DISPERSION_TAU_EXCEEDED_REQUIRES_FAST_CHIP')
        if any(a >= b for a, b in zip(t50_v, t90_v)):
            return _hold('HOLD_SHUTOFF_T50_GE_T90_MONOTONICITY_VIOLATION')

        _, _, t50_u95 = _one_sided_t_bounds_iip0029(t50_v, t_crit)
        if t50_u95 > float(C['READOUT2_T50_MAX_MIN']):
            return _hold('HOLD_READOUT2_STEPDOWN_T50_U95_EXCEEDED')
        _, _, t90_u95 = _one_sided_t_bounds_iip0029(t90_v, t_crit)
        if t90_u95 > float(C['GATE0M_T90_MAX_MIN']):
            return _hold('HOLD_GATE0M_S8_STEPDOWN_T90_U95_EXCEEDED')

        # Canonical Readout 2 (Peak1/Basal1 >= 4.5 within <= 8.0 min) explicitly distinguished from
        # stricter Gate 0M / extended-maturation low-basal check (Basal1/Peak1 <= 0.15 => Peak1/Basal1 >= 6.67x):
        _, p1_4p5_l95, _ = _one_sided_t_bounds_iip0029([p - float(C['DYNAMIC_PEAK1_OVER_BASAL1_MIN']) * b for p, b in zip(peak1_v, basal1_v)], t_crit)
        _, _, tpeak1_u95 = _one_sided_t_bounds_iip0029(tpeak1_v, t_crit)
        if p1_4p5_l95 < 0.0 or tpeak1_u95 > float(C['DYNAMIC_TIME_TO_PEAK1_MAX_MIN']):
            return _hold('HOLD_READOUT2_FIRST_PHASE_PEAK_OR_LATENCY_FAILED')

        _, g0m_b1_l95, _ = _one_sided_t_bounds_iip0029([float(C['GATE0M_BASAL1_FRAC_PEAK1_MAX']) * p - b for p, b in zip(peak1_v, basal1_v)], t_crit)
        _, g0m_l2_l95, _ = _one_sided_t_bounds_iip0029([float(C['DYNAMIC_LOW2_FRAC_PEAK1_MAX']) * p - l2 for p, l2 in zip(peak1_v, low2_v)], t_crit)
        _, wash_l95, _ = _one_sided_t_bounds_iip0029([float(C['LOW2_OVER_LOW1_WASHOUT_MAX']) * l1 - l2 for l1, l2 in zip(low1_v, low2_v)], t_crit)
        if g0m_b1_l95 < 0.0 or g0m_l2_l95 < 0.0 or wash_l95 < 0.0:
            return _hold('HOLD_GATE0M_BASAL_FRAC_PEAK_OR_LOW2_WASHOUT_FAILED')

        # Full canonical Gate 0M paracrine checks (glucagon, threshold, UCN3, counterregulation):
        _, gcg_l95, _ = _one_sided_t_bounds_iip0029(gcg_fold_v, t_crit)
        _, thresh_l95, _ = _one_sided_t_bounds_iip0029(glc_thresh_v, t_crit)
        _, ucn3_l95, _ = _one_sided_t_bounds_iip0029(ucn3_v, t_crit)
        _, creg_l95, _ = _one_sided_t_bounds_iip0029(counterreg_v, t_crit)
        if (
            gcg_l95 < float(C['GATE0M_GLUCAGON_FOLD_MIN'])
            or thresh_l95 < float(C['GATE0M_GLUCOSE_THRESHOLD_MIN_MM'])
            or ucn3_l95 < float(C['GATE0M_UCN3_RATIO_MIN'])
            or creg_l95 < float(C['GATE0M_COUNTERREG_GAIN_MIN'])
        ):
            return _hold('HOLD_GATE0M_PARACRINE_GLUCAGON_THRESHOLD_UCN3_OR_COUNTERREG_FAILED')

        # Matched 100 mmHg sibling SI_1 and Z2 positivity verification:
        _, si1_100_l95, _ = _one_sided_t_bounds_iip0029([h - float(C['INTEGRATED_SI1_MIN']) * lo for h, lo in zip(h1_100_v, l1_100_v)], t_crit)
        z2_100_vec = [e * (h2 - l2) for e, h2, l2 in zip(eta_v, h2_100_v, l2_100_v)]
        _, z2_100_l95, _ = _one_sided_t_bounds_iip0029(z2_100_vec, t_crit)
        if si1_100_l95 < 0.0 or z2_100_l95 < z_min_floor:
            return _hold('HOLD_MATCHED_100MMHG_SIBLING_SI1_OR_PULSE2_INCREMENT_FAILED')

        b1_p1_ratios = [b / max(1e-12, p) for b, p in zip(basal1_v, peak1_v)]
        p1_b1_ratios = [p / max(1e-12, b) for b, p in zip(basal1_v, peak1_v)]
        basal_peak_stats = {
            'basal1_pre_pulse_window_min': [-10.0, 0.0],
            'peak1_window_min': [0.0, 8.0],
            'readout2_nominal_peak1_over_basal1_min': float(C['DYNAMIC_PEAK1_OVER_BASAL1_MIN']),
            'readout2_peak1_over_basal1_mean': round(sum(p1_b1_ratios) / float(n_lots), 4),
            'readout2_peak1_minus_4p5_basal1_l95': round(p1_4p5_l95, 4),
            'gate0m_strict_basal1_over_peak1_max': float(C['GATE0M_BASAL1_FRAC_PEAK1_MAX']),
            'gate0m_basal1_over_peak1_mean': round(sum(b1_p1_ratios) / float(n_lots), 4),
            'gate0m_0p15_peak1_minus_basal1_l95': round(g0m_b1_l95, 4),
            'relationship_note': 'Gate 0M Basal1/Peak1 <= 0.15 (Peak1/Basal1 >= 6.67x) is stricter than nominal Readout 2 Peak1/Basal1 >= 4.5x on the same pre-step [-10, 0] min Basal1 and [0, 8] min Peak1 windows.',
        }
    else:
        _, l1_kcl_l95, _ = _one_sided_t_bounds_iip0029([float(C['STATIC_LOW_OVER_KCL_MAX']) * k - l1 for k, l1 in zip(kcl_v, low1_v)], t_crit)
        _, l2_kcl_l95, _ = _one_sided_t_bounds_iip0029([float(C['STATIC_LOW_OVER_KCL_MAX']) * k - l2 for k, l2 in zip(kcl_v, low2_v)], t_crit)
        if l1_kcl_l95 < 0.0 or l2_kcl_l95 < 0.0:
            return _hold('HOLD_STATIC_BASAL_LEAK_OVER_KCL_EXCEEDED')

    # 9. Lot-Paired Pre-Sort-Normalized Net Increments Z1, Z2 + Contemporaneous Adult-Islet Reference Floor (Sol Fix #1):
    if 'within_lot_technical_var_z2' not in record:
        return _hold('HOLD_MISSING_EXPLICIT_WITHIN_LOT_TECHNICAL_VARIANCE')
    tech_var_z2 = _strict_finite_float_iip0029(record.get('within_lot_technical_var_z2'))
    if tech_var_z2 is None or tech_var_z2 < 0.0:
        return _hold('HOLD_INVALID_WITHIN_LOT_TECHNICAL_VARIANCE')

    z1_vec = [e * (h1 - l1) for e, h1, l1 in zip(eta_v, high1_v, low1_v)]
    z2_vec = [e * (h2 - l2) for e, h2, l2 in zip(eta_v, high2_v, low2_v)]
    z1_mean, z1_l95, _ = _one_sided_t_bounds_iip0029(z1_vec, t_crit)
    z2_mean, z2_l95, _ = _one_sided_t_bounds_iip0029(z2_vec, t_crit, extra_within_var=tech_var_z2 / float(n_lots))
    if z1_l95 < z_min_floor or z2_l95 < z_min_floor:
        return _hold('HOLD_NET_INCREMENT_PER_PRESORT_CELL_L95_INSUFFICIENT')

    # Contemporaneous same-assay adult-islet reference floor (blocks tiny 0.001 increments clearing on ratio alone!):
    ref_mean, ref_z2_l95, _ = _one_sided_t_bounds_iip0029(adult_ref_z2_v, t_crit)
    if ref_z2_l95 < z_min_floor:
        return _hold('HOLD_CONTEMPORANEOUS_ADULT_ISLET_REFERENCE_PULSE2_INSUFFICIENT')
    ref_frac = float(C['ADULT_ISLET_REF_PULSE2_MIN_FRACTION'])
    _, z2_vs_ref_l95, _ = _one_sided_t_bounds_iip0029([z2 - ref_frac * rv for z2, rv in zip(z2_vec, adult_ref_z2_v)], t_crit)
    if z2_vs_ref_l95 < 0.0:
        return _hold(
            'HOLD_SECOND_PULSE_BELOW_ADULT_ISLET_REFERENCE_FLOOR',
            z2_l95=round(z2_l95, 4),
            adult_ref_z2_mean=round(ref_mean, 4),
            z2_minus_half_adult_ref_l95=round(z2_vs_ref_l95, 4),
        )

    # 10. Clock-Classified Extended-Maturation Exposure -> Paired Within-Recipe Rule S8 Fieller (theta_0 = 0.85):
    is_extended_s8 = (s7_total > float(C['BASELINE_WINDOW_MAX_STAGE7_DAYS'])) or (
        post_sort > float(C['BASELINE_WINDOW_MAX_POST_SORT_DAYS'])
    )
    s8_fieller_l95: float | None = None
    if is_extended_s8:
        early_map = record.get('paired_earlier_window_z2_by_lot')
        if not isinstance(early_map, (dict, MappingProxyType)) or set(early_map.keys()) != set(lot_ids):
            return _hold('HOLD_S8_EXTENDED_CLOCK_REQUIRES_SOURCE_LINKED_EARLIER_WINDOW')
        early_vals: list[float] = []
        early_100_vals: list[float] = []
        early_traces_seen: set[str] = set()
        for lid in lot_ids:
            raw_e = early_map[lid]
            if isinstance(raw_e, (dict, MappingProxyType)):
                ebid = _strict_unpadded_str_iip0029(raw_e.get('differentiation_block_id'), 2)
                et40 = _strict_unpadded_str_iip0029(raw_e.get('trace_id_40mmhg'), 3)
                ez40 = _strict_finite_float_iip0029(raw_e.get('z2_40mmhg'))
                dt_eh = _parse_utc_iso_iip0029(raw_e.get('early_harvest_utc'))
                if (
                    ebid != block_by_lot[lid]
                    or et40 is None
                    or ez40 is None
                    or dt_eh is None
                    or dt_eh >= dt_harvest
                    or et40 in seen_trace_ids
                    or et40 in early_traces_seen
                ):
                    return _hold('HOLD_S8_EXTENDED_CLOCK_EARLIER_WINDOW_BLOCK_OR_TIMESTAMP_MISMATCH')
                early_traces_seen.add(et40)
                early_vals.append(ez40)
                if fluidics == 'DYNAMIC_PERIFUSION':
                    et100 = _strict_unpadded_str_iip0029(raw_e.get('trace_id_100mmhg'), 3)
                    ez100 = _strict_finite_float_iip0029(raw_e.get('z2_100mmhg'))
                    if et100 is None or ez100 is None or et100 in seen_trace_ids or et100 in early_traces_seen:
                        return _hold('HOLD_S8_EXTENDED_CLOCK_MISSING_MATCHED_100MMHG_EARLIER_ARM')
                    early_traces_seen.add(et100)
                    early_100_vals.append(ez100)
            else:
                return _hold('HOLD_S8_EXTENDED_CLOCK_REQUIRES_BLOCK_BOUND_EARLIER_RECORD')
        _, early_z2_l95, _ = _one_sided_t_bounds_iip0029(early_vals, t_crit)
        if early_z2_l95 < z_min_floor:
            return _hold('HOLD_S8_EARLIER_REFERENCE_WINDOW_FAILED_POSITIVITY_FLOOR')
        theta0 = float(C['S8_WITHIN_RECIPE_FIELLER_THETA0'])
        _, s8_fieller_l95, _ = _one_sided_t_bounds_iip0029([z_e - theta0 * z_0 for z_e, z_0 in zip(z2_vec, early_vals)], t_crit)
        if s8_fieller_l95 < 0.0:
            return _hold(
                'HOLD_S8_EXTENDED_MATURATION_FIELLER_DEGRADED_KEEP_EARLIER_WINDOW',
                s8_fieller_diff_l95=round(s8_fieller_l95, 4),
                theta0_applied=theta0,
            )
        if fluidics == 'DYNAMIC_PERIFUSION':
            _, early_100_l95, _ = _one_sided_t_bounds_iip0029(early_100_vals, t_crit)
            z2_100_v = [e * (h2 - l2) for e, h2, l2 in zip(eta_v, h2_100_v, l2_100_v)]
            _, s8_100_fieller_l95, _ = _one_sided_t_bounds_iip0029([z_e - theta0 * z_0 for z_e, z_0 in zip(z2_100_v, early_100_vals)], t_crit)
            if early_100_l95 < z_min_floor or s8_100_fieller_l95 < 0.0:
                return _hold(
                    'HOLD_S8_EXTENDED_MATURATION_100MMHG_FIELLER_DEGRADED',
                    s8_100mmhg_fieller_diff_l95=round(s8_100_fieller_l95, 4),
                )

    # 11. Specific Mature-Insulin Inventory Conservation, Exploratory Proinsulin:C-Peptide, & >138.3 IU Gate 0S Trigger:
    if record.get('insulin_inventory_assay_specificity') != 'MATURE_INSULIN_SPECIFIC_LOW_PROINSULIN_CROSSREACTIVITY':
        return _hold('HOLD_CROSS_REACTIVE_OR_UNVERIFIED_MATURE_INSULIN_INVENTORY_ASSAY')
    if 'assay_cumulative_secreted_iu_equiv' not in record:
        return _hold('HOLD_MISSING_EXPLICIT_ASSAY_CUMULATIVE_SECRETED_IU')
    cum_assay_iu = _strict_finite_float_iip0029(record.get('assay_cumulative_secreted_iu_equiv'))
    if cum_assay_iu is None or cum_assay_iu < 0.0:
        return _hold('HOLD_INVALID_ASSAY_CUMULATIVE_SECRETED_IU')

    beta_scale = (beta_frac / 0.60) * (imp_ieq / 500_000.0)
    min_phys_store_iu = max(float(C['STORED_INSULIN_FLOOR_AT_300K_BETA_IU']) * beta_scale, cum_assay_iu)
    _, stored_l95, stored_u95 = _one_sided_t_bounds_iip0029(stored_iu_v, t_crit)
    if stored_l95 < min_phys_store_iu:
        return _hold('HOLD_STORED_INSULIN_L95_BELOW_PHYSIOLOGICAL_OR_MASS_FLOOR')

    _, _, proins_u95 = _one_sided_t_bounds_iip0029(proins_ratio_v, t_crit)
    if proins_u95 > float(C['PROINSULIN_TO_CPEPTIDE_CONTENT_MOLAR_MAX']):
        return _hold(
            'HOLD_ELEVATED_PROINSULIN_TO_CPEPTIDE_CONTENT_RATIO',
            proinsulin_to_cpeptide_u95=round(proins_u95, 4),
            proinsulin_to_cpeptide_marker_classification='EXPLORATORY_STAGE0_IN_VITRO_PROCESSING_MARKER_PENDING_CALIBRATION',
        )

    max_lot_store_iu = max(stored_iu_v)
    ceiling_iu = float(C['GATE0S_ABSOLUTE_STORED_INSULIN_CEILING_IU'])
    if stored_u95 > ceiling_iu or max_lot_store_iu > ceiling_iu:
        return _hold(
            'HOLD_STORED_INSULIN_EXCEEDS_138P3_IU_REQUIRES_FULL_LINKED_GATE0S_LEDGER_REVIEW',
            gate0s_escalation_required=True,
            all_non_store_ceiling_checks_passed=True,
            stored_insulin_l95_iu=round(stored_l95, 4),
            stored_insulin_u95_iu=round(stored_u95, 4),
            stored_insulin_max_lot_iu=round(max_lot_store_iu, 4),
            registry_execution_supported=registry_exec_supported,
            proinsulin_to_cpeptide_u95=round(proins_u95, 4),
            proinsulin_to_cpeptide_marker_classification='EXPLORATORY_STAGE0_IN_VITRO_PROCESSING_MARKER_PENDING_CALIBRATION',
        )

    common_payload: dict[str, Any] = {
        'subgate_pass': True,
        'release_authority': 'DELEGATED_TO_LIVE_ATOMIC_STAGE0_LEDGER',
        'gate0s_escalation_required': False,
        'all_non_store_ceiling_checks_passed': True,
        'registry_execution_supported': registry_exec_supported,
        'is_extended_s8_exposure': is_extended_s8,
        'registered_mixture_id': reg_mix_id,
        't_crit_applied': round(t_crit, 6),
        'z1_mean': round(z1_mean, 4),
        'z1_l95': round(z1_l95, 4),
        'z2_mean': round(z2_mean, 4),
        'z2_l95': round(z2_l95, 4),
        'adult_islet_ref_z2_l95': round(ref_z2_l95, 4),
        'z2_minus_half_adult_ref_l95': round(z2_vs_ref_l95, 4),
        'stored_insulin_l95_iu': round(stored_l95, 4),
        'stored_insulin_u95_iu': round(stored_u95, 4),