-
Notifications
You must be signed in to change notification settings - Fork 17
/
polytope.py
executable file
·2271 lines (1988 loc) · 72.3 KB
/
polytope.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
#
# Copyright (c) 2011-2014 by California Institute of Technology
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the California Institute of Technology nor
# the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL CALTECH
# OR THE CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#
#
# Acknowledgement:
# The overall structure of this library and the functions in the list
# below are taken with permission from:
#
# M. Kvasnica, P. Grieder and M. Baotić,
# Multi-Parametric Toolbox (MPT),
# http://control.ee.ethz.ch/~mpt/
#
# mldivide
# region_diff
# extreme
# envelope
# is_convex
# bounding_box
# intersect2
# projection_interhull
# projection_exthull
#
r"""Computational geometry module for polytope computations.
For linear programming the fastest installed solver is selected.
To change this choice, see the module `polytope.solvers`.
The structure of this module is based on \cite{MPT04}.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
import warnings
import numpy as np
from polytope.solvers import lpsolve
from polytope.esp import esp
from polytope.quickhull import quickhull
logger = logging.getLogger(__name__)
try:
xrange
except NameError:
xrange = range
# Nicer numpy output
np.set_printoptions(precision=5, suppress=True)
# global default absolute tolerance,
# to enable changing it code w/o passing arguments,
# so that magic methods can still be used
ABS_TOL = 1e-7
# inline imports:
#
# import matplotlib as mpl
# from matplotlib import pyplot as plt
class Polytope(object):
"""Polytope class with following fields
- `A`: a numpy array for the hyperplane normals in hyperplane
representation of a polytope
- `b`: a numpy array for the hyperplane offsets in hyperplane
representation of a polytope
- `chebXc`: coordinates of chebyshev center (if calculated)
- `chebR`: chebyshev radius (if calculated)
- `bbox`: bounding box (if calculated)
- `minrep`: if polytope is in minimal representation (after
running reduce)
- `normalize`: if True (default), normalize given A and b arrays;
else, use A and b without modification.
- `dim`: dimension
- `volume`: volume, computed on first call
See Also
========
L{Region}
"""
def __init__(
self, A=np.array([]), b=np.array([]), minrep=False,
chebR=0, chebX=None, fulldim=None,
volume=None, vertices=None, normalize=True):
self.A = A.astype(float)
self.b = b.astype(float).flatten()
if A.size > 0 and normalize:
# Normalize
Anorm = np.sqrt(np.sum(A * A, 1)).flatten()
pos = np.nonzero(Anorm > 1e-10)[0]
self.A = self.A[pos, :]
self.b = self.b[pos]
Anorm = Anorm[pos]
mult = 1 / Anorm
for i in xrange(self.A.shape[0]):
self.A[i, :] = self.A[i, :] * mult[i]
self.b = self.b.flatten() * mult
self.minrep = minrep
self._chebXc = chebX
self._chebR = chebR
self.bbox = None
self.fulldim = fulldim
self._volume = volume
self.vertices = vertices
def __str__(self):
"""Return pretty-formatted H-representation of polytope."""
A, b = self.A, self.b
A_rows = str(A).split('\n')
n_rows = len(A_rows)
# column vector from `b`, if not already one
b_col = b.reshape(b.shape[0], 1) if len(b.shape) == 1 else b
b_rows = str(b_col).split('\n')
# place an "x" somewhere near the middle
x_row = int((n_rows - 1) / 2) # where "x" is shown
above = x_row
below = (n_rows - x_row - 2)
spacer = ' | '
last_middle = [spacer[1:]] if n_rows > 1 else []
middle = (
above * [spacer]
+ [' x <= ']
+ below * [spacer]
+ last_middle)
assert len(middle) == n_rows, (middle, n_rows)
# format lines
lines = [A_rows[k] + middle[k] + b_rows[k]
for k in range(n_rows)]
output = 'Single polytope \n {lines}\n'.format(
lines='\n '.join(lines))
return output
def __len__(self):
return 0
def __copy__(self):
A = self.A.copy()
b = self.b.copy()
P = Polytope(A, b)
P._chebXc = self._chebXc
P._chebR = self._chebR
P.minrep = self.minrep
P.bbox = self.bbox
P.fulldim = self.fulldim
return P
def __contains__(self, point):
"""Return `True` if `self` contains `point`.
Boundary points are included.
@param point: column vector, e.g., as `numpy.ndarray`
@rtype: bool
For multiple points, see the method `self.contains`.
"""
if not isinstance(point, np.ndarray):
point = np.array(point)
test = self.A.dot(point.flatten()) - self.b < ABS_TOL
return np.all(test)
def contains(self, points, abs_tol=ABS_TOL):
"""Return Boolean array of whether each point in `self`.
Any point that satisfies all inequalities is
contained in `self`. A tolerance is added, and
strict inequality checked (<). Pass `abs_tol=0`
to exclude the boundary.
@param points: column vectors
@rtype: bool, 1d array
"""
test = self.A.dot(points) - self.b[:, np.newaxis] < abs_tol
return np.all(test, axis=0)
def __eq__(self, other):
return self <= other and other <= self
def __ne__(self, other):
return not self == other
def __le__(self, other):
return is_subset(self, other)
def __ge__(self, other):
return is_subset(other, self)
def __bool__(self):
return bool(self.volume > 0)
__nonzero__ = __bool__
def union(self, other, check_convex=False):
"""Return union with Polytope or Region.
For usage see function union.
@type other: L{Polytope} or L{Region}
@rtype: L{Region}
"""
return union(self, other, check_convex)
def diff(self, other):
"""Return set difference with Polytope or Region.
@type other: L{Polytope} or L{Region}
@rtype: L{Region}
"""
return mldivide(self, other)
def intersect(self, other, abs_tol=ABS_TOL):
"""Return intersection with Polytope or Region.
@type other: L{Polytope}.
@rtype: L{Polytope} or L{Region}
"""
if isinstance(other, Region):
return other.intersect(self)
if not isinstance(other, Polytope):
msg = 'Polytope intersection defined only'
msg += ' with other Polytope. Got instead: '
msg += str(type(other))
raise Exception(msg)
if (not is_fulldim(self)) or (not is_fulldim(other)):
return Polytope()
if self.dim != other.dim:
raise Exception("polytopes have different dimension")
iA = np.vstack([self.A, other.A])
ib = np.hstack([self.b, other.b])
return reduce(Polytope(iA, ib), abs_tol=abs_tol)
def translation(self, d):
"""Returns a copy of C{self} translated by the vector C{d}.
Consult L{polytope.polytope._translate} for implementation details.
@type d: 1d array
"""
newpoly = self.copy()
_translate(newpoly, d)
return newpoly
def rotation(self, i=None, j=None, theta=None):
"""Returns a rotated copy of C{self}.
Describe the plane of rotation and the angle of rotation (in radians)
with i, j, and theta.
i and j are the indices 0..N-1 of two of the identity basis
vectors, and theta is the angle of rotation.
Consult L{polytope.polytope._rotate} for more detail.
@type i: int
@type j: int
@type theta: number
"""
newpoly = self.copy()
_rotate(newpoly, i=i, j=j, theta=theta)
return newpoly
def copy(self):
"""Return copy of this Polytope."""
return self.__copy__()
@classmethod
def from_box(cls, intervals=[]):
"""Class method for easy construction of hyperrectangles.
@param intervals: intervals [xi_min, xi_max],
the cross-product of which defines the polytope
as an N-dimensional hyperrectangle
@type intervals: [ndim x 2] numpy array or
list of lists::
[[x0_min, x0_max],
[x1_min, x1_max],
...
[xN_min, xN_max]]
@return: hyperrectangle defined by C{intervals}
@rtype: L{Polytope}
"""
if not isinstance(intervals, np.ndarray):
try:
intervals = np.array(intervals)
except Exception:
raise Exception('Polytope.from_box:' +
'intervals must be a numpy ndarray or ' +
'convertible as arg to numpy.array')
if intervals.ndim != 2:
raise Exception('Polytope.from_box: ' +
'intervals must be 2 dimensional')
n = intervals.shape
if n[1] != 2:
raise Exception('Polytope.from_box: ' +
'intervals must have 2 columns')
n = n[0]
# a <= b for each interval ?
if (intervals[:, 0] > intervals[:, 1]).any():
msg = 'Polytope.from_box: '
msg += 'Invalid interval in from_box method.\n'
msg += 'First element of an interval must'
msg += ' not be larger than the second.'
raise Exception(msg)
A = np.vstack([np.eye(n), -np.eye(n)])
b = np.hstack([intervals[:, 1], -intervals[:, 0]])
return cls(A, b, minrep=True)
def project(self, dim, solver=None,
abs_tol=ABS_TOL, verbose=0):
"""Return Polytope projection on selected subspace.
For usage details see function: L{projection}.
"""
return projection(self, dim, solver, abs_tol, verbose)
def scale(self, factor):
"""Multiply polytope by scalar factor.
A x <= b, becomes: A x <= (factor * b)
@type factor: float
"""
self.b = factor * self.b
@property
def dim(self):
"""Return Polytope dimension."""
try:
return np.shape(self.A)[1]
except Exception:
return 0.0
@property
def volume(self):
if self._volume is None:
self._volume = volume(self)
return self._volume
@property
def chebR(self):
r, xc = cheby_ball(self)
return self._chebR
@property
def chebXc(self):
r, xc = cheby_ball(self)
return self._chebXc
@property
def cheby(self):
return cheby_ball(self)
@property
def bounding_box(self):
"""Wrapper of L{polytope.bounding_box}.
Computes the bounding box on first call.
"""
if self.bbox is None:
self.bbox = bounding_box(self)
return self.bbox
def plot(self, ax=None, color=None, hatch=None, alpha=1.0, linestyle=None, linewidth=None, edgecolor=None):
if self.dim != 2:
raise Exception("Cannot plot polytopes of dimension larger than 2")
# Setting default values for plotting
linestyle = linestyle or "dashed"
linewidth = linewidth or 3
edgecolor = edgecolor or "black"
ax = _newax(ax)
if not is_fulldim(self):
logger.error("Cannot plot empty polytope")
return None
if color is None:
color = np.random.rand(3)
poly = _get_patch(
self, facecolor=color, hatch=hatch,
alpha=alpha, linestyle=linestyle, linewidth=linewidth,
edgecolor=edgecolor)
ax.add_patch(poly)
return ax
def text(self, txt, ax=None, color='black'):
"""Plot text at chebyshev center."""
_plot_text(self, txt, ax, color)
def _translate(polyreg, d):
"""Translate C{polyreg} by the vector C{d}. Modifies C{polyreg} in-place.
@type d: 1d array
"""
if isinstance(polyreg, Polytope):
# Translate hyperplanes
polyreg.b = polyreg.b + np.dot(polyreg.A, d)
else:
# Translate subregions
for poly in polyreg.list_poly:
_translate(poly, d)
# Translate bbox and cheby
if polyreg.bbox is not None:
polyreg.bbox = (polyreg.bbox[0] + d,
polyreg.bbox[1] + d)
if polyreg._chebXc is not None:
polyreg._chebXc = polyreg._chebXc + d
def _rotate(polyreg, i=None, j=None, u=None, v=None, theta=None, R=None):
"""Rotate C{polyreg} in-place. Return the rotation matrix.
There are two types of rotation: simple and compound. For simple rotations,
by definition, all motion can be projected as circles in a single plane;
the other N - 2 dimensions are invariant. Therefore any simple rotation can
be parameterized by its plane of rotation. Compound rotations are the
combination of multiple simple rotations; they have more than one plane of
rotation. For N > 3 dimensions, a compound rotation may be necessary to map
one orientation to another (Euler's rotation theorem no longer applies).
Use one of the following three methods to specify rotation. The first two
can only express simple rotation, but simple rotations may be applied in a
sequence to achieve a compound rotation.
(1) Provide the indices 0..N-1 of the identity basis vectors, i and j,
which define the plane of rotation and a radian angle of rotation, theta,
between them. This method contructs the Givens rotation matrix. The right
hand rule defines the positive rotation direction.
(2) Provide two vectors, the two vectors define the plane of rotation
and angle of rotation is TWICE the angle from the first vector, u, to
the second vector, v.
(3) Provide an N-by-N rotation matrix, R. WARNING: No checks are made to
determine whether the provided transformation matrix is a valid rotation.
Further Reading
https://en.wikipedia.org/wiki/Plane_of_rotation
@param polyreg: The polytope or region to be rotated.
@type polyreg: L{Polytope} or L{Region}
@param i: The first index describing the plane of rotation.
@type i: int
@param j: The second index describing the plane of rotation.
@type j: int
@param u: The first vector describing the plane of rotation.
@type u: 1d array
@param u: The second vector describing the plane of rotation.
@type v: 1d array.
@param theta: The radian angle to rotate the polyreg in the plane defined
by i and j.
@type theta: number
@param R: A predefined rotation matrix.
@type R: 2d array
"""
# determine the rotation matrix based on inputs
if R is not None:
logger.debug("rotate: R=\n{}".format(R))
assert i is None, i
assert j is None, j
assert theta is None, theta
assert u is None, u
assert v is None, v
elif i is not None and j is not None and theta is not None:
logger.info("rotate via indices and angle.")
assert R is None, R
assert u is None, u
assert v is None, v
if i == j:
raise ValueError("Must provide two unique basis vectors.")
R = givens_rotation_matrix(i, j, theta, polyreg.dim)
elif u is not None and v is not None:
logger.info("rotate via 2 vectors.")
assert R is None, R
assert i is None, i
assert j is None, j
assert theta is None, theta
R = solve_rotation_ap(u, v)
else:
raise ValueError("R or (i and j and theta) or (u and v) "
"must be defined.")
if isinstance(polyreg, Polytope):
# Ensure that half space is normalized before rotation
n, p = _hessian_normal(polyreg.A, polyreg.b)
# Rotate the hyperplane normals
polyreg.A = np.inner(n, R)
polyreg.b = p
else:
# Rotate subregions
for poly in polyreg.list_poly:
_rotate(poly, None, None, R=R)
# transform bbox and cheby
if polyreg.bbox is not None:
polyreg.bbox = (np.inner(polyreg.bbox[0].T, R).T,
np.inner(polyreg.bbox[1].T, R).T)
if polyreg._chebXc is not None:
polyreg._chebXc = np.inner(polyreg._chebXc, R)
return R
def givens_rotation_matrix(i, j, theta, N):
"""Return the Givens rotation matrix for an N-dimensional space."""
R = np.identity(N)
c = np.cos(theta)
s = np.sin(theta)
R[i, i] = c
R[j, j] = c
R[i, j] = -s
R[j, i] = s
return R
def solve_rotation_ap(u, v):
r"""Return the rotation matrix for the rotation in the plane defined by the
vectors u and v across TWICE the angle between u and v.
This algorithm uses the Aguilera-Perez Algorithm \cite{Aguilera}
to generate the rotation matrix. The algorithm works basically as follows:
Starting with the Nth component of u, rotate u towards the (N-1)th
component until the Nth component is zero. Continue until u is parallel to
the 0th basis vector. Next do the same with v until it only has none zero
components in the first two dimensions. The result will be something like
this:
[[u0, 0, 0 ... 0],
[v0, v1, 0 ... 0]]
Now it is trivial to align u with v. Apply the inverse rotations to return
to the original orientation.
NOTE: The precision of this method is limited by sin, cos, and arctan
functions.
"""
# TODO: Assert vectors are non-zero and non-parallel aka exterior
# product is non-zero
N = u.size # the number of dimensions
uv = np.stack([u, v], axis=1) # the plane of rotation
M = np.identity(N) # stores the rotations for rorienting reference frame
# ensure u has positive basis0 component
if uv[0, 0] < 0:
M[0, 0] = -1
M[1, 1] = -1
uv = M.dot(uv)
# align uv plane with the basis01 plane and u with basis0.
for c in range(0, 2):
for r in range(N - 1, c, -1):
if uv[r, c] != 0: # skip rotations when theta will be zero
theta = np.arctan2(uv[r, c], uv[r - 1, c])
Mk = givens_rotation_matrix(r, r - 1, theta, N)
uv = Mk.dot(uv)
M = Mk.dot(M)
# rotate u onto v
theta = 2 * np.arctan2(uv[1, 1], uv[0, 1])
logger.debug(
"solve_rotation_ap: {d} degree rotation".format(
d=180 * theta / np.pi))
R = givens_rotation_matrix(0, 1, theta, N)
# perform M rotations in reverse order
M_inverse = M.T
R = M_inverse.dot(R.dot(M))
return R
def _hessian_normal(A, b):
"""Normalize half space representation according to hessian normal form."""
L2 = np.reshape(np.linalg.norm(A, axis=1), (-1, 1)) # needs to be column
if any(L2 == 0):
raise ValueError('One of the rows of A is a zero vector.')
n = A / L2 # hyperplane normals
p = b / L2.flatten() # hyperplane distances from origin
return n, p
class Region(object):
"""Class for lists of convex polytopes
Contains the following fields:
- `list_poly`: list of Polytope objects
- `props`: set of propositions inside region
- `bbox`: if calculated, bounding box of region (see bounding_box)
- `fulldim`: if calculated, boolean indicating whether region is
fully dimensional
- `dim`: dimension
- `volume`: volume of region, calculated on first call
- `chebXc`: coordinates of maximum chebyshev center (if calculated)
- `chebR`: maximum chebyshev radius (if calculated)
See Also
========
L{Polytope}
"""
def __init__(self, list_poly=None, props=None):
if list_poly is None:
list_poly = []
if props is None:
props = set()
if isinstance(list_poly, str):
# Hack to be able to use the Region class also for discrete
# problems.
self.list_poly = list_poly
self.props = set(props)
else:
if isinstance(list_poly, Region):
dim = list_poly[0].dim
for poly in list_poly:
if poly.dim != dim:
raise Exception("Region error:"
" Polytopes must be of same dimension!")
self.list_poly = list_poly[:]
for poly in list_poly:
if is_empty(poly):
self.list_poly.remove(poly)
self.props = set(props)
self.bbox = None
self.fulldim = None
self._volume = None
self._chebXc = None
self._chebR = None
def __iter__(self):
return iter(self.list_poly)
def __getitem__(self, key):
return self.list_poly[key]
def __str__(self):
output = ''
for i in xrange(len(self.list_poly)):
output += '\t Polytope number ' + str(i + 1) + ':\n'
poly_str = str(self.list_poly[i])
poly_str = poly_str.replace('\n', '\n\t\t')
output += '\t ' + poly_str + '\n'
output += '\n'
return output
def __len__(self):
return len(self.list_poly)
def __contains__(self, point):
"""Return `True` if `self` contains `point`.
See `Polytope.__contains__`.
"""
if not isinstance(point, np.ndarray):
point = np.array(point)
return any(point in u for u in self.list_poly)
def contains(self, points, abs_tol=ABS_TOL):
"""Return Boolean array of whether each point in `self`.
See `Polytope.contains`.
"""
if not isinstance(points, np.ndarray):
points = np.array(points)
assert points.shape[0] == self.dim, 'points should be column vectors'
contained = np.full(points.shape[1], False, dtype=bool)
for poly in self.list_poly:
contained = np.logical_or(
poly.contains(points, abs_tol),
contained)
return contained
def __eq__(self, other):
return self <= other and other <= self
def __ne__(self, other):
return not self == other
def __le__(self, other):
return is_subset(self, other)
def __ge__(self, other):
return is_subset(other, self)
def __add__(self, other):
"""Return union with Polytope or Region.
Applies convex simplification if possible.
To turn off this check,
use Region.union
@type other: L{Polytope} or L{Region}
@rtype: L{Region}
"""
return union(self, other, check_convex=True)
def __bool__(self):
return bool(self.volume > 0)
__nonzero__ = __bool__
def union(self, other, check_convex=False):
"""Return union with Polytope or Region.
For usage see function union.
@type other: L{Polytope} or L{Region}
@rtype: L{Region}
"""
return union(self, other, check_convex)
def __sub__(self, other):
"""Return set difference with Polytope or Region.
@type other: L{Polytope} or L{Region}
@rtype: L{Region}
"""
return mldivide(self, other)
def diff(self, other):
"""Return set difference with Polytope or Region.
@type other: L{Polytope} or L{Region}
@rtype: L{Region}
"""
return mldivide(self, other)
def __and__(self, other):
"""Return intersection with Polytope or Region.
Absolute tolerance 1e-7 used.
To select the absolute tolerance use
method Region.intersect
@type other: L{Polytope} or L{Region}
@rtype: L{Polytope} or L{Region}
"""
return intersect(self, other)
def intersect(self, other, abs_tol=ABS_TOL):
"""Return intersection with Polytope or Region.
@type other: iterable container of L{Polytope}.
@rtype: L{Region}
"""
if isinstance(other, Polytope):
other = [other]
P = Region()
for poly0 in self:
for poly1 in other:
isect = poly0.intersect(poly1, abs_tol)
rp, xp = isect.cheby
if rp > abs_tol:
P = union(P, isect, check_convex=True)
return P
def rotation(self, i=None, j=None, theta=None):
"""Returns a rotated copy of C{self}.
Describe the plane of rotation and the angle of rotation (in radians)
with i, j, and theta.
i and j are the indices 0..N-1 of two of the identity basis
vectors, and theta is the angle of rotation.
Consult L{polytope.polytope._rotate} for more detail.
@type i: int
@type j: int
@type theta: number
"""
newreg = self.copy()
_rotate(newreg, i=i, j=j, theta=theta)
return newreg
def translation(self, d):
"""Returns a copy of C{self} translated by the vector C{d}.
Consult L{polytope.polytope._translate} for implementation details.
@type d: 1d array
"""
newreg = self.copy()
_translate(newreg, d)
return newreg
def __copy__(self):
"""Return copy of this Region."""
return Region(list_poly=self.list_poly[:],
props=self.props.copy())
def copy(self):
"""Return copy of this Region."""
return self.__copy__()
@property
def dim(self):
"""Return Region dimension."""
return np.shape(self.list_poly[0].A)[1]
@property
def volume(self):
if self._volume is None:
self._volume = volume(self)
return self._volume
@property
def chebR(self):
r, xc = cheby_ball(self)
return self._chebR
@property
def chebXc(self):
r, xc = cheby_ball(self)
return self._chebXc
@property
def cheby(self):
return cheby_ball(self)
@property
def bounding_box(self):
"""Wrapper of polytope.bounding_box.
Computes the bounding box on first call.
"""
if self.bbox is None:
self.bbox = bounding_box(self)
return self.bbox
def plot(self, ax=None, color=None, hatch=None, alpha=1.0, linestyle=None, linewidth=None, edgecolor=None):
"""Plot a `polytope` on axes `ax`."""
# TODO optional arg for text label
if self.dim != 2:
raise Exception("Cannot plot region of dimension larger than 2")
if not is_fulldim(self):
logger.error("Cannot plot empty region")
return None
ax = _newax(ax)
if color is None:
color = np.random.rand(3)
for poly2 in self.list_poly:
# TODO hatched polytopes in same region
poly2.plot(ax, color=color, hatch=hatch, alpha=alpha, linestyle=linestyle, linewidth=linewidth,
edgecolor=edgecolor)
return ax
def text(self, txt, ax=None, color='black'):
"""Plot text at chebyshev center."""
_plot_text(self, txt, ax, color)
def is_empty(polyreg):
"""Check if the description of a polytope is empty
@param polyreg: L{Polytope} or L{Region} instance
@return: Boolean indicating whether polyreg is empty
"""
n = len(polyreg)
if len(polyreg) == 0:
try:
return len(polyreg.A) == 0
except Exception:
return True
else:
N = np.zeros(n, dtype=int)
for i in xrange(n):
N[i] = is_empty(polyreg.list_poly[i])
if np.all(N):
return True
else:
return False
def is_fulldim(polyreg, abs_tol=ABS_TOL):
"""Check if a polytope or region has inner points.
@param polyreg: L{Polytope} or L{Region} instance
@return: Boolean that is True if inner points found, False
otherwise.
"""
# logger.debug('is_fulldim')
if polyreg.fulldim is not None:
return polyreg.fulldim
lenP = len(polyreg)
if lenP == 0:
rc, xc = cheby_ball(polyreg)
status = rc > abs_tol
else:
status = np.zeros(lenP)
for ii in xrange(lenP):
rc, xc = cheby_ball(polyreg.list_poly[ii])
status[ii] = rc > abs_tol
status = np.sum(status)
status = status > 0
polyreg.fulldim = status
return status
def is_convex(reg, abs_tol=ABS_TOL):
"""Check if a region is convex.
@type reg: L{Region}
@return: result,envelope: result indicating if convex. if found to
be convex the envelope describing the convex polytope is
returned.
"""
if not is_fulldim(reg):
return True
if len(reg) == 0:
return True
outer = envelope(reg)
if is_empty(outer):
# Probably because input polytopes were so small and ugly..
return False, None
Pl, Pu = reg.bounding_box
Ol, Ou = outer.bounding_box
bboxP = np.hstack([Pl, Pu])
bboxO = np.hstack([Ol, Ou])
if (
sum(abs(bboxP[:, 0] - bboxO[:, 0]) > abs_tol) > 0 or
sum(abs(bboxP[:, 1] - bboxO[:, 1]) > abs_tol) > 0):
return False, None
if is_fulldim(outer.diff(reg)):
return False, None
else:
return True, outer
def is_inside(polyreg, point, abs_tol=ABS_TOL):
"""Return `point in polyreg`.
@type point: `collections.abc.Sequence` or `numpy.ndarray`
@rtype: bool
"""
warnings.warn(
'Write `point in polyreg` instead of '
'calling this function.',
DeprecationWarning)
if not isinstance(point, np.ndarray):
point = np.array(point)
return polyreg.contains(point[:, np.newaxis], abs_tol)[0]
def is_subset(small, big, abs_tol=ABS_TOL):
"""Return True if small \subseteq big.
@type small: L{Polytope} or L{Region}
@type big: L{Polytope} or L{Region}
@rtype: bool
"""
for x in [small, big]:
if not isinstance(x, (Polytope, Region)):
msg = 'Not a Polytope or Region, got instead:\n\t'
msg += str(type(x))
raise TypeError(msg)
diff = small.diff(big)
volume = diff.volume
if volume < abs_tol:
return True
else:
return False