Skip to content

Loads

trusty.loads applies forces to bodies: a traction on part of a surface, a force on chosen vertices, or a pressure inside a closed cavity. The first two, traction loads and point loads, are the surface loads. Clamping a face is one call, add_pin; see Constraints.

Quick example

A bar clamped at one end and pulled by a traction on the other:

world = trusty.World(backend=backend,
                     time_stepping="static",   # solve for the equilibrium each step
                     gravity=(0.0, 0.0, 0.0))  # the load is the only force

mesh = make_mesh(size=BAR_SIZE, res=BAR_RES)
material = trusty.StableNeoHookean(youngs_modulus=1e6, poisson_ratio=0.3)
body = add_solid(world, mesh, material, density=1000.0)

X = np.asarray(mesh.vertices)
clamp = np.flatnonzero(np.abs(X[:, 0]) < 1e-6).tolist()  # the x = 0 end
trusty.constraints.add_pin(world, body, clamp)

load_faces = end_faces(world, body, x=BAR_SIZE[0])   # triangles on the x = 1 end
load = trusty.loads.add_traction_load(
    world, body, load_faces, np.zeros((len(load_faces), 3)))  # Pa, one row per face

A bar clamped to a wall and stretched by arrows on its free end

The red bar is loaded and the grey one behind it is the same bar at rest. The orange points are the clamped nodes, and the arrows show the traction on the end face. The load starts at zero, and the script raises it step by step; see Traction loads.

Load Function Works on
Traction load add_traction_load solids, shells, embedded solids, affine bodies
Point load add_point_load solids, shells, rods, embedded solids, affine bodies
Pressure cavity add_pressure_cavity solids, shells, embedded solids, affine bodies

Add every load before the first world.step(). After that you can change tractions, but you can't add new loads.

Full script: python examples/loads/fem_traction_load.py
"""Traction load: a bar clamped at one end and pulled by a traction on the other.

A hex (or tet) bar is clamped on its x = 0 face and carries a traction (force
per unit area, Pa) on its x = 1 end face. The traction is a *dead load*: it
keeps its world direction and acts on the faces' rest area, like gravity acts
on the body's mass.

`add_traction_load` puts the load on the end faces, starting at zero, and
returns a handle to it. The run ramps the load up to its full value with
`set_tractions` on that handle, stretching the bar a little further each step. Each step solves for static equilibrium (no
inertia) with gravity off, so the stretch is the load's doing alone.

Usage:
    python examples/loads/fem_traction_load.py              # polyscope
    python examples/loads/fem_traction_load.py --no-viewer  # print the stretch
    python examples/loads/fem_traction_load.py --element tet
"""

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.1, 0.1)
BAR_RES = (20, 2, 2)
TRACTION_MAX = 1.0e5  # Pa in +x, the fully ramped end traction
SOLIDS = {"hex": (trusty.make_beam_hex_mesh, trusty.fem.add_hex_solid),
          "tet": (trusty.make_beam_tet_mesh, trusty.fem.add_tet_solid)}


def end_faces(world, body, x):
    """Indices of the body's surface triangles that lie on the plane at `x`."""
    _, tris = trusty.surface.mesh(world, body)
    verts = np.asarray(trusty.fem.positions(world, body))
    on_plane = np.all(np.abs(verts[tris, 0] - x) < 1e-9, axis=1)
    return np.flatnonzero(on_plane).tolist()


def build_world(backend: str = "auto", element: str = "hex"):
    make_mesh, add_solid = SOLIDS[element]
    world = trusty.World(backend=backend,
                         time_stepping="static",   # solve for the equilibrium each step
                         gravity=(0.0, 0.0, 0.0))  # the load is the only force

    mesh = make_mesh(size=BAR_SIZE, res=BAR_RES)
    material = trusty.StableNeoHookean(youngs_modulus=1e6, poisson_ratio=0.3)
    body = add_solid(world, mesh, material, density=1000.0)

    X = np.asarray(mesh.vertices)
    clamp = np.flatnonzero(np.abs(X[:, 0]) < 1e-6).tolist()  # the x = 0 end
    trusty.constraints.add_pin(world, body, clamp)

    load_faces = end_faces(world, body, x=BAR_SIZE[0])   # triangles on the x = 1 end
    load = trusty.loads.add_traction_load(
        world, body, load_faces, np.zeros((len(load_faces), 3)))  # Pa, one row per face
    return world, body, load, mesh


def traction_at(step: int, steps: int) -> float:
    return TRACTION_MAX * min(1.0, (step + 1) / max(1, steps))


def ramp(world, load, step: int, steps: int):
    """Set this step's traction on every loaded face, then advance."""
    n = trusty.loads.num_loaded_faces(world, load)
    t = np.tile([traction_at(step, steps), 0.0, 0.0], (n, 1))
    trusty.loads.set_tractions(world, load, t)
    world.step()


def _register(ps, world, body, mesh, element):
    x = np.asarray(trusty.fem.positions(world, body)).copy()
    cells = {"hexes": np.asarray(mesh.elements)} if element == "hex" else \
        {"tets": np.asarray(mesh.elements)}
    ps_mesh = ps.register_volume_mesh("bar", x, **cells)
    ps_mesh.set_edge_width(1.0)
    return ps_mesh


def run_polyscope(world, body, load, mesh, element, steps):
    ps = init_polyscope(headless=False)
    ps_mesh = _register(ps, world, body, mesh, element)
    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"]) and state["i"] < steps:
            ramp(world, load, state["i"], steps)
            state["i"] += 1
            ps_mesh.update_vertex_positions(trusty.fem.positions(world, body))
        t = traction_at(state["i"] - 1, steps) if state["i"] else 0.0
        psim.Text(f"step {state['i']} / {steps}   traction_x = {t:.0f} Pa")

    ps.set_user_callback(callback)
    ps.show()


def run_headless(world, body, load, mesh, steps):
    rest = np.asarray(mesh.vertices)
    for i in range(steps):
        ramp(world, load, i, steps)
    x = np.asarray(trusty.fem.positions(world, body))
    tractions = trusty.loads.tractions(world, load)

    def mean_dx(xref):
        on = np.abs(rest[:, 0] - xref) < 1e-9
        return float((x[on, 0] - rest[on, 0]).mean())

    area = BAR_SIZE[1] * BAR_SIZE[2]
    print(f"end traction {tractions[0, 0]:.0f} Pa on {len(tractions)} faces "
          f"= {tractions[0, 0] * area:.0f} N in total")
    print(f"loaded (x = 1) end moved {mean_dx(BAR_SIZE[0]):+.4f} m")
    print(f"clamped (x = 0) end moved {mean_dx(0.0):+.4f} m")


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--backend", choices=["auto", "cpu", "accelerate", "cuda"], default="auto")
    parser.add_argument("--element", choices=list(SOLIDS), default="hex")
    parser.add_argument("--steps", type=int, default=20,
                        help="load increments to reach the full traction")
    parser.add_argument("--no-viewer", action="store_true",
                        help="headless: ramp the load, then print the stretch")
    args = parser.parse_args()

    world, body, load, mesh = build_world(args.backend, args.element)
    if args.no_viewer:
        run_headless(world, body, load, mesh, args.steps)
    else:
        run_polyscope(world, body, load, mesh, args.element, args.steps)


if __name__ == "__main__":
    main()

Traction loads

add_traction_load(world, body, faces, tractions) applies a traction (force per unit area, Pa) to chosen triangles of a body's surface and returns a handle to the load. It is a dead load: it keeps its direction in the world and acts on the triangles' rest area, so a traction t on an area A always pulls with t × A. In the quick example that is 1e5 Pa on 0.01 m², or 1000 N.

faces is a plain list of the body's surface triangle indices, which are rows of F in V, F = trusty.surface.mesh(world, body) for every kind of body. You compute it from the vertex positions you already have, so a triangle is chosen by whatever you can say about its corners, and the list must be non-empty with each triangle named once, in the order its traction row follows.

The quick example picks the triangles on the bar's end:

_, tris = trusty.surface.mesh(world, body)
verts = np.asarray(trusty.fem.positions(world, body))
on_plane = np.all(np.abs(verts[tris, 0] - x) < 1e-9, axis=1)
return np.flatnonzero(on_plane).tolist()

tractions has one row per face in faces, so the load can vary across the surface. set_tractions(world, load, tractions) replaces all of them on the handle from the next step on. The example ramps the load up this way, so each solve starts close to the last:

n = trusty.loads.num_loaded_faces(world, load)
t = np.tile([traction_at(step, steps), 0.0, 0.0], (n, 1))
trusty.loads.set_tractions(world, load, t)
world.step()

A body can carry several traction loads, each with its own handle, so loads on different faces can be driven independently. A rod has no surface triangles, so it takes no traction load; give it a point load instead.

Point loads

add_point_load(world, body, vertices, forces) applies a force (N) to each of chosen vertices of a body and returns a handle to the load. Like a traction load it is a dead load, so each force keeps its direction and size in the world however the body moves, and it adds no stiffness. It is the load for a pinched shell, a tip force on a cantilever or a rod, or a line force you have already split onto the vertices of an edge.

vertices are rows of the body's surface vertices, which for a solid, a shell and a rod are its nodes, and each must lie on a surface triangle or, for a rod, an edge, so a node inside a solid is refused. forces has one row per vertex, and set_point_forces(world, load, forces) replaces them from the next step on. point_forces(world, load) reads them back.

Pressure cavities

add_pressure_cavity(world, body, faces, pressure) drives the volume enclosed by a closed set of surface triangles with a gauge pressure (Pa), the conservative potential -pressure * V, and returns a handle. The triangles must close and enclose a volume, which is checked when the cavity is added, and either winding works, so a void inside a solid and a closed shell are both fine. set_cavity_pressure(world, cavity, pressure) changes the pressure from the next step on, and cavity_volume(world, cavity) reads the enclosed volume, which is the rest volume until the first step.

Function Does
add_traction_load(world, body, faces, tractions) load surface triangles with tractions, (len(faces), 3), Pa; returns the load handle
set_tractions(world, load, tractions) replace the load's tractions
tractions(world, load) the load's current tractions
num_loaded_faces(world, load) how many faces the load covers
add_point_load(world, body, vertices, forces) load surface vertices with forces, (len(vertices), 3), N; returns the load handle
set_point_forces(world, load, forces) replace the point load's forces
point_forces(world, load) the point load's current forces
add_pressure_cavity(world, body, faces, pressure) pressurize the volume the faces enclose; returns the cavity handle
set_cavity_pressure(world, cavity, pressure) change the pressure
cavity_volume(world, cavity) the enclosed volume, m³

Reference

Every function and argument: trusty.loads reference.