Skip to content

OpenSees bridge

apeGmsh's OpenSees deck is constructed via the explicit-constructor pattern after the session closes:

from apeGmsh.opensees import apeSees

fem = g.mesh.queries.get_fem_data(dim=3)
ops = apeSees(fem)
ops.model(ndm=3, ndf=6)
# … typed-primitive declarations, explicit fix / mass / patterns …
ops.tcl("model.tcl")     # or ops.py(...), ops.h5(...), ops.run()

The legacy g.opensees session composite and its sub-composites (materials / elements / ingest / inspect / export) were removed in Phase 8 of the bridge teardown (ADR 0009). apeSees brings the session in three ways (ADR 0051): MP constraints (g.constraints.*) auto-emit; loads (g.loads.*) and prescribed displacements (g.displacements.*) are opt-in — a resolved load case reaches the deck only when a bridge pattern imports it with p.from_model(case) (or you author it with p.load(...)); masses and support fixities / SPs are re-declared explicitly on ops (ops.fix(pg=, dofs=), ops.mass(pg=, values=)).

Loads do not auto-emit. A g.loads.* case reaches the solver only via p.from_model(case) inside a pattern (or an ad-hoc p.load). Nothing auto-emits, so there is no double-count trap; the deck is authoritative — the bridge applies exactly the cases you import and does not audit the geometry's declared cases, so a case you don't import is simply not applied. A staged model must keep every pattern stage-scoped (s.pattern(series=...)) — a global pattern + ops.stage(...) raises BridgeError.

Since the teardown, the bridge has been progressively widened:

  • Loads are opt-in (ADR 0051). A g.loads.* case reaches the runnable Tcl/Py deck (and the live/run path) only when a bridge pattern imports it with p.from_model(case) — or you author the load directly with p.load(...). Nothing auto-emits; the deck is authoritative (see the note above).
  • MP constraints emit automatically from fem.nodes.constraints / fem.elements.constraints (ADR 0022, Phase 7b) — equalDOF / rigidLink / rigidDiaphragm / ASDEmbeddedNodeElement lines land in the runnable Tcl/Py deck without an ingest step. The apeSees.h5(path) write target persists per-record details under /opensees/constraints/ (additive minor schema bump 2.6.0 → 2.7.0). Auto-emits a Transformation constraint handler when MP constraints are present and the user has not declared one.
  • Staged analysis ships via ops.stage(name) — see Staged analysis below for the user- surface walkthrough, and the in-repo internals doc at staged-analysis.md for the per-stage emit pipeline.
  • Read-side broker. OpenSeesModel.from_h5(path, fem_root=) provides a frozen read-only view of the persisted /opensees/ zone with the embedded FEMData lazily attached (ADR 0019). Re-emit via om.build("tcl", path) / om.build("py", path) / om.build("live") without rehydrating the apeSees primitives.

For the full user-facing surface (typed materials, sections, elements, recorders, patterns, analysis chain, staged analysis, SSI helpers, cuts and sweeps), see the in-repo api-design.md.

Public surface

apeGmsh.opensees.apeSees

apeSees(fem: 'FEMData', *, units: 'Any' = None, default_orientation: Orientation | None | _UnsetType = _UNSET, opensees: 'OpenSeesTarget | None' = None, element_tags: ElementTagMode = 'sequential', _artifacts: bool = True)

Bases: _ContactQueryMixin, _ModalMixin, _GravityModalMixin, _FrfMixin, _ExplicitMixin

The OpenSees bridge.

Construct with a :class:~apeGmsh.mesh.FEMData snapshot:

.. code-block:: python

ops = apeSees(fem)
ops.model(ndm=3, ndf=6)
steel = ops.uniaxialMaterial.Steel02(fy=420e6, E=200e9, b=0.01)
...

The bridge holds declared state. apeSees.build() returns a :class:BuiltModel (immutable) that emitters consume.

Parameters

fem The FEM snapshot the bridge is built against. default_orientation Orientation field substituted on any ops.geomTransf.<Type>() call where the user supplied neither orientation= nor vecxz=. Defaults to Cartesian() (Z-up) which matches the prevailing structural convention. Pass an explicit None for 2D models, where vecxz is omitted at emit time and an orientation field makes no sense. Pass a custom orientation (e.g. Cartesian(reference_axis=(0,1,0)) for a Y-up CAD import) to set the model-wide default once. element_tags How emitted elements are numbered. "sequential" (default) tags them 1, 2, ... in declaration order. "fem" (ADR 0111 D2) keeps every physical-group element's FEM element id as its OpenSees tag, so a deck translated from another pre-processor (STKO) keeps that tool's element ids; elements the bridge synthesises (node-pair springs, interface zeroLength, embedded / rebar / rigid-body / coupling elements) are numbered above the largest FEM id. "fem" refuses an id <= 0 and an element fanned out by two declarations (BridgeError at emit). _artifacts ADR 0112 D1: every terminal emit and live build leaves the full model.h5 at the session's conventional path (:mod:~apeGmsh.opensees._internal.artifact_write). False is for the library's own bridges only (importers, strut_tie, the emit-cost bench); it is not a user-facing opt-out.

Source code in src/apeGmsh/opensees/apesees.py
def __init__(
    self,
    fem: "FEMData",
    *,
    units: "Any" = None,
    default_orientation: Orientation | None | _UnsetType = _UNSET,
    opensees: "OpenSeesTarget | None" = None,
    element_tags: ElementTagMode = "sequential",
    _artifacts: bool = True,
) -> None:
    if element_tags not in ELEMENT_TAG_MODES:
        raise ValueError(
            f"apeSees: element_tags must be one of {ELEMENT_TAG_MODES}, "
            f"not {element_tags!r}."
        )
    from apeGmsh.units import UnitSystemId, resolve_unit_system

    resolved_units = resolve_unit_system(units)
    fem_units: UnitSystemId | None = getattr(fem, "units", None)
    if (
        resolved_units is not None
        and fem_units is not None
        and resolved_units != fem_units
    ):
        raise ValueError(
            f"apeSees: declared units {resolved_units!r} conflict with "
            f"fem.units {fem_units!r}."
        )
    self._units: UnitSystemId | None = (
        resolved_units if resolved_units is not None else fem_units
    )
    if (
        resolved_units is not None
        and fem_units is None
        and hasattr(fem, "with_units")
    ):
        fem = fem.with_units(resolved_units)
    self._fem: "FEMData" = fem
    # ADR 0111 D2 — how element tags are numbered at emit (BuiltModel).
    self._element_tags: ElementTagMode = element_tags
    # Last live emitter from :meth:`analyze` — retained so post-run live
    # queries (e.g. :meth:`ladruno_projection_tie_force`) can reach the
    # openseespy session that just ran. ``None`` until a live analyze runs.
    self._live_emitter: "LiveOpsEmitter | None" = None
    # ADR 0115 D2: the read session ``Node.read`` / ``ops.elements``
    # answer from. ``None`` until a live analyze completes; a
    # :class:`DroppedSession` (naming why) once this bridge wipes or
    # replaces the domain it solved, or runs a deck.
    self._read_state: ReadState = None
    # ADR 0115 D3: the last deck run (``py``/``tcl`` with
    # ``run=True``) that ``ops.results(path)`` reads; ``None`` until one
    # starts, unfinished until its subprocess exits cleanly.
    self._deck_run: DeckRun | None = None
    # Which OpenSees runtime the subprocess paths bind, and the live
    # fork expectation.  ``None`` → env-var / PATH fallback (the
    # pre-target behaviour).  See :mod:`apeGmsh.opensees._target`.
    self._opensees: "OpenSeesTarget | None" = opensees
    self._primitives: list[Primitive] = []
    # name -> primitive alias table (bridge-side; the primitive
    # stays pure/tag-less, so names never touch the lineage hash or
    # the h5 schema).  Populated by ``_register(..., name=...)`` and
    # read by ``_resolve`` so reference kwargs accept a name string
    # as well as the object handle.
    self._names: dict[str, Primitive] = {}
    # ADR 0130 D4: declared combinations by name, in declaration order.
    # Their own namespace: a term's ``kind`` separates them from stages.
    self._combinations: dict[str, Combination] = {}
    # ``ops.spring_bed``'s shared unit Elastic / Viscous, by their
    # synthesised provenance key. Kept out of ``_names`` so no user
    # material name can be mistaken for them.
    self._spring_bed_units: dict[str, UniaxialMaterial] = {}
    self._frame_modifier_copies = ModifiedCopies()  # one memo per bridge
    # ADR 0112 D3 (V2d): where in the user's source each primitive
    # was declared.  Filled by ``_register`` through the shared
    # capture helper, one record per user call, keyed
    # ``opensees/<kind>/<name|#k>``; ``h5()`` appends the table to
    # the snapshot's own ``/provenance``.  Never hashed.
    self._provenance = ProvenanceStore()
    # ADR 0114 R5 (K1-6): the declaration of every registered
    # primitive and every fix / mass record, by ``id`` of the object
    # (held, so the id stays unique): ``(key, family, name, synth)``,
    # ``key`` being the provenance path.  Written as
    # ``/opensees/decls`` (hash-excluded) through the archive's
    # ``set_declarations``.  An object apeGmsh registers inside a user
    # call that already has its record (ADR 0112 D3) is keyed
    # ``@k`` per family; ``_call_internal_decls`` counts them.
    self._decls: dict[int, tuple[object, _DeclRow]] = {}
    self._call_internal_decls: dict[str, int] = {}
    # Declaration key -> the user call site that declared it, for the
    # duplicate-name refusals (both sites are named).
    self._decl_sites: dict[str, str] = {}
    self._decl_by_key: dict[str, _DeclRow] = {}
    # ADR 0112 D1 (V2d-4b): the automatic model.h5 write, called once
    # at the end of each terminal emit / live build (not ``h5()``).
    self._artifacts = BridgeArtifactWriter(enabled=_artifacts)
    # ADR 0114 Q3: each distinct set of ``ledger`` verbs ``h5()``
    # warned about, so the automatic write and an explicit ``h5()``
    # warn once per set rather than on every emit.
    self._ledger_warned: set[frozenset[str]] = set()
    # Call ordinal of ``imposed_displacement``: the ``<name>`` of its
    # synthesised records when the call gives no ``name=``.
    self._imposed_displacement_calls = 0
    self._tags = TagAllocator()
    self._ndm: int | None = None
    self._ndf: int | None = None
    self._fix_records: list[FixRecord] = []
    self._equation_constraint_records: list[EquationConstraintRecord] = []
    self._mass_records: list[MassRecord] = []
    # ADR 0065 Tier 2 — opt-in: stream per-node masses from the snapshot
    # at emit instead of one bridge MassRecord per node. Set by
    # ``mass_from_model()``; threaded into the BuiltModel.
    self._mass_from_model: bool = False
    # ADR 0051 §4 — opt-in: fix every homogeneous SP on the snapshot.
    # Set by ``fix_from_model()``; materialized into FixRecords at build.
    self._fix_from_model: bool = False
    # K1-6: the objects that carry the one declaration of
    # ``mass_from_model()`` / ``fix_from_model()`` in ``_decls``; the
    # records ``fix_from_model`` materializes at build share it.
    self._mass_from_model_owner = _ModelWideDeclaration("mass_from_model")
    self._fix_from_model_owner = _ModelWideDeclaration("fix_from_model")
    # ADR 0049 — ``ops.ndf`` directives (element-less decoupled nodes only).
    self._ndf_records: list[NdfRecord] = []
    self._region_records: list[RegionAssignmentRecord] = []
    self._rayleigh_records: list[RayleighRecord] = []
    self._damping_attach_records: list[DampingAttachRecord] = []
    self._modal_damping_records: list[ModalDampingRecord] = []
    self._initial_stress_records: list[InitialStressRecord] = []
    # Phase SSI-2.A: closed StageRecord instances accumulate here as
    # ``with ops.stage(name) as s:`` blocks exit.  ``stage_records``
    # being non-empty switches BuiltModel.emit into the staged
    # emission path (per-stage analyze loops with loadConst /
    # wipeAnalysis / hook-list clear between).
    self._stage_records: list[StageRecord] = []
    # Ladruno-fork stack profiler: ordered ``(verb, args)`` control
    # entries recorded by ``ops.profiler.<verb>(...)``.  The deck
    # emitters (tcl / py) flush these bracketing the appended
    # ``analyze`` line — ``start`` / ``reset`` before, ``stop`` /
    # ``report`` / ``memory`` after (see ``_split_profiler_records``).
    # Live single-call profiling does NOT consume this; it is driven by
    # the ``profile=`` kwarg family on :meth:`analyze`.
    self._profiler_records: list[
        tuple[str, tuple[int | float | str, ...]]
    ] = []
    # Tracks the currently-open _StageBuilder, if any, so
    # ``apeSees.stage()`` can refuse nested ``with`` blocks
    # (post-merge cleanup, red-team M4).  None when no stage is
    # being built.  Cleared by ``_StageBuilder.__exit__``.
    self._open_stage_builder: "_StageBuilder | None" = None
    # Phase SSI-2.D (PR-C) recorder claiming: when ``s.recorder(rec)``
    # PULLs a registered recorder spec into a stage's pool, the
    # spec's ``id(...)`` lands here so the global post-element
    # emit loop knows to SKIP it (the stage's emit will drive
    # ``_emit_recorder_spec`` inside the stage block instead).
    # The recorder stays in ``_primitives`` so its allocated tag
    # remains discoverable via ``tag_for[id(p)]``.
    self._stage_claimed_recorder_ids: set[int] = set()
    # Stage-bound constraint claiming: when ``s.embedded(name=...)``
    # / ``s.equal_dof(name=...)`` / etc. CLAIMS a resolved
    # constraint record from ``fem.{nodes,elements}.constraints``,
    # the record's ``id(...)`` lands here so the global MP-
    # constraint emit loop SKIPS it.  The record stays on the
    # FEMData broker (broker is immutable from the bridge's
    # perspective) but emits inside the owning stage's block
    # via ``emit_stage_mp_constraints``.  Doubles as the
    # double-claim detector across stage builders.
    self._stage_claimed_constraint_ids: set[int] = set()
    # ADR 0093 S7 (INV-6) stage-bound INTERFACE claiming, kept as a
    # PARALLEL id-set rather than folded into the MP set above: the
    # two pools are released and re-emitted by different passes
    # (``emit_stage_mp_constraints`` vs ``emit_stage_interfaces``),
    # and a shared set would let an interface claim satisfy — or
    # collide with — an MP claim.  Same semantics otherwise: the
    # record stays on ``fem.elements.interfaces`` and the base
    # ``emit_interfaces`` pass SKIPS it; doubles as the double-claim
    # detector across stage builders.
    self._stage_claimed_interface_ids: set[int] = set()
    # ADR 0051 (BL-3) stage-scoped pattern claiming: when
    # ``s.pattern(series=)`` creates a stage-owned ``Plain``, its
    # ``id(...)`` lands here so the global post-element pattern emit
    # loop SKIPS it (the stage's emit drives ``emit_pattern_spec`` /
    # ``_emit_one_pattern_partitioned`` inside the stage block).
    # The pattern stays in ``_primitives`` so its tag remains
    # discoverable via ``tag_for[id(p)]``.  Mirrors
    # ``_stage_claimed_recorder_ids``.
    self._stage_claimed_pattern_ids: set[int] = set()
    # ADR 0052 slice 1: the single shared ``Constant`` series (factor
    # 1.0) that every stage's HOLD pattern references.  Created
    # lazily on the first ``s.support(...)`` across any stage (so a
    # model with no supports emits no extra series), then reused —
    # one series, not one per stage (ADR 0052 Resolved decision §3).
    self._hold_series: "TimeSeries | None" = None
    # Resolve the sentinel: unset → Cartesian() (Z-up). Explicit
    # None disables the auto-default (2D models).
    if isinstance(default_orientation, _UnsetType):
        self._default_orientation: Orientation | None = Cartesian()
    else:
        self._default_orientation = default_orientation

    # Namespaces.
    self.uniaxialMaterial = _UniaxialMaterialNS(self)
    self.nDMaterial       = _NDMaterialNS(self)
    self.section          = _SectionNS(self)
    self.geomTransf       = _GeomTransfNS(self)
    self.beamIntegration  = _BeamIntegrationNS(self)
    self.timeSeries       = _TimeSeriesNS(self)
    self.pattern          = _PatternNS(self)
    self.fault            = _FaultNS(self)
    self.element          = _ElementNS(self)
    self.recorder         = _RecorderNS(self)
    self.profiler         = _ProfilerNS(self)
    # ADR 0134: the fork's MPM engine (deck-only).
    self.mpm              = _MPMNS(self)
    self.damping          = _DampingNS(self)

    # FEM-aware aggregates (Phase 5A) — query-and-act over fem.nodes.
    self.nodes            = _NodeAccessor(self)
    # ADR 0115 D2 / Q2: FEM elements by pg= / label= / ids=, for
    # read-back. ``self.element`` (singular) holds the constructors.
    self.elements         = _ElementAccessor(self)
    self.constraints      = _ConstraintsNS(self)
    self.numberer         = _NumbererNS(self)
    self.system           = _SystemNS(self)
    self.test             = _TestNS(self)
    self.algorithm        = _AlgorithmNS(self)
    self.integrator       = _IntegratorNS(self)
    self.analysis         = _AnalysisNS(self)
    self.strategy         = _StrategyNS(self)

units property

units: 'str | None'

Canonical consistent unit system ID (e.g. 'kN_m_s'), or None.

opensees property

opensees: 'OpenSeesTarget | None'

The :class:OpenSeesTarget bound on construction, or None.

all_fix_records property

all_fix_records: 'tuple[tuple[str, FixRecord], ...]'

All fix records — global + every stage's pool.

Returns a tuple of (origin, record) pairs where origin is either "global" or f"stage {stage.name!r}". Order: global pool first (in registration order), then each stage in stage_records order, then each record within a stage in registration order.

all_mass_records property

all_mass_records: 'tuple[tuple[str, MassRecord], ...]'

All mass records — global + every stage's pool.

Same shape as :attr:all_fix_records.

all_region_records property

all_region_records: 'tuple[tuple[str, RegionAssignmentRecord], ...]'

All region records — global + every stage's pool.

Phase SSI-2.D PR-C introspection symmetry (matches the :attr:all_fix_records / :attr:all_mass_records shape). Validator V3 (PR-A) guarantees no name= collision across scopes, so the user-facing name is unambiguous per (origin, record) pair.

all_recorder_specs property

all_recorder_specs: 'tuple[tuple[str, Recorder], ...]'

All recorder specs — global + every stage's pool.

Global recorders are sourced from self._primitives filtered to :class:Recorder instances and EXCLUDING any spec claimed by s.recorder(...); the per-stage entries come from each :class:StageRecord's recorder_specs. Origin is "global" or f"stage {stage.name!r}".

critical_time_step

critical_time_step() -> float

Query the active explicit integrator's critical time step dt_cr.

Fork-only (Ladruno): builds + emits a throwaway live model (like :meth:eigen), primes one tiny step to trigger the integrator's dt_cr computation, then returns the usable (Noh-Bathe) limit.

Requires a complete analysis chain with an explicit integrator constructed with cfl=True (e.g. ops.integrator.ExplicitBathe(cfl=True)), a Transient analysis, and element mass density (-rho / -mass) — the dt_cr eigensolve uses element mass+stiffness, not ops.mass nodal mass.

Raises

BridgeError If the analysis chain is incomplete. NotImplementedError If the model has registered stages (live execution of staged models is unsupported — emit Tcl/Py instead). ValueError If dt_cr is not usable (no cfl flag, a non-explicit integrator, or a pure nodal-mass model).

Source code in src/apeGmsh/opensees/procedures/_explicit.py
def critical_time_step(self) -> float:
    """Query the active explicit integrator's critical time step ``dt_cr``.

    **Fork-only** (Ladruno): builds + emits a throwaway live model
    (like :meth:`eigen`), primes one tiny step to trigger the
    integrator's ``dt_cr`` computation, then returns the usable
    (Noh-Bathe) limit.

    Requires a complete analysis chain with an **explicit**
    integrator constructed with ``cfl=True`` (e.g.
    ``ops.integrator.ExplicitBathe(cfl=True)``), a ``Transient``
    analysis, and **element mass density** (``-rho`` / ``-mass``) —
    the ``dt_cr`` eigensolve uses element mass+stiffness, not
    ``ops.mass`` nodal mass.

    Raises
    ------
    BridgeError
        If the analysis chain is incomplete.
    NotImplementedError
        If the model has registered stages (live execution of staged
        models is unsupported — emit Tcl/Py instead).
    ValueError
        If ``dt_cr`` is not usable (no ``cfl`` flag, a non-explicit
        integrator, or a pure nodal-mass model).
    """
    if self._stage_records:
        raise NotImplementedError(
            "apeSees.critical_time_step: live execution does not "
            "support staged models "
            f"(got {len(self._stage_records)} stage(s)). Emit Tcl/Py "
            "and query criticalTimeStep() there instead."
        )
    self._check_analysis_chain_for_analyze()
    self._check_explicit_solver_compat()
    refuse_fork_verb_before_wipe(
        self, "apeSees.critical_time_step", "fork criticalTimeStep")

    from ..emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe

    bm = self.build()
    self._assert_fork_if_required()
    refuse_fork_chain_before_wipe(bm)
    live_emitter = LiveOpsEmitter(wipe=True)
    bm.emit(live_emitter)
    self._artifacts.after_emit(self)
    # Prime one negligible step so the integrator computes dt_cr.
    live_emitter.analyze(steps=1, dt=_DTCR_PRIME_DT)
    return _dtcr_or_raise(live_emitter.critical_time_step())

analyze_explicit

analyze_explicit(*, duration: float, safety: float = 0.9, dt_max: float | None = None) -> 'ExplicitRunResult'

Run an explicit transient over duration, auto-sized to dt_cr.

Fork-only (Ladruno) driver implementing the explicit-dynamics sub-stepping recipe (ADR D5): build + emit, prime one tiny step, query the critical time step, then integrate duration in n = ceil(duration / (safety * dt_cr)) equal sub-steps via a single analyze(n, duration / n).

.. warning:: dt_cr is queried once, on the initial stiffness. For a model whose tangent stiffens mid-run (contact closing, geometric / material stiffening) the true critical step shrinks and a fixed dt can go supercritical and diverge. Guard such runs by constructing the integrator with cfl_abort=True (and recompute=N) so a recomputed CFL violation aborts the run — this method then re-raises that abort as an error rather than returning silently. A one-shot run with an unguarded integrator emits :class:OpenSeesExplicitSolverWarning.

Parameters

duration Total physical time to integrate (> 0). safety Fraction of dt_cr used as the step (0 < safety <= 1; default 0.9). Scales the value criticalTimeStep() returns — do not re-base it on any larger Noh-Bathe bound. dt_max Optional upper bound on the sub-step — use a step finer than stability requires (e.g. for output resolution). > 0.

Returns

ExplicitRunResult (n, dt, dt_cr) — the sub-step count, the step actually used, and the queried critical time step.

Raises

BridgeError / NotImplementedError / ValueError As for :meth:critical_time_step, plus ValueError for an out-of-range duration / safety / dt_max. RuntimeError If the explicit analyze returns non-zero (divergence, or a mid-run -cflAbort when the integrator is guarded).

Source code in src/apeGmsh/opensees/procedures/_explicit.py
def analyze_explicit(
    self,
    *,
    duration: float,
    safety: float = 0.9,
    dt_max: float | None = None,
) -> "ExplicitRunResult":
    """Run an explicit transient over ``duration``, auto-sized to ``dt_cr``.

    **Fork-only** (Ladruno) driver implementing the explicit-dynamics
    sub-stepping recipe (ADR D5): build + emit, prime one tiny step,
    query the critical time step, then integrate ``duration`` in
    ``n = ceil(duration / (safety * dt_cr))`` equal sub-steps via a
    single ``analyze(n, duration / n)``.

    .. warning::
       ``dt_cr`` is queried **once**, on the initial stiffness. For a
       model whose tangent *stiffens* mid-run (contact closing,
       geometric / material stiffening) the true critical step shrinks
       and a fixed ``dt`` can go supercritical and diverge. Guard such
       runs by constructing the integrator with ``cfl_abort=True`` (and
       ``recompute=N``) so a recomputed CFL violation aborts the run —
       this method then re-raises that abort as an error rather than
       returning silently. A one-shot run with an unguarded integrator
       emits :class:`OpenSeesExplicitSolverWarning`.

    Parameters
    ----------
    duration
        Total physical time to integrate (``> 0``).
    safety
        Fraction of ``dt_cr`` used as the step (``0 < safety <= 1``;
        default ``0.9``). Scales the value ``criticalTimeStep()``
        returns — do not re-base it on any larger Noh-Bathe bound.
    dt_max
        Optional upper bound on the sub-step — use a step finer than
        stability requires (e.g. for output resolution). ``> 0``.

    Returns
    -------
    ExplicitRunResult
        ``(n, dt, dt_cr)`` — the sub-step count, the step actually used,
        and the queried critical time step.

    Raises
    ------
    BridgeError / NotImplementedError / ValueError
        As for :meth:`critical_time_step`, plus ``ValueError`` for an
        out-of-range ``duration`` / ``safety`` / ``dt_max``.
    RuntimeError
        If the explicit ``analyze`` returns non-zero (divergence, or a
        mid-run ``-cflAbort`` when the integrator is guarded).
    """
    if self._stage_records:
        raise NotImplementedError(
            "apeSees.analyze_explicit: live execution does not support "
            f"staged models (got {len(self._stage_records)} stage(s)). "
            "Emit Tcl/Py and drive the explicit run there instead."
        )
    self._check_analysis_chain_for_analyze()
    self._check_explicit_solver_compat()
    refuse_fork_verb_before_wipe(
        self, "apeSees.analyze_explicit", "fork criticalTimeStep")
    self._warn_if_unguarded_explicit_run()

    from ..emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe

    bm = self.build()
    self._assert_fork_if_required()
    refuse_fork_chain_before_wipe(bm)
    live_emitter = LiveOpsEmitter(wipe=True)
    bm.emit(live_emitter)
    self._artifacts.after_emit(self)
    # Prime, query dt_cr, then size + run the sub-stepped analysis on
    # the SAME emitter (the prime step's tiny dt is stable).
    live_emitter.analyze(steps=1, dt=_DTCR_PRIME_DT)
    dtcr = _dtcr_or_raise(live_emitter.critical_time_step())
    n, dt = _explicit_substep_count(
        duration, dtcr, safety=safety, dt_max=dt_max,
    )
    ret = int(live_emitter.analyze(steps=n, dt=dt))
    if ret != 0:
        raise RuntimeError(
            f"apeSees.analyze_explicit: explicit run failed (analyze "
            f"returned {ret}) after sizing dt={dt:.3e} from "
            f"dt_cr={dtcr:.3e} over {n} sub-steps. The solution likely "
            "diverged — on a stiffening model the critical step can fall "
            "below dt mid-run. Lower safety=, pass a smaller dt_max=, or "
            "construct the integrator with cfl_abort=True / recompute=N."
        )
    return ExplicitRunResult(n=n, dt=dt, dt_cr=dtcr)

frequency_response

frequency_response(*, f_min: float, f_max: float, n_freq: int, node: 'int | Node', dof: int, num_modes: int, grid: str = 'lin', base_accel_dir: int | None = None, load: 'Plain | str | None' = None, amp: float = 1.0, damp: float | None = None, rayleigh: tuple[float, float] | None = None, modal_damp: Sequence[float] | None = None, resp: str = 'disp', modes: Sequence[int] | None = None, out: str | None = None, solver: str = '-genBandArpack') -> 'FrequencyResponseResult'

Compute the complex modal FRF of one response DOF, live.

Fork-only (Ladruno ADR-44 P2, frequencyResponse): for a harmonic excitation amp·e^{iΩt} the steady response is a dense post-processor on the mode basis — no time stepping. Returns a :class:FrequencyResponseResult (frequencies in Hz + complex FRF).

Excitation: base_accel_dir= for uniform harmonic base acceleration along a global direction (no timeSeries — the sweep is per amp; relative response) XOR load= for harmonic nodal forces amp·P·e^{iΩt} from a plain-nodal-load pattern (absolute response).

grid: "lin" / "log" / "biased" — biased adds a ±5 % cluster around each in-band modal frequency so sharp low-damping peaks are not stepped over.

resp: "disp" | "vel" (iΩ·û) | "accel" (−Ω²·û). out= additionally writes the table to an ASCII file.

Source code in src/apeGmsh/opensees/procedures/_frf.py
def frequency_response(
    self,
    *,
    f_min: float,
    f_max: float,
    n_freq: int,
    node: "int | Node",
    dof: int,
    num_modes: int,
    grid: str = "lin",
    base_accel_dir: int | None = None,
    load: "Plain | str | None" = None,
    amp: float = 1.0,
    damp: float | None = None,
    rayleigh: tuple[float, float] | None = None,
    modal_damp: Sequence[float] | None = None,
    resp: str = "disp",
    modes: Sequence[int] | None = None,
    out: str | None = None,
    solver: str = "-genBandArpack",
) -> "FrequencyResponseResult":
    """Compute the complex modal FRF of one response DOF, live.

    **Fork-only** (Ladruno ADR-44 P2, ``frequencyResponse``): for a
    harmonic excitation ``amp·e^{iΩt}`` the steady response is a
    dense post-processor on the mode basis — no time stepping.
    Returns a :class:`FrequencyResponseResult` (frequencies in Hz
    + complex FRF).

    Excitation: ``base_accel_dir=`` for uniform harmonic base
    acceleration along a global direction (no timeSeries — the
    sweep is per ``amp``; **relative** response) XOR ``load=`` for
    harmonic nodal forces ``amp·P·e^{iΩt}`` from a plain-nodal-load
    pattern (**absolute** response).

    ``grid``: ``"lin"`` / ``"log"`` / ``"biased"`` — biased adds a
    ±5 % cluster around each in-band modal frequency so sharp
    low-damping peaks are not stepped over.

    ``resp``: ``"disp"`` | ``"vel"`` (``iΩ·û``) | ``"accel"``
    (``−Ω²·û``).  ``out=`` additionally writes the table to an
    ASCII file.
    """
    rows = self._run_modal_sweep(
        command="frequency_response",
        context="apeSees.frequency_response",
        f_min=f_min, f_max=f_max, n_freq=n_freq,
        node=node, dof=dof, num_modes=num_modes, grid=grid,
        base_accel_dir=base_accel_dir, load=load, amp=amp,
        damp=damp, rayleigh=rayleigh, modal_damp=modal_damp,
        resp=resp, modes=modes, out=out, solver=solver,
    )
    from ..analysis.modal import FrequencyResponseResult
    import numpy as np

    table = np.asarray(rows, dtype=np.float64)
    return FrequencyResponseResult(
        freq=table[:, 0],
        response=table[:, 1] + 1j * table[:, 2],
    )

steady_state_dynamics

steady_state_dynamics(*, f_min: float, f_max: float, n_freq: int, node: 'int | Node', dof: int, num_modes: int, grid: str = 'lin', base_accel_dir: int | None = None, load: 'Plain | str | None' = None, amp: float = 1.0, damp: float | None = None, rayleigh: tuple[float, float] | None = None, modal_damp: Sequence[float] | None = None, resp: str = 'disp', modes: Sequence[int] | None = None, out: str | None = None, solver: str = '-genBandArpack') -> 'SteadyStateResult'

Steady-state harmonic response amplitude |response| per sweep frequency — the magnitude companion of :meth:frequency_response (same flags, fork ADR-44 P2).

Source code in src/apeGmsh/opensees/procedures/_frf.py
def steady_state_dynamics(
    self,
    *,
    f_min: float,
    f_max: float,
    n_freq: int,
    node: "int | Node",
    dof: int,
    num_modes: int,
    grid: str = "lin",
    base_accel_dir: int | None = None,
    load: "Plain | str | None" = None,
    amp: float = 1.0,
    damp: float | None = None,
    rayleigh: tuple[float, float] | None = None,
    modal_damp: Sequence[float] | None = None,
    resp: str = "disp",
    modes: Sequence[int] | None = None,
    out: str | None = None,
    solver: str = "-genBandArpack",
) -> "SteadyStateResult":
    """Steady-state harmonic response amplitude ``|response|`` per
    sweep frequency — the magnitude companion of
    :meth:`frequency_response` (same flags, fork ADR-44 P2)."""
    rows = self._run_modal_sweep(
        command="steady_state_dynamics",
        context="apeSees.steady_state_dynamics",
        f_min=f_min, f_max=f_max, n_freq=n_freq,
        node=node, dof=dof, num_modes=num_modes, grid=grid,
        base_accel_dir=base_accel_dir, load=load, amp=amp,
        damp=damp, rayleigh=rayleigh, modal_damp=modal_damp,
        resp=resp, modes=modes, out=out, solver=solver,
    )
    from ..analysis.modal import SteadyStateResult
    import numpy as np

    table = np.asarray(rows, dtype=np.float64)
    return SteadyStateResult(
        freq=table[:, 0], magnitude=table[:, 1],
    )

random_response

random_response(*, f_min: float, f_max: float, n_freq: int, node: 'int | Node', dof: int, num_modes: int, input_psd: 'TimeSeries | str', grid: str = 'biased', base_accel_dir: int | None = None, load: 'Plain | str | None' = None, damp: float | None = None, rayleigh: tuple[float, float] | None = None, modal_damp: Sequence[float] | None = None, resp: str = 'disp', modes: Sequence[int] | None = None, stats: bool = False, duration: float | None = None, out: str | None = None, solver: str = '-genBandArpack') -> 'RandomResponseResult'

Stationary random response RMS on the modal FRF, live.

Fork-only (Ladruno ADR-44 P3, randomResponse): input_psd is a one-sided PSD G(f) in Hz ((excitation)²/ Hz), supplied as a registered timeSeries sampled at f in Hz (Path with f→G breakpoints, Constant for white noise). With base_accel_dir= it is the base-acceleration PSD; with load= the PSD of the scalar multiplying the pattern's nodal-load shape (fully correlated).

grid defaults to "biased" — the RMS is a band integral and a linear grid mis-integrates sharp resonances (fork guide P3). The band [f_min, f_max] must cover the input's support and every resonance carrying response power; the fork refuses zero-damped in-band modes and a rigid-body mode with f_min = 0.

stats= adds ν₀ (mean zero-upcrossing rate, Hz) and the spectral moments m0 / m2; duration= additionally appends the Davenport expected peak over that exposure.

Source code in src/apeGmsh/opensees/procedures/_frf.py
def random_response(
    self,
    *,
    f_min: float,
    f_max: float,
    n_freq: int,
    node: "int | Node",
    dof: int,
    num_modes: int,
    input_psd: "TimeSeries | str",
    grid: str = "biased",
    base_accel_dir: int | None = None,
    load: "Plain | str | None" = None,
    damp: float | None = None,
    rayleigh: tuple[float, float] | None = None,
    modal_damp: Sequence[float] | None = None,
    resp: str = "disp",
    modes: Sequence[int] | None = None,
    stats: bool = False,
    duration: float | None = None,
    out: str | None = None,
    solver: str = "-genBandArpack",
) -> "RandomResponseResult":
    """Stationary random response RMS on the modal FRF, live.

    **Fork-only** (Ladruno ADR-44 P3, ``randomResponse``):
    ``input_psd`` is a **one-sided PSD G(f) in Hz** ((excitation)²/
    Hz), supplied as a registered timeSeries sampled at ``f`` in Hz
    (``Path`` with f→G breakpoints, ``Constant`` for white noise).
    With ``base_accel_dir=`` it is the base-acceleration PSD; with
    ``load=`` the PSD of the scalar multiplying the pattern's
    nodal-load shape (fully correlated).

    ``grid`` defaults to ``"biased"`` — the RMS is a band integral
    and a linear grid mis-integrates sharp resonances (fork guide
    P3).  The band ``[f_min, f_max]`` must cover the input's
    support and every resonance carrying response power; the fork
    refuses zero-damped in-band modes and a rigid-body mode with
    ``f_min = 0``.

    ``stats=`` adds ``ν₀`` (mean zero-upcrossing rate, Hz) and the
    spectral moments ``m0`` / ``m2``; ``duration=`` additionally
    appends the Davenport expected peak over that exposure.
    """
    from ..analysis.modal import RandomResponseResult

    context = "apeSees.random_response"
    ts = self._resolve(input_psd, base=TimeSeries)
    if not isinstance(ts, TimeSeries):
        raise TypeError(
            f"{context}: input_psd= needs an ops.timeSeries.* "
            f"handle (or registered name), got {type(ts).__name__}."
        )
    psd_tag = self.tag_for(ts)
    if psd_tag is None:
        raise BridgeError(
            f"{context}: the input_psd timeSeries is not "
            "registered on this bridge — create it via "
            "ops.timeSeries.<Type>(...)."
        )
    if duration is not None and duration <= 0.0:
        raise ValueError(
            f"{context}: duration must be > 0, got {duration}."
        )
    extra: list[int | float | str] = ["-inputPSD", int(psd_tag)]
    if stats or duration is not None:
        extra.append("-stats")
    if duration is not None:
        extra.extend(("-duration", float(duration)))

    raw = self._run_modal_sweep(
        command="random_response",
        context=context,
        f_min=f_min, f_max=f_max, n_freq=n_freq,
        node=node, dof=dof, num_modes=num_modes, grid=grid,
        base_accel_dir=base_accel_dir, load=load, amp=None,
        damp=damp, rayleigh=rayleigh, modal_damp=modal_damp,
        resp=resp, modes=modes, out=out, solver=solver,
        extra_args=tuple(extra),
    )
    if isinstance(raw, (int, float)):
        return RandomResponseResult(rms=float(raw))
    values = [float(v) for v in raw]
    peak = values[4] if len(values) > 4 else None
    return RandomResponseResult(
        rms=values[0], nu0=values[1], m0=values[2], m2=values[3],
        peak=peak,
    )

modal_after_gravity

modal_after_gravity(num_modes: int, *, p_delta: bool = True, solver: str = '-genBandArpack', basis: str = 'eigen', ritz_dirs: Sequence[int] = (), ritz_patterns: 'Sequence[Plain | str]' = (), residual: 'Sequence[int] | None' = None, residual_period: float | None = None) -> 'GravityModalResult'

Gravity preload, loadConst, then eigen + modalProperties on the same live domain.

The sequence (ADR 0124 D1):

  1. Build and emit the model, as :meth:analyze does.
  2. Run the declared analysis chain to λ = 1: every registered load pattern is the gravity preload (declare the gravity combination, e.g. D + SD + 0.25 L, as the patterns and their factors). The chain must be Static with a fixed-increment LoadControl(dlam=1/N); the driver runs the N steps, and the declared test and algorithm set the tolerance and the iteration (Newton converges a P-Delta model; the step count is the dlam).
  3. loadConst -time 0: the gravity loads stay on, frozen.
  4. eigen on the current tangent, then modalProperties -return.

The mode set (fork chain M, Ladruno ADR 213). The order is fixed: the basis, then the residual pseudo-modes, then modalProperties, with no eigen in between (a later eigen drops the pseudo-modes and the mode tags).

  • basis="eigen" (default) solves eigen; basis="ritz" runs ritzVectors num_modes instead, with the starting loads M ι_d for each of ritz_dirs and the reference loads of each of ritz_patterns (the gravity pattern gives a basis whose static participation in that load is 100 %). Ritz periods are Rayleigh periods, not natural periods.
  • residual=dirs appends residualModes -dir dirs: the missing-mass pseudo-modes, so the modal mass of each direction reaches 100 %. On a Ritz basis the fork re-solves the joint set (all tagged Ritz).
  • residual_period=T adds -period T: a spectrum reads the pseudo-modes' Sa at T and combines them as one rigid mode (ADR 213 D3b). The fork refuses it on a Ritz basis, and so does the bridge.

Each mode's kind is on the result (:attr:~apeGmsh.opensees.analysis.modal.ModalPropertiesResult.kinds).

What p_delta means. True solves step 4 after the preload, so the stiffness is K - Kg with Kg from the gravity axial forces. False solves it before step 2, on the unstressed stiffness K (no initial axial force), and the gravity analysis runs afterwards; the result's :attr:~GravityModalResult.gravity is the same in both. The geometric stiffness comes from the element formulation, not from this driver: geomTransf PDelta (or Corotational) frames and geometrically nonlinear shells such as :class:~apeGmsh.opensees.element.shell.ShellNLDKGQ carry it; a Linear transformation or a linear shell gives the same modes either way.

Solver. solver is passed to eigen verbatim. The default -genBandArpack is the ARPACK ArpackSOE, which factors through the analysis's own linear system, so the declared system (UmfPack/BandGen on stock, Pardiso on the fork) is the one the eigen solve uses. ARPACK needs num_modes below the free DOF count; use -fullGenLapack on a tiny model.

The gravity state is snapshot right after step 3 and re-read after step 4; a difference raises (the eigen solve must not move the domain). The domain is left at the gravity state, and the bridge's read session (Node.read) answers there.

Parameters

num_modes Modes to extract, >= 1. p_delta True (default): modes on K - Kg after the preload. False: modes on K before it. solver The eigen solver flag. basis "eigen" or "ritz" (num_modes Ritz vectors). ritz_dirs, ritz_patterns The Ritz starting loads (basis="ritz" only; at least one): global translations, and ops.pattern.Plain handles or names. residual Directions (1, 2, 3) to complete with residualModes, or None. residual_period The pseudo-modes' Sa period T (s), or None for their Rayleigh periods. Needs residual; refused with basis="ritz".

Raises

ValueError num_modes < 1, the integrator is not a fixed-increment LoadControl reaching λ = 1, or the mode-set options do not fit together. BridgeError The analysis chain is incomplete, or not Static; or a Ritz basis or residual is asked of an MPI (partitioned) model. ForkTooOldError basis="ritz" or residual on a build without chain M. NotImplementedError The model has registered stages (live runs flat models only, ADR 0121 D2). RuntimeError The gravity analysis failed to converge, or the eigen solve moved the gravity state.

Source code in src/apeGmsh/opensees/procedures/_gravity_modal.py
def modal_after_gravity(
    self,
    num_modes: int,
    *,
    p_delta: bool = True,
    solver: str = "-genBandArpack",
    basis: str = "eigen",
    ritz_dirs: Sequence[int] = (),
    ritz_patterns: "Sequence[Plain | str]" = (),
    residual: "Sequence[int] | None" = None,
    residual_period: float | None = None,
) -> "GravityModalResult":
    """Gravity preload, ``loadConst``, then ``eigen`` + ``modalProperties``
    on the same live domain.

    The sequence (ADR 0124 D1):

    1. Build and emit the model, as :meth:`analyze` does.
    2. Run the declared analysis chain to ``λ = 1``: every registered
       load pattern is the gravity preload (declare the gravity
       combination, e.g. ``D + SD + 0.25 L``, as the patterns and
       their factors). The chain must be ``Static`` with a
       fixed-increment ``LoadControl(dlam=1/N)``; the driver runs the
       ``N`` steps, and the declared ``test`` and ``algorithm`` set the
       tolerance and the iteration (``Newton`` converges a P-Delta
       model; the step count is the ``dlam``).
    3. ``loadConst -time 0``: the gravity loads stay on, frozen.
    4. ``eigen`` on the current tangent, then ``modalProperties -return``.

    **The mode set** (fork chain M, Ladruno ADR 213). The order is
    fixed: the basis, then the residual pseudo-modes, then
    ``modalProperties``, with no ``eigen`` in between (a later
    ``eigen`` drops the pseudo-modes and the mode tags).

    - ``basis="eigen"`` (default) solves ``eigen``; ``basis="ritz"``
      runs ``ritzVectors num_modes`` instead, with the starting loads
      ``M ι_d`` for each of ``ritz_dirs`` and the reference loads of
      each of ``ritz_patterns`` (the gravity pattern gives a basis whose
      static participation in that load is 100 %). Ritz periods are
      Rayleigh periods, not natural periods.
    - ``residual=dirs`` appends ``residualModes -dir dirs``: the
      missing-mass pseudo-modes, so the modal mass of each direction
      reaches 100 %. On a Ritz basis the fork re-solves the joint set
      (all tagged Ritz).
    - ``residual_period=T`` adds ``-period T``: a spectrum reads the
      pseudo-modes' Sa at ``T`` and combines them as one rigid mode
      (ADR 213 D3b). The fork refuses it on a Ritz basis, and so does
      the bridge.

    Each mode's kind is on the result
    (:attr:`~apeGmsh.opensees.analysis.modal.ModalPropertiesResult.kinds`).

    **What ``p_delta`` means.** ``True`` solves step 4 after the preload,
    so the stiffness is ``K - Kg`` with ``Kg`` from the gravity axial
    forces. ``False`` solves it *before* step 2, on the unstressed
    stiffness ``K`` (no initial axial force), and the gravity analysis
    runs afterwards; the result's :attr:`~GravityModalResult.gravity`
    is the same in both. The geometric stiffness comes from the element
    formulation, not from this driver: ``geomTransf PDelta`` (or
    ``Corotational``) frames and geometrically nonlinear shells such as
    :class:`~apeGmsh.opensees.element.shell.ShellNLDKGQ` carry it; a
    ``Linear`` transformation or a linear shell gives the same modes
    either way.

    **Solver.** ``solver`` is passed to ``eigen`` verbatim. The default
    ``-genBandArpack`` is the ARPACK ``ArpackSOE``, which factors through
    the analysis's own linear system, so the declared ``system``
    (``UmfPack``/``BandGen`` on stock, ``Pardiso`` on the fork) is the
    one the eigen solve uses. ARPACK needs ``num_modes`` below the free
    DOF count; use ``-fullGenLapack`` on a tiny model.

    The gravity state is snapshot right after step 3 and re-read after
    step 4; a difference raises (the eigen solve must not move the
    domain). The domain is left at the gravity state, and the bridge's
    read session (``Node.read``) answers there.

    Parameters
    ----------
    num_modes
        Modes to extract, ``>= 1``.
    p_delta
        ``True`` (default): modes on ``K - Kg`` after the preload.
        ``False``: modes on ``K`` before it.
    solver
        The ``eigen`` solver flag.
    basis
        ``"eigen"`` or ``"ritz"`` (``num_modes`` Ritz vectors).
    ritz_dirs, ritz_patterns
        The Ritz starting loads (``basis="ritz"`` only; at least one):
        global translations, and ``ops.pattern.Plain`` handles or names.
    residual
        Directions (1, 2, 3) to complete with ``residualModes``, or
        ``None``.
    residual_period
        The pseudo-modes' Sa period ``T`` (s), or ``None`` for their
        Rayleigh periods. Needs ``residual``; refused with
        ``basis="ritz"``.

    Raises
    ------
    ValueError
        ``num_modes < 1``, the integrator is not a fixed-increment
        ``LoadControl`` reaching ``λ = 1``, or the mode-set options do
        not fit together.
    BridgeError
        The analysis chain is incomplete, or not ``Static``; or a Ritz
        basis or residual is asked of an MPI (partitioned) model.
    ForkTooOldError
        ``basis="ritz"`` or ``residual`` on a build without chain M.
    NotImplementedError
        The model has registered stages (live runs flat models only,
        ADR 0121 D2).
    RuntimeError
        The gravity analysis failed to converge, or the eigen solve
        moved the gravity state.
    """
    context = "apeSees.modal_after_gravity"
    return self._run_gravity_modal(
        num_modes, p_delta=p_delta, solver=solver, context=context,
        hook=None, mode_set=self._mode_set(
            num_modes, basis=basis, ritz_dirs=ritz_dirs,
            ritz_patterns=ritz_patterns, residual=residual,
            residual_period=residual_period, context=context),
    )

spectrum_after_gravity

spectrum_after_gravity(num_modes: int, *, spectra: 'Sequence[DesignSpectrum]', extractors: 'Mapping[str, ResponseExtractor]', p_delta: bool = True, solver: str = '-genBandArpack', basis: str = 'eigen', ritz_dirs: Sequence[int] = (), ritz_patterns: 'Sequence[Plain | str]' = (), residual: 'Sequence[int] | None' = None, residual_period: float | None = None) -> 'SpectrumModalResult'

Per-mode response spectrum about the gravity state (ADR 0124 D4).

Runs :meth:modal_after_gravity's sequence, then settles the reference state with unloaded Linear steps (so it is the equilibrium, not wherever the declared test stopped). On the same domain, for each mode k and each sign, it applies the probe force ± a_k M φ_k as a nodal-load pattern, takes one Linear step on the current tangent at dλ = 0 (the tangent the modes were solved on, so the domain moves by exactly ± a_k φ_k / λ_k), calls every extractor there, removes the pattern and settles back. The per-mode value under spectrum d is Γ_kd Sa_d(T_k) (Δr⁺ - Δr⁻) / (2 a_k), each Δr the leg's change from its settled start: the state responseSpectrumAnalysis -mode k imposes, about the reference state instead of in place of it. Displacements are the modal ones to round-off, PDelta included; element forces and reactions are those of the elements at that state. The probe amplitude a_k does not depend on the spectrum: the largest nodal translation moves by 1e-8 of the model's extent. A mode whose effective mass is below 1e-12 of the largest in every requested direction is skipped (left at zero). The two legs must meet the same stiffness in every element: a second difference of an element's resisting force above 1e-3 of its first difference (a no-tension brace or a gap at zero strain, a material that loads and unloads on different branches, such as Concrete01 on its backbone) raises. A mode that fails that check is probed again at 100 times the amplitude, judged there, and takes its values from that probe: a kink's ratio does not depend on the amplitude, while round-off (a near-rigid link, whose force is a large stiffness times a tiny deformation) shrinks with it. Combine the result with :meth:SpectrumModalResult.combine (CQC / SRSS) and :meth:SpectrumModalResult.directional (100/30 / SRSS); the gravity values are kept apart (:func:~apeGmsh.opensees.analysis.spectrum.seismic_envelope).

The reference state is the gravity state with p_delta=True and the unloaded state with p_delta=False (modes and per-mode responses on K, gravity run afterwards). With p_delta=True the domain ends at the settled gravity state, checked against the snapshot taken after settling; with a loose declared test that is nearer equilibrium than the state the gravity analysis stopped at. With p_delta=False it ends where the gravity analysis stopped. Either way result.modal.gravity is the state the domain is left at, so result.modal.gravity_drift() reads 0.0 right after the call.

responseSpectrumAnalysis -mode k is not used: it replaces the committed displacement with the modal one and commits, so the gravity state is lost (ADR 0124, Context). Where the build takes the fork's -increment flag (WP-207, ADR 0124 amendment) and every extractor is a built-in one (NodeDisp, NodeReaction, ElementResponse: they read the trial state), each leg is imposed with responseSpectrumAnalysis -mode k -increment at the same probe amplitude and returned with -revert, instead of the load step and the return settling: the settled reference, the mode skip, the kink check and the recorder refusal are the same on both routes, and the imposed displacement is checked against ± a_k φ_k / λ_k.

Ritz and residual modes (basis, residual, residual_period as in :meth:modal_after_gravity). A Ritz vector or a pseudo-mode ψ is not an eigenvector, so a static leg under a M ψ would move the domain by K⁻¹ M ψ, not by a ψ / λ. Such a mode set therefore needs the -increment route (imposed legs, every extractor a built-in one), and is refused on the static one. The values are those of the fork's RSA: ψ Γ Sa / λ with the Rayleigh λ. With residual_period=T the pseudo-modes read Sa at T, and every combination on the result sums them into one rigid mode at ω = 2π/T (:attr:SpectrumModalResult.sa_periods, ADR 213 D3b). The modes' kinds are :attr:SpectrumModalResult.kinds; a Ritz or pseudo-mode period is a Rayleigh period.

Nodal mass only. The modal force is M φ built from the nodal masses, so a model whose mass sits in its elements (a section or material rho, an element mass=) is refused. Lump the mass to the nodes (g.masses on the session, or ops.mass / mass_from_model): that is the supported route.

The modes must carry the loaded mass. A spectrum direction is refused when modalProperties counts less free mass along it (totalFreeMass) than the nodes carry on DOFs no fix holds, or when the modes' effective masses along it sum to at most 1e-6 of the free mass (every Γ zero to round-off). The first is what stock OpenSees and Ladruno forks older than ladruno-v20261027 (WP-211) give for mass on the constrained nodes of a rigid diaphragm under constraints Transformation: a zero response, or a Γ too low when only some floors lose their mass. These checks need the modes, so with p_delta=True they run after the gravity analysis (in the per-mode step, on the gravity state), and with p_delta=False before it. On those older builds, mass on a node that an equalDOF ties to a fixed node is refused too, although its Γ is right: put that mass on the fixed node, or use a fork with WP-211.

No recorders. Each probe leg and each return solve commits, and on the -increment route each leg calls the domain's recorders on its trial state, so a declared recorder would write extra rows for every mode that are not states of the structure. A model with a declared recorder is refused; the gravity state is in :attr:SpectrumModalResult.gravity_values and in Node.read on the bridge afterwards.

The driver always adds the extractor "base_shear" (the total support reaction per translational direction), so :meth:SpectrumModalResult.base_shear gives V_t per direction. The result also carries each mode's inertia force m φ Γ Sa at every massed node (:attr:SpectrumModalResult.inertia), from which :meth:SpectrumModalResult.storey_forces sums storey shears and moments per mode; each mode's total inertia is checked against its total base reaction, and an :class:~apeGmsh.opensees.analysis.spectrum.InertiaBalanceWarning is issued when they differ by more than 1e-3 of the inertia.

Parameters

num_modes Modes to extract and combine, >= 1. spectra One :class:~apeGmsh.opensees.analysis.spectrum.DesignSpectrum per excitation; each names its translational direction. extractors Name -> extractor(ops) -> 1-D float array of fixed length (:class:~apeGmsh.opensees.analysis.spectrum.NodeDisp, :class:~apeGmsh.opensees.analysis.spectrum.NodeReaction, :class:~apeGmsh.opensees.analysis.spectrum.ElementResponse, or any callable, such as a story-shear aggregator). The name "base_shear" is reserved. p_delta, solver, basis, ritz_dirs, ritz_patterns, residual, residual_period As :meth:modal_after_gravity.

Raises

BridgeError The model carries element mass (refused: the modal force is built from nodal masses), declares a recorder, or a spectrum names a direction outside 1..ndm, or a direction a spectrum loads has less free mass than unfixed nodal mass, or a zero Γ (to round-off) in every mode. ValueError No spectra or extractors, or an extractor's length changed. RuntimeError A per-mode solve failed, a mode has a non-positive eigenvalue, the two probe legs met different stiffnesses, or the domain did not return to the reference state.

Source code in src/apeGmsh/opensees/procedures/_gravity_modal.py
def spectrum_after_gravity(
    self,
    num_modes: int,
    *,
    spectra: "Sequence[DesignSpectrum]",
    extractors: "Mapping[str, ResponseExtractor]",
    p_delta: bool = True,
    solver: str = "-genBandArpack",
    basis: str = "eigen",
    ritz_dirs: Sequence[int] = (),
    ritz_patterns: "Sequence[Plain | str]" = (),
    residual: "Sequence[int] | None" = None,
    residual_period: float | None = None,
) -> "SpectrumModalResult":
    """Per-mode response spectrum about the gravity state (ADR 0124 D4).

    Runs :meth:`modal_after_gravity`'s sequence, then settles the
    reference state with unloaded ``Linear`` steps (so it is the
    equilibrium, not wherever the declared test stopped). On the same
    domain, for each mode ``k`` and each sign, it applies the probe
    force ``± a_k M φ_k`` as a nodal-load pattern, takes one ``Linear``
    step on the current tangent at ``dλ = 0`` (the tangent the modes
    were solved on, so the domain moves by exactly ``± a_k φ_k / λ_k``),
    calls every extractor there, removes the pattern and settles back.
    The per-mode value under spectrum ``d`` is
    ``Γ_kd Sa_d(T_k) (Δr⁺ - Δr⁻) / (2 a_k)``, each ``Δr`` the leg's
    change from its settled start: the state
    ``responseSpectrumAnalysis -mode k`` imposes, about the reference
    state instead of in place of it. Displacements are the modal ones to
    round-off, PDelta included; element forces and reactions are those of
    the elements at that state. The probe amplitude ``a_k`` does not
    depend on the spectrum: the largest nodal translation moves by
    ``1e-8`` of the model's extent. A mode whose effective mass is below
    ``1e-12`` of the largest in every requested direction is skipped
    (left at zero). The two legs must meet the same stiffness in every
    element: a second difference of an element's resisting force above
    ``1e-3`` of its first difference (a no-tension brace or a gap at zero
    strain, a material that loads and unloads on different branches,
    such as ``Concrete01`` on its backbone) raises. A mode that fails
    that check is probed again at 100 times the amplitude, judged there,
    and takes its values from that probe: a kink's ratio does not depend
    on the amplitude, while round-off (a near-rigid link, whose force is
    a large stiffness times a tiny deformation) shrinks with it. Combine
    the result
    with :meth:`SpectrumModalResult.combine` (CQC / SRSS) and
    :meth:`SpectrumModalResult.directional` (100/30 / SRSS); the gravity
    values are kept apart (:func:`~apeGmsh.opensees.analysis.spectrum.seismic_envelope`).

    The reference state is the gravity state with ``p_delta=True`` and
    the unloaded state with ``p_delta=False`` (modes and per-mode
    responses on ``K``, gravity run afterwards). With ``p_delta=True``
    the domain ends at the settled gravity state, checked against the
    snapshot taken after settling; with a loose declared test that is
    nearer equilibrium than the state the gravity analysis stopped at.
    With ``p_delta=False`` it ends where the gravity analysis stopped.
    Either way ``result.modal.gravity`` is the state the domain is left
    at, so ``result.modal.gravity_drift()`` reads ``0.0`` right after the
    call.

    ``responseSpectrumAnalysis -mode k`` is not used: it replaces the
    committed displacement with the modal one and commits, so the gravity
    state is lost (ADR 0124, Context). Where the build takes the fork's
    ``-increment`` flag (WP-207, ADR 0124 amendment) and every extractor
    is a built-in one (``NodeDisp``, ``NodeReaction``,
    ``ElementResponse``: they read the trial state), each leg is imposed
    with ``responseSpectrumAnalysis -mode k -increment`` at the same
    probe amplitude and returned with ``-revert``, instead of the load
    step and the return settling: the settled reference, the mode skip,
    the kink check and the recorder refusal are the same on both routes,
    and the imposed displacement is checked against ``± a_k φ_k / λ_k``.

    **Ritz and residual modes** (``basis``, ``residual``,
    ``residual_period`` as in :meth:`modal_after_gravity`). A Ritz
    vector or a pseudo-mode ``ψ`` is not an eigenvector, so a static
    leg under ``a M ψ`` would move the domain by ``K⁻¹ M ψ``, not by
    ``a ψ / λ``. Such a mode set therefore needs the ``-increment``
    route (imposed legs, every extractor a built-in one), and is
    refused on the static one. The values are those of the fork's RSA:
    ``ψ Γ Sa / λ`` with the Rayleigh ``λ``. With ``residual_period=T``
    the pseudo-modes read Sa at ``T``, and every combination on the
    result sums them into one rigid mode at ``ω = 2π/T``
    (:attr:`SpectrumModalResult.sa_periods`, ADR 213 D3b). The modes'
    kinds are :attr:`SpectrumModalResult.kinds`; a Ritz or pseudo-mode
    period is a Rayleigh period.

    **Nodal mass only.** The modal force is ``M φ`` built from the nodal
    masses, so a model whose mass sits in its elements (a section or
    material ``rho``, an element ``mass=``) is refused. Lump the mass to
    the nodes (``g.masses`` on the session, or ``ops.mass`` /
    ``mass_from_model``): that is the supported route.

    **The modes must carry the loaded mass.** A spectrum direction is
    refused when ``modalProperties`` counts less free mass along it
    (``totalFreeMass``) than the nodes carry on DOFs no ``fix`` holds,
    or when the modes' effective masses along it sum to at most
    ``1e-6`` of the free mass (every Γ zero to round-off). The first is
    what stock OpenSees and Ladruno forks older than
    ``ladruno-v20261027`` (WP-211) give for mass on the constrained
    nodes of a rigid diaphragm under ``constraints Transformation``: a
    zero response, or a Γ too low when only some floors lose their
    mass. These checks need the modes, so with ``p_delta=True`` they
    run after the gravity analysis (in the per-mode step, on the
    gravity state), and with ``p_delta=False`` before it. On those older
    builds, mass on a node that an ``equalDOF`` ties to a fixed node is
    refused too, although its Γ is right: put that mass on the fixed
    node, or use a fork with WP-211.

    **No recorders.** Each probe leg and each return solve commits, and
    on the ``-increment`` route each leg calls the domain's recorders on
    its trial state, so a declared recorder would write extra rows for
    every mode that are not states of the structure. A model with a declared recorder is
    refused; the gravity state is in
    :attr:`SpectrumModalResult.gravity_values` and in ``Node.read`` on
    the bridge afterwards.

    The driver always adds the extractor ``"base_shear"`` (the total
    support reaction per translational direction), so
    :meth:`SpectrumModalResult.base_shear` gives ``V_t`` per direction.
    The result also carries each mode's inertia force ``m φ Γ Sa`` at
    every massed node (:attr:`SpectrumModalResult.inertia`), from which
    :meth:`SpectrumModalResult.storey_forces` sums storey shears and
    moments per mode; each mode's total inertia is checked against its
    total base reaction, and an
    :class:`~apeGmsh.opensees.analysis.spectrum.InertiaBalanceWarning` is
    issued when they differ by more than ``1e-3`` of the inertia.

    Parameters
    ----------
    num_modes
        Modes to extract and combine, ``>= 1``.
    spectra
        One :class:`~apeGmsh.opensees.analysis.spectrum.DesignSpectrum`
        per excitation; each names its translational direction.
    extractors
        Name -> ``extractor(ops) -> 1-D float array`` of fixed length
        (:class:`~apeGmsh.opensees.analysis.spectrum.NodeDisp`,
        :class:`~apeGmsh.opensees.analysis.spectrum.NodeReaction`,
        :class:`~apeGmsh.opensees.analysis.spectrum.ElementResponse`, or
        any callable, such as a story-shear aggregator). The name
        ``"base_shear"`` is reserved.
    p_delta, solver, basis, ritz_dirs, ritz_patterns, residual, residual_period
        As :meth:`modal_after_gravity`.

    Raises
    ------
    BridgeError
        The model carries element mass (refused: the modal force is
        built from nodal masses), declares a recorder, or a spectrum
        names a direction outside ``1..ndm``, or a direction a spectrum
        loads has less free mass than unfixed nodal mass, or a zero Γ
        (to round-off) in every mode.
    ValueError
        No spectra or extractors, or an extractor's length changed.
    RuntimeError
        A per-mode solve failed, a mode has a non-positive eigenvalue,
        the two probe legs met different stiffnesses, or the domain did
        not return to the reference state.
    """
    from .._internal.types import Recorder
    from ..analysis.spectrum import SpectrumModalResult

    context = "apeSees.spectrum_after_gravity"
    mode_set = self._mode_set(
        num_modes, basis=basis, ritz_dirs=ritz_dirs,
        ritz_patterns=ritz_patterns, residual=residual,
        residual_period=residual_period, context=context)
    recorders = sorted({type(p).__name__ for p in self._primitives
                        if isinstance(p, Recorder)})
    if recorders:
        raise BridgeError(
            f"{context}: the model declares recorders ({', '.join(recorders)}). "
            "Every per-mode probe leg and return solve commits, so they "
            "would record rows for every mode that are not states of the "
            "structure. Remove the recorders; the gravity state is in "
            "SpectrumModalResult.gravity_values and Node.read afterwards, "
            "and modal_after_gravity records the gravity run on its own."
        )
    spectra_t = tuple(spectra)
    if not spectra_t:
        raise ValueError(f"{context}: give at least one DesignSpectrum.")
    from ..analysis.spectrum import BASE_SHEAR, _TotalReaction

    named = dict(extractors)
    if not named:
        raise ValueError(f"{context}: give at least one extractor.")
    if BASE_SHEAR in named:
        raise ValueError(
            f"{context}: the extractor name {BASE_SHEAR!r} is reserved "
            "for the driver's own total base reaction."
        )
    ndm = self._ndm
    named[BASE_SHEAR] = _TotalReaction(int(ndm or 0))
    for s in spectra_t:
        if ndm is not None and not 1 <= s.direction <= ndm:
            raise BridgeError(
                f"{context}: a spectrum acts along direction "
                f"{s.direction}, outside the translational 1..{ndm}."
            )
    holder: dict[str, object] = {}

    def hook(live_emitter: "LiveOpsEmitter", eigenvalues: "np.ndarray",
             properties: "Mapping[str, Sequence[float]]") -> None:
        holder["out"] = self._per_mode_spectrum(
            live_emitter, eigenvalues, properties, spectra_t, named,
            context=context, sa_period=residual_period,
        )

    modal = self._run_gravity_modal(
        num_modes, p_delta=p_delta, solver=solver, context=context,
        hook=hook, mode_set=mode_set,
    )
    gravity_values, per_mode, labels, drift, inertia, sa_periods = cast(
        "tuple[dict[str, np.ndarray], dict[str, np.ndarray], "
        "dict[str, tuple[str, ...] | None], tuple[float, float], "
        "tuple[np.ndarray, tuple[int, ...], np.ndarray], "
        "np.ndarray | None]",
        holder["out"],
    )
    if not p_delta:
        # The per-mode reference was the unloaded state; the values the
        # gravity combinations need are those of the gravity state.
        ops = modal._live.ops
        gravity_values = {
            name: _evaluate(ex, ops, name, None, context)
            for name, ex in named.items()
        }
    result = SpectrumModalResult(
        modal=modal,
        spectra=spectra_t,
        gravity_values=gravity_values,
        per_mode=per_mode,
        labels=labels,
        restore_drift=drift,
        inertia=inertia[0],
        inertia_nodes=inertia[1],
        inertia_coords=inertia[2],
        sa_periods=sa_periods,
    )
    result.check_inertia_balance(warn=True)
    return result

eigen

eigen(num_modes: int, *, solver: str = '-genBandArpack') -> 'EigenResult'

Build + emit + run a one-shot eigen solve via the live emitter.

Builds a :class:BuiltModel, drives a :class:~apeGmsh.opensees.emitter.live.LiveOpsEmitter end-to- end (model + nodes + elements + bcs + mass), then issues the single eigen call and returns an :class:EigenResult carrying the eigenvalues plus a back-reference to the live emitter for lazy mode-shape access.

Unlike :meth:analyze, eigen does NOT require an analysis chain (constraints / numberer / system / test / algorithm / integrator / analysis): it only needs the assembled stiffness and mass matrices.

Partitioned models — serial-gather stopgap (ADR 0077 Tier 0). On a partition-authored model this runs the eigensolve serially on the full, gathered model in one process (the live emitter has supports_partitions = False): the modes are exact, but the whole model is assembled on one rank, so it does not scale the eigensolve. There is no distributed modal path yet — never run a bare eigen under OpenSeesMP (it solves each rank's LOCAL subdomain → wrong modes; ADR 0077 refuted v1). Distributed FEAST (ADR 0077 Tier 1) is gated on the classic-Tcl -feast unlock.

Parameters

num_modes Number of modes to compute. Must be >= 1. solver OpenSees eigen-solver flag, one of -genBandArpack (default), -symmBandLapack, -fullGenLapack, -frequency, -standard. Passed through verbatim to ops.eigen(solver, num_modes).

Returns

EigenResult Carries eigenvalues (λ_i = ω_i²) plus derived omega / freq / periods and a :meth:EigenResult.mode_shape accessor.

Raises

ValueError If num_modes < 1. NotImplementedError If the model has any registered stages — live execution of staged models is unsupported (Phase SSI-2.A).

Source code in src/apeGmsh/opensees/procedures/_modal.py
def eigen(
    self,
    num_modes: int,
    *,
    solver: str = "-genBandArpack",
) -> "EigenResult":
    """Build + emit + run a one-shot ``eigen`` solve via the live emitter.

    Builds a :class:`BuiltModel`, drives a
    :class:`~apeGmsh.opensees.emitter.live.LiveOpsEmitter` end-to-
    end (model + nodes + elements + bcs + mass), then issues the
    single ``eigen`` call and returns an :class:`EigenResult`
    carrying the eigenvalues plus a back-reference to the live
    emitter for lazy mode-shape access.

    Unlike :meth:`analyze`, ``eigen`` does NOT require an analysis
    chain (constraints / numberer / system / test / algorithm /
    integrator / analysis): it only needs the assembled stiffness
    and mass matrices.

    **Partitioned models — serial-gather stopgap (ADR 0077 Tier 0).**
    On a partition-authored model this runs the eigensolve *serially
    on the full, gathered model* in one process (the live emitter has
    ``supports_partitions = False``): the modes are exact, but the
    whole model is assembled on one rank, so it does **not** scale the
    eigensolve. There is no *distributed* modal path yet — never run a
    bare ``eigen`` under ``OpenSeesMP`` (it solves each rank's LOCAL
    subdomain → wrong modes; ADR 0077 refuted v1). Distributed FEAST
    (ADR 0077 Tier 1) is gated on the classic-Tcl ``-feast`` unlock.

    Parameters
    ----------
    num_modes
        Number of modes to compute. Must be ``>= 1``.
    solver
        OpenSees eigen-solver flag, one of ``-genBandArpack``
        (default), ``-symmBandLapack``, ``-fullGenLapack``,
        ``-frequency``, ``-standard``. Passed through verbatim to
        ``ops.eigen(solver, num_modes)``.

    Returns
    -------
    EigenResult
        Carries ``eigenvalues`` (``λ_i = ω_i²``) plus derived
        ``omega`` / ``freq`` / ``periods`` and a
        :meth:`EigenResult.mode_shape` accessor.

    Raises
    ------
    ValueError
        If ``num_modes < 1``.
    NotImplementedError
        If the model has any registered stages — live execution
        of staged models is unsupported (Phase SSI-2.A).
    """
    if num_modes < 1:
        raise ValueError(
            f"apeSees.eigen: num_modes must be >= 1, got {num_modes}."
        )
    if self._stage_records:
        raise NotImplementedError(
            "apeSees.eigen: live execution does not support staged "
            "models (Phase SSI-2.A) "
            f"(got {len(self._stage_records)} stage(s)).  Eigen "
            "analyses are typically run against an unstaged build; "
            "either drop the stage blocks or emit Tcl/Py and run "
            "the eigen command there."
        )

    # Local imports — keep openseespy + numpy out of bridge import
    # time for Tcl/Py/H5-only users.
    from ..emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe

    bm = self.build()
    self._assert_fork_if_required()
    refuse_fork_chain_before_wipe(bm)
    self._drop_read_session("ops.eigen(...)")
    live_emitter = LiveOpsEmitter(wipe=True)
    bm.emit(live_emitter)
    self._artifacts.after_emit(self)
    values = live_emitter.eigen(num_modes, solver=solver)
    return self._eigen_result(values, live_emitter)

modal_properties

modal_properties(num_modes: int, *, solver: str = '-genBandArpack', unorm: bool = False) -> 'ModalPropertiesResult'

Build + emit + run eigen + modalProperties live.

Like :meth:eigen, drives a :class:~apeGmsh.opensees.emitter.live.LiveOpsEmitter end-to-end and needs no analysis chain; after the eigen solve it issues modalProperties -return (upstream DomainModalProperties) and wraps the returned dict in a :class:~apeGmsh.opensees.analysis.modal.ModalPropertiesResult carrying participation factors, modal masses, and mass ratios per mode and per global component.

The properties are also stored on the OpenSees Domain, which is the prerequisite state for the Ladruno fork's modal-response commands (fork ADR 44).

Partitioned models — serial-gather stopgap (ADR 0077 Tier 0). Runs serially on the full, gathered model (see :meth:eigen), so participation factors / effective modal mass are correct here. This is the only correct way to get modal properties on a partition-authored model today: the distributed path (ADR 0077 Tier 1) has no participation surface — upstream modalProperties is MPI-blind — so a distributed run would return wrong effective mass. It does not scale the eigensolve (whole model on one rank).

Parameters

num_modes Number of modes to compute. Must be >= 1. solver OpenSees eigen-solver flag, passed through verbatim (see :meth:eigen). Use -fullGenLapack on tiny models — ARPACK needs num_modes < n_dof. unorm Request the displacement-normalized eigenvector scaling (modalProperties -unorm).

Raises

ValueError If num_modes < 1. NotImplementedError If the model has any registered stages — live execution of staged models is unsupported (Phase SSI-2.A).

Source code in src/apeGmsh/opensees/procedures/_modal.py
def modal_properties(
    self,
    num_modes: int,
    *,
    solver: str = "-genBandArpack",
    unorm: bool = False,
) -> "ModalPropertiesResult":
    """Build + emit + run ``eigen`` + ``modalProperties`` live.

    Like :meth:`eigen`, drives a
    :class:`~apeGmsh.opensees.emitter.live.LiveOpsEmitter` end-to-end
    and needs no analysis chain; after the eigen solve it issues
    ``modalProperties -return`` (upstream ``DomainModalProperties``)
    and wraps the returned dict in a
    :class:`~apeGmsh.opensees.analysis.modal.ModalPropertiesResult`
    carrying participation factors, modal masses, and mass ratios
    per mode and per global component.

    The properties are also stored on the OpenSees Domain, which is
    the prerequisite state for the Ladruno fork's modal-response
    commands (fork ADR 44).

    **Partitioned models — serial-gather stopgap (ADR 0077 Tier 0).**
    Runs serially on the full, gathered model (see :meth:`eigen`), so
    participation factors / effective modal mass are **correct** here.
    This is the *only* correct way to get modal properties on a
    partition-authored model today: the distributed path (ADR 0077
    Tier 1) has no participation surface — upstream
    ``modalProperties`` is MPI-blind — so a distributed run would
    return wrong effective mass. It does not scale the eigensolve
    (whole model on one rank).

    Parameters
    ----------
    num_modes
        Number of modes to compute. Must be ``>= 1``.
    solver
        OpenSees eigen-solver flag, passed through verbatim (see
        :meth:`eigen`). Use ``-fullGenLapack`` on tiny models —
        ARPACK needs ``num_modes < n_dof``.
    unorm
        Request the displacement-normalized eigenvector scaling
        (``modalProperties -unorm``).

    Raises
    ------
    ValueError
        If ``num_modes < 1``.
    NotImplementedError
        If the model has any registered stages — live execution
        of staged models is unsupported (Phase SSI-2.A).
    """
    if num_modes < 1:
        raise ValueError(
            "apeSees.modal_properties: num_modes must be >= 1, "
            f"got {num_modes}."
        )
    if self._stage_records:
        raise NotImplementedError(
            "apeSees.modal_properties: live execution does not "
            "support staged models (Phase SSI-2.A) "
            f"(got {len(self._stage_records)} stage(s)).  Either "
            "drop the stage blocks or emit Tcl/Py and run the "
            "modalProperties command there."
        )

    # Local imports — keep openseespy + numpy out of bridge import
    # time for Tcl/Py/H5-only users.
    from ..analysis.modal import ModalPropertiesResult
    from ..emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe
    import numpy as np

    bm = self.build()
    self._assert_fork_if_required()
    refuse_fork_chain_before_wipe(bm)
    live_emitter = LiveOpsEmitter(wipe=True)
    bm.emit(live_emitter)
    self._artifacts.after_emit(self)
    values = live_emitter.eigen(num_modes, solver=solver)
    properties = live_emitter.modal_properties(unorm=unorm)
    return ModalPropertiesResult(
        eigenvalues=np.asarray(values, dtype=np.float64),
        properties=properties,
        _live=live_emitter,
        unorm=bool(unorm),
    )

footfall_walking

footfall_walking(*, num_modes: int, body_weight: float, g: float, response_nodes: 'int | Node | Sequence[int | Node]', excitation: str = 'self', excitation_nodes: 'int | Node | Sequence[int | Node] | None' = None, dof: int = 3, occupancy: str = 'office', limit: str = 'curve', damp: float | None = None, modal_damp: Sequence[float] | None = None, rayleigh: tuple[float, float] | None = None, f_max: float = 20.0, n_extra: int = 30, dt: float = 0.005, solver: str = '-genBandArpack') -> 'FootfallResult'

Evaluate walking footfall vibration on a live modal basis.

AISC Design Guide 11, 2nd ed., §7.4.1, as ADR 0109 lays it out: one eigen + modalProperties pair through :meth:modal_properties, the modal acceleration FRF A_ij(Ω) = −Ω² H_ij(Ω) summed in numpy over the D4 sweep grid, and each response node checked against both Design Guide branches — Eq 7-1 where the FRF peaks below 9 Hz (a low-frequency floor, resonant build-up) and Eq 7-4…7-6 where it peaks in 9-f_max Hz (a high-frequency floor, footstep impulses summed over every mode with f_n <= f_max). The larger governs, and the result records which branch it was.

Runs on stock openseespy — eigen, modalProperties and nodeEigenvector are all upstream; the fork is needed only for the band solve the warning below points at.

Units are yours. body_weight (Q, model force units) and g (model acceleration units) are required and have no defaults — apeGmsh cannot know whether the model is in N·m or kip·in, and a silently wrong g is a factor of 386 in the answer. Q = 168 lb ≈ 747 N is the Guide's recommended walker weight. Every acceleration on the result is a fraction of g.

Where to put the nodes. The Guide walks the walker along the mid-length of an unobstructed path and seats the occupant at the maximum mode-shape ordinate; both at mid-bay is the conservative default. excitation="self" checks the diagonal (j, j) — the walker standing where the occupant sits. excitation="full" checks every (i, j) pair and reports, per response node, the excitation node that produced the largest a_p.

The eigenvector scale is asserted, not assumed (ADR 0109 D2): the modal sum takes m̃_a = 1, and partiMass_C / partiFactor_C² must be 1 for every checkable mode or the evaluation refuses. The provenance lands on :attr:FootfallResult.normalization.

Parameters

num_modes Modes to extract. The Eq 7-5 sum wants every mode with f_n <= f_max; a basis that stops short of f_max warns. body_weight Walker weight Q in model force units. Must be > 0. g Gravitational acceleration in model units. Must be > 0. response_nodes Occupant node(s) — a tag, a Node, or a sequence of either. excitation "self" (the diagonal only) or "full" (every pair). excitation_nodes Walker node(s) for excitation="full"; defaults to response_nodes. Refused under "self", where the excitation set IS the response set. dof 1-based DOF the FRF and the mode shapes are read at — the vertical translation, 3 on a 3-D floor. occupancy Tolerance family: "office" / "residence" / "church" / "school" (0.5 %g), "shopping" / "dining" / "indoor_bridge" (1.5 %g), "outdoor_bridge" (5 %g). limit "curve" (Fig 2-1 — the flat value scaled by the ISO 2631-2 base curve) or "table" (the flat Table 4-1 value). damp, modal_damp, rayleigh Exactly one ADR 0075 damping channel (ADR 0109 D6): a uniform ratio (Table 4-2 is a sum of component ratios), a per-mode list in absolute mode order, or (a0, a1) converted per mode as ξ_a = a0/(2ω_a) + a1·ω_a/2. f_max Upper band edge in Hz — also the Eq 7-5 basis cut. Table 7-1's resonant harmonics stop at 20 Hz, so 0 < f_max <= 20. n_extra Linearly spaced sweep points on top of the modal frequencies and their ±5 % clusters (ADR 0109 D4). dt Sampling step of the Eq 7-5 acceleration history, s. solver Eigen-solver flag, passed through verbatim (see :meth:eigen).

Returns

FootfallResult One row per response node — see :class:~apeGmsh.opensees.analysis.footfall_result.FootfallResult.

Warns

UserWarning When the highest extracted mode is below f_max: the Eq 7-5 impulse sum is then missing modes it should carry. Raise num_modes, or on the fork use eigen_feast over the band.

Raises

ValueError If num_modes < 1, body_weight <= 0, g <= 0, dof < 1, a node set is empty, excitation is not "self" / "full", limit is not "curve" / "table", occupancy is unknown, f_max is outside (0, 20], the damping channel is not exactly one, or the eigenvectors are not mass-normalised. NotImplementedError If the model has any registered stages.

Source code in src/apeGmsh/opensees/procedures/_modal.py
def footfall_walking(
    self,
    *,
    num_modes: int,
    body_weight: float,
    g: float,
    response_nodes: "int | Node | Sequence[int | Node]",
    excitation: str = "self",
    excitation_nodes: "int | Node | Sequence[int | Node] | None" = None,
    dof: int = 3,
    occupancy: str = "office",
    limit: str = "curve",
    damp: float | None = None,
    modal_damp: Sequence[float] | None = None,
    rayleigh: tuple[float, float] | None = None,
    f_max: float = 20.0,
    n_extra: int = 30,
    dt: float = 0.005,
    solver: str = "-genBandArpack",
) -> "FootfallResult":
    """Evaluate walking footfall vibration on a live modal basis.

    AISC Design Guide 11, 2nd ed., §7.4.1, as ADR 0109 lays it out: one
    ``eigen`` + ``modalProperties`` pair through :meth:`modal_properties`,
    the modal acceleration FRF ``A_ij(Ω) = −Ω² H_ij(Ω)`` summed in numpy
    over the D4 sweep grid, and each response node checked against
    **both** Design Guide branches — Eq 7-1 where the FRF peaks below
    9 Hz (a low-frequency floor, resonant build-up) and Eq 7-4…7-6 where
    it peaks in 9-``f_max`` Hz (a high-frequency floor, footstep impulses
    summed over every mode with ``f_n <= f_max``). The larger governs,
    and the result records which branch it was.

    Runs on **stock openseespy** — ``eigen``, ``modalProperties`` and
    ``nodeEigenvector`` are all upstream; the fork is needed only for the
    band solve the warning below points at.

    **Units are yours.** ``body_weight`` (``Q``, model force units) and
    ``g`` (model acceleration units) are required and have no defaults —
    apeGmsh cannot know whether the model is in N·m or kip·in, and a
    silently wrong ``g`` is a factor of 386 in the answer. ``Q = 168 lb
    ≈ 747 N`` is the Guide's recommended walker weight. Every
    acceleration on the result is a **fraction of g**.

    **Where to put the nodes.** The Guide walks the walker along the
    mid-length of an unobstructed path and seats the occupant at the
    maximum mode-shape ordinate; both at mid-bay is the conservative
    default. ``excitation="self"`` checks the diagonal ``(j, j)`` — the
    walker standing where the occupant sits. ``excitation="full"``
    checks every ``(i, j)`` pair and reports, per response node, the
    excitation node that produced the largest ``a_p``.

    **The eigenvector scale is asserted, not assumed** (ADR 0109 D2): the
    modal sum takes ``m̃_a = 1``, and ``partiMass_C / partiFactor_C²``
    must be 1 for every checkable mode or the evaluation refuses. The
    provenance lands on :attr:`FootfallResult.normalization`.

    Parameters
    ----------
    num_modes
        Modes to extract. The Eq 7-5 sum wants every mode with
        ``f_n <= f_max``; a basis that stops short of ``f_max`` warns.
    body_weight
        Walker weight ``Q`` in model force units. Must be ``> 0``.
    g
        Gravitational acceleration in model units. Must be ``> 0``.
    response_nodes
        Occupant node(s) — a tag, a ``Node``, or a sequence of either.
    excitation
        ``"self"`` (the diagonal only) or ``"full"`` (every pair).
    excitation_nodes
        Walker node(s) for ``excitation="full"``; defaults to
        ``response_nodes``. Refused under ``"self"``, where the
        excitation set IS the response set.
    dof
        1-based DOF the FRF and the mode shapes are read at — the
        vertical translation, 3 on a 3-D floor.
    occupancy
        Tolerance family: ``"office"`` / ``"residence"`` / ``"church"`` /
        ``"school"`` (0.5 %g), ``"shopping"`` / ``"dining"`` /
        ``"indoor_bridge"`` (1.5 %g), ``"outdoor_bridge"`` (5 %g).
    limit
        ``"curve"`` (Fig 2-1 — the flat value scaled by the ISO 2631-2
        base curve) or ``"table"`` (the flat Table 4-1 value).
    damp, modal_damp, rayleigh
        Exactly one ADR 0075 damping channel (ADR 0109 D6): a uniform
        ratio (Table 4-2 is a sum of component ratios), a per-mode list
        in absolute mode order, or ``(a0, a1)`` converted per mode as
        ``ξ_a = a0/(2ω_a) + a1·ω_a/2``.
    f_max
        Upper band edge in Hz — also the Eq 7-5 basis cut. Table 7-1's
        resonant harmonics stop at 20 Hz, so ``0 < f_max <= 20``.
    n_extra
        Linearly spaced sweep points on top of the modal frequencies and
        their ±5 % clusters (ADR 0109 D4).
    dt
        Sampling step of the Eq 7-5 acceleration history, s.
    solver
        Eigen-solver flag, passed through verbatim (see :meth:`eigen`).

    Returns
    -------
    FootfallResult
        One row per response node — see
        :class:`~apeGmsh.opensees.analysis.footfall_result.FootfallResult`.

    Warns
    -----
    UserWarning
        When the highest extracted mode is below ``f_max``: the Eq 7-5
        impulse sum is then missing modes it should carry. Raise
        ``num_modes``, or on the fork use ``eigen_feast`` over the band.

    Raises
    ------
    ValueError
        If ``num_modes < 1``, ``body_weight <= 0``, ``g <= 0``,
        ``dof < 1``, a node set is empty, ``excitation`` is not
        ``"self"`` / ``"full"``, ``limit`` is not ``"curve"`` /
        ``"table"``, ``occupancy`` is unknown, ``f_max`` is outside
        ``(0, 20]``, the damping channel is not exactly one, or the
        eigenvectors are not mass-normalised.
    NotImplementedError
        If the model has any registered stages.
    """
    # Local imports — keep numpy + the kernel out of bridge import
    # time for Tcl/Py/H5-only users.
    import warnings as _warnings

    import numpy as np

    from ..analysis.footfall import (
        dominant_frequency,
        tolerance_limit,
        walking_high_frequency,
        walking_low_frequency,
    )
    from ..analysis.footfall_frf import frf_matrix, grid_for
    from ..analysis.footfall_result import FootfallModes, FootfallResult
    from ..analysis.modal import _damping_channel_args

    context = "apeSees.footfall_walking"
    self._modal_prereqs_and_guards(num_modes, context=context)
    if body_weight <= 0.0:
        raise ValueError(
            f"{context}: body_weight is the walker's weight Q in model "
            f"force units and must be > 0, got {body_weight}."
        )
    if g <= 0.0:
        raise ValueError(
            f"{context}: g is gravitational acceleration in model units "
            f"and must be > 0, got {g} (386.1 in/s^2, 9.81 m/s^2)."
        )
    if dof < 1:
        raise ValueError(f"{context}: dof is 1-based, got {dof}.")
    excitations = ("self", "full")
    if excitation not in excitations:
        raise ValueError(
            f"{context}: excitation must be one of {excitations}, got "
            f"{excitation!r}."
        )
    limits = ("curve", "table")
    if limit not in limits:
        raise ValueError(
            f"{context}: limit must be one of {limits}, got {limit!r}."
        )
    if not (0.0 < f_max <= 20.0):
        raise ValueError(
            f"{context}: f_max must be in (0, 20] Hz — Table 7-1's "
            f"resonant harmonics stop at 20 Hz — got {f_max}."
        )
    # Probe the occupancy/kind pair now rather than after the solve.
    tolerance_limit(occupancy, 8.0, kind=limit)  # type: ignore[arg-type]
    # The same exactly-one-of rule the FRF matrix applies (ADR 0075),
    # run up front so a bad channel does not cost an eigen solve.
    _damping_channel_args(
        damp=damp, rayleigh=rayleigh, modal_damp=modal_damp,
        context=context,
    )

    resp_tags = self._footfall_tags(
        response_nodes, "response_nodes", context,
    )
    if excitation == "self":
        if excitation_nodes is not None:
            raise ValueError(
                f"{context}: excitation='self' evaluates the diagonal "
                "(j, j), so the excitation set IS response_nodes — pass "
                "excitation='full' to drive a different node set."
            )
        exc_tags = resp_tags
    elif excitation_nodes is None:
        exc_tags = resp_tags
    else:
        exc_tags = self._footfall_tags(
            excitation_nodes, "excitation_nodes", context,
        )

    props = self.modal_properties(num_modes, solver=solver)
    modal_f = np.asarray(props.freq, dtype=np.float64)
    if float(np.max(modal_f)) < f_max:
        _warnings.warn(
            f"{context}: the highest extracted mode is "
            f"{float(np.max(modal_f)):.3f} Hz, below f_max={f_max} Hz — "
            "the Eq 7-5 impulse sum is missing modes it should carry. "
            "Raise num_modes, or on the fork use "
            f"eigen_feast(0.0, {f_max + 2.0}) to get the band exactly.",
            UserWarning,
            stacklevel=2,
        )
    f_min = max(float(np.min(modal_f)) - 1.0, 0.1)
    freq = grid_for(props, f_min, f_max, n_extra)
    matrix = frf_matrix(
        props, exc_nodes=exc_tags, resp_nodes=resp_tags, dof=dof,
        freq=freq, damp=damp, modal_damp=modal_damp, rayleigh=rayleigh,
        unorm=False,
    )
    # Read the mode-shape columns while this domain is still the live
    # one — everything after is pure numpy (the ADR 0075 staleness
    # contract: a later eigen/sweep call wipes what ``props`` reads).
    n_modes = int(matrix.modal_freq.size)
    phi = {
        tag: np.asarray(
            [
                float(props.mode_shape(tag, mode + 1)[dof - 1])
                for mode in range(n_modes)
            ],
            dtype=np.float64,
        )
        for tag in dict.fromkeys((*exc_tags, *resp_tags))
    }

    modal_damping = matrix.modal_damping
    basis = matrix.modal_freq <= f_max
    hf_band = (freq >= 9.0) & (freq <= f_max)
    n_resp = len(resp_tags)
    nan = float("nan")
    out_f_dom = np.full(n_resp, nan)
    out_f_dom_hf = np.full(n_resp, nan)
    out_frf_max = np.full(n_resp, nan)
    out_a_lf = np.full(n_resp, nan)
    out_a_hf = np.full(n_resp, nan)
    out_a_p = np.full(n_resp, nan)
    out_limit = np.full(n_resp, nan)
    out_ratio = np.full(n_resp, nan)
    out_regime = np.empty(n_resp, dtype=object)
    out_exc = np.zeros(n_resp, dtype=np.int64)

    for row, j_tag in enumerate(resp_tags):
        candidates = (j_tag,) if excitation == "self" else exc_tags
        best: "tuple[float, float, float, float, float, float] | None" = None
        best_exc = j_tag
        best_regime = "none"
        for i_tag in candidates:
            mag = matrix.magnitude(i_tag, j_tag)

            f_lf = dominant_frequency(freq, mag, 9.0)
            a_lf = nan
            if np.isfinite(f_lf):
                beta_dom = float(modal_damping[
                    int(np.argmin(np.abs(matrix.modal_freq - f_lf)))
                ])
                a_lf = walking_low_frequency(
                    float(mag[int(np.argmin(np.abs(freq - f_lf)))]),
                    f_lf, beta_dom, body_weight,
                ) / g

            f_hf = nan
            a_hf = nan
            if bool(np.any(hf_band)):
                f_hf = dominant_frequency(
                    freq[hf_band], mag[hf_band], f_max,
                )
            if np.isfinite(f_hf) and bool(np.any(basis)):
                a_espa = walking_high_frequency(
                    matrix.modal_freq[basis], phi[i_tag][basis],
                    phi[j_tag][basis], f_hf, modal_damping[basis],
                    body_weight, dt,
                )[0]
                a_hf = a_espa / g

            if np.isfinite(a_lf) and np.isfinite(a_hf):
                regime = "both"
                a_p = max(a_lf, a_hf)
                f_gov = f_lf if a_lf >= a_hf else f_hf
            elif np.isfinite(a_lf):
                regime, a_p, f_gov = "low", a_lf, f_lf
            elif np.isfinite(a_hf):
                regime, a_p, f_gov = "high", a_hf, f_hf
            else:
                regime, a_p, f_gov = "none", nan, nan

            # Take the candidate unless the incumbent is finite AND
            # at least as large — a NaN incumbent must never win
            # (R-B finding 5: ``a_p > nan`` is False and would pin
            # the first excitation node forever).
            if best is not None and np.isfinite(best[0]) and not (
                np.isfinite(a_p) and a_p > best[0]
            ):
                continue
            frf_at = (
                float(mag[int(np.argmin(np.abs(freq - f_gov)))])
                if np.isfinite(f_gov) else nan
            )
            best = (a_p, a_lf, a_hf, f_gov, f_hf, frf_at)
            best_exc = i_tag
            best_regime = regime

        assert best is not None  # every node has >= 1 candidate
        out_a_p[row] = best[0]
        out_a_lf[row] = best[1]
        out_a_hf[row] = best[2]
        out_f_dom[row] = best[3]
        out_f_dom_hf[row] = best[4]
        out_frf_max[row] = best[5]
        out_regime[row] = best_regime
        out_exc[row] = best_exc
        if np.isfinite(best[3]):
            limit_value = tolerance_limit(
                occupancy, best[3], kind=limit,  # type: ignore[arg-type]
            )
            out_limit[row] = limit_value
            out_ratio[row] = best[0] / limit_value

    # The key the lineage memo holds this model's archive under, taken
    # after the solve: ``ops.h5()`` usually runs after this driver, so
    # the model_hash is resolved from it in ``to_results``.
    from .._internal.artifact_write import lineage_key

    return FootfallResult(
        nodes=resp_tags,
        f_dom=out_f_dom,
        frf_max=out_frf_max,
        a_p_lf=out_a_lf,
        a_espa_hf=out_a_hf,
        a_p=out_a_p,
        regime=out_regime,
        exc_node=out_exc,
        limit=out_limit,
        ratio=out_ratio,
        occupancy=occupancy,
        limit_kind=limit,
        g=float(g),
        body_weight=float(body_weight),
        normalization=matrix.normalization,
        freq=freq,
        modes=FootfallModes(f_n=matrix.modal_freq, beta=modal_damping),
        dof=int(dof),
        dt=float(dt),
        f_max=float(f_max),
        _matrix=matrix,
        _phi=phi,
        _f_dom_hf=out_f_dom_hf,
        _lineage_key=lineage_key(self),
    )

eigen_feast

eigen_feast(f_min: float, f_max: float, *, certify: bool = False, trace_stop: bool = False) -> 'EigenResult'

Band-targeted FEAST eigensolve via the live emitter.

Fork-only (Ladruno ADR-43): eigen -feast fmin fmax returns all modes whose natural frequency lies in [f_min, f_max] Hz — the mode count is an output (len(result.eigenvalues)), not an input, which is why this is a separate method and not an :meth:eigen solver flag.

certify=True adds the fork's Sturm/inertia completeness certificate: the band content is independently counted via LDLᵀ inertia at the two band edges and the solve REFUSES on a mismatch with FEAST's count.

Parameters

f_min, f_max Frequency band in Hz; needs 0 <= f_min < f_max. certify Emit -certify (the completeness certificate). trace_stop Emit -traceStop: stop on MKL's trace criterion instead of the relative residual, the fork's default from c83ee812e (fork WP-203). The eigenpairs are the same either way; the residual stop skips the refinement loops the trace stop runs.

Returns

EigenResult The standard eigen result (possibly zero modes if the band is empty) with lazy mode_shape access. :meth:EigenResult.modal_properties runs modalProperties on its modes.

Source code in src/apeGmsh/opensees/procedures/_modal.py
def eigen_feast(
    self,
    f_min: float,
    f_max: float,
    *,
    certify: bool = False,
    trace_stop: bool = False,
) -> "EigenResult":
    """Band-targeted FEAST eigensolve via the live emitter.

    **Fork-only** (Ladruno ADR-43): ``eigen -feast fmin fmax``
    returns **all** modes whose natural frequency lies in
    ``[f_min, f_max]`` Hz — the mode count is an output
    (``len(result.eigenvalues)``), not an input, which is why this
    is a separate method and not an :meth:`eigen` solver flag.

    ``certify=True`` adds the fork's Sturm/inertia completeness
    certificate: the band content is independently counted via
    LDLᵀ inertia at the two band edges and the solve REFUSES on a
    mismatch with FEAST's count.

    Parameters
    ----------
    f_min, f_max
        Frequency band in Hz; needs ``0 <= f_min < f_max``.
    certify
        Emit ``-certify`` (the completeness certificate).
    trace_stop
        Emit ``-traceStop``: stop on MKL's trace criterion instead of
        the relative residual, the fork's default from ``c83ee812e``
        (fork WP-203). The eigenpairs are the same either way; the
        residual stop skips the refinement loops the trace stop runs.

    Returns
    -------
    EigenResult
        The standard eigen result (possibly zero modes if the band
        is empty) with lazy ``mode_shape`` access.
        :meth:`EigenResult.modal_properties` runs ``modalProperties``
        on its modes.
    """
    if not (0.0 <= f_min < f_max):
        raise ValueError(
            "apeSees.eigen_feast: need 0 <= f_min < f_max, got "
            f"f_min={f_min}, f_max={f_max}."
        )
    if self._stage_records:
        raise NotImplementedError(
            "apeSees.eigen_feast: live execution does not support "
            "staged models (Phase SSI-2.A) "
            f"(got {len(self._stage_records)} stage(s))."
        )
    # The stock ``ops.eigen`` symbol exists on every build, so the
    # missing-attribute gate cannot fire — pre-check the fork probe
    # for the friendly message (a pre-ADR-43 fork build still fails
    # with the OpenSees '-feast' parse error).
    refuse_fork_verb_before_wipe(
        self, "apeSees.eigen_feast",
        "fork ADR-43 band-targeted FEAST eigensolver")

    from ..emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe

    bm = self.build()
    self._assert_fork_if_required()
    refuse_fork_chain_before_wipe(bm)
    self._drop_read_session("ops.eigen_feast(...)")
    live_emitter = LiveOpsEmitter(wipe=True)
    bm.emit(live_emitter)
    self._artifacts.after_emit(self)
    values = live_emitter.eigen_feast(
        float(f_min), float(f_max), certify=certify,
        trace_stop=trace_stop,
    )
    return self._eigen_result(values, live_emitter, feast=True)

complex_eigen

complex_eigen(num_modes: int, *, solver: str = '-genBandArpack', tol: float | None = None, closed_form: bool = False) -> 'ComplexEigenResult'

Complex / state-space modal analysis via the live emitter.

Fork-only (Ladruno ADR-46, complexEigen): true per-mode damping ratios ζ_k, damped frequencies ω_d,k, and phased mode shapes for non-classically damped models (localized dashpots, bearings, radiation damping). Builds + emits a fresh live domain, runs the real eigen (the projection basis), then complexEigen and parses the flat 7-per-mode return into a :class:ComplexEigenResult.

The default route projects the model's actual M and C (element getDamp()/getMass() + nodal mass/alphaM) — exactly the C a transient analysis feels. closed_form=True uses the fast global-Rayleigh diagonal closed form instead (refuses betaKinit/betaKcomm; blind to scoped Rayleigh).

Contract traps (fork guide): damping that does not flow through getDamp() is invisible (modalDamping, HHT-α numerical damping, elements whose -doRayleigh defaults OFF — the Truss/zeroLength families); the projection spans only the retained num_modes real modes; complex mode shapes are recorded via Node-recorder raw=("complexEigenRe<k>",) / Im<k> tokens, not carried on this result.

Parameters

num_modes Real modes to extract as the projection basis (retain enough to cover the band of interest; -fullGenLapack on tiny models). tol Optional residual tolerance (fork default 1e-8). closed_form Use the closed-form Rayleigh route (Route A).

Source code in src/apeGmsh/opensees/procedures/_modal.py
def complex_eigen(
    self,
    num_modes: int,
    *,
    solver: str = "-genBandArpack",
    tol: float | None = None,
    closed_form: bool = False,
) -> "ComplexEigenResult":
    """Complex / state-space modal analysis via the live emitter.

    **Fork-only** (Ladruno ADR-46, ``complexEigen``): true per-mode
    damping ratios ζ_k, damped frequencies ω_d,k, and phased mode
    shapes for **non-classically damped** models (localized
    dashpots, bearings, radiation damping).  Builds + emits a fresh
    live domain, runs the real ``eigen`` (the projection basis),
    then ``complexEigen`` and parses the flat 7-per-mode return
    into a :class:`ComplexEigenResult`.

    The default route projects the model's **actual** M and C
    (element ``getDamp()``/``getMass()`` + nodal mass/``alphaM``) —
    exactly the C a transient analysis feels.  ``closed_form=True``
    uses the fast global-Rayleigh diagonal closed form instead
    (refuses ``betaKinit``/``betaKcomm``; blind to scoped
    Rayleigh).

    Contract traps (fork guide): damping that does not flow through
    ``getDamp()`` is invisible (``modalDamping``, HHT-α numerical
    damping, elements whose ``-doRayleigh`` defaults OFF — the
    ``Truss``/``zeroLength`` families); the projection spans only
    the retained ``num_modes`` real modes; complex mode shapes are
    recorded via Node-recorder ``raw=("complexEigenRe<k>",)`` /
    ``Im<k>`` tokens, not carried on this result.

    Parameters
    ----------
    num_modes
        Real modes to extract as the projection basis (retain
        enough to cover the band of interest;
        ``-fullGenLapack`` on tiny models).
    tol
        Optional residual tolerance (fork default 1e-8).
    closed_form
        Use the closed-form Rayleigh route (Route A).
    """
    context = "apeSees.complex_eigen"
    self._modal_prereqs_and_guards(num_modes, context=context)
    # Fork guide trap #4: the eigenvector distribution to
    # MP-constrained slave DOFs needs a distributing constraint
    # handler — ``constraints Plain`` + MP constraints yields wrong
    # complex shapes. The bridge-driven eigen path defaults to
    # Transformation when no handler is declared; warn when the
    # user declared Plain.
    from ..analysis.constraint_handler import Plain as _PlainHandler

    if any(isinstance(p, _PlainHandler) for p in self._primitives):
        import warnings

        warnings.warn(
            f"{context}: 'constraints Plain' is declared — on a "
            "model with MP constraints (rigid links, equalDOF, "
            "embedded, ...) complexEigen mode shapes need a "
            "distributing handler (Transformation).",
            UserWarning,
            stacklevel=2,
        )

    from ..analysis.complex_eigen import ComplexEigenResult
    from ..emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe

    args: list[int | float | str] = []
    if tol is not None:
        if tol <= 0.0:
            raise ValueError(
                f"{context}: tol must be > 0, got {tol}."
            )
        args.extend(("-tol", float(tol)))
    if closed_form:
        args.append("-closedForm")

    refuse_fork_verb_before_wipe(
        self, context, "fork ADR-46 complexEigen")
    bm = self.build()
    self._assert_fork_if_required()
    refuse_fork_chain_before_wipe(bm)
    live_emitter = LiveOpsEmitter(wipe=True)
    bm.emit(live_emitter)
    self._artifacts.after_emit(self)
    live_emitter.eigen(num_modes, solver=solver)
    values = live_emitter.complex_eigen(*args)
    return ComplexEigenResult.from_flat(values)

modal_response_history

modal_response_history(*, dt: float, n_steps: int, num_modes: int, base_accel: 'TimeSeries | str | None' = None, direction: int | None = None, load: 'Plain | str | None' = None, series: 'TimeSeries | str | None' = None, damp: float | None = None, rayleigh: tuple[float, float] | None = None, modal_damp: Sequence[float] | None = None, modes: Sequence[int] | None = None, t0: float = 0.0, solver: str = '-genBandArpack') -> 'ModalHistoryResult'

Run the fork's exact modal-superposition transient live.

Fork-only (Ladruno ADR-44 P1a, modalResponseHistory). Builds + emits a fresh live domain, issues eigen + modalProperties, then advances each retained mode by the closed-form piecewise-linear recurrence — no iteration, no factorization. One domain step is committed per station (t0 … t0 + n_steps·dt), so every recorder declared on the model captures the history exactly as in a direct run.

Linear models only — superposition is invalid under any material or geometric nonlinearity (use analyze then).

Parameters

dt, n_steps Time step and station count (n_steps + 1 commits). num_modes Modes to extract for the superposition basis (retain enough to cover the band of interest). base_accel, direction Ground-acceleration channel: a registered ops.timeSeries.* handle (or name) sampled at the stations, plus the global excitation direction (1-based). Response is relative to the moving base. Make the record extend at least one sample past t0 + n_steps·dt. load, series Nodal-force channel P(t) = s(t)·P: an ops.pattern.Plain handle (or name) whose plain nodal loads give the reference shape P (the pattern's own timeSeries is IGNORED by the fork), and the scalar s(t) timeSeries. Response is absolute. Mutually exclusive with the base-acceleration channel. damp, rayleigh, modal_damp Exactly one damping channel (ADR 0075): uniform ratio / Rayleigh (a0, a1) / per-mode ratios. modes Optional 1-based subset of the extracted modes. t0 Start time (base accel sampled at t0 + k·dt). solver Eigen-solver flag (-fullGenLapack on tiny models).

Source code in src/apeGmsh/opensees/procedures/_modal.py
def modal_response_history(
    self,
    *,
    dt: float,
    n_steps: int,
    num_modes: int,
    base_accel: "TimeSeries | str | None" = None,
    direction: int | None = None,
    load: "Plain | str | None" = None,
    series: "TimeSeries | str | None" = None,
    damp: float | None = None,
    rayleigh: tuple[float, float] | None = None,
    modal_damp: Sequence[float] | None = None,
    modes: Sequence[int] | None = None,
    t0: float = 0.0,
    solver: str = "-genBandArpack",
) -> "ModalHistoryResult":
    """Run the fork's exact modal-superposition transient live.

    **Fork-only** (Ladruno ADR-44 P1a, ``modalResponseHistory``).
    Builds + emits a fresh live domain, issues ``eigen`` +
    ``modalProperties``, then advances each retained mode by the
    closed-form piecewise-linear recurrence — no iteration, no
    factorization.  One domain step is **committed per station**
    (``t0 … t0 + n_steps·dt``), so every recorder declared on the
    model captures the history exactly as in a direct run.

    Linear models only — superposition is invalid under any
    material or geometric nonlinearity (use ``analyze`` then).

    Parameters
    ----------
    dt, n_steps
        Time step and station count (``n_steps + 1`` commits).
    num_modes
        Modes to extract for the superposition basis (retain
        enough to cover the band of interest).
    base_accel, direction
        Ground-acceleration channel: a registered
        ``ops.timeSeries.*`` handle (or name) sampled at the
        stations, plus the global excitation direction (1-based).
        Response is **relative** to the moving base.  Make the
        record extend at least one sample past ``t0 + n_steps·dt``.
    load, series
        Nodal-force channel ``P(t) = s(t)·P``: an
        ``ops.pattern.Plain`` handle (or name) whose plain nodal
        loads give the reference shape ``P`` (the pattern's own
        timeSeries is IGNORED by the fork), and the scalar
        ``s(t)`` timeSeries.  Response is **absolute**.  Mutually
        exclusive with the base-acceleration channel.
    damp, rayleigh, modal_damp
        Exactly one damping channel (ADR 0075): uniform ratio /
        Rayleigh ``(a0, a1)`` / per-mode ratios.
    modes
        Optional 1-based subset of the extracted modes.
    t0
        Start time (base accel sampled at ``t0 + k·dt``).
    solver
        Eigen-solver flag (``-fullGenLapack`` on tiny models).
    """
    from ..analysis.modal import (
        ModalHistoryResult,
        _damping_channel_args,
    )
    from ..emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe
    from ..pattern.pattern import Plain as _Plain
    import numpy as np

    context = "apeSees.modal_response_history"
    self._modal_prereqs_and_guards(num_modes, context=context)
    if dt <= 0.0 or n_steps < 1:
        raise ValueError(
            f"{context}: dt must be > 0 and n_steps >= 1, got "
            f"dt={dt}, n_steps={n_steps}."
        )
    damping_args = _damping_channel_args(
        damp=damp, rayleigh=rayleigh, modal_damp=modal_damp,
        context=context,
    )
    excitation = self._resolve_modal_excitation(
        base_accel=base_accel, direction=direction,
        load=load, series=series, context=context,
        plain_cls=_Plain, series_required=True,
    )

    args: list[int | float | str] = [
        "-dt", float(dt), "-nsteps", int(n_steps),
    ]
    if t0 != 0.0:
        args.extend(("-t0", float(t0)))
    args.extend(excitation)
    args.extend(damping_args)
    if modes is not None:
        mode_list = [int(m) for m in modes]
        if not mode_list or any(m < 1 for m in mode_list):
            raise ValueError(
                f"{context}: modes must be 1-based mode numbers, "
                f"got {modes!r}."
            )
        args.extend(("-modes", *mode_list))

    refuse_fork_verb_before_wipe(
        self, context, "fork ADR-44 modalResponseHistory")
    bm = self.build()
    self._assert_fork_if_required()
    refuse_fork_chain_before_wipe(bm)
    live_emitter = LiveOpsEmitter(wipe=True)
    bm.emit(live_emitter)
    self._artifacts.after_emit(self)
    values = live_emitter.eigen(num_modes, solver=solver)
    live_emitter.modal_properties()
    live_emitter.modal_response_history(*args)
    return ModalHistoryResult(
        eigenvalues=np.asarray(values, dtype=np.float64),
        dt=float(dt),
        n_steps=int(n_steps),
        _live=live_emitter,
    )

response_spectrum_analysis

response_spectrum_analysis(direction: int, *, periods: Sequence[float], accels: Sequence[float], combine: str, num_modes: int, damp: float | None = None, modal_damp: Sequence[float] | None = None, solver: str = '-genBandArpack', scale: float | None = None, require_mass: float | None = None) -> 'ResponseSpectrumResult'

Run a response-spectrum analysis with native combination.

Fork-only (Ladruno ADR-44 P1b): the -combine stage on responseSpectrumAnalysis. Builds + emits a fresh live domain, issues eigen + modalProperties, computes the per-mode modal displacements against the (periods, accels) design spectrum, and commits the combined nodal design displacement field, read back via :meth:ResponseSpectrumResult.node_disp.

Combination is per-quantity and nonlinear — do NOT derive combined element forces / drifts from the combined displacements (combine those quantities' own per-mode peaks instead).

Displacements only. The committed field is the combined nodal displacement; element forces, drifts and storey shears read off that domain are not combined responses. For those use :meth:spectrum_after_gravity, which combines each quantity's signed per-mode values.

Parameters

direction Global excitation direction (1-based). periods, accels The design spectrum Sa(Tn) as parallel lists. periods must be non-negative and strictly increasing; a leading T = 0 PGA anchor is legal (the fork clamps T <= Tn[0] to Sa[0]). combine "SRSS" | "CQC" | "ABS" | "TenPercent". CQC and TenPercent weight closely-spaced modes; CQC requires a damping channel. num_modes Modes to extract; the combination spans all of them (-combine and -mode are mutually exclusive — the bridge never emits -mode). damp, modal_damp Optional damping channel (uniform ratio or per-mode). Required for CQC. scale Optional factor on Sa (a unit conversion such as g to model units, or an I/R factor). Must be finite and > 0; None is scale 1. The bridge multiplies the -Sa values by it and does not emit the fork's -scale, which only builds from c83ee812e (fork WP-202) apply under -combine and older ones parse and ignore: the scaled ordinates give the same answer on every build. require_mass Optional ratio in (0, 1]: -requireMass (fork WP-212). The fork refuses the analysis when the modes carry less than this fraction of the free mass in direction, and prints the shortfall. None (the default) emits nothing. Needs chain M (ladruno-v20261027+); an older build refuses before the model is built (:class:~apeGmsh.opensees._target.ForkTooOldError).

Source code in src/apeGmsh/opensees/procedures/_modal.py
def response_spectrum_analysis(
    self,
    direction: int,
    *,
    periods: Sequence[float],
    accels: Sequence[float],
    combine: str,
    num_modes: int,
    damp: float | None = None,
    modal_damp: Sequence[float] | None = None,
    solver: str = "-genBandArpack",
    scale: float | None = None,
    require_mass: float | None = None,
) -> "ResponseSpectrumResult":
    """Run a response-spectrum analysis with native combination.

    **Fork-only** (Ladruno ADR-44 P1b): the ``-combine`` stage on
    ``responseSpectrumAnalysis``.  Builds + emits a fresh live
    domain, issues ``eigen`` + ``modalProperties``, computes the
    per-mode modal displacements against the ``(periods, accels)``
    design spectrum, and commits the **combined** nodal design
    displacement field, read back via
    :meth:`ResponseSpectrumResult.node_disp`.

    Combination is per-quantity and nonlinear — do NOT derive
    combined element forces / drifts from the combined
    displacements (combine those quantities' own per-mode peaks
    instead).

    **Displacements only.** The committed field is the combined
    nodal displacement; element forces, drifts and storey shears
    read off that domain are not combined responses. For those use
    :meth:`spectrum_after_gravity`, which combines each quantity's
    signed per-mode values.

    Parameters
    ----------
    direction
        Global excitation direction (1-based).
    periods, accels
        The design spectrum ``Sa(Tn)`` as parallel lists.
        ``periods`` must be non-negative and strictly increasing;
        a leading ``T = 0`` PGA anchor is legal (the fork clamps
        ``T <= Tn[0]`` to ``Sa[0]``).
    combine
        ``"SRSS"`` | ``"CQC"`` | ``"ABS"`` | ``"TenPercent"``.
        CQC and TenPercent weight closely-spaced modes; CQC
        requires a damping channel.
    num_modes
        Modes to extract; the combination spans all of them
        (``-combine`` and ``-mode`` are mutually exclusive — the
        bridge never emits ``-mode``).
    damp, modal_damp
        Optional damping channel (uniform ratio or per-mode).
        Required for ``CQC``.
    scale
        Optional factor on ``Sa`` (a unit conversion such as g to
        model units, or an ``I/R`` factor). Must be finite and > 0;
        ``None`` is scale 1. The bridge multiplies the ``-Sa`` values
        by it and does not emit the fork's ``-scale``, which only
        builds from ``c83ee812e`` (fork WP-202) apply under
        ``-combine`` and older ones parse and ignore: the scaled
        ordinates give the same answer on every build.
    require_mass
        Optional ratio in ``(0, 1]``: ``-requireMass`` (fork WP-212).
        The fork refuses the analysis when the modes carry less than
        this fraction of the free mass in ``direction``, and prints
        the shortfall. ``None`` (the default) emits nothing. Needs
        chain M (``ladruno-v20261027+``); an older build refuses
        before the model is built
        (:class:`~apeGmsh.opensees._target.ForkTooOldError`).
    """
    from .._target import require_rsa_feature
    from ..analysis.modal import (
        ResponseSpectrumResult,
        _damping_channel_args,
    )
    from ..emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe
    import numpy as np

    context = "apeSees.response_spectrum_analysis"
    self._modal_prereqs_and_guards(num_modes, context=context)
    if int(direction) < 1:
        raise ValueError(
            f"{context}: direction is 1-based, got {direction}."
        )
    rules = ("SRSS", "CQC", "ABS", "TenPercent")
    if combine not in rules:
        raise ValueError(
            f"{context}: combine must be one of {rules}, got "
            f"{combine!r}."
        )
    tn = [float(t) for t in periods]
    sa = [float(a) for a in accels]
    if len(tn) != len(sa) or not tn:
        raise ValueError(
            f"{context}: periods and accels must be equal-length "
            f"non-empty lists, got {len(tn)} periods / {len(sa)} "
            "accels."
        )
    if any(t < 0.0 for t in tn) or any(
        b <= a for a, b in zip(tn, tn[1:])
    ):
        raise ValueError(
            f"{context}: periods must be non-negative and strictly "
            "increasing (the fork refuses negative Tn; a leading "
            "T=0 PGA anchor is legal)."
        )
    if combine == "CQC" and damp is None and modal_damp is None:
        raise ValueError(
            f"{context}: CQC needs a damping channel — pass damp= "
            "or modal_damp=."
        )
    damping_args: tuple[float | str, ...] = ()
    if damp is not None or modal_damp is not None:
        damping_args = _damping_channel_args(
            damp=damp, rayleigh=None, modal_damp=modal_damp,
            context=context,
        )

    if scale is not None:
        s_val = float(scale)
        if not (math.isfinite(s_val) and s_val > 0.0):
            raise ValueError(
                f"{context}: scale must be finite and > 0, got {scale!r}."
            )
        sa = [a * s_val for a in sa]

    args: list[int | float | str] = ["-Tn", *tn, "-Sa", *sa]
    args.extend(("-combine", combine))
    args.extend(damping_args)
    if require_mass is not None:
        r_val = float(require_mass)
        if not 0.0 < r_val <= 1.0:
            raise ValueError(
                f"{context}: require_mass must be in (0, 1], got "
                f"{require_mass!r}."
            )
        require_rsa_feature("responseSpectrumAnalysis -requireMass")
        args.extend(("-requireMass", r_val))

    refuse_fork_verb_before_wipe(
        self, context,
        "fork ADR-44 responseSpectrumAnalysis -combine")
    bm = self.build()
    self._assert_fork_if_required()
    refuse_fork_chain_before_wipe(bm)
    live_emitter = LiveOpsEmitter(wipe=True)
    bm.emit(live_emitter)
    self._artifacts.after_emit(self)
    values = live_emitter.eigen(num_modes, solver=solver)
    live_emitter.modal_properties()
    live_emitter.response_spectrum_analysis(int(direction), *args)
    return ResponseSpectrumResult(
        eigenvalues=np.asarray(values, dtype=np.float64),
        combine=combine,
        _live=live_emitter,
    )

residual_modes

residual_modes(dirs: Sequence[int], *, num_modes: int, period: float | str = 'rayleigh', replace: bool = False, tol: float | None = None, solver: str = '-genBandArpack') -> 'ModalPropertiesResult'

Eigenmodes completed by the fork's missing-mass pseudo-modes, live.

Fork-only (chain M, WP-213). Builds and emits a fresh live domain, then runs eigen (num_modes modes), residualModes -dir ... (:class:~apeGmsh.opensees.analysis. modal.ResidualModes) and modalProperties -return, in that order: a later eigen would drop the pseudo-modes. The result holds every mode of the completed set, the pseudo-modes last, with the cumulative mass ratio of each direction in dirs at 100 %.

Parameters

dirs Global translations (1, 2, 3) to complete, each once. num_modes Eigenmodes solved before the pseudo-modes are appended. period "rayleigh" (default): spectral analyses read each pseudo-mode's Sa at its own Rayleigh period. A period T (s): responseSpectrumAnalysis reads Sa at T and sums the pseudo-modes into one rigid mode (ADR 213 D3b, ASCE 7-22 §12.9.1.1). replace -replace: drop pseudo-modes already in the set first. tol -tol, the relative drop tolerance in (0, 1); None keeps the fork's default (1e-4). solver The eigen-solver flag (see :meth:eigen).

Raises

BridgeError The model runs under MPI (a partitioned model or an MPI system): the fork refuses residualModes on OpenSeesSP, so the bridge refuses before emitting. ForkTooOldError The in-process build lacks residualModes; raised before the model is built.

Source code in src/apeGmsh/opensees/procedures/_modal.py
def residual_modes(
    self,
    dirs: Sequence[int],
    *,
    num_modes: int,
    period: float | str = "rayleigh",
    replace: bool = False,
    tol: float | None = None,
    solver: str = "-genBandArpack",
) -> "ModalPropertiesResult":
    """Eigenmodes completed by the fork's missing-mass pseudo-modes, live.

    **Fork-only** (chain M, WP-213). Builds and emits a fresh live
    domain, then runs ``eigen`` (``num_modes`` modes),
    ``residualModes -dir ...`` (:class:`~apeGmsh.opensees.analysis.
    modal.ResidualModes`) and ``modalProperties -return``, in that
    order: a later ``eigen`` would drop the pseudo-modes. The result
    holds every mode of the completed set, the pseudo-modes last,
    with the cumulative mass ratio of each direction in ``dirs`` at
    100 %.

    Parameters
    ----------
    dirs
        Global translations (1, 2, 3) to complete, each once.
    num_modes
        Eigenmodes solved before the pseudo-modes are appended.
    period
        ``"rayleigh"`` (default): spectral analyses read each
        pseudo-mode's Sa at its own Rayleigh period. A period ``T``
        (s): ``responseSpectrumAnalysis`` reads Sa at ``T`` and sums
        the pseudo-modes into one rigid mode (ADR 213 D3b, ASCE 7-22
        §12.9.1.1).
    replace
        ``-replace``: drop pseudo-modes already in the set first.
    tol
        ``-tol``, the relative drop tolerance in ``(0, 1)``; ``None``
        keeps the fork's default (``1e-4``).
    solver
        The eigen-solver flag (see :meth:`eigen`).

    Raises
    ------
    BridgeError
        The model runs under MPI (a partitioned model or an MPI
        ``system``): the fork refuses ``residualModes`` on OpenSeesSP,
        so the bridge refuses before emitting.
    ForkTooOldError
        The in-process build lacks ``residualModes``; raised before
        the model is built.
    """
    from .._target import require_rsa_feature
    from ..analysis.modal import ModalPropertiesResult, ResidualModes
    from ..emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe
    import numpy as np

    context = "apeSees.residual_modes"
    self._modal_prereqs_and_guards(num_modes, context=context)
    self._refuse_mpi_modal_basis(context, "residualModes")
    record = ResidualModes(
        dirs=tuple(dirs), period=period, replace=replace, tol=tol)
    require_rsa_feature("residualModes")

    bm = self.build()
    self._assert_fork_if_required()
    refuse_fork_chain_before_wipe(bm)
    live_emitter = LiveOpsEmitter(wipe=True)
    bm.emit(live_emitter)
    self._artifacts.after_emit(self)
    live_emitter.eigen(num_modes, solver=solver)
    record._emit(live_emitter, 0)
    properties = live_emitter.modal_properties()
    return ModalPropertiesResult(
        eigenvalues=np.asarray(properties["eigenLambda"], dtype=np.float64),
        properties=properties,
        _live=live_emitter,
    )

ritz_vectors

ritz_vectors(n: int, *, dirs: Sequence[int] = (), patterns: 'Sequence[Plain | str]' = (), cycles: Sequence[int] | None = None, tol: float | None = None) -> 'ModalPropertiesResult'

Load-dependent Ritz vectors as the mode set, live.

Fork-only (chain M, WP-215). Builds and emits a fresh live domain, then runs ritzVectors (:class:~apeGmsh.opensees. analysis.modal.RitzVectors) in place of eigen and modalProperties -return. Ritz periods are Rayleigh periods, not natural periods.

The starting loads are M ι_d for each direction in dirs, then the reference loads of each pattern in patterns, in that order. The fork factors K through the defined analysis, so the bridge must declare one (ops.analysis.Static() and its chain).

Parameters

n Ritz vectors to generate (>= 1). dirs Global translations (1, 2, 3) whose inertia loads start the sequence. patterns ops.pattern.Plain handles (or registered names) whose reference loads start the sequence. cycles Blocks per start, one count per start (dirs then patterns); 0 is no cap. tol -tol, the relative M-norm drop in (0, 1); None keeps the fork's default (1e-10).

Raises

BridgeError The model runs under MPI (a partitioned model or an MPI system): the fork refuses ritzVectors on OpenSeesSP, so the bridge refuses before emitting. Also when no analysis is declared. ForkTooOldError The in-process build lacks ritzVectors; raised before the model is built.

Source code in src/apeGmsh/opensees/procedures/_modal.py
def ritz_vectors(
    self,
    n: int,
    *,
    dirs: Sequence[int] = (),
    patterns: "Sequence[Plain | str]" = (),
    cycles: Sequence[int] | None = None,
    tol: float | None = None,
) -> "ModalPropertiesResult":
    """Load-dependent Ritz vectors as the mode set, live.

    **Fork-only** (chain M, WP-215). Builds and emits a fresh live
    domain, then runs ``ritzVectors`` (:class:`~apeGmsh.opensees.
    analysis.modal.RitzVectors`) in place of ``eigen`` and
    ``modalProperties -return``. Ritz periods are Rayleigh periods,
    not natural periods.

    The starting loads are ``M ι_d`` for each direction in ``dirs``,
    then the reference loads of each pattern in ``patterns``, in
    that order. The fork factors ``K`` through the defined analysis,
    so the bridge must declare one (``ops.analysis.Static()`` and its
    chain).

    Parameters
    ----------
    n
        Ritz vectors to generate (``>= 1``).
    dirs
        Global translations (1, 2, 3) whose inertia loads start the
        sequence.
    patterns
        ``ops.pattern.Plain`` handles (or registered names) whose
        reference loads start the sequence.
    cycles
        Blocks per start, one count per start (``dirs`` then
        ``patterns``); ``0`` is no cap.
    tol
        ``-tol``, the relative M-norm drop in ``(0, 1)``; ``None``
        keeps the fork's default (``1e-10``).

    Raises
    ------
    BridgeError
        The model runs under MPI (a partitioned model or an MPI
        ``system``): the fork refuses ``ritzVectors`` on OpenSeesSP,
        so the bridge refuses before emitting. Also when no analysis
        is declared.
    ForkTooOldError
        The in-process build lacks ``ritzVectors``; raised before
        the model is built.
    """
    from .._internal.types import Analysis
    from .._target import require_rsa_feature
    from ..analysis.modal import ModalPropertiesResult, RitzVectors
    from ..emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe
    from ..pattern.pattern import Plain as _Plain
    import numpy as np

    context = "apeSees.ritz_vectors"
    self._modal_prereqs_and_guards(1, context=context)
    self._refuse_mpi_modal_basis(context, "ritzVectors")
    if not any(isinstance(p, Analysis) for p in self._primitives):
        raise BridgeError(
            f"{context}: the fork factors K through the defined "
            "analysis; declare one first (ops.analysis.Static() with "
            "its chain)."
        )
    pattern_tags: list[int] = []
    for handle in patterns:
        pat = self._resolve(handle, base=_Plain)
        tag = self.tag_for(pat) if isinstance(pat, _Plain) else None
        if tag is None:
            raise BridgeError(
                f"{context}: patterns takes ops.pattern.Plain handles "
                f"(or registered names) on this bridge, got {handle!r}."
            )
        pattern_tags.append(int(tag))
    record = RitzVectors(
        n=n, dirs=tuple(dirs), patterns=tuple(pattern_tags),
        cycles=None if cycles is None else tuple(cycles), tol=tol)
    require_rsa_feature("ritzVectors")

    bm = self.build()
    self._assert_fork_if_required()
    refuse_fork_chain_before_wipe(bm)
    live_emitter = LiveOpsEmitter(wipe=True)
    bm.emit(live_emitter)
    self._artifacts.after_emit(self)
    record._emit(live_emitter, 0)
    properties = live_emitter.modal_properties()
    return ModalPropertiesResult(
        eigenvalues=np.asarray(properties["eigenLambda"], dtype=np.float64),
        properties=properties,
        _live=live_emitter,
    )

ladruno_contact_force

ladruno_contact_force(node: int) -> float

Total normal contact-force magnitude on an NTS slave node.

The sum over that node's active master-segment pairs of tn = kn·<−gap>₊ (fork ladrunoContactForce, ADR-39 B3). Works in 2-D and 3-D. Requires a prior live :meth:analyze; fork-only.

Four limits, none of which the return value can tell you about — read them before using this number:

  • NTS lane only. It is fed exclusively from the segment / end-cap branch, so a mortar or rigid-plane slave always reads 0.0. Those lanes have no force query at all; recover their forces from reactions or the penalty-depth identity instead.
  • A magnitude, not a vector. Near a corner or the 2-D D4 end-cap the pair normal is not axis-aligned, so this does not equal any single global force component. The fork's own guide says so.
  • Zero is ambiguous. 0.0 means "not in contact" and "no contact engine in this domain". Call :meth:ladruno_contact_info and check total_contacts to tell them apart — not n_contacts, which counts the NTS lane only and reads 0 on a perfectly live mortar-only model.
  • A released 3-D pair reports its last-active force forever — a known, deferred fork defect (reproduced at f_query = 1000.0 against f_true = 0.0). The 2-D lane carries the fix.
Source code in src/apeGmsh/opensees/procedures/_contact.py
def ladruno_contact_force(self, node: int) -> float:
    """Total normal contact-force **magnitude** on an NTS slave node.

    The sum over that node's active master-segment pairs of
    ``tn = kn·<−gap>₊`` (fork ``ladrunoContactForce``, ADR-39 B3). Works in
    2-D and 3-D. Requires a prior **live** :meth:`analyze`; fork-only.

    Four limits, none of which the return value can tell you about — read
    them before using this number:

    * **NTS lane only.** It is fed exclusively from the segment / end-cap
      branch, so a **mortar** or **rigid-plane** slave always reads
      ``0.0``. Those lanes have no force query at all; recover their forces
      from reactions or the penalty-depth identity instead.
    * **A magnitude, not a vector.** Near a corner or the 2-D D4 end-cap
      the pair normal is not axis-aligned, so this does **not** equal any
      single global force component. The fork's own guide says so.
    * **Zero is ambiguous.** ``0.0`` means "not in contact" *and* "no
      contact engine in this domain". Call :meth:`ladruno_contact_info`
      and check ``total_contacts`` to tell them apart — **not**
      ``n_contacts``, which counts the NTS lane only and reads ``0`` on a
      perfectly live mortar-only model.
    * **A released 3-D pair reports its last-active force forever** — a
      known, deferred fork defect (reproduced at ``f_query = 1000.0``
      against ``f_true = 0.0``). The 2-D lane carries the fix.
    """
    return self._require_live_for_contact_query(
        "ladruno_contact_force").ladruno_contact_force(node)

ladruno_contact_info

ladruno_contact_info() -> 'ContactInfo'

Engine counters — (n_contacts, n_commits, n_reverts, n_mortar_contacts) (fork ladrunoContactInfo).

Mostly useful as the disambiguator for the other three queries: they all return 0.0 both for "nothing happening here" and for "no contact engine at all". Use info.total_contacts, the sum of the two lane counters — n_contacts and n_mortar_contacts are disjoint lanes, not a total and a subset, so a mortar-only model reports n_contacts == 0 with a live engine (measured on fork b17e8bd82). Requires a prior live :meth:analyze; fork-only.

Source code in src/apeGmsh/opensees/procedures/_contact.py
def ladruno_contact_info(self) -> "ContactInfo":
    """Engine counters — ``(n_contacts, n_commits, n_reverts,
    n_mortar_contacts)`` (fork ``ladrunoContactInfo``).

    Mostly useful as the disambiguator for the other three queries: they
    all return ``0.0`` both for "nothing happening here" and for "no
    contact engine at all". Use ``info.total_contacts``, the sum of the two
    lane counters — ``n_contacts`` and ``n_mortar_contacts`` are **disjoint
    lanes**, not a total and a subset, so a mortar-only model reports
    ``n_contacts == 0`` with a live engine (measured on fork
    ``b17e8bd82``). Requires a prior live :meth:`analyze`; fork-only.
    """
    return self._require_live_for_contact_query(
        "ladruno_contact_info").ladruno_contact_info()

ladruno_mortar_penetration

ladruno_mortar_penetration() -> float

Max KKT-active normal penetration over all mortar slave nodes (fork ladrunoMortarPenetration, ADR-41 C2.2).

A length, not a force — dimension-blind, and unaffected by the mortar thickness=. It is the mortar lane's ALM convergence measure: the quantity a held-load augmentation loop watches to decide it has augmented enough. 0.0 with no mortar contact. Requires a prior live :meth:analyze; fork-only.

Source code in src/apeGmsh/opensees/procedures/_contact.py
def ladruno_mortar_penetration(self) -> float:
    """Max KKT-active normal penetration over all mortar slave nodes
    (fork ``ladrunoMortarPenetration``, ADR-41 C2.2).

    A **length**, not a force — dimension-blind, and unaffected by the
    mortar ``thickness=``. It is the mortar lane's ALM convergence measure:
    the quantity a held-load augmentation loop watches to decide it has
    augmented enough. ``0.0`` with no mortar contact. Requires a prior live
    :meth:`analyze`; fork-only.
    """
    return self._require_live_for_contact_query(
        "ladruno_mortar_penetration").ladruno_mortar_penetration()

ladruno_mortar_tie_residual

ladruno_mortar_tie_residual() -> float

Max weighted relative-displacement bond residual over all mortar tie slave nodes (fork ladrunoMortarTieResidual, ADR-41 C4).

The tie's ALM convergence measure, the counterpart of :meth:ladruno_mortar_penetration for tie=True. 0.0 with no tie declared. Requires a prior live :meth:analyze; fork-only.

Source code in src/apeGmsh/opensees/procedures/_contact.py
def ladruno_mortar_tie_residual(self) -> float:
    """Max weighted relative-displacement bond residual over all mortar
    **tie** slave nodes (fork ``ladrunoMortarTieResidual``, ADR-41 C4).

    The tie's ALM convergence measure, the counterpart of
    :meth:`ladruno_mortar_penetration` for ``tie=True``. ``0.0`` with no
    tie declared. Requires a prior live :meth:`analyze`; fork-only.
    """
    return self._require_live_for_contact_query(
        "ladruno_mortar_tie_residual").ladruno_mortar_tie_residual()

capabilities

capabilities() -> 'OpenSeesCapabilities'

Probe the in-process openseespy build (live path).

Imports openseespy in the active interpreter and reports whether it looks like the Ladruno fork (has_fork), exposes the fork-only profiler command, its version() string, and its build stamp (the exact git hash the binary was compiled from, on fork builds that ship ladrunoBuild). Raises if openseespy is not installed. This introspects the live runtime only — the subprocess paths bind their own interpreter / binary via :class:OpenSeesTarget.

Source code in src/apeGmsh/opensees/apesees.py
def capabilities(self) -> "OpenSeesCapabilities":
    """Probe the in-process openseespy build (live path).

    Imports openseespy in the active interpreter and reports whether
    it looks like the Ladruno fork (``has_fork``), exposes the
    fork-only ``profiler`` command, its ``version()`` string, and its
    ``build`` stamp (the exact git hash the binary was compiled from,
    on fork builds that ship ``ladrunoBuild``).
    Raises if openseespy is not installed.  This introspects the
    **live** runtime only — the subprocess paths bind their own
    interpreter / binary via :class:`OpenSeesTarget`.
    """
    from ._target import probe_live_capabilities

    return probe_live_capabilities()

model

model(*, ndm: int, ndf: int) -> None

Set the model dimensionality (ndm) and the envelope ndf.

Per-node ndf is inferred from the declared element classes (ADR 0048) — ndf here is only the OpenSees model envelope (model BasicBuilder -ndm K -ndf N) and the fallback for nodes inference cannot see: element-less / decoupled nodes, and nodes touched only by adaptive elements (the zeroLength family). Element-attached nodes get their inferred value as a per-node -ndf override, emitted only where it differs from this envelope. There is no per-node ndf to declare on the geometry session — g.node_ndf was removed; the elements you declare determine it.

Source code in src/apeGmsh/opensees/apesees.py
def model(self, *, ndm: int, ndf: int) -> None:
    """Set the model dimensionality (``ndm``) and the envelope ``ndf``.

    Per-node ``ndf`` is **inferred** from the declared element
    classes (ADR 0048) — ``ndf`` here is only the OpenSees model
    **envelope** (``model BasicBuilder -ndm K -ndf N``) and the
    **fallback** for nodes inference cannot see: element-less /
    decoupled nodes, and nodes touched only by adaptive elements
    (the zeroLength family). Element-attached nodes get their
    inferred value as a per-node ``-ndf`` override, emitted only
    where it differs from this envelope. There is no per-node
    ``ndf`` to declare on the geometry session — ``g.node_ndf``
    was removed; the elements you declare determine it.
    """
    self._ndm = ndm
    self._ndf = ndf

fix

fix(*, pg: str | None = None, nodes: Iterable[int | Node] | None = None, label: str | Sequence[str] | None = None, dofs: tuple[int, ...], name: str | None = None) -> None

Apply homogeneous SP constraints (fix).

Exactly one of pg / nodes / label must be supplied. nodes accepts a mix of plain integer tags and :class:Node instances (from ops.nodes.get(...)); both are normalized to tags. The build pipeline expands pg to a per-node fan-out at emit time. label (one geometry label or a list) resolves on the snapshot here, so an unknown label raises before anything registers, listing the labels that exist; it never falls back to a physical group (ADR 0115 D4).

Homogeneous fixes merge within a tier (ADR 0115 D6): a later fix (or fix_from_model) on a (node, DOF) this tier already fixes emits only its remaining DOFs on that node, or nothing. An overlap with a stage's s.fix / s.support still raises at build.

name labels the declaration (opensees/fix/<name> in model.h5's /opensees/decls, read back through OpenSeesModel.declarations); unnamed, it is #k. Names are unique among the fixes (flat and staged). A label only: the deck and model_hash do not change with it.

Source code in src/apeGmsh/opensees/apesees.py
def fix(
    self,
    *,
    pg: str | None = None,
    nodes: Iterable[int | Node] | None = None,
    label: str | Sequence[str] | None = None,
    dofs: tuple[int, ...],
    name: str | None = None,
) -> None:
    """Apply homogeneous SP constraints (``fix``).

    Exactly one of ``pg`` / ``nodes`` / ``label`` must be supplied.
    ``nodes`` accepts a mix of plain integer tags and :class:`Node`
    instances (from ``ops.nodes.get(...)``); both are normalized
    to tags. The build pipeline expands ``pg`` to a per-node
    fan-out at emit time. ``label`` (one geometry label or a list)
    resolves on the snapshot here, so an unknown label raises
    before anything registers, listing the labels that exist; it
    never falls back to a physical group (ADR 0115 D4).

    Homogeneous fixes merge within a tier (ADR 0115 D6): a later
    ``fix`` (or ``fix_from_model``) on a ``(node, DOF)`` this tier
    already fixes emits only its remaining DOFs on that node, or
    nothing. An overlap with a stage's ``s.fix`` / ``s.support``
    still raises at build.

    ``name`` labels the declaration (``opensees/fix/<name>`` in
    ``model.h5``'s ``/opensees/decls``, read back through
    ``OpenSeesModel.declarations``); unnamed, it is ``#k``.  Names
    are unique among the fixes (flat and staged).  A label only: the
    deck and ``model_hash`` do not change with it.
    """
    pg, nodes_tuple, label_names = _select_nodes(
        self._fem, pg=pg, nodes=nodes, label=label, where="apeSees.fix")
    rec = FixRecord(pg=pg, nodes=nodes_tuple, dofs=tuple(dofs),
                    label=label_names)
    self._declare_record(rec, "fix", name)
    self._fix_records.append(rec)

combination

combination(name: str, terms: 'Iterable[object]', *, rule: str = 'linear', envelope: str = '', fraction: float | None = None, damping: float | None = None) -> Combination

Declare a combination, archived in model.h5 (ADR 0130 D4).

A term is (stage_name, factor) for a stage's last step, (combination, factor) for a combination this bridge declared, or a :class:CombinationTerm for a chosen step or a mode. rule is linear, srss, cqc (over modes, damping required: a case's per-mode damping lives in .user.h5), abs_sum, directional (fraction) or envelope (envelope is max, min or absmax).

Refused here, with nothing registered: a bad name, a repeated name, a term naming an undeclared combination, and a spectrum or reference term, whose case lives in .user.h5; declare that combination there after the run. A stage's name is stamped by the run, so it resolves when the combination is evaluated.

Source code in src/apeGmsh/opensees/apesees.py
def combination(
    self,
    name: str,
    terms: "Iterable[object]",
    *,
    rule: str = "linear",
    envelope: str = "",
    fraction: float | None = None,
    damping: float | None = None,
) -> Combination:
    """Declare a combination, archived in ``model.h5`` (ADR 0130 D4).

    A term is ``(stage_name, factor)`` for a stage's last step,
    ``(combination, factor)`` for a combination this bridge declared, or
    a :class:`CombinationTerm` for a chosen step or a mode. ``rule`` is
    ``linear``, ``srss``, ``cqc`` (over modes, ``damping`` required: a
    case's per-mode damping lives in ``.user.h5``), ``abs_sum``,
    ``directional`` (``fraction``) or ``envelope`` (``envelope`` is
    ``max``, ``min`` or ``absmax``).

    Refused here, with nothing registered: a bad name, a repeated name,
    a term naming an undeclared combination, and a ``spectrum`` or
    ``reference`` term, whose case lives in ``.user.h5``; declare that
    combination there after the run. A stage's name is stamped by the
    run, so it resolves when the combination is evaluated.
    """
    combo = declare_combination(
        name, terms, rule=rule, envelope=envelope, fraction=fraction,
        damping=damping, known=self._combinations,
    )
    self._combinations[name] = combo
    return combo

equation_constraint

equation_constraint(*, constrained: 'tuple[int | Node, int]', retained: 'Iterable[tuple[int | Node, int, float]]', coef: float = 1.0) -> None

Declare one equationConstraint row (OpenSees EQ_Constraint).

The row is the linear relation, in OpenSees' sum-to-zero form::

coef * u[cdof](cnode) + sum_i rcoef_i * u[rdof_i](rnode_i) = 0

with constrained=(cnode, cdof) and retained=[(rnode, rdof, rcoef), ...]. So u_c = 0.5 u_a + 0.5 u_b is constrained=(c, 1), retained=[(a, 1, -0.5), (b, 1, -0.5)]. Nodes are FEM node ids (or :class:Node handles); DOFs are 1-based.

Emitted in the MP-constraint pass, after the snapshot's constraints. EQ_Constraint is enforced by Lagrange, Penalty and the fork's LadrunoProjection only: Transformation, Auto and Plain drop it without a word. So with no declared handler the bridge auto-emits Lagrange (implicit) or LadrunoProjection (explicit integrator), and a declared Transformation / Auto raises — the same rules as an enforce="equation" tie (ADR 0068 INV-4).

Validated here (non-zero finite coefficients, DOFs >= 1, a non-empty retained set, the constrained DOF not among the retained ones) and at emit (nodes exist, DOFs fit each node's ndf). The in-process run needs a build with equationConstraint (openseespy >= 3.8.0 — one such model per process, since stock wipe() keeps the rows — or the fork); a partitioned emit refuses the rows. ops.h5(...) archives each one as an EquationConstraintRecord row of /opensees/decl_params, and OpenSeesModel.from_h5(...) replays it.

Source code in src/apeGmsh/opensees/apesees.py
def equation_constraint(
    self,
    *,
    constrained: "tuple[int | Node, int]",
    retained: "Iterable[tuple[int | Node, int, float]]",
    coef: float = 1.0,
) -> None:
    """Declare one ``equationConstraint`` row (OpenSees ``EQ_Constraint``).

    The row is the linear relation, in OpenSees' sum-to-zero form::

        coef * u[cdof](cnode) + sum_i rcoef_i * u[rdof_i](rnode_i) = 0

    with ``constrained=(cnode, cdof)`` and ``retained=[(rnode, rdof,
    rcoef), ...]``. So ``u_c = 0.5 u_a + 0.5 u_b`` is
    ``constrained=(c, 1), retained=[(a, 1, -0.5), (b, 1, -0.5)]``.
    Nodes are FEM node ids (or :class:`Node` handles); DOFs are
    1-based.

    Emitted in the MP-constraint pass, after the snapshot's
    constraints. ``EQ_Constraint`` is enforced by ``Lagrange``,
    ``Penalty`` and the fork's ``LadrunoProjection`` only:
    ``Transformation``, ``Auto`` and ``Plain`` drop it without a word.
    So with no declared handler the bridge auto-emits ``Lagrange``
    (implicit) or ``LadrunoProjection`` (explicit integrator), and a
    declared ``Transformation`` / ``Auto`` raises — the same rules as
    an ``enforce="equation"`` tie (ADR 0068 INV-4).

    Validated here (non-zero finite coefficients, DOFs >= 1, a
    non-empty retained set, the constrained DOF not among the retained
    ones) and at emit (nodes exist, DOFs fit each node's ndf). The
    in-process run needs a build with ``equationConstraint``
    (openseespy >= 3.8.0 — one such model per process, since stock
    ``wipe()`` keeps the rows — or the fork); a partitioned emit
    refuses the rows. ``ops.h5(...)`` archives each one as an
    ``EquationConstraintRecord`` row of ``/opensees/decl_params``, and
    ``OpenSeesModel.from_h5(...)`` replays it.
    """
    try:
        cnode, cdof = constrained
    except (TypeError, ValueError):
        raise ValueError(
            "apeSees.equation_constraint: constrained must be a "
            f"(node, dof) pair, got {constrained!r}."
        ) from None
    rows: list[tuple[int, int, float]] = []
    for triple in retained:
        try:
            rn, rd, rc = triple
        except (TypeError, ValueError):
            raise ValueError(
                "apeSees.equation_constraint: each retained entry must "
                f"be a (node, dof, coef) triple, got {triple!r}."
            ) from None
        rows.append((_iter_tags([rn])[0], rd, rc))
    rec = make_equation_constraint_record(
        _iter_tags([cnode])[0], cdof, coef, rows,
    )
    # K1-6: a declaration with no archived rows (a ledger verb).
    self._declare_record(rec, "equation_constraint", None)
    self._equation_constraint_records.append(rec)

mass

mass(*, pg: str | None = None, nodes: Iterable[int | Node] | None = None, label: str | Sequence[str] | None = None, values: tuple[float, ...], overwrite: bool = False, name: str | None = None) -> None

Attach lumped nodal mass.

Exactly one of pg / nodes / label must be supplied. nodes accepts plain integers or :class:Node instances; label resolves as for :meth:fix. Masses never merge: a second mass on a node raises at build unless overwrite=True (setMass is not idempotent; ADR 0115 D6).

overwrite (Phase SSI-2.E) opts the record out of validator V2's cross-tier duplicate-mass check. Rare at the global tier but kept for symmetry with the stage-bound :meth:_StageBuilder.mass — see that method for the typical use case.

name labels the declaration (opensees/mass/<name> in /opensees/decls), as for :meth:fix; a label only.

Source code in src/apeGmsh/opensees/apesees.py
def mass(
    self,
    *,
    pg: str | None = None,
    nodes: Iterable[int | Node] | None = None,
    label: str | Sequence[str] | None = None,
    values: tuple[float, ...],
    overwrite: bool = False,
    name: str | None = None,
) -> None:
    """Attach lumped nodal mass.

    Exactly one of ``pg`` / ``nodes`` / ``label`` must be supplied.
    ``nodes`` accepts plain integers or :class:`Node` instances;
    ``label`` resolves as for :meth:`fix`. Masses never merge: a
    second mass on a node raises at build unless ``overwrite=True``
    (``setMass`` is not idempotent; ADR 0115 D6).

    ``overwrite`` (Phase SSI-2.E) opts the record out of validator
    V2's cross-tier duplicate-mass check.  Rare at the global tier
    but kept for symmetry with the stage-bound :meth:`_StageBuilder.mass`
    — see that method for the typical use case.

    ``name`` labels the declaration (``opensees/mass/<name>`` in
    ``/opensees/decls``), as for :meth:`fix`; a label only.
    """
    pg, nodes_tuple, label_names = _select_nodes(
        self._fem, pg=pg, nodes=nodes, label=label, where="apeSees.mass")
    rec = MassRecord(
        pg=pg, nodes=nodes_tuple, values=tuple(values),
        overwrite=bool(overwrite), label=label_names,
    )
    self._declare_record(rec, "mass", name)
    self._mass_records.append(rec)

mass_from_model

mass_from_model() -> None

Stream per-node lumped masses straight from the model snapshot.

In 3-D, equivalent to looping ops.mass(nodes=[m.node_id], values=m.mass) over every entry in fem.nodes.masses (e.g. the per-node tributary masses produced by g.masses.volume(...)), but without materializing one bridge MassRecord per node — the snapshot masses are streamed at emit time. On a multi-million-node model this avoids a multi-GB resident list and millions of small objects (ADR 0065 Tier 2). Honours per-node ndf; each broker mass is spatially ordered (mx, my, mz, Ixx, Iyy, Izz) and is mapped onto the node's DOFs by broker_mass_components — byte-identical to the explicit loop in 3-D, and (mx, my[, Izz]) on a 2-D (ndm=2) node.

Model-wide declaration (no arguments). May be combined with explicit :meth:mass calls only on disjoint node sets — overlap raises at emit (nodal mass is additive under MP assembly). Deck/live emit only; the H5 archival emitter rejects it (masses already persist in model.h5 via fem.nodes.masses).

Source code in src/apeGmsh/opensees/apesees.py
def mass_from_model(self) -> None:
    """Stream per-node lumped masses straight from the model snapshot.

    In 3-D, equivalent to looping ``ops.mass(nodes=[m.node_id], values=m.mass)``
    over every entry in ``fem.nodes.masses`` (e.g. the per-node tributary
    masses produced by ``g.masses.volume(...)``), but **without
    materializing one bridge ``MassRecord`` per node** — the snapshot
    masses are streamed at emit time. On a multi-million-node model this
    avoids a multi-GB resident list and millions of small objects (ADR
    0065 Tier 2). Honours per-node ``ndf``; each broker mass is spatially
    ordered ``(mx, my, mz, Ixx, Iyy, Izz)`` and is mapped onto the node's
    DOFs by ``broker_mass_components`` — byte-identical to the explicit
    loop in 3-D, and ``(mx, my[, Izz])`` on a 2-D (``ndm=2``) node.

    Model-wide declaration (no arguments). May be combined with explicit
    :meth:`mass` calls only on *disjoint* node sets — overlap raises at
    emit (nodal mass is additive under MP assembly). Deck/live emit only;
    the H5 archival emitter rejects it (masses already persist in
    ``model.h5`` via ``fem.nodes.masses``).
    """
    if not self._mass_from_model:
        # One declaration, however often it is called (K1-6).
        self._declare_record(self._mass_from_model_owner, "mass", None)
    self._mass_from_model = True

fix_from_model

fix_from_model() -> None

Fix every homogeneous SP on the model snapshot (ADR 0051 §4).

The support twin of :meth:mass_from_model: equivalent to a :meth:fix for each node carrying homogeneous records on fem.nodes.sp (g.constraints.bc(...), or a zero-valued g.displacements), with the node's restrained DOFs folded into one mask, so two targets sharing a node emit one fix. The records' spatial components (ux uy uz rx ry rz) land on the node's deck DOFs by ndm and ndf, and one the node lacks is left out: bc's default [1, 1, 1] pins x and y on a 2-D solid or frame and leaves a frame's rz free. Prescribed (non-zero) SPs are untouched: p.from_model(case) imports those.

Model-wide declaration (no arguments), materialized into ordinary fix records at :meth:build, so every emit path treats them like :meth:fix. It belongs to the global tier, so it merges with explicit :meth:fix calls (ADR 0115 D6, Q1): a (node, DOF) both fix emits once. It may be combined with a stage's s.fix / s.support only on disjoint (node, DOF) pairs: that overlap raises at build, since OpenSees refuses a second SP on a constrained DOF and the lifecycles differ.

Source code in src/apeGmsh/opensees/apesees.py
def fix_from_model(self) -> None:
    """Fix every homogeneous SP on the model snapshot (ADR 0051 §4).

    The support twin of :meth:`mass_from_model`: equivalent to a
    :meth:`fix` for each node carrying homogeneous records on
    ``fem.nodes.sp`` (``g.constraints.bc(...)``, or a zero-valued
    ``g.displacements``), with the node's restrained DOFs folded
    into one mask, so two targets sharing a node emit one ``fix``.
    The records' spatial components (``ux uy uz rx ry rz``) land on
    the node's deck DOFs by ``ndm`` and ndf, and one the node lacks
    is left out: ``bc``'s default ``[1, 1, 1]`` pins x and y on a
    2-D solid or frame and leaves a frame's ``rz`` free. Prescribed
    (non-zero) SPs are untouched: ``p.from_model(case)`` imports
    those.

    Model-wide declaration (no arguments), materialized into
    ordinary fix records at :meth:`build`, so every emit path treats
    them like :meth:`fix`. It belongs to the global tier, so it
    merges with explicit :meth:`fix` calls (ADR 0115 D6, Q1): a
    ``(node, DOF)`` both fix emits once. It may be combined with a
    stage's ``s.fix`` / ``s.support`` only on *disjoint* (node, DOF)
    pairs: that overlap raises at build, since OpenSees refuses a
    second SP on a constrained DOF and the lifecycles differ.
    """
    if not self._fix_from_model:
        # One declaration; the records build() materializes share it.
        self._declare_record(self._fix_from_model_owner, "fix", None)
    self._fix_from_model = True

ndf

ndf(target: object = None, *, ndf: int) -> None

State the per-node ndf of an element-LESS decoupled node (ADR 0049 — the sole explicit per-node ndf channel).

Every other node's ndf is inferred from its incident element classes (ADR 0048). ops.ndf exists only for nodes inference cannot reach — a spring/dashpot ground, a control node, or a mass anchor created via g.decouple_node(...) that no element touches.

Parameters

target The decoupled-node handle returned by g.decouple_node(...) (a DecoupledNodeDef) or its integer node tag. The handle is resolved to its tag at build time (so a handle materialized after meshing resolves correctly); a still-unmeshed handle fails loud at build. ndf The DOF count to assign the node.

Raises (at build) :class:BridgeError if target is a mesh node, an element-touched node (its ndf is inferred — restating it would create a two-headed model), or an unresolved handle. The stated value is also checked by gates G1–G3 (adaptive endpoints, constraint masters, referenced fix/mass/load/sp DOFs).

Source code in src/apeGmsh/opensees/apesees.py
def ndf(self, target: object = None, *, ndf: int) -> None:
    """State the per-node ``ndf`` of an element-LESS decoupled node
    (ADR 0049 — the sole explicit per-node ndf channel).

    Every other node's ndf is **inferred** from its incident element
    classes (ADR 0048). ``ops.ndf`` exists only for nodes inference cannot
    reach — a spring/dashpot **ground**, a control node, or a mass anchor
    created via ``g.decouple_node(...)`` that no element touches.

    Parameters
    ----------
    target
        The decoupled-node handle returned by ``g.decouple_node(...)`` (a
        ``DecoupledNodeDef``) **or** its integer node tag. The handle is
        resolved to its tag at **build** time (so a handle materialized
        after meshing resolves correctly); a still-unmeshed handle fails
        loud at build.
    ndf
        The DOF count to assign the node.

    Raises (at build) :class:`BridgeError` if *target* is a mesh node, an
    element-touched node (its ndf is inferred — restating it would create
    a two-headed model), or an unresolved handle. The stated value is also
    checked by gates G1–G3 (adaptive endpoints, constraint masters,
    referenced fix/mass/load/sp DOFs).
    """
    if target is None:
        raise ValueError(
            "apeSees.ndf: a target is required — pass the decoupled-node "
            "handle from g.decouple_node(...) or its integer tag."
        )
    if not isinstance(ndf, int) or isinstance(ndf, bool) or ndf < 1:
        raise ValueError(
            f"apeSees.ndf: ndf must be a positive int (got {ndf!r})."
        )
    if isinstance(target, bool):
        raise ValueError(
            f"apeSees.ndf: target must be a decoupled-node handle or an "
            f"int tag (got bool {target!r})."
        )
    if isinstance(target, int):
        self._ndf_records.append(NdfRecord(handle=None, tag=int(target), ndf=ndf))
    else:
        # A handle (DecoupledNodeDef) — store it raw; resolve_ndf_overlay
        # dereferences ``.tag`` at build (fail-loud on a None tag).
        self._ndf_records.append(NdfRecord(handle=target, tag=None, ndf=ndf))

spring_bed

spring_bed(ground: 'DecoupledNodeSetDef', *, at: 'DecoupledNodeSetDef | None' = None, k: 'SpringValues', c: 'SpringValues | None' = None, orient: 'OrientValues | None' = None, tributary: str | None = None, dirs: 'Sequence[int]' = (1, 2, 3), do_rayleigh: bool = False, fix: bool = True, ndf: int = 3, name: str | None = None) -> 'SpringBed'

A grounded zeroLength spring (and dashpot) on every node of a decoupled node set (ADR 0119 D2) — a distributed foundation bed.

Spring i joins the ground node i (a g.decouple_node_set(...) handle) to the at node with the same source node — the side nodes of a second set declared with tie_dofs — or, with at=None, to the source node itself. Per spring and direction the bed registers uniaxialMaterial Parallel <m> <E1> <V1> -factors k c over one Elastic 1.0 and one Viscous 1.0 1.0 shared by every bed of the bridge (-factors k alone when c is None), one zeroLength per spring, fix on the ground nodes (all ndf DOFs) and the ndf of the ground and at nodes.

Parameters

ground, at Resolved g.decouple_node_set handles on one source. k, c Stiffness and dashpot coefficient per spring and direction: an (n, len(dirs)) array, len(dirs) values for every spring, or a callable f(xyz, area) returning the array (xyz: the (n, 3) source coordinates in source order; area: the tributary areas, None without tributary=). Values must be finite and >= 0. orient -orient: a 6-tuple, an (n, 6) array or f(xyz); None keeps the global axes. tributary A 2-D label or physical group whose element areas, shared equally among each element's corners, give area. dirs The -dir DOFs, distinct, each <= ndf. do_rayleigh False (default) keeps the springs out of Rayleigh damping: the dashpots carry the foundation damping. fix Fix the ground nodes (default True). ndf The DOF count stated for the ground and at nodes; it must equal the ndf of the node each spring reaches. name A label for the returned record.

Returns the :class:~apeGmsh.opensees._internal.spring_bed.SpringBed record (node tags, k, c, areas, orientations, specs). A partitioned emit routes each spring, its ground and side nodes and their equalDOF to the rank of the structural node (ADR 0120).

Source code in src/apeGmsh/opensees/apesees.py
def spring_bed(
    self,
    ground: "DecoupledNodeSetDef",
    *,
    at: "DecoupledNodeSetDef | None" = None,
    k: "SpringValues",
    c: "SpringValues | None" = None,
    orient: "OrientValues | None" = None,
    tributary: str | None = None,
    dirs: "Sequence[int]" = (1, 2, 3),
    do_rayleigh: bool = False,
    fix: bool = True,
    ndf: int = 3,
    name: str | None = None,
) -> "SpringBed":
    """A grounded zeroLength spring (and dashpot) on every node of a
    decoupled node set (ADR 0119 D2) — a distributed foundation bed.

    Spring ``i`` joins the ``ground`` node ``i`` (a
    ``g.decouple_node_set(...)`` handle) to the ``at`` node with the
    same source node — the side nodes of a second set declared with
    ``tie_dofs`` — or, with ``at=None``, to the source node itself.
    Per spring and direction the bed registers
    ``uniaxialMaterial Parallel <m> <E1> <V1> -factors k c`` over one
    ``Elastic 1.0`` and one ``Viscous 1.0 1.0`` shared by every bed of
    the bridge (``-factors k`` alone when ``c`` is ``None``), one
    ``zeroLength`` per spring, ``fix`` on the ground nodes (all
    ``ndf`` DOFs) and the ``ndf`` of the ground and ``at`` nodes.

    Parameters
    ----------
    ground, at
        Resolved ``g.decouple_node_set`` handles on one source.
    k, c
        Stiffness and dashpot coefficient per spring and direction:
        an ``(n, len(dirs))`` array, ``len(dirs)`` values for every
        spring, or a callable ``f(xyz, area)`` returning the array
        (``xyz``: the ``(n, 3)`` source coordinates in source order;
        ``area``: the tributary areas, ``None`` without
        ``tributary=``). Values must be finite and ``>= 0``.
    orient
        ``-orient``: a 6-tuple, an ``(n, 6)`` array or ``f(xyz)``;
        ``None`` keeps the global axes.
    tributary
        A 2-D label or physical group whose element areas, shared
        equally among each element's corners, give ``area``.
    dirs
        The ``-dir`` DOFs, distinct, each ``<= ndf``.
    do_rayleigh
        ``False`` (default) keeps the springs out of Rayleigh
        damping: the dashpots carry the foundation damping.
    fix
        Fix the ground nodes (default ``True``).
    ndf
        The DOF count stated for the ground and ``at`` nodes; it must
        equal the ``ndf`` of the node each spring reaches.
    name
        A label for the returned record.

    Returns the :class:`~apeGmsh.opensees._internal.spring_bed.SpringBed`
    record (node tags, ``k``, ``c``, areas, orientations, specs).
    A partitioned emit routes each spring, its ground and side nodes and
    their ``equalDOF`` to the rank of the structural node (ADR 0120).
    """
    from ._internal.spring_bed import build_spring_bed

    return build_spring_bed(
        self, ground, at=at, k=k, c=c, orient=orient,
        tributary=tributary, dirs=dirs, do_rayleigh=do_rayleigh,
        fix=fix, ndf=ndf, name=name,
    )

initial_stress

initial_stress(*, name: str, pg: str | None = None, elements: Iterable[int] | None = None, sigma_xx: float, sigma_yy: float, sigma_zz: float, ramp_steps: int, lambda_install: float = 1.0) -> 'InitialStressRecord'

Initialize an in-situ stress tensor on ASDPlasticMaterial3D elements.

Emits the OpenSees parameter / addToParameter / updateParameter ramp pattern that STKO uses to inject a pre-stressed state without applying gravity-driven body loads. The factor ramps linearly 0 → 1 over ramp_steps analyze calls and plateaus at 1.0 thereafter; the target stress baked into the ramp is sigma_* × lambda_install, so passing lambda_install < 1.0 produces a partial-installation (convergence-confinement) result.

Exactly one of pg / elements must be supplied. This primitive is declarative only — the actual stress advancement happens at analyze time, via the per-step dispatcher this primitive registers with. Call ops.analyze(steps=ramp_steps, dt=...) or pass analyze_steps=ramp_steps to :meth:tcl / :meth:py for the ramp to take effect.

Parameters

name Unique Tcl-identifier-safe label. Used to name the emitted proc / state container. pg Physical group whose elements receive the ramped stress. elements Explicit list of FEM element ids. XOR with pg. sigma_xx, sigma_yy, sigma_zz Target Cauchy stress per component (compression negative). ramp_steps Number of analyze steps over which the factor reaches 1.0. Must be >= 1. lambda_install Fraction of target to install (default 1.0). Must be in (0, 1].

Source code in src/apeGmsh/opensees/apesees.py
def initial_stress(
    self,
    *,
    name: str,
    pg: str | None = None,
    elements: Iterable[int] | None = None,
    sigma_xx: float,
    sigma_yy: float,
    sigma_zz: float,
    ramp_steps: int,
    lambda_install: float = 1.0,
) -> "InitialStressRecord":
    """Initialize an in-situ stress tensor on ASDPlasticMaterial3D elements.

    Emits the OpenSees ``parameter`` / ``addToParameter`` /
    ``updateParameter`` ramp pattern that STKO uses to inject a
    pre-stressed state without applying gravity-driven body loads.
    The factor ramps linearly 0 → 1 over ``ramp_steps`` analyze
    calls and plateaus at 1.0 thereafter; the target stress baked
    into the ramp is ``sigma_* × lambda_install``, so passing
    ``lambda_install < 1.0`` produces a partial-installation
    (convergence-confinement) result.

    Exactly one of ``pg`` / ``elements`` must be supplied.  This
    primitive is **declarative only** — the actual stress
    advancement happens at analyze time, via the per-step
    dispatcher this primitive registers with.  Call
    ``ops.analyze(steps=ramp_steps, dt=...)`` or pass
    ``analyze_steps=ramp_steps`` to :meth:`tcl` / :meth:`py` for
    the ramp to take effect.

    Parameters
    ----------
    name
        Unique Tcl-identifier-safe label.  Used to name the
        emitted proc / state container.
    pg
        Physical group whose elements receive the ramped stress.
    elements
        Explicit list of FEM element ids.  XOR with ``pg``.
    sigma_xx, sigma_yy, sigma_zz
        Target Cauchy stress per component (compression negative).
    ramp_steps
        Number of analyze steps over which the factor reaches 1.0.
        Must be ``>= 1``.
    lambda_install
        Fraction of target to install (default 1.0).  Must be in
        ``(0, 1]``.
    """
    record = _build_initial_stress_record(
        source_label="apeSees.initial_stress",
        name=name, pg=pg, elements=elements,
        sigma_xx=sigma_xx, sigma_yy=sigma_yy, sigma_zz=sigma_zz,
        ramp_steps=ramp_steps, lambda_install=lambda_install,
    )
    self._declare_by_name(record, "initial_stress", name)  # K1-6
    self._initial_stress_records.append(record)
    # Phase SSI-2.A: return the record so callers can pass it to
    # ``with ops.stage(...) as s: s.add(record)`` which moves it
    # from this bridge-global pool into the stage's pool.
    # Non-staged callers can ignore the return value — the record
    # is already registered and will emit in the flat path.
    return record

convergence_confinement

convergence_confinement(*, name: str, pg: str | None = None, elements: Iterable[int] | None = None, sigma_xx: float = 0.0, sigma_yy: float = 0.0, sigma_zz: float = 0.0, lambda_target: float, n_steps: int) -> 'InitialStressRecord'

Convergence-confinement helper (Phase SSI-3).

Thin wrapper over :meth:initial_stress for the tunnelling convergence-confinement pattern: ramp a target stress on a boundary region to lambda_target × sigma over n_steps analyze steps. Matches the _stressCtrl_11-style proc from SSI/Interaccion/analysis_steps.tcl:19753-19767.

Differs from :meth:initial_stress in two cosmetic ways:

  • lambda_target (renamed from lambda_install) — more natural reading at the call site for confinement / relaxation contexts.
  • n_steps (renamed from ramp_steps) — matches the spec's naming.

At least one of sigma_xx / sigma_yy / sigma_zz must be non-zero (typically only one — single-component relaxation is the canonical SSI use case).

Returns the underlying :class:InitialStressRecord; pass it to s.add(...) inside a stage block to bind to that stage.

Parameters

name Unique Tcl-identifier-safe label. pg, elements Same XOR semantics as :meth:initial_stress. sigma_xx, sigma_yy, sigma_zz Target Cauchy stress per component (compression negative). At least one must be non-zero. lambda_target Fraction of target stress to install — i.e. the relaxation (or confinement) coefficient. Must be in (0, 1]. n_steps Number of analyze steps over which the factor reaches 1.0 internally. After the cap, the cumulative is sigma × lambda_target.

Source code in src/apeGmsh/opensees/apesees.py
def convergence_confinement(
    self,
    *,
    name: str,
    pg: str | None = None,
    elements: Iterable[int] | None = None,
    sigma_xx: float = 0.0,
    sigma_yy: float = 0.0,
    sigma_zz: float = 0.0,
    lambda_target: float,
    n_steps: int,
) -> "InitialStressRecord":
    """Convergence-confinement helper (Phase SSI-3).

    Thin wrapper over :meth:`initial_stress` for the tunnelling
    convergence-confinement pattern: ramp a target stress on a
    boundary region to ``lambda_target`` × ``sigma`` over
    ``n_steps`` analyze steps.  Matches the
    ``_stressCtrl_11``-style proc from
    ``SSI/Interaccion/analysis_steps.tcl:19753-19767``.

    Differs from :meth:`initial_stress` in two cosmetic ways:

    * ``lambda_target`` (renamed from ``lambda_install``) — more
      natural reading at the call site for confinement / relaxation
      contexts.
    * ``n_steps`` (renamed from ``ramp_steps``) — matches the
      spec's naming.

    At least one of ``sigma_xx`` / ``sigma_yy`` / ``sigma_zz`` must
    be non-zero (typically only one — single-component relaxation
    is the canonical SSI use case).

    Returns the underlying :class:`InitialStressRecord`; pass it to
    ``s.add(...)`` inside a stage block to bind to that stage.

    Parameters
    ----------
    name
        Unique Tcl-identifier-safe label.
    pg, elements
        Same XOR semantics as :meth:`initial_stress`.
    sigma_xx, sigma_yy, sigma_zz
        Target Cauchy stress per component (compression negative).
        At least one must be non-zero.
    lambda_target
        Fraction of target stress to install — i.e. the relaxation
        (or confinement) coefficient.  Must be in ``(0, 1]``.
    n_steps
        Number of analyze steps over which the factor reaches 1.0
        internally.  After the cap, the cumulative is
        ``sigma × lambda_target``.
    """
    if sigma_xx == 0.0 and sigma_yy == 0.0 and sigma_zz == 0.0:
        raise ValueError(
            "apeSees.convergence_confinement: at least one of "
            "sigma_xx / sigma_yy / sigma_zz must be non-zero."
        )
    return self.initial_stress(
        name=name,
        pg=pg,
        elements=elements,
        sigma_xx=sigma_xx,
        sigma_yy=sigma_yy,
        sigma_zz=sigma_zz,
        ramp_steps=n_steps,
        lambda_install=lambda_target,
    )

imposed_displacement

imposed_displacement(*, pg: str | None = None, nodes: Iterable[int] | None = None, ux: float | None = None, uy: float | None = None, uz: float | None = None, pattern_factor: float = 1.0, series: 'TimeSeries | None' = None, name: str | None = None) -> 'Plain'

Imposed-displacement pattern helper (Phase SSI-3).

Emits one pattern Plain containing sp NODE DOF VALUE prescribed-displacement entries for every (node, dof) pair where the corresponding ux / uy / uz is non-None. Used for fault-slip kinematics, support-settlement scenarios, and any other prescribed-displacement driver.

STKO equivalent: pattern Plain N tsTag -fact F { sp NODE DOF VAL ... } from SSI/Interaccion y Falla/analysis_steps.tcl:22832-23253. Where STKO uses -fact F on the pattern, this helper folds the same scaling into the auto-created Linear(factor=F) time series — numerically identical, simpler API.

Parameters

pg, nodes XOR: exactly one of pg (physical-group name) or nodes (iterable of FEM node ids) must be supplied. ux, uy, uz Scalar broadcast: every targeted node gets the same prescribed displacement in this DOF. None (default) skips the DOF. At least one of the three must be set. pattern_factor Multiplier folded into the auto-created Linear time series. Default 1.0 (no scaling). Matches STKO's -fact F semantics: the actual applied displacement at simulation-time t is value × pattern_factor × t. series Optional explicit :class:TimeSeries to use. Must be already registered with the bridge. When supplied, pattern_factor is ignored — the user is in full control of the time-history shape. name Optional bridge-side alias for the pattern (as name= on ops.pattern.Plain). It is also the <name> of the call's provenance records, opensees/pattern/imposed_displacement:<name> and, for the auto-created series, opensees/timeSeries/imposed_displacement:<name>; without it <name> is #<k>, the call's 1-based ordinal on this bridge, so a name may not start with #. A refused or taken name raises before anything is registered. Both records carry origin = "synthesised" and point at this call (ADR 0112 D3, #1378).

Returns

Plain The registered :class:Plain pattern. This is a global (non-staged) pattern: it is valid only in a non-staged deck (global pattern + ops.analyze). Per ADR 0051 §5 a model may not mix a global pattern with stages — combining this with ops.stage(...) raises :class:BridgeError at build. For prescribed motion inside a staged deck, author the sp on a stage pattern instead (with s.pattern(series=...) as p: p.sp(...)).

Notes

Per-node-varying displacements are NOT supported in v1 — every targeted node gets the same scalar. For different values per node, call imposed_displacement multiple times with disjoint nodes= lists, or construct the Plain pattern manually via ops.pattern.Plain(...).

Source code in src/apeGmsh/opensees/apesees.py
def imposed_displacement(
    self,
    *,
    pg: str | None = None,
    nodes: Iterable[int] | None = None,
    ux: float | None = None,
    uy: float | None = None,
    uz: float | None = None,
    pattern_factor: float = 1.0,
    series: "TimeSeries | None" = None,
    name: str | None = None,
) -> "Plain":
    """Imposed-displacement pattern helper (Phase SSI-3).

    Emits one ``pattern Plain`` containing ``sp NODE DOF VALUE``
    prescribed-displacement entries for every (node, dof) pair
    where the corresponding ``ux`` / ``uy`` / ``uz`` is non-None.
    Used for fault-slip kinematics, support-settlement scenarios,
    and any other prescribed-displacement driver.

    STKO equivalent:
    ``pattern Plain N tsTag -fact F { sp NODE DOF VAL ... }``
    from ``SSI/Interaccion y Falla/analysis_steps.tcl:22832-23253``.
    Where STKO uses ``-fact F`` on the pattern, this helper folds
    the same scaling into the auto-created ``Linear(factor=F)``
    time series — numerically identical, simpler API.

    Parameters
    ----------
    pg, nodes
        XOR: exactly one of ``pg`` (physical-group name) or
        ``nodes`` (iterable of FEM node ids) must be supplied.
    ux, uy, uz
        Scalar broadcast: every targeted node gets the same
        prescribed displacement in this DOF.  ``None`` (default)
        skips the DOF.  At least one of the three must be set.
    pattern_factor
        Multiplier folded into the auto-created ``Linear`` time
        series.  Default ``1.0`` (no scaling).  Matches STKO's
        ``-fact F`` semantics: the actual applied displacement
        at simulation-time ``t`` is
        ``value × pattern_factor × t``.
    series
        Optional explicit :class:`TimeSeries` to use.  Must be
        already registered with the bridge.  When supplied,
        ``pattern_factor`` is ignored — the user is in full
        control of the time-history shape.
    name
        Optional bridge-side alias for the pattern (as ``name=`` on
        ``ops.pattern.Plain``).  It is also the ``<name>`` of the
        call's provenance records,
        ``opensees/pattern/imposed_displacement:<name>`` and, for the
        auto-created series,
        ``opensees/timeSeries/imposed_displacement:<name>``; without
        it ``<name>`` is ``#<k>``, the call's 1-based ordinal on this
        bridge, so a name may not start with ``#``.  A refused or
        taken name raises before anything is registered.  Both
        records carry ``origin = "synthesised"`` and point at this
        call (ADR 0112 D3, #1378).

    Returns
    -------
    Plain
        The registered :class:`Plain` pattern.  This is a **global**
        (non-staged) pattern: it is valid only in a non-staged deck
        (global pattern + ``ops.analyze``).  Per ADR 0051 §5 a model
        may not mix a global pattern with stages — combining this
        with ``ops.stage(...)`` raises :class:`BridgeError` at build.
        For prescribed motion inside a staged deck, author the ``sp``
        on a stage pattern instead (``with s.pattern(series=...) as
        p: p.sp(...)``).

    Notes
    -----
    Per-node-varying displacements are NOT supported in v1 —
    every targeted node gets the same scalar.  For different
    values per node, call ``imposed_displacement`` multiple times
    with disjoint ``nodes=`` lists, or construct the ``Plain``
    pattern manually via ``ops.pattern.Plain(...)``.
    """
    if (pg is None) == (nodes is None):
        raise ValueError(
            "apeSees.imposed_displacement: supply exactly one of "
            f"pg= or nodes= (got pg={pg!r}, nodes={nodes!r})."
        )
    if ux is None and uy is None and uz is None:
        raise ValueError(
            "apeSees.imposed_displacement: at least one of ux / "
            "uy / uz must be supplied."
        )
    if pattern_factor == 0.0:
        raise ValueError(
            "apeSees.imposed_displacement: pattern_factor must be "
            "non-zero (a zero factor produces an inert pattern)."
        )

    # DOF-index validation against the model's ndf (red-team H3).
    # ``uz`` maps to DOF 3, which only exists on ndf>=3 models;
    # emitting ``sp NODE 3 VALUE`` on an ndf=2 model produces an
    # OpenSees parse error ("invalid dof").  Catch upfront with a
    # clear error pointing at the offending kwarg.
    if self._ndf is not None:
        dof_kwargs = (("ux", 1, ux), ("uy", 2, uy), ("uz", 3, uz))
        for kw, dof_idx, val in dof_kwargs:
            if val is not None and dof_idx > self._ndf:
                raise ValueError(
                    f"apeSees.imposed_displacement: {kw}= targets "
                    f"DOF {dof_idx}, but the model's ndf is "
                    f"{self._ndf}.  Drop {kw}= or call "
                    f"ops.model(..., ndf={dof_idx}) first."
                )

    from .pattern.pattern import Plain as _Plain
    from .time_series.time_series import Linear as _Linear

    # Every refusal happens here, before anything is registered, so
    # a bad call leaves no series, pattern, alias or record behind.
    # An empty name is no name (as ``_register`` and ``capture``
    # read it): the call takes its ordinal key.
    name = name or None
    if name is not None:
        if name.startswith("#"):
            raise ValueError(
                f"apeSees.imposed_displacement: name={name!r} may not "
                "start with '#': that prefix marks the ordinal key of "
                "an unnamed call (imposed_displacement:#<k>)."
            )
        existing = self._names.get(name)
        if existing is not None:
            raise ValueError(
                f"apeSees: name {name!r} is already registered to a "
                f"{type(existing).__name__}; names must be unique per "
                "bridge.  Pick a different name= (or pass the object "
                "handle directly)."
            )
    if series is not None:
        # A name string resolves through the alias table like every
        # other reference kwarg (an unknown name or a non-series
        # fails loud).
        series = self._resolve(series, base=TimeSeries)

    # Provenance key of this call's synthesised objects
    # (``<verb>:<name>`` or ``<verb>:#<k>``; see ``name`` above).
    # Both prospective keys are checked before either object is
    # registered: user names share the key space, and a refusal
    # must leave no series, pattern or record behind.
    _key = (
        f"imposed_displacement:"
        f"{name if name is not None else f'#{self._imposed_displacement_calls + 1}'}"
    )
    for _family, _needed in (("timeSeries", series is None),
                             ("pattern", True)):
        if _needed and self._provenance.has("opensees", _family, _key):
            raise ValueError(
                "apeSees.imposed_displacement: the provenance key "
                f"'opensees/{_family}/{_key}' of the {_family} it would "
                "create already has a record (a declaration was named "
                "like it); pass another name=.  Nothing was registered."
            )
    self._imposed_displacement_calls += 1

    # Default time series: Linear scaled by pattern_factor.
    # Folds STKO's ``-fact F`` semantics into the time-series
    # factor instead of an explicit ``-fact`` on the pattern
    # (apeGmsh's Plain pattern primitive doesn't carry one).
    if series is None:
        series = self._register(
            _Linear(factor=float(pattern_factor)), synthesised=_key,
        )

    # Register + tag the Plain pattern directly (not through the
    # namespace) so its provenance record carries the verb's key.
    plain = self._register(_Plain(series=series), name=name,
                           synthesised=_key)
    # Populate the sp records.  Plain's recording API accepts
    # either pg= or node=; we route based on the helper's input.
    dof_values: tuple[tuple[int, float | None], ...] = (
        (1, ux), (2, uy), (3, uz),
    )
    with plain:
        if pg is not None:
            for dof, value in dof_values:
                if value is None:
                    continue
                plain.sp(pg=pg, dof=dof, value=float(value))
        else:
            assert nodes is not None
            for node in nodes:
                for dof, value in dof_values:
                    if value is None:
                        continue
                    plain.sp(node=int(node), dof=dof, value=float(value))
    return plain

stage

stage(name: str) -> '_StageBuilder'

Open a staged-analysis block (Phase SSI-2.A).

Nested with ops.stage(...) blocks are NOT supported — opening a second stage builder while another is still open raises RuntimeError. The lexical-vs-emit-order semantics would otherwise be confusing (the inner builder's exit fires first, registering the inner stage BEFORE the outer in _stage_records, which is the opposite of what readers expect).

Usage::

with ops.stage(name="insitu") as s:
    s.add(ops.initial_stress(name="rock", ..., ramp_steps=10))
    s.analysis(
        test=ops.test.NormDispIncr(tol=1e-4, max_iter=150),
        algorithm=ops.algorithm.Newton(),
        integrator=ops.integrator.LoadControl(dlam=0.1),
        constraints=ops.constraints.Plain(),
        numberer=ops.numberer.RCM(),
        system=ops.system.UmfPack(),
        analysis=ops.analysis.Static(),
    )
    s.run(n_increments=10, dt=0.1)

Each stage emits its own analysis-chain primitives, its own analyze loop (hook-wrapped if any s.add(initial_stress(...)) registered a ramp), and a between-stages cleanup block (loadConst -time 0.0 + wipeAnalysis + hook-list clear).

Multiple with ops.stage(...) blocks accumulate in registration order; they emit in that order at deck-emit time.

Validation happens on with exit: every stage must have a complete analysis chain (all six chain kwargs + the analysis directive) and an s.run(...) call.

Returns

_StageBuilder Context manager that collects per-stage records and emits a :class:StageRecord to the bridge on close.

Source code in src/apeGmsh/opensees/apesees.py
def stage(self, name: str) -> "_StageBuilder":
    """Open a staged-analysis block (Phase SSI-2.A).

    Nested ``with ops.stage(...)`` blocks are NOT supported —
    opening a second stage builder while another is still open
    raises ``RuntimeError``.  The lexical-vs-emit-order semantics
    would otherwise be confusing (the inner builder's __exit__
    fires first, registering the inner stage BEFORE the outer in
    ``_stage_records``, which is the opposite of what readers
    expect).

    Usage::

        with ops.stage(name="insitu") as s:
            s.add(ops.initial_stress(name="rock", ..., ramp_steps=10))
            s.analysis(
                test=ops.test.NormDispIncr(tol=1e-4, max_iter=150),
                algorithm=ops.algorithm.Newton(),
                integrator=ops.integrator.LoadControl(dlam=0.1),
                constraints=ops.constraints.Plain(),
                numberer=ops.numberer.RCM(),
                system=ops.system.UmfPack(),
                analysis=ops.analysis.Static(),
            )
            s.run(n_increments=10, dt=0.1)

    Each stage emits its own analysis-chain primitives, its own
    analyze loop (hook-wrapped if any ``s.add(initial_stress(...))``
    registered a ramp), and a between-stages cleanup block
    (``loadConst -time 0.0`` + ``wipeAnalysis`` + hook-list clear).

    Multiple ``with ops.stage(...)`` blocks accumulate in
    registration order; they emit in that order at deck-emit time.

    Validation happens on ``with`` exit: every stage must have a
    complete analysis chain (all six chain kwargs + the analysis
    directive) and an ``s.run(...)`` call.

    Returns
    -------
    _StageBuilder
        Context manager that collects per-stage records and emits
        a :class:`StageRecord` to the bridge on close.
    """
    if not name:
        raise ValueError("apeSees.stage: name= must be non-empty.")
    if self._open_stage_builder is not None:
        raise RuntimeError(
            "apeSees.stage: a stage is already open "
            f"(name={self._open_stage_builder._name!r}).  Close it "
            "before opening another — nested ``with ops.stage(...)``"
            " blocks would register stages in lexically-reversed "
            "order at emit time."
        )
    builder = _StageBuilder(self, str(name))
    self._open_stage_builder = builder
    return builder

region

region(*, name: str, pg: str | None = None, nodes: Iterable[int | Node] | None = None) -> None

Assign nodes to a named OpenSees Region.

Each name collects all nodes registered against it (across multiple calls, across explicit nodes= and pg= resolutions) and emits a single region $tag -node n1 n2 ... line at build time with a region tag from the build's tag plan. Useful for damping assignments and any future recorder that filters by region.

Exactly one of pg / nodes must be supplied; nodes accepts a mix of plain integer tags and :class:Node instances (matching :meth:fix / :meth:mass).

End users typically call this through :meth:Node.region or :meth:NodeSet.region rather than directly.

Source code in src/apeGmsh/opensees/apesees.py
def region(
    self,
    *,
    name: str,
    pg: str | None = None,
    nodes: Iterable[int | Node] | None = None,
) -> None:
    """Assign nodes to a named OpenSees Region.

    Each ``name`` collects all nodes registered against it
    (across multiple calls, across explicit ``nodes=`` and
    ``pg=`` resolutions) and emits a single
    ``region $tag -node n1 n2 ...`` line at build time with a
    region tag from the build's tag plan.  Useful for damping
    assignments and any future recorder that filters by region.

    Exactly one of ``pg`` / ``nodes`` must be supplied; ``nodes``
    accepts a mix of plain integer tags and :class:`Node`
    instances (matching :meth:`fix` / :meth:`mass`).

    End users typically call this through :meth:`Node.region` or
    :meth:`NodeSet.region` rather than directly.
    """
    if not name:
        raise ValueError("apeSees.region: name= must be non-empty.")
    if (pg is None) == (nodes is None):
        raise ValueError(
            "apeSees.region: supply exactly one of pg= or nodes= "
            f"(got pg={pg!r}, nodes={nodes!r})."
        )
    nodes_tuple = _iter_tags(nodes) if nodes is not None else None
    region = RegionAssignmentRecord(name=str(name), pg=pg, nodes=nodes_tuple)
    self._declare_region(region)  # K1-6: one declaration per name
    self._region_records.append(region)

analyze

analyze(*, steps: int, dt: float | None = None, strategy: 'Ladder | None' = None, profile: str | None = None, profile_run: str | None = None, profile_deep: bool = False, profile_memory: bool = False, profile_per_step: bool = False) -> int

Build + emit + run the analysis chain via the live emitter.

Builds a :class:BuiltModel, drives a :class:~apeGmsh.opensees.emitter.live.LiveOpsEmitter end-to- end, then issues the analyze call. Returns the openseespy analyze return value (0 on success).

strategy (ADR 0057 Phase A) attaches a solution-strategy ladder to the analyze loop — on a failed increment the live runner escalates through the ladder's algorithm rungs (the declared chain algorithm is rung 0), restoring rung 0 after a rescue and logging escalations to the live emitter's strategy_events. Exhaustion returns the failing rc.

When profile is given, the live run is bracketed by the Ladruno fork's stack profiler: profiler start [flags] before the analyze loop and profiler report <profile> [-run profile_run] after, with profile_deep / profile_memory / profile_per_step toggling the start flags. Requires the fork build: on stock openseespy it refuses before the domain is wiped. (Deck-mode profiling uses the explicit ops.profiler.* verbs instead, and does NOT consume the profile= kwargs here.)

Raises :class:BridgeError if the analysis chain is incomplete (one or more of constraints / numberer / system / test / algorithm / integrator / analysis is missing).

Phase SSI-2.A: staged models (ops.stage(...) blocks declared) are NOT supported by live execution. Emit a Tcl or Py deck via :meth:tcl / :meth:py and run it via the OpenSees binary / openseespy subprocess instead.

ADR 0115 D2: once the solve returns (whatever its return code), the bridge keeps a read session, so Node.read / NodeSet.read and ops.elements.get(...).read answer at the last committed state. Calling analyze again closes it at the start; eigen, run, a deck run and another bridge's live work close it too.

Source code in src/apeGmsh/opensees/apesees.py
def analyze(
    self,
    *,
    steps: int,
    dt: float | None = None,
    strategy: "Ladder | None" = None,
    profile: str | None = None,
    profile_run: str | None = None,
    profile_deep: bool = False,
    profile_memory: bool = False,
    profile_per_step: bool = False,
) -> int:
    """Build + emit + run the analysis chain via the live emitter.

    Builds a :class:`BuiltModel`, drives a
    :class:`~apeGmsh.opensees.emitter.live.LiveOpsEmitter` end-to-
    end, then issues the ``analyze`` call. Returns the openseespy
    ``analyze`` return value (0 on success).

    ``strategy`` (ADR 0057 Phase A) attaches a solution-strategy
    ladder to the analyze loop — on a failed increment the live
    runner escalates through the ladder's algorithm rungs (the
    declared chain algorithm is rung 0), restoring rung 0 after a
    rescue and logging escalations to the live emitter's
    ``strategy_events``.  Exhaustion returns the failing rc.

    When ``profile`` is given, the live run is bracketed by the Ladruno
    fork's stack profiler: ``profiler start [flags]`` before the analyze
    loop and ``profiler report <profile> [-run profile_run]`` after,
    with ``profile_deep`` / ``profile_memory`` / ``profile_per_step``
    toggling the ``start`` flags. Requires the fork build: on stock
    openseespy it refuses before the domain is wiped. (Deck-mode
    profiling uses the explicit ``ops.profiler.*`` verbs instead, and
    does NOT consume the ``profile=`` kwargs here.)

    Raises :class:`BridgeError` if the analysis chain is incomplete
    (one or more of constraints / numberer / system / test /
    algorithm / integrator / analysis is missing).

    Phase SSI-2.A: staged models (``ops.stage(...)`` blocks
    declared) are NOT supported by live execution.  Emit a Tcl
    or Py deck via :meth:`tcl` / :meth:`py` and run it via the
    OpenSees binary / openseespy subprocess instead.

    ADR 0115 D2: once the solve returns (whatever its return code),
    the bridge keeps a read session, so ``Node.read`` /
    ``NodeSet.read`` and ``ops.elements.get(...).read`` answer at the
    last committed state. Calling ``analyze`` again closes it at the
    start; ``eigen``, ``run``, a deck run and another bridge's live
    work close it too.
    """
    self._read_state = DroppedSession(
        "a later ops.analyze(...) started on this bridge and did not "
        "complete"
    )
    if self._stage_records:
        raise NotImplementedError(
            "apeSees.analyze: live execution does not support "
            "staged models in Phase SSI-2.A "
            f"(got {len(self._stage_records)} stage(s)).  Use "
            "ops.tcl(path, run=True) or ops.py(path, run=True) to "
            "emit a staged deck and run it via the OpenSees binary "
            "/ openseespy subprocess instead."
        )
    self._check_analysis_chain_for_analyze(
        strategy_attached=strategy is not None)
    if strategy is not None:
        strategy.check_live()
    self._check_explicit_solver_compat()

    # Local import — keeps openseespy out of import-time for users
    # who only emit Tcl / py.
    from .emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe

    if profile is not None:
        from .procedures._modal import refuse_fork_verb_before_wipe

        refuse_fork_verb_before_wipe(
            self, "apeSees.analyze(profile=...)", "the fork's profiler")
    bm = self.build()
    self._assert_fork_if_required()
    refuse_fork_chain_before_wipe(bm)
    live_emitter = LiveOpsEmitter(wipe=True)
    # Retain for post-run live queries (e.g. ladruno_projection_tie_force);
    # the in-process openseespy session stays alive after analyze returns.
    self._live_emitter = live_emitter
    bm.emit(live_emitter)
    # A Linear rung of the ladder solves steps too, and the emit above
    # never saw the ladder: warn here for a recorder that reads an
    # upstream shell's stale sections. A Linear base already warned.
    if strategy is not None:
        from .analysis.algorithm import Linear as _LinearAlgorithm
        base_algo = next(
            (p for p in reversed(self._primitives)
             if isinstance(p, SolutionAlgorithm)),
            None,
        )
        if not isinstance(base_algo, _LinearAlgorithm):
            from ._internal.build.validators.shell_probe import (
                warn_stale_shell_probe_under_linear,
            )
            warn_stale_shell_probe_under_linear(
                bm.fem,
                bm._tag_plan(emit_mode(
                    bm,
                    supports_partitions=(
                        live_emitter.caps.supports_partitions),
                )).elements.specs,
                [p for p in bm.primitives if isinstance(p, Recorder)],
                staged=False,
                flat_algorithms=strategy.rungs,
                stage_chain=[],
            )
    self._artifacts.after_emit(self)
    if profile is not None:
        start_flags: list[str] = []
        if profile_deep:
            start_flags.append("-deep")
        if profile_memory:
            start_flags.append("-memory")
        if profile_per_step:
            start_flags.append("-perStep")
        live_emitter.profiler("start", *start_flags)
    spec: StrategySpec | None = None
    if strategy is not None:
        # Rung 0 = the flat chain's declared algorithm (the last
        # one registered wins, matching emission order).
        base = next(
            (p for p in reversed(self._primitives)
             if isinstance(p, SolutionAlgorithm)),
            None,
        )
        spec = strategy.to_spec(base=base)
    result: int = int(
        live_emitter.analyze(steps=steps, dt=dt, strategy=spec)
    )
    # ADR 0115 D2: the element plan the live emit just read (memoised
    # by ``bm.emit``, so this mints nothing) rides the session, which
    # then never needs the allocator or a build to answer a read.
    live_plan = bm._tag_plan(emit_mode(
        bm,
        supports_partitions=live_emitter.caps.supports_partitions))
    self._read_state = open_session(
        live_emitter, ndm=bm.ndm,
        element_plan=tuple(live_plan.elements.specs),
    )
    if profile is not None:
        report_args: list[str] = [profile]
        if profile_run is not None:
            report_args += ["-run", profile_run]
        live_emitter.profiler("report", *report_args)
    return result

ladruno_projection_tie_force

ladruno_projection_tie_force(node: int, dof: int) -> float

Tie force f = M(a_raw - a_proj) at (node, dof) from the last projection step (≈ LS-DYNA *DATABASE_NCFORC).

Recovers the interface force a non-matching equation-tied interface (g.constraints.tie(..., enforce="equation")) carries, via the fork ladrunoProjectionTieForce query (ADR-30 P3 / ADR 0068 P5). dof is 1-based (OpenSees convention).

Requires a prior live :meth:analyze with a LadrunoProjection constraint handler active. Fork-only: a stock build raises RuntimeError (see :data:~apeGmsh.opensees.emitter.live. _TIE_FORCE_FORK_REQUIRED).

For a recorded time history of the tie force instead of a single post-run value, use the recorder route: ops.recorder.Ladruno(nodal_responses=("constraintTieForce",)) and read it back with results.nodes.get(component="constraint_tie_force_x") (explicit analyses only — the recorder channel is scattered by the explicit CentralDifferenceLadruno integrator).

Source code in src/apeGmsh/opensees/apesees.py
def ladruno_projection_tie_force(self, node: int, dof: int) -> float:
    """Tie force ``f = M(a_raw - a_proj)`` at ``(node, dof)`` from the last
    projection step (≈ LS-DYNA ``*DATABASE_NCFORC``).

    Recovers the interface force a non-matching equation-tied interface
    (``g.constraints.tie(..., enforce="equation")``) carries, via the fork
    ``ladrunoProjectionTieForce`` query (ADR-30 P3 / ADR 0068 P5). ``dof``
    is 1-based (OpenSees convention).

    Requires a prior **live** :meth:`analyze` with a ``LadrunoProjection``
    constraint handler active. Fork-only: a stock build raises
    ``RuntimeError`` (see :data:`~apeGmsh.opensees.emitter.live.
    _TIE_FORCE_FORK_REQUIRED`).

    For a recorded **time history** of the tie force instead of a single
    post-run value, use the recorder route:
    ``ops.recorder.Ladruno(nodal_responses=("constraintTieForce",))`` and
    read it back with
    ``results.nodes.get(component="constraint_tie_force_x")`` (explicit
    analyses only — the recorder channel is scattered by the explicit
    ``CentralDifferenceLadruno`` integrator).
    """
    if self._live_emitter is None:
        raise no_live_domain_error(
            "ladruno_projection_tie_force", self._read_state,
            "Call analyze(...) first (the live path); the query reads "
            "the last projection step. For a recorded time history, record "
            "ops.recorder.Ladruno(nodal_responses=('constraintTieForce',)) "
            "and read results.nodes.get(component='constraint_tie_force_x')."
        )
    return self._live_emitter.ladruno_projection_tie_force(node, dof)

augment

augment(*, element: int, tol: float = 1e-08, max_passes: int = 10) -> 'AbstractContextManager[list[float]]'

Run an ADR-41 held-load augmentation sweep on a live run and yield its per-pass constraint-violation history.

The supported way to close an enforce="al" coupling's constraint gap within one step (fork PR #839 §3.2): enforce="al" alone advances its Uzawa recursion once per committed step, so a single push leaves the penalty gap c/K_t standing. Forwards to :meth:~apeGmsh.opensees.emitter.live.LiveOpsEmitter.augment, which owns the whole recipe (ladrunoBeginAugment → integrator LoadControl 0.0 → held passes polling constraintViolation → ladrunoEndAugment + the caller's integrator restored). Read that docstring for the semantics; the passes all run on entry, so the with body is a placeholder and displacements must be read after the block::

ops.analyze(steps=1)                 # the real step
with ops.augment(element=tag, tol=1e-8) as gaps:
    pass
assert gaps[-1] < 1e-8
Parameters

element : int Emitted OpenSees tag of the LadrunoKinematicCoupling. apeGmsh has no name → emitted-tag lookup (the constraint name rides the comment channel only), so the tag has to come from the live domain: max(openseespy.opensees.getEleTags()) when the coupling is the last element emitted, or a scan of a written model.h5 for the "LadrunoKinematicCoupling" type_token (OpenSeesModel.elements()). tol : float, default 1e-8 Stop once the violation falls below this. max_passes : int, default 10 Hard cap on held-load passes; exceeding it raises.

Raises

BridgeError When no live analysis has run; when no integrator was recorded through the live emitter; when tol is not met within max_passes. Also on a stock (non-fork) build, or a nested sweep (RuntimeError).

Source code in src/apeGmsh/opensees/apesees.py
def augment(
    self, *, element: int, tol: float = 1.0e-8, max_passes: int = 10,
) -> "AbstractContextManager[list[float]]":
    """Run an ADR-41 held-load augmentation sweep on a live run and
    yield its per-pass constraint-violation history.

    The supported way to close an ``enforce="al"`` coupling's constraint
    gap **within** one step (fork PR #839 §3.2): ``enforce="al"`` alone
    advances its Uzawa recursion once per *committed* step, so a single
    push leaves the penalty gap ``c/K_t`` standing. Forwards to
    :meth:`~apeGmsh.opensees.emitter.live.LiveOpsEmitter.augment`, which
    owns the whole recipe (``ladrunoBeginAugment`` →
    ``integrator LoadControl 0.0`` → held passes polling
    ``constraintViolation`` → ``ladrunoEndAugment`` + the caller's
    integrator restored). Read that docstring for the semantics; the
    passes all run on **entry**, so the ``with`` body is a placeholder
    and displacements must be read **after** the block::

        ops.analyze(steps=1)                 # the real step
        with ops.augment(element=tag, tol=1e-8) as gaps:
            pass
        assert gaps[-1] < 1e-8

    Parameters
    ----------
    element : int
        Emitted OpenSees tag of the ``LadrunoKinematicCoupling``.
        apeGmsh has **no name → emitted-tag lookup** (the constraint
        name rides the comment channel only), so the tag has to come
        from the live domain: ``max(openseespy.opensees.getEleTags())``
        when the coupling is the last element emitted, or a scan of a
        written ``model.h5`` for the ``"LadrunoKinematicCoupling"``
        ``type_token`` (``OpenSeesModel.elements()``).
    tol : float, default 1e-8
        Stop once the violation falls below this.
    max_passes : int, default 10
        Hard cap on held-load passes; exceeding it raises.

    Raises
    ------
    BridgeError
        When no live analysis has run; when no integrator was recorded
        through the live emitter; when ``tol`` is not met within
        ``max_passes``. Also on a stock (non-fork) build, or a nested
        sweep (``RuntimeError``).
    """
    if self._live_emitter is None:
        raise no_live_domain_error(
            "augment", self._read_state,
            "Call "
            "analyze(...) first (the live path) — the sweep drives the "
            "in-process domain that step left standing. There is no "
            "deck-emission equivalent: ladrunoBeginAugment / "
            "ladrunoEndAugment are issued interactively around held "
            "passes, not written into a Tcl / py deck."
        )
    return self._live_emitter.augment(
        element=element, tol=tol, max_passes=max_passes,
    )

tcl

tcl(path: str, *, run: bool = False, bin: str | None = None, analyze_steps: int | None = None, analyze_dt: float | None = None, per_rank: bool = False, flat: bool = False, stream: bool = False, verbose: bool = False, log: str | None = None, progress: bool = True) -> 'RunReport | None'

Emit a Tcl deck to path; optionally subprocess OpenSees.

When run=True the OpenSees subprocess output is always tee'd to a log file — log (a path) overrides, otherwise it is <path>.log next to the deck. Console output is opt-in via verbose: False (default) prints begin / op / end only; True adds a live step counter (parsed from the APEGMSH_PROGRESS markers progress=True injects into the analyze loop) plus streamed warning lines. A failed run raises RuntimeError carrying the log tail + path, never the whole buffer: a non-zero exit, or an exit of 0 whose log lacks the run driver's completion line (OpenSees.exe exits 0 after a Tcl error, the deck's aborted-analyze guard included). verbose / log / progress are inert when run=False.

run=True returns a frozen :class:~apeGmsh.opensees._run.RunReport (ADR 0106 Amendment 1): returncode, log, elapsed_s, increments (the analyze increments the deck's progress markers prove completed; None with progress=False) and solver_stats — the ADR 0106 D1 :class:~apeGmsh.opensees._solver_stats.RunSolverStats when the deck declared Pardiso(stats=True) anywhere, else None. run=False returns None.

When analyze_steps is supplied, an analyze line is appended to the deck after every other primitive — wrapped in a hook-dispatching for-loop if any :meth:initial_stress calls registered step hooks (Phase SSI-1). Without analyze_steps, the emitted deck declares the model but does not drive an analysis. With it, the deck's last action, once the loop returns, closes every recorder (.out included) and writes <mpco file>.run.json beside each MPCO recorder's output (#2210; read_deck_mpco); the automatic model.h5 is then written before the deck file.

per_rank=True (ADR 0061) writes a driver deck at path plus one ranks/rank<K>_<seq>.tcl fragment per if {[getPID] == K} { ... } block; the driver guards each fragment behind a one-line source so every MPI rank parses only the driver plus its own fragments — O(global + model/np) instead of O(model) per rank. Layout-only: the deck semantics (including the single-process rank-0 fallback) are unchanged. Requires a partitioned model (len(fem.partitions) > 1).

flat=True forces the single-domain (serial) emit even when the model carries partitions — e.g. a composed model, which is auto-partitioned one-rank-per-module (ADR 0038 §"Rank model") and would otherwise take the per-rank fan-out. The deck declares the whole model in one domain with no getPID brackets, exactly as the live in-process runner and modal decks emit it. This is the Tcl route for serial-only records (g.embed ties; fork contact before ADR 0092 S4 landed partitioned emit, and still the escape hatch for the contact cases the partitioned path refuses) on a composed model. Mutually exclusive with per_rank; a no-op on an already-unpartitioned model.

stream=True (ADR 0065 Tier 2 / plan_emit_memory_columnar.md A1–A3) writes the deck through a live file sink instead of accumulating the line buffer, so peak emit memory stops scaling with deck size. Output is byte-identical to the default list mode, including under per_rank=True, where the fragment files are live-routed (partition_open switches the sink) rather than sliced post-hoc. Everything goes to .tmp siblings promoted atomically on clean completion — a mid-emit exception never leaves a half-written deck.

Source code in src/apeGmsh/opensees/apesees.py
def tcl(
    self,
    path: str,
    *,
    run: bool = False,
    bin: str | None = None,
    analyze_steps: int | None = None,
    analyze_dt: float | None = None,
    per_rank: bool = False,
    flat: bool = False,
    stream: bool = False,
    verbose: bool = False,
    log: str | None = None,
    progress: bool = True,
) -> "RunReport | None":
    """Emit a Tcl deck to ``path``; optionally subprocess OpenSees.

    When ``run=True`` the OpenSees subprocess output is **always**
    tee'd to a log file — ``log`` (a path) overrides, otherwise it
    is ``<path>.log`` next to the deck. Console output is opt-in via
    ``verbose``: ``False`` (default) prints begin / op / end only;
    ``True`` adds a live step counter (parsed from the
    ``APEGMSH_PROGRESS`` markers ``progress=True`` injects into the
    analyze loop) plus streamed warning lines. A failed run raises
    ``RuntimeError`` carrying the log tail + path, never the whole
    buffer: a non-zero exit, or an exit of 0 whose log lacks the
    run driver's completion line (``OpenSees.exe`` exits 0 after a
    Tcl ``error``, the deck's aborted-analyze guard included).
    ``verbose`` / ``log`` / ``progress`` are inert when
    ``run=False``.

    ``run=True`` returns a frozen
    :class:`~apeGmsh.opensees._run.RunReport` (ADR 0106 Amendment 1):
    ``returncode``, ``log``, ``elapsed_s``, ``increments`` (the
    analyze increments the deck's ``progress`` markers prove
    completed; ``None`` with ``progress=False``) and
    ``solver_stats`` — the ADR 0106 D1
    :class:`~apeGmsh.opensees._solver_stats.RunSolverStats` when the
    deck declared ``Pardiso(stats=True)`` anywhere, else ``None``.
    ``run=False`` returns ``None``.

    When ``analyze_steps`` is supplied, an ``analyze`` line is
    appended to the deck after every other primitive — wrapped in
    a hook-dispatching for-loop if any
    :meth:`initial_stress` calls registered step hooks (Phase
    SSI-1).  Without ``analyze_steps``, the emitted deck declares
    the model but does not drive an analysis.  With it, the deck's last
    action, once the loop returns, closes every recorder (``.out``
    included) and writes ``<mpco file>.run.json`` beside each MPCO
    recorder's output (#2210; ``read_deck_mpco``); the automatic
    ``model.h5`` is then written before the deck file.

    ``per_rank=True`` (ADR 0061) writes a driver deck at ``path``
    plus one ``ranks/rank<K>_<seq>.tcl`` fragment per
    ``if {[getPID] == K} { ... }`` block; the driver guards each
    fragment behind a one-line ``source`` so every MPI rank parses
    only the driver plus its own fragments — O(global + model/np)
    instead of O(model) per rank.  Layout-only: the deck semantics
    (including the single-process rank-0 fallback) are unchanged.
    Requires a partitioned model (``len(fem.partitions) > 1``).

    ``flat=True`` forces the single-domain (serial) emit even when
    the model carries partitions — e.g. a composed model, which is
    auto-partitioned one-rank-per-module (ADR 0038 §"Rank model")
    and would otherwise take the per-rank fan-out.  The deck
    declares the whole model in one domain with no ``getPID``
    brackets, exactly as the live in-process runner and modal decks
    emit it.  This is the Tcl route for serial-only records
    (``g.embed`` ties; fork contact before ADR 0092 S4 landed
    partitioned emit, and still the escape hatch for the contact
    cases the partitioned path refuses) on a composed model.
    Mutually exclusive with ``per_rank``; a no-op on
    an already-unpartitioned model.

    ``stream=True`` (ADR 0065 Tier 2 / plan_emit_memory_columnar.md
    A1–A3) writes the deck through a live file sink instead of
    accumulating the line buffer, so peak emit memory stops scaling
    with deck size. Output is byte-identical to the default list
    mode, including under ``per_rank=True``, where the fragment
    files are live-routed (``partition_open`` switches the sink)
    rather than sliced post-hoc. Everything goes to ``.tmp``
    siblings promoted atomically on clean completion — a mid-emit
    exception never leaves a half-written deck.
    """
    from ._mpm import (
        remove_stale_particle_set,
        stale_particle_set,
        write_deck_then_remove,
        write_particle_set,
    )
    from .emitter.tcl import TclEmitter, deck_backend

    if flat and per_rank:
        raise ValueError(
            "apeSees.tcl: flat=True and per_rank=True are mutually "
            "exclusive — flat forces the single-domain (serial) "
            "emit; per_rank splits the partitioned fan-out "
            "(ADR 0061). Drop one of the two flags."
        )
    bm = self.build()
    emitter = TclEmitter(backend=deck_backend(self._opensees))
    emitter._emit_progress = bool(progress)
    emitter._run_record = analyze_steps is not None
    # ADR 0134 D1: an MPM model's particle set is seeded and checked
    # here, before anything is written; it is written with the deck.
    # A deck with no mpm members drops the apeGmsh set the deck it
    # overwrites reads (decided here, removed once the deck is in place).
    particles = None
    stale = None
    if bm.mpm_members():
        particles = self._mpm_prepare(bm, path, per_rank=per_rank)
        emitter.bind_particle_set(str(particles.path))
    else:
        stale = stale_particle_set(path)
    # ADR 0099 S5: ``per_rank`` is applied around / after ``bm.emit``
    # (live fragment routing under ``stream``, post-hoc span slicing
    # otherwise), so the INV-4 gate inside emit cannot see it. Stamp
    # it on the emitter — the same seam ``supports_partitions`` uses.
    emitter.caps = replace(emitter.caps, per_rank_fragments=bool(per_rank))
    if flat:
        # Force the single-domain emit for a partition-carrying fem
        # (e.g. a composed model auto-partitioned one-rank-per-module,
        # ADR 0038) — the same seam the live in-process runner and
        # modal decks use. Serial-only records (g.embed ties, plus
        # the contact cases ADR 0092 S4's partitioned fan-out
        # refuses — SOFT, staged, undecidable owner) emit on this
        # path.
        emitter.caps = replace(emitter.caps, supports_partitions=False)
    pre_prof, post_prof = self._split_profiler_records()
    if stream:
        # ADR 0065 Tier 2: write-through sink; per-rank
        # fragment files are live-routed by
        # partition_open/partition_close.
        emitter.stream_to(path, per_rank=per_rank)
    try:
        emit_deck_tail(self, emitter, bm, pre_prof, post_prof,
                       analyze_steps, analyze_dt, path)
        if stream and per_rank and (
            emitter.stream_fragment_count() == 0
        ):
            raise ValueError(
                "apeSees.tcl: per_rank=True requires a "
                "partitioned model (len(fem.partitions) > 1) — "
                "the emitted deck has no per-rank blocks to "
                "split out. Partition the mesh "
                "(g.mesh.partitioning) or drop per_rank."
            )
        if particles is not None:
            # The deck emitted whole; the set lands before the deck is
            # promoted, so no deck exists without its set (ADR 0134 D1).
            write_particle_set(particles)
        if stream:
            # Promotion runs INSIDE the guarded region (review
            # hardening): a failing os.replace mid-promotion
            # (Windows file lock / antivirus) routes to
            # stream_abort below, which removes every remaining
            # .tmp. Fragments already promoted by the partial
            # loop stay in place — the driver is promoted LAST,
            # so no deck entry point exists until everything it
            # sources does; a clean re-run overwrites the
            # leftovers via os.replace.
            emitter.stream_finish()
    except BaseException:
        if stream:
            # Leave no half-written deck: remove every .tmp
            # (final paths are only ever created by a COMPLETE
            # promotion pass, except fragments promoted before
            # a mid-promotion failure — see stream_finish;
            # ADR 0065 Tier 2 Decision §4).
            emitter.stream_abort()
        raise
    if not stream and per_rank:
        spans = emitter.partition_spans()
        if not spans:
            raise ValueError(
                "apeSees.tcl: per_rank=True requires a "
                "partitioned model (len(fem.partitions) > 1) — "
                "the emitted deck has no per-rank blocks to "
                "split out. Partition the mesh "
                "(g.mesh.partitioning) or drop per_rank."
            )
        # line_buffer(): read-only, no deck-sized copy (ADR 0065 A0).
        _write_per_rank_tcl(path, emitter.line_buffer(), spans)
    elif not stream:
        # ADR 0134 D1: a stale set goes only once its deck is replaced.
        write_deck_then_remove(path, emitter.write_to, stale)
        stale = None
    # A streamed or per-rank deck is in place now: its stale set goes.
    remove_stale_particle_set(stale)
    self._artifacts.after_emit(self)

    if not run:
        return None

    self._read_state = DroppedSession(
        DECK_RUN_CAUSE.format(verb="ops.tcl(..., run=True)"))
    deck_run = begin_deck_run(
        self, bm, emitter, path, verb="ops.tcl(..., run=True)")
    self._deck_run = deck_run
    binary = _resolve_opensees_binary(bin, self._opensees)
    # OpenSees.exe exits 0 after a Tcl ``error`` (an aborted analyze
    # included), so the exit code proves nothing: a sibling driver
    # sources the deck unchanged and prints a marker only when the
    # deck ran to its end (ADR 0115 D3).
    log_path = resolve_log_path(log, path)
    report = stream_run(
        [binary, write_tcl_driver(path)],
        log_path=log_path,
        verbose=verbose,
        label=run_label(path, analyze_steps, analyze_dt),
        header="OpenSees",
        deck_path=path,
        expect_solver_stats=_deck_requested_solver_stats(emitter),
        expected_loops=deck_progress_loops(path) if progress else None,
        proves_completion=log_proves_completion,
        completion_line=RUN_COMPLETE_MARKER,
    )
    if log_proves_completion(log_path):
        self._deck_run = deck_run.finish()
    return report

modal_deck

modal_deck(path: str, *, solver: str = 'feast', band: 'tuple[float, float] | None' = None, num_modes: int | None = None, certify: bool = False, target: str = 'tcl', out: str = 'eigenvalues.out') -> None

Emit a distributed modal deck (ADR 0077 Tier 1) — two backends.

solver="feast" (default) emits the replicated FEAST deck described below; solver="arpack" emits the partitioned ARPACK deck (Tier 1B) — see :meth:_modal_deck_arpack for that half. They invert each other on the two facts that matter (flat vs partitioned emit; system inert vs load-bearing), so the docs are kept apart rather than merged.

Which to use. "arpack" when the model does not fit on one node: it is the only backend where both the storage and the factorization are distributed. "feast" when you want a frequency window rather than the lowest N, or -certify completeness. Neither for a model that fits on one node — Tier 0 (:meth:eigen / :meth:modal_properties on the unpartitioned build) is faster at every size measured and is the only route to correct participation factors and effective modal mass.

FEAST backend (solver="feast", needs band=)

Writes a flat Tcl deck — every MPI rank builds the FULL model — that runs band-targeted FEAST under OpenSeesMP: eigen -feast band[0] band[1] -rci routes each contour solve through the distributed dmumps kernel (fork ADR 43, L3-only: every rank holds the full (K, M) CSR and the kernel slices the 2n block system's triplets across ranks). Distribution lives inside the RCI kernel, not in domain decomposition — a partitioned if {[getPID]==K} deck fails FeastEigenSOE::setSize (P2 live finding), so partitions on the model are ignored here (the deck is emitted flat) and the deck's system line plays no part in the FEAST solve. RAM trade-off: the full model is assembled on every rank (the documented L3 regime, ~1e5–1e6 DOF).

The band (Hz) defines the mode count; there is no num_modes. The deck is the HPC entry point (ops.run_remote / Cluster.submit, ADR 0060) and also runs single-process under plain OpenSees (serial FEAST — the getPID shim makes the rank-0 write-out unconditional).

modalProperties is not emitted: it is MPI-blind upstream (wrong effective mass under any multi-rank run; ADR 0077 INV-2). For participation factors run the single-process :meth:modal_properties (Tier 0). Harvest with :meth:ParallelModalResult.from_job — eigenvalues from the rank-0 write-out plus mode shapes (ADR 0077 P3): the deck records one mode_shape_<k>.out per found mode from rank 0 (the replicated model puts ALL nodes on every rank) with a mode_shapes.json sidecar pinning the node→column map (sorted mesh node tags × ndf DOFs).

Parameters

path Deck output path. solver "feast" (default, replicated band solve) or "arpack" (partitioned lowest-N solve, Tier 1B). band (f_min, f_max) frequency band in Hz; needs 0 <= f_min < f_max. FEAST only — rejected for solver="arpack", whose selection axis is a mode count. num_modes Number of modes to extract. ARPACK only — rejected for solver="feast", where the contour is the band and the found count is dynamic. certify Emit -certify (fork Sturm/inertia completeness check). FEAST only. target "tcl" (the classic-Tcl deck). Each solver needs its own fork build: FEAST the classic-Tcl -feast parity build (fork PR #578), ARPACK the MP eigen wiring (fork PR #668, 5a522b03b). "pymp" (an OpenSeesMP-Python deck, ADR 0077 unlock 2a) raises for both solvers — for ARPACK because the modern interpreter still builds its ArpackSOE bare (the same latent F1 defect; #668 is classic-Tcl only). out Rank-0 eigenvalue write-out filename (read by :meth:ParallelModalResult.from_job).

Raises

ValueError If solver is unknown, if the band / mode-count arguments do not match the chosen solver, if band is invalid, if solver="arpack" is given an unpartitioned model, or if a non-Mumps system is declared on an ARPACK deck. NotImplementedError If target != "tcl" or the model has registered stages.

Source code in src/apeGmsh/opensees/apesees.py
def modal_deck(
    self,
    path: str,
    *,
    solver: str = "feast",
    band: "tuple[float, float] | None" = None,
    num_modes: int | None = None,
    certify: bool = False,
    target: str = "tcl",
    out: str = "eigenvalues.out",
) -> None:
    """Emit a distributed modal deck (ADR 0077 Tier 1) — two backends.

    ``solver="feast"`` (default) emits the **replicated** FEAST deck
    described below; ``solver="arpack"`` emits the **partitioned**
    ARPACK deck (Tier 1B) — see
    :meth:`_modal_deck_arpack` for that half. They invert each
    other on the two facts that matter (flat vs partitioned emit;
    ``system`` inert vs load-bearing), so the docs are kept apart
    rather than merged.

    **Which to use.** ``"arpack"`` when the model does not fit on one
    node: it is the only backend where both the storage *and* the
    factorization are distributed. ``"feast"`` when you want a
    frequency window rather than the lowest N, or ``-certify``
    completeness. **Neither** for a model that fits on one node —
    Tier 0 (:meth:`eigen` / :meth:`modal_properties` on the
    unpartitioned build) is faster at every size measured and is the
    only route to correct participation factors and effective modal
    mass.

    FEAST backend (``solver="feast"``, needs ``band=``)
    --------------------------------------------------
    Writes a **flat** Tcl deck — every MPI rank builds the FULL model —
    that runs band-targeted FEAST under ``OpenSeesMP``: ``eigen -feast
    band[0] band[1] -rci`` routes each contour solve through the
    distributed ``dmumps`` kernel (fork ADR 43, **L3-only**: every rank
    holds the full ``(K, M)`` CSR and the kernel slices the 2n block
    system's triplets across ranks). Distribution lives inside the RCI
    kernel, **not** in domain decomposition — a partitioned
    ``if {[getPID]==K}`` deck fails ``FeastEigenSOE::setSize`` (P2
    live finding), so partitions on the model are ignored here (the
    deck is emitted flat) and the deck's ``system`` line plays no part
    in the FEAST solve. RAM trade-off: the full model is assembled on
    every rank (the documented L3 regime, ~1e5–1e6 DOF).

    The band (Hz) defines the mode count; there is no ``num_modes``.
    The deck is the HPC entry point (``ops.run_remote`` /
    ``Cluster.submit``, ADR 0060) and also runs single-process under
    plain ``OpenSees`` (serial FEAST — the ``getPID`` shim makes the
    rank-0 write-out unconditional).

    ``modalProperties`` is **not** emitted: it is MPI-blind upstream
    (wrong effective mass under any multi-rank run; ADR 0077 INV-2).
    For participation factors run the single-process
    :meth:`modal_properties` (Tier 0). Harvest with
    :meth:`ParallelModalResult.from_job` — eigenvalues from the
    rank-0 write-out plus mode shapes (ADR 0077 P3): the deck
    records one ``mode_shape_<k>.out`` per found mode from rank 0
    (the replicated model puts ALL nodes on every rank) with a
    ``mode_shapes.json`` sidecar pinning the node→column map
    (sorted mesh node tags × ``ndf`` DOFs).

    Parameters
    ----------
    path
        Deck output path.
    solver
        ``"feast"`` (default, replicated band solve) or ``"arpack"``
        (partitioned lowest-N solve, Tier 1B).
    band
        ``(f_min, f_max)`` frequency band in Hz; needs
        ``0 <= f_min < f_max``. **FEAST only** — rejected for
        ``solver="arpack"``, whose selection axis is a mode count.
    num_modes
        Number of modes to extract. **ARPACK only** — rejected for
        ``solver="feast"``, where the contour *is* the band and the
        found count is dynamic.
    certify
        Emit ``-certify`` (fork Sturm/inertia completeness check).
        **FEAST only.**
    target
        ``"tcl"`` (the classic-Tcl deck). Each solver needs its own
        fork build: FEAST the classic-Tcl ``-feast`` parity build
        (fork PR #578), ARPACK the MP eigen wiring (fork PR #668,
        ``5a522b03b``). ``"pymp"`` (an
        OpenSeesMP-Python deck, ADR 0077 unlock 2a) raises for both
        solvers — for ARPACK because the modern interpreter still
        builds its ``ArpackSOE`` bare (the same latent F1 defect;
        #668 is classic-Tcl only).
    out
        Rank-0 eigenvalue write-out filename (read by
        :meth:`ParallelModalResult.from_job`).

    Raises
    ------
    ValueError
        If ``solver`` is unknown, if the band / mode-count arguments
        do not match the chosen solver, if ``band`` is invalid, if
        ``solver="arpack"`` is given an unpartitioned model, or if a
        non-``Mumps`` system is declared on an ARPACK deck.
    NotImplementedError
        If ``target != "tcl"`` or the model has registered stages.
    """
    from .emitter.tcl import TclEmitter, deck_backend

    if solver not in ("feast", "arpack"):
        raise ValueError(
            "apeSees.modal_deck: solver must be 'feast' (replicated "
            "band solve) or 'arpack' (partitioned lowest-N solve), "
            f"got {solver!r}."
        )
    if target != "tcl":
        raise NotImplementedError(
            "apeSees.modal_deck: target='pymp' (an OpenSeesMP-Python "
            "deck) is ADR 0077 unlock 2a and not implemented yet; use "
            "target='tcl'. For solver='arpack' this is not just "
            "unimplemented: the modern interpreter (openseespy / PyMP) "
            "still builds its ArpackSOE bare, so the distributed-eigen "
            "wiring of fork PR #668 is classic-Tcl only."
        )
    if self._stage_records:
        raise NotImplementedError(
            "apeSees.modal_deck: staged models are not supported "
            "(per-stage parallel modal is deferred, ADR 0077 / "
            f"SSI-2.A) (got {len(self._stage_records)} stage(s))."
        )
    self._guard_modal_deck_constraint_handler()
    if solver == "arpack":
        if band is not None or certify:
            raise ValueError(
                "apeSees.modal_deck: band= / certify= are FEAST-only "
                "(the contour is the band). solver='arpack' selects "
                "the lowest num_modes= modes; drop band=/certify= or "
                "use solver='feast'."
            )
        if num_modes is None or int(num_modes) < 1:
            raise ValueError(
                "apeSees.modal_deck: solver='arpack' needs "
                f"num_modes >= 1, got {num_modes!r}."
            )
        self._modal_deck_arpack(
            path, num_modes=int(num_modes), out=out,
        )
        return

    if num_modes is not None:
        raise ValueError(
            "apeSees.modal_deck: num_modes= is ARPACK-only — for "
            "solver='feast' the contour IS the band and the found "
            "mode count is dynamic. Pass band= only, or use "
            "solver='arpack'."
        )
    if band is None:
        raise ValueError(
            "apeSees.modal_deck: solver='feast' needs band="
            "(f_min, f_max) in Hz."
        )
    f_min, f_max = band
    if not (0.0 <= f_min < f_max):
        raise ValueError(
            "apeSees.modal_deck: need 0 <= band[0] < band[1], got "
            f"{band!r}."
        )

    bm = self.build()
    emitter = TclEmitter(backend=deck_backend(self._opensees))
    # L3 FEAST needs the FULL model on every rank — force the flat
    # (replicated) emit even for a partition-authored fem, exactly as
    # the live emitter does (ADR 0077 P2 live finding).
    emitter.caps = replace(emitter.caps, supports_partitions=False)
    bm.emit(emitter)
    # Deterministic eigen preamble (every rank identical). The handler
    # matters (Penalty pollutes M, Lagrange injects zero-mass DOFs →
    # spurious modes); the numberer must number identically on every
    # rank (RCM); the system line is NOT in the FEAST solve path — a
    # serial UmfPack is correct even for the distributed run.
    emitter.constraints("Transformation")
    emitter.numberer("RCM")
    emitter.system("UmfPack")
    # P3 mode-shape harvest: pin the recorder column order to the
    # sorted mesh node tags (the sidecar the deck writes lets
    # ParallelModalResult.from_job map columns back without the deck).
    # Mesh nodes only — bridge-declared extra nodes (decoupled nodes)
    # are not harvested.
    shape_tags = tuple(sorted(int(t) for t in bm.fem.nodes.ids))
    emitter.eigen_feast_parallel(
        f_min, f_max, certify=certify, out=out,
        shape_nodes=shape_tags, shape_ndf=bm.ndf, shape_ndm=bm.ndm,
    )

    with open(path, "w", encoding="utf-8") as f:
        emitter.write_to(f)
    self._artifacts.after_emit(self)

py

py(path: str, *, run: bool = False, analyze_steps: int | None = None, analyze_dt: float | None = None, python: str | None = None, stream: bool = False, verbose: bool = False, log: str | None = None, progress: bool = True) -> 'RunReport | None'

Emit an openseespy Python deck to path; optionally run it.

run=True streams the openseespy subprocess exactly like :meth:tcl — full output always tee'd to a log (log path override, else <path>.log), console opt-in via verbose, a live step counter from the progress markers, and a tail-only RuntimeError on a non-zero exit. verbose / log / progress are inert when run=False. The return is :meth:tcl's: a frozen :class:~apeGmsh.opensees._run.RunReport for run=True (ADR 0106 Amendment 1), None for run=False.

analyze_steps / analyze_dt semantics mirror :meth:tcl (Phase SSI-1).

stream=True is out of scope for the Python deck emitter (v1) and fails loud — the HPC path is Tcl (ADR 0065 Tier 2 / plan_emit_memory_columnar.md A1–A3); use ops.tcl(path, stream=True).

Source code in src/apeGmsh/opensees/apesees.py
def py(
    self,
    path: str,
    *,
    run: bool = False,
    analyze_steps: int | None = None,
    analyze_dt: float | None = None,
    python: str | None = None,
    stream: bool = False,
    verbose: bool = False,
    log: str | None = None,
    progress: bool = True,
) -> "RunReport | None":
    """Emit an openseespy Python deck to ``path``; optionally run it.

    ``run=True`` streams the openseespy subprocess exactly like
    :meth:`tcl` — full output always tee'd to a log (``log`` path
    override, else ``<path>.log``), console opt-in via ``verbose``,
    a live step counter from the ``progress`` markers, and a
    tail-only ``RuntimeError`` on a non-zero exit. ``verbose`` /
    ``log`` / ``progress`` are inert when ``run=False``. The return
    is :meth:`tcl`'s: a frozen
    :class:`~apeGmsh.opensees._run.RunReport` for ``run=True``
    (ADR 0106 Amendment 1), ``None`` for ``run=False``.

    ``analyze_steps`` / ``analyze_dt`` semantics mirror :meth:`tcl`
    (Phase SSI-1).

    ``stream=True`` is out of scope for the Python deck emitter
    (v1) and fails loud — the HPC path is Tcl (ADR 0065 Tier 2 /
    plan_emit_memory_columnar.md A1–A3); use
    ``ops.tcl(path, stream=True)``.
    """
    from ._mpm import (
        stale_particle_set,
        write_deck_then_remove,
        write_particle_set,
    )
    from .emitter.py import PyEmitter
    from .emitter.tcl import deck_backend

    if stream:
        raise ValueError(
            "apeSees.py: stream=True is not supported for the "
            "Python deck emitter (v1) — the HPC path is Tcl "
            "(ADR 0065 Tier 2 / plan_emit_memory_columnar.md "
            "A1–A3); use ops.tcl(path, stream=True) instead."
        )
    bm = self.build()
    emitter = PyEmitter(backend=deck_backend(self._opensees))
    emitter._emit_progress = bool(progress)
    emitter._run_record = analyze_steps is not None
    # ADR 0134 D1: as tcl(), the set is checked before anything is
    # written and written with the deck.
    particles = None
    stale = None
    if bm.mpm_members():
        particles = self._mpm_prepare(bm, path, per_rank=False)
        emitter.bind_particle_set(str(particles.path))
    else:
        stale = stale_particle_set(path)
    pre_prof, post_prof = self._split_profiler_records()
    emit_deck_tail(self, emitter, bm, pre_prof, post_prof,
                   analyze_steps, analyze_dt, path)
    if particles is not None:
        write_particle_set(particles)
    # ADR 0134 D1: a stale set goes only once its deck is replaced.
    write_deck_then_remove(path, emitter.write_to, stale)
    self._artifacts.after_emit(self)

    if not run:
        return None

    self._read_state = DroppedSession(
        DECK_RUN_CAUSE.format(verb="ops.py(..., run=True)"))
    deck_run = begin_deck_run(
        self, bm, emitter, path, verb="ops.py(..., run=True)")
    self._deck_run = deck_run
    python_bin = _resolve_python_binary(python, self._opensees)
    # PYTHONUNBUFFERED so the child's stdout streams live through the
    # pipe rather than block-buffering until exit (the tee + live
    # counter depend on it).
    child_env = {**os.environ, "PYTHONUNBUFFERED": "1"}
    report = stream_run(
        [python_bin, path],
        log_path=resolve_log_path(log, path),
        verbose=verbose,
        label=run_label(path, analyze_steps, analyze_dt),
        header="openseespy",
        env=child_env,
        deck_path=path,
        expect_solver_stats=_deck_requested_solver_stats(emitter),
        expected_loops=deck_progress_loops(path) if progress else None,
    )
    self._deck_run = deck_run.finish()
    return report

results

results(path: str) -> 'Results'

The history of this bridge's last deck run, as a Results (ADR 0115 D3).

path is required and must be the deck that ops.py(path, run=True) or ops.tcl(path, run=True) wrote and ran on this bridge (Q5). What the run recorded decides the reader:

  • one ops.recorder.MPCO -> :meth:Results.from_mpco;
  • ops.recorder.declare(nodes=...) and typed ops.recorder.Node(..., time_format="dt") records -> one recorder spec synthesised from them, read by :meth:Results.from_recorders (Q3).

It raises :class:BridgeError, naming why, before writing any file: when no deck run happened on this bridge, the last solve was a live analyze (read that with .read; Q4), path is another deck, the run did not finish, the declarations changed since the run, no recorder was declared, or a record cannot be read here (a typed recorder.Element, a declare element category or raw_* token, a typed record without a time column, a staged or partitioned run's text records, a missing or malformed output file). It never returns a Results that silently lacks a declared record.

A read writes under <path>.results/: the model archive (model.h5) the reader binds, the text records in the reader's layout (out/) and the reader's cache.

A single value, one node at one step, is ops.results(path).nodes.get(label="tip", component="displacement_y").item().

Source code in src/apeGmsh/opensees/apesees.py
def results(self, path: str) -> "Results":
    """The history of this bridge's last deck run, as a ``Results``
    (ADR 0115 D3).

    ``path`` is required and must be the deck that
    ``ops.py(path, run=True)`` or ``ops.tcl(path, run=True)`` wrote
    and ran on this bridge (Q5). What the run recorded decides the
    reader:

    - one ``ops.recorder.MPCO`` -> :meth:`Results.from_mpco`;
    - ``ops.recorder.declare(nodes=...)`` and typed
      ``ops.recorder.Node(..., time_format="dt")`` records -> one
      recorder spec synthesised from them, read by
      :meth:`Results.from_recorders` (Q3).

    It raises :class:`BridgeError`, naming why, before writing any
    file: when no deck run happened on this bridge, the last solve
    was a live ``analyze`` (read that with ``.read``; Q4), ``path``
    is another deck, the run did not finish, the declarations changed
    since the run, no recorder was declared, or a record cannot be
    read here (a typed ``recorder.Element``, a ``declare`` element
    category or ``raw_*`` token, a typed record without a time
    column, a staged or partitioned run's text records, a missing or
    malformed output file). It never returns a ``Results`` that
    silently lacks a declared record.

    A read writes under ``<path>.results/``: the model archive
    (``model.h5``) the reader binds, the text records in the reader's
    layout (``out/``) and the reader's cache.

    A single value, one node at one step, is
    ``ops.results(path).nodes.get(label="tip",
    component="displacement_y").item()``.
    """
    return open_results(self, path)

run

run(*, wipe: bool = True) -> None

Drive an in-process LiveOpsEmitter through the full deck.

This emits every primitive but does NOT call analyze — that is the user's call (or :meth:analyze's). Useful when the user wants to declare a model, populate openseespy state, and then run their own analysis driver.

A staged model is refused before the domain is touched (#2533): the live emitter cannot replay stages, and its stage_open would otherwise raise after the wipe.

Source code in src/apeGmsh/opensees/apesees.py
def run(self, *, wipe: bool = True) -> None:
    """Drive an in-process LiveOpsEmitter through the full deck.

    This emits every primitive but does NOT call ``analyze`` —
    that is the user's call (or :meth:`analyze`'s). Useful when
    the user wants to declare a model, populate openseespy state,
    and then run their own analysis driver.

    A staged model is refused before the domain is touched (#2533):
    the live emitter cannot replay stages, and its ``stage_open``
    would otherwise raise after the wipe.
    """
    from .emitter.live import LiveOpsEmitter, refuse_fork_chain_before_wipe

    if self._stage_records:
        raise NotImplementedError(
            "apeSees.run: live execution does not support staged "
            "models (Phase SSI-2.A) "
            f"(got {len(self._stage_records)} stage(s)). Emit the "
            "deck with ops.tcl(...) / ops.py(...) and run it there; "
            "the live domain is untouched."
        )
    bm = self.build()
    refuse_fork_chain_before_wipe(bm)  # before the domain is touched
    self._read_state = DroppedSession(
        "ops.run() re-emitted the model into the live domain without "
        "solving it; call ops.analyze(...) to read"
    )
    emitter = LiveOpsEmitter(wipe=wipe)
    bm.emit(emitter)
    emitter._write_stage_zero()  # the caller's own analyze follows
    self._artifacts.after_emit(self)

wipe

wipe() -> None

Close the live OpenSees domain (R3-S5, maintainer ruling D6).

Calls OpenSees wipe on the in-process module. It removes the model and destroys every recorder, which flushes and closes its file: a text recorder Node / Element file then holds every row the analysis recorded, and an .mpco file is complete, so Results.from_mpco opens it in the same script, without a subprocess.

It closes this bridge's read session (ADR 0115 D2): a later Node.read / NodeSet.read / ops.elements...read raises, naming ops.wipe(). It also moves the domain epoch, so the read session of any other bridge over the same process-global domain raises too. The declarations stay: ops.analyze(...) or ops.run() builds the model again from them.

A live session action only, never emitted to a deck (a deck flushes its recorders when its process exits). It has no VERBS row and no emitter Protocol method: it calls the live module through LiveOpsEmitter.ops, never command().

Source code in src/apeGmsh/opensees/apesees.py
def wipe(self) -> None:
    """Close the live OpenSees domain (R3-S5, maintainer ruling D6).

    Calls OpenSees ``wipe`` on the in-process module. It removes the
    model and destroys every recorder, which flushes and closes its
    file: a text ``recorder Node`` / ``Element`` file then holds every
    row the analysis recorded, and an ``.mpco`` file is complete, so
    ``Results.from_mpco`` opens it in the same script, without a
    subprocess.

    It closes this bridge's read session (ADR 0115 D2): a later
    ``Node.read`` / ``NodeSet.read`` / ``ops.elements...read`` raises,
    naming ``ops.wipe()``. It also moves the domain epoch, so the
    read session of any other bridge over the same process-global
    domain raises too. The declarations stay: ``ops.analyze(...)`` or
    ``ops.run()`` builds the model again from them.

    A live session action only, never emitted to a deck (a deck
    flushes its recorders when its process exits). It has no
    ``VERBS`` row and no emitter Protocol method: it calls the live
    module through ``LiveOpsEmitter.ops``, never ``command()``.
    """
    from .emitter.live import LiveOpsEmitter

    # Close first, so a wipe that raises still leaves no session that
    # answers from a domain in an unknown state.
    self._read_state = DroppedSession(
        "ops.wipe() closed the live domain (it removed the model and "
        "flushed and closed every recorder); call ops.analyze(...) "
        "again to read"
    )
    self._live_emitter = None
    # Constructing the emitter moves the domain epoch before any call
    # into OpenSees (ADR 0115 D2). ``wipe=False``: the wipe is the call
    # below, made through ``LiveOpsEmitter.ops``; the emitter's stock
    # equation-row guard refuses a *next* model, not a close.
    LiveOpsEmitter(wipe=False).ops.wipe()

run_remote

run_remote(job_dir: str, *, cluster: 'str | Cluster', np: int | None = None, name: str | None = None, deck: str = 'main.tcl', binary: str | None = None, walltime: str | None = None, analyze_steps: int | None = None, analyze_dt: float | None = None, wait: bool = True, poll: float = 15.0, timeout: float | None = None, overwrite: bool = False) -> 'Job'

Emit the Tcl deck and run it on a SLURM cluster (ADR 0060 sugar).

One call for the whole loop: emit into job_dir -> push -> sbatch -> poll to completion -> fetch results back into job_dir. Wraps :class:apeGmsh.hpc.Cluster / :class:apeGmsh.hpc.Job; use those directly for finer control (or pass wait=False to get the live :class:Job handle back right after submission).

Parameters

job_dir Local directory the deck is emitted into and results are fetched back into. Created if missing. cluster Cluster name in ~/.apegmsh/clusters.toml (e.g. "esmeralda") or a constructed Cluster. np MPI ranks. Defaults to the model's partition count (len(fem.partitions)), or 1 for a flat model. analyze_steps / analyze_dt Forwarded to :meth:tcl — appends the analyze drive line exactly as the local emit would. wait True (default) blocks until the job ends and fetches. False returns the submitted Job immediately; poll/fetch it yourself (it survives sessions via Job.load(job_dir)).

Raises

HPCError If the job ends in any state other than COMPLETED (results and logs are still fetched first; the message carries the stderr tail).

Source code in src/apeGmsh/opensees/apesees.py
def run_remote(
    self,
    job_dir: str,
    *,
    cluster: "str | Cluster",
    np: int | None = None,
    name: str | None = None,
    deck: str = "main.tcl",
    binary: str | None = None,
    walltime: str | None = None,
    analyze_steps: int | None = None,
    analyze_dt: float | None = None,
    wait: bool = True,
    poll: float = 15.0,
    timeout: float | None = None,
    overwrite: bool = False,
) -> "Job":
    """Emit the Tcl deck and run it on a SLURM cluster (ADR 0060 sugar).

    One call for the whole loop: emit into ``job_dir`` -> push ->
    ``sbatch`` -> poll to completion -> fetch results back into
    ``job_dir``. Wraps :class:`apeGmsh.hpc.Cluster` /
    :class:`apeGmsh.hpc.Job`; use those directly for finer control
    (or pass ``wait=False`` to get the live :class:`Job` handle back
    right after submission).

    Parameters
    ----------
    job_dir
        Local directory the deck is emitted into and results are
        fetched back into. Created if missing.
    cluster
        Cluster name in ``~/.apegmsh/clusters.toml`` (e.g.
        ``"esmeralda"``) or a constructed ``Cluster``.
    np
        MPI ranks. Defaults to the model's partition count
        (``len(fem.partitions)``), or 1 for a flat model.
    analyze_steps / analyze_dt
        Forwarded to :meth:`tcl` — appends the ``analyze`` drive
        line exactly as the local emit would.
    wait
        ``True`` (default) blocks until the job ends and fetches.
        ``False`` returns the submitted ``Job`` immediately;
        poll/fetch it yourself (it survives sessions via
        ``Job.load(job_dir)``).

    Raises
    ------
    HPCError
        If the job ends in any state other than ``COMPLETED``
        (results and logs are still fetched first; the message
        carries the stderr tail).
    """
    from pathlib import Path as _Path

    from ..hpc import Cluster as _Cluster
    from ..hpc import HPCError as _HPCError
    from ..hpc import JobStatus as _JobStatus

    resolved = (
        _Cluster.load(cluster) if isinstance(cluster, str) else cluster
    )
    ranks = np if np is not None else max(1, len(self._fem.partitions))
    path = _Path(job_dir)
    path.mkdir(parents=True, exist_ok=True)
    self._read_state = DroppedSession(
        DECK_RUN_CAUSE.format(verb="ops.run_remote(...)"))
    self.tcl(
        str(path / deck),
        analyze_steps=analyze_steps,
        analyze_dt=analyze_dt,
    )
    job = resolved.submit(
        path,
        np=ranks,
        name=name,
        deck=deck,
        binary=binary,
        walltime=walltime,
        overwrite=overwrite,
    )
    if not wait:
        return job
    status = job.wait(poll=poll, timeout=timeout)
    # Fetch BEFORE the verdict: on failure the logs are the evidence.
    job.fetch()
    if status is not _JobStatus.COMPLETED:
        raise _HPCError(
            f"remote job {job.name!r} (slurm {job.slurm_id}) ended "
            f"{status.value}; logs fetched into {job.local_dir}.\n"
            f"--- stderr tail ---\n{job.tail(30, stream='err')}"
        )
    return job

h5

h5(path: str, *, model_name: str | None = None, cuts: 'Sequence[SectionCutDef]' = (), sweeps: 'Sequence[SectionSweepDef]' = ()) -> None

Emit a model-definition HDF5 archive at path.

Phase 8.5 composes the file in two layers:

  1. The broker (self._fem) writes /meta + the neutral zone (/nodes, /elements/{type}, /physical_groups, /labels, /constraints/{kind}, /loads/{kind}/{pattern}, /masses). Broker writers live in :mod:apeGmsh.mesh._femdata_h5_io.
  2. The bridge (an :class:H5Emitter driven through the :class:BuiltModel) appends /opensees/... enrichment.
  3. apeGmsh.cuts v4: if cuts and / or sweeps are supplied, they're persisted under /opensees/cuts/ and /opensees/sweeps/ (writer in :mod:apeGmsh.cuts._h5_io).

If self._fem does not expose a real :class:FEMData surface (e.g. integration tests using a hand-rolled stub), the broker step is skipped: the file ends up with the bridge's own /meta plus /opensees/..., but no neutral zone. Real callers always get the full file shape.

Parameters

path File path to write the HDF5 archive to. model_name Optional human-readable name written to /meta/model_name. Defaults to the path's stem. cuts Optional sequence of :class:apeGmsh.cuts.SectionCutDef to persist under /opensees/cuts/cut_{i}. Each cut travels with the model definition; the viewer auto-loads them from the file the next time Results.viewer(...) is opened against a results.h5 carrying the same /opensees/ zone (Phase 8 / ADR 0020 Composed-file pattern). sweeps Optional sequence of :class:apeGmsh.cuts.SectionSweepDef to persist under /opensees/sweeps/sweep_{i}. Each sweep group carries its own cuts/ sub-group in sweep order (see apeGmsh/cuts/ARCHITECTURE.md "## v4").

Source code in src/apeGmsh/opensees/apesees.py
def h5(
    self,
    path: str,
    *,
    model_name: str | None = None,
    cuts: "Sequence[SectionCutDef]" = (),
    sweeps: "Sequence[SectionSweepDef]" = (),
) -> None:
    """Emit a model-definition HDF5 archive at ``path``.

    Phase 8.5 composes the file in two layers:

    1. The **broker** (``self._fem``) writes ``/meta`` + the
       neutral zone (``/nodes``, ``/elements/{type}``,
       ``/physical_groups``, ``/labels``, ``/constraints/{kind}``,
       ``/loads/{kind}/{pattern}``, ``/masses``).  Broker writers
       live in :mod:`apeGmsh.mesh._femdata_h5_io`.
    2. The **bridge** (an :class:`H5Emitter` driven through the
       :class:`BuiltModel`) appends ``/opensees/...`` enrichment.
    3. apeGmsh.cuts v4: if ``cuts`` and / or ``sweeps`` are
       supplied, they're persisted under ``/opensees/cuts/`` and
       ``/opensees/sweeps/`` (writer in
       :mod:`apeGmsh.cuts._h5_io`).

    If ``self._fem`` does not expose a real :class:`FEMData`
    surface (e.g. integration tests using a hand-rolled stub),
    the broker step is skipped: the file ends up with the
    bridge's own ``/meta`` plus ``/opensees/...``, but no neutral
    zone.  Real callers always get the full file shape.

    Parameters
    ----------
    path
        File path to write the HDF5 archive to.
    model_name
        Optional human-readable name written to ``/meta/model_name``.
        Defaults to the path's stem.
    cuts
        Optional sequence of :class:`apeGmsh.cuts.SectionCutDef`
        to persist under ``/opensees/cuts/cut_{i}``.  Each cut
        travels with the model definition; the viewer auto-loads
        them from the file the next time ``Results.viewer(...)``
        is opened against a results.h5 carrying the same
        ``/opensees/`` zone (Phase 8 / ADR 0020 Composed-file
        pattern).
    sweeps
        Optional sequence of :class:`apeGmsh.cuts.SectionSweepDef`
        to persist under ``/opensees/sweeps/sweep_{i}``.  Each
        sweep group carries its own ``cuts/`` sub-group in sweep
        order (see ``apeGmsh/cuts/ARCHITECTURE.md`` "## v4").

    """
    # ADR 0055 Phase 2 + Phase 5 (P5.1, schema 2.19.0): staged
    # builds archive — the H5 emitter captures the per-stage emit
    # stream into ``/opensees/stages`` (see ``set_stage_records``
    # below).  For PARTITIONED staged builds the capture is
    # rank-agnostic by construction: replicated per-rank emission
    # dedupes on record identity, per-rank pattern/region
    # fragments merge by tag, and foreign ghost-node declarations
    # are filtered out of the stage buckets via the
    # ``set_stage_owned_node_tags`` side-channel — the stage zone
    # carries the flat logical program (rank-major capture order),
    # while the per-rank shape stays derivable from the neutral
    # ``/partitions`` zone.  The one staged remainder is the
    # phantom-node degrade (stage-claimed ``node_to_surface``),
    # which ``set_stage_records`` keeps fail-loud for flat and
    # partitioned builds alike.
    # ADR 0055 Phase 1: GLOBAL ``ops.initial_stress(...)`` archival is
    # supported — the records persist declaratively to
    # ``/opensees/initial_stress`` and replay re-runs the emit helpers
    # (see ``set_initial_stress_records`` below).  Per-stage
    # initial-stress persists with its stage under
    # ``/opensees/stages`` (Phase 2).

    self._write_h5(path, self.build(), model_name=model_name, cuts=cuts, sweeps=sweeps)
    self._artifacts.remember_lineage(self, path)  # a later deck's run record reuses it

register

register(prim: _P) -> _P

Register a standalone primitive with the bridge (P11).

Idempotent on the object: registering an instance the bridge already holds (a namespace handle, or a second register) returns it unchanged, so it stays once in the primitive list (#1409).

Source code in src/apeGmsh/opensees/apesees.py
def register(self, prim: _P) -> _P:
    """Register a standalone primitive with the bridge (P11).

    Idempotent on the object: registering an instance the bridge
    already holds (a namespace handle, or a second ``register``)
    returns it unchanged, so it stays once in the primitive list
    (#1409).
    """
    if self._tags.tag_for(prim) is not None:
        return prim
    return self._register(prim)

tag_for

tag_for(prim: Primitive) -> int | None

Return prim's allocated tag, or None if unregistered.

An mpm grid answers the tag its deck line writes (ADR 0134, :func:.mpm.host_tag): a fork load-pattern tag above every registered pattern tag (and every other mpm member's tag), so a pattern or member declared later moves it.

Source code in src/apeGmsh/opensees/apesees.py
def tag_for(self, prim: Primitive) -> int | None:
    """Return ``prim``'s allocated tag, or ``None`` if unregistered.

    An ``mpm`` grid answers the tag its deck line writes (ADR 0134,
    :func:`.mpm.host_tag`): a fork load-pattern tag above every
    registered ``pattern`` tag (and every other ``mpm`` member's tag),
    so a pattern or member declared later moves it.
    """
    tag = self._tags.tag_for(prim)
    if tag is not None and isinstance(prim, _MPMGrid):
        return _mpm_host_tag(
            (self._tags.tag_for(p) for p in self._primitives
             if isinstance(p, Pattern)),
            (self._tags.tag_for(p) for p in self._primitives
             if isinstance(p, MPM) and p is not prim))
    return tag

build

build() -> BuiltModel

Freeze the declarations into a :class:BuiltModel.

Source code in src/apeGmsh/opensees/apesees.py
def build(self) -> BuiltModel:
    """Freeze the declarations into a :class:`BuiltModel`."""
    if self._ndm is None or self._ndf is None:
        raise RuntimeError(
            "apeSees.model(ndm=..., ndf=...) must be called before "
            "build()."
        )
    self._check_damping_attached()

    tag_for: dict[int, int] = {
        id(p): self._tags.tag_for(p) or 0 for p in self._primitives
    }
    decls: dict[int, _DeclRow] = {
        oid: decl for oid, (_owner, decl) in self._decls.items()
    }
    fix_records = tuple(self._fix_records)
    if self._fix_from_model:
        from_model = fix_records_from_model(
            self._fem,
            [p for p in self._primitives if isinstance(p, Element)],
            self._ndm, self._ndf,
            ndf_records=self._ndf_records,
            # ADR 0115 D6/Q1: the global ``fix`` calls share
            # fix_from_model's tier and merge with it below; only the
            # stages' fix / support pools are another tier.
            explicit=(
                *(r for st in self._stage_records for r in st.fix_records),
                *(r for st in self._stage_records
                  for r in st.support_records),
            ),
        )
        # K1-6: the records fix_from_model() stands for share its
        # one declaration.
        model_wide = decls[id(self._fix_from_model_owner)]
        decls.update((id(r), model_wide) for r in from_model)
        fix_records += from_model
    # ADR 0115 D6: identical homogeneous fixes merge within a tier
    # (the global pool, or one stage); a tier without an overlap
    # keeps its records unchanged.
    fix_records = _merge_homogeneous_fixes(self._fem, fix_records, decls)
    stage_records = tuple(
        st if merged is st.fix_records
        else replace(st, fix_records=merged)
        for st, merged in (
            (st, _merge_homogeneous_fixes(self._fem, st.fix_records, decls))
            for st in self._stage_records
        )
    )
    # ADR 0120 D1: on a partitioned FEM, every element-less node (a
    # decoupled node, a spring bed's ground and side nodes) gets one
    # rank — the rank of the mesh node it reaches — so the per-rank
    # emit declares it, its fix and the node-pair element on it.
    fem = self._fem
    if is_partitioned(fem):
        fem = route_element_less_nodes(fem, [
            resolve_element_node_pair(fem, p) for p in self._primitives
            if isinstance(p, Element)
            and getattr(p, "pg", None) is None
            and not isinstance(p, LadrunoMembrane)
        ])
    built = BuiltModel(
        primitives=tuple(self._primitives),
        tag_for=tag_for,
        ndm=self._ndm,
        ndf=self._ndf,
        fem=fem,
        fix_records=fix_records,
        mass_records=tuple(self._mass_records),
        region_records=tuple(self._region_records),
        ndf_records=tuple(self._ndf_records),
        initial_stress_records=tuple(self._initial_stress_records),
        stage_records=stage_records,
        rayleigh_records=tuple(self._rayleigh_records),
        damping_attach_records=tuple(self._damping_attach_records),
        modal_damping_records=tuple(self._modal_damping_records),
        equation_constraint_records=tuple(
            self._equation_constraint_records,
        ),
        name_to_tag={
            nm: tag for nm, _kind, tag in self._name_records()
        },
        mass_from_model=self._mass_from_model,
        element_tags=self._element_tags,
        combinations=tuple(self._combinations.values()),
        _decls=decls,
        _decl_owners={
            oid: owner for oid, (owner, _decl) in self._decls.items()},
    )
    # A membrane pressure= that no pattern activates loads nothing.
    refuse_inert_membrane_pressure(built)
    return built

Staged analysis

Multi-stage workflows (in-situ stress install → excavate → lining install → dynamic shake, or any other sequence of analyze blocks with Domain mutations between them) use the ops.stage(name) context manager:

with ops.stage(name="excavate") as s:
    s.activate(pgs=["Lining"])               # bring new elements online
    s.fix(pg="LiningAnchor", dofs=(1, 1, 1)) # stage-bound BC
    s.embedded(name="lining_embed")          # claim MP constraint by name
    s.analysis(test=…, algorithm=…, integrator=…,
               constraints=…, numberer=…, system=…, analysis=…)
    s.run(n_increments=20, dt=0.05)

Each stage emits its own analysis chain + analyze loop with an explicit inter-stage cleanup (loadConst -time 0.0 + wipeAnalysis). Between-stage Domain mutators (s.remove_sp / s.remove_element / s.set_time / s.set_creep / s.reset / s.mass(overwrite=True)) lift the append-only constraint from earlier phases and unlock the atomic-replace pattern (release prior support + re-fix the same DOF in one stage).

Five validators gate stage-bound BCs at build time (H1 / V1 / V2 / V3 / V4) and two more cover the SSI-2.E removal verbs (V5 / V6). Each raises BridgeError with a clear offender list when a stage references topology that doesn't yet exist or has already been removed.

Tcl + Py text emit are the supported execution paths for staged decks today. Live execution (ops.analyze / ops.eigen) refuses staged models with NotImplementedError — emit via ops.tcl(p, run=True) / ops.py(p, run=True) for the OpenSees subprocess. H5 archival supports staged builds: apeSees.h5(path) archives flat and partitioned staged models into /opensees/stages (ADR 0055). The remaining staged refusals are a stage-claimed interface (phantom nodes / node_to_surface).

The full lifecycle table, builder verbs, validator surface, MP partitioned + staged emit (Phase SSI-2.C), and the SSI-1 initial-stress ramp live in architecture/api-design.md §"Staged analysis"; the internals (deck layout, ownership computation, hook dispatcher, per-emitter dialect divergence, cleanup contract) live in architecture/staged-analysis.md and architecture/emitter.md.

Orientation helpers

Used as the orientation= argument on the typed geom_transf primitives (Linear / PDelta / Corotational).

apeGmsh.opensees.Cartesian

Cartesian(reference_axis: ArrayLike = (0.0, 0.0, 1.0))

Constant Cartesian triad. reference_axis defines e3; e1 and e2 are picked deterministically from the global axis least aligned with e3.

The default reference_axis = (0, 0, 1) reproduces the legacy "Z up" convention: horizontal beams get vecxz = (0, 0, 1) and vertical columns fall back to vecxz = (-1, 0, 0) (the sign follows the tangent direction; see :ref:shoebuckle).

Parameters

reference_axis : 3-vector The axis e3. Need not be unit length.

Example

::

from apeGmsh.opensees import Cartesian

# Standard structural convention: Z is vertical
orientation = Cartesian()                          # reference_axis = +Z

# Mechanical CAD convention: Y is vertical
orientation = Cartesian(reference_axis=(0, 1, 0))
Source code in src/apeGmsh/opensees/_orientation.py
def __init__(self, reference_axis: ArrayLike = (0.0, 0.0, 1.0)) -> None:
    # Pick the global axis least aligned with e3, project it
    # perpendicular to e3, normalise -> e1.
    self._e1, self._e2, self._e3 = _perp_triad_from_e3(
        _unit(reference_axis))

apeGmsh.opensees.Cylindrical

Cylindrical(origin: ArrayLike = (0.0, 0.0, 0.0), axis: ArrayLike = (0.0, 0.0, 1.0))

Cylindrical orientation about an axis of revolution.

At a point p:

  • e1 = radial outward, perpendicular to axis
  • e2 = circumferential, axis × e1
  • e3 = axis (constant) ← reference axis for the rule

Use this for ring beams, tank stiffeners, and any beam set whose natural "vertical" is the axis of revolution.

Parameters

origin : 3-vector Any point on the axis of revolution. axis : 3-vector Direction of the axis of revolution. Need not be unit length.

Example

::

from apeGmsh.opensees import Cylindrical

# Vertical tank
orientation = Cylindrical(origin=(0, 0, 0), axis=(0, 0, 1))
Source code in src/apeGmsh/opensees/_orientation.py
def __init__(
    self,
    origin: ArrayLike = (0.0, 0.0, 0.0),
    axis: ArrayLike = (0.0, 0.0, 1.0),
) -> None:
    self._origin = np.asarray(origin, dtype=float)
    self._axis = _unit(axis)

apeGmsh.opensees.Spherical

Spherical(origin: ArrayLike = (0.0, 0.0, 0.0))

Spherical orientation about a fixed origin. Polar axis is global +Z.

At a point p (with r = |p − origin|):

  • e1 = e_θ — along the meridian (south at the equator)
  • e2 = e_φ — along the parallel (east)
  • e3 = e_r — outward radial ← reference axis for the rule

Useful for fan vaults, geodesic ribs, and any beam network with natural radial structure. Note: for a planar curved beam (e.g. a vertical-plane arch), :class:Cartesian with reference_axis in the plane gives the same answer with less ceremony.

Parameters

origin : 3-vector Centre of the sphere.

Example

::

from apeGmsh.opensees import Spherical

orientation = Spherical(origin=(0, 0, 0))
Source code in src/apeGmsh/opensees/_orientation.py
def __init__(self, origin: ArrayLike = (0.0, 0.0, 0.0)) -> None:
    self._origin = np.asarray(origin, dtype=float)

Frame property modifiers

Passed as modifiers= on elasticBeamColumn, ElasticTimoshenkoBeam, forceBeamColumn and dispBeamColumn. The emitted section properties are the declared ones times the modifiers, in the way ETABS frame property modifiers work.

apeGmsh.opensees.FrameModifiers dataclass

FrameModifiers(*, A: float = 1.0, Avy: float = 1.0, Avz: float = 1.0, J: float = 1.0, Iy: float = 1.0, Iz: float = 1.0, mass: float = 1.0, weight: float = 1.0)

Frame section property modifiers, in OpenSees local axes.

Every field defaults to 1.0 (gross section). The six stiffness modifiers (A, Avy, Avz, J, Iy, Iz) must be finite and > 0; mass and weight finite and >= 0.

Attach to an element spec with modifiers=::

cracked = FrameModifiers.etabs(I22=0.7, I33=0.7)   # ACI 318-25 columns
ops.element.elasticBeamColumn(pg="Cols", transf=t, A=..., E=...,
                              Iz=..., Iy=..., G=..., J=...,
                              modifiers=cracked)

Use :meth:etabs to construct from ETABS-named modifiers.

is_identity property

is_identity: bool

True when every modifier is 1.0 (gross section).

etabs classmethod

etabs(*, A: float = 1.0, As2: float = 1.0, As3: float = 1.0, J: float = 1.0, I22: float = 1.0, I33: float = 1.0, mass: float = 1.0, weight: float = 1.0) -> 'FrameModifiers'

Build from ETABS frame property modifier names.

Axis mapping: ETABS local 1 runs along the member, as OpenSees local x does. Choose the element's geomTransf vecxz along ETABS local 3: OpenSees local z then equals ETABS 3, and since both triads are right-handed with a common first axis, OpenSees local y = z x x = 3 x 1 = ETABS 2. Under that vecxz the mapping is As2 -> Avy, As3 -> Avz, I22 -> Iy (bending about local 2 / y), I33 -> Iz (bending about local 3 / z, the major axis of an ETABS frame section). A, J, mass and weight carry no axis. With any other vecxz the 2 and 3 modifiers land on whichever OpenSees axes it defines, so check it.

For a vertical ETABS column (1 = +Z, 2 = +X, 3 = +Y) that is vecxz=(0, 1, 0); for a beam along +X (1 = +X, 2 = +Z, 3 = -Y) it is vecxz=(0, -1, 0).

The ETABS importer does not use this convention. interop/etabs_import.py (_VECXZ) gives a vertical member vecxz=(1, 0, 0) and any other member (0, 0, 1): for a member at its default orientation both are ETABS 2, not 3, and the importer ignores Frame.rotation. Under that vecxz OpenSees local z is ETABS 2, so I33 lands on the minor axis (and I22 on the major one). The importer passes no modifiers= today; wiring it to this method needs vecxz along ETABS 3 first.

Source code in src/apeGmsh/opensees/element/frame_modifiers.py
@classmethod
def etabs(
    cls,
    *,
    A: float = 1.0,
    As2: float = 1.0,
    As3: float = 1.0,
    J: float = 1.0,
    I22: float = 1.0,
    I33: float = 1.0,
    mass: float = 1.0,
    weight: float = 1.0,
) -> "FrameModifiers":
    """Build from ETABS frame property modifier names.

    Axis mapping: ETABS local 1 runs along the member, as OpenSees
    local x does. Choose the element's ``geomTransf`` ``vecxz`` along
    **ETABS local 3**: OpenSees local z then equals ETABS 3, and since
    both triads are right-handed with a common first axis, OpenSees
    local y = z x x = 3 x 1 = ETABS 2. Under that ``vecxz`` the mapping
    is ``As2 -> Avy``, ``As3 -> Avz``, ``I22 -> Iy`` (bending about
    local 2 / y), ``I33 -> Iz`` (bending about local 3 / z, the major
    axis of an ETABS frame section). ``A``, ``J``, ``mass`` and
    ``weight`` carry no axis. With any other ``vecxz`` the 2 and 3
    modifiers land on whichever OpenSees axes it defines, so check it.

    For a vertical ETABS column (1 = +Z, 2 = +X, 3 = +Y) that is
    ``vecxz=(0, 1, 0)``; for a beam along +X (1 = +X, 2 = +Z,
    3 = -Y) it is ``vecxz=(0, -1, 0)``.

    **The ETABS importer does not use this convention.**
    ``interop/etabs_import.py`` (``_VECXZ``) gives a vertical member
    ``vecxz=(1, 0, 0)`` and any other member ``(0, 0, 1)``: for a member
    at its default orientation both are ETABS **2**, not 3, and the
    importer ignores ``Frame.rotation``. Under that ``vecxz`` OpenSees
    local z is ETABS 2, so ``I33`` lands on the minor axis (and ``I22``
    on the major one). The importer passes no ``modifiers=`` today;
    wiring it to this method needs ``vecxz`` along ETABS 3 first.
    """
    return cls(
        A=A, Avy=As2, Avz=As3, J=J, Iy=I22, Iz=I33,
        mass=mass, weight=weight,
    )

non_unit

non_unit() -> dict[str, float]

The modifiers that differ from 1.0, by OpenSees name.

Source code in src/apeGmsh/opensees/element/frame_modifiers.py
def non_unit(self) -> dict[str, float]:
    """The modifiers that differ from ``1.0``, by OpenSees name."""
    return {
        n: getattr(self, n) for n in _NAMES if getattr(self, n) != 1.0
    }

Recorders

Standalone recorder declaration helper. Recorder declarations live on ops.recorder.* in the apeSees bridge (typed primitives — Node / Element / MPCO / declarative fan-out via ops.recorder.declare(...)).

apeGmsh.opensees.recorder

Typed recorder primitives.

Phase 3B ships three concrete recorder classes mirroring the OpenSees recorder command:

  • :class:Node — recorder Node ...
  • :class:Element — recorder Element ...
  • :class:MPCO — recorder mpco ... (HDF5)

Each class is a @dataclass(frozen=True, kw_only=True, slots=True); the matching :class:apeGmsh.opensees._internal.ns.recorder._RecorderNS methods take the same kwargs and call self._bridge._register(Cls(...)).

Recorders never compose other primitives (dependencies() returns ()). They are leaves in the dependency graph; the build pipeline emits them after the topology + analysis chain so that each recorder command sees fully-allocated node and element tags.

The pg= form (physical-group fan-out into node/element tags) is materialized at build time by :func:apeGmsh.opensees._internal.build.recorders.emit_recorder_spec, which resolves pg through the FEM snapshot, rewrites the spec to its explicit nodes= / elements= form via :func:dataclasses.replace, and then delegates to _emit. End users drive this through apeSees(fem).tcl(...) / .py(...) / .run() — never call _emit directly with a pg spec, which raises :class:NotImplementedError as a defense-in-depth guard.

OpenSees command shapes

::

recorder Node    -file fname [-time] [-dT dT] [-node n...]
                             -dof d... response
recorder Element -file fname [-time] [-dT dT] [-ele e...]
                             response_tokens...
recorder mpco    fname.mpco  [-N nodal_responses...]
                             [-E elem_responses...]
                             [-T dt $dt | -T nsteps $n]

The -time flag (when time_format="dt") instructs OpenSees to include the simulation-time column in the output file. The default time_format="step" writes only the response columns.

Node dataclass

Node(*, file: str, response: str, nodes: tuple[int, ...] | None = None, pg: str | None = None, label: tuple[str, ...] | None = None, dofs: tuple[int, ...], dT: float | None = None, time_format: str = 'step', precision: int | None = None)

Bases: Recorder

recorder Node — record nodal response history.

OpenSees command::

recorder Node -file fname [-time] [-dT dT]
              (-node n1 n2 ... | -nodeRange first last)
              -dof d1 d2 ... response

Exactly one of nodes= (explicit list) or pg= (physical-group label) must be supplied. The bridge build pipeline materializes the pg= form against the FEM snapshot before driving _emit; direct _emit calls on a pg= spec raise :class:NotImplementedError as a defense-in-depth guard.

Parameters

file Output file path. response OpenSees response token ("disp", "vel", "accel", "reaction", "unbalance", ...). nodes Explicit tuple of node tags. Mutually exclusive with pg. pg Physical-group label whose nodes the recorder targets. Mutually exclusive with nodes. Resolved by the bridge build pipeline at emit time. label Provenance of an ops.recorder.Node(label=...) declaration (ADR 0115 amendment R2-f): the geometry label name(s) the call resolved to nodes. Never re-resolved and never emitted; nodes stays authoritative. Needs nodes=, refuses pg=. dofs DOF indices (1-based, OpenSees convention). At least one required. dT Optional cadence — record only every dT simulation seconds. None records every step. time_format "step" (default) writes only response columns; "dt" emits the OpenSees -time flag, prepending the simulation-time column. precision Significant digits per written value (OpenSees -precision N; its default is 6). None (default) emits no flag, so the deck is unchanged. A positive int; anything else raises.

Element dataclass

Element(*, file: str, response: tuple[str, ...], elements: tuple[int, ...] | None = None, pg: str | None = None, label: tuple[str, ...] | None = None, dT: float | None = None, time_format: str = 'step', precision: int | None = None)

Bases: Recorder

recorder Element — record element-level response history.

OpenSees command::

recorder Element -file fname [-time] [-dT dT]
                 (-ele e1 e2 ... | -eleRange first last)
                 response_tokens...

response is a tuple of OpenSees response tokens — the simplest case is ("globalForce",) or ("stresses",); element types that nest responses (e.g. fiber sections) take multi-token forms such as ("section", "1", "force").

Exactly one of elements= (explicit list) or pg= (physical- group label) must be supplied. pg= is resolved against the FEM snapshot by the bridge build pipeline before driving _emit; direct _emit calls on a pg= spec raise :class:NotImplementedError as a defense-in-depth guard.

Parameters

file Output file path. response Tuple of OpenSees response tokens (at least one). elements Explicit tuple of element tags. Mutually exclusive with pg. With label set they are the FEM element ids the label resolved to, which the bridge translates to the emitted OpenSees tags at build (as it does for pg=). pg Physical-group label whose elements the recorder targets. Mutually exclusive with elements. Resolved by the bridge build pipeline at emit time. label Provenance of an ops.recorder.Element(label=...) declaration (ADR 0115 amendment R2-f): the geometry label name(s) the call resolved to FEM element ids. Never re-resolved and never emitted; it marks elements as FEM ids. Needs elements=, refuses pg=. The archive stores the translated OpenSees tags, as for every other Element recorder. dT Optional cadence — record only every dT simulation seconds. None records every step. time_format "step" (default) writes only response columns; "dt" emits the OpenSees -time flag. precision Significant digits per written value (OpenSees -precision N; its default is 6). None (default) emits no flag, so the deck is unchanged. A positive int; anything else raises.

FilterableRecorder dataclass

FilterableRecorder(*, file: str, nodal_responses: tuple[str, ...] = (), elem_responses: tuple[str, ...] = (), dT: float | None = None, nsteps: int | None = None, nodes: tuple[int, ...] | None = None, nodes_pg: str | None = None, elements: tuple[int, ...] | None = None, elements_pg: str | None = None, _region_tag: int | None = None)

Bases: Recorder

Base for HDF5 recorders that share MPCO's region-filter surface.

Carries the four mutually-paired selectors (nodes / nodes_pg / elements / elements_pg) and the region-emit machinery that turns them into an OpenSees region $tag -node ... -ele ... line plus a -R $tag on the recorder command. :class:MPCO and :class:Ladruno both inherit it; they differ only in the recorder kind token and (Ladruno) the trailing -G energy channel.

Carries the shared value channels too (file + nodal_responses / elem_responses -N/-E + dT/nsteps -T cadence), so :meth:_value_channel_args builds the common -N ... -E ... -T ... -R ... tail once for both subclasses — only the recorder kind token and (Ladruno) the trailing -G energy are subclass-specific.

Subclasses own only their required-response rule (MPCO needs nodal or element responses; Ladruno also accepts energy); the cadence mutex (:meth:_validate_cadence) and the four selector guards (:meth:_validate_filter) are shared. The partition-aware build pipeline (ADR 0027 INV-4) keys its per-rank region pass on isinstance(spec, FilterableRecorder) via :meth:has_filter / :meth:resolve_filter_ids.

has_filter

has_filter() -> bool

True iff any node/element selector was supplied.

Used by the partition-aware build pipeline (ADR 0027 INV-4) to decide whether the recorder needs a per-rank region pass — a whole-model recorder (no filter) emits one recorder line and nothing else.

Source code in src/apeGmsh/opensees/recorder.py
def has_filter(self) -> bool:
    """True iff any node/element selector was supplied.

    Used by the partition-aware build pipeline (ADR 0027 INV-4) to
    decide whether the recorder needs a per-rank region pass — a
    whole-model recorder (no filter) emits one ``recorder`` line
    and nothing else.
    """
    return (
        self.nodes is not None
        or self.nodes_pg is not None
        or self.elements is not None
        or self.elements_pg is not None
    )

region_keys

region_keys() -> tuple[str, ...]

The regions this recorder writes, in the order they take tags.

"filter" is the value-channel filter region (-R), present iff :meth:has_filter. :class:Ladruno adds "energy", its decoupled energy region. The tag plan numbers them in this order.

Source code in src/apeGmsh/opensees/recorder.py
def region_keys(self) -> tuple[str, ...]:
    """The regions this recorder writes, in the order they take tags.

    ``"filter"`` is the value-channel filter region (``-R``), present
    iff :meth:`has_filter`. :class:`Ladruno` adds ``"energy"``, its
    decoupled energy region. The tag plan numbers them in this order.
    """
    return ("filter",) if self.has_filter() else ()

planned_region_tags

planned_region_tags(fem: 'FEMData', tag_plan: 'TagPlan') -> dict[object, int]

The tag of each of :meth:region_keys, by key.

Read from tag_plan (ADR 0114 D4, amended): a plan made for another model, or one that lacks a region this recorder writes, raises :class:~._internal.build.errors.TagPlanMiss.

Source code in src/apeGmsh/opensees/recorder.py
def planned_region_tags(
    self, fem: "FEMData", tag_plan: "TagPlan",
) -> dict[object, int]:
    """The tag of each of :meth:`region_keys`, by key.

    Read from ``tag_plan`` (ADR 0114 D4, amended): a plan made for
    another model, or one that lacks a region this recorder writes,
    raises :class:`~._internal.build.errors.TagPlanMiss`.
    """
    return tag_plan.regions.tags_for(
        fem, ("recorder", id(self)), self.region_keys())

resolve_filter_ids

resolve_filter_ids(fem: 'FEMData', fem_eid_to_ops_tag: 'FemToOpsTagMap | dict[int, int] | None' = None) -> tuple[tuple[int, ...], tuple[int, ...]]

Resolve nodes / nodes_pg / elements / elements_pg to explicit id tuples — no emission, no tag allocation.

Returns (node_ids, elem_ids). Either may be empty when its side was not requested; an empty result on a requested side (e.g. nodes_pg="X" resolving to zero nodes) raises :class:BridgeError to mirror the OpenSees runtime rejection of an empty region.

fem_eid_to_ops_tag is the bridge-built {fem_eid: ops_tag} map for element fan-out. When supplied AND elements_pg is set, the resolved FEM eids are translated to OpenSees element tags before they flow into the region's -ele arg list (same drift as the Element recorder, closed by :meth:Element.materialize). Lookup miss → :class:BridgeError. When None (legacy direct callers) the FEM eids are returned verbatim — the partition orchestrator uses this form so it can intersect per-rank in FEM-eid space, then translate at the final region-emit step.

This is the partition-aware split-point of the legacy single- pass :meth:materialize: the partition orchestrator calls resolve_filter_ids once globally to determine the full filter id set, then intersects per-rank before emitting the region. Whole-model recording (has_filter() is False) is a no-op pass-through — callers should not invoke this method in that case.

Source code in src/apeGmsh/opensees/recorder.py
def resolve_filter_ids(
    self,
    fem: "FEMData",
    fem_eid_to_ops_tag: "FemToOpsTagMap | dict[int, int] | None" = None,
) -> tuple[tuple[int, ...], tuple[int, ...]]:
    """Resolve ``nodes`` / ``nodes_pg`` / ``elements`` / ``elements_pg``
    to explicit id tuples — no emission, no tag allocation.

    Returns ``(node_ids, elem_ids)``. Either may be empty when its
    side was not requested; an empty *result* on a *requested* side
    (e.g. ``nodes_pg="X"`` resolving to zero nodes) raises
    :class:`BridgeError` to mirror the OpenSees runtime rejection of
    an empty region.

    ``fem_eid_to_ops_tag`` is the bridge-built ``{fem_eid: ops_tag}``
    map for element fan-out.  When supplied AND ``elements_pg`` is
    set, the resolved FEM eids are translated to OpenSees element
    tags before they flow into the region's ``-ele`` arg list
    (same drift as the Element recorder, closed by
    :meth:`Element.materialize`).  Lookup miss → :class:`BridgeError`.
    When ``None`` (legacy direct callers) the FEM eids are returned
    verbatim — the partition orchestrator uses this form so it can
    intersect per-rank in FEM-eid space, then translate at the
    final region-emit step.

    This is the partition-aware split-point of the legacy single-
    pass :meth:`materialize`: the partition orchestrator calls
    ``resolve_filter_ids`` once globally to determine the full
    filter id set, then intersects per-rank before emitting the
    region.  Whole-model recording (``has_filter() is False``) is
    a no-op pass-through — callers should not invoke this method
    in that case.
    """
    from ._internal.build.errors import BridgeError
    from ._internal.build.pg_expand import (
        expand_pg_to_elements,
        expand_pg_to_nodes,
    )

    kind = type(self).__name__

    # Resolve node-side selector.
    node_ids: tuple[int, ...] = ()
    if self.nodes_pg is not None:
        node_ids = expand_pg_to_nodes(fem, self.nodes_pg)
        if not node_ids:
            raise BridgeError(
                f"{kind} recorder filter: nodes_pg={self.nodes_pg!r} "
                "resolved to zero nodes against the FEM snapshot. "
                "An empty region is rejected by OpenSees at runtime; "
                "check the PG name spelling and that the PG was "
                "populated before get_fem_data."
            )
    elif self.nodes is not None:
        node_ids = tuple(int(n) for n in self.nodes)
        if not node_ids:
            raise BridgeError(
                f"{kind} recorder filter: nodes=() is empty.  An empty "
                "region is rejected by OpenSees at runtime; supply a "
                "non-empty tuple or drop the nodes= kwarg."
            )

    # Resolve element-side selector.
    elem_ids: tuple[int, ...] = ()
    if self.elements_pg is not None:
        fem_eids = tuple(
            eid for eid, _conn in expand_pg_to_elements(fem, self.elements_pg)
        )
        if not fem_eids:
            raise BridgeError(
                f"{kind} recorder filter: elements_pg={self.elements_pg!r} "
                "resolved to zero elements against the FEM snapshot. "
                "An empty region is rejected by OpenSees at runtime; "
                "check the PG name spelling and that elements were "
                "registered against it before get_fem_data."
            )
        if fem_eid_to_ops_tag is None:
            # Legacy / partition-orchestrator form: return FEM eids
            # verbatim so the caller can intersect per-rank in
            # FEM-eid space.  The bridge's flat path always supplies
            # the map; the partition path translates at the final
            # per-rank region-emit step.
            elem_ids = fem_eids
        else:
            ops_tags: list[int] = []
            for eid in fem_eids:
                ops_tag = fem_eid_to_ops_tag.get(int(eid))
                if ops_tag is None:
                    raise BridgeError(
                        f"{kind} recorder filter: elements_pg="
                        f"{self.elements_pg!r} resolves to FEM eid "
                        f"{eid} but no element was emitted at that "
                        "eid — declare an "
                        "``ops.element.X(pg=...)`` primitive whose "
                        f"pg includes {self.elements_pg!r}."
                    )
                ops_tags.append(int(ops_tag))
            elem_ids = tuple(ops_tags)
    elif self.elements is not None:
        elem_ids = tuple(int(e) for e in self.elements)
        if not elem_ids:
            raise BridgeError(
                f"{kind} recorder filter: elements=() is empty.  An "
                "empty region is rejected by OpenSees at runtime; "
                "supply a non-empty tuple or drop the elements= kwarg."
            )

    return node_ids, elem_ids

materialize

materialize(emitter: 'Emitter', fem: 'FEMData', tag_plan: 'TagPlan | None', fem_eid_to_ops_tag: 'FemToOpsTagMap | dict[int, int] | None' = None) -> 'FilterableRecorder'

Resolve filter selectors against the FEM and emit the region.

Whole-model recording (no filter selectors) is a no-op pass- through. When any of nodes / nodes_pg / elements / elements_pg is set, this method:

  1. Resolves *_pg to explicit id tuples via the bridge's PG-expansion helpers; refuses empty resolutions with :class:BridgeError (an empty OpenSees region is rejected at runtime).
  2. Reads the region tag the build's tag plan gave it (:meth:planned_region_tags; tag_plan must be supplied — the bridge build pipeline forwards the emit's tag plan).
  3. Emits one region $tag -node ... -ele ... line on emitter.
  4. Returns a clone with the filter selectors cleared and _region_tag populated, so the subsequent _emit appends -R $tag to the recorder command.

Used by the flat emit path and by the stage passes. The partitioned emit path (ADR 0027 INV-4) invokes :meth:resolve_filter_ids once for each recorder of its global pass and emits the per-rank region line itself; it then injects _region_tag= onto the spec via :func:dataclasses.replace directly, bypassing this method.

Source code in src/apeGmsh/opensees/recorder.py
def materialize(
    self,
    emitter: "Emitter",
    fem: "FEMData",
    tag_plan: "TagPlan | None",
    fem_eid_to_ops_tag: "FemToOpsTagMap | dict[int, int] | None" = None,
) -> "FilterableRecorder":
    """Resolve filter selectors against the FEM and emit the region.

    Whole-model recording (no filter selectors) is a no-op pass-
    through.  When any of ``nodes`` / ``nodes_pg`` / ``elements`` /
    ``elements_pg`` is set, this method:

    1. Resolves ``*_pg`` to explicit id tuples via the bridge's
       PG-expansion helpers; refuses empty resolutions with
       :class:`BridgeError` (an empty OpenSees region is rejected
       at runtime).
    2. Reads the region tag the build's tag plan gave it
       (:meth:`planned_region_tags`; ``tag_plan`` must be supplied —
       the bridge build pipeline forwards the emit's tag plan).
    3. Emits one ``region $tag -node ... -ele ...`` line on
       ``emitter``.
    4. Returns a clone with the filter selectors cleared and
       ``_region_tag`` populated, so the subsequent ``_emit``
       appends ``-R $tag`` to the recorder command.

    Used by the flat emit path and by the stage passes.  The
    partitioned emit path (ADR 0027 INV-4) invokes
    :meth:`resolve_filter_ids` once for each recorder of its global
    pass and emits the per-rank region line itself; it then injects
    ``_region_tag=`` onto the spec via :func:`dataclasses.replace`
    directly, bypassing this method.
    """
    keys = self.region_keys()
    if not keys:
        return self

    from ._internal.build.errors import BridgeError

    if tag_plan is None:
        raise BridgeError(
            f"{type(self).__name__} with a region (a nodes=/elements=/"
            "nodes_pg=/elements_pg= filter, or a Ladruno energy_pg=) "
            "requires a TagPlan on emit_recorder_spec(..., tag_plan=); "
            "the bridge build pipeline supplies one — tests that "
            "bypass the bridge must pass it explicitly."
        )
    return self._write_planned_regions(
        emitter, fem, self.planned_region_tags(fem, tag_plan),
        fem_eid_to_ops_tag,
    )

MPCO dataclass

MPCO(*, file: str, nodal_responses: tuple[str, ...] = (), elem_responses: tuple[str, ...] = (), dT: float | None = None, nsteps: int | None = None, nodes: tuple[int, ...] | None = None, nodes_pg: str | None = None, elements: tuple[int, ...] | None = None, elements_pg: str | None = None, _region_tag: int | None = None)

Bases: FilterableRecorder

recorder mpco — write a single HDF5 .mpco file.

OpenSees command::

recorder mpco fname.mpco [-N nodal_responses...]
                         [-E elem_responses...]
                         [-T dt $dt | -T nsteps $n]
                         [-R $regTag]

The MPCO recorder captures the full response tensor for each requested token (no per-DOF selection at write time); STKO / apeGmsh consumers filter at read time. At least one of nodal_responses or elem_responses must be non-empty.

Cadence is selected by exactly one of dT (seconds) or nsteps (analysis steps). Supplying both raises ValueError; supplying neither records every analysis step.

Filtering — MPCO records the whole model by default. To restrict output to a subset of nodes/elements, supply any of nodes= / nodes_pg= / elements= / elements_pg=: the build pipeline auto-emits an OpenSees region $tag -node ... -ele ... command before the recorder and passes -R $tag to MPCO. nodes= is mutually exclusive with nodes_pg=; the same applies to the element pair. When all four are None (the default) MPCO records the whole model and no region is emitted.

Parameters

file Output .mpco (HDF5) file path. nodal_responses Tuple of MPCO -N tokens (e.g. ("displacement", "reactionForce")). Empty tuple means no nodal recording. elem_responses Tuple of MPCO -E tokens (e.g. ("stresses", "section.fiber.stress")). Empty tuple means no element recording. dT Optional time-based cadence (seconds). Mutually exclusive with nsteps. nsteps Optional step-based cadence (every N analysis steps). Mutually exclusive with dT. nodes Explicit tuple of node tags to include in the region filter. Mutually exclusive with nodes_pg. nodes_pg Physical-group label whose nodes the region filter targets. Mutually exclusive with nodes. Resolved by the bridge build pipeline at emit time. elements Explicit tuple of element tags to include in the region filter. Mutually exclusive with elements_pg. elements_pg Physical-group label whose elements the region filter targets. Mutually exclusive with elements. Resolved by the bridge build pipeline at emit time.

Note

The bridge does not interpret -R-bearing MPCO arg tails when _emit is called directly (outside the build pipeline); the pg= form is materialised by :func:apeGmsh.opensees._internal.build.recorders.emit_recorder_spec, which resolves selectors, reads its planned region tag, emits the region, and replaces the spec via :func:dataclasses.replace with explicit nodes=/elements= before driving _emit.

Ladruno dataclass

Ladruno(*, file: str, nodal_responses: tuple[str, ...] = (), elem_responses: tuple[str, ...] = (), dT: float | None = None, nsteps: int | None = None, nodes: tuple[int, ...] | None = None, nodes_pg: str | None = None, elements: tuple[int, ...] | None = None, elements_pg: str | None = None, _region_tag: int | None = None, energy: bool = False, energy_pg: str | None = None, precision: Literal['f64', 'f32'] = 'f64', _energy_region_tags: tuple[int, ...] = (), _node_region_tag: int | None = None)

Bases: FilterableRecorder

recorder ladruno — write a single HDF5 .ladruno file.

Fork-only. The ladruno recorder exists only in the Ladruno fork build of OpenSees (nmorabowen/OpenSees@ladruno); stock openseespy does not have it. Per the opt-in contract, emission works on any build (the deck line is just recorder ladruno ...); the fork requirement bites only when the deck actually runs (ops.run() / the live emitter). Gate at the point of use, never at import.

OpenSees command (value channels + region filter + energy balance)::

recorder ladruno fname.ladruno [-precision f32]
                               [-N nodal_responses...]
                               [-E elem_responses...]
                               [-T dt $dt | -T nsteps $n]
                               [-R $regTag [-RN $nodeRegTag]]
                               [-G energy]

The .ladruno recorder is forked from the frozen MPCORecorder and shares its value-channel command grammar (the -N/-E/ -T channels reproduce the frozen recorder to 1e-12), so this dataclass mirrors :class:MPCO for those channels and inherits the same region-filter machinery from :class:FilterableRecorder. It diverges only in the recorder kind token (ladruno vs mpco), the output extension (.ladruno), and the trailing -G energy channel.

Cadence is selected by exactly one of dT (seconds) or nsteps (analysis steps). Supplying both raises ValueError; supplying neither records every analysis step.

Filtering — like MPCO, Ladruno records the whole model by default. Supply any of nodes= / nodes_pg= / elements= / elements_pg= to restrict output: the build pipeline auto-emits an OpenSees region $tag -node ... -ele ... command before the recorder and passes -R $tag to ladruno. nodes= is mutually exclusive with nodes_pg= (same for the element pair). A node-only filter cannot be combined with elem_responses (and vice versa) — the auto-region would carry no entries on the other side and produce an empty stream. The -R $tag is emitted before -G energy so the energy flag stays last.

Nodes and elements together (fork WP-234). An OpenSees MeshRegion cannot hold a node list and an element list at once: setNodes and setElements each wipe both, and -ele rebuilds the nodes from the elements, so one region -node ... -ele ... line silently keeps only the element nodes. When a node selector (nodes=/nodes_pg=) and an element selector (elements=/elements_pg=) are both given, Ladruno therefore emits two regions — region $tag -ele ... and region $nodeTag -node ... — and passes -R $tag -RN $nodeTag. The fork records -N rows on the -R element nodes plus the -RN nodes, and -E rows on the -R elements only. That is how embedded rebar nodes (whose minted truss elements carry no FEM id and must stay out of the file) get their displacements recorded. Only a fork build whose ladrunoSchema lists the recorderLadrunoNodeRegion capability reads -RN: the live route refuses another build by name, and a Tcl / openseespy deck checks the running build at its start and stops with the same message.

energy=True adds the fork's whole-model energy-balance channel (-G energy → RESULTS/ON_DOMAIN/energyBalance, components KE/IE/DW/ULW/RES/ERR), read back via Results.energy(). The flag is emitted last: the fork's -G parser eagerly consumes trailing region-tag integers and cannot rewind past a following flag, so -G energy -T nsteps 10 is a parse error while -T nsteps 10 -G energy runs (run-verified on the fork build).

Energy balance. Three forms, all run-verified on the fork build (which always writes the whole-model balance, RESULTS/ON_DOMAIN/energyBalance, and adds a per-region balance, RESULTS/ON_REGIONS/energyBalance, whenever a region tag is given):

  • energy=True alone → whole-model (-G energy, no tag).
  • energy=True + a value filter → energy over the same region the -R filter targets, reusing the filter's already-allocated tag (-G energy $filterTag). The coupled form.
  • energy_pg="X" → energy over an independent region X (-G energy $tagX), decoupled from the -R value filter. X may differ from (or exist without) the value-channel filter; it gets its own region tag. The decoupled form. energy_pg takes precedence over the coupled form, and implies energy recording (no need to also set energy=True).

All three ride the flat / staged / partitioned region plumbing — the decoupled region gets its own per-rank fan-out under partitioning, just like the value filter (ADR 0064 §4). Read any region's balance via Results.energy(region=<tag>); whole-model via Results.energy().

Precision. precision="f32" emits -precision f32 right after the file name, and the fork stores the per-step result DATA as float32 (about half the bytes, ~7 significant digits; the fork stamps the choice in the file's INFO/STORED_PRECISION). The default "f64" emits no flag, so a default deck is byte-identical to one written before the field existed. The flag precedes -N/-E so it never sits where the fork's -G parser eats trailing tokens. The value is archived in ops.h5 with the recorder's other fields (the /opensees/decl_params row), so a reader knows the recorded precision without opening the .ladruno.

Parameters

file Output .ladruno (HDF5) file path. precision On-disk element type of the recorded data: "f64" (default, lossless) or "f32" (-precision f32, lossy). Anything else raises ValueError; the fork would otherwise warn and keep f64. nodal_responses Tuple of -N tokens (e.g. ("displacement", "reactionForce")). Empty tuple means no nodal recording. elem_responses Tuple of -E tokens (e.g. ("stresses", "section.fiber.stress")). Empty tuple means no element recording. dT Optional time-based cadence (seconds). Mutually exclusive with nsteps. nsteps Optional step-based cadence (every N analysis steps). Mutually exclusive with dT. energy Record the energy balance (-G energy). Whole-model when no filter is set; per-region (over the -R filter region, plus whole-model) when combined with a nodes=/elements= filter. energy_pg Physical-group label for a decoupled energy region — records energy over that PG (-G energy $tag) independent of the value filter. Implies energy recording. Resolved by the bridge build pipeline; gets its own auto-emitted region (per-rank under partitioning). nodes Explicit tuple of node tags for the region filter. Mutually exclusive with nodes_pg. nodes_pg Physical-group label whose nodes the region filter targets. Mutually exclusive with nodes. Resolved by the bridge build pipeline at emit time. elements Explicit tuple of element tags for the region filter. Mutually exclusive with elements_pg. elements_pg Physical-group label whose elements the region filter targets. Mutually exclusive with elements. Resolved by the bridge build pipeline at emit time.

resolve_energy_ids

resolve_energy_ids(fem: 'FEMData', fem_eid_to_ops_tag: 'FemToOpsTagMap | dict[int, int] | None' = None) -> tuple[int, ...]

Resolve energy_pg to element ids for the energy region.

Mirrors the element side of :meth:resolve_filter_ids: returns FEM eids verbatim when fem_eid_to_ops_tag is None (the partition orchestrator intersects per-rank in FEM-eid space), else translates to OpenSees element tags. Empty resolution → :class:BridgeError. Energy is an element quantity, so the region carries -ele only (the fork auto-derives the nodes).

Source code in src/apeGmsh/opensees/recorder.py
def resolve_energy_ids(
    self,
    fem: "FEMData",
    fem_eid_to_ops_tag: "FemToOpsTagMap | dict[int, int] | None" = None,
) -> tuple[int, ...]:
    """Resolve ``energy_pg`` to element ids for the energy region.

    Mirrors the element side of :meth:`resolve_filter_ids`: returns
    FEM eids verbatim when ``fem_eid_to_ops_tag is None`` (the
    partition orchestrator intersects per-rank in FEM-eid space),
    else translates to OpenSees element tags. Empty resolution →
    :class:`BridgeError`. Energy is an element quantity, so the
    region carries ``-ele`` only (the fork auto-derives the nodes).
    """
    from ._internal.build.errors import BridgeError
    from ._internal.build.pg_expand import expand_pg_to_elements

    assert self.energy_pg is not None  # caller-guarded
    fem_eids = tuple(
        eid for eid, _conn in expand_pg_to_elements(fem, self.energy_pg)
    )
    if not fem_eids:
        raise BridgeError(
            f"Ladruno energy region: energy_pg={self.energy_pg!r} "
            "resolved to zero elements against the FEM snapshot. "
            "An empty region is rejected by OpenSees at runtime; check "
            "the PG name spelling and that elements were registered "
            "against it before get_fem_data."
        )
    if fem_eid_to_ops_tag is None:
        return fem_eids
    ops_tags: list[int] = []
    for eid in fem_eids:
        ops_tag = fem_eid_to_ops_tag.get(int(eid))
        if ops_tag is None:
            raise BridgeError(
                f"Ladruno energy region: energy_pg={self.energy_pg!r} "
                f"resolves to FEM eid {eid} but no element was emitted "
                "at that eid — declare an ``ops.element.X(pg=...)`` "
                f"primitive whose pg includes {self.energy_pg!r}."
            )
        ops_tags.append(int(ops_tag))
    return tuple(ops_tags)

splits_filter

splits_filter() -> bool

True iff the filter needs a separate -RN node region.

Both a node selector and an element selector set: one OpenSees region cannot carry both lists (MeshRegion::setNodes / setElements each wipe both), so the nodes go to their own region, read by the fork's -RN (WP-234).

Source code in src/apeGmsh/opensees/recorder.py
def splits_filter(self) -> bool:
    """True iff the filter needs a separate ``-RN`` node region.

    Both a node selector and an element selector set: one OpenSees
    region cannot carry both lists (``MeshRegion::setNodes`` /
    ``setElements`` each wipe both), so the nodes go to their own
    region, read by the fork's ``-RN`` (WP-234).
    """
    return (
        (self.nodes is not None or self.nodes_pg is not None)
        and (self.elements is not None or self.elements_pg is not None)
    )

region_keys

region_keys() -> tuple[str, ...]

The value-filter region (base), the -RN node region when the filter splits, then the decoupled energy region.

The energy region (energy_pg) is independent of the -R value filter (the fork's -G energy <tag> list is orthogonal to -R); it takes its own tag, after the filter's.

Source code in src/apeGmsh/opensees/recorder.py
def region_keys(self) -> tuple[str, ...]:
    """The value-filter region (base), the ``-RN`` node region when the
    filter splits, then the decoupled energy region.

    The energy region (``energy_pg``) is independent of the ``-R``
    value filter (the fork's ``-G energy <tag>`` list is orthogonal to
    ``-R``); it takes its own tag, after the filter's.
    """
    keys = FilterableRecorder.region_keys(self)
    if self.splits_filter():
        keys = (*keys, "nodes")
    if self.energy_pg is not None:
        keys = (*keys, "energy")
    return keys

Monitor dataclass

Monitor(*, sink: str, dofs: tuple[int, ...], nodes: tuple[int, ...] | None = None, pg: str | None = None, resp: str = 'disp', every: int | None = None, hz: float | None = None)

Bases: Recorder

recorder Monitor — live SWMR-HDF5 nodal-telemetry sink (fork-only).

Fork-only. The Monitor recorder exists only in the Ladruno fork build; stock openseespy does not have it. Emission works on any build (the deck line is just recorder Monitor ...); the fork requirement bites only when the deck runs. Gate at the point of use.

Unlike the canonical :class:Ladruno recorder, the Monitor is a lightweight live-telemetry sidecar: it streams a few selected nodal scalars to a small SWMR-HDF5 file a viewer process can tail while the analysis is still running. The same file is a valid at-rest result once the run finishes — read both via :func:apeGmsh.results.read_monitor / :func:apeGmsh.results.tail_monitor.

OpenSees command::

recorder Monitor (-node n1 n2 ... | -region tag) -dof d1 d2 ...
                 [-resp disp|vel|accel|reaction]
                 -sink fname.h5 [-every K] [-hz H]

Exactly one of nodes= (explicit tags) or pg= (physical-group label, resolved against the FEM snapshot by the bridge build pipeline) must be supplied. The recorded channels are the cartesian product of nodes × dofs, labelled node<N>.<resp>.dof<D> in node-major order.

Parameters

sink Output .h5 SWMR sink path. dofs DOF indices (1-based, OpenSees convention). At least one required. nodes Explicit tuple of node tags. Mutually exclusive with pg. pg Physical-group label whose nodes are monitored. Mutually exclusive with nodes; resolved at emit time. resp Nodal response — one of disp / vel / accel / reaction (the fork v1 set). Default disp. every Step decimation — emit a frame every K analysis steps. None records every step. hz Wall-clock throttle — emit at most H frames per second of real time (the first frame always passes). None means no throttle. Independent of every; both may bound the stream.

RecorderRecord dataclass

RecorderRecord(*, category: str, components: tuple[str, ...] = (), raw: tuple[str, ...] = (), pg: tuple[str, ...] = (), label: tuple[str, ...] = (), selection: tuple[str, ...] = (), ids: tuple[int, ...] | None = None, dt: float | None = None, n_steps: int | None = None, name: str | None = None, n_modes: int | None = None, element_class_name: str | None = None)

One category-level declaration entry within a RecorderDeclaration.

Stores already-expanded canonical components (or raw OpenSees tokens via the raw= escape hatch). Shorthand expansion ("displacement" → displacement_x/y/z) happens at construction in the namespace method (Phase 9 commit 3), not in this dataclass — by the time a record is built, components are fully expanded.

Parameters

category One of :data:ALL_RECORDER_CATEGORIES. components Tuple of canonical component names, each one the category records (:func:apeGmsh._vocabulary.in_category: the CATEGORY_COMPONENTS table plus its indexed canonicals, state_variable_<n>, fiber_stress_<n>, spring_force_<n>). A bare string is one component. raw Escape hatch for non-canonical OpenSees tokens (e.g. a custom recorder response). Bypasses canonical validation. pg / label / selection / ids Target selectors. ids= is mutually exclusive with the named selectors. Resolution against FEMData happens at emit time (commit 3). dt / n_steps Recording cadence. At most one may be set; both None records every step. name Optional user-supplied name for this record; auto-generated when None. n_modes Required for category="modal"; rejected for other categories. element_class_name Optional OpenSees C++ class name override for element-level records. Used by the .out transcoder to disambiguate elements that share a flat response size (e.g. tri31 vs SSPquad). Carried from the legacy Recorders.elements contract.

RecorderDeclaration dataclass

RecorderDeclaration(*, records: tuple[RecorderRecord, ...], name: str = 'default', ndm: int = 3, ndf: int = 6, file_root: str = '.')

Bases: Recorder

A bundle of recorder records, registered as a single Primitive.

Captures the bridge's ndm and ndf at construction time (Phase 9 D8 — implicit source-of-truth binding). Drives the file-emit path via :func:emit_recorder_spec in :mod:apeGmsh.opensees._internal.build.

Parameters

records Tuple of :class:RecorderRecord entries. Each is one category-level declaration; emit fans them out into one or more concrete OpenSees recorder commands. name Identifier for this declaration (defaults to "default"). Multiple named declarations can coexist on one bridge. ndm, ndf Snapshot of the bridge's ndm/ndf at construction time. Used downstream for shorthand expansion and validation. The bridge passes these in (Phase 9 D8 — user never repeats ops.model(ndm=, ndf=) values). file_root Directory prefix for emitted .out files. Each record fans out to <file_root>/<decl.name>__<record_name>__<token>.out. Defaults to "." (current working directory).

build_recorder_declaration

build_recorder_declaration(*, ndm: int, ndf: int, nodes: 'Iterable[str] | str' = (), elements: 'Iterable[str] | str' = (), line_stations: 'Iterable[str] | str' = (), gauss: 'Iterable[str] | str' = (), raw_nodes: 'Iterable[str] | str | None' = None, raw_elements: 'Iterable[str] | str | None' = None, raw_line_stations: 'Iterable[str] | str | None' = None, raw_gauss: 'Iterable[str] | str | None' = None, pg: 'str | Iterable[str] | None' = None, label: 'str | Iterable[str] | None' = None, selection: 'str | Iterable[str] | None' = None, ids: 'Iterable[int] | None' = None, dt: float | None = None, n_steps: int | None = None, name: str = 'default', record_name: str | None = None, element_class_name: str | None = None, file_root: str = '.') -> RecorderDeclaration

Construct a :class:RecorderDeclaration from declarative kwargs.

Single source of truth for shorthand expansion ("displacement" → displacement_x/y/z via the bound ndm/ndf) and per-category record construction. Shared by :meth:apeGmsh.opensees._internal.ns.recorder._RecorderNS.declare (bridge-owned models) and :meth:apeGmsh.opensees.ModelData.recorders (hand-written decks).

ndm / ndf are supplied by the caller (the bridge or ModelData binds them at declaration time, Phase 9 D8 — the user never repeats ndm=/ndf= here).

Source code in src/apeGmsh/opensees/recorder.py
def build_recorder_declaration(
    *,
    ndm: int,
    ndf: int,
    nodes: "Iterable[str] | str" = (),
    elements: "Iterable[str] | str" = (),
    line_stations: "Iterable[str] | str" = (),
    gauss: "Iterable[str] | str" = (),
    raw_nodes: "Iterable[str] | str | None" = None,
    raw_elements: "Iterable[str] | str | None" = None,
    raw_line_stations: "Iterable[str] | str | None" = None,
    raw_gauss: "Iterable[str] | str | None" = None,
    pg: "str | Iterable[str] | None" = None,
    label: "str | Iterable[str] | None" = None,
    selection: "str | Iterable[str] | None" = None,
    ids: "Iterable[int] | None" = None,
    dt: float | None = None,
    n_steps: int | None = None,
    name: str = "default",
    record_name: str | None = None,
    element_class_name: str | None = None,
    file_root: str = ".",
) -> RecorderDeclaration:
    """Construct a :class:`RecorderDeclaration` from declarative kwargs.

    Single source of truth for shorthand expansion (``"displacement"``
    → ``displacement_x/y/z`` via the bound ``ndm``/``ndf``) and
    per-category record construction.  Shared by
    :meth:`apeGmsh.opensees._internal.ns.recorder._RecorderNS.declare`
    (bridge-owned models) and
    :meth:`apeGmsh.opensees.ModelData.recorders` (hand-written decks).

    ``ndm`` / ``ndf`` are supplied by the caller (the bridge or
    ``ModelData`` binds them at declaration time, Phase 9 D8 — the user
    never repeats ``ndm=``/``ndf=`` here).
    """
    pg_tuple = _normalize_str_selector(pg)
    label_tuple = _normalize_str_selector(label)
    selection_tuple = _normalize_str_selector(selection)
    ids_tuple = tuple(int(i) for i in ids) if ids is not None else None

    records: list[RecorderRecord] = []

    # Per-category record construction. Each category produces at most
    # one record (canonical components + raw tokens combined). A record
    # is skipped only when both are empty for that category.
    category_inputs: tuple[
        tuple[str, "Iterable[str] | str", "Iterable[str] | str | None"], ...
    ] = (
        ("nodes",         nodes,         raw_nodes),
        ("elements",      elements,      raw_elements),
        ("line_stations", line_stations, raw_line_stations),
        ("gauss",         gauss,         raw_gauss),
    )
    for category, canonical_kw, raw_kw in category_inputs:
        canonical_seq = _normalize_str_selector(canonical_kw)
        raw_seq = _normalize_str_selector(raw_kw)
        if not canonical_seq and not raw_seq:
            continue
        components = (
            expand_many(canonical_seq, ndm=ndm, ndf=ndf)
            if canonical_seq else ()
        )
        records.append(
            RecorderRecord(
                category=category,
                components=components,
                raw=raw_seq,
                pg=pg_tuple,
                label=label_tuple,
                selection=selection_tuple,
                ids=ids_tuple,
                dt=dt,
                n_steps=n_steps,
                name=record_name,
                element_class_name=(
                    element_class_name if category != "nodes" else None
                ),
            )
        )

    return RecorderDeclaration(
        records=tuple(records),
        name=name,
        ndm=ndm,
        ndf=ndf,
        file_root=file_root,
    )

Building tables

Story forces, story drifts, pier forces and story masses (the ETABS Story Forces, Story Drifts, Pier Forces and Mass Summary by Story tables), read in-process from the live domain. The extractor classes are callables extractor(ops) -> ndarray with a labels tuple, so a modal driver can evaluate them at each mode.

apeGmsh.opensees.building

Story and pier aggregation on the live OpenSees domain.

The building tables an ETABS model reports — Story Forces, Story Drifts, Pier Forces and Mass Summary by Story / Centers of Mass — computed in-process from the domain the bridge built (:func:~apeGmsh.opensees.emitter.live.get_ops, or an explicit ops=).

Every quantity is read from the current domain state, so the same object serves a static case, the gravity state of a P-Delta run, and each mode of a response-spectrum analysis.

Extractors

:class:StoryForces, :class:StoryDrifts and :class:PierForces are extractors: callables extractor(ops) -> ndarray of a fixed length, with a matching labels tuple (the :class:Extractor protocol). The domain is scanned once, at construction (node coordinates, element connectivity, the elements and nodes each cut needs, the checks below); a call only reads element forces and node displacements for those, both at the trial state (eleForce is the trial resisting force; a displacement is nodeDisp, the committed value, plus nodeResponse IncrDisp, trial minus committed). After a committed solve the two states agree; an uncommitted trial state, such as gravity plus one mode left by responseSpectrumAnalysis -increment, is read as is. A modal driver evaluates an extractor at each mode and combines each entry of the vector across modes; :meth:StoryForces.table (and the other table methods) reshapes any such vector, combined or not, into a :class:StoryTable. The plain functions :func:story_forces, :func:story_drifts, :func:pier_forces and :func:story_masses are the one-off forms.

The free body

A story or pier force is the resultant the part above a horizontal cut transmits to the part below. The cut is node-aligned: it runs through the nodes at the cut elevation, and an element belongs to the part above when all its nodes are at or above the cut and it does not lie in the cut plane. Elements in the plane (the floor slab, the level's beams) belong to the part below; nodal loads on cut nodes act on the part below. eleForce (the forces response: Element::getResistingForce, the global nodal force vector the integrator assembles, element loads included) of the elements above that touch the cut gives, at each cut node, the force the node applies to them; the force they transmit is its negative. Hence, for a structure loaded only above the cut,

``(VX, VY, P) = sum of the loads applied above the cut``

exactly (to solver round-off), and at the base it equals -sum(R) (:func:base_shear_from_reactions). Negate the six components for the reaction convention. The top of a story (location="top") is the cut just below a level, read from the elements below it that touch the level.

Refusals

  • an element whose nodes lie strictly on both sides of a cut (the cut is not node-aligned there);
  • an MP constraint (rigid link, equalDOF, ...) joining a node of the part above to a node of the part below: it carries force past the elements, so the element free body would miss it;
  • any EQ constraint in the domain (equationConstraint, the fork's LadrunoTie): OpenSees does not report their nodes, so whether one crosses a cut cannot be checked. The count comes from a printModel dump to a temporary file, which :class:StoryForces writes once, at construction, never per call. It costs about 30 µs per node and element on a fresh domain, and up to ~150 µs once eigen has run, because Node::Print then writes every eigenvector (16.6 s and 42 MB for 10k shells after eigen(50)): build the extractor before eigen, once, and evaluate it at every mode;
  • in :class:StoryDrifts joint mode, a node on a level with no node at the same plan position on the level below (a cantilever tip, a transfer level, an offset column), named; dropping it would hide its drift;
  • an element whose forces vector is not one value per DOF of its nodes (eleType is named);
  • nodes with an ndf other than 3 or 6, and 2-D models.

Code checks

The tables carry what an ASCE 7 check reads; naming columns is the caller's. AvgX / AvgY are the ASCE 7-22 average of the signed values at the two ends of the structure (Table 12.3-1, Types 1a/1b; delta_avg of Eq. 12.8-14), |d_A + d_B| / 2, the ends being the entries farthest apart across the direction (:func:_max_avg). It is not a mean over every joint, so the max/avg ratio and Ax do not move with the mesh. For example, apeETABS's TorsionCheck drifts frame::

t = drifts.story_max(combined).to_frame().rename_axis("Story").reset_index()
h = dict(zip(drifts.stories, drifts.heights))
t["Elevation"] = list(drifts.levels[1:])
t["drift_max"] = t["DriftX"] * t["Story"].map(h)
t["drift_avg"] = t["AvgX"] * t["Story"].map(h)

and its displacements frame (for Ax) is StoryDisplacements.story_max() with MaxX, AvgX renamed Maximum, Average.

Extractor

Bases: Protocol

A live quantity: extractor(ops) returns a 1-D float64 array of len(labels) entries, read from the current domain state.

StoryTable dataclass

StoryTable(rows: tuple[str, ...], columns: tuple[str, ...], values: FloatArray)

A small labelled table: values[i, j] is row rows[i], column columns[j].

column

column(name: str) -> FloatArray

The column name, one value per row.

Source code in src/apeGmsh/opensees/building.py
def column(self, name: str) -> FloatArray:
    """The column ``name``, one value per row."""
    return np.asarray(self.values[:, self.columns.index(name)])

row

row(name: str) -> FloatArray

The row name, one value per column.

Source code in src/apeGmsh/opensees/building.py
def row(self, name: str) -> FloatArray:
    """The row ``name``, one value per column."""
    return np.asarray(self.values[self.rows.index(name), :])

to_frame

to_frame() -> 'pandas.DataFrame'

The table as a :class:pandas.DataFrame (pandas imported lazily).

Source code in src/apeGmsh/opensees/building.py
def to_frame(self) -> "pandas.DataFrame":
    """The table as a :class:`pandas.DataFrame` (pandas imported lazily)."""
    import pandas as pd

    return pd.DataFrame(self.values, index=list(self.rows),
                        columns=list(self.columns))

StoryForces

StoryForces(levels: Sequence[float], *, names: Sequence[str] | None = None, location: Literal['bottom', 'top'] = 'bottom', reference: tuple[float, float] = (0.0, 0.0), ops: ModuleType | None = None, tol: float | None = None)

Story shear and overturning per story, as an :class:Extractor.

Parameters

levels Level elevations, strictly increasing, the base first. Story i (i = 1..n) spans levels[i-1] to levels[i] and is named after its top level. names One name per level (default "Base", "Story1", ...). location "bottom" (default): the cut just above levels[i-1], the resultant of every load above that level. "top": the cut just below levels[i], the resultant of every load at or above it. reference Plan point (x, y) the moments are taken about, at each cut's elevation (default the origin). MZ is the story torsion. ops The OpenSees module; default :func:~apeGmsh.opensees.emitter.live.get_ops. tol Elevation tolerance; default 1e-6 of the model's size.

A call returns [VX, VY, P, MX, MY, MZ] per story, stories in level order (labels names each entry "<story>:<component>").

Construction checks the domain for EQ constraints with one printModel dump (see Refusals); a call does not repeat it. Build the extractor before eigen (the dump then omits eigenvectors) and evaluate the same object at every mode.

Source code in src/apeGmsh/opensees/building.py
def __init__(
    self,
    levels: Sequence[float],
    *,
    names: Sequence[str] | None = None,
    location: Literal["bottom", "top"] = "bottom",
    reference: tuple[float, float] = (0.0, 0.0),
    ops: ModuleType | None = None,
    tol: float | None = None,
) -> None:
    where = "StoryForces"
    if location not in ("bottom", "top"):
        raise ValueError(f"{where}: location must be 'bottom' or 'top', "
                         f"got {location!r}.")
    z = _check_levels(levels, where)
    level_names = _level_names(names, z.size, where)
    self.levels: tuple[float, ...] = tuple(float(v) for v in z)
    self.stories: tuple[str, ...] = level_names[1:]
    self.location = location
    self._ref_xy = (float(reference[0]), float(reference[1]))
    module = _resolve_ops(ops)
    self._dom = _capture(module, tol, where)
    n_eq = _eq_constraint_count(module, where)
    if n_eq:
        raise BridgeError(
            f"{where}: the domain holds {n_eq} EQ constraint(s) "
            "(equationConstraint, LadrunoTie, or an enforce='equation' "
            "tie). OpenSees does not report their nodes, so a cut "
            "cannot tell whether one carries force past the elements, "
            "which the element free body would miss. Story forces "
            "refuse any EQ constraint; tie with equalDOF / rigid links "
            "inside a level, or read the forces from a model without them."
        )
    mp = _mp_pairs(module, self._dom)
    self._gather = _Gatherer()
    cuts: list[_Cut] = []
    for i in range(1, z.size):
        if location == "bottom":
            cuts.append(_build_cut(module, self._dom, self._gather, z[i - 1],
                                   "above", None, f"{where} {self.stories[i-1]}",
                                   check_mp=mp))
        else:
            cuts.append(_build_cut(module, self._dom, self._gather, z[i],
                                   "below", None, f"{where} {self.stories[i-1]}",
                                   check_mp=mp))
    self._gather.freeze()
    self._cuts = tuple(cuts)
    self.labels: tuple[str, ...] = tuple(
        f"{s}:{c}" for s in self.stories for c in STORY_FORCE_COMPONENTS)

table

table(values: FloatArray | None = None, *, ops: ModuleType | None = None) -> StoryTable

values (a call's vector, or any combination of them) as a story × component table; evaluates now when values is None.

Source code in src/apeGmsh/opensees/building.py
def table(self, values: FloatArray | None = None, *,
          ops: ModuleType | None = None) -> StoryTable:
    """``values`` (a call's vector, or any combination of them) as a
    story × component table; evaluates now when ``values`` is ``None``."""
    v = self(ops) if values is None else _check_len(values, self.labels)
    return StoryTable(self.stories, STORY_FORCE_COMPONENTS,
                      v.reshape(len(self.stories), 6))

StoryDrifts

StoryDrifts(levels: Sequence[float], *, points: Sequence[tuple[float, float]] | None = None, names: Sequence[str] | None = None, method: Literal['nearest', 'rigid'] = 'nearest', max_offset: float | None = None, ops: ModuleType | None = None, tol: float | None = None)

Interstory drift ratios (u_top - u_bottom) / h, as an :class:Extractor.

Parameters

levels, names, ops, tol As :class:StoryForces. points Plan points (x, y) to report. None (default) reports every joint: each node at a level that has a node at the same plan position (within tol) on the level below — ETABS Joint Drifts, whose maximum per story (:meth:story_max) is ETABS Story Drifts. A node on a level above the base with no node at its plan position on the level below raises, named (its drift would otherwise be left out). method How a point reads a level's displacement. "nearest": the nearest node of the level in plan, which must lie within max_offset (default tol). "rigid": the least-squares in-plane rigid motion (ux, uy, rz) of all the level's nodes, evaluated at the point (exact for a rigid diaphragm).

A call returns [DX, DY] per entry, entries per story in level order; labels reads "<story>:<node>:DX" (joints) or "<story>:P<j>:DX" (points). Displacements are the trial displacements (see the module notes).

Source code in src/apeGmsh/opensees/building.py
def __init__(
    self,
    levels: Sequence[float],
    *,
    points: Sequence[tuple[float, float]] | None = None,
    names: Sequence[str] | None = None,
    method: Literal["nearest", "rigid"] = "nearest",
    max_offset: float | None = None,
    ops: ModuleType | None = None,
    tol: float | None = None,
) -> None:
    where = "StoryDrifts"
    if method not in ("nearest", "rigid"):
        raise ValueError(f"{where}: method must be 'nearest' or 'rigid', "
                         f"got {method!r}.")
    z = _check_levels(levels, where)
    level_names = _level_names(names, z.size, where)
    self.levels: tuple[float, ...] = tuple(float(v) for v in z)
    self.stories: tuple[str, ...] = level_names[1:]
    self.heights: tuple[float, ...] = tuple(float(h) for h in np.diff(z))
    module = _resolve_ops(ops)
    dom = _capture(module, tol, where)
    self._dom = dom
    on_level = [np.flatnonzero(np.abs(dom.coords[:, 2] - zk) <= dom.tol)
                for zk in z]
    for k, rows in enumerate(on_level):
        if rows.size == 0:
            raise BridgeError(f"{where}: no node lies on level "
                              f"{level_names[k]!r} (z={z[k]:g}).")
    # Each entry: (story index, top operator, bottom operator); an
    # operator maps the level's needed node displacements to (ux, uy).
    self._story: list[int] = []
    self._ops_top: list[tuple[IntArray, FloatArray]] = []
    self._ops_bot: list[tuple[IntArray, FloatArray]] = []
    self._xy: list[FloatArray] = []          # plan point of each entry
    labels: list[str] = []
    if points is None:
        for i in range(1, z.size):
            top, bot = on_level[i], on_level[i - 1]
            d = np.linalg.norm(dom.coords[top, None, :2]
                               - dom.coords[None, bot, :2], axis=2)
            b_of = np.argmin(d, axis=1)
            lone = top[d[np.arange(top.size), b_of] > dom.tol]
            if lone.size:
                tags = [int(t) for t in dom.node_tags[lone[:8]]]
                raise BridgeError(
                    f"{where}: story {self.stories[i-1]!r}: node(s) {tags}"
                    f"{' ...' if lone.size > 8 else ''} of level "
                    f"{level_names[i]!r} (z={z[i]:g}) have no node at the "
                    f"same plan position on level {level_names[i-1]!r} "
                    f"(z={z[i-1]:g}), as at a cantilever tip, a transfer "
                    "level or an offset column. Dropping them would hide "
                    "their drift; pass points= (method='rigid' for a "
                    "rigid diaphragm)."
                )
            for a, row in enumerate(top):
                self._add(i - 1, _pick(int(row)), _pick(int(bot[int(b_of[a])])),
                          dom.coords[row, :2])
                tag = int(dom.node_tags[row])
                labels += [f"{self.stories[i-1]}:{tag}:DX",
                           f"{self.stories[i-1]}:{tag}:DY"]
    else:
        pts = [(float(p[0]), float(p[1])) for p in points]
        if not pts:
            raise ValueError(f"{where}: points is empty; pass None for every joint.")
        off = dom.tol if max_offset is None else float(max_offset)
        per_level: list[list[tuple[IntArray, FloatArray]]] = []
        for k, rows in enumerate(on_level):
            if method == "nearest":
                per_level.append([
                    _nearest(dom, rows, p, off, f"{where} level "
                             f"{level_names[k]!r}") for p in pts])
            else:
                per_level.append(_rigid(dom, rows, pts,
                                        f"{where} level {level_names[k]!r}"))
        for i in range(1, z.size):
            for j in range(len(pts)):
                self._add(i - 1, per_level[i][j], per_level[i - 1][j],
                          np.asarray(pts[j]))
                labels += [f"{self.stories[i-1]}:P{j}:DX",
                           f"{self.stories[i-1]}:P{j}:DY"]
    need = sorted({int(r) for op in self._ops_top + self._ops_bot for r in op[0]})
    self._need = np.asarray(need, dtype=np.int64)
    pos = {r: k for k, r in enumerate(need)}
    self._top_idx = [np.asarray([pos[int(r)] for r in op[0]], dtype=np.int64)
                     for op in self._ops_top]
    self._bot_idx = [np.asarray([pos[int(r)] for r in op[0]], dtype=np.int64)
                     for op in self._ops_bot]
    self._h = np.asarray([self.heights[s] for s in self._story])
    self._xy_arr = np.asarray(self._xy, dtype=np.float64).reshape(-1, 2)
    self.labels: tuple[str, ...] = tuple(labels)

table

table(values: FloatArray | None = None, *, ops: ModuleType | None = None) -> StoryTable

Every entry as a row ("<story>:<node|P<j>>"), columns DX, DY.

Source code in src/apeGmsh/opensees/building.py
def table(self, values: FloatArray | None = None, *,
          ops: ModuleType | None = None) -> StoryTable:
    """Every entry as a row (``"<story>:<node|P<j>>"``), columns ``DX, DY``."""
    v = self(ops) if values is None else _check_len(values, self.labels)
    rows = tuple(lab.rsplit(":", 1)[0] for lab in self.labels[::2])
    return StoryTable(rows, ("DX", "DY"), v.reshape(-1, 2))

story_max

story_max(values: FloatArray | None = None, *, ops: ModuleType | None = None) -> StoryTable

The largest |DX| and |DY| of each story (ETABS Story Drifts), and beside them AvgX, AvgY: the ASCE 7 average of the signed story drifts at the two ends of the structure, |d_A + d_B| / 2 (:func:_max_avg), the denominator of the Table 12.3-1 torsional irregularity ratio. For a modal combination, pass the combined vector: the maximum of the combined joint drifts, not the combination of maxima.

Source code in src/apeGmsh/opensees/building.py
def story_max(self, values: FloatArray | None = None, *,
              ops: ModuleType | None = None) -> StoryTable:
    """The largest ``|DX|`` and ``|DY|`` of each story (ETABS *Story
    Drifts*), and beside them ``AvgX``, ``AvgY``: the ASCE 7 average of
    the signed story drifts at the two ends of the structure,
    ``|d_A + d_B| / 2`` (:func:`_max_avg`), the denominator of the
    Table 12.3-1 torsional irregularity ratio. For a modal combination,
    pass the combined vector: the maximum of the combined joint drifts,
    not the combination of maxima."""
    v = self(ops) if values is None else _check_len(values, self.labels)
    return StoryTable(self.stories, ("DriftX", "DriftY", "AvgX", "AvgY"),
                      _max_avg(v, self._story, self._xy_arr,
                               len(self.stories), self._dom.tol))

StoryDisplacements

StoryDisplacements(levels: Sequence[float], *, points: Sequence[tuple[float, float]] | None = None, names: Sequence[str] | None = None, method: Literal['nearest', 'rigid'] = 'nearest', max_offset: float | None = None, ops: ModuleType | None = None, tol: float | None = None)

Level displacements UX, UY, as an :class:Extractor.

Every node on each level above the base (points=None), or the given plan points read as :class:StoryDrifts reads them (method, max_offset). :meth:story_max gives each level's largest |UX|, |UY| and the ASCE 7 average of the signed values at the two ends, |d_A + d_B| / 2: the input of a torsional-irregularity or torsional-amplification check. labels read "<story>:<node>:UX" or "<story>:P<j>:UX"; the other parameters are as for :class:StoryDrifts.

Source code in src/apeGmsh/opensees/building.py
def __init__(
    self,
    levels: Sequence[float],
    *,
    points: Sequence[tuple[float, float]] | None = None,
    names: Sequence[str] | None = None,
    method: Literal["nearest", "rigid"] = "nearest",
    max_offset: float | None = None,
    ops: ModuleType | None = None,
    tol: float | None = None,
) -> None:
    where = "StoryDisplacements"
    if method not in ("nearest", "rigid"):
        raise ValueError(f"{where}: method must be 'nearest' or 'rigid', "
                         f"got {method!r}.")
    z = _check_levels(levels, where)
    level_names = _level_names(names, z.size, where)
    self.levels: tuple[float, ...] = tuple(float(v) for v in z)
    self.stories: tuple[str, ...] = level_names[1:]
    module = _resolve_ops(ops)
    self._dom = dom = _capture(module, tol, where)
    self._story: list[int] = []
    self._ops: list[tuple[IntArray, FloatArray]] = []
    self._xy: list[FloatArray] = []          # plan point of each entry
    labels: list[str] = []
    for i in range(1, z.size):
        w = f"{where} level {level_names[i]!r}"
        rows = np.flatnonzero(np.abs(dom.coords[:, 2] - z[i]) <= dom.tol)
        if rows.size == 0:
            raise BridgeError(f"{w}: no node lies on it (z={z[i]:g}).")
        if points is None:
            ops_i = [_pick(int(r)) for r in rows]
            keys = [str(int(dom.node_tags[r])) for r in rows]
            xy_i = [dom.coords[r, :2] for r in rows]
        else:
            pts = [(float(p[0]), float(p[1])) for p in points]
            off = dom.tol if max_offset is None else float(max_offset)
            ops_i = ([_nearest(dom, rows, p, off, w) for p in pts]
                     if method == "nearest" else _rigid(dom, rows, pts, w))
            keys = [f"P{j}" for j in range(len(pts))]
            xy_i = [np.asarray(p) for p in pts]
        for op, key, xy in zip(ops_i, keys, xy_i):
            self._story.append(i - 1)
            self._ops.append(op)
            self._xy.append(xy)
            labels += [f"{level_names[i]}:{key}:UX", f"{level_names[i]}:{key}:UY"]
    self._xy_arr = np.asarray(self._xy, dtype=np.float64).reshape(-1, 2)
    self.labels: tuple[str, ...] = tuple(labels)

table

table(values: FloatArray | None = None, *, ops: ModuleType | None = None) -> StoryTable

Every entry as a row ("<story>:<node|P<j>>"), columns UX, UY.

Source code in src/apeGmsh/opensees/building.py
def table(self, values: FloatArray | None = None, *,
          ops: ModuleType | None = None) -> StoryTable:
    """Every entry as a row (``"<story>:<node|P<j>>"``), columns ``UX, UY``."""
    v = self(ops) if values is None else _check_len(values, self.labels)
    rows = tuple(lab.rsplit(":", 1)[0] for lab in self.labels[::2])
    return StoryTable(rows, ("UX", "UY"), v.reshape(-1, 2))

story_max

story_max(values: FloatArray | None = None, *, ops: ModuleType | None = None) -> StoryTable

Per level MaxX, MaxY, AvgX, AvgY: the largest |UX|, |UY| over its entries, and the ASCE 7 average of the signed displacements at the two ends of the structure, |d_A + d_B| / 2 (:func:_max_avg; delta_avg of Eq. 12.8-14). Pass a combined vector for a modal combination.

Source code in src/apeGmsh/opensees/building.py
def story_max(self, values: FloatArray | None = None, *,
              ops: ModuleType | None = None) -> StoryTable:
    """Per level ``MaxX, MaxY, AvgX, AvgY``: the largest ``|UX|``,
    ``|UY|`` over its entries, and the ASCE 7 average of the signed
    displacements at the two ends of the structure, ``|d_A + d_B| / 2``
    (:func:`_max_avg`; ``delta_avg`` of Eq. 12.8-14). Pass a combined
    vector for a modal combination."""
    v = self(ops) if values is None else _check_len(values, self.labels)
    return StoryTable(self.stories, ("MaxX", "MaxY", "AvgX", "AvgY"),
                      _max_avg(v, self._story, self._xy_arr,
                               len(self.stories), self._dom.tol))

Pier dataclass

Pier(name: str, elements: tuple[int, ...], bottom: float | None = None, top: float | None = None, axis2: tuple[float, float] | None = None)

A wall pier: OpenSees element tags between two node-aligned cuts.

bottom / top default to the lowest / highest node of the elements. axis2 is the plan direction of the pier's length (local axis 2); by default the principal direction of the bottom cut's nodes, oriented toward +X (+Y when it runs along Y). Axis 1 is +Z and axis 3 = axis 1 × axis 2.

from_pg classmethod

from_pg(bridge: 'apeSees', pg: str, *, name: str | None = None, bottom: float | None = None, top: float | None = None, axis2: tuple[float, float] | None = None) -> 'Pier'

The pier of physical group pg's elements in bridge.

FEM element ids map to OpenSees tags directly under element_tags="fem"; otherwise through the bridge's live read session (after a live analyze), which raises when there is none.

Source code in src/apeGmsh/opensees/building.py
@classmethod
def from_pg(
    cls,
    bridge: "apeSees",
    pg: str,
    *,
    name: str | None = None,
    bottom: float | None = None,
    top: float | None = None,
    axis2: tuple[float, float] | None = None,
) -> "Pier":
    """The pier of physical group ``pg``'s elements in ``bridge``.

    FEM element ids map to OpenSees tags directly under
    ``element_tags="fem"``; otherwise through the bridge's live read
    session (after a live ``analyze``), which raises when there is none.
    """
    from ._readback import live_session

    where = f"Pier.from_pg({pg!r})"
    ids = [int(e) for e in bridge.fem.elements.select(pg=pg).ids]
    if not ids:
        raise ValueError(f"{where}: the physical group has no elements.")
    if bridge._element_tags == "fem":
        tags = tuple(ids)
    else:
        rows = live_session(bridge, where).element_rows(ids, where)
        tags = tuple(t for _spec, t in rows)
    return cls(name=pg if name is None else name, elements=tags,
               bottom=bottom, top=top, axis2=axis2)

PierForces

PierForces(piers: Sequence[Pier], *, ops: ModuleType | None = None, tol: float | None = None)

Pier forces at the bottom and top of each pier, as an :class:Extractor.

P, V2, V3, T, M2, M3 in pier local axes (axis 1 up, axis 2 along the pier in plan, axis 3 = 1 × 2), moments about the centroid of the pier section at the cut (the length-weighted centroid of the element edges on the cut, which assumes a uniform thickness). Both cuts give the force the part above transmits to the part below, so P is negative in compression and, under a lateral load H along axis 2 at height L above the cut, V2 = H and M3 = H L.

A call returns, per pier, the bottom row then the top row; labels reads "<pier>:bottom:P".

Source code in src/apeGmsh/opensees/building.py
def __init__(
    self,
    piers: Sequence[Pier],
    *,
    ops: ModuleType | None = None,
    tol: float | None = None,
) -> None:
    where = "PierForces"
    self.piers: tuple[Pier, ...] = tuple(piers)
    if not self.piers:
        raise ValueError(f"{where}: piers is empty.")
    names = [p.name for p in self.piers]
    if len(set(names)) != len(names):
        raise ValueError(f"{where}: pier names must be unique; got {names}.")
    module = _resolve_ops(ops)
    dom = _capture(module, tol, where)
    self._dom = dom
    self._gather = _Gatherer()
    cuts: list[_PierCuts] = []
    for p in self.piers:
        w = f"{where} {p.name!r}"
        idx = _element_index(dom, p, w)
        zb = float(dom.ele_zmin[idx].min()) if p.bottom is None else float(p.bottom)
        zt = float(dom.ele_zmax[idx].max()) if p.top is None else float(p.top)
        if not zt > zb + dom.tol:
            raise ValueError(f"{w}: top ({zt:g}) must lie above bottom ({zb:g}).")
        outside = idx[(dom.ele_zmin[idx] < zb - dom.tol)
                      | (dom.ele_zmax[idx] > zt + dom.tol)]
        if outside.size:
            bad = [int(dom.ele_tags[k]) for k in outside[:8]]
            raise BridgeError(
                f"{w}: element(s) {bad} reach outside the pier's cuts "
                f"(z {zb:g} to {zt:g}); split a multi-story pier with "
                "piers_by_story()."
            )
        bot = _build_cut(module, dom, self._gather, zb, "above", idx, w,
                         check_mp=None)
        top = _build_cut(module, dom, self._gather, zt, "below", idx, w,
                         check_mp=None)
        axes = _pier_axes(dom, bot, p.axis2, w)
        cuts.append(_PierCuts(bot, top, axes, _section_centroid(dom, bot, zb),
                              _section_centroid(dom, top, zt)))
    self._gather.freeze()
    self._cuts = tuple(cuts)
    self.labels: tuple[str, ...] = tuple(
        f"{p.name}:{loc}:{c}" for p in self.piers for loc in ("bottom", "top")
        for c in PIER_FORCE_COMPONENTS)

centroids

centroids() -> StoryTable

Each cut's section centroid (x, y, z): rows "<pier>:bottom|top".

Source code in src/apeGmsh/opensees/building.py
def centroids(self) -> StoryTable:
    """Each cut's section centroid ``(x, y, z)``: rows ``"<pier>:bottom|top"``."""
    rows = tuple(f"{p.name}:{loc}" for p in self.piers for loc in ("bottom", "top"))
    vals = np.vstack([c for pc in self._cuts for c in (pc.c_bottom, pc.c_top)])
    return StoryTable(rows, ("X", "Y", "Z"), vals)

axes

axes(name: str) -> FloatArray

The (3, 3) local axes of pier name, rows axis 1, 2, 3.

Source code in src/apeGmsh/opensees/building.py
def axes(self, name: str) -> FloatArray:
    """The ``(3, 3)`` local axes of pier ``name``, rows axis 1, 2, 3."""
    return np.asarray(self._cuts[[p.name for p in self.piers].index(name)].axes)

table

table(values: FloatArray | None = None, *, ops: ModuleType | None = None) -> StoryTable

Rows "<pier>:bottom|top", columns P, V2, V3, T, M2, M3.

Source code in src/apeGmsh/opensees/building.py
def table(self, values: FloatArray | None = None, *,
          ops: ModuleType | None = None) -> StoryTable:
    """Rows ``"<pier>:bottom|top"``, columns ``P, V2, V3, T, M2, M3``."""
    v = self(ops) if values is None else _check_len(values, self.labels)
    rows = tuple(f"{p.name}:{loc}" for p in self.piers for loc in ("bottom", "top"))
    return StoryTable(rows, PIER_FORCE_COMPONENTS, v.reshape(-1, 6))

story_forces

story_forces(levels: Sequence[float], *, names: Sequence[str] | None = None, location: Literal['bottom', 'top'] = 'bottom', reference: tuple[float, float] = (0.0, 0.0), ops: ModuleType | None = None, tol: float | None = None) -> StoryTable

One-off :class:StoryForces table at the current domain state.

Source code in src/apeGmsh/opensees/building.py
def story_forces(
    levels: Sequence[float],
    *,
    names: Sequence[str] | None = None,
    location: Literal["bottom", "top"] = "bottom",
    reference: tuple[float, float] = (0.0, 0.0),
    ops: ModuleType | None = None,
    tol: float | None = None,
) -> StoryTable:
    """One-off :class:`StoryForces` table at the current domain state."""
    return StoryForces(levels, names=names, location=location,
                       reference=reference, ops=ops, tol=tol).table(ops=ops)

base_shear_from_reactions

base_shear_from_reactions(z_base: float, *, reference: tuple[float, float] = (0.0, 0.0), ops: ModuleType | None = None, tol: float | None = None) -> FloatArray

-sum(R) over the nodes at or below z_base, as [VX, VY, P, MX, MY, MZ] about (reference, z_base).

The cross-check of the base story's :class:StoryForces row: the two agree when no load is applied at or below the base. Calls ops.reactions().

Source code in src/apeGmsh/opensees/building.py
def base_shear_from_reactions(
    z_base: float,
    *,
    reference: tuple[float, float] = (0.0, 0.0),
    ops: ModuleType | None = None,
    tol: float | None = None,
) -> FloatArray:
    """``-sum(R)`` over the nodes at or below ``z_base``, as
    ``[VX, VY, P, MX, MY, MZ]`` about ``(reference, z_base)``.

    The cross-check of the base story's :class:`StoryForces` row: the two
    agree when no load is applied at or below the base. Calls
    ``ops.reactions()``.
    """
    module = _resolve_ops(ops)
    dom = _capture(module, tol, "base_shear_from_reactions")
    module.reactions()
    ref = np.array([float(reference[0]), float(reference[1]), float(z_base)])
    force = np.zeros(3)
    moment = np.zeros(3)
    for r in np.flatnonzero(dom.coords[:, 2] <= float(z_base) + dom.tol):
        reac = np.asarray(module.nodeReaction(int(dom.node_tags[r])), dtype=np.float64)
        f = reac[:3]
        force += f
        moment += np.cross(dom.coords[r] - ref, f)
        if reac.size >= 6:
            moment += reac[3:6]
    return np.asarray(-np.concatenate([force, moment]), dtype=np.float64)

story_drifts

story_drifts(levels: Sequence[float], *, points: Sequence[tuple[float, float]] | None = None, names: Sequence[str] | None = None, method: Literal['nearest', 'rigid'] = 'nearest', max_offset: float | None = None, ops: ModuleType | None = None, tol: float | None = None) -> StoryTable

One-off drift table: the story maximum over every joint (points=None), else one row per story and point.

Source code in src/apeGmsh/opensees/building.py
def story_drifts(
    levels: Sequence[float],
    *,
    points: Sequence[tuple[float, float]] | None = None,
    names: Sequence[str] | None = None,
    method: Literal["nearest", "rigid"] = "nearest",
    max_offset: float | None = None,
    ops: ModuleType | None = None,
    tol: float | None = None,
) -> StoryTable:
    """One-off drift table: the story maximum over every joint
    (``points=None``), else one row per story and point."""
    d = StoryDrifts(levels, points=points, names=names, method=method,
                    max_offset=max_offset, ops=ops, tol=tol)
    return d.story_max(ops=ops) if points is None else d.table(ops=ops)

piers_by_story

piers_by_story(pier: Pier, levels: Sequence[float], *, names: Sequence[str] | None = None, ops: ModuleType | None = None, tol: float | None = None) -> tuple[Pier, ...]

Split pier (one PG over many stories) into one pier per story.

Each story's pier holds the elements between its two levels and is named "<pier>/<story>"; a story with none is left out. An element that crosses a level raises.

Source code in src/apeGmsh/opensees/building.py
def piers_by_story(
    pier: Pier,
    levels: Sequence[float],
    *,
    names: Sequence[str] | None = None,
    ops: ModuleType | None = None,
    tol: float | None = None,
) -> tuple[Pier, ...]:
    """Split ``pier`` (one PG over many stories) into one pier per story.

    Each story's pier holds the elements between its two levels and is
    named ``"<pier>/<story>"``; a story with none is left out. An element
    that crosses a level raises.
    """
    where = f"piers_by_story({pier.name!r})"
    z = _check_levels(levels, where)
    level_names = _level_names(names, z.size, where)
    module = _resolve_ops(ops)
    dom = _capture(module, tol, where)
    idx = _element_index(dom, pier, where)
    out: list[Pier] = []
    assigned = np.zeros(idx.size, dtype=bool)
    for i in range(1, z.size):
        sel = ((dom.ele_zmin[idx] >= z[i - 1] - dom.tol)
               & (dom.ele_zmax[idx] <= z[i] + dom.tol))
        assigned |= sel
        if sel.any():
            out.append(Pier(
                name=f"{pier.name}/{level_names[i]}",
                elements=tuple(int(dom.ele_tags[k]) for k in idx[sel]),
                bottom=float(z[i - 1]), top=float(z[i]), axis2=pier.axis2))
    if not assigned.all():
        bad = [int(dom.ele_tags[k]) for k in idx[~assigned][:8]]
        raise BridgeError(f"{where}: element(s) {bad} do not lie between two "
                          "consecutive levels (they cross a level, or lie "
                          "outside the levels).")
    return tuple(out)

pier_forces

pier_forces(piers: Sequence[Pier], *, ops: ModuleType | None = None, tol: float | None = None) -> StoryTable

One-off :class:PierForces table at the current domain state.

Source code in src/apeGmsh/opensees/building.py
def pier_forces(
    piers: Sequence[Pier],
    *,
    ops: ModuleType | None = None,
    tol: float | None = None,
) -> StoryTable:
    """One-off :class:`PierForces` table at the current domain state."""
    return PierForces(piers, ops=ops, tol=tol).table(ops=ops)

story_masses

story_masses(levels: Sequence[float], *, names: Sequence[str] | None = None, include_elements: bool = True, ops: ModuleType | None = None, tol: float | None = None) -> StoryTable

Translational mass and center of mass per level (ETABS Mass Summary by Story / Centers of Mass).

Rows are the level names (the base first); columns MassX, MassY, MassZ, XCM, YCM. A node's mass is the nodal mass (nodeMass) plus, with include_elements, what the elements lump to it (see :func:_element_translational_mass: element rho, frame mass per length, shell rho * h, whatever the build defines). A node on a level goes to that level; a node between two levels is split between them linearly in height (a lumped story element's mass goes half to each level); a node at or below the base goes to the base row, one above the top level to the top row. XCM, YCM weigh the horizontal mass (MassX + MassY) / 2. modalProperties counts only free DOFs, so with a fixed base its total mass is the sum of the rows above the base.

Source code in src/apeGmsh/opensees/building.py
def story_masses(
    levels: Sequence[float],
    *,
    names: Sequence[str] | None = None,
    include_elements: bool = True,
    ops: ModuleType | None = None,
    tol: float | None = None,
) -> StoryTable:
    """Translational mass and center of mass per level (ETABS *Mass
    Summary by Story* / *Centers of Mass*).

    Rows are the level names (the base first); columns ``MassX, MassY,
    MassZ, XCM, YCM``. A node's mass is the nodal ``mass`` (``nodeMass``)
    plus, with ``include_elements``, what the elements lump to it (see
    :func:`_element_translational_mass`: element ``rho``, frame mass per
    length, shell ``rho * h``, whatever the build defines). A node on a
    level goes to that level; a node between two levels is split between
    them linearly in height (a lumped story element's mass goes half to
    each level); a node at or below the base goes to the base row, one
    above the top level to the top row. ``XCM, YCM`` weigh the horizontal
    mass ``(MassX + MassY) / 2``. ``modalProperties`` counts only free
    DOFs, so with a fixed base its total mass is the sum of the rows above
    the base.
    """
    where = "story_masses"
    z = _check_levels(levels, where)
    level_names = _level_names(names, z.size, where)
    module = _resolve_ops(ops)
    dom = _capture(module, tol, where)
    m = np.zeros((dom.node_tags.size, 3))
    for r, t in enumerate(dom.node_tags):
        nm = np.asarray(module.nodeMass(int(t)), dtype=np.float64).ravel()
        k = min(3, nm.size)
        m[r, :k] = nm[:k]
    if include_elements:
        m += _element_translational_mass(module, dom)
    nz = dom.coords[:, 2]
    w = np.zeros((dom.node_tags.size, z.size))     # node -> level weights
    for r in range(dom.node_tags.size):
        zr = nz[r]
        if zr <= z[0] + dom.tol:
            w[r, 0] = 1.0
        elif zr >= z[-1] - dom.tol:
            w[r, -1] = 1.0
        else:
            i = int(np.searchsorted(z, zr))
            if abs(zr - z[i - 1]) <= dom.tol:
                w[r, i - 1] = 1.0
            elif abs(zr - z[i]) <= dom.tol:
                w[r, i] = 1.0
            else:
                t = (zr - z[i - 1]) / (z[i] - z[i - 1])
                w[r, i - 1] = 1.0 - t
                w[r, i] = t
    mass = w.T @ m                                    # (L, 3)
    mh = 0.5 * (m[:, 0] + m[:, 1])
    wh = w.T @ mh
    with np.errstate(invalid="ignore", divide="ignore"):
        xcm = np.where(wh > 0.0, (w.T @ (mh * dom.coords[:, 0])) / wh, np.nan)
        ycm = np.where(wh > 0.0, (w.T @ (mh * dom.coords[:, 1])) / wh, np.nan)
    return StoryTable(level_names, STORY_MASS_COLUMNS,
                      np.column_stack([mass, xcm, ycm]))

levels_from_pgs

levels_from_pgs(fem: 'FEMData', pgs: Sequence[str], *, tol: float | None = None) -> tuple[float, ...]

The elevation of each physical group in pgs (one per level).

Every node of a group must lie at one elevation within tol (default 1e-6 of the model's size); the result keeps pgs's order, which must be strictly increasing.

Source code in src/apeGmsh/opensees/building.py
def levels_from_pgs(
    fem: "FEMData",
    pgs: Sequence[str],
    *,
    tol: float | None = None,
) -> tuple[float, ...]:
    """The elevation of each physical group in ``pgs`` (one per level).

    Every node of a group must lie at one elevation within ``tol``
    (default ``1e-6`` of the model's size); the result keeps ``pgs``'s
    order, which must be strictly increasing.
    """
    where = "levels_from_pgs"
    if tol is None:
        all_xyz = np.asarray(fem.nodes.coords, dtype=np.float64)
        span = float(np.linalg.norm(all_xyz.max(axis=0) - all_xyz.min(axis=0)))
        tol = 1e-6 * max(span, 1.0)
    out: list[float] = []
    for name in pgs:
        xyz = np.asarray(fem.nodes.select(pg=name).coords, dtype=np.float64)
        if xyz.size == 0:
            raise ValueError(f"{where}: physical group {name!r} has no nodes.")
        zs = xyz.reshape(-1, 3)[:, 2]
        if float(zs.max() - zs.min()) > tol:
            raise ValueError(
                f"{where}: physical group {name!r} spans z {zs.min():g} to "
                f"{zs.max():g}; a level group must be horizontal (tol {tol:g})."
            )
        out.append(float(zs.mean()))
    _check_levels(out, where)
    return tuple(out)

Numberer

apeGmsh.mesh._numberer.Numberer

Numberer(fem_data: dict)

Renumbers a FEM mesh for solver consumption.

Parameters

fem_data : dict Output of Mesh.get_fem_data(). Must contain: node_tags, node_coords, elem_tags, connectivity, used_tags.

Source code in src/apeGmsh/mesh/_numberer.py
def __init__(self, fem_data: dict) -> None:
    self._node_tags   = np.asarray(fem_data['node_tags'], dtype=int)
    self._node_coords = np.asarray(fem_data['node_coords'], dtype=float)
    self._elem_tags   = np.asarray(fem_data['elem_tags'], dtype=int)
    self._connectivity = np.asarray(fem_data['connectivity'], dtype=int)
    self._used_tags   = fem_data.get('used_tags', set(self._connectivity.flatten()))

renumber

renumber(method: str = 'simple', *, base: int = 1, used_only: bool = True) -> NumberedMesh

Produce a solver-ready mesh with contiguous IDs.

Parameters

method : "simple" or "rcm" "simple" — preserves relative order, just makes IDs contiguous. Fast, no optimisation.

``"rcm"``  — Reverse Cuthill-McKee bandwidth minimisation.
Reorders nodes so that the assembled stiffness matrix has
minimal bandwidth.  Recommended for direct solvers.
int

Starting ID (default 1 = Fortran/OpenSees convention; use 0 for C/Python convention).

bool

If True (default), only include nodes that appear in at least one element (skip orphan nodes). Set False to include all nodes from the mesh.

Returns

NumberedMesh

Source code in src/apeGmsh/mesh/_numberer.py
def renumber(
    self,
    method: str = "simple",
    *,
    base: int = 1,
    used_only: bool = True,
) -> NumberedMesh:
    """
    Produce a solver-ready mesh with contiguous IDs.

    Parameters
    ----------
    method : ``"simple"`` or ``"rcm"``
        ``"simple"``  — preserves relative order, just makes IDs
        contiguous.  Fast, no optimisation.

        ``"rcm"``  — Reverse Cuthill-McKee bandwidth minimisation.
        Reorders nodes so that the assembled stiffness matrix has
        minimal bandwidth.  Recommended for direct solvers.

    base : int
        Starting ID (default 1 = Fortran/OpenSees convention;
        use 0 for C/Python convention).

    used_only : bool
        If True (default), only include nodes that appear in at
        least one element (skip orphan nodes).  Set False to
        include all nodes from the mesh.

    Returns
    -------
    NumberedMesh
    """
    # ── Filter nodes ──────────────────────────────────────────
    if used_only:
        mask = np.isin(self._node_tags, list(self._used_tags))
        n_total   = len(self._node_tags)
        gmsh_tags = self._node_tags[mask]
        coords    = self._node_coords[mask]
        n_orphans = n_total - len(gmsh_tags)
        if n_orphans > 0:
            orphan_tags = self._node_tags[~mask]
            print(
                f"[Numberer] WARNING: {n_orphans} orphan node(s) "
                f"skipped (not connected to any element). "
                f"Tags: {orphan_tags.tolist()[:20]}"
                + (f" ... (+{n_orphans - 20} more)"
                   if n_orphans > 20 else "")
            )
    else:
        gmsh_tags = self._node_tags.copy()
        coords    = self._node_coords.copy()

    n_nodes = len(gmsh_tags)

    # ── Temporary 0-based indexing ────────────────────────────
    # Map Gmsh tags -> 0-based indices for internal work
    gtag_to_tmp: dict[int, int] = {
        int(t): i for i, t in enumerate(gmsh_tags)
    }

    # Rewrite connectivity in 0-based tmp indices (vectorized)
    flat = self._connectivity.ravel()
    conn_tmp = np.array(
        [gtag_to_tmp[int(t)] for t in flat],
        dtype=int,
    ).reshape(self._connectivity.shape)

    # ── Compute permutation ───────────────────────────────────
    if method == "rcm":
        perm = _rcm_ordering(n_nodes, conn_tmp)
    elif method == "simple":
        perm = np.arange(n_nodes, dtype=int)
    else:
        raise ValueError(
            f"Unknown method '{method}'. Use 'simple' or 'rcm'."
        )

    # perm[new_pos] = old_pos
    # inverse: inv_perm[old_pos] = new_pos
    inv_perm = np.empty(n_nodes, dtype=int)
    inv_perm[perm] = np.arange(n_nodes)

    # ── Apply permutation ─────────────────────────────────────
    new_coords     = coords[perm]            # reordered coords

    # Rewrite connectivity with new IDs (vectorized)
    new_conn = inv_perm[conn_tmp] + base

    # Element IDs: simple contiguous
    new_elem_ids = np.arange(base, base + len(self._elem_tags), dtype=int)

    # ── Bandwidth ─────────────────────────────────────────────
    bw = _compute_bandwidth(new_conn)

    # ── Build maps ────────────────────────────────────────────
    g2s_node: dict[int, int] = {}
    s2g_node: dict[int, int] = {}
    for new_pos in range(n_nodes):
        old_pos = perm[new_pos]
        gtag = int(gmsh_tags[old_pos])
        sid  = int(inv_perm[old_pos]) + base
        g2s_node[gtag] = sid
        s2g_node[sid]  = gtag

    g2s_elem: dict[int, int] = {}
    s2g_elem: dict[int, int] = {}
    for i, etag in enumerate(self._elem_tags):
        eid = int(new_elem_ids[i])
        g2s_elem[int(etag)] = eid
        s2g_elem[eid]       = int(etag)

    # ── Rewrite node_ids array in order ───────────────────────
    # node_ids[i] = solver ID of the i-th node (in new ordering)
    solver_node_ids = np.arange(base, base + n_nodes, dtype=int)

    result = NumberedMesh(
        node_ids=solver_node_ids,
        node_coords=new_coords,
        elem_ids=new_elem_ids,
        connectivity=new_conn,
        n_nodes=n_nodes,
        n_elems=len(self._elem_tags),
        bandwidth=bw,
        method=method,
        gmsh_to_solver_node=g2s_node,
        solver_to_gmsh_node=s2g_node,
        gmsh_to_solver_elem=g2s_elem,
        solver_to_gmsh_elem=s2g_elem,
    )

    return result

compare_methods

compare_methods() -> dict[str, int]

Compare bandwidth for all available methods.

Returns

dict[str, int] {"simple": bw1, "rcm": bw2}

Source code in src/apeGmsh/mesh/_numberer.py
def compare_methods(self) -> dict[str, int]:
    """
    Compare bandwidth for all available methods.

    Returns
    -------
    dict[str, int]
        ``{"simple": bw1, "rcm": bw2}``
    """
    results = {}
    for method in ("simple", "rcm"):
        data = self.renumber(method=method)
        results[method] = data.bandwidth
    return results

apeGmsh.mesh._numberer.NumberedMesh dataclass

NumberedMesh(node_ids: ndarray, node_coords: ndarray, elem_ids: ndarray, connectivity: ndarray, n_nodes: int = 0, n_elems: int = 0, bandwidth: int = 0, method: str = 'simple', gmsh_to_solver_node: dict[int, int] = dict(), solver_to_gmsh_node: dict[int, int] = dict(), gmsh_to_solver_elem: dict[int, int] = dict(), solver_to_gmsh_elem: dict[int, int] = dict())

Solver-ready mesh with contiguous IDs and bidirectional maps.

All IDs are 1-based (the standard in structural FEM solvers like OpenSees, Abaqus, SAP2000). Set base=0 in :meth:Numberer.renumber for 0-based if your solver needs it.

Attributes

node_ids : ndarray(N,) New contiguous node IDs. node_coords : ndarray(N, 3) Nodal coordinates, same order as node_ids. elem_ids : ndarray(E,) New contiguous element IDs. connectivity : ndarray(E, npe) Element connectivity in terms of new node IDs. n_nodes : int n_elems : int bandwidth : int Semi-bandwidth of the resulting adjacency. method : str Numbering method used ("simple" or "rcm").

Maps ~~~~ gmsh_to_solver_node : dict[int, int] Gmsh node tag -> solver node ID. solver_to_gmsh_node : dict[int, int] Solver node ID -> Gmsh node tag. gmsh_to_solver_elem : dict[int, int] Gmsh element tag -> solver element ID. solver_to_gmsh_elem : dict[int, int] Solver element ID -> Gmsh element tag.

summary

summary() -> str

One-line summary string.

Source code in src/apeGmsh/mesh/_numberer.py
def summary(self) -> str:
    """One-line summary string."""
    return (
        f"NumberedMesh({self.method}): "
        f"{self.n_nodes} nodes, {self.n_elems} elements, "
        f"bandwidth={self.bandwidth}"
    )