"""ETIQ-3 · E9 · impl. 2 · N publicado por entidad-año sin DuckDB (pyarrow.compute: filtros, Table.join, group_by). Universo de la web (NOT es_copia), unidad adjudicación, sin anulados; órgano → entidad por organos_filas (claves nulas casan con nulas, como IS NOT DISTINCT FROM); año = año(coalesce(formalización, adjudicación)) o anio_ref. Uso (etiq3-pub2): python3 -I pub_i2.py """ import sys, os, time import pyarrow as pa, pyarrow.compute as pc, pyarrow.parquet as pq, pyarrow.dataset as ds D = '/d/unified_20261025' SAL = sys.argv[1] NUL = '\x00' vin = pq.read_table('/d/aggregations_20261025/vinculos_filas.parquet', columns=['id_canonical', 'cuenta']) no_cuenta = pc.unique(vin.filter(pc.invert(pc.fill_null(vin['cuenta'], True)))['id_canonical']) of = pq.read_table(f'{D}.identidad/organos_filas.parquet', columns=['organo_nif', 'organo_nombre', 'dir3', 'entidad_clave']) of = pa.table({'k1': pc.fill_null(of['organo_nif'], NUL), 'k2': pc.fill_null(of['organo_nombre'], NUL), 'k3': pc.fill_null(of['dir3'], NUL), 'entidad_clave': of['entidad_clave']}) COLS = ['unidad', 'anulado_en_origen', 'copia_de', 'correccion_imp_adj', 'id_canonical', 'organo_nif', 'organo_nombre', 'dir3', 'fecha_formalizacion', 'fecha_adj', 'anio_ref', 'es_menor'] partes = [] t0 = time.time() for src in sorted(os.listdir(D)): S = src.split('=')[1] d = ds.dataset(f'{D}/{src}', format='parquet', partitioning='hive') cols = [c for c in COLS if c in d.schema.names] t = d.to_table(columns=cols, filter=ds.field('unidad') == 'adjudicacion') for c in COLS: if c not in t.column_names: t = t.append_column(c, pa.nulls(len(t), pa.string() if c not in ('anulado_en_origen', 'es_menor') else pa.bool_())) m = pc.and_(pc.invert(pc.fill_null(t['anulado_en_origen'], False)), pc.is_null(t['copia_de'])) m = pc.and_(m, pc.invert(pc.fill_null(pc.equal(t['correccion_imp_adj'], 'copia_otra_fuente'), False))) m = pc.and_(m, pc.invert(pc.is_in(t['id_canonical'], value_set=no_cuenta))) t = t.filter(m) f = pc.coalesce(t['fecha_formalizacion'], t['fecha_adj']) anio = pc.coalesce(pc.cast(pc.year(f), pa.int64()), pc.cast(t['anio_ref'], pa.int64())) x = pa.table({'k1': pc.fill_null(t['organo_nif'], NUL), 'k2': pc.fill_null(t['organo_nombre'], NUL), 'k3': pc.fill_null(t['dir3'], NUL), 'anio': anio, 'menor': pc.cast(pc.fill_null(t['es_menor'], False), pa.int64()), 'placsp': pa.array([1 if S == 'PLACSP' else 0] * len(t), pa.int64())}) x = x.join(of, keys=['k1', 'k2', 'k3'], join_type='left outer') x = x.filter(pc.and_(pc.is_valid(x['entidad_clave']), pc.and_(pc.greater_equal(x['anio'], 2017), pc.less_equal(x['anio'], 2024)))) g = x.group_by(['entidad_clave', 'anio']).aggregate([('menor', 'count'), ('menor', 'sum'), ('placsp', 'sum')]) partes.append(g) print(S, len(t), len(x), f'{time.time() - t0:.0f}s', flush=True) todo = pa.concat_tables(partes).group_by(['entidad_clave', 'anio']).aggregate([('menor_count', 'sum'), ('menor_sum', 'sum'), ('placsp_sum', 'sum')]) todo = todo.rename_columns(['entidad_clave', 'anio', 'n', 'n_menores', 'n_placsp'][:0] + [c for c in todo.column_names]) import csv with open(SAL, 'w', newline='') as fh: w = csv.writer(fh); w.writerow(['nif', 'anio', 'n', 'n_menores', 'n_placsp']) cols = {c: todo[c].to_pylist() for c in todo.column_names} names = todo.column_names ie, ia = names.index('entidad_clave'), names.index('anio') for row in zip(*[cols[c] for c in names]): d = dict(zip(names, row)) w.writerow([d['entidad_clave'], d['anio'], d['menor_count_sum'], d['menor_sum_sum'], d['placsp_sum_sum']]) print('ok', len(todo), f'{time.time() - t0:.0f}s')