Author: bugman Date: Thu May 28 15:57:48 2009 New Revision: 9063 URL: http://svn.gna.org/viewcvs/relax?rev=9063&view=rev Log: Wrote 2 new functions, R_random_hypersphere() and quaternion_to_R(). Modified: 1.3/maths_fns/rotation_matrix.py Modified: 1.3/maths_fns/rotation_matrix.py URL: http://svn.gna.org/viewcvs/relax/1.3/maths_fns/rotation_matrix.py?rev=9063&r1=9062&r2=9063&view=diff ============================================================================== --- 1.3/maths_fns/rotation_matrix.py (original) +++ 1.3/maths_fns/rotation_matrix.py Thu May 28 15:57:48 2009 @@ -22,9 +22,45 @@ # Python module imports. from math import acos, cos, pi, sin -from numpy import cross, dot +from numpy import array, cross, dot, float64 from numpy.linalg import norm -from random import uniform +from random import gauss, uniform + + +def quaternion_to_R(quat, matrix): + """Convert a quaternion into rotation matrix form. + + @param quat: The quaternion. + @type quat: numpy 4D, rank-1 array + @param matrix: A 3D matrix to convert to a rotation matrix. + @type matrix: numpy 3D, rank-2 array + """ + + # Repetitive calculations. + q4_2 = quat[3]**2 + q12 = quat[0] * quat[1] + q13 = quat[0] * quat[2] + q14 = quat[0] * quat[3] + q23 = quat[1] * quat[2] + q24 = quat[1] * quat[3] + q34 = quat[2] * quat[3] + + # The diagonal. + matrix[0, 0] = (quat[0]**2 + q4_2) - 0.5 + matrix[1, 1] = (quat[1]**2 + q4_2) - 0.5 + matrix[2, 2] = (quat[2]**2 + q4_2) - 0.5 + + # Off-diagonal. + matrix[0, 1] = q12 - q34 + matrix[0, 2] = q13 + q24 + matrix[1, 2] = q23 - q14 + + matrix[1, 0] = q12 + q34 + matrix[2, 0] = q13 - q24 + matrix[2, 1] = q23 + q14 + + # Double. + matrix = 2.0 * matrix def R_2vect(R, vector_orig, vector_fin): @@ -209,6 +245,11 @@ Uniform point sampling on a unit sphere is used to generate a random axis orientation. This, together with the fixed rotation angle, is used to generate the random rotation matrix. + + @param matrix: A 3D matrix to convert to a rotation matrix. + @type matrix: numpy 3D, rank-2 array + @keyword angle: The fixed rotation angle. + @type angle: float """ # Random rotation axis. @@ -217,6 +258,24 @@ # Generate the rotation matrix. R_axis_angle(matrix, rot_axis, angle) + + +def R_random_hypersphere(matrix): + """Generate a random rotation matrix using 4D hypersphere point picking. + + A quaternion is generated by creating a 4D vector with each value randomly selected from a + Gaussian distribution, and then normalising. + + @param matrix: A 3D matrix to convert to a rotation matrix. + @type matrix: numpy 3D, rank-2 array + """ + + # The quaternion. + quat = array([gauss(0, 1), gauss(0, 1), gauss(0, 1), gauss(0, 1)], float64) + quat = quat / norm(quat) + + # Convert the quaternion to a rotation matrix. + quaternion_to_R(quat, matrix) def random_rot_axis(axis):