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