"""MK1 · 20 · validación (a) contra cárteles y (b) estabilidad (DEFINICIONES_PREVIAS §5-6). Principal.""" import json, sys, time import numpy as np, pandas as pd, pyarrow.parquet as pq sys.path.insert(0, '/w/py'); from comun import prepara, auc_w T0 = time.time(); NB = 2000 def log(*a): print(f"[{time.time()-T0:6.0f}s]", *a, flush=True) U = pd.read_parquet('/w/interno/unidades.parquet') LU = pd.read_parquet('/w/interno/lote_unidad.parquet') TO = pq.read_table('/w/interno/lotes.parquet', columns=['lote_key', 'tipo_organo']).to_pandas() lab = pd.read_parquet('/w/interno/lab.parquet'); gris = set(pd.read_parquet('/w/interno/gris.parquet').lote_key) labk = lab.sort_values('exp').groupby('lote_key').agg(exp=('exp', 'first'), v3=('var', lambda s: 'V3' in set(s))).reset_index() SUB = ['o1_D', 'o1b_D', 'o2a_D', 'o2b_D', 'o3_D', 'o4a_D', 'o4b_D']; SC = ['S1', 'S2', 'S3', 'S4']; ALL = ['C'] + SC + SUB X = LU.merge(TO, on='lote_key').merge(labk, on='lote_key', how='left').merge(U[['unidad'] + ALL], on='unidad', how='left') X['y'] = X.exp.notna(); X['gris'] = X.lote_key.isin(gris) & ~X.y X['estrato'] = X.cpv_div + '|' + X.anio.astype(str) R = {'positivos_universo': int(X.y.sum()), 'positivos_con_C': int((X.y & X.C.notna()).sum()), 'positivos_por_exp': X[X.y].groupby('exp').agg(lotes=('y', 'size'), con_C=('C', 'count')).to_dict('index')} log('positivos', R['positivos_universo'], 'con C', R['positivos_con_C']) rng = np.random.default_rng(20261022) def evalua(df, score, estr='estrato', clus_exp='exp', nivel=0.95, por_exp=True): d = df[(df.y | ~df.gris) & df[score].notna()].copy() S = prepara(d[score].values, d.y.values, d[estr].values, d.organo_clave.values) P = S['P']; pexp = d[d.y].set_index(d[d.y].index) # alineado con orden de prepara: P en orden de d[d.y] filtrado por estrato # P conserva el orden de aparición de positivos en d (filtrados por estrato con positivos, que son todos) exps = d.loc[d.y, clus_exp].values a = auc_w(S); out = {'auc': a, 'n_pos': int(len(S['pe'])), 'n_ctrl': int(S['N0'].sum()), 'n_estratos': S['nest']} if len(S['pe']) == 0: return out q = ((1 - nivel) / 2 * 100, (1 + nivel) / 2 * 100) ue = sorted(set(exps)); ie = np.array([ue.index(e) for e in exps]) be = [] for _ in range(NB): k = np.bincount(rng.integers(0, len(ue), len(ue)), minlength=len(ue)); be.append(auc_w(S, wp=k[ie].astype(float))) orgs = S['orgs']; allorg = pd.Index(sorted(set(orgs) | set(S['po']))); jo = allorg.get_indexer(orgs); jp = allorg.get_indexer(S['po']) bo = [] for _ in range(NB): k = np.bincount(rng.integers(0, len(allorg), len(allorg)), minlength=len(allorg)).astype(float) bo.append(auc_w(S, wp=k[jp], wo=k[jo])) ce = np.nanpercentile(be, q); co = np.nanpercentile(bo, q) out.update({'ic_exp': ce.round(3).tolist(), 'ic_org': co.round(3).tolist(), 'ic': [round(min(ce[0], co[0]), 3), round(max(ce[1], co[1]), 3)], 'nivel': nivel}) if por_exp: out['por_exp'] = {e: {'auc': auc_w(S, wp=(ie == i).astype(float)), 'n': int((ie == i).sum())} for i, e in enumerate(ue)} out['dejar_uno_fuera'] = {e: auc_w(S, wp=(ie != i).astype(float)) for i, e in enumerate(ue)} v = [x['auc'] for x in out['por_exp'].values() if x['n'] >= 10 and not np.isnan(x['auc'])] out['mediana_por_exp_n10'] = float(np.median(v)) if v else np.nan out['min_dejar_uno_fuera'] = float(np.nanmin(list(out['dejar_uno_fuera'].values()))) return out # (a) lote LOTE = {} for s in ALL: LOTE[s] = evalua(X, s, nivel=0.95 if s == 'C' else 0.99, por_exp=(s in ['C'] + SC)); log('lote', s, round(LOTE[s]['auc'], 3), LOTE[s].get('ic')) # sensibilidades X['estrato_t'] = X.estrato + '|' + X.tipo_organo SENS = {'estrato_tipo_organo': evalua(X, 'C', estr='estrato_t', por_exp=False), 'solo_V3': evalua(X[~X.y | X.v3.fillna(False)], 'C', por_exp=True)} log('sens', {k: (round(v['auc'], 3), v.get('ic')) for k, v in SENS.items()}) # unidad: pertenencia por ventana completa lk = X[['lote_key', 'organo_clave', 'cpv_div', 'anio', 'y', 'gris', 'exp']] rows = [] for t in range(2014, 2026): w = lk[(lk.anio >= t - 2) & (lk.anio <= t)] g = w.groupby(['organo_clave', 'cpv_div']).agg(npos=('y', 'sum'), ngris=('gris', 'sum'), exp=('exp', lambda s: s.dropna().value_counts().index[0] if s.notna().any() else None)).reset_index() g['t'] = t; rows.append(g) UL = pd.concat(rows); UL['unidad'] = UL.organo_clave + '|' + UL.cpv_div + '|' + UL.t.astype(str) UU = U.merge(UL[['unidad', 'npos', 'ngris', 'exp']], on='unidad', how='left') UU['y'] = UU.npos >= 2; UU['gris'] = ~UU.y & ((UU.npos > 0) | (UU.ngris > 0)); UU['estrato'] = UU.cpv_div + '|' + UU.t.astype(str) UNI = {} for s in ['C'] + SC: UNI[s] = evalua(UU, s, nivel=0.95 if s == 'C' else 0.99, por_exp=False); log('unidad', s, round(UNI[s]['auc'], 3), UNI[s].get('ic'), UNI[s]['n_pos']) # veredicto por puntuación def veredicto(s): a = LOTE[s]; u = UNI.get(s, {}).get('auc', np.nan) if not (a['auc'] >= 0.60): return 'NO PASA' + (' (inverso; no se interpreta)' if a['auc'] < 0.5 else '') ok = a['auc'] >= 0.65 and a['ic'][0] > 0.55 and a.get('min_dejar_uno_fuera', 0) >= 0.60 and a.get('mediana_por_exp_n10', 0) >= 0.60 and u >= 0.60 return 'PASA' if ok else 'COTA' VER = {s: veredicto(s) for s in ['C'] + SC} # (b) estabilidad Ui = U.set_index('unidad'); pares = [] for t in range(2014, 2023): a = U[U.t == t][['organo_clave', 'cpv_div', 'C', 'hecho']]; b = U[U.t == t + 3][['organo_clave', 'cpv_div', 'C', 'hecho']] m = a.merge(b, on=['organo_clave', 'cpv_div'], suffixes=('_1', '_2')); m['t'] = t for k in ['_1', '_2']: tt = t if k == '_1' else t + 3; q90 = U.loc[U.t == tt, 'C'].quantile(0.9); m['dec' + k] = m['C' + k] >= q90 pares.append(m) PA = pd.concat(pares); PA = PA[PA.C_1.notna() & PA.C_2.notna()] def orr(df, a, b): df = df.reset_index(drop=True); t = pd.crosstab(df[a].values, df[b].values).reindex(index=[False, True], columns=[False, True], fill_value=0).values + 0.5 return (t[1, 1] * t[0, 0]) / (t[1, 0] * t[0, 1]), t - 0.5 def or_boot(df, a, b): o, tab = orr(df, a, b); og = df.organo_clave.values; uo = pd.Index(sorted(set(og))); io = uo.get_indexer(og); bs = [] grp = [np.where(io == i)[0] for i in range(len(uo))] for _ in range(NB): sel = np.concatenate([grp[i] for i in rng.integers(0, len(uo), len(uo))]); bs.append(orr(df.iloc[sel], a, b)[0]) return {'or': round(o, 2), 'ic': np.nanpercentile(bs, [2.5, 97.5]).round(2).tolist(), 'tabla': tab.astype(int).tolist()} EST = {'pares': len(PA), 'organos': int(PA.organo_clave.nunique()), 'hecho': or_boot(PA, 'hecho_1', 'hecho_2'), 'decil': or_boot(PA, 'dec_1', 'dec_2'), 'spearman_C': round(PA[['C_1', 'C_2']].corr(method='spearman').iloc[0, 1], 3)} log('estabilidad', EST) json.dump({'base': R, 'lote': LOTE, 'unidad': UNI, 'sensibilidad': SENS, 'veredicto': VER, 'estabilidad': EST}, open('/w/salidas/20_validaciones.json', 'w'), ensure_ascii=False, indent=1, default=lambda o: float(o) if isinstance(o, (np.floating, np.integer)) else str(o)) log('fin', VER)