Skip to content

Actuators

trusty.actuators holds commanded devices that apply their own force law to bodies: cables, muscles, fiber muscles and joint drives. Each add_* returns the actuator's handle, and each kind has its own commands and readers, named after it.

Actuator Command Acts on
cable set_cable_tension (N) or set_cable_length (m), by its drive a polyline of points fixed in bodies
muscle set_muscle_activation, from 0 to 1 a polyline of points fixed in bodies
fiber muscle set_muscle_activation, from 0 to 1 a whole solid, along a field of fiber directions
joint drive set_joint_target: an angle (rad), a slide (m) or a 3x3 rotation; set_joint_effort: a torque (N·m) or force (N) a joint of affine bodies

A command holds until it is changed, and takes effect on the next step. Add actuators before the first world.step(); command them whenever you like.

Polylines

Cables and muscles run along a polyline: positions, (n, 3) points in the rest shape of the bodies, in order. The polyline's length is the sum of the segments joining consecutive points, and the tension acts along every segment. To close a loop, repeat the first point at the end. bodies is one body that holds every point, or one body per point, so a polyline can cross from one body to the next.

The points need not lie on mesh nodes: each body carries its points along with it. Solids, embedded solids, affine bodies and reduced solids take points inside or outside their rest volume; shells take points on their rest midsurface; rods take points on their rest centerline. MPM bodies carry no polyline.

Cables

add_cable(world, bodies, positions, drive=TensionDrive()) runs a tendon along a polyline. A cable has a drive, chosen when it is added:

Drive Command The cable's energy
TensionDrive() set_cable_tension: a tension T, in N T × L, where L is the polyline length
LengthDrive(law=LinearCable()) set_cable_length: a target length Lₜ, in m tension from law in the strain e = (L − Lₜ) / Lₜ; slack once the cable is shorter than Lₜ

A cable starts at zero tension, or with its target length at its starting length. The command of the other drive raises. A LengthDrive takes a force law:

Law Tension for L > Lₜ
LinearCable(axial_stiffness=EA) EA e, with EA the axial rigidity (Young's modulus × cross-section area) in N; the default is about a 1 mm steel cable
ExponentialCable(axial_stiffness=EA, exponent=c) (EA / c)(exp(c e) − 1): slope EA at e = 0, stiffening faster as c > 0 grows

Because the law is in the strain, a cable wound in to a shorter Lₜ is stiffer. Cable fingers drives a finger and a tentacle with cables, and python examples/actuators/cable_curtain.py hangs a cable along a cloth's hem.

Muscles

A muscle pulls along its polyline like a muscle and its tendon. Here one runs from the upper arm to the forearm of two affine bodies, above the elbow:

points = np.array([ORIGIN_POINT, INSERTION_POINT], dtype=np.float64)
rest_length = float(np.linalg.norm(points[1] - points[0]))
# The fiber starts at its optimal length (the rest path minus the tendon),
# where it pulls hardest.
l_tendon_slack = 0.30
l_opt = rest_length - l_tendon_slack
muscle = trusty.actuators.add_muscle(
    world, [upper, fore], points, f_max=f_max, l_opt=l_opt, l_tendon_slack=l_tendon_slack,
    model=model)
Argument Meaning
f_max the most the muscle can pull, in N
l_opt the fibre length at which it pulls hardest, in m
l_tendon_slack the length of the tendon, in m. The fibre is the polyline minus the tendon.
pennation the angle of the fibres to the polyline, in rad. Default 0.
model the force-length law: MuscleModel.Hill (default) or MuscleModel.Polynomial

A muscle starts at activation 0. The active pull is activation * f_max, scaled down as the fibre gets longer or shorter than l_opt; a fibre stretched past l_opt also pulls on its own, even at activation 0. Activation does not set a position: it sets how hard the muscle pulls, and the bodies move until something balances it. Set it, step, and read back the muscle:

trusty.actuators.set_muscle_activation(world, muscle, activation)
for _ in range(steps):
    world.step()
return (elbow_angle(world, fore),
        trusty.actuators.muscle_length(world, muscle),   # m
        trusty.actuators.muscle_tension(world, muscle))    # N

Fully activated, the muscle curls the forearm up to its joint limit, and holds it there (the faint box is the forearm at rest):

A two-link arm curled up by a muscle

A muscle can also run along a rod, through its vertices, so the polyline bends with the rod.

Full script: python examples/affine/line_muscle.py
"""Line muscle: a "biceps" curling a two-link arm.

An upper arm welded to the world and a forearm hinged to it at the elbow, with
one line muscle running from a point on the upper arm to a point on the
forearm. Both points sit above the hinge axis, so the muscle has a lever arm.
There is no joint drive and no gravity: the muscle is the only thing that can
move the arm. Joint limits give the elbow a range of motion, as a real one
has.

Activation does not command a position. It sets how hard the muscle pulls,
and the arm moves until something balances that pull. Here nothing opposes
it, so the muscle curls the arm up to the flexion limit and holds it there,
and the reported tension is how hard it is pulling.

Headless mode settles the arm at rising activation levels and prints the elbow
angle, muscle length and tension at each. Polyscope mode draws the muscle over
the two bodies, with a live activation slider.

Usage:
    python examples/affine/line_muscle.py                # polyscope
    python examples/affine/line_muscle.py --no-viewer    # print the settled poses
    python examples/affine/line_muscle.py --f-max 600
"""

from __future__ import annotations

import argparse

import numpy as np

import trusty

# Geometry (meters). The upper arm runs along -x from the elbow at the origin;
# the forearm runs along +x. Both attachment points sit above the hinge axis,
# which is what gives the muscle its moment arm.
ARM_HALF = (0.5, 0.12, 0.12)
UPPER_CENTER = (-0.5, 0.0, 0.0)
FORE_CENTER = (0.5, 0.0, 0.0)
ORIGIN_POINT = (-0.40, 0.0, 0.15)      # on the upper arm
INSERTION_POINT = (0.25, 0.0, 0.10)    # on the forearm

# Elbow range of motion (rad), straight arm at 0. The muscle pulls its two
# attachment points together, which curls the forearm up, so the range is
# one-sided: a hair of slack below straight, and a flexion stop above.
ELBOW_LO, ELBOW_HI = -0.1, 1.4


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(f_max, backend, model):
    world = trusty.World(backend=backend,
                         timestep=0.01,
                         gravity=(0.0, 0.0, 0.0),  # muscle-only, so nothing else can move the arm
                         newton=trusty.NewtonConfig(max_iters=60, tolerance=1e-4))

    Vu, Fu = make_box(UPPER_CENTER, ARM_HALF)
    upper = trusty.affine.add_affine_body(world, Vu, Fu, density=50.0, stiffness=1e8)
    Vf, Ff = make_box(FORE_CENTER, ARM_HALF)
    fore = trusty.affine.add_affine_body(world, Vf, Ff, density=50.0, stiffness=1e8)

    # Weld the upper arm to the world, then hinge the forearm to it about y
    # through the origin.
    trusty.affine.add_fixed_joint(world, upper, UPPER_CENTER,
                                  axis_u=(0.1, 0.0, 0.0), axis_v=(0.0, 0.1, 0.0),
                                  stiffness=1e8)
    elbow = trusty.affine.add_revolute_joint(world, upper, (0.0, -0.12, 0.0),
                                             (0.0, 0.12, 0.0), body_j=fore,
                                             stiffness=1e8)
    # A real elbow has a range of motion; without stops the unopposed muscle
    # would curl the forearm straight over the top.
    trusty.affine.add_joint_limit(world, elbow, lo=ELBOW_LO, hi=ELBOW_HI,
                                  margin=0.05, stiffness=1e3)

    points = np.array([ORIGIN_POINT, INSERTION_POINT], dtype=np.float64)
    rest_length = float(np.linalg.norm(points[1] - points[0]))
    # The fiber starts at its optimal length (the rest path minus the tendon),
    # where it pulls hardest.
    l_tendon_slack = 0.30
    l_opt = rest_length - l_tendon_slack
    muscle = trusty.actuators.add_muscle(
        world, [upper, fore], points, f_max=f_max, l_opt=l_opt, l_tendon_slack=l_tendon_slack,
        model=model)

    print(f"Two-link arm, one muscle: f_max={f_max:.0f} N, "
          f"rest path {rest_length:.3f} m (l_opt {l_opt:.3f}, "
          f"tendon {l_tendon_slack:.2f}). Elbow range "
          f"[{np.rad2deg(ELBOW_LO):.0f}, {np.rad2deg(ELBOW_HI):.0f}] deg.")
    return world, muscle, upper, fore


def elbow_angle(world, fore):
    """Forearm pitch about the hinge (rad), from its surface centroid.

    The forearm's centroid starts on +x level with the hinge, so the angle it
    subtends at the origin is the elbow flexion directly: 0 straight, rising as
    the muscle curls it up."""
    V = np.asarray(trusty.affine.surface_positions(world, fore))
    c = V.mean(axis=0)
    return float(np.arctan2(c[2], c[0]))


def settle(world, muscle, fore, activation, steps):
    """Hold `activation` for `steps` steps and return the settled state."""
    trusty.actuators.set_muscle_activation(world, muscle, activation)
    for _ in range(steps):
        world.step()
    return (elbow_angle(world, fore),
            trusty.actuators.muscle_length(world, muscle),   # m
            trusty.actuators.muscle_tension(world, muscle))    # N


def run_headless(world, muscle, fore, steps):
    print(f"Settling {steps} steps per activation level...\n")
    print("  activation   elbow (deg)   length (m)   tension (N)")
    levels = [0.0, 0.25, 0.5, 0.75, 1.0]
    results = []
    for a in levels:
        ang, length, force = settle(world, muscle, fore, a, steps)
        results.append((a, ang, length, force))
        print(f"  {a:9.2f}   {np.rad2deg(ang):10.2f}   {length:9.4f}   {force:9.2f}")

    angles = [np.rad2deg(r[1]) for r in results]
    lengths = [r[2] for r in results]
    forces = [r[3] for r in results]
    # Each tension is read at that level's own settled pose, so the column is
    # not a force-length curve and need not rise.
    print(f"\npassive elbow angle   = {angles[0]:+.2f} deg")
    print(f"activated elbow angle = {angles[-1]:+.2f} deg  "
          f"(stop at {np.rad2deg(ELBOW_HI):.0f} deg)")
    print(f"path length {lengths[0]:.4f} -> {lengths[-1]:.4f} m,  tension "
          f"{forces[0]:.2f} -> {forces[-1]:.2f} N")


def run_polyscope(world, muscle, upper, fore, steps):
    try:
        import polyscope as ps
        import polyscope.imgui as psim
    except ImportError:
        print("polyscope not installed; falling back to headless.")
        run_headless(world, muscle, fore, steps)
        return

    ps.init()
    ps.set_up_dir("z_up")
    ps.set_ground_plane_mode("shadow_only")

    meshes = []
    for name, body in (("upper arm", upper), ("forearm", fore)):
        V = trusty.affine.surface_positions(world, body)
        _, F = trusty.surface.mesh(world, body)
        m = ps.register_surface_mesh(name, np.asarray(V), np.asarray(F))
        m.set_color((0.75, 0.72, 0.68))
        meshes.append((body, m))

    path = np.asarray(trusty.actuators.muscle_points(world, muscle))
    edges = np.array([[i, i + 1] for i in range(len(path) - 1)], dtype=np.int64)
    muscle_curve = ps.register_curve_network("muscle", path, edges)
    muscle_curve.set_radius(0.02, relative=False)
    muscle_curve.set_color((0.80, 0.25, 0.25))

    state = {"activation": 0.0, "playing": True}

    def callback():
        changed, state["activation"] = psim.SliderFloat(
            "activation", state["activation"], v_min=0.0, v_max=1.0)
        _, state["playing"] = psim.Checkbox("play", state["playing"])
        if state["playing"] or changed:
            trusty.actuators.set_muscle_activation(world, muscle, state["activation"])
            world.step()
            for body, m in meshes:
                m.update_vertex_positions(
                    np.asarray(trusty.affine.surface_positions(world, body)))
            muscle_curve.update_node_positions(
                np.asarray(trusty.actuators.muscle_points(world, muscle)))
        psim.Text(f"elbow    {np.rad2deg(elbow_angle(world, fore)):+7.2f} deg")
        psim.Text(f"length   {trusty.actuators.muscle_length(world, muscle):7.4f} m")
        psim.Text(f"tension  {trusty.actuators.muscle_tension(world, muscle):7.2f} N")

    ps.set_user_callback(callback)
    ps.show()


def main():
    p = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    p.add_argument("--f-max", type=float, default=300.0,
                   help="peak isometric muscle force (N)")
    p.add_argument("--steps", type=int, default=120,
                   help="settle steps per activation level (headless)")
    p.add_argument("--backend", choices=["auto", "cpu", "accelerate", "cuda"], default="auto")
    p.add_argument("--muscle-model", choices=["hill", "polynomial"], default="hill",
                   help="force-length law; polynomial is exp-free and better "
                        "conditioned under overstretch")
    p.add_argument("--no-viewer", action="store_true")
    args = p.parse_args()

    model = {"hill": trusty.actuators.MuscleModel.Hill,
             "polynomial": trusty.actuators.MuscleModel.Polynomial}[args.muscle_model]

    world, muscle, upper, fore = build(args.f_max, args.backend, model)
    if args.no_viewer:
        run_headless(world, muscle, fore, args.steps)
        return
    run_polyscope(world, muscle, upper, fore, args.steps)


if __name__ == "__main__":
    main()

Fiber muscles

add_fiber_muscle(world, body, directions, stiffness) makes a FEM solid (embedded ones included) or a reduced solid a muscle: raising its activation contracts the body along a field of fiber directions, (1, 3) for one direction everywhere or one row per element. stiffness, in Pa, is the pull at full activation, one number or one per element (0 for a tendon). On a reduced solid, add it to the world the basis is built from as well, so the basis can follow the contraction. The first step rejects one on any other body.

Joint drives

add_joint_drive(world, joint, stiffness, damping=0) drives an affine joint toward a target with a servo of gain stiffness: an angle for a revolute joint (N·m/rad), a slide for a prismatic one (N/m), a 3x3 relative rotation for a spherical one (N·m, on the squared difference of the two bodies' orientations). damping adds a torque (or force) of -damping times the joint's rate: N·m·s/rad for a hinge or a spherical joint, N·s/m for a slider. The target starts at the joint's rest configuration. Any other entity is rejected.

set_joint_effort(world, drive, effort) adds a constant torque about a hinge (N·m) or force along a slider (N), positive toward increasing angle or slide, on top of the servo's pull; it starts at 0. A drive of stiffness 0 is a pure torque source, and turns its hinge on through any number of turns. A spherical joint takes no effort: the first step rejects one.

Functions

Function Does
add_cable(world, bodies, positions, drive) add a cable
add_muscle(world, bodies, positions, f_max, l_opt, l_tendon_slack, pennation, model) add a muscle
add_fiber_muscle(world, body, directions, stiffness) add a fiber muscle
add_joint_drive(world, joint, stiffness, damping) add a joint drive
set_cable_tension(world, cable, tension) command a TensionDrive cable, in N
set_cable_length(world, cable, length) command a LengthDrive cable, in m
cable_length(world, cable) a cable's polyline length from the last step, in m
cable_tension(world, cable) a cable's tension from the last step, in N
cable_points(world, cable) a cable's current points, (n, 3)
set_muscle_activation(world, muscle, activation) command a muscle or fiber muscle
muscle_activation(world, muscle) a muscle's or fiber muscle's activation
muscle_length(world, muscle) a muscle's polyline length from the last step, in m
muscle_tension(world, muscle) a muscle's tension from the last step, in N
muscle_points(world, muscle) a muscle's current points, (n, 3)
set_joint_target(world, drive, target) command a joint drive
joint_target(world, drive) a revolute or prismatic joint drive's target
set_joint_effort(world, drive, effort) command a revolute or prismatic joint drive's torque (N·m) or force (N)
joint_effort(world, drive) a revolute or prismatic joint drive's effort
joint_position(world, drive) a joint drive's angle (rad) or slide (m) from the last step
num_actuators(world) how many actuators of every kind there are
set_project_positive_definite(world, project) make a muscle's Hessian positive definite on every Newton iteration (default off); call before the first step

Each raises for an actuator of the wrong kind: a cable takes no activation, a fiber muscle has no polyline, a length-driven cable takes no tension.

Reference

Every function and argument: trusty.actuators reference.