5 from fractions
import Fraction
7 from . import islhelper
8 from .islhelper
import mainctx
, libisl
, isl_set_basic_sets
9 from .coordinates
import Point
10 from .linexprs
import Expression
, Symbol
19 @functools.total_ordering
28 def __new__(cls
, *polyhedra
):
29 from .polyhedra
import Polyhedron
30 if len(polyhedra
) == 1:
31 polyhedron
= polyhedra
[0]
32 if isinstance(polyhedron
, str):
33 return cls
.fromstring(polyhedron
)
34 elif isinstance(polyhedron
, Polyhedron
):
37 raise TypeError('argument must be a string '
38 'or a Polyhedron instance')
40 for polyhedron
in polyhedra
:
41 if not isinstance(polyhedron
, Polyhedron
):
42 raise TypeError('arguments must be Polyhedron instances')
43 symbols
= cls
._xsymbols
(polyhedra
)
44 islset
= cls
._toislset
(polyhedra
, symbols
)
45 return cls
._fromislset
(islset
, symbols
)
48 def _xsymbols(cls
, iterator
):
50 Return the ordered tuple of symbols present in iterator.
54 symbols
.update(item
.symbols
)
55 return tuple(sorted(symbols
, key
=Symbol
.sortkey
))
59 return self
._polyhedra
67 return self
._dimension
70 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
71 islset
= libisl
.isl_set_make_disjoint(mainctx
, islset
)
72 return self
._fromislset
(islset
, self
.symbols
)
75 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
76 empty
= bool(libisl
.isl_set_is_empty(islset
))
77 libisl
.isl_set_free(islset
)
81 return not self
.isempty()
84 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
85 universe
= bool(libisl
.isl_set_plain_is_universe(islset
))
86 libisl
.isl_set_free(islset
)
90 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
91 bounded
= bool(libisl
.isl_set_is_bounded(islset
))
92 libisl
.isl_set_free(islset
)
95 def __eq__(self
, other
):
96 symbols
= self
._xsymbols
([self
, other
])
97 islset1
= self
._toislset
(self
.polyhedra
, symbols
)
98 islset2
= other
._toislset
(other
.polyhedra
, symbols
)
99 equal
= bool(libisl
.isl_set_is_equal(islset1
, islset2
))
100 libisl
.isl_set_free(islset1
)
101 libisl
.isl_set_free(islset2
)
104 def isdisjoint(self
, other
):
105 symbols
= self
._xsymbols
([self
, other
])
106 islset1
= self
._toislset
(self
.polyhedra
, symbols
)
107 islset2
= self
._toislset
(other
.polyhedra
, symbols
)
108 equal
= bool(libisl
.isl_set_is_disjoint(islset1
, islset2
))
109 libisl
.isl_set_free(islset1
)
110 libisl
.isl_set_free(islset2
)
113 def issubset(self
, other
):
114 symbols
= self
._xsymbols
([self
, other
])
115 islset1
= self
._toislset
(self
.polyhedra
, symbols
)
116 islset2
= self
._toislset
(other
.polyhedra
, symbols
)
117 equal
= bool(libisl
.isl_set_is_subset(islset1
, islset2
))
118 libisl
.isl_set_free(islset1
)
119 libisl
.isl_set_free(islset2
)
122 def __le__(self
, other
):
123 return self
.issubset(other
)
125 def __lt__(self
, other
):
126 symbols
= self
._xsymbols
([self
, other
])
127 islset1
= self
._toislset
(self
.polyhedra
, symbols
)
128 islset2
= self
._toislset
(other
.polyhedra
, symbols
)
129 equal
= bool(libisl
.isl_set_is_strict_subset(islset1
, islset2
))
130 libisl
.isl_set_free(islset1
)
131 libisl
.isl_set_free(islset2
)
134 def complement(self
):
135 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
136 islset
= libisl
.isl_set_complement(islset
)
137 return self
._fromislset
(islset
, self
.symbols
)
139 def __invert__(self
):
140 return self
.complement()
143 #does not change anything in any of the examples
144 #isl seems to do this naturally
145 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
146 islset
= libisl
.isl_set_remove_redundancies(islset
)
147 return self
._fromislset
(islset
, self
.symbols
)
149 def aspolyhedron(self
):
150 # several types of hull are available
151 # polyhedral seems to be the more appropriate, to be checked
152 from .polyhedra
import Polyhedron
153 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
154 islbset
= libisl
.isl_set_polyhedral_hull(islset
)
155 return Polyhedron
._fromislbasicset
(islbset
, self
.symbols
)
157 def project(self
, dims
):
158 # use to remove certain variables
159 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
161 for index
, symbol
in reversed(list(enumerate(self
.symbols
))):
165 islset
= libisl
.isl_set_project_out(islset
, libisl
.isl_dim_set
, index
+ 1, n
)
168 islset
= libisl
.isl_set_project_out(islset
, libisl
.isl_dim_set
, 0, n
)
169 dims
= [symbol
for symbol
in self
.symbols
if symbol
not in dims
]
170 return Domain
._fromislset
(islset
, dims
)
173 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
174 islpoint
= libisl
.isl_set_sample_point(islset
)
175 if bool(libisl
.isl_point_is_void(islpoint
)):
176 libisl
.isl_point_free(islpoint
)
177 raise ValueError('domain must be non-empty')
179 for index
, symbol
in enumerate(self
.symbols
):
180 coordinate
= libisl
.isl_point_get_coordinate_val(islpoint
,
181 libisl
.isl_dim_set
, index
)
182 coordinate
= islhelper
.isl_val_to_int(coordinate
)
183 point
[symbol
] = coordinate
184 libisl
.isl_point_free(islpoint
)
187 def intersection(self
, *others
):
190 symbols
= self
._xsymbols
((self
,) + others
)
191 islset1
= self
._toislset
(self
.polyhedra
, symbols
)
193 islset2
= other
._toislset
(other
.polyhedra
, symbols
)
194 islset1
= libisl
.isl_set_intersect(islset1
, islset2
)
195 return self
._fromislset
(islset1
, symbols
)
197 def __and__(self
, other
):
198 return self
.intersection(other
)
200 def union(self
, *others
):
203 symbols
= self
._xsymbols
((self
,) + others
)
204 islset1
= self
._toislset
(self
.polyhedra
, symbols
)
206 islset2
= other
._toislset
(other
.polyhedra
, symbols
)
207 islset1
= libisl
.isl_set_union(islset1
, islset2
)
208 return self
._fromislset
(islset1
, symbols
)
210 def __or__(self
, other
):
211 return self
.union(other
)
213 def __add__(self
, other
):
214 return self
.union(other
)
216 def difference(self
, other
):
217 symbols
= self
._xsymbols
([self
, other
])
218 islset1
= self
._toislset
(self
.polyhedra
, symbols
)
219 islset2
= other
._toislset
(other
.polyhedra
, symbols
)
220 islset
= libisl
.isl_set_subtract(islset1
, islset2
)
221 return self
._fromislset
(islset
, symbols
)
223 def __sub__(self
, other
):
224 return self
.difference(other
)
227 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
228 islset
= libisl
.isl_set_lexmin(islset
)
229 return self
._fromislset
(islset
, self
.symbols
)
232 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
233 islset
= libisl
.isl_set_lexmax(islset
)
234 return self
._fromislset
(islset
, self
.symbols
)
236 def num_parameters(self
):
237 #could be useful with large, complicated polyhedrons
238 islbset
= self
._toislbasicset
(self
.equalities
, self
.inequalities
, self
.symbols
)
239 num
= libisl
.isl_basic_set_dim(islbset
, libisl
.isl_dim_set
)
242 def involves_dims(self
, dims
):
243 #could be useful with large, complicated polyhedrons
244 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
246 symbols
= sorted(list(self
.symbols
))
251 first
= symbols
.index(dims
[0])
257 value
= bool(libisl
.isl_set_involves_dims(islset
, libisl
.isl_dim_set
, first
, n
))
258 libisl
.isl_set_free(islset
)
261 _RE_COORDINATE
= re
.compile(r
'\((?P<num>\-?\d+)\)(/(?P<den>\d+))?')
264 #returning list of verticies
265 from .polyhedra
import Polyhedron
266 islbset
= self
._toislbasicset
(self
.equalities
, self
.inequalities
, self
.symbols
)
267 vertices
= libisl
.isl_basic_set_compute_vertices(islbset
);
268 vertices
= islhelper
.isl_vertices_vertices(vertices
)
270 for vertex
in vertices
:
271 expr
= libisl
.isl_vertex_get_expr(vertex
)
273 if islhelper
.isl_version
< '0.13':
274 constraints
= islhelper
.isl_basic_set_constraints(expr
)
275 for constraint
in constraints
:
276 constant
= libisl
.isl_constraint_get_constant_val(constraint
)
277 constant
= islhelper
.isl_val_to_int(constant
)
278 for index
, symbol
in enumerate(self
.symbols
):
279 coefficient
= libisl
.isl_constraint_get_coefficient_val(constraint
,
280 libisl
.isl_dim_set
, index
)
281 coefficient
= islhelper
.isl_val_to_int(coefficient
)
283 coordinate
= -Fraction(constant
, coefficient
)
284 coordinates
.append((symbol
, coordinate
))
286 # horrible hack, find a cleaner solution
287 string
= islhelper
.isl_multi_aff_to_str(expr
)
288 matches
= self
._RE
_COORDINATE
.finditer(string
)
289 for symbol
, match
in zip(self
.symbols
, matches
):
290 numerator
= int(match
.group('num'))
291 denominator
= match
.group('den')
292 denominator
= 1 if denominator
is None else int(denominator
)
293 coordinate
= Fraction(numerator
, denominator
)
294 coordinates
.append((symbol
, coordinate
))
295 points
.append(Point(coordinates
))
299 if not self
.isbounded():
300 raise ValueError('domain must be bounded')
301 from .polyhedra
import Universe
, Eq
302 islset
= self
._toislset
(self
.polyhedra
, self
.symbols
)
303 islpoints
= islhelper
.isl_set_points(islset
)
305 for islpoint
in islpoints
:
307 for index
, symbol
in enumerate(self
.symbols
):
308 coordinate
= libisl
.isl_point_get_coordinate_val(islpoint
,
309 libisl
.isl_dim_set
, index
)
310 coordinate
= islhelper
.isl_val_to_int(coordinate
)
311 coordinates
[symbol
] = coordinate
312 points
.append(Point(coordinates
))
315 def __contains__(self
, point
):
316 for polyhedron
in self
.polyhedra
:
317 if point
in polyhedron
:
321 def subs(self
, symbol
, expression
=None):
322 polyhedra
= [polyhedron
.subs(symbol
, expression
)
323 for polyhedron
in self
.polyhedra
]
324 return Domain(*polyhedra
)
327 def _fromislset(cls
, islset
, symbols
):
328 from .polyhedra
import Polyhedron
329 islset
= libisl
.isl_set_remove_divs(islset
)
330 islbsets
= isl_set_basic_sets(islset
)
331 libisl
.isl_set_free(islset
)
333 for islbset
in islbsets
:
334 polyhedron
= Polyhedron
._fromislbasicset
(islbset
, symbols
)
335 polyhedra
.append(polyhedron
)
336 if len(polyhedra
) == 0:
337 from .polyhedra
import Empty
339 elif len(polyhedra
) == 1:
342 self
= object().__new
__(Domain
)
343 self
._polyhedra
= tuple(polyhedra
)
344 self
._symbols
= cls
._xsymbols
(polyhedra
)
345 self
._dimension
= len(self
._symbols
)
349 def _toislset(cls
, polyhedra
, symbols
):
350 polyhedron
= polyhedra
[0]
351 islbset
= polyhedron
._toislbasicset
(polyhedron
.equalities
,
352 polyhedron
.inequalities
, symbols
)
353 islset1
= libisl
.isl_set_from_basic_set(islbset
)
354 for polyhedron
in polyhedra
[1:]:
355 islbset
= polyhedron
._toislbasicset
(polyhedron
.equalities
,
356 polyhedron
.inequalities
, symbols
)
357 islset2
= libisl
.isl_set_from_basic_set(islbset
)
358 islset1
= libisl
.isl_set_union(islset1
, islset2
)
362 def _fromast(cls
, node
):
363 from .polyhedra
import Polyhedron
364 if isinstance(node
, ast
.Module
) and len(node
.body
) == 1:
365 return cls
._fromast
(node
.body
[0])
366 elif isinstance(node
, ast
.Expr
):
367 return cls
._fromast
(node
.value
)
368 elif isinstance(node
, ast
.UnaryOp
):
369 domain
= cls
._fromast
(node
.operand
)
370 if isinstance(node
.operand
, ast
.invert
):
372 elif isinstance(node
, ast
.BinOp
):
373 domain1
= cls
._fromast
(node
.left
)
374 domain2
= cls
._fromast
(node
.right
)
375 if isinstance(node
.op
, ast
.BitAnd
):
376 return And(domain1
, domain2
)
377 elif isinstance(node
.op
, ast
.BitOr
):
378 return Or(domain1
, domain2
)
379 elif isinstance(node
, ast
.Compare
):
382 left
= Expression
._fromast
(node
.left
)
383 for i
in range(len(node
.ops
)):
385 right
= Expression
._fromast
(node
.comparators
[i
])
386 if isinstance(op
, ast
.Lt
):
387 inequalities
.append(right
- left
- 1)
388 elif isinstance(op
, ast
.LtE
):
389 inequalities
.append(right
- left
)
390 elif isinstance(op
, ast
.Eq
):
391 equalities
.append(left
- right
)
392 elif isinstance(op
, ast
.GtE
):
393 inequalities
.append(left
- right
)
394 elif isinstance(op
, ast
.Gt
):
395 inequalities
.append(left
- right
- 1)
400 return Polyhedron(equalities
, inequalities
)
401 raise SyntaxError('invalid syntax')
403 _RE_BRACES
= re
.compile(r
'^\{\s*|\s*\}$')
404 _RE_EQ
= re
.compile(r
'([^<=>])=([^<=>])')
405 _RE_AND
= re
.compile(r
'\band\b|,|&&|/\\|∧|∩')
406 _RE_OR
= re
.compile(r
'\bor\b|;|\|\||\\/|∨|∪')
407 _RE_NOT
= re
.compile(r
'\bnot\b|!|¬')
408 _RE_NUM_VAR
= Expression
._RE
_NUM
_VAR
409 _RE_OPERATORS
= re
.compile(r
'(&|\||~)')
412 def fromstring(cls
, string
):
413 # remove curly brackets
414 string
= cls
._RE
_BRACES
.sub(r
'', string
)
415 # replace '=' by '=='
416 string
= cls
._RE
_EQ
.sub(r
'\1==\2', string
)
417 # replace 'and', 'or', 'not'
418 string
= cls
._RE
_AND
.sub(r
' & ', string
)
419 string
= cls
._RE
_OR
.sub(r
' | ', string
)
420 string
= cls
._RE
_NOT
.sub(r
' ~', string
)
421 # add implicit multiplication operators, e.g. '5x' -> '5*x'
422 string
= cls
._RE
_NUM
_VAR
.sub(r
'\1*\2', string
)
423 # add parentheses to force precedence
424 tokens
= cls
._RE
_OPERATORS
.split(string
)
425 for i
, token
in enumerate(tokens
):
427 token
= '({})'.format(token
)
429 string
= ''.join(tokens
)
430 tree
= ast
.parse(string
, 'eval')
431 return cls
._fromast
(tree
)
434 assert len(self
.polyhedra
) >= 2
435 strings
= [repr(polyhedron
) for polyhedron
in self
.polyhedra
]
436 return 'Or({})'.format(', '.join(strings
))
439 def fromsympy(cls
, expr
):
441 from .polyhedra
import Lt
, Le
, Eq
, Ne
, Ge
, Gt
443 sympy
.And
: And
, sympy
.Or
: Or
, sympy
.Not
: Not
,
444 sympy
.Lt
: Lt
, sympy
.Le
: Le
,
445 sympy
.Eq
: Eq
, sympy
.Ne
: Ne
,
446 sympy
.Ge
: Ge
, sympy
.Gt
: Gt
,
448 if expr
.func
in funcmap
:
449 args
= [Domain
.fromsympy(arg
) for arg
in expr
.args
]
450 return funcmap
[expr
.func
](*args
)
451 elif isinstance(expr
, sympy
.Expr
):
452 return Expression
.fromsympy(expr
)
453 raise ValueError('non-domain expression: {!r}'.format(expr
))
457 polyhedra
= [polyhedron
.tosympy() for polyhedron
in polyhedra
]
458 return sympy
.Or(*polyhedra
)
462 if len(domains
) == 0:
463 from .polyhedra
import Universe
466 return domains
[0].intersection(*domains
[1:])
469 if len(domains
) == 0:
470 from .polyhedra
import Empty
473 return domains
[0].union(*domains
[1:])