Update
[beaver.git] / maze.py
1 #!/usr/bin/env python
2
3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
5
6 # Written by Francois Fleuret <francois@fleuret.org>
7
8 import torch, torchvision
9
10 ######################################################################
11
12 v_empty, v_wall, v_start, v_goal, v_path = 0, 1, 2, 3, 4
13
14
15 def create_maze(h=11, w=17, nb_walls=8):
16     a, k = 0, 0
17
18     while k < nb_walls:
19         while True:
20             if a == 0:
21                 m = torch.zeros(h, w, dtype=torch.int64)
22                 m[0, :] = 1
23                 m[-1, :] = 1
24                 m[:, 0] = 1
25                 m[:, -1] = 1
26
27             r = torch.rand(4)
28
29             if r[0] <= 0.5:
30                 i1, i2, j = (
31                     int((r[1] * h).item()),
32                     int((r[2] * h).item()),
33                     int((r[3] * w).item()),
34                 )
35                 i1, i2, j = i1 - i1 % 2, i2 - i2 % 2, j - j % 2
36                 i1, i2 = min(i1, i2), max(i1, i2)
37                 if i2 - i1 > 1 and i2 - i1 <= h / 2 and m[i1 : i2 + 1, j].sum() <= 1:
38                     m[i1 : i2 + 1, j] = 1
39                     break
40             else:
41                 i, j1, j2 = (
42                     int((r[1] * h).item()),
43                     int((r[2] * w).item()),
44                     int((r[3] * w).item()),
45                 )
46                 i, j1, j2 = i - i % 2, j1 - j1 % 2, j2 - j2 % 2
47                 j1, j2 = min(j1, j2), max(j1, j2)
48                 if j2 - j1 > 1 and j2 - j1 <= w / 2 and m[i, j1 : j2 + 1].sum() <= 1:
49                     m[i, j1 : j2 + 1] = 1
50                     break
51             a += 1
52
53             if a > 10 * nb_walls:
54                 a, k = 0, 0
55
56         k += 1
57
58     return m
59
60
61 ######################################################################
62
63
64 def compute_distance(walls, goal_i, goal_j):
65     max_length = walls.numel()
66     dist = torch.full_like(walls, max_length)
67
68     dist[goal_i, goal_j] = 0
69     pred_dist = torch.empty_like(dist)
70
71     while True:
72         pred_dist.copy_(dist)
73         d = (
74             torch.cat(
75                 (
76                     dist[None, 1:-1, 0:-2],
77                     dist[None, 2:, 1:-1],
78                     dist[None, 1:-1, 2:],
79                     dist[None, 0:-2, 1:-1],
80                 ),
81                 0,
82             ).min(dim=0)[0]
83             + 1
84         )
85
86         dist[1:-1, 1:-1] = torch.min(dist[1:-1, 1:-1], d)
87         dist = walls * max_length + (1 - walls) * dist
88
89         if dist.equal(pred_dist):
90             return dist * (1 - walls)
91
92
93 ######################################################################
94
95
96 def compute_policy(walls, goal_i, goal_j):
97     distance = compute_distance(walls, goal_i, goal_j)
98     distance = distance + walls.numel() * walls
99
100     value = distance.new_full((4,) + distance.size(), walls.numel())
101     value[0, :, 1:] = distance[:, :-1]  # <
102     value[1, :, :-1] = distance[:, 1:]  # >
103     value[2, 1:, :] = distance[:-1, :]  # ^
104     value[3, :-1, :] = distance[1:, :]  # v
105
106     proba = (value.min(dim=0)[0][None] == value).float()
107     proba = proba / proba.sum(dim=0)[None]
108     proba = proba * (1 - walls) + walls.float() / 4
109
110     return proba
111
112
113 def stationary_densities(mazes, policies):
114     policies = policies * (mazes != v_goal)[:, None]
115     start = (mazes == v_start).nonzero(as_tuple=True)
116     probas = mazes.new_zeros(mazes.size(), dtype=torch.float32)
117     pred_probas = probas.clone()
118     probas[start] = 1.0
119
120     while not pred_probas.equal(probas):
121         pred_probas.copy_(probas)
122         probas.zero_()
123         probas[:, 1:, :] += pred_probas[:, :-1, :] * policies[:, 3, :-1, :]
124         probas[:, :-1, :] += pred_probas[:, 1:, :] * policies[:, 2, 1:, :]
125         probas[:, :, 1:] += pred_probas[:, :, :-1] * policies[:, 1, :, :-1]
126         probas[:, :, :-1] += pred_probas[:, :, 1:] * policies[:, 0, :, 1:]
127         probas[start] = 1.0
128
129     return probas
130
131
132 ######################################################################
133
134
135 def mark_path(walls, i, j, goal_i, goal_j, policy):
136     action = torch.distributions.categorical.Categorical(
137         policy.permute(1, 2, 0)
138     ).sample()
139     n, nmax = 0, walls.numel()
140     while i != goal_i or j != goal_j:
141         di, dj = [(0, -1), (0, 1), (-1, 0), (1, 0)][action[i, j]]
142         i, j = i + di, j + dj
143         assert walls[i, j] == 0
144         walls[i, j] = v_path
145         n += 1
146         assert n < nmax
147
148
149 def path_correctness(mazes, paths):
150     still_ok = (mazes - (paths * (paths < 4))).view(mazes.size(0), -1).abs().sum(1) == 0
151     reached = still_ok.new_zeros(still_ok.size())
152     current, pred_current = paths.clone(), paths.new_zeros(paths.size())
153     goal = (mazes == v_goal).long()
154     while not pred_current.equal(current):
155         pred_current.copy_(current)
156         u = (current == v_start).long()
157         possible_next = (
158             u[:, 2:, 1:-1] + u[:, 0:-2, 1:-1] + u[:, 1:-1, 2:] + u[:, 1:-1, 0:-2] > 0
159         ).long()
160         u = u[:, 1:-1, 1:-1]
161         reached += ((goal[:, 1:-1, 1:-1] * possible_next).sum((1, 2)) == 1) * (
162             (current == v_path).sum((1, 2)) == 0
163         )
164         current[:, 1:-1, 1:-1] = (1 - u) * current[:, 1:-1, 1:-1] + (
165             v_start - v_path
166         ) * (possible_next * (current[:, 1:-1, 1:-1] == v_path))
167         still_ok *= (current == v_start).sum((1, 2)) <= 1
168
169     return still_ok * reached
170
171
172 ######################################################################
173
174
175 def create_maze_data(
176     nb, height=11, width=17, nb_walls=8, dist_min=10, progress_bar=lambda x: x
177 ):
178     mazes = torch.empty(nb, height, width, dtype=torch.int64)
179     paths = torch.empty(nb, height, width, dtype=torch.int64)
180     policies = torch.empty(nb, 4, height, width)
181
182     for n in progress_bar(range(nb)):
183         maze = create_maze(height, width, nb_walls)
184         i = (maze == v_empty).nonzero()
185         while True:
186             start, goal = i[torch.randperm(i.size(0))[:2]]
187             if (start - goal).abs().sum() >= dist_min:
188                 break
189         start_i, start_j, goal_i, goal_j = start[0], start[1], goal[0], goal[1]
190
191         policy = compute_policy(maze, goal_i, goal_j)
192         path = maze.clone()
193         mark_path(path, start_i, start_j, goal_i, goal_j, policy)
194         maze[start_i, start_j] = v_start
195         maze[goal_i, goal_j] = v_goal
196         path[start_i, start_j] = v_start
197         path[goal_i, goal_j] = v_goal
198
199         mazes[n] = maze
200         paths[n] = path
201         policies[n] = policy
202
203     return mazes, paths, policies
204
205
206 ######################################################################
207
208
209 def save_image(
210     name,
211     mazes,
212     target_paths=None,
213     predicted_paths=None,
214     score_paths=None,
215     score_truth=None,
216     path_correct=None,
217 ):
218     colors = torch.tensor(
219         [
220             [255, 255, 255],  # empty
221             [0, 0, 0],  # wall
222             [0, 255, 0],  # start
223             [127, 127, 255],  # goal
224             [255, 0, 0],  # path
225         ]
226     )
227
228     mazes = mazes.cpu()
229
230     c_mazes = (
231         colors[mazes.reshape(-1)].reshape(mazes.size() + (-1,)).permute(0, 3, 1, 2)
232     )
233
234     if score_truth is not None:
235         score_truth = score_truth.cpu()
236         c_score_truth = score_truth.unsqueeze(1).expand(-1, 3, -1, -1)
237         c_score_truth = (
238             c_score_truth * colors[4].reshape(1, 3, 1, 1)
239             + (1 - c_score_truth) * colors[0].reshape(1, 3, 1, 1)
240         ).long()
241         c_mazes = (mazes.unsqueeze(1) != v_empty) * c_mazes + (
242             mazes.unsqueeze(1) == v_empty
243         ) * c_score_truth
244
245     imgs = c_mazes.unsqueeze(1)
246
247     if target_paths is not None:
248         target_paths = target_paths.cpu()
249
250         c_target_paths = (
251             colors[target_paths.reshape(-1)]
252             .reshape(target_paths.size() + (-1,))
253             .permute(0, 3, 1, 2)
254         )
255
256         imgs = torch.cat((imgs, c_target_paths.unsqueeze(1)), 1)
257
258     if predicted_paths is not None:
259         predicted_paths = predicted_paths.cpu()
260         c_predicted_paths = (
261             colors[predicted_paths.reshape(-1)]
262             .reshape(predicted_paths.size() + (-1,))
263             .permute(0, 3, 1, 2)
264         )
265         imgs = torch.cat((imgs, c_predicted_paths.unsqueeze(1)), 1)
266
267     if score_paths is not None:
268         score_paths = score_paths.cpu()
269         c_score_paths = score_paths.unsqueeze(1).expand(-1, 3, -1, -1)
270         c_score_paths = (
271             c_score_paths * colors[4].reshape(1, 3, 1, 1)
272             + (1 - c_score_paths) * colors[0].reshape(1, 3, 1, 1)
273         ).long()
274         c_score_paths = c_score_paths * (mazes.unsqueeze(1) == v_empty) + c_mazes * (
275             mazes.unsqueeze(1) != v_empty
276         )
277         imgs = torch.cat((imgs, c_score_paths.unsqueeze(1)), 1)
278
279     # NxKxCxHxW
280     if path_correct is None:
281         path_correct = torch.zeros(imgs.size(0)) <= 1
282     path_correct = path_correct.cpu().long().view(-1, 1, 1, 1)
283     img = torch.tensor([224, 224, 224]).view(1, -1, 1, 1) * path_correct + torch.tensor(
284         [255, 0, 0]
285     ).view(1, -1, 1, 1) * (1 - path_correct)
286     img = img.expand(
287         -1, -1, imgs.size(3) + 2, 1 + imgs.size(1) * (1 + imgs.size(4))
288     ).clone()
289     for k in range(imgs.size(1)):
290         img[
291             :,
292             :,
293             1 : 1 + imgs.size(3),
294             1 + k * (1 + imgs.size(4)) : 1 + k * (1 + imgs.size(4)) + imgs.size(4),
295         ] = imgs[:, k]
296
297     img = img.float() / 255.0
298
299     torchvision.utils.save_image(img, name, nrow=4, padding=1, pad_value=224.0 / 256)
300
301
302 ######################################################################
303
304 if __name__ == "__main__":
305     device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
306     mazes, paths = create_maze_data(8)
307     mazes, paths = mazes.to(device), paths.to(device)
308     save_image("test.png", mazes, paths, paths)
309     print(path_correctness(mazes, paths))
310
311 ######################################################################