Skip to content

Session — apeGmsh

The top-level session object. Owns a single Gmsh kernel and wires all composites (model, mesh, parts, constraints, loads, masses, …). The OpenSees bridge is not a session composite — import it explicitly via from apeGmsh.opensees import apeSees.

Native persistence

The session can persist the neutral zone (the solver-agnostic FEMData snapshot — nodes, elements, physical groups, labels, loads, masses, constraints) to a native model.h5. Two write paths are exposed on the session:

# Autosave: write the neutral zone on context-manager exit
with apeGmsh(model_name="Tower", save_to="model.h5") as g:
    g.model.geometry.add_box(0, 0, 0, 1, 1, 1, label="body")
    g.physical.add_volume("body", name="body")
    g.mesh.generation.generate(3)
# model.h5 now exists

# Manual: write at any point inside the session
with apeGmsh(model_name="Tower") as g:
    ...
    g.save("model.h5")        # explicit path

apeGmsh(save_to=..., overwrite=True) configures autosave at construction; the file is written on end() / context exit. overwrite=False makes a pre-existing target fail-loud on save. g.save(path=None) writes immediately and returns the resolved Path; with no argument it reuses save_to, and raises RuntimeError if neither a path nor save_to was supplied.

Both paths write the neutral zone only. The OpenSees zone (typed primitives, recorders, analysis chain) is written separately by the bridge via apeSees(fem).h5(path) — see the OpenSees bridge page.

Chain-phase reassembly

apeGmsh.from_h5(path, *, model_name=None, verbose=False) rebuilds a session directly from a model.h5, skipping the Gmsh build entirely. The returned session is a chain-phase session: it has no live kernel, so geometry/meshing verbs are unavailable, but it can still compose, save, and feed the bridge.

g = apeGmsh.from_h5("model.h5")        # no gmsh; loads the neutral zone
ops = apeSees(g.mesh.queries.get_fem_data(dim=3))

Composition

g.compose(source, *, label, ...) merges another saved module's model.h5 into the current session under a namespaced label, applying an optional rigid placement (translate, rotate, anchor) and reserving a disjoint tag span so child tags never collide (ADR 0038). It returns a ComposedModule handle.

with apeGmsh.from_h5("frame.h5") as g:
    g.compose("panel.h5", label="Panel_A", translate=(0, 0, 3.0))
    g.compose("panel.h5", label="Panel_B", translate=(0, 0, 6.0))
    g.compose_list()                 # -> (ComposedModule, ...)
    g.compose_tree()                 # nested-compose hierarchy

Inspect a candidate file without composing via g.compose_inspect(path) (returns a dict: fem_hash, neutral_schema_version, tag_span_max, pg_inventory, label_inventory, record_counts, compose_tree, …). g.compose_list() enumerates the modules already composed into this session; g.compose_tree() returns the nested-compose hierarchy. In the viewer, composed parts are colourable by the string-keyed Module modes ('Module', 'Module: Root', 'Module: Leaf').

Declarative assembly — Assembly + couple

To spatially couple several saved model.h5 modules without hand-wiring compose + constraints, use the declarative builder (shipped in v2.0.0, ADR 0043 slice 1.4). It is imported from a sub-pathapeGmsh.Assembly is intentionally not exported, so the top-level "the session is the assembly" model is unchanged.

from apeGmsh.assembly import Assembly

g = (
    Assembly("frame")
    .add("col", "col.h5")                               # first add = host (bare PGs)
    .add("beam", "beam.h5", translate=(0.0, 3.0, 0.0))  # composed under label "beam"
    .couple("col", "beam", kind="equal_dof",
            ports=("top", "end"), dofs=[1, 2, 3])
    .materialize()                                      # -> composed apeGmsh session
)
g.save("frame.h5")

materialize() is a thin wrapper over apeGmsh.from_h5 (host) + g.compose (each later part) + g.constraints.<kind>. Couple kind is equal_dof or tied_contact; ports are bare per-part physical-group names. A couple that resolves to zero constraints, an unknown part, or no parts raises AssemblyError.

Package

apeGmsh

apeGmsh — Gmsh wrapper for structural FEM workflows.

Composition-based API with sub-composites for focused surfaces:

  1. Standalone (single-model, quick prototyping)::

    from apeGmsh import apeGmsh

    g = apeGmsh(model_name="plate", verbose=True) g.begin() p = g.model.geometry.add_point(0, 0, 0) ... g.end()

  2. Multi-part (assembly workflow via g.parts)::

    from apeGmsh import apeGmsh, Part

    web = Part("web") web.begin() web.model.geometry.add_box(0, 0, 0, 1, 0.5, 10) web.save("web.step") web.end()

    g = apeGmsh(model_name="bridge") g.begin() g.parts.add(web, label="web") g.parts.fragment_all() g.constraints.equal_dof("web", "slab", tolerance=1e-3) with g.loads.case("dead"): g.loads.gravity("web", g=(0, 0, -9.81), density=7850) g.masses.volume("web", density=7850) g.mesh.generation.generate(dim=3) fem = g.mesh.queries.get_fem_data(dim=3) g.end()

  3. Persisted session (autosave + resume across scripts)::

    from apeGmsh import apeGmsh, FEMData

    # Build once and autosave on context-manager exit. with apeGmsh(model_name="plate", save_to="plate.h5") as g: g.model.geometry.add_box(0, 0, 0, 1, 1, 0.1, label="body") g.physical.add_volume("body", name="body") g.mesh.generation.generate(dim=3)

    # Resume in a later script — symmetric load. fem = FEMData.from_h5("plate.h5")

apeGmsh

apeGmsh(*, model_name: str = 'ModelName', verbose: bool = False, save_to: str | Path | None = None, overwrite: bool = True)

Bases: _SessionBase

Standalone single-model Gmsh session with all composites.

Parameters

model_name : str Name passed to gmsh.model.add(). verbose : bool If True, composites print diagnostic messages.

Source code in src/apeGmsh/_core.py
def __init__(
    self,
    *,
    model_name: str = "ModelName",
    verbose: bool = False,
    save_to: str | Path | None = None,
    overwrite: bool = True,
) -> None:
    super().__init__(name=model_name, verbose=verbose)
    # Labels (Tier 1 naming) are auto-created from label= kwargs
    # on geometry methods in both Part and Assembly sessions.
    self._auto_pg_from_label = True
    # Autosave configuration. ``save_to=None`` disables autosave;
    # otherwise ``end()`` writes the neutral-zone HDF5 to this path
    # before finalizing gmsh.  Manual ``g.save()`` uses the same path.
    self._save_to: Path | None = Path(save_to) if save_to else None
    self._overwrite: bool = overwrite
    # ── FEMData cache (Phase 3B.2b-prep / ADR 0038) ──────────
    # The session caches the most recent ``get_fem_data()`` result
    # so repeat calls return the same broker object identity (and
    # downstream consumers — chain-phase shims, future
    # ``g.compose()`` — have a single canonical snapshot to update
    # via ``FEMData.with_*`` transforms).  Every broker mutation
    # (``g.constraints.X`` / ``g.loads.X`` / ``g.masses.X``) bumps
    # ``_fem_counter``; the cached snapshot is fresh iff
    # ``_fem_counter == _fem_counter_at_build``.  The first
    # extraction stamps ``_fem_counter_at_build``; any mutation
    # afterwards invalidates the cache and the next
    # ``get_fem_data()`` re-extracts from gmsh + the def lists.
    self._fem: "FEMData | None" = None
    self._fem_counter: int = 0
    self._fem_counter_at_build: int | None = None
    # ── Compose state (Phase 3B.2c / ADR 0038) ────────────────
    # ``_compose_bundles`` holds every ``_RewrittenBundle`` produced
    # by a ``g.compose(...)`` call on this session in compose-call
    # order.  When a broker mutation invalidates the cache, the
    # next ``get_fem_data()`` re-extracts from gmsh + def lists and
    # then re-applies every stored bundle on top — so the composed
    # modules survive any subsequent ``g.constraints.X`` / etc.
    # mutation.
    #
    # ``_fem_from_h5`` flags sessions built via
    # :meth:`apeGmsh.from_h5`: those have no gmsh state, so the
    # cache-stale path must re-use ``_fem`` as the chain head
    # rather than re-extracting from absent gmsh.  3B.2c chooses
    # this scoped-flag approach rather than generalising
    # ``get_fem_data()`` over a missing-gmsh case because the
    # alternative — making ``from_gmsh`` tolerate absent gmsh —
    # would bleed compose-only concerns into every extraction
    # caller.  3B.2d's resolver refactor takes the cleaner cut.
    self._compose_bundles: tuple = ()
    self._fem_from_h5: bool = False

from_h5 classmethod

from_h5(path: 'str | Path', *, model_name: str | None = None, verbose: bool = False) -> 'apeGmsh'

Construct a session in chain phase directly from a saved FEMData.

Skips the gmsh build phase entirely: the loaded FEMData becomes the session's chain head and there is no gmsh kernel behind this session at all. model.h5 persists the FEMData snapshot (nodes, elements, physical groups, labels) — not the geometry kernel — so anything that would read or mutate BRep / mesh state raises :class:~.core._compose_errors.ChainPhaseError naming the H5-safe alternative.

Useful for cross-session composition workflows::

# Day 1
with apeGmsh(model_name="host", save_to="host.h5") as g:
    ...

# Day 2
g = apeGmsh.from_h5("host.h5")
g.compose("module_a.h5", label="A")
g.compose("module_b.h5", label="B")
g.save("final.h5")
What works
  • g.mesh.queries.get_fem_data() — the chain head, and the surface every refusal below points back at.
  • g.compose(...) / compose_inspect(...) / compose_list() and :meth:save.
  • The chain-phase authoring shims, routed through FEMData.with_*: g.constraints.bc / tie / embedded / tied_contact / equalDOF / rigid_link / rigid_diaphragm, plus point g.loads.X / g.masses.X.
  • Kernel-free helpers: g.model.queries.plane / registry, g.view.list_views / count, g.plot.show / savefig / clear / figsize / use_axes.
  • repr() of any composite. The two kernel-backed reprs (g.physical, g.labels) report "no live gmsh kernel — from_h5 session" rather than raising, so debuggers and logging stay usable.
Refused — no live kernel to read

These need the gmsh model and raise on a from_h5 session specifically (a live session still has a kernel, so they stay legal there). Each message names the broker counterpart.

========================= ================================== Surface Guarded members ========================= ================================== g.inspect get_geometry_info, get_mesh_info, print_summary g.physical get_all, get_entities, entities, get_groups_for_entity, get_name, get_tag, summary, get_nodes g.labels entities, get_all, summary, has, reverse_map, labels_for_entity g.mesh.queries get_nodes, get_elements, get_element_properties, get_element_qualities, quality_report g.model.queries bounding_box, center_of_mass, mass, boundary, boundary_curves, boundary_points, adjacencies, entities_in_bounding_box g.mesh.partitioning n_partitions, summary, entity_table, save g.model.io save_step, save_iges, save_dxf, save_msh — the exporters only; the importers are frozen instead (below) g.model.<geometry> find_stale_metadata, and validate_pre_mesh through it g.mesh.recipe check g.parts build_face_map g.rebar resolve g.sections plot_faces g.view add_element_scalar / add_element_vector / add_node_scalar / add_node_vector g.plot geometry, mesh, quality, label_entities, label_nodes, label_elements, physical_groups, physical_groups_mesh ========================= ==================================

Counterparts: fem.inspect for summaries, fem.physical (:class:~.mesh._group_set.PhysicalGroupSet) for physical groups, fem.nodes.labels / fem.elements.labels (:class:~.mesh._group_set.LabelSet) for labels, fem.nodes / fem.elements / fem.info for mesh data, and results.inspect for post-processing — where fem = g.mesh.queries.get_fem_data(). BRep geometry has no counterpart: derive it from mesh coordinates or rebuild the geometry in a live session.

Refused — model frozen

Mutations are refused on any chain-phase session, not just this one: once a FEMData snapshot exists the broker is canonical, and mutating gmsh would silently desync the two. Listed by composite — each guards its mutating operations at a shared chokepoint, so the coverage is per-composite rather than the per-method enumeration given for the reads above.

  • Geometry — g.model.<geometry> (via Model._register, plus add_wire, which creates OCC geometry but is deliberately not registered), g.model.boolean, g.model.transforms, g.model.io.heal_shapes / load_msh / load_geo, and g.model.queries.remove / remove_duplicates / make_conformal (mutations despite the composite name).
  • Mesh — g.mesh.generation, g.mesh.editing, g.mesh.sizing, g.mesh.structured, g.mesh.recipe, and g.mesh.partitioning (its mutating ops partition / partition_explicit / unpartition / renumber; the composite's four readers take the kernel guard instead, and are listed in the read table above).
  • Naming — g.physical.add / set_name / remove / remove_name / remove_all, and g.labels.add / remove / rename / promote_to_physical.
  • Assembly — g.parts instance registration, g.sections builds, g.rebar.place.
Refused — resolves from live geometry

g.constraints.contact / contact_plane / interface, g.embed, g.reinforce and g.decouple_node record definitions that are resolved against live gmsh at extraction. A from_h5 session never re-extracts, so the definition would be stored and silently never applied — declare these in the source part session before saving; the resolved records round-trip through model.h5 and survive g.compose.

Parameters

path : str or Path Path to a model.h5 written by :meth:save / :meth:FEMData.to_h5. model_name : str or None Session name (used by :meth:save for /meta/model_name). Defaults to the source file's stem. verbose : bool, default False Verbose-mode flag forwarded to the constructor.

Raises

~.core._compose_errors.ChainPhaseError From any surface listed above. The message names the offending call and the alternative that answers it.

Source code in src/apeGmsh/_core.py
@classmethod
def from_h5(
    cls,
    path: "str | Path",
    *,
    model_name: str | None = None,
    verbose: bool = False,
) -> "apeGmsh":
    """Construct a session in chain phase directly from a saved FEMData.

    Skips the gmsh build phase entirely: the loaded FEMData becomes
    the session's chain head and **there is no gmsh kernel behind
    this session at all**.  ``model.h5`` persists the FEMData
    snapshot (nodes, elements, physical groups, labels) — not the
    geometry kernel — so anything that would read or mutate BRep /
    mesh state raises :class:`~.core._compose_errors.ChainPhaseError`
    naming the H5-safe alternative.

    Useful for cross-session composition workflows::

        # Day 1
        with apeGmsh(model_name="host", save_to="host.h5") as g:
            ...

        # Day 2
        g = apeGmsh.from_h5("host.h5")
        g.compose("module_a.h5", label="A")
        g.compose("module_b.h5", label="B")
        g.save("final.h5")

    What works
    ----------
    * ``g.mesh.queries.get_fem_data()`` — the chain head, and the
      surface every refusal below points back at.
    * ``g.compose(...)`` / ``compose_inspect(...)`` /
      ``compose_list()`` and :meth:`save`.
    * The chain-phase authoring shims, routed through
      ``FEMData.with_*``: ``g.constraints.bc`` / ``tie`` /
      ``embedded`` / ``tied_contact`` / ``equalDOF`` /
      ``rigid_link`` / ``rigid_diaphragm``, plus point
      ``g.loads.X`` / ``g.masses.X``.
    * Kernel-free helpers: ``g.model.queries.plane`` /
      ``registry``, ``g.view.list_views`` / ``count``,
      ``g.plot.show`` / ``savefig`` / ``clear`` / ``figsize`` /
      ``use_axes``.
    * ``repr()`` of any composite.  The two kernel-backed reprs
      (``g.physical``, ``g.labels``) report
      ``"no live gmsh kernel — from_h5 session"`` rather than
      raising, so debuggers and logging stay usable.

    Refused — no live kernel to read
    --------------------------------
    These need the gmsh model and raise on a ``from_h5`` session
    specifically (a live session still has a kernel, so they stay
    legal there).  Each message names the broker counterpart.

    =========================  ==================================
    Surface                    Guarded members
    =========================  ==================================
    ``g.inspect``              ``get_geometry_info``,
                               ``get_mesh_info``, ``print_summary``
    ``g.physical``             ``get_all``, ``get_entities``,
                               ``entities``,
                               ``get_groups_for_entity``,
                               ``get_name``, ``get_tag``,
                               ``summary``, ``get_nodes``
    ``g.labels``               ``entities``, ``get_all``,
                               ``summary``, ``has``,
                               ``reverse_map``,
                               ``labels_for_entity``
    ``g.mesh.queries``         ``get_nodes``, ``get_elements``,
                               ``get_element_properties``,
                               ``get_element_qualities``,
                               ``quality_report``
    ``g.model.queries``        ``bounding_box``,
                               ``center_of_mass``, ``mass``,
                               ``boundary``, ``boundary_curves``,
                               ``boundary_points``,
                               ``adjacencies``,
                               ``entities_in_bounding_box``
    ``g.mesh.partitioning``    ``n_partitions``, ``summary``,
                               ``entity_table``, ``save``
    ``g.model.io``             ``save_step``, ``save_iges``,
                               ``save_dxf``, ``save_msh`` — the
                               exporters only; the importers are
                               frozen instead (below)
    ``g.model.<geometry>``     ``find_stale_metadata``, and
                               ``validate_pre_mesh`` through it
    ``g.mesh.recipe``          ``check``
    ``g.parts``                ``build_face_map``
    ``g.rebar``                ``resolve``
    ``g.sections``             ``plot_faces``
    ``g.view``                 ``add_element_scalar`` /
                               ``add_element_vector`` /
                               ``add_node_scalar`` /
                               ``add_node_vector``
    ``g.plot``                 ``geometry``, ``mesh``, ``quality``,
                               ``label_entities``, ``label_nodes``,
                               ``label_elements``,
                               ``physical_groups``,
                               ``physical_groups_mesh``
    =========================  ==================================

    Counterparts: ``fem.inspect`` for summaries, ``fem.physical``
    (:class:`~.mesh._group_set.PhysicalGroupSet`) for physical
    groups, ``fem.nodes.labels`` / ``fem.elements.labels``
    (:class:`~.mesh._group_set.LabelSet`) for labels,
    ``fem.nodes`` / ``fem.elements`` / ``fem.info`` for mesh data,
    and ``results.inspect`` for post-processing — where
    ``fem = g.mesh.queries.get_fem_data()``.  BRep geometry has no
    counterpart: derive it from mesh coordinates or rebuild the
    geometry in a live session.

    Refused — model frozen
    ----------------------
    Mutations are refused on **any** chain-phase session, not just
    this one: once a FEMData snapshot exists the broker is
    canonical, and mutating gmsh would silently desync the two.
    Listed by composite — each guards its mutating operations at a
    shared chokepoint, so the coverage is per-composite rather than
    the per-method enumeration given for the reads above.

    * Geometry — ``g.model.<geometry>`` (via ``Model._register``,
      plus ``add_wire``, which creates OCC geometry but is
      deliberately not registered),
      ``g.model.boolean``, ``g.model.transforms``,
      ``g.model.io.heal_shapes`` / ``load_msh`` / ``load_geo``,
      and ``g.model.queries.remove`` / ``remove_duplicates`` /
      ``make_conformal`` (mutations despite the composite name).
    * Mesh — ``g.mesh.generation``, ``g.mesh.editing``,
      ``g.mesh.sizing``, ``g.mesh.structured``, ``g.mesh.recipe``,
      and ``g.mesh.partitioning`` (its mutating ops ``partition`` /
      ``partition_explicit`` / ``unpartition`` / ``renumber``; the
      composite's four readers take the kernel guard instead, and
      are listed in the read table above).
    * Naming — ``g.physical.add`` / ``set_name`` / ``remove`` /
      ``remove_name`` / ``remove_all``, and ``g.labels.add`` /
      ``remove`` / ``rename`` / ``promote_to_physical``.
    * Assembly — ``g.parts`` instance registration,
      ``g.sections`` builds, ``g.rebar.place``.

    Refused — resolves from live geometry
    -------------------------------------
    ``g.constraints.contact`` / ``contact_plane`` / ``interface``,
    ``g.embed``, ``g.reinforce`` and ``g.decouple_node`` record
    definitions that are resolved against live gmsh at extraction.
    A ``from_h5`` session never re-extracts, so the definition
    would be stored and silently never applied — declare these in
    the source part session before saving; the resolved records
    round-trip through ``model.h5`` and survive ``g.compose``.

    Parameters
    ----------
    path : str or Path
        Path to a ``model.h5`` written by :meth:`save` /
        :meth:`FEMData.to_h5`.
    model_name : str or None
        Session name (used by :meth:`save` for ``/meta/model_name``).
        Defaults to the source file's stem.
    verbose : bool, default False
        Verbose-mode flag forwarded to the constructor.

    Raises
    ------
    ~.core._compose_errors.ChainPhaseError
        From any surface listed above.  The message names the
        offending call and the alternative that answers it.
    """
    from .mesh.FEMData import FEMData

    p = Path(path)
    loaded_fem = FEMData.from_h5(str(p))
    name = model_name if model_name is not None else p.stem
    instance = cls(model_name=name, verbose=verbose)
    instance._fem = loaded_fem
    instance._fem_from_h5 = True
    # Mark the cache fresh so the first ``get_fem_data()`` returns
    # the loaded chain head without an extraction attempt.
    instance._mark_fem_fresh()
    # Instantiate the session composites so chain-phase APIs that
    # touch ``g.mesh.queries.get_fem_data()`` / ``g.compose`` /
    # ``g.save`` work without ``begin()`` ever running.  No gmsh
    # state is created here — composite constructors only require
    # the parent session.  Every gmsh-backed sub-API is guarded
    # (kernel reads via ``raise_if_no_live_kernel``, mutations via
    # the chain-phase freeze guard); the docstring above lists the
    # surfaces and their H5-safe counterparts.
    instance._create_composites()
    return instance

decouple_node

decouple_node(*, coords: 'tuple[float, float, float] | None' = None, point: 'str | None' = None, label: 'str | None' = None) -> Any

Declare a decoupled node — an auxiliary node that is not a Gmsh mesh vertex (spring/dashpot ground, rigidDiaphragm master, control node, load/mass anchor).

Exactly one of coords=(x, y, z) or point="label" locates it; point= is snapshotted to coordinates at mesh-extraction time. label is an optional friendly name.

The node is appended to fem.nodes at extraction with a deterministic tag above every mesh node (dedup-immune by construction) and provenance == "decoupled". It carries no ndf — DOF count is a bridge concern (ops.ndf).

Returns the :class:~apeGmsh._kernel.defs.decoupled.DecoupledNodeDef handle; its tag is populated after g.mesh.queries.get_fem_data(...).

Source code in src/apeGmsh/_core.py
def decouple_node(
    self,
    *,
    coords: "tuple[float, float, float] | None" = None,
    point: "str | None" = None,
    label: "str | None" = None,
) -> Any:
    """Declare a decoupled node — an auxiliary node that is **not**
    a Gmsh mesh vertex (spring/dashpot ground, ``rigidDiaphragm``
    master, control node, load/mass anchor).

    Exactly one of ``coords=(x, y, z)`` or ``point="label"`` locates
    it; ``point=`` is snapshotted to coordinates at mesh-extraction
    time.  ``label`` is an optional friendly name.

    The node is appended to ``fem.nodes`` at extraction with a
    deterministic tag above every mesh node (dedup-immune by
    construction) and ``provenance == "decoupled"``.  It carries
    **no** ``ndf`` — DOF count is a bridge concern (``ops.ndf``).

    Returns the :class:`~apeGmsh._kernel.defs.decoupled.DecoupledNodeDef`
    handle; its ``tag`` is populated after
    ``g.mesh.queries.get_fem_data(...)``.
    """
    return self.decoupled_nodes.add(
        coords=coords, point=point, label=label,
    )

save

save(path: str | Path | None = None) -> Path

Write the neutral-zone model.h5 for this session.

Persists what the session knows about the model: nodes, elements, physical groups, labels, constraints, loads, masses. Downstream solver enrichment (e.g. apeSees(fem).h5(p)) is a separate user-driven action and not invoked here.

Parameters

path : str, Path, or None Destination file. None (default) uses the save_to given to the constructor. Raises if neither is set.

Returns the resolved path.

Source code in src/apeGmsh/_core.py
def save(self, path: str | Path | None = None) -> Path:
    """Write the neutral-zone ``model.h5`` for this session.

    Persists what the session knows about the model: nodes,
    elements, physical groups, labels, constraints, loads, masses.
    Downstream solver enrichment (e.g. ``apeSees(fem).h5(p)``) is
    a separate user-driven action and not invoked here.

    Parameters
    ----------
    path : str, Path, or None
        Destination file.  ``None`` (default) uses the ``save_to``
        given to the constructor.  Raises if neither is set.

    Returns the resolved path.
    """
    if path is None and self._save_to is None:
        raise RuntimeError(
            "g.save() requires a path — either pass one explicitly "
            "or construct the session with save_to=<path>."
        )
    target = self._resolve_save_target(path)
    if target.exists() and not self._overwrite:
        raise FileExistsError(
            f"{target} already exists and overwrite=False."
        )
    self._do_save(target)
    return target

compose

compose(source: 'str | Path', *, label: str, **kwargs: Any) -> 'ComposedModule'

Merge a previously-saved apeGmsh model into this session.

See :meth:apeGmsh.mesh._compose.Compose.compose for the full signature, validation contract, and exception types. Phase 3B.1 scaffolds the facade — the merge engine itself lands in Phase 3B.2.

Source code in src/apeGmsh/_core.py
def compose(
    self,
    source: "str | Path",
    *,
    label: str,
    **kwargs: Any,
) -> "ComposedModule":
    """Merge a previously-saved apeGmsh model into this session.

    See :meth:`apeGmsh.mesh._compose.Compose.compose` for the full
    signature, validation contract, and exception types.  Phase
    3B.1 scaffolds the facade — the merge engine itself lands in
    Phase 3B.2.
    """
    return self._compose_facade().compose(source, label=label, **kwargs)

compose_inspect

compose_inspect(path: 'str | Path') -> dict

Read a module's H5 header without composing it.

See :meth:apeGmsh.mesh._compose.Compose.compose_inspect for the returned dict shape.

Source code in src/apeGmsh/_core.py
def compose_inspect(self, path: "str | Path") -> dict:
    """Read a module's H5 header without composing it.

    See :meth:`apeGmsh.mesh._compose.Compose.compose_inspect` for
    the returned dict shape.
    """
    return self._compose_facade().compose_inspect(path)

compose_list

compose_list() -> 'tuple[ComposedModule, ...]'

Composed modules currently on this session.

See :meth:apeGmsh.mesh._compose.Compose.compose_list.

Source code in src/apeGmsh/_core.py
def compose_list(self) -> "tuple[ComposedModule, ...]":
    """Composed modules currently on this session.

    See :meth:`apeGmsh.mesh._compose.Compose.compose_list`.
    """
    return self._compose_facade().compose_list()

compose_tree

compose_tree() -> 'tuple'

Derived nested-compose tree view of this session's modules.

See :meth:apeGmsh.mesh._compose.Compose.compose_tree.

Source code in src/apeGmsh/_core.py
def compose_tree(self) -> "tuple":
    """Derived nested-compose tree view of this session's modules.

    See :meth:`apeGmsh.mesh._compose.Compose.compose_tree`.
    """
    return self._compose_facade().compose_tree()

Part

Part(name: str, *, auto_persist: bool = True)

Bases: _SessionBase

An isolated geometry unit — no meshing, no solver state.

Carries geometry plus Tier-1 naming (labels + auto-created physical groups from label= kwargs, persisted via the STEP sidecar). For independently-meshed parts use a full session per part + g.compose instead — see the module docstring.

Parameters

name : str Descriptive name (also used as the Gmsh model name). auto_persist : bool, default True When True, the Part writes its geometry to an OS tempfile on end() if save() was not called explicitly. The tempfile is reclaimed via weakref.finalize when the Part is garbage-collected, or eagerly via cleanup(). Set to False to opt out — in that case parts.add(part) will raise FileNotFoundError unless you called save() by hand.

Source code in src/apeGmsh/core/Part.py
def __init__(self, name: str, *, auto_persist: bool = True) -> None:
    super().__init__(name=name, verbose=False)
    # Register this Part's name in the process-wide clash table
    # so Part.edit.copy / pattern_* can detect duplicates.
    from ._part_edit import _register_part_name
    _register_part_name(name, self)
    self.file_path: Path | None = None       # set by save() or auto-persist
    self.properties: dict[str, Any] = {}     # user metadata
    # When a geometry method is called with ``label="name"``,
    # ``Model._register`` auto-creates a physical group so the
    # label travels through the STEP sidecar into the Assembly.
    self._auto_pg_from_label = True

    # Auto-persist bookkeeping.  ``_owns_file`` is the
    # authorisation bit for deletion — it is True only when we
    # wrote the file ourselves into a temp directory, never
    # when the user called save() with an explicit path.
    self._auto_persist: bool = auto_persist
    self._owns_file: bool = False
    self._temp_dir: Path | None = None
    self._finalizer: weakref.finalize | None = None

has_file property

has_file: bool

True if the Part has been saved to disk.

begin

begin(*, verbose: bool | None = None) -> 'Part'

Open the Part's Gmsh session.

If the Part is being reused — a previous with part: block auto-persisted a tempfile and this call re-enters — the stale tempfile is cleaned up before the new session starts so the next end() can auto-persist fresh geometry.

Source code in src/apeGmsh/core/Part.py
def begin(self, *, verbose: bool | None = None) -> "Part":
    """Open the Part's Gmsh session.

    If the Part is being reused — a previous ``with part:`` block
    auto-persisted a tempfile and this call re-enters — the stale
    tempfile is cleaned up before the new session starts so the
    next ``end()`` can auto-persist fresh geometry.
    """
    if self._owns_file:
        self.cleanup()
        self.file_path = None
    return super().begin(verbose=verbose)  # type: ignore[return-value]

end

end() -> None

Close the Part's Gmsh session.

When auto_persist=True and the user did not call save() inside the session, the geometry is written to an OS tempfile before Gmsh is finalised so the Part can flow straight into assembly.parts.add(part).

Exceptions raised by auto-persist itself are caught and emitted as a warning rather than masking any exception the user's build code may have raised. Gmsh finalisation always runs.

Source code in src/apeGmsh/core/Part.py
def end(self) -> None:
    """Close the Part's Gmsh session.

    When ``auto_persist=True`` and the user did not call
    ``save()`` inside the session, the geometry is written to
    an OS tempfile **before** Gmsh is finalised so the Part can
    flow straight into ``assembly.parts.add(part)``.

    Exceptions raised by auto-persist itself are caught and
    emitted as a warning rather than masking any exception the
    user's build code may have raised.  Gmsh finalisation
    always runs.
    """
    try:
        if (
            self._active
            and self._auto_persist
            and self.file_path is None
            and gmsh.model.getEntities()
        ):
            self._auto_persist_to_temp()
    except Exception as exc:
        warnings.warn(
            f"Part {self.name!r}: auto-persist failed ({exc!r}); "
            f"the Part will not be auto-importable via "
            f"parts.add(). Call part.save('...') explicitly to "
            f"recover.",
            stacklevel=2,
        )
    finally:
        super().end()

cleanup

cleanup() -> None

Delete any auto-persisted tempfile now, without waiting for garbage collection.

Safe to call multiple times. Safe to call on a Part whose file_path was set by explicit save() — the _owns_file guard means the user's file is never touched. After cleanup(), has_file returns False and the Part can be re-built via a new with block.

Source code in src/apeGmsh/core/Part.py
def cleanup(self) -> None:
    """Delete any auto-persisted tempfile now, without waiting
    for garbage collection.

    Safe to call multiple times.  Safe to call on a Part whose
    ``file_path`` was set by explicit ``save()`` — the
    ``_owns_file`` guard means the user's file is never
    touched.  After ``cleanup()``, ``has_file`` returns False
    and the Part can be re-built via a new ``with`` block.
    """
    # Snapshot ownership BEFORE resetting it so the
    # post-finalizer file_path reset only runs when we
    # genuinely owned the file.
    was_owned = self._owns_file

    if self._finalizer is not None and self._finalizer.alive:
        self._finalizer()
    self._finalizer = None
    self._owns_file = False
    self._temp_dir = None

    if was_owned:
        self.file_path = None

save

save(file_path: str | Path | None = None, *, fmt: str | None = None, write_anchors: bool = True, _internal_autopersist: bool = False) -> Path

Export the Part geometry to a CAD file.

Calling save() with a user-supplied path transfers ownership of the output file to the caller — any tempfile previously created by auto-persist is cleaned up immediately, and the library will never delete the new output.

Parameters

file_path : str, Path, or None Destination path. If None, defaults to "{name}.step". The extension determines the format unless fmt overrides it. fmt : str, optional Force format: "step" or "iges". write_anchors : bool, default True Write a JSON sidecar ({file_path}.apegmsh.json) carrying the label -> center-of-mass map for every user-named entity in the Part. This is what lets assembly.parts.add(part) expose the instance's labels via inst.by_label('name'). The sidecar is silently omitted when the Part has no user-named entities, so there is no cost for small throwaway Parts. Pass write_anchors=False to suppress unconditionally — useful when publishing a CAD file to third-party tools that shouldn't see apeGmsh metadata.

Returns

Path Resolved path of the written file.

Source code in src/apeGmsh/core/Part.py
def save(
    self,
    file_path: str | Path | None = None,
    *,
    fmt: str | None = None,
    write_anchors: bool = True,
    _internal_autopersist: bool = False,
) -> Path:
    """
    Export the Part geometry to a CAD file.

    Calling ``save()`` with a user-supplied path **transfers
    ownership of the output file to the caller** — any
    tempfile previously created by auto-persist is cleaned up
    immediately, and the library will never delete the new
    output.

    Parameters
    ----------
    file_path : str, Path, or None
        Destination path.  If ``None``, defaults to
        ``"{name}.step"``.  The extension determines the format
        unless *fmt* overrides it.
    fmt : str, optional
        Force format: ``"step"`` or ``"iges"``.
    write_anchors : bool, default True
        Write a JSON sidecar (``{file_path}.apegmsh.json``)
        carrying the label -> center-of-mass map for every
        user-named entity in the Part.  This is what lets
        ``assembly.parts.add(part)`` expose the instance's
        labels via ``inst.by_label('name')``.  The sidecar is
        silently omitted when the Part has no user-named
        entities, so there is no cost for small throwaway
        Parts.  Pass ``write_anchors=False`` to suppress
        unconditionally — useful when publishing a CAD file
        to third-party tools that shouldn't see apeGmsh
        metadata.

    Returns
    -------
    Path
        Resolved path of the written file.
    """
    if not self._active:
        raise RuntimeError("Part session is not active — call begin() first.")

    # Explicit save by the user: hand off ownership.  The
    # internal auto-persist path sets ``_internal_autopersist``
    # so this branch is skipped — otherwise auto-persist would
    # cleanup() mid-write and zero out the temp directory we're
    # about to create the file in.
    if not _internal_autopersist and self._owns_file:
        self.cleanup()

    # Default: save as STEP using the Part name
    if file_path is None:
        file_path = Path(f"{self.name}.step")

    file_path = Path(file_path)

    # Override extension if fmt is given
    if fmt is not None:
        fmt = fmt.lower().strip(".")
        ext_map = {"step": ".step", "stp": ".step",
                   "iges": ".iges", "igs": ".iges"}
        ext = ext_map.get(fmt)
        if ext is None:
            raise ValueError(f"Unknown format '{fmt}'. Use 'step' or 'iges'.")
        file_path = file_path.with_suffix(ext)

    if file_path.suffix.lower() not in self._VALID_EXT:
        raise ValueError(
            f"Extension '{file_path.suffix}' is not a supported CAD format. "
            f"Use one of {self._VALID_EXT}."
        )

    # Sync OCC kernel before export
    gmsh.model.occ.synchronize()
    gmsh.write(str(file_path))
    self.file_path = file_path.resolve()

    # Write the label->COM sidecar so Assembly.parts.add(part)
    # can expose this Part's user-named entities via
    # ``inst.by_label(...)``.  Failures here are warned, not
    # raised — the CAD write itself already succeeded.
    if write_anchors:
        self._write_anchors(self.file_path)

    return self.file_path

PartsRegistry

PartsRegistry(parent: '_SessionBase')

Bases: _PartsFragmentationMixin

Instance management composite — registered as g.parts.

Source code in src/apeGmsh/core/_parts_registry.py
def __init__(self, parent: "_SessionBase") -> None:
    self._parent = parent
    self._instances: dict[str, Instance] = {}
    self._counter: int = 0

instances property

instances: dict[str, Instance]

Read-only view of all instances.

part

part(label: str)

Track entities created inside the block as a named part.

Yields the label string. After the block, any entities that exist now but didn't before are stored as an Instance.

Example::

with g.parts.part("beam"):
    g.model.geometry.add_box(0, 0, 0, 1, 0.5, 10)
Source code in src/apeGmsh/core/_parts_registry.py
@contextmanager
def part(self, label: str):
    """Track entities created inside the block as a named part.

    Yields the label string.  After the block, any entities that
    exist now but didn't before are stored as an Instance.

    Example::

        with g.parts.part("beam"):
            g.model.geometry.add_box(0, 0, 0, 1, 0.5, 10)
    """
    if label in self._instances:
        raise ValueError(f"Part label '{label}' already exists.")

    before = {d: set(t for _, t in gmsh.model.getEntities(d)) for d in range(4)}
    yield label
    after = {d: set(t for _, t in gmsh.model.getEntities(d)) for d in range(4)}

    entities: dict[int, list[int]] = {}
    for d in range(4):
        new_tags = sorted(after[d] - before[d])
        if new_tags:
            entities[d] = new_tags

    dimtags = [(d, t) for d, tags in entities.items() for t in tags]
    inst = Instance(
        label=label,
        part_name=label,
        entities=entities,
        bbox=self._compute_bbox(dimtags) if dimtags else None,
    )
    self._register_instance(inst)

register

register(name: str, dimtags: list[DimTag] | None = None, *, label: str | None = None, pg: str | None = None, dim: int | None = None) -> Instance

Tag existing entities under a part name.

Exactly one of dimtags, label, or pg must be given.

Parameters

name : str Unique part name. dimtags : list of (dim, tag), optional Entities to assign directly. Also accepted positionally as the second argument. label : str, optional Name of an apeGmsh label (g.labels) whose entities should be adopted. pg : str, optional Name of a physical group (g.physical) whose entities should be adopted. dim : int, optional Forwarded to g.labels.entities(label, dim=dim) when using label= and the label spans multiple dimensions.

Returns

Instance

Source code in src/apeGmsh/core/_parts_registry.py
def register(
    self,
    name: str,
    dimtags: list[DimTag] | None = None,
    *,
    label: str | None = None,
    pg: str | None = None,
    dim: int | None = None,
) -> Instance:
    """Tag existing entities under a part name.

    Exactly one of ``dimtags``, ``label``, or ``pg`` must be given.

    Parameters
    ----------
    name : str
        Unique part name.
    dimtags : list of (dim, tag), optional
        Entities to assign directly.  Also accepted positionally
        as the second argument.
    label : str, optional
        Name of an apeGmsh label (``g.labels``) whose entities
        should be adopted.
    pg : str, optional
        Name of a physical group (``g.physical``) whose entities
        should be adopted.
    dim : int, optional
        Forwarded to ``g.labels.entities(label, dim=dim)`` when
        using ``label=`` and the label spans multiple dimensions.

    Returns
    -------
    Instance
    """
    provided = sum(x is not None for x in (dimtags, label, pg))
    if provided != 1:
        raise TypeError(
            "register() requires exactly one of dimtags=, label=, "
            f"or pg= (got {provided})."
        )

    if label is not None:
        labels_comp = self._parent.labels
        if dim is not None:
            tags = labels_comp.entities(label, dim=dim)
            resolved: list[DimTag] = [(dim, int(t)) for t in tags]
        else:
            # Raises ValueError on multi-dim, KeyError on missing
            labels_comp.entities(label)
            resolved = []
            for d in range(4):
                try:
                    d_tags = labels_comp.entities(label, dim=d)
                except KeyError:
                    continue
                resolved = [(d, int(t)) for t in d_tags]
                break
    elif pg is not None:
        physical = self._parent.physical
        resolved = []
        for d in range(4):
            pg_tag = physical.get_tag(d, pg)
            if pg_tag is None:
                continue
            resolved.extend(
                (d, int(t)) for t in physical.get_entities(d, pg_tag)
            )
        if not resolved:
            raise KeyError(f"No physical group named {pg!r}.")
        pg_dims = {d for d, _ in resolved}
        if len(pg_dims) > 1:
            raise ValueError(
                f"Physical group {pg!r} exists at multiple "
                f"dimensions {sorted(pg_dims)}. Multi-dimensional "
                f"physical groups are not supported."
            )
    else:
        resolved = [(int(d), int(t)) for d, t in dimtags]

    if name in self._instances:
        raise ValueError(f"Part label '{name}' already exists.")

    # Ownership check — each entity can belong to at most one part
    for d, t in resolved:
        for existing_label, existing_inst in self._instances.items():
            if t in existing_inst.entities.get(d, []):
                raise ValueError(
                    f"Entity (dim={d}, tag={t}) already belongs to "
                    f"part '{existing_label}'. Remove it first."
                )

    entities: dict[int, list[int]] = {}
    for d, t in resolved:
        entities.setdefault(d, []).append(t)

    inst = Instance(
        label=name,
        part_name=name,
        entities=entities,
        bbox=self._compute_bbox(resolved) if resolved else None,
    )
    self._register_instance(inst)
    return inst

from_model

from_model(label: str, *, dim: int | None = None, tags: list[int] | None = None) -> Instance

Adopt entities already in the Gmsh session as a named part.

Useful after g.model.io.load_step() or g.model.io.load_iges() when you want the imported geometry tracked for constraints and fragmentation.

Parameters

label : str Part name. dim : int, optional Dimension to adopt. If None, adopts all dimensions. tags : list[int], optional Specific entity tags to adopt. If None, adopts all untracked entities (not already assigned to a part).

Returns

Instance

Examples

::

# Load geometry, then adopt it
g.model.io.load_step("bracket.step")
g.parts.from_model("bracket")

# Adopt only specific volumes
g.parts.from_model("slab", dim=3, tags=[1, 2])
Source code in src/apeGmsh/core/_parts_registry.py
def from_model(
    self,
    label: str,
    *,
    dim: int | None = None,
    tags: list[int] | None = None,
) -> Instance:
    """Adopt entities already in the Gmsh session as a named part.

    Useful after ``g.model.io.load_step()`` or ``g.model.io.load_iges()``
    when you want the imported geometry tracked for constraints
    and fragmentation.

    Parameters
    ----------
    label : str
        Part name.
    dim : int, optional
        Dimension to adopt.  If None, adopts all dimensions.
    tags : list[int], optional
        Specific entity tags to adopt.  If None, adopts all
        **untracked** entities (not already assigned to a part).

    Returns
    -------
    Instance

    Examples
    --------
    ::

        # Load geometry, then adopt it
        g.model.io.load_step("bracket.step")
        g.parts.from_model("bracket")

        # Adopt only specific volumes
        g.parts.from_model("slab", dim=3, tags=[1, 2])
    """
    if label in self._instances:
        raise ValueError(f"Part label '{label}' already exists.")

    # Collect already-tracked tags per dim
    tracked: dict[int, set[int]] = {}
    for inst in self._instances.values():
        for d, ts in inst.entities.items():
            tracked.setdefault(d, set()).update(ts)

    # Determine which dims to scan
    dims = [dim] if dim is not None else list(range(4))

    entities: dict[int, list[int]] = {}
    for d in dims:
        all_tags_d = [t for _, t in gmsh.model.getEntities(d)]
        if tags is not None:
            # User specified exact tags — use them
            adopted = [t for t in all_tags_d if t in tags]
        else:
            # Adopt untracked entities
            adopted = [t for t in all_tags_d if t not in tracked.get(d, set())]
        if adopted:
            entities[d] = sorted(adopted)

    if not entities:
        import warnings
        warnings.warn(
            f"No entities to adopt for part '{label}'.  "
            f"All entities are already tracked or the session is empty.",
            stacklevel=2,
        )

    dimtags = [(d, t) for d, ts in entities.items() for t in ts]
    inst = Instance(
        label=label,
        part_name=label,
        entities=entities,
        bbox=self._compute_bbox(dimtags) if dimtags else None,
    )
    self._register_instance(inst)
    return inst

add

add(part: 'Part', *, label: str | None = None, translate: tuple[float, float, float] = (0.0, 0.0, 0.0), rotate: tuple[float, ...] | None = None, highest_dim_only: bool = True) -> Instance

Import a saved Part into the session.

Parameters

part : Part Must have been save()-d to disk. label : str, optional Auto-generated as "{part.name}_1" if omitted. translate, rotate : placement transforms. highest_dim_only : keep only highest-dim entities from the CAD.

Source code in src/apeGmsh/core/_parts_registry.py
def add(
    self,
    part: "Part",
    *,
    label: str | None = None,
    translate: tuple[float, float, float] = (0.0, 0.0, 0.0),
    rotate: tuple[float, ...] | None = None,
    highest_dim_only: bool = True,
) -> Instance:
    """Import a saved Part into the session.

    Parameters
    ----------
    part : Part
        Must have been ``save()``-d to disk.
    label : str, optional
        Auto-generated as ``"{part.name}_1"`` if omitted.
    translate, rotate : placement transforms.
    highest_dim_only : keep only highest-dim entities from the CAD.
    """
    if not part.has_file:
        hint = (
            "Call part.save('file.step') explicitly"
            if not getattr(part, "_auto_persist", True)
            else
            "Exit the Part's `with` block (or call part.end()) "
            "before calling parts.add(part) so auto-persist can "
            "write the tempfile, OR call part.save('file.step') "
            "explicitly"
        )
        raise FileNotFoundError(
            f"Part '{part.name}' has no file to import.  {hint}."
        )
    if label is None:
        self._counter += 1
        label = f"{part.name}_{self._counter}"
    # part.has_file was checked above; this implies file_path
    # is not None. Narrow the type for mypy.
    assert part.file_path is not None
    return self._import_cad(
        file_path=part.file_path,
        label=label,
        part_name=part.name,
        translate=translate,
        rotate=rotate,
        highest_dim_only=highest_dim_only,
        properties=dict(part.properties),
    )

add_plane_wave_box

add_plane_wave_box(*, x: tuple[float, int], y: tuple[float, int], z, skin_thickness=None, center: tuple[float, float, float] = (0.0, 0.0, 0.0), rotation_z_deg: float = 0.0, name: str | None = None, names: dict[str, str] | None = None, apply_transfinite: bool = True)

Build a structured soil box wrapped by an ASDAbsorbingBoundary skin.

A plane-wave box is an axis-aligned structured soil box plus a one-element-thick absorbing offset shell on its five truncation faces (the local +Z top is the free surface and is never shelled). Soil + shell form one rectangular block; the shell is decomposed into face / vertical-edge / bottom-edge / bottom-corner regions, each tagged with its OpenSees btype. The companion bridge element (ASDAbsorbingBoundary3D) fans out one element per skin-region hex.

Built directly in the live session (no Part/STEP round-trip); pairs with — but does not use — :meth:add_DRM_box. See ADR 0054.

Parameters

x, y : (size, n_elements) Lateral soil extent (symmetric, centred) and element count. z : (depth, n_elements) | list[(depth, n_elements)] Vertical soil extent (downward, free surface at the top) and element count. Pass a top → bottom list of layers for a stratified column (e.g. z=[(15, 3), (25, 5)]); each layer gets its own soil + lateral skin PGs, so it can take its own absorbing material via ops.element.absorbing_boundary(materials=[m0, m1, …]) (ADR 0054 AB-1c). skin_thickness : float | (tx, ty, tz) | None Absorbing-skin thickness. None (default) matches the adjacent soil element size per face. A skin much thicker than the adjacent soil element warns (WarnAbsorbingSkinAspect) — it absorbs poorly. center : (cx, cy, cz) World location of the soil top-face centre (free surface). rotation_z_deg : float Must be 0 — the ASDAbsorbingBoundary3D element requires boundary-face normals along global X or Y, so a rotated absorbing box is rejected by the solver. name, names, apply_transfinite : PG-name prefix, per-PG override dict, and transfinite toggle — mirroring :meth:add_DRM_box.

Returns

AbsorbingSkinResult PG names (soil_pg, skin_pgs by btype, skin_all_pg, bottom_pgs, free_surface_pg), axes, and placement.

Example

::

res = g.parts.add_plane_wave_box(
    x=(605, 22), y=(605, 20), z=(420, 16),
)
g.mesh.generation.generate(dim=3)
# res.skin_pgs["L"], res.skin_all_pg, res.bottom_pgs ...
Source code in src/apeGmsh/core/_parts_registry.py
def add_plane_wave_box(
    self,
    *,
    x: tuple[float, int],
    y: tuple[float, int],
    z,
    skin_thickness=None,
    center: tuple[float, float, float] = (0.0, 0.0, 0.0),
    rotation_z_deg: float = 0.0,
    name: str | None = None,
    names: dict[str, str] | None = None,
    apply_transfinite: bool = True,
):
    """Build a structured soil box wrapped by an ASDAbsorbingBoundary skin.

    A *plane-wave box* is an axis-aligned structured soil box plus a
    one-element-thick absorbing **offset shell** on its five truncation
    faces (the local ``+Z`` top is the free surface and is never shelled).
    Soil + shell form one rectangular block; the shell is decomposed into
    face / vertical-edge / bottom-edge / bottom-corner regions, each tagged
    with its OpenSees ``btype``.  The companion bridge element
    (``ASDAbsorbingBoundary3D``) fans out one element per skin-region hex.

    Built directly in the live session (no Part/STEP round-trip); pairs with
    — but does not use — :meth:`add_DRM_box`.  See ADR 0054.

    Parameters
    ----------
    x, y : (size, n_elements)
        Lateral soil extent (symmetric, centred) and element count.
    z : (depth, n_elements) | list[(depth, n_elements)]
        Vertical soil extent (downward, free surface at the top) and element
        count.  Pass a top → bottom ``list`` of layers for a stratified column
        (e.g. ``z=[(15, 3), (25, 5)]``); each layer gets its own soil + lateral
        skin PGs, so it can take its own absorbing material via
        ``ops.element.absorbing_boundary(materials=[m0, m1, …])`` (ADR 0054 AB-1c).
    skin_thickness : float | (tx, ty, tz) | None
        Absorbing-skin thickness.  ``None`` (default) matches the adjacent
        soil element size per face.  A skin much thicker than the adjacent
        soil element warns (`WarnAbsorbingSkinAspect`) — it absorbs poorly.
    center : (cx, cy, cz)
        World location of the soil top-face centre (free surface).
    rotation_z_deg : float
        Must be ``0`` — the ASDAbsorbingBoundary3D element requires
        boundary-face normals along global X or Y, so a rotated absorbing
        box is rejected by the solver.
    name, names, apply_transfinite :
        PG-name prefix, per-PG override dict, and transfinite toggle —
        mirroring :meth:`add_DRM_box`.

    Returns
    -------
    AbsorbingSkinResult
        PG names (``soil_pg``, ``skin_pgs`` by btype, ``skin_all_pg``,
        ``bottom_pgs``, ``free_surface_pg``), ``axes``, and placement.

    Example
    -------
    ::

        res = g.parts.add_plane_wave_box(
            x=(605, 22), y=(605, 20), z=(420, 16),
        )
        g.mesh.generation.generate(dim=3)
        # res.skin_pgs["L"], res.skin_all_pg, res.bottom_pgs ...
    """
    from apeGmsh.parts.plane_wave_box import build_plane_wave_box

    return build_plane_wave_box(
        self._parent,
        x=x, y=y, z=z,
        skin_thickness=skin_thickness,
        center=center,
        rotation_z_deg=rotation_z_deg,
        name=name,
        names=names,
        apply_transfinite=apply_transfinite,
    )

add_DRM_box_from_h5drm

add_DRM_box_from_h5drm(*, h5drm: str, crd_scale: float = 1000.0, buffer: int = 0, absorbing: bool = False, name: str | None = None, names: dict[str, str] | None = None, apply_transfinite: bool = True)

Build a structured soil box matched to an .h5drm station grid.

Reads a ShakerMaker-style .h5drm DRM dataset and builds, in the live session, a single transfinite hex box whose nodes land EXACTLY on the dataset stations (so OpenSees' H5DRM node-matching is trivial), tags the soil volume + the six outer boundary faces (the dataset "b" shell) as physical groups, and returns the frame contract the matching ops.pattern.H5DRM(...) consumes — so the user never re-derives the km→m / centred / z-down handshake. See ADR 0066.

The dataset-keyed sibling of the parametric :meth:add_DRM_box (an SSI inner/transition/outer layout, NOT keyed to a dataset). Geometry + PGs only — assign the soil material and elements via the bridge (ops.nDMaterial + ops.element.stdBrick(pg=result.soil_pg)).

Parameters

h5drm : str Path to the .h5drm dataset (DRM_Data/{xyz,internal} + DRM_Metadata/drmbox_x0). The station grid must be a complete, uniform, isotropic regular grid. crd_scale : float Station-units → model-units scale. ShakerMaker stations are in km, FE models in m ⇒ default 1000.0. buffer : int Number of exterior soil layers to add OUTWARD on the four sides + the bottom (never the free surface), at the same grid spacing. 0 (default) builds just the inner DRM box. A free DRM box diverges (rigid-body null-space excited by the residual), so a real run needs a buffer + a far boundary: the buffer hexes carry only NON-dataset nodes, so H5DRM excludes them from the effective-force set (H5DRMLoadPattern.cpp:580). Apply the boundary on result.exterior_pgs via the bridge (ops.fix for the validated fixed far field). absorbing : bool When True (requires buffer >= 1), wrap the buffered box in a one-element ASD absorbing skin (btype-tagged ghost layer) on the sides + bottom — the production-SSI boundary (ADR 0054). The skin sits on the buffer's outer (NON-dataset) faces, so it never lands on the DRM b shell. result.skin is then an AbsorbingSkinResult ready for ops.element.absorbing_boundary(skin=result.skin, ...) + the staged s.activate_absorbing() flip. name, names, apply_transfinite : PG-name prefix, per-PG override dict, and transfinite toggle — mirroring :meth:add_DRM_box.

Returns

DRMBoxFromH5Result soil_pg, boundary_pgs (by face key), boundary_all_pg, free_surface_pg, exterior_pgs (sides+bottom), the frame contract (crd_scale / transform / x0 / center), and the grid descriptor (origin / spacing / counts).

Example

::

drm = g.parts.add_DRM_box_from_h5drm("motions.h5drm")
g.mesh.generation.generate(dim=3)
fem = g.mesh.queries.get_fem_data(dim=3)
ops = apeSees(fem)
soil = ops.nDMaterial.ElasticIsotropic(E=E, nu=nu, rho=rho)
ops.element.stdBrick(pg=drm.soil_pg, material=soil)
with ops.pattern.H5DRM(h5drm="motions.h5drm"):   # defaults match drm
    pass
Source code in src/apeGmsh/core/_parts_registry.py
def add_DRM_box_from_h5drm(
    self,
    *,
    h5drm: str,
    crd_scale: float = 1000.0,
    buffer: int = 0,
    absorbing: bool = False,
    name: str | None = None,
    names: dict[str, str] | None = None,
    apply_transfinite: bool = True,
):
    """Build a structured soil box matched to an ``.h5drm`` station grid.

    Reads a ShakerMaker-style ``.h5drm`` DRM dataset and builds, in the live
    session, a single transfinite hex box whose nodes land EXACTLY on the
    dataset stations (so OpenSees' H5DRM node-matching is trivial), tags the
    soil volume + the six outer boundary faces (the dataset "b" shell) as
    physical groups, and returns the **frame contract** the matching
    ``ops.pattern.H5DRM(...)`` consumes — so the user never re-derives the
    km→m / centred / z-down handshake.  See ADR 0066.

    The dataset-keyed sibling of the parametric :meth:`add_DRM_box` (an SSI
    inner/transition/outer layout, NOT keyed to a dataset).  Geometry + PGs
    only — assign the soil material and elements via the bridge
    (``ops.nDMaterial`` + ``ops.element.stdBrick(pg=result.soil_pg)``).

    Parameters
    ----------
    h5drm : str
        Path to the ``.h5drm`` dataset (``DRM_Data/{xyz,internal}`` +
        ``DRM_Metadata/drmbox_x0``).  The station grid must be a complete,
        uniform, isotropic regular grid.
    crd_scale : float
        Station-units → model-units scale.  ShakerMaker stations are in km,
        FE models in m ⇒ default ``1000.0``.
    buffer : int
        Number of exterior soil layers to add OUTWARD on the four sides + the
        bottom (never the free surface), at the same grid spacing.  ``0``
        (default) builds just the inner DRM box.  A free DRM box diverges
        (rigid-body null-space excited by the residual), so a real run needs a
        buffer + a far boundary: the buffer hexes carry only NON-dataset
        nodes, so H5DRM excludes them from the effective-force set
        (H5DRMLoadPattern.cpp:580).  Apply the boundary on
        ``result.exterior_pgs`` via the bridge (``ops.fix`` for the validated
        fixed far field).
    absorbing : bool
        When ``True`` (requires ``buffer >= 1``), wrap the buffered box in a
        one-element **ASD absorbing skin** (btype-tagged ghost layer) on the
        sides + bottom — the production-SSI boundary (ADR 0054).  The skin
        sits on the buffer's outer (NON-dataset) faces, so it never lands on
        the DRM ``b`` shell.  ``result.skin`` is then an ``AbsorbingSkinResult``
        ready for ``ops.element.absorbing_boundary(skin=result.skin, ...)`` +
        the staged ``s.activate_absorbing()`` flip.
    name, names, apply_transfinite :
        PG-name prefix, per-PG override dict, and transfinite toggle —
        mirroring :meth:`add_DRM_box`.

    Returns
    -------
    DRMBoxFromH5Result
        ``soil_pg``, ``boundary_pgs`` (by face key), ``boundary_all_pg``,
        ``free_surface_pg``, ``exterior_pgs`` (sides+bottom), the frame
        contract (``crd_scale`` / ``transform`` / ``x0`` / ``center``), and
        the grid descriptor (``origin`` / ``spacing`` / ``counts``).

    Example
    -------
    ::

        drm = g.parts.add_DRM_box_from_h5drm("motions.h5drm")
        g.mesh.generation.generate(dim=3)
        fem = g.mesh.queries.get_fem_data(dim=3)
        ops = apeSees(fem)
        soil = ops.nDMaterial.ElasticIsotropic(E=E, nu=nu, rho=rho)
        ops.element.stdBrick(pg=drm.soil_pg, material=soil)
        with ops.pattern.H5DRM(h5drm="motions.h5drm"):   # defaults match drm
            pass
    """
    from apeGmsh.parts.h5drm_box import build_drm_box_from_h5drm

    return build_drm_box_from_h5drm(
        self._parent,
        h5drm=h5drm,
        crd_scale=crd_scale,
        buffer=buffer,
        absorbing=absorbing,
        name=name,
        names=names,
        apply_transfinite=apply_transfinite,
    )

add_absorbing_shell

add_absorbing_shell(*, box, element_size, skin_thickness=None, faces: tuple[str, ...] | None = None, layers: list[tuple[float, int]] | None = None, name: str | None = None, names: dict[str, str] | None = None, apply_transfinite: bool = True)

Weld a one-element ASDAbsorbingBoundary skin onto your own soil box.

The bring-your-own-box counterpart to :meth:add_plane_wave_box: you build the soil box (its placement, PGs, the material/structure you later put on it), and this wraps a one-element-thick absorbing skin onto its five truncation faces — the local +Z top is the free surface and is never shelled. Returns the same :class:AbsorbingSkinResult as :meth:add_plane_wave_box, so the bridge element (ops.element.absorbing_boundary) and the staged flip (s.activate_absorbing) consume it identically. See ADR 0054 (AB-1b).

The skin discretization is size-based and (re)applied to box + skin together after the weld: gmsh cannot report transfinite counts back and the boolean fragment renumbers entities, so the box's prior mesh state is irrelevant — this call makes box + skin one structured hex region.

Parameters

box : The soil box — a PG / label name or a volume handle. Must resolve to exactly one axis-aligned rectangular volume (fail-loud otherwise; rotated / curved / multi-volume boxes are out of scope for this slice). element_size : float | (sx, sy, sz) Target soil element size; sets the structured node counts on box+skin. skin_thickness : float | (tx, ty, tz) | None Absorbing-skin thickness. None (default) matches element_size per axis (one element thick). faces : tuple[str, ...] | None Restrict the skin to a subset of ("L","R","F","K","B") (e.g. omit a symmetry plane). None (default) shells all five truncation faces. layers : list[(depth, n_elements)] | None Stratify the box top → bottom (depths must sum to the box's z-extent). Slices the box into per-layer soil volumes and splits the lateral skin per layer, so each layer can take its own absorbing material via ops.element.absorbing_boundary(materials=[m0, m1, …]) (ADR 0054 AB-1c). None (default) = homogeneous. name, names, apply_transfinite : PG-name prefix, per-PG override dict, and transfinite toggle — mirroring :meth:add_plane_wave_box. When box is a name, soil_pg is reported as that name (no duplicate PG is created).

Returns

AbsorbingSkinResult PG names (soil_pg, skin_pgs by btype, skin_all_pg, bottom_pgs, free_surface_pg), axes, and placement.

Example

::

g.model.geometry.add_box(0, 0, -40, 20, 20, 40, label="soil")
res = g.parts.add_absorbing_shell(box="soil", element_size=2.5)
g.mesh.generation.generate(dim=3)
# res.skin_all_pg, res.bottom_pgs, res.free_surface_pg ...
Source code in src/apeGmsh/core/_parts_registry.py
def add_absorbing_shell(
    self,
    *,
    box,
    element_size,
    skin_thickness=None,
    faces: tuple[str, ...] | None = None,
    layers: list[tuple[float, int]] | None = None,
    name: str | None = None,
    names: dict[str, str] | None = None,
    apply_transfinite: bool = True,
):
    """Weld a one-element ASDAbsorbingBoundary skin onto your own soil box.

    The *bring-your-own-box* counterpart to :meth:`add_plane_wave_box`: you
    build the soil box (its placement, PGs, the material/structure you later
    put on it), and this wraps a one-element-thick absorbing **skin** onto its
    five truncation faces — the local ``+Z`` top is the free surface and is
    never shelled.  Returns the *same* :class:`AbsorbingSkinResult` as
    :meth:`add_plane_wave_box`, so the bridge element
    (``ops.element.absorbing_boundary``) and the staged flip
    (``s.activate_absorbing``) consume it identically.  See ADR 0054 (AB-1b).

    The skin discretization is **size-based** and (re)applied to box + skin
    together after the weld: gmsh cannot report transfinite counts back and
    the boolean ``fragment`` renumbers entities, so the box's prior mesh state
    is irrelevant — this call makes box + skin one structured hex region.

    Parameters
    ----------
    box :
        The soil box — a PG / label name or a volume handle.  Must resolve to
        exactly **one axis-aligned rectangular** volume (fail-loud otherwise;
        rotated / curved / multi-volume boxes are out of scope for this slice).
    element_size : float | (sx, sy, sz)
        Target soil element size; sets the structured node counts on box+skin.
    skin_thickness : float | (tx, ty, tz) | None
        Absorbing-skin thickness.  ``None`` (default) matches ``element_size``
        per axis (one element thick).
    faces : tuple[str, ...] | None
        Restrict the skin to a subset of ``("L","R","F","K","B")`` (e.g. omit a
        symmetry plane).  ``None`` (default) shells all five truncation faces.
    layers : list[(depth, n_elements)] | None
        Stratify the box top → bottom (depths must sum to the box's z-extent).
        Slices the box into per-layer soil volumes and splits the lateral skin
        per layer, so each layer can take its own absorbing material via
        ``ops.element.absorbing_boundary(materials=[m0, m1, …])`` (ADR 0054
        AB-1c).  ``None`` (default) = homogeneous.
    name, names, apply_transfinite :
        PG-name prefix, per-PG override dict, and transfinite toggle — mirroring
        :meth:`add_plane_wave_box`.  When ``box`` is a name, ``soil_pg`` is
        reported as that name (no duplicate PG is created).

    Returns
    -------
    AbsorbingSkinResult
        PG names (``soil_pg``, ``skin_pgs`` by btype, ``skin_all_pg``,
        ``bottom_pgs``, ``free_surface_pg``), ``axes``, and placement.

    Example
    -------
    ::

        g.model.geometry.add_box(0, 0, -40, 20, 20, 40, label="soil")
        res = g.parts.add_absorbing_shell(box="soil", element_size=2.5)
        g.mesh.generation.generate(dim=3)
        # res.skin_all_pg, res.bottom_pgs, res.free_surface_pg ...
    """
    from apeGmsh.parts.plane_wave_box import build_absorbing_shell

    return build_absorbing_shell(
        self._parent,
        box=box,
        element_size=element_size,
        skin_thickness=skin_thickness,
        faces=faces,
        layers=layers,
        name=name,
        names=names,
        apply_transfinite=apply_transfinite,
    )

add_plane_wave_box_2d

add_plane_wave_box_2d(*, x: tuple[float, int], y, skin_thickness=None, center: tuple[float, float] = (0.0, 0.0), rotation_z_deg: float = 0.0, name: str | None = None, names: dict[str, str] | None = None, apply_transfinite: bool = True)

Build a 2D plane-strain soil box wrapped by an absorbing skin.

The 2D sibling of :meth:add_plane_wave_box (ADR 0054, AB-5): a structured soil rectangle in the global X–Y plane at z = 0 (X lateral, Y vertical, free surface at the local top y = 0) plus a one-element-thick absorbing skin on its three truncation faces. Skin regions carry the 2D btypes — L = min-X, R = max-X, B = min-Y, corners BL/BR — and fan out to ASDAbsorbingBoundary2D quads via ops.element.absorbing_boundary(skin=…, thickness=…) (the 2D element needs the out-of-plane slab thickness).

Parameters

x : (size, n_elements) Lateral soil extent (symmetric, centred) and element count. y : (depth, n_elements) | list[(depth, n_elements)] Vertical soil extent (downward, free surface at the top). Pass a top → bottom list of layers for a stratified column; each layer gets its own soil + lateral skin PGs for per-layer absorbing materials (materials=[…]). skin_thickness : float | (tx, ty) | None Absorbing-skin thickness. None (default) matches the adjacent soil element size per face. center : (cx, cy) World location of the soil top-face centre (free surface). rotation_z_deg : float Must be 0 — the ASDAbsorbingBoundary2D element has no distortion handling (it sizes itself from sorted nodal x/y coordinates), so a rotated skin runs with silently wrong terms. name, names, apply_transfinite : PG-name prefix, per-PG override dict, and transfinite toggle.

Returns

AbsorbingSkinResult Same shape as the 3D result (ndm == 2; free_surface_pg is a dim-1 edge PG).

Example

::

res = g.parts.add_plane_wave_box_2d(x=(100, 20), y=(50, 10))
g.mesh.generation.generate(dim=2)
# res.skin_pgs -> {"B": ..., "L": ..., "R": ..., "BL": ..., "BR": ...}
Source code in src/apeGmsh/core/_parts_registry.py
def add_plane_wave_box_2d(
    self,
    *,
    x: tuple[float, int],
    y,
    skin_thickness=None,
    center: tuple[float, float] = (0.0, 0.0),
    rotation_z_deg: float = 0.0,
    name: str | None = None,
    names: dict[str, str] | None = None,
    apply_transfinite: bool = True,
):
    """Build a 2D plane-strain soil box wrapped by an absorbing skin.

    The 2D sibling of :meth:`add_plane_wave_box` (ADR 0054, AB-5): a
    structured soil rectangle in the global **X–Y plane at z = 0** (X
    lateral, Y vertical, free surface at the local top ``y = 0``) plus a
    one-element-thick absorbing skin on its three truncation faces.
    Skin regions carry the 2D btypes — ``L`` = min-X, ``R`` = max-X,
    ``B`` = min-Y, corners ``BL``/``BR`` — and fan out to
    ``ASDAbsorbingBoundary2D`` quads via
    ``ops.element.absorbing_boundary(skin=…, thickness=…)`` (the 2D
    element needs the out-of-plane slab thickness).

    Parameters
    ----------
    x : (size, n_elements)
        Lateral soil extent (symmetric, centred) and element count.
    y : (depth, n_elements) | list[(depth, n_elements)]
        Vertical soil extent (downward, free surface at the top).  Pass a
        top → bottom ``list`` of layers for a stratified column; each
        layer gets its own soil + lateral skin PGs for per-layer
        absorbing materials (``materials=[…]``).
    skin_thickness : float | (tx, ty) | None
        Absorbing-skin thickness.  ``None`` (default) matches the
        adjacent soil element size per face.
    center : (cx, cy)
        World location of the soil top-face centre (free surface).
    rotation_z_deg : float
        Must be ``0`` — the ASDAbsorbingBoundary2D element has **no**
        distortion handling (it sizes itself from sorted nodal x/y
        coordinates), so a rotated skin runs with silently wrong terms.
    name, names, apply_transfinite :
        PG-name prefix, per-PG override dict, and transfinite toggle.

    Returns
    -------
    AbsorbingSkinResult
        Same shape as the 3D result (``ndm == 2``; ``free_surface_pg``
        is a dim-1 edge PG).

    Example
    -------
    ::

        res = g.parts.add_plane_wave_box_2d(x=(100, 20), y=(50, 10))
        g.mesh.generation.generate(dim=2)
        # res.skin_pgs -> {"B": ..., "L": ..., "R": ..., "BL": ..., "BR": ...}
    """
    from apeGmsh.parts.plane_wave_box import build_plane_wave_box_2d

    return build_plane_wave_box_2d(
        self._parent,
        x=x, y=y,
        skin_thickness=skin_thickness,
        center=center,
        rotation_z_deg=rotation_z_deg,
        name=name,
        names=names,
        apply_transfinite=apply_transfinite,
    )

add_absorbing_shell_2d

add_absorbing_shell_2d(*, box, element_size, skin_thickness=None, faces: tuple[str, ...] | None = None, layers: list[tuple[float, int]] | None = None, name: str | None = None, names: dict[str, str] | None = None, apply_transfinite: bool = True)

Weld a one-element absorbing skin onto your own 2D soil rectangle.

The bring-your-own-box 2D entry (ADR 0054, AB-5), mirroring :meth:add_absorbing_shell: box must resolve to exactly one axis-aligned rectangular surface lying flat in a z = const plane. The skin goes on the L/R/B truncation edges (the top is the free surface); faces= restricts it (subset of ("L", "R", "B"), e.g. drop a symmetry edge). layers stratifies box + lateral skin top → bottom (depths must sum to the box's y-extent). Discretization is size-based and (re)applied to box + skin together after the weld, as in 3D.

Returns

AbsorbingSkinResult Same shape as the 3D result (ndm == 2).

Example

::

g.model.geometry.add_rectangle(0, -50, 0, 100, 50, label="soil")
res = g.parts.add_absorbing_shell_2d(box="soil", element_size=5.0)
g.mesh.generation.generate(dim=2)
Source code in src/apeGmsh/core/_parts_registry.py
def add_absorbing_shell_2d(
    self,
    *,
    box,
    element_size,
    skin_thickness=None,
    faces: tuple[str, ...] | None = None,
    layers: list[tuple[float, int]] | None = None,
    name: str | None = None,
    names: dict[str, str] | None = None,
    apply_transfinite: bool = True,
):
    """Weld a one-element absorbing skin onto your own 2D soil rectangle.

    The bring-your-own-box 2D entry (ADR 0054, AB-5), mirroring
    :meth:`add_absorbing_shell`: ``box`` must resolve to exactly one
    axis-aligned rectangular **surface** lying flat in a ``z = const``
    plane.  The skin goes on the ``L``/``R``/``B`` truncation edges (the
    top is the free surface); ``faces=`` restricts it (subset of
    ``("L", "R", "B")``, e.g. drop a symmetry edge).  ``layers``
    stratifies box + lateral skin top → bottom (depths must sum to the
    box's y-extent).  Discretization is size-based and (re)applied to
    box + skin together after the weld, as in 3D.

    Returns
    -------
    AbsorbingSkinResult
        Same shape as the 3D result (``ndm == 2``).

    Example
    -------
    ::

        g.model.geometry.add_rectangle(0, -50, 0, 100, 50, label="soil")
        res = g.parts.add_absorbing_shell_2d(box="soil", element_size=5.0)
        g.mesh.generation.generate(dim=2)
    """
    from apeGmsh.parts.plane_wave_box import build_absorbing_shell_2d

    return build_absorbing_shell_2d(
        self._parent,
        box=box,
        element_size=element_size,
        skin_thickness=skin_thickness,
        faces=faces,
        layers=layers,
        name=name,
        names=names,
        apply_transfinite=apply_transfinite,
    )

add_DRM_box

add_DRM_box(*, x_inner: tuple[float, int], x_layer: tuple[float, int], x_outer: tuple[float, int], y_inner: tuple[float, int], y_layer: tuple[float, int], y_outer: tuple[float, int], z_top: tuple[float, int], z_mid: tuple[float, int], z_bottom: tuple[float, int], center: tuple[float, float, float] = (0.0, 0.0, 0.0), rotation_z_deg: float = 0.0, name: str | None = None, names: dict[str, str] | None = None, apply_transfinite: bool = True, tag_line_pgs: bool = True)

Build, place, and tag a Domain-Reduction-Method soil box.

A DRM box is a layered solid with three concentric regions per lateral axis (inner core | transition layer | outer absorbing layer) and a downward Z stack (top | mid | bottom). The classic symmetric case has 5 * 5 * 3 = 75 axis-aligned hex sub-volumes, each meshed structured-hex with per-region element counts.

center=(0, 0, 0) puts the top-face centre of the inner box at the origin (free-surface convention). Rotation is applied CCW about +Z at center; the rotated frame survives every step (volume PGs, line PGs, transfinite cascade) because we classify by world-coords transformed back to the local frame.

Parameters

x_inner, x_layer, x_outer, y_inner, y_layer, y_outer : (size, n_elements) tuples — symmetric layered lateral axes. Each segment's element count drives the transfinite cascade. z_top, z_mid, z_bottom : (size, n_elements) tuples — downward Z stack with the free surface at z = 0 (inner-box top). center : World-coordinate location for the top-face centre of the inner box. rotation_z_deg : CCW rotation about +Z applied at center, in degrees. name : Instance label and default PG prefix. When None, uses "drm_box". PGs default to inner_box / transition_box / outer_box (and the matching lines_* curves); when name is given they become {name}_inner_box etc. names : Per-PG override dict. Keys: inner_pg, transition_pg, outer_pg, line_pg_<region>_<axis> (e.g. line_pg_inner_x, line_pg_top_z). Each override replaces the entire PG name (the name prefix is ignored for that key). apply_transfinite : When True (default), apply the structured-hex transfinite cascade to every sub-volume using the per-region element counts in axis_x / axis_y / axis_z. tag_line_pgs : When True (default), tag axis-parallel edges by region into curve PGs lines_{region}_{axis}. When False, result.line_pgs is empty.

Returns

DRMBoxResult Frozen summary with PG names, Axis1D descriptors, the applied center and rotation_z (in radians).

Example

::

res = g.parts.add_DRM_box(
    x_inner=(605, 10), x_layer=(10, 1), x_outer=(20, 2),
    y_inner=(605, 10), y_layer=(10, 1), y_outer=(20, 2),
    z_top=(50, 5), z_mid=(50, 5), z_bottom=(200, 20),
    center=(0, 0, 0),
)
g.mesh.generation.generate(dim=3)
# res.inner_pg == "inner_box", res.transition_pg == "transition_box",
# res.outer_pg == "outer_box"
Source code in src/apeGmsh/core/_parts_registry.py
def add_DRM_box(
    self,
    *,
    x_inner: tuple[float, int],
    x_layer: tuple[float, int],
    x_outer: tuple[float, int],
    y_inner: tuple[float, int],
    y_layer: tuple[float, int],
    y_outer: tuple[float, int],
    z_top: tuple[float, int],
    z_mid: tuple[float, int],
    z_bottom: tuple[float, int],
    center: tuple[float, float, float] = (0.0, 0.0, 0.0),
    rotation_z_deg: float = 0.0,
    name: str | None = None,
    names: dict[str, str] | None = None,
    apply_transfinite: bool = True,
    tag_line_pgs: bool = True,
):
    """Build, place, and tag a Domain-Reduction-Method soil box.

    A DRM box is a layered solid with three concentric regions
    per lateral axis (inner core | transition layer | outer
    absorbing layer) and a downward Z stack (top | mid | bottom).
    The classic symmetric case has ``5 * 5 * 3 = 75`` axis-aligned
    hex sub-volumes, each meshed structured-hex with per-region
    element counts.

    ``center=(0, 0, 0)`` puts the top-face centre of the inner
    box at the origin (free-surface convention).  Rotation is
    applied CCW about ``+Z`` at ``center``; the rotated frame
    survives every step (volume PGs, line PGs, transfinite
    cascade) because we classify by world-coords transformed
    back to the local frame.

    Parameters
    ----------
    x_inner, x_layer, x_outer, y_inner, y_layer, y_outer :
        ``(size, n_elements)`` tuples — symmetric layered lateral
        axes.  Each segment's element count drives the
        transfinite cascade.
    z_top, z_mid, z_bottom :
        ``(size, n_elements)`` tuples — downward Z stack with the
        free surface at ``z = 0`` (inner-box top).
    center :
        World-coordinate location for the top-face centre of the
        inner box.
    rotation_z_deg :
        CCW rotation about ``+Z`` applied at ``center``, in
        degrees.
    name :
        Instance label and default PG prefix.  When ``None``,
        uses ``"drm_box"``.  PGs default to ``inner_box`` /
        ``transition_box`` / ``outer_box`` (and the matching
        ``lines_*`` curves); when ``name`` is given they become
        ``{name}_inner_box`` etc.
    names :
        Per-PG override dict.  Keys: ``inner_pg``, ``transition_pg``,
        ``outer_pg``, ``line_pg_<region>_<axis>`` (e.g.
        ``line_pg_inner_x``, ``line_pg_top_z``).  Each override
        replaces the entire PG name (the ``name`` prefix is
        ignored for that key).
    apply_transfinite :
        When True (default), apply the structured-hex transfinite
        cascade to every sub-volume using the per-region element
        counts in ``axis_x`` / ``axis_y`` / ``axis_z``.
    tag_line_pgs :
        When True (default), tag axis-parallel edges by region
        into curve PGs ``lines_{region}_{axis}``.  When False,
        ``result.line_pgs`` is empty.

    Returns
    -------
    DRMBoxResult
        Frozen summary with PG names, Axis1D descriptors, the
        applied ``center`` and ``rotation_z`` (in radians).

    Example
    -------
    ::

        res = g.parts.add_DRM_box(
            x_inner=(605, 10), x_layer=(10, 1), x_outer=(20, 2),
            y_inner=(605, 10), y_layer=(10, 1), y_outer=(20, 2),
            z_top=(50, 5), z_mid=(50, 5), z_bottom=(200, 20),
            center=(0, 0, 0),
        )
        g.mesh.generation.generate(dim=3)
        # res.inner_pg == "inner_box", res.transition_pg == "transition_box",
        # res.outer_pg == "outer_box"
    """
    import math
    import numpy as np

    from apeGmsh.parts.drm_box import DRMBox, DRMBoxResult

    instance_label = name or "drm_box"

    # Resolve PG names — ``name`` acts as a prefix unless the user
    # supplied ``names`` overrides.  When ``name is None`` we keep
    # the bare defaults so the simple case stays terse.
    prefix = f"{name}_" if name else ""
    pg_defaults = {
        "inner_pg":      f"{prefix}inner_box",
        "transition_pg": f"{prefix}transition_box",
        "outer_pg":      f"{prefix}outer_box",
    }
    line_pg_defaults: dict[str, str] = {}
    # Lateral axes carry 3 regions; Z carries 3 regions of its
    # own.  The dict keys mirror the spec example
    # ``{'inner_x', 'layer_x', 'top_z'}``.
    for region in ("inner", "layer", "outer"):
        for axis in ("x", "y"):
            line_pg_defaults[f"{region}_{axis}"] = (
                f"{prefix}lines_{region}_{axis}"
            )
    for region in ("top", "mid", "bottom"):
        line_pg_defaults[f"{region}_z"] = (
            f"{prefix}lines_{region}_z"
        )

    overrides = dict(names or {})
    for k, default in pg_defaults.items():
        if k in overrides:
            pg_defaults[k] = str(overrides[k])
    # Line-PG override keys look like ``line_pg_inner_x``.
    for key in list(line_pg_defaults):
        override_key = f"line_pg_{key}"
        if override_key in overrides:
            line_pg_defaults[key] = str(overrides[override_key])

    # ── Build the DRM-box Part in its own session ────────────────
    # ``Part.begin()`` calls ``gmsh.model.add(part.name)``, which
    # makes the Part's model the current gmsh model.  The Part's
    # ``end()`` decrements the gmsh refcount but does NOT switch
    # the current model back, so without an explicit
    # ``setCurrent`` here ``self.add(drm)`` would importShapes into
    # the Part's model (doubling the volume count in the live
    # session).  Snapshot the assembly's model name first and
    # restore it after the Part's ``with`` block exits.
    assembly_model_name = self._parent.name
    drm = DRMBox(
        x_inner=x_inner, x_layer=x_layer, x_outer=x_outer,
        y_inner=y_inner, y_layer=y_layer, y_outer=y_outer,
        z_top=z_top, z_mid=z_mid, z_bottom=z_bottom,
        name=f"_drm_part_{instance_label}",
    )
    with drm:
        drm.build()
    gmsh.model.setCurrent(assembly_model_name)
    # ``drm`` now has an auto-persisted STEP tempfile.

    theta = math.radians(float(rotation_z_deg))
    rotate_arg: tuple[float, ...] | None
    if abs(theta) > 1e-15:
        # OCC rotate at world origin — then translate.  This
        # matches ``_apply_transforms``: rotate first about
        # axis through (0, 0, 0), then translate by ``center``.
        rotate_arg = (theta, 0.0, 0.0, 1.0)
    else:
        rotate_arg = None

    inst = self.add(
        drm,
        label=instance_label,
        translate=center,
        rotate=rotate_arg,
    )

    # Release the Part's tempfile — we've imported the geometry
    # and no longer need the on-disk STEP.  ``drm`` is otherwise
    # garbage-collected at function exit, but cleanup() here
    # avoids waiting for GC.
    drm.cleanup()

    # ── Classify each sub-volume in the local frame ─────────────
    cx, cy, cz = (float(v) for v in center)
    cos_t, sin_t = math.cos(theta), math.sin(theta)

    def to_local(world_xyz):
        """Inverse of: rotate CCW about +Z at origin, then translate by center."""
        wx, wy, wz = world_xyz
        # subtract translation
        dx, dy, dz = wx - cx, wy - cy, wz - cz
        # inverse rotation
        lx = cos_t * dx + sin_t * dy
        ly = -sin_t * dx + cos_t * dy
        lz = dz
        return lx, ly, lz

    # Volume-PG classifier — matches the canonical DRM layout
    # the user's notebook expressed via in_box selection:
    #
    #   * ``inner_box`` = the single inner-inner-top sub-volume
    #     (the geometric "inner box" where the embedded structure
    #     lives).
    #   * ``transition_box`` = the layer-bounded AABB
    #     ``[-x_LL,+x_LL] x [-y_LL,+y_LL] x [-(z_top+z_mid), 0]``
    #     minus the inner box.  i.e. sub-vols whose lateral region
    #     is ``inner`` or ``layer`` AND whose Z region is ``top`` or
    #     ``mid``, with the single ``inner`` cell carved out.
    #   * ``outer_box`` = everything else — the absorbing region,
    #     including the inner-inner-mid / inner-inner-bottom
    #     sub-vols below the structure (per the user's geometric
    #     AABB rule, those z layers are not inside the transition
    #     shell).
    inner_vols: list[int] = []
    transition_vols: list[int] = []
    outer_vols: list[int] = []
    # ``per_class_counts`` ⇒ list of (vol_tag, nx, ny, nz)
    per_vol_counts: list[tuple[int, int, int, int]] = []

    for vtag in inst.entities.get(3, []):
        com_world = self._parent.model.queries.center_of_mass(
            int(vtag), dim=3,
        )
        lx, ly, lz = to_local(com_world)
        rx = drm.axis_x.region_of(lx)
        ry = drm.axis_y.region_of(ly)
        rz = drm.axis_z.region_of(lz)
        nx = drm.axis_x.count_for(lx)
        ny = drm.axis_y.count_for(ly)
        nz = drm.axis_z.count_for(lz)
        per_vol_counts.append((int(vtag), nx, ny, nz))

        is_inner = (rx == "inner" and ry == "inner" and rz == "top")
        inside_transition_bbox = (
            rx in ("inner", "layer")
            and ry in ("inner", "layer")
            and rz in ("top", "mid")
        )
        if is_inner:
            inner_vols.append(int(vtag))
        elif inside_transition_bbox:
            transition_vols.append(int(vtag))
        else:
            outer_vols.append(int(vtag))

    physical = self._parent.physical
    if inner_vols:
        physical.add(3, inner_vols, name=pg_defaults["inner_pg"])
    if transition_vols:
        physical.add(3, transition_vols, name=pg_defaults["transition_pg"])
    if outer_vols:
        physical.add(3, outer_vols, name=pg_defaults["outer_pg"])

    # ── Optional: transfinite cascade per sub-volume ────────────
    if apply_transfinite:
        structured = self._parent.mesh.structured
        for vtag, nx, ny, nz in per_vol_counts:
            # Tuple form ``n=(nx, ny, nz)`` orders by principal
            # axis (closest-global-axis), so it is rotation-safe
            # by construction — the dict form would require
            # global-axis-aligned edges and raise here.  Axis1D
            # stores element counts; ``set_transfinite`` takes
            # node counts (``n_nodes - 1`` elements per curve).
            structured.set_transfinite(
                (3, vtag),
                n=(nx + 1, ny + 1, nz + 1),
                recombine=True,
            )

    # ── Optional: line PGs per (region, axis) ───────────────────
    line_pgs_out: dict[str, str] = {}
    if tag_line_pgs:
        from apeGmsh.parts.drm_box import classify_drm_box_lines

        all_curves = [int(t) for _d, t in gmsh.model.getEntities(1)]
        classified = classify_drm_box_lines(
            axis_x=drm.axis_x,
            axis_y=drm.axis_y,
            axis_z=drm.axis_z,
            center=(cx, cy, cz),
            rotation_z=theta,
            line_pg_names=line_pg_defaults,
            curve_tags=all_curves,
        )
        # Invert line_pg_defaults so we can pair back to region keys
        # for the result's ``line_pgs`` dict.
        name_to_key = {v: k for k, v in line_pg_defaults.items()}
        for pg_name, edge_tags in classified.items():
            physical.add(1, edge_tags, name=pg_name)
            line_pgs_out[name_to_key[pg_name]] = pg_name

    # ── Stash rebuild-required state on the Instance ────────────
    # The line-PG classifier is a pure function of (axes, center,
    # rotation, curve_tags), so a future boolean that mutates the
    # box can drop the stale PGs and replay the classifier against
    # the post-cut curves.  We persist: the axis construction
    # params (so Axis1D can be rebuilt), the line-PG name map
    # (so we know which PGs are owned by this Part), the center,
    # and rotation_z.  See ``rebuild_drm_box_line_pgs`` in
    # ``apeGmsh.parts.drm_box``.
    inst.properties.setdefault("drm_box", {}).update({
        "line_pgs": dict(line_pgs_out),
        "center": (cx, cy, cz),
        "rotation_z": float(theta),
    })

    return DRMBoxResult(
        inner_pg=pg_defaults["inner_pg"],
        transition_pg=pg_defaults["transition_pg"],
        outer_pg=pg_defaults["outer_pg"],
        line_pgs=line_pgs_out,
        axes={
            "x": drm.axis_x,
            "y": drm.axis_y,
            "z": drm.axis_z,
        },
        center=(cx, cy, cz),
        rotation_z=float(theta),
    )

import_step

import_step(file_path: str | Path, *, label: str | None = None, translate: tuple[float, float, float] = (0.0, 0.0, 0.0), rotate: tuple[float, ...] | None = None, highest_dim_only: bool = True, heal: bool | float | str = False, dedupe: bool | float = False, properties: dict[str, Any] | None = None) -> Instance

Import a STEP or IGES file as a named instance.

Parameters

file_path : path STEP (.step, .stp) or IGES (.iges, .igs) file. label : str, optional Auto-generated from file stem if omitted. translate, rotate : placement transforms. heal : bool, float, or "auto" Heal the imported CAD immediately after import — same semantics as :meth:g.model.io.load_step <_IO.load_step>: True / "auto" use a scale-aware tolerance, a float overrides, False (default) imports raw and emits a :class:WarnGeomImportHealth advisory if slivers are found. Best-effort for sidecar-carrying parts (healing renumbers, so anchors rebind against the healed geometry). dedupe : bool or float Merge coincident entities after import (and after heal). properties : arbitrary metadata.

Source code in src/apeGmsh/core/_parts_registry.py
def import_step(
    self,
    file_path: str | Path,
    *,
    label: str | None = None,
    translate: tuple[float, float, float] = (0.0, 0.0, 0.0),
    rotate: tuple[float, ...] | None = None,
    highest_dim_only: bool = True,
    heal: bool | float | str = False,
    dedupe: bool | float = False,
    properties: dict[str, Any] | None = None,
) -> Instance:
    """Import a STEP or IGES file as a named instance.

    Parameters
    ----------
    file_path : path
        STEP (.step, .stp) or IGES (.iges, .igs) file.
    label : str, optional
        Auto-generated from file stem if omitted.
    translate, rotate : placement transforms.
    heal : bool, float, or "auto"
        Heal the imported CAD immediately after import — same
        semantics as :meth:`g.model.io.load_step <_IO.load_step>`:
        ``True`` / ``"auto"`` use a scale-aware tolerance, a float
        overrides, ``False`` (default) imports raw and emits a
        :class:`WarnGeomImportHealth` advisory if slivers are found.
        Best-effort for sidecar-carrying parts (healing renumbers,
        so anchors rebind against the healed geometry).
    dedupe : bool or float
        Merge coincident entities after import (and after heal).
    properties : arbitrary metadata.
    """
    file_path = Path(file_path)
    if not file_path.exists():
        raise FileNotFoundError(f"CAD file not found: {file_path}")
    if label is None:
        self._counter += 1
        label = f"{file_path.stem}_{self._counter}"
    return self._import_cad(
        file_path=file_path,
        label=label,
        part_name=file_path.stem,
        translate=translate,
        rotate=rotate,
        highest_dim_only=highest_dim_only,
        heal=heal,
        dedupe=dedupe,
        properties=properties or {},
    )

build_node_map

build_node_map(node_tags: ndarray, node_coords: ndarray) -> dict[str, set[int]]

Partition mesh nodes by instance bounding box.

Returns {label: {node_tag, ...}}.

Source code in src/apeGmsh/core/_parts_registry.py
def build_node_map(
    self,
    node_tags: np.ndarray,
    node_coords: np.ndarray,
) -> dict[str, set[int]]:
    """Partition mesh nodes by instance bounding box.

    Returns ``{label: {node_tag, ...}}``.
    """
    tags = np.asarray(node_tags)
    coords = np.asarray(node_coords).reshape(-1, 3)
    return {
        label: self._nodes_in_bbox(tags, coords, inst.bbox)
        for label, inst in self._instances.items()
    }

build_face_map

build_face_map(node_map: dict[str, set[int]]) -> dict[str, np.ndarray]

Partition surface elements by instance node ownership.

Returns {label: face_connectivity_array}.

Source code in src/apeGmsh/core/_parts_registry.py
def build_face_map(
    self,
    node_map: dict[str, set[int]],
) -> dict[str, np.ndarray]:
    """Partition surface elements by instance node ownership.

    Returns ``{label: face_connectivity_array}``.
    """
    from ._compose_errors import raise_if_no_live_kernel
    raise_if_no_live_kernel(
        self._parent, "g.parts.build_face_map()",
        alternative=(
            "fem.elements, where fem = g.mesh.queries.get_fem_data() "
            "— the surface connectivity this partitions is already "
            "in the broker"
        ),
    )
    faces = self._collect_surface_faces()
    if faces.size == 0:
        return {label: np.empty((0, 0), dtype=int)
                for label in self._instances}

    out: dict[str, np.ndarray] = {}
    for label, nodes in node_map.items():
        if not nodes:
            out[label] = np.empty((0, faces.shape[1]), dtype=int)
            continue
        mask = np.all(np.isin(faces, list(nodes)), axis=1)
        out[label] = faces[mask]
    return out

get

get(label: str) -> Instance

Return the Instance registered under label.

Useful when you didn't store the return value of :meth:add / :meth:import_step and want to access an Instance later — e.g. to apply inst.edit.* transforms::

g.parts.add(beam, label="b1")
g.parts.get("b1").edit.translate(0, 0, 50)
Raises

KeyError If no instance is registered under label. The error message lists the available labels so you can spot a typo.

Source code in src/apeGmsh/core/_parts_registry.py
def get(self, label: str) -> Instance:
    """Return the Instance registered under ``label``.

    Useful when you didn't store the return value of
    :meth:`add` / :meth:`import_step` and want to access an
    Instance later — e.g. to apply ``inst.edit.*`` transforms::

        g.parts.add(beam, label="b1")
        g.parts.get("b1").edit.translate(0, 0, 50)

    Raises
    ------
    KeyError
        If no instance is registered under ``label``.  The error
        message lists the available labels so you can spot a typo.
    """
    if label not in self._instances:
        available = sorted(self._instances)
        raise KeyError(
            f"No instance labeled {label!r}.  "
            f"Available: {available}"
        )
    return self._instances[label]

labels

labels() -> list[str]

Return all instance labels in insertion order.

Source code in src/apeGmsh/core/_parts_registry.py
def labels(self) -> list[str]:
    """Return all instance labels in insertion order."""
    return list(self._instances.keys())

rename

rename(old_label: str, new_label: str) -> None

Rename an instance.

Raises

KeyError if old_label does not exist. ValueError if new_label already exists.

Source code in src/apeGmsh/core/_parts_registry.py
def rename(self, old_label: str, new_label: str) -> None:
    """Rename an instance.

    Raises
    ------
    KeyError   if *old_label* does not exist.
    ValueError if *new_label* already exists.
    """
    if old_label not in self._instances:
        raise KeyError(f"No part '{old_label}'.")
    if new_label in self._instances:
        raise ValueError(f"Part '{new_label}' already exists.")
    inst = self._instances.pop(old_label)
    inst.label = new_label
    self._instances[new_label] = inst

delete

delete(label: str) -> None

Remove an instance from the registry.

The entities remain in the Gmsh session — they become "untracked" and will appear under the Untracked group in the viewer's Parts tab.

Raises

KeyError if label does not exist.

Source code in src/apeGmsh/core/_parts_registry.py
def delete(self, label: str) -> None:
    """Remove an instance from the registry.

    The entities remain in the Gmsh session — they become
    "untracked" and will appear under the Untracked group
    in the viewer's Parts tab.

    Raises
    ------
    KeyError if *label* does not exist.
    """
    if label not in self._instances:
        raise KeyError(f"No part '{label}'.")
    self._instances.pop(label)

Instance dataclass

Instance(label: str, part_name: str, file_path: Path | None = None, entities: dict[int, list[int]] = dict(), translate: tuple[float, float, float] = (0.0, 0.0, 0.0), rotate: tuple[float, ...] | None = None, properties: dict[str, Any] = dict(), bbox: tuple[float, float, float, float, float, float] | None = None, label_names: list[str] = list())

Bookkeeping record for one part placement.

Attributes

label : unique name inside the session part_name : name of the source Part or file stem file_path : CAD file that was imported (None for inline parts) entities : {dim: [tag, ...]} — updated in-place by fragment translate : applied translation (dx, dy, dz) rotate : applied rotation (angle_rad, ax, ay, az[, cx, cy, cz]) properties : arbitrary user metadata bbox : axis-aligned bounding box (xmin, ymin, zmin, xmax, ymax, zmax) label_names : label names created for this instance (Tier 1 naming, e.g. ["col_A.shaft", "col_A.top"]). Populated by _import_cad when the Part's CAD file has a .apegmsh.json sidecar carrying label definitions. These are NOT solver-facing physical groups — use g.labels.entities(name) to resolve entity tags, and g.labels.promote_to_physical(name) to create a solver PG when ready.

Axis1D dataclass

Axis1D(name: str, segments: Tuple[Tuple[str, float, float, int], ...])

A 1-D axis split into named, contiguous segments.

Parameters

name : str Axis name — only used for error messages. segments : tuple of (region, lo, hi, count) Ordered contiguous segments. lo of each segment must match hi of the previous one; hi > lo; count >= 1.

lo property

lo: float

Leftmost / lowest coordinate.

hi property

hi: float

Rightmost / highest coordinate.

size property

size: float

Total span hi - lo.

breaks property

breaks: list[float]

Ordered list of all break coordinates, length n_segments + 1.

The first entry is the axis lo, the last is hi, and the interior entries are the boundaries between segments.

slice_offsets

slice_offsets() -> list[float]

Interior break coordinates (everything in :attr:breaks except endpoints).

These are the offsets the geometry builder slices the box at.

Source code in src/apeGmsh/parts/_axis1d.py
def slice_offsets(self) -> list[float]:
    """Interior break coordinates (everything in :attr:`breaks` except endpoints).

    These are the offsets the geometry builder slices the box at.
    """
    return self.breaks[1:-1]

witnesses

witnesses() -> list[tuple[str, float]]

One (region, midpoint) per segment, in order.

Useful as test fixtures and as sanity-check probe points.

Source code in src/apeGmsh/parts/_axis1d.py
def witnesses(self) -> list[tuple[str, float]]:
    """One ``(region, midpoint)`` per segment, in order.

    Useful as test fixtures and as sanity-check probe points.
    """
    return [
        (str(region), 0.5 * (float(lo) + float(hi)))
        for region, lo, hi, _ in self.segments
    ]

region_of

region_of(value: float, *, tol: float = 1e-09) -> str

Return the region whose segment contains value.

Points exactly on a segment boundary are assigned to the segment ending at that boundary (value == hi) when on the very last break, otherwise to the segment beginning there (value == lo). tol widens both endpoint comparisons.

Raises ValueError when value is outside [lo, hi].

Source code in src/apeGmsh/parts/_axis1d.py
def region_of(self, value: float, *, tol: float = 1e-9) -> str:
    """Return the region whose segment contains ``value``.

    Points exactly on a segment boundary are assigned to the
    segment ending at that boundary (``value == hi``) when on the
    very last break, otherwise to the segment beginning there
    (``value == lo``).  ``tol`` widens both endpoint comparisons.

    Raises ``ValueError`` when ``value`` is outside ``[lo, hi]``.
    """
    v = float(value)
    if v < self.lo - tol or v > self.hi + tol:
        raise ValueError(
            f"Axis1D({self.name!r}).region_of({v}): value outside "
            f"axis range [{self.lo}, {self.hi}]."
        )
    for i, (region, lo, hi, _) in enumerate(self.segments):
        lo_f, hi_f = float(lo), float(hi)
        # Each interior boundary is owned by the segment to its
        # right; the very last boundary is owned by the last
        # segment so ``value == hi`` doesn't raise.
        is_last = i == len(self.segments) - 1
        if is_last:
            if lo_f - tol <= v <= hi_f + tol:
                return str(region)
        else:
            if lo_f - tol <= v < hi_f - tol:
                return str(region)
    # Fallback for the case where ``value`` lands exactly on the
    # final break (covered above) or the loop logic missed an
    # edge case — defensive only.
    return str(self.segments[-1][0])

count_for

count_for(value: float, *, tol: float = 1e-09) -> int

Return the element count of the segment containing value.

Source code in src/apeGmsh/parts/_axis1d.py
def count_for(self, value: float, *, tol: float = 1e-9) -> int:
    """Return the element count of the segment containing ``value``."""
    v = float(value)
    if v < self.lo - tol or v > self.hi + tol:
        raise ValueError(
            f"Axis1D({self.name!r}).count_for({v}): value outside "
            f"axis range [{self.lo}, {self.hi}]."
        )
    for i, (_region, lo, hi, count) in enumerate(self.segments):
        lo_f, hi_f = float(lo), float(hi)
        is_last = i == len(self.segments) - 1
        if is_last:
            if lo_f - tol <= v <= hi_f + tol:
                return int(count)
        else:
            if lo_f - tol <= v < hi_f - tol:
                return int(count)
    return int(self.segments[-1][3])

symmetric_layered classmethod

symmetric_layered(name: str, *, inner: tuple[float, int], layer: tuple[float, int], outer: tuple[float, int]) -> 'Axis1D'

5-segment symmetric layout — outer | layer | inner | layer | outer.

The inner segment is centred on zero; the layer mirrors on both sides; the outer mirrors beyond the layer. Each tuple is (size, n_elements).

Source code in src/apeGmsh/parts/_axis1d.py
@classmethod
def symmetric_layered(
    cls,
    name: str,
    *,
    inner: tuple[float, int],
    layer: tuple[float, int],
    outer: tuple[float, int],
) -> "Axis1D":
    """5-segment symmetric layout — outer | layer | inner | layer | outer.

    The inner segment is centred on zero; the layer mirrors on
    both sides; the outer mirrors beyond the layer.  Each tuple
    is ``(size, n_elements)``.
    """
    inner_size, n_inner = float(inner[0]), int(inner[1])
    layer_size, n_layer = float(layer[0]), int(layer[1])
    outer_size, n_outer = float(outer[0]), int(outer[1])
    for s, who in (
        (inner_size, "inner"),
        (layer_size, "layer"),
        (outer_size, "outer"),
    ):
        if s <= 0:
            raise ValueError(
                f"Axis1D.symmetric_layered({name!r}): "
                f"{who} size must be > 0, got {s}."
            )

    x0 = -(inner_size / 2.0 + layer_size + outer_size)
    x1 = -(inner_size / 2.0 + layer_size)
    x2 = -inner_size / 2.0
    x3 = +inner_size / 2.0
    x4 = +(inner_size / 2.0 + layer_size)
    x5 = +(inner_size / 2.0 + layer_size + outer_size)

    return cls(
        name=name,
        segments=(
            ("outer", x0, x1, n_outer),
            ("layer", x1, x2, n_layer),
            ("inner", x2, x3, n_inner),
            ("layer", x3, x4, n_layer),
            ("outer", x4, x5, n_outer),
        ),
    )

downward_layered classmethod

downward_layered(name: str, *, top: tuple[float, int], mid: tuple[float, int], bottom: tuple[float, int]) -> 'Axis1D'

3-segment downward layout — bottom | mid | top, with hi = 0.

Convention for the DRM box: the free surface sits at z = 0 (top of the inner box), and the stack descends downward. Each tuple is (size, n_elements).

Source code in src/apeGmsh/parts/_axis1d.py
@classmethod
def downward_layered(
    cls,
    name: str,
    *,
    top: tuple[float, int],
    mid: tuple[float, int],
    bottom: tuple[float, int],
) -> "Axis1D":
    """3-segment downward layout — bottom | mid | top, with ``hi = 0``.

    Convention for the DRM box: the free surface sits at z = 0
    (top of the inner box), and the stack descends downward.
    Each tuple is ``(size, n_elements)``.
    """
    top_size, n_top = float(top[0]), int(top[1])
    mid_size, n_mid = float(mid[0]), int(mid[1])
    bottom_size, n_bottom = float(bottom[0]), int(bottom[1])
    for s, who in (
        (top_size, "top"),
        (mid_size, "mid"),
        (bottom_size, "bottom"),
    ):
        if s <= 0:
            raise ValueError(
                f"Axis1D.downward_layered({name!r}): "
                f"{who} size must be > 0, got {s}."
            )

    z3 = 0.0
    z2 = -top_size
    z1 = -(top_size + mid_size)
    z0 = -(top_size + mid_size + bottom_size)

    return cls(
        name=name,
        segments=(
            ("bottom", z0, z1, n_bottom),
            ("mid",    z1, z2, n_mid),
            ("top",    z2, z3, n_top),
        ),
    )

DRMBox

DRMBox(*, x_inner: tuple[float, int], x_layer: tuple[float, int], x_outer: tuple[float, int], y_inner: tuple[float, int], y_layer: tuple[float, int], y_outer: tuple[float, int], z_top: tuple[float, int], z_mid: tuple[float, int], z_bottom: tuple[float, int], name: str = 'drm_box')

Bases: Part

Layered DRM-box geometry, built in its own Gmsh session.

The box is centred laterally on (0, 0) and descends from z = 0 (top of the inner box, free-surface convention). No labels or physical groups are attached — the assembly-side helper re-classifies sub-volumes by centroid + Axis1D lookup after import, which is robust to STEP renumbering and to the placement transform.

Parameters

x_inner, x_layer, x_outer, y_inner, y_layer, y_outer : (size, n_elements) tuples — symmetric layered axes (outer | layer | inner | layer | outer) along X and Y. z_top, z_mid, z_bottom : (size, n_elements) tuples — downward Z stack (bottom | mid | top, hi = 0). name : Gmsh model name and default Part / instance name.

Source code in src/apeGmsh/parts/drm_box.py
def __init__(
    self,
    *,
    x_inner: tuple[float, int],
    x_layer: tuple[float, int],
    x_outer: tuple[float, int],
    y_inner: tuple[float, int],
    y_layer: tuple[float, int],
    y_outer: tuple[float, int],
    z_top: tuple[float, int],
    z_mid: tuple[float, int],
    z_bottom: tuple[float, int],
    name: str = "drm_box",
) -> None:
    super().__init__(name=name)
    self.axis_x = Axis1D.symmetric_layered(
        "x", inner=x_inner, layer=x_layer, outer=x_outer,
    )
    self.axis_y = Axis1D.symmetric_layered(
        "y", inner=y_inner, layer=y_layer, outer=y_outer,
    )
    self.axis_z = Axis1D.downward_layered(
        "z", top=z_top, mid=z_mid, bottom=z_bottom,
    )
    # Stored so the assembly-side helper can re-create them via
    # ``result.axes`` if it skipped the live-Part path.
    self.properties.update({
        "drm_box": {
            "x_inner": tuple(x_inner),
            "x_layer": tuple(x_layer),
            "x_outer": tuple(x_outer),
            "y_inner": tuple(y_inner),
            "y_layer": tuple(y_layer),
            "y_outer": tuple(y_outer),
            "z_top": tuple(z_top),
            "z_mid": tuple(z_mid),
            "z_bottom": tuple(z_bottom),
        },
    })

build

build() -> 'DRMBox'

Build the 75-volume sliced box inside the Part's session.

Must be called inside with drm_box:. Returns self so the caller can chain with DRMBox(...) as d: d.build() if desired. Idempotent within a session — repeated calls slice nothing on the already-fully-sliced model.

Source code in src/apeGmsh/parts/drm_box.py
def build(self) -> "DRMBox":
    """Build the 75-volume sliced box inside the Part's session.

    Must be called inside ``with drm_box:``.  Returns ``self`` so
    the caller can chain ``with DRMBox(...) as d: d.build()`` if
    desired.  Idempotent within a session — repeated calls slice
    nothing on the already-fully-sliced model.
    """
    if not self._active:
        raise RuntimeError(
            f"DRMBox({self.name!r}).build(): Part session is not "
            f"active.  Call build() inside a `with` block."
        )

    x_breaks = self.axis_x.breaks
    y_breaks = self.axis_y.breaks
    z_breaks = self.axis_z.breaks

    x0, x_end = x_breaks[0], x_breaks[-1]
    y0, y_end = y_breaks[0], y_breaks[-1]
    z0, z_end = z_breaks[0], z_breaks[-1]

    self.model.geometry.add_box(
        x0, y0, z0,
        x_end - x0, y_end - y0, z_end - z0,
    )

    for x in self.axis_x.slice_offsets():
        self.model.geometry.slice(axis="x", offset=float(x))
    for y in self.axis_y.slice_offsets():
        self.model.geometry.slice(axis="y", offset=float(y))
    for z in self.axis_z.slice_offsets():
        self.model.geometry.slice(axis="z", offset=float(z))

    return self

DRMBoxResult dataclass

DRMBoxResult(inner_pg: str, transition_pg: str, outer_pg: str, line_pgs: dict[str, str] = dict(), axes: dict[str, Axis1D] = dict(), center: tuple[float, float, float] = (0.0, 0.0, 0.0), rotation_z: float = 0.0)

Summary of a DRM-box placement.

Returned by :func:PartsRegistry.add_DRM_box. The user keeps it for downstream references — PG names to feed into recorders or constraints, Axis1D descriptors to drive auxiliary mesh sizing.

ConstraintsComposite

ConstraintsComposite(parent: '_ApeGmshSession')

Solver-agnostic kinematic-constraint composite — declare on geometry, resolve to nodes after meshing.

Two-stage pipeline
  1. Declare (pre-mesh): the factory methods on this composite (equal_dof, rigid_link, rigid_diaphragm, tie, …) store :class:~apeGmsh.solvers.Constraints.ConstraintDef dataclasses describing intent at the geometry level. Defs carry no node tags and survive remeshing.
  2. Resolve (post-mesh): :meth:resolve (called automatically by :meth:Mesh.queries.get_fem_data) walks the def list and hands each one to :class:~apeGmsh.solvers.Constraints.ConstraintResolver, which produces concrete :class:~apeGmsh.solvers.Constraints.ConstraintRecord objects — actual node tags, weights, and offset vectors.

The resolved records land on the FEM broker:

  • node-pair / node-group / node_to_surface records → fem.nodes.constraints
  • surface-coupling / interpolation records → fem.elements.constraints
Constraint taxonomy

Five tiers, ordered by topology and the role each plays in a structural model:

============= ===================================================== ================================= Tier Methods Record family ============= ===================================================== ================================= 1 — Pair :meth:equal_dof, :meth:rigid_link, NodePairRecord :meth:penalty 2 — Group :meth:rigid_diaphragm, :meth:rigid_body, NodeGroupRecord :meth:kinematic_coupling 2b — Mixed :meth:node_to_surface, NodeToSurfaceRecord :meth:node_to_surface_spring (+ phantom nodes) 3 — Surface :meth:tie, :meth:distributing_coupling, InterpolationRecord :meth:embedded 4 — Contact :meth:tied_contact SurfaceCouplingRecord 5 — Fork :meth:contact, :meth:mortar (deprecated alias) ContactRecord ============= ===================================================== =================================

All constraints ultimately express the linear MPC equation u_slave = C · u_master. Tiers differ in how C is built — by node co-location (Tier 1), kinematic transformation around a master point (Tier 2), shape-function interpolation (Tier 3), or numerical integration on the interface (Tier 4).

Target identification

Most methods identify their master and slave sides by name — a part label (a key of g.parts._instances), a physical group (g.physical / .to_physical), or a label (g.labels). :meth:_add_def validates both names and raises KeyError on a typo::

g.constraints.tie(master_label="column",
                  slave_label="slab",
                  master_entities=[(2, 13)],   # optional scope
                  slave_entities=[(2, 17)])

A physical-group model therefore constrains without building Parts (tie("A_top", "B_bot") just works), matching how g.loads / g.masses already resolve names. Precedence: a Part registered under the name wins (the part node/face map is consulted first); otherwise the name resolves through the shared label→PG→part geometry resolver. A name that is simultaneously a Part and a physical group binds the Part's node set.

Optional master_entities / slave_entities (list of (dim, tag)) narrow the search to a subset of the target's entities — useful when a target has many surfaces and only one is the interface.

Exceptions to the part-label scheme ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  • :meth:node_to_surface and :meth:node_to_surface_spring take bare tags instead. The master is a Gmsh point entity (dim=0) and slave is one or more surface entities (dim=2). Both arguments accept int, str, or (dim, tag); label validation is skipped.
  • :meth:embedded uses host_label / embedded_label to mirror the host/embedded vocabulary, but the lookup logic otherwise matches the part-label scheme.
Resolution semantics

:meth:resolve is dependency-injected — it never imports PartsRegistry. The caller (typically Mesh.queries.get_fem_data) supplies:

  • node_map: {part_label → set[int]} of mesh node tags
  • face_map: {part_label → ndarray(F, n_per_face)} built only when surface constraints (Tier 3 / 4) are present.
See Also

apeGmsh.solvers.Constraints : Module-level taxonomy and theory. apeGmsh.solvers._constraint_defs : Stage-1 dataclasses with full per-method theory. apeGmsh.solvers._constraint_resolver.ConstraintResolver : Stage-2 implementation. apeGmsh.mesh._record_set.NodeConstraintSet : Iteration helpers (rigid_link_groups, equal_dofs, rigid_diaphragms, pairs).

Examples

Declare a mix of constraints, mesh, and read out grouped rigid-link masters for OpenSees emission::

with apeGmsh(model_name="frame") as g:
    # Tier 1 — co-located nodes share x/y/z
    g.constraints.equal_dof("col", "beam", dofs=[1, 2, 3])

    # Tier 2 — slab nodes follow the centre-of-mass node
    g.constraints.rigid_diaphragm(
        "slab", "slab_master",
        master_point=(2.5, 2.5, 3.0),
        plane_normal=(0, 0, 1),
    )

    # Tier 3 — non-matching shell-to-solid interface
    g.constraints.tie(
        "shell", "solid",
        master_entities=[(2, 17)],
        slave_entities=[(2, 41)],
    )

    g.mesh.generation.generate(dim=3)
    fem = g.mesh.queries.get_fem_data(dim=3)

    for master, slaves in fem.nodes.constraints.rigid_link_groups():
        for slave in slaves:
            ops.rigidLink("beam", master, slave)
Source code in src/apeGmsh/core/ConstraintsComposite.py
def __init__(self, parent: "_ApeGmshSession") -> None:
    self._parent = parent
    self.constraint_defs: list[ConstraintDef] = []
    self.constraint_records: list[ConstraintRecord] = []
    # Single-point constraints (BCDef) are kept apart from
    # constraint_defs: they carry no master/slave, are not in
    # _DISPATCH, and resolve to fem.nodes.sp (not
    # fem.nodes.constraints).  Mixing them into constraint_defs
    # would break _add_def validation and the resolve() dispatch.
    self._bc_defs: list[BCDef] = []
    # Contact interactions (ContactDef) are kept apart from
    # constraint_defs: they are NOT in the interpolation _DISPATCH
    # (they emit contactSurface/contact commands + the LadrunoContact
    # handler, not embeddedNode/element records) and resolve to an
    # additive fem.elements.contacts list — mirroring g.reinforce /
    # g.embed rather than the MP-constraint dispatch.
    self.contact_defs: list[ContactDef] = []
    self.contact_records: list[ContactRecord] = []
    self.contact_plane_defs: list[ContactPlaneDef] = []
    self.contact_plane_records: list[ContactPlaneRecord] = []
    # Oriented coincident-pair zeroLength interfaces (ADR 0093).
    # Another additive side-list, like the contacts above: they
    # resolve to fem.elements.interfaces, not the MP dispatch.
    self.interface_defs: list[InterfaceDef] = []
    self.interface_records: list[InterfaceRecord] = []
    # Shared phantom-node-tag high-water mark. The MP lane's
    # ConstraintResolver mints node_to_surface phantoms from
    # max(node_tags)+1 (``_next_phantom_tag``); the interface
    # resolver mints its own from a different code path. A model
    # carrying both would collide unless one counter crosses
    # between them — resolve() publishes the MP lane's final value
    # here and resolve_interfaces() starts above it.
    self._phantom_tag_high_water: int | None = None

contact

contact(master, slave, *, formulation='nts', kn=None, kt=None, mu=None, eps_n=None, eps_t=None, cohesion=None, tau_max=None, aug_tol=None, max_aug=None, ngp=None, tie=False, thickness=None, outward=None, soft=None, visc=None, consistent_tan=False, geom_tan=False, cell=None, edge_edge=False, edge_kn=None, edge_band=None, edge_mu=None, edge_kt=None, edge_cohesion=None, edge_tau_max=None, edge_consistent_tan=False, edge_soft=None, edge_alm=False, edge_aug_tol=None, master_entities=None, slave_entities=None, name=None) -> ContactDef

Declare a face-to-face contact between two meshed surfaces (fork contactSurface + contact + LadrunoContact handler).

Parameters

master, slave : str The two surface PG / part labels in contact. The master is faceted (-master); the slave is a node set (NTS, -slave) or faceted (mortar, -slave-segments). formulation : {"nts", "mortar"} "nts" = node-to-segment penalty; "mortar" = segment-to-segment ALM (the non-matching-mesh accuracy lane). kn, kt, mu : float, optional NTS normal/tangential penalty + Coulomb friction (kn may be "auto"). Rejected for mortar. eps_n, eps_t : float | "auto", optional Mortar ALM normal/tangential penalty. Rejected for NTS. cohesion, tau_max : float, optional Mortar friction-cone adhesion + Tresca cap. aug_tol, max_aug, ngp : optional Mortar Uzawa tolerance / max augmentations / slave-facet Gauss order. tie : bool Permanent mesh-tie bond (mortar only; excludes friction). thickness : float, optional 2D mortar only — the plane-model out-of-plane thickness h (-thickness; fork default 1.0). The mortar lane's interval integrals produce force per unit thickness, so the fork applies h once, at its 2D injection site, to eps_n/eps_t/ visc/cohesion/tau_max and the tie stiffness. Keep the three thickness conventions apart: the ELEMENT thickness (ops.element.FourNodeQuad(thickness=…)) is baked into element stiffness and contact never re-reads it; this h scales the EXPLICIT penalties above; and eps_n="auto" is deliberately NOT h-scaled (it already absorbs the element thickness through getInitialStiff(), so re-scaling would be an h² error). An eps_t="auto" (or an eps_t defaulted from eps_n under friction) inherits eps_n's provenance, so it h-scales only when eps_n is explicit. The NTS lane has no -thickness at all, and a 3D model is refused by name here. soft : float | bool, optional Explicit-only Courant-stable SOFT penalty (-soft): True ⇒ the fork default SOFSCL (0.10); a float ⇒ an explicit SOFSCL. Needs a base penalty (kn/eps_n); excludes tie. NTS=SOFT=1, mortar=SOFT=2. See :class:ContactDef. visc : float, optional Viscous normal-stabilisation coefficient μ_c (-visc); excludes tie. consistent_tan : bool Non-symmetric consistent friction tangent (-consistanttan) — needs an unsymmetric solver (FullGeneral / UmfPack / BandGeneral). geom_tan : bool NTS ∂n/∂u geometric normal tangent (-geomtan) for curved / large-sliding interfaces. NTS-only. cell : float, optional Broad-phase cell-size scale (-cell): the spatial-hash bucket size as a fraction of the median segment diagonal (must be > 0). A performance knob — omit for the fork default. Both formulations. edge_edge : bool Enable the perpendicular edge-edge contact fallback (-edgeedge, ADR-57 E2). Mortar-only. See :class:ContactDef. edge_kn : float | "auto", optional Edge-edge normal penalty (-edgeKn); None ⇒ the mortar penalty. edge_band : float, optional Edge-edge gap activation band (-edgeBand). edge_mu, edge_kt, edge_cohesion, edge_tau_max : float, optional Edge-edge Coulomb/Tresca friction (-edgeMu/-edgeKt/ -edgeCohesion/-edgeTauMax). edge_consistent_tan : bool Edge-edge non-symmetric Csl friction tangent (-edgeConsistentTan). edge_soft : float | bool, optional Edge-edge explicit Courant-stable SOFT penalty (-edgeSoft). edge_alm : bool Edge-edge commit-cycle augmented Lagrangian (-edgeAlm). edge_aug_tol : float, optional Edge-edge ALM tolerance (-edgeAugTol). outward : (float, float, float) | (float, float) | "winding", optional None (default) → no -outward is emitted; the fork derives a correct per-facet normal (right for separated bodies and curved / closed / solid masters). Set an explicit direction ONLY for an initially-coincident (zero-gap) FLAT contact, where the fork's per-pair sign reference is in-plane and ambiguous. A single global outward is wrong on a non-flat master. See :class:ContactDef.

**In a 2D model** this is a 2-vector ``(ox, oy)``, and a flush
interface REQUIRES one (or ``"winding"``) — the fork's 2D lanes
orient from an interface-level centroid vote that is ambiguous
there and aborts. ``outward="winding"`` (2D NTS only) declares the
side through the master chain's own winding instead of a
direction, so it also orients curved and closed masters; it needs
a fork build carrying ``-outward winding``.

master_entities, slave_entities : list of (dim, tag), optional Restrict each side to specific Gmsh entities. name : str, optional Friendly name (round-trips into the emitted deck comment).

Returns

ContactDef

Source code in src/apeGmsh/core/ConstraintsComposite.py
def contact(
    self, master, slave, *,
    formulation="nts",
    kn=None, kt=None, mu=None,
    eps_n=None, eps_t=None,
    cohesion=None, tau_max=None,
    aug_tol=None, max_aug=None, ngp=None,
    tie=False, thickness=None, outward=None,
    soft=None, visc=None, consistent_tan=False, geom_tan=False,
    cell=None,
    edge_edge=False, edge_kn=None, edge_band=None,
    edge_mu=None, edge_kt=None, edge_cohesion=None, edge_tau_max=None,
    edge_consistent_tan=False, edge_soft=None, edge_alm=False,
    edge_aug_tol=None,
    master_entities=None, slave_entities=None,
    name=None,
) -> ContactDef:
    """Declare a face-to-face contact between two meshed surfaces
    (fork `contactSurface` + `contact` + `LadrunoContact` handler).

    Parameters
    ----------
    master, slave : str
        The two surface PG / part labels in contact. The master is
        faceted (`-master`); the slave is a node set (NTS, `-slave`) or
        faceted (mortar, `-slave-segments`).
    formulation : {"nts", "mortar"}
        ``"nts"`` = node-to-segment penalty; ``"mortar"`` =
        segment-to-segment ALM (the non-matching-mesh accuracy lane).
    kn, kt, mu : float, optional
        NTS normal/tangential penalty + Coulomb friction (``kn`` may be
        ``"auto"``). Rejected for mortar.
    eps_n, eps_t : float | "auto", optional
        Mortar ALM normal/tangential penalty. Rejected for NTS.
    cohesion, tau_max : float, optional
        Mortar friction-cone adhesion + Tresca cap.
    aug_tol, max_aug, ngp : optional
        Mortar Uzawa tolerance / max augmentations / slave-facet Gauss order.
    tie : bool
        Permanent mesh-tie bond (mortar only; excludes friction).
    thickness : float, optional
        **2D mortar only** — the plane-model out-of-plane thickness ``h``
        (``-thickness``; fork default 1.0). The mortar lane's interval
        integrals produce force per unit thickness, so the fork applies
        ``h`` once, at its 2D injection site, to ``eps_n``/``eps_t``/
        ``visc``/``cohesion``/``tau_max`` and the tie stiffness. Keep the
        three thickness conventions apart: the ELEMENT thickness
        (``ops.element.FourNodeQuad(thickness=…)``) is baked into element
        stiffness and contact never re-reads it; this ``h`` scales the
        EXPLICIT penalties above; and ``eps_n="auto"`` is deliberately NOT
        h-scaled (it already absorbs the element thickness through
        ``getInitialStiff()``, so re-scaling would be an h² error). An
        ``eps_t="auto"`` (or an eps_t defaulted from eps_n under
        friction) inherits ``eps_n``'s provenance, so it h-scales only
        when ``eps_n`` is explicit. The NTS lane has no ``-thickness``
        at all, and a 3D model is refused by name here.
    soft : float | bool, optional
        Explicit-only Courant-stable SOFT penalty (``-soft``): ``True`` ⇒
        the fork default SOFSCL (0.10); a float ⇒ an explicit SOFSCL. Needs
        a base penalty (``kn``/``eps_n``); excludes ``tie``. NTS=SOFT=1,
        mortar=SOFT=2. See :class:`ContactDef`.
    visc : float, optional
        Viscous normal-stabilisation coefficient μ_c (``-visc``); excludes
        ``tie``.
    consistent_tan : bool
        Non-symmetric consistent friction tangent (``-consistanttan``) —
        needs an unsymmetric solver (FullGeneral / UmfPack / BandGeneral).
    geom_tan : bool
        NTS ∂n/∂u geometric normal tangent (``-geomtan``) for curved /
        large-sliding interfaces. NTS-only.
    cell : float, optional
        Broad-phase cell-size scale (``-cell``): the spatial-hash bucket size
        as a fraction of the median segment diagonal (must be > 0). A
        performance knob — omit for the fork default. Both formulations.
    edge_edge : bool
        Enable the perpendicular edge-edge contact fallback (``-edgeedge``,
        ADR-57 E2). **Mortar-only.** See :class:`ContactDef`.
    edge_kn : float | "auto", optional
        Edge-edge normal penalty (``-edgeKn``); ``None`` ⇒ the mortar penalty.
    edge_band : float, optional
        Edge-edge gap activation band (``-edgeBand``).
    edge_mu, edge_kt, edge_cohesion, edge_tau_max : float, optional
        Edge-edge Coulomb/Tresca friction (``-edgeMu``/``-edgeKt``/
        ``-edgeCohesion``/``-edgeTauMax``).
    edge_consistent_tan : bool
        Edge-edge non-symmetric Csl friction tangent (``-edgeConsistentTan``).
    edge_soft : float | bool, optional
        Edge-edge explicit Courant-stable SOFT penalty (``-edgeSoft``).
    edge_alm : bool
        Edge-edge commit-cycle augmented Lagrangian (``-edgeAlm``).
    edge_aug_tol : float, optional
        Edge-edge ALM tolerance (``-edgeAugTol``).
    outward : (float, float, float) | (float, float) | "winding", optional
        ``None`` (default) → no ``-outward`` is emitted; the fork derives a
        correct per-facet normal (right for separated bodies and curved /
        closed / solid masters). Set an explicit direction ONLY for an
        initially-coincident (zero-gap) FLAT contact, where the fork's
        per-pair sign reference is in-plane and ambiguous. A single global
        outward is wrong on a non-flat master. See :class:`ContactDef`.

        **In a 2D model** this is a 2-vector ``(ox, oy)``, and a flush
        interface REQUIRES one (or ``"winding"``) — the fork's 2D lanes
        orient from an interface-level centroid vote that is ambiguous
        there and aborts. ``outward="winding"`` (2D NTS only) declares the
        side through the master chain's own winding instead of a
        direction, so it also orients curved and closed masters; it needs
        a fork build carrying ``-outward winding``.
    master_entities, slave_entities : list of (dim, tag), optional
        Restrict each side to specific Gmsh entities.
    name : str, optional
        Friendly name (round-trips into the emitted deck comment).

    Returns
    -------
    ContactDef
    """
    # Silent-failures slice 2 (PR #889) supersedes the ADR 0086 D4
    # draft guard: gate only from_h5/compose sessions — a LIVE
    # session legitimately re-resolves contact defs at the next
    # extraction. For a permanent bond on a composed assembly use
    # g.constraints.tie(method='mortar', enforce='equation').
    from ._compose_errors import raise_if_from_h5_session
    raise_if_from_h5_session(self._parent, "g.constraints.contact()")
    defn = ContactDef(
        master_label=master, slave_label=slave,
        master_entities=master_entities, slave_entities=slave_entities,
        formulation=formulation,
        kn=kn, kt=kt, mu=mu,
        eps_n=eps_n, eps_t=eps_t,
        cohesion=cohesion, tau_max=tau_max,
        aug_tol=aug_tol, max_aug=max_aug, ngp=ngp,
        tie=tie, thickness=thickness,
        outward=_normalise_outward(outward),
        soft=soft, visc=visc,
        consistent_tan=consistent_tan, geom_tan=geom_tan,
        cell=cell,
        edge_edge=edge_edge, edge_kn=edge_kn, edge_band=edge_band,
        edge_mu=edge_mu, edge_kt=edge_kt, edge_cohesion=edge_cohesion,
        edge_tau_max=edge_tau_max, edge_consistent_tan=edge_consistent_tan,
        edge_soft=edge_soft, edge_alm=edge_alm, edge_aug_tol=edge_aug_tol,
        name=name,
    )
    self.contact_defs.append(defn)
    return defn

resolve_contacts

resolve_contacts(node_tags, node_coords) -> list[ContactRecord]

Resolve every :meth:contact def to a :class:ContactRecord.

Pulls the master faceted surface (+ slave node set / faceted surface) from the live Gmsh session, dropping higher-order facets to corners, mirroring the additive g.reinforce / g.embed resolve. The outward normal is carried through only when the user set it explicitly — the fork kernel derives a correct per-facet normal otherwise (see the outward note below). node_tags / node_coords are accepted for signature parity with the sibling resolvers. Serial-only (the fork contact subsystem is not parallel).

The model dimension is read once, here, and threaded — it is the single branch point of the 2D lane, mirroring :meth:resolve_interfaces. In a 2D model the master is a dim-1 curve, collected as line segments and CHAINED head-to-tail into the fork's stride-2 pair list; in a 3D model nothing below changes.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def resolve_contacts(self, node_tags, node_coords) -> list[ContactRecord]:
    """Resolve every :meth:`contact` def to a :class:`ContactRecord`.

    Pulls the master faceted surface (+ slave node set / faceted surface)
    from the live Gmsh session, dropping higher-order facets to corners,
    mirroring the additive g.reinforce / g.embed resolve. The outward
    normal is carried through only when the user set it explicitly — the
    fork kernel derives a correct per-facet normal otherwise (see the
    outward note below). ``node_tags`` / ``node_coords`` are accepted for
    signature parity with the sibling resolvers. Serial-only (the fork
    contact subsystem is not parallel).

    **The model dimension is read once, here, and threaded** — it is the
    single branch point of the 2D lane, mirroring
    :meth:`resolve_interfaces`. In a 2D model the master is a dim-1
    curve, collected as line segments and CHAINED head-to-tail into the
    fork's stride-2 pair list; in a 3D model nothing below changes.
    """
    records: list[ContactRecord] = []
    if not self.contact_defs:
        self.contact_records = records
        return records

    import gmsh
    model_dim = int(gmsh.model.getDimension())

    parts = getattr(self._parent, "parts", None)
    if parts is None:
        raise RuntimeError(
            "contact: g.parts is unavailable to collect surface faces.")

    # The whole-domain scratch every 2D chain walk needs. Built LAZILY
    # on the first surface (so its refusals still carry that
    # interaction's label, byte-identical to the per-call build) and
    # then shared: without it each surface pays its own Python-level
    # pass over every domain element, and the mortar lane walks two
    # surfaces per contact.
    frames = None
    if model_dim == 2:
        domain_tags, domain_conn = self._collect_domain_elements(
            verb="contact")
        xyz = {
            int(t): np.asarray(c, dtype=float)
            for t, c in zip(np.asarray(node_tags, dtype=int).ravel(),
                            np.asarray(node_coords, dtype=float))
        }

    for defn in self.contact_defs:
        m_ents = (defn.master_entities
                  or self._entities_for_label(defn.master_label))
        s_ents = (defn.slave_entities
                  or self._entities_for_label(defn.slave_label))
        _refuse_contact_entity_dim(
            m_ents, defn.master_label, model_dim=model_dim, role="master")

        if model_dim != 2 and defn.thickness is not None:
            raise ValueError(
                f"contact: interaction "
                f"{defn.name or defn.master_label!r} declares "
                f"thickness={defn.thickness!r}, but the model is "
                f"{model_dim}D. `-thickness` is the 2D plane-model "
                f"out-of-plane thickness; a 3D mortar deck's thickness "
                f"lives in its ELEMENTS, and the fork FATALs on a 3D "
                f"pair carrying it. Drop thickness=.")

        if model_dim == 2:
            _refuse_contact_entity_dim(
                s_ents, defn.slave_label,
                model_dim=model_dim, role="slave",
                formulation=defn.formulation)
            if frames is None:
                from apeGmsh._kernel.geometry._boundary_chain import (
                    domain_frames,
                )
                frames = domain_frames(
                    domain_tags, domain_conn, xyz,
                    f" {defn.master_label!r}", verb="contact",
                    role="master")
            master_faces, master_nps = self._chain_2d_segments(
                m_ents, defn.master_label, xyz, domain_tags, domain_conn,
                role="master", frames=frames)
        else:
            master_faces = parts._collect_surface_faces(m_ents)
            if master_faces.size == 0:
                raise ValueError(
                    f"contact: master label {defn.master_label!r} resolved to "
                    f"entities but carries no surface mesh faces (is it meshed?).")
            master_faces, master_nps = _drop_to_corner_facets(master_faces)

        if defn.formulation == "nts":
            slave_nodes = self._collect_node_set(s_ents, defn.slave_label)
            slave_faces, slave_nps = None, 0
        elif model_dim == 2:
            # 2D mortar — the slave is `-slave-segments 2`, the SAME
            # chained stride-2 pair list as the master and with the same
            # hole hazard, so it goes through the same walk (an unchained
            # slave listing is silently legal fork-side too). Its
            # direction is not load-bearing — the fork's orientation vote
            # reads sigma off the MASTER segments and uses the slave tags
            # only for the centroid datum — but winding it against its own
            # material costs nothing and keeps one code path.
            slave_faces, slave_nps = self._chain_2d_segments(
                s_ents, defn.slave_label, xyz, domain_tags, domain_conn,
                role="slave", frames=frames)
            slave_nodes = None
        else:  # mortar — faceted slave
            slave_faces = parts._collect_surface_faces(s_ents)
            if slave_faces.size == 0:
                raise ValueError(
                    f"contact: mortar slave label {defn.slave_label!r} "
                    f"carries no surface mesh faces (is it meshed?).")
            slave_faces, slave_nps = _drop_to_corner_facets(slave_faces)
            slave_nodes = None

        # Outward normal: pass it ONLY when the user explicitly set it.
        # The fork contact kernel computes a correct PER-FACET normal from
        # each facet's connectivity and uses the supplied -outward purely as
        # a single global SIGN reference (LadrunoContactProjection.h
        # normalOriented). On a curved/closed/solid-part master a single
        # outward silently skips facets ~perpendicular to it and inverts
        # (→ inward, wrong contact) facets opposed to it; omitting it lets
        # the kernel use its correct per-pair (slave − segment-centroid)
        # sign reference. So never auto-derive a global outward here.
        #
        # 2D CARVE-OUT. The paragraph above settles 3D and does not reach
        # 2D, where the fork orients from ONE interface-level centroid
        # vote and aborts when it is ambiguous — flush interfaces (the
        # workhorse 2D case) and strongly curved / closed masters. The 2D
        # answer is `outward="winding"`: apeGmsh still derives no VECTOR
        # (the reasoning above is not overturned, it is out of scope) —
        # the side is declared through the master chain's ORIENTATION,
        # which the chained walk fixed against each segment's own
        # material. That is exact per segment, so it carries the cases a
        # single direction structurally cannot. The price is that the
        # fork's centroid vote is then bypassed, which is why the
        # wrong-side guard below exists.
        outward = _normalise_outward(defn.outward)
        if isinstance(outward, str) and model_dim != 2:
            raise ValueError(
                f"contact: interaction "
                f"{defn.name or defn.master_label!r} declares "
                f"outward='winding', but the model is {model_dim}D. "
                f"Declared-winding orientation is the fork's 2D NTS lane "
                f"only — a 3D master is a facet SET with no head-to-tail "
                f"chain to wind, and the 3D kernel already derives a "
                f"correct per-facet normal from connectivity. Drop "
                f"outward= in 3D, or pass an explicit (ox, oy, oz) for a "
                f"coincident flat interface.")
        if outward is not None and not isinstance(outward, str):
            outward = tuple(float(x) for x in outward)
            if model_dim == 2 and len(outward) == 3 \
                    and outward[2] != 0.0:
                raise ValueError(
                    f"contact: interaction "
                    f"{defn.name or defn.master_label!r} declares "
                    f"outward={outward!r} with a non-zero oz, but the "
                    f"model is 2D — a 2D outward lies in the plane. The "
                    f"fork takes only the 2-component form on a 2D "
                    f"surface (the 3-component 3D form is rejected "
                    f"there), so oz has nowhere to go. Pass "
                    f"outward=(ox, oy).")

        if model_dim == 2:
            # The two orientation guards apeGmsh owes a 2D deck, on
            # BOTH lanes: refuse the flush interface the fork cannot
            # orient, and refuse the master that faces away from the
            # slave — which nothing fork-side refuses (its vote only
            # picks a SIGN, and declared winding bypasses the vote
            # outright).
            #
            # Both take the slave as NODE TAGS, which the NTS lane has
            # directly and the mortar lane carries inside its own chain
            # (deduplicated — the fork's own vote dedups the
            # `-slave-segments` list for exactly this reason: every
            # interior chain vertex appears twice, and a
            # duplicate-weighted centroid can cross the magnitude floor).
            if slave_nodes is not None:
                slave_tags = slave_nodes
            else:
                slave_tags = sorted(
                    {int(t) for t in
                     np.asarray(slave_faces, dtype=np.int64).ravel()})
            if outward is None:
                _refuse_flush_without_orientation(
                    defn, master_faces, slave_tags, xyz,
                    lref_segments=slave_faces)
            from apeGmsh._kernel.geometry._boundary_chain import (
                refuse_wrong_side_master,
            )
            refuse_wrong_side_master(
                master_faces, xyz, slave_tags,
                _contact_label(defn), verb="contact")

        records.append(ContactRecord(
            kind="contact", name=defn.name,
            formulation=defn.formulation,
            master_faces=master_faces, master_nps=master_nps,
            slave_nodes=slave_nodes,
            slave_faces=slave_faces, slave_nps=slave_nps,
            outward=outward,
            kn=defn.kn, kt=defn.kt, mu=defn.mu,
            eps_n=defn.eps_n, eps_t=defn.eps_t,
            cohesion=defn.cohesion, tau_max=defn.tau_max,
            aug_tol=defn.aug_tol, max_aug=defn.max_aug, ngp=defn.ngp,
            tie=defn.tie, thickness=defn.thickness,
            soft=defn.soft, visc=defn.visc,
            consistent_tan=defn.consistent_tan, geom_tan=defn.geom_tan,
            cell=defn.cell,
            edge_edge=defn.edge_edge, edge_kn=defn.edge_kn,
            edge_band=defn.edge_band, edge_mu=defn.edge_mu,
            edge_kt=defn.edge_kt, edge_cohesion=defn.edge_cohesion,
            edge_tau_max=defn.edge_tau_max,
            edge_consistent_tan=defn.edge_consistent_tan,
            edge_soft=defn.edge_soft, edge_alm=defn.edge_alm,
            edge_aug_tol=defn.edge_aug_tol,
        ))

    self.contact_records = records
    return records

contact_plane

contact_plane(slave, *, normal, point, kn, visc=None, soft=None, slave_entities=None, name=None) -> ContactPlaneDef

Declare a rigid analytical-plane contact (fork contactPlane).

The meshed slave surface contacts a fixed infinite rigid plane (normal + point) with normal penalty kn — frictionless, no master mesh. Use it for a rigid floor / wall / foundation where the counter-body needn't be meshed. Optional visc (viscous normal stabilisation) and soft (explicit Courant-stable SOFT penalty; True ⇒ the fork default SOFSCL 0.10, or a float SOFSCL). Fork-only at run time.

Parameters

slave : str The meshed surface PG / part label whose nodes contact the plane. In a 2D model it is the meshed boundary CURVE (a dim-1 PG) or a point set — naming the dim-2 plane collects every interior node of the body and is refused by name. normal : (float, float, float) | (float, float) The plane's outward unit normal (toward the slave / open side). In a 2D model it is the 2-vector (nx, ny); it is z-padded internally and emitted as the fork's permanently-valid zero-padded 9-argument form, so there is only ever one grammar to read. point : (float, float, float) | (float, float) Any point on the plane; (px, py) in a 2D model. kn : float Normal penalty stiffness (required — there is no "auto" on contactPlane). visc : float, optional Viscous normal-stabilisation coefficient μ_c (-visc). soft : float | bool, optional Explicit-only Courant-stable SOFT penalty (-soft). slave_entities : list of (dim, tag), optional Restrict the slave to specific Gmsh entities. name : str, optional Friendly name (round-trips into the emitted deck comment).

Returns

ContactPlaneDef

Source code in src/apeGmsh/core/ConstraintsComposite.py
def contact_plane(
    self, slave, *, normal, point, kn, visc=None, soft=None,
    slave_entities=None, name=None,
) -> ContactPlaneDef:
    """Declare a rigid analytical-plane contact (fork ``contactPlane``).

    The meshed ``slave`` surface contacts a fixed infinite **rigid plane**
    (``normal`` + ``point``) with normal penalty ``kn`` — frictionless, no
    master mesh. Use it for a rigid floor / wall / foundation where the
    counter-body needn't be meshed. Optional ``visc`` (viscous normal
    stabilisation) and ``soft`` (explicit Courant-stable SOFT penalty;
    ``True`` ⇒ the fork default SOFSCL 0.10, or a float SOFSCL). Fork-only
    at run time.

    Parameters
    ----------
    slave : str
        The meshed surface PG / part label whose nodes contact the plane.
        **In a 2D model** it is the meshed boundary CURVE (a dim-1 PG) or
        a point set — naming the dim-2 plane collects every interior node
        of the body and is refused by name.
    normal : (float, float, float) | (float, float)
        The plane's outward unit normal (toward the slave / open side).
        **In a 2D model** it is the 2-vector ``(nx, ny)``; it is z-padded
        internally and emitted as the fork's permanently-valid zero-padded
        9-argument form, so there is only ever one grammar to read.
    point : (float, float, float) | (float, float)
        Any point on the plane; ``(px, py)`` in a 2D model.
    kn : float
        Normal penalty stiffness (**required** — there is no ``"auto"`` on
        ``contactPlane``).
    visc : float, optional
        Viscous normal-stabilisation coefficient μ_c (``-visc``).
    soft : float | bool, optional
        Explicit-only Courant-stable SOFT penalty (``-soft``).
    slave_entities : list of (dim, tag), optional
        Restrict the slave to specific Gmsh entities.
    name : str, optional
        Friendly name (round-trips into the emitted deck comment).

    Returns
    -------
    ContactPlaneDef
    """
    from ._compose_errors import raise_if_from_h5_session
    raise_if_from_h5_session(
        self._parent, "g.constraints.contact_plane()")
    defn = ContactPlaneDef(
        slave_label=slave, slave_entities=slave_entities,
        normal=tuple(normal), point=tuple(point),
        kn=kn, visc=visc, soft=soft, name=name,
    )
    self.contact_plane_defs.append(defn)
    return defn

resolve_contact_planes

resolve_contact_planes(node_tags, node_coords) -> list[ContactPlaneRecord]

Resolve every :meth:contact_plane def to a :class:ContactPlaneRecord — the slave node set is pulled from the live Gmsh session (mirroring the NTS slave of :meth:resolve_contacts). node_tags / node_coords are accepted for signature parity with the sibling resolvers. Serial-only (the fork contact subsystem is not parallel).

The model dimension is read once, here, and threaded — the :meth:resolve_contacts idiom. This lane has no master mesh and no facets, so the whole 2D difference is the slave gate below plus the refusal of an out-of-plane normal / point: the rigid-plane lane keeps the fork's ndf >= ndm (its adapter couples the first ndm DOFs by construction, which is what lets a 3D ndf-6 shell sit on a plane), so unlike the NTS/mortar lanes there is nothing else to branch on.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def resolve_contact_planes(
    self, node_tags, node_coords,
) -> list[ContactPlaneRecord]:
    """Resolve every :meth:`contact_plane` def to a
    :class:`ContactPlaneRecord` — the slave node set is pulled from the live
    Gmsh session (mirroring the NTS slave of :meth:`resolve_contacts`).
    ``node_tags`` / ``node_coords`` are accepted for signature parity with
    the sibling resolvers. Serial-only (the fork contact subsystem is not
    parallel).

    **The model dimension is read once, here, and threaded** — the
    :meth:`resolve_contacts` idiom. This lane has no master mesh and no
    facets, so the whole 2D difference is the slave gate below plus the
    refusal of an out-of-plane normal / point: the rigid-plane lane keeps
    the fork's ``ndf >= ndm`` (its adapter couples the first ``ndm`` DOFs
    by construction, which is what lets a 3D ndf-6 shell sit on a plane),
    so unlike the NTS/mortar lanes there is nothing else to branch on.
    """
    records: list[ContactPlaneRecord] = []
    if not self.contact_plane_defs:
        self.contact_plane_records = records
        return records

    import gmsh
    model_dim = int(gmsh.model.getDimension())

    for defn in self.contact_plane_defs:
        s_ents = (defn.slave_entities
                  or self._entities_for_label(defn.slave_label))
        _refuse_contact_entity_dim(
            s_ents, defn.slave_label, model_dim=model_dim,
            role="slave", verb="contact_plane")
        if model_dim == 2:
            _refuse_contact_plane_out_of_plane(defn)
        slave_nodes = self._collect_node_set(s_ents, defn.slave_label)
        if not slave_nodes:
            raise ValueError(
                f"contact_plane: slave label {defn.slave_label!r} resolved "
                f"to no surface nodes (is it meshed?).")
        records.append(ContactPlaneRecord(
            kind="contact_plane", name=defn.name,
            slave_nodes=slave_nodes,
            normal=tuple(float(x) for x in defn.normal),
            point=tuple(float(x) for x in defn.point),
            kn=defn.kn, visc=defn.visc, soft=defn.soft,
        ))

    self.contact_plane_records = records
    return records

interface

interface(master, slave, *, normal, tangential, thickness, tolerance=1e-06, slave_ndf=None, master_entities=None, slave_entities=None, name=None) -> InterfaceDef

Declare an oriented coincident-pair zeroLength interface (ADR 0093).

One zeroLength spring per coincident (master, slave) node pair, with the local axes taken per pair from the master face geometry — so a curved master's normal follows the face from wall to crown instead of collapsing to one average frame — and the normal / tangential laws scaled by each pair's tributary area. The point of the verb is a unilateral (compression-only, separation allowed) and strength-capped interface: with a bilateral bond a converging ground drives the liner's demand without bound.

2D line masters only in v1; a 3D model or a surface master raises :class:NotImplementedError (ADR 0093 D2).

Parameters

master, slave : str The master curve PG / part label — a free boundary of the meshed 2D continuum — and the node-for-node coincident slave label. The two node sets must be disjoint. normal : NormalLaw Per-area normal law: NormalLaw(kind="ent"|"epp_gap"| "elastic", k_per_area=..., ...). Declarative kernel data, translated to a typed uniaxial material (scaled by A_trib) only at emit. tangential : TangentialLaw Per-area tangential law: TangentialLaw(kind="epp"| "elastic", k_per_area=..., tau_b=...). thickness : float Out-of-plane thickness (required, > 0) — A_trib = ell_trib * thickness. tolerance : float Coincidence radius for the node pairing. A slave with no master inside it is an error, never a silent skip. slave_ndf : {None, 2, 3} The ndf the slave wire will be declared with. None / 2 ⇒ the slave matches the 2D continuum and the pair connects directly; 3 ⇒ a beam slave, so each pair gets the phantom bridge of ADR 0093 D4 (the fork refuses a mixed-ndf zeroLength). Explicit by design — see :class:~apeGmsh._kernel.defs.constraints.InterfaceDef. master_entities, slave_entities : list of (dim, tag), optional Restrict each side to specific Gmsh entities. name : str, optional Friendly name (carried onto every resolved record).

Returns

InterfaceDef

Source code in src/apeGmsh/core/ConstraintsComposite.py
def interface(
    self, master, slave, *,
    normal, tangential, thickness,
    tolerance=1e-6, slave_ndf=None,
    master_entities=None, slave_entities=None,
    name=None,
) -> InterfaceDef:
    """Declare an oriented coincident-pair ``zeroLength`` interface
    (ADR 0093).

    One ``zeroLength`` spring per coincident (master, slave) node
    pair, with the local axes taken **per pair** from the master
    face geometry — so a curved master's normal follows the face
    from wall to crown instead of collapsing to one average frame —
    and the normal / tangential laws scaled by each pair's
    tributary area. The point of the verb is a *unilateral*
    (compression-only, separation allowed) and *strength-capped*
    interface: with a bilateral bond a converging ground drives the
    liner's demand without bound.

    2D line masters only in v1; a 3D model or a surface master
    raises :class:`NotImplementedError` (ADR 0093 D2).

    Parameters
    ----------
    master, slave : str
        The master curve PG / part label — a **free boundary** of
        the meshed 2D continuum — and the node-for-node coincident
        slave label. The two node sets must be disjoint.
    normal : NormalLaw
        Per-area normal law: ``NormalLaw(kind="ent"|"epp_gap"|
        "elastic", k_per_area=..., ...)``. Declarative kernel data,
        translated to a typed uniaxial material (scaled by
        ``A_trib``) only at emit.
    tangential : TangentialLaw
        Per-area tangential law: ``TangentialLaw(kind="epp"|
        "elastic", k_per_area=..., tau_b=...)``.
    thickness : float
        Out-of-plane thickness (**required**, ``> 0``) —
        ``A_trib = ell_trib * thickness``.
    tolerance : float
        Coincidence radius for the node pairing. A slave with no
        master inside it is an error, never a silent skip.
    slave_ndf : {None, 2, 3}
        The ndf the slave wire will be declared with. ``None`` /
        ``2`` ⇒ the slave matches the 2D continuum and the pair
        connects directly; ``3`` ⇒ a beam slave, so each pair gets
        the phantom bridge of ADR 0093 D4 (the fork refuses a
        mixed-ndf ``zeroLength``). Explicit by design — see
        :class:`~apeGmsh._kernel.defs.constraints.InterfaceDef`.
    master_entities, slave_entities : list of (dim, tag), optional
        Restrict each side to specific Gmsh entities.
    name : str, optional
        Friendly name (carried onto every resolved record).

    Returns
    -------
    InterfaceDef
    """
    # Same gate as contact(): a from_h5 / composed session has no
    # live geometry to re-derive the per-pair frames from (ADR 0086
    # precedent, silent-failures slice 2).
    from ._compose_errors import raise_if_from_h5_session
    raise_if_from_h5_session(self._parent, "g.constraints.interface()")
    self._refuse_3d_interface()
    defn = InterfaceDef(
        master_label=master, slave_label=slave,
        master_entities=master_entities, slave_entities=slave_entities,
        normal=normal, tangential=tangential,
        thickness=thickness, tolerance=tolerance,
        slave_ndf=slave_ndf, name=name,
    )
    self.interface_defs.append(defn)
    return defn

resolve_interfaces

resolve_interfaces(node_tags, node_coords) -> list

Resolve every :meth:interface def to :class:InterfaceRecord\ s.

Gathers the live-Gmsh inputs — both node sets, the master's boundary line elements, and the model's 2D domain elements — and hands the geometry math to :func:~apeGmsh._kernel.resolvers._interface_resolver.resolve_interface_records (pure kernel, no Gmsh), mirroring how :meth:resolve_contacts gathers and delegates.

Must run after :meth:resolve so the interface phantom tags start above the MP lane's phantom high-water mark; the factory orders them that way.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def resolve_interfaces(self, node_tags, node_coords) -> list:
    """Resolve every :meth:`interface` def to :class:`InterfaceRecord`\\ s.

    Gathers the live-Gmsh inputs — both node sets, the master's
    boundary line elements, and the model's 2D domain elements —
    and hands the geometry math to
    :func:`~apeGmsh._kernel.resolvers._interface_resolver.resolve_interface_records`
    (pure kernel, no Gmsh), mirroring how :meth:`resolve_contacts`
    gathers and delegates.

    Must run **after** :meth:`resolve` so the interface phantom tags
    start above the MP lane's phantom high-water mark; the factory
    orders them that way.
    """
    from apeGmsh._kernel.resolvers._interface_resolver import (
        resolve_interface_records,
    )

    records: list = []
    if not self.interface_defs:
        self.interface_records = records
        return records

    import gmsh
    model_dim = int(gmsh.model.getDimension())
    if model_dim != 2:
        raise NotImplementedError(
            f"interface: the model is {model_dim}D and only 2D line "
            f"masters are implemented (ADR 0093 D2).")

    domain_tags, domain_conn = self._collect_domain_elements()
    # Start above BOTH the model's own node tags and any phantom the
    # MP lane already minted this resolve (see
    # ``_phantom_tag_high_water``).
    next_phantom = int(np.max(np.asarray(node_tags, dtype=int))) + 1
    if self._phantom_tag_high_water is not None:
        next_phantom = max(next_phantom, int(self._phantom_tag_high_water))

    for defn in self.interface_defs:
        m_ents = (defn.master_entities
                  or self._entities_for_label(defn.master_label))
        s_ents = (defn.slave_entities
                  or self._entities_for_label(defn.slave_label))
        bad_dims = sorted({int(d) for d, _ in m_ents} - {1})
        if bad_dims:
            raise NotImplementedError(
                f"interface: master label {defn.master_label!r} "
                f"resolves to entities of dimension {bad_dims}, but "
                f"only 2D line (dim-1) masters are implemented — a "
                f"surface master is deferred (ADR 0093 D2).")

        master_nodes = self._collect_node_set(
            m_ents, defn.master_label, kind="interface", role="master")
        slave_nodes = self._collect_node_set(
            s_ents, defn.slave_label, kind="interface", role="slave")
        edges = self._collect_master_edges(m_ents, defn.master_label)

        recs, next_phantom = resolve_interface_records(
            node_tags, node_coords,
            master_nodes=master_nodes,
            slave_nodes=slave_nodes,
            master_edges=edges,
            domain_elem_tags=domain_tags,
            domain_elem_nodes=domain_conn,
            normal_law=defn.normal,
            tangential_law=defn.tangential,
            thickness=defn.thickness,
            tolerance=defn.tolerance,
            slave_ndf=defn.slave_ndf,
            ndm=model_dim,
            phantom_tag_start=next_phantom,
            name=defn.name,
        )
        records.extend(recs)

    # Deliberately NOT written back to ``_phantom_tag_high_water``:
    # that field carries the MP lane's mark *for this extraction*,
    # and ``resolve()`` refreshes it every time. Folding this run's
    # advance into it would make a second ``get_fem_data()`` on the
    # same session mint different phantom tags — a tag-determinism
    # break (ADR 0027). Nothing downstream of here mints phantoms.
    self.interface_records = records
    return records

bc

bc(target=None, *, pg=None, label=None, tag=None, dofs=None, name=None) -> BCDef

Homogeneous single-point constraint — fix a pattern to ground.

The natural (essential / Dirichlet) boundary condition: every mesh node in the resolved pattern gets ops.fix(node, *mask) downstream. There is no master and no slave — unlike every other method on this composite, this is a constraint to ground, not between two parts. It resolves into fem.nodes.sp (homogeneous :class:SPRecord\ s) — the same broker channel as g.displacements.surfacenot fem.nodes.constraints.

Because it is a permanent constraint (not a pattern-scoped quantity), it lives here on g.constraints rather than on g.displacements: there is no load-pattern context to accidentally scope it into, and the downstream emitter places it in the model → bcs → patterns deck order via ops.fix.

Parameters

target : str or list[(dim, tag)] Pattern to fix. Resolved label → physical group → raw tags (or a mesh selection) — the same flexible target model as g.displacements.surface. Pass pg= / label= / tag= instead to force a specific resolution path. dofs : list[int], optional Restraint mask (1 = constrained, 0 = free), in DOF order [ux, uy, uz, rx, ry, rz]. Default [1, 1, 1] (pin all translations). This is the OpenSees ops.fix / face_sp convention — not the index-list convention used by :meth:equal_dof (dofs=[1,2,3]). name : str, optional Friendly name shown in summaries / the viewer.

Returns

BCDef The stored definition; the same object is appended to self._bc_defs.

Warnings

Resolution is dimension-agnostic — a point, edge, surface, or volume pattern all just contribute their mesh nodes. Pointing a BC at a volume physical group therefore fixes every interior node of the solid, which is almost never intended; target a boundary surface/edge instead.

Examples

::

g.constraints.bc("base_face")                  # pin x,y,z
g.constraints.bc(pg="Supports", dofs=[1, 1, 0])
g.constraints.bc(label="col.base",
                 dofs=[1, 1, 1, 1, 1, 1])       # full fixity
Source code in src/apeGmsh/core/ConstraintsComposite.py
def bc(self, target=None, *, pg=None, label=None, tag=None,
       dofs=None, name=None) -> BCDef:
    """Homogeneous single-point constraint — fix a pattern to ground.

    The natural (essential / Dirichlet) boundary condition: every
    mesh node in the resolved pattern gets ``ops.fix(node, *mask)``
    downstream. There is **no master and no slave** — unlike every
    other method on this composite, this is a constraint *to
    ground*, not between two parts. It resolves into
    ``fem.nodes.sp`` (homogeneous :class:`SPRecord`\\ s) — the same
    broker channel as ``g.displacements.surface`` — **not**
    ``fem.nodes.constraints``.

    Because it is a *permanent* constraint (not a pattern-scoped
    quantity), it lives here on ``g.constraints`` rather than on
    ``g.displacements``: there is no load-pattern context to accidentally
    scope it into, and the downstream emitter places it in the
    ``model → bcs → patterns`` deck order via ``ops.fix``.

    Parameters
    ----------
    target : str or list[(dim, tag)]
        Pattern to fix. Resolved label → physical group → raw
        tags (or a mesh selection) — the same flexible target
        model as ``g.displacements.surface``. Pass ``pg=`` / ``label=``
        / ``tag=`` instead to force a specific resolution path.
    dofs : list[int], optional
        Restraint **mask** (``1`` = constrained, ``0`` = free), in
        DOF order ``[ux, uy, uz, rx, ry, rz]``. Default
        ``[1, 1, 1]`` (pin all translations). This is the
        OpenSees ``ops.fix`` / ``face_sp`` convention — **not**
        the index-list convention used by
        :meth:`equal_dof` (``dofs=[1,2,3]``).
    name : str, optional
        Friendly name shown in summaries / the viewer.

    Returns
    -------
    BCDef
        The stored definition; the same object is appended to
        ``self._bc_defs``.

    Warnings
    --------
    Resolution is dimension-agnostic — a point, edge, surface, or
    volume pattern all just contribute their mesh nodes. Pointing
    a BC at a **volume** physical group therefore fixes *every
    interior node of the solid*, which is almost never intended;
    target a boundary surface/edge instead.

    Examples
    --------
    ::

        g.constraints.bc("base_face")                  # pin x,y,z
        g.constraints.bc(pg="Supports", dofs=[1, 1, 0])
        g.constraints.bc(label="col.base",
                         dofs=[1, 1, 1, 1, 1, 1])       # full fixity
    """
    t, src = self._parent.loads._coalesce_target(
        target, pg=pg, label=label, tag=tag)
    defn = BCDef(target=t, target_source=src,
                 dofs=list(dofs) if dofs is not None else [1, 1, 1],
                 name=name)
    self._bc_defs.append(defn)
    # Phase 3B.2d / ADR 0038 — chain-phase routing.  See
    # ``MassesComposite._add_def`` for the contract.
    from apeGmsh._kernel.resolvers._chain_phase_router import (
        try_chain_phase_route,
    )
    try_chain_phase_route(self._parent, defn)
    bump = getattr(self._parent, "_bump_fem_counter", None)
    if bump is not None:
        bump()
    return defn

resolve_bcs

resolve_bcs(node_tags, *, node_map=None) -> list

Resolve every :meth:bc def to homogeneous SPRecord\ s.

Mirrors the load/SP resolution path: each BCDef target is run through the loads composite's dimension-agnostic _target_nodes (label → PG → tag → mesh-selection, any dim), then one SPRecord(value=0.0, is_homogeneous=True) is emitted per restrained DOF per node.

Fails loud — consistent with :meth:_resolve_nodes and the resolver contract — if a pattern resolves to zero mesh nodes: a BC that silently binds nothing is worse than one that errors.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def resolve_bcs(self, node_tags, *, node_map=None) -> list:
    """Resolve every :meth:`bc` def to homogeneous ``SPRecord``\\ s.

    Mirrors the load/SP resolution path: each ``BCDef`` target is
    run through the loads composite's dimension-agnostic
    ``_target_nodes`` (label → PG → tag → mesh-selection, any
    dim), then one ``SPRecord(value=0.0, is_homogeneous=True)`` is
    emitted per restrained DOF per node.

    Fails loud — consistent with :meth:`_resolve_nodes` and the
    resolver contract — if a pattern resolves to zero mesh nodes:
    a BC that silently binds nothing is worse than one that errors.
    """
    from apeGmsh._kernel.records._loads import SPRecord

    if not self._bc_defs:
        return []

    loads = self._parent.loads
    all_nodes = {int(t) for t in node_tags}
    out: list = []
    for defn in self._bc_defs:
        nodes = loads._target_nodes(
            defn.target, node_map or {}, all_nodes,
            source=defn.target_source, expected_dim=None,
        )
        if not nodes:
            raise ValueError(
                f"bc: target {defn.target!r} (source="
                f"{defn.target_source!r}) resolved to zero mesh "
                f"nodes — check it is meshed and names a real "
                f"label / physical group / entity. Refusing to "
                f"emit an empty boundary condition.")
        for nid in sorted(nodes):
            for d_idx, mask in enumerate(defn.dofs):
                if mask != 1:
                    continue
                out.append(SPRecord(
                    name=defn.name,
                    node_id=int(nid),
                    dof=d_idx + 1,
                    value=0.0,
                    is_homogeneous=True,
                ))
    return out

equal_dof

equal_dof(master_label, slave_label, *, master_entities=None, slave_entities=None, dofs=None, tolerance=1e-06, name=None) -> EqualDOFDef

Tie matching DOFs between co-located node pairs.

At resolution time the resolver finds every master node whose coordinates match a slave node within tolerance and emits one :class:~apeGmsh.solvers.Constraints.NodePairRecord per match. Each pair becomes ops.equalDOF(master, slave, *dofs) downstream — i.e. u_slave[i] = u_master[i] for every i in dofs.

Use this for conformal interfaces only — meshes that share nodes at the boundary. For non-matching meshes use :meth:tie.

Parameters

master_label : str Part, physical-group, or label name whose nodes drive the constraint. slave_label : str Part, physical-group, or label name whose matching nodes are slaved. master_entities, slave_entities : list of (dim, tag), optional Restrict the node search to specific Gmsh entities of each side. Useful when only one face of a multi-face part is the interface. dofs : list[int], optional 1-based DOF indices to constrain (1=ux, 2=uy, 3=uz, 4=rx, 5=ry, 6=rz). None (default) means all DOFs available — the actual count depends on the model's ndf. tolerance : float, default 1e-6 Maximum distance (in model units) between two nodes for them to be treated as co-located. Unit-sensitive: 1e-3 for millimetre models, 1e-6 for metre models. name : str, optional Friendly name shown in :meth:summary and the viewer.

Returns

EqualDOFDef The stored definition; the same object is appended to self.constraint_defs.

Raises

KeyError If master_label or slave_label is not in g.parts.

See Also

tie : Non-matching mesh equivalent (shape-function projection). rigid_link : Add a kinematic offset on top of co-location.

Examples

Translational continuity between a column and a beam at a joint::

g.constraints.equal_dof(
    "column", "beam",
    dofs=[1, 2, 3],
    tolerance=1e-3,        # mm model
)
Source code in src/apeGmsh/core/ConstraintsComposite.py
def equal_dof(self, master_label, slave_label, *, master_entities=None,
              slave_entities=None, dofs=None, tolerance=1e-6,
              name=None) -> EqualDOFDef:
    """Tie matching DOFs between **co-located** node pairs.

    At resolution time the resolver finds every master node
    whose coordinates match a slave node within ``tolerance``
    and emits one
    :class:`~apeGmsh.solvers.Constraints.NodePairRecord` per
    match. Each pair becomes ``ops.equalDOF(master, slave, *dofs)``
    downstream — i.e. ``u_slave[i] = u_master[i]`` for every
    ``i`` in ``dofs``.

    Use this for **conformal** interfaces only — meshes that share
    nodes at the boundary. For non-matching meshes use :meth:`tie`.

    Parameters
    ----------
    master_label : str
        Part, physical-group, or label name whose nodes drive the
        constraint.
    slave_label : str
        Part, physical-group, or label name whose matching nodes
        are slaved.
    master_entities, slave_entities : list of (dim, tag), optional
        Restrict the node search to specific Gmsh entities of
        each side. Useful when only one face of a multi-face
        part is the interface.
    dofs : list[int], optional
        1-based DOF indices to constrain (``1=ux, 2=uy, 3=uz,
        4=rx, 5=ry, 6=rz``). ``None`` (default) means *all DOFs
        available* — the actual count depends on the model's
        ``ndf``.
    tolerance : float, default 1e-6
        Maximum distance (in model units) between two nodes for
        them to be treated as co-located. **Unit-sensitive**:
        ``1e-3`` for millimetre models, ``1e-6`` for metre
        models.
    name : str, optional
        Friendly name shown in :meth:`summary` and the viewer.

    Returns
    -------
    EqualDOFDef
        The stored definition; the same object is appended to
        ``self.constraint_defs``.

    Raises
    ------
    KeyError
        If ``master_label`` or ``slave_label`` is not in
        ``g.parts``.

    See Also
    --------
    tie : Non-matching mesh equivalent (shape-function projection).
    rigid_link : Add a kinematic offset on top of co-location.

    Examples
    --------
    Translational continuity between a column and a beam at a
    joint::

        g.constraints.equal_dof(
            "column", "beam",
            dofs=[1, 2, 3],
            tolerance=1e-3,        # mm model
        )
    """
    return self._add_def(EqualDOFDef(
        master_label=master_label, slave_label=slave_label,
        master_entities=master_entities, slave_entities=slave_entities,
        dofs=dofs, tolerance=tolerance, name=name))

equal_dof_mixed

equal_dof_mixed(master_label, slave_label, *, dof_pairs, master_entities=None, slave_entities=None, tolerance=1e-06, name=None) -> EqualDOFMixedDef

Tie differently-numbered DOFs between co-located node pairs.

The mixed analog of :meth:equal_dof: rather than tying DOF i to DOF i, each (retained_dof, constrained_dof) couple in dof_pairs is tied explicitly — so master ux can drive slave rz, etc. Resolves like equal_dof (one record per co-located pair) and emits ops.equalDOF_Mixed(R, C, numDOF, RDOF1, CDOF1, ...) per pair.

Use this for conformal interfaces where the two sides expose the coupled quantity under different DOF indices (e.g. tying a solid's translation to a shell's drilling rotation). For matching DOFs use :meth:equal_dof; for non-matching meshes use :meth:tie.

Parameters

master_label : str Part label whose nodes are retained (the R node). slave_label : str Part label whose matching nodes are constrained (C). dof_pairs : list of (int, int) (retained_dof, constrained_dof) couples, 1-based (1=ux, 2=uy, 3=uz, 4=rx, 5=ry, 6=rz). Required and non-empty; the two members of a couple may differ. master_entities, slave_entities : list of (dim, tag), optional Restrict the node search to specific Gmsh entities of each side. tolerance : float, default 1e-6 Co-location distance (model units). Unit-sensitive — see :meth:equal_dof. name : str, optional Friendly name shown in :meth:summary and the viewer.

Returns

EqualDOFMixedDef The stored definition; also appended to self.constraint_defs.

See Also

equal_dof : Same-DOF co-located tie (the common case).

Examples

Tie a solid face's z-translation to a shell edge's drilling DOF::

g.constraints.equal_dof_mixed(
    "solid", "shell",
    dof_pairs=[(3, 6)],    # master uz → slave rz
    tolerance=1e-3,        # mm model
)
Source code in src/apeGmsh/core/ConstraintsComposite.py
def equal_dof_mixed(self, master_label, slave_label, *, dof_pairs,
                    master_entities=None, slave_entities=None,
                    tolerance=1e-6, name=None) -> EqualDOFMixedDef:
    """Tie *differently-numbered* DOFs between **co-located** node pairs.

    The mixed analog of :meth:`equal_dof`: rather than tying DOF
    ``i`` to DOF ``i``, each ``(retained_dof, constrained_dof)``
    couple in ``dof_pairs`` is tied explicitly — so master ``ux``
    can drive slave ``rz``, etc. Resolves like ``equal_dof`` (one
    record per co-located pair) and emits
    ``ops.equalDOF_Mixed(R, C, numDOF, RDOF1, CDOF1, ...)`` per pair.

    Use this for **conformal** interfaces where the two sides expose
    the coupled quantity under different DOF indices (e.g. tying a
    solid's translation to a shell's drilling rotation). For matching
    DOFs use :meth:`equal_dof`; for non-matching meshes use :meth:`tie`.

    Parameters
    ----------
    master_label : str
        Part label whose nodes are **retained** (the ``R`` node).
    slave_label : str
        Part label whose matching nodes are **constrained** (``C``).
    dof_pairs : list of (int, int)
        ``(retained_dof, constrained_dof)`` couples, 1-based
        (``1=ux, 2=uy, 3=uz, 4=rx, 5=ry, 6=rz``). Required and
        non-empty; the two members of a couple may differ.
    master_entities, slave_entities : list of (dim, tag), optional
        Restrict the node search to specific Gmsh entities of each side.
    tolerance : float, default 1e-6
        Co-location distance (model units). **Unit-sensitive** — see
        :meth:`equal_dof`.
    name : str, optional
        Friendly name shown in :meth:`summary` and the viewer.

    Returns
    -------
    EqualDOFMixedDef
        The stored definition; also appended to ``self.constraint_defs``.

    See Also
    --------
    equal_dof : Same-DOF co-located tie (the common case).

    Examples
    --------
    Tie a solid face's z-translation to a shell edge's drilling DOF::

        g.constraints.equal_dof_mixed(
            "solid", "shell",
            dof_pairs=[(3, 6)],    # master uz → slave rz
            tolerance=1e-3,        # mm model
        )
    """
    return self._add_def(EqualDOFMixedDef(
        master_label=master_label, slave_label=slave_label,
        master_entities=master_entities, slave_entities=slave_entities,
        dof_pairs=[tuple(p) for p in dof_pairs],
        tolerance=tolerance, name=name))
rigid_link(master_label, slave_label, *, link_type='beam', master_point=None, slave_entities=None, tolerance=1e-06, name=None) -> RigidLinkDef

Rigid bar between a master node and one or more slave nodes.

Each slave node is constrained to follow the master through a rigid offset arm r = x_slave − x_master::

link_type="beam":     u_s = u_m + θ_m × r,   θ_s = θ_m
link_type="rod":      u_s = u_m + θ_m × r,   θ_s free

Use "beam" for fully rigid kinematic offsets (eccentric connections, lumped-mass arms, fictitious rigid extensions). Use "rod" when you want to transmit translation but leave the slave free to rotate — e.g. pinned eccentric supports.

master_label : str Part, physical-group, or label name that owns the master node. The master is identified inside this part either by master_point (proximity match) or by being the unique node when the part collapses to a single point. slave_label : str Part, physical-group, or label name whose nodes become slaves. link_type : "beam" or "rod", default "beam" "beam" couples 6 DOFs with rotational offset; "rod" couples translations only. master_point : (x, y, z), optional Explicit master coordinates. If None, the resolver picks the master node by proximity within tolerance. slave_entities : list of (dim, tag), optional Restrict the slave node search to specific entities. tolerance : float, default 1e-6 Proximity tolerance for master-node detection. name : str, optional Friendly name.

RigidLinkDef

KeyError If either label is not in g.parts.

kinematic_coupling : Same idea, but lets you pick which DOFs to couple instead of the fixed beam/rod sets. node_to_surface : When the slave side has only translational DOFs (3-DOF solid nodes).

Lumped-mass arm at the top of a tower::

g.constraints.rigid_link(
    "tower_top", "lumped_mass",
    link_type="beam",
    master_point=(0, 0, 30.0),
)
Source code in src/apeGmsh/core/ConstraintsComposite.py
def rigid_link(self, master_label, slave_label, *, link_type="beam",
               master_point=None, slave_entities=None,
               tolerance=1e-6, name=None) -> RigidLinkDef:
    """Rigid bar between a master node and one or more slave nodes.

    Each slave node is constrained to follow the master through
    a rigid offset arm ``r = x_slave − x_master``::

        link_type="beam":     u_s = u_m + θ_m × r,   θ_s = θ_m
        link_type="rod":      u_s = u_m + θ_m × r,   θ_s free

    Use ``"beam"`` for fully rigid kinematic offsets (eccentric
    connections, lumped-mass arms, fictitious rigid extensions).
    Use ``"rod"`` when you want to transmit translation but leave
    the slave free to rotate — e.g. pinned eccentric supports.

    Parameters
    ----------
    master_label : str
        Part, physical-group, or label name that owns the master
        node. The master is
        identified inside this part either by ``master_point``
        (proximity match) or by being the unique node when the
        part collapses to a single point.
    slave_label : str
        Part, physical-group, or label name whose nodes become
        slaves.
    link_type : ``"beam"`` or ``"rod"``, default ``"beam"``
        ``"beam"`` couples 6 DOFs with rotational offset;
        ``"rod"`` couples translations only.
    master_point : (x, y, z), optional
        Explicit master coordinates. If ``None``, the resolver
        picks the master node by proximity within ``tolerance``.
    slave_entities : list of (dim, tag), optional
        Restrict the slave node search to specific entities.
    tolerance : float, default 1e-6
        Proximity tolerance for master-node detection.
    name : str, optional
        Friendly name.

    Returns
    -------
    RigidLinkDef

    Raises
    ------
    KeyError
        If either label is not in ``g.parts``.

    See Also
    --------
    kinematic_coupling : Same idea, but lets you pick which DOFs
        to couple instead of the fixed beam/rod sets.
    node_to_surface : When the slave side has only translational
        DOFs (3-DOF solid nodes).

    Examples
    --------
    Lumped-mass arm at the top of a tower::

        g.constraints.rigid_link(
            "tower_top", "lumped_mass",
            link_type="beam",
            master_point=(0, 0, 30.0),
        )
    """
    return self._add_def(RigidLinkDef(
        master_label=master_label, slave_label=slave_label,
        link_type=link_type, master_point=master_point,
        slave_entities=slave_entities, tolerance=tolerance, name=name))

penalty

penalty(master_label, slave_label, *, stiffness=10000000000.0, dofs=None, tolerance=1e-06, name=None) -> PenaltyDef

Soft-spring (penalty) coupling between co-located node pairs.

Numerically approximates :meth:equal_dof as stiffness → ∞. The resolver still requires master and slave nodes to be co-located within tolerance, but downstream the constraint is enforced by inserting a stiff spring element between each pair instead of a hard MPC.

Use this when:

  • The hard equal_dof constraint causes the constraint-handler to ill-condition the reduced stiffness matrix (typical with mismatched DOF spaces).
  • You want a tunable interface compliance — e.g. a soft contact at a bearing pad.
Parameters

master_label : str Part label of the master side. slave_label : str Part label of the slave side. stiffness : float, default 1e10 Penalty spring stiffness in force/length units. Pick ~3–6 orders of magnitude above the stiffest neighbouring element diagonal — overshoot causes ill-conditioning, undershoot leaks displacement. dofs : list[int], optional 1-based DOFs to penalise. None = all available. tolerance : float, default 1e-6 Spatial co-location tolerance. name : str, optional Friendly name.

Returns

PenaltyDef

Raises

KeyError If either label is not in g.parts.

See Also

equal_dof : Hard MPC equivalent (no tunable stiffness).

Source code in src/apeGmsh/core/ConstraintsComposite.py
def penalty(self, master_label, slave_label, *, stiffness=1e10,
            dofs=None, tolerance=1e-6, name=None) -> PenaltyDef:
    """Soft-spring (penalty) coupling between co-located node pairs.

    Numerically approximates :meth:`equal_dof` as
    ``stiffness → ∞``. The resolver still requires master and
    slave nodes to be co-located within ``tolerance``, but
    downstream the constraint is enforced by inserting a stiff
    spring element between each pair instead of a hard MPC.

    Use this when:

    * The hard ``equal_dof`` constraint causes the
      constraint-handler to ill-condition the reduced stiffness
      matrix (typical with mismatched DOF spaces).
    * You want a tunable interface compliance — e.g. a soft
      contact at a bearing pad.

    Parameters
    ----------
    master_label : str
        Part label of the master side.
    slave_label : str
        Part label of the slave side.
    stiffness : float, default 1e10
        Penalty spring stiffness in force/length units. Pick
        ~3–6 orders of magnitude above the stiffest neighbouring
        element diagonal — overshoot causes ill-conditioning,
        undershoot leaks displacement.
    dofs : list[int], optional
        1-based DOFs to penalise. ``None`` = all available.
    tolerance : float, default 1e-6
        Spatial co-location tolerance.
    name : str, optional
        Friendly name.

    Returns
    -------
    PenaltyDef

    Raises
    ------
    KeyError
        If either label is not in ``g.parts``.

    See Also
    --------
    equal_dof : Hard MPC equivalent (no tunable stiffness).
    """
    return self._add_def(PenaltyDef(
        master_label=master_label, slave_label=slave_label,
        stiffness=stiffness, dofs=dofs, tolerance=tolerance, name=name))

rigid_diaphragm

rigid_diaphragm(master_label, slave_label, *, master_point=(0.0, 0.0, 0.0), plane_normal=(0.0, 0.0, 1.0), constrained_dofs=None, plane_tolerance=1.0, name=None) -> RigidDiaphragmDef

In-plane rigid floor — slaves follow master in the diaphragm plane.

Classic use: each floor of a multi-storey building. All slab nodes within plane_tolerance of the diaphragm plane share in-plane translation and rotation about the out-of-plane axis with the master node, while remaining free in the out-of-plane direction.

Resolution emits a single :class:~apeGmsh.solvers.Constraints.NodeGroupRecord with one master and many slaves. Downstream this becomes ops.rigidDiaphragm(perpDirn, master, *slaves).

Parameters

master_label : str Part, physical-group, or label name that contains (or whose proximity will select) the master node — typically a centre-of-mass point. slave_label : str Part, physical-group, or label name whose nodes are gathered into the diaphragm. master_point : (x, y, z), default (0, 0, 0) Coordinates of the master node. Used to disambiguate when the master part has more than one node. plane_normal : (nx, ny, nz), default (0, 0, 1) Unit normal to the diaphragm plane. (0, 0, 1) is a horizontal floor; (0, 1, 0) is a vertical wall, etc. constrained_dofs : list[int], optional DOFs slaved to the master. Default for a horizontal floor (Z up) is [1, 2, 6] — ux, uy, rz. For a vertical wall use [1, 3, 5]. plane_tolerance : float, default 1.0 Perpendicular distance (in model units) from the diaphragm plane within which a slave node is collected. Unit-sensitive — set this to a fraction of slab thickness. name : str, optional Friendly name.

Returns

RigidDiaphragmDef

Raises

KeyError If either label is not in g.parts.

See Also

kinematic_coupling : When you need a different DOF subset than [1, 2, 6] and don't need plane filtering. rigid_body : When all 6 DOFs must follow the master.

Examples

A horizontal slab at z = 3.0 m::

g.constraints.rigid_diaphragm(
    "slab", "slab_master",
    master_point=(2.5, 2.5, 3.0),
    plane_normal=(0, 0, 1),
    constrained_dofs=[1, 2, 6],
    plane_tolerance=0.05,
)
Source code in src/apeGmsh/core/ConstraintsComposite.py
def rigid_diaphragm(self, master_label, slave_label, *,
                    master_point=(0., 0., 0.),
                    plane_normal=(0., 0., 1.),
                    constrained_dofs=None, plane_tolerance=1.0,
                    name=None) -> RigidDiaphragmDef:
    """In-plane rigid floor — slaves follow master in the
    diaphragm plane.

    Classic use: each floor of a multi-storey building. All
    slab nodes within ``plane_tolerance`` of the diaphragm
    plane share in-plane translation and rotation about the
    out-of-plane axis with the master node, while remaining
    free in the out-of-plane direction.

    Resolution emits a single
    :class:`~apeGmsh.solvers.Constraints.NodeGroupRecord`
    with one master and many slaves. Downstream this becomes
    ``ops.rigidDiaphragm(perpDirn, master, *slaves)``.

    Parameters
    ----------
    master_label : str
        Part, physical-group, or label name that contains (or whose
        proximity will
        select) the master node — typically a centre-of-mass
        point.
    slave_label : str
        Part, physical-group, or label name whose nodes are
        gathered into the diaphragm.
    master_point : (x, y, z), default (0, 0, 0)
        Coordinates of the master node. Used to disambiguate
        when the master part has more than one node.
    plane_normal : (nx, ny, nz), default (0, 0, 1)
        Unit normal to the diaphragm plane. ``(0, 0, 1)`` is a
        horizontal floor; ``(0, 1, 0)`` is a vertical wall, etc.
    constrained_dofs : list[int], optional
        DOFs slaved to the master. Default for a horizontal
        floor (Z up) is ``[1, 2, 6]`` — ux, uy, rz. For a
        vertical wall use ``[1, 3, 5]``.
    plane_tolerance : float, default 1.0
        Perpendicular distance (in model units) from the
        diaphragm plane within which a slave node is
        collected. **Unit-sensitive** — set this to a fraction
        of slab thickness.
    name : str, optional
        Friendly name.

    Returns
    -------
    RigidDiaphragmDef

    Raises
    ------
    KeyError
        If either label is not in ``g.parts``.

    See Also
    --------
    kinematic_coupling : When you need a different DOF subset
        than ``[1, 2, 6]`` and don't need plane filtering.
    rigid_body : When all 6 DOFs must follow the master.

    Examples
    --------
    A horizontal slab at z = 3.0 m::

        g.constraints.rigid_diaphragm(
            "slab", "slab_master",
            master_point=(2.5, 2.5, 3.0),
            plane_normal=(0, 0, 1),
            constrained_dofs=[1, 2, 6],
            plane_tolerance=0.05,
        )
    """
    return self._add_def(RigidDiaphragmDef(
        master_label=master_label, slave_label=slave_label,
        master_point=master_point, plane_normal=plane_normal,
        constrained_dofs=constrained_dofs or [1, 2, 6],
        plane_tolerance=plane_tolerance, name=name))

rigid_body

rigid_body(master_label, slave_label, *, master_point=(0.0, 0.0, 0.0), as_element=False, mass=None, omega=None, name=None) -> RigidBodyDef

Fully rigid cluster — every slave DOF follows the master.

All six DOFs (ux, uy, uz, rx, ry, rz) of every node in the slave part follow the master node through a rigid transformation::

u_s = u_m + θ_m × (x_s − x_m)
θ_s = θ_m

Use this for genuinely rigid pieces (bearing blocks, lumped rigid masses) where the slave region must not deform.

Parameters

master_label : str Part, physical-group, or label name that contains (or whose proximity selects) the master node. slave_label : str Part, physical-group, or label name whose nodes are gathered into the rigid body. master_point : (x, y, z), default (0, 0, 0) Coordinates of the master node. as_element : bool, default False Emit the fork element LadrunoRigidBody over the whole node set {master, *slaves} (class tag 33015, 3D only) instead of the default rigidLink chain. The element gives a private centre-of-mass node, condensed body mass, and explicit-dynamics support that the rigidLink chain cannot. Fork-only: deck emission works on any build; running needs the Ladruno fork. mass : float or None Total body mass for as_element (-mass); None condenses it from the slaves' nodal mass. Only valid with as_element=True. omega : (wx, wy, wz) or None Initial body-frame angular velocity for as_element (-omega) — an explicit-dynamics initial condition (the body spins from t=0). Only valid with as_element=True. name : str, optional Friendly name.

Returns

RigidBodyDef

Raises

KeyError If either label is not in g.parts. ValueError If mass/omega is set without as_element=True, or mass < 0.

See Also

kinematic_coupling : Same topology but with a user-selectable DOF subset. rigid_diaphragm : In-plane variant with plane filtering.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def rigid_body(self, master_label, slave_label, *,
               master_point=(0., 0., 0.), as_element=False, mass=None,
               omega=None, name=None) -> RigidBodyDef:
    """Fully rigid cluster — every slave DOF follows the master.

    All six DOFs (``ux, uy, uz, rx, ry, rz``) of every node in
    the slave part follow the master node through a rigid
    transformation::

        u_s = u_m + θ_m × (x_s − x_m)
        θ_s = θ_m

    Use this for genuinely rigid pieces (bearing blocks, lumped
    rigid masses) where the slave region must not deform.

    Parameters
    ----------
    master_label : str
        Part, physical-group, or label name that contains (or whose
        proximity selects)
        the master node.
    slave_label : str
        Part, physical-group, or label name whose nodes are
        gathered into the rigid
        body.
    master_point : (x, y, z), default (0, 0, 0)
        Coordinates of the master node.
    as_element : bool, default False
        Emit the fork ``element LadrunoRigidBody`` over the whole node
        set ``{master, *slaves}`` (class tag 33015, **3D only**)
        instead of the default ``rigidLink`` chain. The element gives
        a private centre-of-mass node, condensed body mass, and
        explicit-dynamics support that the rigidLink chain cannot.
        Fork-only: deck emission works on any build; running needs the
        Ladruno fork.
    mass : float or None
        Total body mass for ``as_element`` (``-mass``); ``None``
        condenses it from the slaves' nodal mass. Only valid with
        ``as_element=True``.
    omega : (wx, wy, wz) or None
        Initial body-frame angular velocity for ``as_element``
        (``-omega``) — an explicit-dynamics initial condition (the body
        spins from t=0). Only valid with ``as_element=True``.
    name : str, optional
        Friendly name.

    Returns
    -------
    RigidBodyDef

    Raises
    ------
    KeyError
        If either label is not in ``g.parts``.
    ValueError
        If ``mass``/``omega`` is set without ``as_element=True``, or
        ``mass < 0``.

    See Also
    --------
    kinematic_coupling : Same topology but with a user-selectable
        DOF subset.
    rigid_diaphragm : In-plane variant with plane filtering.
    """
    return self._add_def(RigidBodyDef(
        master_label=master_label, slave_label=slave_label,
        master_point=master_point, as_element=as_element, mass=mass,
        omega=(None if omega is None else tuple(omega)), name=name))

kinematic_coupling

kinematic_coupling(master_label, slave_label, *, master_point=(0.0, 0.0, 0.0), dofs=None, k=None, k_alpha=None, host=None, kr=None, enforce='penalty', bipenalty_dtcr=None, bipenalty_wcap=None, absolute=False, name=None) -> KinematicCouplingDef

RBE2 / kinematic coupling — a reference node rigidly drives a node set.

Emits the Ladruno-fork element LadrunoKinematicCoupling (class tag 33012): a penalty rigid-body driver with the correct moment-arm transport u_i = u_R + θ_R × d_i, so an offset reference is coupled rigidly. This replaces the previous equalDOF-per-slave expansion, which ignored the lever arm (correct only for coincident nodes). Fork-only: the deck emits on any build, but running it needs the Ladruno fork — stock OpenSees fails loud at the element line (it does not know class tag 33012).

Reach for this when the region must move as a rigid body (a loading platen, a rigid offset / connection block, a rigid diaphragm over an arbitrary node set). To introduce a load at a point while the region stays flexible, use a distributing coupling (RBE3) instead.

Parameters

master_label : str | DecoupledNodeDef Part, physical-group, or label name that owns the reference (master) node — or a g.decouple_node handle / its label= (ADR 0049 OQ2). The reference node must carry the rotational DOFs (ndf 6 in 3D / 3 in 2D); the fork refuses a too-small reference at setDomain. slave_label : str | DecoupledNodeDef Part, physical-group, or label name whose nodes are slaved (may mix 3- and 6-DOF nodes). A g.decouple_node handle is accepted the same way as master_label. master_point : (x, y, z), default (0, 0, 0) Coordinates of the reference node when the master role resolves to a multi-node set (nearest-in-set). Ignored when the role is a single decoupled node — that node's own coordinates are used. dofs : list[int], optional 1-based dependent components tied on each slave (-dof). None (default) ties every DOF the slave has — the right choice for a mixed 3/6-DOF slave set; pass an explicit list to restrict, e.g. [1, 2, 3] for translations only or [3] for a vertical-only follower. k : float | "auto", optional Translational penalty stiffness (-k). None ⇒ the fork default (1e12). "auto" scales it off a representative host element's stiffness diagonal (K_t = k_alpha · max|K_host(i,i)|) — requires host. k_alpha : float, optional Multiplier for k="auto" (-kAlpha; fork default 1e3). Only valid together with k="auto". host : int, optional Representative host element for k="auto" / bipenalty_wcap (-host) as a FEM element id — the bridge translates it to the emitted OpenSees tag at emit time. Pick a typical element of the coupled part (e.g. one touching the slave surface). kr : float, optional Rotational penalty stiffness (-kr). None ⇒ fork-derived K_t·ℓ² (keeps the translation/rotation conditioning matched). enforce : "penalty" | "al", default "penalty" "al" = augmented Lagrangian (near-exact rigidity at moderate k; implicit only — cannot combine with the bipenalty knobs). bipenalty_dtcr : float, optional Explicit-dynamics critical-time-step target (-bipenalty -dtcr); lumps a penalty mass on any massless tied DOF so the stiff tie doesn't collapse the explicit step. None ⇒ off (the master is usually a massed node). bipenalty_wcap : float, optional Bipenalty via the host frequency (-bipenalty -wcap): m_p = K_t/(β·ω_host)² with β = this value — sets the penalty-mode frequency at β·ω_host instead of a hard dt budget. Requires host; mutually exclusive with bipenalty_dtcr. absolute : bool, default False Keep the absolute tie (-absolute) — skip the default g0 stress-free birth (a coupling added to a deformed model is otherwise born force-free). name : str, optional Friendly name (also the stage-claim key for s.kinematic_coupling).

Returns

KinematicCouplingDef

Raises

KeyError If either label is not in g.parts / PGs / labels and is not a labelled g.decouple_node. ValueError On an invalid knob (enforce not in {penalty, al}; non-positive k/kr/bipenalty_dtcr/bipenalty_wcap; al + a bipenalty knob; k="auto" or bipenalty_wcap without host; k_alpha without k="auto"; a dangling host no knob consumes; bipenalty_dtcr + bipenalty_wcap); a g.decouple_node handle without label=; a label that names both a decoupled node and a Part/PG; an ambiguous duplicate decoupled label.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def kinematic_coupling(self, master_label, slave_label, *,
                       master_point=(0., 0., 0.), dofs=None,
                       k=None, k_alpha=None, host=None,
                       kr=None, enforce="penalty",
                       bipenalty_dtcr=None, bipenalty_wcap=None,
                       absolute=False,
                       name=None) -> KinematicCouplingDef:
    """RBE2 / kinematic coupling — a reference node rigidly drives a
    node set.

    Emits the Ladruno-fork ``element LadrunoKinematicCoupling`` (class
    tag 33012): a penalty rigid-body driver with the correct moment-arm
    transport ``u_i = u_R + θ_R × d_i``, so an *offset* reference is
    coupled rigidly. This replaces the previous ``equalDOF``-per-slave
    expansion, which ignored the lever arm (correct only for coincident
    nodes). **Fork-only:** the deck emits on any build, but running it
    needs the Ladruno fork — stock OpenSees fails loud at the element
    line (it does not know class tag 33012).

    Reach for this when the region must move as a **rigid body** (a
    loading platen, a rigid offset / connection block, a rigid
    diaphragm over an arbitrary node set). To *introduce a load at a
    point while the region stays flexible*, use a distributing coupling
    (RBE3) instead.

    Parameters
    ----------
    master_label : str | DecoupledNodeDef
        Part, physical-group, or label name that owns the reference
        (master) node — **or** a ``g.decouple_node`` handle / its
        ``label=`` (ADR 0049 OQ2). The reference node must carry the
        rotational DOFs (ndf 6 in 3D / 3 in 2D); the fork refuses a
        too-small reference at ``setDomain``.
    slave_label : str | DecoupledNodeDef
        Part, physical-group, or label name whose nodes are slaved
        (may mix 3- and 6-DOF nodes). A ``g.decouple_node`` handle
        is accepted the same way as ``master_label``.
    master_point : (x, y, z), default (0, 0, 0)
        Coordinates of the reference node when the master role
        resolves to a multi-node set (nearest-in-set). **Ignored**
        when the role is a single decoupled node — that node's own
        coordinates are used.
    dofs : list[int], optional
        1-based dependent components tied on each slave (``-dof``).
        ``None`` (default) ties *every DOF the slave has* — the right
        choice for a mixed 3/6-DOF slave set; pass an explicit list to
        restrict, e.g. ``[1, 2, 3]`` for translations only or
        ``[3]`` for a vertical-only follower.
    k : float | ``"auto"``, optional
        Translational penalty stiffness (``-k``). ``None`` ⇒ the fork
        default (``1e12``). ``"auto"`` scales it off a representative
        host element's stiffness diagonal
        (``K_t = k_alpha · max|K_host(i,i)|``) — requires ``host``.
    k_alpha : float, optional
        Multiplier for ``k="auto"`` (``-kAlpha``; fork default ``1e3``).
        Only valid together with ``k="auto"``.
    host : int, optional
        Representative host element for ``k="auto"`` / ``bipenalty_wcap``
        (``-host``) as a **FEM element id** — the bridge translates it to
        the emitted OpenSees tag at emit time. Pick a typical element of
        the coupled part (e.g. one touching the slave surface).
    kr : float, optional
        Rotational penalty stiffness (``-kr``). ``None`` ⇒ fork-derived
        ``K_t·ℓ²`` (keeps the translation/rotation conditioning matched).
    enforce : ``"penalty"`` | ``"al"``, default ``"penalty"``
        ``"al"`` = augmented Lagrangian (near-exact rigidity at moderate
        ``k``; **implicit only** — cannot combine with the bipenalty
        knobs).
    bipenalty_dtcr : float, optional
        Explicit-dynamics critical-time-step target (``-bipenalty
        -dtcr``); lumps a penalty mass on any massless tied DOF so the
        stiff tie doesn't collapse the explicit step. ``None`` ⇒ off
        (the master is usually a massed node).
    bipenalty_wcap : float, optional
        Bipenalty via the host frequency (``-bipenalty -wcap``):
        ``m_p = K_t/(β·ω_host)²`` with ``β`` = this value — sets the
        penalty-mode frequency at ``β·ω_host`` instead of a hard ``dt``
        budget. Requires ``host``; mutually exclusive with
        ``bipenalty_dtcr``.
    absolute : bool, default False
        Keep the **absolute** tie (``-absolute``) — skip the default
        ``g0`` stress-free birth (a coupling added to a deformed model
        is otherwise born force-free).
    name : str, optional
        Friendly name (also the stage-claim key for ``s.kinematic_coupling``).

    Returns
    -------
    KinematicCouplingDef

    Raises
    ------
    KeyError
        If either label is not in ``g.parts`` / PGs / labels and is not
        a labelled ``g.decouple_node``.
    ValueError
        On an invalid knob (``enforce`` not in {penalty, al};
        non-positive ``k``/``kr``/``bipenalty_dtcr``/``bipenalty_wcap``;
        ``al`` + a bipenalty knob; ``k="auto"`` or ``bipenalty_wcap``
        without ``host``; ``k_alpha`` without ``k="auto"``; a dangling
        ``host`` no knob consumes; ``bipenalty_dtcr`` + ``bipenalty_wcap``);
        a ``g.decouple_node`` handle without ``label=``; a label that
        names both a decoupled node and a Part/PG; an ambiguous
        duplicate decoupled label.
    """
    master_label = _as_role_label(master_label, "master_label")
    slave_label = _as_role_label(slave_label, "slave_label")
    return self._add_def(KinematicCouplingDef(
        master_label=master_label, slave_label=slave_label,
        master_point=master_point, dofs=dofs,
        control=CouplingControl(
            k=k, k_alpha=k_alpha, host=host, kr=kr, enforce=enforce,
            bipenalty_dtcr=bipenalty_dtcr, bipenalty_wcap=bipenalty_wcap,
            absolute=absolute,
        ),
        name=name))

tie

tie(master_label, slave_label, *, master_entities=None, slave_entities=None, dofs=None, tolerance=1.0, stiffness='auto', stiffness_p=None, rotational=False, pressure=False, enforce='penalty', control=None, method='collocation', outward=None, name=None) -> TieDef

Non-matching mesh tie via shape-function interpolation.

For each slave node, the resolver finds the closest master element face, projects the node onto it, and constrains its DOFs to the master corner DOFs through that face's shape functions::

u_slave = Σ N_i(ξ, η) · u_master_i

where (ξ, η) are the projected parametric coordinates and N_i are the master face's shape functions (tri3, quad4, tri6, quad8 supported). This is what Abaqus *TIE does — it preserves displacement continuity across non-matching meshes.

Resolution emits one :class:~apeGmsh.mesh.records.InterpolationRecord per successfully projected slave node. The emitted OpenSees coupling depends on enforce= (see below): a penalty ASDEmbeddedNodeElement (default), the fork LadrunoEmbeddedNode, or an exact equationConstraint (EQ_Constraint).

Parameters

master_label : str Part, physical-group, or label name of the master surface (the side whose mesh will provide the shape functions). slave_label : str Part, physical-group, or label name of the slave surface (whose nodes are projected). master_entities : list of (dim, tag), optional Restrict the master surface to specific Gmsh entities. Strongly recommended when the master part has more than one face. slave_entities : list of (dim, tag), optional Restrict the slave surface to specific entities. dofs : list[int], optional DOFs to tie. None (default) ties all translational DOFs available — typically [1, 2, 3]. tolerance : float, default 1.0 Maximum allowed projection distance from a slave node to the master surface. Slave nodes farther than this are skipped with a warning (an all-skipped tie raises) — set generously if the two meshes have a small geometric gap, but not so large that the wrong face is selected. Unit-sensitive. stiffness : float or "auto", default "auto" Penalty stiffness K of the emitted ASDEmbeddedNodeElement (penalty routes only; ignored by "equation"). "auto" resolves at emit from the host material: K = α·E_host·L_char (α = 1e3, E from the element's material, L from the master-face size) — a few orders above the host element stiffness, which is all the penalty needs. A numeric value is unit-dependent and must be calibrated against a known solution: the pre-slice-B default 1e18 (the OpenSees C++ default) destroys the conditioning in N/mm/MPa (E ≈ 2e5) and Newton stalls, while 1e101e12 converge with sub-percent stiffness error; emit still warns when a record carries 1e18. stiffness_p : float, optional Separate rotational/pressure penalty (-KP); None ⇒ the element falls back to K. Same unit caveat. rotational, pressure : bool, default False Extend the coupling to rotational / pressure DOFs (-rot / -p); penalty routes only. enforce : {"penalty", "penalty_al", "equation"}, default "penalty" Coupling route (ADR 0068). "penalty"ASDEmbeddedNodeElement penalty element (tunable K, handler-independent). "equation" → exact equationConstraint (EQ_Constraint), translations only, enforced by the Lagrange (implicit) / LadrunoProjection (explicit, Δt-neutral) handler — auto-selected at emit, and penalty-only knobs (rotational/pressure/stiffness_p) are rejected. "penalty_al" → fork LadrunoEmbeddedNode (penalty + augmented-Lagrange + bipenalty, translations only), configured via control= (see below). control : CouplingControl, optional LadrunoEmbeddedNode penalty/AL/bipenalty knobs — only valid with enforce="penalty_al" (reuses the RBE2/RBE3 :class:CouplingControl: -k/-kAlpha/-host/ -enforce al/-bipenalty/-absolute). None ⇒ the fork element's own defaults. method : {"collocation", "mortar"}, default "collocation" Weight-computation method (ADR 0086). "collocation" is the classic node-to-face projection above. "mortar" integrates the interface over the slave/master facet overlaps with a dual (biorthogonal) slave basis, so neither side's interpolation order is imposed on the other — the fix for order-mismatched interfaces (e.g. hex20 faces tied onto hex8 faces, where collocation over-constrains the quadratic side). Requires enforce="equation" (v1), works on composed assemblies (chain phase), and is fail-loud end to end: a flat, coincident, convex interface is required and every degenerate case raises MortarTieError — a mortar tie never silently resolves to nothing. tolerance becomes the out-of-plane coincidence tolerance. Interface edges must be straight (every midside node at its edge midpoint) and no master facet may overlap another — both are hard errors, because the kernel integrates on the corner polygon and its coverage check counts multiplicity. tri6 SLAVE facets are refused (dual-basis degeneracy) — swap the sides or use collocation. outward : (ox, oy, oz), optional method="mortar" only: interface-plane normal override. Normally derived from master facet winding; needed only when the winding sum cancels (the kernel raises naming this knob — there is no silent zero-force path). name : str, optional Friendly name.

Returns

TieDef

Raises

KeyError If either label is not in g.parts.

See Also

equal_dof : Conformal-mesh equivalent (no interpolation). tied_contact : Bidirectional surface-to-surface tie. mortar : Deprecated alias for a fork mortar mesh-tie (contact(formulation="mortar", tie=True)).

Notes

Master/slave choice matters for accuracy. As a rule:

  • The master should have the finer mesh (more shape functions to project onto).
  • The slave should have the coarser mesh (fewer projection operations).
Examples

Shell-to-solid tie at a column-top interface::

g.constraints.tie(
    "shell_floor", "solid_column",
    master_entities=[(2, 17)],     # column top face
    slave_entities=[(2, 41)],      # shell bottom face
    tolerance=5.0,                 # mm gap
)
Source code in src/apeGmsh/core/ConstraintsComposite.py
def tie(self, master_label, slave_label, *, master_entities=None,
        slave_entities=None, dofs=None, tolerance=1.0,
        stiffness="auto", stiffness_p=None,
        rotational=False, pressure=False,
        enforce="penalty", control=None,
        method="collocation", outward=None,
        name=None) -> TieDef:
    """Non-matching mesh tie via shape-function interpolation.

    For each slave node, the resolver finds the closest master
    element face, projects the node onto it, and constrains its
    DOFs to the master corner DOFs through that face's shape
    functions::

        u_slave = Σ N_i(ξ, η) · u_master_i

    where ``(ξ, η)`` are the projected parametric coordinates
    and ``N_i`` are the master face's shape functions (tri3,
    quad4, tri6, quad8 supported). This is what Abaqus
    ``*TIE`` does — it preserves displacement continuity across
    non-matching meshes.

    Resolution emits one
    :class:`~apeGmsh.mesh.records.InterpolationRecord` per
    successfully projected slave node. The emitted OpenSees coupling
    depends on ``enforce=`` (see below): a penalty
    ``ASDEmbeddedNodeElement`` (default), the fork
    ``LadrunoEmbeddedNode``, or an exact ``equationConstraint``
    (EQ_Constraint).

    Parameters
    ----------
    master_label : str
        Part, physical-group, or label name of the master surface
        (the side whose mesh
        will provide the shape functions).
    slave_label : str
        Part, physical-group, or label name of the slave surface
        (whose nodes are
        projected).
    master_entities : list of (dim, tag), optional
        Restrict the master surface to specific Gmsh
        entities. **Strongly recommended** when the master
        part has more than one face.
    slave_entities : list of (dim, tag), optional
        Restrict the slave surface to specific entities.
    dofs : list[int], optional
        DOFs to tie. ``None`` (default) ties all translational
        DOFs available — typically ``[1, 2, 3]``.
    tolerance : float, default 1.0
        Maximum allowed projection distance from a slave node
        to the master surface. Slave nodes farther than this
        are skipped with a warning (an all-skipped tie raises) —
        set generously if the two meshes have a small geometric
        gap, but not so large that the wrong face is selected.
        **Unit-sensitive.**
    stiffness : float or ``"auto"``, default ``"auto"``
        Penalty stiffness ``K`` of the emitted
        ``ASDEmbeddedNodeElement`` (penalty routes only; ignored by
        ``"equation"``). ``"auto"`` resolves at emit from the host
        material: ``K = α·E_host·L_char`` (α = 1e3, E from the
        element's material, L from the master-face size) — a few
        orders above the host element stiffness, which is all the
        penalty needs. **A numeric value is unit-dependent and must
        be calibrated against a known solution**: the pre-slice-B
        default ``1e18`` (the OpenSees C++ default) destroys the
        conditioning in N/mm/MPa (E ≈ 2e5) and Newton stalls, while
        ``1e10``–``1e12`` converge with sub-percent stiffness
        error; emit still warns when a record carries 1e18.
    stiffness_p : float, optional
        Separate rotational/pressure penalty (``-KP``); ``None`` ⇒
        the element falls back to ``K``. Same unit caveat.
    rotational, pressure : bool, default False
        Extend the coupling to rotational / pressure DOFs
        (``-rot`` / ``-p``); penalty routes only.
    enforce : {"penalty", "penalty_al", "equation"}, default "penalty"
        Coupling route (ADR 0068). ``"penalty"`` →
        ``ASDEmbeddedNodeElement`` penalty element (tunable ``K``,
        handler-independent). ``"equation"`` → exact
        ``equationConstraint`` (EQ_Constraint), translations only,
        enforced by the ``Lagrange`` (implicit) / ``LadrunoProjection``
        (explicit, Δt-neutral) handler — auto-selected at emit, and
        penalty-only knobs (``rotational``/``pressure``/``stiffness_p``)
        are rejected. ``"penalty_al"`` → fork ``LadrunoEmbeddedNode``
        (penalty + augmented-Lagrange + bipenalty, translations only),
        configured via ``control=`` (see below).
    control : CouplingControl, optional
        LadrunoEmbeddedNode penalty/AL/bipenalty knobs — only valid with
        ``enforce="penalty_al"`` (reuses the RBE2/RBE3
        :class:`CouplingControl`: ``-k``/``-kAlpha``/``-host``/
        ``-enforce al``/``-bipenalty``/``-absolute``). ``None`` ⇒ the
        fork element's own defaults.
    method : {"collocation", "mortar"}, default "collocation"
        Weight-computation method (ADR 0086). ``"collocation"`` is
        the classic node-to-face projection above. ``"mortar"``
        integrates the interface over the slave/master facet
        overlaps with a dual (biorthogonal) slave basis, so
        **neither side's interpolation order is imposed on the
        other** — the fix for order-mismatched interfaces (e.g.
        hex20 faces tied onto hex8 faces, where collocation
        over-constrains the quadratic side). Requires
        ``enforce="equation"`` (v1), works on composed assemblies
        (chain phase), and is fail-loud end to end: a flat,
        coincident, convex interface is required and every
        degenerate case raises ``MortarTieError`` — a mortar tie
        never silently resolves to nothing. ``tolerance`` becomes
        the out-of-plane coincidence tolerance. Interface edges must
        be straight (every midside node at its edge midpoint) and no
        master facet may overlap another — both are hard errors,
        because the kernel integrates on the corner polygon and its
        coverage check counts multiplicity. tri6 SLAVE facets are
        refused (dual-basis degeneracy) — swap the sides or use
        collocation.
    outward : (ox, oy, oz), optional
        ``method="mortar"`` only: interface-plane normal override.
        Normally derived from master facet winding; needed only
        when the winding sum cancels (the kernel raises naming
        this knob — there is no silent zero-force path).
    name : str, optional
        Friendly name.

    Returns
    -------
    TieDef

    Raises
    ------
    KeyError
        If either label is not in ``g.parts``.

    See Also
    --------
    equal_dof : Conformal-mesh equivalent (no interpolation).
    tied_contact : Bidirectional surface-to-surface tie.
    mortar : Deprecated alias for a fork mortar mesh-tie
        (``contact(formulation="mortar", tie=True)``).

    Notes
    -----
    Master/slave choice matters for accuracy. As a rule:

    * The master should have the **finer** mesh (more shape
      functions to project onto).
    * The slave should have the **coarser** mesh (fewer
      projection operations).

    Examples
    --------
    Shell-to-solid tie at a column-top interface::

        g.constraints.tie(
            "shell_floor", "solid_column",
            master_entities=[(2, 17)],     # column top face
            slave_entities=[(2, 41)],      # shell bottom face
            tolerance=5.0,                 # mm gap
        )
    """
    return self._add_def(TieDef(
        master_label=master_label, slave_label=slave_label,
        master_entities=master_entities, slave_entities=slave_entities,
        dofs=dofs, tolerance=tolerance, name=name,
        stiffness=stiffness, stiffness_p=stiffness_p,
        rotational=rotational, pressure=pressure, enforce=enforce,
        control=control, method=method, outward=outward))

distributing_coupling

distributing_coupling(master_label, slave_label, *, master_point=(0.0, 0.0, 0.0), weighting='uniform', k=None, k_alpha=None, host=None, kr=None, enforce='penalty', bipenalty_dtcr=None, bipenalty_wcap=None, absolute=False, name=None) -> DistributingCouplingDef

RBE3 / distributing coupling — distribute a load at a reference point over a node set while the set stays flexible.

Emits the Ladruno-fork element LadrunoDistributingCoupling (class tag 33011): the reference (dependent) node R is the weighted-average rigid-body fit of the independent set, and a force/moment at R is distributed to the set as a statically-equivalent pattern (Σ Fᵢ = F, Σ rᵢ × Fᵢ = M) adding no stiffness to the independents. This is the proper RBE3 — it replaces the prior NotImplementedError stub (whose predecessor emitted a mechanically-wrong kinematic mean). It is the flexible counterpart of :meth:kinematic_coupling (RBE2, which holds the set rigid). Fork-only: the deck emits on any build, but running it needs the Ladruno fork — stock OpenSees fails loud at the element line (it does not know class tag 33011).

Reach for this to introduce/transmit a load or BC at a point while the region stays flexible (a column base on a footing, an actuator head on a face, a beam/shell moment into a solid face); use :meth:kinematic_coupling (RBE2) when the region must move as a rigid body, or :meth:tie for a compatible face interpolation.

Parameters

master_label : str | DecoupledNodeDef Part, physical-group, or label name owning the reference (dependent) node R — or a g.decouple_node handle / its label= (ADR 0049 OQ2). R must carry the rotational DOFs (ndf 6 in 3D / 3 in 2D) to transmit a moment; the fork refuses a too-small reference at setDomain. slave_label : str | DecoupledNodeDef Part, physical-group, or label name whose nodes form the independent set (translations-only is fine — no rotational stiffness is injected). A g.decouple_node handle is accepted the same way as master_label. master_point : (x, y, z), default (0, 0, 0) Coordinates of the reference node R when the master role resolves to a multi-node set (nearest-in-set). Ignored when the role is a single decoupled node — that node's own coordinates are used. weighting : "uniform" | "area", default "uniform" "uniform" ⇒ equal weights (-w omitted, the fork element's default). "area" ⇒ apeGmsh computes each independent node's tributary area over the slave surface (each face's area split equally among its nodes — the same lumping model as g.loads surface-tributary resolution) and emits -w w1..wN, so a force at R distributes like a uniform traction on the surface. Requires the slave label (or slave_entities) to resolve to meshed surface faces; an independent node on no slave face fails loud. k : float | "auto", optional Translational penalty stiffness (-k). None ⇒ the fork default (1e12). "auto" scales it off a representative host element's stiffness diagonal (K_t = k_alpha · max|K_host(i,i)|) — requires host. Note the force distribution is exact for any penalty (the RBE3 property); k only relaxes the kinematic fit of the reference node. k_alpha : float, optional Multiplier for k="auto" (-kAlpha; fork default 1e3). Only valid together with k="auto". host : int, optional Representative host element for k="auto" / bipenalty_wcap (-host) as a FEM element id — the bridge translates it to the emitted OpenSees tag at emit time. RBE3 has no single host by construction; name ONE typical element among the independents' parents — it is read ONLY to scale the penalties. kr : float, optional Rotational penalty stiffness (-kr). None ⇒ fork-derived. enforce : "penalty" | "al", default "penalty" "al" = augmented Lagrangian — recovers a near-exact weighted fit of R at moderate k (implicit only; cannot combine with the bipenalty knobs). bipenalty_dtcr : float, optional Explicit-dynamics critical-time-step target (-bipenalty -dtcr). The reference node is massless by construction, so an explicit run needs this (or it has a zero stable step). None ⇒ off. bipenalty_wcap : float, optional Bipenalty via the host frequency (-bipenalty -wcap): m_p = K_t/(β·ω_host)² with β = this value. Requires host; mutually exclusive with bipenalty_dtcr. absolute : bool, default False Keep the absolute tie (-absolute) — skip the default g0 stress-free birth. name : str, optional Friendly name (also the stage-claim key for s.distributing).

Returns

DistributingCouplingDef

Raises

ValueError On an invalid knob (enforce not in {penalty, al}; non-positive k/kr/bipenalty_dtcr/bipenalty_wcap; al + a bipenalty knob; k="auto" or bipenalty_wcap without host; k_alpha without k="auto"; a dangling host no knob consumes; bipenalty_dtcr + bipenalty_wcap; weighting not in {uniform, area}); a g.decouple_node handle without label=; a label that names both a decoupled node and a Part/PG; an ambiguous duplicate decoupled label.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def distributing_coupling(self, master_label, slave_label, *,
                          master_point=(0., 0., 0.),
                          weighting="uniform",
                          k=None, k_alpha=None, host=None,
                          kr=None, enforce="penalty",
                          bipenalty_dtcr=None, bipenalty_wcap=None,
                          absolute=False,
                          name=None) -> DistributingCouplingDef:
    """RBE3 / distributing coupling — distribute a load at a reference
    point over a node set while the set stays flexible.

    Emits the Ladruno-fork ``element LadrunoDistributingCoupling``
    (class tag 33011): the reference (dependent) node R is the
    weighted-average rigid-body fit of the independent set, and a
    force/moment at R is distributed to the set as a
    statically-equivalent pattern (``Σ Fᵢ = F``, ``Σ rᵢ × Fᵢ = M``)
    **adding no stiffness** to the independents. This is the proper
    RBE3 — it replaces the prior `NotImplementedError` stub (whose
    predecessor emitted a mechanically-wrong kinematic mean). It is
    the flexible counterpart of :meth:`kinematic_coupling` (RBE2,
    which holds the set rigid). **Fork-only:** the deck emits on any
    build, but running it needs the Ladruno fork — stock OpenSees
    fails loud at the element line (it does not know class tag 33011).

    Reach for this to **introduce/transmit a load or BC at a point
    while the region stays flexible** (a column base on a footing, an
    actuator head on a face, a beam/shell moment into a solid face);
    use :meth:`kinematic_coupling` (RBE2) when the region must move as
    a rigid body, or :meth:`tie` for a compatible face interpolation.

    Parameters
    ----------
    master_label : str | DecoupledNodeDef
        Part, physical-group, or label name owning the reference
        (dependent) node R — **or** a ``g.decouple_node`` handle / its
        ``label=`` (ADR 0049 OQ2). R must carry the rotational DOFs
        (ndf 6 in 3D / 3 in 2D) to transmit a moment; the fork refuses
        a too-small reference at ``setDomain``.
    slave_label : str | DecoupledNodeDef
        Part, physical-group, or label name whose nodes form the
        **independent** set (translations-only is fine — no rotational
        stiffness is injected). A ``g.decouple_node`` handle is
        accepted the same way as ``master_label``.
    master_point : (x, y, z), default (0, 0, 0)
        Coordinates of the reference node R when the master role
        resolves to a multi-node set (nearest-in-set). **Ignored**
        when the role is a single decoupled node — that node's own
        coordinates are used.
    weighting : ``"uniform"`` | ``"area"``, default ``"uniform"``
        ``"uniform"`` ⇒ equal weights (``-w`` omitted, the fork
        element's default). ``"area"`` ⇒ apeGmsh computes each
        independent node's **tributary area** over the slave
        surface (each face's area split equally among its nodes —
        the same lumping model as ``g.loads`` surface-tributary
        resolution) and emits ``-w w1..wN``, so a force at R
        distributes like a uniform traction on the surface.
        Requires the slave label (or ``slave_entities``) to resolve
        to meshed surface faces; an independent node on no slave
        face fails loud.
    k : float | ``"auto"``, optional
        Translational penalty stiffness (``-k``). ``None`` ⇒ the fork
        default (``1e12``). ``"auto"`` scales it off a representative
        host element's stiffness diagonal
        (``K_t = k_alpha · max|K_host(i,i)|``) — requires ``host``.
        Note the **force distribution is exact for any penalty** (the
        RBE3 property); ``k`` only relaxes the *kinematic* fit of the
        reference node.
    k_alpha : float, optional
        Multiplier for ``k="auto"`` (``-kAlpha``; fork default ``1e3``).
        Only valid together with ``k="auto"``.
    host : int, optional
        Representative host element for ``k="auto"`` / ``bipenalty_wcap``
        (``-host``) as a **FEM element id** — the bridge translates it to
        the emitted OpenSees tag at emit time. RBE3 has no single host
        by construction; name ONE typical element among the independents'
        parents — it is read ONLY to scale the penalties.
    kr : float, optional
        Rotational penalty stiffness (``-kr``). ``None`` ⇒ fork-derived.
    enforce : ``"penalty"`` | ``"al"``, default ``"penalty"``
        ``"al"`` = augmented Lagrangian — recovers a near-exact weighted
        fit of R at moderate ``k`` (**implicit only**; cannot combine
        with the bipenalty knobs).
    bipenalty_dtcr : float, optional
        Explicit-dynamics critical-time-step target (``-bipenalty
        -dtcr``). The reference node is **massless** by construction, so
        an explicit run needs this (or it has a zero stable step).
        ``None`` ⇒ off.
    bipenalty_wcap : float, optional
        Bipenalty via the host frequency (``-bipenalty -wcap``):
        ``m_p = K_t/(β·ω_host)²`` with ``β`` = this value. Requires
        ``host``; mutually exclusive with ``bipenalty_dtcr``.
    absolute : bool, default False
        Keep the **absolute** tie (``-absolute``) — skip the default
        ``g0`` stress-free birth.
    name : str, optional
        Friendly name (also the stage-claim key for `s.distributing`).

    Returns
    -------
    DistributingCouplingDef

    Raises
    ------
    ValueError
        On an invalid knob (``enforce`` not in {penalty, al};
        non-positive ``k``/``kr``/``bipenalty_dtcr``/``bipenalty_wcap``;
        ``al`` + a bipenalty knob; ``k="auto"`` or ``bipenalty_wcap``
        without ``host``; ``k_alpha`` without ``k="auto"``; a dangling
        ``host`` no knob consumes; ``bipenalty_dtcr`` + ``bipenalty_wcap``;
        ``weighting`` not in {uniform, area}); a ``g.decouple_node``
        handle without ``label=``; a label that names both a
        decoupled node and a Part/PG; an ambiguous duplicate
        decoupled label.
    """
    if weighting not in ("uniform", "area"):
        raise ValueError(
            "distributing_coupling: weighting must be 'uniform' (equal "
            "weights) or 'area' (tributary-area -w weights computed over "
            f"the slave surface), got {weighting!r}."
        )
    master_label = _as_role_label(master_label, "master_label")
    slave_label = _as_role_label(slave_label, "slave_label")
    return self._add_def(DistributingCouplingDef(
        master_label=master_label, slave_label=slave_label,
        master_point=master_point, weighting=weighting,
        control=CouplingControl(
            k=k, k_alpha=k_alpha, host=host, kr=kr, enforce=enforce,
            bipenalty_dtcr=bipenalty_dtcr, bipenalty_wcap=bipenalty_wcap,
            absolute=absolute,
        ),
        name=name))

embedded

embedded(host_label, embedded_label, *, tolerance=1.0, host_entities=None, embedded_entities=None, stiffness='auto', stiffness_p=None, rotational=False, pressure=False, host_coupling='linear', name=None) -> EmbeddedDef

Embed lower-dimensional elements inside a host volume or surface.

Each node of the embedded part is constrained to the displacement field of the host element it falls inside via host shape functions. Used for rebar in concrete, stiffeners in shells, fibres in composite hosts, etc.

Supported host element types:

  • 3-D host: tet4 (etype 4), tet10 (11), hex8 (5), hex20 (17), prism6 (6), prism15 (18), pyramid5 (7), pyramid13 (14).
  • 2-D host: tri3 / CST (etype 2), tri6 / LST (9), quad4 (3), quad8 (16), quad9 (10).

Non-simplex and higher-order hosts are decomposed to linear sub-tris / sub-tets using corner nodes only (hex8 → 6 Kuhn tets; prism6 → 3 tets; pyramid5 → 2 tets; quad4 → 2 tris on the (0,2) diagonal; tri6 / tet10 / hex20 / quad8 / quad9 / prism15 / pyramid13 → corner-only). The embedded coupling is therefore linear regardless of the host's native interpolation order — see host_coupling and :class:EmbeddedDef for the full contract. A UserWarning fires once per (host type, entity) the first time a midside-bearing host is decomposed.

The resolver automatically drops embedded nodes that coincide with host element corners, since those are already rigidly attached through shared connectivity.

Parameters

host_label : str Part label whose host elements form the embedding field. Stored internally as master_label. embedded_label : str Part label whose nodes are embedded. Stored as slave_label. (Label validation is bypassed for EmbeddedDef — these labels may also be physical group names if no part registry is in use.) tolerance : float, default 1.0 Maximum dimensionless barycentric excess allowed when locating an embedded node inside a host sub-element. 0.0 means strictly inside; the default 1.0 preserves pre-Phase-2 permissive behaviour. See :class:EmbeddedDef for the fail-loud gate. stiffness : float or "auto", default "auto" Penalty stiffness K of the emitted ASDEmbeddedNodeElement. "auto" resolves at emit from the host material (K = α·E_host·L_char, α = 1e3). A numeric value is unit-dependent and must be calibrated against a known solution — the pre-slice-B default 1e18 (the OpenSees C++ default) stalls Newton in N/mm/MPa models while 1e101e12 converge; emit still warns when a record carries 1e18. (Unlike :meth:tie, embedded has no enforce="equation" escape hatch — the fork g.embed is the conditioned alternative.) stiffness_p : float, optional Separate rotational/pressure penalty (-KP); None ⇒ falls back to K. Same unit caveat. host_entities, embedded_entities : list of (dim, tag), optional Restrict the host / embedded sides to specific Gmsh entities. When omitted the whole label is used. host_coupling : {"linear"}, default "linear" Reserved keyword pinning the coupling kinematics. Only "linear" is currently accepted (coupling to 3 or 4 corner nodes via barycentric shape functions, matching ASDEmbeddedNodeElement). Reserved so that future higher-order options ("trilinear", "biquadratic") can be added without breaking old models. name : str, optional Friendly name.

Returns

EmbeddedDef

Notes

Emitted downstream as ASDEmbeddedNodeElement. The host_label / embedded_label argument names mirror Abaqus's *EMBEDDED ELEMENT vocabulary; internally the composite still stores them as master/slave for consistency with the rest of the constraint records.

Examples

Rebar curve embedded inside a concrete tet mesh::

g.constraints.embedded(
    host_label="concrete_block",
    embedded_label="rebar_curve",
    tolerance=2.0,        # mm
)

Same rebar embedded into a hex8 mesh (each rebar node is located inside one of the 6 Kuhn sub-tets of the enclosing hex and coupled to that sub-tet's 4 corners)::

g.constraints.embedded(
    host_label="concrete_block_hex",
    embedded_label="rebar_curve",
)
Source code in src/apeGmsh/core/ConstraintsComposite.py
def embedded(self, host_label, embedded_label, *, tolerance=1.0,
             host_entities=None, embedded_entities=None,
             stiffness="auto", stiffness_p=None,
             rotational=False, pressure=False,
             host_coupling="linear",
             name=None) -> EmbeddedDef:
    """Embed lower-dimensional elements inside a host volume or
    surface.

    Each node of the embedded part is constrained to the
    displacement field of the host element it falls inside via
    host shape functions. Used for **rebar in concrete**,
    stiffeners in shells, fibres in composite hosts, etc.

    Supported host element types:

    * **3-D host:** tet4 (etype 4), tet10 (11), hex8 (5),
      hex20 (17), prism6 (6), prism15 (18), pyramid5 (7),
      pyramid13 (14).
    * **2-D host:** tri3 / CST (etype 2), tri6 / LST (9),
      quad4 (3), quad8 (16), quad9 (10).

    Non-simplex and higher-order hosts are decomposed to
    linear sub-tris / sub-tets using corner nodes only (hex8
    → 6 Kuhn tets; prism6 → 3 tets; pyramid5 → 2 tets;
    quad4 → 2 tris on the (0,2) diagonal; tri6 / tet10 /
    hex20 / quad8 / quad9 / prism15 / pyramid13 →
    corner-only).  The embedded coupling is therefore
    **linear** regardless of the host's native interpolation
    order — see ``host_coupling`` and :class:`EmbeddedDef`
    for the full contract.  A ``UserWarning`` fires once per
    (host type, entity) the first time a midside-bearing host
    is decomposed.

    The resolver automatically drops embedded nodes that
    coincide with host element corners, since those are
    already rigidly attached through shared connectivity.

    Parameters
    ----------
    host_label : str
        Part label whose host elements form the embedding
        field.  Stored internally as ``master_label``.
    embedded_label : str
        Part label whose nodes are embedded. Stored as
        ``slave_label``. (Label validation is bypassed for
        ``EmbeddedDef`` — these labels may also be physical
        group names if no part registry is in use.)
    tolerance : float, default 1.0
        Maximum dimensionless barycentric excess allowed when
        locating an embedded node inside a host sub-element.
        ``0.0`` means strictly inside; the default ``1.0``
        preserves pre-Phase-2 permissive behaviour.  See
        :class:`EmbeddedDef` for the fail-loud gate.
    stiffness : float or ``"auto"``, default ``"auto"``
        Penalty stiffness ``K`` of the emitted
        ``ASDEmbeddedNodeElement``. ``"auto"`` resolves at emit
        from the host material (``K = α·E_host·L_char``, α = 1e3).
        **A numeric value is unit-dependent and must be calibrated
        against a known solution** — the pre-slice-B default
        ``1e18`` (the OpenSees C++ default) stalls Newton in
        N/mm/MPa models while ``1e10``–``1e12`` converge; emit
        still warns when a record carries 1e18. (Unlike
        :meth:`tie`, ``embedded`` has no ``enforce="equation"``
        escape hatch — the fork ``g.embed`` is the conditioned
        alternative.)
    stiffness_p : float, optional
        Separate rotational/pressure penalty (``-KP``); ``None`` ⇒
        falls back to ``K``. Same unit caveat.
    host_entities, embedded_entities : list of (dim, tag), optional
        Restrict the host / embedded sides to specific Gmsh
        entities.  When omitted the whole label is used.
    host_coupling : {"linear"}, default ``"linear"``
        Reserved keyword pinning the coupling kinematics.  Only
        ``"linear"`` is currently accepted (coupling to 3 or 4
        corner nodes via barycentric shape functions, matching
        ``ASDEmbeddedNodeElement``).  Reserved so that future
        higher-order options (``"trilinear"``, ``"biquadratic"``)
        can be added without breaking old models.
    name : str, optional
        Friendly name.

    Returns
    -------
    EmbeddedDef

    Notes
    -----
    Emitted downstream as ``ASDEmbeddedNodeElement``. The
    ``host_label`` / ``embedded_label`` argument names mirror
    Abaqus's ``*EMBEDDED ELEMENT`` vocabulary; internally the
    composite still stores them as ``master``/``slave`` for
    consistency with the rest of the constraint records.

    Examples
    --------
    Rebar curve embedded inside a concrete tet mesh::

        g.constraints.embedded(
            host_label="concrete_block",
            embedded_label="rebar_curve",
            tolerance=2.0,        # mm
        )

    Same rebar embedded into a hex8 mesh (each rebar node is
    located inside one of the 6 Kuhn sub-tets of the
    enclosing hex and coupled to that sub-tet's 4 corners)::

        g.constraints.embedded(
            host_label="concrete_block_hex",
            embedded_label="rebar_curve",
        )
    """
    return self._add_def(EmbeddedDef(
        master_label=host_label, slave_label=embedded_label,
        tolerance=tolerance, host_entities=host_entities,
        embedded_entities=embedded_entities, name=name,
        stiffness=stiffness, stiffness_p=stiffness_p,
        rotational=rotational, pressure=pressure,
        host_coupling=host_coupling))

node_to_surface

node_to_surface(master, slave, *, dofs=None, tolerance=1e-06, name=None)

6-DOF node to 3-DOF surface coupling via phantom nodes.

Creates a single constraint that aggregates all surface entities in slave. Shared-edge mesh nodes are deduplicated so each original slave node gets exactly one phantom.

Parameters

master : int, str, or (dim, tag) The 6-DOF reference node. slave : int, str, or (dim, tag) The surface(s) to couple. If it resolves to multiple surface entities, they are combined into a single constraint and slave nodes are deduplicated.

Returns

NodeToSurfaceDef A single def covering all resolved surface entities.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def node_to_surface(self, master, slave, *,
                    dofs=None, tolerance=1e-6,
                    name=None):
    """6-DOF node to 3-DOF surface coupling via phantom nodes.

    Creates a single constraint that aggregates all surface
    entities in *slave*.  Shared-edge mesh nodes are deduplicated
    so each original slave node gets exactly one phantom.

    Parameters
    ----------
    master : int, str, or (dim, tag)
        The 6-DOF reference node.
    slave : int, str, or (dim, tag)
        The surface(s) to couple.  If it resolves to multiple
        surface entities, they are combined into a single
        constraint and slave nodes are deduplicated.

    Returns
    -------
    NodeToSurfaceDef
        A single def covering all resolved surface entities.
    """
    from ._helpers import resolve_to_tags
    m_tags = resolve_to_tags(master, dim=0, session=self._parent)
    s_tags = resolve_to_tags(slave,  dim=2, session=self._parent)
    if len(m_tags) != 1:
        raise ValueError(
            f"node_to_surface master {master!r} resolved to "
            f"{len(m_tags)} dim-0 entities {m_tags} — the master "
            f"must identify exactly one reference point.")
    if not s_tags:
        raise ValueError(
            f"node_to_surface slave {slave!r} resolved to no "
            f"dim-2 surface entities.")
    master_tag = m_tags[0]

    if name is None:
        m_name = str(master) if isinstance(master, str) else str(master_tag)
        s_name = str(slave) if isinstance(slave, str) else "surface"
        display_name = f"{m_name}{s_name}"
    else:
        display_name = name

    # Store ALL surface tags as a comma-separated string so the
    # resolver can union their slave nodes and deduplicate.
    slave_label = ",".join(str(int(t)) for t in s_tags)

    return self._add_def(NodeToSurfaceDef(
        master_label=str(master_tag),
        slave_label=slave_label,
        dofs=dofs, tolerance=tolerance,
        name=display_name))

node_to_surface_spring

node_to_surface_spring(master, slave, *, dofs=None, tolerance=1e-06, name=None)

Spring-based variant of :meth:node_to_surface.

Identical topology and call signature, but the master → phantom links are tagged for downstream emission as stiff elasticBeamColumn elements instead of kinematic rigidLink('beam', ...) constraints. Use this variant when the master carries free rotational DOFs (fork support on a solid end face) that receive direct moment loading — the constraint-based variant of node_to_surface can produce an ill-conditioned reduced stiffness matrix in that case because the master rotation DOFs get stiffness only through the kinematic constraint back-propagation, with nothing attaching directly to them.

See :class:~apeGmsh.solvers.Constraints.NodeToSurfaceSpringDef for the full rationale.

Emission in OpenSees::

# Each master → phantom link becomes a stiff beam element
next_eid = max_tet_eid + 1
for master, slaves in fem.nodes.constraints.stiff_beam_groups():
    for phantom in slaves:
        ops.element(
            'elasticBeamColumn', next_eid,
            master, phantom,
            A_big, E, I_big, I_big, J_big, transf_tag,
        )
        next_eid += 1

# equalDOFs are unchanged from the normal variant
for pair in fem.nodes.constraints.equal_dofs():
    ops.equalDOF(
        pair.master_node, pair.slave_node, *pair.dofs)
Parameters

Same as :meth:node_to_surface.

Returns

NodeToSurfaceSpringDef

Source code in src/apeGmsh/core/ConstraintsComposite.py
def node_to_surface_spring(self, master, slave, *,
                           dofs=None, tolerance=1e-6,
                           name=None):
    """Spring-based variant of :meth:`node_to_surface`.

    Identical topology and call signature, but the master → phantom
    links are tagged for downstream emission as stiff
    ``elasticBeamColumn`` elements instead of kinematic
    ``rigidLink('beam', ...)`` constraints. Use this variant when
    the master carries **free rotational DOFs** (fork support on a
    solid end face) that receive direct moment loading — the
    constraint-based variant of ``node_to_surface`` can produce an
    ill-conditioned reduced stiffness matrix in that case because
    the master rotation DOFs get stiffness only through the
    kinematic constraint back-propagation, with nothing attaching
    directly to them.

    See :class:`~apeGmsh.solvers.Constraints.NodeToSurfaceSpringDef`
    for the full rationale.

    Emission in OpenSees::

        # Each master → phantom link becomes a stiff beam element
        next_eid = max_tet_eid + 1
        for master, slaves in fem.nodes.constraints.stiff_beam_groups():
            for phantom in slaves:
                ops.element(
                    'elasticBeamColumn', next_eid,
                    master, phantom,
                    A_big, E, I_big, I_big, J_big, transf_tag,
                )
                next_eid += 1

        # equalDOFs are unchanged from the normal variant
        for pair in fem.nodes.constraints.equal_dofs():
            ops.equalDOF(
                pair.master_node, pair.slave_node, *pair.dofs)

    Parameters
    ----------
    Same as :meth:`node_to_surface`.

    Returns
    -------
    NodeToSurfaceSpringDef
    """
    from ._helpers import resolve_to_tags
    m_tags = resolve_to_tags(master, dim=0, session=self._parent)
    s_tags = resolve_to_tags(slave,  dim=2, session=self._parent)
    if len(m_tags) != 1:
        raise ValueError(
            f"node_to_surface_spring master {master!r} resolved "
            f"to {len(m_tags)} dim-0 entities {m_tags} — the "
            f"master must identify exactly one reference point.")
    if not s_tags:
        raise ValueError(
            f"node_to_surface_spring slave {slave!r} resolved to "
            f"no dim-2 surface entities.")
    master_tag = m_tags[0]

    if name is None:
        m_name = str(master) if isinstance(master, str) else str(master_tag)
        s_name = str(slave) if isinstance(slave, str) else "surface"
        display_name = f"{m_name} \u2192 {s_name} (spring)"
    else:
        display_name = name

    slave_label = ",".join(str(int(t)) for t in s_tags)

    return self._add_def(NodeToSurfaceSpringDef(
        master_label=str(master_tag),
        slave_label=slave_label,
        dofs=dofs, tolerance=tolerance,
        name=display_name))

tied_contact

tied_contact(master_label, slave_label, *, master_entities=None, slave_entities=None, dofs=None, tolerance=1.0, stiffness='auto', stiffness_p=None, rotational=False, pressure=False, enforce='penalty', control=None, name=None) -> TiedContactDef

Full surface-to-surface tie (slave conforms to master).

Every slave-surface node is tied to the master surface via shape-function interpolation. One-directional: an earlier bidirectional variant (also projecting master nodes onto slave faces) was removed because it produced cyclic / over-determined MPCs the constraint handler cannot satisfy. Pick the finer mesh as the master.

enforce= selects the coupling route exactly as in :meth:tie ("penalty" default → ASDEmbeddedNodeElement; "equation" → exact equationConstraint; "penalty_al"LadrunoEmbeddedNode).

Resolution emits :class:~apeGmsh.solvers.Constraints.SurfaceCouplingRecord objects on fem.elements.constraints.

Parameters

master_label : str Part label of the first surface. slave_label : str Part label of the second surface. master_entities, slave_entities : list of (dim, tag), optional Restrict each side to specific Gmsh entities. dofs : list[int], optional DOFs to tie. None = all translational. tolerance : float, default 1.0 Maximum projection distance. Unit-sensitive. stiffness : float or "auto", default "auto" Penalty stiffness K of each emitted ASDEmbeddedNodeElement (penalty routes only). "auto" resolves at emit from the host material — see :meth:tie for the formula and the numeric-value caveat (a fixed number is unit-dependent; the old 1e18 default stalls Newton in N/mm/MPa and still warns at emit). stiffness_p : float, optional Separate rotational/pressure penalty (-KP); None ⇒ falls back to K. enforce : {"penalty", "penalty_al", "equation"}, default "penalty" Coupling route (ADR 0068) — same semantics as :meth:tie; "equation" emits exact equationConstraint rows and rejects the penalty-only knobs. name : str, optional Friendly name.

Returns

TiedContactDef

Raises

KeyError If either label is not in g.parts.

See Also

tie : One-directional tie (slave-projected only). mortar : Deprecated alias for a fork mortar mesh-tie (contact(formulation="mortar", tie=True)).

Source code in src/apeGmsh/core/ConstraintsComposite.py
def tied_contact(self, master_label, slave_label, *,
                 master_entities=None, slave_entities=None,
                 dofs=None, tolerance=1.0,
                 stiffness="auto", stiffness_p=None,
                 rotational=False, pressure=False,
                 enforce="penalty", control=None,
                 name=None) -> TiedContactDef:
    """Full surface-to-surface tie (slave conforms to master).

    Every slave-surface node is tied to the master surface via
    shape-function interpolation. **One-directional**: an earlier
    bidirectional variant (also projecting master nodes onto slave
    faces) was removed because it produced cyclic / over-determined
    MPCs the constraint handler cannot satisfy. Pick the **finer**
    mesh as the master.

    ``enforce=`` selects the coupling route exactly as in :meth:`tie`
    (``"penalty"`` default → ``ASDEmbeddedNodeElement``; ``"equation"``
    → exact ``equationConstraint``; ``"penalty_al"`` →
    ``LadrunoEmbeddedNode``).

    Resolution emits
    :class:`~apeGmsh.solvers.Constraints.SurfaceCouplingRecord`
    objects on ``fem.elements.constraints``.

    Parameters
    ----------
    master_label : str
        Part label of the first surface.
    slave_label : str
        Part label of the second surface.
    master_entities, slave_entities : list of (dim, tag), optional
        Restrict each side to specific Gmsh entities.
    dofs : list[int], optional
        DOFs to tie. ``None`` = all translational.
    tolerance : float, default 1.0
        Maximum projection distance. **Unit-sensitive.**
    stiffness : float or ``"auto"``, default ``"auto"``
        Penalty stiffness ``K`` of each emitted
        ``ASDEmbeddedNodeElement`` (penalty routes only).
        ``"auto"`` resolves at emit from the host material — see
        :meth:`tie` for the formula and the numeric-value caveat
        (a fixed number is unit-dependent; the old ``1e18`` default
        stalls Newton in N/mm/MPa and still warns at emit).
    stiffness_p : float, optional
        Separate rotational/pressure penalty (``-KP``); ``None`` ⇒
        falls back to ``K``.
    enforce : {"penalty", "penalty_al", "equation"}, default "penalty"
        Coupling route (ADR 0068) — same semantics as :meth:`tie`;
        ``"equation"`` emits exact ``equationConstraint`` rows and
        rejects the penalty-only knobs.
    name : str, optional
        Friendly name.

    Returns
    -------
    TiedContactDef

    Raises
    ------
    KeyError
        If either label is not in ``g.parts``.

    See Also
    --------
    tie : One-directional tie (slave-projected only).
    mortar : Deprecated alias for a fork mortar mesh-tie
        (``contact(formulation="mortar", tie=True)``).
    """
    return self._add_def(TiedContactDef(
        master_label=master_label, slave_label=slave_label,
        master_entities=master_entities, slave_entities=slave_entities,
        dofs=dofs, tolerance=tolerance, name=name,
        stiffness=stiffness, stiffness_p=stiffness_p,
        rotational=rotational, pressure=pressure, enforce=enforce,
        control=control))

mortar

mortar(master_label, slave_label, *, eps_n='auto', outward, master_entities=None, slave_entities=None, name=None) -> ContactDef

Deprecated alias for a fork segment-to-segment mortar mesh-tie.

.. deprecated:: mortar() is a thin convenience alias for :meth:contact with formulation="mortar", tie=True; call that directly. It emits a :class:DeprecationWarning.

Delegates to the fork's ALM-penalty mortar mesh-tie (ADR 0073): a permanent segment-to-segment bond (the zero-gap limit — the full 3-vector residual driven to zero, no friction). Returns a :class:ContactDef resolving to fem.elements.contacts (the fork contactSurface + contact -mortar -tie pair + the LadrunoContact handler), not the old MortarDef / Lagrange-multiplier path. Fork-only at run time; deck emission works on any build.

This is a breaking change from the prior stub (which raised NotImplementedError): the return type is now ContactDef, the semantics are an ALM penalty contact-tie (not a Lagrange-multiplier operator), and the never-functional dofs / integration_order parameters are removed (a permanent penalty tie bonds the full 3-vector with a single penalty and has no DOF-subset or quadrature-order knob — passing them now raises TypeError).

Parameters

master_label, slave_label : str The two surface PG / part labels to bond. Both resolve to faceted surfaces (master -master, slave -slave-segments); pick the finer mesh as whichever side you trust more — the fork integrates the overlap either way. eps_n : float | "auto", default "auto" ALM normal penalty for the tie ("auto" sizes it from the solid). outward : (float, float, float) Required. The master surface normal toward the slave. A tie interface is coincident-flat, so without an explicit sign the fork's per-pair reference is in-plane and gate H2 silently drops every pair to zero force (the tie would bond nothing). See :class:ContactDef. master_entities, slave_entities : list of (dim, tag), optional Restrict each side to specific Gmsh entities. name : str, optional Friendly name (round-trips into the emitted deck comment).

Returns

ContactDef

See Also

contact : The canonical fork contact / mortar-tie generator. tied_contact : Collocation-based non-matching tie (no fork required).

Source code in src/apeGmsh/core/ConstraintsComposite.py
def mortar(self, master_label, slave_label, *,
           eps_n="auto", outward,
           master_entities=None, slave_entities=None,
           name=None) -> ContactDef:
    """Deprecated alias for a fork segment-to-segment mortar mesh-tie.

    .. deprecated::
       ``mortar()`` is a thin convenience alias for
       :meth:`contact` with ``formulation="mortar", tie=True``; call
       that directly. It emits a :class:`DeprecationWarning`.

    Delegates to the fork's ALM-penalty mortar **mesh-tie** (ADR 0073):
    a permanent segment-to-segment bond (the zero-gap limit — the full
    3-vector residual driven to zero, no friction). Returns a
    :class:`ContactDef` resolving to ``fem.elements.contacts`` (the fork
    ``contactSurface`` + ``contact -mortar -tie`` pair + the
    ``LadrunoContact`` handler), **not** the old ``MortarDef`` /
    Lagrange-multiplier path. Fork-only at run time; deck emission works on
    any build.

    This is a **breaking** change from the prior stub (which raised
    ``NotImplementedError``): the return type is now ``ContactDef``, the
    semantics are an ALM penalty contact-tie (not a Lagrange-multiplier
    operator), and the never-functional ``dofs`` / ``integration_order``
    parameters are removed (a permanent penalty tie bonds the full
    3-vector with a single penalty and has no DOF-subset or quadrature-order
    knob — passing them now raises ``TypeError``).

    Parameters
    ----------
    master_label, slave_label : str
        The two surface PG / part labels to bond. Both resolve to faceted
        surfaces (master ``-master``, slave ``-slave-segments``); pick the
        finer mesh as whichever side you trust more — the fork integrates
        the overlap either way.
    eps_n : float | "auto", default "auto"
        ALM normal penalty for the tie (``"auto"`` sizes it from the solid).
    outward : (float, float, float)
        **Required.** The master surface normal toward the slave. A tie
        interface is coincident-flat, so without an explicit sign the fork's
        per-pair reference is in-plane and gate H2 silently drops every pair
        to zero force (the tie would bond nothing). See :class:`ContactDef`.
    master_entities, slave_entities : list of (dim, tag), optional
        Restrict each side to specific Gmsh entities.
    name : str, optional
        Friendly name (round-trips into the emitted deck comment).

    Returns
    -------
    ContactDef

    See Also
    --------
    contact : The canonical fork contact / mortar-tie generator.
    tied_contact : Collocation-based non-matching tie (no fork required).
    """
    import warnings
    warnings.warn(
        "g.constraints.mortar() is a deprecated alias for "
        "g.constraints.contact(formulation='mortar', tie=True, ...); "
        "call contact() directly. mortar() now delegates to the fork "
        "ALM-penalty mortar mesh-tie (returns a ContactDef, not the old "
        "MortarDef Lagrange path) — see ADR 0073.",
        DeprecationWarning, stacklevel=2,
    )
    return self.contact(
        master_label, slave_label,
        formulation="mortar", tie=True,
        eps_n=eps_n, outward=outward,
        master_entities=master_entities, slave_entities=slave_entities,
        name=name,
    )

validate_pre_mesh

validate_pre_mesh() -> None

No-op: constraints validate targets eagerly at _add_def.

Present so :meth:Mesh.generate can invoke validate_pre_mesh on all three composites uniformly.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def validate_pre_mesh(self) -> None:
    """No-op: constraints validate targets eagerly at ``_add_def``.

    Present so :meth:`Mesh.generate` can invoke ``validate_pre_mesh``
    on all three composites uniformly.
    """
    return None

summary

summary()

DataFrame of the declared constraint intent — one row per def.

Columns: kind, name, master, slave, params. params is a short stringified view of the kind-specific fields (dofs, tolerance, etc.).

Source code in src/apeGmsh/core/ConstraintsComposite.py
def summary(self):
    """DataFrame of the declared constraint intent — one row per def.

    Columns: ``kind, name, master, slave, params``.  ``params`` is a
    short stringified view of the kind-specific fields (``dofs``,
    ``tolerance``, etc.).
    """
    import pandas as pd
    from dataclasses import fields

    _COMMON = {"kind", "name", "master_label", "slave_label"}

    rows: list[dict] = []
    for d in self.constraint_defs:
        params = {
            f.name: getattr(d, f.name)
            for f in fields(d)
            if f.name not in _COMMON
        }
        params = {k: v for k, v in params.items() if v is not None}
        rows.append({
            "kind"  : d.kind,
            "name"  : d.name or "",
            "master": d.master_label,
            "slave" : d.slave_label,
            "params": ", ".join(f"{k}={v}" for k, v in params.items()),
        })

    cols = ["kind", "name", "master", "slave", "params"]
    if not rows:
        return pd.DataFrame(columns=cols)
    return pd.DataFrame(rows, columns=cols)

NormalLaw dataclass

NormalLaw(kind: str, k_per_area: float, tau_b_n: float | None = None, gap: float | None = None)

Declarative per-area normal-direction law (ADR 0093 D1).

A flat-scalar description of the interface's normal constitutive response — stored on :class:InterfaceRecord (h5-serializable), translated to a typed uniaxial material only at emit time in build.py, scaled per pair by A_trib. Kernel data — imports nothing from apeGmsh.opensees (INV-4). The sign convention is owned by the emit-time translation, never the caller (INV-1): the fields here are positive-magnitude physical quantities.

Attributes

kind "ent" — unilateral, compression-only (ENT(E = k_per_area * A_trib)). "epp_gap" — elastic-perfectly-plastic with a gap (ElasticPPGap(E = k_per_area * A_trib, Fy = -tau_b_n * A_trib, gap)); requires tau_b_n and gap. "elastic" — bilateral elastic (Elastic(E = k_per_area * A_trib)); the acceptance battery's bonded-limit law (ADR 0093 "Alternatives rejected"). k_per_area Stiffness per unit tributary area ([F/L**3]); required for every kind. tau_b_n Normal bond strength, a positive magnitude (epp_gap only); None for ent / elastic. gap Initial gap, <= 0 (epp_gap only); None for ent / elastic.

TangentialLaw dataclass

TangentialLaw(kind: str, k_per_area: float, tau_b: float | None = None)

Declarative per-area tangential-direction law (ADR 0093 D1).

The tangential sibling of :class:NormalLaw — see its docstring for the storage/translation/layering contract.

Attributes

kind "epp" — elastic-perfectly-plastic slip cap (ElasticPP(E = k_per_area * A_trib, epsyP = tau_b / k_per_area)); requires tau_b. A_trib cancels in the strain — the physical yield force tau_b * A_trib is the emergent product E * epsyP. "elastic" — bilateral elastic (Elastic(E = k_per_area * A_trib)); the acceptance battery's bonded-limit law. k_per_area Stiffness per unit tributary area ([F/L**3]); required for every kind. tau_b Tangential bond strength, a positive magnitude (epp only); None for elastic.

FEMData

FEMData(nodes: NodeComposite, elements: ElementComposite, info: MeshInfo, mesh_selection: 'MeshSelectionStore | None' = None, composed_from: 'ComposeSet | tuple[ComposeRecord, ...] | None' = None)

Solver-ready FEM mesh broker.

Organized by what the user needs::

fem.nodes       → NodeComposite
fem.elements    → ElementComposite
fem.info        → MeshInfo
fem.inspect     → InspectComposite
Source code in src/apeGmsh/mesh/FEMData.py
def __init__(
    self,
    nodes: NodeComposite,
    elements: ElementComposite,
    info: MeshInfo,
    mesh_selection: "MeshSelectionStore | None" = None,
    composed_from: "ComposeSet | tuple[ComposeRecord, ...] | None" = None,
) -> None:
    self.nodes    = nodes
    self.elements = elements
    self.info     = info
    self.mesh_selection = mesh_selection
    self.inspect  = InspectComposite(self)
    # ── Compose provenance (Phase 3A.1 / ADR 0038) ───────────
    # ``fem.composed_from`` is a :class:`ComposeSet` exposing one
    # record per composed source module (label-keyed, sorted).
    # Default is an empty set — the canonical "uncomposed" signal.
    # Phase 3B's ``Compose`` facade is the producer; the H5 reader
    # rehydrates it from the optional ``/composed_from/`` sub-group
    # when present.
    if composed_from is None:
        self.composed_from: ComposeSet = ComposeSet(())
    elif isinstance(composed_from, ComposeSet):
        self.composed_from = composed_from
    else:
        self.composed_from = ComposeSet(tuple(composed_from))
    # Wire the sibling NodeComposite onto the ElementComposite so
    # fem.elements.select(...) can compute element centroids
    # in-memory (no live Gmsh session needed — works for
    # import-origin FEMData too). Every construction path funnels
    # through this __init__, so one wiring line covers from_gmsh /
    # from_msh / from_h5 / from_native / from_mpco / direct. The
    # attribute name is the contract shared with
    # mesh/_mesh_selection.NODES_REF_ATTR.
    elements._apegmsh_nodes_ref = nodes

    # ── Partitions composite ─────────────────────────────
    # ``fem.partitions`` is a :class:`PartitionSet` (P2 broker
    # composite) built once from the same dicts the extractor
    # already populated on ``nodes._partitions`` /
    # ``elements._partitions``.  Those private back-stores are
    # left untouched — they still power ``select(partition=N)``;
    # this set is a Python-side ergonomic layer only.
    node_parts: dict[int, dict] = getattr(nodes, "_partitions", {}) or {}
    elem_parts: dict[int, dict] = (
        getattr(elements, "_partitions", {}) or {})
    pids = sorted(set(node_parts.keys()) | set(elem_parts.keys()))
    records: dict[int, PartitionRecord] = {}
    empty_i64 = np.array([], dtype=np.int64)
    for pid in pids:
        n_ids = np.asarray(
            node_parts.get(pid, {}).get("node_ids", empty_i64),
            dtype=np.int64,
        )
        e_ids = np.asarray(
            elem_parts.get(pid, {}).get("element_ids", empty_i64),
            dtype=np.int64,
        )
        records[int(pid)] = PartitionRecord(
            id=int(pid), node_ids=n_ids, element_ids=e_ids,
        )
    self.partitions: PartitionSet = PartitionSet(records)

snapshot_id property

snapshot_id: str

Deterministic content hash identifying this FEMData snapshot.

Computed once and cached. Used by the Results module to bind result files to their producing geometry — see internal_docs/Results_architecture.md § "FEMData embedding & binding".

from_gmsh classmethod

from_gmsh(dim: int | None = None, *, session=None, ndf: int = 6, remove_orphans: bool = False)

Extract FEMData from a live Gmsh session.

Parameters

dim : int or None Element dimension to extract. None = all dims. session : apeGmsh session, optional When provided, auto-resolves constraints, loads, masses. ndf : int DOFs per node for load/mass vector padding. remove_orphans : bool If True, remove mesh nodes not connected to any element.

Source code in src/apeGmsh/mesh/FEMData.py
@classmethod
def from_gmsh(
    cls,
    dim: int | None = None,
    *,
    session=None,
    ndf: int = 6,
    remove_orphans: bool = False,
):
    """Extract FEMData from a live Gmsh session.

    Parameters
    ----------
    dim : int or None
        Element dimension to extract.  ``None`` = all dims.
    session : apeGmsh session, optional
        When provided, auto-resolves constraints, loads, masses.
    ndf : int
        DOFs per node for load/mass vector padding.
    remove_orphans : bool
        If True, remove mesh nodes not connected to any element.
    """
    from ._fem_factory import _from_gmsh
    return _from_gmsh(
        cls, dim=dim, session=session, ndf=ndf,
        remove_orphans=remove_orphans)

from_msh classmethod

from_msh(path: str, dim: int | None = 2, *, remove_orphans: bool = False)

Load FEMData from an external .msh file.

Source code in src/apeGmsh/mesh/FEMData.py
@classmethod
def from_msh(
    cls,
    path: str,
    dim: int | None = 2,
    *,
    remove_orphans: bool = False,
):
    """Load FEMData from an external ``.msh`` file."""
    from ._fem_factory import _from_msh
    return _from_msh(cls, path=path, dim=dim,
                     remove_orphans=remove_orphans)

from_h5 classmethod

from_h5(path: str, *, root: str = '/') -> 'FEMData'

Load a :class:FEMData snapshot from a root-layout model.h5.

Inverse of :meth:to_h5. Reads the seven neutral-zone groups plus /meta and rebuilds nodes, elements (per type), physical groups, labels, mesh selections, constraints, loads, and masses — everything the writer round-trips.

Parameters

path : str Path to a model.h5 written by :meth:to_h5, g.save(), or apeSees(fem).h5(path). root : str, default "/" Sub-group root inside path to read from. Default rehydrates from the file root (standalone model.h5 shape). Per ADR 0020 (Phase 4 cleanup), composed results.h5 files carry the same rich layout under /model/; pass root="/model" to rehydrate from a composed file. Backcompat: root="/" produces byte-identical behaviour to the pre-refactor reader.

Use this to resume a session-saved model in a later script::

# script 1 — build & save
with apeGmsh(model_name="m", save_to="m.h5") as g:
    ...

# script 2 — analyse
fem = FEMData.from_h5("m.h5")
apeSees(fem).h5("m.h5")     # enrich with /opensees/...
Source code in src/apeGmsh/mesh/FEMData.py
@classmethod
def from_h5(cls, path: str, *, root: str = "/") -> "FEMData":
    """Load a :class:`FEMData` snapshot from a root-layout ``model.h5``.

    Inverse of :meth:`to_h5`.  Reads the seven neutral-zone groups
    plus ``/meta`` and rebuilds nodes, elements (per type),
    physical groups, labels, mesh selections, constraints, loads,
    and masses — everything the writer round-trips.

    Parameters
    ----------
    path : str
        Path to a model.h5 written by :meth:`to_h5`, ``g.save()``,
        or ``apeSees(fem).h5(path)``.
    root : str, default ``"/"``
        Sub-group root inside ``path`` to read from.  Default
        rehydrates from the file root (standalone ``model.h5``
        shape).  Per ADR 0020 (Phase 4 cleanup), composed
        ``results.h5`` files carry the same rich layout under
        ``/model/``; pass ``root="/model"`` to rehydrate from a
        composed file.  Backcompat: ``root="/"`` produces
        byte-identical behaviour to the pre-refactor reader.

    Use this to resume a session-saved model in a later script::

        # script 1 — build & save
        with apeGmsh(model_name="m", save_to="m.h5") as g:
            ...

        # script 2 — analyse
        fem = FEMData.from_h5("m.h5")
        apeSees(fem).h5("m.h5")     # enrich with /opensees/...
    """
    from ._femdata_h5_io import read_fem_h5
    return read_fem_h5(path, root=root)

to_native_h5

to_native_h5(group) -> None

Embed this FEMData into an open HDF5 group (/model/).

Used by NativeWriter to snapshot the geometry alongside results. The reconstructed FEMData (via from_native_h5) will produce the same snapshot_id — this is the linking contract for Results.bind().

Phase 4 cleanup (ADR 0020): writes the rich neutral-zone layout :func:write_fem_h5 produces at the file root, but under group instead. The composed results.h5 thus carries /model/meta, /model/nodes, /model/elements, etc. — the same layout :func:read_fem_h5(path, root="/model") rehydrates from. This eliminates the /opensees_archive/ zone that the previous lean embedding required to round-trip the full :class:OpenSeesModel.

Source code in src/apeGmsh/mesh/FEMData.py
def to_native_h5(self, group) -> None:
    """Embed this FEMData into an open HDF5 group (``/model/``).

    Used by ``NativeWriter`` to snapshot the geometry alongside
    results.  The reconstructed FEMData (via ``from_native_h5``)
    will produce the same ``snapshot_id`` — this is the linking
    contract for ``Results.bind()``.

    Phase 4 cleanup (ADR 0020): writes the rich neutral-zone
    layout :func:`write_fem_h5` produces at the file root, but
    under ``group`` instead.  The composed ``results.h5`` thus
    carries ``/model/meta``, ``/model/nodes``, ``/model/elements``,
    etc. — the same layout :func:`read_fem_h5(path, root="/model")`
    rehydrates from.  This eliminates the ``/opensees_archive/``
    zone that the previous lean embedding required to round-trip
    the full :class:`OpenSeesModel`.
    """
    from ._femdata_h5_io import write_neutral_zone_into_group
    write_neutral_zone_into_group(self, group)

to_h5

to_h5(path: str, *, model_name: str = '', apegmsh_version: str = '', ndf: int = 0) -> None

Write a fresh model.h5 containing the neutral zone.

Phase 8.5 entry point: dumps everything the broker knows about the model (nodes, elements per type, physical groups, labels, constraints, loads, masses) into a root-level model.h5. No /opensees/ content is emitted — absent enrichment is the right "no solver loaded" signal.

Use apeSees(fem).h5(path) instead to get a fully enriched file (neutral zone + /opensees/...).

Source code in src/apeGmsh/mesh/FEMData.py
def to_h5(
    self,
    path: str,
    *,
    model_name: str = "",
    apegmsh_version: str = "",
    ndf: int = 0,
) -> None:
    """Write a fresh ``model.h5`` containing the neutral zone.

    Phase 8.5 entry point: dumps everything the broker knows about
    the model (nodes, elements per type, physical groups, labels,
    constraints, loads, masses) into a root-level
    ``model.h5``.  No ``/opensees/`` content is emitted — absent
    enrichment is the right "no solver loaded" signal.

    Use ``apeSees(fem).h5(path)`` instead to get a fully enriched
    file (neutral zone + ``/opensees/...``).
    """
    # g.reinforce (ADR 20 / R2b → ADR 0067 P5.1): LadrunoEmbeddedRebar
    # ties now round-trip through the neutral model.h5 (persisted into the
    # /reinforce_ties group, neutral schema 2.15.0). No deferral warning.
    #
    # ADR 0067 P5.2 / B1a.2: the cage's auto-emitted structural rebar
    # elements (g.rebar.place(emit_elements=True)) now round-trip through
    # the neutral model.h5 (persisted into the /rebar_elements group,
    # neutral schema 2.16.0). No deferral warning.
    from ._femdata_h5_io import write_fem_h5
    write_fem_h5(
        self, path,
        model_name=model_name,
        apegmsh_version=apegmsh_version,
        ndf=ndf,
    )

from_native_h5 classmethod

from_native_h5(group) -> 'FEMData'

Reconstruct a FEMData from its embedded /model/ group.

Phase 4 cleanup (ADR 0020): production writers (:meth:to_native_h5 via :class:NativeWriter) embed the rich neutral zone — full constraints, loads, masses, mesh selections and partitions round-trip alongside nodes/elements/PGs. snapshot_id of the rebuilt FEM matches the source's /meta/snapshot_id attribute (the linking contract :class:Results.bind relies on).

Source code in src/apeGmsh/mesh/FEMData.py
@classmethod
def from_native_h5(cls, group) -> "FEMData":
    """Reconstruct a FEMData from its embedded ``/model/`` group.

    Phase 4 cleanup (ADR 0020): production writers (:meth:`to_native_h5`
    via :class:`NativeWriter`) embed the rich neutral zone — full
    constraints, loads, masses, mesh selections and partitions
    round-trip alongside nodes/elements/PGs.  ``snapshot_id`` of
    the rebuilt FEM matches the source's ``/meta/snapshot_id``
    attribute (the linking contract :class:`Results.bind` relies
    on).
    """
    from ._femdata_h5_io import read_neutral_zone_from_group

    return read_neutral_zone_from_group(
        group, label=getattr(group, "name", "<h5 group>"),
    )

from_mpco_model classmethod

from_mpco_model(group) -> 'FEMData'

Synthesize a partial FEMData from an MPCO MODEL/ group.

Carries: nodes, elements (per OpenSees class tag), physical groups derived from MPCO Regions (MODEL/SETS).

Missing vs. native: - apeGmsh-specific labels - Pre-mesh declarations (loads / masses / constraints) - STKO named selection sets (those live in .cdata sidecars) - Gmsh-style element type codes (uses negated class_tag instead)

snapshot_id will not match a native FEMData of the same mesh — that's expected. Results.bind() will refuse such mismatches.

Source code in src/apeGmsh/mesh/FEMData.py
@classmethod
def from_mpco_model(cls, group) -> "FEMData":
    """Synthesize a partial FEMData from an MPCO ``MODEL/`` group.

    Carries: nodes, elements (per OpenSees class tag), physical
    groups derived from MPCO Regions (``MODEL/SETS``).

    Missing vs. native:
    - apeGmsh-specific ``labels``
    - Pre-mesh declarations (loads / masses / constraints)
    - STKO named selection sets (those live in ``.cdata`` sidecars)
    - Gmsh-style element type codes (uses negated class_tag instead)

    ``snapshot_id`` will not match a native FEMData of the same
    mesh — that's expected. ``Results.bind()`` will refuse such
    mismatches.
    """
    from ._femdata_mpco_io import read_fem_from_mpco
    return read_fem_from_mpco(group)

from_ladruno_model classmethod

from_ladruno_model(group) -> 'FEMData'

Synthesize a partial FEMData from a .ladruno MODEL/ group.

Sibling of :meth:from_mpco_model for the self-describing .ladruno layout (element groups carry a CONNECTIVITY dataset + BASIS attrs). Carries nodes, elements (per OpenSees class tag), and physical groups from MODEL/SETS. Missing vs. native: apeGmsh labels, pre-mesh declarations, selection-set names. snapshot_id will not match a native FEMData of the same mesh — expected.

Source code in src/apeGmsh/mesh/FEMData.py
@classmethod
def from_ladruno_model(cls, group) -> "FEMData":
    """Synthesize a partial FEMData from a ``.ladruno`` ``MODEL/`` group.

    Sibling of :meth:`from_mpco_model` for the self-describing
    ``.ladruno`` layout (element groups carry a ``CONNECTIVITY``
    dataset + BASIS attrs). Carries nodes, elements (per OpenSees
    class tag), and physical groups from ``MODEL/SETS``. Missing vs.
    native: apeGmsh ``labels``, pre-mesh declarations, selection-set
    names. ``snapshot_id`` will not match a native FEMData of the
    same mesh — expected.
    """
    from ._femdata_ladruno_io import read_fem_from_ladruno
    return read_fem_from_ladruno(group)

with_constraint

with_constraint(record) -> 'FEMData'

Return a new :class:FEMData with record appended.

Pure transform. self is unchanged. Dispatch is by record type:

===================================== ================================= Record subclass Appended to ===================================== ================================= NodePairRecord nodes.constraints NodeGroupRecord nodes.constraints NodeToSurfaceRecord nodes.constraints InterpolationRecord elements.constraints SurfaceCouplingRecord elements.constraints SPRecord nodes.sp ===================================== =================================

Routing an unknown record subclass raises TypeError — this is a fail-loud contract because the compose engine needs every record to land in a known broker bucket.

Source code in src/apeGmsh/mesh/FEMData.py
def with_constraint(self, record) -> "FEMData":
    """Return a new :class:`FEMData` with ``record`` appended.

    Pure transform.  ``self`` is unchanged.  Dispatch is by record
    type:

    =====================================  =================================
    Record subclass                        Appended to
    =====================================  =================================
    ``NodePairRecord``                     ``nodes.constraints``
    ``NodeGroupRecord``                    ``nodes.constraints``
    ``NodeToSurfaceRecord``                ``nodes.constraints``
    ``InterpolationRecord``                ``elements.constraints``
    ``SurfaceCouplingRecord``              ``elements.constraints``
    ``SPRecord``                           ``nodes.sp``
    =====================================  =================================

    Routing an unknown record subclass raises ``TypeError`` — this
    is a fail-loud contract because the compose engine needs every
    record to land in a known broker bucket.
    """
    # Imports are deferred so callers using only ``with_load`` /
    # ``with_mass`` don't pay the cost.
    from .._kernel.records._constraints import (
        NodePairRecord, NodeGroupRecord, NodeToSurfaceRecord,
        InterpolationRecord, SurfaceCouplingRecord,
    )
    from .._kernel.records._loads import SPRecord

    if isinstance(record, (NodePairRecord, NodeGroupRecord,
                           NodeToSurfaceRecord)):
        new_set = self.nodes.constraints._with_record(record)
        return self._replaced(
            nodes=self._replaced_nodes(constraints=new_set))
    if isinstance(record, (InterpolationRecord, SurfaceCouplingRecord)):
        new_set = self.elements.constraints._with_record(record)
        return self._replaced(
            elements=self._replaced_elements(constraints=new_set))
    if isinstance(record, SPRecord):
        new_set = self.nodes.sp._with_record(record)
        return self._replaced(
            nodes=self._replaced_nodes(sp=new_set))
    raise TypeError(
        f"FEMData.with_constraint: unsupported record type "
        f"{type(record).__name__!r} — expected a ConstraintRecord "
        f"subclass or SPRecord."
    )

with_load

with_load(record) -> 'FEMData'

Return a new :class:FEMData with record appended.

Pure transform. self is unchanged. Dispatch is by record type:

===================================== ================================= Record subclass Appended to ===================================== ================================= NodalLoadRecord nodes.loads ElementLoadRecord elements.loads SPRecord nodes.sp ===================================== =================================

Source code in src/apeGmsh/mesh/FEMData.py
def with_load(self, record) -> "FEMData":
    """Return a new :class:`FEMData` with ``record`` appended.

    Pure transform.  ``self`` is unchanged.  Dispatch is by record
    type:

    =====================================  =================================
    Record subclass                        Appended to
    =====================================  =================================
    ``NodalLoadRecord``                    ``nodes.loads``
    ``ElementLoadRecord``                  ``elements.loads``
    ``SPRecord``                           ``nodes.sp``
    =====================================  =================================
    """
    from .._kernel.records._loads import (
        NodalLoadRecord, ElementLoadRecord, SPRecord,
    )

    if isinstance(record, NodalLoadRecord):
        new_set = self.nodes.loads._with_record(record)
        return self._replaced(
            nodes=self._replaced_nodes(loads=new_set))
    if isinstance(record, ElementLoadRecord):
        new_set = self.elements.loads._with_record(record)
        return self._replaced(
            elements=self._replaced_elements(loads=new_set))
    if isinstance(record, SPRecord):
        new_set = self.nodes.sp._with_record(record)
        return self._replaced(
            nodes=self._replaced_nodes(sp=new_set))
    raise TypeError(
        f"FEMData.with_load: unsupported record type "
        f"{type(record).__name__!r} — expected NodalLoadRecord, "
        f"ElementLoadRecord, or SPRecord."
    )

compose

compose(source: 'str | Path', *, label: str, translate: tuple[float, float, float] = (0.0, 0.0, 0.0), rotate: tuple[float, float, float, float] | None = None, anchor: str | None = None, partition_rank: int | None = None, properties: 'dict | None' = None, compose_size_per_module: int | None = None, max_compose_depth: int | None = None) -> 'FEMData'

Return a new :class:FEMData extending this chain with a composed module.

Pure transformation. self is unchanged. The returned FEMData's composed_from chain is self.composed_from + (new_record,) and every IMPORT-verdict record from the source H5 surfaces on the result, namespaced with label and offset into a non-overlapping tag window per ADR 0038 §"Tag-offset scheme".

Geometry / mesh build-phase operations are not part of this primitive — the merge runs entirely against the FEMData broker; no live Gmsh state is touched. The compose API is the canonical entry point for cross-session composition: FEMData.from_h5(path).compose("module.h5", label="A").

Drift hazard: the returned FEMData is decoupled from any live gmsh state on the producing session. Mutating the session's mesh/PG/label/parts AFTER calling compose without also re-extracting + re-applying the bundle drops the composed module's records on the floor. The :meth:apeGmsh.compose shim handles this via session-level bundle-replay; if you call this primitive directly, replay is your responsibility.

See :func:apeGmsh.mesh._compose.Compose.compose for the full parameter contract; max_compose_depth is the only Compose.compose parameter intentionally absent here (depth checks come in Phase 3E.1).

Source code in src/apeGmsh/mesh/FEMData.py
def compose(
    self,
    source: "str | Path",
    *,
    label: str,
    translate: tuple[float, float, float] = (0.0, 0.0, 0.0),
    rotate: tuple[float, float, float, float] | None = None,
    anchor: str | None = None,
    partition_rank: int | None = None,
    properties: "dict | None" = None,
    compose_size_per_module: int | None = None,
    max_compose_depth: int | None = None,
) -> "FEMData":
    """Return a new :class:`FEMData` extending this chain with a
    composed module.

    Pure transformation. ``self`` is unchanged.  The returned
    FEMData's ``composed_from`` chain is
    ``self.composed_from + (new_record,)`` and every IMPORT-verdict
    record from the source H5 surfaces on the result, namespaced
    with ``label`` and offset into a non-overlapping tag window
    per ADR 0038 §"Tag-offset scheme".

    Geometry / mesh build-phase operations are not part of this
    primitive — the merge runs entirely against the FEMData
    broker; no live Gmsh state is touched.  The compose API is
    the canonical entry point for cross-session composition:
    ``FEMData.from_h5(path).compose("module.h5", label="A")``.

    Drift hazard: the returned FEMData is decoupled from any
    live gmsh state on the producing session.  Mutating the
    session's mesh/PG/label/parts AFTER calling compose without
    also re-extracting + re-applying the bundle drops the
    composed module's records on the floor.  The
    :meth:`apeGmsh.compose` shim handles this via session-level
    bundle-replay; if you call this primitive directly, replay
    is your responsibility.

    See :func:`apeGmsh.mesh._compose.Compose.compose` for the full
    parameter contract; ``max_compose_depth`` is the only
    ``Compose.compose`` parameter intentionally absent here
    (depth checks come in Phase 3E.1).
    """
    from ._compose import (
        Compose, ComposeAnchorError,
        _compute_source_span, _compute_reservation,
        _rewrite_source_for_compose, _merge_bundle_into_fem,
        _emit_filter_warnings, _host_max_tag,
    )

    # 1. Validate inputs — reuse the Compose facade's static
    #    validators so the contract stays single-sourced.
    Compose._validate_label(label)
    Compose._validate_translate_rotate_anchor(translate, anchor)
    Compose._validate_partition_rank(partition_rank)
    Compose._validate_compose_size(compose_size_per_module)

    # 2. Resolve anchor → translate when anchor is given.  Anchor
    #    + non-zero translate already raised above; an unknown
    #    PG raises ComposeAnchorError with an actionable message.
    if anchor is not None:
        translate = _resolve_anchor_to_translate(self, anchor)

    # 3. Compute reservation against host's max_tag.  The merge
    #    engine doesn't track explicit (base, size) pairs on
    #    composed_from in this slice (deferred to 3D); each
    #    new compose simply rounds host_max_tag up to the next
    #    granularity boundary, which advances naturally as each
    #    bundle's tags fold into the host's id ranges.
    host_max_tag = _host_max_tag(self)
    source_span, source_min_tag, _source_max_tag = (
        _compute_source_span(source)
    )
    base, size = _compute_reservation(
        source_span=source_span,
        host_max_tag=host_max_tag,
        previous_reservations=(),
        granularity=Compose.RESERVATION_GRANULARITY,
        compose_size_per_module=compose_size_per_module,
    )

    # Capacity check (ADR 0038 §"Tag-collision verifier" check 5).
    if compose_size_per_module is not None and source_span > size:
        from ._compose import ComposeCapacityError
        raise ComposeCapacityError(
            f"compose(compose_size_per_module="
            f"{compose_size_per_module}) is smaller than the "
            f"source's tag span ({source_span}); reservation size "
            f"{size} would not fit the imported tags."
        )

    # 4. Rewrite the source into an offset/namespaced bundle.
    #    Phase 3E.1: forward max_compose_depth so the rewriter's
    #    depth gate fires before any rewrite work runs.  ``None``
    #    means "use the default" (DEFAULT_MAX_COMPOSE_DEPTH = 3).
    from ._compose import DEFAULT_MAX_COMPOSE_DEPTH as _DEFAULT_MAX_DEPTH
    depth_cap = (
        max_compose_depth
        if max_compose_depth is not None
        else _DEFAULT_MAX_DEPTH
    )
    bundle = _rewrite_source_for_compose(
        source_path=source,
        label=label,
        translate=translate,
        rotate=rotate,
        partition_rank=partition_rank,
        properties=dict(properties or {}),
        base=base,
        size=size,
        source_span=source_span,
        source_min_tag=source_min_tag,
        max_compose_depth=depth_cap,
    )

    # 5. Emit FILTER warnings (stages / time-series / patterns).
    _emit_filter_warnings(source, label)

    # 5b. Interface-size advisory (Phase 3F.1 / ADR 0038
    #     §"v1 scope gate").  Emits one ComposeInterfaceSizeWarning
    #     when the bundle's MP-style constraint count exceeds
    #     WARN_INTERFACE_SIZE = 50_000 — silenceable per-call via
    #     ``warnings.simplefilter("ignore", ComposeInterfaceSizeWarning)``.
    from ._compose import WARN_INTERFACE_SIZE, _warn_interface_size
    _warn_interface_size(bundle, threshold=WARN_INTERFACE_SIZE)

    # 6. Merge bundle into self → new FEMData.  The merge engine
    #    runs the Phase 2.2 tag-collision verifier first
    #    (ADR 0038 §"Tag-collision verifier") and raises a typed
    #    error on violation.  Cache the bundle on the result for
    #    the session shim's replay machinery.
    new_fem = _merge_bundle_into_fem(
        self, bundle, compose_size_per_module=compose_size_per_module,
    )

    # 7. Phase 3B.2d / ADR 0038 §"Rank model" — eager populator.
    #    Assign one partition per composed module (Layer 1) +
    #    honour partition_rank hints (Layer 2).  Existing
    #    METIS-driven partitions trigger a UserWarning (Layer 3).
    from ._compose import _rebuild_partitions_from_modules
    new_fem = _rebuild_partitions_from_modules(new_fem)

    new_fem._last_compose_bundle = bundle  # type: ignore[attr-defined]
    return new_fem

compose_tree

compose_tree() -> 'tuple'

Derived nested-compose tree view of self.composed_from.

Reconstructs the nested-compose hierarchy from this FEMData's flat composed_from chain (per PR #369's flat-graft storage). Returns a tuple of root :class:~apeGmsh.mesh._compose.ComposeTreeNode instances; each root carries its :class:ComposeRecord plus any direct children parsed from joined labels via the separator- alternation rule (depth-1 ., depth-2 /, depth-3 ., ...).

Empty tuple when self.composed_from is empty (an uncomposed FEMData).

Source code in src/apeGmsh/mesh/FEMData.py
def compose_tree(self) -> "tuple":
    """Derived nested-compose tree view of ``self.composed_from``.

    Reconstructs the nested-compose hierarchy from this FEMData's
    flat ``composed_from`` chain (per PR #369's flat-graft
    storage).  Returns a tuple of root
    :class:`~apeGmsh.mesh._compose.ComposeTreeNode` instances;
    each root carries its :class:`ComposeRecord` plus any direct
    children parsed from joined labels via the separator-
    alternation rule (depth-1 ``.``, depth-2 ``/``, depth-3
    ``.``, ...).

    Empty tuple when ``self.composed_from`` is empty (an
    uncomposed FEMData).
    """
    from ._compose import _build_compose_tree
    return _build_compose_tree(tuple(self.composed_from))

with_mass

with_mass(record) -> 'FEMData'

Return a new :class:FEMData with record appended to nodes.masses.

Pure transform. self is unchanged. Only :class:~apeGmsh._kernel.records._masses.MassRecord is accepted; anything else raises TypeError.

Source code in src/apeGmsh/mesh/FEMData.py
def with_mass(self, record) -> "FEMData":
    """Return a new :class:`FEMData` with ``record`` appended to
    ``nodes.masses``.

    Pure transform.  ``self`` is unchanged.  Only
    :class:`~apeGmsh._kernel.records._masses.MassRecord` is
    accepted; anything else raises ``TypeError``.
    """
    from .._kernel.records._masses import MassRecord

    if isinstance(record, MassRecord):
        new_set = self.nodes.masses._with_record(record)
        return self._replaced(
            nodes=self._replaced_nodes(masses=new_set))
    raise TypeError(
        f"FEMData.with_mass: unsupported record type "
        f"{type(record).__name__!r} — expected MassRecord."
    )

assess

assess(*, figures: bool = False, out_dir: 'str | Path | None' = None) -> 'AssessmentReport'

Compile a v1 :class:~apeGmsh.assess.AssessmentReport (ADR 0094).

figures=True writes one undeformed mesh still via :meth:render. Default is False.

Source code in src/apeGmsh/mesh/FEMData.py
def assess(
    self,
    *,
    figures: bool = False,
    out_dir: "str | Path | None" = None,
) -> "AssessmentReport":
    """Compile a v1 :class:`~apeGmsh.assess.AssessmentReport` (ADR 0094).

    ``figures=True`` writes one undeformed mesh still via
    :meth:`render`. Default is ``False``.
    """
    from apeGmsh.assess import assess_fem
    return assess_fem(self, figures=figures, out_dir=out_dir)

render

render(path: 'str | Path', *, camera: 'str | None' = None, window_size: tuple[int, int] = (1280, 720)) -> 'Path | None'

Write one undeformed mesh still (ADR 0094 S1).

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.

camera= defaults to xy for a planar model, iso otherwise (ADR 0094 Amendment 3); pass it explicitly to override.

Source code in src/apeGmsh/mesh/FEMData.py
def render(
    self,
    path: "str | Path",
    *,
    camera: "str | None" = None,
    window_size: tuple[int, int] = (1280, 720),
) -> "Path | None":
    """Write one undeformed mesh still (ADR 0094 S1).

    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.

    ``camera=`` defaults to ``xy`` for a planar model, ``iso``
    otherwise (ADR 0094 Amendment 3); pass it explicitly to
    override.
    """
    from apeGmsh.viewers.render import render_fem
    return render_fem(
        self, path, camera=camera, window_size=window_size,
    )

viewer

viewer(*, blocking: bool = False) -> None

Open a non-interactive mesh viewer from this snapshot.

Currently disabled — the legacy Results.from_fem(...).viewer() path was removed when the Results module was rebuilt. For a headless mesh still use :meth:render. For an interactive mesh window, use g.mesh.viewer().

Source code in src/apeGmsh/mesh/FEMData.py
def viewer(self, *, blocking: bool = False) -> None:
    """Open a non-interactive mesh viewer from this snapshot.

    Currently disabled — the legacy ``Results.from_fem(...).viewer()``
    path was removed when the Results module was rebuilt. For a
    headless mesh still use :meth:`render`. For an interactive
    mesh window, use ``g.mesh.viewer()``.
    """
    raise NotImplementedError(
        "fem.viewer() relied on the legacy Results class which has "
        "been rebuilt. For a headless mesh still use fem.render(); "
        "for an interactive mesh window use g.mesh.viewer()."
    )

MeshInfo

MeshInfo(n_nodes: int, n_elems: int, bandwidth: int, types: list[ElementTypeInfo] | None = None)

Read-only summary of mesh statistics.

Accessed via fem.info.

Attributes

n_nodes : int n_elems : int bandwidth : int types : list[ElementTypeInfo] Element types present in the mesh.

Source code in src/apeGmsh/mesh/FEMData.py
def __init__(
    self,
    n_nodes: int,
    n_elems: int,
    bandwidth: int,
    types: list[ElementTypeInfo] | None = None,
) -> None:
    self.n_nodes = n_nodes
    self.n_elems = n_elems
    self.bandwidth = bandwidth
    self.types = types or []

nodes_per_elem property

nodes_per_elem: int

First type's npe, or 0 if empty.

elem_type_name property

elem_type_name: str

First type's name, or empty string.

summary

summary() -> str

One-line summary string.

Source code in src/apeGmsh/mesh/FEMData.py
def summary(self) -> str:
    """One-line summary string."""
    s = f"{self.n_nodes} nodes, {self.n_elems} elements"
    if self.types:
        type_parts = [f"{t.name}:{t.count}" for t in self.types]
        s += f" ({', '.join(type_parts)})"
    s += f", bandwidth={self.bandwidth}"
    return s

PhysicalGroupSet

PhysicalGroupSet(groups: dict[tuple[int, int], dict])

Bases: NamedGroupSet

Snapshot of solver-facing physical groups.

Accessed via fem.nodes.physical / fem.elements.physical (shared reference) and indirectly via fem.nodes.select(pg="Base").

Source code in src/apeGmsh/mesh/_group_set.py
def __init__(self, groups: dict[tuple[int, int], dict]) -> None:
    # Apply dtype coercion once at construction time
    self._groups: dict[tuple[int, int], dict] = {}
    for key, info in groups.items():
        coerced = dict(info)
        coerced['node_ids'] = _to_object(info['node_ids'])
        coerced['node_coords'] = np.asarray(
            info['node_coords'], dtype=np.float64)
        if 'element_ids' in info:
            coerced['element_ids'] = _to_object(info['element_ids'])
        # Per-type groups (new extraction format)
        if 'groups' in info:
            coerced['groups'] = info['groups']
        # Legacy flat connectivity (keep if present)
        if 'connectivity' in info:
            coerced['connectivity'] = _to_object(info['connectivity'])
        self._groups[key] = coerced

    self._name_index: dict[str, list[tuple[int, int]]] | None = None
    # Cache for merged multi-dim info dicts
    self._merged_cache: dict[str, dict] = {}

LabelSet

LabelSet(groups: dict[tuple[int, int], dict])

Bases: NamedGroupSet

Snapshot of geometry-time labels (Tier 1).

Accessed via fem.nodes.labels / fem.elements.labels (shared reference) and indirectly via fem.nodes.select(label="col.web").

Source code in src/apeGmsh/mesh/_group_set.py
def __init__(self, groups: dict[tuple[int, int], dict]) -> None:
    # Apply dtype coercion once at construction time
    self._groups: dict[tuple[int, int], dict] = {}
    for key, info in groups.items():
        coerced = dict(info)
        coerced['node_ids'] = _to_object(info['node_ids'])
        coerced['node_coords'] = np.asarray(
            info['node_coords'], dtype=np.float64)
        if 'element_ids' in info:
            coerced['element_ids'] = _to_object(info['element_ids'])
        # Per-type groups (new extraction format)
        if 'groups' in info:
            coerced['groups'] = info['groups']
        # Legacy flat connectivity (keep if present)
        if 'connectivity' in info:
            coerced['connectivity'] = _to_object(info['connectivity'])
        self._groups[key] = coerced

    self._name_index: dict[str, list[tuple[int, int]]] | None = None
    # Cache for merged multi-dim info dicts
    self._merged_cache: dict[str, dict] = {}

Algorithm2D

Bases: IntEnum

2-D meshing algorithm selector (legacy IntEnum form).

Prefer passing a string name to :meth:apeGmsh.mesh.Mesh._Generation.set_algorithm — see :data:ALGORITHM_2D and :class:MeshAlgorithm2D for the canonical names and the accepted aliases.

Algorithm3D

Bases: IntEnum

3-D meshing algorithm selector (legacy IntEnum form).

MeshAlgorithm2D

Canonical 2-D algorithm names as string constants (IDE autocomplete).

MeshAlgorithm3D

Canonical 3-D algorithm names as string constants (IDE autocomplete).

OptimizeMethod

Mesh optimisation method names — use with g.mesh.generation.optimize.

MshLoader

MshLoader(parent: '_SessionBase | None' = None)

Bases: _HasLogging

Load .msh files and produce solver-ready :class:FEMData.

Can be used standalone via the :meth:load classmethod, or as a composite on a apeGmsh / Assembly session via g.loader.

Parameters

parent : _SessionBase or None The owning session when used as a composite. None when used standalone.

Source code in src/apeGmsh/mesh/MshLoader.py
def __init__(self, parent: "_SessionBase | None" = None) -> None:
    self._parent = parent

load classmethod

load(path: str | Path, *, dim: int = 2, verbose: bool = False) -> 'FEMData'

Load a .msh file and return a :class:FEMData.

Manages its own Gmsh session internally — no apeGmsh instance, no begin()/end() needed. Supports MSH2 and MSH4 formats.

Parameters

path : str or Path Path to the .msh file. dim : int Element dimension to extract (1 = lines, 2 = tri/quad, 3 = tet/hex). Default is 2. verbose : bool Print a summary of what was loaded.

Returns

FEMData Self-contained solver-ready mesh data with physical groups, mesh statistics, and connectivity.

Example

::

from apeGmsh import MshLoader, Numberer

fem = MshLoader.load("bridge.msh", dim=2)

print(fem.info)
print(fem.physical.summary())

numb = Numberer(fem)
data = numb.renumber(method="rcm")
Source code in src/apeGmsh/mesh/MshLoader.py
@classmethod
def load(
    cls,
    path: str | Path,
    *,
    dim: int = 2,
    verbose: bool = False,
) -> "FEMData":
    """
    Load a ``.msh`` file and return a :class:`FEMData`.

    Manages its own Gmsh session internally — no ``apeGmsh``
    instance, no ``begin()``/``end()`` needed.  Supports MSH2
    and MSH4 formats.

    Parameters
    ----------
    path : str or Path
        Path to the ``.msh`` file.
    dim : int
        Element dimension to extract (1 = lines, 2 = tri/quad,
        3 = tet/hex).  Default is 2.
    verbose : bool
        Print a summary of what was loaded.

    Returns
    -------
    FEMData
        Self-contained solver-ready mesh data with physical
        groups, mesh statistics, and connectivity.

    Example
    -------
    ::

        from apeGmsh import MshLoader, Numberer

        fem = MshLoader.load("bridge.msh", dim=2)

        print(fem.info)
        print(fem.physical.summary())

        numb = Numberer(fem)
        data = numb.renumber(method="rcm")
    """
    from .FEMData import FEMData

    p = cls._validate_path(path)
    fem = FEMData.from_msh(str(p), dim=dim)

    cls._log_fem(fem, f"load({p.name!r})", verbose)
    return fem

from_msh

from_msh(path: str | Path, *, dim: int = 2) -> 'FEMData'

Load a .msh file into the active Gmsh session.

The mesh is merged via gmsh.merge(), so all composites (g.physical, g.plot, g.inspect, etc.) remain usable afterwards.

Parameters

path : str or Path Path to the .msh file. dim : int Element dimension to extract. Default is 2.

Returns

FEMData Self-contained solver-ready mesh data.

Raises

FileNotFoundError If path does not exist. RuntimeError If no Gmsh session is active (call g.begin() first).

Example

::

g = apeGmsh(model_name="imported")
g.begin()

fem = g.loader.from_msh("model.msh", dim=2)
print(fem.physical.summary())

g.end()
Source code in src/apeGmsh/mesh/MshLoader.py
def from_msh(
    self,
    path: str | Path,
    *,
    dim: int = 2,
) -> "FEMData":
    """
    Load a ``.msh`` file into the **active** Gmsh session.

    The mesh is merged via ``gmsh.merge()``, so all composites
    (``g.physical``, ``g.plot``, ``g.inspect``, etc.) remain
    usable afterwards.

    Parameters
    ----------
    path : str or Path
        Path to the ``.msh`` file.
    dim : int
        Element dimension to extract.  Default is 2.

    Returns
    -------
    FEMData
        Self-contained solver-ready mesh data.

    Raises
    ------
    FileNotFoundError
        If *path* does not exist.
    RuntimeError
        If no Gmsh session is active (call ``g.begin()`` first).

    Example
    -------
    ::

        g = apeGmsh(model_name="imported")
        g.begin()

        fem = g.loader.from_msh("model.msh", dim=2)
        print(fem.physical.summary())

        g.end()
    """
    from .FEMData import FEMData

    p = self._validate_path(path)

    if self._parent is None or not self._parent.is_active:
        raise RuntimeError(
            "No active Gmsh session. Call g.begin() first, "
            "or use MshLoader.load() for standalone loading."
        )

    self._log(f"merging {p.name} ...")
    gmsh.merge(str(p))

    fem = FEMData.from_gmsh(dim=dim)

    verbose = self._parent._verbose if self._parent else False
    self._log_fem(fem, f"from_msh({p.name!r})", verbose)

    return fem

Results

Results(reader: ResultsReader, *, fem: 'Optional[FEMData]' = None, stage_id: Optional[str] = None, path: Optional[Path] = None, model: 'OpenSeesModel', model_path: Optional[Path] = None)

Top-level results object. Returned by Results.from_* constructors.

Stage scoping

Instances may be unscoped (top-level — accesses any stage) or scoped to one stage (returned by .stage(name), .modes[i]). Scoped instances expose stage metadata as properties (.kind, .time, .n_steps); mode-scoped instances additionally expose .eigenvalue, .frequency_hz, .period_s, .mode_index.

Source code in src/apeGmsh/results/Results.py
def __init__(
    self,
    reader: ResultsReader,
    *,
    fem: "Optional[FEMData]" = None,
    stage_id: Optional[str] = None,
    path: Optional[Path] = None,
    model: "OpenSeesModel",
    model_path: Optional[Path] = None,
) -> None:
    self._reader = reader
    self._fem = fem
    self._stage_id = stage_id
    self._path = path
    # ADR 0020 INV-1 (Phase 8 prune) — ``_model`` is required and
    # never None.  The three public constructors validate the
    # contract and raise :class:`TypeError` on missing supply;
    # internal callers (``_derive``) propagate the existing handle.
    self._model = model
    # Sibling-archive path for readers that carry no embedded
    # ``/opensees/`` zone (MPCO).  ``None`` when ``self._path``
    # already is the model archive (native Composed file).  The
    # subprocess viewer reads this to forward ``--model-h5`` to
    # the child process — without it, ``__main__.py`` exits(2)
    # on ``.mpco`` paths.
    self._model_path = model_path
    self._stages_cache: Optional[list[StageInfo]] = None

    # Composites
    self.nodes = NodeResultsComposite(self)
    self.elements = ElementResultsComposite(self)
    self.inspect = ResultsInspect(self)
    self._plot: Optional["ResultsPlot"] = None

fem property

fem: 'Optional[FEMData]'

The bound FEMData snapshot, or None if not bound.

model property

model: 'OpenSeesModel'

The bound :class:OpenSeesModel broker.

Phase 8 (ADR 0020 INV-1) — always non-None on a constructed :class:Results. The chain-forward handle from which the OpenSeesModel and its embedded FEMData can be reached.

lineage property

lineage: 'Lineage'

Phase-6 lineage chain — git-style fem → model → results.

ADR 0021 defines a three-link hash chain fem_hash → model_hash → results_hash where each layer's hash includes its parent's hash (one-directional, tamper-evident). Mismatches between stored and recomputed hashes surface as [lineage] ... warnings in :attr:Lineage.warnings; they never raise from this property (INV-2).

Phase-8 derivation order:

  1. Inherit fem_hash + model_hash + accumulated warnings from :attr:model.lineage (the broker recomputes against the same file).
  2. Read the stored /meta/lineage/results_hash via the reader's results_lineage_attrs helper and recompute from /stages/... via recompute_results_hash; append a drift warning on mismatch.

Readers that don't implement the Phase-6 result-layer protocol methods are tolerated via getattr cushions: their lineage stays at the model layer, no warning emitted.

stages property

stages: list[StageInfo]

All stages in the file (scoped instances also list them).

modes property

modes: list['Results']

Stages with kind='mode' as a list of mode-scoped Results.

Order is the order the modes were written (typically by ascending mode_index). For a stable lookup by index, sort: sorted(results.modes, key=lambda m: m.mode_index).

eigen_modes property

eigen_modes: list[EigenMode]

Mode-kind stages as lightweight :class:EigenMode snapshots.

Each :class:EigenMode carries only the four scalar fields (mode_index, eigenvalue, frequency_hz, period_s) — no file handle, no mode-shape arrays. Use this when you need the eigenvalue spectrum but not the per-node shapes (e.g. an LTB Mcr probe, a pickle-able report, or a return value from a function whose Results context is about to be closed).

For the per-node mode shape arrays, use the mode-scoped :class:Results from :attr:modes instead and query via mode.nodes.get(component="displacement_x", ...).

Order matches :attr:modes. For a stable lookup by index, sort: sorted(results.eigen_modes, key=lambda m: m.mode_index).

plot property

plot: 'ResultsPlot'

results.plot — static matplotlib renderer.

Mirrors the interactive viewer's diagram catalog as headless, publication-ready matplotlib figures::

results.plot.contour("displacement_z", step=-1)
results.plot.deformed(step=-1, scale=50, component="stress_xx")
results.plot.history(node=412, component="displacement_x")

Requires the [plot] extra (matplotlib).

from_native classmethod

from_native(path: str | Path, *, fem: 'Optional[FEMData]' = None, model: 'Optional[OpenSeesModel]' = None, model_path: 'Optional[str | Path]' = None) -> 'Results'

Open an apeGmsh native HDF5 results file.

Phase 8 (ADR 0020 INV-1) — model= is required. Missing supply raises :class:TypeError. Pass model=OpenSeesModel.from_h5(path_to_model_h5) (often the same path as path when the file is a Composed-file per ADR 0020).

If fem is omitted, the embedded /model/ snapshot is used as the bound FEMData.

model_path records the on-disk archive the model was read from, for when it is not path itself — e.g. results whose embedded /model zone is not independently readable. The non-blocking subprocess viewer forwards it as --model-h5 so the child re-reads the model from there instead of from path.

Source code in src/apeGmsh/results/Results.py
@classmethod
def from_native(
    cls,
    path: str | Path,
    *,
    fem: "Optional[FEMData]" = None,
    model: "Optional[OpenSeesModel]" = None,
    model_path: "Optional[str | Path]" = None,
) -> "Results":
    """Open an apeGmsh native HDF5 results file.

    Phase 8 (ADR 0020 INV-1) — ``model=`` is required. Missing
    supply raises :class:`TypeError`. Pass
    ``model=OpenSeesModel.from_h5(path_to_model_h5)`` (often the
    same path as ``path`` when the file is a Composed-file
    per ADR 0020).

    If ``fem`` is omitted, the embedded ``/model/`` snapshot is
    used as the bound FEMData.

    ``model_path`` records the on-disk archive the ``model`` was read
    from, for when it is *not* ``path`` itself — e.g. results whose
    embedded ``/model`` zone is not independently readable. The
    non-blocking subprocess viewer forwards it as ``--model-h5`` so the
    child re-reads the model from there instead of from ``path``.
    """
    if model is None:
        raise TypeError(_MODEL_REQUIRED_MESSAGE)
    from .readers._native import NativeReader
    reader = NativeReader(path)
    bound_fem = _resolve_fem(reader, fem)
    bound_model = resolve_bound_model(reader, model)
    # ``resolve_bound_model`` always returns ``model`` here since
    # we just asserted it is non-None, but route through the helper
    # to keep the resolution semantics in one place.
    assert bound_model is not None
    return cls(
        reader, fem=bound_fem, path=Path(path), model=bound_model,
        model_path=Path(model_path) if model_path is not None else None,
    )._with_autoloaded_definitions()

from_recorders classmethod

from_recorders(spec, output_dir: str | Path, *, fem: 'FEMData', cache_root: str | Path | None = None, stage_name: str = 'analysis', stage_kind: str = 'transient', file_format: str = 'out', stage_id: str | None = None, model: 'Optional[OpenSeesModel]' = None) -> 'Results'

Open the result of an OpenSees run driven by Tcl/Py recorders.

Phase 8 (ADR 0020 INV-1) — model= is required. Missing supply raises :class:TypeError. The model's /opensees/ zone is embedded into the transcoded native h5 (the Composed-file pattern); downstream :meth:Results.from_native then auto-resolves the broker from the same file.

Parses the .out / .xml files emitted at output_dir (matching what spec.emit_recorders(...) or the apeGmsh OpenSees bridge's Tcl/Py emit produced) into an apeGmsh native HDF5, caches the result at cache_root, and opens it through NativeReader.

Caching: subsequent calls with unchanged input files return the cached HDF5 directly (file mtime + size + spec snapshot_id form the cache key). See writers/_cache.py.

stage_id matches the per-stage filename prefix used by :meth:ResolvedRecorderSpec.emit_recorders together with begin_stage(stage_id, ...). When set, only files prefixed with <stage_id>__ are read; stage_name defaults to stage_id if not overridden. None (default) keeps the legacy flat-naming used by Tcl/Py exports.

Phase 6 v1 supports nodal records only; element-level records in the spec are skipped with a note. The capture flow (Phase 7) handles modal recorders.

Source code in src/apeGmsh/results/Results.py
@classmethod
def from_recorders(
    cls,
    spec,
    output_dir: str | Path,
    *,
    fem: "FEMData",
    cache_root: str | Path | None = None,
    stage_name: str = "analysis",
    stage_kind: str = "transient",
    file_format: str = "out",
    stage_id: str | None = None,
    model: "Optional[OpenSeesModel]" = None,
) -> "Results":
    """Open the result of an OpenSees run driven by Tcl/Py recorders.

    Phase 8 (ADR 0020 INV-1) — ``model=`` is required. Missing
    supply raises :class:`TypeError`. The model's ``/opensees/``
    zone is embedded into the transcoded native h5 (the
    Composed-file pattern); downstream
    :meth:`Results.from_native` then auto-resolves the broker
    from the same file.

    Parses the ``.out`` / ``.xml`` files emitted at
    ``output_dir`` (matching what ``spec.emit_recorders(...)`` or
    the apeGmsh OpenSees bridge's Tcl/Py emit produced) into an
    apeGmsh native HDF5, caches the result at
    ``cache_root``, and opens it through ``NativeReader``.

    Caching: subsequent calls with unchanged input files return
    the cached HDF5 directly (file mtime + size + spec
    ``snapshot_id`` form the cache key). See
    ``writers/_cache.py``.

    ``stage_id`` matches the per-stage filename prefix used by
    :meth:`ResolvedRecorderSpec.emit_recorders` together with
    ``begin_stage(stage_id, ...)``. When set, only files prefixed
    with ``<stage_id>__`` are read; ``stage_name`` defaults to
    ``stage_id`` if not overridden. ``None`` (default) keeps the
    legacy flat-naming used by Tcl/Py exports.

    Phase 6 v1 supports nodal records only; element-level records
    in the spec are skipped with a note. The capture flow
    (Phase 7) handles modal recorders.
    """
    if model is None:
        raise TypeError(_MODEL_REQUIRED_MESSAGE)
    from .schema._versions import PARSER_VERSION
    from .transcoders import RecorderTranscoder
    from .writers import _cache

    if fem is None:
        raise TypeError(
            "Results.from_recorders(...) requires fem= "
            "(the spec's snapshot_id must match)."
        )

    # When stage_id is provided and stage_name was left at its
    # default, mirror stage_id so the resulting Results stage is
    # named meaningfully (otherwise everything ends up as
    # "analysis" regardless of which stage the user loaded).
    if stage_id is not None and stage_name == "analysis":
        stage_name = stage_id

    out_dir = Path(output_dir)
    cache_dir = _cache.resolve_cache_root(cache_root)

    source_files = _cache.list_source_files(
        spec, out_dir, file_format=file_format, stage_id=stage_id,
    )
    key = _cache.compute_cache_key(
        source_files,
        parser_version=PARSER_VERSION,
        fem_snapshot_id=fem.snapshot_id,
    )
    cached_h5, _ = _cache.cache_paths(cache_dir, key)

    if not cached_h5.exists():
        # Materialise the model's ``/opensees/`` zone alongside the
        # transcoded results.  ``OpenSeesModel.to_h5`` (the public,
        # schema-authority-respecting writer) shapes the source;
        # NativeWriter copies the ``/opensees/`` group at open
        # time (Composed-file pattern, ADR 0020 INV-3 preserved).
        model_h5_src: Path = cached_h5.with_suffix(".model.h5")
        model.to_h5(model_h5_src)
        transcoder = RecorderTranscoder(
            spec, out_dir, cached_h5, fem,
            stage_name=stage_name,
            stage_kind=stage_kind,
            file_format=file_format,
            stage_id=stage_id,
            model_h5_src=model_h5_src,
        )
        transcoder.run()

    return cls.from_native(cached_h5, fem=fem, model=model)

from_mpco classmethod

from_mpco(path: 'str | Path | list[str | Path]', *, fem: 'Optional[FEMData]' = None, merge_partitions: bool = True, model_h5: 'Optional[str | Path]' = None) -> 'Results'

Open a STKO .mpco HDF5 results file.

Phase 8 (ADR 0020 INV-1) — model_h5= is required. Missing supply raises :class:TypeError. The broker is loaded via :meth:OpenSeesModel.from_h5 and attached to the resulting :class:Results; INV-3 — the broker is held in memory only (no derived results.h5 is written copying the /opensees/ zone in).

Single-file mode (default for non-partitioned analyses): pass the path of one .mpco file. Synthesizes a partial FEMData from the MPCO MODEL/ group if fem is omitted.

Multi-partition mode (parallel OpenSees runs): pass either

  • a single <stem>.part-<N>.mpco path — siblings are discovered automatically by globbing <stem>.part-*.mpco in the same directory and merged into one virtual reader;
  • an explicit list of partition paths.

Boundary nodes deduplicate by ID (first-occurrence wins); elements concatenate (disjoint by partition); slabs stitch across partitions transparently. Stage and time vectors must match across partitions or construction raises.

Pass merge_partitions=False to opt out of auto-discovery and read only the file at path even if it follows the .part-N naming convention.

Source code in src/apeGmsh/results/Results.py
@classmethod
def from_mpco(
    cls,
    path: "str | Path | list[str | Path]",
    *,
    fem: "Optional[FEMData]" = None,
    merge_partitions: bool = True,
    model_h5: "Optional[str | Path]" = None,
) -> "Results":
    """Open a STKO ``.mpco`` HDF5 results file.

    Phase 8 (ADR 0020 INV-1) — ``model_h5=`` is required. Missing
    supply raises :class:`TypeError`. The broker is loaded via
    :meth:`OpenSeesModel.from_h5` and attached to the resulting
    :class:`Results`; INV-3 — the broker is held *in memory only*
    (no derived ``results.h5`` is written copying the
    ``/opensees/`` zone in).

    Single-file mode (default for non-partitioned analyses): pass
    the path of one ``.mpco`` file. Synthesizes a partial FEMData
    from the MPCO ``MODEL/`` group if ``fem`` is omitted.

    Multi-partition mode (parallel OpenSees runs): pass either

    - a single ``<stem>.part-<N>.mpco`` path — siblings are
      discovered automatically by globbing ``<stem>.part-*.mpco``
      in the same directory and merged into one virtual reader;
    - an explicit list of partition paths.

    Boundary nodes deduplicate by ID (first-occurrence wins);
    elements concatenate (disjoint by partition); slabs stitch
    across partitions transparently. Stage and time vectors must
    match across partitions or construction raises.

    Pass ``merge_partitions=False`` to opt out of auto-discovery
    and read only the file at ``path`` even if it follows the
    ``.part-N`` naming convention.
    """
    if model_h5 is None:
        raise TypeError(_MODEL_H5_REQUIRED_MESSAGE)
    from .readers._mpco import MPCOReader
    from .readers._mpco_multi import (
        MPCOMultiPartitionReader, discover_partition_files,
    )

    if isinstance(path, (list, tuple)):
        paths = [Path(p) for p in path]
        reader = (
            MPCOMultiPartitionReader(paths)
            if len(paths) > 1
            else MPCOReader(paths[0])
        )
        anchor = paths[0]
    else:
        anchor = Path(path)
        if merge_partitions:
            discovered = discover_partition_files(anchor)
        else:
            discovered = [anchor]
        if len(discovered) > 1:
            reader = MPCOMultiPartitionReader(discovered)
        else:
            reader = MPCOReader(discovered[0])
    bound_fem = _resolve_fem(reader, fem)
    # Per INV-3, this is an in-memory rehydrate from the sibling
    # file; we never copy the zone into a derived h5.
    from ..opensees.opensees_model import OpenSeesModel
    bound_model = OpenSeesModel.from_h5(model_h5)
    # ADR 0043 slice 1.3 — MPCO buckets key element results by the
    # OpenSees ops tag; the results API speaks fem_eid. Whenever the
    # bound model carries a real element_meta pairing, the reader must
    # relabel ops↔fem through it. This is NOT compose-only: gmsh
    # numbers lower-dimensional elements first, so almost any solid
    # model with surface physical groups has fem_eid != ops_tag even
    # uncomposed (the former compose-provenance gate silently
    # scrambled / dropped element results for exactly that case —
    # fixed 2026-08-04). A deliberately-unrelated stub ``model_h5=``
    # (common in tests) stays safe through the translator's
    # all-or-nothing `_relabel` contract: ids the model does not
    # fully describe pass through untranslated.
    from .readers._tag_translation import ElementTagTranslator
    _tag_map = ElementTagTranslator.from_model(bound_model)
    if not _tag_map.is_empty:
        reader.attach_tag_map(_tag_map)
    return cls(
        reader, fem=bound_fem, path=anchor, model=bound_model,
        model_path=Path(model_h5),
    )._with_autoloaded_definitions()

from_ladruno classmethod

from_ladruno(path: 'str | Path | list[str | Path]', *, fem: 'Optional[FEMData]' = None, merge_partitions: bool = True, model_h5: 'Optional[str | Path]' = None) -> 'Results'

Open a Ladruno .ladruno HDF5 results file.

The Ladruno recorder is the fork's canonical recorder. Unlike .mpco (and unlike :meth:from_mpco, which requires model_h5=), a .ladruno is self-sufficient — it carries its own geometry, regions and beam local axes (schema Principle 0: "this is the native path; no sibling file"). So model_h5= is optional:

  • omitted → the broker is built in-memory from the file's own MODEL group (geometry + inferred ndm/ndf; bridge record zones empty). This is read-time interpretation, not a transcode.
  • supplied → the richer broker is loaded via :meth:OpenSeesModel.from_h5 (full bridge records + lineage), and — whenever the model records an element_meta pairing — the fem_eid↔ops-tag translator is attached (ADR 0043; required for composed models AND for any sparsely-renumbered mesh, e.g. a gmsh solid whose 2-D boundary elements consumed the low ids).

Keys on INFO/GENERATOR="Ladruno" + a supported FORMAT_VERSION (the reader rejects a .mpco / foreign file or an out-of-window version loudly).

Multi-partition merge: a parallel run writes one <stem>.part-<N>.ladruno per rank. Passing one partition path auto-discovers its siblings (<stem>.part-*.ladruno) and merges them into one virtual reader (node-union + element-concat); passing a list merges exactly those paths. merge_partitions=False opts out of sibling auto-discovery.

Source code in src/apeGmsh/results/Results.py
@classmethod
def from_ladruno(
    cls,
    path: "str | Path | list[str | Path]",
    *,
    fem: "Optional[FEMData]" = None,
    merge_partitions: bool = True,
    model_h5: "Optional[str | Path]" = None,
) -> "Results":
    """Open a Ladruno ``.ladruno`` HDF5 results file.

    The Ladruno recorder is the fork's *canonical* recorder. Unlike
    ``.mpco`` (and unlike :meth:`from_mpco`, which **requires**
    ``model_h5=``), a ``.ladruno`` is **self-sufficient** — it carries
    its own geometry, regions and beam local axes (schema Principle 0:
    "this *is* the native path; no sibling file"). So ``model_h5=`` is
    **optional**:

    * omitted → the broker is built in-memory from the file's own
      ``MODEL`` group (geometry + inferred ``ndm``/``ndf``; bridge
      record zones empty). This is read-time interpretation, not a
      transcode.
    * supplied → the richer broker is loaded via
      :meth:`OpenSeesModel.from_h5` (full bridge records + lineage),
      and — whenever the model records an element_meta pairing —
      the fem_eid↔ops-tag translator is attached (ADR 0043; required
      for composed models AND for any sparsely-renumbered mesh, e.g.
      a gmsh solid whose 2-D boundary elements consumed the low ids).

    Keys on ``INFO/GENERATOR="Ladruno"`` + a supported
    ``FORMAT_VERSION`` (the reader rejects a ``.mpco`` / foreign file
    or an out-of-window version loudly).

    Multi-partition merge: a parallel run writes one
    ``<stem>.part-<N>.ladruno`` per rank. Passing one partition path
    auto-discovers its siblings (``<stem>.part-*.ladruno``) and merges
    them into one virtual reader (node-union + element-concat);
    passing a list merges exactly those paths. ``merge_partitions=False``
    opts out of sibling auto-discovery.
    """
    from .readers._ladruno import LadrunoReader
    from .readers._ladruno_multi import (
        LadrunoMultiPartitionReader, discover_partition_files,
    )

    if isinstance(path, (list, tuple)):
        paths = [Path(p) for p in path]
        reader = (
            LadrunoMultiPartitionReader(paths)
            if len(paths) > 1
            else LadrunoReader(paths[0])
        )
        anchor = paths[0]
    else:
        anchor = Path(path)
        discovered = (
            discover_partition_files(anchor)
            if merge_partitions else [anchor]
        )
        reader = (
            LadrunoMultiPartitionReader(discovered)
            if len(discovered) > 1
            else LadrunoReader(discovered[0])
        )
    bound_fem = _resolve_fem(reader, fem)
    bound_model: "Optional[OpenSeesModel]"
    if model_h5 is not None:
        from ..opensees.opensees_model import OpenSeesModel
        bound_model = OpenSeesModel.from_h5(model_h5)
        # Attach the fem_eid↔ops-tag translator whenever the model
        # carries a real element_meta pairing — see the twin comment
        # in :meth:`from_mpco` (the pairing diverges for ANY sparsely
        # renumbered mesh, not just composed models).
        from .readers._tag_translation import ElementTagTranslator
        _tag_map = ElementTagTranslator.from_model(bound_model)
        if not _tag_map.is_empty:
            reader.attach_tag_map(_tag_map)
        model_path: "Optional[Path]" = Path(model_h5)
    else:
        # Self-sufficient path — minimal broker from the file itself.
        bound_model = resolve_bound_model(reader, None)
        model_path = None
    assert bound_model is not None
    return cls(
        reader, fem=bound_fem, path=anchor, model=bound_model,
        model_path=model_path,
    )._with_autoloaded_definitions()

from_fem classmethod

from_fem(fem: 'FEMData', path: 'str | Path | list[str | Path]', *, kind: str = 'auto', merge_partitions: bool = True, cache_root: 'str | Path | None' = None) -> 'Results'

Open a results file against a bare :class:FEMData snapshot.

The one-call route to :class:Results / :meth:viewer for a model that did not go through the apeSees bridge — e.g. a physical-group model where fem = g.mesh.queries.get_fem_data() drove a hand-written OpenSees deck. Without this the only routes were the bridge-bound constructors (which need a bridge-emitted model.h5 / OpenSeesModel) or the self-describing :meth:from_ladruno.

from_fem materialises a neutral-only model.h5 from fem (cached, keyed by fem.snapshot_id) and binds it to the reader for path. Materialising a file — rather than an in-memory model — is deliberate: it sets model_path so the non-blocking / web viewers work (they forward --model-h5), not just data access.

Parameters

fem The bound snapshot (from g.mesh.queries.get_fem_data() or FEMData.from_h5). A composed fem is refused — see below. path The results file (or a partition list). kind "mpco" / "ladruno" / "native", or "auto" (default) to detect from the suffix (.mpco / .ladruno; a native .h5 must pass kind="native"). merge_partitions Forwarded to :meth:from_mpco / :meth:from_ladruno for .part-N auto-discovery. cache_root Where the materialised model.h5 is written — under <cache_root>/from_fem/ (default <cwd>/results/from_fem/ or $APEGMSH_RESULTS_DIR).

Raises

ValueError When fem is composed (g.compose / from_h5 assembly). Element / Gauss results are relabelled through the fem_eid ↔ ops-tag map that only a real bridge run records; a neutral-only model.h5 carries none, so a composed model would silently mislabel every element result. Build the model through apeSees and pass its model.h5 (e.g. apeSees(fem).h5(...) / g.savefrom_mpco(path, model_h5=...)).

Notes

A bare fem carries no envelope ndf (MeshInfo has none), so the cached model's ndf is 0. This is harmless for reading results and for the viewer; it only matters for deck re-emit (model.build(...)), which is not this path's purpose.

Source code in src/apeGmsh/results/Results.py
@classmethod
def from_fem(
    cls,
    fem: "FEMData",
    path: "str | Path | list[str | Path]",
    *,
    kind: str = "auto",
    merge_partitions: bool = True,
    cache_root: "str | Path | None" = None,
) -> "Results":
    """Open a results file against a bare :class:`FEMData` snapshot.

    The one-call route to :class:`Results` / :meth:`viewer` for a
    model that did **not** go through the ``apeSees`` bridge — e.g. a
    physical-group model where ``fem = g.mesh.queries.get_fem_data()``
    drove a hand-written OpenSees deck.  Without this the only routes
    were the bridge-bound constructors (which need a bridge-emitted
    ``model.h5`` / ``OpenSeesModel``) or the self-describing
    :meth:`from_ladruno`.

    ``from_fem`` materialises a neutral-only ``model.h5`` from ``fem``
    (cached, keyed by ``fem.snapshot_id``) and binds it to the reader
    for ``path``.  Materialising a file — rather than an in-memory
    model — is deliberate: it sets ``model_path`` so the non-blocking
    / web viewers work (they forward ``--model-h5``), not just data
    access.

    Parameters
    ----------
    fem
        The bound snapshot (from ``g.mesh.queries.get_fem_data()`` or
        ``FEMData.from_h5``).  A **composed** fem is refused — see
        below.
    path
        The results file (or a partition list).
    kind
        ``"mpco"`` / ``"ladruno"`` / ``"native"``, or ``"auto"``
        (default) to detect from the suffix (``.mpco`` / ``.ladruno``;
        a native ``.h5`` must pass ``kind="native"``).
    merge_partitions
        Forwarded to :meth:`from_mpco` / :meth:`from_ladruno` for
        ``.part-N`` auto-discovery.
    cache_root
        Where the materialised ``model.h5`` is written — under
        ``<cache_root>/from_fem/`` (default ``<cwd>/results/from_fem/``
        or ``$APEGMSH_RESULTS_DIR``).

    Raises
    ------
    ValueError
        When ``fem`` is **composed** (``g.compose`` / ``from_h5``
        assembly).  Element / Gauss results are relabelled through the
        ``fem_eid ↔ ops-tag`` map that only a real bridge run records;
        a neutral-only ``model.h5`` carries none, so a composed model
        would silently mislabel every element result.  Build the model
        through ``apeSees`` and pass its ``model.h5`` (e.g.
        ``apeSees(fem).h5(...)`` / ``g.save`` →
        ``from_mpco(path, model_h5=...)``).

    Notes
    -----
    A bare fem carries no envelope ``ndf`` (``MeshInfo`` has none), so
    the cached model's ``ndf`` is ``0``.  This is harmless for reading
    results and for the viewer; it only matters for deck **re-emit**
    (``model.build(...)``), which is not this path's purpose.
    """
    # ADR 0043 slice 1.3 — element results relabel through the
    # bridge-emitted element_meta.  A neutral-only model.h5 carries
    # none, but ``composed_from`` round-trips, so from_mpco /
    # from_ladruno would see a "composed" model, attach an
    # element-less (empty) tag translator, and silently mislabel
    # every element/gauss/fiber result.  Refuse loudly.
    if len(getattr(fem, "composed_from", ()) or ()) > 0:
        raise ValueError(
            "Results.from_fem: the FEMData is composed (g.compose / "
            "from_h5). Element/Gauss results need the bridge's "
            "fem_eid<->ops-tag map, which a neutral-only model.h5 "
            "cannot provide. Build the model through apeSees and pass "
            "its model.h5 — e.g. Results.from_mpco(path, "
            "model_h5='model.h5')."
        )

    resolved_kind = _resolve_results_kind(kind, path)

    # Materialise a neutral-only model.h5, cached by content hash.
    from .writers._cache import resolve_cache_root

    cache_dir = resolve_cache_root(cache_root) / "from_fem"
    cache_dir.mkdir(parents=True, exist_ok=True)
    snap = str(getattr(fem, "snapshot_id", "") or "model")
    cached = cache_dir / f"{snap}.model.h5"
    if not cached.exists():
        fem.to_h5(str(cached))

    if resolved_kind == "mpco":
        return cls.from_mpco(
            path, fem=fem, model_h5=cached,
            merge_partitions=merge_partitions,
        )
    if resolved_kind == "ladruno":
        return cls.from_ladruno(
            path, fem=fem, model_h5=cached,
            merge_partitions=merge_partitions,
        )
    # native — pass the rehydrated neutral-only model + its path so
    # the subprocess viewer can forward --model-h5.
    from ..opensees.opensees_model import OpenSeesModel

    return cls.from_native(
        path, fem=fem, model=OpenSeesModel.from_h5(cached),
        model_path=cached,
    )

energy

energy(*, region: 'Optional[int]' = None, stage: Optional[str] = None) -> 'Any'

Energy-balance time history — Ladruno-recorder feature.

Returns a :class:pandas.DataFrame of the closure components KE / IE / DW / ULW / RES / ERR indexed by simulation time, written by the recorder's -G energy verb.

  • region=None → whole-domain balance (ON_DOMAIN).
  • region=<tag> → the per-region balance (ON_REGIONS) for the OpenSees region tag.

ERR (the normalized energy-balance error %) is the headline solution-quality diagnostic for explicit runs. Raises :class:TypeError on a non-Ladruno results object (MPCO / native carry no energy balance) and ValueError if energy was not recorded / the region is unknown.

results.plot.energy(...) renders this as a matplotlib time-history figure.

Source code in src/apeGmsh/results/Results.py
def energy(
    self,
    *,
    region: "Optional[int]" = None,
    stage: Optional[str] = None,
) -> "Any":
    """Energy-balance time history — **Ladruno-recorder feature**.

    Returns a :class:`pandas.DataFrame` of the closure components
    ``KE`` / ``IE`` / ``DW`` / ``ULW`` / ``RES`` / ``ERR`` indexed by
    simulation time, written by the recorder's ``-G energy`` verb.

    * ``region=None`` → whole-domain balance (``ON_DOMAIN``).
    * ``region=<tag>`` → the per-region balance (``ON_REGIONS``) for
      the OpenSees region tag.

    ``ERR`` (the normalized energy-balance error %) is the headline
    solution-quality diagnostic for explicit runs. Raises
    :class:`TypeError` on a non-Ladruno results object (MPCO / native
    carry no energy balance) and ``ValueError`` if energy was not
    recorded / the region is unknown.

    ``results.plot.energy(...)`` renders this as a matplotlib
    time-history figure.
    """
    read_energy = getattr(self._reader, "read_energy", None)
    if read_energy is None:
        raise TypeError(
            "Results.energy() is a Ladruno-recorder feature. Open a "
            ".ladruno via Results.from_ladruno(...) recorded with the "
            "'-G energy' verb; MPCO / native results carry no energy "
            "balance."
        )
    sid = self._resolve_stage(stage)
    cols, values, time = read_energy(sid, region=region)
    import pandas as pd
    return pd.DataFrame(
        values, columns=cols, index=pd.Index(time, name="time"),
    )

energy_regions

energy_regions(*, stage: Optional[str] = None) -> 'list[int]'

OpenSees region tags with a recorded per-region energy balance.

The bridge auto-allocates an integer region tag when a Ladruno recorder is given energy_pg= (or a value filter + energy); that tag is opaque to the author. This lists the tags actually present in ON_REGIONS/energyBalance so you can pick one to pass to :meth:energy — e.g. r.energy(region=r.energy_regions()[0]).

Returns [] when only the whole-model balance was recorded (read it with energy(), no region=). Ladruno-recorder feature; raises :class:TypeError on MPCO / native results.

Source code in src/apeGmsh/results/Results.py
def energy_regions(self, *, stage: Optional[str] = None) -> "list[int]":
    """OpenSees region tags with a recorded per-region energy balance.

    The bridge auto-allocates an integer region tag when a Ladruno
    recorder is given ``energy_pg=`` (or a value filter + ``energy``);
    that tag is opaque to the author. This lists the tags actually
    present in ``ON_REGIONS/energyBalance`` so you can pick one to pass
    to :meth:`energy` — e.g. ``r.energy(region=r.energy_regions()[0])``.

    Returns ``[]`` when only the whole-model balance was recorded
    (read it with ``energy()``, no ``region=``). Ladruno-recorder
    feature; raises :class:`TypeError` on MPCO / native results.
    """
    available = getattr(self._reader, "available_energy_regions", None)
    if available is None:
        raise TypeError(
            "Results.energy_regions() is a Ladruno-recorder feature. "
            "Open a .ladruno via Results.from_ladruno(...); MPCO / "
            "native results carry no energy balance."
        )
    sid = self._resolve_stage(stage)
    return available(sid)

node_envelope

node_envelope(component: str, *, stage: Optional[str] = None) -> 'Any'

Per-node time-reduced extremes — Ladruno -envelope feature.

When a .ladruno is recorded with the recorder's -envelope flag, each node channel stores componentwise running extremes (MIN/MAX/ABSMAX and the step at which the abs-extreme occurred) instead of a time series — the cheap way to capture peak response over a long run without keeping every step.

Returns a :class:pandas.DataFrame indexed by node id with columns min / max / absmax / arg_step for component (a neutral name like "displacement_x"). Raises :class:TypeError on a non-Ladruno results object, and :class:ValueError if the file was not recorded with -envelope or the component is absent.

results.plot.node_envelope(...) paints a chosen measure on the mesh as a matplotlib figure.

Source code in src/apeGmsh/results/Results.py
def node_envelope(
    self,
    component: str,
    *,
    stage: Optional[str] = None,
) -> "Any":
    """Per-node time-reduced extremes — **Ladruno ``-envelope`` feature**.

    When a ``.ladruno`` is recorded with the recorder's ``-envelope``
    flag, each node channel stores componentwise running extremes
    (``MIN``/``MAX``/``ABSMAX`` and the step at which the abs-extreme
    occurred) *instead of* a time series — the cheap way to capture peak
    response over a long run without keeping every step.

    Returns a :class:`pandas.DataFrame` indexed by node id with columns
    ``min`` / ``max`` / ``absmax`` / ``arg_step`` for ``component`` (a
    neutral name like ``"displacement_x"``). Raises :class:`TypeError`
    on a non-Ladruno results object, and :class:`ValueError` if the file
    was not recorded with ``-envelope`` or the component is absent.

    ``results.plot.node_envelope(...)`` paints a chosen measure on
    the mesh as a matplotlib figure.
    """
    read_node_envelope = getattr(self._reader, "read_node_envelope", None)
    if read_node_envelope is None:
        raise TypeError(
            "Results.node_envelope() is a Ladruno-recorder feature. Open "
            "a single-file .ladruno via Results.from_ladruno(...) recorded "
            "with the '-envelope' flag. (MPCO / native results and "
            "partitioned .ladruno envelope merges are not supported.)"
        )
    sid = self._resolve_stage(stage)
    env = read_node_envelope(sid, component)
    import pandas as pd
    return pd.DataFrame(
        {
            "min": env.min,
            "max": env.max,
            "absmax": env.absmax,
            "arg_step": env.arg_step,
        },
        index=pd.Index(env.node_ids, name="node_id"),
    )

bind

bind(fem: 'FEMData') -> 'Results'

Re-bind to fem.

Useful when you've re-built the same mesh in a fresh session and want labels / Parts that the embedded snapshot doesn't carry. No hash validation is performed — pairing the FEMData with a results file from the same run is the user's responsibility.

Source code in src/apeGmsh/results/Results.py
def bind(self, fem: "FEMData") -> "Results":
    """Re-bind to ``fem``.

    Useful when you've re-built the same mesh in a fresh session
    and want labels / Parts that the embedded snapshot doesn't
    carry. No hash validation is performed — pairing the FEMData
    with a results file from the same run is the user's
    responsibility.
    """
    bound = _resolve_fem(self._reader, fem)
    return self._derive(fem=bound)

stage

stage(name_or_id: str) -> 'Results'

Return a Results scoped to a stage (matched by id or name).

Source code in src/apeGmsh/results/Results.py
def stage(self, name_or_id: str) -> "Results":
    """Return a Results scoped to a stage (matched by id or name)."""
    info = self._lookup_stage(name_or_id)
    return self._derive(stage_id=info.id)

close

close() -> None

Close the underlying reader (releases the HDF5 file handle).

Source code in src/apeGmsh/results/Results.py
def close(self) -> None:
    """Close the underlying reader (releases the HDF5 file handle)."""
    if hasattr(self._reader, "close"):
        self._reader.close()

demo classmethod

demo(**kwargs) -> 'Results'

Return a ready-to-view demo :class:Results (cantilever pushover).

Zero-setup sample data so Results.demo().show_web() (or .viewer()) renders without supplying an .mpco / model.h5 pair — handy for docs, smoke tests, and trying the viewer. A real apeSees-emitted model with a synthetic, ramped cantilever deflection (no OpenSees solve). See :func:apeGmsh.results.make_demo_results for the keyword options (length / n_elements / n_steps / tip_drift / path).

Source code in src/apeGmsh/results/Results.py
@classmethod
def demo(cls, **kwargs) -> "Results":
    """Return a ready-to-view demo :class:`Results` (cantilever pushover).

    Zero-setup sample data so ``Results.demo().show_web()`` (or
    ``.viewer()``) renders without supplying an ``.mpco`` /
    ``model.h5`` pair — handy for docs, smoke tests, and trying the
    viewer. A real ``apeSees``-emitted model with a synthetic, ramped
    cantilever deflection (no OpenSees solve). See
    :func:`apeGmsh.results.make_demo_results` for the keyword options
    (``length`` / ``n_elements`` / ``n_steps`` / ``tip_drift`` /
    ``path``).
    """
    from .demo import make_demo_results
    return make_demo_results(**kwargs)

assess

assess(*, figures: bool = False, out_dir: 'str | Path | None' = None) -> 'AssessmentReport'

Compile a v1 :class:~apeGmsh.assess.AssessmentReport.

figures=True calls :meth:render_pack. Default is False.

Source code in src/apeGmsh/results/Results.py
def assess(
    self,
    *,
    figures: bool = False,
    out_dir: "str | Path | None" = None,
) -> "AssessmentReport":
    """Compile a v1 :class:`~apeGmsh.assess.AssessmentReport`.

    ``figures=True`` calls :meth:`render_pack`. Default is ``False``.
    """
    from apeGmsh.assess import assess_results
    return assess_results(self, figures=figures, out_dir=out_dir)

session

session()

The presentation session for these results (ADR 0098 §1).

Presentation with no window: a ResultsSession (from apeGmsh.results.session) bound to this broker, booted with the default picture — ONE empty mesh view (grey analysis mesh, no slots, no legends). Configure it (slots, deform, time), then s.render("a.png") for a still; the Qt client (s.show()) arrives at S2 and viewer() flips onto it at S6.

Persisted section cuts boot as view clips (ADR 0098 S6b). The retired section_cut diagram kind took its auto-load contract with it, but not the contract itself: cuts persisted under /opensees/cuts/ come back on the booted view as clips. Only the ones that translate honestly do — a cut that named a strict subset of the model's elements, or that carries a bounding polygon, cuts LESS than a view clip does, so it is skipped with one [session] line rather than silently widening what disappears from the screen. Reading the cuts can never fail this call: a bad zone is a line, not a traceback.

Source code in src/apeGmsh/results/Results.py
def session(self):
    """The presentation session for these results (ADR 0098 §1).

    Presentation with no window: a ``ResultsSession`` (from
    ``apeGmsh.results.session``) bound to this broker, booted with
    the default picture — ONE empty mesh view (grey analysis mesh,
    no slots, no legends). Configure it (slots, deform, time), then
    ``s.render("a.png")`` for a still; the Qt client (``s.show()``)
    arrives at S2 and ``viewer()`` flips onto it at S6.

    **Persisted section cuts boot as view clips** (ADR 0098 S6b).
    The retired ``section_cut`` diagram kind took its auto-load
    contract with it, but not the contract itself: cuts persisted
    under ``/opensees/cuts/`` come back on the booted view as
    clips. Only the ones that translate honestly do — a cut that
    named a strict subset of the model's elements, or that carries
    a bounding polygon, cuts LESS than a view clip does, so it is
    skipped with one ``[session]`` line rather than silently
    widening what disappears from the screen. Reading the cuts can
    never fail this call: a bad zone is a line, not a traceback.
    """
    from .session import ResultsSession
    from .session._cuts import attach_persisted_cuts

    s = ResultsSession(results=self)
    view = s.add_view()
    try:
        notices = attach_persisted_cuts(self, view)
    except Exception as exc:  # noqa: BLE001 - the session always boots
        notices = (
            f"persisted section cuts could not be loaded as view "
            f"clips: {type(exc).__name__}: {exc}",
        )
    for notice in notices:
        print(f"[session] {notice}")
    return s

viewer

viewer(*, blocking: 'Optional[bool]' = None, title: Optional[str] = None, restore_session: 'bool | str' = 'prompt', save_session: bool = True)

Open the post-solve results window on a ResultsSession.

Sugar for :meth:session + show() (ADR 0098 §1, flipped at S6a). The one-liner is unchanged; what it opens is not. A :class:~apeGmsh.results.session.ResultsSession is the document — tiled mesh and plot panes, each with the closed §4 slot catalog — and the window is a client that projects it. The retired Geometry / Composition / Diagram window is gone from this door. Everything the window does, a script can do to the same object::

s = results.session()   # the document, no window
s.render("a.png")       # a still, no Qt
results.viewer()        # the human one-liner
Parameters

blocking None (default) — auto: True in scripts and the plain CLI, False inside a Jupyter / IPython ZMQ kernel, where the blocking Qt loop would freeze (often kill) the kernel. An in-memory Results in a notebook cannot spawn a subprocess and falls back to :meth:show_web. Either notebook path announces itself with one line. True — open the window in-process and block the calling thread until it closes. Matches the signature of :meth:g.mesh.viewer and :meth:g.model.viewer. False — spawn a subprocess via python -m apeGmsh.viewers <path> so the notebook / kernel can keep running. Requires that the Results was opened from disk (self._path is set); raises :class:RuntimeError for in-memory Results. title Optional window title; defaults to "Results — <filename>". restore_session What to do with a session snapshot saved beside the results file. True restores silently, False ignores it, "prompt" (default) asks. No effect for in-memory Results, which have no file to sit beside. save_session If True (default), the session — panes, slots, pose, time link, selection — is written to <results>.viewer-session.json when the window closes. False disables auto-save. Auto-save also disarms itself for a window that could not read an existing file there, so the unreadable file survives (INV-SESSION-OPEN, see apeGmsh.results.session._boot).

Returns

ResultsSession The session the window projected, after the window closes (blocking). Still live: query it, render stills off it, snapshot it. subprocess.Popen The spawned process handle (non-blocking). Deliberately not unified with the blocking return — a session in this process is not what the child window is showing. WebViewer The :meth:show_web handle (auto mode, in-memory Results in a notebook). The web client is a later client of the same session; until it lands this hatch keeps today's path. None If APEGMSH_SKIP_VIEWER is set in the environment. This lets the same cell run under jupyter nbconvert --execute or in CI without spawning a GUI window.

Notes

The v13 <results>.viewer-session.json written by the retired window is not restorable (ADR 0098 Consequences). The first flipped open says so in one line and renames it aside to .legacy — never overwriting it, and never overwriting an aside that is already there.

cuts= is retired with the diagram ontology (§1): a cut plane is clip state on a view. Build cuts with :mod:apeGmsh.cuts and add them as clips — results.session() then view.add_clip.

Source code in src/apeGmsh/results/Results.py
def viewer(
    self,
    *,
    blocking: "Optional[bool]" = None,
    title: Optional[str] = None,
    restore_session: "bool | str" = "prompt",
    save_session: bool = True,
):
    """Open the post-solve results window on a ``ResultsSession``.

    Sugar for :meth:`session` + ``show()`` (ADR 0098 §1, flipped at
    S6a). The one-liner is unchanged; what it opens is not. A
    :class:`~apeGmsh.results.session.ResultsSession` is the
    document — tiled mesh and plot panes, each with the closed §4
    slot catalog — and the window is a client that projects it. The
    retired Geometry / Composition / Diagram window is gone from
    this door. Everything the window does, a script can do to the
    same object::

        s = results.session()   # the document, no window
        s.render("a.png")       # a still, no Qt
        results.viewer()        # the human one-liner

    Parameters
    ----------
    blocking
        ``None`` (default) — auto: ``True`` in scripts and the
        plain CLI, ``False`` inside a Jupyter / IPython ZMQ kernel,
        where the blocking Qt loop would freeze (often kill) the
        kernel. An in-memory Results in a notebook cannot spawn a
        subprocess and falls back to :meth:`show_web`. Either
        notebook path announces itself with one line.
        ``True`` — open the window in-process and block the calling
        thread until it closes. Matches the signature of
        :meth:`g.mesh.viewer` and :meth:`g.model.viewer`.
        ``False`` — spawn a subprocess via
        ``python -m apeGmsh.viewers <path>`` so the notebook /
        kernel can keep running. Requires that the Results was
        opened from disk (``self._path`` is set); raises
        :class:`RuntimeError` for in-memory Results.
    title
        Optional window title; defaults to ``"Results — <filename>"``.
    restore_session
        What to do with a session snapshot saved beside the results
        file. ``True`` restores silently, ``False`` ignores it,
        ``"prompt"`` (default) asks. No effect for in-memory
        Results, which have no file to sit beside.
    save_session
        If ``True`` (default), the session — panes, slots, pose,
        time link, selection — is written to
        ``<results>.viewer-session.json`` when the window closes.
        ``False`` disables auto-save. Auto-save also disarms itself
        for a window that could not read an existing file there, so
        the unreadable file survives (INV-SESSION-OPEN, see
        ``apeGmsh.results.session._boot``).

    Returns
    -------
    ResultsSession
        The session the window projected, **after** the window
        closes (blocking). Still live: query it, render stills off
        it, snapshot it.
    subprocess.Popen
        The spawned process handle (non-blocking). Deliberately not
        unified with the blocking return — a session in this
        process is not what the child window is showing.
    WebViewer
        The :meth:`show_web` handle (auto mode, in-memory Results
        in a notebook). The web client is a later client of the
        same session; until it lands this hatch keeps today's path.
    None
        If ``APEGMSH_SKIP_VIEWER`` is set in the environment. This
        lets the same cell run under ``jupyter nbconvert --execute``
        or in CI without spawning a GUI window.

    Notes
    -----
    The v13 ``<results>.viewer-session.json`` written by the retired
    window is not restorable (ADR 0098 Consequences). The first
    flipped open says so in one line and renames it aside to
    ``.legacy`` — never overwriting it, and never overwriting an
    aside that is already there.

    ``cuts=`` is retired with the diagram ontology (§1): a cut plane
    is clip state on a view. Build cuts with :mod:`apeGmsh.cuts` and
    add them as clips — ``results.session()`` then ``view.add_clip``.
    """
    import os
    if os.environ.get("APEGMSH_SKIP_VIEWER"):
        print("[skip viewer] APEGMSH_SKIP_VIEWER set")
        return None
    if blocking is None:
        if not _in_notebook_kernel():
            blocking = True
        elif self._path is None:
            print(
                "[viewer] notebook kernel detected and this Results "
                "is in-memory — opening the web viewer instead of "
                "blocking the kernel (pass blocking=True to force "
                "the Qt window)."
            )
            return self.show_web()
        else:
            print(
                "[viewer] notebook kernel detected — spawning the "
                "viewer as a separate process so the kernel keeps "
                "running (pass blocking=True to open it in-process)."
            )
            blocking = False
    if not blocking:
        handle = self._spawn_viewer_subprocess(
            title=title,
            restore_session=restore_session,
            save_session=save_session,
        )
        # The subprocess opens its own NativeReader against the
        # path; the parent kernel's reader is no longer needed for
        # rendering. Close it here so the user can re-run a capture
        # script (which deletes / recreates the same .h5) without
        # hitting ``PermissionError: file is being used by another
        # process`` — Windows refuses to unlink a file that any
        # process has open, even read-only.
        #
        # If the user wants to keep querying ``results`` after the
        # spawn, they can re-bind via ``Results.from_native(path)``.
        try:
            self.close()
        except Exception:
            pass
        return handle
    return self._show_session_window(
        title=title,
        restore_session=restore_session,
        save_session=save_session,
    )

render

render(path: 'str | Path', *, view: str = 'contour', component: Optional[str] = None, step: int = -1, deform: 'Optional[Any]' = None, camera: 'Optional[str]' = None, window_size: tuple[int, int] = (1280, 720)) -> 'Optional[Path]'

Write one offscreen still (ADR 0094 S1).

VTK offscreen from the viewer scene / diagram pipeline — no Qt window, no event loop, no setup(plotter, director). view is a closed set: mesh / contour / deformed / reactions.

camera= defaults to xy for a planar model, iso otherwise (ADR 0094 Amendment 3); pass it explicitly to override.

Returns the written :class:~pathlib.Path, or None (and prints the [skip viewer] notice) under APEGMSH_SKIP_VIEWER=1 or with no GL.

Source code in src/apeGmsh/results/Results.py
def render(
    self,
    path: "str | Path",
    *,
    view: str = "contour",
    component: Optional[str] = None,
    step: int = -1,
    deform: "Optional[Any]" = None,
    camera: "Optional[str]" = None,
    window_size: tuple[int, int] = (1280, 720),
) -> "Optional[Path]":
    """Write one offscreen still (ADR 0094 S1).

    VTK offscreen from the viewer scene / diagram pipeline — no
    Qt window, no event loop, no ``setup(plotter, director)``.
    ``view`` is a closed set: ``mesh`` / ``contour`` / ``deformed``
    / ``reactions``.

    ``camera=`` defaults to ``xy`` for a planar model, ``iso``
    otherwise (ADR 0094 Amendment 3); pass it explicitly to
    override.

    Returns the written :class:`~pathlib.Path`, or ``None`` (and
    prints the ``[skip viewer]`` notice) under
    ``APEGMSH_SKIP_VIEWER=1`` or with no GL.
    """
    from apeGmsh.viewers.render import render_results
    return render_results(
        self, path,
        view=view, component=component, step=step,
        deform=deform, camera=camera, window_size=window_size,
    )

render_pack

render_pack(out_dir: 'str | Path', *, camera: 'Optional[str]' = None, window_size: tuple[int, int] = (1280, 720)) -> tuple[Path, ...]

Write the canned report pack (ADR 0094 S3).

Returns the tuple of written paths, or () under APEGMSH_SKIP_VIEWER=1 / no GL (and prints the [skip viewer] notice). Closed view= set only; no setup(). There is no fem.render_pack.

camera= defaults to xy for a planar model, iso otherwise (ADR 0094 Amendment 3); pass it explicitly to override.

Source code in src/apeGmsh/results/Results.py
def render_pack(
    self,
    out_dir: "str | Path",
    *,
    camera: "Optional[str]" = None,
    window_size: tuple[int, int] = (1280, 720),
) -> tuple[Path, ...]:
    """Write the canned report pack (ADR 0094 S3).

    Returns the tuple of written paths, or ``()`` under
    ``APEGMSH_SKIP_VIEWER=1`` / no GL (and prints the
    ``[skip viewer]`` notice). Closed ``view=`` set only; no
    ``setup()``. There is no ``fem.render_pack``.

    ``camera=`` defaults to ``xy`` for a planar model, ``iso``
    otherwise (ADR 0094 Amendment 3); pass it explicitly to
    override.
    """
    from apeGmsh.viewers.render import render_pack as _render_pack
    return _render_pack(
        self, out_dir, camera=camera, window_size=window_size,
    )

export_animation

export_animation(path: 'str | Any', *, fps: int = 30, step_stride: int = 1, stage: 'Optional[str]' = None, deform: 'Optional[Any]' = None, camera: 'Optional[Any]' = None, window_size: 'Optional[tuple[int, int]]' = (1280, 720), setup: 'Optional[Any]' = None)

Render the time history to a video / GIF without a GUI session.

Builds the full results viewer off-screen (so deformation, contours, camera, and theming are pixel-identical to the interactive viewer), walks every step capturing a frame, and encodes to the format chosen by path's suffix — .mp4 (H.264, needs the apegmsh[animation] extra) or .gif (Pillow, no extra). The viewer window is shown briefly while rendering (the OpenGL context requires a realized surface) but no blocking event loop is entered.

Parameters

path Output file. Suffix selects the format (.mp4 / .gif). fps Frames per second of the output. step_stride Capture every N-th step (plus always the last). Useful to keep long histories short. stage Stage id/name to animate. Defaults to the active stage. deform Deformed-shape scaling. A number applies that scale to the "displacement" field; a (field, scale) pair selects another field. None (default) renders the undeformed mesh. camera Optional value assigned to plotter.camera_position (e.g. "iso", "xy", or an explicit position triple) before rendering. None keeps the auto-framed camera. window_size (width, height) of the rendered frames. None keeps the viewer's default size. setup Optional callback(plotter, director) invoked after the scene is built and before capture — the escape hatch for adding contours / section cuts / custom camera work via the same APIs the interactive viewer uses.

Returns

pathlib.Path The resolved output path, or None when APEGMSH_SKIP_VIEWER is set in the environment.

Source code in src/apeGmsh/results/Results.py
def export_animation(
    self,
    path: "str | Any",
    *,
    fps: int = 30,
    step_stride: int = 1,
    stage: "Optional[str]" = None,
    deform: "Optional[Any]" = None,
    camera: "Optional[Any]" = None,
    window_size: "Optional[tuple[int, int]]" = (1280, 720),
    setup: "Optional[Any]" = None,
):
    """Render the time history to a video / GIF without a GUI session.

    Builds the full results viewer off-screen (so deformation,
    contours, camera, and theming are pixel-identical to the
    interactive viewer), walks every step capturing a frame, and
    encodes to the format chosen by ``path``'s suffix — ``.mp4``
    (H.264, needs the ``apegmsh[animation]`` extra) or ``.gif``
    (Pillow, no extra). The viewer window is shown briefly while
    rendering (the OpenGL context requires a realized surface) but
    no blocking event loop is entered.

    Parameters
    ----------
    path
        Output file. Suffix selects the format (``.mp4`` / ``.gif``).
    fps
        Frames per second of the output.
    step_stride
        Capture every N-th step (plus always the last). Useful to
        keep long histories short.
    stage
        Stage id/name to animate. Defaults to the active stage.
    deform
        Deformed-shape scaling. A number applies that scale to the
        ``"displacement"`` field; a ``(field, scale)`` pair selects
        another field. ``None`` (default) renders the undeformed
        mesh.
    camera
        Optional value assigned to ``plotter.camera_position`` (e.g.
        ``"iso"``, ``"xy"``, or an explicit position triple) before
        rendering. ``None`` keeps the auto-framed camera.
    window_size
        ``(width, height)`` of the rendered frames. ``None`` keeps
        the viewer's default size.
    setup
        Optional ``callback(plotter, director)`` invoked after the
        scene is built and before capture — the escape hatch for
        adding contours / section cuts / custom camera work via the
        same APIs the interactive viewer uses.

    Returns
    -------
    pathlib.Path
        The resolved output path, or ``None`` when
        ``APEGMSH_SKIP_VIEWER`` is set in the environment.
    """
    import os
    if os.environ.get("APEGMSH_SKIP_VIEWER"):
        print("[skip viewer] APEGMSH_SKIP_VIEWER set")
        return None
    from ..viewers.results_viewer import ResultsViewer

    viewer = ResultsViewer(
        self, restore_session=False, save_session=False,
    )
    # Borrow this live Results — don't close its HDF5 handle on
    # teardown (the caller keeps using it). Set BEFORE show() so a
    # build failure that triggers teardown still leaves it open.
    viewer._own_results_close = False  # noqa: SLF001
    try:
        # show() is inside the try so a failed off-screen realize
        # (GL / pixel-format error) still hits ``viewer.close()`` —
        # otherwise a half-built, possibly-visible window leaks.
        viewer.show(run_loop=False, window_size=window_size)
        director = viewer.director
        plotter = viewer.plotter
        if stage is not None:
            director.set_stage(stage)
        if deform is not None:
            if isinstance(deform, (tuple, list)):
                d_field, d_scale = deform[0], float(deform[1])
            else:
                d_field, d_scale = "displacement", float(deform)
            geoms = director.geometries
            active = geoms.active or (
                geoms.geometries[0] if geoms.geometries else None
            )
            if active is not None:
                geoms.set_deformation(
                    active.id, enabled=True,
                    field=d_field, scale=d_scale,
                )
        if camera is not None:
            try:
                plotter.camera_position = camera
            except Exception:
                pass
        if setup is not None:
            setup(plotter, director)
        return viewer.export_animation(
            path, fps=fps, step_stride=step_stride,
        )
    finally:
        viewer.close()

show_web

show_web(*, stage: 'Optional[str]' = None, show: bool = True, controls: bool = True, render_mode: str = 'client')

Open the view-only web / Jupyter results viewer (ADR 0042 R-C).

Renders the FEM substrate plus any diagrams the director holds through a pyvista.trame backend — the kernel-safe path that replaces the blocking Qt :meth:viewer in a notebook. View-only (picking is deferred to R-D), but with a step slider + per-layer visibility checkboxes when ipywidgets is available.

No results file handy? Results.demo().show_web() renders a zero-setup cantilever-pushover sample.

Parameters

stage Stage id or name to activate; defaults to the first stage. show When True (default), display inline immediately. When False, return the :class:~apeGmsh.viewers.web_viewer.WebViewer unshown so diagrams can be added via viewer.director first. controls When True (default), stack an ipywidgets control panel (step slider + layer toggles) above the view. Degrades to a bare view if ipywidgets is absent. render_mode "client" (default) renders in the browser via WebGL — fast camera interaction. "server" renders on the kernel and streams images (laggy, most VTK-feature-complete; for very large models). "hybrid" is pyvista's trame backend with a local/remote toggle in the toolbar.

Returns

WebViewer The viewer handle (.director / .set_step / .show).

Source code in src/apeGmsh/results/Results.py
def show_web(
    self,
    *,
    stage: "Optional[str]" = None,
    show: bool = True,
    controls: bool = True,
    render_mode: str = "client",
):
    """Open the view-only web / Jupyter results viewer (ADR 0042 R-C).

    Renders the FEM substrate plus any diagrams the director holds
    through a ``pyvista.trame`` backend — the kernel-safe path that
    replaces the blocking Qt :meth:`viewer` in a notebook. View-only
    (picking is deferred to R-D), but with a step slider + per-layer
    visibility checkboxes when ``ipywidgets`` is available.

    No results file handy? ``Results.demo().show_web()`` renders a
    zero-setup cantilever-pushover sample.

    Parameters
    ----------
    stage
        Stage id or name to activate; defaults to the first stage.
    show
        When ``True`` (default), display inline immediately. When
        ``False``, return the :class:`~apeGmsh.viewers.web_viewer.WebViewer`
        unshown so diagrams can be added via ``viewer.director`` first.
    controls
        When ``True`` (default), stack an ``ipywidgets`` control panel
        (step slider + layer toggles) above the view. Degrades to a
        bare view if ``ipywidgets`` is absent.
    render_mode
        ``"client"`` (default) renders in the browser via WebGL — fast
        camera interaction. ``"server"`` renders on the kernel and
        streams images (laggy, most VTK-feature-complete; for very
        large models). ``"hybrid"`` is pyvista's ``trame`` backend with
        a local/remote toggle in the toolbar.

    Returns
    -------
    WebViewer
        The viewer handle (``.director`` / ``.set_step`` / ``.show``).
    """
    from ..viewers.web_viewer import show_web as _show_web
    return _show_web(
        self, stage=stage, show=show, controls=controls,
        render_mode=render_mode,
    )

serve_web

serve_web(*, stage: 'Optional[str]' = None, render_mode: str = 'client', port: 'Optional[int]' = None, open_browser: bool = True, title: str = 'apeGmsh', **start_kwargs)

Serve the results as a standalone trame web app (ADR 0042 R-C).

The non-Jupyter counterpart of :meth:show_web: builds a vuetify3 single-page app (the FEM view plus a step slider and per-layer switches) and serves it at a local URL, opening a browser tab and blocking until stopped (Ctrl-C). In a notebook use :meth:show_web instead.

Parameters

stage Stage id or name to activate; defaults to the first stage. render_mode "client" (default), "server", or "hybrid" — see :meth:show_web. port Port to serve on; None lets trame pick one. open_browser Open a browser tab at the served URL. title App title shown in the toolbar. **start_kwargs Passed through to the trame server.start (e.g. exec_mode).

Returns

WebViewer The viewer handle.

Source code in src/apeGmsh/results/Results.py
def serve_web(
    self,
    *,
    stage: "Optional[str]" = None,
    render_mode: str = "client",
    port: "Optional[int]" = None,
    open_browser: bool = True,
    title: str = "apeGmsh",
    **start_kwargs,
):
    """Serve the results as a standalone trame web app (ADR 0042 R-C).

    The non-Jupyter counterpart of :meth:`show_web`: builds a vuetify3
    single-page app (the FEM view plus a step slider and per-layer
    switches) and serves it at a local URL, opening a browser tab and
    blocking until stopped (Ctrl-C). In a notebook use :meth:`show_web`
    instead.

    Parameters
    ----------
    stage
        Stage id or name to activate; defaults to the first stage.
    render_mode
        ``"client"`` (default), ``"server"``, or ``"hybrid"`` — see
        :meth:`show_web`.
    port
        Port to serve on; ``None`` lets trame pick one.
    open_browser
        Open a browser tab at the served URL.
    title
        App title shown in the toolbar.
    **start_kwargs
        Passed through to the trame ``server.start`` (e.g.
        ``exec_mode``).

    Returns
    -------
    WebViewer
        The viewer handle.
    """
    from ..viewers.web_viewer import serve_web as _serve_web
    return _serve_web(
        self, stage=stage, render_mode=render_mode, port=port,
        open_browser=open_browser, title=title, **start_kwargs,
    )

save_definitions

save_definitions(path: 'Optional[str | Path]' = None) -> Path

Persist this Results' custom scalar definitions to a JSON sidecar (default <results>.defs.json).

Reloaded automatically by :meth:from_native / :meth:from_mpco / :meth:from_ladruno, and carried to the subprocess viewer. Raises for an in-memory Results with no path= given.

Source code in src/apeGmsh/results/Results.py
def save_definitions(self, path: "Optional[str | Path]" = None) -> Path:
    """Persist this Results' custom scalar definitions to a JSON
    sidecar (default ``<results>.defs.json``).

    Reloaded automatically by :meth:`from_native` / :meth:`from_mpco`
    / :meth:`from_ladruno`, and carried to the subprocess viewer.
    Raises for an in-memory Results with no ``path=`` given.
    """
    import json
    if path is None:
        if self._path is None:
            raise RuntimeError(
                "in-memory Results has no default sidecar path; "
                "pass save_definitions(path=...)."
            )
        path = self._default_defs_path(self._path)
    path = Path(path)
    path.write_text(
        json.dumps(self._definitions_payload(), indent=2), encoding="utf-8",
    )
    return path

load_definitions

load_definitions(path: 'Optional[str | Path]' = None) -> int

Load and register custom scalar definitions from a JSON sidecar (default <results>.defs.json). Returns the count applied; a missing file is a no-op returning 0. Idempotent / best-effort — see :meth:_apply_definitions_payload.

Source code in src/apeGmsh/results/Results.py
def load_definitions(self, path: "Optional[str | Path]" = None) -> int:
    """Load and register custom scalar definitions from a JSON sidecar
    (default ``<results>.defs.json``). Returns the count applied; a
    missing file is a no-op returning 0. Idempotent / best-effort —
    see :meth:`_apply_definitions_payload`."""
    import json
    if path is None:
        if self._path is None:
            return 0
        path = self._default_defs_path(self._path)
    path = Path(path)
    if not path.exists():
        return 0
    payload = json.loads(path.read_text(encoding="utf-8"))
    return self._apply_definitions_payload(payload)

Numberer

Numberer(fem_data: dict)

Renumbers a FEM mesh for solver consumption.

Parameters

fem_data : dict Output of Mesh.get_fem_data(). Must contain: node_tags, node_coords, elem_tags, connectivity, used_tags.

Source code in src/apeGmsh/mesh/_numberer.py
def __init__(self, fem_data: dict) -> None:
    self._node_tags   = np.asarray(fem_data['node_tags'], dtype=int)
    self._node_coords = np.asarray(fem_data['node_coords'], dtype=float)
    self._elem_tags   = np.asarray(fem_data['elem_tags'], dtype=int)
    self._connectivity = np.asarray(fem_data['connectivity'], dtype=int)
    self._used_tags   = fem_data.get('used_tags', set(self._connectivity.flatten()))

renumber

renumber(method: str = 'simple', *, base: int = 1, used_only: bool = True) -> NumberedMesh

Produce a solver-ready mesh with contiguous IDs.

Parameters

method : "simple" or "rcm" "simple" — preserves relative order, just makes IDs contiguous. Fast, no optimisation.

``"rcm"``  — Reverse Cuthill-McKee bandwidth minimisation.
Reorders nodes so that the assembled stiffness matrix has
minimal bandwidth.  Recommended for direct solvers.
int

Starting ID (default 1 = Fortran/OpenSees convention; use 0 for C/Python convention).

bool

If True (default), only include nodes that appear in at least one element (skip orphan nodes). Set False to include all nodes from the mesh.

Returns

NumberedMesh

Source code in src/apeGmsh/mesh/_numberer.py
def renumber(
    self,
    method: str = "simple",
    *,
    base: int = 1,
    used_only: bool = True,
) -> NumberedMesh:
    """
    Produce a solver-ready mesh with contiguous IDs.

    Parameters
    ----------
    method : ``"simple"`` or ``"rcm"``
        ``"simple"``  — preserves relative order, just makes IDs
        contiguous.  Fast, no optimisation.

        ``"rcm"``  — Reverse Cuthill-McKee bandwidth minimisation.
        Reorders nodes so that the assembled stiffness matrix has
        minimal bandwidth.  Recommended for direct solvers.

    base : int
        Starting ID (default 1 = Fortran/OpenSees convention;
        use 0 for C/Python convention).

    used_only : bool
        If True (default), only include nodes that appear in at
        least one element (skip orphan nodes).  Set False to
        include all nodes from the mesh.

    Returns
    -------
    NumberedMesh
    """
    # ── Filter nodes ──────────────────────────────────────────
    if used_only:
        mask = np.isin(self._node_tags, list(self._used_tags))
        n_total   = len(self._node_tags)
        gmsh_tags = self._node_tags[mask]
        coords    = self._node_coords[mask]
        n_orphans = n_total - len(gmsh_tags)
        if n_orphans > 0:
            orphan_tags = self._node_tags[~mask]
            print(
                f"[Numberer] WARNING: {n_orphans} orphan node(s) "
                f"skipped (not connected to any element). "
                f"Tags: {orphan_tags.tolist()[:20]}"
                + (f" ... (+{n_orphans - 20} more)"
                   if n_orphans > 20 else "")
            )
    else:
        gmsh_tags = self._node_tags.copy()
        coords    = self._node_coords.copy()

    n_nodes = len(gmsh_tags)

    # ── Temporary 0-based indexing ────────────────────────────
    # Map Gmsh tags -> 0-based indices for internal work
    gtag_to_tmp: dict[int, int] = {
        int(t): i for i, t in enumerate(gmsh_tags)
    }

    # Rewrite connectivity in 0-based tmp indices (vectorized)
    flat = self._connectivity.ravel()
    conn_tmp = np.array(
        [gtag_to_tmp[int(t)] for t in flat],
        dtype=int,
    ).reshape(self._connectivity.shape)

    # ── Compute permutation ───────────────────────────────────
    if method == "rcm":
        perm = _rcm_ordering(n_nodes, conn_tmp)
    elif method == "simple":
        perm = np.arange(n_nodes, dtype=int)
    else:
        raise ValueError(
            f"Unknown method '{method}'. Use 'simple' or 'rcm'."
        )

    # perm[new_pos] = old_pos
    # inverse: inv_perm[old_pos] = new_pos
    inv_perm = np.empty(n_nodes, dtype=int)
    inv_perm[perm] = np.arange(n_nodes)

    # ── Apply permutation ─────────────────────────────────────
    new_coords     = coords[perm]            # reordered coords

    # Rewrite connectivity with new IDs (vectorized)
    new_conn = inv_perm[conn_tmp] + base

    # Element IDs: simple contiguous
    new_elem_ids = np.arange(base, base + len(self._elem_tags), dtype=int)

    # ── Bandwidth ─────────────────────────────────────────────
    bw = _compute_bandwidth(new_conn)

    # ── Build maps ────────────────────────────────────────────
    g2s_node: dict[int, int] = {}
    s2g_node: dict[int, int] = {}
    for new_pos in range(n_nodes):
        old_pos = perm[new_pos]
        gtag = int(gmsh_tags[old_pos])
        sid  = int(inv_perm[old_pos]) + base
        g2s_node[gtag] = sid
        s2g_node[sid]  = gtag

    g2s_elem: dict[int, int] = {}
    s2g_elem: dict[int, int] = {}
    for i, etag in enumerate(self._elem_tags):
        eid = int(new_elem_ids[i])
        g2s_elem[int(etag)] = eid
        s2g_elem[eid]       = int(etag)

    # ── Rewrite node_ids array in order ───────────────────────
    # node_ids[i] = solver ID of the i-th node (in new ordering)
    solver_node_ids = np.arange(base, base + n_nodes, dtype=int)

    result = NumberedMesh(
        node_ids=solver_node_ids,
        node_coords=new_coords,
        elem_ids=new_elem_ids,
        connectivity=new_conn,
        n_nodes=n_nodes,
        n_elems=len(self._elem_tags),
        bandwidth=bw,
        method=method,
        gmsh_to_solver_node=g2s_node,
        solver_to_gmsh_node=s2g_node,
        gmsh_to_solver_elem=g2s_elem,
        solver_to_gmsh_elem=s2g_elem,
    )

    return result

compare_methods

compare_methods() -> dict[str, int]

Compare bandwidth for all available methods.

Returns

dict[str, int] {"simple": bw1, "rcm": bw2}

Source code in src/apeGmsh/mesh/_numberer.py
def compare_methods(self) -> dict[str, int]:
    """
    Compare bandwidth for all available methods.

    Returns
    -------
    dict[str, int]
        ``{"simple": bw1, "rcm": bw2}``
    """
    results = {}
    for method in ("simple", "rcm"):
        data = self.renumber(method=method)
        results[method] = data.bandwidth
    return results

NumberedMesh dataclass

NumberedMesh(node_ids: ndarray, node_coords: ndarray, elem_ids: ndarray, connectivity: ndarray, n_nodes: int = 0, n_elems: int = 0, bandwidth: int = 0, method: str = 'simple', gmsh_to_solver_node: dict[int, int] = dict(), solver_to_gmsh_node: dict[int, int] = dict(), gmsh_to_solver_elem: dict[int, int] = dict(), solver_to_gmsh_elem: dict[int, int] = dict())

Solver-ready mesh with contiguous IDs and bidirectional maps.

All IDs are 1-based (the standard in structural FEM solvers like OpenSees, Abaqus, SAP2000). Set base=0 in :meth:Numberer.renumber for 0-based if your solver needs it.

Attributes

node_ids : ndarray(N,) New contiguous node IDs. node_coords : ndarray(N, 3) Nodal coordinates, same order as node_ids. elem_ids : ndarray(E,) New contiguous element IDs. connectivity : ndarray(E, npe) Element connectivity in terms of new node IDs. n_nodes : int n_elems : int bandwidth : int Semi-bandwidth of the resulting adjacency. method : str Numbering method used ("simple" or "rcm").

Maps ~~~~ gmsh_to_solver_node : dict[int, int] Gmsh node tag -> solver node ID. solver_to_gmsh_node : dict[int, int] Solver node ID -> Gmsh node tag. gmsh_to_solver_elem : dict[int, int] Gmsh element tag -> solver element ID. solver_to_gmsh_elem : dict[int, int] Solver element ID -> Gmsh element tag.

summary

summary() -> str

One-line summary string.

Source code in src/apeGmsh/mesh/_numberer.py
def summary(self) -> str:
    """One-line summary string."""
    return (
        f"NumberedMesh({self.method}): "
        f"{self.n_nodes} nodes, {self.n_elems} elements, "
        f"bandwidth={self.bandwidth}"
    )

RenumberResult

RenumberResult(method: str, n_nodes: int, n_elements: int, bandwidth_before: int, bandwidth_after: int)

Result of a mesh renumbering operation.

Attributes

method : str Algorithm used ("simple", "rcm", "hilbert", "metis"). n_nodes : int Number of nodes renumbered. n_elements : int Number of elements renumbered. bandwidth_before : int Semi-bandwidth before renumbering. bandwidth_after : int Semi-bandwidth after renumbering.

Source code in src/apeGmsh/mesh/_mesh_partitioning.py
def __init__(
    self,
    method: str,
    n_nodes: int,
    n_elements: int,
    bandwidth_before: int,
    bandwidth_after: int,
) -> None:
    self.method = method
    self.n_nodes = n_nodes
    self.n_elements = n_elements
    self.bandwidth_before = bandwidth_before
    self.bandwidth_after = bandwidth_after

PartitionInfo

PartitionInfo(n_parts: int, elements_per_partition: dict[int, int], weights_per_partition: dict[int, float] | None = None)

Result of a mesh partitioning operation.

Attributes

n_parts : int Number of partitions created. elements_per_partition : dict[int, int] {partition_id: element_count}. weights_per_partition : dict[int, float] | None {partition_id: total_weight} when partition() was called with weights=, otherwise None. Populated by _gather_partition_info() from the per-element weight vector cached on _Partitioning during the weighted call.

Source code in src/apeGmsh/mesh/_mesh_partitioning.py
def __init__(
    self,
    n_parts: int,
    elements_per_partition: dict[int, int],
    weights_per_partition: dict[int, float] | None = None,
) -> None:
    self.n_parts = n_parts
    self.elements_per_partition = elements_per_partition
    self.weights_per_partition = weights_per_partition

MeshViewer

MeshViewer(parent: '_SessionBase', *, dims: list[int] | None = None, point_size: float | None = None, line_width: float | None = None, surface_opacity: float | None = None, show_surface_edges: bool | None = None, origin_markers: list[tuple[float, float, float]] | None = None, origin_marker_show_coords: bool | None = None, view: 'ViewerData | None' = None, fast: bool = True, on_selection_changed: Callable[['SelectionState'], None] | None = None, **kwargs: Any)

Interactive mesh viewer with element/node picking.

Displays mesh elements and nodes with optional load, constraint, and mass overlays. Overlay data comes from a resolved :class:apeGmsh.viewers.data.ViewerData snapshot — either passed explicitly or auto-resolved from the session at show time.

Parameters

parent : _SessionBase The apeGmsh session. dims : list[int], optional Which mesh dimensions to show (default: [1, 2, 3]). point_size, line_width, surface_opacity, show_surface_edges Visual properties. view : ViewerData, optional Pre-resolved structural snapshot. If not provided, the viewer calls get_fem_data() automatically when the window opens and wraps the resulting FEMData. Phase 8.7 commit 6 renamed this kwarg from fem to view. fast : bool Ignored (always fast). Kept for backward compatibility. on_selection_changed : callable, optional callback(SelectionState) fired on every BREP pick change (ADR 0095 studio host). Dispatcher-legal owner mutator.

Source code in src/apeGmsh/viewers/mesh_viewer.py
def __init__(
    self,
    parent: "_SessionBase",
    *,
    dims: list[int] | None = None,
    point_size: float | None = None,
    line_width: float | None = None,
    surface_opacity: float | None = None,
    show_surface_edges: bool | None = None,
    origin_markers: list[tuple[float, float, float]] | None = None,
    origin_marker_show_coords: bool | None = None,
    view: "ViewerData | None" = None,
    fast: bool = True,
    on_selection_changed: Callable[["SelectionState"], None] | None = None,
    **kwargs: Any,
) -> None:
    from .ui.preferences_manager import PREFERENCES
    p = PREFERENCES.current

    self._parent = parent
    self._dims = dims if dims is not None else [1, 2, 3]

    # Mesh viewer keeps its own pref-sourced visual defaults. Explicit
    # kwarg still wins; falling back to the user's persisted preference
    # otherwise. Historic hard-coded fallbacks (6.0/3.0/1.0/True) match
    # ``Preferences``'s ``node_marker_size``/``line_width`` defaults.
    self._point_size = (
        point_size if point_size is not None else p.node_marker_size
    )
    self._line_width = (
        line_width if line_width is not None else p.mesh_line_width
    )
    self._surface_opacity = (
        surface_opacity if surface_opacity is not None
        else p.mesh_surface_opacity
    )
    self._show_surface_edges = (
        show_surface_edges if show_surface_edges is not None
        else p.mesh_show_surface_edges
    )

    # Origin marker overlay. User preference controls whether the
    # default is ``[(0,0,0)]`` or ``[]``; explicit kwarg wins.
    if origin_markers is not None:
        self._origin_markers: list[tuple[float, float, float]] = list(origin_markers)
    elif p.origin_marker_include_world_origin:
        self._origin_markers = [(0.0, 0.0, 0.0)]
    else:
        self._origin_markers = []
    self._origin_marker_show_coords = (
        origin_marker_show_coords if origin_marker_show_coords is not None
        else p.origin_marker_show_coords
    )
    self._view: "ViewerData | None" = view
    # ADR 0095 S2: host publishes a SelectionEnvelope on pick.
    self._on_selection_changed = on_selection_changed

    # Populated during show()
    self._selection_state: "SelectionState | None" = None
    self._scene_data: "MeshSceneData | None" = None

    # Runtime state (populated in show()) — pre-declared for clarity
    self._plotter: Any = None
    self._win: Any = None
    self._scene: "MeshSceneData | None" = None
    self._registry: "EntityRegistry | None" = None
    self._sel: "SelectionState | None" = None
    self._color_mgr: "ColorManager | None" = None
    self._vis_mgr: "VisibilityManager | None" = None
    self._pick_engine: "PickEngine | None" = None
    self._color_mode_ctrl: "ColorModeController | None" = None
    self._explode_ctrl: Any = None
    # Latest browser hide-set received while exploded (can't apply during
    # explosion — actor ids conflict). Replayed to the VisibilityManager
    # when explosion ends so the browser checkboxes don't silently desync.
    self._pending_browser_hidden: Any = None
    self._info_tab: "MeshInfoTab | None" = None
    self._mesh_tn_overlay: "MeshTangentNormalOverlay | None" = None

    # UI tabs (resolved after construction)
    self._display_tab: Any = None
    self._loads_tab: Any = None
    self._mass_tab: Any = None
    self._constraints_tab: Any = None

    # Mutable per-show state buckets
    self._label_actors: list = []
    self._load_actors: list = []
    self._mass_actors: list = []
    self._constraint_actors: list = []
    self._boundary_node_actors: list = []
    # Overlay glyph scales are OWNED by the OverlayVisibilityModel
    # (ADR 0056 V3) — read via self._overlay_model.scale(key).
    self._moment_template: Any = None
    self._pick_mode: list[str] = ["brep"]   # "brep", "element", "node"
    # ADR 0045 S3b: FE element/node picks live in a dedicated
    # SelectionState as MESH_TOPO targets (nodes dim=0, elements
    # dim=element-topo-dim), giving them undo/redo on the unified
    # target contract. Kept separate from ``_sel`` (BREP DimTags) so
    # the BREP ``.picks`` shim never sees a non-BREP target.
    self._fe_sel: "SelectionState | None" = None
    self._prev_hover: list[DimTag | None] = [None]
    self._hover_label: Any = None

    # Plan 04 step 3 — per-viewer ActiveObjects coordinator.
    # Populated by ``show()`` once a QApplication exists. Same
    # design as ``ResultsViewer._active``: a single source of
    # truth for "what is currently selected / which pick mode" so
    # panels subscribe instead of wiring direct callbacks.
    self._active: Any = None
    # Subscription handle for the SelectionState bridge; cleared
    # in ``_on_close``-equivalent paths.
    self._sel_bridge_unsub: Any = None

show

show(*, title: str | None = None, maximized: bool = True)

Open the viewer window, block until closed.

Source code in src/apeGmsh/viewers/mesh_viewer.py
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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
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
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
def show(self, *, title: str | None = None, maximized: bool = True):
    """Open the viewer window, block until closed."""
    from .core.navigation import install_navigation
    from .core.color_manager import ColorManager
    from .core.color_mode_controller import ColorModeController
    from .core.filter_controller import FilterController
    from .core.pick_engine import PickEngine
    from .core.visibility import VisibilityManager
    from .core.selection import SelectionState
    from .scene.mesh_scene import build_mesh_scene
    from .ui.viewer_window import ViewerWindow
    from .ui.preferences import PreferencesTab
    from .ui.mesh_tabs import MeshInfoTab, DisplayTab, MeshFilterTab
    from .ui.preferences_manager import PREFERENCES as _PREF
    from .ui.theme import THEME

    gmsh.model.occ.synchronize()

    self._dims = self._auto_filter_dims(self._dims)

    # ── Selection state ─────────────────────────────────────────
    sel = SelectionState()
    self._selection_state = sel
    self._sel = sel
    # FE-topology pick set (elements + nodes), ADR 0045 S3b.
    fe_sel = SelectionState()
    self._fe_sel = fe_sel
    fe_sel.on_changed.append(self._refresh_fe_status)

    # ── Window (creates QApplication) ───────────────────────────
    # ``window_key`` opts into layout persistence under
    # ``QSettings("apeGmsh", "MeshViewer")`` (plan 08 follow-up).
    # The Outline nav dock is registered HERE as a construction-time
    # extension dock with a cheap placeholder widget, so it is
    # present at saveState / restoreState time and participates in
    # layout persistence exactly like the built-in docks (which have
    # never gotten stuck). The real MeshOutlineTree — which needs
    # scene / selection state that doesn't exist yet — is swapped in
    # later via ``win.set_extension_dock_widget``. ``sanitize=True``
    # opts it into the per-launch degenerate-placement heal.
    from qtpy import QtWidgets as _QtW_outline
    from .ui._dock_registry import DockSpec
    from .ui._layout_metrics import LAYOUT
    default_title = f"MeshViewer — {self._parent.name}"
    win = ViewerWindow(
        title=title or default_title, window_key="MeshViewer",
        extension_docks=[DockSpec(
            dock_id="dock_mesh_outline",
            title="Outline",
            factory=lambda p: _QtW_outline.QWidget(p),
            default_area="left",
            sanitize=True,
            min_width=LAYOUT.outline_min_width,
            initial_width=LAYOUT.outline_initial_width,
            min_height=LAYOUT.outline_min_height,
            initial_height=LAYOUT.outline_initial_height,
        )],
    )
    self._win = win

    # ── Plan 04 step 3 — ActiveObjects coordinator ──────────────
    # One per viewer. Pick mode + selection get their canonical
    # signal surface here; existing per-instance state (the
    # ``_pick_mode[0]`` cache, ``sel.on_changed`` callbacks) stays
    # in lockstep via two bridges installed below.
    from .core._active_objects import ActiveObjects
    self._active = ActiveObjects(parent=win.window)
    # Pick mode bridge — subscribers update the legacy cache + the
    # status bar. ``_set_pick_mode`` now flows through
    # ``set_active_pick_mode``, so any future panel that wants to
    # react to pick-mode flips can subscribe to
    # ``activePickModeChanged`` without touching this file.
    self._active.activePickModeChanged.connect(self._on_active_pick_mode)
    # Seed the active pick mode with whatever the constructor /
    # __init__ set on the legacy cache (default "brep"). This keeps
    # ``self._active.active_pick_mode`` aligned with
    # ``_pick_mode[0]`` from the start — code that subscribes to
    # ``activePickModeChanged`` won't see a phantom "" state before
    # the first user key-press.
    try:
        self._active.set_active_pick_mode(self._pick_mode[0])
    except Exception:
        pass

    # ── UI tabs (AFTER QApplication exists) ─────────────────────
    info_tab = MeshInfoTab()
    self._info_tab = info_tab

    display_tab = DisplayTab(
        on_color_mode=self._on_color_mode,
        on_node_labels=self._toggle_node_labels,
        on_elem_labels=self._toggle_elem_labels,
        on_wireframe=self._toggle_wireframe,
        on_show_edges=self._toggle_edges,
        on_show_nodes=self._toggle_nodes,
        on_explode_axis=self._on_explode_axis,
    )
    self._display_tab = display_tab

    # FilterController (ADR 0045 S2) owns the active dimension set;
    # the checkbox panel and the 0/1/2/3/4 keys are two front-ends
    # writing it (INV-4). Built here (before the pick engine exists)
    # so the panel can route through it at construction; the fan-out
    # sink (on_change) is attached once pick_engine is live.
    self._filter = FilterController(self._dims)
    filter_tab = MeshFilterTab(
        self._dims,
        on_filter_changed=self._filter.set_active,
        on_mesh_probes_changed=self._on_mesh_probes_changed,
    )

    win.add_tab("Info", info_tab.widget)
    win.add_tab("Display", display_tab.widget)
    win.add_tab("Filter", filter_tab.widget)

    plotter = win.plotter
    self._plotter = plotter

    # ── Build scene ─────────────────────────────────────────────
    _verbose = getattr(self._parent, '_verbose', False)
    scene = build_mesh_scene(
        plotter, self._dims,
        line_width=self._line_width,
        surface_opacity=self._surface_opacity,
        show_surface_edges=self._show_surface_edges,
        node_marker_size=self._point_size,
        verbose=_verbose,
    )
    self._scene_data = scene
    self._scene = scene
    registry = scene.registry
    self._registry = registry

    # ── Hover tooltip overlay (Qt label on the plotter widget) ──
    from qtpy import QtWidgets as _QtW, QtCore as _QtC
    _interactor = getattr(plotter, "interactor", None)
    if _interactor is not None:
        self._hover_label = _QtW.QLabel(_interactor)
        self._hover_label.setStyleSheet(
            "QLabel { background-color: rgba(40, 40, 40, 220); "
            "color: #eee; padding: 4px 6px; border: 1px solid #555; "
            "border-radius: 3px; }"
        )
        self._hover_label.setAttribute(
            _QtC.Qt.WA_TransparentForMouseEvents
        )
        self._hover_label.hide()

    # ── Origin markers ──────────────────────────────────────────
    from .overlays.origin_markers_overlay import OriginMarkerOverlay
    from .ui.origin_markers_panel import OriginMarkersPanel
    _marker_size = _PREF.current.origin_marker_size
    origin_overlay = OriginMarkerOverlay(
        plotter,
        origin_shift=registry.origin_shift,
        model_diagonal=scene.model_diagonal,
        points=self._origin_markers,
        show_coords=self._origin_marker_show_coords,
        size=_marker_size,
    )
    origin_panel = OriginMarkersPanel(
        initial_points=self._origin_markers,
        initial_visible=True,
        initial_show_coords=self._origin_marker_show_coords,
        initial_size=_marker_size,
        on_visible_changed=origin_overlay.set_visible,
        on_show_coords_changed=origin_overlay.set_show_coords,
        on_marker_added=origin_overlay.add,
        on_marker_removed=origin_overlay.remove,
        on_size_changed=origin_overlay.set_size,
    )
    win.add_tab("Markers", origin_panel.widget)

    # ── Mesh tangent / normal overlay ───────────────────────────
    from .overlays.mesh_tangent_normal_overlay import (
        MeshTangentNormalOverlay,
    )
    self._mesh_tn_overlay = MeshTangentNormalOverlay(
        plotter,
        origin_shift=registry.origin_shift,
        model_diagonal=scene.model_diagonal,
        scale=_PREF.current.tangent_normal_scale,
    )

    # ── Resolve FEM snapshot for overlays ───────────────────────
    view = self._view
    if view is None:
        # ``get_fem_data`` builds the full FEMData broker (~2.7 s on
        # a 600 k-node mesh). Its only consumer is ``self._view``,
        # which feeds the loads / mass / constraints tabs and their
        # rebuild callbacks. Skip it for mesh-only models — see
        # :func:`_needs_fem_for_overlays`.
        _needs_fem = _needs_fem_for_overlays(self._parent)
        if _needs_fem:
            try:
                fem = self._parent.mesh.queries.get_fem_data(
                    dim=max(self._dims))
            except Exception:
                fem = None
            if fem is not None:
                from .data import ViewerData
                view = ViewerData.from_fem(fem)
    self._view = view

    # ── Overlay visibility model — PR5 / D2 closure ─────────────
    # Single source of truth for {load_patterns, constraint_kinds,
    # mass_visible} across the outline-tree eye-icons and the
    # right-side tab checkboxes.  Pre-PR5 each surface held its
    # own snapshot computed off Qt widget state — alternating
    # writes caused the overlay to flip to whichever surface fired
    # last.  Now both surfaces write to the model; the model
    # dedups (idempotent setters) and fans out to the rebuild
    # callbacks below.
    # Must be constructed BEFORE ``_build_overlay_tabs``: the
    # Loads/Mass/Constraints tab panels receive ``overlay_model=``
    # and ``on_*_changed=self._overlay_model.set_*`` at __init__,
    # so the attribute must already exist when the tabs are built.
    from .core.overlay_visibility import OverlayVisibilityModel
    self._overlay_model = OverlayVisibilityModel()

    # ── Mesh dispatcher (ADR 0056 V3) ────────────────────────────
    # One shared Dispatcher class, mesh pumps bound onto the
    # ``entities`` / ``overlays`` slots. Owner models fire their
    # events themselves; UI surfaces only call mutators; one
    # coalesced render per fire. The overlays pump replaces the
    # four per-overlay observer callbacks that used to hang off
    # ``overlay_model.subscribe`` (and each end in its own
    # ``plotter.render()``); ``key=None`` rebuilds all — the
    # gesture_batch replay path. The boundary-node overlay is
    # inert when ``view.nodes.has_boundary_nodes`` is False
    # (single-partition models, pre-2.10.0 archives, live
    # ``from_fem`` viewers) — unchanged from the observer wiring.
    from .diagrams._dispatch import Dispatcher

    def _pump_overlays(key: "str | None" = None) -> None:
        m = self._overlay_model
        if key in (None, "loads"):
            self._rebuild_loads_overlay(m.load_patterns)
        if key in (None, "mass"):
            self._rebuild_mass_overlay(m.mass_visible)
        if key in (None, "constraints"):
            self._rebuild_constraints_overlay(m.constraint_kinds)
        if key in (None, "boundary"):
            self._rebuild_boundary_node_overlay(m.boundary_nodes_visible)
        tn = getattr(self, "_mesh_tn_overlay", None)
        if key in (None, "tangent") and tn is not None:
            from .ui.preferences_manager import PREFERENCES as _P
            tn.set_scale(
                _P.current.tangent_normal_scale
                * m.scale("tangent_normal_arrow")
            )

    dispatcher = Dispatcher(
        self,
        pump_overlays=_pump_overlays,
        render=lambda: plotter.render(),
    )
    self._dispatcher = dispatcher
    self._overlay_model.dispatcher = dispatcher

    # ── Insert overlay tabs (loads/mass/constraints) ────────────
    self._build_overlay_tabs(win)

    # ── Preferences (created AFTER scene — needs registry) ─────
    self._build_preferences_tab(win)

    # ── Core modules ────────────────────────────────────────────
    color_mgr = ColorManager(registry)
    self._color_mgr = color_mgr
    # With the CAD-neutral palette (dim_pt/crv black, dim_srf/vol gray)
    # the default per-dim idle function already gives a uniform look
    # while keeping nodes black — no override needed.
    vis_mgr = VisibilityManager(registry, color_mgr, sel, plotter, verbose=_verbose)
    self._vis_mgr = vis_mgr
    # ADR 0056 V3: the manager owner-fires
    # MESH_ENTITY_VISIBILITY_CHANGED; its rebuild is the
    # dispatcher's ``entities`` pump (one coalesced render —
    # replaces the on_changed render subscriber).
    vis_mgr.dispatcher = dispatcher
    dispatcher.bind(pump_entities=vis_mgr.rebuild_now)
    pick_engine = PickEngine(
        plotter, registry,
        drag_threshold=_PREF.current.drag_threshold,
    )
    self._pick_engine = pick_engine

    # ── Color mode controller ───────────────────────────────────
    self._color_mode_ctrl = ColorModeController(
        color_mgr=color_mgr,
        registry=registry,
        scene=scene,
        sel=sel,
        vis_mgr=vis_mgr,
        plotter=plotter,
        view=self._view,
    )

    from .core.explode_controller import ExplodeController
    self._explode_ctrl = ExplodeController(
        registry=registry, scene=scene, plotter=plotter, view=self._view,
        vis_mgr=vis_mgr, color_mgr=color_mgr,
    )

    # ── Browser tab (groups + element types visibility) ─────────
    from .ui.mesh_browser_tab import MeshBrowserTab
    if scene.group_to_breps or scene.brep_dominant_type:
        def _browser_hidden_changed(hidden_set):
            if self._explode_ctrl is not None and self._explode_ctrl._active:
                # Stash the latest browser state and replay it when
                # explosion ends (see _on_explode_axis) rather than
                # dropping it — otherwise the checkboxes desync from
                # the VisibilityManager.
                self._pending_browser_hidden = set(hidden_set)
                return
            vis_mgr.set_hidden(hidden_set)

        self._browser_tab = MeshBrowserTab(
            scene, on_hidden_changed=_browser_hidden_changed,
        )
        win.add_tab("Browser", self._browser_tab.widget)

    # ── Left-rail outline tree — primary navigation ────────────
    # ParaView-style alternative to the right-side Browser tab.
    # Lists Physical Groups + Element Types + Parts, plus optional
    # Loads / Masses / Constraints sections when the matching
    # composites are set on ``g``. Eye toggles on those rows fire
    # the same rebuild callbacks the right-side tabs already use,
    # so the overlay updates the same way regardless of which
    # surface drove it.
    from .ui._mesh_outline_tree import MeshOutlineTree
    parts_reg = getattr(self._parent, 'parts', None)
    loads_comp = getattr(self._parent, 'loads', None)
    mass_comp = getattr(self._parent, 'masses', None)
    constraints_comp = getattr(self._parent, 'constraints', None)

    # Map outline row kinds to the right-side tab names whose
    # contents serve as the property editor for that row type.
    # mesh.viewer's right side is the legacy ``QTabWidget`` (not
    # tabified extension docks), so we identify tabs by their
    # text label.
    _OUTLINE_TAB_MAP = {
        "group":           "Browser",
        "type":            "Browser",
        "part":            "Browser",
        "load_pattern":    "Loads",
        "mass":            "Mass",
        "constraint_kind": "Constraints",
    }

    def _on_outline_row_focused(kind: str, _payload) -> None:
        tab_name = _OUTLINE_TAB_MAP.get(kind)
        if tab_name is not None:
            win.focus_tab(tab_name)

    self._outline_tree = MeshOutlineTree(
        scene=scene,
        selection=sel,
        vis_mgr=vis_mgr,
        parts_registry=parts_reg,
        loads_composite=loads_comp,
        mass_composite=mass_comp,
        constraints_composite=constraints_comp,
        # PR5 — both writers go through ``self._overlay_model``;
        # the legacy ``on_*_changed`` callbacks route writes into
        # the model rather than calling ``_rebuild_*`` directly.
        # Passing ``overlay_model=`` ALSO subscribes the outline
        # to model changes so tab-checkbox writes refresh the
        # outline's eye-icons (cross-surface UI sync).
        on_load_patterns_changed=self._overlay_model.set_load_patterns,
        on_mass_visibility_changed=self._overlay_model.set_mass_visible,
        on_constraint_kinds_changed=self._overlay_model.set_constraint_kinds,
        on_boundary_nodes_changed=self._overlay_model.set_boundary_nodes_visible,
        on_row_focused=_on_outline_row_focused,
        overlay_model=self._overlay_model,
        # PR2 — partition rows (ADR 0027). The outline reads
        # ``view.elements.partition_for(eid)`` to group entities by
        # dominant OpenSeesMP rank; hidden when the view is absent
        # or carries no partition labelling.
        view=self._view,
    )
    # Swap the real outline tree into the placeholder dock that was
    # registered at construction (see the ViewerWindow call above).
    # The dock already participates in layout persistence + the
    # per-launch sanitize heal; this just installs its content.
    win.set_extension_dock_widget(
        "dock_mesh_outline", self._outline_tree.widget,
    )

    # ── Clipping tab ────────────────────────────────────────────
    from .core.clipping_controller import ClippingController
    from .ui.clipping_tab import ClippingTab
    self._clipping_ctrl = ClippingController(plotter, registry)
    self._clipping_tab = ClippingTab(
        on_toggle=self._clipping_ctrl.toggle,
        on_reset=self._clipping_ctrl.reset,
    )
    win.add_tab("Clipping", self._clipping_tab.widget)

    # ── Wire callbacks ──────────────────────────────────────────
    pick_engine.on_pick = self._handle_pick
    pick_engine.on_hover = self._handle_hover
    pick_engine.on_box_select = self._handle_box_select
    pick_engine.set_hidden_check(vis_mgr.is_hidden)

    # Attach the FilterController's fan-out now that the pick engine
    # exists: drive both actor visibility (the user-visible effect)
    # and the pick-engine pickable-dims mask (so picks ignore hidden
    # dims), then reflect the set back into the panel (key→panel
    # sync). Replaces the old monkeypatch of ``filter_tab._on_filter``
    # — the panel already routes through ``self._filter.set_active``
    # at construction, so both front-ends share one source of truth.
    def _apply_filter(active_dims) -> None:
        self._on_mesh_filter(set(active_dims))
        pick_engine.set_pickable_dims(set(active_dims))
        filter_tab.sync_active(active_dims)
    self._filter.on_change = _apply_filter

    # Selection changed -> recolor
    sel.on_changed.append(self._handle_sel_changed)
    if self._on_selection_changed is not None:
        def _studio_sel() -> None:
            self._on_selection_changed(sel)
        sel.on_changed.append(_studio_sel)
        _studio_sel()
    # Plan 04 step 3 — selection bridge into ActiveObjects.
    # ``SelectionState`` keeps its legacy ``on_changed`` list (the
    # plan doc marks it as a one-release compatibility shim); this
    # bridge fans the same event out via ``selectionChanged``
    # so new subscribers don't need to know about SelectionState's
    # internal callback list. The payload is an immutable tuple of
    # picks — fresh per emit, so ``ActiveObjects``' identity check
    # doesn't suppress repeat fires when picks mutate in place,
    # and downstream subscribers get a stable snapshot they can
    # cache without worrying about later mutation. Subscribers
    # needing more (centroid, parent shapes) reach for
    # ``viewer._sel`` via the viewer reference.
    def _sel_bridge() -> None:
        if self._active is not None and self._sel is not None:
            self._active.set_selection(tuple(self._sel.picks))
    sel.on_changed.append(_sel_bridge)
    self._sel_bridge_unsub = _sel_bridge
    # (No render subscriber on vis_mgr.on_changed — the dispatcher
    # renders once per MESH_ENTITY_VISIBILITY_CHANGED fire,
    # ADR 0056 V3.)
    # Repaint mesh idle colors when the theme palette changes
    win.on_theme_changed(lambda _p: self._handle_sel_changed())
    # Refresh tangent / normal arrows when palette changes
    win.on_theme_changed(
        lambda _p: self._mesh_tn_overlay.refresh_theme()
        if self._mesh_tn_overlay is not None else None
    )
    win.on_theme_changed(lambda _p: origin_overlay.refresh_theme())

    # ── Navigation ──────────────────────────────────────────────
    install_navigation(
        plotter,
        get_orbit_pivot=lambda: sel.centroid(registry),
    )

    # ── Motion LOD ──────────────────────────────────────────────
    # The per-dim node cloud (one sphere-sprite per FE node — 600k+
    # on large meshes) dominates per-frame GPU cost. Hide it while
    # the camera is moving and restore it ~120 ms after the gesture
    # settles, so orbit/zoom stay smooth without losing the node
    # display at rest. Mirrors ParaView's interactive LOD.
    from .core.motion_lod import MotionLOD
    self._motion_lod = MotionLOD(
        plotter,
        lambda: list(registry.dim_node_actors.values()),
    )
    self._motion_lod.install()

    # ── Install pick engine ─────────────────────────────────────
    pick_engine.install()

    # ── Toolbar buttons for visibility ──────────────────────────
    win.add_toolbar_separator()
    win.add_toolbar_button(
        "Hide selected (H)", "", self._act_hide, icon="eye_off",
    )
    win.add_toolbar_button(
        "Isolate selected (I)", "", self._act_isolate, icon="isolate",
    )
    win.add_toolbar_button(
        "Reveal all (R)", "", self._act_reveal_all, icon="reveal",
    )
    win.add_toolbar_separator()
    win.add_toolbar_button(
        "Save image…", "", self._act_screenshot, icon="image",
    )

    # ── Keybindings ─────────────────────────────────────────────
    plotter.add_key_event("h", self._act_hide)
    plotter.add_key_event("i", self._act_isolate)
    plotter.add_key_event("r", self._act_reveal_all)
    # Undo / clear route to the active pick set: FE-topo in
    # element/node mode, BREP entities in brep mode (ADR 0045 S3b).
    plotter.add_key_event("u", self._handle_undo)

    win.add_shortcut("Escape", self._handle_clear)
    win.add_shortcut("Q", lambda: win.window.close())

    plotter.add_key_event("e", lambda: self._set_pick_mode("element"))
    plotter.add_key_event("n", lambda: self._set_pick_mode("node"))
    plotter.add_key_event("b", lambda: self._set_pick_mode("brep"))

    # Dim filters (ADR 0045 S2 — closes the missing-keys gap, HARD
    # REQ 2): a bare key TOGGLES that dim (multi-select); 4 = all.
    # ApplicationShortcut: VTK's QtInteractor swallows plotter
    # add_key_event digit keys (same law as ResultsViewer Esc).
    for _key, _dim in [("0", 0), ("1", 1), ("2", 2), ("3", 3)]:
        win.add_shortcut(
            _key, lambda d=_dim: self._filter.toggle(d), application=True,
        )
    win.add_shortcut(
        "4", lambda: self._filter.select_all(), application=True,
    )

    # ── File menu (ADR 0087 Appendix B) ─────────────────────────
    # Save image… mirrors the toolbar action; Preferences… opens
    # the persistent global-preferences dialog (also reachable via
    # the Display tab's button). Inserted leftmost so the bar reads
    # File / View / Help (INV-5).
    from qtpy import QtWidgets as _QtW_file
    from .ui.preferences_dialog import open_preferences_dialog as _open_prefs
    _file_menu = _QtW_file.QMenu("File", win.window)
    _file_menu.addAction("Save image…").triggered.connect(
        lambda _checked=False: self._act_screenshot()
    )
    _file_menu.addSeparator()
    _file_menu.addAction("Preferences…").triggered.connect(
        lambda _checked=False: _open_prefs(win.window)
    )
    _mb = win.window.menuBar()
    _mb_acts = _mb.actions()
    if _mb_acts:
        _mb.insertMenu(_mb_acts[0], _file_menu)   # File leftmost
    else:
        _mb.addMenu(_file_menu)

    # ── View → Navigation / Camera / Theme submenus (ADR 0087) ──
    win.install_navigation_menu()
    win.install_camera_menu()
    win.install_theme_menu()

    # ── Help → Shortcuts (top menu) ─────────────────────────────
    from .ui._shortcuts_help import add_help_shortcuts_menu
    add_help_shortcuts_menu(
        win.window,
        entries=[
            ("B / E / N", "Pick mode — BRep / element / node"),
            ("0 / 1 / 2 / 3", "Toggle dim filter — point / curve / surface / volume"),
            ("4", "Show all dims"),
            ("H / I / R", "Hide / isolate / reveal all"),
            ("U", "Undo"),
            ("Shift+LMB drag", "Turntable (yaw-only around up axis)"),
            ("Shift+MMB drag", "Orbit (yaw + pitch, no-roll)"),
            ("MMB / RMB drag", "Pan"),
            ("Scroll", "Zoom (focal point fixed)"),
            ("Esc", "Deselect"),
            ("Q", "Close window"),
        ],
    )

    # ── Show summary ────────────────────────────────────────────
    n_nodes = len(scene.node_tags)
    n_elems = sum(len(v) for v in scene.brep_to_elems.values())
    info_tab.show_summary(n_nodes, n_elems)
    win.set_status(
        f"Mesh: {n_nodes:,} nodes, {n_elems:,} elements | "
        f"Mode: BRep (press E=element, N=node, B=brep)"
    )

    # ── Run ─────────────────────────────────────────────────────
    win.exec()
    if self._color_mode_ctrl is not None:
        self._color_mode_ctrl.close()
    return self

ModelViewer

ModelViewer(parent: '_SessionBase', model: 'Model', *, physical_group: str | None = None, dims: list[int] | None = None, point_size: float | None = None, line_width: float | None = None, surface_opacity: float | None = None, show_surface_edges: bool | None = None, origin_markers: list[tuple[float, float, float]] | None = None, origin_marker_show_coords: bool | None = None, on_selection_changed: Callable[['SelectionState'], None] | None = None, annotate: bool = False)

Interactive BRep model viewer with physical group management.

Displays BRep geometry, 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

parent : _SessionBase The apeGmsh session (provides name, _verbose). model : Model The apeGmsh model (provides sync()). physical_group : str, optional Auto-activate this physical group on open. dims : list[int], optional Which entity dimensions to show (default: [0, 1, 2, 3]). point_size, line_width, surface_opacity, show_surface_edges Visual properties forwarded to the scene builder. on_selection_changed : callable, optional callback(SelectionState) fired on every pick change (ADR 0095 studio host). Dispatcher-legal owner mutator. annotate : bool If True, turn on part + entity name labels with overall sizes (cotas) at open. Studio host sets this; the View tab still toggles them.

Source code in src/apeGmsh/viewers/model_viewer.py
def __init__(
    self,
    parent: "_SessionBase",
    model: "Model",
    *,
    physical_group: str | None = None,
    dims: list[int] | None = None,
    point_size: float | None = None,
    line_width: float | None = None,
    surface_opacity: float | None = None,
    show_surface_edges: bool | None = None,
    origin_markers: list[tuple[float, float, float]] | None = None,
    origin_marker_show_coords: bool | None = None,
    on_selection_changed: Callable[["SelectionState"], None] | None = None,
    annotate: bool = False,
) -> None:
    from .ui.preferences_manager import PREFERENCES
    p = PREFERENCES.current

    self._parent = parent
    self._model = model
    self._dims = dims if dims is not None else [0, 1, 2, 3]
    self._physical_group = physical_group

    # Visual props — explicit kwarg wins, otherwise pull user preference.
    self._point_size = point_size if point_size is not None else p.point_size
    self._line_width = line_width if line_width is not None else p.line_width
    self._surface_opacity = (
        surface_opacity if surface_opacity is not None else p.surface_opacity
    )
    self._show_surface_edges = (
        show_surface_edges if show_surface_edges is not None
        else p.show_surface_edges
    )

    # Origin marker overlay. User preference controls whether the
    # default is ``[(0,0,0)]`` or ``[]``; explicit kwarg wins.
    if origin_markers is not None:
        self._origin_markers: list[tuple[float, float, float]] = list(origin_markers)
    elif p.origin_marker_include_world_origin:
        self._origin_markers = [(0.0, 0.0, 0.0)]
    else:
        self._origin_markers = []
    self._origin_marker_show_coords = (
        origin_marker_show_coords if origin_marker_show_coords is not None
        else p.origin_marker_show_coords
    )

    # Populated during show()
    self._selection_state: "SelectionState | None" = None
    self._registry: "EntityRegistry | None" = None
    # ADR 0095 S2: host publishes a SelectionEnvelope on pick.
    # Dispatcher-legal (owner mutator callback); not Outline puppeteering.
    self._on_selection_changed = on_selection_changed
    self._annotate = annotate

    # Plan 04 step 4 — per-viewer ActiveObjects coordinator.
    # Constructed once a QApplication / window exists (in show()).
    # ModelViewer has no pick-mode concept — only the
    # ``selectionChanged`` bridge is wired today. The legacy
    # ``sel.on_changed`` cascade (recolor → tree → browser →
    # parts_tree) stays untouched per the
    # plan doc's one-release compatibility shim policy; the bridge
    # gives future panels a Qt-signal entry point without forcing
    # them through ``SelectionState``'s internal callback list.
    self._active: Any = None

selection property

selection

The current working set as a :class:Selection object.

tags property

tags: list[DimTag]

The current working set as a list of DimTags.

active_group property

active_group: str | None

The name of the physical group currently receiving picks.

show

show(*, title: str | None = None, maximized: bool = True)

Open the viewer window, block until closed.

Source code in src/apeGmsh/viewers/model_viewer.py
 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
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 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
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 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
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
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
1294
1295
1296
1297
1298
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
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
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
1674
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
1797
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
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
def show(self, *, title: str | None = None, maximized: bool = True):
    """Open the viewer window, block until closed."""
    from .core.navigation import install_navigation
    from .core.color_manager import ColorManager
    from .core.filter_controller import FilterController
    from .core.pick_engine import PickEngine
    from .core.visibility import VisibilityManager
    from .core.selection import SelectionState
    from .scene.brep_scene import build_brep_scene
    from .scene.bbox_source import gmsh_bbox, gmsh_model_bbox
    from .ui.viewer_window import ViewerWindow
    from .ui.preferences import PreferencesTab
    from .ui.model_tabs import (
        FilterTab, ViewTab, SelectionTreePanel, PartsTreePanel,
    )

    # Ensure geometry is synced
    gmsh.model.occ.synchronize()

    # ── Window (creates QApplication + plotter) ─────────────────
    default_title = (
        f"ModelViewer — {self._parent.name}"
        + (f" -> {self._physical_group}" if self._physical_group else "")
    )

    # ── Selection state ─────────────────────────────────────────
    sel = SelectionState()
    self._selection_state = sel

    # Seed staging with pre-existing user-facing PGs (skip labels).
    # ADR 0045 S3c: staging is authoritative, so pull existing groups
    # in up front — the browser/outline read staged, gmsh is written
    # back only at flush (window close).
    sel.seed_from_gmsh()

    if self._physical_group is not None:
        sel.set_active_group(self._physical_group)

    # Pre-init the on_close closure vars (mirrors the _cb_parts_tree
    # pre-init below): the close handler references these before they
    # are assigned ~1300 lines down, so bind them to None up front to
    # stay NameError-safe if construction is ever reordered or aborts
    # early. The real assignments / the _on_sel_changed def overwrite
    # these.
    _on_sel_changed = _cb_sel_tree = _cb_outline = _cb_parts_tree = None
    _cb_active = _cb_theme_sel = _cb_theme_tn = None
    _cb_theme_origin = _cb_theme_measure = None
    _studio_sel = None

    def _on_close():
        # Remove sel.on_changed subscribers registered by this viewer.
        for _cb in (
            _on_sel_changed,
            _cb_sel_tree,
            _cb_outline,
            _cb_parts_tree,
            _cb_active,
            _studio_sel,
        ):
            if _cb is not None:
                try:
                    sel.on_changed.remove(_cb)
                except ValueError:
                    pass
        # Remove win._theme_callbacks subscribers registered by this viewer.
        # ViewerWindow has no off_theme_changed(), so we remove directly.
        for _cb in (
            _cb_theme_sel, _cb_theme_tn,
            _cb_theme_origin, _cb_theme_measure,
        ):
            try:
                win._theme_callbacks.remove(_cb)
            except ValueError:
                pass
        try:
            n = sel.flush_to_gmsh()
        except Exception as exc:
            # Log the full traceback so the user can debug, then surface
            # a dialog. Do NOT re-raise — the user is closing the window;
            # crashing their program after-the-fact loses session state.
            import sys
            import traceback
            print(
                f"[viewer] flush_to_gmsh failed on close: {exc}",
                file=sys.stderr,
            )
            traceback.print_exc(file=sys.stderr)
            try:
                from qtpy import QtWidgets
                QtWidgets.QMessageBox.critical(
                    win.window,
                    "Failed to write physical groups",
                    f"{exc}\n\nSee console for full traceback. "
                    "Pending picks were not committed.",
                )
            except Exception:
                pass
            return
        if self._parent._verbose:
            print(f"[viewer] closed — {n} physical group(s) written, "
                  f"{len(sel.picks)} picks in working set")

    # Create window FIRST so QApplication exists for Qt widgets.
    # ``window_key`` opts into layout persistence under
    # ``QSettings("apeGmsh", "ModelViewer")`` (plan 08 follow-up).
    # The left-column nav docks (Outline + Selection) are registered
    # HERE as construction-time placeholder extension docks so they
    # are present at saveState / restoreState time — the same path
    # the built-in docks use, which is why they never get stuck. The
    # real trees (which need scene / selection state built later) are
    # swapped in via ``win.set_extension_dock_widget`` once ready.
    # ``sanitize=True`` opts them into the per-launch heal.
    from qtpy import QtWidgets as _QtW_nav
    from .ui._dock_registry import DockSpec as _NavDockSpec
    from .ui._layout_metrics import LAYOUT as _NAV_LAYOUT
    _nav_floors = dict(
        sanitize=True,
        min_width=_NAV_LAYOUT.outline_min_width,
        initial_width=_NAV_LAYOUT.outline_initial_width,
        min_height=_NAV_LAYOUT.outline_min_height,
        initial_height=_NAV_LAYOUT.outline_initial_height,
    )
    win = ViewerWindow(
        title=title or default_title,
        on_close=_on_close,
        window_key="ModelViewer",
        extension_docks=[
            _NavDockSpec(
                dock_id="dock_model_outline", title="Outline",
                factory=lambda p: _QtW_nav.QWidget(p),
                default_area="left", **_nav_floors,
            ),
            _NavDockSpec(
                dock_id="dock_model_selection", title="Selection",
                factory=lambda p: _QtW_nav.QWidget(p),
                default_area="left", **_nav_floors,
            ),
        ],
    )
    # Stack Selection under the Outline in the left column. Done here
    # (docks already exist from the constructor) so the default
    # arrangement is set; restoreState re-applies the user's saved
    # layout on top, and the per-launch sanitize heals any degenerate
    # restored share.
    from qtpy import QtCore as _QtC_split
    win.window.splitDockWidget(
        win.extension_dock("dock_model_outline"),
        win.extension_dock("dock_model_selection"),
        _QtC_split.Qt.Vertical,
    )

    # ── Plan 04 step 4 — ActiveObjects coordinator ──────────────
    # One per viewer. Provides the ``selectionChanged`` signal that
    # future panels subscribe to; the legacy ``sel.on_changed``
    # cascade installed further below stays as the compatibility
    # path per the plan doc. The bridge into ActiveObjects is
    # registered alongside the cascade in the "Wire callbacks"
    # section so all selection observers are co-located.
    from .core._active_objects import ActiveObjects
    self._active = ActiveObjects(parent=win.window)

    # ── UI tabs (created AFTER QApplication exists) ─────────────
    # NOTE: PreferencesTab is created AFTER scene build (needs registry).
    # See "Preferences" block below build_brep_scene().

    _DIM_NAMES = {0: "points", 1: "curves", 2: "surfaces", 3: "volumes"}

    def _on_new_group():
        from qtpy import QtWidgets
        current_picks = list(sel.targets)
        # A Gmsh physical group is dimension-scoped. A mixed-dim
        # selection would be written as one PG per dimension under
        # the same name (looks duplicated, wrong for FEM export),
        # so reject it up front rather than silently splitting.
        dims = sorted({t.dim for t in current_picks})
        if len(dims) > 1:
            QtWidgets.QMessageBox.warning(
                win.window,
                "Mixed-dimension selection",
                "A physical group must contain entities of a "
                "single dimension.\n\nThe current selection spans: "
                + ", ".join(_DIM_NAMES.get(d, str(d)) for d in dims)
                + ".\n\nRefine it to one dimension and try again.",
            )
            return
        name, ok = QtWidgets.QInputDialog.getText(
            win.window, "New Physical Group",
            "Group name:",
        )
        if ok and name.strip():
            n = name.strip()
            # Stage current picks as the new group (replayable op),
            # then switch to it (loads picks from staging).
            sel.stage_group(n, current_picks)
            sel.set_active_group(n)
            outline.refresh()
            if current_picks:
                win.set_status(
                    f"Group '{n}' created with {len(current_picks)} entities"
                )
            else:
                win.set_status(f"Active group: {n} — pick entities to add")

    def _on_new_label():
        # The multi-dimensional counterpart to _on_new_group. A
        # label IS allowed to span dimensions — it is backed by one
        # ``_label:`` PG per dimension (PGs are dimension-scoped),
        # which the outline merges into one row.
        from qtpy import QtWidgets
        picks = list(sel.picks)
        if not picks:
            QtWidgets.QMessageBox.information(
                win.window, "New Label",
                "Select one or more entities first — a label "
                "groups the current selection (any mix of "
                "dimensions).",
            )
            return
        labels_api = getattr(self._parent, "labels", None)
        if labels_api is None:
            QtWidgets.QMessageBox.warning(
                win.window, "New Label",
                "This session exposes no labels API.",
            )
            return
        name, ok = QtWidgets.QInputDialog.getText(
            win.window, "New Label",
            "Label name (groups the selection across all its "
            "dimensions):",
        )
        if not (ok and name.strip()):
            return
        n = name.strip()
        by_dim: dict[int, list[int]] = {}
        for d, t in picks:
            by_dim.setdefault(int(d), []).append(int(t))
        try:
            # ``labels.add`` warns about cross-dim "ambiguous
            # lookups" when the same name spans dimensions — which
            # is precisely the intent of a multi-dim label, so
            # silence that one warning for this deliberate add.
            import warnings
            with warnings.catch_warnings():
                warnings.filterwarnings(
                    "ignore",
                    message=r".*already exists at dim=.*",
                )
                for d, tags in sorted(by_dim.items()):
                    labels_api.add(d, tags, n)
        except Exception as exc:
            QtWidgets.QMessageBox.warning(
                win.window, "New Label",
                f"Could not create label '{n}':\n{exc}",
            )
            return
        outline.refresh()
        dims_txt = ", ".join(
            _DIM_NAMES.get(d, str(d)) for d in sorted(by_dim)
        )
        win.set_status(
            f"Label '{n}' created from {len(picks)} entities "
            f"({dims_txt})"
        )

    def _on_rename_label(name: str):
        from qtpy import QtWidgets
        labels_api = getattr(self._parent, "labels", None)
        if labels_api is None:
            return
        new_name, ok = QtWidgets.QInputDialog.getText(
            win.window, "Rename Label",
            "New label name:", text=name,
        )
        if not (ok and new_name.strip()):
            return
        nn = new_name.strip()
        if nn == name:
            return
        try:
            # dim=None → rename across every dimension the label
            # spans (a label is multi-dimensional).
            labels_api.rename(name, nn)
        except Exception as exc:
            QtWidgets.QMessageBox.warning(
                win.window, "Rename Label",
                f"Could not rename label '{name}':\n{exc}",
            )
            return
        outline.refresh()
        win.set_status(f"Label '{name}' renamed to '{nn}'")

    def _on_delete_label(name: str):
        from qtpy import QtWidgets
        labels_api = getattr(self._parent, "labels", None)
        if labels_api is None:
            return
        reply = QtWidgets.QMessageBox.question(
            win.window, "Delete Label",
            f"Delete label '{name}' (all dimensions)?",
        )
        if reply != QtWidgets.QMessageBox.StandardButton.Yes:
            return
        try:
            labels_api.remove(name)        # dim=None → all dims
        except Exception as exc:
            QtWidgets.QMessageBox.warning(
                win.window, "Delete Label",
                f"Could not delete label '{name}':\n{exc}",
            )
            return
        outline.refresh()
        win.set_status(f"Deleted label: {name}")

    def _on_rename_group(old_name: str):
        from qtpy import QtWidgets
        new_name, ok = QtWidgets.QInputDialog.getText(
            win.window, "Rename Group",
            "New name:", text=old_name,
        )
        if ok and new_name.strip():
            sel.rename_group(old_name, new_name.strip())
            outline.refresh()

    def _on_delete_group(name: str):
        from qtpy import QtWidgets
        reply = QtWidgets.QMessageBox.question(
            win.window, "Delete Group",
            f"Delete physical group '{name}'?",
        )
        # Qt6 uses QMessageBox.StandardButton.Yes; Qt5 had the
        # top-level alias. Compare via the enum member to stay
        # portable across PyQt5/PySide2/PyQt6/PySide6.
        if reply == QtWidgets.QMessageBox.StandardButton.Yes:
            # ADR 0045 S3c: delete is staged + tombstoned; the gmsh PG
            # is removed at flush. The outline reads staging, so the
            # group disappears from the UI immediately.
            sel.delete_group(name)
            outline.refresh()
            win.set_status(f"Deleted group: {name}")

    def _on_group_activated(name: str):
        sel.set_active_group(name)
        # In-place active-row restyle only. A full refresh()
        # (takeChildren + rebuild) would reset scroll/expansion
        # and make rows visibly jump on every click; the
        # structure is unchanged here, only which group is active.
        outline.update_active()
        n = len(sel.picks)
        win.set_status(f"Active group: {name} ({n} entities)")

    # Filter -> pick engine + visual dim feedback. The closure references
    # plotter / registry / pick_engine which are bound later in this
    # method; safe because the callback only fires after ``win.exec()``.
    # The FilterController (ADR 0045 S2) is the single source of truth
    # for the active dimension set; the 0/1/2/3/4 keys and this panel
    # are two front-ends writing it (INV-4).
    def _apply_filter(active_dims):
        pick_engine.set_pickable_dims(set(active_dims))
        # Ghost inactive dims (still visible) AND make their actors
        # non-pickable so a vtkCellPicker ray passes THROUGH them to
        # the active dim's actor underneath — the volume-click
        # pass-through (ADR 0045 S5): with only volumes active, a
        # click on a volume's (coincident, ghosted) boundary surface
        # resolves to the volume, not the surface.
        from .overlays.pref_helpers import filter_dim_opacity
        for dim in registry.dims:
            in_active = dim in active_dims
            registry.set_dim_pickable(dim, in_active)
            actor = registry.dim_actors.get(dim)
            if actor is None:
                continue
            actor.GetProperty().SetOpacity(
                filter_dim_opacity(
                    registry, dim,
                    active=in_active,
                    fallback=self._surface_opacity,
                )
            )
        plotter.render()
        filter_tab.sync_active(active_dims)  # key→panel two-way sync
        if not active_dims:
            win.set_status("Dim filter: none")
        elif set(active_dims) == set(self._dims):
            win.set_status("Dim filter: all")
        else:
            win.set_status(
                "Dim filter: "
                + ", ".join(str(d) for d in sorted(active_dims))
            )

    self._filter = FilterController(self._dims, on_change=_apply_filter)
    filter_tab = FilterTab(
        self._dims, on_filter_changed=self._filter.set_active
    )

    # ── View tab (entity labels) ────────────────────────────────
    _label_actors: list = []
    _DIM_ABBR = {0: "P", 1: "C", 2: "S", 3: "V"}

    def _on_labels_changed(
        active_dims, font_size, use_names,
        show_parts=False, show_entity_labels=False,
    ):
        from apeGmsh.core.Labels import is_label_pg, strip_prefix
        from .ui._filter_view_tabs import quotation_text

        # Remove existing labels
        for a in _label_actors:
            try:
                plotter.remove_actor(a)
            except Exception:
                pass
        _label_actors.clear()

        for dim, show in active_dims.items():
            if not show:
                continue
            points = []
            labels = []
            for _, tag in gmsh.model.getEntities(dim=dim):
                dt = (dim, tag)
                c = registry.centroid(dt)
                if c is not None:
                    points.append(c)
                else:
                    try:
                        ctr = gmsh_bbox(dim, tag).center - registry.origin_shift
                        points.append(ctr.tolist())
                    except Exception:
                        continue
                if use_names:
                    name = None
                    for pg_dim, pg_tag in gmsh.model.getPhysicalGroups(dim):
                        try:
                            ents = gmsh.model.getEntitiesForPhysicalGroup(
                                pg_dim, pg_tag,
                            )
                            if tag in ents:
                                pg_name = gmsh.model.getPhysicalName(
                                    pg_dim, pg_tag,
                                )
                                # Skip label PGs here — they show
                                # in the dedicated entity-label
                                # overlay below.
                                if not is_label_pg(pg_name):
                                    name = pg_name
                                    break
                        except Exception:
                            pass
                    labels.append(
                        name or f"{_DIM_ABBR[dim]}{tag}"
                    )
                else:
                    labels.append(f"{_DIM_ABBR[dim]}{tag}")

            if not points:
                continue

            from .ui.theme import THEME as _THEME
            try:
                actor = plotter.add_point_labels(
                    np.array(points), labels,
                    font_size=font_size,
                    text_color=_THEME.current.text,
                    shape_color=_THEME.current.mantle,
                    shape_opacity=0.6,
                    show_points=False,
                    always_visible=True,
                    name=f"_labels_dim{dim}",
                )
                _label_actors.append(actor)
            except Exception:
                pass

        # ── Part labels (one per instance, at centroid) ─────────
        parts_reg_local = getattr(self._parent, 'parts', None)
        if show_parts and parts_reg_local is not None:
            part_points = []
            part_labels = []
            for label, inst in parts_reg_local.instances.items():
                # Use highest-dim entity centroid for placement
                placed = False
                quoted = quotation_text(label, inst.bbox)
                for d in (3, 2, 1, 0):
                    for t in inst.entities.get(d, []):
                        c = registry.centroid((d, t))
                        if c is not None:
                            part_points.append(c)
                            part_labels.append(quoted)
                            placed = True
                            break
                    if placed:
                        break
                if not placed and inst.bbox is not None:
                    bb = inst.bbox
                    part_points.append([
                        (bb[0] + bb[3]) * 0.5 - registry.origin_shift[0],
                        (bb[1] + bb[4]) * 0.5 - registry.origin_shift[1],
                        (bb[2] + bb[5]) * 0.5 - registry.origin_shift[2],
                    ])
                    part_labels.append(quoted)

            if part_points:
                try:
                    actor = plotter.add_point_labels(
                        np.array(part_points), part_labels,
                        font_size=font_size + 2,
                        text_color=_THEME.current.success,
                        shape_color=_THEME.current.base,
                        shape_opacity=0.85,
                        show_points=False,
                        always_visible=True,
                        bold=True,
                        name="_labels_parts",
                    )
                    _label_actors.append(actor)
                except Exception:
                    pass

        # ── Entity labels (Tier 1 — from g.labels) ────────────
        if show_entity_labels:
            label_points = []
            label_texts = []
            for pg_dim, pg_tag in gmsh.model.getPhysicalGroups():
                pg_name = gmsh.model.getPhysicalName(pg_dim, pg_tag)
                if not is_label_pg(pg_name):
                    continue
                display_name = strip_prefix(pg_name)
                ent_tags = gmsh.model.getEntitiesForPhysicalGroup(
                    pg_dim, pg_tag,
                )
                for tag in ent_tags:
                    dt = (pg_dim, int(tag))
                    c = registry.centroid(dt)
                    if c is not None:
                        label_points.append(c)
                    else:
                        try:
                            ctr = gmsh_bbox(pg_dim, int(tag)).center - registry.origin_shift
                            label_points.append(ctr.tolist())
                        except Exception:
                            continue
                    try:
                        bb = gmsh.model.getBoundingBox(pg_dim, int(tag))
                    except Exception:
                        bb = None
                    label_texts.append(quotation_text(display_name, bb))

            if label_points:
                try:
                    actor = plotter.add_point_labels(
                        np.array(label_points), label_texts,
                        font_size=font_size,
                        text_color=_THEME.current.warning,
                        shape_color=_THEME.current.base,
                        shape_opacity=0.75,
                        show_points=False,
                        always_visible=True,
                        italic=True,
                        name="_labels_entities",
                    )
                    _label_actors.append(actor)
                except Exception:
                    pass

        plotter.render()

    # ``tn_overlay`` is constructed later in this method (it needs the
    # registry's origin shift, only known after ``build_brep_scene``).
    # The closure resolves it lazily — safe because the callback only
    # fires after ``win.exec()``.
    def _on_geometry_probes_changed(show_tangents: bool, show_normals: bool):
        tn_overlay.set_show_tangents(show_tangents)
        tn_overlay.set_show_normals(show_normals)

    view_tab = ViewTab(
        self._dims,
        on_labels_changed=_on_labels_changed,
        on_geometry_probes_changed=_on_geometry_probes_changed,
    )

    # ── Selection tree panel ────────────────────────────────────
    def _tree_select_only(dts):
        sel.select_batch(dts, replace=True)

    def _tree_add(dts):
        sel.select_batch(dts)

    def _tree_remove(dts):
        sel.box_remove(dts)

    # Visibility callbacks — late-binding on vis_mgr (defined later
    # in this same method). Owner-fired (ADR 0056 V4): the mutators
    # fire MESH_ENTITY_VISIBILITY_CHANGED and the dispatcher
    # rebuilds + renders once — no call-site renders.
    def _tree_hide(dts):
        vis_mgr.hide_dts(dts)

    def _tree_isolate(dts):
        vis_mgr.isolate_dts(dts)

    def _tree_reveal_all():
        vis_mgr.reveal_all()

    sel_tree = SelectionTreePanel(
        on_select_only=_tree_select_only,
        on_add_to_selection=_tree_add,
        on_remove_from_selection=_tree_remove,
        on_hide=_tree_hide,
        on_isolate=_tree_isolate,
        on_reveal_all=_tree_reveal_all,
    )

    # Plan 08 follow-up — every right-side panel is now its own
    # ``QDockWidget`` tabified together by default. Users can drag
    # any panel out, dock it elsewhere, close it from the title
    # bar, and the arrangement persists via ``window_key``.
    # ``_FIRST_DOCK`` anchors the tabify chain so subsequent calls
    # land next to it instead of fanning out across dock areas.
    from .ui._dock_registry import DockSpec
    # Right-side tool group. ``_FIRST_DOCK`` anchors the tabify
    # chain so the rest land as tabs next to it. View is the
    # anchor now that the Browser is retired (Outline + Labels
    # supersede it); Selection is no longer here — it lives in the
    # left column under the Outline (see below).
    _FIRST_DOCK = "dock_model_view"

    def _add_panel(dock_id: str, title: str, widget) -> Any:
        return win.add_extension_dock(DockSpec(
            dock_id=dock_id,
            title=title,
            factory=lambda _p: widget,
            tabify_with=(
                None if dock_id == _FIRST_DOCK else _FIRST_DOCK
            ),
        ))

    _add_panel(_FIRST_DOCK, "View", view_tab.widget)
    _add_panel("dock_model_filter", "Filter", filter_tab.widget)

    plotter = win.plotter

    # ── Build scene ─────────────────────────────────────────────
    _verbose = getattr(self._parent, '_verbose', False)
    registry = build_brep_scene(
        plotter, self._dims,
        point_size=self._point_size,
        line_width=self._line_width,
        surface_opacity=self._surface_opacity,
        show_surface_edges=self._show_surface_edges,
        verbose=_verbose,
    )
    self._registry = registry

    def _compute_model_diagonal() -> float:
        try:
            return gmsh_model_bbox().diagonal or 1.0
        except Exception:
            return 1.0

    from .overlays.origin_markers_overlay import OriginMarkerOverlay
    from .ui.origin_markers_panel import OriginMarkersPanel
    from .ui.preferences_manager import PREFERENCES as _PREF
    _marker_size = _PREF.current.origin_marker_size
    origin_overlay = OriginMarkerOverlay(
        plotter,
        origin_shift=registry.origin_shift,
        model_diagonal=_compute_model_diagonal(),
        points=self._origin_markers,
        show_coords=self._origin_marker_show_coords,
        size=_marker_size,
    )
    origin_panel = OriginMarkersPanel(
        initial_points=self._origin_markers,
        initial_visible=True,
        initial_show_coords=self._origin_marker_show_coords,
        initial_size=_marker_size,
        on_visible_changed=origin_overlay.set_visible,
        on_show_coords_changed=origin_overlay.set_show_coords,
        on_marker_added=origin_overlay.add,
        on_marker_removed=origin_overlay.remove,
        on_size_changed=origin_overlay.set_size,
    )
    _add_panel("dock_model_markers", "Markers", origin_panel.widget)

    # ── Model info panel (read-only diagnostics) ──────────────
    # No longer a dock tab — surfaced via the top-level "Info"
    # menu as a standalone non-modal window (wired further down,
    # once ``win`` + the menu bar are available).
    from .ui._model_info_panel import ModelInfoPanel
    info_panel = ModelInfoPanel(parts_registry=getattr(self._parent, 'parts', None))

    # ── Section / clipping plane ────────────────────────────────
    from .overlays.clip_plane_overlay import ClipPlaneOverlay
    from .ui._clip_plane_panel import ClipPlanePanel
    clip_overlay = ClipPlaneOverlay(
        plotter, registry, origin_shift=registry.origin_shift,
    )

    def _world_bbox() -> tuple[float, float, float, float, float, float]:
        try:
            box = gmsh_model_bbox()
            return (*box.min, *box.max)
        except Exception:
            return (0.0, 0.0, 0.0, 1.0, 1.0, 1.0)

    clip_panel = ClipPlanePanel(clip_overlay, world_bbox=_world_bbox())
    _add_panel("dock_model_section", "Section", clip_panel.widget)

    # ── Measure tool (entity-centroid distance) ─────────────────
    from .overlays.measure_overlay import MeasureOverlay
    from .ui._measure_panel import MeasurePanel
    measure_overlay = MeasureOverlay(plotter, registry)

    def _push_measure_status() -> None:
        measure_panel.update_status(
            num_points=measure_overlay.num_points,
            endpoints=measure_overlay.last_endpoints,
            distance=measure_overlay.last_distance,
            delta=measure_overlay.last_delta,
        )

    def _on_measure_active(active: bool) -> None:
        # Leaving measure mode wipes any in-flight measurement so
        # the next time the user enters they start fresh.
        if not active:
            measure_overlay.reset()
        _push_measure_status()
        win.set_status(
            "Measure mode ON — click two entities" if active
            else "Measure mode off",
            3000,
        )

    def _on_measure_clear() -> None:
        measure_overlay.reset()
        _push_measure_status()

    measure_panel = MeasurePanel(
        on_active_changed=_on_measure_active,
        on_clear=_on_measure_clear,
    )
    _add_panel("dock_model_measure", "Measure", measure_panel.widget)

    # ── Tangent / normal overlay (geometry probes in View tab) ──
    from .overlays.tangent_normal_overlay import TangentNormalOverlay
    tn_overlay = TangentNormalOverlay(
        plotter,
        origin_shift=registry.origin_shift,
        model_diagonal=_compute_model_diagonal(),
        scale=_PREF.current.tangent_normal_scale,
    )

    # ── Preferences (created AFTER scene — needs registry) ─────
    from .overlays.pref_helpers import make_line_width_cb, make_opacity_cb, make_edges_cb
    from .overlays.glyph_helpers import rebuild_brep_point_glyphs

    # ColorManager constructed before the Session tab: the tab's
    # pick-color swatch initializes from this owner (ADR 0056
    # INV-1). VisibilityManager picks it up below.
    color_mgr = ColorManager(registry)

    # ── Physical Group color mode ───────────────────────────────
    import zlib
    from .core.color_mode_controller import (
        _GROUP_PALETTE_RGB, _FALLBACK_RGB as _PG_FALLBACK,
    )
    brep_to_group: dict = {}
    for _pg_dim, _pg_tag in gmsh.model.getPhysicalGroups():
        try:
            _pg_name = gmsh.model.getPhysicalName(_pg_dim, _pg_tag)
            if not _pg_name:
                continue
            for _ent_tag in gmsh.model.getEntitiesForPhysicalGroup(
                _pg_dim, _pg_tag
            ):
                _dt = (_pg_dim, int(_ent_tag))
                if _dt not in brep_to_group:
                    brep_to_group[_dt] = _pg_name
        except Exception:
            pass
    _color_mode = ["default"]

    def _pg_idle_fn(dt):
        name = brep_to_group.get(dt)
        if name is None:
            return _PG_FALLBACK
        return _GROUP_PALETTE_RGB[
            zlib.crc32(name.encode("utf-8")) % len(_GROUP_PALETTE_RGB)
        ]

    def _toggle_pg_color():
        if _color_mode[0] == "default":
            _color_mode[0] = "pg"
            color_mgr.set_idle_fn(_pg_idle_fn)
            win.set_status("Color mode: Physical Group")
        else:
            _color_mode[0] = "default"
            color_mgr.reset_idle_fn()
            win.set_status("Color mode: Default")
        color_mgr.recolor_all(
            picks=set(sel.picks),
            hidden=vis_mgr.hidden,
            hover=pick_engine.hover_entity,
        )
        plotter.render()

    def _pref_point_size(v: float):
        kw = registry._add_mesh_kwargs.get(0, {})
        kw['point_size'] = v
        registry._add_mesh_kwargs[0] = kw
        rebuild_brep_point_glyphs(plotter, registry)
        plotter.render()

    _pref_line_width = make_line_width_cb(registry, plotter)
    _pref_opacity_inner = make_opacity_cb(registry, plotter)

    def _pref_opacity(v: float):
        # Keep the owner field in sync so scene rebuilds don't
        # snap back to the constructor default. Then re-apply the
        # dim filter so ghosted (inactive) dims stay ghosted —
        # the inner callback writes every dim>=2 actor to ``v``.
        self._surface_opacity = float(v)
        _pref_opacity_inner(v)
        _apply_filter(self._filter.active)

    _pref_edges = make_edges_cb(registry, plotter)

    def _pref_pick_color(hex_str: str):
        h = hex_str.lstrip("#")
        try:
            rgb = (
                int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16),
            )
        except ValueError:
            return
        from .ui.theme import THEME as _THEME
        _THEME.update_current(pick_rgb=rgb)

    from .ui.theme import THEME
    prefs = PreferencesTab(
        point_size=self._point_size,
        line_width=self._line_width,
        surface_opacity=self._surface_opacity,
        show_surface_edges=self._show_surface_edges,
        on_point_size=_pref_point_size,
        on_line_width=_pref_line_width,
        on_opacity=_pref_opacity,
        on_edges=_pref_edges,
        # Initial swatch projects the owner's effective pick colour
        # (ADR 0056 INV-1 — the widget rebuilds from the owner).
        pick_color="#{:02x}{:02x}{:02x}".format(
            *(int(c) for c in color_mgr.pick_rgb)
        ),
        on_pick_color=_pref_pick_color,
        on_theme=lambda name: THEME.set_theme(name),
    )
    # Session tab (formerly "Preferences") — runtime tweaks that reset
    # next session. The "Global preferences…" button at the bottom opens
    # the persistent-prefs dialog.
    from qtpy import QtWidgets as _QtW
    from .ui.preferences_dialog import open_preferences_dialog
    from .ui.theme_editor_dialog import open_theme_editor
    _btn_global = _QtW.QPushButton("Global preferences…")
    _btn_global.clicked.connect(
        lambda: open_preferences_dialog(win.window)
    )
    prefs.widget.layout().addWidget(_btn_global)
    _btn_theme = _QtW.QPushButton("Theme editor…")
    _btn_theme.clicked.connect(
        lambda: open_theme_editor(win.window)
    )
    prefs.widget.layout().addWidget(_btn_theme)
    _btn_gfx = _QtW.QPushButton("Graphics colors…")
    _btn_gfx.clicked.connect(win._open_graphics_colors)
    prefs.widget.layout().addWidget(_btn_gfx)
    # Wrap in a scroll area so the (tall) Session panel never
    # forces a minimum size on the shared right-side tab group —
    # it scrolls instead of stretching its neighbours.
    _sess_scroll = _QtW.QScrollArea()
    _sess_scroll.setWidgetResizable(True)
    _sess_scroll.setFrameShape(_QtW.QFrame.NoFrame)
    _sess_scroll.setWidget(prefs.widget)
    # "Display" per ADR 0087 INV-1/INV-5 (display preferences, not
    # session state); objectName stays ``dock_model_session`` so
    # persisted layouts keep round-tripping.
    _add_panel("dock_model_session", "Display", _sess_scroll)

    # Set generous clipping range for shifted coords
    try:
        plotter.reset_camera()
        cam = plotter.renderer.GetActiveCamera()
        cam.SetClippingRange(0.01, 1e6)
    except Exception:
        pass

    # ── Core modules ────────────────────────────────────────────
    vis_mgr = VisibilityManager(registry, color_mgr, sel, plotter, verbose=_verbose)
    # ── Model dispatcher (ADR 0056 V4) ──────────────────────────
    # Same contract as the mesh viewer (V3): VisibilityManager
    # owner-fires MESH_ENTITY_VISIBILITY_CHANGED; its rebuild is
    # the dispatcher's ``entities`` pump; ONE coalesced render per
    # gesture (this also retires the double-render the model
    # viewer used to do — an on_changed render subscriber PLUS a
    # call-site render after every mutator).
    from .diagrams._dispatch import Dispatcher
    dispatcher = Dispatcher(
        self,
        pump_entities=vis_mgr.rebuild_now,
        render=lambda: plotter.render(),
    )
    self._dispatcher = dispatcher
    vis_mgr.dispatcher = dispatcher
    # Mirror the mesh viewer's attribute surface (it stores all
    # three) — verification drivers and tests reach these.
    self._win = win
    self._plotter = plotter
    self._vis_mgr = vis_mgr
    from .ui.preferences_manager import PREFERENCES as _PREF_DT
    pick_engine = PickEngine(
        plotter, registry, drag_threshold=_PREF_DT.current.drag_threshold,
    )

    # ── Left column — primary navigation ───────────────────────
    # The outline (Physical Groups / Labels / Parts, ParaView-
    # style) is the model navigator; the Browser panel it once
    # mirrored has been retired. Selection sits directly below it
    # (vertical split) so picks stay visible while you browse.
    parts_reg = getattr(self._parent, 'parts', None)
    from .ui._model_outline_tree import ModelOutlineTree

    # Outline PG/Label click → declaration target for the
    # Loads / Masses panels (captured by name + kind).
    self._decl_target = None

    def _on_outline_focus(kind, payload) -> None:
        if kind in ("group", "label"):
            self._decl_target = (kind, str(payload))

    outline = ModelOutlineTree(
        selection=sel,
        vis_mgr=vis_mgr,
        parts_registry=parts_reg,
        on_group_activated=_on_group_activated,
        on_entity_toggled=lambda dt: sel.toggle(dt),
        on_new_group=_on_new_group,
        on_new_label=_on_new_label,
        on_rename_label=_on_rename_label,
        on_delete_label=_on_delete_label,
        on_rename_group=_on_rename_group,
        on_delete_group=_on_delete_group,
        on_row_focused=_on_outline_focus,
    )
    # Swap the real trees into the placeholder nav docks registered
    # at construction (see the ViewerWindow call above). The docks +
    # their Outline-over-Selection split + persistence + per-launch
    # heal are already wired; this installs the content.
    win.set_extension_dock_widget("dock_model_outline", outline.widget)
    win.set_extension_dock_widget("dock_model_selection", sel_tree.widget)

    # ── Info menu — model diagnostics as a standalone window ────
    # Replaces the old "Info" dock tab. Lazily builds one
    # non-modal window the first time it's opened; reuses it
    # afterwards. Parented to the main window so it closes with
    # the viewer but never blocks it.
    from qtpy import QtWidgets as _QtW_info, QtCore as _QtC_info
    _model_name = getattr(self._parent, "model_name", None) or "model"
    _info_window: list[Any] = []

    def _open_model_info() -> None:
        w = _info_window[0] if _info_window else None
        if w is None:
            w = _QtW_info.QMainWindow(win.window)
            w.setWindowFlag(_QtC_info.Qt.Window, True)
            w.setWindowTitle(f"Model info — {_model_name}")
            w.setCentralWidget(info_panel.widget)
            w.resize(420, 620)
            _info_window.append(w)
        info_panel.refresh()
        w.show()
        w.raise_()
        w.activateWindow()

    # View → Model info… — the one-item "Info" menu retired into
    # View per ADR 0087 Appendix B (one-item menus are banned).
    win.add_view_menu_action("Model info…", _open_model_info)

    # ── View → Navigation / Camera / Theme submenus (ADR 0087) ──
    win.install_navigation_menu()
    win.install_camera_menu()
    win.install_theme_menu()

    # ── File menu — CAD geometry import / export ────────────────
    # Import is additive: g.model.io.load_step / load_dxf add to
    # the current model, then the scene rebuilds. Export writes
    # the current model to STEP. Errors surface in a dialog (same
    # as the Boolean / Transform panels). Inserted leftmost so it
    # reads as a conventional File menu.
    from qtpy import QtWidgets as _QtW_file

    def _import_step() -> None:
        path, _f = _QtW_file.QFileDialog.getOpenFileName(
            win.window, "Import STEP", "",
            "STEP (*.step *.stp);;All files (*)",
        )
        if not path:
            return
        try:
            imported = self._model.io.load_step(path)
        except Exception as exc:
            _QtW_file.QMessageBox.warning(
                win.window, "Import STEP", str(exc)
            )
            return
        n = sum(len(v) for v in (imported or {}).values())
        _rebuild_scene()
        win.set_status(
            f"Imported STEP — {n} entit"
            f"{'y' if n == 1 else 'ies'}"
        )

    def _import_dxf() -> None:
        path, _f = _QtW_file.QFileDialog.getOpenFileName(
            win.window, "Import DXF", "",
            "DXF (*.dxf);;All files (*)",
        )
        if not path:
            return
        try:
            self._model.io.load_dxf(path)
        except Exception as exc:
            _QtW_file.QMessageBox.warning(
                win.window, "Import DXF", str(exc)
            )
            return
        _rebuild_scene()
        win.set_status("Imported DXF")

    def _export_step() -> None:
        path, _f = _QtW_file.QFileDialog.getSaveFileName(
            win.window, "Export STEP", "",
            "STEP (*.step);;All files (*)",
        )
        if not path:
            return
        try:
            self._model.io.save_step(path)
        except Exception as exc:
            _QtW_file.QMessageBox.warning(
                win.window, "Export STEP", str(exc)
            )
            return
        win.set_status("Exported STEP")

    _file_menu = _QtW_file.QMenu("File", win.window)
    _file_menu.addAction("Import STEP…").triggered.connect(
        _import_step
    )
    _file_menu.addAction("Import DXF…").triggered.connect(
        _import_dxf
    )
    _file_menu.addSeparator()
    _file_menu.addAction("Export STEP…").triggered.connect(
        _export_step
    )
    # Global preferences (bottom of File, after a separator — ADR
    # 0087 Appendix B: no one-item Edit menu just to host it).
    from .ui.preferences_dialog import open_preferences_dialog as _open_prefs
    _file_menu.addSeparator()
    _file_menu.addAction("Preferences…").triggered.connect(
        lambda _checked=False: _open_prefs(win.window)
    )
    _mb = win.window.menuBar()
    _mb_acts = _mb.actions()
    if _mb_acts:
        _mb.insertMenu(_mb_acts[0], _file_menu)   # File leftmost
    else:
        _mb.addMenu(_file_menu)

    # ── Loads / Masses declaration panels (pre-mesh) ────────────
    # Declared against the outline's selected PG / Label. The
    # library call happens here (pattern-wrapped for loads).
    # model.viewer has no mesh, so no arrows — the declarations
    # render later in g.mesh.viewer(fem=fem). Target dim is
    # validated like PG creation. No _rebuild_scene (no geometry
    # change).
    from .ui._loads_panel import LoadsPanel, LOAD_TYPES
    from .ui._masses_panel import MassesPanel, MASS_TYPES
    from qtpy import QtWidgets as _QtW_decl
    _LOAD_DIM = dict(LOAD_TYPES)
    _MASS_DIM = dict(MASS_TYPES)

    def _decl_target():
        return self._decl_target

    def _target_dims(kind, name):
        from apeGmsh.core.Labels import add_prefix
        pgname = add_prefix(name) if kind == "label" else name
        dims = set()
        for d, t in gmsh.model.getPhysicalGroups():
            try:
                if gmsh.model.getPhysicalName(d, t) == pgname:
                    dims.add(int(d))
            except Exception:
                pass
        return dims

    def _kw_for(kind, name, params):
        kw = {"label": name} if kind == "label" else {"pg": name}
        kw.update(params)
        return kw

    _rec_view = lambda r, with_pattern: _decl_record_view(  # noqa: E731
        r, with_pattern=with_pattern
    )

    def _loads_records():
        recs = getattr(self._parent.loads, "load_defs", []) or []
        return [_rec_view(r, True) for r in recs]

    def _loads_remove(key):
        recs = getattr(self._parent.loads, "load_defs", None)
        if recs is not None:
            recs[:] = [r for r in recs if id(r) != key]
        _loads_panel.refresh_list()

    def _loads_apply(load_type, pattern, target, params):
        kind, name = target
        need = _LOAD_DIM.get(load_type)
        dims = _target_dims(kind, name)
        if need is not None and dims and need not in dims:
            _QtW_decl.QMessageBox.warning(
                win.window, f"Loads: {load_type}",
                f"{load_type} needs a "
                f"{_DIM_NAMES.get(need, need)} target; '{name}' is "
                + ", ".join(
                    _DIM_NAMES.get(x, str(x)) for x in sorted(dims)
                ) + ".",
            )
            _loads_panel.set_hint(f"{load_type}: wrong target dim.")
            return
        try:
            with self._parent.loads.case(pattern):
                getattr(self._parent.loads, load_type)(
                    **_kw_for(kind, name, params)
                )
        except Exception as exc:
            _QtW_decl.QMessageBox.warning(
                win.window, f"Loads: {load_type}", str(exc)
            )
            _loads_panel.set_hint(f"{load_type} failed: {exc}")
            return
        _loads_panel.refresh_patterns()
        _loads_panel.refresh_list()
        _loads_panel.set_hint(
            f"Declared {load_type} on {name} "
            f"(pattern '{pattern}')."
        )
        win.set_status(f"Load declared: {load_type}{name}")

    _loads_panel = LoadsPanel(
        get_target=_decl_target,
        get_patterns=lambda: list(
            getattr(self._parent.loads, "patterns", lambda: [])()
        ),
        on_apply=_loads_apply,
        on_remove=_loads_remove,
        list_records=_loads_records,
    )

    def _masses_records():
        recs = getattr(self._parent.masses, "mass_defs", []) or []
        return [_rec_view(r, False) for r in recs]

    def _masses_remove(key):
        recs = getattr(self._parent.masses, "mass_defs", None)
        if recs is not None:
            recs[:] = [r for r in recs if id(r) != key]
        _masses_panel.refresh_list()

    def _masses_apply(mass_type, target, params):
        kind, name = target
        need = _MASS_DIM.get(mass_type)
        dims = _target_dims(kind, name)
        if need is not None and dims and need not in dims:
            _QtW_decl.QMessageBox.warning(
                win.window, f"Masses: {mass_type}",
                f"{mass_type} mass needs a "
                f"{_DIM_NAMES.get(need, need)} target; '{name}' is "
                + ", ".join(
                    _DIM_NAMES.get(x, str(x)) for x in sorted(dims)
                ) + ".",
            )
            _masses_panel.set_hint(f"{mass_type}: wrong target dim.")
            return
        try:
            getattr(self._parent.masses, mass_type)(
                **_kw_for(kind, name, params)
            )
        except Exception as exc:
            _QtW_decl.QMessageBox.warning(
                win.window, f"Masses: {mass_type}", str(exc)
            )
            _masses_panel.set_hint(f"{mass_type} failed: {exc}")
            return
        _masses_panel.refresh_list()
        _masses_panel.set_hint(
            f"Declared {mass_type} mass on {name}."
        )
        win.set_status(f"Mass declared: {mass_type}{name}")

    _masses_panel = MassesPanel(
        get_target=_decl_target,
        on_apply=_masses_apply,
        on_remove=_masses_remove,
        list_records=_masses_records,
    )

    # Wrap in scroll areas so the wide-range vec3 spin boxes never
    # force their (~1000px) minimum width onto the shared right-side
    # tab group — same guard the Session panel uses for its height.
    def _scrollable(w):
        sc = _QtW.QScrollArea()
        sc.setWidgetResizable(True)
        sc.setFrameShape(_QtW.QFrame.NoFrame)
        sc.setWidget(w)
        return sc

    _add_panel(
        "dock_model_loads", "Loads", _scrollable(_loads_panel.widget)
    )
    _add_panel(
        "dock_model_masses", "Masses",
        _scrollable(_masses_panel.widget),
    )

    # Scene rebuild after any geometry mutation (parts fuse,
    # boolean ops, transforms). Hoisted to show() scope so it
    # exists even without a parts registry.
    def _rebuild_scene():
        """Tear down VTK actors and rebuild from current Gmsh state.

        Mutates ``registry`` in-place so all closures over it
        (color_mgr, vis_mgr, pick_engine) keep working.
        """
        # Save camera state
        cam = plotter.renderer.GetActiveCamera()
        cam_pos = cam.GetPosition()
        cam_fp = cam.GetFocalPoint()
        cam_up = cam.GetViewUp()
        cam_clip = cam.GetClippingRange()

        # Remove stale label actors — positions may be wrong after rebuild.
        for a in list(_label_actors):
            try:
                plotter.remove_actor(a)
            except Exception:
                pass
        _label_actors.clear()

        # Remove old actors
        for actor in list(registry.dim_actors.values()):
            try:
                plotter.remove_actor(actor)
            except Exception:
                pass

        # Silhouettes are separate actors that ``remove_actor(fill)``
        # does NOT take down (same pyvista quirk the visibility
        # rebuild handles explicitly). Without this the pre-transform
        # outline lingers as a ghost while the fresh geometry moves.
        for sil in list(registry.dim_silhouette_actors.values()):
            try:
                plotter.remove_actor(sil)
            except Exception:
                pass

        # Build fresh scene
        fresh = build_brep_scene(
            plotter, self._dims,
            point_size=self._point_size,
            line_width=self._line_width,
            surface_opacity=self._surface_opacity,
            show_surface_edges=self._show_surface_edges,
            verbose=_verbose,
        )

        # Mutate existing registry in place — preserves closures
        for slot in registry.__slots__:
            setattr(registry, slot, getattr(fresh, slot))

        # Re-sync origin markers with the fresh registry's shift
        origin_overlay.set_origin_shift(registry.origin_shift)
        tn_overlay.set_model_diagonal(_compute_model_diagonal())
        tn_overlay.set_origin_shift(registry.origin_shift)

        # Clear stale selection / active group
        sel.clear()

        # Refresh UI panels
        if parts_tree is not None:
            parts_tree.refresh()
        outline.refresh()
        sel_tree.update(sel.picks)
        info_panel.refresh()

        # Re-bind the clip plane to the fresh mappers + new bbox
        clip_overlay.set_origin_shift(registry.origin_shift)
        clip_overlay.rebind()
        clip_panel.refresh_bbox(_world_bbox())

        # Stored centroids are stale after a rebuild
        measure_overlay.reset()
        _push_measure_status()

        # Restore camera
        cam.SetPosition(*cam_pos)
        cam.SetFocalPoint(*cam_fp)
        cam.SetViewUp(*cam_up)
        cam.SetClippingRange(*cam_clip)
        # Fresh actors come in at the live slider opacity; re-ghost
        # whatever the pick filter currently has inactive.
        _apply_filter(self._filter.active)
        plotter.render()

    # Exposed for external callers that need to force a rebuild
    # after mutating Gmsh state out-of-band (ADR 0095 S6a: studio
    # host refresh calls this after a successful script replay).
    self._rebuild_scene = _rebuild_scene

    parts_tree = None
    if parts_reg is not None:
        def _parts_select_only(dts):
            sel.select_batch(dts, replace=True)

        def _parts_add(dts):
            sel.select_batch(dts)

        def _parts_remove(dts):
            sel.box_remove(dts)

        def _parts_isolate(dts):
            sel.select_batch(dts, replace=True)
            vis_mgr.isolate()

        def _parts_hide(dts):
            sel.select_batch(dts, replace=True)
            vis_mgr.hide()

        def _parts_new(label, picks):
            from qtpy.QtWidgets import QMessageBox
            try:
                parts_reg.register(label, picks)
            except ValueError as e:
                QMessageBox.warning(win.window, "Ownership conflict", str(e))
                return
            parts_tree.refresh()

        def _parts_rename(old_label, new_label):
            from qtpy.QtWidgets import QMessageBox
            try:
                parts_reg.rename(old_label, new_label)
            except (KeyError, ValueError) as e:
                QMessageBox.warning(win.window, "Rename failed", str(e))
                return
            parts_tree.refresh()

        def _parts_delete(label):
            parts_reg.delete(label)
            parts_tree.refresh()

        def _parts_fuse(labels, new_label):
            from qtpy.QtWidgets import QMessageBox
            try:
                parts_reg.fuse_group(labels, label=new_label)
            except (ValueError, RuntimeError) as e:
                QMessageBox.warning(win.window, "Fuse failed", str(e))
                return
            _rebuild_scene()

        parts_tree = PartsTreePanel(
            parts_reg, registry,
            on_select_only=_parts_select_only,
            on_add_to_selection=_parts_add,
            on_remove_from_selection=_parts_remove,
            on_isolate=_parts_isolate,
            on_hide=_parts_hide,
            on_new_part=_parts_new,
            on_rename_part=_parts_rename,
            on_delete_part=_parts_delete,
            on_fuse_parts=_parts_fuse,
            get_current_picks=lambda: sel.picks,
        )
        # Insert after Browser tab (position 1)
        win._tab_widget.insertTab(1, parts_tree.widget, "Parts")

    # ── Wire callbacks ──────────────────────────────────────────

    # Pick -> selection (or measure overlay when measure mode is on)
    from .core.pick_tiebreak import coincident_stack

    def _on_pick(dt: DimTag, ctrl: bool):
        if measure_panel.is_active():
            # Measure wants the literal entity hit, not the volume.
            measure_overlay.add_entity(dt)
            _push_measure_status()
            return
        # ADR 0045 S5-tiebreak: a boundary click is coincident with its
        # owning volume. Select the highest active dim (the volume) so a
        # click on a solid's face picks the solid, not the face. Degrades
        # to the hit entity when there is no active owning volume.
        stack = coincident_stack(
            dt, self._filter.active, registry.volumes_of_face,
        )
        chosen = stack[0] if stack else dt
        if ctrl:
            sel.unpick(chosen)
        else:
            sel.toggle(chosen)

    pick_engine.on_pick = _on_pick
    pick_engine.set_hidden_check(vis_mgr.is_hidden)

    # Hover -> color
    _prev_hover: list[DimTag | None] = [None]

    def _on_hover(dt: DimTag | None):
        old = _prev_hover[0]
        _prev_hover[0] = dt
        if old is not None and old != dt:
            is_picked = old in sel.picks
            color_mgr.set_entity_state(old, picked=is_picked)
        if dt is not None:
            is_picked = dt in sel.picks
            if not is_picked:
                color_mgr.set_entity_state(dt, hovered=True)
        plotter.render()

    pick_engine.on_hover = _on_hover

    # Selection changed -> batch recolor + refresh UI
    def _on_sel_changed():
        color_mgr.recolor_all(
            picks=set(sel.picks),
            hidden=vis_mgr.hidden,
            hover=pick_engine.hover_entity,
        )
        plotter.render()
        n = len(sel.picks)
        grp = sel.active_group or "none"
        win.set_status(f"{n} picked | group: {grp}")

    sel.on_changed.append(_on_sel_changed)
    if self._on_selection_changed is not None:
        def _studio_sel():
            self._on_selection_changed(sel)
        sel.on_changed.append(_studio_sel)
        _studio_sel()
    # Repaint idle colors when the theme palette changes
    _cb_theme_sel = lambda _p: _on_sel_changed()
    win.on_theme_changed(_cb_theme_sel)
    _cb_theme_tn = lambda _p: tn_overlay.refresh_theme()
    win.on_theme_changed(_cb_theme_tn)
    _cb_theme_origin = lambda _p: origin_overlay.refresh_theme()
    win.on_theme_changed(_cb_theme_origin)
    _cb_theme_measure = lambda _p: measure_overlay.refresh_theme()
    win.on_theme_changed(_cb_theme_measure)
    _cb_sel_tree = lambda: sel_tree.update(sel.picks)
    sel.on_changed.append(_cb_sel_tree)
    _cb_outline = lambda: outline.update_active()
    sel.on_changed.append(_cb_outline)
    if parts_tree is not None:
        _cb_parts_tree = (
            lambda: parts_tree.highlight_part_for_entity(sel.picks[-1])
            if sel.picks else None
        )
        sel.on_changed.append(_cb_parts_tree)
    else:
        _cb_parts_tree = None
    # ADR 0045 S3c-2: the active group's members are auto-materialised
    # into staging by the log reducer, so no per-pick commit is needed
    # (the old on_changed -> commit_active_group hook is gone).
    # Plan 04 step 4 — selection bridge into ActiveObjects.
    # Same pattern as mesh.viewer: emit a fresh tuple of picks on
    # every mutation so ``ActiveObjects``' identity short-circuit
    # doesn't suppress in-place changes. Subscribers reach for
    # ``viewer._active.selection`` (a tuple snapshot) or, for
    # richer state, hold a viewer reference and inspect
    # ``viewer._selection_state``.
    _active_ref = self._active
    _cb_active = lambda: _active_ref.set_selection(tuple(sel.picks))
    sel.on_changed.append(_cb_active)

    # (No render subscriber on vis_mgr.on_changed — the dispatcher
    # renders once per MESH_ENTITY_VISIBILITY_CHANGED fire,
    # ADR 0056 V4.)

    # Box select
    def _on_box(dts: list[DimTag], ctrl: bool):
        if ctrl:
            n = sel.box_remove(dts)
            verb = "removed"
        else:
            n = sel.box_add(dts)
            verb = "added"
        if n:
            noun = "entity" if n == 1 else "entities"
            win.set_status(f"Box select: {verb} {n} {noun}", 2000)
        else:
            win.set_status("Box select: 0 entities", 2000)

    pick_engine.on_box_select = _on_box

    # ── Boolean / Transform panels (live OCC editing) ───────────
    # Pure-UI panels; these callbacks own the library call +
    # _rebuild_scene (mirrors _parts_fuse). The selection feeds
    # operands; OCC renumbers after each op, so captured operands
    # are dropped and the rebuild clears the selection.
    import math as _math
    from .ui._boolean_panel import BooleanPanel
    from .ui._transform_panel import TransformPanel

    def _on_boolean(op, objects, tools, opts):
        from qtpy import QtWidgets
        if not objects:
            _boolean_panel.set_hint(
                "Set the Objects slot from a selection first."
            )
            return
        if op in ("fuse", "cut", "intersect") and not tools:
            _boolean_panel.set_hint(
                f"{op} needs both Objects and Tools."
            )
            return
        bx = self._model.boolean
        try:
            if op == "fragment":
                res = bx.fragment(
                    objects, tools,
                    remove_object=opts["remove_object"],
                    remove_tool=opts["remove_tool"],
                    cleanup_free=opts["cleanup_free"],
                )
            else:
                kw = dict(
                    remove_object=opts["remove_object"],
                    remove_tool=opts["remove_tool"],
                )
                if opts["label"]:
                    kw["label"] = opts["label"]
                res = getattr(bx, op)(objects, tools, **kw)
        except Exception as exc:
            QtWidgets.QMessageBox.warning(
                win.window, f"Boolean: {op}", str(exc)
            )
            _boolean_panel.set_hint(f"{op} failed: {exc}")
            return
        _boolean_panel.clear_operands()
        _rebuild_scene()
        n = len(res) if res else 0
        _boolean_panel.set_hint(f"{op} OK → {n} result(s)")
        win.set_status(f"Boolean {op}: {n} result(s)")

    def _on_transform(op, params, duplicate):
        from qtpy import QtWidgets
        tags = list(sel.picks)
        tx = self._model.transforms
        geo = self._model.geometry
        if op != "thru_sections" and not tags:
            _transform_panel.set_hint("Select entities first.")
            return
        try:
            if op in ("translate", "rotate", "scale", "mirror"):
                if duplicate:
                    dims = {d for d, _ in tags}
                    if len(dims) != 1:
                        _transform_panel.set_hint(
                            "'Keep original' needs a single-"
                            "dimension selection."
                        )
                        return
                    dim0 = dims.pop()
                    target = [(dim0, t) for t in tx.copy(tags)]
                else:
                    target = tags
                if op == "translate":
                    tx.translate(target, params["dx"],
                                 params["dy"], params["dz"])
                elif op == "rotate":
                    tx.rotate(
                        target, _math.radians(params["angle"]),
                        ax=params["ax"], ay=params["ay"],
                        az=params["az"], cx=params["cx"],
                        cy=params["cy"], cz=params["cz"],
                    )
                elif op == "scale":
                    tx.scale(
                        target, params["sx"], params["sy"],
                        params["sz"], cx=params["cx"],
                        cy=params["cy"], cz=params["cz"],
                    )
                else:  # mirror
                    tx.mirror(target, params["a"], params["b"],
                              params["c"], params["d"])
            elif op == "copy":
                tx.copy(tags)
            elif op == "extrude":
                ne = [params["layers"]] if params["layers"] else None
                tx.extrude(tags, params["dx"], params["dy"],
                           params["dz"], num_elements=ne,
                           recombine=params["recombine"])
            elif op == "revolve":
                ne = [params["layers"]] if params["layers"] else None
                tx.revolve(
                    tags, _math.radians(params["angle"]),
                    x=params["x"], y=params["y"], z=params["z"],
                    ax=params["ax"], ay=params["ay"],
                    az=params["az"], num_elements=ne,
                    recombine=params["recombine"],
                )
            elif op == "sweep":
                pc = params.get("path_curves") or []
                if not pc:
                    _transform_panel.set_hint(
                        "Set the sweep path from selected curves."
                    )
                    return
                wire = geo.add_wire(pc)
                tx.sweep(tags, wire, trihedron=params["trihedron"])
            elif op == "thru_sections":
                secs = params.get("sections") or []
                if len(secs) < 2:
                    _transform_panel.set_hint(
                        "Add at least 2 sections."
                    )
                    return
                wires = [geo.add_wire(c) for c in secs]
                tx.thru_sections(
                    wires, make_solid=params["make_solid"],
                    make_ruled=params["make_ruled"],
                )
        except Exception as exc:
            QtWidgets.QMessageBox.warning(
                win.window, f"Transform: {op}", str(exc)
            )
            _transform_panel.set_hint(f"{op} failed: {exc}")
            return
        _transform_panel.reset_captures()
        _rebuild_scene()
        _transform_panel.set_hint(f"{op} OK")
        win.set_status(f"Transform {op} applied")

    _boolean_panel = BooleanPanel(
        get_selection=lambda: list(sel.picks),
        on_apply=_on_boolean,
    )
    _transform_panel = TransformPanel(
        get_selection=lambda: list(sel.picks),
        on_apply=_on_transform,
    )
    _add_panel("dock_model_boolean", "Boolean", _boolean_panel.widget)
    _add_panel(
        "dock_model_transform", "Transform", _transform_panel.widget
    )

    # ── Navigation ──────────────────────────────────────────────
    install_navigation(
        plotter,
        get_orbit_pivot=lambda: sel.centroid(registry),
    )

    # ── Motion LOD ──────────────────────────────────────────────
    # The per-dim silhouette actors are ``vtkPolyDataSilhouette`` —
    # view-dependent, so they re-execute every frame the camera
    # moves (the dominant per-orbit cost on a complex CAD part,
    # on top of what the navigation bounds-cache already removes).
    # Hide them during any camera gesture and restore ~120 ms
    # after it settles — same interactive-LOD trick mesh.viewer
    # uses for its node cloud. The lambda is re-evaluated per
    # gesture so it always targets the live silhouette actors
    # (they're rebuilt by the visibility hide/show path).
    from .core.motion_lod import MotionLOD
    self._motion_lod = MotionLOD(
        plotter,
        lambda: list(registry.dim_silhouette_actors.values()),
    )
    self._motion_lod.install()

    # ── Install pick engine ─────────────────────────────────────
    pick_engine.install()

    # ── Visibility action helpers (shared between toolbar + keys) ──
    # Owner-fired (ADR 0056 V4) — the dispatcher renders.
    def _act_hide() -> None:
        vis_mgr.hide()

    def _act_isolate() -> None:
        vis_mgr.isolate()

    def _act_reveal_all() -> None:
        vis_mgr.reveal_all()

    # ── Toolbar buttons for visibility ──────────────────────────
    win.add_toolbar_separator()
    win.add_toolbar_button(
        "Hide selected (H)", "", _act_hide, icon="eye_off",
    )
    win.add_toolbar_button(
        "Isolate selected (I)", "", _act_isolate, icon="isolate",
    )
    win.add_toolbar_button(
        "Reveal all (R)", "", _act_reveal_all, icon="reveal",
    )
    if brep_to_group:
        win.add_toolbar_separator()
        win.add_toolbar_button(
            "Color by physical group", "", _toggle_pg_color,
            icon="palette",
        )

    # ── Keybindings ─────────────────────────────────────────────
    # VTK-level (only when 3D viewport has focus)
    plotter.add_key_event("h", _act_hide)
    plotter.add_key_event("i", _act_isolate)
    plotter.add_key_event("r", _act_reveal_all)

    # Undo / redo. ADR 0045 S3c-2: group activate/create/rename/delete
    # are replayable, so undo/redo can change the active group + the
    # group tree — rebuild the outline (not just restyle) after each.
    def _undo():
        if sel.undo():
            outline.refresh()

    def _redo():
        if sel.redo():
            outline.refresh()

    plotter.add_key_event("u", _undo)
    plotter.add_key_event("y", _redo)

    # Dim filters: 0=points, 1=curves, 2=surfaces, 3=volumes.
    # Ratified multi-select semantics (ADR 0045): a bare key TOGGLES
    # that dim in/out of the active set; 4 = all.
    # ApplicationShortcut: VTK's QtInteractor swallows plotter
    # add_key_event digit keys (same law as ResultsViewer Esc).
    for key, dim in [("0", 0), ("1", 1), ("2", 2), ("3", 3)]:
        win.add_shortcut(
            key, lambda d=dim: self._filter.toggle(d), application=True,
        )
    win.add_shortcut(
        "4", lambda: self._filter.select_all(), application=True,
    )

    # Window-level (work regardless of focus / mouse position)
    win.add_shortcut("Escape", lambda: sel.clear())
    win.add_shortcut("Q", lambda: win.window.close())

    # ── Help → Shortcuts (top menu) ─────────────────────────────
    from .ui._shortcuts_help import add_help_shortcuts_menu
    add_help_shortcuts_menu(
        win.window,
        entries=[
            ("LMB", "Pick BRep entity"),
            ("0 / 1 / 2 / 3", "Toggle dim filter — point / curve / surface / volume"),
            ("4", "Show all dims"),
            ("H / I / R", "Hide / isolate / reveal all"),
            ("U / Y", "Undo / redo"),
            ("Shift+LMB drag", "Turntable (yaw-only around up axis)"),
            ("Shift+MMB drag", "Orbit (yaw + pitch, no-roll)"),
            ("MMB / RMB drag", "Pan"),
            ("Scroll", "Zoom (focal point fixed)"),
            ("Esc", "Deselect"),
            ("Q", "Close window"),
        ],
    )

    # ── Pre-load group if specified ─────────────────────────────
    if self._physical_group is not None and sel.picks:
        _on_sel_changed()

    if self._annotate:
        view_tab.apply_quotations()

    # ── Run ─────────────────────────────────────────────────────
    win.exec()
    return self

to_physical

to_physical(name: str | None = None) -> int | None

Write the current picks as a Gmsh physical group.

Source code in src/apeGmsh/viewers/model_viewer.py
def to_physical(self, name: str | None = None) -> int | None:
    """Write the current picks as a Gmsh physical group."""
    if self._selection_state is None:
        return None
    sel = self._selection_state
    group_name = name or self._physical_group
    if not group_name:
        return None
    sel.apply_group(group_name)
    return sel.flush_to_gmsh()

SectionProperties

SectionProperties(fem: 'FEMData', *, materials: Mapping[str, SectionMaterial] | None = None, name: str | None = None, disconnected: Literal['raise', 'sum'] = 'raise')

Analyzer + declaration for one meshed cross-section.

Parameters

fem A FEMData whose 2-D elements mesh the section face in the global XY plane (g.mesh.queries.get_fem_data(dim=2)). materials Physical-group name → :class:SectionMaterial. Every 2-D element must belong to exactly one named PG. Omit entirely for geometric-only mode (unit moduli — classic geometric numbers). name Handle used in fail-loud messages and displays. disconnected Multi-part policy (ADR 0078): "raise" (default) makes the S2 warping solve fail loud on a disconnected mesh — usually the forgot-to-fragment authoring bug; "sum" opts into per-part Saint-Venant solves. Geometric and plastic analyses are connectivity-blind in either mode.

Notes

The analyzer is a declaration: frozen inputs, memoized frozen results. ops.section.ComputedSection(analysis=sec) (S5) binds it to the OpenSees bridge and resolves lazily at emit.

Source code in src/apeGmsh/sections/_analysis.py
def __init__(
    self,
    fem: "FEMData",
    *,
    materials: Mapping[str, SectionMaterial] | None = None,
    name: str | None = None,
    disconnected: Literal["raise", "sum"] = "raise",
) -> None:
    if disconnected not in ("raise", "sum"):
        raise ValueError(
            f"SectionProperties: disconnected must be 'raise' or 'sum', "
            f"got {disconnected!r}."
        )
    self._name = name
    self._disconnected: Literal["raise", "sum"] = disconnected
    self._snapshot: SectionSnapshot = build_snapshot(
        fem, materials, name=name
    )
    self._materials: Mapping[str, SectionMaterial] = MappingProxyType(
        dict(zip(self._snapshot.material_names, self._snapshot.materials))
    )
    self._geometric: GeometricProperties | None = None
    self._warping: WarpingProperties | None = None
    self._warp_solutions: tuple[_PartSolution, ...] = ()
    self._plastic: PlasticProperties | None = None
    self._unit_fields: _UnitFields | None = None

materials property

materials: Mapping[str, SectionMaterial]

Read-only PG-name → material view (empty-ish placeholder map in geometric-only mode).

n_parts property

n_parts: int

Connected-component count of the section mesh.

geometric

geometric() -> GeometricProperties

Area-based (modulus-weighted) properties. Pure quadrature — connectivity-blind, valid for disconnected sections.

Source code in src/apeGmsh/sections/_analysis.py
def geometric(self) -> GeometricProperties:
    """Area-based (modulus-weighted) properties.  Pure quadrature —
    connectivity-blind, valid for disconnected sections."""
    if self._geometric is None:
        self._geometric = compute_geometric(self._snapshot)
    return self._geometric

warping

warping() -> WarpingProperties

Saint-Venant warping / shear analysis: GJ, shear centre (elasticity + Trefftz), warping rigidity EGamma, shear rigidities GAs_*, monosymmetry constants.

Requires a connected mesh under the default disconnected="raise"; "sum" solves per part (ADR 0078). Warns :class:SectionAccuracyWarning on linear elements.

Source code in src/apeGmsh/sections/_analysis.py
def warping(self) -> WarpingProperties:
    """Saint-Venant warping / shear analysis: ``GJ``, shear centre
    (elasticity + Trefftz), warping rigidity ``EGamma``, shear
    rigidities ``GAs_*``, monosymmetry constants.

    Requires a connected mesh under the default
    ``disconnected="raise"``; ``"sum"`` solves per part (ADR 0078).
    Warns :class:`SectionAccuracyWarning` on linear elements.
    """
    if self._warping is None:
        self._warping, self._warp_solutions = compute_warping(
            self._snapshot,
            self.geometric(),
            policy=self._disconnected,
            handle=self._name or "section",
        )
    return self._warping

plastic

plastic() -> PlasticProperties

Rigid-plastic analysis: plastic centroids, fy-weighted plastic moments Mp_*, first-yield shape factors. Requires fy on every material; connectivity-blind (valid for disconnected sections). Invalid for strain-softening materials.

Source code in src/apeGmsh/sections/_analysis.py
def plastic(self) -> PlasticProperties:
    """Rigid-plastic analysis: plastic centroids, fy-weighted plastic
    moments ``Mp_*``, first-yield shape factors.  Requires ``fy`` on
    every material; connectivity-blind (valid for disconnected
    sections).  Invalid for strain-softening materials."""
    if self._plastic is None:
        self._plastic = compute_plastic(
            self._snapshot,
            self.geometric(),
            handle=self._name or "section",
        )
    return self._plastic

stress

stress(*, N: float = 0.0, Vx: float = 0.0, Vy: float = 0.0, Mxx: float = 0.0, Myy: float = 0.0, M11: float = 0.0, M22: float = 0.0, Mzz: float = 0.0) -> SectionStress

Linear-elastic stress recovery for one load vector.

A weighted blend of unit-load fields computed once from the cached geometric + warping solutions — calling with a new load vector never re-solves anything. Sign conventions: N tension-positive; Mxx tension at +y; Myy tension at +x; M11/M22 likewise in the principal frame; Mzz counter-clockwise. See :class:SectionStress for the component list and the per-region access contract.

Under disconnected="sum" the actions distribute per the ADR 0078 policy: N/Mxx/Myy use the global plane-sections composite state unchanged; Mzz goes to parts ∝ GJᵢ/ΣGJ; Vx/Vy ∝ the part flexural-rigidity shares (scalar per axis — exact for parts whose principal axes align with x/y; approximate for in-plane-rotated parts). Consistent with the no-inter-part-shear-transfer lower bound the warping results already carry.

Source code in src/apeGmsh/sections/_analysis.py
def stress(
    self,
    *,
    N: float = 0.0,
    Vx: float = 0.0,
    Vy: float = 0.0,
    Mxx: float = 0.0,
    Myy: float = 0.0,
    M11: float = 0.0,
    M22: float = 0.0,
    Mzz: float = 0.0,
) -> SectionStress:
    """Linear-elastic stress recovery for one load vector.

    A weighted blend of unit-load fields computed once from the
    cached geometric + warping solutions — calling with a new load
    vector never re-solves anything.  Sign conventions: ``N``
    tension-positive; ``Mxx`` tension at ``+y``; ``Myy`` tension at
    ``+x``; ``M11``/``M22`` likewise in the principal frame;
    ``Mzz`` counter-clockwise.  See :class:`SectionStress` for the
    component list and the per-region access contract.

    Under ``disconnected="sum"`` the actions distribute per the
    ADR 0078 policy: ``N``/``Mxx``/``Myy`` use the global
    plane-sections composite state unchanged; ``Mzz`` goes to parts
    ∝ ``GJᵢ/ΣGJ``; ``Vx``/``Vy`` ∝ the part flexural-rigidity
    shares (scalar per axis — exact for parts whose principal axes
    align with x/y; approximate for in-plane-rotated parts).
    Consistent with the no-inter-part-shear-transfer lower bound
    the warping results already carry.
    """
    self.warping()   # ensures solutions (fail-loud under "raise")
    if self._unit_fields is None:
        self._unit_fields = compute_unit_fields(
            self._snapshot, self.geometric(), self._warp_solutions
        )
    return SectionStress(
        self._snapshot,
        self._unit_fields,
        {"N": N, "Vx": Vx, "Vy": Vy, "Mxx": Mxx, "Myy": Myy,
         "M11": M11, "M22": M22, "Mzz": Mzz},
    )

analyze

analyze() -> 'SectionProperties'

Run every available analysis (S1–S3: geometric + warping + plastic when fy is available). Returns self.

Source code in src/apeGmsh/sections/_analysis.py
def analyze(self) -> "SectionProperties":
    """Run every available analysis (S1–S3: geometric + warping +
    plastic when fy is available).  Returns self."""
    self.geometric()
    self.warping()
    if not self._snapshot.geometric_only and all(
        m.fy is not None for m in self._snapshot.materials
    ):
        self.plastic()
    return self

to_elastic_section

to_elastic_section(*, E: float | None = None, G: float | None = None, ndm: int = 3)

Eagerly lower this analyzer into a plain populated :class:~apeGmsh.opensees.section.ElasticSection.

Runs the same shared lowering as ops.section.ComputedSection(analysis=...) — authoring Ixx_c → Iz, Iyy_c → Iy, J → J, As_y/A → alphaY, As_x/A → alphaZ — but resolves now and returns an inspectable, analyzer-decoupled primitive.

E / G default from the single material on a homogeneous analyzer; for a composite they are required reference moduli (transformed-section EA/E, EI/E, GJ/G) and for a geometric-only analyzer they are required deck moduli. ndm=3 (default) emits the 3-D form; ndm=2 the 2-D shear-flexible form.

Source code in src/apeGmsh/sections/_analysis.py
def to_elastic_section(
    self,
    *,
    E: float | None = None,
    G: float | None = None,
    ndm: int = 3,
):
    """Eagerly lower this analyzer into a plain populated
    :class:`~apeGmsh.opensees.section.ElasticSection`.

    Runs the same shared lowering as
    ``ops.section.ComputedSection(analysis=...)`` — authoring
    ``Ixx_c → Iz``, ``Iyy_c → Iy``, ``J → J``, ``As_y/A → alphaY``,
    ``As_x/A → alphaZ`` — but resolves **now** and returns an
    inspectable, analyzer-decoupled primitive.

    ``E`` / ``G`` default from the single material on a homogeneous
    analyzer; for a **composite** they are required reference
    moduli (transformed-section ``EA/E``, ``EI/E``, ``GJ/G``) and
    for a **geometric-only** analyzer they are required deck
    moduli.  ``ndm=3`` (default) emits the 3-D form; ``ndm=2`` the
    2-D shear-flexible form.
    """
    from apeGmsh.opensees.section.beam import ElasticSection

    from ._lowering import lower_to_elastic

    params = lower_to_elastic(self, E=E, G=G)
    return ElasticSection(**params.section_kwargs(ndm))

summary

summary() -> str

Plain-text properties report.

Source code in src/apeGmsh/sections/_analysis.py
def summary(self) -> str:
    """Plain-text properties report."""
    snap = self._snapshot
    handle = self._name or "section"
    lines = [
        f"SectionProperties '{handle}'",
        f"  elements : {snap.n_elements} "
        f"({', '.join(sorted({b.type_name for b in snap.blocks}))})",
        f"  nodes    : {len(snap.coords)}",
        f"  parts    : {snap.n_components} "
        f"(disconnected policy: {self._disconnected})",
    ]
    if snap.geometric_only:
        lines.append("  materials: geometric-only mode (unit moduli)")
    else:
        for pg, mat, a in zip(
            snap.material_names, snap.materials,
            self.geometric().material_areas,
        ):
            fy = f", fy={mat.fy:g}" if mat.fy is not None else ""
            lines.append(
                f"  materials: '{pg}' E={mat.E:g} nu={mat.nu:g}"
                f"{fy}  (A={a:.6g})"
            )
    g = self.geometric()
    lines += [
        f"  area={g.area:.6g}  perimeter={g.perimeter:.6g}"
        + (f"  mass={g.mass:.6g}" if g.mass is not None else ""),
        f"  centroid=({g.cx:.6g}, {g.cy:.6g})  phi={g.phi:.4g} deg",
        f"  EA={g.EA:.6g}",
        f"  EIxx_c={g.EIxx_c:.6g}  EIyy_c={g.EIyy_c:.6g}  "
        f"EIxy_c={g.EIxy_c:.6g}",
        f"  EI11_c={g.EI11_c:.6g}  EI22_c={g.EI22_c:.6g}",
    ]
    if g.e_ref is not None:
        lines.append(
            f"  (single modulus E={g.e_ref:g}: "
            f"A_eff={g.EA / g.e_ref:.6g}, Ixx_c={g.Ixx_c:.6g}, "
            f"Iyy_c={g.Iyy_c:.6g})"
        )
    else:
        lines.append(
            "  (composite: unprefixed accessors raise — use "
            "transformed(e_ref=...))"
        )
    return "\n".join(lines)

plot_mesh

plot_mesh(*, ax=None)

Matplotlib wireframe of the section mesh, colored by material region.

Source code in src/apeGmsh/sections/_analysis.py
def plot_mesh(self, *, ax=None):
    """Matplotlib wireframe of the section mesh, colored by
    material region."""
    import matplotlib.pyplot as plt
    import matplotlib.tri as mtri

    if ax is None:
        _, ax = plt.subplots()
    snap = self._snapshot
    cmap = plt.get_cmap("tab10")
    for m, pg in enumerate(snap.material_names):
        tris = []
        for b in snap.blocks:
            corners = b.conn[b.mat_idx == m][:, : b.n_corners]
            if not len(corners):
                continue
            if b.n_corners == 3:
                tris.append(corners)
            else:
                tris.append(corners[:, [0, 1, 2]])
                tris.append(corners[:, [0, 2, 3]])
        if not tris:
            continue
        tri = mtri.Triangulation(
            snap.coords[:, 0], snap.coords[:, 1],
            triangles=np.concatenate(tris),
        )
        ax.triplot(tri, color=cmap(m % 10), linewidth=0.3, label=pg)
    ax.set_aspect("equal")
    if not snap.geometric_only:
        ax.legend(loc="best", fontsize="small")
    return ax

plot_section

plot_section(*, centroid: bool = True, shear_centre: bool = True, principal_axes: bool = True, ax=None)

Section outline + glyph overlay: elastic centroid, shear centre (triggers :meth:warping — pass shear_centre=False for disconnected sections under the default policy), principal axes at phi.

Source code in src/apeGmsh/sections/_analysis.py
def plot_section(
    self,
    *,
    centroid: bool = True,
    shear_centre: bool = True,
    principal_axes: bool = True,
    ax=None,
):
    """Section outline + glyph overlay: elastic centroid, shear
    centre (triggers :meth:`warping` — pass ``shear_centre=False``
    for disconnected sections under the default policy), principal
    axes at ``phi``."""
    import math


    ax = self.plot_mesh(ax=ax)
    geo = self.geometric()
    if centroid:
        ax.plot(geo.cx, geo.cy, "k+", markersize=12, label="centroid")
    if shear_centre:
        warp = self.warping()
        ax.plot(warp.x_sc, warp.y_sc, "rx", markersize=10,
                label="shear centre")
    if principal_axes:
        theta = math.radians(geo.phi)
        span = 0.35 * max(
            float(np.ptp(self._snapshot.coords[:, 0])),
            float(np.ptp(self._snapshot.coords[:, 1])),
        )
        for ang, style, lbl in (
            (theta, "-", "11"), (theta + math.pi / 2, "--", "22"),
        ):
            dx, dy = span * math.cos(ang), span * math.sin(ang)
            ax.plot([geo.cx - dx, geo.cx + dx],
                    [geo.cy - dy, geo.cy + dy],
                    linestyle=style, color="0.4", linewidth=0.8)
            ax.annotate(lbl, (geo.cx + dx, geo.cy + dy), color="0.4")
    ax.legend(loc="best", fontsize="small")
    return ax

plot_warping

plot_warping(*, shear_flow: bool = False, ax=None, cmap: str = 'viridis', levels: int = 15, max_arrows: int = 800)

Filled contour of the Saint-Venant warping function ω.

Triggers the (memoized) :meth:warping solve. Works for connected sections and per-part under disconnected="sum" (each part carries its own ∫ω dA = 0 reference).

shear_flow=True overlays a quiver of the unit-torsion shear stress τ per Mzz = 1 (direction = the shear-flow pattern). It rides the stress unit fields; under disconnected="sum" each part shows its own flow for its GJᵢ/ΣGJ share of the torque.

Source code in src/apeGmsh/sections/_analysis.py
def plot_warping(
    self,
    *,
    shear_flow: bool = False,
    ax=None,
    cmap: str = "viridis",
    levels: int = 15,
    max_arrows: int = 800,
):
    """Filled contour of the Saint-Venant warping function ω.

    Triggers the (memoized) :meth:`warping` solve.  Works for
    connected sections and per-part under ``disconnected="sum"``
    (each part carries its own ``∫ω dA = 0`` reference).

    ``shear_flow=True`` overlays a quiver of the **unit-torsion
    shear stress** ``τ per Mzz = 1`` (direction = the shear-flow
    pattern).  It rides the stress unit fields; under
    ``disconnected="sum"`` each part shows its own flow for its
    ``GJᵢ/ΣGJ`` share of the torque.
    """
    import matplotlib.pyplot as plt
    import matplotlib.tri as mtri

    self.warping()
    snap = self._snapshot
    omega = np.full(len(snap.coords), np.nan)
    for sol in self._warp_solutions:
        omega[sol.node_rows] = sol.omega

    if ax is None:
        _, ax = plt.subplots()
    tri = mtri.Triangulation(
        snap.coords[:, 0], snap.coords[:, 1],
        triangles=self._corner_triangles(),
    )
    tcs = ax.tricontourf(
        tri, np.nan_to_num(omega), levels=levels, cmap=cmap,
    )
    ax.figure.colorbar(tcs, ax=ax, label="warping function ω")
    if shear_flow:
        st = self.stress(Mzz=1.0)
        tzx = np.nan_to_num(st.get("tau_zx_mzz"))
        tzy = np.nan_to_num(st.get("tau_zy_mzz"))
        idx = np.unique(np.linspace(
            0, len(snap.coords) - 1,
            min(max_arrows, len(snap.coords)),
        ).astype(int))
        ax.quiver(
            snap.coords[idx, 0], snap.coords[idx, 1],
            tzx[idx], tzy[idx],
            color="k", width=0.002, alpha=0.75,
        )
    ax.set_aspect("equal")
    ax.set_title("Saint-Venant warping"
                 + (" + unit-torsion shear flow" if shear_flow else ""))
    return ax

plot

plot(*, figsize: tuple[float, float] = (11.0, 5.0))

One-call overview figure: the glyphed section view (left) beside the :meth:summary report (right). Returns the matplotlib Figure.

Triggers :meth:geometric + :meth:warping (memoized); for a disconnected section under the default policy this fails loud like :meth:warping does.

Source code in src/apeGmsh/sections/_analysis.py
def plot(self, *, figsize: tuple[float, float] = (11.0, 5.0)):
    """One-call overview figure: the glyphed section view (left)
    beside the :meth:`summary` report (right).  Returns the
    matplotlib ``Figure``.

    Triggers :meth:`geometric` + :meth:`warping` (memoized); for a
    disconnected section under the default policy this fails loud
    like :meth:`warping` does.
    """
    import matplotlib.pyplot as plt

    fig, (ax_plot, ax_text) = plt.subplots(
        1, 2, figsize=figsize, width_ratios=(3, 2),
    )
    self.plot_section(ax=ax_plot)
    ax_text.axis("off")
    ax_text.text(
        0.0, 1.0, self.summary(),
        transform=ax_text.transAxes,
        va="top", ha="left", family="monospace", fontsize=8,
    )
    fig.suptitle(self._name or "section")
    return fig

viewer

viewer(*, blocking: bool = True)

Open the Qt section inspector (ADR 0078 S6).

Left: the meshed section with glyph overlays, switching to stress contours when a component is picked. Right: tabbed property tables (Geometric / Warping / Plastic as available; composite sections gain an e_ref input driving a transformed column) and six live load inputs that re-blend the precomputed unit stress fields — no solve ever runs on the UI thread.

Notebooks must pass blocking=False (a blocking Qt loop kills the kernel; enable %gui qt so the window stays responsive). Qt absent raises ImportError with install guidance; every capability is equally reachable headless via :meth:summary, :meth:plot_section, and stress(...).plot().

Source code in src/apeGmsh/sections/_analysis.py
def viewer(self, *, blocking: bool = True):
    """Open the Qt section inspector (ADR 0078 S6).

    Left: the meshed section with glyph overlays, switching to
    stress contours when a component is picked.  Right: tabbed
    property tables (Geometric / Warping / Plastic as available;
    composite sections gain an ``e_ref`` input driving a
    transformed column) and six live load inputs that re-blend the
    precomputed unit stress fields — no solve ever runs on the UI
    thread.

    **Notebooks must pass** ``blocking=False`` (a blocking Qt loop
    kills the kernel; enable ``%gui qt`` so the window stays
    responsive).  Qt absent raises ``ImportError`` with install
    guidance; every capability is equally reachable headless via
    :meth:`summary`, :meth:`plot_section`, and
    ``stress(...).plot()``.
    """
    from ._inspector import launch_inspector
    return launch_inspector(self, blocking=blocking)

SectionMaterial dataclass

SectionMaterial(*, E: float, nu: float, G: float | None = None, fy: float | None = None, density: float | None = None, name: str | None = None)

Material assigned to one physical-group region of a cross-section.

Parameters

E Young's modulus (> 0). Weights the geometric integrals. nu Poisson's ratio (−1 < nu < 0.5). G Shear-modulus override; default is the isotropic E / (2 (1 + nu)). An independent G exists for equivalent shear media — smeared battens / lacing, corrugated webs: a strip with near-zero E and a calibrated G transfers shear between parts without adding parasitic flexural area. The solver assembles the E-field (geometric) and G-field (warping) separately, so the override is exact, not a fudge. fy Yield stress (> 0). Required by plastic(). density Mass density; when every material carries one, the analyzer reports mass per unit length. name Display-only label (tables, plots). Falls back to the physical group name where one is needed.

shear_modulus property

shear_modulus: float

Effective shear modulus: the G override when given, else the isotropic E / (2 (1 + nu)).

settings

settings() -> int

Open the global preferences editor (modal dialog).

Persists changes to the JSON file at PreferencesManager.path (platform-appropriate config dir). Spins up a QApplication if none exists.

Returns the dialog result code (QDialog.Accepted / Rejected).

Source code in src/apeGmsh/viewers/__init__.py
def settings() -> int:
    """Open the global preferences editor (modal dialog).

    Persists changes to the JSON file at
    ``PreferencesManager.path`` (platform-appropriate config dir).
    Spins up a ``QApplication`` if none exists.

    Returns the dialog result code (``QDialog.Accepted`` / ``Rejected``).
    """
    from .ui.preferences_dialog import open_preferences_dialog
    return open_preferences_dialog()

theme_editor

theme_editor() -> int

Open the theme editor (modal dialog with live preview).

Custom themes are persisted under ThemeManager.themes_dir() (platform-appropriate config dir). Spins up a QApplication if none exists.

Returns the dialog result code (QDialog.Accepted / Rejected).

Source code in src/apeGmsh/viewers/__init__.py
def theme_editor() -> int:
    """Open the theme editor (modal dialog with live preview).

    Custom themes are persisted under ``ThemeManager.themes_dir()``
    (platform-appropriate config dir). Spins up a ``QApplication`` if
    none exists.

    Returns the dialog result code (``QDialog.Accepted`` / ``Rejected``).
    """
    from .ui.theme_editor_dialog import open_theme_editor
    return open_theme_editor()

preview

preview(session: Any = None, *, mode: str = 'mesh', dims: list[int] | None = None, show_nodes: bool = True, browser: bool = False, return_fig: bool = False) -> Any

Unified entry point — routes to preview_model or preview_mesh.

Parameters

mode : {"model", "mesh"} Which scene to render. Default "mesh". show_nodes : bool Mesh mode only — render the full mesh-node cloud as a separate trace. Ignored in model mode. browser : bool Open in a new browser tab instead of rendering inline. return_fig : bool Skip display and return the raw plotly Figure.

Source code in src/apeGmsh/viz/NotebookPreview.py
def preview(
    session: Any = None,
    *,
    mode: str = "mesh",
    dims: list[int] | None = None,
    show_nodes: bool = True,
    browser: bool = False,
    return_fig: bool = False,
) -> Any:
    """Unified entry point — routes to ``preview_model`` or ``preview_mesh``.

    Parameters
    ----------
    mode : {"model", "mesh"}
        Which scene to render. Default ``"mesh"``.
    show_nodes : bool
        Mesh mode only — render the full mesh-node cloud as a
        separate trace. Ignored in model mode.
    browser : bool
        Open in a new browser tab instead of rendering inline.
    return_fig : bool
        Skip display and return the raw plotly ``Figure``.
    """
    if mode == "model":
        return preview_model(
            session, dims=dims, browser=browser, return_fig=return_fig,
        )
    if mode == "mesh":
        return preview_mesh(
            session, dims=dims, show_nodes=show_nodes,
            browser=browser, return_fig=return_fig,
        )
    raise ValueError(f"Unknown preview mode: {mode!r} (expected 'model' or 'mesh')")

workdir

workdir(name: str | Path = 'outputs') -> Path

Return Path(name) after ensuring it exists.

Convention for example notebooks: every script puts its artifacts (capture.h5, recorders/, exports, etc.) under a sibling outputs/ folder so the example directory stays self-contained. Typical use::

from apeGmsh import workdir
OUT = workdir()                 # ./outputs/
cap_path = OUT / 'capture.h5'

Pass an explicit name for nested or non-default layouts (workdir('outputs/run_42')).

Source code in src/apeGmsh/_workdir.py
def workdir(name: str | Path = "outputs") -> Path:
    """Return ``Path(name)`` after ensuring it exists.

    Convention for example notebooks: every script puts its
    artifacts (``capture.h5``, ``recorders/``, exports, etc.) under
    a sibling ``outputs/`` folder so the example directory stays
    self-contained. Typical use::

        from apeGmsh import workdir
        OUT = workdir()                 # ./outputs/
        cap_path = OUT / 'capture.h5'

    Pass an explicit name for nested or non-default layouts
    (``workdir('outputs/run_42')``).
    """
    p = Path(name)
    p.mkdir(parents=True, exist_ok=True)
    return p

Session class

apeGmsh._core.apeGmsh

apeGmsh(*, model_name: str = 'ModelName', verbose: bool = False, save_to: str | Path | None = None, overwrite: bool = True)

Bases: _SessionBase

Standalone single-model Gmsh session with all composites.

Parameters

model_name : str Name passed to gmsh.model.add(). verbose : bool If True, composites print diagnostic messages.

Source code in src/apeGmsh/_core.py
def __init__(
    self,
    *,
    model_name: str = "ModelName",
    verbose: bool = False,
    save_to: str | Path | None = None,
    overwrite: bool = True,
) -> None:
    super().__init__(name=model_name, verbose=verbose)
    # Labels (Tier 1 naming) are auto-created from label= kwargs
    # on geometry methods in both Part and Assembly sessions.
    self._auto_pg_from_label = True
    # Autosave configuration. ``save_to=None`` disables autosave;
    # otherwise ``end()`` writes the neutral-zone HDF5 to this path
    # before finalizing gmsh.  Manual ``g.save()`` uses the same path.
    self._save_to: Path | None = Path(save_to) if save_to else None
    self._overwrite: bool = overwrite
    # ── FEMData cache (Phase 3B.2b-prep / ADR 0038) ──────────
    # The session caches the most recent ``get_fem_data()`` result
    # so repeat calls return the same broker object identity (and
    # downstream consumers — chain-phase shims, future
    # ``g.compose()`` — have a single canonical snapshot to update
    # via ``FEMData.with_*`` transforms).  Every broker mutation
    # (``g.constraints.X`` / ``g.loads.X`` / ``g.masses.X``) bumps
    # ``_fem_counter``; the cached snapshot is fresh iff
    # ``_fem_counter == _fem_counter_at_build``.  The first
    # extraction stamps ``_fem_counter_at_build``; any mutation
    # afterwards invalidates the cache and the next
    # ``get_fem_data()`` re-extracts from gmsh + the def lists.
    self._fem: "FEMData | None" = None
    self._fem_counter: int = 0
    self._fem_counter_at_build: int | None = None
    # ── Compose state (Phase 3B.2c / ADR 0038) ────────────────
    # ``_compose_bundles`` holds every ``_RewrittenBundle`` produced
    # by a ``g.compose(...)`` call on this session in compose-call
    # order.  When a broker mutation invalidates the cache, the
    # next ``get_fem_data()`` re-extracts from gmsh + def lists and
    # then re-applies every stored bundle on top — so the composed
    # modules survive any subsequent ``g.constraints.X`` / etc.
    # mutation.
    #
    # ``_fem_from_h5`` flags sessions built via
    # :meth:`apeGmsh.from_h5`: those have no gmsh state, so the
    # cache-stale path must re-use ``_fem`` as the chain head
    # rather than re-extracting from absent gmsh.  3B.2c chooses
    # this scoped-flag approach rather than generalising
    # ``get_fem_data()`` over a missing-gmsh case because the
    # alternative — making ``from_gmsh`` tolerate absent gmsh —
    # would bleed compose-only concerns into every extraction
    # caller.  3B.2d's resolver refactor takes the cleaner cut.
    self._compose_bundles: tuple = ()
    self._fem_from_h5: bool = False

from_h5 classmethod

from_h5(path: 'str | Path', *, model_name: str | None = None, verbose: bool = False) -> 'apeGmsh'

Construct a session in chain phase directly from a saved FEMData.

Skips the gmsh build phase entirely: the loaded FEMData becomes the session's chain head and there is no gmsh kernel behind this session at all. model.h5 persists the FEMData snapshot (nodes, elements, physical groups, labels) — not the geometry kernel — so anything that would read or mutate BRep / mesh state raises :class:~.core._compose_errors.ChainPhaseError naming the H5-safe alternative.

Useful for cross-session composition workflows::

# Day 1
with apeGmsh(model_name="host", save_to="host.h5") as g:
    ...

# Day 2
g = apeGmsh.from_h5("host.h5")
g.compose("module_a.h5", label="A")
g.compose("module_b.h5", label="B")
g.save("final.h5")
What works
  • g.mesh.queries.get_fem_data() — the chain head, and the surface every refusal below points back at.
  • g.compose(...) / compose_inspect(...) / compose_list() and :meth:save.
  • The chain-phase authoring shims, routed through FEMData.with_*: g.constraints.bc / tie / embedded / tied_contact / equalDOF / rigid_link / rigid_diaphragm, plus point g.loads.X / g.masses.X.
  • Kernel-free helpers: g.model.queries.plane / registry, g.view.list_views / count, g.plot.show / savefig / clear / figsize / use_axes.
  • repr() of any composite. The two kernel-backed reprs (g.physical, g.labels) report "no live gmsh kernel — from_h5 session" rather than raising, so debuggers and logging stay usable.
Refused — no live kernel to read

These need the gmsh model and raise on a from_h5 session specifically (a live session still has a kernel, so they stay legal there). Each message names the broker counterpart.

========================= ================================== Surface Guarded members ========================= ================================== g.inspect get_geometry_info, get_mesh_info, print_summary g.physical get_all, get_entities, entities, get_groups_for_entity, get_name, get_tag, summary, get_nodes g.labels entities, get_all, summary, has, reverse_map, labels_for_entity g.mesh.queries get_nodes, get_elements, get_element_properties, get_element_qualities, quality_report g.model.queries bounding_box, center_of_mass, mass, boundary, boundary_curves, boundary_points, adjacencies, entities_in_bounding_box g.mesh.partitioning n_partitions, summary, entity_table, save g.model.io save_step, save_iges, save_dxf, save_msh — the exporters only; the importers are frozen instead (below) g.model.<geometry> find_stale_metadata, and validate_pre_mesh through it g.mesh.recipe check g.parts build_face_map g.rebar resolve g.sections plot_faces g.view add_element_scalar / add_element_vector / add_node_scalar / add_node_vector g.plot geometry, mesh, quality, label_entities, label_nodes, label_elements, physical_groups, physical_groups_mesh ========================= ==================================

Counterparts: fem.inspect for summaries, fem.physical (:class:~.mesh._group_set.PhysicalGroupSet) for physical groups, fem.nodes.labels / fem.elements.labels (:class:~.mesh._group_set.LabelSet) for labels, fem.nodes / fem.elements / fem.info for mesh data, and results.inspect for post-processing — where fem = g.mesh.queries.get_fem_data(). BRep geometry has no counterpart: derive it from mesh coordinates or rebuild the geometry in a live session.

Refused — model frozen

Mutations are refused on any chain-phase session, not just this one: once a FEMData snapshot exists the broker is canonical, and mutating gmsh would silently desync the two. Listed by composite — each guards its mutating operations at a shared chokepoint, so the coverage is per-composite rather than the per-method enumeration given for the reads above.

  • Geometry — g.model.<geometry> (via Model._register, plus add_wire, which creates OCC geometry but is deliberately not registered), g.model.boolean, g.model.transforms, g.model.io.heal_shapes / load_msh / load_geo, and g.model.queries.remove / remove_duplicates / make_conformal (mutations despite the composite name).
  • Mesh — g.mesh.generation, g.mesh.editing, g.mesh.sizing, g.mesh.structured, g.mesh.recipe, and g.mesh.partitioning (its mutating ops partition / partition_explicit / unpartition / renumber; the composite's four readers take the kernel guard instead, and are listed in the read table above).
  • Naming — g.physical.add / set_name / remove / remove_name / remove_all, and g.labels.add / remove / rename / promote_to_physical.
  • Assembly — g.parts instance registration, g.sections builds, g.rebar.place.
Refused — resolves from live geometry

g.constraints.contact / contact_plane / interface, g.embed, g.reinforce and g.decouple_node record definitions that are resolved against live gmsh at extraction. A from_h5 session never re-extracts, so the definition would be stored and silently never applied — declare these in the source part session before saving; the resolved records round-trip through model.h5 and survive g.compose.

Parameters

path : str or Path Path to a model.h5 written by :meth:save / :meth:FEMData.to_h5. model_name : str or None Session name (used by :meth:save for /meta/model_name). Defaults to the source file's stem. verbose : bool, default False Verbose-mode flag forwarded to the constructor.

Raises

~.core._compose_errors.ChainPhaseError From any surface listed above. The message names the offending call and the alternative that answers it.

Source code in src/apeGmsh/_core.py
@classmethod
def from_h5(
    cls,
    path: "str | Path",
    *,
    model_name: str | None = None,
    verbose: bool = False,
) -> "apeGmsh":
    """Construct a session in chain phase directly from a saved FEMData.

    Skips the gmsh build phase entirely: the loaded FEMData becomes
    the session's chain head and **there is no gmsh kernel behind
    this session at all**.  ``model.h5`` persists the FEMData
    snapshot (nodes, elements, physical groups, labels) — not the
    geometry kernel — so anything that would read or mutate BRep /
    mesh state raises :class:`~.core._compose_errors.ChainPhaseError`
    naming the H5-safe alternative.

    Useful for cross-session composition workflows::

        # Day 1
        with apeGmsh(model_name="host", save_to="host.h5") as g:
            ...

        # Day 2
        g = apeGmsh.from_h5("host.h5")
        g.compose("module_a.h5", label="A")
        g.compose("module_b.h5", label="B")
        g.save("final.h5")

    What works
    ----------
    * ``g.mesh.queries.get_fem_data()`` — the chain head, and the
      surface every refusal below points back at.
    * ``g.compose(...)`` / ``compose_inspect(...)`` /
      ``compose_list()`` and :meth:`save`.
    * The chain-phase authoring shims, routed through
      ``FEMData.with_*``: ``g.constraints.bc`` / ``tie`` /
      ``embedded`` / ``tied_contact`` / ``equalDOF`` /
      ``rigid_link`` / ``rigid_diaphragm``, plus point
      ``g.loads.X`` / ``g.masses.X``.
    * Kernel-free helpers: ``g.model.queries.plane`` /
      ``registry``, ``g.view.list_views`` / ``count``,
      ``g.plot.show`` / ``savefig`` / ``clear`` / ``figsize`` /
      ``use_axes``.
    * ``repr()`` of any composite.  The two kernel-backed reprs
      (``g.physical``, ``g.labels``) report
      ``"no live gmsh kernel — from_h5 session"`` rather than
      raising, so debuggers and logging stay usable.

    Refused — no live kernel to read
    --------------------------------
    These need the gmsh model and raise on a ``from_h5`` session
    specifically (a live session still has a kernel, so they stay
    legal there).  Each message names the broker counterpart.

    =========================  ==================================
    Surface                    Guarded members
    =========================  ==================================
    ``g.inspect``              ``get_geometry_info``,
                               ``get_mesh_info``, ``print_summary``
    ``g.physical``             ``get_all``, ``get_entities``,
                               ``entities``,
                               ``get_groups_for_entity``,
                               ``get_name``, ``get_tag``,
                               ``summary``, ``get_nodes``
    ``g.labels``               ``entities``, ``get_all``,
                               ``summary``, ``has``,
                               ``reverse_map``,
                               ``labels_for_entity``
    ``g.mesh.queries``         ``get_nodes``, ``get_elements``,
                               ``get_element_properties``,
                               ``get_element_qualities``,
                               ``quality_report``
    ``g.model.queries``        ``bounding_box``,
                               ``center_of_mass``, ``mass``,
                               ``boundary``, ``boundary_curves``,
                               ``boundary_points``,
                               ``adjacencies``,
                               ``entities_in_bounding_box``
    ``g.mesh.partitioning``    ``n_partitions``, ``summary``,
                               ``entity_table``, ``save``
    ``g.model.io``             ``save_step``, ``save_iges``,
                               ``save_dxf``, ``save_msh`` — the
                               exporters only; the importers are
                               frozen instead (below)
    ``g.model.<geometry>``     ``find_stale_metadata``, and
                               ``validate_pre_mesh`` through it
    ``g.mesh.recipe``          ``check``
    ``g.parts``                ``build_face_map``
    ``g.rebar``                ``resolve``
    ``g.sections``             ``plot_faces``
    ``g.view``                 ``add_element_scalar`` /
                               ``add_element_vector`` /
                               ``add_node_scalar`` /
                               ``add_node_vector``
    ``g.plot``                 ``geometry``, ``mesh``, ``quality``,
                               ``label_entities``, ``label_nodes``,
                               ``label_elements``,
                               ``physical_groups``,
                               ``physical_groups_mesh``
    =========================  ==================================

    Counterparts: ``fem.inspect`` for summaries, ``fem.physical``
    (:class:`~.mesh._group_set.PhysicalGroupSet`) for physical
    groups, ``fem.nodes.labels`` / ``fem.elements.labels``
    (:class:`~.mesh._group_set.LabelSet`) for labels,
    ``fem.nodes`` / ``fem.elements`` / ``fem.info`` for mesh data,
    and ``results.inspect`` for post-processing — where
    ``fem = g.mesh.queries.get_fem_data()``.  BRep geometry has no
    counterpart: derive it from mesh coordinates or rebuild the
    geometry in a live session.

    Refused — model frozen
    ----------------------
    Mutations are refused on **any** chain-phase session, not just
    this one: once a FEMData snapshot exists the broker is
    canonical, and mutating gmsh would silently desync the two.
    Listed by composite — each guards its mutating operations at a
    shared chokepoint, so the coverage is per-composite rather than
    the per-method enumeration given for the reads above.

    * Geometry — ``g.model.<geometry>`` (via ``Model._register``,
      plus ``add_wire``, which creates OCC geometry but is
      deliberately not registered),
      ``g.model.boolean``, ``g.model.transforms``,
      ``g.model.io.heal_shapes`` / ``load_msh`` / ``load_geo``,
      and ``g.model.queries.remove`` / ``remove_duplicates`` /
      ``make_conformal`` (mutations despite the composite name).
    * Mesh — ``g.mesh.generation``, ``g.mesh.editing``,
      ``g.mesh.sizing``, ``g.mesh.structured``, ``g.mesh.recipe``,
      and ``g.mesh.partitioning`` (its mutating ops ``partition`` /
      ``partition_explicit`` / ``unpartition`` / ``renumber``; the
      composite's four readers take the kernel guard instead, and
      are listed in the read table above).
    * Naming — ``g.physical.add`` / ``set_name`` / ``remove`` /
      ``remove_name`` / ``remove_all``, and ``g.labels.add`` /
      ``remove`` / ``rename`` / ``promote_to_physical``.
    * Assembly — ``g.parts`` instance registration,
      ``g.sections`` builds, ``g.rebar.place``.

    Refused — resolves from live geometry
    -------------------------------------
    ``g.constraints.contact`` / ``contact_plane`` / ``interface``,
    ``g.embed``, ``g.reinforce`` and ``g.decouple_node`` record
    definitions that are resolved against live gmsh at extraction.
    A ``from_h5`` session never re-extracts, so the definition
    would be stored and silently never applied — declare these in
    the source part session before saving; the resolved records
    round-trip through ``model.h5`` and survive ``g.compose``.

    Parameters
    ----------
    path : str or Path
        Path to a ``model.h5`` written by :meth:`save` /
        :meth:`FEMData.to_h5`.
    model_name : str or None
        Session name (used by :meth:`save` for ``/meta/model_name``).
        Defaults to the source file's stem.
    verbose : bool, default False
        Verbose-mode flag forwarded to the constructor.

    Raises
    ------
    ~.core._compose_errors.ChainPhaseError
        From any surface listed above.  The message names the
        offending call and the alternative that answers it.
    """
    from .mesh.FEMData import FEMData

    p = Path(path)
    loaded_fem = FEMData.from_h5(str(p))
    name = model_name if model_name is not None else p.stem
    instance = cls(model_name=name, verbose=verbose)
    instance._fem = loaded_fem
    instance._fem_from_h5 = True
    # Mark the cache fresh so the first ``get_fem_data()`` returns
    # the loaded chain head without an extraction attempt.
    instance._mark_fem_fresh()
    # Instantiate the session composites so chain-phase APIs that
    # touch ``g.mesh.queries.get_fem_data()`` / ``g.compose`` /
    # ``g.save`` work without ``begin()`` ever running.  No gmsh
    # state is created here — composite constructors only require
    # the parent session.  Every gmsh-backed sub-API is guarded
    # (kernel reads via ``raise_if_no_live_kernel``, mutations via
    # the chain-phase freeze guard); the docstring above lists the
    # surfaces and their H5-safe counterparts.
    instance._create_composites()
    return instance

decouple_node

decouple_node(*, coords: 'tuple[float, float, float] | None' = None, point: 'str | None' = None, label: 'str | None' = None) -> Any

Declare a decoupled node — an auxiliary node that is not a Gmsh mesh vertex (spring/dashpot ground, rigidDiaphragm master, control node, load/mass anchor).

Exactly one of coords=(x, y, z) or point="label" locates it; point= is snapshotted to coordinates at mesh-extraction time. label is an optional friendly name.

The node is appended to fem.nodes at extraction with a deterministic tag above every mesh node (dedup-immune by construction) and provenance == "decoupled". It carries no ndf — DOF count is a bridge concern (ops.ndf).

Returns the :class:~apeGmsh._kernel.defs.decoupled.DecoupledNodeDef handle; its tag is populated after g.mesh.queries.get_fem_data(...).

Source code in src/apeGmsh/_core.py
def decouple_node(
    self,
    *,
    coords: "tuple[float, float, float] | None" = None,
    point: "str | None" = None,
    label: "str | None" = None,
) -> Any:
    """Declare a decoupled node — an auxiliary node that is **not**
    a Gmsh mesh vertex (spring/dashpot ground, ``rigidDiaphragm``
    master, control node, load/mass anchor).

    Exactly one of ``coords=(x, y, z)`` or ``point="label"`` locates
    it; ``point=`` is snapshotted to coordinates at mesh-extraction
    time.  ``label`` is an optional friendly name.

    The node is appended to ``fem.nodes`` at extraction with a
    deterministic tag above every mesh node (dedup-immune by
    construction) and ``provenance == "decoupled"``.  It carries
    **no** ``ndf`` — DOF count is a bridge concern (``ops.ndf``).

    Returns the :class:`~apeGmsh._kernel.defs.decoupled.DecoupledNodeDef`
    handle; its ``tag`` is populated after
    ``g.mesh.queries.get_fem_data(...)``.
    """
    return self.decoupled_nodes.add(
        coords=coords, point=point, label=label,
    )

save

save(path: str | Path | None = None) -> Path

Write the neutral-zone model.h5 for this session.

Persists what the session knows about the model: nodes, elements, physical groups, labels, constraints, loads, masses. Downstream solver enrichment (e.g. apeSees(fem).h5(p)) is a separate user-driven action and not invoked here.

Parameters

path : str, Path, or None Destination file. None (default) uses the save_to given to the constructor. Raises if neither is set.

Returns the resolved path.

Source code in src/apeGmsh/_core.py
def save(self, path: str | Path | None = None) -> Path:
    """Write the neutral-zone ``model.h5`` for this session.

    Persists what the session knows about the model: nodes,
    elements, physical groups, labels, constraints, loads, masses.
    Downstream solver enrichment (e.g. ``apeSees(fem).h5(p)``) is
    a separate user-driven action and not invoked here.

    Parameters
    ----------
    path : str, Path, or None
        Destination file.  ``None`` (default) uses the ``save_to``
        given to the constructor.  Raises if neither is set.

    Returns the resolved path.
    """
    if path is None and self._save_to is None:
        raise RuntimeError(
            "g.save() requires a path — either pass one explicitly "
            "or construct the session with save_to=<path>."
        )
    target = self._resolve_save_target(path)
    if target.exists() and not self._overwrite:
        raise FileExistsError(
            f"{target} already exists and overwrite=False."
        )
    self._do_save(target)
    return target

compose

compose(source: 'str | Path', *, label: str, **kwargs: Any) -> 'ComposedModule'

Merge a previously-saved apeGmsh model into this session.

See :meth:apeGmsh.mesh._compose.Compose.compose for the full signature, validation contract, and exception types. Phase 3B.1 scaffolds the facade — the merge engine itself lands in Phase 3B.2.

Source code in src/apeGmsh/_core.py
def compose(
    self,
    source: "str | Path",
    *,
    label: str,
    **kwargs: Any,
) -> "ComposedModule":
    """Merge a previously-saved apeGmsh model into this session.

    See :meth:`apeGmsh.mesh._compose.Compose.compose` for the full
    signature, validation contract, and exception types.  Phase
    3B.1 scaffolds the facade — the merge engine itself lands in
    Phase 3B.2.
    """
    return self._compose_facade().compose(source, label=label, **kwargs)

compose_inspect

compose_inspect(path: 'str | Path') -> dict

Read a module's H5 header without composing it.

See :meth:apeGmsh.mesh._compose.Compose.compose_inspect for the returned dict shape.

Source code in src/apeGmsh/_core.py
def compose_inspect(self, path: "str | Path") -> dict:
    """Read a module's H5 header without composing it.

    See :meth:`apeGmsh.mesh._compose.Compose.compose_inspect` for
    the returned dict shape.
    """
    return self._compose_facade().compose_inspect(path)

compose_list

compose_list() -> 'tuple[ComposedModule, ...]'

Composed modules currently on this session.

See :meth:apeGmsh.mesh._compose.Compose.compose_list.

Source code in src/apeGmsh/_core.py
def compose_list(self) -> "tuple[ComposedModule, ...]":
    """Composed modules currently on this session.

    See :meth:`apeGmsh.mesh._compose.Compose.compose_list`.
    """
    return self._compose_facade().compose_list()

compose_tree

compose_tree() -> 'tuple'

Derived nested-compose tree view of this session's modules.

See :meth:apeGmsh.mesh._compose.Compose.compose_tree.

Source code in src/apeGmsh/_core.py
def compose_tree(self) -> "tuple":
    """Derived nested-compose tree view of this session's modules.

    See :meth:`apeGmsh.mesh._compose.Compose.compose_tree`.
    """
    return self._compose_facade().compose_tree()

Base

apeGmsh._session._SessionBase

_SessionBase(name: str, *, verbose: bool = False)

Base class for objects that own a Gmsh session and parent composites.

Source code in src/apeGmsh/_session.py
def __init__(self, name: str, *, verbose: bool = False) -> None:
    self.name: str = name
    self._verbose: bool = verbose
    self._active: bool = False
    # When True, ``Model._register`` auto-creates a physical group
    # for every entity that has a user-supplied ``label=``.  Set to
    # True only on ``Part`` — the main ``apeGmsh`` session leaves
    # this False so labels in the assembly don't produce unwanted PGs.
    self._auto_pg_from_label: bool = False
    # Pre-declare composite slots as None
    for attr_name, _, _, _ in self._COMPOSITES:
        setattr(self, attr_name, None)

is_active property

is_active: bool

True when the wrapped Gmsh session is open.

begin

begin(*, verbose: bool | None = None) -> '_SessionBase'

Open a Gmsh session, create composites.

Parameters

verbose : bool or None Override the verbosity set in __init__. None keeps the current value.

Returns self for chaining.

Source code in src/apeGmsh/_session.py
def begin(self, *, verbose: bool | None = None) -> "_SessionBase":
    """Open a Gmsh session, create composites.

    Parameters
    ----------
    verbose : bool or None
        Override the verbosity set in ``__init__``.  ``None`` keeps
        the current value.

    Returns ``self`` for chaining.
    """
    if self._active:
        raise RuntimeError(
            f"{type(self).__name__} '{self.name}' session is already open."
        )
    if verbose is not None:
        self._verbose = verbose
    _gmsh_acquire()
    try:
        gmsh.model.add(self.name)
        if self._verbose:
            print(f"Gmsh version: {gmsh.__version__}")
        self._create_composites()
    except BaseException:
        # ``_active`` is still False, so ``end()`` will never run for
        # this session — release the acquire here or the refcount
        # leaks and gmsh can never finalize for the process lifetime.
        # BaseException: a KeyboardInterrupt mid-begin in a notebook
        # leaves the kernel alive and must not leak either.
        _gmsh_release()
        raise
    self._active = True
    return self

end

end() -> None

Close the Gmsh session.

If the subclass set a _save_to path (autosave configured at construction), the broker snapshot is written before gmsh.finalize(). Save failures are logged and swallowed — the gmsh process must still finalize.

Source code in src/apeGmsh/_session.py
def end(self) -> None:
    """Close the Gmsh session.

    If the subclass set a ``_save_to`` path (autosave configured at
    construction), the broker snapshot is written before
    ``gmsh.finalize()``.  Save failures are logged and swallowed —
    the gmsh process must still finalize.
    """
    if self._active:
        save_to = getattr(self, "_save_to", None)
        if save_to is not None:
            try:
                # A directory save_to resolves to ``<dir>/<name>.h5``
                # so autosave matches g.save(); a bare directory
                # truncate-opens as a file and fails on Windows.
                resolve = getattr(self, "_resolve_save_target", None)
                target = resolve(None) if resolve is not None else save_to
                self._do_save(target)
            except Exception as exc:  # noqa: BLE001
                import warnings
                warnings.warn(
                    f"autosave to {save_to} failed: {exc!r}",
                    stacklevel=2,
                )
        _gmsh_release()
        self._active = False