"""ETIQ-3 · impl. 1 · métricas por par (DEFINICIONES_PREVIAS_VINT2 §5-§6 y _E9 §3-§4), numpy. AUC por rangos medios; bootstrap por conglomerado de entidad (B = 2.000, PCG64, semilla 20261027 + crc32 del par); logística por IRLS con cresta 1e-4 (numpy.linalg.solve). Uso: python3 -I metricas_i1.py """ import csv, sys, math, zlib from collections import defaultdict import numpy as np PIEZA, BANCO, SCORES, ORG, OUT_CSV, OUT_MD = sys.argv[1:7] B = 2000 SEM = 20261027 IND9 = ['C1', 'C2', 'DOC4', 'M1r', 'M1e', 'M3', 'M2', 'M6', 'M4'] def fnum(x): return None if x in ('', None) else float(x) def auc_rangos(s, y): s = np.asarray(s, float); y = np.asarray(y, int) n1 = int(y.sum()); n0 = len(y) - n1 if n1 == 0 or n0 == 0: return None u, inv, cnt = np.unique(s, return_inverse=True, return_counts=True) cum = np.cumsum(cnt) r = (cum - (cnt - 1) / 2.0)[inv] return float((r[y == 1].sum() - n1 * (n1 + 1) / 2.0) / (n1 * n0)) def u_pares(s, y): """(victorias, pares) de Mann-Whitney dentro de un grupo.""" s = np.asarray(s, float); y = np.asarray(y, int) n1 = int(y.sum()); n0 = len(y) - n1 if n1 == 0 or n0 == 0: return 0.0, 0 u, inv, cnt = np.unique(s, return_inverse=True, return_counts=True) cum = np.cumsum(cnt) r = (cum - (cnt - 1) / 2.0)[inv] return float(r[y == 1].sum() - n1 * (n1 + 1) / 2.0), n1 * n0 def auc_estrat(s, y, est): gan = par = 0.0 est = np.asarray(est) for k in np.unique(est): m = est == k g, p = u_pares(np.asarray(s)[m], np.asarray(y)[m]) gan += g; par += p return (gan / par if par >= 30 else None), int(par) def logistica(X, y, cresta=1e-4, iters=100, tol=1e-8): n, p = X.shape b = np.zeros(p) R = np.eye(p) * cresta; R[0, 0] = 0 for _ in range(iters): eta = np.clip(X @ b, -35, 35) mu = 1 / (1 + np.exp(-eta)) w = mu * (1 - mu) H = (X * w[:, None]).T @ X + R g = X.T @ (y - mu) - R @ b try: d = np.linalg.solve(H, g) except np.linalg.LinAlgError: return None if not np.all(np.isfinite(d)): return None b = b + d if np.max(np.abs(d)) < tol: return b return None def or_aj(F, x): """F: diccionario de columnas (arrays) ya filtrado; x: el predictor (S1/10 o −log2(1+cob)).""" y = F['y'] if len(np.unique(y)) < 2: return None cols = [np.ones(len(y)), x, F['tam']] + F['dummies'] X = np.column_stack(cols) keep = [0, 1] + [j for j in range(2, X.shape[1]) if np.ptp(X[:, j]) > 0] b = logistica(X[:, keep], y.astype(float)) return None if b is None else float(math.exp(b[1])) def dummies(vals, base=None): u = sorted(set(vals)) base = u[0] if base is None else base return [np.array([1.0 if v == k else 0.0 for v in vals]) for k in u if k != base] def pct(a, q): a = sorted(v for v in a if v is not None) if not a: return None k = (len(a) - 1) * q lo, hi = math.floor(k), math.ceil(k) return a[lo] + (a[hi] - a[lo]) * (k - lo) def evaluar(rows, etiqueta, ind, papel, score='s1', minimo_el=20, criterio_d='s2v', extra=None): """rows: lista de dicts con nif, anio, y, s1, s2, v, n_el, tam, estrato, dummies-clave.""" fil = [r for r in rows if r['y'] is not None and r[score] is not None and r['n_el'] >= minimo_el] pos = [r for r in fil if r['y'] == 1]; neg = [r for r in fil if r['y'] == 0] res = {'pieza': PIEZA, 'etiqueta': etiqueta, 'ind': ind, 'papel': papel, 'n_pos': len(pos), 'n_neg': len(neg), 'ent_pos': len({r['nif'] for r in pos}), 'ent_neg': len({r['nif'] for r in neg})} if not pos or not neg: res['veredicto'] = 'NO EVALUABLE'; return res s = np.array([r[score] for r in fil]); y = np.array([r['y'] for r in fil]) res['auc'] = auc_rangos(s, y) res['auc_estrat'], res['pares_estrat'] = auc_estrat(s, y, [r['estrato'] for r in fil]) if extra: for nom, f in extra.items(): sub = [r for r in fil if f(r)] if sub: a, p = auc_estrat([r[score] for r in sub], [r['y'] for r in sub], [r['estrato'] for r in sub]) res[nom], res[nom + '_pares'] = a, p # covariables y bootstrap xs = (s / 10.0) if score == 's1' else s tam = np.array([r['tam'] for r in fil]) dm = [np.array(d) for d in DUMMIES(fil)] F = {'y': y, 'tam': tam, 'dummies': dm} res['or'] = or_aj(F, xs) por = defaultdict(list) for i, r in enumerate(fil): por[r['nif']].append(i) ents = sorted(por); idx = [np.array(por[e]) for e in ents] rng = np.random.default_rng([SEM, zlib.crc32(f'{PIEZA}|{etiqueta}|{ind}'.encode())]) A, O, fallos, k = [], [], 0, 0 while k < B: sel = np.concatenate([idx[j] for j in rng.integers(0, len(ents), len(ents))]) yy = y[sel] if yy.min() == yy.max(): continue k += 1 A.append(auc_rangos(s[sel], yy)) o = or_aj({'y': yy, 'tam': tam[sel], 'dummies': [d[sel] for d in dm]}, xs[sel]) if o is None: fallos += 1 else: O.append(o) res['ic_inf'], res['ic_sup'] = pct(A, 0.025), pct(A, 0.975) res['or_ic_inf'], res['or_ic_sup'], res['or_fallos'] = pct(O, 0.025), pct(O, 0.975), fallos if score == 's1': f2 = [r for r in fil if r['s2'] is not None] res['auc_s2'] = auc_rangos([r['s2'] for r in f2], [r['y'] for r in f2]) if f2 else None res['auc_v'] = auc_rangos([r['v'] for r in fil], [r['y'] for r in fil]) e1 = [r for r in rows if r['y'] is not None and r['s1'] is not None and r['n_el'] >= 1] res['auc_eleg1'] = auc_rangos([r['s1'] for r in e1], [r['y'] for r in e1]) dec = [r for r in fil if r['s1'] >= 90] res['decil_n'], res['decil_pos'] = len(dec), sum(r['y'] for r in dec) res['lift'] = (res['decil_pos'] / len(dec)) / (len(pos) / len(fil)) if dec else None ev = len(pos) >= 10 and len(neg) >= 10 and res['ent_pos'] >= 5 and res['ent_neg'] >= 5 if not ev: res['veredicto'] = 'NO EVALUABLE'; return res a = res['auc'] crit = {'a': a >= 0.65 and res['ic_inf'] > 0.55, 'b': res['auc_estrat'] is not None and res['auc_estrat'] >= 0.60, 'c': fallos <= 0.10 * B and res['or_ic_inf'] is not None and res['or_ic_inf'] > 1} if criterio_d == 's2v': crit['d'] = (res.get('auc_s2') or 0) >= 0.60 and (res.get('auc_v') or 0) >= 0.60 else: # COB: estratificada >= 0,60 en los dos periodos crit['d'] = (res.get('estrat_1721') or 0) >= 0.60 and (res.get('estrat_2224') or 0) >= 0.60 res['criterios'] = ''.join(k for k, v in crit.items() if v) nulo = (res['auc_estrat'] is not None and res['auc_estrat'] <= 0.55) if criterio_d == 'cob' else a <= 0.55 if all(crit.values()): res['veredicto'] = 'PASA' elif nulo: inv = (res['auc_estrat'] or 0.5) < 0.45 if criterio_d == 'cob' else a < 0.45 res['veredicto'] = 'NO PASA · nulo' + (' (invertido)' if inv else '') else: res['veredicto'] = 'NO PASA · no concluyente' if papel != 'principal': res['veredicto'] += f' [{papel}]' return res def leer_scores(): sc = defaultdict(dict) for r in csv.DictReader(open(SCORES)): sc[(r['nif'], int(r['anio']))][r['ind']] = (fnum(r['n_el']) or 0, fnum(r['v_dir']), fnum(r['s1_dir']), fnum(r['s2_dir'])) return sc res = [] if PIEZA == 'vint2': banco = list(csv.DictReader(open(BANCO), delimiter='\t')) sc = leer_scores() def DUMMIES(fil): return dummies([r['anio'] for r in fil], base=2022) def filas(etq, ind): out = [] for b in banco: yv = b[etq] if yv == '': continue t = sc.get((b['nif'], int(b['ejercicio'])), {}).get(ind) if t is None: continue out.append({'nif': b['nif'], 'anio': int(b['ejercicio']), 'y': int(yv), 'n_el': t[0], 'v': t[1], 's1': t[2], 's2': t[3], 'tam': math.log(int(b['poblacion'])), 'intensidad': float(b['intensidad'])}) # estrato: tercil de población entre las filas evaluadas (n_el >= 20 y S1) ev = sorted([r for r in out if r['s1'] is not None and r['n_el'] >= 20], key=lambda r: (r['tam'], r['nif'], r['anio'])) ter = {(r['nif'], r['anio']): min(2, 3 * i // len(ev)) for i, r in enumerate(ev)} if ev else {} for r in out: r['estrato'] = ter.get((r['nif'], r['anio']), -1) return out org = defaultdict(list) if ORG != '-': for r in csv.DictReader(open(ORG)): if r['s1_dir']: org[(r['nif'], int(r['anio']), r['ind'])].append(float(r['s1_dir'])) placebo = {} plan = [('y_ro', i, 'principal') for i in IND9] + [('y_rep', i, 'sensibilidad') for i in IND9] + \ [('y_omi', i, 'sensibilidad') for i in IND9] + [('y_roalta', i, 'exploratorio') for i in IND9] + \ [('y_ano', i, 'placebo') for i in IND9] + [('y_ro', 'M1a', 'exploratorio')] for etq, ind, papel in plan: fs = filas(etq, ind) r = evaluar(fs, etq, ind, papel) pos = [f for f in fs if f['y'] == 1 and f['s1'] is not None and f['n_el'] >= 20] if len(pos) >= 3 and etq != 'y_ano': xs = [f['s1'] for f in pos]; ys = [f['intensidad'] for f in pos] def rk(v): o = sorted(range(len(v)), key=lambda i: v[i]); rr = [0.0] * len(v); i = 0 while i < len(o): j = i while j + 1 < len(o) and v[o[j + 1]] == v[o[i]]: j += 1 for q in range(i, j + 1): rr[o[q]] = (i + j) / 2 + 1 i = j + 1 return rr a, b2 = rk(xs), rk(ys) ma, mb = sum(a) / len(a), sum(b2) / len(b2) den = math.sqrt(sum((x - ma) ** 2 for x in a) * sum((x - mb) ** 2 for x in b2)) r['spearman_intensidad'] = sum((x - ma) * (z - mb) for x, z in zip(a, b2)) / den if den else None oo = [(sv, int(b[etq])) for b in banco if b[etq] != '' for sv in org.get((b['nif'], int(b['ejercicio']), ind), [])] if oo: r['auc_organo'] = auc_rangos([o[0] for o in oo], [o[1] for o in oo]) r['n_organo_pos'] = sum(o[1] for o in oo); r['n_organo_neg'] = len(oo) - r['n_organo_pos'] res.append(r) if etq == 'y_ano': placebo[ind] = r # criterio (e): placebo ANO dentro de [0,40, 0,60] si es evaluable for r in res: if r['etiqueta'] == 'y_ro' and r['papel'] == 'principal' and r.get('veredicto') == 'PASA': p = placebo.get(r['ind']) if p and p['veredicto'] != 'NO EVALUABLE' and not (0.40 <= (p.get('auc') or 0.5) <= 0.60): r['veredicto'] = 'NO PASA · no concluyente (placebo fuera de rango)' else: # e9 banco = list(csv.DictReader(open(BANCO))) # e9_cob_i1.csv (CSV con N) sc = leer_scores() def DUMMIES(fil): return dummies([r['anio'] for r in fil]) + dummies([r['ca'] for r in fil], base='01') def base_row(b, etq): yv = b[etq] if yv in ('', None): return None p = int(b['poblacion']) if b['poblacion'] else None if not p: return None return {'nif': b['nif'], 'anio': int(b['ejercicio']), 'y': int(float(yv)), 'tam': math.log(p), 'pob': p, 'estrato': f"{b['tramo']}|{b['cod_ca']}|{b['ejercicio']}", 'ca': b['cod_ca'], 'tramo': b['tramo'], 'n': int(b['n']), 'n_sin_placsp': int(b['n_sin_placsp'])} def filas_ind(etq, ind): out = [] for b in banco: if int(b['ejercicio']) < 2019: continue r = base_row(b, etq) t = sc.get((b['nif'], int(b['ejercicio'])), {}).get(ind) if r else None if t is None: continue r.update({'n_el': t[0], 'v': t[1], 's1': t[2], 's2': t[3]}) out.append(r) return out def filas_cob(etq, col='n', anios=(2017, 2024)): out = [] for b in banco: if not (anios[0] <= int(b['ejercicio']) <= anios[1]): continue r = base_row(b, etq) if r is None: continue cob = 1000.0 * r[col] / r['pob'] r.update({'n_el': 1e9, 'cob': cob, 'x': -math.log2(1 + cob), 'v': -cob, 's1': None, 's2': None}) out.append(r) return out per = {'estrat_1721': lambda r: r['anio'] <= 2021, 'estrat_2224': lambda r: r['anio'] >= 2022} plan = [('y_nr', i, 'principal') for i in ('C1', 'C2', 'DOC4')] + [('y_nr', i, 'exploratorio') for i in ('M1r', 'M1e', 'M3', 'M2', 'M6', 'M4')] + \ [('y_nrstar', i, 'sensibilidad') for i in ('C1', 'C2', 'DOC4')] + [('y_rep', i, 'exploratorio') for i in ('C1', 'C2', 'DOC4')] for etq, ind, papel in plan: res.append(evaluar(filas_ind(etq, ind), etq, ind, papel)) for etq, col, anios, nom, papel in [('y_nr', 'n', (2017, 2024), 'COB', 'principal'), ('y_nrstar', 'n', (2017, 2024), 'COB', 'sensibilidad'), ('y_rep', 'n', (2017, 2024), 'COB', 'exploratorio'), ('y_nr', 'n_sin_placsp', (2017, 2024), 'COB_sin_PLACSP', 'sensibilidad'), ('y_nr', 'n', (2017, 2021), 'COB_2017_2021', 'sensibilidad')]: fs = filas_cob(etq, col, anios) for r in fs: r['s'] = r['x'] # −log2(1 + cob): más alto = menos cobertura r = evaluar([dict(f, s1=None) | {'sx': f['x']} for f in fs], etq, nom, papel, score='sx', minimo_el=0, criterio_d='cob', extra=per) # descriptivo: publica algo por tramo y RR de Mantel-Haenszel t = defaultdict(lambda: [0, 0, 0, 0]) # a = NR y publica, n1 = NR, c = neg y publica, n0 = neg for f in fs: k = f['tramo'] if f['y'] == 1: t[k][1] += 1; t[k][0] += f[col] >= 1 else: t[k][3] += 1; t[k][2] += f[col] >= 1 num = sum(a * n0 / (n1 + n0) for a, n1, c, n0 in t.values() if n1 + n0) den = sum(c * n1 / (n1 + n0) for a, n1, c, n0 in t.values() if n1 + n0) r['rr_mh_publica'] = num / den if den else None r['publica_por_tramo'] = '; '.join(f"{k}: {a}/{n1} vs {c}/{n0}" for k, (a, n1, c, n0) in sorted(t.items())) res.append(r) campos = ['pieza', 'etiqueta', 'ind', 'papel', 'n_pos', 'n_neg', 'ent_pos', 'ent_neg', 'auc', 'ic_inf', 'ic_sup', 'auc_estrat', 'pares_estrat', 'estrat_1721', 'estrat_2224', 'or', 'or_ic_inf', 'or_ic_sup', 'or_fallos', 'auc_s2', 'auc_v', 'auc_eleg1', 'decil_n', 'decil_pos', 'lift', 'spearman_intensidad', 'auc_organo', 'n_organo_pos', 'n_organo_neg', 'rr_mh_publica', 'publica_por_tramo', 'criterios', 'veredicto'] with open(OUT_CSV, 'w', newline='') as fh: w = csv.DictWriter(fh, campos, extrasaction='ignore'); w.writeheader() for r in res: w.writerow({k: (f'{r[k]:.6f}' if isinstance(r.get(k), float) else r.get(k, '')) for k in campos}) def f3(x, d=3): return '—' if x is None else f'{x:.{d}f}'.replace('.', ',') with open(OUT_MD, 'w') as fh: fh.write(f'# ETIQ-3 · {PIEZA} · impl. 1 · métricas por par (IC 95 % por conglomerado de entidad, B = 2.000)\n\n') fh.write('| Etiqueta | Ind. | Papel | pos/neg (ent.) | AUC [IC 95 %] | estrat. (pares) | OR aj. [IC] (fallos) | S2 | V | extra | Veredicto |\n|---|---|---|---|---|---|---|---|---|---|---|\n') for r in res: extra = (f"1721 {f3(r.get('estrat_1721'))} · 2224 {f3(r.get('estrat_2224'))} · RR publica {f3(r.get('rr_mh_publica'), 2)}" if r['ind'].startswith('COB') else f"ρ {f3(r.get('spearman_intensidad'), 2)} · órg. {f3(r.get('auc_organo'))} · lift {f3(r.get('lift'), 2)} ({r.get('decil_pos', '—')}/{r.get('decil_n', '—')})") fh.write(f"| {r['etiqueta']} | {r['ind']} | {r['papel']} | {r['n_pos']}/{r['n_neg']} ({r['ent_pos']}/{r['ent_neg']}) | {f3(r.get('auc'))} " f"[{f3(r.get('ic_inf'))}, {f3(r.get('ic_sup'))}] | {f3(r.get('auc_estrat'))} ({r.get('pares_estrat', '—')}) | " f"{f3(r.get('or'), 2)} [{f3(r.get('or_ic_inf'), 2)}, {f3(r.get('or_ic_sup'), 2)}] ({r.get('or_fallos', '—')}) | {f3(r.get('auc_s2'))} | " f"{f3(r.get('auc_v'))} | {extra} | {r['veredicto']} |\n") print('pares', len(res))