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