PureOne's picture
Publish Soryeixa research dataset
f3a3f9d verified
Raw History Blame Contribute Delete
9.03 kB
"""Reproduce the finite examples in Soryeixa. Run with Python 3, NumPy, SciPy, SymPy."""
import itertools
import json
import math
import numpy as np
import sympy as sp
from scipy.linalg import sqrtm
from scipy.optimize import linprog, minimize_scalar
def rotation_lp():
"""Two transformation signs and two target signs, with one source atom."""
cost = np.array([[0., 4.], [4., 0.]])
target_rows = np.tile(np.eye(2), (1, 2))
result = linprog(cost.ravel(), A_eq=target_rows, b_eq=[.5, .5])
# Condition Z|theta=nu. Equal row entries enforce it for this uniform target.
balanced = np.vstack((target_rows, [1, -1, 0, 0], [0, 0, 1, -1]))
repair = linprog(cost.ravel(), A_eq=balanced, b_eq=[.5, .5, 0, 0])
assert result.success and repair.success
assert result.fun == 0 and repair.fun == 2 and np.all(cost.mean(axis=1) == 2)
return {"fixed_costs": [2, 2], "source_independence": result.fun,
"both_marginal_independences": repair.fun, "relaxed_plan": result.x.reshape(2, 2).tolist()}
def octagon():
angles = np.arange(8) * math.pi / 4
targets = np.column_stack((np.cos(angles), np.sin(angles)))
rows = np.kron(np.eye(4), np.ones((1, 8)))
cols = np.tile(np.eye(8), (1, 4))
def transport(angle):
source_angles = angles[::2] + angle
source = np.column_stack((np.cos(source_angles), np.sin(source_angles)))
cost = ((source[:, None] - targets[None]) ** 2).sum(axis=2)
fit = linprog(cost.ravel(), A_eq=np.vstack((rows, cols)), b_eq=[.25]*4 + [.125]*8)
assert fit.success
return fit.fun
grid = np.linspace(0, math.pi/4, 33)
deviation = max(abs(transport(t) - (2-math.cos(t)-math.cos(math.pi/4-t))) for t in grid)
optimum = minimize_scalar(transport, bounds=(0, math.pi/4), method="bounded")
exact = 2-2*math.cos(math.pi/8)
assert deviation < 1e-12 and abs(optimum.fun-exact) < 1e-12
return {"squared_minimum": exact, "optimal_angle_radians": optimum.x,
"relaxed_cost": 0, "LP_grid_size": len(grid), "max_formula_discrepancy": deviation}
def elliptical_projection():
t = sp.symbols("t", real=True)
f = 20 + 10*t**2 - 2*sp.sqrt(36+64*t**2)
tstar = sp.sqrt(31)/20
assert sp.simplify(sp.diff(f, t).subs(t, tstar)) == 0
assert f.subs(t, tstar) == sp.Rational(319, 40)
T = np.diag([1., 9.])
max_error = 0.
for u in np.linspace(-.5, .5, 31):
A = np.array([[1., u], [u, 1.]])
S = A @ np.diag([9., 1.]) @ A
root = sqrtm(S)
cost = np.trace(S+T-2*sqrtm(root @ T @ root))
max_error = max(max_error, abs(float(f.subs(t, u)) - cost))
assert max_error < 1e-10
return {"argmin": ["-sqrt(31)/20", "sqrt(31)/20"], "squared_minimum": "319/40",
"squared_cost_at_zero": 8, "max_direct_matrix_discrepancy": max_error}
def radial_moments():
# E[t^p cos(n phi)] is the nth Laurent coefficient when z=exp(i phi).
z = sp.symbols("z")
t = sp.Rational(5, 8) + sp.Rational(3, 16)*(z+1/z)
coefficients = [sp.expand(t**p) for p in range(10)]
summaries = []
for h in range(1, 8):
matrix = sp.Matrix(3, 3, lambda i, j: coefficients[h+j].coeff(z, h+i))
for n in range(h, h+3):
assert all(coefficients[p].coeff(z, n) == 0 for p in range(n))
target = sp.Rational(3, 16)**(3*h+3)
assert matrix.det() == target
# A nonzero three-vector determinant below the proposed budget would refute the claim.
degrees = [2*h+1, 2*h+3, 2*h+5]
assert sum(degrees) == 6*h+9
summaries.append({"h": h, "first_block_sizes": degrees, "threshold": sum(degrees),
"determinant_without_amplitude_factor": str(target)})
return summaries
def block_projection():
"""Compare the iterative KL projection with an independent, bounded dual search."""
from scipy.optimize import minimize
from scipy.special import logsumexp
p = np.array([.25, .75])
b = np.array([.3, .7])
prior = np.array([.45, .55])
cost = np.array([[[0., 1.], [2., .2]], [[.4, 1.7], [1.1, 0.]]])
eps = .55
ref = p[:, None, None] * prior[None, :, None] * b[None, None, :]
kernel = ref * np.exp(-cost/eps)
plan = kernel / kernel.sum()
for step in range(1, 10001):
s = plan.sum(axis=2)
logweights = (p[:, None]*np.log(s/p[:, None])).sum(axis=0)
weights = np.exp(logweights-logsumexp(logweights))
plan *= (p[:, None]*weights/s)[:, :, None]
plan *= (b/plan.sum(axis=(0, 1)))[None, None, :]
residual = np.max(np.abs(plan.sum(axis=2) - p[:, None]*plan.sum(axis=(0, 2))))
if residual < 1e-13:
break
primal = np.sum(plan * (cost + eps*np.log(plan/ref)))
# Independent entropy dual: enforce the two conditional row proportions and one column mass.
features = np.zeros((2, 2, 2, 3))
for j in range(2):
features[0, j, :, j] = 1-p[0]
features[1, j, :, j] = -p[0]
features[:, :, 0, 2] = 1
expected = np.array([0., 0., b[0]])
def negdual(y):
logits = np.log(kernel) + (features @ y)/eps
log_norm = logsumexp(logits)
tilted = np.exp(logits-log_norm)
return eps*log_norm-y @ expected, (tilted[..., None]*features).sum(axis=(0, 1, 2))-expected
dual = minimize(negdual, np.zeros(3), jac=True, method="BFGS", options={"gtol": 1e-11})
assert residual < 1e-12 and abs(primal + dual.fun) < 1e-10
return {"regularized_value": primal, "iterations": step, "constraint_error": residual,
"absolute_primal_dual_difference": abs(primal+dual.fun)}
def pauli_witness():
pauli = [np.array([[0.,1.],[1.,0.]]), np.array([[0.,-1j],[1j,0.]]), np.diag([1.,-1.])]
triple = np.zeros((8, 8), complex)
for perm in itertools.permutations(range(3)):
inversions = sum(perm[i]>perm[j] for i in range(3) for j in range(i+1, 3))
i, j, k = perm
triple += (-1)**inversions*np.kron(np.kron(pauli[i], pauli[j]), pauli[k])
dot = sum(np.kron(p, p) for p in pauli)
vectors = np.array([[.2, .4, .1], [-.3, .2, .5], [.1, -.4, .6]])
states = [(np.eye(2)+sum(a*p for a, p in zip(v, pauli)))/2 for v in vectors]
product = np.kron(np.kron(states[0], states[1]), states[2])
assert abs(np.trace(triple @ product) - np.linalg.det(vectors)) < 1e-14
assert abs(np.trace(dot @ np.kron(states[0], states[0])) - vectors[0] @ vectors[0]) < 1e-14
return {"triple_operator_norm": np.linalg.norm(triple, 2), "pair_operator_norm": np.linalg.norm(dot, 2),
"example_determinant": np.linalg.det(vectors)}
def quantum_information():
"""Numerical cross-check of the tapered feature and the many-copy information bound."""
from scipy.special import roots_legendre
from scipy.stats import binom
nodes, weights = roots_legendre(320)
phi = (nodes+1)*np.pi/2
weights = weights/2
t = 5/8 + (3/8)*np.cos(phi)
radius = np.sqrt(t)
plus = (1+radius)/2
records = []
for h in [1, 2, 5, 12]:
g = np.cos(phi[:, None]*np.arange(h, h+3))
gram = 2*g.T @ ((weights*np.sin(phi)**2)[:, None]*g)
gram_exact = np.array([[.25 if h == 1 else .5, 0, -.25], [0, .5, 0], [-.25, 0, .5]])
assert np.allclose(gram, gram_exact, atol=1e-12)
ratios = []
for m in [1, 3, 10, 40, 100]:
# Binomial counts group the equiprobable strings of the same Hamming weight.
likelihood = binom.pmf(np.arange(m+1)[None, :], m, plus[:, None])
masses = weights @ likelihood
coefficients = likelihood.T @ ((weights/radius)[:, None]*g)
energy = np.sum((coefficients**2)/masses[:, None])
proved_bound = sum((9/4+3*m)/k**2 for k in range(h, h+3))
assert energy <= proved_bound+1e-11
ratios.append(float(energy/proved_bound))
records.append({"h": h, "smallest_tapered_Gram_eigenvalue": float(np.linalg.eigvalsh(gram)[0]),
"largest_tested_energy_to_bound_ratio": max(ratios)})
return records
def continuous_gap():
n = sp.symbols("n", positive=True, integer=True)
u, v = sp.symbols("u v")
shared_bin_cost = sp.integrate(sp.integrate((u-v)**2, (u,0,1/n)), (v,0,1/n))*n**2
deterministic = sp.integrate((u-sp.Rational(1,2))**2, (u,0,1))
assert sp.simplify(shared_bin_cost-1/(6*n*n)) == 0 and deterministic == sp.Rational(1,12)
return {"deterministic": str(deterministic), "shared_bin_cost": str(shared_bin_cost),
"shared_bin_entropy": "log(n)", "relaxed_zero_temperature_limit": 0}
if __name__ == "__main__":
checks = {"two_point": rotation_lp(), "square_octagon": octagon(),
"elliptical_geodesic": elliptical_projection(), "radial_moment_flags": radial_moments(),
"finite_entropic_projection": block_projection(), "continuous_entropic_gap": continuous_gap(),
"pauli_witness": pauli_witness(), "quantum_information": quantum_information()}
print(json.dumps(checks, indent=2))