"""TL-T5-118-E2 · 24_impl2_e2: segunda implementación SIN DuckDB (pyarrow + Python) de la ENM2. Compara por casilla y año con priv/pob_e2_desc_*.parquet (recuento, K y firma id|k|U). Uso: 24_impl2_e2.py desc""" import pyarrow.parquet as pq, pyarrow.compute as pc, json, sys, glob, hashlib, time, unicodedata, datetime as dt, collections, math, re sys.path.insert(0, '/o/py'); import reglas as R, agente as A, e2_reglas as E T0 = time.time(); modo = sys.argv[1]; U = '/d/unified_20261108'; CAS = [c for c in R.DESC if c != 'LA_RIOJA'] RX_AG = re.compile(A.R_AGENTE + '|' + E.P['AG_OTRO']) def nrm(s): return ''.join(ch for ch in unicodedata.normalize('NFKD', s or '') if not unicodedata.combining(ch)).lower() def r10(x): return math.floor(abs(x) / 10 + 0.5) * 10 * (1 if x >= 0 else -1) def h(i, k, u): return int.from_bytes(hashlib.blake2b(f"{i}|{int(k)}|{int(u)}".encode(), digest_size=8).digest(), 'big') def cerca(a, b, t): return a is not None and b is not None and abs(a - b) <= t COLS = ['id_canonical', 'es_menor', 'iva_base', 'imp_adj_eur', 'imp_adj_eur_sin_iva', 'imp_adj_eur_con_iva', 'imp_lic_eur', 'imp_lic_eur_con_iva', 'valor_estimado_eur', 'cpv_code', 'organo_nombre', 'objeto', 'fecha_pub', 'expediente', 'adjudicatario_nif', 'fecha_adj'] out = {'modo': modo, 'casillas': {}}; cand_all = []; agg_all = {} for o, f in enumerate(CAS): pe = {} for b in pq.ParquetFile(f'/o/priv/pob_e1_{modo}_{f}.parquet').iter_batches(200000, columns=['id_canonical', 'anio', 'tipo_contrato', 'base', 'agente_etl']): d = b.to_pydict() for i, y, t, bs, ae in zip(d['id_canonical'], d['anio'], d['tipo_contrato'], d['base'], d['agente_etl']): pe[i] = (y, t, bs, ae) agg = collections.defaultdict(lambda: [0, 0, 0]); cand = [] for fn in sorted(glob.glob(f'{U}/source={f}/**/*.parquet', recursive=True)): pf = pq.ParquetFile(fn); sc = pf.schema_arrow.names for b in pf.iter_batches(100000, columns=[c for c in COLS if c in sc]): b = b.filter(pc.equal(b.column('es_menor'), True)); d = b.to_pydict() for j in range(b.num_rows): i = d['id_canonical'][j]; v = pe.get(i) if v is None: continue y, t, bs, ae = v; x = {c: (d[c][j] if c in d else None) for c in COLS} ag = bool(ae) or bool(RX_AG.search(E.R['DUD'].sub('', nrm(x['organo_nombre'])))) u = R.U_OBRAS if t == 'Obras' else (R.U_AGENTE if ag else R.U_SS) if bs > 10 * u: continue if bs > u: cand.append((i, y, t, bs, ag, u, x)) else: a = agg[int(y)]; a[0] += 1; a[2] = (a[2] + h(i, False, u)) % (1 << 64) del pe # marcas (lógica reescrita en Python a partir del texto del escéptico) sobre los candidatos a K gr = collections.defaultdict(set); dupk = collections.defaultdict(list) for i, y, t, bs, ag, u, x in cand: gr[(nrm(x['organo_nombre']) if False else x['organo_nombre'], round(bs, 2), y)].add((x['objeto'] or '').lower()) dupk[(x['organo_nombre'], x['adjudicatario_nif'], r10(bs * 1) if False else math.floor(abs(bs) + 0.5), str(x['fecha_adj']) if x['fecha_adj'] is not None else (x['objeto'] or '').lower())].append(i) dups = {i for v in dupk.values() for i in sorted(v)[1:]} rep = {(org, bb) for (org, bb, yy), objs in gr.items() if len(objs) >= 3} # como el SQL: el grupo es de un año, la marca no mira el año fuera_c = collections.Counter(); res = [] for i, y, t, bs, ag, u, x in cand: sin = x['imp_adj_eur_sin_iva'] if x['imp_adj_eur_sin_iva'] is not None else x['imp_adj_eur']; con_ = x['imp_adj_eur_con_iva']; lic = x['imp_lic_eur']; ve = x['valor_estimado_eur'] ob = nrm(x['objeto']); on = nrm(x['organo_nombre']); sinb = x['iva_base'] == 'sin'; banda = bs <= 1.21 * u m = {} m['t1_redondeo'] = sinb and banda and con_ is not None and sin is not None and 0.01 <= abs(con_ - sin) <= 0.999 m['t1_ppto'] = banda and (cerca(bs, None if lic is None else 1.21 * lic, 1) or (x['imp_lic_eur_con_iva'] is not None and lic is not None and x['imp_lic_eur_con_iva'] > lic + 1 and cerca(bs, x['imp_lic_eur_con_iva'], 1)) or cerca(bs, None if ve is None else 1.21 * ve, 1)) m['t1_x121'] = sinb and banda and abs(bs / 1.21 - r10(bs / 1.21)) < 0.006 and abs(bs - r10(bs)) >= 0.006 m['t3_noaapp'] = bool(E.R['NOAAPP'].search(on)) m['t4_texto'] = bool(E.R['T4'].search(ob)); m['t4_mes'] = bool(E.R['T4MES'].search(ob)) and not m['t4_texto'] m['t4_repetido'] = (x['organo_nombre'], round(bs, 2)) in rep m['t5_da9'] = bs < 221000 and bool(E.R['DA9'].search(ob)); m['t5_instr'] = bool(E.R['INSTR'].search(ob)); m['t5_dup'] = i in dups m['t6_escala'] = any(z is not None and z > 0 and (9.5 <= bs / z <= 10.5 or 95 <= bs / z <= 105 or 950 <= bs / z <= 1050) for z in (lic, ve)) m['t6_con_absurdo'] = sinb and con_ is not None and sin is not None and 0 < con_ < 0.5 * sin fp = x['fecha_pub']; fp = fp.date() if hasattr(fp, 'date') and not isinstance(fp, dt.date) or isinstance(fp, dt.datetime) else fp m['t7_fecha'] = ((fp is not None and fp < dt.date(2018, 3, 9)) or bool(E.R['T7_EXP'].search(nrm(x['expediente']))) or bool(E.R['T7_OBJ'].search(ob))) and bs <= (50000 if t == 'Obras' else 18000) nok = (t != 'Obras' and not ag and bs <= 40000 and ((x['cpv_code'] or '')[:2] == '45' or (bool(E.R['OBRA_SI'].search(ob)) and not E.R['OBRA_NO'].search(ob)))) or (t != 'Obras' and not ag and bs <= 50000 and bool(E.R['AG_OTRO'].search(on))) fuera = any(m.values()) for k_, v_ in m.items(): fuera_c[k_] += v_ res.append((i, y, bs, u, x['adjudicatario_nif'], fuera, (not fuera) and (not nok))) cand_all.append((o, f, res)); agg_all[f] = agg; out['casillas'][f] = {'marcas': dict(fuera_c), 'candidatos': len(cand)} print(f, len(cand), f'{time.time() - T0:.0f}s', flush=True) # espejos K-K grupos = collections.defaultdict(set) for o, f, res in cand_all: for i, y, bs, u, nif, fuera, k in res: if k and nif: grupos[(nif, round(bs, 2), y)].add(o) for o, f, res in cand_all: agg = agg_all[f]; esp = 0 for i, y, bs, u, nif, fuera, k in res: if fuera: continue if k and nif and len(grupos[(nif, round(bs, 2), y)]) > 1 and o > min(grupos[(nif, round(bs, 2), y)]): esp += 1; continue a = agg[int(y)]; a[0] += 1; a[1] += k; a[2] = (a[2] + h(i, k, u)) % (1 << 64) cmp_ = collections.defaultdict(lambda: [0, 0, 0]) for b in pq.ParquetFile(f'/o/priv/pob_e2_{modo}_{f}.parquet').iter_batches(200000, columns=['id_canonical', 'anio', 'k', 'umbral']): d = b.to_pydict() for i, y, k, u in zip(d['id_canonical'], d['anio'], d['k'], d['umbral']): c = cmp_[int(y)]; c[0] += 1; c[1] += k; c[2] = (c[2] + h(i, k, u)) % (1 << 64) dif = {y: {'impl2': agg[y][:2], 'medida': cmp_[y][:2], 'firma_igual': agg[y][2] == cmp_[y][2]} for y in sorted(set(agg) | set(cmp_))} out['casillas'][f].update(N=sum(v[0] for v in agg.values()), K=sum(v[1] for v in agg.values()), espejos=esp, por_anio=dif, diferencias=sum(1 for v in dif.values() if not v['firma_igual'] or v['impl2'] != v['medida'])) print(f, out['casillas'][f]['N'], out['casillas'][f]['K'], 'dif', out['casillas'][f]['diferencias'], flush=True) out['segundos'] = round(time.time() - T0) json.dump(out, open(f'/o/salidas/24_impl2_e2_{modo}.json', 'w'), ensure_ascii=False, indent=1, default=str); print('fin', out['segundos'])