WorldModelForMaze / data /maze /create_multitask_maze.py
Kalso42's picture
Upload folder using huggingface_hub
34e468d verified
Raw
History Blame Contribute Delete
46.9 kB
import networkx as nx
import random
import os
import sys
import argparse
import numpy
import math
from tqdm import tqdm
# Ensure project root is importable when running this script directly
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', '..')))
from cli_utils import parse_count, format_count, parse_task_distribution
# Default: 10 lowercase letters for node labels (can be overridden via --num_labels)
NODE_LABELS = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
def make_label_list(num_labels):
"""Generate a list of label strings for the given count.
Up to 26: single lowercase letters (a-z).
Above 26: l0, l1, l2, ... (prefixed to avoid collision with directions/tasks).
"""
if num_labels <= 26:
return [chr(ord('a') + i) for i in range(num_labels)]
else:
return [f'l{i}' for i in range(num_labels)]
def generate_maze(n, edge_prob):
# Create a directed grid graph with random edge removal
G = nx.DiGraph()
for i in range(n * n):
# Assign a random label from NODE_LABELS to each node
label = random.choice(NODE_LABELS)
G.add_node(i, label=label)
# 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 and node labels (shifted one position to the right)
# First, print the edge and leading space
for j in range(n):
if G.has_edge(i * n + j, (i + 1) * n + j):
write_line("|")
else:
write_line(" ")
# Print label with spacing
# Print label of node (i, j) in the current cell (shifted right in the output)
label = G.nodes[i * n + j]['label']
write_line(f"{label} ")
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")
# Print labels for the last row nodes
for j in range(n):
# Print label of node (n-1, j) below the border
label = G.nodes[(n - 1) * n + j]['label']
write_line(f" {label} ")
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, allow_cycles=False):
"""Generate a random walk from source_node to target_node.
Args:
source_node: Starting node
target_node: Target node
allow_cycles: If False (default), path is acyclic. If True, path can contain cycles.
Returns:
List of nodes in the path, or empty list if no path found
"""
stack = [source_node]
visited = [] # to track visited nodes for acyclic constraint
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)
if allow_cycles:
# Allow cycles: only check if node is reachable to target
remaining = [element for element in adj if element in anc]
else:
# Acyclic: check both reachability and no previous visits
remaining = [element for element in adj if element in anc and element not in visited]
if len(remaining) == 0:
return [] # no path found from this start/target
next_node = random.choice(remaining)
stack.append(next_node)
return visited
def random_walk_ss(source_node, num_steps):
"""Generate a single-source random walk of a fixed number of steps.
Args:
source_node: Starting node
num_steps: Number of steps to take
Returns:
List of nodes in the path
"""
path = [source_node]
current = source_node
for _ in range(num_steps):
neighbors = list(maze_graph.successors(current))
if not neighbors:
break
current = random.choice(neighbors)
path.append(current)
return path
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 seq2turn(path, start_orientation='E'):
"""Convert an absolute direction path to relative turns.
Each output token both turns and advances one step:
- F: keep facing direction and move forward
- L: turn left then move
- R: turn right then move
- T: turn around then move
"""
absolute_actions = seq2act(path)
turns = []
left_of = {'N': 'W', 'W': 'S', 'S': 'E', 'E': 'N'}
right_of = {v: k for k, v in left_of.items()}
opposite_of = {'N': 'S', 'S': 'N', 'E': 'W', 'W': 'E'}
orientation = start_orientation
for action in absolute_actions:
if action == orientation:
turns.append('F')
elif action == left_of[orientation]:
turns.append('L')
elif action == right_of[orientation]:
turns.append('R')
elif action == opposite_of[orientation]:
turns.append('T')
else:
# Should not happen if the grid uses only NESW moves
continue
orientation = action
return turns
def random_walk_with_cycles(start_node, walk_length):
path = [start_node]
current = start_node
for _ in range(walk_length):
neighbors = list(maze_graph.successors(current))
if not neighbors:
break
current = random.choice(neighbors)
path.append(current)
return path
def shortest_path_to_label(source_node, target_label):
best_path = None
best_len = None
best_target = None
for node_id, attrs in maze_graph.nodes(data=True):
if attrs.get('label') != target_label:
continue
if node_id == source_node:
continue
if source_node not in reachability.get(node_id, []):
continue
try:
path = nx.shortest_path(maze_graph, source_node, node_id)
except nx.NetworkXNoPath:
continue
path_len = len(path)
if best_len is None or path_len < best_len or (path_len == best_len and node_id < best_target):
best_len = path_len
best_path = path
best_target = node_id
return best_path
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 _generate_one_entry(tasks_config, is_train):
"""Generate a single multitask data entry. Returns None on failure or unknown task."""
task_id = select_task(tasks_config, is_train=is_train)
if task_id == 'A':
return create_data_entry_taskA(is_train=is_train)
elif task_id == 'B':
return create_data_entry_taskB(is_train=is_train)
elif task_id == 'C':
return create_data_entry_taskC(is_train=is_train)
elif task_id == 'D':
return create_data_entry_taskD(is_train=is_train)
elif task_id == 'E':
return create_data_entry_taskE(is_train=is_train)
elif task_id == 'F':
return create_data_entry_taskF(is_train=is_train)
elif task_id == 'G':
return create_data_entry_taskG(is_train=is_train)
elif task_id == 'H':
return create_data_entry_taskH(is_train=is_train)
elif task_id == 'I':
return create_data_entry_taskI(is_train=is_train)
else:
print(f"Warning: Unknown task ID '{task_id}'. Skipping this entry.")
return None
def _worker_init(seed_base):
"""Reseed RNGs in each worker so processes produce independent streams."""
pid = os.getpid()
random.seed(seed_base + pid)
numpy.random.seed((seed_base + pid) % (2 ** 31))
def _worker_generate_batch(args_tuple):
"""Worker entry point: generate `count` entries in this process."""
count, tasks_config, is_train = args_tuple
out = []
for _ in range(count):
entry = _generate_one_entry(tasks_config, is_train)
if entry is not None:
out.append(entry)
return out
def create_multitask_dataset(num_of_data, tasks_config, is_train=True):
"""
Generate a multitask dataset with multiple task types.
Args:
num_of_data: Number of data entries to generate
tasks_config: Dictionary with task configurations and percentages
is_train: If True, generate training data; if False, generate test data
Returns:
dataset: List of data entries for the specified tasks
"""
# Parallel path: split work across processes (fork inherits maze_graph etc.)
nw = globals().get('num_workers', 1)
desc = f"Generating {'train' if is_train else 'test'} data"
if nw and nw > 1 and num_of_data > 0:
import multiprocessing as mp
import time
# Use many small batches so the progress bar updates smoothly.
batch_size = max(1, min(1000, math.ceil(num_of_data / (nw * 100))))
batches = []
remaining = num_of_data
while remaining > 0:
c = min(batch_size, remaining)
batches.append((c, tasks_config, is_train))
remaining -= c
seed_base = int(time.time()) + (0 if is_train else 10 ** 6)
ctx = mp.get_context('fork')
dataset = []
with ctx.Pool(processes=nw,
initializer=_worker_init,
initargs=(seed_base,)) as pool:
with tqdm(total=num_of_data, desc=desc) as pbar:
for r in pool.imap_unordered(_worker_generate_batch, batches):
dataset.extend(r)
pbar.update(len(r))
return dataset
# Serial path (original behavior)
dataset = []
for _ in tqdm(range(num_of_data), desc=desc):
data_entry = _generate_one_entry(tasks_config, is_train)
if data_entry is not None:
dataset.append(data_entry)
return dataset
def create_data_entry_taskA(is_train=True):
"""
Generate one Task A (pathfinding) data entry.
Randomly samples a reachable source-target pair that belongs to the requested split
and returns: ['A', source_node, target_node, <actions...>].
"""
while True:
if path_type_tag == 'RWs':
# Single Source (Taxi routing style): Pick a start, walk random steps, find end
source_node = random.randrange(num_nodes)
num_steps = random.randint(5, num_nodes)
path = random_walk_ss(source_node, num_steps)
if not path or len(path) < 2:
continue
target_node = path[-1]
else:
# Goal-oriented: Pick start and end first
source_node = random.randrange(num_nodes)
target_node = random.randrange(num_nodes)
if source_node == target_node:
continue
# Ensure the target is reachable from the source to avoid dead walks
if source_node not in reachability.get(target_node, []):
continue
label = data[source_node][target_node]
if is_train and label != 1:
continue
if (not is_train) and label != -1:
continue
if path_type_tag != 'RWs':
path = random_walk(source_node, target_node, allow_cycles=allow_cycles)
if not path:
continue
actions = seq2act(path)
# Optional minimum path length filter
if min_path_len > 0 and len(actions) < min_path_len:
continue
# for both training and test data, needs to return full format with answer part, this is needed to generate validation data during training
return ['A', source_node, target_node, ':'] + actions
def create_data_entry_taskC(is_train=True):
"""Generate one Task C entry (turn-based pathfinding).
Uses the same reachable-pair sampling as Task A, but encodes the
path with relative turns assuming the agent starts facing East.
Output format: ['C', source_node, target_node, ':', <turns...>] by default.
When cl_mode is True, append the node label after every L/R turn.
"""
while True:
if path_type_tag == 'RWs':
# Single Source logic for Task C
source_node = random.randrange(num_nodes)
num_steps = random.randint(5, num_nodes)
path = random_walk_ss(source_node, num_steps)
if not path or len(path) < 2:
continue
target_node = path[-1]
else:
source_node = random.randrange(num_nodes)
target_node = random.randrange(num_nodes)
if source_node == target_node:
continue
if source_node not in reachability.get(target_node, []):
continue
label = data[source_node][target_node]
if is_train and label != 1:
continue
if (not is_train) and label != -1:
continue
if path_type_tag != 'RWs':
path = random_walk(source_node, target_node, allow_cycles=allow_cycles)
if not path:
continue
turn_actions = seq2turn(path, start_orientation='E')
tokens = ['C', source_node, target_node, ':']
for step_idx, turn in enumerate(turn_actions):
tokens.append(turn)
if cl_mode and turn in ['L', 'R']:
node_id = path[step_idx]
tokens.append(maze_graph.nodes[node_id]['label'])
return tokens
def create_data_entry_taskD(is_train=True):
"""Generate one Task D entry (pathfinding to a target label).
Input provides a source node and a target label. The answer is a shortest
path (directions) to the nearest node with that label.
Format: ['D', source_node, target_label, ':', <directions...>]
"""
while True:
source_node = random.randrange(num_nodes)
target_label = random.choice(NODE_LABELS)
path = shortest_path_to_label(source_node, target_label)
if not path:
continue
actions = seq2act(path)
if not actions:
continue
return ['D', source_node, target_label, ':'] + actions
def create_data_entry_taskE(is_train=True):
"""
Task E (pathfinding with label observations).
- Only split segments when the direction changes (i.e., at turns).
- For each straight segment, let end_label be the label at the last node of this segment
(i.e., the turning node label, or the final node label if path ends).
- In that segment, keep ONLY the positions whose label == end_label.
Emit (dir, end_label) once for each kept position (so you may repeat the same pair).
Format: ['E', source_node, target_node, ':', dir1, lab1, dir2, lab2, ...]
"""
while True:
if path_type_tag == 'RWs':
# Single Source (Taxi routing style): Pick a start, walk random steps, find end
source_node = random.randrange(num_nodes)
num_steps = random.randint(5, num_nodes)
path = random_walk_ss(source_node, num_steps)
if not path or len(path) < 2:
continue
target_node = path[-1]
else:
# Goal-oriented: Pick start and end first
source_node = random.randrange(num_nodes)
target_node = random.randrange(num_nodes)
if source_node == target_node:
continue
if source_node not in reachability.get(target_node, []):
continue
path = random_walk(source_node, target_node)
if not path or len(path) < 2:
continue
y = data[source_node][target_node]
if is_train and y != 1:
continue
if (not is_train) and y != -1:
continue
actions = seq2act(path) # len(actions) == len(path)-1
if not actions:
continue
# Optional minimum path length filter
if min_path_len > 0 and len(actions) < min_path_len:
continue
# ---- 1) split only by turns (direction changes) ----
tokens = ['E', source_node, target_node, ':']
run_dir = actions[0]
run_labels = [] # labels of nodes visited during this run (node after each step)
for step_idx, direction in enumerate(actions):
node_id = path[step_idx + 1]
lab = maze_graph.nodes[node_id]['label']
# direction changed => flush previous run, then start new
if direction != run_dir:
# flush old run
end_label = run_labels[-1]
cnt = sum(1 for x in run_labels if x == end_label)
for _ in range(cnt):
tokens.append(run_dir)
tokens.append(end_label)
# start new run
run_dir = direction
run_labels = [lab]
else:
# still same direction => accumulate
run_labels.append(lab)
# ---- 2) flush last run ----
end_label = run_labels[-1]
cnt = sum(1 for x in run_labels if x == end_label)
for _ in range(cnt):
tokens.append(run_dir)
tokens.append(end_label)
return tokens
def create_data_entry_taskF(is_train=True):
"""Generate one Task F entry (label-based target identification).
Format: ['F', start_label, <directions...>, ':', target_label]
The start node is implicit: any node with the given start_label is valid.
"""
start_label = random.choice(NODE_LABELS)
candidates = [node for node, attrs in maze_graph.nodes(data=True) if attrs.get('label') == start_label]
if not candidates:
return None
start_node = random.choice(candidates)
max_walk_len = max(1, 4 * n)
walk_length = random.randint(1, max_walk_len)
path = random_walk_with_cycles(start_node, walk_length)
end_node = path[-1]
directions = seq2act(path)
target_label = maze_graph.nodes[end_node]['label']
return ['F', start_label] + directions + [':', target_label]
def create_data_entry_taskG(is_train=True):
"""Generate one Task G entry (reachability choice with path as CoT).
Format: ['G', s1, s2, t1, t2, ':', source, target, <directions...>]
Exactly one of (s1->t1) or (s2->t2) is reachable.
"""
while True:
source1 = random.randrange(num_nodes)
source2 = random.randrange(num_nodes)
target1 = random.randrange(num_nodes)
target2 = random.randrange(num_nodes)
if source1 == target1 or source2 == target2:
continue
reachable1 = source1 in reachability.get(target1, [])
reachable2 = source2 in reachability.get(target2, [])
if reachable1 == reachable2:
continue
if reachable1:
source_node, target_node = source1, target1
else:
source_node, target_node = source2, target2
path = random_walk(source_node, target_node)
if not path or len(path) < 2:
continue
actions = seq2act(path)
return ['G', source1, source2, target1, target2, ':', source_node, target_node] + actions
def create_data_entry_taskH(is_train=True):
"""Task H: Relative clockwise-index path encoding.
The walker starts at source facing East. At each step, feasible edges
are enumerated clockwise starting from the first direction after the
current facing direction. The output is the 1-based index of the
chosen direction among the feasible edges.
Format: ['H', source, target, ':', idx1, idx2, ...]
where each idx is a string '1'-'4'.
"""
# Clockwise scan: starting from the current facing direction
CLOCKWISE_SCAN = {
'N': ['N', 'E', 'S', 'W'],
'E': ['E', 'S', 'W', 'N'],
'S': ['S', 'W', 'N', 'E'],
'W': ['W', 'N', 'E', 'S'],
}
DELTA = {'N': -n, 'S': n, 'E': 1, 'W': -1}
while True:
if path_type_tag == 'RWs':
source_node = random.randrange(num_nodes)
num_steps = random.randint(5, num_nodes)
path = random_walk_ss(source_node, num_steps)
if not path or len(path) < 2:
continue
target_node = path[-1]
else:
source_node = random.randrange(num_nodes)
target_node = random.randrange(num_nodes)
if source_node == target_node:
continue
if source_node not in reachability.get(target_node, []):
continue
label = data[source_node][target_node]
if is_train and label != 1:
continue
if (not is_train) and label != -1:
continue
if path_type_tag != 'RWs':
path = random_walk(source_node, target_node, allow_cycles=allow_cycles)
if not path or len(path) < 2:
continue
actions = seq2act(path)
if not actions:
continue
if min_path_len > 0 and len(actions) < min_path_len:
continue
# Convert absolute directions to relative clockwise indices
facing = 'E'
tokens = ['H', source_node, target_node, ':']
valid = True
for step_idx, action in enumerate(actions):
current_node = path[step_idx]
scan_order = CLOCKWISE_SCAN[facing]
feasible = []
for d in scan_order:
neighbor = current_node + DELTA[d]
if 0 <= neighbor < num_nodes and maze_graph.has_edge(current_node, neighbor):
feasible.append(d)
if action not in feasible:
valid = False
break
idx = feasible.index(action) + 1 # 1-based
tokens.append(str(idx))
facing = action # update facing to direction actually moved
if not valid:
continue
return tokens
def create_data_entry_taskI(is_train=True):
"""Task I: Absolute clockwise-index path encoding (fixed North reference).
Like Task H, but feasible edges are always enumerated clockwise starting
from a FIXED North reference (N, E, S, W) regardless of the direction the
walker just moved. The walker therefore does NOT track a facing direction:
its state is the current node alone. The output is the 1-based index of the
chosen direction among the node's feasible edges in this fixed N->E->S->W
order.
This isolates "state-conditioned retrieval" (must read the node's feasible
edge set to emit/decode the index) from "facing tracking": compared to
Task A it adds only retrieval; compared to Task H it removes facing tracking.
Format: ['I', source, target, ':', idx1, idx2, ...]
where each idx is a string '1'-'4'.
"""
# Fixed clockwise scan order from North (no dependence on facing)
FIXED_SCAN = ['N', 'E', 'S', 'W']
DELTA = {'N': -n, 'S': n, 'E': 1, 'W': -1}
while True:
if path_type_tag == 'RWs':
source_node = random.randrange(num_nodes)
num_steps = random.randint(5, num_nodes)
path = random_walk_ss(source_node, num_steps)
if not path or len(path) < 2:
continue
target_node = path[-1]
else:
source_node = random.randrange(num_nodes)
target_node = random.randrange(num_nodes)
if source_node == target_node:
continue
if source_node not in reachability.get(target_node, []):
continue
label = data[source_node][target_node]
if is_train and label != 1:
continue
if (not is_train) and label != -1:
continue
if path_type_tag != 'RWs':
path = random_walk(source_node, target_node, allow_cycles=allow_cycles)
if not path or len(path) < 2:
continue
actions = seq2act(path)
if not actions:
continue
if min_path_len > 0 and len(actions) < min_path_len:
continue
# Convert absolute directions to fixed-North clockwise indices
tokens = ['I', source_node, target_node, ':']
valid = True
for step_idx, action in enumerate(actions):
current_node = path[step_idx]
feasible = []
for d in FIXED_SCAN:
neighbor = current_node + DELTA[d]
if 0 <= neighbor < num_nodes and maze_graph.has_edge(current_node, neighbor):
feasible.append(d)
if action not in feasible:
valid = False
break
idx = feasible.index(action) + 1 # 1-based
tokens.append(str(idx))
# NOTE: no facing update — reference stays fixed at North.
if not valid:
continue
return tokens
# Add 'x' entries for unreachable pairs, only used if we allow unreachable pairs in the dataset, and currently it is not used.
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 create_data_entry_taskB(is_train=True):
"""Generate one Task B entry (target identification).
Training format: B <start> <directions...> : <end_label> <E> <S> <W> <N>
Test format: B <start> <directions...>
Walk length is random up to 4 * grid_size (n).
"""
def get_neighbor_labels(node):
neighbors_order = [(1, 'E'), (n, 'S'), (-1, 'W'), (-n, 'N')]
labels = []
for offset, _ in neighbors_order:
neighbor_id = node + offset
if maze_graph.has_edge(node, neighbor_id):
labels.append(maze_graph.nodes[neighbor_id]['label'])
else:
labels.append('/')
return labels
start_node = random.randint(0, num_nodes - 1)
max_walk_len = max(1, 4 * n)
walk_length = random.randint(1, max_walk_len)
path = random_walk_with_cycles(start_node, walk_length)
end_node = path[-1]
directions = seq2act(path)
end_label = maze_graph.nodes[end_node]['label']
neighbor_labels = get_neighbor_labels(end_node)
# for both training and test data, return answer without target node id (only label + neighbors)
return ['B', start_node] + directions + [':', end_label] + neighbor_labels
def obtain_stats(dataset, is_train=True):
"""
Compute and print statistics for a multitask dataset.
Args:
dataset: List of data entries (can be mixed tasks)
is_train: If True, label output as training data; else as test data
"""
dataset_type = "Training" if is_train else "Test"
print(f'\n{dataset_type} Dataset Statistics:')
print('=' * 80)
# Separate entries by task
taskA_entries = [entry for entry in dataset if entry[0] == 'A']
taskB_entries = [entry for entry in dataset if entry[0] == 'B']
taskC_entries = [entry for entry in dataset if entry[0] == 'C']
taskD_entries = [entry for entry in dataset if entry[0] == 'D']
taskE_entries = [entry for entry in dataset if entry[0] == 'E']
taskF_entries = [entry for entry in dataset if entry[0] == 'F']
taskG_entries = [entry for entry in dataset if entry[0] == 'G']
taskH_entries = [entry for entry in dataset if entry[0] == 'H']
taskI_entries = [entry for entry in dataset if entry[0] == 'I']
print(f'Total entries: {len(dataset)}')
print(f' Task A entries: {len(taskA_entries)}')
print(f' Task B entries: {len(taskB_entries)}')
print(f' Task C entries: {len(taskC_entries)}')
print(f' Task D entries: {len(taskD_entries)}')
print(f' Task E entries: {len(taskE_entries)}')
print(f' Task F entries: {len(taskF_entries)}')
print(f' Task G entries: {len(taskG_entries)}')
print(f' Task H entries: {len(taskH_entries)}')
print(f' Task I entries: {len(taskI_entries)}')
# Task A statistics
if taskA_entries:
print(f'\nTask A (Path finding):')
# Extract source-target pairs from task A entries
# Format: A source target directions...
pairs = set()
for entry in taskA_entries:
if len(entry) >= 3:
source = entry[1]
target = entry[2]
pairs.add((source, target))
num_pairs = len(pairs)
num_entries = len(taskA_entries)
avg_per_pair = num_entries / num_pairs if num_pairs > 0 else 0
print(f' Number of source-target pairs: {num_pairs}')
print(f' Number of data entries: {num_entries}')
print(f' Average entries per pair: {avg_per_pair:.2f}')
# Task B statistics
if taskB_entries:
print(f'\nTask B (Target identification):')
# Extract source nodes from task B entries
# Format: B source directions...
source_nodes = set()
for entry in taskB_entries:
if len(entry) >= 2:
source = entry[1]
source_nodes.add(source)
num_sources = len(source_nodes)
num_entries = len(taskB_entries)
avg_per_source = num_entries / num_sources if num_sources > 0 else 0
print(f' Number of source nodes: {num_sources}')
print(f' Number of data entries: {num_entries}')
print(f' Average entries per source node: {avg_per_source:.2f}')
# Task C statistics (mirrors Task A pair counting)
if taskC_entries:
print(f'\nTask C (Turn-based path finding):')
pairs = set()
for entry in taskC_entries:
if len(entry) >= 3:
source = entry[1]
target = entry[2]
pairs.add((source, target))
num_pairs = len(pairs)
num_entries = len(taskC_entries)
avg_per_pair = num_entries / num_pairs if num_pairs > 0 else 0
print(f' Number of source-target pairs: {num_pairs}')
print(f' Number of data entries: {num_entries}')
print(f' Average entries per pair: {avg_per_pair:.2f}')
if taskD_entries:
print(f'\nTask D (Path finding to label):')
print(f' Number of data entries: {len(taskD_entries)}')
if taskE_entries:
print(f'\nTask E (Path finding with labels):')
print(f' Number of data entries: {len(taskE_entries)}')
if taskF_entries:
print(f'\nTask F (Target label identification):')
print(f' Number of data entries: {len(taskF_entries)}')
if taskG_entries:
print(f'\nTask G (Reachability choice):')
print(f' Number of data entries: {len(taskG_entries)}')
if taskH_entries:
print(f'\nTask H (Relative clockwise-index path):')
print(f' Number of data entries: {len(taskH_entries)}')
def format_data(data, no_task_tag=False):
# Format: task_id source target [remaining_tokens]
# If no_task_tag is True, remove the first token (task identifier)
if no_task_tag and len(data) > 0:
# Remove the task identifier (first token)
return ' '.join(str(token) for token in data[1:]) + '\n'
else:
return ' '.join(str(token) for token in data) + '\n'
def write_dataset(dataset, file_name, no_task_tag=False):
with open(file_name, "w") as file:
for data in dataset:
file.write(format_data(data, no_task_tag))
def parse_tasks(tasks_str):
"""
Parse task specification string into a dictionary.
Format: "A<ratio>B<ratio>C<ratio>..." where ratios determine portions.
Example: "A1" (100% A), "A1B1" (50% A, 50% B), "A3B2" (60% A, 40% B), "A2B1C1" (50% A, 25% B, 25% C)
Returns: {"A": {"train": 50, "test": 50}, "B": {"train": 50, "test": 50}, ...}
Test data follows the same ratio as training data.
"""
weights = parse_task_distribution(tasks_str, default_task='A')
total_ratio = sum(weights.values())
tasks_config = {}
for task_id, ratio in weights.items():
percentage = (ratio / total_ratio) * 100
tasks_config[task_id] = {"train": percentage, "test": percentage}
return tasks_config
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_train_dataset', type=parse_count, default='10M',
help='Number of training data entries to generate (supports K/M/B, default: 50000)')
parser.add_argument('--num_test_dataset', type=parse_count, default=10000,
help='Number of test data entries to generate (supports K/M/B, default: 10000)')
# Multi-task specification:
parser.add_argument('--tasks', type=str, default='H1',
help='Task identifiers with ratios. Format: "A<ratio>B<ratio>C<ratio>...". Examples: "A1" (100%% A), "A1B1" (50%% A, 50%% B), "A3B2" (60%% A, 40%% B), "A1D1F1" (mix A/D/F). Default: A1')
parser.add_argument('--CL', action=argparse.BooleanOptionalAction, default=False,
help='Enable Task C label mode (append node labels after L/R turns) and add _CL_ in filenames')
parser.add_argument('--graph_file', type=str, default=None,
help='Optional path to an existing GraphML file; if provided, skip random graph generation and use this graph instead.')
parser.add_argument('--path_type', type=str, default='RWs', choices=['RWc', 'RWa', 'RWs'],
help='Path generation type: RWc (random walk with cycles), RWa (random walk acyclic, default), RWs (single source random walk). "shortest" is not implemented yet.')
# Arguments for task tag handling
parser.add_argument('--no_task_tag', action='store_true', default=False,
help='Remove task identifiers from generated data. When enabled, output files will have _NT suffix and data entries start directly with node numbers.')
parser.add_argument('--both', action='store_true', default=False,
help='Generate both versions (with and without task tags). When set, --no_task_tag is ignored and two datasets are produced.')
parser.add_argument('--num_labels', type=int, default=10,
help='Number of distinct node labels (default: 10). Up to 26 uses a-z; above 26 uses l0, l1, ...')
parser.add_argument('--min_path_len', type=int, default=0,
help='Minimum raw path length (in steps) for generated entries. 0 means no minimum (default).')
parser.add_argument('--num_workers', type=int, default=256,
help='Number of parallel worker processes for dataset generation (default: 1 = serial). Uses fork; requires Linux/macOS.')
args = parser.parse_args()
# Override NODE_LABELS if --num_labels is specified
if args.num_labels != 10:
NODE_LABELS = make_label_list(args.num_labels)
print(f"Using {args.num_labels} labels: {NODE_LABELS[:5]}{'...' if args.num_labels > 5 else ''}")
min_path_len = args.min_path_len
num_workers = args.num_workers
# Parse task specifications
tasks_config = parse_tasks(args.tasks)
tasks_str = args.tasks # Keep the original tasks string for filenames
tasks_tag = f"{tasks_str}_CL" if args.CL else tasks_str
cl_mode = args.CL
no_task_tag = args.no_task_tag # Get the no_task_tag flag
# Parse path_type for filenames (RWc = cyclic, RWa = acyclic, RWs = single source)
allow_cycles = (args.path_type == 'RWc')
path_type_tag = args.path_type
tasks_tag = f"{tasks_tag}_{path_type_tag}"
# Include num_labels and min_path_len in tags when non-default
if args.num_labels != 10:
tasks_tag = f"{tasks_tag}_L{args.num_labels}"
if args.min_path_len > 0:
tasks_tag = f"{tasks_tag}_P{args.min_path_len}"
edge_prob = args.edge_prob
chance_in_train = args.chance_in_train
num_train_dataset = args.num_train_dataset
num_test_dataset = args.num_test_dataset
train_label = format_count(num_train_dataset)
test_label = format_count(num_test_dataset)
graph_file = args.graph_file
if graph_file:
graph_path = graph_file
if not os.path.isabs(graph_file):
default_dir = os.path.join(os.path.dirname(__file__), f'{args.grid_size * args.grid_size}')
candidate = os.path.join(default_dir, graph_file)
if os.path.exists(candidate):
graph_path = candidate
print(f"Loading maze graph from {graph_path}...")
maze_graph = nx.read_graphml(graph_path)
# Ensure node ids are integers (GraphML loader returns strings)
try:
int_map = {node: int(node) for node in maze_graph.nodes()}
maze_graph = nx.relabel_nodes(maze_graph, int_map, copy=True)
except ValueError:
pass
num_nodes = len(maze_graph.nodes)
n = int(math.isqrt(num_nodes))
if n * n != num_nodes:
print(
f"Warning: provided graph has {num_nodes} nodes; not a perfect square grid. Proceeding with derived size {n}.")
else:
n = args.grid_size
num_nodes = n * n
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)
# Always save grid visualization to file with consistent naming convention
maze_viz_tag = f"{tasks_str}_CL" if cl_mode else tasks_str
maze_viz_tag = f"{maze_viz_tag}_{path_type_tag}"
if args.num_labels != 10:
maze_viz_tag = f"{maze_viz_tag}_L{args.num_labels}"
# Graph and visualization files: always save without _NT, regardless of no_task_tag/both
# This ensures they are compatible with both data formats
grid_file_path = os.path.join(folder_name, f'maze_{maze_viz_tag}_{n}_{edge_prob}.txt')
with open(grid_file_path, 'w') as f:
print_grid(maze_graph, n, file=f)
# Always print visualization to the screen
print_grid(maze_graph, n)
reachability, feasible_pairs = obtain_reachability()
# This is for generating pairs for training and test datasets for task A
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 = create_multitask_dataset(num_train_dataset, tasks_config, is_train=True)
test_set = create_multitask_dataset(num_test_dataset, tasks_config, is_train=False)
obtain_stats(train_set, is_train=True)
obtain_stats(test_set, is_train=False)
# Build graph tag for output files (without _NT)
graph_tag = f"{tasks_str}_CL" if cl_mode else tasks_str
graph_tag = f"{graph_tag}_{path_type_tag}"
# Include num_labels in graph tag when non-default (different label sets = different graphs)
if args.num_labels != 10:
graph_tag = f"{graph_tag}_L{args.num_labels}"
# Generate datasets based on both/no_task_tag flags
if args.both:
# Generate with task tags (no _NT suffix)
tag_with_tags = tasks_tag
write_dataset(train_set, os.path.join(folder_name, f'train_{tag_with_tags}_{train_label}.txt'),
no_task_tag=False)
write_dataset(test_set, os.path.join(folder_name, f'test_{tag_with_tags}_{test_label}.txt'), no_task_tag=False)
# Generate without task tags (_NT suffix)
tag_without_tags = f"{tasks_tag}_NT"
write_dataset(train_set, os.path.join(folder_name, f'train_{tag_without_tags}_{train_label}.txt'),
no_task_tag=True)
write_dataset(test_set, os.path.join(folder_name, f'test_{tag_without_tags}_{test_label}.txt'),
no_task_tag=True)
# Save graph files: both without _NT and with _NT
nx.write_graphml(maze_graph, os.path.join(folder_name, f'maze_graph_{graph_tag}.graphml'))
nx.write_graphml(maze_graph, os.path.join(folder_name, f'maze_graph_{graph_tag}_NT.graphml'))
print("Generated both with-tag and without-tag datasets and graph files.")
else:
# Original logic: generate only one version based on no_task_tag
output_tasks_tag = tasks_tag
if no_task_tag:
output_tasks_tag = f"{tasks_tag}_NT"
write_dataset(train_set, os.path.join(folder_name, f'train_{output_tasks_tag}_{train_label}.txt'), no_task_tag)
write_dataset(test_set, os.path.join(folder_name, f'test_{output_tasks_tag}_{test_label}.txt'), no_task_tag)
# Save graph file with appropriate suffix
graph_suffix = "_NT" if no_task_tag else ""
nx.write_graphml(maze_graph, os.path.join(folder_name, f'maze_graph_{graph_tag}{graph_suffix}.graphml'))