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