Datasets:
Formats:
csv
Languages:
English
Size:
< 1K
Tags:
mathematics
homogenization
spectral-theory
variational-methods
matrix-analysis
scientific-computing
Download research/code/verify_twist.py from PureOne/EVE-QELTHA: direct link, hf CLI and curl.
- Browser
- Download file 7.03 kB
-
https://huggingface.co/datasets/PureOne/EVE-QELTHA/resolve/main/research/code/verify_twist.py
- Command line
-
hf download hf://datasets/PureOne/EVE-QELTHA/research/code/verify_twist.py
-
curl -L -o verify_twist.py https://huggingface.co/datasets/PureOne/EVE-QELTHA/resolve/main/research/code/verify_twist.py
7.03 kB
| #!/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 0<nu<1') | |
| return float(s*2**(1-2*nu)*gamma(1-nu)/gamma(nu)) | |
| def fem_capacity(eps, s=2.0, a=2.0, b=0.8, A=1.0, B=1.0, | |
| cells=4000, endpoint=6.0, quadrature=6, frame='rotating'): | |
| """Return full-model effective capacity and its rescaled value. | |
| t=eps**(1/s)*x; P=Rot(t**s-eps)*(bright,dark). | |
| Dividing energy by eps**((a+1)/s)/A gives the functional | |
| int t**(-a) |z'+s*t**(s-1)*J*z|**2 | |
| + A*B*eps**(-(a-b+2)/s)*t**(-b)*bright**2 dt. | |
| """ | |
| start = eps**(1/s) | |
| ts = np.geomspace(start, endpoint, cells+1) | |
| widths = np.diff(ts) | |
| points, weights = leggauss(quadrature) | |
| loc = np.zeros((cells,4,4)) | |
| penalty = A*B*eps**(-(a-b+2)/s) | |
| cached = [] | |
| for gp, gw in zip(points, weights): | |
| n1, n2 = (1-gp)/2, (1+gp)/2 | |
| tt = (ts[:-1]+ts[1:])/2 + widths*gp/2 | |
| kk = s*tt**(s-1) | |
| dp = 1/widths | |
| BB = np.zeros((cells,2,4)) | |
| if frame == 'rotating': | |
| BB[:,0,:] = np.stack((-dp, -kk*n1, dp, -kk*n2),axis=1) | |
| BB[:,1,:] = np.stack((kk*n1, -dp, kk*n2, dp),axis=1) | |
| CC = np.broadcast_to(np.array([n1,0,n2,0]),(cells,4)) | |
| elif frame == 'physical': | |
| BB[:,0,:] = np.stack((-dp,0*dp,dp,0*dp),axis=1) | |
| BB[:,1,:] = np.stack((0*dp,-dp,0*dp,dp),axis=1) | |
| theta=tt**s-eps | |
| ct,st=np.cos(theta),np.sin(theta) | |
| CC=np.stack((n1*ct,n1*st,n2*ct,n2*st),axis=1) | |
| else: | |
| raise ValueError('unknown frame') | |
| WW = widths*gw/2 | |
| loc += (WW*tt**(-a))[:,None,None]*np.einsum('nki,nkj->nij',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) | |