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_frame_sequences(self, nb):
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 return frame_sequences
115 def generate_token_sequences(self, nb):
116 frame_sequences = self.generate_frame_sequences(nb)
120 for frame_sequence in frame_sequences:
122 if torch.rand(1) < 0.5:
123 for frame in frame_sequence:
125 a.append(torch.tensor([self.token_forward]))
126 a.append(frame.flatten())
128 for frame in reversed(frame_sequence):
130 a.append(torch.tensor([self.token_backward]))
131 a.append(frame.flatten())
133 result.append(torch.cat(a, dim=0)[None, :])
135 return torch.cat(result, dim=0)
137 ######################################################################
139 def frame2img(self, x, scale=15):
140 x = x.reshape(-1, self.height, self.width)
141 m = torch.logical_and(
142 x >= 0, x < self.first_bird_token + self.nb_bird_tokens
144 x = self.colors[x * m].permute(0, 3, 1, 2)
146 x = x[:, :, :, None, :, None].expand(-1, -1, -1, scale, -1, scale)
147 x = x.reshape(s[0], s[1], s[2] * scale, s[3] * scale)
149 x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
150 x[:, :, torch.arange(0, x.size(2), scale), :] = 0
153 for n in range(m.size(0)):
154 for i in range(m.size(1)):
155 for j in range(m.size(2)):
157 for k in range(2, scale - 2):
159 x[n, :, i * scale + k, j * scale + k - l] = 0
161 n, :, i * scale + scale - 1 - k, j * scale + k - l
166 def seq2img(self, seq, scale=15):
169 seq[:, : self.height * self.width].reshape(-1, self.height, self.width),
174 separator = torch.full((seq.size(0), 3, self.height * scale - 1, 1), 0)
176 t = self.height * self.width
178 while t < seq.size(1):
179 direction_tokens = seq[:, t]
182 direction_images = self.colors[
184 (direction_tokens.size(0), self.height * scale - 1, scale), 0
186 ].permute(0, 3, 1, 2)
188 for n in range(direction_tokens.size(0)):
189 if direction_tokens[n] == self.token_forward:
190 for k in range(scale):
195 (self.height * scale) // 2 - scale // 2 + k - l,
196 3 + scale // 2 - abs(k - scale // 2),
198 elif direction_tokens[n] == self.token_backward:
199 for k in range(scale):
204 (self.height * scale) // 2 - scale // 2 + k - l,
205 3 + abs(k - scale // 2),
208 for k in range(2, scale - 2):
213 (self.height * scale) // 2 - scale // 2 + k - l,
219 (self.height * scale) // 2 - scale // 2 + k - l,
228 seq[:, t : t + self.height * self.width].reshape(
229 -1, self.height, self.width
235 t += self.height * self.width
237 return torch.cat(all, dim=3)
239 def seq2str(self, seq):
242 result.append("".join([self.token2char[v] for v in s]))
245 def save_image(self, input, result_dir, filename):
246 img = self.seq2img(input.to("cpu"))
247 image_name = os.path.join(result_dir, filename)
248 torchvision.utils.save_image(img.float() / 255.0, image_name, nrow=6, padding=4)
250 def save_quizzes(self, input, result_dir, filename_prefix):
251 self.save_image(input, result_dir, filename_prefix + ".png")
254 ######################################################################
256 if __name__ == "__main__":
259 sky = Sky(height=6, width=8, speed=1, nb_iterations=4)
261 start_time = time.perf_counter()
262 seq = sky.generate_frame_sequences(nb=64)
263 delay = time.perf_counter() - start_time
264 print(f"{seq.size(0)/delay:02f} seq/s")
266 # print(sky.seq2str(seq[:4]))
268 # for t in range(len(it[0])):
269 # img = torch.cat([sky.frame2img(f[t]) for f in it], dim=0)
270 # torchvision.utils.save_image(
271 # img.float() / 255.0,
272 # f"/tmp/frame_{t:03d}.png",
278 # m = (torch.rand(seq.size()) < 0.05).long()
279 # seq = (1 - m) * seq + m * 23
282 img = sky.seq2img(seq)
285 torchvision.utils.save_image(
286 img.float() / 255.0, "/tmp/world.png", nrow=6, padding=6, pad_value=0