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…

def _load_product_contract_module(root: Path):
    root_res = root.resolve()
    py_path = root_res / 'scripts/product_contract.py'
    json_path = root_res / 'data/protocols/islet1_product_definitions_v0.8.0.json'
    try:
        st_py = py_path.stat()
        py_sig: Any = (st_py.st_mtime_ns, st_py.st_size)
    except OSError:
        py_sig = None
    try:
        st_js = json_path.stat()
        js_sig: Any = (st_js.st_mtime_ns, st_js.st_size)
    except OSError:
        js_sig = None
    cache_key = (str(root_res), py_sig, js_sig)
    cached = _PRODUCT_CONTRACT_MODULE_CACHE.get(cache_key)
    if cached is not None:
        return cached
    spec = importlib.util.spec_from_file_location('openislet_product_contract', py_path)
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    if len(_PRODUCT_CONTRACT_MODULE_CACHE) > 32:
        _PRODUCT_CONTRACT_MODULE_CACHE.clear()
    _PRODUCT_CONTRACT_MODULE_CACHE[cache_key] = module
    return module


def validate_product_and_estimand_compatibility(
    product_variant_id: str | None,
    estimand_scale: str | None,
    observed_mean_keys: list[str] | set[str],
    *,
    root: Path | str | None = None,
) -> None:
    """Enforce registry membership & Arm-1B family compatibility for product_variant_id and canonical unit compatibility for estimand_scale (AUDIT-REF)."""
    root_path = Path(root) if root is not None else Path(__file__).resolve().parents[1]
    obs_set = set(observed_mean_keys)
    if product_variant_id is not None:
        if not isinstance(product_variant_id, str) or not product_variant_id.strip() or product_variant_id != product_variant_id.strip():
            raise ValueError('product_variant_id must be a canonical non-whitespace-padded nonempty string (IIP-0024; DEC-103)')
        p_mod = _load_product_contract_module(root_path)
        product_def = p_mod.get_product_definition(product_variant_id, root=root_path)
        canon_id = product_def['product_variant_id']
        is_track2_b_sct = canon_id.startswith('ISLET1_B_SCT_')
        if (product_def.get('family') != 'A' and not is_track2_b_sct) or (
            bool(obs_set & ARM1B_SCOPED_MEAN_KEYS) and canon_id not in ARM1B_LOCUS1_COMPATIBLE_FAMILY_A_IDS
        ):
            raise ValueError(
                f'Incompatible product_variant_id {product_variant_id!r} (resolved to {canon_id!r}, family={product_def.get("family")!r}): '
                f'wet-lab Bayesian calibration priors are anchored to Family-A Arm-1B or Track-2 B\'-SCT Arm-1B products (AUDIT-REF; AUDIT-REF)'
            )
    if estimand_scale is not None:
        if not isinstance(estimand_scale, str) or not estimand_scale.strip():
            raise ValueError('estimand_scale must be a nonempty string')
        esc = estimand_scale.strip()
        if esc not in ALL_ALLOWED_ESTIMAND_SCALES:
            raise ValueError(
                f'Invalid estimand_scale {estimand_scale!r}: must match canonical endpoint unit specification (AUDIT-REF)'
            )
        for mk in sorted(obs_set):
            allowed_for_mk = ALLOWED_ESTIMAND_SCALES_BY_MEAN_KEY.get(mk, GLOBAL_CANONICAL_ESTIMAND_SCALES)
            if esc not in allowed_for_mk:
                raise ValueError(
                    f'Incompatible estimand_scale {estimand_scale!r} for observed endpoint {mk!r}; allowed scales: {sorted(allowed_for_mk)} (AUDIT-REF)'
                )


STAGE0_ORIGINAL_PRIMARY_MANDATORY_MEAN_KEYS: tuple[str, ...] = (
    'obs_stage7_yield_ratio',
    'obs_cd47_fold',
    'obs_serpinb9_log10_kass',
    'obs_icasp9_log10_kill',
    'obs_pouch_min_po2_mmhg',
    'obs_pouch_max_h2o2_uM',
    'obs_pouch_max_ph',
    'obs_ifng_hla_dr_dq_negative_pct',
)

STAGE0_RELEASE_CRITICAL_MOLECULE_AND_RATE_MEAN_KEYS: tuple[str, ...] = (
    'obs_cd47_hour0_molecules',
    'obs_hlae_hour0_molecules',
    'obs_cd47_p10_single_cell_molecules',
    'obs_hypoxic_72h_cd47_p10_single_cell_molecules',
    'obs_hypoxic_72h_hlae_p10_single_cell_molecules',
    'obs_hypoxic_72h_cd47_retention_molecules',
    'obs_hypoxic_72h_hlae_retention_molecules',
    'obs_iec_cd47_p10_molecules',
    'obs_gate0b_hlac_sct_molecules_per_cell',
    'obs_serpinb9_kass_M_s',
    'obs_nkg2a_lysis_pct',
    'obs_kir_nkg2a_neg_nk_lysis_pct',
    'obs_nkg2c_adaptive_nk_lysis_pct',
    'obs_il12_il18_sirpa_low_nk_lysis_pct',
    'obs_nkg2a_neg_kir2dl_neg_nkg2c_pos_nk_lysis_pct',
    'obs_phagocytosis_index_pct',
    'obs_complement_c3b_opsonized_phagocytosis_pct',
)

STAGE0_DECISION_TREE_BOOLEAN_KEYS: tuple[str, ...] = (
    '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',
    'track2_b_sct_or_hlag1_lilrb1_rescue_qualified',
    'track2_b_sct_or_hlag1_product_switched',
    'cd47_playbook_200k_and_5pct_phago_waiver_approved',
    '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',
    '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',
    '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',
    'reset_prior_safety_stop_after_investigation',
    'oos_retest_investigation_approved',
    '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',
    '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',
    's10_is_replacement_challenger_lot',
    's10_race_5p_3p_junction_verified',
    'hla_a2_d227k_t228a_positive_control_spr_verified',
    'b2_tyk2_saptkflel_allele_assigned_ms_detected',
    'b2_tyk2_peptide_pulsed_positive_control_verified',
    'b2_tyk2_hlac_blockade_abrogation_verified',
    'l3_multimir_pre_aav6_2x2_transient_kd_falsifier_cleared',
    'l3_multimir_low_ifn_and_resting_shield_retention_verified',
    'l3_multimir_arm6_c341s_hlac_and_dq2_dq8_peptide_screen_cleared',
    's6_dose_matched_1500_ieq_verified',
    's6_divider_iso10993_leachables_cleared',
    'p05_full_336h_coupled_o2_h2o2_ca_ph_qualified',
    'design_z_empty_lumen_14d_persistence_verified',
    'design_z_loaded_closed_state_confirmed',
    'require_full_iip0020_biomaterial_and_humoral_panel',
    'p05_recombinant_human_catalase_verified',
    'cuff_dpr_ring_hydrolysis_lcms_verified',
    'cuff_conjugate_disulfide_and_site_occupancy_lcms_verified',
    'cuff_hexafasl_inventory_within_provisional_cap_verified',
    'require_full_iip0021_ocr_and_conditioning_panel',
    'rest_120h_longitudinal_simultaneous_coverage_verified',
    'rest_120h_viable_lineage_yield_and_during_exposure_function_verified',
    'conditioning_pellet_loq_and_extraction_recovery_verified',
    'conditioning_orthogonal_pathway_controls_verified',
    'track2_b_sct_kir_rescue_qualified',
    'track2_hlag1_lilrb1_rescue_qualified',
    'require_full_iip0022_track2_and_guardrail_panel',
    'lineage_necroptosis_time_resolved_viability_and_rescue_verified',
    'design_y_attlr_outside_orf_5p3p_race_verified',
    'design_y_zero_2a_scar_proteomics_verified',
    'design_y_dpcpx_adora1_antagonist_control_run',
    'design_y_anti_cd200_blockade_reversal_verified',
    'design_y_y04_full_coculture_and_clonogenic_confirmed',
    'require_full_iip0024_atomic_provenance_and_bank_panel',
    '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',
    'require_full_iip0025_hurdle4_transport_and_challenger_panel',
    'p05_two_timepoint_same_lot_envelope_verified',
    'contrast_b2_route_qualification_distinct_from_portfolio_credit_verified',
    'contrast_b3_zero_primate_host_ingrowth_verified',
    'require_full_iip0026_molecular_provenance_panel',
    'donor_seed_gnomad_target_site_wgs_verified',
    'post_edit_reciprocal_mosaic_sv_or_clonal_zygosity_verified',
    'design_b_hla_ab_separated_pass_delivery_verified',
    'design_b_chr6p21_1p41mb_loh_sv_cleared',
    'design_b_hlac_dt9_positive',
    'design_b_hlae_3d12_positive',
    'design_b_hlac_allele_specific_surface_or_phased_mrna_verified',
    'b_sct_ciita_exon5_and_trimer_verified',
    'tyk2_phased_haplotype_sap_verified',
    'require_full_iip0028_postdepletion_adcc_mixture_and_iapp_panel',
    'washout_and_natural_decay_unpooled_verified',
    'carrier_and_soluble_adjunct_below_lod_verified',
    'fcr_effector_fcgr3a_158v_typed_verified',
    'dec084_measured_starting_composition_and_fresh_equal_output_verified',
    'iapp_sister_visit_lot_and_viable_beta_mass_concordance_verified',
    'require_full_iip0027_promoter_origin_and_itr_panel',
    'cxcl10_insert_matched_comparator_control_verified',
    'cxcl10_resting_expression_below_loq_confirmed',
    'bio06_itr_rna_origin_attribution_verified',
    'require_full_iip0029_twoclock_maturation_panel',
    'obs_alk5i_free_maturation_applied',
    'terminal_alk5i_tgfb_inhibitor_continued',
    'stage7_t3_10nM_and_nac_1mM_retained',
    'zm447439_washout_verified_pre_iec',
    'pre_coassembly_iec_vascular_function_verified',
    'readout2_both_40_and_100mmhg_tracer_aligned_verified',
    'require_full_iip0031_locus2_and_tier6b_panel',
    'ciita_ki_allele_informative_transcript_recovery_verified',
    'ciita_ko_allele_informative_transcript_recovery_verified',
    'ciita_cis_sentinels_socs1_dexi_clec16a_tost_verified',
    'lineage_matched_wt_stage7_hla_dr_dp_dq_inducibility_verified',
    'l2_v3_same_background_intronless_control_linked_to_cargo',
    'l2_v3_same_background_scramble_control_linked_to_cargo',
    'phasing_verified',
    'cis_verified',
    'wt_inducibility_verified',
    'rnai_attribution_verified',
    'obs_l2_v3_chr16_ha_wgs_pass',
)


def derive_contract(root: Path | str | None = None) -> dict:
    root = Path(root) if root is not None else Path(__file__).resolve().parents[1]
    tree = ast.parse((root / 'scripts/ingest_wetlab_results.py').read_text())
    constants = {}
    for node in tree.body:
        name = node.targets[0].id if isinstance(node, ast.Assign) and isinstance(node.targets[0], ast.Name) else node.target.id if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) else None
        if name in {'ENDPOINT_SPECS', 'EXTENDED_STAGE0_STAGE1_SPECS', 'MIN_BIOLOGICAL_SE_FLOOR'}:
            constants[name] = ast.literal_eval(node.value)
    endpoints = []
    for row in constants['ENDPOINT_SPECS']:
        name, _pm, _ps, mean, se, lo, hi, unit = row
        endpoints.append(dict(endpoint_id=name, meanKey=mean, seKey=se, min=lo, max=hi, se_required=True, default_se=None, unit=unit))
    for row in constants['EXTENDED_STAGE0_STAGE1_SPECS']:
        name, _pm, _ps, mean, se, default, lo, hi, unit = row
        endpoints.append(dict(endpoint_id=name, meanKey=mean, seKey=se, min=lo, max=hi, se_required=False, default_se=default, unit=unit))
    primary_means = {e['meanKey'] for e in endpoints}
    stage0_tree_endpoints = []
    for eid, mean, se, lo, hi, unit in STAGE0_DECISION_TREE_ENDPOINT_SPECS:
        if mean in primary_means:
            continue
        default_se = _scale_aware_stage0_default_se(mean, lo, hi)
        min_se = STAGE0_CUSTOM_MINIMUM_SE.get(mean, constants['MIN_BIOLOGICAL_SE_FLOOR'])
        stage0_tree_endpoints.append(dict(endpoint_id=eid, meanKey=mean, seKey=se, min=lo, max=hi, se_required=False, default_se=default_se, minimum_se=min_se, unit=unit))
    return {'schema_version': '0.9.0', 'txnip_ko_prohibited': True, 'gy026_txnip_ko_prohibited': True, 'source': 'scripts/ingest_wetlab_results.py constant endpoint specifications',
            'minimum_se': constants['MIN_BIOLOGICAL_SE_FLOOR'], 'missing_mean': 'UNAVAILABLE',