Model — g.model¶
OCC geometry composite. Five focused sub-composites: geometry, boolean, transforms, io, queries.
g.model¶
apeGmsh.core.Model.Model ¶
Bases: _HasLogging
Geometry composite attached to an apeGmsh instance as
g.model. Owns five focused sub-composites:
g.model.geometry— point / curve / surface / solid primitivesg.model.boolean— fuse, cut, intersect, fragmentg.model.transforms— translate, rotate, scale, mirror, copy, extrude, revolve, sweep, thru_sectionsg.model.io— load/save STEP, IGES, DXF, MSH, heal_shapesg.model.queries— bounding_box, center_of_mass, mass, boundary, adjacencies, entities_in_bounding_box, registry
Plus entity selection:
g.model.select(...)— fluent spatial entity selection
And top-level utilities on the Model itself:
g.model.sync()— flush the OCC kernelg.model.viewer()— open the interactive Qt viewerg.model.render(path)— offscreen BRep still (ADR 0094 S4)g.model.gui()/g.model.launch_picker()— native Gmsh viewers
Example¶
::
# Solid boolean workflow
box = g.model.geometry.add_box(0, 0, 0, 10, 10, 10)
hole = g.model.geometry.add_cylinder(5, 5, 0, 0, 0, 10, 2)
part = g.model.boolean.cut(box, hole)
# Wire-frame -> surface workflow
p1 = g.model.geometry.add_point(0, 0, 0)
p2 = g.model.geometry.add_point(10, 0, 0)
p3 = g.model.geometry.add_point(10, 5, 0)
p4 = g.model.geometry.add_point(0, 5, 0)
l1 = g.model.geometry.add_line(p1, p2)
l2 = g.model.geometry.add_line(p2, p3)
l3 = g.model.geometry.add_line(p3, p4)
l4 = g.model.geometry.add_line(p4, p1)
loop = g.model.geometry.add_curve_loop([l1, l2, l3, l4])
surf = g.model.geometry.add_plane_surface(loop)
Parameters¶
parent : _SessionBase
Owning session — used to read _verbose and name.
Source code in src/apeGmsh/core/Model.py
sync ¶
Synchronise the OCC kernel with the gmsh model topology.
Call this explicitly when you have been batching operations with
sync=False. Returns self for chaining.
Source code in src/apeGmsh/core/Model.py
select ¶
Select geometry entities (faces, curves, volumes, points) to label or group them before meshing.
Use this to identify geometry for physical groups, boundary
conditions, or mesh sizing. Results are consumed with
.to_label() / .to_physical() / .to_dataframe()::
# mark all bottom faces as a label for later use
(g.model.select("BottomFaces")
.in_box((0, 0, 0), (10, 10, 0.01))
.to_label("base"))
# all surfaces that the z=1.5 plane crosses
(g.model.select(None, dim=2)
.crossing_plane({'z': 1.5}))
# all surfaces that straddle a plane through 3 points
(g.model.select(None, dim=2)
.crossing_plane([(0,0,0), (1,0,0), (0,1,0)]))
Returns an :class:~apeGmsh.core._selection.EntitySelection
(entity family) that chains spatial-refinement verbs and
terminates at .to_label() / .to_physical() /
.to_dataframe(). .result() is an alias that yields
the payload directly.
.. note::
Entity family — .in_box tests BRep bounding-box
containment (always closed, ~1e-8 tolerance), not
centroids. Passing inclusive= raises TypeError.
Use .on_plane(...) or .crossing_plane(...) for
exact boundary predicates. For mesh-level centroid-based
selection use :meth:fem.nodes.select /
:meth:fem.elements.select.
Parameters¶
target :
Label name, physical group name, part name,
(dim, tag) pair, raw int tag, or a list thereof.
A string resolves through label → PG → part name in
that order. Pass None (with dim=) to select
every entity at that dimension.
dim :
Topological dimension for bare int tags and
target=None (0=point, 1=curve, 2=surface,
3=volume). A label / physical group / part enumerates
every dimension it occupies; dim is not a
post-filter. When dim is given explicitly and the
target has no entity at that dimension, select
raises (rather than silently returning another
dimension) — chain .boundary() to walk a volume down
to its faces. Defaults to 3 when omitted (bare int tags /
target=None).
Refining verbs¶
Each returns a new EntitySelection and composes freely.
.in_box(lo, hi)— entities whose BRep bbox falls inside the query box (always closed, ~1e-8 expanded). Noinclusive=kwarg..in_sphere(center, radius).on_plane(point, normal, *, tol)— entities entirely on the plane withintol..crossing_plane(spec, *, tol=1e-6, mode="crossing")— entities that straddle, lie on, or avoid a geometric primitive.
spec accepts:
.. code-block:: python
{'z': 0} # axis-aligned plane
{'x': 3.5} # axis-aligned plane
[(0,0,0), (1,0,0), (0,1,0)] # plane through 3 pts
[(0,0,0), (0,0,1)] # infinite line, 2 pts
mode:
"crossing"(default) — straddles the primitive (corners on both sides)."on"— lies entirely on the primitive (all corners withintol).-
"not_crossing"/"not_on"— negations. -
.nearest_to(point, *, count=1) .where(predicate)|&-^(set algebra).
Terminals¶
.to_label(name)— assign the selection as a label..to_physical(name)— assign as a physical group..to_dataframe()—DataFramewith dim/tag columns..result()— raw :class:~apeGmsh.core._selection.Selectionpayload (also exposes.tags()/.to_label()/.to_physical()).
Source code in src/apeGmsh/core/Model.py
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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 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 | |
viewer ¶
Open the interactive Qt model viewer.
Displays BRep geometry with selectable entities, parts,
physical groups, and labels. This is a geometry-only
viewer — loads, constraints, and masses are mesh-resolved
concepts and live on g.mesh.viewer() instead.
Parameters¶
**kwargs :
Forwarded to
:class:~apeGmsh.viewers.model_viewer.ModelViewer
(e.g. physical_group, dims, point_size,
line_width, surface_opacity).
Source code in src/apeGmsh/core/Model.py
render ¶
render(path: 'str | Path', *, camera: str = 'iso', window_size: tuple[int, int] = (1280, 720)) -> 'Path | None'
Write one offscreen BRep still (ADR 0094 S4).
Live session only. Uses build_brep_scene (same tessellation
as :meth:viewer, including a throwaway coarse 2-D mesh when
none exists). 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.
Source code in src/apeGmsh/core/Model.py
preview ¶
Interactive WebGL preview of the BRep geometry.
Zero Qt dependency — works inline in Jupyter / VS Code / Colab,
or in a dedicated browser tab when browser=True. Hover over
a cell to see its dim and tag.
Parameters¶
dims : list of int, optional
BRep dimensions to render. Defaults to [0, 1, 2, 3].
browser : bool
If True, open in a new browser tab (temp HTML file)
instead of rendering inline. Useful when the notebook
output is cluttered or you want a dedicated window.
return_fig : bool
If True, skip display and return the raw
:class:plotly.graph_objects.Figure for saving with
fig.write_html('path.html') or composing a notebook
layout.
Source code in src/apeGmsh/core/Model.py
gui ¶
launch_picker ¶
launch_picker(*, show_points: bool = True, show_curves: bool = True, show_surfaces: bool = True, show_volumes: bool = False, verbose: bool = True) -> None
Open Gmsh's native FLTK viewer with entity labels pre-enabled.
Source code in src/apeGmsh/core/Model.py
Sub-composites¶
g.model.geometry¶
apeGmsh.core._model_geometry._Geometry ¶
Points, curves, surfaces, and solid primitive creation methods.
Source code in src/apeGmsh/core/_model_geometry.py
add_point ¶
add_point(x: float, y: float, z: float, *, mesh_size: float = 0.0, lc: float | None = None, label: str | None = None, sync: bool = True) -> Tag
Add a single point.
Parameters¶
x, y, z : coordinates mesh_size : target element size at this point (0 = use global size) lc : alias for mesh_size (Gmsh characteristic length)
Returns¶
int tag of the new point.
Source code in src/apeGmsh/core/_model_geometry.py
add_line ¶
Add a straight line segment between two existing points.
Parameters¶
start, end : point references — raw tag, label name, physical
group, part label, or (dim, tag). Each must resolve to
exactly one point.
Source code in src/apeGmsh/core/_model_geometry.py
add_imperfect_line ¶
add_imperfect_line(start: EntityRef, end: EntityRef, *, magnitude: float = 0.0, direction: tuple[float, float, float], shape: Literal['kink', 'sine', 'multi_mode'] = 'kink', n_segments: int = 8, modes: list[tuple[int, float]] | None = None, label: str | None = None, sync: bool = True) -> list[Tag]
Add a line with a built-in geometric imperfection.
Used for seeding initial out-of-straightness on columns, struts,
or braces before running a corotational / nonlinear buckling
analysis. The imperfection is baked into the geometry as a
polyline through intermediate points — there is no solver-side
perturbation. The resulting line segments are a drop-in
replacement for a single :meth:add_line call and can be
grouped into a single physical group via
m.physical.add_curve(tags=[...]).
Parameters¶
start, end : point tags
Endpoints of the imperfect line (straight-line length L).
magnitude : float
Peak perpendicular offset of the imperfection envelope.
Typical engineering choices are L/500 to L/1000.
Ignored when shape='multi_mode' — amplitudes come from
the per-mode entries of modes.
direction : (dx, dy, dz)
Direction hint for the offset. The vector is projected onto
the plane perpendicular to the line axis and normalized.
Only the perpendicular component matters; e.g. for a
diagonal brace you can pass (0, 1, 0) to request an
out-of-plane-Y offset and the method takes care of
orthogonality. Raises ValueError if the vector is
parallel to the line axis.
shape : str
* 'kink' — single midspan intermediate point, two
line segments. Produces a triangular bent; pedagogically
clean but not physically smooth.
* 'sine' — half-sine envelope
y(s) = magnitude · sin(π·s/L) discretized into
n_segments pieces. Matches the first Euler buckling
mode exactly; recommended for quantitative work.
* 'multi_mode' — superposition of multiple sinusoidal
modes, y(s) = Σ_k a_k · sin(k·π·s/L) where
(k, a_k) pairs come from modes. Used to seed
more than one buckling mode at once.
n_segments : int
Number of line pieces the imperfect line is split into.
Only meaningful for 'sine' (default 8) and
'multi_mode' (default 8). 'kink' always uses
exactly 2 segments regardless of this value.
modes : list[(int, float)], optional
Required when shape='multi_mode'. Each entry is a
(mode_number, amplitude) pair. The mode number k
must be a positive integer; the amplitude is absolute (not
relative to magnitude).
label : str, optional
Label applied to all resulting line segments. The
intermediate interior points remain anonymous (no labels).
sync : bool
Whether to synchronise the OCC kernel after creation.
Returns¶
list[Tag]
Line tags in geometric order from start to end.
Pass the list directly to m.physical.add_curve.
Examples¶
Kinked brace with an L/1000 midspan offset in the global-Y direction::
tags = m.model.geometry.add_imperfect_line(
p_base, p_top,
magnitude=L_brace/1000,
direction=(0, 1, 0),
shape='kink',
label='brace',
)
Half-sine imperfection discretised into 16 segments::
tags = m.model.geometry.add_imperfect_line(
p1, p2,
magnitude=L/500,
direction=(1, 0, 0),
shape='sine',
n_segments=16,
label='column',
)
First + third mode seeding::
tags = m.model.geometry.add_imperfect_line(
p1, p2,
direction=(0, 0, 1),
shape='multi_mode',
modes=[(1, L/1000), (3, L/5000)],
n_segments=24,
)
Source code in src/apeGmsh/core/_model_geometry.py
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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 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 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | |
replace_line ¶
replace_line(line_tag: Tag, *, magnitude: float = 0.0, direction: tuple[float, float, float], shape: Literal['kink', 'sine', 'multi_mode'] = 'kink', n_segments: int = 8, modes: list[tuple[int, float]] | None = None, sync: bool = True) -> list[Tag]
Retrofit an existing straight line with a geometric imperfection.
Use this when you built the frame with plain :meth:add_line
calls and then want to introduce an imperfection on a specific
member without rebuilding the whole geometry. The method:
- Validates that
line_tagpoints to a straight line (kind='line'in the model metadata; arcs, splines, and already-imperfect lines are rejected). - Looks up the two endpoint points from the line's boundary.
- Records every physical group (user-facing PGs and label
PGs of the form
_label:…) that contains the line. - Deletes the old curve — endpoints are preserved because other geometry likely references them.
- Calls :meth:
add_imperfect_linebetween the same endpoints to build the new polyline. - Re-wires every recorded physical group: the old line tag is swapped out and the new segment tags are spliced in, so any PG that used to reference the straight line now references the full imperfect polyline.
Parameters¶
line_tag : int
Tag of the existing straight line to replace.
magnitude, direction, shape, n_segments, modes :
Same semantics as :meth:add_imperfect_line.
sync : bool
Whether to synchronise the OCC kernel at the end.
Returns¶
list[Tag]
New line tags in geometric order. Same layout as
:meth:add_imperfect_line would return.
Source code in src/apeGmsh/core/_model_geometry.py
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 | |
sweep ¶
sweep(profile_face: Tag, path_curves: list[Tag], *, label: str | None = None, cleanup: bool = True, sync: bool = True) -> dict
Sweep a planar profile face along a chain of curves (a polyline path) to produce a 3-D solid volume.
Wraps gmsh.model.occ.addWire + gmsh.model.occ.addPipe
and — optionally — cleans up the intermediate geometry that
would otherwise cause trouble downstream:
- The profile face that was used as the input to the pipe. It persists as an orphan at the first station of the sweep, which means when you try to identify the start cap by bbox you pick up two coincident surfaces and their mesh nodes double up.
- The path curves themselves. These live along the
centroid line of the swept solid — i.e. inside the
volume — and Gmsh happily meshes them into
line2elements whose nodes sit interior to the tet mesh and are not shared with any tet4 element. Those become floating null-space DOFs if you emit them to OpenSees.
With cleanup=True (the default) both are removed after the
pipe has produced the volume, so the only surfaces left in the
model are the ones that actually bound the solid (the two end
caps + the n_path_segments * n_profile_edges ruled side
surfaces).
Parameters¶
profile_face : int
Tag of a planar surface that serves as the cross-section.
Most commonly built with addCurveLoop + addPlaneSurface
on a closed polyline of vertices. Must be perpendicular —
at least roughly — to the start of the path; Gmsh orients
the local frame automatically using the Frenet trihedron.
path_curves : list[int]
Ordered list of curve tags that form the path the profile
is swept along. Typically the return value of
:meth:add_imperfect_line or :meth:replace_line.
label : str, optional
If given, the resulting volume is labelled. End caps and
side surfaces remain unlabelled — run the usual
select_surfaces(in_box=…) + to_physical pass to
group them explicitly.
cleanup : bool
Remove the original profile face and path curves after
the pipe is built. Defaults to True. Set to False if you
want to preserve the profile/path for downstream use
(e.g. another sweep on a branched path).
sync : bool
Whether to synchronise the OCC kernel at the end.
Returns¶
dict
{'volume': tag, 'start_cap': tag, 'end_cap': tag}.
The caps are identified by scanning every new dim-2
entity's bounding box for one whose x_min == x_max ==
path_endpoint_x. If either cap cannot be identified its
entry is None.
Examples¶
Swept solid I-beam with a half-sine imperfection in the weak-axis direction::
# 1. Imperfect path
p0 = g.model.geometry.add_point(0, 0, 0, lc=200)
p1 = g.model.geometry.add_point(L, 0, 0, lc=200)
path = g.model.geometry.replace_line(
g.model.geometry.add_line(p0, p1),
magnitude=L/1000, direction=(0, 1, 0),
shape='sine', n_segments=16,
)
# 2. Rectangular profile at x = 0
corners = [
(0, -t/2, -h/2), (0, +t/2, -h/2),
(0, +t/2, +h/2), (0, -t/2, +h/2),
]
pts = [gmsh.model.occ.addPoint(*c) for c in corners]
lns = [gmsh.model.occ.addLine(pts[i], pts[(i+1) % 4])
for i in range(4)]
loop = gmsh.model.occ.addCurveLoop(lns)
profile = gmsh.model.occ.addPlaneSurface([loop])
gmsh.model.occ.synchronize()
# 3. Sweep
swept = g.model.geometry.sweep(profile, path, label='beam')
# swept['volume'] — the solid tag
# swept['start_cap'] — surface tag at path start
# swept['end_cap'] — surface tag at path end
Source code in src/apeGmsh/core/_model_geometry.py
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 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 | |
add_arc ¶
add_arc(start: EntityRef, center: EntityRef, end: EntityRef, *, through_point: bool = False, label: str | None = None, sync: bool = True) -> Tag
Add a circular arc defined by three existing points.
Parameters¶
start : point reference — start of the arc
center : point reference — interpretation depends on
through_point:
* ``through_point=False`` (default) — the **centre of the
circle** (not on the arc). All three points must be
equidistant from this centre.
* ``through_point=True`` — a point the arc **passes
through** (e.g. the apex of an arch). The circle is
fitted through ``start``, this point, and ``end``.
end : point reference — end of the arc
through_point : bool
Switches the meaning of center as above. Use
True for the common "arc through 3 points" case —
add_arc(left, apex, right, through_point=True) — where
you know a point on the arc but not the circle centre.
Each point accepts a raw tag, label name, physical group, part
label, or (dim, tag) and must resolve to exactly one point.
Note¶
With through_point=False the arc is the shorter of the
two possible arcs unless you reverse the start/end order.
See Also¶
:meth:apeGmsh.core._model_queries._Queries.make_conformal — when
an arc joins straight lines to form a closed wire, OCC may create
duplicate endpoint vertices at the arc-line junctions instead of
welding to the existing point tags. The wire then meshes as
disjoint pieces with no moment continuity at the corners. Call
g.model.queries.make_conformal(dims=[1]) after assembling the
wire to weld the topology.
Source code in src/apeGmsh/core/_model_geometry.py
add_arch ¶
add_arch(start: EntityRef, apex: EntityRef, end: EntityRef, *, label: str | None = None, sync: bool = True) -> list[Tag]
Add a circular arch through three points as two arcs that share the apex as a topological vertex.
Unlike :meth:add_arc with through_point=True — which fits
a single circular arc through start/apex/end and
leaves the apex as a floating construction point that the mesher
discards (so a physical group placed on the apex resolves to a
node that never makes it into the mesh) — add_arch builds the
arch as two arcs start -> apex and apex -> end of the
same circle. The apex is then a real vertex, guaranteeing a
conforming mesh node exactly at the crown — the node you want for
a crown load, a monitoring point, or a midspan physical group.
Both halves lie on one circle, so they are tangent-continuous at the apex (no geometric kink). The circle centre is computed from the three points, used to construct the arcs, then removed so it leaves no stray node at the centre of curvature.
Parameters¶
start, apex, end : point references — raw tag, label name,
physical group, part label, or (dim, tag). Each must
resolve to exactly one point. apex is a point on the
arch (the crown), not the circle centre.
label : str, optional
Label applied to both arc halves, so
g.labels.entities(label) (and any physical group promoted
from it) covers the whole arch.
sync : bool
Whether to synchronise the OCC kernel after creation.
Returns¶
list[Tag]
[arc_start_apex, arc_apex_end] in geometric order. Pass
the list directly to g.physical.add_curve.
Raises¶
ValueError If the three points are collinear or coincident (no circle is defined).
Note¶
Like :meth:add_arc, when the arch joins straight lines to form
a closed wire, OCC may create duplicate endpoint vertices at the
arc-line junctions. Call
g.model.queries.make_conformal(dims=[1]) after assembling the
wire to weld the topology.
See Also¶
:meth:add_arc — single-curve circular arc (apex not preserved
as a vertex).
Source code in src/apeGmsh/core/_model_geometry.py
818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 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 | |
add_circle ¶
add_circle(cx: float, cy: float, cz: float, radius: float, *, angle1: float = 0.0, angle2: float = 2 * math.pi, label: str | None = None, sync: bool = True) -> Tag
Add a full circle (or arc sector) as a single curve entity.
Unlike add_arc, this does not require pre-existing point
tags — it creates the circle directly from centre + radius.
Parameters¶
cx, cy, cz : centre radius : radius angle1 : start angle in radians (default 0) angle2 : end angle in radians (default 2π = full circle)
Note¶
Partial arcs (angle2 - angle1 < 2π) joined to other curves
in a closed wire are a classic source of disjoint topology — OCC
does not weld arc endpoints to existing point tags. After
assembling such a wire call
:meth:apeGmsh.core._model_queries._Queries.make_conformal
(g.model.queries.make_conformal(dims=[1])) to fragment-weld
the arc-line junctions.
Source code in src/apeGmsh/core/_model_geometry.py
add_ellipse ¶
add_ellipse(cx: float, cy: float, cz: float, r_major: float, r_minor: float, *, angle1: float = 0.0, angle2: float = 2 * math.pi, label: str | None = None, sync: bool = True) -> Tag
Add a full ellipse (or elliptic arc) as a single curve entity.
Parameters¶
cx, cy, cz : centre r_major : semi-major axis (along X before any rotation) r_minor : semi-minor axis angle1 : start angle in radians angle2 : end angle in radians
Note¶
Partial ellipses (angle2 - angle1 < 2π) joined to other curves
in a closed wire are a classic source of disjoint topology — OCC
does not weld ellipse endpoints to existing point tags. After
assembling such a wire call
:meth:apeGmsh.core._model_queries._Queries.make_conformal
(g.model.queries.make_conformal(dims=[1])) to fragment-weld
the arc-line junctions, or use
:meth:apeGmsh.mesh.FEMData.InspectComposite.find_coincident_node_pairs
on the resulting FEM to surface unbridged coincident nodes.
Source code in src/apeGmsh/core/_model_geometry.py
add_spline ¶
Add a C2-continuous spline curve through the given points (interpolating spline).
Parameters¶
point_tags : ordered list of point references the spline passes
through (raw tag, label, PG, part, or (dim, tag);
each must resolve to one point). Minimum 2 points;
for a closed spline repeat the first reference at the
end.
Example¶
::
p1 = g.model.geometry.add_point(0, 0, 0)
p2 = g.model.geometry.add_point(1, 1, 0)
p3 = g.model.geometry.add_point(2, 0, 0)
s = g.model.geometry.add_spline([p1, p2, p3])
Source code in src/apeGmsh/core/_model_geometry.py
add_bspline ¶
add_bspline(point_tags: list[EntityRef], *, degree: int = 3, weights: list[float] | None = None, knots: list[float] | None = None, multiplicities: list[int] | None = None, label: str | None = None, sync: bool = True) -> Tag
Add a B-spline curve with explicit control points.
Control points are not interpolated (the curve is attracted to
them, not forced through them), which is different from
add_spline.
Parameters¶
point_tags : control-point tags degree : polynomial degree (default 3 = cubic) weights : optional rational weights (len = len(point_tags)) knots : optional knot vector multiplicities : optional knot multiplicities
Source code in src/apeGmsh/core/_model_geometry.py
add_bezier ¶
Add a Bézier curve.
Parameters¶
point_tags : control-point tags. The curve starts at the first point and ends at the last; intermediate points are control handles (not interpolated).
Source code in src/apeGmsh/core/_model_geometry.py
add_polyline ¶
add_polyline(points, *, closed: bool = False, fillet: dict[int, float] | None = None, chamfer: dict[int, float] | None = None, label: str | None = None, sync: bool = True) -> list[Tag]
Add a polyline through 3-D control points, optionally closed, with per-vertex fillet or chamfer.
This is the missing builder named by :meth:add_arch's error
text (ADR 0097). Returns persistent curve tags — lines plus
any inserted fillet arcs / chamfer segments — suitable as a
sweep path (:meth:add_wire + :meth:sweep) or a closed
profile (:meth:add_curve_loop + :meth:add_plane_surface).
The OCC wire itself stays a transient construction object and
is not returned or labelled.
Parameters¶
points : sequence of (x, y, z)
Control vertices in order. A repeated closing vertex on a
closed polyline is dropped.
closed : bool
If True, connect the last vertex back to the first.
fillet : dict[int, float], optional
Vertex index → fillet radius. Trims both adjacent legs and
inserts a circular arc. Open-polyline endpoints cannot be
filleted. The same vertex cannot also appear in chamfer.
chamfer : dict[int, float], optional
Vertex index → setback distance. Trims both adjacent legs
and inserts a straight chamfer. Same endpoint / collision
rules as fillet.
label : str, optional
Label applied to all resulting curves as a group, so
g.labels.entities(label) covers the whole polyline.
sync : bool
Synchronise the OCC kernel after creation (default True).
Returns¶
list[Tag] Ordered curve tags (lines and arcs) along the polyline.
Raises¶
ValueError Degenerate input, fillet+chamfer on the same vertex, setback larger than an adjacent segment, or a collinear / U-turn corner asked to take a fillet.
Notes¶
Interior vertices of an open polyline whose turning angle
exceeds 30° with no fillet or chamfer emit
:class:WarnGeomSharpPolylineCorner — OCC addPipe kinks at
sharp path corners. Closed profiles do not warn (they are not
pipe paths).
Source code in src/apeGmsh/core/_model_geometry.py
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 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 | |
add_wire ¶
add_wire(curve_tags: list[EntityRef], *, check_closed: bool = False, label: str | None = None, sync: bool = True) -> Tag
Assemble an ordered list of curve tags into an OpenCASCADE wire
(open or closed). Wires are the path input for sweep operations
(:meth:sweep) and the section input for lofted volumes
(:meth:thru_sections).
Unlike :meth:add_curve_loop, a wire does not need to be
closed. This is what makes it suitable as a sweep path.
Parameters¶
curve_tags : ordered curve references (raw tag, label, PG, part,
or (dim, tag); each must resolve to one curve). A
leading '-' on a label name — or a negative tag —
reverses that curve's orientation. Curves must be connected
end-to-end but may share only geometrically identical
endpoints (OCC allows topologically distinct but coincident
points).
check_closed : if True, the underlying OCC call verifies that
the wire forms a closed loop and raises otherwise.
label : not supported — passing a non-None value raises
ValueError (see Note).
Returns¶
int tag of the new OCC wire. This is not a persistent,
meshable model entity — use it immediately as the path
argument to :meth:sweep or an element of wires for
:meth:thru_sections.
Note¶
An OpenCASCADE wire is a transient construction object, not a
model entity. Its tag is allocated in the curve tag-space and,
after synchronize(), it does not appear as its own
dim=1 entity — the tag instead aliases one of the member
curves. Consequently the wire is not added to the entity
registry, and label= is rejected: a label would silently
attach the name to an unrelated curve. To name the member
curves as a group, group the curves themselves, e.g.
m.model.select([c1, c2, c3]).to_physical(name=...).
Example¶
::
p0 = g.model.geometry.add_point(0, 0, 0, sync=False)
p1 = g.model.geometry.add_point(1, 0, 0, sync=False)
p2 = g.model.geometry.add_point(1, 1, 0, sync=False)
p3 = g.model.geometry.add_point(1, 1, 2, sync=False)
l1 = g.model.geometry.add_line(p0, p1, sync=False)
l2 = g.model.geometry.add_line(p1, p2, sync=False)
l3 = g.model.geometry.add_line(p2, p3, sync=False)
path = g.model.geometry.add_wire([l1, l2, l3])
g.model.transforms.sweep(section, path)
Source code in src/apeGmsh/core/_model_geometry.py
1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 | |
add_curve_loop ¶
Assemble an ordered list of curve references into a closed wire
(curve loop). The result is used as input to
add_plane_surface or add_surface_filling.
Parameters¶
curve_tags : ordered curve references forming a closed loop
(raw tag, label, PG, part, or (dim, tag); each
must resolve to one curve). Reverse a curve's
orientation with a negative tag or a leading
'-' on its label name, e.g. '-col_right'.
Example¶
::
loop = g.model.geometry.add_curve_loop([l1, l2, l3, l4])
surf = g.model.geometry.add_plane_surface(loop)
# by label, with one reversed curve
loop = g.model.geometry.add_curve_loop(
['col_left', 'arch', '-col_right'])
Source code in src/apeGmsh/core/_model_geometry.py
add_plane_surface ¶
add_plane_surface(wire_tags: EntityRef | list[EntityRef], *, label: str | None = None, sync: bool = True, as_void: bool = False) -> Tag
Create a planar surface bounded by one or more curve loops.
Parameters¶
wire_tags : reference (or list of references) to curve loops —
raw tag, label, PG, part, or (dim, tag); each
must resolve to one curve loop. The first loop is
the outer boundary; any additional loops define holes.
as_void : bool
If True, mark the surface as a 2-D boolean tool (ADR 0097).
Example¶
::
outer = g.model.geometry.add_curve_loop([l1, l2, l3, l4])
hole = g.model.geometry.add_curve_loop([h1, h2, h3, h4])
surf = g.model.geometry.add_plane_surface([outer, hole])
Source code in src/apeGmsh/core/_model_geometry.py
add_surface_filling ¶
Create a surface filling bounded by a single curve loop, using a Coons-patch style interpolation (non-planar surfaces).
Parameters¶
wire_tag : reference to the bounding curve loop — raw tag,
label, PG, part, or (dim, tag); must resolve to
one curve loop.
Source code in src/apeGmsh/core/_model_geometry.py
add_rectangle ¶
add_rectangle(x: float, y: float, z: float, dx: float, dy: float, *, plane: Literal['xy', 'yz', 'xz'] = 'xy', angles_deg: tuple[float, float, float] | None = None, angles_rad: tuple[float, float, float] | None = None, pivot: tuple[float, float, float] = (0.0, 0.0, 0.0), rounded_radius: float = 0.0, label: str | None = None, sync: bool = True, as_void: bool = False) -> Tag
Add a rectangular planar surface on one of the canonical planes.
The rectangle's corner is anchored at (x, y, z) and its
extents dx/dy run along the two in-plane axes selected by
plane:
========= =============== =============== ================
plane dx axis dy axis constant
========= =============== =============== ================
'xy' world X world Y z (default)
'xz' world X world Z y
'yz' world Y world Z x
========= =============== =============== ================
For a fully arbitrary orientation, build on the nearest canonical
plane and rotate in place with angles_deg / angles_rad —
three angles applied as successive rotations about world X, then Y,
then Z, through a pivot point measured as an offset from the
rectangle's geometric centre. (For a centre-anchored square with
an arbitrary normal, see :meth:add_cutting_plane.)
Useful as a cutting tool for :meth:fragment — a 2D rectangle
fragmented against a 3D solid splits the solid along the
rectangle's plane.
Parameters¶
x, y, z : float
Corner of the rectangle.
dx, dy : float
Extents along the two in-plane axes selected by plane
(see the table above).
plane : {'xy', 'yz', 'xz'}
Canonical plane the rectangle lives on. Default 'xy'.
angles_deg, angles_rad : (rx, ry, rz), optional
Rotation angles about world X, Y, Z, applied in that order
through pivot. Pass exactly one of the two — supplying
both raises ValueError. Either may be None (no
rotation).
pivot : (px, py, pz)
Pivot point expressed as an offset from the rectangle's
centre. (0, 0, 0) (default) rotates about the centre;
(dx/2, dy/2, 0) would rotate about the bottom-left
corner, etc. Ignored when no angles are given.
rounded_radius : float
If > 0, rounds the four corners with this radius.
label : str, optional
Human-readable label stored in the internal registry.
sync : bool
Synchronise the OCC kernel after creation (default True).
Returns¶
Tag Surface tag of the new rectangle.
Example¶
::
# Split a solid at mid-height with a cutting plane
bb = gmsh.model.getBoundingBox(3, 1)
xmin, ymin, zmin, xmax, ymax, zmax = bb
zmid = (zmin + zmax) / 2
pad = 1.0
rect = m1.model.geometry.add_rectangle(
xmin - pad, ymin - pad, zmid,
(xmax - xmin) + 2*pad,
(ymax - ymin) + 2*pad,
)
result = m1.model.boolean.fragment(objects=[1], tools=[rect], dim=3)
# Inclined crack plane: 30 about X through the centre
m.model.geometry.add_rectangle(
-10, -10, 0, 20, 20,
angles_deg=(30, 0, 0), label='plane',
)
# A vertical wall on the YZ plane at x = 0, corner at origin
g.model.geometry.add_rectangle(0, 0, 0, 4, 3, plane='yz')
Source code in src/apeGmsh/core/_model_geometry.py
1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 | |
add_cutting_plane ¶
add_cutting_plane(point: list[float] | ndarray, normal_vector: list[float] | ndarray, *, size: float | None = None, label: str | None = None, sync: bool = True) -> Tag
Create a square planar surface through point with the given
normal, suitable for clipping / section / visualisation views.
The surface is a plain BRep face built from 4 points + 4 lines + a curve loop + a plane surface, so it behaves exactly like any other registered surface (it can be selected, meshed as a discrete 2-D grid, exported to STEP, etc.). It is not a Gmsh clipping plane in the rendering sense — it is real geometry.
Parameters¶
point : array-like of 3 floats
A point on the plane. The square is centred here.
normal_vector : array-like of 3 floats
Plane normal. Need not be unit-length — it is normalised
internally.
size : float, optional
Edge length of the square. When None (default), size
is picked as 2 × max(model_bbox_diagonal, 1.0) so the
square comfortably overhangs the current model.
label : str, optional
Human-readable label stored in the internal registry.
sync : bool, optional
Synchronise the OCC kernel after creation (default True).
Returns¶
Tag Surface tag of the new cutting plane.
Example¶
::
# A vertical plane through (0, 0, 0) with normal (1, 0, 0)
g.model.geometry.add_cutting_plane(
point=(0, 0, 0), normal_vector=(1, 0, 0),
)
Source code in src/apeGmsh/core/_model_geometry.py
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 | |
add_axis_cutting_plane ¶
add_axis_cutting_plane(axis: Literal['x', 'y', 'z'], offset: float = 0.0, *, origin: list[float] | ndarray | None = None, rotation: float = 0.0, rotation_about: Literal['x', 'y', 'z'] | None = None, label: str | None = None, sync: bool = True) -> Tag
Add an axis-aligned cutting plane, optionally tilted by a rotation.
Convenience wrapper around :meth:add_cutting_plane. The plane is
initially defined as normal to axis (so axis='z' produces
a horizontal XY-plane). It is then:
- Offset along its base normal by
offset. - Rotated by
rotationdegrees aboutrotation_about(if both are given), producing a tilted plane through the same anchor point.
Parameters¶
axis : {'x', 'y', 'z'}
Axis the plane is normal to. 'z' -> XY plane, etc.
offset : float, optional
Signed distance along the base normal from origin
(or from the global origin if origin is None).
origin : array-like of 3 floats, optional
Anchor point before the offset is applied. Defaults to (0, 0, 0).
rotation : float, optional
Rotation angle in degrees. Requires rotation_about
to have any effect — passing rotation without
rotation_about raises ValueError so silent
no-ops do not sneak through.
rotation_about : {'x', 'y', 'z'}, optional
Axis about which the base normal is rotated. Must differ
from axis for the rotation to have any effect.
label : str, optional
Human-readable label stored in the internal registry.
sync : bool, optional
Synchronise the OCC kernel after creation (default True).
Returns¶
Tag Surface tag of the new cutting plane.
Examples¶
Horizontal plane at z = 3::
g.model.geometry.add_axis_cutting_plane('z', offset=3.0)
Vertical YZ-plane passing through x = 1.5::
g.model.geometry.add_axis_cutting_plane('x', offset=1.5)
Horizontal plane tilted 15° about the y-axis::
g.model.geometry.add_axis_cutting_plane(
'z', offset=0.0,
rotation=15.0, rotation_about='y',
)
Source code in src/apeGmsh/core/_model_geometry.py
1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 | |
cut_by_surface ¶
cut_by_surface(solid: Tag | str | list[Tag | str] | None, surface, *, keep_surface: bool = True, remove_original: bool = True, label: str | None = None, tolerance: float | None = None) -> list[Tag]
Split one or more solids with an arbitrary cutting surface.
Uses OCC's fragment operation under the hood, which splits
every input shape at its intersections and keeps all
resulting sub-shapes. Unlike :meth:cut_by_plane, this method
does not classify the output pieces — callers that need
"above/below" semantics should use :meth:cut_by_plane (which
delegates here and adds the classification step).
After the fragment, :func:sweep_dangling reaps any free-floating
dim<=2 entities that bound no surviving volume (so callers never
see the cutting plane's corner points / edges / trimmed surface
as orphans), plus any stale _metadata entry whose tag was
consumed by OCC. When keep_surface=False the tool surface
itself is forced into the sweep's removal set.
Parameters¶
solid : Tag, list[Tag], or None
Volume(s) to cut. When None, every registered volume
in the model is cut against the surface.
surface : Tag, str, or (2, tag)
The cutting surface. Can be any registered 2-D entity —
a plane from :meth:add_cutting_plane, a STEP-imported
trimmed surface, a Coons patch, etc. Accepts a raw tag,
a label or PG name, or an explicit (2, tag) tuple.
Must resolve to exactly one surface.
keep_surface : bool, default True
Leave the (now-trimmed) surface in the model after the
cut. Useful when you want to mesh the cut interface as a
shared face for conformal ties. Set to False to
delete it.
remove_original : bool, default True
Consume the original solid(s) so only the cut pieces
remain. When False, OCC keeps the originals alongside
the pieces, which usually produces overlapping geometry
and is rarely what you want.
label : str, optional
Label applied to every new volume fragment in the
registry. Pass None to leave the fragments unlabelled.
tolerance : float, optional
Override Geometry.ToleranceBoolean for the duration of
the fragment (restored afterwards). Raise it (e.g.
tolerance=1e-3 on a mm-scale model) when a near-
coincident cutting surface defeats OCC's default
coincidence detection and the cut produces nothing or leaves
debris. None (default) leaves the global tolerance
unchanged.
Returns¶
list[Tag] Solid tags of the fragments produced by the cut, in the order OCC returns them. An empty list means the cut produced nothing new (shouldn't happen unless the surface misses every input solid entirely).
Example¶
::
box = g.model.geometry.add_box(0, 0, 0, 1, 1, 1)
plane = g.model.geometry.add_axis_cutting_plane('z', offset=0.5)
pieces = g.model.geometry.cut_by_surface(box, plane)
Source code in src/apeGmsh/core/_model_geometry.py
2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 | |
cut_by_plane ¶
cut_by_plane(solid: Tag | str | list[Tag | str] | None, plane, *, keep_plane: bool = True, remove_original: bool = True, above_direction: list[float] | ndarray | None = None, label_above: str | None = None, label_below: str | None = None, sync: bool = True, tolerance: float | None = None) -> tuple[list[Tag], list[Tag]]
Split one or more solids with a plane and classify the resulting pieces by which side of the plane they sit on.
Thin wrapper around :meth:cut_by_surface that additionally
computes which fragments are "above" (same side as the plane
normal) vs "below" the plane. The normal direction is
resolved from, in order of priority:
- An explicit
above_directionargument. - The
normalandpointstashed in the registry by :meth:add_cutting_plane/ :meth:add_axis_cutting_plane. gmsh.model.getNormalsampled at the parametric centre of the plane surface.
Parameters¶
solid : Tag, list[Tag], or None
Volume(s) to cut. None = every registered volume.
plane : Tag
Planar surface to cut with. Accepts a raw tag, a label
or PG name, or an explicit (2, tag) tuple — must
resolve to exactly one 2-D entity. Ideally built by
:meth:add_cutting_plane so its normal and point are in
the registry; other planar surfaces work too but require
an explicit above_direction or fall back to querying
Gmsh.
keep_plane : bool, default True
Leave the trimmed plane in the model as a registered
surface (useful for meshing the cut interface).
remove_original : bool, default True
Consume the original solid(s).
above_direction : array-like of 3 floats, optional
Override the plane's normal direction. Pieces whose
centroid dotted with this vector (relative to the plane
point) is positive are classified as "above".
label_above, label_below : str, optional
Labels applied to the above / below fragment solids.
sync : bool, default True
Synchronise the OCC kernel after the cut.
Returns¶
tuple[list[Tag], list[Tag]]
(above_tags, below_tags) — solid tags on each side of
the plane, classified by the sign of
(centroid - plane_point) · normal.
Example¶
::
col = g.model.geometry.add_box(0, 0, 0, 1, 1, 3)
pl = g.model.geometry.add_axis_cutting_plane('z', offset=1.5)
top, bot = g.model.geometry.cut_by_plane(
col, pl,
label_above="col_upper", label_below="col_lower",
)
Source code in src/apeGmsh/core/_model_geometry.py
2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 | |
slice ¶
slice(target: Tag | str | list[Tag | str] | None = None, *, axis: Literal['x', 'y', 'z'], offset: float = 0.0, point: list[float] | ndarray | None = None, dim: SliceDim = 'all', classify: bool = False, label: str | None = None, sync: bool = True, tolerance: float | None = None) -> list[Tag] | tuple[list[Tag], list[Tag]]
Slice entities at an axis-aligned plane in one atomic call.
Internally creates a temporary cutting plane, fragments the
target entities, removes the cutting plane (and any trimmed
geometry it left behind), and returns the fragments. Runs
:func:sweep_dangling after the cut so no orphaned dim<=2
geometry survives — even when the cutting plane is coincident
with an existing face of the operand. If the plane is
coincident with an existing face, :class:WarnGeomCoincidentFace
fires first as an advisory; the sweep cleans up regardless.
The plane location is given either as offset (signed
distance from the global origin along the axis) or as
point (a point the plane passes through) — not both.
Parameters¶
target : Tag, str, list, or None
Entity (or entities) to slice — a raw tag, a label name, or
a list of either. None slices everything the plane
crosses, governed by dim. (Renamed from solid; the
operation is no longer volume-only.)
axis : {'x', 'y', 'z'}
Axis the plane is normal to. 'z' slices with
a horizontal XY-plane, etc.
offset : float, default 0.0
Signed distance along the axis from the global origin.
Mutually exclusive with point.
point : array-like of 3 floats, optional
A point the cutting plane passes through. Only the
coordinate along axis matters (the plane is axis-aligned),
but a full 3-vector is accepted for convenience. Mutually
exclusive with a non-zero offset.
dim : {1, 2, 3, 'all'}, default 'all'
Which entity dimension to slice. 'all' (default) slices
every maximal entity in the model — volumes in a solid
model, surfaces in a shell model, curves in a frame model —
which collapses to the historical volume-only behaviour for
solid models. An explicit 1 / 2 / 3 restricts
the cut to entities of exactly that dimension. Bare integer
targets under 'all' resolve to their highest dimension.
classify : bool, default False
When True, returns (positive_side, negative_side)
classified by the plane's normal direction (the positive
axis direction). When False (default), returns all
fragments as a flat list.
label : str, optional
Label applied to every fragment in the registry.
sync : bool, default True
Synchronise the OCC kernel after the operation.
Returns¶
list[Tag]
All fragment tags (when classify=False).
tuple[list[Tag], list[Tag]]
(positive_side, negative_side) fragments classified
by which side of the plane each piece's centroid sits on
(when classify=True).
Example¶
::
# Slice a box at y = 0.5
box = g.model.geometry.add_box(0, 0, 0, 1, 1, 1)
pieces = g.model.geometry.slice(box, axis='y', offset=0.5)
# Slice through a point instead of an offset
g.model.geometry.slice(box, axis='z', point=(0, 0, 0.5))
# Slice and classify
top, bot = g.model.geometry.slice(
box, axis='z', offset=0.5, classify=True,
)
# Slice every shell surface at x = 0
g.model.geometry.slice(axis='x', offset=0.0, dim=2)
Source code in src/apeGmsh/core/_model_geometry.py
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 | |
find_orphans ¶
Inspect the model for orphan geometry without modifying it.
Returns the dimtags that :meth:remove_orphans (and the
post-op sweep that runs internally inside
:meth:slice / :meth:cut_by_surface / :meth:cut_by_plane
/ :meth:_Boolean.fragment) would reap: dim<=2 entities that
bound no registered volume and are not user-intentional (not
in model._metadata, no label).
Returns¶
dict[int, list[int]]
{0: [...], 1: [...], 2: [...]} — orphan tags at every
dim <= 2. An empty list at every key means the model is
clean.
Source code in src/apeGmsh/core/_model_geometry.py
remove_orphans ¶
Run the orphan sweep manually.
Identical algorithm to the post-op sweep the cut / fragment operations run internally — exposed so callers can clean up after a hand-written OCC operation or after pickling / re-loading geometry from a side channel.
Parameters¶
dry_run
When True, behave like :meth:find_orphans (no
modification) but return the same dict shape.
Returns¶
dict[int, list[int]]
{dim: [tags]} — the tags that were (or would be)
removed.
Source code in src/apeGmsh/core/_model_geometry.py
find_stale_metadata ¶
Return model._metadata keys whose tag is no longer in OCC.
Closed-world inspection. Walks only the entries the
apeGmsh add_* / boolean / cut / fragment primitives
recorded — never the live OCC entity list. By construction
it cannot false-positive on raw gmsh.model.geo.* /
gmsh.model.occ.* workflows: those workflows don't
populate _metadata in the first place, so any key the
check inspects came from apeGmsh's own code, and a stale key
means an apeGmsh-managed entity was consumed without a
matching cleanup.
Counterpart to :meth:find_orphans, which does the full
open-world scan and so MUST stay opt-in (see
:meth:validate_pre_mesh rationale below).
Returns¶
list[tuple[int, int]]
Stale (dim, tag) keys, in iteration order. Empty
list means every registered key still points at a live
OCC entity.
Source code in src/apeGmsh/core/_model_geometry.py
validate_pre_mesh ¶
Raise :class:GeometryValidationError on pre-mesh hazards.
Two modes, gated by strict:
strict=False(default; what :meth:Mesh.generateauto-invokes) — runs :meth:find_stale_metadataonly. Closed-world. Catches the actual leak class the audit was chasing: an apeGmsh boolean / cut / fragment op consumed an entity without cleaning its_metadatakey. Cannot false-positive on raw-gmsh.model.geo.*workflows (they don't populate_metadata).strict=True(opt-in) — runs :meth:find_orphansand raises on any orphan dim<=2 entity. Open-world. Users opt in when they know their build script stays inside the apeGmsh facade (_metadata+g.labelschannels); raw-gmsh users WILL trip it on legitimate models.
The split is deliberate: closed-world is the auto-fire mode because it cannot punish users for working below the apeGmsh facade. Open-world is opt-in for the same reason.
Mirrors :meth:MassesComposite.validate_pre_mesh /
:meth:LoadsComposite.validate_pre_mesh /
:meth:ConstraintsComposite.validate_pre_mesh (those are
intrinsically closed-world; the strict=False default
here matches the same contract — only inspect what the
composite itself recorded).
Source code in src/apeGmsh/core/_model_geometry.py
2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 | |
add_box ¶
add_box(x: float, y: float, z: float, dx: float, dy: float, dz: float, *, label: str | None = None, sync: bool = True, as_void: bool = False) -> Tag
Add an axis-aligned box.
Parameters¶
x, y, z : origin corner
dx, dy, dz : extents along X, Y, Z
as_void : bool
If True, mark the box as a boolean tool (ADR 0097). It
must be subtracted via :meth:_Boolean.cut /
:meth:_Boolean.apply_voids before generate().
Source code in src/apeGmsh/core/_model_geometry.py
add_sphere ¶
add_sphere(cx: float, cy: float, cz: float, radius: float, *, label: str | None = None, sync: bool = True, as_void: bool = False) -> Tag
Add a sphere centred at (cx, cy, cz) with the given radius.
as_void=True marks the sphere as a boolean tool (ADR 0097).
Source code in src/apeGmsh/core/_model_geometry.py
add_cylinder ¶
add_cylinder(x: float, y: float, z: float, dx: float, dy: float, dz: float, radius: float, *, angle: float = 2 * math.pi, label: str | None = None, sync: bool = True, as_void: bool = False) -> Tag
Add a cylinder.
Parameters¶
x, y, z : base-circle centre dx, dy, dz : axis direction vector (length = height of cylinder) radius : base radius angle : sweep angle in radians (default 2π = full cylinder) as_void : bool If True, mark the cylinder as a boolean tool (ADR 0097).
Source code in src/apeGmsh/core/_model_geometry.py
add_cone ¶
add_cone(x: float, y: float, z: float, dx: float, dy: float, dz: float, r1: float, r2: float, *, angle: float = 2 * math.pi, label: str | None = None, sync: bool = True, as_void: bool = False) -> Tag
Add a cone / truncated cone.
Parameters¶
x, y, z : base-circle centre dx, dy, dz : axis vector r1 : base radius r2 : top radius (0 = sharp cone) angle : sweep angle in radians as_void : bool If True, mark the cone as a boolean tool (ADR 0097).
Source code in src/apeGmsh/core/_model_geometry.py
add_torus ¶
add_torus(cx: float, cy: float, cz: float, r1: float, r2: float, *, angle: float = 2 * math.pi, label: str | None = None, sync: bool = True, as_void: bool = False) -> Tag
Add a torus.
Parameters¶
cx, cy, cz : centre r1 : major radius (axis to tube centre) r2 : minor radius (tube cross-section) angle : sweep angle in radians as_void : bool If True, mark the torus as a boolean tool (ADR 0097).
Source code in src/apeGmsh/core/_model_geometry.py
add_wedge ¶
add_wedge(x: float, y: float, z: float, dx: float, dy: float, dz: float, ltx: float, *, label: str | None = None, sync: bool = True, as_void: bool = False) -> Tag
Add a right-angle wedge.
Parameters¶
x, y, z : origin corner dx, dy, dz : extents ltx : top X extent (0 = sharp wedge) as_void : bool If True, mark the wedge as a boolean tool (ADR 0097).
Source code in src/apeGmsh/core/_model_geometry.py
add_void_sweep ¶
Sweep a profile along a path and mark the solid as a void tool.
Orchestration over the shipped pipe (ADR 0097) — does not add a
third sweep. A list of path curve tags delegates to
:meth:sweep (interior path cleanup). A wire tag delegates to
:meth:_Transforms.sweep.
Parameters¶
profile : surface ref or list of curve tags
Existing dim-2 face, or a closed curve-tag list (typically
from :meth:add_polyline with closed=True) that is
promoted to a plane surface.
path : list of curve tags, or a wire tag
Sweep trajectory. Pass a list of curve tags from
:meth:add_polyline; a 2-tuple is a dimtag, not two curves.
label : str, optional
Label on the resulting volume.
sync : bool
Synchronise the OCC kernel after the sweep (default True).
Returns¶
Tag
Volume tag of the void tool. Subtract it with
:meth:_Boolean.cut or :meth:_Boolean.apply_voids.
Source code in src/apeGmsh/core/_model_geometry.py
3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 | |
add_void_loft ¶
add_void_loft(sections: list, *, make_solid: bool = True, make_ruled: bool = False, label: str | None = None, sync: bool = True) -> Tag
Loft through two or more section polylines and mark the solid as a void tool.
Delegates to :meth:_Transforms.thru_sections (ADR 0097).
When every section is a curve-tag list, sub-curve counts must
match (fillet the same vertices on every section).
Parameters¶
sections : list of curve-tag lists or wire tags
At least two. Curve-tag lists typically come from
:meth:add_polyline with closed=True.
make_solid, make_ruled
Forwarded to :meth:_Transforms.thru_sections.
label : str, optional
Label on the highest-dimension survivor.
sync : bool
Synchronise the OCC kernel after the loft (default True).
Returns¶
Tag
Volume (or surface, if make_solid=False) tag of the
void tool.
Source code in src/apeGmsh/core/_model_geometry.py
3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 | |
g.model.boolean¶
apeGmsh.core._model_boolean._Boolean ¶
Boolean-operation sub-composite extracted from Model.
Source code in src/apeGmsh/core/_model_boolean.py
fuse ¶
fuse(objects: EntityRefs, tools: EntityRefs, *, dim: int = 3, remove_object: bool = True, remove_tool: bool = True, sync: bool = True, label: str | None = None, tolerance: float | None = None) -> list[Tag]
Boolean union (A ∪ B). Returns surviving volume tags.
When label= is supplied, the labels carried by the inputs
are dropped from the result and the new label is attached
instead. Without label=, all input labels survive on the
merged volume.
tolerance optionally overrides Geometry.ToleranceBoolean
for the duration of this op (restored after) — bump it (e.g.
tolerance=1e-3 for mm-scale models) when near-coincident
faces defeat OCC's default coincidence detection. None
(default) leaves the current global tolerance unchanged.
Example¶
result = g.model.boolean.fuse(box, sphere, label='merged')
Source code in src/apeGmsh/core/_model_boolean.py
cut ¶
cut(objects: EntityRefs, tools: EntityRefs, *, dim: int = 3, remove_object: bool = True, remove_tool: bool = True, sync: bool = True, label: str | None = None, tolerance: float | None = None) -> list[Tag]
Boolean difference (A − B). Returns surviving volume tags.
When label= is supplied, the object's label is dropped
from the result and the new label is attached instead.
tolerance optionally overrides Geometry.ToleranceBoolean
for the duration of this op (see :meth:fuse); None
(default) leaves the current global tolerance unchanged.
Example¶
result = g.model.boolean.cut(box, cylinder, label='holey')
Source code in src/apeGmsh/core/_model_boolean.py
apply_voids ¶
apply_voids(host: EntityRefs, *, remove_object: bool = True, remove_tool: bool = True, sync: bool = True, label: str | None = None, tolerance: float | None = None) -> list[Tag]
Subtract every unapplied as_void tool from host.
Collects live model._metadata entries with role="void"
at the host's dimension and delegates to :meth:cut (ADR 0097).
Tools at a different dimension than the host are ignored (a
dim-2 opening does not cut a volume, and vice versa).
Parameters¶
host : entity ref(s)
The body (or face) to cut. All host entities must share
one dimension.
remove_object, remove_tool, sync, label, tolerance
Forwarded to :meth:cut. remove_tool=True (default)
consumes the void bodies so they cannot be meshed as
solids.
Returns¶
list[Tag] Surviving host tags after the cut.
Raises¶
ValueError Host is empty, mixed-dimension, or there are no void tools at the host dimension.
Source code in src/apeGmsh/core/_model_boolean.py
intersect ¶
intersect(objects: EntityRefs, tools: EntityRefs, *, dim: int = 3, remove_object: bool = True, remove_tool: bool = True, sync: bool = True, label: str | None = None, tolerance: float | None = None) -> list[Tag]
Boolean intersection (A ∩ B). Returns surviving volume tags.
When label= is supplied, the input labels are dropped from
the intersection and the new label is attached instead.
tolerance optionally overrides Geometry.ToleranceBoolean
for the duration of this op (see :meth:fuse); None
(default) leaves the current global tolerance unchanged.
Source code in src/apeGmsh/core/_model_boolean.py
fragment ¶
fragment(objects: EntityRefs, tools: EntityRefs, *, dim: int = 3, remove_object: bool = True, remove_tool: bool = True, cleanup_free: bool = True, sync: bool = True, tolerance: float | None = None) -> list[Tag]
Boolean fragment — splits all shapes at their intersections and preserves all sub-volumes (useful for conformal meshing).
Parameters¶
objects : tag(s) of the entities to fragment.
tools : tag(s) of the cutting entities (e.g. rectangles).
Dimensions are auto-resolved from the registry, so bare
integer tags work even when tools have a different dimension
than dim.
dim : target dimension for bare integer tags in objects
(default 3).
remove_object, remove_tool : passed to OCC (default True).
cleanup_free : bool, default True
When True, run :func:sweep_dangling after the fragment to
reap free-floating dim<=2 entities that bound no surviving
volume AND are not user-intentional (not in
model._metadata, not carrying a label). The previous
centroid-in-bbox heuristic over-collected shell-on-solid
geometry whose centroid happened to fall outside a volume
bbox; the topology-driven sweep preserves any standalone
shell the user explicitly created (add_rectangle,
add_plane_surface, etc.) because those entities live
in _metadata. Default flipped to True once the
safer sweep landed; pass cleanup_free=False only when
you need OCC's raw output (no orphan removal, no stale-
metadata reap) for downstream inspection.
sync : synchronise the OCC kernel (default True).
tolerance : float | None
Optional override for Geometry.ToleranceBoolean during
the fragment (see :meth:fuse) — raise it when shapes touch
at near-coincident faces the default tolerance misses.
None (default) leaves the current global tolerance
unchanged.
Returns¶
list[Tag] Tags of all surviving entities at the target dimension.
Source code in src/apeGmsh/core/_model_boolean.py
conformal ¶
Fragment all entities against each other to produce a conformal model.
Convenience alias living next to :meth:fragment — delegates to
:meth:Model.queries.make_conformal. Use this when you want to weld
an entire imported/arc-built model into a single connected topology
(the whole-model "fragment everything against everything" case),
rather than fragmenting one explicit object/tool pair.
See :meth:_Queries.make_conformal for full parameter docs and the
Part-instance renumbering caveat.
Source code in src/apeGmsh/core/_model_boolean.py
g.model.transforms¶
apeGmsh.core._model_transforms._Transforms ¶
Transform and extrusion/revolution sub-composite extracted from Model.
Source code in src/apeGmsh/core/_model_transforms.py
translate ¶
translate(tags: EntityRefs, dx: float, dy: float, dz: float, *, dim: int = 3, sync: bool = True) -> '_Transforms'
Translate entities by (dx, dy, dz).
tags accepts int / label / PG name / (dim, tag) / list
of any mix. dim is the fallback for bare ints.
Example¶
::
g.model.transforms.translate(box, 5, 0, 0)
g.model.transforms.translate("col.body", 0, 0, 5)
Source code in src/apeGmsh/core/_model_transforms.py
rotate ¶
rotate(tags: EntityRefs, angle: float, *, ax: float = 0.0, ay: float = 0.0, az: float = 1.0, cx: float = 0.0, cy: float = 0.0, cz: float = 0.0, dim: int = 3, sync: bool = True) -> '_Transforms'
Rotate entities around an axis through (cx, cy, cz) with direction
(ax, ay, az) by angle radians.
tags accepts any flexible-ref form (see :meth:translate).
Example¶
g.model.transforms.rotate(box, math.pi / 4, az=1)
Source code in src/apeGmsh/core/_model_transforms.py
scale ¶
scale(tags: EntityRefs, sx: float, sy: float, sz: float, *, cx: float = 0.0, cy: float = 0.0, cz: float = 0.0, dim: int = 3, sync: bool = True) -> '_Transforms'
Scale (dilate) entities by (sx, sy, sz) from centre (cx, cy, cz).
tags accepts any flexible-ref form (see :meth:translate).
Example¶
g.model.transforms.scale(box, 2, 2, 2) # uniform double
Source code in src/apeGmsh/core/_model_transforms.py
mirror ¶
mirror(tags: EntityRefs, a: float, b: float, c: float, d: float, *, dim: int = 3, sync: bool = True) -> '_Transforms'
Mirror entities through the plane ax + by + cz + d = 0.
tags accepts any flexible-ref form (see :meth:translate).
Example¶
g.model.transforms.mirror(box, 1, 0, 0, 0) # reflect through YZ plane
Source code in src/apeGmsh/core/_model_transforms.py
copy ¶
Duplicate entities. Returns the tags of the new copies.
tags accepts any flexible-ref form (see :meth:translate).
Example¶
copies = g.model.transforms.copy([box, sphere])
Source code in src/apeGmsh/core/_model_transforms.py
extrude ¶
extrude(tags: EntityRefs, dx: float, dy: float, dz: float, *, dim: int = 2, num_elements: list[int] | None = None, heights: list[float] | None = None, recombine: bool = False, sync: bool = True) -> list[DimTag]
Linear extrusion — sweeps entities along (dx, dy, dz).
Creates new geometry one dimension up: point -> curve, curve -> surface, surface -> volume.
Parameters¶
tags : entities to extrude.
dx, dy, dz : extrusion vector.
dim : default dimension for bare integer tags (default 2).
num_elements : structured layer counts, e.g. [10] for
10 layers. Empty list (default) = unstructured.
heights : relative heights per layer, e.g. [0.3, 0.7].
Must sum to 1.0 when provided. Empty = uniform layers.
recombine : if True, produce hex/quad elements instead of
tet/tri (requires structured layers).
sync : synchronise OCC kernel after extrusion (default True).
Returns¶
list[DimTag] All generated (dim, tag) pairs. For a surface -> volume extrusion the list contains the top face, the volume, and the lateral faces — index into it to assign physical groups.
Example¶
::
surf = g.model.geometry.add_plane_surface(loop)
out = g.model.transforms.extrude(surf, 0, 0, 3.0, num_elements=[10])
# out[0] = (2, top_face), out[1] = (3, volume), ...
Source code in src/apeGmsh/core/_model_transforms.py
revolve ¶
revolve(tags: EntityRefs, angle: float, *, x: float = 0.0, y: float = 0.0, z: float = 0.0, ax: float = 0.0, ay: float = 0.0, az: float = 1.0, dim: int = 2, num_elements: list[int] | None = None, heights: list[float] | None = None, recombine: bool = False, sync: bool = True) -> list[DimTag]
Revolution — sweeps entities around an axis.
Parameters¶
tags : entities to revolve.
angle : sweep angle in radians (2π for full revolution).
x, y, z : point on the rotation axis.
ax, ay, az : direction vector of the rotation axis.
dim : default dimension for bare integer tags (default 2).
num_elements, heights, recombine : same as :meth:extrude.
sync : synchronise OCC kernel (default True).
Returns¶
list[DimTag] All generated (dim, tag) pairs.
Example¶
::
# Revolve a cross-section 360° around the Y axis
out = g.model.transforms.revolve(profile, 2 * math.pi, ay=1)
Source code in src/apeGmsh/core/_model_transforms.py
sweep ¶
sweep(profiles: EntityRefs, path: Tag, *, dim: int = 2, trihedron: str = 'DiscreteTrihedron', label: str | None = None, sync: bool = True) -> list[DimTag]
Sweep one or more profile entities along an arbitrary wire.
This is the "constant-section sweep" operation: a single profile
(point, curve, or surface) is translated along path, generating
geometry one dimension up — point -> curve, curve -> surface,
surface -> volume. Unlike :meth:extrude the path does not have
to be a straight line: it can be any OCC wire built from lines,
arcs, splines, or a mix, assembled via
:meth:~Model.add_wire.
Parameters¶
profiles : entity or entities to sweep. For a solid you
normally pass a plane surface.
path : tag of an OCC wire to sweep along (use
:meth:~Model.add_wire to build it). A curve_loop can be
used for closed paths.
dim : default dimension for bare integer tags in profiles
(default 2).
trihedron : how the profile frame is transported along the
path. One of "DiscreteTrihedron" (default),
"CorrectedFrenet", "Fixed", "Frenet",
"ConstantNormal", "Darboux", "GuideAC",
"GuidePlan", "GuideACWithContact",
"GuidePlanWithContact". Most structural workflows
want the default; use "Frenet" for smooth curves
without inflection and "Fixed" to keep the profile's
orientation constant in world space.
label : optional label applied to the highest-dimension
survivor of the sweep (the volume for a surface sweep).
sync : synchronise the OCC kernel after the call (default
True).
Returns¶
list[DimTag]
All generated (dim, tag) pairs. Index into the list
to grab the volume, the lateral faces, or the end caps and
assign them to physical groups.
Example¶
::
section = g.model.geometry.add_plane_surface(loop, label="I_section")
path = g.model.geometry.add_wire([arc1, line1, arc2])
out = g.model.transforms.sweep(section, path, label="curved_beam")
Source code in src/apeGmsh/core/_model_transforms.py
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 | |
thru_sections ¶
thru_sections(wires: list[Tag], *, make_solid: bool = True, make_ruled: bool = False, max_degree: int = -1, continuity: str = '', parametrization: str = '', smoothing: bool = False, label: str | None = None, sync: bool = True) -> list[DimTag]
Variable-section sweep — loft a volume (or surface shell) through an ordered list of wires.
This is the right operation when the cross-section changes along the sweep: a tapered column, a transition piece between two different flange shapes, a blended nozzle. Each wire defines one intermediate section; OCC builds a smooth surface that interpolates between them and (optionally) caps the ends to produce a solid.
All wires should be topologically similar (same number of
sub-curves in the same order) for reliable lofting. Open wires
produce a skin; closed wires with make_solid=True produce a
solid.
Parameters¶
wires : ordered list of wire tags (build each one with
:meth:~Model.add_wire). At least two wires are required.
make_solid : if True (default), cap the ends and return a
solid; if False, return only the skinned surface(s).
make_ruled : if True, force the lateral faces to be ruled
surfaces (linear interpolation between adjacent sections).
max_degree : maximum degree of the resulting surface
(-1 = OCC default).
continuity : "C0", "G1", "C1", "G2", "C2",
"C3", or "CN" ("" = OCC default).
parametrization : "ChordLength", "Centripetal", or
"IsoParametric" ("" = OCC default).
smoothing : if True, apply a smoothing pass to the resulting
surface.
label : optional label applied to the highest-dimension
survivor (the volume when make_solid=True).
sync : synchronise the OCC kernel after the call (default
True).
Returns¶
list[DimTag]
All generated (dim, tag) pairs.
Example¶
::
w_base = g.model.geometry.add_wire([lb1, lb2, lb3, lb4])
w_top = g.model.geometry.add_wire([lt1, lt2, lt3, lt4])
out = g.model.transforms.thru_sections(
[w_base, w_top],
make_solid=True,
label="tapered_column",
)
Source code in src/apeGmsh/core/_model_transforms.py
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 | |
g.model.io¶
apeGmsh.core._model_io._IO ¶
IO sub-composite — import/export IGES, STEP, DXF, MSH.
Source code in src/apeGmsh/core/_model_io.py
load_iges ¶
load_iges(file_path: Path | str, *, highest_dim_only: bool = True, sync: bool = True, heal: bool | float | str = False, dedupe: bool | float = False, fuse: bool = False, label: str | None = None) -> dict[int, list[Tag]]
Import an IGES file into the current model.
All imported entities are registered and their tags are returned so you can immediately use them in boolean ops or transforms.
Parameters¶
highest_dim_only : bool
If True (default) only the highest-dimension entities are
returned and registered (volumes for solids, surfaces for
surface models). Set to False to capture every sub-entity
(faces, edges, vertices) as well.
heal : bool, float, or "auto"
Run heal_shapes on the imported entities immediately
after import. True and "auto" derive a
scale-aware tolerance from the model bounding box
(≈ 1e-6 · bbox_diagonal) — a fixed absolute tolerance is
meaningless across unit systems. A float overrides it
(e.g. heal=1e-3). False (default) imports raw and,
if the result shows slivers, emits a non-mutating
:class:WarnGeomImportHealth advisory (see
:meth:diagnose). For non-tolerance knobs, call
heal_shapes() directly.
dedupe : bool or float
Run g.model.queries.remove_duplicates after the import
(and after heal, if enabled). True uses the current
Gmsh tolerance; a float overrides it for the call.
fuse : bool
If True, union all imported top-dimension entities into a
single survivor via g.model.boolean.fuse. No-op when
the import yields fewer than two entities at the top
dimension. Combined with highest_dim_only=False, the
lower-dim sub-imports are discarded since the volume fuse
invalidates them.
label : str, optional
Global label attached to all imported entities (or to the
fused survivor, when fuse=True). Resolvable via
g.labels.entities(name).
Returns¶
dict[int, list[Tag]]
{dim: [tag, ...]} indexed by dimension.
Example¶
::
imported = g.model.io.load_iges("part.iges")
bodies = imported[3] # all imported volume tags
flange = bodies[0] # first imported volume
boss = g.model.geometry.add_cylinder(10, 10, 0, 0, 0, 5, 3)
result = g.model.boolean.fuse(flange, boss)
Source code in src/apeGmsh/core/_model_io.py
load_step ¶
load_step(file_path: Path | str, *, highest_dim_only: bool = True, sync: bool = True, heal: bool | float | str = False, dedupe: bool | float = False, fuse: bool = False, label: str | None = None) -> dict[int, list[Tag]]
Import a STEP file into the current model.
All imported entities are registered and their tags are returned so you can immediately use them in boolean ops or transforms.
Parameters¶
highest_dim_only : bool
If True (default) only the highest-dimension entities are
returned and registered. Set to False to include all
sub-entities.
heal : bool, float, or "auto"
Run heal_shapes on the imported entities immediately
after import. True and "auto" derive a
scale-aware tolerance from the model bounding box
(≈ 1e-6 · bbox_diagonal) — a fixed absolute tolerance is
meaningless across unit systems. A float overrides it
(e.g. heal=1e-3). False (default) imports raw and,
if the result shows slivers, emits a non-mutating
:class:WarnGeomImportHealth advisory (see
:meth:diagnose). For non-tolerance knobs, call
heal_shapes() directly.
dedupe : bool or float
Run g.model.queries.remove_duplicates after the import
(and after heal, if enabled). True uses the current
Gmsh tolerance; a float overrides it for the call.
fuse : bool
If True, union all imported top-dimension entities into a
single survivor via g.model.boolean.fuse. No-op when
the import yields fewer than two entities at the top
dimension. Combined with highest_dim_only=False, the
lower-dim sub-imports are discarded since the volume fuse
invalidates them.
label : str, optional
Global label attached to all imported entities (or to the
fused survivor, when fuse=True). Resolvable via
g.labels.entities(name).
Returns¶
dict[int, list[Tag]]
{dim: [tag, ...]} indexed by dimension.
Example¶
::
# one-shot: import an assembly, clean + fuse + label
imported = g.model.io.load_step(
"assembly.step",
heal=True, dedupe=True, fuse=True, label="frame",
)
body = imported[3][0] # single fused volume
Source code in src/apeGmsh/core/_model_io.py
heal_shapes ¶
heal_shapes(tags: TagsLike | None = None, *, dim: int = 3, tolerance: float = 1e-08, fix_degenerated: bool = True, fix_small_edges: bool = True, fix_small_faces: bool = True, sew_faces: bool = True, make_solids: bool = True, sync: bool = True) -> _IO
Heal topology issues in imported CAD geometry (STEP / IGES).
Wraps gmsh.model.occ.healShapes which fixes common issues
such as degenerate edges, tiny faces, gaps between faces, and
open shells that should be solids.
Parameters¶
tags : entities to heal (default: all entities in the model). dim : default dimension for bare integer tags. tolerance : healing tolerance (default 1e-8). fix_degenerated : fix degenerate edges/faces. fix_small_edges : remove edges smaller than tolerance. fix_small_faces : remove faces smaller than tolerance. sew_faces : reconnect open shells at shared edges. make_solids : close healed shells into solids. sync : synchronise OCC kernel (default True).
Returns¶
self — for method chaining.
Example¶
::
imported = g.model.io.load_step("legacy_part.step")
g.model.io.heal_shapes(tolerance=1e-3)
Source code in src/apeGmsh/core/_model_io.py
diagnose ¶
Report CAD health of the current model without mutating it.
Scans the live OCC geometry and returns an :class:ImportHealth
with per-dimension entity counts, sliver tallies (edges / faces
far below the model scale), the bbox diagonal, and a suggested
heal= tolerance. Nothing is healed, deduped, or
renumbered — this is the look-before-you-leap counterpart to
:meth:heal_shapes (which does mutate and renumber).
Parameters¶
warn : bool, default False
When True, emit a :class:WarnGeomImportHealth advisory if
the report :attr:~ImportHealth.is_suspect (slivers
present). load_step / load_iges use this internally
on a raw (un-healed) import.
Returns¶
ImportHealth
Example¶
::
g.model.io.load_step("messy.step") # raw
report = g.model.io.diagnose()
if report.is_suspect:
g.model.io.load_step("messy.step", heal="auto", dedupe=True)
Source code in src/apeGmsh/core/_model_io.py
save_iges ¶
Export the current model to IGES.
The .iges extension is appended automatically if omitted.
Source code in src/apeGmsh/core/_model_io.py
save_step ¶
Export the current model to STEP.
The .step extension is appended automatically if omitted.
Source code in src/apeGmsh/core/_model_io.py
load_dxf ¶
load_dxf(file_path: Path | str, *, point_tolerance: float = 1e-06, create_physical_groups: bool = True, sync: bool = True) -> dict[str, dict[int, list[Tag]]]
Import a DXF file into the current model.
Uses ezdxf to parse the DXF (supports all AutoCAD versions
from R12 to 2024+), then builds Gmsh geometry through the OCC
kernel. AutoCAD layers become Gmsh physical groups
automatically.
Supported DXF entity types: LINE, ARC, CIRCLE,
LWPOLYLINE, POLYLINE, SPLINE, POINT.
Parameters¶
file_path : Path or str
Path to the .dxf file.
point_tolerance : float
Distance below which two DXF endpoints are considered
coincident and share a single Gmsh point. Default 1e-6.
create_physical_groups : bool
If True (default), a physical group is created for each DXF
layer. If False, entities are created but no physical groups
are made (useful when you want to assign groups manually).
sync : bool
Synchronise the OCC kernel after import (default True).
Returns¶
dict[str, dict[int, list[Tag]]]
{layer_name: {dim: [tag, ...]}}
Each key is a DXF layer name. Values map entity dimension
to lists of Gmsh tags created from that layer.
Example¶
::
# AutoCAD drawing with layers: "C80x80", "V30x50"
layers = g.model.io.load_dxf("frame_2D.dxf")
# layers == {
# "C80x80": {1: [1, 2, 3, 4]},
# "V30x50": {1: [5, 6, 7, 8, 9]},
# }
# Physical groups are already created — ready for meshing.
# Access beam curves:
beam_curves = layers["V30x50"][1]
Source code in src/apeGmsh/core/_model_io.py
save_dxf ¶
Export the current model to DXF.
The .dxf extension is appended automatically if omitted.
Source code in src/apeGmsh/core/_model_io.py
save_msh ¶
Export the current model to Gmsh's native MSH format.
Unlike STEP/IGES, this preserves everything: geometry, mesh, physical groups, and partition data.
The .msh extension is appended automatically if omitted.
Source code in src/apeGmsh/core/_model_io.py
load_msh ¶
Import a Gmsh .msh file using gmsh.merge.
Unlike load_iges / load_step, this preserves physical
groups, mesh data, and partition info — because .msh is
Gmsh's native format.
Parameters¶
file_path : Path or str
Path to the .msh file.
Returns¶
dict[int, list[Tag]]
{dim: [tag, ...]} of all entities after merge.
Source code in src/apeGmsh/core/_model_io.py
load_geo ¶
Import a Gmsh .geo script using gmsh.merge.
The script is executed in the active model, so any Mesh N;
statements inside the file will run. The CAD kernel used for
synchronization is auto-detected by scanning the file head for
SetFactory("OpenCASCADE"):
- found ->
gmsh.model.occ.synchronize() - absent ->
gmsh.model.geo.synchronize()
Parameters¶
file_path : Path or str
Path to the .geo file.
Returns¶
dict[int, list[Tag]]
{dim: [tag, ...]} of all entities after merge.
Source code in src/apeGmsh/core/_model_io.py
g.model.queries¶
apeGmsh.core._model_queries._Queries ¶
Queries sub-composite — remove, topology queries, and registry.
Source code in src/apeGmsh/core/_model_queries.py
remove ¶
Delete entities from the model.
Parameters¶
recursive : bool If True, also delete all lower-dimensional entities that are exclusively owned by these entities.
Source code in src/apeGmsh/core/_model_queries.py
remove_duplicates ¶
Merge all coincident OCC entities in the current model.
Calls gmsh.model.occ.removeAllDuplicates(), which walks every
dimension (points -> curves -> surfaces -> volumes) and collapses
entities that are geometrically identical within the OCC tolerance.
The internal registry is then reconciled so only entities that
survive the merge are tracked.
This is the recommended post-processing step after importing IGES or STEP files, which routinely produce coincident points and overlapping curves at shared frame joints.
Parameters¶
tolerance : float | None
Geometric merge tolerance. When provided, temporarily overrides
Geometry.Tolerance and Geometry.ToleranceBoolean for the
duration of this call, then restores the previous values.
Use this when the IGES exporter introduced small coordinate
imprecisions (e.g. tolerance=1e-3 for mm-scale models).
When None (default), the current Gmsh tolerance is used unchanged.
sync : bool
Synchronise the OCC kernel after merging (default True).
Set to False only if you intend to call model.sync()
manually as part of a larger batch operation.
Returns¶
self — for method chaining
Example¶
::
imported = g.model.io.load_iges("Frame3D.iges", highest_dim_only=False)
g.model.queries.remove_duplicates(tolerance=1e-3)
g.plot.geometry(label_tags=True)
Source code in src/apeGmsh/core/_model_queries.py
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 | |
make_conformal ¶
make_conformal(*, dims: list[int] | None = None, tolerance: float | None = None, sync: bool = True) -> _Queries
Fragment all entities against each other to produce a conformal model.
Canonical fix for two flavours of disjoint topology:
- IGES/STEP imports — CAD exporters routinely produce coincident vertices on separate BRep objects (column endpoints, beam endpoints) that share an XYZ but have no shared OCC point.
- Arc-built wires (
add_arc/add_circle(angle1,angle2)/add_ellipse(angle1,angle2)) — OCC creates fresh endpoint points on each partial-arc curve rather than welding to existing point tags. A wire built asarc + line + lineis then topologically three disjoint pieces; the mesh produces two nodes at every arc-line junction with no moment continuity.make_conformal(dims=[1])welds them at the geometry layer.
A conformal model is required for FEM meshing because elements must share nodes at junctions rather than having two independent nodes at the same location.
This method calls gmsh.model.occ.fragment() with all entities of
the requested dimensions as both objects and tools. OCC computes all
intersections, splits curves at shared points, and merges coincident
vertices — leaving a single connected topology.
Parameters¶
dims : list[int] | None
Dimensions to fragment. Defaults to all non-empty dimensions
present in the model (typically [1] for wireframe frames,
[1, 2] for mixed models). Pass [1] explicitly to
restrict to curves only and avoid fragmenting surfaces.
tolerance : float | None
Geometric tolerance for OCC's intersection / coincidence detection.
Temporarily overrides Geometry.ToleranceBoolean for the duration
of the fragment call, then restores the original value.
Use this when curves only touch at endpoints (no proper crossing)
and the default OCC tolerance is too tight to detect them —
e.g. tolerance=1.0 for mm-scale models.
When None (default), the current Gmsh tolerance is used unchanged.
sync : bool
Synchronise the OCC kernel after fragmenting (default True).
Returns¶
self — for method chaining
Warnings¶
make_conformal() renumbers OCC entities. Any
:class:Part instances already constructed against the pre-fragment
model hold stale entity-tag dicts in their Instance.entities
attribute, and a best-effort remap runs only for parts registered
on the session at call time. For correctness:
- Preferred: call
make_conformal()before constructingPart/Assemblyinstances. - Otherwise: rebuild any
Partinstances after fragmenting.
Same caveat for hand-stored (dim, tag) references in user code —
fragment refreshes tags, so cached lookups will dangle.
Example¶
::
m1.model.io.load_iges("Frame3D.iges", highest_dim_only=False)
m1.remove_duplicates(tolerance=1.0)
m1.model.queries.make_conformal(dims=[1], tolerance=1.0)
m1.plot.geometry(label_tags=True)
Source code in src/apeGmsh/core/_model_queries.py
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 273 274 275 276 277 278 279 280 281 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 | |
bounding_box ¶
Return the axis-aligned bounding box of an entity.
tag accepts an int, a label, a PG name, or a (dim, tag)
tuple. Must resolve to exactly one entity. When tag is a
bare int, dim is honoured as an explicit dimension hint
(no live-model lookup) — important because Gmsh tag spaces are
per-dimension, so the same int can refer to different entities
at different dims.
Returns¶
(xmin, ymin, zmin, xmax, ymax, zmax)
Example¶
xmin, ymin, zmin, xmax, ymax, zmax = g.model.queries.bounding_box("box")
Source code in src/apeGmsh/core/_model_queries.py
center_of_mass ¶
Return the center of mass of an entity.
tag accepts an int, a label, a PG name, or a (dim, tag)
tuple. Must resolve to exactly one entity. Bare ints are
interpreted at dim directly (no live-model lookup).
Example¶
cx, cy, cz = g.model.queries.center_of_mass("box")
Source code in src/apeGmsh/core/_model_queries.py
mass ¶
Return the mass (volume for 3D, area for 2D, length for 1D) of an entity.
tag accepts an int, a label, a PG name, or a (dim, tag)
tuple. Must resolve to exactly one entity. Bare ints are
interpreted at dim directly (no live-model lookup).
Example¶
vol = g.model.queries.mass("box")
Source code in src/apeGmsh/core/_model_queries.py
boundary ¶
boundary(tags: TagsLike, *, dim: int = 3, oriented: bool = False, combined: bool = True, recursive: bool = False) -> list[DimTag]
Return the boundary entities of the given entities.
Parameters¶
tags : int, label, PG name, (dim, tag), or list thereof.
Strings are resolved as label first (Tier 1, g.labels),
then user physical-group name (Tier 2, g.physical).
dim : default dimension for bare integer tags or string refs.
oriented : if True, return oriented boundary (signs on tags).
combined : if True, return the boundary of the combined entities.
recursive : if True, recurse down to dimension 0.
Returns¶
list[DimTag] Boundary entities as (dim, tag) pairs.
Example¶
::
faces = g.model.queries.boundary(vol_tag) # by tag
edges = g.model.queries.boundary("Plate", dim=2) # by label
Source code in src/apeGmsh/core/_model_queries.py
boundary_curves ¶
Return all unique curves (dim = 1) on the boundary of an entity.
Wraps the two-step query needed to get a volume's edges:
boundary(vol) skips straight to vertices when recursive=True,
so the correct pattern is to fetch faces first, then walk each face's
boundary individually with combined=False (so shared edges are not
cancelled), and deduplicate the result.
Parameters¶
tag : int, label, PG name, (dim, tag) tuple, or list thereof.
Returns¶
list[DimTag]
(1, curve_tag) pairs, deduplicated.
Example¶
::
edges = g.model.queries.boundary_curves('box') # 12 edges
edges = g.model.queries.boundary_curves(surf) # 4 edges of a face
Source code in src/apeGmsh/core/_model_queries.py
boundary_points ¶
Return all unique points (dim = 0) on the boundary of an entity.
Equivalent to boundary(tag, recursive=True) for volumes —
Gmsh's recursive walk goes straight to dim=0 — but provided as a
named alias for symmetry with boundary_curves.
Example¶
::
corners = g.model.queries.boundary_points('box') # 8 corners
Source code in src/apeGmsh/core/_model_queries.py
adjacencies ¶
Return entities adjacent to the given entity.
Returns¶
(upward, downward)
upward — tags of entities of dim + 1 that contain
this entity.
downward — tags of entities of dim - 1 on this
entity's boundary.
Example¶
::
up, down = g.model.queries.adjacencies(face_tag, dim=2)
# up = volumes bounded by this face
# down = curves on this face's boundary
Source code in src/apeGmsh/core/_model_queries.py
entities_in_bounding_box ¶
entities_in_bounding_box(xmin: float, ymin: float, zmin: float, xmax: float, ymax: float, zmax: float, *, dim: int = -1) -> list[DimTag]
Return all entities inside a bounding box.
Parameters¶
xmin, ymin, zmin, xmax, ymax, zmax : box limits. dim : restrict to this dimension (-1 = all dimensions).
Returns¶
list[DimTag]
Example¶
::
# Find all entities in a region
found = g.model.queries.entities_in_bounding_box(
0, 0, 0, 10, 10, 10, dim=3
)
Source code in src/apeGmsh/core/_model_queries.py
plane ¶
Construct a :class:Plane for use with
m.model.select(...).crossing_plane(plane, mode=...) (or any
other API that accepts a plane spec).
Forms accepted¶
plane(z=0) / plane(x=5)
Axis-aligned plane.
plane(p1, p2, p3)
Plane through three non-collinear points.
plane(normal=(0, 0, 1), through=(0, 0, 5))
Direct construction from a normal and an anchor point.
Example¶
::
mid = m.model.queries.plane(z=2.5)
faces_cut = m.model.select(faces, dim=2).crossing_plane(
mid, mode="crossing")
below = m.model.select(faces, dim=2).crossing_plane(
mid, mode="not_crossing")
Source code in src/apeGmsh/core/_model_queries.py
registry ¶
Return a DataFrame of all entities created through this helper.
Indexed by (dim, tag) — matching Gmsh's identity model where
tags are only unique within a dimension.
Columns: kind, label
The label column is populated from g.labels (the single
source of truth), not from the metadata dict.
Source code in src/apeGmsh/core/_model_queries.py
Fluent selection — g.model.select()¶
g.model.select(...) is the single entity-selection surface and
the geometry entry of the unified, daisy-chainable
selection idiom. The former
g.model.queries.select(...) predicate selector and the former
g.model.selection.select_* entity composite have been removed;
their behaviour is folded into the verbs below. select() returns an
EntitySelection (entity
family) with direct terminals .to_label() / .to_physical() /
.to_dataframe(); .result() is a zero-cost identity alias yielding
the Selection payload (retained
by architecture as the entity-side terminal type).
(g.model.select("Faces") # tiered name resolve
.in_box((-0.1, -0.1, -0.1), (1.1, 1.1, 1.1)) # gmsh BRep containment
.on_plane((0, 0, 0), (0, 0, 1), tol=1e-6)
.to_physical("Base"))
Entity-family in_box is gmsh BRep containment and rejects
inclusive= with a TypeError (it is point-family only). See
Selection for the full idiom, the verb surface, and
the point-vs-entity family contract.
Geometric predicates — cheat sheet¶
The straddle predicates are reached two ways: as the
.crossing_plane(spec, *, mode=) verb on the
EntitySelection chain, or
as the .select(on=/crossing=/not_on=/not_crossing=) refinement method
on the Selection payload (after
.result()):
| Predicate | Where | Dim | Example | Keeps entities that… |
|---|---|---|---|---|
mode="on" / on= |
.crossing_plane() verb / .select() kwarg |
any | on={"z": 0} |
lie entirely on the plane |
mode="crossing" / crossing= |
.crossing_plane() verb / .select() kwarg |
any | crossing={"z": 0} |
straddle the plane |
mode="not_on" / not_on= |
.crossing_plane() verb / .select() kwarg |
any | not_on={"z": 0} |
are not entirely on the plane |
mode="not_crossing" / not_crossing= |
.crossing_plane() verb / .select() kwarg |
any | not_crossing={"z": 0} |
lie entirely on one side |
.parallel_to(...) |
method on Selection |
1 (curves) | edges.parallel_to("z") |
are curves whose chord direction is parallel to it |
.normal_along(...) |
method on Selection |
2 (surfaces) | faces.normal_along("z") |
are surfaces whose normal is along it |
Primitive (plane / line) spec formats¶
| Form | Meaning |
|---|---|
{"z": 0} / {"x": 5} / {"y": -3} |
Axis-aligned plane |
[(x1,y1,z1), (x2,y2,z2)] |
Infinite line through 2 points (for curves in 2-D) |
[(x1,y1,z1), (x2,y2,z2), (x3,y3,z3)] |
Infinite plane through 3 points (for surfaces / volumes) |
m.model.queries.plane(...) |
Plane object — axis-aligned, 3-point, or normal=/through= |
Direction formats accepted by .parallel_to(...) / .normal_along(...)¶
| Form | Meaning |
|---|---|
"x", "y", "z" |
Axis alias |
(1, 0, 0) / (1, 1, 0) |
Any non-zero 3-vector (normalized internally) |
angle_tol=2.0 |
Tolerance in degrees; default 1.0. Anti-parallel counts as parallel. |
Seeding a selection¶
| Call | Returns |
|---|---|
g.model.select(dim=N) |
every entity at dimension N (point=0, curve=1, surface=2, volume=3) |
g.model.select(name_or_dimtags, dim=N) |
by PG / label / part name, or from an explicit (dim, tag) set |
Selection — .result() payload of select()¶
g.model.select(...) returns an EntitySelection; its .result()
yields a Selection — a chainable list of (dim, tag) pairs. No
import is needed. The Selection payload still carries the position
predicates (.select(on=/crossing=/not_on=/not_crossing=, tol=)),
direction filters, and set-algebra.
curves = m.model.queries.boundary(surf, oriented=False) # -> Selection
# axis-aligned plane
bottom = curves.select(on={'y': 0})
# 2-point line
mid = curves.select(crossing=[(0,5,0),(5,5,0)])
# chain to narrow further
left_bottom = curves.select(on={'y': 0}).select(on={'x': 0})
# extract bare tags for downstream calls
m.mesh.structured.set_transfinite_curve(bottom.tags(), n=11)
Starting from every entity of a dimension¶
When parsing an imported .geo / STEP file with no labels yet, seed
with g.model.select(dim=N) (no target):
# Every volume in the model
g.model.select(dim=3).to_physical("solids")
# Volumes the plane z = -15 slices through
(g.model.select(dim=3)
.crossing_plane({"z": -15}, mode="crossing")
.to_physical("crossers"))
# The floor (surfaces lying on z = 0)
(g.model.select(dim=2)
.crossing_plane({"z": 0}, mode="on")
.to_physical("base"))
dim=0 points, dim=1 curves, dim=2 surfaces, dim=3 volumes.
Direction-based filters — parallel_to and normal_along¶
For dim-restricted filtering by direction (not position), the
Selection payload offers two methods:
# Curves: keep only edges whose chord is along a direction
edges = g.model.select("box", dim=1).result()
verticals = edges.parallel_to("z") # axis alias
diagonals = edges.parallel_to((1, 1, 0), angle_tol=2) # arbitrary vector
# Surfaces: keep only faces whose normal is along a direction
faces = g.model.select("box", dim=2).result()
horizontals = faces.normal_along("z")
Both accept axis aliases ("x" / "y" / "z") or any non-zero 3-vector
(normalized internally; anti-parallel counts as parallel). Default
angle_tol is 1.0°. The methods are dim-restricted: parallel_to
raises if the Selection contains non-curve entities, normal_along raises
for non-surface entities — with a fix-it suggestion in the error.
They chain with the position predicates:
# Vertical edges on the x = 0 wall
(g.model.select("box", dim=1).result()
.parallel_to("z")
.select(on={"x": 0}))
Combining selections — |, &, -¶
Two Selections can be combined with set-algebra operators. Semantics are
set-like with deduplication — a (dim, tag) pair never appears
twice in the result, so downstream calls like to_physical register each
entity once.
Each operation has both an operator form (terse, for one-liners) and a named-method form (discoverable via autocomplete, keeps the chain fluent — important when you don't want to break out to a variable).
| Operator | Method | Meaning | Example |
|---|---|---|---|
a \| b |
a.union(b) |
entities in either | sides = nx.union(ny) |
a & b |
a.intersect(b) |
entities in both | edge = top.intersect(front) |
a - b |
a.difference(b) |
in a, not in b |
lateral = all.difference(horizontal) |
surf = g.model.select(dim=2).result()
# Three equivalent ways to grab the lateral sides of an axis-aligned box:
(surf.normal_along("x") | surf.normal_along("y")).to_physical("sides")
(surf - surf.normal_along("z")).to_physical("sides")
surf.normal_along("x").union(surf.normal_along("y")).to_physical("sides")
# Intersection — curves shared by two faces (the edge between them)
top_edges = m.model.queries.boundary("top", dim=2, oriented=False)
front_edges = m.model.queries.boundary("front", dim=2, oriented=False)
shared_edge = top_edges.intersect(front_edges)
Why | and not +? Selection subclasses list, where +
already means concatenation with duplicates preserved. The | family
follows Python's set / dict convention for combining-with-dedup,
which is the right semantics for selection sets — combining the xmin
faces with the ymin faces should give each shared corner edge once, not
twice.
Resolve-only select(...) — no predicate required¶
g.model.select("name", dim=N) with no spatial verb returns
the entities under that name as a chainable selection — useful as an
entry point into the method-style filters:
apeGmsh.core._selection.Selection ¶
Bases: list
A filtered list of (dim, tag) pairs — the payload yielded by
the .result() terminal of an :class:EntitySelection (itself
returned by m.model.select(...)). Retained by architecture
as the entity-side terminal payload; it is not a legacy or
backward-compat type.
A Selection is a list subclass, so it iterates as (dim, tag)
pairs and supports indexing. It is also chainable — every method
that narrows or combines returns a new Selection.
Refine (narrow what you have)¶
============================== ==========================================
.select(...) position predicates: on, crossing,
not_on, not_crossing
.parallel_to(direction) curves whose chord is along a direction
.normal_along(direction) surfaces whose normal is along a direction
.partition_by(axis=None) group entities by dominant BB axis
============================== ==========================================
Combine (set algebra on two Selections)¶
Set semantics with deduplication — appropriate for (dim, tag)
pairs, where logical identity matters and duplicates would cause
downstream calls (e.g. to_physical) to register the same
entity twice.
Each operation has both an operator form (terse, for one-liners) and a named-method form (discoverable via autocomplete, keeps the chain fluent).
===================== ===================== ===================== ===========================
Operator Method Meaning Example
===================== ===================== ===================== ===========================
a | b a.union(b) union nx | ny
a & b a.intersect(b) intersection top & front
a - b a.difference(b) set difference all - horizontal
===================== ===================== ===================== ===========================
Why | and not +: Selection subclasses list, where
+ is concatenation with duplicates preserved. | follows
the set / dict convention for combining-with-dedup, and is
the right semantics for selection sets.
Consume (turn a Selection into something else)¶
================================ ===========================================
.tags() bare integer tags (drops dim)
.to_label(name) register entities as a label
.to_physical(name) register entities as a physical group
================================ ===========================================
Example¶
::
surf = m.model.select(dim=2).result()
# Lateral sides of an axis-aligned box — three equivalent forms:
(surf.normal_along("x") | surf.normal_along("y")).to_physical("sides")
(surf - surf.normal_along("z")).to_physical("sides")
surf.normal_along("x").union(surf.normal_along("y")).to_physical("sides")
# Chain refine → consume
(m.model.select(curves, dim=1).result()
.select(on={'z': 0})
.select(on={'x': 0})
.to_label("bottom_left_edge"))
Source code in src/apeGmsh/core/_selection.py
select ¶
select(*, on=None, crossing=None, not_on=None, not_crossing=None, tol: float = 1e-06) -> 'Selection'
Filter this selection further by position predicates
(on / crossing / not_on / not_crossing).
Source code in src/apeGmsh/core/_selection.py
tags ¶
to_label ¶
Register every entity in this selection as a label.
Groups by dimension before calling session.labels.add so a
mixed-dim Selection is handled correctly. Returns self for
chaining.
Example¶
::
(m.model.select(curves, dim=1).result()
.select(on={'x': 0})
.select(on={'y': 5})
.to_label('left_top_edge'))
m.mesh.sizing.set_size('left_top_edge', size=0.1)
Source code in src/apeGmsh/core/_selection.py
to_physical ¶
Register every entity in this selection as a physical group.
Groups by dimension before calling session.physical.add so a
mixed-dim Selection is handled correctly. Returns self for
chaining.
Example¶
::
(m.model.select(faces, dim=2).result()
.select(on={'z': 0})
.to_physical('Base'))
g.constraints.fix('Base', dofs=[1, 2, 3])
Source code in src/apeGmsh/core/_selection.py
parallel_to ¶
parallel_to(direction: 'str | tuple[float, float, float] | np.ndarray', *, angle_tol: float = 1.0) -> 'Selection'
Keep curves whose endpoint chord is parallel to direction.
Only meaningful for curves (dim=1). Raises ValueError if the
Selection contains entities of any other dim.
Parameters¶
direction : str or 3-vector
"x", "y", "z" for axis aliases, or any non-zero
3-vector for an arbitrary direction. Anti-parallel matches
count as parallel — a z-edge with reversed endpoint order is
still a z-edge.
angle_tol : float, default 1.0
Maximum angle (in degrees) between the curve's chord direction
and direction for the curve to be kept.
Returns¶
Selection New Selection of curves that match.
Example¶
::
edges = m.model.select(None, dim=1).result()
verticals = edges.parallel_to("z")
obliques = edges.parallel_to((1, 1, 0), angle_tol=2.0)
m.mesh.structured.set_transfinite_curve(verticals.tags(), n=21)
Source code in src/apeGmsh/core/_selection.py
normal_along ¶
normal_along(direction: 'str | tuple[float, float, float] | np.ndarray', *, angle_tol: float = 1.0) -> 'Selection'
Keep surfaces whose face normal is along direction.
Only meaningful for surfaces (dim=2). Raises ValueError if
the Selection contains entities of any other dim.
Same direction grammar and tolerance as :meth:parallel_to. The
normal is computed from three boundary points — exact for flat
faces, an approximation for curved faces (prefer on= for those).
Anti-parallel matches count as parallel.
Example¶
::
faces = m.model.select("layer_1", dim=2).result()
horizontals = faces.normal_along("z")
verticals = faces.normal_along("x").select(...)
Source code in src/apeGmsh/core/_selection.py
union ¶
intersect ¶
difference ¶
partition_by ¶
Group entities by their dominant bounding-box axis.
Returns¶
If axis is None: dict[str, Selection] keyed by 'x',
'y', 'z'.
If axis is one of 'x', 'y', 'z': a single
Selection for that axis only.
Semantics by entity dimension¶
- dim = 1 (curves) — dominant axis is the largest BB extent (the direction the curve runs along).
- dim = 2 (surfaces) — dominant axis is the smallest BB extent (the surface normal — for axis-aligned faces this picks the perpendicular direction).
- Mixed dims partition independently per dim using the right rule.
Example¶
::
curves = m.model.queries.boundary_curves('box')
groups = curves.partition_by()
m.mesh.structured.set_transfinite_curve(groups['x'].tags(), nx)
m.mesh.structured.set_transfinite_curve(groups['y'].tags(), ny)
m.mesh.structured.set_transfinite_curve(groups['z'].tags(), nz)
Source code in src/apeGmsh/core/_selection.py
Geometric primitives (internal)¶
These classes are constructed automatically by select() from raw input.
You never instantiate them directly, but their docstrings describe the
accepted formats.
apeGmsh.core._selection.Plane
dataclass
¶
Infinite plane defined by a unit normal and an anchor point.
at
classmethod
¶
Axis-aligned plane. E.g. Plane.at(z=0), Plane.at(x=5).
Source code in src/apeGmsh/core/_selection.py
through
classmethod
¶
Plane through three non-collinear points.
Source code in src/apeGmsh/core/_selection.py
signed_distances ¶
Signed distance of each bounding-box corner from this plane.
apeGmsh.core._selection.Line
dataclass
¶
Infinite line used to cut 2-D geometry.
The 'signed distance' is computed as the component of each bounding-box corner along the line's in-plane normal — the axis perpendicular to the line direction projected onto the dominant plane (XY, XZ, or YZ).
through
classmethod
¶
Line through two points.