"""CO1b · 10 · impl1 (Python puro): reconstruye las aristas de CO1, comprueba la reutilización, componente gigante, medidas de Wachs & Kertész (Jaccard, coherencia geom/arit, exclusividad) y las de CO1. Escribe interno/10_grupos_b.parquet.""" import time, json, math, itertools import duckdb, pyarrow as pa, pyarrow.parquet as pq T0 = time.time() def log(*a): print(f"[{time.time()-T0:7.1f} s]", *a, flush=True) con = duckdb.connect('/w/tmp/co1.duckdb', read_only=True); x = con.execute x("SET threads=4; SET memory_limit='4GB'") M = pq.read_table('/co1/interno/10_miembros.parquet').to_pylist() G1 = [r for r in pq.read_table('/co1/interno/10_grupos.parquet').to_pylist() if r['metodo'] == 'louvain' and r['semilla'] == 20261022] g1 = {(r['red'], r['var'], r['grupo']): r for r in G1} mem = {} for r in M: mem.setdefault((r['red'], r['var']), {})[r['emp']] = r['grupo'] def edges(cpv2, a0, a1, var): if var == 'A': q = f"""WITH t AS (SELECT DISTINCT lic g, emp FROM u WHERE cpv2 = ? AND anio BETWEEN ? AND ?), n AS (SELECT g FROM t GROUP BY g HAVING count(*) BETWEEN 2 AND 30) SELECT g, list(emp ORDER BY emp) FROM t JOIN n USING (g) GROUP BY g""" else: q = f"""WITH t AS (SELECT DISTINCT organo_clave || '|' || anio g, emp FROM u WHERE cpv2 = ? AND anio BETWEEN ? AND ? AND organo_clave IS NOT NULL), n AS (SELECT g FROM t GROUP BY g HAVING count(*) BETWEEN 2 AND 50) SELECT g, list(emp ORDER BY emp) FROM t JOIN n USING (g) GROUP BY g""" rows = x(q, [cpv2, a0, a1]).fetchall() W, nc = {}, {} for _, es in rows: for e in es: nc[e] = nc.get(e, 0) + 1 for a, b in itertools.combinations(es, 2): da = W.setdefault(a, {}); da[b] = da.get(b, 0) + 1 db = W.setdefault(b, {}); db[a] = db.get(a, 0) + 1 return W, nc def componentes(W): comp, cid = {}, 0 for s in W: if s in comp: continue st = [s]; comp[s] = cid while st: n = st.pop() for v in W[n]: if v not in comp: comp[v] = cid; st.append(v) cid += 1 return comp OUT, CHK = [], dict(grupos=0, dif_k=0, dif_w=0, nodos_distintos=0, grupos_partidos_entre_componentes=0) redes = sorted(mem) for red, var in redes: if red.startswith('SAMUR/01/24'): continue e, cpv2, ven = red.split('|'); a0, a1 = map(int, ven.split('-')) W, nc = edges(cpv2, a0, a1, var) part = mem[(red, var)] if set(W) != set(part): CHK['nodos_distintos'] += 1 comp = componentes(W) tam = {} for n, c in comp.items(): tam[c] = tam.get(c, 0) + 1 cg = max(tam, key=lambda c: (tam[c], -c)); ncg = tam[cg] grp = {} for n, g in part.items(): grp.setdefault(g, []).append(n) for g, ms in grp.items(): s = set(ms); k = len(ms) if k < 2: continue win = wout = 0; jin = jout = 0.0; jl = []; wl = [] for n in ms: for v, w in W[n].items(): j = w / (nc[n] + nc[v] - w) if v in s: win += w; jin += j if n < v: jl.append(j); wl.append(w) else: wout += w; jout += j win //= 2; jin /= 2 r1 = g1[(red, var, g)]; CHK['grupos'] += 1 CHK['dif_k'] += r1['k'] != k; CHK['dif_w'] += (r1['w_in'] != win or r1['w_out'] != wout) cs = {comp[n] for n in ms} if len(cs) > 1: CHK['grupos_partidos_entre_componentes'] += 1 en_cg = cs == {cg} C1 = win / (k * (k - 1) / 2); E1 = win / (win + wout) if win + wout else 0.0 if jl: CG = math.exp(sum(math.log(j) for j in jl) / len(jl)) / (sum(jl) / len(jl)) CGw = math.exp(sum(math.log(w) for w in wl) / len(wl)) / (sum(wl) / len(wl)) else: CG = CGw = 0.0 EG = jin / (jin + jout) if jin + jout > 0 else 0.0 OUT.append(dict(red=red, exp=e, cpv2=cpv2, var=var, grupo=g, k=k, en_cg=en_cg, n_cg=ncg, nodos=len(W), n_comp=len(tam), aristas_int=len(jl), w_in=win, w_out=wout, j_in=jin, j_out=jout, C1=C1, E1=E1, S1=C1 * E1, CG=CG, EG=EG, SWK=CG * EG, CG_enteros=CGw, clase=r1['clase'], n_sanc_exp=r1['n_sanc_exp'], n_sanc_otro=r1['n_sanc_otro'])) log(red, var, f"nodos={len(W)} componentes={len(tam)} CG={ncg} grupos={len(grp)} en_CG_k>=3={sum(1 for o in OUT if o['red']==red and o['var']==var and o['en_cg'] and o['k']>=3)}") del W pq.write_table(pa.Table.from_pylist(OUT), '/w/interno/10_grupos_b.parquet') json.dump(CHK, open('/w/interno/10_reutilizacion.json', 'w'), indent=1) log('comprobación de reutilización', CHK)