Skip to content

Constraints

trusty.constraints holds bodies in place, moves them and joins them to each other, all with one call, add_pin. A pin holds some points of a body at a target, where the target is the points' own starting positions, positions you prescribe, or another body.

To hold the points Call
where they start add_pin(world, body, nodes)
to another body add_pin(world, body, nodes, to=target_body)
toward positions that you set and move add_pin(world, body, nodes, targets=positions, stiffness=...)
on a plane (a roller) or a line (a slider) add_pin(world, body, nodes, plane=normal), add_pin(world, body, nodes, line=direction)

A pin takes either nodes, a plain list of the body's node indices, or faces=, a plain list of the body's boundary triangles, in which case the pinned points are the vertices of those triangles. Both lists are ordinary Python data that you compute from the positions you already have, for instance the nodes of a solid that lie on a plane are np.flatnonzero(np.abs(x[:, 0]) < 1e-6) on the array x returned by trusty.fem.positions, and the triangles of its right end are the rows of F from V, F = trusty.surface.mesh(world, body) whose vertices all have the largest x. Nodes keep the order you list them in, a node listed twice or out of range raises an error, and so does an empty list. The vertices of the triangles in faces are pinned in ascending order, each weighted by the rest area of the triangles around it, which matters when a pin has a stiffness. The nodes of an embedded solid are its hex grid's nodes, which need not lie on the surface, so an exact pin on one takes nodes with a tolerance wide enough to catch the grid nodes near a face. Its surface vertices are not nodes, so an exact pin on its faces raises at the first step(); a compliant pin on its faces holds the surface vertices themselves.

Pins work on solids, embedded solids, shells and rods, and a reduced solid can be pinned to another body, or have its faces pinned, with a stiffness. Add every pin before the first world.step(). After that you can move the targets of a pin, but you can't add new pins.

Exact and compliant pins

A pin without a stiffness is exact: its points stay on their target along every direction it holds, which is all of them unless you pass plane or line. A pin given a stiffness is compliant instead. It pulls each point toward its target with an elastic energy of zero rest length, so the points settle a little away from the target under load, and in return they give way when something presses into them, which an exact pin does not.

The stiffness is a plain number whose unit follows from how you named the points. With nodes it is in N/m for each pinned node, and with faces it is in N/m³, which is N/m for each square meter of rest area around a node, so a refined mesh splits the stiffness among more nodes instead of multiplying it.

Only a compliant pin can have targets, because an exact pin holds its points where they start or where the target body carries them.

Clamping a face

An exact pin on the nodes of a plane clamps a face. The nodes do not move at all. Here the back face of an embedded cube is clamped, with a tolerance wide enough to catch the grid nodes near the face:

# Clamp the hex-grid nodes within `tolerance` of the post's back face: the grid
# need not line up with the surface, so allow up to about half a hex.
grid = np.asarray(trusty.fem.positions(world, post))
trusty.constraints.add_pin(
    world, post, np.flatnonzero(np.abs(grid[:, 0] - POST_ORIGIN[0]) < 0.06).tolist())

A cube with its back face clamped and a soft flag hanging from it

The orange points are the clamped grid nodes. The soft flag is pinned to the cube.

An exact pin holds its nodes even if something presses into them. Where the pinned part may touch something, use a compliant pin, which gives way to contact. See Moving targets.

Full script: python examples/constraints/fem_embedded_flag.py
"""Soft FEM flag pinned to a clamped embedded post.

An embedded (voxelized) cube acts as a stiff post: its back face is clamped to
the world. A soft FEM beam ("flag") reaches out in +x; its root cap sits
inside the post's hex grid and is pinned to it, so the root vertices
move exactly with the post, as if they were points of it. Under gravity the
flag cantilevers off the clamped post and sags.

Usage:
    python examples/constraints/fem_embedded_flag.py                # polyscope
    python examples/constraints/fem_embedded_flag.py --no-viewer    # headless
    python examples/constraints/fem_embedded_flag.py --steps 400
"""

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  # noqa: E402

# Post: an axis-aligned cube whose cage straddles x = 0 so the flag root
# (x = 0) lands inside it.
POST_SIZE   = (0.4, 0.4, 0.4)
POST_ORIGIN = (-0.3, -0.2, -0.1)
VOXEL_SIZE  = 0.1
FLAG_SIZE   = (1.0, 0.15, 0.15)
FLAG_RES    = (12, 2, 2)


def build_world(backend: str = "auto"):

    world    = trusty.World(backend=backend,
                            timestep=1.0 / 60.0,
                            newton=trusty.NewtonConfig(max_iters=50))
    material = trusty.StableNeoHookean(youngs_modulus=1e5, poisson_ratio=0.3)

    # -- Target body: stiff embedded post, back (x = min) face clamped. ----
    stiff  = trusty.StableNeoHookean(youngs_modulus=1e6, poisson_ratio=0.3)
    pV, pF = make_bar_trimesh(POST_SIZE, res=(4, 4, 4), origin=POST_ORIGIN)
    post   = trusty.fem.add_embedded_solid(
        world, pV, pF, VOXEL_SIZE, stiff, density=1000.0)
    # Clamp the hex-grid nodes within `tolerance` of the post's back face: the grid
    # need not line up with the surface, so allow up to about half a hex.
    grid = np.asarray(trusty.fem.positions(world, post))
    trusty.constraints.add_pin(
        world, post, np.flatnonzero(np.abs(grid[:, 0] - POST_ORIGIN[0]) < 0.06).tolist())

    # -- Pinned body: soft FEM flag reaching out in +x, root at x = 0. ------
    tm = trusty.make_beam_tet_mesh(size=FLAG_SIZE, res=FLAG_RES)
    V  = np.asarray(tm.vertices).copy()
    # Centre the flag's y/z on the post so its root cap sits inside the cage.
    V[:, 1] += -FLAG_SIZE[1] / 2
    V[:, 2] += (POST_ORIGIN[2] + POST_SIZE[2] / 2) - FLAG_SIZE[2] / 2
    tm   = trusty.make_tet_mesh(V, np.asarray(tm.elements))
    flag = trusty.fem.add_tet_solid(world, tm, material, density=1000.0)

    # Root cap = flag vertices on the x = 0 face; pin them to the post.
    root = np.flatnonzero(np.abs(V[:, 0]) < 1e-6).tolist()
    trusty.constraints.add_pin(world, flag, root, to=post)

    print("Embedded post + soft FEM flag, root cap pinned to the post.")
    return world, post, flag


def _register_visuals(ps, world, post, flag):
    pV = trusty.fem.surface_positions(world, post)
    _, pF = trusty.surface.mesh(world, post)
    ps_post = ps.register_surface_mesh("embedded_post", np.asarray(pV),
                                       np.asarray(pF), color=(0.55, 0.55, 0.6))
    ps_flag = ps.register_volume_mesh(
        "soft_flag", np.asarray(trusty.fem.positions(world, flag)).copy(), tets=np.asarray(trusty.fem.elements(world, flag)))
    ps_flag.set_color((0.9, 0.5, 0.2))
    ps_flag.set_edge_width(1.0)
    return ps_post, ps_flag


def _update_visuals(ps_post, ps_flag, world, post, flag):
    ps_post.update_vertex_positions(
        np.asarray(trusty.fem.surface_positions(world, post)))
    ps_flag.update_vertex_positions(
        np.asarray(trusty.fem.positions(world, flag)))


def run_polyscope(world, post, flag, steps: int):
    ps = init_polyscope(headless=False)
    ps_post, ps_flag = _register_visuals(ps, world, post, flag)
    state = {"i": 0, "playing": False}

    def advance():
        if state["i"] < steps:
            world.step()
            state["i"] += 1
            _update_visuals(ps_post, ps_flag, world, post, flag)

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

    ps.set_user_callback(callback)
    ps.show()


def run_headless(world, post, flag, steps: int):
    print(f"Running {steps} steps headless...")
    V0   = np.asarray(trusty.fem.positions(world, flag)).copy()
    root = np.where(np.abs(V0[:, 0]) < 1e-9)[0]          # pinned verts
    tip  = np.where(np.abs(V0[:, 0] - FLAG_SIZE[0]) < 1e-9)[0]
    for i in range(steps):
        world.step()
        r = world.last_report()
        if (i + 1) % 50 == 0:
            print(f"  step {i + 1:4d}  iters={r.iterations}  "
                  f"res={r.final_residual:.2e}")
    V1        = np.asarray(trusty.fem.positions(world, flag))
    root_move = np.linalg.norm(V1[root] - V0[root], axis=1).max()
    tip_sag   = (V0[tip, 2] - V1[tip, 2]).mean()
    print(f"Done. tip sagged {tip_sag:.3f} m; pinned root moved {root_move:.4f} m.")


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

    world, post, flag = build_world(backend=args.backend)
    if args.no_viewer:
        run_headless(world, post, flag, args.steps)
    else:
        run_polyscope(world, post, flag, args.steps)


if __name__ == "__main__":
    main()

Shells and rods are pinned the same way, with node indices; see shells and rods.

Rollers and sliders

A pin holds its points in every direction unless you pass plane or line, a vector in world coordinates of any nonzero length. plane=normal holds each point on the plane through its target with that normal, which is a roller: plane=[0, 0, 1] stops the points moving up or down but lets them slide horizontally. line=direction holds each point on the line through its target along that direction, which is a slider: line=[1, 0, 0] lets the points move along x only. The plane or line stays fixed in the world as the body moves. Here a soft beam is fixed at its left end and rests on a roller at its right end:

X = np.asarray(trusty.fem.positions(world, beam))
left = np.flatnonzero(np.abs(X[:, 0]) < 1e-6).tolist()
right = np.flatnonzero((np.abs(X[:, 0] - BEAM_SIZE[0]) < 1e-6) & (np.abs(X[:, 2]) < 1e-6))
right = right.tolist()
trusty.constraints.add_pin(world, beam, left)  # fixed
# A roller: the bottom edge of the right end is pinned along z only, so it slides freely.
trusty.constraints.add_pin(world, beam, right, plane=[0, 0, 1])

As the beam sags under its own weight, its right end stays at its height and slides toward the fixed end, where a second fixed end would stretch the beam instead.

Planes and lines work with exact and compliant pins, in place or to targets, on nodes and on faces. A target only places the plane or line: a compliant pin pulls each point straight onto the plane or line through its target and ignores the rest of the target, so reaction_forces points across the plane or line too. With plane=[1, 0, 0] and moving targets, that drives a body along x alone and reads the force it takes. A node takes one exact pin on a plane or a line, and no other exact pin beside it. A pin to another body holds every direction.

Full script: python examples/constraints/roller_support.py
"""A soft beam fixed at one end and resting on a roller at the other.

The left face is fixed in every direction. The bottom edge of the right end
sits on a roller: it is pinned only vertically, so it cannot drop, but it is free
to slide along the floor. As the beam sags under its own weight, its right end slides
toward the fixed end instead of stretching the beam the way a second fixed
end would.

Usage:
    python examples/constraints/roller_support.py              # polyscope
    python examples/constraints/roller_support.py --no-viewer  # print the sag and the slide
"""

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


BEAM_SIZE = (1.0, 0.1, 0.1)
BEAM_RES  = (20, 2, 2)


def build_world(backend: str):
    mesh = trusty.make_beam_hex_mesh(size=BEAM_SIZE, res=BEAM_RES)
    material = trusty.StableNeoHookean(youngs_modulus=5e5, 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)

    X = np.asarray(trusty.fem.positions(world, beam))
    left = np.flatnonzero(np.abs(X[:, 0]) < 1e-6).tolist()
    right = np.flatnonzero((np.abs(X[:, 0] - BEAM_SIZE[0]) < 1e-6) & (np.abs(X[:, 2]) < 1e-6))
    right = right.tolist()
    trusty.constraints.add_pin(world, beam, left)  # fixed
    # A roller: the bottom edge of the right end is pinned along z only, so it slides freely.
    trusty.constraints.add_pin(world, beam, right, plane=[0, 0, 1])

    return world, beam, right


def _register_visuals(ps, world, beam):
    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)
    return ps_mesh


def run_polyscope(backend: str, n_steps: int):
    ps = init_polyscope(headless=False)
    world, beam, _ = build_world(backend)
    ps_mesh = _register_visuals(ps, world, beam)

    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"]:
            if state["i"] < n_steps:
                world.step()
                state["i"] += 1
                ps_mesh.update_vertex_positions(
                    np.asarray(trusty.fem.positions(world, beam)))
        psim.Text(f"step {state['i']} / {n_steps}")

    ps.set_user_callback(callback)
    ps.show()


def run_headless(backend: str, n_steps: int):
    world, beam, right = build_world(backend)
    X = np.asarray(trusty.fem.positions(world, beam))
    print(f"{'step':>4}  {'midspan sag':>11}  {'roller slide x':>14}  {'roller drop z':>13}")
    for i in range(n_steps):
        world.step()
        if i % 10 == 9:
            x = np.asarray(trusty.fem.positions(world, beam))
            sag = X[:, 2].min() - x[:, 2].min()
            slide = (x[right, 0] - X[right, 0]).mean()
            drop = np.abs(x[right, 2] - X[right, 2]).max()
            print(f"{i + 1:4d}  {sag:11.4f}  {slide:+14.4f}  {drop:13.2e}")


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=120)
    ap.add_argument("--no-viewer", action="store_true",
                    help="headless: print the sag and the roller's slide every 10 steps")
    args = ap.parse_args()

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


if __name__ == "__main__":
    main()

Pinning to another body

With to=target_body the target body carries each pinned point as if it were one of its own points. The point can lie inside the target or at any distance outside it, so the two bodies need not touch. Here a soft beam is pinned to the tip of a hinged affine bar:

# Root cap = the beam vertices on the x = 1 face; pin them to the bar.
root = np.flatnonzero(np.abs(V[:, 0] - BAR_LEN) < 1e-6).tolist()
trusty.constraints.add_pin(world, beam, root, to=bar)

A soft beam hanging from the tip of a swinging bar

The orange points are the pinned vertices. Released level, the bar swings down and the beam whips behind it.

The pinned body is a solid, a shell or a rod. The target body is a solid, a shell, an embedded solid or an affine body. A shell target takes only points on its midsurface. The pinned body and its target body don't collide with each other unless the pin passes contact=trusty.constraints.PairContact.Keep, and then they must start apart. In glued_ball.py blocks are pinned to a rolling ball, some on its surface and some away from it:

inner_face = np.flatnonzero(local[:, 2] < 1e-9).tolist()
trusty.constraints.add_pin(world, block, inner_face, to=ball)

There are three more examples, fem_embedded_flag.py pins a solid to an embedded cube (the clamp image), shell_affine_flag.py pins a shell to an affine bar and shell_fem_flag.py pins a shell to a quadratic solid.

Full script: python examples/constraints/fem_affine_pendulum.py
"""Soft FEM beam pinned to a swinging affine bar.

A near-rigid affine bar spans x in [0, 1] and is hinged to the world at its
left end by a grounded revolute joint. A soft FEM beam extends the arm from
x = 1 to x = 2; its root cap (the x = 1 face) is pinned to the affine bar.
The pinned vertices stop being unknowns of their own: they move exactly with
the bar, as if they were points of it. Released horizontal, the bar swings
down like a pendulum and the soft beam whips and sags behind it.

Usage:
    python examples/constraints/fem_affine_pendulum.py                # polyscope
    python examples/constraints/fem_affine_pendulum.py --no-viewer    # headless
    python examples/constraints/fem_affine_pendulum.py --steps 400
"""

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_LEN   = 1.0     # affine bar length (x)
BAR_HALF  = 0.1     # bar half-thickness (y, z)
Z0        = 2.0     # start height so the arm can swing freely
BEAM_LEN  = 1.0     # soft FEM beam length (x), continuing past the bar tip
BEAM_RES  = (10, 2, 2)


def make_box(center, half):
    h = np.asarray(half, dtype=np.float64)
    V = np.array(
        [[-h[0], -h[1], -h[2]], [h[0], -h[1], -h[2]],
         [h[0], h[1], -h[2]],   [-h[0], h[1], -h[2]],
         [-h[0], -h[1], h[2]],  [h[0], -h[1], h[2]],
         [h[0], h[1], h[2]],    [-h[0], h[1], h[2]]],
        dtype=np.float64,
    ) + np.asarray(center, dtype=np.float64)
    F = np.array(
        [[4, 5, 6], [4, 6, 7], [0, 3, 2], [0, 2, 1],
         [1, 2, 6], [1, 6, 5], [0, 4, 7], [0, 7, 3],
         [3, 7, 6], [3, 6, 2], [0, 1, 5], [0, 5, 4]],
        dtype=np.int32,
    )
    return V, F


def build_world(backend: str = "auto"):

    world = trusty.World(backend=backend, timestep=0.01, newton=trusty.NewtonConfig(max_iters=50))

    # -- Target body: near-rigid affine bar, hinged to the world at x = 0. --
    bar_V, bar_F = make_box((BAR_LEN / 2, 0.0, Z0), (BAR_LEN / 2, BAR_HALF, BAR_HALF))
    bar = trusty.affine.add_affine_body(
        world, bar_V, bar_F, density=1000.0, stiffness=1e8)
    # Grounded revolute hinge along y at the left end (x = 0): the two points
    # define the hinge axis.
    trusty.affine.add_revolute_joint(
        world, bar, (0.0, -BAR_HALF, Z0), (0.0, BAR_HALF, Z0), stiffness=1e8)

    # -- Pinned body: soft FEM beam continuing the arm from x = 1 to x = 2. --
    # Match the bar's 0.2 x 0.2 cross-section so the two align at the tip.
    tm   = trusty.make_beam_tet_mesh(
        size=(BEAM_LEN, 2 * BAR_HALF, 2 * BAR_HALF), res=BEAM_RES)
    V    = np.asarray(tm.vertices).copy()
    # Translate so the root face sits on the bar tip (x = 1), centred in y/z.
    V[:, 0] += BAR_LEN
    V[:, 1] += -BAR_HALF
    V[:, 2] += Z0 - BAR_HALF
    tm    = trusty.make_tet_mesh(V, np.asarray(tm.elements))
    soft  = trusty.StableNeoHookean(youngs_modulus=5e4, poisson_ratio=0.4)
    beam  = trusty.fem.add_tet_solid(world, tm, soft, density=1000.0)

    # Root cap = the beam vertices on the x = 1 face; pin them to the bar.
    root = np.flatnonzero(np.abs(V[:, 0] - BAR_LEN) < 1e-6).tolist()
    trusty.constraints.add_pin(world, beam, root, to=bar)

    print("Affine bar + soft FEM beam, root cap pinned to the bar.")
    return world, bar, beam


def _register_visuals(ps, world, bar, beam):
    bar_V = trusty.affine.surface_positions(world, bar)
    _, bar_F = trusty.surface.mesh(world, bar)
    ps_bar = ps.register_surface_mesh("affine_bar", np.asarray(bar_V),
                                      np.asarray(bar_F), color=(0.55, 0.55, 0.6))
    ps_beam = ps.register_volume_mesh(
        "soft_beam", np.asarray(trusty.fem.positions(world, beam)).copy(), tets=np.asarray(trusty.fem.elements(world, beam)))
    ps_beam.set_color((0.9, 0.5, 0.2))
    ps_beam.set_edge_width(1.0)
    return ps_bar, ps_beam


def _update_visuals(ps_bar, ps_beam, world, bar, beam):
    ps_bar.update_vertex_positions(
        np.asarray(trusty.affine.surface_positions(world, bar)))
    ps_beam.update_vertex_positions(
        np.asarray(trusty.fem.positions(world, beam)))


def run_polyscope(world, bar, beam, steps: int):
    ps = init_polyscope(headless=False)
    ps_bar, ps_beam = _register_visuals(ps, world, bar, beam)
    state = {"i": 0, "playing": False}

    def advance():
        if state["i"] < steps:
            world.step()
            state["i"] += 1
            _update_visuals(ps_bar, ps_beam, world, bar, beam)

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

    ps.set_user_callback(callback)
    ps.show()


def _root_cap_rigidity(V, root):
    """Max relative change in the root cap's pairwise distances vs rest.

    The pinned root is the image of a near-rigid affine body, so its shape must
    be preserved; a free soft cap would stretch under the swing."""
    P = V[root]
    d = np.linalg.norm(P[:, None, :] - P[None, :, :], axis=-1)
    iu = np.triu_indices(len(root), k=1)
    return d[iu]


def run_headless(world, bar, beam, steps: int):
    print(f"Running {steps} steps headless...")
    V0    = np.asarray(trusty.fem.positions(world, beam)).copy()
    root  = np.where(np.abs(V0[:, 0] - BAR_LEN) < 1e-9)[0]   # pinned verts
    rest0 = _root_cap_rigidity(V0, root)
    for i in range(steps):
        world.step()
        r = world.last_report()
        if (i + 1) % 50 == 0:
            print(f"  step {i + 1:4d}  iters={r.iterations}  "
                  f"res={r.final_residual:.2e}")
    V1     = np.asarray(trusty.fem.positions(world, beam))
    z_tip  = V1[:, 2].min()
    strain = np.abs(_root_cap_rigidity(V1, root) - rest0).max() / rest0.max()
    print(f"Done. beam tip z dropped to {z_tip:.3f} (start ~{Z0:.3f}); "
          f"pinned root cap strain {strain:.1e}.")


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

    world, bar, beam = build_world(backend=args.backend)
    if args.no_viewer:
        run_headless(world, bar, beam, args.steps)
    else:
        run_polyscope(world, bar, beam, args.steps)


if __name__ == "__main__":
    main()

Compliant pins to a body

A reduced solid can't be pinned to a body exactly, because it has no node unknowns to hold, so it takes a stiffness. A compliant pin joins any pinned body to the target body without constraining either body's degrees of freedom. This is the same pendulum with a reduced beam:

# Root = the first slice of beam nodes, which overlaps the bar's tip.
root = np.flatnonzero(V[:, 0] < BAR_LEN + 1e-9)
trusty.constraints.add_pin(
    world, beam, root.tolist(), to=bar,
    stiffness=stiffness)

A reduced beam pinned to the tip of a swinging bar

The stiffness is per node, in N/m. The pin stretches with the load, so the pinned nodes trail the bar slightly. Over the swing, the largest gap is:

--stiffness (N/m) Largest gap (m)
1e4 2.7e-2
1e6 (default) 5.2e-4
1e8 5.3e-6

The pinned body is a solid, a shell, a rod, an embedded solid or a reduced solid. The target body is a solid, a shell, an embedded solid, an affine body or a reduced solid.

Full script: python examples/constraints/subspace_affine_pendulum.py
"""Soft reduced beam pinned to a swinging affine bar with a compliant pin.

The compliant twin of fem_affine_pendulum.py. A near-rigid affine bar spans
x in [0, 1] and is hinged to the world at its left end. A soft beam continues
the arm from x = 1 to x = 2; it is a reduced (subspace) body, so instead of
an exact pin its root nodes are held to the bar by a stiff compliant pin.
Released horizontal, the bar swings down and the beam whips behind it.

A compliant pin gives a little under load. The example reports how far the
pinned nodes drift from the points of the bar they are tied to; raise
`--stiffness` and the gap shrinks in proportion.

Usage:
    python examples/constraints/subspace_affine_pendulum.py                # polyscope
    python examples/constraints/subspace_affine_pendulum.py --no-viewer    # headless
    python examples/constraints/subspace_affine_pendulum.py --no-viewer --stiffness 1e4
"""

from __future__ import annotations

import argparse
import sys
from pathlib import Path

import numpy as np

import trusty
from trusty.subspace.precompute import build_basis

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

BAR_LEN   = 1.0     # affine bar length (x)
BAR_HALF  = 0.1     # bar half-thickness (y, z)
Z0        = 2.0     # start height so the arm can swing freely
BEAM_LEN  = 1.0     # soft beam length (x), continuing past the bar tip
BEAM_RES  = (10, 2, 2)
HANDLES   = 6       # size of the beam's reduced basis


def make_beam_basis(mesh, material):
    """A reduced basis for the beam (see the subspace examples)."""
    precompute = trusty.World()
    trusty.fem.add_hex_solid(precompute, mesh, material, density=1000.0)
    return build_basis.build_skinning_eigenmodes(
        world=precompute, rest_positions=np.asarray(mesh.vertices),
        num_handles=HANDLES)


def build_world(stiffness: float, backend: str = "cpu"):

    world = trusty.World(backend=backend, timestep=0.01,
                         newton=trusty.NewtonConfig(max_iters=50))

    # -- Target body: near-rigid affine bar, hinged to the world at x = 0. --
    bar_V, bar_F = make_bar_trimesh((BAR_LEN, 2 * BAR_HALF, 2 * BAR_HALF), res=(1, 1, 1),
                                    origin=(0.0, -BAR_HALF, Z0 - BAR_HALF))
    bar = trusty.affine.add_affine_body(world, bar_V, bar_F, density=1000.0, stiffness=1e8)
    trusty.affine.add_revolute_joint(
        world, bar, (0.0, -BAR_HALF, Z0), (0.0, BAR_HALF, Z0), stiffness=1e8)

    # -- Pinned body: soft reduced beam continuing the arm from x = 1 to x = 2. --
    m = trusty.make_beam_hex_mesh(size=(BEAM_LEN, 2 * BAR_HALF, 2 * BAR_HALF), res=BEAM_RES)
    V = np.asarray(m.vertices) + (BAR_LEN, -BAR_HALF, Z0 - BAR_HALF)
    mesh = trusty.make_hex_mesh(np.ascontiguousarray(V), np.asarray(m.elements))
    soft = trusty.StableNeoHookean(youngs_modulus=5e4, poisson_ratio=0.4)
    beam = trusty.subspace.add_hex_body(world, mesh, soft, density=1000.0,
                                        basis=make_beam_basis(mesh, soft))

    # Root = the first slice of beam nodes, which overlaps the bar's tip.
    root = np.flatnonzero(V[:, 0] < BAR_LEN + 1e-9)
    trusty.constraints.add_pin(
        world, beam, root.tolist(), to=bar,
        stiffness=stiffness)

    print(f"Affine bar + soft reduced beam, {len(root)} root nodes pinned "
          f"(stiffness {stiffness:.0e}).")
    return world, bar, beam, mesh, root


def pin_gap(world, bar, bar_rest, beam_rest, beam, root):
    """Largest distance between a pinned node and the bar point it is tied to."""
    bar_now = np.asarray(trusty.affine.surface_positions(world, bar))
    # The bar moves affinely: fit x_now = A x_rest + p to its surface vertices.
    X = np.hstack([bar_rest, np.ones((len(bar_rest), 1))])
    Ap, *_ = np.linalg.lstsq(X, bar_now, rcond=None)
    target = np.hstack([beam_rest[root], np.ones((len(root), 1))]) @ Ap
    x = np.asarray(trusty.subspace.deformed_positions(world, body=beam))
    return float(np.linalg.norm(x[root] - target, axis=1).max())


def run_polyscope(world, bar, beam, mesh, steps: int):
    ps = init_polyscope(headless=False)
    bar_V = trusty.affine.surface_positions(world, bar)
    _, bar_F = trusty.surface.mesh(world, bar)
    ps_bar = ps.register_surface_mesh("affine_bar", np.asarray(bar_V), np.asarray(bar_F),
                                      color=(0.55, 0.55, 0.6))
    ps_beam = ps.register_volume_mesh("soft_beam", np.asarray(mesh.vertices).copy(),
                                      hexes=np.asarray(mesh.elements))
    ps_beam.set_color((0.9, 0.5, 0.2))
    ps_beam.set_edge_width(1.0)
    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
            ps_bar.update_vertex_positions(np.asarray(trusty.affine.surface_positions(world, bar)))
            ps_beam.update_vertex_positions(
                np.asarray(trusty.subspace.deformed_positions(world, body=beam)))
        psim.Text(f"step {state['i']} / {steps}")
        r = world.last_report()
        psim.Text(f"solve: iters={r.iterations} res={r.final_residual:.2e}")

    ps.set_user_callback(callback)
    ps.show()


def run_headless(world, bar, beam, mesh, root, steps: int):
    print(f"Running {steps} steps headless...")
    bar_rest = np.asarray(trusty.affine.surface_positions(world, bar)).copy()
    beam_rest = np.asarray(mesh.vertices)
    worst = 0.0
    for i in range(steps):
        world.step()
        r = world.last_report()
        worst = max(worst, pin_gap(world, bar, bar_rest, beam_rest, beam, root))
        if (i + 1) % 50 == 0:
            print(f"  step {i + 1:4d}  iters={r.iterations}  res={r.final_residual:.2e}")
    x = np.asarray(trusty.subspace.deformed_positions(world, body=beam))
    print(f"Done. beam tip z dropped to {x[:, 2].min():.3f} (start ~{Z0:.3f}); "
          f"largest pin gap {worst:.1e} m.")


def main():
    p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    p.add_argument("--backend", choices=["auto", "cpu", "accelerate"], default="cpu")
    p.add_argument("--steps", type=int, default=300)
    p.add_argument("--stiffness", type=float, default=1e6,
                   help="stiffness of the pin on each root node (N/m)")
    p.add_argument("--no-viewer", action="store_true")
    args = p.parse_args()

    world, bar, beam, mesh, root = build_world(args.stiffness, backend=args.backend)
    if args.no_viewer:
        run_headless(world, bar, beam, mesh, root, args.steps)
    else:
        run_polyscope(world, bar, beam, mesh, args.steps)


if __name__ == "__main__":
    main()

Moving targets

add_pin(world, body, faces=faces, targets=positions, stiffness=...) pulls each pinned node toward its own target, one row of positions per node. Here a bar's left face is clamped by an exact pin, and its right face is held by a compliant pin whose targets will move:

X = np.asarray(mesh.vertices)
trusty.constraints.add_pin(world, body, np.flatnonzero(np.abs(X[:, 0]) < 1e-6).tolist())
_, triangles = trusty.surface.mesh(world, body)
right_faces = np.flatnonzero(X[triangles][:, :, 0].min(axis=1) > BAR_SIZE[0] - 1e-9).tolist()
right_nodes = np.unique(triangles[right_faces])
right_targets_init = X[right_nodes].copy()
right_pin = trusty.constraints.add_pin(
    world, body, faces=right_faces, targets=right_targets_init, stiffness=2.5e5)

set_pin_targets(world, pin, targets) replaces the targets, one row per pinned node, from the next step on. Here the right face's targets follow a sine wave:

phase = (2 * np.pi * step) / DRIVE_PERIOD_STEPS
dz = DRIVE_AMP * np.sin(phase)
targets = right_targets_init.copy()
targets[:, 2] += dz

Each step, set the new targets, then step:

targets, dz = prescribed_targets(step, right_targets_init)
trusty.constraints.set_pin_targets(world, right_pin, targets)
world.step()

The orange points are the right face's targets. At the bottom of the drive some are below the floor; a compliant pin gives, so the bar rests on the floor instead of passing through it.

Full script: python examples/constraints/moving_pin.py
"""Compliant pins with moving targets, and a floor in the way.

A soft cantilever bar:
  - its left face is clamped by an exact pin;
  - its right face is pinned to targets that move up and down on a sine wave,
    with a compliant pin;
  - a floor below stops the bar. The targets dip below the floor, but a
    compliant pin gives, so the bar rests on the floor instead of passing
    through it.

Usage:
    python examples/constraints/moving_pin.py              # polyscope
    python examples/constraints/moving_pin.py --no-viewer  # print the drive
"""

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 = (1.0, 0.2, 0.2)
BAR_RES  = (10, 2, 2)
FLOOR_Z  = -0.2
DRIVE_AMP        = 0.27
DRIVE_PERIOD_STEPS = 60


def build_world(backend: str):

    mesh = trusty.make_beam_hex_mesh(size=BAR_SIZE, res=BAR_RES)
    material = trusty.StableNeoHookean(youngs_modulus=1e5, poisson_ratio=0.3)

    world = trusty.World(backend=backend,
                         timestep=1.0 / 60.0,
                         newton=trusty.NewtonConfig(max_iters=60))
    trusty.contact.enable(world, trusty.contact.Config(dhat=5e-3, kappa=1e4))
    body = trusty.fem.add_hex_solid(world, mesh, material, density=1000.0)

    X = np.asarray(mesh.vertices)
    trusty.constraints.add_pin(world, body, np.flatnonzero(np.abs(X[:, 0]) < 1e-6).tolist())
    _, triangles = trusty.surface.mesh(world, body)
    right_faces = np.flatnonzero(X[triangles][:, :, 0].min(axis=1) > BAR_SIZE[0] - 1e-9).tolist()
    right_nodes = np.unique(triangles[right_faces])
    right_targets_init = X[right_nodes].copy()
    right_pin = trusty.constraints.add_pin(
        world, body, faces=right_faces, targets=right_targets_init, stiffness=2.5e5)

    trusty.add_floor_plane(world, z=FLOOR_Z)

    return world, body, right_pin, right_nodes, right_targets_init


def prescribed_targets(step: int, right_targets_init: np.ndarray):
    phase = (2 * np.pi * step) / DRIVE_PERIOD_STEPS
    dz = DRIVE_AMP * np.sin(phase)
    targets = right_targets_init.copy()
    targets[:, 2] += dz
    return targets, dz


def drive(world, right_pin, right_targets_init, step: int):
    """Move the right face's targets for this step, then advance."""
    targets, dz = prescribed_targets(step, right_targets_init)
    trusty.constraints.set_pin_targets(world, right_pin, targets)
    world.step()
    return dz


def _register_visuals(ps, world, body):
    verts = np.asarray(trusty.fem.positions(world, body)).copy()
    hexes = np.asarray(trusty.fem.elements(world, body))
    ps_mesh = ps.register_volume_mesh("bar", verts, hexes=hexes)
    ps_mesh.set_edge_width(1.0)

    Lx = BAR_SIZE[0]
    floor = np.array(
        [[-0.5, -0.5, FLOOR_Z], [Lx + 0.5, -0.5, FLOOR_Z],
         [Lx + 0.5, 0.5, FLOOR_Z], [-0.5, 0.5, FLOOR_Z]])
    ps.register_surface_mesh(
        "floor", floor, np.array([[0, 1, 2], [0, 2, 3]], dtype=np.int32),
        color=(0.6, 0.6, 0.6))
    return ps_mesh


def run_polyscope(backend: str, n_steps: int):
    ps = init_polyscope(headless=False)
    world, body, right_pin, _, right_targets_init = build_world(backend)
    ps_mesh = _register_visuals(ps, world, body)

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

    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:
                drive(world, right_pin, right_targets_init, state["i"])
                state["i"] += 1
                ps_mesh.update_vertex_positions(
                    np.asarray(trusty.fem.positions(world, body)))
        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_headless(backend: str, n_steps: int):
    world, body, right_pin, right_nodes, right_targets_init = build_world(backend)
    print(f"{'step':>4}  {'target dz':>9}  {'face dz':>8}  {'lowest z':>8}  pin force z (N)")
    lowest = np.inf
    for i in range(n_steps):
        dz = drive(world, right_pin, right_targets_init, i)
        x = np.asarray(trusty.fem.positions(world, body))
        lowest = min(lowest, x[:, 2].min())
        if i % 10 == 0:
            face_dz = x[right_nodes, 2].mean() - right_targets_init[:, 2].mean()
            fz = trusty.constraints.reaction_forces(world, right_pin).sum(axis=0)[2]
            print(f"{i:4d}  {dz:+9.3f}  {face_dz:+8.3f}  {x[:, 2].min():+8.3f}  {fz:+.1f}")
    print(f"Lowest point reached: z = {lowest:.3f} (floor at z = {FLOOR_Z})")


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=120)
    ap.add_argument("--no-viewer", action="store_true",
                    help="headless: print the drive and the pin force every 10 steps")
    args = ap.parse_args()

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


if __name__ == "__main__":
    main()

Stiffness and reaction forces

A compliant pin stretches under load, so the pinned nodes settle away from their targets by about force / (stiffness × weight), where the weight is the total of the weights, which is the pinned area when you pass faces and the number of nodes when you pass nodes. Here a 16 kg block hangs from a pin on its top face, built three times with a pin ten times stiffer each time:

X = np.asarray(mesh.vertices)
_, triangles = trusty.surface.mesh(world, body)
top = np.flatnonzero(X[triangles][:, :, 2].min(axis=1) > SIZE[2] - 1e-9).tolist()
pin = trusty.constraints.add_pin(world, body, faces=top, stiffness=stiffness)

reaction_forces(world, pin) returns the force the pin exerts on each pinned node in the last step, one row per node, and zeros before the first step. It reads compliant pins that hold points in place or pull them toward targets:

forces = trusty.constraints.reaction_forces(world, pin)  # one row per pinned node
total = forces.sum(axis=0)  # their sum (fx, fy, fz)

Each row is stiffness × weight × (target − x) for the node, which points toward the target, or its part across the pin's plane or line when it has one. For the hanging block the total is the block's weight, pointing up, at every stiffness:

Stiffness (N/m³) Gap below the targets (m) reaction_forces total z (N)
1e5 0.0392 156.96
1e6 0.00392 156.96
1e7 0.000398 156.96

Three hanging blocks, one per stiffness, each below its targets

From left to right: stiffness 1e5, 1e6 and 1e7 N/m³. The orange points are the targets, and the arrows show the force each pinned node feels from its pin.

To measure how hard a face is held, pin it with a stiff compliant pin instead of an exact one.

Full script: python examples/constraints/hanging_block.py
"""A block hung from a compliant pin: pin stiffness and the pin's reaction force.

A 16 kg block hangs from its top face, which is held at its rest position by a
compliant pin. A compliant pin gives a little under load: the pinned face
settles below its targets by about weight / (k * A), where k is the pin
stiffness (N/m^3) and A the area of the pinned face. Each step solves for the
hanging equilibrium, so the example builds the block three times with a pin
ten times stiffer each time: the gap shrinks tenfold, while the pin's reaction
force (`reaction_forces`) stays equal to the block's weight.

Usage:
    python examples/constraints/hanging_block.py              # live polyscope
    python examples/constraints/hanging_block.py --no-viewer  # print the table
"""

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, 0.2, 0.4)         # m; the block hangs from its top face at z = 0.4
RES = (4, 4, 8)
DENSITY = 1000.0               # kg/m^3, so the block weighs 16 kg
STIFFNESSES = (1e5, 1e6, 1e7)  # N/m^3 of pinned face; the pin is stiffened through these


def build_world(stiffness: float, backend: str = "auto"):
    world = trusty.World(backend=backend,
                         time_stepping="static")  # every step solves for the equilibrium

    mesh = trusty.make_beam_hex_mesh(size=SIZE, res=RES)
    material = trusty.StableNeoHookean(youngs_modulus=1e6, poisson_ratio=0.4)
    body = trusty.fem.add_hex_solid(world, mesh, material, density=DENSITY)

    X = np.asarray(mesh.vertices)
    _, triangles = trusty.surface.mesh(world, body)
    top = np.flatnonzero(X[triangles][:, :, 2].min(axis=1) > SIZE[2] - 1e-9).tolist()
    pin = trusty.constraints.add_pin(world, body, faces=top, stiffness=stiffness)
    return world, body, pin, mesh, np.unique(triangles[top])


def hang(world):
    """Solve for the hanging equilibrium."""
    world.step()


def measure(world, body, pin, mesh, top):
    """The pin's gap below its targets (m), and its reaction force (N)."""
    x = np.asarray(trusty.fem.positions(world, body))
    rest = np.asarray(mesh.vertices)
    gap = float(np.mean(rest[top, 2] - x[top, 2]))
    forces = trusty.constraints.reaction_forces(world, pin)  # one row per pinned node
    total = forces.sum(axis=0)  # their sum (fx, fy, fz)
    return gap, forces, np.asarray(total)


def weight():
    return DENSITY * float(np.prod(SIZE)) * trusty.constants.standard_gravity


def run_headless(backend):
    print(f"block weight: {weight():.2f} N")
    print(f"{'stiffness (N/m^3)':>17}  {'gap (m)':>9}  {'reaction fz (N)':>15}")
    for k in STIFFNESSES:
        world, body, pin, mesh, top = build_world(k, backend)
        hang(world)
        gap, _, total = measure(world, body, pin, mesh, top)
        print(f"{k:17.0e}  {gap:9.2e}  {total[2]:15.2f}")


def run_polyscope(backend):
    import polyscope.imgui as psim

    ps = init_polyscope(headless=False)
    state = {"log_k": np.log10(STIFFNESSES[0]), "scene": None}

    def refresh():
        world, body, pin, mesh, top = build_world(10.0 ** state["log_k"], backend)
        hang(world)
        x = np.asarray(trusty.fem.positions(world, body))
        ps.register_volume_mesh("block", x, hexes=np.asarray(mesh.elements)).set_edge_width(1.0)
        ps.register_point_cloud("targets", np.asarray(mesh.vertices)[top], radius=0.006)
        gap, forces, total = measure(world, body, pin, mesh, top)
        nodes = ps.register_point_cloud("pinned nodes", x[top], radius=0.004)
        nodes.add_vector_quantity("pin force", forces, enabled=True)
        state["scene"] = (gap, total)

    refresh()

    def callback():
        changed, state["log_k"] = psim.SliderFloat("log10 stiffness (N/m^3)", state["log_k"],
                                                   4.5, 8.0)
        if changed:
            refresh()
        gap, total = state["scene"]
        psim.Text(f"gap below targets {gap:.2e} m")
        psim.Text(f"reaction fz {total[2]:.2f} N   (weight {weight():.2f} N)")

    ps.set_user_callback(callback)
    ps.show()


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--backend", choices=["auto", "cpu", "cuda", "accelerate"], default="auto")
    ap.add_argument("--no-viewer", action="store_true",
                    help="headless: step through the stiffnesses and print the table")
    args = ap.parse_args()

    if args.no_viewer:
        run_headless(args.backend)
    else:
        run_polyscope(args.backend)


if __name__ == "__main__":
    main()
Function Does
add_pin(world, body, nodes=None, *, faces=None, to=None, targets=None, stiffness=None, plane=None, line=None) pin the listed nodes or the vertices of the listed faces; exact without a stiffness; on a plane or a line when given; returns the pin
set_pin_targets(world, pin, targets) move the targets of a pin made with targets=, (#pinned points, 3)
reaction_forces(world, pin) the force a compliant pin exerts on each pinned point (N) in the last step, (#pinned points, 3); zero before the first step

Reference

Every function and argument: trusty.constraints reference.