return adj def paired_t_summary(diffs: Sequence[float]) -> Optional[tuple[float, float, float, float]]: """Return (mean, t_stat, two_sided_p, one_sided_l95) for paired differences, or None if degenerate.""" n = len(diffs) if n < 2: return None mean_d = sum(diffs) / n var_d = sum((d - mean_d) ** 2 for d in diffs) / (n - 1) if var_d <= 0.0: return None se = math.sqrt(var_d / n) t_stat = mean_d / se p_two = student_t_two_sided_p(abs(t_stat), n - 1) l95 = mean_d - student_t_one_sided_crit(0.05, n - 1) * se return mean_d, t_stat, p_two, l95 def two_sample_welch_summary(x: Sequence[float], y: Sequence[float]) -> Optional[tuple[float, float, float, float]]: """Return (mean_x - mean_y, t_stat, two_sided_p, one_sided_l95) via Welch's t-test, or None if degenerate.""" nx, ny = len(x), len(y) if nx < 2 or ny < 2: return None mx = sum(x) / nx my = sum(y) / ny vx = sum((v - mx) ** 2 for v in x) / (nx - 1) vy = sum((v - my) ** 2 for v in y) / (ny - 1) s2 = vx / nx + vy / ny if s2 <= 0.0: return None se = math.sqrt(s2) denom = ((vx / nx) ** 2) / (nx - 1) + ((vy / ny) ** 2) / (ny - 1) df = max(1.0, (s2 * s2) / denom) diff = mx - my t_stat = diff / se p_two = student_t_two_sided_p(abs(t_stat), df) l95 = diff - student_t_one_sided_crit(0.05, df) * se return diff, t_stat, p_two, l95 def fieller_ratio_one_sided_lower( num: Sequence[float], den: Sequence[float], *, paired: bool = True, alpha: float = 0.05, ) -> Optional[tuple[float, float]]: """ Exact one-sided (1-alpha) Fieller lower bound for ratio R = E[num] / E[den] (mean(den) > 0). Returns (point_ratio, fieller_lower) or None if denominator precision fails (g >= 1) or degenerate. """ nx, ny = len(num), len(den) if nx < 2 or ny < 2 or (paired and nx != ny): return None mx = sum(num) / nx my = sum(den) / ny if my <= 0.0: return None vx = sum((v - mx) ** 2 for v in num) / (nx - 1) vy = sum((v - my) ** 2 for v in den) / (ny - 1) if paired: v_mx = vx / nx v_my = vy / nx cov_m = sum((num[i] - mx) * (den[i] - my) for i in range(nx)) / (nx * (nx - 1)) df = nx - 1 else: v_mx = vx / nx v_my = vy / ny cov_m = 0.0 df = min(nx, ny) - 1 tcrit = student_t_one_sided_crit(alpha, df) t2 = tcrit * tcrit g = t2 * v_my / (my * my) if g >= 1.0: return None # Quadratic: (my^2 - t2*v_my)*R^2 - 2*(mx*my - t2*cov_m)*R + (mx^2 - t2*v_mx) <= 0 a = my * my - t2 * v_my b = mx * my - t2 * cov_m c = mx * mx - t2 * v_mx disc = b * b - a * c if disc < 0.0: return None r_lo = (b - math.sqrt(disc)) / a return (mx / my), r_lo def sample_t_one_sided_bounds( vals: Sequence[float], alpha: float = 0.05, *, extra_within_var: float = 0.0, ) -> Optional[tuple[float, float, float]]: """Return (mean, one_sided_l, one_sided_u) at tail alpha for n >= 2 values (with optional extra within-lot variance).""" n = len(vals) if n < 2: return None if all(v == vals[0] for v in vals): return None mean_v = sum(vals) / n var_v = sum((v - mean_v) ** 2 for v in vals) / (n - 1) # Match live wetlab_contract.py:_one_sided_t_bounds_iip0029: zero between-block variance # is ALWAYS unestimable (returns None) BEFORE adding extra_within_var! if var_v <= 0.0: return None tot_se_sq = (var_v / n) + max(0.0, float(extra_within_var)) if tot_se_sq <= 0.0: return None se = math.sqrt(tot_se_sq) tcrit = student_t_one_sided_crit(alpha, n - 1) return mean_v, mean_v - tcrit * se, mean_v + tcrit * se def _eval_t_bound_from_vec(vals: Sequence[float], tcrit: float, *, upper: bool) -> float: n = len(vals) m = sum(vals) / n v = sum((x - m) ** 2 for x in vals) / (n - 1) se = math.sqrt(v / n) if v > 0.0 else 0.0 return m + tcrit * se if upper else m - tcrit * se def censor_aware_t_bound( intervals: Sequence[tuple[float, float]], alpha: float = 0.05, *, upper: bool = True, ) -> Optional[float]: """ Mathematically EXACT worst-case censor-aware one-sided Student-t confidence bound over x_i in [lo_i, hi_i] (Bauer's Maximum Principle): - U_alpha(x) = mean(x) + t_{1-alpha,n-1} * sd(x) / sqrt(n) is CONVEX on prod_i [lo_i, hi_i], so its global supremum over ALL admissible completions is attained at a vertex. - L_alpha(x) = mean(x) - t_{1-alpha,n-1} * sd(x) / sqrt(n) is CONCAVE on prod_i [lo_i, hi_i], so its global infimum over ALL admissible completions is attained at a vertex. Uses exact symmetry grouping by identical uncertain intervals (O(n) for single-analyte censoring, exact product/bitmask for multi-analyte censoring). Returns None if n < 2 or combinatorial bound exceeded. """ n = len(intervals) if n < 2: return None tcrit = student_t_one_sided_crit(alpha, n - 1) fixed_vals: list[float] = [] groups: dict[tuple[float, float], list[tuple[float, float]]] = {} uncert_count = 0 for lo, hi in intervals: if hi < lo - 1e-12: return None if hi <= lo + 1e-15: fixed_vals.append(lo) else: key = (round(lo, 12), round(hi, 12)) groups.setdefault(key, []).append((lo, hi)) uncert_count += 1 if uncert_count == 0: return _eval_t_bound_from_vec(fixed_vals, tcrit, upper=upper) group_items = list(groups.values()) total_states = 1 for grp in group_items: total_states *= (len(grp) + 1) if total_states > 16384: return None best: Optional[float] = None def _recurse(g_idx: int, acc: list[float]) -> None: nonlocal best if g_idx == len(group_items): val = _eval_t_bound_from_vec(acc, tcrit, upper=upper) if best is None or (upper and val > best) or ((not upper) and val < best): best = val return grp = group_items[g_idx] k = len(grp) lo_g, hi_g = grp[0] for m_lo in range(k + 1): acc.extend([lo_g] * m_lo) acc.extend([hi_g] * (k - m_lo)) _recurse(g_idx + 1, acc) del acc[-k:] _recurse(0, list(fixed_vals)) return best def _std_normal_inv_cdf(p: float) -> float: """Exact standard normal inverse CDF via monotone bisection on math.erfc (1e-13 accuracy, zero external deps).""" lo, hi = -10.0, 10.0 for _ in range(70): mid = 0.5 * (lo + hi) cdf = 0.5 * math.erfc(-mid / math.sqrt(2.0)) if cdf < p: lo = mid else: hi = mid return 0.5 * (lo + hi) def paired_diff_normality_qq_r(diffs: Sequence[float]) -> Optional[float]: """Compute Blom normal-quantile correlation r_QQ (Shapiro-Francia/Filliben normality diagnostic) for n >= 3.""" n = len(diffs) if n < 3: return None ys = sorted(float(x) for x in diffs) qs = [_std_normal_inv_cdf((i + 1.0 - 0.375) / (n + 0.25)) for i in range(n)] my = sum(ys) / n mq = sum(qs) / n vy = sum((y - my) ** 2 for y in ys) vq = sum((q - mq) ** 2 for q in qs) if vy <= 0.0 or vq <= 0.0: return None cov = sum((ys[i] - my) * (qs[i] - mq) for i in range(n)) return cov / math.sqrt(vy * vq) def _eval_horner_poly(coeffs: Sequence[float], x: float) -> float: acc = 0.0 for c in coeffs: acc = acc * x + c return acc def shapiro_wilk_test(xs: Sequence[float]) -> Optional[tuple[float, float]]: """ Pure-Python Algorithm AS R94 Shapiro-Wilk normality test (Royston 1992, Applied Statistics 41:117-133) for 3 <= n <= 50. Matches R stats::shapiro.test / SciPy to < 1e-4; returns (W, p_value) or None. """ n = len(xs) if n < 3 or n > 50: return None s = sorted(float(x) for x in xs) mean = sum(s) / n ss = sum((x - mean) ** 2 for x in s) if ss <= 1e-18: return None m = [_std_normal_inv_cdf((i + 1.0 - 0.375) / (n + 0.25)) for i in range(n)] m_ss = sum(v * v for v in m) u = 1.0 / math.sqrt(n) a = [0.0] * n if n == 3: a[2] = math.sqrt(0.5) a[0] = -a[2] a[1] = 0.0 else: an = _eval_horner_poly([-2.706056, 4.434685, -2.071190, -0.147981, 0.221157, m[-1] / math.sqrt(m_ss)], u) a[-1] = an a[0] = -an if n <= 5: phi = (m_ss - 2.0 * m[-1] ** 2) / (1.0 - 2.0 * an ** 2) sp = math.sqrt(phi) for i in range(1, n - 1): a[i] = m[i] / sp else: an1 = _eval_horner_poly([-3.582633, 5.682633, -1.752461, -0.293762, 0.042981, m[-2] / math.sqrt(m_ss)], u) a[-2] = an1