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.

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.pattern("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

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

Part

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

Bases: _SessionBase

An isolated geometry unit — no meshing, no physical groups.

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),
    )

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, 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. 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,
    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.
    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,
        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}``.
    """
    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.

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, :meth:mortar SurfaceCouplingRecord ============= ===================================================== =================================

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 part label (a key of g.parts._instances). :meth:_add_def validates both labels against the registry 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)])

Optional master_entities / slave_entities (list of (dim, tag)) narrow the search to a subset of the part's entities — useful when a part 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] = []

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 :meth:g.loads.face_spnot fem.nodes.constraints.

Because it is a permanent constraint (not a pattern-scoped quantity), it lives here on g.constraints rather than on g.loads: 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 :meth:g.loads.face_sp. 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 :meth:`g.loads.face_sp` — **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.loads``: 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 :meth:`g.loads.face_sp`. 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)
    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 label whose nodes drive the constraint. slave_label : str Part label 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 label whose nodes drive the constraint.
    slave_label : str
        Part label 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))
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 label 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 label 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 label 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 label 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 label that contains (or whose proximity will select) the master node — typically a centre-of-mass point. slave_label : str Part label 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 label that contains (or whose proximity will
        select) the master node — typically a centre-of-mass
        point.
    slave_label : str
        Part label 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), 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 label that contains (or whose proximity selects) the master node. slave_label : str Part label whose nodes are gathered into the rigid body. master_point : (x, y, z), default (0, 0, 0) Coordinates of the master node. name : str, optional Friendly name.

Returns

RigidBodyDef

Raises

KeyError If either label is not in g.parts.

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.), 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 label that contains (or whose proximity selects)
        the master node.
    slave_label : str
        Part label whose nodes are gathered into the rigid
        body.
    master_point : (x, y, z), default (0, 0, 0)
        Coordinates of the master node.
    name : str, optional
        Friendly name.

    Returns
    -------
    RigidBodyDef

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

    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, name=name))

kinematic_coupling

kinematic_coupling(master_label, slave_label, *, master_point=(0.0, 0.0, 0.0), dofs=None, name=None) -> KinematicCouplingDef

Generalised one-master-many-slaves coupling on a chosen DOF subset.

The "parent" of :meth:rigid_diaphragm and :meth:rigid_body — they are special cases with pre-set DOF lists. Use this directly when you need a non-standard combination, e.g.::

* vertical-only follower: dofs=[3]
* 2-D in-plane rigid:     dofs=[1, 2, 6]
* symmetry plane:         dofs=[1, 4, 5]

Resolution emits a single :class:~apeGmsh.solvers.Constraints.NodeGroupRecord. Downstream this is typically expanded to one ops.equalDOF per slave.

Parameters

master_label : str Part label that owns the master node. slave_label : str Part label whose nodes are slaved. master_point : (x, y, z), default (0, 0, 0) Coordinates of the master node. dofs : list[int], optional 1-based DOFs to couple. Default [1, 2, 3, 4, 5, 6] (full 6-DOF, equivalent to :meth:rigid_body). name : str, optional Friendly name.

Returns

KinematicCouplingDef

Raises

KeyError If either label is not in g.parts.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def kinematic_coupling(self, master_label, slave_label, *,
                       master_point=(0., 0., 0.), dofs=None,
                       name=None) -> KinematicCouplingDef:
    """Generalised one-master-many-slaves coupling on a chosen
    DOF subset.

    The "parent" of :meth:`rigid_diaphragm` and :meth:`rigid_body`
    — they are special cases with pre-set DOF lists. Use this
    directly when you need a non-standard combination, e.g.::

        * vertical-only follower: dofs=[3]
        * 2-D in-plane rigid:     dofs=[1, 2, 6]
        * symmetry plane:         dofs=[1, 4, 5]

    Resolution emits a single
    :class:`~apeGmsh.solvers.Constraints.NodeGroupRecord`.
    Downstream this is typically expanded to one
    ``ops.equalDOF`` per slave.

    Parameters
    ----------
    master_label : str
        Part label that owns the master node.
    slave_label : str
        Part label whose nodes are slaved.
    master_point : (x, y, z), default (0, 0, 0)
        Coordinates of the master node.
    dofs : list[int], optional
        1-based DOFs to couple. Default ``[1, 2, 3, 4, 5, 6]``
        (full 6-DOF, equivalent to :meth:`rigid_body`).
    name : str, optional
        Friendly name.

    Returns
    -------
    KinematicCouplingDef

    Raises
    ------
    KeyError
        If either label is not in ``g.parts``.
    """
    return self._add_def(KinematicCouplingDef(
        master_label=master_label, slave_label=slave_label,
        master_point=master_point, dofs=dofs or [1, 2, 3, 4, 5, 6],
        name=name))

tie

tie(master_label, slave_label, *, master_entities=None, slave_entities=None, dofs=None, tolerance=1.0, 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. Downstream the apeGmsh OpenSees bridge emits these as ASDEmbeddedNodeElement penalty elements (default K = 1e18; tunable on the bridge ingest API).

Parameters

master_label : str Part label of the master surface (the side whose mesh will provide the shape functions). slave_label : str Part label 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 silently skipped — set generously if the two meshes have a small geometric gap, but not so large that the wrong face is selected. Unit-sensitive. 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 : Higher-accuracy variant via Lagrange multipliers.

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,
        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. Downstream the apeGmsh
    OpenSees bridge emits these as ``ASDEmbeddedNodeElement``
    penalty elements (default K = 1e18; tunable on the bridge
    ingest API).

    Parameters
    ----------
    master_label : str
        Part label of the master surface (the side whose mesh
        will provide the shape functions).
    slave_label : str
        Part label 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 silently skipped — set generously if the two
        meshes have a small geometric gap, but not so large
        that the wrong face is selected. **Unit-sensitive.**
    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 : Higher-accuracy variant via Lagrange multipliers.

    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))

distributing_coupling

distributing_coupling(master_label, slave_label, *, master_point=(0.0, 0.0, 0.0), dofs=None, weighting='uniform', name=None) -> DistributingCouplingDef

Not implemented — raises NotImplementedError.

A true distributing coupling (RBE3) distributes a master force/moment to the slave nodes so that Σ Fᵢ = F and Σ rᵢ × Fᵢ = M while leaving the surface free to deform — a force relation, not a kinematic one.

The previous implementation did not do this: it emitted a kinematic mean constraint (u_ref = Σ wᵢ u_surfᵢ) and its weighting="area" option was inverse-distance-from-centroid (physically meaningless — the opposite of tributary area), with no moment-equilibrium term. It silently produced a mechanically wrong model under a correct-looking API, so it is refused rather than shipped.

Use instead, depending on intent:

  • :meth:kinematic_coupling — a DOF-selective rigid coupling of the surface to a reference node.
  • :meth:tie — shape-function interpolation onto a master face (compatible, non-rigid).
  • a distributed nodal load (g.loads) — to introduce a statically-equivalent load without any kinematic tie.
Raises

NotImplementedError Always. Parameters are accepted only so the message is actionable.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def distributing_coupling(self, master_label, slave_label, *,
                          master_point=(0., 0., 0.), dofs=None,
                          weighting="uniform",
                          name=None) -> DistributingCouplingDef:
    """**Not implemented — raises ``NotImplementedError``.**

    A true distributing coupling (RBE3) distributes a master
    force/moment to the slave nodes so that ``Σ Fᵢ = F`` **and**
    ``Σ rᵢ × Fᵢ = M`` while leaving the surface free to deform —
    a *force* relation, not a kinematic one.

    The previous implementation did **not** do this: it emitted a
    *kinematic* mean constraint (``u_ref = Σ wᵢ u_surfᵢ``) and its
    ``weighting="area"`` option was inverse-distance-from-centroid
    (physically meaningless — the opposite of tributary area),
    with no moment-equilibrium term.  It silently produced a
    mechanically wrong model under a correct-looking API, so it is
    refused rather than shipped.

    Use instead, depending on intent:

    * :meth:`kinematic_coupling` — a DOF-selective rigid coupling
      of the surface to a reference node.
    * :meth:`tie` — shape-function interpolation onto a master
      face (compatible, non-rigid).
    * a distributed nodal load (``g.loads``) — to introduce a
      statically-equivalent load without any kinematic tie.

    Raises
    ------
    NotImplementedError
        Always.  Parameters are accepted only so the message is
        actionable.
    """
    raise NotImplementedError(
        "distributing_coupling (RBE3 force distribution) is not "
        "implemented.  The prior implementation silently emitted a "
        "kinematic mean with a physically-meaningless 'area' "
        "weighting and no moment equilibrium.  Use "
        "kinematic_coupling (DOF-selective rigid coupling), tie "
        "(shape-function interpolation), or a distributed nodal "
        "load instead."
    )

embedded

embedded(host_label, embedded_label, *, tolerance=1.0, host_entities=None, embedded_entities=None, 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.

Currently supports:

  • 3-D host: tet4 (Gmsh element type 4) volumes.
  • 2-D host: tri3 (Gmsh element type 2) surfaces.

Higher-order or hex/quad hosts are not yet supported and will be silently skipped — fall back to :meth:tie if you need that.

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 tet4/tri3 elements form the host 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 Reserved; not currently enforced (the resolver accepts any located host record). Retained for API stability. 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. 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
)
Source code in src/apeGmsh/core/ConstraintsComposite.py
def embedded(self, host_label, embedded_label, *, tolerance=1.0,
             host_entities=None, embedded_entities=None,
             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.

    Currently supports:

    * **3-D host:** tet4 (Gmsh element type 4) volumes.
    * **2-D host:** tri3 (Gmsh element type 2) surfaces.

    Higher-order or hex/quad hosts are not yet supported and
    will be silently skipped — fall back to :meth:`tie` if you
    need that.

    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 tet4/tri3 elements form the host
        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
        Reserved; not currently enforced (the resolver accepts
        any located host record).  Retained for API stability.
    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.
    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
        )
    """
    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))

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, name=None) -> TiedContactDef

Bidirectional surface-to-surface tie.

Conceptually a :meth:tie applied in both directions — slave nodes are projected onto the master surface, and master nodes are also projected onto the slave surface, so every node on either side is interpolated against the opposite mesh. Useful when neither side can be picked as clearly finer than the other and you want a symmetric treatment.

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. 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 : Mathematically rigorous Lagrange-multiplier coupling.

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,
                 name=None) -> TiedContactDef:
    """Bidirectional surface-to-surface tie.

    Conceptually a :meth:`tie` applied in **both directions** —
    slave nodes are projected onto the master surface, and
    master nodes are also projected onto the slave surface, so
    every node on either side is interpolated against the
    opposite mesh. Useful when neither side can be picked as
    clearly finer than the other and you want a symmetric
    treatment.

    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.**
    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 : Mathematically rigorous Lagrange-multiplier
        coupling.
    """
    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))

mortar

mortar(master_label, slave_label, *, master_entities=None, slave_entities=None, dofs=None, integration_order=2, name=None) -> MortarDef

Not implemented — raises NotImplementedError.

A true mortar method introduces a Lagrange-multiplier space ψᵢ on the slave side and integrates the coupling operator Bᵢⱼ = ∫_Γ ψᵢ·Nⱼ dΓ over the overlapping surface segments, satisfying the inf-sup (LBB) condition.

The previous implementation did none of that: no segment intersection, no surface integral, no dual basis — it scattered tied_contact collocation weights onto a block-diagonal B with a hardcoded tolerance=10.0 (model-unit dependent → mis-pairs on millimetre models), yet returned a record labelled MORTAR that downstream could not distinguish from a real one. It is refused rather than shipped as a plausible-but-wrong operator.

Use :meth:tied_contact for a collocation-based non-matching tie (the honest version of what the old code actually did).

Raises

NotImplementedError Always. Parameters are accepted only so the message is actionable.

Source code in src/apeGmsh/core/ConstraintsComposite.py
def mortar(self, master_label, slave_label, *,
           master_entities=None, slave_entities=None,
           dofs=None, integration_order=2,
           name=None) -> MortarDef:
    """**Not implemented — raises ``NotImplementedError``.**

    A true mortar method introduces a Lagrange-multiplier space
    ``ψᵢ`` on the slave side and integrates the coupling operator
    ``Bᵢⱼ = ∫_Γ ψᵢ·Nⱼ dΓ`` over the overlapping surface segments,
    satisfying the inf-sup (LBB) condition.

    The previous implementation did **none** of that: no segment
    intersection, no surface integral, no dual basis — it scattered
    ``tied_contact`` collocation weights onto a block-diagonal
    ``B`` with a hardcoded ``tolerance=10.0`` (model-unit
    dependent → mis-pairs on millimetre models), yet returned a
    record labelled ``MORTAR`` that downstream could not
    distinguish from a real one.  It is refused rather than
    shipped as a plausible-but-wrong operator.

    Use :meth:`tied_contact` for a collocation-based non-matching
    tie (the honest version of what the old code actually did).

    Raises
    ------
    NotImplementedError
        Always.  Parameters are accepted only so the message is
        actionable.
    """
    raise NotImplementedError(
        "mortar (∫ ψ·N dΓ Lagrange-multiplier coupling) is not "
        "implemented.  The prior implementation was a collocation "
        "tie with a unit-dependent hardcoded tolerance mislabelled "
        "as MORTAR.  Use tied_contact for a non-matching "
        "collocation tie."
    )

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)

FEMData

FEMData(nodes: NodeComposite, elements: ElementComposite, info: MeshInfo, mesh_selection: 'MeshSelectionStore | 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,
) -> None:
    self.nodes    = nodes
    self.elements = elements
    self.info     = info
    self.mesh_selection = mesh_selection
    self.inspect  = InspectComposite(self)
    # 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 property

partitions: list[int]

Sorted list of partition IDs.

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) -> '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.

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) -> "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.

    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)

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().

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()``.
    """
    from ._femdata_native_io import write_fem_to_h5
    write_fem_to_h5(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/...``).
    """
    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.

The reconstructed object carries nodes, elements (per type), physical groups, and labels. Loads/masses/constraints are not round-tripped (they don't affect snapshot_id and the viewer doesn't need them).

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

    The reconstructed object carries nodes, elements (per type),
    physical groups, and labels. Loads/masses/constraints are not
    round-tripped (they don't affect ``snapshot_id`` and the
    viewer doesn't need them).
    """
    from ._femdata_native_io import read_fem_from_h5
    return read_fem_from_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)

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. The new flow is being designed as part of the viewer rebuild project; see internal_docs/Results_architecture.md (Phase 9).

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. The new
    flow is being designed as part of the viewer rebuild project;
    see ``internal_docs/Results_architecture.md`` (Phase 9).
    """
    raise NotImplementedError(
        "fem.viewer() relied on the legacy Results class which has "
        "been rebuilt. The replacement is part of the viewer rebuild "
        "project (Phase 9 in Results_architecture.md). For mesh-only "
        "viewing in the meantime, use g.mesh.viewer() with no args."
    )

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)

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,
) -> None:
    self._reader = reader
    self._fem = fem
    self._stage_id = stage_id
    self._path = 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.

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).

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) -> 'Results'

Open an apeGmsh native HDF5 results file.

If fem is omitted, the embedded /model/ snapshot is used as the bound FEMData. If fem is provided and the file embeds a snapshot, the two snapshot_id hashes must match.

Source code in src/apeGmsh/results/Results.py
@classmethod
def from_native(
    cls,
    path: str | Path,
    *,
    fem: "Optional[FEMData]" = None,
) -> "Results":
    """Open an apeGmsh native HDF5 results file.

    If ``fem`` is omitted, the embedded ``/model/`` snapshot is
    used as the bound FEMData. If ``fem`` is provided and the file
    embeds a snapshot, the two ``snapshot_id`` hashes must match.
    """
    from .readers._native import NativeReader
    reader = NativeReader(path)
    bound_fem = resolve_bound_fem(reader, fem)
    return cls(reader, fem=bound_fem, path=Path(path))

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) -> 'Results'

Open the result of an OpenSees run driven by Tcl/Py recorders.

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,
) -> "Results":
    """Open the result of an OpenSees run driven by Tcl/Py recorders.

    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.
    """
    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():
        transcoder = RecorderTranscoder(
            spec, out_dir, cached_h5, fem,
            stage_name=stage_name,
            stage_kind=stage_kind,
            file_format=file_format,
            stage_id=stage_id,
        )
        transcoder.run()

    return cls.from_native(cached_h5, fem=fem)

from_mpco classmethod

from_mpco(path: 'str | Path | list[str | Path]', *, fem: 'Optional[FEMData]' = None, merge_partitions: bool = True) -> 'Results'

Open a STKO .mpco HDF5 results file.

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,
) -> "Results":
    """Open a STKO ``.mpco`` HDF5 results file.

    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.
    """
    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_bound_fem(reader, fem)
    return cls(reader, fem=bound_fem, path=anchor)

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_bound_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()

viewer

viewer(*, blocking: bool = True, title: Optional[str] = None, restore_session: 'bool | str' = 'prompt', save_session: bool = True, cuts: 'Optional[Any]' = None, model_h5: 'Optional[Any]' = None)

Open the post-solve results viewer.

Parameters

blocking True (default) — open the viewer in-process and block the calling thread until the window 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 How to handle a previously-saved session JSON next to the results file. True restores silently, False ignores, "prompt" (default) opens a yes/no dialog if a matching session exists. No effect for in-memory Results. save_session If True (default), the active set of diagrams + scrubber position is saved to <results>.viewer-session.json when the window closes. False disables auto-save. cuts Optional sequence of :class:apeGmsh.cuts.SectionCutDef instances to render as Layers at boot. Each cut becomes a new SectionCutDiagram in the active geometry's "Section cuts" composition (created if absent). Requires model_h5 so OpenSees tags can be mapped back to FEM eids — pass it alongside cuts. Subprocess launches (blocking=False) currently ignore this argument; build cuts programmatically via director.add_section_cut on the spawned viewer once it exposes IPC. model_h5 Path to a model.h5 that carries OpenSees enrichment: /opensees/cuts (for section-cut tag mapping) and / or /opensees/transforms + /opensees/element_meta (for per-element beam orientation, ADR 0018). When omitted and self was opened from disk via :meth:from_native, the viewer auto-resolves the results file itself as the orientation source if it carries those zones; cuts auto-load still requires an explicit model_h5=. Forwarded into the subprocess on blocking=False via --model-h5 so the auto-resolve also fires there for non-default layouts.

Returns

ResultsViewer The viewer instance after the window closes (blocking). subprocess.Popen The spawned process handle (non-blocking). 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.

Source code in src/apeGmsh/results/Results.py
def viewer(
    self,
    *,
    blocking: bool = True,
    title: Optional[str] = None,
    restore_session: "bool | str" = "prompt",
    save_session: bool = True,
    cuts: "Optional[Any]" = None,
    model_h5: "Optional[Any]" = None,
):
    """Open the post-solve results viewer.

    Parameters
    ----------
    blocking
        ``True`` (default) — open the viewer in-process and block
        the calling thread until the window 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
        How to handle a previously-saved session JSON next to the
        results file. ``True`` restores silently, ``False`` ignores,
        ``"prompt"`` (default) opens a yes/no dialog if a matching
        session exists. No effect for in-memory Results.
    save_session
        If ``True`` (default), the active set of diagrams + scrubber
        position is saved to ``<results>.viewer-session.json`` when
        the window closes. ``False`` disables auto-save.
    cuts
        Optional sequence of :class:`apeGmsh.cuts.SectionCutDef`
        instances to render as Layers at boot. Each cut becomes a
        new ``SectionCutDiagram`` in the active geometry's
        ``"Section cuts"`` composition (created if absent). Requires
        ``model_h5`` so OpenSees tags can be mapped back to FEM
        eids — pass it alongside ``cuts``. Subprocess launches
        (``blocking=False``) currently ignore this argument; build
        cuts programmatically via ``director.add_section_cut`` on
        the spawned viewer once it exposes IPC.
    model_h5
        Path to a ``model.h5`` that carries OpenSees enrichment:
        ``/opensees/cuts`` (for section-cut tag mapping) and / or
        ``/opensees/transforms`` + ``/opensees/element_meta`` (for
        per-element beam orientation, ADR 0018). When omitted and
        ``self`` was opened from disk via :meth:`from_native`, the
        viewer auto-resolves the results file itself as the
        orientation source if it carries those zones; cuts
        auto-load still requires an explicit ``model_h5=``.
        Forwarded into the subprocess on ``blocking=False`` via
        ``--model-h5`` so the auto-resolve also fires there for
        non-default layouts.

    Returns
    -------
    ResultsViewer
        The viewer instance after the window closes (blocking).
    subprocess.Popen
        The spawned process handle (non-blocking).
    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.
    """
    import os
    if os.environ.get("APEGMSH_SKIP_VIEWER"):
        print("[skip viewer] APEGMSH_SKIP_VIEWER set")
        return None
    if not blocking:
        handle = self._spawn_viewer_subprocess(
            title=title, model_h5=model_h5,
        )
        # 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
    from ..viewers.results_viewer import ResultsViewer
    return ResultsViewer(
        self,
        title=title,
        restore_session=restore_session,
        save_session=save_session,
        cuts=cuts,
        model_h5=model_h5,
    ).show()

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._raw = fem_data
    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()))

    # Build Gmsh tag -> raw array index
    self._tag_to_raw_idx: dict[int, int] = {
        int(t): i for i, t in enumerate(self._node_tags)
    }

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])

Result of a mesh partitioning operation.

Attributes

n_parts : int Number of partitions created. elements_per_partition : dict[int, int] {partition_id: element_count}.

Source code in src/apeGmsh/mesh/_mesh_partitioning.py
def __init__(
    self,
    n_parts: int,
    elements_per_partition: dict[int, int],
) -> None:
    self.n_parts = n_parts
    self.elements_per_partition = elements_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, **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.

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,
    **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

    # 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._info_tab: "MeshInfoTab | None" = None
    self._mesh_tn_overlay: "MeshTangentNormalOverlay | None" = None

    # UI tabs (resolved after construction)
    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._overlay_scales: dict[str, float] = {
        'force_arrow':           1.0,
        'moment_arrow':          1.0,
        'mass_sphere':           1.0,
        'constraint_marker':     1.0,
        'constraint_line':       1.0,
        'tangent_normal_arrow':  1.0,
    }
    self._moment_template: Any = None
    self._pick_mode: list[str] = ["brep"]   # "brep", "element", "node"
    self._picked_elems: list[int] = []
    self._picked_nodes: list[int] = []
    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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
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
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.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

    # ── Window (creates QApplication) ───────────────────────────
    # ``window_key`` opts into layout persistence under
    # ``QSettings("apeGmsh", "MeshViewer")`` (plan 08 follow-up).
    default_title = f"MeshViewer — {self._parent.name}"
    win = ViewerWindow(
        title=title or default_title, window_key="MeshViewer",
    )
    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,
    )

    filter_tab = MeshFilterTab(
        self._dims,
        on_filter_changed=self._on_mesh_filter,
        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 — and those tabs are only created when
        # the matching composite exists. For a mesh-only model
        # (no loads/mass/constraints) the broker is pure waste, so
        # skip it unless something will actually read it.
        _needs_fem = any(
            getattr(self._parent, _c, None) is not None
            for _c in ("loads", "masses", "constraints")
        )
        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

    # ── 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
    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,
    )

    # ── Browser tab (groups + element types visibility) ─────────
    from .ui.mesh_browser_tab import MeshBrowserTab
    if scene.group_to_breps or scene.brep_dominant_type:
        self._browser_tab = MeshBrowserTab(
            scene, on_hidden_changed=vis_mgr.set_hidden,
        )
        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
    from .ui._dock_registry import DockSpec
    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,
        on_load_patterns_changed=self._rebuild_loads_overlay,
        on_mass_visibility_changed=self._rebuild_mass_overlay,
        on_constraint_kinds_changed=self._rebuild_constraints_overlay,
        on_row_focused=_on_outline_row_focused,
    )
    outline_dock = win.add_extension_dock(DockSpec(
        dock_id="dock_mesh_outline",
        title="Outline",
        factory=lambda _p: self._outline_tree.widget,
        default_area="left",
    ))
    # The outline dock is added here, *after* ViewerWindow.__init__
    # already ran _restore_layout(). A QDockWidget created after
    # QMainWindow.restoreState() is not placed by the restored
    # layout (documented Qt behaviour) and Qt leaves it floating —
    # which a stale persisted MeshViewer layout then re-saves every
    # launch. restoreDockWidget() is Qt's remedy for a late-added
    # dock; if there is no valid saved placement (or it was saved
    # floating from this bug) force it back into the left area.
    # Mirrors the explicit post-add re-dock model.viewer performs
    # via splitDockWidget().
    from qtpy import QtCore as _QtC_dock
    win.window.restoreDockWidget(outline_dock)
    if outline_dock.isFloating():
        outline_dock.setFloating(False)
        win.window.addDockWidget(
            _QtC_dock.Qt.LeftDockWidgetArea, outline_dock,
        )

    # ── 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)

    # Dim checkboxes: drive both actor visibility (the user-visible
    # effect) and the pick-engine pickable-dims mask (so picks ignore
    # hidden dims). Earlier this only set the pickable mask, making
    # the checkboxes appear to do nothing visually.
    def _on_dim_filter(active_dims: set[int]) -> None:
        self._on_mesh_filter(active_dims)
        pick_engine.set_pickable_dims(active_dims)
    filter_tab._on_filter = _on_dim_filter

    # Selection changed -> recolor
    sel.on_changed.append(self._handle_sel_changed)
    # 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
    vis_mgr.on_changed.append(lambda: plotter.render())
    # 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
    )

    # ── 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)", "H", self._act_hide)
    win.add_toolbar_button("Isolate selected (I)", "I", self._act_isolate)
    win.add_toolbar_button("Reveal all (R)", "R", self._act_reveal_all)
    win.add_toolbar_separator()
    win.add_toolbar_button("Save image…", "Img", self._act_screenshot)

    # ── 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)
    plotter.add_key_event("u", lambda: sel.undo())

    win.add_shortcut("Escape", lambda: sel.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"))

    # ── 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()
    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)

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.

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,
) -> 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

    # 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 → commit_active_group) 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
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 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
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.pick_engine import PickEngine
    from .core.visibility import VisibilityManager
    from .core.selection import SelectionState
    from .scene.brep_scene import build_brep_scene
    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 group order with pre-existing user-facing PGs (skip labels)
    from apeGmsh.core.Labels import is_label_pg
    for pg_dim, pg_tag in sorted(gmsh.model.getPhysicalGroups(), key=lambda x: x[1]):
        try:
            pg_name = gmsh.model.getPhysicalName(pg_dim, pg_tag)
            if pg_name and not is_label_pg(pg_name) and pg_name not in sel._group_order:
                sel._group_order.append(pg_name)
        except Exception:
            pass

    if self._physical_group is not None:
        sel.set_active_group(self._physical_group)

    def _on_close():
        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).
    win = ViewerWindow(
        title=title or default_title,
        on_close=_on_close,
        window_key="ModelViewer",
    )

    # ── 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._picks)
        # 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({dt[0] for dt 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 directly
            sel._staged_groups[n] = current_picks
            # Switch to the new group (loads picks from staged)
            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:
            sel.delete_group(name)
            from .core.selection import _delete_group_by_name
            _delete_group_by_name(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()``.
    def _on_filter(active_dims: set[int]):
        pick_engine.set_pickable_dims(active_dims)
        # Dim non-pickable dimension actors
        for dim in registry.dims:
            actor = registry.dim_actors.get(dim)
            if actor is None:
                continue
            if dim in active_dims:
                actor.GetProperty().SetOpacity(
                    self._surface_opacity if dim >= 2 else 1.0
                )
            else:
                actor.GetProperty().SetOpacity(0.1)
        plotter.render()

    filter_tab = FilterTab(self._dims, on_filter_changed=_on_filter)

    # ── 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

        # 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:
                        bb = gmsh.model.getBoundingBox(dim, tag)
                        cx = (bb[0] + bb[3]) * 0.5 - registry.origin_shift[0]
                        cy = (bb[1] + bb[4]) * 0.5 - registry.origin_shift[1]
                        cz = (bb[2] + bb[5]) * 0.5 - registry.origin_shift[2]
                        points.append([cx, cy, cz])
                    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
                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(label)
                            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(label)

            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:
                            bb = gmsh.model.getBoundingBox(pg_dim, int(tag))
                            cx = (bb[0] + bb[3]) * 0.5 - registry.origin_shift[0]
                            cy = (bb[1] + bb[4]) * 0.5 - registry.origin_shift[1]
                            cz = (bb[2] + bb[5]) * 0.5 - registry.origin_shift[2]
                            label_points.append([cx, cy, cz])
                        except Exception:
                            continue
                    label_texts.append(display_name)

            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).
    def _tree_hide(dts):
        vis_mgr.hide_dts(dts)
        plotter.render()

    def _tree_isolate(dts):
        vis_mgr.isolate_dts(dts)
        plotter.render()

    def _tree_reveal_all():
        vis_mgr.reveal_all()
        plotter.render()

    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:
            bb = gmsh.model.getBoundingBox(-1, -1)
            return float(np.linalg.norm(
                [bb[3] - bb[0], bb[4] - bb[1], bb[5] - bb[2]]
            )) 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:
            return tuple(gmsh.model.getBoundingBox(-1, -1))
        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

    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 = make_opacity_cb(registry, plotter)
    _pref_edges = make_edges_cb(registry, plotter)

    def _pref_pick_color(hex_str: str):
        h = hex_str.lstrip("#")
        try:
            rgb = np.array(
                [int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16)],
                dtype=np.uint8,
            )
        except ValueError:
            return
        color_mgr.set_pick_color(rgb)
        color_mgr.recolor_all(
            picks=set(sel._picks),
            hidden=vis_mgr.hidden,
            hover=pick_engine.hover_entity,
        )
        plotter.render()

    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,
        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)
    # 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)
    _add_panel("dock_model_session", "Session", _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 ────────────────────────────────────────────
    color_mgr = ColorManager(registry)
    vis_mgr = VisibilityManager(registry, color_mgr, sel, plotter, verbose=_verbose)
    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,
    )
    outline_dock = win.add_extension_dock(DockSpec(
        dock_id="dock_model_outline",
        title="Outline",
        factory=lambda _p: outline.widget,
        default_area="left",
    ))
    sel_dock = win.add_extension_dock(DockSpec(
        dock_id="dock_model_selection",
        title="Selection",
        factory=lambda _p: sel_tree.widget,
        default_area="left",
    ))
    # Stack Selection under the Outline in the left column.
    from qtpy import QtCore as _QtC_split
    win.window.splitDockWidget(
        outline_dock, sel_dock, _QtC_split.Qt.Vertical,
    )

    # ── 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()

    _info_menu = win.window.menuBar().addMenu("Info")
    _act_model_info = _info_menu.addAction("Model info…")
    _act_model_info.triggered.connect(_open_model_info)

    # ── 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
    )
    _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

    def _rec_view(r, with_pattern):
        t = (getattr(r, "load_type", None)
             or getattr(r, "mass_type", None)
             or getattr(r, "kind", None)
             or getattr(r, "type", None)
             or type(r).__name__)
        tgt = (getattr(r, "pg", None) or getattr(r, "label", None)
               or getattr(r, "target", None) or "")
        ttuple = None
        if getattr(r, "pg", None):
            ttuple = ("group", r.pg)
        elif getattr(r, "label", None):
            ttuple = ("label", r.label)
        params = {}
        for a in dir(r):
            if a.startswith("_"):
                continue
            try:
                v = getattr(r, a)
            except Exception:
                continue
            if callable(v):
                continue
            if isinstance(v, (int, float, bool, str, list, tuple)):
                params[a] = v
        d = {"key": id(r), "type": str(t), "target": str(tgt),
             "target_tuple": ttuple,
             "name": getattr(r, "name", None), "params": params}
        if with_pattern:
            d["pattern"] = getattr(r, "pattern", "default")
        return d

    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.pattern(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 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)
        plotter.render()

    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()
            plotter.render()

        def _parts_hide(dts):
            sel.select_batch(dts, replace=True)
            vis_mgr.hide()
            plotter.render()

        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)
    def _on_pick(dt: DimTag, ctrl: bool):
        if measure_panel.is_active():
            measure_overlay.add_entity(dt)
            _push_measure_status()
            return
        if ctrl:
            sel.unpick(dt)
        else:
            sel.toggle(dt)

    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)
    # Repaint idle colors when the theme palette changes
    win.on_theme_changed(lambda _p: _on_sel_changed())
    win.on_theme_changed(lambda _p: tn_overlay.refresh_theme())
    sel.on_changed.append(lambda: sel_tree.update(sel.picks))
    sel.on_changed.append(lambda: outline.update_active())
    if parts_tree is not None:
        sel.on_changed.append(
            lambda: parts_tree.highlight_part_for_entity(sel.picks[-1])
            if sel.picks else None
        )
    # Write active group to Gmsh on every pick change
    sel.on_changed.append(lambda: sel.commit_active_group())
    # 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
    sel.on_changed.append(
        lambda: _active_ref.set_selection(tuple(sel.picks)),
    )

    # Visibility changed -> render
    vis_mgr.on_changed.append(lambda: plotter.render())

    # 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) ──
    def _act_hide() -> None:
        vis_mgr.hide()
        plotter.render()

    def _act_isolate() -> None:
        vis_mgr.isolate()
        plotter.render()

    def _act_reveal_all() -> None:
        vis_mgr.reveal_all()
        plotter.render()

    # ── Toolbar buttons for visibility ──────────────────────────
    win.add_toolbar_separator()
    win.add_toolbar_button("Hide selected (H)", "H", _act_hide)
    win.add_toolbar_button("Isolate selected (I)", "I", _act_isolate)
    win.add_toolbar_button("Reveal all (R)", "R", _act_reveal_all)

    # ── 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)
    plotter.add_key_event("u", lambda: sel.undo())

    # Dim filters: 0=points, 1=curves, 2=surfaces, 3=volumes
    for key, dim_set in [
        ("0", {0}), ("1", {1}), ("2", {2}), ("3", {3}),
    ]:
        plotter.add_key_event(
            key,
            lambda ds=dim_set: _on_filter(ds),
        )
    # 4 = all dims
    plotter.add_key_event(
        "4", lambda: _on_filter(set(self._dims)),
    )

    # Window-level (work regardless of focus / mouse position)
    win.add_shortcut("Escape", lambda: sel.clear())
    win.add_shortcut("Q", lambda: win.window.close())

    # ── Pre-load group if specified ─────────────────────────────
    if self._physical_group is not None and sel.picks:
        _on_sel_changed()

    # ── 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()

ResultsViewer

ResultsViewer(results: 'Results', *, title: Optional[str] = None, restore_session: 'bool | str' = 'prompt', save_session: bool = True, cuts: 'Optional[Sequence[SectionCutDef]]' = None, model_h5: 'Optional[str | Path]' = None)

Post-solve interactive viewer.

Parameters

results A :class:Results instance — must have a bound FEMData (either from the embedded /model/ snapshot or via results.bind(fem)). title Window title. Defaults to "Results — <path>".

Source code in src/apeGmsh/viewers/results_viewer.py
def __init__(
    self,
    results: "Results",
    *,
    title: Optional[str] = None,
    restore_session: "bool | str" = "prompt",
    save_session: bool = True,
    cuts: "Optional[Sequence[SectionCutDef]]" = None,
    model_h5: "Optional[str | Path]" = None,
) -> None:
    if results.fem is None:
        raise RuntimeError(
            "ResultsViewer requires a Results with a bound FEMData. "
            "Either open with Results.from_native(path) (which auto-"
            "binds the embedded snapshot) or call results.bind(fem)."
        )
    self._results = results
    self._title = title
    self._restore_session = restore_session
    self._save_session = save_session
    # Section cuts to wire in at boot. The director constructs in
    # ``show()`` — these are queued until then and applied right
    # after the registry is bound, so the cut Layers attach against
    # a live plotter + scene like any other diagram added at boot.
    self._pending_cuts: tuple = tuple(cuts) if cuts else ()
    self._pending_model_h5: Optional[Path] = (
        Path(model_h5) if model_h5 is not None else None
    )
    # Effective ``model_h5`` for scene-side orientation: explicit
    # kwarg wins; otherwise fall back to ``results._path`` when the
    # results were opened from disk AND the file carries the
    # OpenSees orientation zone (``/opensees/transforms`` +
    # ``/opensees/element_meta``). Producer-agnostic — both the
    # bridge writer and ``ModelData`` produce a byte-equivalent
    # zone (ADR 0018 INV-16) so a single seam covers both. Distinct
    # from ``_pending_model_h5`` (which still drives the director's
    # cuts wiring + auto-load — P2 does not touch that opt-in
    # path).
    self._effective_model_h5: Optional[Path] = self._resolve_effective_model_h5(
        results=results, explicit=self._pending_model_h5,
    )

    # Populated in show()
    self._director: "ResultsDirector | None" = None
    self._scene: "FEMSceneData | None" = None
    self._win: Any = None
    self._plotter: Any = None
    self._settings_tab: "DiagramSettingsTab | None" = None
    self._color_editor: Any = None
    self._color_editor_action: Any = None
    self._registry_unsub: "Optional[Callable[[], None]]" = None
    self._step_unsub: "Optional[Callable[[], None]]" = None
    self._stage_unsub: "Optional[Callable[[], None]]" = None
    # Output dock + log router. Constructed lazily in _show_impl
    # so headless usage (Results.from_native + queries) doesn't
    # pull Qt. Lifecycle:
    # - router.install() before window construction
    # - dock mounted via extension_docks=[spec]
    # - router.uninstall() in _on_close
    self._log_router: Any = None
    self._output_dock: Any = None
    self._output_badge: Any = None
    # Plan 04 step 2 — per-viewer ActiveObjects coordinator.
    # Initialised in _show_impl after the window so it can parent
    # to win.window for Qt's GC. Panels subscribe to its signals
    # rather than wiring direct callbacks to each other.
    self._active: Any = None
    self._time_scrubber: Any = None
    self._substrate_actor: Any = None
    self._wireframe_actor: Any = None
    self._node_cloud_actor: Any = None
    self._node_label_actor: Any = None
    self._element_label_actor: Any = None
    self._plot_pane: Any = None
    self._details_panel: Any = None
    self._geometry_panel: Any = None
    self._session_panel: Any = None
    # diagram instance -> side panel; lifecycle tied to registry.
    self._diagram_side_panels: dict = {}
    # (node_id, component) -> TimeHistoryPanel; user-closable from
    # the plot-pane tab × button.
    self._history_panels: dict = {}

export_animation

export_animation(path: 'str | Any', *, fps: int = 30, step_stride: int = 1) -> Any

Export the time history as an animated MP4 or GIF.

Format auto-detected from the path suffix (.mp4 / .gif). See :func:apeGmsh.viewers.animation.export_animation for the full parameter documentation. Requires the viewer to have been :meth:show-n so the plotter and director are wired.

Source code in src/apeGmsh/viewers/results_viewer.py
def export_animation(
    self,
    path: "str | Any",
    *,
    fps: int = 30,
    step_stride: int = 1,
) -> Any:
    """Export the time history as an animated MP4 or GIF.

    Format auto-detected from the path suffix (``.mp4`` / ``.gif``).
    See :func:`apeGmsh.viewers.animation.export_animation` for the
    full parameter documentation. Requires the viewer to have been
    :meth:`show`-n so the plotter and director are wired.
    """
    if self._plotter is None or self._director is None:
        raise RuntimeError(
            "export_animation: call viewer.show() first so the "
            "plotter and director are constructed."
        )
    from .animation import export_animation
    return export_animation(
        self._plotter, self._director, path,
        fps=fps, step_stride=step_stride,
    )

show

show(*, maximized: bool = True)

Open the viewer window and run the Qt event loop until close.

Returns self so callers can introspect the viewer state after the window closes.

Source code in src/apeGmsh/viewers/results_viewer.py
def show(self, *, maximized: bool = True):
    """Open the viewer window and run the Qt event loop until close.

    Returns ``self`` so callers can introspect the viewer state
    after the window closes.
    """
    # Pin a strong ref so the window survives even when the kernel
    # has a Qt event loop already running and ``app.exec_()``
    # returns immediately (jupyter ``%gui qt`` and friends).
    _LIVE_VIEWERS.add(self)

    # Initialise the action logger early so anything that fires
    # during construction (NoDataError on attach, FEM bind issues,
    # ...) lands in the session log file. session.start is the
    # logger's own header; this line records *which* file we just
    # opened so the log is self-contained.
    from ._log import log_action, log_error
    results_path = getattr(self._results, "_path", None)  # noqa: SLF001
    log_action(
        "session", "open",
        file=str(results_path) if results_path else "<in-memory>",
    )

    try:
        return self._show_impl(maximized=maximized)
    except BaseException as exc:
        # Anything that escapes ``_show_impl`` — ResultsWindow init
        # failures, VTK render-window pixel-format errors, restore
        # path crashes, Qt resource exhaustion, KeyboardInterrupt —
        # writes to the session log file with full traceback before
        # propagating. The log is on disk by now (session.start
        # flushed); even if the calling terminal closes the user
        # can pull the file from ~/.apegmsh/viewer-logs/ to see
        # what happened. Without this trap the trace went to
        # stderr only and was easy to lose.
        log_error("init", "ResultsViewer.show", exc)
        raise

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

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

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.initialize()
    gmsh.model.add(self.name)
    if self._verbose:
        print(f"Gmsh version: {gmsh.__version__}")
    self._create_composites()
    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:
                self._do_save(save_to)
            except Exception as exc:  # noqa: BLE001
                import warnings
                warnings.warn(
                    f"autosave to {save_to} failed: {exc!r}",
                    stacklevel=2,
                )
        gmsh.finalize()
        self._active = False