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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
#!/usr/bin/env python3

import time
import argparse
import numpy as np
import gym
import gym_minigrid
from gym_minigrid.wrappers import *
from gym_minigrid.window import Window
from utils import *
from models import MultiModalBaby11ACModel
from collections import Counter
import torch_ac
import json
from termcolor import colored, COLORS

from functools import partial
from tkinter import *

from torch.distributions import Categorical

inter_acl = False
draw_tree = True

class InteractiveACL:

    def choose(self, node):

        def pop_up(options):
            pop_data = {}

            def setVar(value):
                pop_data["var"] = value
                root.destroy()

            root = Tk()
            root.title(node.label)
            root.geometry('600x{}'.format(50*len(options)))

            for i, o in enumerate(options):
                fn = partial(setVar, value=i)
                Button(root, text='{}'.format(o), command=fn).pack()

            root.mainloop()

            return pop_data["var"]

        chosen_ind = pop_up([n.label for n in node.children])

        ch = node.children[chosen_ind]

        return ch


if inter_acl:
    interactive_acl = InteractiveACL()
else:
    interactive_acl = None


def redraw(img):
    if not args.agent_view:
        img = env.render('human', tile_size=args.tile_size, mask_unobserved=args.mask_unobserved)

    window.show_img(img)

def reset():
    # if args.seed != -1:
    #     env.seed(args.seed)

    obs = env.reset()

    if hasattr(env, 'mission'):
        print('Mission: %s' % env.mission)
        window.set_caption(env.mission)

    redraw(obs)

    if draw_tree:
        # draw tree
        params = env.current_env.parameters
        env.parameter_tree.draw_tree(
            filename="viz/SocialAIParam/parameters_{}_{}".format(params["Env_type"], hash(str(params))),
            ignore_labels=["Num_of_colors"],
            selected_parameters=params
        )

        with open('viz/SocialAIParam/parameters_{}_{}.json'.format(params["Env_type"], hash(str(params))), 'w') as fp:
            json.dump(params, fp)


tot_bonus = [0]

prev = {
    "prev_obs": None,
    "prev_info": {},
}
shortened_obj_names = {
    'lockablebox'      : 'loc_box',
    'applegenerator'   : 'app_gen',
    'generatorplatform': 'gen_pl',
    'marbletee'        : 'tee',
    'remotedoor'       : 'rem_door',
}

IDX_TO_OBJECT = {v: shortened_obj_names.get(k, k) for k, v in OBJECT_TO_IDX.items()}
# no duplicates
assert len(IDX_TO_OBJECT) == len(OBJECT_TO_IDX)

IDX_TO_COLOR = {v: k for k, v in COLOR_TO_IDX.items()}
assert len(IDX_TO_COLOR) == len(COLOR_TO_IDX)


def to_string(enc):
    s =  "{:<8} {} {} {} {} {:3} {:3} {}\t".format(
        IDX_TO_OBJECT.get(enc[0], enc[0]),  # obj
        *enc[1:3],  # x, y
        IDX_TO_COLOR.get(enc[3], enc[3])[:1].upper(),  # color
        *enc[4:]  #
    )

    if IDX_TO_OBJECT.get(enc[0], enc[0]) == "unseen":
        pass
        # s = colored(s, "on_grey")

    elif IDX_TO_OBJECT.get(enc[0], enc[0]) != "empty":
        col = IDX_TO_COLOR.get(enc[3], enc[3])
        if col in COLORS:
            s = colored(s, col)

    return s


def step(action):
    if type(action) == np.ndarray:
        obs, reward, done, info = env.step(action)
    else:
        action = [int(action), np.nan, np.nan]
        obs, reward, done, info = env.step(action)

    print('\nStep=%s' % (env.step_count))

    # print("".join(info["descriptions"]))
    print(obs['utterance_history'])
    print("")
    # print("Your possible actions are:")
    # print("a) move forward")
    # print("b) turn left")
    # print("c) turn right")
    # print("d) toggle")
    # print("e) no_op")
    # print("Your next action is: ")

    if args.print_grid:
        grid = obs['image'].transpose((1, 0, 2))
        for row_i, row in enumerate(grid):

            # if row_i == 0:
            #     for _ in row:
            #         print(to_string(["OBJECT", "X", "Y", "C", "-", "---", "---", "-"]), end="")
            #         # print("{:<8} {} {} {} {:2} {:2} {} {}\t".format("Object", "X", "Y", "C", "", "", "", ""), end="")
            # print(end="\n")

            for col_i, enc in enumerate(row):
                print(str(enc), end=" | ")
                # if row_i == len(grid) - 1 and col_i == len(row) // 2:
                #     # gent
                #     print(to_string(["^^^^^^", "^", "^", "^", "^", "^^^", "^^^", "^"]), end="")
                # else:
                #     print(to_string(enc), end="")
            print(end="\n")

    if not args.agent_view:

        nvec = algo.acmodel.model_raw_action_space.nvec

        raw_action = (
            5 if np.isnan(action[0]) else 1,  # speak switch
            0 if np.isnan(action[1]) else 1,  # speak switch
            0 if np.isnan(action[1]) else action[1],  # template
            0 if np.isnan(action[2]) else action[2],  # word
        )


        dist = []
        for a, n in zip(raw_action, nvec):
            logits = torch.ones(n)[None, :]
            logits[0][int(a)] *= 10

            d = Categorical(logits=logits)
            dist.append(d)
        if args.calc_bonus:
            bonus = algo.calculate_exploration_bonus(
                obs=[obs],
                embeddings=torch.zeros([1,128]),
                done=[done],
                prev_obs=[prev["prev_obs"]],
                prev_info=[prev["prev_info"]],
                agent_actions=torch.tensor([raw_action]),
                dist=dist,
                i_step=0,
            )

        else:
            bonus = [0]

        prev["prev_obs"] = obs
        prev["prev_info"] = info

        tot_bonus[0] = tot_bonus[0]+bonus[0]
        print('expl_bonus_step=%.2f' % (bonus[0]))
        print('tot_bonus=%.2f' % (tot_bonus[0]))

        if done:
            for v in algo.visitation_counter.values():
                v[0] = Counter()

    print('Full reward (undiminshed)=%.2f' % (reward))

    redraw(obs)

    if done:
        print('done!')
        print('Reward=%.2f' % (reward))
        print('Exploration_bonus=%.2f' % (tot_bonus[0]))
        tot_bonus[0] = 0

        if draw_tree:
            # draw tree
            params = env.current_env.parameters
            env.parameter_tree.draw_tree(
                filename="viz/SocialAIParam/parameters_{}_{}".format(params["Env_type"], hash(str(params))),
                ignore_labels=[],
                selected_parameters=params,
            )

            with open('viz/SocialAIParam/parameters_{}_{}.json'.format(params["Env_type"], hash(str(params))),
                      'w') as fp:
                json.dump(params, fp)

        reset()

def key_handler(event):

    # if hasattr(event.canvas, "_event_loop") and event.canvas._event_loop.isRunning():
    #     return

    print('pressed', event.key)

    action_dict = {
        "up": "a) move forward",
        "left": "b) turn left",
        "right": "c) turn right",
        " ": "d) toggle",
        "shift": "e) no_op",
    }

    if event.key in action_dict:
        your_action = action_dict[event.key]
        print("Your next action is: {}".format(your_action))

    if event.key == 'escape':
        window.close()
        return

    if event.key == 'r':
        reset()
        return

    if event.key == 'tab':
        step(np.array([np.nan, np.nan, np.nan]))
        return

    if event.key == 'shift':
        step(np.array([np.nan, np.nan, np.nan]))
        return

    if event.key == 'left':
        step(env.actions.left)
        return
    if event.key == 'right':
        step(env.actions.right)
        return
    if event.key == 'up':
        step(env.actions.forward)
        return
    if event.key == 't':
        step(env.actions.speak)
        return

    if event.key == '1':
        step(np.array([np.nan, 0, 0]))
        return
    if event.key == '2':
        step(np.array([np.nan, 0, 1]))
        return
    if event.key == '3':
        step(np.array([np.nan, 1, 0]))
        return
    if event.key == '4':
        step(np.array([np.nan, 1, 1]))
        return
    if event.key == '5':
        step(np.array([np.nan, 2, 2]))
        return
    if event.key == '6':
        step(np.array([np.nan, 1, 2]))
        return
    if event.key == '7':
        step(np.array([np.nan, 2, 1]))
        return
    if event.key == '8':
        step(np.array([np.nan, 1, 3]))
        return
    if event.key == 'p':
        step(np.array([np.nan, 3, 3]))
        return

    # Spacebar
    if event.key == ' ':
        step(env.actions.toggle)
        return
    if event.key == '9':
        step(env.actions.pickup)
        return
    if event.key == '0':
        step(env.actions.drop)
        return

    if event.key == 'enter':
        step(env.actions.done)
        return

parser = argparse.ArgumentParser()
parser.add_argument(
    "--env",
    help="gym environment to load",
    default='SocialAI-ELangColorBoxesTestInformationSeekingParamEnv-v1',
)
parser.add_argument(
    "--seed",
    type=int,
    help="random seed to generate the environment with",
    default=-1
)
parser.add_argument(
    "--tile_size",
    type=int,
    help="size at which to render tiles",
    default=32
)
parser.add_argument(
    '--agent_view',
    default=False,
    help="draw the agent sees (partially observable view)",
    action='store_true'
)
parser.add_argument(
    '--print_grid',
    default=False,
    help="print the grid with symbols",
    action='store_true'
)
parser.add_argument(
    '--calc-bonus',
    default=False,
    help="calculate explo bonus",
    action='store_true'
)
parser.add_argument(
    '--mask-unobserved',
    default=False,
    help="mask cells that are not observed by the agent",
    action='store_true'
)

# Put all env related arguments after --env_args, e.g. --env_args nb_foo 1 is_bar True
parser.add_argument("--env-args", nargs='*', default=None)

parser.add_argument("--exploration-bonus", action="store_true", default=False,
                    help="Use a count based exploration bonus")
parser.add_argument("--exploration-bonus-type", nargs="+", default=["lang"],
                    help="modality on which to use the bonus (lang/grid/cell)")
parser.add_argument("--exploration-bonus-params", nargs="+", type=float, default=(30., 50.),  # lang
                    help="parameters for a count based exploration bonus (C, M)")
# parser.add_argument("--exploration-bonus-params", nargs="+", type=float, default=(3, 50.),  # cell
#                     help="parameters for a count based exploration bonus (C, M)")
# parser.add_argument("--exploration-bonus-params", nargs="+", type=float, default=(1.5, 50.), # grid
#                     help="parameters for a count based exploration bonus (C, M)")
parser.add_argument("--exploration-bonus-tanh", nargs="+", type=float, default=None,
                    help="tanh expl bonus scale, None means no tanh")
parser.add_argument("--intrinsic-reward-coef", type=float, default=0.1,
                    help="tanh expl bonus scale, None means no tanh")

args = parser.parse_args()

if interactive_acl:
    env = gym.make(args.env, curriculum=interactive_acl, **env_args_str_to_dict(args.env_args))
else:
    env = gym.make(args.env, **env_args_str_to_dict(args.env_args))

if draw_tree:
    # draw tree
    env.parameter_tree.draw_tree(
        filename="viz/SocialAIParam/{}_raw_tree".format(args.env),
        ignore_labels=["Num_of_colors"],
    )


# if hasattr(env, "draw_tree"):
#     env.draw_tree(ignore_labels=["Num_of_colors"])

# if hasattr(env, "print_tree"):
#     env.print_tree()

if args.seed >= 0:
    env.seed(args.seed)

# dummy just algo instance just to enable exploration bonus calculation
algo = torch_ac.PPOAlgo(
    envs=[env],
    acmodel=MultiModalBaby11ACModel(
        obs_space=utils.get_obss_preprocessor(
            obs_space=env.observation_space,
            text=False,
            dialogue_current=False,
            dialogue_history=True,
        )[0],
        action_space=env.action_space,
    ),
    exploration_bonus=True,
    exploration_bonus_tanh=args.exploration_bonus_tanh,
    exploration_bonus_type=args.exploration_bonus_type,
    exploration_bonus_params=args.exploration_bonus_params,
    expert_exploration_bonus=False,
    episodic_exploration_bonus=True,
    intrinsic_reward_coef=args.intrinsic_reward_coef,
    num_frames_per_proc=40,
)

# if args.agent_view:
#     env = RGBImgPartialObsWrapper(env)
#     env = ImgObsWrapper(env)

window = Window('gym_minigrid - ' + args.env, figsize=(4, 4))
window.reg_key_handler(key_handler)
env.window = window

# Blocking event loop
window.show(block=True)