"""Encapsulation Domains v2.10 -- reproducible checks. numpy only; seeds fixed.
C1-C5: the mathematical statements added since v2.3.  C6: the fiber-invisibility run of Section 8.
C7: dynamics across scales.  C8: congruence of the loaded-stiffness model under a curved outside view."""
import numpy as np, itertools, math
rng = np.random.default_rng(24)

print("C1  Loaded-stiffness model: margin and onset direction (random symmetric stiffness, 6-dimensional)")
ok_stab = ok_align = trials = 0
for _ in range(500):
    B = rng.normal(size=(6, 6)); S = B @ B.T + 0.1*np.eye(6)
    lam, V = np.linalg.eigh(S); lmin, lmax = lam[0], lam[-1]
    for h in (lmin - 0.05*(lmax-lmin), lmin + 0.05*(lmax-lmin)):
        tau = 0.9/(lmax - h); A = np.eye(6) - tau*(S - h*np.eye(6))
        ok_stab += ((max(abs(np.linalg.eigvals(A))) < 1) == (h < lmin)); trials += 1
    h = lmin - 1e-3*(lmax-lmin); tau = 0.9/(lmax - h); A = np.eye(6) - tau*(S - h*np.eye(6)); d = rng.normal(size=6)
    for t in range(4000): d = A @ d; d /= np.linalg.norm(d)
    ok_align += abs(V[:, 0] @ d) > 0.999
print(f"    stable iff load < lowest eigenvalue: {ok_stab}/{trials}")
print(f"    aligned with lowest eigenvector near threshold (|cos| > 0.999): {ok_align}/500")

print("C2  Coarse-graining")
K = 2**16; inv3 = pow(3, -1, K); w = lambda q: (inv3*int(np.sum(q))) % K; ok = 0
for _ in range(1000):
    Q = rng.integers(0, K, size=(5, 3)); ok += w(Q.sum(0) % K) == sum(w(q) for q in Q) % K
print(f"    witness of a sum = sum of witnesses (mod 2^16): {ok}/1000")
dev = lambda T: T - np.trace(T)/3*np.eye(3)
T1, T2 = np.diag([2., 1, 1]), np.diag([1., 2, 1])
for name, T in (("diag(2,1,1)", T1), ("diag(1,2,1)", T2), ("sum diag(3,3,2)", T1+T2)):
    q = np.sort(np.linalg.eigvalsh(T)); d = q - q.mean()
    print(f"    {name:16s} principal deviations {np.round(d,3)} -> {'prolate' if d[-1] > -d[0] else 'oblate'}")
fro2 = lambda T: float(np.sum(T*T))
print("    aggregate sufficiency: parts {diag(2,1,1), diag(1,2,1)} and {diag(3,3,2), 0} have the same sum;")
P1, P2 = (T1, T2), (T1+T2, np.zeros((3, 3)))
print(f"      ||sum||^2 = {fro2(sum(P1)):.0f} and {fro2(sum(P2)):.0f} (factors through the sum); sum ||T_j||^2 = {fro2(P1[0])+fro2(P1[1]):.0f} and {fro2(P2[0])+fro2(P2[1]):.0f} (does not)")

print("C3  Observer hierarchy (closure domain, n = 3, mod 8)")
M = 8; inv = pow(3, -1, M)
def wd(q): ww = (inv*sum(q)) % M; return ww, tuple((x - ww) % M for x in q[:2])
q, qc = (0, 1, 7), (2, 3, 1)                                # qc = q + 2*(1,1,1)
print(f"    q={q}: (w,d)={wd(q)};  q+2*1={qc}: (w,d)={wd(qc)}  -> same deviation, different witness")
print(f"    (0,0,0) and (1,7,0): witnesses {wd((0,0,0))[0]} and {wd((1,7,0))[0]}; deviations differ -> H1 is not a function of H0")
a, b = (1, 7, 0), (7, 1, 0)                                  # two parts whose deviations cancel
s = tuple((x+y) % M for x, y in zip(a, b))
print(f"    parts {a},{b} sum to {s}, the same whole as parts (0,0,0),(0,0,0) -> H2 is not a function of H1")

print("C4  Saturation: first-order versus exact invisibility of tilts")
N = 10; th = 1e-3*rng.normal(size=N)
P = lambda t: np.cos(t).sum()
g = np.array([(P(1e-7*np.eye(N)[i]) - P(np.zeros(N)))/1e-7 for i in range(N)])
print(f"    max |dPi/dtheta_i| at 0 = {np.max(abs(g)):.1e};  Pi(theta) - N = {P(th)-N:.3e} vs -|theta|^2/2 = {-th@th/2:.3e}")

print("C5  Multiplication by a unit preserves equality but leaks structure (mod 2^8)")
k = 8; Mk = 2**k; lam = 2*int(rng.integers(0, Mk//2)) + 1
v2 = lambda x: k if x == 0 else (x & -x).bit_length() - 1
print(f"    lambda = {lam}: injective {len({lam*x % Mk for x in range(Mk)}) == Mk}; zero kept {lam*0 % Mk == 0}; "
      f"2-adic valuation kept for all x: {all(v2(lam*x % Mk) == v2(x) for x in range(Mk))}")

print("C6  Fiber invisibility: pairs sharing an outside view, evolved by total-preserving transitions (n = 3, mod 2^16)")
K6 = 2**16; inv6 = pow(3, -1, K6); wit = lambda q: (inv6*sum(q)) % K6
steps = []                                                    # twenty fixed deterministic transitions, each total-preserving
for _ in range(20):
    perm = [int(x) for x in rng.permutation(3)]; i, j = (int(x) for x in rng.choice(3, 2, replace=False)); c = int(rng.integers(1, K6))
    steps.append((perm, i, j, c))
def step(q, s):
    perm, i, j, c = s; q = [q[p] for p in perm]; a = (c*q[i]*q[i] + q[j]) % K6   # amount moved depends nonlinearly on the state
    q[i] = (q[i] - a) % K6; q[j] = (q[j] + a) % K6; return q
same = differ = 0
for _ in range(500):
    q = [int(x) for x in rng.integers(0, K6, 3)]; d0 = [int(x) for x in rng.integers(0, K6, 2)]
    q2 = [(q[0] + d0[0]) % K6, (q[1] + d0[1]) % K6, (q[2] - d0[0] - d0[1]) % K6]   # same total, different inside
    ok_pair = True
    for s in steps:
        q, q2 = step(q, s), step(q2, s); ok_pair &= wit(q) == wit(q2)
    same += ok_pair; differ += q != q2
print(f"    pairs with equal witness at all 20 steps: {same}/500; pairs whose insides still differ after 20 steps: {differ}/500")

print("C7  Dynamics across scales: cyclic shifts of 3^L entries (mod 8)")
M8 = 8; i3 = pow(3, -1, M8)
def view(q, l):                                                # level-l witnesses
    for _ in range(l): q = [(i3*(q[3*b] + q[3*b+1] + q[3*b+2])) % M8 for b in range(len(q)//3)]
    return q
shift = lambda q, s: q[-s:] + q[:-s] if s else q[:]
q = [1, 0, 7, 0, 0, 0, 0, 0, 0]; z = [0]*9
print(f"    q = {q}: level-1 view {view(q, 1)}, same as zero; after a shift by 1: {view(shift(q, 1), 1)} vs {view(shift(z, 1), 1)}")
L = 3; N = 3**L; ok = 0; cases = 0
for l in range(1, L + 1):
    for s_ in range(N):
        kernel_kept = True
        for a in range(N - 1):                                 # the e_a - e_(a+1) lying inside one level-l block span the kernel of the level-l view
            d = [0]*N; d[a] = 1; d[a+1] = M8 - 1
            if view(d, l) == [0]*len(view(d, l)) and view(shift(d, s_), l) != [0]*len(view(d, l)): kernel_kept = False; break
        predicted = (s_ % 3**l == 0) or l == L
        ok += kernel_kept == predicted; cases += 1
print(f"    shift by s respects level l iff 3^l divides s (or l = L): {ok}/{cases} (L = 3, all s, all l)")

print("C8  Loaded stiffness under a curved outside view Pi = sum cos(theta_i)")
P = lambda th: float(np.cos(th).sum())
A = np.diag([0.5, 0.75]); a1, a2 = np.array([0.5, 0.0]), np.array([0.0, 0.5])
print(f"    A = diag(1/2, 3/4): Pi equal before ({P(a1):.7f}, {P(a2):.7f}); after one step {P(A@a1):.7f} vs {P(A@a2):.7f} -> Axiom 4 fails")
def radial(A, trials=200):                                     # is |A theta| a function of |theta|?  spread of |A u| over unit u
    U = rng.normal(size=(trials, A.shape[0])); U /= np.linalg.norm(U, axis=1)[:, None]
    r = np.linalg.norm(U @ A.T, axis=1); return r.max() - r.min()
Q, _ = np.linalg.qr(rng.normal(size=(4, 4)))
print(f"    spread of |A u| on the unit sphere: random A {radial(rng.normal(size=(4,4))):.3f}; A = 0.7 x orthogonal {radial(0.7*Q):.1e}")
n_iso = n_aniso = 0
for _ in range(500):
    B = rng.normal(size=(4, 4)); S = B @ B.T + 0.1*np.eye(4); lam = np.linalg.eigvalsh(S); eta = lam[0] - 0.1
    tau = 1.0/(lam[-1] - eta); A = np.eye(4) - tau*(S - eta*np.eye(4))
    n_aniso += radial(A) > 1e-9
    lam0 = float(rng.uniform(1, 3)); A = np.eye(4) - tau*(lam0*np.eye(4) - eta*np.eye(4)); n_iso += radial(A) < 1e-9
print(f"    under tau(lmax - eta) <= 1: anisotropic S never radial {n_aniso}/500; isotropic S always radial {n_iso}/500")
lam_soft, eta, tau = 1.0, 0.5, 1.6; c = 1 - tau*(lam_soft - eta); lam_stiff = eta + (1 + c)/tau
A = np.diag([1 - tau*(lam_soft - eta)]*2 + [1 - tau*(lam_stiff - eta)]*2)
print(f"    two-valued S (soft {lam_soft}, stiff {lam_stiff:.3f}, tau = {tau}): mu = {np.round(np.diag(A),3)}, A^T A = cI: {np.allclose(A.T@A, c*c*np.eye(4))}, stable: {tau*(lam_stiff - eta) < 2}")
a = 1.2; b = float(np.arccos((np.cos(a) + 1)/2))                # (a, 0) and (b, b) share the cosine view
t1, t2 = np.array([a, 0.0]), np.array([b, b]); Ah = 0.5*np.eye(2)
print(f"    isotropic step A = I/2 under the cosine view: Pi equal before ({P(t1):.7f}, {P(t2):.7f}); after {P(Ah@t1):.7f} vs {P(Ah@t2):.7f} -> fourth order breaks it")
