File size: 6,788 Bytes
9755170
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reproducible adversarial checks. Run: python code/verify.py

These finite tests corroborate the proofs; they are neither formal
verification nor a novelty/priority audit.
"""
from __future__ import annotations
import json, math, platform, sys
from pathlib import Path
from dataclasses import asdict
import numpy as np
import scipy
import sympy as sp
from scipy.integrate import quad
from floquet import (fixed_period, free_period, monodromy, log_spectral_radius,
                     cell_gain, transfer, solve_eta, defect_integrand)
from exact_inverse import (layer_product, moments, recover_exponential_polynomial,
                           peel_first_row)


def lifted_angle(psi, w):
    n = math.floor((psi + math.pi/2)/math.pi)
    p = psi - n*math.pi
    return math.atan(w*math.tan(p)) + n*math.pi


def phase_segments(us, ts, M):
    vals, vecs = np.linalg.eig(M)
    j = int(np.argmax(np.abs(vals)))
    x = np.real(vecs[:, j]).astype(float)
    theta = math.atan2(-x[1], x[0])
    initial = theta
    out = []
    for u, duration in zip(us, ts):
        w = math.sqrt(u)
        psi = math.atan2(-x[1]/w, x[0])
        nxt = theta + lifted_angle(psi+w*duration, w) - lifted_angle(psi, w)
        out.append((theta, nxt, float(u)))
        x = transfer(float(u), float(duration)) @ x
        x /= np.linalg.norm(x)
        theta = nxt
    n = round((theta-initial)/math.pi)
    assert abs(theta-initial-n*math.pi) < 2e-8
    return out, n


def integrate_defect(segments, eta, R):
    value = 0.0
    for left, right, u in segments:
        points = []
        for base in [math.pi/2, -math.atan(eta)]:
            for j in range(math.floor((left-base)/math.pi)-1,
                           math.ceil((right-base)/math.pi)+2):
                z = base+j*math.pi
                if left < z < right:
                    points.append(z)
        value += quad(lambda th: defect_integrand(th,u,eta,R), left, right,
                      points=sorted(set(points)), epsabs=2e-10, epsrel=2e-10,
                      limit=250)[0]
    return value


def main():
    rng = np.random.default_rng(240925)
    random_count = 0
    hyperbolic_count = 0
    worst_excess = -math.inf
    defect_cases = []
    for R in [1.1, 1.5, 2.0, 3.0, 5.0]:
        for S in np.linspace(0.3,9.0,22):
            optimum, candidates = fixed_period(R, float(S))
            for j in range(60):
                r = int(rng.integers(1,17))
                us = (rng.choice([1.,R*R],size=r) if j%2 == 0
                      else rng.uniform(1.,R*R,size=r))
                ts = rng.dirichlet(np.ones(r))*S
                M = monodromy(us,ts)
                L = log_spectral_radius(M)
                random_count += 1
                worst_excess = max(worst_excess,L-optimum)
                assert L <= optimum+1e-9, (R,S,us,ts,L,optimum)
                if L > 1e-5:
                    hyperbolic_count += 1
                    if len(defect_cases) < 60:
                        defect_cases.append((R,float(S),us,ts,M,L))
    defect_error = 0.0
    for R,S,us,ts,M,L in defect_cases:
        segments,n = phase_segments(us,ts,M)
        eta = solve_eta(R,S/n)
        exact = n*cell_gain(R,eta)-L
        computed = integrate_defect(segments,eta,R)
        defect_error = max(defect_error,abs(exact-computed))
        assert abs(exact-computed) < 1e-7
    canonical_count = 0
    canonical_error = 0.0
    for R in [1.1,1.5,2.,3.,5.]:
        for S in np.linspace(0.25,6,40):
            bound,candidates = fixed_period(R,float(S))
            for c in candidates:
                M=monodromy([R*R,1.]*c.winding,[c.high_time,c.low_time]*c.winding)
                err=abs(log_spectral_radius(M)-c.log_gain)
                canonical_error=max(canonical_error,err)
                assert err<1e-9
                canonical_count += 1
    free = {str(R): asdict(free_period(R)) for R in [1.1,2.,3.,5.,10.]}
    sharp = []
    R=2.; S=3*math.pi/4
    for s in [0.02,0.01,0.005,0.0025]:
        M=monodromy([4.,1.],[math.pi/4+s,math.pi/2-s])
        deficit=math.log(2)-log_spectral_radius(M)
        ratio=deficit/s**2
        sharp.append({'s':s,'deficit':deficit,'deficit_over_s_squared':ratio})
        assert abs(ratio-1.5)<0.002
    # Exact signed-frequency identity for the all-discriminant counterexample.
    A=[(sp.Rational(4),sp.Rational(1,2)),(sp.Rational(2),sp.Rational(1,2))]
    B=[(sp.Rational(5,2),sp.Rational(4,5)),(sp.Rational(5),sp.Rational(1,5))]
    from exact_inverse import add, scaled
    HA,HB=layer_product(A),layer_product(B)
    assert scaled(add(HA[0][0],HA[1][1]),sp.Rational(1,2)) == \
           scaled(add(HB[0][0],HB[1][1]),sp.Rational(1,2))
    assert HA[0] != HB[0]
    # Includes collisions of signed optical-duration sums.
    datasets = [
        [(sp.Rational(2),sp.Rational(3,7))],
        A, B,
        [(sp.Rational(2),sp.Rational(1,5)),(sp.Rational(3),sp.Rational(2,7)),
         (sp.Rational(5),sp.Rational(3,11))],
        [(sp.Rational(2),sp.Rational(1,2)),(sp.Rational(3),sp.Rational(1,3)),
         (sp.Rational(4),sp.Rational(1,4)),(sp.Rational(5),sp.Rational(1,5))]
    ]
    inverse_results=[]
    for layers in datasets:
        r=len(layers); N=2**r
        H=layer_product(layers)
        f=recover_exponential_polynomial(moments(H[0][0],2*N),N)
        g=recover_exponential_polynomial(moments(H[0][1],2*N),N)
        assert f == H[0][0] and g == H[0][1]
        result=peel_first_row(f,g,r)
        assert result == layers,(layers,result)
        inverse_results.append({'r':r,'first_row_terms':[len(f),len(g)],
                                'recovered_layers':[[str(c),str(t)] for c,t in result],
                                'exact':True})
    report={
        'seed':240925,'random_profiles_tested':random_count,
        'hyperbolic_random_profiles':hyperbolic_count,
        'maximum_random_bound_violation':max(0.,worst_excess),
        'canonical_profiles_tested':canonical_count,
        'maximum_canonical_gain_error':canonical_error,
        'defect_identities_tested':len(defect_cases),
        'maximum_defect_identity_error':defect_error,
        'free_period_examples':free,'sharpness_examples':sharp,
        'exact_inverse_roundtrips':inverse_results,
        'exact_discriminant_counterexample_passed':True,
        'all_assertions_passed':True,
        'python':platform.python_version(),'numpy':np.__version__,
        'scipy':scipy.__version__,'sympy':sp.__version__,
        'scope':'Finite computational tests; not formal verification or peer review.'
    }
    path=Path(__file__).resolve().parents[1]/'results'/'verification.json'
    path.parent.mkdir(parents=True,exist_ok=True)
    path.write_text(json.dumps(report,indent=2)+'\n')
    print(json.dumps(report,indent=2))

if __name__ == '__main__':
    main()