-
Notifications
You must be signed in to change notification settings - Fork 7
/
rl_toy_env.py
2454 lines (2212 loc) · 138 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
import os
import warnings
import logging
import copy
from datetime import datetime
import numpy as np
import scipy
from scipy import stats
from scipy.spatial import distance
import gymnasium as gym
from mdp_playground.spaces import (
BoxExtended,
DiscreteExtended,
TupleExtended,
ImageMultiDiscrete,
ImageContinuous,
GridActionSpace,
)
class RLToyEnv(gym.Env):
metadata = {"render_modes": ["human", "rgb_array"], "render_fps": 4}
"""
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):
state_space_type : str
Specifies what the environment type is. Options are "continuous", "discrete" and "grid". The "grid" environment is, basically, a discretised version of the continuous environment.
delay : int >= 0
Delays each reward by this number of timesteps. Default value: 0.
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. Default value: 1.
See also reward_every_n_steps documentation. The default value for reward_every_n_steps = sequence_length means that rewards are handed out only if the rewardable sequence ends at a timestep that is a multiple of the sequence length. Set reward_every_n_steps = 1 to make the environment rewardable at any possible timestep that a rewardable sequence may end.
transition_noise : float in range [0, 1] or Python function(state, action, 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, it should have 3 arguments and return a noise value that is added to next state. The arguments are provided to it by the existing code in this class and are the current state, the current action and the Random Number Generator (RNG) of the environment which is an np.random.RandomState object. This RNG is used to ensure reproducibility. Default value: 0.
reward_noise : float or Python function(state, action, rng)
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, it should have 3 arguments and return a noise value that is to the reward. The arguments are provided to it by the existing code in this class and are the current state, the current action and the Random Number Generator (RNG) of the environment which is an np.random.RandomState object. This RNG is used to ensure reproducibility. Default value: 0.
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. Default value: 0.25.
reward_scale : float
Multiplies the rewards by this value at every time step. Default value: 1.
reward_shift : float
This value is added to the reward at every time step. Default value: 0.
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). Default value: 1 for discrete environments. For continuous environments, this dimension is set automatically based on the state_space_max value.
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. For grid environments, please see terminal_states only. Default value: 0.25.
term_state_reward : float
Adds this to the reward if a terminal state was reached at the current time step. Default value: 0.
image_representations : boolean
Boolean to associate an image as the external observation with every discrete categorical state.
For discrete envs, 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.
For continuous and grid envs, this is handled by an mdp_playground.spaces.ImageContinuous object. More details can be found in the documentation for the ImageContinuous class.
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. No noise is currently added to irrelevant_features parts in continuous or grid spaces. Default value: False.
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.
For grid environments, nothing additional needs to be done as relevant grid shape is also used as the irrelevant grid shape.
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.
If use_custom_mdp = false and the environment is grid, this is a string that chooses one of the following predefined reward functions: move_to_a_point. Support for sequences is planned.
Also see make_denser documentation.
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.
Specific to image_representations for discrete envs:
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. Default value: Infinity.
action_space_max : float
Similar description as for state_space_max. Default value: Infinity.
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. Default value: 1.
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,). Default value: 1.
time_unit : float
time duration over which the action is applied to the system. Default value: 1.
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. Default value: array of 0s.
action_loss_weight : float
A coefficient to multiply the norm of the action and subtract it from the reward to penalise the action magnitude. Default value: 0.
Specific to grid environments:
grid_shape : tuple
Shape of the grid environment. If irrelevant_features is True, this is replicated to add a grid which is irrelevant to the reward.
target_point : numpy.ndarray
The target point in case move_to_a_point is the reward_function. If make_denser is false, reward is only handed out when the target point is reached.
terminal_states : Python function(state) or 1-D numpy.ndarray
Same description as for terminal_states under discrete envs, except that the state is a grid state, e.g., a list of [x, y] coordinates for a 2-D grid.
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.
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 all, continuous, discrete and grid environments:
make_denser : boolean
If true, makes the reward denser in environments:
For discrete environments, hands out a partial reward for completing partial rewarding 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.
For grid envs, the base reward handed out is equal to the Manhattan distance moved towards the target point in the current timestep.
reward_every_n_steps : int
Hand out rewards only at multiples of reward_every_n_steps steps. For discrete envs, this allows one to set it to sequence_length, thereby making the probability that an agent is collecting rewards for overlapping rewarding sequences 0. For discrete, continuous and grid envs, it provides another possibility to have sparser reward envs. This also makes it simpler to evaluate HRL algorithms and whether they can "discretise" time correctly. Noise (in the transition or reward function) is added at every step, regardless of this setting. Default value: sequence_length for discrete envs and 1 for continuous and grid envs.
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.
feature_space : Gym.Space
In case of continuous and grid environments, this is the underlying state space. ##TODO Unify this across all types of environments.
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):
"""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")
if config == {}:
config = {
"state_space_size": 8,
"action_space_size": 8,
"state_space_type": "discrete",
"action_space_type": "discrete",
"terminal_state_density": 0.25,
"maximally_connected": True,
}
# 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.NOTSET # #logging.CRITICAL
else:
self.log_level = config["log_level"]
# print('self.log_level', 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.setLevel(self.log_level)
# print("Logging stuff:", self.logger, self.logger.handlers, __name__)
# Example output of above: <Logger mdp_playground.envs.rl_toy_env (INFO)> [] mdp_playground.envs.rl_toy_env
# 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:
# 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.
if not self.logger.handlers:
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)
print("Logger logging to:", self.log_filename)
# 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 isinstance(config["seed"], dict):
self.seed_dict = config["seed"]
need_to_gen_seeds = False
elif isinstance(
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, actual config: ", type(config["seed"]), config)
# #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.integers(
sys.maxsize
).item() # #random
self.seed_dict["relevant_action_space"] = self._np_random.integers(
sys.maxsize
).item() # #random
self.seed_dict["irrelevant_state_space"] = self._np_random.integers(
sys.maxsize
).item() # #random
self.seed_dict["irrelevant_action_space"] = self._np_random.integers(
sys.maxsize
).item() # #random
# #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["state_space"] = self._np_random.integers(sys.maxsize).item()
# #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["action_space"] = self._np_random.integers(sys.maxsize).item()
self.seed_dict["image_representations"] = self._np_random.integers(
sys.maxsize
).item() # #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
config["state_space_type"] = config["state_space_type"].lower()
# #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
# Common defaults for all types of environments:
if "terminal_state_density" not in config:
self.terminal_state_density = 0.25
else:
self.terminal_state_density = config["terminal_state_density"]
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 s, a, rng: rng.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 s, a, rng: rng.normal(0, p_noise_std, s.shape)
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"]
# Moved these out of the image_representations block when adding render()
# because they are needed for the render() method even if image_representations
# is False.
if "image_transforms" in config:
assert config["state_space_type"] == "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"]
# Defaults for the individual environment types:
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"]
elif config["state_space_type"] == "continuous":
# if not self.use_custom_mdp:
self.state_space_dim = config["state_space_dim"]
# ##TODO Do something to dismbiguate the Python function reward_function from the
# choice of reward_function below.
if "reward_function" not in config:
config["reward_function"] = "move_to_a_point"
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"]
elif config["state_space_type"] == "grid":
assert "grid_shape" in config
self.grid_shape = config["grid_shape"]
else:
raise ValueError("Unknown state_space_type")
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:
# The default is different for the different state_space_types, because
# making it sequence_length for discrete envs makes it easier to find what the optimal returns
# are and it avoids the agent being on overlapping rewarding sequences. For the other
# types, it's set to 1 by default because that is the more natural and common
# setting.
if config["state_space_type"] == "discrete":
self.reward_every_n_steps = self.sequence_length
else: # continuous and grid envs
self.reward_every_n_steps = 1
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"]
# ##TODO Move these to the individual env types' defaults section above?
if config["state_space_type"] == "discrete":
# I think Gymnasium wants int64, but Dreamer-V3 (~June 2024) code may prefer int32
self.dtype_s = np.int64 if "dtype_s" not in config else config["dtype_s"]
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."
elif config["state_space_type"] == "continuous":
self.dtype_s = np.float32 if "dtype_s" not in config else config["dtype_s"]
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"]))
elif config["state_space_type"] == "grid":
self.dtype_s = np.int64 if "dtype_s" not in config else config["dtype_s"]
# Repeat the grid for the irrelevant part as well
if self.irrelevant_features:
self.grid_shape = self.grid_shape * 2
# Set the dtype for the observation space:
if self.image_representations:
self.dtype_o = np.uint8 if "dtype_o" not in config else config["dtype_o"]
else:
self.dtype_o = self.dtype_s if "dtype_o" not in config else config["dtype_o"]
if ("init_state_dist" in config) and ("relevant_init_state_dist" not in config):
config["relevant_init_state_dist"] = config["init_state_dist"]
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":
assert self.sequence_length == 1
if "target_point" in config:
self.target_point = np.array(
config["target_point"], dtype=self.dtype_s
)
assert self.target_point.shape == (
len(config["relevant_indices"]),
), "target_point should have dimensionality = relevant_state_space dimensionality"
else:
# Sets default
self.target_point = np.zeros(shape=(config["state_space_dim"],))
elif config["state_space_type"] == "grid":
if config["reward_function"] == "move_to_a_point":
self.target_point = config["target_point"]
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"],
# dtype=self.dtype_o, # Gymnasium seems to hardcode as np.int64
)
] # #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: # for discrete envs
# 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: # not image_representations for discrete env
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]
elif config["state_space_type"] == "continuous":
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_s,
) # #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_s,
) # #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
elif config["state_space_type"] == "grid":
underlying_space_maxes = list_to_float_np_array(self.grid_shape)
# The min for grid envs is 0, 0, 0, ...
self.feature_space = BoxExtended(
0 * underlying_space_maxes,
underlying_space_maxes,
seed=self.seed_dict["state_space"],
dtype=self.dtype_s,
) # #seed
lows = np.array([-1] * len(self.grid_shape))
highs = np.array([1] * len(self.grid_shape))
self.action_space = GridActionSpace(
lows,
highs,
seed=self.seed_dict["action_space"],
) # #seed
if self.image_representations:
target_pt = list_to_float_np_array(self.target_point)
self.observation_space = ImageContinuous(
self.feature_space,
width=self.image_width,
height=self.image_height,
term_spaces=self.term_spaces,
target_point=target_pt,
circle_radius=5,
grid_shape=self.grid_shape,
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!!
# #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_init_state_dist()
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(seed=self.seed_dict["env"])
) # #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.debug(
"self.augmented_state, len: "
+ str(self.augmented_state)
+ ", "
+ str(len(self.augmented_state))
)
# Needed for rendering with pygame for use with Gymnasium.Env's render() method:
render_mode = config.get("render_mode", None)
assert render_mode is None or render_mode in self.metadata["render_modes"]
self.render_mode = render_mode
self.window = None
self.clock = None
self.logger.debug(
"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 "terminal_states" 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.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"]
elif self.config["state_space_type"] == "continuous":
# 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
# infinite 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_s
)
) # #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
elif self.config["state_space_type"] == "grid":
self.term_spaces = []
if "terminal_states" in self.config:
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
# terminal states on the grid
term_state = list_to_float_np_array(
self.config["terminal_states"][i]
)
lows = term_state
highs = term_state # #hardcoded
self.term_spaces.append(
BoxExtended(
low=lows, high=highs, seed=self.seed_, dtype=self.dtype_s
)
) # #seed #hack #TODO
def is_term(s):
cont_state = list_to_float_np_array(s)
return np.any(
[
self.term_spaces[i].contains(cont_state)
for i in range(len(self.term_spaces))
]
)
self.is_terminal_state = is_term
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