def plot_mesh(pts, tri, *args): if len(args) > 0: tripcolor(pts[:, 0], pts[:, 1], tri, args[0], edgecolor="black", cmap="Blues") else: triplot(pts[:, 0], pts[:, 1], tri, "k-", lw=2) axis("tight") axes().set_aspect("equal")
def uniform_mesh_info(ns): """ A2.4 Page 69. """ h = 1 / ns x = np.linspace(0, 1, ns + 1) y = np.copy(x) # co-ordinates of vertices xv, yv = np.meshgrid(x, y) xv = xv.ravel() yv = yv.ravel() n2 = ns * ns nvtx = (ns + 1) * (ns + 1) ne = 2 * n2 # global vertex labels of individual elements elt2vert = np.zeros((ne, 3), dtype='int') vv = np.reshape(np.arange(0, nvtx), (ns + 1, ns + 1), order='F') v1 = vv[0:ns, 0:ns] v2 = vv[1:, 0:ns] v3 = vv[0:ns, 1:] elt2vert[0:n2, :] = np.vstack((v1.ravel(), v2.ravel(), v3.ravel())).T v1 = vv[1:, 1:] elt2vert[n2:, :] = np.vstack((v1.ravel(), v3.ravel(), v2.ravel())).T plt.figure(2) # ch0.PlotSetup() plt.axis('equal') plt.triplot(xv.ravel(), yv.ravel(), elt2vert, 'k-') plt.xlabel(r'$x_1$') plt.ylabel(r'$x_2$') return xv, yv, elt2vert, nvtx, ne, h
def plot_tri_mesh(pts, tri): triplot(pts[:, 0], pts[:, 1], tri, "k-", lw=2) if len(pts) < 200: for k, p in enumerate(pts): text(p[0], p[1], "%d" % k, color="black", fontsize=10, bbox=dict(boxstyle="round", fc="white"), horizontalalignment='center', verticalalignment='center') if len(tri) < 400: for k in xrange(tri.shape[0]): center = pts[tri[k]].sum(axis=0) / 3.0 text(center[0], center[1], "%d" % k, color="black", fontsize=8, horizontalalignment='center', verticalalignment='center')
def get_distances(points): max_pos = points tri = scipy.spatial.Delaunay(max_pos) pylab.triplot(max_pos[:,0], max_pos[:,1], tri.simplices.copy()) pylab.plot(max_pos[:,0], max_pos[:,1], 'ro') plt.show() edges = [] wholeSize = 0 for triangle in tri.simplices: vertice0=max_pos[triangle[0]] vertice1=max_pos[triangle[1]] vertice2=max_pos[triangle[2]] """ edge0 = math.sqrt(pow(vertice0[0] - vertice1[0], 2) + pow(vertice0[1] - vertice1[1], 2)) edge1 = math.sqrt(pow(vertice1[0] - vertice2[0], 2) + pow(vertice1[1] - vertice2[1], 2)) edge2 = math.sqrt(pow(vertice2[0] - vertice0[0], 2) + pow(vertice2[1] - vertice0[1], 2)) """ edge0 = np.linalg.norm(vertice0-vertice1) edge1 = np.linalg.norm(vertice2-vertice1) edge2 = np.linalg.norm(vertice0-vertice2) edges.append(edge0) edges.append(edge1) edges.append(edge2) wholeSize += edge0 + edge1 + edge2 edges = np.array(edges) print("mean: " + str(np.mean(edges))) print("standard deviation: " + str(np.std(edges))) print("maximum: " + str(np.ndarray.max(edges))) print("minimum: " + str(np.ndarray.min(edges))) print(wholeSize) return edges
def plotmesh(pts, tri, *args, **kwargs): showindex = kwargs.get('index', False) h0 = kwargs.get('h0', 0.0) edges = kwargs.get('edges', np.array([])) if len(args) > 0: tripcolor(pts[:, 0], pts[:, 1], tri, args[0], edgecolor='black', cmap="Blues") else: triplot(pts[:, 0], pts[:, 1], tri, "k-", lw=2) if showindex: dx = h0 / 10.0 for i in range(np.shape(tri)[0]): # label triangle index in green x = np.sum(pts[tri[i, :], 0]) / 3.0 y = np.sum(pts[tri[i, :], 1]) / 3.0 text(x, y, '%d' % i, color='g') for j in range(np.shape(pts)[0]): # label point index in blue text(pts[j, 0] + dx, pts[j, 1] + dx, '%d' % j, color='b') if len(edges) > 0: for k in range(np.shape(edges)[0]): # label edge index in red x = np.sum(pts[edges[k, :], 0]) / 2.0 y = np.sum(pts[edges[k, :], 1]) / 2.0 text(x + dx, y - dx, '%d' % k, color='r') axis('tight') axis('equal')
def plot_mesh(pts, tri, *args): if len(args) > 0: tripcolor(pts[:,0], pts[:,1], tri, args[0], edgecolor='black', cmap="Blues") else: triplot(pts[:,0], pts[:,1], tri, "k-", lw=2) axis('tight') axes().set_aspect('equal')
def plotMesh(self): import pylab as plt import matplotlib.tri as tri vertexCoords = self.mesh.vertexCoords vertexIDs = self.mesh._orderedCellVertexIDs plt.figure(figsize=(8, 8)) plotMesh = tri.Triangulation(vertexCoords[0], vertexCoords[1], np.transpose(vertexIDs)) plt.triplot(plotMesh) plt.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(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 plot_mesh(pts, tri, *args): if len(args) > 0: tripcolor(pts[:, 0], pts[:, 1], tri, args[0], edgecolor='black', cmap="Blues") else: triplot(pts[:, 0], pts[:, 1], tri, "k-", lw=2) axis('tight') axes().set_aspect('equal')
def plot_tri_mesh(pts, tri): triplot(pts[:,0], pts[:,1], tri, "k-", lw=2) if len(pts) < 200: for k,p in enumerate(pts): text(p[0], p[1], "%d" % k, color="black", fontsize=10, bbox=dict(boxstyle = "round", fc = "white"), horizontalalignment='center', verticalalignment='center') if len(tri) < 400: for k in xrange(tri.shape[0]): center = pts[tri[k]].sum(axis=0) / 3.0 text(center[0], center[1], "%d" % k, color="black", fontsize=8, horizontalalignment='center', verticalalignment='center')
def anneal(self, T, m, epsilon, verbose=True, graphics=False, pause=False): step = 0 while not self.anneal_step(m, T): T = (1.0 - epsilon) * T step += m if graphics or verbose: ilo = self.y.argsort()[0] ihi = self.y.argsort()[-1] if graphics: if len(gca().patches) >= 1: del gca().patches[-1:] if len(gca().lines) >= 1: del gca().lines[-1] triplot(ds.p[:, 0], ds.p[:, 1], 'r.--') draw() if pause: raw_input('continue...') if verbose: print 'step %d temperature %f x %s y %f' % ( step, T, self.p[ilo, :], self.y[ilo])
def plotmesh(pts, tri, *args, **kwargs): showindex = kwargs.get('index',False) h0 = kwargs.get('h0',0.0) edges = kwargs.get('edges',np.array([])) if len(args) > 0: tripcolor(pts[:,0], pts[:,1], tri, args[0], edgecolor='black', cmap="Blues") else: triplot(pts[:,0], pts[:,1], tri, "k-", lw=2) if showindex: dx = h0/10.0 for i in range(np.shape(tri)[0]): # label triangle index in green x = np.sum(pts[tri[i,:],0]) / 3.0 y = np.sum(pts[tri[i,:],1]) / 3.0 text(x,y,'%d' % i, color='g') for j in range(np.shape(pts)[0]): # label point index in blue text(pts[j,0]+dx,pts[j,1]+dx,'%d' % j, color='b') if len(edges) > 0: for k in range(np.shape(edges)[0]): # label edge index in red x = np.sum(pts[edges[k,:],0]) / 2.0 y = np.sum(pts[edges[k,:],1]) / 2.0 text(x+dx,y-dx,'%d' % k, color='r') axis('tight') axis('equal')
tf.write('\t\t</vertices>\n\t\t<cells size="%d">\n' % num_triangles) for i in range(0, num_triangles): tf.write('\t\t\t<triangle index="%d" v0="%d" v1="%d" v2="%d"/>\n' % (i, t[i,0], t[i,1], t[i,2])) tf.write('\t\t</cells>\n\t</mesh>\n</dolfin>') # 'Testcase' def _t_phi(x): """ Signed distance function the unit circle. """ return np.maximum(np.sqrt(np.sum(x*x, 1))-1.0, -np.sqrt(np.sum(x*x, 1))+0.5) _t_bbox = np.array([[-1., -1.],[1., 1.]]) if __name__ == '__main__': import pylab as py p, t = distmesh2d(_t_phi, 0.05, _t_bbox) export_xml(p, t, "unit_circle.xml") export_vtk(p, t, "unit_circle.vtk") export_pgf(p, t, "unit_circle.patches") py.triplot(p[:,0], p[:,1], t) py.show()
#!/usr/bin/env python import PylabUtils as plu import pylab from scipy.spatial import Delaunay points = pylab.rand (200, 2) # plot the raw points pylab.figure () pylab.scatter (points[:,0], points[:,1]) # compute and show the triangulated points tri = Delaunay (points) pylab.figure () pylab.triplot(points[:,0], points[:,1], tri.simplices.copy()) pylab.plot(points[:,0], points[:,1], 'o') # compute and show the alpha-shape alphaInds = plu.triang.alphaShape (tri, alpha=0.2, removeNeighbors=True) pylab.figure () pylab.triplot(points[:,0], points[:,1], tri.simplices[alphaInds, :].copy()) pylab.plot(points[:,0], points[:,1], 'o') # compute and show the border ("concave hull") (edgeX, edgeY, borderInds) = plu.triang.border (tri, inds=alphaInds) pylab.figure () pylab.scatter (points[:,0], points[:,1]) plu.plotting.plotLines (edgeX, edgeY, 'r') pylab.show ()
pylab.title("delaunay.Triangulation: linear interp") # delaunay - nearest neighbors interpolation pylab.subplot(2, 2, 3, sharex=ax1, sharey=ax1) d = tri_to_delaunay(mt) nn_interp = d.nn_interpolator(vals) nn_field = nn_interp[0.0:1.0:100j, 0.0:1.0:100j] pylab.imshow(nn_field, origin="lower", extent=[0, 1, 0, 1], interpolation="nearest") pylab.title("delaunay.Triangulation: nearest_nbr interp") # make the full rounds and show topology pylab.subplot(2, 2, 4, sharex=ax1, sharey=ax1) d = tri_to_delaunay(mt) if CGAL: cg = delaunay_to_cgal(d) # just for fun, insert one constrained edge - ll = np.argmin(d.x + d.y) ur = np.argmax(d.x + d.y) cg.insert_constraint(cg.vh[ll], cg.vh[ur]) mt3 = cgal_to_tri(cg) pylab.title("With and without constrained edge") else: mt3 = delaunay_to_tri(d) pylab.title("Roundtrip to delaunay and back") pylab.triplot(mt, lw=2.0, color="b") pylab.triplot(mt3, color="r", lw=1.0) pylab.axis("equal") pylab.show()
#!/usr/bin/env python import PylabUtils as plu import pylab from scipy.spatial import Delaunay points = pylab.rand(200, 2) # plot the raw points pylab.figure() pylab.scatter(points[:, 0], points[:, 1]) # compute and show the triangulated points tri = Delaunay(points) pylab.figure() pylab.triplot(points[:, 0], points[:, 1], tri.simplices.copy()) pylab.plot(points[:, 0], points[:, 1], 'o') # compute and show the alpha-shape alphaInds = plu.triang.alphaShape(tri, alpha=0.2, removeNeighbors=True) pylab.figure() pylab.triplot(points[:, 0], points[:, 1], tri.simplices[alphaInds, :].copy()) pylab.plot(points[:, 0], points[:, 1], 'o') # compute and show the border ("concave hull") (edgeX, edgeY, borderInds) = plu.triang.border(tri, inds=alphaInds) pylab.figure() pylab.scatter(points[:, 0], points[:, 1]) plu.plotting.plotLines(edgeX, edgeY, 'r') pylab.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()
plt.imshow(dataset_queenframe) plt.show() magn = dataset_queenframe print(dataset_cleanqueen.value) values, counts = np.unique(dataset_cleanqueen, return_counts=True) print(counts) #counts = counts/100000 counts = np.array(np.delete(counts,0)) max_pos = scipy.ndimage.center_of_mass(magn, labels=dataset_cleanqueen.value, index = np.arange(1, dataset_cleanqueen.value.max() + 1)) max_pos = np.array(max_pos, int) plt.scatter(max_pos[:,1], max_pos[:,0]) plt.show() tri = scipy.spatial.Delaunay(max_pos) pylab.triplot(max_pos[:,1], max_pos[:,0], tri.simplices.copy()) pylab.plot(max_pos[:,1], max_pos[:,0], 'ro') plt.show() wholeSize = 0 for triangle in tri.simplices: vertice0=max_pos[triangle[0]] vertice1=max_pos[triangle[1]] vertice2=max_pos[triangle[2]] edge0 = math.sqrt(pow(vertice0[0] - vertice1[0], 2) + pow(vertice0[1] - vertice1[1], 2)) edge1 = math.sqrt(pow(vertice1[0] - vertice2[0], 2) + pow(vertice1[1] - vertice2[1], 2)) edge2 = math.sqrt(pow(vertice2[0] - vertice0[0], 2) + pow(vertice2[1] - vertice0[1], 2)) wholeSize += edge0 + edge1 + edge2 print(wholeSize)
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 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()
import matplotlib.tri as mtri print((X.shape)) print((X.size)) points = np.zeros((X.size, 2)) points[:, 0] = X.reshape(X.size) points[:, 1] = Y.reshape(Y.size) tess = Delaunay(points) tri = tess.vertices # or tess.simplices depending on scipy version triang = mtri.Triangulation(x=points[:, 0], y=points[:, 1], triangles=tri) # pl.contourf(X, Y, Xi1) pl.colorbar() # pl.scatter(X,Y,marker='-') pl.triplot(triang, lw=0.5, color="white") pl.axis("equal") pl.title("SCALED MESH : chi1 with arbitrary degree and general hex mesh") pl.show(block=True) # ****************++ # Xi1 = boxspline(X,Y,1) # from mpl_toolkits.mplot3d import Axes3D # from matplotlib import cm # from matplotlib.ticker import LinearLocator, FormatStrFormatter # import matplotlib.pyplot as plt # import numpy as np
from PIL import Image from scipy import ndimage import numpy as np import pylab as plt import matplotlib.tri as md """ Delaunay triangulation as described in the book doesn't seem to work anymore. This instead uses the Triangulation function in the matplotlib.tri library. https://codeloop.org/python-matplotlib-plotting-triangulation/ https://matplotlib.org/3.1.0/api/tri_api.html """ x,y = np.array(np.random.standard_normal((2,100))) """ I'm not sure how this "triangles" output works. It does contain an array "triangles" that contains arrays of 3 integers. My guess is the three integers are the indices of the input x,y arrays that correspond to the 3 vertices of the triangle. """ triangles = md.Triangulation(x,y) plt.figure() # https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.triplot.html plt.triplot(triangles) plt.axis('off') plt.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()
x_list = numpy.random.random(7) y_list = numpy.random.random(7) p_list = [[39.82822367, -121.02163792], [39.5625, -121.4666], [39.6406, -120.6566], [39.5794, -121.0448], [39.5577, -120.6566], [39.5577, -121.4666], [39.5794, -121.0448]] for i in range(len(p_list)): x_list[i] = p_list[i][0] y_list[i] = p_list[i][1] tri = scipy.spatial.Delaunay( numpy.array([[x, y] for x, y in zip(x_list, y_list)])) for j in range(len(p_list)): pylab.subplot(2, len(p_list) - 3, j + 1) pindex = j neighbor_indices = find_neighbors(pindex, tri) print(neighbor_indices) for i in range(len(x_list)): pylab.triplot(x_list, y_list, tri.simplices.copy()) pylab.plot(x_list, y_list, 'b.') pylab.plot(x_list[pindex], y_list[pindex], 'dg') pylab.plot([x_list[i] for i in neighbor_indices], [y_list[i] for i in neighbor_indices], 'ro') pylab.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 own_concave(points, alpha): tri = scipy.spatial.Delaunay(points) ################# pylab.triplot(max_pos[:,0], max_pos[:,1], tri.simplices.copy()) pylab.plot(max_pos[:,0], max_pos[:,1], 'ro') plt.show() ################# index = 0 for triangle in tri.simplices: #print("Warning: hier ist der max_pos index hoechstwahrscheinlich falsch") #vertice0=max_pos[triangle[0]] #vertice1=max_pos[triangle[1]] #vertice2=max_pos[triangle[2]] vertice0=points[triangle[0]] vertice1=points[triangle[1]] vertice2=points[triangle[2]] edge0 = np.linalg.norm(vertice0-vertice1) edge1 = np.linalg.norm(vertice2-vertice1) edge2 = np.linalg.norm(vertice0-vertice2) if (edge0 > alpha or edge1 > alpha or edge2 > alpha): tri.simplices = np.delete(tri.simplices, index, 0) else: index += 1 ################# pylab.triplot(max_pos[:,0], max_pos[:,1], tri.simplices.copy()) pylab.plot(max_pos[:,0], max_pos[:,1], 'ro') plt.show() ################# edges = [] for triangle in tri.simplices: edges.append([triangle[0], triangle[1]]) edges.append([triangle[1], triangle[2]]) edges.append([triangle[0], triangle[2]]) edges = np.array(edges) """ #cool but it can be solved diferent #sorted for the first element of the edge 2-tuple [in case (a, b) for a] ordered_edges_a = np.sort(edges, axis=0) #sorted for the first element of the edge 2-tuple [in case (a, b) for b] edges_b = np.transpose(np.array((edges[:,1], edges[:,0]))) ordered_edges_b = np.sort(edges_b, axis=0) edge_two_times = np.in1d(ordered_edges_a, ordered_edges_b) # funktioniert so nicht? erst muss fuer jede kante die rueckkante gefunden #werden, erst dann muss nach doppelten kanten gesucht werden """ edges_sort_1 = np.sort(edges, axis=1) edges_sort_2 = edges_sort_1[np.argsort(edges_sort_1[:,0])] tp = [tuple(row) for row in edges_sort_2] print(tp) #uniques = np.unique(edges) #print (uniques) from collections import Counter c = Counter(tp) c = dict(c) #print(c) fig, ax = plt.subplots() hull_vertices = [] for key in c: if c[key] == 1: #print("pairs: " + str(pairs)) #plt.scatter(points[key[0]][0], points[key[1]][1]) #plt.scatter(points[key[0]][0], points[key[0]][1]) #plt.scatter(points[key[1]][0], points[key[1]][1]) ax.plot([points[key[0]][0], points[key[1]][0]], [points[key[0]][1], points[key[1]][1]], linewidth=4) hull_vertices.append(points[key[0]]) ax.scatter(points[:,0], points[:,1]) plt.show() return np.array(hull_vertices) """
from scipy.spatial import Delaunay import matplotlib.tri as mtri print((X.shape)) print((X.size)) points = np.zeros((X.size, 2)) points[:, 0] = X.reshape(X.size) points[:, 1] = Y.reshape(Y.size) tess = Delaunay(points) tri = tess.vertices # or tess.simplices depending on scipy version triang = mtri.Triangulation(x=points[:, 0], y=points[:, 1], triangles=tri) # pl.contourf(X, Y, Xi1) pl.colorbar() #pl.scatter(X,Y,marker='-') pl.triplot(triang, lw=0.5, color='white') pl.axis('equal') pl.title("SCALED MESH : chi1 with arbitrary degree and general hex mesh") pl.show(block=True) #****************++ # Xi1 = boxspline(X,Y,1) # from mpl_toolkits.mplot3d import Axes3D # from matplotlib import cm # from matplotlib.ticker import LinearLocator, FormatStrFormatter # import matplotlib.pyplot as plt # import numpy as np # fig = plt.figure()
from scipy.spatial import Delaunay import matplotlib.tri as mtri print(X.shape) print(X.size) points = np.zeros((X.size, 2)) points[:,0] = X.reshape(X.size) points[:,1] = Y.reshape(Y.size) tess = Delaunay(points) tri = tess.vertices # or tess.simplices depending on scipy version triang = mtri.Triangulation(x=points[:, 0], y=points[:, 1], triangles=tri) # pl.contourf(X, Y, Xi1) pl.colorbar() #pl.scatter(X,Y,marker='-') pl.triplot(triang, lw=0.5, color='white') pl.axis('equal') pl.title("SCALED MESH : chi1 with arbitrary degree and general hex mesh") pl.show(block=True) #****************++ # Xi1 = boxspline(X,Y,1) # from mpl_toolkits.mplot3d import Axes3D # from matplotlib import cm # from matplotlib.ticker import LinearLocator, FormatStrFormatter # import matplotlib.pyplot as plt # import numpy as np
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 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()