Skip to content

Solids

trusty.fem simulates deformable volumetric solids: a mesh, a material and a density are all a body needs.

Quick example

A soft beam clamped at one end, sagging under gravity:

mesh = trusty.make_beam_hex_mesh(size=(1.0, 0.1, 0.1), res=(20, 2, 2))
material = trusty.StableNeoHookean(youngs_modulus=1e6, poisson_ratio=0.3)

world = trusty.World(backend=backend, timestep=1.0 / 60.0)
beam = trusty.fem.add_hex_solid(world, mesh, material, density=1000.0, order=order)
X = np.asarray(trusty.fem.positions(world, beam))
clamp = np.flatnonzero(np.abs(X[:, 0]) < 1e-6).tolist()  # the x = 0 end
trusty.constraints.add_pin(world, beam, clamp)

Each world.step() advances one timestep, and trusty.fem.positions(world, beam) returns the deformed nodes as an (N, 3) NumPy array.

Cantilever beam sagging under gravity

add_hex_solid (or add_tet_solid for tet meshes) adds the body and returns its id, which every other trusty.fem function takes.

Argument Meaning
mesh a HexMesh or TetMesh; see Mesh types
material a material model and its parameters (see Material models), or a trusty.fem.ElementMaterials giving each element its own (below)
density kg/m³
order ElementOrder.Linear (default) or a quadratic order; see Element order

The clamp comes from constraints.add_pin on the nodes of a plane. Pins and moving targets are covered under Constraints, and surface loads under Loads.

Full script: python examples/cantilever_beam.py
"""Cantilevered hex beam with Stable Neo-Hookean elasticity and gravity.

Steps the simulator and, unless
``--no-viewer`` is passed, shows the deforming beam in polyscope.

Usage:
    python examples/cantilever_beam.py                # live polyscope
    python examples/cantilever_beam.py --no-viewer    # write PNG sequence
    python examples/cantilever_beam.py --steps 240    # run longer
    python examples/cantilever_beam.py --order q2     # quadratic (Q2) elements

Install polyscope with ``pip install polyscope``.
"""

from __future__ import annotations

import argparse
from pathlib import Path

import numpy as np

import trusty
from utils import init_polyscope

ORDER = trusty.fem.ElementOrder
# CLI order name -> hex element order (Q1/Q2 Lagrange/Q2 serendipity).
HEX_ORDERS = {
    "linear": ORDER.Linear,
    "q2":     ORDER.Quadratic,
    "q2s":    ORDER.QuadraticSerendipity,
}


def build_world(backend: str = "auto", order=ORDER.Linear):
    mesh = trusty.make_beam_hex_mesh(size=(1.0, 0.1, 0.1), res=(20, 2, 2))
    material = trusty.StableNeoHookean(youngs_modulus=1e6, poisson_ratio=0.3)

    world = trusty.World(backend=backend, timestep=1.0 / 60.0)
    beam = trusty.fem.add_hex_solid(world, mesh, material, density=1000.0, order=order)
    X = np.asarray(trusty.fem.positions(world, beam))
    clamp = np.flatnonzero(np.abs(X[:, 0]) < 1e-6).tolist()  # the x = 0 end
    trusty.constraints.add_pin(world, beam, clamp)

    return world, beam


def _register_visuals(ps, world, beam, order):
    # Linear elements render as a hex volume mesh; quadratic elements render
    # via the linear sub-triangle tessellation of their curved surface.
    if order == ORDER.Linear:
        ps_mesh = ps.register_volume_mesh(
            "beam", np.asarray(trusty.fem.positions(world, beam)).copy(), hexes=np.asarray(trusty.fem.elements(world, beam)))
        ps_mesh.set_edge_width(1.0)
        read = lambda: np.asarray(trusty.fem.positions(world, beam))
    else:
        V = np.asarray(trusty.fem.positions(world, beam)).copy()
        _, F = trusty.surface.mesh(world, beam)
        ps_mesh = ps.register_surface_mesh("beam", V, F)
        read = lambda: np.asarray(trusty.fem.positions(world, beam))
    return ps_mesh, read


def run_polyscope(world, beam, steps: int, order):
    ps = init_polyscope(headless=False)
    ps_mesh, read_verts = _register_visuals(ps, world, beam, order)

    state = {"i": 0, "playing": True}

    def callback():
        import polyscope.imgui as psim
        _, state["playing"] = psim.Checkbox("play", state["playing"])
        psim.SameLine()
        if psim.Button("step") or state["playing"]:
            if state["i"] < steps:
                world.step()
                state["i"] += 1
                ps_mesh.update_vertex_positions(read_verts())
        psim.Text(f"step {state['i']} / {steps}")
        report = world.last_report()
        psim.Text(
            f"last solve: iters={report.iterations}  "
            f"residual={report.final_residual:.3e}"
        )

    ps.set_user_callback(callback)
    ps.show()


def run_screenshots(world, beam, steps: int, out_dir: Path, order):
    ps = init_polyscope(headless=True)
    out_dir.mkdir(parents=True, exist_ok=True)
    ps_mesh, read_verts = _register_visuals(ps, world, beam, order)
    ps.reset_camera_to_home_view()

    def snapshot(idx: int):
        ps.screenshot(str(out_dir / f"beam_{idx:04d}.png"), transparent_bg=False)

    snapshot(0)
    for i in range(1, steps + 1):
        world.step()
        ps_mesh.update_vertex_positions(read_verts())
        snapshot(i)

    print(f"Wrote {steps + 1} screenshots to {out_dir}/")


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--backend",
                        choices=["auto", "cpu", "cuda", "accelerate"], default="auto")
    parser.add_argument("--order", choices=list(HEX_ORDERS), default="linear",
                        help="element order: q1 linear (default), q2 Lagrange, q2s serendipity")
    parser.add_argument("--steps", type=int, default=120,
                        help="total simulation steps (default: 120 = 2 s at 1/60)")
    parser.add_argument("--no-viewer", action="store_true",
                        help="headless: write PNG screenshots instead of showing polyscope")
    parser.add_argument("--out", type=Path, default=Path("out"),
                        help="output directory for --no-viewer mode")
    args = parser.parse_args()

    order = HEX_ORDERS[args.order]
    world, beam = build_world(backend=args.backend, order=order)

    if args.no_viewer:
        run_screenshots(world, beam, args.steps, args.out, order)
    else:
        run_polyscope(world, beam, args.steps, order)


if __name__ == "__main__":
    main()

The world

trusty.World takes its settings as keyword arguments, all optional. They are fixed for the world's life, and apply to every body in it:

Argument Meaning
backend "auto" (default): the fastest backend every body type in the world supports, accelerate then cuda then cpu. Or "cpu", "accelerate", "cuda".
timestep seconds per world.step() (default 1/60)
gravity (x, y, z), m/s² (default (0, 0, -9.80665), standard gravity)
time_stepping how each step is solved; see below
newton a trusty.NewtonConfig(max_iters=..., tolerance=...) for the solver (default 20 iterations; the default tolerance=1e-3 stops once no DOF moves faster than 0.1% of the scene size per second)
time_stepping Each step
"backward_euler" (default) moves the bodies forward in time, damping motion slightly
"bdf2" the same, second order: less damping, so swinging and bouncing last longer
"quasi_static" moves forward, then drops every velocity: bodies head for rest without swinging
"static" finds the equilibrium under the current loads, with no inertia

trusty.TimeStepping.BDF2 and the other enum values work too. Contact is turned on separately; see Contact.

Materials

The material is one line. Build a different model to change how the solid responds:

material = trusty.StableNeoHookean(youngs_modulus=1e6, poisson_ratio=0.3)

Every model, its strain energy and its parameters are on Material models.

Graded materials

A material can vary across a body. Any argument of a material, such as youngs_modulus or poisson_ratio, takes an array with one value per element of the mesh, in the mesh's element order, in place of a number; a number still applies to every element. Each element is uniform, so a region of elements (a segmentation label, say) keeps its stiffness right up to its faces. Here one beam is stiff everywhere except a band of soft elements in the middle:

E = element_youngs(mesh)                    # one value per hex, in mesh order
material = trusty.StableNeoHookean(youngs_modulus=E, poisson_ratio=NU)

Under gravity the stiff halves stay straight and the beam folds at the soft band (coloured by Young's modulus):

A graded cantilever folding at its soft middle band

Full script: python examples/fem/graded_beam.py
"""A cantilever with a soft band of elements in the middle.

A beam is clamped at one end and sags under gravity. Each element gets its own
material parameters, and a band of elements in the middle is much softer than
the rest.

Usage:
    python examples/fem/graded_beam.py              # live polyscope
    python examples/fem/graded_beam.py --no-viewer  # print the sag
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np

import trusty

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils import init_polyscope  # noqa: E402

LENGTH = 1.0
NU = 0.3
BAND = (0.4, 0.6)       # where along the beam the soft band runs (m)


def element_youngs(mesh):
    """Young's modulus per hex, in mesh order: stiff, with a soft band in the middle."""
    centres_x = np.asarray(mesh.vertices)[np.asarray(mesh.elements), 0].mean(axis=1)
    in_band = (centres_x > BAND[0]) & (centres_x < BAND[1])
    return np.where(in_band, 5e4, 1e7)


def graded_material(mesh):
    E = element_youngs(mesh)                    # one value per hex, in mesh order
    material = trusty.StableNeoHookean(youngs_modulus=E, poisson_ratio=NU)
    return material


def build_world(backend: str = "auto"):
    world = trusty.World(backend=backend,
                         time_stepping="static",   # solve equilibrium each step
                         newton=trusty.NewtonConfig(max_iters=60))

    mesh = trusty.make_beam_hex_mesh(size=(LENGTH, 0.1, 0.1), res=(40, 4, 4))
    beam = trusty.fem.add_hex_solid(world, mesh, graded_material(mesh), density=1000.0)
    X = np.asarray(mesh.vertices)
    trusty.constraints.add_pin(world, beam, np.flatnonzero(np.abs(X[:, 0]) < 1e-6).tolist())
    return world, beam, mesh


def tip_sag(world, beam) -> float:
    return float(-np.asarray(trusty.fem.positions(world, beam))[:, 2].min())


def run_viewer(world, beam, mesh, steps: int):
    ps = init_polyscope(headless=False)
    m = ps.register_volume_mesh("beam", trusty.fem.positions(world, beam),
                                hexes=np.asarray(mesh.elements))
    m.set_edge_width(1.0)
    m.add_scalar_quantity("log10 Young's modulus", np.log10(element_youngs(mesh)),
                          defined_on="cells", cmap="viridis", enabled=True)
    ps.reset_camera_to_home_view()

    state = {"i": 0, "playing": False}

    def callback():
        import polyscope.imgui as psim
        _, state["playing"] = psim.Checkbox("play", state["playing"])
        psim.SameLine()
        if (psim.Button("step") or state["playing"]) and state["i"] < steps:
            world.step()
            state["i"] += 1
            m.update_vertex_positions(trusty.fem.positions(world, beam))
        psim.Text(f"step {state['i']} / {steps}   tip sag {tip_sag(world, beam):.3f} m")

    ps.set_user_callback(callback)
    ps.show()


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--steps", type=int, default=5)
    ap.add_argument("--backend", default="auto", choices=["auto", "cpu", "accelerate", "cuda"])
    ap.add_argument("--no-viewer", action="store_true", help="headless: print the sag")
    args = ap.parse_args()

    world, beam, mesh = build_world(args.backend)
    if args.no_viewer:
        for _ in range(args.steps):
            world.step()
        print(f"tip sag after {args.steps} steps: {tip_sag(world, beam):.3f} m")
        return
    run_viewer(world, beam, mesh, args.steps)


if __name__ == "__main__":
    main()

Several materials in one body

Elements of one body can also run different models, not only different parameters. A material id says which material each element belongs to, and trusty.fem.ElementMaterials(material_id, materials) pairs the ids with the materials: element e runs materials[material_id[e]]. material_id is an integer array with one entry per element of the mesh, in the mesh's element order. A material's own per-element arrays hold one value per element of that material, in element order. Here the half of a cantilever by the clamp is steel and the half at the tip is rubber:

steel = trusty.Hencky(youngs_modulus=2e11, poisson_ratio=0.3)
rubber = trusty.StableNeoHookean(youngs_modulus=1e6, poisson_ratio=0.45)

centres_x = np.asarray(mesh.vertices)[np.asarray(mesh.elements), 0].mean(axis=1)
material_id = (centres_x > LENGTH / 2).astype(int)      # 0 = steel, 1 = rubber, per element
return trusty.fem.ElementMaterials(material_id, [steel, rubber])

Under gravity the steel stays straight and the rubber droops. A material on its own, as in the other examples, is the body made of that one material.

Full script: python examples/fem/steel_rubber_cantilever.py
"""A cantilever that is steel at its root and rubber at its tip.

A beam is clamped at one end and drops under gravity, swinging before it settles. One mesh carries two materials: the
elements in the half by the clamp are steel, and the elements in the far half are rubber.

Usage:
    python examples/fem/steel_rubber_cantilever.py              # live polyscope
    python examples/fem/steel_rubber_cantilever.py --no-viewer  # print the sag
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np

import trusty

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils import init_polyscope  # noqa: E402

LENGTH = 1.0
STEEL_COLOR = (0.62, 0.66, 0.72)
RUBBER_COLOR = (0.85, 0.30, 0.25)


def element_materials(mesh):
    steel = trusty.Hencky(youngs_modulus=2e11, poisson_ratio=0.3)
    rubber = trusty.StableNeoHookean(youngs_modulus=1e6, poisson_ratio=0.45)

    centres_x = np.asarray(mesh.vertices)[np.asarray(mesh.elements), 0].mean(axis=1)
    material_id = (centres_x > LENGTH / 2).astype(int)      # 0 = steel, 1 = rubber, per element
    return trusty.fem.ElementMaterials(material_id, [steel, rubber])


def build_world(backend: str = "auto"):
    world = trusty.World(backend=backend)

    mesh = trusty.make_beam_hex_mesh(size=(LENGTH, 0.1, 0.1), res=(40, 4, 4))
    beam = trusty.fem.add_hex_solid(world, mesh, element_materials(mesh), density=1000.0)
    X = np.asarray(mesh.vertices)
    trusty.constraints.add_pin(world, beam, np.flatnonzero(np.abs(X[:, 0]) < 1e-6).tolist())
    return world, beam, mesh


def tip_sag(world, beam) -> float:
    return float(-np.asarray(trusty.fem.positions(world, beam))[:, 2].min())


def run_viewer(world, beam, mesh, steps: int):
    ps = init_polyscope(headless=False)
    m = ps.register_volume_mesh("beam", trusty.fem.positions(world, beam),
                                hexes=np.asarray(mesh.elements))
    m.set_edge_width(1.0)
    centres_x = np.asarray(mesh.vertices)[np.asarray(mesh.elements), 0].mean(axis=1)
    colors = np.where((centres_x > LENGTH / 2)[:, None], RUBBER_COLOR, STEEL_COLOR)
    m.add_color_quantity("material", colors, defined_on="cells", enabled=True)
    ps.reset_camera_to_home_view()

    state = {"i": 0, "playing": False}

    def callback():
        import polyscope.imgui as psim
        _, state["playing"] = psim.Checkbox("play", state["playing"])
        psim.SameLine()
        if (psim.Button("step") or state["playing"]) and state["i"] < steps:
            world.step()
            state["i"] += 1
            m.update_vertex_positions(trusty.fem.positions(world, beam))
        psim.Text(f"step {state['i']} / {steps}   tip sag {tip_sag(world, beam):.3f} m")

    ps.set_user_callback(callback)
    ps.show()


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--steps", type=int, default=100)
    ap.add_argument("--backend", default="auto", choices=["auto", "cpu", "accelerate", "cuda"])
    ap.add_argument("--no-viewer", action="store_true", help="headless: print the sag")
    args = ap.parse_args()

    world, beam, mesh = build_world(args.backend)
    if args.no_viewer:
        for _ in range(args.steps):
            world.step()
        print(f"tip sag after {args.steps} steps: {tip_sag(world, beam):.3f} m")
        return
    run_viewer(world, beam, mesh, args.steps)


if __name__ == "__main__":
    main()

Plasticity

Every material model but one is elastic: take the load away and the body returns to its rest shape. HenckyVonMises is plastic, the standard model for ductile metals such as steel and aluminium. It is elastic until its von Mises stress reaches the yield stress, then it flows, and the strain it takes while flowing stays when the load comes off. Here a square steel tube is twisted one and a half turns and bent into an arc between two grips, and keeps both when the right grip lets go:

The colour is the plastic strain, from steel grey where the tube never yielded to amber. The scene is described in Metal forming.

A plastic body takes the same add_hex_solid or add_tet_solid call as any other; only the material changes:

materials = [
    ("elastic", trusty.Hencky(youngs_modulus=E, poisson_ratio=NU)),
    ("plastic", trusty.HenckyVonMises(youngs_modulus=E, poisson_ratio=NU,
                                      yield_stress=YIELD,
                                      isotropic_hardening=ISOTROPIC_HARDENING,
                                      kinematic_hardening=KINEMATIC_HARDENING)),
]
Argument Meaning
youngs_modulus, poisson_ratio the elastic response, as for the other models
yield_stress Pa: the stress at which a bar pulled in tension first yields
isotropic_hardening Pa: how much the yield stress grows per unit of plastic strain
kinematic_hardening Pa: how far the yield surface moves toward the stress per unit of plastic strain

All five are required; pass 0.0 for a kind of hardening the metal should not have. Plastic bodies work with every mesh type, element order, time stepping and backend, and checkpoints save their plastic state. Embedded solids and subspace bodies take the elastic models only.

Yield and permanent strain

Two bars, one Hencky and one HenckyVonMises, are stretched and then brought back to their rest length. They agree until the plastic bar yields; after that it carries less stress, and back at its rest length it is in compression, because it has permanently grown longer.

Full script: python examples/fem/bar_pull_plastic.py
"""Two bars pulled past yield and released: one elastic, one plastic.

The plastic bar keeps the strain it took past yield, so back at its rest length
it is in compression. It is coloured by plastic strain.

Usage:
    python examples/fem/bar_pull_plastic.py              # live polyscope
    python examples/fem/bar_pull_plastic.py --no-viewer  # PNG frames
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path
from typing import NamedTuple

import numpy as np

import trusty

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils import init_polyscope   # noqa: E402

BAR_SIZE = (1.0, 0.1, 0.1)
BAR_RES  = (16, 1, 1)
E, NU    = 1.0e6, 0.0
# N/m^3 of pulled face: 10 times the half element's E / (h / 2), stiff against the bar
PIN_STIFFNESS = 10 * E / (0.5 * BAR_SIZE[0] / BAR_RES[0])
YIELD    = 1.0e4
ISOTROPIC_HARDENING = 6.0e4
KINEMATIC_HARDENING = 4.0e4
GAP      = 0.18              # y offset between the two bars (render only)
PULL     = 0.05              # peak stretch of the far face (5% strain)
PERIOD   = 160               # steps per pull/release cycle


class Bar(NamedTuple):
    label: str
    body: int
    pin: int


def build_world(backend: str):
    mesh = trusty.make_beam_hex_mesh(size=BAR_SIZE, res=BAR_RES)
    verts = np.asarray(mesh.vertices)
    x_min, x_max = float(verts[:, 0].min()), float(verts[:, 0].max())
    fixed = np.flatnonzero(np.abs(verts[:, 0] - x_min) < 1e-9).tolist()

    materials = [
        ("elastic", trusty.Hencky(youngs_modulus=E, poisson_ratio=NU)),
        ("plastic", trusty.HenckyVonMises(youngs_modulus=E, poisson_ratio=NU,
                                          yield_stress=YIELD,
                                          isotropic_hardening=ISOTROPIC_HARDENING,
                                          kinematic_hardening=KINEMATIC_HARDENING)),
    ]

    world = trusty.World(backend=backend,
                         gravity=(0.0, 0.0, 0.0),      # isolate the tensile response
                         time_stepping="static")
    bars = []
    for label, material in materials:
        body = trusty.fem.add_hex_solid(world, mesh, material, density=1000.0)
        trusty.constraints.add_pin(world, body, fixed)
        _, triangles = trusty.surface.mesh(world, body)
        pulled_faces = np.flatnonzero(verts[triangles][:, :, 0].min(axis=1) > x_max - 1e-9).tolist()
        face_rest = verts[np.unique(triangles[pulled_faces])].copy()
        pin = trusty.constraints.add_pin(
            world, body, faces=pulled_faces, targets=face_rest, stiffness=PIN_STIFFNESS)
        bars.append(Bar(label, body, pin))

    return world, bars, face_rest


def pull_targets(step: int, face_rest: np.ndarray):
    """Ramp to PULL over the first half of the period, back to zero over the second."""
    phase = (step % PERIOD) / PERIOD
    dx = PULL * (2.0 * phase if phase < 0.5 else 2.0 * (1.0 - phase))
    targets = face_rest.copy()
    targets[:, 0] += dx
    return targets


def axial_stress(world, pin) -> float:
    """Nominal axial stress (Pa) = reaction / rest cross-section."""
    forces = np.asarray(trusty.constraints.reaction_forces(world, pin))
    return float(forces[:, 0].sum()) / (BAR_SIZE[1] * BAR_SIZE[2])


def axial_strain(world, body, rest: np.ndarray) -> float:
    """Log strain over an interior stretch of the bar, away from the pinned faces."""
    x = np.asarray(trusty.fem.positions(world, body))
    lo, hi = 0.50 * BAR_SIZE[0], 0.75 * BAR_SIZE[0]
    at_lo = np.abs(rest[:, 0] - lo) < 1e-9
    at_hi = np.abs(rest[:, 0] - hi) < 1e-9
    return float(np.log((x[at_hi, 0].mean() - x[at_lo, 0].mean()) / (hi - lo)))


def _register_visuals(ps, world, bars):
    ps_meshes = []
    for i, bar in enumerate(bars):
        verts = np.asarray(trusty.fem.positions(world, bar.body)).copy()
        verts[:, 1] += i * GAP
        pm = ps.register_volume_mesh(bar.label, verts, hexes=np.asarray(trusty.fem.elements(world, bar.body)))
        pm.set_edge_width(1.0)
        ps_meshes.append(pm)
    return ps_meshes


def _update_visuals(ps_meshes, world, bars):
    for i, (pm, bar) in enumerate(zip(ps_meshes, bars)):
        verts = np.asarray(trusty.fem.positions(world, bar.body)).copy()
        verts[:, 1] += i * GAP
        pm.update_vertex_positions(verts)
    ps_meshes[1].add_scalar_quantity(
        "plastic strain", np.asarray(trusty.fem.plastic_strain(world, bars[1].body)),
        defined_on="vertices", cmap="viridis", enabled=True)


def _report(world, bars, rest):
    return [f"{bar.label}: stress = {axial_stress(world, bar.pin):9.1f} Pa  "
            f"strain = {axial_strain(world, bar.body, rest):7.4f}" for bar in bars]


def run_polyscope(backend: str, steps: int):
    ps = init_polyscope(headless=False)
    world, bars, face_rest = build_world(backend)
    rest = np.asarray(trusty.fem.positions(world, bars[0].body))
    ps_meshes = _register_visuals(ps, world, bars)
    state = {"i": 0, "playing": False}

    def callback():
        import polyscope.imgui as psim
        _, state["playing"] = psim.Checkbox("play", state["playing"])
        psim.SameLine()
        if (psim.Button("step") or state["playing"]) and state["i"] < steps:
            for bar in bars:
                trusty.constraints.set_pin_targets(
                    world, bar.pin, pull_targets(state["i"], face_rest))
            world.step()
            state["i"] += 1
            _update_visuals(ps_meshes, world, bars)
        psim.Text(f"step {state['i']} / {steps}  (yield stress {YIELD:.0f} Pa)")
        for line in _report(world, bars, rest):
            psim.Text(line)

    ps.set_user_callback(callback)
    ps.show()


def run_screenshots(backend: str, n_steps: int, out_dir: Path):
    ps = init_polyscope(headless=True)
    out_dir.mkdir(parents=True, exist_ok=True)
    world, bars, face_rest = build_world(backend)
    rest = np.asarray(trusty.fem.positions(world, bars[0].body))
    ps_meshes = _register_visuals(ps, world, bars)
    ps.reset_camera_to_home_view()

    for i in range(n_steps):
        for bar in bars:
            trusty.constraints.set_pin_targets(
                world, bar.pin, pull_targets(i, face_rest))
        world.step()
        _update_visuals(ps_meshes, world, bars)
        ps.screenshot(str(out_dir / f"bar_pull_plastic_{i:04d}.png"),
                      transparent_bg=False)
        if i % 10 == 0 or i == n_steps - 1:
            print(f"step {i:4d}  " + " | ".join(_report(world, bars, rest)))
    print(f"Wrote {n_steps} screenshots to {out_dir}/")


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--steps", type=int, default=PERIOD,
                    help=f"{PERIOD} steps per pull and release")
    ap.add_argument("--backend", default="auto", choices=["auto", "cpu", "accelerate", "cuda"])
    ap.add_argument("--no-viewer", action="store_true",
                    help="headless: write PNG screenshots instead of showing polyscope")
    ap.add_argument("--out", type=Path, default=Path("out_bar_pull_plastic"))
    args = ap.parse_args()

    if args.no_viewer:
        run_screenshots(args.backend, args.steps, args.out)
    else:
        run_polyscope(args.backend, args.steps)


if __name__ == "__main__":
    main()

Hardening

Isotropic hardening grows the yield surface; kinematic hardening moves it along with the stress, so the metal yields again sooner when the load reverses. Two cantilevers are bent up and down five times, with the same hardening modulus used once each way:

materials = [
    ("kinematic hardening", 0.0, HARDENING),
    ("isotropic hardening", HARDENING, 0.0),
]
for label, isotropic, kinematic in materials:
    material = trusty.HenckyVonMises(youngs_modulus=E, poisson_ratio=NU,
                                     yield_stress=YIELD,
                                     isotropic_hardening=isotropic,
                                     kinematic_hardening=kinematic)

The kinematic bar keeps yielding on every cycle; the isotropic bar yields less each time and settles into an elastic response. After five cycles, kinematic in front, coloured by plastic strain on one scale:

Two cantilevers after five bending cycles, coloured by plastic strain

Full script: python examples/fem/bar_bend_plastic.py
"""Two cantilevers bent back and forth: kinematic vs isotropic hardening.

The kinematic bar keeps yielding every cycle; the isotropic one yields less
each time and settles into an elastic response. Coloured by plastic strain.

Usage:
    python examples/fem/bar_bend_plastic.py              # live polyscope
    python examples/fem/bar_bend_plastic.py --no-viewer  # PNG frames
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np

import trusty

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils import init_polyscope   # noqa: E402

BAR_SIZE  = (0.4, 0.1, 0.08)
BAR_RES   = (8, 1, 4)        # 4 through the thickness, to resolve the strain profile
E, NU     = 1.0e6, 0.0
# N/m^3 of tip face: 10 times the half element's E / (h / 2), stiff against the bar
PIN_STIFFNESS = 10 * E / (0.5 * BAR_SIZE[0] / BAR_RES[0])
YIELD     = 1.0e4
HARDENING = 1.0e5
GAP       = 0.18             # y offset between the two bars (render only)
AMPLITUDE = 0.030            # peak tip deflection in z
PERIOD    = 80               # steps per full bend cycle


def build_world(backend: str):
    mesh = trusty.make_beam_hex_mesh(size=BAR_SIZE, res=BAR_RES)
    verts = np.asarray(mesh.vertices)
    x_min, x_max = float(verts[:, 0].min()), float(verts[:, 0].max())
    fixed = np.flatnonzero(np.abs(verts[:, 0] - x_min) < 1e-9).tolist()

    world = trusty.World(backend=backend,
                         gravity=(0.0, 0.0, 0.0),      # isolate the imposed bend
                         time_stepping="static")
    bars = []
    materials = [
        ("kinematic hardening", 0.0, HARDENING),
        ("isotropic hardening", HARDENING, 0.0),
    ]
    for label, isotropic, kinematic in materials:
        material = trusty.HenckyVonMises(youngs_modulus=E, poisson_ratio=NU,
                                         yield_stress=YIELD,
                                         isotropic_hardening=isotropic,
                                         kinematic_hardening=kinematic)
        body = trusty.fem.add_hex_solid(world, mesh, material, density=1000.0)
        trusty.constraints.add_pin(world, body, fixed)
        _, triangles = trusty.surface.mesh(world, body)
        tip_faces = np.flatnonzero(verts[triangles][:, :, 0].min(axis=1) > x_max - 1e-9).tolist()
        tip_rest = verts[np.unique(triangles[tip_faces])].copy()
        pin = trusty.constraints.add_pin(
            world, body, faces=tip_faces, targets=tip_rest, stiffness=PIN_STIFFNESS)
        bars.append((label, body, pin))

    return world, bars, tip_rest


def bend_targets(step: int, tip_rest: np.ndarray):
    dz = AMPLITUDE * np.sin(2.0 * np.pi * step / PERIOD)
    targets = tip_rest.copy()
    targets[:, 2] += dz
    return targets


def _register_visuals(ps, world, bars):
    ps_meshes = []
    for i, (label, body, _) in enumerate(bars):
        verts = np.asarray(trusty.fem.positions(world, body)).copy()
        verts[:, 1] += i * GAP
        pm = ps.register_volume_mesh(label, verts, hexes=np.asarray(trusty.fem.elements(world, body)))
        pm.set_edge_width(1.0)
        ps_meshes.append(pm)
    return ps_meshes


def _update_visuals(ps_meshes, world, bars):
    fields = [np.asarray(trusty.fem.plastic_strain(world, body)) for _, body, _ in bars]
    hi = max(1e-4, max(float(f.max()) for f in fields))
    for i, (pm, (_, body, _)) in enumerate(zip(ps_meshes, bars)):
        verts = np.asarray(trusty.fem.positions(world, body)).copy()
        verts[:, 1] += i * GAP
        pm.update_vertex_positions(verts)
        pm.add_scalar_quantity("plastic strain", fields[i], defined_on="vertices",
                               vminmax=(0.0, hi), cmap="viridis", enabled=True)


def _peaks(world, bars):
    return [float(np.max(trusty.fem.plastic_strain(world, body))) for _, body, _ in bars]


def run_polyscope(backend: str, steps: int):
    ps = init_polyscope(headless=False)
    world, bars, tip_rest = build_world(backend)
    ps_meshes = _register_visuals(ps, world, bars)
    state = {"i": 0, "playing": False}

    def callback():
        import polyscope.imgui as psim
        _, state["playing"] = psim.Checkbox("play", state["playing"])
        psim.SameLine()
        if (psim.Button("step") or state["playing"]) and state["i"] < steps:
            for _, _, pin in bars:
                trusty.constraints.set_pin_targets(
                    world, pin, bend_targets(state["i"], tip_rest))
            world.step()
            state["i"] += 1
            _update_visuals(ps_meshes, world, bars)
        psim.Text(f"step {state['i']} / {steps}  cycle {state['i'] / PERIOD:.2f}")
        for (label, _, _), peak in zip(bars, _peaks(world, bars)):
            psim.Text(f"{label}: peak plastic strain = {peak:.5f}")

    ps.set_user_callback(callback)
    ps.show()


def run_screenshots(backend: str, n_steps: int, out_dir: Path):
    ps = init_polyscope(headless=True)
    out_dir.mkdir(parents=True, exist_ok=True)
    world, bars, tip_rest = build_world(backend)
    ps_meshes = _register_visuals(ps, world, bars)
    ps.reset_camera_to_home_view()

    for i in range(n_steps):
        for _, _, pin in bars:
            trusty.constraints.set_pin_targets(
                world, pin, bend_targets(i, tip_rest))
        world.step()
        _update_visuals(ps_meshes, world, bars)
        ps.screenshot(str(out_dir / f"bar_bend_plastic_{i:04d}.png"),
                      transparent_bg=False)
        if (i + 1) % PERIOD == 0:
            print(f"cycle {(i + 1) // PERIOD} peak plastic strain: " + "  ".join(
                f"{label} {peak:.5f}" for (label, _, _), peak in zip(bars, _peaks(world, bars))))
    print(f"Wrote {n_steps} screenshots to {out_dir}/")


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--steps", type=int, default=5 * PERIOD,
                    help=f"{PERIOD} steps per bend cycle; the two bars part over the first few")
    ap.add_argument("--backend", default="auto", choices=["auto", "cpu", "accelerate", "cuda"])
    ap.add_argument("--no-viewer", action="store_true",
                    help="headless: write PNG screenshots instead of showing polyscope")
    ap.add_argument("--out", type=Path, default=Path("out_bar_bend_plastic"))
    args = ap.parse_args()

    if args.no_viewer:
        run_screenshots(args.backend, args.steps, args.out)
    else:
        run_polyscope(args.backend, args.steps)


if __name__ == "__main__":
    main()

Reading plastic strain

plastic_strain(world, body) returns the accumulated equivalent plastic strain: zero until the body first yields, and it only grows. It is per node by default, matching positions, and per element with nodal=False:

def _peaks(world, bars):
    return [float(np.max(trusty.fem.plastic_strain(world, body))) for _, body, _ in bars]

It raises for a body with no plastic element, and reads 0 on the elastic elements of one that mixes. The stress readouts under Visualizing stress read a plastic body too, at its current plastic state.

Graded plastic materials

trusty.HenckyVonMises grades the same way as the elastic models (see Graded materials): yield_stress, isotropic_hardening and kinematic_hardening, like youngs_modulus and poisson_ratio, each take a number or one value per element. A region with a lower yield stress yields first. Every argument is in the trusty reference.

Mesh types

Solids are built on hexahedral (HexMesh, 8-node bricks) or tetrahedral (TetMesh, 4-node tets) meshes.

Hex Tet
Structured beam make_beam_hex_mesh(size, res) make_beam_tet_mesh(size, res)
From NumPy arrays make_hex_mesh(vertices, hexes) make_tet_mesh(vertices, tets)
From a file read_tet_msh(path) (Gmsh 2.2)
Add to a world fem.add_hex_solid fem.add_tet_solid

Hexes are efficient for box-like shapes; tets fit any shape. To simulate your own geometry, tetrahedralize it with a tool such as fTetWild, TetGen or Gmsh, then load it from a .msh file or pass its arrays to make_tet_mesh. transform_mesh(mesh, A, t) places a mesh before you add it. To start a body away from its rest shape, so that it relaxes toward the mesh when stepped, pass the start vertices as initial_positions, one row per vertex of the mesh.

# Structured beams, built in: (Lx, Ly, Lz) and elements per axis.
hex_mesh = trusty.make_beam_hex_mesh(size=(1.0, 0.1, 0.1), res=(20, 2, 2))
tet_mesh = trusty.make_beam_tet_mesh(size=(1.0, 0.1, 0.1), res=(20, 2, 2))

# Your own tet mesh, from a Gmsh .msh file (format 2.2) ...
loaded = trusty.read_tet_msh(str(mesh_path))
# ... or from NumPy arrays, e.g. produced by TetGen, fTetWild or meshio.
loaded = trusty.make_tet_mesh(loaded.vertices, loaded.elements)

# Place each mesh before adding it: rotate with A, translate with t.
tet_mesh = trusty.transform_mesh(tet_mesh, t=(0.0, 0.0, -0.3))
loaded = trusty.transform_mesh(loaded, t=(1.3, 0.05, -0.1))

The sample ball is examples/data/ball.msh. Try your own mesh with python examples/fem/mesh_types.py --mesh my_mesh.msh.

Full script: python examples/fem/mesh_types.py
"""Hex and tet meshes: built-in beams, and a tet mesh loaded from a file.

Builds one world with a structured hex beam, a structured tet beam and a tet
ball read from ``data/ball.msh`` (Gmsh format 2.2), the way you would load your
own tetrahedralized geometry. Nothing is pinned, so stepping
lets all three fall under gravity.

Usage:
    python examples/fem/mesh_types.py                   # live polyscope
    python examples/fem/mesh_types.py --no-viewer       # print mesh sizes
    python examples/fem/mesh_types.py --mesh my.msh     # your own tet mesh
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np

import trusty

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils import init_polyscope  # noqa: E402

DATA = Path(__file__).resolve().parent.parent / "data"
COLORS = {"hex beam": (0.94, 0.33, 0.31), "tet beam": (0.78, 0.79, 0.84),
          "loaded mesh": (0.35, 0.75, 0.70)}


def build_world(mesh_path: Path = DATA / "ball.msh", backend: str = "auto"):
    # Structured beams, built in: (Lx, Ly, Lz) and elements per axis.
    hex_mesh = trusty.make_beam_hex_mesh(size=(1.0, 0.1, 0.1), res=(20, 2, 2))
    tet_mesh = trusty.make_beam_tet_mesh(size=(1.0, 0.1, 0.1), res=(20, 2, 2))

    # Your own tet mesh, from a Gmsh .msh file (format 2.2) ...
    loaded = trusty.read_tet_msh(str(mesh_path))
    # ... or from NumPy arrays, e.g. produced by TetGen, fTetWild or meshio.
    loaded = trusty.make_tet_mesh(loaded.vertices, loaded.elements)

    # Place each mesh before adding it: rotate with A, translate with t.
    tet_mesh = trusty.transform_mesh(tet_mesh, t=(0.0, 0.0, -0.3))
    loaded = trusty.transform_mesh(loaded, t=(1.3, 0.05, -0.1))

    world = trusty.World(backend=backend)
    material = trusty.StableNeoHookean(youngs_modulus=1e6, poisson_ratio=0.3)
    bodies = {
        "hex beam":    trusty.fem.add_hex_solid(world, hex_mesh, material, density=1000.0),
        "tet beam":    trusty.fem.add_tet_solid(world, tet_mesh, material, density=1000.0),
        "loaded mesh": trusty.fem.add_tet_solid(world, loaded, material, density=1000.0),
    }
    return world, bodies, {"hex beam": hex_mesh, "tet beam": tet_mesh,
                           "loaded mesh": loaded}


def run_viewer(world, bodies, meshes, steps: int):
    ps = init_polyscope(headless=False)
    shown = {}
    for name, body in bodies.items():
        mesh = meshes[name]
        cells = {"hexes": np.asarray(mesh.elements)} if hasattr(mesh, "hexes") \
            else {"tets": np.asarray(mesh.elements)}
        m = ps.register_volume_mesh(name, trusty.fem.positions(world, body), **cells)
        m.set_color(COLORS[name])
        m.set_edge_width(1.0)
        shown[name] = (m, body)
    ps.reset_camera_to_home_view()

    state = {"i": 0, "playing": False}

    def callback():
        import polyscope.imgui as psim
        _, state["playing"] = psim.Checkbox("play (fall under gravity)", state["playing"])
        psim.SameLine()
        if (psim.Button("step") or state["playing"]) and state["i"] < steps:
            world.step()
            state["i"] += 1
            for m, body in shown.values():
                m.update_vertex_positions(trusty.fem.positions(world, body))
        psim.Text(f"step {state['i']} / {steps}")

    ps.set_user_callback(callback)
    ps.show()


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--mesh", type=Path, default=DATA / "ball.msh",
                    help="tet mesh to load (Gmsh .msh, format 2.2)")
    ap.add_argument("--steps", type=int, default=60)
    ap.add_argument("--backend", default="auto", choices=["auto", "cpu", "accelerate", "cuda"])
    ap.add_argument("--no-viewer", action="store_true",
                    help="headless: print each mesh's size")
    args = ap.parse_args()

    world, bodies, meshes = build_world(args.mesh, args.backend)
    if args.no_viewer:
        for name, mesh in meshes.items():
            print(f"{name:<12} {mesh.num_nodes:5d} nodes  {mesh.num_elems:5d} elements")
        return
    run_viewer(world, bodies, meshes, args.steps)


if __name__ == "__main__":
    main()

A hex beam, a tet beam and a tet ball loaded from a file

Element order

Both mesh types support linear and quadratic elements, set with order:

ElementOrder Hex Tet
Linear (default) Q1, 8 nodes P1, 4 nodes
Quadratic Q2, 27 nodes P2, 10 nodes
QuadraticSerendipity Q2 serendipity, 20 nodes —
if kind == "hex":
    return trusty.fem.add_hex_solid(world, mesh, material, density, order=order)
return trusty.fem.add_tet_solid(world, mesh, material, density, order=order)

Pass the ordinary linear mesh: quadratic orders add the extra nodes themselves. Linear elements are cheaper but lock in bending on coarse meshes, which makes the body too stiff. Quadratic elements bend correctly with far fewer elements. Below are five coarse beams (6 × 1 × 1 elements). From front to back: hex Q1, tet P1, tet P2, hex Q2 serendipity, hex Q2. The linear tet beam locks worst and barely sags; all three quadratic beams agree.

Five cantilevers, one per element type and order

Full script: python examples/bending_locking.py
"""Higher-order (P2/Q2) FEM demo: quadratic elements resist bending locking.

Builds one world with a cantilever beam per element family, laid out side by
side, all pinned at x=0 and sagging under gravity. Linear Q1/P1 elements lock
(under-deflect) on a coarse mesh; the quadratic P2 tet and Q2 hexes bend much
more freely. Quadratic bodies are rendered via the same linear sub-triangle
tessellation of their curved surface that contact uses
(the triangles of `surface.mesh(world, body)`).

Usage:
    python examples/bending_locking.py                # live polyscope
    python examples/bending_locking.py --no-viewer    # print comparison
    python examples/bending_locking.py --res 8 1 1    # finer corner mesh
"""

from __future__ import annotations

import argparse

import numpy as np

import trusty
from utils import init_polyscope

ORDER = trusty.fem.ElementOrder

# label -> (mesh kind, element order, color)
FAMILIES = {
    "hex_q1":             ("hex", ORDER.Linear,               (0.6, 0.6, 0.6)),
    "tet_p1":             ("tet", ORDER.Linear,               (0.4, 0.5, 0.7)),
    "tet_p2":             ("tet", ORDER.Quadratic,            (0.9, 0.6, 0.2)),
    "hex_q2_serendipity": ("hex", ORDER.QuadraticSerendipity, (0.3, 0.7, 0.4)),
    "hex_q2":             ("hex", ORDER.Quadratic,            (0.8, 0.3, 0.3)),
}


def add_body(world, kind, order, mesh, material, density):
    if kind == "hex":
        return trusty.fem.add_hex_solid(world, mesh, material, density, order=order)
    return trusty.fem.add_tet_solid(world, mesh, material, density, order=order)


def build_world(size, res, backend="auto"):
    material = trusty.StableNeoHookean(youngs_modulus=1e6, poisson_ratio=0.3)
    spacing = 1.5 * size[1]

    world = trusty.World(backend=backend,
                         timestep=1.0 / 30.0,
                         time_stepping="quasi_static",
                         newton=trusty.NewtonConfig(tolerance=1e-5))
    bodies = {}
    for k, (family, (kind, order, _)) in enumerate(FAMILIES.items()):
        mesh = (trusty.make_beam_hex_mesh(size=size, res=res) if kind == "hex"
                else trusty.make_beam_tet_mesh(size=size, res=res))
        # Shift in +y only, so the x=0 pin still lands on the fixed face.
        mesh = trusty.transform_mesh(mesh, t=(0.0, k * spacing, 0.0))
        body = add_body(world, kind, order, mesh, material, 1000.0)
        X = np.asarray(trusty.fem.positions(world, body))
        trusty.constraints.add_pin(world, body, np.flatnonzero(np.abs(X[:, 0]) < 1e-6).tolist())
        bodies[family] = body

    return world, bodies


def tip_deflection(world, body):
    verts = np.asarray(trusty.fem.positions(world, body))
    tip = verts[:, 0] > verts[:, 0].max() - 1e-3
    return float(-verts[tip, 2].max())  # downward deflection (+ = down)


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--res", type=int, nargs=3, default=[6, 1, 1])
    parser.add_argument("--steps", type=int, default=200)
    parser.add_argument("--backend", choices=["auto", "cpu", "accelerate", "cuda"], default="auto")
    parser.add_argument("--no-viewer", action="store_true",
                        help="headless: print the tip-deflection comparison instead of polyscope")
    args = parser.parse_args()

    size = (1.0, 0.1, 0.1)
    world, bodies = build_world(size, tuple(args.res), args.backend)

    if args.no_viewer:
        for _ in range(args.steps):
            world.step()
        print(f"Cantilever {size} at corner res {tuple(args.res)}, {args.steps} steps")
        print(f"{'family':<20} {'nodes':>7} {'tip deflection (m)':>20}")
        for family, body in bodies.items():
            n = np.asarray(trusty.fem.positions(world, body)).shape[0]
            print(f"{family:<20} {n:>7} {tip_deflection(world, body):>20.5e}")
        return

    run_viewer(world, bodies, args.steps)


def run_viewer(world, bodies, steps):
    ps = init_polyscope(headless=False)
    meshes = {}
    for family, body in bodies.items():
        V = np.asarray(trusty.fem.positions(world, body)).copy()
        _, F = trusty.surface.mesh(world, body)
        m = ps.register_surface_mesh(family, V, F)
        m.set_color(FAMILIES[family][2])
        meshes[family] = (m, body)
    ps.reset_camera_to_home_view()

    state = {"i": 0, "playing": False}

    def callback():
        import polyscope.imgui as psim
        _, state["playing"] = psim.Checkbox("play", state["playing"])
        psim.SameLine()
        if (psim.Button("step") or state["playing"]) and state["i"] < steps:
            world.step()
            state["i"] += 1
            for _family, (m, body) in meshes.items():
                m.update_vertex_positions(np.asarray(trusty.fem.positions(world, body)))
        psim.Text(f"step {state['i']} / {steps}")
        report = world.last_report()
        psim.Text(f"last solve: iters={report.iterations}  "
                  f"residual={report.final_residual:.3e}")

    ps.set_user_callback(callback)
    ps.show()


if __name__ == "__main__":
    main()

A quadratic body runs on its consistent mass matrix by default; consistent_mass=False lumps its mass onto the nodes instead. Linear bodies always lump their mass.

Quadratic bodies have more nodes than their input mesh. positions returns all of them, and the triangles F of trusty.surface.mesh(world, body) are a triangulation of the curved surface, indexed into those positions, for rendering.

Visualizing stress

Function Returns
positions(world, body) current node positions, (num_nodes, 3)
elements(world, body) element connectivity into positions, (num_elements, k): k = 4, 8, 10, 20 or 27 by discretization
surface_positions(world, body) current surface vertex positions, the rows trusty.surface.mesh(world, body) indexes
trusty.surface.mesh(world, body) the rest boundary (V, F); F indexes surface_positions, (F, 3)
von_mises(world, body) von Mises stress in Pa, per node (or per element with nodal=False)
strain_energy_density(world, body) strain energy density in J/m³, likewise
equivalent_strain(world, body) equivalent log strain (dimensionless), likewise
cauchy_stress(world, body) Cauchy stress tensor in Pa, per element, (num_elements, 3, 3)
plastic_strain(world, body) accumulated plastic strain of a plastic body, per node (or per element with nodal=False)

The von Mises, strain energy and equivalent strain readouts take nodal= (a smooth per-node field, or raw per-element values). The equivalent strain is \(\sqrt{\tfrac{2}{3}\, e_{\text{dev}} : e_{\text{dev}}}\), where \(e_{\text{dev}} = e - \tfrac{1}{3}(\operatorname{tr} e)\, I\) is the deviatoric (shape-changing) part of the log strain \(e = \tfrac{1}{2}\log(F^\top F)\). It reads the deformation alone, so soft and stiff regions compare directly, and pure volume change reads 0:

return {
    FIELDS[0]: np.asarray(trusty.fem.von_mises(world, body, nodal=True)),
    FIELDS[1]: np.asarray(trusty.fem.strain_energy_density(world, body, nodal=True)),
    FIELDS[2]: np.asarray(trusty.fem.equivalent_strain(world, body, nodal=True)),
}

cauchy_stress keeps the whole tensor. The normal stress across a plane with unit normal n is n @ sigma @ n, negative in compression, so the elements under a loaded face report the pressure they carry.

The arrays are plain NumPy, so they go straight into polyscope as scalar quantities. Below, a soft block is squeezed 30% between two clamped plates and cut open at its mid-plane: von Mises on the left, strain energy density on the right. The clamped faces cannot spread, so the block bulges. Both fields are highest in the band through the middle and lowest under the centre of each plate, where the material is squeezed almost equally from every side. Von Mises ignores that equal squeezing (pressure) and strain energy includes it. Use von Mises for yielding and strain energy when pressure matters.

A squeezed block cut open, coloured by von Mises and by strain energy

Full script: python examples/fem/visualize_stress.py
"""Von Mises, strain energy density and equivalent strain on a squeezed block.

A soft, nearly incompressible block (E = 500 kPa, nu = 0.45) is clamped at its
bottom face and its top face is pushed down 30% by a moving pin. The clamped
faces cannot spread sideways, so the block bulges at mid-height and the stress
varies through it: highest in the bulging middle band, lowest under the plate
centres, where the material is squeezed almost equally from every side. The
three readouts measure different things:

  * **von Mises** is *deviatoric*: it discards the hydrostatic (pressure) part
    of the stress. It is the measure for yielding and failure.
  * **strain energy density** includes the volumetric term, so it also counts
    how hard the material is being squeezed.
  * **equivalent strain** is the deviatoric log strain, read from the
    deformation alone, so soft and stiff regions are directly comparable.

All three take `nodal=` (True: a smooth per-node field; False: raw per-element
values).

Usage:
    python examples/fem/visualize_stress.py              # live polyscope
    python examples/fem/visualize_stress.py --no-viewer  # print ranges
    python examples/fem/visualize_stress.py --squeeze 0.4
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np

import trusty

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils import init_polyscope  # noqa: E402

SIZE = 0.2                      # block edge (m)
RES = 10                        # hexes per edge
E, NU = 5.0e5, 0.45             # soft and nearly incompressible
PLATE_STIFFNESS = 1e8           # N/m^3 of pressed face; stiff enough to act as a rigid plate

FIELDS = ("von Mises (Pa)", "strain energy (J/m^3)", "equivalent strain")


def read_fields(world, body):
    """The three readouts, per node, for one body."""
    return {
        FIELDS[0]: np.asarray(trusty.fem.von_mises(world, body, nodal=True)),
        FIELDS[1]: np.asarray(trusty.fem.strain_energy_density(world, body, nodal=True)),
        FIELDS[2]: np.asarray(trusty.fem.equivalent_strain(world, body, nodal=True)),
    }


class Press:
    """The block and the moving top plate that squeezes it."""

    def __init__(self, backend: str = "auto"):
        self.world = trusty.World(backend=backend,
                                  time_stepping="static",   # solve equilibrium each step
                                  gravity=(0.0, 0.0, 0.0),  # the plates are the only load
                                  newton=trusty.NewtonConfig(max_iters=60))

        mesh = trusty.make_beam_hex_mesh(size=(SIZE, SIZE, SIZE), res=(RES, RES, RES))
        self.mesh = mesh
        material = trusty.StableNeoHookean(youngs_modulus=E, poisson_ratio=NU)
        self.body = trusty.fem.add_hex_solid(self.world, mesh, material, density=1000.0)

        # Bottom face clamped; top face held by a pin whose targets move down.
        X = np.asarray(mesh.vertices)
        trusty.constraints.add_pin(
            self.world, self.body, np.flatnonzero(np.abs(X[:, 2]) < 1e-6).tolist())
        _, triangles = trusty.surface.mesh(self.world, self.body)
        top = np.flatnonzero(X[triangles][:, :, 2].min(axis=1) > SIZE - 1e-9).tolist()
        self.top = np.unique(triangles[top])
        self.top_rest = X[self.top].copy()
        self.pin = trusty.constraints.add_pin(
            self.world, self.body, faces=top, targets=self.top_rest, stiffness=PLATE_STIFFNESS)

    def squeeze_to(self, fraction: float):
        """Move the top plate down to `fraction` of the height and solve."""
        targets = self.top_rest.copy()
        targets[:, 2] -= fraction * SIZE
        trusty.constraints.set_pin_targets(self.world, self.pin, targets)
        self.world.step()

    def squeeze(self, fraction: float, steps: int):
        """Reach `fraction` in `steps` equal increments."""
        for k in range(1, steps + 1):
            self.squeeze_to(fraction * k / steps)


def report(press):
    width = max(len(f) for f in FIELDS)
    x = np.asarray(trusty.fem.positions(press.world, press.body))
    print(f"height {x[press.top, 2].mean():.3f} m (rest {SIZE} m), "
          f"width {x[:, 0].max() - x[:, 0].min():.3f} m (rest {SIZE} m)")
    for name, values in read_fields(press.world, press.body).items():
        print(f"  {name:<{width}}  min={values.min():10.4g}  max={values.max():10.4g}")


def run_viewer(press, fraction: float, steps: int):
    ps = init_polyscope(headless=False)
    m = ps.register_volume_mesh(
        "block", trusty.fem.positions(press.world, press.body),
        hexes=np.asarray(press.mesh.elements))
    m.set_edge_width(1.0)

    def refresh():
        m.update_vertex_positions(trusty.fem.positions(press.world, press.body))
        for name, values in read_fields(press.world, press.body).items():
            m.add_scalar_quantity(name, values, defined_on="vertices",
                                  cmap="viridis", enabled=(name == FIELDS[0]))

    state = {"i": 0, "playing": False}
    refresh()
    ps.reset_camera_to_home_view()

    def callback():
        import polyscope.imgui as psim
        _, state["playing"] = psim.Checkbox("play (squeeze)", state["playing"])
        psim.SameLine()
        if (psim.Button("step") or state["playing"]) and state["i"] < steps:
            state["i"] += 1
            press.squeeze_to(fraction * state["i"] / steps)
            refresh()
        psim.Text(f"squeeze {100 * fraction * state['i'] / steps:.0f}% "
                  f"(step {state['i']} / {steps})")
        psim.Text("Switch fields under the block's Scalar Quantities.")

    ps.set_user_callback(callback)
    ps.show()


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--squeeze", type=float, default=0.3,
                    help="fraction of the height the top plate moves down")
    ap.add_argument("--steps", type=int, default=10,
                    help="load increments to reach the full squeeze")
    ap.add_argument("--backend", default="auto", choices=["auto", "cpu", "accelerate", "cuda"])
    ap.add_argument("--no-viewer", action="store_true",
                    help="headless: squeeze fully, then print the field ranges")
    args = ap.parse_args()

    press = Press(args.backend)
    if args.no_viewer:
        press.squeeze(args.squeeze, args.steps)
        report(press)
        return
    run_viewer(press, args.squeeze, args.steps)


if __name__ == "__main__":
    main()

Embedded solids

trusty.fem.add_embedded_solid simulates a solid from a triangle surface alone. The surface is filled with a regular grid of hexes (voxelized), the hexes carry the simulation, and the surface rides along inside them. There is no tet meshing step, and the surface can be far finer than the grid.

Building one

A bar clamped at one end, swinging down under gravity:

world = trusty.World(backend=backend,
                     timestep=1.0 / 60.0,
                     newton=trusty.NewtonConfig(max_iters=60, tolerance=1e-4),
                     time_stepping="bdf2")
# V (n, 3) and F (m, 3): the triangle surface. It is filled with hexes
# of edge voxel_size, which carry the simulation.
body = trusty.fem.add_embedded_solid(
    world, V, F, voxel_size=voxel_size, material=material, density=1000.0,
    order=order)

# Stiffness per unit rest area (N/m^3): Young's modulus over the glue thickness.
trusty.constraints.add_pin(
    world, body, faces=pin_faces,
    stiffness=youngs / (GLUE_FRAC * bbox.max()))

Embedded bar bending under gravity, inside its hex grid

add_embedded_solid voxelizes the surface and returns the body id. The grey lines are the hex grid; the red surface is the input mesh, moved by it.

Argument Meaning
V, F the surface: vertices (n, 3) and triangles (m, 3), closed and consistently wound
voxel_size hex edge length, in the units of V; see The voxel grid
material any material model but HenckyVonMises
density kg/m³
sizing_field, max_level optional local refinement; see Adaptive refinement
order ElementOrder of the hexes, as for any solid

The clamp is a compliant pin on the end cap; see Pins.

Full script: python examples/embedded/embedded_cantilever.py
"""Voxelized cantilever sagging under gravity.

A triangle-surface mesh (either a procedurally-generated rectangular bar
or one loaded from disk via --mesh) is voxelized, one end clamped to its
rest positions, and the free end sags under gravity. The clamp is
compliant: it holds the end cap like a thin layer of glue, so the cap
gives slightly under load.

Usage:
    python examples/embedded/embedded_cantilever.py                    # built-in bar
    python examples/embedded/embedded_cantilever.py --mesh bunny.obj   # custom mesh
    python examples/embedded/embedded_cantilever.py --no-viewer        # write PNG frames
    python examples/embedded/embedded_cantilever.py --steps 240
    python examples/embedded/embedded_cantilever.py --order q2         # quadratic (Q2) elements
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np

import trusty

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils import (  # noqa: E402
    init_polyscope,
    load_mesh,
    make_bar_trimesh,
    mean_edge_length,
    rescale_mesh,
)

ORDER = trusty.fem.ElementOrder
# CLI order name -> voxel-hex element order (Q1/Q2 Lagrange/Q2 serendipity).
HEX_ORDERS = {
    "linear": ORDER.Linear,
    "q2":     ORDER.Quadratic,
    "q2s":    ORDER.QuadraticSerendipity,
}


# --- Geometry: a simple axis-aligned bar, 1.0 × 0.2 × 0.2 units -----------
BAR_SIZE = (1.0, 0.2, 0.2)
BAR_FACE_RES = (16, 4, 4)   # surface triangulation resolution per dimension

# The voxelizer's hex edge length is derived from the input mesh's average
# surface-edge length multiplied by this factor.
VOXEL_FACTOR = 1.5

# Pin all triangles whose *centroid* sits in the leftmost slice of the
# mesh's x-extent (fraction of (x_max − x_min)). Centroid-based
# selection works for both axis-aligned faces (every centroid coincides
# with x_min) and organic meshes where no single triangle has all three
# vertices in a tight band.
PIN_BAND_FRAC = 5e-2

# Thickness of the glue layer the clamp acts like, as a fraction of the body's size.
GLUE_FRAC = 0.01


def pinned_face_indices(V: np.ndarray, F: np.ndarray) -> list[int]:
    """Triangles whose centroid sits in the first `PIN_BAND_FRAC` of the
    mesh's x-extent. Works uniformly for axis-aligned faces (every
    centroid is exactly at x_min) and organic meshes (no dependence on
    vertex-count density)."""
    x_min = float(V[:, 0].min())
    x_max = float(V[:, 0].max())
    band = PIN_BAND_FRAC * (x_max - x_min)
    centroids_x = V[F, 0].mean(axis=1)
    return np.flatnonzero(centroids_x - x_min < band).astype(int).tolist()


def build_world(
    backend: str = "auto",
    *,
    mesh_path: Path | None = None,
    voxel_factor: float = VOXEL_FACTOR,
    youngs: float = 2e6,
    rescale_to: float | None = None,
    order=ORDER.Linear,
):

    if mesh_path is not None:
        V, F = load_mesh(mesh_path)
        if rescale_to is not None:
            V = rescale_mesh(V, rescale_to)
        else:
            # Always translate so bbox min is at origin (gravity axis = z,
            # cantilever axis = x, pin face = -x of bbox).
            V = V - V.min(axis=0)
        bbox = V.max(axis=0) - V.min(axis=0)
        print(f"[mesh] {mesh_path.name}  verts={len(V)}  tris={len(F)}  "
              f"bbox_extent={tuple(round(x, 4) for x in bbox)}")
    else:
        V, F = make_bar_trimesh(BAR_SIZE, BAR_FACE_RES)
        bbox = V.max(axis=0) - V.min(axis=0)

    pin_faces = pinned_face_indices(V, F)
    if not pin_faces:
        raise SystemExit(
            f"No pinned faces found — mesh has no triangle centroids in "
            f"the first {PIN_BAND_FRAC:.1%} of its x-extent "
            f"[{V[:, 0].min():.4f}, {V[:, 0].max():.4f}]. "
            "Bump PIN_BAND_FRAC in the example source.")
    print(f"[pin] {len(pin_faces)} triangles pinned near x_min="
          f"{V[:, 0].min():.4f}")

    avg_edge   = mean_edge_length(V, F)
    voxel_size = voxel_factor * avg_edge
    print(f"[voxelize] mean_edge={avg_edge:.4f}  voxel_size="
          f"{voxel_size:.4f}  (factor={voxel_factor})")

    material = trusty.StableNeoHookean(youngs_modulus=youngs, poisson_ratio=0.4)
    world = trusty.World(backend=backend,
                         timestep=1.0 / 60.0,
                         newton=trusty.NewtonConfig(max_iters=60, tolerance=1e-4),
                         time_stepping="bdf2")
    # V (n, 3) and F (m, 3): the triangle surface. It is filled with hexes
    # of edge voxel_size, which carry the simulation.
    body = trusty.fem.add_embedded_solid(
        world, V, F, voxel_size=voxel_size, material=material, density=1000.0,
        order=order)

    # Stiffness per unit rest area (N/m^3): Young's modulus over the glue thickness.
    trusty.constraints.add_pin(
        world, body, faces=pin_faces,
        stiffness=youngs / (GLUE_FRAC * bbox.max()))

    return world, body, V, F


def _register_visuals(ps, world, body, show_hexes: bool = True):
    # The deformed input surface: one row per vertex of V, and its triangles.
    V = np.asarray(trusty.fem.surface_positions(world, body))
    _, F = trusty.surface.mesh(world, body)
    ps_mesh = ps.register_surface_mesh("bar", V, F, smooth_shade=False)
    ps_mesh.set_edge_width(1.0)
    ps_mesh.set_color((0.85, 0.55, 0.25))

    ps_hex = None
    if show_hexes:
        # The hex grid that carries the simulation, at its current positions.
        ps_hex = ps.register_volume_mesh(
            "voxel hexes",
            np.asarray(trusty.fem.positions(world, body)),
            hexes=np.asarray(trusty.fem.elements(world, body)))
        ps_hex.set_color((0.45, 0.6, 0.85))
        ps_hex.set_edge_width(1.0)
        ps_hex.set_transparency(0.55)
        ps_mesh.set_transparency(0.85)
    return ps_mesh, ps_hex


def _update_visuals(ps_mesh, ps_hex, world, body):
    ps_mesh.update_vertex_positions(
        np.asarray(trusty.fem.surface_positions(world, body)))
    if ps_hex is not None:
        ps_hex.update_vertex_positions(
            np.asarray(trusty.fem.positions(world, body)))


def run_polyscope(world, body, steps: int, show_hexes: bool = True):
    ps = init_polyscope(headless=False)
    ps_mesh, ps_hex = _register_visuals(ps, world, body, show_hexes)

    state = {"i": 0, "playing": False}

    def advance_one():
        if state["i"] < steps:
            world.step()
            state["i"] += 1
            _update_visuals(ps_mesh, ps_hex, world, body)

    def callback():
        import polyscope.imgui as psim
        _, state["playing"] = psim.Checkbox("play", state["playing"])
        psim.SameLine()
        if psim.Button("step"):
            advance_one()
        elif state["playing"]:
            advance_one()
        psim.Text(f"step {state['i']} / {steps}")
        rep = world.last_report()
        psim.Text(f"iters={rep.iterations}  res={rep.final_residual:.2e}")

    ps.set_user_callback(callback)
    ps.show()


def run_screenshots(world, body, steps: int, out_dir: Path,
                    show_hexes: bool = True):
    """Headless: step the world, write a PNG per frame via polyscope EGL."""
    ps = init_polyscope(headless=True)
    out_dir.mkdir(parents=True, exist_ok=True)
    ps_mesh, ps_hex = _register_visuals(ps, world, body, show_hexes)

    ps.reset_camera_to_home_view()
    ps.look_at(
        camera_location=(1.8, -1.2, 0.9),
        target=(0.5, 0.1, -0.1),
    )

    def snapshot(idx: int):
        ps.screenshot(str(out_dir / f"embedded_{idx:04d}.png"), transparent_bg=False)

    snapshot(0)
    for i in range(1, steps + 1):
        world.step()
        _update_visuals(ps_mesh, ps_hex, world, body)
        snapshot(i)

    print(f"Wrote {steps + 1} screenshots to {out_dir}/")


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--backend",
                        choices=["auto", "cpu", "cuda", "accelerate"], default="auto")
    parser.add_argument("--order", choices=list(HEX_ORDERS), default="linear",
                        help="element order: q1 linear (default), q2 Lagrange, q2s serendipity")
    parser.add_argument("--steps", type=int, default=120)
    parser.add_argument("--no-viewer", action="store_true")
    parser.add_argument("--mesh", type=Path, default=None,
                        help="Load this triangle mesh instead of the "
                             "built-in bar. Any format trimesh reads "
                             "(.obj, .ply, .stl, .glb, …).")
    parser.add_argument("--voxel-factor", type=float, default=VOXEL_FACTOR,
                        help=f"Hex edge length as a multiple of the mesh's "
                             f"mean surface-edge length (default "
                             f"{VOXEL_FACTOR}).")
    parser.add_argument("--youngs", type=float, default=2e6,
                        help="Young's modulus (Pa) for StableNeoHookean.")
    parser.add_argument("--rescale-to", type=float, default=None,
                        help="Rescale the loaded mesh so its longest axis "
                             "spans this many world units. Ignored when "
                             "using the built-in bar.")
    parser.add_argument("--out", type=Path, default=Path("out_embedded"))
    parser.add_argument("--no-hexes", action="store_true",
                        help="Disable the voxel-hex overlay; show only the "
                             "embedded surface.")
    args = parser.parse_args()

    order = HEX_ORDERS[args.order]
    world, body, _V, _F = build_world(
        backend=args.backend,
        mesh_path=args.mesh,
        voxel_factor=args.voxel_factor,
        youngs=args.youngs,
        rescale_to=args.rescale_to,
        order=order,
    )

    # Quadratic embedded bodies have no linear voxel-hex mesh to read back;
    # only the embedded surface renders.
    show_hexes = not args.no_hexes
    if show_hexes and order != ORDER.Linear:
        print("[viewer] hex overlay unavailable for quadratic elements; "
              "showing embedded surface only.")
        show_hexes = False

    if args.no_viewer:
        run_screenshots(world, body, args.steps, args.out,
                        show_hexes=show_hexes)
    else:
        run_polyscope(world, body, args.steps,
                      show_hexes=show_hexes)


if __name__ == "__main__":
    main()

The voxel grid

Every hex that overlaps the inside of the surface becomes an element, so the grid always covers the surface and usually sticks out past it. voxel_size is the one resolution knob: smaller hexes follow the shape more closely and cost more. The surface keeps its own resolution either way.

Pick voxel_size from the thinnest feature you need, not from the triangles. A wall needs at least two cells through its thickness, or the voxels bridge the gap and the hole disappears:

# Voxel edges are set in absolute terms, not from the input triangle size.
# `add_embedded_solid` fills the inside of the surface with hexes, so a
# thin-walled tube needs at least ~2 cells THROUGH the wall; coarser, and it
# voxelizes into a solid blob spanning the bore.
VOXEL_CORE   = CORE_RADIUS / 3.0
VOXEL_SLEEVE = SLEEVE_WALL / 2.0

A solid cylinder and a thin tube, each inside its grid. The tube keeps its bore because its hexes are half as wide as its wall:

A cylinder and a tube inside their hex grids

Adaptive refinement

To spend resolution only where it matters, pass a sizing_field: a function from a world point p (a length-3 array) to the hex edge length wanted there. voxel_size is then the coarsest edge, and max_level is how many times a hex may be halved, so the finest edge is voxel_size / 2**max_level.

coarse = voxel_factor * mean_edge_length(V, F)
fine   = coarse / (2 ** max_level)

# Refine the band nearest the clamped root; coarse elsewhere.
x_min = float(V[:, 0].min())
x_ext = float(V[:, 0].max()) - x_min

# Target hex edge length at world point p: fine near the root.
def sizing(p, x_min=x_min, x_ext=x_ext, fine=fine, coarse=coarse):
    return fine if (p[0] - x_min) < REFINE_BAND_FRAC * x_ext else coarse
body     = trusty.fem.add_embedded_solid(
    world, V, F, voxel_size=coarse, material=material, density=1000.0,
    sizing_field=sizing, max_level=max_level)

Here the cantilever is refined near its root, where the bending is largest, and stays coarse toward the tip:

A cantilever with fine hexes near the clamp and coarse ones at the tip

Where fine hexes meet coarse ones, the fine nodes are made to follow their coarse neighbours, so the grid stays conforming.

Full script: python examples/embedded/adaptive_embedded_cantilever.py
"""Adaptively-voxelized cantilever sagging under gravity.

Same setup as `embedded_cantilever.py`, but the hex grid is refined near the
clamped root -- where a cantilever's bending stress concentrates -- via a
sizing field. `--voxel-factor` sets the *coarsest* cell; the tip stays coarse.
Refinement introduces T-junction hanging nodes, which the solver constrains
to follow their coarser neighbours.

The clamp holds the input surface's end cap, wherever its points fall in the
refined grid.

Usage:
    python examples/embedded/adaptive_embedded_cantilever.py
    python examples/embedded/adaptive_embedded_cantilever.py --max-level 2
    python examples/embedded/adaptive_embedded_cantilever.py --no-viewer
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np

import trusty

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils import (  # noqa: E402
    load_mesh,
    make_bar_trimesh,
    mean_edge_length,
    rescale_mesh,
)

# Reuse the geometry constants, pin selection, and viewer/screenshot drivers.
from embedded_cantilever import (  # noqa: E402
    BAR_FACE_RES,
    BAR_SIZE,
    GLUE_FRAC,
    VOXEL_FACTOR,
    pinned_face_indices,
    run_polyscope,
    run_screenshots,
)

# Fraction of the x-extent (from the clamped root) refined to the finest level.
REFINE_BAND_FRAC = 0.4


def build_world(
    backend: str = "auto",
    *,
    mesh_path: Path | None = None,
    voxel_factor: float = VOXEL_FACTOR,
    max_level: int = 1,
    youngs: float = 2e6,
    rescale_to: float | None = None,
):

    if mesh_path is not None:
        V, F = load_mesh(mesh_path)
        V = rescale_mesh(V, rescale_to) if rescale_to is not None else V - V.min(axis=0)
        print(f"[mesh] {mesh_path.name}  verts={len(V)}  tris={len(F)}")
    else:
        V, F = make_bar_trimesh(BAR_SIZE, BAR_FACE_RES)

    pin_faces = pinned_face_indices(V, F)
    if not pin_faces:
        raise SystemExit("No pinned faces found near x_min; bump PIN_BAND_FRAC.")

    coarse = voxel_factor * mean_edge_length(V, F)
    fine   = coarse / (2 ** max_level)

    # Refine the band nearest the clamped root; coarse elsewhere.
    x_min = float(V[:, 0].min())
    x_ext = float(V[:, 0].max()) - x_min

    # Target hex edge length at world point p: fine near the root.
    def sizing(p, x_min=x_min, x_ext=x_ext, fine=fine, coarse=coarse):
        return fine if (p[0] - x_min) < REFINE_BAND_FRAC * x_ext else coarse

    material = trusty.StableNeoHookean(youngs_modulus=youngs, poisson_ratio=0.4)
    world    = trusty.World(backend=backend,
                            timestep=1.0 / 60.0,
                            newton=trusty.NewtonConfig(max_iters=60, tolerance=1e-4),
                            time_stepping="bdf2")
    body     = trusty.fem.add_embedded_solid(
        world, V, F, voxel_size=coarse, material=material, density=1000.0,
        sizing_field=sizing, max_level=max_level)

    n_nodes = np.asarray(trusty.fem.positions(world, body)).shape[0]
    print(f"[voxelize] coarse={coarse:.4f}  finest={fine:.4f} "
          f"(max_level={max_level})  {n_nodes} hex nodes")

    size = float((V.max(axis=0) - V.min(axis=0)).max())
    trusty.constraints.add_pin(
        world, body, faces=pin_faces, stiffness=youngs / (GLUE_FRAC * size))

    return world, body, V, F


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--backend",
                        choices=["auto", "cpu", "cuda", "accelerate"], default="auto")
    parser.add_argument("--steps", type=int, default=120)
    parser.add_argument("--no-viewer", action="store_true")
    parser.add_argument("--mesh", type=Path, default=None)
    parser.add_argument("--voxel-factor", type=float, default=VOXEL_FACTOR,
                        help="Coarsest hex edge as a multiple of the mesh's "
                             "mean surface-edge length.")
    parser.add_argument("--max-level", type=int, default=1,
                        help="Refinement depth near the root (finest = "
                             "coarsest / 2^max_level).")
    parser.add_argument("--youngs", type=float, default=2e6)
    parser.add_argument("--rescale-to", type=float, default=None)
    parser.add_argument("--out", type=Path, default=Path("out_adaptive_embedded"))
    parser.add_argument("--no-hexes", action="store_true")
    args = parser.parse_args()

    world, body, _V, _F = build_world(
        backend=args.backend,
        mesh_path=args.mesh,
        voxel_factor=args.voxel_factor,
        max_level=args.max_level,
        youngs=args.youngs,
        rescale_to=args.rescale_to,
    )

    if args.no_viewer:
        run_screenshots(world, body, args.steps, args.out,
                        show_hexes=not args.no_hexes)
    else:
        run_polyscope(world, body, args.steps, show_hexes=not args.no_hexes)


if __name__ == "__main__":
    main()

Pins

Pins on an embedded solid act on the surface, not on hex nodes: name triangles of the input mesh with faces= in trusty.constraints.add_pin, and the pin holds their vertices. It works the same on any grid, refined or not, and the pinned triangles need not line up with hex faces.

x_min = float(V[:, 0].min())
x_max = float(V[:, 0].max())
band = PIN_BAND_FRAC * (x_max - x_min)
centroids_x = V[F, 0].mean(axis=1)
return np.flatnonzero(centroids_x - x_min < band).astype(int).tolist()

The surface's vertices are not hex nodes, so an exact pin cannot hold them yet and raises at the first step(). Give the pin a stiffness instead, which makes it act like a thin layer of glue: per unit of rest area, the stiffness is Young's modulus over the layer's thickness, N/m³. A layer about 1% of the body's size holds the surface close to its targets without making the solve stiff.

Moving targets

A pin given targets pulls its points toward them, one row per pinned vertex in ascending vertex order, and trusty.constraints.set_pin_targets(world, pin, targets) moves them from the next step on. Here the left end of a beam is held where it is, and the right end's targets follow a sine wave:

phase = (2 * np.pi * step) / DRIVE_PERIOD_STEPS
dz    = DRIVE_AMP * np.sin(phase)
targets = V_rest[right_verts].copy()  # one row per pinned vertex
targets[:, 2] += dz
return targets, dz

Each step, set the new targets, then step:

targets, _dz = prescribed_targets(i, V, right_verts)
trusty.constraints.set_pin_targets(world, right_pin, targets)
world.step()

The orange points are the right end's targets.

Full script: python examples/embedded/moving_pin.py
"""Cantilever beam with a moving pin at the free end.

A high-res rectangular bar is voxelized, the left face pinned at rest,
and the right face pinned to targets that follow a vertical sinusoid.
The beam bends elastically as the right end is driven up and down. Both
pins are compliant, like a thin layer of glue between each end cap and
its targets.

Defaults open a polyscope viewer; ``--no-viewer`` writes PNG frames
instead.

Usage:
    python examples/embedded/moving_pin.py
    python examples/embedded/moving_pin.py --steps 360
    python examples/embedded/moving_pin.py --no-viewer
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np

import trusty

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils import init_polyscope, make_bar_trimesh, mean_edge_length  # noqa: E402


# --- Geometry & drive --------------------------------------------------
BAR_SIZE     = (1.0, 0.2, 0.2)
BAR_FACE_RES = (16, 4, 4)        # surface triangulation per dimension
VOXEL_FACTOR = 1.5               # hex edge ≈ VOXEL_FACTOR * mean tri edge

YOUNGS           = 2e6
# Thickness of the glue layer each pin acts like; stiffness per area is E over it.
GLUE_THICKNESS   = 0.01 * BAR_SIZE[0]
DRIVE_AMP        = 0.30
DRIVE_PERIOD_STEPS = 60

# Centroid x-band (fraction of x-extent) within which a triangle is
# considered to lie on the corresponding end face.
PIN_BAND_FRAC = 5e-2


def _end_face_indices(V: np.ndarray, F: np.ndarray):
    """Return (left_face_tris, right_face_tris) — triangle indices into
    F whose centroid sits in the leftmost/rightmost band of x-extent."""
    x_min = float(V[:, 0].min())
    x_max = float(V[:, 0].max())
    band  = PIN_BAND_FRAC * (x_max - x_min)
    cx    = V[F, 0].mean(axis=1)
    left  = np.flatnonzero(cx - x_min < band).astype(int).tolist()
    right = np.flatnonzero(x_max - cx < band).astype(int).tolist()
    return left, right


def _right_face_verts(V: np.ndarray, F: np.ndarray, right_faces):
    """Indices into V that participate in any right-face triangle."""
    return sorted({int(v) for f in right_faces for v in F[f]})


def build_world(backend: str):

    V, F = make_bar_trimesh(BAR_SIZE, BAR_FACE_RES)
    left_faces, right_faces = _end_face_indices(V, F)
    right_verts = _right_face_verts(V, F, right_faces)
    if not left_faces or not right_faces:
        raise SystemExit(
            "moving_pin: failed to identify both end-face triangle "
            "groups — bump PIN_BAND_FRAC or increase BAR_FACE_RES.")

    avg_edge   = mean_edge_length(V, F)
    voxel_size = VOXEL_FACTOR * avg_edge

    world = trusty.World(backend=backend,
                         timestep=1.0 / 60.0,
                         gravity=(0.0, 0.0, 0.0),
                         newton=trusty.NewtonConfig(max_iters=80, tolerance=1e-6))
    mat   = trusty.StableNeoHookean(youngs_modulus=YOUNGS, poisson_ratio=0.4)
    body  = trusty.fem.add_embedded_solid(
        world, V, F, voxel_size=voxel_size, material=mat, density=1000.0)

    stiffness = YOUNGS / GLUE_THICKNESS
    trusty.constraints.add_pin(world, body, faces=left_faces, stiffness=stiffness)
    # One target row per pinned vertex, in ascending vertex order: right_verts.
    right_pin = trusty.constraints.add_pin(
        world, body, faces=right_faces, targets=V[right_verts], stiffness=stiffness)

    print(f"[moving_pin] bar={BAR_SIZE}  surface_verts={len(V)}  "
          f"surface_tris={len(F)}  voxel_size={voxel_size:.4f}  "
          f"left_pinned={len(left_faces)} tris  "
          f"right_pinned={len(right_faces)} tris")

    return world, body, right_pin, V, F, right_verts


def prescribed_targets(step: int, V_rest: np.ndarray, right_verts):
    """The right-face verts' rest positions, pulled up/down along z by a
    sinusoid."""
    phase = (2 * np.pi * step) / DRIVE_PERIOD_STEPS
    dz    = DRIVE_AMP * np.sin(phase)
    targets = V_rest[right_verts].copy()  # one row per pinned vertex
    targets[:, 2] += dz
    return targets, dz


def _register_visuals(ps, world, body, F, V, right_verts):
    surf = np.asarray(trusty.fem.surface_positions(world, body)).copy()
    ps_mesh = ps.register_surface_mesh("beam", surf, F, smooth_shade=False)
    ps_mesh.set_color((0.85, 0.55, 0.25))
    ps_mesh.set_edge_width(1.0)
    ps_target = ps.register_point_cloud(
        "right_targets", V[right_verts].copy(), radius=0.018,
        color=(1.0, 0.4, 0.2))
    return ps_mesh, ps_target


def run_polyscope(backend: str, n_steps: int):
    ps = init_polyscope(headless=False)
    world, body, right_pin, V, F, right_verts = build_world(backend)
    ps_mesh, ps_target = _register_visuals(ps, world, body, F, V, right_verts)

    state = {"i": 0, "playing": True}

    def callback():
        import polyscope.imgui as psim
        _, state["playing"] = psim.Checkbox("play", state["playing"])
        psim.SameLine()
        if psim.Button("step") or state["playing"]:
            if state["i"] < n_steps:
                targets, _dz = prescribed_targets(state["i"], V, right_verts)
                trusty.constraints.set_pin_targets(world, right_pin, targets)
                world.step()
                state["i"] += 1
                ps_mesh.update_vertex_positions(np.asarray(
                    trusty.fem.surface_positions(world, body)))
                ps_target.update_point_positions(targets)
        psim.Text(f"step {state['i']} / {n_steps}")
        rep = world.last_report()
        psim.Text(
            f"last solve: iters={rep.iterations}  "
            f"residual={rep.final_residual:.3e}")

    ps.set_user_callback(callback)
    ps.show()


def run_screenshots(backend: str, n_steps: int, out_dir: Path):
    ps = init_polyscope(headless=True)
    out_dir.mkdir(parents=True, exist_ok=True)

    world, body, right_pin, V, F, right_verts = build_world(backend)
    ps_mesh, ps_target = _register_visuals(ps, world, body, F, V, right_verts)

    Lx = BAR_SIZE[0]
    ps.reset_camera_to_home_view()
    ps.look_at(camera_location=(0.5 * Lx, -2.0, 0.5),
               target=(0.5 * Lx, 0.0, 0.0))

    def snapshot(idx: int):
        ps.screenshot(str(out_dir / f"moving_pin_{idx:04d}.png"),
                      transparent_bg=False)

    snapshot(0)
    for i in range(n_steps):
        targets, _dz = prescribed_targets(i, V, right_verts)
        trusty.constraints.set_pin_targets(world, right_pin, targets)
        world.step()
        ps_mesh.update_vertex_positions(np.asarray(
            trusty.fem.surface_positions(world, body)))
        ps_target.update_point_positions(targets)
        snapshot(i + 1)

    print(f"Wrote {n_steps + 1} screenshots to {out_dir}/")


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--backend",
                    choices=["auto", "cpu", "cuda", "accelerate"], default="auto")
    ap.add_argument("--steps", type=int, default=180)
    ap.add_argument("--no-viewer", action="store_true")
    ap.add_argument("--out", type=Path, default=Path("out_moving_pin"),
                    help="Directory to write PNG frames in --no-viewer mode.")
    args = ap.parse_args()

    if args.no_viewer:
        run_screenshots(args.backend, args.steps, args.out)
    else:
        run_polyscope(args.backend, args.steps)


if __name__ == "__main__":
    main()

Reading results

Read the surface, not the grid: trusty.fem.surface_positions returns the current position of every vertex of V, in the same order, and trusty.surface.mesh(world, body) returns (V, F).

# The deformed input surface: one row per vertex of V, and its triangles.
V = np.asarray(trusty.fem.surface_positions(world, body))
_, F = trusty.surface.mesh(world, body)

The hex grid is still an ordinary solid underneath, so trusty.fem readouts such as von_mises and equivalent_strain work on it and return one value per hex node. trusty.fem.interpolate_to_surface carries such a field over to the surface, one value per vertex of V:

# One value per hex node ...
nodal = trusty.fem.equivalent_strain(world, body)
# ... interpolated to one value per vertex of the input surface.
return trusty.fem.interpolate_to_surface(world, body, nodal)

Below, an undersized stiff sleeve has been press-fitted onto a soft core (the sleeve's near half is cut away). Both surfaces are coloured by equivalent strain: the core is squeezed into a waist where the sleeve grips it, and the sleeve itself barely deforms.

A core squeezed by a sleeve, coloured by equivalent strain

Function Returns
trusty.fem.surface_positions(world, body) current surface vertex positions, (n, 3), rows matching V
trusty.surface.mesh(world, body) the rest surface (V, F), F of shape (m, 3)
trusty.fem.interpolate_to_surface(world, body, nodal_values) a per-hex-node scalar field, per surface vertex, (n,)
trusty.fem.positions(world, body), trusty.fem.elements(world, body) the hex grid: its current node positions and its hexes
Full script: python examples/embedded/interference_fit.py
"""Press-fit: a stiff sleeve relaxing onto an undersized soft core.

Two embedded solids in contact. The sleeve's bore is *smaller* than the
core, so seating it directly would start interpenetrating, and contact needs
a start without overlap. Instead the sleeve is inflated off its rest
shape with `initial_linear_map` in `fem.add_embedded_solid(...)`: its
starting positions scale up, its rest shape does not. It therefore begins
contact-free but strained, and quasi-static relaxation pulls it back toward its
unchanged rest, gripping the core through contact and friction.

That inflate-then-relax trick is the general way to set up an interference fit
without ever authoring a penetrating state.

The core's top cap is held by a pin that acts on the smooth input surface
rather than on the hex nodes. The pin is compliant, like a thin layer of glue
between the cap and where it started.

Readouts come back on the *input* surface, not the hex grid: equivalent
strain is computed per node and mapped onto the input surface with
`fem.interpolate_to_surface`.

Usage:
    python examples/embedded/interference_fit.py
    python examples/embedded/interference_fit.py --no-viewer --steps 120
    python examples/embedded/interference_fit.py --interference 0.15
    python examples/embedded/interference_fit.py --backend accelerate
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np

import trusty

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from utils import init_polyscope  # noqa: E402

# Geometry (meters). The core is a capsule-ish cylinder; the sleeve is an
# open-ended tube whose bore is `interference` smaller than the core radius.
CORE_RADIUS   = 0.05
CORE_HEIGHT   = 0.16
SLEEVE_LENGTH = 0.07
SLEEVE_WALL   = 0.016

# Voxel edges are set in absolute terms, not from the input triangle size.
# `add_embedded_solid` fills the inside of the surface with hexes, so a
# thin-walled tube needs at least ~2 cells THROUGH the wall; coarser, and it
# voxelizes into a solid blob spanning the bore.
VOXEL_CORE   = CORE_RADIUS / 3.0
VOXEL_SLEEVE = SLEEVE_WALL / 2.0

# Soft core, stiff sleeve -- the sleeve should behave near-rigidly against it
# while staying well conditioned for the solver.
CORE_E,   CORE_NU,   CORE_RHO   = 3.0e5, 0.35, 1.0e3
SLEEVE_E, SLEEVE_NU, SLEEVE_RHO = 8.0e7, 0.30, 9.0e2

# Both bodies are sampled on the same angular stations, so their radii can be
# compared station by station (see `fit_radii`).
N_THETA = 28

PIN_TOP_FRAC = 0.15    # fraction of the core's height held by the pin
# Thickness of the glue layer the pin acts like; stiffness per area is E over it.
GLUE_THICKNESS = 0.01 * CORE_HEIGHT

DHAT  = 2.0e-4
KAPPA = 1.0e6
MU    = 0.2


def cylinder_trimesh(radius, height, n_theta=N_THETA, n_z=8, z0=0.0):
    """Closed cylinder (side + both caps) as a triangle soup, axis = +z."""
    th = np.linspace(0.0, 2.0 * np.pi, n_theta, endpoint=False)
    zs = np.linspace(z0, z0 + height, n_z + 1)
    ring = np.stack([radius * np.cos(th), radius * np.sin(th)], axis=1)

    V = [np.column_stack([np.tile(ring, (len(zs), 1)),
                          np.repeat(zs, n_theta)])]
    V.append(np.array([[0.0, 0.0, zs[0]], [0.0, 0.0, zs[-1]]]))
    V = np.vstack(V)
    bot_c, top_c = len(V) - 2, len(V) - 1

    F = []
    for k in range(len(zs) - 1):          # side quads -> 2 tris
        a, b = k * n_theta, (k + 1) * n_theta
        for i in range(n_theta):
            j = (i + 1) % n_theta
            F.append([a + i, a + j, b + j])
            F.append([a + i, b + j, b + i])
    for i in range(n_theta):              # caps (outward winding)
        j = (i + 1) % n_theta
        F.append([bot_c, j, i])
        F.append([top_c, (len(zs) - 1) * n_theta + i,
                  (len(zs) - 1) * n_theta + j])
    return V, np.asarray(F, dtype=np.int32)


def tube_trimesh(r_inner, wall, length, n_theta=N_THETA, n_z=4, z0=0.0):
    """Open-ended tube (inner + outer walls, annular end caps), axis = +z."""
    th = np.linspace(0.0, 2.0 * np.pi, n_theta, endpoint=False)
    zs = np.linspace(z0, z0 + length, n_z + 1)
    c, s = np.cos(th), np.sin(th)

    def shell(radius):
        ring = np.stack([radius * c, radius * s], axis=1)
        return np.column_stack([np.tile(ring, (len(zs), 1)),
                                np.repeat(zs, n_theta)])

    n_shell = len(zs) * n_theta
    V = np.vstack([shell(r_inner), shell(r_inner + wall)])

    F = []
    for k in range(len(zs) - 1):
        a, b = k * n_theta, (k + 1) * n_theta
        for i in range(n_theta):
            j = (i + 1) % n_theta
            # Inner wall faces inward (reversed), outer faces outward.
            F.append([a + i, b + j, a + j])
            F.append([a + i, b + i, b + j])
            oa, ob = a + n_shell, b + n_shell
            F.append([oa + i, oa + j, ob + j])
            F.append([oa + i, ob + j, ob + i])
    for i in range(n_theta):              # annular caps
        j = (i + 1) % n_theta
        lo_i, lo_j = i, j
        F.append([lo_i, lo_j, lo_j + n_shell])
        F.append([lo_i, lo_j + n_shell, lo_i + n_shell])
        hi = (len(zs) - 1) * n_theta
        F.append([hi + i, hi + j + n_shell, hi + j])
        F.append([hi + i, hi + i + n_shell, hi + j + n_shell])
    return V, np.asarray(F, dtype=np.int32)


def build_world(args):

    V_core, F_core = cylinder_trimesh(CORE_RADIUS, CORE_HEIGHT)
    # Bore is undersized by `interference` (a fraction of the core radius), so
    # at rest the sleeve cannot be placed around the core without overlap.
    r_bore = CORE_RADIUS * (1.0 - args.interference)
    z_sleeve = 0.5 * (CORE_HEIGHT - SLEEVE_LENGTH)
    V_slv, F_slv = tube_trimesh(r_bore, SLEEVE_WALL, SLEEVE_LENGTH, z0=z_sleeve)

    world = trusty.World(backend=args.backend,
                         timestep=1.0 / 100.0,
                         gravity=(0.0, 0.0, 0.0),
                         time_stepping="quasi_static",
                         newton=trusty.NewtonConfig(max_iters=args.newton_iters, tolerance=1e-4))
    trusty.contact.enable(world, trusty.contact.Config(dhat=DHAT, kappa=KAPPA))
    core_mat = trusty.StableNeoHookean(youngs_modulus=CORE_E, poisson_ratio=CORE_NU)
    slv_mat = trusty.StableNeoHookean(youngs_modulus=SLEEVE_E, poisson_ratio=SLEEVE_NU)

    core = trusty.fem.add_embedded_solid(
        world, V_core, F_core, voxel_size=VOXEL_CORE,
        material=core_mat, density=CORE_RHO, friction_mu=MU)
    # Inflate the sleeve off its rest shape so it starts clear of the core:
    # its starting positions scale radially, its rest shape does not. The
    # relaxation then drives it back onto that (unchanged) undersized rest.
    clearance = (CORE_RADIUS + 2.0 * args.clearance_margin) / r_bore
    sleeve = trusty.fem.add_embedded_solid(
        world, V_slv, F_slv, voxel_size=VOXEL_SLEEVE,
        material=slv_mat, density=SLEEVE_RHO, friction_mu=MU,
        initial_linear_map=np.diag([clearance, clearance, 1.0]))

    # Hold the core's top cap so the assembly has something to react against.
    z_hi = V_core[:, 2].max() - PIN_TOP_FRAC * CORE_HEIGHT
    pin_faces = [int(f) for f in range(len(F_core))
                 if V_core[F_core[f]][:, 2].min() >= z_hi]
    trusty.constraints.add_pin(world, core, faces=pin_faces,
                               stiffness=CORE_E / GLUE_THICKNESS)

    print(f"[setup] core {len(V_core)} verts / sleeve {len(V_slv)} verts  "
          f"interference={args.interference:.0%}  inflate={clearance:.3f}x  "
          f"pinned {len(pin_faces)} core faces")
    return world, core, sleeve


def surface_strain(world, body):
    """Equivalent strain on the body's input surface."""
    # One value per hex node ...
    nodal = trusty.fem.equivalent_strain(world, body)
    # ... interpolated to one value per vertex of the input surface.
    return trusty.fem.interpolate_to_surface(world, body, nodal)


def fit_radii(world, core, sleeve):
    """(core radius, sleeve-bore radius) at the tightest angular station.

    Their difference is the live contact gap: it must stay >= 0, since contact
    never lets the two surfaces cross.

    Compared station by station rather than globally. Both bodies are faceted
    surfaces of revolution, so a global max core radius against a global min
    bore radius differences one polygon's circumradius against another's
    inradius. That bias is R * (1 - cos(pi / N_THETA)) per body -- several
    millimetres here, an order of magnitude more than the clearance being
    measured, and it reports a crossing when the surfaces are still millimetres
    apart.
    """
    Vc = np.asarray(trusty.fem.surface_positions(world, core))
    Vs = np.asarray(trusty.fem.surface_positions(world, sleeve))
    band = (Vc[:, 2] > Vs[:, 2].min()) & (Vc[:, 2] < Vs[:, 2].max())
    if not band.any():
        return float("nan"), float("nan")

    def station(V):
        return np.rint(np.arctan2(V[:, 1], V[:, 0])
                       / (2.0 * np.pi / N_THETA)).astype(int) % N_THETA

    r_core = np.linalg.norm(Vc[band, :2], axis=1)
    r_bore = np.linalg.norm(Vs[:, :2], axis=1)
    s_core, s_bore = station(Vc[band]), station(Vs)

    tightest = (float("nan"), float("nan"))
    worst = -np.inf
    for k in range(N_THETA):
        c, b = r_core[s_core == k], r_bore[s_bore == k]
        if not c.size or not b.size:
            continue
        if c.max() - b.min() > worst:
            worst = c.max() - b.min()
            tightest = (float(c.max()), float(b.min()))
    return tightest


def step_once(world, core, sleeve, state):
    """Advance one step, printing the fit every tenth."""
    world.step()
    rep = world.last_report()
    if state["i"] % 10 == 0:
        r_core, r_bore = fit_radii(world, core, sleeve)
        print(f"[step {state['i']:4d}] iters={rep.iterations:3d} "
              f"res={rep.final_residual:.2e}  "
              f"core r={r_core * 1e3:6.2f} mm  "
              f"gap={(r_bore - r_core) * 1e3:+5.2f} mm  "
              f"core strain_max={surface_strain(world, core).max():.4g}")
    state["i"] += 1


def report_grip(world, core, sleeve):
    """With a sleeve this much stiffer than the core, the sleeve returns nearly
    to its rest bore and the interference is taken up almost entirely by the
    core compressing -- so the interesting number is how far the core was
    squeezed, not where the sleeve ended up."""
    r_core, r_bore = fit_radii(world, core, sleeve)
    squeeze = (CORE_RADIUS - r_core) / CORE_RADIUS
    print(f"[done] core radius {CORE_RADIUS * 1e3:.2f} -> {r_core * 1e3:.2f} mm "
          f"({squeeze:.1%} compression), sleeve bore {r_bore * 1e3:.2f} mm, "
          f"gap {(r_bore - r_core) * 1e3:+.2f} mm")


def run_polyscope(world, core, sleeve, args):
    ps = init_polyscope(headless=False)
    _, core_F = trusty.surface.mesh(world, core)
    m_core = ps.register_surface_mesh(
        "core", trusty.fem.surface_positions(world, core), core_F)
    _, sleeve_F = trusty.surface.mesh(world, sleeve)
    m_slv = ps.register_surface_mesh(
        "sleeve", trusty.fem.surface_positions(world, sleeve),
        sleeve_F)

    def refresh():
        m_core.update_vertex_positions(trusty.fem.surface_positions(world, core))
        m_slv.update_vertex_positions(trusty.fem.surface_positions(world, sleeve))
        m_core.add_scalar_quantity("equivalent strain", surface_strain(world, core),
                                   enabled=True, cmap="turbo")
        m_slv.add_scalar_quantity("equivalent strain", surface_strain(world, sleeve),
                                  enabled=True, cmap="turbo")

    state = {"i": 0, "playing": False}   # play starts OFF
    refresh()

    def advance_one():
        if state["i"] < args.steps:
            step_once(world, core, sleeve, state)
            refresh()
            if state["i"] == args.steps:
                report_grip(world, core, sleeve)

    def callback():
        import polyscope.imgui as psim
        _, state["playing"] = psim.Checkbox("play", state["playing"])
        psim.SameLine()
        if psim.Button("step"):
            advance_one()
        elif state["playing"]:
            advance_one()
        psim.Text(f"step {state['i']} / {args.steps}")
        r_core, r_bore = fit_radii(world, core, sleeve)
        psim.Text(f"core radius {r_core * 1e3:6.2f} mm   "
                  f"gap {(r_bore - r_core) * 1e3:+5.2f} mm")
        rep = world.last_report()
        psim.Text(f"iters={rep.iterations}  res={rep.final_residual:.2e}")

    ps.set_user_callback(callback)
    ps.show()


def parse_args(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--steps", type=int, default=150)
    ap.add_argument("--newton-iters", type=int, default=8)
    ap.add_argument("--interference", type=float, default=0.10,
                    help="bore undersize as a fraction of core radius")
    ap.add_argument("--clearance-margin", type=float, default=1.5e-3,
                    help="extra radial gap (m) the inflated start leaves")
    ap.add_argument("--backend", default="auto",
                    choices=["auto", "cpu", "accelerate", "cuda"])
    ap.add_argument("--no-viewer", action="store_true")
    return ap.parse_args(argv)


def main():
    args = parse_args()
    world, core, sleeve = build_world(args)

    if args.no_viewer:
        state = {"i": 0}
        for _ in range(args.steps):
            step_once(world, core, sleeve, state)
        report_grip(world, core, sleeve)
        return

    run_polyscope(world, core, sleeve, args)


if __name__ == "__main__":
    main()

Reference

Every function and argument: trusty.fem reference and trusty.surface reference.