50af0531247fd874e9eebb107e4dc05b02457d3a
1 # Copyright 2014 MINES ParisTech
2 #
3 # This file is part of LinPy.
4 #
5 # LinPy is free software: you can redistribute it and/or modify
7 # the Free Software Foundation, either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # LinPy is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with LinPy. If not, see <http://www.gnu.org/licenses/>.
18 import functools
19 import math
20 import numbers
22 from . import islhelper
24 from .islhelper import mainctx, libisl
25 from .geometry import GeometricObject, Point
26 from .linexprs import LinExpr, Rational
27 from .domains import Domain
30 __all__ = [
31 'Polyhedron',
32 'Lt', 'Le', 'Eq', 'Ne', 'Ge', 'Gt',
33 'Empty', 'Universe',
34 ]
37 class Polyhedron(Domain):
38 """
39 A convex polyhedron (or simply "polyhedron") is the space defined by a
40 system of linear equalities and inequalities. This space can be
41 unbounded.
42 """
44 __slots__ = (
45 '_equalities',
46 '_inequalities',
47 '_symbols',
48 '_dimension',
49 )
51 def __new__(cls, equalities=None, inequalities=None):
52 """
53 Return a polyhedron from two sequences of linear expressions: equalities
54 is a list of expressions equal to 0, and inequalities is a list of
55 expressions greater or equal to 0. For example, the polyhedron
56 0 <= x <= 2, 0 <= y <= 2 can be constructed with:
58 >>> x, y = symbols('x y')
59 >>> square = Polyhedron([], [x, 2 - x, y, 2 - y])
61 It may be easier to use comparison operators LinExpr.__lt__(),
62 LinExpr.__le__(), LinExpr.__ge__(), LinExpr.__gt__(), or functions Lt(),
63 Le(), Eq(), Ge() and Gt(), using one of the following instructions:
65 >>> x, y = symbols('x y')
66 >>> square = (0 <= x) & (x <= 2) & (0 <= y) & (y <= 2)
67 >>> square = Le(0, x, 2) & Le(0, y, 2)
69 It is also possible to build a polyhedron from a string.
71 >>> square = Polyhedron('0 <= x <= 2, 0 <= y <= 2')
73 Finally, a polyhedron can be constructed from a GeometricObject
74 instance, calling the GeometricObject.aspolyedron() method. This way, it
75 is possible to compute the polyhedral hull of a Domain instance, i.e.,
76 the convex hull of two polyhedra:
78 >>> square = Polyhedron('0 <= x <= 2, 0 <= y <= 2')
79 >>> square2 = Polyhedron('2 <= x <= 4, 2 <= y <= 4')
80 >>> Polyhedron(square | square2)
81 """
82 if isinstance(equalities, str):
83 if inequalities is not None:
84 raise TypeError('too many arguments')
85 return cls.fromstring(equalities)
86 elif isinstance(equalities, GeometricObject):
87 if inequalities is not None:
88 raise TypeError('too many arguments')
89 return equalities.aspolyhedron()
90 sc_equalities = []
91 if equalities is not None:
92 for equality in equalities:
93 if not isinstance(equality, LinExpr):
94 raise TypeError('equalities must be linear expressions')
95 sc_equalities.append(equality.scaleint())
96 sc_inequalities = []
97 if inequalities is not None:
98 for inequality in inequalities:
99 if not isinstance(inequality, LinExpr):
100 raise TypeError('inequalities must be linear expressions')
101 sc_inequalities.append(inequality.scaleint())
102 symbols = cls._xsymbols(sc_equalities + sc_inequalities)
103 islbset = cls._toislbasicset(sc_equalities, sc_inequalities, symbols)
104 return cls._fromislbasicset(islbset, symbols)
106 @property
107 def equalities(self):
108 """
109 The tuple of equalities. This is a list of LinExpr instances that are
110 equal to 0 in the polyhedron.
111 """
112 return self._equalities
114 @property
115 def inequalities(self):
116 """
117 The tuple of inequalities. This is a list of LinExpr instances that are
118 greater or equal to 0 in the polyhedron.
119 """
120 return self._inequalities
122 @property
123 def constraints(self):
124 """
125 The tuple of constraints, i.e., equalities and inequalities. This is
126 semantically equivalent to: equalities + inequalities.
127 """
128 return self._equalities + self._inequalities
130 @property
131 def polyhedra(self):
132 return self,
134 def make_disjoint(self):
135 return self
137 def isuniverse(self):
138 islbset = self._toislbasicset(self.equalities, self.inequalities,
139 self.symbols)
140 universe = bool(libisl.isl_basic_set_is_universe(islbset))
141 libisl.isl_basic_set_free(islbset)
142 return universe
144 def aspolyhedron(self):
145 return self
147 def convex_union(self, *others):
148 """
149 Return the convex union of two or more polyhedra.
150 """
151 for other in others:
152 if not isinstance(other, Polyhedron):
153 raise TypeError('arguments must be Polyhedron instances')
154 return Polyhedron(self.union(*others))
156 def __contains__(self, point):
157 if not isinstance(point, Point):
158 raise TypeError('point must be a Point instance')
159 if self.symbols != point.symbols:
160 raise ValueError('arguments must belong to the same space')
161 for equality in self.equalities:
162 if equality.subs(point.coordinates()) != 0:
163 return False
164 for inequality in self.inequalities:
165 if inequality.subs(point.coordinates()) < 0:
166 return False
167 return True
169 def subs(self, symbol, expression=None):
170 equalities = [equality.subs(symbol, expression)
171 for equality in self.equalities]
172 inequalities = [inequality.subs(symbol, expression)
173 for inequality in self.inequalities]
174 return Polyhedron(equalities, inequalities)
176 def _asinequalities(self):
177 inequalities = list(self.equalities)
178 inequalities.extend([-expression for expression in self.equalities])
179 inequalities.extend(self.inequalities)
180 return inequalities
182 def widen(self, other):
183 """
184 Compute the standard widening of two polyhedra, à la Halbwachs.
186 In its current implementation, this method is slow and should not be
187 used on large polyhedra.
188 """
189 if not isinstance(other, Polyhedron):
190 raise TypeError('argument must be a Polyhedron instance')
191 inequalities1 = self._asinequalities()
192 inequalities2 = other._asinequalities()
193 inequalities = []
194 for inequality1 in inequalities1:
195 if other <= Polyhedron(inequalities=[inequality1]):
196 inequalities.append(inequality1)
197 for inequality2 in inequalities2:
198 for i in range(len(inequalities1)):
199 inequalities3 = inequalities1[:i] + inequalities[i + 1:]
200 inequalities3.append(inequality2)
201 polyhedron3 = Polyhedron(inequalities=inequalities3)
202 if self == polyhedron3:
203 inequalities.append(inequality2)
204 break
205 return Polyhedron(inequalities=inequalities)
207 @classmethod
208 def _fromislbasicset(cls, islbset, symbols):
209 islconstraints = islhelper.isl_basic_set_constraints(islbset)
210 equalities = []
211 inequalities = []
212 for islconstraint in islconstraints:
213 constant = libisl.isl_constraint_get_constant_val(islconstraint)
214 constant = islhelper.isl_val_to_int(constant)
215 coefficients = {}
216 for index, symbol in enumerate(symbols):
217 coefficient = libisl.isl_constraint_get_coefficient_val(islconstraint,
218 libisl.isl_dim_set, index)
219 coefficient = islhelper.isl_val_to_int(coefficient)
220 if coefficient != 0:
221 coefficients[symbol] = coefficient
222 expression = LinExpr(coefficients, constant)
223 if libisl.isl_constraint_is_equality(islconstraint):
224 equalities.append(expression)
225 else:
226 inequalities.append(expression)
227 libisl.isl_basic_set_free(islbset)
228 self = object().__new__(Polyhedron)
229 self._equalities = tuple(equalities)
230 self._inequalities = tuple(inequalities)
231 self._symbols = cls._xsymbols(self.constraints)
232 self._dimension = len(self._symbols)
233 return self
235 @classmethod
236 def _toislbasicset(cls, equalities, inequalities, symbols):
237 dimension = len(symbols)
238 indices = {symbol: index for index, symbol in enumerate(symbols)}
239 islsp = libisl.isl_space_set_alloc(mainctx, 0, dimension)
240 islbset = libisl.isl_basic_set_universe(libisl.isl_space_copy(islsp))
241 islls = libisl.isl_local_space_from_space(islsp)
242 for equality in equalities:
243 isleq = libisl.isl_equality_alloc(libisl.isl_local_space_copy(islls))
244 for symbol, coefficient in equality.coefficients():
245 islval = str(coefficient).encode()
247 index = indices[symbol]
248 isleq = libisl.isl_constraint_set_coefficient_val(isleq,
249 libisl.isl_dim_set, index, islval)
250 if equality.constant != 0:
251 islval = str(equality.constant).encode()
253 isleq = libisl.isl_constraint_set_constant_val(isleq, islval)
255 for inequality in inequalities:
256 islin = libisl.isl_inequality_alloc(libisl.isl_local_space_copy(islls))
257 for symbol, coefficient in inequality.coefficients():
258 islval = str(coefficient).encode()
260 index = indices[symbol]
261 islin = libisl.isl_constraint_set_coefficient_val(islin,
262 libisl.isl_dim_set, index, islval)
263 if inequality.constant != 0:
264 islval = str(inequality.constant).encode()
266 islin = libisl.isl_constraint_set_constant_val(islin, islval)
268 return islbset
270 @classmethod
271 def fromstring(cls, string):
272 domain = Domain.fromstring(string)
273 if not isinstance(domain, Polyhedron):
274 raise ValueError('non-polyhedral expression: {!r}'.format(string))
275 return domain
277 def __repr__(self):
278 strings = []
279 for equality in self.equalities:
280 strings.append('Eq({}, 0)'.format(equality))
281 for inequality in self.inequalities:
282 strings.append('Ge({}, 0)'.format(inequality))
283 if len(strings) == 1:
284 return strings[0]
285 else:
286 return 'And({})'.format(', '.join(strings))
288 def _repr_latex_(self):
289 strings = []
290 for equality in self.equalities:
291 strings.append('{} = 0'.format(equality._repr_latex_().strip('\$')))
292 for inequality in self.inequalities:
293 strings.append('{} \\ge 0'.format(inequality._repr_latex_().strip('\$')))
294 return '\$\${}\$\$'.format(' \\wedge '.join(strings))
296 @classmethod
297 def fromsympy(cls, expr):
298 domain = Domain.fromsympy(expr)
299 if not isinstance(domain, Polyhedron):
300 raise ValueError('non-polyhedral expression: {!r}'.format(expr))
301 return domain
303 def tosympy(self):
304 import sympy
305 constraints = []
306 for equality in self.equalities:
307 constraints.append(sympy.Eq(equality.tosympy(), 0))
308 for inequality in self.inequalities:
309 constraints.append(sympy.Ge(inequality.tosympy(), 0))
310 return sympy.And(*constraints)
313 class EmptyType(Polyhedron):
314 """
315 The empty polyhedron, whose set of constraints is not satisfiable.
316 """
318 def __new__(cls):
319 self = object().__new__(cls)
320 self._equalities = (Rational(1),)
321 self._inequalities = ()
322 self._symbols = ()
323 self._dimension = 0
324 return self
326 def widen(self, other):
327 if not isinstance(other, Polyhedron):
328 raise ValueError('argument must be a Polyhedron instance')
329 return other
331 def __repr__(self):
332 return 'Empty'
334 def _repr_latex_(self):
335 return '\$\$\\emptyset\$\$'
337 Empty = EmptyType()
340 class UniverseType(Polyhedron):
341 """
342 The universe polyhedron, whose set of constraints is always satisfiable,
343 i.e. is empty.
344 """
346 def __new__(cls):
347 self = object().__new__(cls)
348 self._equalities = ()
349 self._inequalities = ()
350 self._symbols = ()
351 self._dimension = ()
352 return self
354 def __repr__(self):
355 return 'Universe'
357 def _repr_latex_(self):
358 return '\$\$\\Omega\$\$'
360 Universe = UniverseType()
363 def _polymorphic(func):
364 @functools.wraps(func)
365 def wrapper(left, right):
366 if not isinstance(left, LinExpr):
367 if isinstance(left, numbers.Rational):
368 left = Rational(left)
369 else:
370 raise TypeError('left must be a a rational number '
371 'or a linear expression')
372 if not isinstance(right, LinExpr):
373 if isinstance(right, numbers.Rational):
374 right = Rational(right)
375 else:
376 raise TypeError('right must be a a rational number '
377 'or a linear expression')
378 return func(left, right)
379 return wrapper
381 @_polymorphic
382 def Lt(left, right):
383 """
384 Create the polyhedron with constraints expr1 < expr2 < expr3 ...
385 """
386 return Polyhedron([], [right - left - 1])
388 @_polymorphic
389 def Le(left, right):
390 """
391 Create the polyhedron with constraints expr1 <= expr2 <= expr3 ...
392 """
393 return Polyhedron([], [right - left])
395 @_polymorphic
396 def Eq(left, right):
397 """
398 Create the polyhedron with constraints expr1 == expr2 == expr3 ...
399 """
400 return Polyhedron([left - right], [])
402 @_polymorphic
403 def Ne(left, right):
404 """
405 Create the domain such that expr1 != expr2 != expr3 ... The result is a
406 Domain, not a Polyhedron.
407 """
408 return ~Eq(left, right)
410 @_polymorphic
411 def Ge(left, right):
412 """
413 Create the polyhedron with constraints expr1 >= expr2 >= expr3 ...
414 """
415 return Polyhedron([], [left - right])
417 @_polymorphic
418 def Gt(left, right):
419 """
420 Create the polyhedron with constraints expr1 > expr2 > expr3 ...
421 """
422 return Polyhedron([], [left - right - 1])