"""MK1 · 11 · screens S1-S4 por unidad órgano × división × ventana (DEFINICIONES_PREVIAS §2-4). Implementación PRINCIPAL. Lee interno/lotes.parquet y ganadores.parquet (de 01_base, DuckDB); numpy/pandas. Escribe interno/unidades.parquet y interno/lote_unidad.parquet. No lee etiquetas.""" import hashlib, time, json import numpy as np, pandas as pd, pyarrow.parquet as pq T0 = time.time(); B = 200; NMIN = 15; POOLMIN = 50 def log(*a): print(f"[{time.time()-T0:6.0f}s]", *a, flush=True) L = pq.read_table('/w/interno/lotes.parquet', columns=['lote_key', 'organo_clave', 'cpv_div', 'anio', 'nof', 'baja', 'fecha_adj', 'fecha_pub']).to_pandas() L = L[L.cpv_div != '??'].sort_values('lote_key', kind='stable').reset_index(drop=True) G = pq.read_table('/w/interno/ganadores.parquet', columns=['lote_key', 'ent', 'w']).to_pandas() G = G[G.lote_key.isin(set(L.lote_key))] ent_code, ent_names = pd.factorize(G.ent, sort=True); G['e'] = ent_code pos = pd.Series(np.arange(len(L)), index=L.lote_key) G['li'] = pos.loc[G.lote_key].values G = G.sort_values(['li', 'e']).reset_index(drop=True) cnt = np.bincount(G.li.values, minlength=len(L)); starts = np.concatenate([[0], np.cumsum(cnt)]) GE = G.e.values.astype(np.int64); GW = G.w.values.astype(np.float64) assert (cnt > 0).all(), 'lote sin ganador' # conjunto ganador = lista ordenada de entidades setid_str = G.groupby('li', sort=True).e.apply(lambda s: ','.join(map(str, s.values))) SET = pd.factorize(setid_str.reindex(range(len(L))).values)[0] NE = len(ent_names); log('lotes', len(L), 'entidades', NE) ORG = pd.factorize(L.organo_clave)[0]; ANIO = L.anio.values.astype(int) NOF = L.nof.values.astype(float); BAJA = L.baja.values.astype(float) # orden temporal: (fecha_adj, fecha_pub, lote_key) con nulos al final fa = pd.to_datetime(L.fecha_adj, errors='coerce'); fp = pd.to_datetime(L.fecha_pub, errors='coerce') ordf = pd.DataFrame({'a': fa.isna(), 'fa': fa, 'b': fp.isna(), 'fp': fp, 'k': L.lote_key}) RANK = np.empty(len(L), int); RANK[ordf.sort_values(['a', 'fa', 'b', 'fp', 'k'], kind='stable').index.values] = np.arange(len(L)) def rng_for(key, stat): return np.random.default_rng(int(hashlib.md5((key + '|' + stat).encode()).hexdigest()[:15], 16)) def zstat(obs, null): m = null.mean(); s = null.std(ddof=1) # desvío 1: sd nula por debajo de la precisión numérica (1e-9 relativo) = 0 -> z = 0 return 0.0 if not (s > 1e-9 * max(1.0, abs(m))) else (obs - m) / s, m, s def disp(v): # índice de dispersión por filas return v.var(axis=-1, ddof=1) / v.mean(axis=-1) def neff_rows(lot_idx_2d): """lot_idx_2d (R, n) índices globales de lote -> N_eff por fila con pesos de ganadores.""" R, n = lot_idx_2d.shape; flat = lot_idx_2d.ravel() k = cnt[flat]; rep = np.repeat(np.repeat(np.arange(R), n), k) off = np.repeat(starts[flat], k) + (np.arange(k.sum()) - np.repeat(np.cumsum(k) - k, k)) key = rep.astype(np.int64) * NE + GE[off] u, inv = np.unique(key, return_inverse=True); s = np.bincount(inv, weights=GW[off]) / n r_u = (u // NE).astype(int) H = -np.bincount(r_u, weights=s * np.log(s), minlength=R) return np.exp(H), H def shares_var(lots, yidx_2d): """lots (n,) índices de lote; yidx_2d (R, n) año 0..2 de cada lote -> V por fila.""" R, n = yidx_2d.shape; k = cnt[lots] off = np.repeat(starts[lots], k) + (np.arange(k.sum()) - np.repeat(np.cumsum(k) - k, k)) lot_of = np.repeat(np.arange(n), k); e_loc = pd.factorize(GE[off])[0]; ne = e_loc.max() + 1; w = GW[off] pbar = np.bincount(e_loc, weights=w) / n out = np.empty(R) for r in range(R): y = yidx_2d[r]; ny = np.bincount(y, minlength=3) S = np.bincount(e_loc * 3 + y[lot_of], weights=w, minlength=ne * 3).reshape(ne, 3) / ny out[r] = (pbar * S.var(axis=1)).sum() return out U = []; LU = [] for t in range(2014, 2026): win = np.where((ANIO >= t - 2) & (ANIO <= t))[0] Lw = L.iloc[win] for div, gdiv in Lw.groupby('cpv_div', sort=True): mi = win[gdiv.index.values - 0] if False else gdiv.index.values # índices globales (L tiene índice 0..N-1) pool1 = mi[NOF[mi] >= 2]; pool2 = mi; pool4 = mi[~np.isnan(BAJA[mi])] for o, lots in pd.Series(mi).groupby(ORG[mi]): lots = np.sort(lots.values) if len(lots) < NMIN: continue okey = L.organo_clave.values[lots[0]]; key = f"{okey}|{div}|{t}" r = {'unidad': key, 'organo_clave': okey, 'cpv_div': div, 't': t, 'n': len(lots)} # S1 x1 = lots[NOF[lots] >= 2]; r['n1'] = len(x1); r['n_nof1'] = int((NOF[lots] >= 1).sum()) sp1 = pool1[ORG[pool1] != o] if len(x1) >= NMIN and len(sp1) >= POOLMIN: g = rng_for(key, 'S1'); d = g.integers(0, len(sp1), size=(B, len(x1))) r['D'] = float(disp(NOF[x1])); r['z1'], r['D_null'], _ = zstat(r['D'], disp(NOF[sp1[d]])) xa = lots[NOF[lots] >= 1]; sp1b = mi[(NOF[mi] >= 1) & (ORG[mi] != o)] if len(xa) >= NMIN and len(sp1b) >= POOLMIN: # sensibilidad g = rng_for(key, 'S1b'); d = g.integers(0, len(sp1b), size=(B, len(xa))) r['D_todos'] = float(disp(NOF[xa])); r['z1b'], _, _ = zstat(r['D_todos'], disp(NOF[sp1b[d]])) # S2a sp2 = pool2[ORG[pool2] != o]; n = len(lots) ne_obs, H_obs = neff_rows(lots[None, :]); r['Neff'] = float(ne_obs[0]); r['J'] = float(H_obs[0] / np.log(n)) r['n_ent'] = int(len(np.unique(GE[np.concatenate([np.arange(starts[l], starts[l + 1]) for l in lots])]))) if len(sp2) >= POOLMIN: g = rng_for(key, 'S2a'); d = g.integers(0, len(sp2), size=(B, n)) r['z2a'], r['Neff_null'], _ = zstat(r['Neff'], neff_rows(sp2[d])[0]) # S2b seq = lots[np.argsort(RANK[lots], kind='stable')]; ids = SET[seq] r['Sw'] = int((ids[1:] != ids[:-1]).sum()) g = rng_for(key, 'S2b'); P = np.stack([g.permutation(n) for _ in range(B)]) ip = ids[P]; r['z2b'], r['Sw_null'], _ = zstat(r['Sw'], (ip[:, 1:] != ip[:, :-1]).sum(axis=1).astype(float)) # S3 y = ANIO[lots] - (t - 2); ny = np.bincount(y, minlength=3) if ny.min() >= 5: r['V'] = float(shares_var(lots, y[None, :])[0]) g = rng_for(key, 'S3'); P = np.stack([g.permutation(n) for _ in range(B)]) r['z3'], r['V_null'], _ = zstat(r['V'], shares_var(lots, y[P])) # S4 b4 = lots[~np.isnan(BAJA[lots])]; r['n4'] = len(b4); sp4 = pool4[ORG[pool4] != o] if len(b4) >= NMIN and len(sp4) >= POOLMIN: g = rng_for(key, 'S4'); d = g.integers(0, len(sp4), size=(B, len(b4))); v = BAJA[sp4[d]] r['baja_media'] = float(BAJA[b4].mean()); r['baja_sd'] = float(BAJA[b4].std(ddof=1)) r['z4a'], r['bm_null'], _ = zstat(r['baja_media'], v.mean(axis=1)) r['z4b'], r['bs_null'], _ = zstat(r['baja_sd'], v.std(axis=1, ddof=1)) U.append(r) log('ventana', t, 'unidades', len(U)) U = pd.DataFrame(U) # orientación (más alto = más estable) O = {'o1': -U.z1, 'o1b': -U.z1b, 'o2a': -U.z2a, 'o2b': U.z2b, 'o3': -U.z3, 'o4a': -U.z4a, 'o4b': -U.z4b} for k, v in O.items(): U[k] = v; U[k + '_D'] = np.nan for t, idx in U.groupby('t').groups.items(): s = U.loc[idx, k].dropna() if len(s) < 2: continue med = s.median(); mad = 1.4826 * (s - med).abs().median(); sc = mad if mad > 0 else s.std(ddof=1) U.loc[s.index, k + '_D'] = (s - med) / sc U['S1'] = U.o1_D; U['S2'] = U[['o2a_D', 'o2b_D']].mean(axis=1, skipna=False); U['S3'] = U.o3_D U['S4'] = U[['o4a_D', 'o4b_D']].mean(axis=1, skipna=False) SC = ['S1', 'S2', 'S3', 'S4'] U['N_scr'] = U[SC].notna().sum(axis=1); U['K_scr'] = (U[SC] >= 2.326).sum(axis=1) U['C'] = np.where(U.N_scr >= 3, U[SC].mean(axis=1), np.nan) U['hecho'] = (U.N_scr >= 3) & (U.K_scr >= 2) for s in SC: U['hecho_' + s] = U[s] >= 3.09 U.to_parquet('/w/interno/unidades.parquet', index=False) # lote -> unidad centrada c = np.clip(ANIO + 1, 2014, 2025) LUx = pd.DataFrame({'lote_key': L.lote_key, 'unidad': L.organo_clave.values + '|' + L.cpv_div.values + '|' + c.astype(str), 'anio': ANIO, 'cpv_div': L.cpv_div.values, 'organo_clave': L.organo_clave.values}) LUx.to_parquet('/w/interno/lote_unidad.parquet', index=False) res = {'unidades': len(U), 'por_t': U.groupby('t').size().to_dict(), 'con_C': int(U.C.notna().sum()), 'hecho': int(U.hecho.sum()), 'cobertura': {k: int(U[k].notna().sum()) for k in ['S1', 'S2', 'S3', 'S4', 'o1b_D']}, 'hecho_por_screen': {s: int(U['hecho_' + s].sum()) for s in SC}, 'corr_spearman': U[SC + ['C']].corr(method='spearman').round(3).to_dict()} json.dump(res, open('/w/salidas/11_screens.json', 'w'), ensure_ascii=False, indent=1, default=str); log(json.dumps(res, default=str)[:1500])