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, i, j):
65     max_length = walls.numel()
66     dist = torch.full_like(walls, max_length)
67
68     dist[i, 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, i, j):
97     distance = compute_distance(walls, i, 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:, :]
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 ######################################################################
114
115
116 def mark_path(walls, i, j, goal_i, goal_j):
117     policy = compute_policy(walls, goal_i, goal_j)
118     action = torch.distributions.categorical.Categorical(
119         policy.permute(1, 2, 0)
120     ).sample()
121     walls[i, j] = 4
122     n, nmax = 0, walls.numel()
123     while i != goal_i or j != goal_j:
124         di, dj = [(0, -1), (0, 1), (-1, 0), (1, 0)][action[i, j]]
125         i, j = i + di, j + dj
126         assert walls[i, j] == 0
127         walls[i, j] = 4
128         n += 1
129         assert n < nmax
130
131
132 def path_correctness(mazes, paths):
133     still_ok = (mazes - (paths * (paths < 4))).view(mazes.size(0), -1).abs().sum(1) == 0
134     reached = still_ok.new_zeros(still_ok.size())
135     current, pred_current = paths.clone(), paths.new_zeros(paths.size())
136     goal = (mazes == v_goal).long()
137     while not pred_current.equal(current):
138         pred_current.copy_(current)
139         u = (current == v_start).long()
140         possible_next = (
141             u[:, 2:, 1:-1] + u[:, 0:-2, 1:-1] + u[:, 1:-1, 2:] + u[:, 1:-1, 0:-2] > 0
142         ).long()
143         u = u[:, 1:-1, 1:-1]
144         reached += ((goal[:, 1:-1, 1:-1] * possible_next).sum((1, 2)) == 1) * (
145             (current == v_path).sum((1, 2)) == 0
146         )
147         current[:, 1:-1, 1:-1] = (1 - u) * current[:, 1:-1, 1:-1] + (
148             v_start - v_path
149         ) * (possible_next * (current[:, 1:-1, 1:-1] == v_path))
150         still_ok *= (current == v_start).sum((1, 2)) <= 1
151
152     return still_ok * reached
153
154
155 ######################################################################
156
157
158 def create_maze_data(
159     nb, height=11, width=17, nb_walls=8, dist_min=10, progress_bar=lambda x: x
160 ):
161     mazes = torch.empty(nb, height, width, dtype=torch.int64)
162     paths = torch.empty(nb, height, width, dtype=torch.int64)
163
164     for n in progress_bar(range(nb)):
165         maze = create_maze(height, width, nb_walls)
166         i = (1 - maze).nonzero()
167         while True:
168             start, goal = i[torch.randperm(i.size(0))[:2]]
169             if (start - goal).abs().sum() >= dist_min:
170                 break
171
172         path = maze.clone()
173         mark_path(path, start[0], start[1], goal[0], goal[1])
174         maze[start[0], start[1]] = v_start
175         maze[goal[0], goal[1]] = v_goal
176         path[start[0], start[1]] = v_start
177         path[goal[0], goal[1]] = v_goal
178
179         mazes[n] = maze
180         paths[n] = path
181
182     return mazes, paths
183
184
185 ######################################################################
186
187
188 def save_image(name, mazes, target_paths, predicted_paths=None, path_correct=None):
189     mazes, target_paths = mazes.cpu(), target_paths.cpu()
190
191     colors = torch.tensor(
192         [
193             [255, 255, 255],  # empty
194             [0, 0, 0],  # wall
195             [0, 255, 0],  # start
196             [0, 0, 255],  # goal
197             [255, 0, 0],  # path
198         ]
199     )
200
201     mazes = colors[mazes.reshape(-1)].reshape(mazes.size() + (-1,)).permute(0, 3, 1, 2)
202     target_paths = (
203         colors[target_paths.reshape(-1)]
204         .reshape(target_paths.size() + (-1,))
205         .permute(0, 3, 1, 2)
206     )
207     imgs = torch.cat((mazes.unsqueeze(1), target_paths.unsqueeze(1)), 1)
208
209     if predicted_paths is not None:
210         predicted_paths = predicted_paths.cpu()
211         predicted_paths = (
212             colors[predicted_paths.reshape(-1)]
213             .reshape(predicted_paths.size() + (-1,))
214             .permute(0, 3, 1, 2)
215         )
216         imgs = torch.cat((imgs, predicted_paths.unsqueeze(1)), 1)
217
218     # NxKxCxHxW
219     if path_correct is None:
220         path_correct = torch.zeros(imgs.size(0)) <= 1
221     path_correct = path_correct.cpu().long().view(-1, 1, 1, 1)
222     img = torch.tensor([224, 224, 224]).view(1, -1, 1, 1) * path_correct + torch.tensor(
223         [255, 0, 0]
224     ).view(1, -1, 1, 1) * (1 - path_correct)
225     img = img.expand(
226         -1, -1, imgs.size(3) + 2, 1 + imgs.size(1) * (1 + imgs.size(4))
227     ).clone()
228     for k in range(imgs.size(1)):
229         img[
230             :,
231             :,
232             1 : 1 + imgs.size(3),
233             1 + k * (1 + imgs.size(4)) : 1 + k * (1 + imgs.size(4)) + imgs.size(4),
234         ] = imgs[:, k]
235
236     img = img.float() / 255.0
237
238     torchvision.utils.save_image(img, name, nrow=4, padding=1, pad_value=224.0 / 256)
239
240
241 ######################################################################
242
243 if __name__ == "__main__":
244
245     device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
246     mazes, paths = create_maze_data(8)
247     mazes, paths = mazes.to(device), paths.to(device)
248     save_image("test.png", mazes, paths, paths)
249     print(path_correctness(mazes, paths))
250
251 ######################################################################