File size: 13,020 Bytes
8311f95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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])