"""SUB1 · 50 · muestras de los cotejos (d) y (e) (DEFINICIONES_PREVIAS §7d-e) con sus registros originales. Todo a interno/.""" import duckdb, random, csv SEM = 20261022 c = duckdb.connect(); x = c.execute x("SET threads=4; SET memory_limit='6GB'; SET temp_directory='/w/tmp/duck'; SET max_temp_directory_size='5GB'") R = '/id2/etl/salida/real' x("CREATE TABLE ce AS SELECT * FROM '/w/interno/concedente_ente.parquet'") x("CREATE TABLE ee AS SELECT * FROM '/w/interno/entidad_ente.parquet'") x("CREATE TABLE nom AS SELECT ente, string_agg(DISTINCT nombre, ' || ') nombres FROM ee GROUP BY 1") # (e) concedente -> ente cas = x("SELECT cid, via, n FROM ce WHERE motivo_sin IS NULL ORDER BY cid").fetchall() cuota = {'V2_dir3_nombre': 17, 'V1_invente': 10, 'V4_nombre_nuestro': 3, 'V3_ministerio': 0} rnd = random.Random(SEM); sel = [] for v, k in cuota.items(): pool = [r[0] for r in cas if r[1] == v]; sel += rnd.sample(pool, min(k, len(pool))) x("CREATE TABLE se (cid BIGINT)"); c.executemany("INSERT INTO se VALUES (?)", [(s,) for s in sel]) rows = x(f"""SELECT ce.cid, ce.via, ce.nivel1, ce.nivel2, ce.nivel3, ce.inv, ce.n, ce.ente, nom.nombres, (SELECT string_agg(DISTINCT d.nombre || ' [' || d.codigo || ']', ' || ') FROM '{R}/dir3_unidades.parquet' d WHERE d.nif = ce.ente) dir3_mismo_nif, (SELECT string_agg(DISTINCT e.nombre, ' || ') FROM '{R}/entes.parquet' e WHERE e.nif = ce.ente) invente_mismo_nif FROM se JOIN ce USING (cid) LEFT JOIN nom ON nom.ente = ce.ente ORDER BY ce.via, ce.cid""").fetchall() with open('/w/interno/cotejo_e.csv', 'w', newline='') as fh: w = csv.writer(fh); w.writerow(['cid', 'via', 'nivel1', 'nivel2', 'nivel3', 'codigoInvente', 'filas', 'ente', 'nombres_nuestros', 'dir3_mismo_nif', 'invente_mismo_nif']) for r in rows: w.writerow([(s[:400] if isinstance(s, str) else s) for s in r]) # (d) casados (ente, empresa, año) x("CREATE TABLE dob AS SELECT * FROM '/w/interno/doble.parquet'") x("CREATE TABLE sf AS SELECT * FROM '/w/interno/s_filas.parquet' WHERE ente IS NOT NULL") x("CREATE TABLE sfn AS SELECT sf.*, ce.nivel1 FROM sf JOIN ce USING (cid)") x("""CREATE TABLE grp AS SELECT d.ente, d.anio, d.empresa_clave, CASE WHEN min(s.nivel1)='LOCAL' THEN 'LOCAL' WHEN min(s.nivel1)='AUTONOMICA' THEN 'AUTONOMICA' ELSE 'ESTADO_OTROS' END g FROM dob d JOIN sfn s ON s.ente=d.ente AND s.anio=d.anio AND s.cif=d.empresa_clave GROUP BY ALL ORDER BY 1,2,3""") pares = x("SELECT ente, anio, empresa_clave, g FROM grp").fetchall() rnd = random.Random(SEM); rnd.shuffle(pares) usados = set(); muestra = []; cuota = {'LOCAL': 10, 'AUTONOMICA': 10, 'ESTADO_OTROS': 10} for p in pares: if p[0] in usados or cuota[p[3]] == 0: continue usados.add(p[0]); cuota[p[3]] -= 1; muestra.append(p) if sum(cuota.values()) == 0: break x("CREATE TABLE md (ente VARCHAR, anio INTEGER, empresa_clave VARCHAR, g VARCHAR)"); c.executemany("INSERT INTO md VALUES (?,?,?,?)", muestra) x("""CREATE TABLE ms AS SELECT md.*, arg_min(s.id, s.id) sid FROM md JOIN sf s ON s.ente=md.ente AND s.anio=md.anio AND s.cif=md.empresa_clave GROUP BY ALL""") x("""CREATE TABLE mc AS SELECT md.ente, md.anio, md.empresa_clave, arg_min(c.id_canonical, c.id_canonical) idc, arg_min(c.source, c.id_canonical) src FROM md JOIN '/w/interno/c_filas.parquet' c ON c.ente=md.ente AND c.anio=md.anio AND c.empresa_clave=md.empresa_clave AND c.emp_principal GROUP BY ALL""") x("""CREATE TABLE braw AS SELECT id, beneficiario, nivel1, nivel2, nivel3, codigoInvente, fechaConcesion, importe FROM read_json('/bdns/concesiones/*/*.jsonl.gz', format='newline_delimited', union_by_name=true, columns={id:'VARCHAR',beneficiario:'VARCHAR',nivel1:'VARCHAR',nivel2:'VARCHAR',nivel3:'VARCHAR',codigoInvente:'VARCHAR',fechaConcesion:'VARCHAR',importe:'VARCHAR'}) WHERE id IN (SELECT sid FROM ms)""") x("""CREATE TABLE uraw AS SELECT source, id_canonical, adjudicatario_nif_raw, adjudicatario_nombre_raw, organo_nombre, organo_nif, dir3, anio_ref, imp_adj_eur_corregido, objeto, url_origen FROM read_parquet('/d/unified_20261018/**/*.parquet', hive_partitioning=1, union_by_name=1) WHERE id_canonical IN (SELECT idc FROM mc)""") rows = x("""SELECT ms.g, ms.ente, nom.nombres, ms.anio, ms.empresa_clave, b.beneficiario, b.nivel1, b.nivel2, b.nivel3, b.codigoInvente, b.fechaConcesion, b.importe, u.source, u.id_canonical, u.adjudicatario_nif_raw, u.adjudicatario_nombre_raw, u.organo_nombre, u.organo_nif, u.dir3, u.anio_ref, u.imp_adj_eur_corregido, left(u.objeto, 120) FROM ms JOIN mc USING (ente, anio, empresa_clave) LEFT JOIN braw b ON b.id = ms.sid LEFT JOIN uraw u ON u.id_canonical = mc.idc LEFT JOIN nom ON nom.ente = ms.ente ORDER BY ms.g, ms.ente""").fetchall() cols = ['grupo', 'ente', 'nombres_ente', 'anio', 'nif_empresa', 'bdns_beneficiario', 'bdns_nivel1', 'bdns_nivel2', 'bdns_nivel3', 'bdns_invente', 'bdns_fecha', 'bdns_importe', 'u_source', 'u_id', 'u_adj_nif_raw', 'u_adj_nombre_raw', 'u_organo_nombre', 'u_organo_nif', 'u_dir3', 'u_anio_ref', 'u_importe', 'u_objeto'] with open('/w/interno/cotejo_d.csv', 'w', newline='') as fh: w = csv.writer(fh); w.writerow(cols) for r in rows: w.writerow([(s[:300] if isinstance(s, str) else s) for s in r]) print('e', len(sel), 'd', len(rows), cuota)