3 # Any copyright is dedicated to the Public Domain.
4 # https://creativecommons.org/publicdomain/zero/1.0/
6 # Written by Francois Fleuret <francois@fleuret.org>
8 import math, sys, tqdm, os
10 import torch, torchvision
13 from torch.nn import functional as F
15 ######################################################################
20 class Sky(problem.Problem):
21 colors = torch.tensor(
39 nb_bird_tokens = colors.size(0) - 1
40 token_forward = first_bird_token + nb_bird_tokens
41 token_backward = token_forward + 1
44 "_" + "".join([chr(ord("A") + n) for n in range(len(colors) - 1)]) + "><"
58 self.nb_birds = nb_birds
60 self.nb_iterations = nb_iterations
61 self.avoid_collision = avoid_collision
63 def direction_tokens(self):
64 return self.token_forward, self.token_backward
66 def generate_frame_sequences(self, nb):
69 for _ in tqdm.tqdm(range(nb), dynamic_ncols=True, desc="world generation"):
71 torch.empty(self.nb_birds, dtype=torch.int64),
72 torch.empty(self.nb_birds, dtype=torch.int64),
73 torch.empty(self.nb_birds, dtype=torch.int64),
74 torch.empty(self.nb_birds, dtype=torch.int64),
78 if not self.avoid_collision:
81 count = torch.zeros(self.height, self.width, dtype=torch.int64)
83 for n in range(self.nb_birds):
84 count[i[n], j[n]] += 1
85 count[i[n] - vi[n], j[n]] += 1
86 count[i[n], j[n] - vj[n]] += 1
88 return count.max() <= 1
91 torch.randperm(self.colors.size(0) - 1)[: self.nb_birds].sort().values
97 for n in range(self.nb_birds):
99 i[n] = torch.randint(self.height, (1,))
100 j[n] = torch.randint(self.width, (1,))
101 vm = torch.randint(4, (1,))
102 vi[n], vj[n] = (vm % 2) * 2 - 1, (vm // 2) * 2 - 1
105 and i[n] - vi[n] < self.height
106 and j[n] - vj[n] >= 0
107 and j[n] - vj[n] < self.width
114 result = torch.zeros(
115 self.nb_iterations, self.height, self.width, dtype=torch.int64
118 for l in range(self.nb_iterations):
119 fine = collision_okay()
120 for n in range(self.nb_birds):
122 result[l, i[n], j[n]] = c
123 result[l, i[n] - vi[n], j[n]] = c
124 result[l, i[n], j[n] - vj[n]] = c
126 if (i[n] == 0 and vi[n] == -1) or (
127 i[n] == self.height - 1 and vi[n] == 1
131 if (j[n] == 0 and vj[n] == -1) or (
132 j[n] == self.width - 1 and vj[n] == 1
142 frame_sequences.append(result)
144 return frame_sequences
146 ######################################################################
148 def generate_token_sequences(self, nb):
149 frame_sequences = self.generate_frame_sequences(nb)
153 for frame_sequence in frame_sequences:
155 if torch.rand(1) < 0.5:
156 for frame in frame_sequence:
158 a.append(torch.tensor([self.token_forward]))
159 a.append(frame.flatten())
161 for frame in reversed(frame_sequence):
163 a.append(torch.tensor([self.token_backward]))
164 a.append(frame.flatten())
166 result.append(torch.cat(a, dim=0)[None, :])
168 return torch.cat(result, dim=0)
170 ######################################################################
172 def frame2img(self, x, scale=15):
173 x = x.reshape(-1, self.height, self.width)
174 m = torch.logical_and(
175 x >= 0, x < self.first_bird_token + self.nb_bird_tokens
177 x = self.colors[x * m].permute(0, 3, 1, 2)
179 x = x[:, :, :, None, :, None].expand(-1, -1, -1, scale, -1, scale)
180 x = x.reshape(s[0], s[1], s[2] * scale, s[3] * scale)
182 x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
183 x[:, :, torch.arange(0, x.size(2), scale), :] = 0
186 for n in range(m.size(0)):
187 for i in range(m.size(1)):
188 for j in range(m.size(2)):
190 for k in range(2, scale - 2):
192 x[n, :, i * scale + k, j * scale + k - l] = 0
194 n, :, i * scale + scale - 1 - k, j * scale + k - l
199 def seq2img(self, seq, scale=15):
202 seq[:, : self.height * self.width].reshape(-1, self.height, self.width),
207 separator = torch.full((seq.size(0), 3, self.height * scale - 1, 1), 0)
209 t = self.height * self.width
211 while t < seq.size(1):
212 direction_tokens = seq[:, t]
215 direction_images = self.colors[
217 (direction_tokens.size(0), self.height * scale - 1, scale), 0
219 ].permute(0, 3, 1, 2)
221 for n in range(direction_tokens.size(0)):
222 if direction_tokens[n] == self.token_forward:
223 for k in range(scale):
228 (self.height * scale) // 2 - scale // 2 + k - l,
229 3 + scale // 2 - abs(k - scale // 2),
231 elif direction_tokens[n] == self.token_backward:
232 for k in range(scale):
237 (self.height * scale) // 2 - scale // 2 + k - l,
238 3 + abs(k - scale // 2),
241 for k in range(2, scale - 2):
246 (self.height * scale) // 2 - scale // 2 + k - l,
252 (self.height * scale) // 2 - scale // 2 + k - l,
261 seq[:, t : t + self.height * self.width].reshape(
262 -1, self.height, self.width
268 t += self.height * self.width
270 return torch.cat(all, dim=3)
272 def seq2str(self, seq):
275 result.append("".join([self.token2char[v] for v in s]))
278 def save_image(self, input, result_dir, filename):
279 img = self.seq2img(input.to("cpu"))
280 image_name = os.path.join(result_dir, filename)
281 torchvision.utils.save_image(img.float() / 255.0, image_name, nrow=6, padding=4)
283 def save_quizzes(self, input, result_dir, filename_prefix):
284 self.save_image(input, result_dir, filename_prefix + ".png")
287 ######################################################################
289 if __name__ == "__main__":
292 sky = Sky(height=6, width=8, speed=2, nb_iterations=2)
294 start_time = time.perf_counter()
295 token_sequences = sky.generate_token_sequences(nb=64)
296 delay = time.perf_counter() - start_time
297 print(f"{token_sequences.size(0)/delay:02f} seq/s")
299 # print(sky.seq2str(seq[:4]))
301 # for t in range(len(it[0])):
302 # img = torch.cat([sky.frame2img(f[t]) for f in it], dim=0)
303 # torchvision.utils.save_image(
304 # img.float() / 255.0,
305 # f"/tmp/frame_{t:03d}.png",
311 # m = (torch.rand(seq.size()) < 0.05).long()
312 # seq = (1 - m) * seq + m * 23
315 img = sky.seq2img(token_sequences)
318 torchvision.utils.save_image(
319 img.float() / 255.0, "/tmp/world.png", nrow=6, padding=6, pad_value=0