"""EJ2 · 20 · histogramas, contrafactual de Poisson, exceso, hueco, IC bootstrap por licitación, placebos, desagregaciones, órganos (K de N) y sensibilidades. Imagen report-worker (numpy, pandas, pyarrow).""" import numpy as np, pandas as pd, json, re, time, sys sys.path.insert(0, '/w/py') from comun import * T0 = time.time() def log(*a): print(f"[{time.time()-T0:6.1f}s]", *a, flush=True) B = 1000; SEMILLA = 20261022 U = pd.read_parquet('/w/interno/u.parquet') U['cat'] = categorias(U['s'].values) U['enhist'] = U['cat'] < 120 log('U', len(U)) def celda(cat, umbrales=UMBRALES, boot=True, grado=2): cnt = recuento(cat); out = {'n': int(len(cat)), 'n_hist': int(cnt[:120].sum()), 'masas': {f'{int(m*100)}': int(cnt[120+j]) for j, m in enumerate(MASAS)}, 'neg': int(cnt[140]), 'ge60': int(cnt[141])} curvas = {} for c in umbrales: cu = ajuste(cnt, c, grado); curvas[c] = cu out[f'c{c}'] = medidas(cnt, c, cu) if boot and out['n_hist'] >= 300: rng = np.random.default_rng(SEMILLA); n = len(cat) reps = {c: {'X': [], 'R_H': [], 'D': [], 'B': []} for c in umbrales} for _ in range(B): cb = recuento(cat[rng.integers(0, n, n)]) for c in umbrales: m = medidas(cb, c, ajuste(cb, c, grado)) if m is None: continue for k in reps[c]: if k in m: reps[c][k].append(m[k]) for c in umbrales: if out[f'c{c}'] is None: continue for k, v in reps[c].items(): if v: out[f'c{c}'][f'{k}_ic'] = [float(np.percentile(v, 2.5)), float(np.percentile(v, 97.5))] out[f'c{c}']['reps_validas'] = len(reps[c]['X']) return out, cnt, curvas R = {'md5': open('/w/DEFINICIONES_PREVIAS.md5').read().split()[0]} # --- total y por tipo R['total'], cnt_tot, cur_tot = celda(U['cat'].values); log('total', R['total']['c20']) R['tipo'] = {}; dens = [] def filas_densidad(nombre, cnt, cur): E20, H20, F20 = config(20) for k in range(NB): f = {'celda': nombre, 'bin_desde_pct': k * 0.5, 'bin_hasta_pct': k * 0.5 + 0.5, 'n': int(cnt[k])} for c in (10, 20, 50): E, H, F = config(c) f[f'contrafactual_c{c}'] = round(float(cur[c][k]), 3) if cur.get(c) is not None and (k in E or k in H or k in F) else None f['tramo_c20'] = 'E' if k in E20 else 'H' if k in H20 else 'F' if k in F20 else 'otro' dens.append(f) for j, m in enumerate(MASAS): dens.append({'celda': nombre, 'bin_desde_pct': round(m * 100, 2), 'bin_hasta_pct': round(m * 100, 2), 'n': int(cnt[120 + j]), 'tramo_c20': 'masa_puntual'}) dens.append({'celda': nombre, 'bin_desde_pct': None, 'bin_hasta_pct': 0, 'n': int(cnt[140]), 'tramo_c20': 's<0'}) dens.append({'celda': nombre, 'bin_desde_pct': 60, 'bin_hasta_pct': None, 'n': int(cnt[141]), 'tramo_c20': 's>=60'}) filas_densidad('total', cnt_tot, cur_tot) for t, g in U.groupby('tipo'): R['tipo'][t], cnt, cur = celda(g['cat'].values); filas_densidad(t, cnt, cur); log(t, R['tipo'][t]['c20']) SS = U[U.tipo != 'Obras'] R['placebo15_sin_obras'], _, _ = celda(SS['cat'].values, umbrales=[15, 20]); log('15 sin obras', R['placebo15_sin_obras']['c15']) pd.DataFrame(dens).to_csv('/w/salidas/densidad_sobrecoste.csv', index=False) # --- por año, régimen, tipo × año, tipo de órgano, mercado (solo c = 20, 10, 50 y placebos 15/25) UM = [20, 10, 50, 15, 25] def grupo(cols, umbr=UM): d = {} for k, g in U.groupby(cols): k = k if isinstance(k, tuple) else (k,) nh = int(g['enhist'].sum()) if nh >= 300: o, _, _ = celda(g['cat'].values, umbrales=umbr) else: cnt = recuento(g['cat'].values); o = {'n': int(len(g)), 'n_hist': nh, 'muestra_insuficiente': True, 'O_19_20': int(cnt[38:40].sum()), 'O_20_21': int(cnt[40:42].sum())} d['|'.join(map(str, k))] = o return d R['anio'] = grupo(['anio']); log('anio') R['regimen'] = grupo(['regimen']); R['regimen_tipo'] = grupo(['regimen', 'tipo']) R['tipo_anio'] = grupo(['tipo', 'anio']); log('tipo_anio') R['tipo_organo'] = grupo(['tipo_organo']); log('tipo_organo') R['mercado'] = grupo(['tipo', 'cpv'], umbr=[20, 10, 50]); log('mercado') # --- órganos: K de N pi_tot = R['total']['c20']['Ehat_E'] / R['total']['n_hist'] pi = {t: (R['tipo'][t]['c20']['Ehat_E'] / R['tipo'][t]['n_hist'] if R['tipo'][t]['c20'] else pi_tot) for t in R['tipo']} # Otros: sin ajuste propio -> el del total (declarado) R['pi_organos'] = pi H = U[U.enhist & U.organo_clave.notna()].copy() H['enE'] = H['cat'].isin(config(20)[0]); H['pi'] = H['tipo'].map(pi) og = H.groupby('organo_clave').agg(n=('cat', 'size'), O=('enE', 'sum'), E=('pi', 'sum'), tipo_organo=('tipo_organo', 'first'), nombre=('organo_nombre', 'first')).reset_index() og['X'] = og.O / og.E ics = [garwood(int(o)) for o in og.O] og['X_ic_inf'] = [a / e for (a, b), e in zip(ics, og.E)]; og['X_ic_sup'] = [b / e for (a, b), e in zip(ics, og.E)] og['hecho'] = (og.n >= 100) & (og.X_ic_inf > 1.5) og['posicion'] = np.where(og.n < 100, 'muestra insuficiente', np.where(og.hecho, 'exceso (IC inf > 1,5)', 'sin exceso demostrado')) PF = re.compile(r'^([0-9]{8}[A-Z]|[XYZ][0-9]{7}[A-Z])') pf = og.organo_clave.str.match(PF) R['organos'] = {'N_n100': int((og.n >= 100).sum()), 'K': int(og.hecho.sum()), 'clave_persona_fisica_excluidas': int(pf.sum()), 'K_de_N_por_tipo': {t: [int(g.hecho.sum()), int((g.n >= 100).sum())] for t, g in og.groupby('tipo_organo')}, 'X_mediana_n100': float(og[og.n >= 100].X.median()), 'X_p10_p90_n100': [float(og[og.n >= 100].X.quantile(q)) for q in (0.1, 0.9)], 'organos_con_al_menos_1': int((og.n >= 1).sum())} R['organos']['saturado'] = R['organos']['K'] / max(R['organos']['N_n100'], 1) >= 0.75 og[~pf].sort_values(['organo_clave'])[['organo_clave', 'nombre', 'tipo_organo', 'n', 'O', 'E', 'X', 'X_ic_inf', 'X_ic_sup', 'posicion']].round(4).to_csv('/w/salidas/organo_exceso.csv', index=False) log('organos', R['organos']) # --- sensibilidades (total y por tipo, sin desagregar más) S = {} for g in (1, 3): S[f'grado{g}'] = {'total': celda(U['cat'].values, umbrales=[20, 10, 50, 15, 25], grado=g)[0]} for t, gg in U.groupby('tipo'): S[f'grado{g}'][t] = celda(gg['cat'].values, umbrales=[20, 10, 50, 15, 25], grado=g, boot=False)[0] S['bu1_lineal'] = {} for nombre, g in [('total', U)] + list(U.groupby('tipo')): cnt = recuento(g['cat'].values); S['bu1_lineal'][nombre] = {f'c{c}': medidas(cnt, c, ajuste_bu1(cnt, c)) for c in (20, 10, 50)} cnt = cnt_tot.copy(); m20 = int(cnt[120 + MASAS.index(0.2)]); m10 = int(cnt[120 + MASAS.index(0.1)]); m50 = int(cnt[120 + MASAS.index(0.5)]) S['masas_en_ventana'] = {'c20': (R['total']['c20']['O_E'] + m20) / R['total']['c20']['Ehat_E'], 'c10': (R['total']['c10']['O_E'] + m10) / R['total']['c10']['Ehat_E'], 'c50': (R['total']['c50']['O_E'] + m50) / R['total']['c50']['Ehat_E'], 'masa20': m20, 'masa10': m10, 'masa50': m50} L = pd.read_parquet('/w/interno/lote.parquet') S['v_lote'] = {'total': celda(categorias(L['s_lote'].values), umbrales=[20, 10, 50, 15, 25])[0]} for t, g in L.groupby('tipo'): S['v_lote'][t] = celda(categorias(g['s_lote'].values), umbrales=[20, 10, 50], boot=False)[0] S['v_final'] = {'total': celda(categorias(L['s_fin'].values), umbrales=[20, 10, 50, 15, 25])[0]} for t, g in L.groupby('tipo'): S['v_final'][t] = celda(categorias(g['s_fin'].values), umbrales=[20, 10, 50], boot=False)[0] C = U[~U.no_cuadra.fillna(False).astype(bool)] S['v_cuadra'] = {'total': celda(C['cat'].values, umbrales=[20, 10, 50, 15, 25])[0]} for t, g in C.groupby('tipo'): S['v_cuadra'][t] = celda(g['cat'].values, umbrales=[20, 10, 50], boot=False)[0] Es = U[U.s_estricta != 0] S['v_estricta'] = {'total': celda(categorias(Es['s_estricta'].values), umbrales=[20, 10, 50, 15, 25])[0]} R['sensibilidades'] = S; log('sensibilidades') # --- CSV publicable mercado × año (ROLLUP: tipo, cpv, año) def bandas(cat): cnt = recuento(cat); b = lambda lo, hi: int(cnt[bins(lo, hi)].sum()) return {'n_U': int(len(cat)), 'n_0_60': int(cnt[:120].sum()), 'n_18_19': b(18, 19), 'n_19_20': b(19, 20), 'n_20_21': b(20, 21), 'n_9_5_10': b(9.5, 10), 'n_10_10_5': b(10, 10.5), 'n_49_50': b(49, 50), 'n_50_50_5': b(50, 50.5), 'masa_10': int(cnt[121]), 'masa_20': int(cnt[123]), 'masa_50': int(cnt[129])} filas = [] for niv, cols in [('tipo×cpv×año', ['tipo', 'cpv', 'anio']), ('tipo×cpv', ['tipo', 'cpv']), ('tipo×año', ['tipo', 'anio']), ('tipo', ['tipo']), ('año', ['anio'])]: for k, g in U.groupby(cols): k = k if isinstance(k, tuple) else (k,) f = {'nivel': niv, 'tipo': None, 'cpv_division': None, 'anio': None} for col, v in zip(cols, k): f[{'tipo': 'tipo', 'cpv': 'cpv_division', 'anio': 'anio'}[col]] = v f.update(bandas(g['cat'].values)) if f['n_0_60'] >= 300: o, _, _ = celda(g['cat'].values, umbrales=[20]); c = o['c20'] if c: f.update({'X_20': round(c['X'], 3), 'X_20_ic_inf': round(c['X_ic'][0], 3), 'X_20_ic_sup': round(c['X_ic'][1], 3), 'R_H_20': round(c['R_H'], 3), 'R_H_20_ic_inf': round(c['R_H_ic'][0], 3), 'R_H_20_ic_sup': round(c['R_H_ic'][1], 3)}) filas.append(f) f = {'nivel': 'total', 'tipo': None, 'cpv_division': None, 'anio': None}; f.update(bandas(U['cat'].values)) c = R['total']['c20']; f.update({'X_20': round(c['X'], 3), 'X_20_ic_inf': round(c['X_ic'][0], 3), 'X_20_ic_sup': round(c['X_ic'][1], 3), 'R_H_20': round(c['R_H'], 3), 'R_H_20_ic_inf': round(c['R_H_ic'][0], 3), 'R_H_20_ic_sup': round(c['R_H_ic'][1], 3)}); filas.append(f) P = pd.DataFrame(filas); P['anio'] = P['anio'].astype('Int64') P.to_csv('/w/salidas/publicable_mercado_anio.csv', index=False) json.dump(R, open('/w/salidas/20_exceso.json', 'w'), ensure_ascii=False, indent=1, default=float) log('fin', len(P))