255c995b76654b92ea23ffcfe7b86c350d5e757f
[linpy.git] / pypol / domains.py
1 import ast
2 import functools
3 import re
4
5 from fractions import Fraction
6
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
11
12
13 __all__ = [
14 'Domain',
15 'And', 'Or', 'Not',
16 ]
17
18
19 @functools.total_ordering
20 class Domain:
21
22 __slots__ = (
23 '_polyhedra',
24 '_symbols',
25 '_dimension',
26 )
27
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):
35 return polyhedron
36 else:
37 raise TypeError('argument must be a string '
38 'or a Polyhedron instance')
39 else:
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)
46
47 @classmethod
48 def _xsymbols(cls, iterator):
49 """
50 Return the ordered tuple of symbols present in iterator.
51 """
52 symbols = set()
53 for item in iterator:
54 symbols.update(item.symbols)
55 return tuple(sorted(symbols, key=Symbol.sortkey))
56
57 @property
58 def polyhedra(self):
59 return self._polyhedra
60
61 @property
62 def symbols(self):
63 return self._symbols
64
65 @property
66 def dimension(self):
67 return self._dimension
68
69 def disjoint(self):
70 islset = self._toislset(self.polyhedra, self.symbols)
71 islset = libisl.isl_set_make_disjoint(mainctx, islset)
72 return self._fromislset(islset, self.symbols)
73
74 def isempty(self):
75 islset = self._toislset(self.polyhedra, self.symbols)
76 empty = bool(libisl.isl_set_is_empty(islset))
77 libisl.isl_set_free(islset)
78 return empty
79
80 def __bool__(self):
81 return not self.isempty()
82
83 def isuniverse(self):
84 islset = self._toislset(self.polyhedra, self.symbols)
85 universe = bool(libisl.isl_set_plain_is_universe(islset))
86 libisl.isl_set_free(islset)
87 return universe
88
89 def isbounded(self):
90 islset = self._toislset(self.polyhedra, self.symbols)
91 bounded = bool(libisl.isl_set_is_bounded(islset))
92 libisl.isl_set_free(islset)
93 return bounded
94
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)
102 return equal
103
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)
111 return equal
112
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)
120 return equal
121
122 def __le__(self, other):
123 return self.issubset(other)
124
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)
132 return equal
133
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)
138
139 def __invert__(self):
140 return self.complement()
141
142 def simplify(self):
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)
148
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)
156
157 def project(self, dims):
158 # use to remove certain variables
159 islset = self._toislset(self.polyhedra, self.symbols)
160 n = 0
161 for index, symbol in reversed(list(enumerate(self.symbols))):
162 if symbol in dims:
163 n += 1
164 elif n > 0:
165 islset = libisl.isl_set_project_out(islset, libisl.isl_dim_set, index + 1, n)
166 n = 0
167 if n > 0:
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)
171
172 def sample(self):
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')
178 point = {}
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)
185 return point
186
187 def intersection(self, *others):
188 if len(others) == 0:
189 return self
190 symbols = self._xsymbols((self,) + others)
191 islset1 = self._toislset(self.polyhedra, symbols)
192 for other in others:
193 islset2 = other._toislset(other.polyhedra, symbols)
194 islset1 = libisl.isl_set_intersect(islset1, islset2)
195 return self._fromislset(islset1, symbols)
196
197 def __and__(self, other):
198 return self.intersection(other)
199
200 def union(self, *others):
201 if len(others) == 0:
202 return self
203 symbols = self._xsymbols((self,) + others)
204 islset1 = self._toislset(self.polyhedra, symbols)
205 for other in others:
206 islset2 = other._toislset(other.polyhedra, symbols)
207 islset1 = libisl.isl_set_union(islset1, islset2)
208 return self._fromislset(islset1, symbols)
209
210 def __or__(self, other):
211 return self.union(other)
212
213 def __add__(self, other):
214 return self.union(other)
215
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)
222
223 def __sub__(self, other):
224 return self.difference(other)
225
226 def lexmin(self):
227 islset = self._toislset(self.polyhedra, self.symbols)
228 islset = libisl.isl_set_lexmin(islset)
229 return self._fromislset(islset, self.symbols)
230
231 def lexmax(self):
232 islset = self._toislset(self.polyhedra, self.symbols)
233 islset = libisl.isl_set_lexmax(islset)
234 return self._fromislset(islset, self.symbols)
235
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)
240 return num
241
242 def involves_dims(self, dims):
243 #could be useful with large, complicated polyhedrons
244 islset = self._toislset(self.polyhedra, self.symbols)
245 dims = sorted(dims)
246 symbols = sorted(list(self.symbols))
247 n = 0
248 if len(dims)>0:
249 for dim in dims:
250 if dim in symbols:
251 first = symbols.index(dims[0])
252 n +=1
253 else:
254 first = 0
255 else:
256 return False
257 value = bool(libisl.isl_set_involves_dims(islset, libisl.isl_dim_set, first, n))
258 libisl.isl_set_free(islset)
259 return value
260
261 _RE_COORDINATE = re.compile(r'\((?P<num>\-?\d+)\)(/(?P<den>\d+))?')
262
263 def vertices(self):
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)
269 points = []
270 for vertex in vertices:
271 expr = libisl.isl_vertex_get_expr(vertex)
272 coordinates = []
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)
282 if coefficient != 0:
283 coordinate = -Fraction(constant, coefficient)
284 coordinates.append((symbol, coordinate))
285 else:
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))
296 return points
297
298 def points(self):
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)
304 points = []
305 for islpoint in islpoints:
306 coordinates = {}
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))
313 return points
314
315 def __contains__(self, point):
316 for polyhedron in self.polyhedra:
317 if point in polyhedron:
318 return True
319 return False
320
321 def subs(self, symbol, expression=None):
322 polyhedra = [polyhedron.subs(symbol, expression)
323 for polyhedron in self.polyhedra]
324 return Domain(*polyhedra)
325
326 @classmethod
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)
332 polyhedra = []
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
338 return Empty
339 elif len(polyhedra) == 1:
340 return polyhedra[0]
341 else:
342 self = object().__new__(Domain)
343 self._polyhedra = tuple(polyhedra)
344 self._symbols = cls._xsymbols(polyhedra)
345 self._dimension = len(self._symbols)
346 return self
347
348 @classmethod
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)
359 return islset1
360
361 @classmethod
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):
371 return Not(domain)
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):
380 equalities = []
381 inequalities = []
382 left = Expression._fromast(node.left)
383 for i in range(len(node.ops)):
384 op = node.ops[i]
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)
396 else:
397 break
398 left = right
399 else:
400 return Polyhedron(equalities, inequalities)
401 raise SyntaxError('invalid syntax')
402
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'(&|\||~)')
410
411 @classmethod
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):
426 if i % 2 == 0:
427 token = '({})'.format(token)
428 tokens[i] = token
429 string = ''.join(tokens)
430 tree = ast.parse(string, 'eval')
431 return cls._fromast(tree)
432
433 def __repr__(self):
434 assert len(self.polyhedra) >= 2
435 strings = [repr(polyhedron) for polyhedron in self.polyhedra]
436 return 'Or({})'.format(', '.join(strings))
437
438 @classmethod
439 def fromsympy(cls, expr):
440 import sympy
441 from .polyhedra import Lt, Le, Eq, Ne, Ge, Gt
442 funcmap = {
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,
447 }
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))
454
455 def tosympy(self):
456 import sympy
457 polyhedra = [polyhedron.tosympy() for polyhedron in polyhedra]
458 return sympy.Or(*polyhedra)
459
460
461 def And(*domains):
462 if len(domains) == 0:
463 from .polyhedra import Universe
464 return Universe
465 else:
466 return domains[0].intersection(*domains[1:])
467
468 def Or(*domains):
469 if len(domains) == 0:
470 from .polyhedra import Empty
471 return Empty
472 else:
473 return domains[0].union(*domains[1:])
474
475 def Not(domain):
476 return ~domain