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…

            'upper95': param_u95,
            'depth_explicit': True,
            'depth_underpowered': True,
        }

    depth_f = float(duplex_depth)
    k_from_rate = val_f * depth_f
    if mutant_molecules_k is not None:
        k_sup = float(mutant_molecules_k)
        if abs(k_sup - k_from_rate) > 0.51:
            bad_count = True
        k_est = max(k_sup, k_from_rate)
    else:
        k_est = k_from_rate
    pois_u95 = _poisson_exact_upper95_rate(k_est, depth_f)
    eff_u95 = max(param_u95, pois_u95)
    if val_f >= cap or eff_u95 >= cap:
        return {
            'status': 'FAIL_HARD_STOP',
            'hard_stop': True,
            'upper95': eff_u95,
            'depth_explicit': True,
            'depth_underpowered': bool(depth_f < min_depth),
        }
    if bad_count:
        return {
            'status': 'HOLD_S9_INVALID_OR_CONFLICTING_EVENT_COUNT',
            'hard_stop': False,
            'upper95': eff_u95,
            'depth_explicit': True,
            'depth_underpowered': depth_f < min_depth,
        }
    if depth_f < min_depth:
        return {
            'status': 'HOLD_S9_DUPLEX_DEPTH_UNDERPOWERED_BELOW_62958',
            'hard_stop': False,
            'upper95': eff_u95,
            'depth_explicit': True,
            'depth_underpowered': True,
        }
    return {
        'status': 'PASS',
        'hard_stop': False,
        'upper95': eff_u95,
        'depth_explicit': True,
        'depth_underpowered': False,
    }


STAGE0_STRICT_INTEGER_COUNT_AND_DENOMINATOR_KEYS: frozenset[str] = frozenset({
    'obs_20q11_bcl2l1_single_cell_mosaic_cells_scored',
    'obs_17q_birc5_survivin_single_cell_mosaic_cells_scored',
    'obs_gate0v_day28_persistent_vp1_ie1_cells_scored',
    'obs_cd24_sox2_oct4_3d_escapee_cells_scored',
    'obs_off_target_gp2_amylase_acinar_cells_scored',
    'obs_off_target_krt19_cftr_ductal_cells_scored',
    'obs_assembled_cluster_ki67_progenitor_cells_scored',
    'obs_ductal_sox9_krt19_double_pos_cells_scored',
    'obs_assembled_cluster_slc18a1_enterochromaffin_cells_scored',
    'obs_senescent_p16_sasp_cells_scored',
    'obs_mcb_1q32_mdm4_single_cell_mosaic_cells_scored',
    'obs_1q32_mdm4_single_cell_mosaic_cells_scored',
    'obs_mcb_effective_clonogenic_trials',
    'obs_mcb_clonogenic_survivor_count_k',
    'obs_residual_psc_effective_trials',
    'obs_hazard_state_prolif_effective_trials',
    'obs_hazard_state_prolif_survivor_count_k',
    'obs_ap1903_step1_sublethal_survivor_count_k',
    'obs_dxs_screened_cell_count',
    '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_cuff_serum_donor_count',
    'obs_cuff_serum_failing_donor_count',
    'obs_hcmv_pos_donor_count',
    'obs_s10_nk_failing_donor_count',
    'obs_ul40_reactive_donor_count',
    'obs_ul40_ctl_failing_donor_count',
    'obs_track2_bsct_donor_count',
    'obs_track2_bsct_failing_donor_count',
    'obs_track2_hlag1_donor_count',
    'obs_track2_hlag1_failing_donor_count',
    'obs_challenger_aberrant_splice_umi_count_k',
    'obs_design_y02_wgs_pseudosite_k',
    'obs_design_y04_all4_lineages_scored_count',
    'obs_design_y04_ap1903_survivor_count_k',
    'obs_design_b_locus5_5prime_race_coord_bp',
    'obs_design_b_locus5_3prime_race_coord_bp',
    'obs_design_b_locus5_race_umi_n_eff',
    'obs_design_b_locus5_aberrant_umi_k',
    'obs_tyk2_pe4max_pentaplex_msi_shifts_k',
    'obs_tyk2_pe4max_wgs_repeat_indels_clone',
    'obs_tyk2_pe4max_wgs_repeat_indels_ctrl',
    'obs_tyk2_pe4max_coding_or_splice_de_novo_indels',
    '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',
    'obs_bio06_itr_origin_rna_umi_k',
})


def evaluate_stage0_decision_tree(
    observations: dict,
    *,
    root: Path | str | None = None,
    require_full_5endpoint_s9_panel: bool = False,
    defaulted_se_keys: list[str] | set[str] | None = None,
    prior_batch_sticky_s9_safety_stop: bool = False,
    product_def: dict | None = None,
) -> dict:
    """Deterministically evaluate the machine-readable Stage-0 promotion/fallback decision tree (S1..S9; AUDIT-REF, AUDIT-REF, AUDIT-REF, AUDIT-REF, AUDIT-REF, & R7S3-F01/F02; DEC-058; IIP-0024; DEC-103)."""
    if not isinstance(observations, dict):
        raise ValueError('Stage-0 decision-tree observations must be a dictionary')
    if type(require_full_5endpoint_s9_panel) is not bool:
        raise ValueError('require_full_5endpoint_s9_panel must be a boolean')
    if type(prior_batch_sticky_s9_safety_stop) is not bool:
        raise ValueError('prior_batch_sticky_s9_safety_stop must be a boolean')
    observations = _canonicalize_stage0_alias_keys(observations)
    for bkey in STAGE0_DECISION_TREE_BOOLEAN_KEYS:
        if bkey in observations and observations[bkey] is not None:
            if type(observations[bkey]) is not bool:
                raise ValueError(f'{bkey} must be a boolean when provided')
    if observations.get('require_full_5endpoint_s9_panel') is True:
        require_full_5endpoint_s9_panel = True
    root_path = Path(root) if root is not None else Path(__file__).resolve().parents[1]
    tree_doc = json.loads((root_path / STAGE0_DECISION_TREE_RELATIVE_PATH).read_text(encoding='utf-8'))
    p_mod = _load_product_contract_module(root_path)
    # Canonical product resolution (IIP-0024 & IIP-0028; DEC-103 & DEC-106): reject whitespace-padded IDs and caller-overridden lifecycle/execution_supported fields!
    obs_pvid_raw = observations.get('product_variant_id')
    if obs_pvid_raw is not None:
        if not isinstance(obs_pvid_raw, str) or not obs_pvid_raw.strip() or obs_pvid_raw != obs_pvid_raw.strip():
            raise ValueError(f'Invalid or whitespace-padded product_variant_id: {obs_pvid_raw!r} (IIP-0024; DEC-103)')
        canon_from_obs = p_mod.get_product_definition(obs_pvid_raw, root=root_path)
        if product_def is not None:
            if not isinstance(product_def, dict):
                raise ValueError('product_def must be a dictionary when provided (IIP-0024; DEC-103)')
            kw_pvid = product_def.get('product_variant_id')
            if not isinstance(kw_pvid, str) or kw_pvid != kw_pvid.strip() or p_mod.get_product_definition(kw_pvid, root=root_path)['product_variant_id'] != canon_from_obs['product_variant_id']:
                raise ValueError('Conflicting or whitespace-padded product_def and observations product_variant_id (IIP-0024 / IIP-0028; DEC-103 / DEC-106)')
            if 'execution_supported' in product_def and product_def['execution_supported'] is not canon_from_obs['execution_supported']:
                raise ValueError('Caller-overridden execution_supported in product_def rejected (IIP-0028; DEC-106)')
            if 'lifecycle_state' in product_def and product_def.get('lifecycle_state') != canon_from_obs.get('lifecycle_state'):
                raise ValueError('Caller-overridden lifecycle_state in product_def rejected (IIP-0028; DEC-106)')
        product_def = canon_from_obs
    elif product_def is not None:
        if (
            not isinstance(product_def, dict)
            or not isinstance(product_def.get('product_variant_id'), str)
            or not product_def['product_variant_id'].strip()
            or product_def['product_variant_id'] != product_def['product_variant_id'].strip()
        ):
            raise ValueError('product_def must contain a canonical unpadded string product_variant_id (IIP-0024 / IIP-0028; DEC-103 / DEC-106)')
        canon_kw = p_mod.get_product_definition(product_def['product_variant_id'], root=root_path)
        if 'execution_supported' in product_def and product_def['execution_supported'] is not canon_kw['execution_supported']:
            raise ValueError('Caller-overridden execution_supported in product_def rejected (IIP-0028; DEC-106)')
        if 'lifecycle_state' in product_def and product_def.get('lifecycle_state') != canon_kw.get('lifecycle_state'):
            raise ValueError('Caller-overridden lifecycle_state in product_def rejected (IIP-0028; DEC-106)')
        product_def = canon_kw

    contract = derive_contract(root_path)
    default_se_by_mean: dict[str, float] = {}
    for e in list(contract['endpoints']) + list(contract.get('stage0_decision_tree_endpoints', [])):
        if e.get('default_se') is not None:
            default_se_by_mean[e['meanKey']] = float(e['default_se'])
    primary_spec_by_mean = {
        e['meanKey']: (e['endpoint_id'], e['meanKey'], e['seKey'], e['min'], e['max'], e['unit'])
        for e in contract['endpoints']
    }
    spec_by_mean = dict(primary_spec_by_mean)
    for row in STAGE0_DECISION_TREE_ENDPOINT_SPECS:
        spec_by_mean[row[1]] = row
    spec_by_se = {row[2]: row for row in spec_by_mean.values()}
    allowed_boolean_and_meta_flags = {
        'batch_id',
        'assay_id',
        'product_variant_id',
        'estimand_scale',
        's8b_epistasis_estimand_scale',
        'obs_beta_x1_x4_epistasis_scale',
        'obs_beta_x3_x4_epistasis_scale',
        'specimen_or_clone_id',
        'specimen_or_clone_ids',
        'require_full_5endpoint_s9_panel',
        'require_full_7metric_combined_stress_panel',
        's1_gzmb_kass_or_pdl1_scar_failed',
        's1_l3_bfb_replacement_qualified',
        's2_arm1x_clears_15k_resting_hlae_and_cd47_c15g_noninferior',
        's3_arm1b_and_arm1x_below_15k_and_arm1c_splicing_ge_0p95',
        's4_rnls_wt_clears_gsis_shutoff_and_ocr_and_er_gate',
        's5_fasl_delta_tunel_gt_5pp',
        's5_sa_thbd_fhl1_only_replacement_qualified',
        's6_er_rescue_genotype_requalified',
        'b_prime_sct_recipient_cd8_mlc_cleared',
        's8_fasting_leak_or_ucn3_failed',
        's8_staged_dose_and_omental_portal_drainage_qualified',
        's9_mineral_pore_occlusion_gt_15pct',
        's9_chronic_80um_lowload_or_omental_scaffold_qualified',
        's9_chronic_80um_lowload_qualified',
        's9_omental_revascularization_qualified',
        'obs_masked_perfusion_confirmed',
        's10_sct_selectivity_coupon_cleared_kc_ka_ge_4_and_lysis_le_8pct',
        'combined_stress_coupon_cleared_lysis_le_8pct_and_si_ge_2p5',
        'prior_batch_sticky_s9_safety_stop',
        'prior_variant_safety_status',
        'reset_prior_safety_stop_after_investigation',
        'reset_prior_safety_stop_reason',
        'reset_prior_safety_stop_reason_code',
        'reset_prior_safety_stop_repeat_batch_ids',
        'reset_prior_safety_stop_independent_qp_approver_id',
        'verified_ledger_passing_s9_batch_ids',
        'track2_b_sct_or_hlag1_lilrb1_rescue_qualified',
        'track2_b_sct_or_hlag1_product_switched',
        'cd47_playbook_200k_and_5pct_phago_waiver_approved',
        's9_staged_cassette_excision_and_d10w_clamp_qualified',
        'periimplant_closed_suction_drain_verified',
        'obs_vascularized_explant_en_bloc_recovery_verified',
        'obs_ap1903_pulsed_pk_washout_regimen_verified',
        'mcb_clone_id',
        'oos_retest_investigation_approved',
        'oos_retest_assignable_cause_code',
        'allow_cross_clone_pooling_for_exploratory_research',
        'obs_arm2_bound_and_supernatant_fasl_bioactivity_depleted_verified',
        'obs_arm2_sa_thbd_bioactivity_depleted_verified',
        'obs_arm2_contemporaneous_sham_handling_matched',
        'obs_arm3_ongoing_adjunct_bioactivity_verified',
        'adjunct_conditioning_history_arm',
        'adjunct_depletion_mode',
        'adjunct_sa_fhl1_status',
        'adjunct_immune_responder_history',
        'obs_challenger_ivt_rna_recovery_standard_verified',
        'obs_challenger_pam_seed_shield_coconversion_verified',
        'obs_challenger_host_isoforms_above_loq_verified',
        'obs_challenger_sv40pa_and_host_3prime_cleavage_checked',
        'knockin_splice_challenger_arm',
        'knockin_locus4_orientation',
        's10_construct_id',
        's10_construct_donor_sha256',
        'current_lot_id',
        's10_qualified_lot_id',
        's10_hlae_floor_mode',
        's10_is_replacement_challenger_lot',
        's10_race_5p_3p_junction_verified',
        'hla_a2_d227k_t228a_positive_control_spr_verified',
        'b2_tyk2_recipient_genotype_stratum',
        'b2_tyk2_hlac_allele',