"""SUB1 · 20 · doble relación por ente-periodo, embudo (DEFINICIONES_PREVIAS §4-6), salidas publicables. Escribe interno/{ea,eb,ea_sens,ea_ventana,doble}.parquet, salidas/publicable_ente_anio.csv, salidas/publicable_mercado_anio.csv, salidas/funnel_anio.csv, salidas/20_embudo.json.""" import duckdb, json, math, csv, sys, time sys.path.insert(0, '/w/py') from comun import tau2, posicion, Z95, Z998, NMIN T0 = time.time() c = duckdb.connect(); x = c.execute x("SET threads=4; SET memory_limit='6GB'; SET temp_directory='/w/tmp/duck'; SET max_temp_directory_size='5GB'") def log(*a): print(f"[{time.time()-T0:6.1f}s]", *a, flush=True) x("CREATE TABLE cfil AS SELECT * FROM '/w/interno/c_filas.parquet' WHERE ente IS NOT NULL") x("CREATE TABLE sfil AS SELECT * FROM '/w/interno/s_filas.parquet' WHERE ente IS NOT NULL") x("CREATE TABLE te AS SELECT * FROM '/w/interno/tipo_ente.parquet'") x("CREATE TABLE conc_casado AS SELECT DISTINCT ente FROM sfil") EMIN = 0.001 def tramo(nb): return '1-9' if nb < 10 else ('10-99' if nb < 100 else ('100-999' if nb < 1000 else '1000+')) def unidades(emp, per, ventana=False, nombre='ea'): """emp: columna booleana de empresa; per: expresión SQL del periodo sobre anio. Devuelve lista de dicts por ente-periodo.""" x(f"""CREATE OR REPLACE TABLE cf AS SELECT ente, ({per})::VARCHAR per, empresa_clave e, coalesce(sum(importe) FILTER (WHERE abs(importe) <= 1e9), 0) w, count(*) nadj FROM cfil WHERE {emp} GROUP BY ALL""") x(f"""CREATE OR REPLACE TABLE sf AS SELECT ente, ({per})::VARCHAR per, cif e, sum(importe) imp_s, count(*) ns FROM sfil GROUP BY ALL""") if ventana: # sensibilidad: concesión en t-1..t+1 x("""CREATE OR REPLACE TABLE sfv AS SELECT s.ente, (s.per::INT + d)::VARCHAR per, s.e, sum(s.imp_s) imp_s, sum(s.ns) ns FROM sf s, (SELECT unnest([-1,0,1]) d) WHERE s.per::INT + d BETWEEN 2022 AND 2025 GROUP BY ALL""") sft = 'sfv' else: sft = 'sf' x(f"""CREATE OR REPLACE TABLE j AS SELECT cf.*, (s.e IS NOT NULL) y, coalesce(s.imp_s,0) imp_s_e FROM cf LEFT JOIN {sft} s USING (ente, per, e)""") x("""CREATE OR REPLACE TABLE b AS SELECT ente, per, count(DISTINCT e) n_benef, sum(imp_s) imp_s, sum(ns) n_conc FROM sf GROUP BY ALL""") x(f"""CREATE OR REPLACE TABLE {nombre} AS SELECT j.ente, j.per, coalesce(te.tipo,'sin_tipo') tipo, count(*) n_emp, count(*) FILTER (WHERE w > 0) n_w, sum(nadj) n_adj, sum(w) imp_c, sum(w*w) w2, count(*) FILTER (WHERE y) k, sum(w) FILTER (WHERE y) imp_c_doble, count(*) FILTER (WHERE y AND w > 0) k_w, sum(imp_s_e) imp_s_doble, coalesce(b.n_benef,0) n_benef, coalesce(b.imp_s,0) imp_s, coalesce(b.n_conc,0) n_conc FROM j LEFT JOIN b USING (ente, per) LEFT JOIN te USING (ente) GROUP BY j.ente, j.per, te.tipo, b.n_benef, b.imp_s, b.n_conc""") rows = x(f"SELECT * FROM {nombre}").fetchall(); cols = [d[0] for d in c.description] U = [dict(zip(cols, r)) for r in rows] for u in U: u['imp_c_doble'] = u['imp_c_doble'] or 0.0 u['r'] = u['imp_c_doble'] / u['imp_c'] if u['imp_c'] > 0 else None u['n_eff'] = u['imp_c'] ** 2 / u['w2'] if u['w2'] > 0 else 0.0 u['rk'] = u['k'] / u['n_emp'] u['concede'] = u['n_benef'] > 0 u['tramo'] = tramo(u['n_benef']) u['elig'] = u['concede'] and u['n_w'] >= NMIN u['elig10'] = u['concede'] and u['n_w'] >= 10 # esperado: media de r de los OTROS elegibles del estrato (tipo, per, tramo) -> (tipo, per) -> (per) for medida, rr in (('e', 'r'), ('ek', 'rk')): niveles = [lambda u: (u['tipo'], u['per'], u['tramo']), lambda u: (u['tipo'], u['per']), lambda u: (u['per'],)] sumas = [] for f in niveles: d = {} for u in U: if u['elig']: s = d.setdefault(f(u), [0.0, 0]); s[0] += u[rr]; s[1] += 1 sumas.append(d) for u in U: if not u['elig10']: u[medida] = None; u[medida + '_nivel'] = None; continue for lv, (f, d) in enumerate(zip(niveles, sumas)): s = d.get(f(u), [0.0, 0]); sm, nn = s if u['elig']: sm -= u[rr]; nn -= 1 if nn >= 5: u[medida] = min(max(sm / nn, EMIN), 1 - EMIN); u[medida + '_nivel'] = lv; break else: u[medida] = None; u[medida + '_nivel'] = None # s, tau2 (dos versiones) por periodo, z_D pers = sorted({u['per'] for u in U}) tinfo = {} for p in pers: for medida, rr, nn in (('e', 'r', 'n_eff'), ('ek', 'rk', 'n_emp')): fil = [(u[rr], u[medida], math.sqrt(u[medida] * (1 - u[medida]) / u[nn])) for u in U if u['per'] == p and u['elig'] and u[medida] is not None] tw = tau2(fil, True); tn = tau2(fil, False) tinfo[(p, medida)] = {'tau2_w': tw[0], 'phi_w': tw[1], 'tau2_nw': tn[0], 'phi_nw': tn[1], 'I': tw[2]} for u in U: for medida, rr, nn, suf in (('e', 'r', 'n_eff', ''), ('ek', 'rk', 'n_emp', '_k')): if u[medida] is None: u['s' + suf] = u['zd' + suf] = u['zd_nw' + suf] = None; continue s = math.sqrt(u[medida] * (1 - u[medida]) / u[nn]); ti = tinfo[(u['per'], medida)] u['s' + suf] = s u['zd' + suf] = (u[rr] - u[medida]) / math.sqrt(s * s + ti['tau2_w']) u['zd_nw' + suf] = (u[rr] - u[medida]) / math.sqrt(s * s + ti['tau2_nw']) u['hecho_w'] = bool(u['elig'] and u['zd'] is not None and u['zd'] > Z998) u['hecho_nw'] = bool(u['elig'] and u['zd_nw'] is not None and u['zd_nw'] > Z998) u['hecho'] = u['hecho_w'] and u['hecho_nw'] u['fuera95'] = bool(u['elig'] and u['zd'] is not None and u['zd'] > Z95 and u['zd_nw'] > Z95) u['hecho_k'] = bool(u['elig'] and u['zd_k'] is not None and u['zd_k'] > Z998 and u['zd_nw_k'] > Z998) return U, {f"{p}|{m}": v for (p, m), v in tinfo.items()} def guardar(U, nombre): cols = list(U[0].keys()) import pyarrow as pa, pyarrow.parquet as pq pq.write_table(pa.table({k: [u[k] for u in U] for k in cols}), f'/w/interno/{nombre}.parquet') RES = {} EA, RES['tau_anio'] = unidades('emp_principal', 'anio', nombre='ea'); guardar(EA, 'ea'); log('ea', len(EA)) EB, RES['tau_bloque'] = unidades('emp_principal', "CASE WHEN anio <= 2023 THEN 'B1' ELSE 'B2' END", nombre='eb'); guardar(EB, 'eb'); log('eb', len(EB)) ES, RES['tau_sens'] = unidades('emp_sens', 'anio', nombre='es'); guardar(ES, 'ea_sens'); log('es', len(ES)) EV, _ = unidades('emp_principal', 'anio', ventana=True, nombre='ev'); guardar(EV, 'ea_ventana'); log('ev', len(EV)) def resumen(U): out = {} for p in sorted({u['per'] for u in U}): g = [u for u in U if u['per'] == p] out[p] = {'entes_con_adjudicatarias': len(g), 'entes_conceden': sum(u['concede'] for u in g), 'entes_con_doble': sum(u['k'] > 0 for u in g), 'empresas_doble_pares': sum(u['k'] for u in g), 'imp_c': sum(u['imp_c'] for u in g), 'imp_c_doble': sum(u['imp_c_doble'] for u in g), 'imp_c_entes_que_conceden': sum(u['imp_c'] for u in g if u['concede']), 'imp_s_doble': sum(u['imp_s_doble'] for u in g), 'embudo_n30': sum(u['elig'] for u in g), 'hecho': sum(u['hecho'] for u in g), 'hecho_solo_w': sum(u['hecho_w'] and not u['hecho_nw'] for u in g), 'hecho_solo_nw': sum(u['hecho_nw'] and not u['hecho_w'] for u in g), 'fuera95': sum(u['fuera95'] for u in g), 'debajo998': sum(1 for u in g if u['elig'] and u['zd'] is not None and u['zd'] < -Z998), 'hecho_recuento': sum(u['hecho_k'] for u in g), 'mediana_r_embudo': sorted(u['r'] for u in g if u['elig'])[sum(u['elig'] for u in g) // 2] if any(u['elig'] for u in g) else None} return out RES['resumen_anio'] = resumen(EA); RES['resumen_bloque'] = resumen(EB); RES['resumen_sens_diccionario'] = resumen(ES); RES['resumen_ventana_t1'] = resumen(EV) # empresas distintas con doble relación (alguna vez) x("CREATE TABLE dob AS SELECT DISTINCT c.ente, c.anio, c.empresa_clave FROM cfil c JOIN sfil s ON s.ente=c.ente AND s.anio=c.anio AND s.cif=c.empresa_clave WHERE c.emp_principal") x("COPY dob TO '/w/interno/doble.parquet' (FORMAT parquet)") RES['empresas_distintas_doble'] = x("SELECT count(DISTINCT empresa_clave), count(*), count(DISTINCT ente) FROM dob").fetchone() RES['empresas_distintas_adjudicatarias'] = x("SELECT count(DISTINCT empresa_clave) FROM cfil WHERE emp_principal").fetchone()[0] RES['beneficiarias_distintas_entes_casados'] = x("SELECT count(DISTINCT cif) FROM sfil").fetchone()[0] # por tipo de ente (2022-2025) tipos = sorted({u['tipo'] for u in EA}) RES['por_tipo'] = {t: {'ente_anios': sum(1 for u in EA if u['tipo'] == t), 'conceden': sum(1 for u in EA if u['tipo'] == t and u['concede']), 'con_doble': sum(1 for u in EA if u['tipo'] == t and u['k'] > 0), 'pct_imp_c_doble_en_los_que_conceden': (sum(u['imp_c_doble'] for u in EA if u['tipo'] == t and u['concede']) / max(sum(u['imp_c'] for u in EA if u['tipo'] == t and u['concede']), 1)), 'embudo': sum(1 for u in EA if u['tipo'] == t and u['elig']), 'hecho': sum(1 for u in EA if u['tipo'] == t and u['hecho'])} for t in tipos} # K de N kn = {} for u in EA: if u['elig']: s = kn.setdefault((u['tipo'], u['per']), [0, 0]); s[0] += u['hecho']; s[1] += 1 RES['entes_distintos_hecho'] = len({u['ente'] for u in EA if u['hecho']}) RES['hecho_por_n_anios'] = {} from collections import Counter cnt = Counter(u['ente'] for u in EA if u['hecho']); RES['hecho_por_n_anios'] = dict(Counter(cnt.values())) # ── publicable_ente_anio ── x("""CREATE TABLE nom AS SELECT ee.ente, arg_max(e.nombre, CASE WHEN ee.entidad_clave = ee.ente THEN 1e18 ELSE e.filas END) nombre, bool_or(ee.ente_dni) dni FROM '/w/interno/entidad_ente.parquet' ee JOIN '/d/unified_20261018.identidad/entidades.parquet' e USING (entidad_clave) GROUP BY 1""") nom = {a: (b, d) for a, b, d in x("SELECT ente, nombre, dni FROM nom").fetchall()} casados = {r[0] for r in x("SELECT ente FROM conc_casado").fetchall()} excl = 0 with open('/w/salidas/publicable_ente_anio.csv', 'w', newline='') as fh: w = csv.writer(fh) w.writerow(['ente_clave', 'ente_nombre', 'tipo_ente', 'anio', 'consta_como_concedente_bdns', 'adjudicatarias_empresas', 'adjudicaciones', 'importe_adjudicado_eur', 'beneficiarias_personas_juridicas', 'concesiones', 'importe_concedido_eur', 'empresas_doble_relacion', 'importe_adjudicado_a_doble_eur', 'importe_concedido_a_doble_eur', 'pct_importe_adjudicado_a_doble', 'pct_adjudicatarias_doble', 'tasa_esperada_su_tipo', 'z_D', 'z_D_sin_winsorizar', 'posicion', 'hecho_sub1', 'K_su_tipo_anio', 'N_su_tipo_anio']) for u in sorted(EA, key=lambda u: (u['ente'], u['per'])): nm, dni = nom.get(u['ente'], (None, False)) if dni: excl += 1; continue cas = u['ente'] in casados pos = (posicion(u['n_w'], u['zd']) if u['zd'] is not None else ('muestra insuficiente' if u['concede'] else 'no concede')) if u['concede'] else ('no concede' if cas else 'sin dato BDNS') K, N = kn.get((u['tipo'], u['per']), ['', '']) w.writerow([u['ente'], nm, u['tipo'], u['per'], int(cas), u['n_emp'], u['n_adj'], f"{u['imp_c']:.2f}", u['n_benef'], u['n_conc'], f"{u['imp_s']:.2f}", u['k'], f"{u['imp_c_doble']:.2f}", f"{u['imp_s_doble']:.2f}", f"{u['r']:.4f}" if u['r'] is not None else '', f"{u['rk']:.4f}", f"{u['e']:.4f}" if u['e'] is not None else '', f"{u['zd']:.3f}" if u['zd'] is not None else '', f"{u['zd_nw']:.3f}" if u['zd_nw'] is not None else '', pos, int(u['hecho']), K if u['elig'] else '', N if u['elig'] else '']) RES['publicable_excluidos_dni'] = excl # ── publicable_mercado_anio ── x("""CREATE TABLE cm AS SELECT c.anio, coalesce(c.cpv_division,'??') cpv_division, CASE WHEN c.tipo_contrato IN ('Obras','Servicios','Suministros') THEN c.tipo_contrato ELSE 'Otros' END tipo_contrato, count(*) adj, coalesce(sum(c.importe) FILTER (WHERE abs(c.importe)<=1e9),0) imp, count(*) FILTER (WHERE d.ente IS NOT NULL) adj_d, coalesce(sum(c.importe) FILTER (WHERE abs(c.importe)<=1e9 AND d.ente IS NOT NULL),0) imp_d, count(*) FILTER (WHERE c.ente IN (SELECT ente FROM conc_casado)) adj_conc, coalesce(sum(c.importe) FILTER (WHERE abs(c.importe)<=1e9 AND c.ente IN (SELECT ente FROM conc_casado)),0) imp_conc FROM cfil c LEFT JOIN dob d ON d.ente=c.ente AND d.anio=c.anio AND d.empresa_clave=c.empresa_clave WHERE c.emp_principal GROUP BY ALL ORDER BY 1,2,3""") with open('/w/salidas/publicable_mercado_anio.csv', 'w', newline='') as fh: w = csv.writer(fh) w.writerow(['anio', 'cpv_division', 'tipo_contrato', 'adjudicaciones_a_empresas', 'importe_adjudicado_eur', 'adjudicaciones_doble_relacion', 'importe_doble_relacion_eur', 'pct_importe_doble', 'adjudicaciones_de_entes_concedentes', 'importe_de_entes_concedentes_eur', 'pct_importe_doble_sobre_entes_concedentes']) for a, cpv, tc, adj, imp, adjd, impd, adjc, impc in x("SELECT * FROM cm").fetchall(): w.writerow([a, cpv, tc, adj, f"{imp:.2f}", adjd, f"{impd:.2f}", f"{impd/imp:.4f}" if imp else '', adjc, f"{impc:.2f}", f"{impd/impc:.4f}" if impc else '']) RES['mercado_tipo_contrato'] = x("SELECT tipo_contrato, sum(adj), sum(adj_d), sum(imp_d)/sum(imp), sum(imp_d)/nullif(sum(imp_conc),0) FROM cm GROUP BY 1 ORDER BY 1").fetchall() RES['mercado_top_divisiones_pct'] = x("SELECT cpv_division, sum(adj), sum(imp)/1e6, sum(imp_d)/sum(imp) FROM cm GROUP BY 1 HAVING sum(adj)>=5000 ORDER BY 4 DESC LIMIT 12").fetchall() # funnel por año (para el dibujo): rejilla de n_eff with open('/w/salidas/funnel_anio.csv', 'w', newline='') as fh: w = csv.writer(fh); w.writerow(['anio', 'n_eff', 'p_media', 'tau2_w', 'tau2_nw', 'sup_95_w', 'sup_998_w', 'sup_998_nw']) for p in sorted({u['per'] for u in EA}): g = [u for u in EA if u['per'] == p and u['elig']] pb = sum(u['r'] for u in g) / len(g); tw = RES['tau_anio'][f'{p}|e']['tau2_w']; tn = RES['tau_anio'][f'{p}|e']['tau2_nw'] for i in range(40): ne = 2 * (10 ** (i * 4 / 39)) sd = math.sqrt(pb * (1 - pb) / ne) w.writerow([p, f"{ne:.2f}", f"{pb:.5f}", f"{tw:.6f}", f"{tn:.6f}", f"{pb + Z95*math.sqrt(sd*sd+tw):.5f}", f"{pb + Z998*math.sqrt(sd*sd+tw):.5f}", f"{pb + Z998*math.sqrt(sd*sd+tn):.5f}"]) RES['kn'] = {f"{t}|{p}": v for (t, p), v in sorted(kn.items())} json.dump(RES, open('/w/salidas/20_embudo.json', 'w'), ensure_ascii=False, indent=1, default=str) log(json.dumps({k: RES[k] for k in ('resumen_anio', 'empresas_distintas_doble', 'tau_anio', 'por_tipo', 'entes_distintos_hecho', 'hecho_por_n_anios')}, ensure_ascii=False, default=str)[:6000])