New module coordinates.py
[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 subs(self, symbol, expression=None):
316 polyhedra = [polyhedron.subs(symbol, expression)
317 for polyhedron in self.polyhedra]
318 return Domain(*polyhedra)
319
320 @classmethod
321 def _fromislset(cls, islset, symbols):
322 from .polyhedra import Polyhedron
323 islset = libisl.isl_set_remove_divs(islset)
324 islbsets = isl_set_basic_sets(islset)
325 libisl.isl_set_free(islset)
326 polyhedra = []
327 for islbset in islbsets:
328 polyhedron = Polyhedron._fromislbasicset(islbset, symbols)
329 polyhedra.append(polyhedron)
330 if len(polyhedra) == 0:
331 from .polyhedra import Empty
332 return Empty
333 elif len(polyhedra) == 1:
334 return polyhedra[0]
335 else:
336 self = object().__new__(Domain)
337 self._polyhedra = tuple(polyhedra)
338 self._symbols = cls._xsymbols(polyhedra)
339 self._dimension = len(self._symbols)
340 return self
341
342 @classmethod
343 def _toislset(cls, polyhedra, symbols):
344 polyhedron = polyhedra[0]
345 islbset = polyhedron._toislbasicset(polyhedron.equalities,
346 polyhedron.inequalities, symbols)
347 islset1 = libisl.isl_set_from_basic_set(islbset)
348 for polyhedron in polyhedra[1:]:
349 islbset = polyhedron._toislbasicset(polyhedron.equalities,
350 polyhedron.inequalities, symbols)
351 islset2 = libisl.isl_set_from_basic_set(islbset)
352 islset1 = libisl.isl_set_union(islset1, islset2)
353 return islset1
354
355 @classmethod
356 def _fromast(cls, node):
357 from .polyhedra import Polyhedron
358 if isinstance(node, ast.Module) and len(node.body) == 1:
359 return cls._fromast(node.body[0])
360 elif isinstance(node, ast.Expr):
361 return cls._fromast(node.value)
362 elif isinstance(node, ast.UnaryOp):
363 domain = cls._fromast(node.operand)
364 if isinstance(node.operand, ast.invert):
365 return Not(domain)
366 elif isinstance(node, ast.BinOp):
367 domain1 = cls._fromast(node.left)
368 domain2 = cls._fromast(node.right)
369 if isinstance(node.op, ast.BitAnd):
370 return And(domain1, domain2)
371 elif isinstance(node.op, ast.BitOr):
372 return Or(domain1, domain2)
373 elif isinstance(node, ast.Compare):
374 equalities = []
375 inequalities = []
376 left = Expression._fromast(node.left)
377 for i in range(len(node.ops)):
378 op = node.ops[i]
379 right = Expression._fromast(node.comparators[i])
380 if isinstance(op, ast.Lt):
381 inequalities.append(right - left - 1)
382 elif isinstance(op, ast.LtE):
383 inequalities.append(right - left)
384 elif isinstance(op, ast.Eq):
385 equalities.append(left - right)
386 elif isinstance(op, ast.GtE):
387 inequalities.append(left - right)
388 elif isinstance(op, ast.Gt):
389 inequalities.append(left - right - 1)
390 else:
391 break
392 left = right
393 else:
394 return Polyhedron(equalities, inequalities)
395 raise SyntaxError('invalid syntax')
396
397 _RE_BRACES = re.compile(r'^\{\s*|\s*\}$')
398 _RE_EQ = re.compile(r'([^<=>])=([^<=>])')
399 _RE_AND = re.compile(r'\band\b|,|&&|/\\|∧|∩')
400 _RE_OR = re.compile(r'\bor\b|;|\|\||\\/|∨|∪')
401 _RE_NOT = re.compile(r'\bnot\b|!|¬')
402 _RE_NUM_VAR = Expression._RE_NUM_VAR
403 _RE_OPERATORS = re.compile(r'(&|\||~)')
404
405 @classmethod
406 def fromstring(cls, string):
407 # remove curly brackets
408 string = cls._RE_BRACES.sub(r'', string)
409 # replace '=' by '=='
410 string = cls._RE_EQ.sub(r'\1==\2', string)
411 # replace 'and', 'or', 'not'
412 string = cls._RE_AND.sub(r' & ', string)
413 string = cls._RE_OR.sub(r' | ', string)
414 string = cls._RE_NOT.sub(r' ~', string)
415 # add implicit multiplication operators, e.g. '5x' -> '5*x'
416 string = cls._RE_NUM_VAR.sub(r'\1*\2', string)
417 # add parentheses to force precedence
418 tokens = cls._RE_OPERATORS.split(string)
419 for i, token in enumerate(tokens):
420 if i % 2 == 0:
421 token = '({})'.format(token)
422 tokens[i] = token
423 string = ''.join(tokens)
424 tree = ast.parse(string, 'eval')
425 return cls._fromast(tree)
426
427 def __repr__(self):
428 assert len(self.polyhedra) >= 2
429 strings = [repr(polyhedron) for polyhedron in self.polyhedra]
430 return 'Or({})'.format(', '.join(strings))
431
432 @classmethod
433 def fromsympy(cls, expr):
434 import sympy
435 from .polyhedra import Lt, Le, Eq, Ne, Ge, Gt
436 funcmap = {
437 sympy.And: And, sympy.Or: Or, sympy.Not: Not,
438 sympy.Lt: Lt, sympy.Le: Le,
439 sympy.Eq: Eq, sympy.Ne: Ne,
440 sympy.Ge: Ge, sympy.Gt: Gt,
441 }
442 if expr.func in funcmap:
443 args = [Domain.fromsympy(arg) for arg in expr.args]
444 return funcmap[expr.func](*args)
445 elif isinstance(expr, sympy.Expr):
446 return Expression.fromsympy(expr)
447 raise ValueError('non-domain expression: {!r}'.format(expr))
448
449 def tosympy(self):
450 import sympy
451 polyhedra = [polyhedron.tosympy() for polyhedron in polyhedra]
452 return sympy.Or(*polyhedra)
453
454
455 def And(*domains):
456 if len(domains) == 0:
457 from .polyhedra import Universe
458 return Universe
459 else:
460 return domains[0].intersection(*domains[1:])
461
462 def Or(*domains):
463 if len(domains) == 0:
464 from .polyhedra import Empty
465 return Empty
466 else:
467 return domains[0].union(*domains[1:])
468
469 def Not(domain):
470 return ~domain