"""MOD-EJEC · 53 · muestra de confirmación de la enmienda A del PREREG_2 (md5 fb55fcd8…): por fuente (RPC, Madrid y, para información, PSCP), contratos con y = 1 de órganos con n >= 30, sin ninguno de priv/sob_muestra.json, en el orden de md5('20261104|conf|' || id). Principal 20: <= 4 por año, órganos distintos mientras queden y una segunda vuelta admitiendo repetidos si no llegan. Reserva 10: las siguientes en ese orden, sin tope. Con lo nuestro: A, las modificaciones y la fila de origen. -> priv/sob_muestra_conf.json (700)""" import duckdb, json c = duckdb.connect(); x = c.execute x("SET threads=2; SET memory_limit='1500MB'") D = '/d/unified_20261103' vistos = {f: {m['id'] for m in v} for f, v in json.load(open('/w/priv/sob_muestra.json')).items()} x("CREATE TABLE cc AS SELECT * FROM '/w/priv/sob_contratos.parquet'") x("CREATE TABLE og AS SELECT * FROM '/w/priv/sob_organos.parquet' WHERE n >= 30") x("CREATE TABLE cand AS SELECT cc.*, md5('20261104|conf|' || cc.id) h FROM cc JOIN og USING (fuente, organo_clave) WHERE cc.y") M = {}; disponibles = {} for f in ('RPC', 'MADRID', 'PSCP'): filas = [r for r in x("SELECT id, organo_clave, anio, A, s_mod, nmod, h FROM cand WHERE fuente = ? ORDER BY h", [f]).fetchall() if r[0] not in vistos[f]] disponibles[f] = len(filas) prin, anios, orgs = [], {}, set() for i, o, a, A, s, nm, h in filas: # primera vuelta: órganos distintos if len(prin) < 20 and anios.get(a, 0) < 4 and o not in orgs: anios[a] = anios.get(a, 0) + 1; orgs.add(o); prin.append(i) if len(prin) < 20: # segunda vuelta: admite órganos repetidos, sigue el tope por año for i, o, a, A, s, nm, h in filas: if len(prin) < 20 and i not in prin and anios.get(a, 0) < 4: anios[a] = anios.get(a, 0) + 1; prin.append(i) res = [r[0] for r in filas if r[0] not in prin][:10] por_id = {r[0]: r for r in filas} M[f] = [{'id': i, 'organo_clave': por_id[i][1], 'anio': por_id[i][2], 'A': por_id[i][3], 's_mod': por_id[i][4], 'nmod': por_id[i][5], 'reserva': i in res} for i in prin + res] ids = {f: [m['id'] for m in M[f]] for f in M} src = {'RPC': 'CATALUNYA', 'PSCP': 'CATALUNYA_PSCP', 'MADRID': 'MADRID_AYTO'} for f, s in src.items(): fil = dict((r[0], r[1:]) for r in x(f"""SELECT id_canonical, fila_origen, expediente, organo_nombre, organo_nif, adjudicatario_nombre IS NOT NULL FROM read_parquet('{D}/source={s}/**/*.parquet', hive_partitioning=1, union_by_name=1) WHERE id_canonical IN (SELECT unnest(?))""", [ids[f]]).fetchall()) mods = {} for i, fe, imp in x(f"""SELECT DISTINCT id_canonical, fecha, importe_cambio FROM '{D}.cambios/cambios.parquet' WHERE fuente = ? AND tipo = 'modificacion' AND coalesce(importe_cambio, 0) <> 0 AND id_canonical IN (SELECT unnest(?)) ORDER BY 1, 2, 3""", [s, ids[f]]).fetchall(): mods.setdefault(i, []).append([str(fe), imp]) for m in M[f]: fo = fil[m['id']]; m.update(fila_origen=fo[0], expediente=fo[1], organo_nombre=fo[2], organo_nif=fo[3], mods=mods.get(m['id'], [])) assert len(m['mods']) == m['nmod'], m json.dump(M, open('/w/priv/sob_muestra_conf.json', 'w'), ensure_ascii=False, indent=1, default=str) print({f: {'disponibles': disponibles[f], 'principal': sum(not m['reserva'] for m in v), 'reserva': sum(m['reserva'] for m in v), 'organos_principal': len({m['organo_clave'] for m in v if not m['reserva']}), 'solapa': len(set(ids[f]) & vistos[f])} for f, v in M.items()})