Guest User

Untitled

a guest
Jun 21st, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. # Standard Library
  2. from math import pi as M_PI
  3. from math import cos, sin
  4.  
  5. class Quaternion(object):
  6. @classmethod
  7. def from_rpy(cls, r, p, y):
  8. cr = cos(r * 0.5)
  9. sr = sin(r * 0.5)
  10. cp = cos(p * 0.5)
  11. sp = sin(p * 0.5)
  12. cy = cos(y * 0.5)
  13. sy = sin(y * 0.5)
  14.  
  15. return cls(
  16. w=cy * cr * cp + sy * sr * sp,
  17. x=cy * sr * cp - sy * cr * sp,
  18. y=cy * cr * sp + sy * sr * cp,
  19. z=sy * cr * cp - cy * sr * sp)
  20.  
  21. @classmethod
  22. def _conjugate(cls, q):
  23. return cls(q.w, -q.x, -q.y, -q.z)
  24.  
  25. @classmethod
  26. def _mul(cls, q0, q1):
  27. return cls(
  28. w=q0.w*q1.w - q0.x*q1.x - q0.y*q1.y - q0.z*q1.z
  29. x=q0.w*q1.x + q0.x*q1.w - q0.y*q1.z + q0.z*q1.y
  30. y=q0.w*q1.y + q0.x*q1.z + q0.y*q1.w - q0.z*q1.x
  31. z=q0.w*q1.z - q0.x*q1.y + q0.y*q1.x + q0.z*q1.w)
  32.  
  33. @classmethod
  34. def _rot(cls, q, v):
  35. q2 = cls(w=0, x=v[0], y=v[1], z=v[2])
  36. # q * v * q^-1
  37. return cls._mul(cls._mul(q, q2), cls_.conjugate(q))[1:]
  38.  
  39. def __init__(self, w, x, y, z):
  40. self.w = w
  41. self.x = x
  42. self.y = y
  43. self.z = z
  44.  
  45. def __iter__(self):
  46. return (self.w, self.x, self.y, self.z)
  47.  
  48. def __mul__(self, other):
  49. if isinstance(other, type(self)):
  50. return __class__._mul(self, other)
  51. elif isinstance(other, tuple):
  52. return __class__._rot(self, other)
  53.  
  54. def inv(self):
  55. return __class__._conjugate(self)
Add Comment
Please, Sign In to add comment