621a157638462f8ec01f1a64909cebdd3616e5a3
4 from fractions
import Fraction
, gcd
7 from pypol
.isl
import libisl
11 'Expression', 'Constant', 'Symbol', 'symbols',
12 'eq', 'le', 'lt', 'ge', 'gt',
18 def _polymorphic_method(func
):
19 @functools.wraps(func
)
21 if isinstance(b
, Expression
):
23 if isinstance(b
, numbers
.Rational
):
29 def _polymorphic_operator(func
):
30 # A polymorphic operator should call a polymorphic method, hence we just
31 # have to test the left operand.
32 @functools.wraps(func
)
34 if isinstance(a
, numbers
.Rational
):
37 elif isinstance(a
, Expression
):
39 raise TypeError('arguments must be linear expressions')
43 _main_ctx
= isl
.Context()
48 This class implements linear expressions.
51 def __new__(cls
, coefficients
=None, constant
=0):
52 if isinstance(coefficients
, str):
54 raise TypeError('too many arguments')
55 return cls
.fromstring(coefficients
)
56 if isinstance(coefficients
, dict):
57 coefficients
= coefficients
.items()
58 if coefficients
is None:
59 return Constant(constant
)
60 coefficients
= [(symbol
, coefficient
)
61 for symbol
, coefficient
in coefficients
if coefficient
!= 0]
62 if len(coefficients
) == 0:
63 return Constant(constant
)
64 elif len(coefficients
) == 1 and constant
== 0:
65 symbol
, coefficient
= coefficients
[0]
68 self
= object().__new
__(cls
)
69 self
._coefficients
= {}
70 for symbol
, coefficient
in coefficients
:
71 if isinstance(symbol
, Symbol
):
73 elif not isinstance(symbol
, str):
74 raise TypeError('symbols must be strings or Symbol instances')
75 if isinstance(coefficient
, Constant
):
76 coefficient
= coefficient
.constant
77 if not isinstance(coefficient
, numbers
.Rational
):
78 raise TypeError('coefficients must be rational numbers or Constant instances')
79 self
._coefficients
[symbol
] = coefficient
80 if isinstance(constant
, Constant
):
81 constant
= constant
.constant
82 if not isinstance(constant
, numbers
.Rational
):
83 raise TypeError('constant must be a rational number or a Constant instance')
84 self
._constant
= constant
85 self
._symbols
= tuple(sorted(self
._coefficients
))
86 self
._dimension
= len(self
._symbols
)
90 def fromstring(cls
, string
):
91 raise NotImplementedError
99 return self
._dimension
101 def coefficient(self
, symbol
):
102 if isinstance(symbol
, Symbol
):
104 elif not isinstance(symbol
, str):
105 raise TypeError('symbol must be a string or a Symbol instance')
107 return self
._coefficients
[symbol
]
111 __getitem__
= coefficient
113 def coefficients(self
):
114 for symbol
in self
.symbols
:
115 yield symbol
, self
.coefficient(symbol
)
119 return self
._constant
121 def isconstant(self
):
125 for symbol
in self
.symbols
:
126 yield self
.coefficient(symbol
)
142 def __add__(self
, other
):
143 coefficients
= dict(self
.coefficients())
144 for symbol
, coefficient
in other
.coefficients():
145 if symbol
in coefficients
:
146 coefficients
[symbol
] += coefficient
148 coefficients
[symbol
] = coefficient
149 constant
= self
.constant
+ other
.constant
150 return Expression(coefficients
, constant
)
155 def __sub__(self
, other
):
156 coefficients
= dict(self
.coefficients())
157 for symbol
, coefficient
in other
.coefficients():
158 if symbol
in coefficients
:
159 coefficients
[symbol
] -= coefficient
161 coefficients
[symbol
] = -coefficient
162 constant
= self
.constant
- other
.constant
163 return Expression(coefficients
, constant
)
165 def __rsub__(self
, other
):
166 return -(self
- other
)
169 def __mul__(self
, other
):
170 if other
.isconstant():
171 coefficients
= dict(self
.coefficients())
172 for symbol
in coefficients
:
173 coefficients
[symbol
] *= other
.constant
174 constant
= self
.constant
* other
.constant
175 return Expression(coefficients
, constant
)
176 if isinstance(other
, Expression
) and not self
.isconstant():
177 raise ValueError('non-linear expression: '
178 '{} * {}'.format(self
._parenstr
(), other
._parenstr
()))
179 return NotImplemented
184 def __truediv__(self
, other
):
185 if other
.isconstant():
186 coefficients
= dict(self
.coefficients())
187 for symbol
in coefficients
:
188 coefficients
[symbol
] = \
189 Fraction(coefficients
[symbol
], other
.constant
)
190 constant
= Fraction(self
.constant
, other
.constant
)
191 return Expression(coefficients
, constant
)
192 if isinstance(other
, Expression
):
193 raise ValueError('non-linear expression: '
194 '{} / {}'.format(self
._parenstr
(), other
._parenstr
()))
195 return NotImplemented
197 def __rtruediv__(self
, other
):
198 if isinstance(other
, self
):
199 if self
.isconstant():
200 constant
= Fraction(other
, self
.constant
)
201 return Expression(constant
=constant
)
203 raise ValueError('non-linear expression: '
204 '{} / {}'.format(other
._parenstr
(), self
._parenstr
()))
205 return NotImplemented
210 for symbol
in self
.symbols
:
211 coefficient
= self
.coefficient(symbol
)
216 string
+= ' + {}'.format(symbol
)
217 elif coefficient
== -1:
219 string
+= '-{}'.format(symbol
)
221 string
+= ' - {}'.format(symbol
)
224 string
+= '{}*{}'.format(coefficient
, symbol
)
225 elif coefficient
> 0:
226 string
+= ' + {}*{}'.format(coefficient
, symbol
)
228 assert coefficient
< 0
230 string
+= ' - {}*{}'.format(coefficient
, symbol
)
232 constant
= self
.constant
233 if constant
!= 0 and i
== 0:
234 string
+= '{}'.format(constant
)
236 string
+= ' + {}'.format(constant
)
239 string
+= ' - {}'.format(constant
)
244 def _parenstr(self
, always
=False):
246 if not always
and (self
.isconstant() or self
.issymbol()):
249 return '({})'.format(string
)
252 string
= '{}({{'.format(self
.__class
__.__name
__)
253 for i
, (symbol
, coefficient
) in enumerate(self
.coefficients()):
256 string
+= '{!r}: {!r}'.format(symbol
, coefficient
)
257 string
+= '}}, {!r})'.format(self
.constant
)
261 def __eq__(self
, other
):
263 # see http://docs.sympy.org/dev/tutorial/gotchas.html#equals-signs
264 return isinstance(other
, Expression
) and \
265 self
._coefficients
== other
._coefficients
and \
266 self
.constant
== other
.constant
269 return hash((tuple(sorted(self
._coefficients
.items())), self
._constant
))
272 lcm
= functools
.reduce(lambda a
, b
: a
*b
// gcd(a
, b
),
273 [value
.denominator
for value
in self
.values()])
277 def _eq(self
, other
):
278 return Polyhedron(equalities
=[(self
- other
)._toint
()])
281 def __le__(self
, other
):
282 return Polyhedron(inequalities
=[(other
- self
)._toint
()])
285 def __lt__(self
, other
):
286 return Polyhedron(inequalities
=[(other
- self
)._toint
() - 1])
289 def __ge__(self
, other
):
290 return Polyhedron(inequalities
=[(self
- other
)._toint
()])
293 def __gt__(self
, other
):
294 return Polyhedron(inequalities
=[(self
- other
)._toint
() - 1])
297 class Constant(Expression
):
299 def __new__(cls
, numerator
=0, denominator
=None):
300 self
= object().__new
__(cls
)
301 if denominator
is None:
302 if isinstance(numerator
, numbers
.Rational
):
303 self
._constant
= numerator
304 elif isinstance(numerator
, Constant
):
305 self
._constant
= numerator
.constant
307 raise TypeError('constant must be a rational number or a Constant instance')
309 self
._constant
= Fraction(numerator
, denominator
)
310 self
._coefficients
= {}
315 def isconstant(self
):
319 return bool(self
.constant
)
322 return '{}({!r})'.format(self
.__class
__.__name
__, self
._constant
)
325 class Symbol(Expression
):
327 def __new__(cls
, name
):
328 if isinstance(name
, Symbol
):
330 elif not isinstance(name
, str):
331 raise TypeError('name must be a string or a Symbol instance')
332 self
= object().__new
__(cls
)
333 self
._coefficients
= {name
: 1}
335 self
._symbols
= tuple(name
)
348 return '{}({!r})'.format(self
.__class
__.__name
__, self
._name
)
351 if isinstance(names
, str):
352 names
= names
.replace(',', ' ').split()
353 return (Symbol(name
) for name
in names
)
356 @_polymorphic_operator
360 @_polymorphic_operator
364 @_polymorphic_operator
368 @_polymorphic_operator
372 @_polymorphic_operator
379 This class implements polyhedrons.
382 def __new__(cls
, equalities
=None, inequalities
=None):
383 if isinstance(equalities
, str):
384 if inequalities
is not None:
385 raise TypeError('too many arguments')
386 return cls
.fromstring(equalities
)
387 self
= super().__new
__(cls
)
388 self
._equalities
= []
389 if equalities
is not None:
390 for constraint
in equalities
:
391 for value
in constraint
.values():
392 if value
.denominator
!= 1:
393 raise TypeError('non-integer constraint: '
394 '{} == 0'.format(constraint
))
395 self
._equalities
.append(constraint
)
396 self
._equalities
= tuple(self
._equalities
)
397 self
._inequalities
= []
398 if inequalities
is not None:
399 for constraint
in inequalities
:
400 for value
in constraint
.values():
401 if value
.denominator
!= 1:
402 raise TypeError('non-integer constraint: '
403 '{} <= 0'.format(constraint
))
404 self
._inequalities
.append(constraint
)
405 self
._inequalities
= tuple(self
._inequalities
)
406 self
._constraints
= self
._equalities
+ self
._inequalities
407 self
._symbols
= set()
408 for constraint
in self
._constraints
:
409 self
.symbols
.update(constraint
.symbols
)
410 self
._symbols
= tuple(sorted(self
._symbols
))
414 def fromstring(cls
, string
):
415 raise NotImplementedError
418 def equalities(self
):
419 return self
._equalities
422 def inequalities(self
):
423 return self
._inequalities
426 def constraints(self
):
427 return self
._constraints
435 return len(self
.symbols
)
438 return not self
.is_empty()
440 def __contains__(self
, value
):
441 # is the value in the polyhedron?
442 raise NotImplementedError
444 def __eq__(self
, other
):
445 # works correctly when symbols is not passed
446 # should be equal if values are the same even if symbols are different
448 other
= other
._toisl
()
449 return bool(libisl
.isl_basic_set_plain_is_equal(bset
, other
))
453 return bool(libisl
.isl_basic_set_is_empty(bset
))
455 def isuniverse(self
):
457 return bool(libisl
.isl_basic_set_is_universe(bset
))
459 def isdisjoint(self
, other
):
460 # return true if the polyhedron has no elements in common with other
461 #symbols = self._symbolunion(other)
463 other
= other
._toisl
()
464 return bool(libisl
.isl_set_is_disjoint(bset
, other
))
466 def issubset(self
, other
):
467 # check if self(bset) is a subset of other
468 symbols
= self
._symbolunion
(other
)
469 bset
= self
._toisl
(symbols
)
470 other
= other
._toisl
(symbols
)
471 return bool(libisl
.isl_set_is_strict_subset(other
, bset
))
473 def __le__(self
, other
):
474 return self
.issubset(other
)
476 def __lt__(self
, other
):
477 symbols
= self
._symbolunion
(other
)
478 bset
= self
._toisl
(symbols
)
479 other
= other
._toisl
(symbols
)
480 return bool(libisl
.isl_set_is_strict_subset(other
, bset
))
482 def issuperset(self
, other
):
483 # test whether every element in other is in the polyhedron
484 raise NotImplementedError
486 def __ge__(self
, other
):
487 return self
.issuperset(other
)
489 def __gt__(self
, other
):
490 symbols
= self
._symbolunion
(other
)
491 bset
= self
._toisl
(symbols
)
492 other
= other
._toisl
(symbols
)
493 bool(libisl
.isl_set_is_strict_subset(other
, bset
))
494 raise NotImplementedError
496 def union(self
, *others
):
497 # return a new polyhedron with elements from the polyhedron and all
498 # others (convex union)
499 raise NotImplementedError
501 def __or__(self
, other
):
502 return self
.union(other
)
504 def intersection(self
, *others
):
505 # return a new polyhedron with elements common to the polyhedron and all
507 # a poor man's implementation could be:
508 # equalities = list(self.equalities)
509 # inequalities = list(self.inequalities)
510 # for other in others:
511 # equalities.extend(other.equalities)
512 # inequalities.extend(other.inequalities)
513 # return self.__class__(equalities, inequalities)
514 raise NotImplementedError
516 def __and__(self
, other
):
517 return self
.intersection(other
)
519 def difference(self
, other
):
520 # return a new polyhedron with elements in the polyhedron that are not in the other
521 symbols
= self
._symbolunion
(other
)
522 bset
= self
._toisl
(symbols
)
523 other
= other
._toisl
(symbols
)
524 difference
= libisl
.isl_set_subtract(bset
, other
)
528 def __sub__(self
, other
):
529 return self
.difference(other
)
533 for constraint
in self
.equalities
:
534 constraints
.append('{} == 0'.format(constraint
))
535 for constraint
in self
.inequalities
:
536 constraints
.append('{} >= 0'.format(constraint
))
537 return '{{{}}}'.format(', '.join(constraints
))
542 elif self
.isuniverse():
545 equalities
= list(self
.equalities
)
546 inequalities
= list(self
.inequalities
)
547 return '{}(equalities={!r}, inequalities={!r})' \
548 ''.format(self
.__class
__.__name
__, equalities
, inequalities
)
550 def _symbolunion(self
, *others
):
551 symbols
= set(self
.symbols
)
553 symbols
.update(other
.symbols
)
554 return sorted(symbols
)
556 def _toisl(self
, symbols
=None):
558 symbols
= self
.symbols
559 num_coefficients
= len(symbols
)
560 space
= libisl
.isl_space_set_alloc(_main_ctx
, 0, num_coefficients
)
561 bset
= libisl
.isl_basic_set_universe(libisl
.isl_space_copy(space
))
562 ls
= libisl
.isl_local_space_from_space(space
)
563 #if there are equalities/inequalities, take each constant and coefficient and add as a constraint to the basic set
564 for eq
in self
.equalities
:
565 ceq
= libisl
.isl_equality_alloc(libisl
.isl_local_space_copy(ls
))
566 coeff_eq
= dict(eq
.coefficients())
568 value
= str(eq
.constant
).encode()
569 val
= libisl
.isl_val_read_from_str(_main_ctx
, value
)
570 ceq
= libisl
.isl_constraint_set_constant_val(ceq
, val
)
572 number
= str(coeff_eq
.get(eq
)).encode()
573 num
= libisl
.isl_val_read_from_str(_main_ctx
, number
)
574 iden
= symbols
.index(eq
)
575 ceq
= libisl
.isl_constraint_set_coefficient_val(ceq
, libisl
.isl_dim_set
, iden
, num
) #use 3 for type isl_dim_set
576 bset
= libisl
.isl_basic_set_add_constraint(bset
, ceq
)
577 for ineq
in self
.inequalities
:
578 cin
= libisl
.isl_inequality_alloc(libisl
.isl_local_space_copy(ls
))
579 coeff_in
= dict(ineq
.coefficients())
581 value
= str(ineq
.constant
).encode()
582 val
= libisl
.isl_val_read_from_str(_main_ctx
, value
)
583 cin
= libisl
.isl_constraint_set_constant_val(cin
, val
)
584 for ineq
in coeff_in
:
585 number
= str(coeff_in
.get(ineq
)).encode()
586 num
= libisl
.isl_val_read_from_str(_main_ctx
, number
)
587 iden
= symbols
.index(ineq
)
588 cin
= libisl
.isl_constraint_set_coefficient_val(cin
, libisl
.isl_dim_set
, iden
, num
) #use 3 for type isl_dim_set
589 bset
= libisl
.isl_basic_set_add_constraint(bset
, cin
)
590 bset
= isl
.BasicSet(bset
)
594 def _fromisl(cls
, bset
):
595 raise NotImplementedError
598 return cls(equalities
, inequalities
)
599 '''takes basic set in isl form and puts back into python version of polyhedron
600 isl example code gives isl form as:
601 "{[i] : exists (a : i = 2a and i >= 10 and i <= 42)}")
602 our printer is giving form as:
603 { [i0, i1] : 2i1 >= -2 - i0 } '''
606 Universe
= Polyhedron()
608 if __name__
== '__main__':
609 ex1
= Expression(coefficients
={'a': 6, 'b': 6}, constant
= 3) #this is the expression that does not work (even without adding values)
610 ex2
= Expression(coefficients
={'x': 4, 'y': 2}, constant
= 3)
611 p
= Polyhedron(equalities
=[ex2
])
612 p2
= Polyhedron(equalities
=[ex2
])
613 print(p
._toisl
()) # checking is values works for toisl