"""ETIQ-3 · E9 · impl. 2 (variante vectorizada, mismo diseño que metricas_i2.py: banco y N de la impl. 2, AUC por recuento de pares con searchsorted, logística por Newton con Cholesky y sustituciones propias, remuestreo con random.Random). Existe porque la versión en Python puro tarda horas con 53.000 filas y 2.000 réplicas. Uso: python3 -I metricas_i2_e9np.py """ import csv, sys, math, random from collections import defaultdict import numpy as np BAN, PUB, SC, OUT = sys.argv[1:5] B = 2000 def auc_pares(s, y): pos, neg = s[y == 1], np.sort(s[y == 0]) if len(pos) == 0 or len(neg) == 0: return None, 0.0, 0 lo = np.searchsorted(neg, pos, side='left'); hi = np.searchsorted(neg, pos, side='right') g = float(lo.sum() + 0.5 * (hi - lo).sum()) return g / (len(pos) * len(neg)), g, len(pos) * len(neg) def estrat(s, y, e): g = n = 0.0 orden = np.argsort(e, kind='stable'); e2 = e[orden] cortes = np.flatnonzero(np.r_[True, e2[1:] != e2[:-1], True]) for a, b in zip(cortes[:-1], cortes[1:]): idx = orden[a:b] _, gg, nn = auc_pares(s[idx], y[idx]); g += gg; n += nn return (g / n if n >= 30 else None), int(n) def chol_solve(H, g): try: L = np.linalg.cholesky(H) except np.linalg.LinAlgError: return None n = len(g); z = np.zeros(n); x = np.zeros(n) for i in range(n): z[i] = (g[i] - L[i, :i] @ z[:i]) / L[i, i] for i in reversed(range(n)): x[i] = (z[i] - L[i + 1:, i] @ x[i + 1:]) / L[i, i] return x def newton(X, y, cresta=1e-4): keep = [0, 1] + [j for j in range(2, X.shape[1]) if X[:, j].min() != X[:, j].max()] X = X[:, keep]; p = X.shape[1]; b = np.zeros(p) for _ in range(100): m = 1 / (1 + np.exp(-np.clip(X @ b, -35, 35))) g = X.T @ (y - m); H = (X * (m * (1 - m))[:, None]).T @ X H[np.arange(1, p), np.arange(1, p)] += cresta; g[1:] -= cresta * b[1:] d = chol_solve(H, g) if d is None or not np.all(np.isfinite(d)): return None b = b + d if np.max(np.abs(d)) < 1e-8: return math.exp(b[1]) return None def cuantil(v, q): v = sorted(x for x in v if x is not None) k = (len(v) - 1) * q; i = int(math.floor(k)); j = min(i + 1, len(v) - 1) return v[i] + (v[j] - v[i]) * (k - i) def medir(F, et, ind, cob): y = np.array([f['y'] for f in F]); s = np.array([f['s'] for f in F], float); x = np.array([f['x'] for f in F], float) est = np.array([f['estrato'] for f in F]); ent = [f['nif'] for f in F] anios = sorted({f['anio'] for f in F}); cas = sorted({f['ca'] for f in F}) X = np.column_stack([np.ones(len(F)), x, [f['tam'] for f in F]] + [[1.0 if f['anio'] == a else 0.0 for f in F] for a in anios[1:]] + [[1.0 if f['ca'] == c else 0.0 for f in F] for c in cas if c != '01']) r = {'etiqueta': et, 'ind': ind, 'n_pos': int(y.sum()), 'n_neg': int(len(y) - y.sum()), 'ent_pos': len({e for e, v in zip(ent, y) if v == 1}), 'ent_neg': len({e for e, v in zip(ent, y) if v == 0})} r['auc'] = auc_pares(s, y)[0] r['auc_estrat'], r['pares_estrat'] = estrat(s, y, est) if cob: a = np.array([f['anio'] for f in F]) r['estrat_1721'] = estrat(s[a <= 2021], y[a <= 2021], est[a <= 2021])[0] r['estrat_2224'] = estrat(s[a >= 2022], y[a >= 2022], est[a >= 2022])[0] r['or'] = newton(X, y.astype(float)) por = defaultdict(list) for i, e in enumerate(ent): por[e].append(i) ents = sorted(por); idx = [np.array(por[e]) for e in ents] rng = random.Random(f'20261027|e9|{et}|{ind}|impl2') A, O, fallos, k = [], [], 0, 0 while k < B: sel = np.concatenate([idx[rng.randrange(len(ents))] for _ in ents]) yy = y[sel] if yy.min() == yy.max(): continue k += 1 A.append(auc_pares(s[sel], yy)[0]) o = newton(X[sel], yy.astype(float)) if o is None: fallos += 1 else: O.append(o) r.update({'ic_inf': cuantil(A, 0.025), 'ic_sup': cuantil(A, 0.975), 'or_ic_inf': cuantil(O, 0.025), 'or_ic_sup': cuantil(O, 0.975), 'or_fallos': fallos}) if not cob: m2 = np.array([f['s2'] is not None for f in F]) r['auc_s2'] = auc_pares(np.array([f['s2'] for f in F if f['s2'] is not None], float), y[m2])[0] r['auc_v'] = auc_pares(np.array([f['v'] for f in F], float), y)[0] ev = r['n_pos'] >= 10 and r['n_neg'] >= 10 and r['ent_pos'] >= 5 and r['ent_neg'] >= 5 if not ev: r['veredicto'] = 'NO EVALUABLE'; return r ok = [r['auc'] >= 0.65 and r['ic_inf'] > 0.55, r['auc_estrat'] is not None and r['auc_estrat'] >= 0.60, fallos <= 200 and r['or_ic_inf'] > 1] if cob: ok.append((r['estrat_1721'] or 0) >= 0.60 and (r['estrat_2224'] or 0) >= 0.60) nulo, inv = r['auc_estrat'] is not None and r['auc_estrat'] <= 0.55, (r['auc_estrat'] or 0.5) < 0.45 else: ok.append((r['auc_s2'] or 0) >= 0.60 and (r['auc_v'] or 0) >= 0.60) nulo, inv = r['auc'] <= 0.55, r['auc'] < 0.45 r['veredicto'] = 'PASA' if all(ok) else ('NO PASA · nulo' + (' (invertido)' if inv else '') if nulo else 'NO PASA · no concluyente') print(et, ind, r['n_pos'], r['n_neg'], round(r['auc'], 4), r['veredicto'], flush=True) return r pub = {(r['nif'], int(r['anio'])): r for r in csv.DictReader(open(PUB))} banco = list(csv.DictReader(open(BAN), delimiter='\t')) sc = {} for r in csv.DictReader(open(SC)): g = lambda c: float(r[c]) if r[c] != '' else None sc[(r['nif'], int(r['anio']), r['ind'])] = (float(r['n_el']), g('v_dir'), g('s1_dir'), g('s2_dir')) def base(b, et): if b[et] in ('', 'None') or b['poblacion'] in ('', 'None'): return None p = int(b['poblacion']) return {'nif': b['nif'], 'anio': int(b['ejercicio']), 'y': int(b[et]), 'tam': math.log(p), 'pob': p, 'ca': b['cod_ca'], 'estrato': f"{b['tramo']}|{b['cod_ca']}|{b['ejercicio']}"} salida = [] for et, ind in [('y_nr', i) for i in ('C1', 'C2', 'DOC4', 'M1r', 'M1e', 'M3', 'M2', 'M6', 'M4')] + [('y_nrstar', i) for i in ('C1', 'C2', 'DOC4')] + [('y_rep', i) for i in ('C1', 'C2', 'DOC4')]: F = [] for b in banco: if int(b['ejercicio']) < 2019: continue f = base(b, et) t = sc.get((b['nif'], int(b['ejercicio']), ind)) if f else None if t is None or t[2] is None or t[0] < 20: continue f.update({'s': t[2], 's2': t[3], 'v': t[1], 'x': t[2] / 10}); F.append(f) salida.append(medir(F, et, ind, False)) for et, col, a0, a1, nom in [('y_nr', 'n', 2017, 2024, 'COB'), ('y_nrstar', 'n', 2017, 2024, 'COB'), ('y_rep', 'n', 2017, 2024, 'COB'), ('y_nr', 'sin', 2017, 2024, 'COB_sin_PLACSP'), ('y_nr', 'n', 2017, 2021, 'COB_2017_2021')]: F = [] for b in banco: if not (a0 <= int(b['ejercicio']) <= a1): continue f = base(b, et) if f is None: continue pr = pub.get((b['nif'], int(b['ejercicio']))) n = (int(pr['n']) - int(pr['n_placsp'])) if (pr and col == 'sin') else (int(pr['n']) if pr else 0) f['x'] = -math.log2(1 + 1000.0 * n / f['pob']); f['s'] = f['x']; F.append(f) salida.append(medir(F, et, nom, True)) campos = ['etiqueta', 'ind', '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', 'veredicto'] with open(OUT, 'w', newline='') as fh: w = csv.DictWriter(fh, campos, extrasaction='ignore'); w.writeheader() for r in salida: w.writerow({k: (f'{r[k]:.6f}' if isinstance(r.get(k), float) else r.get(k, '')) for k in campos}) print('ok', len(salida))