emnlp-submission commited on
Commit
6343f32
·
verified ·
1 Parent(s): 8388cad

Update scripts / maze.py

Browse files
Files changed (1) hide show
  1. scripts / maze.py +693 -0
scripts / maze.py CHANGED
@@ -0,0 +1,693 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import numpy as np
3
+ import matplotlib.pyplot as plt
4
+ from collections import defaultdict
5
+ import copy
6
+ import json
7
+ import pickle
8
+ from math import floor, ceil
9
+ import os
10
+ from concurrent.futures import ThreadPoolExecutor, as_completed
11
+ import traceback
12
+ from maze_loader import MazeLoader
13
+
14
+ from rooms import NameGenerator
15
+
16
+
17
+ class MazeGenerator:
18
+ """A class for generating mazes with locked doors and distributed keys.
19
+
20
+ The maze is generated using Kruskal's algorithm and includes features like:
21
+ - Locked doors requiring keys
22
+ - Keys distributed throughout the maze
23
+ - Sub-problems with reduced complexity
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ N, # number of rows
29
+ M, # number of columns
30
+ rescue_agent="Bob", # the name of the rescue agent
31
+ victim="Alice", # the name of the victim
32
+ max_big_loop_count=5, # retry logic parameter
33
+ max_retry_count=10, # retry logic parameter
34
+ N_locked_doors=2, # the number of locked doors in the maze for the most difficult sub-problem
35
+ generate_sub_problems=True, # whether to generate sub-problems from the original problem (reduced N_locked_doors without changing the maze pattern)
36
+ verbose=True, # whether to print the maze parameters
37
+ random_seeds=None,
38
+ # shuffle_room_names=False,
39
+ shuffle_key_ids=False,
40
+ ):
41
+
42
+ # random_seeds = {'random_room_name_pool': 1744527184380, 'key_ids': 1744527184480, 'maze_generation': 1744527184580, 'door_distribution': 1744527184680, 'problem_generation': 22869, 'end_room': 993550, 'remove_key': 1744527184980, 'remove_key_1': 63332129, 'remove_key_2': 3892716716, 'remove_key_3': 4053259202, 'remove_key_4': 2836627271, 'remove_key_5': 2154501613, 'remove_key_6': 3371613490, 'remove_key_7': 638681366}
43
+ if random_seeds is None:
44
+ self.random_seeds = {
45
+ "key_ids": random.randint(100, 2**32 - 1),
46
+ "maze_generation": random.randint(100, 2**32 - 1),
47
+ "door_distribution": random.randint(100, 2**32 - 1),
48
+ "problem_generation": random.randint(100, 2**32 - 1),
49
+ "end_room": random.randint(100, 2**32 - 1),
50
+ "remove_key": random.randint(100, 2**32 - 1),
51
+ }
52
+ else:
53
+ self.random_seeds = random_seeds
54
+ self.name_generator = NameGenerator(N, M)
55
+ self.N = N # Number of rows
56
+ self.M = M # Number of columns
57
+ self.rescue_agent = rescue_agent
58
+ self.victim = victim
59
+ self.max_big_loop_count = max_big_loop_count
60
+ self.max_retry_count = max_retry_count
61
+ self.N_locked_doors = N_locked_doors # the number of locked doors in the maze for the most difficult sub-problem
62
+ self.generate_sub_problems = generate_sub_problems # whether to generate sub-problems from the original problem (N_locked_doors)
63
+ self.verbose = verbose
64
+ self.shuffle_key_ids = shuffle_key_ids
65
+ self.parent = {} # Disjoint set for Kruskal's algorithm
66
+ self.rank = {} # Rank for union-find
67
+ self.edges = [] # List of possible edges
68
+ self.maze = np.ones((2 * N + 1, 2 * M + 1)) # Initialize grid with walls
69
+ self.connected_cells = defaultdict(dict)
70
+ self.room_name = {}
71
+ self.doors = {}
72
+ # self.key_ids = #["0"*(6-len(str(i))) + f"{i}" for i in range(100000)]
73
+ self.key_ids = [f"{i}" for i in range(1, 10000)][::-1]
74
+ self.keys_locations = {}
75
+ # self.random_room_name_pool = ["R" + "0"*(6-len(str(i))) + f"{i}" for i in range(100000)]
76
+ # room_index_max = ceil((N * M) / 26) if N * M > 26 else 0
77
+ # self.random_room_name_pool = generate_letter_number_list(room_index_max)
78
+ # print(len(self.random_room_name_pool), room_index_max)
79
+ # if random_seeds is None:
80
+ self.random_seeds.update(
81
+ {
82
+ f"remove_key_{i+1}": random.randint(100, 2**32 - 1)
83
+ for i, _ in enumerate(range(self.N_locked_doors))
84
+ }
85
+ )
86
+ self.did_succeed = False
87
+ if verbose:
88
+ self.print_maze_parameters()
89
+
90
+ random.seed(self.random_seeds["key_ids"])
91
+ if self.shuffle_key_ids:
92
+ random.shuffle(self.key_ids)
93
+
94
+ def print_maze_parameters(self):
95
+ """Print the current maze generation parameters."""
96
+ print("\033[93m" + "the random seeds are: " + "\033[0m", self.random_seeds)
97
+ print("maze parameters are: ")
98
+ print(f"N: {self.N}")
99
+ print(f"M: {self.M}")
100
+ print(f"rescue_agent: {self.rescue_agent}")
101
+ print(f"victim: {self.victim}")
102
+ print(f"max_big_loop_count: {self.max_big_loop_count}")
103
+ print(f"max_retry_count: {self.max_retry_count}")
104
+ print(f"N_locked_doors: {self.N_locked_doors}")
105
+ print(f"generate_sub_problems: {self.generate_sub_problems}")
106
+
107
+ def find(self, node):
108
+ """Find the root of the set containing node (with path compression).
109
+ This is used in the union function"""
110
+ if self.parent[node] != node:
111
+ self.parent[node] = self.find(self.parent[node])
112
+ return self.parent[node]
113
+
114
+ def union(self, node1, node2):
115
+ """Union by rank - used in kruskal's algorithm"""
116
+ root1 = self.find(node1)
117
+ root2 = self.find(node2)
118
+
119
+ if root1 != root2:
120
+ if self.rank[root1] > self.rank[root2]:
121
+ self.parent[root2] = root1
122
+ elif self.rank[root1] < self.rank[root2]:
123
+ self.parent[root1] = root2
124
+ else:
125
+ self.parent[root2] = root1
126
+ self.rank[root1] += 1
127
+ return True
128
+ return False
129
+
130
+ def assign_room_name(self, cell):
131
+ return self.name_generator.get_name(cell)
132
+
133
+ def generate_edges(self):
134
+ """Generate edges between adjacent cells."""
135
+ for r in range(self.N):
136
+ for c in range(self.M):
137
+ node = (r, c)
138
+ self.parent[node] = node
139
+ self.rank[node] = 0
140
+ if r < self.N - 1: # Vertical edge
141
+ self.edges.append(((r, c), (r + 1, c)))
142
+ if c < self.M - 1: # Horizontal edge
143
+ self.edges.append(((r, c), (r, c + 1)))
144
+ self.room_name[node] = self.assign_room_name(node)
145
+
146
+ def generate_maze_with_doors(self):
147
+ """Generate the maze using Kruskal's algorithm."""
148
+ if self.verbose:
149
+ print("generating the maze with doors...")
150
+ self.generate_edges()
151
+ random.seed(self.random_seeds["maze_generation"])
152
+ random.shuffle(self.edges) # Shuffle edges for randomness
153
+ random.seed(self.random_seeds["door_distribution"])
154
+ ps = [(random.random(), random.random()) for _ in range(len(self.edges))]
155
+ for (cell1, cell2), p in zip(self.edges, ps):
156
+ if self.union(cell1, cell2): # Connect disjoint sets
157
+ # Convert lattice coordinates to maze coordinates
158
+ wall_r = 2 * cell1[0] + 1 + (cell2[0] - cell1[0])
159
+ wall_c = 2 * cell1[1] + 1 + (cell2[1] - cell1[1])
160
+ self.maze[2 * cell1[0] + 1, 2 * cell1[1] + 1] = 0 # Mark cell as open
161
+ self.maze[2 * cell2[0] + 1, 2 * cell2[1] + 1] = 0 # Mark cell as open
162
+ self.maze[wall_r, wall_c] = 0 # Remove wall
163
+ self.connected_cells[cell1][cell2] = 1
164
+ self.connected_cells[cell2][cell1] = 1
165
+ status = "open"
166
+ self.maze[
167
+ wall_r, wall_c
168
+ ] = 4 # 3 if status == 'closed but unlocked' else 4
169
+ self.doors[(cell1, cell2)] = (status, self.key_ids.pop())
170
+ self.doors[(cell2, cell1)] = self.doors[(cell1, cell2)]
171
+
172
+ def flush_checkpoints(self, checkpoints, removed_key_count):
173
+ while len(checkpoints) > 1:
174
+ rooms_in_path = self.find_shortest_path(checkpoints[0], checkpoints[1])
175
+ if rooms_in_path is None:
176
+ rooms_in_path = []
177
+ for sub_room in rooms_in_path[
178
+ :-1
179
+ ]: # we ensure we are not double counting the rooms
180
+ self.standardized_problem_solution_backward[removed_key_count] += [
181
+ ("move_to", sub_room)
182
+ ]
183
+ checkpoints.pop(0)
184
+
185
+ def standardize_sub_problems_and_solutions(self):
186
+ # use the strategy backward to generate the standardized problem and solution in the final desired format
187
+ self.standardized_problem_solution_backward = defaultdict(list)
188
+ removed_key_count = 0
189
+ self.sub_maze_configurations = {}
190
+ self.sub_problem_maze = copy.deepcopy(self.maze_original)
191
+ self.sub_problem_doors = copy.deepcopy(self.doors_original)
192
+ self.connected_cells = dict(self.connected_cells)
193
+ number_of_unlocking_actions_required = (
194
+ len(self.strategy_backward_original) - 2
195
+ ) // 2
196
+ while removed_key_count <= (len(self.strategy_backward_original) - 2) // 2:
197
+ checkpoints = []
198
+ for i, (room, context, action) in enumerate(self.strategy_backward):
199
+ if action.split(":")[0] == "end_room":
200
+ self.standardized_problem_solution_backward[removed_key_count] += [
201
+ ("rescue", self.victim)
202
+ ]
203
+ checkpoints.append(room)
204
+ elif action.split(":")[0] == "unlock_door":
205
+ checkpoints.append(room)
206
+ checkpoints.append(context)
207
+ self.flush_checkpoints(checkpoints, removed_key_count)
208
+ self.standardized_problem_solution_backward[removed_key_count] += [
209
+ ("unlock_and_open_door_to", room)
210
+ ]
211
+ self.standardized_problem_solution_backward[removed_key_count] += [
212
+ ("use_key", self.doors[(room, context)][1])
213
+ ]
214
+ elif action.split(":")[0] == "pick_up_key":
215
+ checkpoints.append(room)
216
+ self.flush_checkpoints(checkpoints, removed_key_count)
217
+ self.standardized_problem_solution_backward[removed_key_count] += [
218
+ ("pick_up_key", action.split(":")[1])
219
+ ]
220
+ elif action.split(":")[0] == "start_room":
221
+ checkpoints.append(room)
222
+ self.flush_checkpoints(checkpoints, removed_key_count)
223
+ self.standardized_problem_solution_backward[removed_key_count] += [
224
+ ("start", room)
225
+ ]
226
+ self.flush_checkpoints(checkpoints, removed_key_count)
227
+
228
+ self.sub_maze_configurations[removed_key_count] = {
229
+ "maze": self.sub_problem_maze.astype(int).tolist(),
230
+ "doors": copy.deepcopy(self.sub_problem_doors),
231
+ "keys_locations": copy.deepcopy(self.keys_locations),
232
+ "number_of_unlocking_actions_required": number_of_unlocking_actions_required,
233
+ }
234
+ # if the flag is not set, we stop the process after generating the first sub-problem (with N_locked_doors locked doors)
235
+ if not self.generate_sub_problems:
236
+ break
237
+
238
+ removed_key_count += 1
239
+ if len(self.on_optimal_path_locked_doors_indices) == 0:
240
+ break
241
+
242
+ random.seed(self.random_seeds[f"remove_key_{removed_key_count}"])
243
+ # ss = random.randint(0, floor((len(self.strategy_backward) - 2) / 2) - 1)
244
+
245
+ ss = self.on_optimal_path_locked_doors_indices.pop(0)
246
+
247
+ cell1, cell2 = (
248
+ self.drs[ss][0],
249
+ self.drs[ss][1],
250
+ )
251
+ status = "open"
252
+ self.sub_problem_doors[(cell1, cell2)] = (
253
+ status,
254
+ self.sub_problem_doors[(cell1, cell2)][1],
255
+ )
256
+ self.sub_problem_doors[(cell2, cell1)] = self.sub_problem_doors[
257
+ (cell1, cell2)
258
+ ]
259
+ # updating the maze and doors to reflect that
260
+ wall_r = 2 * cell1[0] + 1 + (cell2[0] - cell1[0])
261
+ wall_c = 2 * cell1[1] + 1 + (cell2[1] - cell1[1])
262
+ self.sub_problem_maze[wall_r, wall_c] = 4
263
+ # don't need to change the key locations and can keep that as noise
264
+ # we remove the locked door knowing that the backward strategy pattern is
265
+ # inverse of ['start_room'] +['pick_up_key', 'unlock_door'] * N_locked_doors + ['end_room']
266
+ self.drs[ss] = (
267
+ self.drs[ss][0],
268
+ self.drs[ss][1],
269
+ "open",
270
+ self.drs[ss][3],
271
+ False,
272
+ )
273
+ (
274
+ extra_removed_keys,
275
+ number_of_unlocking_actions_required,
276
+ ) = self.remove_redundant_steps_from_strategy_backward(
277
+ ss
278
+ ) # if the rooms associated with a removed locked door is not on the optimal path, we remove it
279
+ removed_key_count += extra_removed_keys
280
+
281
+ if not removed_key_count <= (len(self.strategy_backward_original) - 2) // 2:
282
+ break
283
+
284
+ def remove_redundant_steps_from_strategy_backward(self, ss):
285
+ # prouning the ground truth to ensure optimality by tweaking the strategy backward
286
+ """
287
+ get the list of all locked doors in the original backward strategy in the following format:
288
+ drs = [(cell1, cell2, status = 'open | locked', is_on_optimal_path[bool], included_in_gt_or_not[bool]),...]
289
+ when changing status of an item to open (as part of sub problem generation logic)
290
+ set drs[s]['included_in_gt_or_not'] = False, check prevoius item (s = s-1)
291
+ if drs[s]['is_on_optimal_path'] = False , set drs[s]['included_in_gt_or_not'] = False
292
+ and set s = s-1 and do the check again
293
+ if drs[s]['is_on_optimal_path'] = True, stop the process
294
+ return the number of extra removed keys
295
+ """
296
+ inds_to_drop = []
297
+ # drop the opened door from the strategy backward
298
+ dr = self.drs[ss]
299
+ for i, item in enumerate(self.strategy_backward):
300
+ if (item[0] == dr[0] and item[1] == dr[1]) or (
301
+ item[0] == dr[1] and item[1] == dr[0]
302
+ ):
303
+ inds_to_drop.append(i)
304
+ i = ss + 1
305
+ if i >= len(self.drs):
306
+ self.strategy_backward = [
307
+ self.strategy_backward[i]
308
+ for i in range(len(self.strategy_backward))
309
+ if i not in inds_to_drop and i - 1 not in inds_to_drop
310
+ ]
311
+ number_of_unlocking_actions_required = (
312
+ len(self.strategy_backward) - 2
313
+ ) // 2
314
+ return 0, number_of_unlocking_actions_required
315
+ is_on_optimal_path = self.drs[i][3]
316
+ extra_removed_keys = 0
317
+
318
+ while i < len(self.drs) and ((not is_on_optimal_path)):
319
+ dr = self.drs[i]
320
+ self.drs[i] = (dr[0], dr[1], dr[2], False, False)
321
+ # drop the removed door from the ground truth from the strategy backward
322
+ for j, item in enumerate(self.strategy_backward):
323
+ if (item[0] == dr[0] and item[1] == dr[1]) or (
324
+ item[0] == dr[1] and item[1] == dr[0]
325
+ ):
326
+ inds_to_drop.append(j)
327
+ extra_removed_keys += 1
328
+
329
+ i += 1
330
+ if i >= len(self.drs):
331
+ break
332
+ is_on_optimal_path = self.drs[i][3]
333
+ # remove both unlock and pickup from the strategy backward for dropped doors
334
+ self.strategy_backward = [
335
+ self.strategy_backward[i]
336
+ for i in range(len(self.strategy_backward))
337
+ if i not in inds_to_drop and i - 1 not in inds_to_drop
338
+ ]
339
+ number_of_unlocking_actions_required = (len(self.strategy_backward) - 2) // 2
340
+ return extra_removed_keys, number_of_unlocking_actions_required
341
+
342
+ def generate_distributed_keys_rescue_positive_problem(self):
343
+ # positive means that the problem is solvable
344
+ # there are locked doors between start_room and end_room
345
+ # these locked doors have keys distributed throughout the maze
346
+ # Alex needs to find the keys and open the doors on its path to rescue Maggie
347
+ # Not all keys open all doors
348
+ # circular dependency can exist: when the key to open a
349
+ # locked door to room A is in a room B that is on the path to it has a locked door
350
+ # but the key to open that locked door is in room A -
351
+ # there is a circular dependency and it makes it impossible to rescue Maggie
352
+
353
+ ### GENERATION PROCESS #########################################################
354
+ # We use a reverse back in time to build the problem configuration
355
+ # We move back in time from the moment Maggie is rescued to the moment Alex starts the rescue
356
+ # Initially all the rooms are unlocked
357
+ ################################################################################
358
+ # 1. Pick a random room as the episode's final state (Maggie's location - Alex's final location):
359
+ self.maze_original = copy.deepcopy(self.maze)
360
+ self.doors_original = copy.deepcopy(self.doors)
361
+ self.keys_locations_original = copy.deepcopy(self.keys_locations)
362
+ self.random_seeds["problem_generation"] = random.randint(0, 1000000)
363
+ random.seed(self.random_seeds["problem_generation"])
364
+ succeeded = False
365
+ big_loop_count = 0
366
+ while not succeeded:
367
+ self.all_originally_locked_doors_on_optimal_path = []
368
+ self.strategy_backward = []
369
+ self.drs = []
370
+ big_loop_count += 1
371
+ if big_loop_count > self.max_big_loop_count:
372
+ return False
373
+ self.keys_locations = {}
374
+ self.random_seeds["end_room"] = random.randint(0, 1000000)
375
+ random.seed(self.random_seeds["end_room"])
376
+ end_room = random.choice(list(self.room_name.keys()))
377
+ current_room = copy.deepcopy(end_room)
378
+ self.end_room = end_room
379
+ step_count = 0
380
+ while True:
381
+ if step_count == 0:
382
+ self.strategy_backward += [(current_room, current_room, "end_room")]
383
+ step_count += 1
384
+ # 2. Select a random previous room from the list of all rooms accessible from current room.
385
+ # Alex moves back in time by going to a randomly selected previous room in the maze:
386
+ accessible_rooms = self.list_of_all_currently_accessible_rooms(
387
+ current_room
388
+ )
389
+ if self.N_locked_doors==0:
390
+ start_room = accessible_rooms[
391
+ random.randint(0, len(accessible_rooms) - 1)
392
+ ][0]
393
+ self.start_room = start_room
394
+ self.strategy_backward += [(start_room, start_room, "start_room")]
395
+ succeeded = True
396
+ break
397
+ retry_count = 0
398
+ all_doors_on_path = []
399
+ while (
400
+ retry_count < self.max_retry_count and len(all_doors_on_path) == 0
401
+ ):
402
+ if len(accessible_rooms) != 0:
403
+ previous_room = accessible_rooms[
404
+ random.randint(0, len(accessible_rooms) - 1)
405
+ ][0]
406
+ # 3. Alex locks a randomly selected door on the way back to the previous room
407
+ # from all the blue doors it encounters:
408
+ all_doors_on_path = self.get_all_doors_on_path(
409
+ current_room, previous_room
410
+ )
411
+ if len(all_doors_on_path) == 0:
412
+ # need to ensure we choose a path that has at least one blue or green door
413
+ if self.verbose:
414
+ print(
415
+ f"no doors found between {current_room} and {previous_room} - retrying..."
416
+ )
417
+ retry_count += 1
418
+ if retry_count == self.max_retry_count:
419
+ self.maze = copy.deepcopy(self.maze_original)
420
+ self.doors = copy.deepcopy(self.doors_original)
421
+ self.keys_locations = copy.deepcopy(self.keys_locations_original)
422
+ break
423
+
424
+ cell1, cell2 = random.choice(all_doors_on_path)
425
+ self.strategy_backward += [(cell1, cell2, "unlock_door")]
426
+ self.drs.append((cell1, cell2, "closed and locked", None, True))
427
+ self.all_originally_locked_doors_on_optimal_path.append((cell1, cell2))
428
+ self.doors[(cell1, cell2)] = (
429
+ "closed and locked",
430
+ self.doors[(cell1, cell2)][1],
431
+ )
432
+ self.doors[(cell2, cell1)] = self.doors[(cell1, cell2)]
433
+ wall_r = 2 * cell1[0] + 1 + (cell2[0] - cell1[0])
434
+ wall_c = 2 * cell1[1] + 1 + (cell2[1] - cell1[1])
435
+ self.maze[wall_r, wall_c] = 2 # 2 is the value for locked doors
436
+ # 4. Alex then leaves the associated key to this locked door in the selected previous room:
437
+ self.keys_locations[self.doors[(cell1, cell2)][1]] = previous_room
438
+ self.strategy_backward += [
439
+ (
440
+ previous_room,
441
+ (cell1, cell2),
442
+ f"pick_up_key:{self.doors[(cell1, cell2)][1]}",
443
+ )
444
+ ]
445
+ current_room = copy.deepcopy(previous_room)
446
+ # 5. repeat the steps from 2 to 4 (while loop) until N keys are distributed and user goes to a final
447
+ # randomly accessible room
448
+ if len(self.keys_locations) == self.N_locked_doors:
449
+ accessible_rooms = self.list_of_all_currently_accessible_rooms(
450
+ current_room
451
+ )
452
+ if len(accessible_rooms) == 0:
453
+ start_room = current_room
454
+ else:
455
+ start_room = accessible_rooms.pop(
456
+ random.randint(0, len(accessible_rooms) - 1)
457
+ )[0]
458
+ self.start_room = start_room
459
+ self.strategy_backward += [(start_room, start_room, "start_room")]
460
+ succeeded = True
461
+ break
462
+
463
+ # no already locked doors should be traversed - the final room becomes the start room
464
+ # the process stops after N keys are distributed and user goes to a final randomly accessible room
465
+ if succeeded:
466
+ self.maze_original = copy.deepcopy(self.maze)
467
+ self.doors_original = copy.deepcopy(self.doors)
468
+ self.keys_locations_original = copy.deepcopy(self.keys_locations)
469
+ self.strategy_backward_original = copy.deepcopy(self.strategy_backward)
470
+ self.drs_set_3rd_item()
471
+ self.standardize_sub_problems_and_solutions()
472
+ self.did_succeed = True
473
+ return True
474
+ else:
475
+ return False
476
+
477
+ def drs_set_3rd_item(self):
478
+ # [(cell1, cell2, status = 'open | locked', is_on_optimal_path[bool], included_in_gt_or_not[bool]),...]
479
+ self.on_optimal_path_locked_doors_indices = []
480
+ optimal_path = self.find_shortest_path(self.start_room, self.end_room)
481
+ for i, dr in enumerate(self.drs):
482
+ # self.drs[i][3]-> is_on_optimal_path
483
+ is_on_optimal_path = dr[0] in optimal_path and dr[1] in optimal_path
484
+ self.drs[i] = (dr[0], dr[1], dr[2], is_on_optimal_path, dr[4])
485
+ if is_on_optimal_path:
486
+ self.on_optimal_path_locked_doors_indices.append(i)
487
+ return None
488
+
489
+ def list_of_all_currently_accessible_rooms(
490
+ self, current_room, previous_room=None, steps=0
491
+ ):
492
+ # consideriing the current room and the maze structure as well as status of all the doors
493
+ # return a list of all the rooms that are accessible from the current room
494
+ if previous_room is None:
495
+ self.accessible_rooms = []
496
+ adjacent_cells = list(self.connected_cells[current_room].keys())
497
+ for cell in adjacent_cells:
498
+ if cell == previous_room:
499
+ continue
500
+ if (current_room, cell) not in self.doors.keys() or self.doors[
501
+ (current_room, cell)
502
+ ][0] == "open":
503
+ self.accessible_rooms.append((cell, steps + 1))
504
+ self.list_of_all_currently_accessible_rooms(
505
+ cell, previous_room=current_room, steps=steps + 1
506
+ )
507
+ return self.accessible_rooms
508
+
509
+ def find_shortest_path(self, room_A, room_B, path=[]):
510
+
511
+ if room_A == room_B:
512
+ return path + [room_B]
513
+ adjacent_cells = [
514
+ cell
515
+ for cell in list(self.connected_cells[room_A].keys())
516
+ if cell not in path and cell != room_A
517
+ ]
518
+ for cell in adjacent_cells:
519
+ res = self.find_shortest_path(cell, room_B, path=path + [room_A])
520
+ if res is not None:
521
+ return res
522
+ return None
523
+
524
+ def get_all_doors_on_path(self, room_A, room_B):
525
+ if room_A == room_B:
526
+ return []
527
+ path = self.find_shortest_path(room_A, room_B)
528
+ if path is None:
529
+ return []
530
+ return [
531
+ (path[i], path[i + 1])
532
+ for i in range(len(path) - 1)
533
+ if (path[i], path[i + 1]) in self.doors.keys()
534
+ and self.doors[(path[i], path[i + 1])][0] == "open"
535
+ ]
536
+
537
+ def display_maze(self):
538
+ """Display the maze using Matplotlib."""
539
+ fig, ax = plt.subplots(figsize=(self.M / 2, self.N / 2))
540
+ # Create a custom colormap with red for locked doors
541
+ # create cmap to show black for walls (1 value), white for open space (0 value), and red for locked doors (2 value)
542
+ cmap = plt.cm.colors.ListedColormap(["white", "black", "red", "blue", "green"])
543
+ ax.imshow(self.maze, cmap=cmap, interpolation="nearest")
544
+ ax.set_xticks([]), ax.set_yticks([])
545
+ plt.show()
546
+
547
+ def save_maze(self):
548
+ # create the directory if it doesn't exist
549
+ os.makedirs(
550
+ f"generated_data/maze_{self.N}_{self.M}_{self.N_locked_doors}"
551
+ f"_{self.generate_sub_problems}",
552
+ exist_ok=True,
553
+ )
554
+
555
+ filename = (
556
+ f"generated_data/maze_{self.N}_{self.M}_{self.N_locked_doors}"
557
+ f"_{self.generate_sub_problems}/{self.random_seeds['problem_generation']}.pkl"
558
+ )
559
+ data = {}
560
+ data["world_parameters"] = {
561
+ "N": self.N,
562
+ "M": self.M,
563
+ "N_keys": len(self.keys_locations),
564
+ "N_locked_doors": self.N_locked_doors,
565
+ "rescue_agent": self.rescue_agent,
566
+ "victim": self.victim,
567
+ "random_seeds": self.random_seeds,
568
+ }
569
+
570
+ data.update(
571
+ {
572
+ "start_room": self.start_room,
573
+ "end_room": self.end_room,
574
+ "standardized_problem_solution": self.standardized_problem_solution_backward,
575
+ "sub_maze_configurations": self.sub_maze_configurations, # if any key values are ndarray, convert to list
576
+ "connected_cells": self.connected_cells,
577
+ "room_name": self.room_name,
578
+ }
579
+ )
580
+
581
+ pickle.dump(data, open(filename, "wb"))
582
+ return filename, None
583
+
584
+
585
+ def single_run(N, M, N_locked_doors, display_maze=False, verbose=False):
586
+ try:
587
+ print(f"Starting run with N: {N}, M: {M}, N_locked_doors: {N_locked_doors}")
588
+ succeeded = False
589
+ counter = 0
590
+
591
+ while not succeeded:
592
+ counter += 1
593
+ maze = MazeGenerator(
594
+ N=N,
595
+ M=M,
596
+ rescue_agent="Alex",
597
+ victim="Maggie",
598
+ max_big_loop_count=500,
599
+ max_retry_count=100,
600
+ N_locked_doors=N_locked_doors,
601
+ generate_sub_problems=True,
602
+ verbose=verbose,
603
+ )
604
+ maze.generate_maze_with_doors()
605
+ maze.generate_distributed_keys_rescue_positive_problem()
606
+ succeeded = maze.did_succeed
607
+
608
+ if counter > 100:
609
+ print(f"Failed to generate {N}, M: {M}, N_locked_doors: {N_locked_doors}")
610
+ break
611
+
612
+ if succeeded:
613
+ if display_maze:
614
+ maze.display_maze()
615
+
616
+ # Save the maze data
617
+ filename, maze_file = maze.save_maze()
618
+
619
+ if maze_file:
620
+ maze_id = os.path.splitext(os.path.basename(maze_file))[0]
621
+ maze_dir = os.path.dirname(maze_file)
622
+ plots_dir = os.path.join(maze_dir, "plots")
623
+ os.makedirs(plots_dir, exist_ok=True)
624
+
625
+ maze_loader = MazeLoader(maze_file, hide_coordinates=True)
626
+ plot_path = os.path.join(plots_dir, f"{maze_id}.png")
627
+ maze_loader.pretty_plot(save_path=plot_path)
628
+ print(f"Saved maze visualization to {plot_path}")
629
+
630
+ return (
631
+ f"run with N: {N}, M: {M}, N_locked_doors: {N_locked_doors} succeeded",
632
+ filename,
633
+ )
634
+ else:
635
+ return (
636
+ f"run with N: {N}, M: {M}, N_locked_doors: {N_locked_doors} maxed out retry count",
637
+ None,
638
+ )
639
+
640
+ except Exception as e:
641
+ print(traceback.print_exc())
642
+ raise Exception(
643
+ f"Run with N: {N}, M: {M}, N_locked_doors: {N_locked_doors} failed"
644
+ )
645
+
646
+
647
+ def run_maze_generation(NMs, num_instances_per_parameter_combination=1):
648
+ fs = []
649
+ generated_maze_files = []
650
+ with ThreadPoolExecutor(max_workers=60) as executor:
651
+ for i in range(num_instances_per_parameter_combination):
652
+ print(
653
+ f"Running instance {i+1} of {num_instances_per_parameter_combination}..."
654
+ )
655
+ for N, M, N_locked_doors in NMs:
656
+ fs.append(
657
+ executor.submit(
658
+ single_run,
659
+ N,
660
+ M,
661
+ N_locked_doors,
662
+ display_maze=False,
663
+ verbose=False,
664
+ )
665
+ )
666
+
667
+ for f in as_completed(fs):
668
+ if f.exception() is None:
669
+ res = f.result()
670
+ print(res[0])
671
+ if res[1] is not None:
672
+ generated_maze_files.append(res[1])
673
+
674
+ return generated_maze_files
675
+
676
+
677
+ if __name__ == "__main__":
678
+
679
+ NMs = [(j,j) for j in range(6, 22, 2)]
680
+
681
+ NMs = [(it[0], it[1], i) for it in NMs for i in range(9,11)]
682
+ print(NMs)
683
+ generated_maze_files = run_maze_generation(
684
+ NMs, num_instances_per_parameter_combination=1000
685
+ )
686
+ print(generated_maze_files)
687
+ # fix weird behavior you are seeing with 8,8,6 reduced key count to 1 for maze_8_8_6_0.5_0.0_True/745275.pkl
688
+
689
+ # cognetive load is constraints on key lock distributions
690
+ # can we introduce a "time pressure" on cognetive load
691
+ # starting with small problems and deeply understanding the behaviors
692
+ # constraint reduction behavior of the model - as we reduce the number of keys distributed
693
+ #