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)]) + "><"
47 def __init__(self, height=6, width=8, nb_birds=3, speed=1, nb_iterations=4):
50 self.nb_birds = nb_birds
52 self.nb_iterations = nb_iterations
54 def direction_tokens(self):
55 return self.token_forward, self.token_backward
57 def generate_seq(self, nb, return_frame_sequences=False):
60 for _ in tqdm.tqdm(range(nb), dynamic_ncols=True, desc="world generation"):
62 self.nb_iterations, self.height, self.width, dtype=torch.int64
66 torch.empty(self.nb_birds, dtype=torch.int64),
67 torch.empty(self.nb_birds, dtype=torch.int64),
68 torch.empty(self.nb_birds, dtype=torch.int64),
69 torch.empty(self.nb_birds, dtype=torch.int64),
73 torch.randperm(self.colors.size(0) - 1)[: self.nb_birds].sort().values
77 for n in range(self.nb_birds):
79 i[n] = torch.randint(self.height, (1,))
80 j[n] = torch.randint(self.width, (1,))
81 vm = torch.randint(4, (1,))
82 vi[n], vj[n] = (vm % 2) * 2 - 1, (vm // 2) * 2 - 1
85 and i[n] - vi[n] < self.height
87 and j[n] - vj[n] < self.width
91 for l in range(self.nb_iterations):
92 for n in range(self.nb_birds):
94 result[l, i[n], j[n]] = c
95 result[l, i[n] - vi[n], j[n]] = c
96 result[l, i[n], j[n] - vj[n]] = c
98 if (i[n] == 0 and vi[n] == -1) or (
99 i[n] == self.height - 1 and vi[n] == 1
103 if (j[n] == 0 and vj[n] == -1) or (
104 j[n] == self.width - 1 and vj[n] == 1
111 frame_sequences.append(result)
113 if return_frame_sequences:
114 return frame_sequences
116 # Randomize the time direction, annd convert to token
117 # sequences with the time direction tokens added
121 for frame_sequence in frame_sequences:
123 if torch.rand(1) < 0.5:
124 for frame in frame_sequence:
126 a.append(torch.tensor([self.token_forward]))
127 a.append(frame.flatten())
129 for frame in reversed(frame_sequence):
131 a.append(torch.tensor([self.token_backward]))
132 a.append(frame.flatten())
134 result.append(torch.cat(a, dim=0)[None, :])
136 return torch.cat(result, dim=0)
138 ######################################################################
140 def frame2img(self, x, scale=15):
141 x = x.reshape(-1, self.height, self.width)
142 m = torch.logical_and(
143 x >= 0, x < self.first_bird_token + self.nb_bird_tokens
145 x = self.colors[x * m].permute(0, 3, 1, 2)
147 x = x[:, :, :, None, :, None].expand(-1, -1, -1, scale, -1, scale)
148 x = x.reshape(s[0], s[1], s[2] * scale, s[3] * scale)
150 x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
151 x[:, :, torch.arange(0, x.size(2), scale), :] = 0
154 for n in range(m.size(0)):
155 for i in range(m.size(1)):
156 for j in range(m.size(2)):
158 for k in range(2, scale - 2):
160 x[n, :, i * scale + k, j * scale + k - l] = 0
162 n, :, i * scale + scale - 1 - k, j * scale + k - l
167 def seq2img(self, seq, scale=15):
170 seq[:, : self.height * self.width].reshape(-1, self.height, self.width),
175 separator = torch.full((seq.size(0), 3, self.height * scale - 1, 1), 0)
177 t = self.height * self.width
179 while t < seq.size(1):
180 direction_tokens = seq[:, t]
183 direction_images = self.colors[
185 (direction_tokens.size(0), self.height * scale - 1, scale), 0
187 ].permute(0, 3, 1, 2)
189 for n in range(direction_tokens.size(0)):
190 if direction_tokens[n] == self.token_forward:
191 for k in range(scale):
196 (self.height * scale) // 2 - scale // 2 + k - l,
197 3 + scale // 2 - abs(k - scale // 2),
199 elif direction_tokens[n] == self.token_backward:
200 for k in range(scale):
205 (self.height * scale) // 2 - scale // 2 + k - l,
206 3 + abs(k - scale // 2),
209 for k in range(2, scale - 2):
214 (self.height * scale) // 2 - scale // 2 + k - l,
220 (self.height * scale) // 2 - scale // 2 + k - l,
229 seq[:, t : t + self.height * self.width].reshape(
230 -1, self.height, self.width
236 t += self.height * self.width
238 return torch.cat(all, dim=3)
240 def seq2str(self, seq):
243 result.append("".join([self.token2char[v] for v in s]))
246 def save_image(self, input, result_dir, filename):
247 img = self.seq2img(input.to("cpu"))
248 image_name = os.path.join(result_dir, filename)
249 torchvision.utils.save_image(img.float() / 255.0, image_name, nrow=6, padding=4)
251 def save_quizzes(self, input, result_dir, filename_prefix):
252 self.save_image(input, result_dir, filename_prefix + ".png")
255 ######################################################################
257 if __name__ == "__main__":
260 sky = Sky(height=6, width=8, speed=1, nb_iterations=4)
262 start_time = time.perf_counter()
263 seq = sky.generate_seq(nb=64)
264 delay = time.perf_counter() - start_time
265 print(f"{seq.size(0)/delay:02f} seq/s")
267 # print(sky.seq2str(seq[:4]))
269 # for t in range(len(it[0])):
270 # img = torch.cat([sky.frame2img(f[t]) for f in it], dim=0)
271 # torchvision.utils.save_image(
272 # img.float() / 255.0,
273 # f"/tmp/frame_{t:03d}.png",
279 # m = (torch.rand(seq.size()) < 0.05).long()
280 # seq = (1 - m) * seq + m * 23
283 img = sky.seq2img(seq)
286 torchvision.utils.save_image(
287 img.float() / 255.0, "/tmp/world.png", nrow=6, padding=6, pad_value=0