-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathreward_manager.py
916 lines (789 loc) · 28.4 KB
/
reward_manager.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
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import annotations
import enum
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Callable, List, Tuple
if TYPE_CHECKING:
from minihack import MiniHack
from nle.nethack import Command, CompassDirection
Y_cmd = CompassDirection.NW
class EventType(enum.IntEnum):
MESSAGE = 0
LOC_ACTION = 1
COORD = 2
LOC = 3
COMESTIBLES = [
"orange",
"meatball",
"meat ring",
"meat stick",
"kelp frond",
"eucalyptus leaf",
"clove of garlic",
"sprig of wolfsbane",
"carrot",
"egg",
"banana",
"melon",
"candy bar",
"lump of royal jelly",
]
class Event(ABC):
"""An event which can occur in a MiniHack episode.
This is the base class of all other events.
"""
def __init__(
self,
reward: float,
repeatable: bool,
terminal_required: bool,
terminal_sufficient: bool,
):
"""Initialise the Event.
Args:
reward (float):
The reward for the event occuring
repeatable (bool):
Whether the event can occur repeated (i.e. if the reward can be
collected repeatedly
terminal_required (bool):
Whether this event is required for the episode to terminate.
terminal_sufficient (bool):
Whether this event causes the episode to terminate on its own.
"""
self.reward = reward
self.repeatable = repeatable
self.terminal_required = terminal_required
self.terminal_sufficient = terminal_sufficient
self.achieved = False
@abstractmethod
def check(self, env, previous_observation, action, observation) -> float:
"""Check whether the environment is in the state such that this event
has occured.
Args:
env (MiniHack):
The MiniHack environment in question.
previous_observation (tuple):
The previous state observation.
action (int):
The action taken.
observation (tuple):
The current observation.
Returns:
float: The reward.
"""
pass
def reset(self):
"""Reset the event, if there is any state necessary."""
self.achieved = False
def _set_achieved(self) -> float:
if not self.repeatable:
self.achieved = True
return self.reward
def _standing_on_top(env, location):
return not env.screen_contains(location)
class LocActionEvent(Event):
"""An event which checks whether an action is performed at a specified
location.
"""
def __init__(
self,
*args,
loc: str,
action: Command,
):
"""Initialise the Event.
Args:
loc (str):
The name of the location to reach.
action (int):
The action to perform.
reward (float):
The reward for the event occuring
repeatable (bool):
Whether the event can occur repeated (i.e. if the reward can be
collected repeatedly
terminal_required (bool):
Whether this event is required for the episode to terminate.
terminal_sufficient (bool):
Whether this event causes the episode to terminate on its own.
"""
super().__init__(*args)
self.loc = loc
self.action = action
self.status = False
def check(self, env, previous_observation, action, observation) -> float:
del previous_observation, observation
if env._actions[action] == self.action and _standing_on_top(
env, self.loc
):
self.status = True
elif env._actions[action] == Y_cmd and self.status:
return self._set_achieved()
else:
self.status = False
return 0
def reset(self):
super().reset()
self.status = False
class LocEvent(Event):
"""An event which checks whether a specified location is reached."""
def __init__(self, *args, loc: str):
super().__init__(*args)
"""Initialise the Event.
Args:
loc (str):
The name of the location to reach.
reward (float):
The reward for the event occuring
repeatable (bool):
Whether the event can occur repeated (i.e. if the reward can be
collected repeatedly
terminal_required (bool):
Whether this event is required for the episode to terminate.
terminal_sufficient (bool):
Whether this event causes the episode to terminate on its own.
"""
self.loc = loc
def check(self, env, previous_observation, action, observation) -> float:
del previous_observation, action, observation
if _standing_on_top(env, self.loc):
return self._set_achieved()
return 0.0
class CoordEvent(Event):
"""An event which occurs when reaching certain coordinates."""
def __init__(self, *args, coordinates: Tuple[int, int]):
"""Initialise the Event.
Args:
coordinates (tuple):
The coordinates to reach for the event.
reward (float):
The reward for the event occuring
repeatable (bool):
Whether the event can occur repeated (i.e. if the reward can be
collected repeatedly
terminal_required (bool):
Whether this event is required for the episode to terminate.
terminal_sufficient (bool):
Whether this event causes the episode to terminate on its own.
"""
super().__init__(*args)
self.coordinates = coordinates
def check(self, env, previous_observation, action, observation) -> float:
coordinates = tuple(observation[env._blstats_index][:2])
if self.coordinates == coordinates:
return self._set_achieved()
return 0.0
class MessageEvent(Event):
"""An event which occurs when any of the `messages` appear."""
def __init__(self, *args, messages: List[str]):
"""Initialise the Event.
Args:
messages (list):
The messages to be seen to trigger the event.
reward (float):
The reward for the event occuring
repeatable (bool):
Whether the event can occur repeated (i.e. if the reward can be
collected repeatedly
terminal_required (bool):
Whether this event is required for the episode to terminate.
terminal_sufficient (bool):
Whether this event causes the episode to terminate on its own.
"""
super().__init__(*args)
self.messages = messages
def check(self, env, previous_observation, action, observation) -> float:
del previous_observation, action
curr_msg = (
observation[env._original_observation_keys.index("message")]
.tobytes()
.decode("utf-8")
)
for msg in self.messages:
if msg in curr_msg:
return self._set_achieved()
return 0.0
class AlwaysEvent(Event):
def __init__(self, *args):
super().__init__(*args)
def check(self, env, previous_observation, action, observation) -> float:
return self._set_achieved()
class AbstractRewardManager(ABC):
"""This is the abstract base class for the ``RewardManager`` that is used
for defining custom reward functions.
"""
def __init__(self):
self.terminal_sufficient = None
self.terminal_required = None
@abstractmethod
def collect_reward(self) -> float:
"""Return reward calculated and accumulated in check_episode_end_call,
and then reset it.
Returns:
flaot: The reward.
"""
raise NotImplementedError
@abstractmethod
def check_episode_end_call(
self, env, previous_observation, action, observation
) -> bool:
"""Check if the task has ended, and accumulate any reward from the
transition in ``self._reward``.
Args:
env (MiniHack):
The MiniHack environment in question.
previous_observation (tuple):
The previous state observation.
action (int):
The action taken.
observation (tuple):
The current observation.
Returns:
bool: Boolean whether the episode has ended.
"""
raise NotImplementedError
@abstractmethod
def reset(self) -> None:
"""Reset all events, to be called when a new episode occurs."""
raise NotImplementedError
class RewardManager(AbstractRewardManager):
"""This class is used for managing rewards, events and termination for
MiniHack tasks.
Some notes on the ordering or calls in the MiniHack/NetHack base class:
- ``step(action)`` is called on the environment
- Within ``step``, first a copy of the last observation is made, and then the
underlying NetHack game is stepped
- Then ``_is_episode_end(observation)`` is called to check whether this the
episode has ended (and this is overridden if we've gone over our
max_steps, or the underlying NetHack game says we're done (i.e. we died)
- Then ``_reward_fn(last_observation, observation)`` is called to calculate
the reward at this time-step
- if ``end_status`` tells us the game is done, we quit the game
- then ``step`` returns the observation, calculated reward, done, and some
statistics.
All this means that we need to check whether an observation is terminal in
``_is_episode_end`` before we're calculating the reward function.
The call of ``_is_episode_end`` in ``MiniHack`` will call
``check_episode_end_call`` in this class, which checks for termination and
accumulates any reward, which is returned and zeroed in ``collect_reward``.
"""
def __init__(self):
self.events: List[Event] = []
self.custom_reward_functions: List[
Callable[[MiniHack, Any, int, Any], float]
] = []
self._reward = 0.0
# Only used for GroupedRewardManager
self.terminal_sufficient = None
self.terminal_required = None
def add_custom_reward_fn(
self, reward_fn: Callable[[MiniHack, Any, int, Any], float]
) -> None:
"""Add a custom reward function which is called every after step to
calculate reward.
The function should be a callable which takes the environment, previous
observation, action and current observation and returns a float reward.
Args:
reward_fn (Callable[[MiniHack, Any, int, Any], float]):
A reward function which takes an environment, previous
observation, action, next observation and returns a reward.
"""
self.custom_reward_functions.append(reward_fn)
def add_event(self, event: Event):
"""Add an event to be managed by the reward manager.
Args:
event (Event):
The event to be added.
"""
self.events.append(event)
def _add_message_event(
self, msgs, reward, repeatable, terminal_required, terminal_sufficient
):
self.add_event(
MessageEvent(
reward,
repeatable,
terminal_required,
terminal_sufficient,
messages=msgs,
)
)
def _add_loc_action_event(
self,
loc,
action,
reward,
repeatable,
terminal_required,
terminal_sufficient,
):
try:
action = Command[action.upper()]
except KeyError:
raise KeyError(
"Action {} is not in the action space.".format(action.upper())
)
self.add_event(
LocActionEvent(
reward,
repeatable,
terminal_required,
terminal_sufficient,
loc=loc.lower(),
action=action,
)
)
def add_eat_event(
self,
name: str,
reward=1,
repeatable=False,
terminal_required=True,
terminal_sufficient=False,
):
"""Add an event which is triggered when `name` is eaten.
Args:
name (str):
The name of the object being eaten.
reward (float):
The reward for this event. Defaults to 1.
repeatable (bool):
Whether this event can be triggered multiple times. Defaults to
False.
terminal_required (bool):
Whether this event is required for termination. Defaults to
True.
terminal_sufficient (bool):
Whether this event is sufficient for termination. Defaults to
False.
"""
msgs = [
f"This {name} is delicious",
"Blecch! Rotten food!",
"last bite of your meal",
]
if name == "apple":
msgs.append("Delicious! Must be a Macintosh!")
msgs.append("Core dumped.")
if name == "pear":
msgs.append("Core dumped.")
self._add_message_event(
msgs, reward, repeatable, terminal_required, terminal_sufficient
)
def add_wield_event(
self,
name: str,
reward=1,
repeatable=False,
terminal_required=True,
terminal_sufficient=False,
):
"""Add event which is triggered when a specific weapon is wielded.
Args:
name (str):
The name of the weapon to be wielded.
reward (float):
The reward for this event. Defaults to 1.
repeatable (bool):
Whether this event can be triggered multiple times. Defaults to
False.
terminal_required (bool):
Whether this event is required for termination. Defaults to
True.
terminal_sufficient (bool):
Whether this event is sufficient for termination. Defaults to
False.
"""
msgs = [
f"{name} wields itself to your hand!",
f"{name} (weapon in hand)",
]
self._add_message_event(
msgs, reward, repeatable, terminal_required, terminal_sufficient
)
def add_wear_event(
self,
name: str,
reward=1,
repeatable=False,
terminal_required=True,
terminal_sufficient=False,
):
"""Add event which is triggered when a specific armor is worn.
Args:
name (str):
The name of the armor to be worn.
reward (float):
The reward for this event. Defaults to 1.
repeatable (bool):
Whether this event can be triggered multiple times. Defaults to
False.
terminal_required (bool):
Whether this event is required for termination. Defaults to
True.
terminal_sufficient (bool):
Whether this event is sufficient for termination. Defaults to
False.
"""
msgs = [f"You are now wearing a {name}"]
self._add_message_event(
msgs, reward, repeatable, terminal_required, terminal_sufficient
)
def add_amulet_event(
self,
reward=1,
repeatable=False,
terminal_required=True,
terminal_sufficient=False,
):
"""Add event which is triggered when an amulet is worn.
Args:
reward (float):
The reward for this event. Defaults to 1.
repeatable (bool):
Whether this event can be triggered multiple times. Defaults to
False.
terminal_required (bool):
Whether this event is required for termination. Defaults to
True.
terminal_sufficient (bool):
Whether this event is sufficient for termination. Defaults to
False.
"""
self._add_message_event(
["amulet (being worn)."],
reward,
repeatable,
terminal_required,
terminal_sufficient,
)
def add_kill_event(
self,
name: str,
reward=1,
repeatable=False,
terminal_required=True,
terminal_sufficient=False,
):
"""Add event which is triggered when a specified monster is killed.
Args:
name (str):
The name of the monster to be killed.
reward (float):
The reward for this event. Defaults to 1.
repeatable (bool):
Whether this event can be triggered multiple times. Defaults to
False.
terminal_required (bool):
Whether this event is required for termination. Defaults to
True.
terminal_sufficient (bool):
Whether this event is sufficient for termination. Defaults to
False.
"""
self._add_message_event(
[f"You kill the {name}"],
reward,
repeatable,
terminal_required,
terminal_sufficient,
)
def add_message_event(
self,
msgs: List[str],
reward=1,
repeatable=False,
terminal_required=True,
terminal_sufficient=False,
):
"""Add event which is triggered when any of the given messages are seen.
Args:
msgs (List[str]):
The name of the monster to be killed.
reward (float):
The reward for this event. Defaults to 1.
repeatable (bool):
Whether this event can be triggered multiple times. Defaults to
False.
terminal_required (bool):
Whether this event is required for termination. Defaults to
True.
terminal_sufficient (bool):
Whether this event is sufficient for termination. Defaults to
False.
"""
self._add_message_event(
msgs, reward, repeatable, terminal_required, terminal_sufficient
)
def add_positional_event(
self,
place_name: str,
action_name: str,
reward=1,
repeatable=False,
terminal_required=True,
terminal_sufficient=False,
):
"""Add event which is triggered on taking a given action at a given place.
Args:
place_name (str):
The name of the place to trigger the event.
action_name (int):
The name of the action to trigger the event.
reward (float):
The reward for this event. Defaults to 1.
repeatable (bool):
Whether this event can be triggered multiple times. Defaults to
False.
terminal_required (bool):
Whether this event is required for termination. Defaults to
True.
terminal_sufficient (bool):
Whether this event is sufficient for termination. Defaults to
False.
"""
self._add_loc_action_event(
place_name,
action_name,
reward,
repeatable,
terminal_required,
terminal_sufficient,
)
def add_coordinate_event(
self,
coordinates: Tuple[int, int],
reward=1,
repeatable=False,
terminal_required=True,
terminal_sufficient=False,
):
"""Add event which is triggered on when reaching the specified
coordinates.
Args:
coordinates (Tuple[int, int]):
The coordinates to be reached (tuple of ints).
reward (float):
The reward for this event. Defaults to 1.
repeatable (bool):
Whether this event can be triggered multiple times. Defaults to
False.
terminal_required (bool):
Whether this event is required for termination. Defaults to
True.
terminal_sufficient (bool):
Whether this event is sufficient for termination. Defaults to
False.
"""
self.add_event(
CoordEvent(
reward,
repeatable,
terminal_required,
terminal_sufficient,
coordinates=coordinates,
)
)
def add_location_event(
self,
location: str,
reward=1,
repeatable=False,
terminal_required=True,
terminal_sufficient=False,
):
"""Add event which is triggered on reaching a specified location.
Args:
name (str):
The name of the location to be reached.
reward (float):
The reward for this event. Defaults to 1.
repeatable (bool):
Whether this event can be triggered multiple times. Defaults to
False.
terminal_required (bool):
Whether this event is required for termination. Defaults to
True.
terminal_sufficient (bool):
Whether this event is sufficient for termination. Defaults to
False.
"""
self.add_event(
LocEvent(
reward,
repeatable,
terminal_required,
terminal_sufficient,
loc=location,
)
)
def _set_achieved(self, event: Event) -> float:
if not event.repeatable:
event.achieved = True
return event.reward
def _standing_on_top(self, env, name):
"""Returns whether the agents is standing on top of the given object.
The object name (e.g. altar, sink, fountain) must exist on the map.
Args:
env (MiniHack):
The environment object.
name (str):
The name of the object.
Returns:
bool: True if the object name is not in the screen descriptions
with agent info taking the space of the corresponding tile rather
than the object).
"""
return not env.screen_contains(name)
def check_episode_end_call(
self, env, previous_observation, action, observation
) -> bool:
reward = 0.0
for event in self.events:
if event.achieved:
continue
reward += event.check(
env, previous_observation, action, observation
)
for custom_reward_function in self.custom_reward_functions:
reward += custom_reward_function(
env, previous_observation, action, observation
)
self._reward += reward
return self._check_complete()
def _check_complete(self) -> bool:
"""Checks whether the episode is complete.
Requires any event which is sufficient to be achieved, OR all required
events to be achieved."""
result = True
for event in self.events:
# This event is enough, we're done
if event.achieved and event.terminal_sufficient:
return True
# We need this event and we haven't done it, we're not done
if not event.achieved and event.terminal_required:
result = False
# We've achieved all terminal_required events, we're done
return result
def collect_reward(self) -> float:
result = self._reward
self._reward = 0.0
return result
def reset(self):
self._reward = 0.0
for event in self.events:
event.reset()
class SequentialRewardManager(RewardManager):
"""A reward manager that ignores ``terminal_required`` and
``terminal_sufficient``, and just require every event is completed in the
order it is added to the reward manager.
"""
def __init__(self):
self.current_event_idx = 0
super().__init__()
def check_episode_end_call(
self, env, previous_observation, action, observation
):
event = self.events[self.current_event_idx]
reward = event.check(env, previous_observation, action, observation)
if event.achieved:
self.current_event_idx += 1
self._reward += reward
return self._check_complete()
def _check_complete(self) -> bool:
return self.current_event_idx == len(self.events)
class GroupedRewardManager(AbstractRewardManager):
"""Operates as a collection of reward managers.
The rewards from each reward manager are summed, and termination can be
specified by ``terminal_sufficient`` and ``terminal_required`` on each
reward manager.
Given this can be nested arbitrarily deeply (as each reward manager could
itself be a GroupedRewardManager), this enables complex specification of
groups of rewards.
"""
def __init__(self):
self.reward_managers: List[AbstractRewardManager] = []
def check_episode_end_call(
self, env, previous_observation, action, observation
) -> bool:
for reward_manager in self.reward_managers:
result = reward_manager.check_episode_end_call(
env, previous_observation, action, observation
)
# This reward manager has completed and it's sufficient so we're
# done
if reward_manager.terminal_sufficient and result:
return True
# This reward manager is required and hasn't completed, so we're
# not done
if reward_manager.terminal_required and not result:
return False
# If we've got here we've completed all required reward managers, so
# we're done
return True
def add_reward_manager(
self,
reward_manager: AbstractRewardManager,
terminal_required: bool,
terminal_sufficient: bool,
) -> None:
"""Add a new reward manager, with ``terminal_sufficient`` and
``terminal_required`` acting as for individual events.
Args:
reward_manager (RewardManager):
The reward manager to be added.
terminal_required (bool):
Whether this reward manager terminating is required for the
episode to terminate.
terminal_sufficient:
Whether this reward manager terminating is sufficient for the
episode to terminate.
"""
reward_manager.terminal_required = terminal_required
reward_manager.terminal_sufficient = terminal_sufficient
self.reward_managers.append(reward_manager)
def collect_reward(self):
reward = 0.0
for reward_manager in self.reward_managers:
reward += reward_manager.collect_reward()
return reward
def reset(self):
self._reward = 0.0
for reward_manager in self.reward_managers:
reward_manager.reset()
class IntersectionRewardManager(RewardManager):
"""
Requires every event to be completed (in any order) and will only give
reward when all events are completed.
Ignores terminal_required and terminal_sufficient.
"""
def __init__(self):
super().__init__()
self._stored_reward = 0
self._reward = 0
def check_episode_end_call(
self, env, previous_observation, action, observation
) -> bool:
reward = 0.0
for event in self.events:
if event.achieved:
continue
reward += event.check(
env, previous_observation, action, observation
)
self._stored_reward += reward
completed = self._check_complete()
if completed:
self._reward = self._stored_reward
return completed
def _check_complete(self) -> bool:
result = True
for event in self.events:
# We require all events to be completed
if not event.achieved:
result = False
return result
def reset(self):
super().reset()
self._stored_reward = 0.0