Mesh — g.mesh¶
Meshing composite. Seven focused sub-composites.
g.mesh¶
apeGmsh.mesh.Mesh.Mesh ¶
Bases: _HasLogging
Thin composition container for meshing. Every action lives in a focused sub-composite — see the module docstring for the full map.
Parameters¶
parent : _SessionBase
Owning session — used to read _verbose and access the
physical composite during _by_physical helpers.
Source code in src/apeGmsh/mesh/Mesh.py
viewer ¶
Open the interactive mesh viewer.
The viewer supports picking (BRep entities, elements, nodes), color modes, and load/constraint/mass overlays.
Parameters are forwarded to :class:MeshViewer.
Source code in src/apeGmsh/mesh/Mesh.py
render ¶
render(path: 'str | Path', *, camera: str = 'iso', window_size: tuple[int, int] = (1280, 720)) -> 'Path | None'
Write one offscreen undeformed mesh still (ADR 0094 S4).
Live session only. Uses build_mesh_scene (the same live
Gmsh scene as :meth:viewer), not get_fem_data +
build_fem_scene. VTK offscreen — no Qt window, no event
loop.
Returns the written :class:~pathlib.Path, or None (and
prints the [skip viewer] notice) under
APEGMSH_SKIP_VIEWER=1 or with no GL. Raises
RuntimeError on a from_h5 / closed session, or when
no mesh has been generated. Snapshot stills stay on
fem.render.
Source code in src/apeGmsh/mesh/Mesh.py
Sub-composites¶
g.mesh.generation¶
apeGmsh.mesh._mesh_generation._Generation ¶
Mesh generation, high-order elevation, refinement, optimisation, and algorithm selection.
Source code in src/apeGmsh/mesh/_mesh_generation.py
generate ¶
Generate a mesh up to the given dimension.
Parameters¶
dim : 1 = edges only, 2 = surface mesh, 3 = volume mesh (default)
Source code in src/apeGmsh/mesh/_mesh_generation.py
set_order ¶
Elevate elements to high order.
Parameters¶
order : 1 = linear, 2 = quadratic, 3 = cubic, … bubble : include interior (bubble) nodes for order ≥ 2. True → complete Lagrange (e.g. Q9, T6+bubble). False → serendipity / incomplete (e.g. Q8, T6). Global Gmsh flag — applies to the entire mesh.
Source code in src/apeGmsh/mesh/_mesh_generation.py
refine ¶
Uniformly refine by splitting every element once.
Source code in src/apeGmsh/mesh/_mesh_generation.py
optimize ¶
optimize(method: str = '', *, force: bool = False, niter: int = 1, dim_tags: list[tuple[int, int]] | None = None) -> '_Generation'
Optimise mesh quality.
Parameters¶
method : one of OptimizeMethod.* constants
force : apply optimisation even to already-valid elements
niter : number of passes
dim_tags : limit to specific entities (None = all)
Example¶
::
g.mesh.generation.generate(3).optimize(OptimizeMethod.NETGEN, niter=5)
Source code in src/apeGmsh/mesh/_mesh_generation.py
set_algorithm ¶
Choose the meshing algorithm for a surface (dim=2) or globally for all volumes (dim=3).
tag accepts int, label, or PG name. If it resolves to
multiple surfaces, the algorithm is applied to each.
Example¶
::
g.mesh.generation.set_algorithm("col.web", "frontal_delaunay_quads")
g.mesh.generation.set_algorithm(0, "hxt", dim=3)
Source code in src/apeGmsh/mesh/_mesh_generation.py
set_algorithm_by_physical ¶
Deprecated. set_algorithm accepts a PG name directly.
With dim=3 the original wrapper passed tag=0 (since
Mesh.Algorithm3D is a global option); preserve that here.
Source code in src/apeGmsh/mesh/_mesh_generation.py
g.mesh.sizing¶
apeGmsh.mesh._mesh_sizing._Sizing ¶
Global and per-entity element size control.
Source code in src/apeGmsh/mesh/_mesh_sizing.py
set_global_size ¶
Set the global element-size band.
Parameters¶
max_size : upper bound assigned to Mesh.MeshSizeMax. Acts
as a ceiling on every size source.
min_size : lower bound assigned to Mesh.MeshSizeMin.
Defaults to 0.0 — i.e. no floor, so per-point
refinements (set_size(..., 100)) are free to
produce elements smaller than max_size.
Example¶
::
m1.mesh.sizing.set_global_size(6000) # ceiling only
m1.mesh.sizing.set_global_size(6000, 200) # band [200, 6000]
Source code in src/apeGmsh/mesh/_mesh_sizing.py
set_size_sources ¶
set_size_sources(*, from_points: bool | None = None, from_curvature: bool | None = None, extend_from_boundary: bool | None = None) -> '_Sizing'
Control which size sources Gmsh consults when meshing.
Gmsh combines several size sources at each node and takes the
minimum. When from_points is on (Gmsh default), every
BRep point carries its own characteristic length — imported
CAD files typically bake in small lc values that silently
override :meth:set_global_size.
Example¶
::
(g.mesh.sizing
.set_size_sources(from_points=False,
from_curvature=False,
extend_from_boundary=False)
.set_global_size(6000))
Source code in src/apeGmsh/mesh/_mesh_sizing.py
set_size_global ¶
Set the global mesh-size bounds independently.
Example¶
::
g.mesh.sizing.set_size_global(min_size=15, max_size=25)
g.mesh.sizing.set_size_global(max_size=50)
Source code in src/apeGmsh/mesh/_mesh_sizing.py
set_size ¶
Assign a target element size by walking to the entity's points.
Gmsh's setSize only honours characteristic lengths on
points (dim=0). This method accepts any reference shape and
recursively walks higher-dimensional entities down to their
BRep points before applying the size — so passing a volume
label, surface PG, or (3, vol_tag) dimtag does what you
expect.
Parameters¶
tags : int, str, (dim, tag), or list of those
Entity reference. Strings resolve via labels first, then
physical groups, at the entity's native dimension.
size : float
Target characteristic length on the resolved points.
dim : int, optional
Disambiguation hint. Used only when the input is a raw
int tag or when a label exists at multiple dimensions.
Leave as None (default) for label/PG/dimtag inputs.
Example¶
::
# Per-volume sizing by label (auto-walks to corner points)
g.mesh.sizing.set_size("box", 1.0)
g.mesh.sizing.set_size("box_2", 0.3)
# Direct point list still works
g.mesh.sizing.set_size([p1, p2, p3], 0.05)
# Dimtag form for an explicit volume
g.mesh.sizing.set_size([(3, vol_tag)], 10.0)
Source code in src/apeGmsh/mesh/_mesh_sizing.py
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
set_size_all_points ¶
Assign the same characteristic length to every BRep point in the model.
Typical use — normalising per-point lc values after an
IGES/STEP/DXF import.
Example¶
::
(g.mesh.sizing
.set_size_all_points(6000)
.set_global_size(6000))
Source code in src/apeGmsh/mesh/_mesh_sizing.py
set_size_callback ¶
Register a Python callback that returns the desired element size at any point in the model.
Callback signature func(dim, tag, x, y, z, lc) -> float.
Source code in src/apeGmsh/mesh/_mesh_sizing.py
set_size_by_physical ¶
Apply :meth:set_size to every entity in a physical group.
Resolves the PG (optionally restricted to dim), then
delegates to :meth:set_size, which walks higher-dimensional
entities down to their boundary points automatically.
Parameters¶
name : physical-group name.
size : target characteristic length.
dim : optional dimension filter; None resolves at the
PG's native dim.
Source code in src/apeGmsh/mesh/_mesh_sizing.py
g.mesh.field¶
apeGmsh.mesh._mesh_field.FieldHelper ¶
Fluent wrapper around gmsh.model.mesh.field.
Accessed via g.mesh.field. Two usage levels:
Raw control (full flexibility)::
f = g.mesh.field.add("Distance")
g.mesh.field.set_numbers(f, "CurvesList", [1, 2, 3])
g.mesh.field.set_background(f)
Convenience builders (common fields with named parameters)::
dist = g.mesh.field.distance(curves=[1, 2])
thr = g.mesh.field.threshold(dist, size_min=0.05, size_max=0.5,
dist_min=0.1, dist_max=1.0)
g.mesh.field.set_background(thr)
Source code in src/apeGmsh/mesh/_mesh_field.py
add ¶
Create a new field of the given type and return its tag.
Source code in src/apeGmsh/mesh/_mesh_field.py
set_number ¶
set_numbers ¶
set_string ¶
set_background ¶
Register a field as the global background mesh size.
Source code in src/apeGmsh/mesh/_mesh_field.py
set_boundary_layer_field ¶
Register a BoundaryLayer field to be applied during meshing.
Source code in src/apeGmsh/mesh/_mesh_field.py
distance ¶
Create a Distance field measuring shortest distance to entities.
Each of curves, surfaces, points accepts an int, a
label or PG name, a (dim, tag) tuple, or a list of any mix.
Refs are validated against the expected dimension.
Source code in src/apeGmsh/mesh/_mesh_field.py
threshold ¶
threshold(distance_field: int, *, size_min: float, size_max: float, dist_min: float, dist_max: float, sigmoid: bool = False, stop_at_dist_max: bool = False) -> int
Create a Threshold field ramping size from size_min to size_max.
Source code in src/apeGmsh/mesh/_mesh_field.py
math_eval ¶
Create a MathEval field using an expression in x, y, z.
Source code in src/apeGmsh/mesh/_mesh_field.py
box ¶
box(*, x_min: float, y_min: float, z_min: float, x_max: float, y_max: float, z_max: float, size_in: float, size_out: float, thickness: float = 0.0) -> int
Create a Box field: size_in inside, size_out outside.
Source code in src/apeGmsh/mesh/_mesh_field.py
minimum ¶
Create a Min field — element-wise minimum of several fields.
Source code in src/apeGmsh/mesh/_mesh_field.py
boundary_layer ¶
boundary_layer(*, curves=None, points=None, size_near: float, ratio: float = 1.2, n_layers: int = 5, thickness: float | None = None, fan_points=None) -> int
Create a BoundaryLayer field for wall-resolved meshes.
curves, points, and fan_points accept any flexible
reference shape (int / label / PG / (dim, tag) / list).
Source code in src/apeGmsh/mesh/_mesh_field.py
g.mesh.options¶
apeGmsh.mesh._mesh_options._Options ¶
Global Gmsh mesher options.
Each set_* method maps to one gmsh.option.setNumber("Mesh.X", v)
call but adds string-enum input, validation, and logging. Methods
return self for chaining.
Source code in src/apeGmsh/mesh/_mesh_options.py
set_subdivision_algorithm ¶
Post-process tets/prisms into hexes after generation.
Maps to Mesh.SubdivisionAlgorithm.
Parameters¶
algorithm : str or int One of:
- ``"none"`` (0) no subdivision (default)
- ``"all_quad"`` (1) split tris into 3 quads each
- ``"all_hex"`` (2) split tets/prisms into hexes
Notes¶
Redundant for transfinite + face-recombined volumes — those produce hexes natively via the structured mesher. This option is for the unstructured-tet → hex conversion path.
Example¶
::
g.mesh.options.set_subdivision_algorithm("all_hex")
Source code in src/apeGmsh/mesh/_mesh_options.py
get_subdivision_algorithm ¶
Return the current Mesh.SubdivisionAlgorithm as a string or int.
set_smoothing ¶
Number of global Laplacian smoothing passes applied after generation.
Maps to Mesh.Smoothing.
Parameters¶
iterations : int
Number of smoothing passes. 0 disables. Higher values
improve element quality on unstructured meshes; on
transfinite meshes the option is effectively a no-op since
interior nodes are already on the structured grid.
See Also¶
g.mesh.structured.set_smoothing :
Per-entity smoothing constraint (different — sets
gmsh.model.mesh.setSmoothing on a specific tag).
Source code in src/apeGmsh/mesh/_mesh_options.py
get_smoothing ¶
set_element_order ¶
Element interpolation order.
Maps to Mesh.ElementOrder.
Parameters¶
order : int
1 for linear elements (default), 2 for quadratic,
higher orders supported but rarely used. Higher-order
meshes have additional mid-edge / mid-face nodes; downstream
FEM code must support the element type.
Example¶
::
g.mesh.options.set_element_order(2) # quadratic hexes/tets
Source code in src/apeGmsh/mesh/_mesh_options.py
get_element_order ¶
set_algorithm_2d ¶
2-D meshing algorithm.
Maps to Mesh.Algorithm.
Parameters¶
algorithm : str or int One of:
- ``"meshadapt"`` (1) adaptive Delaunay
- ``"automatic"`` (2) default — let Gmsh choose
- ``"delaunay"`` (5) pure Delaunay
- ``"frontal"`` (6) frontal-Delaunay
- ``"bamg"`` (7) anisotropic remeshing
- ``"frontal_quads"`` (8) frontal-Delaunay for quads
- ``"packing"`` (9) packing of parallelograms
- ``"quasi_structured_quad"`` (11) quasi-structured quads
(Gmsh ≥ 4.10)
Source code in src/apeGmsh/mesh/_mesh_options.py
get_algorithm_2d ¶
Return the current Mesh.Algorithm as a string or int.
set_algorithm_3d ¶
3-D meshing algorithm.
Maps to Mesh.Algorithm3D.
Parameters¶
algorithm : str or int One of:
- ``"delaunay"`` (1) pure Delaunay (default)
- ``"frontal"`` (4) frontal
- ``"frontal_delaunay"`` (5) frontal-Delaunay
- ``"mmg3d"`` (7) anisotropic remeshing
- ``"rtree"`` (9) R-tree based
- ``"hxt"`` (10) HXT — much faster than Delaunay
on large unstructured tet meshes
Source code in src/apeGmsh/mesh/_mesh_options.py
get_algorithm_3d ¶
Return the current Mesh.Algorithm3D as a string or int.
set_recombination_algorithm ¶
Strategy used when recombining triangles into quads.
Maps to Mesh.RecombinationAlgorithm.
Parameters¶
algorithm : str or int One of:
- ``"simple"`` (0) simple
- ``"blossom"`` (1) Blossom — better quality, default
- ``"simple_full"`` (2) simple, full recombination
- ``"blossom_full"`` (3) Blossom, full recombination —
highest quality for all-quad meshes
Source code in src/apeGmsh/mesh/_mesh_options.py
get_recombination_algorithm ¶
Return the current Mesh.RecombinationAlgorithm as a string or int.
Source code in src/apeGmsh/mesh/_mesh_options.py
Common recipes¶
# All-hex output for an unstructured tet model
g.mesh.options.set_subdivision_algorithm("all_hex")
# Quadratic elements (8-node hex → 27-node hex, 4-node tet → 10-node tet)
g.mesh.options.set_element_order(2)
# HXT algorithm — much faster than Delaunay for large unstructured tet meshes
g.mesh.options.set_algorithm_3d("hxt")
# Highest-quality all-quad surface mesh
g.mesh.options.set_recombination_algorithm("blossom_full")
g.mesh.options.set_algorithm_2d("frontal_quads")
# Fluent chaining — every setter returns self
(g.mesh.options
.set_algorithm_3d("hxt")
.set_element_order(2)
.set_smoothing(iterations=3))
For options not wrapped here, drop to gmsh.option.setNumber("Mesh.X", v)
directly. The wrapper covers the ~6 options users actually tune; Gmsh has
~50+ Mesh.* options total.
g.mesh.structured¶
apeGmsh.mesh._mesh_structured._Structured ¶
Transfinite constraints, recombination, smoothing, compounds.
Source code in src/apeGmsh/mesh/_mesh_structured.py
set_transfinite_curve ¶
set_transfinite_curve(tag, n_nodes: int, *, mesh_type: str = 'Progression', coef: float = 1.0) -> '_Structured'
Force a curve to be meshed with a deterministic node count and distribution.
A "transfinite" curve has its nodes placed by formula rather than by the unstructured mesher. This is the building block for structured meshes: when every bounding curve of a surface is transfinite, the surface itself can be made transfinite (a structured grid); same for volumes built from transfinite surfaces.
Parameters¶
tag :
Curve identifier. Accepts an int tag, a label string, a
physical-group name, a (1, tag) dimtag, or a list of any
of these (constraint applied to each). Works with
:meth:Selection.tags() <apeGmsh.core._selection.Selection.tags>
output.
n_nodes : int
Number of nodes along the curve (≥ 2). n_nodes - 1
elements are produced.
mesh_type : str, default "Progression"
Node distribution rule. One of:
- ``"Progression"`` — geometric progression. ``coef`` is
the ratio between successive intervals.
``coef = 1`` ⇒ uniform; ``coef > 1`` clusters nodes
toward the curve's end point; ``coef < 1`` clusters
toward the start.
- ``"Bump"`` — symmetric biasing. ``coef > 1`` clusters
toward the middle; ``coef < 1`` clusters toward both
ends; ``coef = 1`` ⇒ uniform.
- ``"Beta"`` — Beta-distribution biasing (Gmsh ≥ 4.10).
coef : float, default 1.0
Distribution parameter — meaning depends on mesh_type
(see above). Use 1.0 for a uniform distribution.
Returns¶
_Structured
self for chaining.
Notes¶
The constraint is only honored if the curve is part of a transfinite surface (and the surface part of a transfinite volume, for 3-D meshes). A transfinite curve in isolation will simply seed the unstructured mesher with that node count.
Curve direction matters for non-uniform distributions: which
end is "start" vs "end" follows the curve's intrinsic orientation
in Gmsh. Reverse the orientation (or pass coef = 1/r instead
of r) to flip the clustering.
Examples¶
Uniform 11-node spacing on a single curve::
m.mesh.structured.set_transfinite_curve(curve_tag, n_nodes=11)
Geometric refinement toward the curve's end (boundary-layer style)::
m.mesh.structured.set_transfinite_curve(
curve_tag, n_nodes=21,
mesh_type="Progression", coef=1.1,
)
Symmetric refinement toward the middle (capture a feature at mid-span)::
m.mesh.structured.set_transfinite_curve(
curve_tag, n_nodes=21,
mesh_type="Bump", coef=0.25,
)
Pass a Selection's tags to constrain many curves at once::
edges = m.model.select(None, dim=1).result()
m.mesh.structured.set_transfinite_curve(
edges.parallel_to("z").tags(),
n_nodes=21,
)
Source code in src/apeGmsh/mesh/_mesh_structured.py
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | |
one_element_per_curve ¶
Mesh each free curve as exactly one 1-D element (two nodes).
The one-element-per-member switch for trusses and frames: each
selected curve gets set_transfinite_curve(curve, n_nodes=2),
so its only mesh nodes are its two end points.
Parameters¶
*labels : str
Label, physical-group or part names (the precedence of
:func:~apeGmsh.core._helpers.resolve_to_dimtags). Every
curve under each name is selected; entities of other
dimensions under the same name are ignored. With no
labels, every free curve in the model (see below) is
selected, so no surface edge and no referenced curve is
constrained.
Returns¶
_Structured
self for chaining.
Raises¶
KeyError A name is not a label, physical group or part (the message lists the existing labels and groups). ValueError A name resolves to no curve; a named curve bounds or is embedded in a surface, or is tied into a host (the message names the surface or the definition); a definition's references cannot be enumerated; or, with no labels, the model has no free curve.
Warns¶
CurvesSkippedWarning
The no-argument form skipped curves that a definition
references.
TypeError
A name is not a str.
Notes¶
A curve is free when nothing else depends on its mesh:
- it bounds no surface (
gmsh.model.getAdjacencies); - it is embedded in no surface or volume
(
g.mesh.editing.embed, read back withgmsh.model.mesh.getEmbedded); - no definition references it, in any role, in any store of any
declaration composite on the session (
g.constraints,g.embed,g.reinforce,g.rebar,g.displacements, and any composite added later; loads, masses and decoupled nodes are not read, since they tie no node to another). Gmsh does not know these definitions, so they are read field by field, without a list of known classes. A definition whose references cannot be enumerated is refused rather than ignored.
All three are known before meshing. The helper constrains no surface edge; it does not promise an identical surface mesh, since gmsh's meshing order can still shift a count slightly.
The no-argument form skips every curve that is not free. When
it skips one because a definition references it, it emits a
:class:CurvesSkippedWarning naming each such curve and the
definition; it is silent otherwise.
By name, a curve is refused when it bounds a surface, is
embedded in one, or is referenced by a definition that also
references a surface or volume, i.e. ties it into a host
(embedded, reinforce, tie, tied contact). Two nodes there would
rewrite that surface's mesh, or tie a rebar to its host at two
points only. A curve referenced only by a node-level definition
(a BC, a diaphragm over beam lines) is allowed by name. To
coarsen a refused curve anyway, say so explicitly with
set_transfinite_curve(curve, n_nodes=2).
The by-name refusal applies to ties into a surface or volume
host. A curve tied only to another curve (for example
g.constraints.embedded('bm', 'stiff') or a tie between
two curves) is accepted by name and coarsened; the no-argument
form warns with :class:CurvesSkippedWarning and skips it.
Order: the definitions are read when the helper is called, so call it after every tie is declared. A tie declared later does not undo the two-node constraint already set.
Examples¶
One element per bar of a truss::
g.mesh.structured.one_element_per_curve("chords", "diagonals")
Every free frame member of a frame-plus-slab model::
g.mesh.structured.one_element_per_curve()
Source code in src/apeGmsh/mesh/_mesh_structured.py
333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 | |
set_transfinite_surface ¶
set_transfinite_surface(tag, *, arrangement: str = 'Left', corners: list[int] | None = None) -> '_Structured'
Force a surface to be meshed as a structured grid.
A transfinite surface has its interior nodes laid out by transfinite
interpolation between its bounding curves. Combined with transfinite
curves on every bounding edge, this produces a fully structured
surface mesh (triangles by default, quads with
:meth:set_recombine).
Parameters¶
tag :
Surface identifier. Accepts an int tag, label string,
physical-group name, (2, tag) dimtag, or list of any.
arrangement : str, default "Left"
Diagonal direction for the structured triangles. Ignored
once the surface is recombined to quads. Values:
- ``"Left"`` all diagonals slant the same way
- ``"Right"`` all diagonals slant the other way
- ``"AlternateLeft"`` alternating pattern, starting Left
- ``"AlternateRight"`` alternating pattern, starting Right
corners : list[int] | None, default None
Tags of the 3 or 4 corner points defining the structured
topology. Required when the surface has more than 4
bounding curves (e.g. after a face split) or when Gmsh
can't auto-detect the corners. Pass None for a clean
3- or 4-sided face.
Returns¶
_Structured
self for chaining.
Prerequisites¶
Every bounding curve of the surface must already be transfinite
(see :meth:set_transfinite_curve). Opposite edges must have
matching n_nodes (or the mesher will fail at generation time
with a "transfinite surface: inconsistent number of nodes" error).
Examples¶
Clean rectangle::
m.mesh.structured.set_transfinite_surface(face_tag)
Surface with 5+ bounding curves — pick the 4 logical corners::
m.mesh.structured.set_transfinite_surface(
face_tag, corners=[p1, p2, p3, p4],
)
Apply to every horizontal face of a layer::
faces = m.model.select("layer_1", dim=2).result()
m.mesh.structured.set_transfinite_surface(
faces.normal_along("z").tags(),
)
Notes¶
For a quad/hex mesh, follow with :meth:set_recombine on the
same surface. The all-in-one helper :meth:set_transfinite_box
does this automatically for clean hex volumes.
Source code in src/apeGmsh/mesh/_mesh_structured.py
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 | |
set_transfinite_volume ¶
Force a volume to be meshed as a structured grid.
A transfinite volume has its interior nodes laid out by transfinite
interpolation between its bounding surfaces. Combined with
:meth:set_recombine on each face, this produces a pure hex mesh.
Parameters¶
tag :
Volume identifier. Accepts an int tag, label string,
physical-group name, (3, tag) dimtag, or list of any.
corners : list[int] | None, default None
Tags of the 6 (prism) or 8 (hex) corner points that define
the structured topology. Required when the volume has
irregular face counts or when Gmsh can't auto-detect the
corners. Pass None for a clean 5- or 6-faced volume.
Returns¶
_Structured
self for chaining.
Prerequisites¶
- Every bounding surface must already be transfinite
(:meth:
set_transfinite_surface). - Opposite surfaces must have matching node counts on their shared edges.
Examples¶
Single hex (after edges and faces are already transfinite)::
m.mesh.structured.set_transfinite_volume(vol_tag)
Notes¶
For the common case of "transfinite + recombine + hex on every
face of a clean box," use :meth:set_transfinite_box instead —
it sets the constraints on edges, faces, and volume in one call.
Source code in src/apeGmsh/mesh/_mesh_structured.py
set_transfinite_automatic ¶
set_transfinite_automatic(dim_tags: list[DimTag] | None = None, *, corner_angle: float = 2.35, recombine: bool = True) -> '_Structured'
Auto-detect transfinite-compatible entities and constrain them.
Walks each surface and volume in dim_tags (or the entire model
if None). A face counts as "transfinite-compatible" if it
has 3 or 4 corners whose angles are within corner_angle of a
flat angle (π radians). Compatible faces and the volumes built
from them get transfinite + (optionally) recombine constraints
applied automatically.
Useful as a fallback after boolean operations leave you with a
mix of clean and split faces — :meth:set_transfinite_box
would fail on the split faces, but automatic simply skips
them.
Parameters¶
dim_tags : list[(dim, tag)] | None, default None
Restrict the search to these entities. None ⇒ walk
every entity in the model.
corner_angle : float, default 2.35
Threshold angle in radians for the "is this a corner?"
test. The default ≈ 135° is Gmsh's own — vertices whose
interior angle deviates from π (180°) by less than this
tolerance are not counted as corners. Reduce for stricter
corner detection; raise to admit more rounded transitions.
recombine : bool, default True
Recombine detected faces into quads (and volumes into hexes).
Set False for a transfinite tet mesh.
Returns¶
_Structured
self for chaining.
Examples¶
Mesh-everything-it-can fallback after a boolean op::
m.model.boolean.fragment("box_a", "box_b")
m.mesh.structured.set_transfinite_automatic()
m.mesh.generation.generate(dim=3)
Restrict to a subset (only the volumes you care about)::
m.mesh.structured.set_transfinite_automatic(
dim_tags=[(3, t) for t in vol_tags],
)
Source code in src/apeGmsh/mesh/_mesh_structured.py
set_transfinite_box ¶
set_transfinite_box(vol, *, size: float | None = None, n: int | None = None, recombine: bool = True) -> '_Structured'
Apply transfinite + recombine constraints to a clean hex volume.
Captures the full "structured hex" setup in one call. Walks the
volume's bounding curves, assigns a node count per edge, marks
every bounding surface as transfinite (and recombined to quads
when recombine=True), then marks the volume itself as
transfinite.
Parameters¶
vol :
Volume identifier. Accepts an int tag, a label string, a
physical-group name, or a (3, tag) dimtag. If it
resolves to multiple volumes, all are constrained.
size : float, optional
Target element edge length. Node count per edge is
round(edge_length / size) + 1 (clamped to a minimum
of 2 nodes). Provides isotropic sizing — each edge gets
its own n_nodes based on its length.
n : int, optional
Uniform node count on every edge of the volume.
Overrides per-edge length-based sizing.
recombine : bool, default True
Recombine each face to quads (gives a hex mesh). Set
False for a transfinite tet mesh.
Returns¶
_Structured
self for chaining.
Raises¶
ValueError
If neither size nor n is given, or both are.
Requirements¶
The volume must be hex-decomposable: exactly 5 or 6 faces,
each a 3- or 4-sided patch. After :meth:boolean.fragment
operations, volumes may end up with split faces and stop being
transfinite-compatible — in that case use
:meth:set_transfinite_automatic instead, which silently
skips incompatible faces.
Examples¶
Uniform mesh — same n per edge regardless of edge length::
m.mesh.structured.set_transfinite_box("box", n=11)
Length-based sizing — denser mesh on longer edges::
m.mesh.structured.set_transfinite_box("box", size=0.5)
Per-axis control — use the lower-level methods instead::
edges = m.model.select(None, dim=1).result()
m.mesh.structured.set_transfinite_curve(
edges.parallel_to("x").tags(), n_nodes=11)
m.mesh.structured.set_transfinite_curve(
edges.parallel_to("y").tags(), n_nodes=11)
m.mesh.structured.set_transfinite_curve(
edges.parallel_to("z").tags(), n_nodes=21)
# then surfaces + volume via set_transfinite_box(recombine=...)
Source code in src/apeGmsh/mesh/_mesh_structured.py
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 | |
build_graded_box ¶
build_graded_box(*, extent: tuple[float, float, float], footprint: tuple[float, float], h: float, l_mech: float, d_mech: float, r: float, orientation: float = 0.0) -> list[int]
Build a soil box with a uniform mechanism block and graded far field.
One call for the footing-on-soil discretisation of PM-01 D14:
a uniform block at cell size h around the footprint, a
geometric growth ratio r per cell from there to the
boundary, and the footprint edges guaranteed to be mesh
lines so the footing width is exact.
Unlike the other structured verbs this one creates the
geometry — a 3×3×2 arrangement of boxes, fragmented conformal
— because a single box cannot carry a uniform interior and a
graded exterior on one transfinite curve. It then combines
:meth:set_transfinite_curve (uniform inside the block,
Progression outside), :meth:set_transfinite_surface,
:meth:set_recombine and :meth:set_transfinite_volume over
the 18 sub-volumes. It does not call generate().
The box is centred on the origin in plan and hangs below it:
x ∈ [-bx/2, bx/2], y ∈ [-ly/2, ly/2], z ∈ [-hz, 0],
with the footprint centred at the origin on the z = 0 face.
Parameters¶
extent : (bx, ly, hz)
Full domain width, depth (in plan) and height.
footprint : (B, L)
Footing plan dimensions. h must divide both exactly
— that is the invariant that puts a mesh line on each
footprint edge.
h : float
Near-field cell size. Used uniformly inside the block and
as the first far-field cell.
l_mech : float
Lateral extent of the uniform block measured from the
footing edge. Rounded to a whole number of cells.
d_mech : float
Depth of the uniform block below z = 0. Rounded to a
whole number of cells (at least one).
r : float
Geometric growth ratio per cell outside the block,
r >= 1. r = 1 grades nothing (uniform far field).
orientation : float, default 0.0
Rotation of the whole grid about the z axis, in
degrees. The mesh is laid out axis-aligned and then
rotated rigidly, so the footprint rotates with it and stays
on mesh lines, and the element/node counts are identical at
every angle. This is the parameter the two-orientation
refinement study varies (PM-01 §10, ADR 65 D3): it changes
the grid direction relative to a load direction, not
relative to the footing.
Returns¶
list[int]
Tags of the 18 sub-volumes, ready for
g.physical.add_volume(...).
Raises¶
ValueError
If h does not divide B or L exactly, if r < 1,
or if the block does not fit strictly inside the domain
(there would be no far field to grade).
Examples¶
The PM-01 reference case — 1.5 m square footing, 15B × 15B × 12B domain, block 1B out and 1B deep, ratio 1.3::
vols = g.mesh.structured.build_graded_box(
extent=(22.5, 22.5, 18.0), footprint=(1.5, 1.5),
h=0.1875, l_mech=1.5, d_mech=1.5, r=1.3,
)
g.physical.add_volume(vols, name="soil")
g.mesh.generation.generate(dim=3)
Source code in src/apeGmsh/mesh/_mesh_structured.py
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 | |
set_transfinite ¶
set_transfinite(target=None, *, n=None, size=None, recombine: bool = True, dim: int | None = None, angle_tol_deg: float = 5.0) -> '_Structured'
Apply transfinite (+ optional recombine) to one entity, many, or the whole model.
High-level dispatcher that infers the dim of the target and applies the full cascade for that dim — curves of bounding edges, surfaces, recombine, and (for volumes) the volume itself.
Parameters¶
target : What to constrain. Accepts:
- ``None`` → every volume in the model
- ``"name"`` (label or PG name) → all entities under that
name, any dim (each gets the cascade for its dim)
- a Selection — uses its dimtags
- a ``(dim, tag)`` dimtag, or list of them
- a bare int — must be paired with ``dim=``
int | tuple | dict | None
Node-count sizing. Pass exactly one of n or size.
int— uniform on every edge of each entity, any orientationdict— per-axis, keyed by"x"/"y"/"z". Requires axis-aligned entities (raises otherwise — the error reports the cluster directions so you can switch to tuple form).tuple— per principal axis, in the order(X-aligned, Y-aligned, Z-aligned). Works on any rotation; closest-global-axis assignment with lex tie-break. Length must match the entity's principal-axis count (3 for volumes, 2 for surfaces, 1 for curves).
size : float | tuple | dict | None
Length-based sizing — node count per edge is
round(edge_length / size) + 1. Same grammar as n.
recombine : bool, default True
Recombine to quads on each face and (for volumes) hex on
the volume. Set False for a structured tet mesh.
dim : int | None, default None
Only used when target is a bare int. Ignored otherwise.
angle_tol_deg : float, default 5.0
Tolerance for grouping edges into principal-axis clusters.
Raise if your geometry has nearly-parallel non-orthogonal
edges that you want kept separate.
Returns¶
_Structured
self for chaining.
Behavior¶
- Volumes are processed first so their bounding surfaces and edges aren't reset by a later surface-level call.
- Entities whose edges don't cluster into the expected principal-axis count (e.g. a face split by a boolean op into a 5-sided patch) are warned and skipped rather than failing the whole call.
Examples¶
Whole-model, uniform sizing::
g.mesh.structured.set_transfinite(n=11)
Axis-aligned box, per-axis sizing::
g.mesh.structured.set_transfinite(
"layer_top", n={"x": 101, "y": 101, "z": 6},
)
Rotated box, per principal axis (tuple)::
g.mesh.structured.set_transfinite("rotated_box", n=(11, 11, 21))
Length-based sizing on a named surface::
g.mesh.structured.set_transfinite("base", size={"x": 100, "y": 100})
For per-edge bias (Progression/Bump/Beta) or explicit corner
lists, fall back to the granular methods —
:meth:set_transfinite_curve, :meth:set_transfinite_surface,
:meth:set_transfinite_volume.
Source code in src/apeGmsh/mesh/_mesh_structured.py
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 | |
set_transfinite_by_physical ¶
Deprecated. set_transfinite_curve/surface/volume already
accept a label or physical-group name directly — pass it as
tag.
Example¶
::
# old
g.mesh.structured.set_transfinite_by_physical("flange", dim=2,
arrangement="Left")
# new
g.mesh.structured.set_transfinite_surface("flange",
arrangement="Left")
Source code in src/apeGmsh/mesh/_mesh_structured.py
set_recombine ¶
Request quad recombination. tag accepts int, label, or PG name.
Source code in src/apeGmsh/mesh/_mesh_structured.py
recombine ¶
Globally recombine all triangular elements into quads.
This is a 2-D surface operation. Running it while 3-D
tetrahedra exist corrupts the volume mesh: Gmsh deletes interior
nodes but leaves the tets that referenced them pointing at node
0, which later aborts OpenSees with no Node 0 exists.
We warn up front; the corruption itself is caught fail-loud at
FEM extraction (_validate_connectivity). For a hexahedral
volume mesh use a structured/transfinite setup instead.
It is also a post-generation operation: with no 2-D elements
yet (called before generate()) there is nothing to merge, so
it warns :class:RecombineEmptyMeshWarning and does nothing.
Request quads before meshing with :meth:set_recombine or
g.mesh.recipe.structured.
Source code in src/apeGmsh/mesh/_mesh_structured.py
set_recombine_by_physical ¶
Deprecated. set_recombine accepts a PG name directly.
Source code in src/apeGmsh/mesh/_mesh_structured.py
set_smoothing ¶
Set smoothing passes. tag accepts int, label, or PG name.
Source code in src/apeGmsh/mesh/_mesh_structured.py
set_smoothing_by_physical ¶
Deprecated. set_smoothing accepts a PG name directly.
Source code in src/apeGmsh/mesh/_mesh_structured.py
set_compound ¶
Merge entities so they are meshed together as a single compound.
tags accepts int, label/PG name, (dim, tag) tuple, or a
list of any mix.
Source code in src/apeGmsh/mesh/_mesh_structured.py
remove_constraints ¶
Remove all meshing constraints from the given (or all) entities.
dim_tags accepts any flexible-ref form (int, label/PG name,
(dim, tag), or list thereof). None clears every
entity in the model.
Source code in src/apeGmsh/mesh/_mesh_structured.py
One-call recipe — set_transfinite()¶
For the common case of "apply transfinite + recombine to one entity, many,
or the whole model," use the unified
set_transfinite()
method. It infers the dim from the target and runs the appropriate cascade
(curves → faces → recombine → volume):
# Whole model, uniform — typical "just give me hexes"
g.mesh.structured.set_transfinite(n=11)
# Axis-aligned hex, per-axis sizing (most readable)
g.mesh.structured.set_transfinite("layer_top",
n={"x": 101, "y": 101, "z": 6})
# Rotated hex, per principal axis (works for any orientation)
g.mesh.structured.set_transfinite("rotated_box", n=(11, 11, 21))
# Length-based sizing (per axis)
g.mesh.structured.set_transfinite("layer_top",
size={"x": 100, "y": 100, "z": 10})
Sizing forms — all three coexist; pick by readability:
| Form | Use when | Example |
|---|---|---|
scalar n=11 |
uniform on every edge; any orientation | n=11 |
dict n={"x":..., "y":..., "z":...} |
axis-aligned hex, want per-axis counts | n={"x":11, "y":11, "z":21} |
tuple n=(n1, n2, n3) |
any rotation; counts in (X-closest, Y-closest, Z-closest) order |
n=(11, 11, 21) |
Behavior on incompatible geometry — entities whose edges don't cluster
into the expected principal-axis count (e.g. a face split by a boolean op
into a 5-sided patch) are warned and skipped rather than failing the
whole call. Use
set_transfinite_automatic()
if you want silent skipping with no warning.
For per-edge bias (Progression / Bump / Beta with coef=), explicit
corner lists, or custom triangle arrangement, drop to the granular methods:
set_transfinite_curve(), set_transfinite_surface(),
set_transfinite_volume().
g.mesh.editing¶
apeGmsh.mesh._mesh_editing._Editing ¶
Mesh mutation, embedding, periodicity, STL import.
Source code in src/apeGmsh/mesh/_mesh_editing.py
embed ¶
Embed lower-dimensional entities inside a higher-dimensional entity so the mesh is conforming along them.
Parameters accept int tags, label/PG strings, or lists thereof.
Example¶
::
g.mesh.editing.embed("crack_surf", "body", dim=2, in_dim=3)
g.mesh.editing.embed([p1, p2, p3], surf_tag, dim=0, in_dim=2)
Source code in src/apeGmsh/mesh/_mesh_editing.py
set_periodic ¶
Declare periodic mesh correspondence between entities.
Parameters¶
tags : slave entity reference(s) — int, label, PG name,
(dim, tag) tuple, or list of any mix.
master_tags : master entity reference(s) — same flexible form.
transform : 16-element row-major 4×4 affine matrix mapping
master -> slave coordinates
dim : entity dimension (1 = curves, 2 = surfaces)
Source code in src/apeGmsh/mesh/_mesh_editing.py
import_stl ¶
Classify an STL mesh previously loaded into the gmsh model via
gmsh.merge as a discrete surface mesh.
Source code in src/apeGmsh/mesh/_mesh_editing.py
classify_surfaces ¶
classify_surfaces(angle: float, *, boundary: bool = True, for_reparametrization: bool = False, curve_angle: float = math.pi, export_discrete: bool = True) -> '_Editing'
Partition a discrete STL mesh into surface patches based on dihedral angle.
Source code in src/apeGmsh/mesh/_mesh_editing.py
create_geometry ¶
Create a proper CAD-like geometry from classified discrete surfaces.
Must be called after classify_surfaces.
Source code in src/apeGmsh/mesh/_mesh_editing.py
clear ¶
Clear mesh data (nodes + elements).
dim_tags accepts any flexible-ref form — int, label/PG name,
(dim, tag), or a list mixing those — resolved via
:func:resolve_to_dimtags (default_dim=3). None (the
default) clears every entity in the model.
Example¶
::
g.mesh.editing.clear() # clear everything
g.mesh.editing.clear("col.body") # clear a labelled volume
g.mesh.editing.clear([(2, 5), "fillet"]) # mixed refs
Source code in src/apeGmsh/mesh/_mesh_editing.py
reverse ¶
Reverse the orientation of mesh elements in the given entities.
dim_tags accepts any flexible-ref form (int, label/PG name,
(dim, tag), or list thereof). None reverses every
entity in the model.
Example¶
::
g.mesh.editing.reverse("inverted_face")
g.mesh.editing.reverse([(2, 5), (2, 6)])
Source code in src/apeGmsh/mesh/_mesh_editing.py
relocate_nodes ¶
Project mesh nodes back onto their underlying geometry.
tag accepts an int, label/PG name, (dim, tag), or a
list mixing those. Because gmsh's relocateNodes operates
on a single entity at a time, when a reference resolves to
multiple entities the wrapper iterates and calls gmsh once
per resolved (dim, tag).
tag=-1 (the default) relocates nodes for every entity in
the model; dim is forwarded to gmsh in that case.
Example¶
::
g.mesh.editing.relocate_nodes() # all entities
g.mesh.editing.relocate_nodes(tag="col.faces") # whole label
g.mesh.editing.relocate_nodes(tag=(2, 5))
Source code in src/apeGmsh/mesh/_mesh_editing.py
remove_duplicate_nodes ¶
Merge nodes that share the same position within tolerance.
Node removal is always announced on stdout — there is no silent mode. Deleting nodes from a meshed model is a destructive operation; the visibility floor is intentional so that an unexpected dedup never hides in a long pipeline log.
Source code in src/apeGmsh/mesh/_mesh_editing.py
remove_duplicate_elements ¶
Remove elements with identical node connectivity.
Source code in src/apeGmsh/mesh/_mesh_editing.py
crack ¶
crack(physical_group: str, *, dim: int = 1, open_boundary: str | None = None, normal: tuple[float, float, float] | None = None, side_labels: tuple[str, str] | bool = True) -> '_Editing'
Duplicate mesh nodes along a physical group to create a crack.
Wraps Gmsh's built-in Crack plugin
(gmsh.plugin.run("Crack")). After meshing, the plugin
walks the elements on one side of physical_group and
reconnects them to a freshly duplicated set of nodes — the
crack is therefore a discontinuity in the mesh, not in the
geometry.
By default the plugin keeps the boundary vertices of the
crack curve shared (e.g. the crack tip in fracture
mechanics). Naming a sub-region of those boundary vertices
in open_boundary overrides the default and duplicates
them too — that is how you model a crack mouth that opens
onto a free surface.
Must be called after g.mesh.generation.generate(...)
— the plugin operates on the mesh, not the geometry.
Parameters¶
physical_group : str
Name of the physical group containing the crack
curves (dim=1) or surfaces (dim=2). Create it
ahead of time via g.physical.add_curve(..., name=...)
or g.physical.add_surface(..., name=...).
dim : int
Dimension of the crack itself. 1 for a 1-D crack
in a 2-D mesh; 2 for a 2-D crack in a 3-D mesh.
open_boundary : str, optional
Name of a physical group, one dimension lower than
dim, naming the crack-curve boundary vertices that
should also be duplicated. Use this for the crack
mouth (where the crack reaches a free surface). Leave
None for an interior crack so every boundary vertex
(including the tip) stays shared.
normal : (nx, ny, nz), optional
Hint vector forwarded to the plugin to disambiguate the
two sides of the crack when topology alone is not enough.
Almost never needed for clean transfinite or unstructured
meshes.
side_labels : tuple[str, str] or bool, default True
Post-plugin, the crack is owned by two distinct face
entities (the original entity plus a new one created by the
plugin to host the duplicated side). This argument
controls whether they get named physical groups attached:
* ``True`` (default) — auto-derive
``f"{physical_group}_normal"`` and
``f"{physical_group}_inverted"`` and add them as
physical groups, one per face entity.
* ``(normal_name, inverted_name)`` tuple — use these
explicit names instead.
* ``False`` — skip side labeling (legacy behaviour).
**Convention.** ``<pg>_normal`` is the face entity whose
adjacent volume elements sit on the side the *original*
surface normal points toward; ``<pg>_inverted`` is the
face on the opposite side. This is computed at runtime
from the signed distance between an adjacent tet's
centroid and the crack plane along that normal — it does
not assume the plugin's "original vs new" mapping is
stable. Only supported for ``dim=2`` cracks in 3D meshes.
Returns¶
_Editing (self, for chaining)
Example¶
Edge crack reaching the bottom edge — duplicate the mouth, keep the tip shared::
g.physical.add_curve([crack_curve], name="Crack")
g.physical.add_point([base_point], name="CrackBase")
g.mesh.generation.generate(dim=2)
g.mesh.editing.crack(
"Crack", dim=1, open_boundary="CrackBase",
)
Source code in src/apeGmsh/mesh/_mesh_editing.py
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 | |
split_higher_order_lines ¶
split_higher_order_lines(physical_group: str | Iterable[str], *, policy: Literal['forbid', 'split', 'constrain'], dim: int = 1) -> '_Editing'
Demote higher-order line elements (Line3) on the named PG(s) to the 1st-order Line2 elements that OpenSees beam-columns require.
2nd-order continuum meshes (quadratic shells, solid tet10s, etc.)
propagate their order to every line entity in the same Gmsh
model — even line entities the user intended as frame elements
get meshed as Line3 (Gmsh type 8, three nodes (i, j, mid)).
OpenSees beam-columns are strictly 2-node 1st-order, so the
bridge raises at _check_two_nodes whenever it sees a Line3
in a frame PG. This method is the broker-side resolution:
rewrite the mesh so the bridge sees only Line2 on the named
PG(s), keeping the continuum side untouched.
Three policies pick what happens to the mid-side node:
"split"— each Line3(i, j, mid)is replaced by two Line2 elements(i, mid)and(mid, j)on the SAME dim=1 entity (PG membership tracks at entity level — no rebinding). The mid-node becomes a real FE node with its own DOFs. Exact subdivision for prismatic elastic frames; for distributed- plasticity frames the integration-point count doubles (each sub-element gets its own N-IP rule), which can shift hinge locations under softening / cyclic degradation. Concentrated- plasticity integration rules (HingeRadau,HingeRadauTwo,HingeMidpoint,HingeEndpoint) are structurally incompatible with this policy — splitting puts the calibrated end-region hinges in the wrong places. Use"forbid"if you must lock in 1st-order lines, or fall back to "this PG stays 1st-order in the mesh";"constrain"is reserved but not implemented this round."constrain"— RESERVED but NOT IMPLEMENTED this round. The kinematically clean answer (mid-node interpolated linearly from i and j via a 2-master/1-slave constraint) requires an OpenSees primitive that does not exist today:ASDEmbeddedNodeElementaccepts exactly 3 or 4 retained nodes (ADR 0036), so a Line2 master pair (2 nodes) cannot be expressed. A future round paired with upstream OpenSees work (new element class accepting N-retained-node coupling, or a new MP_Constraint primitive) will land this policy. RaisesNotImplementedErroruntil then."forbid"— fail-loud if the named PG(s) contain any Line3 element. Use as a build-time invariant lock when you must guarantee a PG remained 1st-order through meshing.
Call timing: AFTER g.mesh.generation.generate(...) (the
method operates on the live mesh), BEFORE
g.mesh.queries.get_fem_data(...) (the snapshot must see the
rewritten topology). Never call inside a stage block — the
mesh edit is global and must complete before the bridge builds.
Parameters¶
physical_group
PG name (str) or iterable of PG names (list/
tuple). Required — there is no "split everything"
mode, callers must name what they're rewriting. Each name
must already exist as a physical group of dim; unknown
names raise KeyError naming the missing one.
policy
"forbid" / "split" / "constrain" — see above.
Required kwarg; no default in the spirit of fail-loud:
destructive mesh mutation should never happen by accident.
dim
Dimension of the higher-order lines. Currently only 1
is supported; dim != 1 raises NotImplementedError.
Future work (line4, cubic edges from order-3 meshes) lands
via the same kwarg.
Returns¶
_Editing (self, for chaining)
Raises¶
NotImplementedError
policy="constrain" (deferred to a follow-up paired with
upstream OpenSees work — ADR 0036 future track).
dim != 1 (line4 / cubic lines are out of scope this
round; structure permits adding them with the same kwarg).
RuntimeError
policy="forbid" and any named PG contains at least one
Line3 element. Message names the offending PG and count.
KeyError
A named PG does not exist at dim.
ValueError
policy is not one of the three accepted values.
Example¶
::
# Quadratic shell + frame model. The 2nd-order shell mesh
# forces every line entity to Line3; the frame PG needs
# to come back to Line2 before the bridge sees it.
g.mesh.generation.generate(dim=3)
g.mesh.editing.split_higher_order_lines(
"Beams", policy="split",
)
fem = g.mesh.queries.get_fem_data(dim=3)
ops = apeSees(fem)
ops.element.elasticBeamColumn(pg="Beams", ...) # works now
Source code in src/apeGmsh/mesh/_mesh_editing.py
593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 | |
affine_transform ¶
Apply an affine transformation to mesh nodes (12 coefficients, row-major 4x3 matrix — translation in last column).
dim_tags accepts any flexible-ref form (int, label/PG name,
(dim, tag), or list thereof). None transforms every
entity in the model.
Example¶
::
identity = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0]
g.mesh.editing.affine_transform(identity, "col.body")
Source code in src/apeGmsh/mesh/_mesh_editing.py
g.mesh.queries¶
apeGmsh.mesh._mesh_queries._Queries ¶
Read-only mesh data extraction and quality reporting.
Source code in src/apeGmsh/mesh/_mesh_queries.py
get_nodes ¶
get_nodes(*, dim: int = -1, tag: int = -1, include_boundary: bool = False, return_parametric: bool = False) -> dict
Query mesh nodes.
Returns¶
dict
'tags' : ndarray(N,) — node tags
'coords' : ndarray(N, 3) — XYZ coordinates
'parametric_coords' : ndarray — only if requested
Source code in src/apeGmsh/mesh/_mesh_queries.py
get_elements ¶
Query mesh elements.
Returns¶
dict
'types' : list[int] — gmsh element type codes
'tags' : list[ndarray] — element tags per type
'node_tags' : list[ndarray] — connectivity per type
Source code in src/apeGmsh/mesh/_mesh_queries.py
get_element_properties ¶
Return metadata for a given gmsh element type code.
Returns¶
dict
'name', 'dim', 'order', 'n_nodes',
'n_primary_nodes', 'local_coords'.
Source code in src/apeGmsh/mesh/_mesh_queries.py
get_fem_data ¶
Extract solver-ready FEM data as a :class:FEMData object.
Must be called after generate().
Parameters¶
dim : int or None
Element dimension to extract. None extracts all
dimensions present in the mesh.
remove_orphans : bool
If True, remove mesh nodes not connected to any element.
Nodes referenced by constraints, loads, or masses are
always kept. Default False.
Caching (Phase 3B.2b-prep / ADR 0038)¶
Repeat calls return the same :class:FEMData object identity
until a declaration invalidates the cache (every
g.constraints.X / g.loads.X / g.masses.X /
g.displacements.X call, g.reinforce / g.embed /
g.rebar.place / g.decouple_node, and each composite's
clear() bumps an internal counter; the cache is fresh iff
the counter has not advanced since the last extraction). This
means the session has a single canonical "chain head" snapshot
that the FEMData.with_* transforms update.
Vanilla sessions (no _fem_counter attribute — direct
FEMData.from_gmsh fixtures or test stubs) skip the cache
entirely and behave like the pre-cache extraction call.
Example¶
::
fem = g.mesh.queries.get_fem_data() # all dims
fem = g.mesh.queries.get_fem_data(dim=3) # 3D only
Source code in src/apeGmsh/mesh/_mesh_queries.py
145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 | |
get_element_qualities ¶
Compute quality metrics for the given elements.
Parameters¶
element_tags : element tags to evaluate
quality_name : "minSICN", "minSIGE", "gamma", or
"minSJ"
Source code in src/apeGmsh/mesh/_mesh_queries.py
quality_report ¶
Compute a summary quality report for all mesh elements.
For each element type and quality metric, reports count, min, max, mean, std, and the percentage of elements below common thresholds.
Must be called after generate().
Example¶
::
g.mesh.generation.generate(2)
print(g.mesh.queries.quality_report().to_string())
Source code in src/apeGmsh/mesh/_mesh_queries.py
282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 | |
g.mesh.partitioning¶
apeGmsh.mesh._mesh_partitioning._Partitioning ¶
Mesh partitioning plus node / element renumbering.
Accessed via g.mesh.partitioning.
Source code in src/apeGmsh/mesh/_mesh_partitioning.py
renumber ¶
Renumber nodes and elements in the Gmsh model.
After this call every Gmsh query returns solver-ready contiguous
IDs. Call once, before extracting FEM data with
:meth:~_Queries.get_fem_data.
Parameters¶
dim : int
Element dimension used to compute bandwidth and to collect
element tags for renumbering.
method : "simple" | "rcm" | "hilbert" | "metis"
"simple" — contiguous IDs, no optimisation.
"rcm" — Reverse Cuthill-McKee (bandwidth reduction).
"hilbert" — Hilbert space-filling curve (cache locality).
"metis" — METIS graph-partitioner ordering.
base : int
Starting ID (default 1 = OpenSees / Abaqus convention).
Returns¶
RenumberResult
Source code in src/apeGmsh/mesh/_mesh_partitioning.py
194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 | |
partition ¶
partition(n_parts: int, *, weights: Sequence[float] | ndarray | None = None, backend: PartitionBackend | None = None, uncuttable_elements: Sequence[int] | ndarray | None = None) -> PartitionInfo
Partition the mesh into n_parts sub-domains.
Must be called after g.mesh.generation.generate().
Two flavours, dispatched by weights / backend:
============= ================== ==================================
weights backend Path
============= ================== ==================================
None None Gmsh-native METIS (unweighted)
None "gmsh" Gmsh-native METIS (explicit alias)
None "pymetis" pymetis with vwgt = ones(n)
None "networkx-... networkx-metis, unit weights
sequence None pymetis (default for weighted)
sequence "pymetis" pymetis with the given weights
sequence "networkx-... networkx-metis with weights
sequence "gmsh" ValueError — Gmsh has no vwgt
============= ================== ==================================
uncuttable_elements applies after either flavour above has
run (ADR 0092 INV-4 — "the partitioner may cut the slave side of a
contact interface, never the master"): every element tag it names
is forced onto a single partition — whichever one currently holds
the most of them, ties breaking to the lowest partition id — by
overriding the just-computed assignment through
:meth:partition_explicit. This is a deterministic correction,
not a bias: METIS vertex weights (weights= above) balance
partition size, they do not stop it from cutting through a
specific group, so a group that must stay whole is enforced as a
post-hoc override instead.
Parameters¶
n_parts : int
Number of partitions (>= 1).
weights : sequence of float, optional
Per-element vertex weights for METIS. Length must match the
total number of elements across all dimensions, ordered
by flattened gmsh.model.mesh.getElements(dim=-1, tag=-1)
traversal — the same order used to drive
partition_explicit internally.
backend : "gmsh" | "pymetis" | "networkx-metis", optional
Backend selector. See dispatch table above.
uncuttable_elements : sequence of int, optional
Gmsh element tags (any dimension) that must all end up on the
same partition — e.g. a contact interface's master-surface
face elements plus their backing solid elements. None or
empty is a no-op: the base partition from weights/
backend is returned unchanged.
Returns¶
PartitionInfo
weights_per_partition is populated when weights was
passed, else None.
Raises¶
ValueError
On n_parts < 1, backend="gmsh" with weights,
wrong-length weights, or an uncuttable_elements tag
absent from the partitioned mesh.
ImportError
When the selected backend is not installed (with a
pip install apeGmsh[partition-pymetis] hint).
Source code in src/apeGmsh/mesh/_mesh_partitioning.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 | |
partition_explicit ¶
Partition with an explicit per-element assignment.
Parameters¶
n_parts : int Total number of partitions declared. elem_tags : list[int] Element tags to assign. parts : list[int] Parallel list of 1-based partition IDs.
Returns¶
PartitionInfo
Source code in src/apeGmsh/mesh/_mesh_partitioning.py
unpartition ¶
Remove the partition structure and restore a monolithic mesh.
Source code in src/apeGmsh/mesh/_mesh_partitioning.py
n_partitions ¶
Return the current number of partitions (0 if not partitioned).
summary ¶
Concise text summary of the partition state.
Source code in src/apeGmsh/mesh/_mesh_partitioning.py
entity_table ¶
DataFrame of all model entities and their partition membership.
Parameters¶
dim : int
Restrict to a single dimension (-1 = all).
Returns¶
pd.DataFrame
Columns: dim, tag, partitions,
parent_dim, parent_tag.
Source code in src/apeGmsh/mesh/_mesh_partitioning.py
save ¶
save(path: Path | str, *, one_file_per_partition: bool = False, create_topology: bool = False, create_physicals: bool = True) -> '_Partitioning'
Write the partitioned mesh to file(s).
Parameters¶
path : Path or str
Output file path (format inferred from extension).
one_file_per_partition : bool
Write one file per partition alongside the combined file.
create_topology : bool
Pass to Mesh.PartitionCreateTopology.
create_physicals : bool
Pass to Mesh.PartitionCreatePhysicals.
Returns¶
self — for chaining
Source code in src/apeGmsh/mesh/_mesh_partitioning.py
Fluent selection — g.mesh_selection.select()¶
g.mesh_selection (a session attribute,
MeshSelectionSet)
is the live-mesh entry of the unified, daisy-chainable
selection idiom. select() returns a
MeshSelection
(point family, bi-level) with .ids / .coords / .result() and the
live-engine-only .save_as(name) terminal. The former
add_nodes / add_elements spatial registrars (and from_geometric)
have been removed; persist a selection with
.select(...).save_as(name) (live engine), or register explicit ids
with the retained g.mesh_selection.add(dim, ids, name=) /
g.mesh_selection.from_physical(...). filter_set / sort_set /
union / intersection / difference remain.
node_set = (g.mesh_selection.select() # node level
.in_box((0, 0, 0), (1, 1, 1)) # half-open [lo, hi)
.on_plane((0, 0, 0), (0, 0, 1), tol=1e-9)
.save_as("base")) # live-engine persist
hexes = g.mesh_selection.select(level="element", dim=3).in_box(
lo, hi, inclusive=True).ids
S2 — point-family box is half-open
The point-family in_box(lo, hi) is half-open [lo, hi) (to
match results). Pass inclusive=True to get a closed
[lo, hi] box. See the changelog for the
migration note.
See Selection for the full idiom and the removed-vs-retained migration table.
Supporting types¶
apeGmsh.mesh.PhysicalGroups.PhysicalGroups ¶
Bases: _HasLogging
Physical-group composite attached to a apeGmsh instance as
g.physical.
Wraps the physical-group subset of the Gmsh Python API with a clean, method-chaining interface organised into:
- Creation —
add,add_point,add_curve,add_surface,add_volume - Naming —
set_name,remove_name - Removal —
remove,remove_all - Queries —
get_all,get_entities,get_groups_for_entity,get_name,get_tag,summary - Mesh nodes—
get_nodes
Name lookups go through an index, name -> {dim: tag}, so
get_tag and add cost O(1) per call instead of a scan of every
group. It never answers stale, even after raw gmsh.model.*
calls; the rule is in :mod:apeGmsh.core._pg_name_index.
All mutating methods return self for chaining::
(g.physical
.add_surface([s_inlet], name="Inlet")
.add_surface([s1, s2], name="Wall")
.add_volume([vol], name="Fluid"))
Parameters¶
parent : _SessionBase
The owning instance — used for _verbose.
Source code in src/apeGmsh/mesh/PhysicalGroups.py
add ¶
Create or append to a physical group.
If name matches an existing PG at this dim, the new tags are merged into it (upsert). Otherwise a new PG is created.
Parameters¶
dim : entity dimension (0 = points, 1 = curves, 2 = surfaces,
3 = volumes)
tags : entity tags — accepts int, str (label or PG name),
(dim, tag) tuples, or a list mixing all of these.
String references are resolved via g.labels first,
then g.physical.
name : human-readable name. If a PG with this name already
exists at dim, the new entities are appended. A
physical-group name maps to exactly one dimension —
reusing name at a different dim raises ValueError.
tag : requested physical-group tag (-1 = auto-assign).
Ignored when appending to an existing named PG.
Returns¶
Tag the physical-group tag (existing or newly created)
Raises¶
ValueError
If name is already used by a physical group at a
different dimension. Multi-dimensional physical groups
are not supported — pick a distinct name per dimension.
Also if name starts with the reserved _label: prefix.
Source code in src/apeGmsh/mesh/PhysicalGroups.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 | |
add_point ¶
Shorthand: add(dim=0, tags, ...) — returns self for chaining.
add_curve ¶
Shorthand: add(dim=1, tags, ...) — returns self for chaining.
add_surface ¶
Shorthand: add(dim=2, tags, ...) — returns self for chaining.
add_volume ¶
Shorthand: add(dim=3, tags, ...) — returns self for chaining.
from_label ¶
Create (or append to) a PG from a label's entities.
Parameters¶
label_name : str
Label name (without _label: prefix).
name : str, optional
PG name. Defaults to the label name.
dim : int, optional
Dimension. If None, inferred from the label.
Returns¶
Tag the physical-group tag
Source code in src/apeGmsh/mesh/PhysicalGroups.py
from_labels ¶
Create (or append to) a PG from multiple labels (union).
Parameters¶
label_names : list[str]
Label names to combine.
name : str
PG name for the combined group.
dim : int, optional
Dimension. If None, inferred from the first label.
Returns¶
Tag the physical-group tag
Source code in src/apeGmsh/mesh/PhysicalGroups.py
set_name ¶
Assign (or rename) the label of an existing physical group.
A named group is renamed in place: it keeps its tag and its entities, takes name, and no longer answers to its old name.
Parameters¶
dim : dimension of the physical group tag : physical-group tag name : new label
Raises¶
ValueError
If another physical group at dim is already named name.
gmsh keeps one group per name and dim and drops the call
without a word, so neither group would change. If name
already names a group at another dim, as :meth:add
refuses: a physical-group name maps to one dimension. If
name starts with the reserved _label: prefix, as
:meth:add refuses, or if the group is a label's
(rename it with g.labels.rename()). If name is
"" and the group is named: use :meth:remove_name to
unname it. Setting a group's own current name stays a
no-op. Every refusal comes before any gmsh write.
Source code in src/apeGmsh/mesh/PhysicalGroups.py
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 | |
remove_name ¶
Remove the name-to-tag mapping for name.
The physical group itself is not deleted — only the name entry.
Source code in src/apeGmsh/mesh/PhysicalGroups.py
remove ¶
Remove specific physical groups.
Parameters¶
dim_tags : [(dim, pg_tag), ...] pairs identifying groups to remove.
An empty list removes nothing.
Source code in src/apeGmsh/mesh/PhysicalGroups.py
remove_all ¶
Remove every physical group in the current model.
The groups are listed and removed by (dim, tag). gmsh's
argument-less removePhysicalGroups() is never called: in
gmsh 4.15.2 it corrupts the heap at finalize once any targeted
removePhysicalGroups([(dim, tag)]) ran in the model (the
upsert in :meth:add, :meth:remove, label upkeep), and the
process then dies at g.end() with no traceback (#2608;
pinned by tests/test_physical_upsert_remove_all.py).
Listing them also drops their names, which the argument-less
form kept, so a group later created at a freed tag no longer
inherits a stale name.
Source code in src/apeGmsh/mesh/PhysicalGroups.py
get_all ¶
Return all user-facing physical groups as (dim, tag)
pairs. Internal label PGs (Tier 1 naming, prefixed with
_label:) are filtered out — use g.labels.get_all()
to see those.
Parameters¶
dim : filter to a single dimension (-1 = all)
Source code in src/apeGmsh/mesh/PhysicalGroups.py
get_entities ¶
Return the model-entity tags contained in a physical group.
Parameters¶
dim : dimension of the physical group tag : physical-group tag
Source code in src/apeGmsh/mesh/PhysicalGroups.py
entities ¶
Resolve a physical group to its entity tags — by name or by tag.
Parameters¶
name_or_tag : str | int
Physical group name, or the raw PG tag (dim required).
dim : int | None, optional
Dimension to search. If omitted and name_or_tag is a string,
all dimensions are searched. A physical-group name maps to a
single dimension; if a legacy model nonetheless carries the
name at multiple dims this raises — pass dim= to read
one slice.
Returns¶
list[Tag] Flat list of model-entity tags contained in the group.
Raises¶
KeyError
If no physical group with that name exists.
ValueError
If name_or_tag is a string, dim is omitted, and the
name matches physical groups at more than one dimension.
TypeError
If name_or_tag is an int but dim is not provided.
Source code in src/apeGmsh/mesh/PhysicalGroups.py
get_groups_for_entity ¶
Return the physical-group tags that contain a given model entity.
Parameters¶
dim : entity dimension tag : model-entity tag
Source code in src/apeGmsh/mesh/PhysicalGroups.py
get_name ¶
Return the name of a physical group, or "" if unnamed.
Parameters¶
dim : dimension of the physical group tag : physical-group tag
Source code in src/apeGmsh/mesh/PhysicalGroups.py
get_tag ¶
Look up the tag of a named physical group.
Returns None if no group with that name and dimension exists.
Parameters¶
dim : dimension to search name : human-readable label
Source code in src/apeGmsh/mesh/PhysicalGroups.py
summary ¶
Build a DataFrame describing every user-facing physical group in the model. Internal label PGs are excluded.
Returns¶
pd.DataFrame indexed by (dim, pg_tag) with columns:
dim entity dimension
pg_tag physical-group tag
name label (empty string if unnamed)
n_entities number of model entities in the group
entity_tags comma-separated entity tags as a string
Source code in src/apeGmsh/mesh/PhysicalGroups.py
get_nodes ¶
Return the mesh nodes belonging to a physical group.
Must be called after mesh generation.
Parameters¶
dim : dimension of the physical group tag : physical-group tag
Returns¶
dict
'tags' : ndarray(N,) — node tags
'coords' : ndarray(N, 3) — XYZ coordinates
Source code in src/apeGmsh/mesh/PhysicalGroups.py
apeGmsh.mesh.MeshSelectionSet.MeshSelectionSet ¶
Bases: _HasLogging
Post-mesh selection composite — complementary to PhysicalGroups.
Attached to g.mesh_selection by the session framework.
Stores sets of mesh node/element IDs, resolved by spatial queries
or explicit tag lists. Mirrors the PhysicalGroups API shape so
downstream consumers (solvers, FEMData) can treat both identically.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
add ¶
Add a mesh selection set from explicit node/element IDs.
Parameters¶
dim : 0 for node set, 1/2/3 for element set tags : list of node IDs (dim=0) or element IDs (dim>=1) name : optional label tag : explicit tag (auto-allocated if -1)
Returns¶
int — the allocated set tag
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
get_entities ¶
Return node IDs (dim=0) or element IDs (dim>=1).
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
get_nodes ¶
Return {'tags': ndarray, 'coords': ndarray(N,3)}.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
get_elements ¶
Return {'element_ids': ndarray, 'connectivity': ndarray(E,npe)}.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
union ¶
Create a new set = A ∪ B.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
intersection ¶
Create a new set = A ∩ B.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
difference ¶
Create a new set = A \ B.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
from_physical ¶
Import a physical group as a mesh selection set.
Parameters¶
dim : dimension of the physical group name_or_tag : physical group name or tag ms_name : name for the new mesh selection ms_tag : tag for the new mesh selection (-1 = auto)
Returns¶
int — mesh selection tag
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
filter_set ¶
filter_set(dim: int, tag: int, *, name: str = '', new_tag: int = -1, on_plane: tuple | None = None, in_box: tuple | list | None = None, in_sphere: tuple | None = None, closest_to: tuple | None = None, count: int = 1, predicate: Callable[[ndarray], ndarray] | None = None, inclusive: bool = False) -> int
Refine an existing set with spatial filters -> create a new set.
For node sets, filters apply to node coordinates. For element sets, filters apply to element centroids. All filters are AND-combined.
Parameters¶
dim, tag : source set identifier
name, new_tag : identifier for the resulting set
on_plane, in_box, in_sphere, closest_to, predicate :
same semantics as :meth:add_nodes (in_box is half-open
on the upper side by default)
inclusive : if True, in_box uses a closed upper bound
(restores the pre-S2 closed-closed behavior).
Returns¶
int — tag of the new (filtered) set
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 | |
select ¶
Build a named mesh-selection set from the live mesh.
Returns a :class:~apeGmsh.mesh._mesh_selection.MeshSelection
(point family) that chains spatial-refinement verbs. Finish
with .save_as(name) to register the result — it then
snapshots into FEMData and round-trips via HDF5::
# capture all base nodes and persist
(g.mesh_selection.select()
.in_box((0, 0, 0), (10, 10, 0.01))
.on_plane((0, 0, 0), (0, 0, 1), tol=1e-6)
.save_as("base_nodes"))
# 3-D solid elements in a region (dim=3 required for tets)
(g.mesh_selection.select(level="element", dim=3)
.in_box(lo, hi)
.save_as("core_tets"))
# narrow an existing set further
g.mesh_selection.select(name="base_nodes").in_sphere(c, r)
# set algebra
g.mesh_selection.select(ids=a) | g.mesh_selection.select(ids=b)
No arguments seeds the full live-mesh universe for the chosen
level and dim.
Parameters¶
level : "node" | "element"
"node" (default) — atoms are node ids.
"element" — atoms are element ids for dim.
dim :
Element dimension (1=line, 2=surface, 3=volume) used
when level="element" (ignored for nodes).
Defaults to 2 (surface elements) — pass dim=3
for solid/tet meshes.
ids :
Explicit id list to seed from. Mutually exclusive
with name=.
name :
Name of an existing g.mesh_selection set to
seed from. Node ids are used for level="node",
element ids for level="element". Mutually
exclusive with ids=. An unknown name raises.
Refining verbs¶
Each returns a new MeshSelection and composes freely:
.in_box(lo, hi, *, inclusive=False).in_sphere(center, radius).on_plane(point, normal, *, tol)—tol=is required; raisesTypeErrorif omitted..nearest_to(point, *, count=1).where(predicate)|&-^(set algebra).
Terminals¶
.ids—list[int]..coords—ndarray (N, 3)..save_as(name)— registers the narrowed id set as a named mesh-selection, so it snapshots intoFEMDataand round-trips via HDF5 asselection=.
Notes¶
To seed from a physical group or label, register it first::
g.mesh_selection.from_physical(2, "BottomFace",
ms_name="bottom")
g.mesh_selection.select(name="bottom").in_sphere(c, r)
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 | |
sort_set ¶
Sort the entries of a set in place by coordinate axis.
Parameters¶
dim, tag : set identifier by : "x", "y", or "z" — axis to sort along descending : reverse the order
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
summary ¶
DataFrame describing all mesh selection sets.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
to_dataframe ¶
Return a DataFrame of the entries of a single set.
For dim=0 (node set): columns [node_id, x, y, z].
For dim>0 (element set): columns [element_id, cx, cy, cz, n_nodes].
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
apeGmsh.mesh.MeshSelectionSet.MeshSelectionStore ¶
Immutable snapshot of mesh selections captured at get_fem_data() time.
Accessed via fem.mesh_selection. Mirrors the query API of
:class:MeshSelectionSet and :class:PhysicalGroupSet.
Example¶
::
fem = g.mesh.queries.get_fem_data(dim=2)
fem.mesh_selection.get_all()
fem.mesh_selection.get_nodes(0, 1)
fem.mesh_selection.get_elements(2, 1)
fem.mesh_selection.summary()
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
get_nodes ¶
Return {'tags': ndarray, 'coords': ndarray(N,3)}.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
get_elements ¶
Return {'element_ids': ndarray, 'connectivity': ndarray(E,npe)}.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
names ¶
All non-empty selection names, optionally filtered by dim.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
node_ids ¶
Node IDs for any selection matching name (any dim).
For dim=0 selections returns the explicit node IDs.
For dim>=1 selections returns the node IDs implied by the
elements' connectivity.
Raises KeyError if no selection matches name.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
element_ids ¶
Element IDs for an element-bearing selection matching name.
Searches dim>=1 selections only (dim=0 selections have
no element data).
Raises KeyError if no element-bearing selection matches.
Source code in src/apeGmsh/mesh/MeshSelectionSet.py
apeGmsh.mesh.MshLoader.MshLoader ¶
Bases: _HasLogging
Load .msh files and produce solver-ready :class:FEMData.
Can be used standalone via the :meth:load classmethod, or as a
composite on a apeGmsh / Assembly session via g.loader.
Parameters¶
parent : _SessionBase or None
The owning session when used as a composite. None when
used standalone.
Source code in src/apeGmsh/mesh/MshLoader.py
load
classmethod
¶
Load a .msh file and return a :class:FEMData.
Manages its own Gmsh session internally — no apeGmsh
instance, no begin()/end() needed. Supports MSH2
and MSH4 formats.
Parameters¶
path : str or Path
Path to the .msh file.
dim : int
Element dimension to extract (1 = lines, 2 = tri/quad,
3 = tet/hex). Default is 2.
verbose : bool
Print a summary of what was loaded.
Returns¶
FEMData Self-contained solver-ready mesh data with physical groups, mesh statistics, and connectivity.
Example¶
::
from apeGmsh import MshLoader, Numberer
fem = MshLoader.load("bridge.msh", dim=2)
print(fem.info)
print(fem.physical.summary())
numb = Numberer(fem)
data = numb.renumber(method="rcm")
Source code in src/apeGmsh/mesh/MshLoader.py
from_msh ¶
Load a .msh file into the active Gmsh session.
The mesh is merged via gmsh.merge(), so all composites
(g.physical, g.plot, g.inspect, etc.) remain
usable afterwards.
Parameters¶
path : str or Path
Path to the .msh file.
dim : int
Element dimension to extract. Default is 2.
Returns¶
FEMData Self-contained solver-ready mesh data.
Raises¶
FileNotFoundError
If path does not exist.
RuntimeError
If no Gmsh session is active (call g.begin() first).
Example¶
::
g = apeGmsh(model_name="imported")
g.begin()
fem = g.loader.from_msh("model.msh", dim=2)
print(fem.physical.summary())
g.end()
Source code in src/apeGmsh/mesh/MshLoader.py
Legacy
Partition below is the standalone, pre-composite class. New code
should use the live g.mesh.partitioning composite documented above.
apeGmsh.mesh.Partition.Partition ¶
Bases: _HasLogging
Mesh-partitioning composite attached to a apeGmsh instance as
g.partition.
Wraps gmsh.model.mesh.partition / unpartition and the
partition-aware model queries exposed after partitioning.
Workflow¶
::
with apeGmsh(model_name="Cube") as g:
# build and mesh
g.model.geometry.add_box(0, 0, 0, 1, 1, 1)
g.model.sync()
g.mesh.generation.generate(3)
# auto-partition into 4 parts
g.partition.auto(4)
# inspect
print(g.partition.summary())
df = g.partition.entity_table()
# save — one combined file or one per partition
g.partition.save("cube_part.msh")
g.partition.save("cube", one_file_per_partition=True)
Or with an explicit element -> partition assignment::
elem_tags = [1, 2, 3, 4, 5, 6]
part_ids = [1, 1, 2, 2, 3, 4]
g.partition.explicit(4, element_tags=elem_tags,
partitions=part_ids)
Parameters¶
parent : _SessionBase The owning instance.
Source code in src/apeGmsh/mesh/Partition.py
auto ¶
Partition the current mesh into n_parts sub-domains using Gmsh's built-in partitioner (Metis when available).
Must be called after g.mesh.generation.generate().
Parameters¶
n_parts : number of partitions (≥ 1)
Returns¶
self — for chaining
Source code in src/apeGmsh/mesh/Partition.py
explicit ¶
Partition the mesh with an explicit per-element assignment.
Parameters¶
n_parts : total number of partitions declared element_tags : list of element tags to assign partitions : parallel list of partition IDs (1-based) for each element in element_tags
Returns¶
self — for chaining
Example¶
::
g.partition.explicit(
2,
element_tags=[1, 2, 3, 4],
partitions =[1, 1, 2, 2],
)
Source code in src/apeGmsh/mesh/Partition.py
unpartition ¶
renumber ¶
Compute and apply a node renumbering (e.g. RCMK bandwidth reduction) — commonly run after partitioning to improve solver performance.
Parameters¶
method : renumbering algorithm passed to
gmsh.model.mesh.computeRenumbering.
Supported values: "RCMK" (bandwidth reduction),
"Hilbert" (space-filling curve, good cache
locality), "Metis" (graph-partitioner ordering).
"RCMK" is the most commonly used default.
element_tags : restrict to a subset of elements (None = all)
Returns¶
self — for chaining
Source code in src/apeGmsh/mesh/Partition.py
n_partitions ¶
get_partitions ¶
Return the partition IDs that contain a given model entity.
Parameters¶
dim : entity dimension tag : entity tag
Returns¶
list[int] partition IDs (empty for non-partitioned entities)
Source code in src/apeGmsh/mesh/Partition.py
get_parent ¶
Return the (dim, tag) of the parent entity of a partitioned
sub-entity.
Parameters¶
dim : dimension of the partitioned entity tag : tag of the partitioned entity
Source code in src/apeGmsh/mesh/Partition.py
entity_table ¶
Build a DataFrame of all model entities and their partition membership.
Parameters¶
dim : restrict to a single dimension (-1 = all)
Returns¶
pd.DataFrame with columns:
dim entity dimension
tag entity tag
partitions comma-separated partition IDs (empty string = unpartitioned)
parent_dim parent entity dimension (-1 if top-level)
parent_tag parent entity tag (-1 if top-level)
Source code in src/apeGmsh/mesh/Partition.py
summary ¶
Return a concise text summary of the current partition state: number of partitions and a per-dimension entity count.
Source code in src/apeGmsh/mesh/Partition.py
save ¶
save(path: Path | str, *, one_file_per_partition: bool = False, create_topology: bool = False, create_physicals: bool = True) -> Partition
Write the partitioned mesh to file(s).
Parameters¶
path : output file path or base name.
The format is inferred from the extension
(".msh" is the natural choice for
partitioned meshes).
one_file_per_partition : when True, Gmsh writes one file per
partition alongside the combined file.
The per-partition files are named
<stem>_<k><suffix> (e.g.
mesh_1.msh, mesh_2.msh …).
create_topology : pass to Mesh.PartitionCreateTopology
create_physicals : pass to Mesh.PartitionCreatePhysicals
(keep True so solvers can find BC tags)
Returns¶
self — for chaining
Source code in src/apeGmsh/mesh/Partition.py
apeGmsh.mesh.View.View ¶
Bases: _HasLogging
Solver-agnostic post-processing view composite attached to a apeGmsh
instance as g.view.
Wraps gmsh.view to inject scalar and vector fields onto the active
mesh. No solver dependency — you compute the result arrays yourself
and pass them in.
Usage::
# Element-wise scalar (constant per element)
g.view.add_element_scalar("VonMises", elem_tags, values)
# Nodal scalar (smooth contour via Gmsh interpolation)
g.view.add_node_scalar("sigma_xx avg", node_tags, values)
# Nodal vector (displacement arrows / deformed shape)
g.view.add_node_vector("Displacement", node_tags, vectors)
All add_* methods return the Gmsh view tag (int).
Parameters¶
parent : _SessionBase
Owning instance — used for name and _verbose.
Source code in src/apeGmsh/mesh/View.py
add_element_scalar ¶
add_element_scalar(name: str, elem_tags: list[int] | ndarray, values: list[float] | ndarray, *, step: int = 0, time: float = 0.0) -> Tag
Add a scalar field with one value per element.
Parameters¶
name : view name shown in the Gmsh GUI sidebar
elem_tags : Gmsh element tags (from g.mesh.get_elements)
values : one scalar per element, same order as elem_tags
Returns¶
int Gmsh view tag
Source code in src/apeGmsh/mesh/View.py
add_element_vector ¶
add_element_vector(name: str, elem_tags: list[int] | ndarray, vectors: ndarray, *, step: int = 0, time: float = 0.0) -> Tag
Add a vector field with one 3-component vector per element.
Parameters¶
vectors : shape (nElem, 3) — [vx, vy, vz] per element
Source code in src/apeGmsh/mesh/View.py
add_node_scalar ¶
add_node_scalar(name: str, node_tags: list[int] | ndarray, values: list[float] | ndarray, *, step: int = 0, time: float = 0.0) -> Tag
Add a scalar field with one value per node.
Parameters¶
node_tags : Gmsh node tags values : one scalar per node, same order as node_tags
Source code in src/apeGmsh/mesh/View.py
add_node_vector ¶
add_node_vector(name: str, node_tags: list[int] | ndarray, vectors: ndarray, *, step: int = 0, time: float = 0.0, vector_type: int = 5) -> Tag
Add a vector field with one 3-component vector per node.
Parameters¶
vectors : shape (nNode, 2) or (nNode, 3) — missing components are zero-padded
vector_type : Gmsh display style (1=arrows, 2=cones, 5=displacement)
Source code in src/apeGmsh/mesh/View.py
list_views ¶
Algorithms & enums¶
apeGmsh.mesh._mesh_algorithms ¶
Algorithm / optimise constants + _normalize_algorithm helper.
Split out of the old monolithic Mesh.py so the generation
sub-composite can import the normaliser without pulling in the
main :class:~apeGmsh.mesh.Mesh.Mesh module.
The public names here are re-exported from apeGmsh.mesh.Mesh and
from the top-level apeGmsh package for backwards-compatible
imports.
Algorithm2D ¶
Bases: IntEnum
2-D meshing algorithm selector (legacy IntEnum form).
Prefer passing a string name to
:meth:apeGmsh.mesh.Mesh._Generation.set_algorithm — see
:data:ALGORITHM_2D and :class:MeshAlgorithm2D for the canonical
names and the accepted aliases.
Algorithm3D ¶
Bases: IntEnum
3-D meshing algorithm selector (legacy IntEnum form).
MeshAlgorithm2D ¶
Canonical 2-D algorithm names as string constants (IDE autocomplete).
MeshAlgorithm3D ¶
Canonical 3-D algorithm names as string constants (IDE autocomplete).
OptimizeMethod ¶
Mesh optimisation method names — use with g.mesh.generation.optimize.
apeGmsh.mesh._mesh_partitioning.RenumberResult ¶
RenumberResult(method: str, n_nodes: int, n_elements: int, bandwidth_before: int, bandwidth_after: int)
Result of a mesh renumbering operation.
Attributes¶
method : str
Algorithm used ("simple", "rcm", "hilbert", "metis").
n_nodes : int
Number of nodes renumbered.
n_elements : int
Number of elements renumbered.
bandwidth_before : int
Semi-bandwidth before renumbering.
bandwidth_after : int
Semi-bandwidth after renumbering.
Source code in src/apeGmsh/mesh/_mesh_partitioning.py
apeGmsh.mesh._mesh_partitioning.PartitionInfo ¶
PartitionInfo(n_parts: int, elements_per_partition: dict[int, int], weights_per_partition: dict[int, float] | None = None)
Result of a mesh partitioning operation.
Attributes¶
n_parts : int
Number of partitions created.
elements_per_partition : dict[int, int]
{partition_id: element_count}.
weights_per_partition : dict[int, float] | None
{partition_id: total_weight} when partition() was called
with weights=, otherwise None. Populated by
_gather_partition_info() from the per-element weight vector
cached on _Partitioning during the weighted call.
Source code in src/apeGmsh/mesh/_mesh_partitioning.py
Group sets¶
apeGmsh.mesh._group_set.PhysicalGroupSet ¶
Bases: NamedGroupSet
Snapshot of solver-facing physical groups.
Accessed via fem.nodes.physical / fem.elements.physical
(shared reference) and indirectly via
fem.nodes.select(pg="Base").
Source code in src/apeGmsh/mesh/_group_set.py
apeGmsh.mesh._group_set.LabelSet ¶
Bases: NamedGroupSet
Snapshot of geometry-time labels (Tier 1).
Accessed via fem.nodes.labels / fem.elements.labels
(shared reference) and indirectly via
fem.nodes.select(label="col.web").