Articulations (kinematic trees)#
cuNLS optimizes over the generalized coordinates of articulated mechanisms (robot arms, hands, humanoids, closed-chain linkages): inverse kinematics with hard joint limits, closed loops and mimic joints, many problems per call.
ArticulationTopology: the kinematic tree, built once from flat joint arrays or a URDF file (pycunls.articulation.topology_from_urdf).ArticulationStateBatch: many instances of one topology; each holds itsjoint_qand a cache of link poses that the factors read.Kinematic factors:
LinkPositionFactorBatch,LinkOrientationFactorBatch,LinkPoseFactorBatch,PostureFactorBatchandMimicJointFactorBatch. Every Jacobian is analytic.Closed loops:
pycunls.articulation.loop_closurebuilds a loop-closing joint as equality constraints from existing factors (see Closed loops and mimic joints).LinkFrameFactorBatch: existing factors over SE(3) poses, 3D points or SO(3) rotations (built-in or a Warp kernel) on frames of links, for objectives of your own (see Custom kinematic objectives).
Read Conventions first: an articulation has several frames, four index spaces and three pose layouts, and most mistakes come from mixing them up.
Conventions#
Frames#
All poses are world_from_frame transforms: a pose \(X = (R, p)\) maps a point from the
frame into the world, \(x_{world} = R\,x + p\). Lengths are in meters, angles in radians.
World: the frame every target, link pose and motion column is expressed in.
Root frame
root_pose: where joints with parent -1 attach (the identity by default; set it to place a fixed-base robot on a table). A loop closure with parent -1 means the world.Link frame: each link’s own frame; \(X_L(q)\) is its world pose.
Joint frame: each joint has a frame fixed on its parent link,
joint_X_p, and one fixed on its child link,joint_X_c; the joint motion \(X_{joint}(q)\) happens between them. \(A = X_{parent}(q)\,X_p\) is the parent-anchor frame: the joint frame as the parent carries it, in which the joint axes, BALL rotations and FREE positions are expressed.A frame on a link (a tool tip, a camera mount): an offset \(X_{off}\) in the link frame; its world pose is \(X_L(q)\,X_{off}\) (the
offsets/points/frame_offsetsarguments of the link factors).
Forward kinematics, joint by joint from the root (parents first):
Index spaces#
Four kinds of integer indices describe one articulation; each argument says which one it takes.
Index |
Range |
Where it comes from |
Taken by |
|---|---|---|---|
joint j |
0 .. |
order of the joint arrays ( |
the topology arrays |
link l |
0 .. |
link l is the child of the joint with |
|
coordinate c |
0 .. |
joint j owns |
|
DOF d |
0 .. |
joint j owns |
bounds and limits, posture weights, |
Joint j and link j are the same index only when joint_child[j] == j (always true for
topology_from_urdf, not required for joint arrays). Coordinates and DOFs differ for BALL (4
coordinates, 3 DOFs) and FREE (7, 6) joints; topology.scalar_coord[d] maps a scalar DOF to its
coordinate (-1 for BALL and FREE DOFs). Two more indices belong to the problem, not the robot:
the instance (which articulation of the state batch, 0 .. capacity - 1) and the state
slot (a factor’s k-th state, in the order of its state_sizes).
Pose layouts#
The same pose appears in three layouts. Quaternions are always (x, y, z, w), as in
Warp’s wp.transform and SciPy’s Rotation.as_quat(); libraries that put w first (Eigen’s
constructor, MuJoCo) need reordering.
Layout |
Floats |
Used by |
|---|---|---|
position, quaternion |
7: |
|
position |
3: |
|
quaternion |
4: |
|
row-major 3x4 |
12 |
the state’s cache of link poses ( |
row-major 4x4 |
16 |
|
Joint types, coordinates and tangents#
Joint |
Coordinates |
Tangent (DOFs) |
\(X_{joint}(q)\) |
|---|---|---|---|
PRISMATIC |
1 |
1 |
translation \(a\,q\) |
REVOLUTE |
1 |
1 |
rotation about \(a\) by \(q\) |
BALL |
4 (quaternion x, y, z, w) |
3: rotation vector in A, \(quat \leftarrow Exp(\delta) \otimes quat\) |
rotation \(quat\) |
FREE |
7 (position, quaternion) |
6: \((\delta p, \delta\theta)\) in A |
\((p, quat)\) |
FIXED |
0 |
0 |
identity |
D6 |
linear + angular axes |
one per axis |
translation \(\sum a_k q_k\), then the angular axes as intrinsic rotations (each axis rotated by the rotations before it); angular axes must be orthogonal |
The tangent is cuNLS’s own chart: FREE’s \(\delta p\) is the change of the joint position in
A, not a velocity referenced to a center of mass. BALL and FREE quaternions are stored
normalized (a zero one becomes the identity). Loop-closing joints are not part of the tree;
add each one as constraints (pycunls.articulation.loop_closure).
Perturbations: which side, which frame#
A Jacobian is a derivative with respect to a small step \(\delta\); what \(\delta\) means differs between the pieces, and a custom factor must use the right one.
Quantity |
Step \(\delta\) |
Frame |
|---|---|---|
articulation scalar DOF |
\(q \leftarrow q + \delta\) |
(scalar) |
articulation BALL / FREE rotation |
left: \(quat \leftarrow Exp(\delta) \otimes quat\) |
parent-anchor frame A |
|
right: \(X \leftarrow X\,Exp(\delta)\), \(\delta = [\omega, v]\) |
body frame of the pose |
|
\(p \leftarrow p + \delta\) |
world |
|
right: \(R \leftarrow R\,Exp(\delta)\) |
body frame of the rotation |
motion column of DOF j (the cache) |
world twist \((\omega_j, v_j)\) per unit of \(q_j\) |
world, at the world origin: a point x moves with \(\omega_j \times x + v_j\) |
The built-in orientation residuals (LinkOrientationFactorBatch, LinkPoseFactorBatch) are
world-frame rotation vectors \(Log(R_{cur} R^{*T})\); PostureFactorBatch’s rotation rows
live in each joint’s frame A.
Common mistakes#
Passing a joint index where a link index is expected (or a DOF where a coordinate is expected): they coincide only for simple chains of 1-DOF joints.
Quaternions w first: the rotation is silently wrong. cuNLS reads (x, y, z, w) everywhere.
Reading the cache as 4x4: link poses are 12 floats (3x4); only
FrameView.Poseslots ofLinkFrameFactorBatchare 4x4.A custom SE(3) or SO(3) factor with a world-frame or left Jacobian:
PoseandOrientationslots use the right (body) perturbation, likeSE3StateBatchandSO3StateBatch.pycunls.check_jacobianscatches it.Writing
state_device_ptrcoordinates withoutrefresh(stream): the cache keeps the old link poses until the next solve.
Python example: bounded inverse kinematics from a URDF#
import numpy as np
import warp as wp
import pycunls
from pycunls.articulation import topology_from_urdf
robot = topology_from_urdf("fr3.urdf") # limits become hard bounds
topo, n = robot.topology, 1024 # 1024 IK problems
# Solve on Warp's stream: uploads, target updates, solves and reads stay in order.
stream = wp.get_stream()
q0 = wp.array(q_initial, dtype=wp.float32) # (n, topo.coord_count)
targets = wp.array(target_poses, dtype=wp.transform) # (n,): position, quaternion x, y, z, w
links = wp.full(n, robot.link_names.index("fr3_hand"), dtype=wp.int32)
instance = wp.array(np.arange(n, dtype=np.int32)) # factor i acts on instance i
states = pycunls.ArticulationStateBatch(topo, n)
states.set_num_active_states(n)
states.set_joint_q(q0, n, stream)
pose = pycunls.LinkPoseFactorBatch(topo, links, None, targets, None, n)
pose.set_num_active_factors(n)
problem = pycunls.Problem()
problem.add_state_batch(states)
problem.add_factor_batch(pose, [states], instance)
problem.set_problem_partition(n, [instance]) # each problem converges and stops alone
solver = pycunls.AugmentedLagrangianMinimizer()
summary = solver.minimize(stream, problem)
q = wp.zeros((n, topo.coord_count), dtype=wp.float32)
states.get_joint_q(q, n, stream) # asynchronous, on the same stream as q.numpy()
Joint limits are box bounds of the state: the iterates never leave them (projected Gauss-Newton,
see Constraints), so solve with AugmentedLagrangianMinimizer; the plain minimizers
reject a bounded problem. ArticulationStateBatch(topo, n, apply_joint_limits=False) leaves
the coordinates unbounded.
Building an inverse-kinematics solver#
cuNLS has no IK solver class: an application (a simulator, a robot stack) assembles one from the pieces above, which keeps its objectives, seeding and result selection in its own hands. The pieces that make that cheap:
A topology from a scene’s joint arrays. A simulator stores the joints of all its robots and worlds in flat arrays with scene indices (bodies,
joint_q/joint_qdoffsets, per-DOF axes and limits).pycunls.articulation.topology_from_joint_arrays(..., joints=range(first, last))selects one articulation’s joints, remaps them to local indices and returns the topology with the maps between the two:link_of_body(scene body -> link, for thelinksof factors),bodies(link -> scene body),coord_index/dof_index(local -> scene),coord_start(where the articulation’s coordinates start in the scenejoint_qwhen they are contiguous) andloop_joints(joints whose child already has a tree joint: add them withpycunls.articulation.loop_closure). The arrays may be GPU arrays (copied once to the host).Scene arrays in place.
set_joint_q/get_joint_qtake astride(floats between instances), so instances embedded in a larger array are read and written without a gather: with one articulation per replicated world of a scene-widejoint_q,states.set_joint_q(scene_q[art.coord_start:], worlds, stream, stride=coords_per_world).Forward kinematics and link poses.
set_joint_qruns forward kinematics;get_link_transforms(out, n, stream, stride=0)writes every link’s world pose (7 floats: position, quaternion x, y, z, w; the convention of the factor targets) of every instance, with a stride for writing into a scene-wide pose array. Use it to check a solution (position and angle errors) or to pick the best of several seeds.Targets change, the problem does not. Factors read their device arrays (targets, weights, links) at every evaluation: write the next targets into the same arrays (
wp.copy, a kernel) on the stream the solve runs on (withstream = wp.get_stream()as above, any Warp work is; work on another stream is not ordered with the solve) and callminimizeagain. Repeated solves skip the structure setup withbase_options.reuse_structureof the augmented Lagrangian’s options:options = pycunls.AugmentedLagrangianMinimizerOptions() options.base_options.reuse_structure = True solver = pycunls.AugmentedLagrangianMinimizer(options)
Several seeds per problem. Make
problems x seedsinstances (seeds next to each other), give each instance its own subproblem, solve once, then compare the link-pose errors of each problem’s seeds and keep the best one.Frozen DOFs. A box of zero width,
lower == upper == q, holds a scalar DOF atq.set_bounds(lower, upper)replaces all bounds, so start from the joint limits and change only the frozen entries:lower = np.tile(topo.lower_limits, (n, 1)).astype(np.float32) # (n, topo.dof_count) upper = np.tile(topo.upper_limits, (n, 1)).astype(np.float32) lower[:, dof] = upper[:, dof] = q_frozen states.set_bounds(wp.array(lower), wp.array(upper))
Objectives are factors. Position, orientation and pose targets (with per-row weights), posture regularization, loop-closing joints and mimic joints are factors; constraints are factors wrapped in
ConstraintFactorBatch. Several targets per instance are several factors (or several rows of one batch) connected to the same instance.
Custom kinematic objectives#
An objective the built-in factors do not cover (look at a point, stay above a table, keep clear
of an obstacle, match an object’s pose) is written as an ordinary factor over SE(3) poses,
3D points or SO(3) rotations, which knows nothing about robots. LinkFrameFactorBatch puts it
on the robot, so the factors cuNLS already has work on robot links.
How it works#
The wrapped factor (the inner factor) has state slots, e.g. state_sizes=[6] for one SE(3)
pose. Normally each slot connects to a state of the problem. frame_slots lists the slots that
do not: each receives, at every evaluation, a view of a frame on a link instead, in the
layout and convention of an existing state type.
View |
The slot receives |
As the state type |
Slot tangent |
|---|---|---|---|
|
the frame’s pose, row-major 4x4 |
|
6 |
|
the frame’s origin in the world (3 floats) |
|
3 |
|
the frame’s rotation, row-major 3x3 |
|
3 |
The view is named explicitly because the tangent size alone is ambiguous (6: a pose or a 6-vector; 3: a rotation or a point).
inner factor slots [0: pose (6)] [0: pose (6), 1: pose (6)]
frame_slots [(0, Pose)] [(0, Pose)]
LinkFrameFactorBatch slots [0: articulation instance] [0: articulation instance,
1: SE3 pose (a problem state)]
For factor f and frame slot s (the position of the slot in frame_slots; nF =
len(frame_slots)):
L = topology_links[f * nF + s]: the topology link that carries the frame (a link index, e.g.robot.link_names.index("wrist")).X_off = frame_offsets[f * nF + s]: where the frame sits on that link, in the link frame (7 floats: position, quaternion x, y, z, w;None: the link frame itself).The frame is \(F_s = X_L(q)\,X_{off} = (R, p)\); the inner factor receives its view and evaluates as if the slot were a state of the view’s type, returning its residual and its Jacobian columns for that slot (6 for a pose, 3 otherwise).
The wrapper turns those columns into joint columns. Per unit of DOF j (world motion column \((\omega_j, v_j)\)), a pose moves by the body twist \((R^T\omega_j,\; R^T(\omega_j \times p + v_j))\), a position by \(\omega_j \times p + v_j\), an orientation by \(R^T\omega_j\); \(\partial r / \partial q_j\) sums these over the frame slots whose link DOF j moves.
The residual size and active count are the inner factor’s (set_num_active_factors on the
wrapper sets the inner one).
# The tool tip stays above a table at z = h: a halfspace a^T p <= b on the tip's position.
plane = pycunls.HalfspaceFactorBatch3(normals, offsets, n) # a = (0, 0, -1), b = -h
tip = pycunls.LinkFrameFactorBatch(topo, plane, frame_slots=[(0, pycunls.FrameView.Position)],
topology_links=tool_links, frame_offsets=tip_offsets)
tip.set_num_active_factors(n)
problem.add_factor_batch(pycunls.ConstraintFactorBatch(tip, pycunls.ConstraintKind.Inequality),
[states], instance)
Writing the inner factor#
Two ways, both in pycunls.warp:
A residual function only (
WarpFunctionFactorBatch, see pycunls.warp.WarpFunctionFactorBatch): a Warp function of the frames (awp.transformfor aPoseview,wp.vec3forPosition,wp.quatforOrientation) and of one per-factor data item; Warp’s automatic differentiation provides the Jacobian (checked once against central differences):@wp.func def look_at(X: wp.transform, target: wp.vec3) -> wp.vec4: d = wp.quat_rotate_inv(wp.transform_get_rotation(X), target - wp.transform_get_translation(X)) u = wp.normalize(d) return wp.vec4(u[0], u[1], u[2] - 1.0, wp.length(d) - 0.35) # look along +z from 0.35 m inner = pycunls.warp.WarpFunctionFactorBatch(look_at, data=wp.array(points, dtype=wp.vec3), capacity=n) camera = pycunls.LinkFrameFactorBatch(topo, inner, frame_slots=[(0, pycunls.FrameView.Pose)], topology_links=wrist_links, frame_offsets=mounts)
An analytic Jacobian (a
WarpFactorBatchwhosestate_sizesmatch the views: 6 for a pose, 3 for a position or orientation; see Custom Factors and States (Python and C++)). The device functionspose_at,point_atandrotation_atread one entry of the item-major pointer table in its view’s layout (awp.transform, awp.vec3, awp.mat33): state k of item t is entryt * K + kfor a factor with K states.jacobian_indexgives the position of a Jacobian entry:X = pycunls.warp.pose_at(state_pointers, t * K + 0) # state 0 of item t, a wp.transform jacobians[pycunls.warp.jacobian_index(t, row, column, num_rows, num_columns)] = value
For a pose, Jacobian columns are with respect to the right perturbation \(X\,Exp([\omega, v])\), under which, to first order, \(p \to p + R\,v\) and \(R \to R\,(I + [\omega]_\times)\). Two useful consequences: a world point fixed in the frame, \(x = R c + p\), has \(\partial x / \partial \omega = -R [c]_\times\) and \(\partial x / \partial v = R\); a world point t seen in the frame, \(d = R^T (t - p)\), has \(\partial d / \partial \omega = [d]_\times\) and \(\partial d / \partial v = -I\).
The analytic form is faster (one kernel, while the reverse pass of the residual-function form
runs the function once per residual row); the residual-function form is quicker to write and a
reference for the analytic one. When only the
origin or only the rotation matters, a position or orientation view keeps the factor smaller.
Check either with pycunls.check_jacobians(problem) before solving.
Recipes#
Objective |
Inner factor and views |
|---|---|
a point on a link reaches a target |
|
stay above a table / on one side of a wall |
|
stay inside a workspace box |
|
a frame reaches a target orientation |
|
relative orientation of two links |
|
a frame reaches a target pose |
|
relative pose of two links |
|
keep a point off a sphere |
|
a link and an object pose solved together (grasping, hand-eye) |
|
Constraints: always wrap the
LinkFrameFactorBatch(ConstraintFactorBatcharound it), never its inner factor: a constraint inside would be hidden from the augmented Lagrangian, and the constructor rejects it.Joint-space objectives (soft limits, preferred ranges) need no wrapper: a custom factor on the articulation state reads DOF d of a scalar joint at float
topology.scalar_coord[d]of its instance’s storage. Hard joint boxes are the state’s bounds (set_bounds).Speed: an evaluation runs three steps (copy the views, the inner factor, the chain rule). For batched IK (7-DOF arm, 32k problems) a position plus an orientation view cost about 1.26x the fused
LinkPoseFactorBatch; use the built-in kinematic factors for what they cover.
python/examples/robot_custom_objective.py puts it together: a 7-DOF arm aims a wrist camera
at 512 points with a Warp look-at factor (pose view), keeps the elbow off an obstacle
(SE3SphereClearanceFactorBatch, pose view) and the camera above a table
(HalfspaceFactorBatch3, position view), under hard joint limits.
Closed loops and mimic joints#
A loop-closing joint keeps two joint frames together in the directions its type does not allow:
the parent frame \(X_P X_p\) (\(X_P\) the parent link’s world pose, the identity for the
world) and the child frame \(X_C X_c\). It is not a factor class of its own but equality
constraints built from existing factors on LinkFrameFactorBatch views of the two frames
(slot 0 the parent frame, slot 1 the child frame; see Custom kinematic objectives):
Joint |
Rows |
|---|---|
BALL |
origins coincide: |
REVOLUTE |
origins coincide (3), and |
PRISMATIC |
rotations equal: |
FIXED |
poses equal: |
pycunls.articulation.loop_closure builds them:
from pycunls.articulation import loop_closure
# links: (parent link or -1 for the world, child link) per loop; frames: joint_X_p then
# joint_X_c per loop (14 floats); axes: the joint axis in the joint frame (3 floats).
loop = loop_closure(topo, pycunls.ArticulationJointType.Revolute, links, frames, axes)
loop.set_num_active_factors(n) # batches start with 0 active factors
for constraint in loop.constraints:
problem.add_factor_batch(constraint, [states], instance) # one loop per instance
The arrays are used in place (frames is exactly the views’ frame_offsets), and
loop.factors are the unconstrained rows, for pycunls.check_jacobians. Rows may be
redundant (a planar four-bar’s revolute loop has 6 rows of rank 2); the augmented Lagrangian
tolerates that, and constraint rows only define where the loop is closed, so their
parameterization does not change the solution. To assemble a mechanism at given actuated
angles, add a PostureFactorBatch with a high weight on the actuated DOFs and a low one on
the passive DOFs: when the solve converges, the result is a nearby closed configuration. The
posture is a soft preference, so the actuated angles may move if the loop cannot close at them;
to hold them exactly, give the actuated DOFs zero-width bounds (lower == upper) and check
that the solve converged (a loop that cannot close at those angles then fails the
constraints).
A mimic joint q_m = a + b q_ref (URDF <mimic>) is a
MimicJointFactorBatch wrapped the same way; topology_from_urdf returns the couplings in
mimic_joints.
Performance notes#
The state’s
Plusruns forward kinematics once per update and stores link poses and motion columns; factors read them, so evaluating a residual does not traverse the tree. Jacobians still visit every DOF: their cost grows with the number of movable joints (dense rows).One subproblem per IK problem (
set_problem_partition): each one converges and stops on its own.The Jacobian of a factor is dense over the articulation’s DOFs; the Hessian assembler stages each factor’s block in shared memory, which bounds an articulation at roughly 140 DOFs for 6-row factors and roughly 85 DOFs with
PostureFactorBatch(one row per DOF).After writing coordinates through
state_device_ptrdirectly, callrefresh(stream)beforepycunls.evaluate;set_joint_qand the minimizers refresh on their own.