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…

            or _upper95('obs_design_y02_wt_b2m_residual_allele_frac') > 0.001
            or _upper95('obs_design_y02_backbone_kanr_vaf') > 0.0001
            or abs(validated_stage0['obs_design_y02_wgs_pseudosite_k']) > 1e-9
        ):
            iip0023_dy_status = 'HOLD_DESIGN_Y02_EEPASSIGE_HOMOZYGOUS_CN2_KANR_OR_PSEUDOSITE_GATE_FAILED'
        elif (
            _lower95('obs_design_y03_iec_beta_selectivity_ratio') < 50.0
            or _lower95('obs_design_y03_beta_mir375_retention_pct') < 90.0
            or _lower95('obs_design_y03_coculture_gsis_si') < 2.5
            or _lower95('obs_design_y03_gsis_retention_pct') < 90.0
            or _upper95('obs_design_y03_supernatant_adenosine_nM') > 25.0
            or _upper95('obs_design_y03_dpcpx_gsis_delta_pct') > 10.0
        ):
            iip0023_dy_status = 'HOLD_DESIGN_Y03_ADORA1_PARACRINE_GSIS_OR_CD200_SELECTIVITY_FAILED'
        else:
            _dy_surv_k = validated_stage0['obs_design_y04_ap1903_survivor_count_k']
            _dy_neff = validated_stage0['obs_design_y04_ap1903_effective_trials']
            _dy_poisson_u95 = _poisson_exact_upper95_rate(_dy_surv_k, _dy_neff) if _dy_neff > 0.0 else 1.0
            if (
                _lower95('obs_design_y04_multicistron_retention_pct') < 95.0
                or _upper95('obs_design_y04_nhs20_c5b9_mac_pct') > 5.0
                or _upper95('obs_design_y04_indirect_apc_cd4_si') > 1.5
                or 'obs_kir_nkg2a_neg_nk_lysis_pct' not in validated_stage0
                or kir_nkg2a_neg_upper95 > 8.0
                or _dy_neff < 299573228.0
                or abs(_dy_surv_k) > 1e-9
                or _dy_poisson_u95 > 1e-8
                or _upper95('obs_design_y04_ap1903_clonogenic_survival_frac') > 1e-8
                or ('obs_gsis_si' in validated_stage0 and _lower95('obs_gsis_si') < 3.0)
            ):
                iip0023_dy_status = 'HOLD_DESIGN_Y04_MULTICISTRON_COMPLEMENT_KIR_OR_3E8_CLONOGENIC_GATE_FAILED'
            else:
                iip0023_dy_status = 'CLEARED_DESIGN_Y_WILDCARD_COUPONS_ELIGIBLE_FOR_SEPARATE_D2_CHALLENGE_PROPOSAL_ONLY'
        if iip0023_dy_status != 'CLEARED_DESIGN_Y_WILDCARD_COUPONS_ELIGIBLE_FOR_SEPARATE_D2_CHALLENGE_PROPOSAL_ONLY':
            iip0023_hold_status = iip0023_dy_status

    iip0023_eval_summary: dict[str, object] | None = None
    if _iip0023_dy_active:
        iip0023_eval_summary = {
            'gate_pass': iip0023_hold_status is None,
            'hold_status': iip0023_hold_status,
            'wildcard_status': iip0023_dy_status,
            'design_y_integrase_modality': _dy_int_mod,
            'design_y_silencing_modality': _dy_sil_mod,
            'design_y_payload_arm': _dy_pay_arm,
            'auto_promotes_into_core_blueprints': False,
        }

    # S8b TYK2 x inducible-promoter epistasis: support explicit enumerated scale {FRACTION_HALF_EFFECT, PP_HALF_EFFECT, PP_FULL_CONTRAST, DID_PP} with per-endpoint scale retention across batches, unified fractional half-effect threshold (point < -0.05 or lower95 < -0.10), and sign-independent underpowered SE hold (AUDIT-REF & AUDIT-REF; DEC-042/044):
    s8b_scale_enum = observations.get('s8b_epistasis_estimand_scale')
    if s8b_scale_enum is not None:
        if not isinstance(s8b_scale_enum, str) or s8b_scale_enum.strip() not in ALLOWED_S8B_EPISTASIS_ESTIMAND_SCALES:
            raise ValueError(
                f"Invalid s8b_epistasis_estimand_scale {s8b_scale_enum!r}; must be one of {sorted(ALLOWED_S8B_EPISTASIS_ESTIMAND_SCALES)} (AUDIT-REF)"
            )
        s8b_scale_enum = s8b_scale_enum.strip()

    def _eval_tyk2_beta(mean_key: str, se_key: str, scale_key: str) -> tuple[bool, bool]:
        if mean_key not in validated_stage0:
            return False, False
        raw_b = validated_stage0[mean_key]
        ep_scale_raw = observations.get(scale_key)
        if ep_scale_raw is not None:
            if not isinstance(ep_scale_raw, str) or ep_scale_raw.strip() not in ALLOWED_S8B_EPISTASIS_ESTIMAND_SCALES:
                raise ValueError(
                    f"Invalid {scale_key} {ep_scale_raw!r}; must be one of {sorted(ALLOWED_S8B_EPISTASIS_ESTIMAND_SCALES)} (AUDIT-REF)"
                )
            eff_scale = ep_scale_raw.strip()
        else:
            eff_scale = s8b_scale_enum
        if eff_scale == 'FRACTION_HALF_EFFECT':
            scale_div = 1.0
        elif eff_scale == 'PP_HALF_EFFECT':
            scale_div = 100.0
        elif eff_scale == 'PP_FULL_CONTRAST':
            scale_div = 200.0
        elif eff_scale == 'DID_PP':
            scale_div = 400.0
        else:
            is_pp_scale = abs(raw_b) > 1.0 or str(observations.get('estimand_scale', '')).endswith('_pp')
            scale_div = 100.0 if is_pp_scale else 1.0
        b_frac = raw_b / scale_div
        thresh_frac = -0.05
        if se_provenance_by_mean.get(mean_key) == 'EXPLICIT_SE_SUPPLIED':
            raw_s = validated_stage0_se.get(se_key, 0.0)
            s_frac = (raw_s / scale_div) if eff_scale is not None else (raw_s / scale_div if (scale_div > 1.0 or raw_s > 0.5) else raw_s)
            # If SE is so wide (> 0.15 fractional = 15 pp half-effect) that the test cannot rule out a >10 pp deficit, flag as underpowered/inconclusive hold regardless of point sign (AUDIT-REF & AUDIT-REF):
            if s_frac > 0.15:
                return False, True
        else:
            s_frac = float(STAGE0_CUSTOM_DEFAULT_SE.get(mean_key, 0.05))
        b_lower95 = b_frac - 1.645 * s_frac
        return bool(b_frac < thresh_frac or b_lower95 < -0.10), False

    x14_trig, x14_underpowered = _eval_tyk2_beta('obs_beta_x1_x4_epistasis', 'obs_beta_x1_x4_epistasis_se', 'obs_beta_x1_x4_epistasis_scale')
    x34_trig, x34_underpowered = _eval_tyk2_beta('obs_beta_x3_x4_epistasis', 'obs_beta_x3_x4_epistasis_se', 'obs_beta_x3_x4_epistasis_scale')
    sat_trig = bool(_lower95('obs_tyk2_p1104a_3x2_satellite_shield_induction_pct', 95.0) < 70.0)
    is_tyk2_product_or_unspecified = bool(
        product_def is None
        or 'TYK2' in str(product_def.get('product_variant_id', '')).upper()
        or any('TYK2' in str(e).upper() for e in product_def.get('edits', []))
    )
    s8_tyk2_epistasis_triggered = bool(
        is_tyk2_product_or_unspecified and (x14_trig or x34_trig or sat_trig)
    )
    s8_tyk2_epistasis_underpowered_hold = bool(
        is_tyk2_product_or_unspecified and (x14_underpowered or x34_underpowered)
    )
    subthreshold_outer_band_kperf = bool(
        'obs_outer_band_kperf_s_inv' in validated_stage0
        and 1e-5 < _lower95('obs_outer_band_kperf_s_inv') < 0.10
    )
    periimplant_fluid_film_gt_80_failed = bool(
        'obs_periimplant_fluid_film_um' in validated_stage0
        and _upper95('obs_periimplant_fluid_film_um') > 80.0
    )
    periimplant_fluid_film_50_to_80_unmitigated = bool(
        'obs_periimplant_fluid_film_um' in validated_stage0
        and 50.0 < _upper95('obs_periimplant_fluid_film_um') <= 80.0
        and observations.get('periimplant_closed_suction_drain_verified') is not True
    )
    periimplant_fluid_film_failed = bool(
        periimplant_fluid_film_gt_80_failed
        or periimplant_fluid_film_50_to_80_unmitigated
    )
    explant_retrieval_failed = bool(
        ('obs_explant_en_bloc_recovery_fraction' in validated_stage0 and _lower95_student_t('obs_explant_en_bloc_recovery_fraction') < 0.99)
        or ('obs_gate0s_day30_en_bloc_recovery_fraction' in validated_stage0 and _lower95_student_t('obs_gate0s_day30_en_bloc_recovery_fraction') < 0.99)
        or ('obs_gate0s_day90_en_bloc_recovery_fraction' in validated_stage0 and _lower95_student_t('obs_gate0s_day90_en_bloc_recovery_fraction') < 0.99)
        or observations.get('obs_vascularized_explant_en_bloc_recovery_verified') is False
    )
    ap1903_insulin_dump_failed = bool(
        ('obs_gate0s_ap1903_supernatant_insulin_dump_fraction_24h' in validated_stage0 and _upper95('obs_gate0s_ap1903_supernatant_insulin_dump_fraction_24h') > 0.15)
        or ('obs_gate0s_ap1903_1h_insulin_burst_iu' in validated_stage0 and _upper95('obs_gate0s_ap1903_1h_insulin_burst_iu') > 2.8)
    )
    ap1903_insulin_dump_unmitigated = bool(
        ap1903_insulin_dump_failed
        and observations.get('s9_staged_cassette_excision_and_d10w_clamp_qualified') is not True
    )
    senescent_p16_upper95 = _prop_or_pct_u95(
        'obs_senescent_p16_sasp_positive_cell_pct',
        'obs_senescent_p16_sasp_cells_scored',
        is_pct=True,
    )
    senescent_p16_sasp_failed = bool(
        'obs_senescent_p16_sasp_positive_cell_pct' in validated_stage0
        and senescent_p16_upper95 > 1.0
    )
    periimplant_fluid_film_gt_50_triggered = bool(
        'obs_periimplant_fluid_film_um' in validated_stage0
        and (
            validated_stage0['obs_periimplant_fluid_film_um'] > 50.0
            or _upper95('obs_periimplant_fluid_film_um') > 50.0
        )
    )
    s9_promoted = bool(
        (has_chronic_capsule_obs and capsule_dz_upper95 > 10.4)
        or _lower95('obs_d_o2_gel_aged_cm2_s', 1.5e-5) < 1.50e-5
        or _lower95('obs_capsule_d_o2_cm2_s', 1.5e-5) < 1.50e-5
        or _upper95('obs_cao2_kinetic_law', 0.0) >= 1.5
        or observations.get('obs_masked_perfusion_confirmed') is True
        or observations.get('s9_mineral_pore_occlusion_gt_15pct') is True
        or periimplant_fluid_film_gt_50_triggered
    )
    primary_biological_or_pouch_gate_failed = bool(
        ('obs_pouch_min_po2_mmhg' in validated_stage0 and _lower95('obs_pouch_min_po2_mmhg') < 15.0)
        or ('obs_pouch_max_h2o2_uM' in validated_stage0 and _upper95('obs_pouch_max_h2o2_uM') > 5.0)
        or ('obs_pouch_max_ph' in validated_stage0 and _upper95('obs_pouch_max_ph') > 7.45)
        or ('obs_ifng_hla_dr_dq_negative_pct' in validated_stage0 and _lower95('obs_ifng_hla_dr_dq_negative_pct') < 99.0)
        or ('obs_stage7_yield_ratio' in validated_stage0 and _lower95('obs_stage7_yield_ratio') < 0.70)
        or ('obs_cd47_fold' in validated_stage0 and _lower95('obs_cd47_fold') < 3.0)
        or ('obs_day28_functional_beta_survival_fraction' in validated_stage0 and _lower95('obs_day28_functional_beta_survival_fraction') < 0.80)
    )

    # Stage-0 atomic provenance, donor-bank kinship, Readout-2 kinetics, CD16+ ADCC, coupled catalase endotoxin, Gate 0S dual shedding, 3-metric IAPP, and Design Z route binding (IIP-0024; DEC-103):
    _req_iip0024_full = observations.get('require_full_iip0024_atomic_provenance_and_bank_panel') is True
    _iip0024_quant_or_flag_keys = (
        'obs_mcb_donor_pairwise_ibd_pi_hat',
        'obs_mcb_1q32_mdm4_cnv_ratio',
        'obs_mcb_1q32_mdm4_single_cell_mosaic_fraction',
        'obs_1q32_mdm4_cnv_ratio',
        'obs_1q32_mdm4_single_cell_mosaic_fraction',
        'obs_readout2_perifusion_gsis_si',
        'obs_readout2_first_phase_peak_to_basal_ratio',
        'obs_readout2_first_phase_time_to_peak_min',
        'obs_readout2_stepdown_shutoff_t50_min',
        'obs_exact_product_net_cd16_adcc_lysis_pct',
        'obs_cd16_adcc_positive_control_lysis_pct',
        'obs_p05_total_loaded_catalase_protein_mg',
        'obs_gate0s_shedding_ddpcr_events_k',
        'obs_gate0s_shedding_ddpcr_trials_n',
        'obs_gate0s_shedding_viable_events_k',
        'obs_gate0s_shedding_viable_trials_n',
        'obs_stage0_independent_lot_replicates_n',
        'obs_iapp_3metric_thioflavin_s_area_pct',
        'obs_iapp_3metric_soluble_oligomer_fold',
        'obs_iapp_3metric_insoluble_fibril_fold',
    )
    _iip0024_bool_or_meta_keys = (
        'cd16_adcc_igg_depletion_paired_control_verified',
        'iapp_age_matched_reference_above_loq_verified',
        'mcb_imprinting_ic1_ic2_igdmr_conjunctive_cleared',
        'stage7_lot_imprinting_ic1_ic2_igdmr_conjunctive_cleared',
        'mcb_and_lot_xci_46xx_3axis_cleared_or_46xy',
        'mcb_and_lot_mtdna_1000x_numt_filtered_cleared',
        'physical_route_id',
        'donor_seedline_id',
        'device_assembly_id',
    )
    _is_design_z_product = bool(
        product_def is not None
        and str(product_def.get('product_variant_id', '')) == 'ISLET1_Z_X_MOL_140UM_ZERO_CAO2'
    )
    _iip0024_active = bool(
        _req_iip0024_full
        or _is_design_z_product
        or any(_k in validated_stage0 for _k in _iip0024_quant_or_flag_keys)
        or any(observations.get(_bk) is not None for _bk in _iip0024_bool_or_meta_keys)
    )
    iip0024_hold_status: str | None = None
    _phys_route_in = observations.get('physical_route_id')
    if isinstance(_phys_route_in, str):
        _phys_route_in = _phys_route_in.strip()
    if _phys_route_in is not None:
        _is_z_route = _phys_route_in in ('Z_OMENTAL_140UM_ZERO_CAO2', 'DESIGN_Z_140UM_ZERO_CAO2_PLAIN_HYDROGEL', 'DESIGN_Z_140UM_ZERO_CAO2_EXPLORATORY_DIVIDER')
        _is_cao2_route = _phys_route_in == 'SUPRAFASCIAL_350UM_CAO2_CATALASE_POUCH'
        if not (_is_z_route or _is_cao2_route):
            iip0024_hold_status = 'HOLD_UNREGISTERED_PHYSICAL_ROUTE_ID'
        elif _is_design_z_product and not _is_z_route:
            iip0024_hold_status = 'HOLD_BIDIRECTIONAL_PRODUCT_PHYSICAL_ROUTE_MISMATCH'
        elif product_def is not None and not _is_design_z_product and product_def.get('family') in ('A', 'B') and _is_z_route:
            iip0024_hold_status = 'HOLD_BIDIRECTIONAL_PRODUCT_PHYSICAL_ROUTE_MISMATCH'
    if iip0024_hold_status is None and product_def is not None and not _is_design_z_product and (
        _dz_arm_val is not None or any(_k.startswith('obs_design_z_') for _k in validated_stage0)
    ):
        iip0024_hold_status = 'HOLD_BIDIRECTIONAL_PRODUCT_PHYSICAL_ROUTE_MISMATCH'
    if iip0024_hold_status is None and _is_design_z_product and (
        observations.get('p05_catalase_uniprot_accession') is not None
        or any(_k.startswith('obs_p05_') for _k in validated_stage0)
    ):
        iip0024_hold_status = 'HOLD_BIDIRECTIONAL_PRODUCT_PHYSICAL_ROUTE_MISMATCH'
    if iip0024_hold_status is None and _is_design_z_product:
        if iip0019_dz_status != 'CLEARED_DESIGN_Z_TWO_STAGE_EMPTY_LUMEN_AND_LOADED_CLOSED_STATE_GATE':
            iip0024_hold_status = iip0019_transport_hold_status or 'HOLD_DESIGN_Z_WILDCARD_TWO_STAGE_QUALIFICATION_REQUIRED'
    if iip0024_hold_status is None and stage0_replicates_below_6_hold:
        iip0024_hold_status = 'HOLD_STAGE0_INDEPENDENT_LOT_REPLICATES_BELOW_6_STUDENT_T_MINIMUM'
    if iip0024_hold_status is None and 'obs_mcb_donor_pairwise_ibd_pi_hat' in validated_stage0:
        if validated_stage0['obs_mcb_donor_pairwise_ibd_pi_hat'] >= 0.05 or _upper95('obs_mcb_donor_pairwise_ibd_pi_hat') >= 0.05:
            iip0024_hold_status = 'HOLD_MCB_DONOR_SEEDLINE_PAIRWISE_IBD_PI_HAT_GE_0P05'
    if iip0024_hold_status is None and any(