"""RONDA 2 (ADENDA_R2_V3 85fcec42): órgano (i) o (ii), clase e. Servicios invisibles v3 · implementación 2 (Python puro; pyarrow solo para leer; sin SQL ni código de impl1/mapa_v3). PREREGISTRO_V3 (310a2cf4…), REGLAS_V3.json (cbd8062b…). Cabeza por programación dinámica sobre posiciones de tokens (impl1 usa regex con retroceso). El bloque del mapa (M1-M3, M4, N, M5) es el de servicios-invisibles-v2-24nov/py/impl2_v2.py, generalizado: M5 por programa (hoja CE4a), N solo G<->V.""" import csv, json, re, unicodedata, datetime, time from collections import Counter, defaultdict import pyarrow.parquet as pq ID = '/d/unified_20261123.identidad/'; CO = '/d/aggregations_20261123/cobertura/' R = json.load(open('/w/REGLAS_V3.json')); S = R['servicios'] PROG24 = {d['prog24'] for d in S.values()} def nz(s): if s is None: return '' s = s.lower() if not s.isascii(): s = ''.join(ch for ch in unicodedata.normalize('NFD', s) if not unicodedata.combining(ch)) return ' '.join(re.findall(r'[a-z0-9]+', s)) class Tok: def __init__(self, lst): self.r = re.compile('(?:' + '|'.join(lst) + ')'); self.c = {} def __call__(self, w): v = self.c.get(w) if v is None: v = self.c[w] = self.r.fullmatch(w) is not None return v def prep(f): out = [] for e in f: if 'gap' in e: out.append(('g', e['gap'], Tok(e['solo']) if 'solo' in e else None)) else: out.append(('t', Tok(e['t']))) return out FR = {s: [prep(f) for f in d['frases']] for s, d in S.items()} MARCO = Tok(R['marco']) AMBT = {s: Tok(R['ambito_general'] + d['ambito']) for s, d in S.items()} TF = set(R['tipos_fuera']) def fin(ph, tk, i): n = len(tk); cur = {i} for e in ph: nx = set() if e[0] == 'g': for p in cur: nx.add(p); q = p for _ in range(e[1]): if q < n and (e[2] is None or e[2](tk[q])): q += 1; nx.add(q) else: break else: for p in cur: if p < n and e[1](tk[p]): nx.add(p + 1) cur = nx if not cur: return cur return cur def cabezas(tk): n = len(tk); llega = [False] * (n + 1); llega[0] = True; out = set() for i in range(n): if not llega[i]: continue if MARCO(tk[i]): llega[i + 1] = True for s, phs in FR.items(): for ph, p0 in zip(phs, PRIM[s]): if not p0(tk[i]): continue e = fin(ph, tk, i) if e: out.add(s) for j in e: llega[j] = True return out PRIM = {s: [ph[0][1] for ph in phs] for s, phs in FR.items()} # primer elemento de cada frase (siempre token) def ancha(tk, s): for ph, p0 in zip(FR[s], PRIM[s]): for i, w in enumerate(tk): if p0(w) and fin(ph, tk, i): return True return False def leer(p, cols): return pq.read_table(p, columns=cols).to_pylist() t0 = time.time() filas = [] # (onif, onom, dir3, ccaa, year, menor, id, {s: (acepta, ambtxt)}) acc = {} cols = ['organo_nif', 'organo_nombre', 'dir3', 'ccaa', 'year', 'objeto', 'cpv_code', 'tipo_contrato', 'procedimiento', 'es_menor', 'id_canonical'] tb = pq.read_table('/w/datos/filas_cand.parquet', columns=cols) d = {k: tb.column(k).to_pylist() for k in cols} for i in range(tb.num_rows): if (d['tipo_contrato'][i] or '') in TF: continue tk = nz(d['objeto'][i]).split() c8 = ''.join(ch for ch in (d['cpv_code'][i] or '') if ch.isdigit())[:8] hs = None; sv = {} for s, dd in S.items(): cp = any(c8.startswith(p) for p in dd['cpv']) if not (cp or ancha(tk, s)): continue am = any(AMBT[s](w) for w in tk) if hs is None: hs = cabezas(tk) sv[s] = ((am or cp) and s in hs, am) if sv: idc = d['id_canonical'][i] for s, v in sv.items(): acc[(idc, s)] = v menor = d['procedimiento'][i] == 'Menor' or bool(d['es_menor'][i]) filas.append((d['organo_nif'][i], d['organo_nombre'][i], d['dir3'][i], d['ccaa'][i], int(d['year'][i]), menor, idc, sv)) del d, tb print('filas ancha', len(filas), 'pares', len(acc), round(time.time() - t0), 's') k3, k4 = {}, {} for r in leer(ID + 'organos_filas.parquet', ['organo_nif', 'organo_nombre', 'dir3', 'organo_clave']): k3[(r['organo_nif'], r['organo_nombre'], r['dir3'])] = r['organo_clave'] for r in leer(ID + 'organos_filas_ccaa.parquet', ['organo_nif', 'organo_nombre', 'dir3', 'ccaa', 'organo_clave']): k4[(r['organo_nif'], r['organo_nombre'], r['dir3'], r['ccaa'])] = r['organo_clave'] def clave(f): return k4.get((f[0], f[1], f[2], f[3])) or k3.get((f[0], f[1], f[2])) # M1-M3 base = defaultdict(set) # ronda 2: solo M3 (Ceuta y Melilla) entes = leer(ID + 'entes.parquet', ['codigo_invente', 'letra_dependencia', 'municipio_ine', 'estado', 'fecha_baja', 'nombre', 'ccaa']) ente_mun = {e['codigo_invente']: e['municipio_ine'] for e in entes if e['letra_dependencia'] in ('A', 'Z') and e['municipio_ine']} organos = leer(ID + 'organos.parquet', ['organo_clave', 'ente_codigo_invente', 'dir3_oficial', 'nif_oficial', 'entidad_clave']) raiz = {'A18002888': '51001', 'A19002898': '52001'} d3 = leer(ID + 'dir3_unidades.parquet', ['codigo', 'principal', 'nif']) nif_ciudad = {r['nif']: raiz[r['codigo']] for r in d3 if r['codigo'] in raiz and r['nif']} hijo_ciudad = {r['codigo']: raiz[r['principal']] for r in d3 if r['principal'] in raiz} for o in organos: for x in (o['nif_oficial'], o['entidad_clave'], (o['organo_clave'] or '').split('|')[0]): if x in nif_ciudad: base[o['organo_clave']].add(nif_ciudad[x]) if o['dir3_oficial'] in hijo_ciudad: base[o['organo_clave']].add(hijo_ciudad[o['dir3_oficial']]) def _nif(x): x = ''.join(ch for ch in (x or '').upper() if ch not in ' -.\t\n\r') return x if len(x) == 9 and 'A' <= x[0] <= 'Z' and x[1:8].isdigit() and (x[8].isdigit() or 'A' <= x[8] <= 'Z') else None inv = json.load(open('/m/bruto/inventario_I.json'))['informeInventario'] cif, nomb, provn = {}, {}, {} for r in inv: k = (r['caCodigo'], r['provinciaCodigo'], r['corporacion'], r['tipoEntePrincipalCodigo'], r['tipoEntePrincipalODependienteCodigo'], r['secuencialOrganismo']) cif[k] = _nif(r['cif']); nomb[k] = r['nombreCorporacion']; provn[k] = r['provinciaNombre'] ayto = {} for r in leer(CO + 'ayuntamientos_nif.parquet', ['municipio_ine', 'nif']): if _nif(r['nif']): ayto[_nif(r['nif'])] = r['municipio_ine'] hijos = defaultdict(list) for t in 'MCRTG': for r in json.load(open('/m/bruto/comp_%s.json' % t))['informeEntesComposicion']: hijos[(r['caCodigo'], r['provinciaCodigo'], r['corporacion'], r['tipoEntePrincipalCodigo'])].append( (r['compCACodigo'], r['compProvinciaCodigo'], r['compCorporacion'], r['compTipo1Codigo'], r['compTipo2Codigo'])) def muns(k4, pila=()): if k4 in pila: return set() s = set() for ca, pr, co, t1, t2 in hijos.get(k4, []): if t1 == 'A' and t2 in ('A', 'E'): m = ayto.get(cif.get((ca, pr, co, 'A', 'A', '000'))) if m: s.add(m) elif t1 in 'MCRTG' and t2 == t1: s |= muns((ca, pr, co, t1), pila + (k4,)) return s nm4 = defaultdict(set) for (ca, pr, co, t1, t2, sq), n in cif.items(): if not n: continue if t1 in 'MCRTG': nm4[n] |= muns((ca, pr, co, t1)) elif t1 == 'A': if t2 == 'A' and sq == '000': if n in ayto: nm4[n].add(ayto[n]) elif t2 != 'E': m = ayto.get(cif.get((ca, pr, co, 'A', 'A', '000'))) if m: nm4[n].add(m) # ronda 2 (i): entes BDGEL de la corporación del municipio, T1=A, T2 en A,V,O,L,P,I nmI = defaultdict(set) for (ca, pr, co, t1, t2, sq), n in cif.items(): if n and t1 == 'A' and t2 in 'AVOLPI': m = ayto.get(cif.get((ca, pr, co, 'A', 'A', '000'))) if m: nmI[n].add(m) # M5 def nom(s): return nz(s) aa_idx = defaultdict(list) for k, n in cif.items(): if k[3] == 'A' and k[4] == 'A' and k[5] == '000': for parte in (provn[k] or '').split('/'): aa_idx[(nom(parte), nom(nomb[k]))].append(n) nm5 = defaultdict(set); dip5 = set(); servidos = set() with open('/w/datos/ce4_2024.tsv', encoding='utf-8', newline='') as fh: for r in csv.DictReader(fh, delimiter='\t'): if r['hoja'] != 'CE4a' or r['programa'] not in PROG24: continue c = list({n for parte in r['provincia'].split('/') for n in aa_idx.get((nom(parte), nom(r['entidad_servida'])), [])}) if len(c) != 1 or c[0] not in ayto: continue p = r['cod_ente'].split('-') if len(p) != 5 or len(p[3]) != 2: continue pn = cif.get((p[0], p[1], p[2], p[3][0], p[3][1], p[4])) if pn: servidos.add((r['programa'], ayto[c[0]])) nm5[pn].add((r['programa'], ayto[c[0]])) if p[3] == 'DD': dip5.add(pn) # N todos = {n for n in cif.values() if n} cola = defaultdict(list) for n in todos: cola[n[1:]].append(n) def leer_n(x): if x in todos: return None l = cola.get(x[1:], []) if len(l) == 1 and l[0][0] != x[0] and x[0] in 'GV' and l[0][0] in 'GV': return l[0] return None dd3 = {r['codigo']: (r['nif'], r['principal']) for r in d3} fil = defaultdict(set) for r in leer(ID + 'organos_filas.parquet', ['organo_clave', 'organo_nif', 'organo_nif_inferido', 'dir3']): fil[r['organo_clave']].update([('n', r['organo_nif']), ('n', r['organo_nif_inferido']), ('d', r['dir3'])]) tipo_o = {r['organo_clave']: r['tipo'] for r in leer(ID + 'organos_tipo.parquet', ['organo_clave', 'tipo'])} mapa = defaultdict(lambda: defaultdict(set)) # oc -> ine -> tags for oc, ms in base.items(): for m in ms: mapa[oc][m].add('M3') casados_n, pares_m5 = set(), set() for o in organos: oc = o['organo_clave'] ns = [o['nif_oficial'], o['entidad_clave'], (oc or '').split('|')[0]] ds = [o['dir3_oficial']] for k, v in fil.get(oc, ()): (ns if k == 'n' else ds).append(v) for d in ds: if d in dd3: ns.append(dd3[d][0]) if dd3[d][1] in dd3: ns.append(dd3[dd3[d][1]][0]) xs = {_nif(x) for x in ns} - {None} for x in xs: y = leer_n(x) for n, suf in ((x, ''), (y, 'N')): if not n: continue if suf and (nm4.get(n) or nm5.get(n) or nmI.get(n)): # ronda 1 (solo código): nm4 guarda conjuntos vacíos; impl1 no cuenta entes sin municipios casados_n.add((oc, x, n)) for m in nmI.get(n, ()): mapa[oc][m].add('I' + suf) if tipo_o.get(oc) in ('autonomica', 'salud', 'age', 'investigacion'): continue for pg, m in nm5.get(n, ()): mapa[oc][m].add('M5' + ('D' if n in dip5 else '') + suf + ':' + pg) pares_m5.add((oc, m, pg)) uni = defaultdict(set) with open('/datos/padron_municipios_2019_2025.csv', encoding='utf-8') as fh: for r in csv.DictReader(fh): for s, dd in S.items(): if int(r['poblacion_2025']) > max(dd['umbral_hab'], 20000): uni[s].add(r['ine']) va, vam, v26 = defaultdict(set), defaultdict(set), defaultdict(set) # (s, ine) -> vías for f in filas: oc = clave(f) if not oc or oc not in mapa: continue for s, (ac, am) in f[7].items(): if not ac: continue pg = S[s]['prog24'] for m, tags in mapa[oc].items(): for tg in tags: if tg.startswith('M5') and tg.split(':')[1] != pg: continue if tg.startswith('M5D') and not am: continue if f[4] == 2026 and not f[5]: v26[(s, m)].add(tg) elif 2016 <= f[4] <= 2025: (vam if f[5] else va)[(s, m)].add(tg) desde = datetime.date(2016, 1, 1) REB = {s: re.compile(r'(?= desde)): continue t = nz(e['nombre']) for s in S: if REB[s].search(t): B1[s].add(mun) def mun_de(cod): p = cod.split('-') return ayto.get(cif.get((p[0], p[1], p[2], 'A', 'A', '000'))) if len(p) == 5 and p[3] == 'AA' and p[4] == '000' else None def dep_propio(princ, ente): p, e = princ.split('-'), ente.split('-') return ente != princ and len(e) == 5 and p[:3] == e[:3] and e[3][:1] == 'A' p21 = {dd['prog21']: s for s, dd in S.items()}; p24 = {dd['prog24']: s for s, dd in S.items()} B3 = defaultdict(set); decl = defaultdict(lambda: defaultdict(set)) with open('/m/cesel/2021_CE2.tsv', encoding='utf-8', newline='') as fh: for r in csv.DictReader(fh, delimiter='\t'): s = p21.get(r['Programa']) m = mun_de(r['EnteP']) if s else None if not m: continue if r['TipoEnte'] == 'AA' and r['Ente'] == r['EnteP']: decl[(s, m)]['2021'].add(r['CodGestion']) if dep_propio(r['EnteP'], r['Ente']) and r['CodGestion'].startswith('Gestión directa'): B3[(s, m)].add('b3_2021') with open('/w/datos/ce1_2024.tsv', encoding='utf-8', newline='') as fh: for r in csv.DictReader(fh, delimiter='\t'): s = p24.get(r['programa']) if r['hoja'] != 'CE1a' or not s: continue m = mun_de(r['cod_principal']) if not m: continue if r['cod_ente'] == r['cod_principal']: decl[(s, m)]['2024'].add(r['tipo_gestion']) if dep_propio(r['cod_principal'], r['cod_ente']) and r['tipo_gestion'].startswith('Gestión directa'): B3[(s, m)].add('b3_2024') res = defaultdict(dict) for s in S: for m in sorted(uni[s]): k2 = (s, m) cd = sorted('c' + a[2:] for a, fs in decl[k2].items() if fs and all(x.startswith('Gestión directa') for x in fs)) b = m in B1[s] or bool(B3.get(k2)) fs = set().union(*decl[k2].values()) if decl[k2] else set() ee = (['e_forma'] if any(x != 'No se presta el servicio' and not x.startswith('Gestión directa') for x in fs) else []) + \ (['e_ce4'] if (S[s]['prog24'], m) in servidos else []) k = 'a' if va.get(k2) else 'a_menor' if vam.get(k2) else 'b' if b else 'c' if cd else 'a2026' if v26.get(k2) else 'e' if ee else 'd' dt = None if k == 'd': dt = 'd_no_presta' if 'No se presta el servicio' in fs else 'd_sin_cesel' if not fs else 'd_resto' res[s][m] = dict(clase=k, vias_a=sorted(va.get(k2, ())), vias_am=sorted(vam.get(k2, ())), vias_2026=sorted(v26.get(k2, ())), b1=m in B1[s], b3=sorted(B3.get(k2, ())), c=cd, e=ee, d_tipo=dt) json.dump(dict(clases=res, acepta=sorted([k[0], k[1], v[0], v[1]] for k, v in acc.items()), pares_m5=sorted(map(list, pares_m5)), casados_n=sorted(map(list, casados_n))), open('/w/salidas/impl2_v3r2.json', 'w'), ensure_ascii=False, indent=0, sort_keys=True) for s in S: print(s, len(res[s]), dict(Counter(x['clase'] for x in res[s].values())))