-
Notifications
You must be signed in to change notification settings - Fork 0
/
AgentBasedTestGen.py
1771 lines (1454 loc) · 60 KB
/
AgentBasedTestGen.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 sys
import numpy as np
import cv2
import time
import matplotlib.pyplot as plt
import random
import os.path
import datetime
class Environment(object):
def __init__(self, gridH, gridW, end_positions, end_rewards, blocked_positions, start_position, default_reward, road_positions, road_rewards, scale=25):
self.action_space = 4
self.state_space = gridH * gridW
self.gridH = gridH
self.gridW = gridW
self.scale = scale
self.end_positions = end_positions
self.end_rewards = end_rewards
self.blocked_positions = blocked_positions
self.road_positions = road_positions
self.road_rewards = road_rewards
#perceptions
self.on_road = 0
self.diff_x = 0
self.diff_y = 0
self.euclid = 0
self.inv_euclid = 0
self.inv_euclid2 = 0
self.inv_euclid3 = 0
self.last_av_pos = -1
self.start_position = start_position
if self.start_position == None:
self.position = self.init_start_state()
else:
self.position = self.start_position
self.state2idx = {}
self.idx2state = {}
self.idx2reward = {}
for i in range(self.gridH):
for j in range(self.gridW):
idx = i*self.gridW + j
self.state2idx[(i, j)] = idx
self.idx2state[idx]=(i, j)
self.idx2reward[idx] = default_reward
# set the AV reward
for position, reward in zip(self.end_positions, self.end_rewards):
self.idx2reward[self.state2idx[position]] = reward
#update road rewards
for position, reward in zip(self.road_positions, self.road_rewards):
self.idx2reward[self.state2idx[position]] = reward
self.frame = np.zeros((self.gridH * self.scale, self.gridW * self.scale, 3), np.uint8)
# for position in self.blocked_positions:
# y, x = position
# cv2.rectangle(self.frame, (x*self.scale, y*self.scale), ((x+1)*self.scale, (y+1)*self.scale), (100, 100, 100), -1)
for position, reward in zip(self.road_positions, self.road_rewards):
text = str(int(reward))
if reward > 0.0: text = '+' + text
if reward > 0.0: color = (0, 255, 0)
else: color = (0, 0, 255)
font = cv2.FONT_HERSHEY_SIMPLEX
y, x = position
(w, h), _ = cv2.getTextSize(text, font, 1, 2)
#cv2.rectangle(self.frame, (x*self.scale, y*self.scale), ((x+1)*self.scale, (y+1)*self.scale), (100, 100, 100), -1) #from blocked positions
#cv2.putText(self.frame, text, (int((x+0.5)*self.scale-w/2), int((y+0.5)*self.scale+h/2)), font, 1, color, 2, cv2.LINE_AA)
for position, reward in zip(self.end_positions, self.end_rewards):
text = str(int(reward))
if reward > 0.0: text = '+' + text
if reward > 0.0: color = (0, 255, 0)
else: color = (0, 0, 255)
font = cv2.FONT_HERSHEY_SIMPLEX
y, x = position
(w, h), _ = cv2.getTextSize(text, font, 1, 2)
cv2.putText(self.frame, text, (int((x+0.5)*self.scale-w/2), int((y+0.5)*self.scale+h/2)), font, 1, color, 2, cv2.LINE_AA)
#cv2.putText(self.frame, text, (int((x+0.5)*self.scale)-w/2, int((y+0.5)*self.scale+h/2)), font, 1, color, 2, cv2.LINE_AA)
# colour the pavements
pavement_rows = [0,1,10,11]
for y in pavement_rows:
for x in range(self.gridW+1):
cv2.rectangle(self.frame, (x*self.scale, y*self.scale), ((x+1)*self.scale, (y+1)*self.scale), (100, 100, 100), -1)
def init_start_state(self):
while True:
preposition = (np.random.choice(self.gridH), np.random.choice(self.gridW))
if preposition not in self.end_positions and preposition not in self.blocked_positions:
return preposition
def get_state(self):
return self.state2idx[self.position]
def update_state(self):
#clear the board of previous blocked positions
self.frame = np.zeros((self.gridH * self.scale, self.gridW * self.scale, 3), np.uint8)
# #update blocked positions
# for position in self.blocked_positions:
# y, x = position
# cv2.rectangle(self.frame, (x*self.scale, y*self.scale), ((x+1)*self.scale, (y+1)*self.scale), (100, 100, 100), -1)
# update the road rewards
for position, reward in zip(self.road_positions, self.road_rewards):
text = str(int(reward))
if reward > 0.0: text = '+' + text
if reward > 0.0: color = (0, 255, 0)
else: color = (0, 0, 255)
font = cv2.FONT_HERSHEY_SIMPLEX
y, x = position
(w, h), _ = cv2.getTextSize(text, font, 1, 2)
#cv2.rectangle(self.frame, (x*self.scale, y*self.scale), ((x+1)*self.scale, (y+1)*self.scale), (100, 100, 100), -1) #from blocked positions
#cv2.putText(self.frame, text, (int((x+0.5)*self.scale-w/2), int((y+0.5)*self.scale+h/2)), font, 0.5, color, 1, cv2.LINE_AA)
#GC update the position of the AV and rewards
for position, reward in zip(self.end_positions, self.end_rewards):
self.idx2reward[self.state2idx[position]] = reward
#update grid
text = str(int(reward))
if reward > 0.0: text = '+' + text
if reward > 0.0: color = (0, 255, 0)
else: color = (0, 0, 255)
font = cv2.FONT_HERSHEY_SIMPLEX
y, x = position
(w, h), _ = cv2.getTextSize(text, font, 1, 2)
cv2.rectangle(self.frame, (x*self.scale, y*self.scale), ((x+1)*self.scale, (y+1)*self.scale), (100, 100, 100), -1) #from blocked positions
# cv2.putText(self.frame, text, (int((x+0.5)*self.scale-w/2), int((y+0.5)*self.scale+h/2)), font, 0.5, color, 1, cv2.LINE_AA)
# colour the pavements
pavement_rows = [0,1,10,11]
for y in pavement_rows:
for x in range(self.gridW+1):
cv2.rectangle(self.frame, (x*self.scale, y*self.scale), ((x+1)*self.scale, (y+1)*self.scale), (100, 100, 100), -1)
def percepts(self, AV_state):
#shorthand - pedestrian position
xp = self.position[1]
yp = self.position[0]
#av position
xa = AV_state[1]
ya = AV_state[0]
# is agent on road
if (xp > 1) | (xp < 4):
self.on_road = 1
if (xp <= 1) | (xp >= 4):
self.on_road = 0
# distance to AV
self.diff_x = (xp - xa)
self.diff_y = (yp - ya)
self.euclid = np.sqrt(np.square(self.diff_x) + np.square(self.diff_y))
# inverse distance to AV
if self.euclid == 0:
self.inv_euclid = 1
self.inv_euclid2 = 1
self.inv_euclid3 = 1
else:
self.inv_euclid = 1/self.euclid
self.inv_euclid2 = 1/np.square(self.euclid)
self.inv_euclid3 = 1/np.power(self.euclid,3)
#return (self.on_road, self.diff_x, self.diff_y, self.euclid, self.inv_euclid, self.inv_euclid2, self.inv_euclid3)
return (self.on_road, self.diff_x, self.diff_y, self.euclid,0,0,0)
def one_step_ahead_features(self, future_actions, AV_state):
#shorthand - pedestrian position
curr_xp = self.position[1]
curr_yp = self.position[0]
loop =0
#print("old position ", curr_xp, curr_yp)
#print("future_actions ", list(future_actions))
for action in future_actions:
#print("action from future_actions", action)
# Update position based on future_action
if action == 0:
xp = curr_xp
yp = curr_yp + 1 #proposed = (self.position[0] +1, self.position[1])
elif action == 1:
xp = curr_xp
yp = curr_yp - 1 #proposed = (self.position[0] -1, self.position[1])
elif action == 2:
xp = curr_xp + 1 #proposed = (self.position[0], self.position[1] +1)
yp = curr_yp
elif action == 3:
xp = curr_xp - 1 #proposed = (self.position[0], self.position[1] -1)
yp = curr_yp
#print("new position ", xp, yp)
#av position
xa = AV_state[1]
ya = AV_state[0]
# is agent on road
if (xp > 1) | (xp < 4):
on_road = 1
if (xp <= 1) | (xp >= 4):
on_road = 0
# distance to AV
diff_x = (xp - xa)
diff_y = (yp - ya)
euclid = np.sqrt(np.square(diff_x) + np.square(diff_y))
# inverse distance to AV
if euclid==0:
inv_euclid = 1
inv_euclid2 = 1
inv_euclid3 = 1
else:
inv_euclid = 1/euclid
inv_euclid2 = 1/np.square(euclid)
inv_euclid3 = 1/np.power(euclid,3)
curr_features = np.array([on_road, diff_x, diff_y,euclid, inv_euclid, inv_euclid2, inv_euclid3])
#print("curr_features ", curr_features)
#print("loop ", loop)
if loop == 0:
features = curr_features
loop =1
else:
features = np.vstack((features,curr_features))
loop = loop + 1
#print("features shape ", features.shape)
#print("features ", features)
return features
def get_possible_actions(self):
return range(self.action_space)
def step(self, action):
# Actions are:
# 0 = down (+Y)
# 1 = up (-Y)
# 2 = right (+X)
# 3 = left (-X)
# Check if action is blocked, then update position
if action >= self.action_space:
return
if action == 0:
proposed = (self.position[0] +1, self.position[1])
elif action == 1:
proposed = (self.position[0] -1, self.position[1])
elif action == 2:
proposed = (self.position[0], self.position[1] +1)
elif action == 3:
proposed = (self.position[0], self.position[1] -1)
y_within = proposed[0] >= 0 and proposed[0] < self.gridH
x_within = proposed[1] >= 0 and proposed[1] < self.gridW
free = proposed not in self.blocked_positions
if x_within and y_within and free:
self.position = proposed
next_state = self.state2idx[self.position]
reward = self.idx2reward[next_state]
# print("###STEP### self.position",self.position)
# print("###STEP### next_state",next_state)
if self.position in self.end_positions:
done = True
else:
done = False
return next_state, reward, done
def reset_state(self):
#print("\n ~ GAME RESTARTING ~\n")
if self.start_position == None:
self.position = self.init_start_state()
else:
self.position = self.start_position
def render(self, qvalues_matrix, running_score, simTime, nA, agentState):
frame = self.frame.copy()
# for each state cell
for idx, qvalues in enumerate(qvalues_matrix):
position = self.idx2state[idx]
if position in self.end_positions or position in self.blocked_positions:
continue
qvalues = np.tanh(qvalues*0.1) # for vizualization only
# for each action in state cell
for action, qvalue in enumerate(qvalues):
# draw (state, action) qvalue traingle
if action == 0:
dx2, dy2, dx3, dy3 = 0.0, 1.0, 1.0, 1.0
if action == 1:
dx2, dy2, dx3, dy3 = 0.0, 0.0, 1.0, 0.0
if action == 2:
dx2, dy2, dx3, dy3 = 1.0, 0.0, 1.0, 1.0
if action == 3:
dx2, dy2, dx3, dy3 = 0.0, 0.0, 0.0, 1.0
x1 = int(self.scale*(position[1] + 0.5))
y1 = int(self.scale*(position[0] + 0.5))
x2 = int(self.scale*(position[1] + dx2))
y2 = int(self.scale*(position[0] + dy2))
x3 = int(self.scale*(position[1] + dx3))
y3 = int(self.scale*(position[0] + dy3))
pts = np.array([[x1, y1], [x2, y2], [x3, y3]], np.int32)
pts = pts.reshape((-1, 1, 2))
if qvalue > 0: color = (0, int(qvalue*255),0)
elif qvalue < 0: color = (0,0, -int(qvalue*255))
else: color = (0, 0, 0)
cv2.fillPoly(frame, [pts], color)
# draw horizontal lines
for i in range(self.gridH+1):
cv2.line(frame, (0, i*self.scale), (self.gridW * self.scale, i*self.scale), (255, 255, 255), 1)
# draw vertical lines
for i in range(self.gridW+1):
cv2.line(frame, (i*self.scale, 0), (i*self.scale, self.gridH * self.scale), (255, 255, 255), 1)
#openCV rectangle function
# cv2.rectangle(img, pt1, pt2, color, thickness, lineType, shift)
# Parameters
# img Image.
# pt1 Vertex of the rectangle.
# pt2 Vertex of the rectangle opposite to pt1 .
# color Rectangle color or brightness (grayscale image).
# thickness Thickness of lines that make up the rectangle. Negative values,
# like CV_FILLED , mean that the function has to draw a filled rectangle.
# lineType Type of the line. See the line description.
# shift Number of fractional bits in the point coordinates.
# Must be integers
# Must have order (left, top) and (right, bottom)
# # draw agent
# for i in range(0,2):
# y, x = self.position
# x = x + (i * 2)
# y = y + (i * 2)
# y1 = int((y + 0.3)*self.scale)
# x1 = int((x + 0.3)*self.scale)
# y2 = int((y + 0.7)*self.scale)
# x2 = int((x + 0.7)*self.scale)
# cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 255), -1)
# cv2.imshow('frame', frame)
# cv2.moveWindow('frame', 0, 0)
# key = cv2.waitKey(1)
# if key == 27: sys.exit()
# #print('### RENDER1 ### xy',x,y,x1,x2,y1,y2)
# # cv2.rectangle(frame, (x1+50, y1+50), (x2+50, y2+50), (0, 255, 255), -1)
#======================================
# draw agent
#======================================
#print("simTime, nA",simTime, nA)
for agentID in range(0,nA):
y,x = agentState[simTime, agentID,:]
y1 = int((y + 0.3)*self.scale)
x1 = int((x + 0.3)*self.scale)
y2 = int((y + 0.7)*self.scale)
x2 = int((x + 0.7)*self.scale)
cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 255), -1)
#print('### RENDER2 ### xy',x,y,x1,x2,y1,y2)
#print("### RENDER ### simTime, agentID, x,y,x1,x2,y1,y2",simTime, agentID,x,y,x1,x2,y1,y2)
#time.sleep(1)
#======================================
cv2.imshow('frame', frame)
cv2.moveWindow('frame', 0, 0)
key = cv2.waitKey(1)
if key == 27: sys.exit()
#print score
text = 'score = ' + str(int(running_score))
# if running_score > 0.0: text = '+' + text
if running_score > 0.0: color = (0, 255, 0)
else: color = (0, 0, 255)
font = cv2.FONT_HERSHEY_SIMPLEX
# y, x = position
y = self.gridH - 1
x = self.gridW - 1
(w, h), _ = cv2.getTextSize(text, font, 1, 2)
# cv2.putText(img, running_score, org, fontFace, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]])
cv2.putText(frame, text, (int((x+0.5)*self.scale-w/2), int((y+0.5)*self.scale+h/2)), font, 0.5, color, 1, cv2.LINE_AA)
cv2.imshow('frame', frame)
cv2.moveWindow('frame', 0, 0)
key = cv2.waitKey(1)
if key == 27: sys.exit()
#---------------------------------------------------------------------------------------------
#-------------------------------- ~ Feature Based Agent ~ -----------------------------------
#---------------------------------------------------------------------------------------------
class FeatAgent:
# This class uses a featured based representation of the world rather than explicit states
# as such perception is required to inform the agent on the environment
def __init__(self, alpha, epsilon, discount, action_space, state_space):
self.feat_space = 7 #set this to the number of features
self.action_space = action_space
self.alpha = alpha
self.epsilon = epsilon
self.discount = discount
# we remove the explicit state space and replace with feature based representation
#self.qvalues = np.zeros((state_space, action_space), np.float32)
#self.feat_weights = np.zeros((self.feat_space), np.float32)
self.feat_weights = np.random.uniform(size=(self.feat_space),low=-1,high=1) #set random feature weights
self.qvalues = np.zeros((self.feat_space, action_space), np.float32)
# print("feat_weights ", self.feat_weights)
# print("qvalues ", self.qvalues)
# print("feat_space ", self.feat_space)
# print("action_space ", self.action_space)
def feat_q_update(self, state, AV_state, action, reward, next_state, next_state_possible_actions, done, features, q_val_dash):
# calculate Q-values based on the feature representation
# Q(s,a) = w1.f1(s,a) + w2.f2(s,a) + ... wi.fi(s,a)
# features are:
# f1 = on_road
# f2 = x distance between av and ped
# f3 = y distance between av and ped
# f4 = euclidean distance between av and ped
# f5 = inverse euclidean distance between av and ped
# f6 = inverse euclidean distance^2 between av and ped
# f7 = inverse euclidean distance^3 between av and ped
qval = np.sum(np.multiply(self.feat_weights, features))
# now update the feature weights given the reward
difference = (reward + self.alpha * q_val_dash) - qval
# print("features x weights ", np.multiply(self.feat_weights, features))
# print("#############################")
# print("reward ", reward)
# print("self.discount ", self.discount)
#print("next_state ", next_state)
#print("next_state_possible_actions ", list(next_state_possible_actions))
# print("qval ", qval)
# print("q_val_dash ", q_val_dash)
# print("self.feat_weights", self.feat_weights)
# print("difference", difference)
#print("self.feat_weights.shape", self.feat_weights.shape)
for i in range(self.feat_weights.shape[0]):
wi = self.feat_weights[i]
self.feat_weights[i] = wi + self.alpha * difference * features[i]
# print("~~~~~~~~~~~~~~~~~~~~~~~~")
# print("i", i)
# print("i w_old new ", i, wi, self.feat_weights[i])
# print("self.feat_weights[i]", c)
# print("self.alpha", self.alpha)
# print("difference", difference)
# print("wi shape", wi.shape)
# print("self.feat_weights[i] shape", self.feat_weights[i].shape)
# print("self.alpha shape", self.alpha)
# print("difference shape", difference.shape)
# print("features[i]", features[i])
def update(self, state, action, reward, next_state, next_state_possible_actions, done):
# Q(s,a) = (1.0 - alpha) * Q(s,a) + alpha * (reward + discount * V(s'))
if done==True:
qval_dash = reward
else:
qval_dash = reward + self.discount * self.get_value(next_state, next_state_possible_actions)
qval_old = self.qvalues[state][action]
qval = (1.0 - self.alpha)* qval_old + self.alpha * qval_dash
self.qvalues[state][action] = qval
# def get_best_action(self, state, possible_actions, features):
# print("------ QVAL ------")
# # calculate q-val for all actions
# all_q_val = np.sum(np.multiply(self.feat_weights, features),axis=1)
# # find the best q-val and return the index
# q_val_dash = np.max(all_q_val)
# idx_best_q = np.argmax(all_q_val)
# #retun the action for the best q-val
# best_action = possible_actions[idx_best_q]
# print("all_q_val ", all_q_val)
# print("idx_best_q ", idx_best_q)
# print("best_action ", best_action)
# return best_action, q_val_dash, all_q_val
def calc_new_feature_func(action, features):
# if I take this action what will my new feature functions be?
return new_features
def get_action(self, state, possible_actions, features):
# with probability epsilon take random action, otherwise - the best policy action
epsilon = self.epsilon
# find the best action an associated q-value
# calculate q-val for all actions
all_q_val = np.sum(np.multiply(self.feat_weights, features),axis=1)
# find the best q-val and return the index
#q_val_dash = np.max(all_q_val)
idx_best_q = np.argmax(all_q_val)
#retun the action for the best q-val
best_action = possible_actions[idx_best_q]
#chosen_action = self.get_best_action(state, possible_actions, features)
# print("------------------")
# print("------ QVAL ------")
if epsilon > np.random.uniform(0.0, 1.0):
chosen_action = random.choice(possible_actions)
action_index = np.where(np.isclose(possible_actions,chosen_action))
# print("possible_actions ", possible_actions)
# print("chosen_action ", chosen_action)
# print("action_index ", action_index)
# print("action_index shape ", np.shape(action_index))
# print("action_index[0] ", action_index[0])
# print("action_index ", action_index)
# print("random action taken")
q_val_dash = all_q_val[action_index[0]]
else:
chosen_action = best_action
q_val_dash = np.max(all_q_val)
# print("all_q_val ", all_q_val)
# print("idx_best_q ", idx_best_q)
# print("best_action ", best_action)
# print("chosen_action ", chosen_action)
# print("q_val_dash ", q_val_dash)
return chosen_action, q_val_dash
def get_value(self, state, possible_actions):
pass
#---------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------
def randomStart(startLocations, simTime, nA, agentState, rsLog, pLog, nExp):
#print("### randomStart ###")
# initialise each agent with random position based on "deadzone"
log_string = ""
start_array = startLocations[nExp,:]
# print("nExp start_array",nExp,start_array)
for agentID in range(0,nA):
# read start location from master table
x = start_array[(0+2*agentID)]
y = start_array[(1+2*agentID)]
# add locations to agent state array
agentState[simTime,agentID,0] = x
agentState[simTime,agentID,1] = y
log_string = log_string + ", %4i, %4i" % (x,y)
#print(log_string)
#print("initial state for agent", agentID," is ",agentState[simTime,agentID,:])
rsindex = "%4i" % (nExp)
index = "%4i, %4i, %4i" % (0, nExp, simTime)
rsLog.write(rsindex + log_string + "\n")
pLog.write(index + log_string + "\n")
def moveGen(simTime, agentID, rLog):
ran = random.randint(1,5)
#print("ran",ran)
x, y = 0, 0
if ran==1:
log = "moving UP"
y = y - 1
if ran==2:
log = "moving DOWN"
y = y + 1
if ran==3:
log = "moving LEFT"
x = x - 1
if ran==4:
log = "moving RIGHT"
x = x + 1
if ran==5:
log = "moving NONE"
#store the random numbers to check consistency
rLog.write("%7i, %4i \n" % (simTime, ran))
return x,y #WARNING X and Y are used the wrong way around
def randomMove(simTime, nA, agentState, pLog, rLog, nExp, AV_y):
#print("### randomMove ###")
log_string = ""
for agentID in range(0,nA):
illegal_move=True
while(illegal_move):
#get a delta move randomly
dx, dy = moveGen(simTime, agentID, rLog)
# Add delta to previous state
new_x = int(agentState[simTime-1,agentID,0] + dx)
new_y = int(agentState[simTime-1,agentID,1] + dy)
#print("new x y ", new_x, new_y)
# check if agent has moved off the board
if (new_x<0):
#print("ILLEGAL move 1")
continue
elif(new_x>gridH-1):
#print("ILLEGAL move 2")
continue
elif(new_y<0):
#print("ILLEGAL move 3")
continue
elif(new_y>gridW-1):
#print("ILLEGAL move 4")
#print("y value ",new_y," is greater than grid limit ", gridH)
continue
else:
illegal_move=False
# Add delta to previous state
agentState[simTime,agentID,0] = new_x
agentState[simTime,agentID,1] = new_y
# Log position data
# pLog.write("%d, %d, %d, %d \n" % (simTime, agentID, x, y))
#print("state for agent", agentID," is ",agentState[simTime,agentID,:])
log_string = log_string + ", %4i, %4i" % (new_x,new_y)
#print(log_string)
#print("initial state for agent", agentID," is ",agentState[simTime,agentID,:])
index = "%4i, %4i, %4i" % (nExp, simTime, AV_y)
pLog.write(index + log_string + "\n")
# Agent walks along pavement and randomly choose to cross the road
def randomBehaviour(simTime, nA, agentState, pLog, rLog, nExp, AV_y, diag=True):
for agentID in range(0,nA):
walk_direction = 0
crossing_road = 0
log_string = ""
# ran = random.randint(1,5) #roll 5-sided dice
ran = random.randint(1,11) #roll 11-sided dice
rLog.write("%7i, %4i \n" % (simTime, ran)) #log random number
old_ax = agentState[simTime-1,agentID,0]
old_ay = agentState[simTime-1,agentID,1]
#if first step then set agents down pavement
if int(simTime)==1:
# if old_ay>int(round(gridH/2)): #walking direction
if ran>1 and ran<7:
walk_direction = -1
#if diag:print("Agent is East side")
elif ran>6:
walk_direction = 1
#if diag:print("Agent is West side")
#set 1/5 chance of crossing road
if ran==1:
if old_ax>9: crossing_road = -1 #if on lower pavement, move up
if old_ax<2: crossing_road = 1 #if on upper pavement, move down
else:
crossing_road = 0
#print("old_xy=%2i,%2i xy=%2i,%2i n=%3i t=%2i WD=%2i XR=%2i" % (old_ax, old_ay, 0, 0, nExp, simTime,walk_direction,crossing_road))
#find walk direction if sim started
if simTime>1:
old2_ax = agentState[simTime-2,agentID,0]
old2_ay = agentState[simTime-2,agentID,1]
old_ax = agentState[simTime-1,agentID,0]
old_ay = agentState[simTime-1,agentID,1]
#if diag:print("Agent old XY=%d %d new XY=%d,%d" % (old_ax, old_ay, ax, ay))
if old2_ay>old_ay: #walking direction
walk_direction = -1 #walking 'left'
if diag:print("Left walking detected")
if old2_ay<old_ay:
walk_direction = 1 #walking 'right'
if diag:print("Right walking detected")
if old2_ay==old_ay:
#find if agent is crossing road
if old2_ax>old_ax:
crossing_road=-1 #moving 'up'
if diag:print("Agent is mid-crossing going up")
elif old2_ax<old_ax:
crossing_road=1 #moving 'down'
if diag:print("Agent is mid-crossing going down")
else:
print("##RB## WARNING: Unrecognised agent behaviour")
#set 1/5 chance of crossing road
if ran==1:
if old_ax>9:
crossing_road = -1 #if on lower pavement, move up
if diag:print("Agent has decided to cross UP")
if old_ax<2:
crossing_road = 1 #if on upper pavement, move down
if diag:print("Agent has decided to cross DOWN")
# Move the agent based on the walk and crossing direction
dx = 0
dy = 0
if crossing_road == -1:
dx = -1
dy = 0
if crossing_road == 1:
dx = 1
dy = 0
if crossing_road == 0:
if walk_direction == -1:
dy = -1
dx = 0
elif walk_direction == 1:
dy = 1
dx = 0
else:
print("##RB## WARNING: No valid move found")
if diag:print("Agent dx=%2i dy=%2i" % (dx, dy))
# Determine new position
new_x = int(old_ax + dx)
new_y = int(old_ay + dy)
# Reverse direction if agent hits edge
if (new_y == 0) or (new_y > gridW-1):
dy = dy * -1
if diag:print("Agent at y-limit reversing")
new_y = int(old_ay + dy)
if (new_x == 0) or (new_x > gridH-1):
dx = dx * -1
new_x = int(old_ax + dx)
if diag:print("Agent at x-limit reversing")
# print("nExp=%3i simTime=%2i WD=%2i XR=%2i" % (nExp, simTime,walk_direction,crossing_road))
if diag: print("old_xy=%2i,%2i xy=%2i,%2i n=%3i t=%2i WD=%2i XR=%2i" % (old_ax, old_ay, new_x, new_y, nExp, simTime,walk_direction,crossing_road))
# print("walk_direction=%d" % walk_direction)
# print("crossing_road=%d" % crossing_road)
# Add delta to previous state
agentState[simTime,agentID,0] = new_x
agentState[simTime,agentID,1] = new_y
log_string = log_string + ", %4i, %4i" % (new_x,new_y)
# write position log
index = "%4i, %4i, %4i" % (nExp, simTime, AV_y)
pLog.write(index + log_string + "\n")
# Agent walks along pavement and randomly choose to cross the road
def Proximity(simTime, nA, agentState, pLog, rLog, nExp, AV_y, trigger_radius=15, diag=False):
from scipy.spatial import distance #for cityblock distance
for agentID in range(0,nA):
walk_direction = 0
crossing_road = 0
log_string = ""
ran = random.randint(1,10) #roll 10-sided dice
rLog.write("%7i, %4i \n" % (simTime, ran)) #log random number
old_ax = agentState[simTime-1,agentID,0]
old_ay = agentState[simTime-1,agentID,1]
#if first step then set agents down pavement
if int(simTime)==1:
# if old_ay>int(round(gridH/2)): #walking direction
if ran<6:
walk_direction = -1
#if diag:print("Agent is East side")
elif ran>5:
walk_direction = 1
#if diag:print("Agent is West side")
else:
walk_direction = 1
#check if at edge/corner
if old_ay==0:
walk_direction = 1
if old_ay==gridW-1:
walk_direction = -1
#find walk direction if sim started
if simTime>1:
crossing_road, walk_direction = detectAction(crossing_road, walk_direction,simTime,agentID)
# if walk_direction==0 and crossing_road==0:
# print("post detect-action check")
# print("old_xy=%2i,%2i n=%3i t=%2i WD=%2i XR=%2i" % (old_ax, old_ay, nExp, simTime,walk_direction,crossing_road))
#If AV is within radius then cross the road
# AV coordiantes are: [2,3,4,5], AV_y
pt = np.zeros(shape=(4,1))
for AV_x in range (2, 6):
AV_coord = np.array([AV_x,AV_y])
AG_coord = np.array([old_ax, old_ay])
#print(AV_coord, type(AV_coord))
#print(AG_coord, type(AG_coord))
temp = distance.cityblock(AV_coord, AG_coord)
pt[AV_x-2] = temp
#print("AV=%s AG=%s PT=%d" % (AV_coord, AG_coord, temp))
prox_MIN = np.min(pt)
# print("proximity_test output is %d %d %d %d" % (pt[0],pt[1],pt[2],pt[3]))
# print("minimum prox=%d" % prox_MIN)
# print("trigger_radius =%d" % trigger_radius)
# if you want to manually step through each tick
# raw_input("Press Enter to continue...")
if prox_MIN<trigger_radius:
if(diag): print("proximity triggered for agent %d at %d m" % (agentID, 1.5*prox_MIN))
if old_ax>9:
crossing_road = -1 #if on lower pavement, move up
if diag:print("Agent has decided to cross UP")
if old_ax<2:
crossing_road = 1 #if on upper pavement, move down
if diag:print("Agent has decided to cross DOWN")
# calculate new xy positions
if walk_direction==0 and crossing_road==0:
print("##Proximity## WARNING: walk_direction overwritten")
print("old_xy=%2i,%2i n=%3i t=%2i WD=%2i XR=%2i" % (old_ax, old_ay, nExp, simTime,walk_direction,crossing_road))
raw_input("Press Enter to continue...")
new_x, new_y = moveXR(old_ax, old_ay, crossing_road, walk_direction, diag)
new_x, new_y = checkEdge(gridW, gridH, old_ax, old_ay, new_x, new_y, diag)
if diag: print("old_xy=%2i,%2i xy=%2i,%2i n=%3i t=%2i WD=%2i XR=%2i" % (old_ax, old_ay, new_x, new_y, nExp, simTime,walk_direction,crossing_road))
# Add delta to previous state
agentState[simTime,agentID,0] = new_x
agentState[simTime,agentID,1] = new_y
log_string = log_string + ", %4i, %4i" % (new_x,new_y)
# write position log
index = "%4i, %4i, %4i" % (nExp, simTime, AV_y)
pLog.write(index + log_string + "\n")
# Agent walks along pavement and randomly choose to cross the road
def Election(simTime, nA, agentState, XR_WD_status, pLog, rLog, nExp, AV_y, CP=True, ECA=True, trigger_radius=15, diag=True):
from scipy.spatial import distance #for cityblock distance
electionArray = np.zeros(shape=(nA,4)) #store election results
# XR_WD_status = np.zeros(shape=(nA,2))
agentElected = False
use_closest_agent = ECA
CP_array = np.zeros(shape=(nA,))
for agentID in range(0,nA):
walk_direction = 0
crossing_road = 0
log_string = ""
dx = 0
dy = 0
ran = random.randint(1,10) #roll 10-sided dice
rLog.write("%7i, %4i \n" % (simTime, ran)) #log random number
old_ax = agentState[simTime-1,agentID,0]
old_ay = agentState[simTime-1,agentID,1]
#if first step then set agents down pavement
if int(simTime)==1:
#reset the election parameters
allAgentsXR = 0
agentElected = False
XR_WD_status[agentID,0] = 0
XR_WD_status[agentID,1] = 0
# randomly set walking direction
if ran<6:
walk_direction = -1
elif ran>5:
walk_direction = 1
else:
walk_direction = 1
#check if at edge/corner
if old_ay==0:
walk_direction = 1
if old_ay==gridW-1:
walk_direction = -1
# execute move orders
new_x, new_y = moveXR(old_ax, old_ay, crossing_road, walk_direction)
new_x, new_y = checkEdge(gridW, gridH, old_ax, old_ay, new_x, new_y)
# Add delta to previous state
agentState[simTime,agentID,0] = new_x
agentState[simTime,agentID,1] = new_y
XR_WD_status[agentID,1] = walk_direction
log_string = log_string + ", %4i, %4i" % (new_x,new_y)
#find walk direction if sim started
if simTime>1:
crossing_road, walk_direction = detectAction(crossing_road, walk_direction,simTime,agentID)
# XR_WD_status[agentID,0] = crossing_road #don't want to update this as is election specific
XR_WD_status[agentID,1] = walk_direction
#see which agents on pavement closest to AV
all_agents_upper_pavement = agentState[simTime-1,:,0] < 2
#Cityblock distance to AV
pt = np.zeros(shape=(4,1))
for AV_x in range (2, 6):
AV_coord = np.array([AV_x,AV_y])
AG_coord = np.array([old_ax, old_ay])
#print(AV_coord, type(AV_coord))
#print(AG_coord, type(AG_coord))
temp = distance.cityblock(AV_coord, AG_coord)
pt[AV_x-2] = temp
#print("AV=%s AG=%s PT=%d" % (AV_coord, AG_coord, temp))
#prox_MIN = np.min(pt)
#print("proximity_test output is %d %d %d %d" % (pt[0],pt[1],pt[2],pt[3]))
electionArray[agentID,:] = pt[0],pt[1],pt[2],pt[3]
# see which agents on upper pavement
if (simTime>1):
# Show the minimum proximity per agent
PT_over_agents = np.min(electionArray, axis=1)
#if(diag):print("min PT per agent ", PT_over_agents )
for agentID in range (0,nA):
old_ax = agentState[simTime-1,agentID,0]
old_ay = agentState[simTime-1,agentID,1]
curr_XR = XR_WD_status[agentID,0]
allAgentsXR = np.any(XR_WD_status[:,0])
#choose the min PT
min_PT_per_Agent = np.min(electionArray[agentID,:])
best_candidate = -1
# find if any proximity test is within the trigger radius
trigger = (np.min(electionArray[agentID,:])<=trigger_radius)
if(diag):print(" ID %d PT=%d trigger=%d XR %d and anyXR= %d ectd=%d" % (agentID, min_PT_per_Agent, trigger, curr_XR, allAgentsXR, agentElected))
#========================================================
#
# ~~~~~~~~~~~ Hold the election! ~~~~~~~~~~~~~
#
#========================================================
# if there is a single agent, you have a Rotten Borough
if nA==1 and trigger and not(allAgentsXR):
best_candidate = 0
#print("best_candidate ID=%d" % best_candidate)