-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathreactive_planner_lib.py
executable file
·1806 lines (1475 loc) · 108 KB
/
reactive_planner_lib.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
#!/usr/bin/env python
"""
MIT License (modified)
Copyright (c) 2020 The Trustees of the University of Pennsylvania
Authors:
Vasileios Vasilopoulos <[email protected]>
Omur Arslan <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this **file** (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import time
import itertools
import shapely as sp
from matplotlib.collections import PatchCollection
from shapely.geometry import Polygon, Point, LineString, LinearRing
from shapely.ops import cascaded_union
from scipy.spatial import ConvexHull
from scipy.signal import butter, lfilter
from operator import itemgetter
# Geometry imports
from polygeom_lib import cvxpolyxhplane, cvxpolyerode, polydist, polyxline, inpolygon, cvxpolyintersect, polyxray
from polygeom_lib import polytriangulation, polycvxdecomp, polyconvexdecomposition
class LIDARClass:
"""
Class that describes a LIDAR object and is updated as new measurements are received
Properties:
1) RangeMeasurements: Range measurements received
2) Range: Range of the sensor
3) Infinity: Range to be considered as infinity
4) MinAngle: Minimum angle of the sensor
5) MaxAngle: Maximum angle of the sensor
6) Resolution: Sensor angular resolution
"""
def __init__(self, RangeMeasurements, Range, Infinity, MinAngle, MaxAngle, Resolution):
self.RangeMeasurements = RangeMeasurements # 1D numpy array
self.Range = Range # float
self.Infinity = Infinity # float
self.MinAngle = MinAngle # float
self.MaxAngle = MaxAngle # float
self.Resolution = Resolution # float
self.NumSample = int(1+round((MaxAngle-MinAngle)/Resolution)) # integer
self.Angle = np.linspace(MinAngle, MaxAngle, self.NumSample) # 1D numpy array
def completeLIDAR2D(LIDAR):
"""
Function that completes missing LIDAR data due to limited field of view
Input:
1) LIDAR: Incomplete LIDAR object
Output:
1) LIDAR: Complete modified LIDAR object
"""
if ((LIDAR.MaxAngle-LIDAR.MinAngle) < 2*np.pi):
tempR = LIDAR.RangeMeasurements
tempAngle = LIDAR.Angle
tempResolution = LIDAR.Resolution
# Updated LIDAR model
LIDAR.MaxAngle = LIDAR.MinAngle + 2*np.pi
LIDAR.NumSample = int(round((2*np.pi/tempResolution)+1))
LIDAR.Resolution = (LIDAR.MaxAngle-LIDAR.MinAngle)/(LIDAR.NumSample-1)
LIDAR.Angle = np.linspace(LIDAR.MinAngle, LIDAR.MaxAngle, LIDAR.NumSample)
# Completed Range Data
R = LIDAR.Infinity*np.ones(LIDAR.NumSample)
Indices = np.floor(((tempAngle-LIDAR.MinAngle+LIDAR.Resolution/2)%(2*np.pi))/LIDAR.Resolution)
Indices = Indices.astype(int)
R[Indices] = tempR
R[R>LIDAR.Range] = LIDAR.Range
LIDAR.RangeMeasurements = R
return LIDAR
def constructLIDAR2D(DataLIDAR, CutoffRange, AllowableRange, Pitch=0.):
"""
Function that constructs a LIDAR object to be used by the reactive planner
Input:
1) DataLIDAR: Received LIDAR data
2) CutoffRange: Cutoff range below which the range measurement is ignored
3) AllowableRange: Maximum allowable LIDAR range
4) Pitch: Robot pitch to be considered for range compensation (default is 0)
Output:
1) LIDAR: Constructed LIDAR object
"""
# LIDAR operations
Range = AllowableRange
Infinity = AllowableRange+10.
MinAngle = float(DataLIDAR.angle_min)
MaxAngle = float(DataLIDAR.angle_max)
Resolution = float(DataLIDAR.angle_increment)
RangeMeasurements = np.array(DataLIDAR.ranges)
# Project on the robot plane
RangeMeasurements = RangeMeasurements*np.cos(Pitch)
# Reject NaN
Inan = np.nonzero(np.isnan(RangeMeasurements))
Inan = Inan[0]
for k in Inan:
RangeMeasurements[k] = Infinity
# Cutoff LIDAR range
Icutoff = np.nonzero(RangeMeasurements <= CutoffRange)
for k in Icutoff:
RangeMeasurements[k] = Infinity
# Construct LIDAR object
LIDAR = LIDARClass(RangeMeasurements, Range, Infinity, MinAngle, MaxAngle, Resolution)
return LIDAR
def obstaclePointsLIDAR2D(RobotState, LIDAR):
"""
Function that returns the coordinates of observed obstacle points from the LIDAR
Input:
1) RobotState: Robot position and orientation
2) LIDAR: Current LIDAR object
Output:
1) PointsAll: Coordinates of the observed obstacle points from the LIDAR - Nx2 numpy.array
"""
# Find robot position and orientation
RobotPosition = RobotState[0:2]
RobotOrientation = RobotState[2]
# Range measurements
R = np.array(LIDAR.RangeMeasurements)
# Find observed LIDAR points coordinates
PointsAll = np.zeros((R.shape[0], 2))
for i in range(PointsAll.shape[0]):
PointsAll[i][0] = RobotPosition[0]+R[i]*np.cos(LIDAR.Angle[i]+RobotOrientation)
PointsAll[i][1] = RobotPosition[1]+R[i]*np.sin(LIDAR.Angle[i]+RobotOrientation)
return PointsAll
def compensateObstacleLIDAR2D(RobotState, Obstacle, LIDAR):
"""
Function that checks if the LIDAR hits a specific obstacle whose polygon is known
Input:
1) RobotState: Robot position and orientation
2) Obstacle: shapely.geometry.Polygon obstacle defining the polygonal obstacle
3) LIDAR: Current LIDAR object
Output:
1) LIDAR: Final LIDAR object
"""
# Find robot position and orientation
RobotPosition = RobotState[0:2]
RobotOrientation = RobotState[2]
# Find the indices that correspond to a LIDAR range less than the maximum range
lidar_indices = np.where(LIDAR.RangeMeasurements < LIDAR.Range)
for k in lidar_indices[0]:
lidar_point_x = RobotPosition[0]+LIDAR.RangeMeasurements[k]*np.cos(LIDAR.Angle[k]+RobotOrientation)
lidar_point_y = RobotPosition[1]+LIDAR.RangeMeasurements[k]*np.sin(LIDAR.Angle[k]+RobotOrientation)
if Obstacle.contains(Point(lidar_point_x, lidar_point_y)):
LIDAR.RangeMeasurements[k] = LIDAR.Range
return LIDAR
def readLIDAR2D(RobotState,Obstacles,Range,MinAngle,MaxAngle,NumSample):
"""
Function that generates a virtual LIDAR object, based on the position of the robot and the surrounding obstacles
Input:
1) RobotState: Robot position and orientation
2) Obstacles: shapely.geometry.Polygon obstacle array defining the polygonal obstacles
3) Range: Range of the LIDAR object to be generated
4) MinAngle: Minimum angle of the LIDAR object to be generated
5) MaxAngle: Maximum angle of the LIDAR object to be generated
6) NumSample: Number of samples used in the process
Output:
1) virtualLIDAR: Complete virtual LIDAR object
"""
# Find robot position and orientation
RobotPosition = RobotState[0:2]
RobotOrientation = RobotState[2]
# Initialize LIDAR object
Resolution = (MaxAngle-MinAngle)/(NumSample-1)
RangeMeasurements = np.zeros(NumSample)
Infinity = Range + 20.0
virtualLIDAR = LIDARClass(RangeMeasurements, Range, Infinity, MinAngle, MaxAngle, Resolution)
# Rotation matrix from the global frame to the local sensor frame
RotMat = np.array([[np.cos(-RobotOrientation),-np.sin(-RobotOrientation)],[np.sin(-RobotOrientation),np.cos(-RobotOrientation)]])
# Determine distance to the workspace boundary and obstacles
virtualLIDAR.RangeMeasurements = virtualLIDAR.Infinity*np.ones(virtualLIDAR.NumSample)
for co in range(len(Obstacles)):
# Obstacle in the local sensor frame
Obs = np.vstack((Obstacles[co].exterior.coords.xy[0],Obstacles[co].exterior.coords.xy[1])).transpose() - RobotPosition
Obs = np.matmul(Obs,RotMat.transpose())
# Compute distance to every obstacle edge
for cv in range(Obs.shape[0]):
cn = ((cv+1)%Obs.shape[0])
vc = Obs[cv][:] # current vertex
vn = Obs[cn][:] # next vertex
# Compute the distance to the origin
dist = np.min([np.linalg.norm(vc),np.linalg.norm(vn)])
w = (np.dot(vn,(vn-vc).transpose()))/(np.linalg.norm(vn-vc)**2)
if (w>=0.0) and (w<=1.0):
vx = w*vc + (1-w)*vn
dist = np.min([dist, np.linalg.norm(vx)])
ac = np.arctan2(vc[1],vc[0]) # Relative angle of the current vertex
an = np.arctan2(vn[1],vn[0]) # Relative angle of the next vertex
flagDist = (dist <= virtualLIDAR.Range)
flagAngle = (np.min([ac,an]) <= virtualLIDAR.MaxAngle) and (np.max([ac,an]) >= virtualLIDAR.MinAngle)
# Compute LIDAR range if the obstacle segment is in the sensing region
if flagDist and flagAngle:
# Closest LIDAR ray index
I = int(round((np.max([np.min([ac,an]),virtualLIDAR.MinAngle])-virtualLIDAR.MinAngle)/virtualLIDAR.Resolution))
I = (I%virtualLIDAR.NumSample)
# Compute the intersection of the LIDAR ray with the sensor footprint
vtemp = np.array([np.cos(virtualLIDAR.Angle[I]), np.sin(virtualLIDAR.Angle[I])])
vRtemp = np.array([-np.sin(virtualLIDAR.Angle[I]), np.cos(virtualLIDAR.Angle[I])])
w = -(np.dot(vn,vRtemp.transpose()))/(np.dot(vc-vn,vRtemp.transpose()))
if (w>=0.0) and (w<=1.0):
xtemp = w*vc + (1-w)*vn
if (np.dot(xtemp,vtemp.transpose()) >= 0):
virtualLIDAR.RangeMeasurements[I] = np.min([virtualLIDAR.RangeMeasurements[I],np.linalg.norm(xtemp)])
# Compute the intersection of adjacent LIDAR rays
J = ((I+1)%virtualLIDAR.NumSample)
flagValid = True
while flagValid and (J is not I):
vtemp = np.array([np.cos(virtualLIDAR.Angle[J]),np.sin(virtualLIDAR.Angle[J])])
vRtemp = np.array([-np.sin(virtualLIDAR.Angle[J]),np.cos(virtualLIDAR.Angle[J])])
w = -(np.dot(vn,vRtemp.transpose()))/(np.dot(vc-vn,vRtemp.transpose()))
if (w>=0.0) and (w<=1.0):
xtemp = w*vc + (1-w)*vn
if (np.dot(xtemp,vtemp.transpose()) >= 0):
virtualLIDAR.RangeMeasurements[J] = np.min([virtualLIDAR.RangeMeasurements[J],np.linalg.norm(xtemp)])
J = ((J+1)%virtualLIDAR.NumSample)
else:
flagValid = False
else:
flagValid = False
J = (I-1)%virtualLIDAR.NumSample
flagValid = True
while flagValid and (J is not I):
vtemp = np.array([np.cos(virtualLIDAR.Angle[J]),np.sin(virtualLIDAR.Angle[J])])
vRtemp = np.array([-np.sin(virtualLIDAR.Angle[J]),np.cos(virtualLIDAR.Angle[J])])
w = -(np.dot(vn,vRtemp.transpose()))/(np.dot(vc-vn,vRtemp.transpose()))
if (w>=0.0) and (w<=1.0):
xtemp = w*vc + (1-w)*vn
if (np.dot(xtemp,vtemp.transpose()) >= 0):
virtualLIDAR.RangeMeasurements[J] = np.min([virtualLIDAR.RangeMeasurements[J],np.linalg.norm(xtemp)])
J = (J-1)%virtualLIDAR.NumSample
else:
flagValid = False
else:
flagValid = False
# Check sensor range
virtualLIDAR.RangeMeasurements[virtualLIDAR.RangeMeasurements > virtualLIDAR.Range] = virtualLIDAR.Range
return virtualLIDAR
def translateLIDAR2D(RobotState, RobotStateTransformed, RobotRadius, LIDAR):
"""
Rebase LIDAR readings from RobotState to RobotStateTransformed
Input:
1) RobotState: Original robot position and orientation
2) RobotStateTransformed: Transformed robot position and orientation
3) RobotRadius: Robot radius
4) LIDAR: Current LIDAR object
Output:
1) newLIDAR: Transformed LIDAR object
"""
# Find robot position and orientation
RobotPosition = RobotState[0:2]
RobotOrientation = RobotState[2]
# Find transformed robot position and orientation
RobotPositionTransformed = RobotStateTransformed[0:2]
RobotOrientationTransformed = RobotStateTransformed[2]
# Account for the robot radius
LIDAR.RangeMeasurements = LIDAR.RangeMeasurements - RobotRadius
# Find obstacle points
obstacle_points = obstaclePointsLIDAR2D(RobotState, LIDAR) - RobotPosition
# Rotation matrix from the global frame to the local sensor frame
RotMat = np.array([[np.cos(-RobotOrientation),-np.sin(-RobotOrientation)],[np.sin(-RobotOrientation),np.cos(-RobotOrientation)]])
# Points in the local sensor frame
obstacle_points = np.matmul(obstacle_points,RotMat.transpose())
# Rotation matrix from the local sensor frame to the global frame in the transformed space
RotMatTransformed = np.array([[np.cos(RobotOrientationTransformed),-np.sin(RobotOrientationTransformed)],[np.sin(RobotOrientationTransformed),np.cos(RobotOrientationTransformed)]])
# Points in the transformed space
obstacle_points_transformed = np.matmul(obstacle_points,RotMatTransformed.transpose())
obstacle_points_transformed = obstacle_points_transformed + RobotPositionTransformed
# Find new ranges
obstacle_points_transformedT = obstacle_points_transformed.transpose()
obstacle_points_transformed_x = obstacle_points_transformedT[0][:]
obstacle_points_transformed_y = obstacle_points_transformedT[1][:]
R = np.sqrt((obstacle_points_transformed_x-RobotPositionTransformed[0])**2+(obstacle_points_transformed_y-RobotPositionTransformed[1])**2)
newLIDAR = LIDARClass(R, LIDAR.Range-np.linalg.norm(RobotPositionTransformed-RobotPosition), LIDAR.Infinity, LIDAR.MinAngle, LIDAR.MaxAngle, LIDAR.Resolution)
return newLIDAR
def localminLIDAR2D(LIDAR):
"""
Function that finds the indices of local minima of the LIDAR range data
Input:
1) LIDAR: Current LIDAR object
Output:
1) Imin: Indices of local minima of the LIDAR range data
"""
R = LIDAR.RangeMeasurements
# Compute the indices of strictly local minima of the LIDAR range data
if ((LIDAR.MaxAngle-LIDAR.MinAngle)<2*np.pi):
# Assume that the region outside the angular range of LIDAR is free
Rp = np.hstack((np.array([LIDAR.Range]), R[0:-1]))
Rn = np.hstack((R[1:], np.array([LIDAR.Range])))
else:
Rp = np.hstack((np.array([R[-2]]), R[0:-1]))
Rn = np.hstack((R[1:], np.array([R[1]])))
# Logical tests
logical_test = np.logical_or(np.logical_and(R<=Rp, R<Rn), np.logical_and(R<Rp, R<=Rn))
Imin = logical_test+0
return Imin
def localworkspaceLIDAR2D(RobotState, RobotRadius, LIDAR):
"""
Function that returns the local workspace
Input:
1) RobotState: Robot position and orientation
2) RobotRadius: Robot radius
3) LIDAR: Current LIDAR object
Output:
1) LW: Local workspace polygon array
"""
X = RobotState
epsilon = 0.000000001
R = LIDAR.RangeMeasurements
if R.min(0)<epsilon:
LW = np.array([[]])
return LW
else:
# Complete missing data due to the LIDAR's angular range limits
LIDAR = completeLIDAR2D(LIDAR)
# Modified range data defining the local workspace
R = 0.5*(LIDAR.RangeMeasurements+RobotRadius)
# Initialize the local workspace with the minimum square that respects
# the LIDAR's sensing range
LW = (0.5*(LIDAR.Range+RobotRadius))*np.array([[-1,-1], [-1,1], [1,1], [1,-1]])
Imin = np.nonzero(localminLIDAR2D(LIDAR))
Imin = Imin[0]
for k in Imin:
if not LW.any():
return LW
else:
# Local minimum parameters
Ak = LIDAR.Angle[k] # Angle
Rk = R[k] # Range
# Separating hyperplane parameters
n = np.array([-np.cos(Ak+X[2]), -np.sin(Ak+X[2])]) # Hyperplane normal
m = -Rk*n # A point on the separating hyperplane
# Update the local workspace by taking its intersection with the associated halfplane
LW = cvxpolyxhplane(LW, m, n)
# Local workspace footprint
LocalFootprint = np.vstack((R*np.cos(LIDAR.Angle+X[2]), R*np.sin(LIDAR.Angle+X[2])))
LocalFootprint = LocalFootprint.transpose()
# Update local workspace
if Polygon(LW).is_valid and Polygon(LocalFootprint).is_valid:
LW = cvxpolyintersect(LW, LocalFootprint)
if LW.any():
LW = LW + np.array([[X[0], X[1]]])
else:
LW = np.array([[]])
return LW
# Make local workspace convex
convhullind = ConvexHull(LW)
LW = LW[convhullind.vertices]
return LW
else:
LW = np.array([[]])
return LW
def localfreespaceLIDAR2D(RobotState, RobotRadius, LIDAR):
"""
Function that returns the local freespace
Input:
1) RobotState: Robot position and orientation
2) RobotRadius: Robot radius
3) LIDAR: Current LIDAR object
Output:
1) LF: Local freespace polygon array
"""
X = RobotState
epsilon = 0.000000001
R = LIDAR.RangeMeasurements
if R.min(0)<epsilon:
LF = np.array([[]])
return LF
else:
# Complete missing data due to the LIDAR's angular range limits
LIDAR = completeLIDAR2D(LIDAR)
# Modified range data defining the local freespace
R = 0.5*(LIDAR.RangeMeasurements-RobotRadius)
# Initialize the local freespace with the minimum square that respects
# the LIDAR's sensing range
LF = (0.5*(LIDAR.Range-RobotRadius))*np.array([[-1,-1], [-1,1], [1,1], [1,-1]])
Imin = np.nonzero(localminLIDAR2D(LIDAR))
Imin = Imin[0]
for k in Imin:
if not LF.any():
return LF
else:
# Local minimum parameters
Ak = LIDAR.Angle[k] # Angle
Rk = R[k] # Range
# Separating hyperplane parameters
n = np.array([-np.cos(Ak+X[2]), -np.sin(Ak+X[2])]) # Hyperplane normal
m = -Rk*n # A point on the separating hyperplane
# Update the local freespace by taking its intersection with the associated halfplane
LF = cvxpolyxhplane(LF, m, n)
LocalFootprint = np.vstack((R*np.cos(LIDAR.Angle+X[2]), R*np.sin(LIDAR.Angle+X[2])))
LocalFootprint = LocalFootprint.transpose()
# Update local freespace
if Polygon(LF).is_valid and Polygon(LocalFootprint).is_valid:
LF = cvxpolyintersect(LF, LocalFootprint)
if LF.any():
LF = LF + np.array([[X[0], X[1]]])
else:
LF = np.array([[]])
return LF
# Make local freespace convex
convhullind = ConvexHull(LF)
LF = LF[convhullind.vertices]
return LF
else:
LF = np.array([[]])
return LF
def localfreespace_linearLIDAR2D(RobotState, LF):
"""
Function that returns the linear local freespace as the intersection of the local freespace with the current heading line
Input:
1) RobotState: Robot position and orientation
2) LF: Local freespace
Output:
1) LFL: Linear freespace
"""
X = RobotState
if not LF.any():
LFL = np.array([[]])
return LFL
else:
RobotPosition = np.array([X[0], X[1]])
RobotDirection = np.array([np.cos(X[2]), np.sin(X[2])])
LFL = polyxray(LF, RobotPosition, RobotDirection)
LFL = np.vstack((RobotPosition, LFL))
return LFL
def localfreespace_angularLIDAR2D(RobotState, LF, Goal):
"""
Function that returns the angular local freespace as the intersection of the local freespace with the line connecting the robot to the goal
Input:
1) RobotState: Robot position and orientation
2) LF: Local freespace
Output:
1) LFA: Angular freespace
"""
X = RobotState
if not LF.any():
LFA = np.array([[]])
return LFA
else:
RobotPosition = np.array([X[0], X[1]])
GoalDirection = np.array([Goal[0]-RobotPosition[0], Goal[1]-RobotPosition[1]])
LFA = polyxray(LF, RobotPosition, GoalDirection)
LFA = np.vstack((RobotPosition, LFA))
return LFA
def localgoalLIDAR2D(LF, Goal):
"""
Function that computes the local goal as the projection of the global goal on the local freespace
Input:
1) LF: Local freespace
2) Goal: Global goal
Output:
1) LGA1: Local goal
"""
# Compute local goal --- the closest point of local free space to the global goal
if not LF.any():
LGA1 = np.array([Goal])
else:
if inpolygon(LF, Goal):
LGA1 = np.array([Goal])
else:
D, LGA1 = polydist(LF, Goal)
return LGA1
def localgoal_linearLIDAR2D(RobotState, LF, Goal):
"""
Function that computes the linear local goal as the projection of the global goal on the linear local freespace
Input:
1) RobotState: Robot position and orientation
2) LF: Local freespace
3) Goal: Global goal
Output:
1) LGL: Local linear goal
"""
# Compute linear local free space
LFL = localfreespace_linearLIDAR2D(RobotState, LF)
# Compute local goal for unicycle
if not LFL.any():
LGL = np.array([[RobotState[0], RobotState[1]]])
else:
D, LGL = polydist(LFL, Goal)
return LGL
def localgoal_angularLIDAR2D(RobotState, LF, Goal):
"""
Function that computes the angular local goal as the projection of the global goal on the angular local freespace
Input:
1) RobotState: Robot position and orientation
2) LF: Local freespace
3) Goal: Global goal
Output:
1) LGA2: Local angular goal
"""
# Compute angular local free space
LFA = localfreespace_angularLIDAR2D(RobotState, LF, Goal)
# Compute local goal for unicycle
if not LFA.any():
LGA2 = np.array([[Goal[0], Goal[1]]])
else:
D, LGA2 = polydist(LFA, Goal)
return LGA2
def diffeoTreeTriangulation(PolygonVertices, DiffeoParams):
"""
Function that calculates the triangulation tree of a polygon and augments it with properties used in semantic navigation
Input:
1) PolygonVertices: Vertex Coordinates of input polygon - Nx2 numpy.array (start and end vertices must be the same)
2) DiffeoParams: Options for the diffeomorphism construction
Output:
1) tree: Modified tree with added properties
a) For the root:
i) 'radius': the radius of the final sphere to be constructed
b) For the children:
i) 'r_center_t': The tangents from vertices 0 and 1 to the center - 2x2 numpy array
2) 'r_center_n': The normals corresponding to 'r_center_t'
c) For the root and the children:
i) 'vertices': the vertices of the triangle - 3x2 numpy array in CCW order
ii) 'vertices_tilde': the vertices of the polygonal collar that encompasses the triangle - Mx2 numpy array in CCW order starting from the center in the parent
iii) 'r_t': the unit tangents for the triangle to be deformed in a 3x2 numpy array in CCW order
(the 1st row is the tangent shared between the parent and the child)
iv) 'r_n': the unit normals for the triangle to be deformed in a 3x2 array corresponding to 'r_t'
v) 'r_tilde_t': the unit tangents for the polygonal collar in a Mx2 numpy array in CCW order
vi) 'r_tilde_n': the unit normals for the polygonal collar in a Mx2 numpy array corresponding to 'r_tilde_t'
vii) 'center': the center in the parent, used for the purging transformation, or the center of the root used for the final transformation
"""
# Unpack diffeomorphism parameters
varepsilon = DiffeoParams['varepsilon']
workspace = DiffeoParams['workspace']
# Check if the polygon intersects the workspace boundary
if Polygon(PolygonVertices).intersects(LineString(workspace)):
# Compute the intersection with the workspace
polygon_to_use = sp.geometry.polygon.orient(Polygon(PolygonVertices).intersection(Polygon(workspace)), 1.0)
PolygonVertices = np.vstack((polygon_to_use.exterior.coords.xy[0], polygon_to_use.exterior.coords.xy[1])).transpose()
# Compute the triangulation tree of the polygon with its dual (adjacency) graph
tree = polytriangulation(PolygonVertices, workspace, True)
# Find the center and the adjacency edge to the boundary
D, C = polydist(workspace,tree[-1]['vertices'])
inds = D.argsort()
tree[-1]['vertices'] = tree[-1]['vertices'][inds]
root_polygon_coords = np.vstack((tree[-1]['vertices'], tree[-1]['vertices'][0]))
if not LinearRing(root_polygon_coords).is_ccw:
tree[-1]['vertices'][[0,1]] = tree[-1]['vertices'][[1,0]]
tree[-1]['adj_edge'] = np.vstack((tree[-1]['vertices'][0], tree[-1]['vertices'][1]))
median_point = 0.5*np.array([[tree[-1]['adj_edge'][1][0]+tree[-1]['adj_edge'][0][0], tree[-1]['adj_edge'][1][1]+tree[-1]['adj_edge'][0][1]]])
median_ray = np.array([[median_point[0][0]-tree[-1]['vertices'][2][0], median_point[0][1]-tree[-1]['vertices'][2][1]]])
median_ray = median_ray/np.linalg.norm(median_ray[0])
tree[-1]['center'] = np.array([[median_point[0][0]+1.0*median_ray[0][0], median_point[0][1]+1.0*median_ray[0][1]]])
# Compute the tangent and normal vectors of the root triangle
tree[-1]['r_t'] = np.array(tree[-1]['vertices'][1]-tree[-1]['vertices'][0])/np.linalg.norm(tree[-1]['vertices'][1]-tree[-1]['vertices'][0])
tree[-1]['r_t'] = np.vstack((tree[-1]['r_t'], np.array(tree[-1]['vertices'][2]-tree[-1]['vertices'][1])/np.linalg.norm(tree[-1]['vertices'][2]-tree[-1]['vertices'][1])))
tree[-1]['r_t'] = np.vstack((tree[-1]['r_t'], np.array(tree[-1]['vertices'][0]-tree[-1]['vertices'][2])/np.linalg.norm(tree[-1]['vertices'][0]-tree[-1]['vertices'][2])))
tree[-1]['r_n'] = np.array([-tree[-1]['r_t'][0][1], tree[-1]['r_t'][0][0]])
tree[-1]['r_n'] = np.vstack((tree[-1]['r_n'], np.array([-tree[-1]['r_t'][1][1],tree[-1]['r_t'][1][0]])))
tree[-1]['r_n'] = np.vstack((tree[-1]['r_n'], np.array([-tree[-1]['r_t'][2][1],tree[-1]['r_t'][2][0]])))
# Find the remaining tangents and normals from vertices 0 and 1 to the center
tree[-1]['r_center_t'] = (tree[-1]['center'][0]-tree[-1]['vertices'][0])/np.linalg.norm(tree[-1]['center'][0]-tree[-1]['vertices'][0])
tree[-1]['r_center_n'] = np.array([-tree[-1]['r_center_t'][1], tree[-1]['r_center_t'][0]])
tree[-1]['r_center_t'] = np.vstack((tree[-1]['r_center_t'], (tree[-1]['vertices'][1]-tree[-1]['center'][0])/np.linalg.norm(tree[-1]['vertices'][1]-tree[-1]['center'][0])))
tree[-1]['r_center_n'] = np.vstack((tree[-1]['r_center_n'], np.array([-tree[-1]['r_center_t'][1][1],tree[-1]['r_center_t'][1][0]])))
# Compute the dilated polygon and truncate it by the rays emanating from the center
original_polygon = np.array([tree[-1]['center'][0], tree[-1]['vertices'][1], tree[-1]['vertices'][2], tree[-1]['vertices'][0], tree[-1]['center'][0]])
polygon_tilde = sp.geometry.polygon.orient(Polygon(original_polygon).buffer(varepsilon, join_style=1), 1.0)
dilation = np.vstack((polygon_tilde.exterior.coords.xy[0], polygon_tilde.exterior.coords.xy[1])).transpose()
intersect_1 = cvxpolyxhplane(dilation[0:-1], tree[-1]['center'][0], tree[-1]['r_center_n'][0])
intersect_2 = cvxpolyxhplane(intersect_1, tree[-1]['center'][0], tree[-1]['r_center_n'][1])
polygon_tilde_vertices = np.vstack((intersect_2,intersect_2[0]))
# Compute the intersection with the workspace
final_polygon = sp.geometry.polygon.orient(Polygon(polygon_tilde_vertices).intersection(Polygon(workspace).union(Polygon(np.array([tree[-1]['center'][0], tree[-1]['vertices'][1], tree[-1]['vertices'][2], tree[-1]['vertices'][0], tree[-1]['center'][0]])))).simplify(0.01), 1.0)
tree[-1]['vertices_tilde'] = np.vstack((final_polygon.exterior.coords.xy[0][0:-1], final_polygon.exterior.coords.xy[1][0:-1])).transpose()
# Find the tangent and normal vectors for the generated polygonal collar
vertices_to_consider = np.vstack((tree[-1]['vertices_tilde'],tree[-1]['vertices_tilde'][0]))
tree[-1]['r_tilde_t'] = (vertices_to_consider[1]-vertices_to_consider[0])/np.linalg.norm(vertices_to_consider[1]-vertices_to_consider[0])
tree[-1]['r_tilde_n'] = np.array([-tree[-1]['r_tilde_t'][1],tree[-1]['r_tilde_t'][0]])
for j in range(1,vertices_to_consider.shape[0]-1):
tree[-1]['r_tilde_t'] = np.vstack((tree[-1]['r_tilde_t'],(vertices_to_consider[j+1]-vertices_to_consider[j])/np.linalg.norm(vertices_to_consider[j+1]-vertices_to_consider[j])))
tree[-1]['r_tilde_n'] = np.vstack((tree[-1]['r_tilde_n'],np.array([-tree[-1]['r_tilde_t'][j][1],tree[-1]['r_tilde_t'][j][0]])))
# Add a dummy radius
tree[-1]['radius'] = 0.0
else:
# Compute the triangulation tree of the polygon with its dual (adjacency) graph
tree = polytriangulation(PolygonVertices, workspace, False)
# Start with the root and find the center and the radius
root_coords = tree[-1]['vertices'].transpose()
tree[-1]['center'] = np.array([[sum(root_coords[0])/len(root_coords[0]), sum(root_coords[1])/len(root_coords[1])]])
D, closest_point = polydist(tree[-1]['vertices'], tree[-1]['center'])
tree[-1]['radius'] = 0.8*D[0]
# Compute the tangent and normal vectors of the root triangle
tree[-1]['r_t'] = np.array(tree[-1]['vertices'][1]-tree[-1]['vertices'][0])/np.linalg.norm(tree[-1]['vertices'][1]-tree[-1]['vertices'][0])
tree[-1]['r_t'] = np.vstack((tree[-1]['r_t'], np.array(tree[-1]['vertices'][2]-tree[-1]['vertices'][1])/np.linalg.norm(tree[-1]['vertices'][2]-tree[-1]['vertices'][1])))
tree[-1]['r_t'] = np.vstack((tree[-1]['r_t'], np.array(tree[-1]['vertices'][0]-tree[-1]['vertices'][2])/np.linalg.norm(tree[-1]['vertices'][0]-tree[-1]['vertices'][2])))
tree[-1]['r_n'] = np.array([-tree[-1]['r_t'][0][1], tree[-1]['r_t'][0][0]])
tree[-1]['r_n'] = np.vstack((tree[-1]['r_n'], np.array([-tree[-1]['r_t'][1][1],tree[-1]['r_t'][1][0]])))
tree[-1]['r_n'] = np.vstack((tree[-1]['r_n'], np.array([-tree[-1]['r_t'][2][1],tree[-1]['r_t'][2][0]])))
# Find the polygonal collar for the root by dilating the triangle by varepsilon
polygon_tilde = sp.geometry.polygon.orient(Polygon(tree[-1]['vertices']).buffer(varepsilon, join_style=1).intersection(Polygon(workspace)).simplify(0.01), 1.0)
tree[-1]['vertices_tilde'] = np.vstack((polygon_tilde.exterior.coords.xy[0][0:-1], polygon_tilde.exterior.coords.xy[1][0:-1])).transpose()
# Find the tangent and normal vectors for the generated polygonal collar
vertices_to_consider = np.vstack((tree[-1]['vertices_tilde'],tree[-1]['vertices_tilde'][0]))
tree[-1]['r_tilde_t'] = (vertices_to_consider[1]-vertices_to_consider[0])/np.linalg.norm(vertices_to_consider[1]-vertices_to_consider[0])
tree[-1]['r_tilde_n'] = np.array([-tree[-1]['r_tilde_t'][1],tree[-1]['r_tilde_t'][0]])
for j in range(1,vertices_to_consider.shape[0]-1):
tree[-1]['r_tilde_t'] = np.vstack((tree[-1]['r_tilde_t'],(vertices_to_consider[j+1]-vertices_to_consider[j])/np.linalg.norm(vertices_to_consider[j+1]-vertices_to_consider[j])))
tree[-1]['r_tilde_n'] = np.vstack((tree[-1]['r_tilde_n'],np.array([-tree[-1]['r_tilde_t'][j][1],tree[-1]['r_tilde_t'][j][0]])))
# Identify all the children properties
for i in range(0,len(tree)-1):
# Compute the tangent and normal vectors of the child hyperplanes
# r0 is always the shared edge between the parent and the child, r1 and r2 the rest in CCW order
tree[i]['r_t'] = np.array(tree[i]['vertices'][1]-tree[i]['vertices'][0])/np.linalg.norm(tree[i]['vertices'][1]-tree[i]['vertices'][0])
tree[i]['r_t'] = np.vstack((tree[i]['r_t'], np.array(tree[i]['vertices'][2]-tree[i]['vertices'][1])/np.linalg.norm(tree[i]['vertices'][2]-tree[i]['vertices'][1])))
tree[i]['r_t'] = np.vstack((tree[i]['r_t'], np.array(tree[i]['vertices'][0]-tree[i]['vertices'][2])/np.linalg.norm(tree[i]['vertices'][0]-tree[i]['vertices'][2])))
tree[i]['r_n'] = np.array([-tree[i]['r_t'][0][1], tree[i]['r_t'][0][0]])
tree[i]['r_n'] = np.vstack((tree[i]['r_n'], np.array([-tree[i]['r_t'][1][1],tree[i]['r_t'][1][0]])))
tree[i]['r_n'] = np.vstack((tree[i]['r_n'], np.array([-tree[i]['r_t'][2][1],tree[i]['r_t'][2][0]])))
# Find the median from the 3rd point to the shared edge and from that compute the center for the purging transformation
median_point = 0.5*np.array([[tree[i]['adj_edge'][1][0]+tree[i]['adj_edge'][0][0], tree[i]['adj_edge'][1][1]+tree[i]['adj_edge'][0][1]]])
median_ray = np.array([[median_point[0][0]-tree[i]['vertices'][2][0], median_point[0][1]-tree[i]['vertices'][2][1]]])
median_ray = median_ray/np.linalg.norm(median_ray[0])
intersection_point = polyxray(tree[tree[i]['predecessor']]['vertices'], median_point[0], median_ray[0]) # offset median point by a little bit to avoid numerical problems
tree[i]['center'] = np.array([[0.2*median_point[0][0]+0.8*intersection_point[0], 0.2*median_point[0][1]+0.8*intersection_point[1]]])
# Find the remaining tangents and normals from vertices 0 and 1 to the center
tree[i]['r_center_t'] = (tree[i]['center'][0]-tree[i]['vertices'][0])/np.linalg.norm(tree[i]['center'][0]-tree[i]['vertices'][0])
tree[i]['r_center_n'] = np.array([-tree[i]['r_center_t'][1], tree[i]['r_center_t'][0]])
tree[i]['r_center_t'] = np.vstack((tree[i]['r_center_t'], (tree[i]['vertices'][1]-tree[i]['center'][0])/np.linalg.norm(tree[i]['vertices'][1]-tree[i]['center'][0])))
tree[i]['r_center_n'] = np.vstack((tree[i]['r_center_n'], np.array([-tree[i]['r_center_t'][1][1],tree[i]['r_center_t'][1][0]])))
# Compute the dilated polygon and truncate it by the rays emanating from the center
original_polygon = np.array([tree[i]['center'][0], tree[i]['vertices'][1], tree[i]['vertices'][2], tree[i]['vertices'][0], tree[i]['center'][0]])
polygon_tilde = sp.geometry.polygon.orient(Polygon(original_polygon).buffer(varepsilon, join_style=1).simplify(0.01), 1.0)
dilation = np.vstack((polygon_tilde.exterior.coords.xy[0], polygon_tilde.exterior.coords.xy[1])).transpose()
intersect_1 = cvxpolyxhplane(dilation[0:-1], tree[i]['center'][0], tree[i]['r_center_n'][0])
intersect_2 = cvxpolyxhplane(intersect_1, tree[i]['center'][0], tree[i]['r_center_n'][1])
candidate_polygon_vertices = np.vstack((intersect_2,intersect_2[0]))
candidate_polygon = Polygon(candidate_polygon_vertices)
# Check for collisions with all the triangles that will succeed i in the diffeomorphism construction except for its parent
for j in range(i+1,len(tree)):
if (j == tree[i]['predecessor']):
continue
else:
polygon_to_test = Polygon(tree[j]['vertices'])
candidate_polygon = (candidate_polygon.buffer(0)).difference(polygon_to_test.buffer(0))
# If the difference operation created a multipolygon, keep only the polygon that contains the barycenter of the extended triangle
if candidate_polygon.geom_type == 'MultiPolygon':
point_to_consider = Point((tree[i]['vertices'][0][0]+tree[i]['vertices'][1][0]+tree[i]['center'][0][0])/3.0, (tree[i]['vertices'][0][1]+tree[i]['vertices'][1][1]+tree[i]['center'][0][1])/3.0)
for k in range(len(candidate_polygon)):
if candidate_polygon[k].contains(point_to_consider):
candidate_polygon = candidate_polygon[k]
break
# Extract final vertices
candidate_polygon = sp.geometry.polygon.orient(candidate_polygon.simplify(0.01), 1.0)
candidate_polygon_vertices = np.vstack((candidate_polygon.exterior.coords.xy[0], candidate_polygon.exterior.coords.xy[1])).transpose()
# Decompose the polygon into its convex pieces and find the piece that includes the barycenter of the extended triangle
decomposition = polycvxdecomp(candidate_polygon_vertices.tolist())
for j in range(len(decomposition)):
point_to_consider = Point((tree[i]['vertices'][0][0]+tree[i]['vertices'][1][0]+tree[i]['center'][0][0])/3.0, (tree[i]['vertices'][0][1]+tree[i]['vertices'][1][1]+tree[i]['center'][0][1])/3.0)
polygon_to_consider = Polygon(decomposition[j])
if polygon_to_consider.buffer(0.01).contains(point_to_consider):
final_polygon_vertices = np.vstack((polygon_to_consider.exterior.coords.xy[0], polygon_to_consider.exterior.coords.xy[1])).transpose()
break
# Generate the outer polygonal collar
final_polygon = sp.geometry.polygon.orient(Polygon(final_polygon_vertices).intersection(Polygon(workspace)), 1.0)
tree[i]['vertices_tilde'] = np.vstack((final_polygon.exterior.coords.xy[0][0:-1], final_polygon.exterior.coords.xy[1][0:-1])).transpose()
# Find the tangent and normal vectors for the generated polygonal collar
vertices_to_consider = np.vstack((tree[i]['vertices_tilde'],tree[i]['vertices_tilde'][0]))
tree[i]['r_tilde_t'] = (vertices_to_consider[1]-vertices_to_consider[0])/np.linalg.norm(vertices_to_consider[1]-vertices_to_consider[0])
tree[i]['r_tilde_n'] = np.array([-tree[i]['r_tilde_t'][1],tree[i]['r_tilde_t'][0]])
for j in range(1,vertices_to_consider.shape[0]-1):
tree[i]['r_tilde_t'] = np.vstack((tree[i]['r_tilde_t'],(vertices_to_consider[j+1]-vertices_to_consider[j])/np.linalg.norm(vertices_to_consider[j+1]-vertices_to_consider[j])))
tree[i]['r_tilde_n'] = np.vstack((tree[i]['r_tilde_n'],np.array([-tree[i]['r_tilde_t'][j][1],tree[i]['r_tilde_t'][j][0]])))
return tree
def diffeoTreeConvex(PolygonVertices, DiffeoParams):
"""
Function that calculates the convex decomposition of a polygon and augments it with properties used in semantic navigation
Input:
1) PolygonVertices: Vertex Coordinates of input polygon - Nx2 numpy.array (start and end vertices must be the same)
2) DiffeoParams: Options for the diffeomorphism construction
Output:
1) tree: Modified tree with added properties
a) For the root:
i) 'radius': the radius of the final sphere to be constructed
b) For the children:
i) 'r_center_t': The tangents from vertices 0 and 1 to the center - 2x2 numpy array
2) 'r_center_n': The normals corresponding to 'r_center_t'
c) For the root and the children:
i) 'vertices': the vertices of the polygon - Nx2 numpy array in CCW order
ii) 'augmented_vertices': the vertices of the polygon including the center of deformation (the second element in this array) - (N+1)x2 numpy array in CCW order
ii) 'vertices_tilde': the vertices of the polygonal collar that encompasses the polygon - Mx2 numpy array in CCW order starting from the center in the parent
iii) 'r_t': the unit tangents corresponding to augmented_vertices in CCW order
iv) 'r_n': the unit normals for the polygon to be deformed in an array corresponding to 'r_t'
v) 'r_tilde_t': the unit tangents for the polygonal collar in a Mx2 numpy array in CCW order
vi) 'r_tilde_n': the unit normals for the polygonal collar in a Mx2 numpy array corresponding to 'r_tilde_t'
vii) 'center': the center in the parent, used for the purging transformation, or the center of the root used for the final transformation
"""
# Unpack diffeomorphism parameters
varepsilon = DiffeoParams['varepsilon']
workspace = DiffeoParams['workspace']
# Check if the polygon intersects the workspace boundary
if Polygon(PolygonVertices).intersects(LineString(workspace)):
# Compute the intersection with the workspace
polygon_to_use = sp.geometry.polygon.orient(Polygon(PolygonVertices).intersection(Polygon(workspace)), 1.0)
PolygonVertices = np.vstack((polygon_to_use.exterior.coords.xy[0], polygon_to_use.exterior.coords.xy[1])).transpose()
# Compute the convex decomposition tree of the polygon with its dual (adjacency) graph
tree = polyconvexdecomposition(PolygonVertices, workspace, True)
# Find the center and the adjacency edge to the boundary
D, C = polydist(workspace,tree[-1]['vertices'])
inds = D.argsort()
if D[(inds[0]+1)%tree[-1]['vertices'].shape[0]] >= D[(inds[0]-1)%tree[-1]['vertices'].shape[0]]:
tree[-1]['vertices'] = np.roll(tree[-1]['vertices'],-(inds[0]-1)%tree[-1]['vertices'].shape[0],axis=0)
else:
tree[-1]['vertices'] = np.roll(tree[-1]['vertices'],-(inds[0])%tree[-1]['vertices'].shape[0],axis=0)
tree[-1]['adj_edge'] = np.vstack((tree[-1]['vertices'][0], tree[-1]['vertices'][1]))
median_point = 0.5*np.array([[tree[-1]['adj_edge'][1][0]+tree[-1]['adj_edge'][0][0], tree[-1]['adj_edge'][1][1]+tree[-1]['adj_edge'][0][1]]])
median_ray = np.array([[median_point[0][0]-tree[-1]['vertices'][2][0], median_point[0][1]-tree[-1]['vertices'][2][1]]])
median_ray = median_ray/np.linalg.norm(median_ray[0])
tree[-1]['center'] = np.array([[median_point[0][0]+0.3*median_ray[0][0], median_point[0][1]+0.3*median_ray[0][1]]])
# Compute the tangent and normal vectors of the child hyperplanes
# r0 is always the shared edge between the parent and the child, the rest in CCW order
tree[-1]['r_t'] = []
for j in range(0,tree[-1]['vertices'].shape[0]):
tree[-1]['r_t'].append(np.array(tree[-1]['vertices'][(j+1)%tree[-1]['vertices'].shape[0]]-tree[-1]['vertices'][j%tree[-1]['vertices'].shape[0]])/np.linalg.norm(tree[-1]['vertices'][(j+1)%tree[-1]['vertices'].shape[0]]-tree[-1]['vertices'][j%tree[-1]['vertices'].shape[0]]))
tree[-1]['r_t'] = np.array(tree[-1]['r_t'])
tree[-1]['r_n'] = np.zeros((tree[-1]['r_t'].shape[0],2))
for j in range(0,tree[-1]['r_n'].shape[0]):
tree[-1]['r_n'][j][0] = -tree[-1]['r_t'][j][1]
tree[-1]['r_n'][j][1] = tree[-1]['r_t'][j][0]
# Find the remaining tangents and normals from vertices 0 and 1 to the center
tree[-1]['r_center_t'] = (tree[-1]['center'][0]-tree[-1]['vertices'][0])/np.linalg.norm(tree[-1]['center'][0]-tree[-1]['vertices'][0])
tree[-1]['r_center_n'] = np.array([-tree[-1]['r_center_t'][1], tree[-1]['r_center_t'][0]])
tree[-1]['r_center_t'] = np.vstack((tree[-1]['r_center_t'], (tree[-1]['vertices'][1]-tree[-1]['center'][0])/np.linalg.norm(tree[-1]['vertices'][1]-tree[-1]['center'][0])))
tree[-1]['r_center_n'] = np.vstack((tree[-1]['r_center_n'], np.array([-tree[-1]['r_center_t'][1][1],tree[-1]['r_center_t'][1][0]])))
# Compute the dilated polygon and truncate it by the rays emanating from the center
original_polygon = np.vstack((tree[-1]['vertices'][0], tree[-1]['center'], tree[-1]['vertices'][1:]))
polygon_tilde = sp.geometry.polygon.orient(Polygon(original_polygon).buffer(varepsilon, join_style=1), 1.0)
dilation = np.vstack((polygon_tilde.exterior.coords.xy[0], polygon_tilde.exterior.coords.xy[1])).transpose()
intersect_1 = cvxpolyxhplane(dilation[0:-1], tree[-1]['center'][0], tree[-1]['r_center_n'][0])
intersect_2 = cvxpolyxhplane(intersect_1, tree[-1]['center'][0], tree[-1]['r_center_n'][1])
polygon_tilde_vertices = np.vstack((intersect_2,intersect_2[0]))
# Compute the intersection with the workspace
final_polygon = sp.geometry.polygon.orient(((Polygon(polygon_tilde_vertices).intersection(Polygon(workspace))).union(Polygon(np.vstack((tree[-1]['center'][0], tree[-1]['vertices'][1:], tree[-1]['vertices'][0], tree[-1]['center'][0]))))).simplify(0.01), 1.0)
tree[-1]['vertices_tilde'] = np.vstack((final_polygon.exterior.coords.xy[0][0:-1], final_polygon.exterior.coords.xy[1][0:-1])).transpose()
# Find the tangent and normal vectors for the generated polygonal collar
tree[-1]['r_tilde_t'] = []
for j in range(0,tree[-1]['vertices_tilde'].shape[0]):
tree[-1]['r_tilde_t'].append(np.array(tree[-1]['vertices_tilde'][(j+1)%tree[-1]['vertices_tilde'].shape[0]]-tree[-1]['vertices_tilde'][j%tree[-1]['vertices_tilde'].shape[0]])/np.linalg.norm(tree[-1]['vertices_tilde'][(j+1)%tree[-1]['vertices_tilde'].shape[0]]-tree[-1]['vertices_tilde'][j%tree[-1]['vertices_tilde'].shape[0]]))
tree[-1]['r_tilde_t'] = np.array(tree[-1]['r_tilde_t'])
tree[-1]['r_tilde_n'] = np.zeros((tree[-1]['r_tilde_t'].shape[0],2))
for j in range(0,tree[-1]['r_tilde_n'].shape[0]):
tree[-1]['r_tilde_n'][j][0] = -tree[-1]['r_tilde_t'][j][1]
tree[-1]['r_tilde_n'][j][1] = tree[-1]['r_tilde_t'][j][0]
# Finally, compute the augmented inner polygon that includes the center of deformation and update
tree[-1]['augmented_vertices'] = np.vstack((tree[-1]['vertices'][0], tree[-1]['center'], tree[-1]['vertices'][1:]))
tree[-1]['r_t'] = np.vstack((tree[-1]['r_center_t'][0], tree[-1]['r_center_t'][1], tree[-1]['r_t'][1:]))
tree[-1]['r_n'] = np.vstack((tree[-1]['r_center_n'][0], tree[-1]['r_center_n'][1], tree[-1]['r_n'][1:]))
# Add a dummy radius
tree[-1]['radius'] = 0.0
else:
# Compute the convex decomposition tree of the polygon with its dual (adjacency) graph
tree = polyconvexdecomposition(PolygonVertices, workspace, False)
# Start with the root and find the center and the radius
root_coords = tree[-1]['vertices'].transpose()
tree[-1]['center'] = np.array([[sum(root_coords[0])/len(root_coords[0]), sum(root_coords[1])/len(root_coords[1])]])
D, closest_point = polydist(tree[-1]['vertices'], tree[-1]['center'])
tree[-1]['radius'] = 0.8*D[0]
# Compute the tangent and normal vectors of the root polygon
tree[-1]['r_t'] = []
for j in range(0,tree[-1]['vertices'].shape[0]):
tree[-1]['r_t'].append(np.array(tree[-1]['vertices'][(j+1)%tree[-1]['vertices'].shape[0]]-tree[-1]['vertices'][j%tree[-1]['vertices'].shape[0]])/np.linalg.norm(tree[-1]['vertices'][(j+1)%tree[-1]['vertices'].shape[0]]-tree[-1]['vertices'][j%tree[-1]['vertices'].shape[0]]))
tree[-1]['r_t'] = np.array(tree[-1]['r_t'])
tree[-1]['r_n'] = np.zeros((tree[-1]['r_t'].shape[0],2))
for j in range(0,tree[-1]['r_n'].shape[0]):
tree[-1]['r_n'][j][0] = -tree[-1]['r_t'][j][1]
tree[-1]['r_n'][j][1] = tree[-1]['r_t'][j][0]
# Find the polygonal collar for the root by dilating the polygon by varepsilon
polygon_tilde = sp.geometry.polygon.orient(Polygon(tree[-1]['vertices']).buffer(varepsilon, join_style=1).intersection(Polygon(workspace)).simplify(0.01), 1.0)
tree[-1]['vertices_tilde'] = np.vstack((polygon_tilde.exterior.coords.xy[0][0:-1], polygon_tilde.exterior.coords.xy[1][0:-1])).transpose()
# Find the tangent and normal vectors for the generated polygonal collar
tree[-1]['r_tilde_t'] = []
for j in range(0,tree[-1]['vertices_tilde'].shape[0]):
tree[-1]['r_tilde_t'].append(np.array(tree[-1]['vertices_tilde'][(j+1)%tree[-1]['vertices_tilde'].shape[0]]-tree[-1]['vertices_tilde'][j%tree[-1]['vertices_tilde'].shape[0]])/np.linalg.norm(tree[-1]['vertices_tilde'][(j+1)%tree[-1]['vertices_tilde'].shape[0]]-tree[-1]['vertices_tilde'][j%tree[-1]['vertices_tilde'].shape[0]]))
tree[-1]['r_tilde_t'] = np.array(tree[-1]['r_tilde_t'])
tree[-1]['r_tilde_n'] = np.zeros((tree[-1]['r_tilde_t'].shape[0],2))
for j in range(0,tree[-1]['r_tilde_n'].shape[0]):
tree[-1]['r_tilde_n'][j][0] = -tree[-1]['r_tilde_t'][j][1]
tree[-1]['r_tilde_n'][j][1] = tree[-1]['r_tilde_t'][j][0]
# In this case the augmented vertices are the same
tree[-1]['augmented_vertices'] = tree[-1]['vertices']
# Identify all the children properties
for i in range(0,len(tree)-1):
# Compute the tangent and normal vectors of the child hyperplanes
# r0 is always the shared edge between the parent and the child, the rest in CCW order
tree[i]['r_t'] = []
for j in range(0,tree[i]['vertices'].shape[0]):
tree[i]['r_t'].append(np.array(tree[i]['vertices'][(j+1)%tree[i]['vertices'].shape[0]]-tree[i]['vertices'][j%tree[i]['vertices'].shape[0]])/np.linalg.norm(tree[i]['vertices'][(j+1)%tree[i]['vertices'].shape[0]]-tree[i]['vertices'][j%tree[i]['vertices'].shape[0]]))
tree[i]['r_t'] = np.array(tree[i]['r_t'])
tree[i]['r_n'] = np.zeros((tree[i]['r_t'].shape[0],2))
for j in range(0,tree[i]['r_n'].shape[0]):
tree[i]['r_n'][j][0] = -tree[i]['r_t'][j][1]
tree[i]['r_n'][j][1] = tree[i]['r_t'][j][0]
# Find the median from the point furthest away from the adjacency edge and from that compute the center for the purging transformation
# To compute the center, first compute the intersection of the parent polygon with the hyperplanes of the child polygon next to the adjacency edge - this defines the admissible region within which you are allowed to search for a center
dot_product_list = []
for j in range(0,tree[i]['vertices'].shape[0]):
dot_product_list.append(np.dot(tree[i]['vertices'][j]-tree[i]['vertices'][0],tree[i]['r_n'][0]))
inds = np.array(dot_product_list).argsort()
median_point = 0.5*np.array([[tree[i]['adj_edge'][1][0]+tree[i]['adj_edge'][0][0], tree[i]['adj_edge'][1][1]+tree[i]['adj_edge'][0][1]]])
median_ray = np.array([[median_point[0][0]-tree[i]['vertices'][inds[-1]][0], median_point[0][1]-tree[i]['vertices'][inds[-1]][1]]])
median_ray = median_ray/np.linalg.norm(median_ray[0])
intersect_1_cvx = cvxpolyxhplane(tree[tree[i]['predecessor']]['vertices'], tree[i]['adj_edge'][0], tree[i]['r_n'][-1])
intersect_2_cvx = cvxpolyxhplane(intersect_1_cvx, tree[i]['adj_edge'][1], tree[i]['r_n'][1])
intersection_point = polyxray(intersect_2_cvx, median_point[0]+0.05*median_ray[0], median_ray[0]) # offset median point by a little bit to avoid numerical problems
tree[i]['center'] = np.array([[0.5*median_point[0][0]+0.5*intersection_point[0], 0.5*median_point[0][1]+0.5*intersection_point[1]]])
# Find the remaining tangents and normals from vertices 0 and 1 to the center
tree[i]['r_center_t'] = (tree[i]['center'][0]-tree[i]['vertices'][0])/np.linalg.norm(tree[i]['center'][0]-tree[i]['vertices'][0])
tree[i]['r_center_n'] = np.array([-tree[i]['r_center_t'][1], tree[i]['r_center_t'][0]])
tree[i]['r_center_t'] = np.vstack((tree[i]['r_center_t'], (tree[i]['vertices'][1]-tree[i]['center'][0])/np.linalg.norm(tree[i]['vertices'][1]-tree[i]['center'][0])))
tree[i]['r_center_n'] = np.vstack((tree[i]['r_center_n'], np.array([-tree[i]['r_center_t'][1][1],tree[i]['r_center_t'][1][0]])))
# Compute the dilated polygon and truncate it by the rays emanating from the center
# Make sure that the intersection of the dilation with the convex pieces succeeding the current convex piece in the transformation does not generate a multipolygon - otherwise reduce the radius of dilation until we have a single piece
succeeding_polygons = []
for j in range(i+1,len(tree)):
succeeding_polygons.append(Polygon(tree[j]['vertices']))
succeeding_polygons_union = cascaded_union(succeeding_polygons)