def create_beam(vol): # build using MeshPy from meshpy.tet import MeshInfo,build mesh_info = MeshInfo() mesh_info.set_points([ (0,0,0), (0,1,0), (0,1,1), (0,0,1), (5,0,0), (5,1,0), (5,1,1), (5,0,1), ]) mesh_info.set_facets([ [0,1,2,3], [4,5,6,7], [0,1,5,4], [1,2,6,5], [0,3,7,4], [3,2,6,7], ]) mesh = build(mesh_info,max_volume=vol) return fmsh.MeshPyTet(mesh)
def main(): #Test1: mesh testing MeshPoints = [] MeshFacets = [] with open('MeshFacets', 'rb') as input: MeshFacets = pickle.load(input) with open('MeshPoints', 'rb') as input: MeshPoints = pickle.load(input) mesh_info = MeshInfo() mesh_info.regions.resize(1) mesh_info.regions[0] = [ MeshPoints[0][0], MeshPoints[0][1], MeshPoints[0][2], # point in volume -> first box 0, # region tag (user-defined number) 1, # max tet volume in region ] print "Building mesh from {} facets and {} points".format(len(MeshFacets), len(MeshPoints)) try: mesh = build(mesh_info, options=Options(switches="pqT", epsilon=0.01), volume_constraints=True) except: pass try: mesh = build(mesh_info, options=Options(switches="pqT", epsilon=0.0001), volume_constraints=True) except: pass print "Created mesh with {} points, {} faces and {} elements.".format(len(mesh.points), len(mesh.faces), len(mesh.elements))
def make_cylinder_mesh(radius=0.5, height=1, radial_subdivisions=10, height_subdivisions=1, max_volume=None, periodic=False, boundary_tagger=(lambda fvi, el, fn, all_v: [])): from meshpy.tet import MeshInfo, build from meshpy.geometry import make_cylinder points, facets, facet_holestarts, facet_markers = \ make_cylinder(radius, height, radial_subdivisions, height_subdivisions) assert len(facets) == len(facet_markers) if periodic: return _make_z_periodic_mesh( points, facets, facet_holestarts, facet_markers, height=height, max_volume=max_volume, boundary_tagger=boundary_tagger) else: mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets_ex(facets, facet_holestarts, facet_markers) generated_mesh = build(mesh_info, max_volume=max_volume) from hedge.mesh import make_conformal_mesh_ext from hedge.mesh.element import Tetrahedron vertices = numpy.asarray(generated_mesh.points, dtype=float, order="C") return make_conformal_mesh_ext( vertices, [Tetrahedron(i, el_idx, vertices) for i, el_idx in enumerate(generated_mesh.elements)], boundary_tagger)
def make_inverse_mesh_info(rz, radial_subdiv): # chop off points with zero radius while rz[0][0] == 0: rz.pop(0) while rz[-1][0] == 0: rz.pop(-1) # construct outer cylinder ((min_r, max_r), (min_z, max_z)) = bounding_box(rz) if rz[0][1] < rz[-1][1]: # built in positive z direction rz.extend([ (max_r+2, max_z), (max_r+2, min_z), ]) else: rz.extend([ (max_r+2, min_z), (max_r+2, max_z), ]) from meshpy.tet import MeshInfo from meshpy.geometry import EXT_CLOSED_IN_RZ, \ generate_surface_of_revolution points, facets, facet_holestarts, facet_markers = \ generate_surface_of_revolution(rz, closure=EXT_CLOSED_IN_RZ, radial_subdiv=radial_subdiv) mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets_ex(facets, facet_holestarts, facet_markers) return mesh_info
def generate_Preview(): bpy.ops.object.mode_set(mode = 'OBJECT', toggle = False) config = bpy.context.scene.CONFIG_MeshPy vertList = [] faceList = [] meshPoints = [] meshFacets = [] split_faceList = [] split_vertList = [] ob = bpy.context.active_object obname = ob.name #compute mesh compute_vertices(ob, meshPoints) compute_polygones(ob, meshFacets) if config.make_subdivision == False: arg = "Y" else: arg = "" mesh_info = MeshInfo() mesh_info.set_points(meshPoints) mesh_info.set_facets(meshFacets) print(meshPoints) print(meshFacets) #args = ("pq" + str(config.ratio_quality) + "a" + str(config.ratio_maxsize) + str(arg)) '''
def mesh(self): mesh_info = MeshInfo() mesh_info.set_points(transpose([self.flat_x,self.flat_y,self.flat_z])) mesh = build(mesh_info) print 'yo' for i, t in enumerate(mesh.elements): print i, t
def main(): from math import pi, cos, sin from meshpy.tet import MeshInfo, build from meshpy.geometry import generate_surface_of_revolution,\ EXT_CLOSED_IN_RZ, GeometryBuilder big_r = 3 little_r = 2.9 points = 50 dphi = 2*pi/points rz = [(big_r+little_r*cos(i*dphi), little_r*sin(i*dphi)) for i in range(points)] geob = GeometryBuilder() geob.add_geometry(*generate_surface_of_revolution(rz, closure=EXT_CLOSED_IN_RZ, radial_subdiv=20)) mesh_info = MeshInfo() geob.set(mesh_info) mesh_info.save_nodes("torus") mesh_info.save_poly("torus") mesh = build(mesh_info) mesh.write_vtk("torus.vtk") mesh.save_elements("torus_mesh") mesh.save_nodes("torus_mesh") mesh.write_neu(file("torus.neu", "w"), {1: ("pec", 0)})
def test_tetgen(): from meshpy.tet import MeshInfo, build mesh_info = MeshInfo() mesh_info.set_points([ (0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0), (0, 0, 12), (2, 0, 12), (2, 2, 12), (0, 2, 12), ]) mesh_info.set_facets([ [0, 1, 2, 3], [4, 5, 6, 7], [0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], ]) build(mesh_info)
def generateCubeMesh(): mesh_info = MeshInfo() mesh_info.set_points([ (0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1), ]) mesh_info.set_facets([ [0, 1, 2, 3], [4, 5, 6, 7], [0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], ]) mesh = build(mesh_info) cellList = [] vertexList = [] mupifMesh = Mesh.UnstructuredMesh() print("Mesh Points:") for i, p in enumerate(mesh.points): print(i, p) vertexList.extend([Vertex.Vertex(i, i, p)]) print("Point numbers in tetrahedra:") for i, t in enumerate(mesh.elements): print(i, t) cellList.extend([Cell.Tetrahedron_3d_lin(mupifMesh, i, i, t)]) mupifMesh.setup(vertexList, cellList) return(mupifMesh)
def main(): mesh_info = MeshInfo() mesh_info.set_points([ (0, 0, 0), (2, 0, 0), (2, 2, 0), (0, 2, 0), (0, 0, 12), (2, 0, 12), (2, 2, 12), (0, 2, 12), ]) mesh_info.set_facets([ [0, 1, 2, 3], [4, 5, 6, 7], [0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], ]) mesh_info.save_nodes("bar") mesh_info.save_poly("bar") mesh = build(mesh_info) mesh.save_nodes("barout") mesh.save_elements("barout") mesh.save_faces("barout") mesh.write_vtk("test.vtk")
def brep2lar(larBrep): V,FV = larBrep mesh_info = MeshInfo() mesh_info.set_points(V) mesh_info.set_facets(FV) mesh = build(mesh_info) W = [v for h,v in enumerate(mesh.points)] CW = [tet for k,tet in enumerate(mesh.elements)] FW = sorted(set(AA(tuple)(CAT(AA(faces)(CW))))) EW = sorted(set(AA(tuple)(CAT(AA(edges)(FW))))) return W,CW,FW,EW
def test_tetgen_points(): from meshpy.tet import MeshInfo, build, Options import numpy as np points = np.random.randn(10000, 3) mesh_info = MeshInfo() mesh_info.set_points(points) options = Options("") mesh = build(mesh_info, options=options) print(len(mesh.points)) print(len(mesh.elements))
def make_mesh_info(rz, radial_subdiv): from meshpy.tet import MeshInfo from meshpy.geometry import EXT_OPEN, generate_surface_of_revolution points, facets, facet_holestarts, facet_markers = \ generate_surface_of_revolution(rz, closure=EXT_OPEN, radial_subdiv=radial_subdiv) mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets_ex(facets, facet_holestarts, facet_markers) return mesh_info
def _make_z_periodic_mesh(points, facets, facet_holestarts, facet_markers, height, max_volume, boundary_tagger): from meshpy.tet import MeshInfo, build from meshpy.geometry import Marker mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets_ex(facets, facet_holestarts, facet_markers) mesh_info.pbc_groups.resize(1) pbcg = mesh_info.pbc_groups[0] pbcg.facet_marker_1 = Marker.MINUS_Z pbcg.facet_marker_2 = Marker.PLUS_Z pbcg.set_transform(translation=[0, 0, height]) def zper_boundary_tagger(fvi, el, fn, all_v): # we only ask about *boundaries* # we should not try to have the user tag # the (periodicity-induced) interior faces face_marker = fvi2fm[frozenset(fvi)] if face_marker == Marker.MINUS_Z: return ["minus_z"] if face_marker == Marker.PLUS_Z: return ["plus_z"] result = boundary_tagger(fvi, el, fn, all_v) if face_marker == Marker.SHELL: result.append("shell") return result generated_mesh = build(mesh_info, max_volume=max_volume) fvi2fm = generated_mesh.face_vertex_indices_to_face_marker from hedge.mesh import make_conformal_mesh_ext from hedge.mesh.element import Tetrahedron vertices = numpy.asarray(generated_mesh.points, dtype=float, order="C") return make_conformal_mesh_ext( vertices, [Tetrahedron(i, el_idx, vertices) for i, el_idx in enumerate(generated_mesh.elements)], zper_boundary_tagger, periodicity=[None, None, ("minus_z", "plus_z")])
def main(): from ply import parse_ply import sys data = parse_ply(sys.argv[1]) from meshpy.geometry import GeometryBuilder builder = GeometryBuilder() builder.add_geometry( points=[pt[:3] for pt in data["vertex"].data], facets=[fd[0] for fd in data["face"].data]) builder.wrap_in_box(1) from meshpy.tet import MeshInfo, build mi = MeshInfo() builder.set(mi) mi.set_holes([builder.center()]) mesh = build(mi) print("%d elements" % len(mesh.elements)) mesh.write_vtk("out.vtk")
def brep2lar(model,cycles,holes): V,FV,EV = model FE = crossRelation(V,FV,EV) mesh_info = MeshInfo() mesh_info.set_points(V) mesh_info.set_facets_ex(cycles) #mesh_info.set_holes(holes) mesh = build(mesh_info,options=Options("pqYY")) W = [v for h,v in enumerate(mesh.points)] CW = [tet for k,tet in enumerate(mesh.elements)] def simplify(fun): def simplify0(simplices): cellDict = defaultdict(tuple) for cell in CAT(AA(fun)(simplices)): cellDict[tuple(sorted(cell))] = tuple(cell) return cellDict.values() return simplify0 FW = sorted(simplify(faces)(CW)) EW = sorted(simplify(edges)(FW)) return W,CW,FW,EW
def main(): import numpy from meshpy.tet import MeshInfo, build from meshpy.geometry import GeometryBuilder, Marker, make_box geob = GeometryBuilder() box_marker = Marker.FIRST_USER_MARKER extent_small = 0.3*numpy.ones(3, dtype=numpy.float64) points, facets, _, _ = \ make_box(-extent_small, extent_small) geob.add_geometry(points, facets, facet_markers=box_marker) points, facets, _, facet_markers = \ make_box(numpy.array([-1, -1, -1]), numpy.array([1, 1, 5])) geob.add_geometry(points, facets, facet_markers=facet_markers) mesh_info = MeshInfo() geob.set(mesh_info) #mesh_info.set_holes([(0, 0, 0)]) # region attributes mesh_info.regions.resize(1) mesh_info.regions[0] = ( # point in region [0, 0, 0] + [ # region number 1, # max volume in region 0.001]) mesh = build(mesh_info, max_volume=0.06, volume_constraints=True, attributes=True) print(("%d elements" % len(mesh.elements))) mesh.write_vtk("box-in-box.vtk")
def make_mesh_info_with_inner_tube(rz, tube_r, radial_subdiv, max_inner_volume=1e-4): # chop off points with zero radius while rz[0][0] == 0: rz.pop(0) while rz[-1][0] == 0: rz.pop(-1) # construct outer cylinder first_z = rz[0][1] last_z = rz[-1][1] rz.insert(0, (tube_r, first_z)) rz.append((tube_r, last_z)) from meshpy.tet import MeshInfo from meshpy.geometry import EXT_OPEN, generate_surface_of_revolution outer_points, outer_facets, outer_facet_holestarts, outer_facet_markers = \ generate_surface_of_revolution(rz, closure=EXT_OPEN, radial_subdiv=radial_subdiv) outer_point_indices = tuple(range(len(outer_points))) inner_points, inner_facets, inner_facet_holestarts, inner_facet_markers = \ generate_surface_of_revolution( [(0,first_z), (tube_r, first_z), (tube_r, last_z), (0, last_z)], point_idx_offset=len(outer_points), radial_subdiv=radial_subdiv, ring_point_indices=[ None, outer_point_indices[:radial_subdiv], outer_point_indices[-radial_subdiv:], None, ] ) points = outer_points + inner_points facets = outer_facets + inner_facets facet_holestarts = outer_facet_holestarts + inner_facet_holestarts facet_markers = outer_facet_markers + inner_facet_markers mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets_ex(facets, facet_holestarts, facet_markers) # set regional max. volume mesh_info.regions.resize(1) mesh_info.regions[0] = [0, 0,(first_z+last_z)/2, 0, max_inner_volume] return mesh_info
def test_torus(): from math import pi, cos, sin from meshpy.tet import MeshInfo, build from meshpy.geometry import generate_surface_of_revolution, \ EXT_CLOSED_IN_RZ, GeometryBuilder big_r = 3 little_r = 2.9 points = 50 dphi = 2 * pi / points rz = [(big_r + little_r * cos(i * dphi), little_r * sin(i * dphi)) for i in range(points)] geob = GeometryBuilder() geob.add_geometry(*generate_surface_of_revolution( rz, closure=EXT_CLOSED_IN_RZ, radial_subdiv=20)) mesh_info = MeshInfo() geob.set(mesh_info) build(mesh_info)
def create_ball_mesh(num_longi_points=10): radius = 5.0 radial_subdiv = 2 * num_longi_points dphi = np.pi / num_longi_points # Make sure the nodes meet at the poles of the ball. def truncate(r): if abs(r) < 1e-10: return 0 else: return r # Compute the volume of a canonical tetrahedron # with edgelength radius*dphi. a = radius * dphi canonical_tet_volume = np.sqrt(2.0) / 12 * a ** 3 # Build outline for surface of revolution. rz = [ (truncate(radius * np.sin(i * dphi)), radius * np.cos(i * dphi)) for i in range(num_longi_points + 1) ] geob = GeometryBuilder() geob.add_geometry( *generate_surface_of_revolution( rz, closure=EXT_OPEN, 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)
def generateCubeMesh(): mesh_info = MeshInfo() mesh_info.set_points([ (0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0), (0, 0, 1), (1, 0, 1), (1, 1, 1), (0, 1, 1), ]) mesh_info.set_facets([ [0, 1, 2, 3], [4, 5, 6, 7], [0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], ]) mesh = build(mesh_info) cellList = [] vertexList = [] mupifMesh = Mesh.UnstructuredMesh() print("Mesh Points:") for i, p in enumerate(mesh.points): print(i, p) vertexList.extend([Vertex.Vertex(i, i, p)]) print("Point numbers in tetrahedra:") for i, t in enumerate(mesh.elements): print(i, t) cellList.extend([Cell.Tetrahedron_3d_lin(mupifMesh, i, i, t)]) mupifMesh.setup(vertexList, cellList) return (mupifMesh)
def make_ball_mesh(r=0.5, subdivisions=10, max_volume=None, boundary_tagger=(lambda fvi, el, fn, all_v: [])): from meshpy.tet import MeshInfo, build from meshpy.geometry import make_ball points, facets, facet_holestarts, facet_markers = \ make_ball(r, subdivisions) mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets_ex(facets, facet_holestarts, facet_markers) generated_mesh = build(mesh_info, max_volume=max_volume) vertices = numpy.asarray(generated_mesh.points, dtype=float, order="C") from hedge.mesh.element import Tetrahedron from hedge.mesh import make_conformal_mesh_ext return make_conformal_mesh_ext( vertices, [Tetrahedron(i, el_idx, vertices) for i, el_idx in enumerate(generated_mesh.elements)], boundary_tagger)
def brep2lar(model, cycles, holes): V, FV, EV = model FE = crossRelation(V, FV, EV) mesh_info = MeshInfo() mesh_info.set_points(V) mesh_info.set_facets_ex(cycles) #mesh_info.set_holes(holes) mesh = build(mesh_info, options=Options("pqYY")) W = [v for h, v in enumerate(mesh.points)] CW = [tet for k, tet in enumerate(mesh.elements)] def simplify(fun): def simplify0(simplices): cellDict = defaultdict(tuple) for cell in CAT(AA(fun)(simplices)): cellDict[tuple(sorted(cell))] = tuple(cell) return cellDict.values() return simplify0 FW = sorted(simplify(faces)(CW)) EW = sorted(simplify(edges)(FW)) return W, CW, FW, EW
def make_tetgen_mesh(vert_list, face_list): # Make the tetgen mesh mesh_info = MeshInfo() # Points mesh_info.set_points(vert_list) # Faces mesh_info.set_facets(face_list) # --- TEMP --- ''' # Make an object from the surface we are planning to tetrahedronalize mesh_new = bpy.data.meshes.new("pre_tet_mesh") mesh_new.from_pydata(vert_list,[],face_list) mesh_new.validate(verbose=False) # Important! and i dont know why mesh_new.update() obj_new = bpy.data.objects.new("pre_tet",mesh_new) context.scene.objects.link(obj_new) # return ''' # --- FIN TEMP --- # Tetrahedralize # Options: # neighout = Write out neighbors # facesout = Write out faces # edgesout = Write out edges # regionattrib = Write out element_attributes = unique id for every tet in a distinct volume # nobisect = Dont alter surface print("> Starting TetGen") opts = Options(switches='pq', neighout = True, facesout = True, edgesout = True, regionattrib = True, verbose = True, docheck = True) mesh_built = build(mesh_info, options=opts) print("> Finished TetGen successfully") return mesh_built
def unstructure_mesh(h): mesh_info = MeshInfo() # Set the vertices of the domain [0, 1]^3 mesh_info.set_points([ (0,0,0), (1,0,0), (1,1,0), (0,1,0), (0,0,1), (1,0,1), (1,1,1), (0,1,1), ]) # Set the facets of the domain [0, 1]^3 mesh_info.set_facets([ [0,1,2,3], [4,5,6,7], [0,4,5,1], [1,5,6,2], [2,6,7,3], [3,7,4,0], ]) # Generate the tet mesh mesh = build(mesh_info, max_volume=(h)**3) point = np.array(mesh.points, dtype=np.float) cell = np.array(mesh.elements, dtype=np.int) return TetrahedronMesh(point, cell)
#============================================================ #- Triangulation. #============================================================ for i in range(0, m.shape[0]): S = m[i, :] outfile = outfilename + '.' + str(i) + '.vtk' print('Compute Delauney triangulation ...') x = 6371.0 * np.cos(lat * np.pi / 180.0) * np.cos(lon * np.pi / 180.0) y = 6371.0 * np.cos(lat * np.pi / 180.0) * np.sin(lon * np.pi / 180.0) z = 6371.0 * np.sin(lat * np.pi / 180.0) pts = np.array((x, y, z)).T mesh_info = MeshInfo() mesh_info.set_points(pts) opts = Options("Q") mesh = build(mesh_info, options=opts) elements = mesh.elements #============================================================ #- Write vtk file. #============================================================ print('Write vtk file ...') vtkElements = pyvtk.VtkData(pyvtk.UnstructuredGrid(pts, tetra=elements), PointData(Scalars(S, 'grad_PSD_ZZ')), "Mesh") vtkElements.tofile(outfile)
from meshpy.tet import MeshInfo, build mesh_info = MeshInfo() # construct a two-box extrusion of this base base = [(-2,-2,0), (2,-2,0), (2,2,0), (-2,2,0)] # first, the nodes mesh_info.set_points( base +[(x,y,z+5) for x,y,z in base] +[(x,y,z+10) for x,y,z in base] ) # next, the facets # vertex indices for a box missing the -z face box_without_minus_z = [ [4,5,6,7], [0,4,5,1], [1,5,6,2], [2,6,7,3], [3,7,4,0], ] def add_to_all_vertex_indices(facets, increment): return [[pt+increment for pt in facet] for facet in facets] mesh_info.set_facets( [[0,1,2,3]] # base +box_without_minus_z # first box
def main(): import numpy # from math import pi, cos, sin from meshpy.tet import MeshInfo, build from meshpy.geometry import GeometryBuilder, Marker, generate_extrusion, make_box from meshpy.naca import get_naca_points geob = GeometryBuilder() box_marker = Marker.FIRST_USER_MARKER wing_length = 2 wing_subdiv = 5 rz_points = ([ (0, -wing_length * 1.05), (0.7, -wing_length * 1.05), ] + [(r, x) for x, r in zip( numpy.linspace(-wing_length, 0, wing_subdiv, endpoint=False), numpy.linspace(0.8, 1, wing_subdiv, endpoint=False), )] + [(1, 0)] + [(r, x) for x, r in zip( numpy.linspace(wing_length, 0, wing_subdiv, endpoint=False), numpy.linspace(0.8, 1, wing_subdiv, endpoint=False), )][::-1] + [(0.7, wing_length * 1.05), (0, wing_length * 1.05)]) geob.add_geometry(*generate_extrusion( rz_points=rz_points, base_shape=get_naca_points("0012", verbose=False, number_of_points=20), ring_markers=(wing_subdiv * 2 + 4) * [box_marker], )) from meshpy.tools import make_swizzle_matrix swizzle_matrix = make_swizzle_matrix("z:x,y:y,x:z") geob.apply_transform(lambda p: numpy.dot(swizzle_matrix, p)) def deform_wing(p): x, y, z = p return numpy.array([ x, y + 0.1 * abs(x / wing_length)**2, z + 0.8 * abs(x / wing_length)**1.2, ]) geob.apply_transform(deform_wing) points, facets, _, facet_markers = make_box( numpy.array([-wing_length - 1, -1, -1.5]), numpy.array([wing_length + 1, 1, 3])) geob.add_geometry(points, facets, facet_markers=facet_markers) mesh_info = MeshInfo() geob.set(mesh_info) mesh_info.set_holes([(0, 0, 0.5)]) mesh = build(mesh_info) print("%d elements" % len(mesh.elements)) mesh.write_vtk("airfoil3d.vtk")
def make_boxmesh(): from meshpy.tet import MeshInfo, build from meshpy.geometry import GeometryBuilder, Marker, make_box geob = GeometryBuilder() box_marker = Marker.FIRST_USER_MARKER extent_small = 0.1 * numpy.ones(3, dtype=numpy.float64) geob.add_geometry(*make_box(-extent_small, extent_small)) # make small "separator box" for region attribute geob.add_geometry( *make_box(-extent_small * 4, numpy.array([4, 0.4, 0.4], dtype=numpy.float64))) geob.add_geometry(*make_box(numpy.array([-1, -1, -1], dtype=numpy.float64), numpy.array([5, 1, 1], dtype=numpy.float64))) mesh_info = MeshInfo() geob.set(mesh_info) mesh_info.set_holes([(0, 0, 0)]) # region attributes mesh_info.regions.resize(1) mesh_info.regions[0] = ( # point in region list(extent_small * 2) + [ # region number 1, # max volume in region #0.0001 0.005 ]) mesh = build(mesh_info, max_volume=0.02, volume_constraints=True, attributes=True) print("%d elements" % len(mesh.elements)) #mesh.write_vtk("box-in-box.vtk") #print "done writing" fvi2fm = mesh.face_vertex_indices_to_face_marker face_marker_to_tag = { box_marker: "noslip", Marker.MINUS_X: "inflow", Marker.PLUS_X: "outflow", Marker.MINUS_Y: "inflow", Marker.PLUS_Y: "inflow", Marker.PLUS_Z: "inflow", Marker.MINUS_Z: "inflow" } def bdry_tagger(fvi, el, fn, all_v): face_marker = fvi2fm[fvi] return [face_marker_to_tag[face_marker]] from grudge.mesh import make_conformal_mesh return make_conformal_mesh(mesh.points, mesh.elements, bdry_tagger)
def main(): import numpy #from math import pi, cos, sin from meshpy.tet import MeshInfo, build from meshpy.geometry import GeometryBuilder, Marker, \ generate_extrusion, make_box from meshpy.naca import get_naca_points geob = GeometryBuilder() box_marker = Marker.FIRST_USER_MARKER wing_length = 2 wing_subdiv = 5 rz_points = [ (0, -wing_length*1.05), (0.7, -wing_length*1.05), ] + [ (r, x) for x, r in zip( numpy.linspace(-wing_length, 0, wing_subdiv, endpoint=False), numpy.linspace(0.8, 1, wing_subdiv, endpoint=False)) ] + [(1, 0)] + [ (r, x) for x, r in zip( numpy.linspace(wing_length, 0, wing_subdiv, endpoint=False), numpy.linspace(0.8, 1, wing_subdiv, endpoint=False)) ][::-1] + [ (0.7, wing_length*1.05), (0, wing_length*1.05) ] geob.add_geometry(*generate_extrusion( rz_points=rz_points, base_shape=get_naca_points("0012", verbose=False, number_of_points=20), ring_markers=(wing_subdiv*2+4)*[box_marker])) from meshpy.tools import make_swizzle_matrix swizzle_matrix = make_swizzle_matrix("z:x,y:y,x:z") geob.apply_transform(lambda p: numpy.dot(swizzle_matrix, p)) def deform_wing(p): x, y, z = p return numpy.array([ x, y + 0.1*abs(x/wing_length)**2, z + 0.8*abs(x/wing_length) ** 1.2]) geob.apply_transform(deform_wing) points, facets, _, facet_markers = make_box( numpy.array([-wing_length-1, -1, -1.5]), numpy.array([wing_length+1, 1, 3])) geob.add_geometry(points, facets, facet_markers=facet_markers) mesh_info = MeshInfo() geob.set(mesh_info) mesh_info.set_holes([(0, 0, 0.5)]) mesh = build(mesh_info) print("%d elements" % len(mesh.elements)) mesh.write_vtk("airfoil3d.vtk")
def ProcessGlobalAction(ActionType, GlobalAction, NumberedPoints, Elements, Points): ExtendedData = {'ElementPropertyIndex' : {}} if ActionType == 'SpecialEntities': Filters = json.loads(GlobalAction['Filters']) if not 'SpecialEntities' in ExtendedData: ExtendedData['SpecialEntities'] = [] for Element in Elements: if Element and Element['filter'] in Filters: ExtendedData['SpecialEntities'].append(Element) return ExtendedData, False if ActionType == 'Nonlinear': Output = {} #for key in GlobalAction: # if 'ElementPropertyMaxIndex' in ExtendedData: # ExtendedData['ElementPropertyMaxIndex'] += 1 # else: # ExtendedData['ElementPropertyMaxIndex'] = 1 # propertyindex = ExtendedData['ElementPropertyMaxIndex'] # ExtendedData['ElementPropertyIndex'][key] = propertyindex # ExtendedData['NonlinearPropertyIndex'][key] = nonlinearindex # # # ExtendedData['ElementPropertyIndex'][key] = workingindex #In this same notation we can get the index when writing elements # Output[index] = "" return ExtendedData, Output #Here we have Output ready to be printed and ExtendedData, a mapper to Output if ActionType == 'ElementProperties': Output = {} for key in GlobalAction: if 'ElementPropertyMaxIndex' in ExtendedData: ExtendedData['ElementPropertyMaxIndex'] += 1 else: ExtendedData['ElementPropertyMaxIndex'] = 1 workingindex = ExtendedData['ElementPropertyMaxIndex'] ExtendedData['ElementPropertyIndex'][key] = workingindex #In this same notation we can get the index when writing elements Output[workingindex] = GlobalAction[key] return ExtendedData, Output #Here we have Output ready to be printed and ExtendedData, a mapper to Output if ActionType == 'Orphans': Output = [] for Number, Point in NumberedPoints['points'].iteritems(): ElementAmount = len(Point['elementnumbers']) if ElementAmount < 2: print "Orphan node {}!".format(Number) Output.append({'element_type': 'POINT', 'position': Point['point'], 'layer': 'Errors', 'nodenumber': Number}) return {'information':'addObjects'}, Output#Here we have Output ready to be printed and ExtendedData, a mapper to Output if ActionType == 'Meshing': EntityModelData = json.loads(GlobalAction['EntityModelData']) if 'EntityModelData' in GlobalAction else {} ExtendedModelData = json.loads(GlobalAction['ExtendedModelData']) if 'ExtendedModelData' in GlobalAction else {} Semantic = json.loads(GlobalAction['Semantic']) if 'Semantic' in GlobalAction else {} if 'exclude filters' in Semantic: if not 'ExcludeFilters' in ExtendedData: ExtendedData['ExcludeFilters'] = [] ExtendedData['ExcludeFilters'] = ExtendedData['ExcludeFilters'] + Semantic['exclude filters'] Boundaries = [] Output = [] Geometry = json.loads(GlobalAction['Geometry']) if 'Geometry' in GlobalAction else {} Parameters = json.loads(GlobalAction['Parameters']) if 'Parameters' in GlobalAction else {} AdditionalPointsFilters = Geometry['points'] if 'points' in Geometry else [] for Filter in Geometry['boundaries']: print "Using filter {} as finite element domain boundary.".format(Filter) for Element in Elements: if Element and Element['filter'] == Filter and Element['elementclass'] in ['FACE_3NODES', 'FACE_4NODES', 'POLYLINE', 'PLINE_5NODES']: Boundaries.append(Element) AdditionalPoints = [] for Filter in AdditionalPointsFilters: print "Using filter {} as additional points container.".format(Filter) for Element in Elements: if Element and Element['filter'] == Filter and Element['elementclass'] in ['FACE_3NODES', 'FACE_4NODES', 'POLYLINE', 'LINE_2NODES']: AdditionalPoints.extend( Element['points'] ) print "Assembling FE domain" mesh_info = MeshInfo() #additional_points = MeshInfo() #additional_points.set_points(list(set(AdditionalPoints))) MeshPoints = [] MeshFacets = [] MeshPointsIndex = {} PointIndex = 0 for BoundaryElement in Boundaries: ElementPoints = BoundaryElement['points'] MeshFacet = [] if Parameters['type'] == 'divide_4p_faces': for point in [ElementPoints[0],ElementPoints[1],ElementPoints[2]]: if not point in MeshPointsIndex: MeshPointsIndex[point] = PointIndex MeshPoints.append(False) MeshPoints[PointIndex] = NumberedPoints['points'][point]['point'] PointIndex += 1 MeshFacet.append(MeshPointsIndex[point]) MeshFacets.append(MeshFacet) MeshFacet = [] if ElementPoints[2] != ElementPoints[3]: for point in [ElementPoints[0],ElementPoints[2],ElementPoints[3]]: if not point in MeshPointsIndex: MeshPointsIndex[point] = PointIndex MeshPoints.append(False) MeshPoints[PointIndex] = NumberedPoints['points'][point]['point'] PointIndex += 1 MeshFacet.append(MeshPointsIndex[point]) MeshFacets.append(MeshFacet) else: for point in ElementPoints: if not point in MeshPointsIndex: MeshPointsIndex[point] = PointIndex MeshPoints.append(False) MeshPoints[PointIndex] = NumberedPoints['points'][point]['point'] PointIndex += 1 if not MeshPointsIndex[point] in MeshFacet: MeshFacet.append(MeshPointsIndex[point]) else: print "Mesh error or 3-point 3DFACE." MeshFacets.append(MeshFacet) MeshFacet = [] for point in list(set(AdditionalPoints)): if not point in MeshPointsIndex: #See whether the point is already indexed by its native number MeshPointsIndex[point] = PointIndex MeshPoints.append(False) MeshPoints[PointIndex] = NumberedPoints['points'][point]['point'] PointIndex += 1 saveobject(MeshFacets, r'MeshFacets') saveobject(MeshPoints, r'MeshPoints') mesh_info.set_facets(MeshFacets) mesh_info.set_points(MeshPoints) #insertaddpoints #points = np.array([list(x) for x in MeshPoints]) #qhull = scipy.spatial.Delaunay(points) #mesh_info.Options(switches='pq') #mesh_info.set_points([ # (0,0,0), (12,0,0), (12,12,0), (0,12,0), # (0,0,12), (12,0,12), (12,12,12), (0,12,12), # ]) #mesh_info.set_facets([ # [0,1,2,3], # [4,5,6,7], # [0,4,5,1], # [1,5,6,2], # [2,6,7,3], # [3,7,4,0], # ]) #opts = Options(switches='pq') #opts.maxvolume = 0.0001 #opts.parse_switches() mesh_info.regions.resize(1) mesh_info.regions[0] = [ MeshPoints[0][0], MeshPoints[0][1], MeshPoints[0][2], # point in volume -> first box 0, # region tag (user-defined number) Parameters['maxvolume'], # max tet volume in region ] mesh = build(mesh_info, options=Options(switches="pqT", epsilon=Parameters['tolerance']), volume_constraints=True) print "Created mesh with {} points, {} faces and {} elements.".format(len(mesh.points), len(mesh.faces), len(mesh.elements)) #mesh = build(mesh_info, options=Options(switches="pTi", epsilon=Parameters['tolerance'], insertaddpoints=True), volume_constraints=True, insert_points=additional_points) #mesh.write_vtk("test.vtk") #mesh.points #mesh.elements #mesh.faces filename = "test" #mesh.save_elements(filename) #mesh.save_nodes(filename) #mesh.save_elements(filename) #mesh.save_faces(filename) #mesh.save_edges(filename) #mesh.save_neighbors(filename) #mesh.save_poly(filename) #for element in qhull.simplices: # Position = [list(qhull.points[x]) for x in element] # Output.append({'element_type': '3DFACE', 'position': Position, 'layer': 'Elements'}) #NumberedPoints['points'][compoundObject['points'][0]]['point'] if not Boundaries: return False, False Precision = int(GlobalAction['Precision']) if 'Precision' in GlobalAction else 4 if Semantic['output'].lower() == 'graphics': for face in mesh.faces: Position = [mesh.points[x] for x in face] Output.append({'element_type': '3DFACE', 'position': Position, 'layer': 'Faces'}) for element in mesh.elements: Position = [mesh.points[x] for x in element] Output.append({'element_type': '3DFACE', 'position': Position, 'layer': 'Elements'}) return {'information':'addObjects'}, Output elif Semantic['output'].lower() == 'fea': Points = {} for NumberedPoint in NumberedPoints['points']: Points[NumberedPoints['points'][NumberedPoint]['point']] = NumberedPoint NodeNumber = NumberedPoints['maximumNode'] for element in mesh.elements: Position = [mesh.points[x] for x in element] for i, point in enumerate(Position): Position[i] = [round(x, Precision) for x in point] #else: # if tuple([round(x, PrepPrecision) for x in Coords]) in [(4.95,-17.69,58.9), (4.96,-17.69,58.9)]: # pass # object['points'][i] = tuple([round(x, PrepPrecision) for x in Coords]) # if not object['points'][i] in GlobalPointIndex: # GlobalPointIndex.append(object['points'][i]) ElementPoints = [] ElementNumber = len(Elements) for point in Position: #Update NumberedPoints and construct all necessary data for Elements point = NeighborhoodRaw(tuple(point), Precision, Points) if not tuple(point) in Points: NodeNumber += 1 Points[tuple(point)] = NodeNumber #PointsNumbered.append(None) NumberedPoints['points'][NodeNumber] = {'point': tuple(point), 'elementnumbers': []} NumberedPoints['maximumNode'] = NodeNumber CurrentPointNumber = Points[tuple(point)] ElementPoints.append(CurrentPointNumber) NumberedPoints['points'][CurrentPointNumber]['elementnumbers'].append(ElementNumber) #Update Points if possible #Update Elements Element = { 'points' : ElementPoints, 'elementclass' : 'SOLID_4NODES', 'elementnum': ElementNumber, #??? 'filter': Semantic['filter'], 'entity_model_data': EntityModelData, 'extended_model_data': ExtendedModelData, 'generation_order': None, } Elements.append(None) Elements[ElementNumber] = Element return ExtendedData, False if ActionType == 'AddShells': ExtendedData = {} EntityModelData = json.loads(GlobalAction['EntityModelData']) if 'EntityModelData' in GlobalAction else {} ExtendedModelData = json.loads(GlobalAction['ExtendedModelData']) if 'ExtendedModelData' in GlobalAction else {} Filters = json.loads(GlobalAction['Filters']) if 'Filters' in GlobalAction else {} for Element in Elements: if not Element or not Element['filter'] in Filters: continue if Element['generation_order'] == 0 and Element['entity_model_data']['layer'] != "Concrete bases crown": ElementPoints = [Element['points'][0], Element['points'][1], Element['points'][2]] ElementNumber = len(Elements) NewElement = { 'points' : ElementPoints, 'elementclass' : 'FACE_3NODES', 'elementnum': ElementNumber, #??? 'filter': GlobalAction['AssignedFilter'], 'entity_model_data': EntityModelData, 'extended_model_data': ExtendedModelData, 'generation_order': None, } Elements.append(None) Elements[ElementNumber] = NewElement if Element['elementclass'] == 'SOLID_8NODES': ElementPoints = [Element['points'][0], Element['points'][2], Element['points'][3]] ElementNumber = len(Elements) NewElement = { 'points' : ElementPoints, 'elementclass' : 'FACE_3NODES', 'elementnum': ElementNumber, #??? 'filter': GlobalAction['AssignedFilter'], 'entity_model_data': EntityModelData, 'extended_model_data': ExtendedModelData, 'generation_order': None, } Elements.append(None) Elements[ElementNumber] = NewElement if Element['elementclass'] == 'SOLID_10NODES': pass pass return {}, {} return False
# figure() n, bins, patches = hist(vols, 50, facecolor='green') xlabel('Volume') ylabel('Number') show() # close() def volTet2(vertPoints): return abs(dot((vertPoints[0]-vertPoints[3]),cross((vertPoints[1]-vertPoints[3]),(vertPoints[2]-vertPoints[3])))/6.0) # mainDir = '/home/hessb/Downloads/temp' mainDir = '/fslhome/bch/trash' os.chdir(mainDir) mesh_info = MeshInfo() # Cubic IBZ # mesh_info.set_points([ # (0,0,0), (0.5,0.5,0), (0,0.5,0), (0.5,0.5,0.5) # ]) # mesh_info.set_facets([ # [0,1,2], # [0,1,3], # [1,2,3], # [3,2,0] # ]) #Cubic entire cubic voronoi cell.... a = 0.5; b = -0.5 mesh_info.set_points([ (b,b,b), (b,b,a), (b,a,a),(b,a,b),(a,b,b), (a,b,a), (a,a,a),(a,a,b)
def generateConeMesh(plot=True): x0 = 0 y0 = 0 z0 = 1 h = 1 r_bottom = 1.3 r_top = 1.5 r_scale = r_top / r_bottom rz = [(0, z0), (1, z0), (r_scale, z0 + h), (0, z0 + h)] base = [] # Create circle for theta in np.linspace(0, 2 * np.pi, 40): x = r_bottom * np.sin(theta) y = r_bottom * np.cos(theta) base.extend([(x, y)]) (points, facets, facet_holestarts, markers) = generate_extrusion(rz_points=rz, base_shape=base) if plot: p_array = np.array(points) xs = p_array[:, 0] + x0 ys = p_array[:, 1] + y0 zs = p_array[:, 2] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(xs, ys, zs) for f in facets: plt.plot(xs[list(f[0])], ys[list(f[0])], zs[list(f[0])]) if True: axLim = ax.get_w_lims() MAX = np.max(axLim) for direction in (-1, 1): for point in np.diag(direction * MAX * np.array([1, 1, 1])): ax.plot([point[0]], [point[1]], [np.abs(point[2])], 'w') x = [0, 0] y = [0, 0] z = [1, 1 + 0.2] plt.plot(x, y, z) plt.show() mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets_ex(facets) mesh = build(mesh_info) # print(mesh.elements) cellList = [] vertexList = [] mupifMesh = Mesh.UnstructuredMesh() for i, p in enumerate(mesh.points): p = (p[0] + x0, p[1] + y0, p[2]) vertexList.extend([Vertex.Vertex(i, i, p)]) for i, t in enumerate(mesh.elements): cellList.extend([Cell.Tetrahedron_3d_lin(mupifMesh, i, i, t)]) mupifMesh.setup(vertexList, cellList) return (mupifMesh)
from meshpy.tet import MeshInfo, build mesh_info = MeshInfo() mesh_info.set_points([ (0,0,0), (2,0,0), (2,2,0), (0,2,0), (0,0,12), (2,0,12), (2,2,12), (0,2,12), ]) mesh_info.set_facets([ [0,1,2,3], [4,5,6,7], [0,4,5,1], [1,5,6,2], [2,6,7,3], [3,7,4,0], ]) mesh = build(mesh_info) print "Mesh Points:" for i, p in enumerate(mesh.points): print i, p print "Point numbers in tetrahedra:" for i, t in enumerate(mesh.elements): print i, t mesh.write_vtk("test.vtk")
def make_boxmesh(): from meshpy.tet import MeshInfo, build from meshpy.geometry import GeometryBuilder, Marker, make_box geob = GeometryBuilder() box_marker = Marker.FIRST_USER_MARKER extent_small = 0.1*numpy.ones(3, dtype=numpy.float64) geob.add_geometry(*make_box(-extent_small, extent_small)) # make small "separator box" for region attribute geob.add_geometry( *make_box( -extent_small*4, numpy.array([4, 0.4, 0.4], dtype=numpy.float64))) geob.add_geometry( *make_box( numpy.array([-1, -1, -1], dtype=numpy.float64), numpy.array([5, 1, 1], dtype=numpy.float64))) mesh_info = MeshInfo() geob.set(mesh_info) mesh_info.set_holes([(0, 0, 0)]) # region attributes mesh_info.regions.resize(1) mesh_info.regions[0] = ( # point in region list(extent_small*2) + [ # region number 1, # max volume in region #0.0001 0.005 ]) mesh = build(mesh_info, max_volume=0.02, volume_constraints=True, attributes=True) print "%d elements" % len(mesh.elements) #mesh.write_vtk("box-in-box.vtk") #print "done writing" fvi2fm = mesh.face_vertex_indices_to_face_marker face_marker_to_tag = { box_marker: "noslip", Marker.MINUS_X: "inflow", Marker.PLUS_X: "outflow", Marker.MINUS_Y: "inflow", Marker.PLUS_Y: "inflow", Marker.PLUS_Z: "inflow", Marker.MINUS_Z: "inflow" } def bdry_tagger(fvi, el, fn, all_v): face_marker = fvi2fm[fvi] return [face_marker_to_tag[face_marker]] from hedge.mesh import make_conformal_mesh return make_conformal_mesh( mesh.points, mesh.elements, bdry_tagger)
def make_extrusion_with_fine_core(rz, inner_r, max_volume_inner=1e-4, max_volume_outer=5e-2, radial_subdiv=20): min_z = min(rz_pt[1] for rz_pt in rz) max_z = max(rz_pt[1] for rz_pt in rz) from meshpy.tet import MeshInfo, build from meshpy.geometry import generate_surface_of_revolution MINUS_Z_MARKER = 1 PLUS_Z_MARKER = 2 inner_points, inner_facets, inner_holes, inner_markers = \ generate_surface_of_revolution( [ (0, min_z), (inner_r, min_z), (inner_r, max_z), (0, max_z), ], ring_markers=[ MINUS_Z_MARKER, 0, PLUS_Z_MARKER ], radial_subdiv=radial_subdiv, ) inner_point_indices = tuple(range(len(inner_points))) outer_points, outer_facets, outer_holes, outer_markers = \ generate_surface_of_revolution( [(inner_r,min_z)] + rz + [(inner_r, max_z)], ring_markers=[MINUS_Z_MARKER] + [0]*(len(rz)-1) + [PLUS_Z_MARKER], point_idx_offset=len(inner_points), radial_subdiv=radial_subdiv, ring_point_indices= [ inner_point_indices[:radial_subdiv] ] + [None]*len(rz) + [inner_point_indices[radial_subdiv:]] ) mesh_info = MeshInfo() mesh_info.set_points(inner_points + outer_points) mesh_info.set_facets_ex( inner_facets + outer_facets, inner_holes + outer_holes, inner_markers + outer_markers, ) # set regional max. volume mesh_info.regions.resize(2) mesh_info.regions[0] = [0, 0, (max_z + min_z) / 2, 0, max_volume_inner] mesh_info.regions[1] = [ inner_r + (rz[0][0] - inner_r) / 2, 0, (max_z + min_z) / 2, 0, max_volume_outer ] # add periodicity mesh_info.pbc_groups.resize(1) pbcg = mesh_info.pbc_groups[0] pbcg.facet_marker_1 = MINUS_Z_MARKER pbcg.facet_marker_2 = PLUS_Z_MARKER pbcg.set_transform(translation=[0, 0, max_z - min_z]) mesh = build(mesh_info, verbose=True, volume_constraints=True) #print "%d elements" % len(mesh.elements) #mesh.write_vtk("gun.vtk") fvi2fm = mesh.face_vertex_indices_to_face_marker def zper_boundary_tagger(fvi, el, fn, points): face_marker = fvi2fm[frozenset(fvi)] if face_marker == MINUS_Z_MARKER: return ["minus_z"] elif face_marker == PLUS_Z_MARKER: return ["plus_z"] else: return ["shell"] vertices = numpy.asarray(mesh.points, dtype=float, order="C") from hedge.mesh import make_conformal_mesh_ext from hedge.mesh.element import Tetrahedron return make_conformal_mesh_ext( vertices, [ Tetrahedron(i, el_idx, vertices) for i, el_idx in enumerate(mesh.elements) ], zper_boundary_tagger, periodicity=[None, None, ("minus_z", "plus_z")])
def make_wingmesh(): import numpy from math import pi, cos, sin from meshpy.tet import MeshInfo, build from meshpy.geometry import GeometryBuilder, Marker, \ generate_extrusion, make_box geob = GeometryBuilder() profile_marker = Marker.FIRST_USER_MARKER wing_length = 2 wing_subdiv = 5 rz_points = [ (0, -wing_length * 1.05), (0.7, -wing_length * 1.05), ] + [(r, x) for x, r in zip( numpy.linspace(-wing_length, 0, wing_subdiv, endpoint=False), numpy.linspace(0.8, 1, wing_subdiv, endpoint=False))] + [(1, 0)] + [ (r, x) for x, r in zip( numpy.linspace(wing_length, 0, wing_subdiv, endpoint=False), numpy.linspace(0.8, 1, wing_subdiv, endpoint=False)) ][::-1] + [(0.7, wing_length * 1.05), (0, wing_length * 1.05)] from meshpy.naca import get_naca_points geob.add_geometry(*generate_extrusion( rz_points=rz_points, base_shape=get_naca_points("0012", number_of_points=20), ring_markers=(wing_subdiv * 2 + 4) * [profile_marker])) def deform_wing(p): x, y, z = p return numpy.array([ x + 0.8 * abs(z / wing_length)**1.2, y + 0.1 * abs(z / wing_length)**2, z ]) geob.apply_transform(deform_wing) points, facets, facet_markers = make_box( numpy.array([-1.5, -1, -wing_length - 1], dtype=numpy.float64), numpy.array([3, 1, wing_length + 1], dtype=numpy.float64)) geob.add_geometry(points, facets, facet_markers=facet_markers) mesh_info = MeshInfo() geob.set(mesh_info) mesh_info.set_holes([(0.5, 0, 0)]) mesh = build(mesh_info) print("%d elements" % len(mesh.elements)) fvi2fm = mesh.face_vertex_indices_to_face_marker face_marker_to_tag = { profile_marker: "noslip", Marker.MINUS_X: "inflow", Marker.PLUS_X: "outflow", Marker.MINUS_Y: "inflow", Marker.PLUS_Y: "inflow", Marker.PLUS_Z: "inflow", Marker.MINUS_Z: "inflow" } def bdry_tagger(fvi, el, fn, all_v): face_marker = fvi2fm[fvi] return [face_marker_to_tag[face_marker]] from grudge.mesh import make_conformal_mesh return make_conformal_mesh(mesh.points, mesh.elements, bdry_tagger)
def generate_TetMesh(): bpy.ops.object.mode_set(mode = 'OBJECT', toggle = False) bpy.context.scene.update() print("Scene Updated!") config = bpy.context.scene.CONFIG_MeshPy tetIndex = 0 vertList = [] faceList = [] meshPoints = [] meshFacets = [] split_faceList = [] split_vertList = [] ob = bpy.context.active_object obname = ob.name #convert all faces to triangles for testing ### that did not help with the crash problem:( ''' for vert in ob.data.vertices: vert.select = True bpy.ops.object.mode_set(mode = 'EDIT', toggle = False) bpy.ops.mesh.quads_convert_to_tris() bpy.ops.object.mode_set(mode = 'OBJECT', toggle = False) ''' #compute mesh compute_vertices(ob, meshPoints) compute_faces(ob, meshFacets) if config.make_subdivision == False: arg = "Y" else: arg = "" mesh_info = MeshInfo() mesh_info.set_points(meshPoints) mesh_info.set_facets(meshFacets) debugArg = "" args = (debugArg + "pq" + str(config.ratio_quality) + "a" + str(config.ratio_maxsize) + str(arg)) #args = ("o2" + str(arg)) tetmesh = build(mesh_info, Options(args), verbose = True, attributes = False, volume_constraints = False, max_volume = None, diagnose = False, insert_points = None) compute_mesh(tetmesh, vertList, faceList) ##all this should only be executed when preview is disabled if config.make_split == True: ##add counter to iterate to iterate the loop through all tetras #print(len(tetmesh.elements)) while tetIndex < len(tetmesh.elements): compute_mesh_split(tetmesh, split_faceList, split_vertList, vertList) #print("split_faceList ", tetIndex, ": ", split_faceList[tetIndex]) #print("split_vertList ", tetIndex, ": ", split_vertList[tetIndex]) #put this in a separate loop maybe bring some speed up #create mesh tetname = obname + "Tet" tet = create_mesh(tetname, split_vertList[tetIndex], split_faceList[tetIndex]) #run configs enable_game(config, tet) enable_physics(config, tet, tetname) #bpy.ops.group.create(name='test') world_correction(config, ob, tet) tetIndex = tetIndex + 1 else: #create mesh tetname = obname + "Tet" tetMesh = create_mesh(tetname, vertList, faceList) #run configs enable_game(config, tetMesh) enable_physics(config, tetMesh, tetname) world_correction(config, ob, tetMesh)
x = np.sin(theta) y = np.cos(theta) base.extend([(x, y)]) (points, facets, facet_holestarts, markers) = generate_extrusion(rz_points=rz, base_shape=base) p_array = np.array(points) xs = p_array[:, 0] ys = p_array[:, 1] zs = p_array[:, 2] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(xs, ys, zs) for f in facets: plt.plot(xs[list(f[0])], ys[list(f[0])], zs[list(f[0])]) plt.show() for i_facet, poly_list in enumerate(facets): print(poly_list) mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets_ex(facets, facet_holestarts, markers) mesh = build(mesh_info) print(mesh.elements) mesh.write_vtk('test.vtk')
def make_box_mesh(a=(0, 0, 0), b=(1, 1, 1), max_volume=None, periodicity=None, boundary_tagger=(lambda fvi, el, fn, all_v: []), return_meshpy_mesh=False): """Return a mesh for a brick from the origin to `dimensions`. *max_volume* specifies the maximum volume for each tetrahedron. *periodicity* is either None, or a triple of bools, indicating whether periodic BCs are to be applied along that axis. See :func:`make_conformal_mesh` for the meaning of *boundary_tagger*. A few stock boundary tags are provided for easy application of boundary conditions, namely plus_[xyz] and minus_[xyz] tag the appropriate faces of the brick. """ def count(iterable): result = 0 for i in iterable: result += 1 return result from meshpy.tet import MeshInfo, build from meshpy.geometry import make_box points, facets, _, facet_markers = make_box(a, b) mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets(facets, facet_markers) if periodicity is None: periodicity = (False, False, False) axes = ["x", "y", "z"] per_count = count(p for p in periodicity if p) marker_to_tag = {} mesh_periodicity = [] periodic_tags = set() if per_count: mesh_info.pbc_groups.resize(per_count) pbc_group_number = 0 for axis, axis_per in enumerate(periodicity): minus_marker = 1+2*axis plus_marker = 2+2*axis minus_tag = "minus_"+axes[axis] plus_tag = "plus_"+axes[axis] marker_to_tag[minus_marker] = minus_tag marker_to_tag[plus_marker] = plus_tag if axis_per: pbcg = mesh_info.pbc_groups[pbc_group_number] pbc_group_number += 1 pbcg.facet_marker_1 = minus_marker pbcg.facet_marker_2 = plus_marker translation = [0, 0, 0] translation[axis] = b[axis]-a[axis] pbcg.set_transform(translation=translation) mesh_periodicity.append((minus_tag, plus_tag)) periodic_tags.add(minus_tag) periodic_tags.add(plus_tag) else: mesh_periodicity.append(None) generated_mesh = build(mesh_info, max_volume=max_volume) fvi2fm = generated_mesh.face_vertex_indices_to_face_marker def wrapped_boundary_tagger(fvi, el, fn, all_v): face_tag = marker_to_tag[fvi2fm[frozenset(fvi)]] if face_tag in periodic_tags: return [face_tag] else: return [face_tag] + boundary_tagger(fvi, el, fn, all_v) from hedge.mesh import make_conformal_mesh_ext from hedge.mesh.element import Tetrahedron vertices = numpy.asarray(generated_mesh.points, dtype=float, order="C") result = make_conformal_mesh_ext( vertices, [Tetrahedron(i, el_idx, vertices) for i, el_idx in enumerate(generated_mesh.elements)], wrapped_boundary_tagger, periodicity=mesh_periodicity) if return_meshpy_mesh: return result, generated_mesh else: return result
def make_extrusion_with_fine_core(rz, inner_r, max_volume_inner=1e-4, max_volume_outer=5e-2, radial_subdiv=20): min_z = min(rz_pt[1] for rz_pt in rz) max_z = max(rz_pt[1] for rz_pt in rz) from meshpy.tet import MeshInfo, build from meshpy.geometry import generate_surface_of_revolution MINUS_Z_MARKER = 1 PLUS_Z_MARKER = 2 inner_points, inner_facets, inner_holes, inner_markers = \ generate_surface_of_revolution( [ (0, min_z), (inner_r, min_z), (inner_r, max_z), (0, max_z), ], ring_markers=[ MINUS_Z_MARKER, 0, PLUS_Z_MARKER ], radial_subdiv=radial_subdiv, ) inner_point_indices = tuple(range(len(inner_points))) outer_points, outer_facets, outer_holes, outer_markers = \ generate_surface_of_revolution( [(inner_r,min_z)] + rz + [(inner_r, max_z)], ring_markers=[MINUS_Z_MARKER] + [0]*(len(rz)-1) + [PLUS_Z_MARKER], point_idx_offset=len(inner_points), radial_subdiv=radial_subdiv, ring_point_indices= [ inner_point_indices[:radial_subdiv] ] + [None]*len(rz) + [inner_point_indices[radial_subdiv:]] ) mesh_info = MeshInfo() mesh_info.set_points(inner_points + outer_points) mesh_info.set_facets_ex( inner_facets + outer_facets, inner_holes + outer_holes, inner_markers + outer_markers, ) # set regional max. volume mesh_info.regions.resize(2) mesh_info.regions[0] = [0, 0, (max_z+min_z)/2, 0, max_volume_inner] mesh_info.regions[1] = [inner_r+(rz[0][0]-inner_r)/2, 0, (max_z+min_z)/2, 0, max_volume_outer] # add periodicity mesh_info.pbc_groups.resize(1) pbcg = mesh_info.pbc_groups[0] pbcg.facet_marker_1 = MINUS_Z_MARKER pbcg.facet_marker_2 = PLUS_Z_MARKER pbcg.set_transform(translation=[0,0,max_z-min_z]) mesh = build(mesh_info, verbose=True, volume_constraints=True) #print "%d elements" % len(mesh.elements) #mesh.write_vtk("gun.vtk") fvi2fm = mesh.face_vertex_indices_to_face_marker def zper_boundary_tagger(fvi, el, fn, points): face_marker = fvi2fm[frozenset(fvi)] if face_marker == MINUS_Z_MARKER: return ["minus_z"] elif face_marker == PLUS_Z_MARKER: return ["plus_z"] else: return ["shell"] vertices = numpy.asarray(mesh.points, dtype=float, order="C") from hedge.mesh import make_conformal_mesh_ext from hedge.mesh.element import Tetrahedron return make_conformal_mesh_ext( vertices, [Tetrahedron(i, el_idx, vertices) for i, el_idx in enumerate(mesh.elements)], zper_boundary_tagger, periodicity=[None, None, ("minus_z", "plus_z")])
def generateConeMesh(plot=True): x0 = 0 y0 = 0 z0 = 1 h = 1 r_bottom = 1.3 r_top = 1.5 r_scale = r_top / r_bottom rz = [(0, z0), (1, z0), (r_scale, z0 + h), (0, z0 + h)] base = [] # Create circle for theta in np.linspace(0, 2 * np.pi, 40): x = r_bottom * np.sin(theta) y = r_bottom * np.cos(theta) base.extend([(x, y)]) (points, facets, facet_holestarts, markers) = generate_extrusion(rz_points=rz, base_shape=base) if plot: p_array = np.array(points) xs = p_array[:, 0] + x0 ys = p_array[:, 1] + y0 zs = p_array[:, 2] fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.scatter(xs, ys, zs) for f in facets: plt.plot(xs[list(f[0])], ys[list(f[0])], zs[list(f[0])]) if True: axLim = ax.get_w_lims() MAX = np.max(axLim) for direction in (-1, 1): for point in np.diag(direction * MAX * np.array([1, 1, 1])): ax.plot( [point[0]], [point[1]], [np.abs(point[2])], 'w') x = [0, 0] y = [0, 0] z = [1, 1 + 0.2] plt.plot(x, y, z) plt.show() mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets_ex(facets) mesh = build(mesh_info) # print(mesh.elements) cellList = [] vertexList = [] mupifMesh = Mesh.UnstructuredMesh() for i, p in enumerate(mesh.points): p = (p[0] + x0, p[1] + y0, p[2]) vertexList.extend([Vertex.Vertex(i, i, p)]) for i, t in enumerate(mesh.elements): cellList.extend([Cell.Tetrahedron_3d_lin(mupifMesh, i, i, t)]) mupifMesh.setup(vertexList, cellList) return(mupifMesh)
from meshpy.tet import MeshInfo, build mesh_info = MeshInfo() # construct a two-box extrusion of this base base = [(-2, -2, 0), (2, -2, 0), (2, 2, 0), (-2, 2, 0)] # first, the nodes mesh_info.set_points(base + [(x, y, z + 5) for x, y, z in base] + [(x, y, z + 10) for x, y, z in base]) # next, the facets # vertex indices for a box missing the -z face box_without_minus_z = [ [4, 5, 6, 7], [0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0], ] def add_to_all_vertex_indices(facets, increment): return [[pt + increment for pt in facet] for facet in facets] mesh_info.set_facets( [[0, 1, 2, 3]] # base + box_without_minus_z # first box
def ProcessGlobalAction(ActionType, GlobalAction, NumberedPoints, Elements, Points): ExtendedData = {'ElementPropertyIndex' : {}} if ActionType == 'SpecialEntities': Filters = json.loads(GlobalAction['Filters']) if not 'SpecialEntities' in ExtendedData: ExtendedData['SpecialEntities'] = [] for Element in Elements: if Element and Element['filter'] in Filters: ExtendedData['SpecialEntities'].append(Element) return ExtendedData, False if ActionType == 'Nonlinear': Output = {} #for key in GlobalAction: # if 'ElementPropertyMaxIndex' in ExtendedData: # ExtendedData['ElementPropertyMaxIndex'] += 1 # else: # ExtendedData['ElementPropertyMaxIndex'] = 1 # propertyindex = ExtendedData['ElementPropertyMaxIndex'] # ExtendedData['ElementPropertyIndex'][key] = propertyindex # ExtendedData['NonlinearPropertyIndex'][key] = nonlinearindex # # # ExtendedData['ElementPropertyIndex'][key] = workingindex #In this same notation we can get the index when writing elements # Output[index] = "" return ExtendedData, Output #Here we have Output ready to be printed and ExtendedData, a mapper to Output if ActionType == 'ElementProperties': Output = {} for key in GlobalAction: if 'ElementPropertyMaxIndex' in ExtendedData: ExtendedData['ElementPropertyMaxIndex'] += 1 else: ExtendedData['ElementPropertyMaxIndex'] = 1 workingindex = ExtendedData['ElementPropertyMaxIndex'] ExtendedData['ElementPropertyIndex'][key] = workingindex #In this same notation we can get the index when writing elements Output[workingindex] = GlobalAction[key] return ExtendedData, Output #Here we have Output ready to be printed and ExtendedData, a mapper to Output if ActionType == 'Orphans': Output = [] for Number, Point in NumberedPoints['points'].iteritems(): ElementAmount = len(Point['elementnumbers']) if ElementAmount < 2: print "Orphan node {}!".format(Number) Output.append({'element_type': 'POINT', 'position': Point['point'], 'layer': 'Errors', 'nodenumber': Number}) return {'information':'addObjects'}, Output#Here we have Output ready to be printed and ExtendedData, a mapper to Output if ActionType == 'Meshing': EntityModelData = json.loads(GlobalAction['EntityModelData']) if 'EntityModelData' in GlobalAction else {} ExtendedModelData = json.loads(GlobalAction['ExtendedModelData']) if 'ExtendedModelData' in GlobalAction else {} Semantic = json.loads(GlobalAction['Semantic']) if 'Semantic' in GlobalAction else {} if 'exclude filters' in Semantic: if not 'ExcludeFilters' in ExtendedData: ExtendedData['ExcludeFilters'] = [] ExtendedData['ExcludeFilters'] = ExtendedData['ExcludeFilters'] + Semantic['exclude filters'] Boundaries = [] Output = [] Geometry = json.loads(GlobalAction['Geometry']) if 'Geometry' in GlobalAction else {} Parameters = json.loads(GlobalAction['Parameters']) if 'Parameters' in GlobalAction else {} AdditionalPointsFilters = Geometry['points'] if 'points' in Geometry else [] for Filter in Geometry['boundaries']: print "Using filter {} as finite element domain boundary.".format(Filter) for Element in Elements: if Element and Element['filter'] == Filter and Element['elementclass'] in ['FACE_3NODES', 'FACE_4NODES', 'POLYLINE', 'PLINE_5NODES']: Boundaries.append(Element) AdditionalPoints = [] for Filter in AdditionalPointsFilters: print "Using filter {} as additional points container.".format(Filter) for Element in Elements: if Element and Element['filter'] == Filter and Element['elementclass'] in ['FACE_3NODES', 'FACE_4NODES', 'POLYLINE', 'LINE_2NODES']: AdditionalPoints.extend( Element['points'] ) print "Assembling FE domain" mesh_info = MeshInfo() #additional_points = MeshInfo() #additional_points.set_points(list(set(AdditionalPoints))) MeshPoints = [] MeshFacets = [] MeshPointsIndex = {} PointIndex = 0 for BoundaryElement in Boundaries: ElementPoints = BoundaryElement['points'] MeshFacet = [] if Parameters['type'] == 'divide_4p_faces': for point in [ElementPoints[0],ElementPoints[1],ElementPoints[2]]: if not point in MeshPointsIndex: MeshPointsIndex[point] = PointIndex MeshPoints.append(False) MeshPoints[PointIndex] = NumberedPoints['points'][point]['point'] PointIndex += 1 MeshFacet.append(MeshPointsIndex[point]) MeshFacets.append(MeshFacet) MeshFacet = [] if ElementPoints[2] != ElementPoints[3]: for point in [ElementPoints[0],ElementPoints[2],ElementPoints[3]]: if not point in MeshPointsIndex: MeshPointsIndex[point] = PointIndex MeshPoints.append(False) MeshPoints[PointIndex] = NumberedPoints['points'][point]['point'] PointIndex += 1 MeshFacet.append(MeshPointsIndex[point]) MeshFacets.append(MeshFacet) else: for point in ElementPoints: if not point in MeshPointsIndex: MeshPointsIndex[point] = PointIndex MeshPoints.append(False) MeshPoints[PointIndex] = NumberedPoints['points'][point]['point'] PointIndex += 1 if not MeshPointsIndex[point] in MeshFacet: MeshFacet.append(MeshPointsIndex[point]) else: print "Mesh error or 3-point 3DFACE." MeshFacets.append(MeshFacet) MeshFacet = [] for point in list(set(AdditionalPoints)): if not point in MeshPointsIndex: #See whether the point is already indexed by its native number MeshPointsIndex[point] = PointIndex MeshPoints.append(False) MeshPoints[PointIndex] = NumberedPoints['points'][point]['point'] PointIndex += 1 saveobject(MeshFacets, r'MeshFacets') saveobject(MeshPoints, r'MeshPoints') mesh_info.set_facets(MeshFacets) mesh_info.set_points(MeshPoints) #insertaddpoints #points = np.array([list(x) for x in MeshPoints]) #qhull = scipy.spatial.Delaunay(points) #mesh_info.Options(switches='pq') #mesh_info.set_points([ # (0,0,0), (12,0,0), (12,12,0), (0,12,0), # (0,0,12), (12,0,12), (12,12,12), (0,12,12), # ]) #mesh_info.set_facets([ # [0,1,2,3], # [4,5,6,7], # [0,4,5,1], # [1,5,6,2], # [2,6,7,3], # [3,7,4,0], # ]) #opts = Options(switches='pq') #opts.maxvolume = 0.0001 #opts.parse_switches() mesh_info.regions.resize(1) mesh_info.regions[0] = [ MeshPoints[0][0], MeshPoints[0][1], MeshPoints[0][2], # point in volume -> first box 0, # region tag (user-defined number) Parameters['maxvolume'], # max tet volume in region ] mesh = build(mesh_info, options=Options(switches="pqT", epsilon=Parameters['tolerance']), volume_constraints=True) print "Created mesh with {} points, {} faces and {} elements.".format(len(mesh.points), len(mesh.faces), len(mesh.elements)) #mesh = build(mesh_info, options=Options(switches="pTi", epsilon=Parameters['tolerance'], insertaddpoints=True), volume_constraints=True, insert_points=additional_points) #mesh.write_vtk("test.vtk") #mesh.points #mesh.elements #mesh.faces filename = "test" #mesh.save_elements(filename) #mesh.save_nodes(filename) #mesh.save_elements(filename) #mesh.save_faces(filename) #mesh.save_edges(filename) #mesh.save_neighbors(filename) #mesh.save_poly(filename) #for element in qhull.simplices: # Position = [list(qhull.points[x]) for x in element] # Output.append({'element_type': '3DFACE', 'position': Position, 'layer': 'Elements'}) #NumberedPoints['points'][compoundObject['points'][0]]['point'] if not Boundaries: return False, False Precision = int(GlobalAction['Precision']) if 'Precision' in GlobalAction else 4 if not 'output' in Semantic or Semantic['output'].lower() == 'graphics': for face in mesh.faces: Position = [mesh.points[x] for x in face] Output.append({'element_type': '3DFACE', 'position': Position, 'layer': 'Faces'}) for element in mesh.elements: Position = [mesh.points[x] for x in element] Output.append({'element_type': '3DFACE', 'position': Position, 'layer': 'Elements'}) return {'information':'addObjects'}, Output elif Semantic['output'].lower() == 'fea': Points = {} for NumberedPoint in NumberedPoints['points']: Points[NumberedPoints['points'][NumberedPoint]['point']] = NumberedPoint NodeNumber = NumberedPoints['maximumNode'] for element in mesh.elements: Position = [mesh.points[x] for x in element] for i, point in enumerate(Position): Position[i] = [round(x, Precision) for x in point] #else: # if tuple([round(x, PrepPrecision) for x in Coords]) in [(4.95,-17.69,58.9), (4.96,-17.69,58.9)]: # pass # object['points'][i] = tuple([round(x, PrepPrecision) for x in Coords]) # if not object['points'][i] in GlobalPointIndex: # GlobalPointIndex.append(object['points'][i]) ElementPoints = [] ElementNumber = len(Elements) for point in Position: #Update NumberedPoints and construct all necessary data for Elements point = NeighborhoodRaw(tuple(point), Precision, Points) if not tuple(point) in Points: NodeNumber += 1 Points[tuple(point)] = NodeNumber #PointsNumbered.append(None) NumberedPoints['points'][NodeNumber] = {'point': tuple(point), 'elementnumbers': []} NumberedPoints['maximumNode'] = NodeNumber CurrentPointNumber = Points[tuple(point)] ElementPoints.append(CurrentPointNumber) NumberedPoints['points'][CurrentPointNumber]['elementnumbers'].append(ElementNumber) #Update Points if possible #Update Elements Element = { 'points' : ElementPoints, 'elementclass' : 'SOLID_4NODES', 'elementnum': ElementNumber, #??? 'filter': Semantic['filter'], 'entity_model_data': EntityModelData, 'extended_model_data': ExtendedModelData, 'generation_order': None, } Elements.append(None) Elements[ElementNumber] = Element return ExtendedData, False if ActionType == 'AddShells': ExtendedData = {} EntityModelData = json.loads(GlobalAction['EntityModelData']) if 'EntityModelData' in GlobalAction else {} ExtendedModelData = json.loads(GlobalAction['ExtendedModelData']) if 'ExtendedModelData' in GlobalAction else {} Filters = json.loads(GlobalAction['Filters']) if 'Filters' in GlobalAction else {} for Element in Elements: if not Element or not Element['filter'] in Filters: continue if Element['generation_order'] == 0 and Element['entity_model_data']['layer'] != "Concrete bases crown": ElementPoints = [Element['points'][0], Element['points'][1], Element['points'][2]] ElementNumber = len(Elements) NewElement = { 'points' : ElementPoints, 'elementclass' : 'FACE_3NODES', 'elementnum': ElementNumber, #??? 'filter': GlobalAction['AssignedFilter'], 'entity_model_data': EntityModelData, 'extended_model_data': ExtendedModelData, 'generation_order': None, } Elements.append(None) Elements[ElementNumber] = NewElement if Element['elementclass'] == 'SOLID_8NODES': ElementPoints = [Element['points'][0], Element['points'][2], Element['points'][3]] ElementNumber = len(Elements) NewElement = { 'points' : ElementPoints, 'elementclass' : 'FACE_3NODES', 'elementnum': ElementNumber, #??? 'filter': GlobalAction['AssignedFilter'], 'entity_model_data': EntityModelData, 'extended_model_data': ExtendedModelData, 'generation_order': None, } Elements.append(None) Elements[ElementNumber] = NewElement if Element['elementclass'] == 'SOLID_10NODES': pass pass return {}, {} return False
def save_mesh(filepath, mesh, boundary_condition, use_graphics, fem_dimensions, mass_density, poisson_ratio, young_modulus, meshpy ): """Write mesh data out to ply file If graphics are checked to be exported, it will prep any UVs and normals it can and prepare a full list of faces FEM3D meshes have their mesh run through MeshPy which is a Python interface for TetGen """ file = open(filepath, "w", encoding="utf8", newline="\n") fwrite = file.write verts = [] faces = [] elements = [] uvcoords = {} normals = {} has_uv = bool(mesh.uv_textures) and mesh.uv_textures.active if has_uv and use_graphics: mesh.calc_tessface() uv_data = mesh.tessface_uv_textures.active.data for i, polygon in enumerate(mesh.polygons): uv = uv_data[i].uv1, uv_data[i].uv2, uv_data[i].uv3, uv_data[i].uv4 for j, vert in enumerate(polygon.vertices): uvcoord = uv[j][0], uv[j][1] normal = mesh.vertices[vert].normal[:] vertcoord = mesh.vertices[vert].co[:] if vertcoord not in uvcoords: uvcoords[vertcoord] = uvcoord if vertcoord not in normals: normals[vertcoord] = normal if fem_dimensions == '3': from meshpy.tet import MeshInfo, build, Options bpy.ops.object.mode_set(mode='OBJECT', toggle=False) bpy.context.scene.update() # get list of verts and faces direct from mesh mesh_verts = [] for vert in mesh.vertices: mesh_verts.append(vert.co[:]) mesh_faces = [] for face in mesh.polygons: mesh_faces.append(face.vertices[:]) args = meshpy mesh_info = MeshInfo() mesh_info.set_points(mesh_verts) mesh_info.set_facets(mesh_faces) tets = build(mesh_info, Options(args), verbose=True, attributes=False, volume_constraints=False, max_volume=None, diagnose=False, insert_points=None) # Ply prep by creating updated vert list and face list using tets.points and tets.elements for point in tets.points: verts.append((point[0], point[1], point[2])) for tet in tets.elements: elements.append((tet[0], tet[1], tet[2], tet[3])) for face in tets.faces: faces.append((face[2], face[1], face[0])) else: for vert in mesh.vertices: verts.append((vert.co[0], vert.co[1], vert.co[2])) for face in mesh.polygons: if len(face.vertices) == 3: faces.append((face.vertices[0], face.vertices[1], face.vertices[2])) else: faces.append((face.vertices[0], face.vertices[1], face.vertices[2])) faces.append((face.vertices[0], face.vertices[2], face.vertices[3])) fwrite("ply\n") fwrite("format ascii 1.0\n") fwrite("comment Created by OpenSurgSim FEM exporter for Blender\n") fwrite("comment MeshPy options '%s'\n" % meshpy) fwrite("element vertex %d\n" % len(verts)) fwrite("property double x\n" "property double y\n" "property double z\n") if use_graphics: if fem_dimensions != '1': if normals: fwrite("property double nx\n" "property double ny\n" "property double nz\n") if has_uv: fwrite("property double s\n" "property double t\n") fwrite("element face %d\n" % len(faces)) fwrite("property list uint uint vertex_indices\n") if fem_dimensions == '1': fwrite("element 1d_element %d\n" % len(mesh.vertices)-1) fwrite("property list uint uint vertex_indices\n") elif fem_dimensions == '2': fwrite("element 2d_element %d\n" % len(faces)) fwrite("property list uint uint vertex_indices\n") elif fem_dimensions == '3': fwrite("element 3d_element %d\n" % len(elements)) fwrite("property list uint uint vertex_indices\n") fwrite("element material 1\n") fwrite("property double mass_density\n") fwrite("property double poisson_ratio\n") fwrite("property double young_modulus\n") if boundary_condition is not None: fwrite("element boundary_condition %d\n" % len(boundary_condition)) fwrite("property uint vertex_index\n") fwrite("end_header\n") if fem_dimensions != '1': if use_graphics: for vert in verts: fwrite("%.6f %.6f %.6f" % vert[:]) if vert in normals: fwrite(" %.6f %.6f %.6f" % normals[vert][:]) if has_uv and vert in uvcoords: fwrite(" %.6f %.6f" % uvcoords[vert][:]) fwrite("\n") for face in faces: fwrite("3 %d %d %d\n" % face[:]) else: for vert in verts: fwrite("%.6f %.6f %.6f\n" % vert[:]) else: for vert in mesh.vertices: fwrite("%.6f %.6f %.6f\n" % vert.co[:]) if fem_dimensions is '1': for i in len(mesh.vertices)-1: fwrite("2 %d %d\n" % list(i, i+1)) elif fem_dimensions is '2': for face in faces: fwrite("3 %d %d %d\n" % face[:]) elif fem_dimensions is '3': for tet in elements: fwrite("4 %d %d %d %d\n" % tet[:]) fwrite("%s %s %s\n" % (mass_density, poisson_ratio, young_modulus)) if boundary_condition is not None: for index in boundary_condition: fwrite("%d\n" % index) file.close() print("writing %r done" % filepath) return {'FINISHED'}
# Show the plot to the screen #pyplot.show() points = [] for _tri in stl_mesh.vectors: points = points + [tuple(x) for x in [_tri[0],_tri[1],_tri[2]]] uniques = np.unique(points, axis=0) #This needs significant speedup panels = [] for _tri in stl_mesh.vectors: _tripnt = [] for _index in range(len(uniques)): if list(uniques[_index]) in list(list(x) for x in _tri): _tripnt.append(_index) panels.append(tuple(_tripnt)) mesh_info = MeshInfo() mesh_info.set_points(points) mesh_info.set_facets(panels) ### Plotting points = np.array(mesh_info.points) from plotting import scatter3d scatter3d(points) ## mesh = build(mesh_info, options=Options("")) #mesh = build(mesh_info, options=Options("pq")) mesh.write_vtk("test.vtk")
''' Created on Jul 10, 2014 @author: BOIRUM ''' from meshpy.tet import MeshInfo, build mesh_info = MeshInfo() mesh_info.set_points([ (0,0,0), (2,0,0), (2,2,0), (0,2,0), (0,0,12), (2,0,12), (2,2,12), (0,2,12), ]) mesh_info.set_facets([ [0,1,2,3], [4,5,6,7], [0,4,5,1], [1,5,6,2], [2,6,7,3], [3,7,4,0], ]) mesh = build(mesh_info) print "Mesh Points:" for i, p in enumerate(mesh.points): print i, p print "Point numbers in tetrahedra:" for i, t in enumerate(mesh.elements): print i, t mesh.write_vtk("test.vtk")
def make_tetgen_mesh(): global mn_section_dict global face_marker_plane_dict # Make single volume vert_stack = [] face_stack = [] face_marker_stack = [] face_marker_brdr = 1 # are positive face_marker_surf = -1 # are negative # Make sure we don't double count any planes # Sides ids to face marker plane_sides_ids_done = {} # Go through all the sections for sec_id in mn_section_dict.keys(): sec = mn_section_dict[sec_id] # Check that there are any borders if len(sec.planes_sc_brdrs[0]) == 0 and len(sec.planes_sc_brdrs[1]) == 0 and sec.plane_surf == -1: print("Error! No bounding planes for this section!") # Add the surface plane... if not sec.plane_surf.sides_ids in plane_sides_ids_done: vert_stack += [sec.plane_surf.vert_list] face_stack += [sec.plane_surf.face_list] face_marker_stack += [len(sec.plane_surf.face_list)*[face_marker_surf]] face_marker_plane_dict[face_marker_surf] = sec.plane_surf sec.face_marker_dict[face_marker_surf] = -1 plane_sides_ids_done[sec.plane_surf.sides_ids] = face_marker_surf face_marker_surf -= 1 else: # Do this for EVERY section sec.face_marker_dict[plane_sides_ids_done[sec.plane_surf.sides_ids]] = -1 # And the borders... for i,brdr in enumerate(sec.planes_sc_brdrs): for j,plane in enumerate(brdr): if not plane.sides_ids in plane_sides_ids_done: vert_stack += [plane.vert_list] face_stack += [plane.face_list] # Face marker face_marker_stack += [len(plane.face_list)*[face_marker_brdr]] face_marker_plane_dict[face_marker_brdr] = plane sec.face_marker_dict[face_marker_brdr] = (i,j) ''' if mn_sec.sc_id == (1,3): global shared_3_27 PLANE_SHARED = True for v in shared_3_27: if not v in plane.vert_list: PLANE_SHARED = False break if PLANE_SHARED: print("THIS IS THE SHARED PLANE: marker: " + str(face_marker_brdr)) if triplet[0] in shared_3_27 and triplet[1] in shared_3_27 and triplet[2] in shared_3_27: print("Trip: " + str(triplet) + " is shared; has face marker: " + str(face_marker)) ''' plane_sides_ids_done[plane.sides_ids] = face_marker_brdr face_marker_brdr += 1 else: # Do this for EVERY section sec.face_marker_dict[plane_sides_ids_done[plane.sides_ids]] = (i,j) # Create a correctly indexed closed volume vert_list, face_list, face_marker_list = stack_lists(vert_stack,face_stack,face_marker_stack=face_marker_stack) # Make the tetgen mesh mesh_info = MeshInfo() # Points mesh_info.set_points(vert_list) # Faces mesh_info.set_facets(face_list, markers = face_marker_list) # --- TEMP --- ''' # Make an object from the surface we are planning to tetrahedronalize mesh_new = bpy.data.meshes.new("pre_tet_mesh") mesh_new.from_pydata(vert_list,[],face_list) mesh_new.validate(verbose=False) # Important! and i dont know why mesh_new.update() obj_new = bpy.data.objects.new("pre_tet",mesh_new) context.scene.objects.link(obj_new) # return ''' # --- FIN TEMP --- # Tetrahedralize # Options: # neighout = Write out neighbors # facesout = Write out faces # edgesout = Write out edges # regionattrib = Write out element_attributes = unique id for every tet in a distinct volume # nobisect = Dont alter surface print("> Starting TetGen") opts = Options(switches='pq', neighout = True, facesout = True, edgesout = True, regionattrib = True, verbose = True, docheck = True) mesh_built = build(mesh_info, options=opts) print("> Finished TetGen successfully") return mesh_built
def make_wingmesh(): import numpy from math import pi, cos, sin from meshpy.tet import MeshInfo, build from meshpy.geometry import GeometryBuilder, Marker, \ generate_extrusion, make_box geob = GeometryBuilder() profile_marker = Marker.FIRST_USER_MARKER wing_length = 2 wing_subdiv = 5 rz_points = [ (0, -wing_length*1.05), (0.7, -wing_length*1.05), ] + [ (r, x) for x, r in zip( numpy.linspace(-wing_length, 0, wing_subdiv, endpoint=False), numpy.linspace(0.8, 1, wing_subdiv, endpoint=False)) ] + [(1,0)] + [ (r, x) for x, r in zip( numpy.linspace(wing_length, 0, wing_subdiv, endpoint=False), numpy.linspace(0.8, 1, wing_subdiv, endpoint=False)) ][::-1] + [ (0.7, wing_length*1.05), (0, wing_length*1.05) ] from meshpy.naca import get_naca_points geob.add_geometry(*generate_extrusion( rz_points=rz_points, base_shape=get_naca_points("0012", number_of_points=20), ring_markers=(wing_subdiv*2+4)*[profile_marker])) def deform_wing(p): x, y, z = p return numpy.array([ x + 0.8*abs(z/wing_length)** 1.2, y + 0.1*abs(z/wing_length)**2, z]) geob.apply_transform(deform_wing) points, facets, facet_markers = make_box( numpy.array([-1.5,-1,-wing_length-1], dtype=numpy.float64), numpy.array([3,1,wing_length+1], dtype=numpy.float64)) geob.add_geometry(points, facets, facet_markers=facet_markers) mesh_info = MeshInfo() geob.set(mesh_info) mesh_info.set_holes([(0.5,0,0)]) mesh = build(mesh_info) print "%d elements" % len(mesh.elements) fvi2fm = mesh.face_vertex_indices_to_face_marker face_marker_to_tag = { profile_marker: "noslip", Marker.MINUS_X: "inflow", Marker.PLUS_X: "outflow", Marker.MINUS_Y: "inflow", Marker.PLUS_Y: "inflow", Marker.PLUS_Z: "inflow", Marker.MINUS_Z: "inflow" } def bdry_tagger(fvi, el, fn, all_v): face_marker = fvi2fm[fvi] return [face_marker_to_tag[face_marker]] from hedge.mesh import make_conformal_mesh return make_conformal_mesh(mesh.points, mesh.elements, bdry_tagger)
def area_of_tri(nodes): v1 = np.array(nodes[0].coord[:2]) - np.array(nodes[1].coord[:2]) v2 = np.array(nodes[0].coord[:2]) - np.array(nodes[2].coord[:2]) area = np.cross(v1, v2) / 2. return area if __name__ == "__main__": #mesh r = 1 l = 2 rz = [(0, 0), (r, 0), (r, l), (0, l)] geob = GeometryBuilder() geob.add_geometry(*generate_surface_of_revolution( rz, radial_subdiv=20, ring_markers=[1, 2, 3])) mesh_info = MeshInfo() geob.set(mesh_info) mesh = build(mesh_info, max_volume=0.01) E = 210e6 nu = 0.3 P = 2000 points = np.array(mesh.points) cells = np.array(mesh.elements) face_cells = np.array(mesh.faces) z_face0_cells = [ c for c in face_cells if np.isclose(points[c][:, 2], 0).all() ] z_face2_cells = [ c for c in face_cells if np.isclose(points[c][:, 2], 2).all() ]