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…

    d_L_by_frac: dict[str, float] = {}
    d_L_details: dict[str, dict[str, Any]] = {}
    p_i_U_by_frac: dict[str, float] = {}
    N_by_frac: dict[str, int] = {}
    e_lo_by_frac: dict[str, float] = {}
    e_hi_by_frac: dict[str, float] = {}

    for f in sorted(lot_roster):
        N_i = int(agg_by_frac[f]['N'])
        plated_sum_f = int(agg_by_frac[f]['plated_treated_cells_sum'])
        untr_items = sorted(agg_by_frac[f]['untr_by_id'].items())
        u_f_cnt = len(untr_items)
        alpha_cfu_tail = alpha_cfu / (2.0 * float(u_f_cnt))
        f_lo_vals = [_exact_one_sided_cp_lower_iip0031(uk_v, un_v, alpha_cfu_tail) for _, (uk_v, un_v) in untr_items]
        f_hi_vals = [clopper_pearson_upper95_independent(uk_v, un_v, alpha=alpha_cfu_tail) for _, (uk_v, un_v) in untr_items]
        f_lo_f = min(f_lo_vals)
        f_hi_f = max(f_hi_vals)
        for (n_sub, plated_sub, uk_sub, un_sub) in agg_by_frac[f]['obs_list']:
            f_sub_l = _exact_one_sided_cp_lower_iip0031(uk_sub, un_sub, alpha_cfu_tail)
            max_sup_sub = _conservative_int_product_floor_iip0031(plated_sub, f_sub_l)
            if n_sub > max_sup_sub:
                return _hold_unqual(
                    'UNTREATED_CFU_DOES_NOT_SUPPORT_CLAIMED_OPPORTUNITIES',
                    untreated_cfu_max_supported_N=max_sup_sub,
                    claimed_N=n_sub,
                    fraction_id=f,
                )
        max_sup_frac = _conservative_int_product_floor_iip0031(plated_sum_f, f_lo_f)
        if N_i > max_sup_frac:
            return _hold_unqual(
                'UNTREATED_CFU_DOES_NOT_SUPPORT_CLAIMED_OPPORTUNITIES',
                untreated_cfu_max_supported_N=max_sup_frac,
                claimed_N=N_i,
                fraction_id=f,
            )
        c_f = float(agg_by_frac[f]['presort_fraction_cells'])
        e_lo_by_frac[f] = c_f * f_lo_f
        e_hi_by_frac[f] = c_f * f_hi_f
        N_by_frac[f] = N_i

        cal_items = sorted(agg_by_frac[f]['cal_by_key'].items())
        b_i_count = len(cal_items)
        alpha_each_f = alpha_cal / (2.0 * float(b_i_count))
        per_cal_bounds = []
        for (_ck, (rk_h, rn_h, rk_d, rn_d)) in cal_items:
            d_l_h = _exact_one_sided_cp_lower_iip0031(rk_h, rn_h, alpha_each_f)
            d_l_d = _exact_one_sided_cp_lower_iip0031(rk_d, rn_d, alpha_each_f)
            per_cal_bounds.append((min(d_l_h, d_l_d), rk_h, rn_h, d_l_h, rk_d, rn_d, d_l_d))
        worst_cal = min(per_cal_bounds, key=lambda x: x[0])
        d_i_L = worst_cal[0]
        d_L_details[f] = {
            'mode': 'EXACT_DUAL_SEPARATE_CALIBRANTS',
            'distinct_calibration_batches_in_fraction': b_i_count,
            'alpha_per_calibrant_in_fraction': alpha_each_f,
            'r_k_hpsc': worst_cal[1],
            'r_n_hpsc': worst_cal[2],
            'd_L_hpsc': worst_cal[3],
            'r_k_diff': worst_cal[4],
            'r_n_diff': worst_cal[5],
            'd_L_diff': worst_cal[6],
            'd_i_L': d_i_L,
            'f_cfu_L': f_lo_f,
            'f_cfu_U': f_hi_f,
        }
        d_L_by_frac[f] = d_i_L
        if d_i_L > 0.0 and f_lo_f > 0.0:
            p_exact_plated = min(1.0, (-math.expm1(math.log(alpha_obs) / float(plated_sum_f))) / (f_lo_f * d_i_L))
            p_decl_n = min(1.0, (-math.expm1(math.log(alpha_obs) / float(N_i))) / d_i_L)
            p_i_U_by_frac[f] = max(p_exact_plated, p_decl_n)
        else:
            p_i_U_by_frac[f] = 1.0

    # Exact global maximizer of sum_i (E_i / sum_j E_j) * p_{i,U} over the simultaneous box E_i in [E_lo_i, E_hi_i]:
    sorted_by_p = sorted(lot_roster, key=lambda fk: (-p_i_U_by_frac[fk], fk))
    best_p_lot = -1.0
    w_used: dict[str, float] = dict(w_point)
    for r_cut in range(len(sorted_by_p) + 1):
        e_vec = {
            fk: (e_hi_by_frac[fk] if idx_r < r_cut else e_lo_by_frac[fk])
            for idx_r, fk in enumerate(sorted_by_p)
        }
        tot_e_vec = sum(e_vec.values())
        if tot_e_vec <= 0.0:
            continue
        cand_w = {fk: e_vec[fk] / tot_e_vec for fk in lot_roster}
        cand_p = float(sum(cand_w[fk] * p_i_U_by_frac[fk] for fk in lot_roster))
        if cand_p > best_p_lot:
            best_p_lot = cand_p
            w_used = cand_w
    p_lot_U95 = best_p_lot if best_p_lot >= 0.0 else 1.0

    detection_floor_cleared = all(d_L_by_frac[f] >= TIER6B_DETECTION_FLOOR_IIP0031 for f in lot_roster)
    if not detection_floor_cleared:
        return _hold_unqual(
            'DETECTION_LOWER_BOUND_BELOW_0P50_FLOOR',
            p_lot_U95=p_lot_U95,
            d_L_by_fraction=d_L_by_frac,
            d_L_details=d_L_details,
            p_i_U_by_fraction=p_i_U_by_frac,
            N_by_fraction=N_by_frac,
            w_by_fraction=w_used,
            alpha_obs=alpha_obs,
            alpha_cal=alpha_cal,
            alpha_each=alpha_each,
            m_fractions=m_fracs,
            detection_floor_cleared=False,
            deduplicated_sample_ids=sorted(deduplicated_sample_ids),
        )

    # Exact unrounded comparison against 3.0e-7 (exact equality passes; never round before comparing):
    if p_lot_U95 > TIER6B_PER_FRACTION_LOT_CAP_IIP0031:
        return {
            'gate_pass': False,
            'status': 'HOLD_TIER6B_INSUFFICIENT_DENOMINATOR',
            'disposition': 'HOLD_TIER6B_INSUFFICIENT_DENOMINATOR',
            'reason_code': 'HOLD_TIER6B_LOT_U95_EXCEEDS_3E_7',
            'tier6b_status': 'HOLD_TIER6B_INSUFFICIENT_DENOMINATOR',
            'hard_stop': False,
            'p_lot_U95': p_lot_U95,
            'threshold': TIER6B_PER_FRACTION_LOT_CAP_IIP0031,
            'd_L_by_fraction': d_L_by_frac,
            'd_L_details': d_L_details,
            'p_i_U_by_fraction': p_i_U_by_frac,
            'N_by_fraction': N_by_frac,
            'w_by_fraction': w_used,
            'alpha_obs': alpha_obs,
            'alpha_cal': alpha_cal,
            'alpha_each': alpha_each,
            'm_fractions': m_fracs,
            'detection_floor_cleared': True,
            'deduplicated_sample_ids': sorted(deduplicated_sample_ids),
        }

    # Summing opportunities across >= 2 observations in the same fraction requires explicit, distinct
    # source-owned trial & calibration identifiers on every summed row so relabelled duplicate payloads
    # without stable source identity can NEVER pass Tier 6B (#5):
    for f in sorted(lot_roster):
        f_obs_ids = agg_by_frac[f]['obs_identities']
        if len(f_obs_ids) >= 2:
            seen_rids: set[str] = set()
            seen_srcs: set[str] = set()
            seen_cals: set[str] = set()
            for r_obs, r_aliquot_tokens in f_obs_ids:
                rid_val = next((r_obs[rk] for rk in _TIER6B_RECORD_ID_ALIASES if rk in r_obs and isinstance(r_obs[rk], str) and r_obs[rk].strip()), None)
                src_tokens = [tok for tok in r_aliquot_tokens[1:] if isinstance(tok, str) and tok.strip()]
                cal_val = r_obs.get('cal_batch_id')
                if (
                    rid_val is None or rid_val in seen_rids
                    or not src_tokens or any(tok in seen_srcs for tok in src_tokens)
                    or not isinstance(cal_val, str) or not cal_val.strip() or cal_val in seen_cals
                ):
                    return _hold_unqual(
                        'MISSING_SOURCE_OWNED_TRIAL_OR_CALIBRANT_IDENTITY_FOR_MULTI_OBSERVATION_SUM',
                        p_lot_U95=p_lot_U95,
                        d_L_by_fraction=d_L_by_frac,
                        d_L_details=d_L_details,
                        p_i_U_by_fraction=p_i_U_by_frac,
                        N_by_fraction=N_by_frac,
                        w_by_fraction=w_used,
                        alpha_obs=alpha_obs,
                        alpha_cal=alpha_cal,
                        alpha_each=alpha_each,
                        m_fractions=m_fracs,
                        detection_floor_cleared=True,
                        deduplicated_sample_ids=sorted(deduplicated_sample_ids),
                    )
                seen_rids.add(rid_val)
                seen_srcs.update(src_tokens)
                seen_cals.add(cal_val)

    return {
        'gate_pass': True,
        'status': 'PASS',
        'disposition': 'PASS',
        'reason_code': 'PASS_TIER6B_PER_FRACTION_THINNING',
        'tier6b_status': 'PASS_TIER6B_PER_FRACTION_THINNING',
        'hard_stop': False,
        'p_lot_U95': p_lot_U95,
        'threshold': TIER6B_PER_FRACTION_LOT_CAP_IIP0031,
        'd_L_by_fraction': d_L_by_frac,
        'd_L_details': d_L_details,
        'p_i_U_by_fraction': p_i_U_by_frac,
        'N_by_fraction': N_by_frac,
        'w_by_fraction': w_used,
        'alpha_obs': alpha_obs,
        'alpha_cal': alpha_cal,
        'alpha_each': alpha_each,
        'm_fractions': m_fracs,
        'detection_floor_cleared': True,
        'deduplicated_sample_ids': sorted(deduplicated_sample_ids),
    }


def _paired_difference_se_consistent(arm_a: Any, arm_b: Any, difference: Any) -> bool:
    """Check the sharp paired-SE bounds using the decimal values carried by JSON."""
    values = (arm_a, arm_b, difference)
    if not all(_is_strict_finite_number_iip0024(v) and v >= 0 for v in values):
        return False
    a, b, d = (Fraction(str(v)) for v in values)
    return abs(a - b) <= d <= a + b


_ALL_S11_RECOGNIZED_EVIDENCE_KEYS: frozenset[str] = frozenset({
    'ciita_locus2_genotype_copy_class',
    'ciita_ki_allele_informative_transcript_recovery_verified',
    'ciita_ko_allele_informative_transcript_recovery_verified',
    'ciita_ki_allele1_informative_transcript_recovery_verified',
    'ciita_ki_allele2_informative_transcript_recovery_verified',
    'ciita_cis_sentinels_socs1_dexi_clec16a_tost_verified',
    'lineage_matched_wt_stage7_hla_dr_dp_dq_inducibility_verified',
    'phasing_verified',
    'cis_verified',
    'wt_inducibility_verified',
    'rnai_attribution_verified',
    'rnai_specific_benefit_claimed',
    'rnai_attribution_scramble_control_id',
    'rnai_attribution_scramble_background_id',
    'rnai_attribution_scramble_control_sha256',
    'rnai_attribution_scramble_sample_id',
    'rnai_attribution_intronless_control_id',
    'rnai_attribution_intronless_background_id',
    'rnai_attribution_intronless_control_sha256',
    'rnai_attribution_intronless_sample_id',
    'l2_v3_same_background_intronless_control_linked_to_cargo',
    'l2_v3_same_background_scramble_control_linked_to_cargo',
    'has_intronic_mir_cd276_pvr',
    'syn_5xisre_cd200_in_design_y',
    's11_replicate_n',
    'obs_edited_72h_ifng_hla_dr_dp_dq_pos_pct',
    'obs_edited_72h_ifng_hla_dr_dp_dq_pos_se',
    'obs_wt_lineage_matched_72h_ifng_hla_dr_dp_dq_pos_pct',
    'obs_wt_lineage_matched_72h_ifng_hla_dr_dp_dq_pos_se',
    'obs_cis_socs1_tost90_ratio_lo',
    'obs_cis_socs1_tost90_ratio_hi',
    'obs_cis_dexi_tost90_ratio_lo',
    'obs_cis_dexi_tost90_ratio_hi',
    'obs_cis_clec16a_tost90_ratio_lo',
    'obs_cis_clec16a_tost90_ratio_hi',
    'obs_16p13_ddpcr_cn_ratio',
    'obs_16p13_phased_baf',
})

_S11_KIKO_ONLY_FIELDS: frozenset[str] = frozenset({
    'obs_ciita_ki_allele_informative_reads_n',
    'obs_ciita_ki_ex4_ex6_aberrant_skip_reads_k',
    'obs_ciita_ki_ex4_ex6_aberrant_skip_pct',
    'obs_ciita_ki_ex4_ex6_aberrant_skip_se',
    'obs_ciita_ko_allele_informative_reads_n',
    'obs_ciita_ko_ex4_ex6_aberrant_skip_reads_k',