Skip to content

Inverse Kinematics

Differential IK

min sum_tasks || weight * (J v - v_des) ||^2 + (reg + lam) * ||v||^2 s.t. A v == b; G v <= h

i.e. - Minimimize the weighted task velocity error, plus regularization and damping terms for stability - Subject to a set of equality and inequality constraints

Note that since we use ElastiQP as our solver, inequality constraints are automatically (and efficiently) relaxed with an L1 penalty term. These constraints are held exactly when the problem is feasible, and only relaxed when the problem is infeasible*

*See the ElastiQP paper for more details, and more precise conditions on relaxation and when this occurs

Equality constraints are still held as hard constraints with ElastiQP, unless explicitly posed as an elastic equality. In this case, the equality is converted to a pair of opposing elastic inequalities.

DiffIKSolver

Differential IK with ElastiQP

Parameters:

Name Type Description Default
robot Robot

Robot model

required
tasks Sequence[Task]

Tracking tasks

required
constraints Sequence[InequalityConstraint | EqualityConstraint]

Constraints. Defaults to an empty tuple (unconstrained)

()
regularization ArrayLike

Tikhonov regularization on v, scalar or shape (nv,). Defaults to 1e-8

1e-08
damping float

Levenberg-Marquardt damping, per unit of task cost. Defaults to 0.0 (no damping)

0.0
solver_tol float

QP solver tolerance. Defaults to 1e-5

1e-05
warm_start bool

Whether to warm-start each QP from the previous solution. Defaults to True.

True
Source code in frax/ik/solver.py
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
@jax.tree_util.register_static
class DiffIKSolver:
    """Differential IK with ElastiQP

    Args:
        robot (Robot): Robot model
        tasks (Sequence[Task]): Tracking tasks
        constraints (Sequence[InequalityConstraint | EqualityConstraint]):
            Constraints. Defaults to an empty tuple (unconstrained)
        regularization (ArrayLike): Tikhonov regularization on v,
            scalar or shape (nv,). Defaults to 1e-8
        damping (float): Levenberg-Marquardt damping, per unit of task cost.
            Defaults to 0.0 (no damping)
        solver_tol (float): QP solver tolerance. Defaults to 1e-5
        warm_start (bool): Whether to warm-start each QP from the previous
            solution. Defaults to True.
    """

    def __init__(
        self,
        robot: Robot,
        tasks: Sequence[Task],
        constraints: Sequence[InequalityConstraint | EqualityConstraint] = (),
        regularization: ArrayLike = 1e-8,
        damping: float = 0.0,
        solver_tol: float = 1e-5,
        warm_start: bool = True,
    ):
        assert len(tasks) > 0
        assert damping >= 0
        self.robot = robot
        self.tasks = tuple(tasks)
        self.constraints = tuple(constraints)
        self.regularization = np.broadcast_to(
            np.asarray(regularization, dtype=float), (robot.nv,)
        ).copy()
        self.damping = damping
        self.solver_tol = solver_tol
        self.warm_start = warm_start
        self.max_gain = _max_gain(self.tasks + self.constraints)
        for c in self.constraints:
            assert isinstance(c, InequalityConstraint | EqualityConstraint), (
                f"{type(c).__name__} is neither an InequalityConstraint nor an "
                + "EqualityConstraint"
            )
        for term in self.tasks + self.constraints:
            assert term.robot is robot, (
                f"{type(term).__name__} was built for a different robot than the solver's"
            )
        self.inequalities = tuple(
            c for c in self.constraints if isinstance(c, InequalityConstraint)
        )
        self.equalities = tuple(
            c for c in self.constraints if isinstance(c, EqualityConstraint)
        )
        self.n_eq = sum(c.num_rows for c in self.equalities)

        def penalties(c):
            return np.broadcast_to(np.asarray(c.penalty, dtype=float), (c.num_rows,))

        self.penalty = np.concatenate(
            [penalties(c) for c in self.inequalities] + [np.zeros(0)]
        )
        self.n_ineq = len(self.penalty)

    def init(self, q0: Array) -> SolverState:
        nv = self.robot.nv
        qp_warm_start = (jnp.zeros(nv), jnp.zeros(self.n_eq), jnp.zeros(self.n_ineq))
        q = jnp.asarray(q0, dtype=jnp.float64)  # float64 for elastiqp
        return SolverState(q=q, qp_warm_start=qp_warm_start)

    def _qp(self, q: Array, ref: Any):
        """The diff IK QP at q, and the cost of q

        Returns:
            tuple: P, c, G, h, A, b (A and b are None if there are no hard
                equalities), and the cost of q (the QP objective at v = 0)
        """
        robot = self.robot
        assert q.shape == (robot.nq,), f"q has shape {q.shape}, expected ({robot.nq},)"
        Js, v_des, ws = zip(*(task.linearize(q, ref) for task in self.tasks))
        w = jnp.concatenate(ws)
        WJ = w[:, None] * jnp.concatenate(Js)
        w_v_des = w * jnp.concatenate(v_des)
        task_error = jnp.sum(w_v_des**2)
        P = WJ.T @ WJ + jnp.diag(self.regularization + self.damping * task_error)
        c = -w_v_des @ WJ

        Gs, hs = [jnp.zeros((0, robot.nv))], [jnp.zeros(0)]
        for con in self.inequalities:
            G, h = con.rows(q, ref)
            Gs.append(G)
            hs.append(h)
        G = jnp.concatenate(Gs)
        h = jnp.concatenate(hs)
        cost = task_error + jnp.maximum(-h, 0.0) @ self.penalty

        A = b = None
        if self.equalities:
            As, bs = zip(*(con.rows(q, ref) for con in self.equalities))
            A = jnp.concatenate(As)
            b = jnp.concatenate(bs)
            # Hard equalities have no penalty, so their residual |A 0 - b| is
            # weighted like a default elastic row's
            cost += DEFAULT_PENALTY * jnp.sum(jnp.abs(b))
        return P, c, G, h, A, b, cost

    def cost(self, q: Array, ref: Any) -> Array:
        """The cost of q: the QP objective at v = 0 (if the robot doesn't move),
        for the given reference data"""
        *_, cost = self._qp(q, ref)
        return cost

    def solve(
        self, q: Array, ref: Any, qp_warm_start: tuple[Array, Array, Array]
    ) -> tuple[Array, tuple[Array, Array, Array], SolverInfo]:
        """Solve the diff IK QP

        Args:
            q (Array): Configuration, shape (nq,)
            ref (Any): Per-step reference data (any pytree)
            qp_warm_start (tuple[Array, Array, Array]): QP warm start (x, y, z)

        Returns:
            v (Array): Generalized velocity, shape (nv,)
            qp_warm_start (tuple[Array, Array, Array]): QP solution (x, y, z),
                to warm-start the next QP
            info (SolverInfo): Solver info, with the cost of q
        """
        P, c, G, h, A, b, cost = self._qp(q, ref)
        result = elastiqp.jax.solve(
            P,
            c,
            G,
            h,
            penalty=self.penalty,
            A=A,
            b=b,
            eps_abs=self.solver_tol,
            warm_start=qp_warm_start if self.warm_start else None,
        )
        info = SolverInfo(result.iters, result.converged, cost)
        return result.x, (result.x, result.y, result.z), info

    def step(
        self, state: SolverState, ref: Any, dt: float
    ) -> tuple[SolverState, Array, SolverInfo]:
        """One diff IK step

        Args:
            state (SolverState): Current state
            ref (Any): Per-step reference data (any pytree)
            dt (float): Timestep

        Returns:
            state (SolverState): New state
            v (Array): Generalized velocity, shape (nv,)
            info (SolverInfo): Solver info
        """
        v, qp_warm_start, info = self.solve(state.q, ref, state.qp_warm_start)
        q = self.robot.integrate(state.q, v, dt)
        return SolverState(q=q, qp_warm_start=qp_warm_start), v, info

    def converge(
        self, state: SolverState, ref: Any, max_iters: int, dt_max: float, tol: float
    ) -> tuple[SolverState, Array]:
        """Run differential IK until convergence

        Note: This method should generally only be called as a component of a
        global IK pipeline, or at initialization of a solver. During online
        operation, or sequential calls in an offline pipeline, generally
        only a single diff IK step() should be taken.

        Args:
            state (SolverState): Initial state
            ref (Any): Reference data (any pytree)
            max_iters (int): Maximum iterations
            dt_max (float): Largest stepsize
            tol (float): Convergence tolerance on max |v|

        Returns:
            state (SolverState): Converged state
            iters (Array): Number of iterations
        """
        state, ref = jax.lax.stop_gradient((state, ref))
        robot = self.robot
        v, qp_warm_start, info = self.solve(state.q, ref, state.qp_warm_start)
        dt_min = MIN_STEP_RATIO * dt_max

        def cond(carry):
            *_, i, done = carry
            return ~done & (i < max_iters)

        def body(carry):
            q, v, qp_warm_start, cost, dt, i, _ = carry
            q_new = robot.integrate(q, v, dt)
            v_new, qp_warm_start_new, info = self.solve(q_new, ref, qp_warm_start)
            # Accept if the step lowers the cost
            accept = info.cost < cost
            q, v, qp_warm_start, cost = jax.tree.map(
                lambda new, old: jnp.where(accept, new, old),
                (q_new, v_new, qp_warm_start_new, info.cost),
                (q, v, qp_warm_start, cost),
            )
            # If accepted, double dt, otherwise halve it
            dt = jnp.where(accept, jnp.minimum(2.0 * dt, dt_max), 0.5 * dt)
            # Stopping condition on the max |v| or on a minimum dt
            done = (accept & (jnp.max(jnp.abs(v)) <= tol)) | (dt < dt_min)
            return q, v, qp_warm_start, cost, dt, i + 1, done

        carry = (
            state.q,
            v,
            qp_warm_start,
            info.cost,
            jnp.asarray(dt_max, dtype=state.q.dtype),
            0,
            jnp.max(jnp.abs(v)) <= tol,
        )
        q, _, qp_warm_start, _, _, iters, _ = jax.lax.while_loop(cond, body, carry)
        return SolverState(q=q, qp_warm_start=qp_warm_start), iters

cost(q, ref)

The cost of q: the QP objective at v = 0 (if the robot doesn't move), for the given reference data

Source code in frax/ik/solver.py
176
177
178
179
180
def cost(self, q: Array, ref: Any) -> Array:
    """The cost of q: the QP objective at v = 0 (if the robot doesn't move),
    for the given reference data"""
    *_, cost = self._qp(q, ref)
    return cost

solve(q, ref, qp_warm_start)

Solve the diff IK QP

Parameters:

Name Type Description Default
q Array

Configuration, shape (nq,)

required
ref Any

Per-step reference data (any pytree)

required
qp_warm_start tuple[Array, Array, Array]

QP warm start (x, y, z)

required

Returns:

Name Type Description
v Array

Generalized velocity, shape (nv,)

qp_warm_start tuple[Array, Array, Array]

QP solution (x, y, z), to warm-start the next QP

info SolverInfo

Solver info, with the cost of q

Source code in frax/ik/solver.py
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def solve(
    self, q: Array, ref: Any, qp_warm_start: tuple[Array, Array, Array]
) -> tuple[Array, tuple[Array, Array, Array], SolverInfo]:
    """Solve the diff IK QP

    Args:
        q (Array): Configuration, shape (nq,)
        ref (Any): Per-step reference data (any pytree)
        qp_warm_start (tuple[Array, Array, Array]): QP warm start (x, y, z)

    Returns:
        v (Array): Generalized velocity, shape (nv,)
        qp_warm_start (tuple[Array, Array, Array]): QP solution (x, y, z),
            to warm-start the next QP
        info (SolverInfo): Solver info, with the cost of q
    """
    P, c, G, h, A, b, cost = self._qp(q, ref)
    result = elastiqp.jax.solve(
        P,
        c,
        G,
        h,
        penalty=self.penalty,
        A=A,
        b=b,
        eps_abs=self.solver_tol,
        warm_start=qp_warm_start if self.warm_start else None,
    )
    info = SolverInfo(result.iters, result.converged, cost)
    return result.x, (result.x, result.y, result.z), info

step(state, ref, dt)

One diff IK step

Parameters:

Name Type Description Default
state SolverState

Current state

required
ref Any

Per-step reference data (any pytree)

required
dt float

Timestep

required

Returns:

Name Type Description
state SolverState

New state

v Array

Generalized velocity, shape (nv,)

info SolverInfo

Solver info

Source code in frax/ik/solver.py
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
def step(
    self, state: SolverState, ref: Any, dt: float
) -> tuple[SolverState, Array, SolverInfo]:
    """One diff IK step

    Args:
        state (SolverState): Current state
        ref (Any): Per-step reference data (any pytree)
        dt (float): Timestep

    Returns:
        state (SolverState): New state
        v (Array): Generalized velocity, shape (nv,)
        info (SolverInfo): Solver info
    """
    v, qp_warm_start, info = self.solve(state.q, ref, state.qp_warm_start)
    q = self.robot.integrate(state.q, v, dt)
    return SolverState(q=q, qp_warm_start=qp_warm_start), v, info

converge(state, ref, max_iters, dt_max, tol)

Run differential IK until convergence

Note: This method should generally only be called as a component of a global IK pipeline, or at initialization of a solver. During online operation, or sequential calls in an offline pipeline, generally only a single diff IK step() should be taken.

Parameters:

Name Type Description Default
state SolverState

Initial state

required
ref Any

Reference data (any pytree)

required
max_iters int

Maximum iterations

required
dt_max float

Largest stepsize

required
tol float

Convergence tolerance on max |v|

required

Returns:

Name Type Description
state SolverState

Converged state

iters Array

Number of iterations

Source code in frax/ik/solver.py
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
def converge(
    self, state: SolverState, ref: Any, max_iters: int, dt_max: float, tol: float
) -> tuple[SolverState, Array]:
    """Run differential IK until convergence

    Note: This method should generally only be called as a component of a
    global IK pipeline, or at initialization of a solver. During online
    operation, or sequential calls in an offline pipeline, generally
    only a single diff IK step() should be taken.

    Args:
        state (SolverState): Initial state
        ref (Any): Reference data (any pytree)
        max_iters (int): Maximum iterations
        dt_max (float): Largest stepsize
        tol (float): Convergence tolerance on max |v|

    Returns:
        state (SolverState): Converged state
        iters (Array): Number of iterations
    """
    state, ref = jax.lax.stop_gradient((state, ref))
    robot = self.robot
    v, qp_warm_start, info = self.solve(state.q, ref, state.qp_warm_start)
    dt_min = MIN_STEP_RATIO * dt_max

    def cond(carry):
        *_, i, done = carry
        return ~done & (i < max_iters)

    def body(carry):
        q, v, qp_warm_start, cost, dt, i, _ = carry
        q_new = robot.integrate(q, v, dt)
        v_new, qp_warm_start_new, info = self.solve(q_new, ref, qp_warm_start)
        # Accept if the step lowers the cost
        accept = info.cost < cost
        q, v, qp_warm_start, cost = jax.tree.map(
            lambda new, old: jnp.where(accept, new, old),
            (q_new, v_new, qp_warm_start_new, info.cost),
            (q, v, qp_warm_start, cost),
        )
        # If accepted, double dt, otherwise halve it
        dt = jnp.where(accept, jnp.minimum(2.0 * dt, dt_max), 0.5 * dt)
        # Stopping condition on the max |v| or on a minimum dt
        done = (accept & (jnp.max(jnp.abs(v)) <= tol)) | (dt < dt_min)
        return q, v, qp_warm_start, cost, dt, i + 1, done

    carry = (
        state.q,
        v,
        qp_warm_start,
        info.cost,
        jnp.asarray(dt_max, dtype=state.q.dtype),
        0,
        jnp.max(jnp.abs(v)) <= tol,
    )
    q, _, qp_warm_start, _, _, iters, _ = jax.lax.while_loop(cond, body, carry)
    return SolverState(q=q, qp_warm_start=qp_warm_start), iters

Differential IK tasks

Notes: - Tasks operate on the velocity level, as opposed to a delta-q. - In general, a task has a least-squares structure || weight * (J v - v_des) ||^2

Task

Base differential IK task

Source code in frax/ik/tasks.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Task:
    """Base differential IK task"""

    robot: Robot
    num_rows: int

    def linearize(self, q: Array, ref: Any) -> tuple[Array, Array, Array]:
        """Linearize the task about q

        Args:
            q (Array): Configuration, shape (nq,)
            ref (Any): Per-step reference data (any pytree)

        Returns:
            J (Array): Task Jacobian, shape (num_rows, nv)
            v_des (Array): Desired task velocity, shape (num_rows,)
            weight (Array): Per-row weight, shape (num_rows,)
        """
        raise NotImplementedError

linearize(q, ref)

Linearize the task about q

Parameters:

Name Type Description Default
q Array

Configuration, shape (nq,)

required
ref Any

Per-step reference data (any pytree)

required

Returns:

Name Type Description
J Array

Task Jacobian, shape (num_rows, nv)

v_des Array

Desired task velocity, shape (num_rows,)

weight Array

Per-row weight, shape (num_rows,)

Source code in frax/ik/tasks.py
37
38
39
40
41
42
43
44
45
46
47
48
49
def linearize(self, q: Array, ref: Any) -> tuple[Array, Array, Array]:
    """Linearize the task about q

    Args:
        q (Array): Configuration, shape (nq,)
        ref (Any): Per-step reference data (any pytree)

    Returns:
        J (Array): Task Jacobian, shape (num_rows, nv)
        v_des (Array): Desired task velocity, shape (num_rows,)
        weight (Array): Per-row weight, shape (num_rows,)
    """
    raise NotImplementedError

ResidualTask

Bases: Task

Drive a residual e(q, ref) to zero, with a forward-mode autodiff Jacobian

Parameters:

Name Type Description Default
robot Robot

Robot model

required
residual_fn Callable

(q, ref) -> e, shape (num_rows,)

required
num_rows int

Residual dimension

required
gain ArrayLike

Scalar or per-row gain (1/s)

1.0
weight ArrayLike

Scalar or per-row weight

1.0
Source code in frax/ik/tasks.py
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
@jax.tree_util.register_static
class ResidualTask(Task):
    """Drive a residual e(q, ref) to zero, with a forward-mode autodiff Jacobian

    Args:
        robot (Robot): Robot model
        residual_fn (Callable): (q, ref) -> e, shape (num_rows,)
        num_rows (int): Residual dimension
        gain (ArrayLike): Scalar or per-row gain (1/s)
        weight (ArrayLike): Scalar or per-row weight
    """

    def __init__(
        self,
        robot: Robot,
        residual_fn: Callable[[Array, Any], Array],
        num_rows: int,
        gain: ArrayLike = 1.0,
        weight: ArrayLike = 1.0,
    ):
        self.robot = robot
        self.residual_fn = residual_fn
        self.num_rows = num_rows
        self.gain = _per_row(gain, num_rows)
        self.weight = _per_row(weight, num_rows)

    def linearize(self, q, ref):
        e, J = _velocity_jacobian(self.robot, lambda q: self.residual_fn(q, ref), q)
        return J, -self.gain * e, self.weight

JointTask

Bases: Task

Track a joint-space task

Note: this is currently configured to only deal with actuated joints. For free-floating bases, use a FrameTask

Parameters:

Name Type Description Default
robot Robot

Robot model

required
idxs ArrayLike

Indices into v to track

required
ref_key str

Reference key for the targets, shape (len(idxs),)

required
gain ArrayLike

Scalar or per-joint gain (1/s)

1.0
weight ArrayLike

Scalar or per-joint weight

1.0
Source code in frax/ik/tasks.py
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
@jax.tree_util.register_static
class JointTask(Task):
    """Track a joint-space task

    Note: this is currently configured to only deal with actuated
    joints. For free-floating bases, use a FrameTask

    Args:
        robot (Robot): Robot model
        idxs (ArrayLike): Indices into v to track
        ref_key (str): Reference key for the targets, shape (len(idxs),)
        gain (ArrayLike): Scalar or per-joint gain (1/s)
        weight (ArrayLike): Scalar or per-joint weight
    """

    def __init__(
        self,
        robot: Robot,
        idxs: ArrayLike,
        ref_key: str,
        gain: ArrayLike = 1.0,
        weight: ArrayLike = 1.0,
    ):
        self.robot = robot
        self.idxs = np.asarray(idxs)
        v_to_q = robot.velocity_to_configuration_index
        assert all(int(i) in v_to_q for i in self.idxs), (
            "JointTask entries must have q_dot = v (not a quaternion base's orientation)"
        )
        self.q_idxs = np.array([v_to_q[int(i)] for i in self.idxs], dtype=int)
        self.J = np.eye(robot.nv)[self.idxs]
        self.ref_key = ref_key
        self.num_rows = len(self.idxs)
        self.gain = _per_row(gain, self.num_rows)
        self.weight = _per_row(weight, self.num_rows)

    def linearize(self, q, ref):
        e = q[self.q_idxs] - ref[self.ref_key]
        return self.J, -self.gain * e, self.weight

FrameTask

Bases: _PoseTask

Track world-frame positions and/or orientations of joint frames

Parameters:

Name Type Description Default
robot Robot

Robot model

required
joints ArrayLike

Indices of the tracked joints, shape (n,)

required
gain_pos, gain_rot ArrayLike

Scalar or per-frame gains (1/s)

required
weight_pos, weight_rot ArrayLike

Scalar or per-frame weights

required
pos_key str | None

Reference key for target positions, shape (n, 3). None to not track position

'frame_pos'
rot_key str | None

Reference key for target rotation matrices, shape (n, 3, 3). None to not track rotation

'frame_rmat'
offsets ArrayLike | None

Tracked frames in their joint frames, shape (4, 4) or (n, 4, 4). Defaults to None (identity)

None
Source code in frax/ik/tasks.py
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
@jax.tree_util.register_static
class FrameTask(_PoseTask):
    """Track world-frame positions and/or orientations of joint frames

    Args:
        robot (Robot): Robot model
        joints (ArrayLike): Indices of the tracked joints, shape (n,)
        gain_pos, gain_rot (ArrayLike): Scalar or per-frame gains (1/s)
        weight_pos, weight_rot (ArrayLike): Scalar or per-frame weights
        pos_key (str | None): Reference key for target positions, shape (n, 3).
            None to not track position
        rot_key (str | None): Reference key for target rotation matrices,
            shape (n, 3, 3). None to not track rotation
        offsets (ArrayLike | None): Tracked frames in their joint frames, shape
            (4, 4) or (n, 4, 4). Defaults to None (identity)
    """

    def __init__(
        self,
        robot: Robot,
        joints: ArrayLike,
        gain_pos: ArrayLike = 1.0,
        gain_rot: ArrayLike = 1.0,
        weight_pos: ArrayLike = 1.0,
        weight_rot: ArrayLike = 1.0,
        pos_key: str | None = "frame_pos",
        rot_key: str | None = "frame_rmat",
        offsets: ArrayLike | None = None,
    ):
        self.joints = np.asarray(joints)
        n = len(self.joints)
        super().__init__(
            robot, n, gain_pos, gain_rot, weight_pos, weight_rot, pos_key, rot_key
        )
        if offsets is not None:
            offsets = np.broadcast_to(
                np.asarray(offsets, dtype=float), (n, 4, 4)
            ).copy()
        self.offsets = offsets

    def linearize(self, q, ref):
        tfs = self.robot.joint_to_world_transforms(q)
        Jv, Jw = self.robot._joint_jacobians(tfs)
        tfs, Jv, Jw = tfs[self.joints], Jv[self.joints], Jw[self.joints]
        if self.offsets is not None:
            tfs, Jv, Jw = offset_transforms_and_jacobians(tfs, Jv, Jw, self.offsets)
        return self._pose_rows(tfs, jnp.concatenate([Jv, Jw], axis=1), ref)

EETask

Bases: _PoseTask

Track the world-frame position and/or orientation of a Manipulator's end effector (including its ee_offset)

Parameters:

Name Type Description Default
robot Manipulator

Manipulator model

required
gain_pos, gain_rot float

Gains (1/s)

required
weight_pos, weight_rot float

Weights

required
pos_key str | None

Reference key for the target position, shape (3,). None to not track position

'ee_pos'
rot_key str | None

Reference key for the target rotation matrix, shape (3, 3). None to not track rotation

'ee_rmat'
Source code in frax/ik/tasks.py
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
@jax.tree_util.register_static
class EETask(_PoseTask):
    """Track the world-frame position and/or orientation of a Manipulator's end
    effector (including its `ee_offset`)

    Args:
        robot (Manipulator): Manipulator model
        gain_pos, gain_rot (float): Gains (1/s)
        weight_pos, weight_rot (float): Weights
        pos_key (str | None): Reference key for the target position, shape (3,).
            None to not track position
        rot_key (str | None): Reference key for the target rotation matrix,
            shape (3, 3). None to not track rotation
    """

    def __init__(
        self,
        robot: Manipulator,
        gain_pos: float = 1.0,
        gain_rot: float = 1.0,
        weight_pos: float = 1.0,
        weight_rot: float = 1.0,
        pos_key: str | None = "ee_pos",
        rot_key: str | None = "ee_rmat",
    ):
        super().__init__(
            robot, 1, gain_pos, gain_rot, weight_pos, weight_rot, pos_key, rot_key
        )

    def linearize(self, q, ref):
        joint_tfs = self.robot.joint_to_world_transforms(q)
        tf = self.robot._ee_transform(joint_tfs)
        J = self.robot._ee_jacobian(joint_tfs)
        keys = (key for key in (self.pos_key, self.rot_key) if key is not None)
        ref = {key: ref[key][None] for key in keys}
        return self._pose_rows(tf[None], J[None], ref)

IK constraints

Notes: - We use ElastiQP for our solver, which allows us to use efficient elastic inequality constraints, and hard equalities (where applicable) - Each inequality has an L1 relaxation with associated penalty w, typically left at a default high value like 1e6, though this can be tuned on a per-task basis. If this penalty is greater than the optimal dual multiplier for a feasible problem, the relaxation is exact - For tuning gains, ensure that gain * dt <= 1 to avoid overshoot - Since this solver operates on generalized velocities, all inequalities deal with v rather than a delta q. This is slightly different from other diff IK libraries like pink or mink

InequalityConstraint

Base (elastic) inequality constraint G v <= h

Source code in frax/ik/constraints.py
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class InequalityConstraint:
    """Base (elastic) inequality constraint G v <= h"""

    robot: Robot
    num_rows: int
    penalty: ArrayLike

    def rows(self, q: Array, ref: Any) -> tuple[Array, Array]:
        """Rows of G v <= h for this constraint, evaluated at q

        Args:
            q (Array): Configuration, shape (nq,)
            ref (Any): A pytree (such as a dict) containing problem data
                that is updated each step

        Returns:
            G (Array): Inequality matrix rows, shape (num_rows, nv)
            h (Array): Inequality vector rows, shape (num_rows,)
        """
        raise NotImplementedError

rows(q, ref)

Rows of G v <= h for this constraint, evaluated at q

Parameters:

Name Type Description Default
q Array

Configuration, shape (nq,)

required
ref Any

A pytree (such as a dict) containing problem data that is updated each step

required

Returns:

Name Type Description
G Array

Inequality matrix rows, shape (num_rows, nv)

h Array

Inequality vector rows, shape (num_rows,)

Source code in frax/ik/constraints.py
39
40
41
42
43
44
45
46
47
48
49
50
51
def rows(self, q: Array, ref: Any) -> tuple[Array, Array]:
    """Rows of G v <= h for this constraint, evaluated at q

    Args:
        q (Array): Configuration, shape (nq,)
        ref (Any): A pytree (such as a dict) containing problem data
            that is updated each step

    Returns:
        G (Array): Inequality matrix rows, shape (num_rows, nv)
        h (Array): Inequality vector rows, shape (num_rows,)
    """
    raise NotImplementedError

EqualityConstraint

Base (hard) equality constraint Av = b

Generally, you should wrap any soft task terms that may not be feasible by construction in an ElasticEquality

Source code in frax/ik/constraints.py
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class EqualityConstraint:
    """Base (hard) equality constraint Av = b

    Generally, you should wrap any soft task terms that may not be feasible by
    construction in an ElasticEquality
    """

    robot: Robot
    num_rows: int

    def rows(self, q: Array, ref: Any) -> tuple[Array, Array]:
        """Rows of A v = b for this constraint, evaluated at q

        Args:
            q (Array): Configuration, shape (nq,)
            ref (Any): A pytree (such as a dict) containing problem data
                that is updated each step

        Returns:
            A (Array): Equality matrix rows, shape (num_rows, nv)
            b (Array): Equality vector rows, shape (num_rows,)
        """
        raise NotImplementedError

rows(q, ref)

Rows of A v = b for this constraint, evaluated at q

Parameters:

Name Type Description Default
q Array

Configuration, shape (nq,)

required
ref Any

A pytree (such as a dict) containing problem data that is updated each step

required

Returns:

Name Type Description
A Array

Equality matrix rows, shape (num_rows, nv)

b Array

Equality vector rows, shape (num_rows,)

Source code in frax/ik/constraints.py
64
65
66
67
68
69
70
71
72
73
74
75
76
def rows(self, q: Array, ref: Any) -> tuple[Array, Array]:
    """Rows of A v = b for this constraint, evaluated at q

    Args:
        q (Array): Configuration, shape (nq,)
        ref (Any): A pytree (such as a dict) containing problem data
            that is updated each step

    Returns:
        A (Array): Equality matrix rows, shape (num_rows, nv)
        b (Array): Equality vector rows, shape (num_rows,)
    """
    raise NotImplementedError

JointLimits

Bases: InequalityConstraint

Joint position and velocity limits on the actuated joint velocities

max(v_min, gain * (q_min - q)) <= v <= min(v_max, gain * (q_max - q))

Limits default to "robot" to use the robot's own actuated joint position/ velocity limits, but you can also pass None (no limit) or an array of custom limits.

Currently, limits on floating bases are not implemented.

Parameters:

Name Type Description Default
robot Robot

The frax robot model

required
q_min ArrayLike | str | None

Lower position limits, shape (num_actuated,). Defaults to robot.actuated_joint_lower_limits

'robot'
q_max ArrayLike | str | None

Upper position limits, shape (num_actuated,). Defaults to robot.actuated_joint_upper_limits

'robot'
v_max ArrayLike | str | None

Upper velocity limits, shape (num_actuated,). Defaults to robot.actuated_joint_max_velocities

'robot'
v_min ArrayLike | str | None

Lower velocity limits, shape (num_actuated,). Defaults to -v_max

'robot'
gain float

CBF gain (1/s): how fast the position limits may be approached

10.0
penalty float

Relaxation penalty

DEFAULT_PENALTY
Source code in frax/ik/constraints.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
@jax.tree_util.register_static
class JointLimits(InequalityConstraint):
    """Joint position and velocity limits on the actuated joint velocities

        max(v_min, gain * (q_min - q)) <= v <= min(v_max, gain * (q_max - q))

    Limits default to "robot" to use the robot's own actuated joint position/
    velocity limits, but you can also pass None (no limit) or an array of
    custom limits.

    Currently, limits on floating bases are not implemented.

    Args:
        robot (Robot): The frax robot model
        q_min (ArrayLike | str | None): Lower position limits, shape (num_actuated,).
            Defaults to robot.actuated_joint_lower_limits
        q_max (ArrayLike | str | None): Upper position limits, shape (num_actuated,).
            Defaults to robot.actuated_joint_upper_limits
        v_max (ArrayLike | str | None): Upper velocity limits, shape (num_actuated,).
            Defaults to robot.actuated_joint_max_velocities
        v_min (ArrayLike | str | None): Lower velocity limits, shape (num_actuated,).
            Defaults to -v_max
        gain (float): CBF gain (1/s): how fast the position limits may be approached
        penalty (float): Relaxation penalty
    """

    def __init__(
        self,
        robot: Robot,
        q_min: ArrayLike | Literal["robot"] | None = "robot",
        q_max: ArrayLike | Literal["robot"] | None = "robot",
        v_max: ArrayLike | Literal["robot"] | None = "robot",
        v_min: ArrayLike | Literal["robot"] | None = "robot",
        gain: float = 10.0,
        penalty: float = DEFAULT_PENALTY,
    ):
        assert gain > 0
        self.robot = robot
        n = robot.nv - robot.nv_floating  # Actuated joints
        self.q_min = _resolve_limits(q_min, robot.actuated_joint_lower_limits, n, -1)
        self.q_max = _resolve_limits(q_max, robot.actuated_joint_upper_limits, n, 1)
        self.v_max = _resolve_limits(v_max, robot.actuated_joint_max_velocities, n, 1)
        self.v_min = _resolve_limits(v_min, -self.v_max, n, -1)
        self.upper_idxs = np.flatnonzero(
            np.isfinite(self.q_max) | np.isfinite(self.v_max)
        )
        self.lower_idxs = np.flatnonzero(
            np.isfinite(self.q_min) | np.isfinite(self.v_min)
        )
        I = np.eye(n)
        G = np.vstack([I[self.upper_idxs], -I[self.lower_idxs]])
        self.num_rows = G.shape[0]
        assert self.num_rows > 0
        # Zero columns for the floating base
        self.G = np.hstack([np.zeros((self.num_rows, robot.nv_floating)), G])
        self.gain = gain
        self.penalty = penalty

    def rows(self, q, ref):
        pos = q[self.robot.nq_floating :]
        up, lo = self.upper_idxs, self.lower_idxs
        upper = jnp.minimum(self.v_max[up], self.gain * (self.q_max[up] - pos[up]))
        lower = jnp.maximum(self.v_min[lo], self.gain * (self.q_min[lo] - pos[lo]))
        return self.G, jnp.concatenate([upper, -lower])

SelfCollisionConstraint

Bases: _SphereConstraint

Self-collision avoidance: h = robot.self_collision_distances(q) - margin

Parameters:

Name Type Description Default
robot Robot

Robot, with collision and self-collision data

required
max_rows int | None

If set, keep only this many closest pairs per step

None
gain float

CBF gain (1/s)

10.0
penalty float

Relaxation penalty

DEFAULT_PENALTY
margin float

Additional safety margin between every collision pair

0.0
Source code in frax/ik/constraints.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
@jax.tree_util.register_static
class SelfCollisionConstraint(_SphereConstraint):
    """Self-collision avoidance: h = robot.self_collision_distances(q) - margin

    Args:
        robot (Robot): Robot, with collision and self-collision data
        max_rows (int | None): If set, keep only this many closest pairs per step
        gain (float): CBF gain (1/s)
        penalty (float): Relaxation penalty
        margin (float): Additional safety margin between every collision pair
    """

    def __init__(
        self,
        robot: Robot,
        max_rows: int | None = None,
        gain: float = 10.0,
        penalty: float = DEFAULT_PENALTY,
        margin: float = 0.0,
    ):
        super().__init__(robot, gain, penalty)
        assert robot.has_sc_data
        self.margin = margin
        self._set_num_rows(len(robot.sc_pairs), max_rows)

    def rows(self, q, ref):
        joint_tfs = self.robot.joint_to_world_transforms(q)
        pos = self.robot._link_collision_positions(joint_tfs)
        dists = self.robot._self_collision_distances_from_link_data(pos, self.radii)
        h = dists - self.margin
        keep = self._keep(h)
        Jv, Jw = self.robot._joint_jacobians(joint_tfs)
        J = self.robot._self_collision_jacobian(joint_tfs, Jv, Jw, pos, keep)
        return -J, self.gain * h[keep]

ObstacleConstraint

Bases: _SphereConstraint

Sphere obstacle avoidance: h = |p_i - c_k| - r_i - R_k - margin for each robot sphere i in sphere_idxs and obstacle k

Parameters:

Name Type Description Default
robot Robot

Robot, with collision data

required
obstacles SphereObstacles

Obstacles. Their count K is fixed

required
sphere_idxs ArrayLike | None

Robot collision spheres to check. Defaults to all

None
ref_key str | None

If set, ref[ref_key] replaces obstacles each step

None
max_rows int | None

If set, keep only this many closest pairs per step

None
gain float

CBF gain (1/s)

10.0
penalty float

Relaxation penalty

DEFAULT_PENALTY
margin float

Safety distance from every obstacle

0.0
Source code in frax/ik/constraints.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
@jax.tree_util.register_static
class ObstacleConstraint(_SphereConstraint):
    """Sphere obstacle avoidance: h = |p_i - c_k| - r_i - R_k - margin for each
    robot sphere i in sphere_idxs and obstacle k

    Args:
        robot (Robot): Robot, with collision data
        obstacles (SphereObstacles): Obstacles. Their count K is fixed
        sphere_idxs (ArrayLike | None): Robot collision spheres to check.
            Defaults to all
        ref_key (str | None): If set, ref[ref_key] replaces `obstacles` each step
        max_rows (int | None): If set, keep only this many closest pairs per step
        gain (float): CBF gain (1/s)
        penalty (float): Relaxation penalty
        margin (float): Safety distance from every obstacle
    """

    def __init__(
        self,
        robot: Robot,
        obstacles: SphereObstacles,
        sphere_idxs: ArrayLike | None = None,
        ref_key: str | None = None,
        max_rows: int | None = None,
        gain: float = 10.0,
        penalty: float = DEFAULT_PENALTY,
        margin: float = 0.0,
    ):
        super().__init__(robot, gain, penalty)
        self.margin = margin
        self.obstacles = SphereObstacles(
            np.asarray(obstacles.centers, dtype=float),
            np.asarray(obstacles.radii, dtype=float),
            np.asarray(obstacles.active, dtype=bool),
        )
        self.num_obstacles = self.obstacles.radii.shape[0]
        self.sphere_idxs = (
            np.arange(len(self.radii))
            if sphere_idxs is None
            else np.asarray(sphere_idxs)
        )
        self.row_spheres = np.tile(self.sphere_idxs, self.num_obstacles)
        self.ref_key = ref_key
        self._set_num_rows(len(self.row_spheres), max_rows)

    def rows(self, q, ref):
        obstacles = self.obstacles if self.ref_key is None else ref[self.ref_key]
        assert obstacles.radii.shape == (self.num_obstacles,), (
            "Obstacle count must match the constructor"
        )
        joint_tfs = self.robot.joint_to_world_transforms(q)
        pos = self.robot._link_collision_positions(joint_tfs)
        idxs = self.sphere_idxs
        delta = (pos[idxs][None] - obstacles.centers[:, None]).reshape(-1, 3)
        offsets = self.radii[idxs][None] + obstacles.radii[:, None] + self.margin
        offsets = offsets.reshape(-1)
        active = jnp.repeat(obstacles.active, len(idxs))
        dist = jnp.linalg.norm(delta, axis=-1)
        h = jnp.where(active, dist - offsets, _INACTIVE_DISTANCE)
        keep = self._keep(h)
        spheres = jnp.asarray(self.row_spheres)[keep]
        Jv, Jw = self.robot._joint_jacobians(joint_tfs)
        J = self.robot._link_collision_jacobians(joint_tfs, Jv, Jw, spheres)
        normals = delta[keep] / dist[keep, None]
        dh = jnp.einsum("ki,kij->kj", normals, J)
        dh = jnp.where(active[keep, None], dh, 0.0)
        return -dh, self.gain * h[keep]

FloorConstraint

Bases: _SphereConstraint

Floor at z = 0: h = z_i - r_i - margin for each robot sphere i in sphere_idxs

Parameters:

Name Type Description Default
robot Robot

Robot, with collision data

required
sphere_idxs ArrayLike | None

Robot collision spheres to check. Defaults to all

None
max_rows int | None

If set, keep only this many lowest spheres per step

None
gain float

CBF gain (1/s)

10.0
penalty float

Relaxation penalty

DEFAULT_PENALTY
margin float

Height kept above the floor

0.0
Source code in frax/ik/constraints.py
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
@jax.tree_util.register_static
class FloorConstraint(_SphereConstraint):
    """Floor at z = 0: h = z_i - r_i - margin for each robot sphere i in sphere_idxs

    Args:
        robot (Robot): Robot, with collision data
        sphere_idxs (ArrayLike | None): Robot collision spheres to check.
            Defaults to all
        max_rows (int | None): If set, keep only this many lowest spheres per step
        gain (float): CBF gain (1/s)
        penalty (float): Relaxation penalty
        margin (float): Height kept above the floor
    """

    def __init__(
        self,
        robot: Robot,
        sphere_idxs: ArrayLike | None = None,
        max_rows: int | None = None,
        gain: float = 10.0,
        penalty: float = DEFAULT_PENALTY,
        margin: float = 0.0,
    ):
        super().__init__(robot, gain, penalty)
        self.margin = margin
        self.sphere_idxs = (
            np.arange(len(self.radii))
            if sphere_idxs is None
            else np.asarray(sphere_idxs)
        )
        self._set_num_rows(len(self.sphere_idxs), max_rows)

    def rows(self, q, ref):
        joint_tfs = self.robot.joint_to_world_transforms(q)
        pos = self.robot._link_collision_positions(joint_tfs)[self.sphere_idxs]
        h = pos[:, 2] - self.radii[self.sphere_idxs] - self.margin
        keep = self._keep(h)
        spheres = jnp.asarray(self.sphere_idxs)[keep]
        Jv, Jw = self.robot._joint_jacobians(joint_tfs)
        J = self.robot._link_collision_jacobians(joint_tfs, Jv, Jw, spheres)
        return -J[:, 2], self.gain * h[keep]

BarrierConstraint

Bases: InequalityConstraint

CBF on a user-defined barrier h(q, ref) >= 0: dh/dq E(q) v >= -gain * h

The Jacobian is by forward-mode autodiff, so this suits a handful of rows

Parameters:

Name Type Description Default
robot Robot

Robot model

required
h_fn Callable

(q, ref) -> h, shape (num_rows,)

required
num_rows int

Number of barriers

required
gain float

CBF gain (1/s)

10.0
penalty ArrayLike

Scalar or per-row relaxation penalty

DEFAULT_PENALTY
Source code in frax/ik/constraints.py
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
@jax.tree_util.register_static
class BarrierConstraint(InequalityConstraint):
    """CBF on a user-defined barrier h(q, ref) >= 0: dh/dq E(q) v >= -gain * h

    The Jacobian is by forward-mode autodiff, so this suits a handful of rows

    Args:
        robot (Robot): Robot model
        h_fn (Callable): (q, ref) -> h, shape (num_rows,)
        num_rows (int): Number of barriers
        gain (float): CBF gain (1/s)
        penalty (ArrayLike): Scalar or per-row relaxation penalty
    """

    def __init__(
        self,
        robot: Robot,
        h_fn: Callable[[Array, Any], Array],
        num_rows: int,
        gain: float = 10.0,
        penalty: ArrayLike = DEFAULT_PENALTY,
    ):
        self.robot = robot
        self.h_fn = h_fn
        self.num_rows = num_rows
        self.gain = gain
        self.penalty = penalty

    def rows(self, q, ref):
        def h_fn(q):
            h = self.h_fn(q, ref)
            assert h.shape == (self.num_rows,), (
                f"h has shape {h.shape}, expected ({self.num_rows},)"
            )
            return h

        h, dh = _velocity_jacobian(self.robot, h_fn, q)
        return -dh, self.gain * h

ResidualEquality

Bases: EqualityConstraint

Equality on a user-defined residual e(q, ref) = 0: de/dq E(q) v = -gain * e

Parameters:

Name Type Description Default
robot Robot

Robot model

required
residual_fn Callable

(q, ref) -> e, shape (num_rows,)

required
num_rows int

Residual dimension

required
gain float

Gain (1/s)

10.0
Source code in frax/ik/constraints.py
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
@jax.tree_util.register_static
class ResidualEquality(EqualityConstraint):
    """Equality on a user-defined residual e(q, ref) = 0: de/dq E(q) v = -gain * e

    Args:
        robot (Robot): Robot model
        residual_fn (Callable): (q, ref) -> e, shape (num_rows,)
        num_rows (int): Residual dimension
        gain (float): Gain (1/s)
    """

    def __init__(
        self,
        robot: Robot,
        residual_fn: Callable[[Array, Any], Array],
        num_rows: int,
        gain: float = 10.0,
    ):
        self.robot = robot
        self.residual_fn = residual_fn
        self.num_rows = num_rows
        self.gain = gain

    def rows(self, q, ref):
        def e_fn(q):
            e = self.residual_fn(q, ref)
            assert e.shape == (self.num_rows,), (
                f"e has shape {e.shape}, expected ({self.num_rows},)"
            )
            return e

        e, de = _velocity_jacobian(self.robot, e_fn, q)
        return de, -self.gain * e

ElasticEquality

Bases: InequalityConstraint

An equality A v = b, relaxed with an L1 penalty, as the inequalities A v <= b and -A v <= -b

Parameters:

Name Type Description Default
equality EqualityConstraint

The equality to relax

required
penalty ArrayLike

Scalar or per-row relaxation penalty, shape (equality.num_rows,)

DEFAULT_PENALTY
Source code in frax/ik/constraints.py
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
@jax.tree_util.register_static
class ElasticEquality(InequalityConstraint):
    """An equality A v = b, relaxed with an L1 penalty, as the inequalities
    A v <= b and -A v <= -b

    Args:
        equality (EqualityConstraint): The equality to relax
        penalty (ArrayLike): Scalar or per-row relaxation penalty, shape
            (equality.num_rows,)
    """

    def __init__(
        self, equality: EqualityConstraint, penalty: ArrayLike = DEFAULT_PENALTY
    ):
        self.equality = equality
        self.robot = equality.robot
        self.num_rows = 2 * equality.num_rows
        penalty = np.broadcast_to(
            np.asarray(penalty, dtype=float), (equality.num_rows,)
        )
        self.penalty = np.tile(penalty, 2)

    @property
    def gain(self):
        return self.equality.gain

    def rows(self, q, ref):
        A, b = self.equality.rows(q, ref)
        return jnp.concatenate([A, -A]), jnp.concatenate([b, -b])

Online and offline motion retargeting

Retargeter

Differential IK-based motion retargeter.

Given a sequence of frames, this class solves for the robot configurations q, based on the input DiffIKSolver

As opposed to just using a DiffIK solver, this adds logic for converging to an initial configuration on the first step, and processing a whole sequence in a single scan

Parameters:

Name Type Description Default
solver DiffIKSolver

Diff IK solver

required
preprocess Callable

Input frame -> the solver's reference

required
initial_q Callable

First input frame -> initial guess for q

required
converge_max_iters int

Max iterations to converge onto the first frame

300
converge_dt float | None

Largest convergence stepsize. Defaults to 1 / solver.max_gain (full Gauss-Newton step)

None
converge_tol float

Convergence tolerance on max |v|

0.001
global_ik_init GlobalIKSolver | None

If set, solves the first frame by global IK before converging, to avoid poor local solutions.

None
global_ik_seed int

Seed for the global IK samples

0
Source code in frax/ik/retargeter.py
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
@jax.tree_util.register_static
class Retargeter:
    """Differential IK-based motion retargeter.

    Given a sequence of frames, this class solves for the robot
    configurations q, based on the input DiffIKSolver

    As opposed to just using a DiffIK solver, this adds logic for
    converging to an initial configuration on the first step, and
    processing a whole sequence in a single scan

    Args:
        solver (DiffIKSolver): Diff IK solver
        preprocess (Callable): Input frame -> the solver's reference
        initial_q (Callable): First input frame -> initial guess for q
        converge_max_iters (int): Max iterations to converge onto the first frame
        converge_dt (float | None): Largest convergence stepsize. Defaults to
            1 / solver.max_gain (full Gauss-Newton step)
        converge_tol (float): Convergence tolerance on max |v|
        global_ik_init (GlobalIKSolver | None): If set, solves the first frame by
            global IK before converging, to avoid poor local solutions.
        global_ik_seed (int): Seed for the global IK samples
    """

    def __init__(
        self,
        solver: DiffIKSolver,
        preprocess: Callable[[Any], Any],
        initial_q: Callable[[Any], Array],
        converge_max_iters: int = 300,
        converge_dt: float | None = None,
        converge_tol: float = 1e-3,
        global_ik_init: GlobalIKSolver | None = None,
        global_ik_seed: int = 0,
    ):
        self.solver = solver
        self.preprocess = preprocess
        self.initial_q = initial_q
        self.converge_max_iters = converge_max_iters
        if converge_dt is None:
            assert solver.max_gain is not None, "A term has no gain: pass converge_dt"
            converge_dt = 1.0 / solver.max_gain
        self.converge_dt = converge_dt
        self.converge_tol = converge_tol
        self.global_ik_init = global_ik_init
        self.global_ik_seed = global_ik_seed

    def init(self, frame: Any) -> tuple[SolverState, Array]:
        """Converge onto the first frame

        Returns:
            state (SolverState): Converged state
            iters (Array): Number of iterations
        """
        q, ref = self.initial_q(frame), self.preprocess(frame)
        if self.global_ik_init is not None:
            key = jax.random.key(self.global_ik_seed)
            q = self.global_ik_init.solve(q, ref, key).q
        state, iters = self.solver.converge(
            self.solver.init(q),
            ref,
            self.converge_max_iters,
            self.converge_dt,
            self.converge_tol,
        )
        return state, iters

    def step(
        self, state: SolverState, frame: Any, dt: float
    ) -> tuple[SolverState, SolverInfo]:
        """Take one solver step towards an input frame"""
        state, _, info = self.solver.step(state, self.preprocess(frame), dt)
        return state, info

    @jax.jit
    def retarget_clip(self, frames: Any, dt: float) -> tuple[Array, SolverInfo, Array]:
        """Retarget a full clip of input frames

        Args:
            frames (Any): Input frames, with leading time axis T (any pytree)
            dt (float): Time between frames

        Returns:
            q (Array): Configurations, shape (T, nq)
            infos (SolverInfo): Per-step info, leading dim T - 1
            init_iters (Array): Iterations to converge onto the first frame
        """
        first = jax.tree.map(lambda x: x[0], frames)
        rest = jax.tree.map(lambda x: x[1:], frames)
        init_state, init_iters = self.init(first)

        def scan_step(state, frame):
            state, info = self.step(state, frame, dt)
            return state, (state.q, info)

        _, (q, infos) = jax.lax.scan(scan_step, init_state, rest)
        return jnp.concatenate([init_state.q[None], q]), infos, init_iters

init(frame)

Converge onto the first frame

Returns:

Name Type Description
state SolverState

Converged state

iters Array

Number of iterations

Source code in frax/ik/retargeter.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
def init(self, frame: Any) -> tuple[SolverState, Array]:
    """Converge onto the first frame

    Returns:
        state (SolverState): Converged state
        iters (Array): Number of iterations
    """
    q, ref = self.initial_q(frame), self.preprocess(frame)
    if self.global_ik_init is not None:
        key = jax.random.key(self.global_ik_seed)
        q = self.global_ik_init.solve(q, ref, key).q
    state, iters = self.solver.converge(
        self.solver.init(q),
        ref,
        self.converge_max_iters,
        self.converge_dt,
        self.converge_tol,
    )
    return state, iters

step(state, frame, dt)

Take one solver step towards an input frame

Source code in frax/ik/retargeter.py
84
85
86
87
88
89
def step(
    self, state: SolverState, frame: Any, dt: float
) -> tuple[SolverState, SolverInfo]:
    """Take one solver step towards an input frame"""
    state, _, info = self.solver.step(state, self.preprocess(frame), dt)
    return state, info

retarget_clip(frames, dt)

Retarget a full clip of input frames

Parameters:

Name Type Description Default
frames Any

Input frames, with leading time axis T (any pytree)

required
dt float

Time between frames

required

Returns:

Name Type Description
q Array

Configurations, shape (T, nq)

infos SolverInfo

Per-step info, leading dim T - 1

init_iters Array

Iterations to converge onto the first frame

Source code in frax/ik/retargeter.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
@jax.jit
def retarget_clip(self, frames: Any, dt: float) -> tuple[Array, SolverInfo, Array]:
    """Retarget a full clip of input frames

    Args:
        frames (Any): Input frames, with leading time axis T (any pytree)
        dt (float): Time between frames

    Returns:
        q (Array): Configurations, shape (T, nq)
        infos (SolverInfo): Per-step info, leading dim T - 1
        init_iters (Array): Iterations to converge onto the first frame
    """
    first = jax.tree.map(lambda x: x[0], frames)
    rest = jax.tree.map(lambda x: x[1:], frames)
    init_state, init_iters = self.init(first)

    def scan_step(state, frame):
        state, info = self.step(state, frame, dt)
        return state, (state.q, info)

    _, (q, infos) = jax.lax.scan(scan_step, init_state, rest)
    return jnp.concatenate([init_state.q[None], q]), infos, init_iters

OfflineRetargeter

Retargets many clips, spread across devices. Clips are padded to a multiple of bucket frames, and compiled shapes are cached across calls

Parameters:

Name Type Description Default
retargeter Retargeter

Retargeter

required
dt float

Time between frames

required
bucket int

Padded clip lengths are multiples of this

1024
devices all | default | Sequence[Device]

Devices to spread the clips across. Defaults to "all"

'all'
Source code in frax/ik/retargeter.py
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
class OfflineRetargeter:
    """Retargets many clips, spread across devices. Clips are padded to a multiple
    of bucket frames, and compiled shapes are cached across calls

    Args:
        retargeter (Retargeter): Retargeter
        dt (float): Time between frames
        bucket (int): Padded clip lengths are multiples of this
        devices ("all" | "default" | Sequence[jax.Device]): Devices to spread the
            clips across. Defaults to "all"
    """

    def __init__(
        self,
        retargeter: Retargeter,
        dt: float,
        bucket: int = 1024,
        devices: Literal["all", "default"] | Sequence[jax.Device] = "all",
    ):
        self.devices = _resolve_devices(devices)
        self.bucket = bucket
        self.retarget = jax.jit(
            device_vmap(
                lambda clip: retargeter.retarget_clip(clip, dt)[0], self.devices
            )
        )
        self.compiled = {}
        self.compile_time = 0.0

    def __call__(self, clips: Sequence) -> list[np.ndarray]:
        """Retarget clips

        Args:
            clips (Sequence): Clips of input frames, each a pytree with leading
                time axis T. T may differ between clips

        Returns:
            list[np.ndarray]: Configurations, one array per clip, each shape
                (T, nq) with that clip's T
        """
        if not clips:
            return []
        # No more devices than clips, so no device solves a filler clip
        n = min(len(self.devices), len(clips))
        lengths = [len(jax.tree.leaves(clip)[0]) for clip in clips]
        order = sorted(range(len(clips)), key=lambda i: -lengths[i])
        groups = [order[i : i + n] for i in range(0, len(order), n)]
        pending = []
        for group in groups:
            length = -(-lengths[group[0]] // self.bucket) * self.bucket
            # Top up the last group so it shares the compiled shape
            members = [clips[i] for i in group] + [clips[group[0]]] * (n - len(group))
            batch = jax.tree.map(
                lambda *x: np.stack(x),
                *[_pad_with_last_frame(clip, length) for clip in members],
            )
            leaves, structure = jax.tree.flatten(batch)
            key = (structure, tuple(x.shape for x in leaves))
            if key not in self.compiled:
                start = time.perf_counter()
                self.compiled[key] = self.retarget.lower(batch).compile()
                self.compile_time += time.perf_counter() - start
            # Asynchronous dispatch
            pending.append(self.compiled[key](batch))
        qs = [None] * len(clips)
        for group, q in zip(groups, pending):
            q = np.asarray(q)
            for k, i in enumerate(group):
                qs[i] = q[k, : lengths[i]]
        return qs

__call__(clips)

Retarget clips

Parameters:

Name Type Description Default
clips Sequence

Clips of input frames, each a pytree with leading time axis T. T may differ between clips

required

Returns:

Type Description
list[ndarray]

list[np.ndarray]: Configurations, one array per clip, each shape (T, nq) with that clip's T

Source code in frax/ik/retargeter.py
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
def __call__(self, clips: Sequence) -> list[np.ndarray]:
    """Retarget clips

    Args:
        clips (Sequence): Clips of input frames, each a pytree with leading
            time axis T. T may differ between clips

    Returns:
        list[np.ndarray]: Configurations, one array per clip, each shape
            (T, nq) with that clip's T
    """
    if not clips:
        return []
    # No more devices than clips, so no device solves a filler clip
    n = min(len(self.devices), len(clips))
    lengths = [len(jax.tree.leaves(clip)[0]) for clip in clips]
    order = sorted(range(len(clips)), key=lambda i: -lengths[i])
    groups = [order[i : i + n] for i in range(0, len(order), n)]
    pending = []
    for group in groups:
        length = -(-lengths[group[0]] // self.bucket) * self.bucket
        # Top up the last group so it shares the compiled shape
        members = [clips[i] for i in group] + [clips[group[0]]] * (n - len(group))
        batch = jax.tree.map(
            lambda *x: np.stack(x),
            *[_pad_with_last_frame(clip, length) for clip in members],
        )
        leaves, structure = jax.tree.flatten(batch)
        key = (structure, tuple(x.shape for x in leaves))
        if key not in self.compiled:
            start = time.perf_counter()
            self.compiled[key] = self.retarget.lower(batch).compile()
            self.compile_time += time.perf_counter() - start
        # Asynchronous dispatch
        pending.append(self.compiled[key](batch))
    qs = [None] * len(clips)
    for group, q in zip(groups, pending):
        q = np.asarray(q)
        for k, i in enumerate(group):
            qs[i] = q[k, : lengths[i]]
    return qs

OnlineRetargeter

Stateful retargeting wrapper for online operation.

Call compile() before any strict real-time operation to compile the performance-critical methods.

Source code in frax/ik/retargeter.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
class OnlineRetargeter:
    """Stateful retargeting wrapper for online operation.

    Call compile() before any strict real-time operation to
    compile the performance-critical methods.
    """

    def __init__(self, retargeter: Retargeter):
        self.retargeter = retargeter
        self.state = None
        self._init = jax.jit(retargeter.init)
        self._step = jax.jit(retargeter.step)

    def compile(self, example_frame: Any) -> None:
        """Compile the init and step functions ahead of time

        Args:
            example_frame (Any): Example input frame (may be jax.ShapeDtypeStructs)
        """
        state, _ = jax.eval_shape(self._init, example_frame)
        self._init.lower(example_frame).compile()
        self._step.lower(state, example_frame, 0.0).compile()

    def reset(self) -> None:
        self.state = None

    def step(self, frame: Any, dt: float) -> Array:
        if self.state is None:
            self.state, _ = self._init(frame)
        else:
            self.state, _ = self._step(self.state, frame, float(dt))
        return self.state.q

compile(example_frame)

Compile the init and step functions ahead of time

Parameters:

Name Type Description Default
example_frame Any

Example input frame (may be jax.ShapeDtypeStructs)

required
Source code in frax/ik/retargeter.py
207
208
209
210
211
212
213
214
215
def compile(self, example_frame: Any) -> None:
    """Compile the init and step functions ahead of time

    Args:
        example_frame (Any): Example input frame (may be jax.ShapeDtypeStructs)
    """
    state, _ = jax.eval_shape(self._init, example_frame)
    self._init.lower(example_frame).compile()
    self._step.lower(state, example_frame, 0.0).compile()

Global IK with multi-start SQP

Note: for continuous motion control, you should probably stick to differential IK. Global IK is useful for if instantaneous jumps are acceptable: for instance, finding a configuration that achieves a desired initial or goal pose, without worrying about continuity from your current state.

GlobalIKSolver

Multi-start SQP global IK solver

Parameters:

Name Type Description Default
solver DiffIKSolver

Diff IK solver

required
num_samples int

Number of starts, including q

32
q_min, q_max ArrayLike | robot

Sampling range for the actuated joints. Default to "robot", for the robot's joint limits, narrowed to those of any JointLimits constraints in the solver

required
max_iters int

Max convergence iterations per start

200
dt_max float | None

Largest convergence stepsize. Defaults to 1 / solver.max_gain

None
tol float

Convergence tolerance on max |v|

0.0001
cost_tol float | None

Cost tolerance for acceptable solutions. If this term is set, then we return the closest sampled solution that is within cost_tol of the lowest cost. Defaults to None (select the lowest cost regardless of how far the solution is in configuration space)

None
devices all | default | Sequence[Device]

Devices to parallelize the samples across. Defaults to "default" (JAX's default device).

'default'
Source code in frax/ik/global_ik.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
@jax.tree_util.register_static
class GlobalIKSolver:
    """Multi-start SQP global IK solver


    Args:
        solver (DiffIKSolver): Diff IK solver
        num_samples (int): Number of starts, including q
        q_min, q_max (ArrayLike | "robot"): Sampling range for the actuated
            joints. Default to "robot", for the robot's joint limits, narrowed
            to those of any JointLimits constraints in the solver
        max_iters (int): Max convergence iterations per start
        dt_max (float | None): Largest convergence stepsize. Defaults to
            1 / solver.max_gain
        tol (float): Convergence tolerance on max |v|
        cost_tol (float | None): Cost tolerance for acceptable solutions. If
            this term is set, then we return the closest sampled solution that is
            within cost_tol of the lowest cost. Defaults to None (select the lowest
            cost regardless of how far the solution is in configuration space)
        devices ("all" | "default" | Sequence[jax.Device]): Devices to parallelize
            the samples across. Defaults to "default" (JAX's default device).
    """

    def __init__(
        self,
        solver: DiffIKSolver,
        num_samples: int = 32,
        q_min: ArrayLike | Literal["robot"] = "robot",
        q_max: ArrayLike | Literal["robot"] = "robot",
        max_iters: int = 200,
        dt_max: float | None = None,
        tol: float = 1e-4,
        cost_tol: float | None = None,
        devices: Literal["all", "default"] | Sequence[jax.Device] = "default",
    ):
        self.solver = solver
        self.num_samples = num_samples

        # Handle joint limits for determining a sampling range
        lower = np.asarray(solver.robot.actuated_joint_lower_limits, dtype=float)
        upper = np.asarray(solver.robot.actuated_joint_upper_limits, dtype=float)
        for c in solver.constraints:
            if isinstance(c, JointLimits):
                lower = np.maximum(lower, c.q_min)
                upper = np.minimum(upper, c.q_max)
        for x in (q_min, q_max):
            if isinstance(x, str):
                assert x == "robot", (
                    f'Sampling limits must be arrays or "robot", got {x!r}'
                )
        self.q_min = lower if isinstance(q_min, str) else np.asarray(q_min, dtype=float)
        self.q_max = upper if isinstance(q_max, str) else np.asarray(q_max, dtype=float)
        assert np.all(np.isfinite(self.q_min)) and np.all(np.isfinite(self.q_max)), (
            "Unbounded sampling range: pass q_min and q_max, or give the solver "
            + "JointLimits"
        )

        self.max_iters = max_iters
        if dt_max is None:
            assert solver.max_gain is not None, "A term has no gain: pass dt_max"
            dt_max = 1.0 / solver.max_gain
        self.dt_max = dt_max
        self.tol = tol
        self.cost_tol = cost_tol
        self.devices = tuple(_resolve_devices(devices))

    def solve(self, q: Array, ref: Any, key: Array) -> GlobalIKResult:
        """Solve global IK

        Args:
            q (Array): Current configuration, shape (nq,)
            ref (Any): Reference data (any pytree)
            key (Array): PRNG key for the samples

        Returns:
            GlobalIKResult: Result
        """
        solver, robot = self.solver, self.solver.robot
        joints = slice(robot.nq_floating, None)

        def converge(q0, ref):
            state, iters = solver.converge(
                solver.init(q0), ref, self.max_iters, self.dt_max, self.tol
            )
            return state.q, iters, solver.cost(state.q, ref)

        def select(qs, costs, iters, sampled):
            if self.cost_tol is None:
                best = jnp.argmin(costs)
            else:
                acceptable = costs <= jnp.min(costs) + self.cost_tol
                distance = jnp.sum((qs[:, joints] - q[joints]) ** 2, axis=1)
                best = jnp.argmin(jnp.where(acceptable, distance, jnp.inf))
            return GlobalIKResult(qs[best], costs[best], qs, costs, iters, sampled)

        def sample():
            q0s = sample_configurations(
                robot, q, key, self.num_samples, self.q_min, self.q_max
            )
            converge_all = device_vmap(converge, self.devices, in_axes=(0, None))
            qs, iters, costs = converge_all(q0s, ref)
            return select(qs, costs, iters, jnp.array(True))

        if self.cost_tol is None:
            return sample()
        q_local, iters_local, cost_local = converge(q, ref)

        def keep_local():
            tile = lambda x: jnp.broadcast_to(x, (self.num_samples,) + jnp.shape(x))
            return select(
                tile(q_local), tile(cost_local), tile(iters_local), jnp.array(False)
            )

        return jax.lax.cond(cost_local <= self.cost_tol, keep_local, sample)

solve(q, ref, key)

Solve global IK

Parameters:

Name Type Description Default
q Array

Current configuration, shape (nq,)

required
ref Any

Reference data (any pytree)

required
key Array

PRNG key for the samples

required

Returns:

Name Type Description
GlobalIKResult GlobalIKResult

Result

Source code in frax/ik/global_ik.py
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
def solve(self, q: Array, ref: Any, key: Array) -> GlobalIKResult:
    """Solve global IK

    Args:
        q (Array): Current configuration, shape (nq,)
        ref (Any): Reference data (any pytree)
        key (Array): PRNG key for the samples

    Returns:
        GlobalIKResult: Result
    """
    solver, robot = self.solver, self.solver.robot
    joints = slice(robot.nq_floating, None)

    def converge(q0, ref):
        state, iters = solver.converge(
            solver.init(q0), ref, self.max_iters, self.dt_max, self.tol
        )
        return state.q, iters, solver.cost(state.q, ref)

    def select(qs, costs, iters, sampled):
        if self.cost_tol is None:
            best = jnp.argmin(costs)
        else:
            acceptable = costs <= jnp.min(costs) + self.cost_tol
            distance = jnp.sum((qs[:, joints] - q[joints]) ** 2, axis=1)
            best = jnp.argmin(jnp.where(acceptable, distance, jnp.inf))
        return GlobalIKResult(qs[best], costs[best], qs, costs, iters, sampled)

    def sample():
        q0s = sample_configurations(
            robot, q, key, self.num_samples, self.q_min, self.q_max
        )
        converge_all = device_vmap(converge, self.devices, in_axes=(0, None))
        qs, iters, costs = converge_all(q0s, ref)
        return select(qs, costs, iters, jnp.array(True))

    if self.cost_tol is None:
        return sample()
    q_local, iters_local, cost_local = converge(q, ref)

    def keep_local():
        tile = lambda x: jnp.broadcast_to(x, (self.num_samples,) + jnp.shape(x))
        return select(
            tile(q_local), tile(cost_local), tile(iters_local), jnp.array(False)
        )

    return jax.lax.cond(cost_local <= self.cost_tol, keep_local, sample)

sample_configurations(robot, q, key, num_samples, q_min='robot', q_max='robot')

Sample configurations for global IK

The actuated joints are sampled uniformly. The floating base stays at q's: it has no joint limits to sample within, and is usually pinned by a task

Parameters:

Name Type Description Default
robot Robot

Robot model

required
q Array

Nominal configuration, shape (nq,). This is also included as the first sample

required
key Array

PRNG key

required
num_samples int

Number of samples, including q

required
q_min ArrayLike | robot

Lower joint bounds, shape (num_actuated,). Defaults to "robot", for robot.actuated_joint_lower_limits

'robot'
q_max ArrayLike | robot

Upper joint bounds, shape (num_actuated,). Defaults to "robot", for robot.actuated_joint_upper_limits

'robot'

Returns:

Name Type Description
Array Array

Sampled configurations, shape (num_samples, nq)

Source code in frax/ik/global_ik.py
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
def sample_configurations(
    robot: Robot,
    q: Array,
    key: Array,
    num_samples: int,
    q_min: ArrayLike | Literal["robot"] = "robot",
    q_max: ArrayLike | Literal["robot"] = "robot",
) -> Array:
    """Sample configurations for global IK

    The actuated joints are sampled uniformly. The floating base stays at q's:
    it has no joint limits to sample within, and is usually pinned by a task

    Args:
        robot (Robot): Robot model
        q (Array): Nominal configuration, shape (nq,).
            This is also included as the first sample
        key (Array): PRNG key
        num_samples (int): Number of samples, including q
        q_min (ArrayLike | "robot"): Lower joint bounds, shape (num_actuated,).
            Defaults to "robot", for robot.actuated_joint_lower_limits
        q_max (ArrayLike | "robot"): Upper joint bounds, shape (num_actuated,).
            Defaults to "robot", for robot.actuated_joint_upper_limits

    Returns:
        Array: Sampled configurations, shape (num_samples, nq)
    """
    if isinstance(q_min, str):
        assert q_min == "robot", f'q_min must be an array or "robot", got {q_min!r}'
        q_min = np.asarray(robot.actuated_joint_lower_limits, dtype=float)
        assert np.all(np.isfinite(q_min)), "Unbounded joint limits: pass q_min"
    if isinstance(q_max, str):
        assert q_max == "robot", f'q_max must be an array or "robot", got {q_max!r}'
        q_max = np.asarray(robot.actuated_joint_upper_limits, dtype=float)
        assert np.all(np.isfinite(q_max)), "Unbounded joint limits: pass q_max"
    joints = jax.random.uniform(
        key,
        (num_samples - 1, robot.nq - robot.nq_floating),
        minval=q_min,
        maxval=q_max,
        dtype=q.dtype,
    )
    base = jnp.broadcast_to(
        q[: robot.nq_floating], (num_samples - 1, robot.nq_floating)
    )
    return jnp.concatenate([q[None], jnp.concatenate([base, joints], axis=1)])

IK and motion utilities

load_bvh(filepath, to_world=None, scale=0.01)

Global bone poses from a BVH file

Parameters:

Name Type Description Default
filepath str | Path

BVH file

required
to_world ArrayLike | None

Rotation from the BVH frame to the world, shape (3, 3). Defaults to identity

None
scale float

BVH length unit (m). Defaults to cm

0.01

Returns:

Name Type Description
poses ndarray

Poses [position, WXYZ quaternion], shape (T, B, 7)

names list[str]

The B bone names

Raises:

Type Description
ValueError

If any frame has NaNs

Source code in frax/ik/utils.py
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
def load_bvh(
    filepath: str | Path, to_world: ArrayLike | None = None, scale: float = 0.01
) -> tuple[np.ndarray, list[str]]:
    """Global bone poses from a BVH file

    Args:
        filepath (str | Path): BVH file
        to_world (ArrayLike | None): Rotation from the BVH frame to the world,
            shape (3, 3). Defaults to identity
        scale (float): BVH length unit (m). Defaults to cm

    Returns:
        poses (np.ndarray): Poses [position, WXYZ quaternion], shape (T, B, 7)
        names (list[str]): The B bone names

    Raises:
        ValueError: If any frame has NaNs
    """
    names, parents, local_pos, local_rot = _parse_bvh(filepath)
    T, B = local_pos.shape[:2]
    rot = np.zeros((T, B, 3, 3))
    pos = np.zeros((T, B, 3))
    for i, parent in enumerate(parents):  # Parents precede their children
        if parent < 0:
            rot[:, i], pos[:, i] = local_rot[:, i], local_pos[:, i]
        else:
            rot[:, i] = rot[:, parent] @ local_rot[:, i]
            pos[:, i] = pos[:, parent] + np.einsum(
                "tij,tj->ti", rot[:, parent], local_pos[:, i]
            )
    to_world = np.eye(3) if to_world is None else np.asarray(to_world, dtype=float)
    pos = scale * pos @ to_world.T
    quat = Rotation.from_matrix((to_world @ rot).reshape(-1, 3, 3))
    quat = quat.as_quat(scalar_first=True).reshape(T, B, 4)
    return np.concatenate([pos, quat], axis=-1), names

smooth_poses(poses, dt, sigma_pos=0.0, sigma_rot=0.0)

Zero-phase Gaussian smoothing of a clip of poses along time, for offline retargeting

Parameters:

Name Type Description Default
poses ArrayLike

Poses [position, WXYZ quaternion], shape (T, ..., 7)

required
dt float

Time between poses

required
sigma_pos float

Position kernel standard deviation (s). 0 to not smooth

0.0
sigma_rot float

Rotation kernel standard deviation (s). 0 to not smooth

0.0

Returns:

Type Description
ndarray

np.ndarray: Smoothed poses, shape (T, ..., 7)

Source code in frax/ik/utils.py
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
def smooth_poses(
    poses: ArrayLike, dt: float, sigma_pos: float = 0.0, sigma_rot: float = 0.0
) -> np.ndarray:
    """Zero-phase Gaussian smoothing of a clip of poses along time,
    for offline retargeting

    Args:
        poses (ArrayLike): Poses [position, WXYZ quaternion], shape (T, ..., 7)
        dt (float): Time between poses
        sigma_pos (float): Position kernel standard deviation (s). 0 to not smooth
        sigma_rot (float): Rotation kernel standard deviation (s). 0 to not smooth

    Returns:
        np.ndarray: Smoothed poses, shape (T, ..., 7)
    """
    poses = np.array(poses, dtype=float)
    if sigma_pos > 0:
        poses[..., :3] = gaussian_filter1d(
            poses[..., :3], sigma_pos / dt, axis=0, mode="nearest"
        )
    if sigma_rot > 0:
        quat = poses[..., 3:]
        # Sign-align, so componentwise filtering approximates the geodesic mean
        flips = np.sum(quat[1:] * quat[:-1], axis=-1) < 0
        signs = np.cumprod(np.where(flips, -1.0, 1.0), axis=0)
        quat[1:] *= signs[..., None]
        quat = gaussian_filter1d(quat, sigma_rot / dt, axis=0, mode="nearest")
        poses[..., 3:] = quat / np.linalg.norm(quat, axis=-1, keepdims=True)
    return poses

resample_poses(poses, fps_in, fps_out)

Resample a clip of poses to a new frame rate

Parameters:

Name Type Description Default
poses ArrayLike

Poses [position, WXYZ quaternion], shape (T, ..., 7)

required
fps_in float

Frame rate of poses

required
fps_out float

Frame rate to resample to

required

Returns:

Type Description
ndarray

np.ndarray: Resampled poses, shape (T_out, ..., 7), with T_out = floor((T - 1) * fps_out / fps_in) + 1

Source code in frax/ik/utils.py
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def resample_poses(poses: ArrayLike, fps_in: float, fps_out: float) -> np.ndarray:
    """Resample a clip of poses to a new frame rate

    Args:
        poses (ArrayLike): Poses [position, WXYZ quaternion], shape (T, ..., 7)
        fps_in (float): Frame rate of poses
        fps_out (float): Frame rate to resample to

    Returns:
        np.ndarray: Resampled poses, shape (T_out, ..., 7), with
            T_out = floor((T - 1) * fps_out / fps_in) + 1
    """
    poses = np.asarray(poses, dtype=float)
    T = len(poses)
    assert T >= 2, "Need at least two poses to resample"
    flat = poses.reshape(T, -1, 7)
    n = flat.shape[1]

    T_out = int(np.floor((T - 1) * fps_out / fps_in + 1e-9)) + 1
    frame_times = np.arange(T_out) * fps_in / fps_out  # In input frames
    i = np.minimum(frame_times.astype(int), T - 2)
    alpha = frame_times - i
    before, after = flat[i], flat[i + 1]

    a = alpha[:, None, None]
    pos = (1 - a) * before[..., :3] + a * after[..., :3]

    rot_before = Rotation.from_quat(before[..., 3:].reshape(-1, 4), scalar_first=True)
    rot_after = Rotation.from_quat(after[..., 3:].reshape(-1, 4), scalar_first=True)
    relative = (rot_before.inv() * rot_after).as_rotvec()
    a = np.repeat(alpha, n)[:, None]
    rot = rot_before * Rotation.from_rotvec(a * relative)
    quat = rot.as_quat(scalar_first=True).reshape(T_out, n, 4)

    out = np.concatenate([pos, quat], axis=-1)
    return out.reshape(T_out, *poses.shape[1:])

save_motion(path, robot, q, fps)

Save a motion as an .npz file with fields q (float32), fps, and the actuated joint_names

Parameters:

Name Type Description Default
path str | Path

Output file (.npz)

required
robot Robot

Robot model

required
q ArrayLike

Configurations, shape (T, nq)

required
fps float

Frame rate

required
Source code in frax/ik/utils.py
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
def save_motion(path: str | Path, robot: Robot, q: ArrayLike, fps: float) -> None:
    """Save a motion as an .npz file with fields q (float32), fps, and the
    actuated joint_names

    Args:
        path (str | Path): Output file (.npz)
        robot (Robot): Robot model
        q (ArrayLike): Configurations, shape (T, nq)
        fps (float): Frame rate
    """
    q = np.asarray(q)
    assert q.ndim == 2 and q.shape[1] == robot.nq, (
        f"q has shape {q.shape}, expected (T, {robot.nq})"
    )
    np.savez(
        path,
        q=q.astype(np.float32),
        fps=float(fps),
        joint_names=np.array(robot.joint_names[robot.nv_floating :]),
    )