# Section 9: circulant sign matrices, as spin chains on a ring. For a sequence s of N signs, the energy Tr|S| of the circulant # matrix S is the sum of the absolute values of the discrete Fourier transform of s. The program checks this, computes the # explicit families (one flipped spin, the alternating chain, the Legendre sequences), goes through all the 2^N sequences # for N <= 30, with the density of states at N = 13, 19, 23, and through all the matrices made of 2 circulant blocks, for # N <= 26 with N = 2 modulo 4, with the equality case of the upper bound up to N = 50, and with the chains of planar # rotators from Section 10. Output in chains.json. Usage: python3 chains.py [names of the functions to be run] import numpy as np, itertools, math, sys, json from scipy.linalg import polar, circulant from designs import SETS, incidence def tracenorm(S): return np.linalg.svd(S, compute_uv=False).sum() def circ(s): return np.array([[s[(j - i) % len(s)] for j in range(len(s))] for i in range(len(s))]) def energy(s): return np.abs(np.fft.fft(s)).sum() def fixed(S): return bool(np.array_equal(np.sign(polar(S)[0]), S)) def legendre(p): return np.array([1] + [1 if pow(k, (p - 1) // 2, p) == 1 else -1 for k in range(1, p)]) def text(s): return "".join("+" if x > 0 else "-" for x in s) def basics(): rng = np.random.default_rng(3); worst = 0; pol = True for N in range(3, 16): for _ in range(20): s = rng.choice([-1, 1], N); S = circ(s); worst = max(worst, abs(tracenorm(S) - energy(s))) if abs(np.linalg.det(S)) > 0.5: U = polar(S)[0]; pol = pol and np.allclose(U, circ(U[0])) print("random circulant sign matrices: Tr|S| equals the sum of the |DFT|, largest error %.1e; the polar part is circulant: %s" % (worst, pol)) for name, (v, D) in SETS.items(): M = incidence(v, D); print("%s: the incidence matrix is circulant: %s" % (name, np.array_equal(M, circ(M[0])))) def families(): for N in (5, 7, 9, 11, 13, 101): s = np.ones(N, dtype=int); s[0] = -1; a = np.array([(-1) ** min(j, N - j) for j in range(N)]) U = polar(circ(a))[0]; g = np.array([(-1) ** j / (N * math.cos(math.pi * j / N)) for j in range(N)]) print("N = %d: one flipped spin: energy %.6f = 3N - 4: %s, fixed point: %s; alternating chain: energy %.6f = sum of 1/|cos(k pi/N)|: %s, fixed point: %s, polar part with entries (-1)^j/(N cos(j pi/N)): %s; energy divided by N log N: %.4f" % (N, energy(s), abs(energy(s) - 3 * N + 4) < 1e-9, fixed(circ(s)), energy(a), abs(energy(a) - sum(1 / abs(math.cos(math.pi * k / N)) for k in range(N))) < 1e-9, fixed(circ(a)), np.allclose(np.abs(U[0]), np.abs(g)) and np.allclose(np.sign(U[0]), a), energy(a) / (N * math.log(N)))) for p in (5, 7, 11, 13, 17, 19, 23, 29, 37, 41): s = legendre(p); S = circ(s); e = energy(s); Q = circ(np.concatenate([[0], s[1:]])) if p % 4 == 3: print("p = %d = 3 (4): Legendre sequence, energy %.6f = 1 + (p-1) sqrt(p+1): %s, fixed point: %s" % (p, e, abs(e - 1 - (p - 1) * math.sqrt(p + 1)) < 1e-9, fixed(S))) else: print("p = %d = 1 (4): Legendre sequence, energy %.6f = 1 + (p-1) sqrt(p): %s, fixed point: %s, polar part (all-one + sqrt(p) Q)/p: %s" % (p, e, abs(e - 1 - (p - 1) * math.sqrt(p)) < 1e-9, fixed(S), np.allclose(polar(S)[0], (1 + math.sqrt(p) * Q) / p))) from portraits import paleygraph A = paleygraph(9); Q = 2 * A - 1 + np.eye(9, dtype=int); S = Q + np.eye(9, dtype=int) print("q = 9: Paley graph, S = 1 + Q: energy %.6f = 1 + 8 sqrt(9), fixed point: %s, polar part (all-one + 3Q)/9: %s" % (tracenorm(S), fixed(S), np.allclose(polar(S)[0], (1 + 3 * Q) / 9))) def exhaustive(top=30, dos=(13, 19, 23)): out = {} for N in range(3, top + 1): best = -1; count = 0; arg = None; width = 0.02; nb = int(math.ceil((N ** 1.5 - N) / width)) + 1; hist = np.zeros(nb, dtype=np.int64) total = 2 ** (N - 1); step = 2 ** 18; sh = np.arange(N - 1) for start in range(0, total, step): idx = np.arange(start, min(start + step, total), dtype=np.int64) s = np.empty((len(idx), N), dtype=np.float32); s[:, 0] = 1; s[:, 1:] = 1 - 2 * ((idx[:, None] >> sh) & 1) f = np.abs(np.fft.rfft(s.astype(np.float64), axis=1)) e = f[:, 0] + 2 * f[:, 1:(N + 1) // 2].sum(1) + (f[:, N // 2] if N % 2 == 0 else 0) m = e.max() if m > best + 1e-7: best = m; count = 0; arg = s[int(e.argmax())].astype(int) count += int((e > best - 1e-7).sum()) if N in dos: hist += np.bincount(((e - N) / width).astype(int).clip(0, nb - 1), minlength=nb) out[N] = {"best": float(best), "ratio": float(best / N ** 1.5), "states": 2 * count, "sequence": text(arg), "fixed": fixed(circ(arg))} if N in dos: out[N]["hist"] = [int(x) for x in hist] print("N = %d: largest energy %.6f, divided by N^1.5: %.4f, attained by %d sequences, such as %s; sign matrix of its polar part: %s" % (N, best, best / N ** 1.5, 2 * count, text(arg), out[N]["fixed"]), flush=True) return out def heat(out, dos=(13, 19, 23)): T = [0.02 * k for k in range(2, 151)] for N in dos: h = np.array(out[N]["hist"], dtype=float); E = N + 0.02 * (np.arange(len(h)) + 0.5); C = [] for t in T: w = h * np.exp((E - E.max()) / t); z = w.sum(); m = (w * E).sum() / z; C.append(float(((w * E * E).sum() / z - m * m) / (t * t * N))) out[N]["heat"] = C; k = int(np.argmax(C)); print("N = %d: specific heat per spin, maximum %.4f at T = %.2f" % (N, C[k], T[k])) out["temperatures"] = T def twocirculant(): out = {} for N in range(6, 27, 4): n = N // 2; seqs = np.array(list(itertools.product([1, -1], repeat=n)), dtype=float); P = np.abs(np.fft.rfft(seqs, axis=1)) ** 2 w = np.array([1] + [2] * (n // 2)); best = -1; arg = None for i in range(len(seqs)): e = 2 * (np.sqrt(P[i][None, :] + P[i:]) * w).sum(1); j = int(e.argmax()) if e[j] > best + 1e-9: best = e[j]; arg = (i, i + j) a, b = seqs[arg[0]].astype(int), seqs[arg[1]].astype(int); A, B = circ(a), circ(b); M = np.block([[A, B], [-B.T, A.T]]) bound = (N - 2) * math.sqrt(N - 2) + 2 * math.sqrt(2 * N - 2) out[N] = {"best": float(best), "a": text(a), "b": text(b), "bound": bound, "attained": bool(abs(best - bound) < 1e-7)} print("N = %d: 2 circulant blocks, largest energy %.6f (Tr|M| = %.6f), upper bound %.6f, attained: %s, by a = %s, b = %s; sign matrix of its polar part: %s" % (N, best, tracenorm(M), bound, out[N]["attained"], text(a), text(b), fixed(M)), flush=True) return out def rotators(runs=400, steps=20000): # chains of planar rotators: the alternating maximization s -> phases of the inverse transform of the phases of the transform rng = np.random.default_rng(5); out = {} for N in range(3, 31): j = np.arange(N); s = np.exp(2j * math.pi * j * j / N) if N % 2 else np.exp(1j * math.pi * j * j / N) assert abs(np.abs(np.fft.fft(s)).sum() - N ** 1.5) < 1e-8 print("quadratic chains: energy N sqrt(N) at any N <= 30") for N in range(3, 17): s = np.exp(2j * math.pi * rng.random((runs, N))) for it in range(steps): f = np.fft.fft(s, axis=1); u = np.fft.ifft(f / np.abs(f), axis=1); s = u / np.abs(u) r = np.abs(np.fft.fft(s, axis=1)).sum(1) / N ** 1.5; good = r > 1 - 1e-9 z = s[good] / s[good][:, :1]; z = z * np.exp(-1j * np.outer(np.angle(z[:, 1]), np.arange(N))) # s_0 = s_1 = 1, by a phase and a modulation keys = {tuple(np.round(np.concatenate([x.real, x.imag]), 4) + 0.0) for x in z} out[N] = {"perfect": int(good.sum()), "runs": runs, "worst": float(r.min()), "limits": len(keys)} print("N = %d: %d runs out of %d end at energy N sqrt(N), smallest final ratio %.9f, number of distinct limits with s_0 = s_1 = 1: %d" % (N, good.sum(), runs, r.min(), len(keys)), flush=True) return out def pairs(): # 2 sequences of odd length n whose periodic autocorrelations sum up to 2: the equality case at N = 2n out = {} for n in (3, 5, 7, 9, 13, 15, 19, 21, 23, 25): sums = {x for x in range(1, 2 * n, 2) for y in range(1, 2 * n, 2) if x * x + y * y == 4 * n - 2}; h = (n - 1) // 2; table = {} total = 2 ** (n - 1); step = 2 ** 17; sh = np.arange(n - 1); found = None; count = 0 for start in range(0, total, step): idx = np.arange(start, min(start + step, total), dtype=np.int64); s = np.ones((len(idx), n)); s[:, 1:] = 1 - 2 * ((idx[:, None] >> sh) & 1) keep = np.isin(np.abs(s.sum(1)).astype(int), list(sums)); s = s[keep] if len(s) == 0: continue paf = np.rint(np.fft.irfft(np.abs(np.fft.rfft(s, axis=1)) ** 2, n=n, axis=1)[:, 1:h + 1]).astype(np.int8) for row, key in zip(s, paf): table.setdefault(key.tobytes(), row.astype(np.int8)) for key, a in table.items(): other = (2 - np.frombuffer(key, dtype=np.int8)).astype(np.int8).tobytes() if other in table: count += 1 if found is None: found = (a, table[other]) a, b = found; A, B = circ(a.astype(int)), circ(b.astype(int)); M = np.block([[A, B], [-B.T, A.T]]); N = 2 * n ok = np.array_equal(M @ M.T, np.kron(np.eye(2, dtype=int), (N - 2) * np.eye(n, dtype=int) + 2)) out[N] = {"a": text(a), "b": text(b), "bound": (N - 2) * math.sqrt(N - 2) + 2 * math.sqrt(2 * N - 2)} print("N = %d: %d autocorrelation vectors having a complement; a = %s, b = %s; S S^t has diagonal blocks N - 2 + 2 (all-one), and vanishes elsewhere: %s; Tr|S| = %.6f" % (N, count, text(a), text(b), ok, tracenorm(M)), flush=True) return out def saddles(runs=1500, steps=20000, polish=200000): # the chains of rotators which are local maximizers of the energy, without being perfect, and the inertia of the Hessian # of the 1-norm on the unitary group U_N at the corresponding matrices Pol(S), computed as in inertia.py. The chains are # iterated until the gradient of the energy is below 1e-9, the Hessians being meaningless otherwise. The chains found are # grouped into spectral classes, 2 chains being in the same class when they have the same numbers |hat s_k|, up to their # order, a multiset which is invariant under the symmetries of the energy: global phases, shifts, multiplications by # characters, conjugation, and the maps j -> aj with a invertible modulo N. Thus chains in different classes are not # equivalent, while chains in the same class might not be equivalent either. Several classes can have the same energy. from inertia import hessL rng = np.random.default_rng(7); out = {} def move(s): f = np.fft.fft(s, axis=-1); u = np.fft.ifft(f / np.abs(f), axis=-1); return u / np.abs(u) def gradient(x): f = np.fft.fft(x); return np.abs((np.conj(x) * np.fft.ifft(f / np.abs(f)) * len(x)).imag).max() def E(th): return np.abs(np.fft.fft(np.exp(1j * th))).sum() def hess(th, h=1e-4): n = len(th); H = np.zeros((n, n)); I = np.eye(n) * h for i in range(n): for j in range(i, n): H[i, j] = H[j, i] = (E(th + I[i] + I[j]) - E(th + I[i] - I[j]) - E(th - I[i] + I[j]) + E(th - I[i] - I[j])) / (4 * h * h) return H for N in range(11, 19): s = np.exp(2j * math.pi * rng.random((runs, N))) for it in range(steps): s = move(s) r = np.abs(np.fft.fft(s, axis=1)).sum(1) / N ** 1.5; s = s[r < 1 - 1e-7] for it in range(polish): s = move(s) found = [] # (ratio, sorted spectrum, chain, number of runs) for x in s: f = np.abs(np.fft.fft(x)); y = f.sum() / N ** 1.5 if y > 1 - 1e-7 or gradient(x) > 1e-9: continue for c in found: if abs(c[0] - y) < 1e-8 and np.abs(c[1] - np.sort(f)).max() < 1e-6: c[3] += 1; break else: found.append([y, np.sort(f), x, 1]) rows = [] for y, spec, x, count in sorted(found, key=lambda c: (round(c[0], 8), tuple(np.round(c[1], 5)))): top = np.linalg.eigvalsh(hess(np.angle(x)))[-2:] if top[0] > -1e-4 or abs(top[1]) > 1e-4: continue # one zero eigenvalue, coming from the global phase S = circ(x); U = polar(S)[0] if not np.allclose(U / np.abs(U), S, atol=1e-7): continue ev = np.linalg.eigvalsh(hessL(U)); pos = ev[ev > 1e-8] rows.append({"ratio": float(y), "runs": count, "negative": int((ev < -1e-8).sum()), "zero": int((np.abs(ev) <= 1e-8).sum()), "positive": len(pos), "smallest positive": float(pos.min()) if len(pos) else 0.0, "largest negative": float(ev[ev < -1e-8].max()), "spectrum": [float(spec.min()), float(spec.max())], "angles": [float(a) for a in np.mod(np.angle(x / x[0]), 2 * math.pi)]}) out[N] = rows levels = len(set(round(row["ratio"], 7) for row in rows)) print("N = %d: %d runs, %d classes of local maximizers of the chain energy which are not perfect, on %d energy levels, %d of them with no escape direction" % (N, runs, len(rows), levels, sum(row["positive"] == 0 for row in rows)), flush=True) for row in rows: print(" ratio %.7f, %4d runs, |transform| between %.4f and %.4f: inertia (negative, zero, positive) = (%d, %d, %d), smallest positive eigenvalue %.6f" % (row["ratio"], row["runs"], row["spectrum"][0], row["spectrum"][1], row["negative"], row["zero"], row["positive"], row["smallest positive"]), flush=True) return out SIXTEEN = [0.000000000000000, 6.240306560271331, 2.868822117139449, 2.389181994234404, 0.732512772864909, 4.623096445794694, 4.554149641545951, 5.351695847842301, 5.389932745529107, 3.194231298411252, 4.386957422709028, 5.151415954209852, 2.131057143607693, 5.024113455285562, 1.946536126846845, 5.434630538974839] def witness(theta, trials=6): # a chain of rotators, given by its angles, whose matrix U = Pol(S) is, numerically, a local maximizer of the 1-norm on the # unitary group U_N, without being a rescaled complex Hadamard matrix. We polish the chain, and we compute the inertia of # the Hessian in 3 ways: with hessL and hessM from inertia.py, and by finite differences, over an orthonormal basis of the # Lie algebra. Then we cool on the full unitary group, from perturbed points, and we come back to the same value of the 1-norm. from inertia import hessL, hessM from scipy.linalg import expm N = len(theta); x = np.exp(1j * np.array(theta)); L = lambda U: np.abs(U).sum(); r = 1 / math.sqrt(2) f = np.fft.fft(x); print("chain of %d rotators, as given: Tr|S| = %.12f, largest derivative of the energy %.1e" % (N, np.abs(f).sum(), np.abs((np.conj(x) * np.fft.ifft(f / np.abs(f)) * N).imag).max())) for it in range(200000): f = np.fft.fft(x); u = np.fft.ifft(f / np.abs(f)); x = u / np.abs(u) f = np.fft.fft(x); g = np.abs((np.conj(x) * np.fft.ifft(f / np.abs(f)) * N).imag).max(); S = circ(x); U = polar(S)[0] print(" polished: Tr|S| = %.12f, ratio %.12f, deficit %.12f, largest derivative of the energy %.1e, |transform| between %.6f and %.6f" % (np.abs(f).sum(), np.abs(f).sum() / N ** 1.5, N ** 1.5 - np.abs(f).sum(), g, np.abs(f).min(), np.abs(f).max())) print(" largest change of an angle under the polishing: %.1e" % np.abs(np.angle(x / x[0] * np.exp(-1j * (np.array(theta) - theta[0])))).max()) print(" U = Pol(S): 1-norm %.12f, S is the phase matrix of U: %s, entries of |U| between %.6f and %.6f" % (L(U), np.allclose(U / np.abs(U), S, atol=1e-9), np.abs(U).min(), np.abs(U).max())) basis = [] for i in range(N): D = np.zeros((N, N), dtype=complex); D[i, i] = 1j; basis.append(D) for j in range(i + 1, N): A = np.zeros((N, N), dtype=complex); A[i, j] = r; A[j, i] = -r; basis.append(A) B = np.zeros((N, N), dtype=complex); B[i, j] = 1j * r; B[j, i] = 1j * r; basis.append(B) h = 2e-3; n = len(basis); H = np.zeros((n, n)); d = [0.5 * (L(U @ expm(h * A)) + L(U @ expm(-h * A))) - L(U) for A in basis] for a in range(n): H[a, a] = 2 * d[a] / h ** 2 for b in range(a + 1, n): P = basis[a] + basis[b]; H[a, b] = H[b, a] = (0.5 * (L(U @ expm(h * P)) + L(U @ expm(-h * P))) - L(U) - d[a] - d[b]) / h ** 2 for name, M, eps in (("hessL", hessL(U), 1e-6), ("hessM", hessM(U), 1e-6), ("finite differences", H, 1e-4)): e = np.linalg.eigvalsh(M); print(" Hessian, %s: %d positive eigenvalues, %d zero ones, %d negative ones, the largest negative one being %.6f" % (name, (e > eps).sum(), (np.abs(e) <= eps).sum(), (e < -eps).sum(), e[e < -eps].max()), flush=True) rng = np.random.default_rng(3); gains = [] for trial in range(trials): A = sum(c * B for c, B in zip(rng.standard_normal(n), basis)); V = U @ expm(0.02 * A / np.linalg.norm(A)) for it in range(60000): V = polar(V / np.abs(V))[0] gains.append(L(V) - L(U)) print(" cooling on U_%d from %d perturbed points, at distance 0.02: final 1-norm minus the initial one: %s" % (N, trials, " ".join("%.1e" % v for v in gains)), flush=True) def witnesses(): # the above checks for the chain of order 16 printed in the paper, then for all the classes with no escape direction found by saddles() witness(SIXTEEN) try: data = json.load(open("chains.json"))["saddles"] except Exception: return for N in sorted(data, key=int): for row in data[N]: if row["positive"] == 0: witness(row["angles"]) if __name__ == "__main__": run = sys.argv[1:] or ["basics", "families", "exhaustive", "twocirculant", "pairs", "rotators", "saddles", "witnesses"] data = {} if "basics" in run: basics() if "families" in run: families() if "exhaustive" in run: data["chains"] = exhaustive(); heat(data["chains"]) if "twocirculant" in run: data["blocks"] = twocirculant() if "pairs" in run: data["pairs"] = pairs() if "rotators" in run: data["rotators"] = rotators() if "saddles" in run: data["saddles"] = saddles() if data: try: old = json.load(open("chains.json")) except Exception: old = {} old.update(data); json.dump(old, open("chains.json", "w")) if "witnesses" in run: witnesses()