File size: 8,972 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
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
"""Two-resource Maxwell rectangle: explicit symmetric canonical programs.

Physical coefficients are a=1/epsilon, b=k^2/mu in fixed canonical units.
This floating evaluator computes candidates and phase windings, not certified
interval decisions at degenerate band edges or exact branch ties.
"""
from __future__ import annotations
from dataclasses import dataclass
import math
import numpy as np
from scipy.integrate import quad
from maxwell_rectangle import Rectangle,generator_transfer,phase_speed
from resource_floquet import lifted_phase_map,resource_optimum
from floquet import log_spectral_radius

@dataclass(frozen=True)
class MaxwellResourceCell:
    period:float
    mean_a:float
    mean_b:float
    log_gain:float
    # (a,b,duration), chronological; possible first/last identical pieces allowed
    states:tuple


def quadratic_roots(A:float,C:float)->list[float]:
    """Zeros of sin(theta)cos(theta)+A cos^2(theta)-C sin^2(theta)."""
    offset=(A-C)/2;cc=(A+C)/2;ss=.5
    amp=math.hypot(cc,ss);target=-offset/amp
    if abs(target)>1:return []
    phi=math.atan2(ss,cc);z=math.acos(max(-1.,min(1.,target)))
    return sorted({((phi+z)%(2*math.pi))/2,((phi-z)%(2*math.pi))/2})


def calibrated_resource_cell(box:Rectangle,eta:float,xi:float,zeta:float)->MaxwellResourceCell:
    """Produce the exact-formula corner selector for any finite three duals."""
    am,ap,bm,bp=box.amin,box.amax,box.bmin,box.bmax
    if eta>0:forms=[(xi,zeta+eta/bp),(xi+eta/ap,zeta)]
    elif eta<0:forms=[(xi+eta/am,zeta),(xi,zeta+eta/bm)]
    else:forms=[(xi,zeta)]
    cuts=sorted([0.,math.pi]+[t for A,C in forms for t in quadratic_roots(A,C) if 1e-12<t<math.pi-1e-12])
    cuts=[t for i,t in enumerate(cuts) if i==0 or t-cuts[i-1]>1e-12]
    states=[];T=0.;Ua=0.;Ub=0.;G=0.
    for left,right in zip(cuts[:-1],cuts[1:]):
        th=(left+right)/2;c,s=math.cos(th),math.sin(th);K=s*c+xi*c*c-zeta*s*s
        if eta>0:
            a,b=(am,bp) if K>eta*s*s/bp else ((ap,bm) if K < -eta*c*c/ap else (ap,bp))
        elif eta<0:
            a,b=(am,bp) if K> -eta*c*c/am else ((ap,bm) if K<eta*s*s/bm else (am,bm))
        else:a,b=(am,bp) if K>0 else (ap,bm)
        duration=quad(lambda theta:1/phase_speed(theta,a,b),left,right,epsabs=1e-13)[0]
        gain=.5*math.log(phase_speed(left,a,b)/phase_speed(right,a,b))
        if states and states[-1][:2]==(a,b):
            a0,b0,t0=states[-1];states[-1]=(a0,b0,t0+duration)
        else:states.append((a,b,duration))
        T+=duration;Ua+=a*duration;Ub+=b*duration;G+=gain
    return MaxwellResourceCell(T,Ua/T,Ub/T,G,tuple(states))


def explicit_resource_cell(box:Rectangle,tau:float,mean_a:float,mean_b:float)->MaxwellResourceCell:
    """The unique positive one-turn equality architecture, when hyperbolic.

    Feasibility as a *one-turn* extremal candidate must still be checked with
    cell_winding. For endpoint means use the lower-dimensional scalar theorem.
    """
    am,ap,bm,bp=box.amin,box.amax,box.bmin,box.bmax
    if not (ap>am and bp>bm and am<mean_a<ap and bm<mean_b<bp and tau>0):
        raise ValueError('Strict rectangle, positive period, and interior means required.')
    p=(mean_a-am)/(ap-am);q=(mean_b-bm)/(bp-bm);w=p+q-1
    if w>0:
        h=(1-p)*tau;v=(1-q)*tau;d=w*tau/2;diag=(ap,bp)
    elif w<0:
        h=q*tau;v=p*tau;d=-w*tau/2;diag=(am,bm)
    else:
        h=q*tau;v=p*tau;d=0.;diag=(am,bm)
    states=[(am,bp,h)]
    if d:states.append((*diag,d))
    states.append((ap,bm,v))
    if d:states.append((*diag,d))
    M=np.eye(2)
    for a,b,t in states:M=generator_transfer(a,b,t)@M
    return MaxwellResourceCell(tau,mean_a,mean_b,log_spectral_radius(M),tuple(states))


def resource_cell_monodromy(cell:MaxwellResourceCell)->np.ndarray:
    M=np.eye(2)
    for a,b,t in cell.states:M=generator_transfer(a,b,t)@M
    return M


def cell_winding(cell:MaxwellResourceCell)->int:
    """Expanding eigenline winding; return zero for nonhyperbolic cells."""
    M=resource_cell_monodromy(cell)
    if abs(float(np.trace(M)))/2<=1:return 0
    vals,vecs=np.linalg.eig(M);x=np.real(vecs[:,np.argmax(np.abs(vals))])
    theta=math.atan2(-x[1],x[0]);start=theta
    for a,b,t in cell.states:
        w=math.sqrt(b/a)
        psi=lifted_phase_map(theta,w)+math.sqrt(a*b)*t
        theta=lifted_phase_map(psi,w,True)
    n=round((theta-start)/math.pi)
    if abs(theta-start-n*math.pi)>1e-7:raise ArithmeticError('Unresolved eigenline winding.')
    return n


def rectangle_resource_optimum(box:Rectangle,S:float,mean_a:float,mean_b:float):
    if not all(map(math.isfinite,(S,mean_a,mean_b))) or S<=0:
        raise ValueError('Finite means and positive finite period required.')
    am,ap,bm,bp=box.amin,box.amax,box.bmin,box.bmax
    if not (am<=mean_a<=ap and bm<=mean_b<=bp):
        raise ValueError('Resource means lie outside the material bounds.')
    fixed_a=mean_a in (am,ap);fixed_b=mean_b in (bm,bp)
    if fixed_a and fixed_b:return 0.,[]
    if fixed_a or fixed_b:
        if fixed_a:
            scale=math.sqrt(mean_a*bm);R=math.sqrt(bp/bm);m=mean_b/bm
        else:
            scale=math.sqrt(bm*am) if mean_b==bm else math.sqrt(mean_b*am)
            R=math.sqrt(ap/am);m=mean_a/am
        value,scalar=resource_optimum(R,scale*S,m)
        out=[]
        for c in scalar:
            h,ell=c.high_time/scale,c.low_time/scale
            states=((mean_a,bp,h),(mean_a,bm,ell)) if fixed_a else ((ap,mean_b,h),(am,mean_b,ell))
            out.append((c.winding,MaxwellResourceCell(S/c.winding,mean_a,mean_b,c.log_gain/c.winding,states)))
        return value,out
    slow=math.sqrt(am*bm);fast=math.sqrt(ap*bp)
    candidates=[]
    for n in range(1,math.floor(fast*S/math.pi)+1):
        tau=S/n
        if not math.pi/fast<tau<math.pi/slow:continue
        cell=explicit_resource_cell(box,tau,mean_a,mean_b)
        if cell.log_gain>0 and cell_winding(cell)==1:candidates.append((n,cell))
    return max((n*c.log_gain for n,c in candidates),default=0.),candidates


def resource_dual_parameters(box:Rectangle,cell:MaxwellResourceCell):
    """Recover the unique normal certificate from a positive one-turn cell.

    Switch equations are solved linearly. Floating residuals must not be read as
    interval-certified decisions arbitrarily close to a degenerate band edge.
    """
    if cell.log_gain<=0 or cell_winding(cell)!=1:
        raise ValueError('A positive one-turn cell is required.')
    M=resource_cell_monodromy(cell)
    vals,vecs=np.linalg.eig(M);x=np.real(vecs[:,np.argmax(np.abs(vals))])
    theta=math.atan2(-x[1],x[0]);start=theta
    rows=[];rhs=[];switches=[]
    for i,(a,b,t) in enumerate(cell.states):
        w=math.sqrt(b/a)
        theta=lifted_phase_map(lifted_phase_map(theta,w)+math.sqrt(a*b)*t,w,True)
        aa,bb,_=cell.states[(i+1)%len(cell.states)]
        c,s=math.cos(theta),math.sin(theta)
        v=b*c*c+a*s*s;vv=bb*c*c+aa*s*s
        f=(b-a)*s*c;ff=(bb-aa)*s*c
        rows.append([1/v-1/vv,a/v-aa/vv,b/v-bb/vv]);rhs.append(f/v-ff/vv)
        switches.append(theta)
    if len(cell.states)==2:
        rows.append([1.,0.,0.]);rhs.append(0.)
    A=np.array(rows);y=np.array(rhs)
    dual,_,rank,_=np.linalg.lstsq(A,y,rcond=None)
    if rank<3:raise ArithmeticError('Unresolved dual rank; use higher precision.')
    return tuple(float(z) for z in dual),float(np.max(np.abs(A@dual-y))),tuple(switches)


def rectangle_resource_gap_interval(box:Rectangle,mean_a:float,mean_b:float):
    """First one-turn resource gap via the proved connected feasible interval.

    Binary search is on hyperbolicity plus winding, not on an assumed monotone
    trace. Endpoint values are floating approximations, not exact tie decisions.
    """
    tau0=math.pi/math.sqrt(mean_a*mean_b)
    central=explicit_resource_cell(box,tau0,mean_a,mean_b)
    if central.log_gain<=0 or cell_winding(central)!=1:
        raise ArithmeticError('Central resource gap unresolved at this precision.')
    def inside(t):
        c=explicit_resource_cell(box,t,mean_a,mean_b)
        return c.log_gain>0 and cell_winding(c)==1
    lo=math.pi/math.sqrt(box.amax*box.bmax);hi=tau0
    for _ in range(55):
        mid=(lo+hi)/2
        if inside(mid):hi=mid
        else:lo=mid
    left=(lo+hi)/2
    lo=tau0;hi=math.pi/math.sqrt(box.amin*box.bmin)
    for _ in range(55):
        mid=(lo+hi)/2
        if inside(mid):lo=mid
        else:hi=mid
    return left,(lo+hi)/2


def rectangle_resource_free(box:Rectangle,mean_a:float,mean_b:float):
    """Numerically evaluate the unique two-resource free-period maximum."""
    from scipy.optimize import minimize_scalar
    lo,hi=rectangle_resource_gap_interval(box,mean_a,mean_b)
    cut=(hi-lo)*1e-7
    def objective(t):return -explicit_resource_cell(box,t,mean_a,mean_b).log_gain/t
    result=minimize_scalar(objective,bounds=(lo+cut,hi-cut),method='bounded',options={'xatol':1e-13})
    if not result.success:raise ArithmeticError(result.message)
    return explicit_resource_cell(box,float(result.x),mean_a,mean_b)