b1bbbc25b4
Preserve dev risk batches and governance, individual patient selection, optional access and explicit cohort reader overrides. Register one CaMa implementation and retain legacy Python blueprint consumers. Validated with 681 WebApi tests on the integrated parent and submodules.
94 lines
3.8 KiB
Python
94 lines
3.8 KiB
Python
"""The statistics the descriptive analysis uses: Wilson intervals, the chi-square test of homogeneity and quantiles.
|
|
|
|
Plain `math`: no statistics package, so the same inputs give the same numbers on every engine and machine.
|
|
"""
|
|
|
|
import math
|
|
|
|
Z95 = 1.959963984540054
|
|
|
|
|
|
def wilson(k: int, n: int, z: float = Z95) -> tuple[float, float]:
|
|
"""The Wilson score interval of `k` of `n`, as proportions in [0, 1]. Needs `n > 0` and `0 <= k <= n`."""
|
|
if n <= 0 or not 0 <= k <= n:
|
|
raise ValueError(f"Wilson needs 0 <= k <= n and n > 0; got k={k}, n={n}")
|
|
p = k / n
|
|
denominador = 1 + z * z / n
|
|
centro = (p + z * z / (2 * n)) / denominador
|
|
margen = z * math.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / denominador
|
|
return max(0.0, round(centro - margen, 12)), min(1.0, round(centro + margen, 12))
|
|
|
|
|
|
def _gamma_q(a: float, x: float) -> float:
|
|
"""The regularized upper incomplete gamma function Q(a, x)."""
|
|
if x <= 0:
|
|
return 1.0
|
|
if x < a + 1:
|
|
# Series for P(a, x); Q = 1 - P.
|
|
termino = suma = 1.0 / a
|
|
n = a
|
|
for _ in range(1000):
|
|
n += 1
|
|
termino *= x / n
|
|
suma += termino
|
|
if abs(termino) < abs(suma) * 1e-15:
|
|
break
|
|
return max(0.0, 1.0 - suma * math.exp(-x + a * math.log(x) - math.lgamma(a)))
|
|
# Continued fraction for Q(a, x) (modified Lentz).
|
|
tiny = 1e-300
|
|
b = x + 1 - a
|
|
c = 1 / tiny
|
|
d = 1 / b
|
|
h = d
|
|
for i in range(1, 1000):
|
|
an = -i * (i - a)
|
|
b += 2
|
|
d = an * d + b
|
|
d = tiny if abs(d) < tiny else d
|
|
c = b + an / c
|
|
c = tiny if abs(c) < tiny else c
|
|
d = 1 / d
|
|
delta = d * c
|
|
h *= delta
|
|
if abs(delta - 1) < 1e-15:
|
|
break
|
|
return min(1.0, math.exp(-x + a * math.log(x) - math.lgamma(a)) * h)
|
|
|
|
|
|
def chi2_sf(x: float, gl: int) -> float:
|
|
"""The probability that a chi-square variable with `gl` degrees of freedom exceeds `x`."""
|
|
if gl < 1:
|
|
raise ValueError("a chi-square needs at least one degree of freedom")
|
|
return _gamma_q(gl / 2, x / 2)
|
|
|
|
|
|
def chi2_homogeneidad(grupos: list[tuple[int, int]], minimo_esperado: float = 5.0) -> dict:
|
|
"""The chi-square test that `k` groups share one proportion, from each group's (cases, total).
|
|
|
|
Valid only with at least two groups and every expected count (cases and non-cases) at or above `minimo_esperado`;
|
|
otherwise it says why it isn't. Never a p-value from a table the approximation can't be trusted on.
|
|
"""
|
|
if len(grupos) < 2:
|
|
return {"valida": False, "motivo": "Hacen falta al menos dos grupos con datos publicados."}
|
|
casos, total = sum(k for k, _ in grupos), sum(n for _, n in grupos)
|
|
if total == 0 or casos in (0, total):
|
|
return {"valida": False, "motivo": "Todos los pacientes tienen el mismo resultado."}
|
|
p = casos / total
|
|
esperados = [(n * p, n * (1 - p)) for _, n in grupos]
|
|
if any(min(a, b) < minimo_esperado for a, b in esperados):
|
|
return {"valida": False, "motivo": f"Algún conteo esperado es menor que {minimo_esperado:g}: la aproximación no es confiable."}
|
|
estadistico = sum((k - n * p) ** 2 / (n * p) + ((n - k) - n * (1 - p)) ** 2 / (n * (1 - p)) for k, n in grupos)
|
|
gl = len(grupos) - 1
|
|
return {"valida": True, "estadistico": round(estadistico, 4), "gl": gl, "p": chi2_sf(estadistico, gl)}
|
|
|
|
|
|
def cuantil(valores: list[float], q: float) -> float:
|
|
"""The quantile `q` (0 to 1) by linear interpolation between order statistics (the common 'type 7')."""
|
|
if not valores:
|
|
raise ValueError("a quantile needs at least one value")
|
|
ordenados = sorted(valores)
|
|
posicion = (len(ordenados) - 1) * q
|
|
abajo = math.floor(posicion)
|
|
arriba = min(abajo + 1, len(ordenados) - 1)
|
|
return ordenados[abajo] + (ordenados[arriba] - ordenados[abajo]) * (posicion - abajo)
|