File size: 46,877 Bytes
34e468d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 | 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')) |