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