#!/usr/bin/env python3 """Independent Gaussian-quadrature FEM check of weak rank-one twist capacity. The original two-component pressure energy is discretized in a rotating basis. Six-point quadrature integrates derivative connection terms and the leakage penalty; no nodal or midpoint-only approximation of the rank-one sink is used. Boundary data: dark pressure 1 at the inlet, bright pressure free, zero pressure at a remote truncated endpoint. Results concern the stated reduced model. """ from pathlib import Path import argparse import json import numpy as np from scipy import sparse from scipy.sparse.linalg import spsolve from scipy.special import gamma from numpy.polynomial.legendre import leggauss def limit_constant(a, s): nu = (a + 1) / (2*s) if not 0 < nu < 1: raise ValueError('Supercritical formula requires 0nij',BB,BB) loc += (WW*penalty*tt**(-b))[:,None,None]*np.einsum('ni,nj->nij',CC,CC) cached.append((BB,CC,WW,tt)) ids = 2*np.arange(cells)[:,None]+np.arange(4)[None,:] rr = np.broadcast_to(ids[:,:,None],loc.shape).ravel() cc = np.broadcast_to(ids[:,None,:],loc.shape).ravel() size=2*(cells+1) mat=sparse.coo_matrix((loc.ravel(),(rr,cc)),shape=(size,size)).tocsr() # h(start)=1, u(start) free; final values both zero. fixed=np.array([1,size-2,size-1]) free=np.setdiff1d(np.arange(size),fixed,assume_unique=True) rhs=-mat[free,1].toarray().ravel() mm=mat[free,:][:,free].tocsc() diag=1/np.sqrt(mm.diagonal()) scale=sparse.diags(diag) zz=np.zeros(size) zz[1]=1 zz[free]=diag*spsolve(scale@mm@scale,diag*rhs) zloc=zz[ids] # Evaluate positive integrals directly, avoiding cancellation in z^T K z. derivative_energy=0.0 leakage_energy=0.0 for BB,CC,WW,tt in cached: dv=np.einsum('nki,ni->nk',BB,zloc) uv=np.einsum('ni,ni->n',zloc,CC) derivative_energy += np.dot(WW*tt**(-a),np.sum(dv*dv,axis=1)) leakage_energy += np.dot(WW*penalty*tt**(-b),uv*uv) scaled=derivative_energy+leakage_energy capacity=scaled*eps**((a+1)/s)/A residual=np.linalg.norm(mm@zz[free]-rhs)/max(np.linalg.norm(rhs),1.) return dict(epsilon=eps,s=s,a=a,b=b,A=A,B=B,cells=cells, endpoint=endpoint,scaled_capacity=float(scaled), capacity=float(capacity),impedance=float(1/capacity), scaled_derivative_energy=float(derivative_energy), scaled_leakage_energy=float(leakage_energy), relative_linear_residual=float(residual), bright_inlet_pressure=float(zz[0]),frame=frame) def run(output): rows=[] for s,endpoint in [(2.,6.),(3.,4.)]: target=limit_constant(2.,s) for eps in [1e-2,1e-3,1e-4,1e-5,1e-6]: row=fem_capacity(eps,s=s,cells=5000,endpoint=endpoint) row['limiting_constant']=target row['relative_error_to_limit']=abs(row['scaled_capacity']/target-1) rows.append(row) # Separate mesh and truncation checks at a fixed small epsilon. checks=[fem_capacity(1e-5,s=s,cells=nn,endpoint=endpoint) for nn in [2500,5000,10000]] trunc=fem_capacity(1e-5,s=s,cells=10000,endpoint=endpoint*1.25) relmesh=abs(checks[-1]['scaled_capacity']/checks[-2]['scaled_capacity']-1) reltail=abs(trunc['scaled_capacity']/checks[-1]['scaled_capacity']-1) assert relmesh < 3e-4, ('mesh',s,relmesh) assert reltail < 3e-4, ('tail',s,reltail) for row in checks: row['kind']='mesh_check' rows.append(row) trunc['kind']='truncation_check' rows.append(trunc) assert rows[-5]['relative_error_to_limit'] < .015 # Different discretization in the original, fixed laboratory coordinates. # Agreement here checks the connection signs and sink rotation independently. physical=fem_capacity(1e-3,s=3.,cells=12000,endpoint=4.,frame='physical') rotating=fem_capacity(1e-3,s=3.,cells=12000,endpoint=4.,frame='rotating') relframe=abs(physical['capacity']/rotating['capacity']-1) assert relframe < 3e-6, ('independent physical-frame check',relframe) for row in [physical,rotating]: row['kind']='independent_frame_check' rows.append(row) for AA,BB in [(0.5,0.25),(2.,5.),(3.,0.1)]: row=fem_capacity(1e-6,s=3.,A=AA,B=BB,cells=6000,endpoint=4.) row['kind']='coefficient_check' row['limiting_constant']=3. row['relative_error_to_limit']=abs(row['scaled_capacity']/3.-1) assert row['relative_error_to_limit'] < 5e-4 rows.append(row) result={'model':'two-component rank-one rotating drainage, six-point FEM', 'status':'passed','rows':rows, 'independent_frame_relative_difference':relframe, 'scope':'supercritical s=2,3 only; numerical confirmation is not proof'} output=Path(output) output.parent.mkdir(parents=True,exist_ok=True) output.write_text(json.dumps(result,indent=2)+'\n') print(json.dumps({'status':'passed','output':str(output),'rows':len(rows), 'independent_frame_relative_difference':relframe, 'last_coefficient_check':rows[-1]},indent=2)) return result if __name__=='__main__': parser=argparse.ArgumentParser() parser.add_argument('--output',default=str(Path(__file__).resolve().parents[1]/'results'/'twist.json')) args=parser.parse_args() run(args.output)