File size: 9,103 Bytes
ee2ebbb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Validated exact interface frontier for a synthetic nonseparable film model.

The continuum upper certificate is analytical. All numerical root signs use
outward integer Taylor enclosures. No measured polymer properties are used.
"""
from __future__ import annotations
from dataclasses import dataclass
from fractions import Fraction as F
from pathlib import Path
from collections import Counter
import json,math,csv
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

ROOT=Path(__file__).resolve().parent
BITS=160;Q=1<<BITS
def ceildiv(a,b):return -((-a)//b)
@dataclass(frozen=True)
class I:
    lo:int;hi:int
    @staticmethod
    def f(v):
        v=F(v);return I(v.numerator*Q//v.denominator,ceildiv(v.numerator*Q,v.denominator))
    def __add__(self,o):
        if not isinstance(o,I):o=I.f(o)
        return I(self.lo+o.lo,self.hi+o.hi)
    __radd__=__add__
    def __neg__(self):return I(-self.hi,-self.lo)
    def __sub__(self,o):return self+(-o if isinstance(o,I) else -I.f(o))
    def __rsub__(self,o):return I.f(o)+(-self)
    def __mul__(self,o):
        if not isinstance(o,I):o=I.f(o)
        z=[self.lo*o.lo,self.lo*o.hi,self.hi*o.lo,self.hi*o.hi]
        return I(min(z)//Q,ceildiv(max(z),Q))
    __rmul__=__mul__
    def divint(self,n):return I(self.lo//n,ceildiv(self.hi,n))

def expi(x):
    steps=0
    while max(abs(x.lo),abs(x.hi))*2>Q:x=x.divint(2);steps+=1
    n=48
    assert 2*F(1,2)**(n+1)/math.factorial(n+1)<F(1,Q)
    term=I.f(1);ans=term
    for k in range(1,n+1):term=(term*x).divint(k);ans=ans+term
    ans=I(ans.lo-1,ans.hi+1)
    for _ in range(steps):ans=ans*ans
    return ans
def sinhi(x):return (expi(x)-expi(-x)).divint(2)
def coshi(x):return (expi(x)+expi(-x)).divint(2)
def asfr(x):return [str(F(x.lo,Q)),str(F(x.hi,Q))]

L=F(1);H=F(1,20);K=F(4,5);DELTA=F(1);LAM=F(-1);C=F(3)
M=L-4*H
NS=[1,2,4,5,8,16,41,128]

def layer_stack(n):
    if F(n)<=L/(4*H):
        b=L/(4*n);out=[('A',b)]
        for j in range(n):
            out.append(('B',2*b))
            out.append(('A',b if j==n-1 else 2*b))
        return out,'low',b
    a=M/(4*(n-1));out=[('A',H),('B',H+a)]
    for _ in range(n-2):out.extend([('A',2*a),('B',2*a)])
    out.extend([('A',2*a),('B',H+a),('A',H)])
    return out,'high',a

def F_interval(j,n=None):
    j=I.f(j)
    if n is None:return (4/K)*sinhi(K*H*j)+M*j
    if F(n)<=L/(4*H):return (4*n/K)*sinhi(K*(L/(4*n))*j)
    a=M/(4*(n-1));return (4/K)*(sinhi(K*H*j)+(n-1)*sinhi(K*a*j))

def bracket(n=None):
    lo=F(0);hi=DELTA/L
    assert F_interval(lo,n).hi<DELTA*Q<F_interval(hi,n).lo
    for _ in range(96):
        mid=(lo+hi)/2;v=F_interval(mid,n)
        if v.hi<DELTA*Q:lo=mid
        elif v.lo>DELTA*Q:hi=mid
        else:
            # F' >= L for every branch, so ambiguity already gives a tiny
            # exact enclosure rather than requiring an equality decision.
            e=max(DELTA-F(v.lo,Q),F(v.hi,Q)-DELTA)/L
            lo=max(lo,mid-e);hi=min(hi,mid+e);break
    assert lo>0 and F_interval(lo,n).hi<DELTA*Q<F_interval(hi,n).lo
    return lo,hi

def resistance(br):
    lo,hi=br
    assert LAM<0
    return C+LAM*DELTA/lo,C+LAM*DELTA/hi

def occupation(stack):
    q=F(0);coef=Counter();qpoints=[q]
    for phase,h in stack:
        qq=q+(K if phase=='B' else -K)*h
        coef[max(q,qq)]+=1;coef[min(q,qq)]-=1
        q=qq;qpoints.append(q)
    assert q==0
    return sorted((x,c) for x,c in coef.items() if c),qpoints

def main():
    infj=bracket();infr=resistance(infj)
    ji=I(I.f(infj[0]).lo,I.f(infj[1]).hi)
    fp=4*H*coshi(K*H*ji)+M
    # Interval for the exact asymptotic leading constant.
    num=(-LAM*DELTA)*K*K*M*M*M
    astar_lo=num*infj[0]/(96*F(fp.hi,Q));astar_hi=num*infj[1]/(96*F(fp.lo,Q))
    cases=[];rows=[]
    for n in NS:
        st,branch,scale=layer_stack(n)
        assert len(st)==2*n+1
        assert sum((h for _,h in st),F(0))==L
        assert all(sum((h for p,h in st if p==phase),F(0))==L/2 for phase in ['A','B'])
        assert st==st[::-1] and st[0][1]>=H
        occ,qp=occupation(st)
        br=bracket(n);rr=resistance(br)
        gap=(infr[0]-rr[1],infr[1]-rr[0]);assert gap[0]>0
        scaled=((n-1)**2*gap[0],(n-1)**2*gap[1])
        case={'n_B_layers':n,'interfaces':2*n,'layers':2*n+1,'branch':branch,'scale':str(scale),
              'stack':[[p,str(h)] for p,h in st],'occupation_coefficients':[[str(q),v] for q,v in occ],
              'Q_extrema':[str(x) for x in qp],'flux_interval':list(map(str,br)),
              'resistance_interval':list(map(str,rr)),'unrestricted_regret_interval':list(map(str,gap)),
              'scaled_regret_interval':list(map(str,scaled))}
        cases.append(case)
        rows.append({'n_B_layers':n,'interfaces':2*n,'layers':2*n+1,'branch':branch,
          'flux_lower':float(br[0]),'flux_upper':float(br[1]),'resistance_lower':float(rr[0]),
          'resistance_upper':float(rr[1]),'regret_upper':float(gap[1]),'scaled_regret':float(sum(scaled)/2)})
    floor=F(1,100);nmax=math.floor(1+M/(2*floor));assert nmax==41
    st,_,_=layer_stack(nmax);assert min(h for _,h in st)>=floor
    cert={'format':'Nuyori VI exact finite-interface frontier v1','synthetic':True,'fixed_point_bits':BITS,
      'inputs':{'L':str(L),'H_A':str(L/2),'H_B':str(L/2),'skin':str(H),'kappa':str(K),
        'a_L':'0','a_H':str(DELTA),'alpha_A':'3','alpha_B':'3','psi':'-1','Lambda':str(LAM*DELTA),
        'r_A':'1-kappa*a','r_B':'1+kappa*a','q_A':'2+kappa*a','q_B':'2-kappa*a'},
      'unrestricted':{'flux_interval':list(map(str,infj)),'resistance_interval':list(map(str,infr)),
          'attained_by_pure_film':False,'asymptotic_constant_interval':[str(astar_lo),str(astar_hi)]},
      'cases':cases,'minimum_thickness':{'floor':str(floor),'n_max':nmax,'layers':2*nmax+1,'interfaces':2*nmax,
          'minimum_actual_layer':str(min(h for _,h in st))}}
    (ROOT/'certificate.json').write_text(json.dumps(cert,indent=2)+'\n')
    with (ROOT/'minimum_thickness_layers.csv').open('w',newline='') as f:
        w=csv.writer(f);w.writerow(['layer','phase','start_depth','end_depth','thickness','relative_thickness'])
        y=F(0)
        for idx,(phase,thick) in enumerate(st,1):
            w.writerow([idx,phase,str(y),str(y+thick),str(thick),str(thick/L)]);y+=thick
    result={'status':'PASS: exact analytic global frontier with validated synthetic root intervals',
      'synthetic':True,'finite_interface_cases':len(cases),'nonattainment_for_any_pure_measurable_film':True,
      'unrestricted_flux_interval':[float(x) for x in infj],'unrestricted_resistance_interval':[float(x) for x in infr],
      'asymptotic_constant_interval':[float(astar_lo),float(astar_hi)],'cases':rows,
      'minimum_thickness':{'floor':float(floor),'n_max':nmax,'layers':2*nmax+1,'interfaces':2*nmax,
        'resistance_interval':[float(x) for x in map(F,cases[NS.index(nmax)]['resistance_interval'])]},
      'limitations':['Synthetic ideal 1D model; no manufactured polymer claim.',
       'Exact frontier applies to equal inventories, opposing affine reciprocal water slopes, potential-compatible oxygen laws and the stated A skins.',
       'Unrestricted optimum is a supremum and requires a relaxed mixing limit, not a finite pure film.',
       'The numerical minimum-layer example has d<=h; the general theorem uses h_eff=max(h,d).']}
    (ROOT/'results.json').write_text(json.dumps(result,indent=2)+'\n')
    with (ROOT/'frontier.csv').open('w',newline='') as f:
        w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
    fig,axs=plt.subplots(1,3,figsize=(12.3,3.7),layout='constrained')
    xs=[r['interfaces'] for r in rows];gaps=[r['regret_upper'] for r in rows]
    axs[0].loglog(xs,gaps,'o-',color='#117b85',label='Exact global finite-interface gap')
    axs[0].set_xlabel('Maximum physical interfaces');axs[0].set_ylabel('Gap to unrestricted supremum')
    axs[0].set_title('Manufacturing frontier');axs[0].grid(alpha=.2)
    sel=[r for r in rows if r['n_B_layers']>1]
    axs[1].semilogx([r['n_B_layers']-1 for r in sel],[r['scaled_regret'] for r in sel],'o-',color='#117b85')
    axs[1].axhline(float((astar_lo+astar_hi)/2),color='#b18b31',linestyle='--',label='Proved leading constant')
    axs[1].set_xlabel('n - 1');axs[1].set_ylabel('(n - 1)^2 × gap');axs[1].set_title('Sharp inverse-square law');axs[1].legend(fontsize=7);axs[1].grid(alpha=.2)
    y=0.
    for phase,h in st:
        axs[2].barh(0,float(h),left=y,height=.5,color='#173c49' if phase=='A' else '#d4b35b');y+=float(h)
    axs[2].set_xlim(0,float(L));axs[2].set_ylim(-.6,.6);axs[2].set_yticks([]);axs[2].set_xlabel('Physical depth / total thickness')
    axs[2].set_title('1% minimum layer: 83-layer optimum')
    fig.suptitle('Synthetic exact model: interface count and layer thickness are explicit constraints',fontsize=10)
    fig.savefig(ROOT/'frontier.png',dpi=190);plt.close(fig)
    (ROOT/'verification_summary.txt').write_text(json.dumps(result,indent=2)+'\n')
    print(json.dumps({k:v for k,v in result.items() if k not in ['cases','limitations']},indent=2))

if __name__=='__main__':main()