Plot domain added
[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 return not bool(self)
111
112 def __hash__(self):
113 return super().__hash__()
114
115 def __add__(self, other):
116 if not isinstance(other, Vector):
117 return NotImplemented
118 coordinates = self._map2(other, operator.add)
119 return Point(coordinates)
120
121 def __sub__(self, other):
122 coordinates = []
123 if isinstance(other, Point):
124 coordinates = self._map2(other, operator.sub)
125 return Vector(coordinates)
126 elif isinstance(other, Vector):
127 coordinates = self._map2(other, operator.sub)
128 return Point(coordinates)
129 else:
130 return NotImplemented
131
132 def __eq__(self, other):
133 return isinstance(other, Point) and \
134 self._coordinates == other._coordinates
135
136 def aspolyhedron(self):
137 from .polyhedra import Polyhedron
138 equalities = []
139 for symbol, coordinate in self.coordinates():
140 equalities.append(symbol - coordinate)
141 return Polyhedron(equalities)
142
143
144 class Vector(Coordinates):
145 """
146 This class represents displacements in space.
147 """
148
149 def __new__(cls, initial, terminal=None):
150 if not isinstance(initial, Point):
151 initial = Point(initial)
152 if terminal is None:
153 coordinates = initial._coordinates
154 else:
155 if not isinstance(terminal, Point):
156 terminal = Point(terminal)
157 coordinates = terminal._map2(initial, operator.sub)
158 return super().__new__(cls, coordinates)
159
160 def isnull(self):
161 return not bool(self)
162
163 def __hash__(self):
164 return super().__hash__()
165
166 def __add__(self, other):
167 if isinstance(other, (Point, Vector)):
168 coordinates = self._map2(other, operator.add)
169 return other.__class__(coordinates)
170 return NotImplemented
171
172 def angle(self, other):
173 """
174 Retrieve the angle required to rotate the vector into the vector passed
175 in argument. The result is an angle in radians, ranging between -pi and
176 pi.
177 """
178 if not isinstance(other, Vector):
179 raise TypeError('argument must be a Vector instance')
180 cosinus = self.dot(other) / (self.norm()*other.norm())
181 return math.acos(cosinus)
182
183 def cross(self, other):
184 """
185 Calculate the cross product of two Vector3D structures.
186 """
187 if not isinstance(other, Vector):
188 raise TypeError('other must be a Vector instance')
189 if self.dimension != 3 or other.dimension != 3:
190 raise ValueError('arguments must be three-dimensional vectors')
191 if self.symbols != other.symbols:
192 raise ValueError('arguments must belong to the same space')
193 x, y, z = self.symbols
194 coordinates = []
195 coordinates.append((x, self[y]*other[z] - self[z]*other[y]))
196 coordinates.append((y, self[z]*other[x] - self[x]*other[z]))
197 coordinates.append((z, self[x]*other[y] - self[y]*other[x]))
198 return Vector(coordinates)
199
200 def __truediv__(self, other):
201 """
202 Divide the vector by the specified scalar and returns the result as a
203 vector.
204 """
205 if not isinstance(other, numbers.Real):
206 return NotImplemented
207 coordinates = self._map(lambda coordinate: coordinate / other)
208 return Vector(coordinates)
209
210 def dot(self, other):
211 """
212 Calculate the dot product of two vectors.
213 """
214 if not isinstance(other, Vector):
215 raise TypeError('argument must be a Vector instance')
216 result = 0
217 for symbol, coordinate1, coordinate2 in self._iter2(other):
218 result += coordinate1 * coordinate2
219 return result
220
221 def __eq__(self, other):
222 return isinstance(other, Vector) and \
223 self._coordinates == other._coordinates
224
225 def __hash__(self):
226 return hash(tuple(self.coordinates()))
227
228 def __mul__(self, other):
229 if not isinstance(other, numbers.Real):
230 return NotImplemented
231 coordinates = self._map(lambda coordinate: other * coordinate)
232 return Vector(coordinates)
233
234 __rmul__ = __mul__
235
236 def __neg__(self):
237 coordinates = self._map(operator.neg)
238 return Vector(coordinates)
239
240 def norm(self):
241 return math.sqrt(self.norm2())
242
243 def norm2(self):
244 result = 0
245 for coordinate in self._coordinates.values():
246 result += coordinate ** 2
247 return result
248
249 def asunit(self):
250 return self / self.norm()
251
252 def __sub__(self, other):
253 if isinstance(other, (Point, Vector)):
254 coordinates = self._map2(other, operator.sub)
255 return other.__class__(coordinates)
256 return NotImplemented