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