Skip to content

Viz

Visualization of solved results: field lines, the field-display models and the render targets a viewer draws.

femforge.viz

Visualization of solved results: field-line rendering, the field-display models and the composable render targets a viewer draws from a case.vtu.

Modules:

  • colormaps –

    ParaView's colormap presets, registered with matplotlib so every colormap name resolves through pyvista.

  • field_display –

    Field display state for a solved run: which array is colored, how it reduces to a scalar, and the color range that follows; pyvista is imported lazily inside the render half.

  • field_lines –

    3D magnetic field lines from a solved Elmer case.vtu: streamlines seeded through the domain and colored by |B|.

  • glyphs –

    Scene glyphs of what a run's groups received: load arrows, held-face tints, magnet arrows, current markers and value labels, plus the Setup tab's selection, section outline and authored ghost.

  • scene –

    Composable render targets: a Scene draws several Renderables in one plotter refresh, on the plotter thread.

  • symmetry –

    Expansion of a 2D section into a 3D view: an axisymmetric r–z section mirrored or revolved, a Cartesian one extruded through its depth.

Classes:

  • FieldLines –

    A Renderable for the solved B-field streamlines of one case.vtu.

  • FieldLineOptions –

    Typed options for the 3D field-line render.

  • SeedPlacement –

    Where the streamline seed points are placed within the domain bounding box.

  • Colormap –

    Perceptually-uniform matplotlib colormaps for the |B| magnitude scale.

  • OpacityTransfer –

    A pyvista opacity transfer function that maps the |B| scalar to per-element opacity; the _r variants reverse the ramp.

  • InterpolatorType –

    The cell-location strategy the streamline integrator uses (pyvista's interpolator_type).

  • StreamlineActor –

    The plotter actor names draw_streamlines registers, so toggling the overlay off is a single remove_actor.

  • StreamlineActors –

    The precomputed drawables for a field-line view, split from plotting so the expensive part runs off the UI thread.

  • Association –

    Whether a VTU array lives on mesh points or cells (pyvista's preference).

  • BodyPaint –

    Where a body's color comes from.

  • BodyStyle –

    A body's own look: where its color comes from, a solid color when it has one, and its opacity.

  • DisplayMode –

    How a field array is reduced to the value that drives the color.

  • DisplaySpec –

    The complete, serializable state of one field display: which array is colored, how it reduces, and how the colors map.

  • EdgeStyle –

    How the drawn lines draw: the feature-edge outline, the hover and selection outlines and the field lines.

  • Shading –

    How solid surfaces shade under the lights.

  • FieldInfo –

    One displayable VTU array: where it lives, how wide it is, and which display modes it supports.

  • FieldKind –

    What one row of a field array holds, which sets its display modes and whether an expansion turns it.

  • FieldScene –

    One run's solved bodies as a recolorable field display.

  • SceneActor –

    The plotter actor names a FieldScene registers, so a toggle removes exactly one.

  • Renderable –

    Something a workbench run returns for display: it draws itself into plotter (on the plotter thread).

  • Scene –

    An ordered group of Renderables drawn into one plotter refresh: clear once, draw in order (later items on top), repaint once.

  • Expansion –

    How a 2D section is shown.

  • Basis –

    Where the solve frame sits in the authored model.

  • Prism –

    A Cartesian section's depth along the solve Z, with the section plane at its middle.

  • GlyphLabels –

    How glyph values are labelled in the scene.

  • GlyphActor –

    The plotter actor names the glyph layer owns, so a redraw replaces or removes exactly these.

  • EntityKind –

    Whether an entity row names a body group or a boundary group.

  • EntityRef –

    A body or boundary group by kind and name, so a body and a named face that share a name stay apart.

  • Glyph –

    One condition as the scene draws it, in the solve frame the run was meshed in.

  • GlyphView –

    What the Setup tab asks the scene to draw: which glyphs, their labels and size, and the selection, outline and ghost around them.

  • GlyphPlacement –

    How solve-frame geometry lands in the displayed scene: as solved, beside its mirror image, on the planes of a revolution, or on the front face of an extrusion.

  • GlyphHost –

    The scene a glyph layer draws over: its frame, how it is shown and the cells of each group.

  • GlyphDraw –

    One merged glyph actor: its name, its geometry and how it is styled.

  • GlyphLayer –

    A run's glyphs and the scene decorations the Setup tab asks for, drawn over a host scene as named actors.

  • GroupScene –

    A run without fields drawn from its Elmer mesh: every body plain grey, with its glyph layer over them.

Functions:

  • select_flux_density_array –

    Pick the B array from a VTU's array names: the nodal form first (no cell→point projection needed), then the elemental "... e", then any name containing the phrase (case-insensitive).

  • seed_points –

    The (N, 3) streamline seed coordinates for the domain bounds and options (pure Python — unit-testable without a render context).

  • build_streamlines –

    Seed and integrate |B| streamlines through a dataset that already carries B as point data, without touching a plotter.

  • build_streamlines_from_vtu –

    Read a solved case.vtu and integrate its B-field streamlines into a drawable StreamlineActors — no plotter touched, safe off the UI thread.

  • build_swept_streamlines –

    Field lines of a revolved or extruded section: seeded in the shown 3D frame, folded into the section, integrated there and carried back to each seed's angle or depth.

  • prepare_streamline_source –

    Narrow a read grid to the integration region and put B on its points, returning the dataset and the B array name — the read-independent half of build_streamlines_from_vtu.

  • draw_streamlines –

    Draw a precomputed StreamlineActors into plotter without clearing or showing it, so it composes inside a Scene.

  • render_streamlines –

    One-shot: build streamlines through dataset and draw them, in a plotter of its own when plotter is None.

  • render_field_lines –

    Render the magnetic flux-density field lines from a solved case.vtu, headless to a PNG or in an interactive window.

  • field_infos –

    Every displayable array of a VTU as a FieldInfo, sorted by display name; GeometryIds and tensors are left out.

  • line_vectors –

    The vector field the field lines follow: the shown one when it is a vector, else the flux density, else the first vector field; None for a run with none.

  • default_display –

    The display a run opens on: its stack's primary field, on the component its loads share, with field lines and opacity mapping for a flux or current.

  • reduce_field –

    The scalar a display mode draws from one field array.

  • polar_angle –

    Each vector's XY direction as a cyclic coordinate in [0, 1] — atan2(y, x) mapped off [-pi, pi].

  • polar_rgba –

    Per-vector RGBA for DisplayMode.POLAR_XY: hue from the XY angle through a cyclic cmap, brightness and alpha from the sigmoid-scaled XY magnitude.

  • color_range –

    The (lo, hi) color limits spanning every scalar chunk's own range, from the finite values only; an empty selection gives (0.0, 1.0).

  • camera_needs_reset –

    Whether the camera has lost the model, with the box behind it or outside its view cone; a camera inside the box always keeps its view.

  • list_fields –

    Every displayable field of a VTU grid (GeometryIds excluded), sorted by display name, with the units physics decides.

  • split_by_body –

    The grid split into one block per named body, keyed by its entities.json name via the GeometryIds cell array.

  • feature_outline –

    The feature and boundary edges of a multiblock's outer surface — the black wireframe drawn over the field, the body outlines on a 2D slice — or None when the surface has none.

  • model_dim_of –

    2 for a flat (axisymmetric slice) grid with no Z extent, else 3.

  • sample_colormap –

    count evenly-spaced RGBA rows from a named colormap, resolved through pyvista's get_cmap_safe.

  • extrude –

    The closed surface of a Cartesian section extruded along the solve Z through depth, centred on the section plane.

  • mirror –

    Both halves of an axisymmetric section in the solve frame: its triangles and quads beside their reflection across the axis; line and vertex cells are dropped.

  • revolve –

    The surfaces of an axisymmetric section swept about its axis into the authored frame, capped on a partial sweep.

  • swept_lines –

    The quads a section's line cells sweep sweep degrees about the axis, segments steps per turn, uncapped.

  • glyph_label –

    The short scene label of condition, magnitudes only since the shape shows the direction; None for a condition the shape says enough about.

  • glyphs_of –

    The glyphs of every drawable condition a run's groups received, joined to their measured centroids and normals.

  • glyph_actors –

    The merged glyph actors of the shown glyphs, at most one per GLYPH_ACTORS name.

  • plain_spec –

    spec with every one of bodies painted PLAIN_BODY, its own opacity kept.

Attributes:

  • Bounds –

    A pyvista axis-aligned bounding box, as (xmin, xmax, ymin, ymax, zmin, zmax).

  • Point3 –

    One 3D seed coordinate, as (x, y, z).

  • FLUX_DENSITY –

    The MagnetoDynamicsCalcFields name for B in its nodal form; the elemental form the solver writes by default appends " e".

  • FIELD_RENAMES (dict[str, str]) –

    Display-name overrides for solver array names that title-casing alone leaves cryptic.

  • SCALARS_ARRAY –

    The point/cell array every reduction is written to, so one mapper name serves every field and mode.

  • GLYPH_ACTORS (tuple[GlyphActor, ...]) –

    The actors that draw conditions, at most one merged actor each.

Bounds module-attribute

A pyvista axis-aligned bounding box, as (xmin, xmax, ymin, ymax, zmin, zmax).

Point3 module-attribute

Point3 = tuple[float, float, float]

One 3D seed coordinate, as (x, y, z).

FLUX_DENSITY module-attribute

FLUX_DENSITY = 'magnetic flux density'

The MagnetoDynamicsCalcFields name for B in its nodal form; the elemental form the solver writes by default appends " e".

FIELD_RENAMES module-attribute

FIELD_RENAMES: dict[str, str] = {'Jfix': 'Fixed Current Density'}

Display-name overrides for solver array names that title-casing alone leaves cryptic.

SCALARS_ARRAY module-attribute

SCALARS_ARRAY = 'display_scalars'

The point/cell array every reduction is written to, so one mapper name serves every field and mode.

GLYPH_ACTORS module-attribute

The actors that draw conditions, at most one merged actor each.

FieldLines dataclass

FieldLines(vtu_path: str | Path, options: FieldLineOptions | None = None)

A Renderable for the solved B-field streamlines of one case.vtu.

VTU read + streamline integration run in __post_init__ (whichever worker thread constructs it); render only draws precomputed actors, keeping the plotter thread free.

Methods:

  • render –

    Draw the precomputed field lines into plotter.

Attributes:

vtu_path instance-attribute

vtu_path: str | Path

The solved case.vtu whose B field the lines follow.

options class-attribute instance-attribute

options: FieldLineOptions | None = None

The streamline options; None uses the defaults.

render

render(plotter: Plotter) -> None

Draw the precomputed field lines into plotter.

Source code in src/femforge/viz/field_lines.py
def render(self, plotter: pv.Plotter) -> None:  # pragma: no cover - needs pyvista (viz extra) + a VTK render context
    """Draw the precomputed field lines into ``plotter``."""
    assert self._actors is not None  # set in __post_init__

    options = self.options if self.options is not None else FieldLineOptions()
    draw_streamlines(self._actors, options, plotter)

FieldLineOptions pydantic-model

Bases: BaseModel

Typed options for the 3D field-line render.

Config:

  • use_attribute_docstrings: True
  • validate_assignment: True

Fields:

seed_placement pydantic-field

Where to seed the streamlines within the domain bounding box.

seed_grid pydantic-field

seed_grid: bool = True

Seed the streamlines on a grid (True) or at random points (False).

line_count pydantic-field

line_count: int = 18

Seed points per axis: CENTER_PLANE seeds line_count², VOLUME line_count³, GAP_LINE line_count.

max_length pydantic-field

max_length: float = 0.75

[-]: Fraction of the domain diagonal a streamline may integrate along, keeping the picture framed on the magnets.

colormap pydantic-field

colormap: Colormap | str | list[str] = Colormap.TURBO

The |B| colormap: a Colormap member, any matplotlib or colorcet colormap name, or a list of colors interpolated across the scalar range.

invert pydantic-field

invert: bool = False

Reverse the colormap.

log_scale pydantic-field

log_scale: bool = False

Map |B| to colors logarithmically.

clim pydantic-field

clim: tuple[float, float] | None = None

[?]: The |B| color limits, or None for the lines' own range.

opacity_map pydantic-field

opacity_map: tuple[float, float] | None = None

[-]: The opacity at the low and high color limits, linear in the color mapping between them; it replaces an OpacityTransfer.

opacity pydantic-field

opacity: float | OpacityTransfer = 1.0

[-]: Line or tube opacity: a constant in [0, 1], or an OpacityTransfer that maps |B| to opacity like the color.

interpolator pydantic-field

The integrator's cell-location strategy. CELL (default) fixes the straight "spike" streamlines a point locator produces near the air↔magnet interface.

seed_fraction pydantic-field

seed_fraction: float = 0.6

[-]: Fraction of the bounding box, centered, that the seed grid spans, keeping seeds out of the outer air shell where B ≈ 0.

region_array pydantic-field

region_array: str | None = None

Name of a cell-data region-id array (e.g. Elmer's "GeometryIds") identifying each cell's body. Used with region_id and clip_to_region.

region_id pydantic-field

region_id: int | None = None

The single region id to confine integration to when clip_to_region is set (e.g. the air body id).

clip_to_region pydantic-field

clip_to_region: bool = False

Confine streamline integration to region_id (needs region_array and region_id), which keeps elemental B from averaging across the air↔magnet interface.

tube_radius pydantic-field

tube_radius: float | None = None

r_tube [m]: Streamline tube radius; None draws the streamlines as plain poly-lines.

line_width pydantic-field

line_width: float = 1.0

[px]: The width of a plain poly-line in window pixels.

initial_step_length pydantic-field

initial_step_length: float = 0.5

[-]: The integrator's initial step, in cell lengths; smaller values follow tight curves.

min_step_length pydantic-field

min_step_length: float = 0.01

[-]: The integrator's smallest step, in cell lengths.

max_step_length pydantic-field

max_step_length: float = 1.0

[-]: The integrator's largest step, in cell lengths.

show_outline pydantic-field

show_outline: bool = True

Draw the domain bounding-box outline for spatial context.

vectors pydantic-field

vectors: str | None = None

The 3-component array the lines follow; None picks the magnetic flux density.

SeedPlacement

Bases: StrEnum

Where the streamline seed points are placed within the domain bounding box.

Attributes:

  • CENTER_PLANE –

    A line_count × line_count grid on the mid-Z plane (the field-line cross-section), the default.

  • VOLUME –

    A line_count³ grid filling the box: denser, fuller 3D coverage.

  • GAP_LINE –

    A single line of line_count points along X through the center (e.g. across the Halbach gap).

CENTER_PLANE class-attribute instance-attribute

CENTER_PLANE = 'center_plane'

A line_count × line_count grid on the mid-Z plane (the field-line cross-section), the default.

VOLUME class-attribute instance-attribute

VOLUME = 'volume'

A line_count³ grid filling the box: denser, fuller 3D coverage.

GAP_LINE class-attribute instance-attribute

GAP_LINE = 'gap_line'

A single line of line_count points along X through the center (e.g. across the Halbach gap).

Colormap

Bases: StrEnum

Perceptually-uniform matplotlib colormaps for the |B| magnitude scale.

Attributes:

  • VIRIDIS –

    Dark blue through green to yellow.

  • PLASMA –

    Dark blue through magenta to yellow.

  • MAGMA –

    Black through red to pale yellow.

  • TURBO –

    A smooth rainbow from dark blue to dark red.

  • COOLWARM –

    A diverging map from blue through grey to red.

VIRIDIS class-attribute instance-attribute

VIRIDIS = 'viridis'

Dark blue through green to yellow.

PLASMA class-attribute instance-attribute

PLASMA = 'plasma'

Dark blue through magenta to yellow.

MAGMA class-attribute instance-attribute

MAGMA = 'magma'

Black through red to pale yellow.

TURBO class-attribute instance-attribute

TURBO = 'turbo'

A smooth rainbow from dark blue to dark red.

COOLWARM class-attribute instance-attribute

COOLWARM = 'coolwarm'

A diverging map from blue through grey to red.

OpacityTransfer

Bases: StrEnum

A pyvista opacity transfer function that maps the |B| scalar to per-element opacity; the _r variants reverse the ramp.

Attributes:

  • LINEAR –

    Opacity rises linearly with |B|.

  • LINEAR_R –

    Opacity falls linearly with |B|.

  • GEOM –

    Opacity rises geometrically with |B|.

  • GEOM_R –

    Opacity falls geometrically with |B|.

  • SIGMOID –

    Opacity follows a sigmoid in |B|, so weak-field lines fade out.

  • SIGMOID_R –

    Opacity follows a reversed sigmoid in |B|, so strong-field lines fade out.

LINEAR class-attribute instance-attribute

LINEAR = 'linear'

Opacity rises linearly with |B|.

LINEAR_R class-attribute instance-attribute

LINEAR_R = 'linear_r'

Opacity falls linearly with |B|.

GEOM class-attribute instance-attribute

GEOM = 'geom'

Opacity rises geometrically with |B|.

GEOM_R class-attribute instance-attribute

GEOM_R = 'geom_r'

Opacity falls geometrically with |B|.

SIGMOID class-attribute instance-attribute

SIGMOID = 'sigmoid'

Opacity follows a sigmoid in |B|, so weak-field lines fade out.

SIGMOID_R class-attribute instance-attribute

SIGMOID_R = 'sigmoid_r'

Opacity follows a reversed sigmoid in |B|, so strong-field lines fade out.

InterpolatorType

Bases: StrEnum

The cell-location strategy the streamline integrator uses (pyvista's interpolator_type).

Both integrate the same point vector field; this only changes how each step finds its containing cell.

Attributes:

  • CELL –

    Locate cells with a cell locator, the right default for this geometry.

  • POINT –

    Locate cells via the nearest mesh point (pyvista's default). Faster, but near interfaces/thin features it can grab the wrong

CELL class-attribute instance-attribute

CELL = 'cell'

Locate cells with a cell locator, the right default for this geometry.

It stays robust near the air↔magnet interface and thin air gaps, where a point locator mislocates a step into the wrong (magnet) cell and sends the streamline off as a straight "spike".

POINT class-attribute instance-attribute

POINT = 'point'

Locate cells via the nearest mesh point (pyvista's default). Faster, but near interfaces/thin features it can grab the wrong cell's vector and produce the spike streamlines.

StreamlineActor

Bases: StrEnum

The plotter actor names draw_streamlines registers, so toggling the overlay off is a single remove_actor.

Attributes:

  • LINES –

    The integrated streamlines.

  • OUTLINE –

    The domain's bounding-box outline.

LINES class-attribute instance-attribute

LINES = 'streamlines'

The integrated streamlines.

OUTLINE class-attribute instance-attribute

OUTLINE = 'streamlines-outline'

The domain's bounding-box outline.

StreamlineActors dataclass

StreamlineActors(streamlines: PolyData, b_name: str, outline: PolyData | None, magnitudes: list[NDArray[float64]])

The precomputed drawables for a field-line view, split from plotting so the expensive part runs off the UI thread.

Built by build_streamlines (worker-thread safe) and drawn by draw_streamlines (plotter thread only).

Attributes:

  • streamlines (PolyData) –

    The integrated streamlines, within the integration region.

  • b_name (str) –

    The name of the B array the lines carry for coloring.

  • outline (PolyData | None) –

    The domain's bounding-box outline; None when show_outline is off.

  • magnitudes (list[NDArray[float64]]) –

    The integrated field's magnitudes over the integration region, one chunk per body, which set the lines' color range.

streamlines instance-attribute

streamlines: PolyData

The integrated streamlines, within the integration region.

b_name instance-attribute

b_name: str

The name of the B array the lines carry for coloring.

outline instance-attribute

outline: PolyData | None

The domain's bounding-box outline; None when show_outline is off.

magnitudes instance-attribute

magnitudes: list[NDArray[float64]]

The integrated field's magnitudes over the integration region, one chunk per body, which set the lines' color range.

Association

Bases: StrEnum

Whether a VTU array lives on mesh points or cells (pyvista's preference).

Attributes:

  • POINT –

    One value per mesh point.

  • CELL –

    One value per mesh cell.

POINT class-attribute instance-attribute

POINT = 'point'

One value per mesh point.

CELL class-attribute instance-attribute

CELL = 'cell'

One value per mesh cell.

BodyPaint

Bases: StrEnum

Where a body's color comes from.

Attributes:

  • FIELD –

    The field colormap, by the displayed value.

  • COLORMAP –

    One color of the body colormap, spread evenly over every body that takes it.

  • SOLID –

    The body's own color.

FIELD class-attribute instance-attribute

FIELD = 'field'

The field colormap, by the displayed value.

COLORMAP class-attribute instance-attribute

COLORMAP = 'colormap'

One color of the body colormap, spread evenly over every body that takes it.

SOLID class-attribute instance-attribute

SOLID = 'solid'

The body's own color.

BodyStyle pydantic-model

Bases: BaseModel

A body's own look: where its color comes from, a solid color when it has one, and its opacity.

Config:

  • use_attribute_docstrings: True
  • frozen: True

Fields:

Validators:

  • _solid_has_color

body pydantic-field

body: str

The body's entities.json name.

paint pydantic-field

Where the body's color comes from.

color pydantic-field

color: str | None = None

Any color pyvista resolves (a name or a hex triplet); a SOLID body needs one, the others ignore it.

opacity pydantic-field

opacity: float = 1.0

[-]: The body's own opacity, multiplied by the display's.

DisplayMode

Bases: StrEnum

How a field array is reduced to the value that drives the color.

Attributes:

  • VALUE –

    The value itself.

  • ABSVALUE –

    The absolute value.

  • X –

    The x component.

  • Y –

    The y component.

  • Z –

    The z component.

  • MAGNITUDE –

    The vector magnitude.

  • POLAR_XY –

    The in-plane direction as hue, brightened by the in-plane magnitude.

  • MAX_PRINCIPAL –

    The largest of the three principal values.

  • MID_PRINCIPAL –

    The middle one of the three principal values.

  • MIN_PRINCIPAL –

    The smallest of the three principal values.

  • label (str) –

    The mode's name as it reads in a picker.

VALUE class-attribute instance-attribute

VALUE = 'value'

The value itself.

ABSVALUE class-attribute instance-attribute

ABSVALUE = 'absolute_value'

The absolute value.

X class-attribute instance-attribute

X = 'x'

The x component.

Y class-attribute instance-attribute

Y = 'y'

The y component.

Z class-attribute instance-attribute

Z = 'z'

The z component.

MAGNITUDE class-attribute instance-attribute

MAGNITUDE = 'magnitude'

The vector magnitude.

POLAR_XY class-attribute instance-attribute

POLAR_XY = 'polar_xy'

The in-plane direction as hue, brightened by the in-plane magnitude.

MAX_PRINCIPAL class-attribute instance-attribute

MAX_PRINCIPAL = 'max_principal'

The largest of the three principal values.

MID_PRINCIPAL class-attribute instance-attribute

MID_PRINCIPAL = 'mid_principal'

The middle one of the three principal values.

MIN_PRINCIPAL class-attribute instance-attribute

MIN_PRINCIPAL = 'min_principal'

The smallest of the three principal values.

label property

label: str

The mode's name as it reads in a picker.

DisplaySpec pydantic-model

Bases: BaseModel

The complete, serializable state of one field display: which array is colored, how it reduces, and how the colors map.

Config:

  • use_attribute_docstrings: True
  • validate_assignment: True

Fields:

field pydantic-field

field: str = ''

Name of the VTU array to color by; empty opens the viewer on each run's default_display, and fitted takes the first array.

mode pydantic-field

How the array is reduced to the displayed value.

colormap pydantic-field

colormap: str = 'turbo'

Colormap name, resolved through pyvista's get_cmap_safe (matplotlib and colorcet names both work).

log_scale pydantic-field

log_scale: bool = False

Map the color range logarithmically; only the strictly positive values take part.

invert pydantic-field

invert: bool = False

Reverse the colormap.

clim pydantic-field

clim: tuple[float, float] | None = None

[?]: Pinned color limits in the displayed value's unit, or None to recompute them from the data on every apply.

robust pydantic-field

robust: bool = True

Clamp the automatic limits to the 2-98 percentiles so a few outlier cells cannot flatten the picture.

legend pydantic-field

legend: Legend = Legend.HIDDEN

Whether and where the color bar is drawn; field lines mapped like the field share it.

expansion pydantic-field

How a run solved on a section is shown, one its frame lacks taken as the frame's 3D form (Revolve becomes Extrude for a Cartesian section); a run solved in 3D is shown as is.

sweep pydantic-field

sweep: float = FULL_SWEEP

[deg]: The turn a revolved section sweeps; less than a full one leaves a cutaway.

warp pydantic-field

warp: str | None

The vector array the bodies are displaced by, None to draw them undeformed.

warp_scale pydantic-field

warp_scale: float | None = None

[-]: The displacement exaggeration; None moves the largest displacement WARP_SHARE of the section diagonal.

hidden_bodies pydantic-field

hidden_bodies: tuple[str, ...] = ()

Body names to hide, by their entities.json name.

outline pydantic-field

outline: bool = False

Draw the black feature-edge wireframe over the visible bodies.

edges pydantic-field

edges: EdgeStyle

How the wireframe and the field lines draw.

shading pydantic-field

shading: Shading

How the bodies shade.

scale pydantic-field

scale: float = 1.0

[-]: Window pixels per CSS pixel, which the wireframe's width scales by.

opacity pydantic-field

opacity: float = 1.0

[-]: Multiplies every body's own opacity.

opacity_map pydantic-field

opacity_map: tuple[float, float] | None = OPACITY_MAP

[-]: The opacity at the low and high color limits, linear in the color mapping between them; None draws opacity throughout.

body_styles pydantic-field

body_styles: tuple[BodyStyle, ...] = ()

Bodies with a color source or an opacity of their own; the rest take the field colormap at full opacity.

body_colormap pydantic-field

body_colormap: str = 'batlow'

The colormap the COLORMAP bodies share, in body_styles order.

streamlines pydantic-field

streamlines: FieldLineOptions | None

Options for the field-line overlay, or None to draw none.

solid

solid() -> dict[str, str]

The color of every body not on the field colormap, by body: its own, or its share of the body colormap.

Source code in src/femforge/viz/field_display.py
def solid(self) -> dict[str, str]:
    """The color of every body not on the field colormap, by body: its own, or its share of the body colormap."""
    spread: list[str] = [style.body for style in self.body_styles if style.paint is BodyPaint.COLORMAP]
    shares: dict[str, str] = dict(zip(spread, spread_colors(self.body_colormap, len(spread)), strict=True)) if spread else {}
    colors: dict[str, str] = {}
    for style in self.body_styles:
        if style.paint is BodyPaint.COLORMAP:
            colors[style.body] = shares[style.body]
        elif style.paint is BodyPaint.SOLID and style.color is not None:
            colors[style.body] = style.color

    return colors

body_opacity

body_opacity(body: str) -> float

A body's drawn opacity: its own times the overall one.

Source code in src/femforge/viz/field_display.py
def body_opacity(self, body: str) -> float:
    """A body's drawn opacity: its own times the overall one."""
    own: float = next((style.opacity for style in self.body_styles if style.body == body), 1.0)
    return own * self.opacity

unmatched

unmatched(bodies: Iterable[str]) -> list[str]

The hidden_bodies and body_styles names missing from bodies, in spec order.

Source code in src/femforge/viz/field_display.py
def unmatched(self, bodies: Iterable[str]) -> list[str]:
    """The ``hidden_bodies`` and ``body_styles`` names missing from ``bodies``, in spec order."""
    present: set[str] = set(bodies)
    named: list[str] = [*self.hidden_bodies, *(style.body for style in self.body_styles)]
    return [name for name in dict.fromkeys(named) if name not in present]

fitted

fitted(fields: Sequence[FieldInfo]) -> DisplaySpec

This spec snapped to what a run offers: an unset field takes the first one, a disallowed mode the field's first allowed one, and a warp without a vector field to follow is dropped.

An unknown field name raises KeyError naming the available arrays.

Source code in src/femforge/viz/field_display.py
def fitted(self, fields: Sequence[FieldInfo]) -> DisplaySpec:
    """
    This spec snapped to what a run offers: an unset field takes the first one, a disallowed mode the field's first allowed one, and a warp without a vector field to follow is dropped.

    An unknown field name raises [`KeyError`][] naming the available arrays.
    """
    if not fields:
        raise KeyError("no displayable fields")

    by_name: dict[str, FieldInfo] = {info.name: info for info in fields}
    chosen: FieldInfo = fields[0] if not self.field else by_name[select_array(by_name, self.field)]

    def resolved_warp() -> str | None:
        vectors: list[str] = [info.name for info in fields if info.kind is FieldKind.VECTOR]
        if self.warp is None:
            return None

        try:
            return select_array(vectors, self.warp)
        except KeyError:
            return None

    allowed: tuple[DisplayMode, ...] = chosen.modes
    mode: DisplayMode = self.mode if self.mode in allowed else allowed[0]
    warp: str | None = resolved_warp()
    if chosen.name == self.field and mode is self.mode and warp == self.warp:
        return self

    return self.model_copy(update={"field": chosen.name, "mode": mode, "warp": warp})

EdgeStyle pydantic-model

Bases: BaseModel

How the drawn lines draw: the feature-edge outline, the hover and selection outlines and the field lines.

Config:

  • frozen: True
  • use_attribute_docstrings: True

Fields:

width pydantic-field

width: float = 2.0

[px]: The width of the feature-edge outline in CSS pixels.

feature_angle pydantic-field

feature_angle: float = FEATURE_ANGLE

[deg]: The dihedral angle above which a surface edge counts as a feature edge.

highlight_width pydantic-field

highlight_width: float = 2.0

[px]: The width of a hover outline in CSS pixels; a selection draws wider in proportion.

line_width pydantic-field

line_width: float = 1.0

[px]: The width of a field line drawn as a poly-line, in CSS pixels.

Shading pydantic-model

Bases: BaseModel

How solid surfaces shade under the lights.

Config:

  • frozen: True
  • use_attribute_docstrings: True

Fields:

smooth pydantic-field

smooth: bool = True

Interpolate the normals across each surface so curved faces shade evenly; False shades every facet flat.

split_angle pydantic-field

split_angle: float = FEATURE_ANGLE

[deg]: The dihedral angle above which a smooth surface keeps its edge sharp.

ambient pydantic-field

ambient: float = 0.0

[-]: The share of a surface's color shown without light, which lifts the faces turned away from the lights.

specular pydantic-field

specular: float = PLAIN_SPECULAR

[-]: The highlight strength of a body in a plain color; a body on a colormap takes none, so no highlight reads as a value.

FieldInfo dataclass

FieldInfo(name: str, association: Association, components: int, dtype: str, unit: str | None = None, physics: Physics | None = None)

One displayable VTU array: where it lives, how wide it is, and which display modes it supports.

Attributes:

  • name (str) –

    The array's name in the VTU.

  • association (Association) –

    Whether the array lives on points or cells.

  • components (int) –

    The number of components per value: 1 for a scalar, 3 for a vector.

  • dtype (str) –

    The array's numpy dtype name.

  • unit (str | None) –

    The unit the values are in, None when unknown.

  • physics (Physics | None) –

    The physics the run solved, which decides what its potential is; None when unknown.

  • display_name (str) –

    The array's name as it reads in a picker: the variable's display name, Magnetic Potential for a 2D magnetostatic one, with the FIELD_RENAMES overrides applied.

  • title (str) –

    The display name with the unit in brackets, as a color bar is titled.

  • kind (FieldKind) –

    What one row of the array holds.

  • modes (tuple[DisplayMode, ...]) –

    The display modes this array supports, the default first; a tensor supports none.

name instance-attribute

name: str

The array's name in the VTU.

association instance-attribute

association: Association

Whether the array lives on points or cells.

components instance-attribute

components: int

The number of components per value: 1 for a scalar, 3 for a vector.

dtype instance-attribute

dtype: str

The array's numpy dtype name.

unit class-attribute instance-attribute

unit: str | None = None

The unit the values are in, None when unknown.

physics class-attribute instance-attribute

physics: Physics | None = None

The physics the run solved, which decides what its potential is; None when unknown.

display_name property

display_name: str

The array's name as it reads in a picker: the variable's display name, Magnetic Potential for a 2D magnetostatic one, with the FIELD_RENAMES overrides applied.

title property

title: str

The display name with the unit in brackets, as a color bar is titled.

kind property

kind: FieldKind

What one row of the array holds.

modes property

modes: tuple[DisplayMode, ...]

The display modes this array supports, the default first; a tensor supports none.

FieldKind

Bases: StrEnum

What one row of a field array holds, which sets its display modes and whether an expansion turns it.

Attributes:

  • SCALAR –

    One value.

  • VECTOR –

    A 3-component vector, turned with a mirrored or revolved copy.

  • PRINCIPAL –

    Three principal values, which no rotation changes.

  • TENSOR –

    A Voigt tensor, whole or as one of the stress_xx columns Elmer splits it into, or any other width; not displayed.

SCALAR class-attribute instance-attribute

SCALAR = 'scalar'

One value.

VECTOR class-attribute instance-attribute

VECTOR = 'vector'

A 3-component vector, turned with a mirrored or revolved copy.

PRINCIPAL class-attribute instance-attribute

PRINCIPAL = 'principal'

Three principal values, which no rotation changes.

TENSOR class-attribute instance-attribute

TENSOR = 'tensor'

A Voigt tensor, whole or as one of the stress_xx columns Elmer splits it into, or any other width; not displayed.

FieldScene

FieldScene(*, grid: UnstructuredGrid, blocks: MultiBlock, fields: Sequence[FieldInfo], model_dim: int, run_id: str, bodies: Bodies | None = None, frame: Frame | None = None, boundaries: Boundaries | None = None)

One run's solved bodies as a recolorable field display.

It is a Renderable whose DisplaySpec picks the field, its reduction, its colors and how a section is expanded.

Parameters:

  • grid (UnstructuredGrid) –

    The solved VTU grid.

  • blocks (MultiBlock) –

    The grid split into one block per named body.

  • fields (Sequence[FieldInfo]) –

    The displayable arrays.

  • model_dim (int) –

    2 for an axisymmetric slice, else 3.

  • run_id (str) –

    The run bundle's name.

  • bodies (Bodies | None, default: None ) –

    The named bodies from entities.json; None names none.

  • frame (Frame | None, default: None ) –

    The solve frame; None takes the first shipped frame that solves on the grid's dimension.

  • boundaries (Boundaries | None, default: None ) –

    The named boundaries from entities.json; None names none.

Methods:

  • from_run –

    Open a run bundle's VTU as a field scene, its bodies split and named from entities.json.

  • expansion_of –

    The expansion and sweep a spec asks of this run, an expansion its frame lacks taken as the frame's 3D form: a run solved in 3D is shown as is, and only a revolution has a sweep.

  • dim_for –

    The dimension the run shows in under a spec.

  • auto_warp_scale –

    The scale that moves the largest name displacement WARP_SHARE of the section's bounds diagonal, 0.0 when nothing moves.

  • warp_of –

    The vector array and the scale a spec displaces the bodies by: its own scale, else the automatic one; None for no warp or a zero scale.

  • shades_like –

    Whether the drawn surfaces carry the normals shading asks for; its light terms restyle them in place.

  • reshaped –

    Whether a spec asks for other shown blocks than the scene holds: another expansion, sweep or warp.

  • expand –

    Rebuilds the shown blocks and grid for the spec's expansion and warp when either changed, dropping the field lines integrated for the old ones; True when it did.

  • field_info –

    The FieldInfo for an array name, resolved the same way a field query resolves one.

  • apply –

    Write the spec's reduction into every block's display_scalars array and return the color limits it produced.

  • render –

    Draw the whole display into plotter: the composite body actor, then everything update owns; solid bodies an earlier scene left go first.

  • update –

    Recolor an already-rendered scene in place, the cheap path a panel calls on every knob change; a changed expansion or warp draws the scene anew.

  • group_cells –

    The solved cells of a body, or of a boundary a condition marked in the VTU; None for any other group.

  • shown_blocks –

    The blocks of every body not in hidden, under their names.

  • lines_share –

    Whether lines drawn with styled map like the field: the same colormap, inversion, log scale, opacity map and limits.

  • lines_array –

    The array the field lines follow: the one asked for when the grid has it, else the one line_vectors picks for the shown array.

  • integrated –

    The cached field lines when options only restyle them, None when they need integrating.

  • integrate_streamlines –

    Seed and integrate the field lines through the shown grid, carried into a revolved or extruded display from its section — the compute half, safe off the UI thread.

  • region_bounds –

    The shown bounds the field lines seed: the integration region's body when the options confine them to one, else every body.

  • swept_seeds –

    The seeds of the revolved display as a solid run would place them in bounds, less the ones a partial sweep cuts away; None leaves a full sweep to seed itself.

  • region_magnitudes –

    The magnitudes of array name per body of a region (every body for None) as solved, the chunks a field-line range spans.

  • show_streamlines –

    Draw integrated field lines into plotter in the display's mapping, record their options as the drawn ones and keep the lines for a restyle.

  • lines_follow –

    Whether field lines following vectors take the display's range: it shows that field's magnitude, so one scale reads for both.

  • lines_title –

    The field lines' scalar bar title: the integrated field's name and unit.

  • line_style –

    The field lines at the display's width, in its colormap, inversion, log scale and opacity map; a polar display leaves their colors as asked.

Attributes:

  • section_grid (UnstructuredGrid) –

    The grid as solved.

  • section_blocks (MultiBlock) –

    The bodies as solved, whose values set every range.

  • grid (UnstructuredGrid) –

    The grid as shown, which the field lines run through: the section, its mirror, or the section again under a revolved or extruded display, displaced under a warp.

  • blocks (MultiBlock) –

    The bodies as shown.

  • basis (Basis | None) –

    Where the section sits in the authored model, None for a run solved whole.

  • depth (float) –

    t [m]: The depth a Cartesian section extrudes through; 0 for any other frame.

  • expanded (tuple[Expansion, float]) –

    The expansion and sweep the shown blocks were built for.

  • warped (tuple[str, float] | None) –

    The vector array and the scale the shown blocks are displaced by, None while they are drawn as solved.

  • glyphs (GlyphLayer | None) –

    The run's glyph layer, drawn after everything else on every redraw; None draws none.

  • glyph_view (GlyphView | None) –

    What the glyph layer draws; None removes its actors.

  • shading (Shading) –

    How the drawn surfaces shade, whose normals a change of smoothness or split angle rebuilds.

  • drawn_lines (FieldLineOptions | None) –

    The styled options of the lines the plotter holds.

  • expandable (bool) –

    Whether the run was solved on a section that can be shown in another form.

  • display_dim (int) –

    2 while the run is shown flat, 3 when it is solid, revolved or extruded.

  • bounds (Bounds) –

    The bounds of the shown bodies.

Source code in src/femforge/viz/field_display.py
def __init__(
    self,
    *,
    grid: pv.UnstructuredGrid,
    blocks: pv.MultiBlock,
    fields: Sequence[FieldInfo],
    model_dim: int,
    run_id: str,
    bodies: Bodies | None = None,
    frame: Frame | None = None,
    boundaries: Boundaries | None = None,
) -> None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """Hold one run's solved grid, split into bodies, under a default display.

    Args:
        grid: The solved VTU grid.
        blocks: The grid split into one block per named body.
        fields: The displayable arrays.
        model_dim: 2 for an axisymmetric slice, else 3.
        run_id: The run bundle's name.
        bodies: The named bodies from ``entities.json``; None names none.
        frame: The solve frame; None takes the first shipped frame that solves on the grid's dimension.
        boundaries: The named boundaries from ``entities.json``; None names none.
    """
    from femforge.run.entities import Bodies, Boundaries

    register_paraview()
    self.frame: Frame = frame if frame is not None else default_frame(model_dim)
    self.model_dim: int = self.frame.model_dim
    if self.model_dim == 2:
        flatten(grid, blocks)

    self.section_grid: pv.UnstructuredGrid = grid
    """The grid as solved."""
    self.section_blocks: pv.MultiBlock = blocks
    """The bodies as solved, whose values set every range."""
    self.grid: pv.UnstructuredGrid = grid
    """The grid as shown, which the field lines run through: the section, its mirror, or the section again under a revolved or extruded display, displaced under a warp."""
    self.blocks: pv.MultiBlock = blocks
    """The bodies as shown."""
    self.fields: list[FieldInfo] = list(fields)
    plane: SolvePlane | None = self.frame.plane
    self.basis: Basis | None = scaled_basis(plane) if plane is not None and self.frame.revolves else None
    """Where the section sits in the authored model, None for a run solved whole."""
    self.depth: float = prism_depth(self.frame)
    """`t` `[m]`: The depth a Cartesian section extrudes through; 0 for any other frame."""
    self.expanded: tuple[Expansion, float] = (Expansion.SECTION, FULL_SWEEP)
    """The expansion and sweep the shown blocks were built for."""
    self.warped: tuple[str, float] | None = None
    """The vector array and the scale the shown blocks are displaced by, None while they are drawn as solved."""
    self.run_id: str = run_id
    self.bodies: Bodies = bodies if bodies is not None else Bodies([])
    self.boundaries: Boundaries = boundaries if boundaries is not None else Boundaries([])
    self.glyphs: GlyphLayer | None = None
    """The run's glyph layer, drawn after everything else on every redraw; None draws none."""
    self.glyph_view: GlyphView | None = None
    """What the glyph layer draws; None removes its actors."""
    self.spec: DisplaySpec = DisplaySpec().fitted(self.fields) if self.fields else DisplaySpec()
    self.clim: tuple[float, float] = (0.0, 1.0)
    self.data_range: tuple[float, float] = (0.0, 1.0)
    self._actor: pv.Actor | None = None
    self._surfaces: pv.MultiBlock | None = None
    self.shading: Shading = Shading()
    """How the drawn surfaces shade, whose normals a change of smoothness or split angle rebuilds."""
    self._styled_shading: Shading = Shading()
    """The surface copy of the shown blocks the body actor draws, which every apply recolors with the blocks."""
    self._styled: dict[str, tuple[str, float]] = {}
    """The ``(color, opacity)`` of every solid body actor the plotter holds."""
    self._lines: tuple[StreamlineActors, FieldLineOptions] | None = None
    """The last integrated field lines and the options they were integrated with, restyled without integrating again."""
    self.drawn_lines: FieldLineOptions | None = None
    """The styled options of the lines the plotter holds."""
    self._lines_bar: str | None = None
    """The title of the field lines' scalar bar the plotter holds."""
    self._field_bar: str | None = None
    """The title of the field's scalar bar the plotter holds."""

section_grid instance-attribute

section_grid: UnstructuredGrid = grid

The grid as solved.

section_blocks instance-attribute

section_blocks: MultiBlock = blocks

The bodies as solved, whose values set every range.

grid instance-attribute

grid: UnstructuredGrid = grid

The grid as shown, which the field lines run through: the section, its mirror, or the section again under a revolved or extruded display, displaced under a warp.

blocks instance-attribute

blocks: MultiBlock = blocks

The bodies as shown.

basis instance-attribute

basis: Basis | None = scaled_basis(plane) if plane is not None and self.frame.revolves else None

Where the section sits in the authored model, None for a run solved whole.

depth instance-attribute

depth: float = prism_depth(self.frame)

t [m]: The depth a Cartesian section extrudes through; 0 for any other frame.

expanded instance-attribute

expanded: tuple[Expansion, float] = (Expansion.SECTION, FULL_SWEEP)

The expansion and sweep the shown blocks were built for.

warped instance-attribute

warped: tuple[str, float] | None = None

The vector array and the scale the shown blocks are displaced by, None while they are drawn as solved.

glyphs instance-attribute

glyphs: GlyphLayer | None = None

The run's glyph layer, drawn after everything else on every redraw; None draws none.

glyph_view instance-attribute

glyph_view: GlyphView | None = None

What the glyph layer draws; None removes its actors.

shading instance-attribute

shading: Shading = Shading()

How the drawn surfaces shade, whose normals a change of smoothness or split angle rebuilds.

drawn_lines instance-attribute

drawn_lines: FieldLineOptions | None = None

The styled options of the lines the plotter holds.

expandable property

expandable: bool

Whether the run was solved on a section that can be shown in another form.

display_dim property

display_dim: int

2 while the run is shown flat, 3 when it is solid, revolved or extruded.

bounds property

bounds: Bounds

The bounds of the shown bodies.

from_run classmethod

from_run(run: Run) -> FieldScene

Open a run bundle's VTU as a field scene, its bodies split and named from entities.json.

Source code in src/femforge/viz/field_display.py
@classmethod
def from_run(cls, run: Run) -> FieldScene:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """Open a run bundle's VTU as a field scene, its bodies split and named from ``entities.json``."""
    import pyvista as pv

    if run.vtu_path is None:
        raise FileNotFoundError(f"{run.path}: no VTU output to display")

    bodies: Bodies = run.bodies
    if not len(bodies):
        raise FileNotFoundError(f"{run.path}: no named bodies ({BundleFile.ENTITIES} missing); re-solve the run so the bundle carries its entities")

    from femforge.run.mechanical import add_derived_fields

    grid: pv.UnstructuredGrid = cast("pv.UnstructuredGrid", pv.read(str(run.vtu_path)))
    add_derived_fields(grid)
    blocks: pv.MultiBlock = split_by_body(grid, bodies)
    manifest: RunManifest | None = run_manifest(run)
    fields: list[FieldInfo] = list_fields(grid, manifest.physics if manifest is not None else None)
    frame: Frame | None = manifest.config.frame if manifest is not None else None

    log.bind(run_id=run.path.name, bodies=len(blocks), fields=len(fields), frame=frame.label if frame is not None else None).info("Field scene loaded.")
    return cls(grid=grid, blocks=blocks, fields=fields, model_dim=model_dim_of(grid), run_id=run.path.name, bodies=bodies, frame=frame, boundaries=run.boundaries)

expansion_of

expansion_of(spec: DisplaySpec) -> tuple[Expansion, float]

The expansion and sweep a spec asks of this run, an expansion its frame lacks taken as the frame's 3D form: a run solved in 3D is shown as is, and only a revolution has a sweep.

Source code in src/femforge/viz/field_display.py
def expansion_of(self, spec: DisplaySpec) -> tuple[Expansion, float]:
    """The expansion and sweep a spec asks of this run, an expansion its frame lacks taken as the frame's 3D form: a run solved in 3D is shown as is, and only a revolution has a sweep."""
    expansion: Expansion = shown_as(self.frame, spec.expansion)

    return (expansion, spec.sweep if expansion is Expansion.REVOLVE else FULL_SWEEP)

dim_for

dim_for(spec: DisplaySpec) -> int

The dimension the run shows in under a spec.

Source code in src/femforge/viz/field_display.py
def dim_for(self, spec: DisplaySpec) -> int:
    """The dimension the run shows in under a spec."""
    return self.expansion_of(spec)[0].dim if self.expandable else self.model_dim

auto_warp_scale

auto_warp_scale(name: str) -> float

The scale that moves the largest name displacement WARP_SHARE of the section's bounds diagonal, 0.0 when nothing moves.

Source code in src/femforge/viz/field_display.py
def auto_warp_scale(self, name: str) -> float:  # pragma: no cover - needs pyvista (viz extra); proven by the gated tests
    """The scale that moves the largest ``name`` displacement `WARP_SHARE` of the section's bounds diagonal, 0.0 when nothing moves."""
    finite: list[FloatArray] = [chunk[np.isfinite(chunk)] for chunk in self.region_magnitudes(name, None)]
    largest: float = max((float(np.max(chunk)) for chunk in finite if chunk.size), default=0.0)
    if largest == 0.0:
        return 0.0

    bounds: Sequence[float] = self.section_blocks.bounds
    diagonal: float = math.dist(bounds[0::2], bounds[1::2])

    return WARP_SHARE * diagonal / largest

warp_of

warp_of(spec: DisplaySpec) -> tuple[str, float] | None

The vector array and the scale a spec displaces the bodies by: its own scale, else the automatic one; None for no warp or a zero scale.

Source code in src/femforge/viz/field_display.py
def warp_of(self, spec: DisplaySpec) -> tuple[str, float] | None:
    """The vector array and the scale a spec displaces the bodies by: its own scale, else the automatic one; None for no warp or a zero scale."""
    name: str | None = spec.fitted(self.fields).warp if self.fields else None
    if name is None:
        return None

    scale: float = spec.warp_scale if spec.warp_scale is not None else self.auto_warp_scale(name)

    return (name, scale) if scale > 0.0 else None

shades_like

shades_like(shading: Shading) -> bool

Whether the drawn surfaces carry the normals shading asks for; its light terms restyle them in place.

Source code in src/femforge/viz/field_display.py
def shades_like(self, shading: Shading) -> bool:
    """Whether the drawn surfaces carry the normals ``shading`` asks for; its light terms restyle them in place."""
    return self.shading.smooth == shading.smooth and (not shading.smooth or self.shading.split_angle == shading.split_angle)

reshaped

reshaped(spec: DisplaySpec) -> bool

Whether a spec asks for other shown blocks than the scene holds: another expansion, sweep or warp.

Source code in src/femforge/viz/field_display.py
def reshaped(self, spec: DisplaySpec) -> bool:
    """Whether a spec asks for other shown blocks than the scene holds: another expansion, sweep or warp."""
    return self.expansion_of(spec) != self.expanded or self.warp_of(spec) != self.warped

expand

expand(spec: DisplaySpec) -> bool

Rebuilds the shown blocks and grid for the spec's expansion and warp when either changed, dropping the field lines integrated for the old ones; True when it did.

Source code in src/femforge/viz/field_display.py
def expand(self, spec: DisplaySpec) -> bool:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """Rebuilds the shown blocks and grid for the spec's expansion and warp when either changed, dropping the field lines integrated for the old ones; True when it did."""
    import pyvista as pv

    wanted: tuple[Expansion, float] = self.expansion_of(spec)
    warp: tuple[str, float] | None = self.warp_of(spec)
    if wanted == self.expanded and warp == self.warped:
        return False

    expansion, sweep = wanted
    basis: Basis | None = self.basis
    still: frozenset[str] = frozenset(info.name for info in self.fields if info.kind is not FieldKind.VECTOR)

    def deform[Shown: pv.DataSet](dataset: Shown) -> Shown:
        """The dataset displaced by the warp, as is without one."""
        if warp is None:
            return dataset

        return warped(dataset, *warp)

    def rebuilt(build: Callable[[pv.DataSet], pv.DataSet]) -> pv.MultiBlock:
        """Every section block through ``build`` and the warp, under its name."""
        shown: pv.MultiBlock = pv.MultiBlock()
        for name in (str(key) for key in self.section_blocks.keys()):
            shown.append(deform(build(cast("pv.DataSet", self.section_blocks[name]))), name=name)

        return shown

    match expansion:
        case Expansion.SECTION if warp is None:
            self.blocks, self.grid = self.section_blocks, self.section_grid
        case Expansion.SECTION:
            self.blocks, self.grid = rebuilt(lambda block: block), deform(self.section_grid)
        case Expansion.MIRROR:
            self.blocks, self.grid = rebuilt(lambda block: mirror(block, still=still)), deform(mirror(self.section_grid, still=still))
        case Expansion.REVOLVE:
            assert basis is not None, "a run without a basis is shown as is"
            self.blocks, self.grid = rebuilt(lambda block: revolve(block, basis, sweep=sweep, still=still)), deform(self.section_grid)
        case Expansion.EXTRUDE:
            self.blocks, self.grid = rebuilt(lambda block: extrude(block, self.depth, still=still)), deform(self.section_grid)

    # Recorded only once the blocks stand, so a build that raised is tried again by the next draw; the body actor holds the old blocks, so it is added anew.
    self.expanded = wanted
    self.warped = warp
    self._actor = None
    self._surfaces = None
    self._lines = None
    self.drawn_lines = None
    log.bind(
        run_id=self.run_id,
        expansion=str(expansion),
        sweep=sweep,
        warp=warp[0] if warp is not None else None,
        scale=warp[1] if warp is not None else None,
    ).info("Shown bodies rebuilt.")

    return True

field_info

field_info(name: str) -> FieldInfo

The FieldInfo for an array name, resolved the same way a field query resolves one.

Source code in src/femforge/viz/field_display.py
def field_info(self, name: str) -> FieldInfo:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """The [`FieldInfo`][] for an array name, resolved the same way a field query resolves one."""
    by_name: dict[str, FieldInfo] = {info.name: info for info in self.fields}
    return by_name[select_array(by_name, name)]

apply

apply(spec: DisplaySpec) -> tuple[float, float]

Write the spec's reduction into every block's display_scalars array and return the color limits it produced.

Source code in src/femforge/viz/field_display.py
def apply(self, spec: DisplaySpec) -> tuple[float, float]:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """Write the spec's reduction into every block's ``display_scalars`` array and return the color limits it produced."""
    import pyvista as pv

    fitted: DisplaySpec = spec.fitted(self.fields)
    info: FieldInfo = self.field_info(fitted.field)
    _ = self.expand(fitted)

    def raw_values(block: pv.DataSet) -> FloatArray:
        """One block's copy of the displayed array, zero-filled when the block never carried it."""
        arrays = block.point_data if info.association is Association.POINT else block.cell_data
        width: int = block.n_points if info.association is Association.POINT else block.n_cells
        if info.name not in arrays:
            return np.zeros((width, info.components), dtype=np.float64)

        return np.asarray(arrays[info.name], dtype=np.float64)

    names: list[str] = [str(key) for key in self.blocks.keys()]
    solved: list[AnyArray] = [reduce_field(raw_values(cast("pv.DataSet", self.section_blocks[name])), fitted.mode) for name in names]
    shown: list[AnyArray] = solved if self.blocks is self.section_blocks else [reduce_field(raw_values(cast("pv.DataSet", self.blocks[name])), fitted.mode) for name in names]

    # Every body counts, each through its own range, whatever it is shown as: the scale belongs to the field, not the view. A
    # component or an in-plane direction turns with the expansion, so its range comes from the values drawn.
    ranged: list[AnyArray] = solved if fitted.mode in ROTATION_FREE_MODES else shown
    self.data_range = color_range(ranged, robust=False)
    clim: tuple[float, float] = fitted.clim if fitted.clim is not None else color_range(ranged, log_scale=fitted.log_scale, robust=fitted.robust)

    def painted(block: pv.DataSet) -> AnyArray:
        """What colors one block: the reduction, or RGBA rows in the polar mode, whose reduction only sets the range."""
        values: FloatArray = raw_values(block)
        if fitted.mode is not DisplayMode.POLAR_XY:
            return reduce_field(values, fitted.mode)

        cmap = pv.get_cmap_safe(fitted.colormap)  # pyright: ignore[reportUnknownMemberType]  # pyvista returns an untyped matplotlib Colormap

        def mapper(fractions: FloatArray) -> FloatArray:
            """RGBA rows for cyclic angle fractions, through the spec's colormap."""
            return np.asarray(cmap(fractions), dtype=np.float64)

        return polar_rgba(values, clim[0], clim[1], mapper)

    surfaces: list[pv.DataSet] = [] if self._surfaces is None else [cast("pv.DataSet", self._surfaces[name]) for name in names]
    for block in [*(cast("pv.DataSet", self.blocks[name]) for name in names), *surfaces]:
        arrays = block.point_data if info.association is Association.POINT else block.cell_data
        # VTK's SetScalars replaces whichever array is active, the displayed field itself when it is, so the reduction is added beside it and then made active.
        arrays[SCALARS_ARRAY] = painted(block)
        arrays.active_scalars_name = SCALARS_ARRAY

    self.spec = fitted
    self.clim = clim
    return clim

render

render(plotter: Plotter) -> None

Draw the whole display into plotter: the composite body actor, then everything update owns; solid bodies an earlier scene left go first.

Source code in src/femforge/viz/field_display.py
def render(self, plotter: pv.Plotter) -> None:  # pragma: no cover - needs pyvista (viz extra) + a VTK render context; proven by the gated integration test
    """Draw the whole display into ``plotter``: the composite body actor, then everything [`update`][] owns; solid bodies an earlier scene left go first."""
    spec: DisplaySpec = self.spec
    _ = self.apply(spec)
    self._styled = {}
    self.drawn_lines = None

    actors = cast("Mapping[str, object]", plotter.renderer.actors)
    leftovers = [name for name in actors if name.startswith(SceneActor.STYLED.of(""))]
    for name in leftovers:
        _ = plotter.remove_actor(name)  # pyright: ignore[reportUnknownMemberType, reportArgumentType]  # pyvista removes by actor name, and its _Wrapped stub loses `self`

    # pyvista draws a composite through surface copies of its blocks, so the scene keeps those copies to recolor them.
    surfaces: pv.MultiBlock = self.blocks.as_polydata_blocks()
    for name in [str(key) for key in surfaces.keys()]:
        surfaces[name] = shaded(cast("pv.PolyData", surfaces[name]), spec.shading)

    self._surfaces = surfaces
    self.shading = spec.shading
    self._actor = plotter.add_mesh(  # pyright: ignore[reportUnknownMemberType]
        surfaces,
        scalars=SCALARS_ARRAY,
        show_edges=False,
        show_scalar_bar=False,
        name=str(SceneActor.BODIES),
    )
    # Translucent bodies sort per fragment only under depth peeling; without it a far body can paint over a near one.
    _ = cast("object", plotter.enable_depth_peeling())  # pyright: ignore[reportCallIssue, reportUnknownMemberType]  # pyvista's _Wrapped stub loses `self`
    self._redraw(plotter, spec)

update

update(plotter: Plotter, spec: DisplaySpec) -> None

Recolor an already-rendered scene in place, the cheap path a panel calls on every knob change; a changed expansion or warp draws the scene anew.

Source code in src/femforge/viz/field_display.py
def update(self, plotter: pv.Plotter, spec: DisplaySpec) -> None:  # pragma: no cover - needs pyvista (viz extra) + a VTK render context; proven by the gated integration test
    """Recolor an already-rendered scene in place, the cheap path a panel calls on every knob change; a changed expansion or warp draws the scene anew."""
    if self._actor is None or self.reshaped(spec.fitted(self.fields)) or not self.shades_like(spec.shading):
        self.spec = spec
        self.render(plotter)
        return

    self._redraw(plotter, spec)

group_cells

group_cells(ref: EntityRef) -> DataSet | None

The solved cells of a body, or of a boundary a condition marked in the VTU; None for any other group.

Source code in src/femforge/viz/field_display.py
def group_cells(self, ref: EntityRef) -> pv.DataSet | None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The solved cells of a body, or of a boundary a condition marked in the VTU; None for any other group."""
    from femforge.viz.glyphs import EntityKind

    if ref.kind is EntityKind.BODY:
        return cast("pv.DataSet", self.section_blocks[ref.name]) if ref.name in self.section_blocks.keys() else None

    boundary = self.boundaries.get(ref.name)
    if boundary is None or boundary.sif_index is None or GEOMETRY_IDS_ARRAY not in self.section_grid.cell_data:
        return None

    # The VTU marks a boundary's cells by its block number past an offset that grows tenfold until it clears every body id.
    largest: int = max((body.mesh_id for body in self.bodies), default=0)
    offset: int = BC_ID_OFFSET
    while offset <= largest:
        offset *= 10

    ids: IntArray = np.asarray(self.section_grid.cell_data[GEOMETRY_IDS_ARRAY], dtype=np.int64)
    picked = cast("np.typing.NDArray[np.bool_]", ids == offset + boundary.sif_index)
    if not bool(np.any(picked)):
        return None

    return cast("pv.DataSet", self.section_grid.extract_cells(np.flatnonzero(picked)))  # pyright: ignore[reportUnknownMemberType]  # pyvista's extract_cells index parameter is partially untyped

shown_blocks

shown_blocks(hidden: Iterable[str]) -> MultiBlock

The blocks of every body not in hidden, under their names.

Source code in src/femforge/viz/field_display.py
def shown_blocks(self, hidden: Iterable[str]) -> pv.MultiBlock:  # pragma: no cover - needs pyvista (viz extra)
    """The blocks of every body not in ``hidden``, under their names."""
    import pyvista as pv

    skipped: set[str] = set(hidden)
    shown: pv.MultiBlock = pv.MultiBlock()
    for name in (str(key) for key in self.blocks.keys()):
        if name not in skipped:
            shown.append(self.blocks[name], name=name)

    return shown

lines_share

lines_share(styled: FieldLineOptions) -> bool

Whether lines drawn with styled map like the field: the same colormap, inversion, log scale, opacity map and limits.

Source code in src/femforge/viz/field_display.py
def lines_share(self, styled: FieldLineOptions) -> bool:
    """Whether lines drawn with ``styled`` map like the field: the same colormap, inversion, log scale, opacity map and limits."""
    spec: DisplaySpec = self.spec
    same_map: bool = styled.colormap == spec.colormap and styled.invert == spec.invert and styled.log_scale == spec.log_scale

    return same_map and styled.opacity_map == spec.opacity_map and styled.clim == self.clim

lines_array

lines_array(options: FieldLineOptions, shown: str) -> str | None

The array the field lines follow: the one asked for when the grid has it, else the one line_vectors picks for the shown array.

Source code in src/femforge/viz/field_display.py
def lines_array(self, options: FieldLineOptions, shown: str) -> str | None:
    """The array the field lines follow: the one asked for when the grid has it, else the one [`line_vectors`][] picks for the ``shown`` array."""
    if options.vectors is None:
        return line_vectors(self.fields, shown)

    return options.vectors if options.vectors in self.grid.array_names else None

integrated

integrated(options: FieldLineOptions) -> StreamlineActors | None

The cached field lines when options only restyle them, None when they need integrating.

Source code in src/femforge/viz/field_display.py
def integrated(self, options: FieldLineOptions) -> StreamlineActors | None:
    """The cached field lines when ``options`` only restyle them, None when they need integrating."""
    if self._lines is None or not integrates_like(self._lines[1], options):
        return None

    return self._lines[0]

integrate_streamlines

integrate_streamlines(options: FieldLineOptions) -> StreamlineActors

Seed and integrate the field lines through the shown grid, carried into a revolved or extruded display from its section — the compute half, safe off the UI thread.

Source code in src/femforge/viz/field_display.py
def integrate_streamlines(self, options: FieldLineOptions) -> StreamlineActors:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """Seed and integrate the field lines through the shown grid, carried into a revolved or extruded display from its section — the compute half, safe off the UI thread."""
    expansion: Expansion = self.expanded[0]
    folding: Basis | Prism | None = self.basis if expansion is Expansion.REVOLVE else Prism(self.depth) if expansion is Expansion.EXTRUDE else None
    if folding is not None:
        source, b_name = prepare_streamline_source(self.grid, options)
        bounds: Bounds = self.region_bounds(options)
        actors: StreamlineActors = build_swept_streamlines(source, b_name, options, folding, bounds, seeds=self.swept_seeds(options, bounds))
    else:
        source, b_name = prepare_streamline_source(self.grid, options)
        actors = build_streamlines(source, b_name, options)

    return replace(actors, magnitudes=self.region_magnitudes(b_name, options.region_id))

region_bounds

region_bounds(options: FieldLineOptions) -> Bounds

The shown bounds the field lines seed: the integration region's body when the options confine them to one, else every body.

Source code in src/femforge/viz/field_display.py
def region_bounds(self, options: FieldLineOptions) -> Bounds:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """The shown bounds the field lines seed: the integration region's body when the options confine them to one, else every body."""
    region: int | None = options.region_id if options.clip_to_region else None
    named: list[str] = [body.name for body in self.bodies if region is not None and body.mesh_id == region and body.name in self.blocks.keys()]
    if not named:
        return self.bounds

    return cast("Bounds", tuple(cast("pv.DataSet", self.blocks[named[0]]).bounds))

swept_seeds

swept_seeds(options: FieldLineOptions, bounds: Bounds) -> FloatArray | None

The seeds of the revolved display as a solid run would place them in bounds, less the ones a partial sweep cuts away; None leaves a full sweep to seed itself.

Source code in src/femforge/viz/field_display.py
def swept_seeds(self, options: FieldLineOptions, bounds: Bounds) -> FloatArray | None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """The seeds of the revolved display as a solid run would place them in ``bounds``, less the ones a partial sweep cuts away; None leaves a full sweep to seed itself."""
    basis: Basis | None = self.basis
    sweep: float = self.expanded[1]
    if basis is None or sweep >= FULL_SWEEP:
        return None

    filling: FloatArray = np.asarray(seed_points(bounds, options), dtype=np.float64)
    _, theta = basis.fold(filling)
    # Shifted by the slack before the wrap, so a seed a rounding error below the first cut face counts as on it, like one past the last.
    inside = cast("np.typing.NDArray[np.bool_]", np.mod(theta + AXIS_SLACK, 2.0 * math.pi) <= math.radians(sweep) + 2.0 * AXIS_SLACK)

    return filling[inside]

region_magnitudes

region_magnitudes(name: str, region_id: int | None) -> list[FloatArray]

The magnitudes of array name per body of a region (every body for None) as solved, the chunks a field-line range spans.

Source code in src/femforge/viz/field_display.py
def region_magnitudes(self, name: str, region_id: int | None) -> list[FloatArray]:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """The magnitudes of array ``name`` per body of a region (every body for None) as solved, the chunks a field-line range spans."""

    chunks: list[FloatArray] = []
    for block_name in (str(key) for key in self.section_blocks.keys()):
        body = self.bodies.get(block_name)
        if region_id is not None and (body is None or body.mesh_id != region_id):
            continue

        block: pv.DataSet = cast("pv.DataSet", self.section_blocks[block_name])
        arrays = block.cell_data if name in block.cell_data else block.point_data
        if name in arrays:
            chunks.append(reduce_field(np.asarray(arrays[name]), DisplayMode.MAGNITUDE))

    return chunks

show_streamlines

show_streamlines(plotter: Plotter, actors: StreamlineActors, options: FieldLineOptions) -> None

Draw integrated field lines into plotter in the display's mapping, record their options as the drawn ones and keep the lines for a restyle.

Parameters:

  • plotter (Plotter) –

    The plotter to draw into.

  • actors (StreamlineActors) –

    The integrated field lines.

  • options (FieldLineOptions) –

    The options the lines were integrated with.

Source code in src/femforge/viz/field_display.py
def show_streamlines(
    self, plotter: pv.Plotter, actors: StreamlineActors, options: FieldLineOptions
) -> None:  # pragma: no cover - needs pyvista (viz extra) + a VTK render context; proven by the gated integration test
    """Draw integrated field lines into ``plotter`` in the display's mapping, record their options as the drawn ones and keep the lines for a restyle.

    Args:
        plotter: The plotter to draw into.
        actors: The integrated field lines.
        options: The options the lines were integrated with.
    """
    styled: FieldLineOptions = self.line_style(options, actors)
    draw_streamlines(actors, styled, plotter)
    self._lines = (actors, options)
    self.drawn_lines = styled
    self.spec = self.spec.model_copy(update={"streamlines": options})

    # The bar holds the mapper it was made with, and a redraw replaces the lines' actor, so it is made again every time.
    self._update_lines_bar(plotter)

lines_follow

lines_follow(vectors: str) -> bool

Whether field lines following vectors take the display's range: it shows that field's magnitude, so one scale reads for both.

Source code in src/femforge/viz/field_display.py
def lines_follow(self, vectors: str) -> bool:
    """Whether field lines following ``vectors`` take the display's range: it shows that field's magnitude, so one scale reads for both."""
    spec: DisplaySpec = self.spec
    return spec.mode is DisplayMode.MAGNITUDE and spec.field == vectors

lines_title

lines_title(b_name: str) -> str

The field lines' scalar bar title: the integrated field's name and unit.

Source code in src/femforge/viz/field_display.py
def lines_title(self, b_name: str) -> str:
    """The field lines' scalar bar title: the integrated field's name and unit."""
    info: FieldInfo = self.field_info(b_name)

    return titled(f"{info.display_name}{LINES_SUFFIX}", info.unit)

line_style

line_style(options: FieldLineOptions, actors: StreamlineActors) -> FieldLineOptions

The field lines at the display's width, in its colormap, inversion, log scale and opacity map; a polar display leaves their colors as asked.

Their range is the display's while it shows their field's magnitude, else the automatic range of that magnitude over their own region, whatever the bodies show.

Source code in src/femforge/viz/field_display.py
def line_style(self, options: FieldLineOptions, actors: StreamlineActors) -> FieldLineOptions:
    """
    The field lines at the display's width, in its colormap, inversion, log scale and opacity map; a polar display leaves their colors as asked.

    Their range is the display's while it shows their field's magnitude, else the automatic range of that magnitude over their own region, whatever the bodies show.
    """
    spec: DisplaySpec = self.spec
    width: float = spec.edges.line_width * spec.scale
    if spec.mode is DisplayMode.POLAR_XY:
        return options.model_copy(update={"line_width": width})

    return options.model_copy(
        update={
            "line_width": width,
            "colormap": spec.colormap,
            "invert": spec.invert,
            "log_scale": spec.log_scale,
            "opacity_map": spec.opacity_map,
            "clim": self.clim if self.lines_follow(actors.b_name) else color_range(actors.magnitudes, log_scale=spec.log_scale, robust=spec.robust),
        }
    )

SceneActor

Bases: StrEnum

The plotter actor names a FieldScene registers, so a toggle removes exactly one.

Methods:

  • of –

    The actor name of one body under this prefix.

Attributes:

  • BODIES –

    The colored field over the shown bodies.

  • OUTLINE –

    The feature-edge outline of the bodies.

  • STYLED –

    The prefix of a styled body's own actor, followed by the body name.

BODIES class-attribute instance-attribute

BODIES = 'field-bodies'

The colored field over the shown bodies.

OUTLINE class-attribute instance-attribute

OUTLINE = 'field-outline'

The feature-edge outline of the bodies.

STYLED class-attribute instance-attribute

STYLED = 'field-styled'

The prefix of a styled body's own actor, followed by the body name.

of

of(body: str) -> str

The actor name of one body under this prefix.

Source code in src/femforge/viz/field_display.py
def of(self, body: str) -> str:
    """The actor name of one body under this prefix."""
    return f"{self}:{body}"

Renderable

Bases: Protocol

Something a workbench run returns for display: it draws itself into plotter (on the plotter thread).

Methods:

  • render –

    Draw into plotter, on the plotter thread.

render

render(plotter: Plotter) -> None

Draw into plotter, on the plotter thread.

Source code in src/femforge/viz/scene.py
def render(self, plotter: pv.Plotter) -> None:
    """Draw into ``plotter``, on the plotter thread."""
    ...

Scene

Scene(*items: Renderable)

An ordered group of Renderables drawn into one plotter refresh: clear once, draw in order (later items on top), repaint once.

Scene is itself a Renderable, so scenes can nest.

Methods:

  • add –

    Append a renderable to draw; returns self so calls chain.

  • render –

    Clear the plotter but keep its lights, draw every item in order, and repaint — once. Call on the plotter thread.

Source code in src/femforge/viz/scene.py
def __init__(self, *items: Renderable) -> None:
    """Hold ``items`` in drawing order."""
    self.items: list[Renderable] = list(items)

add

add(item: Renderable) -> Scene

Append a renderable to draw; returns self so calls chain.

Source code in src/femforge/viz/scene.py
def add(self, item: Renderable) -> Scene:
    """Append a renderable to draw; returns ``self`` so calls chain."""
    self.items.append(item)
    return self

render

render(plotter: Plotter) -> None

Clear the plotter but keep its lights, draw every item in order, and repaint — once. Call on the plotter thread.

Source code in src/femforge/viz/scene.py
def render(self, plotter: pv.Plotter) -> None:
    """Clear the plotter but keep its lights, draw every item in order, and repaint — once. Call on the plotter thread."""
    lights: list[pv.Light] = list(cast("list[pv.Light]", plotter.renderer.lights))
    plotter.clear()
    for light in lights:
        plotter.add_light(light)

    for item in self.items:
        item.render(plotter)
    plotter.render()

Expansion

Bases: StrEnum

How a 2D section is shown.

Attributes:

  • SECTION –

    The r–z half-plane as solved.

  • MIRROR –

    Both halves of the r–z plane, still 2D in the solve frame.

  • REVOLVE –

    The section swept around the axis into the authored 3D frame.

  • EXTRUDE –

    A Cartesian section extruded through its depth, centred on the section plane in the solve frame.

  • dim (Literal[2, 3]) –

    The dimension of the shown geometry.

SECTION class-attribute instance-attribute

SECTION = 'section'

The r–z half-plane as solved.

MIRROR class-attribute instance-attribute

MIRROR = 'mirror'

Both halves of the r–z plane, still 2D in the solve frame.

REVOLVE class-attribute instance-attribute

REVOLVE = 'revolve'

The section swept around the axis into the authored 3D frame.

EXTRUDE class-attribute instance-attribute

EXTRUDE = 'extrude'

A Cartesian section extruded through its depth, centred on the section plane in the solve frame.

dim property

dim: Literal[2, 3]

The dimension of the shown geometry.

Basis dataclass

Basis(origin: Triple, radial: Triple, axis: Triple)

Where the solve frame sits in the authored model.

Methods:

  • of –

    The basis of a frame's solve plane, as numpy rows.

  • directions –

    The unit radial and azimuthal directions e_r and e_φ at each angle, as (N, 3) rows.

  • place –

    The authored points of section points (r, z) swept to theta; any section Z is ignored.

  • rotate –

    The authored form of solve-frame vectors at theta: X along e_r, Y along the axis, Z along -e_φ.

  • fold –

    The section points (r, z, 0) of authored points and their angles in (-π, π], inverting place.

  • carry –

    values rotated to theta when they are 3-component floating vectors, else unchanged.

Attributes:

  • origin (Triple) –

    A point on the axis, the section's (0, 0).

  • radial (Triple) –

    The unit radial direction at θ = 0, the section's +X.

  • axis (Triple) –

    The unit axis direction, the section's +Y.

  • DEFAULT (Basis) –

    The default frame's basis: radial +X, axis +Z, normal +Y.

  • SOLVE (Basis) –

    The solve frame itself, whose θ = π half is the section's mirror image.

  • normal (Triple) –

    The radial direction at θ = 90°, axis × radial.

origin instance-attribute

origin: Triple

A point on the axis, the section's (0, 0).

radial instance-attribute

radial: Triple

The unit radial direction at θ = 0, the section's +X.

axis instance-attribute

axis: Triple

The unit axis direction, the section's +Y.

DEFAULT class-attribute

DEFAULT: Basis

The default frame's basis: radial +X, axis +Z, normal +Y.

SOLVE class-attribute

SOLVE: Basis

The solve frame itself, whose θ = π half is the section's mirror image.

normal property

normal: Triple

The radial direction at θ = 90°, axis × radial.

of classmethod

of(plane: SolvePlane) -> Basis

The basis of a frame's solve plane, as numpy rows.

Source code in src/femforge/viz/symmetry.py
@classmethod
def of(cls, plane: SolvePlane) -> Basis:
    """The basis of a frame's solve plane, as numpy rows."""
    return cls(
        origin=_triple(np.asarray(plane.origin.to_list(), dtype=np.float64)),
        radial=_triple(np.asarray(plane.x_dir.to_list(), dtype=np.float64)),
        axis=_triple(np.asarray(plane.y_dir.to_list(), dtype=np.float64)),
    )

directions

directions(theta: FloatArray | float) -> tuple[FloatArray, FloatArray]

The unit radial and azimuthal directions e_r and e_φ at each angle, as (N, 3) rows.

Source code in src/femforge/viz/symmetry.py
def directions(self, theta: FloatArray | float) -> tuple[FloatArray, FloatArray]:
    """The unit radial and azimuthal directions ``e_r`` and ``e_φ`` at each angle, as ``(N, 3)`` rows."""
    angles: FloatArray = np.asarray(theta, dtype=np.float64).reshape(-1, 1)
    cosine: FloatArray = np.cos(angles)
    sine: FloatArray = np.sin(angles)
    radial: FloatArray = np.asarray(self.radial)
    normal: FloatArray = np.asarray(self.normal)

    return cosine * radial + sine * normal, cosine * normal - sine * radial

place

place(section: FloatArray, theta: FloatArray | float) -> FloatArray

The authored points of section points (r, z) swept to theta; any section Z is ignored.

Source code in src/femforge/viz/symmetry.py
def place(self, section: FloatArray, theta: FloatArray | float) -> FloatArray:
    """The authored points of section points ``(r, z)`` swept to ``theta``; any section Z is ignored."""
    e_r, _ = self.directions(theta)

    return np.asarray(self.origin) + section[:, :1] * e_r + section[:, 1:2] * np.asarray(self.axis)

rotate

rotate(vectors: FloatArray, theta: FloatArray | float) -> FloatArray

The authored form of solve-frame vectors at theta: X along e_r, Y along the axis, Z along -e_φ.

Source code in src/femforge/viz/symmetry.py
def rotate(self, vectors: FloatArray, theta: FloatArray | float) -> FloatArray:
    """The authored form of solve-frame vectors at ``theta``: X along ``e_r``, Y along the axis, Z along ``-e_φ``."""
    e_r, e_phi = self.directions(theta)

    return vectors[:, :1] * e_r + vectors[:, 1:2] * np.asarray(self.axis) - vectors[:, 2:3] * e_phi

fold

fold(points: FloatArray) -> tuple[FloatArray, FloatArray]

The section points (r, z, 0) of authored points and their angles in (-π, π], inverting place.

Source code in src/femforge/viz/symmetry.py
def fold(self, points: FloatArray) -> tuple[FloatArray, FloatArray]:
    """The section points ``(r, z, 0)`` of authored points and their angles in ``(-π, π]``, inverting [`place`][]."""
    offset: FloatArray = points - np.asarray(self.origin)
    along: FloatArray = offset @ np.asarray(self.axis)
    x: FloatArray = offset @ np.asarray(self.radial)
    y: FloatArray = offset @ np.asarray(self.normal)
    angles: FloatArray = np.arctan2(y, x)
    theta: FloatArray = np.where(angles <= -np.pi, np.pi, angles)
    radius: FloatArray = np.hypot(x, y)

    return np.column_stack([radius, along, np.zeros_like(radius)]), theta

carry

carry(values: AnyArray, theta: FloatArray | float) -> AnyArray

values rotated to theta when they are 3-component floating vectors, else unchanged.

Source code in src/femforge/viz/symmetry.py
def carry(self, values: AnyArray, theta: FloatArray | float) -> AnyArray:
    """``values`` rotated to ``theta`` when they are 3-component floating vectors, else unchanged."""
    if values.ndim != 2 or values.shape[1] != 3 or not np.issubdtype(values.dtype, np.floating):
        return values

    return self.rotate(values.astype(np.float64), theta).astype(values.dtype)

Prism dataclass

Prism(depth: float)

A Cartesian section's depth along the solve Z, with the section plane at its middle.

Methods:

  • fold –

    The section points (x, y, 0) of solve-frame points and their Z, inverting place.

  • place –

    Section points (x, y) at solve Z along; any section Z is ignored.

  • carry –

    values unchanged, since an extrusion turns no vector.

Attributes:

  • depth (float) –

    t [m]: The extrusion depth.

depth instance-attribute

depth: float

t [m]: The extrusion depth.

fold

fold(points: FloatArray) -> tuple[FloatArray, FloatArray]

The section points (x, y, 0) of solve-frame points and their Z, inverting place.

Source code in src/femforge/viz/symmetry.py
def fold(self, points: FloatArray) -> tuple[FloatArray, FloatArray]:
    """The section points ``(x, y, 0)`` of solve-frame points and their Z, inverting [`place`][]."""
    along: FloatArray = np.asarray(points[:, 2], dtype=np.float64).copy()

    return np.column_stack([points[:, 0], points[:, 1], np.zeros_like(along)]), along

place

place(section: FloatArray, along: FloatArray | float) -> FloatArray

Section points (x, y) at solve Z along; any section Z is ignored.

Source code in src/femforge/viz/symmetry.py
def place(self, section: FloatArray, along: FloatArray | float) -> FloatArray:
    """Section points ``(x, y)`` at solve Z ``along``; any section Z is ignored."""
    heights: FloatArray = np.broadcast_to(np.asarray(along, dtype=np.float64), (len(section),))

    return np.column_stack([section[:, 0], section[:, 1], heights])

carry

carry(values: AnyArray, _along: FloatArray | float) -> AnyArray

values unchanged, since an extrusion turns no vector.

Source code in src/femforge/viz/symmetry.py
def carry(self, values: AnyArray, _along: FloatArray | float) -> AnyArray:
    """``values`` unchanged, since an extrusion turns no vector."""
    return values

GlyphLabels

Bases: StrEnum

How glyph values are labelled in the scene.

Attributes:

  • SCENE –

    Point labels in the scene, the only text actor both renderers draw crisply.

  • NONE –

    No labels; the shapes alone.

SCENE class-attribute instance-attribute

SCENE = 'scene'

Point labels in the scene, the only text actor both renderers draw crisply.

NONE class-attribute instance-attribute

NONE = 'none'

No labels; the shapes alone.

GlyphActor

Bases: StrEnum

The plotter actor names the glyph layer owns, so a redraw replaces or removes exactly these.

Attributes:

  • ARROWS –

    Load, magnet and displacement arrows and the filled marks.

  • HALOS –

    The dark hulls behind the arrows.

  • FACES –

    Translucent tints of 3D or revolved faces.

  • LINES –

    Opaque tints of 2D faces.

  • MARKS –

    Clamp ticks, support pins, rollers and current markers.

  • LEADERS –

    The lines from a face to its label chip.

  • LABELS –

    Value labels.

  • SELECTION –

    The accent silhouette or line of the selected entity.

  • SELECTION_FILL –

    The accent fill of the selected entity.

  • SELECTION_GLYPHS –

    The selected entity's arrows and pins redrawn in the accent.

  • OUTLINE –

    The boundary loops of a 2D section.

  • PLANE –

    The section plane under a revolved display.

  • GHOST –

    The translucent authored bodies a 2D frame sectioned.

  • HULL –

    The ghost's silhouette and the dashed prism or revolved outline it is checked against.

  • HOVER –

    The prefix of each entity's hidden hover outline, which the browser shows while the entity's row is hovered.

ARROWS class-attribute instance-attribute

ARROWS = 'glyph-arrows'

Load, magnet and displacement arrows and the filled marks.

HALOS class-attribute instance-attribute

HALOS = 'glyph-halos'

The dark hulls behind the arrows.

FACES class-attribute instance-attribute

FACES = 'glyph-faces'

Translucent tints of 3D or revolved faces.

LINES class-attribute instance-attribute

LINES = 'glyph-lines'

Opaque tints of 2D faces.

MARKS class-attribute instance-attribute

MARKS = 'glyph-marks'

Clamp ticks, support pins, rollers and current markers.

LEADERS class-attribute instance-attribute

LEADERS = 'glyph-leaders'

The lines from a face to its label chip.

LABELS class-attribute instance-attribute

LABELS = 'glyph-labels'

Value labels.

SELECTION class-attribute instance-attribute

SELECTION = 'glyph-selection'

The accent silhouette or line of the selected entity.

SELECTION_FILL class-attribute instance-attribute

SELECTION_FILL = 'glyph-selection-fill'

The accent fill of the selected entity.

SELECTION_GLYPHS class-attribute instance-attribute

SELECTION_GLYPHS = 'glyph-selection-glyphs'

The selected entity's arrows and pins redrawn in the accent.

OUTLINE class-attribute instance-attribute

OUTLINE = 'glyph-outline'

The boundary loops of a 2D section.

PLANE class-attribute instance-attribute

PLANE = 'glyph-plane'

The section plane under a revolved display.

GHOST class-attribute instance-attribute

GHOST = 'glyph-ghost'

The translucent authored bodies a 2D frame sectioned.

HULL class-attribute instance-attribute

HULL = 'glyph-hull'

The ghost's silhouette and the dashed prism or revolved outline it is checked against.

HOVER class-attribute instance-attribute

HOVER = 'glyph-hover:'

The prefix of each entity's hidden hover outline, which the browser shows while the entity's row is hovered.

EntityKind

Bases: StrEnum

Whether an entity row names a body group or a boundary group.

Attributes:

  • BODY –

    A body group.

  • BOUNDARY –

    A boundary group.

BODY class-attribute instance-attribute

BODY = 'body'

A body group.

BOUNDARY class-attribute instance-attribute

BOUNDARY = 'boundary'

A boundary group.

EntityRef dataclass

EntityRef(kind: EntityKind, name: str)

A body or boundary group by kind and name, so a body and a named face that share a name stay apart.

Methods:

  • parse –

    The ref an id names, None for anything else.

Attributes:

  • kind (EntityKind) –

    Whether the group is a body or a boundary.

  • name (str) –

    The group name, shared by the mesh and the sif.

  • id (str) –

    The ref as one string, such as boundary:RIGHTFACE.

kind instance-attribute

kind: EntityKind

Whether the group is a body or a boundary.

name instance-attribute

name: str

The group name, shared by the mesh and the sif.

id property

id: str

The ref as one string, such as boundary:RIGHTFACE.

parse classmethod

parse(value: str) -> EntityRef | None

The ref an id names, None for anything else.

Source code in src/femforge/viz/glyphs.py
@classmethod
def parse(cls, value: str) -> EntityRef | None:
    """The ref an [`id`][femforge.viz.glyphs.EntityRef.id] names, None for anything else."""
    kind, separator, name = value.partition(":")

    if not separator or not name or kind not in EntityKind:
        return None

    return cls(EntityKind(kind), name)

Glyph pydantic-model

Bases: BaseModel

One condition as the scene draws it, in the solve frame the run was meshed in.

Config:

  • frozen: True
  • use_attribute_docstrings: True

Fields:

group pydantic-field

group: str

The group the condition landed on.

target pydantic-field

target: EntityKind

Whether the group is a body or a boundary.

kind pydantic-field

The shape the condition draws as.

anchor pydantic-field

anchor: Vec3Field

[m]: Where the glyph sits: the group's centroid.

normal pydantic-field

normal: Vec3Field | None = None

[-]: The outward normal of a boundary; None for a body or an ill-defined normal.

vector pydantic-field

vector: Vec3Field | None = None

[-]: The unit direction of the condition vector the solver received; None for a condition without one.

share pydantic-field

share: float = 1.0

[-]: The load's size against the largest load of its kind, which sets an arrow's length.

label pydantic-field

label: str | None = None

The value label; None draws no label.

held pydantic-field

held: tuple[bool, ...] = ()

Whether each solve coordinate is held, for a fixed displacement.

extent pydantic-field

extent: float | None = None

L [m]: The arrow length of a magnet.

reach pydantic-field

reach: float = 0.0

r [m]: How far a magnet reaches from its centroid along its direction, where a 3D display starts its arrow so the body does not hide it.

ref property

ref: EntityRef

The group this glyph draws on.

GlyphView pydantic-model

Bases: BaseModel

What the Setup tab asks the scene to draw: which glyphs, their labels and size, and the selection, outline and ghost around them.

Config:

  • frozen: True
  • use_attribute_docstrings: True

Fields:

kinds pydantic-field

The glyph kinds drawn; empty draws no glyph.

hidden pydantic-field

hidden: frozenset[str]

The entity ids whose glyphs are hidden.

plain_bodies pydantic-field

plain_bodies: bool = False

Paint every body plain grey while the view is shown.

labels pydantic-field

How the values are labelled.

scale pydantic-field

scale: float = 1.0

[-]: Window pixels per CSS pixel, which text sizes and line widths scale by.

selected pydantic-field

selected: str | None = None

The entity id highlighted in the accent; None highlights nothing.

outline pydantic-field

outline: bool = True

Draw a 2D section's boundary loops.

ghost pydantic-field

ghost: bool = False

Draw the authored bodies a 2D frame sectioned, beside the prism or revolved outline they are checked against.

accent pydantic-field

accent: str = GLYPH_ACCENT

The selection color, any color pyvista resolves.

hover pydantic-field

hover: str = GLYPH_ACCENT

The hover outline color, any color pyvista resolves.

ink pydantic-field

ink: str = GLYPH_HALO

The color of lines drawn against the background: marks, leaders, the outline and the hull.

edges pydantic-field

edges: EdgeStyle

How the outlines draw, in CSS pixels that scale multiplies.

shading pydantic-field

shading: Shading

How the bodies shade.

GlyphPlacement dataclass

GlyphPlacement(expansion: Expansion = SECTION, sweep: float = FULL_SWEEP, basis: Basis | None = None, diagonal: float = 1.0, flat: bool = False, depth: float = 0.0)

How solve-frame geometry lands in the displayed scene: as solved, beside its mirror image, on the planes of a revolution, or on the front face of an extrusion.

Methods:

  • placed –

    Solve-frame (n, 3) points on the plane at theta radians of a revolved display, unchanged otherwise.

  • copies –

    Solve-frame (n, 3) points as the display shows them: once, beside their mirror image, on the 0° plane of a revolution, or on an extrusion's front face.

  • swept_face –

    The surface solve-frame (n, 2, 3) line segments sweep in a revolved or extruded display, standing for the face a section line is; None in a flat one.

  • angles –

    The radians a revolved display repeats a body's arrow at; only 0 otherwise.

Attributes:

  • expansion (Expansion) –

    How the section is shown.

  • sweep (float) –

    [deg]: The turn a revolved display sweeps.

  • basis (Basis | None) –

    Where the section sits in the authored model; None for a run solved whole.

  • diagonal (float) –

    D [m]: The undeformed scene diagonal glyph sizes scale with.

  • flat (bool) –

    Whether the run solved on a 2D section.

  • depth (float) –

    t [m]: The depth an extruded display extrudes the section through.

  • revolved (bool) –

    Whether the section is shown revolved into the authored frame.

  • extruded (bool) –

    Whether the section is shown extruded through its depth.

  • front (FloatArray) –

    The offset from the section plane to the front face of an extruded display, which the viewer of a flat run faces; zero otherwise.

expansion class-attribute instance-attribute

How the section is shown.

sweep class-attribute instance-attribute

sweep: float = FULL_SWEEP

[deg]: The turn a revolved display sweeps.

basis class-attribute instance-attribute

basis: Basis | None = None

Where the section sits in the authored model; None for a run solved whole.

diagonal class-attribute instance-attribute

diagonal: float = 1.0

D [m]: The undeformed scene diagonal glyph sizes scale with.

flat class-attribute instance-attribute

flat: bool = False

Whether the run solved on a 2D section.

depth class-attribute instance-attribute

depth: float = 0.0

t [m]: The depth an extruded display extrudes the section through.

revolved property

revolved: bool

Whether the section is shown revolved into the authored frame.

extruded property

extruded: bool

Whether the section is shown extruded through its depth.

front property

front: FloatArray

The offset from the section plane to the front face of an extruded display, which the viewer of a flat run faces; zero otherwise.

placed

placed(points: FloatArray, theta: float = 0.0) -> FloatArray

Solve-frame (n, 3) points on the plane at theta radians of a revolved display, unchanged otherwise.

Source code in src/femforge/viz/glyphs.py
def placed(self, points: FloatArray, theta: float = 0.0) -> FloatArray:
    """Solve-frame ``(n, 3)`` points on the plane at ``theta`` radians of a revolved display, unchanged otherwise."""
    if not self.revolved or self.basis is None:
        return points

    return np.asarray(self.basis.origin) + self.basis.rotate(points, theta)

copies

copies(points: FloatArray) -> list[FloatArray]

Solve-frame (n, 3) points as the display shows them: once, beside their mirror image, on the 0° plane of a revolution, or on an extrusion's front face.

Source code in src/femforge/viz/glyphs.py
def copies(self, points: FloatArray) -> list[FloatArray]:
    """Solve-frame ``(n, 3)`` points as the display shows them: once, beside their mirror image, on the 0° plane of a revolution, or on an extrusion's front face."""
    if self.expansion is Expansion.MIRROR:
        return [points, points * MIRROR]

    return [self.placed(points) + self.front]

swept_face

swept_face(segments: FloatArray) -> Surface | None

The surface solve-frame (n, 2, 3) line segments sweep in a revolved or extruded display, standing for the face a section line is; None in a flat one.

Source code in src/femforge/viz/glyphs.py
def swept_face(self, segments: FloatArray) -> Surface | None:
    """The surface solve-frame ``(n, 2, 3)`` line segments sweep in a revolved or extruded display, standing for the face a section line is; None in a flat one."""
    points: FloatArray = segments.reshape(-1, 3)
    pairs: IntArray = np.arange(len(points), dtype=np.int64).reshape(-1, 2)
    if self.revolved and self.basis is not None:
        return swept_lines(points, pairs, self.basis, sweep=self.sweep)

    if self.extruded:
        return extruded_lines(points, pairs, self.depth)

    return None

angles

angles() -> tuple[float, ...]

The radians a revolved display repeats a body's arrow at; only 0 otherwise.

Source code in src/femforge/viz/glyphs.py
def angles(self) -> tuple[float, ...]:
    """The radians a revolved display repeats a body's arrow at; only 0 otherwise."""
    if not self.revolved:
        return (0.0,)

    return tuple(math.radians(angle) for angle in revolve_angles(self.sweep))

GlyphHost

Bases: Protocol

The scene a glyph layer draws over: its frame, how it is shown and the cells of each group.

GlyphDraw dataclass

GlyphDraw(actor: str, mesh: PolyData, color: str = GLYPH_FILL, opacity: float = 1.0, line_width: float | None = None, culling: Literal['front'] | None = None, labels: tuple[str, ...] = (), font_size: int = 0, overlay: bool = False, layer: Layer = BASE)

One merged glyph actor: its name, its geometry and how it is styled.

Attributes:

  • actor (str) –

    The actor name: a GlyphActor, or the hover prefix and an entity id.

  • mesh (PolyData) –

    The geometry, in the displayed scene's frame.

  • color (str) –

    Any color pyvista resolves.

  • opacity (float) –

    [-]: The actor's opacity.

  • line_width (float | None) –

    [px]: The width of its lines in window pixels; None for surfaces.

  • culling (Literal['front'] | None) –

    The faces culled, front for an arrow's halo.

  • labels (tuple[str, ...]) –

    The text at each point of a label actor; empty for geometry.

  • font_size (int) –

    The label font size in window pixels.

  • overlay (bool) –

    Whether the lines draw over the scene as a 2D overlay at their world positions rather than among the bodies.

  • layer (Layer) –

    Which coincident geometry it draws over by a depth offset, its points left where they are.

actor instance-attribute

actor: str

The actor name: a GlyphActor, or the hover prefix and an entity id.

mesh instance-attribute

mesh: PolyData

The geometry, in the displayed scene's frame.

color class-attribute instance-attribute

color: str = GLYPH_FILL

Any color pyvista resolves.

opacity class-attribute instance-attribute

opacity: float = 1.0

[-]: The actor's opacity.

line_width class-attribute instance-attribute

line_width: float | None = None

[px]: The width of its lines in window pixels; None for surfaces.

culling class-attribute instance-attribute

culling: Literal['front'] | None = None

The faces culled, front for an arrow's halo.

labels class-attribute instance-attribute

labels: tuple[str, ...] = ()

The text at each point of a label actor; empty for geometry.

font_size class-attribute instance-attribute

font_size: int = 0

The label font size in window pixels.

overlay class-attribute instance-attribute

overlay: bool = False

Whether the lines draw over the scene as a 2D overlay at their world positions rather than among the bodies.

layer class-attribute instance-attribute

layer: Layer = Layer.BASE

Which coincident geometry it draws over by a depth offset, its points left where they are.

GlyphLayer dataclass

GlyphLayer(glyphs: list[Glyph], bodies: Sequence[Body] = (), boundaries: Sequence[Boundary] = (), frame: Frame = (lambda: default_frame(3))(), mesh_groups: MeshGroups | None = None, authored: PolyData | None = None, run_id: str = '', host: GlyphHost | None = None, drawn: tuple[object, ...] | None = None, names: frozenset[str] = frozenset(), label_spots: FloatArray = (lambda: zeros((0, 3)))(), label_texts: tuple[str, ...] = (), hover_actors: dict[str, Actor] = dict(), chosen: tuple[object, ...] | None = None, chosen_names: frozenset[str] = frozenset(), shown: tuple[list[Glyph], dict[str, DataSet]] = (lambda: ([], {}))(), shapes: dict[tuple[str, str, float], PolyData] = dict())

A run's glyphs and the scene decorations the Setup tab asks for, drawn over a host scene as named actors.

Methods:

  • from_run –

    The glyphs of run from its conditions sidecar and entities, in the frame of scene when given, else of its manifest.

  • group_cells –

    The solve-frame cells of ref from host (else the last host), else from the Elmer mesh; None when neither has any.

  • has –

    Whether ref has cells to highlight.

  • placement –

    How host shows the solve frame.

  • bounds_of –

    The bounds of ref as the last host shows it, its cells moved by their mean warp as the glyph anchors are, from its measured box when it has no cells there; None when it has neither.

  • update –

    Draw view over host as named actors, rebuilt only when the view, the expansion, the warp or the hidden bodies changed.

  • draw_base –

    Draw everything but the selection: the glyphs, the decorations and the hidden hover outlines.

  • draw_selection –

    Swap only the selection actors for those of the selected entity, so a new selection never rebuilds the rest of the layer.

  • shape –

    A copy of a body's surface or feature outline, extracted once while the host, expansion and warp stay.

  • refs –

    Every body host draws and every boundary of the run.

  • hover_draw –

    The outline ref shows while its row is hovered: a body's feature edges, a boundary's lines or rim; None when it has no cells.

  • moved_glyphs –

    The shown glyphs with their anchors moved with host's warp, and the warped cells of each glyph's group by entity id.

  • accent_glyphs –

    The arrows and pins of one entity's glyphs, which a highlight redraws in its color; None when the entity shows none.

  • selection –

    The accent silhouette and fill of the selected body, or the accent lines or cells of the selected boundary.

  • decorations –

    The section outline with its plane, and the authored ghost with its hull.

  • deformed_section –

    The section blocks of host displaced by its warp, so an outline follows the body the scene shows; as solved without a warp.

  • hull –

    The (m, 2, 3) edges the ghost is checked against: the section extruded through the prism depth, or revolved about the axis.

Attributes:

  • glyphs (list[Glyph]) –

    The drawable conditions, in the solve frame.

  • bodies (Sequence[Body]) –

    The run's bodies.

  • boundaries (Sequence[Boundary]) –

    The run's boundaries.

  • frame (Frame) –

    The frame the run solved in.

  • mesh_groups (MeshGroups | None) –

    The group cells from the Elmer mesh, for groups the host has no cells of; None when the mesh is gone.

  • authored (PolyData | None) –

    The authored bodies a 2D frame sectioned, in the solve frame; None when the run wrote none.

  • run_id (str) –

    The run bundle's name, for the log.

  • host (GlyphHost | None) –

    The scene the layer last drew over.

  • drawn (tuple[object, ...] | None) –

    What the drawn actors were built for: the view, the expansion, the warp and the hidden bodies.

  • names (frozenset[str]) –

    The actor names the plotter holds from the last draw.

  • label_spots (FloatArray) –

    [m]: The (n, 3) points the last draw labelled, in the displayed scene's frame.

  • label_texts (tuple[str, ...]) –

    The text at each of label_spots.

  • hover_actors (dict[str, Actor]) –

    The hidden hover outline of each entity id the last draw outlined.

  • chosen (tuple[object, ...] | None) –

    What the selection actors were built for: the drawn key and the selected entity id.

  • chosen_names (frozenset[str]) –

    The selection actor names the plotter holds from the last selection draw.

  • shown (tuple[list[Glyph], dict[str, DataSet]]) –

    The glyphs the last draw showed, anchors moved with the warp, and their groups' warped cells, which a selection reuses.

  • shapes (dict[tuple[str, str, float], PolyData]) –

    A body's surface or feature outline by kind, name and feature angle, kept while the host, its expansion and its warp stay.

glyphs instance-attribute

glyphs: list[Glyph]

The drawable conditions, in the solve frame.

bodies class-attribute instance-attribute

bodies: Sequence[Body] = ()

The run's bodies.

boundaries class-attribute instance-attribute

boundaries: Sequence[Boundary] = ()

The run's boundaries.

frame class-attribute instance-attribute

frame: Frame = field(default_factory=lambda: default_frame(3))

The frame the run solved in.

mesh_groups class-attribute instance-attribute

mesh_groups: MeshGroups | None = None

The group cells from the Elmer mesh, for groups the host has no cells of; None when the mesh is gone.

authored class-attribute instance-attribute

authored: PolyData | None = None

The authored bodies a 2D frame sectioned, in the solve frame; None when the run wrote none.

run_id class-attribute instance-attribute

run_id: str = ''

The run bundle's name, for the log.

host class-attribute instance-attribute

host: GlyphHost | None = None

The scene the layer last drew over.

drawn class-attribute instance-attribute

drawn: tuple[object, ...] | None = None

What the drawn actors were built for: the view, the expansion, the warp and the hidden bodies.

names class-attribute instance-attribute

names: frozenset[str] = frozenset()

The actor names the plotter holds from the last draw.

label_spots class-attribute instance-attribute

label_spots: FloatArray = field(default_factory=lambda: np.zeros((0, 3)))

[m]: The (n, 3) points the last draw labelled, in the displayed scene's frame.

label_texts class-attribute instance-attribute

label_texts: tuple[str, ...] = ()

The text at each of label_spots.

hover_actors class-attribute instance-attribute

hover_actors: dict[str, Actor] = field(default_factory=dict)

The hidden hover outline of each entity id the last draw outlined.

chosen class-attribute instance-attribute

chosen: tuple[object, ...] | None = None

What the selection actors were built for: the drawn key and the selected entity id.

chosen_names class-attribute instance-attribute

chosen_names: frozenset[str] = frozenset()

The selection actor names the plotter holds from the last selection draw.

shown class-attribute instance-attribute

shown: tuple[list[Glyph], dict[str, DataSet]] = field(default_factory=lambda: ([], {}))

The glyphs the last draw showed, anchors moved with the warp, and their groups' warped cells, which a selection reuses.

shapes class-attribute instance-attribute

shapes: dict[tuple[str, str, float], PolyData] = field(default_factory=dict)

A body's surface or feature outline by kind, name and feature angle, kept while the host, its expansion and its warp stay.

from_run classmethod

from_run(run: Run, scene: FieldScene | None = None) -> GlyphLayer

The glyphs of run from its conditions sidecar and entities, in the frame of scene when given, else of its manifest.

Source code in src/femforge/viz/glyphs.py
@classmethod
def from_run(cls, run: Run, scene: FieldScene | None = None) -> GlyphLayer:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The glyphs of ``run`` from its conditions sidecar and entities, in the frame of ``scene`` when given, else of its manifest."""
    manifest = run_manifest(run) if scene is None else None
    frame: Frame = scene.frame if scene is not None else manifest.config.frame if manifest is not None else default_frame(3)
    conditions: ConditionsFile | None = run.conditions()
    bodies: list[Body] = list(run.bodies)
    boundaries: list[Boundary] = list(run.boundaries)
    glyphs: list[Glyph] = glyphs_of(conditions, bodies, boundaries, frame) if conditions is not None else []

    try:
        authored: pv.PolyData | None = run.authored_geometry()
    except (FileNotFoundError, ValueError):
        authored = None

    log.bind(run_id=run.path.name, glyphs=len(glyphs), conditions=conditions is not None, ghost=authored is not None).info("Glyph layer loaded.")

    return cls(glyphs, bodies=bodies, boundaries=boundaries, frame=frame, mesh_groups=run.mesh_groups(), authored=authored, run_id=run.path.name)

group_cells

group_cells(ref: EntityRef, host: GlyphHost | None = None) -> DataSet | None

The solve-frame cells of ref from host (else the last host), else from the Elmer mesh; None when neither has any.

Source code in src/femforge/viz/glyphs.py
def group_cells(self, ref: EntityRef, host: GlyphHost | None = None) -> pv.DataSet | None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The solve-frame cells of ``ref`` from ``host`` (else the last host), else from the Elmer mesh; None when neither has any."""
    source: GlyphHost | None = host if host is not None else self.host
    found: pv.DataSet | None = source.group_cells(ref) if source is not None else None

    if found is not None and found.n_cells:
        return found

    groups: MeshGroups | None = self.mesh_groups

    if groups is None:
        return None

    match ref.kind:
        case EntityKind.BODY:
            body: Body | None = next((candidate for candidate in self.bodies if candidate.name == ref.name), None)
            mesh: pv.DataSet | None = groups.body(body) if body is not None else None
        case EntityKind.BOUNDARY:
            boundary: Boundary | None = next((candidate for candidate in self.boundaries if candidate.name == ref.name), None)
            mesh = groups.boundary(boundary) if boundary is not None else None

    if mesh is None or not mesh.n_cells:
        return None

    if self.frame.model_dim == 2:
        points: FloatArray = np.asarray(mesh.points, dtype=np.float64)
        points[:, 2] = 0.0
        mesh.points = points

    return mesh

has

has(ref: EntityRef) -> bool

Whether ref has cells to highlight.

Source code in src/femforge/viz/glyphs.py
def has(self, ref: EntityRef) -> bool:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """Whether ``ref`` has cells to highlight."""
    return self.group_cells(ref) is not None

placement

placement(host: GlyphHost) -> GlyphPlacement

How host shows the solve frame.

Source code in src/femforge/viz/glyphs.py
def placement(self, host: GlyphHost) -> GlyphPlacement:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """How ``host`` shows the solve frame."""
    expansion, sweep = host.expanded

    return GlyphPlacement(
        expansion=expansion,
        sweep=sweep,
        basis=host.basis,
        diagonal=shown_diagonal(tuple(host.section_blocks.bounds), expansion),
        flat=host.frame.model_dim == 2,
        depth=prism_depth(host.frame),
    )

bounds_of

bounds_of(ref: EntityRef) -> Bounds | None

The bounds of ref as the last host shows it, its cells moved by their mean warp as the glyph anchors are, from its measured box when it has no cells there; None when it has neither.

Source code in src/femforge/viz/glyphs.py
def bounds_of(self, ref: EntityRef) -> Bounds | None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The bounds of ``ref`` as the last host shows it, its cells moved by their mean warp as the glyph anchors are, from its measured box when it has no cells there; None when it has neither."""
    host: GlyphHost | None = self.host

    if host is not None and ref.kind is EntityKind.BODY and ref.name in host.blocks.keys():
        return cast("Bounds", tuple(cast("pv.DataSet", host.blocks[ref.name]).bounds))

    cells: pv.DataSet | None = self.group_cells(ref)

    if cells is not None and host is not None:
        moved: FloatArray = np.asarray(cells.points, dtype=np.float64) + _mean_shift(cells, host.warped)
        points: FloatArray = np.concatenate(self.placement(host).copies(moved))
        low: FloatArray = points.min(axis=0)
        high: FloatArray = points.max(axis=0)

        return cast("Bounds", (low[0], high[0], low[1], high[1], low[2], high[2]))

    candidates: Sequence[Body | Boundary] = self.bodies if ref.kind is EntityKind.BODY else self.boundaries
    entity: Body | Boundary | None = next((candidate for candidate in candidates if candidate.name == ref.name), None)

    if entity is None or entity.bbox is None:
        return None

    box = entity.bbox

    return (box.low.x, box.high.x, box.low.y, box.high.y, box.low.z, box.high.z)

update

update(plotter: Plotter, host: GlyphHost, view: GlyphView | None) -> None

Draw view over host as named actors, rebuilt only when the view, the expansion, the warp or the hidden bodies changed.

Parameters:

  • plotter (Plotter) –

    The plotter the host scene is drawn in.

  • host (GlyphHost) –

    The scene the glyphs sit on.

  • view (GlyphView | None) –

    What to draw; None removes every glyph actor.

Source code in src/femforge/viz/glyphs.py
def update(self, plotter: pv.Plotter, host: GlyphHost, view: GlyphView | None) -> None:  # pragma: no cover - needs pyvista (viz extra) + a VTK render context; proven by the gated glyph tests
    """Draw ``view`` over ``host`` as named actors, rebuilt only when the view, the expansion, the warp or the hidden bodies changed.

    Args:
        plotter: The plotter the host scene is drawn in.
        host: The scene the glyphs sit on.
        view: What to draw; None removes every glyph actor.
    """
    if host is not self.host or self.drawn is None or self.drawn[1:3] != (host.expanded, host.warped):
        self.shapes = {}

    self.host = host
    base: GlyphView | None = view.model_copy(update={"selected": None}) if view is not None else None
    key: tuple[object, ...] = (base, host.expanded, host.warped, host.spec.hidden_bodies)
    present: set[str] = set(cast("Mapping[str, object]", plotter.renderer.actors).keys())

    if key != self.drawn or not self.names <= present:
        self.draw_base(plotter, host, base, key, present)

    self.draw_selection(plotter, host, view)

draw_base

draw_base(plotter: Plotter, host: GlyphHost, view: GlyphView | None, key: tuple[object, ...], present: set[str]) -> None

Draw everything but the selection: the glyphs, the decorations and the hidden hover outlines.

Parameters:

  • plotter (Plotter) –

    The plotter the host scene is drawn in.

  • host (GlyphHost) –

    The scene the glyphs sit on.

  • view (GlyphView | None) –

    What to draw, without a selection; None removes every glyph actor.

  • key (tuple[object, ...]) –

    What the actors are built for, recorded as the drawn key.

  • present (set[str]) –

    The actor names the plotter holds.

Source code in src/femforge/viz/glyphs.py
def draw_base(
    self, plotter: pv.Plotter, host: GlyphHost, view: GlyphView | None, key: tuple[object, ...], present: set[str]
) -> None:  # pragma: no cover - needs pyvista (viz extra) + a VTK render context; proven by the gated glyph tests
    """Draw everything but the selection: the glyphs, the decorations and the hidden hover outlines.

    Args:
        plotter: The plotter the host scene is drawn in.
        host: The scene the glyphs sit on.
        view: What to draw, without a selection; None removes every glyph actor.
        key: What the actors are built for, recorded as the drawn key.
        present: The actor names the plotter holds.
    """

    for name in sorted(name for name in present if name.startswith(GLYPH_PREFIX)):
        _ = plotter.remove_actor(name, render=False)  # pyright: ignore[reportUnknownMemberType, reportArgumentType]  # pyvista removes by actor name, and its _Wrapped stub loses `self`

    self.drawn = key
    self.names = frozenset()
    self.chosen = None
    self.chosen_names = frozenset()
    self.shown = ([], {})
    self.label_spots = np.zeros((0, 3))
    self.label_texts = ()
    self.hover_actors = {}

    if view is None:
        return

    moved, cells = self.moved_glyphs(host, view)
    self.shown = (moved, cells)
    placement: GlyphPlacement = self.placement(host)
    built: list[GlyphDraw] = [*glyph_actors(moved, cells, placement, view), *self.decorations(host, view)]

    draws: list[GlyphDraw] = [draw for draw in built if draw.mesh.n_points]
    labelled: list[GlyphDraw] = [draw for draw in draws if draw.labels]
    merged: list[GlyphDraw] = [draw for draw in draws if not draw.labels]

    if labelled:
        import pyvista as pv

        spots: FloatArray = np.concatenate([np.asarray(draw.mesh.points, dtype=np.float64) for draw in labelled])
        texts: tuple[str, ...] = tuple(text for draw in labelled for text in draw.labels)
        merged.append(GlyphDraw(GlyphActor.LABELS, pv.PolyData(spots), labels=texts, font_size=labelled[0].font_size))
        self.label_spots = spots
        self.label_texts = texts

    for draw in merged:
        if draw.overlay:
            _ = plotter.add_actor(_overlay(draw), name=str(draw.actor), reset_camera=False, render=False)  # pyright: ignore[reportUnknownMemberType, reportArgumentType]  # pyvista adds any prop by name, and its _Wrapped stub loses `self`
            continue

        if draw.labels:
            _ = plotter.add_point_labels(  # pyright: ignore[reportUnknownMemberType]
                np.asarray(draw.mesh.points, dtype=np.float64),
                list(draw.labels),
                font_size=draw.font_size,
                text_color=GLYPH_FILL,
                shape_color=GLYPH_HALO,
                shape_opacity=LABEL_OPACITY,
                show_points=False,
                always_visible=True,
                reset_camera=False,
                render=False,
                name=str(draw.actor),
            )
            continue

        added = plotter.add_mesh(  # pyright: ignore[reportUnknownMemberType]
            draw.mesh,
            color=draw.color,
            opacity=draw.opacity,
            line_width=draw.line_width,
            culling=draw.culling,
            show_scalar_bar=False,
            reset_camera=False,
            render=False,
            name=str(draw.actor),
        )
        forward(added, draw.layer)

    for ref in self.refs(host):
        hover: GlyphDraw | None = self.hover_draw(ref, host, view)
        if hover is None or not hover.mesh.n_points:
            continue

        accent: pv.PolyData | None = self.accent_glyphs(ref.id, moved, cells, placement, view)
        if accent is not None:
            hover = replace(hover, mesh=_merged([hover.mesh, accent]), layer=Layer.HOVER)

        actor = plotter.add_mesh(  # pyright: ignore[reportUnknownMemberType]
            hover.mesh,
            color=hover.color,
            opacity=hover.opacity,
            line_width=hover.line_width,
            show_scalar_bar=False,
            reset_camera=False,
            render=False,
            name=hover.actor,
        )
        actor.SetVisibility(False)
        forward(actor, hover.layer)

        self.hover_actors[ref.id] = actor

    hovers: list[str] = [f"{GlyphActor.HOVER}{ref_id}" for ref_id in self.hover_actors]
    self.names = frozenset([*(f"{draw.actor}{LABELS_SUFFIX}" if draw.labels else str(draw.actor) for draw in merged), *hovers])
    log.bind(run_id=self.run_id, actors=sorted(self.names), glyphs=len(self.glyphs)).debug("Glyphs drawn.")

draw_selection

draw_selection(plotter: Plotter, host: GlyphHost, view: GlyphView | None) -> None

Swap only the selection actors for those of the selected entity, so a new selection never rebuilds the rest of the layer.

Parameters:

  • plotter (Plotter) –

    The plotter the host scene is drawn in.

  • host (GlyphHost) –

    The scene the glyphs sit on.

  • view (GlyphView | None) –

    What to draw; its selected names the entity to accent.

Source code in src/femforge/viz/glyphs.py
def draw_selection(
    self, plotter: pv.Plotter, host: GlyphHost, view: GlyphView | None
) -> None:  # pragma: no cover - needs pyvista (viz extra) + a VTK render context; proven by the gated glyph tests
    """Swap only the selection actors for those of the selected entity, so a new selection never rebuilds the rest of the layer.

    Args:
        plotter: The plotter the host scene is drawn in.
        host: The scene the glyphs sit on.
        view: What to draw; its ``selected`` names the entity to accent.
    """
    selected: str | None = view.selected if view is not None else None
    key: tuple[object, ...] = (self.drawn, selected)
    present: set[str] = set(cast("Mapping[str, object]", plotter.renderer.actors).keys())

    if key == self.chosen and self.chosen_names <= present:
        return

    for name in sorted(self.chosen_names & present):
        _ = plotter.remove_actor(name, render=False)  # pyright: ignore[reportUnknownMemberType, reportArgumentType]  # pyvista removes by actor name, and its _Wrapped stub loses `self`

    self.chosen = key
    self.chosen_names = frozenset()

    if view is None or selected is None:
        return

    moved, cells = self.shown
    placement: GlyphPlacement = self.placement(host)
    draws: list[GlyphDraw] = self.selection(host, view)
    accented: pv.PolyData | None = self.accent_glyphs(selected, moved, cells, placement, view)
    if accented is not None:
        draws.append(GlyphDraw(GlyphActor.SELECTION_GLYPHS, accented, color=view.accent, line_width=MARK_LINE_PX * view.scale, layer=Layer.SELECTION))

    for draw in (draw for draw in draws if draw.mesh.n_points):
        added = plotter.add_mesh(  # pyright: ignore[reportUnknownMemberType]
            draw.mesh,
            color=draw.color,
            opacity=draw.opacity,
            line_width=draw.line_width,
            show_scalar_bar=False,
            reset_camera=False,
            render=False,
            name=str(draw.actor),
        )
        forward(added, draw.layer)
        self.chosen_names = self.chosen_names | {str(draw.actor)}

shape

shape(host: GlyphHost, kind: str, name: str, feature_angle: float = 0.0) -> PolyData | None

A copy of a body's surface or feature outline, extracted once while the host, expansion and warp stay.

Parameters:

  • host (GlyphHost) –

    The scene whose blocks hold the body.

  • kind (str) –

    surface for the outer surface, outline for the feature edges.

  • name (str) –

    The body's block name.

  • feature_angle (float, default: 0.0 ) –

    The crease angle of an outline, in degrees.

Source code in src/femforge/viz/glyphs.py
def shape(self, host: GlyphHost, kind: str, name: str, feature_angle: float = 0.0) -> pv.PolyData | None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """A copy of a body's surface or feature outline, extracted once while the host, expansion and warp stay.

    Args:
        host: The scene whose blocks hold the body.
        kind: ``surface`` for the outer surface, ``outline`` for the feature edges.
        name: The body's block name.
        feature_angle: The crease angle of an outline, in degrees.
    """
    import pyvista as pv

    key: tuple[str, str, float] = (kind, name, feature_angle)
    if key not in self.shapes:
        block = cast("pv.DataSet", host.blocks[name])
        if kind == "outline":
            found: pv.PolyData | None = feature_outline(pv.MultiBlock([block]), feature_angle)
        else:
            found = cast("pv.PolyData", block.extract_surface(algorithm=None))
            found.clear_data()

        if found is None:
            return None

        self.shapes[key] = found

    return self.shapes[key].copy()

refs

refs(host: GlyphHost) -> list[EntityRef]

Every body host draws and every boundary of the run.

Source code in src/femforge/viz/glyphs.py
def refs(self, host: GlyphHost) -> list[EntityRef]:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """Every body ``host`` draws and every boundary of the run."""
    bodies: list[EntityRef] = [EntityRef(kind=EntityKind.BODY, name=name) for name in host.blocks.keys()]

    return [*bodies, *(EntityRef(kind=EntityKind.BOUNDARY, name=boundary.name) for boundary in self.boundaries)]

hover_draw

hover_draw(ref: EntityRef, host: GlyphHost, view: GlyphView) -> GlyphDraw | None

The outline ref shows while its row is hovered: a body's feature edges, a boundary's lines or rim; None when it has no cells.

Parameters:

  • ref (EntityRef) –

    The body or boundary to outline.

  • host (GlyphHost) –

    The scene the outline sits on, whose warp it follows.

  • view (GlyphView) –

    The view whose hover color and pixel scale it takes.

Source code in src/femforge/viz/glyphs.py
def hover_draw(self, ref: EntityRef, host: GlyphHost, view: GlyphView) -> GlyphDraw | None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The outline ``ref`` shows while its row is hovered: a body's feature edges, a boundary's lines or rim; None when it has no cells.

    Args:
        ref: The body or boundary to outline.
        host: The scene the outline sits on, whose warp it follows.
        view: The view whose hover color and pixel scale it takes.
    """
    import pyvista as pv

    placement: GlyphPlacement = self.placement(host)
    lift: float = 2.0 * TINT_LIFT * placement.diagonal
    name: str = f"{GlyphActor.HOVER}{ref.id}"
    width: float = view.edges.highlight_width * view.scale

    if ref.kind is EntityKind.BODY:
        if ref.name not in host.blocks.keys():
            return None

        edges: pv.PolyData | None = self.shape(host, "outline", ref.name, view.edges.feature_angle)
        if edges is None:
            return None

        if placement.flat and not placement.revolved and not placement.extruded:
            edges.points = np.asarray(edges.points, dtype=np.float64) + np.array([0.0, 0.0, lift])

        return GlyphDraw(name, edges, color=view.hover, line_width=width)

    cells: pv.DataSet | None = self.group_cells(ref, host)
    if cells is None:
        return None

    if host.warped is not None:
        field, scale = host.warped
        # A boundary without a condition comes from the plain mesh, so it takes the solved displacement from the bodies around it.
        carrying: pv.DataSet = cells if field in cells.point_data else cast("pv.DataSet", cells.sample(host.section_blocks.combine()))
        cells = warped(carrying, field, scale) if field in carrying.point_data else cells

    swept: Surface | None = placement.swept_face(_segments(cells)) if placement.flat else None
    if swept is not None:
        return GlyphDraw(name, _surface(swept), color=view.hover, opacity=HOVER_OPACITY, layer=Layer.HOVER)

    if placement.flat:
        segments: FloatArray = _segments(cells) + np.array([0.0, 0.0, lift])
        copies: list[FloatArray] = [copy.reshape(-1, 2, 3) for copy in placement.copies(segments.reshape(-1, 3))]

        return GlyphDraw(name, _polylines(np.concatenate(copies)), color=view.hover, line_width=width)

    # A group's boundary elements come with mixed windings, which the feature filter reads as folds between neighbours; a 3D rim stays on the surface, where VTK draws lines over coincident faces.
    surface: pv.PolyData = cast("pv.PolyData", cells.extract_surface(algorithm=None))
    faced: bool = surface.GetNumberOfPolys() > 0
    wound: pv.PolyData = cast("pv.PolyData", surface.compute_normals(cell_normals=True, point_normals=False, consistent_normals=True, split_vertices=False)) if faced else surface
    rim: pv.PolyData | None = feature_outline(pv.MultiBlock([wound]))

    return GlyphDraw(name, rim, color=view.hover, line_width=width) if rim is not None else None

moved_glyphs

moved_glyphs(host: GlyphHost, view: GlyphView) -> tuple[list[Glyph], dict[str, DataSet]]

The shown glyphs with their anchors moved with host's warp, and the warped cells of each glyph's group by entity id.

Source code in src/femforge/viz/glyphs.py
def moved_glyphs(self, host: GlyphHost, view: GlyphView) -> tuple[list[Glyph], dict[str, pv.DataSet]]:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The shown glyphs with their anchors moved with ``host``'s warp, and the warped cells of each glyph's group by entity id."""
    shown: list[Glyph] = [glyph for glyph in self.glyphs if glyph.kind in view.kinds and glyph.ref.id not in view.hidden]
    cells: dict[str, pv.DataSet] = {}
    moved: list[Glyph] = []

    for glyph in shown:
        found: pv.DataSet | None = self.group_cells(glyph.ref, host)

        if found is None:
            moved.append(glyph)
            continue

        shift_x, shift_y, shift_z = cast("list[float]", _mean_shift(found, host.warped).tolist())
        anchor: Vec3 = glyph.anchor + Vec3(shift_x, shift_y, shift_z)
        moved.append(glyph.model_copy(update={"anchor": anchor}))
        warp: tuple[str, float] | None = host.warped
        displaced: bool = warp is not None and (warp[0] in found.point_data or warp[0] in found.cell_data)
        cells[glyph.ref.id] = warped(found, *warp) if warp is not None and displaced else found

    return moved, cells

accent_glyphs staticmethod

accent_glyphs(ref_id: str, glyphs: Sequence[Glyph], cells: Mapping[str, DataSet], placement: GlyphPlacement, view: GlyphView) -> PolyData | None

The arrows and pins of one entity's glyphs, which a highlight redraws in its color; None when the entity shows none.

Parameters:

  • ref_id (str) –

    The entity id whose glyphs to take.

  • glyphs (Sequence[Glyph]) –

    The shown glyphs, anchors already moved with the warp.

  • cells (Mapping[str, DataSet]) –

    The warped cells of each glyph's group by entity id.

  • placement (GlyphPlacement) –

    How the solve frame lands in the displayed scene.

  • view (GlyphView) –

    How large the glyphs draw.

Source code in src/femforge/viz/glyphs.py
@staticmethod
def accent_glyphs(
    ref_id: str, glyphs: Sequence[Glyph], cells: Mapping[str, pv.DataSet], placement: GlyphPlacement, view: GlyphView
) -> pv.PolyData | None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The arrows and pins of one entity's glyphs, which a highlight redraws in its color; None when the entity shows none.

    Args:
        ref_id: The entity id whose glyphs to take.
        glyphs: The shown glyphs, anchors already moved with the warp.
        cells: The warped cells of each glyph's group by entity id.
        placement: How the solve frame lands in the displayed scene.
        view: How large the glyphs draw.
    """
    own: list[Glyph] = [glyph for glyph in glyphs if glyph.ref.id == ref_id]
    pieces: list[pv.PolyData] = [draw.mesh for draw in glyph_actors(own, cells, placement, view) if draw.actor in (GlyphActor.ARROWS, GlyphActor.MARKS)] if own else []

    return _merged(pieces) if pieces else None

selection

selection(host: GlyphHost, view: GlyphView) -> list[GlyphDraw]

The accent silhouette and fill of the selected body, or the accent lines or cells of the selected boundary.

Source code in src/femforge/viz/glyphs.py
def selection(self, host: GlyphHost, view: GlyphView) -> list[GlyphDraw]:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The accent silhouette and fill of the selected body, or the accent lines or cells of the selected boundary."""
    placement: GlyphPlacement = self.placement(host)
    lift: FloatArray = np.array([0.0, 0.0, TINT_LIFT * placement.diagonal])
    draws: list[GlyphDraw] = []

    def segments_mesh(segments: FloatArray) -> pv.PolyData:
        copies: list[FloatArray] = [copy.reshape(-1, 2, 3) for copy in placement.copies(segments.reshape(-1, 3))]

        return _polylines(np.concatenate(copies))

    ref: EntityRef | None = EntityRef.parse(view.selected) if view.selected else None

    if ref is not None and ref.kind is EntityKind.BODY and ref.name in host.blocks.keys():
        edges: pv.PolyData | None = self.shape(host, "outline", ref.name, view.edges.feature_angle)
        raise_by: FloatArray = 2.0 * lift if placement.flat and not placement.revolved and not placement.extruded else np.zeros(3)

        if edges is not None:
            edges.points = np.asarray(edges.points, dtype=np.float64) + raise_by
            draws.append(GlyphDraw(GlyphActor.SELECTION, edges, color=view.accent, line_width=SILHOUETTE_LINE_SHARE * view.edges.highlight_width * view.scale))

        fill: pv.PolyData | None = self.shape(host, "surface", ref.name) if ref.name not in host.spec.hidden_bodies else None
        if fill is not None:
            fill.points = np.asarray(fill.points, dtype=np.float64) + raise_by
            draws.append(GlyphDraw(GlyphActor.SELECTION_FILL, fill, color=view.accent, opacity=SELECTION_TINT, layer=Layer.SELECTION))
    elif ref is not None and ref.kind is EntityKind.BOUNDARY:
        cells: pv.DataSet | None = self.group_cells(ref, host)

        if cells is not None and host.warped is not None and host.warped[0] in cells.point_data:
            cells = warped(cells, *host.warped)

        swept: Surface | None = placement.swept_face(_segments(cells)) if cells is not None and placement.flat else None

        if swept is not None:
            draws.append(GlyphDraw(GlyphActor.SELECTION_FILL, _surface(swept), color=view.accent, opacity=SELECTION_OPACITY, layer=Layer.SELECTION))
        elif cells is not None and placement.flat:
            width: float = SELECTION_LINE_SHARE * view.edges.highlight_width * view.scale
            draws.append(GlyphDraw(GlyphActor.SELECTION, segments_mesh(_segments(cells) + 2.0 * lift), color=view.accent, line_width=width))
        elif cells is not None:
            surface: pv.PolyData = cast("pv.PolyData", cells.extract_surface(algorithm=None))
            surface.clear_data()
            draws.append(GlyphDraw(GlyphActor.SELECTION_FILL, surface, color=view.accent, opacity=SELECTION_OPACITY, layer=Layer.SELECTION))

    return draws

decorations

decorations(host: GlyphHost, view: GlyphView) -> list[GlyphDraw]

The section outline with its plane, and the authored ghost with its hull.

Source code in src/femforge/viz/glyphs.py
def decorations(self, host: GlyphHost, view: GlyphView) -> list[GlyphDraw]:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The section outline with its plane, and the authored ghost with its hull."""
    import pyvista as pv

    placement: GlyphPlacement = self.placement(host)
    diagonal: float = placement.diagonal
    lift: FloatArray = np.array([0.0, 0.0, TINT_LIFT * diagonal])
    draws: list[GlyphDraw] = []
    plane = self.frame.plane

    def segments_mesh(segments: FloatArray) -> pv.PolyData:
        copies: list[FloatArray] = [copy.reshape(-1, 2, 3) for copy in placement.copies(segments.reshape(-1, 3))]

        return _polylines(np.concatenate(copies))

    if plane is not None and view.outline:
        loops: pv.PolyData | None = feature_outline(self.deformed_section(host))

        # VTK.wasm lets a revolved display's translucent bodies hide or stipple the lines behind and along them, so there the outline draws on top in both renderers.
        def stroked(actor: GlyphActor, lines: pv.PolyData) -> GlyphDraw:
            return GlyphDraw(actor, lines, color=view.ink, line_width=view.edges.width * view.scale, overlay=placement.revolved)

        if loops is not None:
            draws.append(stroked(GlyphActor.OUTLINE, segments_mesh(_segments(loops) + lift)))

        if placement.revolved:
            bounds: Sequence[float] = tuple(host.section_blocks.bounds)
            square: FloatArray = np.array([[bounds[0], bounds[2], 0.0], [bounds[1], bounds[2], 0.0], [bounds[1], bounds[3], 0.0], [bounds[0], bounds[3], 0.0]])
            quad: pv.PolyData = pv.PolyData(placement.placed(square), faces=np.array([4, 0, 1, 2, 3]))
            draws.append(GlyphDraw(GlyphActor.PLANE, quad, color=GLYPH_TINT, opacity=PLANE_OPACITY))

    if plane is not None and view.ghost and self.authored is not None:
        ghost: pv.PolyData = self.authored.copy()
        ghost.clear_data()
        ghost.points = placement.placed(np.asarray(ghost.points, dtype=np.float64))
        draws.append(GlyphDraw(GlyphActor.GHOST, ghost, color=GLYPH_TINT, opacity=GHOST_OPACITY))
        silhouette: pv.PolyData = ghost.extract_feature_edges(boundary_edges=True, feature_edges=True, manifold_edges=False, non_manifold_edges=False, feature_angle=30.0)
        hull: FloatArray = self.hull(host, placement)
        pieces: list[FloatArray] = [_segments(silhouette)] if silhouette.n_cells else []
        pieces.append(dashed(hull, DASH_SHARE * diagonal))
        draws.append(GlyphDraw(GlyphActor.HULL, _polylines(np.concatenate(pieces)), color=view.ink, line_width=MARK_LINE_PX * view.scale))

    return draws

deformed_section

deformed_section(host: GlyphHost) -> MultiBlock

The section blocks of host displaced by its warp, so an outline follows the body the scene shows; as solved without a warp.

Source code in src/femforge/viz/glyphs.py
def deformed_section(self, host: GlyphHost) -> pv.MultiBlock:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The section blocks of ``host`` displaced by its warp, so an outline follows the body the scene shows; as solved without a warp."""
    import pyvista as pv

    warp: tuple[str, float] | None = host.warped

    if warp is None:
        return host.section_blocks

    moved: pv.MultiBlock = pv.MultiBlock()

    for name in (str(key) for key in host.section_blocks.keys()):
        block: pv.DataSet = cast("pv.DataSet", host.section_blocks[name])
        displaced: bool = warp[0] in block.point_data or warp[0] in block.cell_data
        moved.append(warped(block, *warp) if displaced else block, name=name)

    return moved

hull

hull(host: GlyphHost, placement: GlyphPlacement) -> FloatArray

The (m, 2, 3) edges the ghost is checked against: the section extruded through the prism depth, or revolved about the axis.

Source code in src/femforge/viz/glyphs.py
def hull(self, host: GlyphHost, placement: GlyphPlacement) -> FloatArray:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The ``(m, 2, 3)`` edges the ghost is checked against: the section extruded through the prism depth, or revolved about the axis."""

    loops: pv.PolyData | None = feature_outline(host.section_blocks)

    if loops is None:
        return np.zeros((0, 2, 3))

    if self.frame.revolves:
        basis: Basis = placement.basis if placement.revolved and placement.basis is not None else Basis.SOLVE
        points: FloatArray = np.asarray(loops.points, dtype=np.float64)
        pairs: IntArray = np.asarray(loops.lines, dtype=np.int64).reshape(-1, 3)[:, 1:]  # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType]  # pyvista types the cell array loosely
        swept: pv.PolyData = _surface(swept_lines(points, pairs, basis, segments=HULL_SEGMENTS))
        rings: pv.PolyData = swept.extract_feature_edges(boundary_edges=True, feature_edges=True, manifold_edges=False, non_manifold_edges=False, feature_angle=30.0)
        outline: FloatArray = points[pairs].reshape(-1, 3)
        meridians: list[FloatArray] = [(np.asarray(basis.origin) + basis.rotate(outline, math.radians(angle))).reshape(-1, 2, 3) for angle in revolve_angles(FULL_SWEEP)]

        return np.concatenate([_segments(rings), *meridians])

    depth: float = prism_depth(self.frame)
    surface: pv.PolyData = cast("pv.PolyData", host.section_blocks.extract_surface(algorithm=None))
    surface.clear_data()
    surface.points = np.asarray(surface.points, dtype=np.float64) - [0.0, 0.0, depth / 2.0]
    prism = cast("pv.PolyData", surface.extrude((0.0, 0.0, depth), capping=True))  # pyright: ignore[reportUnknownMemberType]  # pyvista leaves the extrusion untyped
    edges: pv.PolyData = prism.extract_feature_edges(boundary_edges=True, feature_edges=True, manifold_edges=False, non_manifold_edges=False, feature_angle=30.0)

    return _segments(edges)

GroupScene

GroupScene(groups: MeshGroups, *, bodies: Bodies, boundaries: Boundaries, frame: Frame, run_id: str)

A run without fields drawn from its Elmer mesh: every body plain grey, with its glyph layer over them.

Parameters:

  • groups (MeshGroups) –

    The run's Elmer mesh by group.

  • bodies (Bodies) –

    The run's bodies.

  • boundaries (Boundaries) –

    The run's boundaries.

  • frame (Frame) –

    The frame the run solved in.

  • run_id (str) –

    The run bundle's name.

Methods:

  • from_run –

    The mesh-only scene of run with its glyph layer; None when its Elmer mesh is gone.

  • group_cells –

    The cells of ref from the Elmer mesh.

  • render –

    Draw every body shaded in its body color, a solid run's feature edges in black over them, then the glyph layer.

Source code in src/femforge/viz/glyphs.py
def __init__(
    self, groups: MeshGroups, *, bodies: Bodies, boundaries: Boundaries, frame: Frame, run_id: str
) -> None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """Split the mesh into one block per named body.

    Args:
        groups: The run's Elmer mesh by group.
        bodies: The run's bodies.
        boundaries: The run's boundaries.
        frame: The frame the run solved in.
        run_id: The run bundle's name.
    """
    import pyvista as pv

    self.groups: MeshGroups = groups
    self.bodies: Bodies = bodies
    self.boundaries: Boundaries = boundaries
    self.frame: Frame = frame
    self.run_id: str = run_id
    self.basis: Basis | None = None
    self.expanded: tuple[Expansion, float] = (Expansion.SECTION, FULL_SWEEP)
    self.warped: tuple[str, float] | None = None
    self.spec: DisplaySpec = DisplaySpec()
    self.glyphs: GlyphLayer | None = None
    self.glyph_view: GlyphView | None = None
    blocks: pv.MultiBlock = pv.MultiBlock()

    for body in bodies:
        cells: pv.UnstructuredGrid = groups.body(body)

        if not cells.n_cells:
            continue

        if frame.model_dim == 2:
            points: FloatArray = np.asarray(cells.points, dtype=np.float64)
            points[:, 2] = 0.0
            cells.points = points

        blocks.append(cells, name=body.name)

    self.section_blocks: pv.MultiBlock = blocks
    self.blocks: pv.MultiBlock = blocks
    self.surfaces: tuple[pv.MultiBlock, dict[str, pv.PolyData]] | None = None
    self.outline: tuple[pv.MultiBlock, float, pv.PolyData | None] | None = None

from_run classmethod

from_run(run: Run) -> GroupScene | None

The mesh-only scene of run with its glyph layer; None when its Elmer mesh is gone.

Source code in src/femforge/viz/glyphs.py
@classmethod
def from_run(cls, run: Run) -> GroupScene | None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The mesh-only scene of ``run`` with its glyph layer; None when its Elmer mesh is gone."""
    groups: MeshGroups | None = run.mesh_groups()

    if groups is None:
        return None

    layer: GlyphLayer = GlyphLayer.from_run(run)
    scene: GroupScene = cls(groups, bodies=run.bodies, boundaries=run.boundaries, frame=layer.frame, run_id=run.path.name)
    scene.glyphs = layer

    return scene

group_cells

group_cells(ref: EntityRef) -> DataSet | None

The cells of ref from the Elmer mesh.

Source code in src/femforge/viz/glyphs.py
def group_cells(self, ref: EntityRef) -> pv.DataSet | None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The cells of ``ref`` from the Elmer mesh."""
    if ref.kind is EntityKind.BODY:
        return cast("pv.DataSet", self.section_blocks[ref.name]) if ref.name in self.section_blocks.keys() else None

    boundary: Boundary | None = self.boundaries.get(ref.name)

    if boundary is None:
        return None

    cells: pv.UnstructuredGrid = self.groups.boundary(boundary)

    if self.frame.model_dim == 2:
        points: FloatArray = np.asarray(cells.points, dtype=np.float64)
        points[:, 2] = 0.0
        cells.points = points

    return cells

render

render(plotter: Plotter) -> None

Draw every body shaded in its body color, a solid run's feature edges in black over them, then the glyph layer.

Source code in src/femforge/viz/glyphs.py
def render(self, plotter: pv.Plotter) -> None:  # pragma: no cover - needs pyvista (viz extra) + a VTK render context; proven by the gated glyph tests
    """Draw every body shaded in its body color, a solid run's feature edges in black over them, then the glyph layer."""
    view: GlyphView = self.glyph_view or GlyphView()
    shading: Shading = view.shading
    # Surfaces and outline are extracted once per blocks object: a 3D mesh of millions of cells takes seconds to extract.
    if self.surfaces is None or self.surfaces[0] is not self.blocks:
        extracted: dict[str, pv.PolyData] = {}
        for name in (str(key) for key in self.blocks.keys()):
            surface: pv.PolyData = cast("pv.PolyData", cast("pv.DataSet", self.blocks[name]).extract_surface(algorithm=None))
            surface.clear_data()
            extracted[name] = surface

        self.surfaces = (self.blocks, extracted)

    for index, (name, surface) in enumerate(self.surfaces[1].items()):
        _ = plotter.add_mesh(  # pyright: ignore[reportUnknownMemberType]
            surface,
            color=body_color(index),
            smooth_shading=shading.smooth,
            split_sharp_edges=shading.smooth,
            feature_angle=shading.split_angle,
            ambient=shading.ambient,
            specular=shading.specular,
            show_scalar_bar=False,
            reset_camera=False,
            name=SceneActor.STYLED.of(name),
        )

    if self.frame.model_dim == 3 and (self.outline is None or self.outline[0] is not self.blocks or self.outline[1] != view.edges.feature_angle):
        self.outline = (self.blocks, view.edges.feature_angle, feature_outline(self.blocks, view.edges.feature_angle))

    edges: pv.PolyData | None = self.outline[2] if self.frame.model_dim == 3 and self.outline is not None else None

    if edges is not None:
        outline = plotter.add_mesh(edges, color="black", line_width=view.edges.width * view.scale, reset_camera=False, name=str(SceneActor.OUTLINE))  # pyright: ignore[reportUnknownMemberType]
        forward(outline, Layer.EDGE)

    if self.glyphs is not None:
        self.glyphs.update(plotter, self, self.glyph_view)

select_flux_density_array

select_flux_density_array(names: Iterable[str]) -> str

Pick the B array from a VTU's array names: the nodal form first (no cell→point projection needed), then the elemental "... e", then any name containing the phrase (case-insensitive).

Raises KeyError naming the available arrays if none matches.

Source code in src/femforge/viz/field_lines.py
def select_flux_density_array(names: Iterable[str]) -> str:
    """
    Pick the B array from a VTU's array names: the nodal form first (no cell→point projection needed), then the elemental ``"... e"``, then any name containing the phrase (case-insensitive).

    Raises [`KeyError`][] naming the available arrays if none matches.
    """
    by_lower: dict[str, str] = {name.lower(): name for name in names}
    if FLUX_DENSITY in by_lower:
        return by_lower[FLUX_DENSITY]
    if f"{FLUX_DENSITY} e" in by_lower:
        return by_lower[f"{FLUX_DENSITY} e"]
    for lower, original in by_lower.items():
        if FLUX_DENSITY in lower:
            return original
    raise KeyError(f"no '{FLUX_DENSITY}' array in {sorted(by_lower.values())}; was MagnetoDynamicsCalcFields run?")

seed_points

seed_points(bounds: Bounds, options: FieldLineOptions) -> list[Point3]

The (N, 3) streamline seed coordinates for the domain bounds and options (pure Python — unit-testable without a render context).

The grid is centered and spans seed_fraction of each axis, keeping seeds out of the outer air shell where B ≈ 0.

Source code in src/femforge/viz/field_lines.py
def seed_points(bounds: Bounds, options: FieldLineOptions) -> list[Point3]:
    """
    The ``(N, 3)`` streamline seed coordinates for the domain ``bounds`` and ``options`` (pure Python — unit-testable without a render context).

    The grid is centered and spans ``seed_fraction`` of each axis, keeping seeds out of the outer air shell where B ≈ 0.
    """
    xmin, xmax, ymin, ymax, zmin, zmax = bounds

    cx, cy, cz = (xmin + xmax) / 2, (ymin + ymax) / 2, (zmin + zmax) / 2
    f: float = options.seed_fraction
    hx, hy, hz = (xmax - xmin) * f / 2, (ymax - ymin) * f / 2, (zmax - zmin) * f / 2

    n: int = options.line_count
    xs: list[float] = _seed_axis(cx, hx, n)
    ys: list[float] = _seed_axis(cy, hy, n)
    zs: list[float] = _seed_axis(cz, hz, n)

    dims: float = 3.0
    match options.seed_placement:
        case SeedPlacement.GAP_LINE:
            dims = 1.0
        case SeedPlacement.CENTER_PLANE:
            dims = 2.0
        case SeedPlacement.VOLUME:
            dims = 3.0

    # Reduce n to keep the n constant regardless of dim
    n = int(n ** (1.0 / dims))  # pyright: ignore[reportAny]
    if options.seed_grid:
        match options.seed_placement:
            case SeedPlacement.GAP_LINE:
                return [(x, cy, cz) for x in xs]
            case SeedPlacement.CENTER_PLANE:
                return [(x, y, cz) for y in ys for x in xs]
            case SeedPlacement.VOLUME:
                return [(x, y, z) for z in zs for y in ys for x in xs]
    else:
        match options.seed_placement:
            case SeedPlacement.GAP_LINE:
                return [(random.uniform(xmin, xmax), cy, cz) for _ in range(n)]
            case SeedPlacement.CENTER_PLANE:
                return [(random.uniform(xmin, xmax), random.uniform(ymin, ymax), cz) for _ in range(n * n)]
            case SeedPlacement.VOLUME:
                return [(random.uniform(xmin, xmax), random.uniform(ymin, ymax), random.uniform(zmin, zmax)) for _ in range(n * n * n)]

build_streamlines

build_streamlines(dataset: DataSet, b_name: str, options: FieldLineOptions | None = None) -> StreamlineActors

Seed and integrate |B| streamlines through a dataset that already carries B as point data, without touching a plotter.

Parameters:

  • dataset (DataSet) –

    The dataset carrying B on its points.

  • b_name (str) –

    The point array the lines follow.

  • options (FieldLineOptions | None, default: None ) –

    The field-line options; None takes the defaults.

Source code in src/femforge/viz/field_lines.py
def build_streamlines(
    dataset: pv.DataSet, b_name: str, options: FieldLineOptions | None = None
) -> StreamlineActors:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration tests
    """Seed and integrate |B| streamlines through a dataset that already carries B as **point** data, without touching a plotter.

    Args:
        dataset: The dataset carrying B on its points.
        b_name: The point array the lines follow.
        options: The field-line options; None takes the defaults.
    """
    import pyvista as pv

    opts: FieldLineOptions = options if options is not None else FieldLineOptions()
    bounds: Bounds = cast("Bounds", tuple(dataset.bounds))
    seeds: pv.PolyData = pv.PolyData(seed_points(bounds, opts))

    # Far from the magnets the air field is weak and near-uniform, so the arc length is bounded by a share of the domain diagonal to keep the picture framed on the magnets.
    xmin, xmax, ymin, ymax, zmin, zmax = bounds
    dx, dy, dz = xmax - xmin, ymax - ymin, zmax - zmin
    max_length: float = math.sqrt(dx * dx + dy * dy + dz * dz) * opts.max_length
    streamlines: pv.PolyData = cast(
        "pv.PolyData",
        dataset.streamlines_from_source(
            seeds,
            vectors=b_name,
            integration_direction="both",
            max_length=max_length,
            initial_step_length=opts.initial_step_length,
            min_step_length=opts.min_step_length,
            max_step_length=opts.max_step_length,
            interpolator_type=opts.interpolator.value,
        ),
    )
    streamlines = trim_reversals(streamlines)

    # Tubes when a radius is given, else raw poly-lines (cheaper, the right look for a dense field). pyvista's
    # geometry methods carry `**kwargs: Unknown`, so pin the typed return with a cast and silence the member report.
    tubed: pv.PolyData = (
        cast("pv.PolyData", streamlines.tube(radius=opts.tube_radius))  # pyright: ignore[reportUnknownMemberType]
        if opts.tube_radius is not None
        else streamlines
    )
    outline: pv.PolyData | None = cast("pv.PolyData", dataset.outline()) if opts.show_outline else None
    magnitudes: np.typing.NDArray[np.float64] = np.linalg.norm(np.asarray(dataset.point_data[b_name], dtype=np.float64).reshape(dataset.n_points, -1), axis=1)
    return StreamlineActors(streamlines=tubed, b_name=b_name, outline=outline, magnitudes=[magnitudes])

build_streamlines_from_vtu

build_streamlines_from_vtu(vtu_path: str | Path, options: FieldLineOptions | None = None) -> StreamlineActors

Read a solved case.vtu and integrate its B-field streamlines into a drawable StreamlineActors — no plotter touched, safe off the UI thread.

Source code in src/femforge/viz/field_lines.py
def build_streamlines_from_vtu(vtu_path: str | Path, options: FieldLineOptions | None = None) -> StreamlineActors:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """Read a solved ``case.vtu`` and integrate its B-field streamlines into a drawable [`StreamlineActors`][] — no plotter touched, safe off the UI thread."""
    import pyvista as pv

    opts: FieldLineOptions = options if options is not None else FieldLineOptions()
    grid: pv.UnstructuredGrid = cast("pv.UnstructuredGrid", pv.read(str(vtu_path)))

    sampled, b_name = prepare_streamline_source(grid, opts)
    return build_streamlines(sampled, b_name, opts)

build_swept_streamlines

build_swept_streamlines(section: DataSet, b_name: str, options: FieldLineOptions, basis: Basis | Prism, bounds: Bounds, *, seeds: NDArray[float64] | None = None) -> StreamlineActors

Field lines of a revolved or extruded section: seeded in the shown 3D frame, folded into the section, integrated there and carried back to each seed's angle or depth.

Parameters:

  • section (DataSet) –

    The solved section in the solve frame, carrying B on its points.

  • b_name (str) –

    The point array the lines follow.

  • options (FieldLineOptions) –

    The field-line options.

  • basis (Basis | Prism) –

    How the section folds out of the shown frame: a revolution's basis or an extrusion's prism.

  • bounds (Bounds) –

    The shown 3D bounds, which the seeds fill and the outline draws.

  • seeds (NDArray[float64] | None, default: None ) –

    (N, 3) authored seed points to use instead of seeding bounds.

Source code in src/femforge/viz/field_lines.py
def build_swept_streamlines(
    section: pv.DataSet,
    b_name: str,
    options: FieldLineOptions,
    basis: Basis | Prism,
    bounds: Bounds,
    *,
    seeds: np.typing.NDArray[np.float64] | None = None,
) -> StreamlineActors:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration tests
    """Field lines of a revolved or extruded section: seeded in the shown 3D frame, folded into the section, integrated there and carried back to each seed's angle or depth.

    Args:
        section: The solved section in the solve frame, carrying B on its points.
        b_name: The point array the lines follow.
        options: The field-line options.
        basis: How the section folds out of the shown frame: a revolution's basis or an extrusion's prism.
        bounds: The shown 3D bounds, which the seeds fill and the outline draws.
        seeds: ``(N, 3)`` authored seed points to use instead of seeding ``bounds``.
    """
    import pyvista as pv

    authored: np.typing.NDArray[np.float64] = seeds if seeds is not None else np.asarray(seed_points(bounds, options), dtype=np.float64)
    folded, theta = basis.fold(authored)

    xmin, xmax, ymin, ymax, zmin, zmax = cast("Bounds", tuple(section.bounds))
    max_length: float = math.sqrt((xmax - xmin) ** 2 + (ymax - ymin) ** 2 + (zmax - zmin) ** 2) * options.max_length
    traced: pv.PolyData = cast(
        "pv.PolyData",
        section.streamlines_from_source(
            pv.PolyData(folded),
            vectors=b_name,
            integration_direction="both",
            max_length=max_length,
            initial_step_length=options.initial_step_length,
            min_step_length=options.min_step_length,
            max_step_length=options.max_step_length,
            interpolator_type=options.interpolator.value,
        ),
    )
    lines: pv.PolyData = trim_reversals(traced)

    if lines.n_points:
        counts: np.typing.NDArray[np.int64] = np.diff(np.asarray(lines.line_offsets, dtype=np.int64))  # pyright: ignore[reportUnknownMemberType, reportUnknownArgumentType]  # pyvista types line_offsets loosely
        point_theta: np.typing.NDArray[np.float64] = np.repeat(theta[np.asarray(lines.cell_data[SEED_IDS], dtype=np.int64)], counts)
        lines.points = basis.place(np.asarray(lines.points, dtype=np.float64), point_theta)
        for name in lines.point_data.keys():
            lines.point_data[name] = basis.carry(np.asarray(lines.point_data[name]), point_theta)

    tubed: pv.PolyData = (
        cast("pv.PolyData", lines.tube(radius=options.tube_radius))  # pyright: ignore[reportUnknownMemberType]
        if options.tube_radius is not None and lines.n_points
        else lines
    )
    outline: pv.PolyData | None = cast("pv.PolyData", pv.Box(bounds).outline()) if options.show_outline else None  # pyright: ignore[reportUnknownMemberType]  # pyvista types Box bounds loosely
    magnitudes: np.typing.NDArray[np.float64] = np.linalg.norm(np.asarray(section.point_data[b_name], dtype=np.float64).reshape(section.n_points, -1), axis=1)

    return StreamlineActors(streamlines=tubed, b_name=b_name, outline=outline, magnitudes=[magnitudes])

prepare_streamline_source

prepare_streamline_source(grid: UnstructuredGrid, options: FieldLineOptions) -> tuple[DataSet, str]

Narrow a read grid to the integration region and put B on its points, returning the dataset and the B array name — the read-independent half of build_streamlines_from_vtu.

Source code in src/femforge/viz/field_lines.py
def prepare_streamline_source(grid: pv.UnstructuredGrid, options: FieldLineOptions) -> tuple[pv.DataSet, str]:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """Narrow a read grid to the integration region and put B on its points, returning the dataset and the B array name — the read-independent half of [`build_streamlines_from_vtu`][]."""
    # Viz toggle: confine integration to one region (e.g. air) by thresholding to that body BEFORE projecting B to
    # points. This kills the "spike" streamlines: the cell->point average then never mixes across the air<->magnet
    # interface, so air-side nodes don't inherit the magnets' huge magnetization-aligned B.
    if options.clip_to_region and options.region_array is not None and options.region_id is not None and options.region_array in grid.cell_data:
        rid: float = float(options.region_id)
        grid = cast("pv.UnstructuredGrid", grid.threshold([rid, rid], scalars=options.region_array, preference="cell"))  # pyright: ignore[reportUnknownMemberType]

    b_name: str = options.vectors if options.vectors is not None else select_flux_density_array(list(grid.array_names))
    # A true nodal B is integrated as-is; the elemental "... e" form (cell data) is projected to points here.
    sampled: pv.DataSet = cast("pv.DataSet", grid.cell_data_to_point_data() if b_name in grid.cell_data else grid)
    return (sampled, b_name)

draw_streamlines

draw_streamlines(actors: StreamlineActors, options: FieldLineOptions, plotter: Plotter) -> None

Draw a precomputed StreamlineActors into plotter without clearing or showing it, so it composes inside a Scene.

Parameters:

  • actors (StreamlineActors) –

    The integrated lines; an empty set removes any lines drawn before.

  • options (FieldLineOptions) –

    The field-line options that style them.

  • plotter (Plotter) –

    The plotter to draw into, on its own thread.

Source code in src/femforge/viz/field_lines.py
def draw_streamlines(
    actors: StreamlineActors, options: FieldLineOptions, plotter: pv.Plotter
) -> None:  # pragma: no cover - needs pyvista (viz extra) + a VTK render context; proven by the gated integration tests
    """Draw a precomputed [`StreamlineActors`][] into ``plotter`` without clearing or showing it, so it composes inside a [`Scene`][femforge.viz.scene.Scene].

    Args:
        actors: The integrated lines; an empty set removes any lines drawn before.
        options: The field-line options that style them.
        plotter: The plotter to draw into, on its own thread.
    """
    if actors.streamlines.n_points == 0:
        _ = plotter.remove_actor(str(StreamlineActor.LINES))  # pyright: ignore[reportUnknownMemberType, reportArgumentType]  # pyvista removes by actor name, and its _Wrapped stub loses `self`
        return

    register_paraview()

    # The scalar bar title avoids a literal "|" -- VTK's off-screen text renderer crashes on a pipe glyph.
    # opacity: a constant float, or an OpacityTransfer name; pyvista types it as a Literal a StrEnum can't satisfy
    # statically even though it's valid at runtime -- hence the reportArgumentType ignore.
    actor = plotter.add_mesh(  # pyright: ignore[reportUnknownMemberType]
        actors.streamlines,
        scalars=actors.b_name,
        cmap=options.colormap,
        flip_scalars=options.invert,
        clim=options.clim,
        log_scale=options.log_scale,
        opacity=options.opacity,  # pyright: ignore[reportArgumentType]
        line_width=options.line_width,
        lighting=False,
        show_scalar_bar=False,
        scalar_bar_args={"title": "B (T)"},
        label=f"streamlines ({options.seed_placement.value})",
        name=str(StreamlineActor.LINES),
    )
    if options.opacity_map is not None:
        ramp_alpha(actor.mapper.lookup_table, *options.opacity_map)

    if actors.outline is not None:
        plotter.add_mesh(actors.outline, color="gray", name=str(StreamlineActor.OUTLINE))  # pyright: ignore[reportUnknownMemberType]

render_streamlines

render_streamlines(dataset: DataSet, b_name: str, options: FieldLineOptions | None = None, *, off_screen: bool = False, screenshot: str | Path | None = None, plotter: Plotter | None = None) -> None

One-shot: build streamlines through dataset and draw them, in a plotter of its own when plotter is None.

Parameters:

  • dataset (DataSet) –

    The dataset carrying B on its points.

  • b_name (str) –

    The point array the lines follow.

  • options (FieldLineOptions | None, default: None ) –

    The field-line options; None takes the defaults.

  • off_screen (bool, default: False ) –

    Render without a window.

  • screenshot (str | Path | None, default: None ) –

    The PNG to write when rendering off screen.

  • plotter (Plotter | None, default: None ) –

    A live plotter to add the lines to instead of opening one.

Source code in src/femforge/viz/field_lines.py
def render_streamlines(
    dataset: pv.DataSet,
    b_name: str,
    options: FieldLineOptions | None = None,
    *,
    off_screen: bool = False,
    screenshot: str | Path | None = None,
    plotter: pv.Plotter | None = None,
) -> None:  # pragma: no cover - needs pyvista (viz extra) + a VTK render context; proven by the gated integration tests
    """One-shot: build streamlines through ``dataset`` and draw them, in a plotter of its own when ``plotter`` is None.

    Args:
        dataset: The dataset carrying B on its points.
        b_name: The point array the lines follow.
        options: The field-line options; None takes the defaults.
        off_screen: Render without a window.
        screenshot: The PNG to write when rendering off screen.
        plotter: A live plotter to add the lines to instead of opening one.
    """
    import pyvista as pv

    opts: FieldLineOptions = options if options is not None else FieldLineOptions()
    actors: StreamlineActors = build_streamlines(dataset, b_name, opts)

    own_plotter: bool = plotter is None
    if plotter is None:
        plotter = pv.Plotter(off_screen=off_screen)

    draw_streamlines(actors, opts, plotter)

    if own_plotter:
        screenshot_arg: str | bool = str(screenshot) if screenshot is not None else False
        plotter.show(screenshot=screenshot_arg)  # pyright: ignore[reportUnknownMemberType]

render_field_lines

render_field_lines(vtu_path: str | Path, options: FieldLineOptions | None = None, *, off_screen: bool = False, screenshot: str | Path | None = None, plotter: Plotter | None = None) -> None

Render the magnetic flux-density field lines from a solved case.vtu, headless to a PNG or in an interactive window.

Parameters:

  • vtu_path (str | Path) –

    The solved case.vtu.

  • options (FieldLineOptions | None, default: None ) –

    The field-line options; None takes the defaults.

  • off_screen (bool, default: False ) –

    Render without a window.

  • screenshot (str | Path | None, default: None ) –

    The PNG to write when rendering off screen.

  • plotter (Plotter | None, default: None ) –

    A live plotter to add the lines to instead of opening one.

Source code in src/femforge/viz/field_lines.py
def render_field_lines(
    vtu_path: str | Path,
    options: FieldLineOptions | None = None,
    *,
    off_screen: bool = False,
    screenshot: str | Path | None = None,
    plotter: pv.Plotter | None = None,
) -> None:  # pragma: no cover - needs pyvista (viz extra) + a VTK render context; proven by the gated integration test
    """Render the magnetic flux-density field lines from a solved ``case.vtu``, headless to a PNG or in an interactive window.

    Args:
        vtu_path: The solved ``case.vtu``.
        options: The field-line options; None takes the defaults.
        off_screen: Render without a window.
        screenshot: The PNG to write when rendering off screen.
        plotter: A live plotter to add the lines to instead of opening one.
    """
    import pyvista as pv

    opts: FieldLineOptions = options if options is not None else FieldLineOptions()
    actors: StreamlineActors = build_streamlines_from_vtu(vtu_path, opts)

    own_plotter: bool = plotter is None
    if plotter is None:
        plotter = pv.Plotter(off_screen=off_screen)

    draw_streamlines(actors, opts, plotter)

    if own_plotter:
        screenshot_arg: str | bool = str(screenshot) if screenshot is not None else False
        plotter.show(screenshot=screenshot_arg)  # pyright: ignore[reportUnknownMemberType]

field_infos

field_infos(point_arrays: Mapping[str, AnyArray], cell_arrays: Mapping[str, AnyArray], physics: Physics | None = None) -> list[FieldInfo]

Every displayable array of a VTU as a FieldInfo, sorted by display name; GeometryIds and tensors are left out.

Parameters:

  • point_arrays (Mapping[str, AnyArray]) –

    The VTU's point arrays by name.

  • cell_arrays (Mapping[str, AnyArray]) –

    The VTU's cell arrays by name.

  • physics (Physics | None, default: None ) –

    The physics the run solved, which names the unit of its potential; None leaves it unitless.

Source code in src/femforge/viz/field_display.py
def field_infos(point_arrays: Mapping[str, AnyArray], cell_arrays: Mapping[str, AnyArray], physics: Physics | None = None) -> list[FieldInfo]:
    """Every displayable array of a VTU as a [`FieldInfo`][], sorted by display name; ``GeometryIds`` and tensors are left out.

    Args:
        point_arrays: The VTU's point arrays by name.
        cell_arrays: The VTU's cell arrays by name.
        physics: The physics the run solved, which names the unit of its potential; None leaves it unitless.
    """
    infos: list[FieldInfo] = []
    for association, arrays in ((Association.POINT, point_arrays), (Association.CELL, cell_arrays)):
        for name, values in arrays.items():
            if name == GEOMETRY_IDS_ARRAY:
                continue

            array: AnyArray = np.asarray(values)
            shape: tuple[int, ...] = array.shape
            components: int = shape[-1] if array.ndim > 1 else 1

            if field_kind(name, components) is FieldKind.TENSOR:
                continue

            infos.append(
                FieldInfo(
                    name=name,
                    association=association,
                    components=components,
                    dtype=str(array.dtype),
                    unit=variable_unit(name, physics),
                    physics=physics,
                ),
            )

    return sorted(infos, key=lambda info: info.display_name)

line_vectors

line_vectors(fields: Sequence[FieldInfo], shown: str) -> str | None

The vector field the field lines follow: the shown one when it is a vector, else the flux density, else the first vector field; None for a run with none.

Parameters:

  • fields (Sequence[FieldInfo]) –

    The run's displayable fields, in picker order.

  • shown (str) –

    The name of the array the display colors by.

Source code in src/femforge/viz/field_display.py
def line_vectors(fields: Sequence[FieldInfo], shown: str) -> str | None:
    """The vector field the field lines follow: the shown one when it is a vector, else the flux density, else the first vector field; None for a run with none.

    Args:
        fields: The run's displayable fields, in picker order.
        shown: The name of the array the display colors by.
    """
    vectors: list[str] = [info.name for info in fields if info.kind is FieldKind.VECTOR]
    if shown in vectors:
        return shown

    if not vectors:
        return None

    try:
        return select_flux_density_array(vectors)
    except KeyError:
        return vectors[0]

default_display

default_display(run: Run) -> DisplaySpec

The display a run opens on: its stack's primary field, on the component its loads share, with field lines and opacity mapping for a flux or current.

Source code in src/femforge/viz/field_display.py
def default_display(run: Run) -> DisplaySpec:
    """The display a run opens on: its stack's primary field, on the component its loads share, with field lines and opacity mapping for a flux or current."""
    try:
        manifest: RunManifest = run.manifest
    except (FileNotFoundError, ValueError):
        return DisplaySpec()

    variable: ElmerVariable | None = manifest.physics_config.primary_variable
    if variable is None:
        return DisplaySpec()

    flows: bool = variable.lines_by_default

    return DisplaySpec(
        field=variable.lower(),
        mode=load_mode(manifest.config),
        streamlines=FieldLineOptions() if flows else None,
        opacity_map=OPACITY_MAP if flows else None,
    )

reduce_field

reduce_field(values: AnyArray, mode: DisplayMode) -> FloatArray

The scalar a display mode draws from one field array.

VALUE passes the array through, POLAR_XY returns the XY magnitude (the quantity that sets the color range; the angle rides along as hue) and a principal mode picks from each row sorted.

Source code in src/femforge/viz/field_display.py
def reduce_field(values: AnyArray, mode: DisplayMode) -> FloatArray:
    """
    The scalar a display mode draws from one field array.

    ``VALUE`` passes the array through, ``POLAR_XY`` returns the XY magnitude (the quantity that sets the color range; the angle rides along as hue) and a principal mode picks from each row sorted.
    """
    array: FloatArray = np.asarray(values, dtype=np.float64)
    wide: bool = mode in VECTOR_MODES or mode in PRINCIPAL_MODES
    if wide and (array.ndim < 2 or array.shape[-1] != 3):
        raise ValueError(f"display mode {mode.value!r} needs 3 components per row, got shape {array.shape}")

    match mode:
        case DisplayMode.VALUE:
            return array
        case DisplayMode.ABSVALUE:
            return np.abs(array)
        case DisplayMode.X:
            return array[..., 0]
        case DisplayMode.Y:
            return array[..., 1]
        case DisplayMode.Z:
            return array[..., 2]
        case DisplayMode.MAGNITUDE:
            return np.linalg.norm(array, axis=-1)
        case DisplayMode.POLAR_XY:
            return np.linalg.norm(array[..., :2], axis=-1)
        case DisplayMode.MAX_PRINCIPAL:
            return np.sort(array, axis=-1)[..., 2]
        case DisplayMode.MID_PRINCIPAL:
            return np.sort(array, axis=-1)[..., 1]
        case DisplayMode.MIN_PRINCIPAL:
            return np.sort(array, axis=-1)[..., 0]

polar_angle

polar_angle(values: AnyArray) -> FloatArray

Each vector's XY direction as a cyclic coordinate in [0, 1] — atan2(y, x) mapped off [-pi, pi].

Source code in src/femforge/viz/field_display.py
def polar_angle(values: AnyArray) -> FloatArray:
    """Each vector's XY direction as a cyclic coordinate in ``[0, 1]`` — ``atan2(y, x)`` mapped off ``[-pi, pi]``."""
    array: FloatArray = np.asarray(values, dtype=np.float64)
    if array.ndim < 2 or array.shape[-1] < 2:
        raise ValueError(f"polar angle needs at least 2 components, got shape {array.shape}")

    radians: FloatArray = np.arctan2(array[..., 1], array[..., 0])
    return (radians + np.pi) / (2.0 * np.pi)

polar_rgba

polar_rgba(values: AnyArray, lo: float, hi: float, cmap: Colormapper) -> Float32Array

Per-vector RGBA for DisplayMode.POLAR_XY: hue from the XY angle through a cyclic cmap, brightness and alpha from the sigmoid-scaled XY magnitude.

Parameters:

  • values (AnyArray) –

    The (N, 3) vectors.

  • lo (float) –

    The XY magnitude at the dark end.

  • hi (float) –

    The XY magnitude at the bright end.

  • cmap (Colormapper) –

    The cyclic colormap the XY angle maps through.

Source code in src/femforge/viz/field_display.py
def polar_rgba(values: AnyArray, lo: float, hi: float, cmap: Colormapper) -> Float32Array:
    """Per-vector RGBA for [`DisplayMode.POLAR_XY`][]: hue from the XY angle through a cyclic ``cmap``, brightness and alpha from the sigmoid-scaled XY magnitude.

    Args:
        values: The ``(N, 3)`` vectors.
        lo: The XY magnitude at the dark end.
        hi: The XY magnitude at the bright end.
        cmap: The cyclic colormap the XY angle maps through.
    """
    array: FloatArray = np.asarray(values, dtype=np.float64)
    magnitude: FloatArray = reduce_field(array, DisplayMode.POLAR_XY)

    # A degenerate range would divide by zero; a unit span leaves the magnitudes where they already are.
    span: float = hi - lo if hi > lo else 1.0
    normalized: FloatArray = np.clip((magnitude - lo) / span, 0.0, 1.0)
    sigmoid: FloatArray = 1.0 / (1.0 + np.exp(-POLAR_STEEPNESS * (normalized - 0.5)))
    scaled: FloatArray = POLAR_BLEND * normalized + (1.0 - POLAR_BLEND) * sigmoid

    hue: FloatArray = np.asarray(cmap(polar_angle(array)), dtype=np.float64)
    rgba: Float32Array = np.zeros((array.shape[0], 4), dtype=np.float32)
    rgba[..., 0:3] = np.clip(hue[..., :3] * scaled[..., np.newaxis], 0.0, 1.0)
    rgba[..., 3] = scaled
    return rgba

color_range

color_range(chunks: Iterable[AnyArray], *, log_scale: bool = False, robust: bool = True) -> tuple[float, float]

The (lo, hi) color limits spanning every scalar chunk's own range, from the finite values only; an empty selection gives (0.0, 1.0).

Parameters:

  • chunks (Iterable[AnyArray]) –

    The scalar arrays, one per body.

  • log_scale (bool, default: False ) –

    Keep only the strictly positive values and start at their 1st percentile.

  • robust (bool, default: True ) –

    Clamp each chunk to its 2-98 percentiles, so a small body keeps its range beside a large one.

Source code in src/femforge/viz/field_display.py
def color_range(chunks: Iterable[AnyArray], *, log_scale: bool = False, robust: bool = True) -> tuple[float, float]:
    """The ``(lo, hi)`` color limits spanning every scalar chunk's own range, from the finite values only; an empty selection gives ``(0.0, 1.0)``.

    Args:
        chunks: The scalar arrays, one per body.
        log_scale: Keep only the strictly positive values and start at their 1st percentile.
        robust: Clamp each chunk to its 2-98 percentiles, so a small body keeps its range beside a large one.
    """

    def bounds(chunk: AnyArray) -> tuple[float, float] | None:
        values: FloatArray = np.asarray(chunk, dtype=np.float64).ravel()
        finite: FloatArray = values[np.isfinite(values)]
        usable: FloatArray = finite[finite > 0.0] if log_scale else finite
        if usable.size == 0:
            return None

        if log_scale:
            return (float(np.percentile(usable, 1.0)), float(np.max(usable)))

        if robust:
            return (float(np.percentile(usable, 2.0)), float(np.percentile(usable, 98.0)))

        return (float(np.min(usable)), float(np.max(usable)))

    ranges: list[tuple[float, float]] = [found for found in (bounds(chunk) for chunk in chunks) if found is not None]
    if not ranges:
        return (0.0, 1.0)

    lo: float = min(low for low, _ in ranges)
    hi: float = max(high for _, high in ranges)

    def widened(low: float, high: float) -> tuple[float, float]:
        """A single-valued range nudged apart so the colormap has somewhere to map."""
        if high > low:
            return (low, high)

        if log_scale:
            return (low / 2.0, high * 2.0)

        pad: float = abs(high) if high != 0.0 else 1.0
        return (low - pad, high + pad)

    return widened(lo, hi)

camera_needs_reset

camera_needs_reset(position: Sequence[float], focal: Sequence[float], bounds: Sequence[float] | None, *, half_angle_deg: float = 30.0) -> bool

Whether the camera has lost the model, with the box behind it or outside its view cone; a camera inside the box always keeps its view.

Parameters:

  • position (Sequence[float]) –

    The camera position.

  • focal (Sequence[float]) –

    The camera's focal point.

  • bounds (Sequence[float] | None) –

    The model box as (xmin, xmax, ymin, ymax, zmin, zmax); missing or non-finite bounds always re-frame.

  • half_angle_deg (float, default: 30.0 ) –

    The half angle of the view cone some box corner must fall inside, in degrees.

Source code in src/femforge/viz/field_display.py
def camera_needs_reset(position: Sequence[float], focal: Sequence[float], bounds: Sequence[float] | None, *, half_angle_deg: float = 30.0) -> bool:
    """Whether the camera has lost the model, with the box behind it or outside its view cone; a camera inside the box always keeps its view.

    Args:
        position: The camera position.
        focal: The camera's focal point.
        bounds: The model box as ``(xmin, xmax, ymin, ymax, zmin, zmax)``; missing or non-finite bounds always re-frame.
        half_angle_deg: The half angle of the view cone some box corner must fall inside, in degrees.
    """
    if bounds is None:
        return True

    box: list[float] = [float(value) for value in bounds]
    if not all(math.isfinite(value) for value in box):
        return True

    eye: FloatArray = np.asarray([float(value) for value in position], dtype=np.float64)
    view: FloatArray = np.asarray([float(value) for value in focal], dtype=np.float64) - eye
    length: float = float(np.linalg.norm(view))
    if length == 0.0:
        return True

    xs, ys, zs = box[0:2], box[2:4], box[4:6]
    lower: FloatArray = np.asarray([xs[0], ys[0], zs[0]], dtype=np.float64)
    upper: FloatArray = np.asarray([xs[1], ys[1], zs[1]], dtype=np.float64)
    if bool(np.all((eye >= lower) & (eye <= upper))):
        return False

    corners: FloatArray = np.asarray([(x, y, z) for x in xs for y in ys for z in zs], dtype=np.float64)
    offsets: FloatArray = corners - eye
    along: FloatArray = offsets @ (view / length)
    if float(np.max(along)) <= 0.0:
        return True

    distances: FloatArray = np.linalg.norm(offsets, axis=1)
    cosines: FloatArray = np.divide(along, distances, out=np.zeros_like(along), where=distances > 0.0)
    return not bool(np.any(cosines >= math.cos(math.radians(half_angle_deg))))

list_fields

list_fields(grid: DataSet, physics: Physics | None = None) -> list[FieldInfo]

Every displayable field of a VTU grid (GeometryIds excluded), sorted by display name, with the units physics decides.

Source code in src/femforge/viz/field_display.py
def list_fields(grid: pv.DataSet, physics: Physics | None = None) -> list[FieldInfo]:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """Every displayable field of a VTU grid (``GeometryIds`` excluded), sorted by display name, with the units ``physics`` decides."""
    point_arrays: dict[str, AnyArray] = {name: np.asarray(grid.point_data[name]) for name in grid.point_data.keys()}
    cell_arrays: dict[str, AnyArray] = {name: np.asarray(grid.cell_data[name]) for name in grid.cell_data.keys()}
    return field_infos(point_arrays, cell_arrays, physics)

split_by_body

split_by_body(grid: UnstructuredGrid, bodies: Bodies) -> MultiBlock

The grid split into one block per named body, keyed by its entities.json name via the GeometryIds cell array.

Source code in src/femforge/viz/field_display.py
def split_by_body(grid: pv.UnstructuredGrid, bodies: Bodies) -> pv.MultiBlock:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """The grid split into one block per named body, keyed by its ``entities.json`` name via the ``GeometryIds`` cell array."""
    import pyvista as pv

    ids: IntArray = np.asarray(grid.cell_data[GEOMETRY_IDS_ARRAY], dtype=np.int64)
    blocks: pv.MultiBlock = pv.MultiBlock()
    for body in bodies:
        mask = cast("np.typing.NDArray[np.bool_]", ids == body.mesh_id)
        if not bool(np.any(mask)):
            continue

        block = cast("pv.UnstructuredGrid", grid.extract_cells(mask))  # pyright: ignore[reportUnknownMemberType]  # pyvista's extract_cells index parameter is partially untyped
        blocks.append(block, name=body.name)

    return blocks

feature_outline

feature_outline(blocks: MultiBlock, feature_angle: float = FEATURE_ANGLE) -> PolyData | None

The feature and boundary edges of a multiblock's outer surface — the black wireframe drawn over the field, the body outlines on a 2D slice — or None when the surface has none.

Source code in src/femforge/viz/field_display.py
def feature_outline(blocks: pv.MultiBlock, feature_angle: float = FEATURE_ANGLE) -> pv.PolyData | None:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """The feature and boundary edges of a multiblock's outer surface — the black wireframe drawn over the field, the body outlines on a 2D slice — or None when the surface has none."""
    import pyvista as pv

    if blocks.is_empty:
        return None

    surface: object = blocks.extract_surface(algorithm=None)
    if not isinstance(surface, pv.PolyData) or surface.n_points == 0:
        return None

    edges: pv.PolyData = surface.extract_feature_edges(
        boundary_edges=True,
        feature_edges=True,
        manifold_edges=False,
        non_manifold_edges=False,
        feature_angle=feature_angle,
        clear_data=True,
    )
    if edges.n_points == 0:
        return None

    return edges

model_dim_of

model_dim_of(grid: DataSet) -> int

2 for a flat (axisymmetric slice) grid with no Z extent, else 3.

Source code in src/femforge/viz/field_display.py
def model_dim_of(grid: pv.DataSet) -> int:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """2 for a flat (axisymmetric slice) grid with no Z extent, else 3."""
    bounds: Sequence[float] = grid.bounds
    extents: list[float] = [bounds[1] - bounds[0], bounds[3] - bounds[2], bounds[5] - bounds[4]]
    # Elmer writes a 2D mesh with a Z extent of a few 1e-18, never exactly zero.
    return 2 if extents[2] <= FLAT_RATIO * max(extents) else 3

sample_colormap

sample_colormap(name: str, count: int = 256) -> FloatArray

count evenly-spaced RGBA rows from a named colormap, resolved through pyvista's get_cmap_safe.

Source code in src/femforge/viz/field_display.py
def sample_colormap(name: str, count: int = 256) -> FloatArray:  # pragma: no cover - needs pyvista (viz extra); proven by the gated integration test
    """``count`` evenly-spaced RGBA rows from a named colormap, resolved through pyvista's ``get_cmap_safe``."""
    import pyvista as pv

    register_paraview()
    cmap = pv.get_cmap_safe(name)  # pyright: ignore[reportUnknownMemberType]  # pyvista returns an untyped matplotlib Colormap
    return np.asarray(cmap(np.linspace(0.0, 1.0, count)), dtype=np.float64)

extrude

extrude(dataset: DataSet, depth: float, *, still: frozenset[str] = frozenset()) -> PolyData

The closed surface of a Cartesian section extruded along the solve Z through depth, centred on the section plane.

Parameters:

  • dataset (DataSet) –

    The section in the solve frame; line and vertex cells are dropped.

  • depth (float) –

    t [m]: The extrusion depth.

  • still (frozenset[str], default: frozenset() ) –

    The array names copied as they are; an extrusion turns no vector, so it changes nothing.

Source code in src/femforge/viz/symmetry.py
def extrude(dataset: pv.DataSet, depth: float, *, still: frozenset[str] = frozenset()) -> pv.PolyData:  # pragma: no cover - needs pyvista (viz extra); proven by the gated tests
    """The closed surface of a Cartesian section extruded along the solve Z through ``depth``, centred on the section plane.

    Args:
        dataset: The section in the solve frame; line and vertex cells are dropped.
        depth: `t` `[m]`: The extrusion depth.
        still: The array names copied as they are; an extrusion turns no vector, so it changes nothing.
    """
    import pyvista as pv

    grid, points, polygons = _section(dataset)
    surface: Surface = extruded(points, polygons, depth)
    if not surface.corners.size:
        return pv.PolyData()

    output = pv.PolyData(surface.points, faces=surface.faces)
    _dress(grid, surface, output, still)

    return output

mirror

mirror(dataset: DataSet, *, still: frozenset[str] = frozenset()) -> UnstructuredGrid

Both halves of an axisymmetric section in the solve frame: its triangles and quads beside their reflection across the axis; line and vertex cells are dropped.

Parameters:

  • dataset (DataSet) –

    The section in the solve frame.

  • still (frozenset[str], default: frozenset() ) –

    The array names copied unturned, such as principal values.

Source code in src/femforge/viz/symmetry.py
def mirror(dataset: pv.DataSet, *, still: frozenset[str] = frozenset()) -> pv.UnstructuredGrid:  # pragma: no cover - needs pyvista (viz extra); proven by the gated tests
    """Both halves of an axisymmetric section in the solve frame: its triangles and quads beside their reflection across the axis; line and vertex cells are dropped.

    Args:
        dataset: The section in the solve frame.
        still: The array names copied unturned, such as principal values.
    """
    import pyvista as pv

    grid, points, polygons = _section(dataset)
    surface: Surface = mirrored(points, polygons)
    celltypes: np.typing.NDArray[np.uint8] = np.full(len(surface.corners), VtkCell.QUAD, dtype=np.uint8)
    celltypes[surface.corners == 3] = VtkCell.TRIANGLE
    output = pv.UnstructuredGrid(surface.faces, celltypes, surface.points)
    _dress(grid, surface, output, still)

    return output

revolve

revolve(dataset: DataSet, basis: Basis, *, segments: int = 72, sweep: float = 360.0, still: frozenset[str] = frozenset()) -> PolyData

The surfaces of an axisymmetric section swept about its axis into the authored frame, capped on a partial sweep.

Parameters:

  • dataset (DataSet) –

    The section in the solve frame; line and vertex cells are dropped.

  • basis (Basis) –

    Where the section sits in the authored frame.

  • segments (int, default: 72 ) –

    The ring count per full turn.

  • sweep (float, default: 360.0 ) –

    The swept angle in degrees, in (0, 360].

  • still (frozenset[str], default: frozenset() ) –

    The array names copied unturned, such as principal values.

Source code in src/femforge/viz/symmetry.py
def revolve(
    dataset: pv.DataSet, basis: Basis, *, segments: int = 72, sweep: float = 360.0, still: frozenset[str] = frozenset()
) -> pv.PolyData:  # pragma: no cover - needs pyvista (viz extra); proven by the gated tests
    """The surfaces of an axisymmetric section swept about its axis into the authored frame, capped on a partial sweep.

    Args:
        dataset: The section in the solve frame; line and vertex cells are dropped.
        basis: Where the section sits in the authored frame.
        segments: The ring count per full turn.
        sweep: The swept angle in degrees, in ``(0, 360]``.
        still: The array names copied unturned, such as principal values.
    """
    import pyvista as pv

    grid, points, polygons = _section(dataset)
    surface: Surface = swept(points, polygons, basis, segments=segments, sweep=sweep)
    if not surface.corners.size:
        return pv.PolyData()

    output = pv.PolyData(surface.points, faces=surface.faces)
    _dress(grid, surface, output, still)

    return output

swept_lines

swept_lines(points: FloatArray, lines: IntArray, basis: Basis, *, segments: int = 72, sweep: float = 360.0) -> Surface

The quads a section's line cells sweep sweep degrees about the axis, segments steps per turn, uncapped.

Parameters:

  • points (FloatArray) –

    The (N, 3) section points, X = r and Y = z.

  • lines (IntArray) –

    The (E, 2) point ids of each line cell.

  • basis (Basis) –

    Where the section sits in the authored frame.

  • segments (int, default: 72 ) –

    The ring count per full turn.

  • sweep (float, default: 360.0 ) –

    The swept angle in degrees, in (0, 360].

Source code in src/femforge/viz/symmetry.py
def swept_lines(points: FloatArray, lines: IntArray, basis: Basis, *, segments: int = 72, sweep: float = 360.0) -> Surface:
    """The quads a section's line cells sweep ``sweep`` degrees about the axis, ``segments`` steps per turn, uncapped.

    Args:
        points: The ``(N, 3)`` section points, X = r and Y = z.
        lines: The ``(E, 2)`` point ids of each line cell.
        basis: Where the section sits in the authored frame.
        segments: The ring count per full turn.
        sweep: The swept angle in degrees, in ``(0, 360]``.
    """
    if segments < 3:
        raise ValueError(f"A revolve needs at least 3 segments per turn, not {segments}.")

    if not 0.0 < sweep <= 360.0:
        raise ValueError(f"The sweep must lie in (0, 360] degrees, not {sweep:g}.")

    if not len(lines):
        return Surface.empty(basis)

    full: bool = sweep >= 360.0
    steps: int = segments if full else max(1, round(segments * sweep / 360.0))
    rings: int = steps if full else steps + 1
    step: float = math.radians(sweep) / steps
    angles: FloatArray = step * np.arange(rings, dtype=np.float64)

    used: IntArray = np.unique(lines)
    per_ring: int = len(used)
    slot: IntArray = np.zeros(len(points), dtype=np.int64)
    slot[used] = np.arange(per_ring)

    segment: IntArray = np.arange(steps, dtype=np.int64)
    following: IntArray = (segment + 1) % rings
    start: IntArray = slot[lines[:, 0]][:, np.newaxis]
    end: IntArray = slot[lines[:, 1]][:, np.newaxis]
    quads: IntArray = np.stack([start + per_ring * segment, start + per_ring * following, end + per_ring * following, end + per_ring * segment], axis=2).reshape(-1, 4)
    sizes: IntArray = np.full(len(quads), 4, dtype=np.int64)

    return Surface(
        points=basis.place(np.tile(points[used], (rings, 1)), np.repeat(angles, per_ring)),
        faces=np.column_stack([sizes, quads]).reshape(-1),
        corners=sizes,
        point_source=np.tile(used, rings),
        point_theta=np.repeat(angles, per_ring),
        cell_source=np.repeat(np.arange(len(lines), dtype=np.int64), steps),
        cell_theta=np.tile(angles[segment] + step / 2.0, len(lines)),
        basis=basis,
    )

glyph_label

glyph_label(condition: ConditionUnion, *, revolved: bool, dropped: Sequence[str] = ()) -> str | None

The short scene label of condition, magnitudes only since the shape shows the direction; None for a condition the shape says enough about.

Parameters:

  • condition (ConditionUnion) –

    The authored condition.

  • revolved (bool) –

    Whether the run solves a revolved section, whose loads are totals over the turn.

  • dropped (Sequence[str], default: () ) –

    The authored fields the frame has no solve coordinate for.

Source code in src/femforge/viz/glyphs.py
def glyph_label(condition: ConditionUnion, *, revolved: bool, dropped: Sequence[str] = ()) -> str | None:
    """The short scene label of ``condition``, magnitudes only since the shape shows the direction; None for a condition the shape says enough about.

    Args:
        condition: The authored condition.
        revolved: Whether the run solves a revolved section, whose loads are totals over the turn.
        dropped: The authored fields the frame has no solve coordinate for.
    """
    match condition:
        case SurfaceForce():
            size: Quantity = quantity(condition.force.to(U.N).magnitude.magnitude(), "N")
            text: str = readout(size)

            return f"{text} Total" if revolved else text
        case FixedDisplacement():
            authored: tuple[tuple[str, Quantity | None], ...] = (("x", condition.x), ("y", condition.y), ("z", condition.z))
            axes: list[tuple[str, Quantity | None]] = [(name, value) for name, value in authored if name not in dropped]
            moved: list[float] = [value.m_as("m") for _, value in axes if value is not None]

            if any(moved):
                return readout(quantity(math.hypot(*moved), "m"))

            if all(value is not None for _, value in axes):
                return None

            held: list[str] = [name.upper() for name, value in axes if value is not None]

            return f"{', '.join(held)} Fixed" if held else None
        case CurrentDensity():
            return readout(abs(condition.value), unit=U.A / U.mm**2)
        case FixedTemperature():
            return readout(condition.value, unit=U.K)
        case HeatFlux():
            return f"q {readout(condition.value)}"
        case Convection():
            return f"h {_bare(condition.coefficient, U.W / (U.m**2 * U.K))} · T {readout(condition.ext_temperature, unit=U.K)}"
        case HeatSource():
            return f"q {readout(condition.power_density)}"
        case JouleHeat():
            return "Joule Heat"
        case CoilDrive():
            return f"Coil {readout(condition.current)}"
        case FixedVoltage():
            return readout(condition.value)
        case CoilTerminal():
            return title(condition.role)
        case Magnetization() | CalculateMagneticForce():
            return None

glyphs_of

glyphs_of(conditions: ConditionsFile, bodies: Sequence[Body], boundaries: Sequence[Boundary], frame: Frame) -> list[Glyph]

The glyphs of every drawable condition a run's groups received, joined to their measured centroids and normals.

Parameters:

  • conditions (ConditionsFile) –

    What each group received from the sif.

  • bodies (Sequence[Body]) –

    The run's bodies, which carry the centroids and bounding boxes.

  • boundaries (Sequence[Boundary]) –

    The run's boundaries, which carry the centroids and outward normals.

  • frame (Frame) –

    The frame the run solved in.

Source code in src/femforge/viz/glyphs.py
def glyphs_of(conditions: ConditionsFile, bodies: Sequence[Body], boundaries: Sequence[Boundary], frame: Frame) -> list[Glyph]:
    """The glyphs of every drawable condition a run's groups received, joined to their measured centroids and normals.

    Args:
        conditions: What each group received from the sif.
        bodies: The run's bodies, which carry the centroids and bounding boxes.
        boundaries: The run's boundaries, which carry the centroids and outward normals.
        frame: The frame the run solved in.
    """
    found: list[Glyph] = []

    for group in conditions.bodies:
        body: Body | None = next((candidate for candidate in bodies if candidate.name == group.group), None)

        if body is None or body.centroid is None:
            continue

        for record in group.conditions:
            condition: ConditionUnion | None = record.condition

            if condition is None or condition.glyph is None:
                continue

            vector: Vec3 | None = None
            extent: float | None = None
            reach: float = 0.0

            if condition.glyph is ConditionGlyph.MAGNETIZATION and body.bbox is not None:
                spans: tuple[float, float, float] = (body.bbox.high - body.bbox.low).to_tuple()
                sizes: list[float] = [size for size in spans if size > FLAT_RATIO * max(spans)]
                vector = _unit(_padded(record))
                extent = MAGNET_SHARE * min(sizes) if sizes else None
                reach = 0.0 if vector is None else sum(abs(component) * span / 2.0 for component, span in zip(vector.to_tuple(), spans, strict=True))

            if condition.glyph is ConditionGlyph.CURRENT_DENSITY and frame.model_dim == 2:
                vector = Vec3(0.0, 0.0, _drive_sign(record))

            label: str | None = glyph_label(condition, revolved=frame.revolves, dropped=record.dropped)
            found.append(Glyph(group=group.group, target=EntityKind.BODY, kind=condition.glyph, anchor=body.centroid, vector=vector, label=label, extent=extent, reach=reach))

    for group in conditions.boundaries:
        boundary: Boundary | None = next((candidate for candidate in boundaries if candidate.name == group.group), None)

        if boundary is None or boundary.centroid is None:
            continue

        for record in group.conditions:
            condition = record.condition

            if condition is None or condition.glyph is None:
                continue

            solved: Vec3 | None = _padded(record)
            indices: set[int] = {component.index for component in record.solve_components}
            moved: bool = solved is not None and solved.magnitude() > 0.0
            held: tuple[bool, ...] = tuple(index in indices for index in range(1, frame.model_dim + 1)) if condition.glyph is ConditionGlyph.FIXED_DISPLACEMENT else ()
            vector = _unit(solved) if condition.glyph is ConditionGlyph.SURFACE_FORCE or moved else None
            share: float = solved.magnitude() if condition.glyph is ConditionGlyph.SURFACE_FORCE and solved is not None else 1.0
            label = glyph_label(condition, revolved=frame.revolves, dropped=record.dropped)
            glyph: Glyph = Glyph(
                group=group.group,
                target=EntityKind.BOUNDARY,
                kind=condition.glyph,
                anchor=boundary.centroid,
                normal=boundary.normal,
                vector=vector,
                share=share,
                label=label,
                held=held,
            )
            found.append(glyph)

    loads: list[float] = [glyph.share for glyph in found if glyph.kind is ConditionGlyph.SURFACE_FORCE]
    largest: float = max(loads, default=0.0)

    if largest <= 0.0:
        return found

    return [glyph.model_copy(update={"share": glyph.share / largest}) if glyph.kind is ConditionGlyph.SURFACE_FORCE else glyph for glyph in found]

glyph_actors

glyph_actors(glyphs: Sequence[Glyph], cells: Mapping[str, DataSet], placement: GlyphPlacement, view: GlyphView) -> list[GlyphDraw]

The merged glyph actors of the shown glyphs, at most one per GLYPH_ACTORS name.

Parameters:

  • glyphs (Sequence[Glyph]) –

    The run's glyphs, anchors already moved with the warp.

  • cells (Mapping[str, DataSet]) –

    The solve-frame cells of each glyph's group by entity id, already displaced with the warp.

  • placement (GlyphPlacement) –

    How the solve frame lands in the displayed scene.

  • view (GlyphView) –

    Which glyphs to draw, and how large.

Source code in src/femforge/viz/glyphs.py
def glyph_actors(
    glyphs: Sequence[Glyph], cells: Mapping[str, pv.DataSet], placement: GlyphPlacement, view: GlyphView
) -> list[GlyphDraw]:  # pragma: no cover - needs pyvista (viz extra); proven by the gated glyph tests
    """The merged glyph actors of the shown glyphs, at most one per `GLYPH_ACTORS` name.

    Args:
        glyphs: The run's glyphs, anchors already moved with the warp.
        cells: The solve-frame cells of each glyph's group by entity id, already displaced with the warp.
        placement: How the solve frame lands in the displayed scene.
        view: Which glyphs to draw, and how large.
    """
    import pyvista as pv

    diagonal: float = placement.diagonal
    lift: float = TINT_LIFT * diagonal
    toward_viewer: FloatArray = np.array([0.0, 0.0, lift])
    arrows: list[pv.PolyData] = []
    halos: list[pv.PolyData] = []
    faces: list[pv.PolyData] = []
    lines: list[FloatArray] = []
    marks: list[FloatArray] = []
    leaders: list[FloatArray] = []
    spots: list[FloatArray] = []
    texts: list[str] = []
    areas: list[float] = []
    shown: list[Glyph] = [glyph for glyph in glyphs if glyph.kind in view.kinds and glyph.ref.id not in view.hidden]

    def point(vector: Vec3) -> FloatArray:
        return np.asarray(vector.to_list(), dtype=np.float64)

    def arrow(tail: FloatArray, head: FloatArray, theta: float = 0.0) -> None:
        ends: FloatArray = np.stack([tail, head])
        copies: list[FloatArray] = [placement.placed(ends, theta)] if placement.revolved else placement.copies(ends)

        for placed in copies:
            tail_at: FloatArray = placed[0:1].reshape(3)
            head_at: FloatArray = placed[1:2].reshape(3)
            arrows.append(_arrow(tail_at, head_at))
            halos.append(_arrow(tail_at, head_at, halo=True))

    def chip(glyph: Glyph, at: FloatArray | None = None) -> None:
        if glyph.label is None or view.labels is GlyphLabels.NONE:
            return

        anchor: FloatArray = point(glyph.anchor)
        spot: FloatArray = anchor if at is None else at

        if at is None and glyph.normal is not None and glyph.target is EntityKind.BOUNDARY:
            spot = anchor + LEADER_SHARE * diagonal * point(glyph.normal)
            leaders.append(np.stack([anchor, spot])[np.newaxis])

        spots.append(spot)
        texts.append(glyph.label)

    def tint(glyph: Glyph) -> FloatArray | None:
        found: pv.DataSet | None = cells.get(glyph.ref.id)

        if found is None or found.n_cells == 0:
            return None

        if not placement.flat:
            surface: pv.PolyData = cast("pv.PolyData", found.extract_surface(algorithm=None))
            surface.clear_data()

            faces.append(surface)
            areas.append(float(surface.area))

            return np.asarray(surface.points, dtype=np.float64)

        segments: FloatArray = _segments(found)
        swept: Surface | None = placement.swept_face(segments)

        if swept is not None:
            faces.append(_surface(swept))
        else:
            lines.append(segments + toward_viewer)

        return segments

    for glyph in shown:
        anchor: FloatArray = point(glyph.anchor)

        match glyph.kind:
            case ConditionGlyph.SURFACE_FORCE:
                if glyph.vector is None:
                    continue

                start, end = arrow_span(glyph.anchor, glyph.vector, glyph.normal, glyph.share, diagonal)
                pulled: bool = glyph.normal is None or glyph.vector.dot(glyph.normal) >= 0.0
                gap: Vec3 = glyph.vector.normalized() * (LEADER_SHARE * diagonal / 4.0)
                arrow(point(start), point(end))
                chip(glyph, point(end + gap if pulled else start - gap))
            case ConditionGlyph.FIXED_DISPLACEMENT:
                held: FloatArray | None = tint(glyph)
                area: float = areas[-1] if areas else 0.0
                outward: Vec3 | None = glyph.normal

                if held is not None and outward is not None and placement.flat:
                    rolled: bool = not all(glyph.held)
                    segments: FloatArray = held.reshape(-1, 2, 3) + toward_viewer

                    if rolled:
                        radius: float = ROLLER_RADIUS * diagonal
                        face_length: float = float(np.linalg.norm(segments[:, 1] - segments[:, 0], axis=1).sum())
                        middles: FloatArray = spread(densified(segments, radius), max(face_length / PIN_COUNT, 3.0 * radius))
                        marks.append(circles(middles + radius * point(outward), radius))
                    else:
                        marks.append(clamp_ticks(segments, outward, diagonal))
                elif held is not None and outward is not None:
                    roots: FloatArray = spread(held, math.sqrt(area / PIN_COUNT))
                    tips: FloatArray = roots + PIN_LENGTH * diagonal * point(outward)
                    marks.append(np.stack([roots, tips], axis=1))

                    if not all(glyph.held):
                        centers: list[list[float]] = cast("list[list[float]]", tips.tolist())
                        arrows.extend(pv.Sphere(radius=ROLLER_RADIUS * diagonal, center=center) for center in centers)  # pyright: ignore[reportUnknownMemberType]  # pyvista types the center parameter loosely

                if glyph.vector is not None:
                    reach: FloatArray = anchor + ARROW_FLOOR * diagonal * point(glyph.vector)
                    marks.append(dashed(np.stack([anchor, reach])[np.newaxis], DASH_SHARE * diagonal / 2.0))

                chip(glyph)
            case ConditionGlyph.MAGNETIZATION:
                if glyph.vector is None or glyph.extent is None:
                    continue

                direction: FloatArray = point(glyph.vector)
                length: float = max(glyph.extent, ARROW_FLOOR * diagonal)
                solid: bool = placement.revolved or not placement.flat
                tail: FloatArray = anchor + direction * glyph.reach if solid else anchor - direction * length / 2.0 + toward_viewer

                for theta in placement.angles():
                    arrow(tail, tail + direction * length, theta)
            case ConditionGlyph.CURRENT_DENSITY:
                radius = MARKER_RADIUS * diagonal

                if glyph.vector is not None:
                    center: FloatArray = anchor + toward_viewer
                    marks.append(circles(center[np.newaxis], radius))

                    if glyph.vector.z > 0.0:
                        marks.extend(circles(center[np.newaxis], radius * scale) for scale in (0.15, 0.25))
                    else:
                        cross: float = radius / math.sqrt(2.0)
                        marks.append(np.array([[center + [-cross, -cross, 0.0], center + [cross, cross, 0.0]], [center + [-cross, cross, 0.0], center + [cross, -cross, 0.0]]]))

                chip(glyph, anchor + np.array([1.5 * radius, 0.0, 0.0]) if glyph.vector is not None else None)
            case ConditionGlyph.THERMAL | ConditionGlyph.VOLTAGE | ConditionGlyph.COIL_TERMINAL:
                if glyph.target is EntityKind.BOUNDARY:
                    _ = tint(glyph)

                chip(glyph)

    draws: list[GlyphDraw] = []
    width: float = view.scale

    def placed_segments(groups: list[FloatArray]) -> pv.PolyData | None:
        if not groups:
            return None

        joined: FloatArray = np.concatenate(groups)

        if not len(joined):
            return None

        copies: list[FloatArray] = [copy.reshape(-1, 2, 3) for copy in placement.copies(joined.reshape(-1, 3))]

        return _polylines(np.concatenate(copies))

    if arrows:
        draws.append(GlyphDraw(GlyphActor.ARROWS, _merged(arrows), color=GLYPH_FILL))

    if halos:
        draws.append(GlyphDraw(GlyphActor.HALOS, _merged(halos), color=GLYPH_HALO, culling="front"))

    if faces:
        draws.append(GlyphDraw(GlyphActor.FACES, _merged(faces), color=GLYPH_TINT, opacity=TINT_OPACITY, layer=Layer.TINT))

    for actor, groups, color, px in (
        (GlyphActor.LINES, lines, GLYPH_TINT, TINT_LINE_PX),
        (GlyphActor.MARKS, marks, view.ink, MARK_LINE_PX),
        (GlyphActor.LEADERS, leaders, view.ink, MARK_LINE_PX),
    ):
        mesh: pv.PolyData | None = placed_segments(groups)

        if mesh is not None:
            draws.append(GlyphDraw(actor, mesh, color=color, line_width=px * width))

    if spots:
        located: FloatArray = placement.placed(np.asarray(spots, dtype=np.float64)) + placement.front
        draws.append(GlyphDraw(GlyphActor.LABELS, pv.PolyData(located), labels=tuple(texts), font_size=round(LABEL_FONT_PX * view.scale)))

    return draws

plain_spec

plain_spec(spec: DisplaySpec, bodies: Iterable[str]) -> DisplaySpec

spec with every one of bodies painted PLAIN_BODY, its own opacity kept.

Source code in src/femforge/viz/glyphs.py
def plain_spec(spec: DisplaySpec, bodies: Iterable[str]) -> DisplaySpec:
    """``spec`` with every one of ``bodies`` painted `PLAIN_BODY`, its own opacity kept."""
    styles: list[BodyStyle] = [BodyStyle(body=body, paint=BodyPaint.SOLID, color=PLAIN_BODY, opacity=next((style.opacity for style in spec.body_styles if style.body == body), 1.0)) for body in bodies]

    return spec.model_copy(update={"body_styles": tuple(styles)})