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