Skip to content

Results

Post-processing container.

Construction — every Results has a model

Every Results carries a model, so the post-processing container always has a read-side broker to resolve names, PGs, and connectivity against. An in-process run recorded with spec.emit_default(...) opens with run.results(), which picks the reader for the route the build took and passes the model for you. Each reader can also be called directly:

from apeGmsh import Results
from apeGmsh.opensees import OpenSeesModel

# The default route: run.results() after `with spec.emit_default(...) as run:`
results = run.results()

# Ladruno fork .ladruno: model_h5= binds the archive's PGs and labels
results = Results.from_ladruno("run.ladruno", model_h5="model.h5")

# STKO .mpco: model_h5= points at the sibling model archive
results = Results.from_mpco("run.mpco", model_h5="model.h5")  # model_h5= REQUIRED

# Classic recorder files: fem= and model=
model = OpenSeesModel.from_h5("model.h5")
results = Results.from_recorders(spec, "out/", fem=fem, model=model)  # model= REQUIRED

# Native apeGmsh HDF5, e.g. the modes file EigenResult.to_native() writes
p = ops.eigen(3).to_native()          # the file embeds the bridge's model
results = Results.from_native(p, model=OpenSeesModel.from_h5(p))  # model= REQUIRED

Omitting model= (from_recorders, from_native) or model_h5= (from_mpco) raises TypeError. from_ladruno builds its broker from the file's own MODEL group when model_h5= is left out, but then the read has no physical groups or labels.

results.model is never None on a constructed Results (ADR 0020 INV-1). Reach the neutral FEMData zone through the broker chain:

osm = results.model            # OpenSeesModel broker (never None)
fem = results.model.fem        # neutral FEMData zone

results.fem is the locally-bound snapshot and may differ from results.model.fem after a .bind().

Lineage — results.lineage warns, never raises

results.lineage returns a Lineage(fem_hash, model_hash, results_hash, warnings) describing the git-style fem → model → results hash chain. Stored-vs-recomputed mismatches surface as [lineage] ... strings in lineage.warnings; the property itself never raises. Call lineage.assert_clean() to escalate any warnings to LineageError.

BindError is gone

Construction no longer rejects a mismatched FEM with BindError (deleted in the three-broker refactor). results.bind(fem) performs no hash validation — pairing a FEM with the right run is the user's responsibility, reported through lineage.warnings.

Fluent selection — .nodes.select() / .elements.select()

results.nodes.select(...) and results.elements.select(...) are the results entries of the unified, daisy-chainable selection idiom. .select() returns a MeshSelection (point family); the terminal is .values(component=...), which forwards to the retained results.<level>.get(...) reader and returns the same slab (NodeSlab / ElementSlab) with id/value parity.

slab = (results.nodes.select(pg="Base")
    .in_box(lo, hi)                                # half-open [lo, hi)
    .on_plane((0, 0, 0), (0, 0, 1), tol=1e-6)
    .values(component="displacement_x"))           # -> NodeSlab

A bare results selection needs a component — .result() raises RuntimeError; use .values(component=...). Element spatial verbs operate on element centroids.

S5 — formerly-silent results paths now raise

results with selection= on an import-origin (from_msh/MPCO/native) FEMData now raises RuntimeError instead of resolving to an empty set; results element-centroid computation raises KeyError on an unknown connectivity node, which also makes the legacy results.elements.in_box/nearest_to/on_plane helpers fail loud. See the changelog.

See Selection for the full idiom; results sub-composite .select() (gauss/fibers/layers/line_stations/ springs) is a tracked, not-yet-shipped follow-up.

apeGmsh.results.Results.Results

Results(reader: ResultsReader, *, fem: 'Optional[FEMData]' = None, stage_id: Optional[str] = None, path: Optional[Path] = None, model: 'OpenSeesModel', model_path: Optional[Path] = None)

Top-level results object. Returned by Results.from_* constructors.

Stage scoping

Instances may be unscoped (top-level — accesses any stage) or scoped to one stage (returned by .stage(name), .modes[i]). Scoped instances expose stage metadata as properties (.kind, .time, .n_steps); mode-scoped instances additionally expose .eigenvalue, .frequency_hz, .period_s, .mode_index.

Source code in src/apeGmsh/results/Results.py
def __init__(
    self,
    reader: ResultsReader,
    *,
    fem: "Optional[FEMData]" = None,
    stage_id: Optional[str] = None,
    path: Optional[Path] = None,
    model: "OpenSeesModel",
    model_path: Optional[Path] = None,
) -> None:
    self._reader = reader
    self._fem = fem
    # ADR 0113 D9 — ``from_native`` sets this after construction
    # when no ``fem=`` was supplied and the file's embedded
    # ``/model`` is below its floor: the refusal text. ``/stages``
    # read; :attr:`fem` raises it until ``bind(fem)`` supplies a
    # snapshot. Not a constructor keyword: it stays off the public
    # ``Results`` signature.
    self._fem_unavailable: Optional[str] = None
    self._stage_id = stage_id
    self._path = path
    # ADR 0020 INV-1 (Phase 8 prune) — ``_model`` is required and
    # never None.  The three public constructors validate the
    # contract and raise :class:`TypeError` on missing supply;
    # internal callers (``_derive``) propagate the existing handle.
    self._model = model
    # Sibling-archive path for readers that carry no embedded
    # ``/opensees/`` zone (MPCO).  ``None`` when ``self._path``
    # already is the model archive (native Composed file).  The
    # subprocess viewer reads this to forward ``--model-h5`` to
    # the child process — without it, ``__main__.py`` exits(2)
    # on ``.mpco`` paths.
    self._model_path = model_path
    self._stages_cache: Optional[list[StageInfo]] = None
    self._units_override: Optional[str] = None
    self._source_units_override: Optional[str] = None
    self._base_fem: "Optional[FEMData]" = fem
    from ._units import resolve_results_units

    resolve_results_units(self)

    # Composites
    self.nodes = NodeResultsComposite(self)
    self.elements = ElementResultsComposite(self)
    # MPM particle outputs of a .ladruno (ADR 0134 D4).
    self.particles = ParticleResultsComposite(self)
    self.inspect = ResultsInspect(self)
    self._plot: Optional["ResultsPlot"] = None

fem property

fem: 'Optional[FEMData]'

The bound FEMData snapshot, or None if not bound.

Raises :class:SchemaVersionError on a native results file whose embedded /model is below its floor and no fem= was supplied (ADR 0113 D9): the zone is never read silently, and the message says to pass fem= or call :meth:bind.

model property

model: 'OpenSeesModel'

The bound :class:OpenSeesModel broker.

Phase 8 (ADR 0020 INV-1) — always non-None on a constructed :class:Results. The chain-forward handle from which the OpenSeesModel and its embedded FEMData can be reached.

path property

path: Optional[Path]

The results file these Results read, or None when none.

The path the constructor opened: a .ladruno (the first partition of a merged <stem>.part-<N>.ladruno set), an .mpco, a native .h5, or the recorders' cache. Stage and mode scopes carry it. Read-only. The Windows stills draw this file with apeGmshViewer, which opens a .ladruno only (ADR 0128 slice 6, VA6b).

units property

units: 'Optional[str]'

The active consistent unit system ID (e.g. "kN_m_s"), or None when no unit system was declared.

source_units property

source_units: 'Optional[str]'

The native (as-recorded) unit system ID of the underlying file or model, or None when undeclared and no source= was given.

lineage property

lineage: 'Lineage'

Phase-6 lineage chain — git-style fem → model → results.

ADR 0021 defines a three-link hash chain fem_hash → model_hash → results_hash where each layer's hash includes its parent's hash (one-directional, tamper-evident). Mismatches between stored and recomputed hashes surface as [lineage] ... warnings in :attr:Lineage.warnings; they never raise from this property (INV-2).

Phase-8 derivation order:

  1. Inherit fem_hash + model_hash + accumulated warnings from :attr:model.lineage (the broker recomputes against the same file).
  2. Read the stored /meta/lineage/results_hash via the reader's results_lineage_attrs helper and recompute from /stages/... via recompute_results_hash; append a drift warning on mismatch.

Readers that don't implement the Phase-6 result-layer protocol methods are tolerated via getattr cushions: their lineage stays at the model layer, no warning emitted.

stages property

stages: list[StageInfo]

All stages in the file (scoped instances also list them).

modes property

modes: list['Results']

Stages with kind='mode' as a list of mode-scoped Results.

Order is the order the modes were written (typically by ascending mode_index). For a stable lookup by index, sort: sorted(results.modes, key=lambda m: m.mode_index).

eigen_modes property

eigen_modes: list[EigenMode]

Mode-kind stages as lightweight :class:EigenMode snapshots.

Each :class:EigenMode carries only the four scalar fields (mode_index, eigenvalue, frequency_hz, period_s) — no file handle, no mode-shape arrays. Use this when you need the eigenvalue spectrum but not the per-node shapes (e.g. an LTB Mcr probe, a pickle-able report, or a return value from a function whose Results context is about to be closed).

For the per-node mode shape arrays, use the mode-scoped :class:Results from :attr:modes instead and query via mode.nodes.get(component="displacement_x", ...).

Order matches :attr:modes. For a stable lookup by index, sort: sorted(results.eigen_modes, key=lambda m: m.mode_index).

plot property

plot: 'ResultsPlot'

results.plot — static matplotlib renderer.

Mirrors the interactive viewer's diagram catalog as headless, publication-ready matplotlib figures::

results.plot.contour("displacement_z", step=-1)
results.plot.deformed(step=-1, scale=50, component="stress_xx")
results.plot.history(node=412, component="displacement_x")

Requires the [plot] extra (matplotlib).

from_native classmethod

from_native(path: str | Path, *, fem: 'Optional[FEMData]' = None, model: 'Optional[OpenSeesModel]' = None, model_path: 'Optional[str | Path]' = None) -> 'Results'

Open an apeGmsh native HDF5 results file.

Phase 8 (ADR 0020 INV-1) — model= is required. Missing supply raises :class:TypeError. Pass model=OpenSeesModel.from_h5(path_to_model_h5) (often the same path as path when the file is a Composed-file per ADR 0020).

If fem is omitted, the embedded /model/ snapshot is used as the bound FEMData.

ADR 0113 D9 — a results file outlives its embedded model zones. When the embedded /model is below its floor the file still opens and /stages read: with fem= supplied the zone is never read; without it :attr:fem raises the reader's refusal (with a fem= hint) until :meth:bind supplies a snapshot. The embedded /opensees is never read here, since model= is required; OpenSeesModel.from_h5 on such a file refuses, so the model comes from a sidecar archive.

model_path records the on-disk archive the model was read from, for when it is not path itself — e.g. results whose embedded /model zone is not independently readable. The non-blocking subprocess viewer forwards it as --model-h5 so the child re-reads the model from there instead of from path.

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

    Phase 8 (ADR 0020 INV-1) — ``model=`` is required. Missing
    supply raises :class:`TypeError`. Pass
    ``model=OpenSeesModel.from_h5(path_to_model_h5)`` (often the
    same path as ``path`` when the file is a Composed-file
    per ADR 0020).

    If ``fem`` is omitted, the embedded ``/model/`` snapshot is
    used as the bound FEMData.

    ADR 0113 D9 — a results file outlives its embedded model zones.
    When the embedded ``/model`` is below its floor the file still
    opens and ``/stages`` read: with ``fem=`` supplied the zone is
    never read; without it :attr:`fem` raises the reader's refusal
    (with a ``fem=`` hint) until :meth:`bind` supplies a snapshot.
    The embedded ``/opensees`` is never read here, since ``model=``
    is required; ``OpenSeesModel.from_h5`` on such a file refuses,
    so the model comes from a sidecar archive.

    ``model_path`` records the on-disk archive the ``model`` was read
    from, for when it is *not* ``path`` itself — e.g. results whose
    embedded ``/model`` zone is not independently readable. The
    non-blocking subprocess viewer forwards it as ``--model-h5`` so the
    child re-reads the model from there instead of from ``path``.
    """
    if model is None:
        raise TypeError(_MODEL_REQUIRED_MESSAGE)
    from ..opensees._internal.schema_version import NEUTRAL
    from .readers._native import NativeReader
    reader = NativeReader(path)
    fem_unavailable: Optional[str] = None
    if fem is None and NEUTRAL in reader.unavailable_zones:
        # D9: no snapshot to bind and the file's own is below its
        # floor. Open anyway; ``Results.fem`` refuses with the text.
        fem_unavailable = reader.unavailable_zones[NEUTRAL]
        bound_fem: "Optional[FEMData]" = None
    else:
        bound_fem = _resolve_fem(reader, fem)
    bound_model = resolve_bound_model(reader, model)
    # ``resolve_bound_model`` always returns ``model`` here since
    # we just asserted it is non-None, but route through the helper
    # to keep the resolution semantics in one place.
    assert bound_model is not None
    results = cls(
        reader, fem=bound_fem, path=Path(path), model=bound_model,
        model_path=Path(model_path) if model_path is not None else None,
    )
    results._fem_unavailable = fem_unavailable
    return results._with_autoloaded_definitions()

from_recorders classmethod

from_recorders(spec, output_dir: str | Path, *, fem: 'FEMData', cache_root: str | Path | None = None, stage_name: str | None = None, stage_kind: str | None = None, file_format: str = 'out', stage_id: str | None = None, model: 'Optional[OpenSeesModel]' = None, stages: 'Optional[Iterable[Any]]' = None) -> 'Results'

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

model= is required (else :class:TypeError).

Parses the .out / .xml files emitted at output_dir (matching what spec.emit_recorders(...) or the bridge's Tcl/Py emit produced), caches the result at cache_root and opens it (ADR 0131 D6). Nodal records only, over ops.stage blocks of model with their kinds (any order or subset), are cached as <key>.ladruno stamped against <key>.model.h5 (opensees_backend="unknown", the stage names), read by name with from_ladruno(model_h5=) and bound to model. Any other run (an element record, displacement_increment, a stage the program does not declare or of another kind) is cached as native HDF5 embedding model's /opensees/ zone (keeps the names). A layers record refuses by name; modal records are not emitted.

Caching: unchanged input files, model, stage names and kinds reuse the cached file (writers/_cache.py). Recorders sample every step or every dt=, never at arbitrary caller instants.

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, else "analysis", and stage_kind to "transient". None (default) keeps the legacy flat-naming used by Tcl/Py exports. stages=live.stages reads every stage of a :meth:ResolvedRecorderSpec.emit_recorders run into one file, one stage each with its name and kind; it excludes stage_id / stage_name / stage_kind.

Rows are labelled with the spec's FEM ids, so the files must come from an emit that translated them to OpenSees tags (spec.emit_recorders(..., model=) or spec.to_tcl_commands(model=)).

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 | None = None,
    stage_kind: str | None = None,
    file_format: str = "out",
    stage_id: str | None = None,
    model: "Optional[OpenSeesModel]" = None,
    stages: "Optional[Iterable[Any]]" = None,
) -> "Results":
    """Open the result of an OpenSees run driven by Tcl/Py recorders.

    ``model=`` is required (else :class:`TypeError`).

    Parses the ``.out`` / ``.xml`` files emitted at ``output_dir``
    (matching what ``spec.emit_recorders(...)`` or the bridge's Tcl/Py
    emit produced), caches the result at ``cache_root`` and opens it
    (ADR 0131 D6). Nodal records only, over ``ops.stage`` blocks of ``model``
    with their kinds (any order or subset), are cached as ``<key>.ladruno``
    stamped against ``<key>.model.h5`` (``opensees_backend="unknown"``, the
    stage names), read by name with ``from_ladruno(model_h5=)`` and bound to
    ``model``. Any other run (an element record, ``displacement_increment``,
    a stage the program does not declare or of another kind) is cached as
    native HDF5 embedding ``model``'s ``/opensees/`` zone (keeps the names).
    A layers record refuses by name; modal records are not emitted.

    Caching: unchanged input files, model, stage names and kinds reuse
    the cached file (``writers/_cache.py``). Recorders sample every step
    or every ``dt=``, never at arbitrary caller instants.

    ``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``, else ``"analysis"``, and ``stage_kind`` to
    ``"transient"``. ``None`` (default) keeps the
    legacy flat-naming used by Tcl/Py exports. ``stages=live.stages``
    reads every stage of a :meth:`ResolvedRecorderSpec.emit_recorders`
    run into one file, one stage each with its name and kind; it
    excludes ``stage_id`` / ``stage_name`` / ``stage_kind``.

    Rows are labelled with the spec's FEM ids, so the files must come
    from an emit that translated them to OpenSees tags
    (``spec.emit_recorders(..., model=)`` or
    ``spec.to_tcl_commands(model=)``).
    """
    if model is None:
        raise TypeError(_MODEL_REQUIRED_MESSAGE)
    from .readers._ladruno_writer import open_transcode, transcode_target
    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)."
        )

    # stage_id names the stage when stage_name is left at its default.
    if stage_id is not None and stage_name in (None, "analysis"):
        stage_name = stage_id
    stages = None if stages is None else tuple(stages)   # read a generator once
    plan = RecorderTranscoder.stage_plan(stages, stage_name, stage_kind, 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,
    )
    if stages is not None:
        source_files = [f for *_, prefix in plan for f in _cache.list_source_files(
            spec, out_dir, file_format=file_format, stage_id=prefix)]
    key = _cache.compute_cache_key(
        source_files,
        parser_version=PARSER_VERSION, fem_snapshot_id=fem.snapshot_id,
        model_token=_cache.model_cache_token(model), stages=plan,
    )
    cached_h5, _ = _cache.cache_paths(cache_dir, key)
    model_h5_src: Path = cached_h5.with_suffix(".model.h5")   # embedded, or stamped by
    target = transcode_target(spec, cached_h5, plan, model, model_h5_src)
    if not target.exists() or not model_h5_src.exists():
        model.to_h5(model_h5_src)
    if not target.exists():
        RecorderTranscoder(
            spec, out_dir, target, fem, stage_name=stage_name,
            stage_kind=stage_kind, file_format=file_format, stage_id=stage_id,
            model_h5_src=model_h5_src, stages=stages,
        ).run()
    if target != cached_h5:
        (res := open_transcode(target, plan, fem=fem, model_h5=model_h5_src))._model = model
        return res   # bound to the caller's model, as the native route is
    return cls.from_native(cached_h5, fem=fem, model=model)

from_mpco classmethod

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

Open a STKO .mpco HDF5 results file.

Phase 8 (ADR 0020 INV-1) — model_h5= is required. Missing supply raises :class:TypeError. The broker is loaded via :meth:OpenSeesModel.from_h5 and attached to the resulting :class:Results; INV-3 — the broker is held in memory only (no derived results.h5 is written copying the /opensees/ zone in).

What the archive carries, the results use (#1324, #1325):

  • FEMData. fem= wins when given. Otherwise the neutral FEMData stored in model_h5 (physical groups, labels) is bound whenever its node ids cover the capture's and sit at the capture's coordinates (the model's ndm columns: a 2-D model on an offset plane compares in x, y), so pg= queries work from files alone. An archive written by fem.to_h5 carries no element tag map, so it is bound only when the capture's element ids and nodes are its own (ops tags are read as fem element ids on that route); a model_h5 from another model or another mesh of the same part warns (ModelFemMismatchWarning) and the partial FEMData synthesized from the MPCO MODEL/ group is bound instead.
  • Stage names. ops.stage(name=...) names from /opensees/stages replace the file's MODEL_STAGE[<k>] names in order (results.stage("gravity")); MODEL_STAGE[<k>] stays resolvable as an alias. A partial run (fewer capture stages than program stages) names the prefix and warns (StageCountMismatchWarning); more capture stages than program stages warns and keeps the file's names. Two program stages with one name warn (DuplicateStageNameWarning); stage(name) picks the first, and the ids stage_<k> stay unique.

Single-file mode (default for non-partitioned analyses): pass the path of one .mpco file.

Multi-partition mode (parallel OpenSees runs): pass either

  • a single <stem>.part-<N>.mpco path — siblings are discovered automatically by globbing <stem>.part-*.mpco in the same directory and merged into one virtual reader;
  • an explicit list of partition paths.

Boundary nodes deduplicate by ID (first-occurrence wins); elements concatenate (disjoint by partition); slabs stitch across partitions transparently. Stage and time vectors must match across partitions or construction raises.

Pass merge_partitions=False to opt out of auto-discovery and read only the file at path even if it follows the .part-N naming convention.

Source code in src/apeGmsh/results/Results.py
@classmethod
def from_mpco(
    cls,
    path: "str | Path | list[str | Path]",
    *,
    fem: "Optional[FEMData]" = None,
    merge_partitions: bool = True,
    model_h5: "Optional[str | Path]" = None,
) -> "Results":
    """Open a STKO ``.mpco`` HDF5 results file.

    Phase 8 (ADR 0020 INV-1) — ``model_h5=`` is required. Missing
    supply raises :class:`TypeError`. The broker is loaded via
    :meth:`OpenSeesModel.from_h5` and attached to the resulting
    :class:`Results`; INV-3 — the broker is held *in memory only*
    (no derived ``results.h5`` is written copying the
    ``/opensees/`` zone in).

    What the archive carries, the results use (#1324, #1325):

    - **FEMData.** ``fem=`` wins when given. Otherwise the neutral
      FEMData stored in ``model_h5`` (physical groups, labels) is
      bound whenever its node ids cover the capture's and sit at
      the capture's coordinates (the model's ``ndm`` columns: a 2-D
      model on an offset plane compares in ``x, y``), so ``pg=``
      queries work from files alone. An archive written by
      ``fem.to_h5`` carries no element tag map, so it is bound
      only when the capture's element ids and nodes are its own
      (ops tags are read as fem element ids on that route); a ``model_h5`` from another model or another mesh of
      the same part warns (``ModelFemMismatchWarning``) and the
      partial FEMData synthesized from the MPCO ``MODEL/`` group is
      bound instead.
    - **Stage names.** ``ops.stage(name=...)`` names from
      ``/opensees/stages`` replace the file's ``MODEL_STAGE[<k>]``
      names in order (``results.stage("gravity")``);
      ``MODEL_STAGE[<k>]`` stays resolvable as an alias. A partial
      run (fewer capture stages than program stages) names the
      prefix and warns (``StageCountMismatchWarning``); more capture
      stages than program stages warns and keeps the file's names.
      Two program stages with one name warn
      (``DuplicateStageNameWarning``); ``stage(name)`` picks the
      first, and the ids ``stage_<k>`` stay unique.

    Single-file mode (default for non-partitioned analyses): pass
    the path of one ``.mpco`` file.

    Multi-partition mode (parallel OpenSees runs): pass either

    - a single ``<stem>.part-<N>.mpco`` path — siblings are
      discovered automatically by globbing ``<stem>.part-*.mpco``
      in the same directory and merged into one virtual reader;
    - an explicit list of partition paths.

    Boundary nodes deduplicate by ID (first-occurrence wins);
    elements concatenate (disjoint by partition); slabs stitch
    across partitions transparently. Stage and time vectors must
    match across partitions or construction raises.

    Pass ``merge_partitions=False`` to opt out of auto-discovery
    and read only the file at ``path`` even if it follows the
    ``.part-N`` naming convention.
    """
    if model_h5 is None:
        raise TypeError(_MODEL_H5_REQUIRED_MESSAGE)
    from .readers._mpco import MPCOReader
    from .readers._mpco_multi import (
        MPCOMultiPartitionReader, discover_partition_files,
    )

    if isinstance(path, (list, tuple)):
        paths = [Path(p) for p in path]
        reader = (
            MPCOMultiPartitionReader(paths)
            if len(paths) > 1
            else MPCOReader(paths[0])
        )
        anchor = paths[0]
    else:
        anchor = Path(path)
        if merge_partitions:
            discovered = discover_partition_files(anchor)
        else:
            discovered = [anchor]
        if len(discovered) > 1:
            reader = MPCOMultiPartitionReader(discovered)
        else:
            reader = MPCOReader(discovered[0])
    # A step after the open that raises closes the reader
    # first (the file is free again on Windows), then re-raises.
    try:
        # Per INV-3, this is an in-memory rehydrate from the sibling
        # file; we never copy the zone into a derived h5.
        from ..opensees.opensees_model import OpenSeesModel
        bound_model = OpenSeesModel.from_h5(model_h5)
        # The archive's neutral FEMData carries the physical groups
        # the MPCO MODEL/ group lacks; its /opensees/stages carry the
        # names the MODEL_STAGE[<k>] groups lack.
        bound_fem = _resolve_fem_via_model(
            reader, fem, bound_model, model_path=model_h5,
        )
        _bind_stage_names(reader, bound_model, model_path=model_h5)
        # ADR 0043 slice 1.3 — MPCO buckets key element results by
        # the OpenSees ops tag; the results API speaks fem_eid.
        # Whenever the bound model carries a real element_meta
        # pairing, the reader must relabel ops↔fem through it. This
        # is NOT compose-only: gmsh numbers lower-dimensional elements
        # first, so almost any solid model with surface physical
        # groups has fem_eid != ops_tag even uncomposed (the former
        # compose-provenance gate silently scrambled / dropped element
        # results for exactly that case — fixed 2026-08-04). A
        # deliberately-unrelated stub ``model_h5=`` (common in tests)
        # stays safe through the translator's all-or-nothing
        # `_relabel` contract: ids the model does not fully describe
        # pass through untranslated.
        from .readers._tag_translation import ElementTagTranslator
        _tag_map = ElementTagTranslator.from_model(bound_model)
        if not _tag_map.is_empty:
            reader.attach_tag_map(_tag_map)
        # The file holds no per-node ndf; the model's masks the
        # recorder's 0.0 rotations at nodes without rotational DOFs.
        from .readers._mpco import attach_model_nodes_ndf
        attach_model_nodes_ndf(reader, model_h5, bound_model.ndm)
        return cls(
            reader, fem=bound_fem, path=anchor, model=bound_model,
            model_path=Path(model_h5),
        )._with_autoloaded_definitions()
    except BaseException:
        reader.close()
        raise

from_ladruno classmethod

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

Open a Ladruno .ladruno HDF5 results file.

The Ladruno recorder is the fork's canonical recorder. Unlike .mpco (and unlike :meth:from_mpco, which requires model_h5=), a .ladruno is self-sufficient — it carries its own geometry, regions and beam local axes (schema Principle 0: "this is the native path; no sibling file"). So model_h5= is optional:

  • omitted → the broker is built in-memory from the file's own MODEL group (geometry + inferred ndm/ndf; bridge record zones empty). This is read-time interpretation, not a transcode. A file with no MODEL group raises :class:ValueError naming the file; model_h5= opens it.
  • supplied → the richer broker is loaded via :meth:OpenSeesModel.from_h5 (full bridge records + lineage), and — whenever the model records an element_meta pairing — the fem_eid↔ops-tag translator is attached (ADR 0043; required for composed models AND for any sparsely-renumbered mesh, e.g. a gmsh solid whose 2-D boundary elements consumed the low ids).

FEMData with model_h5= (#2329): as in :meth:from_mpco, fem= wins when given; otherwise the FEMData archived in model_h5 is bound, with its physical groups and labels, so pg= and label= reads work. An archive of another model or another mesh warns ModelFemMismatchWarning and the file's own MODEL group (no physical groups) is bound instead. Without model_h5= the file's MODEL group is bound, as before.

Stage names with model_h5= (ADR 0122 D3, #2101, #2823): the ops.stage(name=...) names and each stage's analysis kind from /opensees/stages replace the file's MODEL_STAGE[<k>] names, which stay resolvable as aliases; a stage is never paired with a program stage by position alone (_bind.py::_bind_ladruno_stage_names):

  • a file stamped with INFO/PROVENANCE@stage_names binds each stage to the program stage its stamp names, in any order; a stage stamped with its own MODEL_STAGE name (modes) keeps it. A stamped name the program does not declare, or a program stage of another kind than the recorded KIND, raises StageStampRefused naming it;
  • an unstamped file: a modes-only stage (KIND=eigen, no step) is no program stage and keeps its name. The others pair one to one when they are as many as the program's stages, where a disagreeing KIND renames nothing and warns StageKindMismatchWarning (#2079 Q7; KIND=eigen or none is no evidence either way); fewer pair with the program's first stages only when their KIND s fit no other run of program stages (a partial run, StageCountMismatchWarning), and otherwise keep their names with UnpairedStageWarning.

Without model_h5= the file's names stand.

The file records no per-node ndf, so the recorder writes 0.0 for a rotation a node does not have (a solid node beside a shell). With model_h5= a one-file read gives NaN there, from the model's /opensees/nodes_ndf; without it a rotation read over continuum elements warns AbsentDofWarning once (#1971).

MPM particles (ADR 0134 D3/D4): at ``INFO/FORMAT_MINOR_VERSION

= 2a stage's particle group reads through :attr:`particles` (results.particles.get(component=...)). An all-particle file opens withoutmodel_h5=: it has no FEM (:attr:`fem` isNone``), its broker wraps the empty stage model, and a node or element read of a particle-only stage refuses by name. A part file with particles is refused.

Keys on INFO/GENERATOR="Ladruno" + a supported FORMAT_VERSION (the reader rejects a .mpco / foreign file or an out-of-window version loudly).

Multi-partition merge: a parallel run writes one <stem>.part-<N>.ladruno per rank. Passing one partition path auto-discovers its siblings (<stem>.part-*.ladruno) and merges them into one virtual reader (node-union + element-concat); passing a list merges exactly those paths. merge_partitions=False opts out of sibling auto-discovery.

Source code in src/apeGmsh/results/Results.py
@classmethod
def from_ladruno(
    cls,
    path: "str | Path | list[str | Path]",
    *,
    fem: "Optional[FEMData]" = None,
    merge_partitions: bool = True,
    model_h5: "Optional[str | Path]" = None,
) -> "Results":
    """Open a Ladruno ``.ladruno`` HDF5 results file.

    The Ladruno recorder is the fork's *canonical* recorder. Unlike
    ``.mpco`` (and unlike :meth:`from_mpco`, which **requires**
    ``model_h5=``), a ``.ladruno`` is **self-sufficient** — it carries
    its own geometry, regions and beam local axes (schema Principle 0:
    "this *is* the native path; no sibling file"). So ``model_h5=`` is
    **optional**:

    * omitted → the broker is built in-memory from the file's own
      ``MODEL`` group (geometry + inferred ``ndm``/``ndf``; bridge
      record zones empty). This is read-time interpretation, not a
      transcode. A file with no ``MODEL`` group raises
      :class:`ValueError` naming the file; ``model_h5=`` opens it.
    * supplied → the richer broker is loaded via
      :meth:`OpenSeesModel.from_h5` (full bridge records + lineage),
      and — whenever the model records an element_meta pairing —
      the fem_eid↔ops-tag translator is attached (ADR 0043; required
      for composed models AND for any sparsely-renumbered mesh, e.g.
      a gmsh solid whose 2-D boundary elements consumed the low ids).

    FEMData with ``model_h5=`` (#2329): as in :meth:`from_mpco`,
    ``fem=`` wins when given; otherwise the FEMData archived in
    ``model_h5`` is bound, with its physical groups and labels, so
    ``pg=`` and ``label=`` reads work. An archive of another model or
    another mesh warns ``ModelFemMismatchWarning`` and the file's own
    ``MODEL`` group (no physical groups) is bound instead. Without
    ``model_h5=`` the file's ``MODEL`` group is bound, as before.

    Stage names with ``model_h5=`` (ADR 0122 D3, #2101, #2823): the
    ``ops.stage(name=...)`` names and each stage's ``analysis`` kind
    from ``/opensees/stages`` replace the file's ``MODEL_STAGE[<k>]``
    names, which stay resolvable as aliases; a stage is never paired
    with a program stage by position alone
    (``_bind.py::_bind_ladruno_stage_names``):

    * a file stamped with ``INFO/PROVENANCE@stage_names`` binds each
      stage to the program stage its stamp names, in any order; a
      stage stamped with its own ``MODEL_STAGE`` name (modes) keeps
      it. A stamped name the program does not declare, or a program
      stage of another kind than the recorded ``KIND``, raises
      ``StageStampRefused`` naming it;
    * an unstamped file: a modes-only stage (``KIND=eigen``, no step)
      is no program stage and keeps its name. The others pair one to
      one when they are as many as the program's stages, where a
      disagreeing ``KIND`` renames nothing and warns
      ``StageKindMismatchWarning`` (#2079 Q7; ``KIND=eigen`` or none
      is no evidence either way); fewer pair with the program's first
      stages only when their ``KIND`` s fit no other run of program
      stages (a partial run, ``StageCountMismatchWarning``), and
      otherwise keep their names with ``UnpairedStageWarning``.

    Without ``model_h5=`` the file's names stand.

    The file records no per-node ndf, so the recorder writes 0.0 for
    a rotation a node does not have (a solid node beside a shell).
    With ``model_h5=`` a one-file read gives NaN there, from the
    model's ``/opensees/nodes_ndf``; without it a rotation read over
    continuum elements warns ``AbsentDofWarning`` once (#1971).

    MPM particles (ADR 0134 D3/D4): at ``INFO/FORMAT_MINOR_VERSION
    >= 2`` a stage's particle group reads through
    :attr:`particles` (``results.particles.get(component=...)``). An
    all-particle file opens without ``model_h5=``: it has no FEM
    (:attr:`fem` is ``None``), its broker wraps the empty stage
    model, and a node or element read of a particle-only stage
    refuses by name. A part file with particles is refused.

    Keys on ``INFO/GENERATOR="Ladruno"`` + a supported
    ``FORMAT_VERSION`` (the reader rejects a ``.mpco`` / foreign file
    or an out-of-window version loudly).

    Multi-partition merge: a parallel run writes one
    ``<stem>.part-<N>.ladruno`` per rank. Passing one partition path
    auto-discovers its siblings (``<stem>.part-*.ladruno``) and merges
    them into one virtual reader (node-union + element-concat);
    passing a list merges exactly those paths. ``merge_partitions=False``
    opts out of sibling auto-discovery.
    """
    from .readers._ladruno import LadrunoReader
    from .readers._ladruno_multi import (
        LadrunoMultiPartitionReader, discover_partition_files,
    )

    if isinstance(path, (list, tuple)):
        files = [Path(p) for p in path]
        reader = (
            LadrunoMultiPartitionReader(files)
            if len(files) > 1
            else LadrunoReader(files[0])
        )
        anchor = files[0]
    else:
        anchor = Path(path)
        files = (
            discover_partition_files(anchor)
            if merge_partitions else [anchor]
        )
        reader = (
            LadrunoMultiPartitionReader(files)
            if len(files) > 1
            else LadrunoReader(files[0])
        )
    # A step after the open that raises closes the reader
    # first (the file is free again on Windows), then re-raises.
    try:
        bound_model: "Optional[OpenSeesModel]"
        if model_h5 is not None:
            from ..opensees.opensees_model import OpenSeesModel
            bound_model = OpenSeesModel.from_h5(model_h5)
            # A FEMData-only archive (fem.to_h5) records no ndm, so the
            # coordinate check takes the file's: the reader's minimal
            # broker reads INFO/SPATIAL_DIM or the coordinate width
            # (the parts of a set agree, or the reader refused them).
            spatial_dim: "Optional[int]" = None
            if fem is None and int(bound_model.ndm) < 1:
                from .readers._ladruno_element_io import SpatialDimUnknown
                try:
                    file_model = reader.opensees_model()
                except SpatialDimUnknown as e:
                    raise type(e)(
                        f"{anchor}: model_h5={str(model_h5)!r} is a "
                        f"FEMData archive that records no ndm, and the "
                        f"file gives no spatial dimension ({e}), so the "
                        f"archive cannot be checked against the file. "
                        f"Pass fem= to bind a FEMData explicitly, or "
                        f"write the archive with ops.h5(...)."
                    ) from e
                if file_model is not None:
                    spatial_dim = int(file_model.ndm)
            # As in from_mpco: the archive's FEMData carries
            # the physical groups and labels the file's MODEL group
            # lacks; a model of another mesh warns and binds the file's.
            bound_fem = _resolve_fem_via_model(
                reader, fem, bound_model, model_path=model_h5,
                spatial_dim=spatial_dim,
            )
            # The program's stage names and kinds: by the file's
            # stamped stage_names, else by a proven kind match, never
            # by position alone (ADR 0122 D3).
            from .readers._ladruno import read_stage_stamp
            _bind_stage_names(
                reader, bound_model, model_path=model_h5,
                stamp=read_stage_stamp(files),
            )
            # Attach the fem_eid↔ops-tag translator whenever the
            # model carries a real element_meta pairing — see the
            # twin comment in :meth:`from_mpco` (the pairing diverges
            # for ANY sparsely renumbered mesh, not just composed
            # models).
            from .readers._tag_translation import ElementTagTranslator
            _tag_map = ElementTagTranslator.from_model(bound_model)
            if not _tag_map.is_empty:
                reader.attach_tag_map(_tag_map)
            # As in :meth:`from_mpco`: NaN, not the recorder's 0.0,
            # for rotations a node does not have.
            from .readers._ladruno import attach_model_nodes_ndf
            attach_model_nodes_ndf(reader, model_h5, bound_model.ndm)
            model_path: "Optional[Path]" = Path(model_h5)
        else:
            # Self-sufficient path — minimal broker from the file.
            bound_fem = _resolve_fem(reader, fem)
            bound_model = resolve_bound_model(reader, None)
            model_path = None
        if bound_model is None:
            # The reader builds its broker from the MODEL
            # group; a file without one needs model_h5=.
            raise ValueError(
                f"{anchor}: this results file carries no MODEL group "
                f"(node geometry), so the OpenSees model cannot be "
                f"built from the file. Pass model_h5= to supply it."
            )
        return cls(
            reader, fem=bound_fem, path=anchor, model=bound_model,
            model_path=model_path,
        )._with_autoloaded_definitions()
    except BaseException:
        reader.close()
        raise

from_fem classmethod

from_fem(fem: 'FEMData', path: 'str | Path | list[str | Path]', *, kind: str = 'auto', merge_partitions: bool = True, cache_root: 'str | Path | None' = None) -> 'Results'

Open a results file against a bare :class:FEMData snapshot.

The one-call route to :class:Results / :meth:viewer for a model that did not go through the apeSees bridge — e.g. a physical-group model where fem = g.mesh.queries.get_fem_data() drove a hand-written OpenSees deck. Without this the only routes were the bridge-bound constructors (which need a bridge-emitted model.h5 / OpenSeesModel) or the self-describing :meth:from_ladruno.

from_fem materialises a neutral-only model.h5 from fem (cached, keyed by fem.snapshot_id) and binds it to the reader for path. Materialising a file — rather than an in-memory model — is deliberate: it sets model_path so the non-blocking / web viewers work (they forward --model-h5), not just data access.

Parameters

fem The bound snapshot (from g.mesh.queries.get_fem_data() or FEMData.from_h5). A composed fem is refused — see below. path The results file (or a partition list). kind "mpco" / "ladruno" / "native", or "auto" (default) to detect from the suffix (.mpco / .ladruno; a native .h5 must pass kind="native"). merge_partitions Forwarded to :meth:from_mpco / :meth:from_ladruno for .part-N auto-discovery. cache_root Where the materialised model.h5 is written — under <cache_root>/from_fem/ (default <cwd>/results/from_fem/ or $APEGMSH_RESULTS_DIR).

Raises

ValueError When fem is composed (g.compose / from_h5 assembly). Element / Gauss results are relabelled through the fem_eid ↔ ops-tag map that only a real bridge run records; a neutral-only model.h5 carries none, so a composed model would silently mislabel every element result. Build the model through apeSees and pass its model.h5 (e.g. apeSees(fem).h5(...) / g.save → from_mpco(path, model_h5=...)).

Notes

A bare fem carries no envelope ndf (MeshInfo has none), so the cached model's ndf is 0. This is harmless for reading results and for the viewer; it only matters for deck re-emit (model.build(...)), which is not this path's purpose.

Source code in src/apeGmsh/results/Results.py
@classmethod
def from_fem(
    cls,
    fem: "FEMData",
    path: "str | Path | list[str | Path]",
    *,
    kind: str = "auto",
    merge_partitions: bool = True,
    cache_root: "str | Path | None" = None,
) -> "Results":
    """Open a results file against a bare :class:`FEMData` snapshot.

    The one-call route to :class:`Results` / :meth:`viewer` for a
    model that did **not** go through the ``apeSees`` bridge — e.g. a
    physical-group model where ``fem = g.mesh.queries.get_fem_data()``
    drove a hand-written OpenSees deck.  Without this the only routes
    were the bridge-bound constructors (which need a bridge-emitted
    ``model.h5`` / ``OpenSeesModel``) or the self-describing
    :meth:`from_ladruno`.

    ``from_fem`` materialises a neutral-only ``model.h5`` from ``fem``
    (cached, keyed by ``fem.snapshot_id``) and binds it to the reader
    for ``path``.  Materialising a file — rather than an in-memory
    model — is deliberate: it sets ``model_path`` so the non-blocking
    / web viewers work (they forward ``--model-h5``), not just data
    access.

    Parameters
    ----------
    fem
        The bound snapshot (from ``g.mesh.queries.get_fem_data()`` or
        ``FEMData.from_h5``).  A **composed** fem is refused — see
        below.
    path
        The results file (or a partition list).
    kind
        ``"mpco"`` / ``"ladruno"`` / ``"native"``, or ``"auto"``
        (default) to detect from the suffix (``.mpco`` / ``.ladruno``;
        a native ``.h5`` must pass ``kind="native"``).
    merge_partitions
        Forwarded to :meth:`from_mpco` / :meth:`from_ladruno` for
        ``.part-N`` auto-discovery.
    cache_root
        Where the materialised ``model.h5`` is written — under
        ``<cache_root>/from_fem/`` (default ``<cwd>/results/from_fem/``
        or ``$APEGMSH_RESULTS_DIR``).

    Raises
    ------
    ValueError
        When ``fem`` is **composed** (``g.compose`` / ``from_h5``
        assembly).  Element / Gauss results are relabelled through the
        ``fem_eid ↔ ops-tag`` map that only a real bridge run records;
        a neutral-only ``model.h5`` carries none, so a composed model
        would silently mislabel every element result.  Build the model
        through ``apeSees`` and pass its ``model.h5`` (e.g.
        ``apeSees(fem).h5(...)`` / ``g.save`` →
        ``from_mpco(path, model_h5=...)``).

    Notes
    -----
    A bare fem carries no envelope ``ndf`` (``MeshInfo`` has none), so
    the cached model's ``ndf`` is ``0``.  This is harmless for reading
    results and for the viewer; it only matters for deck **re-emit**
    (``model.build(...)``), which is not this path's purpose.
    """
    # ADR 0043 slice 1.3 — element results relabel through the
    # bridge-emitted element_meta.  A neutral-only model.h5 carries
    # none, but ``composed_from`` round-trips, so from_mpco /
    # from_ladruno would see a "composed" model, attach an
    # element-less (empty) tag translator, and silently mislabel
    # every element/gauss/fiber result.  Refuse loudly.
    if len(getattr(fem, "composed_from", ()) or ()) > 0:
        raise ValueError(
            "Results.from_fem: the FEMData is composed (g.compose / "
            "from_h5). Element/Gauss results need the bridge's "
            "fem_eid<->ops-tag map, which a neutral-only model.h5 "
            "cannot provide. Build the model through apeSees and pass "
            "its model.h5 — e.g. Results.from_mpco(path, "
            "model_h5='model.h5')."
        )

    resolved_kind = _resolve_results_kind(kind, path)

    # Materialise a neutral-only model.h5, cached by content hash.
    from .writers._cache import resolve_cache_root

    cache_dir = resolve_cache_root(cache_root) / "from_fem"
    cache_dir.mkdir(parents=True, exist_ok=True)
    snap = str(getattr(fem, "snapshot_id", "") or "model")
    units_tag = f".{fem.units}" if getattr(fem, "units", None) else ""
    cached = cache_dir / f"{snap}{units_tag}.model.h5"
    if not cached.exists():
        fem.to_h5(str(cached))

    if resolved_kind == "mpco":
        return cls.from_mpco(
            path, fem=fem, model_h5=cached,
            merge_partitions=merge_partitions,
        )
    if resolved_kind == "ladruno":
        return cls.from_ladruno(
            path, fem=fem, model_h5=cached,
            merge_partitions=merge_partitions,
        )
    # native — pass the rehydrated neutral-only model + its path so
    # the subprocess viewer can forward --model-h5.
    from ..opensees.opensees_model import OpenSeesModel

    return cls.from_native(
        path, fem=fem, model=OpenSeesModel.from_h5(cached),
        model_path=cached,
    )

unit_factor

unit_factor(component: str, *, level: 'str | Any' = 'nodes', target: 'Any' = None, source: 'Any' = None) -> float

Return the multiplicative conversion factor for component at level (1.0 when target=None, or converting to target).

Raises :class:ValueError when target is supplied on an undeclared Results without an explicit source=.

Source code in src/apeGmsh/results/Results.py
def unit_factor(
    self,
    component: str,
    *,
    level: "str | Any" = "nodes",
    target: "Any" = None,
    source: "Any" = None,
) -> float:
    """Return the multiplicative conversion factor for ``component`` at
    ``level`` (``1.0`` when ``target=None``, or converting to ``target``).

    Raises :class:`ValueError` when ``target`` is supplied on an
    undeclared ``Results`` without an explicit ``source=``.
    """
    from ._units import compute_results_unit_factor
    return compute_results_unit_factor(
        self, component, level=level, target=target, source=source,
    )

unit_symbol

unit_symbol(component: str, *, level: 'str | Any' = 'nodes') -> str

Return the display unit symbol for component in :attr:units (e.g. "kN", "MPa"), or "" when :attr:units is None or the component is dimensionless.

Source code in src/apeGmsh/results/Results.py
def unit_symbol(
    self,
    component: str,
    *,
    level: "str | Any" = "nodes",
) -> str:
    """Return the display unit symbol for ``component`` in :attr:`units`
    (e.g. ``"kN"``, ``"MPa"``), or ``""`` when :attr:`units` is ``None``
    or the component is dimensionless."""
    from ._units import compute_results_unit_symbol
    return compute_results_unit_symbol(self, component, level=level)

to_units

to_units(target: 'Any', *, source: 'Any' = None) -> 'Results'

Return a new :class:Results view whose slabs and bound :attr:fem coordinates are scaled to target consistent units.

  • When :attr:units is declared on the model or results file, source is inferred automatically and may be omitted (passing a conflicting source raises :class:ValueError).
  • When :attr:units is None (undeclared), source is required — omitting it raises :class:ValueError asking the caller to specify the source unit system explicitly.
Source code in src/apeGmsh/results/Results.py
def to_units(
    self,
    target: "Any",
    *,
    source: "Any" = None,
) -> "Results":
    """Return a new :class:`Results` view whose slabs and bound
    :attr:`fem` coordinates are scaled to ``target`` consistent units.

    * When :attr:`units` is declared on the model or results file,
      ``source`` is inferred automatically and may be omitted
      (passing a conflicting ``source`` raises :class:`ValueError`).
    * When :attr:`units` is ``None`` (undeclared), ``source`` is
      **required** — omitting it raises :class:`ValueError` asking the
      caller to specify the source unit system explicitly.
    """
    from ._units import build_scaled_results
    return build_scaled_results(self, target, source=source)

energy

energy(*, region: 'Optional[int]' = None, stage: Optional[str] = None) -> 'Any'

Energy-balance time history — Ladruno-recorder feature.

Returns a :class:pandas.DataFrame of the closure components KE / IE / DW / ULW / RES / ERR indexed by simulation time, written by the recorder's -G energy verb.

  • region=None → whole-domain balance (ON_DOMAIN).
  • region=<tag> → the per-region balance (ON_REGIONS) for the OpenSees region tag.

ERR (the normalized energy-balance error %) is the headline solution-quality diagnostic for explicit runs. Raises :class:TypeError on a non-Ladruno results object (MPCO / native carry no energy balance) and ValueError if energy was not recorded / the region is unknown.

results.plot.energy(...) renders this as a matplotlib time-history figure.

Source code in src/apeGmsh/results/Results.py
def energy(
    self,
    *,
    region: "Optional[int]" = None,
    stage: Optional[str] = None,
) -> "Any":
    """Energy-balance time history — **Ladruno-recorder feature**.

    Returns a :class:`pandas.DataFrame` of the closure components
    ``KE`` / ``IE`` / ``DW`` / ``ULW`` / ``RES`` / ``ERR`` indexed by
    simulation time, written by the recorder's ``-G energy`` verb.

    * ``region=None`` → whole-domain balance (``ON_DOMAIN``).
    * ``region=<tag>`` → the per-region balance (``ON_REGIONS``) for
      the OpenSees region tag.

    ``ERR`` (the normalized energy-balance error %) is the headline
    solution-quality diagnostic for explicit runs. Raises
    :class:`TypeError` on a non-Ladruno results object (MPCO / native
    carry no energy balance) and ``ValueError`` if energy was not
    recorded / the region is unknown.

    ``results.plot.energy(...)`` renders this as a matplotlib
    time-history figure.
    """
    read_energy = getattr(self._reader, "read_energy", None)
    if read_energy is None:
        raise TypeError(
            "Results.energy() is a Ladruno-recorder feature. Open a "
            ".ladruno via Results.from_ladruno(...) recorded with the "
            "'-G energy' verb; MPCO / native results carry no energy "
            "balance."
        )
    sid = self._resolve_stage(stage)
    cols, values, time = read_energy(sid, region=region)
    import pandas as pd
    return pd.DataFrame(
        values, columns=cols, index=pd.Index(time, name="time"),
    )

energy_regions

energy_regions(*, stage: Optional[str] = None) -> 'list[int]'

OpenSees region tags with a recorded per-region energy balance.

The bridge auto-allocates an integer region tag when a Ladruno recorder is given energy_pg= (or a value filter + energy); that tag is opaque to the author. This lists the tags actually present in ON_REGIONS/energyBalance so you can pick one to pass to :meth:energy — e.g. r.energy(region=r.energy_regions()[0]).

Returns [] when only the whole-model balance was recorded (read it with energy(), no region=). Ladruno-recorder feature; raises :class:TypeError on MPCO / native results.

Source code in src/apeGmsh/results/Results.py
def energy_regions(self, *, stage: Optional[str] = None) -> "list[int]":
    """OpenSees region tags with a recorded per-region energy balance.

    The bridge auto-allocates an integer region tag when a Ladruno
    recorder is given ``energy_pg=`` (or a value filter + ``energy``);
    that tag is opaque to the author. This lists the tags actually
    present in ``ON_REGIONS/energyBalance`` so you can pick one to pass
    to :meth:`energy` — e.g. ``r.energy(region=r.energy_regions()[0])``.

    Returns ``[]`` when only the whole-model balance was recorded
    (read it with ``energy()``, no ``region=``). Ladruno-recorder
    feature; raises :class:`TypeError` on MPCO / native results.
    """
    available = getattr(self._reader, "available_energy_regions", None)
    if available is None:
        raise TypeError(
            "Results.energy_regions() is a Ladruno-recorder feature. "
            "Open a .ladruno via Results.from_ladruno(...); MPCO / "
            "native results carry no energy balance."
        )
    sid = self._resolve_stage(stage)
    return available(sid)

node_envelope

node_envelope(component: str, *, stage: Optional[str] = None) -> 'Any'

Per-node time-reduced extremes — Ladruno -envelope feature.

When a .ladruno is recorded with the recorder's -envelope flag, each node channel stores componentwise running extremes (MIN/MAX/ABSMAX and the step at which the abs-extreme occurred) instead of a time series — the cheap way to capture peak response over a long run without keeping every step.

Returns a :class:pandas.DataFrame indexed by node id with columns min / max / absmax / arg_step for component (a neutral name like "displacement_x"). Raises :class:TypeError on a non-Ladruno results object, and :class:ValueError if the file was not recorded with -envelope or the component is absent.

results.plot.node_envelope(...) paints a chosen measure on the mesh as a matplotlib figure.

Source code in src/apeGmsh/results/Results.py
def node_envelope(
    self,
    component: str,
    *,
    stage: Optional[str] = None,
) -> "Any":
    """Per-node time-reduced extremes — **Ladruno ``-envelope`` feature**.

    When a ``.ladruno`` is recorded with the recorder's ``-envelope``
    flag, each node channel stores componentwise running extremes
    (``MIN``/``MAX``/``ABSMAX`` and the step at which the abs-extreme
    occurred) *instead of* a time series — the cheap way to capture peak
    response over a long run without keeping every step.

    Returns a :class:`pandas.DataFrame` indexed by node id with columns
    ``min`` / ``max`` / ``absmax`` / ``arg_step`` for ``component`` (a
    neutral name like ``"displacement_x"``). Raises :class:`TypeError`
    on a non-Ladruno results object, and :class:`ValueError` if the file
    was not recorded with ``-envelope`` or the component is absent.

    ``results.plot.node_envelope(...)`` paints a chosen measure on
    the mesh as a matplotlib figure.
    """
    read_node_envelope = getattr(self._reader, "read_node_envelope", None)
    if read_node_envelope is None:
        raise TypeError(
            "Results.node_envelope() is a Ladruno-recorder feature. Open "
            "a single-file .ladruno via Results.from_ladruno(...) recorded "
            "with the '-envelope' flag. (MPCO / native results and "
            "partitioned .ladruno envelope merges are not supported.)"
        )
    sid = self._resolve_stage(stage)
    env = read_node_envelope(sid, component)
    import pandas as pd
    return pd.DataFrame(
        {
            "min": env.min,
            "max": env.max,
            "absmax": env.absmax,
            "arg_step": env.arg_step,
        },
        index=pd.Index(env.node_ids, name="node_id"),
    )

bind

bind(fem: 'FEMData') -> 'Results'

Re-bind to fem.

Useful when you've re-built the same mesh in a fresh session and want labels / Parts that the embedded snapshot doesn't carry. No hash validation is performed — pairing the FEMData with a results file from the same run is the user's responsibility.

Source code in src/apeGmsh/results/Results.py
def bind(self, fem: "FEMData") -> "Results":
    """Re-bind to ``fem``.

    Useful when you've re-built the same mesh in a fresh session
    and want labels / Parts that the embedded snapshot doesn't
    carry. No hash validation is performed — pairing the FEMData
    with a results file from the same run is the user's
    responsibility.
    """
    from ._units import resolve_results_units

    bound = _resolve_fem(self._reader, fem)
    derived = self._derive(fem=bound)
    if (
        self._units_override is not None
        and bound is not None
        and getattr(bound, "units", None) is not None
        and bound.units not in (self.units, self.source_units)
    ):
        raise ValueError(
            f"Conflicting unit declarations on Results.bind: "
            f"Results has units={self.units!r}, but fem declares "
            f"units={bound.units!r}."
        )
    resolve_results_units(derived)
    return derived

stage

stage(name_or_id: str) -> 'Results'

Return a Results scoped to a stage (matched by id, name or alias).

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, name or alias)."""
    info = self._lookup_stage(name_or_id)
    return self._derive(stage_id=info.id)

combinations

combinations(user_h5: 'Optional[str | Path]' = None, *, model_h5: 'Optional[str | Path]' = None, spectra: Any = None) -> 'UserCombinations'

The set's User Combinations, evaluated per quantity on read (ADR 0130 D4).

user_h5 is the set's <stem>.user.h5. Omitted, the first that exists beside this file is used: <model stem>.user.h5, then this file's stem without .part-<N> and .results. model_h5 (default: the archive this was opened with) brings its /opensees/combinations into the table. spectra reads the spectrum and reference terms; by default it is a :class:~apeGmsh.results.user.UserSpectra over that .user.h5's /spectra, judged stale against model_h5 (ADR 0130 A6), so a stale zone's terms are refused unless evaluate(..., allow_stale=True).

A term names a stage by its stamped name, else stage_<i> (A3). The names are bound when the results are opened (model_h5=), never here: a read does not rename the caller's stages. So when the model (model_h5, or the one this was opened with) declares program stage names and none of them names a stage here, every stage and mode term is refused, with a reason that says to open the results with model_h5=; otherwise a term could read a different stage than the same set opened with its model. That holds however the Results was opened (from_fem binds a neutral cache archive that names no stage). A Results with no names from either source keeps stage_<i>, and so does one whose reader declined that same model's names when it was opened.

evaluate(state, component, level=...) combines a recorded result (level="domain" a /spectra domain value such as base_shear), evaluate(state, user_result=...) a user result. A state handle of another Results is refused.

Source code in src/apeGmsh/results/Results.py
def combinations(
    self,
    user_h5: "Optional[str | Path]" = None,
    *,
    model_h5: "Optional[str | Path]" = None,
    spectra: Any = None,
) -> "UserCombinations":
    """The set's User Combinations, evaluated per quantity on read (ADR 0130 D4).

    ``user_h5`` is the set's ``<stem>.user.h5``. Omitted, the first that
    exists beside this file is used: ``<model stem>.user.h5``, then this
    file's stem without ``.part-<N>`` and ``.results``. ``model_h5``
    (default: the archive this was opened with) brings its
    ``/opensees/combinations`` into the table. ``spectra`` reads the
    ``spectrum`` and ``reference`` terms; by default it is a
    :class:`~apeGmsh.results.user.UserSpectra` over that ``.user.h5``'s
    ``/spectra``, judged stale against ``model_h5`` (ADR 0130 A6), so a
    stale zone's terms are refused unless ``evaluate(...,
    allow_stale=True)``.

    A term names a stage by its stamped name, else ``stage_<i>`` (A3).
    The names are bound when the results are opened (``model_h5=``), never
    here: a read does not rename the caller's stages. So when the model
    (``model_h5``, or the one this was opened with) declares program stage
    names and none of them names a stage here, every ``stage`` and
    ``mode`` term is refused, with a reason that says to open the results
    with ``model_h5=``; otherwise a term could read a different stage than
    the same set opened with its model. That holds however the
    ``Results`` was opened (``from_fem`` binds a neutral cache archive
    that names no stage). A ``Results`` with no names from either source
    keeps ``stage_<i>``, and so does one whose reader declined that same
    model's names when it was opened.

    ``evaluate(state, component, level=...)`` combines a recorded result
    (``level="domain"`` a ``/spectra`` domain value such as
    ``base_shear``), ``evaluate(state, user_result=...)`` a user result. A state handle of
    another ``Results`` is refused.
    """
    from .user._evaluate import CombinationRefused
    from .user._spectra_source import UserSpectra
    from .user._states import UserCombinations, user_file_beside

    model = model_h5 if model_h5 is not None else self._model_path
    unbound = None if model is None else self._unbound_stage_names(Path(model))
    if user_h5 is None:
        user_h5 = user_file_beside(
            None if self._path is None else Path(self._path),
            None if model is None else Path(model))
    if spectra is None:
        spectra = UserSpectra(user_h5, model_h5=model)

    def handle(obj: Any) -> Optional[str]:
        if not isinstance(obj, Results):
            return None
        if obj._reader is not self._reader:
            raise CombinationRefused(
                "", "foreign-handle", "this state handle belongs to another "
                "Results; combining states of different runs is refused "
                "(ADR 0130 D4, A7)")
        if obj._stage_id is None:
            raise TypeError(
                "an unscoped Results is not a state; use results.stage(...)")
        return obj._stage_id

    return UserCombinations(
        self,
        user_h5=None if user_h5 is None else Path(user_h5),
        model_h5=None if model is None else Path(model),
        results_file=self._path,
        handle=handle,
        spectra=spectra,
        unbound_stages=unbound,
    )

close

close() -> None

Close the underlying reader (releases the HDF5 file handle).

Source code in src/apeGmsh/results/Results.py
def close(self) -> None:
    """Close the underlying reader (releases the HDF5 file handle)."""
    if hasattr(self._reader, "close"):
        self._reader.close()

demo classmethod

demo(**kwargs) -> 'Results'

Return a ready-to-view demo :class:Results (cantilever pushover).

Zero-setup sample data so Results.demo().show_web() (or .viewer()) renders without supplying an .mpco / model.h5 pair — handy for docs, smoke tests, and trying the viewer. A real apeSees-emitted model with a synthetic, ramped cantilever deflection (no OpenSees solve). See :func:apeGmsh.results.make_demo_results for the keyword options (length / n_elements / n_steps / tip_drift / path).

Source code in src/apeGmsh/results/Results.py
@classmethod
def demo(cls, **kwargs) -> "Results":
    """Return a ready-to-view demo :class:`Results` (cantilever pushover).

    Zero-setup sample data so ``Results.demo().show_web()`` (or
    ``.viewer()``) renders without supplying an ``.mpco`` /
    ``model.h5`` pair — handy for docs, smoke tests, and trying the
    viewer. A real ``apeSees``-emitted model with a synthetic, ramped
    cantilever deflection (no OpenSees solve). See
    :func:`apeGmsh.results.make_demo_results` for the keyword options
    (``length`` / ``n_elements`` / ``n_steps`` / ``tip_drift`` /
    ``path``).
    """
    from .demo import make_demo_results
    return make_demo_results(**kwargs)

assess

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

Compile a v1 :class:~apeGmsh.assess.AssessmentReport.

figures=True calls :meth:render_pack. Default is False.

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

    ``figures=True`` calls :meth:`render_pack`. Default is ``False``.
    """
    from apeGmsh.assess import assess_results
    return assess_results(self, figures=figures, out_dir=out_dir)

session

session()

The presentation session for these results (ADR 0098 §1).

Presentation with no window: a ResultsSession (from apeGmsh.results.session) bound to this broker, booted with the default picture — ONE empty mesh view (grey analysis mesh, no slots, no legends). Configure it (slots, deform, time), then s.render("a.png") for a still; the Qt client (s.show()) arrives at S2 and viewer() flips onto it at S6.

Persisted section cuts boot as view clips (ADR 0098 S6b). The retired section_cut diagram kind took its auto-load contract with it, but not the contract itself: cuts persisted under /opensees/cuts/ come back on the booted view as clips. Only the ones that translate honestly do — a cut that named a strict subset of the model's elements, or that carries a bounding polygon, cuts LESS than a view clip does, so it is skipped with one [session] line rather than silently widening what disappears from the screen. Reading the cuts can never fail this call: a bad zone is a line, not a traceback.

Source code in src/apeGmsh/results/Results.py
def session(self):
    """The presentation session for these results (ADR 0098 §1).

    Presentation with no window: a ``ResultsSession`` (from
    ``apeGmsh.results.session``) bound to this broker, booted with
    the default picture — ONE empty mesh view (grey analysis mesh,
    no slots, no legends). Configure it (slots, deform, time), then
    ``s.render("a.png")`` for a still; the Qt client (``s.show()``)
    arrives at S2 and ``viewer()`` flips onto it at S6.

    **Persisted section cuts boot as view clips** (ADR 0098 S6b).
    The retired ``section_cut`` diagram kind took its auto-load
    contract with it, but not the contract itself: cuts persisted
    under ``/opensees/cuts/`` come back on the booted view as
    clips. Only the ones that translate honestly do — a cut that
    named a strict subset of the model's elements, or that carries
    a bounding polygon, cuts LESS than a view clip does, so it is
    skipped with one ``[session]`` line rather than silently
    widening what disappears from the screen. Reading the cuts can
    never fail this call: a bad zone is a line, not a traceback.
    """
    from .session import ResultsSession
    from .session._cuts import attach_persisted_cuts

    s = ResultsSession(results=self)
    view = s.add_view()
    try:
        notices = attach_persisted_cuts(self, view)
    except Exception as exc:  # noqa: BLE001 - the session always boots
        notices = (
            f"persisted section cuts could not be loaded as view "
            f"clips: {type(exc).__name__}: {exc}",
        )
    for notice in notices:
        print(f"[session] {notice}")
    return s

viewer

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

Open the post-solve results window on a ResultsSession.

Sugar for :meth:session + show() (ADR 0098 §1, flipped at S6a). The one-liner is unchanged; what it opens is not. A :class:~apeGmsh.results.session.ResultsSession is the document — tiled mesh and plot panes, each with the closed §4 slot catalog — and the window is a client that projects it. The retired Geometry / Composition / Diagram window is gone from this door. Everything the window does, a script can do to the same object::

s = results.session()   # the document, no window
s.render("a.png")       # a still, no Qt
results.viewer()        # the human one-liner
Parameters

blocking None (default) — auto: True in scripts and the plain CLI, False inside a Jupyter / IPython ZMQ kernel, where the blocking Qt loop would freeze (often kill) the kernel. A hand-built, in-memory Results (no backing file) in a notebook cannot spawn a subprocess and raises :class:RuntimeError naming the from_* constructors to open it from a file instead. The notebook path announces itself with one line. True — open the window in-process and block the calling thread until it closes. Matches the signature of :meth:g.mesh.viewer and :meth:g.model.viewer. False — spawn a subprocess via python -m apeGmsh.viewers <path> so the notebook / kernel can keep running. Requires that the Results was opened from disk (self._path is set); raises :class:RuntimeError for in-memory Results. title Optional window title; defaults to "Results — <filename>". restore_session What to do with a session snapshot saved beside the results file. True restores silently, False ignores it, "prompt" (default) asks. No effect for in-memory Results, which have no file to sit beside. save_session If True (default), the session — panes, slots, pose, time link, selection — is written to <results>.viewer-session.json when the window closes. False disables auto-save. Auto-save also disarms itself for a window that could not read an existing file there, so the unreadable file survives (INV-SESSION-OPEN, see apeGmsh.results.session._boot).

Returns

ResultsSession The session the window projected, after the window closes (blocking). Still live: query it, render stills off it, snapshot it. subprocess.Popen The spawned process handle (non-blocking). Deliberately not unified with the blocking return — a session in this process is not what the child window is showing. 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.

Raises

RuntimeError Auto mode (blocking=None) inside a notebook kernel on an in-memory Results (_path is None): there is no file for python -m apeGmsh.viewers to open. Open the results with :meth:from_native, :meth:from_mpco, :meth:from_ladruno, :meth:from_recorders or :meth:from_fem. Nothing is converted to a temporary file: the reader protocol does not carry everything a native .h5 needs, so a conversion would lose data (#1664).

Notes

The v13 <results>.viewer-session.json written by the retired window is not restorable (ADR 0098 Consequences). The first flipped open says so in one line and renames it aside to .legacy — never overwriting it, and never overwriting an aside that is already there.

cuts= is retired with the diagram ontology (§1): a cut plane is clip state on a view. Build cuts with :mod:apeGmsh.cuts and add them as clips — results.session() then view.add_clip.

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

    Sugar for :meth:`session` + ``show()`` (ADR 0098 §1, flipped at
    S6a). The one-liner is unchanged; what it opens is not. A
    :class:`~apeGmsh.results.session.ResultsSession` is the
    document — tiled mesh and plot panes, each with the closed §4
    slot catalog — and the window is a client that projects it. The
    retired Geometry / Composition / Diagram window is gone from
    this door. Everything the window does, a script can do to the
    same object::

        s = results.session()   # the document, no window
        s.render("a.png")       # a still, no Qt
        results.viewer()        # the human one-liner

    Parameters
    ----------
    blocking
        ``None`` (default) — auto: ``True`` in scripts and the
        plain CLI, ``False`` inside a Jupyter / IPython ZMQ kernel,
        where the blocking Qt loop would freeze (often kill) the
        kernel. A hand-built, in-memory Results (no backing file)
        in a notebook cannot spawn a subprocess and raises
        :class:`RuntimeError` naming the ``from_*`` constructors to
        open it from a file instead. The notebook path announces
        itself with one line.
        ``True`` — open the window in-process and block the calling
        thread until it closes. Matches the signature of
        :meth:`g.mesh.viewer` and :meth:`g.model.viewer`.
        ``False`` — spawn a subprocess via
        ``python -m apeGmsh.viewers <path>`` so the notebook /
        kernel can keep running. Requires that the Results was
        opened from disk (``self._path`` is set); raises
        :class:`RuntimeError` for in-memory Results.
    title
        Optional window title; defaults to ``"Results — <filename>"``.
    restore_session
        What to do with a session snapshot saved beside the results
        file. ``True`` restores silently, ``False`` ignores it,
        ``"prompt"`` (default) asks. No effect for in-memory
        Results, which have no file to sit beside.
    save_session
        If ``True`` (default), the session — panes, slots, pose,
        time link, selection — is written to
        ``<results>.viewer-session.json`` when the window closes.
        ``False`` disables auto-save. Auto-save also disarms itself
        for a window that could not read an existing file there, so
        the unreadable file survives (INV-SESSION-OPEN, see
        ``apeGmsh.results.session._boot``).

    Returns
    -------
    ResultsSession
        The session the window projected, **after** the window
        closes (blocking). Still live: query it, render stills off
        it, snapshot it.
    subprocess.Popen
        The spawned process handle (non-blocking). Deliberately not
        unified with the blocking return — a session in this
        process is not what the child window is showing.
    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.

    Raises
    ------
    RuntimeError
        Auto mode (``blocking=None``) inside a notebook kernel on an
        in-memory Results (``_path is None``): there is no file for
        ``python -m apeGmsh.viewers`` to open. Open the results with
        :meth:`from_native`, :meth:`from_mpco`, :meth:`from_ladruno`,
        :meth:`from_recorders` or :meth:`from_fem`. Nothing is
        converted to a temporary file: the reader protocol does not
        carry everything a native ``.h5`` needs, so a conversion
        would lose data (#1664).

    Notes
    -----
    The v13 ``<results>.viewer-session.json`` written by the retired
    window is not restorable (ADR 0098 Consequences). The first
    flipped open says so in one line and renames it aside to
    ``.legacy`` — never overwriting it, and never overwriting an
    aside that is already there.

    ``cuts=`` is retired with the diagram ontology (§1): a cut plane
    is clip state on a view. Build cuts with :mod:`apeGmsh.cuts` and
    add them as clips — ``results.session()`` then ``view.add_clip``.
    """
    import os
    if os.environ.get("APEGMSH_SKIP_VIEWER"):
        print("[skip viewer] APEGMSH_SKIP_VIEWER set")
        return None
    if blocking is None:
        if not _in_notebook_kernel():
            blocking = True
        elif self._path is None:
            raise RuntimeError(
                "Results.viewer(): a notebook kernel needs the viewer "
                "in a separate process, and this Results is in-memory "
                "(no backing file) so there is nothing for that "
                "process to open. Open it from a file with "
                "Results.from_native(path), Results.from_mpco(path), "
                "Results.from_recorders(spec, output_dir, fem=fem), "
                "Results.from_fem(fem, path) or another "
                "Results.from_* constructor, then call viewer() again. "
                "(blocking=True opens the Qt window in-process, but "
                "that kills a Jupyter kernel.)"
            )
        else:
            print(
                "[viewer] notebook kernel detected — spawning the "
                "viewer as a separate process so the kernel keeps "
                "running (pass blocking=True to open it in-process)."
            )
            blocking = False
    if not blocking:
        handle = self._spawn_viewer_subprocess(
            title=title,
            restore_session=restore_session,
            save_session=save_session,
        )
        # The subprocess opens its own NativeReader against the
        # path; the parent kernel's reader is no longer needed for
        # rendering. Close it here so the user can re-run a capture
        # script (which deletes / recreates the same .h5) without
        # hitting ``PermissionError: file is being used by another
        # process`` — Windows refuses to unlink a file that any
        # process has open, even read-only.
        #
        # If the user wants to keep querying ``results`` after the
        # spawn, they can re-bind via ``Results.from_native(path)``.
        try:
            self.close()
        except Exception:
            pass
        return handle
    return self._show_session_window(
        title=title,
        restore_session=restore_session,
        save_session=save_session,
    )

render

render(path: 'str | Path', *, view: str = 'contour', component: Optional[str] = None, step: int = -1, deform: 'Optional[Any]' = None, camera: 'Optional[str]' = None, window_size: tuple[int, int] = (1280, 720)) -> 'Optional[Path]'

Write one offscreen still (ADR 0094 S1).

Drawn by :meth:ResultsSession.render (X2-d): view is translated into one session mesh view (slots, pose, instant) and rendered VTK-offscreen — no Qt window, no event loop, no setup(plotter, director). view is a closed set: mesh / contour / deformed / reactions.

The stage drawn is the scope of results.stage(s) (or results.modes[i]), else the only stage; an unscoped multi-stage Results draws its LAST stage. step indexes that stage.

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

Returns the written :class:~pathlib.Path, or None (and prints the [skip viewer] notice) under APEGMSH_SKIP_VIEWER=1 or with no GL.

Source code in src/apeGmsh/results/Results.py
def render(
    self,
    path: "str | Path",
    *,
    view: str = "contour",
    component: Optional[str] = None,
    step: int = -1,
    deform: "Optional[Any]" = None,
    camera: "Optional[str]" = None,
    window_size: tuple[int, int] = (1280, 720),
) -> "Optional[Path]":
    """Write one offscreen still (ADR 0094 S1).

    Drawn by :meth:`ResultsSession.render` (X2-d): ``view`` is
    translated into one session mesh view (slots, pose, instant)
    and rendered VTK-offscreen — no Qt window, no event loop, no
    ``setup(plotter, director)``. ``view`` is a closed set:
    ``mesh`` / ``contour`` / ``deformed`` / ``reactions``.

    The stage drawn is the scope of ``results.stage(s)`` (or
    ``results.modes[i]``), else the only stage; an unscoped
    multi-stage Results draws its LAST stage. ``step`` indexes that
    stage.

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

    Returns the written :class:`~pathlib.Path`, or ``None`` (and
    prints the ``[skip viewer]`` notice) under
    ``APEGMSH_SKIP_VIEWER=1`` or with no GL.
    """
    from apeGmsh.viewers.session._results_stills import (
        render_results_still,
    )
    return render_results_still(
        self, path,
        view=view, component=component, step=step,
        deform=deform, camera=camera, window_size=window_size,
    )

render_pack

render_pack(out_dir: 'str | Path', *, camera: 'Optional[str]' = None, window_size: tuple[int, int] = (1280, 720)) -> tuple[Path, ...]

Write the canned report pack (ADR 0094 S3).

Each still is a :meth:render call, so the pack is drawn by :meth:ResultsSession.render too. Returns the tuple of written paths, or () under APEGMSH_SKIP_VIEWER=1 / no GL (and prints the [skip viewer] notice). Closed view= set only; no setup(). There is no fem.render_pack. The stage is :meth:render's: a stage-scoped Results packs that stage.

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

Source code in src/apeGmsh/results/Results.py
def render_pack(
    self,
    out_dir: "str | Path",
    *,
    camera: "Optional[str]" = None,
    window_size: tuple[int, int] = (1280, 720),
) -> tuple[Path, ...]:
    """Write the canned report pack (ADR 0094 S3).

    Each still is a :meth:`render` call, so the pack is drawn by
    :meth:`ResultsSession.render` too. Returns the tuple of written paths, or ``()`` under
    ``APEGMSH_SKIP_VIEWER=1`` / no GL (and prints the
    ``[skip viewer]`` notice). Closed ``view=`` set only; no
    ``setup()``. There is no ``fem.render_pack``. The stage is
    :meth:`render`'s: a stage-scoped Results packs that stage.

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

export_animation

export_animation(path: 'str | Any', *, fps: int = 30, step_stride: int = 1, stage: 'Optional[str]' = None, deform: 'Optional[Any]' = None, camera: 'Optional[Any]' = None, window_size: 'Optional[tuple[int, int]]' = (1280, 720), setup: 'Optional[Any]' = None)

Render the time history to a video / GIF without a GUI session.

Re-steps one :class:~apeGmsh.results.session.ResultsSession mesh view (the results.session() picture) through an offscreen plotter: the scene is realized once, then each captured step moves the session instant and re-steps the pane in place. No Qt window and no event loop. Frames are encoded to the format chosen by path's suffix: .mp4 (H.264, needs the apegmsh[animation] extra) or .gif (Pillow, no extra). A failed frame leaves no file at path.

Parameters

path Output file. Suffix selects the format (.mp4 / .gif). fps Frames per second of the output. step_stride Capture every N-th step (plus always the last). Useful to keep long histories short. stage Stage id/name to animate. Defaults to this Results' own stage (results.stage(...)), else the only stage; with several stages and none picked it raises. deform Deformed-shape scaling. A number applies that scale to the "displacement" field; a (field, scale) pair selects another field. None (default) renders the undeformed mesh. camera "iso" / "xy" / "xz" / "yz", or an explicit value assigned to plotter.camera_position. None uses the still rule: xy for a planar model, iso otherwise. window_size (width, height) of the rendered frames. None uses (1280, 720). setup Optional callback(plotter, view) invoked once after the first frame's scene is built and the camera applied, before capture. view is the session's :class:~apeGmsh.results.session.MeshView: fill a slot (view.contour = Contour("displacement_x")) and the pane is realized again before the first frame. Before X2-b (#1663) the second argument was the retired ResultsDirector; a callback still written against it fails loudly.

Returns

pathlib.Path The resolved output path, or None when APEGMSH_SKIP_VIEWER is set or no GL context is available.

Source code in src/apeGmsh/results/Results.py
def export_animation(
    self,
    path: "str | Any",
    *,
    fps: int = 30,
    step_stride: int = 1,
    stage: "Optional[str]" = None,
    deform: "Optional[Any]" = None,
    camera: "Optional[Any]" = None,
    window_size: "Optional[tuple[int, int]]" = (1280, 720),
    setup: "Optional[Any]" = None,
):
    """Render the time history to a video / GIF without a GUI session.

    Re-steps one :class:`~apeGmsh.results.session.ResultsSession`
    mesh view (the ``results.session()`` picture) through an
    offscreen plotter: the scene is realized once, then each
    captured step moves the session instant and re-steps the pane
    in place. No Qt window and no event loop. Frames are encoded to
    the format chosen by ``path``'s suffix: ``.mp4`` (H.264, needs
    the ``apegmsh[animation]`` extra) or ``.gif`` (Pillow, no
    extra). A failed frame leaves no file at ``path``.

    Parameters
    ----------
    path
        Output file. Suffix selects the format (``.mp4`` / ``.gif``).
    fps
        Frames per second of the output.
    step_stride
        Capture every N-th step (plus always the last). Useful to
        keep long histories short.
    stage
        Stage id/name to animate. Defaults to this Results' own
        stage (``results.stage(...)``), else the only stage; with
        several stages and none picked it raises.
    deform
        Deformed-shape scaling. A number applies that scale to the
        ``"displacement"`` field; a ``(field, scale)`` pair selects
        another field. ``None`` (default) renders the undeformed
        mesh.
    camera
        ``"iso"`` / ``"xy"`` / ``"xz"`` / ``"yz"``, or an explicit
        value assigned to ``plotter.camera_position``. ``None``
        uses the still rule: ``xy`` for a planar model, ``iso``
        otherwise.
    window_size
        ``(width, height)`` of the rendered frames. ``None`` uses
        ``(1280, 720)``.
    setup
        Optional ``callback(plotter, view)`` invoked once after the
        first frame's scene is built and the camera applied, before
        capture. ``view`` is the session's
        :class:`~apeGmsh.results.session.MeshView`: fill a slot
        (``view.contour = Contour("displacement_x")``) and the
        pane is realized again before the first frame. Before
        X2-b (#1663) the second argument was the retired
        ``ResultsDirector``; a callback still written against it
        fails loudly.

    Returns
    -------
    pathlib.Path
        The resolved output path, or ``None`` when
        ``APEGMSH_SKIP_VIEWER`` is set or no GL context is
        available.
    """
    import os
    if os.environ.get("APEGMSH_SKIP_VIEWER"):
        print("[skip viewer] APEGMSH_SKIP_VIEWER set")
        return None
    from apeGmsh.viewers.session._animation import (
        export_session_animation,
    )

    from .session import Deform

    if stage == "__all__":
        # The director's combined stage (every stage on one
        # concatenated time axis). The session has one instant per
        # (stage, step), so there is no combined animation to draw.
        names = [s.name for s in self._all_stages()]
        raise ValueError(
            "export_animation: stage='__all__' (all stages on one "
            "time axis) is no longer supported. Animate one stage "
            f"at a time with stage=<id or name> (have: {names})."
        )
    # stage= wins, then this Results' own scope (``.stage()``), then
    # the only stage; several stages and no pick refuse and name
    # ``stage=`` (the director animated nothing there either).
    try:
        stage_id = self._resolve_stage(stage)
    except RuntimeError as exc:
        raise RuntimeError(
            f"export_animation: no stage to animate — {exc}"
        ) from exc
    session = self.session()
    view = session.panes[0]
    if deform is not None:
        if isinstance(deform, (tuple, list)):
            d_field, d_scale = deform[0], float(deform[1])
        else:
            d_field, d_scale = "displacement", float(deform)
        view.deform = Deform(field=d_field, scale=d_scale)
    return export_session_animation(
        session, view, path,
        stage_id=stage_id, fps=fps, step_stride=step_stride,
        camera=camera, window_size=window_size, setup=setup,
    )

show_web

show_web(*, stage: 'Optional[str]' = None, show: bool = True, controls: bool = True, render_mode: str = 'client')

Open the view-only web / Jupyter results viewer (ADR 0042 R-C).

Renders the FEM substrate plus any diagrams the director holds through a pyvista.trame backend — the kernel-safe path that replaces the blocking Qt :meth:viewer in a notebook. View-only (picking is deferred to R-D), but with a step slider + per-layer visibility checkboxes when ipywidgets is available.

No results file handy? Results.demo().show_web() renders a zero-setup cantilever-pushover sample.

Parameters

stage Stage id or name to activate; defaults to the first stage. show When True (default), display inline immediately. When False, return the :class:~apeGmsh.viewers.web_viewer.WebViewer unshown so diagrams can be added via viewer.director first. controls When True (default), stack an ipywidgets control panel (step slider + layer toggles) above the view. Degrades to a bare view if ipywidgets is absent. render_mode "client" (default) renders in the browser via WebGL — fast camera interaction. "server" renders on the kernel and streams images (laggy, most VTK-feature-complete; for very large models). "hybrid" is pyvista's trame backend with a local/remote toggle in the toolbar.

Returns

WebViewer The viewer handle (.director / .set_step / .show).

Source code in src/apeGmsh/results/Results.py
def show_web(
    self,
    *,
    stage: "Optional[str]" = None,
    show: bool = True,
    controls: bool = True,
    render_mode: str = "client",
):
    """Open the view-only web / Jupyter results viewer (ADR 0042 R-C).

    Renders the FEM substrate plus any diagrams the director holds
    through a ``pyvista.trame`` backend — the kernel-safe path that
    replaces the blocking Qt :meth:`viewer` in a notebook. View-only
    (picking is deferred to R-D), but with a step slider + per-layer
    visibility checkboxes when ``ipywidgets`` is available.

    No results file handy? ``Results.demo().show_web()`` renders a
    zero-setup cantilever-pushover sample.

    Parameters
    ----------
    stage
        Stage id or name to activate; defaults to the first stage.
    show
        When ``True`` (default), display inline immediately. When
        ``False``, return the :class:`~apeGmsh.viewers.web_viewer.WebViewer`
        unshown so diagrams can be added via ``viewer.director`` first.
    controls
        When ``True`` (default), stack an ``ipywidgets`` control panel
        (step slider + layer toggles) above the view. Degrades to a
        bare view if ``ipywidgets`` is absent.
    render_mode
        ``"client"`` (default) renders in the browser via WebGL — fast
        camera interaction. ``"server"`` renders on the kernel and
        streams images (laggy, most VTK-feature-complete; for very
        large models). ``"hybrid"`` is pyvista's ``trame`` backend with
        a local/remote toggle in the toolbar.

    Returns
    -------
    WebViewer
        The viewer handle (``.director`` / ``.set_step`` / ``.show``).
    """
    from ..viewers.web_viewer import show_web as _show_web
    return _show_web(
        self, stage=stage, show=show, controls=controls,
        render_mode=render_mode,
    )

serve_web

serve_web(*, stage: 'Optional[str]' = None, render_mode: str = 'client', port: 'Optional[int]' = None, open_browser: bool = True, title: str = 'apeGmsh', **start_kwargs)

Serve the results as a standalone trame web app (ADR 0042 R-C).

The non-Jupyter counterpart of :meth:show_web: builds a vuetify3 single-page app (the FEM view plus a step slider and per-layer switches) and serves it at a local URL, opening a browser tab and blocking until stopped (Ctrl-C). In a notebook use :meth:show_web instead.

Parameters

stage Stage id or name to activate; defaults to the first stage. render_mode "client" (default), "server", or "hybrid" — see :meth:show_web. port Port to serve on; None lets trame pick one. open_browser Open a browser tab at the served URL. title App title shown in the toolbar. **start_kwargs Passed through to the trame server.start (e.g. exec_mode).

Returns

WebViewer The viewer handle.

Source code in src/apeGmsh/results/Results.py
def serve_web(
    self,
    *,
    stage: "Optional[str]" = None,
    render_mode: str = "client",
    port: "Optional[int]" = None,
    open_browser: bool = True,
    title: str = "apeGmsh",
    **start_kwargs,
):
    """Serve the results as a standalone trame web app (ADR 0042 R-C).

    The non-Jupyter counterpart of :meth:`show_web`: builds a vuetify3
    single-page app (the FEM view plus a step slider and per-layer
    switches) and serves it at a local URL, opening a browser tab and
    blocking until stopped (Ctrl-C). In a notebook use :meth:`show_web`
    instead.

    Parameters
    ----------
    stage
        Stage id or name to activate; defaults to the first stage.
    render_mode
        ``"client"`` (default), ``"server"``, or ``"hybrid"`` — see
        :meth:`show_web`.
    port
        Port to serve on; ``None`` lets trame pick one.
    open_browser
        Open a browser tab at the served URL.
    title
        App title shown in the toolbar.
    **start_kwargs
        Passed through to the trame ``server.start`` (e.g.
        ``exec_mode``).

    Returns
    -------
    WebViewer
        The viewer handle.
    """
    from ..viewers.web_viewer import serve_web as _serve_web
    return _serve_web(
        self, stage=stage, render_mode=render_mode, port=port,
        open_browser=open_browser, title=title, **start_kwargs,
    )

save_definitions

save_definitions(path: 'Optional[str | Path]' = None) -> Path

Persist this Results' custom scalar definitions to a JSON sidecar (default <results>.defs.json).

Reloaded automatically by :meth:from_native / :meth:from_mpco / :meth:from_ladruno, and carried to the subprocess viewer. Raises for an in-memory Results with no path= given.

Source code in src/apeGmsh/results/Results.py
def save_definitions(self, path: "Optional[str | Path]" = None) -> Path:
    """Persist this Results' custom scalar definitions to a JSON
    sidecar (default ``<results>.defs.json``).

    Reloaded automatically by :meth:`from_native` / :meth:`from_mpco`
    / :meth:`from_ladruno`, and carried to the subprocess viewer.
    Raises for an in-memory Results with no ``path=`` given.
    """
    import json
    if path is None:
        if self._path is None:
            raise RuntimeError(
                "in-memory Results has no default sidecar path; "
                "pass save_definitions(path=...)."
            )
        path = self._default_defs_path(self._path)
    path = Path(path)
    path.write_text(
        json.dumps(self._definitions_payload(), indent=2), encoding="utf-8",
    )
    return path

load_definitions

load_definitions(path: 'Optional[str | Path]' = None) -> int

Load and register custom scalar definitions from a JSON sidecar (default <results>.defs.json). Returns the count applied; a missing file is a no-op returning 0. Idempotent / best-effort — see :meth:_apply_definitions_payload.

Source code in src/apeGmsh/results/Results.py
def load_definitions(self, path: "Optional[str | Path]" = None) -> int:
    """Load and register custom scalar definitions from a JSON sidecar
    (default ``<results>.defs.json``). Returns the count applied; a
    missing file is a no-op returning 0. Idempotent / best-effort —
    see :meth:`_apply_definitions_payload`."""
    import json
    if path is None:
        if self._path is None:
            return 0
        path = self._default_defs_path(self._path)
    path = Path(path)
    if not path.exists():
        return 0
    payload = json.loads(path.read_text(encoding="utf-8"))
    return self._apply_definitions_payload(payload)

Slabs

Tabular dataclasses returned by reader queries.

apeGmsh.results._slabs

Slab dataclasses returned by ResultsReader implementations.

A slab carries one component's values plus enough location metadata that the caller can interpret each row without re-deriving it. They are numpy-native and immutable; the viewer wraps them in xarray when it wants labeled axes.

Shape conventions (single-stage, post-stitching across partitions):

================ ======================== ================================================= Slab values shape Location index fields ================ ======================== ================================================= NodeSlab (T, N) node_ids: (N,) ElementSlab (T, E, npe) element_ids: (E,) LineStationSlab (T, sum_S) element_index, station_natural_coord: (sum_S,) GaussSlab (T, sum_GP) element_index: (sum_GP,), natural_coords: (sum_GP, dim) FiberSlab (T, sum_F) element_index, gp_index, y, z, area, material_tag: (sum_F,), station_natural_coord: (sum_F,) | None LayerSlab (T, sum_L) element_index, gp_index, layer_index, sub_gp_index, thickness: (sum_L,) ParticleSlab (S, nComp) ragged particle_ids: (S,), offsets: (T+1,) ================ ======================== =================================================

GaussCensus is not a slab: it is the subset of ONE GaussSlab time row that met a predicate (see Results.elements.gauss's tension_census / corner_census).

For a single time step (time_slice was a scalar), T is 1 and the leading axis is preserved — the caller can squeeze if desired.

LocalAxes dataclass

LocalAxes(element_ids: ndarray, quaternions: ndarray)

Per-element local coordinate frames (beam / shell orientation).

Read from a .ladruno MODEL/LOCAL_AXES group — the orientation a .mpco does not carry for beam-columns (so apeGmsh can orient line / section-force diagrams straight from .ladruno for wired element classes, instead of the native vecxz path).

quaternions are scalar-first (w, x, y, z), mapping global → element-local at the reference configuration. The local axes are the rows of the rotation matrix (OpenSees quatFromMat stores the transpose convention), so matrices[k] has row 0 = local x, row 1 = local y, row 2 = local z — each expressed in global coordinates. Elements with no recorded frame get the identity quaternion.

matrices property

matrices: ndarray

(n, 3, 3) per-element rotations; rows are the local axes in global coordinates.

x_axis property

x_axis: ndarray

(n, 3) — each element's local x-axis (beam axis) in global coords.

y_axis property

y_axis: ndarray

(n, 3) — each element's local y-axis in global coords.

z_axis property

z_axis: ndarray

(n, 3) — each element's local z-axis in global coords.

NodeSlab dataclass

NodeSlab(component: str, values: ndarray, node_ids: ndarray, time: ndarray)

Node-level result values.

item

item() -> float

The slab's one value, as a float (ADR 0115 D3).

Raises :class:ValueError unless values holds exactly one value: one node at one time step. Narrow the read first, by node (label=, pg=, ids=) and by time (time=-1). It replaces .values[-1, 0], which answers silently from whatever the slab holds.

Source code in src/apeGmsh/results/_slabs.py
def item(self) -> float:
    """The slab's one value, as a ``float`` (ADR 0115 D3).

    Raises :class:`ValueError` unless ``values`` holds exactly one
    value: one node at one time step. Narrow the read first, by node
    (``label=``, ``pg=``, ``ids=``) and by time (``time=-1``). It
    replaces ``.values[-1, 0]``, which answers silently from whatever
    the slab holds.
    """
    values = np.asarray(self.values)
    if values.size != 1:
        raise ValueError(
            f"NodeSlab.item(): {self.component!r} holds {values.size} "
            f"values (shape {values.shape}: time steps x nodes); item() "
            "needs exactly one. Narrow the read to one node "
            "(label=, pg=, ids=) and one step (time=-1)."
        )
    return float(values.reshape(-1)[0])

ElementSlab dataclass

ElementSlab(component: str, values: ndarray, element_ids: ndarray, time: ndarray)

Per-element-node values (e.g. globalForce / localForce).

LineStationSlab dataclass

LineStationSlab(component: str, values: ndarray, element_index: ndarray, station_natural_coord: ndarray, time: ndarray, local_axes_quaternion: Optional[ndarray] = None)

Beam line-diagram values per integration station.

GaussSlab dataclass

GaussSlab(component: str, values: ndarray, element_index: ndarray, natural_coords: ndarray, local_axes_quaternion: Optional[ndarray], time: ndarray)

Continuum Gauss-point values.

natural_coords are gmsh reference coordinates for every family: [-1, +1]^d for lines, quads and hexes, and (u, v[, w]) on the unit simplex for triangles and tets, where node 0 carries 1 - u - v[ - w] and node k the k-th coordinate (the frame the gmsh shape functions in :mod:apeGmsh.fem._shape_functions take). Every reader converts its source's frame to this once, at the source (#2228): an element's barycentric rule is never passed through. To get global coordinates, call slab.global_coords(fem) — interpolates through the bound FEMData's element shape functions for hex8 / quad4, falling back to a centroid + bbox-scaled approximation for element types that don't yet have explicit shape-fn support.

global_coords

global_coords(fem) -> ndarray

Map per-GP natural coords to (sum_GP, 3) world coords.

Uses element shape functions for supported types (hex8, quad4); falls back to centroid + 0.5 * bbox_span * natural for others — visualization-faithful for axis-aligned elements.

Source code in src/apeGmsh/results/_slabs.py
def global_coords(self, fem) -> ndarray:
    """Map per-GP natural coords to ``(sum_GP, 3)`` world coords.

    Uses element shape functions for supported types (hex8, quad4);
    falls back to ``centroid + 0.5 * bbox_span * natural`` for
    others — visualization-faithful for axis-aligned elements.
    """
    from ._gauss_world_coords import compute_global_coords
    return compute_global_coords(self, fem)

GaussCensus dataclass

GaussCensus(component: str, predicate: str, count: int, examined: int, values: ndarray, element_index: ndarray, natural_coords: ndarray, time: float)

The Gauss points of a :class:GaussSlab that met a predicate.

A census answers "how many, and where" at ONE instant — the count plus the location metadata needed to draw or tabulate the matching points. It carries the same element_index / natural_coords pair a :class:GaussSlab does, so :meth:global_coords behaves identically.

count is element_index.size; examined is how many Gauss points the predicate ran over, so count / examined is the fraction without a second read. Both are needed: a census of 12 is a different fact at 40 Gauss points than at 40 000.

global_coords

global_coords(fem) -> ndarray

Map the matching GPs to (count, 3) world coords.

Same reconstruction (and same :class:~apeGmsh.results._gauss_world_coords.WarnGaussCoordsApproximate caveat) as :meth:GaussSlab.global_coords.

Source code in src/apeGmsh/results/_slabs.py
def global_coords(self, fem) -> ndarray:
    """Map the matching GPs to ``(count, 3)`` world coords.

    Same reconstruction (and same
    :class:`~apeGmsh.results._gauss_world_coords.WarnGaussCoordsApproximate`
    caveat) as :meth:`GaussSlab.global_coords`.
    """
    from ._gauss_world_coords import compute_global_coords_from_arrays
    return compute_global_coords_from_arrays(
        self.element_index, self.natural_coords, fem,
    )

FiberSlab dataclass

FiberSlab(component: str, values: ndarray, element_index: ndarray, gp_index: ndarray, y: ndarray, z: ndarray, area: ndarray, material_tag: ndarray, time: ndarray, station_natural_coord: Optional[ndarray] = None)

Fiber-level values within fiber-section GPs.

LayerSlab dataclass

LayerSlab(component: str, values: ndarray, element_index: ndarray, gp_index: ndarray, layer_index: ndarray, sub_gp_index: ndarray, thickness: ndarray, local_axes_quaternion: ndarray, time: ndarray)

Layered shell layer values (one row per (elem, surf_gp, layer, sub_gp)).

ParticleSlab dataclass

ParticleSlab(component: str, values: ndarray, particle_ids: ndarray, offsets: ndarray, time: ndarray, step: ndarray, registry_ids: ndarray, components: tuple[str, ...])

Particle values in the file's own ragged layout (ADR 0134 D4).

Particles move, appear and disappear, so an output's particle count varies. The slab keeps the .ladruno CSR layout (contract 232a §2.5): output k is rows offsets[k]:offsets[k + 1] of values and particle_ids.

================ ============================================= values (S, nComp), concatenated over outputs particle_ids (S,), sorted within each output offsets (T + 1,), offsets[0] = 0, offsets[T] = S time (T,) the Domain time; it may restart in a stage step (T,) the Domain commit tag, strictly increasing registry_ids (M,) the stage registry rows this read covers components nComp labels, as the file spells them ================ =============================================

Outputs are keyed by index or step, never by time.

output

output(k: int) -> 'tuple[ndarray, ndarray]'

Output k's (particle_ids (n,), values (n, nComp)).

Source code in src/apeGmsh/results/_slabs.py
def output(self, k: int) -> "tuple[ndarray, ndarray]":
    """Output ``k``'s ``(particle_ids (n,), values (n, nComp))``."""
    n = self.n_outputs
    if not -n <= k < n:
        raise IndexError(
            f"ParticleSlab.output({k}): {self.component!r} holds {n} "
            "output(s)."
        )
    k = k % n
    a, b = int(self.offsets[k]), int(self.offsets[k + 1])
    return self.particle_ids[a:b], self.values[a:b]

dense

dense() -> ndarray

(T, M, nComp) aligned to :attr:registry_ids, NaN where a particle is absent from an output.

Source code in src/apeGmsh/results/_slabs.py
def dense(self) -> ndarray:
    """``(T, M, nComp)`` aligned to :attr:`registry_ids`, ``NaN`` where a
    particle is absent from an output."""
    values = np.asarray(self.values)
    reg = np.asarray(self.registry_ids, dtype=np.int64)
    ids = np.asarray(self.particle_ids, dtype=np.int64)
    out = np.full(
        (self.n_outputs, reg.size, values.shape[1]), np.nan,
        dtype=np.result_type(values.dtype, np.float32),
    )
    if ids.size == 0:
        return out
    pos = np.searchsorted(reg, ids)
    bad = (pos >= reg.size) | (reg[np.minimum(pos, reg.size - 1)] != ids)
    if bool(bad.any()):
        raise ValueError(
            f"ParticleSlab.dense(): {self.component!r} holds particle "
            f"id(s) {np.unique(ids[bad])[:10].tolist()} that are not "
            "in its registry (contract C2-ID)."
        )
    rows = np.repeat(np.arange(self.n_outputs), np.diff(self.offsets))
    out[rows, pos, :] = values
    return out

item

item() -> float

The slab's one value, as a float (ADR 0115 D3).

Raises :class:ValueError unless values holds exactly one value: one particle, one component, one output. Narrow the read by particle (ids=), component ("FIELD/label") and output (time=-1) first.

Source code in src/apeGmsh/results/_slabs.py
def item(self) -> float:
    """The slab's one value, as a ``float`` (ADR 0115 D3).

    Raises :class:`ValueError` unless ``values`` holds exactly one
    value: one particle, one component, one output. Narrow the read
    by particle (``ids=``), component (``"FIELD/label"``) and output
    (``time=-1``) first.
    """
    values = np.asarray(self.values)
    if values.size != 1:
        raise ValueError(
            f"ParticleSlab.item(): {self.component!r} holds "
            f"{values.size} values ({self.n_outputs} output(s), "
            f"{values.shape[0]} row(s) x {values.shape[1] if values.ndim == 2 else 1} "
            "component(s)); item() needs exactly one. Narrow the read "
            "to one particle (ids=), one component ('FIELD/label') "
            "and one output (time=-1)."
        )
    return float(values.reshape(-1)[0])

SpringSlab dataclass

SpringSlab(component: str, values: ndarray, element_index: ndarray, time: ndarray)

Zero-length spring values (one column per element, one spring index).

component encodes which spring is represented (e.g. "spring_force_0" for the force in the first configured spring direction). Each column in values corresponds to one element; element_index carries the raw OpenSees element tag so the caller can correlate columns with elements without needing a separate ID array.

================ ======================== values (T, E) element_index (E,) ================ ========================

Readers

Reader protocol and supporting types shared by every backend.

apeGmsh.results.readers._protocol

Reader protocol — backend-agnostic contract for the composite layer.

Two implementations:

  • NativeReader reads apeGmsh native HDF5 (Phase 1).
  • MPCOReader reads STKO MPCO HDF5 (Phase 3).

The composite layer above (Results.nodes.get(...) etc.) talks only to this protocol — it never branches on backend type.

ResultLevel

Bases: Enum

The topology level a component lives at.

StageInfo dataclass

StageInfo(id: str, name: str, kind: str, n_steps: int, eigenvalue: Optional[float] = None, frequency_hz: Optional[float] = None, period_s: Optional[float] = None, mode_index: Optional[int] = None, aliases: tuple[str, ...] = ())

Stage metadata returned by ResultsReader.stages().

For kind="mode", the eigenvalue/frequency/period/index fields are populated and n_steps is 1. For other kinds, the mode-only fields are None.

aliases are further names Results.stage(...) resolves to this stage. Empty under every reader's own naming; an MPCO reader that has had the program's stage names attached (#1324) keeps the file's MODEL_STAGE[<k>] group name here so older scripts still find it.

EigenMode dataclass

EigenMode(mode_index: int, eigenvalue: float, frequency_hz: float, period_s: float)

Lightweight snapshot of one eigenmode — no file handle.

Returned by :attr:apeGmsh.results.Results.eigen_modes. Mirrors the mode-only fields of :class:StageInfo but is detachable from the Results context, so it is safe to pickle, pass between processes, or return from a function whose Results was already closed.

For the mode shape (per-node displacement vectors), use the mode-scoped :class:apeGmsh.results.Results from results.modes and query via results.nodes.get(component="displacement_x", ...) — that path holds the file handle and reads the underlying arrays.

omega_rad_s property

omega_rad_s: float

Angular frequency omega = sqrt(eigenvalue) in rad/s.

Returns 0.0 for non-positive (rigid-body or numerical zero) eigenvalues — the mode-stage writers' convention.

ResultsReader

Bases: Protocol

Backend-agnostic reader protocol.

Implementations must support all six topology levels even if a given file has no data at some of them; they should return empty component lists from available_components() in that case rather than raising.

stages

stages() -> list[StageInfo]

All stages in this file, in write order.

Source code in src/apeGmsh/results/readers/_protocol.py
def stages(self) -> list[StageInfo]:
    """All stages in this file, in write order."""
    ...

time_vector

time_vector(stage_id: str) -> ndarray

Time vector for a stage. Shape (n_steps,).

Source code in src/apeGmsh/results/readers/_protocol.py
def time_vector(self, stage_id: str) -> ndarray:
    """Time vector for a stage. Shape ``(n_steps,)``."""
    ...

partitions

partitions(stage_id: str) -> list[str]

Partition IDs for a stage (always at least one).

Source code in src/apeGmsh/results/readers/_protocol.py
def partitions(self, stage_id: str) -> list[str]:
    """Partition IDs for a stage (always at least one)."""
    ...

fem

fem() -> 'Optional[FEMData]'

Embedded / synthesized FEMData snapshot.

  • NativeReader: reconstructs from /model/ when the file carries it. An embedded /model below its floor is listed in NativeReader.unavailable_zones and this raises SchemaVersionError with that text instead of reading it (ADR 0113 D9); /stages read regardless.
  • MPCOReader: synthesizes a partial FEMData from /MODEL/ (no apeGmsh labels, no Part provenance).
Source code in src/apeGmsh/results/readers/_protocol.py
def fem(self) -> "Optional[FEMData]":
    """Embedded / synthesized FEMData snapshot.

    - ``NativeReader``: reconstructs from ``/model/`` when the file
      carries it. An embedded ``/model`` below its floor is listed in
      ``NativeReader.unavailable_zones`` and this raises
      ``SchemaVersionError`` with that text instead of reading it
      (ADR 0113 D9); ``/stages`` read regardless.
    - ``MPCOReader``: synthesizes a partial FEMData from ``/MODEL/``
      (no apeGmsh labels, no Part provenance).
    """
    ...

opensees_model

opensees_model() -> 'Optional[OpenSeesModel]'

Embedded :class:OpenSeesModel from the file's /opensees/ zone.

Phase 4 (ADR 0020) — the Composed-file pattern. Native readers auto-resolve from the file when the zone is present, and raise SchemaVersionError when that zone or the /model it pairs with is below its floor (ADR 0113 D9: the zone is flagged in NativeReader.unavailable_zones and never read silently); third-party file readers (MPCO) return None.

Returns

OpenSeesModel | None The rehydrated broker when the file carries the zone, None otherwise. INV-1 — Phase 4 callers must tolerate None; the value becomes required only in Phase 8.

Source code in src/apeGmsh/results/readers/_protocol.py
def opensees_model(self) -> "Optional[OpenSeesModel]":
    """Embedded :class:`OpenSeesModel` from the file's ``/opensees/`` zone.

    Phase 4 (ADR 0020) — the Composed-file pattern. Native readers
    auto-resolve from the file when the zone is present, and raise
    ``SchemaVersionError`` when that zone or the ``/model`` it pairs
    with is below its floor (ADR 0113 D9: the zone is flagged in
    ``NativeReader.unavailable_zones`` and never read silently);
    third-party file readers (MPCO) return ``None``.

    Returns
    -------
    OpenSeesModel | None
        The rehydrated broker when the file carries the zone,
        ``None`` otherwise. INV-1 — Phase 4 callers must tolerate
        ``None``; the value becomes required only in Phase 8.
    """
    ...

available_components

available_components(stage_id: str, level: ResultLevel) -> list[str]

Canonical component names available at the given level.

Source code in src/apeGmsh/results/readers/_protocol.py
def available_components(
    self, stage_id: str, level: ResultLevel,
) -> list[str]:
    """Canonical component names available at the given level."""
    ...

Live capture

Recorder wiring used during a live OpenSees analysis.

LiveRecorders

apeGmsh.results.live._recorders.LiveRecorders

LiveRecorders(spec: 'ResolvedRecorderSpec', output_dir: 'str | Path', *, file_format: str = 'out', ops=None, model=None)

Context manager that owns stage-scoped OpenSees recorders.

Parameters

spec The :class:ResolvedRecorderSpec whose records to emit. output_dir Directory the recorder .out / .xml files land in. Created on __enter__ if missing. file_format "out" (text) or "xml". Defaults to "out". ops The OpenSees module (or a stand-in for testing). Defaults to the module the bridge drives (:func:~apeGmsh.opensees.emitter.live.get_ops), resolved lazily on __enter__. Pass it when you drive another module by hand. model The built :class:~apeGmsh.opensees.OpenSeesModel. Records name elements by FEM id; OpenSees records by element tag, and under element_tags="sequential" (the bridge default) the two differ. The model's (fem_eid, tag) pairing translates every -ele list, and its ndm and per-node ndf map every node record's -dof list to the DOFs the nodes carry (a 2-D frame's rotation_z is DOF 3). Required whenever the spec holds a node or element record. A :class:~apeGmsh.opensees._recorder_translate.LiveDomainFacts (what emit_default passes for a FEMData archive) maps the -dof lists from the live domain's ndm, per-node ndf and element classes instead, and pairs elements as its archive does.

Raises

RuntimeError On __enter__ if the spec contains any modal records. ValueError On __enter__ if the spec holds a layers record, or a node or element record (fibres included) is emitted without model=, names a FEM id the model has no element for, or records a DOF its nodes do not carry.

Source code in src/apeGmsh/results/live/_recorders.py
def __init__(
    self,
    spec: "ResolvedRecorderSpec",
    output_dir: "str | Path",
    *,
    file_format: str = "out",
    ops=None,
    model=None,
) -> None:
    self._spec = spec
    self._tag_map = None if model is None else element_tag_map(
        model, fem_snapshot_id=spec.fem_snapshot_id,
    )
    self._model = model
    self._output_dir = str(output_dir) if output_dir else ""
    self._file_format = file_format
    self._ops = ops

    self._opened = False
    self._exited = False
    self._current_stage: Optional[StageRecord] = None
    self._current_tags: list[int] = []
    self._stages: list[StageRecord] = []

stages property

stages: tuple[StageRecord, ...]

All completed stages, in the order they ran.

tags property

tags: tuple[int, ...]

Recorder tags issued so far across all stages (read-only).

begin_stage

begin_stage(name: str, kind: str = 'transient') -> None

Issue recorders for a new stage. Files are prefixed <name>__.

kind is forwarded to Results.from_recorders(..., stage_kind=kind) when the stage is read back; valid values are "transient" or "static".

Source code in src/apeGmsh/results/live/_recorders.py
def begin_stage(self, name: str, kind: str = "transient") -> None:
    """Issue recorders for a new stage. Files are prefixed ``<name>__``.

    ``kind`` is forwarded to ``Results.from_recorders(...,
    stage_kind=kind)`` when the stage is read back; valid values
    are ``"transient"`` or ``"static"``.
    """
    self._require_opened()
    if self._current_stage is not None:
        raise RuntimeError(
            f"begin_stage({name!r}) called while stage "
            f"{self._current_stage.name!r} is still open. Call "
            f"end_stage() first."
        )
    if not name:
        raise ValueError("Stage name must be a non-empty string.")
    if "__" in name:
        raise ValueError(
            f"Stage name {name!r} contains '__', which collides "
            f"with the stage/record filename separator."
        )

    # Translate every record, and raise every warning, before any
    # recorder reaches the domain: a refusal (or a warning turned
    # into an error) never leaves a stage half-issued.
    planned: list[tuple] = []
    for record in self._spec.records:
        if record.category in _SUPPORTED_CATEGORIES:
            for logical in emit_logical(
                record,
                output_dir=self._output_dir,
                file_format=self._file_format,
                stage_id=name,
            ):
                planned.append(to_ops_args(to_deck(
                    logical, self._tag_map, self._model, where=_WHERE,
                )))
            continue

        # Modal and layers already raised in __enter__.
        if record.category in _MODAL_CATEGORIES | _NON_RECORDER_CATEGORIES:
            continue

        warnings.warn(
            f"LiveRecorders: skipping record {record.name!r} "
            f"with unrecognised category={record.category!r}.",
            stacklevel=2,
        )

    self._current_stage = StageRecord(name=name, kind=kind)
    self._current_tags = []
    for args in planned:
        tag = self._ops.recorder(*args)
        if isinstance(tag, int):
            self._current_tags.append(tag)

end_stage

end_stage() -> None

Remove the current stage's recorders and flush their files.

Source code in src/apeGmsh/results/live/_recorders.py
def end_stage(self) -> None:
    """Remove the current stage's recorders and flush their files."""
    self._require_opened()
    if self._current_stage is None:
        raise RuntimeError(
            "end_stage() called without a matching begin_stage()."
        )

    for tag in self._current_tags:
        try:
            self._ops.remove("recorder", tag)
        except Exception:  # noqa: BLE001 — best-effort flush
            warnings.warn(
                f"LiveRecorders: failed to remove recorder tag "
                f"{tag}; output file may not be flushed.",
                stacklevel=2,
            )

    completed = StageRecord(
        name=self._current_stage.name,
        kind=self._current_stage.kind,
        tags=tuple(self._current_tags),
    )
    self._stages.append(completed)
    self._current_stage = None
    self._current_tags = []

LiveMPCO

apeGmsh.results.live._mpco.LiveMPCO

LiveMPCO(spec: 'ResolvedRecorderSpec', path: 'str | Path', *, ops=None)

Context manager that owns a single in-process MPCO recorder.

Parameters

spec The :class:ResolvedRecorderSpec whose records to emit. path Output .mpco HDF5 file path. Parent directory created on __enter__ if missing. ops The OpenSees module (or a stand-in for testing). Defaults to the module the bridge drives (:func:~apeGmsh.opensees.emitter.live.get_ops), resolved lazily on __enter__. Pass it when you drive another module by hand.

Raises

RuntimeError On __enter__ if ops.recorder('mpco', ...) fails — most commonly because the openseespy build does not include the MPCO recorder.

Source code in src/apeGmsh/results/live/_mpco.py
def __init__(
    self,
    spec: "ResolvedRecorderSpec",
    path: "str | Path",
    *,
    ops=None,
) -> None:
    self._spec = spec
    self._path = Path(path)
    self._ops = ops

    self._opened = False
    self._exited = False
    self._tag: Optional[int] = None

tag property

tag: Optional[int]

The recorder tag returned by ops.recorder, if any.

LiveDefault

The default route, returned by ResolvedRecorderSpec.emit_default.

apeGmsh.results.live._default.LiveDefault

LiveDefault(spec: 'ResolvedRecorderSpec', path: 'str | Path', *, model_h5: 'str | Path', ops: Any = None, overwrite: bool = False)

Context manager that records one in-process run on the default route.

Parameters

spec The :class:ResolvedRecorderSpec whose records to emit. path Names the run: the route replaces its suffix ("", .mpco or the fork's suffix), so "run" records run.mpco on a stock build. model_h5 The model archive the live domain was built from: the bridge's (ops.h5) or a FEMData archive (fem.to_h5). Required: every route's read pairs with it. A FEMData archive declares no ndm and archives no per-node ndf or element classes, so the classic-recorder route reads them from the live domain (getNDM, getNDF, eleType; #2251). It pairs no FEM element id with an OpenSees tag either, so an element record pairs each FEM element with the live element of its own id only when that element's eleNodes is the FEM connectivity in order and its class is known; any other id refuses, naming it (#2269). A per-Gauss-point material record reads through that pairing (#2290), and so does a fibers record: its elements' section locations and fibre counts are read from the live domain at __enter__, in place of a beamIntegration. ops The OpenSees module, or a stand-in for testing. Defaults to the module the bridge drives. overwrite Replace the fork's file of an earlier run (on a stock MPCO build, the .ladruno the run converts to). Without it a rerun onto an existing file refuses at __enter__. With it, both routes remove that file at __enter__, once the run will record: a stock read that then refuses leaves no earlier .ladruno beside the new .mpco.

Source code in src/apeGmsh/results/live/_default.py
def __init__(
    self,
    spec: "ResolvedRecorderSpec",
    path: "str | Path",
    *,
    model_h5: "str | Path",
    ops: Any = None,
    overwrite: bool = False,
) -> None:
    self._spec = spec
    self._path = Path(path)
    self._model_h5 = Path(model_h5)
    self._ops = ops
    self._overwrite = overwrite
    self._opened = False
    self._exited = False
    self._route: Optional[str] = None
    self._target: Optional[Path] = None
    self._tag: Optional[int] = None
    self._live: Optional[LiveRecorders] = None
    self._model: Optional[OpenSeesModel] = None
    #: The classic-recorder route over a FEMData archive (no
    #: ``/opensees`` zone): read with no bridge zone embedded.
    self._neutral = False
    #: The live facts of that route, with the element pairing proved
    #: at ``__enter__``; the read carries the pairing.
    self._facts: Optional[LiveDomainFacts] = None
    self._build = "unknown"

route property

route: Optional[str]

"fork", "mpco" or "recorders"; None before entry.

path property

path: Optional[Path]

The file (or, on the recorder route, the directory) written.

tag property

tag: Optional[int]

The recorder tag of the fork or MPCO route.

results

results(*, cache_root: 'str | Path | None' = None) -> Results

Open what the run recorded, on the route __enter__ picked.

cache_root is where the classic-recorder route caches its transcoded file (:meth:Results.from_recorders); the other routes read their file in place and ignore it.

The stock MPCO route converts its .mpco to the .ladruno beside it (atomically; the .mpco is kept) and opens that. When the file's stages do not pair with the declared ones, it refuses with :class:~apeGmsh.results.readers._ladruno_from_mpco.StageKindRefused and writes nothing; the .mpco is never read in its place.

Source code in src/apeGmsh/results/live/_default.py
def results(self, *, cache_root: "str | Path | None" = None) -> Results:
    """Open what the run recorded, on the route ``__enter__`` picked.

    ``cache_root`` is where the classic-recorder route caches its
    transcoded file (:meth:`Results.from_recorders`); the other routes
    read their file in place and ignore it.

    The stock MPCO route converts its ``.mpco`` to the ``.ladruno``
    beside it (atomically; the ``.mpco`` is kept) and opens that. When
    the file's stages do not pair with the declared ones, it refuses
    with :class:`~apeGmsh.results.readers._ladruno_from_mpco.StageKindRefused`
    and writes nothing; the ``.mpco`` is never read in its place.
    """
    if not self._exited:
        raise RuntimeError(
            "LiveDefault.results() reads the run after the with block "
            "has closed; call it outside the block."
        )
    target = self._target
    assert target is not None
    if self._route == "fork":
        refused = stamp_fork_file(target, self._model_h5, self._build)
        if refused is not None:
            warnings.warn(DefaultRouteWarning(
                f"emit_default: {target} was left unstamped and is read "
                f"without its provenance: {refused}"), stacklevel=2)
        return open_fork_results(target, self._model_h5)
    if self._route == "mpco":
        return self._convert_and_open(target)
    if self._route == "recorders":
        assert self._live is not None and self._model is not None
        if self._neutral:
            return _read_neutral_recorders(
                self._spec, target, self._model, self._live.stages,
                facts=self._facts, cache_root=cache_root,
            )
        return Results.from_recorders(
            self._spec, target, fem=self._model.fem,
            cache_root=cache_root, model=self._model,
            stages=self._live.stages,
        )
    raise RuntimeError(f"LiveDefault has no route {self._route!r}; "
                       f"expected one of {ROUTES}.")

read_deck_mpco

apeGmsh.results.live._default.read_deck_mpco

read_deck_mpco(path: 'str | Path', *, model_h5: 'str | Path', overwrite: bool = False) -> Results

Read the .mpco of a deck the bridge emitted, on the default route.

path is the .mpco written by running the bridge's own exported deck (ops.py / ops.tcl) out of process, as it was emitted, and model_h5 the archive of that bridge. An in-process run (ops.run() then your own opspy.analyze loop) is not a deck and writes no run record: record it with :meth:ResolvedRecorderSpec.emit_default, whose stock MPCO route converts the same way when model_h5 declares its stages and otherwise refuses by name (ADR 0131 D5).

The .mpco (or any part of a partitioned set) converts to the fork's format beside it, which is then opened; the .mpco is always kept. A staged program converts: each ops.stage records its kind. An unstaged program converts only through convert_mpco's private _implicit_stage path, which only this function passes, when the deck's run record (<recorder file>.run.json, written by a deck emitted with analyze_steps) passes the checks in the converter's module docstring. Otherwise it refuses by name: a refusal about stage kinds (:class:~apeGmsh.results.readers._ladruno_from_mpco.StageKindRefused) raises again as one, quoting it, naming the remedies (declare the stages with ops.stage(...), or emit the deck with analyze_steps), and chained from the converter's refusal (__cause__), which ops.results quotes under its own remedies. No kind is defaulted, the .mpco is never read in its place, and nothing is written. Every other refusal (the archive is another model's, an incomplete partition set, a staging directory in the way) raises as it is. A converted file from an earlier run refuses unless overwrite=True.

Source code in src/apeGmsh/results/live/_default.py
def read_deck_mpco(
    path: "str | Path",
    *,
    model_h5: "str | Path",
    overwrite: bool = False,
) -> Results:
    """Read the ``.mpco`` of a deck the bridge emitted, on the default route.

    ``path`` is the ``.mpco`` written by running the bridge's own exported
    deck (``ops.py`` / ``ops.tcl``) out of process, as it was emitted, and
    ``model_h5`` the archive of that bridge. An in-process run (``ops.run()``
    then your own ``opspy.analyze`` loop) is not a deck and writes no run
    record: record it with :meth:`ResolvedRecorderSpec.emit_default`,
    whose stock MPCO route converts the same way when ``model_h5``
    declares its stages and otherwise refuses by name (ADR 0131 D5).

    The ``.mpco`` (or any part of a partitioned set) converts to the fork's
    format beside it, which is then opened; the ``.mpco`` is always kept.
    A staged program converts: each ``ops.stage`` records its kind. An
    unstaged program converts only through ``convert_mpco``'s private
    ``_implicit_stage`` path, which only this function passes, when the
    deck's run record (``<recorder file>.run.json``, written by a deck
    emitted with ``analyze_steps``) passes the checks in the converter's
    module docstring. Otherwise it refuses by name: a refusal about stage
    kinds
    (:class:`~apeGmsh.results.readers._ladruno_from_mpco.StageKindRefused`)
    raises again as one, quoting it, naming the remedies (declare the
    stages with ``ops.stage(...)``, or emit the deck with
    ``analyze_steps``), and chained from the converter's refusal
    (``__cause__``), which ``ops.results`` quotes under its own
    remedies. No kind is defaulted, the ``.mpco`` is never read in its
    place, and nothing is written. Every other
    refusal (the archive is another model's, an incomplete partition set,
    a staging directory in the way) raises as it is. A converted file from
    an earlier run refuses unless ``overwrite=True``.
    """
    mpco, model = Path(path), Path(model_h5)
    existing = existing_fork_files(fork_target_of(mpco))
    if existing and not overwrite:
        raise FileExistsError(
            f"read_deck_mpco would overwrite {[str(p) for p in existing]} "
            "from an earlier run; pass overwrite=True to replace them."
        )
    try:
        return convert_and_open(mpco, model, overwrite=overwrite)
    except StageKindRefused as e:
        raise StageKindRefused(
            f"read_deck_mpco: {mpco} cannot be read, because its stage kinds "
            f"are not facts and no kind is defaulted: {e} {_REMEDY}"
        ) from e

Inspect

apeGmsh.results._inspect.ResultsInspect

ResultsInspect(results: 'Results')

results.inspect — what's available.

Source code in src/apeGmsh/results/_inspect.py
def __init__(self, results: "Results") -> None:
    self._r = results

summary

summary() -> str

Multi-line human-readable summary.

Source code in src/apeGmsh/results/_inspect.py
def summary(self) -> str:
    """Multi-line human-readable summary."""
    r = self._r
    lines = [f"Results: {r._reader_path()!s}"]

    # Read the stored fields, not ``r.fem``: on a D9-flagged file the
    # property raises, and a summary (``repr``, Jupyter display) must
    # still print and say so.
    fem = r._fem
    if fem is not None:
        lines.append(
            f"  FEM: {len(fem.nodes.ids)} nodes, "
            f"{sum(len(g) for g in fem.elements)} elements "
            f"(snapshot_id={fem.snapshot_id})"
        )
    elif r._fem_unavailable is not None:
        lines.append(
            "  FEM: unavailable (embedded /model below its floor, "
            "ADR 0113 D9; pass fem= or call .bind(fem))"
        )
    else:
        lines.append("  FEM: not bound")

    if r.units is not None:
        lines.append(f"  Units: {r.units}")

    stages = r.stages
    if not stages:
        lines.append("  Stages: (none)")
    else:
        lines.append(f"  Stages ({len(stages)}):")
        for s in stages:
            detail = f"steps={s.n_steps}, kind={s.kind}"
            if s.kind == "mode":
                detail += (
                    f", f={s.frequency_hz:.4g} Hz, "
                    f"T={s.period_s:.4g} s, "
                    f"mode_index={s.mode_index}"
                )
            lines.append(f"    - {s.id} ({s.name}): {detail}")

    return "\n".join(lines)

components

components(*, stage: str | None = None) -> dict[str, list[str]]

Available components per topology level for one stage.

If no stage is given, defaults to the only stage when there is exactly one; otherwise raises.

Source code in src/apeGmsh/results/_inspect.py
def components(
    self, *, stage: str | None = None,
) -> dict[str, list[str]]:
    """Available components per topology level for one stage.

    If no stage is given, defaults to the only stage when there is
    exactly one; otherwise raises.
    """
    sid = self._r._resolve_stage(stage)
    return {
        level.value: self._r._reader.available_components(sid, level)
        for level in ResultLevel
    }

diagnose

diagnose(component: str, *, stage: str | None = None) -> str

Explain where a component lives (or doesn't) in this stage.

When a viewer or downstream consumer asks for a component and gets nothing back, this is the routing-side answer to "why is the slab empty?". Walks every topology, calls each composite's available_components(), and returns a human-readable report that shows where component was found and what's actually available at each level.

Parameters

component Canonical component name (e.g. "axial_force", "displacement_z", "stress_xx"). stage Stage id or name. Defaults to the only stage when there is exactly one.

Returns

str Multi-line report. Print it or include it in an error message.

Source code in src/apeGmsh/results/_inspect.py
def diagnose(
    self,
    component: str,
    *,
    stage: str | None = None,
) -> str:
    """Explain where a component lives (or doesn't) in this stage.

    When a viewer or downstream consumer asks for a component and
    gets nothing back, this is the routing-side answer to "why
    is the slab empty?". Walks every topology, calls each
    composite's ``available_components()``, and returns a
    human-readable report that shows where ``component`` was
    found and what's actually available at each level.

    Parameters
    ----------
    component
        Canonical component name (e.g. ``"axial_force"``,
        ``"displacement_z"``, ``"stress_xx"``).
    stage
        Stage id or name. Defaults to the only stage when there
        is exactly one.

    Returns
    -------
    str
        Multi-line report. Print it or include it in an error
        message.
    """
    try:
        sid = self._r._resolve_stage(stage)
    except Exception as exc:
        return f"diagnose({component!r}): could not resolve stage: {exc}"

    lines = [
        f"diagnose({component!r}) — stage={sid!r}",
    ]
    per_level: list[tuple[str, list[str], bool]] = []
    errors: list[tuple[str, str]] = []
    found: list[str] = []

    for level in ResultLevel:
        try:
            comps = self._r._reader.available_components(sid, level)
        except Exception as exc:
            errors.append((level.value, f"{type(exc).__name__}: {exc}"))
            continue
        is_match = component in comps
        per_level.append((level.value, comps, is_match))
        if is_match:
            found.append(level.value)

    if found:
        lines.append(f"  FOUND in: {', '.join(found)}")
    else:
        lines.append("  NOT FOUND in any topology level.")

    # Per-level preview — same for found and not-found, so the user
    # always sees what's actually present at each level.
    for level_value, comps, is_match in per_level:
        preview = ", ".join(comps[:6])
        if len(comps) > 6:
            preview += f", … (+{len(comps) - 6} more)"
        available = preview if comps else "(empty — no buckets present)"
        marker = "✓" if is_match else " "
        lines.append(
            f"    {marker} {level_value:16s}  available: {available}"
        )

    for level_value, msg in errors:
        lines.append(f"      {level_value:16s}  error: {msg}")

    if not found:
        lines.append("")
        lines.append(
            "  If you expected the component above, try:"
        )
        lines.append(
            "    * Check spelling against ``results.inspect.components()``."
        )
        lines.append(
            "    * Check the recorder declared this component in this stage."
        )
        lines.append(
            "    * For MPCO files: confirm the underlying recorder "
            "wrote a bucket the reader knows about (section.force, "
            "localForce, etc.)."
        )

    return "\n".join(lines)

Vocabulary

Canonical result names and shorthand expansion.

apeGmsh._vocabulary

Canonical component names and shorthand expansion.

apeGmsh speaks one canonical name per result component, chosen to be verbose and human-readable. Backend adapters (MPCO, recorder transcoders, domain capture, OpenSees recorder declarations) translate to these names on the way in. Users can also write shorthands ("displacement", "stress") which expand here, clipped to the active ndm/ndf.

This is the single source of truth for "what components exist."

Location history. This module originally lived at apeGmsh.results._vocabulary (results-side ownership). Phase 9 moved it to the top-level apeGmsh._vocabulary so that both the OpenSees bridge (declaration-side) and the results module (consumer-side) can import without creating a layering inversion. The content is solver-neutral — future second-solver work consumes the same vocabulary. The legacy apeGmsh.results._vocabulary shim has been removed.

ALL_CANONICAL module-attribute

ALL_CANONICAL: frozenset[str] = frozenset(NODAL_KINEMATICS + NODAL_FORCES + PER_ELEMENT_NODAL_FORCES + LINE_DIAGRAMS + LINE_STATION_DEFORMATIONS + SHELL_STRESS_RESULTANTS + SHELL_GENERALIZED_STRAINS + STRESS + STRAIN + PLASTIC_STRAIN + DERIVED_SCALARS + FIBER + SPRING + MATERIAL_STATE)

expand_shorthand

expand_shorthand(name: str, *, ndm: int = 3, ndf: int = 6) -> tuple[str, ...]

Expand a shorthand or pass through a canonical name.

Translational shorthands clip to ndm axes (e.g. ndm=2 → displacement_x/y only). Rotational shorthands require rotational DOFs in the active ndf and return () if there are none. Tensor shorthands ("stress", "strain") clip to 3 components in ndm=2 (xx, yy, xy) and 6 in ndm=3.

Raises ValueError if name is neither a known shorthand nor a canonical name.

Source code in src/apeGmsh/_vocabulary.py
def expand_shorthand(
    name: str, *, ndm: int = 3, ndf: int = 6,
) -> tuple[str, ...]:
    """Expand a shorthand or pass through a canonical name.

    Translational shorthands clip to ``ndm`` axes (e.g. ``ndm=2`` →
    ``displacement_x/y`` only). Rotational shorthands require
    rotational DOFs in the active ``ndf`` and return ``()`` if there
    are none. Tensor shorthands (``"stress"``, ``"strain"``) clip to
    3 components in ``ndm=2`` (xx, yy, xy) and 6 in ``ndm=3``.

    Raises ``ValueError`` if ``name`` is neither a known shorthand
    nor a canonical name.
    """
    if is_canonical(name):
        return (name,)

    if name in _SHORTHAND_TRANSLATIONAL:
        full = _SHORTHAND_TRANSLATIONAL[name]
        return _clip_translational(full, ndm)

    if name in _SHORTHAND_ROTATIONAL:
        full = _SHORTHAND_ROTATIONAL[name]
        return _clip_rotational(full, ndm, ndf)

    if name in _SHORTHAND_TENSOR:
        full = _SHORTHAND_TENSOR[name]
        return _clip_tensor(full, ndm)

    if name in _SHORTHAND_LINE_STATION:
        # Line-station shorthands are not clipped by ``ndm``/``ndf``:
        # the catalog declares per-element which subset is emitted,
        # and ``Results`` returns empty slabs for components a given
        # element doesn't expose. Clipping here would hide tokens
        # users genuinely want (e.g. asking for ``section_force`` on
        # a 3D model and missing ``torsion``).
        return _SHORTHAND_LINE_STATION[name]

    if name in _SHORTHAND_SHELL:
        # Not clipped either: the eight resultants are one fixed
        # response layout, and which subset a given shell class emits
        # is the catalog's answer, not ``ndm``'s.
        return _SHORTHAND_SHELL[name]

    if name == "reaction":
        forces = _clip_translational(_SHORTHAND_REACTION[:3], ndm)
        moments = _clip_rotational(_SHORTHAND_REACTION[3:], ndm, ndf)
        return forces + moments

    raise ValueError(
        f"Unknown component '{name}'. Must be a canonical name "
        f"(e.g. 'displacement_x', see ALL_CANONICAL) or a known shorthand "
        f"({sorted(ALL_SHORTHANDS)})."
    )

is_canonical

is_canonical(name: str) -> bool

True if name is a known canonical component name.

Source code in src/apeGmsh/_vocabulary.py
def is_canonical(name: str) -> bool:
    """True if ``name`` is a known canonical component name."""
    if name in ALL_CANONICAL:
        return True
    # Pattern: state_variable_<integer>.
    if name.startswith("state_variable_"):
        suffix = name[len("state_variable_"):]
        return suffix.isdigit()
    # Patterns: fiber_stress_<integer> / fiber_strain_<integer>.
    # Layered shells write a vector per layer (e.g. 5-component
    # plane-stress + transverse-shear), not a scalar; the canonical
    # split is index-based when META labels are generic.
    for stem in ("fiber_stress_", "fiber_strain_"):
        if name.startswith(stem):
            suffix = name[len(stem):]
            if suffix.isdigit():
                return True
    # Patterns: spring_force_<integer> / spring_deformation_<integer>.
    # ZeroLength elements can have N springs; each gets an indexed
    # canonical tied to its position in the configured direction list.
    for stem in ("spring_force_", "spring_deformation_"):
        if name.startswith(stem):
            suffix = name[len(stem):]
            if suffix.isdigit():
                return True
    return False