Finite elements II: error estimates, adaptivity, nonlinearity and mixed problems
Study a priori and duality error estimates, high-order elements, residual estimators and adaptive refinement, then extend FEM to evolution, nonlinear Newton solves and mixed Stokes problems.
After this lesson you can
- Derive a priori H1 and L2 rates for degree-p elements using Aubin–Nitsche duality.
- Implement P2 elements and compare error against degrees of freedom with P1.
- Implement residual estimation and a solve–estimate–mark–refine loop with Dörfler marking.
- Solve a nonlinear solution-dependent diffusion PDE with Newton on the weak form.
- Explain inf-sup and distinguish stable and unstable Stokes element pairs.
Before you start
Error has geometry too
The previous lesson built FEM assembly. Now we ask where it falls short and what correction costs. A reentrant corner can limit regularity even for a simple equation: on the L-shaped domain a typical harmonic solution behaves as near the vertex. Its gradient diverges there, but is square-integrable. Refining smooth areas and the corner equally is often not the most efficient strategy. We assign no universal savings percentage: it depends on problem, tolerance and implementation.
For coercive Poisson and degree- elements on a regular mesh family, the a priori estimate, combining Céa and interpolation, has the form
if the solution has that regularity and boundary conditions and geometry satisfy the assumptions. If it belongs only to , the available rate is limited by even when is increased. The estimate precedes computation and needs information about the exact solution; Céa’s lemma does not make a singular solution smooth.
The Aubin–Nitsche argument improves the norm using a dual problem. Let and solve for every . By Galerkin orthogonality, , so
Dividing if gives an additional factor provided the dual problem has regularity , for example for suitable Poisson problems on a convex domain. A reentrant corner can invalidate that regularity. Improvement is not automatic for every domain or coefficient.
Degree and regularity
P2 higher-order elements have six degrees of freedom per triangle: three vertices and three edge midpoints. In barycentric coordinates the functions are at vertices and at edges. Their gradients are no longer constant, and quadrature must integrate products of the appropriate degree. On affine meshes with a smooth solution, P2 can achieve error of order , versus for P1; relevant cost is compared by degrees of freedom, not only element count.
The points come from assemblies and eighth-order quadrature of gradient differences, rather than invented theoretical lines. At the singularity that integral also has quadrature error. P2 reduces error on the shown meshes, but exponent limits uniform-rate improvement. In 2D, when , an error scales as ; reducing it tenfold requires roughly one hundred times more degrees of freedom under the same assumptions.
Estimate, mark, refine
An a posteriori estimator uses the computed solution. For P1 Poisson and interior edges, one residual version is
For affine P1, on each element. The jump measures flux discontinuity between neighbors; a globally constant gradient gives zero jump. Boundary residuals must be added for Neumann or Robin conditions. In standard formulations under mesh-regularity assumptions, reliability and efficiency relate estimator and error through constants, data oscillation and boundary terms where appropriate. is not exact error and its effectivity index need not be one. Here nonhomogeneous Dirichlet data are interpolated; the example does not claim a complete reliable bound without quantifying that boundary-data error.
Adaptive refinement repeats solve, estimate, mark and refine. Dörfler marking selects the largest indicators until is reached, with . The longest edges of marked elements are then split and the mesh closed to avoid hanging nodes; the code uses green and red splits when multiple triangle edges are marked. Closure may refine unmarked elements. A finite measurement sequence illustrates behavior but does not itself prove an optimal rate. Dörfler’s original work studies adaptive convergence under precise assumptions.
In this sequence, with , quadrature-estimated error drops from 0.428 to 0.0705 as nodes increase from 8 to 208; the uniform sequence reaches 0.0732 with 833 nodes. These are two meshes with similar errors, not a time measurement or universal percentage. Geometry, boundary treatment and quadrature are exactly those of the lab.
Evolution and nonlinear equations
For heat, spatial Galerkin produces , with mass matrix . Crank–Nicolson solves . One cannot replace by the identity unless a transformation or approximation, such as mass lumping, has been justified. Time stiffness and oscillations from discontinuous data follow the Crank–Nicolson precautions.
For , the weak residual is . The Gâteaux derivative in direction is
The second term must not be omitted: freezing produces a different iteration, not Newton. FEM Newton solves on free degrees of freedom and uses line search or continuation if the full step fails. Allen–Cahn adds nonlinear reaction and a mass matrix in evolution; its multiple states and stiffness require further analysis. A small algebraic residual checks the discrete system, not PDE accuracy by itself.
Pressure and the inf-sup condition
Stokes couples velocity and pressure in the saddle-point system
Pressure imposes zero weak divergence as a Lagrange multiplier. The inf-sup condition requires a uniform positive bound on coupling between mean-zero pressure and admissible velocities. If the discrete pair fails it, spurious pressure modes can appear. Taylor–Hood P2-P1 and MINI P1 with bubble-P1 are stable under their mesh assumptions; generic P1-P1 and P1-P0 are not without stabilization or other specific conditions.
The figure switches between modes and pressures for a smooth-lid cavity. For P1-P1 the singular system is approximated by least squares and relative residual is about 0.0055: this output does not exactly satisfy the system and pressure is not unique. The Taylor–Hood system has relative residual of order on the same mesh. In modal view, P1-P1 projects a checkerboard onto the nonconstant kernel and P2-P1 shows the first positive mode. One mesh does not prove a uniform inf-sup bound. Pressure is fixed at one degree of freedom to remove its constant.
Lab: adaptivity and nonlinear diffusion
This P1 implementation is self-contained: it assembles, imposes Dirichlet, computes jumps, marks and refines without hanging nodes. Indicators use three-point triangular quadrature. The exact singular function corresponds to the domain with the lower-right quadrant excluded.
"""Poisson P1, indicador residual y refinamiento conforme por aristas."""
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import spsolve
def geometry(p,t):
q=p[t];J=np.stack((q[:,1]-q[:,0],q[:,2]-q[:,0]),axis=-1)
area=np.abs(np.linalg.det(J))/2
if np.any(area<=0):raise ValueError("triángulo degenerado")
grad=np.einsum('ij,ejk->eik',np.array([[-1.,-1.],[1.,0.],[0.,1.]]),np.linalg.inv(J))
return q,area,grad
def edge_table(t):
raw=np.concatenate((t[:,[0,1]],t[:,[1,2]],t[:,[2,0]]))
edges,inv,counts=np.unique(np.sort(raw,axis=1),axis=0,return_inverse=True,return_counts=True)
return edges,inv.reshape(3,-1).T,counts
def solve_poisson(p,t,f,g):
q,area,grad=geometry(p,t);m=len(t);N=len(p)
local=area[:,None,None]*np.einsum('eik,ejk->eij',grad,grad)
row=np.broadcast_to(t[:,:,None],(m,3,3)).ravel();col=np.broadcast_to(t[:,None,:],(m,3,3)).ravel()
A=coo_matrix((local.ravel(),(row,col)),shape=(N,N)).tocsr()
bary=np.array([[2/3,1/6,1/6],[1/6,2/3,1/6],[1/6,1/6,2/3]])
xy=np.einsum('qi,eid->eqd',bary,q);fv=np.broadcast_to(f(xy[:,:,0],xy[:,:,1]),xy.shape[:2])
b=np.zeros(N);np.add.at(b,t.ravel(),(area[:,None]/3*np.einsum('eq,qi->ei',fv,bary)).ravel())
edges,_,count=edge_table(t);boundary=np.unique(edges[count==1]);free=np.setdiff1d(np.arange(N),boundary)
u=np.zeros(N);u[boundary]=g(p[boundary,0],p[boundary,1])
u[free]=spsolve(A[free][:,free],(b-A@u)[free])
return u
def residual_estimator(p,t,u,f):
"""eta_K²=h_K²∫_K f² + 1/2 Σ interior h_E∫_E [∇u·n]²."""
q,area,grad=geometry(p,t);gradient=np.einsum('ei,eid->ed',u[t],grad)
length=np.linalg.norm(q[:,[1,2,0]]-q[:,[0,1,2]],axis=2)
h=length.max(axis=1);bary=np.array([[2/3,1/6,1/6],[1/6,2/3,1/6],[1/6,1/6,2/3]])
xy=np.einsum('qi,eid->eqd',bary,q);fv=np.broadcast_to(f(xy[:,:,0],xy[:,:,1]),xy.shape[:2])
eta2=h*h*area*np.mean(fv*fv,axis=1)
edges,elem_edges,count=edge_table(t)
adjacent=[[] for _ in edges]
for k,row in enumerate(elem_edges):
for e in row:adjacent[e].append(k)
for e in np.flatnonzero(count==2):
ids=np.asarray(adjacent[e])
a,b=p[edges[e]];delta=b-a;normal=np.array([delta[1],-delta[0]])/np.linalg.norm(delta)
jump=(gradient[ids[0]]-gradient[ids[1]])@normal
eta2[ids]+=.5*np.dot(delta,delta)*jump*jump
return np.sqrt(eta2)
def mark_dorfler(eta,theta):
if not 0<theta<=1:raise ValueError("theta debe estar en (0,1]")
weights=np.asarray(eta)**2
if weights.sum()==0:return np.array([],dtype=int)
order=np.argsort(-weights,kind='stable');k=np.searchsorted(np.cumsum(weights[order]),theta*weights.sum())+1
return order[:k]
def refine(p,t,marked):
"""Biseca aristas más largas marcadas, cerrando conformidad con subdivisión roja/verde."""
edges,te,_=edge_table(t);length=np.linalg.norm(p[edges[:,0]]-p[edges[:,1]],axis=1)
chosen=set(te[k,np.argmax(length[te[k]])] for k in marked)
# Una celda con dos aristas partidas pasa a tres: partición roja sin nodos colgantes.
while True:
add={int(e) for row in te if sum(int(x in chosen) for x in row)>=2 for e in row}
if add.issubset(chosen):break
chosen.update(add)
pnew=p.tolist();mid={}
for e in sorted(chosen):mid[e]=len(pnew);pnew.append(((p[edges[e,0]]+p[edges[e,1]])/2).tolist())
out=[]
for (a,b,c),(e0,e1,e2) in zip(t,te):
hit=[e in chosen for e in (e0,e1,e2)]
if sum(hit)==0:out.append([a,b,c])
elif sum(hit)==1:
if hit[0]:m=mid[e0];out.extend([[a,m,c],[m,b,c]])
elif hit[1]:m=mid[e1];out.extend([[b,m,a],[m,c,a]])
else:m=mid[e2];out.extend([[c,m,b],[m,a,b]])
else:
x,y,z=mid[e0],mid[e1],mid[e2]
out.extend([[a,x,z],[x,b,y],[z,y,c],[x,y,z]])
return np.asarray(pnew),np.asarray(out,dtype=int)
def l_mesh():
p=np.array([[-1,-1],[0,-1],[1,-1],[-1,0],[0,0],[1,0],[-1,1],[0,1],[1,1]],dtype=float)
t=np.array([[0,1,4],[0,4,3],[3,4,7],[3,7,6],[4,5,8],[4,8,7]])
used=np.unique(t);mapping=np.full(len(p),-1);mapping[used]=np.arange(len(used))
return p[used],mapping[t]
def exact_l(x,y):
r=np.hypot(x,y);theta=np.mod(np.arctan2(y,x),2*np.pi)
return r**(2/3)*np.sin(2*theta/3)
def energy_error(p,t,u):
q,area,grad=geometry(p,t);discrete=np.einsum('ei,eid->ed',u[t],grad)
bary=np.array([[2/3,1/6,1/6],[1/6,2/3,1/6],[1/6,1/6,2/3]])
xy=np.einsum('qi,eid->eqd',bary,q);r=np.hypot(xy[:,:,0],xy[:,:,1]);theta=np.mod(np.arctan2(xy[:,:,1],xy[:,:,0]),2*np.pi)
a=2/3;dr=a*r**(a-1)*np.sin(a*theta);dt=a*r**(a-1)*np.cos(a*theta)
exact=np.stack((dr*np.cos(theta)-dt*np.sin(theta),dr*np.sin(theta)+dt*np.cos(theta)),axis=-1)
return np.sqrt(np.sum(area*np.mean(np.sum((exact-discrete[:,None,:])**2,axis=-1),axis=1)))p,t=l_mesh()
f=lambda x,y:np.zeros_like(x)
for iteration in range(5):
u=solve_poisson(p,t,f,exact_l)
eta=residual_estimator(p,t,u,f);marked=mark_dorfler(eta,.5)
print(iteration,'nodos',len(p),'elementos',len(t),
'error energía por cuadratura',energy_error(p,t,u),'estimador',np.linalg.norm(eta))
p,t=refine(p,t,marked)The next cell adds the residual and exact Jacobian of the discrete system. The line search reduces the step if the free residual norm does not decrease.
"""Difusión k(u)=1+u², P1, Newton amortiguado y jacobiana exacta discreta."""
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import spsolve
def nonlinear_residual_jacobian(p,t,u,f):
q,area,grad=geometry(p,t);m=len(t);N=len(p)
bary=np.array([[2/3,1/6,1/6],[1/6,2/3,1/6],[1/6,1/6,2/3]])
xy=np.einsum('qi,eid->eqd',bary,q);v=u[t];uq=v@bary.T
gu=np.einsum('ei,eid->ed',v,grad);gu_phi=np.einsum('ed,eid->ei',gu,grad)
kmean=np.mean(1+uq**2,axis=1)
fv=np.broadcast_to(f(xy[:,:,0],xy[:,:,1]),xy.shape[:2])
residual=area[:,None]*(kmean[:,None]*gu_phi-np.einsum('eq,qi->ei',fv,bary)/3)
stiffness=np.einsum('eid,ejd->eij',grad,grad)*kmean[:,None,None]
derivative=np.einsum('eq,qj->ej',2*uq,bary)/3
jac=area[:,None,None]*(stiffness+gu_phi[:,:,None]*derivative[:,None,:])
R=np.zeros(N);np.add.at(R,t.ravel(),residual.ravel())
rows=np.broadcast_to(t[:,:,None],(m,3,3)).ravel();cols=np.broadcast_to(t[:,None,:],(m,3,3)).ravel()
return R,coo_matrix((jac.ravel(),(rows,cols)),shape=(N,N)).tocsr()
def newton_diffusion(p,t,f,tol=1e-10,maxiter=25):
edges,_,counts=edge_table(t);boundary=np.unique(edges[counts==1])
free=np.setdiff1d(np.arange(len(p)),boundary);u=np.zeros(len(p));history=[]
for _ in range(maxiter):
R,J=nonlinear_residual_jacobian(p,t,u,f);norm=np.linalg.norm(R[free]);history.append(norm)
if norm<tol:return u,history
step=spsolve(J[free][:,free],-R[free]);alpha=1.
while alpha>1/128:
trial=u.copy();trial[free]+=alpha*step
if np.linalg.norm(nonlinear_residual_jacobian(p,t,trial,f)[0][free])<norm:break
alpha/=2
if alpha<=1/128:raise RuntimeError('Newton sin descenso')
u=trial
raise RuntimeError('Newton no converge')n=12;x=np.linspace(0,1,n+1);X,Y=np.meshgrid(x,x);p=np.column_stack((X.ravel(),Y.ravel()))
t=[]
for j in range(n):
for i in range(n):
a=j*(n+1)+i;b=a+1;c=a+n+1;d=c+1
t.extend([[a,b,d],[a,d,c]])
t=np.array(t)
def source(x,y):
u=np.sin(np.pi*x)*np.sin(np.pi*y)
dx=np.pi*np.cos(np.pi*x)*np.sin(np.pi*y);dy=np.pi*np.sin(np.pi*x)*np.cos(np.pi*y)
return 2*np.pi**2*u*(1+u*u)-2*u*(dx*dx+dy*dy)
u,history=newton_diffusion(p,t,source)
exact=np.sin(np.pi*p[:,0])*np.sin(np.pi*p[:,1])
rng=np.random.default_rng(42);v=rng.normal(size=len(p));R,J=nonlinear_residual_jacobian(p,t,u,source)
eps=1e-6;R2,_=nonlinear_residual_jacobian(p,t,u+eps*v,source)
print('normas de residuo:',history)
print('error nodal máximo:',np.max(np.abs(u-exact)))
print('error de diferencia finita para Jv:',np.linalg.norm((R2-R)/eps-J@v))The following comparison uses scikit-fem installed in the reader’s runtime. At the corner of its L mesh, the upper-right quadrant is excluded, so the solution angle is rotated relative to the previous cell.
"""Comparación reproducible P1/P2 con cuadratura y datos manufacturados."""
import numpy as np
from skfem import MeshTri,Basis,ElementTriP1,ElementTriP2,asm,condense,solve,LinearForm,Functional
from skfem.models.poisson import laplace
def exact(x,kind):
if kind=='smooth':return np.sin(np.pi*x[0])*np.sin(np.pi*x[1])
r=np.hypot(x[0],x[1]);theta=np.mod(np.arctan2(x[1],x[0])-np.pi/2,2*np.pi)
return r**(2/3)*np.sin(2*theta/3)
def gradient(x,kind):
if kind=='smooth':return np.array([np.pi*np.cos(np.pi*x[0])*np.sin(np.pi*x[1]),np.pi*np.sin(np.pi*x[0])*np.cos(np.pi*x[1])])
r=np.hypot(x[0],x[1]);phi=np.arctan2(x[1],x[0]);theta=np.mod(phi-np.pi/2,2*np.pi);a=2/3
dr=a*r**(a-1)*np.sin(a*theta);dt=a*r**(a-1)*np.cos(a*theta)
return np.array([dr*np.cos(phi)-dt*np.sin(phi),dr*np.sin(phi)+dt*np.cos(phi)])
def experiment(kind,degree,level):
mesh=(MeshTri.init_sqsymmetric() if kind=='smooth' else MeshTri.init_lshaped()).refined(level)
basis=Basis(mesh,ElementTriP1() if degree==1 else ElementTriP2(),intorder=8)
@LinearForm
def load(v,w):
return (2*np.pi**2*exact(w.x,kind) if kind=='smooth' else 0.)*v
@Functional
def error(w):
d=gradient(w.x,kind)-w.u.grad
return d[0]**2+d[1]**2
A=asm(laplace,basis);b=asm(load,basis);u=basis.zeros()
boundary=basis.get_dofs().all();u[boundary]=exact(basis.doflocs[:,boundary],kind)
u=solve(*condense(A,b,x=u,D=boundary))
return basis.N,float(np.sqrt(asm(error,basis,u=basis.interpolate(u))))
if __name__=='__main__':
for kind in ('smooth','singular'):
for degree in (1,2):
for level in range(1,5):print(kind,degree,level,experiment(kind,degree,level),flush=True)The next two cells reproduce the Schur-complement spectrum and Stokes solutions used in the figure. The equal-order pair is computed by least squares because its matrix is singular; its residual is printed instead of presenting the result as an exact solution.
"""Modos de presión débiles para pares P1-P1 y P2-P1 en una malla fija."""
import numpy as np
from scipy.linalg import eigh
from scipy.sparse.linalg import splu
from skfem import MeshTri,Basis,ElementVector,ElementTriP1,ElementTriP2,asm
from skfem.models.poisson import vector_laplace,mass
from skfem.models.general import divergence
def modes(n=6,degree=1):
mesh=MeshTri.init_tensor(np.linspace(0,1,n+1),np.linspace(0,1,n+1))
V=Basis(mesh,ElementVector(ElementTriP1() if degree==1 else ElementTriP2()),intorder=5)
Q=Basis(mesh,ElementTriP1(),intorder=5)
free=np.setdiff1d(np.arange(V.N),V.get_dofs().all())
A=asm(vector_laplace,V)[free][:,free].tocsc();B=-asm(divergence,V,Q)[:,free];M=asm(mass,Q).toarray()
S=B@(-splu(A).solve((-B.T).toarray()))
eigen,v=eigh((S+S.T)/2,M)
return mesh,Q,eigen,v
def display_mode(n=6,degree=1):
"""Presión normalizada de la figura; proyección M-ortogonal de un tablero."""
mesh,Q,eigen,v=modes(n,degree)
M=asm(mass,Q).toarray();ones=np.ones(Q.N)
if degree==1:
checker=(-1.)**np.round((mesh.p[0]+mesh.p[1])*n)
checker-=ones*(ones@M@checker)/(ones@M@ones)
sub=v[:,eigen<1e-10];vector=sub@(sub.T@M@checker)
vector-=ones*(ones@M@vector)/(ones@M@ones)
else:vector=v[:,1]
return mesh,vector/np.max(np.abs(vector))
if __name__=='__main__':
for degree in (1,2):
_,_,eigen,_=modes(degree=degree)
print('grado velocidad',degree,'autovalores cerca de cero',np.count_nonzero(eigen<1e-10),'primeros:',eigen[:12])"""Stokes de cavidad con Taylor-Hood y mínimos cuadrados para P1-P1 singular."""
import numpy as np
from scipy.sparse import bmat
from scipy.sparse.linalg import spsolve,lsmr
from skfem import MeshTri,Basis,ElementVector,ElementTriP1,ElementTriP2,asm
from skfem.models.poisson import vector_laplace
from skfem.models.general import divergence
def stokes_cavity(n=6,degree=1):
mesh=MeshTri.init_tensor(np.linspace(0,1,n+1),np.linspace(0,1,n+1))
V=Basis(mesh,ElementVector(ElementTriP1() if degree==1 else ElementTriP2()),intorder=5)
Q=Basis(mesh,ElementTriP1(),intorder=5)
A=asm(vector_laplace,V);B=-asm(divergence,V,Q);K=bmat([[A,B.T],[B,None]],format='csr')
boundary=V.get_dofs().all();top=boundary[np.isin(boundary,V.split_indices()[0])&np.isclose(V.doflocs[1,boundary],1)]
x=np.zeros(V.N+Q.N);x[top]=16*V.doflocs[0,top]**2*(1-V.doflocs[0,top])**2
fixed=np.r_[boundary,V.N];free=np.setdiff1d(np.arange(len(x)),fixed);rhs=(-K@x)[free];matrix=K[free][:,free]
if degree==1:
x[free]=lsmr(matrix,rhs,atol=1e-12,btol=1e-12,maxiter=20000)[0]
else:x[free]=spsolve(matrix,rhs)
return mesh,Q,x[V.N:],float(np.linalg.norm((K@x)[free])),float(np.linalg.norm(rhs))
if __name__=='__main__':
for degree in (1,2):
mesh,Q,p,res,rhs=stokes_cavity(degree=degree)
print('P'+str(degree)+'-P1, presión min/max, residuo, norma lado derecho:',p.min(),p.max(),res,rhs)Local lab: cavity
Install numpy, scipy and scikit-fem==12.0.2 in local Python. The horizontal lid has smooth profile , zero at corners. First solve Stokes, then steady Navier–Stokes with Newton and continuation . Reynolds number corresponds to unit reference speed and length; this is not a validated benchmark for a discontinuous constant lid. A small residual does not prove convergence on refinement or guarantee capture of high-Reynolds flows.
"""Cavidad 2D Taylor-Hood con tapa suave y continuación estacionaria."""
import numpy as np
from scipy.sparse import bmat
from scipy.sparse.linalg import spsolve
from skfem import MeshTri,Basis,ElementVector,ElementTriP2,ElementTriP1,asm,BilinearForm,LinearForm
from skfem.helpers import dot,grad,mul
from skfem.models.poisson import vector_laplace
from skfem.models.general import divergence
@LinearForm
def convection(v,w):
return dot(mul(grad(w.u),w.u),v)
@BilinearForm
def convection_jac(du,v,w):
return dot(mul(grad(du),w.u)+mul(grad(w.u),du),v)
def cavity(n=10,reynolds=(1.,10.,100.)):
mesh=MeshTri.init_tensor(np.linspace(0,1,n+1),np.linspace(0,1,n+1))
V=Basis(mesh,ElementVector(ElementTriP2()),intorder=5);Q=Basis(mesh,ElementTriP1(),intorder=5)
A=asm(vector_laplace,V);B=-asm(divergence,V,Q);nu=V.N;npres=Q.N
# Identifica componentes vectoriales mediante split_indices, incluidos puntos de arista P2.
boundary=V.get_dofs().all();horizontal=V.split_indices()[0]
top=boundary[np.isin(boundary,horizontal)&np.isclose(V.doflocs[1,boundary],1.)]
x=np.zeros(nu+npres);x[top]=16*V.doflocs[0,top]**2*(1-V.doflocs[0,top])**2
fixed=np.r_[boundary,nu];free=np.setdiff1d(np.arange(nu+npres),fixed)
results=[]
for Re in reynolds:
visc=1/Re;K=bmat([[visc*A,B.T],[B,None]],format='csr')
# Primera etapa Stokes y posteriores Newton con línea de búsqueda.
if not results:
x[free]=spsolve(K[free][:,free],(-K@x)[free])
results.append(('Stokes',0,float(np.linalg.norm((K@x)[free])),float(np.linalg.norm((B@x[:nu])[1:])),float(np.linalg.norm(x[:nu]))))
for it in range(25):
field=V.interpolate(x[:nu]);conv=asm(convection,V,u=field)
r=K@x;r[:nu]+=conv;norm=np.linalg.norm(r[free])
if norm<1e-9:break
jac=asm(convection_jac,V,u=field);J=K.copy().tolil();J[:nu,:nu]+=jac;J=J.tocsr()
step=spsolve(J[free][:,free],-r[free]);alpha=1.
while alpha>1/128:
trial=x.copy();trial[free]+=alpha*step
rr=K@trial;rr[:nu]+=asm(convection,V,u=V.interpolate(trial[:nu]))
if np.linalg.norm(rr[free])<norm:break
alpha/=2
if alpha<=1/128:raise RuntimeError('Newton sin descenso')
x=trial
else:raise RuntimeError('Newton no converge')
div=np.linalg.norm((B@x[:nu])[1:])
results.append((Re,it,float(norm),float(div),float(np.linalg.norm(x[:nu]))))
return mesh,V,Q,x,results
if __name__=='__main__':
_,V,Q,_,results=cavity()
print('Taylor-Hood: grados velocidad, presión',V.N,Q.N)
for result in results:print('Re, iteraciones Newton, residuo libre, divergencia débil, norma velocidad:',result)npm run lab and open the connection link.The code uses a direct sparse solver and a small mesh; a larger mesh requires evaluating cost and preconditioning. scikit-fem facilitates Python prototypes; FEniCSx and Firedrake offer broader formulation and execution tools. The choice depends on support, scale, installation and specific problems.
Exercises
Step 1 of 3. How is ‖e‖² expressed using dual z?
import numpy as np
def residual_estimator(p,t,u,f):
pass