1 # Copyright 2014 MINES ParisTech
3 # This file is part of LinPy.
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.
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.
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/>.
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
32 'Lt', 'Le', 'Eq', 'Ne', 'Ge', 'Gt',
37 class Polyhedron(Domain
):
39 A convex polyhedron (or simply "polyhedron") is the space defined by a
40 system of linear equalities and inequalities. This space can be unbounded. A
41 Z-polyhedron (simply called "polyhedron" in LinPy) is the set of integer
42 points in a convex polyhedron.
52 def __new__(cls
, equalities
=None, inequalities
=None):
54 Return a polyhedron from two sequences of linear expressions: equalities
55 is a list of expressions equal to 0, and inequalities is a list of
56 expressions greater or equal to 0. For example, the polyhedron
57 0 <= x <= 2, 0 <= y <= 2 can be constructed with:
59 >>> x, y = symbols('x y')
60 >>> square1 = Polyhedron([], [x, 2 - x, y, 2 - y])
62 And(0 <= x, x <= 2, 0 <= y, y <= 2)
64 It may be easier to use comparison operators LinExpr.__lt__(),
65 LinExpr.__le__(), LinExpr.__ge__(), LinExpr.__gt__(), or functions Lt(),
66 Le(), Eq(), Ge() and Gt(), using one of the following instructions:
68 >>> x, y = symbols('x y')
69 >>> square1 = (0 <= x) & (x <= 2) & (0 <= y) & (y <= 2)
70 >>> square1 = Le(0, x, 2) & Le(0, y, 2)
72 It is also possible to build a polyhedron from a string.
74 >>> square1 = Polyhedron('0 <= x <= 2, 0 <= y <= 2')
76 Finally, a polyhedron can be constructed from a GeometricObject
77 instance, calling the GeometricObject.aspolyedron() method. This way, it
78 is possible to compute the polyhedral hull of a Domain instance, i.e.,
79 the convex hull of two polyhedra:
81 >>> square1 = Polyhedron('0 <= x <= 2, 0 <= y <= 2')
82 >>> square2 = Polyhedron('1 <= x <= 3, 1 <= y <= 3')
83 >>> Polyhedron(square1 | square2)
84 And(0 <= x, 0 <= y, x <= y + 2, y <= x + 2, x <= 3, y <= 3)
86 if isinstance(equalities
, str):
87 if inequalities
is not None:
88 raise TypeError('too many arguments')
89 return cls
.fromstring(equalities
)
90 elif isinstance(equalities
, GeometricObject
):
91 if inequalities
is not None:
92 raise TypeError('too many arguments')
93 return equalities
.aspolyhedron()
95 if equalities
is not None:
96 for equality
in equalities
:
97 if isinstance(equality
, LinExpr
):
98 sc_equalities
.append(equality
.scaleint())
99 elif isinstance(equality
, numbers
.Rational
):
100 sc_equalities
.append(Rational(equality
).scaleint())
102 raise TypeError('equalities must be linear expressions '
103 'or rational numbers')
105 if inequalities
is not None:
106 for inequality
in inequalities
:
107 if isinstance(inequality
, LinExpr
):
108 sc_inequalities
.append(inequality
.scaleint())
109 elif isinstance(inequality
, numbers
.Rational
):
110 sc_inequalities
.append(Rational(inequality
).scaleint())
112 raise TypeError('inequalities must be linear expressions '
113 'or rational numbers')
114 symbols
= cls
._xsymbols
(sc_equalities
+ sc_inequalities
)
115 islbset
= cls
._toislbasicset
(sc_equalities
, sc_inequalities
, symbols
)
116 return cls
._fromislbasicset
(islbset
, symbols
)
119 def equalities(self
):
121 The tuple of equalities. This is a list of LinExpr instances that are
122 equal to 0 in the polyhedron.
124 return self
._equalities
127 def inequalities(self
):
129 The tuple of inequalities. This is a list of LinExpr instances that are
130 greater or equal to 0 in the polyhedron.
132 return self
._inequalities
135 def constraints(self
):
137 The tuple of constraints, i.e., equalities and inequalities. This is
138 semantically equivalent to: equalities + inequalities.
140 return self
._equalities
+ self
._inequalities
146 def make_disjoint(self
):
149 def isuniverse(self
):
150 islbset
= self
._toislbasicset
(self
.equalities
, self
.inequalities
,
152 universe
= bool(libisl
.isl_basic_set_is_universe(islbset
))
153 libisl
.isl_basic_set_free(islbset
)
156 def aspolyhedron(self
):
159 def convex_union(self
, *others
):
161 Return the convex union of two or more polyhedra.
164 if not isinstance(other
, Polyhedron
):
165 raise TypeError('arguments must be Polyhedron instances')
166 return Polyhedron(self
.union(*others
))
168 def __contains__(self
, point
):
169 if not isinstance(point
, Point
):
170 raise TypeError('point must be a Point instance')
171 if self
.symbols
!= point
.symbols
:
172 raise ValueError('arguments must belong to the same space')
173 for equality
in self
.equalities
:
174 if equality
.subs(point
.coordinates()) != 0:
176 for inequality
in self
.inequalities
:
177 if inequality
.subs(point
.coordinates()) < 0:
181 def subs(self
, symbol
, expression
=None):
182 equalities
= [equality
.subs(symbol
, expression
)
183 for equality
in self
.equalities
]
184 inequalities
= [inequality
.subs(symbol
, expression
)
185 for inequality
in self
.inequalities
]
186 return Polyhedron(equalities
, inequalities
)
188 def asinequalities(self
):
190 Express the polyhedron using inequalities, given as a list of
191 expressions greater or equal to 0.
193 inequalities
= list(self
.equalities
)
194 inequalities
.extend([-expression
for expression
in self
.equalities
])
195 inequalities
.extend(self
.inequalities
)
198 def widen(self
, other
):
200 Compute the standard widening of two polyhedra, à la Halbwachs.
202 In its current implementation, this method is slow and should not be
203 used on large polyhedra.
205 if not isinstance(other
, Polyhedron
):
206 raise TypeError('argument must be a Polyhedron instance')
207 inequalities1
= self
.asinequalities()
208 inequalities2
= other
.asinequalities()
210 for inequality1
in inequalities1
:
211 if other
<= Polyhedron(inequalities
=[inequality1
]):
212 inequalities
.append(inequality1
)
213 for inequality2
in inequalities2
:
214 for i
in range(len(inequalities1
)):
215 inequalities3
= inequalities1
[:i
] + inequalities
[i
+ 1:]
216 inequalities3
.append(inequality2
)
217 polyhedron3
= Polyhedron(inequalities
=inequalities3
)
218 if self
== polyhedron3
:
219 inequalities
.append(inequality2
)
221 return Polyhedron(inequalities
=inequalities
)
224 def _fromislbasicset(cls
, islbset
, symbols
):
225 islconstraints
= islhelper
.isl_basic_set_constraints(islbset
)
228 for islconstraint
in islconstraints
:
229 constant
= libisl
.isl_constraint_get_constant_val(islconstraint
)
230 constant
= islhelper
.isl_val_to_int(constant
)
232 for index
, symbol
in enumerate(symbols
):
233 coefficient
= libisl
.isl_constraint_get_coefficient_val(islconstraint
,
234 libisl
.isl_dim_set
, index
)
235 coefficient
= islhelper
.isl_val_to_int(coefficient
)
237 coefficients
[symbol
] = coefficient
238 expression
= LinExpr(coefficients
, constant
)
239 if libisl
.isl_constraint_is_equality(islconstraint
):
240 equalities
.append(expression
)
242 inequalities
.append(expression
)
243 libisl
.isl_basic_set_free(islbset
)
244 self
= object().__new
__(Polyhedron
)
245 self
._equalities
= tuple(equalities
)
246 self
._inequalities
= tuple(inequalities
)
247 self
._symbols
= cls
._xsymbols
(self
.constraints
)
248 self
._dimension
= len(self
._symbols
)
252 def _toislbasicset(cls
, equalities
, inequalities
, symbols
):
253 dimension
= len(symbols
)
254 indices
= {symbol
: index
for index
, symbol
in enumerate(symbols
)}
255 islsp
= libisl
.isl_space_set_alloc(mainctx
, 0, dimension
)
256 islbset
= libisl
.isl_basic_set_universe(libisl
.isl_space_copy(islsp
))
257 islls
= libisl
.isl_local_space_from_space(islsp
)
258 for equality
in equalities
:
259 isleq
= libisl
.isl_equality_alloc(libisl
.isl_local_space_copy(islls
))
260 for symbol
, coefficient
in equality
.coefficients():
261 islval
= str(coefficient
).encode()
262 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
263 index
= indices
[symbol
]
264 isleq
= libisl
.isl_constraint_set_coefficient_val(isleq
,
265 libisl
.isl_dim_set
, index
, islval
)
266 if equality
.constant
!= 0:
267 islval
= str(equality
.constant
).encode()
268 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
269 isleq
= libisl
.isl_constraint_set_constant_val(isleq
, islval
)
270 islbset
= libisl
.isl_basic_set_add_constraint(islbset
, isleq
)
271 for inequality
in inequalities
:
272 islin
= libisl
.isl_inequality_alloc(libisl
.isl_local_space_copy(islls
))
273 for symbol
, coefficient
in inequality
.coefficients():
274 islval
= str(coefficient
).encode()
275 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
276 index
= indices
[symbol
]
277 islin
= libisl
.isl_constraint_set_coefficient_val(islin
,
278 libisl
.isl_dim_set
, index
, islval
)
279 if inequality
.constant
!= 0:
280 islval
= str(inequality
.constant
).encode()
281 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
282 islin
= libisl
.isl_constraint_set_constant_val(islin
, islval
)
283 islbset
= libisl
.isl_basic_set_add_constraint(islbset
, islin
)
287 def fromstring(cls
, string
):
288 domain
= Domain
.fromstring(string
)
289 if not isinstance(domain
, Polyhedron
):
290 raise ValueError('non-polyhedral expression: {!r}'.format(string
))
295 for equality
in self
.equalities
:
296 left
, right
, swap
= 0, 0, False
297 for i
, (symbol
, coefficient
) in enumerate(equality
.coefficients()):
299 left
+= coefficient
* symbol
301 right
-= coefficient
* symbol
304 if equality
.constant
> 0:
305 left
+= equality
.constant
307 right
-= equality
.constant
309 left
, right
= right
, left
310 strings
.append('{} == {}'.format(left
, right
))
311 for inequality
in self
.inequalities
:
313 for symbol
, coefficient
in inequality
.coefficients():
315 left
-= coefficient
* symbol
317 right
+= coefficient
* symbol
318 if inequality
.constant
< 0:
319 left
-= inequality
.constant
321 right
+= inequality
.constant
322 strings
.append('{} <= {}'.format(left
, right
))
323 if len(strings
) == 1:
326 return 'And({})'.format(', '.join(strings
))
329 def fromsympy(cls
, expression
):
330 domain
= Domain
.fromsympy(expression
)
331 if not isinstance(domain
, Polyhedron
):
332 raise ValueError('non-polyhedral expression: {!r}'.format(expression
))
338 for equality
in self
.equalities
:
339 constraints
.append(sympy
.Eq(equality
.tosympy(), 0))
340 for inequality
in self
.inequalities
:
341 constraints
.append(sympy
.Ge(inequality
.tosympy(), 0))
342 return sympy
.And(*constraints
)
345 class EmptyType(Polyhedron
):
347 The empty polyhedron, whose set of constraints is not satisfiable.
351 self
= object().__new
__(cls
)
352 self
._equalities
= (Rational(1),)
353 self
._inequalities
= ()
358 def widen(self
, other
):
359 if not isinstance(other
, Polyhedron
):
360 raise ValueError('argument must be a Polyhedron instance')
369 class UniverseType(Polyhedron
):
371 The universe polyhedron, whose set of constraints is always satisfiable,
376 self
= object().__new
__(cls
)
377 self
._equalities
= ()
378 self
._inequalities
= ()
386 Universe
= UniverseType()
389 def _pseudoconstructor(func
):
390 @functools.wraps(func
)
391 def wrapper(expression1
, expression2
, *expressions
):
392 expressions
= (expression1
, expression2
) + expressions
393 for expression
in expressions
:
394 if not isinstance(expression
, LinExpr
):
395 if isinstance(expression
, numbers
.Rational
):
396 expression
= Rational(expression
)
398 raise TypeError('arguments must be rational numbers '
399 'or linear expressions')
400 return func(*expressions
)
404 def Lt(*expressions
):
406 Create the polyhedron with constraints expr1 < expr2 < expr3 ...
409 for left
, right
in zip(expressions
, expressions
[1:]):
410 inequalities
.append(right
- left
- 1)
411 return Polyhedron([], inequalities
)
414 def Le(*expressions
):
416 Create the polyhedron with constraints expr1 <= expr2 <= expr3 ...
419 for left
, right
in zip(expressions
, expressions
[1:]):
420 inequalities
.append(right
- left
)
421 return Polyhedron([], inequalities
)
424 def Eq(*expressions
):
426 Create the polyhedron with constraints expr1 == expr2 == expr3 ...
429 for left
, right
in zip(expressions
, expressions
[1:]):
430 equalities
.append(left
- right
)
431 return Polyhedron(equalities
, [])
434 def Ne(*expressions
):
436 Create the domain such that expr1 != expr2 != expr3 ... The result is a
437 Domain object, not a Polyhedron.
440 for left
, right
in zip(expressions
, expressions
[1:]):
441 domain
&= ~
Eq(left
, right
)
445 def Ge(*expressions
):
447 Create the polyhedron with constraints expr1 >= expr2 >= expr3 ...
450 for left
, right
in zip(expressions
, expressions
[1:]):
451 inequalities
.append(left
- right
)
452 return Polyhedron([], inequalities
)
455 def Gt(*expressions
):
457 Create the polyhedron with constraints expr1 > expr2 > expr3 ...
460 for left
, right
in zip(expressions
, expressions
[1:]):
461 inequalities
.append(left
- right
- 1)
462 return Polyhedron([], inequalities
)