seqBench / scripts /maze_loader.py
emnlp-submission's picture
Upload maze_loader.py
8311f95 verified
import pickle
import random
import math
import os
from rooms import NameGenerator
class MazeLoader:
"""
Loads a maze that can be plotted and used to generate a natural language problem.
"""
def __init__(
self,
filename,
shuffle_description=True,
hide_coordinates=False,
removed_key_count=None,
solvable=True,
):
self.solvable = solvable
self.filename = filename
self.data = pickle.load(open(filename, "rb"))
self.shuffle_description = shuffle_description
self.hide_coordinates = hide_coordinates
self.removed_key_count = removed_key_count
if self.removed_key_count is None:
self.removed_key_count = 0
if removed_key_count not in self.data["sub_maze_configurations"].keys():
raise ValueError(
f"Removed key count {removed_key_count} is not in the sub_maze_configurations keys"
)
self.room_name = self.data["room_name"]
self.maze = self.data["sub_maze_configurations"][self.removed_key_count]["maze"]
self.doors = self.data["sub_maze_configurations"][self.removed_key_count][
"doors"
]
self.keys_locations = self.data["sub_maze_configurations"][
self.removed_key_count
]["keys_locations"]
self.connected_cells = self.data["connected_cells"]
self.num_locked_doors = (
self.data["world_parameters"]["N_locked_doors"] - self.removed_key_count
)
self.N = self.data["world_parameters"]["N"]
self.M = self.data["world_parameters"]["M"]
name_generator = NameGenerator(self.N, self.M)
self.R = lambda x: name_generator.get_name(x)
if not self.solvable:
print("Maze is not solvable")
# get keys to first and last locked doors
first_key, last_key = self.get_first_and_last_key()
self.swap_key_locations(first_key, last_key)
self.solution = None
else:
self.solution = self.data["standardized_problem_solution"][
self.removed_key_count
][::-1]
self.solution_with_room_names = [
(item[0], self.room_name[item[1]])
if item[0].split("_")[-1] in ["to", "start"]
else item
for item in self.solution
]
self.solution_with_friendly_room_names = [
(item[0], self.R(item[1]))
if item[0].split("_")[-1] in ["to", "start"]
else item
for item in self.solution
]
# we keep the definition of supporting facts in the original solvable problem even if the maze is not solvable as the same path still needs to be used to make the conclusion
self.used_keys = [item[1] for item in self.solution if item[0] == "use_key"]
self.used_path = (
[self.data["start_room"]]
+ [item[1] for item in self.solution if item[0] == "move_to"]
+ [self.data["end_room"]]
)
self.used_connections = list(zip(self.used_path[:-1], self.used_path[1:]))
def compile_description(self, args, mode, friendly=False):
if mode == "door":
cell1, cell2 = args
status = self.doors[(cell1, cell2)][0]
if friendly:
room1, room2 = self.R(cell1), self.R(cell2)
else:
room1, room2 = self.room_name[cell1], self.room_name[cell2]
return f"Room {room1} has a door to room {room2}. "
elif mode == "key_door_relation":
cell1, cell2 = args[:2]
if friendly:
room1, room2 = self.R(cell1), self.R(cell2)
else:
room1, room2 = self.room_name[cell1], self.room_name[cell2]
return (
f"""The locked door between {room1} and {room2} requires key {self.doors[(cell1, cell2)][1]}. """
if self.doors[(cell1, cell2)][0] == "closed and locked"
else ""
)
elif mode == "connected_rooms":
cell1, cell2, door_status = args
if not self.hide_coordinates:
location_description1 = " at " + str(cell1)
location_description2 = " at " + str(cell2)
else:
location_description1 = ""
location_description2 = ""
if friendly:
roomA, roomB = self.R(cell1), self.R(cell2)
else:
roomA, roomB = self.room_name[cell1], self.room_name[cell2]
return (
f"""Room {roomA}{location_description1}"""
+ f""" and {roomB}{location_description2} are connected by a{'n' if door_status == 'open' else ''} {door_status} door. """
)
elif mode == "key_location":
key_id, room = args
if friendly:
room1 = self.R(room)
else:
room1 = self.room_name[room]
return f"""Key {key_id} is in room {room1}. """
elif mode == "rescue_agent_location":
room = args
if friendly:
room1 = self.R(room)
else:
room1 = self.room_name[room]
return f"{self.rescue_agent} is in room {room1}. "
elif mode == "victim_location":
room = args
if friendly:
room1 = self.R(room)
else:
room1 = self.room_name[room]
return f"{self.victim} is in room {room1}. "
def encode_problem_into_nlp(self, shuffle_ratio=0.5, noise_ratio=0.5):
"""
Encodes the problem into a natural language problem.
The facts can be of the following types:
connected_rooms:
1. Room A and B are connected by an open door. (for regular connections)
2. Room A and B are connected by a closed and locked door. (for locked doors)
key_door_relation:
3. The locked door between Room A and Room B requires key 5. (for key door relations)
key_location:
4. Key 5 is in Room C. (for key locations)
rescue_agent_location:
5. The rescue agent is in Room A. (for rescue agent location)
victim_location:
6. The victim is in Room A. (for victim location)
"""
# I. connected_rooms
self.nlp_problem = []
covered_cells = set()
for cell in sorted(self.connected_cells.keys()):
for neighbor in sorted(self.connected_cells[cell]):
if (cell, neighbor) in covered_cells or cell == neighbor:
continue
if (cell, neighbor) in self.used_connections or (
neighbor,
cell,
) in self.used_connections:
supporting = True
else:
supporting = False
door_status = self.doors[(cell, neighbor)][0]
key_id = self.doors[(cell, neighbor)][1]
self.nlp_problem.append(
((cell, neighbor, door_status), "connected_rooms", supporting)
)
# II. key_door_relation
if door_status == "closed and locked" and supporting:
supporting1 = True
else:
supporting1 = False
if door_status == "closed and locked":
self.nlp_problem.append(
((cell, neighbor, key_id), "key_door_relation", supporting1)
)
# III. key_location
if key_id in self.used_keys:
supporting2 = True
else:
supporting2 = False
if door_status == "closed and locked":
self.nlp_problem.append(
(
(key_id, self.keys_locations[key_id]),
"key_location",
supporting2,
)
)
covered_cells.add((cell, neighbor))
covered_cells.add((neighbor, cell))
self.victim = self.data["world_parameters"]["victim"]
self.rescue_agent = self.data["world_parameters"]["rescue_agent"]
# ordering the facts by supporting facts first
self.nlp_problem = [
item[1]
for item in sorted(
[(i, it) for i, it in enumerate(self.nlp_problem[::-1])],
key=lambda x: (x[1][2], x[0]),
reverse=True,
)
]
# number of distracting facts
N_minus = len([item for item in self.nlp_problem if item[2] == False])
# number of supporting facts
N_plus = len(self.nlp_problem) - N_minus
# number of distracting facts to remove
N_minus_x = int(N_minus * (1 - noise_ratio)) - 1
if N_minus_x > 0:
self.nlp_problem = self.nlp_problem[:-N_minus_x]
x = int((N_plus) * (1 - shuffle_ratio))
ordered_part = self.nlp_problem[:x]
shuffle_part = self.nlp_problem[x:]
random.shuffle(shuffle_part)
self.nlp_problem = ordered_part + shuffle_part
self.nlp_problem.append(
(self.data["start_room"], "rescue_agent_location", True)
)
self.nlp_problem.append((self.data["end_room"], "victim_location", True))
natural_language_problem = []
natural_language_problem_friendly = []
for item in self.nlp_problem:
natural_language_problem += [self.compile_description(item[0], item[1])]
natural_language_problem_friendly += [
self.compile_description(item[0], item[1], friendly=True)
]
N_minus = len([item for item in self.nlp_problem if item[2] == False])
N_plus = len(self.nlp_problem) - N_minus
self.support_weight = round(N_plus / float(N_plus + N_minus), 2)
self.shuffle_entropy = self.measure_distraction_entropy()
return (
self.nlp_problem,
"".join(natural_language_problem),
"".join(natural_language_problem_friendly),
self.support_weight,
self.shuffle_entropy,
)
def measure_distraction_entropy(self):
entropy = 0
count = 0
for i in range(0, len(self.nlp_problem), 2):
first_fact = self.nlp_problem[i][-1]
second_fact = (
self.nlp_problem[i + 1][-1] if i + 1 < len(self.nlp_problem) else None
)
if second_fact is None:
continue
count += 1
if first_fact != second_fact and (
first_fact == True or second_fact == True
):
entropy -= math.log(0.5)
return entropy / float(count)
def get_first_and_last_key(self):
pass
def swap_key_locations(self, first_key, last_key):
pass
def single_file_load(
folder_name="maze_5_5_3_0.5_0.0_True",
file_name=None,
removed_key_count=0,
hide_coordinates=True,
):
solvable = True
folder = f"generated_data/{folder_name}/"
if file_name is None:
for file in os.listdir(folder):
maze_loader = MazeLoader(
folder + file,
removed_key_count=removed_key_count,
solvable=solvable,
hide_coordinates=hide_coordinates,
)
break
else:
maze_loader = MazeLoader(
folder + file_name,
removed_key_count=removed_key_count,
solvable=solvable,
hide_coordinates=hide_coordinates,
)
nlp = maze_loader.encode_problem_into_nlp(shuffle_ratio=0.2, noise_ratio=0.0)
facts = nlp[1]
solution = maze_loader.solution_with_room_names
return facts, solution, maze_loader, file_name if file_name is not None else file
if __name__ == "__main__":
removed_key_count = 4
solvable = True
hide_coordinates = True
folder = "generated_data/maze_7_7_7_True/"
for file in os.listdir(folder):
if file not in ["874841.pkl"]:
continue
maze_loader = MazeLoader(
folder + file,
removed_key_count=removed_key_count,
solvable=solvable,
hide_coordinates=hide_coordinates,
)
break
from plot import pretty_plot_maze
# pretty_plot_maze(maze_loader)
nlp = maze_loader.encode_problem_into_nlp(shuffle_ratio=0.2, noise_ratio=1.0)
# colored print
print(f"\033[91mProvided Facts:\033[0m {nlp[2]}")
print(f"\033[92mSolution:\033[0m {maze_loader.solution_with_room_names}")
# print("Problem Prompt NLP: Compact List format", nlp[0])
# print("Distraction Weight: ", nlp[2])
# print("Shuffle Entropy: ", nlp[3])