2024-11-11_simple-python-tricks-11.html
001|
002|
003|
004|
005| from math import sqrt
006|
007| class vector (tuple):
008| '''Vector class (based on tuple).'''
009| ErrNotAVector = 'Comparisons require two vector objects!'
010| ErrWrongLength = 'Vector lengths must match.'
011| ErrBadMathType = 'Unsupported type for vector %s: %s'
012| ErrNoInPlaceOp = 'Vectors are immutable. In-place operations not allowed.'
013|
014| def __new__ (cls, *args, **kwargs):
015| '''New vector instance.'''
016|
017|
018| arglst = list(args[0]) if len(args)==1 else args
019|
020|
021| for ix,a in enumerate(arglst, start=1):
022| if isinstance(a,int): continue
023| if isinstance(a,float): continue
024| raise ValueError(f'Illegal list item: #{ix}={a}')
025|
026|
027| return super().__new__(cls, arglst)
028|
029| def __init__ (self, *args, prec=3, sep=', ', plus=True):
030| '''Initialize vector instance.'''
031|
032| super().__init__()
033|
034|
035| self.precision = prec
036| self.separator = sep
037| self.plus = '+' if plus else ''
038|
039| def __str__ (self):
040| ''' Return pretty string version. '''
041| ss = [f'{a:{self.plus}.{self.precision}f}' for a in self]
042| return f'[{self.separator.join(ss)}]'
043|
044| def __repr__ (self):
045| ''' Return Vector as a serializable object (JSON). '''
046| ss = [f'"e{ix}":{a:.6f}' for ix,a in enumerate(self)]
047| return f'"vector":{ {", ".join(ss)}} '
048|
049| def __getattr__ (self, name):
050| '''Read-only Properties.'''
051| if name == 'x': return self[0] if 0<len(self) else None
052| if name == 'y': return self[1] if 1<len(self) else None
053| if name == 'z': return self[2] if 2<len(self) else None
054| if name == 'w': return self[3] if 3<len(self) else None
055| if name == 'u': return self[4] if 4<len(self) else None
056|
057| def __call__ (self): return tuple(self)
058|
059| def aslist (self): return list(self)
060| def asdict (self): return {f'x{ix}':a for ix,a in enumerate(self)}
061|
062| def __bool__ (self):
063| '''Vector is zero if all members are zero.'''
064| return (sum(self) != 0)
065|
066| def props (self, prec=None, sep=None, plus=None):
067| '''Return (optionally set) keyword parameters.'''
068|
069| if prec is not None:
070| self.precision = prec
071| if sep is not None:
072| self.separator = sep
073| if plus is not None:
074| self.plus = '+' if plus else ''
075|
076|
077| return dict(prec=self.precision, sep=self.separator, plus=self.plus)
078|
079| @property
080| def magnitude (self):
081| '''Magnitude: sqrt(sum(x_i^2)).'''
082|
083| ss = [pow(a,2) for a in self]
084|
085| return sqrt(sum(ss))
086|
087| def distance (self, other):
088| '''Distance from one vector to another.'''
089|
090| assert isinstance(other,vector), TypeError(self.ErrNotAVector)
091|
092| assert len(self)==len(other), ValueError(self.ErrWrongLength)
093|
094| ss = [pow(a-b,2) for a,b in zip(self,other)]
095|
096| return sqrt(sum(ss))
097|
098| def dot (self, other):
099| '''Return the dot product of two vectors. '''
100|
101| assert isinstance(other,vector), TypeError(self.ErrNotAVector)
102|
103| assert len(self)==len(other), ValueError(self.ErrWrongLength)
104|
105| ss = [a*b for a,b in zip(self,other)]
106|
107| return sum(ss)
108|
109| def __eq__ (self, other):
110| '''Test self & other for equality.'''
111|
112| assert isinstance(other,vector), TypeError(self.ErrNotAVector)
113|
114| if len(self) != len(other):
115| return False
116|
117| for a,b in zip(self,other):
118| if a != b:
119| return False
120|
121| return True
122|
123| def __lt__ (self, other):
124| '''Is self < other.'''
125|
126| assert isinstance(other,vector), TypeError(self.ErrNotAVector)
127|
128| for a,b in zip(self,other):
129| if a < b:
130| return True
131| if b < a:
132| return False
133|
134| return False
135|
136| def __gt__ (self, other):
137| '''Is self > other.'''
138|
139| assert isinstance(other,vector), TypeError(self.ErrNotAVector)
140|
141| for a,b in zip(self,other):
142| if a < b:
143| return False
144| if b < a:
145| return True
146|
147| return False
148|
149| def __ne__ (self, other): return not self.__eq__(other)
150| def __le__ (self, other): return not self.__gt__(other)
151| def __ge__ (self, other): return not self.__lt__(other)
152|
153| def __hash__ (self): return id(self)
154|
155| def __pos__ (self):
156| '''Operator +: creates a copy.'''
157| return vector([a for a in self], **self.props())
158|
159| def __neg__ (self):
160| '''Operator -: memberwise negation.'''
161| return vector([-a for a in self], **self.props())
162|
163| def __abs__ (self):
164| '''Operator abs: memberwise absolute value.'''
165| return vector([abs(a) for a in self], **self.props())
166|
167| def __invert__ (self):
168| '''Operator ~: invert members.'''
169| return vector([(1/a if a else 0) for a in self], **self.props())
170|
171| def _is_numeric_type (self, obj):
172| '''Is object a valid numeric type?'''
173| if isinstance(obj, int): return True
174| if isinstance(obj, float): return True
175|
176| return False
177|
178| def __add__ (self, other):
179| '''Vector or Scalar Addition.'''
180|
181| if isinstance(other,vector):
182| return vector([a+b for a,b in zip(self,other)], **self.props())
183|
184|
185| if self._is_numeric_type(other):
186| return vector([a+other for a in self], **self.props())
187|
188| raise TypeError(self.ErrBadMathType % ('addition', type(other)))
189|
190| def __sub__ (self, other):
191| '''Vector or Scalar Subtration.'''
192|
193| if isinstance(other,vector):
194| return vector([a-b for a,b in zip(self,other)], **self.props())
195|
196|
197| if self._is_numeric_type(other):
198| return vector([a-other for a in self], **self.props())
199|
200| raise TypeError(self.ErrBadMathType % ('subtraction', type(other)))
201|
202| def __mul__ (self, other):
203| '''Vector or Scalar Multiplication.'''
204|
205| if isinstance(other,vector):
206| return vector([a*b for a,b in zip(self,other)], **self.props())
207|
208|
209| if self._is_numeric_type(other):
210| return vector([a*other for a in self], **self.props())
211|
212| raise TypeError(self.ErrBadMathType % ('multiplication', type(other)))
213|
214| def __truediv__ (self, other):
215| '''Vector or Scalar Division.'''
216|
217| if isinstance(other,vector):
218| return vector([a/b for a,b in zip(self,other)], **self.props())
219|
220|
221| if self._is_numeric_type(other):
222| return vector([a/other for a in self], **self.props())
223|
224| raise TypeError(self.ErrBadMathType % ('division', type(other)))
225|
226| def __radd__ (self, other):
227| '''RHS Scalar Addition.'''
228| return self.__add__(other)
229|
230| def __rsub__ (self, other):
231| '''RHS Scalar Subtraction.'''
232|
233| if self._is_numeric_type(other):
234| return vector([other-a for a in self], **self.props())
235|
236| raise TypeError(self.ErrBadMathType % ('subtraction', type(other)))
237|
238| def __rmul__ (self, other):
239| '''RHS Scalar Multiplication.'''
240| return self.__mul__(other)
241|
242| def __rtruediv__ (self, other):
243| '''RHS Scalar Division.'''
244|
245| if self._is_numeric_type(other):
246| return vector([other/a for a in self], **self.props())
247|
248| raise TypeError(self.ErrBadMathType % ('division', type(other)))
249|
250| def __iadd__ (self, other):
251| '''In-place Addition.'''
252| raise NotImplementedError(self.ErrNoInPlaceOp)
253|
254| def __isub__ (self, other):
255| '''In-place Subtraction.'''
256| raise NotImplementedError(self.ErrNoInPlaceOp)
257|
258| def __imul__ (self, other):
259| '''In-place Multiplication.'''
260| raise NotImplementedError(self.ErrNoInPlaceOp)
261|
262| def __itruediv__ (self, other):
263| '''In-place Division.'''
264| raise NotImplementedError(self.ErrNoInPlaceOp)
265|
266|
267| from vector import vector
268|
269| vec = vector(0.51, 1.67, 2.72, 3.14, 6.63, prec=2)
270| print(vec)
271| print()
272| print(f'{vec.x = :.6f}')
273| print(f'{vec.y = :.6f}')
274| print(f'{vec.z = :.6f}')
275| print(f'{vec.w = :.6f}')
276| print(f'{vec.u = :.6f}')
277| print()
278|
279|
280| from vector import vector
281|
282| vec = vector(0.51, 1.67, 2.72, 3.14, 6.63, prec=2)
283| vlist = vec.aslist()
284| vdict = vec.asdict()
285|
286| print(f'{vec() = }')
287| print()
288| print(f'{type(vlist) = }')
289| for ix,item in enumerate(vlist):
290| print(f' {ix}: {item}')
291| print()
292| print(f'{type(vdict) = }')
293| for key,value in vdict.items():
294| print(f' {key}: {value}')
295| print()
296|
297|
298| from vector import vector
299|
300| def test_vec (v):
301| print(v)
302| if v:
303| print('vector is True')
304| else:
305| print('vector is False')
306| print()
307|
308| vec = vector(0.5, 1.7, 2.7, 3.1, 6.6, prec=1, plus=False)
309| test_vec(vec)
310| test_vec(vector())
311| test_vec(vector([0], prec=0, plus=False))
312| test_vec(vector([1, 0], prec=0, plus=False))
313| test_vec(vector(0,0,0, prec=0, plus=False))
314| test_vec(vector(0,0,0,0,1, prec=0, plus=False))
315|
316|
317| from vector import vector
318|
319| vec0 = vector(0, 0, prec=0, plus=False)
320| vec1 = vector(1, 0, prec=0, plus=False)
321| vec2 = vector(1, 1, prec=0, plus=False)
322| vec3 = vector(0, 1, prec=0, plus=False)
323| vec4 = vector(2, 5, prec=0, plus=False)
324|
325| print(f'{vec0 = !s}')
326| print(f'{vec1 = !s}')
327| print(f'{vec2 = !s}')
328| print(f'{vec3 = !s}')
329| print(f'{vec4 = !s}')
330| print()
331| print(f'{vec0.magnitude = !s}')
332| print(f'{vec1.magnitude = !s}')
333| print(f'{vec2.magnitude = !s}')
334| print(f'{vec3.magnitude = !s}')
335| print(f'{vec4.magnitude = !s}')
336| print()
337| print(f'{vec0.distance(vec0) = }')
338| print(f'{vec0.distance(vec1) = }')
339| print(f'{vec0.distance(vec2) = }')
340| print(f'{vec0.distance(vec3) = }')
341| print(f'{vec0.distance(vec4) = }')
342| print()
343| print(f'{vec1.dot(vec1) = }')
344| print(f'{vec1.dot(vec2) = }')
345| print(f'{vec1.dot(vec3) = }')
346| print(f'{vec1.dot(vec4) = }')
347| print()
348|
349|
350| from vector import vector
351|
352| vec0 = vector([0]*3, prec=0)
353| vec1 = vector(0.5, -1.6, -2.7, prec=1)
354| vec2 = vector(0.5, +1.6, -2.7, prec=1)
355| vec3 = vector(1/2, +3/4, -3/7, prec=1)
356|
357| print(f'vec0: {vec0}')
358| print(f'vec1: {vec1}')
359| print(f'vec2: {vec2}')
360| print(f'vec3: {vec3}')
361| print()
362| print(f'{hash(vec0) = }')
363| print(f'{hash(vec1) = }')
364| print(f'{hash(vec2) = }')
365| print(f'{hash(vec3) = }')
366| print()
367| print(f'{vec1 == vec1 = }')
368| print(f'{vec1 == vec2 = }')
369| print()
370| print(f'{vec1 != vec1 = }')
371| print(f'{vec1 != vec2 = }')
372| print()
373| print(f'{vec1 < vec1 = }')
374| print(f'{vec1 < vec2 = }')
375| print()
376| print(f'{vec1 <= vec1 = }')
377| print(f'{vec1 <= vec2 = }')
378| print()
379| print(f'{vec1 > vec1 = }')
380| print(f'{vec1 > vec2 = }')
381| print()
382| print(f'{vec1 >= vec1 = }')
383| print(f'{vec1 >= vec2 = }')
384| print()
385|
386|
387| from random import random
388| from vector import vector
389|
390| randelem = lambda: 10*random()
391| randvect = lambda: vector(randelem(),randelem(),randelem())
392|
393| vs = [randvect() for _ in range(16)]
394|
395| for v in sorted(vs):
396| print(v)
397| print()
398|
399|
400| from vector import vector
401|
402| def demo_unary_ops (v):
403| v1 = +v
404| v2 = -v
405| v3 = abs(v)
406| v4 = ~v
407| print(f'vector : {v} id={id(v)}')
408| print(f'unary plus : {v1} id={id(v1)}')
409| print(f'unary minus : {v2} id={id(v2)}')
410| print(f'abs() value : {v3} id={id(v3)}')
411| print(f'unary invert: {v4} id={id(v4)}')
412| print()
413|
414| demo_unary_ops(vector(-1/3, -1/5, +1/7, prec=6))
415| demo_unary_ops(vector(-2/3, +3/5, -5/7, prec=6))
416|
417|
418| from vector import vector
419|
420| v1 = vector(2.71828, 3.14159, 6.62607, prec=2)
421| v2 = vector(1, 1, 1, prec=0)
422|
423| print(f'{v1 = !s}, id={id(v1)}')
424| print(f'{v2 = !s}')
425| print()
426|
427| v1 += v2
428|
429| print(f'{v1 = !s}, id={id(v1)}')
430| print()
431|
432|
433| from vector import vector
434|
435| v1 = vector(2.71828, 3.14159, 6.62607, prec=2)
436| v2 = vector(1, 1, 1, prec=0)
437|
438| print(f'{v1 = !s}, id={id(v1)}')
439| print(f'{v2 = !s}')
440| print()
441|
442| v1 = (v1 + v2)
443|
444| print(f'{v1 = !s}, id={id(v1)}')
445| print()
446|
447|
448| from vector import vector
449|
450| def demo_binary_ops (a, b):
451| print(f'vector-a (self) = {a}')
452| print(f'vector-b (other) = {b}')
453| print()
454| print(f'{a + b = !s}')
455| print(f'{a - b = !s}')
456| print(f'{a * b = !s}')
457| print(f'{a / b = !s}')
458| print()
459| print(f'{a + 2 = !s}')
460| print(f'{2 + a = !s}')
461| print()
462| print(f'{a - 2 = !s}')
463| print(f'{2 - a = !s}')
464| print()
465| print(f'{a * 2 = !s}')
466| print(f'{2 * a = !s}')
467| print()
468| print(f'{a / 2 = !s}')
469| print(f'{2 / a = !s}')
470| print(f'')
471| print()
472| print()
473|
474| v1 = vector(2.71828, 3.14159, 6.62607, prec=6)
475| v2 = vector(1.00000, 2.00000, 3.00000, prec=6)
476| v3 = vector(0.50000, 0.25000, 0.12500, prec=6)
477|
478| demo_binary_ops(v1, v2)
479| demo_binary_ops(v1, v3)
480| demo_binary_ops(v2, v3)
481|
482|
483| from vector import vector
484|
485| vec = vector(1.6, 2.7)
486|
487| print(f'{vec = !s}')
488| print(f'{vec.x = }')
489| print(f'{vec.y = }')
490| print(f'{vec.z = }')
491| print()
492|
493| vec.x = 42
494| vec.z = 21
495| print(f'{vec = !s}')
496| print(f'{vec.x = }')
497| print(f'{vec.y = }')
498| print(f'{vec.z = }')
499| print()
500|
501|
502| from vector import vector
503|
504| vec = vector(0.510998, 1.618033, 2.718281, 3.141592, 6.626070, prec=2)
505|
506| print(f'{vec = !s}')
507| print()
508|
509|
510|