TITLE: Derivative of quaternions
QUESTION [6 upvotes]: I am trying to calculate the Jacobian of a function that has quaternions and 3D points in it. I refer to quaternions as $q$ and 3D points as $p$
$$h_1(q)=A C(q)p $$
$$h_2(q)=q_1\otimes q \otimes q_2 $$
where $A\in R^{3x3}$ and $C(q)$ is Direction cosine matrix.
I am using the Hamilton form for the quaternions.
I would like to calculate the following Jacobians:
$$H_1 = \frac{\partial h_1(q)}{\partial q} $$
$$H_2 = \frac{\partial h_2(q)}{\partial q} $$
Following Joan Solà's reference eq. 18 what I have is 
$$H_1 = A^TC(q)^T[p]_x $$
$$H_2 = [q_1]_L[q_2]_R $$
Where $[q]_R$ and $[q]_L$ are the right and left handed conversion of quaternion to matrix form as defined in Joan Solà's reference eq. 18.
All rotations are body centric.
Is this correct? 
Is there a better way to do this? 
Can the expression be easily simplified?

REPLY [8 votes]: There are different ways to answer your question, but you probably want one of these two: 

You want the derivative with respect to the 4 components of the quaternion q=w+ix+iy+iz, that is, with respect to a 4 vector $v_q=(w,x,y,z)^\top\in R^4$. 
We have the derivative of the rotation wrt this vector q as:
$$
\frac{\partial q\otimes p \otimes q^*}{\partial v_q} = 2[wp+v×p , v^\top p I + vp^\top−pv^\top−w[p]_\times] \in R^{3\times4}
$$
where:

$I$ is the 3x3 identity matrix.
$[p]_\times$ is the skew symmetric matrix fromed from $p$.
$\times$ is the cross product
$\otimes$ is the quaternion product. This sign can be omitted since it's a product and write simply $qpq^*$.

So assuming A is a constant matrix, and knowing that $C(q)p = qpq^*$, your derivative is
$$
\frac{\partial (AC(q)p)}{\partial v_q} = 2A[wp+v×p , v^\top p I + vp^\top−pv^\top−w[p]_\times] \in R^{3\times4}
$$
This is the derivative that e.g. Ceres is going to compute should you use automatic differentiation of your function using #include Jet.h.
You want the derivative with respect to the rotation itself seen as a 3-vector of the Lie algebra of the rotation group. The Lie-theory defines two Jacobians, left and right, for this, depending on whether you perturb the rotation on the right, $\tilde R=R\exp([\theta]_\times)$, or on the left, $\tilde R=\exp([\theta]_\times)R$. 
The right Jacobian of the rotation is:
$$
\frac{\partial C(q)p}{\partial C} = -C(q)[p]_\times \in R^{3\times 3}
$$
and so your full Jacobian is
$$
\frac{\partial (AC(q)p)}{\partial C} = -AC(q)[p]_\times \in R^{3\times 3}
$$
The left Jacobian of the rotation is
$$
\frac{\partial C(q)p}{\partial C} = -[C(q)p]_\times \in R^{3\times 3}
$$
and so your full Jacobian is
$$
\frac{\partial (AC(q)p)}{\partial C} = -A[C(q)p]_\times \in R^{3\times 3}
$$