Add warning in widening documentation
[linpy.git] / linpy / polyhedra.py
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
6 # it under the terms of the GNU General Public License as published by
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/>.
17
18 import functools
19 import math
20 import numbers
21
22 from . import islhelper
23
24 from .islhelper import mainctx, libisl
25 from .geometry import GeometricObject, Point
26 from .linexprs import LinExpr, Rational
27 from .domains import Domain
28
29
30 __all__ = [
31 'Polyhedron',
32 'Lt', 'Le', 'Eq', 'Ne', 'Ge', 'Gt',
33 'Empty', 'Universe',
34 ]
35
36
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 """
43
44 __slots__ = (
45 '_equalities',
46 '_inequalities',
47 '_symbols',
48 '_dimension',
49 )
50
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:
57
58 >>> x, y = symbols('x y')
59 >>> square = Polyhedron([], [x, 2 - x, y, 2 - y])
60
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:
64
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)
68
69 It is also possible to build a polyhedron from a string.
70
71 >>> square = Polyhedron('0 <= x <= 2, 0 <= y <= 2')
72
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:
77
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)
105
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
113
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
121
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
129
130 @property
131 def polyhedra(self):
132 return self,
133
134 def make_disjoint(self):
135 return self
136
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
143
144 def aspolyhedron(self):
145 return self
146
147 def __contains__(self, point):
148 if not isinstance(point, Point):
149 raise TypeError('point must be a Point instance')
150 if self.symbols != point.symbols:
151 raise ValueError('arguments must belong to the same space')
152 for equality in self.equalities:
153 if equality.subs(point.coordinates()) != 0:
154 return False
155 for inequality in self.inequalities:
156 if inequality.subs(point.coordinates()) < 0:
157 return False
158 return True
159
160 def subs(self, symbol, expression=None):
161 equalities = [equality.subs(symbol, expression)
162 for equality in self.equalities]
163 inequalities = [inequality.subs(symbol, expression)
164 for inequality in self.inequalities]
165 return Polyhedron(equalities, inequalities)
166
167 def _asinequalities(self):
168 inequalities = list(self.equalities)
169 inequalities.extend([-expression for expression in self.equalities])
170 inequalities.extend(self.inequalities)
171 return inequalities
172
173 def widen(self, other):
174 """
175 Compute the standard widening of two polyhedra, à la Halbwachs.
176
177 In its current implementation, this method is slow and should not be
178 used on large polyhedra.
179 """
180 if not isinstance(other, Polyhedron):
181 raise ValueError('argument must be a Polyhedron instance')
182 inequalities1 = self._asinequalities()
183 inequalities2 = other._asinequalities()
184 inequalities = []
185 for inequality1 in inequalities1:
186 if other <= Polyhedron(inequalities=[inequality1]):
187 inequalities.append(inequality1)
188 for inequality2 in inequalities2:
189 for i in range(len(inequalities1)):
190 inequalities3 = inequalities1[:i] + inequalities[i + 1:]
191 inequalities3.append(inequality2)
192 polyhedron3 = Polyhedron(inequalities=inequalities3)
193 if self == polyhedron3:
194 inequalities.append(inequality2)
195 break
196 return Polyhedron(inequalities=inequalities)
197
198 @classmethod
199 def _fromislbasicset(cls, islbset, symbols):
200 islconstraints = islhelper.isl_basic_set_constraints(islbset)
201 equalities = []
202 inequalities = []
203 for islconstraint in islconstraints:
204 constant = libisl.isl_constraint_get_constant_val(islconstraint)
205 constant = islhelper.isl_val_to_int(constant)
206 coefficients = {}
207 for index, symbol in enumerate(symbols):
208 coefficient = libisl.isl_constraint_get_coefficient_val(islconstraint,
209 libisl.isl_dim_set, index)
210 coefficient = islhelper.isl_val_to_int(coefficient)
211 if coefficient != 0:
212 coefficients[symbol] = coefficient
213 expression = LinExpr(coefficients, constant)
214 if libisl.isl_constraint_is_equality(islconstraint):
215 equalities.append(expression)
216 else:
217 inequalities.append(expression)
218 libisl.isl_basic_set_free(islbset)
219 self = object().__new__(Polyhedron)
220 self._equalities = tuple(equalities)
221 self._inequalities = tuple(inequalities)
222 self._symbols = cls._xsymbols(self.constraints)
223 self._dimension = len(self._symbols)
224 return self
225
226 @classmethod
227 def _toislbasicset(cls, equalities, inequalities, symbols):
228 dimension = len(symbols)
229 indices = {symbol: index for index, symbol in enumerate(symbols)}
230 islsp = libisl.isl_space_set_alloc(mainctx, 0, dimension)
231 islbset = libisl.isl_basic_set_universe(libisl.isl_space_copy(islsp))
232 islls = libisl.isl_local_space_from_space(islsp)
233 for equality in equalities:
234 isleq = libisl.isl_equality_alloc(libisl.isl_local_space_copy(islls))
235 for symbol, coefficient in equality.coefficients():
236 islval = str(coefficient).encode()
237 islval = libisl.isl_val_read_from_str(mainctx, islval)
238 index = indices[symbol]
239 isleq = libisl.isl_constraint_set_coefficient_val(isleq,
240 libisl.isl_dim_set, index, islval)
241 if equality.constant != 0:
242 islval = str(equality.constant).encode()
243 islval = libisl.isl_val_read_from_str(mainctx, islval)
244 isleq = libisl.isl_constraint_set_constant_val(isleq, islval)
245 islbset = libisl.isl_basic_set_add_constraint(islbset, isleq)
246 for inequality in inequalities:
247 islin = libisl.isl_inequality_alloc(libisl.isl_local_space_copy(islls))
248 for symbol, coefficient in inequality.coefficients():
249 islval = str(coefficient).encode()
250 islval = libisl.isl_val_read_from_str(mainctx, islval)
251 index = indices[symbol]
252 islin = libisl.isl_constraint_set_coefficient_val(islin,
253 libisl.isl_dim_set, index, islval)
254 if inequality.constant != 0:
255 islval = str(inequality.constant).encode()
256 islval = libisl.isl_val_read_from_str(mainctx, islval)
257 islin = libisl.isl_constraint_set_constant_val(islin, islval)
258 islbset = libisl.isl_basic_set_add_constraint(islbset, islin)
259 return islbset
260
261 @classmethod
262 def fromstring(cls, string):
263 domain = Domain.fromstring(string)
264 if not isinstance(domain, Polyhedron):
265 raise ValueError('non-polyhedral expression: {!r}'.format(string))
266 return domain
267
268 def __repr__(self):
269 strings = []
270 for equality in self.equalities:
271 strings.append('Eq({}, 0)'.format(equality))
272 for inequality in self.inequalities:
273 strings.append('Ge({}, 0)'.format(inequality))
274 if len(strings) == 1:
275 return strings[0]
276 else:
277 return 'And({})'.format(', '.join(strings))
278
279 def _repr_latex_(self):
280 strings = []
281 for equality in self.equalities:
282 strings.append('{} = 0'.format(equality._repr_latex_().strip('$')))
283 for inequality in self.inequalities:
284 strings.append('{} \\ge 0'.format(inequality._repr_latex_().strip('$')))
285 return '$${}$$'.format(' \\wedge '.join(strings))
286
287 @classmethod
288 def fromsympy(cls, expr):
289 domain = Domain.fromsympy(expr)
290 if not isinstance(domain, Polyhedron):
291 raise ValueError('non-polyhedral expression: {!r}'.format(expr))
292 return domain
293
294 def tosympy(self):
295 import sympy
296 constraints = []
297 for equality in self.equalities:
298 constraints.append(sympy.Eq(equality.tosympy(), 0))
299 for inequality in self.inequalities:
300 constraints.append(sympy.Ge(inequality.tosympy(), 0))
301 return sympy.And(*constraints)
302
303
304 class EmptyType(Polyhedron):
305 """
306 The empty polyhedron, whose set of constraints is not satisfiable.
307 """
308
309 __slots__ = Polyhedron.__slots__
310
311 def __new__(cls):
312 self = object().__new__(cls)
313 self._equalities = (Rational(1),)
314 self._inequalities = ()
315 self._symbols = ()
316 self._dimension = 0
317 return self
318
319 def widen(self, other):
320 if not isinstance(other, Polyhedron):
321 raise ValueError('argument must be a Polyhedron instance')
322 return other
323
324 def __repr__(self):
325 return 'Empty'
326
327 def _repr_latex_(self):
328 return '$$\\emptyset$$'
329
330 Empty = EmptyType()
331
332
333 class UniverseType(Polyhedron):
334 """
335 The universe polyhedron, whose set of constraints is always satisfiable,
336 i.e. is empty.
337 """
338
339 __slots__ = Polyhedron.__slots__
340
341 def __new__(cls):
342 self = object().__new__(cls)
343 self._equalities = ()
344 self._inequalities = ()
345 self._symbols = ()
346 self._dimension = ()
347 return self
348
349 def __repr__(self):
350 return 'Universe'
351
352 def _repr_latex_(self):
353 return '$$\\Omega$$'
354
355 Universe = UniverseType()
356
357
358 def _polymorphic(func):
359 @functools.wraps(func)
360 def wrapper(left, right):
361 if not isinstance(left, LinExpr):
362 if isinstance(left, numbers.Rational):
363 left = Rational(left)
364 else:
365 raise TypeError('left must be a a rational number '
366 'or a linear expression')
367 if not isinstance(right, LinExpr):
368 if isinstance(right, numbers.Rational):
369 right = Rational(right)
370 else:
371 raise TypeError('right must be a a rational number '
372 'or a linear expression')
373 return func(left, right)
374 return wrapper
375
376 @_polymorphic
377 def Lt(left, right):
378 """
379 Create the polyhedron with constraints expr1 < expr2 < expr3 ...
380 """
381 return Polyhedron([], [right - left - 1])
382
383 @_polymorphic
384 def Le(left, right):
385 """
386 Create the polyhedron with constraints expr1 <= expr2 <= expr3 ...
387 """
388 return Polyhedron([], [right - left])
389
390 @_polymorphic
391 def Eq(left, right):
392 """
393 Create the polyhedron with constraints expr1 == expr2 == expr3 ...
394 """
395 return Polyhedron([left - right], [])
396
397 @_polymorphic
398 def Ne(left, right):
399 """
400 Create the domain such that expr1 != expr2 != expr3 ... The result is a
401 Domain, not a Polyhedron.
402 """
403 return ~Eq(left, right)
404
405 @_polymorphic
406 def Gt(left, right):
407 """
408 Create the polyhedron with constraints expr1 > expr2 > expr3 ...
409 """
410 return Polyhedron([], [left - right - 1])
411
412 @_polymorphic
413 def Ge(left, right):
414 """
415 Create the polyhedron with constraints expr1 >= expr2 >= expr3 ...
416 """
417 return Polyhedron([], [left - right])