3 import ctypes
, ctypes
.util
6 from fractions
import Fraction
, gcd
8 libisl
= ctypes
.CDLL(ctypes
.util
.find_library('isl'))
10 libisl
.isl_printer_get_str
.restype
= ctypes
.c_char_p
14 'constant', 'symbol', 'symbols',
15 'eq', 'le', 'lt', 'ge', 'gt',
21 _CONTEXT
= isl
.Context()
23 def _polymorphic_method(func
):
24 @functools.wraps(func
)
26 if isinstance(b
, Expression
):
28 if isinstance(b
, numbers
.Rational
):
34 def _polymorphic_operator(func
):
35 # A polymorphic operator should call a polymorphic method, hence we just
36 # have to test the left operand.
37 @functools.wraps(func
)
39 if isinstance(a
, numbers
.Rational
):
42 elif isinstance(a
, Expression
):
44 raise TypeError('arguments must be linear expressions')
50 This class implements linear expressions.
53 def __new__(cls
, coefficients
=None, constant
=0):
54 if isinstance(coefficients
, str):
56 raise TypeError('too many arguments')
57 return cls
.fromstring(coefficients
)
58 self
= super().__new
__(cls
)
59 self
._coefficients
= {}
60 if isinstance(coefficients
, dict):
61 coefficients
= coefficients
.items()
62 if coefficients
is not None:
63 for symbol
, coefficient
in coefficients
:
64 if isinstance(symbol
, Expression
) and symbol
.issymbol():
66 elif not isinstance(symbol
, str):
67 raise TypeError('symbols must be strings')
68 if not isinstance(coefficient
, numbers
.Rational
):
69 raise TypeError('coefficients must be rational numbers')
71 self
._coefficients
[symbol
] = coefficient
72 if not isinstance(constant
, numbers
.Rational
):
73 raise TypeError('constant must be a rational number')
74 self
._constant
= constant
79 yield from sorted(self
._coefficients
)
83 return len(list(self
.symbols()))
85 def coefficient(self
, symbol
):
86 if isinstance(symbol
, Expression
) and symbol
.issymbol():
88 elif not isinstance(symbol
, str):
89 raise TypeError('symbol must be a string')
91 return self
._coefficients
[symbol
]
95 __getitem__
= coefficient
97 def coefficients(self
):
98 for symbol
in self
.symbols():
99 yield symbol
, self
.coefficient(symbol
)
103 return self
._constant
105 def isconstant(self
):
106 return len(self
._coefficients
) == 0
109 for symbol
in self
.symbols():
110 yield self
.coefficient(symbol
)
113 def values_int(self
):
114 for symbol
in self
.symbols():
115 return self
.coefficient(symbol
)
116 return int(self
.constant
)
120 if not self
.issymbol():
121 raise ValueError('not a symbol: {}'.format(self
))
122 for symbol
in self
.symbols():
126 return len(self
._coefficients
) == 1 and self
._constant
== 0
129 return (not self
.isconstant()) or bool(self
.constant
)
138 def __add__(self
, other
):
139 coefficients
= dict(self
.coefficients())
140 for symbol
, coefficient
in other
.coefficients():
141 if symbol
in coefficients
:
142 coefficients
[symbol
] += coefficient
144 coefficients
[symbol
] = coefficient
145 constant
= self
.constant
+ other
.constant
146 return Expression(coefficients
, constant
)
151 def __sub__(self
, other
):
152 coefficients
= dict(self
.coefficients())
153 for symbol
, coefficient
in other
.coefficients():
154 if symbol
in coefficients
:
155 coefficients
[symbol
] -= coefficient
157 coefficients
[symbol
] = -coefficient
158 constant
= self
.constant
- other
.constant
159 return Expression(coefficients
, constant
)
161 def __rsub__(self
, other
):
162 return -(self
- other
)
165 def __mul__(self
, other
):
166 if other
.isconstant():
167 coefficients
= dict(self
.coefficients())
168 for symbol
in coefficients
:
169 coefficients
[symbol
] *= other
.constant
170 constant
= self
.constant
* other
.constant
171 return Expression(coefficients
, constant
)
172 if isinstance(other
, Expression
) and not self
.isconstant():
173 raise ValueError('non-linear expression: '
174 '{} * {}'.format(self
._parenstr
(), other
._parenstr
()))
175 return NotImplemented
180 def __truediv__(self
, other
):
181 if other
.isconstant():
182 coefficients
= dict(self
.coefficients())
183 for symbol
in coefficients
:
184 coefficients
[symbol
] = \
185 Fraction(coefficients
[symbol
], other
.constant
)
186 constant
= Fraction(self
.constant
, other
.constant
)
187 return Expression(coefficients
, constant
)
188 if isinstance(other
, Expression
):
189 raise ValueError('non-linear expression: '
190 '{} / {}'.format(self
._parenstr
(), other
._parenstr
()))
191 return NotImplemented
193 def __rtruediv__(self
, other
):
194 if isinstance(other
, self
):
195 if self
.isconstant():
196 constant
= Fraction(other
, self
.constant
)
197 return Expression(constant
=constant
)
199 raise ValueError('non-linear expression: '
200 '{} / {}'.format(other
._parenstr
(), self
._parenstr
()))
201 return NotImplemented
205 symbols
= sorted(self
.symbols())
207 for symbol
in symbols
:
208 coefficient
= self
[symbol
]
213 string
+= ' + {}'.format(symbol
)
214 elif coefficient
== -1:
216 string
+= '-{}'.format(symbol
)
218 string
+= ' - {}'.format(symbol
)
221 string
+= '{}*{}'.format(coefficient
, symbol
)
222 elif coefficient
> 0:
223 string
+= ' + {}*{}'.format(coefficient
, symbol
)
225 assert coefficient
< 0
227 string
+= ' - {}*{}'.format(coefficient
, symbol
)
229 constant
= self
.constant
230 if constant
!= 0 and i
== 0:
231 string
+= '{}'.format(constant
)
233 string
+= ' + {}'.format(constant
)
236 string
+= ' - {}'.format(constant
)
241 def _parenstr(self
, always
=False):
243 if not always
and (self
.isconstant() or self
.issymbol()):
246 return '({})'.format(string
)
249 string
= '{}({{'.format(self
.__class
__.__name
__)
250 for i
, (symbol
, coefficient
) in enumerate(self
.coefficients()):
253 string
+= '{!r}: {!r}'.format(symbol
, coefficient
)
254 string
+= '}}, {!r})'.format(self
.constant
)
258 def fromstring(cls
, string
):
259 raise NotImplementedError
262 def __eq__(self
, other
):
264 # see http://docs.sympy.org/dev/tutorial/gotchas.html#equals-signs
265 return isinstance(other
, Expression
) and \
266 self
._coefficients
== other
._coefficients
and \
267 self
.constant
== other
.constant
270 return hash((self
._coefficients
, self
._constant
))
273 lcm
= functools
.reduce(lambda a
, b
: a
*b
// gcd(a
, b
),
274 [value
.denominator
for value
in self
.values()])
278 def _eq(self
, other
):
279 return Polyhedron(equalities
=[(self
- other
)._canonify
()])
282 def __le__(self
, other
):
283 return Polyhedron(inequalities
=[(self
- other
)._canonify
()])
286 def __lt__(self
, other
):
287 return Polyhedron(inequalities
=[(self
- other
)._canonify
() + 1])
290 def __ge__(self
, other
):
291 return Polyhedron(inequalities
=[(other
- self
)._canonify
()])
294 def __gt__(self
, other
):
295 return Polyhedron(inequalities
=[(other
- self
)._canonify
() + 1])
298 def constant(numerator
=0, denominator
=None):
299 if denominator
is None and isinstance(numerator
, numbers
.Rational
):
300 return Expression(constant
=numerator
)
302 return Expression(constant
=Fraction(numerator
, denominator
))
305 if not isinstance(name
, str):
306 raise TypeError('name must be a string')
307 return Expression(coefficients
={name
: 1})
310 if isinstance(names
, str):
311 names
= names
.replace(',', ' ').split()
312 return (symbol(name
) for name
in names
)
315 @_polymorphic_operator
319 @_polymorphic_operator
323 @_polymorphic_operator
327 @_polymorphic_operator
331 @_polymorphic_operator
338 This class implements polyhedrons.
341 def __new__(cls
, equalities
=None, inequalities
=None):
342 if isinstance(equalities
, str):
343 if inequalities
is not None:
344 raise TypeError('too many arguments')
345 return cls
.fromstring(equalities
)
346 self
= super().__new
__(cls
)
347 self
._equalities
= []
348 if equalities
is not None:
349 for constraint
in equalities
:
350 for value
in constraint
.values():
351 if value
.denominator
!= 1:
352 raise TypeError('non-integer constraint: '
353 '{} == 0'.format(constraint
))
354 self
._equalities
.append(constraint
)
355 self
._inequalities
= []
356 if inequalities
is not None:
357 for constraint
in inequalities
:
358 for value
in constraint
.values():
359 if value
.denominator
!= 1:
360 raise TypeError('non-integer constraint: '
361 '{} <= 0'.format(constraint
))
362 self
._inequalities
.append(constraint
)
363 self
._bset
= self
.to_isl()
368 def equalities(self
):
369 yield from self
._equalities
372 def inequalities(self
):
373 yield from self
._inequalities
377 return self
._constant
379 def isconstant(self
):
380 return len(self
._coefficients
) == 0
384 return bool(libisl
.isl_basic_set_is_empty(self
._bset
))
386 def constraints(self
):
387 yield from self
.equalities
388 yield from self
.inequalities
393 for constraint
in self
.constraints():
394 s
.update(constraint
.symbols
)
397 def symbol_count(self
):
399 for constraint
in self
.constraints():
400 s
.append(constraint
.symbols
)
405 return len(self
.symbols())
408 # return false if the polyhedron is empty, true otherwise
409 if self
._equalities
or self
._inequalities
:
415 def __contains__(self
, value
):
416 # is the value in the polyhedron?
417 raise NotImplementedError
419 def __eq__(self
, other
):
420 raise NotImplementedError
425 def isuniverse(self
):
426 return self
== universe
428 def isdisjoint(self
, other
):
429 # return true if the polyhedron has no elements in common with other
430 raise NotImplementedError
432 def issubset(self
, other
):
433 raise NotImplementedError
435 def __le__(self
, other
):
436 return self
.issubset(other
)
438 def __lt__(self
, other
):
439 raise NotImplementedError
441 def issuperset(self
, other
):
442 # test whether every element in other is in the polyhedron
444 if value
== self
.constraints():
448 raise NotImplementedError
450 def __ge__(self
, other
):
451 return self
.issuperset(other
)
453 def __gt__(self
, other
):
454 raise NotImplementedError
456 def union(self
, *others
):
457 # return a new polyhedron with elements from the polyhedron and all
458 # others (convex union)
459 raise NotImplementedError
461 def __or__(self
, other
):
462 return self
.union(other
)
464 def intersection(self
, *others
):
465 # return a new polyhedron with elements common to the polyhedron and all
467 # a poor man's implementation could be:
468 # equalities = list(self.equalities)
469 # inequalities = list(self.inequalities)
470 # for other in others:
471 # equalities.extend(other.equalities)
472 # inequalities.extend(other.inequalities)
473 # return self.__class__(equalities, inequalities)
474 raise NotImplementedError
476 def __and__(self
, other
):
477 return self
.intersection(other
)
479 def difference(self
, *others
):
480 # return a new polyhedron with elements in the polyhedron that are not
482 raise NotImplementedError
484 def __sub__(self
, other
):
485 return self
.difference(other
)
489 for constraint
in self
.equalities
:
490 constraints
.append('{} == 0'.format(constraint
))
491 for constraint
in self
.inequalities
:
492 constraints
.append('{} <= 0'.format(constraint
))
493 return '{{{}}}'.format(', '.join(constraints
))
496 equalities
= list(self
.equalities
)
497 inequalities
= list(self
.inequalities
)
498 return '{}(equalities={!r}, inequalities={!r})' \
499 ''.format(self
.__class
__.__name
__, equalities
, inequalities
)
502 def fromstring(cls
, string
):
503 raise NotImplementedError
507 ip
= libisl
.isl_printer_to_str(_CONTEXT
)
508 ip
= libisl
.isl_printer_print_val(ip
, self
) #self should be value
509 string
= libisl
.isl_printer_get_str(ip
).decode()
515 space
= libisl
.isl_space_set_alloc(_CONTEXT
, 0, len(self
.symbol_count()))
516 bset
= libisl
.isl_basic_set_empty(libisl
.isl_space_copy(space
))
517 ls
= libisl
.isl_local_space_from_space(libisl
.isl_space_copy(space
))
518 ceq
= libisl
.isl_equality_alloc(libisl
.isl_local_space_copy(ls
))
519 cin
= libisl
.isl_inequality_alloc(libisl
.isl_local_space_copy(ls
))
520 dict_ex
= Expression().__dict
__
523 if there are equalities/inequalities, take each constant and coefficient and add as a constraint to the basic set
524 need to change the symbols method to a lookup table for the integer value for each letter that could be a symbol
527 for _constant
in dict_ex
:
528 value
= dict_ex
.get('_constant')
529 ceq
= libisl
.isl_constraint_set_constant_val(ceq
, value
)
530 for _coefficients
in dict_ex
:
531 value_co
= dict_ex
.get('_coefficients')
533 ceq
= libisl
.isl_constraint_set_coefficient_si(ceq
, libisl
.isl_set_dim
, self
.symbols(), value_co
)
534 bset
= libisl
.isl_set_add_constraint(bset
, ceq
)
535 bset
= libisl
.isl_basic_set_project_out(bset
, libisl
.isl_set_dim
, 1, 1);
536 elif self
.inequalities
:
537 for _constant
in dict_ex
:
538 value
= dict_ex
.get('_constant')
539 cin
= libisl
.isl_constraint_set_constant_val(cin
, value
)
540 for _coefficients
in dict_ex
:
541 value_co
= dict_ex
.get('_coefficients')
543 cin
= libisl
.isl_constraint_set_coefficient_si(cin
, libisl
.isl_set_dim
, self
.symbols(), value_co
)
544 bset
= libisl
.isl_set_add_contraint(bset
, cin
)
546 string
= libisl
.isl_printer_print_basic_set(bset
)
556 universe
= Polyhedron()