"""CO1 · 25 · EXPLORATORIO POSTERIOR (enmienda §12-1, no decide): (a) conjunto del fallo frente a conjuntos aleatorios CONEXOS (bola de nieve desde una semilla del mismo decil de fuerza que la sancionada más fuerte); (b) diagnóstico de los controles: cuántos son componentes conexas enteras (E = 1) y AUC dentro de la componente gigante.""" import sys, json, random, itertools import duckdb, pyarrow.parquet as pq con = duckdb.connect('/w/tmp/co1.duckdb', read_only=True); x = con.execute x("SET threads=4; SET memory_limit='3GB'") redes = x("SELECT m.exp, m.cpv2, p.a0, p.a1 FROM merc m JOIN per p USING (exp) WHERE m.exp <> 'SAMUR/01/24' ORDER BY 1, 2").fetchall() sanc = {} for e, k in x("SELECT exp, k FROM sanc").fetchall(): sanc.setdefault(e, set()).add(k) todas = set().union(*sanc.values()) def edges(cpv2, a0, a1, var): if var == 'A': q = "SELECT DISTINCT lic g, emp FROM u WHERE cpv2 = ? AND anio BETWEEN ? AND ?"; cap = 30 else: q = "SELECT DISTINCT organo_clave || '|' || anio g, emp FROM u WHERE cpv2 = ? AND anio BETWEEN ? AND ? AND organo_clave IS NOT NULL"; cap = 50 rows = x(f"WITH t AS ({q}), n AS (SELECT g FROM t GROUP BY g HAVING count(*) BETWEEN 2 AND {cap}) SELECT g, list(emp ORDER BY emp) FROM t JOIN n USING (g) GROUP BY g", [cpv2, a0, a1]).fetchall() G = {} for _, es in rows: for a, b in itertools.combinations(es, 2): G.setdefault(a, {}); G.setdefault(b, {}); G[a][b] = G[a].get(b, 0) + 1; G[b][a] = G[b].get(a, 0) + 1 return G def score(G, s): k = len(s); win = wout = 0 for n in s: for v, w in G[n].items(): if v in s: win += w else: wout += w win /= 2; C = win / (k * (k - 1) / 2); E = win / (win + wout) if win + wout else 0.0 return C * E def comps(G): seen, out = set(), [] for n in G: if n in seen: continue st, c = [n], set([n]); seen.add(n) while st: a = st.pop() for v in G[a]: if v not in seen: seen.add(v); c.add(v); st.append(v) out.append(c) return out R = {} grp = pq.read_table('/w/interno/10_grupos.parquet').to_pylist(); mem = pq.read_table('/w/interno/10_miembros.parquet').to_pylist() for e, cpv2, a0, a1 in redes: red = f"{e}|{cpv2}|{a0}-{a1}" for var in ('A', 'B'): G = edges(cpv2, a0, a1, var); rng = random.Random(20261022) pres = [n for n in sanc[e] if n in G] cc = comps(G); giant = max(cc, key=len); cid = {n: i for i, c in enumerate(cc) for n in c} d = dict(nodos=len(G), componentes=len(cc), gigante=len(giant), sanc_presentes=len(pres), sanc_en_gigante=sum(1 for n in pres if n in giant)) if len(pres) >= 2: s0 = score(G, set(pres)); st = {n: sum(G[n].values()) for n in G} orden = sorted(G, key=lambda n: (st[n], str(n))); N = len(orden); dec = {n: min(9, i * 10 // N) for i, n in enumerate(orden)} top = max(pres, key=lambda n: st[n]); pool = [n for n in G if dec[n] == dec[top] and n not in todas and len(G[n]) > 0] low = tot = 0 for _ in range(1000): sd = rng.choice(pool); s = {sd}; front = set(G[sd]) - todas while len(s) < len(pres) and front: q = rng.choice(sorted(front, key=str)); s.add(q); front |= set(G[q]); front -= s; front -= todas if len(s) < len(pres): continue r = score(G, s); tot += 1; low += 1 if r < s0 else (0.5 if r == s0 else 0) d.update(S_fallo=s0, percentil_conexo=low / tot if tot else None, n_null=tot) # (b) controles: componentes enteras y AUC dentro de la gigante g = [r for r in grp if r['red'] == red and r['var'] == var and r['metodo'] == 'louvain' and r['semilla'] == 20261022] gm = {} for m in mem: if m['red'] == red and m['var'] == var: gm.setdefault(m['grupo'], []).append(m['emp']) ctrl = [r for r in g if r['clase'] == 'ctrl']; pos = [r for r in g if r['clase'] == 'pos'] d['ctrl'] = len(ctrl); d['ctrl_componente_entera'] = sum(1 for r in ctrl if r['w_out'] == 0) cg = [r['S'] for r in ctrl if all(n in giant for n in gm[r['grupo']])] d['ctrl_en_gigante'] = len(cg) d['pos_f_gigante'] = [sum(1 if c < p['S'] else 0.5 if c == p['S'] else 0 for c in cg) / len(cg) for p in pos if cg and all(n in giant for n in gm[p['grupo']])] R[f"{red}|{var}"] = d print(red, var, {k: v for k, v in d.items()}, flush=True) for var in ('A', 'B'): ps = [v['percentil_conexo'] for k, v in R.items() if k.endswith('|' + var) and v.get('percentil_conexo') is not None] fs = [f for k, v in R.items() if k.endswith('|' + var) for f in v['pos_f_gigante']] R[f'resumen_{var}'] = dict(percentil_conexo_medio=sum(ps) / len(ps), redes=len(ps), auc_gigante=sum(fs) / len(fs) if fs else None, pos_gigante=len(fs), ctrl=sum(v['ctrl'] for k, v in R.items() if k.endswith('|' + var)), ctrl_componente_entera=sum(v['ctrl_componente_entera'] for k, v in R.items() if k.endswith('|' + var))) print(var, R[f'resumen_{var}']) json.dump(R, open('/w/interno/25_posterior.json', 'w'), indent=1)