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…

            try:
                below = _is_below(mid)
            except ArithmeticError:
                # Retain the already-established outer bracket on numerical failure.
                return hi if upper else lo
            if below:
                lo = mid
            else:
                hi = mid


def _clopper_pearson_limit(k: int, n: int, alpha: float, *, upper: bool) -> float:
    if type(k) is not int or type(n) is not int or n <= 0 or not 0 <= k <= n:
        raise ValueError('Clopper-Pearson requires integer 0 <= k <= n and n > 0')
    if type(alpha) not in (int, float) or not math.isfinite(float(alpha)) or not 0 < alpha < 1:
        raise ValueError('Clopper-Pearson requires a finite numeric alpha strictly between 0 and 1')
    if upper and k == n:
        return 1.0
    if not upper and k == 0:
        return 0.0
    if n.bit_length() > 53:
        return 1.0 if upper else 0.0
    if (upper and k in (0, n - 1)) or (not upper and k in (1, n)):
        from decimal import localcontext
        with localcontext() as ctx:
            ctx.prec = 96
            a_dec = Decimal.from_float(float(alpha))
            n_dec = Decimal(n)
            if upper and k == 0:
                exact = Decimal(1) - (a_dec.ln() / n_dec).exp()
            elif not upper and k == n:
                exact = (a_dec.ln() / n_dec).exp()
            elif upper and k == n - 1:
                exact = ((Decimal(1) - a_dec).ln() / n_dec).exp()
            else:
                exact = Decimal(1) - ((Decimal(1) - a_dec).ln() / n_dec).exp()
            if exact <= 0:
                return 0.0
            if exact >= 1:
                return 1.0
            res = float(exact)
            if upper:
                while Decimal.from_float(res) < exact and res < 1.0:
                    res = math.nextafter(res, 1.0)
            else:
                while Decimal.from_float(res) > exact and res > 0.0:
                    res = math.nextafter(res, 0.0)
            return res
    return _cp_interior_limit(k, n, float(alpha), upper)


def clopper_pearson_upper95_independent(k: int, n: int, alpha: float = 0.05) -> float:
    """One-sided binomial upper confidence limit, conservatively enclosed on numerical failure."""
    return _clopper_pearson_limit(k, n, alpha, upper=True)


def clopper_pearson_lower95_independent(k: int, n: int, alpha: float = 0.05) -> float:
    """One-sided binomial lower confidence limit, conservatively enclosed on numerical failure."""
    return _clopper_pearson_limit(k, n, alpha, upper=False)


S9_CORE_LOT_ENDPOINT_IDS = (
    'obs_icasp9_log10_kill',
    'obs_tp53_ppm1d_bcor_vaf',
    'obs_castseq_translocation_freq',
)
S9_FREQUENCY_ASSAY_KEYS = {
    'obs_tp53_ppm1d_bcor_vaf': ('obs_tp53_ppm1d_bcor_duplex_depth', 'obs_tp53_ppm1d_bcor_mutant_molecules_k'),
    'obs_castseq_translocation_freq': ('obs_castseq_duplex_or_amplicon_depth', 'obs_castseq_mutant_junctions_k'),
}
S9_REPLICATE_KEYS = {
    'default': ('obs_stage0_independent_lot_replicates_n', 'replicates_n', 'sample_n'),
    'obs_icasp9_log10_kill': ('obs_icasp9_log10_kill_n', 'obs_icasp9_log10_kill_sample_n', 'obs_icasp9_log10_kill_replicates_n'),
    'obs_tp53_ppm1d_bcor_vaf': ('obs_tp53_ppm1d_bcor_vaf_n', 'obs_tp53_ppm1d_bcor_vaf_sample_n', 'obs_tp53_ppm1d_bcor_vaf_replicates_n'),
    'obs_castseq_translocation_freq': ('obs_castseq_translocation_freq_n', 'obs_castseq_translocation_n', 'obs_castseq_translocation_sample_n', 'obs_castseq_translocation_replicates_n'),
}
_S9_ASSAY_RANGES = {
    key: (low, high) for _, key, _, low, high, _ in STAGE0_DECISION_TREE_ENDPOINT_SPECS
    if key in S9_CORE_LOT_ENDPOINT_IDS or any(key in pair for pair in S9_FREQUENCY_ASSAY_KEYS.values())
}


def _resolve_s9_replicate_counts_detailed_iip0031(
    containers: tuple[dict[str, Any], ...] | list[dict[str, Any]],
    *,
    flag_explicit_none: bool = False,
) -> tuple[dict[str, int | None], set[str], bool]:
    """
    Order-independent S9 replicate-count resolver across all containers and aliases
    in each S9_REPLICATE_KEYS group, unifying lot-default and endpoint-specific keys
    identically to Atomic Stage-0 Ledger (IIP-0031; DEC-110).
    Returns (resolved_by_group, conflicted_groups, any_conflict_or_invalid):
      - For `default`, inspects `S9_REPLICATE_KEYS['default']`; for each endpoint `eid`,
        inspects `(*S9_REPLICATE_KEYS['default'], *S9_REPLICATE_KEYS[eid])` so a conflict
        between `replicates_n` (e.g. 6) and `obs_icasp9_log10_kill_n` (e.g. 100) is handled
        identically across Direct, Atomic Ledger, Serialized Ingestion, and Chronological Replay.
      - Any group with multiple distinct supplied values (type-aware, unhashable-safe)
        or any invalid value (not an integral count in [6, 10000]) is flagged.
      - For S9 hard-stop evaluation, picks the most conservative valid integer count >= 2
        (`min(valid_ge2)`, capped at <= 6 when an invalid entry also appears in the group)
        so contradictory counts always evaluate symmetrically at the wider Student-t bound.
    """
    resolved: dict[str, int | None] = {}
    conflicted_groups: set[str] = set()
    group_key_map = {
        'default': S9_REPLICATE_KEYS['default'],
        **{
            eid: (*S9_REPLICATE_KEYS['default'], *S9_REPLICATE_KEYS[eid])
            for eid in S9_CORE_LOT_ENDPOINT_IDS
        },
    }
    for group_name, group_keys in group_key_map.items():
        supplied: list[Any] = []
        explicit_none_seen = False
        for container in containers:
            if not isinstance(container, dict):
                continue
            for key in group_keys:
                if key not in container:
                    continue
                val = container[key]
                if val is None:
                    if flag_explicit_none:
                        explicit_none_seen = True
                    continue
                supplied.append(val)
        if not supplied and not explicit_none_seen:
            continue
        first_val = supplied[0] if supplied else None
        group_conflict = False
        for v in supplied[1:]:
            if _is_integral_count_iip0026(v) and _is_integral_count_iip0026(first_val):
                if int(v) != int(first_val):
                    group_conflict = True
                    break
            elif type(v) is not type(first_val) or v != first_val:
                group_conflict = True
                break
        group_invalid = explicit_none_seen or any(
            not _is_integral_count_iip0026(v) or not (6 <= int(v) <= 10000)
            for v in supplied
        )
        if group_conflict or group_invalid:
            conflicted_groups.add(group_name)
        valid_ge2 = [
            (v if type(v) is int else int(round(v)))
            for v in supplied
            if (
                (type(v) is int and 2 <= v <= 10000)
                or (isinstance(v, float) and math.isfinite(v) and 2.0 <= v <= 10000.0 and v.is_integer())
            )
        ]
        if valid_ge2:
            resolved[group_name] = min(valid_ge2 + ([6] if group_invalid else []))
        else:
            resolved[group_name] = None
    return resolved, conflicted_groups, bool(conflicted_groups)


def _evaluate_s9_tp53_vaf_guard(
    vaf_val: Any,
    vaf_se: Any,
    duplex_depth: Any,
    *,
    sample_n: Any = None,
    mutant_molecules_k: Any = None,
    require_explicit_depth: bool = True,
    cap: float = 1.0e-4,
    min_depth: float = 62958.0,
    endpoint_label: str = 'obs_tp53_ppm1d_bcor_vaf',
) -> dict[str, Any]:
    """
    Single shared Rule S9 TP53/PPM1D/BCOR VAF & CAST-Seq translocation guard across ALL 4 entry paths
    (Direct product contract, Atomic Stage-0 Ledger, Serialized JSON Ingestion, and Chronological Replay;
    IIP-0031; DEC-110).
    - Never defaults omitted duplex depth to 62,958 on live paths (`require_explicit_depth=True` holds).
    - Computes the EXACT same one-sided 95% Student-t (df = sample_n - 1, defaulting to df = 5 / n = 6
      per DEC-104 when omitted), Wald normal, and exact Poisson upper95 bounds identically across all 4 paths.
    """
    if not _is_strict_finite_number_iip0024(vaf_val) or not _is_strict_finite_number_iip0024(vaf_se):
        return {
            'status': 'HOLD_S9_OUT_OF_RANGE_VAF_OR_SE',
            'hard_stop': False,
            'upper95': 1.0,
            'depth_explicit': False,
            'depth_underpowered': True,
        }
    val_f = float(vaf_val)
    se_f = float(vaf_se)
    if val_f < 0.0 or val_f > 1.0 or se_f < 0.0:
        return {
            'status': 'HOLD_S9_OUT_OF_RANGE_VAF_OR_SE',
            'hard_stop': False,
            'upper95': 1.0,
            'depth_explicit': False,
            'depth_underpowered': True,
        }
    if (
        sample_n is not None
        and type(sample_n) is not bool
        and isinstance(sample_n, (int, float))
        and math.isfinite(float(sample_n))
        and float(sample_n) >= 2.0
    ):
        t95_mult = student_t_ppf_one_sided_95(float(int(round(float(sample_n))) - 1))
    else:
        t95_mult = student_t_ppf_one_sided_95(5.0)
    t_u95 = val_f + t95_mult * se_f
    wald_u95 = val_f + 1.645 * se_f
    param_u95 = max(t_u95, wald_u95)

    depth_key, count_key = S9_FREQUENCY_ASSAY_KEYS[endpoint_label]
    bad_count = mutant_molecules_k is not None and (
        not _is_integral_count_iip0026(mutant_molecules_k)
        or not 0 <= mutant_molecules_k <= _S9_ASSAY_RANGES[count_key][1]
    )
    if bad_count:
        mutant_molecules_k = None
    depth_explicit = duplex_depth is not None
    if not depth_explicit:
        k_ref = val_f * min_depth
        if mutant_molecules_k is not None:
            k_ref = max(float(mutant_molecules_k), k_ref)
        pois_ref = _poisson_exact_upper95_rate(k_ref, min_depth)
        eff_u95 = max(param_u95, pois_ref)
        is_stop = bool(val_f >= cap or eff_u95 >= cap)
        if is_stop:
            return {
                'status': 'FAIL_HARD_STOP',
                'hard_stop': True,
                'upper95': eff_u95,
                'depth_explicit': False,
                'depth_underpowered': bool(require_explicit_depth),
            }
        return {
            'status': 'HOLD_S9_MISSING_OR_INVALID_DUPLEX_DEPTH',
            'hard_stop': False,
            'upper95': eff_u95,
            'depth_explicit': False,
            'depth_underpowered': bool(require_explicit_depth),
        }

    if (
        not _is_integral_count_iip0026(duplex_depth)
        or not _S9_ASSAY_RANGES[depth_key][0] <= duplex_depth <= _S9_ASSAY_RANGES[depth_key][1]
    ):
        is_stop = bool(val_f >= cap or param_u95 >= cap)
        return {
            'status': 'FAIL_HARD_STOP' if is_stop else 'HOLD_S9_MISSING_OR_INVALID_DUPLEX_DEPTH',
            'hard_stop': is_stop,