import random import numpy as np import matplotlib.pyplot as plt from collections import defaultdict import copy import json import pickle from math import floor, ceil import os from concurrent.futures import ThreadPoolExecutor, as_completed import traceback from maze_loader import MazeLoader from rooms import NameGenerator class MazeGenerator: """A class for generating mazes with locked doors and distributed keys. The maze is generated using Kruskal's algorithm and includes features like: - Locked doors requiring keys - Keys distributed throughout the maze - Sub-problems with reduced complexity """ def __init__( self, N, # number of rows M, # number of columns rescue_agent="Bob", # the name of the rescue agent victim="Alice", # the name of the victim max_big_loop_count=5, # retry logic parameter max_retry_count=10, # retry logic parameter N_locked_doors=2, # the number of locked doors in the maze for the most difficult sub-problem generate_sub_problems=True, # whether to generate sub-problems from the original problem (reduced N_locked_doors without changing the maze pattern) verbose=True, # whether to print the maze parameters random_seeds=None, # shuffle_room_names=False, shuffle_key_ids=False, ): # 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} if random_seeds is None: self.random_seeds = { "key_ids": random.randint(100, 2**32 - 1), "maze_generation": random.randint(100, 2**32 - 1), "door_distribution": random.randint(100, 2**32 - 1), "problem_generation": random.randint(100, 2**32 - 1), "end_room": random.randint(100, 2**32 - 1), "remove_key": random.randint(100, 2**32 - 1), } else: self.random_seeds = random_seeds self.name_generator = NameGenerator(N, M) self.N = N # Number of rows self.M = M # Number of columns self.rescue_agent = rescue_agent self.victim = victim self.max_big_loop_count = max_big_loop_count self.max_retry_count = max_retry_count self.N_locked_doors = N_locked_doors # the number of locked doors in the maze for the most difficult sub-problem self.generate_sub_problems = generate_sub_problems # whether to generate sub-problems from the original problem (N_locked_doors) self.verbose = verbose self.shuffle_key_ids = shuffle_key_ids self.parent = {} # Disjoint set for Kruskal's algorithm self.rank = {} # Rank for union-find self.edges = [] # List of possible edges self.maze = np.ones((2 * N + 1, 2 * M + 1)) # Initialize grid with walls self.connected_cells = defaultdict(dict) self.room_name = {} self.doors = {} # self.key_ids = #["0"*(6-len(str(i))) + f"{i}" for i in range(100000)] self.key_ids = [f"{i}" for i in range(1, 10000)][::-1] self.keys_locations = {} # self.random_room_name_pool = ["R" + "0"*(6-len(str(i))) + f"{i}" for i in range(100000)] # room_index_max = ceil((N * M) / 26) if N * M > 26 else 0 # self.random_room_name_pool = generate_letter_number_list(room_index_max) # print(len(self.random_room_name_pool), room_index_max) # if random_seeds is None: self.random_seeds.update( { f"remove_key_{i+1}": random.randint(100, 2**32 - 1) for i, _ in enumerate(range(self.N_locked_doors)) } ) self.did_succeed = False if verbose: self.print_maze_parameters() random.seed(self.random_seeds["key_ids"]) if self.shuffle_key_ids: random.shuffle(self.key_ids) def print_maze_parameters(self): """Print the current maze generation parameters.""" print("\033[93m" + "the random seeds are: " + "\033[0m", self.random_seeds) print("maze parameters are: ") print(f"N: {self.N}") print(f"M: {self.M}") print(f"rescue_agent: {self.rescue_agent}") print(f"victim: {self.victim}") print(f"max_big_loop_count: {self.max_big_loop_count}") print(f"max_retry_count: {self.max_retry_count}") print(f"N_locked_doors: {self.N_locked_doors}") print(f"generate_sub_problems: {self.generate_sub_problems}") def find(self, node): """Find the root of the set containing node (with path compression). This is used in the union function""" if self.parent[node] != node: self.parent[node] = self.find(self.parent[node]) return self.parent[node] def union(self, node1, node2): """Union by rank - used in kruskal's algorithm""" root1 = self.find(node1) root2 = self.find(node2) if root1 != root2: if self.rank[root1] > self.rank[root2]: self.parent[root2] = root1 elif self.rank[root1] < self.rank[root2]: self.parent[root1] = root2 else: self.parent[root2] = root1 self.rank[root1] += 1 return True return False def assign_room_name(self, cell): return self.name_generator.get_name(cell) def generate_edges(self): """Generate edges between adjacent cells.""" for r in range(self.N): for c in range(self.M): node = (r, c) self.parent[node] = node self.rank[node] = 0 if r < self.N - 1: # Vertical edge self.edges.append(((r, c), (r + 1, c))) if c < self.M - 1: # Horizontal edge self.edges.append(((r, c), (r, c + 1))) self.room_name[node] = self.assign_room_name(node) def generate_maze_with_doors(self): """Generate the maze using Kruskal's algorithm.""" if self.verbose: print("generating the maze with doors...") self.generate_edges() random.seed(self.random_seeds["maze_generation"]) random.shuffle(self.edges) # Shuffle edges for randomness random.seed(self.random_seeds["door_distribution"]) ps = [(random.random(), random.random()) for _ in range(len(self.edges))] for (cell1, cell2), p in zip(self.edges, ps): if self.union(cell1, cell2): # Connect disjoint sets # Convert lattice coordinates to maze coordinates wall_r = 2 * cell1[0] + 1 + (cell2[0] - cell1[0]) wall_c = 2 * cell1[1] + 1 + (cell2[1] - cell1[1]) self.maze[2 * cell1[0] + 1, 2 * cell1[1] + 1] = 0 # Mark cell as open self.maze[2 * cell2[0] + 1, 2 * cell2[1] + 1] = 0 # Mark cell as open self.maze[wall_r, wall_c] = 0 # Remove wall self.connected_cells[cell1][cell2] = 1 self.connected_cells[cell2][cell1] = 1 status = "open" self.maze[ wall_r, wall_c ] = 4 # 3 if status == 'closed but unlocked' else 4 self.doors[(cell1, cell2)] = (status, self.key_ids.pop()) self.doors[(cell2, cell1)] = self.doors[(cell1, cell2)] def flush_checkpoints(self, checkpoints, removed_key_count): while len(checkpoints) > 1: rooms_in_path = self.find_shortest_path(checkpoints[0], checkpoints[1]) if rooms_in_path is None: rooms_in_path = [] for sub_room in rooms_in_path[ :-1 ]: # we ensure we are not double counting the rooms self.standardized_problem_solution_backward[removed_key_count] += [ ("move_to", sub_room) ] checkpoints.pop(0) def standardize_sub_problems_and_solutions(self): # use the strategy backward to generate the standardized problem and solution in the final desired format self.standardized_problem_solution_backward = defaultdict(list) removed_key_count = 0 self.sub_maze_configurations = {} self.sub_problem_maze = copy.deepcopy(self.maze_original) self.sub_problem_doors = copy.deepcopy(self.doors_original) self.connected_cells = dict(self.connected_cells) number_of_unlocking_actions_required = ( len(self.strategy_backward_original) - 2 ) // 2 while removed_key_count <= (len(self.strategy_backward_original) - 2) // 2: checkpoints = [] for i, (room, context, action) in enumerate(self.strategy_backward): if action.split(":")[0] == "end_room": self.standardized_problem_solution_backward[removed_key_count] += [ ("rescue", self.victim) ] checkpoints.append(room) elif action.split(":")[0] == "unlock_door": checkpoints.append(room) checkpoints.append(context) self.flush_checkpoints(checkpoints, removed_key_count) self.standardized_problem_solution_backward[removed_key_count] += [ ("unlock_and_open_door_to", room) ] self.standardized_problem_solution_backward[removed_key_count] += [ ("use_key", self.doors[(room, context)][1]) ] elif action.split(":")[0] == "pick_up_key": checkpoints.append(room) self.flush_checkpoints(checkpoints, removed_key_count) self.standardized_problem_solution_backward[removed_key_count] += [ ("pick_up_key", action.split(":")[1]) ] elif action.split(":")[0] == "start_room": checkpoints.append(room) self.flush_checkpoints(checkpoints, removed_key_count) self.standardized_problem_solution_backward[removed_key_count] += [ ("start", room) ] self.flush_checkpoints(checkpoints, removed_key_count) self.sub_maze_configurations[removed_key_count] = { "maze": self.sub_problem_maze.astype(int).tolist(), "doors": copy.deepcopy(self.sub_problem_doors), "keys_locations": copy.deepcopy(self.keys_locations), "number_of_unlocking_actions_required": number_of_unlocking_actions_required, } # if the flag is not set, we stop the process after generating the first sub-problem (with N_locked_doors locked doors) if not self.generate_sub_problems: break removed_key_count += 1 if len(self.on_optimal_path_locked_doors_indices) == 0: break random.seed(self.random_seeds[f"remove_key_{removed_key_count}"]) # ss = random.randint(0, floor((len(self.strategy_backward) - 2) / 2) - 1) ss = self.on_optimal_path_locked_doors_indices.pop(0) cell1, cell2 = ( self.drs[ss][0], self.drs[ss][1], ) status = "open" self.sub_problem_doors[(cell1, cell2)] = ( status, self.sub_problem_doors[(cell1, cell2)][1], ) self.sub_problem_doors[(cell2, cell1)] = self.sub_problem_doors[ (cell1, cell2) ] # updating the maze and doors to reflect that wall_r = 2 * cell1[0] + 1 + (cell2[0] - cell1[0]) wall_c = 2 * cell1[1] + 1 + (cell2[1] - cell1[1]) self.sub_problem_maze[wall_r, wall_c] = 4 # don't need to change the key locations and can keep that as noise # we remove the locked door knowing that the backward strategy pattern is # inverse of ['start_room'] +['pick_up_key', 'unlock_door'] * N_locked_doors + ['end_room'] self.drs[ss] = ( self.drs[ss][0], self.drs[ss][1], "open", self.drs[ss][3], False, ) ( extra_removed_keys, number_of_unlocking_actions_required, ) = self.remove_redundant_steps_from_strategy_backward( ss ) # if the rooms associated with a removed locked door is not on the optimal path, we remove it removed_key_count += extra_removed_keys if not removed_key_count <= (len(self.strategy_backward_original) - 2) // 2: break def remove_redundant_steps_from_strategy_backward(self, ss): # prouning the ground truth to ensure optimality by tweaking the strategy backward """ get the list of all locked doors in the original backward strategy in the following format: drs = [(cell1, cell2, status = 'open | locked', is_on_optimal_path[bool], included_in_gt_or_not[bool]),...] when changing status of an item to open (as part of sub problem generation logic) set drs[s]['included_in_gt_or_not'] = False, check prevoius item (s = s-1) if drs[s]['is_on_optimal_path'] = False , set drs[s]['included_in_gt_or_not'] = False and set s = s-1 and do the check again if drs[s]['is_on_optimal_path'] = True, stop the process return the number of extra removed keys """ inds_to_drop = [] # drop the opened door from the strategy backward dr = self.drs[ss] for i, item in enumerate(self.strategy_backward): if (item[0] == dr[0] and item[1] == dr[1]) or ( item[0] == dr[1] and item[1] == dr[0] ): inds_to_drop.append(i) i = ss + 1 if i >= len(self.drs): self.strategy_backward = [ self.strategy_backward[i] for i in range(len(self.strategy_backward)) if i not in inds_to_drop and i - 1 not in inds_to_drop ] number_of_unlocking_actions_required = ( len(self.strategy_backward) - 2 ) // 2 return 0, number_of_unlocking_actions_required is_on_optimal_path = self.drs[i][3] extra_removed_keys = 0 while i < len(self.drs) and ((not is_on_optimal_path)): dr = self.drs[i] self.drs[i] = (dr[0], dr[1], dr[2], False, False) # drop the removed door from the ground truth from the strategy backward for j, item in enumerate(self.strategy_backward): if (item[0] == dr[0] and item[1] == dr[1]) or ( item[0] == dr[1] and item[1] == dr[0] ): inds_to_drop.append(j) extra_removed_keys += 1 i += 1 if i >= len(self.drs): break is_on_optimal_path = self.drs[i][3] # remove both unlock and pickup from the strategy backward for dropped doors self.strategy_backward = [ self.strategy_backward[i] for i in range(len(self.strategy_backward)) if i not in inds_to_drop and i - 1 not in inds_to_drop ] number_of_unlocking_actions_required = (len(self.strategy_backward) - 2) // 2 return extra_removed_keys, number_of_unlocking_actions_required def generate_distributed_keys_rescue_positive_problem(self): # positive means that the problem is solvable # there are locked doors between start_room and end_room # these locked doors have keys distributed throughout the maze # Alex needs to find the keys and open the doors on its path to rescue Maggie # Not all keys open all doors # circular dependency can exist: when the key to open a # locked door to room A is in a room B that is on the path to it has a locked door # but the key to open that locked door is in room A - # there is a circular dependency and it makes it impossible to rescue Maggie ### GENERATION PROCESS ######################################################### # We use a reverse back in time to build the problem configuration # We move back in time from the moment Maggie is rescued to the moment Alex starts the rescue # Initially all the rooms are unlocked ################################################################################ # 1. Pick a random room as the episode's final state (Maggie's location - Alex's final location): self.maze_original = copy.deepcopy(self.maze) self.doors_original = copy.deepcopy(self.doors) self.keys_locations_original = copy.deepcopy(self.keys_locations) self.random_seeds["problem_generation"] = random.randint(0, 1000000) random.seed(self.random_seeds["problem_generation"]) succeeded = False big_loop_count = 0 while not succeeded: self.all_originally_locked_doors_on_optimal_path = [] self.strategy_backward = [] self.drs = [] big_loop_count += 1 if big_loop_count > self.max_big_loop_count: return False self.keys_locations = {} self.random_seeds["end_room"] = random.randint(0, 1000000) random.seed(self.random_seeds["end_room"]) end_room = random.choice(list(self.room_name.keys())) current_room = copy.deepcopy(end_room) self.end_room = end_room step_count = 0 while True: if step_count == 0: self.strategy_backward += [(current_room, current_room, "end_room")] step_count += 1 # 2. Select a random previous room from the list of all rooms accessible from current room. # Alex moves back in time by going to a randomly selected previous room in the maze: accessible_rooms = self.list_of_all_currently_accessible_rooms( current_room ) if self.N_locked_doors==0: start_room = accessible_rooms[ random.randint(0, len(accessible_rooms) - 1) ][0] self.start_room = start_room self.strategy_backward += [(start_room, start_room, "start_room")] succeeded = True break retry_count = 0 all_doors_on_path = [] while ( retry_count < self.max_retry_count and len(all_doors_on_path) == 0 ): if len(accessible_rooms) != 0: previous_room = accessible_rooms[ random.randint(0, len(accessible_rooms) - 1) ][0] # 3. Alex locks a randomly selected door on the way back to the previous room # from all the blue doors it encounters: all_doors_on_path = self.get_all_doors_on_path( current_room, previous_room ) if len(all_doors_on_path) == 0: # need to ensure we choose a path that has at least one blue or green door if self.verbose: print( f"no doors found between {current_room} and {previous_room} - retrying..." ) retry_count += 1 if retry_count == self.max_retry_count: self.maze = copy.deepcopy(self.maze_original) self.doors = copy.deepcopy(self.doors_original) self.keys_locations = copy.deepcopy(self.keys_locations_original) break cell1, cell2 = random.choice(all_doors_on_path) self.strategy_backward += [(cell1, cell2, "unlock_door")] self.drs.append((cell1, cell2, "closed and locked", None, True)) self.all_originally_locked_doors_on_optimal_path.append((cell1, cell2)) self.doors[(cell1, cell2)] = ( "closed and locked", self.doors[(cell1, cell2)][1], ) self.doors[(cell2, cell1)] = self.doors[(cell1, cell2)] wall_r = 2 * cell1[0] + 1 + (cell2[0] - cell1[0]) wall_c = 2 * cell1[1] + 1 + (cell2[1] - cell1[1]) self.maze[wall_r, wall_c] = 2 # 2 is the value for locked doors # 4. Alex then leaves the associated key to this locked door in the selected previous room: self.keys_locations[self.doors[(cell1, cell2)][1]] = previous_room self.strategy_backward += [ ( previous_room, (cell1, cell2), f"pick_up_key:{self.doors[(cell1, cell2)][1]}", ) ] current_room = copy.deepcopy(previous_room) # 5. repeat the steps from 2 to 4 (while loop) until N keys are distributed and user goes to a final # randomly accessible room if len(self.keys_locations) == self.N_locked_doors: accessible_rooms = self.list_of_all_currently_accessible_rooms( current_room ) if len(accessible_rooms) == 0: start_room = current_room else: start_room = accessible_rooms.pop( random.randint(0, len(accessible_rooms) - 1) )[0] self.start_room = start_room self.strategy_backward += [(start_room, start_room, "start_room")] succeeded = True break # no already locked doors should be traversed - the final room becomes the start room # the process stops after N keys are distributed and user goes to a final randomly accessible room if succeeded: self.maze_original = copy.deepcopy(self.maze) self.doors_original = copy.deepcopy(self.doors) self.keys_locations_original = copy.deepcopy(self.keys_locations) self.strategy_backward_original = copy.deepcopy(self.strategy_backward) self.drs_set_3rd_item() self.standardize_sub_problems_and_solutions() self.did_succeed = True return True else: return False def drs_set_3rd_item(self): # [(cell1, cell2, status = 'open | locked', is_on_optimal_path[bool], included_in_gt_or_not[bool]),...] self.on_optimal_path_locked_doors_indices = [] optimal_path = self.find_shortest_path(self.start_room, self.end_room) for i, dr in enumerate(self.drs): # self.drs[i][3]-> is_on_optimal_path is_on_optimal_path = dr[0] in optimal_path and dr[1] in optimal_path self.drs[i] = (dr[0], dr[1], dr[2], is_on_optimal_path, dr[4]) if is_on_optimal_path: self.on_optimal_path_locked_doors_indices.append(i) return None def list_of_all_currently_accessible_rooms( self, current_room, previous_room=None, steps=0 ): # consideriing the current room and the maze structure as well as status of all the doors # return a list of all the rooms that are accessible from the current room if previous_room is None: self.accessible_rooms = [] adjacent_cells = list(self.connected_cells[current_room].keys()) for cell in adjacent_cells: if cell == previous_room: continue if (current_room, cell) not in self.doors.keys() or self.doors[ (current_room, cell) ][0] == "open": self.accessible_rooms.append((cell, steps + 1)) self.list_of_all_currently_accessible_rooms( cell, previous_room=current_room, steps=steps + 1 ) return self.accessible_rooms def find_shortest_path(self, room_A, room_B, path=[]): if room_A == room_B: return path + [room_B] adjacent_cells = [ cell for cell in list(self.connected_cells[room_A].keys()) if cell not in path and cell != room_A ] for cell in adjacent_cells: res = self.find_shortest_path(cell, room_B, path=path + [room_A]) if res is not None: return res return None def get_all_doors_on_path(self, room_A, room_B): if room_A == room_B: return [] path = self.find_shortest_path(room_A, room_B) if path is None: return [] return [ (path[i], path[i + 1]) for i in range(len(path) - 1) if (path[i], path[i + 1]) in self.doors.keys() and self.doors[(path[i], path[i + 1])][0] == "open" ] def display_maze(self): """Display the maze using Matplotlib.""" fig, ax = plt.subplots(figsize=(self.M / 2, self.N / 2)) # Create a custom colormap with red for locked doors # create cmap to show black for walls (1 value), white for open space (0 value), and red for locked doors (2 value) cmap = plt.cm.colors.ListedColormap(["white", "black", "red", "blue", "green"]) ax.imshow(self.maze, cmap=cmap, interpolation="nearest") ax.set_xticks([]), ax.set_yticks([]) plt.show() def save_maze(self): # create the directory if it doesn't exist os.makedirs( f"generated_data/maze_{self.N}_{self.M}_{self.N_locked_doors}" f"_{self.generate_sub_problems}", exist_ok=True, ) filename = ( f"generated_data/maze_{self.N}_{self.M}_{self.N_locked_doors}" f"_{self.generate_sub_problems}/{self.random_seeds['problem_generation']}.pkl" ) data = {} data["world_parameters"] = { "N": self.N, "M": self.M, "N_keys": len(self.keys_locations), "N_locked_doors": self.N_locked_doors, "rescue_agent": self.rescue_agent, "victim": self.victim, "random_seeds": self.random_seeds, } data.update( { "start_room": self.start_room, "end_room": self.end_room, "standardized_problem_solution": self.standardized_problem_solution_backward, "sub_maze_configurations": self.sub_maze_configurations, # if any key values are ndarray, convert to list "connected_cells": self.connected_cells, "room_name": self.room_name, } ) pickle.dump(data, open(filename, "wb")) return filename, None def single_run(N, M, N_locked_doors, display_maze=False, verbose=False): try: print(f"Starting run with N: {N}, M: {M}, N_locked_doors: {N_locked_doors}") succeeded = False counter = 0 while not succeeded: counter += 1 maze = MazeGenerator( N=N, M=M, rescue_agent="Alex", victim="Maggie", max_big_loop_count=500, max_retry_count=100, N_locked_doors=N_locked_doors, generate_sub_problems=True, verbose=verbose, ) maze.generate_maze_with_doors() maze.generate_distributed_keys_rescue_positive_problem() succeeded = maze.did_succeed if counter > 100: print(f"Failed to generate {N}, M: {M}, N_locked_doors: {N_locked_doors}") break if succeeded: if display_maze: maze.display_maze() # Save the maze data filename, maze_file = maze.save_maze() if maze_file: maze_id = os.path.splitext(os.path.basename(maze_file))[0] maze_dir = os.path.dirname(maze_file) plots_dir = os.path.join(maze_dir, "plots") os.makedirs(plots_dir, exist_ok=True) maze_loader = MazeLoader(maze_file, hide_coordinates=True) plot_path = os.path.join(plots_dir, f"{maze_id}.png") maze_loader.pretty_plot(save_path=plot_path) print(f"Saved maze visualization to {plot_path}") return ( f"run with N: {N}, M: {M}, N_locked_doors: {N_locked_doors} succeeded", filename, ) else: return ( f"run with N: {N}, M: {M}, N_locked_doors: {N_locked_doors} maxed out retry count", None, ) except Exception as e: print(traceback.print_exc()) raise Exception( f"Run with N: {N}, M: {M}, N_locked_doors: {N_locked_doors} failed" ) def run_maze_generation(NMs, num_instances_per_parameter_combination=1): fs = [] generated_maze_files = [] with ThreadPoolExecutor(max_workers=60) as executor: for i in range(num_instances_per_parameter_combination): print( f"Running instance {i+1} of {num_instances_per_parameter_combination}..." ) for N, M, N_locked_doors in NMs: fs.append( executor.submit( single_run, N, M, N_locked_doors, display_maze=False, verbose=False, ) ) for f in as_completed(fs): if f.exception() is None: res = f.result() print(res[0]) if res[1] is not None: generated_maze_files.append(res[1]) return generated_maze_files if __name__ == "__main__": NMs = [(j,j) for j in range(6, 22, 2)] NMs = [(it[0], it[1], i) for it in NMs for i in range(9,11)] print(NMs) generated_maze_files = run_maze_generation( NMs, num_instances_per_parameter_combination=1000 ) print(generated_maze_files) # 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 # cognetive load is constraints on key lock distributions # can we introduce a "time pressure" on cognetive load # starting with small problems and deeply understanding the behaviors # constraint reduction behavior of the model - as we reduce the number of keys distributed #