"""UE1 · funciones compartidas por la implementación PRINCIPAL (la segunda, 60_impl2, no importa esto).""" import math import numpy as np Z95, Z998 = 1.959964, 3.090232 NMIN = 20 SEMILLA = 20261023 def percentil(v, q): s = sorted(v); n = len(s) if n == 0: return float('nan') h = (n - 1) * q; i = int(math.floor(h)); f = h - i return s[i] if i + 1 >= n else s[i] + f * (s[i + 1] - s[i]) def tau2(filas, winsor=True): """filas: (r, e, s) con n >= NMIN. Spiegelhalter 2005; winsor=True: z al 10 % por cola (OU1); False: sin winsorizar.""" fil = [(r, e, s) for r, e, s in filas if s > 0] zs = [(r - e) / s for r, e, s in fil] I = len(zs) if I < 2: return 0.0, float('nan'), I if winsor: lo, hi = percentil(zs, 0.10), percentil(zs, 0.90) zs = [min(max(z, lo), hi) for z in zs] phi = sum(z * z for z in zs) / I w = [1 / (s * s) for r, e, s in fil] sw = sum(w); sw2 = sum(a * a for a in w) t = (I * phi - (I - 1)) / (sw - sw2 / sw) if I * phi > I - 1 else 0.0 return max(t, 0.0), phi, I def posicion(n, zd): if n < NMIN: return 'muestra insuficiente' if zd > Z998: return 'por encima del 99,8 %' if zd > Z95: return 'por encima del 95 %' if zd >= -Z95: return 'dentro' if zd >= -Z998: return 'por debajo del 95 %' return 'por debajo del 99,8 %' def auc(score, y): pares = sorted(zip(score, y)); n1 = sum(y); n0 = len(y) - n1 if n1 == 0 or n0 == 0: return float('nan') i = 0; suma = 0.0 while i < len(pares): j = i while j < len(pares) and pares[j][0] == pares[i][0]: j += 1 suma += (i + 1 + j) / 2 * sum(1 for k in range(i, j) if pares[k][1] == 1) i = j return (suma - n1 * (n1 + 1) / 2) / (n1 * n0) def matriz_boot(n_grupos, B=1000, semilla=SEMILLA): """B x n_grupos: veces que sale cada conglomerado (orden fijo) en cada réplica.""" rng = np.random.default_rng(semilla) C = np.zeros((B, n_grupos), dtype=np.float64) for b in range(B): C[b] = np.bincount(rng.integers(0, n_grupos, n_grupos), minlength=n_grupos) return C def woolf(a, b, c, d): if min(a, b, c, d) == 0: a, b, c, d = a + .5, b + .5, c + .5, d + .5 lor = math.log(a * d / (b * c)); se = math.sqrt(1/a + 1/b + 1/c + 1/d) return math.exp(lor), math.exp(lor - 1.96 * se), math.exp(lor + 1.96 * se)