c30fd136d18aac3ecd7a57c18cc8db4f7dee8152
5 from . import islhelper
7 from .islhelper
import mainctx
, libisl
8 from .geometry
import GeometricObject
9 from .coordinates
import Point
10 from .linexprs
import Expression
, Symbol
, Rational
11 from .domains
import Domain
16 'Lt', 'Le', 'Eq', 'Ne', 'Ge', 'Gt',
21 class Polyhedron(Domain
):
31 def __new__(cls
, equalities
=None, inequalities
=None):
32 if isinstance(equalities
, str):
33 if inequalities
is not None:
34 raise TypeError('too many arguments')
35 return cls
.fromstring(equalities
)
36 elif isinstance(equalities
, GeometricObject
):
37 if inequalities
is not None:
38 raise TypeError('too many arguments')
39 return equalities
.aspolyhedron()
40 if equalities
is None:
43 for i
, equality
in enumerate(equalities
):
44 if not isinstance(equality
, Expression
):
45 raise TypeError('equalities must be linear expressions')
46 equalities
[i
] = equality
.scaleint()
47 if inequalities
is None:
50 for i
, inequality
in enumerate(inequalities
):
51 if not isinstance(inequality
, Expression
):
52 raise TypeError('inequalities must be linear expressions')
53 inequalities
[i
] = inequality
.scaleint()
54 symbols
= cls
._xsymbols
(equalities
+ inequalities
)
55 islbset
= cls
._toislbasicset
(equalities
, inequalities
, symbols
)
56 return cls
._fromislbasicset
(islbset
, symbols
)
60 return self
._equalities
63 def inequalities(self
):
64 return self
._inequalities
67 def constraints(self
):
68 return self
._constraints
78 islbset
= self
._toislbasicset
(self
.equalities
, self
.inequalities
,
80 universe
= bool(libisl
.isl_basic_set_is_universe(islbset
))
81 libisl
.isl_basic_set_free(islbset
)
84 def aspolyhedron(self
):
87 def __contains__(self
, point
):
88 if not isinstance(point
, Point
):
89 raise TypeError('point must be a Point instance')
90 if self
.symbols
!= point
.symbols
:
91 raise ValueError('arguments must belong to the same space')
92 for equality
in self
.equalities
:
93 if equality
.subs(point
.coordinates()) != 0:
95 for inequality
in self
.inequalities
:
96 if inequality
.subs(point
.coordinates()) < 0:
100 def subs(self
, symbol
, expression
=None):
101 equalities
= [equality
.subs(symbol
, expression
)
102 for equality
in self
.equalities
]
103 inequalities
= [inequality
.subs(symbol
, expression
)
104 for inequality
in self
.inequalities
]
105 return Polyhedron(equalities
, inequalities
)
108 def _fromislbasicset(cls
, islbset
, symbols
):
109 islconstraints
= islhelper
.isl_basic_set_constraints(islbset
)
112 for islconstraint
in islconstraints
:
113 constant
= libisl
.isl_constraint_get_constant_val(islconstraint
)
114 constant
= islhelper
.isl_val_to_int(constant
)
116 for index
, symbol
in enumerate(symbols
):
117 coefficient
= libisl
.isl_constraint_get_coefficient_val(islconstraint
,
118 libisl
.isl_dim_set
, index
)
119 coefficient
= islhelper
.isl_val_to_int(coefficient
)
121 coefficients
[symbol
] = coefficient
122 expression
= Expression(coefficients
, constant
)
123 if libisl
.isl_constraint_is_equality(islconstraint
):
124 equalities
.append(expression
)
126 inequalities
.append(expression
)
127 libisl
.isl_basic_set_free(islbset
)
128 self
= object().__new
__(Polyhedron
)
129 self
._equalities
= tuple(equalities
)
130 self
._inequalities
= tuple(inequalities
)
131 self
._constraints
= tuple(equalities
+ inequalities
)
132 self
._symbols
= cls
._xsymbols
(self
._constraints
)
133 self
._dimension
= len(self
._symbols
)
137 def _toislbasicset(cls
, equalities
, inequalities
, symbols
):
138 dimension
= len(symbols
)
139 indices
= {symbol
: index
for index
, symbol
in enumerate(symbols
)}
140 islsp
= libisl
.isl_space_set_alloc(mainctx
, 0, dimension
)
141 islbset
= libisl
.isl_basic_set_universe(libisl
.isl_space_copy(islsp
))
142 islls
= libisl
.isl_local_space_from_space(islsp
)
143 for equality
in equalities
:
144 isleq
= libisl
.isl_equality_alloc(libisl
.isl_local_space_copy(islls
))
145 for symbol
, coefficient
in equality
.coefficients():
146 islval
= str(coefficient
).encode()
147 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
148 index
= indices
[symbol
]
149 isleq
= libisl
.isl_constraint_set_coefficient_val(isleq
,
150 libisl
.isl_dim_set
, index
, islval
)
151 if equality
.constant
!= 0:
152 islval
= str(equality
.constant
).encode()
153 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
154 isleq
= libisl
.isl_constraint_set_constant_val(isleq
, islval
)
155 islbset
= libisl
.isl_basic_set_add_constraint(islbset
, isleq
)
156 for inequality
in inequalities
:
157 islin
= libisl
.isl_inequality_alloc(libisl
.isl_local_space_copy(islls
))
158 for symbol
, coefficient
in inequality
.coefficients():
159 islval
= str(coefficient
).encode()
160 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
161 index
= indices
[symbol
]
162 islin
= libisl
.isl_constraint_set_coefficient_val(islin
,
163 libisl
.isl_dim_set
, index
, islval
)
164 if inequality
.constant
!= 0:
165 islval
= str(inequality
.constant
).encode()
166 islval
= libisl
.isl_val_read_from_str(mainctx
, islval
)
167 islin
= libisl
.isl_constraint_set_constant_val(islin
, islval
)
168 islbset
= libisl
.isl_basic_set_add_constraint(islbset
, islin
)
172 def fromstring(cls
, string
):
173 domain
= Domain
.fromstring(string
)
174 if not isinstance(domain
, Polyhedron
):
175 raise ValueError('non-polyhedral expression: {!r}'.format(string
))
181 elif self
.isuniverse():
185 for equality
in self
.equalities
:
186 strings
.append('0 == {}'.format(equality
))
187 for inequality
in self
.inequalities
:
188 strings
.append('0 <= {}'.format(inequality
))
189 if len(strings
) == 1:
192 return 'And({})'.format(', '.join(strings
))
195 def fromsympy(cls
, expr
):
196 domain
= Domain
.fromsympy(expr
)
197 if not isinstance(domain
, Polyhedron
):
198 raise ValueError('non-polyhedral expression: {!r}'.format(expr
))
204 for equality
in self
.equalities
:
205 constraints
.append(sympy
.Eq(equality
.tosympy(), 0))
206 for inequality
in self
.inequalities
:
207 constraints
.append(sympy
.Ge(inequality
.tosympy(), 0))
208 return sympy
.And(*constraints
)
211 def _sort_polygon_2d(cls
, points
):
214 o
= sum((Vector(point
) for point
in points
)) / len(points
)
215 o
= Point(o
.coordinates())
219 dx
, dy
= (coordinate
for symbol
, coordinates
in om
.coordinates())
220 angle
= math
.atan2(dy
, dx
)
222 return sorted(points
, key
=angles
.get
)
225 def _sort_polygon_3d(cls
, points
):
228 o
= sum((Vector(point
) for point
in points
)) / len(points
)
229 o
= Point(o
.coordinates())
234 u
= (oa
.cross(ob
)).asunit()
238 normprod
= norm_oa
* om
.norm()
239 cosinus
= oa
.dot(om
) / normprod
240 sinus
= u
.dot(oa
.cross(om
)) / normprod
241 angle
= math
.acos(cosinus
)
242 angle
= math
.copysign(angle
, sinus
)
244 return sorted(points
, key
=angles
.get
)
247 import matplotlib
.pyplot
as plt
248 from matplotlib
.path
import Path
249 import matplotlib
.patches
as patches
251 if len(self
.symbols
)> 3:
254 elif len(self
.symbols
) == 2:
255 verts
= self
.vertices()
257 codes
= [Path
.MOVETO
]
260 for sym
in sorted(vert
, key
=Symbol
.sortkey
):
262 pairs
= pairs
+ (num
,)
264 points
.append((0.0, 0.0))
267 codes
.append(Path
.LINETO
)
270 codes
.append(Path
.CLOSEPOLY
)
271 path
= Path(points
, codes
)
273 ax
= fig
.add_subplot(111)
274 patch
= patches
.PathPatch(path
, facecolor
='blue', lw
=2)
280 elif len(self
.symbols
)==3:
286 def _polymorphic(func
):
287 @functools.wraps(func
)
288 def wrapper(left
, right
):
289 if isinstance(left
, numbers
.Rational
):
290 left
= Rational(left
)
291 elif not isinstance(left
, Expression
):
292 raise TypeError('left must be a a rational number '
293 'or a linear expression')
294 if isinstance(right
, numbers
.Rational
):
295 right
= Rational(right
)
296 elif not isinstance(right
, Expression
):
297 raise TypeError('right must be a a rational number '
298 'or a linear expression')
299 return func(left
, right
)
304 return Polyhedron([], [right
- left
- 1])
308 return Polyhedron([], [right
- left
])
312 return Polyhedron([left
- right
], [])
316 return ~
Eq(left
, right
)
320 return Polyhedron([], [left
- right
- 1])
324 return Polyhedron([], [left
- right
])
329 Universe
= Polyhedron([])