def test_cli(): input_mesh = helpers.tri_mesh infile = tempfile.NamedTemporaryFile().name meshio.write(infile, input_mesh, file_format="gmsh4-ascii") outfile = tempfile.NamedTemporaryFile().name meshio.cli.main( [ infile, outfile, "--input-format", "gmsh-ascii", "--output-format", "vtk-binary", ] ) mesh = meshio.read(outfile, file_format="vtk-binary") atol = 1.0e-15 assert numpy.allclose(input_mesh.points, mesh.points, atol=atol, rtol=0.0) for cell_type, data in input_mesh.cells.items(): assert numpy.allclose(data, mesh.cells[cell_type]) return
def write(self, filename, point_data=None, cell_data=None, field_data=None ): if self.node_coords.shape[1] == 2: n = len(self.node_coords) a = numpy.ascontiguousarray( numpy.c_[self.node_coords, numpy.zeros(n)] ) else: a = self.node_coords if self.cells['nodes'].shape[1] == 3: cell_type = 'triangle' elif self.cells['nodes'].shape[1] == 4: cell_type = 'tetra' else: raise RuntimeError('Only triangles/tetrahedra supported') meshio.write( filename, a, {cell_type: self.cells['nodes']}, point_data=point_data, cell_data=cell_data, field_data=field_data )
def mesh(mesh_path, lc, H, L, b_dist, b_h, b_l, f_l, f_h, **NS_namespace): # Name mesh after local cell length mesh_path = mesh_path.format(lc) if not path.exists(mesh_path): # Initialize geometry geom = pygmsh.built_in.geometry.Geometry() # Surounding box b0 = geom.add_point([0, 0, 0], lcar=lc*2) b1 = geom.add_point([L, 0, 0], lcar=lc*2) b2 = geom.add_point([L, H, 0], lcar=lc*2) b3 = geom.add_point([0, H, 0], lcar=lc*2) # Inner geometry f0 = geom.add_point([b_dist, H / 2 - b_h / 2, 0], lcar=lc/3) f1 = geom.add_point([b_dist + b_l, H / 2 - b_h / 2, 0], lcar=lc/3) f2 = geom.add_point([b_dist + b_l, H / 2 - f_h / 2, 0], lcar=lc/3) f3 = geom.add_point([b_dist + b_l + f_l, H / 2 - f_h / 2, 0], lcar=lc/3) f4 = geom.add_point([b_dist + b_l + f_l, H / 2 + f_h / 2, 0], lcar=lc/3) f5 = geom.add_point([b_dist + b_l, H / 2 + f_h / 2, 0], lcar=lc/3) f6 = geom.add_point([b_dist + b_l, H / 2 + b_h / 2, 0], lcar=lc/3) f7 = geom.add_point([b_dist, H / 2 + b_h / 2, 0], lcar=lc/3) # Draw lines l0 = geom.add_line(b0, b1) l1 = geom.add_line(b1, b2) l2 = geom.add_line(b2, b3) l3 = geom.add_line(b3, b0) l4 = geom.add_line(f0, f1) l5 = geom.add_line(f1, f2) l6 = geom.add_line(f2, f3) l7 = geom.add_line(f3, f4) l8 = geom.add_line(f4, f5) l9 = geom.add_line(f5, f6) l10 = geom.add_line(f6, f7) l11 = geom.add_line(f7, f0) # Gather lines ll_outer = geom.add_line_loop(lines=[l0, l1, l2, l3]) ll_inner = geom.add_line_loop(lines=[l4, l5, l6, l7, l8, l9, l10, l11]) # Set surface ps = geom.add_plane_surface(ll_outer, [ll_inner]) # Mesh surface points, cells, point_data, cell_data, field_data = pygmsh.generate_mesh(geom) # Write mesh meshio.write(mesh_path, meshio.Mesh( points=points, cells={"triangle": cells["triangle"]})) mesh = Mesh() with XDMFFile(MPI.comm_world, mesh_path) as infile: infile.read(mesh) return mesh
def mesh(mesh_path, mesh_function_path, lc, **NS_namespace): # Inspired from # https://gist.github.com/michalhabera/bbe8a17f788192e53fd758a67cbf3bed geom = pygmsh.built_in.geometry.Geometry() r1 = 1.7*2 r2 = 3.8*2 # Create geometry p0 = geom.add_point([ 0, 0, 0], lcar=lc) p1 = geom.add_point([ r1, 0, 0], lcar=lc) p2 = geom.add_point([ 0, -2*r2, 0], lcar=lc) p3 = geom.add_point([-r1, 0, 0], lcar=lc) p4 = geom.add_point([ 1.615, 0, 0], lcar=lc) p5 = geom.add_point([-0.085, 0, 0], lcar=lc) p6 = geom.add_point([-0.272, 0, 0], lcar=lc) p7 = geom.add_point([-1.632, 0, 0], lcar=lc) l0 = geom.add_ellipse_arc(p1, p0, p2, p2) l1 = geom.add_ellipse_arc(p2, p0, p3, p3) #l2 = geom.add_line(p3, p1) l3 = geom.add_line(p3, p7) l4 = geom.add_line(p7, p6) l5 = geom.add_line(p6, p5) l6 = geom.add_line(p5, p4) l7 = geom.add_line(p4, p1) #ll = geom.add_line_loop(lines=[l0, l1, l2]) ll = geom.add_line_loop(lines=[l7, l0, l1, l3, l4, l5, l6]) ps = geom.add_plane_surface(ll) # Tag line and surface geom.add_physical_line(lines=l4, label=1) geom.add_physical_line(lines=l6, label=2) geom.add_physical_line(lines=[l7, l0, l1, l3, l5], label=3) geom.add_physical_surface(surfaces=ps, label=4) # Mesh surface points, cells, point_data, cell_data, field_data = pygmsh.generate_mesh(geom) # Write, then read mesh and MeshFunction meshio.write(mesh_path, meshio.Mesh( points=points, cells={"triangle": cells["triangle"]})) meshio.write(mesh_function_path, meshio.Mesh( points=points, cells={"line": cells["line"]}, cell_data={"line": {"boundary": cell_data["line"]["gmsh:physical"]}} )) mesh = Mesh() with XDMFFile(MPI.comm_world, mesh_path) as infile: infile.read(mesh) return mesh
def test_boundaries(self): import meshzoo from scipy.sparse import linalg class Gamma0(Subdomain): def is_inside(self, x): return x[1] < 0.5 is_boundary_only = True class Gamma1(Subdomain): def is_inside(self, x): return x[1] >= 0.5 is_boundary_only = True # Define the problem class Poisson(LinearFvmProblem): def apply(self, u): return integrate(lambda x: -n_dot_grad(u(x)), dS) \ - integrate(lambda x: 1.0, dV) def dirichlet(self, u): return [ (lambda x: u(x) - 0.0, Gamma0()), (lambda x: u(x) - 1.0, Gamma1()) ] # Create mesh using meshzoo vertices, cells = meshzoo.rectangle.create_mesh( 0.0, 1.0, 0.0, 1.0, 21, 21, zigzag=True ) mesh = pyfvm.meshTri.meshTri(vertices, cells) linear_system = pyfvm.discretize(Poisson(), mesh) x = linalg.spsolve(linear_system.matrix, linear_system.rhs) import meshio meshio.write('test.vtu', mesh.node_coords, {'triangle': mesh.cells['nodes']}, point_data={'x': x}) k0 = -1 for k, coord in enumerate(mesh.node_coords): # print(coord - [0.5, 0.5, 0.0]) if numpy.linalg.norm(coord - [0.5, 0.5, 0.0]) < 1.0e-5: k0 = k break self.assertNotEqual(k0, -1) self.assertAlmostEqual(x[k0], 0.59455184740329481, delta=1.0e-7) x_dot_x = numpy.dot(x, mesh.control_volumes * x) self.assertAlmostEqual(x_dot_x, 0.42881926935620163, delta=1.0e-7) return
def writeVTKFile(self,fn="",sub=False): """Writes mesh into vtk file. Uses *meshIO* (https://github.com/nschloe/meshio), to convert the mesh saved in ``fnMesh`` to a .vtk file. If ``sub==True``, will start a seperate subprocess and submit ``pyfrp_meshIO_script.py`` to it. This can be sometimes useful, since PyFRAP sometimes tends to crash otherwise. If no output path is given via ``fn``, will use same path as ``fnMesh``. .. note:: *meshIO* only gets imported inside this function, making PyFRAP running even without the package installed. However, this feature will only run with *meshIO*. Keyword Args: fn (str): Optional output path. sub (bool): Subprocess flag. Returns: str: Used output path. """ if not os.path.isfile(self.fnMesh): printWarning("Filepath to meshfile has not been specified yet. Cannot write VTK file.") if fn=="": fn=self.fnMesh.replace('.msh','.vtk') if sub: cmd = "python pyfrp_meshIO_script.py "+ self.fnMesh import shlex import subprocess args = shlex.split(cmd) p = subprocess.Popen(args) p.wait() else: #MeshIO import meshio points, cells, point_data, cell_data, field_data = meshio.read(self.fnMesh) meshio.write(fn,points,cells,point_data=point_data,cell_data=cell_data,field_data=field_data) return fn
def gen_mesh(self, filename, n): import pygmsh as pg geom = pg.Geometry() loops = [] for be in self.blade_elements: car = 0.5/1000 line_l, line_u = be.get_foil_points(n, self.get_scimitar_offset(be.r)) loop_points = np.concatenate((line_l, line_u[::-1]), axis=0) g_pts = [] for p in loop_points[0:-2]: g_pts.append(geom.add_point(p,car)) l_foil = geom.add_bspline(g_pts) loops.append(l_foil) #print geom.get_code() geom.add_ruled_surface([loops[0], loops[1]]) #l in range(len(loops) - 1): #geom.add_surface(loops[l], loops[l+1]) #poly = geom.add_polygon([ #[0.0, 0.5, 0.0], #[-0.1, 0.1, 0.0], #[-0.5, 0.0, 0.0], #[-0.1, -0.1, 0.0], #[0.0, -0.5, 0.0], #[0.1, -0.1, 0.0], #[0.5, 0.0, 0.0], #[0.1, 0.1, 0.0] #], #lcar=0.05 #) #axis = [0, 0, 1] #geom.extrude( #'Surface{%s}' % poly, #translation_axis=axis, #rotation_axis=axis, #point_on_axis=[0, 0, 0], #angle=2.0 / 6.0 * np.pi #) points, cells = pg.generate_mesh(geom) import meshio meshio.write(filename, points, cells)
def write_file(name, obj, **cell_data): for ext in ['msh','vtk']: t1 = time.time() fname = "test_geometry_%s.%s"%(name, ext) print 'min/max elements:', numpy.min(obj.grid_elements), numpy.max(obj.grid_elements) print "points: ",obj.grid_points.shape cd = dict(cell_data, domains=obj.grid_domains) print "cell data:", obj.grid_elements.shape for k,v in cd.items(): print "\t",k,v.shape meshio.write(fname, obj.grid_points, dict(triangle=obj.grid_elements), cell_data = cd) t2 = time.time() print 'wrote %s in %.1f seconds' % (fname, t2-t1)
def _write_read(filename, mesh): '''Write and read a file, and make sure the data is the same as before. ''' meshio.write( filename, mesh['points'], mesh['cells'], point_data=mesh['point_data'], cell_data=mesh['cell_data'] ) points, cells, point_data, cell_data, _ = meshio.read(filename) # We cannot compare the exact rows here since the order of the points might # have changes. Just compare the sums assert numpy.allclose(mesh['points'], points) for key, data in mesh['cells'].items(): assert numpy.array_equal(data, cells[key]) for key, data in mesh['point_data'].items(): assert numpy.array_equal(data, point_data[key]) for key, data in mesh['cell_data'].items(): assert numpy.array_equal(data, cell_data[key]) return
def _write_read(filename, mesh): '''Write and read a file, and make sure the data is the same as before. ''' try: input_point_data = mesh['point_data'] except KeyError: input_point_data = {} try: input_cell_data = mesh['cell_data'] except KeyError: input_cell_data = {} meshio.write( filename, mesh['points'], mesh['cells'], point_data=input_point_data, cell_data=input_cell_data ) points, cells, point_data, cell_data, _ = meshio.read(filename) # Numpy's array_equal is too strict here, cf. # <https://mail.scipy.org/pipermail/numpy-discussion/2015-December/074410.html>. # Use allclose. # We cannot compare the exact rows here since the order of the points might # have changes. Just compare the sums assert numpy.allclose(mesh['points'], points) for key, data in mesh['cells'].items(): assert numpy.allclose(data, cells[key]) for key, data in input_point_data.items(): assert numpy.allclose(data, point_data[key]) for key, data in input_cell_data.items(): assert numpy.allclose(data, cell_data[key]) os.remove(filename) return
def read_write(): X, cells = generate_mesh() formats = [ "ansys-ascii", "ansys-binary", "exodus", "dolfin-xml", "gmsh-ascii", "gmsh-binary", "med", "medit", "permas", "moab", "off", "stl-ascii", "stl-binary", "vtk-ascii", "vtk-binary", "vtu-ascii", "vtu-binary", "xdmf", ] filename = "foo" print() print("format write (s) read(s)") print() for fmt in formats: t = time.time() meshio.write(filename, X, cells, file_format=fmt) elapsed_write = time.time() - t t = time.time() meshio.read(filename, file_format=fmt) elapsed_read = time.time() - t print("{0: <12} {1:e} {2:e}".format(fmt, elapsed_write, elapsed_read)) return
def _write_file(name, p, e, pd=None, cd=None, fd=None): pd = pd or dict() cd = cd or dict() fd = fd or dict() print 'points:',p.shape print 'elements:',len(e) for k,v in e.items(): print '\t%s:%s' % (k, v.shape) print 'point data:',len(pd) for k,v in pd.items(): print '\t%s:%s' % (k,v.shape) print 'cell data:',len(cd) for k,v in cd.items(): print '\t%s:%s' % (k,v.shape) for ext in ['msh','vtk']: t1 = time.time() fname = "test_geometry_%s.%s"%(name, ext) meshio.write(fname,p,e, point_data=pd,cell_data=cd,field_data=fd) t2 = time.time() print 'wrote %s in %.1f seconds' % (fname, t2-t1)
entity_cells = {} entity_data = {} volume_cell = list(mesh.cells_dict.keys())[-1] cells[volume_cell] = mesh.cells_dict[volume_cell] print("Mesh of {} {}".format(len(cells[volume_cell]), volume_cell)) if volume_cell in mesh.cell_data_dict["gmsh:physical"]: cell_data[volume_cell] = [mesh.get_cell_data("gmsh:physical", volume_cell)] print("Tagged {} {}".format(len(cell_data[volume_cell][0]), volume_cell)) else: cell_data[volume_cell] = [] meshio.write("{}.xdmf".format(args.outfile), meshio.Mesh(points=mesh.points, cells=cells, cell_data=cell_data), file_format="xdmf") if len(mesh.cells_dict.keys()) > 1: entity_cell = list(mesh.cells_dict.keys())[-2] entity_cells[entity_cell] = mesh.cells_dict[entity_cell] if entity_cell in mesh.cell_data_dict["gmsh:physical"]: entity_data[entity_cell] = [ mesh.get_cell_data("gmsh:physical", entity_cell) ] print("Tagged {} {}".format(len(entity_data[entity_cell][0]), entity_cell)) else: entity_data[entity_cell] = []
points.append(geom.add_point((x[0], y[1], z[1]), lcar=lcar)) points.append(geom.add_point((x[0], y[1], z[2]), lcar=lcar)) points.append(geom.add_point((x[0], y[2], z[2]), lcar=lcar)) points.append(geom.add_point((x[0], y[2], z[1]), lcar=lcar)) points.append(geom.add_point((x[0], y[3], z[1]), lcar=lcar)) points.append(geom.add_point((x[0], y[3], z[0]), lcar=lcar)) lines = [] lines.append(geom.add_line(points[0], points[1])) lines.append(geom.add_circle_arc(points[1], points[2], points[3])) lines.append(geom.add_line(points[3], points[4])) lines.append(geom.add_circle_arc(points[4], points[5], points[6])) lines.append(geom.add_line(points[6], points[7])) lines.append(geom.add_line(points[7], points[0])) line_loop = geom.add_line_loop(lines) surface = geom.add_plane_surface(line_loop) vol = geom.extrude(surface, translation_axis=[l, 0, 0]) points, cells, _, _, _ = pygmsh.generate_mesh(geom) ref = 24941.503891355664 assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return points, cells if __name__ == '__main__': import meshio meshio.write('opencascade_extrude2.vtu', *test())
import meshio msh = meshio.read("tensile_dog_bone_specimen.msh") for cell in msh.cells: if cell.type == "triangle": triangle_cells = cell.data elif cell.type == "tetra": tetra_cells = cell.data for key in msh.cell_data_dict["gmsh:physical"].keys(): if key == "triangle": triangle_data = msh.cell_data_dict["gmsh:physical"][key] elif key == "tetra": tetra_data = msh.cell_data_dict["gmsh:physical"][key] tetra_mesh = meshio.Mesh(points=msh.points, cells={"tetra": tetra_cells}) triangle_mesh =meshio.Mesh(points=msh.points, cells=[("triangle", triangle_cells)], cell_data={"name_to_read":[triangle_data]}) meshio.write("mesh.xdmf", tetra_mesh) meshio.write("mf.xdmf", triangle_mesh)
#! /usr/bin/env python # -*- coding: utf-8 -*- from math import pi import pytest import pygmsh from helpers import compute_volume @pytest.mark.skipif(pygmsh.get_gmsh_major_version() < 3, reason="requires Gmsh >= 3") def test(): geom = pygmsh.opencascade.Geometry() geom.add_ball( [0.0, 0.0, 0.0], 1.0, x0=-0.9, x1=+0.9, alpha=0.5 * pi, char_length=0.1 ) ref = 0.976088698545 points, cells, _, _, _ = pygmsh.generate_mesh(geom) assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return points, cells if __name__ == "__main__": import meshio meshio.write("opencascade_ball.vtu", *test())
import pygmsh import numpy as np from helpers import compute_volume def test(): '''Torus, rotated in space. ''' geom = pygmsh.built_in.Geometry() R = np.array([[1.0, 0.0, 0.0], [0.0, 0.0, 1.0], [0.0, 1.0, 0.0]]) geom.add_torus(irad=0.05, orad=0.6, lcar=0.03, x0=[0.0, 0.0, -1.0], R=R) R = np.array([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]) geom.add_torus(irad=0.05, orad=0.6, lcar=0.03, x0=[0.0, 0.0, 1.0], variant='extrude_circle') ref = 0.06604540601899624 points, cells, _, _, _ = pygmsh.generate_mesh(geom) assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return points, cells if __name__ == '__main__': import meshio meshio.write('torus.vtu', *test())
geom = pygmsh.built_in.Geometry() # Draw a square poly = geom.add_polygon( [[+0.5, +0.0, 0.0], [+0.0, +0.5, 0.0], [-0.5, +0.0, 0.0], [+0.0, -0.5, 0.0]], lcar=lcar, ) axis = [0, 0, 1.0] geom.extrude( poly, translation_axis=axis, rotation_axis=axis, point_on_axis=[0.0, 0.0, 0.0], angle=0.5 * pi, num_layers=5, recombine=True, ) ref = 3.98156496566 mesh = pygmsh.generate_mesh(geom) assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("rotated_layers.vtu", test())
def test(): x = 5 y = 4 z = 3 x_layers = 10 y_layers = 5 z_layers = 3 geom = pygmsh.opencascade.Geometry() p = geom.add_point([0, 0, 0], 1) _, l, _ = geom.extrude(p, [x, 0, 0], num_layers=x_layers) _, s, _ = geom.extrude(l, [0, y, 0], num_layers=y_layers) geom.extrude(s, [0, 0, z], num_layers=z_layers) mesh = pygmsh.generate_mesh(geom) ref_vol = x * y * z assert abs(compute_volume(mesh) - ref_vol) < 1.0e-2 * ref_vol # Each grid-cell from layered extrusion will result in 6 tetrahedrons. ref_tetras = 6 * x_layers * y_layers * z_layers assert len(mesh.cells_dict["tetra"]) == ref_tetras return mesh if __name__ == "__main__": import meshio meshio.write("cube.vtu", test())
def gosplDisp(coords, lonlat, cells, paleodisp, dispmesh, visvtk=False, reverse=False): with open(paleodisp) as f: for i, l in enumerate(f): pass maxlines = i # Open gPlates 1 degree 3D displacement maps (xy files) data = pd.read_csv( paleodisp, sep=r"\s+", engine="c", header=None, skiprows=[0, 1, 2, 3, 4, 5, maxlines], error_bad_lines=True, na_filter=False, dtype=np.float, low_memory=False, ) # Build the kdtree lon = data.values[:, 0] + 180.0 lat = data.values[:, 1] + 90.0 # Create kdtree... tree2 = cKDTree(list(zip(lon, lat))) d2, inds2 = tree2.query(list(zip(lonlat[0, :], lonlat[1, :])), k=1) # Conversion from cm/yr to m/yr if reverse: tmpx = -data.values[:, 2] / 100.0 tmpy = -data.values[:, 3] / 100.0 tmpz = -data.values[:, 4] / 100.0 else: tmpx = data.values[:, 2] / 100.0 tmpy = data.values[:, 3] / 100.0 tmpz = data.values[:, 4] / 100.0 # speed = np.sqrt(np.square(tmpx) + np.square(tmpy) + np.square(tmpz)) # Interpolate the paleo displacement on global mesh dX = tmpx.flatten()[inds2].reshape(lonlat[0, :].shape) dY = tmpy.flatten()[inds2].reshape(lonlat[0, :].shape) dZ = tmpz.flatten()[inds2].reshape(lonlat[0, :].shape) disps = np.stack((dX, dY, dZ)).T # Save the mesh as compressed numpy file for global simulation np.savez_compressed(dispmesh, xyz=disps) if visvtk: paleovtk = dispmesh + ".vtk" vis_mesh = meshio.Mesh( coords, {"triangle": cells}, point_data={ "x": disps[:, 0], "y": disps[:, 1], "z": disps[:, 2] }, ) meshio.write(paleovtk, vis_mesh) print("Writing VTK file {}".format(paleovtk)) return
import pygmsh def test(): geom = pygmsh.built_in.Geometry() lcar = 0.1 p1 = geom.add_point([0.0, 0.0, 0.0], lcar) p2 = geom.add_point([1.0, 0.0, 0.0], lcar) p3 = geom.add_point([1.0, 0.5, 0.0], lcar) p4 = geom.add_point([1.0, 1.0, 0.0], lcar) s1 = geom.add_bspline([p1, p2, p3, p4]) p2 = geom.add_point([0.0, 1.0, 0.0], lcar) p3 = geom.add_point([0.5, 1.0, 0.0], lcar) s2 = geom.add_bspline([p4, p3, p2, p1]) ll = geom.add_line_loop([s1, s2]) geom.add_plane_surface(ll) ref = 0.9156598733673261 if pygmsh.get_gmsh_major_version() < 4 else 0.75 mesh = pygmsh.generate_mesh(geom) assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("bsplines.vtu", test())
#! /usr/bin/env python # -*- coding: utf-8 -*- from math import pi import pytest import pygmsh from helpers import compute_volume @pytest.mark.skipif(pygmsh.get_gmsh_major_version() < 3, reason="requires Gmsh >= 3") def test(): geom = pygmsh.opencascade.Geometry() geom.add_cylinder([0.0, 0.0, 0.0], [0.0, 0.0, 1.0], 0.5, 0.25 * pi, char_length=0.1) ref = 0.097625512963 points, cells, _, _, _ = pygmsh.generate_mesh(geom) assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return points, cells if __name__ == "__main__": import meshio meshio.write("opencascade_cylinder.vtu", *test())
circ = geom.add_circle([0.0, 0.0, 0.0], 0.1, lcar=lcar, make_surface=False) poly = geom.add_polygon( [ [+0.0, +0.5, 0.0], [-0.1, +0.1, 0.0], [-0.5, +0.0, 0.0], [-0.1, -0.1, 0.0], [+0.0, -0.5, 0.0], [+0.1, -0.1, 0.0], [+0.5, +0.0, 0.0], [+0.1, +0.1, 0.0], ], lcar=lcar, holes=[circ], ) axis = [0, 0, 1.0] geom.extrude(poly, translation_axis=axis, num_layers=1) ref = 0.16951514066385628 mesh = pygmsh.generate_mesh(geom) assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("layers.vtu", test())
def to_file(mesh, filename, point_data=None, **kwargs): meshio.write(filename, to_meshio(mesh, point_data), **kwargs)
def test_info(): input_mesh = helpers.tri_mesh infile = tempfile.NamedTemporaryFile().name meshio.write(infile, input_mesh, file_format="gmsh") meshio._cli.info([infile, "--input-format", "gmsh"])
# Create polygon for airfoil char_length = 1.0e-1 airfoil = geom.add_polygon(airfoil_coordinates, char_length, make_surface=False) # Create surface for numerical domain with an airfoil-shaped hole left_dist = 1.0 right_dist = 3.0 top_dist = 1.0 bottom_dist = 1.0 xmin = airfoil_coordinates[:, 0].min() - left_dist * coord xmax = airfoil_coordinates[:, 0].max() + right_dist * coord ymin = airfoil_coordinates[:, 1].min() - bottom_dist * coord ymax = airfoil_coordinates[:, 1].max() + top_dist * coord domainCoordinates = numpy.array( [[xmin, ymin, 0.0], [xmax, ymin, 0.0], [xmax, ymax, 0.0], [xmin, ymax, 0.0]] ) polygon = geom.add_polygon(domainCoordinates, char_length, holes=[airfoil]) geom.add_raw_code("Recombine Surface {{{}}};".format(polygon.surface.id)) ref = 10.525891646546 mesh = pygmsh.generate_mesh(geom, remove_faces=True) assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("airfoil.vtu", test())
# -*- coding: utf-8 -*- from math import pi import pytest import pygmsh from helpers import compute_volume @pytest.mark.skipif(pygmsh.get_gmsh_major_version() < 3, reason="requires Gmsh >= 3") def test(): geom = pygmsh.opencascade.Geometry() geom.add_torus([0.0, 0.0, 0.0], 1.0, 0.3, 1.25 * pi, char_length=0.1) ref = 1.09994740709 mesh = pygmsh.generate_mesh(geom) assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("opencascade_torus.vtu", test())
# Vertices of a square hole squareHoleCoordinates = np.array([[1, 1, 0], [4, 1, 0], [4, 4, 0], [1, 4, 0]]) # Create geometric object geom = pygmsh.built_in.Geometry() # Create square hole squareHole = geom.add_polygon(squareHoleCoordinates, lcar, make_surface=False) # Create square domain with square hole geom.add_rectangle(xmin, xmax, ymin, ymax, 0.0, lcar, holes=[squareHole.line_loop]) ref = 16.0 points, cells, _, _, _ = pygmsh.generate_mesh(geom) assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return points, cells if __name__ == '__main__': import meshio meshio.write('hole_in_square.vtu', *test())
circle = geom.add_circle([0.5, 0.5, 0.0], 1.0, lcar) triangle = geom.add_polygon([ [2.0, -0.5, 0.0], [4.0, -0.5, 0.0], [4.0, 1.5, 0.0], ], lcar ) rectangle = geom.add_rectangle(4.75, 6.25, -0.24, 1.25, 0.0, lcar) # hold all domain geom.add_polygon([ [-1.0, -1.0, 0.0], [+7.0, -1.0, 0.0], [+7.0, +2.0, 0.0], [-1.0, +2.0, 0.0], ], lcar, holes=[circle.line_loop, triangle.line_loop, rectangle.line_loop] ) ref = 24.0 points, cells, _, _, _ = pygmsh.generate_mesh(geom) assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return points, cells if __name__ == '__main__': import meshio meshio.write('subdomains.vtu', *test())
#! /usr/bin/env python # -*- coding: utf-8 -*- from math import pi import pytest import pygmsh from helpers import compute_volume @pytest.mark.skipif(pygmsh.get_gmsh_major_version() < 3, reason='requires Gmsh >= 3') def test(): geom = pygmsh.opencascade.Geometry() geom.add_cylinder([0.0, 0.0, 0.0], [0.0, 0.0, 1.0], 0.5, 0.25 * pi, char_length=0.1) ref = 0.097625512963 points, cells, _, _, _ = pygmsh.generate_mesh(geom) assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return points, cells if __name__ == '__main__': import meshio meshio.write('opencascade_cylinder.vtu', *test())
#meshes to render files_to_use = [ 'b6b378a05bf6982b70c33714b19283df', 'e16c0191973a25f02d63c890dc92b5', 'e2d06603fba3bf3310af74324aae27f', 'b7a9d8b469cb06037824b732b006daaa', 'e22f10f551cac7fc6cb99ff1a702c4e9', 'eaf341c056c79bec1a2c782fdbf60db6' ] for mesh_file in files_to_use: if '.ipynb' in mesh_file: continue mesh = meshio.read( os.path.join(off_folder, mesh_file + '.off'), # string, os.PathLike, or a buffer/open file ) meshio.write( os.path.join(outfolder, mesh_file + '.obj'), mesh, ) ot_file = os.path.join(outfolder, mesh_file + '.obj') render_file = os.path.join(render_dir) blender_command = f'blender --background --python render_blender.py -- --output_folder {render_file} {ot_file} --format OPEN_EXR --color_depth 16 --scale 2.5' blender_command_args = shlex.split(blender_command) p1 = Popen(blender_command_args, stdout=PIPE, stderr=PIPE) time.sleep(0.1) out, err = p1.communicate()
[0.0, 0.5, 0.0], [-0.1, 0.1, 0.0], [-0.5, 0.0, 0.0], [-0.1, -0.1, 0.0], [0.0, -0.5, 0.0], [0.1, -0.1, 0.0], [0.5, 0.0, 0.0], [0.1, 0.1, 0.0] ], lcar=0.05 ) axis = [0, 0, 1] geom.extrude( 'Surface{%s}' % poly, translation_axis=axis, rotation_axis=axis, point_on_axis=[0, 0, 0], angle=2.0 / 6.0 * np.pi ) points, cells = pg.generate_mesh(geom) return points, cells['tetra'] if __name__ == '__main__': import meshio points, cells = create_screw_mesh() meshio.write('screw.e', points, {'tetra': cells})
def mesh_3D(): """ creates a simple model with hexahedral mesh """ # # note: we want to create a hexahedral mesh with mostly regular shape, like a structured grid. # Gmsh allows this by using an extrusion. we will thus create a surface at top and extrude it down along vertical direction. # # however, the extrude-command will only return identifiers for the top and lateral surfaces, but not the bottom. # we will thus create explicitly the bottom surface, which will get meshed and merged with the mesh from the extrusion. # this will allow us to define physical surfaces for all bounding surfaces, and the mesh file will contain all surface quads. # # for topography, using a top surface with topography and then extrude it down would lead to problems (flat bottom surface?). # thus to obtain a top with some elevation, we will stretch the mesh points accordingly after the mesh was generated. # it is done here in a simple way to show how one could modify the mesh. global xsize,ysize,zsize,mesh_element_size_XY,mesh_element_size_Z global python_major_version,pygmsh_major_version # output directory for mesh files os.system("mkdir -p MESH/") # dimensions xmin = 0.0 xmax = xmin + xsize ymin = 0.0 ymax = ymin + ysize z_top = 0.0 z_bottom = -zsize # characteristic length of mesh elements lc_XY = mesh_element_size_XY number_of_element_layers_Z = int(zsize / mesh_element_size_Z) # output info lc_Z = zsize / number_of_element_layers_Z print("") print("meshing:") print("characteristic length: ",lc_XY,lc_Z) ## geometry mesh, points, cells, point_data, cell_data, field_data = create_gmsh_model(xmin,xmax,ymin,ymax,z_top,z_bottom, lc_XY,number_of_element_layers_Z) ## mesh modification # uniform vertical stretch from bottom (at z_bottom) to a topography (with respect to z_top) points = stretch_to_elevation(points,z_bottom,z_top) # creates new modified mesh # (otherwise, points have been modified by its reference pointer and thus mesh contains now modification) if False: # creates new mesh object with modified point locations mesh = meshio.Mesh(points, cells, point_data, cell_data, field_data) # save as vtk-file filename = "MESH/box.vtu" meshio.write(filename, mesh) print("VTK file written to : ",filename) # saves as Gmsh-file (msh mesh format) filename = "MESH/box.msh" if pygmsh_major_version >= 7: # pygmsh versions 7.x # note: reading back in with Gmsh2specfem.py requires msh version 2 format for now as # version 4.x format will return different mesh list orderings... meshio.write(filename, mesh, file_format='gmsh22',binary=False) else: # pygmsh versions 6.x meshio.write(filename, mesh, file_format='gmsh2-ascii') print("Gmsh file written to: ",filename) print("") ## export print("exporting Gmsh file to specfem format...") export2SPECFEM3D(filename) # overwrite material properties create_material_file() return
def load_aggregate(filename): base, ext = os.path.splitext(filename) mesh = meshio.read(filename) meshio.write(base + '.vtk', mesh) return mesh
R = np.array([0.1, 0.2, 0.1, 0.14]) holes = [ geom.add_ball(x0, r, with_volume=False, lcar=0.2 * r).surface_loop for x0, r in zip(X0, R) ] # geom.add_box( # -1, 1, # -1, 1, # -1, 1, # lcar=0.2, # holes=holes # ) geom.add_ball([0, 0, 0], 1.0, lcar=0.2, holes=holes) # geom.add_physical_volume(ball, label="cheese") ref = 4.07064892966291 mesh = pygmsh.generate_mesh(geom) assert abs(compute_volume(mesh) - ref) < 2.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("swiss_cheese.vtu", test())
def test(): geom = pygmsh.built_in.Geometry() lcar = 0.1 p1 = geom.add_point([0.0, 0.0, 0.0], lcar) p2 = geom.add_point([1.0, 0.0, 0.0], lcar) p3 = geom.add_point([1.0, 0.5, 0.0], lcar) p4 = geom.add_point([1.0, 1.0, 0.0], lcar) s1 = geom.add_spline([p1, p2, p3, p4]) p2 = geom.add_point([0.0, 1.0, 0.0], lcar) p3 = geom.add_point([0.5, 1.0, 0.0], lcar) s2 = geom.add_spline([p4, p3, p2, p1]) ll = geom.add_line_loop([s1, s2]) geom.add_plane_surface(ll) ref = 1.0809439490373247 points, cells, _, _, _ = pygmsh.generate_mesh(geom) assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return points, cells if __name__ == "__main__": import meshio out = test() meshio.write("splines.vtu", *out)
) ) for alpha, a1, z in zip(Alpha, A1, Z_pos): # Rotate torus to the y-z-plane. R1 = pygmsh.rotation_matrix([0.0, 1.0, 0.0], 0.5 * np.pi) R2 = pygmsh.rotation_matrix([0.0, 0.0, 1.0], alpha) x0 = np.array([a1, 0.0, 0.0]) x1 = np.array([0.0, 0.0, z]) # First rotate to y-z-plane, then move out to a1, rotate by angle # alpha, move up by z. # # xnew = R2*(R1*x+x0) + x1 # geom.add_torus( irad=irad, orad=orad, lcar=0.1, R=np.dot(R2, R1), x0=np.dot(R2, x0) + x1 ) geom.add_box(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, lcar=0.3) ref = len(A1) * 2 * np.pi ** 2 * orad * irad ** 2 + 2.0 ** 3 mesh = pygmsh.generate_mesh(geom) assert np.isclose(compute_volume(mesh), ref, rtol=2e-2) return mesh if __name__ == "__main__": import meshio meshio.write("torus_crowd.vtu", test())
info = meshpy.triangle.MeshInfo() info.set_points(boundary_points) def _round_trip_connect(start, end): result = [] for i in range(start, end): result.append((i, i + 1)) result.append((end, start)) return result info.set_facets(_round_trip_connect(0, len(boundary_points) - 1)) def _needs_refinement(vertices, area): return bool(area > max_area) meshpy_mesh = meshpy.triangle.build(info, refinement_func=_needs_refinement) # append column pts = np.array(meshpy_mesh.points) points = np.c_[pts[:, 0], pts[:, 1], np.zeros(len(pts))] return points, np.array(meshpy_mesh.elements) if __name__ == '__main__': import meshio points, cells = create_mesh() meshio.write('rectangle.e', points, {'triangle': cells})
#! /usr/bin/env python # -*- coding: utf-8 -*- import pygmsh as pg def generate(): geom = pg.Geometry() geom.add_rectangle( 0.0, 1.0, 0.0, 1.0, 0.0, 0.1 ) return geom if __name__ == '__main__': import meshio points, cells = pg.generate_mesh(generate()) meshio.write('rectangle.vtu', points, cells)
# -*- coding: utf-8 -*- """ Creates a mesh for a square with a round hole. """ import pygmsh from helpers import compute_volume def test(): geom = pygmsh.built_in.Geometry() circle = geom.add_circle( x0=[0.5, 0.5, 0.0], radius=0.25, lcar=0.1, num_sections=4, make_surface=False ) geom.add_rectangle(0.0, 1.0, 0.0, 1.0, 0.0, lcar=0.1, holes=[circle.line_loop]) ref = 0.8086582838174551 mesh = pygmsh.generate_mesh(geom, geo_filename="h.geo") assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("rectangle_with_hole.vtu", test())
poly = geom.add_polygon([ [0.0, 0.5, 0.0], [-0.1, 0.1, 0.0], [-0.5, 0.0, 0.0], [-0.1, -0.1, 0.0], [0.0, -0.5, 0.0], [0.1, -0.1, 0.0], [0.5, 0.0, 0.0], [0.1, 0.1, 0.0] ], lcar=lcar ) axis = [0, 0, 1] geom.extrude( 'Surface{%s}' % poly, translation_axis=axis, rotation_axis=axis, point_on_axis=[0, 0, 0], angle=2.0 / 6.0 * np.pi ) return geom if __name__ == '__main__': import meshio points, cells = pg.generate_mesh(generate()) meshio.write('screw.vtu', points, cells)
# -*- coding: utf-8 -*- import pygmsh def test(lcar=1.0): geom = pygmsh.built_in.Geometry() poly = geom.add_polygon( [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]], lcar ) geom.set_transfinite_surface(poly.surface, size=[11, 9]) mesh = pygmsh.generate_mesh(geom, geo_filename="transfinite.geo") assert len(mesh.cells["triangle"]) == 10 * 8 * 2 return mesh if __name__ == "__main__": import meshio meshio.write("transfinite.vtu", test())
field0 = geom.add_boundary_layer( edges_list=[poly.line_loop.lines[0]], hfar=0.1, hwall_n=0.01, ratio=1.1, thickness=0.2, anisomax=100.0, ) field1 = geom.add_boundary_layer( nodes_list=[poly.line_loop.lines[1].points[1]], hfar=0.1, hwall_n=0.01, ratio=1.1, thickness=0.2, anisomax=100.0, ) geom.add_background_field([field0, field1]) ref = 4.0 mesh = pygmsh.generate_mesh(geom) assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("boundary_layers.vtu", test())
(0.5 * lx, 0.0, 0.5 * lz), (0.0, 0.0, 0.5 * lz), (0.0, 0.0, 0.0), ] facets = [ [0, 1, 2, 3], [4, 7, 12, 11, 5, 6], [0, 1, 9, 8, 7, 4], [1, 2, 5, 11, 10, 9], [2, 5, 6, 3], [3, 6, 4, 0], [8, 13, 12, 7], [8, 9, 10, 13], [10, 11, 12, 13], ] # create the mesh # Set the geometry and build the mesh. info = meshpy.tet.MeshInfo() info.set_points(points) info.set_facets(facets) meshpy_mesh = meshpy.tet.build(info, max_volume=maxvol) return np.array(meshpy_mesh.points), np.array(meshpy_mesh.elements) if __name__ == "__main__": import meshio points, cells = create_mesh() meshio.write("lshape3d.e", points, {"tetra": cells})
# -*- coding: utf-8 -*- from math import pi import pytest import pygmsh from helpers import compute_volume @pytest.mark.skipif(pygmsh.get_gmsh_major_version() < 3, reason="requires Gmsh >= 3") def test(): geom = pygmsh.opencascade.Geometry() geom.add_cylinder([0.0, 0.0, 0.0], [0.0, 0.0, 1.0], 0.5, 0.25 * pi, char_length=0.1) ref = 0.097625512963 mesh = pygmsh.generate_mesh(geom) assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("opencascade_cylinder.vtu", test())
#! /usr/bin/env python # -*- coding: utf-8 -*- import pygmsh as pg def generate(): geom = pg.Geometry() circle = geom.add_circle( [0.0, 0.0, 0.0], 1.0, 0.3, num_sections=4, # If compound==False, the section borders have to be points of the # discretization. If using a compound circle, they don't; gmsh can # choose by itself where to point the circle points. compound=True ) ll = geom.add_line_loop(circle) surf = geom.add_plane_surface(ll) return geom if __name__ == '__main__': import meshio points, cells = pg.generate_mesh(generate()) meshio.write('circle.vtu', points, cells)
def test_vox(): R = 0.2 eps = 0.02 Nx = 10 Ny = 11 Nz = 12 Lx = Ly = Lz = 1 C = helpers.sphere_vox(Lx, Ly, Lz, Nx, Ny, Nz, R, eps) mesh = pygalmesh.generate_mesh_from_vox( C, [Lx, Ly, Lz], [0, 0, 0, Lx, Ly, Lz], cell_size=0.2, facet_angle=30, facet_size=0.05, facet_distance=0.025, cell_radius_edge_ratio=2.0, verbose=False, ) return mesh if __name__ == "__main__": # test_ball_with_sizing_field() mesh = test_vox() import meshio meshio.write("out_vox_vol.vtk", mesh)
info = meshpy.triangle.MeshInfo() info.set_points(boundary_points) def _round_trip_connect(start, end): result = [] for i in range(start, end): result.append((i, i+1)) result.append((end, start)) return result info.set_facets(_round_trip_connect(0, len(boundary_points)-1)) def _needs_refinement(vertices, area): return bool(area > max_area) meshpy_mesh = meshpy.triangle.build(info, refinement_func=_needs_refinement ) # append column pts = np.array(meshpy_mesh.points) points = np.c_[pts[:, 0], pts[:, 1], np.zeros(len(pts))] return points, np.array(meshpy_mesh.elements) if __name__ == '__main__': import meshio points, cells = create_mesh() meshio.write('ellipse.e', points, {'triangle': cells})
# -*- coding: utf-8 -*- import pygmsh from helpers import compute_volume def test(): geom = pygmsh.built_in.Geometry() geom.add_circle( [0.0, 0.0, 0.0], 1.0, lcar=0.1, num_sections=4, # If compound==False, the section borders have to be points of the # discretization. If using a compound circle, they don't; gmsh can # choose by itself where to point the circle points. compound=True, ) ref = 3.1363871677682247 mesh = pygmsh.generate_mesh(geom, prune_z_0=True) assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("circle.vtk", test())
geom = pygmsh.built_in.Geometry() sqrt2on2 = 0.5 * np.sqrt(2.0) R = pygmsh.rotation_matrix([sqrt2on2, sqrt2on2, 0], np.pi / 6.0) geom.add_pipe(inner_radius=0.3, outer_radius=0.4, length=1.0, R=R, lcar=0.04) R = np.array([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]) geom.add_pipe( inner_radius=0.3, outer_radius=0.4, length=1.0, lcar=0.04, R=R, variant="circle_extrusion", ) ref = 0.43988203517453256 mesh = pygmsh.generate_mesh(geom) assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("pipes.vtu", test())
def gmsh_to_fenics(msh_path): assert msh_path.endswith(".msh") base_path = msh_path[:-4] # Read back in the mesh with meshio meshio_mesh = meshio.read(msh_path) # Save volume mesh in xdmf format mesh_xdmf_path = base_path + "_mesh.xdmf" if os.path.exists(mesh_xdmf_path): os.remove(mesh_xdmf_path) if os.path.exists(mesh_xdmf_path.replace(".xdmf", ".h5")): os.remove(mesh_xdmf_path.replace(".xdmf", ".h5")) points = meshio_mesh.points[:, :2] cells = meshio_mesh.cells_dict["triangle"] if ("gmsh:physical" in meshio_mesh.cell_data_dict and "triangle" in meshio_mesh.cell_data_dict["gmsh:physical"]): subdomains_data = meshio_mesh.cell_data_dict["gmsh:physical"][ "triangle"] else: subdomains_data = np.zeros_like(cells) meshio.write( mesh_xdmf_path, meshio.Mesh(points=points, cells={"triangle": cells}, cell_data={"subdomains": [subdomains_data]})) # Save boundary mesh in xdmf format boundaries_xdmf_path = base_path + "_boundaries.xdmf" if os.path.exists(boundaries_xdmf_path): os.remove(boundaries_xdmf_path) if os.path.exists(boundaries_xdmf_path.replace(".xdmf", ".h5")): os.remove(boundaries_xdmf_path.replace(".xdmf", ".h5")) facets = meshio_mesh.cells_dict["line"] if ("gmsh:physical" in meshio_mesh.cell_data_dict and "line" in meshio_mesh.cell_data_dict["gmsh:physical"]): boundaries_data = meshio_mesh.cell_data_dict["gmsh:physical"]["line"] else: boundaries_data = np.zeros_like(facets) meshio.write( boundaries_xdmf_path, meshio.Mesh(points=points, cells={"line": facets}, cell_data={"boundaries": [boundaries_data]})) # Read back in the mesh with dolfin mesh = dolfin.Mesh() with dolfin.XDMFFile(mesh_xdmf_path) as infile: infile.read(mesh) # Read back in subdomains with dolfin subdomains_mvc = dolfin.MeshValueCollection("size_t", mesh, mesh.topology().dim()) with dolfin.XDMFFile(mesh_xdmf_path) as infile: infile.read(subdomains_mvc, "subdomains") subdomains = dolfin.cpp.mesh.MeshFunctionSizet(mesh, subdomains_mvc) # Clean up mesh file os.remove(mesh_xdmf_path) os.remove(mesh_xdmf_path.replace(".xdmf", ".h5")) # Read back in boundaries with dolfin, and explicitly set to 0 any facet # which had not been marked by gmsh boundaries_mvc = dolfin.MeshValueCollection("size_t", mesh, mesh.topology().dim() - 1) with dolfin.XDMFFile(boundaries_xdmf_path) as infile: infile.read(boundaries_mvc, "boundaries") boundaries_mvc_dict = boundaries_mvc.values() for c in dolfin.cells(mesh): for f, _ in enumerate(dolfin.facets(c)): if (c.index(), f) not in boundaries_mvc_dict: boundaries_mvc.set_value(c.index(), f, 0) boundaries = dolfin.cpp.mesh.MeshFunctionSizet(mesh, boundaries_mvc) # Clean up boundary mesh file os.remove(boundaries_xdmf_path) os.remove(boundaries_xdmf_path.replace(".xdmf", ".h5")) return mesh, subdomains, boundaries
# -*- coding: utf-8 -*- import pygmsh def test(lcar=0.5): geom = pygmsh.built_in.Geometry() poly = geom.add_polygon( [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]], lcar ) top, volume, lat = geom.extrude(poly.surface, [0, 0, 2]) geom.add_physical(poly.surface, label="bottom") geom.add_physical(top, label="top") geom.add_physical(volume, label="volume") geom.add_physical(lat, label="lat") geom.add_physical(poly.lines[0], label="line") mesh = pygmsh.generate_mesh(geom, geo_filename="physical.geo") return mesh if __name__ == "__main__": import meshio meshio.write("physical.vtu", test())
# Compute the volume of a canonical tetrahedron # with edgelength radius2*dphi. a = small_r * dphi canonical_tet_volume = np.sqrt(2.0) / 12 * a ** 3 radial_subdiv = int(2 * np.pi * big_r / a) rz = [ (big_r + small_r * np.cos(i * dphi), 0.5 * small_r * np.sin(i * dphi)) for i in range(num_points) ] geob = GeometryBuilder() geob.add_geometry( *generate_surface_of_revolution( rz, closure=EXT_CLOSED_IN_RZ, radial_subdiv=radial_subdiv ) ) mesh_info = MeshInfo() geob.set(mesh_info) meshpy_mesh = build(mesh_info, max_volume=canonical_tet_volume) return np.array(meshpy_mesh.points), np.array(meshpy_mesh.elements) if __name__ == "__main__": import meshio points, cells = create_mesh() meshio.write("torus.e", points, {"tetra": cells})
R2 = pg.rotation_matrix([0.0, 0.0, 1.0], alpha) x0 = np.array([a1, 0.0, 0.0]) x1 = np.array([0.0, 0.0, z]) # First rotate to y-z-plane, then move out to a1, rotate by angle # alpha, move up by z. # # xnew = R2*(R1*x+x0) + x1 # geom.add_torus( irad=irad, orad=orad, lcar=0.1, R=np.dot(R2, R1), x0=np.dot(R2, x0) + x1 ) geom.add_box( -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, lcar=0.3 ) return geom if __name__ == '__main__': import meshio points, cells = pg.generate_mesh(generate()) meshio.write('torus_crowd.vtu', points, cells)
return (((x[0] / l1) ** 2) ** (1/l5) + ((x[1] / l2) ** 2) ** (1/l5) )** (l5/l4) \ + ( (x[2] / l3) ** 2) ** (1/l4) - 1 def get_bounding_sphere_squared_radius(self): return 0.5 d = SQ() mesh = pygalmesh.generate_surface_mesh( d, min_facet_angle=30, max_radius_surface_delaunay_ball=0.005, max_facet_distance=0.005 ) meshio.write(os.path.join(obj_dir, "model.obj"), mesh, file_format="obj") # check normal issue with trimesh mesh_1 = trimesh.load_mesh(os.path.join(obj_dir, "model.obj")) mesh_1.show() cmd = input("Shape {}: invert? y/n... ".format(counter)) if cmd == 'y': mesh_1.invert() mesh_1.export(os.path.join(obj_dir, "model.obj")) counter += 1 t1 = time.time() print("elapsed time {}".format(round(t1 - t0, 4)))
# create the mesh info = meshpy.triangle.MeshInfo() info.set_points(boundary_points) def _round_trip_connect(start, end): result = [] for i in range(start, end): result.append((i, i + 1)) result.append((end, start)) return result info.set_facets(_round_trip_connect(0, len(boundary_points) - 1)) def _needs_refinement(vertices, area): return bool(area > max_area) meshpy_mesh = meshpy.triangle.build(info, refinement_func=_needs_refinement) # append column pts = np.array(meshpy_mesh.points) points = np.c_[pts[:, 0], pts[:, 1], np.zeros(len(pts))] return points, np.array(meshpy_mesh.elements) if __name__ == "__main__": import meshio points, cells = create_pacman_mesh() meshio.write("pacman.vtu", points, {"triangle": cells})
def test(): """Pipe with double-ring enclosure, rotated in space. """ geom = pygmsh.built_in.Geometry() sqrt2on2 = 0.5 * np.sqrt(2.0) R = pygmsh.rotation_matrix([sqrt2on2, sqrt2on2, 0], np.pi / 6.0) geom.add_pipe(inner_radius=0.3, outer_radius=0.4, length=1.0, R=R, lcar=0.04) R = np.array([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]) geom.add_pipe( inner_radius=0.3, outer_radius=0.4, length=1.0, lcar=0.04, R=R, variant="circle_extrusion", ) ref = 0.43988203517453256 mesh = pygmsh.generate_mesh(geom) assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": import meshio meshio.write("pipes.vtu", test())
geom = pygmsh.built_in.Geometry() points = [geom.add_point([x, 0.0, 0.0], lcar) for x in [0.0, lbw[0]]] line = geom.add_line(*points) _, rectangle, _ = geom.extrude(line, translation_axis=[0.0, lbw[1], 0.0], num_layers=lbw[1], recombine=True) geom.extrude( rectangle, translation_axis=[0.0, 0.0, lbw[2]], num_layers=lbw[2], recombine=True, ) # compute_volume only supports 3D for tetras, but does return # surface area for quads ref = sum(l * w for l, w in permutations(lbw, 2)) # surface area mesh = pygmsh.generate_mesh(geom, prune_vertices=False) # TODO compute hex volumes assert (abs( compute_volume( meshio.Mesh(mesh.points, {"quad": mesh.cells_dict["quad"]})) - ref) < 1.0e-2 * ref) return mesh if __name__ == "__main__": meshio.write("hex.vtu", test())
def test(): x = 5 y = 4 z = 3 x_layers = 10 y_layers = 5 z_layers = 3 geom = pygmsh.opencascade.Geometry() p = geom.add_point([0, 0, 0], 1) _, l, _ = geom.extrude(p, [x, 0, 0], num_layers=x_layers) _, s, _ = geom.extrude(l, [0, y, 0], num_layers=y_layers) geom.extrude(s, [0, 0, z], num_layers=z_layers) mesh = pygmsh.generate_mesh(geom) ref_vol = x * y * z assert abs(compute_volume(mesh) - ref_vol) < 1.0e-2 * ref_vol # Each grid-cell from layered extrusion will result in 6 tetrahedrons. ref_tetras = 6 * x_layers * y_layers * z_layers assert len(mesh.cells["tetra"]) == ref_tetras return mesh if __name__ == "__main__": import meshio meshio.write("cube.vtu", test())
if key == "line": if len(line_data) == 0: line_data = msh.cell_data_dict["gmsh:physical"][key] else: line_data = np.vstack( [line_data, msh.cell_data_dict["gmsh:physical"][key]]) elif key == "triangle": triangle_data = msh.cell_data_dict["gmsh:physical"][key] triangle_mesh = meshio.Mesh(points=msh.points, cells={"triangle": triangle_cells}) line_mesh = meshio.Mesh(points=msh.points, cells=[("line", line_cells)], cell_data={"name_to_read": [line_data]}) meshio.write(os.path.join(Wri_path, "md_.xdmf"), triangle_mesh) meshio.xdmf.write(os.path.join(Wri_path, "mf_.xdmf"), line_mesh) # Reading mesh data stored in .xdmf files. mesh = Mesh() with XDMFFile(os.path.join(Wri_path, "md_.xdmf")) as infile: infile.read(mesh) mvc = MeshValueCollection("size_t", mesh, 1) with XDMFFile(os.path.join(Wri_path, "mf_.xdmf")) as infile: infile.read(mvc, "name_to_read") mf = cpp.mesh.MeshFunctionSizet(mesh, mvc) # Define function spaces for PDEs variational formulation. P1 = FiniteElement('P', mesh.ufl_cell(), 1) # Lagrange 1-order polynomials family