The Gmsh API Cookbook
This is a collection of short examples to get you started with the Gmsh API.
Geometry
Recipe | Concepts |
---|---|
Embed a point in a curve | Boolean operations, OpenCASCADE |
Mesh
Recipe | Concepts |
---|---|
Create a mesh of connected line segments | Creating mesh elements by hand |
Post processing
Recipe | Concepts |
---|---|
Get the list of view names | Inspecting Gmsh state, options interface |
Gmsh is copyright (C) Christophe Geuzaine and Jean-François Remacle
Geometry
Recipe | Concepts |
---|---|
Embed a point in a curve | Boolean operations, OpenCASCADE |
Embed a point in a curve
Gmsh supports embedding arbitrary points in surfaces and volumes, but not for curves.
We can provide this feature ourselves by segmenting the curve at the given point.
This requires the OpenCASCADE
kernel.
Python
import gmsh
def pointInCurve(point_tag, curve_tag):
return gmsh.model.occ.fragment([(0, point_tag)], [(1, curve_tag)])[0]
gmsh.initialize()
a = gmsh.model.occ.addPoint(0, 0, 0)
b = gmsh.model.occ.addPoint(5, 0, 0)
line = gmsh.model.occ.addLine(a, b)
# the point we want to embed
p = gmsh.model.occ.addPoint(1, 0, 0)
# embed it
result_tags = pointInCurve(p, line)
# find the new point tag
embedded_point = next(tag for (dim, tag) in result_tags if dim == 0)
# add a physical group for the new point
gmsh.model.occ.synchronize()
group = gmsh.model.addPhysicalGroup(0, [embedded_point])
gmsh.model.setPhysicalName(0, group, "embedded point")
gmsh.finalize()
Mesh
Recipe | Concepts |
---|---|
Create a mesh of connected line segments | Creating mesh elements by hand |
Line segments
Gmsh does not have a line segment primitive, but we can make our own by adding 1D mesh elements one by one.
Python
import gmsh
import itertools
# points to connect
points = [(-1, 0, 0), (1, 1, 0), (-1, 2, 0), (1, 3, 0), (-1, 4, 0)]
# assign node numbers
nodes = [x for x in range(1, len(points)+1)]
# get a flat list of coordinates
coords = list(itertools.chain.from_iterable(points))
gmsh.initialize()
# add a dummy line to add nodes to
dummy_line = 1
gmsh.model.addDiscreteEntity(1, dummy_line)
# add nodes
gmsh.model.mesh.addNodes(1, dummy_line, nodes, coords)
# add line elements between each node
line_elt = 1
for i in range(len(nodes) - 1):
gmsh.model.mesh.addElementsByType(
dummy_line, line_elt, [], [nodes[i], nodes[i+1]])
gmsh.finalize()
Post processing
Recipe | Concepts |
---|---|
Get the list of view names | Inspecting Gmsh state, options interface |
List of view names
A lot of Gmsh state is available through the options
interface. We use this feature to get a list of all the view names.
Python
import gmsh
def getViewNames(view_tags):
return [gmsh.option.getString(f'View[{gmsh.view.getIndex(tag)}].Name')
for tag in view_tags]
gmsh.initialize()
gmsh.view.add("view 1")
gmsh.view.add("view 2")
gmsh.view.add("view 3")
for name in getViewNames(gmsh.view.getTags()):
print(name)
gmsh.finalize()