fe143d46f24be36006326ba983ede7e56b15cba7
5 from . import islhelper
7 from .islhelper
import mainctx
, libisl
8 from .geometry
import GeometricObject
, Point
9 from .linexprs
import Expression
, Rational
10 from .domains
import Domain
15 'Lt', 'Le', 'Eq', 'Ne', 'Ge', 'Gt',
20 class Polyhedron(Domain
):
30 def __new__(cls
, equalities
=None, inequalities
=None):
31 if isinstance(equalities
, str):
32 if inequalities
is not None:
33 raise TypeError('too many arguments')
34 return cls
.fromstring(equalities
)
35 elif isinstance(equalities
, GeometricObject
):
36 if inequalities
is not None:
37 raise TypeError('too many arguments')
38 return equalities
.aspolyhedron()
39 if equalities
is None:
42 for i
, equality
in enumerate(equalities
):
43 if not isinstance(equality
, Expression
):
44 raise TypeError('equalities must be linear expressions')
45 equalities
[i
] = equality
.scaleint()
46 if inequalities
is None:
49 for i
, inequality
in enumerate(inequalities
):
50 if not isinstance(inequality
, Expression
):
51 raise TypeError('inequalities must be linear expressions')
52 inequalities
[i
] = inequality
.scaleint()
53 symbols
= cls
._xsymbols
(equalities
+ inequalities
)
54 islbset
= cls
._toislbasicset
(equalities
, inequalities
, symbols
)
55 return cls
._fromislbasicset
(islbset
, symbols
)
60 Return a list of the equalities in a set.
62 return self
._equalities
65 def inequalities(self
):
67 Return a list of the inequalities in a set.
69 return self
._inequalities
72 def constraints(self
):
74 Return ta list of the constraints of a set.
76 return self
._constraints
84 Return a set as disjoint.
90 Return true if a set is the Universe set.
92 islbset
= self
._toislbasicset
(self
.equalities
, self
.inequalities
,
94 universe
= bool(libisl
.isl_basic_set_is_universe(islbset
))
95 libisl
.isl_basic_set_free(islbset
)
98 def aspolyhedron(self
):
100 Return polyhedral hull of a set.
104 def __contains__(self
, point
):
105 if not isinstance(point
, Point
):
106 raise TypeError('point must be a Point instance')
107 if self
.symbols
!= point
.symbols
:
108 raise ValueError('arguments must belong to the same space')
109 for equality
in self
.equalities
:
110 if equality
.subs(point
.coordinates()) != 0:
112 for inequality
in self
.inequalities
:
113 if inequality
.subs(point
.coordinates()) < 0:
117 def subs(self
, symbol
, expression
=None):
119 Subsitute the given value into an expression and return the resulting expression.
121 equalities
= [equality
.subs(symbol
, expression
)
122 for equality
in self
.equalities
]
123 inequalities
= [inequality
.subs(symbol
, expression
)
124 for inequality
in self
.inequalities
]
125 return Polyhedron(equalities
, inequalities
)
127 def _asinequalities(self
):
128 inequalities
= list(self
.equalities
)
129 inequalities
.extend([-expression
for expression
in self
.equalities
])
130 inequalities
.extend(self
.inequalities
)
133 def widen(self
, other
):
134 if not isinstance(other
, Polyhedron
):
135 raise ValueError('argument must be a Polyhedron instance')
136 inequalities1
= self
._asinequalities
()
137 inequalities2
= other
._asinequalities
()
139 for inequality1
in inequalities1
:
140 if other
<= Polyhedron(inequalities
=[inequality1
]):
141 inequalities
.append(inequality1
)
142 for inequality2
in inequalities2
:
143 for i
in range(len(inequalities1
)):
144 inequalities3
= inequalities1
[:i
] + inequalities
[i
+ 1:]
145 inequalities3
.append(inequality2
)
146 polyhedron3
= Polyhedron(inequalities
=inequalities3
)
147 if self
== polyhedron3
:
148 inequalities
.append(inequality2
)
150 return Polyhedron(inequalities
=inequalities
)
153 def _fromislbasicset(cls
, islbset
, symbols
):
154 islconstraints
= islhelper
.isl_basic_set_constraints(islbset
)
157 for islconstraint
in islconstraints
:
158 constant
= libisl
.isl_constraint_get_constant_val(islconstraint
)
159 constant
= islhelper
.isl_val_to_int(constant
)
161 for index
, symbol
in enumerate(symbols
):
162 coefficient
= libisl
.isl_constraint_get_coefficient_val(islconstraint
,
163 libisl
.isl_dim_set
, index
)
164 coefficient
= islhelper
.isl_val_to_int(coefficient
)
166 coefficients
[symbol
] = coefficient
167 expression
= Expression(coefficients
, constant
)
168 if libisl
.isl_constraint_is_equality(islconstraint
):
169 equalities
.append(expression
)
171 inequalities
.append(expression
)
172 libisl
.isl_basic_set_free(islbset
)
173 self
= object().__new
__(Polyhedron
)
174 self
._equalities
= tuple(equalities
)
175 self
._inequalities
= tuple(inequalities
)
176 self
._constraints
= tuple(equalities
+ inequalities
)
177 self
._symbols
= cls
._xsymbols
(self
._constraints
)
178 self
._dimension
= len(self
._symbols
)
182 def _toislbasicset(cls
, equalities
, inequalities
, symbols
):
183 dimension
= len(symbols
)
184 indices
= {symbol
: index
for index
, symbol
in enumerate(symbols
)}
185 islsp
= libisl
.isl_space_set_alloc(mainctx
, 0, dimension
)
186 islbset
= libisl
.isl_basic_set_universe(libisl
.isl_space_copy(islsp
))
187 islls
= libisl
.isl_local_space_from_space(islsp
)
188 for equality
in equalities
:
189 isleq
= libisl
.isl_equality_alloc(libisl
.isl_local_space_copy(islls
))
190 for symbol
, coefficient
in equality
.coefficients():
191 islval
= str(coefficient
).encode()
192 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
193 index
= indices
[symbol
]
194 isleq
= libisl
.isl_constraint_set_coefficient_val(isleq
,
195 libisl
.isl_dim_set
, index
, islval
)
196 if equality
.constant
!= 0:
197 islval
= str(equality
.constant
).encode()
198 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
199 isleq
= libisl
.isl_constraint_set_constant_val(isleq
, islval
)
200 islbset
= libisl
.isl_basic_set_add_constraint(islbset
, isleq
)
201 for inequality
in inequalities
:
202 islin
= libisl
.isl_inequality_alloc(libisl
.isl_local_space_copy(islls
))
203 for symbol
, coefficient
in inequality
.coefficients():
204 islval
= str(coefficient
).encode()
205 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
206 index
= indices
[symbol
]
207 islin
= libisl
.isl_constraint_set_coefficient_val(islin
,
208 libisl
.isl_dim_set
, index
, islval
)
209 if inequality
.constant
!= 0:
210 islval
= str(inequality
.constant
).encode()
211 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
212 islin
= libisl
.isl_constraint_set_constant_val(islin
, islval
)
213 islbset
= libisl
.isl_basic_set_add_constraint(islbset
, islin
)
217 def fromstring(cls
, string
):
218 domain
= Domain
.fromstring(string
)
219 if not isinstance(domain
, Polyhedron
):
220 raise ValueError('non-polyhedral expression: {!r}'.format(string
))
225 for equality
in self
.equalities
:
226 strings
.append('Eq({}, 0)'.format(equality
))
227 for inequality
in self
.inequalities
:
228 strings
.append('Ge({}, 0)'.format(inequality
))
229 if len(strings
) == 1:
232 return 'And({})'.format(', '.join(strings
))
235 def _repr_latex_(self
):
237 for equality
in self
.equalities
:
238 strings
.append('{} = 0'.format(equality
._repr
_latex
_().strip('$')))
239 for inequality
in self
.inequalities
:
240 strings
.append('{} \\ge 0'.format(inequality
._repr
_latex
_().strip('$')))
241 return '$${}$$'.format(' \\wedge '.join(strings
))
244 def fromsympy(cls
, expr
):
246 Convert a sympy object to an expression.
248 domain
= Domain
.fromsympy(expr
)
249 if not isinstance(domain
, Polyhedron
):
250 raise ValueError('non-polyhedral expression: {!r}'.format(expr
))
255 Return an expression as a sympy object.
259 for equality
in self
.equalities
:
260 constraints
.append(sympy
.Eq(equality
.tosympy(), 0))
261 for inequality
in self
.inequalities
:
262 constraints
.append(sympy
.Ge(inequality
.tosympy(), 0))
263 return sympy
.And(*constraints
)
265 class EmptyType(Polyhedron
):
267 __slots__
= Polyhedron
.__slots
__
270 self
= object().__new
__(cls
)
271 self
._equalities
= (Rational(1),)
272 self
._inequalities
= ()
273 self
._constraints
= self
._equalities
278 def widen(self
, other
):
279 if not isinstance(other
, Polyhedron
):
280 raise ValueError('argument must be a Polyhedron instance')
286 def _repr_latex_(self
):
287 return '$$\\emptyset$$'
292 class UniverseType(Polyhedron
):
294 __slots__
= Polyhedron
.__slots
__
297 self
= object().__new
__(cls
)
298 self
._equalities
= ()
299 self
._inequalities
= ()
300 self
._constraints
= ()
308 def _repr_latex_(self
):
311 Universe
= UniverseType()
314 def _polymorphic(func
):
315 @functools.wraps(func
)
316 def wrapper(left
, right
):
317 if not isinstance(left
, Expression
):
318 if isinstance(left
, numbers
.Rational
):
319 left
= Rational(left
)
321 raise TypeError('left must be a a rational number '
322 'or a linear expression')
323 if not isinstance(right
, Expression
):
324 if isinstance(right
, numbers
.Rational
):
325 right
= Rational(right
)
327 raise TypeError('right must be a a rational number '
328 'or a linear expression')
329 return func(left
, right
)
335 Assert first set is less than the second set.
337 return Polyhedron([], [right
- left
- 1])
342 Assert first set is less than or equal to the second set.
344 return Polyhedron([], [right
- left
])
349 Assert first set is equal to the second set.
351 return Polyhedron([left
- right
], [])
356 Assert first set is not equal to the second set.
358 return ~
Eq(left
, right
)
363 Assert first set is greater than the second set.
365 return Polyhedron([], [left
- right
- 1])
370 Assert first set is greater than or equal to the second set.
372 return Polyhedron([], [left
- right
])