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 _norm_cdf_iip0024(x: float) -> float:
    return 0.5 * (1.0 + math.erf(x / math.sqrt(2.0)))


def _chi2_pdf_iip0024(w: float, df: float) -> float:
    if w <= 0.0:
        return 0.0
    half_df = 0.5 * df
    return math.exp((half_df - 1.0) * math.log(w) - 0.5 * w - half_df * math.log(2.0) - math.lgamma(half_df))


def welch_tost_power_exact_2d_iip0024(
    m1: int,
    m2: int,
    sigma1: float,
    sigma2: float,
    delta_true: float,
    theta_margin: float,
    n_pts: int = 350,
) -> float:
    """Exact 2D chi-square quadrature over independent (S1^2, S2^2) for unpooled Welch 90% TOST power (IIP-0024; DEC-103)."""
    df1 = float(m1 - 1)
    df2 = float(m2 - 1)
    se_true = math.sqrt((sigma1 ** 2) / m1 + (sigma2 ** 2) / m2)
    u1_max = math.sqrt(df1 + 15.0 * math.sqrt(2.0 * df1))
    u2_max = math.sqrt(df2 + 15.0 * math.sqrt(2.0 * df2))
    h1 = u1_max / n_pts
    h2 = u2_max / n_pts
    u1_nodes = [
        ((i + 0.5) * h1, _chi2_pdf_iip0024(((i + 0.5) * h1) ** 2, df1) * 2.0 * ((i + 0.5) * h1) * h1)
        for i in range(n_pts)
    ]
    u2_nodes = [
        ((j + 0.5) * h2, _chi2_pdf_iip0024(((j + 0.5) * h2) ** 2, df2) * 2.0 * ((j + 0.5) * h2) * h2)
        for j in range(n_pts)
    ]
    c1 = (sigma1 ** 2) / (m1 * df1)
    c2 = (sigma2 ** 2) / (m2 * df2)
    df_lo = min(df1, df2)
    df_hi = df1 + df2
    n_tab = 4096
    df_step = (df_hi - df_lo) / n_tab
    t_tab = [student_t_ppf_one_sided_95(df_lo + idx * df_step) for idx in range(n_tab + 1)]
    inv_sqrt2 = 1.0 / math.sqrt(2.0)

    acc = 0.0
    for u1, wt1 in u1_nodes:
        a1 = c1 * (u1 * u1)
        a1_sq_df = (a1 * a1) / df1
        for u2, wt2 in u2_nodes:
            a2 = c2 * (u2 * u2)
            v_tot = a1 + a2
            se_w = math.sqrt(v_tot)
            df_w = (v_tot * v_tot) / (a1_sq_df + (a2 * a2) / df2)
            pos = (df_w - df_lo) / df_step
            idx = int(pos)
            if idx < 0:
                t_val = t_tab[0]
            elif idx >= n_tab:
                t_val = t_tab[n_tab]
            else:
                frac = pos - idx
                t_val = t_tab[idx] + frac * (t_tab[idx + 1] - t_tab[idx])
            half_w = t_val * se_w
            if half_w < theta_margin:
                hi_z = (theta_margin - half_w - delta_true) / se_true
                lo_z = (-theta_margin + half_w - delta_true) / se_true
                if hi_z > lo_z:
                    acc += 0.5 * (math.erf(hi_z * inv_sqrt2) - math.erf(lo_z * inv_sqrt2)) * wt1 * wt2
    return min(1.0, max(0.0, acc))


def evaluate_donor_blocked_contrast_and_welch_tost_iip0024(n_pts: int = 350) -> dict[str, Any]:
    """
    Deterministic audit of asymptotic z=1.644854 Type-I inflation vs Student-t,
    unblocked cross-donor false >25% shifts vs Donor-1 paired blocking, and
    6+3 vs 6+6 unpooled Welch 90% TOST on [0.75, 1.3333] (IIP-0024; DEC-103).
    """
    z95 = 1.6448536269514722
    type1_z_m3_pct = 100.0 * (1.0 - student_t_cdf(z95, 2.0))
    type1_z_m6_pct = 100.0 * (1.0 - student_t_cdf(z95, 5.0))
    type1_t_m6_pct = 100.0 * (1.0 - student_t_cdf(student_t_ppf_one_sided_95(5.0), 5.0))
    # False >25% (|Delta_log| > ln(1.25)) shift probability under unblocked cross-donor vs blocked Donor-1 contrast (m=6, sigma_batch=0.12):
    margin_25 = math.log(1.25)
    sigma_batch = 0.12
    sd_blocked = math.sqrt(2.0 * (sigma_batch ** 2) / 6.0)
    blocked_false_shift_pct = 100.0 * 2.0 * (1.0 - _norm_cdf_iip0024(margin_25 / sd_blocked))
    unblocked_false_shifts_pct: dict[str, float] = {}
    for s_don in (0.10, 0.20, 0.30):
        sd_unb = math.sqrt(2.0 * (s_don ** 2) + 2.0 * (sigma_batch ** 2) / 6.0)
        unblocked_false_shifts_pct[f'sigma_donor_{s_don:.2f}'] = round(100.0 * 2.0 * (1.0 - _norm_cdf_iip0024(margin_25 / sd_unb)), 2)

    theta_eq = math.log(4.0 / 3.0)
    w_63_0 = 100.0 * welch_tost_power_exact_2d_iip0024(6, 3, 0.12, 0.12, 0.0, theta_eq, n_pts=n_pts)
    w_63_10 = 100.0 * welch_tost_power_exact_2d_iip0024(6, 3, 0.12, 0.12, math.log(1.10), theta_eq, n_pts=n_pts)
    w_63_15 = 100.0 * welch_tost_power_exact_2d_iip0024(6, 3, 0.12, 0.12, math.log(1.15), theta_eq, n_pts=n_pts)
    w_66_0 = 100.0 * welch_tost_power_exact_2d_iip0024(6, 6, 0.12, 0.12, 0.0, theta_eq, n_pts=n_pts)
    w_66_10 = 100.0 * welch_tost_power_exact_2d_iip0024(6, 6, 0.12, 0.12, math.log(1.10), theta_eq, n_pts=n_pts)
    w_66_15 = 100.0 * welch_tost_power_exact_2d_iip0024(6, 6, 0.12, 0.12, math.log(1.15), theta_eq, n_pts=n_pts)
    w_66_type1_sd_006_015 = 100.0 * welch_tost_power_exact_2d_iip0024(6, 6, 0.06, 0.15, theta_eq, theta_eq, n_pts=n_pts)
    return {
        'proposal_id': 'IIP-0024',
        'decision_id': 'DEC-103',
        'asymptotic_z_type1_error_pct': {
            'm_eq_3_df2': round(type1_z_m3_pct, 3),
            'm_eq_6_df5': round(type1_z_m6_pct, 3),
            'student_t_m_eq_6_df5': round(type1_t_m6_pct, 3),
        },
        'construct_contrast_false_gt25pct_shift_pct': {
            'donor1_paired_blocked_m6': round(blocked_false_shift_pct, 2),
            'unblocked_cross_donor_m6': unblocked_false_shifts_pct,
        },
        'welch_90pct_tost_power_on_0p75_1p3333_pct': {
            'lots_6_plus_3': {
                'drift_0pct': round(w_63_0, 2),
                'drift_plus10pct': round(w_63_10, 2),
                'drift_plus15pct': round(w_63_15, 3),
            },
            'lots_6_plus_6': {
                'drift_0pct': round(w_66_0, 2),
                'drift_plus10pct': round(w_66_10, 2),
                'drift_plus15pct': round(w_66_15, 2),
                'boundary_type1_sd_0p06_vs_0p15_pct': round(w_66_type1_sd_006_015, 3),
            },
        },
    }


def evaluate_iip0024_atomic_stage0_ledger(
    batches: list[dict[str, Any]],
    target_provenance: dict[str, Any],
    *,
    target_campaign_id: str,
    root: Path | str | None = None,
    specimen_lifecycle_stage: str = 'FULL_LOT_RELEASE_WITH_SISTER_UNIT_TERMINAL',
    authorized_sister_assembly_ids: frozenset[str] = frozenset(),
) -> dict[str, Any]:
    """
    Fail-closed atomic Stage-0 ledger evaluator enforcing 4/5/7-key provenance scopes,
    adverse observation latching across batch merges until an authorized same-scope QP reset,
    distinct specimen units on Gate 0S dual shedding, and non-executable product holds (IIP-0024; DEC-103).
    """
    root_path = Path(root) if root is not None else Path(__file__).resolve().parents[1]
    p_mod = _load_product_contract_module(root_path)
    try:
        mcb_k = MCBScopeKey(
            target_provenance['product_variant_id'],
            target_provenance['construct_sha256'],
            target_provenance['donor_seedline_id'],
            target_provenance['mcb_id'],
        )
        lot_k = LotScopeKey(
            mcb_k.product_variant_id,
            mcb_k.construct_sha256,
            mcb_k.donor_seedline_id,
            mcb_k.mcb_id,
            target_provenance['lot_id'],
        )
    except (KeyError, TypeError, ValueError) as exc:
        return {'readiness_tier': 'HOLD_MISSING_OR_INVALID_IMMUTABLE_PROVENANCE_KEY', 'overall_status': 'HOLD_MISSING_OR_INVALID_IMMUTABLE_PROVENANCE_KEY', 'hard_stop_precedence_winner': None, 'execution_supported': False, 'holds': [str(exc)]}

    try:
        pdef = p_mod.get_product_definition(mcb_k.product_variant_id, root=root_path)
    except ValueError as exc:
        return {'readiness_tier': 'HOLD_UNKNOWN_PRODUCT_VARIANT', 'overall_status': 'HOLD_UNKNOWN_PRODUCT_VARIANT', 'hard_stop_precedence_winner': None, 'execution_supported': False, 'holds': [str(exc)]}

    pvid_canon = str(pdef['product_variant_id'])
    staged_l2_v3_ids = getattr(p_mod, 'STAGED_LOCUS2_V3_PRODUCT_IDS', frozenset())
    is_non_exec_product = (pdef.get('execution_supported') is False)
    is_z_prod = (pvid_canon == 'ISLET1_Z_X_MOL_140UM_ZERO_CAO2')
    is_staged_research_comparator = (pvid_canon == 'ISLET1_B2_5LOCUS_BASE' or pvid_canon in staged_l2_v3_ids)

    mcb_k_c = MCBScopeKey(pvid_canon, mcb_k.construct_sha256, mcb_k.donor_seedline_id, mcb_k.mcb_id)
    lot_k_c = LotScopeKey(pvid_canon, mcb_k.construct_sha256, mcb_k.donor_seedline_id, mcb_k.mcb_id, lot_k.lot_id)

    early_device_or_route_hold: tuple[str, str] | None = None
    dev_k_c: AssembledDeviceLotScopeKey | None = None
    try:
        dev_k = AssembledDeviceLotScopeKey(
            mcb_k.product_variant_id,
            mcb_k.construct_sha256,
            mcb_k.donor_seedline_id,
            mcb_k.mcb_id,
            lot_k.lot_id,
            target_provenance['device_assembly_id'],
            target_provenance['physical_route_id'],
        )
        dev_k_c = AssembledDeviceLotScopeKey(
            pvid_canon,
            mcb_k.construct_sha256,
            mcb_k.donor_seedline_id,
            mcb_k.mcb_id,
            lot_k.lot_id,
            dev_k.device_assembly_id,
            dev_k.physical_route_id,
        )
        routes = ENDPOINT_REGISTRY_SPEC['physical_routes']
        if dev_k.physical_route_id not in routes:
            early_device_or_route_hold = ('HOLD_UNREGISTERED_PHYSICAL_ROUTE_ID', dev_k.physical_route_id)
        else:
            route_spec = routes[dev_k.physical_route_id]
            if is_z_prod and not route_spec['requires_design_z_two_stage']:
                early_device_or_route_hold = ('HOLD_BIDIRECTIONAL_PRODUCT_PHYSICAL_ROUTE_MISMATCH', dev_k.physical_route_id)
            elif not is_z_prod and route_spec['requires_design_z_two_stage']:
                early_device_or_route_hold = ('HOLD_BIDIRECTIONAL_PRODUCT_PHYSICAL_ROUTE_MISMATCH', dev_k.physical_route_id)
    except (KeyError, TypeError, ValueError) as exc:
        early_device_or_route_hold = ('HOLD_MISSING_OR_INVALID_IMMUTABLE_PROVENANCE_KEY', str(exc))

    def _canon_scope_tuple_iip0031(sk: Any) -> tuple[str, ...]:
        raw_t = sk.as_tuple()
        c_pid, _ = _canonicalize_product_id_iip0031(raw_t[0], root_path)
        return (c_pid or raw_t[0], *raw_t[1:])

    mcb_store: dict[str, AtomicObservation] = {}
    lot_store: dict[str, AtomicObservation] = {}
    dev_store: dict[str, AtomicObservation] = {}
    atom_status_by_store_key: dict[tuple[str, str], str] = {}
    invalidated_stale_keys: set[str] = set()
    latched_adverse: dict[tuple[str, tuple[str, ...]], dict[str, Any]] = {}
    retained_reset_audit_log: list[dict[str, Any]] = []
    structural_holds: list[str] = []
    malformed_batch_holds: list[str] = []
    tier6b_atoms_collected: list[Any] = []
    s11_panel_eval_collected: dict[str, Any] | None = None
    latched_s11_fail_eval: dict[str, Any] | None = None
    latched_s11_fail_b_idx: int | None = None
    latched_s11_all_fail_reasons: list[str] = []
    elevated_store_gate0s_escalated_on_lot = False
    iip0029_lot_source_fingerprint: tuple[Any, ...] | None = None
    iip0029_lot_store_sample_unit_id: str | None = None

    count_caps = ENDPOINT_REGISTRY_SPEC['count_endpoint_caps_and_zero_vetoes']
    sister_terminal_ids = set(ENDPOINT_REGISTRY_SPEC['device_sister_terminal_endpoint_ids'])
    target_scope_tuples = {mcb_k_c.as_tuple(), lot_k_c.as_tuple()}
    if dev_k_c is not None and early_device_or_route_hold is None:
        target_scope_tuples.add(dev_k_c.as_tuple())

    for b_idx, batch in enumerate(batches):
        if not isinstance(batch, dict):
            malformed_batch_holds.append('HOLD_MALFORMED_BATCH_ATOM_LIST')
            continue
        has_t6b_container = False
        for _nested_name in ('scope', 'measurements', 'iip0026_molecular_observations'):
            if _nested_name in batch and batch[_nested_name] is not None and not isinstance(batch[_nested_name], dict):
                malformed_batch_holds.append('HOLD_MALFORMED_BATCH_ATOM_LIST')
                tier6b_atoms_collected.append(None)
        _b_t6_ctrs = (
            batch,
            batch.get('scope') if isinstance(batch.get('scope'), dict) else {},