vector.html
001| '''Vector and Quaternion Classes.
001|
001| Classes:
001| vector - Basic vector class (based on tuple; any size)
001| cvector - Subclass of vector for complex values (work in progress)
001| quaternion - Quaternion class (based on tuple; always 4-tuple)
001|
001| Global Instances:
001| V0 - vector (0, 0, 0) - zero vector (origin)
001| VX - vector (1, 0, 0) - X basis unit vector
001| VY - vector (0, 1, 0) - Y basis unit vector
001| VZ - vector (0, 0, 1) - Z basis unit vector
001| VW - vector (0, 0, 0, 1) - W basis unit vector
001| VU - vector (0, 0, 0, 0, 1) - U basis unit vector
001|
001| Q0 - quaternion (0, 0, 0, 0) - zero quaternion
001| QI - quaternion (0, 1, 0, 0) - i basis unit quaternion
001| QJ - quaternion (0, 0, 1, 0) - j basis unit quaternion
001| QK - quaternion (0, 0, 0, 1) - k basis unit quaternion
001|
001| Developer@Sonnack.com
001| August 2018
001| '''
002|
003| from math import sqrt, sin,cos, acos, degrees,radians
004| from cmath import sqrt as csqrt
005| from random import random
006|
007|
008|
009|
010| class vector (tuple):
011| '''Euclidean Vector Class.
011|
011| Supports vectors of any size, but has some special methods for 3-vectors.
011|
011| A vector has the general form (empty vectors are allowed):
011| ([v1 [,v2 [,v3 [,...]]]])
011|
011| Vectors have Cartesian coordinate members (depending on length):
011| ([x [,y [,z [,w [,u]]]]])
011|
011| As well as the general coordinate members (depending on length):
011| ([a [,b [,c [,d [,e [, f [,g [,h]]]]]]]])
011|
011| Instance Properties:
011| x,y,z,w,u - respective members of vector (if len allows)
011| a-h - respective members of vector (if len allows)
011| magnitude - vector magnitude (sqrt of sum of sqs)
011| argument - vector argument (angle)
011| unit - identical vector, but with magnitude 1.00
011| aslist - vector as a list
011| asdict - vector as a dictionary
011| ascomplex - vector as a complex number [2-vec only]
011| polar - polar vector (radius plus angle(s)) [up to R4]
011|
011| Instance Methods:
011| distance(vec) - distance of one vector from another
011| angle(vec) - angle of vec to self
011| dot(vec) - dot product of self and vec
011| cross(vec) - cross product of self and vec [3-vec only]
011| clone() - return a copy
011| +obj - same vector (note: creates a copy!)
011| -obj - negative vector (member-wise; -x)
011| ~obj - inverse of vec (member-wise; 1/x)
011| abs(obj) - absolute value (member-wise; abs(x))
011| obj + vec - vector addition
011| obj - vec - vector subtraction
011| obj * vec - vector multiplication
011| obj + nbr - scalar (member-wise) addition
011| obj - nbr - scalar (member-wise) subtraction
011| obj * nbr - scalar (member-wise) multiplication
011| obj / nbr - scalar (member-wise) division
011| obj == vec - vector equality (member-wise)
011| obj != vec - vector equality (member-wise)
011| obj rel vec - comparison (based only on magnitude) [rel: < <= >= >]
011|
011| Global Methods:
011| fromcomplex - return a 2D vector from a complex number
011| frompolar - return a 2D vector from a magnitude and angle
011| fromheading - return a 3D unit vector from an Azimuth and Elevation
011| randvect - return a random unit vector with n elements
011|
011| '''
012| NamedElements = ['x','y','z', 'w','u', 'a','b','c','d','e']
013|
014| ErrNotVector = 'Other object must be a vector, not a {type(0).__name__}.'
015| ErrNotNumeric = 'Unsupported type for vector {0}: {type(1).__name__}'
016|
017|
018|
019| def __new__ (cls, *args, **kwargs):
020| '''Create new vector instance.'''
021|
022| arglst = list(args[0]) if len(args)==1 else args
023|
024|
025| for ix,a in enumerate(arglst, start=1):
026| if isinstance(a,int): continue
027| if isinstance(a,float): continue
028| if isinstance(a,complex): continue
029| raise ValueError(f'Illegal list item: #{ix}={a}')
030|
031|
032| return super().__new__(cls, arglst)
033|
034| def __init__ (self, *args, sep=', ', prec=3, plus='+'):
035| '''Initialize new vector instance.'''
036| super().__init__()
037| self.delim = sep
038| self.prec = prec
039| self.plus = plus
040|
041| def __repr__ (self):
042| '''Debug string.'''
043| return f'<{type(self).__name__}{len(self)} @{id(self):012x}>'
044|
045| def __str__ (self):
046| '''String version.'''
047| return f'[{self._slist}]'
048|
049|
050|
051|
052| @property
053| def x (self): return self[0] if 0 <len(self) else None
054|
055| @property
056| def y (self): return self[1] if 1 <len(self) else None
057|
058| @property
059| def z (self): return self[2] if 2 <len(self) else None
060|
061| @property
062| def w (self): return self[3] if 3 <len(self) else None
063|
064| @property
065| def u (self): return self[4] if 4 <len(self) else None
066|
067| @property
068| def a (self): return self[0] if 0 <len(self) else None
069|
070| @property
071| def b (self): return self[1] if 1 <len(self) else None
072|
073| @property
074| def c (self): return self[2] if 2 <len(self) else None
075|
076| @property
077| def d (self): return self[3] if 3 <len(self) else None
078|
079| @property
080| def e (self): return self[4] if 4 <len(self) else None
081|
082| @property
083| def f (self): return self[5] if 5 <len(self) else None
084|
085| @property
086| def g (self): return self[6] if 6 <len(self) else None
087|
088| @property
089| def h (self): return self[7] if 7 <len(self) else None
090|
091| def __setattr__ (self, name, value):
092| '''Don't allow setting read-only properties.'''
093| if name in type(self).NamedElements:
094| raise AttributeError(f'Read-Only Attribute: "{name}"')
095| super().__setattr__(name, value)
096|
097| def __delattr__ (self, name):
098| '''Don't allow deleting read-only properties.'''
099| if name in type(self).NamedElements:
100| raise AttributeError(f'Read-Only Attribute: "{name}"')
101| super().__delattr__(name, value)
102|
103|
104|
105|
106| def __bool__ (self) -> bool:
107| '''A vector is zero if all its members are zero.'''
108| return (sum(self) != 0.0)
109|
110| @property
111| def magnitude (self) -> float:
112| '''Return magnitude (length) of self. (float)'''
113|
114| ss = [pow(a,2) for a in self]
115|
116| return sqrt(sum(ss))
117|
118| @property
119| def argument (self) -> float:
120| '''Return argument (treating vector as a complex number). (float)'''
121| v0 = vector(1, 0)
122| return self.angle(v0)
123|
124| @property
125| def unit (self) -> tuple:
126| '''Return self as a (new) normalized vector.'''
127| d = self.magnitude
128| if d: return self.__class__(*[n/d for n in self])
129| return vector(*[0.0 for n in self], **self.options())
130|
131|
132|
133|
134| def distance (self, other):
135| '''Distance from one vector to another.'''
136| self._length_check(other)
137|
138| ss = [pow(a-b,2) for a,b in zip(self,other)]
139|
140| return sqrt(sum(ss))
141|
142| def angle (self, other:tuple) -> float:
143| '''Return the angle with a given vector. (float)'''
144| self._length_check(other)
145| area = self.magnitude * other.magnitude
146| return degrees(acos(self.dot(other) / area))
147|
148| def dot (self, other:tuple) -> float:
149| '''Given another vector, return Dot Product (float).'''
150| self._length_check(other)
151|
152| ss = [a*b for a,b in zip(self,other)]
153|
154| return sum(ss)
155|
156| def cross (self, other:tuple) -> tuple:
157| '''Given another vector, return Cross Product (vector).'''
158| if len(self) != 3:
159| raise ValueError('Sorry! Cross Product is for 3-vectors only.')
160| self._length_check(other)
161| a = (self[1] * other[2]) - (self[2] * other[1])
162| b = (self[2] * other[0]) - (self[0] * other[2])
163| c = (self[0] * other[1]) - (self[1] * other[0])
164| return vector(a, b, c, **self.options())
165|
166|
167|
168|
169| def __eq__ (self, other):
170| '''Note: Equality requires matching length, but comparison is based ONLY on magnitude.'''
171|
172| if not isinstance(other,vector): return False
173|
174| if len(other) != len(self): return False
175|
176| for a,b in zip(self,other):
177| if a != b:
178| return False
179|
180| return True
181|
182| def __lt__ (self, other):
183| '''Is self < other.'''
184|
185| if not isinstance(other,vector):
186| raise ValueError(vector.ErrNotVector.format(other))
187|
188| self._length_check(other)
189|
190| for a,b in zip(self,other):
191| if a < b:
192| return True
193| if b < a:
194| return False
195|
196| return False
197|
198| def __gt__ (self, other):
199| '''Is self > other.'''
200|
201| if not isinstance(other,vector):
202| raise ValueError(vector.ErrNotVector.format(other))
203|
204| self._length_check(other)
205|
206| for a,b in zip(self,other):
207| if a < b:
208| return False
209| if b < a:
210| return True
211|
212| return False
213|
214| def __ne__ (self, other): return not self.__eq__(other)
215| def __le__ (self, other): return not self.__gt__(other)
216| def __ge__ (self, other): return not self.__lt__(other)
217|
218|
219|
220|
221| def __pos__ (self) -> tuple:
222| '''+vec generates a copy!'''
223| return vector(*[n for n in self], **self.options())
224|
225| def __neg__ (self) -> tuple:
226| '''-vec multiplies members by -1.'''
227| return vector(*[-n for n in self], **self.options())
228|
229| def __abs__ (self) -> tuple:
230| '''Absolute value (member-wise).'''
231| return vector(*[abs(n) for n in self], **self.options())
232|
233| def __invert__ (self) -> tuple:
234| '''~vec inverts members: 1/n.'''
235| return vector(*[1.0/n if n else 0.0 for n in self], **self.options())
236|
237|
238| def _is_numeric_type (self, other):
239| '''Is object a valid numeric type?'''
240| if isinstance(other, int): return True
241| if isinstance(other, float): return True
242| if isinstance(other, complex): return True
243|
244| return False
245|
246| def __add__ (self, other) -> tuple:
247| '''Vector or Scalar Addition.'''
248|
249|
250| if isinstance(other, vector):
251| self._length_check(other)
252| return vector(*[a+b for a,b in zip(self,other)], **self.options())
253|
254|
255| if not self._is_numeric_type(other):
256| raise TypeError(vector.ErrNotNumeric.format('addition',other))
257|
258|
259| return vector(*[n+other for n in self], **self.options())
260|
261| def __radd__ (self, scalar) -> tuple:
262| '''RHS Scalar Addition (communtes).'''
263| return self.__add__(scalar)
264|
265|
266| def __sub__ (self, other) -> tuple:
267| '''Vector or Scalar Subtration.'''
268|
269|
270| if isinstance(other, vector):
271| self._length_check(other)
272| return vector(*[a-b for a,b in zip(self,other)], **self.options())
273|
274|
275| if not self._is_numeric_type(other):
276| raise TypeError(vector.ErrNotNumeric.format('subtraction',other))
277|
278|
279| return vector(*[n-other for n in self], **self.options())
280|
281| def __rsub__ (self, scalar) -> tuple:
282| '''RHS Scalar Subtraction (does not commute).'''
283|
284| if not self._is_numeric_type(other):
285| raise TypeError(vector.ErrNotNumeric.format('subtraction',other))
286|
287|
288| return vector(*[scalar-n for n in self], **self.options())
289|
290|
291| def __mul__ (self, other) -> tuple:
292| '''Vector or Scalar Multiplication.'''
293|
294|
295| if isinstance(other, vector):
296| self._length_check(other)
297| return vector(*[a*b for a,b in zip(self,other)], **self.options())
298|
299|
300| if not self._is_numeric_type(other):
301| raise TypeError(vector.ErrNotNumeric.format('multiplication',other))
302|
303|
304| return vector(*[n*other for n in self], **self.options())
305|
306| def __rmul__ (self, scalar) -> tuple:
307| '''RHS Scalar Multiplication (commutes).'''
308| return self.__mul__(scalar)
309|
310|
311| def __truediv__ (self, other) -> tuple:
312| '''Scalar Division.'''
313|
314|
315| if isinstance(other, vector):
316| self._length_check(other)
317| return vector(*[a/b for a,b in zip(self,other)], **self.options())
318|
319|
320| if not self._is_numeric_type(other):
321| raise TypeError(vector.ErrNotNumeric.format('division',other))
322|
323|
324| return vector(*[n/other for n in self], **self.options())
325|
326| def __rtruediv__ (self, scalar):
327| '''RHS Scalar Division (does not commute).'''
328|
329| if not self._is_numeric_type(other):
330| raise TypeError(vector.ErrNotNumeric.format('division',other))
331|
332|
333| return vector(*[scalar/n for n in self], **self.options())
334|
335|
336|
337|
338| def _length_check (self, other):
339| if len(other) != len(self):
340| raise ValueError(f'Dimension Mismatch: {len(other)} <> {len(self)}')
341|
342| @property
343| def _slist (self) -> str:
344| '''Elements-to-CSV string. Override in subclasses to modify str(obj).'''
345| plus = self.plus
346| prec = self.prec
347| seps = f'{self.delim} '
348| return seps.join(f'{n:{plus}.{prec}f}' for n in self)
349|
350| def options (self, sep=None, prec=None, plus=None) -> dict:
351| '''Return (optionally set) keyword parameters.'''
352|
353| if prec is not None:
354| self.precision = prec
355| if sep is not None:
356| self.separator = sep
357| if plus is not None:
358| self.plus = '+' if plus else ''
359|
360|
361| return dict(sep=self.delim, prec=self.prec, plus=self.plus)
362|
363| def clone (self) -> tuple:
364| '''Return a copy.'''
365| return vector(*[n for n in self], **self.options())
366|
367| @property
368| def aslist (self) -> list:
369| '''Return a list containing vector elements.'''
370| return list(self)
371|
372| @property
373| def asdict (self) -> dict:
374| '''Return a dictionary containing vector elements.'''
375| return {f'x{ix}':a for ix,a in enumerate(self)}
376|
377| @property
378| def ascomplex (self) -> complex:
379| '''Return a complex number (IF vector has two elements).'''
380| if len(self) != 2:
381| raise ValueError('Sorry! A complex number requires a 2-vector.')
382| return complex(self[0], self[1])
383|
384| @property
385| def polar (self) -> tuple:
386| '''Return polar coordinate version of self. [Up to 3 dimensions]'''
387| if len(self) == 0: return self.__class__()
388| if len(self) == 1: return self.__class__(self[0])
389| if len(self) == 2:
390| a = self.magnitude
391| b = degrees(acos(self.unit.x))
392| return vector(a, b, **self.options())
393| if len(self) == 3:
394| v2 = vector(self.x, self.z, **self.options())
395| v3 = vector(v2.magnitude, self.y, **self.options())
396| a = self.magnitude
397| b = degrees(acos(v2.unit.x))
398| c = v2.angle(v3)
399| return vector(a, b, c, **self.options())
400| raise ValueError('Sorry! Vector is too big to convert to polar coordinates.')
401|
402|
403|
404|
405| @classmethod
406| def fromcomplex (cls, z:complex, **kwargs) -> tuple:
407| '''Return a (two-element) vector from a complex number.'''
408| return vector(z.real, z.imag, **kwargs)
409|
410| @classmethod
411| def frompolar (cls, magnitude:float, angle:float, **kwargs) -> tuple:
412| '''Return a vector from a magnitude and angle.'''
413| a = radians(angle)
414| x = magnitude * cos(a)
415| y = magnitude * sin(a)
416| return vector(x, y, **kwargs)
417|
418| @classmethod
419| def fromheading (cls, azimuth:float, elevation:float, **kwargs) -> tuple:
420| '''From Heading.
420| Get vector from Azimuth and Elevation. Assumes:
420| forward = 0az = +Z
420| left = 90az = +X
420| backward = 180az = -Z
420| right = 270az = -X
420| '''
421| a = (450.0 - float(azimuth)) % 360
422| v = vector(cos(radians(a)), sin(radians(elevation)), sin(radians(a)), **kwargs)
423| return v.unit
424|
425| @classmethod
426| def randvect (cls, n:int, **kwargs) -> tuple:
427| '''Return a random unit vector with n elements.'''
428| xs = [1.0-(random()*2.0) for _ in range(n)]
429| return vector(*xs, **kwargs).unit
430|
431|
432|
433| class cvector (vector):
434| '''Complex Vector Class.'''
435|
436|
437| def __new__ (cls, *args):
438| '''Make a new vector instance.'''
439| return tuple.__new__(cls, [complex(a) for a in args])
440|
441| def magnitude (self):
442| '''Return magnitude (length) of self.'''
443| return csqrt(self.dot(self))
444|
445| def dot (self, other):
446| '''Given another vector, return Dot Product.'''
447| self._length_check(other)
448| return sum([(z1.conjugate()*z2) for z1,z2 in zip(self,other)])
449|
450| def _slist (self):
451| plus = self.plus
452| prec = self.prec
453| seps = f'{self.delim} '
454| a = [f'({z.real:{plus}.{prec}f}+{z.imag:{plus}.{prec}f}i)' for z in self]
455| return seps.join(a)
456|
457|
458|
459| class quaternion (tuple):
460| '''Quaternion Class.
460|
460| A quaternion has the form: (a + bi + cj + dk)
460|
460| Where: a, b, c, d are real numbers,
460| i, j, k are unit vectors in quaternion space.
460|
460| Quaternion Multiplication Table:
460| x| 1 i j k|
460| -+-----------+
460| 1| 1 i j k|
460| i| i -1 k -j|
460| j| j -k -1 i|
460| k| k j -i -1|
460| -+-----------+
460|
460| Note:
460| Addition and Multiplication can be expressed in terms of the
460| scalar and vector components of the quaternion:
460|
460| ((r1, v1) + (r2, v2)) = (r1+r2, v1+v2)
460| ((r1, v1) * (r2, v2)) = ((r1*r2)-v1.dot(v2), (r1*v2)+(r2*v1)+v1.cross(v2))
460|
460| '''
461|
462|
463| def __new__ (cls, a=0.0, b=0.0, c=0.0, d=0.0, vec=None):
464| if vec and (len(vec)==3):
465| return super().__new__(cls, [float(a),float(vec[0]),float(vec[1]),float(vec[2])])
466| return super().__new__(cls, [float(a),float(b),float(c),float(d)])
467|
468| def __init__ (self, *args, **kwargs):
469| super().__init__()
470|
471| def __repr__ (self):
472| '''Debug string.'''
473| return f'<{type(self).__name__} @{id(self):012x}>'
474|
475| def __str__ (self):
476| return '(%+.4f, %+.4fi, %+.4fj, %+.4fk)' % self
477|
478|
479|
480| @property
481| def a (self): return self[0]
482| def b (self): return self[0]
483| def c (self): return self[0]
484| def d (self): return self[0]
485|
486| def __setattr__ (self, name, value):
487| if name in ['a', 'b', 'c', 'd']:
488| raise AttributeError(f'Read-Only Attribute: "{name}"')
489| super().__setattr__(name, value)
490|
491| def __delattr__ (self, name, value):
492| if name in ['a', 'b', 'c', 'd']:
493| raise AttributeError(f'Read-Only Attribute: "{name}"')
494| super().__delattr__(name, value)
495|
496|
497|
498| def scalar (self): return self[0]
499| def vector (self): return vector(self[1], self[2], self[3])
500|
501| def unit (self):
502| '''Return a quaternion with a norm of 1.0.'''
503| d = self.norm()
504| if d: return quaternion(*[n/d for n in self])
505| return quaternion()
506|
507| def conj (self):
508| '''Return conjugation quaternion of self.'''
509| return quaternion(self.a, -self.b, -self.c, -self.d)
510|
511| def norm (self):
512| '''Norm is like the magnitude of a vector.'''
513| return sqrt(sum([n*n for n in self]))
514|
515| def recip (self):
516| '''Reciprocal is q.conj() / (q.norm() * q.norm()).'''
517| return self.conj() / (self.norm() * self.norm())
518|
519|
520|
521| def __bool__ (self):
522| '''A quaternion is zero if all its members are zero.'''
523| return True if 0.0 < self.norm() else False
524|
525| def __abs__ (self):
526| '''Absolute value (member-wise).'''
527| return quaternion(*[abs(n) for n in self])
528|
529| def __invert__ (self):
530| '''Invert members: 1/n.'''
531| return quaternion(*[1.0/n if n else 0.0 for n in self])
532|
533| def __add__ (self, q):
534| '''Quaternion addition uses matching members.'''
535| a1 = float(self.a + q.a)
536| b1 = float(self.b + q.b)
537| c1 = float(self.c + q.c)
538| d1 = float(self.d + q.d)
539| return quaternion(a1, b1, c1, d1)
540|
541| def __sub__ (self, q):
542| '''Quaternion subtraction uses matching members.'''
543| a1 = float(self.a - q.a)
544| b1 = float(self.b - q.b)
545| c1 = float(self.c - q.c)
546| d1 = float(self.d - q.d)
547| return quaternion(a1, b1, c1, d1)
548|
549| def __mul__ (self, scalar_or_quat):
550| '''Vector or Scalar Multiplication.'''
551| if isinstance(scalar_or_quat,int) or isinstance(scalar_or_quat,float):
552| nf = float(scalar_or_quat)
553| return quaternion(*[float(n*nf) for n in self])
554|
555| if isinstance(scalar_or_quat,quaternion):
556| q = scalar_or_quat
557| a1 = float((self.a * q.a) - (self.b * q.b) - (self.c * q.c) - (self.d * q.d))
558| b1 = float((self.a * q.b) + (self.b * q.a) + (self.c * q.d) - (self.d * q.c))
559| c1 = float((self.a * q.c) - (self.b * q.d) + (self.c * q.a) + (self.d * q.b))
560| d1 = float((self.a * q.d) + (self.b * q.c) - (self.c * q.b) + (self.d * q.a))
561| return quaternion(a1, b1, c1, d1)
562| raise TypeError('Unsupported type for quaternion multiplication: {type(scalar_or_quat).__name__}')
563|
564| def __truediv__ (self, scalar):
565| '''Scalar Division.'''
566| nf = float(scalar)
567| return quaternion(*[float(n/nf) for n in self])
568|
569| def __rmul__ (self, scalar):
570| '''Scalar Multiplication.'''
571| return self.__mul__(scalar)
572|
573|
574|
575| @classmethod
576| def rotator (cls, vect, angle):
577| '''Return a rotation quaternion given a rotation vector and an angle.'''
578| fa = float(angle)
579| rr = cos(radians(fa/2.0))
580| rv = vect * sin(radians(fa/2.0))
581| return cls(rr, vec=rv)
582|
583|
584|
585| V0 = vector(0, 0, 0)
586| VX = vector(1, 0, 0)
587| VY = vector(0, 1, 0)
588| VZ = vector(0, 0, 1)
589| VW = vector(0, 0, 0, 1)
590| VU = vector(0, 0, 0, 0, 1)
591|
592|
593| Q0 = quaternion()
594| QI = quaternion(0, 1, 0, 0)
595| QJ = quaternion(0, 0, 1, 0)
596| QK = quaternion(0, 0, 0, 1)
597|
598|
599|
600| '''eof'''
601|