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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
import numpy as np

from gym_minigrid.minigrid import *
from gym_minigrid.register import register
 
import time
from collections import deque


class Peer(NPC):
    """
    A dancing NPC that the agent has to copy
    """

    def __init__(self, color, name, env, knowledgeable=False):
        super().__init__(color)
        self.name = name
        self.npc_dir = 1  # NPC initially looks downward
        self.npc_type = 0
        self.env = env
        self.knowledgeable = knowledgeable 
        self.npc_actions = []
        self.dancing_step_idx = 0
        self.actions = MiniGridEnv.Actions
        self.add_npc_direction = True
        self.available_moves = [self.rotate_left, self.rotate_right, self.go_forward, self.toggle_action]
        self.exited = False

    def step(self):
        if self.exited:
            return

        if all(np.array(self.cur_pos) == np.array(self.env.door_pos)):
            # disappear
            self.env.grid.set(*self.cur_pos, self.env.object)
            self.cur_pos = np.array([np.nan, np.nan])

            # close door
            self.env.object.toggle(self.env, self.cur_pos)

            # reset switches door
            for s in self.env.switches:
                s.is_on = False

            # update door
            self.env.update_door_lock()

            self.exited = True

        elif self.knowledgeable:

            if self.env.object.is_locked:
                first_wrong_id = np.where(self.env.get_selected_password() != self.env.password)[0][0]
                print("first_wrong_id:", first_wrong_id)
                goal_pos = self.env.switches_pos[first_wrong_id]
                act = self.path_to_toggle_pos(goal_pos)
                act()

            else:
                if all(self.front_pos == self.env.door_pos) and self.env.object.is_open:
                    self.go_forward()

                else:
                    act = self.path_to_toggle_pos(self.env.door_pos)
                    act()

        else:
            self.env._rand_elem(self.available_moves)()

        self.env.update_door_lock()


class SpyingGrammar(object):

    templates = ["Move your", "Shake your"]
    things = ["body", "head"]

    grammar_action_space = spaces.MultiDiscrete([len(templates), len(things)])

    @classmethod
    def construct_utterance(cls, action):
        return cls.templates[int(action[0])] + " " + cls.things[int(action[1])] + " "


class SpyingEnv(MultiModalMiniGridEnv):
    """
    Environment in which the agent is instructed to go to a given object
    named using an English text string
    """

    def __init__(
        self,
        size=5,
        diminished_reward=True,
        step_penalty=False,
        knowledgeable=False,
        hard_password=False,
        max_steps=None,
        n_switches=3
    ):
        assert size >= 5
        self.empty_symbol = "NA \n"
        self.diminished_reward = diminished_reward
        self.step_penalty = step_penalty
        self.knowledgeable = knowledgeable
        self.hard_password = hard_password
        self.n_switches = n_switches

        super().__init__(
            grid_size=size,
            max_steps=max_steps or 5*size**2,
            # Set this to True for maximum speed
            see_through_walls=True,
            actions=MiniGridEnv.Actions,
            action_space=spaces.MultiDiscrete([
                len(MiniGridEnv.Actions),
                *SpyingGrammar.grammar_action_space.nvec
            ]),
            add_npc_direction=True
        )

        print({
            "size": size,
            "diminished_reward": diminished_reward,
            "step_penalty": step_penalty,
        })

    def get_selected_password(self):
        return np.array([int(s.is_on) for s in self.switches])

    def _gen_grid(self, width, height):
        # Create the grid
        self.grid = Grid(width, height, nb_obj_dims=4)

        # Randomly vary the room width and height
        width = self._rand_int(5, width+1)
        height = self._rand_int(5, height+1)

        self.wall_x = width - 1
        self.wall_y = height - 1

        # Generate the surrounding walls
        self.grid.wall_rect(0, 0, width, height)

        door_color = self._rand_elem(COLOR_NAMES)

        wall_for_door = self._rand_int(1, 4)

        if wall_for_door < 2:
            w = self._rand_int(1, width-1)
            h = height-1 if wall_for_door == 0 else 0
        else:
            w = width-1 if wall_for_door == 3 else 0
            h = self._rand_int(1, height-1)

        assert h != height-1  # door mustn't be on the bottom wall

        self.door_pos = (w, h)
        self.door = Door(door_color, is_locked=True)
        self.grid.set(*self.door_pos, self.door)

        # add the switches
        self.switches = []
        self.switches_pos = []
        for i in range(self.n_switches):
            c = COLOR_NAMES[i]
            pos = np.array([i+1, height-1])
            sw = Switch(c)
            self.grid.set(*pos, sw)
            self.switches.append(sw)
            self.switches_pos.append(pos)

        # sample password
        if self.hard_password:
            self.password = np.array([self._rand_int(0, 2) for _ in range(self.n_switches)])

        else:
            idx = self._rand_int(0, self.n_switches)
            self.password = np.zeros(self.n_switches)
            self.password[idx] = 1.0

        # Set a randomly coloured Dancer NPC
        color = self._rand_elem(COLOR_NAMES)
        self.peer = Peer(color, "Jim", self, knowledgeable=self.knowledgeable)

        # Place it on the middle left side of the room
        peer_pos = np.array((self._rand_int(1, width - 1), self._rand_int(1, height - 1)))

        self.grid.set(*peer_pos, self.peer)
        self.peer.init_pos = peer_pos
        self.peer.cur_pos = peer_pos

        # Randomize the agent's start position and orientation
        self.place_agent(size=(width, height))

        # Generate the mission string
        self.mission = 'exit the room'

        # Dummy beginning string
        self.beginning_string = "This is what you hear. \n"
        self.utterance = self.beginning_string

        # utterance appended at the end of each step
        self.utterance_history = ""

        # used for rendering
        self.conversation = self.utterance

    def update_door_lock(self):
        if np.array_equal(self.get_selected_password(), self.password):
            self.door.is_locked = False
        else:
            self.door.is_locked = True
            self.door.is_open = False

    def step(self, action):
        p_action = action[0]
        utterance_action = action[1:]

        obs, reward, done, info = super().step(p_action)
        self.update_door_lock()

        print("pass:", self.password)

        if p_action == self.actions.done:
            done = True

        self.peer.step()

        if all(self.agent_pos == self.door_pos):
            done = True
            if self.peer.exited:
                # only give reward of both exited
                reward = self._reward()

        # discount
        if self.step_penalty:
            reward = reward - 0.01

        # fill observation with text
        self.append_existing_utterance_to_history()
        obs = self.add_utterance_to_observation(obs)
        self.reset_utterance()
        return obs, reward, done, info

    def _reward(self):
        if self.diminished_reward:
            return super()._reward()
        else:
            return 1.0

    def render(self, *args, **kwargs):
        obs = super().render(*args, **kwargs)
        print("conversation:\n", self.conversation)
        print("utterance_history:\n", self.utterance_history)
        self.window.set_caption(self.conversation, [self.peer.name])
        return obs


class Spying8x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8)


class Spying6x6Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=6)


# knowledgeable
class SpyingKnowledgeableEnv(SpyingEnv):
    def __init__(self):
        super().__init__(size=5, knowledgeable=True)

class SpyingKnowledgeable6x6Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=6, knowledgeable=True)

class SpyingKnowledgeable8x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8, knowledgeable=True)

class SpyingKnowledgeableHardPassword8x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8, knowledgeable=True, hard_password=True)

class Spying508x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8, max_steps=50)

class SpyingKnowledgeable508x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8, knowledgeable=True, max_steps=50)

class SpyingKnowledgeableHardPassword508x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8, knowledgeable=True, hard_password=True, max_steps=50)

class SpyingKnowledgeable1008x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8, knowledgeable=True, max_steps=100)

class SpyingKnowledgeable100OneSwitch8x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8, knowledgeable=True, max_steps=100, n_switches=1)

class SpyingKnowledgeable50OneSwitch5x5Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=5, knowledgeable=True, max_steps=50, n_switches=1)


class SpyingKnowledgeable505x5Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=5, knowledgeable=True, max_steps=50, n_switches=3)

class SpyingKnowledgeable50TwoSwitches8x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8, knowledgeable=True, max_steps=50, n_switches=2)

class SpyingKnowledgeable50TwoSwitchesHard8x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8, knowledgeable=True, max_steps=50, n_switches=2, hard_password=True)


class SpyingKnowledgeable100TwoSwitches8x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8, knowledgeable=True, max_steps=100, n_switches=2)

class SpyingKnowledgeable100TwoSwitchesHard8x8Env(SpyingEnv):
    def __init__(self):
        super().__init__(size=8, knowledgeable=True, max_steps=100, n_switches=2, hard_password=True)




register(
    id='MiniGrid-Spying-5x5-v0',
    entry_point='gym_minigrid.envs:SpyingEnv'
)

register(
    id='MiniGrid-Spying-6x6-v0',
    entry_point='gym_minigrid.envs:Spying6x6Env'
)

register(
    id='MiniGrid-Spying-8x8-v0',
    entry_point='gym_minigrid.envs:Spying8x8Env'
)

register(
    id='MiniGrid-SpyingKnowledgeable-5x5-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeableEnv'
)

register(
    id='MiniGrid-SpyingKnowledgeable-6x6-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeable6x6Env'
)

register(
    id='MiniGrid-SpyingKnowledgeable-8x8-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeable8x8Env'
)

register(
    id='MiniGrid-SpyingKnowledgeableHardPassword-8x8-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeableHardPassword8x8Env'
)

# max len 50
register(
    id='MiniGrid-Spying50-8x8-v0',
    entry_point='gym_minigrid.envs:Spying508x8Env'
)

register(
    id='MiniGrid-SpyingKnowledgeable50-8x8-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeable508x8Env'
)

register(
    id='MiniGrid-SpyingKnowledgeableHardPassword50-8x8-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeableHardPassword508x8Env'
)

# max len 100
register(
    id='MiniGrid-SpyingKnowledgeable100-8x8-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeable1008x8Env'
)

# max len OneSwitch
register(
    id='MiniGrid-SpyingKnowledgeable100OneSwitch-8x8-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeable100OneSwitch8x8Env'
)

register(
    id='MiniGrid-SpyingKnowledgeable50OneSwitch-5x5-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeable50OneSwitch5x5Env'
)

register(
    id='MiniGrid-SpyingUnknowledgeable50OneSwitch-5x5-v0',
    entry_point='gym_minigrid.envs:SpyingUnknowledgeable50OneSwitch5x5Env'
)

register(
    id='MiniGrid-SpyingKnowledgeable50-5x5-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeable505x5Env'
)

register(
    id='MiniGrid-SpyingKnowledgeable50TwoSwitches-8x8-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeable50TwoSwitches8x8Env'
)
register(
    id='MiniGrid-SpyingKnowledgeable50TwoSwitchesHard-8x8-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeable50TwoSwitchesHard8x8Env'
)
register(
    id='MiniGrid-SpyingKnowledgeable100TwoSwitches-8x8-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeable100TwoSwitches8x8Env'
)
register(
    id='MiniGrid-SpyingKnowledgeable100TwoSwitchesHard-8x8-v0',
    entry_point='gym_minigrid.envs:SpyingKnowledgeable100TwoSwitchesHard8x8Env'
)