-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenvironments.py
1687 lines (1387 loc) · 58.8 KB
/
environments.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
"""
environments.py
====================================
The module containing RL environment objects. They are separated in EstimationTasks, where the agent only needs
to estimate the value function, and ControlTasks, where the agent
"""
import numpy as np
import networkx as nx
import pandas as pd
import random
import os
from scipy import stats
import gym
from gym import spaces
from gym.utils import seeding
import utils
import matplotlib.pyplot as plt
from dynamic_programming_utils import generate_random_policy
class EstimationTask(object):
def __init__(self):
pass
def make_exp_seq(self):
"""Construct the experimental sequence of stimuli and rewards shown to the agent"""
pass
class SharpeRevaluation(EstimationTask):
"""This class simulates the revaluation experiment ran by Sharpe et al.
The correspondence of features and feature numbers:
A = 0
C = 1
D = 2
E = 3
F = 4
X = 5
food = 6
The full experiment has 5 stages
1: preconditioning 1
A --> X (x24)
2: preconditioning 2
EF --> X
AD --> X
AC --> X
A --> X (x8)
3: Conditioning
X --> food (4x24)
4: Devaluation
food --> -10 R (x1)
5: Test
C (x6)
"""
def __init__(self, devalue=False, opto=True):
super().__init__()
self.devalue = devalue
self.opto = opto
self.nr_features = 7
self.feature_names = {
0: 'A',
1: 'C',
2: 'D',
3: 'E',
4: 'F',
5: 'X',
6: 'food'
}
identity = np.eye(self.nr_features)
self.A = identity[0]
self.C = identity[1]
self.D = identity[2]
self.E = identity[3]
self.F = identity[4]
self.X = identity[5]
self.food = identity[6]
self.A_X = np.stack((self.A, self.X + self.A))
self.EF_X = np.stack((self.E + self.F, self.X))
self.AD_X = np.stack((self.A + self.D, self.X))
self.AC_X = np.stack((self.A + self.C, self.X))
self.X_food = np.stack((self.X, self.food + self.X))
self.stim_seq = None
self.reward_seq = None
self.opto_seq = None
self.stage_idx = None
self.make_exp_seq()
def make_exp_seq(self):
"""Construct the experimental sequence of stimuli and rewards shown to the agent"""
# Make stimulus sequence
stage_1 = self.randomise_trials(24, self.A_X) # Preconditioning 1
stage_2 = self.randomise_trials(8, self.EF_X, self.AD_X, self.AC_X) # Preconditioning 2
stage_3 = self.randomise_trials(4*24, self.X_food) # Conditioning
stage_4 = np.tile(self.food, (1, 1)) # Devaluation
stage_5 = np.tile(self.C, (6, 1)) # Test
self.stage_idx = np.concatenate((np.tile(1, len(stage_1)),
np.tile(2, len(stage_2)),
np.tile(3, len(stage_3)),
np.tile(4, len(stage_4)),
np.tile(5, len(stage_5))))
self.stim_seq = np.vstack((stage_1, stage_2, stage_3, stage_4, stage_5))
self.reward_seq = np.zeros(len(self.stim_seq))
idx_c = np.where((self.stim_seq == self.X_food[1]).all(axis=1))[0]
idx_d = np.where((self.stage_idx == 4))[0][0]
self.reward_seq[idx_c] = 1.
if self.devalue:
self.reward_seq[idx_d] = -5.
else:
self.reward_seq[idx_d] = 1.
self.make_opto_seq()
def make_opto_seq(self):
self.opto_seq = np.zeros(len(self.stim_seq))
if self.opto:
opto_idx_acx = np.where((self.stim_seq == self.AC_X[0]).all(axis=1))[0] + 1
opto_idx_adx = np.where((self.stim_seq == self.AD_X[0]).all(axis=1))[0] + 1
self.opto_seq[opto_idx_acx] = 1
self.opto_seq[opto_idx_adx] = 1
def randomise_trials(self, n_trials, *args):
"""Randomise stimulus presentations, adding a vector of zeros between every presentation.
:param n_trials:
:param *args: Stimulus sequences to be added. Each stimulus is an [ s X D ] matrix (s = number of states within
a single stimulus sequence, D = number of features)
:return:
"""
n_cues = len(args)
stimulus_sequence = []
for trial in range(n_trials):
stim_order = np.random.permutation(n_cues)
for cue in stim_order:
stim_length = args[cue].shape[0]
for k in range(stim_length):
stimulus_sequence.append(args[cue][k])
stimulus_sequence.append(np.zeros(self.nr_features))
return np.array(stimulus_sequence)
def get_stage(self, trial):
return self.stage_idx[trial]
class HartRevaluation(EstimationTask):
"""This class simulates the revaluation experiment ran by Hart et al. (2020)
The correspondence of features and feature numbers:
A = 0
C = 1
D = 2
E = 3
F = 4
X = 5
food = 6
The full experiment has 4 stages
1: preconditioning 1
C --> X (x8)
2: Conditioning
X --> food (4x24)
3: Devaluation
food --> -10 R (x1)
4: Test
C (x6)
"""
def __init__(self, devalue=False, opto=True, n_precond_trials=8, n_cond_trials=4*24):
super().__init__()
self.devalue = devalue
self.opto = opto
self.nr_features = 7
self.feature_names = {
0: 'A',
1: 'C',
2: 'D',
3: 'E',
4: 'F',
5: 'X',
6: 'food'
}
identity = np.eye(self.nr_features)
self.A = identity[0]
self.C = identity[1]
self.D = identity[2]
self.E = identity[3]
self.F = identity[4]
self.X = identity[5]
self.food = identity[6]
self.C_X = np.stack((self.C, self.X))
self.X_food = np.stack((self.X, self.food))
self.stim_seq = None
self.reward_seq = None
self.opto_seq = None
self.stage_idx = None
self.make_exp_seq(n_precond_trials, n_cond_trials)
def make_exp_seq(self, n_precond_trials=8, n_cond_trials=4*24):
"""Construct the experimental sequence of stimuli and rewards shown to the agent"""
# Make stimulus sequence
stage_2 = self.randomise_trials(n_precond_trials, self.C_X) # Preconditioning
stage_3 = self.randomise_trials(n_cond_trials, self.X_food) # Conditioning
stage_4 = np.tile(np.stack([self.food, np.zeros(self.food.shape)]), (1, 1)) # Devaluation
stage_5 = np.tile(self.C, (3, 1)) # Test
self.stage_idx = np.concatenate((np.tile(2, len(stage_2)),
np.tile(3, len(stage_3)),
np.tile(4, len(stage_4)),
np.tile(5, len(stage_5))))
self.stim_seq = np.vstack((stage_2, stage_3, stage_4, stage_5))
self.reward_seq = np.zeros(len(self.stim_seq))
idx_c = np.where((self.stim_seq == self.X_food[1]).all(axis=1))[0]
idx_d = np.where((self.stage_idx == 4))[0][0]
self.reward_seq[idx_c] = 1.
if self.devalue:
self.reward_seq[idx_d] = -5.
else:
self.reward_seq[idx_d] = 1.
self.make_opto_seq()
def randomise_trials(self, n_trials, *args):
"""Randomise stimulus presentations, adding a vector of zeros between every presentation.
:param n_trials:
:param *args: Stimulus sequences to be added. Each stimulus is an [ s X D ] matrix (s = number of states within
a single stimulus sequence, D = number of features)
:return:
"""
n_cues = len(args)
stimulus_sequence = []
for trial in range(n_trials):
stim_order = np.random.permutation(n_cues)
for cue in stim_order:
stim_length = args[cue].shape[0]
for k in range(stim_length):
stimulus_sequence.append(args[cue][k])
stimulus_sequence.append(np.zeros(self.nr_features))
return np.array(stimulus_sequence)
def get_stage(self, trial):
return self.stage_idx[trial]
def make_opto_seq(self):
# no opto in this task
self.opto_seq = np.zeros(len(self.stim_seq))
class ControlTask(object):
"""Parent class for RL environments holding some general methods.
"""
def __init__(self):
self.nr_states = None
self.nr_actions = None
self.actions = None
self.adjacency_mat = None
self.goal_state = None
self.reward_func = None
self.graph = None
self.n_features = None
self.rf = None
self.transition_probabilities = None
self.terminal_state = None
self.state_indices = None
self.current_state = None
def act(self, action):
pass
def get_current_state(self):
return self.current_state
def reset(self):
pass
def define_adjacency_graph(self):
pass
def _fill_adjacency_matrix(self):
pass
def get_adjacency_matrix(self):
if self.adjacency_graph is None:
self._fill_adjacency_matrix()
return self.adjacency_graph
def create_graph(self):
"""Create networkx graph from adjacency matrix.
"""
self.graph = nx.from_numpy_array(self.get_adjacency_matrix())
def show_graph(self, map_variable=None, layout=None, node_size=1500, **kwargs):
"""Plot graph showing possible state transitions.
:param node_size:
:param map_variable: Continuous variable that can be mapped on the node colours.
:param layout:
:param kwargs: Any other drawing parameters accepted. See nx.draw docs.
:return:
"""
if layout is None:
layout = nx.spring_layout(self.graph)
if map_variable is not None:
categories = pd.Categorical(map_variable)
node_color = categories
else:
node_color = 'b'
nx.draw(self.graph, with_labels=True, pos=layout, node_color=node_color, node_size=node_size, **kwargs)
def set_reward_location(self, state_idx, action_idx):
self.goal_state = state_idx
action_destination = self.transition_probabilities[state_idx, action_idx]
self.reward_func = np.zeros([self.nr_states, self.nr_actions, self.nr_states])
self.reward_func[state_idx, action_idx] = action_destination
def is_terminal(self, state_idx):
if not self.get_possible_actions(state_idx):
return True
else:
return False
def get_destination_state(self, current_state, current_action):
transition_probabilities = self.transition_probabilities[current_state, current_action]
return np.flatnonzero(transition_probabilities)
def get_degree_mat(self):
degree_mat = np.eye(self.nr_states)
for state, degree in self.graph.degree:
degree_mat[state, state] = degree
return degree_mat
def get_laplacian(self):
return self.get_degree_mat() - self.adjacency_mat
def get_normalised_laplacian(self):
"""Return the normalised laplacian.
"""
D = self.get_degree_mat()
L = self.get_laplacian() # TODO: check diff with non normalised laplacian. check adverserial examples
exp_D = utils.exponentiate(D, -.5)
return exp_D.dot(L).dot(exp_D)
def compute_laplacian(self, normalization_method=None):
"""Compute the Laplacian.
:param normalization_method: Choose None for unnormalized, 'rw' for RW normalized or 'sym' for symmetric.
:return:
"""
if normalization_method not in [None, 'rw', 'sym']:
raise ValueError('Not a valid normalisation method. See help(compute_laplacian) for more info.')
D = self.get_degree_mat()
L = D - self.adjacency_mat
if normalization_method is None:
return L
elif normalization_method == 'sym':
exp_D = utils.exponentiate(D, -.5)
return exp_D.dot(L).dot(exp_D)
elif normalization_method == 'rw':
exp_D = utils.exponentiate(D, -1)
return exp_D.dot(L)
def get_possible_actions(self, state_idx):
pass
def get_adjacent_states(self, state_idx):
pass
def compute_feature_response(self):
pass
def get_transition_matrix(self, policy):
transition_matrix = np.zeros([self.nr_states, self.nr_states])
for state in self.state_indices:
if self.is_terminal(state):
continue
for action in range(self.nr_actions):
transition_matrix[state] += self.transition_probabilities[state, action] * policy[state][action]
return transition_matrix
def get_successor_representation(self, policy, gamma=.95):
transition_matrix = self.get_transition_matrix(policy)
m = np.linalg.inv(np.eye(self.nr_states) - gamma * transition_matrix)
return m
def frep(self, s):
return np.identity(self.nr_states)[s]
def sarep(self, s, a):
return np.identity(self.nr_states * self.nr_actions)[(a * self.nr_states) + s]
def get_next_state(self, origin, action):
pass
def get_reward(self, state, **args):
pass
def get_random_sr(self, gamma=.95):
random_policy = generate_random_policy(self)
random_walk_sr = self.get_successor_representation(random_policy, gamma=gamma)
return random_walk_sr
class SimpleMDP(ControlTask):
"""Very simple MDP with states on a linear track. Agent gets reward of 1 if it reaches last state.
"""
def __init__(self, nr_states=3, reward_probability=1.):
ControlTask.__init__(self)
self.reward_probability = reward_probability
self.nr_states = nr_states
self.n_features = nr_states
self.state_indices = np.arange(self.nr_states)
self.nr_actions = 2
self.actions = [0, 1]
self.action_consequences = {0: -1, 1: +1}
self.terminal_states = [self.nr_states - 1]
self.transition_probabilities = self.define_transition_probabilities()
self.reward_func = np.zeros((self.nr_states, self.nr_actions))
self.reward_func[self.nr_states-2, 1] = 1
self.start_state = 0
self.current_state = self.start_state
def reset(self):
self.current_state = self.start_state
def frep(self, state_idx):
"""Get one-hot feature representation from state index.
"""
if self.is_terminal(state_idx):
return np.zeros(self.nr_states)
else:
return np.eye(self.nr_states)[state_idx]
def define_transition_probabilities(self):
transition_probabilities = np.zeros([self.nr_states, self.nr_actions, self.nr_states])
for predecessor in self.state_indices:
if self.is_terminal(predecessor):
transition_probabilities[predecessor, :, :] = 0
continue
for action_key, consequence in self.action_consequences.items():
successor = int(predecessor + consequence)
if successor not in self.state_indices:
transition_probabilities[predecessor, action_key, predecessor] = 1 # stay in current state
else:
transition_probabilities[predecessor, action_key, successor] = 1
return transition_probabilities
def get_possible_actions(self, state_idx):
if state_idx in self.terminal_states:
return []
else:
return list(self.action_consequences)
def define_adjacency_graph(self):
transitions_under_random_policy = self.transition_probabilities.sum(axis=1)
adjacency_graph = transitions_under_random_policy != 0
return adjacency_graph.astype('int')
def get_transition_matrix(self, policy):
transition_matrix = np.zeros([self.nr_states, self.nr_states])
for state in self.state_indices:
if self.is_terminal(state):
continue
for action in range(self.nr_actions):
transition_matrix[state] += self.transition_probabilities[state, action] * policy[state][action]
return transition_matrix
def get_successor_representation(self, policy, gamma=.95):
transition_matrix = self.get_transition_matrix(policy)
m = np.linalg.inv(np.eye(self.nr_states) - gamma * transition_matrix)
return m
def get_next_state(self, current_state, action):
next_state = np.flatnonzero(self.transition_probabilities[current_state, action])[0]
return next_state
def get_reward(self, current_state, action):
if np.random.rand() <= self.reward_probability:
reward = self.reward_func[current_state, action]
else:
reward = 0.
return reward
def get_next_state_and_reward(self, current_state, action):
# If current state is terminal absorbing state:
if self.is_terminal(current_state):
return current_state, 0
next_state = self.get_next_state(current_state, action)
reward = self.get_reward(current_state, action)
return next_state, reward
def act(self, action):
next_state, reward = self.get_next_state_and_reward(self.current_state, action)
self.current_state = next_state
return next_state, reward
def get_current_state(self):
"""Return current state idx given current position.
"""
return self.current_state
def _fill_adjacency_matrix(self):
self.adjacency_graph = np.zeros((self.nr_states, self.nr_states), dtype=np.int)
for idx in self.state_indices:
if (idx + 1) in self.state_indices:
self.adjacency_graph[idx, idx + 1] = 1
def get_adjacency_matrix(self):
if self.adjacency_graph is None:
self._fill_adjacency_matrix()
return self.adjacency_graph
class DeterministicTask(ControlTask):
"""This class implements the deterministic two-step task described in Doll et al (2015, Nature Neuroscience).
"""
output_folder = 'data/DeterministicTask/'
def __init__(self, n_trials=272):
ControlTask.__init__(self)
self.state_names = ['faces', 'tools', 'bodyparts', 'scenes',
'terminal1', 'terminal2', 'terminal3', 'terminal4']
self.actions = np.array(['left', 'right'])
self.nr_states = len(self.state_names)
self.n_trials = n_trials
self.nr_actions = 2
self.states_actions_outcomes = {
'faces': {
'left': ['bodyparts'],
'right': ['scenes']
},
'tools': {
'left': ['bodyparts'],
'right': ['scenes']
},
'bodyparts': {
'left': ['terminal1'],
'right': ['terminal2']
},
'scenes': {
'left': ['terminal3'],
'right': ['terminal4']
},
'terminal1': {},
'terminal2': {},
'terminal3': {},
'terminal4': {}
}
self._fill_adjacency_matrix()
self.set_transition_probabilities()
self.create_graph()
self.reward_traces = self.load_reward_traces()
self.reward_probs = self.reward_traces[:, 0] # [1, 0, .1, .1]
self.start_state = 0 # Change this to stochastic 0 or 1
self.curr_state = self.start_state
self.curr_action_idx = 0
def _fill_adjacency_matrix(self):
self.adjacency_graph = np.zeros((self.nr_states, self.nr_states))
for idx in range(self.nr_states):
state_name = self.state_names[idx]
actions = self.states_actions_outcomes[state_name]
for act, destination_list in actions.items():
for dest in destination_list:
destination_idx = list(self.states_actions_outcomes.keys()).index(dest)
self.adjacency_graph[idx, destination_idx] = 1
def set_transition_probabilities(self):
"""Set the transition probability matrix.
"""
self.transition_probabilities = np.zeros((self.nr_states, self.nr_actions, self.nr_states))
for state, act_outcome in self.states_actions_outcomes.items():
s_idx = self.get_state_idx(state)
for a_idx, (act, possible_destinations) in enumerate(act_outcome.items()):
for i, d in enumerate(possible_destinations):
d_idx = self.get_state_idx(d)
if len(possible_destinations) == 1:
self.transition_probabilities[s_idx, a_idx, d_idx] = 1
def get_possible_actions(self, state_idx):
state_name = self.state_names[state_idx]
possible_actions = list(self.states_actions_outcomes[state_name].keys())
return possible_actions
def get_state_idx(self, state_name):
return self.state_names.index(state_name)
def is_terminal(self, state_idx):
state_name = self.state_names[state_idx]
return self.states_actions_outcomes[state_name] == {}
def reset(self):
self.start_state = np.random.choice([0, 1])
self.curr_state = self.start_state
def plot_graph(self, map_variable=None, node_size=1500, **kwargs):
positions = {0: [0.25, 2], 1: [1.25, 2], 2: [.25, 1], 3: [1.25, 1],
4: [0, 0], 5: [.5, 0], 6: [1, 0], 7: [1.5, 0]}
self.show_graph(map_variable=map_variable, node_size=node_size,
layout=positions, **kwargs)
def generate_reward_traces(self, **kwargs):
"""Generate reward traces per reward port per trial using a Gaussian random walk and save in file.
:return:
"""
r1 = bounded_random_walk(self.n_trials, **kwargs)
r2 = [1-r for r in r1] # bounded_random_walk(self.n_trials, **kwargs)
#r2 = bounded_random_walk(self.n_trials, **kwargs)
rewards = np.array([r1, r2, r1[::-1], r2[::-1]])
file_path = os.path.join(self.output_folder, 'reward_traces_anticorrelated.npy')
np.save(file_path, rewards)
def load_reward_traces(self):
file_path = os.path.join(self.output_folder, 'reward_traces_anticorrelated.npy')
try:
reward_traces = np.load(file_path)
print('Loaded reward traces from file.')
except FileNotFoundError:
print('Warning: No reward traces file was found so I generate a new one.')
self.generate_reward_traces(avg_stepsize=.05, sigma=.0005)
reward_traces = np.load(file_path)
return reward_traces
class StochasticTask(ControlTask):
"""This class implements the stochastic two-step task as described in Daw et al. (2011, Neuron).
"""
output_folder = 'data/StochasticTask'
def __init__(self, n_trials=272):
ControlTask.__init__(self)
self.state_names = ['initiation', 'left_state', 'right_state',
'terminal1', 'terminal2', 'terminal3', 'terminal4']
self.common_probability = .7
self.rare_probability = 1 - self.common_probability
self.actions = np.array(['left', 'right'])
self.nr_states = len(self.state_names)
self.n_trials = n_trials
self.nr_actions = 2
self.states_actions_outcomes = {
'initiation': {
'left': ['left_state', 'right_state'],
'right': ['right_state', 'left_state']
},
'left_state': {
'left': ['terminal1'],
'right': ['terminal2']
},
'right_state': {
'left': ['terminal3'],
'right': ['terminal4']
},
'terminal1': {},
'terminal2': {},
'terminal3': {},
'terminal4': {}
}
self._fill_adjacency_matrix()
self.set_transition_probabilities()
self.create_graph()
self.reward_traces = self.load_reward_traces()
self.reward_probs = self.reward_traces[:, 0] # [1, 0, .1, .1]
self.start_state = 0
self.curr_state = self.start_state
self.curr_action_idx = 0
def _fill_adjacency_matrix(self):
self.adjacency_graph = np.zeros((self.nr_states, self.nr_states))
for idx in range(self.nr_states):
state_name = self.state_names[idx]
actions = self.states_actions_outcomes[state_name]
for act, destination_list in actions.items():
for dest in destination_list:
destination_idx = list(self.states_actions_outcomes.keys()).index(dest)
self.adjacency_graph[idx, destination_idx] = 1
def set_transition_probabilities(self):
"""Set the transition probability matrix.
"""
self.transition_probabilities = np.zeros((self.nr_states, self.nr_actions, self.nr_states))
for state, act_outcome in self.states_actions_outcomes.items():
s_idx = self.get_state_idx(state)
for a_idx, (act, possible_destinations) in enumerate(act_outcome.items()):
for i, d in enumerate(possible_destinations):
d_idx = self.get_state_idx(d)
if len(possible_destinations) == 1:
self.transition_probabilities[s_idx, a_idx, d_idx] = 1
elif len(possible_destinations) > 1 and i == 0:
self.transition_probabilities[s_idx, a_idx, d_idx] = self.common_probability
elif len(possible_destinations) > 1 and i == 1:
self.transition_probabilities[s_idx, a_idx, d_idx] = self.rare_probability
def plot_graph(self, map_variable=None, node_size=1500, **kwargs):
positions = {0: [0.75, 2], 1: [.25, 1], 2: [1.25, 1],
3: [0, 0], 4: [.5, 0], 5: [1, 0], 6: [1.5, 0]}
self.show_graph(map_variable=map_variable, node_size=node_size,
layout=positions, **kwargs)
def generate_reward_traces(self, **kwargs):
"""Generate reward traces per reward port per trial using a Gaussian random walk and save in file.
:return:
"""
r1 = bounded_random_walk(self.n_trials, **kwargs)
r2 = [1-r for r in r1] # bounded_random_walk(self.n_trials, **kwargs)
#r2 = bounded_random_walk(self.n_trials, **kwargs)
rewards = np.array([r1, r2, r1[::-1], r2[::-1]])
file_path = os.path.join(self.output_folder, 'reward_traces_anticorrelated.npy')
if not os.path.isdir(self.output_folder):
os.makedirs(self.output_folder)
np.save(file_path, rewards)
def load_reward_traces(self):
file_path = os.path.join(self.output_folder, 'reward_traces_anticorrelated.npy')
try:
reward_traces = np.load(file_path)
print('Loaded reward traces from file.')
except FileNotFoundError:
print('Warning: No reward traces file was found so I generate a new one.')
self.generate_reward_traces(avg_stepsize=.05, sigma=.0005)
reward_traces = np.load(file_path)
return reward_traces
def reset(self):
self.curr_state = self.start_state
def get_possible_actions(self, state_idx):
state_name = self.state_names[state_idx]
possible_actions = list(self.states_actions_outcomes[state_name].keys())
return possible_actions
def get_state_idx(self, state_name):
return self.state_names.index(state_name)
def is_terminal(self, state_idx):
state_name = self.state_names[state_idx]
return self.states_actions_outcomes[state_name] == {}
class SquareGrid(ControlTask):
def __init__(self, num_rows=3, num_cols=3):
super().__init__()
self.num_rows = num_rows
self.num_cols = num_cols
self.original_goal_x = None
self.original_goal_y = None
self.goal_x = None
self.goal_y = None
self.nr_occupiable_states = None
self.absorbing_states = []
self.matrix_MDP = self.get_matrix_MDP()
self.start_x = 0
self.start_y = 0
self.curr_x = self.start_x
self.curr_y = self.start_y
self.nr_states = self.num_rows * self.num_cols
self.state_indices = np.arange(self.nr_states)
self.actions = ['up', 'right', 'down', 'left']
self.action_idx = np.arange(len(self.actions))
self.nr_actions = len(self.actions)
self.reset_reward_func()
self._fill_adjacency_matrix()
self.create_graph()
self.define_transition_probabilities()
self.n_features = self.nr_states
def get_matrix_MDP(self):
return np.zeros((self.num_rows, self.num_cols))
def reset_reward_func(self):
if self.goal_x is not None and self.goal_y is not None:
self.reward_func = np.zeros(self.nr_states)
self.goal_state = self.get_state_idx(self.goal_x, self.goal_y)
self.reward_func[self.goal_state] = 10
def set_reward_func(self, rewards, set_goal=True):
"""Set the reward function of the environment.
:param rewards: Vector of length self.nr_states containing the rewards for each states.
:param set_goal: Reset the terminal state to be at the non-zero position of the reward vecctor.
:return:
"""
self.reward_func = rewards
if set_goal:
self.goal_state = np.where(rewards)[0][0]
self.goal_x, self.goal_y = self.get_state_position(self.goal_state)
def get_state_idx(self, x, y):
"""Given coordinates, return the state index.
"""
idx = x + y * self.num_rows
return idx
def get_state_position(self, idx):
"""Given the state index, return the x, y position.
"""
x = idx % self.num_rows
y = (idx - x) / self.num_rows
return int(x), int(y)
def get_next_state(self, origin, action):
x, y = self.get_state_position(origin)
if self.matrix_MDP[x][y] == -1:
return origin
if action == 'up' and y < self.num_rows:
next_x = x
next_y = y + 1
elif action == 'right' and x < self.num_cols:
next_x = x + 1
next_y = y
elif action == 'down' and y >= 0:
next_x = x
next_y = y - 1
elif action == 'left' and x >= 0:
next_x = x - 1
next_y = y
else: # terminate
next_state = self.nr_states
return next_state
if not self.location_in_maze(next_x, next_y):
next_x = x
next_y = y
if self.matrix_MDP[next_x][next_y] == -1:
next_x = x
next_y = y
next_state = self.get_state_idx(next_x, next_y)
return next_state
def get_reward(self, state, **kwargs):
if self.reward_func is None:
return None
reward = self.reward_func[state]
return reward
def is_terminal(self, state_idx):
rewarded_states = np.flatnonzero(self.reward_func)
return state_idx in rewarded_states
def current_state_is_terminal(self):
if self.curr_x == self.goal_x and self.curr_y == self.goal_y:
return True
else:
for loc in self.absorbing_states:
if loc[0] == self.curr_x and loc[1] == self.curr_y:
return True
return False
def get_next_state_and_reward(self, origin, action):
# If current state is terminal absorbing state:
if origin == self.nr_states:
return origin, 0
next_state = self.get_next_state(origin, action)
reward = self.get_reward(next_state, )
return next_state, reward
def get_adjacency_matrix(self):
if self.adjacency_mat is None:
self._fill_adjacency_matrix()
return self.adjacency_mat
def _fill_adjacency_matrix(self):
self.adjacency_mat = np.zeros((self.nr_states, self.nr_states), dtype=np.int)
self.idx_matrix = np.zeros((self.num_rows, self.num_cols), dtype=np.int)
for row in range(len(self.idx_matrix)):
for col in range(len(self.idx_matrix[row])):
self.idx_matrix[row][col] = row * self.num_cols + col
for row in range(len(self.matrix_MDP)):
for col in range(len(self.matrix_MDP[row])):
adj_locs = [[row + 1, col], [row - 1, col], [row, col + 1], [row, col - 1]]
if self.matrix_MDP[row][col] != -1:
for adj_row, adj_col in adj_locs:
if self.location_in_maze(adj_row, adj_col):
if self.matrix_MDP[adj_row, adj_col] != -1:
self.adjacency_mat[self.idx_matrix[row, col]][self.idx_matrix[adj_row, adj_col]] = 1
def location_in_maze(self, row, col):
return row >= 0 and row < self.num_rows and col >= 0 and col < self.num_cols
def get_possible_actions(self, state_idx):
if state_idx == self.goal_state:
return []
else:
return self.actions #list(self.action_idx)
def define_transition_probabilities(self):
self.transition_probabilities = np.zeros([self.nr_states, self.nr_actions, self.nr_states])
for s in self.state_indices:
x, y = self.get_state_position(s)
moves = {0: [x, y + 1], 1: [x + 1, y], 2: [x, y - 1], 3: [x - 1, y]}
if self.matrix_MDP[x][y] != -1:
for a, loc in moves.items():
if self.location_in_maze(loc[0], loc[1]) and self.matrix_MDP[tuple(loc)] != -1:
sprime = self.get_state_idx(loc[0], loc[1])
self.transition_probabilities[s, a, sprime] = 1
else:
self.transition_probabilities[s, a, s] = 1
def reset(self):
"""Reset agent to start position.
"""
self.curr_x = self.start_x
self.curr_y = self.start_y
def get_current_state(self):
"""Return current state idx given current position.
"""
current_state_idx = self.get_state_idx(self.curr_x, self.curr_y)
return current_state_idx
def act(self, action):
"""
:param action:
:return:
"""
current_state = self.get_current_state()
if self.reward_func is None and self.is_terminal(current_state):
return 0
else:
next_state, reward = self.get_next_state_and_reward(current_state, action)
next_x, next_y = self.get_state_position(next_state)
self.curr_x = next_x
self.curr_y = next_y
return next_state, reward
def set_rand_start_location(self):
x = 0
y = 0
while not self.matrix_MDP[x, y] == 0:
x, y = self.get_state_position(np.random.choice(np.arange(self.nr_states)))
self.start_x = x
self.start_y = y
class TransitionRevaluation(ControlTask):
"""This class simulates the transition revaluation experiment designed by Momennejad et al. (2017).
"""
def __init__(self):
ControlTask.__init__(self)
self.nr_states = 7
self.state_indices = list(range(self.nr_states))
self.nr_actions = None
self.actions = None
self.n_features = self.nr_states
self.transitions = {