OpenIslet

scripts/verify_iip0044_foundry_v1_3_biologics.py

IIP-0044 / DEC-123 (CAND-035 / EXP-032): OpenIslet Foundry v1.3 Clean-Room

script Release v0.8.0 gen-eb955f8266035aba 619 KB · 44 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/verify_iip0044_foundry_v1_3_biologics.py · SHA-256: 1d6c53a0817f6254…

    17: 2.1098155778331806,
    18: 2.10092204024096,
    19: 2.093024054408263,
    20: 2.0859634472658364,
    21: 2.079613844727662,
    22: 2.0738730679040147,
    23: 2.0686576104190406,
    24: 2.0638985616280205,
    25: 2.059538552753294,
    26: 2.055529438642871,
    27: 2.0518305164802833,
    28: 2.048407141795244,
    29: 2.045229642132703,
    30: 2.0422724563012373,
}


def _shield_t95_critical(df: int) -> float:
    """Exact two-sided 95% (one-sided 97.5%) Student-t critical value (df=1..30 tabulated verbatim; Cornish-Fisher for df > 30)."""
    if df < 1:
        raise ValueError(f"Student-t degrees of freedom must be >= 1, got {df}")
    if df in _SHIELD_STUDENT_T_95_TWO_SIDED:
        return _SHIELD_STUDENT_T_95_TWO_SIDED[df]
    z = 1.959963984540054
    z3 = z ** 3
    z5 = z ** 5
    return z + (z3 + z) / (4.0 * df) + (5.0 * z5 + 16.0 * z3 + 3.0 * z) / (96.0 * (df ** 2))


def _shield_reject_nonfinite_tree(obj: Any, path: str = "root") -> None:
    """Pre-adjudication strict finiteness & magnitude check: raises ValueError on ANY NaN/Inf/abs>1e300 (Decimal, IEEE-754 float, or exact int)."""
    if isinstance(obj, Decimal):
        if not obj.is_finite() or obj.copy_abs() > Decimal("1e300"):
            raise ValueError(f"Non-finite or overflowing Decimal rejected fail-closed at {path}: {obj!r}")
    elif isinstance(obj, float):
        if not math.isfinite(obj) or abs(obj) > 1e300:
            raise ValueError(f"Non-finite or overflowing float rejected fail-closed at {path}: {obj!r}")
    elif type(obj) is int:
        if abs(obj) > 10 ** 300:
            raise ValueError(f"Overflowing integer rejected fail-closed at {path}")
    elif isinstance(obj, dict):
        for k, v in obj.items():
            _shield_reject_nonfinite_tree(v, f"{path}.{k}")
    elif isinstance(obj, (list, tuple)):
        for i, v in enumerate(obj):
            _shield_reject_nonfinite_tree(v, f"{path}[{i}]")


def _shield_binom_pmf(n: int, k: int, p: float) -> float:
    if p <= 0.0:
        return 1.0 if k == 0 else 0.0
    if p >= 1.0:
        return 1.0 if k == n else 0.0
    log_c = math.lgamma(n + 1) - math.lgamma(k + 1) - math.lgamma(n - k + 1)
    return math.exp(log_c + k * math.log(p) + (n - k) * math.log(1.0 - p))


def _shield_binom_cdf_le(n: int, k: int, p: float) -> float:
    if k < 0:
        return 0.0
    if k >= n:
        return 1.0
    if p <= 0.0:
        return 1.0
    if p >= 1.0:
        return 0.0
    if k <= n // 2:
        return min(1.0, sum(_shield_binom_pmf(n, j, p) for j in range(0, k + 1)))
    return max(0.0, 1.0 - sum(_shield_binom_pmf(n, j, p) for j in range(k + 1, n + 1)))


def _shield_binom_sf_ge(n: int, k: int, p: float) -> float:
    if k <= 0:
        return 1.0
    if k > n:
        return 0.0
    if p <= 0.0:
        return 0.0
    if p >= 1.0:
        return 1.0
    return max(0.0, min(1.0, 1.0 - _shield_binom_cdf_le(n, k - 1, p)))


def _clopper_pearson_one_sided_95_pct(k_obs: int, n_eff: int, alpha: float = 0.05) -> tuple[float, float]:
    """Exact one-sided (1 - alpha) Clopper-Pearson (lower_pct, upper_pct) for k_obs of n_eff independent units."""
    if n_eff < 1 or k_obs < 0 or k_obs > n_eff:
        raise ValueError(f"Invalid Clopper-Pearson counts: k_obs={k_obs}, n_eff={n_eff}")
    if not (0.0 < alpha < 1.0):
        raise ValueError(f"Invalid Clopper-Pearson alpha: {alpha!r}")
    if k_obs == 0:
        return 0.0, 100.0 * (1.0 - (alpha ** (1.0 / n_eff)))
    if k_obs == n_eff:
        return 100.0 * (alpha ** (1.0 / n_eff)), 100.0

    lo, hi = 0.0, k_obs / float(n_eff)
    for _ in range(70):
        mid = 0.5 * (lo + hi)
        if _shield_binom_sf_ge(n_eff, k_obs, mid) < alpha:
            lo = mid
        else:
            hi = mid
    lower = 0.5 * (lo + hi)

    lo, hi = k_obs / float(n_eff), 1.0
    for _ in range(70):
        mid = 0.5 * (lo + hi)
        if _shield_binom_cdf_le(n_eff, k_obs, mid) > alpha:
            lo = mid
        else:
            hi = mid
    upper = 0.5 * (lo + hi)
    return 100.0 * lower, 100.0 * upper


def _shield_check_num(
    val: Any,
    label: str,
    *,
    lo: float | None = None,
    hi: float | None = None,
    strictly_gt_lo: bool = False,
) -> tuple[float | None, str | None]:
    if isinstance(val, bool) or not isinstance(val, (int, float)):
        return None, f"{label} must be a finite non-bool numeric value (got {val!r})"
    fval = float(val)
    if lo is not None:
        if strictly_gt_lo and fval <= lo:
            return None, f"{label}={fval} must be > {lo}"
        if not strictly_gt_lo and fval < lo:
            return None, f"{label}={fval} violates lower bound {lo}"
    if hi is not None and fval > hi:
        return None, f"{label}={fval} violates upper bound {hi}"
    return fval, None


def _shield_check_strict_int(
    val: Any,
    label: str,
    *,
    min_val: int = 0,
    max_val: int | None = None,
) -> tuple[int | None, str | None]:
    if type(val) is not int:
        return None, f"{label} must be a strict integer (got {val!r})"
    if val < min_val:
        return None, f"{label}={val} < required minimum {min_val}"
    if max_val is not None and val > max_val:
        return None, f"{label}={val} > maximum {max_val}"
    return val, None


def _shield_check_exact_deff(val: Any, label: str) -> tuple[float | None, str | None]:
    """Enforce GY-018 exact zero-tolerance design_effect_deff == 1.0, preserving exact Decimal tokens
    decoded by load_strict_json_text (rejecting 1.00000000000000001 and 0.99999999999999999).
    """
    if isinstance(val, bool):
        return None, f"{label} must be a finite non-bool numeric value (got {val!r})"
    if isinstance(val, Decimal):
        if val == Decimal("1"):
            return 1.0, None
        return (
            None,
            f"{label}: GY-018 violation — exact design_effect_deff == 1.0 required "
            f"(got exact Decimal({str(val)!r}) != 1; zero tolerance)",
        )
    if type(val) is int:
        if val == 1:
            return 1.0, None
        return (
            None,
            f"{label}: GY-018 violation — exact design_effect_deff == 1.0 required "
            f"(got {val!r} != 1; zero tolerance)",
        )
    if isinstance(val, float):
        if math.isfinite(val) and val == 1.0:
            return 1.0, None
        return (
            None,
            f"{label}: GY-018 violation — exact design_effect_deff == 1.0 required "
            f"(got {val!r} != 1.0; zero tolerance)",
        )
    return None, f"{label} must be a finite non-bool numeric value (got {val!r})"


def _shield_canonicalize_construct_id(raw_cid: str) -> str:
    clean = raw_cid.strip()
    return _SHIELD_CONSTRUCT_CANONICAL_MAP.get(clean, clean)


def _shield_parse_batch_construct_ids(
    batch_obj: dict[str, Any],
    batch_id: str,
) -> tuple[frozenset[str] | None, str | None]:
    """Parse & validate non-empty construct_ids (or alias constructs) on a declared expression batch."""
    has_cids = "construct_ids" in batch_obj and batch_obj["construct_ids"] is not None
    has_cons = "constructs" in batch_obj and batch_obj["constructs"] is not None
    if not has_cids and not has_cons:
        return None, f"Expression batch {batch_id!r} missing non-empty construct_ids (or constructs) list"

    def _parse_one(raw_list: Any, field_name: str) -> tuple[frozenset[str] | None, str | None]:
        if not isinstance(raw_list, list) or len(raw_list) == 0:
            return None, f"Expression batch {batch_id!r} {field_name} must be a non-empty list of construct IDs"
        seen_c: set[str] = set()
        for c_idx, c_item in enumerate(raw_list):
            if type(c_item) is not str or not c_item.strip():
                return None, f"Expression batch {batch_id!r}.{field_name}[{c_idx}] must be a non-empty string (got {c_item!r})"
            canon = _shield_canonicalize_construct_id(c_item)
            if canon in seen_c:
                return None, f"Expression batch {batch_id!r}.{field_name} contains duplicate construct ID {canon!r}"
            seen_c.add(canon)
        return frozenset(seen_c), None

    cset_primary: frozenset[str] | None = None
    cset_alias: frozenset[str] | None = None
    if has_cids:
        cset_primary, err_p = _parse_one(batch_obj["construct_ids"], "construct_ids")
        if err_p is not None:
            return None, err_p
    if has_cons:
        cset_alias, err_a = _parse_one(batch_obj["constructs"], "constructs")
        if err_a is not None:
            return None, err_a
    if cset_primary is not None and cset_alias is not None and cset_primary != cset_alias:
        return None, (
            f"Expression batch {batch_id!r} construct_ids={sorted(cset_primary)} "
            f"disagrees with constructs={sorted(cset_alias)}"
        )
    final_set = cset_primary if cset_primary is not None else cset_alias
    return final_set, None


def _shield_validate_batch_ids(
    raw_ids: Any,
    label: str,
    passing_batch_constructs: dict[str, frozenset[str]],
    referenced_batches: set[str],
    *,
    required_construct_all: str | None = None,
    require_cocktail_both_leads: bool = False,
    role_comp1_batches: set[str] | None = None,
    role_comp2_batches: set[str] | None = None,
) -> str | None:
    if not isinstance(raw_ids, list) or len(raw_ids) == 0:
        return f"{label} missing non-empty expression_batch_ids linkage list"
    local_seen: set[str] = set()
    for idx, bid in enumerate(raw_ids):
        if type(bid) is not str or not bid.strip():
            return f"{label}.expression_batch_ids[{idx}] must be a non-empty string (got {bid!r})"
        bid_c = bid.strip()
        if bid_c in local_seen: