Download code/maxwell_resource.py from PureOne/eve-floquet-defect-rigidity: direct link, hf CLI and curl.
- Browser
- Download file 8.97 kB
-
https://huggingface.co/datasets/PureOne/eve-floquet-defect-rigidity/resolve/main/code/maxwell_resource.py
- Command line
-
hf download hf://datasets/PureOne/eve-floquet-defect-rigidity/code/maxwell_resource.py
-
curl -L -o maxwell_resource.py https://huggingface.co/datasets/PureOne/eve-floquet-defect-rigidity/resolve/main/code/maxwell_resource.py
8.97 kB
| """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 | |
| 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) | |