+import math
+import numbers
+import operator
+
+from collections import OrderedDict
+
+from .linexprs import Symbol
+
+
+__all__ = [
+ 'Point',
+ 'Vector',
+]
+
+
+def _map(obj, func):
+ for symbol, coordinate in obj.coordinates():
+ yield symbol, func(coordinate)
+
+def _iter2(obj1, obj2):
+ if obj1.symbols != obj2.symbols:
+ raise ValueError('arguments must belong to the same space')
+ coordinates1 = obj1._coordinates.values()
+ coordinates2 = obj2._coordinates.values()
+ yield from zip(obj1.symbols, coordinates1, coordinates2)
+
+def _map2(obj1, obj2, func):
+ for symbol, coordinate1, coordinate2 in _iter2(obj1, obj2):
+ yield symbol, func(coordinate1, coordinate2)
+
+
+class Point:
+ """
+ This class represents points in space.
+ """
+
+ def __new__(cls, coordinates=None):
+ if isinstance(coordinates, dict):
+ coordinates = coordinates.items()
+ self = object().__new__(cls)
+ self._coordinates = OrderedDict()
+ for symbol, coordinate in sorted(coordinates,
+ key=lambda item: item[0].sortkey()):
+ if not isinstance(symbol, Symbol):
+ raise TypeError('symbols must be Symbol instances')
+ if not isinstance(coordinate, numbers.Real):
+ raise TypeError('coordinates must be real numbers')
+ self._coordinates[symbol] = coordinate
+ return self
+
+ @property
+ def symbols(self):
+ return tuple(self._coordinates)
+
+ @property
+ def dimension(self):
+ return len(self.symbols)
+
+ def coordinates(self):
+ yield from self._coordinates.items()
+
+ def coordinate(self, symbol):
+ if not isinstance(symbol, Symbol):
+ raise TypeError('symbol must be a Symbol instance')
+ return self._coordinates[symbol]
+
+ __getitem__ = coordinate
+
+ def isorigin(self):
+ return not bool(self)
+
+ def __bool__(self):
+ return any(self._coordinates.values())
+
+ def __add__(self, other):
+ if not isinstance(other, Vector):
+ return NotImplemented
+ coordinates = _map2(self, other, operator.add)
+ return Point(coordinates)
+
+ def __sub__(self, other):
+ coordinates = []
+ if isinstance(other, Point):
+ coordinates = _map2(self, other, operator.sub)
+ return Vector(coordinates)
+ elif isinstance(other, Vector):
+ coordinates = _map2(self, other, operator.sub)
+ return Point(coordinates)
+ else:
+ return NotImplemented
+
+ def __eq__(self, other):
+ return isinstance(other, Point) and \
+ self._coordinates == other._coordinates
+
+ def __hash__(self):
+ return hash(tuple(self.coordinates()))
+
+ def __repr__(self):
+ string = ', '.join(['{!r}: {!r}'.format(symbol, coordinate)
+ for symbol, coordinate in self.coordinates()])
+ return '{}({{{}}})'.format(self.__class__.__name__, string)
+
+
+class Vector:
+ """
+ This class represents displacements in space.
+ """
+
+ __slots__ = (
+ '_coordinates',
+ )
+
+ def __new__(cls, initial, terminal=None):
+ self = object().__new__(cls)
+ if not isinstance(initial, Point):
+ initial = Point(initial)
+ if terminal is None:
+ self._coordinates = initial._coordinates
+ elif not isinstance(terminal, Point):
+ terminal = Point(terminal)
+ self._coordinates = _map2(terminal, initial, operator.sub)
+ return self
+
+ @property
+ def symbols(self):
+ return tuple(self._coordinates)
+
+ @property
+ def dimension(self):
+ return len(self.symbols)
+
+ def coordinates(self):
+ yield from self._coordinates.items()
+
+ def coordinate(self, symbol):
+ if not isinstance(symbol, Symbol):
+ raise TypeError('symbol must be a Symbol instance')
+ return self._coordinates[symbol]
+
+ __getitem__ = coordinate
+
+ def isnull(self):
+ return not bool(self)
+
+ def __bool__(self):
+ return any(self._coordinates.values())
+
+ def __add__(self, other):
+ if isinstance(other, (Point, Vector)):
+ coordinates = _map2(self, other, operator.add)
+ return other.__class__(coordinates)
+ return NotImplemented
+
+ def angle(self, other):
+ """
+ Retrieve the angle required to rotate the vector into the vector passed
+ in argument. The result is an angle in radians, ranging between -pi and
+ pi.
+ """
+ if not isinstance(other, Vector):
+ raise TypeError('argument must be a Vector instance')
+ cosinus = self.dot(other) / (self.norm() * other.norm())
+ return math.acos(cosinus)
+
+ def cross(self, other):
+ """
+ Calculate the cross product of two Vector3D structures.
+ """
+ if not isinstance(other, Vector):
+ raise TypeError('other must be a Vector instance')
+ if self.dimension != 3 or other.dimension != 3:
+ raise ValueError('arguments must be three-dimensional vectors')
+ if self.symbols != other.symbols:
+ raise ValueError('arguments must belong to the same space')
+ x, y, z = self.symbols
+ coordinates = []
+ coordinates.append((x, self[y]*other[z] - self[z]*other[y]))
+ coordinates.append((y, self[z]*other[x] - self[x]*other[z]))
+ coordinates.append((z, self[x]*other[y] - self[y]*other[x]))
+ return Vector(coordinates)
+
+ def __truediv__(self, other):
+ """
+ Divide the vector by the specified scalar and returns the result as a
+ vector.
+ """
+ if not isinstance(other, numbers.Real):
+ return NotImplemented
+ coordinates = _map(self, lambda coordinate: coordinate / other)
+ return Vector(coordinates)
+
+ def dot(self, other):
+ """
+ Calculate the dot product of two vectors.
+ """
+ if not isinstance(other, Vector):
+ raise TypeError('argument must be a Vector instance')
+ result = 0
+ for symbol, coordinate1, coordinate2 in _iter2(self, other):
+ result += coordinate1 * coordinate2
+ return result
+
+ def __eq__(self, other):
+ return isinstance(other, Vector) and \
+ self._coordinates == other._coordinates
+
+ def __hash__(self):
+ return hash(tuple(self.coordinates()))
+
+ def __mul__(self, other):
+ if not isinstance(other, numbers.Real):
+ return NotImplemented
+ coordinates = _map(self, lambda coordinate: other * coordinate)
+ return Vector(coordinates)
+
+ __rmul__ = __mul__
+
+ def __neg__(self):
+ coordinates = _map(self, operator.neg)
+ return Vector(coordinates)
+
+ def norm(self):
+ return math.sqrt(self.norm2())
+
+ def norm2(self):
+ result = 0
+ for coordinate in self._coordinates.values():
+ result += coordinate ** 2
+ return result
+
+ def asunit(self):
+ return self / self.norm()
+
+ def __sub__(self, other):
+ if isinstance(other, (Point, Vector)):
+ coordinates = _map2(self, other, operator.sub)
+ return other.__class__(coordinates)
+ return NotImplemented
+
+ def __repr__(self):
+ string = ', '.join(['{!r}: {!r}'.format(symbol, coordinate)
+ for symbol, coordinate in self.coordinates()])
+ return '{}({{{}}})'.format(self.__class__.__name__, string)