#!/usr/bin/env python3 """Certified all-film bounds for declared nonlinear, non-Lie-closed inputs. Synthetic mathematical examples only. Floating-point shooting proposes rational flux brackets. Integer outward matrix-exponential arithmetic verifies them; the global ceiling follows from affine coefficient comparison and the analytical minimax theorem, not from an unverified numerical search. """ from __future__ import annotations from dataclasses import dataclass from fractions import Fraction as F from pathlib import Path import csv,json,math import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt ROOT=Path(__file__).resolve().parent BITS=76;Q=1<Q: a=[[v.divint(2)for v in row]for row in a];nscale+=1 n=32 assert 2*F(1,2)**(n+1)/math.factorial(n+1)1e-14: s=math.sinh(math.sqrt(d)*x)/math.sqrt(d);co=math.cosh(math.sqrt(d)*x) elif d< -1e-14: s=math.sin(math.sqrt(-d)*x)/math.sqrt(-d);co=math.cos(math.sqrt(-d)*x) else:s=x;co=1. u=((co+s*b/2)*u+s*a)/(-s*c*u+co-s*b/2) return u def endpoint_interval(j,layers,rho): a,b,c=rho;u=I.f(0);jj=I.f(j);checks=[] for phase,h in layers: if phase=='A':u=u+jj*h;continue x=jj*h matrix=[[x*(b/2),x*a],[-x*c,-x*(b/2)]] # For EVERY time within the layer, ||exp(tM)-I|| <=2d if d<=1/2. # Thus q(t)>=1-2d max(1,u_start)>0. This rules out hidden Riccati poles. d=F(mnorm(matrix),Q);umax=max(F(1),F(u.hi,Q)) assert 2*d<=1 and 2*d*umax<1 and u.lo>=0 e=mexp(matrix) denominator=e[1][0]*u+e[1][1] assert denominator.lo>0 u=(e[0][0]*u+e[0][1])/denominator assert u.lo>=0 checks.append({'layer':str(h),'matrix_norm_upper':str(d),'pole_margin_lower':str(1-2*d*umax)}) return u,checks def certified_flux(layers,rho): a,b,c=rho # All six declared models and their affine envelopes are increasing on [0,U]. assert a>0 and b>=0 and c>=0 rmin=min(F(1),a);rmax=max(F(1),a+b*U+c*U*U) jmin=U/(L*rmax);jmax=U/(L*rmin) lo=float(jmin);hi=float(jmax) for _ in range(80): mid=(lo+hi)/2 if endpoint_float(mid,layers,rho)0 el,pl=endpoint_interval(jl,layers,rho);eh,ph=endpoint_interval(jh,layers,rho) if el.hi0 rho_max=rho[0]+rho[1]*U+rho[2]*U*U qA_min=F(3,4);qB_min=4-F(5,4)*rho_max assert qB_min>0 for sign in [1,-1]: lam=sign*F(7,4) layers=CENTRAL if sign>0 else SPLIT envelope_layers=layers actual=certified_flux(layers,rho);actual_r=ri(actual,lam) chosen=upper if sign>0 else lower envelope=certified_flux(layers,chosen);envelope_r=ri(envelope,lam) opposite=SPLIT if sign>0 else CENTRAL alternative=certified_flux(opposite,rho);alternative_r=ri(alternative,lam) # A nonlinear law need not retain the affine architecture ranking. # Select a concrete feasible lower witness after evaluating both. if alternative_r.lo>actual_r.lo: layers,opposite=opposite,layers actual,alternative=alternative,actual actual_r,alternative_r=alternative_r,actual_r # The upper proof ALWAYS uses the affine envelope's own optimizer, # which may be a different physical stack from the actual candidate. upper_bound=F(envelope_r.hi,Q);lower_bound=F(actual_r.lo,Q) assert lower_bound>0 and upper_bound>=F(actual_r.hi,Q) name='eps_'+str(eps).replace('/','_')+('_positive'if sign>0 else'_negative') rec={'name':name,'eps':str(eps),'potential_sign':sign,'Lambda':str(lam), 'rho':list(map(str,rho)),'rho_lower':list(map(str,lower)),'rho_upper':list(map(str,upper)), 'positive_qA_lower':str(qA_min),'positive_qB_lower':str(qB_min), 'candidate_architecture':'central'if layers==CENTRAL else'protected_split', 'affine_envelope_architecture':'central'if sign>0 else'protected_split', 'candidate_differs_from_affine_architecture':layers!=envelope_layers, 'candidate_stack':[[p,str(h)]for p,h in layers], 'actual_candidate_flux':actual,'actual_candidate_resistance':actual_r.fractions(), 'global_envelope':'upper_chord'if sign>0 else'lower_midpoint_tangent', 'global_envelope_stack':[[p,str(h)]for p,h in envelope_layers], 'global_envelope_flux':envelope,'global_envelope_resistance':envelope_r.fractions(), 'all_film_bracket':[str(lower_bound),str(upper_bound)], 'exact_relative_gap':str((upper_bound-lower_bound)/lower_bound), 'alternative_stack':[[p,str(h)]for p,h in opposite], 'alternative_flux':alternative,'alternative_resistance':alternative_r.fractions()} records.append(rec) rows.append({'name':name,'eps':float(eps),'sign':sign, 'candidate':rec['candidate_architecture'], 'affine_envelope_architecture':rec['affine_envelope_architecture'], 'ranking_reversal_certified':actual_r.lo>alternative_r.hi and layers!=envelope_layers, 'candidate_lower':float(lower_bound),'candidate_upper':actual_r.hi/Q, 'global_upper':float(upper_bound),'relative_global_gap':float((upper_bound-lower_bound)/lower_bound), 'alternative_resistance':(alternative_r.lo+alternative_r.hi)/(2*Q), 'candidate_flux_width':float(F(actual['J_upper'])-F(actual['J_lower']))}) family_trials=[] for arch,st in [('central',CENTRAL),('protected_split',SPLIT)]: scenario=[] for rec in records: field='actual_candidate_resistance'if rec['candidate_architecture']==arch else'alternative_resistance' scenario.append({'name':rec['name'],'resistance':rec[field]}) family_trials.append({'architecture':arch,'stack':[[p,str(h)]for p,h in st], 'scenario_responses':scenario, 'worst_interval':[str(min(F(s['resistance'][0])for s in scenario)), str(min(F(s['resistance'][1])for s in scenario))]}) family_choice=max(family_trials,key=lambda c:F(c['worst_interval'][0])) family_lower=F(family_choice['worst_interval'][0]) family_upper=min(F(rec['all_film_bracket'][1])for rec in records) assert family_lower>0 and family_upper>=F(family_choice['worst_interval'][1]) family={'operating_conditions':len(records),'humidity_orientations':2*len(records), 'candidate_trials':family_trials,'chosen_architecture':family_choice['architecture'], 'chosen_stack':family_choice['stack'], 'all_film_robust_bracket':[str(family_lower),str(family_upper)], 'exact_relative_gap':str((family_upper-family_lower)/family_lower), 'upper_bound_logic':'sup_F min_s R_s(F) <= min_s sup_F R_s(F); each upper is already all-film'} cert={'format':'Nuyori-VI nonlinear affine-envelope certificate v1','synthetic':True, 'fixed_point_bits':BITS,'inputs':{'L':str(L),'H_A':str(HA),'H_B':str(HB),'skin':str(SKIN), 'a_L':'0','a_H':'1','K_A':'1+a','G':'a+a^2/2','U':str(U), 'K_B':'K_A/rho(G)','phi_base':'1+2*u/3-4*u^2/9', 'q_A':'2+phi(G)','q_B':'4+rho(G)*phi(G)','C':str(C)},'cases':records, 'common_film_family':family} (ROOT/'certificate.json').write_text(json.dumps(cert,indent=2)+'\n') result={'status':'PASS: validated synthetic nonlinear all-film bounds','cases':len(rows), 'actual_water_not_Lie_closed':True,'both_oxygen_laws_nonconstant':True, 'global_affine_bounds_exact_algebra':True,'rows':rows, 'maximum_relative_gap':max(r['relative_global_gap']for r in rows), 'primary_eps_1_10_gaps':[r['relative_global_gap']for r in rows if r['eps']==.1], 'certified_departures_from_affine_candidate':[r['name']for r in rows if r['ranking_reversal_certified']], 'common_film_family':{'operating_conditions':len(records),'humidity_orientations':2*len(records), 'architecture':family_choice['architecture'],'worst_lower':float(family_lower), 'global_upper':float(family_upper),'relative_global_gap':float((family_upper-family_lower)/family_lower)}, 'limitations':['No measured material properties or superiority are established.', 'The true quadratic water law does not have the exact Lie-closed architecture theorem; affine comparison yields a certified gap, not exact optimality.', 'The oxygen potential identity is imposed in these inputs; residual envelopes are needed for other measured oxygen laws.', 'The midpoint tangent minimizes uniform paired envelope width, not necessarily the final flux or objective gap.', 'The feasible candidate is selected from central and protected-split stacks; it need not equal the affine envelope optimizer or the unknown actual global optimizer.', 'No interfacial cost, minimum layer thickness, swelling, lateral defects or transient transport is covered.']} (ROOT/'results.json').write_text(json.dumps(result,indent=2)+'\n') (ROOT/'verification_summary.txt').write_text(json.dumps(result,indent=2)+'\n') with (ROOT/'cases.csv').open('w',newline='')as f: w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows) fig,ax=plt.subplots(1,2,figsize=(10.4,3.7),layout='constrained') x=[1.5*j/200 for j in range(201)];eps=.1 ax[0].plot(x,[1+.5*v+eps*v*v for v in x],color='#117b85',label='Actual nonlinear ratio') ax[0].plot(x,[1+(.5+eps*1.5)*v for v in x],color='#b28a42',linestyle='--',label='Affine upper chord') ax[0].plot(x,[1-eps*1.5**2/4+(.5+eps*1.5)*v for v in x],color='#667d88',linestyle=':',label='Affine lower tangent') ax[0].set_xlabel('Water primitive u=G(a)');ax[0].set_ylabel('Water reciprocal ratio rho');ax[0].legend(fontsize=7) ax[0].set_title('Global coefficient enclosure, eps=0.1') for sign,col,label in [(1,'#117b85','Positive potential integral'),(-1,'#b28a42','Negative potential integral')]: rr=[r for r in rows if r['sign']==sign] ax[1].plot([r['eps']for r in rr],[100*r['relative_global_gap']for r in rr],'o-',color=col,label=label) ax[1].set_xlabel('Quadratic coefficient eps');ax[1].set_ylabel('Certified all-film relative gap (%)') ax[1].set_title('Actual finite film versus a global ceiling');ax[1].legend(fontsize=7) fig.suptitle('Synthetic smooth laws; exact oxygen identity and validated nonlinear fluxes',fontsize=10) fig.savefig(ROOT/'nonlinear_certificate.png',dpi=190);plt.close(fig) print(json.dumps({k:v for k,v in result.items()if k not in ['rows','limitations']},indent=2)) if __name__=='__main__':main()