Skip to content

gymnasium

This module is a wrapper around the Gym / Gymnasium interfaces and drives all the interactions between the agent and the system, including the main event loop.

count = 0 module-attribute

dump_env_file = None module-attribute

BottomlineStats

Bases: BaseModel

A Pydantic model representing the Nethack bottom line statistics.

Source code in roc/gymnasium.py
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
class BottomlineStats(BaseModel):
    """A Pydantic model representing the Nethack bottom line statistics."""

    x: int
    y: int
    str25: int
    str125: int
    dex: int
    con: int
    intel: int = Field(alias="int")
    wis: int
    cha: int
    score: int
    hp: int
    hpmax: int
    depth: int
    gold: int
    ene: int
    enemax: int
    ac: int
    hd: int
    xp: int
    exp: int
    time: int
    hunger: int
    cap: int
    dnum: int
    dlevel: int
    condition: int
    align: int
    stone: bool
    slime: bool
    stringl: bool
    foodpois: bool
    termill: bool
    blind: bool
    deaf: bool
    stun: bool
    conf: bool
    hallu: bool
    lev: bool
    fly: bool
    ride: bool

ac instance-attribute

align instance-attribute

blind instance-attribute

cap instance-attribute

cha instance-attribute

con instance-attribute

condition instance-attribute

conf instance-attribute

deaf instance-attribute

depth instance-attribute

dex instance-attribute

dlevel instance-attribute

dnum instance-attribute

ene instance-attribute

enemax instance-attribute

exp instance-attribute

fly instance-attribute

foodpois instance-attribute

gold instance-attribute

hallu instance-attribute

hd instance-attribute

hp instance-attribute

hpmax instance-attribute

hunger instance-attribute

intel = Field(alias='int') class-attribute instance-attribute

lev instance-attribute

ride instance-attribute

score instance-attribute

slime instance-attribute

stone instance-attribute

str125 instance-attribute

str25 instance-attribute

stringl instance-attribute

stun instance-attribute

termill instance-attribute

time instance-attribute

wis instance-attribute

x instance-attribute

xp instance-attribute

y instance-attribute

Gym

Bases: Component, ABC

A wrapper around an OpenAI Gym / Farama Gymnasium that drives the event loop and interfaces to the ROC agent.

Source code in roc/gymnasium.py
 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
class Gym(Component, ABC):
    """A wrapper around an OpenAI Gym / Farama Gymnasium that drives the event
    loop and interfaces to the ROC agent.
    """

    def __init__(self, gym_id: str, *, gym_opts: dict[str, Any] | None = None) -> None:
        super().__init__()
        gym_opts = gym_opts or {}
        logger.info(f"Gym options: {gym_opts}")
        self.env = gym.make(gym_id, **gym_opts)

        # setup communications
        self.env_bus_conn = Perception.bus.connect(self)
        self.action_bus_conn = Action.bus.connect(self)
        self.intrinsic_bus_conn = Intrinsic.bus.connect(self)

        # config
        self.config(self.env)

        # TODO: config environment
        # setup which features detectors to use on each bus

    @abstractmethod
    def send_obs(self, obs: Any) -> None: ...

    @abstractmethod
    def config(self, env: gym.core.Env[Any, Any]) -> None: ...

    @abstractmethod
    def get_action(self) -> Any: ...

    @logger.catch
    def start(self) -> None:
        obs, reset_info = self.env.reset()
        settings = Config.get()

        done = False
        truncated = False
        _dump_env_start()

        logger.info("Starting NLE loop...")
        loop_num = 0
        game_num = 0

        # main environment loop
        while game_num < settings.num_games:
            logger.trace(f"Sending observation: {obs}")
            breakpoints.check()

            # save the current screen
            screen = nle.nethack.tty_render(obs["tty_chars"], obs["tty_colors"], obs["tty_cursor"])
            states.screen.set(screen)

            # do all the real work
            self.send_obs(obs)

            # get an action
            action = self.get_action()
            logger.trace(f"Doing action: {action}")

            # perform the action and get the next observation
            obs, reward, done, truncated, info = self.env.step(action)

            # optionally save the screen to file
            _dump_env_record(obs, loop_num)

            logger.trace(f"Main loop done: {done}, {truncated}")

            # set and save the loop number
            loop_num += 1
            states.loop.set(loop_num)
            if (loop_num % settings.status_update) == 0:
                print_state()

            if done or truncated:
                logger.info(f"Game {game_num} completed, starting next game")
                self.env.reset()
                game_num += 1

        logger.info("NLE loop done, exiting.")
        _dump_env_end()

action_bus_conn = Action.bus.connect(self) instance-attribute

env = gym.make(gym_id, **gym_opts) instance-attribute

env_bus_conn = Perception.bus.connect(self) instance-attribute

intrinsic_bus_conn = Intrinsic.bus.connect(self) instance-attribute

__init__(gym_id, *, gym_opts=None)

Source code in roc/gymnasium.py
32
33
34
35
36
37
38
39
40
41
42
43
44
def __init__(self, gym_id: str, *, gym_opts: dict[str, Any] | None = None) -> None:
    super().__init__()
    gym_opts = gym_opts or {}
    logger.info(f"Gym options: {gym_opts}")
    self.env = gym.make(gym_id, **gym_opts)

    # setup communications
    self.env_bus_conn = Perception.bus.connect(self)
    self.action_bus_conn = Action.bus.connect(self)
    self.intrinsic_bus_conn = Intrinsic.bus.connect(self)

    # config
    self.config(self.env)

config(env) abstractmethod

Source code in roc/gymnasium.py
52
53
@abstractmethod
def config(self, env: gym.core.Env[Any, Any]) -> None: ...

get_action() abstractmethod

Source code in roc/gymnasium.py
55
56
@abstractmethod
def get_action(self) -> Any: ...

send_obs(obs) abstractmethod

Source code in roc/gymnasium.py
49
50
@abstractmethod
def send_obs(self, obs: Any) -> None: ...

start()

Source code in roc/gymnasium.py
 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
@logger.catch
def start(self) -> None:
    obs, reset_info = self.env.reset()
    settings = Config.get()

    done = False
    truncated = False
    _dump_env_start()

    logger.info("Starting NLE loop...")
    loop_num = 0
    game_num = 0

    # main environment loop
    while game_num < settings.num_games:
        logger.trace(f"Sending observation: {obs}")
        breakpoints.check()

        # save the current screen
        screen = nle.nethack.tty_render(obs["tty_chars"], obs["tty_colors"], obs["tty_cursor"])
        states.screen.set(screen)

        # do all the real work
        self.send_obs(obs)

        # get an action
        action = self.get_action()
        logger.trace(f"Doing action: {action}")

        # perform the action and get the next observation
        obs, reward, done, truncated, info = self.env.step(action)

        # optionally save the screen to file
        _dump_env_record(obs, loop_num)

        logger.trace(f"Main loop done: {done}, {truncated}")

        # set and save the loop number
        loop_num += 1
        states.loop.set(loop_num)
        if (loop_num % settings.status_update) == 0:
            print_state()

        if done or truncated:
            logger.info(f"Game {game_num} completed, starting next game")
            self.env.reset()
            game_num += 1

    logger.info("NLE loop done, exiting.")
    _dump_env_end()

NethackGym

Bases: Gym

Wrapper around the Gym class for driving the Nethack interface to the ROC agent. Decodes Nethack specific data and sends it to the agent as Events.

Source code in roc/gymnasium.py
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
class NethackGym(Gym):
    """Wrapper around the Gym class for driving the Nethack interface to the ROC
    agent. Decodes Nethack specific data and sends it to the agent as Events.
    """

    def __init__(self, *, gym_opts: dict[str, Any] | None = None) -> None:
        gym_opts = gym_opts or {}
        settings = Config.get()
        gym_opts["options"] = list(nle.nethack.NETHACKOPTIONS) + settings.nethack_extra_options
        gym_opts["max_episode_steps"] = settings.nethack_max_turns
        # XXX: note that 'gym_opts["character"]' sets the character type, not
        # the player name... player name is forced to be "Agent" by NLE

        # XXX: env name options include: "NetHack", "NetHackScore", "NetHackStaircase", "NetHackStaircasePet", "NetHackOracle", "NetHackGold", "NetHackEat", "NetHackScout", "NetHackChallenge"
        # see: https://github.com/heiner/nle/blob/731f2aaa94f6d67838228f9c9b5b04faa31cb862/nle/env/__init__.py#L9
        # and: https://github.com/heiner/nle/blob/731f2aaa94f6d67838228f9c9b5b04faa31cb862/nle/env/tasks.py
        # "NetHack" is the vanilla environment
        # "NetHackScore" and "NetHackChallenge" also appear to be interesting
        super().__init__("NetHack-v0", gym_opts=gym_opts)

    def config(self, env: gym.core.Env[Any, Any]) -> None:
        settings = Config.get()
        assert isinstance(self.env.action_space, gym.spaces.Discrete)
        self.action_count = int(self.env.action_space.n)

        settings.gym_actions = tuple(self.env.unwrapped.actions)  # type: ignore
        settings.observation_shape = nle.nethack.DUNGEON_SHAPE

    def send_obs(self, obs: Any) -> None:
        self.send_vision(obs)
        self.send_intrinsics(obs)
        self.send_auditory(obs)

    def get_action(self) -> Any:
        self.action_bus_conn.send(ActionRequest())

        # get result using cache
        assert self.action_bus_conn.attached_bus.cache is not None
        cache = self.action_bus_conn.attached_bus.cache
        a = list(filter(lambda e: isinstance(e.data, TakeAction), cache))[-1]
        assert isinstance(a.data, TakeAction)

        return a.data.action

    def send_vision(self, obs: Any) -> None:
        vd = VisionData.from_dict(obs)
        self.env_bus_conn.send(vd)

    def send_auditory(self, obs: Any) -> None:
        # msg = "".join(chr(ch) for ch in obs["message"])
        # print("message", msg)
        pass

    def send_proprioceptive(self) -> None:
        pass

    def send_intrinsics(self, obs: Any) -> None:
        blstats = obs["blstats"]
        blstats_vals = {e.name.lower(): blstats[e.value] for e in blstat_offsets}
        for bit in condition_bits:
            blstats_vals[bit.name.lower()] = (
                True if blstats_vals["condition"] & bit.value else False
            )

        bl = BottomlineStats(**blstats_vals)
        self.intrinsic_bus_conn.send(bl.dict())

__init__(*, gym_opts=None)

Source code in roc/gymnasium.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
def __init__(self, *, gym_opts: dict[str, Any] | None = None) -> None:
    gym_opts = gym_opts or {}
    settings = Config.get()
    gym_opts["options"] = list(nle.nethack.NETHACKOPTIONS) + settings.nethack_extra_options
    gym_opts["max_episode_steps"] = settings.nethack_max_turns
    # XXX: note that 'gym_opts["character"]' sets the character type, not
    # the player name... player name is forced to be "Agent" by NLE

    # XXX: env name options include: "NetHack", "NetHackScore", "NetHackStaircase", "NetHackStaircasePet", "NetHackOracle", "NetHackGold", "NetHackEat", "NetHackScout", "NetHackChallenge"
    # see: https://github.com/heiner/nle/blob/731f2aaa94f6d67838228f9c9b5b04faa31cb862/nle/env/__init__.py#L9
    # and: https://github.com/heiner/nle/blob/731f2aaa94f6d67838228f9c9b5b04faa31cb862/nle/env/tasks.py
    # "NetHack" is the vanilla environment
    # "NetHackScore" and "NetHackChallenge" also appear to be interesting
    super().__init__("NetHack-v0", gym_opts=gym_opts)

config(env)

Source code in roc/gymnasium.py
233
234
235
236
237
238
239
def config(self, env: gym.core.Env[Any, Any]) -> None:
    settings = Config.get()
    assert isinstance(self.env.action_space, gym.spaces.Discrete)
    self.action_count = int(self.env.action_space.n)

    settings.gym_actions = tuple(self.env.unwrapped.actions)  # type: ignore
    settings.observation_shape = nle.nethack.DUNGEON_SHAPE

get_action()

Source code in roc/gymnasium.py
246
247
248
249
250
251
252
253
254
255
def get_action(self) -> Any:
    self.action_bus_conn.send(ActionRequest())

    # get result using cache
    assert self.action_bus_conn.attached_bus.cache is not None
    cache = self.action_bus_conn.attached_bus.cache
    a = list(filter(lambda e: isinstance(e.data, TakeAction), cache))[-1]
    assert isinstance(a.data, TakeAction)

    return a.data.action

send_auditory(obs)

Source code in roc/gymnasium.py
261
262
263
264
def send_auditory(self, obs: Any) -> None:
    # msg = "".join(chr(ch) for ch in obs["message"])
    # print("message", msg)
    pass

send_intrinsics(obs)

Source code in roc/gymnasium.py
269
270
271
272
273
274
275
276
277
278
def send_intrinsics(self, obs: Any) -> None:
    blstats = obs["blstats"]
    blstats_vals = {e.name.lower(): blstats[e.value] for e in blstat_offsets}
    for bit in condition_bits:
        blstats_vals[bit.name.lower()] = (
            True if blstats_vals["condition"] & bit.value else False
        )

    bl = BottomlineStats(**blstats_vals)
    self.intrinsic_bus_conn.send(bl.dict())

send_obs(obs)

Source code in roc/gymnasium.py
241
242
243
244
def send_obs(self, obs: Any) -> None:
    self.send_vision(obs)
    self.send_intrinsics(obs)
    self.send_auditory(obs)

send_proprioceptive()

Source code in roc/gymnasium.py
266
267
def send_proprioceptive(self) -> None:
    pass

send_vision(obs)

Source code in roc/gymnasium.py
257
258
259
def send_vision(self, obs: Any) -> None:
    vd = VisionData.from_dict(obs)
    self.env_bus_conn.send(vd)

blstat_offsets

Bases: IntEnum

An enumeration of Nethack bottom line statistics (intelligence, strength, charisma, position, hit points, etc.)

Source code in roc/gymnasium.py
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
class blstat_offsets(IntEnum):
    """An enumeration of Nethack bottom line statistics (intelligence, strength,
    charisma, position, hit points, etc.)
    """

    # fmt: off
    X =         0
    Y =         1
    STR25 =     2
    STR125 =    3
    DEX =       4
    CON =       5
    INT =       6
    WIS =       7
    CHA =       8
    SCORE =     9
    HP =        10
    HPMAX =     11
    DEPTH =     12
    GOLD =      13
    ENE =       14
    ENEMAX =    15
    AC =        16
    HD =        17
    XP =        18
    EXP =       19
    TIME =      20
    HUNGER =    21
    CAP =       22
    DNUM =      23
    DLEVEL =    24
    CONDITION = 25
    ALIGN =     26

AC = 16 class-attribute instance-attribute

ALIGN = 26 class-attribute instance-attribute

CAP = 22 class-attribute instance-attribute

CHA = 8 class-attribute instance-attribute

CON = 5 class-attribute instance-attribute

CONDITION = 25 class-attribute instance-attribute

DEPTH = 12 class-attribute instance-attribute

DEX = 4 class-attribute instance-attribute

DLEVEL = 24 class-attribute instance-attribute

DNUM = 23 class-attribute instance-attribute

ENE = 14 class-attribute instance-attribute

ENEMAX = 15 class-attribute instance-attribute

EXP = 19 class-attribute instance-attribute

GOLD = 13 class-attribute instance-attribute

HD = 17 class-attribute instance-attribute

HP = 10 class-attribute instance-attribute

HPMAX = 11 class-attribute instance-attribute

HUNGER = 21 class-attribute instance-attribute

INT = 6 class-attribute instance-attribute

SCORE = 9 class-attribute instance-attribute

STR125 = 3 class-attribute instance-attribute

STR25 = 2 class-attribute instance-attribute

TIME = 20 class-attribute instance-attribute

WIS = 7 class-attribute instance-attribute

X = 0 class-attribute instance-attribute

XP = 18 class-attribute instance-attribute

Y = 1 class-attribute instance-attribute

condition_bits

Bases: IntEnum

Bits for decoding the CONDITION bottomline stat to determin if the player is flying, deaf, food poisoned, etc.

Source code in roc/gymnasium.py
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
class condition_bits(IntEnum):
    """Bits for decoding the `CONDITION` bottomline stat to determin if the
    player is flying, deaf, food poisoned, etc.
    """

    # fmt: off
    STONE =    nle.nethack.BL_MASK_STONE
    SLIME =    nle.nethack.BL_MASK_SLIME
    STRINGL =  nle.nethack.BL_MASK_STRNGL
    FOODPOIS = nle.nethack.BL_MASK_FOODPOIS
    TERMILL =  nle.nethack.BL_MASK_TERMILL
    BLIND =    nle.nethack.BL_MASK_BLIND
    DEAF =     nle.nethack.BL_MASK_DEAF
    STUN =     nle.nethack.BL_MASK_STUN
    CONF =     nle.nethack.BL_MASK_CONF
    HALLU =    nle.nethack.BL_MASK_HALLU
    LEV =      nle.nethack.BL_MASK_LEV
    FLY =      nle.nethack.BL_MASK_FLY
    RIDE =     nle.nethack.BL_MASK_RIDE

BLIND = nle.nethack.BL_MASK_BLIND class-attribute instance-attribute

CONF = nle.nethack.BL_MASK_CONF class-attribute instance-attribute

DEAF = nle.nethack.BL_MASK_DEAF class-attribute instance-attribute

FLY = nle.nethack.BL_MASK_FLY class-attribute instance-attribute

FOODPOIS = nle.nethack.BL_MASK_FOODPOIS class-attribute instance-attribute

HALLU = nle.nethack.BL_MASK_HALLU class-attribute instance-attribute

LEV = nle.nethack.BL_MASK_LEV class-attribute instance-attribute

RIDE = nle.nethack.BL_MASK_RIDE class-attribute instance-attribute

SLIME = nle.nethack.BL_MASK_SLIME class-attribute instance-attribute

STONE = nle.nethack.BL_MASK_STONE class-attribute instance-attribute

STRINGL = nle.nethack.BL_MASK_STRNGL class-attribute instance-attribute

STUN = nle.nethack.BL_MASK_STUN class-attribute instance-attribute

TERMILL = nle.nethack.BL_MASK_TERMILL class-attribute instance-attribute