a924b834150f9e1f24e9a3fbd91937488aa69e41
[linpy.git] / pypol / domains.py
1 import ast
2 import functools
3 import re
4
5 from . import islhelper
6
7 from .islhelper import mainctx, libisl, isl_set_basic_sets
8 from .linexprs import Expression, Symbol
9
10
11 __all__ = [
12 'Domain',
13 'And', 'Or', 'Not',
14 ]
15
16
17 @functools.total_ordering
18 class Domain:
19
20 __slots__ = (
21 '_polyhedra',
22 '_symbols',
23 '_dimension',
24 )
25
26 def __new__(cls, *polyhedra):
27 from .polyhedra import Polyhedron
28 if len(polyhedra) == 1:
29 polyhedron = polyhedra[0]
30 if isinstance(polyhedron, str):
31 return cls.fromstring(polyhedron)
32 elif isinstance(polyhedron, Polyhedron):
33 return polyhedron
34 else:
35 raise TypeError('argument must be a string '
36 'or a Polyhedron instance')
37 else:
38 for polyhedron in polyhedra:
39 if not isinstance(polyhedron, Polyhedron):
40 raise TypeError('arguments must be Polyhedron instances')
41 symbols = cls._xsymbols(polyhedra)
42 islset = cls._toislset(polyhedra, symbols)
43 return cls._fromislset(islset, symbols)
44
45 @classmethod
46 def _xsymbols(cls, iterator):
47 """
48 Return the ordered tuple of symbols present in iterator.
49 """
50 symbols = set()
51 for item in iterator:
52 symbols.update(item.symbols)
53 return tuple(sorted(symbols, key=Symbol.sortkey))
54
55 @property
56 def polyhedra(self):
57 return self._polyhedra
58
59 @property
60 def symbols(self):
61 return self._symbols
62
63 @property
64 def dimension(self):
65 return self._dimension
66
67 def disjoint(self):
68 islset = self._toislset(self.polyhedra, self.symbols)
69 islset = libisl.isl_set_make_disjoint(mainctx, islset)
70 return self._fromislset(islset, self.symbols)
71
72 def isempty(self):
73 islset = self._toislset(self.polyhedra, self.symbols)
74 empty = bool(libisl.isl_set_is_empty(islset))
75 libisl.isl_set_free(islset)
76 return empty
77
78 def __bool__(self):
79 return not self.isempty()
80
81 def isuniverse(self):
82 islset = self._toislset(self.polyhedra, self.symbols)
83 universe = bool(libisl.isl_set_plain_is_universe(islset))
84 libisl.isl_set_free(islset)
85 return universe
86
87 def isbounded(self):
88 islset = self._toislset(self.polyhedra, self.symbols)
89 bounded = bool(libisl.isl_set_is_bounded(islset))
90 libisl.isl_set_free(islset)
91 return bounded
92
93 def __eq__(self, other):
94 symbols = self._xsymbols([self, other])
95 islset1 = self._toislset(self.polyhedra, symbols)
96 islset2 = other._toislset(other.polyhedra, symbols)
97 equal = bool(libisl.isl_set_is_equal(islset1, islset2))
98 libisl.isl_set_free(islset1)
99 libisl.isl_set_free(islset2)
100 return equal
101
102 def isdisjoint(self, other):
103 symbols = self._xsymbols([self, other])
104 islset1 = self._toislset(self.polyhedra, symbols)
105 islset2 = self._toislset(other.polyhedra, symbols)
106 equal = bool(libisl.isl_set_is_disjoint(islset1, islset2))
107 libisl.isl_set_free(islset1)
108 libisl.isl_set_free(islset2)
109 return equal
110
111 def issubset(self, other):
112 symbols = self._xsymbols([self, other])
113 islset1 = self._toislset(self.polyhedra, symbols)
114 islset2 = self._toislset(other.polyhedra, symbols)
115 equal = bool(libisl.isl_set_is_subset(islset1, islset2))
116 libisl.isl_set_free(islset1)
117 libisl.isl_set_free(islset2)
118 return equal
119
120 def __le__(self, other):
121 return self.issubset(other)
122
123 def __lt__(self, other):
124 symbols = self._xsymbols([self, other])
125 islset1 = self._toislset(self.polyhedra, symbols)
126 islset2 = self._toislset(other.polyhedra, symbols)
127 equal = bool(libisl.isl_set_is_strict_subset(islset1, islset2))
128 libisl.isl_set_free(islset1)
129 libisl.isl_set_free(islset2)
130 return equal
131
132 def complement(self):
133 islset = self._toislset(self.polyhedra, self.symbols)
134 islset = libisl.isl_set_complement(islset)
135 return self._fromislset(islset, self.symbols)
136
137 def __invert__(self):
138 return self.complement()
139
140 def simplify(self):
141 #does not change anything in any of the examples
142 #isl seems to do this naturally
143 islset = self._toislset(self.polyhedra, self.symbols)
144 islset = libisl.isl_set_remove_redundancies(islset)
145 return self._fromislset(islset, self.symbols)
146
147 def polyhedral_hull(self):
148 # several types of hull are available
149 # polyhedral seems to be the more appropriate, to be checked
150 from .polyhedra import Polyhedron
151 islset = self._toislset(self.polyhedra, self.symbols)
152 islbset = libisl.isl_set_polyhedral_hull(islset)
153 return Polyhedron._fromislbasicset(islbset, self.symbols)
154
155 def project_out(self, dims):
156 # use to remove certain variables
157 islset = self._toislset(self.polyhedra, self.symbols)
158 n = 0
159 for index, symbol in reversed(list(enumerate(self.symbols))):
160 if symbol in dims:
161 n += 1
162 elif n > 0:
163 islset = libisl.isl_set_project_out(islset, libisl.isl_dim_set, index + 1, n)
164 n = 0
165 if n > 0:
166 islset = libisl.isl_set_project_out(islset, libisl.isl_dim_set, 0, n)
167 dims = [symbol for symbol in self.symbols if symbol not in dims]
168 return Domain._fromislset(islset, dims)
169
170 def sample(self):
171 from .polyhedra import Polyhedron
172 islset = self._toislset(self.polyhedra, self.symbols)
173 islbset = libisl.isl_set_sample(islset)
174 # next instruction should NOT be required
175 islbset = libisl.isl_basic_set_finalize(islbset)
176 return Polyhedron._fromislbasicset(islbset, self.symbols)
177
178 def intersection(self, *others):
179 if len(others) == 0:
180 return self
181 symbols = self._xsymbols((self,) + others)
182 islset1 = self._toislset(self.polyhedra, symbols)
183 for other in others:
184 islset2 = other._toislset(other.polyhedra, symbols)
185 islset1 = libisl.isl_set_intersect(islset1, islset2)
186 return self._fromislset(islset1, symbols)
187
188 def __and__(self, other):
189 return self.intersection(other)
190
191 def union(self, *others):
192 if len(others) == 0:
193 return self
194 symbols = self._xsymbols((self,) + others)
195 islset1 = self._toislset(self.polyhedra, symbols)
196 for other in others:
197 islset2 = other._toislset(other.polyhedra, symbols)
198 islset1 = libisl.isl_set_union(islset1, islset2)
199 return self._fromislset(islset1, symbols)
200
201 def __or__(self, other):
202 return self.union(other)
203
204 def __add__(self, other):
205 return self.union(other)
206
207 def difference(self, other):
208 symbols = self._xsymbols([self, other])
209 islset1 = self._toislset(self.polyhedra, symbols)
210 islset2 = other._toislset(other.polyhedra, symbols)
211 islset = libisl.isl_set_subtract(islset1, islset2)
212 return self._fromislset(islset, symbols)
213
214 def __sub__(self, other):
215 return self.difference(other)
216
217 def lexmin(self):
218 islset = self._toislset(self.polyhedra, self.symbols)
219 islset = libisl.isl_set_lexmin(islset)
220 return self._fromislset(islset, self.symbols)
221
222 def lexmax(self):
223 islset = self._toislset(self.polyhedra, self.symbols)
224 islset = libisl.isl_set_lexmax(islset)
225 return self._fromislset(islset, self.symbols)
226
227 def num_parameters(self):
228 #could be useful with large, complicated polyhedrons
229 islbset = self._toislbasicset(self.equalities, self.inequalities, self.symbols)
230 num = libisl.isl_basic_set_dim(islbset, libisl.isl_dim_set)
231 return num
232
233 def involves_dims(self, dims):
234 #could be useful with large, complicated polyhedrons
235 islset = self._toislset(self.polyhedra, self.symbols)
236 dims = sorted(dims)
237 symbols = sorted(list(self.symbols))
238 n = 0
239 if len(dims)>0:
240 for dim in dims:
241 if dim in symbols:
242 first = symbols.index(dims[0])
243 n +=1
244 else:
245 first = 0
246 else:
247 return False
248 value = bool(libisl.isl_set_involves_dims(islset, libisl.isl_dim_set, first, n))
249 libisl.isl_set_free(islset)
250 return value
251
252 def vertices(self):
253 islbset = self._toislbasicset(self.equalities, self.inequalities, self.symbols)
254 vertices = libisl.isl_basic_set_compute_vertices(islbset);
255 vertices = islhelper.isl_vertices_vertices(vertices)
256 for vertex in vertices:
257 expr = libisl.isl_vertex_get_expr(vertex);
258 if islhelper.isl_version < '0.13':
259 string = islhelper.isl_set_to_str(expr)
260 else:
261 string = islhelper.isl_multi_aff_to_str(expr)
262 print(string)
263
264 def points(self):
265 if not self.isbounded():
266 raise ValueError('domain must be unbounded')
267 from .polyhedra import Universe, Eq
268 islset = self._toislset(self.polyhedra, self.symbols)
269 islpoints = islhelper.isl_set_points(islset)
270 points = []
271 for islpoint in islpoints:
272 point = {}
273 for index, symbol in enumerate(self.symbols):
274 coordinate = libisl.isl_point_get_coordinate_val(islpoint,
275 libisl.isl_dim_set, index)
276 coordinate = islhelper.isl_val_to_int(coordinate)
277 point[symbol] = coordinate
278 points.append(point)
279 return points
280
281 @classmethod
282 def _fromislset(cls, islset, symbols):
283 from .polyhedra import Polyhedron
284 islset = libisl.isl_set_remove_divs(islset)
285 islbsets = isl_set_basic_sets(islset)
286 libisl.isl_set_free(islset)
287 polyhedra = []
288 for islbset in islbsets:
289 polyhedron = Polyhedron._fromislbasicset(islbset, symbols)
290 polyhedra.append(polyhedron)
291 if len(polyhedra) == 0:
292 from .polyhedra import Empty
293 return Empty
294 elif len(polyhedra) == 1:
295 return polyhedra[0]
296 else:
297 self = object().__new__(Domain)
298 self._polyhedra = tuple(polyhedra)
299 self._symbols = cls._xsymbols(polyhedra)
300 self._dimension = len(self._symbols)
301 return self
302
303 def _toislset(cls, polyhedra, symbols):
304 polyhedron = polyhedra[0]
305 islbset = polyhedron._toislbasicset(polyhedron.equalities,
306 polyhedron.inequalities, symbols)
307 islset1 = libisl.isl_set_from_basic_set(islbset)
308 for polyhedron in polyhedra[1:]:
309 islbset = polyhedron._toislbasicset(polyhedron.equalities,
310 polyhedron.inequalities, symbols)
311 islset2 = libisl.isl_set_from_basic_set(islbset)
312 islset1 = libisl.isl_set_union(islset1, islset2)
313 return islset1
314
315 @classmethod
316 def _fromast(cls, node):
317 from .polyhedra import Polyhedron
318 if isinstance(node, ast.Module) and len(node.body) == 1:
319 return cls._fromast(node.body[0])
320 elif isinstance(node, ast.Expr):
321 return cls._fromast(node.value)
322 elif isinstance(node, ast.UnaryOp):
323 domain = cls._fromast(node.operand)
324 if isinstance(node.operand, ast.invert):
325 return Not(domain)
326 elif isinstance(node, ast.BinOp):
327 domain1 = cls._fromast(node.left)
328 domain2 = cls._fromast(node.right)
329 if isinstance(node.op, ast.BitAnd):
330 return And(domain1, domain2)
331 elif isinstance(node.op, ast.BitOr):
332 return Or(domain1, domain2)
333 elif isinstance(node, ast.Compare):
334 equalities = []
335 inequalities = []
336 left = Expression._fromast(node.left)
337 for i in range(len(node.ops)):
338 op = node.ops[i]
339 right = Expression._fromast(node.comparators[i])
340 if isinstance(op, ast.Lt):
341 inequalities.append(right - left - 1)
342 elif isinstance(op, ast.LtE):
343 inequalities.append(right - left)
344 elif isinstance(op, ast.Eq):
345 equalities.append(left - right)
346 elif isinstance(op, ast.GtE):
347 inequalities.append(left - right)
348 elif isinstance(op, ast.Gt):
349 inequalities.append(left - right - 1)
350 else:
351 break
352 left = right
353 else:
354 return Polyhedron(equalities, inequalities)
355 raise SyntaxError('invalid syntax')
356
357 _RE_BRACES = re.compile(r'^\{\s*|\s*\}$')
358 _RE_EQ = re.compile(r'([^<=>])=([^<=>])')
359 _RE_AND = re.compile(r'\band\b|,|&&|/\\|∧|∩')
360 _RE_OR = re.compile(r'\bor\b|;|\|\||\\/|∨|∪')
361 _RE_NOT = re.compile(r'\bnot\b|!|¬')
362 _RE_NUM_VAR = Expression._RE_NUM_VAR
363 _RE_OPERATORS = re.compile(r'(&|\||~)')
364
365 @classmethod
366 def fromstring(cls, string):
367 # remove curly brackets
368 string = cls._RE_BRACES.sub(r'', string)
369 # replace '=' by '=='
370 string = cls._RE_EQ.sub(r'\1==\2', string)
371 # replace 'and', 'or', 'not'
372 string = cls._RE_AND.sub(r' & ', string)
373 string = cls._RE_OR.sub(r' | ', string)
374 string = cls._RE_NOT.sub(r' ~', string)
375 # add implicit multiplication operators, e.g. '5x' -> '5*x'
376 string = cls._RE_NUM_VAR.sub(r'\1*\2', string)
377 # add parentheses to force precedence
378 tokens = cls._RE_OPERATORS.split(string)
379 for i, token in enumerate(tokens):
380 if i % 2 == 0:
381 token = '({})'.format(token)
382 tokens[i] = token
383 string = ''.join(tokens)
384 tree = ast.parse(string, 'eval')
385 return cls._fromast(tree)
386
387 def __repr__(self):
388 assert len(self.polyhedra) >= 2
389 strings = [repr(polyhedron) for polyhedron in self.polyhedra]
390 return 'Or({})'.format(', '.join(strings))
391
392 @classmethod
393 def fromsympy(cls, expr):
394 import sympy
395 from .polyhedra import Lt, Le, Eq, Ne, Ge, Gt
396 funcmap = {
397 sympy.And: And, sympy.Or: Or, sympy.Not: Not,
398 sympy.Lt: Lt, sympy.Le: Le,
399 sympy.Eq: Eq, sympy.Ne: Ne,
400 sympy.Ge: Ge, sympy.Gt: Gt,
401 }
402 if expr.func in funcmap:
403 args = [Domain.fromsympy(arg) for arg in expr.args]
404 return funcmap[expr.func](*args)
405 elif isinstance(expr, sympy.Expr):
406 return Expression.fromsympy(expr)
407 raise ValueError('non-domain expression: {!r}'.format(expr))
408
409 def tosympy(self):
410 import sympy
411 polyhedra = [polyhedron.tosympy() for polyhedron in polyhedra]
412 return sympy.Or(*polyhedra)
413
414
415 def And(*domains):
416 if len(domains) == 0:
417 from .polyhedra import Universe
418 return Universe
419 else:
420 return domains[0].intersection(*domains[1:])
421
422 def Or(*domains):
423 if len(domains) == 0:
424 from .polyhedra import Empty
425 return Empty
426 else:
427 return domains[0].union(*domains[1:])
428
429 def Not(domain):
430 return ~domain