Nyeolixa / code /verify.py
PureOne's picture
Release Nyeolixa research and exact verification data
248a358 verified
Raw History Blame Contribute Delete
15.5 kB
"""Exact polynomial certificates for the Nyeolixa reference-tetrahedron experiments."""
import argparse
import json
import math
from functools import lru_cache
from pathlib import Path
import sympy as sp
x, y, z = axes = sp.symbols("x y z")
X = sp.Matrix(axes)
V = sp.Rational(1, 6)
center = sp.Matrix([sp.Rational(1, 4)] * 3)
r = X - center
one = sp.ones(3, 1)
total = x + y + z
pair = x*y + y*z + z*x
triple = x*y*z
barycentric = (1-total, x, y, z)
bubble = sp.prod(barycentric)
p = one.cross(r)
k = sp.Matrix([x*p[0], y*p[1], z*p[2]])
@lru_cache(None)
def monomial_integral(powers):
return sp.Rational(math.prod(math.factorial(n) for n in powers),
math.factorial(sum(powers)+3))
def integrate_scalar(expr):
poly = sp.Poly(expr, *axes, domain=sp.QQ)
return sum(coef*monomial_integral(powers) for powers, coef in poly.terms())
def gradient(f):
return sp.Matrix([sp.diff(f, var) for var in axes])
def curl(a):
return sp.Matrix([sp.diff(a[2], y)-sp.diff(a[1], z),
sp.diff(a[0], z)-sp.diff(a[2], x),
sp.diff(a[1], x)-sp.diff(a[0], y)])
def terms(field):
return tuple(tuple(sp.Poly(v, *axes, domain=sp.QQ).terms()) for v in field)
@lru_cache(None)
def product_integral(left, right):
return sum(a*b*monomial_integral(tuple(i+j for i, j in zip(e, f)))
for e, a in left for f, b in right)
def inner(left, right):
return sum(product_integral(a, b) for a, b in zip(left, right))
def independent(fields):
keys = sorted({(c, e) for field in fields for c, poly in enumerate(field)
for e, coeff in poly if coeff})
columns = [{(c, e): coeff for c, poly in enumerate(field) for e, coeff in poly}
for field in fields]
matrix = sp.Matrix(len(keys), len(fields), lambda i, j: columns[j].get(keys[i], 0))
return [fields[j] for j in matrix.rref()[1]]
def projected_energy(target, candidates):
basis = independent(candidates)
count = len(basis)
gram = sp.zeros(count)
for i in range(count):
for j in range(i+1):
gram[i,j] = gram[j,i] = inner(basis[i],basis[j])
rhs = sp.Matrix([inner(target,v) for v in basis])
coeffs = gram.inv()*rhs
return (rhs.T*coeffs)[0], count
def tangency_check(field):
div = sum(sp.diff(a,t) for a,t in zip(field,axes))
if sp.expand(div) != 0:
raise ValueError("Nonzero divergence in a lower-bound test field")
walls = [field[i].subs(axes[i],0) for i in range(3)]
walls.append(sum(field).subs(z,1-x-y))
if any(sp.expand(f) != 0 for f in walls):
raise ValueError("Nonzero normal flux in a lower-bound test field")
def symmetric_factors(degree):
for a in range(degree+1):
for b in range((degree-a)//2+1):
for c in range((degree-a-2*b)//3+1):
yield total**a * pair**b * triple**c
def strain_vector(field):
grad = field.jacobian(X)
return sp.Matrix(list((grad+grad.T)/2-sp.trace(grad)*sp.eye(3)/3))
def stress_tests(degree):
"""Symmetric, traceless stresses with vanishing tangential traction."""
tests = []
basis = sp.eye(3)
for a in range(degree+1):
for sym in symmetric_factors(degree-a):
first, second = sp.zeros(3), sp.zeros(3)
for i in range(3):
j, l = (i+1)%3, (i+2)%3
u, v, w = axes[i], axes[j], axes[l]
edge = basis[:,j]-basis[:,i]
first += (1-total)*u*(v-w)*u**a*sym*(basis[:,i]*basis[:,i].T-sp.eye(3)/3)
second += u*v*(u-v)*w**a*sym*(edge*edge.T-2*sp.eye(3)/3)
tests.extend([first,second])
return tests
def rotation_bounds(degree, sqrt_alpha=0):
# Every potential in the lower space has zero tangential boundary trace.
# Upper tests are gradients of alternating scalar polynomials.
lower = []
for f in symmetric_factors(degree):
lower.append(curl(triple*f*one))
for a in range(degree+1):
for f in symmetric_factors(degree-a):
A = (1-total)*f*sp.Matrix([y*z*x**a, z*x*y**a, x*y*z**a])
lower.append(curl(A))
for field in lower:
tangency_check(field)
vandermonde = (x-y)*(y-z)*(z-x)
upper = [gradient(vandermonde*f) for f in symmetric_factors(degree)]
target = terms(p)
if sqrt_alpha:
lower = [v.col_join(sqrt_alpha*strain_vector(v)) for v in lower]
upper = [v.col_join(sp.zeros(9,1)) for v in upper]
for stress in stress_tests(max(0,degree-1)):
div = sp.Matrix([sum(sp.diff(stress[i,j],axes[j]) for j in range(3)) for i in range(3)])
for normal,sub in [(sp.eye(3)[:,i],{axes[i]:0}) for i in range(3)]+[(one,{z:1-x-y})]:
if any(sp.expand(e.subs(sub)) != 0 for e in normal.cross(stress*normal)):
raise ValueError("Invalid tangential traction in an upper-bound test stress")
if any(sp.expand(e) != 0 for e in stress-stress.T) or sp.expand(sp.trace(stress))!=0:
raise ValueError("Test stress must be symmetric and trace-free")
upper.append(div.col_join(sp.Matrix(list(stress))/sqrt_alpha))
target = terms(p.col_join(sp.zeros(9,1)))
inertia = inner(target,target)
low, nlow = projected_energy(target, [terms(v) for v in lower])
complement, nhigh = projected_energy(target, [terms(v) for v in upper])
high = inertia - complement
if not 0 < low <= high < inertia:
raise ValueError("Invalid continuum enclosure")
return low, high, nlow, nhigh
def moment_checks():
# Non-affine field with nontrivial boundary data and constant divergence.
J = sp.Matrix([[1,2,-1],[-3,0,2],[0,1,1]])
affine = sp.Matrix([2,-1,1]) + J*r
m = affine + k
mass = m.applyfunc(integrate_scalar)
C = (m*r.T).applyfunc(integrate_scalar)
ell = r.cross(m).applyfunc(integrate_scalar)
Sigma = (r*r.T).applyfunc(integrate_scalar)
theta = sp.trace(J)
def surface_flux_integral(test):
# Oriented area vectors for graph-parameterized triangular faces.
t, u = sp.symbols("t u")
points = [(0,t,u),(t,0,u),(t,u,0),(t,u,1-t-u)]
normals = [(-1,0,0),(0,-1,0),(0,0,-1),(1,1,1)]
result = sp.zeros(*test.shape)
for point, normal in zip(points,normals):
integrand = (test*m.dot(sp.Matrix(normal))).subs(dict(zip(axes,point)), simultaneous=True)
for i in range(test.rows):
for j in range(test.cols):
poly = sp.Poly(integrand[i,j],t,u)
result[i,j] += sum(a*sp.Rational(math.factorial(e[0])*math.factorial(e[1]),
math.factorial(sum(e)+2))
for e,a in poly.terms())
return result
cross_ell = sp.Matrix([[0,-ell[2],ell[1]],[ell[2],0,-ell[0]],[-ell[1],ell[0],0]])
assert mass == surface_flux_integral(r)
assert 2*C == surface_flux_integral(r*r.T)-theta*Sigma+cross_ell
reconstructed = mass/V+C*Sigma.inv()*r
residual = m-reconstructed
assert residual.applyfunc(integrate_scalar) == sp.zeros(3,1)
assert (residual*r.T).applyfunc(integrate_scalar) == sp.zeros(3)
gram = sp.zeros(3)
for i in range(3):
mode = curl(bubble*sp.eye(3)[:,i])
tangency_check(mode)
gram[:,i] = r.cross(mode).applyfunc(integrate_scalar)
assert gram == 2*integrate_scalar(bubble)*sp.eye(3) == V*sp.eye(3)/420
silent = curl(bubble*(x-center[0])*sp.Matrix([1,0,0]))
tangency_check(silent)
assert r.cross(silent).applyfunc(integrate_scalar) == sp.zeros(3,1)
assert any(sp.expand(v)!=0 for v in silent)
# Each face can expose two tangential traces. Their strain pairings span
# the five deviatoric directions. Zero-boundary curls of b^2 give three
# independent angular moments with vanishing integrated strain.
columns = []
normals = [sp.Matrix([-1,0,0]),sp.Matrix([0,-1,0]),sp.Matrix([0,0,-1]),one]
for n in normals:
tangents = sp.Matrix.hstack(*(n.cross(sp.eye(3)[:,i]) for i in range(3))).columnspace()
for t in tangents:
E = (t*n.T+n*t.T)/2
columns.append(sp.Matrix([E[0,0],E[1,1],E[0,1],E[0,2],E[1,2]]))
shear_rank = sp.Matrix.hstack(*columns).rank()
assert shear_rank == 5 and integrate_scalar(bubble**2)>0
return {"moment_identity":"exact", "angular_right_inverse_factor":str(gram[0,0]),
"shear_trace_pairing_rank":shear_rank, "total_response_rank_positive_shear":3+shear_rank,
"silent_nonzero_mode":True, "reconstructed_affine_gradient":list(map(str,C*Sigma.inv()))}
def outward(a, digits, upper=False):
scale = 10**digits
n = int(sp.ceiling(scale*a) if upper else sp.floor(scale*a))
return str(n//scale)+"."+str(n%scale).zfill(digits)
def temporal_checks():
# Positive shape with disconnected mass supports is also permitted.
initial = [sp.Rational(0),sp.Rational(0),sp.Rational(0)]
final = [sp.Rational(4),sp.Rational(0),sp.Rational(9)]
volumes = [sp.Rational(1,6),sp.Rational(1,4),sp.Rational(1,3)]
gamma = sp.Rational(3,2)
mass = sum(v*c for v,c in zip(volumes,final))
costs = {}
for T in [1,2,3,8,17]:
h = sp.Rational(1,T)
cost = 0
for n in range(T):
for start,end,volume in zip(initial,final,volumes):
a = sp.sqrt(start)+(sp.sqrt(end)-sp.sqrt(start))*n*h
b = sp.sqrt(start)+(sp.sqrt(end)-sp.sqrt(start))*(n+1)*h
U = (a+b)**2/4
if U != 0:
cost += volume*(b*b-a*a)**2/(2*gamma*h*U)
assert cost == 2*mass/gamma
costs[str(T)] = str(cost)
return {"terminal_mass":str(mass),"gamma":str(gamma),"root_mobility_energies":costs,
"arithmetic_one_step":str(mass/gamma)}
def conic_certificate_check():
R = sp.Rational
a, b, d, source = R(1), R(4), R(5,2), R(3)
mobility = (sp.sqrt(a)+sp.sqrt(b))**2/4
anchors = [R(1,2),R(17,4)]
primal = 2*(a-anchors[0])**2 + 2*(b-anchors[1])**2 + source**2/(2*mobility)
phi, eta = -R(4,3), R(0)
w_r = [-phi-eta/2,phi-eta/2]
w_s = -phi
sigma = w_s**2/2
def lower(tau):
tangent = [sigma*(1+tau)/4,sigma*(1+1/tau)/4]
dual = sum(2*t**2-max(0,4*t+w+v)**2/8 for t,w,v in zip(anchors,w_r,tangent))
return dual + d**2/2-max(0,d+eta)**2/2
if not primal == lower(R(2)) == R(21,8) or not lower(R(1)) < primal:
raise ArithmeticError("The manufactured dual certificate failed")
# Nonzero terms in the decomposed continuum enclosure, using distinct cell forms.
g_low, g_high, prior = R(1), R(3,2), R(1,2)
eta_test, tau_test = R(1,3), R(1)
residual = source-d*prior
w_nodes = [-phi-eta_test/2,phi-eta_test/2]
B = d+eta_test+prior*w_s
A = [4*t+w+sigma*(1+c)/4 for t,w,c in zip(anchors,w_nodes,[tau_test,1/tau_test])]
def remainder(v,force,weight):
return weight*v**2/2-force*v+max(0,force)**2/(2*weight)
dual = sum(2*t**2-max(0,F)**2/8 for t,F in zip(anchors,A))+d**2/2-max(0,B)**2/2
upper = sum(2*(v-t)**2 for v,t in zip([a,b],anchors))+g_high*residual**2/(2*mobility)
parts = {
"nodes":sum(remainder(v,F,4) for v,F in zip([a,b],A)),
"midpoint":remainder(d,B,1),
"cell_approximation":(g_high-g_low)*residual**2/(2*mobility),
"residual_slope":mobility*g_low*(residual/mobility-w_s/g_low)**2/2,
"time_slope":sigma*(sp.sqrt(tau_test*a)-sp.sqrt(b/tau_test))**2/4,
}
assert all(value > 0 for value in parts.values()) and sum(parts.values()) == upper-dual
return {"nodes":["1","4"],"mobility":str(mobility),"primal":str(primal),
"dual_at_tau_2":str(lower(R(2))),"dual_at_tau_1":str(lower(R(1))),
"gap_split":{name:str(value) for name,value in parts.items()}, "total_gap":str(upper-dual)}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--degree", type=int, default=4, choices=range(6))
parser.add_argument("--check", type=Path, help="recompute and compare with the recorded JSON")
args = parser.parse_args()
target, basic = terms(p), terms(k)
I, pk, kk = inner(target,target), inner(target,basic), inner(basic,basic)
S = (k.jacobian(X)+k.jacobian(X).T)/2
strain = integrate_scalar(sum(a*a for a in S))
assert [I,pk,kk,strain] == [sp.Rational(1,20),sp.Rational(1,120),
sp.Rational(1,420),sp.Rational(3,40)]
results = {"one_mode":{"prior_norm_squared":str(I),"coupling":str(pk),
"mode_norm_squared":str(kk),"shear_norm_squared":str(strain),
"kinetic_improvement_fraction":str(pk**2/(kk*I)),
"shear_0.01_improvement_fraction":str(pk**2/((kk+strain/100)*I))},
"moments":moment_checks(),"time":temporal_checks(),
"conic_certificate":conic_certificate_check(),"rotation_bounds":[]}
for n in range(args.degree+1):
low,high,k1,k2 = rotation_bounds(n)
results["rotation_bounds"].append({"degree_parameter":n,"lower_space_rank":k1,"upper_space_rank":k2,
"lower_fraction":str(low/I),"upper_fraction":str(high/I),
"percentage_interval":[outward(100*low/I,6),outward(100*high/I,6,True)]})
shear_degree = min(4,args.degree)
shear_low,shear_high,primal_rank,dual_rank = rotation_bounds(shear_degree,sp.Rational(1,10))
results["shear_0.01_continuum"] = {
"degree_parameter":shear_degree,"lower_space_rank":primal_rank,"upper_space_rank":dual_rank,
"lower_fraction":str(shear_low/I),"upper_fraction":str(shear_high/I),
"percentage_interval":[outward(100*shear_low/I,6),outward(100*shear_high/I,6,True)]}
# The cyclic permutation symmetry fixes the rotation axis. The optimizer
# with the three measured angular moments is a scalar multiple of R_L(1,1,1).
ell = r.cross(k).applyfunc(integrate_scalar)
assert ell == one/360 and ell.dot(one) == pk
recovery = {}
for weight, lo, hi, truth_norm in [
("kinetic", low, high, kk), ("shear_0.01", shear_low, shear_high, kk+strain/100)
]:
left, right = pk**2/(hi*truth_norm), pk**2/(lo*truth_norm)
assert 0 < left <= right <= 1
recovery[weight] = {"lower_fraction":str(left),"upper_fraction":str(right),
"percentage_interval":[outward(100*left,6),outward(100*right,6,True)]}
results["measured_circulation_recovery"] = {"angular_moment":list(map(str,ell)),"reduction":recovery}
# Coupled one-cell optimization with three unit density anchor weights.
elow,ehigh = I-high,I-low
value = lambda e: e/2-e**2/24
results["closed_cell_full_objective"] = {
"optimal_density_interval":[outward(1-ehigh/6,9),outward(1-elow/6,9,True)],
"optimal_objective_interval":[outward(value(elow),9),outward(value(ehigh),9,True)],
"affine_optimum":str(value(I)),
"objective_improvement_percent":[outward(100*(1-value(ehigh)/value(I)),6),
outward(100*(1-value(elow)/value(I)),6,True)]}
if args.check and results != json.loads(args.check.read_text()):
raise ValueError("The independently recomputed exact results differ from the supplied JSON")
print(json.dumps(results,indent=2))
if __name__ == "__main__":
main()