c844e5559061f6ba51eebbf1ab0f26606641db54
[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
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))
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, symbols):
156 # use to remove certain variables
157 islset = self._toislset(self.polyhedra, self.symbols)
158 # the trick is to walk symbols in reverse order, to avoid index updates
159 for index, symbol in reversed(list(enumerate(self.symbols))):
160 if symbol in symbols:
161 islset = libisl.isl_set_project_out(islset, libisl.isl_dim_set, index, 1)
162 # remaining symbols
163 symbols = [symbol for symbol in self.symbols if symbol not in symbols]
164 return Domain._fromislset(islset, symbols)
165
166 def sample(self):
167 from .polyhedra import Polyhedron
168 islset = self._toislset(self.polyhedra, self.symbols)
169 islbset = libisl.isl_set_sample(islset)
170 return Polyhedron._fromislbasicset(islbset, self.symbols)
171
172 def intersection(self, *others):
173 if len(others) == 0:
174 return self
175 symbols = self._xsymbols((self,) + others)
176 islset1 = self._toislset(self.polyhedra, symbols)
177 for other in others:
178 islset2 = other._toislset(other.polyhedra, symbols)
179 islset1 = libisl.isl_set_intersect(islset1, islset2)
180 return self._fromislset(islset1, symbols)
181
182 def __and__(self, other):
183 return self.intersection(other)
184
185 def union(self, *others):
186 if len(others) == 0:
187 return self
188 symbols = self._xsymbols((self,) + others)
189 islset1 = self._toislset(self.polyhedra, symbols)
190 for other in others:
191 islset2 = other._toislset(other.polyhedra, symbols)
192 islset1 = libisl.isl_set_union(islset1, islset2)
193 return self._fromislset(islset1, symbols)
194
195 def __or__(self, other):
196 return self.union(other)
197
198 def __add__(self, other):
199 return self.union(other)
200
201 def difference(self, other):
202 symbols = self._xsymbols([self, other])
203 islset1 = self._toislset(self.polyhedra, symbols)
204 islset2 = other._toislset(other.polyhedra, symbols)
205 islset = libisl.isl_set_subtract(islset1, islset2)
206 return self._fromislset(islset, symbols)
207
208 def __sub__(self, other):
209 return self.difference(other)
210
211 def lexmin(self):
212 islset = self._toislset(self.polyhedra, self.symbols)
213 islset = libisl.isl_set_lexmin(islset)
214 return self._fromislset(islset, self.symbols)
215
216 def lexmax(self):
217 islset = self._toislset(self.polyhedra, self.symbols)
218 islset = libisl.isl_set_lexmax(islset)
219 return self._fromislset(islset, self.symbols)
220
221 @classmethod
222 def _fromislset(cls, islset, symbols):
223 from .polyhedra import Polyhedron
224 islset = libisl.isl_set_remove_divs(islset)
225 islbsets = isl_set_basic_sets(islset)
226 libisl.isl_set_free(islset)
227 polyhedra = []
228 for islbset in islbsets:
229 polyhedron = Polyhedron._fromislbasicset(islbset, symbols)
230 polyhedra.append(polyhedron)
231 if len(polyhedra) == 0:
232 from .polyhedra import Empty
233 return Empty
234 elif len(polyhedra) == 1:
235 return polyhedra[0]
236 else:
237 self = object().__new__(Domain)
238 self._polyhedra = tuple(polyhedra)
239 self._symbols = cls._xsymbols(polyhedra)
240 self._dimension = len(self._symbols)
241 return self
242
243 def _toislset(cls, polyhedra, symbols):
244 polyhedron = polyhedra[0]
245 islbset = polyhedron._toislbasicset(polyhedron.equalities,
246 polyhedron.inequalities, symbols)
247 islset1 = libisl.isl_set_from_basic_set(islbset)
248 for polyhedron in polyhedra[1:]:
249 islbset = polyhedron._toislbasicset(polyhedron.equalities,
250 polyhedron.inequalities, symbols)
251 islset2 = libisl.isl_set_from_basic_set(islbset)
252 islset1 = libisl.isl_set_union(islset1, islset2)
253 return islset1
254
255 @classmethod
256 def _fromast(cls, node):
257 from .polyhedra import Polyhedron
258 if isinstance(node, ast.Module) and len(node.body) == 1:
259 return cls._fromast(node.body[0])
260 elif isinstance(node, ast.Expr):
261 return cls._fromast(node.value)
262 elif isinstance(node, ast.UnaryOp):
263 domain = cls._fromast(node.operand)
264 if isinstance(node.operand, ast.invert):
265 return Not(domain)
266 elif isinstance(node, ast.BinOp):
267 domain1 = cls._fromast(node.left)
268 domain2 = cls._fromast(node.right)
269 if isinstance(node.op, ast.BitAnd):
270 return And(domain1, domain2)
271 elif isinstance(node.op, ast.BitOr):
272 return Or(domain1, domain2)
273 elif isinstance(node, ast.Compare):
274 equalities = []
275 inequalities = []
276 left = Expression._fromast(node.left)
277 for i in range(len(node.ops)):
278 op = node.ops[i]
279 right = Expression._fromast(node.comparators[i])
280 if isinstance(op, ast.Lt):
281 inequalities.append(right - left - 1)
282 elif isinstance(op, ast.LtE):
283 inequalities.append(right - left)
284 elif isinstance(op, ast.Eq):
285 equalities.append(left - right)
286 elif isinstance(op, ast.GtE):
287 inequalities.append(left - right)
288 elif isinstance(op, ast.Gt):
289 inequalities.append(left - right - 1)
290 else:
291 break
292 left = right
293 else:
294 return Polyhedron(equalities, inequalities)
295 raise SyntaxError('invalid syntax')
296
297 _RE_BRACES = re.compile(r'^\{\s*|\s*\}$')
298 _RE_EQ = re.compile(r'([^<=>])=([^<=>])')
299 _RE_AND = re.compile(r'\band\b|,|&&|/\\|∧|∩')
300 _RE_OR = re.compile(r'\bor\b|;|\|\||\\/|∨|∪')
301 _RE_NOT = re.compile(r'\bnot\b|!|¬')
302 _RE_NUM_VAR = Expression._RE_NUM_VAR
303 _RE_OPERATORS = re.compile(r'(&|\||~)')
304
305 @classmethod
306 def fromstring(cls, string):
307 # remove curly brackets
308 string = cls._RE_BRACES.sub(r'', string)
309 # replace '=' by '=='
310 string = cls._RE_EQ.sub(r'\1==\2', string)
311 # replace 'and', 'or', 'not'
312 string = cls._RE_AND.sub(r' & ', string)
313 string = cls._RE_OR.sub(r' | ', string)
314 string = cls._RE_NOT.sub(r' ~', string)
315 # add implicit multiplication operators, e.g. '5x' -> '5*x'
316 string = cls._RE_NUM_VAR.sub(r'\1*\2', string)
317 # add parentheses to force precedence
318 tokens = cls._RE_OPERATORS.split(string)
319 for i, token in enumerate(tokens):
320 if i % 2 == 0:
321 token = '({})'.format(token)
322 tokens[i] = token
323 string = ''.join(tokens)
324 tree = ast.parse(string, 'eval')
325 return cls._fromast(tree)
326
327 def __repr__(self):
328 assert len(self.polyhedra) >= 2
329 strings = [repr(polyhedron) for polyhedron in self.polyhedra]
330 return 'Or({})'.format(', '.join(strings))
331
332 @classmethod
333 def fromsympy(cls, expr):
334 raise NotImplementedError
335
336 def tosympy(self):
337 raise NotImplementedError
338
339 def And(*domains):
340 if len(domains) == 0:
341 from .polyhedra import Universe
342 return Universe
343 else:
344 return domains[0].intersection(*domains[1:])
345
346 def Or(*domains):
347 if len(domains) == 0:
348 from .polyhedra import Empty
349 return Empty
350 else:
351 return domains[0].union(*domains[1:])
352
353 def Not(domain):
354 return ~domain