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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import pickle
|
2 |
+
import random
|
3 |
+
import math
|
4 |
+
import os
|
5 |
+
from rooms import NameGenerator
|
6 |
+
|
7 |
+
|
8 |
+
class MazeLoader:
|
9 |
+
"""
|
10 |
+
Loads a maze that can be plotted and used to generate a natural language problem.
|
11 |
+
"""
|
12 |
+
|
13 |
+
def __init__(
|
14 |
+
self,
|
15 |
+
filename,
|
16 |
+
shuffle_description=True,
|
17 |
+
hide_coordinates=False,
|
18 |
+
removed_key_count=None,
|
19 |
+
solvable=True,
|
20 |
+
):
|
21 |
+
self.solvable = solvable
|
22 |
+
self.filename = filename
|
23 |
+
self.data = pickle.load(open(filename, "rb"))
|
24 |
+
self.shuffle_description = shuffle_description
|
25 |
+
self.hide_coordinates = hide_coordinates
|
26 |
+
self.removed_key_count = removed_key_count
|
27 |
+
if self.removed_key_count is None:
|
28 |
+
self.removed_key_count = 0
|
29 |
+
|
30 |
+
if removed_key_count not in self.data["sub_maze_configurations"].keys():
|
31 |
+
raise ValueError(
|
32 |
+
f"Removed key count {removed_key_count} is not in the sub_maze_configurations keys"
|
33 |
+
)
|
34 |
+
|
35 |
+
self.room_name = self.data["room_name"]
|
36 |
+
self.maze = self.data["sub_maze_configurations"][self.removed_key_count]["maze"]
|
37 |
+
self.doors = self.data["sub_maze_configurations"][self.removed_key_count][
|
38 |
+
"doors"
|
39 |
+
]
|
40 |
+
self.keys_locations = self.data["sub_maze_configurations"][
|
41 |
+
self.removed_key_count
|
42 |
+
]["keys_locations"]
|
43 |
+
self.connected_cells = self.data["connected_cells"]
|
44 |
+
self.num_locked_doors = (
|
45 |
+
self.data["world_parameters"]["N_locked_doors"] - self.removed_key_count
|
46 |
+
)
|
47 |
+
self.N = self.data["world_parameters"]["N"]
|
48 |
+
self.M = self.data["world_parameters"]["M"]
|
49 |
+
name_generator = NameGenerator(self.N, self.M)
|
50 |
+
self.R = lambda x: name_generator.get_name(x)
|
51 |
+
|
52 |
+
if not self.solvable:
|
53 |
+
print("Maze is not solvable")
|
54 |
+
# get keys to first and last locked doors
|
55 |
+
first_key, last_key = self.get_first_and_last_key()
|
56 |
+
self.swap_key_locations(first_key, last_key)
|
57 |
+
self.solution = None
|
58 |
+
else:
|
59 |
+
self.solution = self.data["standardized_problem_solution"][
|
60 |
+
self.removed_key_count
|
61 |
+
][::-1]
|
62 |
+
self.solution_with_room_names = [
|
63 |
+
(item[0], self.room_name[item[1]])
|
64 |
+
if item[0].split("_")[-1] in ["to", "start"]
|
65 |
+
else item
|
66 |
+
for item in self.solution
|
67 |
+
]
|
68 |
+
self.solution_with_friendly_room_names = [
|
69 |
+
(item[0], self.R(item[1]))
|
70 |
+
if item[0].split("_")[-1] in ["to", "start"]
|
71 |
+
else item
|
72 |
+
for item in self.solution
|
73 |
+
]
|
74 |
+
|
75 |
+
# 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
|
76 |
+
self.used_keys = [item[1] for item in self.solution if item[0] == "use_key"]
|
77 |
+
self.used_path = (
|
78 |
+
[self.data["start_room"]]
|
79 |
+
+ [item[1] for item in self.solution if item[0] == "move_to"]
|
80 |
+
+ [self.data["end_room"]]
|
81 |
+
)
|
82 |
+
self.used_connections = list(zip(self.used_path[:-1], self.used_path[1:]))
|
83 |
+
|
84 |
+
def compile_description(self, args, mode, friendly=False):
|
85 |
+
|
86 |
+
if mode == "door":
|
87 |
+
cell1, cell2 = args
|
88 |
+
status = self.doors[(cell1, cell2)][0]
|
89 |
+
if friendly:
|
90 |
+
room1, room2 = self.R(cell1), self.R(cell2)
|
91 |
+
else:
|
92 |
+
room1, room2 = self.room_name[cell1], self.room_name[cell2]
|
93 |
+
return f"Room {room1} has a door to room {room2}. "
|
94 |
+
elif mode == "key_door_relation":
|
95 |
+
cell1, cell2 = args[:2]
|
96 |
+
if friendly:
|
97 |
+
room1, room2 = self.R(cell1), self.R(cell2)
|
98 |
+
else:
|
99 |
+
room1, room2 = self.room_name[cell1], self.room_name[cell2]
|
100 |
+
return (
|
101 |
+
f"""The locked door between {room1} and {room2} requires key {self.doors[(cell1, cell2)][1]}. """
|
102 |
+
if self.doors[(cell1, cell2)][0] == "closed and locked"
|
103 |
+
else ""
|
104 |
+
)
|
105 |
+
elif mode == "connected_rooms":
|
106 |
+
cell1, cell2, door_status = args
|
107 |
+
if not self.hide_coordinates:
|
108 |
+
location_description1 = " at " + str(cell1)
|
109 |
+
location_description2 = " at " + str(cell2)
|
110 |
+
else:
|
111 |
+
location_description1 = ""
|
112 |
+
location_description2 = ""
|
113 |
+
if friendly:
|
114 |
+
roomA, roomB = self.R(cell1), self.R(cell2)
|
115 |
+
else:
|
116 |
+
roomA, roomB = self.room_name[cell1], self.room_name[cell2]
|
117 |
+
|
118 |
+
return (
|
119 |
+
f"""Room {roomA}{location_description1}"""
|
120 |
+
+ f""" and {roomB}{location_description2} are connected by a{'n' if door_status == 'open' else ''} {door_status} door. """
|
121 |
+
)
|
122 |
+
elif mode == "key_location":
|
123 |
+
key_id, room = args
|
124 |
+
if friendly:
|
125 |
+
room1 = self.R(room)
|
126 |
+
else:
|
127 |
+
room1 = self.room_name[room]
|
128 |
+
return f"""Key {key_id} is in room {room1}. """
|
129 |
+
elif mode == "rescue_agent_location":
|
130 |
+
room = args
|
131 |
+
if friendly:
|
132 |
+
room1 = self.R(room)
|
133 |
+
else:
|
134 |
+
room1 = self.room_name[room]
|
135 |
+
return f"{self.rescue_agent} is in room {room1}. "
|
136 |
+
elif mode == "victim_location":
|
137 |
+
room = args
|
138 |
+
if friendly:
|
139 |
+
room1 = self.R(room)
|
140 |
+
else:
|
141 |
+
room1 = self.room_name[room]
|
142 |
+
return f"{self.victim} is in room {room1}. "
|
143 |
+
|
144 |
+
def encode_problem_into_nlp(self, shuffle_ratio=0.5, noise_ratio=0.5):
|
145 |
+
"""
|
146 |
+
Encodes the problem into a natural language problem.
|
147 |
+
The facts can be of the following types:
|
148 |
+
connected_rooms:
|
149 |
+
1. Room A and B are connected by an open door. (for regular connections)
|
150 |
+
2. Room A and B are connected by a closed and locked door. (for locked doors)
|
151 |
+
key_door_relation:
|
152 |
+
3. The locked door between Room A and Room B requires key 5. (for key door relations)
|
153 |
+
key_location:
|
154 |
+
4. Key 5 is in Room C. (for key locations)
|
155 |
+
rescue_agent_location:
|
156 |
+
5. The rescue agent is in Room A. (for rescue agent location)
|
157 |
+
victim_location:
|
158 |
+
6. The victim is in Room A. (for victim location)
|
159 |
+
"""
|
160 |
+
|
161 |
+
# I. connected_rooms
|
162 |
+
self.nlp_problem = []
|
163 |
+
covered_cells = set()
|
164 |
+
for cell in sorted(self.connected_cells.keys()):
|
165 |
+
for neighbor in sorted(self.connected_cells[cell]):
|
166 |
+
if (cell, neighbor) in covered_cells or cell == neighbor:
|
167 |
+
continue
|
168 |
+
if (cell, neighbor) in self.used_connections or (
|
169 |
+
neighbor,
|
170 |
+
cell,
|
171 |
+
) in self.used_connections:
|
172 |
+
supporting = True
|
173 |
+
else:
|
174 |
+
supporting = False
|
175 |
+
door_status = self.doors[(cell, neighbor)][0]
|
176 |
+
key_id = self.doors[(cell, neighbor)][1]
|
177 |
+
self.nlp_problem.append(
|
178 |
+
((cell, neighbor, door_status), "connected_rooms", supporting)
|
179 |
+
)
|
180 |
+
# II. key_door_relation
|
181 |
+
if door_status == "closed and locked" and supporting:
|
182 |
+
supporting1 = True
|
183 |
+
else:
|
184 |
+
supporting1 = False
|
185 |
+
if door_status == "closed and locked":
|
186 |
+
self.nlp_problem.append(
|
187 |
+
((cell, neighbor, key_id), "key_door_relation", supporting1)
|
188 |
+
)
|
189 |
+
# III. key_location
|
190 |
+
if key_id in self.used_keys:
|
191 |
+
supporting2 = True
|
192 |
+
else:
|
193 |
+
supporting2 = False
|
194 |
+
if door_status == "closed and locked":
|
195 |
+
self.nlp_problem.append(
|
196 |
+
(
|
197 |
+
(key_id, self.keys_locations[key_id]),
|
198 |
+
"key_location",
|
199 |
+
supporting2,
|
200 |
+
)
|
201 |
+
)
|
202 |
+
|
203 |
+
covered_cells.add((cell, neighbor))
|
204 |
+
covered_cells.add((neighbor, cell))
|
205 |
+
|
206 |
+
self.victim = self.data["world_parameters"]["victim"]
|
207 |
+
self.rescue_agent = self.data["world_parameters"]["rescue_agent"]
|
208 |
+
# ordering the facts by supporting facts first
|
209 |
+
self.nlp_problem = [
|
210 |
+
item[1]
|
211 |
+
for item in sorted(
|
212 |
+
[(i, it) for i, it in enumerate(self.nlp_problem[::-1])],
|
213 |
+
key=lambda x: (x[1][2], x[0]),
|
214 |
+
reverse=True,
|
215 |
+
)
|
216 |
+
]
|
217 |
+
# number of distracting facts
|
218 |
+
N_minus = len([item for item in self.nlp_problem if item[2] == False])
|
219 |
+
# number of supporting facts
|
220 |
+
N_plus = len(self.nlp_problem) - N_minus
|
221 |
+
# number of distracting facts to remove
|
222 |
+
N_minus_x = int(N_minus * (1 - noise_ratio)) - 1
|
223 |
+
if N_minus_x > 0:
|
224 |
+
self.nlp_problem = self.nlp_problem[:-N_minus_x]
|
225 |
+
|
226 |
+
x = int((N_plus) * (1 - shuffle_ratio))
|
227 |
+
ordered_part = self.nlp_problem[:x]
|
228 |
+
shuffle_part = self.nlp_problem[x:]
|
229 |
+
random.shuffle(shuffle_part)
|
230 |
+
self.nlp_problem = ordered_part + shuffle_part
|
231 |
+
self.nlp_problem.append(
|
232 |
+
(self.data["start_room"], "rescue_agent_location", True)
|
233 |
+
)
|
234 |
+
self.nlp_problem.append((self.data["end_room"], "victim_location", True))
|
235 |
+
natural_language_problem = []
|
236 |
+
natural_language_problem_friendly = []
|
237 |
+
for item in self.nlp_problem:
|
238 |
+
natural_language_problem += [self.compile_description(item[0], item[1])]
|
239 |
+
natural_language_problem_friendly += [
|
240 |
+
self.compile_description(item[0], item[1], friendly=True)
|
241 |
+
]
|
242 |
+
N_minus = len([item for item in self.nlp_problem if item[2] == False])
|
243 |
+
N_plus = len(self.nlp_problem) - N_minus
|
244 |
+
self.support_weight = round(N_plus / float(N_plus + N_minus), 2)
|
245 |
+
self.shuffle_entropy = self.measure_distraction_entropy()
|
246 |
+
return (
|
247 |
+
self.nlp_problem,
|
248 |
+
"".join(natural_language_problem),
|
249 |
+
"".join(natural_language_problem_friendly),
|
250 |
+
self.support_weight,
|
251 |
+
self.shuffle_entropy,
|
252 |
+
)
|
253 |
+
|
254 |
+
def measure_distraction_entropy(self):
|
255 |
+
entropy = 0
|
256 |
+
count = 0
|
257 |
+
for i in range(0, len(self.nlp_problem), 2):
|
258 |
+
first_fact = self.nlp_problem[i][-1]
|
259 |
+
second_fact = (
|
260 |
+
self.nlp_problem[i + 1][-1] if i + 1 < len(self.nlp_problem) else None
|
261 |
+
)
|
262 |
+
if second_fact is None:
|
263 |
+
continue
|
264 |
+
count += 1
|
265 |
+
if first_fact != second_fact and (
|
266 |
+
first_fact == True or second_fact == True
|
267 |
+
):
|
268 |
+
entropy -= math.log(0.5)
|
269 |
+
return entropy / float(count)
|
270 |
+
|
271 |
+
def get_first_and_last_key(self):
|
272 |
+
pass
|
273 |
+
|
274 |
+
def swap_key_locations(self, first_key, last_key):
|
275 |
+
pass
|
276 |
+
|
277 |
+
|
278 |
+
def single_file_load(
|
279 |
+
folder_name="maze_5_5_3_0.5_0.0_True",
|
280 |
+
file_name=None,
|
281 |
+
removed_key_count=0,
|
282 |
+
hide_coordinates=True,
|
283 |
+
):
|
284 |
+
solvable = True
|
285 |
+
folder = f"generated_data/{folder_name}/"
|
286 |
+
if file_name is None:
|
287 |
+
for file in os.listdir(folder):
|
288 |
+
maze_loader = MazeLoader(
|
289 |
+
folder + file,
|
290 |
+
removed_key_count=removed_key_count,
|
291 |
+
solvable=solvable,
|
292 |
+
hide_coordinates=hide_coordinates,
|
293 |
+
)
|
294 |
+
break
|
295 |
+
else:
|
296 |
+
maze_loader = MazeLoader(
|
297 |
+
folder + file_name,
|
298 |
+
removed_key_count=removed_key_count,
|
299 |
+
solvable=solvable,
|
300 |
+
hide_coordinates=hide_coordinates,
|
301 |
+
)
|
302 |
+
|
303 |
+
nlp = maze_loader.encode_problem_into_nlp(shuffle_ratio=0.2, noise_ratio=0.0)
|
304 |
+
facts = nlp[1]
|
305 |
+
solution = maze_loader.solution_with_room_names
|
306 |
+
return facts, solution, maze_loader, file_name if file_name is not None else file
|
307 |
+
|
308 |
+
|
309 |
+
if __name__ == "__main__":
|
310 |
+
removed_key_count = 4
|
311 |
+
solvable = True
|
312 |
+
hide_coordinates = True
|
313 |
+
folder = "generated_data/maze_7_7_7_True/"
|
314 |
+
|
315 |
+
for file in os.listdir(folder):
|
316 |
+
if file not in ["874841.pkl"]:
|
317 |
+
continue
|
318 |
+
maze_loader = MazeLoader(
|
319 |
+
folder + file,
|
320 |
+
removed_key_count=removed_key_count,
|
321 |
+
solvable=solvable,
|
322 |
+
hide_coordinates=hide_coordinates,
|
323 |
+
)
|
324 |
+
break
|
325 |
+
from plot import pretty_plot_maze
|
326 |
+
|
327 |
+
# pretty_plot_maze(maze_loader)
|
328 |
+
|
329 |
+
nlp = maze_loader.encode_problem_into_nlp(shuffle_ratio=0.2, noise_ratio=1.0)
|
330 |
+
# colored print
|
331 |
+
print(f"\033[91mProvided Facts:\033[0m {nlp[2]}")
|
332 |
+
print(f"\033[92mSolution:\033[0m {maze_loader.solution_with_room_names}")
|
333 |
+
# print("Problem Prompt NLP: Compact List format", nlp[0])
|
334 |
+
# print("Distraction Weight: ", nlp[2])
|
335 |
+
# print("Shuffle Entropy: ", nlp[3])
|