# [Numpy-discussion] Faster way to generate a rotation matrix?

Charles R Harris charlesr.harris@gmail....
Wed Mar 4 03:07:40 CST 2009

On Wed, Mar 4, 2009 at 1:27 AM, Robert Cimrman <cimrman3@ntc.zcu.cz> wrote:

> Jonathan Taylor wrote:
> > Sorry.. obviously having some copy and paste trouble here.  The
> > message should be as follows:
> >
> > Hi,
> >
> > I am doing optimization on a vector of rotation angles tx,ty and tz
> > using scipy.optimize.fmin.  Unfortunately the function that I am
> > optimizing needs the rotation matrix corresponding to this vector so
> > it is getting constructed once for each iteration with new values.
> >> >From profiling I can see that the function I am using to construct
> > this rotation matrix is a bottleneck.  I am currently using:
> >
> > def rotation(theta):
> >    tx,ty,tz = theta
> >
> >    Rx = np.array([[1,0,0], [0, cos(tx), -sin(tx)], [0, sin(tx),
> cos(tx)]])
> >    Ry = np.array([[cos(ty), 0, -sin(ty)], [0, 1, 0], [sin(ty), 0,
> cos(ty)]])
> >    Rz = np.array([[cos(tz), -sin(tz), 0], [sin(tz), cos(tz), 0],
> [0,0,1]])
> >
> >    return np.dot(Rx, np.dot(Ry, Rz))
> >
> > Is there a faster way to do this?  Perhaps I can do this faster with a
> > small cython module, but this might be overkill?
> >
> > Thanks for any help,
> > Jonathan.
>
> An alternative to specifying the rotation by the three angles tx,ty and
> tz could be creating directly the rotation matrix given an axis and an
> angle:
>
> def make_axis_rotation_matrix(direction, angle):
>     """
>     Create a rotation matrix corresponding to the rotation around a general
>     axis by a specified angle.
>
>     R = dd^T + cos(a) (I - dd^T) + sin(a) skew(d)
>
>     Parameters:
>
>         angle : float a
>         direction : array d
>     """
>     d = np.array(direction, dtype=np.float64)
>     d /= np.linalg.norm(d)
>
>     eye = np.eye(3, dtype=np.float64)
>     ddt = np.outer(d, d)
>     skew = np.array([[    0,  d[2],  -d[1]],
>                      [-d[2],     0,  d[0]],
>                      [d[1], -d[0],    0]], dtype=np.float64)
>
>     mtx = ddt + np.cos(angle) * (eye - ddt) + np.sin(angle) * skew
>     return mtx
>

It might be worth looking at the function in the original problem to see if
it can be cast to a different form. Multiplication by a 3d skew matrix can
also be represented as a cross product. BTW, the formula above is the matrix
exponential of a skew matrix and rotations in higher dimensions can be
represented that way also.

Chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://projects.scipy.org/pipermail/numpy-discussion/attachments/20090304/14ae05d4/attachment.html