"""Estadística sin dependencias para el piloto: intervalos exactos (Clopper-Pearson), Fisher exacto bilateral, AUC con empates, kappa de Cohen y bootstrap por percentiles con semilla fija.""" from __future__ import annotations import math import random from typing import Callable, Sequence SEMILLA_BOOT = 20261021 B_BOOT = 10_000 def _log_binom_pmf(i: int, n: int, p: float) -> float: if p <= 0: return 0.0 if i == 0 else -math.inf if p >= 1: return 0.0 if i == n else -math.inf return (math.lgamma(n + 1) - math.lgamma(i + 1) - math.lgamma(n - i + 1) + i * math.log(p) + (n - i) * math.log1p(-p)) def binom_cdf(k: int, n: int, p: float) -> float: if k < 0: return 0.0 if k >= n: return 1.0 return min(1.0, sum(math.exp(_log_binom_pmf(i, n, p)) for i in range(0, k + 1))) def _biseccion(f: Callable[[float], float], objetivo: float, creciente: bool) -> float: lo, hi = 0.0, 1.0 for _ in range(200): mid = (lo + hi) / 2 v = f(mid) if (v < objetivo) == creciente: lo = mid else: hi = mid return (lo + hi) / 2 def clopper_pearson(k: int, n: int, alfa: float = 0.05) -> tuple[float | None, float | None]: if n <= 0: return None, None lo = 0.0 if k == 0 else _biseccion(lambda p: 1 - binom_cdf(k - 1, n, p), alfa / 2, True) hi = 1.0 if k == n else _biseccion(lambda p: binom_cdf(k, n, p), alfa / 2, False) return lo, hi def fisher_bilateral(a: int, b: int, c: int, d: int) -> float: """Tabla [[a, b], [c, d]]; suma de las probabilidades hipergeométricas ≤ la observada.""" r1, r2, c1, n = a + b, c + d, a + c, a + b + c + d if n == 0: return 1.0 def lp(x): return (math.lgamma(r1 + 1) - math.lgamma(x + 1) - math.lgamma(r1 - x + 1) + math.lgamma(r2 + 1) - math.lgamma(c1 - x + 1) - math.lgamma(r2 - c1 + x + 1) - math.lgamma(n + 1) + math.lgamma(c1 + 1) + math.lgamma(n - c1 + 1)) obs = lp(a) tot = 0.0 for x in range(max(0, c1 - r2), min(r1, c1) + 1): v = lp(x) if v <= obs + 1e-9: tot += math.exp(v) return min(1.0, tot) def auc(pos: Sequence[float], neg: Sequence[float]) -> float | None: if not pos or not neg: return None s = 0.0 for p in pos: for q in neg: s += 1.0 if p > q else (0.5 if p == q else 0.0) return s / (len(pos) * len(neg)) def kappa(pares: Sequence[tuple[int, int]]) -> float | None: n = len(pares) if not n: return None po = sum(1 for a, b in pares if a == b) / n pa = sum(a for a, _ in pares) / n pb = sum(b for _, b in pares) / n pe = pa * pb + (1 - pa) * (1 - pb) if pe >= 1: return None return (po - pe) / (1 - pe) def kappa_cuentas(c11: int, c10: int, c01: int, c00: int) -> float | None: """Kappa de Cohen desde la tabla 2×2 (c11 = los dos 1, c10 = A 1 y B 0, …).""" n = c11 + c10 + c01 + c00 if not n: return None po = (c11 + c00) / n pa, pb = (c11 + c10) / n, (c11 + c01) / n pe = pa * pb + (1 - pa) * (1 - pb) if pe >= 1: return None return (po - pe) / (1 - pe) def percentil(xs: list[float], q: float) -> float: xs = sorted(xs) if not xs: return float('nan') k = (len(xs) - 1) * q f, c = math.floor(k), math.ceil(k) return xs[f] if f == c else xs[f] + (xs[c] - xs[f]) * (k - f) def bootstrap(grupos: Sequence[Sequence], estadistico: Callable[..., float | None], b: int = B_BOOT, semilla: int = SEMILLA_BOOT) -> dict: """Remuestrea con reemplazo, por separado, cada grupo de unidades (p. ej. casos P+ y casos N+) y devuelve el intervalo de percentiles 2,5-97,5 del estadístico (las réplicas en que no está definido no cuentan).""" rnd = random.Random(semilla) vals = [] for _ in range(b): muestra = [[g[rnd.randrange(len(g))] for _ in range(len(g))] if g else [] for g in grupos] v = estadistico(*muestra) if v is not None and not (isinstance(v, float) and math.isnan(v)): vals.append(v) if not vals: return {'ic95': [None, None], 'replicas_validas': 0} return {'ic95': [percentil(vals, 0.025), percentil(vals, 0.975)], 'replicas_validas': len(vals)}