Vector, matrix, normalize, rotate. What package?

James Stroud jstroud at mbi.ucla.edu
Tue Feb 27 19:39:03 EST 2007


Mattias Brändström wrote:
> Hello!
> 
> I'm trying to find what package I should use if I want to:
> 
> 1. Create 3d vectors.
> 2. Normalize those vectors.
> 3. Create a 3x3 rotation matrix from a unit 3-d vector and an angle in
> radians.
> 4. Perform matrix multiplication.
> 
> It seems to me that perhaps numpy should be able to help me with this.
> However, I can only figure out how to do 1 and 4 using numpy. Meybe
> someone knows a way to use numpy for 2 and 3? If not, what Python
> package helps me with geometry related tasks such as 2 and 3?
> 
> Any help here would be greatly appreciated!
> 
> Regards,
> Mattias
> 

As Paul is hinting, your best bet is to make use of quaternions, you 
will save yourself a lot of frustration as soon as you need to do 
anything with them outside of matrix-multiplying a bunch of 3D 
coordinates. See the Scientific Python module: 
Scientific.Geometry.Quaternion. To make a matrix from Quaternion, q, use 
"q.asRotations().tensor".

To make a quaternion from an axis and an angle, here is what I use:

#######################################################################
# axis_angle_to_quaternion()
#######################################################################
def axis_angle_to_quaternion(axis, angle):
   """
   Takes an I{axis} (3x1 array) and an I{angle} (in degrees) and
   returns the rotation as a
   I{Scientific.Geometry.Quaternion.Quaternion}.

   @param axis: 3x1 array specifiying an axis
   @type  axis: numarray.array
   @param angle: C{float} specifying the rotation around I{axis}
   @type angle: float
   @return: a I{Quaternion} from an I{axis} and an I{angle}
   @rtype: Quaternion
   """
   axis = normalize(axis)

   angle = math.radians(float(angle))
   qx = float(axis[0])
   qy = float(axis[1])
   qz = float(axis[2])
   sin_a = math.sin(angle / 2.0)
   cos_a = math.cos(angle / 2.0)
   qx = qx * sin_a
   qy = qy * sin_a
   qz = qz * sin_a
   qw = cos_a

   return Quaternion(qw, qx, qy, qz).normalized()


See your linear algebra text on how to normalize a 1x3 vector.

James



More information about the Python-list mailing list