def GmshToMesh(self, filename): gmsh.merge(filename) all_nodes = gmsh.model.mesh.getNodes() self.Npts = len(all_nodes[0]) for i in range(self.Npts): self.points.append( Point(all_nodes[1][i * 3], all_nodes[1][i * 3 + 1], all_nodes[1][i * 3 + 2])) for temp in gmsh.model.getPhysicalGroups(): dim = temp[0] physical_tag = temp[1] for entity in gmsh.model.getEntitiesForPhysicalGroup( dim, physical_tag): elements = gmsh.model.mesh.getElements(dim, entity) for i in range(len(elements[1][0])): list_pts = [] for k in range(dim + 1): list_pts.append( self.points[int(elements[2][0][i * (dim + 1) + k]) - 1]) if (dim == 2): self.triangles.append(Triangle(list_pts, physical_tag)) else: self.segments.append(Segment(list_pts, physical_tag)) return
def read_from_msh(filename: str, cell_data=False, facet_data=False, gdim=None): """ Reads a mesh from a msh-file and returns the dolfin-x mesh. Input: filename: Name of msh file cell_data: Boolean, True of a mesh tag for cell data should be returned (Default: False) facet_data: Boolean, True if a mesh tag for facet data should be returned (Default: False) gdim: Geometrical dimension of problem (Default: 3) """ if MPI.COMM_WORLD.rank == 0: # Check if gmsh is already initialized try: current_model = gmsh.model.getCurrent() except ValueError: current_model = None gmsh.initialize() gmsh.model.add("Mesh from file") gmsh.merge(filename) output = gmsh_model_to_mesh(gmsh.model, cell_data=cell_data, facet_data=facet_data, gdim=gdim) if MPI.COMM_WORLD.rank == 0: if current_model is None: gmsh.finalize() else: gmsh.model.setCurrent(current_model) return output
def create_volume(self, model, x): gmsh.merge(self.stl_path) s = gmsh.model.getEntities(2) l = gmsh.model.geo.addSurfaceLoop([s[i][1] for i in range(len(s))]) vol = gmsh.model.geo.addVolume([l]) gmsh.model.geo.synchronize() return {3: vol}
def addGeometry(self, filename: str, name: str, meshFactor: Optional[float] = 0.03): """ Adds CAD geometry into the GMSH kernel. The filename of compatiable model files along with the mesh factor should be used to specify a target mesh size. :param filename: :param name: Name to assign to the geometries imported :param meshFactor: Initialise the target element size to a proportion of the average bounding box dimensions """ if not (os.path.exists(filename) and os.access(filename, os.R_OK)): raise ValueError('File ({:s}) is not readable'.format(filename)) # Adds a single volume self.setAsCurrentModel() # Additional geometry will be merged into the current model gmsh.merge(filename) self.geoms.append({ 'name': name, 'filename': filename, 'meshSize': None, 'meshFactor': meshFactor }) # Set the name of the volume # This automatically done to ensure that are all exported. This may change to parse through all volumes following # merged and be recreated gmsh.model.setEntityName(3, len(self.geoms), name) gmsh.model.addPhysicalGroup(3, [len(self.geoms)], len(self.geoms)) gmsh.model.setPhysicalName(3, len(self.geoms), name) # set the mesh size for this geometry bbox = self.getGeomBoundingBoxById(len(self.geoms)) extents = bbox[1, :] - bbox[0, :] avgDim = np.mean(extents) meshSize = avgDim * meshFactor print('GMSH: Avg dim', avgDim, ' mesh size: ', meshSize) geomPoints = self.getPointsFromVolume(len(self.geoms)) # Set the geometry volume size self.geoms[-1]['meshSize'] = meshSize self.setMeshSize(geomPoints, meshSize) self._isGeometryDirty = True self.setModelChanged()
def gmsh_to_fenicsx(msh_path): # Initialize gmsh gmsh.initialize() # Read in the mesh gmsh.model.add(os.path.basename(msh_path)) gmsh.merge(msh_path) mesh, ct, ft = gmsh_model_to_mesh(gmsh.model, 2) # Finalize gmsh gmsh.finalize() # Return return mesh, ct, ft
def dfm_from_gmsh(file_name: str, dim: int, **kwargs) -> pp.GridBucket: """Generate a GridBucket from a gmsh file. If the provided file is input for gmsh (.geo, not .msh), gmsh will be called to generate the mesh before the GridBucket is constructed. Parameters: file_name (str): Name of gmsh in and out file. Should have extsion .geo or .msh. In the former case, gmsh will be called upon to generate the mesh before the mixed-dimensional mesh is constructed. dim (int): Dimension of the problem. Should be 2 or 3. Returns: GridBucket: Mixed-dimensional grid as contained in the gmsh file. """ # run gmsh to create .msh file if if file_name[-4:] == ".msh": out_file = file_name else: if file_name[-4:] == ".geo": file_name = file_name[:-4] in_file = file_name + ".geo" out_file = file_name + ".msh" # initialize gmsh gmsh.initialize() # Reduce verbosity gmsh.option.setNumber("General.Verbosity", 3) # read the specified file. gmsh.merge(in_file) # Generate mesh, write gmsh.model.mesh.generate(dim=dim) gmsh.write(out_file) # Wipe Gmsh's memory gmsh.finalize() if dim == 2: grids = pp.fracs.simplex.triangle_grid_from_gmsh(out_file, **kwargs) elif dim == 3: grids = pp.fracs.simplex.tetrahedral_grid_from_gmsh(file_name=out_file, **kwargs) else: raise ValueError(f"Unknown dimension, dim: {dim}") return pp.meshing.grid_list_to_grid_bucket(grids, **kwargs)
def optimize(points, cells): meshio.write_points_cells( "cube.msh", points, [("tetra", cells)], file_format="gmsh22", binary=False ) # optimize quality gmsh.initialize() gmsh.model.add("Mesh from file") gmsh.merge("cube.msh") t2 = time.time() gmsh.model.mesh.optimize("", force=True) print("Time spent in optimization: " + str(time.time() - t2)) gmsh.write("cube_ng.msh") gmsh.finalize() # read it back in mesh = meshio.read("cube_ng.msh") points, cells = mesh.points, mesh.cells[0].data return points, cells
def meshObjSTL(obj, dim): import tempfile tmpFile = tempfile.NamedTemporaryFile(suffix='.stl').name obj.Mesh.write(tmpFile) #gmsh.option.setNumber("Mesh.RecombinationAlgorithm",2) #gmsh.option.setNumber("Mesh.Optimize",1) #gmsh.option.setNumber("Mesh.QualityType",2) gmsh.merge(tmpFile) n = gmsh.model.getDimension() s = gmsh.model.getEntities(n) #l = gmsh.model.geo.addSurfaceLoop([s[i][1] for i in range(len(s))]) #gmsh.model.geo.addVolume([l]) #print("Volume added") gmsh.model.geo.synchronize() gmsh.model.mesh.generate(dim) print('Mesh Generated ' + str(dim)) #gmsh.model.mesh.renumberNodes() return True
import gmsh import math import os import sys gmsh.initialize() gmsh.model.add("t17") # Create a square gmsh.model.occ.addRectangle(-1, -1, 0, 2, 2) gmsh.model.occ.synchronize() # Merge a post-processing view containing the target anisotropic mesh sizes path = os.path.dirname(os.path.abspath(__file__)) gmsh.merge(os.path.join(path, os.pardir, 't17_bgmesh.pos')) # Apply the view as the current background mesh bg_field = gmsh.model.mesh.field.add("PostView") gmsh.model.mesh.field.setNumber(bg_field, "ViewIndex", 0) gmsh.model.mesh.field.setAsBackgroundMesh(bg_field) # Use bamg gmsh.option.setNumber("Mesh.SmoothRatio", 3) gmsh.option.setNumber("Mesh.AnisoMax", 1000) gmsh.option.setNumber("Mesh.Algorithm", 7) gmsh.model.mesh.generate(2) gmsh.write("t17.msh") # Launch the GUI to see the results:
import gmsh import math import os import meshio gmsh.initialize() gmsh.option.setNumber("General.Terminal", 1) components = [ "csf", "parenchyma", "lateral_ventricles", "aqueduct", "third_ventricle", "fourth_ventricle", "foramina", "median_aperture" ] for c in components: gmsh.merge(f"/home/marius/Documents/brain_meshes/slicer_stl_files/{c}.stl") #gmsh.merge("/home/marius/Downloads/124422_csf.stl") #gmsh.merge("/home/marius/Downloads/101309_ventricles.stl") n = gmsh.model.getDimension() s = gmsh.model.getEntities(n) #l = gmsh.model.geo.addSurfaceLoop([s[i][1] for i in range(len(s))]) # add all tags of .stl surfaces! #gmsh.model.geo.addVolume([l]) surface_tags = [] for i, comp in enumerate(components): surface_tag = gmsh.model.geo.addSurfaceLoop([s[i][1]]) surface_tags.append(surface_tag) #vol_tag = gmsh.model.geo.addVolume([surface_tag]) for i, tag in enumerate(surface_tags):
gmsh.model.geo.addPoint(0, 0, 0, lc, 1) gmsh.model.geo.addPoint(.1, 0, 0, lc, 2) gmsh.model.geo.addPoint(.1, .3, 0, lc, 3) gmsh.model.geo.addPoint(0, .3, 0, lc, 4) gmsh.model.geo.addLine(1, 2, 1) gmsh.model.geo.addLine(3, 2, 2) gmsh.model.geo.addLine(3, 4, 3) gmsh.model.geo.addLine(4, 1, 4) gmsh.model.geo.addCurveLoop([4, 1, -2, 3], 1) gmsh.model.geo.addPlaneSurface([1], 1) gmsh.model.geo.synchronize() # We merge some post-processing views to work on path = os.path.dirname(os.path.abspath(__file__)) gmsh.merge(os.path.join(path, os.pardir, 'view1.pos')) gmsh.merge(os.path.join(path, os.pardir, 'view1.pos')) gmsh.merge(os.path.join(path, os.pardir, 'view4.pos')) # contains 2 views inside # Gmsh can read post-processing views in various formats. Here the `view1.pos' # and `view4.pos' files are in the Gmsh "parsed" format, which is interpreted by # the GEO script parser. The parsed format should only be used for relatively # small datasets of course: for larger datasets using e.g. MSH files is much # more efficient. Post-processing views can also be created directly from the # Python API. # We then set some general options: gmsh.option.setNumber("General.Trackball", 0) gmsh.option.setNumber("General.RotationX", 0) gmsh.option.setNumber("General.RotationY", 0)
import gmsh import math import os gmsh.initialize() gmsh.option.setNumber('General.Terminal', 1) # load two STL surfaces path = os.path.dirname(os.path.abspath(__file__)) gmsh.merge(os.path.join(path, 'surface1.stl')) gmsh.merge(os.path.join(path, 'surface2.stl')) # merge nodes that are at the same position up to some tol gmsh.option.setNumber('Geometry.Tolerance', 1e-4) gmsh.model.mesh.removeDuplicateNodes() # classify surface mesh according to given angle, and create discrete model # entities (surfaces, curves and points) accordingly gmsh.model.mesh.classifySurfaces(math.pi / 2) # Notes: # # - for more complicated surfaces `forReparametrization=True` could be specified # to force the creation of reparametrizable patches # # - in this simple case, since the two surfaces were simple and already colored, # one could have also simply used `gmsh.model.mesh.createTopology()` instead of # `gmsh.model.mesh.classifySurfaces()` # create a geometry for the discrete curves and surfaces (comment this if you # don't want to remesh the surfaces and simply use the original mesh)
def make_gmsh(df, **kwargs): logger.info('create grid') model = gmsh.model factory = model.geo gmsh.initialize() model.add("schism") # gmsh.option.setNumber("General.Terminal", 1) interpolate = kwargs.get('interpolate', False) if interpolate: ddf=gset(df,**kwargs) else: ddf=df lc = kwargs.get('lc', .5) ddf['lc'] = lc ddf = ddf.apply(pd.to_numeric) # save boundary configuration for Line0 rb0=ddf.loc['line0'].copy() if not shapely.geometry.LinearRing(rb0[['lon','lat']].values).is_ccw:# check for clockwise orientation rb0=ddf.loc['line0'].iloc[::-1].reset_index(drop=True) rb0.index=rb0.index+1 # fix index rb0['bounds']=[[i,i+1] for i in rb0.index] rb0['bounds']=rb0.bounds.values.tolist()[:-1]+[[rb0.index[-1],1]] # fix last one #store blines blines={} for tag_ in rb0.tag.unique(): ibs=rb0.loc[rb0.tag==tag_].index.values #ibs lbs=rb0.loc[rb0.tag==tag_].bounds.values.tolist() #lbs ai=np.unique(np.concatenate(lbs)) #ai itags=[i for i in ai if i in ibs] #itags if tag_ > 0: items = set(itags) imask=[set(x).issubset(items) for x in rb0.loc[rb0.tag==tag_].bounds] #imask bi=rb0.loc[rb0.tag==tag_][imask].index.values.tolist() else: bi=rb0.loc[rb0.tag==tag_].index.values.tolist() blines.update({tag_:bi}) al = [j for i in list(blines.values()) for j in i] lover=[x for x in rb0.index if x not in al] for i,v in rb0.loc[lover].iterrows(): nns=rb0.loc[v[5],['tag']].values itag=[x for x in nns if x < 0 ][0] blines.update({itag[0]:blines[itag[0]]+[i]}) land_lines = { your_key: blines[your_key] for your_key in [x for x in blines.keys() if x < 0] } open_lines = { your_key: blines[your_key] for your_key in [x for x in blines.keys() if x > 0] } logger.info('Define geometry') loops=[] islands=[] all_lines=[] ltag=1 for row in rb0.itertuples(index=True, name='Pandas'): factory.addPoint(getattr(row, "lon"),getattr(row, "lat"),getattr(row, "z"),getattr(row, "lc"),getattr(row, "Index")) for row in rb0.itertuples(index=True, name='Pandas'): factory.addLine(getattr(row, "bounds")[0],getattr(row, "bounds")[1],getattr(row, "Index")) lines=rb0.index.values all_lines.append(lines) tag=rb0.index.values[-1] factory.addCurveLoop(lines, tag=ltag) #print(loop) loops.append(ltag) all_lines.append(lines) tag += 1 ltag += 1 for contour in tqdm(ddf.index.levels[0][1:]): rb=ddf.loc[contour].copy() if not shapely.geometry.LinearRing(rb[['lon','lat']].values).is_ccw:# check for clockwise orientation rb=ddf.loc[contour].iloc[::-1].reset_index(drop=True) rb.index=rb.index+tag rb['bounds']=[[i,i+1] for i in rb.index] rb['bounds']=rb.bounds.values.tolist()[:-1]+[[rb.index[-1],rb.index[0]]] # fix last one for row in rb.itertuples(index=True, name='Pandas'): factory.addPoint(getattr(row, "lon"),getattr(row, "lat"),getattr(row, "z"),getattr(row, "lc"),getattr(row, "Index")) for row in rb.itertuples(index=True, name='Pandas'): factory.addLine(getattr(row, "bounds")[0],getattr(row, "bounds")[1],getattr(row, "Index")) lines=rb.index.values all_lines.append(lines) tag=rb.index.values[-1]+1 factory.addCurveLoop(lines,tag=ltag) # print(tag) loops.append(ltag) islands.append(lines) all_lines.append(lines) tag += 1 ltag += 1 factory.addPlaneSurface(loops) logger.info('synchronize') factory.synchronize() ## Group open boundaries lines for key,values in open_lines.items(): gmsh.model.addPhysicalGroup(1, values,1000-int(key)) ## Group land boundaries lines for key,values in land_lines.items(): gmsh.model.addPhysicalGroup(1, values,1000-int(key)) ntag=1 for k in tqdm(range(len(islands))): gmsh.model.addPhysicalGroup(1, islands[k], 2000+ntag) ntag += 1 ps = gmsh.model.addPhysicalGroup(2, [1]) gmsh.model.setPhysicalName(2, ps, "MyMesh") flat_list = [item for sublist in all_lines for item in sublist] ols=[j for i in list(open_lines.values()) for j in i] lists = [x for x in flat_list if x not in ols] model.mesh.field.add("Distance", 1) model.mesh.field.setNumbers(1, "CurvesList", lists) SizeMin = kwargs.get("SizeMin",.1) SizeMax = kwargs.get("SizeMax",.5) DistMin = kwargs.get("DistMin",.01) DistMax = kwargs.get("DistMax",.2) model.mesh.field.add("Threshold", 2); model.mesh.field.setNumber(2, "InField", 1); model.mesh.field.setNumber(2, "SizeMin", SizeMin); model.mesh.field.setNumber(2, "SizeMax", SizeMax); model.mesh.field.setNumber(2, "DistMin", DistMin); model.mesh.field.setNumber(2, "DistMax", DistMax); # Set bgmesh bgmesh = kwargs.get('bgmesh', None) if bgmesh == 'auto': try: logger.info('Read DEM') dem = pdem.dem(**kwargs) res_min = kwargs.get('resolution_min',.01) res_max = kwargs.get('resolution_max',.5) logger.info('Evaluate bgmesh') w = make_bgmesh(dem.Dataset,res_min, res_max) path = kwargs.get('rpath','.') if not os.path.exists(path): # check if run folder exists os.makedirs(path) logger.info('Save bgmesh to {}/bgmesh/bgmesh.pos'.format(path)) fpos = path + '/bgmesh/bgmesh.pos' to_sq(w,fpos) # save bgmesh kwargs.update({'bgmesh':fpos}) model.mesh.field.setNumber(2, "StopAtDistMax", 1); # Merge a post-processing view containing the target anisotropic mesh sizes gmsh.merge(fpos) model.mesh.field.add("PostView", 3) model.mesh.field.setNumber(3, "ViewIndex", 0) model.mesh.field.add("Min", 4) model.mesh.field.setNumbers(4, "FieldsList", [2,3]) model.mesh.field.setAsBackgroundMesh(4) except: logger.warning('bgmesh failed... continuing without background mesh size') model.mesh.field.setAsBackgroundMesh(2) else: model.mesh.field.setAsBackgroundMesh(2) gmsh.option.setNumber('Mesh.MeshSizeExtendFromBoundary',0) gmsh.option.setNumber('Mesh.MeshSizeFromPoints',0) gmsh.option.setNumber('Mesh.MeshSizeFromCurvature',0) logger.info('execute') gmsh.model.mesh.generate(2) # ... and save it to disk rpath = kwargs.get('rpath', '.') logger.info('save mesh') # gmsh.option.setNumber("Mesh.SaveAll", 1) gmsh.write(rpath + '/gmsh/mymesh.msh') # gmsh.write('mymesh.vtk') gmsh.finalize()
def createGeometryAndMesh(): # Clear all models and merge an STL mesh that we would like to remesh (from # the parent directory): gmsh.clear() path = os.path.dirname(os.path.abspath(__file__)) gmsh.merge(os.path.join(path, os.pardir, 't13_data.stl')) # We first classify ("color") the surfaces by splitting the original surface # along sharp geometrical features. This will create new discrete surfaces, # curves and points. # Angle between two triangles above which an edge is considered as sharp, # retrieved from the ONELAB database (see below): angle = gmsh.onelab.getNumber('Parameters/Angle for surface detection')[0] # For complex geometries, patches can be too complex, too elongated or too # large to be parametrized; setting the following option will force the # creation of patches that are amenable to reparametrization: forceParametrizablePatches = gmsh.onelab.getNumber( 'Parameters/Create surfaces guaranteed to be parametrizable')[0] # For open surfaces include the boundary edges in the classification # process: includeBoundary = True # Force curves to be split on given angle: curveAngle = 180 gmsh.model.mesh.classifySurfaces(angle * math.pi / 180., includeBoundary, forceParametrizablePatches, curveAngle * math.pi / 180.) # Create a geometry for all the discrete curves and surfaces in the mesh, by # computing a parametrization for each one gmsh.model.mesh.createGeometry() # Note that if a CAD model (e.g. as a STEP file, see `t20.py') is available # instead of an STL mesh, it is usually better to use that CAD model instead # of the geometry created by reparametrizing the mesh. Indeed, CAD # geometries will in general be more accurate, with smoother # parametrizations, and will lead to more efficient and higher quality # meshing. Discrete surface remeshing in Gmsh is optimized to handle dense # STL meshes coming from e.g. imaging systems, where no CAD is available; it # is less well suited for the poor quality STL triangulations (optimized for # size, with e.g. very elongated triangles) that are usually generated by # CAD tools for e.g. 3D printing. # Create a volume from all the surfaces s = gmsh.model.getEntities(2) l = gmsh.model.geo.addSurfaceLoop([s[i][1] for i in range(len(s))]) gmsh.model.geo.addVolume([l]) gmsh.model.geo.synchronize() # We specify element sizes imposed by a size field, just because we can :-) f = gmsh.model.mesh.field.add("MathEval") if gmsh.onelab.getNumber('Parameters/Apply funny mesh size field?')[0]: gmsh.model.mesh.field.setString(f, "F", "2*Sin((x+y)/5) + 3") else: gmsh.model.mesh.field.setString(f, "F", "4") gmsh.model.mesh.field.setAsBackgroundMesh(f) gmsh.model.mesh.generate(3) gmsh.write('t13.msh')
factory.addPoint(-1, -1, 0) factory.addPoint(1, -1, 0) factory.addPoint(1, 1, 0) factory.addPoint(-1, 1, 0) factory.addLine(1, 2, 1) factory.addLine(2, 3, 2) factory.addLine(3, 4, 3) factory.addLine(4, 1, 4) factory.addCurveLoop([1, 2, 3, 4], 1) factory.addPlaneSurface([1], 1) factory.synchronize() # add a post-processing view to use as a size field gmsh.merge("t17.pos") bg_field = model.mesh.field.add("PostView") model.mesh.field.setAsBackgroundMesh(bg_field) # use bamg gmsh.option.setNumber("Mesh.SmoothRatio", 3) gmsh.option.setNumber("Mesh.AnisoMax", 1000) gmsh.option.setNumber("Mesh.Algorithm", 7) gmsh.model.mesh.generate(2) gmsh.write("t17.msh") gmsh.fltk.run() gmsh.finalize()
import gmsh import sys import math gmsh.initialize() gmsh.model.add('Torus') gmsh.merge('C:/Tor.stl') angle = 40 Patch = False Boundary = True curveangle = 180 gmsh.model.mesh.classifySurfaces(angle * math.pi / 180., Patch, Boundary, curveangle * math.pi / 180.) gmsh.model.mesh.createGeometry() s = gmsh.model.getEntities(2) l = gmsh.model.geo.addSurfaceLoop([s[i][1] for i in range(len(s))]) gmsh.model.geo.addVolume([l]) gmsh.model.geo.synchronize() gmsh.model.mesh.generate(3) gmsh.write('Tor.msh') if '-nopopup' not in sys.argv: gmsh.fltk.run() gmsh.finalize()
import gmsh import sys dt = 0.01 gmsh.initialize(sys.argv) gmsh.merge("temp-cylinder.msh") gmsh.option.setNumber("General.TrackballQuaternion0", -0.2152548072727626) gmsh.option.setNumber("General.TrackballQuaternion1", -0.2112165920022461) gmsh.option.setNumber("General.TrackballQuaternion2", -0.01270861835676978) gmsh.option.setNumber("General.TrackballQuaternion3", 0.953357965419278) gmsh.option.setNumber("Mesh.SurfaceEdges", 0) gmsh.option.setNumber("Mesh.VolumeEdges", 0) n_steps = int(gmsh.option.getNumber("View[0].NbTimeStep")) times = [] temps = [] for i in range(n_steps): kind, tags, temp, t, _ = gmsh.view.getModelData(0, i) temps.append(temp) times.append(t) end_time = t temp_inst = [0] * len(temp) view_inst = gmsh.view.add("temp_temp") # as in temperature and temporal t = 0
tic = gmsh.logger.getWallTime() surf = gmsh.model.addDiscreteEntity(2) toc = gmsh.logger.getWallTime() print("==> created surface in {} seconds".format(toc - tic)) tic = gmsh.logger.getWallTime() gmsh.model.mesh.addNodes(2, 1, nodes, coords) toc = gmsh.logger.getWallTime() print("==> imported nodes in {} seconds".format(toc - tic)) tic = gmsh.logger.getWallTime() gmsh.model.mesh.addElementsByType(1, 2, [], tris) toc = gmsh.logger.getWallTime() print("==> imported elements in {} seconds".format(toc - tic)) tic = gmsh.logger.getWallTime() gmsh.option.setNumber("Mesh.Binary", 1) gmsh.write("import_perf.msh") toc = gmsh.logger.getWallTime() print("==> wrote to disk in {} seconds".format(toc - tic)) tic = gmsh.logger.getWallTime() gmsh.merge("import_perf.msh") toc = gmsh.logger.getWallTime() print("==> read from disk in {} seconds".format(toc - tic)) #gmsh.fltk.run() gmsh.finalize()
import gmsh import os gmsh.initialize() path = os.path.dirname(os.path.abspath(__file__)) gmsh.merge(os.path.join(path, 'step_boundary_colors.stp')) for tag in gmsh.model.getEntities(): col = gmsh.model.getColor(*tag) if col != (0, 0, 255, 0): print('entity', tag, 'color', col) gmsh.finalize()
import gmsh import math import os import sys gmsh.initialize() path = os.path.dirname(os.path.abspath(__file__)) gmsh.merge(os.path.join(path, 'poor_cat.stl')) gmsh.model.mesh.classifySurfaces(40 * math.pi / 180., True, False, 180 * math.pi / 180.) s = gmsh.model.getEntities(2) l = gmsh.model.geo.addSurfaceLoop([s[i][1] for i in range(len(s))]) gmsh.model.geo.addVolume([l]) gmsh.model.geo.synchronize() funny = False f = gmsh.model.mesh.field.add("MathEval") if funny: gmsh.model.mesh.field.setString(f, "F", "2*Sin((x+y)/5) + 6") else: gmsh.model.mesh.field.setString(f, "F", "0.7") gmsh.model.mesh.field.setAsBackgroundMesh(f) gmsh.model.mesh.generate(3)
import gmsh import sys dt = 1 gmsh.initialize(sys.argv) gmsh.merge("temp-valve.msh") gmsh.option.setNumber("General.Trackball", 0) gmsh.option.setNumber("General.RotationX", 290) gmsh.option.setNumber("General.RotationY", 2) gmsh.option.setNumber("General.RotationZ", 25) gmsh.option.setNumber("General.ScaleX", 1.3) gmsh.option.setNumber("General.ScaleY", 1.3) gmsh.option.setNumber("General.ScaleZ", 1.3) gmsh.option.setNumber("Mesh.SurfaceEdges", 0) gmsh.option.setNumber("Mesh.VolumeEdges", 0) n_steps = int(gmsh.option.getNumber("View[0].NbTimeStep")) times = [] temps = [] for i in range(n_steps): kind, tags, temp, t, _ = gmsh.view.getModelData(0, i) temps.append(temp) times.append(t) end_time = t temp_inst = [0] * len(temp)
# This file reimplements gmsh/tutorial/t9.geo in Python. # # Post-processing plugins (levelsets, sections, annotations) import gmsh import os model = gmsh.model factory = model.geo gmsh.initialize() gmsh.option.setNumber("General.Terminal", 1) # add a three-dimensional scalar view to work on: path = os.path.dirname(os.path.abspath(__file__)) gmsh.merge(os.path.join(path, '..', 'view3.pos')) # set plugin options plugin = gmsh.plugin # First plugin is Isosurface plugin.setNumber("Isosurface", "Value", 0.67) plugin.setNumber("Isosurface", "View", 0) plugin.run("Isosurface") # Second is CutPlane plugin.setNumber("CutPlane", "A", 0) plugin.setNumber("CutPlane", "B", 0.2) plugin.setNumber("CutPlane", "C", 1) plugin.setNumber("CutPlane", "D", 0)
import gmsh import math import os import sys gmsh.initialize() path = os.path.dirname(os.path.abspath(__file__)) gmsh.merge(os.path.join(path, 'rabbit.stl')) # We first classify ("color") the surfaces by splitting the original surface # along sharp geometrical features. This will create new discrete surfaces, # curves and points. # Angle between two triangles above which an edge is considered as sharp: angle = 40 # For complex geometries, patches can be too complex, too elongated or too large # to be parametrized; setting the following option will force the creation of # patches that are amenable to reparametrization: forceParametrizablePatches = False # For open surfaces include the boundary edges in the classification process: includeBoundary = True # Force curves to be split on given angle: curveAngle = 180 gmsh.model.mesh.classifySurfaces(angle * math.pi / 180., includeBoundary, forceParametrizablePatches, curveAngle * math.pi / 180.)
import gmsh import sys dt = 10 gmsh.initialize(sys.argv) gmsh.merge("temp-square.msh") n_steps = int(gmsh.option.getNumber("View[0].NbTimeStep")) times = [] temps = [] for i in range(n_steps): kind, tags, temp, t, _ = gmsh.view.getModelData(0, i) temps.append(temp) times.append(t) end_time = t temp_inst = [0] * len(temp) view_inst = gmsh.view.add("temp_temp") # as in temperature and temporal t = 0 step = 0 i = 1 while t < end_time: if t > times[i]: while times[i] < t: i += 1 alpha = (t - times[i - 1]) / (times[i] - times[i - 1]) print(t, i, alpha)
# # ------------------------------------------------------------------------------ import gmsh import os import sys # Mesh sizes can be specified very accurately by providing a background mesh, # i.e., a post-processing view that contains the target characteristic lengths. gmsh.initialize() gmsh.option.setNumber("General.Terminal", 1) # Merge a list-based post-processing view containing the target mesh sizes: path = os.path.dirname(os.path.abspath(__file__)) gmsh.merge(os.path.join(path, '..', 't7_bgmesh.pos')) # If the post-processing view was model-based instead of list-based (i.e. if it # was based on an actual mesh), we would need to create a new model to contain # the geometry so that meshing it does not destroy the background mesh. It's not # necessary here since the view is list-based, but it does no harm: gmsh.model.add("t7") # Create a simple rectangular geometry: lc = 1e-2 gmsh.model.geo.addPoint(0, 0, 0, lc, 1) gmsh.model.geo.addPoint(.1, 0, 0, lc, 2) gmsh.model.geo.addPoint(.1, .3, 0, lc, 3) gmsh.model.geo.addPoint(0, .3, 0, lc, 4) gmsh.model.geo.addLine(1, 2, 1) gmsh.model.geo.addLine(3, 2, 2)
import gmsh import math import os import sys gmsh.initialize(sys.argv) path = os.path.dirname(os.path.abspath(__file__)) # load an STL surface gmsh.merge(os.path.join(path, 'terrain_stl_data.stl')) # classify the surface mesh according to given angle, and create discrete model # entities (surfaces, curves and points) accordingly; curveAngle forces bounding # curves to be split on sharp corners gmsh.model.mesh.classifySurfaces(math.pi, curveAngle=math.pi / 3) # create a geometry for the discrete curves and surfaces gmsh.model.mesh.createGeometry() # retrieve the surface, its boundary curves and corner points s = gmsh.model.getEntities(2) c = gmsh.model.getBoundary(s) if (len(c) != 4): gmsh.logger.write('Should have 4 boundary curves!', level='error') z = -1000 p = [] xyz = []
"""Ford nuclear reactor.""" import math import gmsh import mocmg import mocmg.mesh import mocmg.model lc = 5.0 N = 10 gmsh.initialize() mocmg.initialize() gmsh.merge("xsec.step") # rotate dim_tags = gmsh.model.getEntities(2) gmsh.model.occ.rotate(dim_tags, 0, 1, 0, 0, 1, 0, -math.pi / 2) gmsh.model.occ.translate(dim_tags, 37.3225 - 0.0099 + 1, 44.09 - 0.00174209 + 1, -436.5625) gmsh.model.occ.synchronize() # gmsh.fltk.run() fuel_tags = [ 20, 10, 5, 32, 38, 6, 15, 27, 31, 11, 12, 13, 33, 4, 36, 9, 25, 21 ] clad_tags = [t[1] for t in dim_tags] for t in fuel_tags: if t in clad_tags: clad_tags.remove(t)
import gmsh gmsh.initialize() gmsh.option.setNumber("General.Terminal", 1) gmsh.merge('step_boundary_colors.stp') for tag in gmsh.model.getEntities(): col = gmsh.model.getColor(*tag) if col != (0, 0, 255, 0): print('entity', tag, 'color', col)
# Создаём снапшот в файле с заданным именем writer = vtk.vtkXMLUnstructuredGridWriter() writer.SetInputDataObject(unstructuredGrid) writer.SetFileName("tetr3d-step-" + str(snap_number) + ".vtu") writer.Write() # Теперь придётся немного упороться: # (а) построением сетки средствами gmsh, # (б) извлечением данных этой сетки в свой код. gmsh.initialize() # Считаем STL try: path = os.path.dirname(os.path.abspath(__file__)) gmsh.merge(os.path.join(path, 't13_data.stl')) except: print("Could not load STL mesh: bye!") gmsh.finalize() exit(-1) # Восстановим геометрию angle = 40 forceParametrizablePatches = False includeBoundary = True curveAngle = 180 gmsh.model.mesh.classifySurfaces(angle * math.pi / 180., includeBoundary, forceParametrizablePatches, curveAngle * math.pi / 180.) gmsh.model.mesh.createGeometry() # Зададим объём по считанной поверхности s = gmsh.model.getEntities(2)
# Gmsh Python tutorial 13 # # Remeshing an STL file without an underlying CAD model # # ------------------------------------------------------------------------------ import gmsh import math import os import sys gmsh.initialize() path = os.path.dirname(os.path.abspath(__file__)) gmsh.merge(os.path.join(path, 'moth.stl')) angle = 30 forceParametrizablePatches = False includeBoundary = True curveAngle = 180 gmsh.model.mesh.classifySurfaces(angle * math.pi / 180., includeBoundary, forceParametrizablePatches, curveAngle * math.pi / 180.) gmsh.model.mesh.createGeometry()