in gym_hil/controllers/opspace.py [0:0]
def mat_to_quat(mat: np.ndarray) -> np.ndarray:
"""Convert a 3x3 rotation matrix to a quaternion.
Args:
mat: 3x3 rotation matrix
Returns:
Quaternion as [w, x, y, z]
"""
trace = np.trace(mat)
if trace > 0:
s = 2.0 * np.sqrt(trace + 1.0)
w = 0.25 * s
x = (mat[2, 1] - mat[1, 2]) / s
y = (mat[0, 2] - mat[2, 0]) / s
z = (mat[1, 0] - mat[0, 1]) / s
elif mat[0, 0] > mat[1, 1] and mat[0, 0] > mat[2, 2]:
s = 2.0 * np.sqrt(1.0 + mat[0, 0] - mat[1, 1] - mat[2, 2])
w = (mat[2, 1] - mat[1, 2]) / s
x = 0.25 * s
y = (mat[0, 1] + mat[1, 0]) / s
z = (mat[0, 2] + mat[2, 0]) / s
elif mat[1, 1] > mat[2, 2]:
s = 2.0 * np.sqrt(1.0 + mat[1, 1] - mat[0, 0] - mat[2, 2])
w = (mat[0, 2] - mat[2, 0]) / s
x = (mat[0, 1] + mat[1, 0]) / s
y = 0.25 * s
z = (mat[1, 2] + mat[2, 1]) / s
else:
s = 2.0 * np.sqrt(1.0 + mat[2, 2] - mat[0, 0] - mat[1, 1])
w = (mat[1, 0] - mat[0, 1]) / s
x = (mat[0, 2] + mat[2, 0]) / s
y = (mat[1, 2] + mat[2, 1]) / s
z = 0.25 * s
return np.array([w, x, y, z])