def create_mesh(self): self.mesh=dolfin.Mesh() editor=dolfin.MeshEditor() editor.open(self.mesh, "tetrahedron", 3, 3) editor.init_vertices_global(len(self.geometry.nodetags), len(self.geometry.nodetags)) self.nodemap, self.nodemap_inv, self.cellmap, self.cellmap_inv = (dict(), dict(), dict(), dict()) for i, tag in enumerate(self.geometry.nodetags): self.nodemap[i]=tag self.nodemap_inv[tag]=i editor.add_vertex(i, [self.geometry.nodecoords[3*i], self.geometry.nodecoords[3*i+1], self.geometry.nodecoords[3*i+2]]) index_tetra=np.where(self.geometry.elementTypes==4)[0][0] editor.init_cells_global(len(self.geometry.elementTags[index_tetra]), len(self.geometry.elementTags[index_tetra])) if self.cell_physical is None: self.cell_physical = dict() self.cell_physical['No material']=dict() for i, tag in enumerate(self.geometry.elementTags[index_tetra]): self.cell_physical['No material'][tag]=[self.geometry.elementnodeTags[0][4*i], self.geometry.elementnodeTags[0][4*i+1], self.geometry.elementnodeTags[0][4*i+2], self.geometry.elementnodeTags[0][4*i+3]] i=0 for material in self.cell_physical.keys(): for tag, nodes in self.cell_physical[material].items(): self.cellmap[i]=tag self.cellmap_inv[tag]=i editor.add_cell(i, [self.nodemap_inv[node] for node in nodes]) i+=1 editor.close()
def init_mesh_geometry(mesh, points, connectivity, tdim, gdim): """ Create a dolfin mesh from a list of points and connectivity for each cell (as returned by meshio). The geometric dimmension dim should be 2 or 3 """ cell_type = {2: 'triangle', 3: 'tetrahedron'}[tdim] # Get global mesh sizes Nvert = points.shape[0] Ncell = len(connectivity) # Open mesh for editing editor = dolfin.MeshEditor() editor.open(mesh, cell_type, tdim, gdim) # Add vertices editor.init_vertices_global(Nvert, Nvert) for i, pnt in enumerate(points): editor.add_vertex(i, [float(xi) for xi in pnt[:gdim]]) # Add cells editor.init_cells_global(Ncell, Ncell) for i, conn in enumerate(connectivity): editor.add_cell(i, conn) editor.close()
def irregular_interval_mesh(xmin, xmax, n): """ Create a mesh on the interval [xmin, xmax] with n vertices. The first and last mesh node coincide with xmin and xmax, but the other nodes are picked at random from within the interval. """ # Create an 'empty' mesh mesh = df.Mesh() # Open it in the MeshEditor as a mesh of topological and geometrical # dimension 1 editor = df.MeshEditor() editor.open(mesh, 1, 1) # We're going to define 5 vertices, which result in 4 'cells' (= intervals) editor.init_vertices(n) editor.init_cells(n - 1) coords = (xmax - xmin) * np.random.random_sample(n - 1) + xmin coords.sort(0) # Define the vertices and cells with their corresponding indices for (i, x) in enumerate(coords): editor.add_vertex(i, np.array([x], dtype=float)) editor.add_vertex(n - 1, np.array([xmax], dtype=float)) for i in xrange(n - 1): editor.add_cell(i, np.array([i, i + 1], dtype='uintp')) editor.close() return mesh
def convertUGridToXMLMesh(ugrid): num_pts = ugrid.GetNumberOfPoints() num_cells = ugrid.GetNumberOfCells() celltypes = numpy_support.vtk_to_numpy(ugrid.GetCellTypesArray()) num_tetra = np.count_nonzero(celltypes == 10) print "Number of points = ", num_pts print "Number of tetra = ", num_tetra mesh = dolfin.Mesh() editor = dolfin.MeshEditor() editor.open(mesh, 3, 3) # top. and geom. dimension are both 2 editor.init_vertices(num_pts) # number of vertices editor.init_cells(num_tetra) # number of cells for p in range(0, num_pts): pt = ugrid.GetPoints().GetPoint(p) editor.add_vertex(p, pt[0], pt[1], pt[2]) cnt = 0 for p in range(0, num_cells): pts = vtk.vtkIdList() ugrid.GetCellPoints(p, pts) if(pts.GetNumberOfIds() == 4): editor.add_cell(cnt, pts.GetId(0), pts.GetId(1), pts.GetId(2), pts.GetId(3)) cnt = cnt + 1 editor.close() return mesh
def create_mesh(): mesh = dolfin.Mesh() ed = dolfin.MeshEditor() ed.open(mesh, 'triangle', 2, 2) ed.init_vertices(5) av = ed.add_vertex av(0, [0.0, 1.0]) av(1, [0.0, 0.0]) av(2, [1.0, 0.0]) av(3, [1.0, 1.0]) av(4, [0.5, 1.0]) ed.init_cells(3) ac = ed.add_cell ac(0, [4, 1, 2]) ac(1, [0, 1, 4]) ac(2, [4, 2, 3]) ed.close() return { 'mesh': mesh, 'marker0': create_mf_and_set(mesh, 0, {4}), 'marker2': create_mf_and_set(mesh, 2, {0}), }
def create_3d_mesh(self, mesh): nv = mesh.num_vertices() nc = mesh.num_cells() h = self.thickness mesh3 = df.Mesh() editor = df.MeshEditor() editor.open(mesh3, 3, 3) editor.init_vertices(2 * nv) editor.init_cells(3 * nc) for v in df.vertices(mesh): i = v.index() p = v.point() editor.add_vertex(i, p.x(), p.y(), 0) editor.add_vertex(i + nv, p.x(), p.y(), h) gid = 0 for c in df.cells(mesh): i, j, k = c.entities(0) editor.add_cell(gid, i, j, k, i + nv) gid = gid + 1 editor.add_cell(gid, j, j + nv, k, i + nv) gid = gid + 1 editor.add_cell(gid, k, k + nv, j + nv, i + nv) gid = gid + 1 editor.close() return mesh3
def make_mesh(vertices, cells, cell_type=None): '''Mesh from data by MeshEditor''' # Decide tetrahedron/triangle mesh = df.Mesh() assert mesh.mpi_comm().size == 1 if cell_type is None: if len(cells[0]) == 3: gdim = vertices.shape[1] module.fill_mesh(vertices.flatten(), cells.flatten(), 2, gdim, mesh) return mesh if len(cells[0]) == 4 and vertices.shape[1] == 3: module.fill_mesh(vertices.flatten(), cells.flatten(), 3, 3, mesh) return mesh raise ValueError('cell_type cannot be determined reliably %d %d %d' % ((len(cells[0]), ) + vertices.shape)) if cell_type.cellname() == 'triangle': module.fill_mesh(vertices.flatten(), cells.flatten(), 2, cell_type.geometric_dimension, mesh) return mesh if cell_type.cellname() == 'tetrahedron': module.fill_mesh(vertices.flatten(), cells.flatten(), 3, cell_type.geometric_dimension, mesh) return mesh # Fallback to python gdim = cell_type.geometric_dimension() assert vertices.shape[1] == gdim tdim = cell_type.topological_dimension() editor = df.MeshEditor() editor.open(mesh, str(cell_type), tdim, gdim) editor.init_vertices(len(vertices)) editor.init_cells(len(cells)) for vi, x in enumerate(vertices): editor.add_vertex(vi, x) for ci, c in enumerate(cells): editor.add_cell(ci, *c) editor.close() return mesh
def get_dolfin_mesh(self): mesh = dolfin.Mesh() me = dolfin.MeshEditor() me.open(mesh,'tetrahedron', 3, 3) me.init_vertices(len(self.coordinates)) me.init_cells(len(self.element_nodes)) for i, coord in enumerate(self.coordinates): me.add_vertex(N.uint(i), *coord) for i, el_nodes in enumerate(self.element_nodes): me.add_cell(i, *el_nodes) me.close() return mesh
def l_panel_mesh(lx, ly, refinement=5, show=False): """ Creates something like ly +---------+ | ^y | | | | | 0->--+ | | x | | -ly +----+ -lx lx out of triangles """ mesh = df.Mesh() e = df.MeshEditor() e.open(mesh, "triangle", 2, 2) e.init_vertices(8) e.add_vertex(0, [0, 0]) e.add_vertex(1, [lx, 0]) e.add_vertex(2, [lx, ly]) e.add_vertex(3, [0, ly]) e.add_vertex(4, [-lx, ly]) e.add_vertex(5, [-lx, 0]) e.add_vertex(6, [-lx, -ly]) e.add_vertex(7, [0, -ly]) e.init_cells(6) e.add_cell(0, [0, 1, 3]) e.add_cell(1, [1, 2, 3]) e.add_cell(2, [0, 3, 5]) e.add_cell(3, [5, 3, 4]) e.add_cell(4, [0, 5, 7]) e.add_cell(5, [7, 5, 6]) e.close mesh.order() for _ in range(refinement): mesh = df.refine(mesh) if show: df.plot(mesh) import matplotlib.pyplot as plt plt.show() return mesh
def listmesh_2_dolfin_mesh(listmesh, reorder=False): """Setup dolfin mesh using node and tet data from listmesh If parameter reorder is set to True, the order() method will be called on the dolfin mesh to sort the mesh according to UFC specifications. """ dm = dolfin.Mesh() me = dolfin.MeshEditor() me.open(dm, 'tetrahedron', 3, 3) me.init_vertices(len(listmesh['Nodes'])) me.init_cells(len(listmesh['ElementNodes'])) dm.coordinates()[:, :] = listmesh['Nodes'] #dm.cells()[:,:] = listmesh['ElementNodes'] for i, enodes in enumerate(listmesh['ElementNodes']): me.add_cell(i, *enodes) me.close() if reorder: dm.order() return dm
def create2Dmesh(msh, unused_points): """ Helping function to create a 2D mesh for FEniCS from a gmsh. important! Dont leave any unused points like the center of the circle in the node list. FEniCS will crash! """ msh.prune_z_0() nodes = msh.points[unused_points:] cells = msh.cells_dict["triangle"].astype(np.uintp) - unused_points mesh = dolfin.Mesh() editor = dolfin.MeshEditor() # point, interval, triangle, quadrilateral, hexahedron editor.open(mesh, "triangle", 2, 2) editor.init_vertices(len(nodes)) editor.init_cells(len(cells)) [editor.add_vertex(i, n) for i, n in enumerate(nodes)] [editor.add_cell(i, n) for i, n in enumerate(cells)] editor.close() return mesh
def makemesh(vertex_coordinates, cells): "constructs dolfin mesh given numpy arrays of vertex coordinates and cell maps, *does not* output mesh to file" # create mesh and editor mesh = dolfin.Mesh() M = dolfin.MeshEditor() # get information about mesh num_vertices, gdim = vertex_coordinates.shape num_cells, cdim = cells.shape tdim = cdim - 1 # topological dimension if tdim == 2: shape="triangle" elif tdim == 3: shape = "tetrahedron" else: print "Error: unknown cell shape" return # make sure cell vertex indices are 0 offset (C style) rather than 1 offset (Fortran style) cells -= cells.min() # initialize mesh M.open(mesh,shape,tdim,gdim) M.init_vertices(num_vertices) M.init_cells(num_cells) # add vertices for i in range(num_vertices): p = dolfin.Point(gdim,vertex_coordinates[i,:]) M.add_vertex(i,p) # add cells for i in range(num_cells): #c = STLVectorUInt(cells[i,:]) M.add_cell(i, cells[i,0], cells[i,1], cells[i,2]) # finish up and order M.close() return mesh
def make_line_mesh(vertices, cells=None, close_path=False): '''Mesh from data by MeshEditor''' assert vertices.ndim == 2 # Path mesh if cells is None: nvertices = len(vertices) if not close_path: cells = np.array([(i, i + 1) for i in range(nvertices - 1)], dtype='uintp') else: cells = np.array([(i, (i + 1) % nvertices) for i in range(nvertices)], dtype='uintp') return make_line_mesh(vertices, cells) ncells, nvtx_per_cell = cells.shape assert nvtx_per_cell == 2 tdim = 1 nvertices, gdim = vertices.shape assert gdim > 1 mesh = df.Mesh() editor = df.MeshEditor() editor.open(mesh, 'interval', tdim, gdim) editor.init_vertices(nvertices) editor.init_cells(ncells) for vi, x in enumerate(vertices): editor.add_vertex(vi, x) for ci, c in enumerate(np.asarray(cells, dtype='uintp')): editor.add_cell(ci, c) editor.close() return mesh
def mesh(self): Xs, Ys = self.Xs, self.Ys nX, nY = self.nX, self.nY mesh = dolfin.Mesh() ed = dolfin.MeshEditor() ed.open(mesh, 'triangle', 2, 2) ed.init_vertices(nX*nY) av = ed.add_vertex i = 0 for x in Xs: for y in Ys: av(i, [x, y]) i += 1 ed.init_cells((nX-1)*(nY-1)*2) ac = ed.add_cell i = 0 for ix in range(nX-1): for iy in range(nY-1): # ^ y # | (b+1)(c+1) # | | / | # | | / | # | | / | # | (b)---(c) # | # +---------------> x b = ix*nY + iy c = b + nY ac(i , [b, c, c+1]) ac(i+1, [b, c+1, b+1]) i += 2 ed.close() mesh.init() mesh.order() return mesh
def test_triangle_mesh(): # Create mesh object and open editor mesh = df.Mesh() editor = df.MeshEditor() editor.open(mesh, 2, 2) editor.init_vertices(3) editor.init_cells(1) # Add vertices editor.add_vertex(0, 0.0, 0.0) editor.add_vertex(1, 1.0, 0.0) editor.add_vertex(2, 0.0, 1.0) # Add cell editor.add_cell(0, 0, 1, 2) # Close editor editor.close() return mesh
def build_mesh(vertices, cells, cell_type): '''Mesh defined by its vertices, cells''' cell_tdim = cell_type.topological_dimension() gdim = cell_type.geometric_dimension() # Consistency assert gdim == vertices.shape[1] assert cell_type.num_vertices() == cells.shape[1] mesh = df.Mesh() editor = df.MeshEditor() editor.open(mesh, cell_type.cellname(), cell_tdim, gdim) editor.init_cells(len(cells)) editor.init_vertices(len(vertices)) for i, v in enumerate(vertices): editor.add_vertex(i, v) for i, c in enumerate(cells): editor.add_cell(i, c) editor.close() return mesh
def make_1d_mesh_from_points(Xs): N = len(Xs) mesh = dolfin.Mesh() ed = dolfin.MeshEditor() ed.open(mesh, 'interval', 1, 1) ed.init_vertices(N) av = ed.add_vertex for i, x in enumerate(Xs): av(i, [x]) ed.init_cells(N-1) ac = ed.add_cell for i in range(N-1): ac(i, [i, i+1]) ed.close() mesh.init() mesh.order() return mesh
def create_3d_mesh(mesh, h=1): assert mesh.topology().dim() == 2 for cell in df.cells(mesh): print cell print cell.entities(0) print cell.get_vertex_coordinates() nv = mesh.num_vertices() nc = mesh.num_cells() mesh3 = df.Mesh() editor = df.MeshEditor() editor.open(mesh3, 3, 3) editor.init_vertices(2 * nv) editor.init_cells(3 * nc) for v in df.vertices(mesh): i = v.global_index() p = v.point() editor.add_vertex(i, p.x(), p.y(), 0) editor.add_vertex(i + nv, p.x(), p.y(), h) gid = 0 for c in df.cells(mesh): #gid = c.global_index() i, j, k = c.entities(0) print i, j, k editor.add_cell(gid, i, j, k, i + nv) gid = gid + 1 editor.add_cell(gid, j, j + nv, k, i + nv) gid = gid + 1 editor.add_cell(gid, k, k + nv, j + nv, i + nv) gid = gid + 1 editor.close() return mesh3
lines = [ model.occ.addLine(points[i], points[(i + 1) % len(points)]) for i in range(len(points)) ] loop = model.occ.addCurveLoop(lines) rect1 = model.occ.addPlaneSurface([loop]) model.occ.synchronize() model.mesh.generate(2) elementTypes, elementTags, elementnodeTags = model.mesh.getElements() nodetags, nodecoords, _ = model.mesh.getNodes() gmsh.write("eigen.vtk") gmsh.write("eigen.msh") gmsh.finalize() mesh = dolfin.Mesh() editor = dolfin.MeshEditor() editor.open(mesh, "triangle", 2, 3) editor.init_vertices_global(len(nodetags), len(nodetags)) for i, tag in enumerate(nodetags): editor.add_vertex( i, [nodecoords[3 * i], nodecoords[3 * i + 1], nodecoords[3 * i + 2]]) index_triangle = np.where(elementTypes == 2)[0][0] editor.init_cells_global(len(elementTags[index_triangle]), len(elementTags[index_triangle])) for i, tag in enumerate(elementTags[index_triangle]): #if i%100==0: # print(float(i)/len(elementTags[index_tetra])*100.) editor.add_cell(i, [ int(elementnodeTags[index_triangle][3 * i] - 1), int(elementnodeTags[index_triangle][3 * i + 1] - 1), int(elementnodeTags[index_triangle][3 * i + 2] - 1)
def mesh(self): # prepare FEniCS mesh and mesh editor mesh = df.Mesh() mesh_editor = df.MeshEditor() mesh_editor.open(mesh, "tetrahedron", 3, 3) mesh_editor.init_vertices(self._model.getNumMeshVertices()) # prepare container for physical IDs self._physical_cell_ids = set() self._physical_face_ids = set() # get mesh vertices entities = gp.GEntityVector() self._model.getEntities(entities) for entity in entities: for vertex in entity.mesh_vertices: mesh_editor.add_vertex( vertex.getIndex() - 1, df.Point(vertex.x(), vertex.y(), vertex.z())) # get mesh cells mesh_editor.init_cells( reduce( lambda x, y: x + y, map(lambda r: r.tetrahedra.size(), self._model.bindingsGetRegions()))) i = 0 for region in self._model.bindingsGetRegions(): if len(region.physicals) == 0: region_id = None elif len(region.physicals) == 1: region_id = region.physicals[0] else: raise Exception( "Tetrahedra should belong to only one physical domain.") for tet in region.tetrahedra: mesh_editor.add_cell( i, np.array([ tet.getVertex(0).getIndex() - 1, tet.getVertex(1).getIndex() - 1, tet.getVertex(2).getIndex() - 1, tet.getVertex(3).getIndex() - 1 ], dtype=np.uintp)) if region_id is not None: mesh.domains().set_marker((i, region_id), 3) self._physical_cell_ids.add(region_id) i += 1 # finish mesh creation mesh_editor.close() # set facet domains mesh.init(0, 2) for face in self._model.bindingsGetFaces(): if len(face.physicals) == 0: continue elif len(face.physicals) == 1: face_id = face.physicals[0] else: raise Exception( "Facets should belong to only one physical domain.") for tri in face.triangles: i = reduce( lambda x, y: x.intersection(y), map( lambda i: set(mesh.topology()(0, 2) (tri.getVertex(i).getIndex() - 1)), range(3))).pop() mesh.domains().set_marker((i, face_id), 2) self._physical_face_ids.add(face_id) return mesh
def create_subdivided_mesh(mesh, selected_cells, degree): """ Create a subdivided mesh for the given cells that can represent a function of the given degree """ num_div = degree + 2 # Subdivide each of the selected cells vertex_coords = mesh.coordinates() subvertices = [] subcells = [] parent_cell = {} for cell in dolfin.cells(mesh): cid = cell.index() if cid not in selected_cells: continue # Create subdivided cells vid0, vid1, vid2 = cell.entities(0) x0 = tuple(vertex_coords[vid0, :]) x1 = tuple(vertex_coords[vid1, :]) x2 = tuple(vertex_coords[vid2, :]) subdiv_cells = subdivide_cell(num_div, x0, x1, x2) # Number the new vertices and subcells. Connectivity to other # subcells is only inside this parent cell, not across to # other parent cells vtx_ids = {} for vtxs in subdiv_cells: subcell_id = len(subcells) # Add the vertices subcell = [] for xN in vtxs: if xN not in vtx_ids: vtx_ids[xN] = len(subvertices) subvertices.append(xN) subcell.append(vtx_ids[xN]) # Add the cell subcells.append(subcell) parent_cell[subcell_id] = cid # Create a new dolfin.Mesh subdivided_mesh = dolfin.Mesh() editor = dolfin.MeshEditor() editor.open(subdivided_mesh, 2, 2) # Add the vertices (nodes) editor.init_vertices(len(subvertices)) for iv, vtx in enumerate(subvertices): editor.add_vertex(iv, vtx[0], vtx[1]) # Add the cells (triangular elements) # Loop over the vertices and build two cells for each square # where the selected vertex is in the lower left corner editor.init_cells(len(subcells)) for ic, subcell in enumerate(subcells): editor.add_cell(ic, subcell[0], subcell[1], subcell[2]) # Close the mesh for editing editor.close() return subdivided_mesh, parent_cell
def _create_hex_mesh(self, N): """Creates custom 3D hex mesh with of size with elements N :N: Number of points (number of elements - 1) :returns: Dolfin Mesh """ x = np.linspace(0, self.size, N) mesh = dlf.Mesh() editor = dlf.MeshEditor() editor.open(mesh, 'hexahedron', 3, 3) mat_vert = np.full((N, N, N), -1) def get_vertex_id(mat_vert, xi, yi, zi): """ input: xi,yi,zi: vertex indizes mat_Vert: matrix storing the indices of the vetrices (-1 -> not used) return: vertex id """ return mat_vert[xi, yi, zi] vertindex = np.full((N, N, N), 0) matindex = np.full((N-1, N-1, N-1), 1) #check which vertrices are needed -> can be done smarter logging.info("Check which vertices are needed") for zi in tqdm(range(N-1), ncols=80): for yi in range(N-1): for xi in range(N-1): if matindex[xi, yi, zi] >= 1: vertindex[xi, yi, zi] = 1 vertindex[xi + 1, yi, zi] = 1 vertindex[xi, yi + 1, zi] = 1 vertindex[xi + 1, yi + 1, zi] = 1 vertindex[xi, yi, zi + 1] = 1 vertindex[xi + 1, yi, zi + 1] = 1 vertindex[xi, yi + 1, zi + 1] = 1 vertindex[xi + 1, yi + 1, zi + 1] = 1 editor.init_vertices(np.sum(vertindex)) editor.init_cells(np.sum(matindex)) #create all nodes/vertices logging.info('Init {} vertices:'.format(np.sum(vertindex))) vertex_id = 0 for zi in tqdm(range(N), ncols=80): zcoor = x[zi] for yi in range(N): ycoor = x[yi] for xi in range(N): xcoor = x[xi] if vertindex[xi, yi, zi] == 1: editor.add_vertex(vertex_id, [xcoor, ycoor, zcoor]) mat_vert[xi, yi, zi] = vertex_id vertex_id += 1 #create elements/cells logging.info('Init {} cells:'.format(np.sum(matindex))) cell_id = 0 for zi in tqdm(range(N-1), ncols=80): for yi in range(N-1): for xi in range(N-1): if matindex[xi, yi, zi] >= 1: ind0 = get_vertex_id(mat_vert, xi, yi, zi) ind1 = get_vertex_id(mat_vert, xi + 1, yi, zi) ind2 = get_vertex_id(mat_vert, xi, yi + 1, zi) ind3 = get_vertex_id(mat_vert, xi + 1, yi + 1, zi) ind4 = get_vertex_id(mat_vert, xi, yi, zi + 1) ind5 = get_vertex_id(mat_vert, xi + 1, yi, zi + 1) ind6 = get_vertex_id(mat_vert, xi, yi + 1, zi + 1) ind7 = get_vertex_id(mat_vert, xi + 1, yi + 1, zi + 1) cell_index = [ind0, ind1, ind2, ind3, ind4, ind5, ind6, ind7] #Debug check: is index in correct order if not ind0 < ind1 < ind2 < ind3 < ind4 < ind5 < ind6 < ind7: print(cell_id, cell_index) editor.add_cell(cell_id, cell_index) cell_id += 1 editor.close(order=True) return mesh
#Make mesh np.random.seed(1) # Always the same results plt.ion() p, t = dm.distmesh2d(fd, fh, 0.0004, (-0.01,-0.03, 0.03,0.03), 0.001, [(rad,-rad),(2*rad,-rad), (rad,rad),(2*rad,rad)]) # Write mesh as xml file numVertices = p.shape[0] numCells = t.shape[0] editor = df.MeshEditor() mesh = df.Mesh() dim = 2 editor.open(mesh, 2, 2) # top. and geom. dimension are both 3 editor.init_vertices(numVertices) # number of vertices editor.init_cells(numCells) # number of cells for x in range(0, numVertices): editor.add_vertex(x, p[x][:]) for x in range(0, numCells): editor.add_cell(x, np.array(t[x][:], dtype=np.uintp)) editor.close()
def __init__(self, marking_function, markers): base_mesh = marking_function.mesh() assert base_mesh.topology().dim() >= marking_function.dim() # Work in serial only (much like submesh) assert df.MPI.size(base_mesh.mpi_comm()) == 1 gdim = base_mesh.geometry().dim() tdim = marking_function.dim() assert tdim > 0, 'No Embedded mesh from vertices' if isinstance(markers, int): markers = [markers] assert markers, markers # We reuse a lot of Submesh capabilities if marking by cell_f if base_mesh.topology().dim() == marking_function.dim(): # Submesh works only with one marker so we conform color_array = marking_function.array() color_cells = dict( (m, np.where(color_array == m)[0]) for m in markers) # So everybody is marked as 1 one_cell_f = df.MeshFunction('size_t', base_mesh, tdim, 0) for cells in color_cells.itervalues(): one_cell_f.array()[cells] = 1 # The Embedded mesh now steals a lot from submesh submesh = df.SubMesh(base_mesh, one_cell_f, 1) df.Mesh.__init__(self, submesh) # The entity mapping attribute mesh_key = marking_function.mesh().id() self.parent_entity_map = { mesh_key: { 0: submesh.data().array('parent_vertex_indices', 0), tdim: submesh.data().array('parent_cell_indices', tdim) } } # Finally it remains to preserve the markers f = df.MeshFunction('size_t', self, tdim, 0) if len(markers) > 1: # We turn the old cells to set for faster lookup color_cells = {k: set(v) for k, v in color_cells.iteritems()} # And then use the new -> old mapping to color for new_cell, old_cell in enumerate( self.parent_entity_map[mesh_key][tdim]): for color, cells in color_cells.iteritems(): if old_cell in cells: f[new_cell] = color break else: f.set_all(markers[0]) self.marking_function = f return None # https://stackoverflow.com/questions/2491819/how-to-return-a-value-from-init-in-python # Otherwise the mesh needs to by build from scratch base_mesh.init(tdim, 0) # Collect unique vertices based on their new-mesh indexing, the cells # of the embedded mesh are defined in terms of their embedded-numbering new_vertices, new_cells = [], [] # NOTE: new_vertices is actually new -> old vertex map # Map from cells of embedded mesh to tdim entities of base mesh, and cell_map = [] cell_colors = defaultdict(list) # Preserve the markers new_cell_index, new_vertex_index = 0, 0 for marker in markers: for entity in df.SubsetIterator(marking_function, marker): vs = entity.entities(0) cell = [] # Vertex lookup for v in vs: try: local = new_vertices.index(v) except ValueError: local = new_vertex_index new_vertices.append(v) new_vertex_index += 1 # Cell, one by one in terms of vertices cell.append(local) # The cell new_cells.append(cell) # Into map cell_map.append(entity.index()) # Colors cell_colors[marker].append(new_cell_index) new_cell_index += 1 # With acquired data build the mesh df.Mesh.__init__(self) editor = df.MeshEditor() if df.__version__ == '2017.2.0': cell_type = {1: 'interval', 2: 'triangle', 3: 'tetrahedron'}[tdim] editor.open(self, cell_type, tdim, gdim) else: editor.open(self, tdim, gdim) editor.init_vertices(len(new_vertices)) editor.init_cells(len(new_cells)) vertex_coordinates = base_mesh.coordinates()[new_vertices] for vi, x in enumerate(vertex_coordinates): editor.add_vertex(vi, x) for ci, c in enumerate(new_cells): editor.add_cell(ci, *c) editor.close() # The entity mapping attribute mesh_key = marking_function.mesh().id() self.parent_entity_map = {mesh_key: {0: new_vertices, tdim: cell_map}} f = df.MeshFunction('size_t', self, tdim, 0) f_ = f.array() # Finally the inherited marking function if len(markers) > 1: for marker, cells in cell_colors.iteritems(): f_[cells] = marker else: f.set_all(markers[0]) self.marking_function = f
def create_dolfin_mesh(grid): """ Create a DOLFIN mesh from VTK unstructured grid. Args: grid: VTK unstructured grid. Returns: mesh (dolfin.Mesh): DOLFIN mesh object. """ print("Creating DOLFIN mesh") v2n = vtk.util.numpy_support.vtk_to_numpy coords = v2n(grid.GetPoints().GetData()) cells = v2n(grid.GetCells().GetData()) cell_types = v2n(grid.GetCellTypesArray()) cell_locations = v2n(grid.GetCellLocationsArray()) num_vertices = grid.GetNumberOfPoints() num_cells = grid.GetNumberOfCells() print("VTK grid has {} vertices".format(num_vertices)) print("VTK grid has {} cells".format(num_cells)) mesh = dolfin.Mesh() vtk_to_dolfin_celltype_map = { # VTK_TETRAHEDRON 10: { "celltype": "tetrahedron", "tdim": 3, "gdim": 3, "degree": 1, "ordering": [0, 1, 2, 3] }, # VTK_HEXAHEDRON 12: { "celltype": "hexahedron", "tdim": 3, "gdim": 3, "degree": 1, "ordering": [0, 1, 3, 2, 4, 5, 7, 6] }, } # DOLFIN only supports meshes of a single element type if not (cell_types == cell_types[0]).all(): raise ValueError("Grid contains cells of different types") dolfin_cell_data = vtk_to_dolfin_celltype_map[cell_types[0]] celltype = dolfin_cell_data["celltype"] tdim = dolfin_cell_data["tdim"] gdim = dolfin_cell_data["gdim"] degree = dolfin_cell_data["degree"] me = dolfin.MeshEditor() me.open(mesh, celltype, tdim, gdim, degree=degree) me.init_vertices(num_vertices) for i, x in enumerate(coords): me.add_vertex(i, x) me.init_cells(num_cells) for i, l in enumerate(cell_locations): cell = cells[l + 1:l + 1 + cells[l]] cell = [cell[j] for j in dolfin_cell_data["ordering"]] me.add_cell(i, cell) # mesh.order() mesh.init() print("DOLFIN mesh has {} vertices".format(mesh.num_vertices())) print("DOLFIN mesh has {} cells".format(mesh.num_cells())) return mesh
def create_mesh(txt): # pegando pontos do arquivo vtu e definindo nossos numeros de vertices (nvertices) e o numero de celulas (ncells) with open(txt) as arquivo: ret = arquivo.read() ret = ret.split('"') nvertices = int(ret[7]) ncells = int(ret[9]) # limpando o arquivo.vtu de caracteres especiais e deixando ele com todos os valor como elementos da lista limpa with open(txt) as arquivo: ret = arquivo.read() ret = ret.split("'", ) nova = [] novamente = [] limpa = [] for palavras in ret: nova.append(palavras.split('\n')) for i in range(len(nova)): for palavras in nova[i]: novamente.append(palavras.split(' ')) for i in range(len(novamente)): for palavras in novamente[i]: if palavras is not '': limpa.append(palavras) print(f'o numero de vertices é {nvertices} \n') print(f'o numero de faces é {ncells} \n') # criando as listas de vertices e de celulas, a lista de vertices começa no indice 13 pois é o indice que começa os pontos dela, indo até 3 vezes o numero de vertices,pois cada vertice tem x,y e z, as celular começam 7 indices depois do fim do numero de vertices indo até 3 vezes o numero dela pois tambem tem 3 elementos pra cada vertice vertices = [float(limpa[i]) for i in range(13, 13 + 3 * nvertices)] cells = [int(limpa[i]) for i in range(20 + 3 * nvertices, 20 + 3 * nvertices + 3 * ncells)] # para poder criar a mesh foi criado um vetor de pontos dolfin utilizando a lista vertices (Vpoints), cada coordenadas de vertices é criado um ponto dolfin, já para as celulas era necessario um array com 3 elementos, então foi criado uma lista onde cada elemento da lista é um array contendo 3 coordenadas da celula(Cpoints) Vpoints = [] near = 0 for i in range(0, len(vertices), 3): Vpoints.append(df.Point(vertices[i], vertices[i + 1])) if vertices[i] >= near: near = vertices[i] Cpoints = [] for i in range(0, len(cells), 3): Caux = [cells[i], cells[i + 1], cells[i + 2]] Cpoints.append(Caux) # criando a malha mesh = df.Mesh() editor = df.MeshEditor() editor.open(mesh, 'triangle', 2, 2) # Adicionandos os vertices contidos em Vpoints editor.init_vertices(nvertices) for i in range(nvertices): editor.add_vertex(i, Vpoints[i]) # adicionando as celulas que estão em Cpoints editor.init_cells(ncells) for i in range(len(Cpoints)): editor.add_cell(i, Cpoints[i]) # fechando a edição da malha e retornando a mesma editor.close() print(f'criado uma malha com {nvertices} vertices e {ncells} celulas') return mesh,near