Coverage for ase/quaternions.py: 84.25%

127 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1import numpy as np 

2 

3 

4class Quaternion: 

5 def __init__(self, qin=None): 

6 if qin is None: 

7 qin = [1, 0, 0, 0] 

8 assert len(qin) == 4 

9 self.q = np.array(qin) 

10 

11 def __str__(self): 

12 return self.q.__str__() 

13 

14 def __mul__(self, other): 

15 sw, sx, sy, sz = self.q 

16 ow, ox, oy, oz = other.q 

17 return Quaternion( 

18 [ 

19 sw * ow - sx * ox - sy * oy - sz * oz, 

20 sw * ox + sx * ow + sy * oz - sz * oy, 

21 sw * oy + sy * ow + sz * ox - sx * oz, 

22 sw * oz + sz * ow + sx * oy - sy * ox, 

23 ] 

24 ) 

25 

26 def conjugate(self): 

27 return Quaternion(-self.q * np.array([-1.0, 1.0, 1.0, 1.0])) 

28 

29 def rotate(self, vector): 

30 """Apply the rotation matrix to a vector.""" 

31 qw, qx, qy, qz = self.q[0], self.q[1], self.q[2], self.q[3] 

32 x, y, z = vector[0], vector[1], vector[2] 

33 

34 ww = qw * qw 

35 xx = qx * qx 

36 yy = qy * qy 

37 zz = qz * qz 

38 wx = qw * qx 

39 wy = qw * qy 

40 wz = qw * qz 

41 xy = qx * qy 

42 xz = qx * qz 

43 yz = qy * qz 

44 

45 return np.array( 

46 [ 

47 (ww + xx - yy - zz) * x + 2 * ((xy - wz) * y + (xz + wy) * z), 

48 (ww - xx + yy - zz) * y + 2 * ((xy + wz) * x + (yz - wx) * z), 

49 (ww - xx - yy + zz) * z + 2 * ((xz - wy) * x + (yz + wx) * y), 

50 ] 

51 ) 

52 

53 def rotation_matrix(self): 

54 

55 qw, qx, qy, qz = self.q[0], self.q[1], self.q[2], self.q[3] 

56 

57 ww = qw * qw 

58 xx = qx * qx 

59 yy = qy * qy 

60 zz = qz * qz 

61 wx = qw * qx 

62 wy = qw * qy 

63 wz = qw * qz 

64 xy = qx * qy 

65 xz = qx * qz 

66 yz = qy * qz 

67 

68 return np.array( 

69 [ 

70 [ww + xx - yy - zz, 2 * (xy - wz), 2 * (xz + wy)], 

71 [2 * (xy + wz), ww - xx + yy - zz, 2 * (yz - wx)], 

72 [2 * (xz - wy), 2 * (yz + wx), ww - xx - yy + zz], 

73 ] 

74 ) 

75 

76 def axis_angle(self): 

77 """Returns axis and angle (in radians) for the rotation described 

78 by this Quaternion""" 

79 

80 sinth_2 = np.linalg.norm(self.q[1:]) 

81 

82 if sinth_2 == 0: 

83 # The angle is zero 

84 theta = 0.0 

85 n = np.array([0, 0, 1]) 

86 else: 

87 theta = np.arctan2(sinth_2, self.q[0]) * 2 

88 n = self.q[1:] / sinth_2 

89 

90 return n, theta 

91 

92 def euler_angles(self, mode='zyz'): 

93 """Return three Euler angles describing the rotation, in radians. 

94 Mode can be zyz or zxz. Default is zyz.""" 

95 # https://journals.plos.org/plosone/article?id=10.1371/journal.pone.0276302 

96 if mode == 'zyz': 

97 a, b, c, d = self.q[0], self.q[3], self.q[2], -self.q[1] 

98 elif mode == 'zxz': 

99 a, b, c, d = self.q[0], self.q[3], self.q[1], self.q[2] 

100 else: 

101 raise ValueError(f'Invalid Euler angles mode {mode}') 

102 

103 beta = 2 * np.arccos( 

104 np.sqrt((a**2 + b**2) / (a**2 + b**2 + c**2 + d**2)) 

105 ) 

106 gap = np.arctan2(b, a) # (gamma + alpha) / 2 

107 gam = np.arctan2(d, c) # (gamma - alpha) / 2 

108 if np.isclose(beta, 0): 

109 # gam is meaningless here 

110 alpha = 0 

111 gamma = 2 * gap - alpha 

112 elif np.isclose(beta, np.pi): 

113 # gap is meaningless here 

114 alpha = 0 

115 gamma = 2 * gam + alpha 

116 else: 

117 alpha = gap - gam 

118 gamma = gap + gam 

119 

120 return np.array([alpha, beta, gamma]) 

121 

122 def arc_distance(self, other): 

123 """Gives a metric of the distance between two quaternions, 

124 expressed as 1-|q1.q2|""" 

125 

126 return 1.0 - np.abs(np.dot(self.q, other.q)) 

127 

128 @staticmethod 

129 def rotate_byq(q, vector): 

130 """Apply the rotation matrix to a vector.""" 

131 qw, qx, qy, qz = q[0], q[1], q[2], q[3] 

132 x, y, z = vector[0], vector[1], vector[2] 

133 

134 ww = qw * qw 

135 xx = qx * qx 

136 yy = qy * qy 

137 zz = qz * qz 

138 wx = qw * qx 

139 wy = qw * qy 

140 wz = qw * qz 

141 xy = qx * qy 

142 xz = qx * qz 

143 yz = qy * qz 

144 

145 return np.array( 

146 [ 

147 (ww + xx - yy - zz) * x + 2 * ((xy - wz) * y + (xz + wy) * z), 

148 (ww - xx + yy - zz) * y + 2 * ((xy + wz) * x + (yz - wx) * z), 

149 (ww - xx - yy + zz) * z + 2 * ((xz - wy) * x + (yz + wx) * y), 

150 ] 

151 ) 

152 

153 @staticmethod 

154 def from_matrix(matrix): 

155 """Build quaternion from rotation matrix.""" 

156 m = np.array(matrix) 

157 assert m.shape == (3, 3) 

158 

159 # Now we need to find out the whole quaternion 

160 # This method takes into account the possibility of qw being nearly 

161 # zero, so it picks the stablest solution 

162 

163 if m[2, 2] < 0: 

164 if m[0, 0] > m[1, 1]: 

165 # Use x-form 

166 qx = np.sqrt(1 + m[0, 0] - m[1, 1] - m[2, 2]) / 2.0 

167 fac = 1.0 / (4 * qx) 

168 qw = (m[2, 1] - m[1, 2]) * fac 

169 qy = (m[0, 1] + m[1, 0]) * fac 

170 qz = (m[0, 2] + m[2, 0]) * fac 

171 else: 

172 # Use y-form 

173 qy = np.sqrt(1 - m[0, 0] + m[1, 1] - m[2, 2]) / 2.0 

174 fac = 1.0 / (4 * qy) 

175 qw = (m[0, 2] - m[2, 0]) * fac 

176 qx = (m[0, 1] + m[1, 0]) * fac 

177 qz = (m[1, 2] + m[2, 1]) * fac 

178 else: 

179 if m[0, 0] < -m[1, 1]: 

180 # Use z-form 

181 qz = np.sqrt(1 - m[0, 0] - m[1, 1] + m[2, 2]) / 2.0 

182 fac = 1.0 / (4 * qz) 

183 qw = (m[1, 0] - m[0, 1]) * fac 

184 qx = (m[2, 0] + m[0, 2]) * fac 

185 qy = (m[1, 2] + m[2, 1]) * fac 

186 else: 

187 # Use w-form 

188 qw = np.sqrt(1 + m[0, 0] + m[1, 1] + m[2, 2]) / 2.0 

189 fac = 1.0 / (4 * qw) 

190 qx = (m[2, 1] - m[1, 2]) * fac 

191 qy = (m[0, 2] - m[2, 0]) * fac 

192 qz = (m[1, 0] - m[0, 1]) * fac 

193 

194 return Quaternion(np.array([qw, qx, qy, qz])) 

195 

196 @staticmethod 

197 def from_axis_angle(n, theta): 

198 """Build quaternion from axis (n, vector of 3 components) and angle 

199 (theta, in radianses).""" 

200 

201 n = np.array(n, float) / np.linalg.norm(n) 

202 return Quaternion( 

203 np.concatenate([[np.cos(theta / 2.0)], np.sin(theta / 2.0) * n]) 

204 ) 

205 

206 @staticmethod 

207 def from_euler_angles(a, b, c, mode='zyz'): 

208 """Build quaternion from Euler angles, given in radians. Default 

209 mode is ZYZ, but it can be set to ZXZ as well.""" 

210 

211 q_a = Quaternion.from_axis_angle([0, 0, 1], a) 

212 q_c = Quaternion.from_axis_angle([0, 0, 1], c) 

213 

214 if mode == 'zyz': 

215 q_b = Quaternion.from_axis_angle([0, 1, 0], b) 

216 elif mode == 'zxz': 

217 q_b = Quaternion.from_axis_angle([1, 0, 0], b) 

218 else: 

219 raise ValueError(f'Invalid Euler angles mode {mode}') 

220 

221 return q_c * q_b * q_a