# TL-T5-118-E1 (ENM1) · 31_cotejo_e1: copia de 30_cotejo.py (16a52f92) sobre pob_e1, semilla |tl-t5-118-e1|, sin los 40 casos del cotejo anterior. """TL-T5-118 · 30_cotejo: 30 de K(V1) + 10 de control de la casilla PLACSP (descubrimiento) contra los ZIP de la sindicación 1143 en disco (todas las versiones guardadas). Muestra con semilla sellada '|tl-t5-118|PLACSP|desc': los 30, estratificados por tramo de exceso en proporción a K (resto mayor); los 10, al azar de la población con base en [0,8·U; U]. Clasifica cada caso (prereg §10). Salidas: /o/priv/cotejo_desc.json, /o/priv/orig/PLACSP//v_*.xml (700) y /o/salidas/30_cotejo_desc.json (solo recuentos). Uso: 30_cotejo.py [desc]""" import duckdb, json, random, hashlib, os, re, zipfile, collections, time, sys import xml.etree.ElementTree as ET T0 = time.time(); modo = sys.argv[1] if len(sys.argv) > 1 else 'desc'; CEL = 'PLACSP' semilla = int(hashlib.md5(f'|tl-t5-118-e1|{CEL}|{modo}'.encode()).hexdigest(), 16); rnd = random.Random(semilla) con = duckdb.connect(config={'memory_limit': '1000MB', 'threads': 2}) pob = f'/o/priv/pob_e1_{modo}_{CEL}.parquet' k = con.execute(f"SELECT id_canonical, anio, tipo_contrato, agente, cota, base, umbral, CASE WHEN base <= 1.21*umbral THEN 'a' WHEN base <= 2*umbral THEN 'b' ELSE 'c' END t FROM read_parquet('{pob}') WHERE k ORDER BY id_canonical").fetchall() ctl = con.execute(f"SELECT id_canonical, anio, tipo_contrato, agente, cota, base, umbral, 'ctl' t FROM read_parquet('{pob}') WHERE NOT k AND base >= 0.8*umbral ORDER BY id_canonical").fetchall() prev = {x['id'] for x in json.load(open('/o/priv/cotejo_desc.json'))}; k = [r for r in k if r[0] not in prev]; ctl = [r for r in ctl if r[0] not in prev] # casos nuevos K = ['id', 'anio', 'tipo', 'agente', 'cota', 'base', 'umbral', 'tramo'] por = collections.defaultdict(list) for r in k: por[r[7]].append(r) cuota = {t: 30 * len(v) / len(k) for t, v in por.items()}; n = {t: int(c) for t, c in cuota.items()} for t in sorted(cuota, key=lambda t: -(cuota[t] - n[t]))[:30 - sum(n.values())]: n[t] += 1 mu = [dict(zip(K, r), grupo='k') for t in sorted(por) for r in rnd.sample(por[t], n[t])] + [dict(zip(K, r), grupo='control') for r in rnd.sample(ctl, 10)] assert len(mu) == 40 # metadatos de la construcción para cada caso ids = [m['id'] for m in mu] meta = {r[0]: r[1:] for r in con.execute("""SELECT id_canonical, fecha_adj, organo_nombre, organo_nif, objeto, imp_adj_eur, iva_base, url_origen FROM read_parquet('/d/unified_20261108/source=PLACSP/**/*.parquet', hive_partitioning=true, union_by_name=true) WHERE id_canonical IN (SELECT unnest(?))""", [ids]).fetchall()} for m in mu: fa, on, onif, ob, imp, iva, url = meta[m['id']]; m.update(fa=str(fa), organo=on, organo_nif=onif, objeto=ob, imp=imp, iva_base=iva, url=url) m['clave'] = m['id'].split(':', 2)[2].split('||')[0]; m['ref'] = hashlib.md5(m['id'].encode()).hexdigest()[:12] PA = '/h/nacional/salida/licitaciones_completo_2012_2026' arch = con.execute(f"SELECT DISTINCT id, archivo_origen, conjunto FROM read_parquet('{PA}.parquet') WHERE conjunto = 'menores' AND regexp_extract(id, '[^/]+/[^/]+$') IN (SELECT unnest(?))", [[m['clave'] for m in mu]]).fetchall() porz = collections.defaultdict(set) for i, z, c_ in arch: p = f'/h/nacional/zips/{c_}/{z}' if not os.path.exists(p): p = f'/h/nacional/zips/{c_}/_historico/{z}' if os.path.exists(p): porz[p].add('/'.join(i.split('/')[-2:])) RE_ID = re.compile(rb'https?://contratacion(?:delestado\.es|delsectorpublico\.gob\.es)/sindicacion/([^<]+)'); RE_UPD = re.compile(rb'([^<]+)') ver = collections.defaultdict(dict) for zp, cl in porz.items(): with zipfile.ZipFile(zp) as z: for nm in z.namelist(): if not nm.endswith('.atom'): continue data = z.read(nm) for mm in RE_ID.finditer(data): kk = '/'.join(mm.group(1).decode().split('/')[-2:]) if kk not in cl: continue i0 = data.rfind(b'', mm.end()) if i0 < 0 or i1 < 0: continue ent = data[i0:i1 + 8]; u = RE_UPD.search(ent); ver[kk].setdefault(u.group(1).decode() if u else '', ent) del data def ln(e): return e.tag.split('}')[-1] def parse(ent): e2 = re.sub(r'\sxmlns(:[\w\-]+)?="[^"]*"', '', ent.decode('utf-8', 'replace')); e2 = re.sub(r'\s[\w\-]+:[\w\-]+="[^"]*"', '', e2) return ET.fromstring(re.sub(r'<(/?)[A-Za-z\-]+:', r'<\1', e2)) def num(s): try: return float(s) except (TypeError, ValueError): return None def dentro(root, padre, hijo): return [num(x.text) for p in root.iter() if ln(p) == padre for x in p.iter() if ln(x) == hijo and x.text] TIPO = {'1': 'Suministros', '2': 'Servicios', '3': 'Obras'} res = [] for m in mu: vs = sorted(ver.get(m['clave'], {}).items()); f = []; o = {} d = f"/o/priv/orig_e1/{CEL}/{m['ref']}"; os.makedirs(d, exist_ok=True) for u, ent in vs: open(f"{d}/v_{re.sub(r'[^0-9T]', '', u)[:20]}.xml", 'wb').write(ent) if not vs: clase = 'sin_original' else: ult = parse(vs[-1][1]) sin = [x for x in dentro(ult, 'LegalMonetaryTotal', 'TaxExclusiveAmount') if x is not None]; conv = [x for x in dentro(ult, 'LegalMonetaryTotal', 'PayableAmount') if x is not None] pres = [x for x in dentro(ult, 'BudgetAmount', 'TaxExclusiveAmount') if x is not None] tc = next((x.text for p in ult.iter() if ln(p) == 'ProcurementProject' for x in p if ln(x) == 'TypeCode'), None) st = next((x.text for x in ult.iter() if ln(x) == 'ContractFolderStatusCode'), None) rc = sorted({x.text for x in ult.iter() if ln(x) == 'ResultCode' and x.text}) lcp = next((x for x in ult.iter() if ln(x) == 'LocatedContractingParty'), None) nifs = {x.text.strip().upper() for x in (lcp.iter() if lcp is not None else []) if ln(x) == 'ID' and x.text} ad = sorted({x.text[:10] for x in ult.iter() if ln(x) == 'AwardDate' and x.text}) o = dict(versiones=len(vs), sin_iva=sin, con_iva=conv, presupuesto_sin=pres, tipo_code=tc, estado=st, result=rc, award=ad) b_or = (max(sin) if sin else (max(conv) / 1.21 if conv else None)) if st in ('ANUL',): f.append('anulado') if b_or is None: f.append('sin_importe') elif abs(b_or - m['base']) > 1.0: f.append(f'importe_distinto:{b_or}') if sin and conv and abs(max(sin) - max(conv)) < 0.01: f.append('impuesto_dentro_posible') if TIPO.get(tc) and TIPO.get(tc) != m['tipo']: f.append(f'tipo_distinto:{TIPO.get(tc)}') if m['organo_nif'] and m['organo_nif'].upper() not in nifs: f.append('organo_nif_distinto') if m['fa'] not in (ad or [m['fa']]): f.append(f'fecha_distinta:{ad}') if m['grupo'] == 'k' and b_or is not None and b_or <= m['umbral']: f.append('original_no_supera') if m['grupo'] == 'control' and b_or is not None and b_or > m['umbral']: f.append('control_supera') clase = 'aguanta' if not f else ('artefacto_iva' if f == ['impuesto_dentro_posible'] else 'artefacto_' + f[0].split(':')[0]) res.append(dict(m, original=o, fallos=f, clase=clase)) json.dump(res, open(f'/o/priv/cotejo_e1_{modo}.json', 'w'), ensure_ascii=False, indent=1, default=str) os.chmod('/o/priv/cotejo_e1_' + modo + '.json', 0o600) ks = [r for r in res if r['grupo'] == 'k']; cs = [r for r in res if r['grupo'] == 'control'] resumen = {'casilla': CEL, 'modo': modo, 'semilla': f'|tl-t5-118-e1|{CEL}|{modo}', 'K_total': len(k), 'reparto_tramos': n, 'k_clases': collections.Counter(r['clase'] for r in ks), 'control_clases': collections.Counter(r['clase'] for r in cs), 'k_aguantan': sum(r['clase'] == 'aguanta' for r in ks), 'k_artefactos': sum(r['clase'].startswith('artefacto') for r in ks), 'k_sin_original': sum(r['clase'] == 'sin_original' for r in ks), 'control_ok': sum(r['clase'] == 'aguanta' for r in cs)} resumen['muere_cotejo'] = resumen['k_artefactos'] > 15; resumen['no_concluyente'] = resumen['k_sin_original'] > 5; resumen['controles_ge_9'] = resumen['control_ok'] >= 9 resumen['segundos'] = round(time.time() - T0) json.dump(resumen, open(f'/o/salidas/31_cotejo_e1_{modo}.json', 'w'), ensure_ascii=False, indent=1, default=str); print(json.dumps(resumen, ensure_ascii=False, default=str))