"""BU1 · 40 · validaciones (a) y (b) (DEFINICIONES_PREVIAS §7). Imagen report-worker. Escribe salidas/40_validaciones.json.""" import sys, json, math, time sys.path.insert(0, '/w/py') import numpy as np, pyarrow.parquet as pq from comun import ajuste, boot_auc, or_woolf, NB, NMIN, SEM T0 = time.time() def log(*a): print(f"[{time.time()-T0:6.1f}s]", *a, flush=True) R = {} # (a) estabilidad ob = pq.read_table('/w/interno/organo_bloque.parquet').to_pylist() idx = {(r['organo_clave'], r['bloque'], r['grupo']): r for r in ob} for g in ('SS', 'O'): pares = [] for (o, b, gg), r in idx.items(): if b == 'B1' and gg == g and r['n_v'] >= NMIN and r['posicion'] in ('hecho', 'sin hecho'): r2 = idx.get((o, 'B2', g)) if r2 and r2['n_v'] >= NMIN and r2['posicion'] in ('hecho', 'sin hecho'): pares.append((o, r, r2)) t = [sum(1 for o, a, b in pares if (a['posicion'] == 'hecho') == p1 and (b['posicion'] == 'hecho') == p2) for p1, p2 in ((1, 1), (1, 0), (0, 1), (0, 0))] if sum(t): o_, lo, hi = or_woolf(*t) ver = 'pasa' if lo > 2 and t[0] + t[1] >= 30 else ('cota' if lo > 1 else 'no pasa') un = [(o, a['X'], int(b['posicion'] == 'hecho')) for o, a, b in pares] R[f'a_{g}'] = {'tabla_B1si_B2si,B1si_B2no,B1no_B2si,B1no_B2no': t, 'organos_ambos': len(pares), 'OR': o_, 'ic95': [lo, hi], 'P_B2_si_B1': t[0] / (t[0] + t[1]) if t[0] + t[1] else None, 'P_B2_no_B1': t[2] / (t[2] + t[3]) if t[2] + t[3] else None, 'veredicto': ver, 'auc_XB1_hechoB2': boot_auc(un) if 0 < sum(u[2] for u in un) < len(un) else None, 'correlacion_logX': float(np.corrcoef([math.log(a['X']) for o, a, b in pares if a['X'] > 0 and b['X'] > 0], [math.log(b['X']) for o, a, b in pares if a['X'] > 0 and b['X'] > 0])[0, 1]) if len(pares) > 2 else None} else: R[f'a_{g}'] = {'organos_ambos': 0} log('a', g, R[f'a_{g}']) # bins SS por órgano-año bins = [r for r in pq.read_table('/w/interno/bins.parquet').to_pylist() if r['esquema'] == 'u' and r['grupo'] == 'SS'] oa = {} for r in bins: e = oa.setdefault((r['organo_clave'], r['anio']), [[0] * NB, [0] * NB]); e[0][r['b']] += r['c']; e[1][r['b']] += r['c_all'] pub = {(r['organo_clave'], r['anio']): r for r in pq.read_table('/w/interno/organo_anio.parquet').to_pylist() if r['grupo'] == 'SS'} def suma(claves): c = [0] * NB; ca = [0] * NB for k in claves: if k in oa: for b in range(NB): c[b] += oa[k][0][b]; ca[b] += oa[k][1][b] return c, ca # (b1) P6 banco = [r for r in pq.read_table('/et/p6/salidas/banco_entidades.parquet').to_pylist() if r['etiqueta'] in ('positivo', 'negativo') and 2019 <= r['anio'] <= 2025] org_ent = {} for r in pq.read_table('/d/unified_20261018.identidad/organos.parquet', columns=['organo_clave', 'entidad_clave']).to_pylist(): if r['entidad_clave']: org_ent.setdefault(r['entidad_clave'], set()).add(r['organo_clave']) un, binr, desc = [], [], {'positivo': [0, 0, 0], 'negativo': [0, 0, 0]} for r in banco: ks = [(o, r['anio']) for o in org_ent.get(r['entidad_clave'], ())] c, ca = suma(ks); nv = sum(ca) if nv < 50: continue O, E, X, _ = ajuste(c) if not E > 0: continue y = int(r['etiqueta'] == 'positivo'); un.append((r['entidad_clave'], X, y)) hecho = any(pub.get(k, {}).get('posicion') == 'hecho' for k in ks) binr.append((y, hecho)); d = desc[r['etiqueta']]; d[0] += 1; d[1] += O; d[2] += E R['b1_banco'] = {'entidad_anio_banco': len(banco), 'con_n50': len(un)} R['b1_auc'] = boot_auc(un) if len(un) >= 10 and 0 < sum(u[2] for u in un) < len(un) else {'no_evaluable': len(un)} mk = [y for y, h in binr if h]; base = sum(y for y, h in binr) / len(binr) if binr else None R['b1_bin'] = {'unidades': len(binr), 'marcadas': len(mk), 'positivas_marcadas': sum(mk), 'precision': sum(mk) / len(mk) if mk else None, 'base': base, 'lift': (sum(mk) / len(mk)) / base if mk and base else None} R['b1_O_E_agregado'] = {k: {'unidades': v[0], 'O': v[1], 'E': v[2], 'X': v[1] / v[2] if v[2] else None} for k, v in desc.items()} log('b1', R['b1_banco'], R['b1_auc'], R['b1_bin'], R['b1_O_E_agregado']) # (b2) E-M2b et = [r for r in pq.read_table('/et/redflags_comunes/interno/et_u.parquet').to_pylist() if r['etiqueta'] == 'EM2B'] porg = {} for r in et: e = porg.setdefault(r['conglo'], [0, 0, 0]); e[0] = max(e[0], r['y']); e[1] += r['y'] if r['tipo_unidad'] == 'serie' else 0; e[2] += 1 un2, dd = [], {1: [0, 0, 0], 0: [0, 0, 0]} for o, (y, nser, nu) in porg.items(): c, ca = suma([(o, a) for a in range(2020, 2025)]); nv = sum(ca) if nv < 50: continue O, E, X, _ = ajuste(c) if not E > 0: continue un2.append((o, X, y)) R['b2_organos_et_u'] = len(porg); R['b2_con_n50'] = len(un2) R['b2_auc'] = boot_auc(un2) if len(un2) >= 10 else {'no_evaluable': len(un2)} # secundario: series EM2b por 1.000 menores (todas las filas SS 2020-2024 del órgano en M, contadas en m? -> se usa n en [0,7u,u)) hecho_org = {o for (o, a), r in pub.items() if r['posicion'] == 'hecho' and 2020 <= a <= 2024} for o, (y, nser, nu) in porg.items(): c, ca = suma([(o, a) for a in range(2020, 2025)]); nv = sum(ca) if nv < NMIN: continue g = 1 if o in hecho_org else 0; dd[g][0] += 1; dd[g][1] += nser; dd[g][2] += nv R['b2_series_por_1000_en_ventana30'] = {('con hecho' if g else 'sin hecho'): {'organos': v[0], 'series_em2b': v[1], 'n_v': v[2], 'por_1000': 1000 * v[1] / v[2] if v[2] else None} for g, v in dd.items()} log('b2', R['b2_organos_et_u'], R['b2_con_n50'], R['b2_auc'], R['b2_series_por_1000_en_ventana30']) json.dump(R, open('/w/salidas/40_validaciones.json', 'w'), ensure_ascii=False, indent=1, default=str)