Algorithm Search⌘K

Algorithmresearch

Style-based inverse kinematics

Also called style-based IK.

Solve inverse kinematics by choosing the most likely pose under a scaled Gaussian process latent variable model learned from motion capture.

Time
O(I (N^2 + N D d + (D + d)^2)) queryO(N^3 + N^2 D) training
Space
O(N^2 + N D + (D + d)^2) extra
Where
D = the number of pose coordinates; I = the number of optimizer iterations; N = the number of training poses; d = the latent dimension
Properties
deterministicnot exactofflineiterative

Style-based inverse kinematics finds a pose of a character that meets a few constraints, such as a hand on a target, and also looks like the poses of a motion capture example. Plain inverse kinematics has many solutions for a redundant chain, and most of them look wrong for a human. Grochow, Martin, Hertzmann and Popović (2004) learn a probability model of poses from the example, a scaled Gaussian process latent variable model (SGPLVM), and then return the pose of the highest likelihood that meets the constraints. The same constraints give a different pose for a model learned from a different style, for example a throw or a walk.

In plain words

Many poses put the hand at the same place, and the solver must choose one. This method lets a set of example poses choose. It learns a smooth map from a few hidden numbers, the latent point, to a full pose. The map is a Gaussian process: at each latent point it gives a mean pose and a variance, and the variance is small near the examples and large far from them. The cost of a pose has three parts. It is small when the pose is near the mean pose, when the variance is small, and when the latent point is near the origin. The solver moves the latent point and the pose together, so that the cost is small and the hand is at the target. The result is a pose like the examples, not only a pose that reaches.

The problem

The input is a trained model and the constraints. The model has the latent points x1,…,xN∈Rdx_1, \ldots, x_N \in \mathbb{R}^d of NN training poses y1,…,yN∈RDy_1, \ldots, y_N \in \mathbb{R}^D, their mean μ\mu, a scale wk>0w_k > 0 for each pose coordinate, and the kernel

k(x,x′)=αexp⁡(−γ2∥x−x′∥2)+δx,x′β−1.k(x, x') = \alpha \exp\left(-\tfrac{\gamma}{2} \lVert x - x' \rVert^2\right) + \delta_{x, x'} \beta^{-1}.

With Kij=k(xi,xj)K_{ij} = k(x_i, x_j), YY the centered poses as rows, and k(x)k(x) the vector of k(x,xj)k(x, x_j), the model predicts at any latent point xx the mean pose and the variance

f(x)=μ+Y⊤K−1k(x),σ2(x)=k(x,x)−k(x)⊤K−1k(x).f(x) = \mu + Y^\top K^{-1} k(x), \qquad \sigma^2(x) = k(x, x) - k(x)^\top K^{-1} k(x).

The negative log likelihood of a pose yy at the latent point xx is, up to a constant,

LIK(x,y)=∥W(y−f(x))∥22σ2(x)+D2ln⁡σ2(x)+12∥x∥2,L_{IK}(x, y) = \frac{\lVert W (y - f(x)) \rVert^2}{2 \sigma^2(x)} + \frac{D}{2} \ln \sigma^2(x) + \frac12 \lVert x \rVert^2,

with W=diag⁡(wk)W = \operatorname{diag}(w_k). The constraints are written as g(y)=pg(y) = p for the forward kinematics map gg of the end effector. The output is the pair (x,y)(x, y) that minimizes LIKL_{IK} subject to the constraints.

The latent points and the hyperparameters α,γ,β,w\alpha, \gamma, \beta, w are inputs here. The paper learns them from the motion capture data by maximizing the likelihood of the model, which is a separate optimization done once per style. The code in impl/python takes them as given, uses a planar chain of three links as the character, and replaces the hard constraint by the penalty λ2∥g(y)−p∥2\frac{\lambda}{2} \lVert g(y) - p \rVert^2.

The algorithm

  1. STYLE-IK(model, target p, start x₀, weight λ)
  2. 1z ← (x₀, f(x₀)); H ← I
  3. 2E, ∇E ← objective at z
  4. 3repeat:
  5. 4L_IK(x, y) ← ‖W (y - f(x))‖² / (2σ²(x)) + (D/2) ln σ²(x) + ½‖x‖²
  6. 5E ← L_IK(x, y) + (λ/2) ‖g(y) - p‖²
  7. 6d ← -H ∇E; halve the step t from 1 until E(z + t d) ≤ E(z) + 10⁻⁴ t dᵀ∇E
  8. 7z ← z + t d; update H by the BFGS formula
  9. 8until ‖∇E‖ is small or the step is below the rounding level of z
  10. 9return z = (x, y)

Lines L4 and L5 are evaluated inside the objective of lines L2 and L6. The gradient is analytic. With r=W(y−f(x))r = W (y - f(x)), the gradient in yy is Wr/σ2+λJ⊤(g(y)−p)W r / \sigma^2 + \lambda J^\top (g(y) - p), where JJ is the Jacobian of gg. The gradient in xx uses ∇f\nabla f and ∇σ2=−2∇k(x)⊤K−1k(x)\nabla \sigma^2 = -2 \nabla k(x)^\top K^{-1} k(x), and ∇k(x,xj)=−γ(x−xj)k(x,xj)\nabla k(x, x_j) = -\gamma (x - x_j) k(x, x_j). The matrix K−1K^{-1} and the product K−1YK^{-1} Y are computed once, when the model is built.

The paper solves the constrained problem with SQP, and also uses L-BFGS. The code uses BFGS with a backtracking line search on the penalty form, which is simpler and enough for a small chain. If the BFGS direction is not a descent direction, the code resets HH to the identity and takes the steepest descent direction.

Example

The tests use a chain of three links of lengths 1, 0.8 and 0.6, with joint angles y=(y1,y2,y3)y = (y_1, y_2, y_3). The style is a curve of nine poses y(s)=(0.2+0.8s, 0.5−0.3s+0.2s2, 0.9s)y(s) = (0.2 + 0.8 s,\ 0.5 - 0.3 s + 0.2 s^2,\ 0.9 s) at s=−1,−0.75,…,1s = -1, -0.75, \ldots, 1, with the latent point x=sx = s and α=1\alpha = 1, γ=2\gamma = 2, β=1000\beta = 1000.

Put the target at the end effector of the training pose at s=0.5s = 0.5, which is y=(0.6,0.4,0.45)y = (0.6, 0.4, 0.45). From the start x0=0.25x_0 = 0.25 with λ=105\lambda = 10^5, BFGS takes 21 steps and returns x=0.5001x = 0.5001 and y=(0.5999,0.4003,0.4496)y = (0.5999, 0.4003, 0.4496), which is the training pose. Plain inverse kinematics, with minimum norm Newton steps from the training pose at s=−1s = -1, reaches the same target exactly, but with y=(0.619,0.781,−0.514)y = (0.619, 0.781, -0.514). That pose is valid for the chain, but it is not in the style.

A check value for a small model: two training poses (0,0,0)(0, 0, 0) and (1,2,3)(1, 2, 3) at the latents −1-1 and 11, with α=γ=1\alpha = \gamma = 1 and β=100\beta = 100. At x=0x = 0, the two kernel values are equal, so f(0)f(0) is the mean (0.5,1,1.5)(0.5, 1, 1.5), and

σ2(0)=1.01−2e−11.01+e−2≈0.3676.\sigma^2(0) = 1.01 - \frac{2 e^{-1}}{1.01 + e^{-2}} \approx 0.3676.

Correctness

The proofs are in proofs/correctness.md.

  • The gradient is exact. The formulas above follow from the chain rule, and the tests compare them with central differences.
  • The objective decreases. Each accepted step satisfies the Armijo condition along a descent direction, so EE decreases at every step, and the method stops at a point where the gradient is small or no step decreases EE at the rounding level.
  • Without constraints, the pose is the mean pose. With λ=0\lambda = 0, the minimizer in yy for a fixed xx is y=f(x)y = f(x), and the problem reduces to minimizing D2ln⁡σ2(x)+12∥x∥2\frac{D}{2} \ln \sigma^2(x) + \frac12 \lVert x \rVert^2 over xx. The tests check this against a grid search.
  • The penalty approaches the constraint. For a larger λ\lambda, the end effector error at the global minimizer does not increase. The tests check this for the local minima that the solver finds.

The objective is not convex, so the method finds a local minimum, as any gradient based solver of this problem.

Proof: The gradient of the style-based IK objective is exact, each step decreases it, and without constraints the pose is the mean posefull

We use the notation of the page. E(x,y)=LIK(x,y)+λ2∥g(y)−p∥2E(x, y) = L_{IK}(x, y) + \frac{\lambda}{2} \lVert g(y) - p \rVert^2, with r=W(y−f(x))r = W (y - f(x)) and σ2=σ2(x)\sigma^2 = \sigma^2(x). KK is symmetric positive definite, because the RBF kernel matrix is positive semidefinite and β−1I\beta^{-1} I is positive definite. The arithmetic is exact.

The variance is positive

Lemma 1. σ2(x)≥β−1>0\sigma^2(x) \ge \beta^{-1} > 0 for every xx.

Proof. Let k0k_0 be the vector of the RBF values αexp⁡(−γ2∥x−xj∥2)\alpha \exp(-\frac{\gamma}{2} \lVert x - x_j \rVert^2) and GG the RBF matrix of the training latents, so K=G+β−1IK = G + \beta^{-1} I. If xx is not a training latent, then k(x)=k0k(x) = k_0 and k(x,x)=α+β−1k(x, x) = \alpha + \beta^{-1}. The matrix (αk0⊤k0G)\begin{pmatrix} \alpha & k_0^\top \\ k_0 & G \end{pmatrix} is an RBF kernel matrix, so it is positive semidefinite, and adding β−1I\beta^{-1} I to its lower block gives (αk0⊤k0K)⪰0\begin{pmatrix} \alpha & k_0^\top \\ k_0 & K \end{pmatrix} \succeq 0. Its Schur complement α−k0⊤K−1k0\alpha - k_0^\top K^{-1} k_0 is therefore at least 0, and σ2=α−k0⊤K−1k0+β−1≥β−1\sigma^2 = \alpha - k_0^\top K^{-1} k_0 + \beta^{-1} \ge \beta^{-1}. The code uses k(x,x)=α+β−1k(x, x) = \alpha + \beta^{-1} and k(x)=k0k(x) = k_0 for every xx, also at a training latent, which is the same formula, so the bound holds there too. □\square

So ln⁡σ2\ln \sigma^2 and 1/σ21 / \sigma^2 are smooth, and EE is a smooth function of (x,y)(x, y).

The gradient

Lemma 2. With a=K−1k(x)a = K^{-1} k(x) and ∇kj=−γ(x−xj)k(x,xj)\nabla k_j = -\gamma (x - x_j) k(x, x_j),

∇fk=∑j(K−1Y)jk∇kj,∇σ2=−2∑jaj∇kj.\nabla f_k = \sum_j (K^{-1} Y)_{jk} \nabla k_j, \qquad \nabla \sigma^2 = -2 \sum_j a_j \nabla k_j.

Proof. fk=μk+∑j(K−1Y)jkkj(x)f_k = \mu_k + \sum_j (K^{-1} Y)_{jk} k_j(x) is linear in k(x)k(x), which gives the first formula. σ2=α+β−1−k⊤K−1k\sigma^2 = \alpha + \beta^{-1} - k^\top K^{-1} k, and the derivative of a quadratic form with the symmetric K−1K^{-1} is 2(K−1k)⊤∇k2 (K^{-1} k)^\top \nabla k. The derivative of αexp⁡(−γ2∥x−xj∥2)\alpha \exp(-\frac{\gamma}{2} \lVert x - x_j \rVert^2) is −γ(x−xj)-\gamma (x - x_j) times the value. □\square

Theorem 1. The gradient that objective returns is the gradient of EE:

∇yE=Wrσ2+λJ⊤(g(y)−p),∇xE=−(∇f)⊤Wrσ2+(D2σ2−∥r∥22σ4)∇σ2+x.\nabla_y E = \frac{W r}{\sigma^2} + \lambda J^\top (g(y) - p), \qquad \nabla_x E = -\frac{(\nabla f)^\top W r}{\sigma^2} + \left(\frac{D}{2 \sigma^2} - \frac{\lVert r \rVert^2}{2 \sigma^4}\right) \nabla \sigma^2 + x.

Proof. In yy: ∇y∥r∥22σ2=W⊤r/σ2=Wr/σ2\nabla_y \frac{\lVert r \rVert^2}{2 \sigma^2} = W^\top r / \sigma^2 = W r / \sigma^2, the other terms of LIKL_{IK} do not depend on yy, and the gradient of λ2∥g(y)−p∥2\frac{\lambda}{2} \lVert g(y) - p \rVert^2 is λJ⊤(g(y)−p)\lambda J^\top (g(y) - p). In xx: rr depends on xx through −Wf(x)-W f(x), so ∇x∥r∥2=−2(∇f)⊤Wr\nabla_x \lVert r \rVert^2 = -2 (\nabla f)^\top W r. The quotient rule gives ∇x∥r∥22σ2=−(∇f)⊤Wrσ2−∥r∥22σ4∇σ2\nabla_x \frac{\lVert r \rVert^2}{2 \sigma^2} = -\frac{(\nabla f)^\top W r}{\sigma^2} - \frac{\lVert r \rVert^2}{2 \sigma^4} \nabla \sigma^2. ∇xD2ln⁡σ2=D2σ2∇σ2\nabla_x \frac{D}{2} \ln \sigma^2 = \frac{D}{2 \sigma^2} \nabla \sigma^2 and ∇x12∥x∥2=x\nabla_x \frac12 \lVert x \rVert^2 = x. For the planar chain, the end point is g(y)=∑kℓk(cos⁡θk,sin⁡θk)g(y) = \sum_k \ell_k (\cos \theta_k, \sin \theta_k) with θk=y1+⋯+yk\theta_k = y_1 + \cdots + y_k, and ∂θk/∂yi=1\partial \theta_k / \partial y_i = 1 for k≥ik \ge i, so column ii of JJ is ∑k≥iℓk(−sin⁡θk,cos⁡θk)\sum_{k \ge i} \ell_k (-\sin \theta_k, \cos \theta_k), which is what end_effector returns. □\square

Each step decreases the objective

Theorem 2. Every accepted step decreases EE, and the sequence of the values of EE is strictly decreasing until the method stops.

Proof. If ∇E=0\nabla E = 0, the method stops at line L8. Otherwise, the direction dd of line L6 has d⊤∇E<0d^\top \nabla E < 0: either the BFGS direction has this property, or the code takes d=−∇Ed = -\nabla E, for which d⊤∇E=−∥∇E∥2<0d^\top \nabla E = -\lVert \nabla E \rVert^2 < 0. EE is differentiable, so E(z+td)=E(z)+td⊤∇E+o(t)E(z + t d) = E(z) + t d^\top \nabla E + o(t), and for every small enough t>0t > 0, E(z+td)≤E(z)+10−4td⊤∇EE(z + t d) \le E(z) + 10^{-4} t d^\top \nabla E, because 10−4<110^{-4} < 1. So the halving stops at some t>0t > 0, unless tt falls below 10−1610^{-16}, in which case the method returns the current point without a step. An accepted step satisfies E(z+td)≤E(z)+10−4td⊤∇E<E(z)E(z + t d) \le E(z) + 10^{-4} t d^\top \nabla E < E(z). □\square

The BFGS update keeps HH symmetric positive definite when s⊤yv>0s^\top y_v > 0, where ss is the step and yvy_v the change of the gradient, and the code skips the update otherwise. Then the BFGS direction is a descent direction, and the reset of line L6 only guards against rounding.

The method has no guarantee of a global minimum: EE is not convex, and the page shows two local minima for the same target.

Without constraints, the pose is the mean pose

Theorem 3. Let λ=0\lambda = 0. For a fixed xx, the unique minimizer of E(x,⋅)E(x, \cdot) is y=f(x)y = f(x), and (x∗,y∗)(x^*, y^*) minimizes EE if and only if y∗=f(x∗)y^* = f(x^*) and x∗x^* minimizes h(x)=D2ln⁡σ2(x)+12∥x∥2h(x) = \frac{D}{2} \ln \sigma^2(x) + \frac12 \lVert x \rVert^2. At a stationary point of EE, y=f(x)y = f(x) and ∇h(x)=0\nabla h(x) = 0.

Proof. For a fixed xx, E(x,y)=∥W(y−f(x))∥22σ2+h(x)E(x, y) = \frac{\lVert W (y - f(x)) \rVert^2}{2 \sigma^2} + h(x), and the first term is at least 0, with equality exactly at y=f(x)y = f(x), because WW is invertible. So min⁡yE(x,y)=h(x)\min_y E(x, y) = h(x), and min⁡x,yE=min⁡xh\min_{x, y} E = \min_x h, with the minimizers as stated. At a stationary point, ∇yE=Wr/σ2=0\nabla_y E = W r / \sigma^2 = 0, so r=0r = 0 and y=f(x)y = f(x). Then ∇xE=D2σ2∇σ2+x=∇h(x)\nabla_x E = \frac{D}{2 \sigma^2} \nabla \sigma^2 + x = \nabla h(x), which is 0. □\square

The test compares the result of the solver with the best point of a grid search on hh.

The penalty

Theorem 4. Let (x1,y1)(x_1, y_1) and (x2,y2)(x_2, y_2) be global minimizers of EE for λ1<λ2\lambda_1 < \lambda_2, and ci=∥g(yi)−p∥2c_i = \lVert g(y_i) - p \rVert^2. Then c2≤c1c_2 \le c_1.

Proof. Write Eλ=L+λ2cE_\lambda = L + \frac{\lambda}{2} c. By the optimality of each point, L1+λ12c1≤L2+λ12c2L_1 + \frac{\lambda_1}{2} c_1 \le L_2 + \frac{\lambda_1}{2} c_2 and L2+λ22c2≤L1+λ22c1L_2 + \frac{\lambda_2}{2} c_2 \le L_1 + \frac{\lambda_2}{2} c_1. Adding the two inequalities gives λ1−λ22(c1−c2)≤0\frac{\lambda_1 - \lambda_2}{2} (c_1 - c_2) \le 0, and λ1<λ2\lambda_1 < \lambda_2 gives c1≥c2c_1 \ge c_2. □\square

The check value

Take the latents −1-1 and 11, the poses (0,0,0)(0, 0, 0) and (1,2,3)(1, 2, 3), α=γ=1\alpha = \gamma = 1 and β=100\beta = 100. Then μ=(0.5,1,1.5)\mu = (0.5, 1, 1.5), the centered poses are ∓(0.5,1,1.5)\mp (0.5, 1, 1.5), and K=(1.01e−2e−21.01)K = \begin{pmatrix} 1.01 & e^{-2} \\ e^{-2} & 1.01 \end{pmatrix}, since ∥x1−x2∥2=4\lVert x_1 - x_2 \rVert^2 = 4. At x=0x = 0, k(0)=(e−1/2,e−1/2)k(0) = (e^{-1/2}, e^{-1/2}), which is an eigenvector of KK with the eigenvalue 1.01+e−21.01 + e^{-2}. So K−1k(0)=k(0)/(1.01+e−2)K^{-1} k(0) = k(0) / (1.01 + e^{-2}), which has two equal entries, and Y⊤K−1k(0)Y^\top K^{-1} k(0) is a multiple of −(0.5,1,1.5)+(0.5,1,1.5)=0-(0.5, 1, 1.5) + (0.5, 1, 1.5) = 0, so f(0)=μf(0) = \mu. k(0)⊤K−1k(0)=2e−1/(1.01+e−2)k(0)^\top K^{-1} k(0) = 2 e^{-1} / (1.01 + e^{-2}), so σ2(0)=1.01−2e−1/(1.01+e−2)=1.01−0.735759/1.145335≈0.367604\sigma^2(0) = 1.01 - 2 e^{-1} / (1.01 + e^{-2}) = 1.01 - 0.735759 / 1.145335 \approx 0.367604.

Complexity

The costs are in the real RAM model. Building the model inverts KK in O(N3)O(N^3) and forms K−1YK^{-1} Y in O(N2D)O(N^2 D). One evaluation of the objective costs O(N2)O(N^2) for K−1k(x)K^{-1} k(x) and O(NDd)O(N D d) for ff and its gradient, plus O(D)O(D) for the forward kinematics of a chain. The BFGS update costs O((D+d)2)O((D + d)^2). With a bounded number of line search steps, a query with II iterations costs O(I(N2+NDd+(D+d)2))O(I (N^2 + N D d + (D + d)^2)). The cost grows with NN, so for interactive use the model is built on a moderate number of poses, for example a subset of the frames of the motion capture.

Properties

  • Learned prior: the pose comes from a model of the example motion, not from a hand made cost such as the distance to a rest pose.
  • Same constraints, different styles: changing the model changes the pose, without changing the constraints.
  • Probabilistic: the variance tells how far a pose is from the data, and the cost grows when the solver leaves the data.
  • Local: the solver finds a local minimum, which depends on the start.
  • Smooth: the objective is smooth in xx and yy, so gradient based solvers apply.

Variants and improvements

  • Hard constraints. Solve the constrained problem with SQP, as in the paper, instead of the penalty. The penalty with a large λ\lambda is close, but it never meets the constraint exactly.
  • Learning the model. Fit the latent points and the hyperparameters by maximizing the likelihood of the training data, starting from principal component analysis of the poses.
  • Style interpolation. Blend two learned models to get poses between two styles.
  • Dynamics. Later work adds a model of motion in the latent space, so that a sequence of poses is likely as a motion and not only pose by pose.
  • Other priors. A simple prior, such as the distance to a rest pose or a Gaussian on the joint angles, also chooses among the solutions, but it does not know the style.

When to use it

Use style-based inverse kinematics when an animator or a game must pose a character from a few constraints, and the result must look like a known kind of motion. It needs motion capture of the style, and a training step per style. For a pose that only has to reach, plain solvers such as damped least squares or the Jacobian pseudoinverse are simpler and faster. For a whole motion that meets constraints over time, see spacetime constraints and motion retargeting.

Pitfalls

  • Local minima. In the example, from the start x0=0x_0 = 0 the solver goes to x≈1.54x \approx 1.54, outside the training latents, with E≈−0.36E \approx -0.36, while the start x0=0.25x_0 = 0.25 gives the training pose with E≈−9.61E \approx -9.61. Start from the latent point of a training pose that is near the target.
  • Leaving the data. Far from the training latents, σ2\sigma^2 goes to α+β−1\alpha + \beta^{-1} and ff goes to the mean pose, so a far target gives a pose that is close to the mean and does not reach well.
  • Penalty weight. A small λ\lambda misses the target; a large λ\lambda makes the problem badly conditioned and needs more iterations.
  • Joint angles. The model is a Gaussian process on the pose coordinates, so the coordinates must be smooth in the motion, for example without jumps of 2π2\pi in the angles.
  • Cancellation in the variance. σ2\sigma^2 is a difference of two numbers close to α\alpha, so near the training latents it has a large relative rounding error. Keep β\beta moderate.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

anim.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the graphics-and-signals animation and simulation pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small vectors, matrices, polar decomposition, quaternions and transforms.

This file is copied byte for byte into each impl/python folder that needs it.
It holds no method of a page: no curve, no skinning, no integrator step, no
collision test and no solver of a page. The method of each page lives in its
slug file.

Conventions (prompts/graphics-ext.md, "Mathematical conventions"):
- Vectors are tuples. Functions accept lists too and return tuples.
- Matrices are lists of rows, and a matrix acts on a column vector on the
  left: x' = M x.
- Quaternions use the Hamilton convention, scalar first, q = (w, x, y, z)
  with i j = k. A unit quaternion q rotates v by v' = q (0, v) q*.
- The log of a unit quaternion (cos phi, sin phi u) is (0, phi u), and the
  rotation angle is 2 phi. q_exp is the inverse map.
- Angles are in radians.
"""

import math

# Below this angle on the sphere of R^4, slerp uses normalized linear
# interpolation (nlerp), which avoids the division by sin(W).
SLERP_SMALL_ANGLE = 1e-6


# ---------------------------------------------------------------- vectors


def add(a, b):
    """Return a + b."""
    return tuple(x + y for x, y in zip(a, b))


def sub(a, b):
    """Return a - b."""
    return tuple(x - y for x, y in zip(a, b))


def scale(a, s):
    """Return s a for a number s."""
    return tuple(s * x for x in a)


def dot(a, b):
    """Return the dot product of a and b."""
    return sum(x * y for x, y in zip(a, b))


def cross(a, b):
    """Return the cross product of two 3D vectors."""
    return (
        a[1] * b[2] - a[2] * b[1],
        a[2] * b[0] - a[0] * b[2],
        a[0] * b[1] - a[1] * b[0],
    )


def cross2(a, b):
    """Return the scalar 2D cross product a_x b_y - a_y b_x."""
    return a[0] * b[1] - a[1] * b[0]


def norm(a):
    """Return the Euclidean length of a."""
    return math.sqrt(sum(x * x for x in a))


def normalize(a):
    """Return a / |a|. Raise ValueError for the zero vector."""
    n = norm(a)
    if n == 0.0:
        raise ValueError("cannot normalize the zero vector")
    return tuple(x / n for x in a)


def lerp(a, b, t):
    """Return (1 - t) a + t b."""
    return tuple((1 - t) * x + t * y for x, y in zip(a, b))


# ---------------------------------------------------------------- matrices


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None)."""
    if m is None:
        m = n
    return [[0.0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix."""
    return [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]


def mul(a, b):
    """Return the matrix product a b."""
    bt = list(zip(*b))
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the vector a x as a tuple."""
    return tuple(sum(p * q for p, q in zip(row, x)) for row in a)


def transpose(a):
    """Return the transpose of a."""
    return [list(col) for col in zip(*a)]


def _lu(a):
    """Gaussian elimination with partial pivoting on a copy of a square a.

    Return (lu, perm, sign), or None if a pivot is exactly zero.
    """
    n = len(a)
    lu = [list(map(float, row)) for row in a]
    perm = list(range(n))
    sign = 1.0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(lu[i][k]))
        if lu[p][k] == 0.0:
            return None
        if p != k:
            lu[k], lu[p] = lu[p], lu[k]
            perm[k], perm[p] = perm[p], perm[k]
            sign = -sign
        piv = lu[k][k]
        for i in range(k + 1, n):
            f = lu[i][k] / piv
            lu[i][k] = f
            if f != 0.0:
                rk = lu[k]
                ri = lu[i]
                for j in range(k + 1, n):
                    ri[j] -= f * rk[j]
    return lu, perm, sign


def det(a):
    """Return the determinant of a square matrix."""
    n = len(a)
    if n == 1:
        return a[0][0]
    if n == 2:
        return a[0][0] * a[1][1] - a[0][1] * a[1][0]
    if n == 3:
        return (
            a[0][0] * (a[1][1] * a[2][2] - a[1][2] * a[2][1])
            - a[0][1] * (a[1][0] * a[2][2] - a[1][2] * a[2][0])
            + a[0][2] * (a[1][0] * a[2][1] - a[1][1] * a[2][0])
        )
    r = _lu(a)
    if r is None:
        return 0.0
    lu, _, sign = r
    d = sign
    for i in range(n):
        d *= lu[i][i]
    return d


def _lu_solve(lu, perm, b):
    n = len(lu)
    y = [float(b[perm[i]]) for i in range(n)]
    for i in range(n):
        s = y[i]
        row = lu[i]
        for j in range(i):
            s -= row[j] * y[j]
        y[i] = s
    for i in range(n - 1, -1, -1):
        s = y[i]
        row = lu[i]
        for j in range(i + 1, n):
            s -= row[j] * y[j]
        y[i] = s / row[i]
    return y


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (returns a list) or a matrix given as a list of rows
    (returns a list of rows, one column of x per column of b).
    Raise ValueError if a is singular.
    """
    r = _lu(a)
    if r is None:
        raise ValueError("singular matrix")
    lu, perm, _ = r
    if len(b) > 0 and isinstance(b[0], (list, tuple)):
        cols = [_lu_solve(lu, perm, col) for col in zip(*b)]
        return [list(row) for row in zip(*cols)]
    return _lu_solve(lu, perm, b)


def inv(a):
    """Return the inverse of a square matrix. Raise ValueError if singular."""
    return solve(a, eye(len(a)))


# ---------------------------------------------------------------- polar decomposition


def rot2(theta):
    """Return the 2 by 2 rotation matrix by the angle theta."""
    c, s = math.cos(theta), math.sin(theta)
    return [[c, -s], [s, c]]


def _frob(a):
    return math.sqrt(sum(x * x for row in a for x in row))


def _sym_eig3(s):
    """Eigenvalues and eigenvectors of a symmetric 3 by 3 matrix (cyclic Jacobi).

    Return (values, vectors), where vectors[k] is the unit eigenvector of
    values[k].
    """
    a = [list(map(float, row)) for row in s]
    v = eye(3)
    for _ in range(50):
        off = a[0][1] ** 2 + a[0][2] ** 2 + a[1][2] ** 2
        if off <= 1e-30 * (sum(a[i][i] ** 2 for i in range(3)) + 1e-300):
            break
        for p, q in ((0, 1), (0, 2), (1, 2)):
            if a[p][q] == 0.0:
                continue
            theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
            t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
            c = 1.0 / math.sqrt(t * t + 1.0)
            sn = t * c
            for k in range(3):
                akp, akq = a[k][p], a[k][q]
                a[k][p] = c * akp - sn * akq
                a[k][q] = sn * akp + c * akq
            for k in range(3):
                apk, aqk = a[p][k], a[q][k]
                a[p][k] = c * apk - sn * aqk
                a[q][k] = sn * apk + c * aqk
            for k in range(3):
                vkp, vkq = v[k][p], v[k][q]
                v[k][p] = c * vkp - sn * vkq
                v[k][q] = sn * vkp + c * vkq
    values = [a[i][i] for i in range(3)]
    vectors = [tuple(v[k][i] for k in range(3)) for i in range(3)]
    return values, vectors


def polar(f, tol=1e-14, max_iter=100):
    """Return (R, S) with F = R S, det R = +1 and S symmetric.

    2 by 2: closed form. R = rot2(theta) with theta = atan2(f10 - f01, f00 + f11),
    the rotation that maximizes trace(R^T F), and S = R^T F.
    3 by 3: the Newton iteration X <- (X + X^(-T)) / 2 of Higham (1986), with
    the scaling gamma = (|X^(-1)|_F / |X|_F)^(1/2) while the relative change
    is above 1e-2. It stops when the relative change in the Frobenius norm is
    at most tol, or after max_iter steps. The iteration gives the orthogonal
    polar factor U. If det U < 0 (det F < 0), R = U (I - 2 v v^T) for the unit
    eigenvector v of the smallest eigenvalue of U^T F, so that det R = +1.
    If det F > 0, S is symmetric positive definite. If det F < 0, S is
    symmetric with one negative eigenvalue. Raise ValueError for a singular
    3 by 3 F.
    """
    n = len(f)
    if n == 2:
        theta = math.atan2(f[1][0] - f[0][1], f[0][0] + f[1][1])
        r = rot2(theta)
        s = mul(transpose(r), f)
        s01 = 0.5 * (s[0][1] + s[1][0])
        s[0][1] = s[1][0] = s01
        return r, s
    if n != 3:
        raise ValueError("polar supports 2 by 2 and 3 by 3 matrices")
    x = [list(map(float, row)) for row in f]
    change = float("inf")
    for _ in range(max_iter):
        xi = inv(x)
        if change > 1e-2:
            g = math.sqrt(_frob(xi) / _frob(x))
        else:
            g = 1.0
        xit = transpose(xi)
        y = [[0.5 * (g * x[i][j] + xit[i][j] / g) for j in range(3)] for i in range(3)]
        change = _frob([[y[i][j] - x[i][j] for j in range(3)] for i in range(3)]) / _frob(y)
        x = y
        if change <= tol:
            break
    u = x
    s = mul(transpose(u), f)
    s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    if det(u) < 0.0:
        values, vectors = _sym_eig3(s)
        k = min(range(3), key=lambda i: values[i])
        v = vectors[k]
        h = [[(1.0 if i == j else 0.0) - 2.0 * v[i] * v[j] for j in range(3)] for i in range(3)]
        u = mul(u, h)
        s = mul(h, s)
        s = [[0.5 * (s[i][j] + s[j][i]) for j in range(3)] for i in range(3)]
    return u, s


# ---------------------------------------------------------------- quaternions


def q_mul(p, q):
    """Return the Hamilton product p q."""
    a1, b1, c1, d1 = p
    a2, b2, c2, d2 = q
    return (
        a1 * a2 - b1 * b2 - c1 * c2 - d1 * d2,
        a1 * b2 + b1 * a2 + c1 * d2 - d1 * c2,
        a1 * c2 - b1 * d2 + c1 * a2 + d1 * b2,
        a1 * d2 + b1 * c2 - c1 * b2 + d1 * a2,
    )


def q_conj(q):
    """Return the conjugate (w, -x, -y, -z)."""
    return (q[0], -q[1], -q[2], -q[3])


def q_dot(p, q):
    """Return the dot product of p and q as vectors of R^4."""
    return p[0] * q[0] + p[1] * q[1] + p[2] * q[2] + p[3] * q[3]


def q_normalize(q):
    """Return q / |q|."""
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("cannot normalize the zero quaternion")
    return (q[0] / n, q[1] / n, q[2] / n, q[3] / n)


def q_from_axis_angle(axis, angle):
    """Return the unit quaternion of the rotation by angle about axis (any length)."""
    u = normalize(axis)
    s = math.sin(0.5 * angle)
    return (math.cos(0.5 * angle), s * u[0], s * u[1], s * u[2])


def q_to_mat3(q):
    """Return the 3 by 3 rotation matrix of a unit quaternion."""
    w, x, y, z = q
    return [
        [1 - 2 * (y * y + z * z), 2 * (x * y - w * z), 2 * (x * z + w * y)],
        [2 * (x * y + w * z), 1 - 2 * (x * x + z * z), 2 * (y * z - w * x)],
        [2 * (x * z - w * y), 2 * (y * z + w * x), 1 - 2 * (x * x + y * y)],
    ]


def q_rotate(q, v):
    """Return the vector part of q (0, v) q* for a unit quaternion q."""
    r = q_mul(q_mul(q, (0.0, v[0], v[1], v[2])), q_conj(q))
    return (r[1], r[2], r[3])


def q_log(q):
    """Return the log of a nonzero quaternion as a 4-tuple (ln|q|, phi u).

    For a unit quaternion (cos phi, sin phi u) this is (0, phi u), with
    phi = atan2(|v|, w) in [0, pi]. For a real q the vector part is zero.
    """
    n = math.sqrt(q_dot(q, q))
    if n == 0.0:
        raise ValueError("log of the zero quaternion")
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    lw = math.log(n)
    if vn == 0.0:
        return (lw, 0.0, 0.0, 0.0)
    phi = math.atan2(vn, q[0])
    f = phi / vn
    return (lw, f * q[1], f * q[2], f * q[3])


def q_exp(q):
    """Return exp(q) = e^w (cos|v|, sin|v| v / |v|) for q = (w, v)."""
    vn = math.sqrt(q[1] * q[1] + q[2] * q[2] + q[3] * q[3])
    ew = math.exp(q[0])
    if vn == 0.0:
        return (ew, 0.0, 0.0, 0.0)
    f = ew * math.sin(vn) / vn
    return (ew * math.cos(vn), f * q[1], f * q[2], f * q[3])


def slerp(q0, q1, t):
    """Spherical linear interpolation of unit quaternions on the short arc.

    If q0 . q1 < 0, q1 is replaced by -q1 (the same rotation). The angle W
    comes from atan2(|q1 - q0|, |q1 + q0|). Below SLERP_SMALL_ANGLE the
    normalized linear interpolation is returned. See
    robotics/rigid-body-motion/spherical-linear-interpolation.
    """
    if q_dot(q0, q1) < 0.0:
        q1 = (-q1[0], -q1[1], -q1[2], -q1[3])
    a = math.sqrt(sum((y - x) ** 2 for x, y in zip(q0, q1)))
    b = math.sqrt(sum((y + x) ** 2 for x, y in zip(q0, q1)))
    w = 2.0 * math.atan2(a, b)
    if w < SLERP_SMALL_ANGLE:
        return q_normalize(tuple((1 - t) * x + t * y for x, y in zip(q0, q1)))
    s = math.sin(w)
    c0 = math.sin((1 - t) * w) / s
    c1 = math.sin(t * w) / s
    return tuple(c0 * x + c1 * y for x, y in zip(q0, q1))


def q_from_mat3(r):
    """Return the unit quaternion, with w >= 0, of a 3 by 3 rotation matrix.

    Shepperd's method: take the largest of the trace, r00, r11 and r22, and
    divide by the component that it gives. See
    robotics/rigid-body-motion/shepperd-method.
    """
    t = r[0][0] + r[1][1] + r[2][2]
    k = max(range(4), key=lambda i: (t, r[0][0], r[1][1], r[2][2])[i])
    if k == 0:
        w = math.sqrt(1.0 + t) / 2.0
        f = 4.0 * w
        q = (w, (r[2][1] - r[1][2]) / f, (r[0][2] - r[2][0]) / f, (r[1][0] - r[0][1]) / f)
    elif k == 1:
        x = math.sqrt(max(0.0, 1.0 + 2.0 * r[0][0] - t)) / 2.0
        f = 4.0 * x
        q = ((r[2][1] - r[1][2]) / f, x, (r[1][0] + r[0][1]) / f, (r[0][2] + r[2][0]) / f)
    elif k == 2:
        y = math.sqrt(max(0.0, 1.0 + 2.0 * r[1][1] - t)) / 2.0
        f = 4.0 * y
        q = ((r[0][2] - r[2][0]) / f, (r[1][0] + r[0][1]) / f, y, (r[2][1] + r[1][2]) / f)
    else:
        z = math.sqrt(max(0.0, 1.0 + 2.0 * r[2][2] - t)) / 2.0
        f = 4.0 * z
        q = ((r[1][0] - r[0][1]) / f, (r[0][2] + r[2][0]) / f, (r[2][1] + r[1][2]) / f, z)
    if q[0] < 0.0:
        q = (-q[0], -q[1], -q[2], -q[3])
    return q


# ---------------------------------------------------------------- transforms


def make_T(r, t):
    """Return the homogeneous (d + 1) by (d + 1) matrix [[R, t], [0, 1]] for d = len(t)."""
    d = len(t)
    m = [[float(r[i][j]) for j in range(d)] + [float(t[i])] for i in range(d)]
    m.append([0.0] * d + [1.0])
    return m


def T_mul(a, b):
    """Return the product a b of two homogeneous transforms."""
    return mul(a, b)


def T_inv(m):
    """Return the inverse of an affine homogeneous transform [[A, t], [0, 1]].

    The result is [[A^(-1), -A^(-1) t], [0, 1]]; A may hold a scale.
    """
    d = len(m) - 1
    a = [row[:d] for row in m[:d]]
    t = [m[i][d] for i in range(d)]
    ai = inv(a)
    ti = matvec(ai, t)
    return make_T(ai, tuple(-x for x in ti))


def T_apply(m, p):
    """Apply a homogeneous transform to a point p and return a tuple."""
    d = len(m) - 1
    return tuple(sum(m[i][j] * p[j] for j in range(d)) + m[i][d] for i in range(d))


# ---------------------------------------------------------------- derivatives


def num_grad(f, x, h=1e-6):
    """Return the gradient of a scalar f at x by central differences of step h."""
    x = list(x)
    g = []
    for i in range(len(x)):
        xi = x[i]
        x[i] = xi + h
        fp = f(x)
        x[i] = xi - h
        fm = f(x)
        x[i] = xi
        g.append((fp - fm) / (2.0 * h))
    return g
style_based_inverse_kinematics.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/style-based-inverse-kinematics/. The authors are listed in prov/1FCH43.jsonl.
"""Style-based inverse kinematics (Grochow, Martin, Hertzmann and Popovic 2004).

A scaled Gaussian process latent variable model (SGPLVM) maps a latent
point x (dimension d) to a pose y (dimension D) with the kernel

    k(x, x') = alpha exp(-(gamma / 2) |x - x'|^2) + delta(x, x') / beta.

For the training latents X and poses Y (centered by their mean mu), the
model gives a mean and a variance at any x:

    f(x) = mu + Y^T K^(-1) k(x),   s2(x) = k(x, x) - k(x)^T K^(-1) k(x).

The inverse kinematics objective is the negative log likelihood of a pose,

    L_IK(x, y) = |W (y - f(x))|^2 / (2 s2(x)) + (D / 2) ln s2(x) + |x|^2 / 2,

plus a soft constraint (lam / 2) |g(y) - p|^2 on the end effector position
g(y). Both x and y are unknowns. The code minimizes the sum by BFGS with
a backtracking line search, using the analytic gradient. The paper uses
SQP and L-BFGS.

The latent points and the hyperparameters are inputs. The paper learns
them from the motion capture data by maximizing the likelihood of the
model; that step is not part of this file. The chain is a planar arm with
the joint angles y and the link lengths in LENGTHS.
"""

import math

from anim import dot, solve

LENGTHS = (1.0, 0.8, 0.6)


def kernel(a, b, alpha, gamma):
    """Return the RBF part alpha exp(-(gamma / 2) |a - b|^2)."""
    return alpha * math.exp(-0.5 * gamma * sum((x - y) ** 2 for x, y in zip(a, b)))


class SGPLVM:
    """A trained model: latents X, poses Y, hyperparameters and scaling W."""

    def __init__(self, latents, poses, alpha=1.0, gamma=1.0, beta=100.0, scale=None):
        self.x = [list(p) for p in latents]
        n, dim = len(poses), len(poses[0])
        self.mu = [sum(p[k] for p in poses) / n for k in range(dim)]
        self.y = [[p[k] - self.mu[k] for k in range(dim)] for p in poses]
        self.alpha, self.gamma, self.beta = alpha, gamma, beta
        self.w = list(scale) if scale is not None else [1.0] * dim
        kmat = [[kernel(a, b, alpha, gamma) + (1.0 / beta if i == j else 0.0) for j, b in enumerate(self.x)] for i, a in enumerate(self.x)]
        eye = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
        self.kinv = solve(kmat, eye)  # K^(-1), once
        self.kinv_y = [[sum(self.kinv[i][j] * self.y[j][k] for j in range(n)) for k in range(dim)] for i in range(n)]

    def predict(self, x):
        """Return (f, s2, df, ds2): the mean, the variance and their gradients in x."""
        n, dim, d = len(self.x), len(self.mu), len(x)
        kx = [kernel(x, xj, self.alpha, self.gamma) for xj in self.x]
        dk = [[-self.gamma * (x[c] - xj[c]) * kv for c in range(d)] for xj, kv in zip(self.x, kx)]
        f = [self.mu[k] + sum(self.kinv_y[j][k] * kx[j] for j in range(n)) for k in range(dim)]
        df = [[sum(self.kinv_y[j][k] * dk[j][c] for j in range(n)) for c in range(d)] for k in range(dim)]
        a = [sum(self.kinv[i][j] * kx[j] for j in range(n)) for i in range(n)]
        s2 = self.alpha + 1.0 / self.beta - dot(kx, a)
        ds2 = [-2.0 * sum(a[j] * dk[j][c] for j in range(n)) for c in range(d)]
        return f, s2, df, ds2


def end_effector(y):
    """Return the end position of the planar chain and its Jacobian (2 by D)."""
    th = 0.0
    px = py = 0.0
    pts = []
    for ang, ln in zip(y, LENGTHS):
        th += ang
        px += ln * math.cos(th)
        py += ln * math.sin(th)
        pts.append((th, ln))
    jac = [[0.0] * len(y) for _ in range(2)]
    for i in range(len(y)):
        for th_k, ln in pts[i:]:
            jac[0][i] -= ln * math.sin(th_k)
            jac[1][i] += ln * math.cos(th_k)
    return (px, py), jac


def objective(model, z, target, lam):
    """Return (E, gradient) for z = (x, y) with the soft constraint of weight lam."""
    d = len(model.x[0])
    x, y = z[:d], z[d:]
    dim = len(y)
    f, s2, df, ds2 = model.predict(x)
    r = [model.w[k] * (y[k] - f[k]) for k in range(dim)]
    rr = dot(r, r)
    e = rr / (2.0 * s2) + 0.5 * dim * math.log(s2) + 0.5 * dot(x, x)  # @line L4
    gx = [0.0] * d
    gy = [model.w[k] * r[k] / s2 for k in range(dim)]
    for c in range(d):
        gx[c] = -sum(model.w[k] * r[k] * df[k][c] for k in range(dim)) / s2
        gx[c] += (-rr / (2.0 * s2 * s2) + 0.5 * dim / s2) * ds2[c] + x[c]
    if lam:
        p, jac = end_effector(y)  # @line L5
        res = (p[0] - target[0], p[1] - target[1])
        e += 0.5 * lam * dot(res, res)
        for k in range(dim):
            gy[k] += lam * (jac[0][k] * res[0] + jac[1][k] * res[1])
    return e, gx + gy


def style_ik(model, target, x0, y0=None, lam=1e3, max_iter=500, gtol=1e-9):
    """Return (x, y, history) minimizing L_IK(x, y) + (lam / 2) |g(y) - target|^2.

    The start is x0 and y0 = f(x0) if y0 is None. The minimizer is BFGS
    with a backtracking (Armijo) line search; history holds E after each
    accepted step. With lam = 0 there is no constraint and target is unused.
    """
    d = len(x0)
    if y0 is None:
        y0 = model.predict(list(x0))[0]
    z = list(x0) + list(y0)  # @line L1
    nz = len(z)
    h = [[1.0 if i == j else 0.0 for j in range(nz)] for i in range(nz)]  # inverse Hessian estimate
    e, g = objective(model, z, target, lam)  # @line L2
    history = [e]
    for _ in range(max_iter):  # @line L3
        if math.sqrt(dot(g, g)) <= gtol:  # @line L8
            break
        p = [-sum(h[i][j] * g[j] for j in range(nz)) for i in range(nz)]  # @line L6
        slope = dot(p, g)
        if slope >= 0.0:
            h = [[1.0 if i == j else 0.0 for j in range(nz)] for i in range(nz)]
            p = [-x for x in g]
            slope = -dot(g, g)
        step = 1.0
        while True:
            z2 = [a + step * b for a, b in zip(z, p)]
            e2, g2 = objective(model, z2, target, lam)
            if e2 <= e + 1e-4 * step * slope:
                break
            step *= 0.5
            if step < 1e-16:
                return z[:d], z[d:], history
        s = [a - b for a, b in zip(z2, z)]
        yv = [a - b for a, b in zip(g2, g)]
        sy = dot(s, yv)
        if sy > 1e-14 * math.sqrt(dot(s, s) * dot(yv, yv)):  # BFGS update of the inverse Hessian
            hy = [sum(h[i][j] * yv[j] for j in range(nz)) for i in range(nz)]
            yhy = dot(yv, hy)
            for i in range(nz):
                for j in range(nz):
                    h[i][j] += (sy + yhy) * s[i] * s[j] / (sy * sy) - (hy[i] * s[j] + s[i] * hy[j]) / sy
        z, e, g = z2, e2, g2  # @line L7
        history.append(e)
        if max(abs(x) for x in s) <= 1e-13 * (1.0 + max(abs(x) for x in z)):
            break  # the steps are below the rounding level of z
    return z[:d], z[d:], history  # @line L9
test_style_based_inverse_kinematics.py 110 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/style-based-inverse-kinematics/. The authors are listed in prov/1FCH43.jsonl.
"""Tests of style-based inverse kinematics.

The analytic gradient is compared with central differences. The Gaussian
process reproduces the training poses with a small variance. The objective
decreases at every step. Without a constraint, the result is the mean pose
f(x) at the latent point that minimizes (D / 2) ln s2(x) + |x|^2 / 2, which
is checked against a grid search. With a constraint, a larger weight brings
the end effector closer, and a target reached by a training pose gives that
pose back, although other poses of the redundant chain reach it too. The
check values of the page hold.
"""

import math
import random

from anim import num_grad
from style_based_inverse_kinematics import SGPLVM, end_effector, objective, style_ik

S = [-1.0 + 0.25 * i for i in range(9)]
POSES = [(0.2 + 0.8 * s, 0.5 - 0.3 * s + 0.2 * s * s, 0.9 * s) for s in S]
MODEL = SGPLVM([[s] for s in S], POSES, alpha=1.0, gamma=2.0, beta=1e3)


def test_gradient_against_central_differences():
    rng = random.Random(7)
    target = (1.2, 1.5)
    for _ in range(10):
        x = [rng.uniform(-1.2, 1.2)]
        z = x + [a + rng.uniform(-0.1, 0.1) for a in MODEL.predict(x)[0]]
        for lam in (0.0, 50.0):
            _, g = objective(MODEL, z, target, lam)
            ng = num_grad(lambda q: objective(MODEL, q, target, lam)[0], z, h=1e-5)
            scale = 1.0 + max(abs(v) for v in g)
            assert max(abs(a - b) for a, b in zip(g, ng)) < 1e-5 * scale


def test_gaussian_process_reproduces_the_training_poses():
    for s, y in zip(S, POSES):
        f, s2, _, _ = MODEL.predict([s])
        assert max(abs(a - b) for a, b in zip(f, y)) < 0.01
        assert s2 < 0.003
    _, far, _, _ = MODEL.predict([6.0])
    assert abs(far - (1.0 + 1e-3)) < 1e-9


def test_objective_decreases_and_gradient_vanishes():
    target = (1.4, 1.7)
    _, _, hist = style_ik(MODEL, target, [0.0])
    assert all(hist[i + 1] <= hist[i] for i in range(len(hist) - 1))
    x, y, _ = style_ik(MODEL, target, [0.0])
    e, g = objective(MODEL, x + y, target, 1e3)
    assert math.sqrt(sum(v * v for v in g)) < 1e-3
    assert len(hist) < 100


def test_without_constraints_against_a_grid():
    latents = [[-1.0], [-0.7], [-0.5], [-0.2], [0.1], [0.5], [0.6], [1.0]]
    poses = [POSES[i] for i in (0, 1, 2, 3, 4, 6, 7, 8)]
    model = SGPLVM(latents, poses, alpha=1.0, gamma=2.0, beta=1e3)

    def reduced(x):
        return 1.5 * math.log(model.predict([x])[1]) + 0.5 * x * x

    best = min((reduced(-1.5 + 1e-3 * i), -1.5 + 1e-3 * i) for i in range(3001))
    x, y, _ = style_ik(model, None, [best[1] + 0.05], lam=0.0)
    f = model.predict(x)[0]
    assert max(abs(a - b) for a, b in zip(y, f)) < 1e-7
    assert reduced(x[0]) <= best[0] + 1e-9
    assert abs(x[0] - best[1]) < 2e-3


def test_larger_weight_brings_the_end_effector_closer():
    target = (1.45, 1.6)
    errs = []
    for lam in (10.0, 1e3, 1e5):
        _, y, _ = style_ik(MODEL, target, [0.0], lam=lam)
        p = end_effector(y)[0]
        errs.append(math.hypot(p[0] - target[0], p[1] - target[1]))
    assert errs[0] > errs[1] > errs[2]
    assert errs[2] < 1e-3


def test_target_of_a_training_pose_gives_that_pose():
    target = end_effector(POSES[6])[0]
    # the start is the latent point of the neighbor POSES[5]; the objective has other local minima
    _, y, _ = style_ik(MODEL, target, [S[5]], lam=1e5)
    assert max(abs(a - b) for a, b in zip(y, POSES[6])) < 0.01
    # plain inverse kinematics (minimum norm Newton steps from the pose POSES[0]) reaches the same target with another pose
    q = list(POSES[0])
    for _ in range(50):
        p, jac = end_effector(q)
        r = (p[0] - target[0], p[1] - target[1])
        a = [[sum(jac[i][k] * jac[j][k] for k in range(3)) for j in range(2)] for i in range(2)]
        det = a[0][0] * a[1][1] - a[0][1] * a[1][0]
        mu = ((a[1][1] * r[0] - a[0][1] * r[1]) / det, (a[0][0] * r[1] - a[1][0] * r[0]) / det)
        q = [q[k] - jac[0][k] * mu[0] - jac[1][k] * mu[1] for k in range(3)]
    p = end_effector(q)[0]
    assert math.hypot(p[0] - target[0], p[1] - target[1]) < 1e-10
    assert max(abs(a - b) for a, b in zip(q, POSES[6])) > 0.1


def test_check_values_of_the_page():
    model = SGPLVM([[-1.0], [1.0]], [(0.0, 0.0, 0.0), (1.0, 2.0, 3.0)], alpha=1.0, gamma=1.0, beta=100.0)
    f, s2, _, _ = model.predict([0.0])
    assert max(abs(a - b) for a, b in zip(f, (0.5, 1.0, 1.5))) < 1e-12
    want = 1.01 - 2.0 * math.exp(-1.0) / (1.01 + math.exp(-2.0))
    assert abs(s2 - want) < 1e-12
    assert abs(s2 - 0.3676) < 1e-4

History

Inverse kinematics for characters used hand made costs for a long time, such as joint limits and the distance to a rest pose. Lawrence introduced the Gaussian process latent variable model in 2003 and 2004 as a nonlinear form of probabilistic PCA. Grochow, Martin, Hertzmann and Popović (2004) scaled it to poses, learned a model per style from motion capture, and used its likelihood as the cost of inverse kinematics, with an interactive solver. Later work used Gaussian process models with dynamics for tracking people in video and for animation.

References

  1. Keith Grochow, Steven L. Martin, Aaron Hertzmann and Zoran Popović, Style-based inverse kinematics, ACM Transactions on Graphics 23(3), SIGGRAPH 2004, pages 522 to 531, the SGPLVM kernel with its predictive mean and variance, the objective L_IK in equation (3), and the optimization with SQP and L-BFGS in Section 6.2

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.query
  • a full proof of time.training
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • History with a source
  • at least three sources
  • a scene preset for the example