Remove Vector.__slots__, useless
[linpy.git] / pypol / coordinates.py
1 import math
2 import numbers
3 import operator
4
5 from collections import OrderedDict, Mapping
6
7 from .linexprs import Symbol
8
9
10 __all__ = [
11 'Point',
12 'Vector',
13 ]
14
15
16 class Coordinates:
17
18 __slots__ = (
19 '_coordinates',
20 )
21
22 def __new__(cls, coordinates):
23 if isinstance(coordinates, Mapping):
24 coordinates = coordinates.items()
25 self = object().__new__(cls)
26 self._coordinates = OrderedDict()
27 for symbol, coordinate in sorted(coordinates,
28 key=lambda item: item[0].sortkey()):
29 if not isinstance(symbol, Symbol):
30 raise TypeError('symbols must be Symbol instances')
31 if not isinstance(coordinate, numbers.Real):
32 raise TypeError('coordinates must be real numbers')
33 self._coordinates[symbol] = coordinate
34 return self
35
36 @property
37 def symbols(self):
38 return tuple(self._coordinates)
39
40 @property
41 def dimension(self):
42 return len(self.symbols)
43
44 def coordinates(self):
45 yield from self._coordinates.items()
46
47 def coordinate(self, symbol):
48 if not isinstance(symbol, Symbol):
49 raise TypeError('symbol must be a Symbol instance')
50 return self._coordinates[symbol]
51
52 __getitem__ = coordinate
53
54 def __bool__(self):
55 return any(self._coordinates.values())
56
57 def __hash__(self):
58 return hash(tuple(self.coordinates()))
59
60 def __repr__(self):
61 string = ', '.join(['{!r}: {!r}'.format(symbol, coordinate)
62 for symbol, coordinate in self.coordinates()])
63 return '{}({{{}}})'.format(self.__class__.__name__, string)
64
65 def _map(self, func):
66 for symbol, coordinate in self.coordinates():
67 yield symbol, func(coordinate)
68
69 def _iter2(self, other):
70 if self.symbols != other.symbols:
71 raise ValueError('arguments must belong to the same space')
72 coordinates1 = self._coordinates.values()
73 coordinates2 = other._coordinates.values()
74 yield from zip(self.symbols, coordinates1, coordinates2)
75
76 def _map2(self, other, func):
77 for symbol, coordinate1, coordinate2 in self._iter2(other):
78 yield symbol, func(coordinate1, coordinate2)
79
80
81 class Point(Coordinates):
82 """
83 This class represents points in space.
84 """
85
86 def isorigin(self):
87 return not bool(self)
88
89 def __add__(self, other):
90 if not isinstance(other, Vector):
91 return NotImplemented
92 coordinates = self._map2(other, operator.add)
93 return Point(coordinates)
94
95 def __sub__(self, other):
96 coordinates = []
97 if isinstance(other, Point):
98 coordinates = self._map2(other, operator.sub)
99 return Vector(coordinates)
100 elif isinstance(other, Vector):
101 coordinates = self._map2(other, operator.sub)
102 return Point(coordinates)
103 else:
104 return NotImplemented
105
106 def __eq__(self, other):
107 return isinstance(other, Point) and \
108 self._coordinates == other._coordinates
109
110 def aspolyhedron(self):
111 from .polyhedra import Polyhedron
112 equalities = []
113 for symbol, coordinate in self.coordinates():
114 equalities.append(symbol - coordinate)
115 return Polyhedron(equalities)
116
117
118 class Vector(Coordinates):
119 """
120 This class represents displacements in space.
121 """
122
123 def __new__(cls, initial, terminal=None):
124 if not isinstance(initial, Point):
125 initial = Point(initial)
126 if terminal is None:
127 coordinates = initial._coordinates
128 elif not isinstance(terminal, Point):
129 terminal = Point(terminal)
130 coordinates = terminal._map2(initial, operator.sub)
131 return super().__new__(cls, coordinates)
132
133 def isnull(self):
134 return not bool(self)
135
136 def __add__(self, other):
137 if isinstance(other, (Point, Vector)):
138 coordinates = self._map2(other, operator.add)
139 return other.__class__(coordinates)
140 return NotImplemented
141
142 def angle(self, other):
143 """
144 Retrieve the angle required to rotate the vector into the vector passed
145 in argument. The result is an angle in radians, ranging between -pi and
146 pi.
147 """
148 if not isinstance(other, Vector):
149 raise TypeError('argument must be a Vector instance')
150 cosinus = self.dot(other) / (self.norm()*other.norm())
151 return math.acos(cosinus)
152
153 def cross(self, other):
154 """
155 Calculate the cross product of two Vector3D structures.
156 """
157 if not isinstance(other, Vector):
158 raise TypeError('other must be a Vector instance')
159 if self.dimension != 3 or other.dimension != 3:
160 raise ValueError('arguments must be three-dimensional vectors')
161 if self.symbols != other.symbols:
162 raise ValueError('arguments must belong to the same space')
163 x, y, z = self.symbols
164 coordinates = []
165 coordinates.append((x, self[y]*other[z] - self[z]*other[y]))
166 coordinates.append((y, self[z]*other[x] - self[x]*other[z]))
167 coordinates.append((z, self[x]*other[y] - self[y]*other[x]))
168 return Vector(coordinates)
169
170 def __truediv__(self, other):
171 """
172 Divide the vector by the specified scalar and returns the result as a
173 vector.
174 """
175 if not isinstance(other, numbers.Real):
176 return NotImplemented
177 coordinates = self._map(lambda coordinate: coordinate / other)
178 return Vector(coordinates)
179
180 def dot(self, other):
181 """
182 Calculate the dot product of two vectors.
183 """
184 if not isinstance(other, Vector):
185 raise TypeError('argument must be a Vector instance')
186 result = 0
187 for symbol, coordinate1, coordinate2 in self._iter2(other):
188 result += coordinate1 * coordinate2
189 return result
190
191 def __eq__(self, other):
192 return isinstance(other, Vector) and \
193 self._coordinates == other._coordinates
194
195 def __hash__(self):
196 return hash(tuple(self.coordinates()))
197
198 def __mul__(self, other):
199 if not isinstance(other, numbers.Real):
200 return NotImplemented
201 coordinates = self._map(lambda coordinate: other * coordinate)
202 return Vector(coordinates)
203
204 __rmul__ = __mul__
205
206 def __neg__(self):
207 coordinates = self._map(operator.neg)
208 return Vector(coordinates)
209
210 def norm(self):
211 return math.sqrt(self.norm2())
212
213 def norm2(self):
214 result = 0
215 for coordinate in self._coordinates.values():
216 result += coordinate ** 2
217 return result
218
219 def asunit(self):
220 return self / self.norm()
221
222 def __sub__(self, other):
223 if isinstance(other, (Point, Vector)):
224 coordinates = self._map2(other, operator.sub)
225 return other.__class__(coordinates)
226 return NotImplemented