"""End-to-end check of the open-class lower bound on the explicit three-state, three-symbol source. A. Exact (Fraction) check of the recombination identity sum_s kappa_{j,s} P(w_s | p, v) = 1/
.
B. Row and column words are found by coding grid nodes backwards through the covering; the matrix
Z_ij = 1/ = 1
f = np.array([[1, -1, 0], [1, 1, -2]]) / 1.0 # basis of {y : = 0}
assert np.allclose(f @ fd.T, np.eye(2)) and np.allclose(fd @ pstar, 0)
rho = 0.02; L = 420
for q in (2, 3, 4):
t = rho * np.arange(1, q + 1) / q
nodes = np.array(list(itertools.product(t, repeat=2)))
H = 1 / (1 - nodes @ nodes.T)
rows, cols = [], []
p0 = np.random.default_rng(q).dirichlet(np.ones(n))
for g in nodes:
y = g @ f # chart value phi(p) = p* - p/ ... here = 1
p = pstar - y
lets = code(p, L) # p = F_{a_1} o ... o F_{a_L}(.)
x = p0.copy()
for a in reversed(lets): x = x @ T[a]; x = x / x.sum() # row word u = a_L ... a_1
rows.append(x)
beta = bstar + g @ fd; beta = beta / beta.sum() # symmetric matrices: same coding for the ray
lets = code(beta, L)
b = np.ones(n); logscale = 0.0
for a in reversed(lets): b = T[a] @ b; sc = b.sum(); b = b / sc; logscale += np.log(sc) # T_{a_1}...T_{a_L} 1
cols.append(b) # ray only; the scale multiplies a column
P = np.array(rows); B = np.array(cols).T
Zray = 1 / (P @ B) # columns rescaled to sum one: b_j absorbs it
a_i = 1 / (P @ bstar); b_j = 1 / (pstar @ B)
Hp = Zray / np.outer(a_i, b_j)
assert np.abs(Hp - H).max() < 1e-10, (q, np.abs(Hp - H).max())
print(f"B. q={q}: nodes {len(nodes)}, max |H' - H| = {np.abs(Hp - H).max():.1e}, "
f"smallest eigenvalue of H {np.linalg.eigvalsh(H)[0]:.2e}, smallest singular value of H' {np.linalg.svd(Hp, compute_uv=False)[-1]:.2e}, "
f"log-probability scale of a column word {logscale:.0f}")