"""CO1 · 20 · medida (impl1, Python puro): AUC por comparación de pares dentro de la red, bootstrap, dejar un mercado fuera.""" import json, random, statistics as stt import pyarrow.parquet as pq g = pq.read_table('/w/interno/10_grupos.parquet').to_pylist() SEED, NB = 20261022, 2000 def estr(k): for lim, lab in ((2, '2'), (3, '3'), (5, '4-5'), (10, '6-10'), (20, '11-20'), (50, '21-50')): if k <= lim: return lab return '>50' def sel(var='A', met='louvain', sd=20261022): return [r for r in g if r['var'] == var and r['metodo'] == met and r['semilla'] == sd and r['red'].split('|')[0] != 'SAMUR/01/24'] def unidades(rows, key='S', emparejado=False): """Una unidad por positivo: (exp, cpv2, red, fracción de controles de su red [y estrato] con key menor).""" ctrl = {} for r in rows: if r['clase'] == 'ctrl': ctrl.setdefault((r['red'], estr(r['k']) if emparejado else None), []).append(r[key]) out = [] for r in rows: if r['clase'] != 'pos': continue cs = ctrl.get((r['red'], estr(r['k']) if emparejado else None), []) if not cs: continue f = sum(1.0 if c < r[key] else (0.5 if c == r[key] else 0.0) for c in cs) / len(cs) out.append(dict(exp=r['exp'], cpv2=r['cpv2'], red=r['red'], f=f, k=r['k'], n_ctrl=len(cs), S=r[key])) return out def auc(us): return sum(u['f'] for u in us) / len(us) if us else None def boot(us): rng = random.Random(SEED); exps = sorted({u['exp'] for u in us}); byexp = {e: [u for u in us if u['exp'] == e] for e in exps} a1, a2 = [], [] for _ in range(NB): s = [u for e in (rng.choice(exps) for _ in exps) for u in byexp[e]]; a1.append(auc(s)) s = [rng.choice(us) for _ in us]; a2.append(auc(s)) q = lambda a: (sorted(a)[int(0.025 * NB)], sorted(a)[int(0.975 * NB) - 1]) i1, i2 = q(a1), q(a2) return dict(ic_expediente=i1, ic_positivo=i2, li=min(i1[0], i2[0]), ls=max(i1[1], i2[1])) R = {} base = sel('A') cnt = {c: sum(1 for r in base if r['clase'] == c) for c in ('pos', 'ctrl', 'fuera')} R['recuento_A'] = cnt R['recuento_A_por_red'] = {} for red in sorted({r['red'] for r in base}): rr = [r for r in base if r['red'] == red] R['recuento_A_por_red'][red] = dict(grupos=len(rr), pos=sum(r['clase'] == 'pos' for r in rr), ctrl=sum(r['clase'] == 'ctrl' for r in rr), fuera=sum(r['clase'] == 'fuera' for r in rr), tam_pos=[r['k'] for r in rr if r['clase'] == 'pos'], sanc_en_pos=sum(r['n_sanc_exp'] for r in rr if r['clase'] == 'pos'), sanc_en_grupos=sum(r['n_sanc_exp'] for r in rr)) U = unidades(base); R['AUC_A'] = dict(auc=auc(U), n_pos=len(U), **boot(U)) Ue = unidades(base, emparejado=True); R['AUC_A_emparejado'] = dict(auc=auc(Ue), n_pos=len(Ue), **(boot(Ue) if len(Ue) > 1 else {})) for key in ('C', 'E'): u = unidades(base, key); R[f'AUC_A_{key}'] = dict(auc=auc(u), n_pos=len(u), **boot(u)) u = unidades(base, key, True); R[f'AUC_A_{key}_emparejado'] = dict(auc=auc(u), n_pos=len(u)) b = sel('B'); R['recuento_B'] = {c: sum(1 for r in b if r['clase'] == c) for c in ('pos', 'ctrl', 'fuera')} u = unidades(b); R['AUC_B'] = dict(auc=auc(u), n_pos=len(u), **(boot(u) if len(u) > 1 else {})) u = unidades(b, emparejado=True); R['AUC_B_emparejado'] = dict(auc=auc(u), n_pos=len(u)) for met, sd in (('louvain', 1), ('louvain', 2), ('lpa', 20261022)): rr = sel('A', met, sd); u = unidades(rr); ue = unidades(rr, emparejado=True) R[f'sens_{met}{sd}'] = dict(auc=auc(u), n_pos=len(u), auc_emparejado=auc(ue), n_pos_emp=len(ue)) R['por_expediente'] = {e: dict(auc=auc([x for x in U if x['exp'] == e]), n=sum(1 for x in U if x['exp'] == e), auc_emp=auc([x for x in Ue if x['exp'] == e]), n_emp=sum(1 for x in Ue if x['exp'] == e)) for e in sorted({x['exp'] for x in U})} R['por_red'] = {red: dict(auc=auc([x for x in U if x['red'] == red]), n=sum(1 for x in U if x['red'] == red)) for red in sorted({x['red'] for x in U})} R['dejar_mercado_fuera'] = {m: dict(auc=auc([x for x in U if x['cpv2'] != m]), n=sum(1 for x in U if x['cpv2'] != m)) for m in ('15', '33', '34', '35', '45', '50', '71', '72')} R['dejar_expediente_fuera'] = {e: dict(auc=auc([x for x in U if x['exp'] != e]), n=sum(1 for x in U if x['exp'] != e)) for e in sorted({x['exp'] for x in U})} R['positivos'] = sorted([(x['red'], x['k'], round(x['f'], 4), x['n_ctrl']) for x in U]) # tamaño: positivos frente a controles ks_pos = [r['k'] for r in base if r['clase'] == 'pos']; ks_c = [r['k'] for r in base if r['clase'] == 'ctrl'] R['tamanos'] = dict(pos_mediana=stt.median(ks_pos) if ks_pos else None, ctrl_mediana=stt.median(ks_c), pos=sorted(ks_pos)) R['fallo'] = json.load(open('/w/interno/10_fallo.json')) # veredicto a = R['AUC_A']; lomo = min(v['auc'] for v in R['dejar_mercado_fuera'].values() if v['auc'] is not None) c1 = a['li'] > 0.60; c2 = (R['AUC_A_emparejado']['auc'] or 0) >= 0.60; c3 = lomo >= 0.55 v = 'PASA' if (c1 and c2 and c3) else ('COTA' if a['auc'] >= 0.60 else 'NO PASA') if a['n_pos'] < 10 and v == 'PASA': v = 'COTA' R['veredicto'] = dict(c_i=c1, c_ii=c2, c_iii=c3, lomo_min=lomo, veredicto=v) json.dump(R, open('/w/interno/20_res.json', 'w'), indent=1, ensure_ascii=False) print(json.dumps({k: R[k] for k in R if k not in ('positivos', 'fallo', 'recuento_A_por_red')}, indent=1, ensure_ascii=False))