From: Vivien Maisonneuve Date: Mon, 23 Jun 2014 16:26:49 +0000 (+0200) Subject: Methods Polyhedron.fromsympy(), Polyhedron.tosympy() X-Git-Tag: 1.0~210 X-Git-Url: https://scm.cri.ensmp.fr/git/linpy.git/commitdiff_plain/236157f4861732617ec9078a4364464514bd5b4c?ds=inline;hp=5a4b72c59f689a3eb67303c60a5d76a99d4b097c Methods Polyhedron.fromsympy(), Polyhedron.tosympy() --- diff --git a/pypol/linear.py b/pypol/linear.py index b69836d..74b5477 100644 --- a/pypol/linear.py +++ b/pypol/linear.py @@ -686,6 +686,48 @@ class Polyhedron: return '{}(equalities={!r}, inequalities={!r})' \ ''.format(self.__class__.__name__, equalities, inequalities) + @classmethod + def _fromsympy(cls, expr): + import sympy + equalities = [] + inequalities = [] + if expr.func == sympy.And: + for arg in expr.args: + arg_eqs, arg_ins = cls._fromsympy(arg) + equalities.extend(arg_eqs) + inequalities.extend(arg_ins) + elif expr.func == sympy.Eq: + expr = Expression.fromsympy(expr.args[0] - expr.args[1]) + equalities.append(expr) + else: + if expr.func == sympy.Lt: + expr = Expression.fromsympy(expr.args[1] - expr.args[0] - 1) + elif expr.func == sympy.Le: + expr = Expression.fromsympy(expr.args[1] - expr.args[0]) + elif expr.func == sympy.Ge: + expr = Expression.fromsympy(expr.args[0] - expr.args[1]) + elif expr.func == sympy.Gt: + expr = Expression.fromsympy(expr.args[0] - expr.args[1] - 1) + else: + raise ValueError('non-polyhedral expression: {!r}'.format(expr)) + inequalities.append(expr) + return equalities, inequalities + + @classmethod + def fromsympy(cls, expr): + import sympy + equalities, inequalities = cls._fromsympy(expr) + return cls(equalities, inequalities) + + def tosympy(self): + import sympy + constraints = [] + for equality in self.equalities: + constraints.append(sympy.Eq(equality.tosympy(), 0)) + for inequality in self.inequalities: + constraints.append(sympy.Ge(inequality.tosympy(), 0)) + return sympy.And(*constraints) + def _symbolunion(self, *others): symbols = set(self.symbols) for other in others: