OpenIslet

scripts/verify_iip0042_master_multilayer_portfolio_crosswalk.py

IIP-0042 / DEC-121 (CAND-033 / EXP-030): Master Exact 2^20 Multi-Layer Portfolio

script Release v0.8.0 gen-eb955f8266035aba 881 KB · 63 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_iip0042_master_multilayer_portfolio_crosswalk.py · SHA-256: 16964a158458b5cf…

    "INDEPENDENT_DROPLET_PARTITIONS": frozenset({
        "Single physically isolated microfluidic droplet partition "
        "(one independent primary T1D APC partition per unit prior to dosing)",
        "INDEPENDENT_DROPLET_PARTITION",
    }),
    "INDEPENDENT_CLONAL_COLONIES": frozenset({
        "Single physically separated clonal primary T1D APC colony unit "
        "(one independent isolated colony per unit prior to dosing)",
        "INDEPENDENT_CLONAL_COLONY",
    }),
}
_SHIELD_ALLOWED_CLUSTERING_CONTROLS: dict[str, frozenset[str]] = {
    "INDEPENDENT_REPLICATE_WELLS": frozenset({
        "Randomized plate layout across physically separated wells with independent "
        "dosing aliquots and zero cross-well pooling",
        "RANDOMIZED_SEPARATE_WELLS_INDEPENDENT_ALIQUOTS_NO_POOLING",
    }),
    "INDEPENDENT_DROPLET_PARTITIONS": frozenset({
        "Physically isolated independent droplet partitions with independent "
        "reagent loading and zero cross-droplet pooling",
        "ISOLATED_DROPLET_PARTITIONS_INDEPENDENT_LOADING_NO_POOLING",
    }),
    "INDEPENDENT_CLONAL_COLONIES": frozenset({
        "Physically separated independent clonal colony units with independent "
        "dosing aliquots and zero cross-colony pooling",
        "SEPARATED_CLONAL_COLONIES_INDEPENDENT_ALIQUOTS_NO_POOLING",
    }),
}
_SHIELD_ALLOWED_GY018_UNIT_CLASSES: frozenset[str] = frozenset(
    _SHIELD_ALLOWED_INDEPENDENT_EXPERIMENTAL_UNITS.keys()
)
_SHIELD_FWER_EXTERNAL_CUSTODY_CONDITION = (
    "Exact distribution-free FWER <= 0.05 Boole bound applies strictly to the fixed-roster, fixed-per-donor-N, "
    "single-look donor cytotoxicity family (H0_all: max_{i=1..N_roster} p_i <= 5.0%, NOT the union with SPR or "
    "suppression failure routes) and holds mathematically conditional on external outcome-blind custody and "
    "pre-readout commitment receipt of the FULL preregistered analysis plan inside preregistered_donor_family_roster "
    "(roster membership, fixed per-donor sample size N, and single-look fixed horizon planned_analysis_looks == 1) "
    "prior to assay readouts; unpinned, tampered, multi-look, sample-size-mismatched, or incompletely reconciled "
    "submissions fail closed to non-authorizing HOLD_INVALID_OR_MISSING_INPUT for overall PASS and donor-based "
    "FAIL (independent valid non-donor SPR failures remain fail-first FAIL, while out-of-spec physicochemical "
    "SEC-MALS/DLS measurements route to HOLD_INVALID_OR_MISSING_INPUT as unqualified material inputs)."
)
_SHIELD_SUPPRESSION_STATISTICAL_BOUNDARY_NOTE = (
    "Exact <= 5% finite-sample Clopper-Pearson suppression error control applies to the HLA-DQ-eligible "
    "(HLA-DQ2.5, HLA-DQ8, HLA-DQ8-trans, or HLA-DQ2.2) T1D donor sampling frame and is computed conservatively "
    "over donor, expression-batch, assay-run, and joint (batch U run) connected-component clusters "
    "(requiring >= 9 disjoint batch/run units for confirmatory PASS and >= 6 disjoint batch/run units "
    "for suppression FAIL) strictly for simple random or consecutive independent cohorts "
    "(sampling_design_class == 'SIMPLE_RANDOM_OR_CONSECUTIVE_INDEPENDENT_T1D_COHORT'); stratified/quota "
    "cohorts such as 'STRATIFIED_INDEPENDENT_T1D_HLA_DQ_COHORT' are non-authorizing for unweighted "
    "population-suppression inference and route to HOLD "
    "(STRATIFIED_COHORT_REQUIRES_TARGET_WEIGHTED_SUPPRESSION_ESTIMATOR). Only the one-sided lower bounds "
    "(suppression_responder_l95_clopper_pearson_pct and suppression_nonresponder_lt40_l95_clopper_pearson_pct) "
    "drive PASS/FAIL adjudication; suppression_responder_u95_clopper_pearson_pct is a descriptive diagnostic "
    "only with no general marginal upper-coverage guarantee under cluster-all-positive events. For each "
    "independent connected component C_j, the cluster-level all-positive event probability P(all donors in "
    "C_j meet threshold) is bounded above by the applicable single-donor marginal probability p_donor ONLY "
    "under independent components with non-informative cluster sizes and identical marginal response "
    "distributions across assay conditions; informative cluster sizes or systematically differing batch/run "
    "assay conditions are external sampling and laboratory QA assumptions not verified by ID graph topology "
    "alone, and external pre-readout custody of preregistered_donor_family_roster remains mandatory."
)
_SHIELD_LOCAL_JSON_REPLAY_SCOPE_NOTE = (
    "Local JSON replay verifies cryptographic digest calculation over the full pre-registered analysis plan "
    "(roster membership, fixed per-donor sample size N, and single-look fixed horizon planned_analysis_looks == 1), "
    "per-mixture physical co-formulation SEC-MALS/DLS binding, matched shared comparator expression-batch coverage "
    "across WT15 and 6DFX, complete raw roster accounting, strict canonical allowlist schemas for GY-018 and "
    "sampling-design declarations (zero free-text prose accepted), complete donor batch/run dependency topology "
    "retention, and cluster-conservative Clopper-Pearson/Bonferroni bounds only; an independent external pre-readout "
    "commitment receipt covering the full analysis plan and a laboratory QA audit verifying physical unit "
    "independence and target-population sampling are required before relying on the conditional statistical "
    "error-rate interpretation."
)

# Exact complete two-sided 95% Student-t critical values (alpha = 0.05; one-sided 97.5% quantile) for EVERY integer df = 1..30 (zero interpolation!)
_SHIELD_STUDENT_T_95_TWO_SIDED: dict[int, float] = {
    1: 12.706204736432095,
    2: 4.302652729911275,
    3: 3.182446305284263,
    4: 2.7764451051977987,
    5: 2.5705818366147395,
    6: 2.4469118487916806,
    7: 2.3646242510102993,
    8: 2.3060041350333704,
    9: 2.2621571627409915,
    10: 2.2281388519649385,
    11: 2.200985160082949,
    12: 2.1788128296634177,
    13: 2.1603686564610127,
    14: 2.1447866879169273,
    15: 2.131449545559323,
    16: 2.1199052992210112,
    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):