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
51 def __new__(cls
, equalities
=None, inequalities
=None):
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)
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()
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())
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
)
107 def equalities(self
):
109 The tuple of equalities. This is a list of LinExpr instances that are
110 equal to 0 in the polyhedron.
112 return self
._equalities
115 def inequalities(self
):
117 The tuple of inequalities. This is a list of LinExpr instances that are
118 greater or equal to 0 in the polyhedron.
120 return self
._inequalities
123 def constraints(self
):
125 The tuple of constraints, i.e., equalities and inequalities. This is
126 semantically equivalent to: equalities + inequalities.
128 return self
._equalities
+ self
._inequalities
134 def make_disjoint(self
):
137 def isuniverse(self
):
138 islbset
= self
._toislbasicset
(self
.equalities
, self
.inequalities
,
140 universe
= bool(libisl
.isl_basic_set_is_universe(islbset
))
141 libisl
.isl_basic_set_free(islbset
)
144 def aspolyhedron(self
):
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:
155 for inequality
in self
.inequalities
:
156 if inequality
.subs(point
.coordinates()) < 0:
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
)
167 def _asinequalities(self
):
168 inequalities
= list(self
.equalities
)
169 inequalities
.extend([-expression
for expression
in self
.equalities
])
170 inequalities
.extend(self
.inequalities
)
173 def widen(self
, other
):
175 Compute the standard widening of two polyhedra, à la Halbwachs.
177 if not isinstance(other
, Polyhedron
):
178 raise ValueError('argument must be a Polyhedron instance')
179 inequalities1
= self
._asinequalities
()
180 inequalities2
= other
._asinequalities
()
182 for inequality1
in inequalities1
:
183 if other
<= Polyhedron(inequalities
=[inequality1
]):
184 inequalities
.append(inequality1
)
185 for inequality2
in inequalities2
:
186 for i
in range(len(inequalities1
)):
187 inequalities3
= inequalities1
[:i
] + inequalities
[i
+ 1:]
188 inequalities3
.append(inequality2
)
189 polyhedron3
= Polyhedron(inequalities
=inequalities3
)
190 if self
== polyhedron3
:
191 inequalities
.append(inequality2
)
193 return Polyhedron(inequalities
=inequalities
)
196 def _fromislbasicset(cls
, islbset
, symbols
):
197 islconstraints
= islhelper
.isl_basic_set_constraints(islbset
)
200 for islconstraint
in islconstraints
:
201 constant
= libisl
.isl_constraint_get_constant_val(islconstraint
)
202 constant
= islhelper
.isl_val_to_int(constant
)
204 for index
, symbol
in enumerate(symbols
):
205 coefficient
= libisl
.isl_constraint_get_coefficient_val(islconstraint
,
206 libisl
.isl_dim_set
, index
)
207 coefficient
= islhelper
.isl_val_to_int(coefficient
)
209 coefficients
[symbol
] = coefficient
210 expression
= LinExpr(coefficients
, constant
)
211 if libisl
.isl_constraint_is_equality(islconstraint
):
212 equalities
.append(expression
)
214 inequalities
.append(expression
)
215 libisl
.isl_basic_set_free(islbset
)
216 self
= object().__new
__(Polyhedron
)
217 self
._equalities
= tuple(equalities
)
218 self
._inequalities
= tuple(inequalities
)
219 self
._symbols
= cls
._xsymbols
(self
.constraints
)
220 self
._dimension
= len(self
._symbols
)
224 def _toislbasicset(cls
, equalities
, inequalities
, symbols
):
225 dimension
= len(symbols
)
226 indices
= {symbol
: index
for index
, symbol
in enumerate(symbols
)}
227 islsp
= libisl
.isl_space_set_alloc(mainctx
, 0, dimension
)
228 islbset
= libisl
.isl_basic_set_universe(libisl
.isl_space_copy(islsp
))
229 islls
= libisl
.isl_local_space_from_space(islsp
)
230 for equality
in equalities
:
231 isleq
= libisl
.isl_equality_alloc(libisl
.isl_local_space_copy(islls
))
232 for symbol
, coefficient
in equality
.coefficients():
233 islval
= str(coefficient
).encode()
234 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
235 index
= indices
[symbol
]
236 isleq
= libisl
.isl_constraint_set_coefficient_val(isleq
,
237 libisl
.isl_dim_set
, index
, islval
)
238 if equality
.constant
!= 0:
239 islval
= str(equality
.constant
).encode()
240 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
241 isleq
= libisl
.isl_constraint_set_constant_val(isleq
, islval
)
242 islbset
= libisl
.isl_basic_set_add_constraint(islbset
, isleq
)
243 for inequality
in inequalities
:
244 islin
= libisl
.isl_inequality_alloc(libisl
.isl_local_space_copy(islls
))
245 for symbol
, coefficient
in inequality
.coefficients():
246 islval
= str(coefficient
).encode()
247 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
248 index
= indices
[symbol
]
249 islin
= libisl
.isl_constraint_set_coefficient_val(islin
,
250 libisl
.isl_dim_set
, index
, islval
)
251 if inequality
.constant
!= 0:
252 islval
= str(inequality
.constant
).encode()
253 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
254 islin
= libisl
.isl_constraint_set_constant_val(islin
, islval
)
255 islbset
= libisl
.isl_basic_set_add_constraint(islbset
, islin
)
259 def fromstring(cls
, string
):
260 domain
= Domain
.fromstring(string
)
261 if not isinstance(domain
, Polyhedron
):
262 raise ValueError('non-polyhedral expression: {!r}'.format(string
))
267 for equality
in self
.equalities
:
268 strings
.append('Eq({}, 0)'.format(equality
))
269 for inequality
in self
.inequalities
:
270 strings
.append('Ge({}, 0)'.format(inequality
))
271 if len(strings
) == 1:
274 return 'And({})'.format(', '.join(strings
))
276 def _repr_latex_(self
):
278 for equality
in self
.equalities
:
279 strings
.append('{} = 0'.format(equality
._repr
_latex
_().strip('$')))
280 for inequality
in self
.inequalities
:
281 strings
.append('{} \\ge 0'.format(inequality
._repr
_latex
_().strip('$')))
282 return '$${}$$'.format(' \\wedge '.join(strings
))
285 def fromsympy(cls
, expr
):
286 domain
= Domain
.fromsympy(expr
)
287 if not isinstance(domain
, Polyhedron
):
288 raise ValueError('non-polyhedral expression: {!r}'.format(expr
))
294 for equality
in self
.equalities
:
295 constraints
.append(sympy
.Eq(equality
.tosympy(), 0))
296 for inequality
in self
.inequalities
:
297 constraints
.append(sympy
.Ge(inequality
.tosympy(), 0))
298 return sympy
.And(*constraints
)
301 class EmptyType(Polyhedron
):
303 The empty polyhedron, whose set of constraints is not satisfiable.
306 __slots__
= Polyhedron
.__slots
__
309 self
= object().__new
__(cls
)
310 self
._equalities
= (Rational(1),)
311 self
._inequalities
= ()
316 def widen(self
, other
):
317 if not isinstance(other
, Polyhedron
):
318 raise ValueError('argument must be a Polyhedron instance')
324 def _repr_latex_(self
):
325 return '$$\\emptyset$$'
330 class UniverseType(Polyhedron
):
332 The universe polyhedron, whose set of constraints is always satisfiable,
336 __slots__
= Polyhedron
.__slots
__
339 self
= object().__new
__(cls
)
340 self
._equalities
= ()
341 self
._inequalities
= ()
349 def _repr_latex_(self
):
352 Universe
= UniverseType()
355 def _polymorphic(func
):
356 @functools.wraps(func
)
357 def wrapper(left
, right
):
358 if not isinstance(left
, LinExpr
):
359 if isinstance(left
, numbers
.Rational
):
360 left
= Rational(left
)
362 raise TypeError('left must be a a rational number '
363 'or a linear expression')
364 if not isinstance(right
, LinExpr
):
365 if isinstance(right
, numbers
.Rational
):
366 right
= Rational(right
)
368 raise TypeError('right must be a a rational number '
369 'or a linear expression')
370 return func(left
, right
)
376 Create the polyhedron with constraints expr1 < expr2 < expr3 ...
378 return Polyhedron([], [right
- left
- 1])
383 Create the polyhedron with constraints expr1 <= expr2 <= expr3 ...
385 return Polyhedron([], [right
- left
])
390 Create the polyhedron with constraints expr1 == expr2 == expr3 ...
392 return Polyhedron([left
- right
], [])
397 Create the domain such that expr1 != expr2 != expr3 ... The result is a
398 Domain, not a Polyhedron.
400 return ~
Eq(left
, right
)
405 Create the polyhedron with constraints expr1 > expr2 > expr3 ...
407 return Polyhedron([], [left
- right
- 1])
412 Create the polyhedron with constraints expr1 >= expr2 >= expr3 ...
414 return Polyhedron([], [left
- right
])