#!/usr/bin/env python3 """Independent kill-graph component censuses (no streaming machine). uf_runs(g, p) - explicit union-find over edge endpoints (small words) scipy_runs(g, p) - vectorised edge list + scipy connected_components Both return (runs, edges) with runs = {component size: count}, including the isolated nodes (2D - #endpoint nodes) as size 1. """ import numpy as np def edge_arrays(g, p): """u,v arrays of every kill-graph edge (g is uint16 array, cyclic word).""" D = g.size m = g.astype(np.int64) % p iz = np.nonzero(m == 0)[0] ip = np.nonzero(m == 2)[0] im = np.nonzero(m == p - 2)[0] nz, npz, nm = iz.size, ip.size, im.size u = np.empty(2 * nz + npz + nm, dtype=np.int64) v = np.empty_like(u) o = 0 nxt = lambda a: (a + 1) % D u[o:o + nz] = 2 * iz; v[o:o + nz] = 2 * nxt(iz); o += nz u[o:o + nz] = 2 * iz + 1; v[o:o + nz] = 2 * nxt(iz) + 1; o += nz u[o:o + npz] = 2 * ip + 1; v[o:o + npz] = 2 * nxt(ip); o += npz u[o:o + nm] = 2 * im; v[o:o + nm] = 2 * nxt(im) + 1; o += nm assert o == u.size return u, v def scipy_runs(g, p): from scipy.sparse import coo_matrix from scipy.sparse.csgraph import connected_components D = g.size u, v = edge_arrays(g, p) if u.size == 0: return {1: 2 * D}, 0 alln = np.concatenate([u, v]) uniq, inv = np.unique(alln, return_inverse=True) nu = int(uniq.size) rows = inv[:u.size] cols = inv[u.size:] A = coo_matrix((np.ones(rows.size, dtype=np.int8), (rows, cols)), shape=(nu, nu)) ncomp, labels = connected_components(A, directed=False) sizes = np.bincount(labels) runs = {} for s in sizes.tolist(): runs[s] = runs.get(s, 0) + 1 runs[1] = runs.get(1, 0) + (2 * D - nu) return runs, int(u.size) def uf_runs(g, p): """Plain union-find over edge endpoints; memory Ok while edges is small.""" D = g.size parent = {} size = {} def find(a): root = a while parent[root] != root: root = parent[root] while parent[a] != root: parent[a], a = root, parent[a] return root def union(a, b): ra, rb = find(a), find(b) if ra == rb: return if size[ra] < size[rb]: ra, rb = rb, ra parent[rb] = ra size[ra] += size[rb] def touch(a): if a not in parent: parent[a] = a size[a] = 1 edges = 0 m = g.astype(np.int64) % p idx = np.nonzero((m == 0) | (m == 2) | (m == p - 2))[0] for i in idx.tolist(): mi = int(g[i]) % p j = (i + 1) % D n0, n1 = 2 * i, 2 * i + 1 m0, m1 = 2 * j, 2 * j + 1 if mi == 0: touch(n0); touch(m0); union(n0, m0) touch(n1); touch(m1); union(n1, m1) edges += 2 elif mi == 2: touch(n1); touch(m0); union(n1, m0) edges += 1 elif mi == p - 2: touch(n0); touch(m1); union(n0, m1) edges += 1 roots = {} for a in parent: r = find(a) roots[r] = roots.get(r, 0) + 1 runs = {} for s in roots.values(): runs[s] = runs.get(s, 0) + 1 runs[1] = runs.get(1, 0) + (2 * D - len(parent)) return runs, edges def runs_to_list(runs): return {int(k): int(v) for k, v in runs.items() if v}