"""CPV1-v2 · paso 50 (etl:v2, DuckDB): las muestras del cotejo a ciegas (pre-registro v2 §2). Escribe en interno/cotejo/ (700): ciega.tsv lo que ve el lector (n, fuente, año, órgano, tipo, importe, objeto): SIN la estimación clave.tsv la estimación de cada n y su muestra (no se abre hasta haber sellado etiquetas.tsv) E: 50 emitidas de O 2026 ('cpv1v2-cotejo-50', reparto por fuente proporcional a las emitidas, restos mayores, ≥ 1 para fuentes con ≥ 1 %); S: 10 emitidas del Servicio Gallego de Salud en GALICIA ('cpv1v2-cotejo-sergas', sin repetir las de E); N: 20 no emitidas ('cpv1v2-cotejo-20', mismo reparto). Ninguna puede estar en el cotejo de la v1 (se comprueba).""" import duckdb, math, sys, random P = '/w/interno/pred'; D = '/w/interno/datos'; C = '/w/interno/cotejo' V1 = '/w/interno/cotejo/v1_ids.txt' # los id de las 70 filas del cotejo de la v1 (de su clave.tsv) pred = sys.argv[1] # final__f25fu_t0.1__O2026 con = duckdb.connect() con.execute("SET memory_limit='4GB'; SET threads=3; SET temp_directory='/w/tmp/duck'; SET max_temp_directory_size='5GB'") rd = lambda p: f"read_csv('{p}', delim='\t', header=true, quote='', escape='', all_varchar=true)" con.execute(f"CREATE TABLE p AS SELECT * FROM {rd(P + '/' + pred + '.tsv')}") con.execute(f"""CREATE TABLE x AS SELECT p.*, o.imp_adj_eur, o.objeto, n.organo_nombre FROM p JOIN {rd(D + '/O2026.tsv')} o ON o.id_canonical = p.id JOIN {rd(D + '/organo_nombre.tsv')} n ON n.id = p.id""") print('filas', con.execute("SELECT count(*), (SELECT count(*) FROM p) FROM x").fetchone()) SERGAS = """source = 'GALICIA' AND (upper(organo_nombre) LIKE '%SERVIZO GALEGO DE SA%' OR upper(organo_nombre) LIKE '%SERVICIO GALLEGO DE SALUD%' OR upper(organo_nombre) LIKE '%SERGAS%')""" print('SERGAS en O 2026 puntuadas / emitidas', con.execute(f"SELECT count(*), count(*) FILTER (WHERE emitida = '1') FROM x WHERE {SERGAS}").fetchone()) def reparto(emit, n, sal, extra='TRUE', excluir=()): cnt = dict(con.execute(f"SELECT source, count(*) FROM x WHERE emitida = '{emit}' AND {extra} GROUP BY 1").fetchall()) tot = sum(cnt.values()) base = {s: (1 if c / tot >= 0.01 else 0) for s, c in cnt.items()} resto = n - sum(base.values()) cuota = {s: resto * c / tot for s, c in cnt.items()} asig = {s: base[s] + int(math.floor(cuota[s])) for s in cnt} falta = n - sum(asig.values()) for s in sorted(cnt, key=lambda s: -(cuota[s] - math.floor(cuota[s])))[:falta]: asig[s] += 1 filas = [] # sin exclusiones, ninguna condición: «id NOT IN (NULL)» no deja pasar ninguna fila (3-nov: la primera pasada se quedó sin muestra) ex = ("AND id NOT IN (" + ", ".join("'" + i.replace("'", "''") + "'" for i in excluir) + ")") if excluir else "" for s, k in sorted(asig.items()): if k: filas += con.execute(f"""SELECT source, anio, organo_nombre, tipo, imp_adj_eur, objeto, id, d1, p1, d2, d3, emitida, regimen FROM x WHERE emitida = '{emit}' AND source = '{s}' AND {extra} {ex} ORDER BY hash(id || '{sal}'), id LIMIT {k}""").fetchall() return asig, filas a50, f50 = reparto('1', 50, 'cpv1v2-cotejo-50') assert len(f50) == 50, len(f50) ns = con.execute(f"SELECT count(*) FROM x WHERE emitida = '1' AND {SERGAS}").fetchone()[0] fs = con.execute(f"""SELECT source, anio, organo_nombre, tipo, imp_adj_eur, objeto, id, d1, p1, d2, d3, emitida, regimen FROM x WHERE emitida = '1' AND {SERGAS} {("AND id NOT IN (" + ", ".join("'" + f[6].replace("'", "''") + "'" for f in f50) + ")") if f50 else ""} ORDER BY hash(id || 'cpv1v2-cotejo-sergas'), id LIMIT 10""").fetchall() a20, f20 = reparto('0', 20, 'cpv1v2-cotejo-20') print('reparto 50', a50); print('SERGAS emitidas', ns, 'en la muestra', len(fs)); print('reparto 20', a20) v1 = set() try: with open(V1, encoding='utf-8') as f: v1 = {l.rstrip('\n') for l in f if l.strip()} except FileNotFoundError: pass ids = [f[6] for f in f50 + fs + f20] assert len(ids) == len(set(ids)), 'repetidas' assert not (set(ids) & v1), 'filas del cotejo de la v1' print('ninguna en el cotejo de la v1 (', len(v1), 'filas)') todas = [('E', f) for f in f50] + [('S', f) for f in fs] + [('N', f) for f in f20] random.Random(20261103).shuffle(todas) # el lector no sabe cuáles son emitidas ni de qué muestra lim = lambda v: ('' if v is None else str(v)).replace('\t', ' ').replace('\n', ' ').replace('\r', ' ') with open(f'{C}/ciega.tsv', 'w', encoding='utf-8') as fc, open(f'{C}/clave.tsv', 'w', encoding='utf-8') as fk: fc.write('n\tfuente\tanio\torgano\ttipo\timporte\tobjeto\n') fk.write('n\tmuestra\tid\td1\tp1\td2\td3\temitida\tregimen\n') for i, (m, f) in enumerate(todas, 1): fc.write('\t'.join(lim(v) for v in (i,) + f[:6]) + '\n') fk.write('\t'.join(lim(v) for v in (i, m) + f[6:]) + '\n') print('escritas', len(todas))