Last active
January 29, 2022 02:11
-
-
Save Alex7Li/f9eed631c76febc161f6eb042ed71993 to your computer and use it in GitHub Desktop.
Rotate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
import numpy as np | |
def get_rotating_transform(u, v): | |
""" | |
Given two unit vectors u, v, | |
we compute the rotation R such that v = R @ u | |
""" | |
assert np.isclose(np.linalg.norm(u), 1) | |
assert np.isclose(np.linalg.norm(v), 1) | |
n = np.cross(u, v) | |
while np.allclose(n, 0): # u and v are on the same line -.- | |
rand_dir = np.random.randn(3) | |
n = np.cross(u, rand_dir) | |
n /= np.linalg.norm(n) | |
t = np.cross(n, u) | |
T = np.stack([u, t, n], axis=1) | |
alpha = math.atan2(v @ t, v @ u) | |
R = np.array([ | |
[math.cos(alpha), -math.sin(alpha), 0], | |
[math.sin(alpha), math.cos(alpha), 0], | |
[0, 0, 1] | |
]) | |
transform = T @ R @ T.T | |
assert np.allclose(v, transform @ u) | |
return transform |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment