File size: 13,218 Bytes
9427ec0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
#!/usr/bin/env python3
"""Critical rank-one-bright microstructure crossover: numerical verification.

The full three-component pressure problem has one bright direction and two
dark directions. Frequencies 2*pi*n and 4*pi*n are coupled by C_n=r_n S.
At rho=tau*n^2 the candidate/proved accompanying effective potential is
V_tau=S^dagger diag(tau/(tau+omega_j^2)) S, omega_j=2*pi*j.

Diagonal S uses the independently shipped exact constant-transfer algorithm.
Non-diagonal S uses time-dependent short-cell transfer integration and stable
Riccati composition, plus a separate Gaussian-quadrature Cartesian nodal FEM
in the rotating frame. The program checks implementations and limiting
behavior; it does not itself prove the asymptotic theorem or scientific novelty.
"""
from __future__ import annotations

import argparse
import importlib.util
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
from scipy.linalg import expm
from scipy.sparse.linalg import splu


LENGTH=1.0
OMEGA=2*np.pi*np.arange(1,3,dtype=float)
PI=np.diag([0.,0.,1.]).astype(complex)
DIAGONAL_S=np.diag(np.sqrt([.7,1.8])).astype(complex)
MIXED_S=np.array([[1.,.3],[.3,1.4]],dtype=complex)


def baseline_diagonal_solver():
    """Prefer the unchanged sibling verifier when the release bundles it.

    The embedded implementation below remains a self-contained fallback.
    No workspace-absolute or parent-release path is required.
    """
    filename=Path(__file__).parent/'verify_microstructure.py'
    if not filename.is_file():
        return diagonal_transfer_response
    spec=importlib.util.spec_from_file_location('critical_diagonal_baseline',filename)
    module=importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    spec.loader.exec_module(module)
    return module.full_admittance


def diagonal_transfer_response(n,rho,step_multiplier=1):
    """The read-only release3 constant-transfer algorithm, included locally.

    Keeping this short implementation here makes the verifier self-contained
    when the new release is extracted independently of release3.
    """
    cc=np.sqrt([.7,1.8])[None,:]
    base=np.block([[np.zeros((2,2)),-cc.T],[cc,np.zeros((1,1))]]).astype(complex)
    jj=base+np.diag(-2j*np.pi*n*np.array([1.,2.,0.]))
    op=np.block([[-jj,np.eye(3)],[rho*PI,-jj]])
    cells=step_multiplier*max(100,int(np.ceil(2*np.sqrt(rho))),int(np.ceil(4*np.pi*n)))
    tr=expm(op/cells)
    t11,t12,t21,t22=tr[:3,:3],tr[:3,3:],tr[3:,:3],tr[3:,3:]
    tail=np.linalg.solve(t12,t11)
    for _ in range(cells-1):
        tail=np.linalg.solve(t22+tail@t12,t21+tail@t11)
    response=tail[:2,:2]
    err=float(np.linalg.norm(response-response.conj().T))
    assert err<2e-8
    return (response+response.conj().T)/2,dict(exact_transfer_cells=cells,raw_hermitian_error=err)


def coupling(y,ss):
    row=np.exp(1j*OMEGA*y)[None,:]@ss
    return row


def frame_generator(y,ss):
    cc=coupling(y,ss)
    return np.block([[np.zeros((2,2),complex),-cc.conj().T],
                     [cc,np.zeros((1,1),complex)]])


def effective_potential(ss,tau):
    weights=tau/(tau+OMEGA**2)
    return ss.conj().T@np.diag(weights)@ss


def matrix_target_response(vv):
    ev,uu=np.linalg.eigh(vv)
    ev=np.maximum(0.,ev)
    root=np.sqrt(ev)
    response=np.ones_like(ev)/LENGTH
    np.divide(root,np.tanh(root*LENGTH),out=response,where=root>1e-14)
    return (uu*response[None,:])@uu.conj().T


def serialize_matrix(xx):
    return dict(real_part=xx.real.tolist(),imaginary_part=xx.imag.tolist(),
                eigenvalues=np.linalg.eigvalsh((xx+xx.conj().T)/2).tolist())


def periodic_transfer_response(ss,n,tau,refinement=1):
    """Full model, not the effective 2x2 equation.

    In y=n*x and scaled covariant momentum m=(z_x+K_n z)/n,
    z_y=m-K(y)z/n, m_y=tau*Pi*z-K(y)m/n. Short-cell transfers
    cover one period. Their exact Riccati action is repeated over n periods.
    """
    cells=refinement*max(40,int(np.ceil(4*np.sqrt(tau))))
    widths=1./cells
    transfers=[]
    omega_form=np.block([[np.zeros((3,3)),np.eye(3)],[-np.eye(3),np.zeros((3,3))]])
    max_symplectic=0.
    for j in range(cells):
        lo,hi=j*widths,(j+1)*widths
        def rhs(y,flat):
            kk=frame_generator(y,ss)/n
            op=np.block([[-kk,np.eye(3)],[tau*PI,-kk]])
            return (op@flat.reshape(6,6)).ravel()
        sol=solve_ivp(rhs,(lo,hi),np.eye(6,dtype=complex).ravel(),
                      method='DOP853',rtol=1.5e-12,atol=1e-13)
        if not sol.success:raise RuntimeError(sol.message)
        transfer=sol.y[:,-1].reshape(6,6)
        transfers.append(transfer)
        max_symplectic=max(max_symplectic,float(np.linalg.norm(transfer.conj().T@omega_form@transfer-omega_form)))
    last=transfers[-1]
    tail=np.linalg.solve(last[:3,3:],last[:3,:3])
    for index in range(n*cells-2,-1,-1):
        tr=transfers[index%cells]
        t11,t12,t21,t22=tr[:3,:3],tr[:3,3:],tr[3:,:3],tr[3:,3:]
        tail=np.linalg.solve(t22+tail@t12,t21+tail@t11)
    response=n*tail[:2,:2]
    hermitian=float(np.linalg.norm(response-response.conj().T))
    assert hermitian<2e-8,hermitian
    response=(response+response.conj().T)/2
    return response,dict(period_subcells=cells,total_riccati_cells=n*cells,
                         maximum_cell_symplectic_defect=max_symplectic,
                         raw_hermitian_error=hermitian)


def rotating_frame_fem(ss,n,tau,cells,quadrature=8):
    """Independent original-x energy FEM: ∫|z'+K_n z|²+rho|z_b|²."""
    dim=3;rho=tau*n*n;width=LENGTH/cells
    nodes=np.linspace(0,LENGTH,cells+1)
    pts,wts=leggauss(quadrature)
    local=np.zeros((cells,6,6),complex)
    identity=np.eye(3,dtype=complex)
    for gp,gw in zip(pts,wts):
        phi=np.array([(1-gp)/2,(1+gp)/2])
        locations=nodes[:-1]+width*(gp+1)/2
        kk=np.stack([frame_generator(n*x,ss) for x in locations])
        b1=-identity[None,:,:]/width+phi[0]*kk
        b2= identity[None,:,:]/width+phi[1]*kk
        bb=np.concatenate([b1,b2],axis=2)
        local+=(width*gw/2)*np.einsum('nki,nkj->nij',bb.conj(),bb)
        for a in range(2):
            for b in range(2):
                local[:,a*3:(a+1)*3,b*3:(b+1)*3]+=(width*gw/2)*rho*phi[a]*phi[b]*PI
    ids=3*np.arange(cells)[:,None]+np.arange(6)[None,:]
    rr=np.broadcast_to(ids[:,:,None],local.shape).ravel()
    cc=np.broadcast_to(ids[:,None,:],local.shape).ravel()
    matrix=sparse.coo_matrix((local.ravel(),(rr,cc)),shape=(3*(cells+1),3*(cells+1))).tocsc()
    boundary=np.arange(2)
    free=np.arange(3,3*cells)
    mff=matrix[free,:][:,free].tocsc()
    mfb=matrix[free,:][:,boundary].toarray()
    mbb=matrix[boundary,:][:,boundary].toarray()
    xx=splu(mff).solve(mfb)
    response=mbb-mfb.conj().T@xx
    residual=float(np.linalg.norm(mff@xx-mfb)/max(np.linalg.norm(mfb),1.))
    response=(response+response.conj().T)/2
    return response,residual


def run():
    diagonal_solver=baseline_diagonal_solver()
    cases=[]
    for label,ss in [('diagonal',DIAGONAL_S),('mixed',MIXED_S)]:
        for tau in (10.,40.,160.,640.):
            potential=effective_potential(ss,tau)
            target=matrix_target_response(potential)
            rows=[]
            for n in (4,8,16,32,64):
                if label=='diagonal':
                    response,metrics=diagonal_solver(n,tau*n*n)
                    method='exact constant-transfer baseline reused from release3, included locally'
                else:
                    response,metrics=periodic_transfer_response(ss,n,tau)
                    method='time-dependent periodic short-cell transfer and Riccati composition'
                error=float(np.linalg.norm(response-target)/np.linalg.norm(target))
                rows.append(dict(n=n,penalty=tau*n*n,relative_error_to_effective_response=error,
                                 response=serialize_matrix(response),solver_metrics=metrics))
            assert all(b['relative_error_to_effective_response']<a['relative_error_to_effective_response']
                       for a,b in zip(rows,rows[1:]))
            assert rows[-1]['relative_error_to_effective_response']<.01
            assert rows[-1]['relative_error_to_effective_response']<rows[0]['relative_error_to_effective_response']/8
            cases.append(dict(kind=label,coupling_matrix=serialize_matrix(ss),tau=tau,
                              effective_potential=serialize_matrix(potential),
                              effective_response=serialize_matrix(target),rows=rows,full_solver=method))
    v10=effective_potential(MIXED_S,10.)
    v640=effective_potential(MIXED_S,640.)
    noncommutator=float(np.linalg.norm(v10@v640-v640@v10))
    assert noncommutator>.001
    refinements=[]
    for label,ss in [('diagonal',DIAGONAL_S),('mixed',MIXED_S)]:
        if label=='diagonal':
            coarse,cm=diagonal_solver(64,640*64**2)
            fine,fm=diagonal_solver(64,640*64**2,step_multiplier=2)
        else:
            coarse,cm=periodic_transfer_response(ss,64,640.)
            fine,fm=periodic_transfer_response(ss,64,640.,refinement=2)
        change=float(np.linalg.norm(fine-coarse)/np.linalg.norm(fine))
        assert change<2e-8
        refinements.append(dict(kind=label,n=64,tau=640.,relative_response_change=change,
                                coarse_metrics=cm,fine_metrics=fm))
    reference,_=periodic_transfer_response(MIXED_S,4,40.)
    fem=[]
    for nn in (800,1600,3200):
        hh,res=rotating_frame_fem(MIXED_S,4,40.,nn)
        error=float(np.linalg.norm(hh-reference)/np.linalg.norm(reference))
        fem.append(dict(cells=nn,relative_error_to_periodic_transfer=error,linear_residual=res))
    assert fem[-1]['relative_error_to_periodic_transfer']<1e-5
    assert fem[-1]['relative_error_to_periodic_transfer']<fem[0]['relative_error_to_periodic_transfer']/10
    baseline,metrics=periodic_transfer_response(MIXED_S,16,0.)
    baseline_error=float(np.linalg.norm(baseline-np.eye(2))/np.sqrt(2))
    assert baseline_error<1e-9
    # Inverse design at a finite critical strength: compensate the filter.
    target_w=np.array([[1.1,.25+.12j],[.25-.12j,.8]],dtype=complex)
    vals,vecs=np.linalg.eigh(target_w)
    sqrt_w=(vecs*np.sqrt(vals)[None,:])@vecs.conj().T
    tau_c=40.
    weights=tau_c/(tau_c+OMEGA**2)
    factor=np.diag(1/np.sqrt(weights))@sqrt_w
    identity_error=float(np.linalg.norm(effective_potential(factor,tau_c)-target_w))
    assert identity_error<1e-12
    design_target=matrix_target_response(target_w)
    design_rows=[]
    for n in (8,16,32,64):
        response,metrics=periodic_transfer_response(factor,n,tau_c)
        error=float(np.linalg.norm(response-design_target)/np.linalg.norm(design_target))
        design_rows.append(dict(n=n,penalty=tau_c*n*n,relative_error_to_prescribed_response=error,
                                response=serialize_matrix(response),solver_metrics=metrics))
    assert all(b['relative_error_to_prescribed_response']<a['relative_error_to_prescribed_response']
               for a,b in zip(design_rows,design_rows[1:]))
    assert design_rows[-1]['relative_error_to_prescribed_response']<.01
    compensation=dict(tau=tau_c,prescribed_potential=serialize_matrix(target_w),
              factor_real_part=factor.real.tolist(),factor_imaginary_part=factor.imag.tolist(),
              effective_potential_identity_error=identity_error,
              prescribed_response=serialize_matrix(design_target),rows=design_rows)
    return dict(status='PASS',model='critical crossover, two dark directions and one bright direction',
                interval=[0,LENGTH],frequencies=OMEGA.tolist(),
                effective_potential_formula='S^dagger diag(tau/(tau+omega_j^2)) S',
                effective_boundary_response_formula='sqrt(V_tau)*coth(sqrt(V_tau)*L)',
                cases=cases,mixed_potential_commutator_norm_tau10_tau640=noncommutator,
                transfer_refinements=refinements,independent_mixed_frame_fem=fem,
                zero_penalty_baseline=dict(n=16,relative_error_to_free=baseline_error,metrics=metrics),
                finite_critical_compensation_design=compensation,
                interpretation='Observed convergence and solver consistency support the separately proved model theorem; these numerical tests do not establish scientific priority.')


def main():
    parser=argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--out',type=Path,default=Path(__file__).resolve().parents[1]/'results/critical.json')
    args=parser.parse_args()
    result=run()
    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=result['status'],output=str(args.out),
            mixed_noncommutator=result['mixed_potential_commutator_norm_tau10_tau640'],
            last_fem_error=result['independent_mixed_frame_fem'][-1]['relative_error_to_periodic_transfer'],
            last_errors=[dict(kind=c['kind'],tau=c['tau'],relative_error=c['rows'][-1]['relative_error_to_effective_response']) for c in result['cases']]),indent=2))


if __name__=='__main__':main()