-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrobotarium_main.py
2158 lines (1897 loc) · 89.6 KB
/
robotarium_main.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
import functools
import sys
import numpy as np
import random
import time
## Not required for the physical runs
import os
import pandas as pd
import openpyxl
import threading
## ----------------------------------
import rps.robotarium as robotarium
from rps.utilities.transformations import *
from rps.utilities.barrier_certificates import *
from rps.utilities.misc import *
from rps.utilities.controllers import *
from rps.utilities.graph import *
from robotarium_init import *
"""
The main file for robotarium based simulations is same as the discrete simulation's main
file however functions like bfs, bfsNearestTask, dirShortestPath are brought over
from utils file and customized for continous space to enable a concise codebase to be submitted
to robotarium for physical robot simulations
Also contains additional code for robotarium specific implementation of robot simulations
"""
# Direction radians
NORTH = 1.5708
SOUTH = 4.71239
WEST = 3.1419
EAST = 0.0000
BASE_DIR = [0, 1]
wait_time = 0
totalCost = 0
A, numTasks, k, psi, wall_prob, seed, only_base_policy, exp_seed = getParameters()
centralized = False
visualizer = False
collisions = False
exp_strat = 0
rows = 9
cols = 9
size = 9
step = 0.2
verbose = '-1'
new_data = {'Centralized':str(centralized), 'Seed #': str(seed), 'Exp Seed #': str(exp_seed),
'Rows': str(rows), 'Cols': str(cols), 'Wall Prob': str(wall_prob),
'# of Agents': str(A), '# of Tasks': str(numTasks), 'k': str(k),
'psi': str(psi), 'Only Base Policy': str(only_base_policy)}
vertices=[]
global colors
colors=[]
for i in range(100):
colors+=[1,2,3,4,5,6,7,8,9,10,12,13,14,15,16,17,18,
19,20,21,22,23,24,25,26,27,28,29,30,31]
colorIndex = ['#FDD835',
'#E53935',
'#03A9F4',
'#78909C',
'#8BC34A',
'#7E57C2',
'#26C6DA',
'#827717',
'#9C27B0',
'#8D6E63',
'none',
'#FDD835',
'#E53935',
'#03A9F4',
'#78909C',
'#8BC34A',
'#7E57C2',
'#26C6DA',
'#827717',
'#9C27B0',
'#8D6E63',
'#FDD835',
'#E53935',
'#03A9F4',
'#78909C',
'#8BC34A',
'#7E57C2',
'#26C6DA',
'#827717',
'#9C27B0',
'#8D6E63',
'#FDD835']
marker_shapes = ['none','s','o','P', 'H', 'X', 'D','*', '^','p', '1','s','o','*', '^','p','P', 'H', 'X', 'D', '1','s','o','*', '^','p','P', 'H', 'X', 'D', '1',]
out = init_valid_grid(A, numTasks, wall_prob=wall_prob,
seed=seed, colis=collisions)
gridGraph = out['gridGraph']
adjList = out['adjList']
vertices = out['verts']
agentVertices = out['agnt_verts']
taskVertices = out['task_verts']
obstacles = out["obs_verts"]
edgeList = out["adjList"]
obs_dir = out["obs_dir"]
random.seed(exp_seed)
## Uncomment below for better graphics in robotarium
# x_obs = [-1.0, 1]
# for x in x_obs:
# for y in np.arange(1.0, -1.2, -0.2):
# obstacles.append((x,round(y,1)))
# obs_dir.append(1)
## --------------------------------------------------
for vertex in vertices:
assert (vertex,vertex) in adjList
## truncate task list to accomodate lesser number of tasks
assert len(taskVertices) >= numTasks
if len(taskVertices) != numTasks:
delete_inds = random.sample(range(len(taskVertices)),
len(taskVertices)-numTasks)
tasks = [taskVertices[i] for i in range(len(taskVertices)) \
if i not in delete_inds]
taskVertices = tasks
assert len(taskVertices) == numTasks
for i in range(len(taskVertices)):
colors+=[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]
N = len(vertices)
N = 2**(psi+1)
def getTasksWithinRadius(agent_pos, taskVertices, radius):
visible_tasks = []
for t in taskVertices:
if np.linalg.norm(np.asarray(t)-agent_pos)<=radius:
visible_tasks.append(t)
return visible_tasks
def bfs(vertices, edges, root, goal):
Q = []
labels = {}
for v in vertices:
if v[0] == 0 and v[1] == 0:
tup = (0.0, 0.0)
labels[str(tup)] = False
elif v[0] == 0:
tup = (0.0, v[1])
labels[str(tup)] = False
elif v[1] == 0:
tup = (v[0], 0.0)
labels[str(tup)] = False
else:
labels[str(v)] = False
Q.append(root)
labels[str(root)] = True
while (len(Q)) > 0:
v = Q.pop(0)
if v == goal:
return True
for e in edges:
if e[0] == v:
if e[1][0] == 0 and e[1][1] == 0:
tup = (0.0, 0.0)
elif e[1][0] == 0:
tup = (0.0, e[1][1])
elif e[1][1] == 0:
tup = (e[1][0], 0.0)
else:
tup = (e[1][0], e[1][1])
if labels[str(tup)] == False:
labels[str(tup)] = True
Q.append(tup)
return False
def bfsNearestTask(networkVertices, networkEdges, source, taskVertices):
Q = []
labels = {}
prev = {}
prev[str(source)] = None
dist = -1
for v in networkVertices:
if v[0] == 0 and v[1] == 0:
tup = (0.0, 0.0)
labels[str(tup)] = False
elif v[0] == 0:
tup = (0.0, v[1])
labels[str(tup)] = False
elif v[1] == 0:
tup = (v[0], 0.0)
labels[str(tup)] = False
else:
labels[str(v)] = False
Q.append(source)
labels[str(source)] = True
while(len(Q)) > 0:
v = Q.pop(0)
for edge in networkEdges:
if edge[0] == v:
if edge[1][0] == 0 and edge[1][1] == 0:
tup = (0.0, 0.0)
elif edge[1][0] == 0:
tup = (0.0, edge[1][1])
elif edge[1][1] == 0:
tup = (edge[1][0], 0.0)
else:
tup = (edge[1][0], edge[1][1])
if labels[str(tup)] == False:
labels[str(tup)] = True
prev[str(tup)] = v
Q.append(tup)
if tup in taskVertices:
t = tup
if prev[str(t)] != None or t==source:
path = []
while t != None:
path.append(t)
t = prev[str(t)]
dist += 1
return dist, list(reversed(path))
return None,None
def dirShortestPath(networkVertices,networkEdges,source,target):
Q=[]
dist={}
prev={}
assert target in networkVertices
assert source in networkVertices
for v in networkVertices:
if v[0] == 0 and v[1] == 0:
tup = (0.0, 0.0)
elif v[0] == 0:
tup = (0.0, v[1])
elif v[1] == 0:
tup = (v[0], 0.0)
else:
tup = v
dist[str(tup)]= 9999999999
prev[str(tup)]=None
Q.append(tup)
dist[str(source)]=0
while len(Q)>0:
uNum=9999999999
u=None
for q in Q:
if dist[str(q)]<=uNum:
u=q
uNum=dist[str(q)]
Q.remove(u)
if u == target:
S=[]
if target[0] == 0 and target[1] == 0:
t0 = (0.0, 0.0)
elif target[0] == 0:
t0 = (0.0, target[1])
elif target[1] == 0:
t0 = (target[0], 0.0)
else:
t0 = target
t = t0
if prev[str(t)] != None or t==source:
while t != None:
S.append(t)
t=prev[str(t)]
return dist[str(t0)],list(reversed(S))
for e in networkEdges:
if e[0]==u:
if e[1][0] == 0 and e[1][1] == 0:
tup = (0.0, 0.0)
elif e[1][0] == 0:
tup = (0.0, e[1][1])
elif e[1][1] == 0:
tup = (e[1][0], 0.0)
else:
tup = (e[1][0], e[1][1])
alt = dist[str(u)]+1
if alt < dist[str(tup)]:
dist[str(tup)]=alt
prev[str(tup)]=u
return None, None
class Agent:
def __init__(self,x,y,orient,ID,color=1):
self.posX=x
self.posY=y
self.orientation = orient
self.prev_move = None
self.cost=0
self.color=color
self.ID=ID
self.copy_number = 1
self.posX_prime = x
self.posY_prime = y
self.cost_prime = 0
self.color_prime = color
self.exploring = False
self.exp_dir = ''
self.exp_dist_remaining = 0
self.reset()
def resetColor(self):
self.color=11
self.color_prime=11
sys.stdout.flush()
def deallocate(self):
del self.clusterID, self.children, self.stateMem, self.viewEdges
del self.viewVertices, self.viewAgents, self.viewTasks, self.clusterVertices
del self.clusterEdges, self.clusterTasks, self.clusterAgents
del self.localVertices, self.localTasks, self.localEdges, self.localAgents
del self.childMarkers, self.moveList
del self.clusterID_prime, self.children_prime, self.stateMem_prime, self.viewEdges_prime
del self.viewVertices_prime, self.viewAgents_prime, self.viewTasks_prime, self.clusterVertices_prime
del self.clusterEdges_prime, self.clusterTasks_prime, self.clusterAgents_prime
del self.localVertices_prime, self.localTasks_prime, self.localEdges_prime, self.localAgents_prime
del self.childMarkers_prime, self.moveList_prime
def reset(self):
self.dir=''
self.clusterID=[]
self.parent=None
self.children=[]
self.stateMem=[]
self.viewEdges=set()
self.viewVertices=set([(self.posX,self.posY)])
self.viewAgents=set()
self.viewTasks=set()
self.eta=0
self.message=False
self.clusterVertices=set()
self.clusterEdges=set()
self.clusterTasks=set()
self.clusterAgents={}
self.localVertices=set()
self.localEdges=set()
self.localTasks=set()
self.localAgents=set()
self.childMarkers=[]
self.xOffset=0
self.yOffset=0
self.resetCounter=0
self.moveList=dict()
self.marker=False
self.dfsNext=False
self.dir_prime=''
self.clusterID_prime=[]
self.parent_prime=None
self.children_prime=[]
self.stateMem_prime=[]
self.viewEdges_prime=set()
self.viewVertices_prime=set([(self.posX,self.posY)])
self.viewAgents_prime=set()
self.viewTasks_prime=set()
self.eta_prime=0
self.message_prime=False
self.clusterVertices_prime=set()
self.clusterEdges_prime=set()
self.clusterTasks_prime=set()
self.clusterAgents_prime={}
self.localVertices_prime=set()
self.localEdges_prime=set()
self.localTasks_prime=set()
self.localAgents_prime=set()
self.childMarkers_prime=[]
self.xOffset_prime=0
self.yOffset_prime=0
self.resetCounter_prime=0
self.moveList_prime=dict()
self.marker_prime=False
self.dfsNext_prime=False
def setXPos(self,x):
self.posX=x
def setYPos(self,y):
self.posY=y
def setOrientation(self, orient):
self.orientation = orient
def getCostIncurred(self):
return self.cost
def getDir(self):
return self.dir
def move(self,dir):
self.dir=dir
def getColor(self):
return self.color
def getCluster(self):
return self.clusterID
def updateView(self, poses):
self.viewEdges = set()
self.viewEdges.add(((self.posX, self.posY), (self.posX, self.posY)))
self.viewVertices = set([(self.posX, self.posY)])
self.viewAgents = set()
self.viewTasks = set()
self.viewEdges_prime = set()
self.viewEdges_prime.add(
((self.posX, self.posY), (self.posX, self.posY)))
self.viewVertices_prime = set([(self.posX, self.posY)])
self.viewAgents_prime = set()
self.viewTasks_prime = set()
# Create Internal Representation
# k = hops
# for each hop
agent_pos = poses[:2,self.ID-1]
visible_tasks = getTasksWithinRadius(agent_pos, taskVertices, step*k+(step*0.25))
for i in range(1, k+1):
# One hop in each direction
up = round(self.posY+i*step, 1)
down = round(self.posY-i*step, 1)
left = round(self.posX-i*step, 1)
right = round(self.posX+i*step, 1)
# check if it exist in the grid bounds
if (right, self.posY) in vertices:
self.viewVertices.add((right, self.posY))
self.viewVertices_prime.add((right, self.posY))
if any([np.linalg.norm(np.asarray(t)-np.asarray((right, self.posY)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((right, self.posY))
self.viewTasks_prime.add((right, self.posY))
# for remaining hops
for j in range(1, k-i+1):
up_steps = round(self.posY+j*step, 1)
down_steps = round(self.posY-j*step, 1)
if (right, up_steps) in vertices:
self.viewVertices.add((right, up_steps))
self.viewVertices_prime.add((right, up_steps))
if any([np.linalg.norm(np.asarray(t)-np.asarray((right, up_steps)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((right, up_steps))
self.viewTasks_prime.add(
(right, up_steps))
if (right, down_steps) in vertices:
self.viewVertices.add((right, down_steps))
self.viewVertices_prime.add((right, down_steps))
if any([np.linalg.norm(np.asarray(t)-np.asarray((right, down_steps)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((right, down_steps))
self.viewTasks_prime.add(
(right, down_steps))
# check if it exist in the grid bounds
if (left, self.posY) in vertices:
self.viewVertices.add((left, self.posY))
self.viewVertices_prime.add((left, self.posY))
if any([np.linalg.norm(np.asarray(t)-np.asarray((left, self.posY)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((left, self.posY))
self.viewTasks_prime.add((left, self.posY))
for j in range(1, k-i+1):
up_steps = round(self.posY+j*step, 1)
down_steps = round(self.posY-j*step, 1)
if (left, up_steps) in vertices:
self.viewVertices.add((left, up_steps))
self.viewVertices_prime.add((left, up_steps))
if any([np.linalg.norm(np.asarray(t)-np.asarray((left, up_steps)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((left, up_steps))
self.viewTasks_prime.add(
(left, up_steps))
if (left, down_steps) in vertices:
self.viewVertices.add((left, down_steps))
self.viewVertices_prime.add((left, down_steps))
if any([np.linalg.norm(np.asarray(t)-np.asarray((left, down_steps)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((left, down_steps))
self.viewTasks_prime.add(
(left, down_steps))
# check if it exist in the grid bounds
if (self.posX, up) in vertices:
self.viewVertices.add((self.posX, up))
self.viewVertices_prime.add((self.posX, up))
if any([np.linalg.norm(np.asarray(t)-np.asarray((self.posX, up)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((self.posX, up))
self.viewTasks_prime.add((self.posX, up))
for j in range(1, k-i+1):
right_steps = round(self.posX+j*step, 1)
left_steps = round(self.posX-j*step, 1)
if (right_steps, up) in vertices:
self.viewVertices.add((right_steps, up))
self.viewVertices_prime.add((right_steps, up))
if any([np.linalg.norm(np.asarray(t)-np.asarray((right_steps, up)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((right_steps, up))
self.viewTasks_prime.add(
(right_steps, up))
if (left_steps, up) in vertices:
self.viewVertices.add((left_steps, up))
self.viewVertices_prime.add((left_steps, up))
if any([np.linalg.norm(np.asarray(t)-np.asarray((left_steps, up)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((left_steps, up))
self.viewTasks_prime.add(
(left_steps, up))
# check if it exist in the grid bounds
if (self.posX, down) in vertices:
self.viewVertices.add((self.posX, down))
self.viewVertices_prime.add((self.posX, down))
if any([np.linalg.norm(np.asarray(t)-np.asarray((self.posX, down)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((self.posX, down))
self.viewTasks_prime.add((self.posX, down))
for j in range(1, k-i+1):
right_steps = round(self.posX+j*step, 1)
left_steps = round(self.posX-j*step, 1)
if (right_steps, down) in vertices:
self.viewVertices.add((right_steps, down))
self.viewVertices_prime.add((right_steps, down))
if any([np.linalg.norm(np.asarray(t)-np.asarray((right_steps, down)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((right_steps, down))
self.viewTasks_prime.add(
(right_steps, down))
if (left_steps, down) in vertices:
self.viewVertices.add((left_steps, down))
self.viewVertices_prime.add((left_steps, down))
if any([np.linalg.norm(np.asarray(t)-np.asarray((left_steps, down)))<=0.1 for t in visible_tasks]):
self.viewTasks.add((left_steps, down))
self.viewTasks_prime.add(
(left_steps, down))
for u in self.viewVertices:
up_edge = round(u[1]+1*step, 1)
down_edge = round(u[1]-1*step, 1)
left_edge = round(u[0]-1*step, 1)
right_edge = round(u[0]+1*step, 1)
if (right_edge, u[1]) in self.viewVertices:
self.viewEdges.add(((u[0], u[1]), (right_edge, u[1])))
self.viewEdges.add(((right_edge, u[1]), (u[0], u[1])))
if (left_edge, u[1]) in self.viewVertices:
self.viewEdges.add(((u[0], u[1]), (left_edge, u[1])))
self.viewEdges.add(((left_edge, u[1]), (u[0], u[1])))
if (u[0], up_edge) in self.viewVertices:
self.viewEdges.add(((u[0], u[1]), (u[0], up_edge)))
self.viewEdges.add(((u[0], up_edge), (u[0], u[1])))
if (u[0], down_edge) in self.viewVertices:
self.viewEdges.add(((u[0], u[1]), (u[0], down_edge)))
self.viewEdges.add(((u[0], down_edge), (u[0], u[1])))
for u in self.viewVertices_prime:
up_edge = round(u[1]+1*step, 1)
down_edge = round(u[1]-1*step, 1)
left_edge = round(u[0]-1*step, 1)
right_edge = round(u[0]+1*step, 1)
if (right_edge, u[1]) in self.viewVertices_prime:
self.viewEdges_prime.add(
((u[0], u[1]), (right_edge, u[1])))
self.viewEdges_prime.add(
((right_edge, u[1]), (u[0], u[1])))
if (left_edge, u[1]) in self.viewVertices_prime:
self.viewEdges_prime.add(((u[0], u[1]), (left_edge, u[1])))
self.viewEdges_prime.add(((left_edge, u[1]), (u[0], u[1])))
if (u[0], up_edge) in self.viewVertices_prime:
self.viewEdges_prime.add(((u[0], u[1]), (u[0], up_edge)))
self.viewEdges_prime.add(((u[0], up_edge), (u[0], u[1])))
if (u[0], down_edge) in self.viewVertices_prime:
self.viewEdges_prime.add(((u[0], u[1]), (u[0], down_edge)))
self.viewEdges_prime.add(((u[0], down_edge), (u[0], u[1])))
s = self.viewVertices.copy()
E = self.viewEdges.copy()
T = self.viewTasks.copy()
s_prime = self.viewVertices_prime.copy()
E_prime = self.viewEdges_prime.copy()
T_prime = self.viewTasks_prime.copy()
for u in s:
if u != (self.posX, self.posY) and not bfs(s, E, (self.posX, self.posY), u):
for e in E:
if (e[0] == u or e[1] == u) and e in self.viewEdges:
self.viewEdges.remove(e)
self.viewVertices.remove(u)
if u in T:
self.viewTasks.remove(u)
del s
for u in s_prime:
if u != (self.posX, self.posY) and not bfs(s_prime, E_prime, (self.posX, self.posY), u):
for e in E_prime:
if (e[0] == u or e[1] == u) and e in self.viewEdges_prime:
self.viewEdges_prime.remove(e)
self.viewVertices_prime.remove(u)
if u in T_prime:
self.viewTasks_prime.remove(u)
del s_prime
def mapOffset(self,offX,offY,mapVerts,mapEdges,mapTasks,mapAgents):
vertices = set()
edges = set()
taskSet = set()
agentSet = {}
for v in mapVerts:
vertices.add((round(v[0]-offX, 1), round(v[1]-offY, 1)))
for e in mapEdges:
newEdge = ((round(e[0][0]-offX, 1), round(e[0][1]-offY, 1)),
(round(e[1][0]-offX, 1), round(e[1][1]-offY, 1)))
edges.add(newEdge)
for t in mapTasks:
taskSet.add((round(t[0]-offX, 1), round(t[1]-offY, 1)))
for a in mapAgents:
agentSet[a.ID] = (offX, offY)
return [vertices,edges,taskSet,agentSet]
def updateLocalView(self):
l=self.mapOffset(self.posX,self.posY,self.viewVertices,self.viewEdges,self.viewTasks,self.viewAgents)
self.localVertices=l[0]
self.localEdges=l[1]
self.localTasks=l[2]
self.localAgents=l[3]
def updateAgentToAgentView(poses):
for a in agents:
a.viewAgents.add(a)
a.viewAgents_prime.add(a)
for idx in delta_disk_neighbors(poses, a.ID-1, step*k+(step*0.25)):
for v in a.viewVertices:
dxi = np.reshape(np.array(v), (2,1)) - poses[:2,[idx]]
if np.linalg.norm(dxi) < 0.1:
a.viewAgents.add(agents[idx])
break
for v in a.viewVertices_prime:
dxi = np.reshape(np.array(v), (2,1)) - poses[:2,[idx]]
if np.linalg.norm(dxi) < 0.1:
a.viewAgents_prime.add(agents[idx])
break
id = 1
agents = []
for i in range(A):
agent = Agent(agentVertices[i][0], agentVertices[i][1], NORTH, id, 11)
agents.append(agent)
id += 1
pos = []
for a in agents:
pos.append([a.posX, a.posY, a.orientation])
starting_pos = np.asarray(pos).T
# show_figure = True for physical simulation verification
r_env = robotarium.Robotarium(number_of_robots=A, show_figure=False, initial_conditions=starting_pos,sim_in_real_time=True)
## Uncomment below when doing an actual experiment on robotarium with graphics
# marker_size_obs = determine_marker_size(r_env, 0.03)
# marker_obs_sml = determine_marker_size(r_env, 0.02)
# marker_size_goal = determine_marker_size(r_env, 0.02)
# marker_size_robot = determine_marker_size(r_env, 0.04)
# taskss = [r_env.axes.scatter(taskVertices[ii][0], taskVertices[ii][1], s=marker_size_goal, marker='o', facecolors='y',edgecolors='none',linewidth=2,zorder=-2)
# for ii in range(len(taskVertices))]
# horizontal_obs = [[-3, -1], [3, -1], [3, 1], [-3, 1], [-3, -1]]
# vert_obs = [[-1, -3], [1, -3], [1, 3], [-1, 3], [-1, -3]]
# square = [[-1, -1], [1, -1], [1, 1], [-1, 1], [-1, -1]]
# print(len(obs_dir))
# print(len(obstacles))
# shapes_dir = {
# 0: horizontal_obs,
# 1: vert_obs,
# 2: 's'
# }
# 0 - horizontal
# 1 - vertical
# 2 - square
# obs = [r_env.axes.scatter(obstacles[ii][0], obstacles[ii][1], s= marker_obs_sml if obs_dir[ii] == 2 else marker_size_obs, marker=shapes_dir[obs_dir[ii]], facecolors='k',edgecolors='k',linewidth=5,zorder=-2)
# for ii in range(len(obstacles))]
## New obs
# obs = [r_env.axes.scatter(obstacles[ii][0], obstacles[ii][1], s= marker_size_obs, marker=shapes_dir[2], facecolors='k',edgecolors='k',linewidth=5,zorder=-2)
# for ii in range(len(obstacles))]
## ------------------------------------------------------------
robot_markers = []
# Create a custom hybrid controller
unicycle_pose_controller = create_hybrid_unicycle_pose_controller(0.3, 0.3, 0.2, np.pi, 0.05, 0.03, 0.01)
# Create barrier certificates to avoid collision
uni_barrier_cert = create_unicycle_barrier_certificate(100, 0.12, 0.01, 0.2)
def getOppositeDirection(direction):
if direction == 'n':
return 's'
elif direction == 's':
return 'n'
elif direction == 'e':
return 'w'
elif direction == 'w':
return 'e'
elif direction == 'q':
return 'q'
def getExplorationMove(agent, updated_pos):
legal = getLegalMovesFrom(agent, updated_pos)
if exp_strat == 0:
if len(legal) > 1:
legal.remove('q')
return random.choice(legal)
## Guaranteed to move
# check if it exist in the grid bounds
def getLegalMovesFrom(agent, updated_pos):
# Guard against potential collision
moves = ['q']
up = round(agent.posY+1*step, 1)
down = round(agent.posY-1*step, 1)
left = round(agent.posX-1*step, 1)
right = round(agent.posX+1*step, 1)
if (right, agent.posY) in vertices and not updated_pos.get((right, agent.posY)):
moves.append('e')
if (left, agent.posY) in vertices and not updated_pos.get((left, agent.posY)):
moves.append('w')
if (agent.posX, up) in vertices and not updated_pos.get((agent.posX, up)):
moves.append('n')
if (agent.posX, down) in vertices and not updated_pos.get((agent.posX, down)):
moves.append('s')
return moves
## Not used
def executeStep(r_pos, eAgnt, goal_points):
if (np.size(at_pose(r_pos[:, eAgnt], goal_points[:,eAgnt])) != A):
# Get poses of agents
r_pos = r_env.get_poses()
## Remove Tasks
remove_t = set()
for t in taskVertices:
if any(np.linalg.norm(r_pos[:2,:] - np.reshape(np.array(t), (2,1)), axis=0) < 0.1):
remove_t.add(t)
# for ts in taskss:
# if ts.get_offsets()[0][0] == t[0] and ts.get_offsets()[0][1] == t[1]:
# ts.set_visible(False)
# break
for t in remove_t:
taskVertices.remove(t)
# Create unicycle control inputs
dxu = unicycle_pose_controller(r_pos, goal_points)
# Create safe control inputs (i.e., no collisions)
dxu = uni_barrier_cert(dxu, r_pos)
# Set the velocities
r_env.set_velocities(np.arange(A), dxu)
# Iterate the simulation
r_env.step()
return r_pos
else:
r_pos = r_env.get_poses()
r_env.step()
return r_pos
def movePrecedenceCmp(agentA, agentB):
## simple precedence filter based on remaining actual moves in the move list
## Filters out even the wait moves in between, but ideally should remove only the trailing wait moves
agentA_filtMovesLen = len([x for x in agentA.moves if x != 'q'])
agentB_filtMovesLen = len([x for x in agentB.moves if x != 'q'])
return agentB_filtMovesLen - agentA_filtMovesLen
def stateUpdate(r_pos, totalCost, waitCost, explore_steps, tempTasks):
sys.stdout.flush()
## First resolve collision between agents in clusters and have them move first
all_pos = {}
prev_pos = {}
agentsInClusterLen = 0
for a in agents:
a.back = False
if len(a.clusterID)!=0:
## Add the pos to old pos_directory
if prev_pos.get((a.posX, a.posY)):
prev_pos[(a.posX, a.posY)].append(a.ID)
else:
prev_pos[(a.posX, a.posY)] = [a.ID]
agentsInClusterLen += 1
## get the next move for an agent and account for costs
try:
a.dir = a.moves.pop(0)
if a.dir != 'q':
totalCost += 1
else:
waitCost += 1
except IndexError:
a.dir = 'q'
waitCost += 1
if a.getDir() == 'e':
east_move = round(a.posX+1*step, 1)
a.setXPos(east_move)
a.setOrientation(EAST)
elif a.getDir() == 'w':
west_move = round(a.posX-1*step, 1)
a.setXPos(west_move)
a.setOrientation(WEST)
elif a.getDir() == 's':
south_move = round(a.posY-1*step, 1)
a.setYPos(south_move)
a.setOrientation(SOUTH)
elif a.getDir() == 'n':
north_move = round(a.posY+1*step, 1)
a.setYPos(north_move)
a.setOrientation(NORTH)
elif a.getDir() == 'q':
pass
else:
raise ValueError("Incorrect direction. ")
## Add the new pos to updated pos_directory
if all_pos.get((a.posX, a.posY)):
all_pos[(a.posX, a.posY)].append(a.ID)
else:
all_pos[(a.posX, a.posY)] = [a.ID]
## Resolve collision - both 1. Intra Cluster 2. Inter Cluster
## TODO: Check for deadlocks that can occur: x -> y; y -> x || x j y || j is waiting permanently
## this occurs since trajectories don't allow to move into previously occupied location
## Account for exploring agents which are waiting
for a in agents:
if len(a.clusterID)==0:
a.updateView(r_pos)
found = False
for vertex in a.viewVertices:
if vertex in tempTasks:
found = True
break
if found == True:
a.dir = 'q'
waitCost += 1
for a in agents:
if len(a.clusterID)==0 and a.dir == 'q':
agentsInClusterLen += 1
if all_pos.get((a.posX, a.posY)):
all_pos[(a.posX, a.posY)].append(a.ID)
else:
all_pos[(a.posX, a.posY)] = [a.ID]
while len(all_pos) < agentsInClusterLen:
for pos in list(all_pos.keys()):
## check for collisions
if len(all_pos[pos]) > 1:
print("Colision at Loc:",pos, " for agents", all_pos[pos])
colliding_agents_IDs = all_pos[pos]
## Find agents which were previously waiting here or its their original position and have back tracked
## vs agents which have moved into this new position and have collided with already residing agents
colliding_agents_moved = list(filter(lambda a: a.ID in colliding_agents_IDs and len(a.clusterID) > 0 and (a.dir != 'q' and not a.back), agents))
prev_waiting = False
if len(colliding_agents_moved) == len(colliding_agents_IDs):
# No previously waiting agents
prev_waiting = False
elif len(colliding_agents_moved) == len(colliding_agents_IDs)-1:
# One previously waiting agents
prev_waiting = True
else:
raise ValueError("Impossible, two agents cannot be waiting at same location")
sorted_agents = sorted(colliding_agents_moved, key=functools.cmp_to_key(movePrecedenceCmp))
curr_agnt = None
if not prev_waiting:
## Since no one was waiting the agent to travel farthest will retain its move
curr_agnt = sorted_agents.pop(0)
else:
## Find the currently waiting agent or one who backtracked
curr_agnt = list(filter(lambda a: a.ID in colliding_agents_IDs and (a.dir == 'q' or a.back), agents))[0]
assert curr_agnt != None
curr_always_waiting = len(curr_agnt.clusterID) == 0 or len([x for x in curr_agnt.moves if x != 'q']) == 0
## Now the current colliding location is filled and who occupies it is fixed
## For everyone else find a safe next location or backtrack
for collide_agt in sorted_agents:
if len([x for x in collide_agt.moves if x != 'q']) > 0:
## Trajectory agent
safe = False
any_future_safe = False ## used this later to make better waits for travelling agents
trajectory_seen = 0
agent_t_cost = 0
agent_w_cost = 0
agent_pos = pos
agent_orient = collide_agt.orientation
## keep looking for next safe move until all of trajectory is seen
## A safe move is one where no one currently is and no one can backtrack as well
while not safe and trajectory_seen < len(collide_agt.moves):
next_move = collide_agt.moves[trajectory_seen]
trajectory_seen += 1
if next_move != 'q':
agent_t_cost += 1
else:
agent_w_cost += 1
if next_move == 'e':
east_move = round(agent_pos[0]+1*step, 1)
agent_pos = (east_move, agent_pos[1])
agent_orient = EAST
elif next_move == 'w':
west_move = round(agent_pos[0]-1*step, 1)
agent_pos = (west_move, agent_pos[1])
agent_orient = WEST
elif next_move == 's':
south_move = round(agent_pos[1]-1*step, 1)
agent_pos = (agent_pos[0], south_move)
agent_orient = SOUTH
elif next_move == 'n':
north_move = round(agent_pos[1]+1*step, 1)
agent_pos = (agent_pos[0], north_move)
agent_orient = NORTH
elif next_move == 'q':
pass
else:
raise ValueError("Incorrect direction. ")
## Make sure that it is really unsafe by checking if its currently occupied by someone or
## is someone else's previous location and not just your own!
if all_pos.get(agent_pos) or (prev_pos.get(agent_pos) and not (collide_agt.ID in prev_pos.get(agent_pos))):
## Not a safe location
## Check if any the agent in the location will stay there permanently by looking at the length of their remaining moves?
## if so not so then just wait for future ie. check if all the agents in the location are bound to move
## condition read "if no agents in next location such that no move left -> conversely all agents in next location have aleast 1 move left"
if all_pos.get(agent_pos) and len([x for x in all_pos.get(agent_pos) if len([y for y in agents[x-1].moves if y != 'q']) == 0]) == 0:
## If there is only one agent then check its remaining moves length
## If there are multiple agents then see
any_future_safe = True
else:
## Found safe then update move, location, trajectory and account for taken move costs
all_pos[agent_pos] = [collide_agt.ID]
all_pos[pos].remove(collide_agt.ID)
totalCost += agent_t_cost
waitCost += agent_w_cost
collide_agt.setXPos(agent_pos[0])
collide_agt.setYPos(agent_pos[1])
collide_agt.dir = next_move
collide_agt.setOrientation(agent_orient)
for _ in range(trajectory_seen):
collide_agt.moves.pop(0)
safe = True
print("Collision resolution for Agent:", collide_agt.ID, " move to (",collide_agt.posX,",",collide_agt.posY,")")
break
## Still can't find a safe location but in future a location might open up then wait
## for future to move
if not safe and any_future_safe:
## Backtrack and discount for previously computed costs
collide_agt.moves.insert(0, collide_agt.dir)
collide_agt.back = True
all_pos[pos].remove(collide_agt.ID)
if collide_agt.dir != 'q':
totalCost -= 1
else:
waitCost -= 1
opposite_dir = getOppositeDirection(collide_agt.dir)
if opposite_dir == 'e':
east_move = round(collide_agt.posX+1*step, 1)
collide_agt.setXPos(east_move)
collide_agt.setOrientation(EAST)
elif opposite_dir == 'w':
west_move = round(collide_agt.posX-1*step, 1)
collide_agt.setXPos(west_move)
collide_agt.setOrientation(WEST)
elif opposite_dir == 's':
south_move = round(collide_agt.posY-1*step, 1)
collide_agt.setYPos(south_move)
collide_agt.setOrientation(SOUTH)
elif opposite_dir == 'n':
north_move = round(collide_agt.posY+1*step, 1)
collide_agt.setYPos(north_move)
collide_agt.setOrientation(NORTH)
elif opposite_dir == 'q':
pass