X-Git-Url: https://svn.cri.ensmp.fr/git/linpy.git/blobdiff_plain/c3d305942999eeb429c6941184b47e7f1b55c499..8332ae24f41a1f2bbba78597cc9e412ef9935ae8:/pypol/linexprs.py diff --git a/pypol/linexprs.py b/pypol/linexprs.py index 9449219..5ec5efd 100644 --- a/pypol/linexprs.py +++ b/pypol/linexprs.py @@ -3,14 +3,14 @@ import functools import numbers import re -from collections import OrderedDict +from collections import OrderedDict, defaultdict, Mapping 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): - right = Constant(right) + right = Rational(right) return func(left, right) return NotImplemented return wrapper @@ -36,56 +36,51 @@ class Expression: '_constant', '_symbols', '_dimension', - '_hash', ) def __new__(cls, coefficients=None, constant=0): if isinstance(coefficients, str): if constant: raise TypeError('too many arguments') - return cls.fromstring(coefficients) - if isinstance(coefficients, dict): - coefficients = coefficients.items() + return Expression.fromstring(coefficients) if coefficients is None: - return Constant(constant) + return Rational(constant) + if isinstance(coefficients, Mapping): + coefficients = coefficients.items() + for symbol, coefficient in coefficients: + if not isinstance(symbol, Symbol): + raise TypeError('symbols must be Symbol instances') coefficients = [(symbol, coefficient) for symbol, coefficient in coefficients if coefficient != 0] if len(coefficients) == 0: - return Constant(constant) - elif len(coefficients) == 1 and constant == 0: + return Rational(constant) + if len(coefficients) == 1 and constant == 0: symbol, coefficient = coefficients[0] if coefficient == 1: - return Symbol(symbol) + return symbol self = object().__new__(cls) - self._coefficients = {} - for symbol, coefficient in coefficients: - if isinstance(symbol, Symbol): - symbol = symbol.name - elif not isinstance(symbol, str): - raise TypeError('symbols must be strings or Symbol instances') - if isinstance(coefficient, Constant): + self._coefficients = OrderedDict() + for symbol, coefficient in sorted(coefficients, + 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 ' - 'or Constant instances') + 'or Rational instances') self._coefficients[symbol] = coefficient - self._coefficients = OrderedDict(sorted(self._coefficients.items())) - 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 ' - 'or a Constant instance') + 'or a Rational instance') self._constant = constant self._symbols = tuple(self._coefficients) self._dimension = len(self._symbols) - self._hash = hash((tuple(self._coefficients.items()), self._constant)) return self def coefficient(self, symbol): - if isinstance(symbol, Symbol): - symbol = symbol.name - elif not isinstance(symbol, str): - raise TypeError('symbol must be a string or a Symbol instance') + if not isinstance(symbol, Symbol): + raise TypeError('symbol must be a Symbol instance') try: return self._coefficients[symbol] except KeyError: @@ -109,7 +104,7 @@ class Expression: return self._dimension def __hash__(self): - return self._hash + return hash((tuple(self._coefficients.items()), self._constant)) def isconstant(self): return False @@ -118,8 +113,7 @@ class Expression: return False def values(self): - for symbol in self.symbols: - yield self.coefficient(symbol) + yield from self._coefficients.values() yield self.constant def __bool__(self): @@ -133,12 +127,9 @@ class Expression: @_polymorphic def __add__(self, other): - coefficients = dict(self.coefficients()) + coefficients = defaultdict(Rational, self.coefficients()) for symbol, coefficient in other.coefficients(): - if symbol in coefficients: - coefficients[symbol] += coefficient - else: - coefficients[symbol] = coefficient + coefficients[symbol] += coefficient constant = self.constant + other.constant return Expression(coefficients, constant) @@ -146,12 +137,9 @@ class Expression: @_polymorphic def __sub__(self, other): - coefficients = dict(self.coefficients()) + coefficients = defaultdict(Rational, self.coefficients()) for symbol, coefficient in other.coefficients(): - if symbol in coefficients: - coefficients[symbol] -= coefficient - else: - coefficients[symbol] = -coefficient + coefficients[symbol] -= coefficient constant = self.constant - other.constant return Expression(coefficients, constant) @@ -178,9 +166,8 @@ class Expression: if other.isconstant(): coefficients = dict(self.coefficients()) for symbol in coefficients: - coefficients[symbol] = \ - Fraction(coefficients[symbol], other.constant) - constant = Fraction(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: ' @@ -190,8 +177,7 @@ class Expression: def __rtruediv__(self, other): if isinstance(other, self): if self.isconstant(): - constant = Fraction(other, self.constant) - return Expression(constant=constant) + return Rational(other, self.constant) else: raise ValueError('non-linear expression: ' '{} / {}'.format(other._parenstr(), self._parenstr())) @@ -202,8 +188,8 @@ class Expression: # "normal" equality # see http://docs.sympy.org/dev/tutorial/gotchas.html#equals-signs return isinstance(other, Expression) and \ - self._coefficients == other._coefficients and \ - self.constant == other.constant + self._coefficients == other._coefficients and \ + self.constant == other.constant @_polymorphic def __le__(self, other): @@ -225,11 +211,28 @@ class Expression: from .polyhedra import Gt return Gt(self, other) - def _toint(self): + def scaleint(self): lcm = functools.reduce(lambda a, b: a*b // gcd(a, b), [value.denominator for value in self.values()]) return self * lcm + def subs(self, symbol, expression=None): + if expression is None: + if isinstance(symbol, Mapping): + symbol = symbol.items() + substitutions = symbol + else: + substitutions = [(symbol, expression)] + result = self + for symbol, expression in substitutions: + coefficients = [(othersymbol, coefficient) + for othersymbol, coefficient in result.coefficients() + if othersymbol != symbol] + coefficient = result.coefficient(symbol) + constant = result.constant + result = Expression(coefficients, constant) + coefficient*expression + return result + @classmethod def _fromast(cls, node): if isinstance(node, ast.Module) and len(node.body) == 1: @@ -239,7 +242,7 @@ class Expression: 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): @@ -260,45 +263,33 @@ class Expression: @classmethod def fromstring(cls, string): # add implicit multiplication operators, e.g. '5x' -> '5*x' - string = cls._RE_NUM_VAR.sub(r'\1*\2', string) + string = Expression._RE_NUM_VAR.sub(r'\1*\2', string) tree = ast.parse(string, 'eval') return cls._fromast(tree) - def __str__(self): + 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 i == 0: - string += symbol - else: - string += ' + {}'.format(symbol) + string += '' if i == 0 else ' + ' + string += '{!r}'.format(symbol) 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: - string += '{}*{}'.format(coefficient, symbol) + string += '{}*{!r}'.format(coefficient, symbol) elif coefficient > 0: - string += ' + {}*{}'.format(coefficient, symbol) + string += ' + {}*{!r}'.format(coefficient, symbol) else: - assert coefficient < 0 - coefficient *= -1 - string += ' - {}*{}'.format(coefficient, symbol) - i += 1 + string += ' - {}*{!r}'.format(-coefficient, symbol) 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: - constant *= -1 - string += ' - {}'.format(constant) - if string == '': - string = '0' + string += ' - {}'.format(-constant) return string def _parenstr(self, always=False): @@ -308,30 +299,27 @@ class Expression: else: return '({})'.format(string) - def __repr__(self): - return '{}({!r})'.format(self.__class__.__name__, str(self)) - @classmethod def fromsympy(cls, expr): import sympy - coefficients = {} + coefficients = [] constant = 0 for symbol, coefficient in expr.as_coefficients_dict().items(): coefficient = Fraction(coefficient.p, coefficient.q) if symbol == sympy.S.One: constant = coefficient elif isinstance(symbol, sympy.Symbol): - symbol = symbol.name - coefficients[symbol] = coefficient + symbol = Symbol(symbol.name) + coefficients.append((symbol, coefficient)) else: raise ValueError('non-linear expression: {!r}'.format(expr)) - return cls(coefficients, constant) + return Expression(coefficients, constant) def tosympy(self): import sympy expr = 0 for symbol, coefficient in self.coefficients(): - term = coefficient * sympy.Symbol(symbol) + term = coefficient * sympy.Symbol(symbol.name) expr += term expr += self.constant return expr @@ -341,18 +329,13 @@ class Symbol(Expression): __slots__ = ( '_name', - '_hash', ) def __new__(cls, name): - if isinstance(name, Symbol): - name = name.name - elif not isinstance(name, str): - raise TypeError('name must be a string or a Symbol instance') - name = name.strip() + if not isinstance(name, str): + raise TypeError('name must be a string') self = object().__new__(cls) - self._name = name - self._hash = hash(self._name) + self._name = name.strip() return self @property @@ -360,20 +343,18 @@ class Symbol(Expression): return self._name def __hash__(self): - return self._hash + return hash(self.sortkey()) def coefficient(self, symbol): - if isinstance(symbol, Symbol): - symbol = symbol.name - elif not isinstance(symbol, str): - raise TypeError('symbol must be a string or a Symbol instance') - if symbol == self.name: + if not isinstance(symbol, Symbol): + raise TypeError('symbol must be a Symbol instance') + if symbol == self: return 1 else: return 0 def coefficients(self): - yield self.name, 1 + yield self, 1 @property def constant(self): @@ -381,17 +362,27 @@ class Symbol(Expression): @property def symbols(self): - return self.name, + return self, @property def dimension(self): return 1 + def sortkey(self): + return self.name, + def issymbol(self): return True + def values(self): + 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): @@ -404,7 +395,7 @@ class Symbol(Expression): raise SyntaxError('invalid syntax') def __repr__(self): - return '{}({!r})'.format(self.__class__.__name__, self._name) + return self.name @classmethod def fromsympy(cls, expr): @@ -415,40 +406,67 @@ class Symbol(Expression): 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 (Symbol(name) for name in names) + return tuple(Symbol(name) for name in names) -class Constant(Expression): +class Rational(Expression): __slots__ = ( '_constant', - '_hash', ) 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._hash = hash(self._constant) return self def __hash__(self): - return self._hash + return hash(self.constant) def coefficient(self, symbol): - if isinstance(symbol, Symbol): - symbol = symbol.name - elif not isinstance(symbol, str): - raise TypeError('symbol must be a string or a Symbol instance') + if not isinstance(symbol, Symbol): + raise TypeError('symbol must be a Symbol instance') return 0 def coefficients(self): - yield from [] + yield from () @property def symbols(self): @@ -461,34 +479,28 @@ class Constant(Expression): def isconstant(self): return True + def values(self): + yield self._constant + @_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 @classmethod def fromstring(cls, string): - if isinstance(string, str): - return Constant(Fraction(string)) - else: + if not isinstance(string, str): raise TypeError('string must be a string instance') - - def __repr__(self): - if self.constant.denominator == 1: - return '{}({!r})'.format(self.__class__.__name__, - self.constant.numerator) - else: - return '{}({!r}, {!r})'.format(self.__class__.__name__, - self.constant.numerator, self.constant.denominator) + return Rational(Fraction(string)) @classmethod def fromsympy(cls, expr): import sympy if isinstance(expr, sympy.Rational): - return cls(expr.p, expr.q) + return Rational(expr.p, expr.q) elif isinstance(expr, numbers.Rational): - return cls(expr) + return Rational(expr) else: raise TypeError('expr must be a sympy.Rational instance')