e6d442e454c4072fcc2addeca305e9846791c62b
6 from fractions
import Fraction
, gcd
9 from pypol
.isl
import libisl
13 'Expression', 'Constant', 'Symbol', 'symbols',
14 'eq', 'le', 'lt', 'ge', 'gt',
20 def _polymorphic_method(func
):
21 @functools.wraps(func
)
23 if isinstance(b
, Expression
):
25 if isinstance(b
, numbers
.Rational
):
31 def _polymorphic_operator(func
):
32 # A polymorphic operator should call a polymorphic method, hence we just
33 # have to test the left operand.
34 @functools.wraps(func
)
36 if isinstance(a
, numbers
.Rational
):
39 elif isinstance(a
, Expression
):
41 raise TypeError('arguments must be linear expressions')
45 _main_ctx
= isl
.Context()
50 This class implements linear expressions.
60 def __new__(cls
, coefficients
=None, constant
=0):
61 if isinstance(coefficients
, str):
63 raise TypeError('too many arguments')
64 return cls
.fromstring(coefficients
)
65 if isinstance(coefficients
, dict):
66 coefficients
= coefficients
.items()
67 if coefficients
is None:
68 return Constant(constant
)
69 coefficients
= [(symbol
, coefficient
)
70 for symbol
, coefficient
in coefficients
if coefficient
!= 0]
71 if len(coefficients
) == 0:
72 return Constant(constant
)
73 elif len(coefficients
) == 1 and constant
== 0:
74 symbol
, coefficient
= coefficients
[0]
77 self
= object().__new
__(cls
)
78 self
._coefficients
= {}
79 for symbol
, coefficient
in coefficients
:
80 if isinstance(symbol
, Symbol
):
82 elif not isinstance(symbol
, str):
83 raise TypeError('symbols must be strings or Symbol instances')
84 if isinstance(coefficient
, Constant
):
85 coefficient
= coefficient
.constant
86 if not isinstance(coefficient
, numbers
.Rational
):
87 raise TypeError('coefficients must be rational numbers or Constant instances')
88 self
._coefficients
[symbol
] = coefficient
89 if isinstance(constant
, Constant
):
90 constant
= constant
.constant
91 if not isinstance(constant
, numbers
.Rational
):
92 raise TypeError('constant must be a rational number or a Constant instance')
93 self
._constant
= constant
94 self
._symbols
= tuple(sorted(self
._coefficients
))
95 self
._dimension
= len(self
._symbols
)
99 def _fromast(cls
, node
):
100 if isinstance(node
, ast
.Module
) and len(node
.body
) == 1:
101 return cls
._fromast
(node
.body
[0])
102 elif isinstance(node
, ast
.Expr
):
103 return cls
._fromast
(node
.value
)
104 elif isinstance(node
, ast
.Name
):
105 return Symbol(node
.id)
106 elif isinstance(node
, ast
.Num
):
107 return Constant(node
.n
)
108 elif isinstance(node
, ast
.UnaryOp
) and isinstance(node
.op
, ast
.USub
):
109 return -cls
._fromast
(node
.operand
)
110 elif isinstance(node
, ast
.BinOp
):
111 left
= cls
._fromast
(node
.left
)
112 right
= cls
._fromast
(node
.right
)
113 if isinstance(node
.op
, ast
.Add
):
115 elif isinstance(node
.op
, ast
.Sub
):
117 elif isinstance(node
.op
, ast
.Mult
):
119 elif isinstance(node
.op
, ast
.Div
):
121 raise SyntaxError('invalid syntax')
124 def fromstring(cls
, string
):
125 string
= re
.sub(r
'(\d+|\))\s*([^\W\d_]\w*|\()', r
'\1*\2', string
)
126 tree
= ast
.parse(string
, 'eval')
127 return cls
._fromast
(tree
)
135 return self
._dimension
137 def coefficient(self
, symbol
):
138 if isinstance(symbol
, Symbol
):
140 elif not isinstance(symbol
, str):
141 raise TypeError('symbol must be a string or a Symbol instance')
143 return self
._coefficients
[symbol
]
147 __getitem__
= coefficient
149 def coefficients(self
):
150 for symbol
in self
.symbols
:
151 yield symbol
, self
.coefficient(symbol
)
155 return self
._constant
157 def isconstant(self
):
161 for symbol
in self
.symbols
:
162 yield self
.coefficient(symbol
)
178 def __add__(self
, other
):
179 coefficients
= dict(self
.coefficients())
180 for symbol
, coefficient
in other
.coefficients():
181 if symbol
in coefficients
:
182 coefficients
[symbol
] += coefficient
184 coefficients
[symbol
] = coefficient
185 constant
= self
.constant
+ other
.constant
186 return Expression(coefficients
, constant
)
191 def __sub__(self
, other
):
192 coefficients
= dict(self
.coefficients())
193 for symbol
, coefficient
in other
.coefficients():
194 if symbol
in coefficients
:
195 coefficients
[symbol
] -= coefficient
197 coefficients
[symbol
] = -coefficient
198 constant
= self
.constant
- other
.constant
199 return Expression(coefficients
, constant
)
201 def __rsub__(self
, other
):
202 return -(self
- other
)
205 def __mul__(self
, other
):
206 if other
.isconstant():
207 coefficients
= dict(self
.coefficients())
208 for symbol
in coefficients
:
209 coefficients
[symbol
] *= other
.constant
210 constant
= self
.constant
* other
.constant
211 return Expression(coefficients
, constant
)
212 if isinstance(other
, Expression
) and not self
.isconstant():
213 raise ValueError('non-linear expression: '
214 '{} * {}'.format(self
._parenstr
(), other
._parenstr
()))
215 return NotImplemented
220 def __truediv__(self
, other
):
221 if other
.isconstant():
222 coefficients
= dict(self
.coefficients())
223 for symbol
in coefficients
:
224 coefficients
[symbol
] = \
225 Fraction(coefficients
[symbol
], other
.constant
)
226 constant
= Fraction(self
.constant
, other
.constant
)
227 return Expression(coefficients
, constant
)
228 if isinstance(other
, Expression
):
229 raise ValueError('non-linear expression: '
230 '{} / {}'.format(self
._parenstr
(), other
._parenstr
()))
231 return NotImplemented
233 def __rtruediv__(self
, other
):
234 if isinstance(other
, self
):
235 if self
.isconstant():
236 constant
= Fraction(other
, self
.constant
)
237 return Expression(constant
=constant
)
239 raise ValueError('non-linear expression: '
240 '{} / {}'.format(other
._parenstr
(), self
._parenstr
()))
241 return NotImplemented
246 for symbol
in self
.symbols
:
247 coefficient
= self
.coefficient(symbol
)
252 string
+= ' + {}'.format(symbol
)
253 elif coefficient
== -1:
255 string
+= '-{}'.format(symbol
)
257 string
+= ' - {}'.format(symbol
)
260 string
+= '{}*{}'.format(coefficient
, symbol
)
261 elif coefficient
> 0:
262 string
+= ' + {}*{}'.format(coefficient
, symbol
)
264 assert coefficient
< 0
266 string
+= ' - {}*{}'.format(coefficient
, symbol
)
268 constant
= self
.constant
269 if constant
!= 0 and i
== 0:
270 string
+= '{}'.format(constant
)
272 string
+= ' + {}'.format(constant
)
275 string
+= ' - {}'.format(constant
)
280 def _parenstr(self
, always
=False):
282 if not always
and (self
.isconstant() or self
.issymbol()):
285 return '({})'.format(string
)
288 string
= '{}({{'.format(self
.__class
__.__name
__)
289 for i
, (symbol
, coefficient
) in enumerate(self
.coefficients()):
292 string
+= '{!r}: {!r}'.format(symbol
, coefficient
)
293 string
+= '}}, {!r})'.format(self
.constant
)
297 def __eq__(self
, other
):
299 # see http://docs.sympy.org/dev/tutorial/gotchas.html#equals-signs
300 return isinstance(other
, Expression
) and \
301 self
._coefficients
== other
._coefficients
and \
302 self
.constant
== other
.constant
305 return hash((tuple(sorted(self
._coefficients
.items())), self
._constant
))
308 lcm
= functools
.reduce(lambda a
, b
: a
*b
// gcd(a
, b
),
309 [value
.denominator
for value
in self
.values()])
313 def _eq(self
, other
):
314 return Polyhedron(equalities
=[(self
- other
)._toint
()])
317 def __le__(self
, other
):
318 return Polyhedron(inequalities
=[(other
- self
)._toint
()])
321 def __lt__(self
, other
):
322 return Polyhedron(inequalities
=[(other
- self
)._toint
() - 1])
325 def __ge__(self
, other
):
326 return Polyhedron(inequalities
=[(self
- other
)._toint
()])
329 def __gt__(self
, other
):
330 return Polyhedron(inequalities
=[(self
- other
)._toint
() - 1])
333 class Constant(Expression
):
335 def __new__(cls
, numerator
=0, denominator
=None):
336 self
= object().__new
__(cls
)
337 if denominator
is None:
338 if isinstance(numerator
, numbers
.Rational
):
339 self
._constant
= numerator
340 elif isinstance(numerator
, Constant
):
341 self
._constant
= numerator
.constant
343 raise TypeError('constant must be a rational number or a Constant instance')
345 self
._constant
= Fraction(numerator
, denominator
)
346 self
._coefficients
= {}
351 def isconstant(self
):
355 return bool(self
.constant
)
358 if self
.constant
.denominator
== 1:
359 return '{}({!r})'.format(self
.__class
__.__name
__, self
.constant
)
361 return '{}({!r}, {!r})'.format(self
.__class
__.__name
__,
362 self
.constant
.numerator
, self
.constant
.denominator
)
364 class Symbol(Expression
):
366 __slots__
= Expression
.__slots
__ + (
370 def __new__(cls
, name
):
371 if isinstance(name
, Symbol
):
373 elif not isinstance(name
, str):
374 raise TypeError('name must be a string or a Symbol instance')
375 self
= object().__new
__(cls
)
376 self
._coefficients
= {name
: 1}
378 self
._symbols
= tuple(name
)
391 return '{}({!r})'.format(self
.__class
__.__name
__, self
._name
)
394 if isinstance(names
, str):
395 names
= names
.replace(',', ' ').split()
396 return (Symbol(name
) for name
in names
)
399 @_polymorphic_operator
403 @_polymorphic_operator
407 @_polymorphic_operator
411 @_polymorphic_operator
415 @_polymorphic_operator
422 This class implements polyhedrons.
432 def __new__(cls
, equalities
=None, inequalities
=None):
433 if isinstance(equalities
, str):
434 if inequalities
is not None:
435 raise TypeError('too many arguments')
436 return cls
.fromstring(equalities
)
437 self
= super().__new
__(cls
)
438 self
._equalities
= []
439 if equalities
is not None:
440 for constraint
in equalities
:
441 for value
in constraint
.values():
442 if value
.denominator
!= 1:
443 raise TypeError('non-integer constraint: '
444 '{} == 0'.format(constraint
))
445 self
._equalities
.append(constraint
)
446 self
._equalities
= tuple(self
._equalities
)
447 self
._inequalities
= []
448 if inequalities
is not None:
449 for constraint
in inequalities
:
450 for value
in constraint
.values():
451 if value
.denominator
!= 1:
452 raise TypeError('non-integer constraint: '
453 '{} <= 0'.format(constraint
))
454 self
._inequalities
.append(constraint
)
455 self
._inequalities
= tuple(self
._inequalities
)
456 self
._constraints
= self
._equalities
+ self
._inequalities
457 self
._symbols
= set()
458 for constraint
in self
._constraints
:
459 self
.symbols
.update(constraint
.symbols
)
460 self
._symbols
= tuple(sorted(self
._symbols
))
464 def _fromast(cls
, node
):
465 if isinstance(node
, ast
.Module
) and len(node
.body
) == 1:
466 return cls
._fromast
(node
.body
[0])
467 elif isinstance(node
, ast
.Expr
):
468 return cls
._fromast
(node
.value
)
469 elif isinstance(node
, ast
.BinOp
) and isinstance(node
.op
, ast
.BitAnd
):
470 equalities1
, inequalities1
= cls
._fromast
(node
.left
)
471 equalities2
, inequalities2
= cls
._fromast
(node
.right
)
472 equalities
= equalities1
+ equalities2
473 inequalities
= inequalities1
+ inequalities2
474 return equalities
, inequalities
475 elif isinstance(node
, ast
.Compare
):
478 left
= Expression
._fromast
(node
.left
)
479 for i
in range(len(node
.ops
)):
481 right
= Expression
._fromast
(node
.comparators
[i
])
482 if isinstance(op
, ast
.Lt
):
483 inequalities
.append(right
- left
- 1)
484 elif isinstance(op
, ast
.LtE
):
485 inequalities
.append(right
- left
)
486 elif isinstance(op
, ast
.Eq
):
487 equalities
.append(left
- right
)
488 elif isinstance(op
, ast
.GtE
):
489 inequalities
.append(left
- right
)
490 elif isinstance(op
, ast
.Gt
):
491 inequalities
.append(left
- right
- 1)
496 return equalities
, inequalities
497 raise SyntaxError('invalid syntax')
500 def fromstring(cls
, string
):
501 string
= string
.strip()
502 string
= re
.sub(r
'^\{\s*|\s*\}$', '', string
)
503 string
= re
.sub(r
'([^<=>])=([^<=>])', r
'\1==\2', string
)
504 string
= re
.sub(r
'(\d+|\))\s*([^\W\d_]\w*|\()', r
'\1*\2', string
)
505 tokens
= re
.split(r
',|;|and|&&|/\\|∧', string
, flags
=re
.I
)
506 tokens
= ['({})'.format(token
) for token
in tokens
]
507 string
= ' & '.join(tokens
)
508 tree
= ast
.parse(string
, 'eval')
509 equalities
, inequalities
= cls
._fromast
(tree
)
510 return cls(equalities
, inequalities
)
513 def equalities(self
):
514 return self
._equalities
517 def inequalities(self
):
518 return self
._inequalities
521 def constraints(self
):
522 return self
._constraints
530 return len(self
.symbols
)
533 return not self
.is_empty()
535 def __contains__(self
, value
):
536 # is the value in the polyhedron?
537 raise NotImplementedError
539 def __eq__(self
, other
):
540 # works correctly when symbols is not passed
541 # should be equal if values are the same even if symbols are different
543 other
= other
._toisl
()
544 return bool(libisl
.isl_basic_set_plain_is_equal(bset
, other
))
548 return bool(libisl
.isl_basic_set_is_empty(bset
))
550 def isuniverse(self
):
552 return bool(libisl
.isl_basic_set_is_universe(bset
))
554 def isdisjoint(self
, other
):
555 # return true if the polyhedron has no elements in common with other
556 #symbols = self._symbolunion(other)
558 other
= other
._toisl
()
559 return bool(libisl
.isl_set_is_disjoint(bset
, other
))
561 def issubset(self
, other
):
562 # check if self(bset) is a subset of other
563 symbols
= self
._symbolunion
(other
)
564 bset
= self
._toisl
(symbols
)
565 other
= other
._toisl
(symbols
)
566 return bool(libisl
.isl_set_is_strict_subset(other
, bset
))
568 def __le__(self
, other
):
569 return self
.issubset(other
)
571 def __lt__(self
, other
):
572 symbols
= self
._symbolunion
(other
)
573 bset
= self
._toisl
(symbols
)
574 other
= other
._toisl
(symbols
)
575 return bool(libisl
.isl_set_is_strict_subset(other
, bset
))
577 def issuperset(self
, other
):
578 # test whether every element in other is in the polyhedron
579 raise NotImplementedError
581 def __ge__(self
, other
):
582 return self
.issuperset(other
)
584 def __gt__(self
, other
):
585 symbols
= self
._symbolunion
(other
)
586 bset
= self
._toisl
(symbols
)
587 other
= other
._toisl
(symbols
)
588 bool(libisl
.isl_set_is_strict_subset(other
, bset
))
589 raise NotImplementedError
591 def union(self
, *others
):
592 # return a new polyhedron with elements from the polyhedron and all
593 # others (convex union)
594 raise NotImplementedError
596 def __or__(self
, other
):
597 return self
.union(other
)
599 def intersection(self
, *others
):
600 # return a new polyhedron with elements common to the polyhedron and all
602 # a poor man's implementation could be:
603 # equalities = list(self.equalities)
604 # inequalities = list(self.inequalities)
605 # for other in others:
606 # equalities.extend(other.equalities)
607 # inequalities.extend(other.inequalities)
608 # return self.__class__(equalities, inequalities)
609 raise NotImplementedError
611 def __and__(self
, other
):
612 return self
.intersection(other
)
614 def difference(self
, other
):
615 # return a new polyhedron with elements in the polyhedron that are not in the other
616 symbols
= self
._symbolunion
(other
)
617 bset
= self
._toisl
(symbols
)
618 other
= other
._toisl
(symbols
)
619 difference
= libisl
.isl_set_subtract(bset
, other
)
622 def __sub__(self
, other
):
623 return self
.difference(other
)
627 for constraint
in self
.equalities
:
628 constraints
.append('{} == 0'.format(constraint
))
629 for constraint
in self
.inequalities
:
630 constraints
.append('{} >= 0'.format(constraint
))
631 return '{{{}}}'.format(', '.join(constraints
))
636 elif self
.isuniverse():
639 equalities
= list(self
.equalities
)
640 inequalities
= list(self
.inequalities
)
641 return '{}(equalities={!r}, inequalities={!r})' \
642 ''.format(self
.__class
__.__name
__, equalities
, inequalities
)
644 def _symbolunion(self
, *others
):
645 symbols
= set(self
.symbols
)
647 symbols
.update(other
.symbols
)
648 return sorted(symbols
)
650 def _toisl(self
, symbols
=None):
652 symbols
= self
.symbols
653 dimension
= len(symbols
)
654 space
= libisl
.isl_space_set_alloc(_main_ctx
, 0, dimension
)
655 bset
= libisl
.isl_basic_set_universe(libisl
.isl_space_copy(space
))
656 ls
= libisl
.isl_local_space_from_space(space
)
657 for equality
in self
.equalities
:
658 ceq
= libisl
.isl_equality_alloc(libisl
.isl_local_space_copy(ls
))
659 for symbol
, coefficient
in equality
.coefficients():
660 val
= str(coefficient
).encode()
661 val
= libisl
.isl_val_read_from_str(_main_ctx
, val
)
662 dim
= symbols
.index(symbol
)
663 ceq
= libisl
.isl_constraint_set_coefficient_val(ceq
, libisl
.isl_dim_set
, dim
, val
)
664 if equality
.constant
!= 0:
665 val
= str(equality
.constant
).encode()
666 val
= libisl
.isl_val_read_from_str(_main_ctx
, val
)
667 ceq
= libisl
.isl_constraint_set_constant_val(ceq
, val
)
668 bset
= libisl
.isl_basic_set_add_constraint(bset
, ceq
)
669 for inequality
in self
.inequalities
:
670 cin
= libisl
.isl_inequality_alloc(libisl
.isl_local_space_copy(ls
))
671 for symbol
, coefficient
in inequality
.coefficients():
672 val
= str(coefficient
).encode()
673 val
= libisl
.isl_val_read_from_str(_main_ctx
, val
)
674 dim
= symbols
.index(symbol
)
675 cin
= libisl
.isl_constraint_set_coefficient_val(cin
, libisl
.isl_dim_set
, dim
, val
)
676 if inequality
.constant
!= 0:
677 val
= str(inequality
.constant
).encode()
678 val
= libisl
.isl_val_read_from_str(_main_ctx
, val
)
679 cin
= libisl
.isl_constraint_set_constant_val(cin
, val
)
680 bset
= libisl
.isl_basic_set_add_constraint(bset
, cin
)
681 bset
= isl
.BasicSet(bset
)
685 def _fromisl(cls
, bset
, symbols
):
686 raise NotImplementedError
689 return cls(equalities
, inequalities
)
690 '''takes basic set in isl form and puts back into python version of polyhedron
691 isl example code gives isl form as:
692 "{[i] : exists (a : i = 2a and i >= 10 and i <= 42)}")
693 our printer is giving form as:
694 { [i0, i1] : 2i1 >= -2 - i0 } '''
698 Universe
= Polyhedron()
701 if __name__
== '__main__':
702 p1
= Polyhedron('2a + 2b + 1 == 0') # empty
704 p2
= Polyhedron('3x + 2y + 3 == 0') # not empty