def test_mesh_metric(): mesh = RectangleMesh(0, 0, 1, 1, 20, 20) mesh = adapt( interpolate(Constant(((10., 0.), (0., 10.))), TensorFunctionSpace(mesh, 'CG', 1))) #extract mesh metric MpH = mesh_metric2(mesh) # Plot element i i = 20 t = linspace(0, 2 * pi, 101) ind = MpH.function_space().dofmap().cell_dofs(i) thecell = mesh.cells()[i] centerxy = mesh.coordinates()[thecell, :].mean(0).repeat(3).reshape([2, 3]).T cxy = mesh.coordinates()[thecell, :] - centerxy pyplot(cxy[:, 0], cxy[:, 1], '-b') H = MpH.vector().gather(ind).reshape(2, 2) # H = array([[H[1],H[0]],[H[0],H[2]]]) #H = MpH.vector().gather(ind); H = array([[H[1],H[0]],[H[0],H[2]]]) #H = MpH.vector().array()[ind]; H = array([[H[1],H[0]],[H[0],H[2]]]) [v, w] = linalg.eig(H) v /= pysqrt(3) #v = 1/pysqrt(v)/pysqrt(3) elxy = array([pycos(t), pysin(t)]).T.dot(w).dot(diag(v)).dot(w.T) hold('on') pyplot(elxy[:, 0], elxy[:, 1], '-r') hold('off') axis('equal') print('triangle area: %0.6f, ellipse axis product(*3*sqrt(3)/4): %0.6f' % ( pyabs(linalg.det(array([cxy[1, :] - cxy[0, :], cxy[2, :] - cxy[0, :] ]))) / 2, v[0] * v[1] * 3 * sqrt(3) / 4)) show()
def test_mesh_metric3D(): mesh = BoxMesh(0, 0, 0, 1, 1, 1, 20, 20, 20) mesh = adapt( interpolate(Constant(((100., 0., 0.), (0., 100., 0.), (0., 0., 100.))), TensorFunctionSpace(mesh, 'CG', 1))) #extract mesh metric MpH = mesh_metric2(mesh) for i in range(0, 40): thecell = mesh.cells()[i] ind = MpH.function_space().dofmap().cell_dofs(i) coords = mesh.coordinates()[thecell, :] r1 = coords[1, :] - coords[0, :] r2 = coords[2, :] - coords[0, :] r3 = coords[0:3, :].mean(0) - coords[3, :] r12c = cross(r2, r1) / 6. det1234 = pyabs((r12c * r3).sum()) H = MpH.vector().gather(ind).reshape( 3, 3) # H = array([[H[1],H[0]],[H[0],H[2]]]) [v, w] = linalg.eig(H) print( 'tetrahedron volume: %0.6f, ellipsoid axis product(*sqrt(2)/12): %0.6f' % (det1234, v.prod() * sqrt(2) / 12)) print v.prod() * sqrt(2) / 12 / (det1234)
def check_metric_ellipse(width=2e-2, eta = 0.02, Nadapt=6): set_log_level(WARNING) parameters["allow_extrapolation"] = True ### CONSTANTS meshsz = 40 hd = Constant(width) ### SETUP MESH mesh = RectangleMesh(Point(-0.5,-0.5),Point(0.5,0.5),1*meshsz,1*meshsz,"left/right") ### SETUP SOLUTION angle = pi/8#rand()*pi/2 #testsol = 'tanh(x[0]/' + str(float(hd)) + ')' #tanh(x[0]/hd) testsol = 'tanh((' + str(cos(angle)) + '*x[0]+'+ str(sin(angle)) + '*x[1])/' + str(float(hd)) + ')' #tanh(x[0]/hd) ddtestsol = str(cos(angle)+sin(angle))+'*2*'+testsol+'*(1-pow('+testsol+',2))/'+str(float(hd)**2) #testsol2 = 'tanh(x[1]/' + str(float(hd)) + ')' #tanh(x[0]/hd) testsol2 = 'tanh((' + str(cos(angle)) + '*x[1]-'+ str(sin(angle)) + '*x[0])/' + str(float(hd)) + ')' #tanh(x[0]/hd) ddtestsol2 = str(cos(angle)-sin(angle))+'*2*'+testsol2+'*(1-pow('+testsol2+',2))/'+str(float(hd)**2) def boundary(x): return x[0]-mesh.coordinates()[:,0].min() < DOLFIN_EPS or mesh.coordinates()[:,0].max()-x[0] < DOLFIN_EPS \ or mesh.coordinates()[:,1].min()+0.5 < DOLFIN_EPS or mesh.coordinates()[:,1].max()-x[1] < DOLFIN_EPS # PERFORM ONE ADAPTATION ITERATION for iii in range(Nadapt): V = FunctionSpace(mesh, "CG" ,2); dis = TrialFunction(V); dus = TestFunction(V); u = Function(V); u2 = Function(V) bc = DirichletBC(V, Expression(testsol), boundary) bc2 = DirichletBC(V, Expression(testsol2), boundary) R = interpolate(Expression(ddtestsol),V) R2 = interpolate(Expression(ddtestsol2),V) a = inner(grad(dis), grad(dus))*dx L = R*dus*dx L2 = R2*dus*dx solve(a == L, u, bc) solve(a == L2, u2, bc2) H = metric_pnorm(u , eta, max_edge_length=1., max_edge_ratio=50); #Mp = project(H, TensorFunctionSpace(mesh, "CG", 1)) H2 = metric_pnorm(u2, eta, max_edge_length=1., max_edge_ratio=50); #Mp2 = project(H2, TensorFunctionSpace(mesh, "CG", 1)) H3 = metric_ellipse(H,H2); Mp3 = project(H3, TensorFunctionSpace(mesh, "CG", 1)) print("H11: %0.0f, H22: %0.0f, V: %0.0f,E: %0.0f" % (assemble(abs(H3[0,0])*dx),assemble(abs(H3[1,1])*dx),mesh.num_vertices(),mesh.num_cells())) startTime = time() if iii != 6: # mesh2 = Mesh(adapt(Mp2)) mesh = Mesh(adapt(Mp3)) # mesh3 = adapt(Mp) print("total time was %0.1fs" % (time()-startTime)) # PLOT MESH figure(1); triplot(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells()); axis('equal'); axis('off'); box('off') #figure(2); triplot(mesh2.coordinates()[:,0],mesh2.coordinates()[:,1],mesh2.cells()) #mesh = mesh2 #figure(3); triplot(mesh3.coordinates()[:,0],mesh3.coordinates()[:,1],mesh3.cells()) #mesh = mesh3 figure(4); testf = interpolate(u2,FunctionSpace(mesh,'CG',1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG" ,1)) zz = testf.vector().array()[vtx2dof]; zz[zz==1] -= 1e-16 tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100) show()
def minimal_example3D(width=2e-2, Nadapt=10, eta = 0.04): ### CONSTANTS meshsz = 10 ### SETUP MESH mesh = BoxMesh(-0.5,-0.5,-0.5,0.5,0.5,0.5,meshsz,meshsz,meshsz) ### DERIVE FORCING TERM angle = pi/8 #rand*pi/2 angle2 = pi/8 #rand*pi/2 sx = Symbol('sx'); sy = Symbol('sy'); sz = Symbol('sz'); width_ = Symbol('ww'); aa = Symbol('aa'); bb = Symbol('bb') testsol = pytanh((sx*pycos(aa)*pysin(bb)+sy*pysin(aa)*pysin(bb)+sz*pycos(bb))/width_) ddtestsol = str(diff(testsol,sx,sx)+diff(testsol,sy,sy)+diff(testsol,sz,sz)).replace('sx','x[0]').replace('sy','x[1]').replace('sz','x[2]') #replace ** with pow ddtestsol = ddtestsol.replace('tanh((x[0]*sin(aa)*cos(bb) + x[1]*cos(aa)*cos(bb) + x[2]*sin(bb))/ww)**2','pow(tanh((x[0]*sin(aa)*sin(bb) + x[1]*cos(aa)*sin(bb) + x[2]*cos(bb))/ww),2.)') ddtestsol = ddtestsol.replace('cos(aa)**2','pow(cos(aa),2.)').replace('sin(aa)**2','pow(sin(aa),2.)').replace('ww**2','(ww*ww)').replace('cos(bb)**2','(cos(bb)*cos(bb))').replace('sin(bb)**2','(sin(bb)*sin(bb))') #insert vaulues ddtestsol = ddtestsol.replace('aa',str(angle)).replace('ww',str(width)).replace('bb',str(angle2)) testsol = str(testsol).replace('sx','x[0]').replace('sy','x[1]').replace('aa',str(angle)).replace('ww',str(width)).replace('bb',str(angle2)).replace('sz','x[2]') ddtestsol = "-("+ddtestsol+")" def boundary(x): return x[0]-mesh.coordinates()[:,0].min() < DOLFIN_EPS or mesh.coordinates()[:,0].max()-x[0] < DOLFIN_EPS \ or mesh.coordinates()[:,1].min() < DOLFIN_EPS or mesh.coordinates()[:,1].max()-x[1] < DOLFIN_EPS \ or mesh.coordinates()[:,2].min() < DOLFIN_EPS or mesh.coordinates()[:,2].max()-x[2] < DOLFIN_EPS # PERFORM TEN ADAPTATION ITERATIONS fid = File("out.pvd") for iii in range(Nadapt): V = FunctionSpace(mesh, "CG" ,2); dis = TrialFunction(V); dus = TestFunction(V); u = Function(V) a = inner(grad(dis), grad(dus))*dx L = Expression(ddtestsol)*dus*dx bc = DirichletBC(V, Expression(testsol), boundary) solve(a == L, u, bc) fid << u startTime = time() H = metric_pnorm(u, eta, max_edge_length=2., max_edge_ratio=50, CG1out=True) #H = logproject(H) if iii != Nadapt-1: mesh = adapt(H) L2error = errornorm(Expression(testsol), u, degree_rise=4, norm_type='L2') log(INFO+1,"total (adapt+metric) time was %0.1fs, L2error=%0.0e, nodes: %0.0f" % (time()-startTime,L2error,mesh.num_vertices())) plot(u,interactive=True) plot(mesh,interactive=True)
def minimal_example3D(width=2e-2, Nadapt=10, eta = 0.04): ### CONSTANTS meshsz = 10 ### SETUP MESH mesh = BoxMesh(Point(-0.5,-0.5,-0.5),Point(0.5,0.5,0.5),meshsz,meshsz,meshsz) ### DERIVE FORCING TERM angle = pi/8 #rand*pi/2 angle2 = pi/8 #rand*pi/2 sx = Symbol('sx'); sy = Symbol('sy'); sz = Symbol('sz'); width_ = Symbol('ww'); aa = Symbol('aa'); bb = Symbol('bb') testsol = pytanh((sx*pycos(aa)*pysin(bb)+sy*pysin(aa)*pysin(bb)+sz*pycos(bb))/width_) ddtestsol = str(diff(testsol,sx,sx)+diff(testsol,sy,sy)+diff(testsol,sz,sz)).replace('sx','x[0]').replace('sy','x[1]').replace('sz','x[2]') #replace ** with pow ddtestsol = ddtestsol.replace('tanh((x[0]*sin(aa)*cos(bb) + x[1]*cos(aa)*cos(bb) + x[2]*sin(bb))/ww)**2','pow(tanh((x[0]*sin(aa)*sin(bb) + x[1]*cos(aa)*sin(bb) + x[2]*cos(bb))/ww),2.)') ddtestsol = ddtestsol.replace('cos(aa)**2','pow(cos(aa),2.)').replace('sin(aa)**2','pow(sin(aa),2.)').replace('ww**2','(ww*ww)').replace('cos(bb)**2','(cos(bb)*cos(bb))').replace('sin(bb)**2','(sin(bb)*sin(bb))') #insert vaulues ddtestsol = ddtestsol.replace('aa',str(angle)).replace('ww',str(width)).replace('bb',str(angle2)) testsol = str(testsol).replace('sx','x[0]').replace('sy','x[1]').replace('aa',str(angle)).replace('ww',str(width)).replace('bb',str(angle2)).replace('sz','x[2]') ddtestsol = "-("+ddtestsol+")" def boundary(x): return x[0]-mesh.coordinates()[:,0].min() < DOLFIN_EPS or mesh.coordinates()[:,0].max()-x[0] < DOLFIN_EPS \ or mesh.coordinates()[:,1].min() < DOLFIN_EPS or mesh.coordinates()[:,1].max()-x[1] < DOLFIN_EPS \ or mesh.coordinates()[:,2].min() < DOLFIN_EPS or mesh.coordinates()[:,2].max()-x[2] < DOLFIN_EPS # PERFORM TEN ADAPTATION ITERATIONS fid = File("out.pvd") for iii in range(Nadapt): V = FunctionSpace(mesh, "CG" ,2); dis = TrialFunction(V); dus = TestFunction(V); u = Function(V) a = inner(grad(dis), grad(dus))*dx L = Expression(ddtestsol)*dus*dx bc = DirichletBC(V, Expression(testsol), boundary) solve(a == L, u, bc) fid << u startTime = time() H = metric_pnorm(u, eta, max_edge_length=2., max_edge_ratio=50, CG1out=True) #H = logproject(H) if iii != Nadapt-1: mesh = adapt(H) L2error = errornorm(Expression(testsol), u, degree_rise=4, norm_type='L2') log(INFO+1,"total (adapt+metric) time was %0.1fs, L2error=%0.0e, nodes: %0.0f" % (time()-startTime,L2error,mesh.num_vertices())) plot(u,interactive=True) plot(mesh,interactive=True)
def test_mesh_metric3D(): mesh = BoxMesh(0,0,0,1,1,1,20,20,20) mesh = adapt(interpolate(Constant(((100.,0.,0.),(0.,100.,0.),(0.,0.,100.))),TensorFunctionSpace(mesh,'CG',1))) #extract mesh metric MpH = mesh_metric2(mesh) for i in range(0,40): thecell = mesh.cells()[i] ind = MpH.function_space().dofmap().cell_dofs(i) coords = mesh.coordinates()[thecell,:] r1 = coords[1,:]-coords[0,:] r2 = coords[2,:]-coords[0,:] r3 = coords[0:3,:].mean(0)-coords[3,:] r12c = cross(r2,r1)/6. det1234 = pyabs((r12c*r3).sum()) H = MpH.vector().gather(ind).reshape(3,3)# H = array([[H[1],H[0]],[H[0],H[2]]]) [v,w] = linalg.eig(H) print('tetrahedron volume: %0.6f, ellipsoid axis product(*sqrt(2)/12): %0.6f' % (det1234,v.prod()*sqrt(2)/12)) print v.prod()*sqrt(2)/12/(det1234)
def test_mesh_metric(): mesh = RectangleMesh(0,0,1,1,20,20) mesh = adapt(interpolate(Constant(((10.,0.),(0.,10.))),TensorFunctionSpace(mesh,'CG',1))) #extract mesh metric MpH = mesh_metric2(mesh) # Plot element i i = 20; t = linspace(0,2*pi,101) ind = MpH.function_space().dofmap().cell_dofs(i) thecell = mesh.cells()[i] centerxy = mesh.coordinates()[thecell,:].mean(0).repeat(3).reshape([2,3]).T cxy = mesh.coordinates()[thecell,:]-centerxy pyplot(cxy[:,0],cxy[:,1],'-b') H = MpH.vector().gather(ind).reshape(2,2);# H = array([[H[1],H[0]],[H[0],H[2]]]) #H = MpH.vector().gather(ind); H = array([[H[1],H[0]],[H[0],H[2]]]) #H = MpH.vector().array()[ind]; H = array([[H[1],H[0]],[H[0],H[2]]]) [v,w] = linalg.eig(H); v /= pysqrt(3) #v = 1/pysqrt(v)/pysqrt(3) elxy = array([pycos(t),pysin(t)]).T.dot(w).dot(diag(v)).dot(w.T) hold('on'); pyplot(elxy[:,0],elxy[:,1],'-r'); hold('off'); axis('equal') print('triangle area: %0.6f, ellipse axis product(*3*sqrt(3)/4): %0.6f' % (pyabs(linalg.det(array([cxy[1,:]-cxy[0,:],cxy[2,:]-cxy[0,:]])))/2,v[0]*v[1]*3*sqrt(3)/4)) show()
def test_refine_metric(): # from mpi4py import MPI import sys # comm = MPI.COMM_WORLD # mesh = Mesh("greenland.xml.gz") mesh = UnitSquareMesh(100, 100) V = FunctionSpace(mesh, "CG", 2) f = interpolate(Expression("0.1*sin(50.*(2*x[0]-1)) + atan2(-0.1, (2.0*(2*x[0]-1) - sin(5.*(2*x[1]-1))))"), V) eta = 0.01 #Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) #mesh = adapt(Mp) if True: level = 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh1 = adapt(Mp) level *= 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh2 = adapt(Mp) level *= 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh3 = adapt(Mp) level *= 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh4 = adapt(Mp) level *= 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh5 = adapt(Mp) level *= 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh6 = adapt(Mp) else: eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh1 = adapt(Mp) eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh2 = adapt(Mp) eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh3 = adapt(Mp) eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh4 = adapt(Mp) eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh5 = adapt(Mp) eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh6 = adapt(Mp) # plot(Mp[0,0]) # from IPython import embed # embed() plot(mesh, title="initial mesh") plot(new_mesh1, title="coarsen 1") plot(new_mesh2, title="coarsen 2") plot(new_mesh3, title="coarsen 3") plot(new_mesh4, title="coarsen 4") plot(new_mesh5, title="coarsen 5") plot(new_mesh6, title="coarsen 6") interactive()
def adv_convergence(width=2e-2, delta=1e-2, relp=1, Nadapt=10, use_adapt=True, problem=3, outname='', use_reform=False, CGorderL=[2, 3], noplot=False, Lx=3.): ### SETUP SOLUTION sy = Symbol('sy') width_ = Symbol('ww') if problem == 3: stepfunc = 0.5 + 165. / 104. / width_ * sy - 20. / 13. / width_**3 * sy**3 - 102. / 13. / width_**5 * sy**5 + 240. / 13. / width_**7 * sy**7 elif problem == 2: stepfunc = 0.5 + 15. / 8. / width_ * sy - 5. / width_**3 * sy**3 + 6. / width_**5 * sy**5 elif problem == 1: stepfunc = 0.5 + 1.5 / width_ * sy - 2 / width_**3 * sy**3 stepfunc = str(stepfunc).replace('sy', 'x[1]').replace('x[1]**2', '(x[1]*x[1])') #REPLACE ** with pow stepfunc = stepfunc.replace('x[1]**3', 'pow(x[1],3.)') stepfunc = stepfunc.replace('x[1]**5', 'pow(x[1],5.)') stepfunc = stepfunc.replace('x[1]**7', 'pow(x[1],7.)') testsol = '(-ww/2 < x[1] && x[1] < ww/2 ? ' + stepfunc + ' : 0) + (ww/2<x[1] ? 1 : 0)' testsol = testsol.replace('ww**2', '(ww*ww)').replace( 'ww**3', 'pow(ww,3.)').replace('ww**5', 'pow(ww,5.)').replace('ww**7', 'pow(ww,7.)') testsol = testsol.replace('ww', str(width)) dp = Constant(1.) fac = Constant(1 + 2. * delta) delta = Constant(delta) def left(x, on_boundary): return x[0] + Lx / 2. < DOLFIN_EPS def right(x, on_boundary): return x[0] - Lx / 2. > -DOLFIN_EPS def top_bottom(x, on_boundary): return x[1] - 0.5 > -DOLFIN_EPS or x[1] + 0.5 < DOLFIN_EPS class Inletbnd(SubDomain): def inside(self, x, on_boundary): return x[0] + Lx / 2. < DOLFIN_EPS for CGorder in [2]: #CGorderL: dofs = [] L2errors = [] for eta in 0.04 * pyexp2(-array(range(9)) * pylog(2) / 2): ### SETUP MESH meshsz = int( round(80 * 0.005 / (eta * (bool(use_adapt) == False) + 0.05 * (bool(use_adapt) == True)))) if not bool(use_adapt) and meshsz > 80: continue mesh = RectangleMesh(-Lx / 2., -0.5, Lx / 2., 0.5, meshsz, meshsz, "left/right") # PERFORM TEN ADAPTATION ITERATIONS for iii in range(Nadapt): V = VectorFunctionSpace(mesh, "CG", CGorder) Q = FunctionSpace(mesh, "CG", CGorder - 1) W = V * Q (u, p) = TrialFunctions(W) (v, q) = TestFunctions(W) alpha = Expression( "-0.25<x[0] && x[0]<0.25 && 0. < x[1] ? 1e4 : 0") boundaries = FacetFunction("size_t", mesh) #outletbnd = Outletbnd() inletbnd = Inletbnd() boundaries.set_all(0) #outletbnd.mark(boundaries, 1) inletbnd.mark(boundaries, 1) ds = Measure("ds")[boundaries] bc0 = DirichletBC(W.sub(0), Constant((0., 0.)), top_bottom) bc1 = DirichletBC(W.sub(1), dp, left) bc2 = DirichletBC(W.sub(1), Constant(0), right) bc3 = DirichletBC(W.sub(0).sub(1), Constant(0.), left) bc4 = DirichletBC(W.sub(0).sub(1), Constant(0.), right) bcs = [bc0, bc1, bc2, bc3, bc4] bndterm = dp * dot(v, Constant((-1., 0.))) * ds(1) a = eta * inner(grad(u), grad( v)) * dx - div(v) * p * dx + q * div(u) * dx + alpha * dot( u, v) * dx #+bndterm L = inner(Constant((0., 0.)), v) * dx - bndterm U = Function(W) solve(a == L, U, bcs) u, ps = U.split() #SOLVE CONCENTRATION mm = mesh_metric2(mesh) vdir = u / sqrt(inner(u, u) + DOLFIN_EPS) if iii == 0 or use_reform == False: Q2 = FunctionSpace(mesh, 'CG', 2) c = Function(Q2) q = TestFunction(Q2) p = TrialFunction(Q2) newq = (q + dot(vdir, dot(mm, vdir)) * inner(grad(q), vdir) ) #SUPG if use_reform: F = newq * (fac / ( (1 + exp(-c))**2) * exp(-c)) * inner(grad(c), u) * dx J = derivative(F, c) bc = DirichletBC( Q2, Expression("-log(" + str(float(fac)) + "/(" + testsol + "+" + str(float(delta)) + ")-1)"), left) # bc = DirichletBC(Q, -ln(fac/(Expression(testsol)+delta)-1), left) problem = NonlinearVariationalProblem(F, c, bc, J) solver = NonlinearVariationalSolver(problem) solver.parameters["newton_solver"][ "relaxation_parameter"] = relp solver.solve() else: a2 = newq * inner(grad(p), u) * dx bc = DirichletBC(Q2, Expression(testsol), left) L2 = Constant(0.) * q * dx solve(a2 == L2, c, bc) if (not bool(use_adapt)) or iii == Nadapt - 1: break um = project(sqrt(inner(u, u)), FunctionSpace(mesh, 'CG', 2)) H = metric_pnorm(um, eta, max_edge_ratio=1 + 49 * (use_adapt != 2), p=2) H2 = metric_pnorm(c, eta, max_edge_ratio=1 + 49 * (use_adapt != 2), p=2) #H3 = metric_pnorm(ps , eta, max_edge_ratio=1+49*(use_adapt!=2), p=2) H4 = metric_ellipse(H, H2) #H5 = metric_ellipse(H3,H4,mesh) mesh = adapt(H4) if use_reform: Q2 = FunctionSpace(mesh, 'CG', 2) c = interpolate(c, Q2) if use_reform: c = project(fac / (1 + exp(-c)) - delta, FunctionSpace(mesh, 'CG', 2)) L2error = bnderror(c, Expression(testsol), ds) dofs.append(len(c.vector().array()) + len(U.vector().array())) L2errors.append(L2error) # fid = open("DOFS_L2errors_mesh_c_CG"+str(CGorder)+outname+".mpy",'w') # pickle.dump([dofs[0],L2errors[0],c.vector().array().min(),c.vector().array().max()-1,mesh.cells(),mesh.coordinates(),c.vector().array()],fid) # fid.close(); log( INFO + 1, "%1dX ADAPT<->SOLVE complete: DOF=%5d, error=%0.0e, min(c)=%0.0e,max(c)-1=%0.0e" % (Nadapt, dofs[len(dofs) - 1], L2error, c.vector().array().min(), c.vector().array().max() - 1)) # PLOT MESH + solution figure() testf = interpolate(c, FunctionSpace(mesh, 'CG', 1)) testfe = interpolate(Expression(testsol), FunctionSpace(mesh, 'CG', 1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG", 1)) zz = testf.vector().array()[vtx2dof] zz[zz == 1] -= 1e-16 hh = tricontourf(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), zz, 100, cmap=get_cmap('binary')) colorbar(hh) hold('on') triplot(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), color='r', linewidth=0.5) hold('off') axis('equal') box('off') # savefig(outname+'final_mesh_CG2.png',dpi=300) #; savefig('outname+final_mesh_CG2.eps',dpi=300) #PLOT ERROR figure() xe = interpolate(Expression("x[0]"), FunctionSpace(mesh, 'CG', 1)).vector().array() ye = interpolate(Expression("x[1]"), FunctionSpace(mesh, 'CG', 1)).vector().array() I = xe - Lx / 2 > -DOLFIN_EPS I2 = ye[I].argsort() pyplot(ye[I][I2], testf.vector().array()[I][I2] - testfe.vector().array()[I][I2], '-b') ylabel('error') # PLOT L2error graph figure() pyloglog(dofs, L2errors, '-b.', linewidth=2, markersize=16) xlabel('Degree of freedoms') ylabel('L2 error') # SAVE SOLUTION dofs = array(dofs) L2errors = array(L2errors) fid = open("DOFS_L2errors_CG" + str(CGorder) + outname + ".mpy", 'w') pickle.dump([dofs, L2errors], fid) fid.close() # #show() # #LOAD SAVED SOLUTIONS # fid = open("DOFS_L2errors_CG2"+outname+".mpy",'r') # [dofs,L2errors] = pickle.load(fid) # fid.close() # # PERFORM FITS ON LAST THREE POINTS NfitP = 5 I = array(range(len(dofs) - NfitP, len(dofs))) slope, ints = polyfit(pylog(dofs[I]), pylog(L2errors[I]), 1) fid = open("DOFS_L2errors_CG2_fit" + outname + ".mpy", 'w') pickle.dump([dofs, L2errors, slope, ints], fid) fid.close() #PLOT THEM TOGETHER if CGorderL != [2]: fid = open("DOFS_L2errors_CG3.mpy", 'r') [dofs_old, L2errors_old] = pickle.load(fid) fid.close() slope2, ints2 = polyfit(pylog(dofs_old[I]), pylog(L2errors_old[I]), 1) figure() pyloglog(dofs, L2errors, '-b.', dofs_old, L2errors_old, '--b.', linewidth=2, markersize=16) hold('on') pyloglog(dofs, pyexp2(ints) * dofs**slope, '-r', dofs_old, pyexp2(ints2) * dofs_old**slope2, '--r', linewidth=1) hold('off') xlabel('Degree of freedoms') ylabel('L2 error') legend([ 'CG2', 'CG3', "%0.2f*log(DOFs)" % slope, "%0.2f*log(DOFs)" % slope2 ]) #legend(['new data','old_data']) # savefig('comparison.png',dpi=300) #savefig('comparison.eps'); if not noplot: show()
def minimal_example3D(meshsz=20, Nadapt=10, dL=0.05, eta=0.01, returnmesh=False, hax=False): class inlet(SubDomain): def inside(self, x, on_boundary): return 0.5-DOLFIN_EPS < x[0] \ and -dL-DOLFIN_EPS < x[1] and x[1] < dL+DOLFIN_EPS \ and -dL-DOLFIN_EPS < x[2] and x[2] < dL+DOLFIN_EPS def boundary(x, on_boundary): #not(boundary(x)) return on_boundary and ((0.5-DOLFIN_EPS >= x[0] \ or -dL-DOLFIN_EPS >= x[1] or x[1] >= dL+DOLFIN_EPS \ or -dL-DOLFIN_EPS >= x[2] or x[2] >= dL+DOLFIN_EPS)) def get_bnd_mesh(mesh): coords = mesh.coordinates() [bfaces, bfaces_IDs] = polyhedron_surfmesh(mesh) bcoords = (coords[bfaces[:, 0], :] + coords[bfaces[:, 1], :] + coords[bfaces[:, 2], :]) / 3. I = (bcoords[:,0] > 0.5-DOLFIN_EPS) & (bcoords[:,1] < dL) & (bcoords[:,1] > -dL) \ & (bcoords[:,2] < dL) & (bcoords[:,2] > -dL) I2 = (bcoords[:,0] > 0.5-DOLFIN_EPS) & (bcoords[:,1] < dL) & (bcoords[:,1] > -dL) \ & (bcoords[:,2] > dL) I3 = (bcoords[:,0] > 0.5-DOLFIN_EPS) & (bcoords[:,1] < dL) & (bcoords[:,1] > -dL) \ & (bcoords[:,2] < -dL) bfaces_IDs[I] = 97 if hax: bfaces_IDs[I2] = 98 bfaces_IDs[I3] = 99 #problems c1 = numpy.array([0.5, -dL, -dL]).repeat(coords.shape[0]).reshape( [3, coords.shape[0]]).T c2 = numpy.array([0.5, -dL, dL]).repeat(coords.shape[0]).reshape( [3, coords.shape[0]]).T c3 = numpy.array([0.5, dL, -dL]).repeat(coords.shape[0]).reshape( [3, coords.shape[0]]).T c4 = numpy.array([0.5, dL, dL]).repeat(coords.shape[0]).reshape( [3, coords.shape[0]]).T crnds = numpy.where((numpy.sqrt(((coords - c1)**2).sum(1)) < 1e3*DOLFIN_EPS) | \ (numpy.sqrt(((coords - c2)**2).sum(1)) < 1e3*DOLFIN_EPS) | \ (numpy.sqrt(((coords - c3)**2).sum(1)) < 1e3*DOLFIN_EPS) | \ (numpy.sqrt(((coords - c4)**2).sum(1)) < 1e3*DOLFIN_EPS))[0] # return [bfaces,bfaces_IDs,crnds] return [bfaces, bfaces_IDs] ### SETUP MESH mesh = BoxMesh(-0.5, -0.5, -0.5, 0.5, 0.5, 0.5, meshsz, meshsz, meshsz) fid = File("out.pvd") # PERFORM TEN ADAPTATION ITERATIONS for iii in range(Nadapt): V = FunctionSpace(mesh, "CG", 2) dis = TrialFunction(V) dus = TestFunction(V) u = Function(V) a = inner(grad(dis), grad(dus)) * dx boundaries = FacetFunction("size_t", mesh) Inlet = inlet() boundaries.set_all(0) Inlet.mark(boundaries, 1) ds = Measure("ds")[boundaries] L = dus * ds(1) #+dus*dx bc = DirichletBC(V, Constant(0.), boundary) solve(a == L, u, bc) fid << u startTime = time() H = metric_pnorm(u, eta, max_edge_length=2., max_edge_ratio=50, CG1out=True) #H = logproject(H) if iii != Nadapt - 1: [bfaces, bfaces_IDs] = get_bnd_mesh(mesh) mesh = adapt(H, bfaces=bfaces, bfaces_IDs=bfaces_IDs) log( INFO + 1, "total (adapt+metric) time was %0.1fs, nodes: %0.0f" % (time() - startTime, mesh.num_vertices())) plot(u, interactive=True) plot(mesh, interactive=True)
def ellipse_convergence(asp=2,width=1e-2, Nadapt=10, eta_list=0.04*pyexp2(-array(range(15))*pylog(2)/2), \ use_adapt=True, problem=2, outname='', CGorderL = [2, 3], noplot=False, octaveimpl=False): ### SETUP SOLUTION sx = Symbol('sx'); sy = Symbol('sy'); width_ = Symbol('ww'); asp_ = Symbol('a') rrpy = pysqrt(sx*sx/asp_+sy*sy*asp_) if problem == 2: stepfunc = 0.5+165./104./width_*(rrpy-0.25)-20./13./width_**3*(rrpy-0.25)**3-102./13./width_**5*(rrpy-0.25)**5+240./13./width_**7*(rrpy-0.25)**7 elif problem == 1: stepfunc = 0.5+15./8./width_*(rrpy-0.25)-5./width_**3*(rrpy-0.25)**3+6./width_**5*(rrpy-0.25)**5 else: stepfunc = 0.5+1.5/width_*(rrpy-0.25)-2/width_**3*(rrpy-0.25)**3 ddstepfunc = str(diff(stepfunc,sx,sx)+diff(stepfunc,sy,sy)).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') stepfunc = str(stepfunc).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') #REPLACE ** with pow stepfunc = stepfunc.replace('(a*(x[1]*x[1]) + (x[0]*x[0])/a)**(1/2)','sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a)') ddstepfunc = ddstepfunc.replace('(a*(x[1]*x[1]) + (x[0]*x[0])/a)**(1/2)','sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a)') ddstepfunc = ddstepfunc.replace('(a*(x[1]*x[1]) + (x[0]*x[0])/a)**(3/2)','pow(a*x[1]*x[1]+x[0]*x[0]/a,1.5)') ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**2','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,2.)') ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**3','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,3.)') ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**4','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,4.)') ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**5','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,5.)') ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**6','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,6.)') stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**3','pow(sqrt(a*x[1]*x[1] + x[0]*x[0]/a) - 0.25,3.)') stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**5','pow(sqrt(a*x[1]*x[1] + x[0]*x[0]/a) - 0.25,5.)') stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**7','pow(sqrt(a*x[1]*x[1] + x[0]*x[0]/a) - 0.25,7.)') testsol = '(0.25-ww/2<sqrt(x[0]*x[0]/a+x[1]*x[1]*a) && sqrt(x[0]*x[0]/a+x[1]*x[1]*a) < 0.25+ww/2 ? (' + stepfunc + ') : 0) + (0.25+ww/2<sqrt(x[0]*x[0]/a+x[1]*x[1]*a) ? 1 : 0)' # testsol = '(0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + stepfunc + ')) : (0.25<sqrt(x[0]*x[0]+x[1]*x[1]) ? 1 : 0)' ddtestsol = '0.25-ww/2<sqrt(x[0]*x[0]/a+x[1]*x[1]*a) && sqrt(x[0]*x[0]/a+x[1]*x[1]*a) < 0.25+ww/2 ? (' + ddstepfunc + ') : 0' # A = array([[0.5,0.5**3,0.5**5],[1,3*0.5**2,5*0.5**4],[0,6*0.5,20*0.5**3]]); b = array([0.5,0,0]) # from numpy.linalg import solve as pysolve #15/8,-5,6 # X = pysolve(A,b); from numpy import linspace; xx = linspace(-0.5,0.5,100) # from pylab import plot as pyplot; pyplot(xx,X[0]*xx+X[1]*xx**3+X[2]*xx**5,'-b') # rrpy = pysqrt(sx*sx+sy*sy) # # ddstepfunc = str(diff(stepfunc,sx,sx)+diff(stepfunc,sy,sy)).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') # stepfunc = str(stepfunc).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') # #REPLACE ** with pow # ddstepfunc = ddstepfunc.replace('(a*(x[1]*x[1]) + (x[0]*x[0])/a)**(3/2)','pow(a*x[1]*x[1]+x[0]*x[0]/a,1.5)') # ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**2','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,2.)') # ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**3','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,3.)') # ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**4','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,4.)') # stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**3','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,3.)') # stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**5','pow(sqrt(a*x[1]*x[1]+x[0]*x[0]/a) - 0.25,5.)') # testsol = '(0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + stepfunc + ') : 0) + (0.25+ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) ? 1 : 0)' ## testsol = '(0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + stepfunc + ')) : (0.25<sqrt(x[0]*x[0]+x[1]*x[1]) ? 1 : 0)' # ddtestsol = '0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + ddstepfunc + ') : 0' # else: # problem == 0: # rrpy = pysqrt(sx*sx+sy*sy) # #'if(t<2*WeMax,0,if(t<4*WeMax,0.5+3/2/(2*WeMax)*(t-3*WeMax)-2/(2*WeMax)^3*(t-3*WeMax)^3,1))'; %0.5+3/2/dx*(x-xc)-2/dx^3*(x-xc)^3 # ddstepfunc = str(diff(stepfunc,sx,sx)+diff(stepfunc,sy,sy)).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') # stepfunc = str(stepfunc).replace('sx','x[0]').replace('sy','x[1]').replace('x[0]**2','(x[0]*x[0])').replace('x[1]**2','(x[1]*x[1])') # #REPLACE ** with pow # ddstepfunc = ddstepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**2','pow(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25,2.)') # ddstepfunc = ddstepfunc.replace('(a*(x[1]*x[1]) + (x[0]*x[0])/a)**(3/2)','pow(a*(x[1]*x[1]) + (x[0]*x[0])/a,1.5)') # stepfunc = stepfunc.replace('(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25)**3','pow(sqrt(a*(x[1]*x[1]) + (x[0]*x[0])/a) - 0.25,3.)') # testsol = '0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + stepfunc + ') : (0.25<sqrt(x[0]*x[0]+x[1]*x[1]) ? 1 : 0)' # ddtestsol = '0.25-ww/2<sqrt(x[0]*x[0]+x[1]*x[1]) && sqrt(x[0]*x[0]+x[1]*x[1]) < 0.25+ww/2 ? (' + ddstepfunc + ') : 0' ddtestsol = ddtestsol.replace('a**2','(a*a)').replace('ww**2','(ww*ww)').replace('ww**3','pow(ww,3.)').replace('ww**4','pow(ww,4.)').replace('ww**5','pow(ww,5.)').replace('ww**6','pow(ww,6.)').replace('ww**7','pow(ww,7.)') testsol = testsol.replace('ww**2','(ww*ww)').replace('ww**3','pow(ww,3.)').replace('ww**5','pow(ww,5.)').replace('ww**7','pow(ww,7.)') ddtestsol = ddtestsol.replace('ww',str(width)).replace('a',str(asp)) testsol = testsol.replace('ww',str(width)).replace('a',str(asp)) ddtestsol = '-('+ddtestsol+')' def boundary(x): return x[0]+0.5 < DOLFIN_EPS or 0.5-x[0] < DOLFIN_EPS or x[1]+0.5 < DOLFIN_EPS or 0.5-x[1] < DOLFIN_EPS for CGorder in CGorderL: dofs = [] L2errors = [] #for eta in [0.16, 0.08, 0.04, 0.02, 0.01, 0.005, 0.0025] #, 0.0025/2, 0.0025/4, 0.0025/8]: # for eta in eta_list: ### SETUP MESH meshsz = int(round(80*0.005/(eta*(bool(use_adapt)==False)+0.05*(bool(use_adapt)==True)))) if (not bool(use_adapt)) and meshsz > 80: continue mesh = RectangleMesh(-0.0,-0.0,0.5*sqrt(asp),0.5/sqrt(asp),meshsz,meshsz,"left/right") # PERFORM TEN ADAPTATION ITERATIONS for iii in range(Nadapt): V = FunctionSpace(mesh, "CG", CGorder); dis = TrialFunction(V); dus = TestFunction(V); u = Function(V) #V2 = FunctionSpace(mesh, "CG", CGorder+2) R = Expression(ddtestsol) #interpolate(Expression(ddtestsol),V2) a = inner(grad(dis), grad(dus))*dx L = R*dus*dx bc = DirichletBC(V, Expression(testsol), boundary) #Constant(0.) solve(a == L, u, bc) if not bool(use_adapt): break H = metric_pnorm(u, eta, max_edge_ratio=1+49*(use_adapt!=2), p=2) H = logproject(H) if iii != Nadapt-1: mesh = adapt(H, octaveimpl=octaveimpl, debugon=False) L2error = errornorm(Expression(testsol), u, degree_rise=CGorder+2, norm_type='L2') dofs.append(len(u.vector().array())) L2errors.append(L2error) log(INFO+1,"%1dX ADAPT<->SOLVE complete: DOF=%5d, error=%0.0e" % (Nadapt, dofs[len(dofs)-1], L2error)) # PLOT MESH + solution figure() testf = interpolate(u ,FunctionSpace(mesh,'CG',1)) testfe = interpolate(Expression(testsol),FunctionSpace(mesh,'CG',1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG" ,1)) zz = testf.vector().array()[vtx2dof]; zz[zz==1] -= 1e-16 hh=tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100,cmap=get_cmap('binary')) colorbar(hh) axis('equal'); axis('off'); box('off'); xlim([0,0.5*sqrt(asp)]); ylim([0, 0.5/sqrt(asp)]); savefig('solution.png',dpi=300) figure() hold('on'); triplot(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),color='r',linewidth=0.5); hold('off') axis('equal'); box('off') axis('off'); xlim([0,0.5*sqrt(asp)]); ylim([0, 0.5/sqrt(asp)]) savefig(outname+'final_mesh_CG2.png',dpi=300) #; savefig('outname+final_mesh_CG2.eps',dpi=300) #PLOT ERROR figure() zz = pyabs(testf.vector().array()-testfe.vector().array())[vtx2dof]; zz[zz==1] -= 1e-16 hh=tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100,cmap=get_cmap('binary')) colorbar(hh); axis('equal'); box('off'); title('error') # PLOT L2error graph figure() pyloglog(dofs,L2errors,'-b.',linewidth=2,markersize=16); xlabel('Degree of freedoms'); ylabel('L2 error') # SAVE SOLUTION dofs = array(dofs); L2errors = array(L2errors) fid = open("DOFS_L2errors_CG"+str(CGorder)+outname+".mpy",'w') pickle.dump([dofs,L2errors],fid) fid.close(); #LOAD SAVED SOLUTIONS fid = open("DOFS_L2errors_CG2"+outname+".mpy",'r') [dofs,L2errors] = pickle.load(fid) fid.close() # PERFORM FITS ON LAST THREE POINTS NfitP = 9 I = array(range(len(dofs)-NfitP,len(dofs))) slope,ints = polyfit(pylog(dofs[I]), pylog(L2errors[I]), 1) if slope < -0.7: fid = open("DOFS_L2errors_CG2_fit"+outname+".mpy",'w') pickle.dump([dofs,L2errors,slope,ints],fid) fid.close() log(INFO+1,'succes') else: os.system('rm '+outname+'.lock') log(INFO+1,'fail') #PLOT THEM TOGETHER if CGorderL != [2]: fid = open("DOFS_L2errors_CG3.mpy",'r') [dofs_old,L2errors_old] = pickle.load(fid) fid.close() slope2,ints2 = polyfit(pylog(dofs_old[I]), pylog(L2errors_old[I]), 1) figure() pyloglog(dofs,L2errors,'-b.',dofs_old,L2errors_old,'--b.',linewidth=2,markersize=16) hold('on'); pyloglog(dofs,pyexp2(ints)*dofs**slope,'-r',dofs_old,pyexp2(ints2)*dofs_old**slope2,'--r',linewidth=1); hold('off') xlabel('Degree of freedoms'); ylabel('L2 error') legend(['CG2','CG3',"%0.2f*log(DOFs)" % slope, "%0.2f*log(DOFs)" % slope2]) #legend(['new data','old_data']) # savefig('comparison.png',dpi=300) #savefig('comparison.eps'); if not noplot: show()
def check_metric_ellipse(width=2e-2, eta=0.02, Nadapt=6): set_log_level(WARNING) parameters["allow_extrapolation"] = True ### CONSTANTS meshsz = 40 hd = Constant(width) ### SETUP MESH mesh = RectangleMesh(-0.5, -0.5, 0.5, 0.5, 1 * meshsz, 1 * meshsz, "left/right") ### SETUP SOLUTION angle = pi / 8 #rand()*pi/2 #testsol = 'tanh(x[0]/' + str(float(hd)) + ')' #tanh(x[0]/hd) testsol = 'tanh((' + str(cos(angle)) + '*x[0]+' + str( sin(angle)) + '*x[1])/' + str(float(hd)) + ')' #tanh(x[0]/hd) ddtestsol = str(cos(angle) + sin(angle) ) + '*2*' + testsol + '*(1-pow(' + testsol + ',2))/' + str( float(hd)**2) #testsol2 = 'tanh(x[1]/' + str(float(hd)) + ')' #tanh(x[0]/hd) testsol2 = 'tanh((' + str(cos(angle)) + '*x[1]-' + str( sin(angle)) + '*x[0])/' + str(float(hd)) + ')' #tanh(x[0]/hd) ddtestsol2 = str(cos(angle) - sin( angle)) + '*2*' + testsol2 + '*(1-pow(' + testsol2 + ',2))/' + str( float(hd)**2) def boundary(x): return x[0]-mesh.coordinates()[:,0].min() < DOLFIN_EPS or mesh.coordinates()[:,0].max()-x[0] < DOLFIN_EPS \ or mesh.coordinates()[:,1].min()+0.5 < DOLFIN_EPS or mesh.coordinates()[:,1].max()-x[1] < DOLFIN_EPS # PERFORM ONE ADAPTATION ITERATION for iii in range(Nadapt): V = FunctionSpace(mesh, "CG", 2) dis = TrialFunction(V) dus = TestFunction(V) u = Function(V) u2 = Function(V) bc = DirichletBC(V, Expression(testsol), boundary) bc2 = DirichletBC(V, Expression(testsol2), boundary) R = interpolate(Expression(ddtestsol), V) R2 = interpolate(Expression(ddtestsol2), V) a = inner(grad(dis), grad(dus)) * dx L = R * dus * dx L2 = R2 * dus * dx solve(a == L, u, bc) solve(a == L2, u2, bc2) H = metric_pnorm(u, eta, max_edge_length=1., max_edge_ratio=50) #Mp = project(H, TensorFunctionSpace(mesh, "CG", 1)) H2 = metric_pnorm(u2, eta, max_edge_length=1., max_edge_ratio=50) #Mp2 = project(H2, TensorFunctionSpace(mesh, "CG", 1)) H3 = metric_ellipse(H, H2) Mp3 = project(H3, TensorFunctionSpace(mesh, "CG", 1)) print("H11: %0.0f, H22: %0.0f, V: %0.0f,E: %0.0f" % (assemble(abs(H3[0, 0]) * dx), assemble( abs(H3[1, 1]) * dx), mesh.num_vertices(), mesh.num_cells())) startTime = time() if iii != 6: # mesh2 = Mesh(adapt(Mp2)) mesh = Mesh(adapt(Mp3)) # mesh3 = adapt(Mp) print("total time was %0.1fs" % (time() - startTime)) # PLOT MESH figure(1) triplot(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells()) axis('equal') axis('off') box('off') #figure(2); triplot(mesh2.coordinates()[:,0],mesh2.coordinates()[:,1],mesh2.cells()) #mesh = mesh2 #figure(3); triplot(mesh3.coordinates()[:,0],mesh3.coordinates()[:,1],mesh3.cells()) #mesh = mesh3 figure(4) testf = interpolate(u2, FunctionSpace(mesh, 'CG', 1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG", 1)) zz = testf.vector().array()[vtx2dof] zz[zz == 1] -= 1e-16 tricontourf(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), zz, 100) show()
def test_refine_metric(): # from mpi4py import MPI import sys # comm = MPI.COMM_WORLD # mesh = Mesh("greenland.xml.gz") mesh = UnitSquareMesh(100, 100) V = FunctionSpace(mesh, "CG", 2) f = interpolate( Expression( "0.1*sin(50.*(2*x[0]-1)) + atan2(-0.1, (2.0*(2*x[0]-1) - sin(5.*(2*x[1]-1))))" ), V) eta = 0.01 #Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) #mesh = adapt(Mp) if True: level = 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh1 = adapt(Mp) level *= 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh2 = adapt(Mp) level *= 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh3 = adapt(Mp) level *= 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh4 = adapt(Mp) level *= 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh5 = adapt(Mp) level *= 0.5 Mp = refine_metric(mesh_metric(mesh), level) new_mesh6 = adapt(Mp) else: eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh1 = adapt(Mp) eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh2 = adapt(Mp) eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh3 = adapt(Mp) eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh4 = adapt(Mp) eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh5 = adapt(Mp) eta *= 2 Mp = metric_pnorm(f, mesh, eta, max_edge_ratio=5) new_mesh6 = adapt(Mp) # plot(Mp[0,0]) # from IPython import embed # embed() plot(mesh, title="initial mesh") plot(new_mesh1, title="coarsen 1") plot(new_mesh2, title="coarsen 2") plot(new_mesh3, title="coarsen 3") plot(new_mesh4, title="coarsen 4") plot(new_mesh5, title="coarsen 5") plot(new_mesh6, title="coarsen 6") interactive()
def adv_convergence(width=2e-2, delta=1e-2, relp=1, Nadapt=10, use_adapt=True, problem=3, outname='', use_reform=False, CGorderL = [2, 3], noplot=False, Lx=3.): ### SETUP SOLUTION sy = Symbol('sy'); width_ = Symbol('ww') if problem == 3: stepfunc = 0.5+165./104./width_*sy-20./13./width_**3*sy**3-102./13./width_**5*sy**5+240./13./width_**7*sy**7 elif problem == 2: stepfunc = 0.5+15./8./width_*sy-5./width_**3*sy**3+6./width_**5*sy**5 elif problem == 1: stepfunc = 0.5+1.5/width_*sy-2/width_**3*sy**3 stepfunc = str(stepfunc).replace('sy','x[1]').replace('x[1]**2','(x[1]*x[1])') #REPLACE ** with pow stepfunc = stepfunc.replace('x[1]**3','pow(x[1],3.)') stepfunc = stepfunc.replace('x[1]**5','pow(x[1],5.)') stepfunc = stepfunc.replace('x[1]**7','pow(x[1],7.)') testsol = '(-ww/2 < x[1] && x[1] < ww/2 ? ' + stepfunc +' : 0) + (ww/2<x[1] ? 1 : 0)' testsol = testsol.replace('ww**2','(ww*ww)').replace('ww**3','pow(ww,3.)').replace('ww**5','pow(ww,5.)').replace('ww**7','pow(ww,7.)') testsol = testsol.replace('ww',str(width)) dp = Constant(1.) fac = Constant(1+2.*delta) delta = Constant(delta) def left(x, on_boundary): return x[0] + Lx/2. < DOLFIN_EPS def right(x, on_boundary): return x[0] - Lx/2. > -DOLFIN_EPS def top_bottom(x, on_boundary): return x[1] - 0.5 > -DOLFIN_EPS or x[1] + 0.5 < DOLFIN_EPS class Inletbnd(SubDomain): def inside(self, x, on_boundary): return x[0] + Lx/2. < DOLFIN_EPS for CGorder in [2]: #CGorderL: dofs = [] L2errors = [] for eta in 0.04*pyexp2(-array(range(9))*pylog(2)/2): ### SETUP MESH meshsz = int(round(80*0.005/(eta*(bool(use_adapt)==False)+0.05*(bool(use_adapt)==True)))) if not bool(use_adapt) and meshsz > 80: continue mesh = RectangleMesh(-Lx/2.,-0.5,Lx/2.,0.5,meshsz,meshsz,"left/right") # PERFORM TEN ADAPTATION ITERATIONS for iii in range(Nadapt): V = VectorFunctionSpace(mesh, "CG", CGorder); Q = FunctionSpace(mesh, "CG", CGorder-1) W = V*Q (u, p) = TrialFunctions(W) (v, q) = TestFunctions(W) alpha = Expression("-0.25<x[0] && x[0]<0.25 && 0. < x[1] ? 1e4 : 0") boundaries = FacetFunction("size_t",mesh) #outletbnd = Outletbnd() inletbnd = Inletbnd() boundaries.set_all(0) #outletbnd.mark(boundaries, 1) inletbnd.mark(boundaries, 1) ds = Measure("ds")[boundaries] bc0 = DirichletBC(W.sub(0), Constant((0., 0.)), top_bottom) bc1 = DirichletBC(W.sub(1), dp , left) bc2 = DirichletBC(W.sub(1), Constant(0), right) bc3 = DirichletBC(W.sub(0).sub(1), Constant(0.), left) bc4 = DirichletBC(W.sub(0).sub(1), Constant(0.), right) bcs = [bc0,bc1,bc2,bc3,bc4] bndterm = dp*dot(v,Constant((-1.,0.)))*ds(1) a = eta*inner(grad(u), grad(v))*dx - div(v)*p*dx + q*div(u)*dx+alpha*dot(u,v)*dx#+bndterm L = inner(Constant((0.,0.)), v)*dx -bndterm U = Function(W) solve(a == L, U, bcs) u, ps = U.split() #SOLVE CONCENTRATION mm = mesh_metric2(mesh) vdir = u/sqrt(inner(u,u)+DOLFIN_EPS) if iii == 0 or use_reform == False: Q2 = FunctionSpace(mesh,'CG',2); c = Function(Q2) q = TestFunction(Q2); p = TrialFunction(Q2) newq = (q+dot(vdir,dot(mm,vdir))*inner(grad(q),vdir)) #SUPG if use_reform: F = newq*(fac/((1+exp(-c))**2)*exp(-c))*inner(grad(c),u)*dx J = derivative(F,c) bc = DirichletBC(Q2, Expression("-log("+str(float(fac)) +"/("+testsol+"+"+str(float(delta))+")-1)"), left) # bc = DirichletBC(Q, -ln(fac/(Expression(testsol)+delta)-1), left) problem = NonlinearVariationalProblem(F,c,bc,J) solver = NonlinearVariationalSolver(problem) solver.parameters["newton_solver"]["relaxation_parameter"] = relp solver.solve() else: a2 = newq*inner(grad(p),u)*dx bc = DirichletBC(Q2, Expression(testsol), left) L2 = Constant(0.)*q*dx solve(a2 == L2, c, bc) if (not bool(use_adapt)) or iii == Nadapt-1: break um = project(sqrt(inner(u,u)),FunctionSpace(mesh,'CG',2)) H = metric_pnorm(um, eta, max_edge_ratio=1+49*(use_adapt!=2), p=2) H2 = metric_pnorm(c, eta, max_edge_ratio=1+49*(use_adapt!=2), p=2) #H3 = metric_pnorm(ps , eta, max_edge_ratio=1+49*(use_adapt!=2), p=2) H4 = metric_ellipse(H,H2) #H5 = metric_ellipse(H3,H4,mesh) mesh = adapt(H4) if use_reform: Q2 = FunctionSpace(mesh,'CG',2) c = interpolate(c,Q2) if use_reform: c = project(fac/(1+exp(-c))-delta,FunctionSpace(mesh,'CG',2)) L2error = bnderror(c,Expression(testsol),ds) dofs.append(len(c.vector().array())+len(U.vector().array())) L2errors.append(L2error) # fid = open("DOFS_L2errors_mesh_c_CG"+str(CGorder)+outname+".mpy",'w') # pickle.dump([dofs[0],L2errors[0],c.vector().array().min(),c.vector().array().max()-1,mesh.cells(),mesh.coordinates(),c.vector().array()],fid) # fid.close(); log(INFO+1,"%1dX ADAPT<->SOLVE complete: DOF=%5d, error=%0.0e, min(c)=%0.0e,max(c)-1=%0.0e" % (Nadapt, dofs[len(dofs)-1], L2error,c.vector().array().min(),c.vector().array().max()-1)) # PLOT MESH + solution figure() testf = interpolate(c ,FunctionSpace(mesh,'CG',1)) testfe = interpolate(Expression(testsol),FunctionSpace(mesh,'CG',1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG" ,1)) zz = testf.vector().array()[vtx2dof]; zz[zz==1] -= 1e-16 hh=tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100,cmap=get_cmap('binary')) colorbar(hh) hold('on'); triplot(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),color='r',linewidth=0.5); hold('off') axis('equal'); box('off') # savefig(outname+'final_mesh_CG2.png',dpi=300) #; savefig('outname+final_mesh_CG2.eps',dpi=300) #PLOT ERROR figure() xe = interpolate(Expression("x[0]"),FunctionSpace(mesh,'CG',1)).vector().array() ye = interpolate(Expression("x[1]"),FunctionSpace(mesh,'CG',1)).vector().array() I = xe - Lx/2 > -DOLFIN_EPS; I2 = ye[I].argsort() pyplot(ye[I][I2],testf.vector().array()[I][I2]-testfe.vector().array()[I][I2],'-b'); ylabel('error') # PLOT L2error graph figure() pyloglog(dofs,L2errors,'-b.',linewidth=2,markersize=16); xlabel('Degree of freedoms'); ylabel('L2 error') # SAVE SOLUTION dofs = array(dofs); L2errors = array(L2errors) fid = open("DOFS_L2errors_CG"+str(CGorder)+outname+".mpy",'w') pickle.dump([dofs,L2errors],fid) fid.close(); # #show() # #LOAD SAVED SOLUTIONS # fid = open("DOFS_L2errors_CG2"+outname+".mpy",'r') # [dofs,L2errors] = pickle.load(fid) # fid.close() # # PERFORM FITS ON LAST THREE POINTS NfitP = 5 I = array(range(len(dofs)-NfitP,len(dofs))) slope,ints = polyfit(pylog(dofs[I]), pylog(L2errors[I]), 1) fid = open("DOFS_L2errors_CG2_fit"+outname+".mpy",'w') pickle.dump([dofs,L2errors,slope,ints],fid) fid.close() #PLOT THEM TOGETHER if CGorderL != [2]: fid = open("DOFS_L2errors_CG3.mpy",'r') [dofs_old,L2errors_old] = pickle.load(fid) fid.close() slope2,ints2 = polyfit(pylog(dofs_old[I]), pylog(L2errors_old[I]), 1) figure() pyloglog(dofs,L2errors,'-b.',dofs_old,L2errors_old,'--b.',linewidth=2,markersize=16) hold('on'); pyloglog(dofs,pyexp2(ints)*dofs**slope,'-r',dofs_old,pyexp2(ints2)*dofs_old**slope2,'--r',linewidth=1); hold('off') xlabel('Degree of freedoms'); ylabel('L2 error') legend(['CG2','CG3',"%0.2f*log(DOFs)" % slope, "%0.2f*log(DOFs)" % slope2]) #legend(['new data','old_data']) # savefig('comparison.png',dpi=300) #savefig('comparison.eps'); if not noplot: show()
def minimal_example(width=2e-2, Nadapt=10, eta = 0.01): ### CONSTANTS meshsz = 40 hd = Constant(width) ### SETUP MESH mesh = RectangleMesh(Point(-0.5,-0.5),Point(0.5,0.5),1*meshsz,1*meshsz,"left/right") ### DERIVE FORCING TERM angle = pi/8 #rand*pi/2 sx = Symbol('sx'); sy = Symbol('sy'); width_ = Symbol('ww'); aa = Symbol('aa') testsol = pytanh((sx*pycos(aa)+sy*pysin(aa))/width_) ddtestsol = str(diff(testsol,sx,sx)+diff(testsol,sy,sy)).replace('sx','x[0]').replace('sy','x[1]') #replace ** with pow ddtestsol = ddtestsol.replace('tanh((x[0]*sin(aa) + x[1]*cos(aa))/ww)**2','pow(tanh((x[0]*sin(aa) + x[1]*cos(aa))/ww),2.)') ddtestsol = ddtestsol.replace('cos(aa)**2','pow(cos(aa),2.)').replace('sin(aa)**2','pow(sin(aa),2.)').replace('ww**2','(ww*ww)') #insert vaulues ddtestsol = ddtestsol.replace('aa',str(angle)).replace('ww',str(width)) testsol = str(testsol).replace('sx','x[0]').replace('sy','x[1]').replace('aa',str(angle)).replace('ww',str(width)) ddtestsol = "-("+ddtestsol+")" def boundary(x): return x[0]-mesh.coordinates()[:,0].min() < DOLFIN_EPS or mesh.coordinates()[:,0].max()-x[0] < DOLFIN_EPS \ or mesh.coordinates()[:,1].min()+0.5 < DOLFIN_EPS or mesh.coordinates()[:,1].max()-x[1] < DOLFIN_EPS # PERFORM TEN ADAPTATION ITERATIONS for iii in range(Nadapt): V = FunctionSpace(mesh, "CG" ,2); dis = TrialFunction(V); dus = TestFunction(V); u = Function(V) a = inner(grad(dis), grad(dus))*dx L = Expression(ddtestsol)*dus*dx bc = DirichletBC(V, Expression(testsol), boundary) solve(a == L, u, bc) startTime = time() H = metric_pnorm(u, eta, max_edge_length=3., max_edge_ratio=None) H = logproject(H) if iii != Nadapt-1: mesh = adapt(H) L2error = errornorm(Expression(testsol), u, degree_rise=4, norm_type='L2') log(INFO+1,"total (adapt+metric) time was %0.1fs, L2error=%0.0e, nodes: %0.0f" % (time()-startTime,L2error,mesh.num_vertices())) # # PLOT MESH # figure() coords = mesh.coordinates().transpose() # triplot(coords[0],coords[1],mesh.cells(),linewidth=0.1) # #savefig('mesh.png',dpi=300) #savefig('mesh.eps'); figure() #solution testf = interpolate(Expression(testsol),FunctionSpace(mesh,'CG',1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG" ,1)) zz = testf.vector().array()[vtx2dof] hh=tricontourf(coords[0],coords[1],mesh.cells(),zz,100) colorbar(hh) # savefig('solution.png',dpi=300) #savefig('solution.eps'); figure() #analytical solution testfe = interpolate(u,FunctionSpace(mesh,'CG',1)) zz = testfe.vector().array()[vtx2dof] hh=tricontourf(coords[0],coords[1],mesh.cells(),zz,100) colorbar(hh) #savefig('analyt.png',dpi=300) #savefig('analyt.eps'); figure() #error zz -= testf.vector().array()[vtx2dof]; zz[zz==1] -= 1e-16 hh=tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100,cmap=get_cmap('binary')) colorbar(hh) hold('on'); triplot(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),color='r',linewidth=0.5); hold('off') axis('equal'); box('off'); title('error') show()
def maximal_example(eta_list=array([0.001]), Nadapt=5, timet=1., period=2 * pi): ### CONSTANTS ### SETUP SOLUTION #testsol = '0.1*sin(50*x+2*pi*t/T)+atan(-0.1/(2*x - sin(5*y+2*pi*t/T)))'; sx = Symbol('sx') sy = Symbol('sy') sT = Symbol('sT') st = Symbol('st') spi = Symbol('spi') testsol = 0.1 * pysin(50 * sx + 2 * spi * st / sT) + pyatan( -0.1, 2 * sx - pysin(5 * sy + 2 * spi * st / sT)) ddtestsol = str(diff(testsol, sx, sx) + diff(testsol, sy, sy)).replace( 'sx', 'x[0]').replace('sy', 'x[1]').replace('spi', 'pi') # replacing **P with pow(,P) ddtestsol = ddtestsol.replace("(2*x[0] - sin(5*x[1] + 2*pi*st/sT))**2", "pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.)") ddtestsol = ddtestsol.replace("cos(5*x[1] + 2*pi*st/sT)**2", "pow(cos(5*x[1] + 2*pi*st/sT),2.)") ddtestsol = ddtestsol.replace( "(pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.) + 0.01)**2", "pow((pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.) + 0.01),2.)") ddtestsol = ddtestsol.replace( "(1 + 0.01/pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.))**2", "pow(1 + 0.01/pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.),2.)") ddtestsol = ddtestsol.replace("(2*x[0] - sin(5*x[1] + 2*pi*st/sT))**5", "pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),5.)") #insert values ddtestsol = ddtestsol.replace('sT', str(period)).replace('st', str(timet)) testsol = str(testsol).replace('sx', 'x[0]').replace('sy', 'x[1]').replace( 'spi', 'pi').replace('sT', str(period)).replace('st', str(timet)) ddtestsol = "-(" + ddtestsol + ")" error_list = [] dof_list = [] for eta in eta_list: meshsz = 40 ### SETUP MESH # mesh = RectangleMesh(0.4,-0.1,0.6,0.3,1*meshsz,1*meshsz,"left/right") #shock # mesh = RectangleMesh(-0.75,-0.3,-0.3,0.5,1*meshsz,1*meshsz,"left/right") #waves mesh = RectangleMesh(-1.5, -0.25, 0.5, 0.75, 1 * meshsz, 1 * meshsz, "left/right") #shock+waves def boundary(x): return near(x[0],mesh.coordinates()[:,0].min()) or near(x[0],mesh.coordinates()[:,0].max()) \ or near(x[1],mesh.coordinates()[:,1].min()) or near(x[1],mesh.coordinates()[:,1].max()) # PERFORM ONE ADAPTATION ITERATION for iii in range(Nadapt): startTime = time() V = FunctionSpace(mesh, "CG", 2) dis = TrialFunction(V) dus = TestFunction(V) u = Function(V) # R = interpolate(Expression(ddtestsol),V) a = inner(grad(dis), grad(dus)) * dx L = Expression(ddtestsol) * dus * dx # bc = DirichletBC(V, Expression(testsol), boundary) solve(a == L, u, bc) soltime = time() - startTime startTime = time() H = metric_pnorm(u, eta, max_edge_ratio=50, CG0H=3, p=4) metricTime = time() - startTime if iii != Nadapt - 1: mesh = adapt(H) TadaptTime = time() - startTime L2error = errornorm(Expression(testsol), u, degree_rise=4, norm_type='L2') printstr = "%5.0f elements, %0.0e L2error, adapt took %0.0f %% of the total time, (%0.0f %% of which was the metric calculation)" \ % (mesh.num_cells(),L2error,TadaptTime/(TadaptTime+soltime)*100,metricTime/TadaptTime*100) if len(eta_list) == 1: print(printstr) else: error_list.append(L2error) dof_list.append(len(u.vector().array())) print(printstr) if len(dof_list) > 1: dof_list = array(dof_list) error_list = array(error_list) figure() loglog(dof_list, error_list, '.b-', linewidth=2, markersize=16) xlabel('Degree of freedoms') ylabel('L2 error') # # PLOT MESH # figure() coords = mesh.coordinates().transpose() # triplot(coords[0],coords[1],mesh.cells(),linewidth=0.1) # #savefig('mesh.png',dpi=300) #savefig('mesh.eps'); figure() #solution testf = interpolate(Expression(testsol), FunctionSpace(mesh, 'CG', 1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG", 1)) zz = testf.vector().array()[vtx2dof] hh = tricontourf(coords[0], coords[1], mesh.cells(), zz, 100) colorbar(hh) #savefig('solution.png',dpi=300) #savefig('solution.eps'); figure() #analytical solution testfe = interpolate(u, FunctionSpace(mesh, 'CG', 1)) zz = testfe.vector().array()[vtx2dof] hh = tricontourf(coords[0], coords[1], mesh.cells(), zz, 100) colorbar(hh) #savefig('analyt.png',dpi=300) #savefig('analyt.eps'); figure() #error zz -= testf.vector().array()[vtx2dof] zz[zz == 1] -= 1e-16 hh = tricontourf(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), zz, 100, cmap=get_cmap('binary')) colorbar(hh) hold('on') triplot(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), color='r', linewidth=0.5) hold('off') axis('equal') box('off') title('error') show()
def minimal_example(width=2e-2, Nadapt=10, eta=0.01): ### CONSTANTS meshsz = 40 hd = Constant(width) ### SETUP MESH mesh = RectangleMesh(Point(-0.5, -0.5), Point(0.5, 0.5), 1 * meshsz, 1 * meshsz, "left/right") ### DERIVE FORCING TERM angle = pi / 8 #rand*pi/2 sx = Symbol('sx') sy = Symbol('sy') width_ = Symbol('ww') aa = Symbol('aa') testsol = pytanh((sx * pycos(aa) + sy * pysin(aa)) / width_) ddtestsol = str(diff(testsol, sx, sx) + diff(testsol, sy, sy)).replace( 'sx', 'x[0]').replace('sy', 'x[1]') #replace ** with pow ddtestsol = ddtestsol.replace( 'tanh((x[0]*sin(aa) + x[1]*cos(aa))/ww)**2', 'pow(tanh((x[0]*sin(aa) + x[1]*cos(aa))/ww),2.)') ddtestsol = ddtestsol.replace('cos(aa)**2', 'pow(cos(aa),2.)').replace( 'sin(aa)**2', 'pow(sin(aa),2.)').replace('ww**2', '(ww*ww)') #insert vaulues ddtestsol = ddtestsol.replace('aa', str(angle)).replace('ww', str(width)) testsol = str(testsol).replace('sx', 'x[0]').replace('sy', 'x[1]').replace( 'aa', str(angle)).replace('ww', str(width)) ddtestsol = "-(" + ddtestsol + ")" def boundary(x): return x[0]-mesh.coordinates()[:,0].min() < DOLFIN_EPS or mesh.coordinates()[:,0].max()-x[0] < DOLFIN_EPS \ or mesh.coordinates()[:,1].min()+0.5 < DOLFIN_EPS or mesh.coordinates()[:,1].max()-x[1] < DOLFIN_EPS # PERFORM TEN ADAPTATION ITERATIONS for iii in range(Nadapt): V = FunctionSpace(mesh, "CG", 2) dis = TrialFunction(V) dus = TestFunction(V) u = Function(V) a = inner(grad(dis), grad(dus)) * dx L = Expression(ddtestsol) * dus * dx bc = DirichletBC(V, Expression(testsol), boundary) solve(a == L, u, bc) startTime = time() H = metric_pnorm(u, eta, max_edge_length=3., max_edge_ratio=None) H = logproject(H) if iii != Nadapt - 1: mesh = adapt(H) L2error = errornorm(Expression(testsol), u, degree_rise=4, norm_type='L2') log( INFO + 1, "total (adapt+metric) time was %0.1fs, L2error=%0.0e, nodes: %0.0f" % (time() - startTime, L2error, mesh.num_vertices())) # # PLOT MESH # figure() coords = mesh.coordinates().transpose() # triplot(coords[0],coords[1],mesh.cells(),linewidth=0.1) # #savefig('mesh.png',dpi=300) #savefig('mesh.eps'); figure() #solution testf = interpolate(Expression(testsol), FunctionSpace(mesh, 'CG', 1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG", 1)) zz = testf.vector().array()[vtx2dof] hh = tricontourf(coords[0], coords[1], mesh.cells(), zz, 100) colorbar(hh) # savefig('solution.png',dpi=300) #savefig('solution.eps'); figure() #analytical solution testfe = interpolate(u, FunctionSpace(mesh, 'CG', 1)) zz = testfe.vector().array()[vtx2dof] hh = tricontourf(coords[0], coords[1], mesh.cells(), zz, 100) colorbar(hh) #savefig('analyt.png',dpi=300) #savefig('analyt.eps'); figure() #error zz -= testf.vector().array()[vtx2dof] zz[zz == 1] -= 1e-16 hh = tricontourf(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), zz, 100, cmap=get_cmap('binary')) colorbar(hh) hold('on') triplot(mesh.coordinates()[:, 0], mesh.coordinates()[:, 1], mesh.cells(), color='r', linewidth=0.5) hold('off') axis('equal') box('off') title('error') show()
def maximal_example(eta_list = array([0.001]), Nadapt=5, timet=1., period=2*pi): ### CONSTANTS ### SETUP SOLUTION #testsol = '0.1*sin(50*x+2*pi*t/T)+atan(-0.1/(2*x - sin(5*y+2*pi*t/T)))'; sx = Symbol('sx'); sy = Symbol('sy'); sT = Symbol('sT'); st = Symbol('st'); spi = Symbol('spi') testsol = 0.1*pysin(50*sx+2*spi*st/sT)+pyatan(-0.1,2*sx - pysin(5*sy+2*spi*st/sT)) ddtestsol = str(diff(testsol,sx,sx)+diff(testsol,sy,sy)).replace('sx','x[0]').replace('sy','x[1]').replace('spi','pi') # replacing **P with pow(,P) ddtestsol = ddtestsol.replace("(2*x[0] - sin(5*x[1] + 2*pi*st/sT))**2","pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.)") ddtestsol = ddtestsol.replace("cos(5*x[1] + 2*pi*st/sT)**2","pow(cos(5*x[1] + 2*pi*st/sT),2.)") ddtestsol = ddtestsol.replace("(pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.) + 0.01)**2","pow((pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.) + 0.01),2.)") ddtestsol = ddtestsol.replace("(1 + 0.01/pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.))**2","pow(1 + 0.01/pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),2.),2.)") ddtestsol = ddtestsol.replace("(2*x[0] - sin(5*x[1] + 2*pi*st/sT))**5","pow(2*x[0] - sin(5*x[1] + 2*pi*st/sT),5.)") #insert values ddtestsol = ddtestsol.replace('sT',str(period)).replace('st',str(timet)) testsol = str(testsol).replace('sx','x[0]').replace('sy','x[1]').replace('spi','pi').replace('sT',str(period)).replace('st',str(timet)) ddtestsol = "-("+ddtestsol+")" error_list = []; dof_list = [] for eta in eta_list: meshsz = 40 ### SETUP MESH # mesh = RectangleMesh(0.4,-0.1,0.6,0.3,1*meshsz,1*meshsz,"left/right") #shock # mesh = RectangleMesh(-0.75,-0.3,-0.3,0.5,1*meshsz,1*meshsz,"left/right") #waves mesh = RectangleMesh(-1.5,-0.25,0.5,0.75,1*meshsz,1*meshsz,"left/right") #shock+waves def boundary(x): return near(x[0],mesh.coordinates()[:,0].min()) or near(x[0],mesh.coordinates()[:,0].max()) \ or near(x[1],mesh.coordinates()[:,1].min()) or near(x[1],mesh.coordinates()[:,1].max()) # PERFORM ONE ADAPTATION ITERATION for iii in range(Nadapt): startTime = time() V = FunctionSpace(mesh, "CG" ,2); dis = TrialFunction(V); dus = TestFunction(V); u = Function(V) # R = interpolate(Expression(ddtestsol),V) a = inner(grad(dis), grad(dus))*dx L = Expression(ddtestsol)*dus*dx # bc = DirichletBC(V, Expression(testsol), boundary) solve(a == L, u, bc) soltime = time()-startTime startTime = time() H = metric_pnorm(u, eta, max_edge_ratio=50, CG0H=3, p=4) metricTime = time()-startTime if iii != Nadapt-1: mesh = adapt(H) TadaptTime = time()-startTime L2error = errornorm(Expression(testsol), u, degree_rise=4, norm_type='L2') printstr = "%5.0f elements, %0.0e L2error, adapt took %0.0f %% of the total time, (%0.0f %% of which was the metric calculation)" \ % (mesh.num_cells(),L2error,TadaptTime/(TadaptTime+soltime)*100,metricTime/TadaptTime*100) if len(eta_list) == 1: print(printstr) else: error_list.append(L2error); dof_list.append(len(u.vector().array())) print(printstr) if len(dof_list) > 1: dof_list = array(dof_list); error_list = array(error_list) figure() loglog(dof_list,error_list,'.b-',linewidth=2,markersize=16); xlabel('Degree of freedoms'); ylabel('L2 error') # # PLOT MESH # figure() coords = mesh.coordinates().transpose() # triplot(coords[0],coords[1],mesh.cells(),linewidth=0.1) # #savefig('mesh.png',dpi=300) #savefig('mesh.eps'); figure() #solution testf = interpolate(Expression(testsol),FunctionSpace(mesh,'CG',1)) vtx2dof = vertex_to_dof_map(FunctionSpace(mesh, "CG" ,1)) zz = testf.vector().array()[vtx2dof] hh=tricontourf(coords[0],coords[1],mesh.cells(),zz,100) colorbar(hh) #savefig('solution.png',dpi=300) #savefig('solution.eps'); figure() #analytical solution testfe = interpolate(u,FunctionSpace(mesh,'CG',1)) zz = testfe.vector().array()[vtx2dof] hh=tricontourf(coords[0],coords[1],mesh.cells(),zz,100) colorbar(hh) #savefig('analyt.png',dpi=300) #savefig('analyt.eps'); figure() #error zz -= testf.vector().array()[vtx2dof]; zz[zz==1] -= 1e-16 hh=tricontourf(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),zz,100,cmap=get_cmap('binary')) colorbar(hh) hold('on'); triplot(mesh.coordinates()[:,0],mesh.coordinates()[:,1],mesh.cells(),color='r',linewidth=0.5); hold('off') axis('equal'); box('off'); title('error') show()