def domain(self, domaintype='meshpy'): if domaintype is 'meshpy': from meshpy.triangle import MeshInfo domain = MeshInfo() points = np.zeros((16, 2), dtype=np.float) points[0:4, :] = np.array([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)], dtype=np.float) idx = np.arange(5, -1, -1) points[4:10, 0] = 0.25 + 0.1 * np.cos(idx * np.pi / 3) points[4:10, 1] = 0.75 + 0.1 * np.sin(idx * np.pi / 3) points[10:, 0] = 0.6 + 0.1 * np.cos(idx * np.pi / 3) points[10:, 1] = 0.4 + 0.1 * np.sin(idx * np.pi / 3) facets = np.zeros((16, 2), dtype=np.int) facets[0:4, :] = np.array([(0, 1), (1, 2), (2, 3), (3, 0)], dtype=np.int) facets[4:10, :] = np.array([(4, 5), (5, 6), (6, 7), (7, 8), (8, 9), (9, 4)], dtype=np.int) facets[10:, :] = np.array([(10, 11), (11, 12), (12, 13), (13, 14), (14, 15), (15, 10)], dtype=np.int) domain.set_points(points) domain.set_facets(facets) domain.set_holes([(0.25, 0.75), (0.6, 0.4)]) return domain
def par_mesh(h, n): mesh_info = MeshInfo() # Set the vertices of the domain [0, 1]^2 mesh_info.set_points([ (0,0), (1,0), (1,1), (0,1)]) # Set the facets of the domain [0, 1]^2 mesh_info.set_facets([ [0,1], [1,2], [2,3], [3,0] ]) # Generate the tet mesh mesh = build(mesh_info, max_volume=(h)**2) node = np.array(mesh.points, dtype=np.float) cell = np.array(mesh.elements, dtype=np.int) tmesh = TriangleMesh(node, cell) # Partition the mesh cells into n parts if n > 1: edgecuts, parts = metis.part_mesh(tmesh, nparts=n, entity='node') else: NN = tmesh.number_of_nodes() parts = np.zeros(NN, dtype=np.int) tmesh.nodedata['partition'] = parts return tmesh
def triangulate(self, options=None): if options is None: options = self._get_triangle_options() mesh_info = MeshInfo() mesh_info.set_points(self.vertices) if self.boundary is not None: segments = [] for b in self.boundary: segments += self.get_segments(b) mesh_info.set_facets(segments) if self.holes is not None: mesh_info.set_holes(self.holes) try: import locale except ImportError: use_locale = False else: use_locale = True prev_num_locale = locale.getlocale(locale.LC_NUMERIC) locale.setlocale(locale.LC_NUMERIC, "C") try: mesh = MeshInfo() internals.triangulate(options, mesh_info, mesh, MeshInfo(), None) finally: # restore previous locale if we've changed it if use_locale: locale.setlocale(locale.LC_NUMERIC, prev_num_locale) return mesh
def triangle(box, h): from meshpy.triangle import MeshInfo, build mesh_info = MeshInfo() mesh_info.set_points([(box[0], box[2]), (box[1], box[2]), (box[1], box[3]), (box[0], box[3])]) mesh_info.set_facets([[0, 1], [1, 2], [2, 3], [3, 0]]) mesh = build(mesh_info, max_volume=h**2) point = np.array(mesh.points, dtype=np.float) cell = np.array(mesh.elements, dtype=np.int) return TriangleMesh(point, cell)
def domain(self, domaintype='meshpy'): if domaintype == 'meshpy': from meshpy.triangle import MeshInfo domain = MeshInfo() points = np.array([(0, 0), (48, 44), (48, 60), (0, 44)], dtype=np.float) facets = np.array([(0, 1), (1, 2), (2, 3), (3, 0)], dtype=np.int) domain.set_points(points) domain.set_facets(facets) return domain if domaintype == 'halfedge': return None
def triangle(box, h, meshtype='tri'): from meshpy.triangle import MeshInfo, build mesh_info = MeshInfo() mesh_info.set_points([(box[0], box[2]), (box[1], box[2]), (box[1], box[3]), (box[0], box[3])]) mesh_info.set_facets([[0,1], [1,2], [2,3], [3,0]]) mesh = build(mesh_info, max_volume=h**2) node = np.array(mesh.points, dtype=np.float) cell = np.array(mesh.elements, dtype=np.int) if meshtype is 'tri': return TriangleMesh(node, cell) elif meshtype is 'polygon': mesh = TriangleMeshWithInfinityNode(TriangleMesh(node, cell)) pnode, pcell, pcellLocation = mesh.to_polygonmesh() return PolygonMesh(pnode, pcell, pcellLocation)
def triangle_polygon_domain(points, facets, h, meshtype='tri'): from meshpy.triangle import MeshInfo, build mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets(facets) mesh = build(mesh_info, max_volume=h**2) node = np.array(mesh.points, dtype=np.float) cell = np.array(mesh.elements, dtype=np.int) if meshtype is 'tri': return TriangleMesh(node, cell) elif meshtype is 'polygon': mesh = TriangleMeshWithInfinityNode(TriangleMesh(node, cell)) pnode, pcell, pcellLocation = mesh.to_polygonmesh() return PolygonMesh(pnode, pcell, pcellLocation)
def get_mesh_example(): area = rect((0.,0.),(1.,1.)) init = rect((0.1,0.1),(0.2,0.2)) goal1 = rect((0.8,0.8),(0.9,0.9)) goal2 = rect((0.2,0.8),(0.3,0.9)) env = area + goal1 + goal2 + init info = MeshInfo() info.set_points(env) info.set_facets(loop(0,4) + loop(4,8) + loop(8,12) + loop(12,16), facet_markers = [0]*4 + [1]*4 + [2]*4 + [3]*4) # Create 8 facets and apply markers 1-8 on them info.regions.resize(4) s = 0.05 info.regions[0] = [0.15, 0.15, 0, s] # Replace 0.1 by a smaller value to produce a finer mesh info.regions[1] = [0.25, 0.85, 1, s] # Fourth item specifies maximum area of triangles as a region attribute info.regions[2] = [0.85, 0.85, 2, s] # Replace 0.1 by a smaller value to produce a finer mesh info.regions[3] = [0.5, 0.5, 3, s] # Fourth item specifies maximum area of triangles as a region attribute mesh = build(info, volume_constraints=True, attributes=True, generate_faces=True, min_angle=20, mesh_order=1) return mesh
def make_mesh_triangle_meshpy(self, **params): """make_mesh_meshpy_triangle create mesh using meshpy.triangle.MeshInfo """ c = params['c'] mesh_info = MeshInfo() # generate vertices and facets if params['obj'] == 'line': points, facets, faces = make_vertex_facets_line(params) elif params['obj'] == 'hexagon': points, facets, faces = make_vertex_facets_hexagon(params) elif params['obj'] == 'rect': points, facets = make_vertex_facets_rect(params) print('points = {0}\nfacets = {1}'.format(pformat(points), pformat(facets))) # print('mesh_info.unit = {0}'.format(mesh_info.unit)) # copy points data into mesh mesh_info.set_points(points) # copy facets data into mesh mesh_info.set_facets(facets) # build the mesh mesh = build(mesh_info) # writing objects # mesh.write_vtk("trigrid.vtk") # f = open('trigrid.pkl', 'wb') # pickle.dump(mesh, f) # f.close() # joblib.dump(mesh, 'trigrid.pkl') # sys.exit() return mesh
from meshpy.triangle import MeshInfo, build, refine import numpy as np mesh_info = MeshInfo() mesh_info.set_points([ (0,0), (0,1), (1,1), (1,0) ]) mesh_info.set_facets([ [0,1], [1,2], [2,3], [3,0] ]) def refinement_func(tri_points, area): max_area=0.001 return bool(area>max_area); mesh = build(mesh_info, refinement_func = refinement_func) ''' print "Mesh Points:" for i, p in enumerate(mesh.points): print i, p print "Point numbers in tetrahedra:"
from meshpy.triangle import MeshInfo, build # Utility function to create lists of the form [(1,2), (2,3), (3,4), # (4,1)], given two numbers 1 and 4 from itertools import islice, cycle def loop(a, b): return list( zip(list(range(a, b)), islice(cycle(list(range(a, b))), 1, None))) info = MeshInfo() info.set_points([(0, 0), (1, 0), (1, 1), (0, 1), (2, 0), (3, 0), (3, 1), (2, 1)]) info.set_facets(loop(0, 4) + loop(4, 8), list(range( 1, 9))) # Create 8 facets and apply markers 1-8 on them info.regions.resize(2) info.regions[0] = [ 0.5, 0.5, 1, 0.1, ] # Fourth item specifies maximum area of triangles as a region attribute info.regions[1] = [ 2.5, 0.5, 2, 0.1, ] # Replace 0.1 by a smaller value to produce a finer mesh mesh = build(
from fealpy.functionspace.mixed_fem_space import BDMFiniteElementSpace2d from fealpy.functionspace.mixed_fem_space import FirstNedelecFiniteElement2d def mesh_2dpy(mesh_info, h): mesh = build(mesh_info, max_volume=(h)**2) point = np.array(mesh.points, dtype=np.float) cell = np.array(mesh.elements, dtype=np.int) tmesh = TriangleMesh(point, cell) return tmesh mesh_info = MeshInfo() mesh_info.set_points([(0, 0), (1, 0), (1, 1), (0, 1)]) mesh_info.set_facets([[0, 1], [1, 2], [2, 3], [3, 0]]) h = 0.5 tmesh = mesh_2dpy(mesh_info, h) #point = np.array([ # (0, 0), # (1, 0), # (1, 1), # (0, 1)], dtype=np.float) #cell = np.array([ # (1, 2, 0), # (3, 0, 2)], dtype=np.int) #tmesh = TriangleMesh(point, cell) space = RaviartThomasFiniteElementSpace2d(tmesh) #space = BDMFiniteElementSpace2d(tmesh)
def discretise_faces(vertices, faces, target, min_angle=15, factor=3): """ Make discretised triangles from input coarse triangles data. Parameters ---------- vertices : list Co-ordinates of coarse vertices. faces : list Vertex indices of each face of the coarse triangles. target : float Target edge length of each triangle. min_angle : float Minimum internal angle of triangles. factor : float Factor on the maximum area of each triangle. Returns ------- list Vertices of the discretised trianlges. list Vertex numbers of the discretised trianlges. Notes ----- - An experimental script. """ points_all = [] faces_all = [] Amax = factor * 0.5 * target**2 for count, face in enumerate(faces): # Seed face.append(face[0]) points = [] facets = [] for u, v in zip(face[:-1], face[1:]): sp = vertices[u] ep = vertices[v] vec = subtract_vectors(ep, sp) l = length_vector(vec) div = l / target n = max([1, int(div)]) for j in range(n): points.append(add_vectors(sp, scale_vector(vec, j / n))) facets = [[i, i + 1] for i in range(len(points) - 1)] facets.append([len(points) - 1, 0]) # Starting orientation cent = centroid_points(points) vec1 = subtract_vectors(points[1], points[0]) vec2 = subtract_vectors(cent, points[0]) vecn = cross_vectors(vec1, vec2) # Rotate about x points = array(points).transpose() phi = -arctan2(vecn[2], vecn[1]) + 0.5 * pi Rx = array([[1, 0, 0], [0, cos(phi), -sin(phi)], [0, sin(phi), cos(phi)]]) vecn_x = dot(Rx, array(vecn)[:, newaxis]) points_x = dot(Rx, points) Rx_inv = inv(Rx) # Rotate about y psi = +arctan2(vecn_x[2, 0], vecn_x[0, 0]) - 0.5 * pi Ry = array([[cos(psi), 0, sin(psi)], [0, 1, 0], [-sin(psi), 0, cos(psi)]]) points_y = dot(Ry, points_x) Ry_inv = inv(Ry) V = points_y.transpose() try: new_points = [list(i) for i in list(V[:, :2])] info = MeshInfo_tri() info.set_points(new_points) info.set_facets(facets) tris = build_tri(info, allow_boundary_steiner=False, min_angle=min_angle, max_volume=Amax) new_points = [list(j) + [V[0, 2]] for j in tris.points] new_tris = [list(j) for j in tris.elements] V = array(new_points) points = dot(Ry_inv, V.transpose()) points_all.append( [list(i) for i in list(dot(Rx_inv, points).transpose())]) faces_all.append(new_tris) except: print('***** ERROR discretising face {0} *****'.format(count)) return points_all, faces_all
from numpy import * from matplotlib.pyplot import * from meshpy.triangle import MeshInfo, build # Utility function to create lists of the form [(1,2), (2,3), (3,4), # (4,1)], given two numbers 1 and 4 from itertools import islice, cycle from six.moves import range from six.moves import zip loop = lambda a, b: list(zip(list(range(a, b)), islice(cycle(list(range(a, b))), 1, None))) info = MeshInfo() info.set_points([(0, 0), (1, 0), (1, 1), (0, 1), (2, 0), (3, 0), (3, 1), (2, 1)]) info.set_facets(loop(0, 4) + loop(4, 8), list(range(1, 9))) # Create 8 facets and apply markers 1-8 on them info.regions.resize(2) info.regions[0] = [0.5, 0.5, 1, 0.1] # Fourth item specifies maximum area of triangles as a region attribute info.regions[1] = [2.5, 0.5, 2, 0.1] # Replace 0.1 by a smaller value to produce a finer mesh mesh = build(info, volume_constraints=True, attributes=True, generate_faces=True, min_angle=33, mesh_order=2) pts = vstack(mesh.points) # (npoints, 2)-array of points elements = vstack(mesh.elements) # (ntriangles, 6)-array specifying element connectivity # Matplotlib's Triangulation module uses only linear elements, so use only first 3 columns when plotting triplot(pts[:, 0], pts[:, 1], elements[:, :3]) plot(pts[:, 0], pts[:, 1], "ko") # Manually plot all points including the ones at the midpoints of triangle faces # Plot a filled contour plot of the function (x - 1.5)^2 + y^2 over
from meshpy.triangle import MeshInfo, build import numpy as np import matplotlib.pyplot as plt from fealpy.mesh import TriangleMesh domain = MeshInfo() domain.set_points([(0,0),(1,0),(1,1),(0,1)]) domain.set_facets([(0,1),(1,2),(2,3),(3,0)], facet_markers=[1, 2, 3, 4]) mesh = build(domain, max_volume = 0.1**2, attributes=True) node = np.array(mesh.points, dtype = np.float) cell = np.array(mesh.elements, dtype = np.int) tmesh = TriangleMesh(node, cell) fig = plt.figure() axes = fig.gca() tmesh.add_plot(axes) cell = tmesh.entity('cell') node = tmesh.entity('node') NN = tmesh.number_of_nodes() isBdNode = tmesh.ds.boundary_node_flag() newNode = np.zeros((NN, 2), dtype=np.float) degree = np.zeros(NN, dtype=np.int) np.add.at(degree, cell, 1) for i in range(10): #bc = tmesh.entity_barycenter('cell') bc, R = tmesh.circumcenter() np.add.at(newNode, (cell, np.s_[:]), bc[:, np.newaxis, :]) newNode /= degree[:, np.newaxis] node[~isBdNode] = newNode[~isBdNode] newNode[:] = 0
#redraw the delaunay triangles return findDelaunayTriangles(nodepts) if __name__ == '__main__': #Create the intial mesh node pts nodepts = createInitialTriGridPts(4, 4) #Define the element triangles that link the nodes elements = defineElementConnectivity(nodepts) mesh_info = MeshInfo() print(nodepts) mesh_info.set_points(nodepts) print(elements.simplices) mesh_info.set_facets(elements.simplices) mesh = build(mesh_info) #mesh.triangle. write_gnuplot_mesh("test.vtk", mesh_info.points, facets=False) #triangle=showMesh(nodepts,elements.simplices) print(elements) print(elements.simplices) print(elements.points) nodepts, elements = refineMesh(nodepts, elements, 7) nodepts, elements = refineMesh(nodepts, elements, 20) #nodepts,elements = refineMesh(nodepts,elements,100) #nodepts,elements = refineMesh(nodepts,elements,50) #nodepts,elements = refineMesh(nodepts,elements,2) #nodepts,elements = refineMesh(nodepts,elements,10)
child[idx, :] = np.arange(NC, NC + 4 * NCC).reshape(NCC, 4) cell = np.concatenate((cell, newCell), axis=0) self.node = np.concatenate((node, edgeCenter, cellCenter), axis=0) self.parent = np.concatenate((parent, newParent), axis=0) self.child = np.concatenate((child, newChild), axis=0) self.ds.reinit(N + NEC + NCC, cell) return True else: return False mesh_info = MeshInfo() mesh_info.set_points([(-1, -1), (0, -1), (0, 0), (1, 0), (1, 1), (0, 1), (1, 1), (-1, 0)]) mesh_info.set_facets([[0, 1], [1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7], [7, 0]]) h = 0.05 mesh = build(mesh_info, max_volume=h**2) node = np.array(mesh.points, dtype=np.float) cell = np.array(mesh.elements, dtype=np.int) ttree = Tritree(node, cell) mesh = ttree.to_mesh() pde = LShapeRSinData() integrator = mesh.integrator(3) fem = PoissonFEMModel(pde, mesh, 1, integrator) fem.solve() eta = fem.recover_estimate() ttree.refine(marker=AdaptiveMarker(eta, theta=theta))