"""E1c · muestra del cotejo (DEFINICIONES_PREVIAS §7.1, semilla 2026102103): 20 anuncios con dato_desierto, 2 parecidas por anuncio (una desierta y una adjudicada si las hay) y el nivel B (todas las parecidas si N <= 150; si no, 150 al azar). Módulo 5e584bd; los anuncios salen de /tmpw/impl1/anuncios.parquet. Escribe /cotejo/muestra_{anuncios,A,B}.csv y /out/03_muestra.json.""" import csv, json, random from pathlib import Path from etl.v2 import exante_l1 as ex U = Path('/d/unified_20261018'); S = U.parent con = ex.conexion('6GB', 6, Path('/tmpw/duck_m')) ex.paso_entrada(con, U, S / 'unified_20261018.identidad', S / 'unified_20261018.criterios', S / 'unified_20261018.documentos', Path('/sat/unified_20261018.cpvs')) ex.paso_lotes(con) con.execute("""CREATE TEMP TABLE an AS SELECT * FROM (SELECT *, row_number() OVER (PARTITION BY licitacion_id ORDER BY lote_u) rn FROM read_parquet('/tmpw/impl1/anuncios.parquet')) WHERE rn = 1""") universo = [r[0] for r in con.execute("""SELECT licitacion_id FROM an WHERE dato_desierto AND ffo >= DATE '2026-10-18' ORDER BY licitacion_id""").fetchall()] rng = random.Random(2026102103) muestra = rng.sample(universo, 20) cols_l = ['licitacion_id', 'lote_u', 'num_ofertas', 'adjudicado', 'desierto', 'desistido', 'anio_ref', 'fecha_adj', 'organo_clave', 'organo_nom', 'cpv_cel', 'cpv_divisiones', 'organo_nif', 'organo_nombre', 'dir3', 'url_origen', 'filas'] con.execute(f"""CREATE TEMP TABLE ln AS SELECT {', '.join(cols_l)} FROM x_lotes WHERE feed = 'propio' AND organo_clave IS NOT NULL AND anio_ref BETWEEN 2023 AND 2025 AND (adjudicado OR desierto) AND coalesce(cpv_ok, FALSE)""") fan, fA, fB = [], [], [] for i, lid in enumerate(muestra, 1): a = dict(zip(['licitacion_id', 'lote_u', 'organo_clave', 'organo_nom', 'cpv_cel', 'ffo', 'N', 'X'], con.execute( "SELECT licitacion_id, lote_u, organo_clave, organo_nom, cpv_cel, ffo, n_parecidas_desierto, k_desiertas FROM an WHERE licitacion_id = ?", [lid]).fetchone())) u = con.execute("""SELECT url_origen, organo_nombre, organo_nif, dir3, cpv_code, expediente, id_canonical FROM x_u WHERE licitacion_id = ? AND tabla_origen = 'licitaciones_sin_resultado' ORDER BY id_canonical LIMIT 1""", [lid]).fetchone() a.update(dict(zip(['url', 'organo_nombre', 'organo_nif', 'dir3', 'cpv_code', 'expediente', 'id_canonical'], u))) lotes = [dict(zip(cols_l, r)) for r in con.execute(f"""SELECT {', '.join(cols_l)} FROM ln WHERE organo_clave = ? AND organo_nom IS NOT DISTINCT FROM ? AND cpv_cel = ? ORDER BY licitacion_id, lote_u""", [a['organo_clave'], a['organo_nom'], a['cpv_cel']]).fetchall()] n = len(lotes); x = sum(1 for l in lotes if l['desierto'] and not l['adjudicado']) assert (n, x) == (a['N'], a['X']), (lid, n, x, a['N'], a['X']) D = [l for l in lotes if l['desierto'] and not l['adjudicado']]; A = [l for l in lotes if l['adjudicado']] p1 = rng.choice(D) if D else rng.choice(A) pool = A if A else D otros = [l for l in pool if l['licitacion_id'] != p1['licitacion_id'] and l is not p1] p2 = rng.choice(otros) if otros else rng.choice([l for l in pool if l is not p1]) for k, l in enumerate((p1, p2), 1): fA.append({'anuncio': i, 'k': k, **l}) bl = lotes if n <= 150 else rng.sample(lotes, 150) for l in bl: fB.append({'anuncio': i, **l}) fan.append({'anuncio': i, 'n_B': len(bl), **a}) def escribe(nombre, filas): with open(f'/cotejo/{nombre}', 'w', newline='') as f: w = csv.DictWriter(f, fieldnames=list(filas[0])); w.writeheader(); w.writerows(filas) escribe('muestra_anuncios.csv', fan); escribe('muestra_A.csv', fA); escribe('muestra_B.csv', fB) inf = {'universo': len(universo), 'anuncios': len(fan), 'parecidas_A': len(fA), 'A_desiertas': sum(1 for l in fA if l['desierto'] and not l['adjudicado']), 'A_con_lote': sum(1 for l in fA if l['lote_u'] != l['licitacion_id']), 'parecidas_B': len(fB), 'B_desiertas': sum(1 for l in fB if l['desierto'] and not l['adjudicado']), 'B_licitaciones': len({l['licitacion_id'] for l in fB}), 'anuncios_completos': sum(1 for a in fan if a['N'] <= 150)} json.dump(inf, open('/out/03_muestra.json', 'w'), indent=1, default=str) print(json.dumps(inf, indent=1)) for a in fan: print(a['anuncio'], a['licitacion_id'], (a['organo_nom'] or '')[:50], a['cpv_cel'], 'N', a['N'], 'X', a['X'], 'B', a['n_B'])