"""E-M2b ampliación · candidatos (DEFINICIONES_AMPLIA §2-§3) con el ETL de main (ed652b7): series PLACSP de t ∈ {2019, 2020, 2021, 2022, 2024} con sus candidatas E0 (sl_cand, en la lista o no), muestra del control (100 cadenas por año) y anclas; comprobación al dato frente a E-M2 y al piloto (2023); tablas persistentes en /w/tmp/em2ba.duckdb para los lotes. Uso (contenedor, sin red): sql/ejecutar.sh 10_candidatos.py candidatos""" import csv import sys import time from pathlib import Path import duckdb sys.path.insert(0, "/app") from etl import series_licitadas as sl # noqa: E402 ANIOS = (2019, 2020, 2021, 2022, 2024) N_CTRL = 100 T0 = time.time() DB = Path("/w/tmp/em2ba.duckdb") DB.unlink(missing_ok=True) con = duckdb.connect(DB.as_posix()) con.execute("SET threads=6; SET memory_limit='7GB'; SET temp_directory='/w/tmp/duckdb_tmp'; SET preserve_insertion_order=false") c, e = sl.preparar(con, Path("/d/unified_20261018"), Path("/d/unified_20261018.identidad"), Path("/d/unified_20261018.vinculos"), 2025) assert e is not None, (c.omitido, c.avisos) print("pipeline", round(time.time() - T0), "s", flush=True) q = lambda s: con.execute(s).fetchall() # noqa: E731 out = [] def p(*a): s = " ".join(str(x) for x in a) out.append(s) print(s, flush=True) # ── Anclas: las parejas PLACSP de los jueces de E-M2 ────────────────────────────────────────────────────────────── anc = [r for r in csv.DictReader(open("/em2/cotejo/jueces_clave.csv", encoding="utf-8"), delimiter=";") if r["fuente"] == "PLACSP"] res = {r["id"]: r for r in csv.DictReader(open("/em2/cotejo/jueces_resultado.csv", encoding="utf-8"), delimiter=";")} con.execute("CREATE TEMP TABLE anclas (ancla_id INT, grupo VARCHAR, serie_m1r VARCHAR, licitacion VARCHAR, consenso VARCHAR)") con.executemany("INSERT INTO anclas VALUES (?, ?, ?, ?, ?)", [(int(r["id"]), r["grupo"], r["serie_m1r"], r["licitacion"], res[r["id"]]["consenso"]) for r in anc]) # ── Parejas a nivel de licitación para series y control (la definición del piloto, 10_candidatos.py) ─────────────────── con.execute("""CREATE TEMP TABLE f AS WITH c AS (SELECT p.tipo_unidad, p.unidad, p.obj_l, p.jw, p.r_tokens, u.organo_clave, u.anio, u.cpvs, u.cabeza FROM sl_par p JOIN sl_u u USING (tipo_unidad, unidad)) SELECT c.tipo_unidad, c.unidad, c.anio, l.licitacion, l.id_canonical, (c.jw >= 0.85 AND list_contains(c.cpvs, substr(l.cpv, 1, 5))) AS a, c.r_tokens AS b, (len(c.cabeza) > 0 AND len(list_intersect(c.cabeza, em2_tokens(l.objeto_norm))) = len(c.cabeza)) AS cab FROM c JOIN sl_lic l ON l.organo_clave = c.organo_clave AND l.anio_lic = c.anio + 1 AND l.objeto_norm = c.obj_l""") con.execute("""CREATE TEMP TABLE par0 AS SELECT tipo_unidad, unidad, any_value(anio) anio, licitacion, bool_or((a OR b) AND cab) AS e0b, list(DISTINCT id_canonical ORDER BY id_canonical) FILTER (WHERE a OR b) AS filas_casadas FROM f WHERE a OR b GROUP BY tipo_unidad, unidad, licitacion""") print("parejas", round(time.time() - T0), "s", flush=True) # ── Comprobación al dato (§3) ───────────────────────────────────────────────────────────────────────────────────── T = "/em2/salidas/tablas" ESP = {2019: (270, 92, 70, 6822, 573, 254), 2020: (680, 117, 80, 8950, 548, 174), 2021: (875, 149, 84, 11925, 744, 259), 2022: (1089, 215, 122, 13800, 782, 341), 2023: (1264, 227, 139, 13457, 876, 342), 2024: (1233, 258, 151, 13456, 760, 317)} ESP_H = {2019: (516, 140), 2020: (1352, 973), 2021: (1331, 943), 2022: (1293, 591), 2023: (1514, 748), 2024: (4500, 3807)} mal = {} p("## Comprobación al dato frente a E-M2 (§3)") for t in sorted(ESP): r = q(f"""SELECT (SELECT count(*) FROM sl_u WHERE tipo_unidad='serie' AND anio={t}), (SELECT count(DISTINCT unidad) FROM par0 WHERE tipo_unidad='serie' AND anio={t}), (SELECT count(DISTINCT unidad) FROM par0 WHERE tipo_unidad='serie' AND anio={t} AND e0b), (SELECT count(*) FROM sl_u WHERE tipo_unidad='control' AND anio={t}), (SELECT count(DISTINCT unidad) FROM par0 WHERE tipo_unidad='control' AND anio={t}), (SELECT count(DISTINCT unidad) FROM par0 WHERE tipo_unidad='control' AND anio={t} AND e0b)""")[0] et = q(f"""SELECT count(*) FILTER (WHERE u.tipo_unidad='serie' AND e.pasa), count(*) FILTER (WHERE u.tipo_unidad='control' AND e.pasa) FROM sl_et e JOIN sl_u u USING (tipo_unidad, unidad) WHERE u.anio={t}""")[0] p(f"- {t}: series {r[0]}, E0 {r[1]}, E0b {r[2]} · control {r[3]}, E0 {r[4]}, E0b {r[5]} (esperado {ESP[t]}) · sl_et E0b: {et}") if tuple(r) != ESP[t] or et != (ESP[t][2], ESP[t][5]): mal[f"recuentos_{t}"] = (r, et, ESP[t]) for tab, flt, k in (("hechos_e0", "TRUE", 0), ("hechos_e0b", "p.e0b", 1)): d = q(f"""WITH m AS (SELECT p.unidad serie_m1r, p.licitacion FROM par0 p JOIN sl_u u USING (tipo_unidad, unidad) WHERE p.tipo_unidad='serie' AND p.anio={t} AND u.en_lista AND {flt}), h AS (SELECT h.serie_m1r, h.licitacion FROM '{T}/{tab}.parquet' h WHERE h.anio={t} AND h.serie_m1r IN (SELECT serie_m1r FROM '{T}/series_e0.parquet' WHERE fuente='PLACSP')) SELECT (SELECT count(*) FROM m), (SELECT count(*) FROM h), (SELECT count(*) FROM (SELECT * FROM m EXCEPT SELECT * FROM h)), (SELECT count(*) FROM (SELECT * FROM h EXCEPT SELECT * FROM m))""")[0] p(f" {tab}: nuestras {d[0]}, suyas {d[1]}, solo nuestras {d[2]}, solo suyas {d[3]} (esperado {ESP_H[t][k]})") if d != (ESP_H[t][k], ESP_H[t][k], 0, 0): mal[f"{tab}_{t}"] = d # sl_cand (lo que une el job) = las parejas de series de par0, al dato d = q(f"""SELECT (SELECT count(*) FROM (SELECT serie_m1r, licitacion, e0b FROM sl_cand WHERE anio={t} EXCEPT SELECT unidad, licitacion, e0b FROM par0 WHERE tipo_unidad='serie' AND anio={t})), (SELECT count(*) FROM (SELECT unidad, licitacion, e0b FROM par0 WHERE tipo_unidad='serie' AND anio={t} EXCEPT SELECT serie_m1r, licitacion, e0b FROM sl_cand WHERE anio={t}))""")[0] p(f" sl_cand frente a las parejas de series (con e0b): solo sl_cand {d[0]}, solo par0 {d[1]}") if d != (0, 0): mal[f"sl_cand_{t}"] = d # 2023: las parejas de series del piloto piloto = [(r["unidad"], r["licitacion"]) for r in csv.DictReader(open("/em2b/clave/parejas.csv", encoding="utf-8"), delimiter=";") if r["tipo_unidad"] == "serie" and r["de_2023"] == "1"] con.execute("CREATE TEMP TABLE piloto (serie_m1r VARCHAR, licitacion VARCHAR)") con.executemany("INSERT INTO piloto VALUES (?, ?)", piloto) d = q("""SELECT (SELECT count(*) FROM piloto), (SELECT count(*) FROM sl_cand WHERE anio=2023), (SELECT count(*) FROM (SELECT * FROM piloto EXCEPT SELECT serie_m1r, licitacion FROM sl_cand WHERE anio=2023)), (SELECT count(*) FROM (SELECT serie_m1r, licitacion FROM sl_cand WHERE anio=2023 EXCEPT SELECT * FROM piloto))""")[0] p(f"- 2023 frente al piloto: piloto {d[0]}, sl_cand {d[1]}, solo piloto {d[2]}, solo sl_cand {d[3]} (esperado 1545, 1545, 0, 0)") if d != (1545, 1545, 0, 0): mal["piloto_2023"] = d a = q(f"""SELECT s.anio, count(*), count(p.unidad) FROM anclas a JOIN sl_u s ON s.tipo_unidad='serie' AND s.unidad=a.serie_m1r LEFT JOIN par0 p ON p.tipo_unidad='serie' AND p.unidad=a.serie_m1r AND p.licitacion=a.licitacion GROUP BY 1 ORDER BY 1""") p(f"- anclas PLACSP (año, en sl_u, encontradas como pareja): {a}") n_bloque = sum(x[2] for x in a if x[0] in ANIOS) if n_bloque != 21 or sum(x[1] for x in a if x[0] in ANIOS) != 21 or sum(x[2] for x in a) != 34: mal["anclas"] = a p(f"DIFERENCIAS: {mal}") Path("/w/salidas/10_comprobacion.txt").write_text("\n".join(out) + "\n", encoding="utf-8") if mal: raise SystemExit(f"NO COINCIDE: {mal}") # ── Muestra del control (§2.2): 100 cadenas por año ─────────────────────────────────────────────────────────────── con.execute(f"""CREATE TEMP TABLE ctrl_m AS SELECT unidad, anio FROM (SELECT unidad, any_value(anio) anio FROM par0 WHERE tipo_unidad='control' GROUP BY unidad) QUALIFY row_number() OVER (PARTITION BY anio ORDER BY md5('em2b-control' || unidad)) <= {N_CTRL}""") anios_sql = ", ".join(str(t) for t in ANIOS) # ── Tablas persistentes ────────────────────────────────────────────────────────────────────────────────────────── con.execute(f"""CREATE TABLE unidades AS SELECT u.tipo_unidad, u.unidad, u.anio, u.organo_clave, u.en_lista, u.n, u.suma, u.fecha_ini, u.fecha_fin, u.objeto_norm, EXISTS (SELECT 1 FROM par0 p WHERE p.tipo_unidad = u.tipo_unidad AND p.unidad = u.unidad AND p.e0b) AS e0b, (u.tipo_unidad = 'serie' AND u.unidad IN (SELECT serie_m1r FROM anclas)) AS es_ancla FROM sl_u u WHERE u.anio IN ({anios_sql}) AND ( (u.tipo_unidad = 'serie' AND u.unidad IN (SELECT unidad FROM par0 WHERE tipo_unidad='serie')) OR (u.tipo_unidad = 'control' AND u.unidad IN (SELECT unidad FROM ctrl_m)))""") con.execute("""CREATE TABLE parejas AS SELECT p.tipo_unidad, p.unidad, p.anio, p.licitacion, p.e0b, p.filas_casadas, a.ancla_id, a.grupo AS ancla_grupo, a.consenso AS ancla_consenso FROM par0 p JOIN unidades u USING (tipo_unidad, unidad) LEFT JOIN anclas a ON a.serie_m1r = p.unidad AND a.licitacion = p.licitacion AND p.tipo_unidad = 'serie'""") con.execute("""CREATE TABLE contratos AS SELECT u.tipo_unidad, u.unidad, k.id_canonical, k.fecha_adj, k.base, k.cpv, k.objeto, m.organo_nombre FROM unidades u JOIN sl_cad k ON u.tipo_unidad = 'serie' AND k.serie_m1r = u.unidad JOIN pm m ON m.id_canonical = k.id_canonical UNION ALL SELECT u.tipo_unidad, u.unidad, k.id_canonical, k.fecha_adj, k.base, k.cpv, k.objeto, m.organo_nombre FROM unidades u JOIN sl_cad k ON u.tipo_unidad = 'control' AND k.cadena = u.unidad JOIN pm m ON m.id_canonical = k.id_canonical""") con.execute("""CREATE TABLE lic_filas AS SELECT l.licitacion, l.id_canonical, l.fuente_lic, l.anio_lic, l.fecha_pub, l.procedimiento, l.unidad AS unidad_fila, l.expediente, l.objeto, l.cpv, l.imp_lic_eur, l.url_origen, l.rol_am FROM sl_lic l WHERE l.licitacion IN (SELECT DISTINCT licitacion FROM parejas)""") p("\n## Lo que se leerá (bloque 1)") p("año · tipo · unidades · con e0b · anclas · parejas · parejas e0b · en lista") for r in q("""SELECT u.anio, u.tipo_unidad, count(DISTINCT u.unidad), count(DISTINCT u.unidad) FILTER (WHERE u.e0b), count(DISTINCT u.unidad) FILTER (WHERE u.es_ancla), count(p.licitacion), count(p.licitacion) FILTER (WHERE p.e0b), count(p.licitacion) FILTER (WHERE u.en_lista) FROM unidades u JOIN parejas p USING (tipo_unidad, unidad) GROUP BY ALL ORDER BY ALL"""): p(" ", r) p("total:", q("""SELECT (SELECT count(*) FROM unidades), (SELECT count(*) FROM parejas), (SELECT count(*) FROM contratos), (SELECT count(*) FROM lic_filas), (SELECT count(DISTINCT licitacion) FROM parejas), (SELECT count(*) FROM parejas WHERE ancla_id IS NOT NULL)""")[0]) p("unidades sin contratos:", q("SELECT count(*) FROM unidades u WHERE NOT EXISTS (SELECT 1 FROM contratos k WHERE k.unidad = u.unidad)")[0], "· n distinto:", q("SELECT count(*) FROM unidades u JOIN (SELECT unidad, count(*) n FROM contratos GROUP BY 1) k USING (unidad) WHERE k.n <> u.n")[0], "· licitaciones sin filas:", q("SELECT count(DISTINCT licitacion) FROM parejas WHERE licitacion NOT IN (SELECT licitacion FROM lic_filas)")[0]) p("\n## Unidades con más de 100 parejas (descriptivo, sin etiquetas)") for r in q("""SELECT u.anio, u.tipo_unidad, count(*) n, count(*) FILTER (WHERE p.e0b), u.en_lista, (SELECT mode(organo_nombre) FROM contratos k WHERE k.unidad = u.unidad), left(u.objeto_norm, 90) FROM unidades u JOIN parejas p USING (tipo_unidad, unidad) GROUP BY ALL HAVING count(*) > 100 ORDER BY 3 DESC"""): p(" ", r) Path("/w/salidas/10_comprobacion.txt").write_text("\n".join(out) + "\n", encoding="utf-8") print("hecho", round(time.time() - T0), "s")