matrix.html


001| '''Matrices.
001| 
001| Classes:
001|     matrix              - general matrix class
001|     matrix2d            - 2D matrix [2x2]
001|     matrix3d            - 3D matrix [3x3]
001|     matrix4d            - 4D matrix [4x4]
001| 
001|     mvector2d           - 2D matrix column vector [2x1]
001|     mvector3d           - 3D matrix column vector [3x1]
001|     mvector4d           - 4D matrix column vector [4x1]
001| 
001|     mlorentz            - 2D Lorentz (gamma factor) matrix [2x2]
001| 
001|     rotate2d            - 2D rotation matrix [2x2]
001|     rotate3d            - 3D rotation matrix [3x3] (base class)
001|     rotate4d            - 4D rotation matrix [4x4] (base class)
001| 
001|     rotate3d_x          - 3D x-axis rotation matrix [3x3]
001|     rotate3d_y          - 3D y-axis rotation matrix [3x3]
001|     rotate3d_z          - 3D z-axis rotation matrix [3x3]
001| 
001|     rotate4d_xw         - 4D xw-axis rotation matrix [4x4]
001|     rotate4d_yw         - 4D yw-axis rotation matrix [4x4]
001|     rotate4d_zw         - 4D zw-axis rotation matrix [4x4]
001|     rotate4d_xy         - 4D xy-axis rotation matrix [4x4]
001|     rotate4d_xz         - 4D xz-axis rotation matrix [4x4]
001|     rotate4d_yz         - 4D yz-axis rotation matrix [4x4]
001| 
001|     rotate2d_0          - 2D 0 degrees rotation matrix [2x2] (identity matrix)
001|     rotate2d_90         - 2D 90 degrees rotation matrix [2x2]
001|     rotate2d_180        - 2D 180 degrees rotation matrix [2x2]
001|     rotate2d_270        - 2D 2700 degrees rotation matrix [2x2]
001| 
001|     rotate3d_x_0        - 3D 0 degrees x-axis rotation matrix [3x3] (identity matrix)
001|     rotate3d_x_90       - 3D 90 degrees x-axis rotation matrix [3x3]
001|     rotate3d_x_180      - 3D 180 degrees x-axis rotation matrix [3x3]
001|     rotate3d_x_270      - 3D 2700 degrees x-axis rotation matrix [3x3]
001| 
001|     rotate3d_y_0        - 3D 0 degrees y-axis rotation matrix [3x3] (identity matrix)
001|     rotate3d_y_90       - 3D 90 degrees y-axis rotation matrix [3x3]
001|     rotate3d_y_180      - 3D 180 degrees y-axis rotation matrix [3x3]
001|     rotate3d_y_270      - 3D 2700 degrees y-axis rotation matrix [3x3]
001| 
001|     rotate3d_z_0        - 3D 0 degrees z-axis rotation matrix [3x3] (identity matrix)
001|     rotate3d_z_90       - 3D 90 degrees z-axis rotation matrix [3x3]
001|     rotate3d_z_180      - 3D 180 degrees z-axis rotation matrix [3x3]
001|     rotate3d_z_270      - 3D 2700 degrees z-axis rotation matrix [3x3]
001| 
001| '''

002| ####################################################################################################
003| from sys import argv
004| from os import path
005| from math import sqrt, sin,cos, radians,degrees
006| from goodies import typename
007| from vector import vector
008| ####################################################################################################
009| 
010| 
011| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
012| class matrix (object):
013|     '''Basic Matrix Object (with Matrix Multiply).
013| 
013| Instance Arguments:
013|     rows            - number of matrix rows
013|     cols            - number of matrix columns
013| 
013| Instance Properties:
013|     m               - matrix (row list of column lists)
013| 
013| Instance Methods:
013|     rows            - return number of matrix rows
013|     cols            - return number of matrix cols
013|     row(rx)         - return a given row (as a list)
013|     col(cx)         - return a given col (as a list)
013|     rowvec(rx)      - return a given row (as vector object)
013|     colvec(rx)      - return a given col (as vector object)
013|     trace           - return matrix trace value (if rows=cols)
013|     transpose       - return the transpose of self
013|     obj(r,c)        - return a given row and col
013|     str(obj)        - string version (pretty)
013|     repr(obj)       - string version (JSON-like)
013| '''

014|     sRepr = '{%s:{rows:%d, cols:%d}}'
015|     eType = 'Invalid type: %s'
016|     eColRow = 'A.cols (%d) not same as B.rows (%d)'
017|     eRowCol = 'A.rows (%d) not same as B.cols (%d)'
018|     eColVec = 'Expected a column vector %s'
019|     eRowVec = 'Expected a row vector %s'
020| 
021|     def __init__ (self, rows=4, cols=1, data=[]):
022|         value = lambda: data.pop(0) if len(data) else 0.0
023|         self.m = [[value() for c in range(cols)] for r in range(rows)]
024| 
025|     def rows (self): return len(self.m)
026|     def cols (self): return len(self.m[0])
027| 
028|     def row (self, rx): return self.m[rx]
029|     def col (self, cx): return [r[cx] for r in self.m]
030| 
031|     def rowvec (self, rx): return vector(*self.m[rx])
032|     def colvec (self, cx): return vector(*[r[cx] for r in self.m])
033| 
034|     def transpose (self):
035|         '''Return a (new) transposed matrix.'''
036|         mt = matrix(rows=self.cols(), cols=self.rows())
037|         for rx in range(self.rows()):
038|             for cx in range(self.cols()):
039|                 mt.m[cx][rx] = self.m[rx][cx]
040|         return mt
041| 
042|     def trace (self):
043|         '''Return a matrix trace.'''
044|         if self.rows() != self.cols():
045|             raise TypeError('Trace requires matching row and column counts.')
046|         total = 0.0
047|         for ix in range(self.rows()):
048|             total += self.m[ix][ix]
049|         return total
050| 
051|     def inner (self, other):
052|         '''Inner product. (self=col-vector, other=row-vector)'''
053|         assert isinstance(other,matrix), TypeError(matrix.eType % type(other).__name__)
054|         assert self.cols()==1, TypeError(matrix.eColVec % 'as the caller.')
055|         assert other.rows()==1, TypeError(matrix.eRowVec % 'as the parameter.')
056|         assert self.rows()==other.cols(), TypeError(matrix.eRowCol % (self.rows(),other.cols()))
057|         acc = 0
058|         for ix in range(self.rows()):
059|             acc += (self(ix,0) * other(0,ix))
060|         return acc
061| 
062|     def outer (self, other):
063|         '''Outer product. (self=col-vector, other=row-vector)'''
064|         assert isinstance(other,matrix), TypeError(matrix.eType % type(other).__name__)
065|         assert self.cols()==1, TypeError(matrix.eColVec % 'as the caller.')
066|         assert other.rows()==1, TypeError(matrix.eRowVec % 'as the parameter.')
067|         assert self.rows()==other.cols(), TypeError(matrix.eRowCol % (self.rows(),other.cols()))
068|         op = matrix(self.rows(), self.rows())
069|         for rx in range(self.rows()):
070|             for cx in range(self.rows()):
071|                 op(rx,cx, self(rx,0) * other(0,cx))
072|         return op
073| 
074|     def __call__ (self, row=0, col=0, val=None):
075|         '''Access matrix element by row,col.'''
076|         if val is not None:
077|             self.m[row][col] = val
078|         return self.m[row][col]
079| 
080|     def __str__ (self):
081|         return '[%s]' % '\n '.join([str(r) for r in self.m])
082| 
083|     def __repr__ (self):
084|         return matrix.sRepr % (typename(self), self.rows(), self.cols())
085| 
086|     def __add__ (self, other):
087|         '''Add another matrix or a scalar. Returns new matrix.'''
088|         if isinstance(other,matrix):
089|             return self._matrix_oper_other(other, lambda a,v:(a+v))
090|         if isinstance(other,float) or isinstance(other,int):
091|             return self._matrix_oper(lambda v:(v+other))
092|         raise TypeError(matrix.eType % type(other))
093| 
094|     def __sub__ (self, other):
095|         '''Subtract another matrix or a scalar. Returns new matrix.'''
096|         if isinstance(other,matrix):
097|             return self._matrix_oper_other(other, lambda a,v:(a-v))
098|         if isinstance(other,float) or isinstance(other,int):
099|             return self._matrix_oper(lambda v:(v-other))
100|         raise TypeError(matrix.eType % type(other))
101| 
102|     def __mul__ (self, other):
103|         '''Multiply by another matrix or a scalar. Returns new matrix.'''
104|         if isinstance(other,matrix):
105|             return self._matrix_multiply(other)
106|         if isinstance(other,float) or isinstance(other,int):
107|             return self._matrix_oper(lambda v:(v*other))
108|         raise TypeError(matrix.eType % type(other))
109| 
110|     def __truediv__ (self, other):
111|         '''Divide by another matrix or a scalar. Returns new matrix.'''
112|         if isinstance(other,float) or isinstance(other,int):
113|             return self._matrix_oper(lambda v:(v/other))
114|         raise TypeError(matrix.eType % type(other))
115| 
116|     def __iadd__ (self, other):
117|         '''Add another matrix or a scalar from this matrix.'''
118|         if isinstance(other,matrix):
119|             return self._matrix_oper_self_other(other, lambda a,v:(a+v))
120|         if isinstance(other,float) or isinstance(other,int):
121|             return self._matrix_oper_self(lambda v:(v+other))
122|         raise TypeError(matrix.eType % type(other))
123| 
124|     def __isub__ (self, other):
125|         '''Subtract another matrix or a scalar from this matrix.'''
126|         if isinstance(other,matrix):
127|             return self._matrix_oper_self_other(other, lambda a,v:(a-v))
128|         if isinstance(other,float) or isinstance(other,int):
129|             return self._matrix_oper_self(lambda v:(v-other))
130|         raise TypeError(matrix.eType % type(other))
131| 
132|     def __imul__ (self, scalar):
133|         '''Multiply this matrix by a scalar.'''
134|         if isinstance(scalar,float) or isinstance(scalar,int):
135|             return self._matrix_oper_self(lambda v:(v*scalar))
136|         raise TypeError(matrix.eType % type(scalar))
137| 
138|     def __itruediv__ (self, scalar):
139|         '''Divide this matrix by a scalar.'''
140|         if isinstance(scalar,float) or isinstance(scalar,int):
141|             return self._matrix_oper_self(lambda v:(v/scalar))
142|         raise TypeError(matrix.eType % type(scalar))
143| 
144|     def _matrix_oper_self (self, ftn):
145|         '''Apply an operation to this matrix.'''
146|         nr,nc = self.rows(), self.cols()
147|         for rx in range(nr):
148|             for cx in range(nc):
149|                 self.m[rx][cx] = ftn(self.m[rx][cx])
150|         return self
151| 
152|     def _matrix_oper_self_other (self, other, ftn):
153|         '''Apply an operation with another matrix to this matrix.'''
154|         nr,nc = self.rows(), self.cols()
155|         for rx in range(nr):
156|             for cx in range(nc):
157|                 self.m[rx][cx] = ftn(self.m[rx][cx], other.m[rx][cx])
158|         return self
159| 
160|     def _matrix_oper (self, ftn):
161|         '''Apply an operation with this matrix to a new matrix. Returns new matrix.'''
162|         nr,nc = self.rows(), self.cols()
163|         obj = self.__class__()
164|         obj.m = [[0.0 for c in range(nc)] for r in range(nr)]
165|         for rx in range(nr):
166|             for cx in range(nc):
167|                 obj.m[rx][cx] = ftn(self.m[rx][cx])
168|         return obj
169| 
170|     def _matrix_oper_other (self, other, ftn):
171|         '''Apply an operation with this matrix and another matrix to a new matrix. Returns new matrix.'''
172|         nr,nc = self.rows(), self.cols()
173|         obj = other.__class__()
174|         obj.m = [[0.0 for c in range(nc)] for r in range(nr)]
175|         for rx in range(nr):
176|             for cx in range(nc):
177|                 obj.m[rx][cx] = ftn(self.m[rx][cx], other.m[rx][cx])
178|         return obj
179| 
180|     def _matrix_multiply (self, other):
181|         '''Matrix multiplication. Returns new matrix.'''
182|         assert self.cols()==other.rows(), TypeError(matrix.eColRow % (self.cols(),other.rows()))
183|         nr,ni,nc = self.rows(), self.cols(), other.cols()
184|         obj = other.__class__()
185|         obj.m = [[0.0 for c in range(nc)] for r in range(nr)]
186|         for rx in range(nr):
187|             row = self.m[rx]
188|             for cx in range(nc):
189|                 obj.m[rx][cx] = sum([row[ix] * other.m[ix][cx] for ix in range(ni)])
190|         return obj
191| 
192| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
193| class mvector2d (matrix):
194|     '''2D Point Matrix.
194| 
194| Instance Arguments:
194|     x               - X coordinate
194|     y               - Y coordinate
194| 
194| Instance Methods:
194|     astuple         - return as tuple
194|     aslist          - return as list
194|     obj[ix]         - get/set vector member
194|     str(obj)        - string version (pretty)
194|     repr(obj)       - string version (JSON-like)
194| '''

195|     def __init__ (self, x=0.0, y=0.0):
196|         super().__init__(rows=2, cols=1)
197|         self.m[0][0] = x
198|         self.m[1][0] = y
199| 
200|     def astuple (self): return (self.x, self.y)
201|     def aslist (self): return [self.x, self.y]
202| 
203|     def __getattr__ (self, name):
204|         if name == 'x': return self.m[0][0]
205|         if name == 'y': return self.m[1][0]
206|         super().__getattr__(name)
207| 
208|     def __setattr__ (self, name, value):
209|         if name == 'x': self.m[0][0] = value; return
210|         if name == 'y': self.m[1][0] = value; return
211|         super().__setattr__(name, value)
212| 
213|     def __bool__ (self):
214|         if self.m[0][0]: return True
215|         if self.m[1][0]: return True
216|         return False
217| 
218|     def __len__ (self): return len(self.m)
219| 
220|     def __iter__ (self): return iter([self.m[0][0], self.m[1][0]])
221| 
222|     def __getitem__ (self, ix):
223|         '''Get vector item.'''
224|         return self.m[ix][0]
225| 
226|     def __setitem__ (self, ix, value):
227|         '''Set vector item.'''
228|         self.m[ix][0] = value
229| 
230|     def __delitem__ (self, ix):
231|         '''"Delete" vector item (set to zero).'''
232|         self.m[ix][0] = 0
233| 
234|     def __str__ (self):
235|         return '[%s, %s]' % (self.x, self.y)
236| 
237|     def __repr__ (self):
238|         s = '{%s:{x:%s, y:%s}}'
239|         t = (typename(self), self.x, self.y)
240|         return s%t
241| 
242| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
243| class mvector3d (matrix):
244|     '''3D Point Matrix.
244| 
244| Instance Arguments:
244|     x               - X coordinate
244|     y               - Y coordinate
244|     z               - Z coordinate
244| 
244| Instance Methods:
244|     astuple         - return as tuple
244|     aslist          - return as list
244|     obj[ix]         - get/set vector member
244|     str(obj)        - string version (pretty)
244|     repr(obj)       - string version (JSON-like)
244| '''

245|     def __init__ (self, x=0.0, y=0.0, z=0.0):
246|         super().__init__(rows=3, cols=1)
247|         self.m[0][0] = x
248|         self.m[1][0] = y
249|         self.m[2][0] = z
250| 
251|     def astuple (self): return (self.x, self.y, self.z)
252|     def aslist (self): return [self.x, self.y, self.z]
253| 
254|     def __getattr__ (self, name):
255|         if name == 'x': return self.m[0][0]
256|         if name == 'y': return self.m[1][0]
257|         if name == 'z': return self.m[2][0]
258|         super().__getattr__(name)
259| 
260|     def __setattr__ (self, name, value):
261|         if name == 'x': self.m[0][0] = value; return
262|         if name == 'y': self.m[1][0] = value; return
263|         if name == 'z': self.m[2][0] = value; return
264|         super().__setattr__(name, value)
265| 
266|     def __bool__ (self):
267|         if self.m[0][0]: return True
268|         if self.m[1][0]: return True
269|         if self.m[2][0]: return True
270|         return False
271| 
272|     def __len__ (self): return len(self.m)
273| 
274|     def __iter__ (self):
275|         return iter([self.m[0][0], self.m[1][0], self.m[2][0]])
276| 
277|     def __getitem__ (self, ix):
278|         '''Get vector item.'''
279|         return self.m[ix][0]
280| 
281|     def __setitem__ (self, ix, value):
282|         '''Set vector item.'''
283|         self.m[ix][0] = value
284| 
285|     def __delitem__ (self, ix):
286|         '''"Delete" vector item (set to zero).'''
287|         self.m[ix][0] = 0
288| 
289|     def __str__ (self):
290|         return '[%s, %s, %s]' % (self.x, self.y, self.z)
291| 
292|     def __repr__ (self):
293|         s = '{%s:{x:%s, y:%s, z:%s}}'
294|         t = (typename(self), self.x, self.y, self.z)
295|         return s%t
296| 
297| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
298| class mvector4d (matrix):
299|     '''4D Point Matrix.
299| 
299| Instance Arguments:
299|     x               - X coordinate
299|     y               - Y coordinate
299|     z               - Z coordinate
299|     w               - W coordinate
299| 
299| Instance Methods:
299|     astuple         - return as tuple
299|     aslist          - return as list
299|     obj[ix]         - get/set vector member
299|     str(obj)        - string version (pretty)
299|     repr(obj)       - string version (JSON-like)
299| '''

300|     def __init__ (self, x=0.0, y=0.0, z=0.0, w=0.0):
301|         super().__init__(rows=4, cols=1)
302|         self.m[0][0] = x
303|         self.m[1][0] = y
304|         self.m[2][0] = z
305|         self.m[3][0] = w
306| 
307|     def astuple (self): return (self.x, self.y, self.z, self.w)
308|     def aslist (self): return [self.x, self.y, self.z, self.w]
309| 
310|     def __getattr__ (self, name):
311|         if name == 'x': return self.m[0][0]
312|         if name == 'y': return self.m[1][0]
313|         if name == 'z': return self.m[2][0]
314|         if name == 'w': return self.m[3][0]
315|         super().__getattr__(name)
316| 
317|     def __setattr__ (self, name, value):
318|         if name == 'x': self.m[0][0] = value; return
319|         if name == 'y': self.m[1][0] = value; return
320|         if name == 'z': self.m[2][0] = value; return
321|         if name == 'w': self.m[3][0] = value; return
322|         super().__setattr__(name, value)
323| 
324|     def __bool__ (self):
325|         if self.m[0][0]: return True
326|         if self.m[1][0]: return True
327|         if self.m[2][0]: return True
328|         if self.m[3][0]: return True
329|         return False
330| 
331|     def __len__ (self): return len(self.m)
332| 
333|     def __iter__ (self):
334|         return iter([self.m[0][0], self.m[1][0], self.m[2][0], self.m[3][0]])
335| 
336|     def __getitem__ (self, ix):
337|         '''Get vector item.'''
338|         return self.m[ix][0]
339| 
340|     def __setitem__ (self, ix, value):
341|         '''Set vector item.'''
342|         self.m[ix][0] = value
343| 
344|     def __delitem__ (self, ix):
345|         '''"Delete" vector item (set to zero).'''
346|         self.m[ix][0] = 0
347| 
348|     def __str__ (self):
349|         return '[%s, %s, %s, %s]' % (self.x, self.y, self.z, self.w)
350| 
351|     def __repr__ (self):
352|         s = '{%s:{x:%s, y:%s, z:%s, w:%s}}'
353|         t = (typename(self), self.x, self.y, self.z, self.w)
354|         return s%t
355| 
356| 
357| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
358| class matrix2d (matrix):
359|     '''2D Transformation Matrix.
359| 
359| Instance Arguments:
359|     vals            - array of 4 values for the matrix (L->R, T->B)
359| 
359| Instance Properties:
359|     a               - array member [0][0]
359|     b               - array member [0][1]
359|     c               - array member [1][0]
359|     d               - array member [1][1]
359| 
359| Instance Methods:
359|     det             - determinant
359|     inv             - inverse
359|     str(obj)
359| '''

360|     def __init__ (self, vals=[]):
361|         super().__init__(rows=2, cols=2)
362|         if len(vals) == 4:
363|             self.m[0][0] = vals[0]
364|             self.m[0][1] = vals[1]
365|             self.m[1][0] = vals[2]
366|             self.m[1][1] = vals[3]
367| 
368|     def __getattr__ (self, name):
369|         if name == 'a': return self.m[0][0]
370|         if name == 'b': return self.m[0][1]
371|         if name == 'c': return self.m[1][0]
372|         if name == 'd': return self.m[1][1]
373|         super().__getattr__(name)
374| 
375|     def __setattr__ (self, name, value):
376|         if name == 'a': self.m[0][0] = value; return
377|         if name == 'b': self.m[0][1] = value; return
378|         if name == 'c': self.m[1][0] = value; return
379|         if name == 'd': self.m[1][1] = value; return
380|         super().__setattr__(name, value)
381| 
382|     def det (self):
383|         '''Matrix determinant.'''
384|         return ((self.a * self.d) - (self.b * self.c))
385| 
386|     def inv (self):
387|         '''Matrix inverse. also: 1/det(M)[I*trace(M) - M]'''
388|         d0 = self.det()
389|         if d0 == 0:
390|             raise RuntimeError('Cannot invert matrix with determinant of 0!')
391|         d1 = 1.0 / d0
392|         A = d1 * self.a
393|         B = d1 * self.b
394|         C = d1 * self.c
395|         D = d1 * self.d
396|         vs = [D, -B, -C, A]
397|         return matrix2d(vs)
398| 
399|     def __str__ (self):
400|         return '[[%f, %f] [%f, %f]]' % (self.a, self.b, self.c, self.d)
401| 
402| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
403| class mlorentz (matrix2d):
404|     '''2D Lorentz Transformation Matrix.
404| 
404| Instance Arguments:
404|     v_c             - velocity as a fraction of c (i.e. v/c)
404| 
404| '''

405|     def __init__ (self, v_c):
406|         gamma = 1.0 / sqrt(1.0 - (v_c*v_c))
407|         super().__init__([gamma, v_c*gamma, v_c*gamma, gamma])
408| 
409| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
410| class rotate2d (matrix2d):
411|     '''2D Rotation Matrix.
411| 
411| Instance Arguments:
411|     angle           - rotation angle
411| 
411| Instance Methods:
411|     rotate(vec)     - rotate vector; returns new mvector
411| '''

412|     def __init__ (self, angle=0.0):
413|         super().__init__()
414|         self.a = angle
415|         self.r = radians(self.a)
416|         self.m = [[cos(self.r), -sin(self.r)], [sin(self.r), cos(self.r)]]
417| 
418|     def rotate (self, vec):
419|         '''Rotate vec. Returns new mvector.'''
420|         assert vec.cols()==1, TypeError('Not a column vector! (cols=%d)' % vec.cols())
421|         assert vec.rows()==2, TypeError('Not a 2D vector! (rows=%d)' % vec.rows())
422|         x = (self.m[0][0]*vec.m[0][0]) + (self.m[0][1]*vec.m[1][0])
423|         y = (self.m[1][0]*vec.m[0][0]) + (self.m[1][1]*vec.m[1][0])
424|         return mvector2d(x,y)
425| 
426| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
427| class rotate2d_0 (rotate2d):
428|     '''2D Rotate 0 degrees (on Z Axis).'''
429|     def __init__ (self):
430|         super().__init__(0.0)
431|         self.m = [[1.0, 0.0], [0.0, 1.0]]
432| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
433| class rotate2d_90 (rotate2d):
434|     '''2D Rotate 90 degrees (on Z Axis).'''
435|     def __init__ (self):
436|         super().__init__(90.0)
437|         self.m = [[0.0, -1.0], [1.0, 0.0]]
438| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
439| class rotate2d_180 (rotate2d):
440|     '''2D Rotate 180 degrees (on Z Axis).'''
441|     def __init__ (self):
442|         super().__init__(180.0)
443|         self.m = [[-1.0, 0.0], [0.0, -1.0]]
444| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
445| class rotate2d_270 (rotate2d):
446|     '''2D Rotate 270 degrees (on Z Axis).'''
447|     def __init__ (self):
448|         super().__init__(270.0)
449|         self.m = [[0.0, 1.0], [-1.0, 0.0]]
450| 
451| 
452| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
453| class matrix3d (matrix):
454|     '''3D Transformation Matrix.
454| 
454| Instance Arguments:
454|     vals            - array of 9 values for the matrix (L->R, T->B)
454| 
454| Instance Methods:
454|     det             - determinant
454|     inv             - inverse
454| '''

455|     def __init__ (self, vals=[]):
456|         super().__init__(rows=3, cols=3)
457|         if len(vals) == 9:
458|             self.m[0][0] = vals[0]
459|             self.m[0][1] = vals[1]
460|             self.m[0][2] = vals[2]
461|             self.m[1][0] = vals[3]
462|             self.m[1][1] = vals[4]
463|             self.m[1][2] = vals[5]
464|             self.m[2][0] = vals[6]
465|             self.m[2][1] = vals[7]
466|             self.m[2][2] = vals[8]
467| 
468|     def det (self):
469|         a = self.m[0][0] * self.m[1][1] * self.m[2][2]
470|         b = self.m[0][1] * self.m[1][2] * self.m[2][0]
471|         c = self.m[0][2] * self.m[1][0] * self.m[2][1]
472|         d = self.m[2][0] * self.m[1][1] * self.m[0][2]
473|         e = self.m[2][1] * self.m[1][2] * self.m[0][0]
474|         f = self.m[2][2] * self.m[1][0] * self.m[0][1]
475|         return ((a+b+c)-(d+e+f))
476| 
477|     def inv (self):
478|         d0 = self.det()
479|         if d0 == 0:
480|             raise RuntimeError('Cannot invert matrix with determinant of 0!')
481|         d1 = 1.0 / d0
482|         A = d1 * ((self.m[1][1] * self.m[2][2])-(self.m[1][2] * self.m[2][1])) # ei-fh
483|         B = d1 * ((self.m[1][0] * self.m[2][2])-(self.m[1][2] * self.m[2][0])) # di-fg
484|         C = d1 * ((self.m[1][0] * self.m[2][1])-(self.m[1][1] * self.m[2][0])) # dh-eg
485|         D = d1 * ((self.m[0][1] * self.m[2][2])-(self.m[0][2] * self.m[2][1])) # bi-ch
486|         E = d1 * ((self.m[0][0] * self.m[2][2])-(self.m[0][2] * self.m[2][0])) # ai-cg
487|         F = d1 * ((self.m[0][0] * self.m[2][1])-(self.m[0][1] * self.m[2][0])) # ah-bg
488|         G = d1 * ((self.m[0][1] * self.m[1][2])-(self.m[0][2] * self.m[1][1])) # bf-ce
489|         H = d1 * ((self.m[0][0] * self.m[1][2])-(self.m[0][2] * self.m[1][0])) # af-cd
490|         I = d1 * ((self.m[0][0] * self.m[1][1])-(self.m[0][1] * self.m[1][0])) # ae-bd
491|         vs = [A,-D,G, -B,E,-H, C,-F,I]
492|         return matrix3d(vs)
493| 
494| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
495| class rotate3d (matrix3d):
496|     '''3D Rotate Base Class.
496| 
496| Instance Arguments:
496|     angle           - rotation angle
496| 
496| Instance Methods:
496|     rotate(vec)     - rotate vector; returns new mvector
496| '''

497|     def __init__ (self, angle=0.0):
498|         super().__init__()
499|         self.a = angle
500|         self.r = radians(self.a)
501| 
502|     def rotate (self, vec):
503|         '''Rotate vec. Returns new mvector.'''
504|         assert vec.cols()==1, TypeError('Not a column vector! (cols=%d)' % vec.cols())
505|         assert vec.rows()==3, TypeError('Not a 3D vector! (rows=%d)' % vec.rows())
506|         x = (self.m[0][0]*vec.m[0][0]) + (self.m[0][1]*vec.m[1][0]) + (self.m[0][2]*vec.m[2][0])
507|         y = (self.m[1][0]*vec.m[0][0]) + (self.m[1][1]*vec.m[1][0]) + (self.m[1][2]*vec.m[2][0])
508|         z = (self.m[2][0]*vec.m[0][0]) + (self.m[2][1]*vec.m[1][0]) + (self.m[2][2]*vec.m[2][0])
509|         return mvector3d(x,y,z)
510| 
511| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
512| class rotate3d_x (rotate3d):
513|     '''3D Rotate on X Axis.
513| 
513| Instance Arguments:
513|     angle           - rotation angle
513| '''

514|     def __init__ (self, angle=0.0):
515|         super().__init__(angle)
516|         self.m[0] = [1.0,         0.0,          0.0]
517|         self.m[1] = [0.0, cos(self.r), -sin(self.r)]
518|         self.m[2] = [0.0, sin(self.r),  cos(self.r)]
519| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
520| class rotate3d_x_0 (rotate3d):
521|     '''3D Rotate 0 degrees on X Axis.'''
522|     def __init__ (self):
523|         super().__init__(0.0)
524|         self.m = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
525| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
526| class rotate3d_x_90 (rotate3d):
527|     '''3D Rotate 90 degrees on X Axis.'''
528|     def __init__ (self):
529|         super().__init__(90.0)
530|         self.m = [[1.0, 0.0, 0.0], [0.0, 0.0,-1.0], [0.0, 1.0, 0.0]]
531| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
532| class rotate3d_x_180 (rotate3d):
533|     '''3D Rotate 180 degrees on X Axis.'''
534|     def __init__ (self):
535|         super().__init__(180.0)
536|         self.m = [[1.0, 0.0, 0.0], [0.0,-1.0, 0.0], [0.0, 0.0,-1.0]]
537| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
538| class rotate3d_x_270 (rotate3d):
539|     '''3D Rotate 270 degrees on X Axis.'''
540|     def __init__ (self):
541|         super().__init__(270.0)
542|         self.m = [[1.0, 0.0, 0.0], [0.0, 0.0,-1.0], [0.0, 1.0, 0.0]]
543| 
544| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
545| class rotate3d_y (rotate3d):
546|     '''3D Rotate on Y Axis.
546| 
546| Instance Arguments:
546|     angle           - rotation angle
546| '''

547|     def __init__ (self, angle=0.0):
548|         super().__init__(angle)
549|         self.m[0] = [cos(self.r), 0.0, -sin(self.r)]
550|         self.m[1] = [        0.0, 1.0,          0.0]
551|         self.m[2] = [sin(self.r), 0.0,  cos(self.r)]
552| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
553| class rotate3d_y_0 (rotate3d):
554|     '''3D Rotate 0 degrees on Y Axis.'''
555|     def __init__ (self):
556|         super().__init__(0.0)
557|         self.m = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
558| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
559| class rotate3d_y_90 (rotate3d):
560|     '''3D Rotate 90 degrees on Y Axis.'''
561|     def __init__ (self):
562|         super().__init__(90.0)
563|         self.m = [[0.0, 0.0,-1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]
564| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
565| class rotate3d_y_180 (rotate3d):
566|     '''3D Rotate 180 degrees on Y Axis.'''
567|     def __init__ (self):
568|         super().__init__(180.0)
569|         self.m = [[-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0,-1.0]]
570| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
571| class rotate3d_y_270 (rotate3d):
572|     '''3D Rotate 270 degrees on Y Axis.'''
573|     def __init__ (self):
574|         super().__init__(270.0)
575|         self.m = [[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [-1.0, 0.0, 0.0]]
576| 
577| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
578| class rotate3d_z (rotate3d):
579|     '''3D Rotate on Z Axis.
579| 
579| Instance Arguments:
579|     angle           - rotation angle
579| '''

580|     def __init__ (self, angle=0.0):
581|         super().__init__(angle)
582|         self.m[0] = [cos(self.r), -sin(self.r), 0.0]
583|         self.m[1] = [sin(self.r),  cos(self.r), 0.0]
584|         self.m[2] = [        0.0,          0.0, 1.0]
585| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
586| class rotate3d_z_0 (rotate3d):
587|     '''3D Rotate 0 degrees on Z Axis.'''
588|     def __init__ (self):
589|         super().__init__(0.0)
590|         self.m = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
591| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
592| class rotate3d_z_90 (rotate3d):
593|     '''3D Rotate 90 degrees on Z Axis.'''
594|     def __init__ (self):
595|         super().__init__(90.0)
596|         self.m = [[0.0,-1.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]
597| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
598| class rotate3d_z_180 (rotate3d):
599|     '''3D Rotate 180 degrees on Z Axis.'''
600|     def __init__ (self):
601|         super().__init__(180.0)
602|         self.m = [[-1.0, 0.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, 1.0]]
603| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
604| class rotate3d_z_270 (rotate3d):
605|     '''3D Rotate 270 degrees on Z Axis.'''
606|     def __init__ (self):
607|         super().__init__(270.0)
608|         self.m = [[0.0, 1.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]
609| 
610| 
611| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
612| class matrix4d (matrix):
613|     '''4D Transformation Matrix.
613| 
613| Instance Arguments:
613|     vals            - array of 16 values for the matrix (L->R, T->B)
613| 
613| Instance Methods:
613|     det             - determinant (NotImplemented!)
613| '''

614|     def __init__ (self, vals=[]):
615|         super().__init__(rows=4, cols=4)
616|         if len(vals) == 16:
617|             self.m[0][0] = vals[0]
618|             self.m[0][1] = vals[1]
619|             self.m[0][2] = vals[2]
620|             self.m[0][3] = vals[3]
621|             self.m[1][0] = vals[4]
622|             self.m[1][1] = vals[5]
623|             self.m[1][2] = vals[6]
624|             self.m[1][3] = vals[7]
625|             self.m[2][0] = vals[8]
626|             self.m[2][1] = vals[9]
627|             self.m[2][2] = vals[10]
628|             self.m[2][3] = vals[11]
629|             self.m[3][0] = vals[12]
630|             self.m[3][1] = vals[13]
631|             self.m[3][2] = vals[14]
632|             self.m[3][3] = vals[15]
633| 
634|     def det (self):
635|         '''[https://en.wikipedia.org/wiki/Determinant]'''
636|         raise NotImplementedError('On the TODO list!')
637| 
638| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
639| class rotate4d (matrix4d):
640|     '''4D Rotate Base Class.
640| 
640| Instance Arguments:
640|     angle           - rotation angle
640| '''

641|     def __init__ (self, angle=0.0):
642|         super().__init__()
643|         self.a = angle
644|         self.r = radians(self.a)
645| 
646|     def rotate (self, vec):
647|         '''Rotate vec. Returns new mvector.'''
648|         assert vec.cols()==1, TypeError('Not a column vector! (cols=%d)' % vec.cols())
649|         assert vec.rows()==4, TypeError('Not a 4D vector! (rows=%d)' % vec.rows())
650|         x = (self.m[0][0]*vec.m[0][0]) + (self.m[0][1]*vec.m[1][0]) + (self.m[0][2]*vec.m[2][0]) + (self.m[0][3]*vec.m[3][0])
651|         y = (self.m[1][0]*vec.m[0][0]) + (self.m[1][1]*vec.m[1][0]) + (self.m[1][2]*vec.m[2][0]) + (self.m[1][3]*vec.m[3][0])
652|         z = (self.m[2][0]*vec.m[0][0]) + (self.m[2][1]*vec.m[1][0]) + (self.m[2][2]*vec.m[2][0]) + (self.m[2][3]*vec.m[3][0])
653|         w = (self.m[3][0]*vec.m[0][0]) + (self.m[3][1]*vec.m[1][0]) + (self.m[3][2]*vec.m[2][0]) + (self.m[3][3]*vec.m[3][0])
654|         return mvector4d(x,y,z,w)
655| 
656| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
657| class rotate4d_xw (rotate4d):
658|     '''4D Rotate on XW Axis.
658| 
658| Instance Arguments:
658|     angle           - rotation angle
658| '''

659|     def __init__ (self, angle=0.0):
660|         super().__init__(angle)
661|         self.m[0] = [1.0,         0.0,          0.0, 0.0]
662|         self.m[1] = [0.0, cos(self.r), -sin(self.r), 0.0]
663|         self.m[2] = [0.0, sin(self.r),  cos(self.r), 0.0]
664|         self.m[3] = [0.0,         0.0,          0.0, 1.0]
665| 
666| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
667| class rotate4d_yw (rotate4d):
668|     '''4D Rotate on YW Axis.
668| 
668| Instance Arguments:
668|     angle           - rotation angle
668| '''

669|     def __init__ (self, angle=0.0):
670|         super().__init__(angle)
671|         self.m[0] = [cos(self.r), 0.0, -sin(self.r), 0.0]
672|         self.m[1] = [0.0,         1.0,          0.0, 0.0]
673|         self.m[2] = [sin(self.r), 0.0,  cos(self.r), 0.0]
674|         self.m[3] = [0.0,         0.0,          0.0, 1.0]
675| 
676| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
677| class rotate4d_zw (rotate4d):
678|     '''4D Rotate on ZW Axis.
678| 
678| Instance Arguments:
678|     angle           - rotation angle
678| '''

679|     def __init__ (self, angle=0.0):
680|         super().__init__(angle)
681|         self.m[0] = [cos(self.r), -sin(self.r), 0.0, 0.0]
682|         self.m[1] = [sin(self.r),  cos(self.r), 0.0, 0.0]
683|         self.m[2] = [        0.0,         0.0,  1.0, 0.0]
684|         self.m[3] = [        0.0,         0.0,  0.0, 1.0]
685| 
686| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
687| class rotate4d_xy (rotate4d):
688|     '''4D Rotate on XW Axis.
688| 
688| Instance Arguments:
688|     angle           - rotation angle
688| '''

689|     def __init__ (self, angle=0.0):
690|         super().__init__(angle)
691|         self.m[2] = [1.0, 0.0,         0.0,         0.0]
692|         self.m[3] = [0.0, 1.0,         0.0,         0.0]
693|         self.m[0] = [0.0, 0.0, cos(self.r), -sin(self.r)]
694|         self.m[1] = [0.0, 0.0, sin(self.r),  cos(self.r)]
695| 
696| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
697| class rotate4d_xz (rotate4d):
698|     '''4D Rotate on YW Axis.
698| 
698| Instance Arguments:
698|     angle           - rotation angle
698| '''

699|     def __init__ (self, angle=0.0):
700|         super().__init__(angle)
701|         self.m[0] = [1.0,         0.0, 0.0,          0.0]
702|         self.m[1] = [0.0, cos(self.r), 0.0, -sin(self.r)]
703|         self.m[2] = [0.0,         0.0, 1.0,          0.0]
704|         self.m[3] = [0.0, sin(self.r), 0.0,  cos(self.r)]
705| 
706| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
707| class rotate4d_yz (rotate4d):
708|     '''4D Rotate on ZW Axis.
708| 
708| Instance Arguments:
708|     angle           - rotation angle
708| '''

709|     def __init__ (self, angle=0.0):
710|         super().__init__(angle)
711|         self.m[0] = [cos(self.r), 0.0, 0.0, -sin(self.r)]
712|         self.m[1] = [0.0,         1.0, 0.0,          0.0]
713|         self.m[2] = [0.0,         0.0, 1.0,          0.0]
714|         self.m[3] = [sin(self.r), 0.0, 0.0,  cos(self.r)]
715| 
716| 
717| ####################################################################################################
718| '''eof'''
719|