"""The mala knot in 12 dimensions.

A torus knot is a curve on a product of circles. In 3D the (4, 27) knot uses two circles (ring and
tube) and has to bend one around the other, which makes the geometry non-uniform (inner and outer
beads differ) and crowds the 27 stations onto one ring. In 12 dimensions there is room for SIX
independent circles (6 x 2 = 12 coordinates), so bead k can sit at

    x_k = ( rho_1 cos(2 pi f_1 k/108), rho_1 sin(...), ..., rho_6 cos(2 pi f_6 k/108), rho_6 sin(...) )

a "torus knot on the 6-torus". Such an embedding is FLAT: the distance between beads k and k+s depends
on s only, so every bead is equivalent (couplings are exactly circulant).

The mala structure is kept by construction:
  * the tube circle has frequency 27, so the four beads of a station sit a quarter turn apart
    (27 * 27 = 729 = 6*108 + 81), and bead k, k+27, k+54, k+81 form a planar square;
  * every ring circle has frequency 4m, so it sees only the station (k mod 27): angle 2 pi m k / 27.
    Squares collapse to a point on every ring circle, exactly as on the 3D ring.

Embeddings compared (ring scale fixed by RMS: sum of ring radii^2 = 1; tube radius r):
  3D      the lab's torus, ring radius 1, tube r                         (reference)
  4D      flat Clifford torus: one ring circle (m = 1) and the tube      (the 3D knot, flattened)
  12D-u   five ring circles m in {1, 5, 7, 11, 13} (units mod 27) + tube (6 circles, 12 coordinates)
  12D-n   five ring circles m in {1, 2, 3, 4, 5} + tube                 (naive choice, shares factors)
  12D-*   the best five multipliers from 1..13 by exhaustive search      (max of min station spacing)
  12D-rnd 108 points placed at random in 12D at the same overall scale   (geometry without arithmetic)

Tests (all-pairs couplings J = (d_sq / d)^alpha normalised to the square edge; alpha = 6 and 3):
  T1  nearest structure: fraction of beads whose nearest neighbour is a square partner, vs r; the
      threshold r* where the square stops being nearest.
  T2  one-corner transfer: best P(bead 55) from bead 1 over 0 <= t <= 40, vs r.
  T3  square-qubit leakage: start (|1> + |55>)/sqrt2, min probability left in its own square, t <= 40.
  T4  the diagonal cap: for four points with equal edges in ANY dimension, Euler's quadrilateral
      theorem gives d02^2 + d13^2 <= 4 e^2, so equal diagonals are at most sqrt2 * edge, the planar
      square. Verified by random sampling in R^12, and the first-pass flip mapped over equal-edge
      quadrilaterals (rhombus angle, skew fold) under 1/d^6.

Predictions, written before running:
  P1  The flat 4D embedding reproduces the 3D threshold (about 0.14) but is exactly uniform: every bead
      has the same nearest-neighbour status.
  P2  The 12D-u embedding raises the threshold several-fold (r* > 0.5): 27 stations spread over five
      circles in ten dimensions are far from each other, and the flip survives at tube sizes that kill
      it in 3D.
  P3  12D-n does worse than 12D-u: multipliers sharing a factor with 27 put stations on top of each
      other on some circles. The arithmetic of the frequencies matters, not the count of dimensions.
  P4  No embedding in any dimension beats the 0.962 first-pass cap for an equal-edge, equal-diagonal
      square; only unequal shapes can.
  P5  Random placement in 12D has no squares at all (fraction nearest = about 3/107), and no transfer.

Usage: python3 knot12d.py   (NumPy, Matplotlib; about a minute)
"""
import itertools, json, math, time
from pathlib import Path
import numpy as np

HERE = Path(__file__).resolve().parent
N = 108
PREDICTIONS = {
    "P1": "Flat 4D reproduces the 3D threshold (~0.14) exactly and uniformly.",
    "P2": "12D with ring multipliers {1,5,7,11,13} raises the threshold several-fold (r* > 0.5); the flip survives at tube sizes that kill it in 3D.",
    "P3": "12D with multipliers {1,2,3,4,5} does worse than {1,5,7,11,13}: frequency arithmetic matters, not dimension count.",
    "P4": "No embedding in any dimension beats the 0.962 first-pass cap for an equal-edge, equal-diagonal square.",
    "P5": "Random placement in 12D has no squares (nearest fraction ~3/107) and no transfer.",
}
R_GRID = [0.02, 0.05, 0.08, 0.10, 0.12, 0.14, 0.16, 0.20, 0.30, 0.40, 0.50, 0.70, 1.00, 1.50]


# ----------------------------------------------------------------------------- embeddings
def torus3d(r):
    k = np.arange(N); t = 2 * np.pi * k / N; u, v = 4 * t, 27 * t
    return np.stack([(1 + r * np.cos(v)) * np.cos(u), (1 + r * np.cos(v)) * np.sin(u), r * np.sin(v)], -1)


def flat(ms, r):
    """Ring circles with multipliers ms (frequency 4m), equal radii with RMS 1, plus the tube circle."""
    k = np.arange(N); cols = []
    rho = 1 / math.sqrt(len(ms))
    for m in ms:
        a = 2 * np.pi * 4 * m * k / N
        cols += [rho * np.cos(a), rho * np.sin(a)]
    a = 2 * np.pi * 27 * k / N
    cols += [r * np.cos(a), r * np.sin(a)]
    X = np.stack(cols, -1)
    if X.shape[1] < 12:
        X = np.concatenate([X, np.zeros((N, 12 - X.shape[1]))], 1)
    return X


def station_min_gap(ms):
    """Min over station steps s = 1..26 of the squared ring distance (RMS radius 1)."""
    s = np.arange(1, 27)
    d2 = sum(2 * (1 / len(ms)) * (1 - np.cos(2 * np.pi * m * s / 27)) for m in ms)
    return float(d2.min())


def random12(r, seed=0):
    """Random 108 points in R^12 with the same RMS radius as the flat embedding (sqrt(1 + r^2))."""
    rng = np.random.default_rng(seed)
    X = rng.normal(size=(N, 12)); X /= np.linalg.norm(X, axis=1, keepdims=True)
    return X * math.sqrt(1 + r * r)


# ----------------------------------------------------------------------------- tests
def dist(X):
    return np.linalg.norm(X[:, None] - X[None], axis=-1)


def nearest_fraction(D):
    D = D + np.eye(N) * 1e9
    nn = np.argmin(D, axis=1)
    return float(np.mean([((nn[k] - k) % N) in (27, 81) for k in range(N)]))


def couplings(D, alpha):
    ref = D[0, 27]
    with np.errstate(divide="ignore"):
        return np.where(np.eye(N) == 1, 0.0, (ref / np.maximum(D, 1e-12)) ** alpha)


def dynamics(J, tmax=40.0, steps=4001):
    w, V = np.linalg.eigh(-J)
    ts = np.linspace(0, tmax, steps)
    E = np.exp(-1j * np.outer(ts, w))                       # steps x N
    # one-corner transfer from bead 0 to bead 54
    c = V[0, :]
    amp = (E * c) @ V.T                                      # steps x N
    transfer = float(np.max(np.abs(amp[:, 54]) ** 2))
    first = float(np.max(np.abs(amp[ts <= 2.5, 54]) ** 2))
    # square qubit: (|0> + |54>)/sqrt2, probability left in the square {0, 27, 54, 81}
    c2 = (V[0, :] + V[54, :]) / math.sqrt(2)
    amp2 = (E * c2) @ V.T
    stay = float(np.min(np.sum(np.abs(amp2[:, [0, 27, 54, 81]]) ** 2, axis=1)))
    return transfer, first, stay


def run_embedding(name, make):
    rows = []
    for r in R_GRID:
        X = make(r); D = dist(X)
        row = {"r": r, "nearest_is_square": nearest_fraction(D),
               "edge_over_station_gap": float(D[0, 27] / np.min([D[0, s] for s in range(1, N) if s % 27])) }
        for alpha in (6, 3):
            tr, fp, st = dynamics(couplings(D, alpha))
            row[f"transfer_a{alpha}"] = tr; row[f"first_pass_a{alpha}"] = fp; row[f"square_qubit_stay_a{alpha}"] = st
        rows.append(row)
    thr = next((row["r"] for row in rows if row["nearest_is_square"] < 1.0), None)
    print(f"{name:10s} squares nearest until r = {thr}   " +
          "  ".join(f"r={row['r']:.2f}: T {row['transfer_a6']:.3f}" for row in rows if row["r"] in (0.05, 0.14, 0.3, 0.5, 1.0)))
    return {"rows": rows, "first_r_where_square_not_nearest": thr}


def t4_diagonal():
    rng = np.random.default_rng(12)
    worst = 0.0
    for _ in range(200000):
        P = rng.normal(size=(4, 12))
        e2 = sum(np.sum((P[i] - P[(i + 1) % 4]) ** 2) for i in range(4))
        d2 = np.sum((P[0] - P[2]) ** 2) + np.sum((P[1] - P[3]) ** 2)
        worst = max(worst, d2 / e2)
    # flip over equal-edge quadrilaterals: rhombus (planar, angle theta) and skew (fold angle phi)
    def flip(P, alpha=6, tmax=2.5):
        D = dist4(P); ref = D[0, 1]
        with np.errstate(divide="ignore"):
            J = np.where(np.eye(4) == 1, 0.0, (ref / np.maximum(D, 1e-12)) ** alpha)
        w, V = np.linalg.eigh(-J); c = V[0]
        ts = np.linspace(0, tmax / 1.0, 5001)
        return float(np.max(np.abs((np.exp(-1j * np.outer(ts, w)) * c) @ V[2]) ** 2))
    def dist4(P):
        return np.linalg.norm(P[:, None] - P[None], axis=-1)
    rh = []
    for th in np.linspace(60, 120, 25):
        a = math.radians(th) / 2
        P = np.array([[math.cos(a), 0, 0], [0, math.sin(a), 0], [-math.cos(a), 0, 0], [0, -math.sin(a), 0]])
        rh.append({"angle_deg": float(th), "diag02_over_edge": float(2 * math.cos(a)), "diag13_over_edge": float(2 * math.sin(a)), "flip": flip(P)})
    sk = []
    for ph in np.linspace(0, 80, 17):
        # square folded along the 0-2 diagonal: corners 1 and 3 lifted out of plane symmetrically
        f = math.radians(ph) / 2; h = 1 / math.sqrt(2)
        P = np.array([[h, 0, 0], [0, h * math.cos(f), h * math.sin(f)], [-h, 0, 0], [0, -h * math.cos(f), h * math.sin(f)]])
        D = dist4(P)
        sk.append({"fold_deg": float(ph), "diag02_over_edge": float(D[0, 2] / D[0, 1]), "diag13_over_edge": float(D[1, 3] / D[0, 1]), "flip": flip(P)})
    best_rh = max(rh, key=lambda x: x["flip"]); best_sk = max(sk, key=lambda x: x["flip"])
    print(f"T4 Euler bound: max (d02^2+d13^2)/sum(edges^2) over 200,000 random quadrilaterals in R^12 = {worst:.4f} (theorem: <= 1)")
    print(f"T4 rhombus: best flip {best_rh['flip']:.4f} at {best_rh['angle_deg']:.1f} deg (square 90 deg: {[x for x in rh if abs(x['angle_deg']-90)<1e-6][0]['flip']:.4f});  skew fold: best {best_sk['flip']:.4f} at {best_sk['fold_deg']:.0f} deg")
    return {"euler_ratio_max_sampled": worst, "rhombus": rh, "skew_fold": sk}


def plot(out):
    try:
        import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt
    except Exception as e:
        print("plot skipped:", e); return
    S, T1, T2 = "#fcfcfb", "#0b0b0b", "#52514e"
    cols = {"3D": "#52514e", "4D": "#2a78d6", "12D-u": "#1baf7a", "12D-n": "#eb6834", "12D-*": "#e87ba4", "12D-rnd": "#eda100"}
    fig, axes = plt.subplots(1, 3, figsize=(15, 4.6), facecolor=S)
    for ax in axes:
        ax.set_facecolor(S); ax.tick_params(colors=T2)
        for sp in ("top", "right"): ax.spines[sp].set_visible(False)
    E = out["embeddings"]
    for key, ax, ylab, title in (("nearest_is_square", axes[0], "fraction of beads whose nearest is a square partner", "1. Is the square the nearest structure?"),
                                 ("transfer_a6", axes[1], "best P(bead 1 → bead 55), t ≤ 40, 1/d⁶", "2. One-corner transfer")):
        for name, d in E.items():
            ax.plot([r["r"] for r in d["rows"]], [r[key] for r in d["rows"]], "o-", ms=3.5, lw=1.8, color=cols[name], label=name)
        ax.set_xscale("log"); ax.set_ylim(-0.02, 1.02); ax.set_xlabel("tube radius ÷ RMS ring radius", color=T2); ax.set_ylabel(ylab, color=T2)
        ax.set_title(title, loc="left", fontsize=10, color=T1, weight="bold")
    axes[0].legend(frameon=False, fontsize=8, labelcolor=T2)
    ax = axes[2]; T4 = out["T4"]
    ax.plot([x["diag02_over_edge"] for x in T4["rhombus"]], [x["flip"] for x in T4["rhombus"]], "o-", ms=3, color="#2a78d6", label="rhombus in a plane")
    ax.plot([x["diag02_over_edge"] for x in T4["skew_fold"]], [x["flip"] for x in T4["skew_fold"]], "s-", ms=3, color="#eb6834", label="square folded out of plane")
    ax.axhline(0.962, ls=":", color=T2, lw=1); ax.text(1.02, 0.965, "planar square 0.962", fontsize=8, color=T2)
    ax.set_xlabel("diagonal 0–2 ÷ edge (square = 1.414)", color=T2); ax.set_ylabel("first-pass flip, 1/d⁶", color=T2)
    ax.set_title("3. The diagonal cap, any dimension", loc="left", fontsize=10, color=T1, weight="bold"); ax.legend(frameon=False, fontsize=8, labelcolor=T2)
    fig.suptitle("The (4, 27) mala knot embedded in 3, 4 and 12 dimensions (six circles × 2 coordinates)", x=0.01, ha="left", fontsize=11, color=T1)
    fig.tight_layout(); fig.savefig(HERE / "knot12d.png", dpi=130, facecolor=S, bbox_inches="tight"); print("wrote knot12d.png")


if __name__ == "__main__":
    t0 = time.time()
    # exhaustive choice of five ring multipliers from 1..13 maximising the minimum station gap
    best = max(itertools.combinations(range(1, 14), 5), key=station_min_gap)
    gaps = {"3D/4D (m=1)": station_min_gap([1]), "12D-u {1,5,7,11,13}": station_min_gap([1, 5, 7, 11, 13]),
            "12D-n {1,2,3,4,5}": station_min_gap([1, 2, 3, 4, 5]), f"12D-* {list(best)}": station_min_gap(list(best))}
    print("min squared station gap (RMS ring radius 1):", {k: round(v, 4) for k, v in gaps.items()})
    out = {"predictions": PREDICTIONS, "station_min_gap_sq": gaps, "best_multipliers": list(best), "embeddings": {}}
    for name, make in (("3D", torus3d), ("4D", lambda r: flat([1], r)), ("12D-u", lambda r: flat([1, 5, 7, 11, 13], r)),
                       ("12D-n", lambda r: flat([1, 2, 3, 4, 5], r)), ("12D-*", lambda r: flat(list(best), r)), ("12D-rnd", random12)):
        out["embeddings"][name] = run_embedding(name, make)
    out["T4"] = t4_diagonal()
    (HERE / "knot12d.json").write_text(json.dumps(out, indent=1))
    print(f"wrote knot12d.json [{time.time()-t0:.0f} s]")
    plot(out)
