-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathrl_toy_env.py
1425 lines (1205 loc) · 107 KB
/
rl_toy_env.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
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys, os
import warnings
import logging
import copy
from datetime import datetime
import numpy as np
import scipy
from scipy import stats
import gym
from mdp_playground.spaces import BoxExtended, DiscreteExtended, TupleExtended,\
ImageMultiDiscrete, ImageContinuous
class RLToyEnv(gym.Env):
"""
The base toy environment in MDP Playground. It is parameterised by a config dict and can be instantiated to be an MDP with any of the possible dimensions from the accompanying research paper. The class extends OpenAI Gym's environment gym.Env.
The accompanying paper is available at: https://arxiv.org/abs/1909.07750.
Instead of implementing a new class for every type of MDP, the intent is to capture as many common dimensions across different types of environments as possible and to be able to control the difficulty of an environment by allowing fine-grained control over each of these dimensions. The focus is to be as flexible as possible.
The configuration for the environment is passed as a dict at initialisation and contains all the information needed to determine the dynamics of the MDP that the instantiated environment will emulate. We recommend looking at the examples in example.py to begin using the environment since the dimensions and config options are mostly self-explanatory. If you want to specify custom MDPs, please see the use_custom_mdp config option below. For more details, we list here the dimensions and config options (their names here correspond to the keys to be passed in the config dict):
delay : int >= 0
Delays each reward by this number of timesteps.
sequence_length : int >= 1
Intrinsic sequence length of the reward function of an environment. For discrete environments, randomly selected sequences of this length are set to be rewardable at initialisation if use_custom_mdp = false and generate_random_mdp = true.
transition_noise : float in range [0, 1] or Python function(rng)
For discrete environments, it is a float that specifies the fraction of times the environment transitions to a noisy next state at each timestep, independently and uniformly at random.
For continuous environments, if it's a float, it's used as the standard deviation of an i.i.d. normal distribution of noise. If it is a Python function with one argument, it is added to next state. The argument is the Random Number Generator (RNG) of the environment which is an np.random.RandomState object. This RNG should be used to perform calls to the desired random function to be used as noise to ensure reproducibility.
reward_noise : float or Python function(rng)
If it's a float, it's used as the standard deviation of an i.i.d. normal distribution of noise.
If it's a Python function with one argument, it is added to the reward given at every time step. The argument is the Random Number Generator (RNG) of the environment which is an np.random.RandomState object. This RNG should be used to perform calls to the desired random function to be used as noise to ensure reproducibility.
reward_density : float in range [0, 1]
The fraction of possible sequences of a given length that will be selected to be rewardable at initialisation time.
reward_scale : float
Multiplies the rewards by this value at every time step.
reward_shift : float
This value is added to the reward at every time step.
diameter : int > 0
For discrete environments, if diameter = d, the set of states is set to be a d-partite graph (and NOT a complete d-partite graph), where, if we order the d sets as 1, 2, .., d, states from set 1 will have actions leading to states in set 2 and so on, with the final set d having actions leading to states in set 1. Number of actions for each state will, thus, be = (number of states) / (d).
terminal_state_density : float in range [0, 1]
For discrete environments, the fraction of states that are terminal; the terminal states are fixed to the "last" states when we consider them to be ordered by their numerical value. This is w.l.o.g. because discrete states are categorical. For continuous environments, please see terminal_states and term_state_edge for how to control terminal states.
term_state_reward : float
Adds this to the reward if a terminal state was reached at the current time step.
irrelevant_features : boolean
If True, an additional irrelevant sub-space (irrelevant to achieving rewards) is present as part of the observation space. This sub-space has its own transition dynamics independent of the dynamics of the relevant sub-space. For discrete environments, additionally, state_space_size must be specified as a list. For continuous environments, the option relevant_indices must be specified. This option specifies the dimensions relevant to achieving rewards.
use_custom_mdp : boolean
If true, users specify their own transition and reward functions using the config options transition_function and reward_function (see below). Optionally, they can also use init_state_dist and terminal_states for discrete spaces (see below).
transition_function : Python function(state, action) or a 2-D numpy.ndarray
A Python function emulating P(s, a). For discrete envs it's also possible to specify an |S|x|A| transition matrix.
reward_function : Python function(state_sequence, action_sequence) or a 2-D numpy.ndarray
A Python function emulating R(state_sequence, action_sequence). The state_sequence is recorded by the environment and transition_function is called before reward_function, so the "current" state (when step() was called) and next state are the last 2 states in the sequence. For discrete environments, it's also possible to specify an |S|x|A| transition matrix where reward is assumed to be a function over the "current" state and action. If use_custom_mdp = false and the environment is continuous, this is a string that chooses one of the following predefined reward functions: move_along_a_line or move_to_a_point.
Specific to discrete environments:
state_space_size : int > 0 or list of length 2
A number specifying size of the state space for normal discrete environments and a list of len = 2 when irrelevant_features is True (The list contains sizes of relevant and irrelevant sub-spaces where the 1st sub-space is assumed relevant and the 2nd sub-space is assumed irrelevant).
NOTE: When automatically generating MDPs, do not specify this value as its value depends on the action_space_size and the diameter as state_space_size = action_space_size * diameter.
action_space_size : int > 0
Similar description as state_space_size. When automatically generating MDPs, however, its value determines the state_space_size.
reward_dist : list with 2 floats or a Python function(env_rng, reward_sequence_dict)
If it's a list with 2 floats, then these 2 values are interpreted as a closed interval and taken as the end points of a categorical distribution which points equally spaced along the interval.
If it's a Python function, it samples rewards for the rewardable_sequences dict of the environment. The rewardable_sequences dict of the environment holds the rewardable_sequences with the key as a tuple holding the sequence and value as the reward handed out. The 1st argument for the reward_dist function is the Random Number Generator (RNG) of the environment which is an np.random.RandomState object. This RNG should be used to perform calls to the desired random function to be used to sample rewards to ensure reproducibility. The 2nd argument is the rewardable_sequences dict of the environment. This is available because one may need access to the already created reward sequences in the reward_dist function.
init_state_dist : 1-D numpy.ndarray
Specifies an array of initialisation probabilities for the discrete state space.
terminal_states : Python function(state) or 1-D numpy.ndarray
A Python function with the state as argument that returns whether the state is terminal. If this is specified as an array, the array lists the discrete states that are terminal.
image_representations : boolean
Boolean to associate an image as the external observation with every discrete categorical state. This is handled by an mdp_playground.spaces.ImageMultiDiscrete object. It associates the image of an n + 3 sided polygon for a categorical state n. More details can be found in the documentation for the ImageMultiDiscrete class.
Specific to image_representations:
image_transforms : str
String containing the transforms that must be applied to the image representations. As long as one of the following words is present in the string - shift, scale, rotate, flip - the corresponding transform will be applied at random to the polygon in the image representation whenever an observation is generated. Care is either explicitly taken that the polygon remains inside the image region or a warning is generated.
sh_quant : int
An int to quantise the shift transforms.
scale_range : (float, float)
A tuple of real numbers to specify (min_scaling, max_scaling).
ro_quant : int
An int to quantise the rotation transforms.
Specific to continuous environments:
state_space_dim : int
A number specifying state space dimensionality. A Gym Box space of this dimensionality will be instantiated.
action_space_dim : int
Same description as state_space_dim. This is currently set equal to the state_space_dim and doesn't need to specified.
relevant_indices : list
A list that provides the dimensions relevant to achieving rewards for continuous environments. The dynamics for these dimensions are independent of the dynamics for the remaining (irrelevant) dimensions.
state_space_max : float
Max absolute value that a dimension of the space can take. A Gym Box will be instantiated with range [-state_space_max, state_space_max]. Sampling will be done as for Gym Box spaces.
action_space_max : float
Similar description as for state_space_max.
terminal_states : numpy.ndarray
The centres of hypercube sub-spaces which are terminal.
term_state_edge : float
The edge of the hypercube sub-spaces which are terminal.
transition_dynamics_order : int
An order of n implies that the n-th state derivative is set equal to the action/inertia.
inertia : float or numpy.ndarray
inertia of the rigid body or point object that is being simulated. If numpy.ndarray, it specifies independent inertiae for the dimensions and the shape should be (state_space_dim,).
time_unit : float
time duration over which the action is applied to the system.
target_point : numpy.ndarray
The target point in case move_to_a_point is the reward_function. If make_denser is false, target_radius determines distance from the target point at which the sparse reward is handed out.
action_loss_weight : float
A coefficient to multiply the norm of the action and subtract it from the reward to penalise the action magnitude.
Other important config:
Specific to discrete environments:
repeats_in_sequences : boolean
If true, allows rewardable sequences to have repeating states in them.
maximally_connected : boolean
If true, sets the transition function such that every state in independent set i can transition to every state in independent set i + 1. If false, then sets the transition function such that a state in independent set i may have any state in independent set i + 1 as the next state for a transition.
reward_every_n_steps : boolean
Hand out rewards only at multiples of sequence_length steps. This makes the probability that an agent is executing overlapping rewarding sequences 0. This makes it simpler to evaluate HRL algorithms and whether they can "discretise" time correctly. Noise is added at every step, regardless of this setting. Currently, not implemented for either the make_denser = true case or for continuous environments.
generate_random_mdp : boolean
If true, automatically generate MDPs when use_custom_mdp = false. Currently, this option doesn't need to be specified because random MDPs are always generated when use_custom_mdp = false.
Specific to continuous environments:
none as of now
For both, continuous and discrete environments:
make_denser : boolean
If true, makes the reward denser in environments. For discrete environments, hands out a partial reward for completing partial sequences. For continuous environments, for reward function move_to_a_point, the base reward handed out is equal to the distance moved towards the target point in the current timestep.
seed : int or dict
Recommended to be passed as an int which generates seeds to be used for the various components of the environment. It is, however, possible to control individual seeds by passing it as a dict. Please see the default initialisation for seeds below to see how to do that.
log_filename : str
The name of the log file to which logs are written.
log_level : logging.LOG_LEVEL option
Python log level for logging
Below, we list the important attributes and methods for this class.
Attributes
----------
config : dict
the config contains all the details required to generate an environment
seed : int or dict
recommended to set to an int, which would set seeds for the env, relevant and irrelevant and externally visible observation and action spaces automatically. If fine-grained control over the seeds is necessary, a dict, with key values as in the source code further below, can be passed.
observation_space : Gym.Space
The externally visible observation space for the enviroment.
action_space : Gym.Space
The externally visible action space for the enviroment.
rewardable_sequences : dict
holds the rewardable sequences. The keys are tuples of rewardable sequences and values are the rewards handed out. When make_denser is True for discrete environments, this dict also holds the rewardable partial sequences.
Methods
-------
init_terminal_states()
Initialises terminal states, T
init_init_state_dist()
Initialises initial state distribution, rho_0
init_transition_function()
Initialises transition function, P
init_reward_function()
Initialises reward function, R
transition_function(state, action)
the transition function of the MDP, P
P(state, action)
defined as a lambda function in the call to init_transition_function() and is equivalent to calling transition_function()
reward_function(state, action)
the reward function of the MDP, R
R(state, action)
defined as a lambda function in the call to init_reward_function() and is equivalent to calling reward_function()
get_augmented_state()
gets underlying Markovian state of the MDP
reset()
Resets environment state
seed()
Sets the seed for the numpy RNG used by the environment (state and action spaces have their own seeds as well)
step(action, imaginary_rollout=False)
Performs 1 transition of the MDP
"""
def __init__(self, **config): # = None):
"""Initialises the MDP to be emulated using the settings provided in config.
Parameters
----------
config : dict
the member variable config is initialised to this value after inserting defaults
"""
print("Passed config:", config, "\n")
# Set default settings for config to be able to use class without any config being passed
if len(config) == 0: #is None:
# config = {}
# Discrete spaces configs:
config["state_space_type"] = "discrete" # TODO if states are assumed categorical in discrete setting, need to have an embedding for their OHE when using NNs; do the encoding on the training end!
config["action_space_type"] = "discrete"
config["state_space_size"] = 8 # To be given as an integer for simple Discrete environment like Gym's. To be given as a list of integers for a MultiDiscrete environment like Gym's #TODO Rename state_space_size and action_space_size to be relevant_... wherever irrelevant dimensions are not used.
config["action_space_size"] = 8
# Continuous spaces configs:
# config["state_space_type"] = "continuous"
# config["action_space_type"] = "continuous"
# config["state_space_dim"] = 2
# config["action_space_dim"] = 2
# config["transition_dynamics_order"] = 1
# config["inertia"] = 1 # 1 unit, e.g. kg for mass, or kg * m^2 for moment of inertia.
# config["state_space_max"] = 5 # Will be a Box in the range [-max, max]
# config["action_space_max"] = 5 # Will be a Box in the range [-max, max]
# config["time_unit"] = 0.01 # Discretization of time domain
# config["terminal_states"] = [[0.0, 1.0], [1.0, 0.0]]
# config["term_state_edge"] = 1.0 # Terminal states will be in a hypercube centred around the terminal states given above with the edge of the hypercube of this length.
# config for user specified P, R, rho_0, T. Examples here are for discrete spaces
# config["transition_function"] = np.array([[4 - i for i in range(config["state_space_size"])] for j in range(config["action_space_size"])]) #TODO ###IMP For all these prob. dist., there's currently a difference in what is returned for discrete vs continuous!
# config["reward_function"] = np.array([[4 - i for i in range(config["state_space_size"])] for j in range(config["action_space_size"])])
# config["init_state_dist"] = np.array([i/10 for i in range(config["state_space_size"])])
# config["terminal_states"] = np.array([config["state_space_size"] - 1]) # Can be discrete array or function to test terminal or not (e.g. for discrete and continuous spaces we may prefer 1 of the 2) #TODO currently always the same terminal state for a given environment state space size; have another variable named terminal_states to make semantic sense of variable name.
config["generate_random_mdp"] = True ###IMP # This supersedes previous settings and generates a random transition function, a random reward function (for random specific sequences)
config["delay"] = 0
config["sequence_length"] = 1
config["repeats_in_sequences"] = False
config["reward_scale"] = 1.0
config["reward_density"] = 0.25 # Number between 0 and 1
# config["transition_noise"] = 0.2 # Currently the fractional chance of transitioning to one of the remaining states when given the deterministic transition function - in future allow this to be given as function; keep in mind that the transition function itself could be made a stochastic function - does that qualify as noise though?
# config["reward_noise"] = lambda a: a.normal(0, 0.1) #random #hack # a probability function added to reward function
# config["transition_noise"] = lambda a: a.normal(0, 0.1) #random #hack # a probability function added to transition function in cont. spaces
config["make_denser"] = False
config["terminal_state_density"] = 0.25 # Number between 0 and 1
config["maximally_connected"] = True # Make every state reachable from every state; If maximally_connected, then no. of actions has to be at least equal to no. of states( - 1 if without self-loop); if repeating sequences allowed, then we have to have self-loops. Self-loops are ok even in non-repeating sequences - we just have a harder search problem then! Or make it maximally connected by having transitions to as many different states as possible - the row for P would have as many different transitions as possible!
# print(config)
#TODO asserts for the rest of the config settings
# next: To implement delay, we can keep the previous observations to make state Markovian or keep an info bit in the state to denote that; Buffer length increase by fixed delay and fixed sequence length; current reward is incremented when any of the satisfying conditions (based on previous states) matches
config["seed"] = 0
# Print initial "banner"
screen_output_width = 132 #hardcoded #TODO get from system
repeat_equal_sign = (screen_output_width - 20) // 2
set_ansi_escape = "\033[32;1m"
reset_ansi_escape = "\033[0m"
print(set_ansi_escape + "=" * repeat_equal_sign + "Initialising Toy MDP" + "=" * repeat_equal_sign + reset_ansi_escape)
print("Current working directory:", os.getcwd())
# Set other default settings for config to use if config is passed without any values for them
if "log_level" not in config:
self.log_level = logging.CRITICAL #logging.NOTSET
else:
self.log_level = config["log_level"]
# print('self.log_level', self.log_level)
logging.getLogger(__name__).setLevel(self.log_level)
# fmtr = logging.Formatter(fmt='%(message)s - %(levelname)s - %(name)s - %(asctime)s', datefmt='%m.%d.%Y %I:%M:%S %p', style='%')
# sh = logging.StreamHandler()
# sh.setFormatter(fmt=fmtr)
self.logger = logging.getLogger(__name__)
# self.logger.addHandler(sh)
if "log_filename" in config:
# self.log_filename = __name__ + '_' + datetime.today().strftime('%m.%d.%Y_%I:%M:%S_%f') + '.log' #TODO Make a directoy 'log/' and store there.
# else:
if not self.logger.handlers: # checks that handlers is [], before adding a file logger, otherwise we would have multiple loggers to file if multiple RLToyEnvs were instantiated by the same process.
self.log_filename = config["log_filename"]
# logging.basicConfig(filename='/tmp/' + self.log_filename, filemode='a', format='%(message)s - %(levelname)s - %(name)s - %(asctime)s', datefmt='%m.%d.%Y %I:%M:%S %p', level=self.log_level)
log_file_handler = logging.FileHandler(self.log_filename)
self.logger.addHandler(log_file_handler)
# log_filename = "logs/output.log"
# os.makedirs(os.path.dirname(log_filename), exist_ok=True)
#seed
if "seed" not in config: #####IMP It's very important to not modify the config dict since it may be shared across multiple instances of the Env in the same process and could lead to very hard to catch bugs (I faced problems with Ray's A3C)
self.seed_int = None
need_to_gen_seeds = True
elif type(config["seed"]) == dict:
self.seed_dict = config["seed"]
need_to_gen_seeds = False
elif type(config["seed"]) == int: # should be an int then. Gym doesn't accept np.int64, etc..
self.seed_int = config["seed"]
need_to_gen_seeds = True
else:
raise TypeError("Unsupported data type for seed: ", type(config["seed"]))
#seed #TODO move to seed() so that obs., act. space, etc. have their seeds reset too when env seed is reset?
if need_to_gen_seeds:
self.seed_dict = {}
self.seed_dict["env"] = self.seed_int
self.seed(self.seed_dict["env"])
##IMP All these diff. seeds may not be needed (you could have one seed for the joint relevant + irrelevant parts). But they allow for easy separation of the relevant and irrelevant dimensions!! _And_ the seed remaining the same for the underlying discrete environment makes it easier to write tests!
self.seed_dict["relevant_state_space"] = self.np_random.randint(sys.maxsize) #random
self.seed_dict["relevant_action_space"] = self.np_random.randint(sys.maxsize) #random
self.seed_dict["irrelevant_state_space"] = self.np_random.randint(sys.maxsize) #random
self.seed_dict["irrelevant_action_space"] = self.np_random.randint(sys.maxsize) #random
self.seed_dict["state_space"] = self.np_random.randint(sys.maxsize) #IMP This is currently used to sample only for continuous spaces and not used for discrete spaces by the Environment. User might want to sample from it for multi-discrete environments. #random
self.seed_dict["action_space"] = self.np_random.randint(sys.maxsize) #IMP This IS currently used to sample random actions by the RL agent for both discrete and continuous environments (but not used anywhere by the Environment). #random
self.seed_dict["image_representations"] = self.np_random.randint(sys.maxsize) #random
# print("Mersenne0, dummy_eval:", self.np_random.get_state()[2], "dummy_eval" in config)
else: # if seed dict was passed
self.seed(self.seed_dict["env"])
# print("Mersenne0 (dict), dummy_eval:", self.np_random.get_state()[2], "dummy_eval" in config)
self.logger.warning('Seeds set to:' + str(self.seed_dict))
# print(f'Seeds set to {self.seed_dict=}') # Available from Python 3.8
#defaults ###TODO throw warning in case unknown config option is passed
if "use_custom_mdp" not in config:
self.use_custom_mdp = False
else:
self.use_custom_mdp = config["use_custom_mdp"]
if self.use_custom_mdp:
assert "transition_function" in config
assert "reward_function" in config
# if config["state_space_type"] == "discrete":
# assert "init_state_dist" in config
if not self.use_custom_mdp:
if "generate_random_mdp" not in config:
self.generate_random_mdp = True
else:
self.generate_random_mdp = config["generate_random_mdp"]
if "term_state_reward" not in config:
self.term_state_reward = 0.0
else:
self.term_state_reward = config["term_state_reward"]
if "delay" not in config:
self.delay = 0
else:
self.delay = config["delay"]
self.reward_buffer = [0.0] * (self.delay)
if "sequence_length" not in config:
self.sequence_length = 1
else:
self.sequence_length = config["sequence_length"]
if "reward_density" not in config:
self.reward_density = 0.25
else:
self.reward_density = config["reward_density"]
if "make_denser" not in config:
self.make_denser = False
else:
self.make_denser = config["make_denser"]
if "maximally_connected" not in config:
self.maximally_connected = True
else:
self.maximally_connected = config["maximally_connected"]
if "reward_noise" in config:
if callable(config["reward_noise"]):
self.reward_noise = config["reward_noise"]
else:
reward_noise_std = config["reward_noise"]
self.reward_noise = lambda a: a.normal(0, reward_noise_std)
else:
self.reward_noise = None
if "transition_noise" in config:
if config["state_space_type"] == "continuous":
if callable(config["transition_noise"]):
self.transition_noise = config["transition_noise"]
else:
p_noise_std = config["transition_noise"]
self.transition_noise = lambda a: a.normal(0, p_noise_std)
else: # discrete case
self.transition_noise = config["transition_noise"]
else: # no transition noise
self.transition_noise = None
if "reward_scale" not in config:
self.reward_scale = 1.0
else:
self.reward_scale = config["reward_scale"]
if "reward_shift" not in config:
self.reward_shift = 0.0
else:
self.reward_shift = config["reward_shift"]
if "irrelevant_features" not in config:
self.irrelevant_features = False
else:
self.irrelevant_features = config["irrelevant_features"]
if "image_representations" not in config:
self.image_representations = False
else:
self.image_representations = config["image_representations"]
if "image_transforms" in config:
assert config["state_space_type"].lower() == "discrete", "Image\
transforms are only applicable to discrete envs."
self.image_transforms = config["image_transforms"]
else:
self.image_transforms = "none"
if "image_width" in config:
self.image_width = config["image_width"]
else:
self.image_width = 100
if "image_height" in config:
self.image_height = config["image_height"]
else:
self.image_height = 100
# The following transforms are only applicable in discrete envs:
if config["state_space_type"] == "discrete":
if "image_sh_quant" not in config:
if 'shift' in self.image_transforms:
warnings.warn("Setting image shift quantisation to the \
default of 1, since no config value was provided for it.")
self.image_sh_quant = 1
else:
self.image_sh_quant = None
else:
self.image_sh_quant = config["image_sh_quant"]
if "image_ro_quant" not in config:
if 'rotate' in self.image_transforms:
warnings.warn("Setting image rotate quantisation to the \
default of 1, since no config value was provided for it.")
self.image_ro_quant = 1
else:
self.image_ro_quant = None
else:
self.image_ro_quant = config["image_ro_quant"]
if "image_scale_range" not in config:
if 'scale' in self.image_transforms:
warnings.warn("Setting image scale range to the default \
of (0.5, 1.5), since no config value was provided for it.")
self.image_scale_range = (0.5, 1.5)
else:
self.image_scale_range = None
else:
self.image_scale_range = config["image_scale_range"]
if config["state_space_type"] == "discrete":
if "reward_dist" not in config:
self.reward_dist = None
else:
self.reward_dist = config["reward_dist"]
if "diameter" not in config:
self.diameter = 1
else:
self.diameter = config["diameter"]
else: # cont. spaces
# if not self.use_custom_mdp:
self.state_space_dim = config["state_space_dim"]
if "transition_dynamics_order" not in config:
self.dynamics_order = 1
else:
self.dynamics_order = config["transition_dynamics_order"]
if 'inertia' not in config:
self.inertia = 1.0
else:
self.inertia = config["inertia"]
if 'time_unit' not in config:
self.time_unit = 1.0
else:
self.time_unit = config["time_unit"]
if 'target_radius' not in config:
self.target_radius = 0.05
else:
self.target_radius = config["target_radius"]
if "action_loss_weight" not in config:
self.action_loss_weight = 0.0
else:
self.action_loss_weight = config["action_loss_weight"]
if "reward_every_n_steps" not in config:
self.reward_every_n_steps = False
else:
self.reward_every_n_steps = config["reward_every_n_steps"]
if 'repeats_in_sequences' not in config:
self.repeats_in_sequences = False
else:
self.repeats_in_sequences = config['repeats_in_sequences']
self.dtype = np.float32 if "dtype" not in config else config["dtype"]
#TODO Make below code more compact by reusing parts for state and action spaces?
config["state_space_type"] = config["state_space_type"].lower()
config["action_space_type"] = config["state_space_type"]
# config["action_space_type"] = config["action_space_type"].lower()
if config["state_space_type"] == "discrete":
if self.irrelevant_features:
assert len(config["action_space_size"]) == 2, "Currently, 1st sub-state (and action) space is assumed to be relevant to rewards and 2nd one is irrelevant. Please provide a list with sizes for the 2."
self.action_space_size = config["action_space_size"]
else: # uni-discrete space
assert isinstance(config["action_space_size"], int), "Did you mean to turn irrelevant_features? If so, please set irrelevant_features = True in config. If not, please provide an int for action_space_size."
self.action_space_size = [config["action_space_size"]] # Make a list to be able to iterate over observation spaces in for loops later
# assert type(config["state_space_size"]) == int, 'config["state_space_size"] has to be provided as an int when we have a simple Discrete environment. Was:' + str(type(config["state_space_size"]))
if self.use_custom_mdp:
self.state_space_size = [config["state_space_size"]]
else:
self.state_space_size = np.array(self.action_space_size) * np.array(self.diameter)
# assert (np.array(self.state_space_size) % np.array(self.diameter) == 0).all(), "state_space_size should be a multiple of the diameter to allow for the generation of regularly connected MDPs."
else: # cont. space
self.action_space_dim = self.state_space_dim
if self.irrelevant_features:
assert "relevant_indices" in config, "Please provide dimensions\
of state space relevant to rewards."
if "relevant_indices" not in config:
config["relevant_indices"] = range(self.state_space_dim)
# config["irrelevant_indices"] = list(set(range(len(config["state_space_dim"]))) - set(config["relevant_indices"]))
if ("init_state_dist" in config) and ("relevant_init_state_dist" not in config):
config["relevant_init_state_dist"] = config["init_state_dist"]
# assert config["action_space_type"] == config["state_space_type"], 'config["state_space_type"] != config["action_space_type"]. Currently mixed space types are not supported.'
assert self.sequence_length > 0, "config[\"sequence_length\"] <= 0. Set to: " + str(self.sequence_length) # also should be int
if "maximally_connected" in config and config["maximally_connected"]: ###TODO remove
pass
# assert config["state_space_size"] == config["action_space_size"], "config[\"state_space_size\"] != config[\"action_space_size\"]. For maximally_connected transition graphs, they should be equal. Please provide valid values. Vals: " + str(config["state_space_size"]) + " " + str(config["action_space_size"]) + ". In future, \"maximally_connected\" graphs are planned to be supported!"
# assert config["irrelevant_state_space_size"] == config["irrelevant_action_space_size"], "config[\"irrelevant_state_space_size\"] != config[\"irrelevant_action_space_size\"]. For maximally_connected transition graphs, they should be equal. Please provide valid values! Vals: " + str(config["irrelevant_state_space_size"]) + " " + str(config["irrelevant_action_space_size"]) + ". In future, \"maximally_connected\" graphs are planned to be supported!" #TODO Currently, irrelevant dimensions have a P similar to that of relevant dimensions. Should this be decoupled?
if config["state_space_type"] == 'continuous':
# assert config["state_space_dim"] == config["action_space_dim"], "For continuous spaces, state_space_dim has to be = action_space_dim. state_space_dim was: " + str(config["state_space_dim"]) + " action_space_dim was: " + str(config["action_space_dim"])
if config["reward_function"] == "move_to_a_point":
self.target_point = np.array(config["target_point"], dtype=self.dtype)
assert self.target_point.shape == (len(config["relevant_indices"]),), "target_point should have dimensionality = relevant_state_space dimensionality"
self.config = config
self.augmented_state_length = self.sequence_length + self.delay + 1
self.total_episodes = 0
# This init_...() is done before the others below because it's needed
# for image_representations for continuous
self.init_terminal_states()
if config["state_space_type"] == "discrete":
self.observation_spaces = [DiscreteExtended(self.state_space_size[0], seed=self.seed_dict["relevant_state_space"])] #seed #hardcoded, many time below as well
self.action_spaces = [DiscreteExtended(self.action_space_size[0], seed=self.seed_dict["relevant_action_space"])] #seed #hardcoded
if self.irrelevant_features:
self.observation_spaces.append(DiscreteExtended(self.state_space_size[1], seed=self.seed_dict["irrelevant_state_space"])) #seed #hardcoded
self.action_spaces.append(DiscreteExtended(self.action_space_size[1], seed=self.seed_dict["irrelevant_action_space"])) #seed #hardcoded
# Commented code below may used to generalise relevant sub-spaces to more than the current max of 2.
# self.observation_spaces = [None] * len(config["all_indices"])
# for i in config["relevant_indices"]:
# self.observation_spaces[i] =
# self.action_spaces[i] = DiscreteExtended(self.action_space_size[i], seed=self.seed_dict["relevant_action_space"]) #seed
# for i in config["irrelevant_indices"]:
# self.observation_spaces[i] = DiscreteExtended(self.state_space_size[i], seed=self.seed_dict["irrelevant_state_space"])) #seed # hack
# self.action_spaces[i] = DiscreteExtended(self.action_space_size[i], seed=self.seed_dict["irrelevant_action_space"]) #seed
if self.image_representations:
# underlying_obs_space = MultiDiscreteExtended(self.state_space_size, seed=self.seed_dict["state_space"]) #seed
self.observation_space = ImageMultiDiscrete(self.state_space_size, width=self.image_width, height=self.image_height, transforms=self.image_transforms, sh_quant=self.image_sh_quant, scale_range=self.image_scale_range, ro_quant=self.image_ro_quant, circle_radius=20, seed=self.seed_dict["image_representations"]) #seed
if self.irrelevant_features:
self.action_space = TupleExtended(self.action_spaces, seed=self.seed_dict["action_space"]) #seed
else:
self.action_space = self.action_spaces[0]
else:
if self.irrelevant_features:
self.observation_space = TupleExtended(self.observation_spaces, seed=self.seed_dict["state_space"]) #seed # hack #TODO Gym (and so Ray) apparently needs observation_space as a member of an env.
self.action_space = TupleExtended(self.action_spaces, seed=self.seed_dict["action_space"]) #seed
else:
self.observation_space = self.observation_spaces[0]
self.action_space = self.action_spaces[0]
else: # cont. spaces
self.state_space_max = config["state_space_max"] \
if 'state_space_max' in config else np.inf # should we
# select a random max? #test?
self.feature_space = BoxExtended(-self.state_space_max,\
self.state_space_max, shape=(self.state_space_dim,),\
seed=self.seed_dict["state_space"], dtype=self.dtype) #seed
# hack #TODO # low and high are 1st 2 and required arguments
# for instantiating BoxExtended
self.action_space_max = config["action_space_max"] \
if 'action_space_max' in config else np.inf #test?
# config["action_space_max"] = \
# num_to_list(config["action_space_max"]) * config["action_space_dim"]
self.action_space = BoxExtended(-self.action_space_max,\
self.action_space_max, shape=(self.action_space_dim,),\
seed=self.seed_dict["action_space"], dtype=self.dtype) #seed
# hack #TODO
if self.image_representations:
self.observation_space = ImageContinuous(self.feature_space,\
width=self.image_width, height=self.image_height, \
term_spaces=self.term_spaces, target_point=self.target_point,\
circle_radius=5, seed=self.seed_dict["image_representations"]) #seed
else:
self.observation_space = self.feature_space
# if config["action_space_type"] == "discrete":
# if not config["generate_random_mdp"]:
# # self.logger.error("User defined P and R are currently not supported.") ##TODO
# # sys.exit(1)
# self.P = config["transition_function"] if callable(config["transition_function"]) else lambda s, a: config["transition_function"][s, a] ##IMP callable may not be optimal always since it was deprecated in Python 3.0 and 3.1
# self.R = config["reward_function"] if callable(config["reward_function"]) else lambda s, a: config["reward_function"][s, a]
# else:
##TODO Support imaginary rollouts for continuous envs. and user-defined P and R? Will do it depending on demand for it. In fact, for imagined rollouts, let our code handle storing augmented_state, curr_state, etc. in separate variables, so that it's easy for user to perform imagined rollouts instead of having to maintain their own state and action sequences.
#TODO Generate state and action space sizes also randomly?
###IMP The order in which the following inits are called is important, so don't change!!
self.init_init_state_dist() #init_state_dist: Initialises uniform distribution over non-terminal states for discrete distribution; After looking into Gym code, I can say that for continuous, it's uniform over non-terminal if limits are [a, b], shifted exponential if exactly one of the limits is np.inf, normal if both limits are np.inf - this sampling is independent for each dimension (and is done for the defined limits for the respective dimension).
self.init_transition_function()
# print("Mersenne1, dummy_eval:", self.np_random.get_state()[2], "dummy_eval" in self.config)
self.init_reward_function()
self.curr_obs = self.reset() #TODO Maybe not call it here, since Gym seems to expect to _always_ call this method when using an environment; make this seedable? DO NOT do seed dependent initialization in reset() otherwise the initial state distrbution will always be at the same state at every call to reset()!! (Gym env has its own seed? Yes, it does, as does also space);
self.logger.info("self.augmented_state, len: " + str(self.augmented_state) + ", " + str(len(self.augmented_state)))
self.logger.info("MDP Playground toy env instantiated with config: " + str(self.config))
print("MDP Playground toy env instantiated with config: " + str(self.config))
def init_terminal_states(self):
"""Initialises terminal state set to be the 'last' states for discrete environments. For continuous environments, terminal states will be in a hypercube centred around config['terminal_states'] with the edge of the hypercube of length config['term_state_edge'].
"""
if self.config["state_space_type"] == "discrete":
if self.use_custom_mdp and not "terminal_state_density" in self.config: # custom/user-defined terminal states
self.is_terminal_state = self.config["terminal_states"] if callable(self.config["terminal_states"]) else lambda s: s in self.config["terminal_states"]
else:
# Define the no. of terminal states per independent set of the state space
self.num_terminal_states = int(self.config["terminal_state_density"] * self.action_space_size[0]) #hardcoded ####IMP Using action_space_size since it contains state_space_size // diameter
# if self.num_terminal_states == 0: # Have at least 1 terminal state?
# warnings.warn("WARNING: int(terminal_state_density * relevant_state_space_size) was 0. Setting num_terminal_states to be 1!")
# self.num_terminal_states = 1
self.config["terminal_states"] = np.array([j * self.action_space_size[0] - 1 - i for j in range(1, self.diameter + 1) for i in range(self.num_terminal_states)]) # terminal states inited to be at the "end" of the sorted states
self.logger.warning("Inited terminal states to self.config['terminal_states']: " + str(self.config["terminal_states"]) + ". Total " + str(self.num_terminal_states))
self.is_terminal_state = lambda s: s in self.config["terminal_states"]
else: # if continuous space
# print("# TODO for cont. spaces: term states")
self.term_spaces = []
if 'terminal_states' in self.config: ##TODO For continuous spaces, could also generate terminal spaces based on a terminal_state_density given by user (Currently, user specifies terminal state points around which hypercubes in state space are terminal. If the user want a specific density and not hypercubes, the user has to design the terminal states they specify such that they would have a given density in space.). But only for state spaces with limits? For state spaces without limits, could do it for a limited subspace of the inifinite state space 1st and then repeat that pattern indefinitely along each dimension's axis. #test?
if callable(self.config["terminal_states"]):
self.is_terminal_state = self.config["terminal_states"]
else:
for i in range(len(self.config["terminal_states"])): # List of centres of terminal state regions.
assert len(self.config["terminal_states"][i]) == len(self.config["relevant_indices"]), "Specified terminal state centres should have dimensionality = number of relevant_indices. That was not the case for centre no.: " + str(i) + ""
lows = np.array([self.config["terminal_states"][i][j] - self.config["term_state_edge"]/2 for j in range(len(self.config["relevant_indices"]))])
highs = np.array([self.config["terminal_states"][i][j] + self.config["term_state_edge"]/2 for j in range(len(self.config["relevant_indices"]))])
# print("Term state lows, highs:", lows, highs)
self.term_spaces.append(BoxExtended(low=lows, high=highs, seed=self.seed_, dtype=self.dtype)) #seed #hack #TODO
self.logger.debug("self.term_spaces samples:" + str(self.term_spaces[0].sample()) + str(self.term_spaces[-1].sample()))
self.is_terminal_state = lambda s: np.any([self.term_spaces[i].contains(s[self.config["relevant_indices"]]) for i in range(len(self.term_spaces))]) ### TODO for cont. #test?
else: # no custom/user-defined terminal states
self.is_terminal_state = lambda s: False
def init_init_state_dist(self):
"""Initialises initial state distrbution, rho_0, to be uniform over the non-terminal states for discrete environments. For both discrete and continuous environments, the uniform sampling over non-terminal states is taken care of in reset() when setting the initial state for an episode.
"""
# relevant dimensions part
if self.config["state_space_type"] == "discrete":
if self.use_custom_mdp and "init_state_dist" in self.config: # custom/user-defined phi_0
# self.config["relevant_init_state_dist"] = #TODO make this also a lambda function?
pass
else:
# For relevant sub-space
non_term_state_space_size = self.action_space_size[0] - self.num_terminal_states #hardcoded
self.config["relevant_init_state_dist"] = ([1 / (non_term_state_space_size * self.diameter) for i in range(non_term_state_space_size)] + [0 for i in range(self.num_terminal_states)]) * self.diameter #TODO Currently only uniform distribution over non-terminal states; Use Dirichlet distribution to select prob. distribution to use?
#TODO make init_state_dist the default sample() for state space?
self.config["relevant_init_state_dist"] = np.array(self.config["relevant_init_state_dist"])
self.logger.warning("self.relevant_init_state_dist:" + str(self.config["relevant_init_state_dist"]))
#irrelevant sub-space
if self.irrelevant_features:
non_term_state_space_size = self.state_space_size[1] #hardcoded
self.config["irrelevant_init_state_dist"] = ([1 / (non_term_state_space_size) for i in range(non_term_state_space_size)]) # diameter not needed here as we directly take the state_space_size in the prev. line
self.config["irrelevant_init_state_dist"] = np.array(self.config["irrelevant_init_state_dist"])
self.logger.warning("self.irrelevant_init_state_dist:" + str(self.config["irrelevant_init_state_dist"]))
else: # if continuous space
pass # this is handled in reset where we resample if we sample a term. state
def init_transition_function(self):
"""Initialises transition function, P by selecting random next states for every (state, action) tuple for discrete environments. For continuous environments, we have 1 option for the transition function which varies depending on dynamics order and inertia and time_unit for a point object.
"""
if self.config["state_space_type"] == "discrete":
if self.use_custom_mdp: # custom/user-defined P
#
pass
else:
# relevant dimensions part
self.config["transition_function"] = np.zeros(shape=(self.state_space_size[0], self.action_space_size[0]), dtype=object) #hardcoded
self.config["transition_function"][:] = -1 #IMP # To avoid having a valid value from the state space before we actually assign a usable value below!
if self.maximally_connected:
if self.diameter == 1: #hack # TODO Remove this if block; this case is currently separately handled just so that tests do not fail. Using prob=prob in the sample call causes the sampling to change even if the probabilities remain the same. All solutions I can think of are hacky except changing the expected values in all the test cases which would take quite some time.
for s in range(self.state_space_size[0]):
self.config["transition_function"][s] = self.observation_spaces[0].sample(size=self.action_space_size[0], replace=False) #random #TODO Preferably use the seed of the Env for this? #hardcoded
else: # if diam > 1
for s in range(self.state_space_size[0]):
i_s = s // self.action_space_size[0] # select the current independent set number
prob = np.zeros(shape=(self.state_space_size[0],))
prob_next_states = np.ones(shape=(self.action_space_size[0],)) / self.action_space_size[0]
ind_1 = ((i_s + 1) * self.action_space_size[0]) % self.state_space_size[0]
ind_2 = ((i_s + 2) * self.action_space_size[0]) % self.state_space_size[0]
# print(ind_1, ind_2)
if ind_2 <= ind_1: # edge case
ind_2 += self.state_space_size[0]
prob[ind_1 : ind_2] = prob_next_states
self.config["transition_function"][s] = self.observation_spaces[0].sample(prob=prob, size=self.action_space_size[0], replace=False) #random #TODO Preferably use the seed of the Env for this? #hardcoded
# hacky way to do the above
# self.config["transition_function"][s] = self.observation_spaces[0].sample(max=self.action_space_size[0], size=self.action_space_size[0], replace=False) #random #TODO Preferably use the seed of the Env for this? #hardcoded
# Set the transitions from current state to be to the next independent set's states
# self.config["transition_function"][s] += ((i_s + 1) * self.action_space_size[0]) % self.state_space_size[0]
else: # if not maximally_connected
for s in range(self.state_space_size[0]):
i_s = s // self.action_space_size[0] # select the current independent set number
# Set the probabilities of the next state for the current independent set
prob = np.zeros(shape=(self.state_space_size[0],))
prob_next_states = np.ones(shape=(self.action_space_size[0],)) / self.action_space_size[0]
ind_1 = ((i_s + 1) * self.action_space_size[0]) % self.state_space_size[0]
ind_2 = ((i_s + 2) * self.action_space_size[0]) % self.state_space_size[0]
# print(ind_1, ind_2)
if ind_2 <= ind_1: # edge case
ind_2 += self.state_space_size[0]
prob[ind_1 : ind_2] = prob_next_states
for a in range(self.action_space_size[0]):
# prob[i_s * self.action_space_size[0] : (i_s + 1) * self.action_space_size[0]] = prob_next_states
self.config["transition_function"][s, a] = self.observation_spaces[0].sample(prob=prob) #random #TODO Preferably use the seed of the Env for this?
# Set the next state for terminal states to be themselves, for any action taken.
for i_s in range(self.diameter):
for s in range(self.action_space_size[0] - self.num_terminal_states, self.action_space_size[0]):
for a in range(self.action_space_size[0]):
assert self.is_terminal_state(i_s * self.action_space_size[0] + s) == True
self.config["transition_function"][i_s * self.action_space_size[0] + s, a] = i_s * self.action_space_size[0] + s # Setting P(s, a) = s for terminal states, for P() to be meaningful even if someone doesn't check for 'done' being = True
#irrelevant dimensions part
if self.irrelevant_features: #test
self.config["transition_function_irrelevant"] = np.zeros(shape=(self.state_space_size[1], self.action_space_size[1]), dtype=object)
self.config["transition_function_irrelevant"][:] = -1 #IMP # To avoid having a valid value from the state space before we actually assign a usable value below!
if self.maximally_connected:
for s in range(self.state_space_size[1]):
i_s = s // self.action_space_size[1] # select the current independent set number
# Set the probabilities of the next state for the current independent set
prob = np.zeros(shape=(self.state_space_size[1],))
prob_next_states = np.ones(shape=(self.action_space_size[1],)) / self.action_space_size[1]
ind_1 = ((i_s + 1) * self.action_space_size[1]) % self.state_space_size[1]
ind_2 = ((i_s + 2) * self.action_space_size[1]) % self.state_space_size[1]
print(ind_1, ind_2)
if ind_2 <= ind_1: # edge case
ind_2 += self.state_space_size[1]
prob[ind_1 : ind_2] = prob_next_states
self.config["transition_function_irrelevant"][s] = self.observation_spaces[1].sample(prob=prob, size=self.action_space_size[1], replace=False) #random #TODO Preferably use the seed of the Env for this? #hardcoded
# self.config["transition_function_irrelevant"][s] = self.observation_spaces[1].sample(max=self.action_space_size[1], size=self.action_space_size[1], replace=False) #random #TODO Preferably use the seed of the Env for this?
# self.config["transition_function_irrelevant"][s] += ((i_s + 1) * self.action_space_size[1]) % self.state_space_size[1]
else:
for s in range(self.state_space_size[1]):
i_s = s // self.action_space_size[1] # select the current independent set number
# Set the probabilities of the next state for the current independent set
prob = np.zeros(shape=(self.state_space_size[1],))
prob_next_states = np.ones(shape=(self.action_space_size[1],)) / self.action_space_size[1]
ind_1 = ((i_s + 1) * self.action_space_size[1]) % self.state_space_size[1]
ind_2 = ((i_s + 2) * self.action_space_size[1]) % self.state_space_size[1]
# print(ind_1, ind_2)
if ind_2 <= ind_1: # edge case
ind_2 += self.state_space_size[1]
prob[ind_1 : ind_2] = prob_next_states
for a in range(self.action_space_size[1]):
# prob[i_s * self.action_space_size[1] : (i_s + 1) * self.action_space_size[1]] = prob_next_states
self.config["transition_function_irrelevant"][s, a] = self.observation_spaces[1].sample(prob=prob) #random #TODO Preferably use the seed of the Env for this?
self.logger.warning(str(self.config["transition_function_irrelevant"]) + "init_transition_function _irrelevant" + str(type(self.config["transition_function_irrelevant"][0, 0])))
if not callable(self.config["transition_function"]):
self.transition_matrix = self.config["transition_function"]
self.config["transition_function"] = lambda s, a: self.transition_matrix[s, a]
print("transition_matrix inited to:\n" + str(self.transition_matrix) + "\nPython type of state: " + str(type(self.config["transition_function"](0, 0)))) # The Python type of the state can lead to hard to catch bugs
else: # if continuous space
# self.logger.debug("# TODO for cont. spaces") # transition function is a fixed parameterisation for cont. envs. right now.
pass
self.P = lambda s, a: self.transition_function(s, a)
def init_reward_function(self):
"""Initialises reward function, R by selecting random sequences to be rewardable for discrete environments. For continuous environments, we have fixed available options for the reward function.
"""
# print("Mersenne2, dummy_eval:", self.np_random.get_state()[2], "dummy_eval" in self.config)
#TODO Maybe refactor this code and put useful reusable permutation generators, etc. in one library
if self.config["state_space_type"] == "discrete":
if self.use_custom_mdp: # custom/user-defined R
if not callable(self.config["reward_function"]):
self.reward_matrix = self.config["reward_function"]
self.config["reward_function"] = lambda s, a: self.reward_matrix[s[-2], a] #hardcoded to be 2nd last state in state sequence passed to reward function, so that reward is R(s, a) when transition is s, a, r, s'
print("reward_matrix inited to:" + str(self.reward_matrix))
else:
non_term_state_space_size = self.action_space_size[0] - self.num_terminal_states
def get_sequences(maximum, length, fraction, repeats=False, diameter=1):
'''
Returns random sequences of integers
maximum: int
Max value of the integers in the sequence
length: int
Length of sequence
fraction: float
Fraction of total possible sequences to be returned
repeats: boolean
Allows repeats in returned sequences
diameter: int
Relates to the diameter of the MDP
'''
sequences = []
if repeats:
num_possible_sequences = (maximum) ** length
num_sel_sequences = int(fraction * num_possible_sequences)
if num_sel_sequences == 0:
num_sel_sequences = 1
warnings.warn('0 rewardable sequences per independent set for given reward_density, sequence_length, diameter and terminal_state_density. Setting it to 1.')
sel_sequence_nums = self.np_random.choice(num_possible_sequences, size=num_sel_sequences, replace=False) #random # This assumes that all sequences have an equal likelihood of being selected for being a reward sequence; This line also makes it not possible to have this function be portable as part of a library because it use the np_random member variable of this class
for i_s in range(diameter): # Allow sequences to begin in any of the independent sets and therefore this loop is over the no. of independent sets(= diameter)
for i in range(num_rewardable_sequences):
curr_sequence_num = sel_sequence_nums[i]
specific_sequence = []
while len(specific_sequence) != length:
specific_sequence.append(curr_sequence_num % (non_term_state_space_size) + ((len(specific_sequence) + i_s) % diameter) * self.action_space_size[0]) #TODO this uses a member variable of the class. Add another function param to receive this value? Name it independent set size?
curr_sequence_num = curr_sequence_num // (non_term_state_space_size)
#bottleneck When we sample sequences here, it could get very slow if reward_density is high; alternative would be to assign numbers to sequences and then sample these numbers without replacement and take those sequences
# specific_sequence = self.relevant_observation_space.sample(size=self.sequence_length, replace=True) # Be careful that sequence_length is less than state space size
sequences.append(specific_sequence)
self.logger.info("Total no. of rewarded sequences:" + str(len(sequences)) + str("Out of", num_possible_sequences) + "per independent set")
else: # if no repeats
assert length <= diameter * maximum, "When there are no repeats in sequences, the sequence length should be <= diameter * maximum."
permutations = []
for i in range(length):
permutations.append(maximum - i // diameter)
# permutations = list(range(maximum + 1 - length, maximum + 1))
self.logger.info("No. of choices for each element in a possible sequence (Total no. of permutations will be a product of this), no. of possible perms per independent set: " + str(permutations) + ", " + str(np.prod(permutations)))
for i_s in range(diameter): # Allow sequences to begin in any of the independent sets and therefore this loop is over the no. of independent sets(= diameter). Could maybe sample independent set no. as "part" of sel_sequence_nums below and avoid this loop?
num_possible_permutations = np.prod(permutations) # Number of possible permutations/sequences for, say, a diameter of 3 and 24 total states and terminal_state_density = 0.25, i.e., 6 non-terminal states (out of 8 states) per independent set, for sequence length of 5 is np.prod([6, 6, 6, 5, 5]) * 3; the * diameter at the end is needed because the sequence can begin in any of the independent sets; However, for simplicity, we omit * diameter here and just perform the same procedure per independent set. This can lead to slightly fewer rewardable sequences than should be the case for a given reward_density - this is due int() in the next step
num_sel_sequences = int(fraction * num_possible_permutations)
if num_sel_sequences == 0: ##TODO Remove this test here and above?
num_sel_sequences = 1
warnings.warn('0 rewardable sequences per independent set for given reward_density, sequence_length, diameter and terminal_state_density. Setting it to 1.')
# print("Mersenne3:", self.np_random.get_state()[2])
sel_sequence_nums = self.np_random.choice(num_possible_permutations, size=num_sel_sequences, replace=False) #random # This assumes that all sequences have an equal likelihood of being selected for being a reward sequence; # TODO this code could be replaced with self.np_random.permutation(non_term_state_space_size)[self.sequence_length]? Replacement becomes a problem then! We have to keep sampling until we have all unique rewardable sequences.
# print("Mersenne4:", self.np_random.get_state()[2])
total_clashes = 0
for i in range(num_sel_sequences):
curr_permutation = sel_sequence_nums[i]
seq_ = []
curr_rem_digits = []
for j in range(diameter):
curr_rem_digits.append(list(range(maximum))) # has to contain every number up to n so that any one of them can be picked as part of the sequence below
for enum, j in enumerate(permutations): # Goes from largest to smallest number among the factors of nPk
rem_ = curr_permutation % j
# rem_ = (enum // maximum) * maximum + rem_
seq_.append(curr_rem_digits[(enum + i_s) % diameter][rem_] + ((enum + i_s) % diameter) * self.action_space_size[0]) # Use (enum + i_s) to allow other independent sets to have states beginning a rewardable sequence
del curr_rem_digits[(enum + i_s) % diameter][rem_]
# print("curr_rem_digits", curr_rem_digits)
curr_permutation = curr_permutation // j
if seq_ in sequences: #hack
total_clashes += 1 #TODO remove these extra checks and assert below
sequences.append(seq_)
self.logger.debug("Number of generated sequences that did not clash with an existing one when it was generated:" + str(total_clashes))
assert total_clashes == 0, 'None of the generated sequences should have clashed with an existing rewardable sequence when it was generated. No. of times a clash was detected:' + str(total_clashes)
self.logger.info("Total no. of rewarded sequences:" + str(len(sequences)) + "Out of" + str(num_possible_permutations) + "per independent set")
return sequences
def insert_sequence(sequence):
'''
Inserts rewardable sequences into the rewardable_sequences dict member variable
'''
sequence = tuple(sequence) # tuples are immutable and can be used as keys for a dict
if callable(self.reward_dist):
self.rewardable_sequences[sequence] = self.reward_dist(self.np_random, self.rewardable_sequences)
else:
self.rewardable_sequences[sequence] = 1.0 # this is the default reward value, reward scaling will be handled later
self.logger.warning("specific_sequence that will be rewarded" + str(sequence)) #TODO impose a different distribution for these: independently sample state for each step of specific sequence; or conditionally dependent samples if we want something like DMPs/manifolds
if self.make_denser:
for ss_len in range(1, len(sequence)):
sub_sequence = tuple(sequence[:ss_len])
if sub_sequence not in self.rewardable_sequences:
self.rewardable_sequences[sub_sequence] = 0.0
self.rewardable_sequences[sub_sequence] += self.rewardable_sequences[sequence] * ss_len / len(sequence) # this could cause problems if we support variable sequence lengths and there are clashes in selected rewardable sequences
self.rewardable_sequences = {}
if self.repeats_in_sequences:
rewardable_sequences = get_sequences(maximum=non_term_state_space_size, length=self.sequence_length, fraction=self.reward_density, repeats=True, diameter=self.diameter)
else: # if no repeats_in_sequences
rewardable_sequences = get_sequences(maximum=non_term_state_space_size, length=self.sequence_length, fraction=self.reward_density, repeats=False, diameter=self.diameter)
# Common to both cases: repeats_in_sequences or not
if type(self.reward_dist) == list: # Specified as interval
reward_dist_ = self.reward_dist
num_rews = self.diameter * len(rewardable_sequences)
print("num_rewardable_sequences set to:", num_rews)
if num_rews == 1:
rews = [1.0]
else:
rews = np.linspace(reward_dist_[0], reward_dist_[1], num=num_rews)
assert rews[-1] == 1.0
self.np_random.shuffle(rews)
def get_rews(rng, r_dict):
return rews[len(r_dict)]
self.reward_dist = get_rews
if len(rewardable_sequences) > 1000:
warnings.warn('Too many rewardable sequences and/or too long rewardable sequence length. Environment might be too slow. Please consider setting the reward_density to be lower or reducing the sequence length. No. of rewardable sequences:' + str(len(rewardable_sequences))) #TODO Maybe even exit the program if too much memory is (expected to be) taken.; Took about 80s for 40k iterations of the for loop below on my laptop
for specific_sequence in rewardable_sequences:
insert_sequence(specific_sequence)
# else: # "repeats" in sequences are allowed until diameter - 1 steps have been taken: We sample the sequences as the state number inside each independent set, which are numbered from 0 to action_space_size - 1
# pass
print("rewardable_sequences: " + str(self.rewardable_sequences)) #debug print
else: # if continuous space
# self.logger.debug("# TODO for cont. spaces?: init_reward_function") # reward functions are fixed for cont. right now with a few available choices.
pass
self.R = lambda s, a: self.reward_function(s, a)
def transition_function(self, state, action):
"""The transition function, P.
Performs a transition according to the initialised P for discrete environments (with dynamics independent for relevant vs irrelevant dimension sub-spaces). For continuous environments, we have a fixed available option for the dynamics (which is the same for relevant or irrelevant dimensions):
The order of the system decides the dynamics. For an nth order system, the nth order derivative of the state is set to the action value / inertia for time_unit seconds. And then the dynamics are integrated over the time_unit to obtain the next state.
Parameters
----------
state : list
The state that the environment will use to perform a transition.
action : list
The action that the environment will use to perform a transition.
Returns
-------
int or np.array
The state at the end of the current transition
"""
if self.config["state_space_type"] == "discrete":
next_state = self.config["transition_function"](state, action)
if self.transition_noise:
probs = np.ones(shape=(self.state_space_size[0],)) * self.transition_noise / (self.state_space_size[0] - 1)
probs[next_state] = 1 - self.transition_noise
# TODO Samples according to new probs to get noisy discrete transition
new_next_state = self.observation_spaces[0].sample(prob=probs) #random
# print("noisy old next_state, new_next_state", next_state, new_next_state)
if next_state != new_next_state:
self.logger.info("NOISE inserted! old next_state, new_next_state" + str(next_state) + str(new_next_state))
self.total_noisy_transitions_episode += 1
# print("new probs:", probs, self.relevant_observation_space.sample(prob=probs))
next_state = new_next_state
# assert np.sum(probs) == 1, str(np.sum(probs)) + " is not equal to " + str(1)
else: # if continuous space
##TODO implement imagined transitions also for cont. spaces
if self.use_custom_mdp: