"""05b. Cotejo de la segunda implementación con la principal (§7c), pandas sin DuckDB. Escribe salidas/05_cotejo_impl2.json.""" import json, os, gc import numpy as np, pandas as pd, pyarrow.parquet as pq SUF = "_prueba" if os.environ.get("PRUEBA") else "" R = json.load(open(f"/w/tmp/05_impl2_recuentos{SUF}.json")) def agrega(k, j, j6): o = np.argsort(k, kind="stable"); k = k[o]; j = j[o].astype(np.int64); j6 = j6[o].astype(np.int64) u, ini, n = np.unique(k, return_index=True, return_counts=True) return pd.DataFrame({"n": n, "j": np.add.reduceat(j, ini), "j6": np.add.reduceat(j6, ini)}, index=u) def resumen(ruta): ks, js, j6s = [], [], [] for bt in pq.ParquetFile(ruta).iter_batches(batch_size=500_000, columns=["id_canonical", "source", "joven", "joven6"]): df = bt.to_pandas() ks.append(pd.util.hash_array(np.asarray((df.id_canonical.astype(object).astype(str) + "|" + df.source.astype(object).astype(str)).to_numpy(), dtype=object))) js.append(df.joven.to_numpy().astype(np.int8)); j6s.append(df.joven6.to_numpy().astype(np.int8)) return agrega(np.concatenate(ks), np.concatenate(js), np.concatenate(j6s)) b = resumen("/w/interno/ev.parquet") R["principal"] = {"evaluables": int(b.n.sum()), "jovenes": int(b.j.sum()), "jovenes6": int(b.j6.sum())} t2 = pq.read_table(f"/w/interno/impl2_ev{SUF}.parquet").to_pandas() a = agrega(t2.key.to_numpy(), t2.joven.to_numpy(), t2.joven6.to_numpy()); del t2 m = a.join(b, how="outer", lsuffix="2", rsuffix="1").fillna(0) dif_ev = int((m.n1 != m.n2).sum()); dif_j = int((m.j1 != m.j2).sum()); dif_j6 = int((m.j61 != m.j62).sum()) filas_jov = int(((m.j1 > 0) | (m.j2 > 0)).sum()) R["filas"] = {"claves_comparadas": len(m), "dif_evaluable": dif_ev, "dif_joven": dif_j, "dif_joven6": dif_j6, "filas_jovenes_en_alguna": filas_jov, "pct_dif_sobre_jovenes": 100.0 * max(dif_ev, dif_j) / filas_jov if filas_jov else None} o1 = pq.read_table("/w/interno/oa_j12.parquet", columns=["organo_clave", "anio", "estrato", "n", "k", "E", "zd", "hecho"]).to_pandas() o2 = pq.read_table(f"/w/interno/impl2_oa{SUF}.parquet").to_pandas() o2["anio"] = o2.anio.astype(int); o1["anio"] = o1.anio.astype(int) for o in (o1, o2): o["organo_clave"] = o.organo_clave.astype(str); o["estrato"] = o.estrato.astype(str) mo = o1.merge(o2, on=["organo_clave", "anio", "estrato"], how="outer", suffixes=("_1", "_2"), indicator=True) ambos = mo[mo._merge == "both"] n30 = ambos[(ambos.n_1 >= 30) | (ambos.n_2 >= 30)] R["organo_anio"] = {"solo_principal": int((mo._merge == "left_only").sum()), "solo_impl2": int((mo._merge == "right_only").sum()), "ambos": len(ambos), "dif_n": int((ambos.n_1 != ambos.n_2).sum()), "dif_k": int((ambos.k_1 != ambos.k_2).sum()), "dif_E_rel_gt_0.5pct": int((abs(ambos.E_1 - ambos.E_2) > 0.005 * ambos.E_1.abs().clip(lower=1e-12)).sum()), "max_dif_zd": float(abs(ambos.zd_1 - ambos.zd_2).max()), "dif_hecho_n30": int((n30.hecho_1 != n30.hecho_2).sum()), "n30": len(n30)} r_ = R["filas"]; o_ = R["organo_anio"] R["veredicto"] = "pasa" if ((r_["pct_dif_sobre_jovenes"] or 0) <= 0.5 and o_["dif_hecho_n30"] <= 0.005 * o_["n30"] and o_["dif_E_rel_gt_0.5pct"] <= 0.005 * o_["ambos"] and o_["dif_n"] == 0 and o_["dif_k"] == 0) else "no pasa" print(json.dumps(R, ensure_ascii=False, default=str)) json.dump(R, open(f"/w/tmp/05_prueba.json" if SUF else "/w/salidas/05_cotejo_impl2.json", "w"), ensure_ascii=False, indent=1, default=str)