-
-
Notifications
You must be signed in to change notification settings - Fork 710
/
Copy pathmatrix.py
51 lines (44 loc) · 1.86 KB
/
matrix.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
"""Transformation matrix."""
class Matrix(list):
def __init__(self, a=1, b=0, c=0, d=1, e=0, f=0, matrix=None):
if matrix is None:
matrix = [[a, b, 0], [c, d, 0], [e, f, 1]]
super().__init__(matrix)
def __matmul__(self, other):
assert len(self[0]) == len(other) == len(other[0]) == 3
return Matrix(matrix=[
[sum(self[i][k] * other[k][j] for k in range(3)) for j in range(3)]
for i in range(len(self))])
@property
def invert(self):
d = self.determinant
return Matrix(matrix=[
[
(self[1][1] * self[2][2] - self[1][2] * self[2][1]) / d,
(self[0][1] * self[2][2] - self[0][2] * self[2][1]) / -d,
(self[0][1] * self[1][2] - self[0][2] * self[1][1]) / d,
],
[
(self[1][0] * self[2][2] - self[1][2] * self[2][0]) / -d,
(self[0][0] * self[2][2] - self[0][2] * self[2][0]) / d,
(self[0][0] * self[1][2] - self[0][2] * self[1][0]) / -d,
],
[
(self[1][0] * self[2][1] - self[1][1] * self[2][0]) / d,
(self[0][0] * self[2][1] - self[0][1] * self[2][0]) / -d,
(self[0][0] * self[1][1] - self[0][1] * self[1][0]) / d,
],
])
@property
def determinant(self):
assert len(self) == len(self[0]) == 3
return (
self[0][0] * (self[1][1] * self[2][2] - self[1][2] * self[2][1]) -
self[1][0] * (self[0][1] * self[2][2] - self[0][2] * self[2][1]) +
self[2][0] * (self[0][1] * self[1][2] - self[0][2] * self[1][1]))
def transform_point(self, x, y):
return (Matrix(matrix=[[x, y, 1]]) @ self)[0][:2]
@property
def values(self):
(a, b), (c, d), (e, f) = [column[:2] for column in self]
return a, b, c, d, e, f