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 Expression
, Rational
27 from .domains
import Domain
32 'Lt', 'Le', 'Eq', 'Ne', 'Ge', 'Gt',
37 class Polyhedron(Domain
):
47 def __new__(cls
, equalities
=None, inequalities
=None):
48 if isinstance(equalities
, str):
49 if inequalities
is not None:
50 raise TypeError('too many arguments')
51 return cls
.fromstring(equalities
)
52 elif isinstance(equalities
, GeometricObject
):
53 if inequalities
is not None:
54 raise TypeError('too many arguments')
55 return equalities
.aspolyhedron()
56 if equalities
is None:
59 for i
, equality
in enumerate(equalities
):
60 if not isinstance(equality
, Expression
):
61 raise TypeError('equalities must be linear expressions')
62 equalities
[i
] = equality
.scaleint()
63 if inequalities
is None:
66 for i
, inequality
in enumerate(inequalities
):
67 if not isinstance(inequality
, Expression
):
68 raise TypeError('inequalities must be linear expressions')
69 inequalities
[i
] = inequality
.scaleint()
70 symbols
= cls
._xsymbols
(equalities
+ inequalities
)
71 islbset
= cls
._toislbasicset
(equalities
, inequalities
, symbols
)
72 return cls
._fromislbasicset
(islbset
, symbols
)
77 Return a list of the equalities in a set.
79 return self
._equalities
82 def inequalities(self
):
84 Return a list of the inequalities in a set.
86 return self
._inequalities
89 def constraints(self
):
91 Return ta list of the constraints of a set.
93 return self
._constraints
101 Return a set as disjoint.
105 def isuniverse(self
):
107 Return true if a set is the Universe set.
109 islbset
= self
._toislbasicset
(self
.equalities
, self
.inequalities
,
111 universe
= bool(libisl
.isl_basic_set_is_universe(islbset
))
112 libisl
.isl_basic_set_free(islbset
)
115 def aspolyhedron(self
):
117 Return polyhedral hull of a set.
121 def __contains__(self
, point
):
122 if not isinstance(point
, Point
):
123 raise TypeError('point must be a Point instance')
124 if self
.symbols
!= point
.symbols
:
125 raise ValueError('arguments must belong to the same space')
126 for equality
in self
.equalities
:
127 if equality
.subs(point
.coordinates()) != 0:
129 for inequality
in self
.inequalities
:
130 if inequality
.subs(point
.coordinates()) < 0:
134 def subs(self
, symbol
, expression
=None):
136 Subsitute the given value into an expression and return the resulting
139 equalities
= [equality
.subs(symbol
, expression
)
140 for equality
in self
.equalities
]
141 inequalities
= [inequality
.subs(symbol
, expression
)
142 for inequality
in self
.inequalities
]
143 return Polyhedron(equalities
, inequalities
)
145 def _asinequalities(self
):
146 inequalities
= list(self
.equalities
)
147 inequalities
.extend([-expression
for expression
in self
.equalities
])
148 inequalities
.extend(self
.inequalities
)
151 def widen(self
, other
):
152 if not isinstance(other
, Polyhedron
):
153 raise ValueError('argument must be a Polyhedron instance')
154 inequalities1
= self
._asinequalities
()
155 inequalities2
= other
._asinequalities
()
157 for inequality1
in inequalities1
:
158 if other
<= Polyhedron(inequalities
=[inequality1
]):
159 inequalities
.append(inequality1
)
160 for inequality2
in inequalities2
:
161 for i
in range(len(inequalities1
)):
162 inequalities3
= inequalities1
[:i
] + inequalities
[i
+ 1:]
163 inequalities3
.append(inequality2
)
164 polyhedron3
= Polyhedron(inequalities
=inequalities3
)
165 if self
== polyhedron3
:
166 inequalities
.append(inequality2
)
168 return Polyhedron(inequalities
=inequalities
)
171 def _fromislbasicset(cls
, islbset
, symbols
):
172 islconstraints
= islhelper
.isl_basic_set_constraints(islbset
)
175 for islconstraint
in islconstraints
:
176 constant
= libisl
.isl_constraint_get_constant_val(islconstraint
)
177 constant
= islhelper
.isl_val_to_int(constant
)
179 for index
, symbol
in enumerate(symbols
):
180 coefficient
= libisl
.isl_constraint_get_coefficient_val(islconstraint
,
181 libisl
.isl_dim_set
, index
)
182 coefficient
= islhelper
.isl_val_to_int(coefficient
)
184 coefficients
[symbol
] = coefficient
185 expression
= Expression(coefficients
, constant
)
186 if libisl
.isl_constraint_is_equality(islconstraint
):
187 equalities
.append(expression
)
189 inequalities
.append(expression
)
190 libisl
.isl_basic_set_free(islbset
)
191 self
= object().__new
__(Polyhedron
)
192 self
._equalities
= tuple(equalities
)
193 self
._inequalities
= tuple(inequalities
)
194 self
._constraints
= tuple(equalities
+ inequalities
)
195 self
._symbols
= cls
._xsymbols
(self
._constraints
)
196 self
._dimension
= len(self
._symbols
)
200 def _toislbasicset(cls
, equalities
, inequalities
, symbols
):
201 dimension
= len(symbols
)
202 indices
= {symbol
: index
for index
, symbol
in enumerate(symbols
)}
203 islsp
= libisl
.isl_space_set_alloc(mainctx
, 0, dimension
)
204 islbset
= libisl
.isl_basic_set_universe(libisl
.isl_space_copy(islsp
))
205 islls
= libisl
.isl_local_space_from_space(islsp
)
206 for equality
in equalities
:
207 isleq
= libisl
.isl_equality_alloc(libisl
.isl_local_space_copy(islls
))
208 for symbol
, coefficient
in equality
.coefficients():
209 islval
= str(coefficient
).encode()
210 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
211 index
= indices
[symbol
]
212 isleq
= libisl
.isl_constraint_set_coefficient_val(isleq
,
213 libisl
.isl_dim_set
, index
, islval
)
214 if equality
.constant
!= 0:
215 islval
= str(equality
.constant
).encode()
216 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
217 isleq
= libisl
.isl_constraint_set_constant_val(isleq
, islval
)
218 islbset
= libisl
.isl_basic_set_add_constraint(islbset
, isleq
)
219 for inequality
in inequalities
:
220 islin
= libisl
.isl_inequality_alloc(libisl
.isl_local_space_copy(islls
))
221 for symbol
, coefficient
in inequality
.coefficients():
222 islval
= str(coefficient
).encode()
223 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
224 index
= indices
[symbol
]
225 islin
= libisl
.isl_constraint_set_coefficient_val(islin
,
226 libisl
.isl_dim_set
, index
, islval
)
227 if inequality
.constant
!= 0:
228 islval
= str(inequality
.constant
).encode()
229 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
230 islin
= libisl
.isl_constraint_set_constant_val(islin
, islval
)
231 islbset
= libisl
.isl_basic_set_add_constraint(islbset
, islin
)
235 def fromstring(cls
, string
):
236 domain
= Domain
.fromstring(string
)
237 if not isinstance(domain
, Polyhedron
):
238 raise ValueError('non-polyhedral expression: {!r}'.format(string
))
243 for equality
in self
.equalities
:
244 strings
.append('Eq({}, 0)'.format(equality
))
245 for inequality
in self
.inequalities
:
246 strings
.append('Ge({}, 0)'.format(inequality
))
247 if len(strings
) == 1:
250 return 'And({})'.format(', '.join(strings
))
253 def _repr_latex_(self
):
255 for equality
in self
.equalities
:
256 strings
.append('{} = 0'.format(equality
._repr
_latex
_().strip('$')))
257 for inequality
in self
.inequalities
:
258 strings
.append('{} \\ge 0'.format(inequality
._repr
_latex
_().strip('$')))
259 return '$${}$$'.format(' \\wedge '.join(strings
))
262 def fromsympy(cls
, expr
):
264 Convert a sympy object to an expression.
266 domain
= Domain
.fromsympy(expr
)
267 if not isinstance(domain
, Polyhedron
):
268 raise ValueError('non-polyhedral expression: {!r}'.format(expr
))
273 Return an expression as a sympy object.
277 for equality
in self
.equalities
:
278 constraints
.append(sympy
.Eq(equality
.tosympy(), 0))
279 for inequality
in self
.inequalities
:
280 constraints
.append(sympy
.Ge(inequality
.tosympy(), 0))
281 return sympy
.And(*constraints
)
284 class EmptyType(Polyhedron
):
286 __slots__
= Polyhedron
.__slots
__
289 self
= object().__new
__(cls
)
290 self
._equalities
= (Rational(1),)
291 self
._inequalities
= ()
292 self
._constraints
= self
._equalities
297 def widen(self
, other
):
298 if not isinstance(other
, Polyhedron
):
299 raise ValueError('argument must be a Polyhedron instance')
305 def _repr_latex_(self
):
306 return '$$\\emptyset$$'
311 class UniverseType(Polyhedron
):
313 __slots__
= Polyhedron
.__slots
__
316 self
= object().__new
__(cls
)
317 self
._equalities
= ()
318 self
._inequalities
= ()
319 self
._constraints
= ()
327 def _repr_latex_(self
):
330 Universe
= UniverseType()
333 def _polymorphic(func
):
334 @functools.wraps(func
)
335 def wrapper(left
, right
):
336 if not isinstance(left
, Expression
):
337 if isinstance(left
, numbers
.Rational
):
338 left
= Rational(left
)
340 raise TypeError('left must be a a rational number '
341 'or a linear expression')
342 if not isinstance(right
, Expression
):
343 if isinstance(right
, numbers
.Rational
):
344 right
= Rational(right
)
346 raise TypeError('right must be a a rational number '
347 'or a linear expression')
348 return func(left
, right
)
354 Assert first set is less than the second set.
356 return Polyhedron([], [right
- left
- 1])
361 Assert first set is less than or equal to the second set.
363 return Polyhedron([], [right
- left
])
368 Assert first set is equal to the second set.
370 return Polyhedron([left
- right
], [])
375 Assert first set is not equal to the second set.
377 return ~
Eq(left
, right
)
382 Assert first set is greater than the second set.
384 return Polyhedron([], [left
- right
- 1])
389 Assert first set is greater than or equal to the second set.
391 return Polyhedron([], [left
- right
])