import networkx as nx import random import os import argparse import numpy def generate_maze(n, edge_prob): # Create a directed grid graph with random edge removal G = nx.DiGraph() for i in range(n*n): G.add_node(i) # Add edges with probability edge_prob for i in range(n): for j in range(n): node = i*n + j # # up # if i > 0 and random.random() < edge_prob: # G.add_edge(node, (i-1)*n + j) # G.add_edge((i-1)*n + j, node) # down if i < n-1 and random.random() < edge_prob: G.add_edge(node, (i+1)*n + j) G.add_edge((i+1)*n + j, node) # # left # if j > 0 and random.random() < edge_prob: # G.add_edge(node, i*n + j-1) # G.add_edge(i*n + j-1, node) # right if j < n-1 and random.random() < edge_prob: G.add_edge(node, i*n + j+1) G.add_edge(i*n + j+1, node) return G def print_grid(G, n, file=None): def write_line(text): if file is None: print(text, end="") else: file.write(text) for i in range(n-1): # Print row edges for j in range(n): write_line("+") if j < n-1 and G.has_edge(i*n + j, i*n + j+1): write_line("---") elif j < n-1: write_line(" ") write_line("\n") # Print column edges for j in range(n): if G.has_edge(i*n + j, (i+1)*n + j): write_line("|") else: write_line(" ") if j < n-1: write_line(" ") write_line("\n") # Print bottom border for j in range(n): write_line("+") if j < n-1 and G.has_edge((n-1)*n + j, (n-1)*n + j+1): write_line("---") elif j < n-1: write_line(" ") write_line("\n") def get_reachable_nodes(G, target_node): # Get the transitive closure of the graph TC = nx.transitive_closure(G) # Find the predecessors in the transitive closure (nodes that can reach the target_node) reachable_from = TC.predecessors(target_node) return list(reachable_from) def obtain_reachability(): reachability = {} pairs = 0 for node in maze_graph.nodes(): reachability[node] = get_reachable_nodes(maze_graph, node) pairs += len(reachability[node]) return reachability, pairs def random_walk(source_node, target_node): stack = [source_node] visited = [] # to eliminate cycles while stack != []: cur_node = stack.pop() visited.append(cur_node) if cur_node == target_node: return visited adj = list(maze_graph.successors(cur_node)) anc = list(reachability[target_node]) anc.append(target_node) remaining = [element for element in adj if element in anc and element not in visited] #if we want the path to contain cycles, we should remove "and element not in visited" if len(remaining) == 0: return random_walk(source_node, target_node) # for non-DAGs next_node = random.choice(remaining) stack.append(next_node) return visited def seq2act(path): actions = [] for i in range(1, len(path)): diff = path[i] - path[i-1] if diff == -n: actions.append('N') elif diff == n: actions.append('S') elif diff == -1: actions.append('W') elif diff == 1: actions.append('E') return actions def wall_directions(node): """Return the list of NESW directions that hit a wall from `node`. A direction is a "wall" when the adjacent in-grid cell exists but there is no edge to it in the maze graph (i.e. the move is illegal). """ i, j = divmod(node, n) dirs = [] # North if i > 0 and not maze_graph.has_edge(node, (i - 1) * n + j): dirs.append('N') # South if i < n - 1 and not maze_graph.has_edge(node, (i + 1) * n + j): dirs.append('S') # West if j > 0 and not maze_graph.has_edge(node, i * n + (j - 1)): dirs.append('W') # East if j < n - 1 and not maze_graph.has_edge(node, i * n + (j + 1)): dirs.append('E') return dirs def corrupt_one_token(path): """Turn a correct node path into a wrong (wall-hitting) action sequence. Takes the correct actions of `path` and replaces ONE move (at a random position, not necessarily the last) with an illegal direction that hits a wall from that move's starting cell. The remaining tokens are kept as-is. Returns the corrupted action list, or None if no position can be corrupted. """ actions = seq2act(path) if not actions: return None # actions[i] is the move taken from node path[i]; try positions in random # order until we find one that has a wall to bump into. idxs = list(range(len(actions))) random.shuffle(idxs) for i in idxs: walls = wall_directions(path[i]) # illegal dirs from path[i]; excludes the legal actions[i] if walls: d = random.choice(walls) return actions[:i] + [d] + actions[i + 1:] return None def select_task(tasks_config, is_train=True): """ Randomly select a task based on the configured percentages. For training: uses 'train' percentage from tasks_config For testing: uses 'test' percentage from tasks_config Returns the selected task ID. """ key = 'train' if is_train else 'test' percentages = [(task_id, config[key]) for task_id, config in tasks_config.items()] # Generate random number between 0 and 100 rand = random.random() * 100 cumsum = 0 for task_id, pct in percentages: cumsum += pct if rand < cumsum: return task_id # Fallback to the last task if rounding errors occur return percentages[-1][0] def create_dataset(i, tasks_config): train_set = [] test_set = [] train_num_per_pair = max(i,1) for target_node in range(num_nodes): cnt = 0 # to avoid some target not appear in training dataset for source_node in range(num_nodes): if source_node == target_node: continue if (data[source_node][target_node] == 1): if maze_graph.has_edge(source_node, target_node): task_id = select_task(tasks_config, is_train=True) if task_id == 'A': train_set.append(['A', source_node, target_node] + seq2act([source_node, target_node])) else: print(f"Error: Task {task_id} is not yet defined. Skipping training data generation for this entry.") for ii in range(train_num_per_pair): task_id = select_task(tasks_config, is_train=True) if task_id == 'A': train_set.append(['A', source_node, target_node] + seq2act(random_walk(source_node, target_node)) ) else: print(f"Error: Task {task_id} is not yet defined. Skipping training data generation for this entry.") if (data[source_node][target_node] == -1): task_id = select_task(tasks_config, is_train=False) if task_id == 'A': test_set.append(['A', source_node, target_node] + seq2act(random_walk(source_node, target_node))) else: print(f"Error: Task {task_id} is not yet defined. Skipping test data generation for this entry.") return train_set, test_set def add_x(train_set, test_set, tasks_config): cnt = 0 for target_node in range(num_nodes): for source_node in range(num_nodes): if source_node == target_node: continue if source_node not in reachability[target_node]: cnt += 1 prob_in_test = len(test_set) / cnt * 0.2 prob_in_train = min(len(train_set) / cnt * 0.2, 1 - prob_in_test) train_repeat = max(int(len(train_set) / cnt * 0.15 / prob_in_train), 1) print(prob_in_train, prob_in_test, train_repeat) for target_node in range(num_nodes): for source_node in range(num_nodes): if source_node == target_node: continue if source_node not in reachability[target_node]: coin = random.random() if coin < prob_in_train: for _ in range(train_repeat): task_id = select_task(tasks_config, is_train=True) if task_id == 'A': train_set.append(['A', source_node, target_node, 'x']) else: print(f"Error: Task {task_id} is not yet defined. Skipping training data generation for this entry.") elif coin > 1 - prob_in_test: task_id = select_task(tasks_config, is_train=False) if task_id == 'A': test_set.append(['A', source_node, target_node, 'x']) else: print(f"Error: Task {task_id} is not yet defined. Skipping test data generation for this entry.") return train_set, test_set def add_wrong_paths(train_set, test_set, tasks_config, wrong_ratio): """Append wall-hitting wrong paths to the datasets. Each wrong path is built from a CORRECT path (source -> target) by replacing ONE move token (at a random position, not necessarily the last) with an illegal direction that hits a wall, then appending 'x' at the end. Format: ['A', source, target, , 'x']. During training only the final 'x' token is supervised (see train_maze.py / get_batch); every other token is masked out of the loss, so the model is not taught to imitate the wrong trajectory and must inspect the whole sequence to flag that a wall was hit. """ if wrong_ratio <= 0: return train_set, test_set num_train_wrong = int(len(train_set) * wrong_ratio) num_test_wrong = int(len(test_set) * wrong_ratio) # Collect reachable (source, target) pairs, split like the correct data. train_pairs = [] test_pairs = [] for target_node in range(num_nodes): for source_node in range(num_nodes): if source_node == target_node: continue if source_node in reachability[target_node]: if data[source_node][target_node] == 1: train_pairs.append((source_node, target_node)) elif data[source_node][target_node] == -1: test_pairs.append((source_node, target_node)) def gen_wrong(pairs, count, is_train): out = [] if not pairs or count <= 0: return out attempts = 0 max_attempts = count * 50 + 100 while len(out) < count and attempts < max_attempts: attempts += 1 source_node, target_node = random.choice(pairs) path = random_walk(source_node, target_node) if not path or len(path) < 2: continue corrupted = corrupt_one_token(path) if corrupted is None: continue task_id = select_task(tasks_config, is_train=is_train) if task_id != 'A': continue out.append(['A', source_node, target_node] + corrupted + ['x']) return out train_wrong = gen_wrong(train_pairs, num_train_wrong, True) test_wrong = gen_wrong(test_pairs, num_test_wrong, False) print(f'Added {len(train_wrong)} wrong (wall-hit) paths to train, {len(test_wrong)} to test.') return train_set + train_wrong, test_set + test_wrong def obtain_stats(dataset): max_len = 0 pairs = set() for data in dataset: max_len = max(max_len, len(data)) pairs.add((data[0],data[-1])) len_stats = [0]*(max_len + 1) for data in dataset: length = len(data) len_stats[length] += 1 print('number of source target pairs:', len(pairs)) for ii in range(3, len(len_stats)): print(f'There are {len_stats[ii]} paths with length {ii-3}') def format_data(data): # Format: task_id source target [remaining_tokens] return ' '.join(str(token) for token in data) + '\n' def write_dataset(dataset, file_name): with open(file_name, "w") as file: for data in dataset: file.write(format_data(data)) def parse_tasks(tasks_str): """ Parse task specification string into a dictionary. Format: "TaskID:train_percent:test_percent,TaskID:train_percent:test_percent,..." Example: "A:50:50,B:30:30,C:20:20" Returns: {"A": {"train": 50, "test": 50}, "B": {"train": 30, "test": 30}, ...} Validates that all training percentages sum to 100% and all test percentages sum to 100%. """ tasks = {} for task_spec in tasks_str.split(','): parts = task_spec.strip().split(':') if len(parts) != 3: raise ValueError(f"Invalid task specification: {task_spec}. Expected format: TaskID:train_percent:test_percent") task_id, train_pct, test_pct = parts[0].strip(), int(parts[1].strip()), int(parts[2].strip()) if task_id in tasks: raise ValueError(f"Duplicate task ID: {task_id}") tasks[task_id] = {"train": train_pct, "test": test_pct} # Validate that percentages sum to 100% total_train = sum(config["train"] for config in tasks.values()) total_test = sum(config["test"] for config in tasks.values()) if total_train != 100: raise ValueError(f"Training task percentages must sum to 100%, but got {total_train}%") if total_test != 100: raise ValueError(f"Test task percentages must sum to 100%, but got {total_test}%") return tasks if __name__ == "__main__": parser = argparse.ArgumentParser(description='Generate a maze based on the given parameters.') parser.add_argument('--grid_size', type=int, default=10, help='Size of the grid (n x n)') parser.add_argument('--edge_prob', type=float, default=0.6, help='Probability to keep an edge in the grid graph') parser.add_argument('--chance_in_train', type=float, default=0.5, help='Chance of a pair being in the training set') parser.add_argument('--num_of_paths', type=int, default=20, help='Number of paths per pair nodes in training dataset') parser.add_argument('--wrong_ratio', type=float, default=0.0, help='Fraction of extra wall-hitting wrong paths to add, relative to the ' 'number of correct paths (e.g. 0.2 = +20%%). Each wrong path ends in ' 'an illegal move + "x"; only the "x" step is supervised during training. ' 'Default 0.0 (disabled).') # Multi-task specification: comma-separated task identifiers with their train/test percentages # Format: "TaskID:train_percent:test_percent,TaskID:train_percent:test_percent,..." # Example: "A:100:100" or "A:50:50,B:30:30,C:20:20" # Default is Task A (pathfinding) with 100% in both train and test datasets parser.add_argument('--tasks', type=str, default='A:100:100', help='Task identifiers with percentages. Format: "TaskID:train_pct:test_pct,TaskID:train_pct:test_pct,..." (default: A:100:100)') args = parser.parse_args() # Parse task specifications tasks_config = parse_tasks(args.tasks) n = args.grid_size edge_prob = args.edge_prob num_nodes = n * n chance_in_train = args.chance_in_train num_of_paths = args.num_of_paths maze_graph = generate_maze(n, edge_prob) folder_name = os.path.join(os.path.dirname(__file__), f'{num_nodes}') if not os.path.exists(folder_name): os.makedirs(folder_name) # Save grid visualization to file grid_file_path = os.path.join(folder_name, f'maze_{n}_{edge_prob}_{num_of_paths}.txt') with open(grid_file_path, 'w') as f: print_grid(maze_graph, n, file=f) print_grid(maze_graph, n) reachability, feasible_pairs = obtain_reachability() data = numpy.zeros([num_nodes,num_nodes]) for target_node in range(num_nodes): cnt = 0 # to avoid some target not appear in training dataset for source_node in range(num_nodes): if source_node == target_node: continue if source_node in reachability[target_node]: if (maze_graph.has_edge(source_node, target_node)) or random.random() < chance_in_train or cnt < 1: data[source_node][target_node] = 1 cnt += 1 else: data[source_node][target_node] = -1 train_set, test_set = create_dataset(num_of_paths, tasks_config) train_set, test_set = add_wrong_paths(train_set, test_set, tasks_config, args.wrong_ratio) obtain_stats(train_set) print('number of source target pairs:', len(test_set)) write_dataset(train_set, os.path.join(folder_name, f'train_{num_of_paths}.txt')) write_dataset(test_set, os.path.join(folder_name, f'test.txt')) nx.write_graphml(maze_graph, os.path.join(folder_name, f'maze_graph.graphml'))