Datasets:
Formats:
csv
Languages:
English
Size:
< 1K
Tags:
mathematics
homogenization
spectral-theory
variational-methods
matrix-analysis
scientific-computing
Download research/code/verify_universality.py from PureOne/EVE-QELTHA: direct link, hf CLI and curl.
- Browser
- Download file 12.2 kB
-
https://huggingface.co/datasets/PureOne/EVE-QELTHA/resolve/main/research/code/verify_universality.py
- Command line
-
hf download hf://datasets/PureOne/EVE-QELTHA/research/code/verify_universality.py
-
curl -L -o verify_universality.py https://huggingface.co/datasets/PureOne/EVE-QELTHA/resolve/main/research/code/verify_universality.py
12.2 kB
| #!/usr/bin/env python3 | |
| """Independent numerical checks of universal moving-dark-frame synthesis. | |
| All tests concern the specified finite-interval passive variational model. | |
| They are implementation checks, not a proof of the theorem or of novelty. | |
| The full ambient penalty problem is discretized in fixed Cartesian variables; | |
| the target matrix Sturm--Liouville problem is also solved by an independent | |
| fundamental-matrix ODE. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| from pathlib import Path | |
| import numpy as np | |
| from numpy.polynomial.legendre import leggauss | |
| from scipy import sparse | |
| from scipy.integrate import solve_ivp, solve_bvp | |
| from scipy.sparse.linalg import splu | |
| LENGTH = 1.4 | |
| I2 = np.eye(2, dtype=complex) | |
| SX = np.array([[0, 1], [1, 0]], dtype=complex) | |
| SZ = np.diag([1., -1.]).astype(complex) | |
| def coupling(t): | |
| """A smooth invertible C; V=C^dagger C is positive and noncommuting.""" | |
| return np.array([[1. + .1*np.cos(1.7*t), .35*np.exp(1.4j*t)], | |
| [0., .7 + .2*np.sin(1.1*t)]], dtype=complex) | |
| def potential(t): | |
| cc = coupling(t) | |
| return cc.conj().T @ cc | |
| def connection(t): | |
| return 1j*(.2*SZ + .15*np.cos(2*t)*SX) | |
| def generator(t, include_connection): | |
| cc = coupling(t) | |
| aa = connection(t) if include_connection else np.zeros((2,2), complex) | |
| return np.block([[aa, -cc.conj().T], [cc, np.zeros((2,2), complex)]]) | |
| def frame_solution(include_connection=False): | |
| def rhs(t, flat): | |
| return (flat.reshape(4,4) @ generator(t, include_connection)).ravel() | |
| sol = solve_ivp(rhs, (0., LENGTH), np.eye(4, dtype=complex).ravel(), | |
| method='DOP853', rtol=2e-12, atol=2e-13, dense_output=True) | |
| if not sol.success: | |
| raise RuntimeError(sol.message) | |
| return sol | |
| def frame_identity_checks(): | |
| sol = frame_solution(True) | |
| rng = np.random.default_rng(20261020) | |
| metrics = dict(unitarity=0., projector_spectrum=0., connection=0., | |
| geometric_potential=0., section_energy=0., | |
| ode_finite_difference=0.) | |
| for t in np.linspace(0., LENGTH, 151): | |
| uu = sol.sol(t).reshape(4,4) | |
| nn = uu[:, :2] | |
| nd = (uu @ generator(t, True))[:, :2] | |
| mm = np.eye(4)-nn@nn.conj().T | |
| metrics['unitarity'] = max(metrics['unitarity'], float(np.linalg.norm(uu.conj().T@uu-np.eye(4)))) | |
| metrics['projector_spectrum'] = max(metrics['projector_spectrum'], float(np.max(abs(np.linalg.eigvalsh(mm)-[0,0,1,1])))) | |
| metrics['connection'] = max(metrics['connection'], float(np.linalg.norm(nn.conj().T@nd-connection(t)))) | |
| metrics['geometric_potential'] = max(metrics['geometric_potential'], float(np.linalg.norm(nd.conj().T@mm@nd-potential(t)))) | |
| xi = rng.normal(size=2)+1j*rng.normal(size=2) | |
| xid = rng.normal(size=2)+1j*rng.normal(size=2) | |
| lhs = np.linalg.norm(nd@xi+nn@xid)**2 | |
| rhs = np.linalg.norm(xid+connection(t)@xi)**2+np.vdot(xi,potential(t)@xi).real | |
| metrics['section_energy'] = max(metrics['section_energy'], float(abs(lhs-rhs))) | |
| if .001 < t < LENGTH-.001: | |
| hh = 2e-5 | |
| numerical = (sol.sol(t+hh).reshape(4,4)-sol.sol(t-hh).reshape(4,4))/(2*hh) | |
| metrics['ode_finite_difference'] = max(metrics['ode_finite_difference'], float(np.linalg.norm(numerical-uu@generator(t,True)))) | |
| vv0,vv1=potential(.2),potential(1.1) | |
| noncomm = float(np.linalg.norm(vv0@vv1-vv1@vv0)) | |
| assert noncomm > .05 | |
| assert max(metrics[k] for k in metrics if k!='ode_finite_difference') < 1e-8, metrics | |
| assert metrics['ode_finite_difference'] < 1e-7, metrics | |
| return dict(maximum_absolute_errors=metrics, noncommuting_potential_commutator_norm=noncomm, | |
| sample_positions=151, seed=20261020) | |
| def assemble_fem(cells, field, dimension, gauss_order=5): | |
| """Assemble ∫|P'|²+P†field(t)P for nodal linear Cartesian P.""" | |
| nodes = np.linspace(0., LENGTH, cells+1) | |
| width = LENGTH/cells | |
| dim = dimension | |
| ids = dim*np.arange(cells)[:,None]+np.arange(2*dim)[None,:] | |
| local = np.zeros((cells,2*dim,2*dim), dtype=complex) | |
| ident = np.eye(dim) | |
| local[:,:dim,:dim] += ident/width | |
| local[:,:dim,dim:] -= ident/width | |
| local[:,dim:,:dim] -= ident/width | |
| local[:,dim:,dim:] += ident/width | |
| points,weights=leggauss(gauss_order) | |
| for gp,gw in zip(points,weights): | |
| n1,n2=(1-gp)/2,(1+gp)/2 | |
| locations=nodes[:-1]+width*(gp+1)/2 | |
| vv=np.stack([field(t) for t in locations]) | |
| weight=width*gw/2 | |
| local[:,:dim,:dim]+=weight*n1*n1*vv | |
| local[:,:dim,dim:]+=weight*n1*n2*vv | |
| local[:,dim:,:dim]+=weight*n2*n1*vv | |
| local[:,dim:,dim:]+=weight*n2*n2*vv | |
| rr=np.broadcast_to(ids[:,:,None],local.shape).ravel() | |
| cc=np.broadcast_to(ids[:,None,:],local.shape).ravel() | |
| mat=sparse.coo_matrix((local.ravel(),(rr,cc)),shape=(dim*(cells+1),dim*(cells+1))).tocsc() | |
| return mat | |
| def inlet_dtn(mat, dim, inlet_dim): | |
| """P(0)=(z,0), P(L)=0. Return z's inlet energy matrix.""" | |
| boundary=np.arange(inlet_dim) | |
| free=np.arange(dim,mat.shape[0]-dim) | |
| mff=mat[free,:][:,free].tocsc() | |
| mfb=mat[free,:][:,boundary].toarray() | |
| mbb=mat[boundary,:][:,boundary].toarray() | |
| factor=splu(mff) | |
| response=factor.solve(mfb) | |
| capacity=mbb-mfb.conj().T@response | |
| residue=np.linalg.norm(mff@response-mfb)/max(np.linalg.norm(mfb),1.) | |
| return (capacity+capacity.conj().T)/2, float(residue) | |
| def target_dtn_ode(): | |
| def rhs(t,flat): | |
| state=flat.reshape(4,4) | |
| op=np.block([[np.zeros((2,2)),I2],[potential(t),np.zeros((2,2))]]) | |
| return (op@state).ravel() | |
| sol=solve_ivp(rhs,(0.,LENGTH),np.eye(4,dtype=complex).ravel(), | |
| method='DOP853',rtol=2e-12,atol=2e-13) | |
| if not sol.success:raise RuntimeError(sol.message) | |
| flow=sol.y[:,-1].reshape(4,4) | |
| response=np.linalg.solve(flow[:2,2:],flow[:2,:2]) | |
| return (response+response.conj().T)/2 | |
| def penalty_boundary_checks(): | |
| target=target_dtn_ode() | |
| target_rows=[] | |
| for cells in (200,400,800): | |
| hh,res=inlet_dtn(assemble_fem(cells,potential,2),2,2) | |
| err=float(np.linalg.norm(hh-target)/np.linalg.norm(target)) | |
| target_rows.append(dict(cells=cells,relative_error_to_ode=err,linear_residual=res)) | |
| assert target_rows[-1]['relative_error_to_ode'] < 2e-6 | |
| sol=frame_solution(False) | |
| def projector(t): | |
| uu=sol.sol(t).reshape(4,4) | |
| bb=uu[:,2:] | |
| return bb@bb.conj().T | |
| # Precompute the stiffness and unit-penalty matrices once for each mesh. | |
| rows=[] | |
| for cells in (800,1600): | |
| kk=assemble_fem(cells,lambda t:np.zeros((4,4),complex),4) | |
| mass=assemble_fem(cells,projector,4)-kk | |
| last=None | |
| for penalty in (1.,10.,100.,1000.,10000.,100000.): | |
| hh,res=inlet_dtn(kk+penalty*mass,4,2) | |
| err=float(np.linalg.norm(hh-target)/np.linalg.norm(target)) | |
| row=dict(cells=cells,penalty=penalty,relative_error_to_limit=err, | |
| linear_residual=res,eigenvalues=np.linalg.eigvalsh(hh).tolist(), | |
| real_part=hh.real.tolist(),imaginary_part=hh.imag.tolist()) | |
| if last is not None: | |
| row['least_eigenvalue_of_capacity_increment']=float(np.min(np.linalg.eigvalsh(hh-last))) | |
| assert row['least_eigenvalue_of_capacity_increment'] > -1e-8 | |
| last=hh | |
| rows.append(row) | |
| finest=[r for r in rows if r['cells']==1600] | |
| assert finest[-1]['relative_error_to_limit'] < .003 | |
| assert finest[-1]['relative_error_to_limit'] < finest[0]['relative_error_to_limit']/30 | |
| coarse=rows[5] | |
| fine=rows[-1] | |
| hco=np.array(coarse['real_part'])+1j*np.array(coarse['imaginary_part']) | |
| hfi=np.array(fine['real_part'])+1j*np.array(fine['imaginary_part']) | |
| mesh_error=float(np.linalg.norm(hfi-hco)/np.linalg.norm(hfi)) | |
| assert mesh_error < .001 | |
| return dict(interval=[0,LENGTH],target_method='independent fundamental-matrix ODE', | |
| target_real_part=target.real.tolist(),target_imaginary_part=target.imag.tolist(), | |
| target_eigenvalues=np.linalg.eigvalsh(target).tolist(), | |
| target_fem_cross_checks=target_rows,penalty_rows=rows, | |
| last_mesh_relative_change=mesh_error, | |
| full_method='fixed Cartesian four-component linear FEM; five-point potential quadrature', | |
| scope='finite penalties approximate the proven infinite-penalty limit; finite-element errors are empirical mesh checks') | |
| def residual_gram_correction_checks(): | |
| """Check the sharp 1/rho correction by an independent boundary-value ODE. | |
| Constant diagonal target potentials reduce to two independent real 2x2 | |
| rotating planes. This avoids finite-element locking at large rho. | |
| """ | |
| rows=[] | |
| for vv in (.7,1.8): | |
| cc=np.sqrt(vv) | |
| kk=np.array([[0.,-cc],[cc,0.]]) | |
| projection=np.diag([0.,1.]) | |
| target=cc/np.tanh(cc*LENGTH) | |
| derivative_integral=vv/(np.sinh(cc*LENGTH)**2)*(LENGTH/2+np.sinh(2*cc*LENGTH)/(4*cc)) | |
| gram=4*vv*derivative_integral | |
| ratios=[] | |
| for rho in (100.,1000.,10000.,100000.,1000000.): | |
| # The mesh has endpoint clustering; solve_bvp refines it further. | |
| tt=np.unique(np.concatenate([np.linspace(0,LENGTH,121), | |
| LENGTH*np.linspace(0,1,61)**3, | |
| LENGTH-LENGTH*np.linspace(0,1,61)**3])) | |
| xi=np.sinh(cc*(LENGTH-tt))/np.sinh(cc*LENGTH) | |
| xid=-cc*np.cosh(cc*(LENGTH-tt))/np.sinh(cc*LENGTH) | |
| guess=np.vstack([xi,np.zeros_like(tt),xid,np.zeros_like(tt)]) | |
| jac=np.block([[np.zeros((2,2)),np.eye(2)], | |
| [vv*np.eye(2)+rho*projection,-2*kk]]) | |
| def rhs(t,y):return jac@y | |
| def bc(left,right):return np.r_[left[:2]-[1.,0.],right[:2]] | |
| def fjac(t,y):return np.repeat(jac[:,:,None],t.size,axis=2) | |
| sol=solve_bvp(rhs,bc,tt,guess,tol=3e-10,max_nodes=12000,fun_jac=fjac) | |
| assert sol.success, sol.message | |
| actual=-sol.y[2,0] | |
| defect=target-actual | |
| ratio=rho*defect/gram | |
| assert defect > -2e-9 | |
| assert ratio < 1+2e-6 | |
| assert ratio > 0 | |
| ratios.append(ratio) | |
| rows.append(dict(target_eigenvalue=vv,penalty=rho, | |
| target_admittance=float(target),finite_penalty_admittance=float(actual), | |
| residual_gram_coefficient=float(gram),scaled_defect=float(rho*defect), | |
| scaled_defect_to_gram_ratio=float(ratio), | |
| adaptive_nodes=sol.x.size,maximum_rms_residual=float(np.max(sol.rms_residuals)))) | |
| assert abs(ratios[-1]-1) < .006, ratios | |
| assert all(b>a for a,b in zip(ratios,ratios[1:])),ratios | |
| return dict(method='independent adaptive rotating-plane boundary-value ODE', | |
| target_potential_eigenvalues=[.7,1.8],interval=[0,LENGTH],rows=rows, | |
| checked_bound='0 <= Y_infinity-Y_rho <= W/rho', | |
| checked_limit='rho*(Y_infinity-Y_rho) -> W') | |
| def main(): | |
| parser=argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--out',type=Path,default=Path(__file__).resolve().parents[1]/'results/universality.json') | |
| args=parser.parse_args() | |
| result=dict(status='PASS',frame_checks=frame_identity_checks(), | |
| boundary_checks=penalty_boundary_checks(), | |
| residual_gram_correction=residual_gram_correction_checks(), | |
| hypotheses='smooth prescribed A skew-Hermitian and V=C^dagger C; fixed finite interval; dark inlet and zero far-end trace') | |
| args.out.parent.mkdir(parents=True,exist_ok=True) | |
| args.out.write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8') | |
| print(json.dumps(dict(status='PASS',output=str(args.out), | |
| maximum_frame_error=max(result['frame_checks']['maximum_absolute_errors'].values()), | |
| final_penalty_error=result['boundary_checks']['penalty_rows'][-1]['relative_error_to_limit'], | |
| last_mesh_relative_change=result['boundary_checks']['last_mesh_relative_change']),indent=2)) | |
| if __name__=='__main__': | |
| main() | |