Update.
[culture.git] / sky.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 math, sys, tqdm, os
9
10 import torch, torchvision
11
12 from torch import nn
13 from torch.nn import functional as F
14
15 ######################################################################
16
17 import problem
18
19
20 class Sky(problem.Problem):
21     colors = torch.tensor(
22         [
23             [255, 255, 255],
24             [255, 0, 0],
25             [0, 192, 0],
26             [0, 0, 255],
27             [255, 192, 0],
28             [0, 255, 255],
29             [255, 0, 255],
30             [192, 255, 192],
31             [255, 192, 192],
32             [192, 192, 255],
33             [192, 192, 192],
34         ]
35     )
36
37     token_background = 0
38     first_bird_token = 1
39     nb_bird_tokens = colors.size(0) - 1
40     token_forward = first_bird_token + nb_bird_tokens
41     token_backward = token_forward + 1
42
43     token2char = (
44         "_" + "".join([chr(ord("A") + n) for n in range(len(colors) - 1)]) + "><"
45     )
46
47     def __init__(
48         self,
49         height=6,
50         width=8,
51         nb_birds=3,
52         speed=2,
53         nb_iterations=2,
54         avoid_collision=True,
55     ):
56         self.height = height
57         self.width = width
58         self.nb_birds = nb_birds
59         self.speed = speed
60         self.nb_iterations = nb_iterations
61         self.avoid_collision = avoid_collision
62
63     def direction_tokens(self):
64         return self.token_forward, self.token_backward
65
66     def generate_frame_sequences(self, nb):
67         frame_sequences = []
68
69         for _ in tqdm.tqdm(range(nb), dynamic_ncols=True, desc="world generation"):
70             i, j, vi, vj = (
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),
75             )
76
77             def collision_okay():
78                 if not self.avoid_collision:
79                     return True
80
81                 count = torch.zeros(self.height, self.width, dtype=torch.int64)
82
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
87
88                 return count.max() <= 1
89
90             col = (
91                 torch.randperm(self.colors.size(0) - 1)[: self.nb_birds].sort().values
92                 + 1
93             )
94
95             while True:
96                 while True:
97                     for n in range(self.nb_birds):
98                         while True:
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
103                             if (
104                                 i[n] - vi[n] >= 0
105                                 and i[n] - vi[n] < self.height
106                                 and j[n] - vj[n] >= 0
107                                 and j[n] - vj[n] < self.width
108                             ):
109                                 break
110
111                     if collision_okay():
112                         break
113
114                 result = torch.zeros(
115                     self.nb_iterations * self.speed,
116                     self.height,
117                     self.width,
118                     dtype=torch.int64,
119                 )
120
121                 for l in range(self.nb_iterations * self.speed):
122                     fine = collision_okay()
123                     for n in range(self.nb_birds):
124                         c = col[n]
125                         result[l, i[n], j[n]] = c
126                         result[l, i[n] - vi[n], j[n]] = c
127                         result[l, i[n], j[n] - vj[n]] = c
128
129                         if (i[n] == 0 and vi[n] == -1) or (
130                             i[n] == self.height - 1 and vi[n] == 1
131                         ):
132                             vi[n] = -vi[n]
133
134                         if (j[n] == 0 and vj[n] == -1) or (
135                             j[n] == self.width - 1 and vj[n] == 1
136                         ):
137                             vj[n] = -vj[n]
138
139                         i[n] += vi[n]
140                         j[n] += vj[n]
141
142                 if fine:
143                     break
144
145             frame_sequences.append(
146                 result[
147                     torch.arange(self.nb_iterations, device=result.device) * self.speed
148                 ]
149             )
150
151         return frame_sequences
152
153     ######################################################################
154
155     def generate_token_sequences(self, nb):
156         frame_sequences = self.generate_frame_sequences(nb)
157
158         result = []
159
160         for frame_sequence in frame_sequences:
161             a = []
162             if torch.rand(1) < 0.5:
163                 for frame in frame_sequence:
164                     if len(a) > 0:
165                         a.append(torch.tensor([self.token_forward]))
166                     a.append(frame.flatten())
167             else:
168                 for frame in reversed(frame_sequence):
169                     if len(a) > 0:
170                         a.append(torch.tensor([self.token_backward]))
171                     a.append(frame.flatten())
172
173             result.append(torch.cat(a, dim=0)[None, :])
174
175         return torch.cat(result, dim=0)
176
177     ######################################################################
178
179     def frame2img(self, x, scale=15):
180         x = x.reshape(-1, self.height, self.width)
181         m = torch.logical_and(
182             x >= 0, x < self.first_bird_token + self.nb_bird_tokens
183         ).long()
184         x = self.colors[x * m].permute(0, 3, 1, 2)
185         s = x.shape
186         x = x[:, :, :, None, :, None].expand(-1, -1, -1, scale, -1, scale)
187         x = x.reshape(s[0], s[1], s[2] * scale, s[3] * scale)
188
189         x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
190         x[:, :, torch.arange(0, x.size(2), scale), :] = 0
191         x = x[:, :, 1:, 1:]
192
193         for n in range(m.size(0)):
194             for i in range(m.size(1)):
195                 for j in range(m.size(2)):
196                     if m[n, i, j] == 0:
197                         for k in range(2, scale - 2):
198                             for l in [0, 1]:
199                                 x[n, :, i * scale + k, j * scale + k - l] = 0
200                                 x[
201                                     n, :, i * scale + scale - 1 - k, j * scale + k - l
202                                 ] = 0
203
204         return x
205
206     def seq2img(self, seq, scale=15):
207         all = [
208             self.frame2img(
209                 seq[:, : self.height * self.width].reshape(-1, self.height, self.width),
210                 scale,
211             )
212         ]
213
214         separator = torch.full((seq.size(0), 3, self.height * scale - 1, 1), 0)
215
216         t = self.height * self.width
217
218         while t < seq.size(1):
219             direction_tokens = seq[:, t]
220             t += 1
221
222             direction_images = self.colors[
223                 torch.full(
224                     (direction_tokens.size(0), self.height * scale - 1, scale), 0
225                 )
226             ].permute(0, 3, 1, 2)
227
228             for n in range(direction_tokens.size(0)):
229                 if direction_tokens[n] == self.token_forward:
230                     for k in range(scale):
231                         for l in [0, 1]:
232                             direction_images[
233                                 n,
234                                 :,
235                                 (self.height * scale) // 2 - scale // 2 + k - l,
236                                 3 + scale // 2 - abs(k - scale // 2),
237                             ] = 0
238                 elif direction_tokens[n] == self.token_backward:
239                     for k in range(scale):
240                         for l in [0, 1]:
241                             direction_images[
242                                 n,
243                                 :,
244                                 (self.height * scale) // 2 - scale // 2 + k - l,
245                                 3 + abs(k - scale // 2),
246                             ] = 0
247                 else:
248                     for k in range(2, scale - 2):
249                         for l in [0, 1]:
250                             direction_images[
251                                 n,
252                                 :,
253                                 (self.height * scale) // 2 - scale // 2 + k - l,
254                                 k,
255                             ] = 0
256                             direction_images[
257                                 n,
258                                 :,
259                                 (self.height * scale) // 2 - scale // 2 + k - l,
260                                 scale - 1 - k,
261                             ] = 0
262
263             all += [
264                 separator,
265                 direction_images,
266                 separator,
267                 self.frame2img(
268                     seq[:, t : t + self.height * self.width].reshape(
269                         -1, self.height, self.width
270                     ),
271                     scale,
272                 ),
273             ]
274
275             t += self.height * self.width
276
277         return torch.cat(all, dim=3)
278
279     def seq2str(self, seq):
280         result = []
281         for s in seq:
282             result.append("".join([self.token2char[v] for v in s]))
283         return result
284
285     def save_image(self, input, result_dir, filename):
286         img = self.seq2img(input.to("cpu"))
287         image_name = os.path.join(result_dir, filename)
288         torchvision.utils.save_image(img.float() / 255.0, image_name, nrow=6, padding=4)
289
290     def save_quizzes(self, input, result_dir, filename_prefix):
291         self.save_image(input, result_dir, filename_prefix + ".png")
292
293
294 ######################################################################
295
296 if __name__ == "__main__":
297     import time
298
299     sky = Sky(height=6, width=8, speed=2, nb_iterations=2)
300
301     start_time = time.perf_counter()
302     token_sequences = sky.generate_token_sequences(nb=64)
303     delay = time.perf_counter() - start_time
304     print(f"{token_sequences.size(0)/delay:02f} seq/s")
305
306     # print(sky.seq2str(seq[:4]))
307
308     # for t in range(len(it[0])):
309     # img = torch.cat([sky.frame2img(f[t]) for f in it], dim=0)
310     # torchvision.utils.save_image(
311     # img.float() / 255.0,
312     # f"/tmp/frame_{t:03d}.png",
313     # nrow=8,
314     # padding=6,
315     # pad_value=0,
316     # )
317
318     # m = (torch.rand(seq.size()) < 0.05).long()
319     # seq = (1 - m) * seq + m * 23
320
321     # print(seq.size())
322     img = sky.seq2img(token_sequences)
323     # print(img.size())
324
325     torchvision.utils.save_image(
326         img.float() / 255.0, "/tmp/world.png", nrow=6, padding=6, pad_value=0
327     )