"""TL-T1-151-E2 · segunda implementación independiente de V1 con ENM2 (además fuera código de legislación 2 o «24/2011», leído aquí del parquet de py/13_legis.py con su propio recorte, y exterior con el patrón escrito aquí otra vez). Antes: V1 con ENM1 (fuera prórrogas y emergencias por el objeto: patrones del escéptico copiados aquí a mano, aplicados con el motor de pyarrow sobre el objeto en mayúsculas recortado a 600 caracteres en Python) (pyarrow por lotes y Python puro; sin DuckDB ni el SQL de la medida). Uso: 20_impl2.py DESDE HASTA. Rehace desde los crudos: población, AwardDate vigente, publicación p (regla 4': primera del DOC_CAN_ADJ en el perfil, cualquier versión, >= AwardDate; regla 4 en el bloque de AwardDate cambiada), comunidad de la sede, tope (calendario propio: fiestas nacionales escritas a mano; inhábiles autonómicos del BOE tomados como DATOS de calendario_auto.INHAB) y tarde. Compara id a id con /o/priv/medida_D_H.parquet (base_v1).""" import sys, json, re, time, unicodedata, collections, datetime as dt sys.path[:0] = ['/e/py', '/n/py'] import pyarrow as pa, pyarrow.parquet as pq, pyarrow.compute as pc import calendario_auto INHAB, PROV = calendario_auto.INHAB, calendario_auto.PROV_CA # solo datos (transcripción del BOE) D, Hh = int(sys.argv[1]), int(sys.argv[2]); T0 = time.time() import resource def mem(): return f"{resource.getrusage(resource.RUSAGE_SELF).ru_maxrss // 1024} MB" H = '/h/nacional/salida/licitaciones_completo_2012_2026' ADJ = {'1', '2', '8', '9'} def lotes(f, cols, filtro=None, bs=100_000): for b in pq.ParquetFile(f).iter_batches(batch_size=bs, columns=cols): if filtro is not None: m = filtro(b) if not pc.any(m).as_py(): continue b = b.filter(m) if b.num_rows: yield b def no_rep(t): return pc.invert(pc.fill_null(t['entrada_repetida'], False)) VADJ = pa.array(sorted(ADJ)) def ult_adj(t): return pc.and_(pc.and_(pc.and_(pc.equal(t['conjunto'], 'licitaciones'), pc.fill_null(t['es_ultima_version'], False)), no_rep(t)), pc.and_(pc.is_in(t['resultado_code'], value_set=VADJ), pc.is_valid(t['fecha_adjudicacion']))) # 1) última versión: ids con alguna AwardDate adjudicada en la ventana; luego todas sus AwardDate adjudicadas A = set() for t in lotes(f'{H}_resultados.parquet', ['id', 'conjunto', 'es_ultima_version', 'entrada_repetida', 'resultado_code', 'fecha_adjudicacion'], lambda t: pc.and_(ult_adj(t), pc.and_(pc.greater_equal(pc.year(t['fecha_adjudicacion']), D), pc.less_equal(pc.year(t['fecha_adjudicacion']), Hh)))): A.update(t['id'].to_pylist()) VA = pa.array(sorted(A), pa.large_string()); ult = collections.defaultdict(set) for t in lotes(f'{H}_resultados.parquet', ['id', 'conjunto', 'es_ultima_version', 'entrada_repetida', 'resultado_code', 'fecha_adjudicacion'], lambda t: pc.and_(ult_adj(t), pc.is_in(t['id'], value_set=VA))): for i, fa in zip(t['id'].to_pylist(), t['fecha_adjudicacion'].to_pylist()): ult[i].add(fa.date()) cand = {i: s_ for i, s_ in ult.items() if D <= min(s_).year <= Hh} del ult, A CS = pa.array(sorted(cand), pa.large_string()) print('candidatas', len(cand), round(time.time() - T0), mem(), flush=True) # 3) licitación (última versión), tipo de órgano, inventario de entes lic = {} LIC_OK = lambda t: pc.and_(pc.and_(pc.equal(t['conjunto'], 'licitaciones'), pc.fill_null(t['es_ultima_version'], False)), pc.and_(no_rep(t), pc.is_in(t['id'], value_set=CS))) BASEC = ['id', 'conjunto', 'es_ultima_version', 'entrada_repetida'] for t in lotes(f'{H}.parquet', BASEC + ['nif_organo', 'sistema_contratacion_code', 'tipo_contrato_code', 'procedimiento_code', 'urgencia', 'sara', 'valor_estimado_contrato', 'fecha_publicacion', 'nuts', 'organo_contratante'], LIC_OK, bs=50_000): for row in pa.Table.from_batches([t]).drop(BASEC[1:]).to_pylist(): lic[row['id']] = row print('lic', len(lic), round(time.time() - T0), mem(), flush=True) toc = {} for t in lotes(f'{H}_ampliado.parquet', ['id', 'es_ultima_version', 'entrada_repetida', 'tipo_organo_code'], lambda t: pc.and_(pc.and_(pc.fill_null(t['es_ultima_version'], False), no_rep(t)), pc.is_in(t['id'], value_set=CS))): for i, k in zip(t['id'].to_pylist(), t['tipo_organo_code'].to_pylist()): toc[i] = k fjd = {} for r in pq.read_table('/d/unified_20261103.identidad/entes.parquet', columns=['nif', 'fj_cod']).to_pylist(): if r['nif'] is not None and r['fj_cod'] is not None: k = r['nif'].upper(); fjd[k] = min(fjd.get(k, 10**9), r['fj_cod']) def umbral(tc, tocx, a): if tc == '3': u = 5225000 if a <= 2017 else 5548000 if a <= 2019 else 5350000 if a <= 2021 else 5382000 if a <= 2023 else 5538000 if a <= 2025 else 5404000 else: u = 209000 if a <= 2017 else 221000 if a <= 2019 else 214000 if a <= 2021 else 215000 if a <= 2023 else 221000 if a <= 2025 else 216000 if tc in ('1', '2') and tocx == '1': u = min(u, 135000 if a <= 2017 else 144000 if a <= 2019 else 139000 if a <= 2021 else 140000 if a <= 2023 else 143000 if a <= 2025 else 140000) return u # 3b) población sin texto (sin Ley 24/2011, comunidad ni publicación): reduce las candidatas antes de leer textos, versiones y anuncios def pre_ok(i): L = lic.get(i); fas = cand[i] if L is None or len(fas) != 1: return False fa = next(iter(fas)); tk = toc.get(i); nif = (L['nif_organo'] or '').upper(); letra = nif[:1] if not (L['tipo_contrato_code'] in ('1', '2', '3') and (L['procedimiento_code'] or '') in ('1', '2', '3', '4', '5', '9', '10', '13') and (L['urgencia'] or '') != '3' and tk in ('1', '2', '3') and (letra in ('S', 'P') or (letra == 'Q' and fjd.get(nif) in (7, 8, 9, 13, 19, 3))) and not ((nif[1:3] == '31' or (L['nuts'] or '').startswith('ES22')) and tk != '1') and (L['sistema_contratacion_code'] or '') not in ('2', '3', '4') and L['sara'] is not True): return False a = (L['fecha_publicacion'] or dt.datetime.combine(fa, dt.time())).year return L['valor_estimado_contrato'] is None or L['valor_estimado_contrato'] < umbral(L['tipo_contrato_code'], tk, a) P = [i for i in cand if pre_ok(i)]; cand = {i: cand[i] for i in P}; lic = {i: lic[i] for i in P} CS = pa.array(sorted(P), pa.large_string()) print('poblacion previa', len(P), round(time.time() - T0), mem(), flush=True) for t in lotes(f'{H}.parquet', BASEC + ['objeto'], LIC_OK, bs=20_000): for i, x, ob in zip(t['id'].to_pylist(), pc.fill_null(pc.match_substring_regex(pc.utf8_upper(t['objeto']), '24/2011|DEFENSA Y SEGURIDAD'), False).to_pylist(), t['objeto'].to_pylist()): lic[i]['l24'] = x; lic[i]['ob6'] = (ob or '').upper()[:600] # ENM1: patrones del escéptico de datos (verif/escep_datos/py/09_final.py), escritos aquí otra vez PRS = r"^\W*(\d+\W*)?(PRIMERA |SEGUNDA |TERCERA |CUARTA |1[ªA]? |2[ªA]? |3[ªA]? )?PR[OÓ]RROGA|\b(PRIMERA|SEGUNDA|TERCERA|CUARTA|1ª|2ª|3ª|[ÚU]NICA)\s+PR[OÓ]RROGA|PR[OÓ]RROGA (DEL|DE LA|DE LOS|DE LAS|CONTRATO|CTO)\b|PR[OÓ]RROGA (N[ºO°.]|NUM)" PRN = r"POSIBILIDAD DE PR[OÓ]RROGA|POSIBLE PR[OÓ]RROGA|PRORROGABLE|CON PR[OÓ]RROGA|PR[OÓ]RROGAS? (DE|POR|HASTA) (UN|DOS|TRES|CUATRO|1|2|3|4)\b|INCLUIDAS? (LAS )?PR[OÓ]RROGAS?|M[AÁ]S (UNA |LAS |SUS )?PR[OÓ]RROGA" EMS = r"\b(OBRAS?|ACTUACI[OÓ]N(ES)?|TRABAJOS?|INTERVENCI[OÓ]N(ES)?|REPARACI[OÓ]N(ES)?|CONTRATO|SUMINISTRO|SERVICIO)\b[A-ZÁÉÍÓÚÑ ,]{0,30}\bDE EMERGENCIA\b|\bPOR EMERGENCIA\b|TRAMITACI[OÓ]N DE EMERGENCIA|\bEMERGENCIA (POR|DERIVAD|OCASIONAD|CAUSAD|EN|PARA)\b" EMN = r"SERVICIOS? DE EMERGENCIAS|ILUMINACI[OÓ]N DE EMERGENCIA|LUMINARIAS? DE EMERGENCIA|SALIDAS? DE EMERGENCIA|PLAN(ES)? DE EMERGENCIA|CENTRO DE EMERGENCIAS|\b112\b|AUTOPROTECCI|ALUMBRA(DO|MIENTO) DE EMERGENCIA|VEH[IÍ]CULOS?" _ids = list(lic); _ob = pa.array([lic[i].get('ob6', '') for i in _ids]) def _m(p): return pc.fill_null(pc.match_substring_regex(_ob, p), False) _pe = pc.or_(pc.and_(_m(PRS), pc.invert(_m(PRN))), pc.and_(_m(EMS), pc.invert(_m(EMN)))).to_pylist() EXO = r"EMBAJADA|CONSULADO|CANCILLER[IÍ]A|REPRESENTACI[OÓ]N PERMANENTE|OFICINA ECON[OÓ]MICA Y COMERCIAL|EN EL EXTRANJERO|INSTITUTO CERVANTES DE" _org = pa.array([lic[i].get('organo_contratante') or '' for i in _ids]) _ex = pc.or_(_m(EXO), pc.fill_null(pc.match_substring_regex(_org, 'Servicio Exterior'), False)).to_pylist() LEG = {} for rw in pq.read_table('/o/priv/legis_e2_medida.parquet', columns=['clave', 'cod_ult']).to_pylist(): cd = (rw['cod_ult'] or '').lstrip('|').strip(); LEG[rw['clave']] = cd == '2' or '24/2011' in cd for i, x, e in zip(_ids, _pe, _ex): lic[i]['pe'] = x or e or LEG.get('/'.join(i.split('/')[-2:]), False) print('prorroga o emergencia', sum(_pe), flush=True) for t in lotes(f'{H}.parquet', BASEC + ['dependencia', 'ciudad_organo'], LIC_OK, bs=50_000): for i, dp, ci in zip(t['id'].to_pylist(), t['dependencia'].to_pylist(), t['ciudad_organo'].to_pylist()): lic[i]['dependencia'] = dp; lic[i]['ciudad_organo'] = ci print('lic texto', round(time.time() - T0), mem(), flush=True) # 2) todas las versiones: AwardDate mínima por versión fav = collections.defaultdict(dict) for t in lotes(f'{H}_resultados.parquet', ['id', 'conjunto', 'entrada_repetida', 'resultado_code', 'fecha_adjudicacion', 'fecha_updated'], lambda t: pc.and_(pc.and_(pc.and_(pc.equal(t['conjunto'], 'licitaciones'), no_rep(t)), pc.is_in(t['id'], value_set=CS)), pc.and_(pc.is_in(t['resultado_code'], value_set=VADJ), pc.is_valid(t['fecha_adjudicacion'])))): for i, fa, u in zip(t['id'].to_pylist(), t['fecha_adjudicacion'].to_pylist(), t['fecha_updated'].to_pylist()): fav[i][u] = min(fav[i].get(u, fa.date()), fa.date()) print('versiones', len(fav), round(time.time() - T0), mem(), flush=True) # 4) anuncios DOC_CAN_ADJ en el perfil, todas las versiones an = collections.defaultdict(list) for t in lotes(f'{H}_anuncios.parquet', ['id', 'tipo_anuncio_code', 'medio_publicacion', 'fecha_publicacion', 'fecha_updated', 'entrada_repetida'], lambda t: pc.and_(pc.and_(pc.equal(t['tipo_anuncio_code'], 'DOC_CAN_ADJ'), no_rep(t)), pc.is_in(t['id'], value_set=CS))): for i, m, fp, u in zip(t['id'].to_pylist(), t['medio_publicacion'].to_pylist(), t['fecha_publicacion'].to_pylist(), t['fecha_updated'].to_pylist()): if fp is not None and (m or '').lower().startswith('perfil'): an[i].append((fp.date(), u)) print('lecturas', round(time.time() - T0), flush=True) # 5) calendario propio: fiestas nacionales 2022-2027 a mano (Viernes Santo de cada año, escrito, no calculado) VS = {2022: dt.date(2022, 4, 15), 2023: dt.date(2023, 4, 7), 2024: dt.date(2024, 3, 29), 2025: dt.date(2025, 4, 18), 2026: dt.date(2026, 4, 3), 2027: dt.date(2027, 3, 26)} NAC = {dt.date(a, m, d_) for a in VS for m, d_ in ((1, 1), (1, 6), (5, 1), (8, 15), (10, 12), (11, 1), (12, 6), (12, 8), (12, 25))} | set(VS.values()) def es_inhabil(x, ca): return x.isoweekday() in (6, 7) or x in NAC or (ca in INHAB and x in INHAB[ca]) def tope(fa, ca): x = fa + dt.timedelta(days=15) while es_inhabil(x, ca): x = x + dt.timedelta(days=1) return x def plano(s): return re.sub(r'\s+', ' ', re.sub(r'[^a-z0-9]', ' ', unicodedata.normalize('NFKD', s or '').encode('ascii', 'ignore').decode().lower())).strip() RAICES = {'mancha': 'CM', 'leon': 'CL', 'andaluc': 'AN', 'aragon': 'AR', 'asturias': 'AS', 'balear': 'IB', 'canarias': 'CN', 'cantabria': 'CB', 'catalu': 'CT', 'ceuta': 'CE', 'melilla': 'ML', 'madrid': 'MD', 'valencia': 'VC', 'extremadura': 'EX', 'galicia': 'GA', 'murcia': 'MC', 'navarra': 'NC', 'vasco': 'PV', 'euskadi': 'PV', 'rioja': 'RI'} ORDEN = ['mancha', 'leon', 'andaluc', 'aragon', 'asturias', 'balear', 'canarias', 'cantabria', 'catalu', 'ceuta', 'melilla', 'madrid', 'valencia', 'extremadura', 'galicia', 'murcia', 'navarra', 'vasco', 'euskadi', 'rioja'] muni = collections.defaultdict(set) for r in pq.read_table('/d/aggregations_20261103/cobertura/municipios.parquet', columns=['municipio_ine', 'municipio']).to_pylist(): if not r['municipio']: continue for parte in [r['municipio']] + r['municipio'].split('/'): k = plano(parte); m = re.match(r'^(.*) (el|la|los|las|l|a|o|os|as|es|sa|ses|s)$', k) for v in {k, f'{m.group(2)} {m.group(1)}' if m else k}: if v and r['municipio_ine'][:2] in PROV: muni[v].add(PROV[r['municipio_ine'][:2]]) def comunidad(dep, ciu, nif): p = [x.strip() for x in (dep or '').split(' > ')] if len(p) >= 3 and p[1] in ('ENTIDADES LOCALES', 'COMUNIDADES Y CIUDADES AUTÓNOMAS'): k = plano(p[2]) for r_ in ORDEN: if r_ in k: return RAICES[r_] for v in [ciu] + re.split(r'[/,(]', ciu or ''): s = muni.get(plano(v)) if s and len(s) == 1: return next(iter(s)) n = (nif or '').strip().upper() return PROV.get(n[1:3]) if n[:1] in ('P', 'S') else None yo = {} for i in P: L = lic[i]; fa = next(iter(cand[i])); nif = (L['nif_organo'] or '').upper() if L.get('l24') or L.get('pe'): continue pubs = an.get(i, []) p4p = min((f for f, u in pubs if f >= fa), default=None) if p4p is None: continue fv = fav.get(i, {}) p4 = min((f for f, u in pubs if fv.get(u) == fa), default=None) ca = comunidad(L['dependencia'], L['ciudad_organo'], nif); tp = tope(fa, ca) tarde = p4p > tp and (len(set(fv.values())) < 2 or (p4 is not None and p4 > tp)) yo[i] = dict(fa=fa, p=p4p, tope=tp, tarde=tarde, anio=fa.year) med = {r['id']: r for r in pq.read_table(f'/o/priv/medida_e2_{D}_{Hh}.parquet', columns=['id', 'fa', 'p4p', 'tope', 'tarde', 'anio', 'base_v1']).to_pylist() if r['base_v1']} solo_yo = sorted(set(yo) - set(med)); solo_med = sorted(set(med) - set(yo)) dif = collections.Counter(); ej = [] for i in set(yo) & set(med): for k, km in (('fa', 'fa'), ('p', 'p4p'), ('tope', 'tope'), ('tarde', 'tarde'), ('anio', 'anio')): if yo[i][k] != med[i][km]: dif[k] += 1 if len(ej) < 8: ej.append((i[-12:], k, str(yo[i][k]), str(med[i][km]))) o = dict(desde=D, hasta=Hh, n_yo=len(yo), k_yo=sum(x['tarde'] for x in yo.values()), n_medida=len(med), k_medida=sum(bool(x['tarde']) for x in med.values()), solo_yo=len(solo_yo), solo_medida=len(solo_med), diferencias=dict(dif), ejemplos=ej, ejemplos_solo=[x[-12:] for x in (solo_yo[:4] + solo_med[:4])], segundos=round(time.time() - T0)) o['cero_diferencias'] = not (solo_yo or solo_med or dif) json.dump(o, open(f"/o/salidas/{'ensayo/' if Hh < 2024 else ''}24_impl2_e2_{D}_{Hh}.json", 'w'), indent=1, ensure_ascii=False, default=str) print(json.dumps(o, ensure_ascii=False, default=str))