quaternion.py 1.0 KB

1234567891011121314151617181920212223242526272829303132333435
  1. # Copyright (c) 2018-present, Facebook, Inc.
  2. # All rights reserved.
  3. #
  4. # This source code is licensed under the license found in the
  5. # LICENSE file in the root directory of this source tree.
  6. #
  7. import torch
  8. def qrot(q, v):
  9. """
  10. Rotate vector(s) v about the rotation described by quaternion(s) q.
  11. Expects a tensor of shape (*, 4) for q and a tensor of shape (*, 3) for v,
  12. where * denotes any number of dimensions.
  13. Returns a tensor of shape (*, 3).
  14. """
  15. assert q.shape[-1] == 4
  16. assert v.shape[-1] == 3
  17. assert q.shape[:-1] == v.shape[:-1]
  18. qvec = q[..., 1:]
  19. uv = torch.cross(qvec, v, dim=len(q.shape)-1)
  20. uuv = torch.cross(qvec, uv, dim=len(q.shape)-1)
  21. return (v + 2 * (q[..., :1] * uv + uuv))
  22. def qinverse(q, inplace=False):
  23. # We assume the quaternion to be normalized
  24. if inplace:
  25. q[..., 1:] *= -1
  26. return q
  27. else:
  28. w = q[..., :1]
  29. xyz = q[..., 1:]
  30. return torch.cat((w, -xyz), dim=len(q.shape)-1)