Fix methods Domain._sort_polygon_2d(), Domain._sort_polygon_3d()
[linpy.git] / pypol / linexprs.py
index ccd1564..5ec5efd 100644 (file)
@@ -3,14 +3,14 @@ import functools
 import numbers
 import re
 
 import numbers
 import re
 
-from collections import OrderedDict, defaultdict
+from collections import OrderedDict, defaultdict, Mapping
 from fractions import Fraction, gcd
 
 
 __all__ = [
     'Expression',
 from fractions import Fraction, gcd
 
 
 __all__ = [
     'Expression',
-    'Symbol', 'symbols',
-    'Constant',
+    'Symbol', 'Dummy', 'symbols',
+    'Rational',
 ]
 
 
 ]
 
 
@@ -20,7 +20,7 @@ def _polymorphic(func):
         if isinstance(right, Expression):
             return func(left, right)
         elif isinstance(right, numbers.Rational):
         if isinstance(right, Expression):
             return func(left, right)
         elif isinstance(right, numbers.Rational):
-            right = Constant(right)
+            right = Rational(right)
             return func(left, right)
         return NotImplemented
     return wrapper
             return func(left, right)
         return NotImplemented
     return wrapper
@@ -44,8 +44,8 @@ class Expression:
                 raise TypeError('too many arguments')
             return Expression.fromstring(coefficients)
         if coefficients is None:
                 raise TypeError('too many arguments')
             return Expression.fromstring(coefficients)
         if coefficients is None:
-            return Constant(constant)
-        if isinstance(coefficients, dict):
+            return Rational(constant)
+        if isinstance(coefficients, Mapping):
             coefficients = coefficients.items()
         for symbol, coefficient in coefficients:
             if not isinstance(symbol, Symbol):
             coefficients = coefficients.items()
         for symbol, coefficient in coefficients:
             if not isinstance(symbol, Symbol):
@@ -53,7 +53,7 @@ class Expression:
         coefficients = [(symbol, coefficient)
             for symbol, coefficient in coefficients if coefficient != 0]
         if len(coefficients) == 0:
         coefficients = [(symbol, coefficient)
             for symbol, coefficient in coefficients if coefficient != 0]
         if len(coefficients) == 0:
-            return Constant(constant)
+            return Rational(constant)
         if len(coefficients) == 1 and constant == 0:
             symbol, coefficient = coefficients[0]
             if coefficient == 1:
         if len(coefficients) == 1 and constant == 0:
             symbol, coefficient = coefficients[0]
             if coefficient == 1:
@@ -61,18 +61,18 @@ class Expression:
         self = object().__new__(cls)
         self._coefficients = OrderedDict()
         for symbol, coefficient in sorted(coefficients,
         self = object().__new__(cls)
         self._coefficients = OrderedDict()
         for symbol, coefficient in sorted(coefficients,
-                key=lambda item: item[0].name):
-            if isinstance(coefficient, Constant):
+                key=lambda item: item[0].sortkey()):
+            if isinstance(coefficient, Rational):
                 coefficient = coefficient.constant
             if not isinstance(coefficient, numbers.Rational):
                 raise TypeError('coefficients must be rational numbers '
                 coefficient = coefficient.constant
             if not isinstance(coefficient, numbers.Rational):
                 raise TypeError('coefficients must be rational numbers '
-                    'or Constant instances')
+                    'or Rational instances')
             self._coefficients[symbol] = coefficient
             self._coefficients[symbol] = coefficient
-        if isinstance(constant, Constant):
+        if isinstance(constant, Rational):
             constant = constant.constant
         if not isinstance(constant, numbers.Rational):
             raise TypeError('constant must be a rational number '
             constant = constant.constant
         if not isinstance(constant, numbers.Rational):
             raise TypeError('constant must be a rational number '
-                'or a Constant instance')
+                'or a Rational instance')
         self._constant = constant
         self._symbols = tuple(self._coefficients)
         self._dimension = len(self._symbols)
         self._constant = constant
         self._symbols = tuple(self._coefficients)
         self._dimension = len(self._symbols)
@@ -127,7 +127,7 @@ class Expression:
 
     @_polymorphic
     def __add__(self, other):
 
     @_polymorphic
     def __add__(self, other):
-        coefficients = defaultdict(Constant, self.coefficients())
+        coefficients = defaultdict(Rational, self.coefficients())
         for symbol, coefficient in other.coefficients():
             coefficients[symbol] += coefficient
         constant = self.constant + other.constant
         for symbol, coefficient in other.coefficients():
             coefficients[symbol] += coefficient
         constant = self.constant + other.constant
@@ -137,7 +137,7 @@ class Expression:
 
     @_polymorphic
     def __sub__(self, other):
 
     @_polymorphic
     def __sub__(self, other):
-        coefficients = defaultdict(Constant, self.coefficients())
+        coefficients = defaultdict(Rational, self.coefficients())
         for symbol, coefficient in other.coefficients():
             coefficients[symbol] -= coefficient
         constant = self.constant - other.constant
         for symbol, coefficient in other.coefficients():
             coefficients[symbol] -= coefficient
         constant = self.constant - other.constant
@@ -166,8 +166,8 @@ class Expression:
         if other.isconstant():
             coefficients = dict(self.coefficients())
             for symbol in coefficients:
         if other.isconstant():
             coefficients = dict(self.coefficients())
             for symbol in coefficients:
-                coefficients[symbol] = Constant(coefficients[symbol], other.constant)
-            constant = Constant(self.constant, other.constant)
+                coefficients[symbol] = Rational(coefficients[symbol], other.constant)
+            constant = Rational(self.constant, other.constant)
             return Expression(coefficients, constant)
         if isinstance(other, Expression):
             raise ValueError('non-linear expression: '
             return Expression(coefficients, constant)
         if isinstance(other, Expression):
             raise ValueError('non-linear expression: '
@@ -177,7 +177,7 @@ class Expression:
     def __rtruediv__(self, other):
         if isinstance(other, self):
             if self.isconstant():
     def __rtruediv__(self, other):
         if isinstance(other, self):
             if self.isconstant():
-                return Constant(other, self.constant)
+                return Rational(other, self.constant)
             else:
                 raise ValueError('non-linear expression: '
                         '{} / {}'.format(other._parenstr(), self._parenstr()))
             else:
                 raise ValueError('non-linear expression: '
                         '{} / {}'.format(other._parenstr(), self._parenstr()))
@@ -218,7 +218,7 @@ class Expression:
 
     def subs(self, symbol, expression=None):
         if expression is None:
 
     def subs(self, symbol, expression=None):
         if expression is None:
-            if isinstance(symbol, dict):
+            if isinstance(symbol, Mapping):
                 symbol = symbol.items()
             substitutions = symbol
         else:
                 symbol = symbol.items()
             substitutions = symbol
         else:
@@ -242,7 +242,7 @@ class Expression:
         elif isinstance(node, ast.Name):
             return Symbol(node.id)
         elif isinstance(node, ast.Num):
         elif isinstance(node, ast.Name):
             return Symbol(node.id)
         elif isinstance(node, ast.Num):
-            return Constant(node.n)
+            return Rational(node.n)
         elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
             return -cls._fromast(node.operand)
         elif isinstance(node, ast.BinOp):
         elif isinstance(node, ast.UnaryOp) and isinstance(node.op, ast.USub):
             return -cls._fromast(node.operand)
         elif isinstance(node, ast.BinOp):
@@ -269,39 +269,27 @@ class Expression:
 
     def __repr__(self):
         string = ''
 
     def __repr__(self):
         string = ''
-        i = 0
-        for symbol in self.symbols:
-            coefficient = self.coefficient(symbol)
+        for i, (symbol, coefficient) in enumerate(self.coefficients()):
             if coefficient == 1:
             if coefficient == 1:
-                if i == 0:
-                    string += symbol.name
-                else:
-                    string += ' + {}'.format(symbol)
+                string += '' if i == 0 else ' + '
+                string += '{!r}'.format(symbol)
             elif coefficient == -1:
             elif coefficient == -1:
-                if i == 0:
-                    string += '-{}'.format(symbol)
-                else:
-                    string += ' - {}'.format(symbol)
+                string += '-' if i == 0 else ' - '
+                string += '{!r}'.format(symbol)
             else:
                 if i == 0:
             else:
                 if i == 0:
-                    string += '{}*{}'.format(coefficient, symbol)
+                    string += '{}*{!r}'.format(coefficient, symbol)
                 elif coefficient > 0:
                 elif coefficient > 0:
-                    string += ' + {}*{}'.format(coefficient, symbol)
+                    string += ' + {}*{!r}'.format(coefficient, symbol)
                 else:
                 else:
-                    assert coefficient < 0
-                    coefficient *= -1
-                    string += ' - {}*{}'.format(coefficient, symbol)
-            i += 1
+                    string += ' - {}*{!r}'.format(-coefficient, symbol)
         constant = self.constant
         constant = self.constant
-        if constant != 0 and i == 0:
+        if len(string) == 0:
             string += '{}'.format(constant)
         elif constant > 0:
             string += ' + {}'.format(constant)
         elif constant < 0:
             string += '{}'.format(constant)
         elif constant > 0:
             string += ' + {}'.format(constant)
         elif constant < 0:
-            constant *= -1
-            string += ' - {}'.format(constant)
-        if string == '':
-            string = '0'
+            string += ' - {}'.format(-constant)
         return string
 
     def _parenstr(self, always=False):
         return string
 
     def _parenstr(self, always=False):
@@ -355,7 +343,7 @@ class Symbol(Expression):
         return self._name
 
     def __hash__(self):
         return self._name
 
     def __hash__(self):
-        return hash(self._name)
+        return hash(self.sortkey())
 
     def coefficient(self, symbol):
         if not isinstance(symbol, Symbol):
 
     def coefficient(self, symbol):
         if not isinstance(symbol, Symbol):
@@ -380,6 +368,9 @@ class Symbol(Expression):
     def dimension(self):
         return 1
 
     def dimension(self):
         return 1
 
+    def sortkey(self):
+        return self.name,
+
     def issymbol(self):
         return True
 
     def issymbol(self):
         return True
 
@@ -387,7 +378,11 @@ class Symbol(Expression):
         yield 1
 
     def __eq__(self, other):
         yield 1
 
     def __eq__(self, other):
-        return isinstance(other, Symbol) and self.name == other.name
+        return not isinstance(other, Dummy) and isinstance(other, Symbol) \
+            and self.name == other.name
+
+    def asdummy(self):
+        return Dummy(self.name)
 
     @classmethod
     def _fromast(cls, node):
 
     @classmethod
     def _fromast(cls, node):
@@ -399,22 +394,56 @@ class Symbol(Expression):
             return Symbol(node.id)
         raise SyntaxError('invalid syntax')
 
             return Symbol(node.id)
         raise SyntaxError('invalid syntax')
 
+    def __repr__(self):
+        return self.name
+
     @classmethod
     def fromsympy(cls, expr):
         import sympy
         if isinstance(expr, sympy.Symbol):
     @classmethod
     def fromsympy(cls, expr):
         import sympy
         if isinstance(expr, sympy.Symbol):
-            return Symbol(expr.name)
+            return cls(expr.name)
         else:
             raise TypeError('expr must be a sympy.Symbol instance')
 
 
         else:
             raise TypeError('expr must be a sympy.Symbol instance')
 
 
+class Dummy(Symbol):
+
+    __slots__ = (
+        '_name',
+        '_index',
+    )
+
+    _count = 0
+
+    def __new__(cls, name=None):
+        if name is None:
+            name = 'Dummy_{}'.format(Dummy._count)
+        self = object().__new__(cls)
+        self._name = name.strip()
+        self._index = Dummy._count
+        Dummy._count += 1
+        return self
+
+    def __hash__(self):
+        return hash(self.sortkey())
+
+    def sortkey(self):
+        return self._name, self._index
+
+    def __eq__(self, other):
+        return isinstance(other, Dummy) and self._index == other._index
+
+    def __repr__(self):
+        return '_{}'.format(self.name)
+
+
 def symbols(names):
     if isinstance(names, str):
         names = names.replace(',', ' ').split()
     return tuple(Symbol(name) for name in names)
 
 
 def symbols(names):
     if isinstance(names, str):
         names = names.replace(',', ' ').split()
     return tuple(Symbol(name) for name in names)
 
 
-class Constant(Expression):
+class Rational(Expression):
 
     __slots__ = (
         '_constant',
 
     __slots__ = (
         '_constant',
@@ -422,7 +451,7 @@ class Constant(Expression):
 
     def __new__(cls, numerator=0, denominator=None):
         self = object().__new__(cls)
 
     def __new__(cls, numerator=0, denominator=None):
         self = object().__new__(cls)
-        if denominator is None and isinstance(numerator, Constant):
+        if denominator is None and isinstance(numerator, Rational):
             self._constant = numerator.constant
         else:
             self._constant = Fraction(numerator, denominator)
             self._constant = numerator.constant
         else:
             self._constant = Fraction(numerator, denominator)
@@ -455,7 +484,7 @@ class Constant(Expression):
 
     @_polymorphic
     def __eq__(self, other):
 
     @_polymorphic
     def __eq__(self, other):
-        return isinstance(other, Constant) and self.constant == other.constant
+        return isinstance(other, Rational) and self.constant == other.constant
 
     def __bool__(self):
         return self.constant != 0
 
     def __bool__(self):
         return self.constant != 0
@@ -464,14 +493,14 @@ class Constant(Expression):
     def fromstring(cls, string):
         if not isinstance(string, str):
             raise TypeError('string must be a string instance')
     def fromstring(cls, string):
         if not isinstance(string, str):
             raise TypeError('string must be a string instance')
-        return Constant(Fraction(string))
+        return Rational(Fraction(string))
 
     @classmethod
     def fromsympy(cls, expr):
         import sympy
         if isinstance(expr, sympy.Rational):
 
     @classmethod
     def fromsympy(cls, expr):
         import sympy
         if isinstance(expr, sympy.Rational):
-            return Constant(expr.p, expr.q)
+            return Rational(expr.p, expr.q)
         elif isinstance(expr, numbers.Rational):
         elif isinstance(expr, numbers.Rational):
-            return Constant(expr)
+            return Rational(expr)
         else:
             raise TypeError('expr must be a sympy.Rational instance')
         else:
             raise TypeError('expr must be a sympy.Rational instance')