"""TL-DOUE-ENT · SEGUNDA implementación de la medida por entidad: pyarrow y Python puro, sin SQL; calendario propio sobre las TABLAS de días inhábiles (calendario_auto.INHAB, calendario.FEST, PROV_CA), binomial y BH escritos aparte. Compara con PRIV/contratos_D_H.parquet y PRIV/entidades_D_H.parquet de 50_entidad.py. Uso: 60_entidad_impl2.py DESDE HASTA. Salida: SAL/60_impl2_D_H.json.""" import sys, os, json, math, random, re, hashlib, collections, unicodedata, datetime as dt, time sys.path[:0] = ['/c'] import pyarrow.parquet as pq, pyarrow.dataset as ds, pyarrow.compute as pc, resource def marca(t): print(t, round(time.time() - T0), resource.getrusage(resource.RUSAGE_SELF).ru_maxrss // 1024, 'MB', flush=True) from calendario_auto import INHAB, PROV_CA from calendario import FEST D, Hh = int(sys.argv[1]), int(sys.argv[2]); T0 = time.time() SAL, PRIV = os.environ.get('SAL', '/o/salidas'), os.environ.get('PRIV', '/o/priv'); NMIN = int(os.environ.get('NMIN', '20')) H = '/h/nacional/salida/licitaciones_completo_2012_2026' import pyarrow as pa FCOLS = ['id', 'es_ultima_version', 'entrada_repetida', 'conjunto', 'tipo_anuncio_code', 'medio_publicacion', 'sara', 'year', 'fecha_formalizacion', 'envio_fecha'] def leer(path, cols, filtro): # lectura por páginas (sin pre_buffer) para caber en 2 GB; el filtro se aplica a cada lote f = pq.ParquetFile(path, buffer_size=8 << 20, pre_buffer=False); nombres = set(f.schema_arrow.names) cc = cols + [c for c in FCOLS if c in nombres and c not in cols] for b in f.iter_batches(batch_size=16384, columns=cc, use_threads=False): t = pa.Table.from_batches([b]).filter(filtro) if t.num_rows: yield from t.select(cols).to_pylist() def up(x): return (x or '').strip().upper().replace(' ', '') # población P = [r for r in pq.read_table(f'/m/medida_{D}_{Hh}.parquet', columns=['id', 'nif_organo', 'expediente', 'anio', 'ff', 'form_env', 'tarde', 'd', 've', 'tc', 'sara']).to_pylist() if r['sara']] ids = [r['id'] for r in P]; IDS = set(ids) f_ult = (ds.field('es_ultima_version') == True) & ((ds.field('entrada_repetida') != True) | ds.field('entrada_repetida').is_null()) L = {r['id']: r for r in leer(f'{H}.parquet', ['id', 'objeto', 'organo_contratante', 'dir3_organo', 'id_plataforma', 'dependencia', 'ciudad_organo', 'sistema_contratacion_code', 'urgencia', 'cpv_principal'], ds.field('id').isin(ids) & f_ult & (ds.field('conjunto') == 'licitaciones'))} A = collections.defaultdict(lambda: [None, set()]) for r in leer(f'{H}_ampliado.parquet', ['id', 'tipo_organo_code', 'actividad_organo_code'], ds.field('id').isin(ids) & f_ult): if A[r['id']][0] is None: A[r['id']][0] = r['tipo_organo_code'] if r['actividad_organo_code']: A[r['id']][1].add(r['actividad_organo_code']) FFT, FAM = collections.defaultdict(set), {} for r in leer(f'{H}_resultados.parquet', ['id', 'fecha_formalizacion', 'fecha_adjudicacion', 'es_ultima_version', 'entrada_repetida', 'conjunto'], ds.field('id').isin(ids) & ds.field('fecha_formalizacion').is_valid()): if r['conjunto'] != 'licitaciones' or r['entrada_repetida']: continue FFT[r['id']].add(r['fecha_formalizacion'].date()) if r['es_ultima_version'] and r['fecha_adjudicacion'] is not None: FAM[r['id']] = max(FAM.get(r['id'], r['fecha_adjudicacion'].date()), r['fecha_adjudicacion'].date()) def fechas(s): o = set() for x in (s or '').split('|'): try: o.add(dt.date.fromisoformat(x.strip()[:10])) except ValueError: pass return o marca('L+A+resultados') ENV = collections.defaultdict(set) for r in leer(f'{H}_anuncios.parquet', ['id', 'envio_fecha', 'entrada_repetida'], ds.field('id').isin(ids) & (ds.field('tipo_anuncio_code') == 'DOC_FORM') & (ds.field('medio_publicacion') == 'DOUE') & ds.field('envio_fecha').is_valid()): if not r['entrada_repetida']: ENV[r['id']] |= fechas(r['envio_fecha']) # TED marca('anuncios') XML = {r['ted_notice_id']: r for r in pq.read_table('/x/ted_xml_2024_2025_2026.parquet', columns=['ted_notice_id', 'envio_xml', 'conclusion_xml', 'carpeta']).to_pylist()} TT = collections.defaultdict(list) for r in leer('/t/ted_es_can.parquet', ['ted_notice_id', 'year', 'dt_dispatch', 'cae_nif_clean', 'expediente_sin_lote', 'notice_type', 'buyer_legal_type', 'cae_type'], (ds.field('year') >= D) & (ds.field('year') <= Hh + 1)): if not r['cae_nif_clean'] or not r['expediente_sin_lote'] or (r['notice_type'] or '') == 'can-modif': continue x = XML.get(r['ted_notice_id'], {}) b05 = r['dt_dispatch'].date() if r['dt_dispatch'] else (dt.date.fromisoformat(x['envio_xml'][:10]) if x.get('envio_xml') else None) TT[(r['cae_nif_clean'], r['expediente_sin_lote'].strip().upper())].append((r['ted_notice_id'], b05, r['buyer_legal_type'] or ('cae:' + r['cae_type'] if r['cae_type'] else None))) marca('TED') cnt = collections.Counter((up(r['nif_organo']), (r['expediente'] or '').strip().upper()) for r in P) TM = {} for r in P: k = (up(r['nif_organo']), (r['expediente'] or '').strip().upper()) if cnt[k] == 1 and k in TT and len({t[0] for t in TT[k]}) == 1: b05s = [t[1] for t in TT[k] if t[1]]; TM[r['id']] = (min(b05s) if b05s else None, {t[2] for t in TT[k] if t[2]}) # calendario propio def inh(x, ca): return x.weekday() >= 5 or x in FEST or (ca is not None and x in INHAB.get(ca, ())) def plazo(ff, ca, n): x = ff + dt.timedelta(days=n) while inh(x, ca): x = x + dt.timedelta(days=1) return x def habiles_entre(a, b, ca): # hábiles en (a, b] return sum(1 for i in range(1, (b - a).days + 1) if not inh(a + dt.timedelta(days=i), ca)) if b > a else -sum(1 for i in range(0, (a - b).days) if not inh(b + dt.timedelta(days=i + 1), ca)) def enesimo_habil(x, n, ca): while n: x += dt.timedelta(days=1); n -= 0 if inh(x, ca) else 1 return x def norm(s): return ' '.join(re.sub(r'[^a-z0-9]', ' ', unicodedata.normalize('NFKD', s or '').encode('ascii', 'ignore').decode().lower()).split()) PATS = {'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'} MU = 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'] or r['municipio_ine'][:2] not in PROV_CA: continue for parte in [r['municipio']] + r['municipio'].split('/'): k = norm(parte); w = k.split(' ') MU[k].add(PROV_CA[r['municipio_ine'][:2]]) if len(w) > 1 and w[-1] in ('el', 'la', 'los', 'las', 'l', 'a', 'o', 'os', 'as', 'es', 'sa', 'ses', 's'): MU[' '.join([w[-1]] + w[:-1])].add(PROV_CA[r['municipio_ine'][:2]]) def com(nif, dep, ci): p = [x.strip() for x in (dep or '').split(' > ')] if len(p) >= 3 and p[1] in ('ENTIDADES LOCALES', 'COMUNIDADES Y CIUDADES AUTÓNOMAS'): n = norm(p[2]) for pat, ca in PATS.items(): if pat in n: return ca for v in [ci] + re.split(r'[/,(]', ci or ''): if len(MU.get(norm(v), ())) == 1: return list(MU[norm(v)])[0] return PROV_CA.get(nif[1:3]) if nif[:1] in ('P', 'S') else None txt = open('/x/lcsp.txt', encoding='utf-8').read().split('\nANEXO IV\n', 1)[1].split('\nANEXO V', 1)[0] RG = [(int(a), int(b)) for a, b in re.findall(r'[Dd]e (\d{8})-\d a (\d{8})-\d', txt)]; PF = [s.rstrip('0') or s for s in set(re.findall(r'(\d{8})-\d', txt))] def a4(cpv): m = re.match(r'\d{8}', cpv or ''); return bool(m) and (any(a <= int(m.group()) <= b for a, b in RG) or any(m.group().startswith(p) for p in PF)) SEG = {x['nif'] for x in json.load(open('/p/SEGURIDAD_LISTA.json'))['seguridad']} ENT = collections.defaultdict(lambda: {'fj': set(), 'nom': [], 'fb': [], 'est': set(), 'amb': set()}) for r in pq.read_table('/d/unified_20261103.identidad/entes.parquet', columns=['nif', 'fj_cod', 'nombre', 'fecha_baja', 'estado', 'ambito']).to_pylist(): if not r['nif']: continue e = ENT[up(r['nif'])]; e['fj'].add(r['fj_cod']); e['nom'].append(r['nombre'] or ''); e['est'].add(r['estado']); e['amb'].add(r['ambito']) if r['fecha_baja']: e['fb'].append(r['fecha_baja']) ENT = dict(ENT) marca('calendario+entes') # 1044 AG_ID = {r['id'] for r in leer(f'{H}_resultados.parquet', ['id', 'fecha_formalizacion'], (ds.field('conjunto') == 'agregacion') & ds.field('fecha_formalizacion').is_valid()) if D <= r['fecha_formalizacion'].year <= Hh} AGD, NU = set(), collections.defaultdict(set) for r in leer(f'{H}.parquet', ['id', 'dir3_organo', 'nuts', 'fecha_publicacion'], ds.field('conjunto') == 'agregacion'): y = r['fecha_publicacion'].year if r['fecha_publicacion'] else None if r['dir3_organo'] and ((y is not None and D <= y <= Hh) or r['id'] in AG_ID): AGD.add(r['dir3_organo']) if y is not None and D <= y <= Hh: NU[(r['nuts'] or '')[:4]].add((r['id'], r['nuts'] or '')) marca('1044') N2C = {'ES61': 'AN', 'ES24': 'AR', 'ES12': 'AS', 'ES53': 'IB', 'ES70': 'CN', 'ES13': 'CB', 'ES42': 'CM', 'ES41': 'CL', 'ES51': 'CT', 'ES63': 'CE', 'ES64': 'ML', 'ES30': 'MD', 'ES52': 'VC', 'ES43': 'EX', 'ES11': 'GA', 'ES62': 'MC', 'ES22': 'NC', 'ES21': 'PV', 'ES23': 'RI'} C1044 = {N2C[k] for k, v in NU.items() if k in N2C and len(v) >= 100} # universo U y R UL = {r['id']: r for r in leer(f'{H}.parquet', ['id', 'nif_organo', 'dependencia', 'ciudad_organo', 'tipo_contrato_code', 'procedimiento_code'], f_ult & (ds.field('conjunto') == 'licitaciones') & (ds.field('sara') == True)) if r['tipo_contrato_code'] in ('1', '2', '3') and (r['procedimiento_code'] or '') not in ('7', '12')} marca('UL') UF = collections.defaultdict(set) for r in leer(f'{H}_resultados.parquet', ['id', 'fecha_formalizacion'], ds.field('id').isin(list(UL)) & f_ult & ds.field('fecha_formalizacion').is_valid()): UF[r['id']].add(r['fecha_formalizacion'].date()) UF = {i: s for i, s in UF.items() if D <= min(s).year <= Hh} marca('UF') UE = collections.defaultdict(set) for r in leer(f'{H}_anuncios.parquet', ['id', 'envio_fecha'], ds.field('id').isin(list(UF)) & f_ult & (ds.field('tipo_anuncio_code') == 'DOC_FORM') & (ds.field('medio_publicacion') == 'DOUE') & ds.field('envio_fecha').is_valid()): UE[r['id']] |= fechas(r['envio_fecha']) marca('UE') UNR = collections.defaultdict(lambda: [0, 0, 0, 0]) for i, s in UF.items(): u = UL[i]; n = up(u['nif_organo']); e = UE.get(i, set()) if not e: UNR[n][0] += 1 elif len(e) > 1: UNR[n][1] += 1 if len(s) == 1: UNR[n][2] += 1; UNR[n][3] += min(e) > plazo(min(s), com(n, u['dependencia'], u['ciudad_organo']), 10) # por contrato UMB = {2023: (431000, 5382000), 2024: (443000, 5538000), 2025: (443000, 5538000)} PA = {'cga', 'ra', 'la', 'body-pl', 'body-pl-cga', 'body-pl-ra', 'body-pl-la', 'cae:1', 'cae:3', 'cae:N', 'cae:R', 'cae:6'} C = [] for p in P: l = L[p['id']]; nif = up(p['nif_organo']); ca = com(nif, l['dependencia'], l['ciudad_organo']); ff, env = p['ff'], p['form_env'] act = A[p['id']][1]; espec = any(re.search(r'\b1\d\d\b', a) for a in act) t10 = plazo(ff, ca, 10); vs = ENV.get(p['id'], set()); b05, b11 = TM.get(p['id'], (None, set())) tarde = env > t10 and not (vs and min(vs) <= t10) and not (b05 is not None and b05 <= t10) ob = (l['objeto'] or '').upper(); dep = l['dependencia'] or ''; parts = [x.strip() for x in dep.split(' > ')]; ve = p['ve']; tc = p['tc']; cpv = l['cpv_principal'] or '' u = UMB[ff.year]; lim = u[1] if tc == '3' else (1000000 if tc == '2' and a4(cpv) else u[0]) rec = (tc in ('1', '2') and ve is not None and ve > 100000) or (tc == '3' and ve is not None and ve > 3000000) or espec fam = FAM.get(p['id']) C.append(dict(id=p['id'], nif=nif, anio=p['anio'], ff=ff, env=env, ca=ca, t10=t10, tarde=tarde, d=p['d'], espec=espec, b11=b11, idp=l['id_plataforma'], dir3=l['dir3_organo'], dep=dep, org=(l['organo_contratante'] or '').upper(), toc=A[p['id']][0], am=l['sistema_contratacion_code'] in ('1', '2', '3', '4') or bool(re.search(r'ACUERDO MARCO|ACORD MARC|ESPARRU.?AKORDIO|SISTEMA DIN[AÁ]MIC', ob)), se=espec and (ve is None or ve < lim), em=l['urgencia'] == '3', b12=bool(re.search(r'24/2011|DEFENSA Y SEGURIDAD', ob)), nav=(nif[:1] in 'PSQ' and nif[1:3] == '31' and 'ADMINISTRACIÓN GENERAL DEL ESTADO' not in dep) or (len(parts) >= 3 and parts[1] in ('ENTIDADES LOCALES', 'COMUNIDADES Y CIUDADES AUTÓNOMAS') and ('NAVARRA' in parts[2].upper() or 'NAFARROA' in parts[2].upper())), m3=tarde and env <= enesimo_habil(t10, 3 if ca == 'CN' else 2, ca), rec=bool(rec and fam is not None and habiles_entre(fam, ff, ca) < 15), inest=len(FFT.get(p['id'], ())) > 1, rep=len(vs) > 1, j30=tarde and env > plazo(ff, ca, 30) and not (tc == '2' and a4(cpv)), k48=tarde and env > plazo(ff, ca, 48))) # naturaleza GRP = {} porn = collections.defaultdict(list) for x in C: porn[x['nif']].append(x) PATR = r'CONSORCI|PARTZUERGO|EMPRESARIAL|FUNDACI|FUNDAZIO|SOCIEDAD|SOCIETAT|MUTUA| S\.?A\.?U?\.?( |$)| S\.?L\.?U?\.?( |$)' DA44 = r'CONGRESO DE LOS DIPUTADOS|SENADO|CONSEJO GENERAL DEL PODER JUDICIAL|TRIBUNAL CONSTITUCIONAL|TRIBUNAL DE CUENTAS|DEFENSOR DEL PUEBLO|PARLAMENT|CORTES DE |CORTS |ASAMBLEA (DE|REGIONAL)|ASSEMBLEA|JUNTA GENERAL DEL PRINCIPADO|C[ÁA]MARA DE C(UENTAS|OMPTOS)|SINDICATURA|CONSELLO DE CONTAS|AUDIENCIA DE CUENTAS|ARARTEKO|S[ÍI]NDIC|VALEDOR DO POBO|PROCURADOR DEL COM|DIPUTADO DEL COM|JUSTICIA DE ARAG' for nif, xs in porn.items(): inv = ENT.get(nif); tx = ([sorted(inv['nom'])[0].upper()] if inv else []) + sorted({x['org'] for x in xs if x['org']}) b = [y for x in xs for y in x['b11']]; pad = len(b) > 0 and set(b) <= PA fj = inv['fj'] if inv else set() if nif[0] == 'S' and any(re.search(DA44, t) for t in tx): g = 1 elif any('MUTUA COLABORADORA CON LA SEGURIDAD SOCIAL' in t for t in tx): g = 1 elif fj & {3, 7, 8, 9, 13, 19} or 6 in fj: g = 1 elif fj & {1, 2, 4, 12, 14, 20}: g = 2 elif inv is None and nif[0] in 'SP': g = 2 if any(re.search(PATR, t) for t in tx) else 1 elif inv is None and nif[0] == 'Q' and any('UNIVERSI' in t for t in tx): g = 1 else: g = 0 GRP[nif] = (g, pad, tx, inv) for x in C: g, pad, _, _ = GRP[x['nif']]; x['g2'] = g == 2 and not x['espec'] and not pad x['fuera'] = 'x_am' if x['am'] else 'x_se' if x['se'] else 'x_emerg' if x['em'] else 'x_b12' if x['b12'] else 'x_nav' if x['nav'] else 'x_g2' if x['g2'] else '' V = [x for x in C if not x['fuera']] lt = collections.Counter((x['nif'], x['env']) for x in V if x['tarde']) for x in C: x['dud'] = x['tarde'] and (x['rec'] or x['inest'] or x['rep'] or (not x['fuera'] and lt[(x['nif'], x['env'])] >= 5)) P0 = sum(x['tarde'] for x in V) / len(V) P0A = {a: sum(x['tarde'] for x in V if x['anio'] == a) / sum(1 for x in V if x['anio'] == a) for a in range(D, Hh + 1)} # estadística escrita aparte def wil(k, n, z=1.959963984540054): if not n: return 0.0 c_ = z * z / n; ph = k / n return (ph + c_ / 2 - z * math.sqrt(ph * (1 - ph) / n + c_ / (4 * n))) / (1 + c_) def cola(k, n, p): if k <= 0: return 1.0 lpmf = lambda j: math.lgamma(n + 1) - math.lgamma(j + 1) - math.lgamma(n - j + 1) + j * math.log(p) + (n - j) * math.log(1 - p) v = [lpmf(j) for j in range(k, n + 1)]; m = max(v); return min(1.0, sum(math.exp(t - m) for t in v) * math.exp(m)) def bhset(pv, q=0.05): o = sorted(range(len(pv)), key=lambda i: (pv[i], i)); k = 0 for r, i in enumerate(o, 1): if pv[i] <= q * r / len(pv): k = r return set(o[:k]) # entidades TIPO = {'ADMINISTRACIÓN GENERAL DEL ESTADO': 'AGE', 'COMUNIDADES Y CIUDADES AUTÓNOMAS': 'CCAA', 'ENTIDADES LOCALES': 'EELL'} ORGP = r'ALCALD|PRESIDEN|PLENO|JUNTA DE GOBIERNO|CONCEJAL|SECRETAR|JEFATURA|DIRECCI|[ÓO]RGANOS? DIRECTIVOS|SERVICIO|GERENCIA|TENENCIA|GERENTE|CONSEJO DE ADMINISTRACI|CONSEJERO DELEGADO|RECTOR' E = {} for nif, xs in porn.items(): g, pad, tx, inv = GRP[nif]; v = [x for x in xs if not x['fuera']] dc = collections.Counter(x['dep'] for x in xs if x['dep']); dm = sorted(dc.items(), key=lambda t: (-t[1], t[0]))[0][0] if dc else ''; sg = [s.strip() for s in dm.split(' > ')] if inv: npub = sorted(inv['nom'])[0].upper() elif len(sg) >= 3 and sg[1] == 'ADMINISTRACIÓN GENERAL DEL ESTADO': npub = sg[2] + ' (Administración General del Estado)' else: j = len(sg) - 1 while j > 1 and re.search(ORGP, sg[j].upper()): j -= 1 npub = sg[j] if j > 1 else '' if re.search(ORGP, npub.upper()): npub = '' cc = collections.Counter(x['ca'] for x in xs if x['ca']); ca = sorted(cc.items(), key=lambda t: (-t[1], t[0]))[0][0] if cc else None tc_ = collections.Counter(x['toc'] for x in xs); toc = sorted(tc_.items(), key=lambda t: (-t[1], t[0] or ''))[0][0] tipo = TIPO.get(sg[1] if len(sg) > 1 else '', 'OTRAS') b6ii = (toc == '2' or tipo == 'CCAA' or (inv is not None and 'autonomico' in inv['amb'])) and ca in C1044 b7 = inv is not None and (any(f <= dt.date(Hh, 12, 31) for f in inv['fb']) or ('baja' in inv['est'] and not inv['fb'])) real = any(re.search(r'CASA DE S\.?\s?M|CASA REAL|CASA DE SU MAJESTAD', t) for t in tx) el = g in (1, 2) and ca is not None and not ({x['dir3'] for x in xs if x['dir3']} & AGD) and not b6ii and not b7 and bool(npub) and not real and not all(x['nav'] for x in xs) e = dict(N=len(v), K=sum(x['tarde'] for x in v), KL=sum(x['tarde'] and not x['dud'] for x in v), K3=sum(x['tarde'] and not x['m3'] for x in v), N4=sum(x['d'] <= 180 for x in v), K4=sum(x['tarde'] and x['d'] <= 180 for x in v), J=sum(x['j30'] for x in v), K48=sum(x['k48'] for x in v), U=UNR[nif][0], R=UNR[nif][1], R1n=UNR[nif][2], R1k=UNR[nif][3], tipo=tipo, el=el, seg=nif in SEG, grupo=g) for a in range(D, Hh + 1): e[f'N{a}'] = sum(x['anio'] == a for x in v); e[f'K{a}'] = sum(x['tarde'] for x in v if x['anio'] == a) E[nif] = e G = sorted([n for n in E if E[n]['N'] >= NMIN]) def tr(n): return '20-29' if n < 30 else '30-49' if n < 50 else '50-99' if n < 100 else '100+' TRL = ['20-29', '30-49', '50-99', '100+'] CEL = {} for t in {E[n]['tipo'] for n in G}: gs = [[x] for x in TRL] while len(gs) > 1: cnts = [sum(1 for n in G if E[n]['tipo'] == t and tr(E[n]['N']) in g) for g in gs] i = next((i for i, c_ in enumerate(cnts) if c_ < 5), None) if i is None: break j = i - 1 if i > 0 else 1; gs[j] = sorted(gs[j] + gs[i], key=TRL.index); gs.pop(i) for g in gs: for x in g: CEL[(t, x)] = t + '|' + '+'.join(g) for n in G: E[n]['celda'] = CEL[(E[n]['tipo'], tr(E[n]['N']))] PEX = {} for n in G: PEX.setdefault(E[n]['celda'], [0, 0]); PEX[E[n]['celda']][0] += E[n]['K']; PEX[E[n]['celda']][1] += E[n]['N'] PEX = {k: a / b for k, (a, b) in PEX.items()} def cab(lista, k, nn, p0): pv = [cola(k(n), nn(n), p0(n)) for n in lista]; s = bhset(pv) return {lista[i] for i in s if E[lista[i]]['el'] and not E[lista[i]]['seg'] and wil(k(lista[i]), nn(lista[i])) > p0(lista[i]) and k(lista[i]) / nn(lista[i]) >= p0(lista[i]) + 0.05}, pv H1, PV1 = cab(G, lambda n: E[n]['K'], lambda n: E[n]['N'], lambda n: P0) H2, _ = cab(G, lambda n: E[n]['K'], lambda n: E[n]['N'], lambda n: PEX[E[n]['celda']]) H3, _ = cab(G, lambda n: E[n]['K3'], lambda n: E[n]['N'], lambda n: P0) P04 = sum(e['K4'] for e in E.values()) / sum(e['N4'] for e in E.values()); G4 = [n for n in G if E[n]['N4'] >= NMIN] H4, _ = cab(G4, lambda n: E[n]['K4'], lambda n: E[n]['N4'], lambda n: P04) H5, _ = cab([n for n in G if E[n]['N'] >= 30], lambda n: E[n]['K'], lambda n: E[n]['N'], lambda n: P0) dt_ = collections.Counter(x['env'] for x in V if x['tarde']); AT = {k for k, v in dt_.items() if v >= 20} V6 = [x for x in V if x['env'] not in AT]; P06 = sum(x['tarde'] for x in V6) / len(V6); n6 = collections.Counter(x['nif'] for x in V6); k6 = collections.Counter(x['nif'] for x in V6 if x['tarde']) H6, _ = cab([n for n in G if n6[n] >= NMIN], lambda n: k6[n], lambda n: n6[n], lambda n: P06) mit = collections.defaultdict(lambda: [[0, 0], [0, 0]]) for x in V: h = int(hashlib.md5((x['nif'] + '|' + x['env'].isoformat() + '|tl-doue-ent-mitad').encode()).hexdigest(), 16) & 1; mit[x['nif']][h][0] += 1; mit[x['nif']][h][1] += x['tarde'] # P1 propia (otra semilla y otro barajado): misma conclusión y p99 a ±10 % o ±1 gi = {n: i for i, n in enumerate(G)}; st = collections.defaultdict(list) for j, x in enumerate(V): st[(E[x['nif']]['tipo'], tr(E[x['nif']]['N']) if E[x['nif']]['N'] >= NMIN else f'<{NMIN}', x['anio'])].append(j) labs = [x['tarde'] for x in V]; rr = random.Random(7) def hs(lb): k = collections.Counter(V[j]['nif'] for j, t in enumerate(lb) if t) pv = [cola(k[n], E[n]['N'], P0) for n in G]; s = bhset(pv) return sum(1 for i in s if E[G[i]]['el'] and not E[G[i]]['seg'] and wil(k[G[i]], E[G[i]]['N']) > P0 and k[G[i]] / E[G[i]]['N'] >= P0 + 0.05) perm = [] for _ in range(int(os.environ.get('NPERM', '1000'))): lb = labs[:] for js in st.values(): sub = [lb[j] for j in js]; rr.shuffle(sub) for j, t in zip(js, sub): lb[j] = t perm.append(hs(lb)) perm.sort(); p99 = perm[min(len(perm) - 1, math.ceil(0.99 * len(perm)) - 1)] # comparación con la implementación 1 c1 = {r['id']: r for r in pq.read_table(f'{PRIV}/contratos_{D}_{Hh}.parquet').to_pylist()} e1 = {r['nif']: r for r in pq.read_table(f'{PRIV}/entidades_{D}_{Hh}.parquet').to_pylist()} if os.path.exists(f'{PRIV}/entidades_{D}_{Hh}.parquet') else {} difc = collections.Counter(); muestra = [] for x in C: y = c1[x['id']] for a, b in (('t10', 'tope_auto'), ('tarde', 'tarde'), ('fuera', 'fuera'), ('dud', 'dudoso'), ('m3', 'm3_salva'), ('j30', 'j30'), ('k48', 'k48'), ('ca', 'ca')): va = x[a] if a != 'm3' else x['m3'] if va != y[b]: difc[a] += 1; muestra.append((x['id'][-20:], a, str(va), str(y[b]))) if len(muestra) < 10 else None dife = collections.Counter() if set(G) != set(e1): dife['conjunto_N_ge_min'] += 1 for n in G: if n not in e1: continue e, y = E[n], e1[n] pares = [('N', 'N'), ('K', 'K'), ('KL', 'K_limpio'), ('K3', 'K_m3'), ('N4', 'N_m4'), ('K4', 'K_m4'), ('J', 'J'), ('K48', 'K48'), ('U', 'U'), ('R', 'R'), ('el', 'elegible'), ('seg', 'seguridad'), ('grupo', 'grupo'), ('tipo', 'tipo')] + \ [(f'N{a}', f'N{a}') for a in range(D, Hh + 1)] + [(f'K{a}', f'K{a}') for a in range(D, Hh + 1)] for a, b in pares: if e[a] != y[b]: dife[a] += 1 if abs(wil(e['K'], e['N']) - y['lb_bruta']) > 1e-9: dife['lb_bruta'] += 1 if abs(wil(e['KL'], e['N']) - y['lb_limpia']) > 1e-9: dife['lb_limpia'] += 1 if abs(PV1[G.index(n)] - y['p']) > 1e-9 * max(1e-300, y['p']) and abs(PV1[G.index(n)] - y['p']) > 1e-15: dife['p'] += 1 for hset, key in ((H1, 'cabeza'), (H2, 'm2'), (H3, 'm3'), (H4, 'm4'), (H5, 'm5'), (H6, 'm6')): if (n in hset) != bool(y[key]): dife[key] += 1 if json.dumps(mit[n]) != y['mitades']: dife['mitades'] += 1 p99_1 = json.load(open(f'{SAL}/50_entidad_{D}_{Hh}.json'))['placebo_P1'] res = dict(desde=D, hasta=Hh, contratos=len(C), p0=round(P0, 6), cabeza=len(H1), dif_contratos=dict(difc), dif_entidades=dict(dife), muestra=muestra, P1_impl2=dict(p99=p99, media=round(sum(perm) / len(perm), 3), pasa=len(H1) > p99 and sum(perm) / len(perm) < 0.1 * len(H1) if H1 else False), P1_impl1=p99_1, cero_diferencias=not difc and not dife, segundos=round(time.time() - T0)) res['P1_coincide'] = res['P1_impl2']['pasa'] == p99_1['pasa'] and abs(p99 - p99_1['p99_permutada']) <= max(1, 0.1 * p99_1['p99_permutada']) json.dump(res, open(f'{SAL}/60_impl2_{D}_{Hh}.json', 'w'), indent=1, ensure_ascii=False, default=str) print(json.dumps(res, ensure_ascii=False, default=str))