"""SUB1 · 30 · SEGUNDA implementación (pandas + pyarrow, sin DuckDB), escrita desde DEFINICIONES_PREVIAS §4-6, sin importar nada de la principal. Entrada: interno/c_filas.parquet y s_filas.parquet + tipo_ente.parquet. Salida: interno/impl2_ea.parquet.""" import pandas as pd, numpy as np, json C = pd.read_parquet('/w/interno/c_filas.parquet', columns=['ente', 'anio', 'empresa_clave', 'importe', 'emp_principal']) S = pd.read_parquet('/w/interno/s_filas.parquet', columns=['ente', 'anio', 'cif', 'importe']) T = pd.read_parquet('/w/interno/tipo_ente.parquet') C = C[C.emp_principal & C.ente.notna()].copy() S = S[S.ente.notna()].copy() C['w'] = np.where(C.importe.abs() <= 1e9, C.importe, np.nan) cf = C.groupby(['ente', 'anio', 'empresa_clave'], dropna=False).agg(w=('w', lambda s: s.sum(min_count=1)), nadj=('w', 'size')).reset_index() cf['w'] = cf.w.fillna(0.0) sf = S.groupby(['ente', 'anio', 'cif']).agg(imp_s=('importe', 'sum')).reset_index().rename(columns={'cif': 'empresa_clave'}) j = cf.merge(sf[['ente', 'anio', 'empresa_clave']].assign(y=True), on=['ente', 'anio', 'empresa_clave'], how='left') j['y'] = j.y.fillna(False).astype(bool) j['wy'] = j.w * j.y g = j.groupby(['ente', 'anio']).agg(n_emp=('empresa_clave', 'size'), n_w=('w', lambda s: int((s > 0).sum())), imp_c=('w', 'sum'), w2=('w', lambda s: float((s ** 2).sum())), k=('y', 'sum'), imp_c_doble=('wy', 'sum')).reset_index() b = S.groupby(['ente', 'anio']).agg(n_benef=('cif', 'nunique')).reset_index() g = g.merge(b, on=['ente', 'anio'], how='left').merge(T, on='ente', how='left') g['n_benef'] = g.n_benef.fillna(0).astype(int); g['tipo'] = g.tipo.fillna('sin_tipo') g['r'] = np.where(g.imp_c > 0, g.imp_c_doble / g.imp_c.where(g.imp_c > 0), np.nan) g['n_eff'] = np.where(g.w2 > 0, g.imp_c ** 2 / g.w2.where(g.w2 > 0), 0.0) g['elig'] = (g.n_benef > 0) & (g.n_w >= 30) g['elig10'] = (g.n_benef > 0) & (g.n_w >= 10) g['tramo'] = pd.cut(g.n_benef, [-1, 9, 99, 999, 10 ** 12], labels=['1-9', '10-99', '100-999', '1000+']).astype(str) E = g[g.elig] def esperado(row): for keys in (['tipo', 'anio', 'tramo'], ['tipo', 'anio'], ['anio']): m = np.ones(len(E), bool) for k in keys: m &= (E[k].values == row[k]) sub = E[m] if row['elig']: sub = sub[sub.ente != row['ente']] if len(sub) >= 5: return float(np.clip(sub.r.mean(), 0.001, 0.999)) return np.nan g['e'] = [esperado(r) if r['elig10'] else np.nan for _, r in g.iterrows()] g['s'] = np.sqrt(g.e * (1 - g.e) / g.n_eff.where(g.n_eff > 0)) def t2(df, wins): z = ((df.r - df.e) / df.s).values; I = len(z) if wins: lo, hi = np.quantile(z, 0.10), np.quantile(z, 0.90); z = np.clip(z, lo, hi) phi = float(np.mean(z ** 2)); w = 1 / df.s.values ** 2 return max((I * phi - (I - 1)) / (w.sum() - (w ** 2).sum() / w.sum()), 0.0) if I * phi > I - 1 else 0.0 tw = {a: t2(d, True) for a, d in g[g.elig].groupby('anio')}; tn = {a: t2(d, False) for a, d in g[g.elig].groupby('anio')} g['zd'] = (g.r - g.e) / np.sqrt(g.s ** 2 + g.anio.map(tw)); g['zd_nw'] = (g.r - g.e) / np.sqrt(g.s ** 2 + g.anio.map(tn)) g['hecho'] = g.elig & (g.zd > 3.090232) & (g.zd_nw > 3.090232) g.to_parquet('/w/interno/impl2_ea.parquet') print(json.dumps({'unidades': len(g), 'hecho': int(g.hecho.sum()), 'elig': int(g.elig.sum()), 'tau_w': tw, 'tau_nw': tn}, default=str))