forked from dimikout3/ConvCAOAirSim
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontrollerBase.py
More file actions
1513 lines (1040 loc) · 57.4 KB
/
Copy pathcontrollerBase.py
File metadata and controls
1513 lines (1040 loc) · 57.4 KB
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
# import setup_path
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
import airsim
import os
import cv2
import numpy as np
import time
import pickle
import utilities.utils as utils
import matplotlib.pyplot as plt
import scipy
from scipy.spatial import Delaunay
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.pipeline import Pipeline
from sklearn.svm import SVR
from sklearn.neighbors import KNeighborsRegressor
from sklearn.neural_network import MLPRegressor
# the value wich will devide the field of view (constraing the yaw movement)
CAM_DEV = 4
ORIENTATION_DEV = 4
# how may tries we will try to get images from AirSim
IMAGES_TRIES = 10
SAVE_DETECTED = True
DEBUG_GEOFENCE = False
DEBUG_RANDOMZ = False
DEBUG_MOVE = False
DEBUG_MOVE1DOF = False
DEBUG_MOVE_OMNI = False
DEBUG_ESTIMATOR = False
DEBUG_CANDITATE_LIDAR = False
DEBUG_CLEAR_LIDAR = False
DEBUG_LIDAR_DIST = False
PLOT_CANDITATES = True
WEIGHTS = {"cars":1.0, "persons":0.0 , "trafficLights":1.0}
class controller:
def __init__(self, clientIn, droneName, offSets, ip="1",
wayPointsSize=200, estimatorWindow=55, maxDistView=None):
self.client = clientIn
self.name = droneName
self.lidarName = "Lidar1"
self.ip = ip
self.estimatorWindow = estimatorWindow
self.pointCloud = []
self.client.enableApiControl(True, self.name)
self.client.armDisarm(True, self.name)
self.offSetX = offSets[0]
self.offSetY = offSets[1]
self.offSetZ = offSets[2]
self.wayPointSize = wayPointsSize
self.maxDistView = maxDistView
self.updateMultirotorState()
self.updateCameraInfo()
self.stateList = []
self.model = Pipeline([('poly', PolynomialFeatures(degree=3)),
('linear', LinearRegression())])
self.estimator = self.model.fit([np.random.uniform(0,1,3)],[np.random.uniform(0,1)])
self.estimations = []
self.historyData = []
# how much vehicles currrent movement affected the cost Function (delta)
self.contribution = []
self.j_i = []
self.informationJ = []
self.informationJi = []
self.timeStep = 0
self.posIdx = 0
self.restrictingMovement = np.linspace(1,0.1,wayPointsSize)
self.estimatorWeights = np.linspace(1,1,self.estimatorWindow)
self.parentRaw = os.path.join(os.getcwd(),f"results_{ip}", "swarm_raw_output")
try:
os.makedirs(self.parentRaw)
except OSError:
if not os.path.isdir(self.parentRaw):
raise
self.parentDetect = os.path.join(os.getcwd(),f"results_{ip}", "swarm_detected")
try:
os.makedirs(self.parentDetect)
except OSError:
if not os.path.isdir(self.parentDetect):
raise
def takeOff(self):
return self.client.takeoffAsync(vehicle_name = self.name)
def hover(self):
return self.client.hoverAsync(vehicle_name=self.name)
def setPose(self, x, y, z, pitch, roll, yaw):
x -= self.offSetX
y -= self.offSetY
z -= self.offSetZ
position = airsim.Vector3r(x , y, z)
heading = airsim.to_quaternion(pitch, roll, yaw)
pose = airsim.Pose(position, heading)
return self.client.simSetVehiclePose(pose, True,vehicle_name=self.name)
def moveToPositionYawModeAsync(self, x, y, z, speed=1, yawmode = 0):
# moveToPositionAsync works only for relative coordinates, therefore we must
# subtrack the offset (which corresponds to global coordinates)
x -= self.offSetX
y -= self.offSetY
z -= self.offSetZ
return self.client.moveToPositionAsync(x, y, z, speed,
yaw_mode = airsim.YawMode(False, yawmode),
vehicle_name=self.name)
def moveToPositionYawMode(self, x, y, z, speed, yawmode = 0):
# moveToPositionAsync works only for relative coordinates, therefore we must
# subtrack the offset (which corresponds to global coordinates)
x -= self.offSetX
y -= self.offSetY
z -= self.offSetZ
return self.client.moveToPositionAsync(x, y, z, speed,
yaw_mode = airsim.YawMode(False, yawmode),
vehicle_name=self.name).join()
def moveToPosition(self, x, y, z, speed):
# moveToPositionAsync works only for relative coordinates, therefore we must
# subtrack the offset (which corresponds to global coordinates)
x -= self.offSetX
y -= self.offSetY
z -= self.offSetZ
return self.client.moveToPositionAsync(x,y,z,speed,vehicle_name=self.name)
def setCameraOrientation(self, cam_yaw, cam_pitch, cam_roll):
self.client.simSetCameraOrientation("0",
airsim.to_quaternion(cam_yaw, cam_pitch, cam_roll),
vehicle_name = self.name)
def getName(self):
return self.name
def getImages(self, save_raw=False):
for _ in range(IMAGES_TRIES):
try:
responses = self.client.simGetImages([
airsim.ImageRequest("0", airsim.ImageType.DepthPerspective, True), #depth visualization image
airsim.ImageRequest("0", airsim.ImageType.Scene, False, False),
airsim.ImageRequest("1", airsim.ImageType.DepthPerspective, True),
airsim.ImageRequest("4", airsim.ImageType.DepthPerspective, True),
airsim.ImageRequest("1", airsim.ImageType.Segmentation, True), #depth in perspective projection
airsim.ImageRequest("4", airsim.ImageType.Segmentation, True)],
vehicle_name = self.name) #scene vision image in uncompressed RGB array
img1d = np.frombuffer(responses[1].image_data_uint8, dtype=np.uint8) #get numpy array
if os.name=='nt':
img_rgb = img1d.reshape(responses[1].height, responses[1].width, 3) #reshape array to 3 channel image array H X W X 3
else:
img_rgb = img1d.reshape(responses[1].height, responses[1].width, 4) #reshape array to 3 channel image array H X W X 3
img_rgb = img_rgb[:,:,0:3]
img_rgb = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2RGB)
self.imageScene = img_rgb
self.imageDepthCamera = responses[0]
imageDepthFront = airsim.list_to_2d_float_array(responses[2].image_data_float,
responses[2].width,
responses[2].height)
self.imageDepthFront = imageDepthFront
self.imageDepthFrontRaw = responses[2]
self.frontSegmented = airsim.list_to_2d_float_array(responses[4].image_data_float,
responses[4].width,
responses[4].height)
imageDepthBack = airsim.list_to_2d_float_array(responses[3].image_data_float,
responses[3].width,
responses[3].height)
self.imageDepthBack = imageDepthBack
self.imageDepthBackRaw = responses[3]
self.backSegmented = airsim.list_to_2d_float_array(responses[5].image_data_float,
responses[5].width,
responses[5].height)
self.imageDepthPeripheralWidth = responses[3].width
self.imageDepthPeripheralHeight = responses[3].height
if save_raw:
filenameDepth = os.path.join(self.raw_dir, f"depth_time_{self.timeStep}" )
airsim.write_pfm(os.path.normpath(filenameDepth + '.pfm'), airsim.get_pfm_array(responses[0]))
filenameScene = os.path.join(self.raw_dir, f"scene_time_{self.timeStep}" )
cv2.imwrite(os.path.normpath(filenameScene + '.png'), img_rgb) # write to png
# if code reach here, we should break the loop
break
except:
pass
return responses
def getPointCloud(self, x=500, y=500):
randomPointsSize = x*y
height, width, _ = self.imageScene.shape
halfWidth = width/2
halfHeight= height/2
r = np.random.uniform(0,min(halfHeight,halfWidth),randomPointsSize)
thetas = np.random.uniform(0,2*np.pi,randomPointsSize)
pointsH = r*np.sin(thetas)
pointsW = r*np.cos(thetas)
centerH = int(halfHeight)
centerW = int(halfWidth)
pointsH = centerH + pointsH.astype(int)
pointsW = centerW + pointsW.astype(int)
colors = self.imageScene[pointsH, pointsW]
xRelative, yRelative, zRelative, colors = utils.to3D(pointsW, pointsH,
self.cameraInfo, self.imageDepthCamera,
color = colors, maxDistView = self.maxDistView)
x, y, z = utils.to_absolute_coordinates(xRelative, yRelative, zRelative,
self.cameraInfo)
# utils.plot3dColor(x,y,z,colors,show=True)
self.pointCloud.append([x,y,z,colors])
return x,y,z,colors
# TODO: getDepth() -> from camera "0", similar to rgb
def getCanditatesSegmented(self, maxDistTravel=5., size=500, safeDist=2.):
depthImageList = [(self.imageDepthFrontRaw, self.imageDepthFront, self.frontSegmented, self.cameraInfoFront),
(self.imageDepthBackRaw, self.imageDepthBack, self.backSegmented, self.cameraInfoBack)]
height, width, _ = self.imageScene.shape
halfWidth = width/2
halfHeight= height/2
centerH = int(halfHeight)
centerW = int(halfWidth)
randomBatchSize = int(size/len(depthImageList))
x = np.array([])
y = np.array([])
z = np.array([])
xCurrent = self.state.kinematics_estimated.position.x_val
yCurrent = self.state.kinematics_estimated.position.y_val
zCurrent = self.state.kinematics_estimated.position.z_val
uav = np.array([xCurrent, yCurrent, zCurrent])
for depthImageRaw, depthImage, segmentedImage, camInfo in depthImageList:
r = np.random.uniform(0,min(halfHeight,halfWidth),randomBatchSize)
thetas = np.random.uniform(0,2*np.pi,randomBatchSize)
distTravel = np.random.uniform(0, maxDistTravel, randomBatchSize)
# Identify how many unique objects are in the segmented image
uni = np.unique(segmentedImage)
# find the closest point of each segment from the drone and map them
# as dictionary. segMinDist -> { objectID_1 -> 13.4 [meters],
# objectID_2 -> 33.4 [meters]}
segMinDist = {}
for objectID in uni:
# import pdb; pdb.set_trace()
segMinDist[objectID] = np.min( depthImage[segmentedImage == objectID] )
pointsHFloat = r*np.sin(thetas)
pointsWFloat = r*np.cos(thetas)
pointsH = centerH + pointsHFloat.astype(int)
pointsW = centerW + pointsWFloat.astype(int)
# Points from center of image to target pixels (= the line from current
# position towards the target position, in pixel coordinates)
widthSpaced = np.linspace(np.repeat(centerW,randomBatchSize), pointsW, int(halfWidth))
heightSpaced = np.linspace(np.repeat(centerH,randomBatchSize), pointsH, int(halfHeight))
# segmentID of the points in the line
# axis_0 -> line step
# axis_1 -> pertubation
segmentsSpaced = segmentedImage[widthSpaced.astype(int), heightSpaced.astype(int)]
segmentClosest = np.zeros(segmentsSpaced.shape)
for objectID, closestPoint in segMinDist.items():
segmentClosest[segmentsSpaced == objectID] = closestPoint
pertubationClosest = np.min( segmentClosest, axis=0)
valid = np.where( pertubationClosest > distTravel + safeDist)
xRelative, yRelative, zRelative = utils.vectorTo3D(pointsW, pointsH,
camInfo, depthImage,
maxDistView = self.maxDistView,
vectorDistances = distTravel)
xCommon, yCommon, zCommon = utils.to_absolute_coordinates(xRelative, yRelative, zRelative,
camInfo)
x = np.append(x, xCommon[valid])
y = np.append(y, yCommon[valid])
z = np.append(z, zCommon[valid])
safeCanditates = np.stack((x,y,z), axis=1)
return safeCanditates
def getPseudoLidar(self, size=1000):
depthImageList = [(self.imageDepthFrontRaw, self.cameraInfoFront),
(self.imageDepthBackRaw, self.cameraInfoBack)]
height, width, _ = self.imageScene.shape
halfWidth = width/2
halfHeight= height/2
randomPointsSize = int(size/len(depthImageList))
x = np.array([])
y = np.array([])
z = np.array([])
hullList = []
xCurrent = self.state.kinematics_estimated.position.x_val
yCurrent = self.state.kinematics_estimated.position.y_val
zCurrent = self.state.kinematics_estimated.position.z_val
uav = np.array([xCurrent, yCurrent, zCurrent])
for depthImage, camInfo in depthImageList:
r = np.random.uniform(0,min(halfHeight,halfWidth),randomPointsSize)
thetas = np.random.uniform(0,2*np.pi,randomPointsSize)
pointsH = r*np.sin(thetas)
pointsW = r*np.cos(thetas)
centerH = int(halfHeight)
centerW = int(halfWidth)
pointsH = centerH + pointsH.astype(int)
pointsW = centerW + pointsW.astype(int)
xRelative, yRelative, zRelative = utils.to3D(pointsW, pointsH,
camInfo, depthImage,
maxDistView = self.maxDistView)
xCommon, yCommon, zCommon = utils.to_absolute_coordinates(xRelative, yRelative, zRelative,
camInfo)
x = np.append(x, xCommon)
y = np.append(y, yCommon)
z = np.append(z, zCommon)
pointsHull = np.stack((xCommon, yCommon, zCommon), axis=1)
pointsHull = np.append(pointsHull, uav.reshape(1,3), axis=0)
hull = Delaunay(pointsHull)
hullList.append(hull)
lidarPoints = np.stack((x,y,z), axis=1)
return lidarPoints, hullList
def getPointCloudList(self, index=-1):
if abs(index) > len(self.pointCloud):
x,y,z,colors = self.pointCloud[-1]
else:
x,y,z,colors = self.pointCloud[index]
return x,y,z,colors
def appendContribution(self, contrib):
self.contribution.append(contrib)
def appendJi(self, Ji):
self.j_i.append(Ji)
def resetJi(self, resetStyle=""):
if resetStyle == "gradientInformationJ":
self.j_i = np.gradient(self.informationJ)
elif resetStyle == "directInformationJ":
self.j_i = self.informationJ.copy()
elif resetStyle == "deltaInformationJi":
self.j_i = self.informationJi.copy()
def getJi(self, index=-1):
return self.j_i[index]
def getJiList(self):
return self.j_i
def getDepthFront(self):
responses = self.client.simGetImages([
airsim.ImageRequest("1", airsim.ImageType.DepthPerspective, True)],
vehicle_name = self.name) #scene vision image in uncompressed RGB array
self.imageDepthFront = responses[0]
def getDepthImage(self):
#TODO: replace simGetImages with self.getImages -> save depth image
responses = self.client.simGetImages([
airsim.ImageRequest("0", airsim.ImageType.DepthPerspective, True)],
vehicle_name = self.name) #scene vision image in uncompressed RGB array
self.imageDepthCamera = responses[0]
return responses[0]
def stabilize(self):
task = self.client.moveByVelocityAsync(0,0,0,4,vehicle_name=self.name)
return task
def moveToZ(self, targetZ, speedClim=3.0):
self.altitude = targetZ
task = self.client.moveToZAsync(targetZ,speedClim,vehicle_name=self.name)
return task
def rotateYawRelative(self, relavtiveYaw):
""" Relative rotate in degrees"""
self.client.rotateByYawRateAsync(relavtiveYaw,1,vehicle_name=self.name).join()
self.client.rotateByYawRateAsync(0,1,vehicle_name=self.name).join()
def rotateToYaw(self, yaw):
self.updateMultirotorState()
_,_,currentYaw = airsim.to_eularian_angles(self.state.kinematics_estimated.orientation)
self.client.rotateByYawRateAsync(float(yaw) - np.degrees(currentYaw),1,vehicle_name=self.name).join()
self.client.rotateByYawRateAsync(0,1,vehicle_name=self.name).join()
# self.client.rotateToYawAsync(yaw, vehicle_name=self.name).join()
def setGeoFence(self, geofence):
"""Applying geo fence as object"""
self.geoFence = geofence
def insideGeoFence(self, d=5., c=[]):
if type(c) is list:
x,y,z = c
dist = np.sqrt( (self.fenceX-x)**2 + (self.fenceY-y)**2 + (self.fenceZ-z)**2)
elif type(c) is np.ndarray:
# in that case c=[[x1,y1,z1],[x2,y2,z2],[x3,y3,z3] ...]
dist = scipy.spatial.distance.cdist(c, [np.array([self.fenceX, self.fenceY, self.fenceZ])])
return (dist+d) < self.fenceR
def applyGeoFence(self):
if DEBUG_GEOFENCE:
print(f"\n-- Checking Geo Fence for {self.getName()}")
droneX = self.state.kinematics_estimated.position.x_val
droneY = self.state.kinematics_estimated.position.y_val
droneZ = self.state.kinematics_estimated.position.z_val
dist = np.sqrt( (self.fenceX - droneX)**2 + (self.fenceY - droneY)**2
+ (self.fenceZ - droneZ)**2)
if DEBUG_GEOFENCE:
print(f" Sphere (x:{self.fenceX:.2f}, y:{self.fenceY:.2f}, z:{self.fenceZ:.2f}, R:{self.fenceR:.2f}) ")
print(f" {self.getName()} (x:{droneX:.2f}, y:{droneY:.2f}, z:{droneZ:.2f}, dist:{dist:.2f}) ")
if dist >= self.fenceR:
# OA -> X-Y origin to drone position
# OC -> X-Y origin to sphere center
# AC -> Drone to sphere
acX = self.fenceX - droneX
acY = self.fenceY - droneY
acYaw = np.arctan2(acY, acX)
_,_,currentYaw = airsim.to_eularian_angles(self.state.kinematics_estimated.orientation)
# turn -> how much the drone must turn in order to orient itself towards the speher's center
turn = acYaw - currentYaw
if DEBUG_GEOFENCE:
print(f" Applying Geo Fence yaw:{np.degrees(currentYaw):.2f} acYaw:{np.degrees(acYaw):.2f} turn:{np.degrees(turn):.2f}")
# XXX: airsim function rotateToYaw seems not to perform correctly ...
self.client.rotateByYawRateAsync(np.degrees(turn),1,vehicle_name=self.name).join()
self.client.rotateByYawRateAsync(0,1,vehicle_name=self.name).join()
# self.state = self.getState()
self.updateMultirotorState()
def move(self, randomPointsSize=70, maxTravelTime=5., minDist=5., plotEstimator=True):
axiZ = self.altitude
speedScalar = 2
np.random.seed()
# camera field of view (degrees)
camFOV = self.cameraInfo.fov
leftDeg, rightDeg = -camFOV/2 , camFOV/2
maxTries = 12
availablePosition = False
for i in range(maxTries):
# self.state = self.getState()
self.updateMultirotorState()
_,_,currentYaw = airsim.to_eularian_angles(self.state.kinematics_estimated.orientation)
self.getDepthFront()
imageDepth = airsim.list_to_2d_float_array(self.imageDepthFront.image_data_float,
self.imageDepthFront.width,
self.imageDepthFront.height)
height, width = self.imageDepthFront.height, self.imageDepthFront.width
pixel10H = height*0.1
lowHeight, highHeight = int(height/2-pixel10H), int(height/2+pixel10H)
wLow, wHigh = int(width*0.1) ,int(width*0.1)
# boundaries should be avoided for collision avoidance (thats what +/- 3 degrees do ...)
randomOrientation = np.random.uniform(np.radians(leftDeg/ORIENTATION_DEV), np.radians(rightDeg/ORIENTATION_DEV), randomPointsSize)
# travelTime = np.random.uniform(0, maxTravelTime, randomPointsSize)
travelTime = np.random.uniform(0., maxTravelTime, randomPointsSize)
yawCanditate = np.random.uniform(leftDeg/CAM_DEV,rightDeg/CAM_DEV,randomPointsSize)
# validPoint = []
jPoint = []
xCanditateList = []
yCanditateList = []
yawAngleList = []
for i in range(randomPointsSize):
wCenter = int( width * ( ( np.degrees(randomOrientation[i]) + camFOV/2 ) / camFOV ) )
if wCenter - wLow < 0: wCenter = wLow + 1
if wCenter + wHigh> (width-1): wCenter = wHigh + 1
# print(f"{self.getName()} wCenter:{wCenter}")
dist = np.min(imageDepth[ (wCenter-wLow) : (wCenter+wHigh), lowHeight:highHeight])
safeDist = dist>(travelTime[i]*speedScalar + minDist)
xCurrent = self.state.kinematics_estimated.position.x_val
yCurrent = self.state.kinematics_estimated.position.y_val
zCurrent = self.state.kinematics_estimated.position.z_val
xCanditate = xCurrent + np.cos(randomOrientation[i] + currentYaw)*speedScalar*travelTime[i]
yCanditate = yCurrent + np.sin(randomOrientation[i] + currentYaw)*speedScalar*travelTime[i]
zCanditate = zCurrent
angle = np.radians(yawCanditate[i]) + currentYaw + randomOrientation[i]
xCanditateList.append(xCanditate)
yCanditateList.append(yCanditate)
yawAngleList.append(angle)
canditates = [xCanditate,yCanditate,zCanditate]
inGeoFence = self.insideGeoFence(c = canditates, d = minDist)
# the estimated score each canditate point has
if safeDist and inGeoFence:
jPoint.append(self.estimate(xCanditate, yCanditate, angle))
availablePosition = True
else:
# canditate position is outside geo-fence or on collision
jPoint.append(-1000.)
if availablePosition:
break
else:
# there is no avaoilable point tin the current orientation, change it
print(f"\n[WARNING][MOVE] There is no available position for {self.getName()}, changing orientation")
# rotateByYawRateAsync takes as input degres
self.client.rotateByYawRateAsync(30,1,vehicle_name=self.name).join()
self.client.rotateByYawRateAsync(0,1,vehicle_name=self.name).join()
tartgetPointIndex = np.argmax(jPoint)
anglesSpeed = currentYaw + randomOrientation[tartgetPointIndex]
vx = np.cos(anglesSpeed)
vy = np.sin(anglesSpeed)
# travelTime = np.random.uniform(maxTravelTime)
self.client.moveByVelocityZAsync(speedScalar*vx, speedScalar*vy, axiZ, travelTime[tartgetPointIndex],
airsim.DrivetrainType.ForwardOnly,
airsim.YawMode(False, 0),
vehicle_name=self.name).join()
self.stabilize().join()
self.client.rotateByYawRateAsync(yawCanditate[tartgetPointIndex],1,vehicle_name=self.name).join()
self.client.rotateByYawRateAsync(0,1,vehicle_name=self.name).join()
if plotEstimator:
self.plotEstimator(xCanditateList, yCanditateList, yawAngleList, jPoint)
if DEBUG_MOVE:
print(f"\n[DEBUG][MOVE] ----- {self.getName()} -----")
print(f"[DEBUG][MOVE] randomOrientation: {np.degrees(randomOrientation)}")
print(f"[DEBUG][MOVE] travelTime: {travelTime}")
print(f"[DEBUG][MOVE] yawCanditate: {yawCanditate}")
print(f"[DEBUG][MOVE] jPoint: {jPoint}")
print(f"[DEBUG][MOVE] tartgetPointIndex: {tartgetPointIndex}")
def getPeripheralView(self):
imageDepth = []
imageDepthFront = self.imageDepthFront
imageDepth.append(imageDepthFront)
imageDepthBack = self.imageDepthBack
imageDepth.append(imageDepthBack)
return imageDepth, self.imageDepthPeripheralHeight, self.imageDepthPeripheralWidth
def getCanditates(self, randomPointsSize=70, maxTravelTime=5., minDist=5., maxYaw=15.):
speedScalar = 1
np.random.seed()
self.updateMultirotorState()
_,_,currentYaw = airsim.to_eularian_angles(self.state.kinematics_estimated.orientation)
# camera field of view (degrees)
camFOV = self.cameraInfo.fov
leftDeg, rightDeg = -camFOV/2 , camFOV/2
imageDepthList, height, width = self.getPeripheralView()
# height, width = imageDepthList[0].height, imageDepthList[0].width
pixel10H = height*0.1
lowHeight, highHeight = int(height/2-pixel10H), int(height/2+pixel10H)
wLow, wHigh = int(width*0.1) ,int(width*0.1)
jEstimated = []
xCanditateList = []
yCanditateList = []
zCanditateList = []
yawCanditateList = []
# decreasing the available movement because we are getting closer to convergence point
# initialy we wan to explore and then exploit more carefully
a = self.restrictingMovement[self.posIdx]
counter = 0
inGeoFenceCounter = 0
inSafeDistCounter = 0
while (jEstimated == []) and (counter<360):
counter += 1
if counter>1:
print(f"[CANDITATES] {self.getName()} regeting images ... ")
print(f"[CANDITATES] {self.getName()} has canditates inGeoFence={inGeoFenceCounter}, inSafeDist={inSafeDistCounter}")
self.rotateYawRelative(10)
self.updateMultirotorState()
_,_,currentYaw = airsim.to_eularian_angles(self.state.kinematics_estimated.orientation)
print(f"[CANDITATES] {self.getName()} rotating in order to find canditates (currentYaw={np.degrees(currentYaw):.3f}) move more freely (no restrictingMovement)")
a = 2
self.getImages()
imageDepthList, height, width = self.getPeripheralView()
inGeoFenceCounter = 0
inSafeDistCounter = 0
for imageIdx,imageDepth in enumerate(imageDepthList):
# boundaries should be avoided for collision avoidance (thats what +/- 3 degrees do ...)
randomOrientation = np.random.uniform(np.radians(leftDeg + 5), np.radians(rightDeg - 5), randomPointsSize)
# travelTime = np.random.uniform(0, maxTravelTime, randomPointsSize)
travelTime = np.random.uniform(0., maxTravelTime, randomPointsSize)
yawCanditate = np.random.uniform(np.degrees(currentYaw) - (maxYaw/2)*a, np.degrees(currentYaw) + (maxYaw/2)*a, randomPointsSize)
for i in range(randomPointsSize):
wCenter = int( width * ( ( np.degrees(randomOrientation[i]) + camFOV/2 ) / camFOV ) )
if wCenter - wLow < 0: wCenter = wLow + 1
if wCenter + wHigh> (width-1): wCenter = wHigh + 1
# print(f"{self.getName()} wCenter:{wCenter}")
dist = np.min(imageDepth[ (wCenter-wLow) : (wCenter+wHigh), lowHeight:highHeight])
safeDist = dist>(travelTime[i]*speedScalar*a + minDist)
xCurrent = self.state.kinematics_estimated.position.x_val
yCurrent = self.state.kinematics_estimated.position.y_val
zCurrent = self.state.kinematics_estimated.position.z_val
xCanditate = xCurrent + np.cos( (randomOrientation[i] + imageIdx*np.pi) + currentYaw)*speedScalar*travelTime[i]*a
yCanditate = yCurrent + np.sin( (randomOrientation[i] + imageIdx*np.pi) + currentYaw)*speedScalar*travelTime[i]*a
zCanditate = zCurrent
canditates = [xCanditate,yCanditate,zCanditate]
inGeoFence = self.insideGeoFence(c = canditates, d = minDist)
if safeDist: inSafeDistCounter += 1
if inGeoFence: inGeoFenceCounter += 1
# the estimated score each canditate point has
if safeDist and inGeoFence:
jEstimated.append(self.estimate(xCanditate, yCanditate, np.radians(yawCanditate[i]) ))
xCanditateList.append(xCanditate)
yCanditateList.append(yCanditate)
zCanditateList.append(zCanditate)
yawCanditateList.append(yawCanditate[i])
return jEstimated, xCanditateList, yCanditateList, zCanditateList, yawCanditateList
def plotCanditates(self, xCanditate, yCanditate, zCanditate, isSafeDist, lidarPoints):
report_canditates = os.path.join(os.getcwd(),f"results_{self.ip}", f"canditates_{self.getName()}")
try:
os.makedirs(report_canditates)
except OSError:
if not os.path.isdir(report_canditates):
raise
# add the lidar point cloud
plt.scatter( lidarPoints[:,1], lidarPoints[:,0], c="green", label="Lidar")
# safe canditates plot
safeDistTrue = np.where(np.array(isSafeDist)==True)[0]
# print(f"[DEBUG_CANDITATES]{self.getName()} has safeDist={len(safeDistTrue)}")
plt.scatter(yCanditate[safeDistTrue], xCanditate[safeDistTrue], c="blue", label="Safe")
# not safe canditates
safeDistFalse = np.where(np.array(isSafeDist)==False)[0]
# print(f"[DEBUG_CANDITATES]{self.getName()} has not safe ={len(safeDistFalse)}")
plt.scatter(yCanditate[safeDistFalse], xCanditate[safeDistFalse], c="red", label="Not Safe")
plt.xlabel("Y-Axis (network)")
plt.ylabel("X-Axis (network)")
try:
canditates_file = os.path.join(report_canditates, f"canditates_{self.posIdx}.png")
# plt.title(f"{self.getName()} - Time:{self.timeStep} - Canditates")
except:
canditates_file = os.path.join(report_canditates, f"canditates_{0}.png")
plt.tight_layout()
plt.legend()
plt.savefig(canditates_file)
plt.close()
def getLidarData(self, save_lidar=False):
# print(f"Getting lidar data for {self.getName()} from {self.lidarName}")
for test in range(10):
lidarData = self.client.getLidarData(lidar_name = self.lidarName,
vehicle_name = self.getName())
points = np.array(lidarData.point_cloud, dtype=np.dtype('f4'))
if points.size != 0:
break
# getLidarData failed ... wait and try to get lidar data again
time.sleep(1)
points = np.reshape(points, (int(points.shape[0]/3), 3))
if save_lidar:
filenameLidar = os.path.join(self.raw_dir, f"lidar_time_{self.timeStep}" )
np.save(filenameLidar, points)
return points
def clearLidarPoints(self, lidarPoints=[], maxTravelTime=5., controllers=[]):
initialSize = len(lidarPoints)
xCurrent = self.state.kinematics_estimated.position.x_val
yCurrent = self.state.kinematics_estimated.position.y_val
zCurrent = self.state.kinematics_estimated.position.z_val
droneCurrent = np.array([xCurrent, yCurrent, zCurrent])
distLidar2Drone = scipy.spatial.distance.cdist(lidarPoints, [droneCurrent])
lidarPoints = lidarPoints[np.where(distLidar2Drone<=maxTravelTime*10.)[0]]
for ctrl in controllers:
if ctrl.getName() != self.getName():
state = ctrl.getState()
xCurrent = state.kinematics_estimated.position.x_val
yCurrent = state.kinematics_estimated.position.y_val
zCurrent = state.kinematics_estimated.position.z_val
ctrlCurrent = np.array([xCurrent, yCurrent, zCurrent])
distLidar2Drone = scipy.spatial.distance.cdist(lidarPoints, [ctrlCurrent])
lidarPoints = lidarPoints[np.where(distLidar2Drone>=3.)[0]]
# if DEBUG_CLEAR_LIDAR:
# print(f"{self.getName()} excluding lidar from {ctrl.getName()} excluded size {len(np.where(distLidar2Drone<2.)[0])}")
if DEBUG_CLEAR_LIDAR:
print(f"[DEBUG_CLEAR_LIDAR]{self.getName()} initial lidar points {initialSize} cleared {len(lidarPoints)}")
return lidarPoints
def addOffsetLidar(self, lidarPoints=[]):
offset = np.array([self.offSetX, self.offSetY, self.offSetZ])
points = lidarPoints + offset
return points
def distLine2Point(self, p1, p2, p3):
"""Distance from line p1p2 and point p3"""
# return np.linalg.norm(np.cross(p2-p1, p1-p3))/np.linalg.norm(p2-p1)
"""Distance from line p2(canditate) and point p3(lidar point)"""
return np.linalg.norm(p2-p3)
def isSafeDist(self,canditate=[], lidarPoints=[], minDist=5.):
xCurrent = self.state.kinematics_estimated.position.x_val
yCurrent = self.state.kinematics_estimated.position.y_val
zCurrent = self.state.kinematics_estimated.position.z_val
droneCurrent = np.array([xCurrent, yCurrent, zCurrent])
if canditate.shape==(3,):
for point in lidarPoints:
dist = self.distLine2Point(droneCurrent, canditate, point)
if dist<minDist:
return False
return True
else:
# canditate = [[x1,y1,z1],[x2,y2,z2],[]]
# canditateList = []
# for x,y,z in canditate:
# cand = np.array([x,y,z])
# for point in lidarPoints:
# dist = self.distLine2Point(droneCurrent, cand, point)
# if dist<minDist:
# canditateList.append(False)
# break
# canditateList.append(True)
# return canditateList
dist = scipy.spatial.distance.cdist(lidarPoints, canditate)
distMin = np.min(dist, axis=0)
return distMin>minDist
def getCanditatesLidar(self, randomPointsSize=70, maxTravelTime=5.,
minDist=5., maxYaw=15., controllers=[],
saveLidar=False):
speedScalar = 1
np.random.seed()
self.updateMultirotorState()
_,_,currentYaw = airsim.to_eularian_angles(self.state.kinematics_estimated.orientation)
xCurrent = self.state.kinematics_estimated.position.x_val
yCurrent = self.state.kinematics_estimated.position.y_val
zCurrent = self.state.kinematics_estimated.position.z_val
# decreasing the available movement because we are getting closer to convergence point
# initialy we wan to explore and then exploit more carefully
a = self.restrictingMovement[self.posIdx]
for helperIcreasedMove in np.linspace(1,5,40):
if DEBUG_CANDITATE_LIDAR:
print(f"{self.getName()} has helperIcreasedMove={helperIcreasedMove}")
# [-np.pi, np.pi] canditates are inside a shpere with radius=maxTravelTime
randomOrientation = np.random.uniform(-np.pi, np.pi, randomPointsSize)
travelTime = np.random.uniform(0., maxTravelTime, randomPointsSize)
yawCanditate = np.random.uniform(np.degrees(currentYaw) - (maxYaw/2)*a, np.degrees(currentYaw) + (maxYaw/2)*a, randomPointsSize)
lidarPoints = self.getLidarData(save_lidar=saveLidar)
lidarPoints = self.clearLidarPoints(lidarPoints=lidarPoints,
maxTravelTime=maxTravelTime,
controllers=controllers)
lidarPoints = self.addOffsetLidar(lidarPoints=lidarPoints)
if DEBUG_LIDAR_DIST:
droneCurrent = np.array([xCurrent, yCurrent, zCurrent])
dist = scipy.spatial.distance.cdist(lidarPoints, [droneCurrent])
print(f"[DEBUG_LIDAR_DIST]{self.getName()} has minDist={minDist} min.dist.(drone,lidar)={np.min(dist)}")
xCanditate = xCurrent + np.cos(randomOrientation)*speedScalar*travelTime*a*helperIcreasedMove
yCanditate = yCurrent + np.sin(randomOrientation)*speedScalar*travelTime*a*helperIcreasedMove
zCanditate = np.repeat(zCurrent,len(xCanditate))
canditates = np.stack((xCanditate,yCanditate,zCanditate),axis=1)
inGeoFence = self.insideGeoFence(c = canditates, d = minDist)
isSafeDist = self.isSafeDist(canditate = canditates,
lidarPoints = lidarPoints,
minDist = minDist)
# print(f"{self.getName()} isSafeDist={len(isSafeDist)}")
# print(f"{self.getName()} inGeoFence={len(inGeoFence)}")
geoFenceSafe = np.where(inGeoFence==True)[0]
safeDistTrue = np.where(np.array(isSafeDist)==True)[0]
validCandidatesIndex = np.intersect1d(geoFenceSafe, safeDistTrue)
# print(f"{self.getName()} validCandidatesIndex={validCandidatesIndex} ")
if PLOT_CANDITATES:
self.plotCanditates(xCanditate, yCanditate, zCanditate, isSafeDist, lidarPoints)
if validCandidatesIndex.size == 0: