examples.html


001| '''examples.py'''
002| from os import path
003| import math
004| 
005| ###
006| ### Useful Definitions
007| ###
008| EOF = '\n'
009| 
010| DIG0 = ord('0')
011| UCA = ord('A')
012| LCA = ord('a')
013| 
014| 
015| ###
016| ### Useful Lambda Functions
017| ###
018| kwarg = lambda name,dflt,typ,args: typ(args[name]) if name in args else dflt
019| 
020| typename = lambda obj: type(obj).__name__
021| 
022| list2str = lambda xs,delim: delim.join(str(x) for x in xs)
023| 
024| makefilename = lambda fp,fn: path.join(fp,fn) if fp else fn
025| 
026| 
027| 
028| class Point:
029|     '''A 3D XYZ Point class.'''
030| 
031|     def __init__ (self, x=0.0, y=0.0, z=0.0):
032|         '''New instance.'''
033|         self.x = float(x)
034|         self.y = float(y)
035|         self.z = float(z)
036| 
037| 
038|     def __str__ (self):
039|         '''Return a string version.'''
040|         return f'[{self.x:.3f}, {self.y:.3f}, {self.z:.3f}]'
041| 
042|     def __repr__ (self):
043|         '''Return a debug string.'''
044|         return f'{typename(self)}(x={self.x}, y={self.y}, z={self.z})'
045| 
046| 
047|     def __bool__ (self):
048|         '''Return True (non-zero point) or False (point is zero).'''
049|         return any(self)
050| 
051| 
052|     ### Equality Test ###
053| 
054|     def __eq__ (self, other):
055|         '''Test self & other for equality.'''
056| 
057|         # We need another Point object to test...
058|         if not isinstance(other, type(self)):
059|             raise ValueError(f"Can't compare with a {typename(other)}!")
060| 
061|         # Do an element-by-element comparison...
062|         if self.x != other.x: return False
063|         if self.y != other.y: return False
064|         if self.z != other.z: return False
065| 
066|         # All vector elements are equal...
067|         return True
068| 
069|     def __ne__ (self, other):
070|         '''Test self & other for inequality.'''
071|         return not self.__eq__(other)
072| 
073| 
074|     ### Point Methods ###
075| 
076|     def reset (self):
077|         '''Reset point to default value [0,0,0].'''
078|         self.x = 0.0
079|         self.y = 0.0
080|         self.z = 0.0
081|         return self
082| 
083|     def move (self, x=None, y=None, z=None):
084|         '''Change a point's coordinates.'''
085|         if x is not None: self.x = float(x)
086|         if y is not None: self.y = float(y)
087|         if z is not None: self.z = float(z)
088|         return self
089| 
090|     def distance (self, other):
091|         '''Return the distance between self and other.'''
092|         x2 = pow(self.x - other.x, 2)
093|         y2 = pow(self.y - other.y, 2)
094|         z2 = pow(self.z - other.z, 2)
095|         return math.sqrt(x2 + y2 + z2)
096| 
097|     def dot (self, other):
098|         '''Return the dot product between self and other.'''
099|         xx = self.x * other.x
100|         yy = self.y * other.y
101|         zz = self.z * other.z
102|         return xx + yy + zz
103| 
104|     @property
105|     def magnitude (self):
106|         '''Pythagorean distance from origin.'''
107|         x2 = pow(self.x, 2)
108|         y2 = pow(self.y, 2)
109|         z2 = pow(self.z, 2)
110|         return math.sqrt(x2 + y2 + z2)
111| 
112|     @property
113|     def normalized (self):
114|         '''Return same vector with length one.'''
115|         if not self:
116|             raise ValueError("Can't normalize a null vector!")
117| 
118|         # Normalize by dividing each element by the magnitude...
119|         m = self.magnitude
120|         xn = self.x / m
121|         yn = self.y / m
122|         zn = self.z / m
123|         return Point(xn, yn, zn)
124| 
125|     @property
126|     def polar (self):
127|         '''Return a polar coordinate tuple.'''
128|         radius = self.magnitude
129|         theta = math.atan2(self.y, self.x)
130|         phi = math.atan2(self.z, math.sqrt(pow(self.x,2)+pow(self.y,2)))
131|         return (radius, theta, phi)
132| 
133|     ### Class Methods ###
134| 
135|     @classmethod
136|     def from_polar (cls, radius=1.0, theta=0.0, phi=0.0):
137|         '''Create an XYZ Point from polar coordinates.'''
138|         x = math.cos(theta) * radius * math.cos(phi)
139|         y = math.sin(theta) * radius * math.cos(phi)
140|         z = math.sin(phi) * radius
141|         return cls(x, y, z)
142| 
143|     @classmethod
144|     def xaxis (cls): return cls(1,0,0)
145| 
146|     @classmethod
147|     def yaxis (cls): return cls(0,1,0)
148| 
149|     @classmethod
150|     def zaxis (cls): return cls(0,0,1)
151| 
152| 
153|     ### List Operations ###
154| 
155|     def __len__ (self):
156|         '''Return length (always 3).'''
157|         return 3
158| 
159|     def __getitem__ (self, element_index):
160|         '''Return an element by index (x=0, y=1, z=2).'''
161|         if element_index == 0: return self.x
162|         if element_index == 1: return self.y
163|         if element_index == 2: return self.z
164| 
165|         # Invalid type...
166|         raise IndexError(f"Invalid index: {element_index}")
167| 
168|     def __setitem__ (self, element_index, new_value):
169|         '''Set an element by index (x=0, y=1, z=2).'''
170|         if element_index == 0: self.x = float(new_value); return
171|         if element_index == 1: self.y = float(new_value); return
172|         if element_index == 2: self.z = float(new_value); return
173| 
174|         # Invalid type...
175|         raise IndexError(f"Invalid index: {element_index}")
176| 
177|     def __delitem__ (self, element_index):
178|         '''Delete an element by index (not allowed).'''
179|         raise NotImplementedError(f"Point elements may not be deleted!")
180| 
181| 
182|     #NOTE: Non-ideal; use the version below!
183|     #def __iter__ (self):
184|     # '''Return an iterator over the elements.'''
185|     # return iter([self.x, self.y, self.z])
186| 
187|     def __iter__ (self):
188|         '''Return an iterator (generator).'''
189|         def generator ():
190|             '''Generator function for elements.'''
191|             yield self.x
192|             yield self.y
193|             yield self.z
194| 
195|         # Return a new generator...
196|         return generator()
197| 
198|     #NOTE: Non-ideal; use the version below!
199|     #def __reversed__ (self):
200|     # '''Return a reversed list.'''
201|     # return iter([self.z, self.y, self.x])
202| 
203|     def __reversed__ (self):
204|         '''Return a reversed generator.'''
205|         def generator ():
206|             '''Generator function for reversed elements.'''
207|             yield self.z
208|             yield self.y
209|             yield self.x
210| 
211|         # Return a new generator...
212|         return generator()
213| 
214| 
215|     ### Math Operations ###
216| 
217|     def __abs__ (self):
218|         '''Function abs: apply element-by-element.'''
219|         return Point(abs(self.x), abs(self.y), abs(self.z))
220| 
221|     def __pos__ (self):
222|         '''Operator +: creates a copy.'''
223|         return Point(self.x, self.y, self.z)
224| 
225|     def __neg__ (self):
226|         '''Operator -: memberwise negation.'''
227|         return Point(-self.x, -self.y, -self.z)
228| 
229|     def __invert__ (self):
230|         '''Operator ~: invert members.'''
231|         x = (1.0/self.x if self.x else 0.0)
232|         y = (1.0/self.y if self.y else 0.0)
233|         z = (1.0/self.z if self.z else 0.0)
234|         return Point(x, y, z)
235| 
236| 
237|     ### Addition ###
238| 
239|     def __add__ (self, other):
240|         '''Add self to a point or scalar; return sum in new Point.'''
241| 
242|         # A scalar adds to each member...
243|         if isinstance(other,int) or isinstance(other,float):
244|             x = self.x + other
245|             y = self.y + other
246|             z = self.z + other
247|             return Point(x, y, z)
248| 
249|         # A vector adds memberwise...
250|         if isinstance(other, type(self)):
251|             x = self.x + other.x
252|             y = self.y + other.y
253|             z = self.z + other.z
254|             return Point(x, y, z)
255| 
256|         # Invalid type...
257|         raise ValueError(f"Can't add a {typename(other)}!")
258| 
259|     def __iadd__ (self, other):
260|         '''Add a point or scalar to self; return self.'''
261| 
262|         # A scalar adds to each member...
263|         if isinstance(other,int) or isinstance(other,float):
264|             self.x += other
265|             self.y += other
266|             self.z += other
267|             return self
268| 
269|         # A vector adds memberwise...
270|         if isinstance(other, type(self)):
271|             self.x += other.x
272|             self.y += other.y
273|             self.z += other.z
274|             return self
275| 
276|         # Invalid type...
277|         raise ValueError(f"Can't add a {typename(other)}!")
278| 
279|     # Addition commutes so radd is the same as add...
280|     __radd__ = __add__
281| 
282|     # Alternate dunder radd #1...
283|     #def __radd__ (self, other):
284|     # '''Add scalar number to self; return new Point.'''
285|     #
286|     # # Only called when X + Point, so X is never a Point...
287|     # if isinstance(other,int) or isinstance(other,float):
288|     # return self.__add__(other)
289|     #
290|     # # Invalid type...
291|     # raise ValueError(f"Can't add a {typename(other)}!")
292| 
293|     # Alternate dunder radd #2...
294|     #def __radd__ (self, other):
295|     # '''Add scalar number to self; return new Point.'''
296|     # return self.__add__(other)
297| 
298| 
299|     ### Subtraction ###
300| 
301|     def __sub__ (self, other):
302|         '''Subtract a point or scalar from self; return result in new Point.'''
303| 
304|         # A scalar subtracts from each member...
305|         if isinstance(other,int) or isinstance(other,float):
306|             x = self.x - other
307|             y = self.y - other
308|             z = self.z - other
309|             return Point(x, y, z)
310| 
311|         # A vector subtracts memberwise...
312|         if isinstance(other, type(self)):
313|             x = self.x - other.x
314|             y = self.y - other.y
315|             z = self.z - other.z
316|             return Point(x, y, z)
317| 
318|         # Invalid type...
319|         raise ValueError(f"Can't subtract a {typename(other)}!")
320| 
321|     def __isub__ (self, other):
322|         '''Subtract a point or scalar from self; return self.'''
323| 
324|         # A scalar subtracts from each member...
325|         if isinstance(other,int) or isinstance(other,float):
326|             self.x -= other
327|             self.y -= other
328|             self.z -= other
329|             return self
330| 
331|         # A vector subtracts memberwise...
332|         if isinstance(other, type(self)):
333|             self.x -= other.x
334|             self.y -= other.y
335|             self.z -= other.z
336|             return self
337| 
338|         # Invalid type...
339|         raise ValueError(f"Can't subtract a {typename(other)}!")
340| 
341|     def __rsub__ (self, other):
342|         '''Subtract self from a point or scalar; return new Point.'''
343| 
344|         # Only called when X - Point, so X is never a Point...
345|         if isinstance(other,int) or isinstance(other,float):
346|             x = other - self.x
347|             y = other - self.y
348|             z = other - self.z
349|             return Point(x, y, z)
350| 
351|         # Invalid type...
352|         raise ValueError(f"Can't subtract from a {typename(other)}!")
353| 
354| 
355|     ### Multiplication ###
356| 
357|     def __mul__ (self, other):
358|         '''Multiply self and a point or scalar, return product in new Point.'''
359| 
360|         # A scalar multiplies each member...
361|         if isinstance(other,int) or isinstance(other,float):
362|             x = self.x * other
363|             y = self.y * other
364|             z = self.z * other
365|             return Point(x, y, z)
366| 
367|         # A vector multiplies memberwise...
368|         if isinstance(other, type(self)):
369|             x = self.x * other.x
370|             y = self.y * other.y
371|             z = self.z * other.z
372|             return Point(x, y, z)
373| 
374|         # Invalid type...
375|         raise ValueError(f"Can't multiply a {typename(other)}!")
376| 
377|     def __imul__ (self, other):
378|         '''Multiply self by a point or scalar; return self.'''
379| 
380|         # A scalar multiplies each member...
381|         if isinstance(other,int) or isinstance(other,float):
382|             self.x *= other
383|             self.y *= other
384|             self.z *= other
385|             return self
386| 
387|         # A vector multiplies memberwise...
388|         if isinstance(other, type(self)):
389|             self.x *= other.x
390|             self.y *= other.y
391|             self.z *= other.z
392|             return self
393| 
394|         # Invalid type...
395|         raise ValueError(f"Can't multiply a {typename(other)}!")
396| 
397|     # Multiplication commutes so rmul is the same as mul!
398|     __rmul__ = __mul__
399| 
400|     # Alternate dunder rmul #1...
401|     #def __rmul__ (self, other):
402|     # '''Multiply self by scalar number; return new Point.'''
403|     # if isinstance(other,int) or isinstance(other,float):
404|     # x = self.x * other
405|     # y = self.y * other
406|     # z = self.z * other
407|     # return Point(x, y, z)
408|     #
409|     # # Invalid type...
410|     # raise ValueError(f"Can't multiply a {typename(other)}!")
411| 
412| 
413|     ### Division ###
414| 
415|     def __truediv__ (self, other):
416|         '''Divide self by a point or scalar; return result in new Point.'''
417| 
418|         # A scalar divides each member...
419|         if isinstance(other,int) or isinstance(other,float):
420|             x = self.x / other
421|             y = self.y / other
422|             z = self.z / other
423|             return Point(x, y, z)
424| 
425|         # A vector divides memberwise...
426|         if isinstance(other, type(self)):
427|             x = self.x / other.x
428|             y = self.y / other.y
429|             z = self.z / other.z
430|             return Point(x, y, z)
431| 
432|         # Invalid type...
433|         raise ValueError(f"Can't divide by a {typename(other)}!")
434| 
435|     def __itruediv__ (self, other):
436|         '''Divide self by a point or scalar; return self.'''
437| 
438|         # A scalar divides each member...
439|         if isinstance(other,int) or isinstance(other,float):
440|             self.x /= other
441|             self.y /= other
442|             self.z /= other
443|             return self
444| 
445|         # A vector divides memberwise...
446|         if isinstance(other, type(self)):
447|             self.x /= other.x
448|             self.y /= other.y
449|             self.z /= other.z
450|             return self
451| 
452|         # Invalid type...
453|         raise ValueError(f"Can't divide by a {typename(other)}!")
454| 
455|     def __rtruediv__ (self, other):
456|         '''Divide a point or scalar by self; return result in new Point.'''
457| 
458|         # A scalar divides by each member...
459|         if isinstance(other,int) or isinstance(other,float):
460|             x = other / self.x
461|             y = other / self.y
462|             z = other / self.z
463|             return Point(x, y, z)
464| 
465|         # A vector divides memberwise...
466|         if isinstance(other, type(self)):
467|             x = other.x / self.x
468|             y = other.y / self.y
469|             z = other.z / self.z
470|             return Point(x, y, z)
471| 
472|         # Invalid type...
473|         raise ValueError(f"Can't divide a {typename(other)}!")
474| 
475| 
476|     ### LOGICAL OPERATIONS ###
477| 
478|     def __and__ (self, other):
479|         '''AND self with point or scalar; return result in new Point.'''
480| 
481|         # A scalar ANDs with each member...
482|         if isinstance(other,int) or isinstance(other,float):
483|             x = self.x & other
484|             y = self.y & other
485|             z = self.z & other
486|             return Point(x, y, z)
487| 
488|         # A vector ANDs memberwise...
489|         if isinstance(other, type(self)):
490|             x = self.x & other.x
491|             y = self.y & other.y
492|             z = self.z & other.z
493|             return Point(x, y, z)
494| 
495|         # Invalid type...
496|         raise ValueError(f"Can't AND a {typename(other)}!")
497| 
498|     def __or__ (self, other):
499|         '''OR self with point or scalar; return result in new Point.'''
500| 
501|         # A scalar ANDs with each member...
502|         if isinstance(other,int) or isinstance(other,float):
503|             x = self.x | other
504|             y = self.y | other
505|             z = self.z | other
506|             return Point(x, y, z)
507| 
508|         # A vector ANDs memberwise...
509|         if isinstance(other, type(self)):
510|             x = self.x | other.x
511|             y = self.y | other.y
512|             z = self.z | other.z
513|             return Point(x, y, z)
514| 
515|         # Invalid type...
516|         raise ValueError(f"Can't OR a {typename(other)}!")
517| 
518|     def __xor__ (self, other):
519|         '''XOR self with point or scalar; return result in new Point.'''
520| 
521|         # A scalar ANDs with each member...
522|         if isinstance(other,int) or isinstance(other,float):
523|             x = self.x ^ other
524|             y = self.y ^ other
525|             z = self.z ^ other
526|             return Point(x, y, z)
527| 
528|         # A vector ANDs memberwise...
529|         if isinstance(other, type(self)):
530|             x = self.x ^ other.x
531|             y = self.y ^ other.y
532|             z = self.z ^ other.z
533|             return Point(x, y, z)
534| 
535|         # Invalid type...
536|         raise ValueError(f"Can't XOR a {typename(other)}!")
537| 
538|     def __iand__ (self, other):
539|         '''AND self with point or scalar; return self.'''
540| 
541|         # A scalar ANDs with each member...
542|         if isinstance(other,int) or isinstance(other,float):
543|             self.x &= other
544|             self.y &= other
545|             self.z &= other
546|             return self
547| 
548|         # A vector ANDs memberwise...
549|         if isinstance(other, type(self)):
550|             self.x &= other.x
551|             self.y &= other.y
552|             self.z &= other.z
553|             return self
554| 
555|         # Invalid type...
556|         raise ValueError(f"Can't AND a {typename(other)}!")
557| 
558|     def __ior__ (self, other):
559|         '''OR self with point or scalar; return self.'''
560| 
561|         # A scalar ANDs with each member...
562|         if isinstance(other,int) or isinstance(other,float):
563|             self.x |= other
564|             self.y |= other
565|             self.z |= other
566|             return self
567| 
568|         # A vector ANDs memberwise...
569|         if isinstance(other, type(self)):
570|             self.x |= other.x
571|             self.y |= other.y
572|             self.z |= other.z
573|             return self
574| 
575|         # Invalid type...
576|         raise ValueError(f"Can't OR a {typename(other)}!")
577| 
578|     def __ixor__ (self, other):
579|         '''XOR self with point or scalar; return self.'''
580| 
581|         # A scalar ANDs with each member...
582|         if isinstance(other,int) or isinstance(other,float):
583|             self.x ^= other
584|             self.y ^= other
585|             self.z ^= other
586|             return self
587| 
588|         # A vector ANDs memberwise...
589|         if isinstance(other, type(self)):
590|             self.x ^= other.x
591|             self.y ^= other.y
592|             self.z ^= other.z
593|             return self
594| 
595|         # Invalid type...
596|         raise ValueError(f"Can't XOR a {typename(other)}!")
597| 
598|     # Logical operations all commute...
599|     __rand__ = __and__
600|     __ror__ = __or__
601|     __rxor__ = __xor__
602| 
603| 
604| 
605| '''eof'''
606|