"""07. Comparación fila a fila impl1 (base, tabla h) / impl2 (pandas) (§8).""" import sys, json sys.path.insert(0, "/w/py") from util import Informe, abrir con = abrir(macros=False) r = Informe(con, "Segunda implementación: comparación fila a fila (`07_cotejo_impl2.py`)") R2 = json.load(open("/w/interno/impl2_recuentos.json")) r.texto("Recuentos de la impl2 (pandas " + R2.get("pandas", "?") + "): " + json.dumps({k: v for k, v in R2.items() if k != "pandas"}, ensure_ascii=False)) r.x("CREATE OR REPLACE TEMP TABLE i2 AS SELECT * FROM read_parquet('/w/interno/impl2_hechos_INTERNO.parquet')") r.q("Recuentos impl1", """SELECT (SELECT count(*) FROM pe) P, count(*) ev1, count(*) FILTER (WHERE ev2) ev2, count(*) FILTER (WHERE parte='a_sin_actos') a, count(*) FILTER (WHERE parte='b_con_actos') b, count(*) FILTER (WHERE parte='c_no_evaluable') c, count(*) FILTER (WHERE h1) h1, count(*) FILTER (WHERE h2) h2, count(*) FILTER (WHERE h2_ext) h2_ext, count(*) FILTER (WHERE h2s) h2s, count(*) FILTER (WHERE h3) h3, count(*) FILTER (WHERE h1 OR h2 OR h3) alguno FROM h""") r.x("""CREATE OR REPLACE TEMP TABLE cmp AS SELECT coalesce(a.id_canonical, b.id_canonical) id_canonical, coalesce(a.source, b.source) source, coalesce(a.ev2, TRUE) e1, coalesce(b.ev2, TRUE) e2, coalesce(a.h1, FALSE) h1a, coalesce(b.h1, FALSE) h1b, coalesce(a.h2, FALSE) h2a, coalesce(b.h2, FALSE) h2b, coalesce(a.h2_ext, FALSE) h2ea, coalesce(b.h2_ext, FALSE) h2eb, coalesce(a.h2s, FALSE) h2sa, coalesce(b.h2s, FALSE) h2sb, coalesce(a.h3, FALSE) h3a, coalesce(b.h3, FALSE) h3b FROM (SELECT * FROM h WHERE h1 OR h2 OR h3 OR h2s OR NOT ev2) a FULL JOIN i2 b USING (id_canonical, source)""") filas = r.q("Diferencias por campo (filas con algún hecho o no evaluables en cualquiera de las dos)", """SELECT count(*) filas, count(*) FILTER (WHERE e1 <> e2) dif_ev2, count(*) FILTER (WHERE h1a <> h1b) dif_h1, count(*) FILTER (WHERE h2a <> h2b) dif_h2, count(*) FILTER (WHERE h2ea <> h2eb) dif_h2_ext, count(*) FILTER (WHERE h2sa <> h2sb) dif_h2s, count(*) FILTER (WHERE h3a <> h3b) dif_h3, count(*) FILTER (WHERE (h1a OR h2a OR h3a) OR (h1b OR h2b OR h3b)) con_hecho, count(*) FILTER (WHERE (h1a <> h1b OR h2a <> h2b OR h3a <> h3b OR h2ea <> h2eb)) dif_alguna FROM cmp""") f = filas[0] pct = 100.0 * f[-1] / max(f[-2], 1) r.q("Muestra de diferencias (hasta 30)", "SELECT * FROM cmp WHERE e1 <> e2 OR h1a <> h1b OR h2a <> h2b OR h3a <> h3b OR h2ea <> h2eb OR h2sa <> h2sb LIMIT 30") r.texto(f"**Diferencias en H1/H2/H3: {f[-1]} de {f[-2]} filas con algún hecho ({pct:.3f} %). Tolerancia ≤ 0,5 %: {'PASA' if pct <= 0.5 else 'NO PASA'}.**") r.guardar("/w/salidas/07_cotejo_impl2.md")