98e2334e5f218bb21add43f982ee0783658c6e68
[culture.git] / wireworld.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 Physics(problem.Problem):
21     colors = torch.tensor(
22         [
23             [128, 128, 128],
24             [128, 128, 255],
25             [255, 0, 0],
26             [255, 255, 0],
27         ]
28     )
29
30     token_empty = 0
31     token_head = 1
32     token_tail = 2
33     token_conductor = 3
34     token_forward = 4
35     token_backward = 5
36
37     token2char = (
38         "_" + "".join([chr(ord("A") + n) for n in range(len(colors) - 1)]) + "><"
39     )
40
41     def __init__(
42         self, height=6, width=8, nb_objects=2, nb_walls=2, speed=1, nb_iterations=4
43     ):
44         self.height = height
45         self.width = width
46         self.nb_objects = nb_objects
47         self.nb_walls = nb_walls
48         self.speed = speed
49         self.nb_iterations = nb_iterations
50
51     def direction_tokens(self):
52         return self.token_forward, self.token_backward
53
54     def generate_frame_sequences(self, nb):
55         frame_sequences = []
56
57         result = torch.full(
58             (nb * 100, self.nb_iterations, self.height, self.width), self.token_empty
59         )
60
61         for n in range(result.size(0)):
62             while True:
63                 i = torch.randint(self.height, (1,))
64                 j = torch.randint(self.width, (1,))
65                 v = torch.randint(2, (2,))
66                 vi = v[0] * (v[1] * 2 - 1)
67                 vj = (1 - v[0]) * (v[1] * 2 - 1)
68                 while True:
69                     if i < 0 or i >= self.height or j < 0 or j >= self.width:
70                         break
71                     result[n, 0, i, j] = self.token_conductor
72                     i += vi
73                     j += vj
74                 if torch.rand(1) < 0.5:
75                     break
76
77         weight = torch.full((1, 1, 3, 3), 1.0)
78
79         mask = (torch.rand(result[:, 0].size()) < 0.01).long()
80         rand = torch.randint(4, mask.size())
81         result[:, 0] = mask * rand + (1 - mask) * result[:, 0]
82
83         # empty->empty
84         # head->tail
85         # tail->conductor
86         # conductor->head if 1 or 2 head in the neighborhood, or remains conductor
87
88         for l in range(self.nb_iterations - 1):
89             nb_head_neighbors = (
90                 F.conv2d(
91                     input=(result[:, l] == self.token_head).float()[:, None, :, :],
92                     weight=weight,
93                     padding=1,
94                 )
95                 .long()
96                 .squeeze(1)
97             )
98             mask_1_or_2_heads = (nb_head_neighbors == 1).long() + (
99                 nb_head_neighbors == 2
100             ).long()
101             result[:, l + 1] = (
102                 (result[:, l] == self.token_empty).long() * self.token_empty
103                 + (result[:, l] == self.token_head).long() * self.token_tail
104                 + (result[:, l] == self.token_tail).long() * self.token_conductor
105                 + (result[:, l] == self.token_conductor).long()
106                 * (
107                     mask_1_or_2_heads * self.token_head
108                     + (1 - mask_1_or_2_heads) * self.token_conductor
109                 )
110             )
111
112         i = (result[:, -1] == self.token_head).flatten(1).max(dim=1).values > 0
113
114         result = result[i]
115
116         if result.size(0) < nb:
117             print(result.size(0))
118             result = torch.cat(
119                 [result, self.generate_frame_sequences(nb - result.size(0))], dim=0
120             )
121
122         return result
123
124     def generate_token_sequences(self, nb):
125         frame_sequences = self.generate_frame_sequences(nb)
126
127         result = []
128
129         for frame_sequence in frame_sequences:
130             a = []
131             if torch.rand(1) < 0.5:
132                 for frame in frame_sequence:
133                     if len(a) > 0:
134                         a.append(torch.tensor([self.token_forward]))
135                     a.append(frame.flatten())
136             else:
137                 for frame in reversed(frame_sequence):
138                     if len(a) > 0:
139                         a.append(torch.tensor([self.token_backward]))
140                     a.append(frame.flatten())
141
142             result.append(torch.cat(a, dim=0)[None, :])
143
144         return torch.cat(result, dim=0)
145
146     ######################################################################
147
148     def frame2img(self, x, scale=15):
149         x = x.reshape(-1, self.height, self.width)
150         m = torch.logical_and(x >= 0, x < 4).long()
151
152         x = self.colors[x * m].permute(0, 3, 1, 2)
153         s = x.shape
154         x = x[:, :, :, None, :, None].expand(-1, -1, -1, scale, -1, scale)
155         x = x.reshape(s[0], s[1], s[2] * scale, s[3] * scale)
156
157         x[:, :, :, torch.arange(0, x.size(3), scale)] = 0
158         x[:, :, torch.arange(0, x.size(2), scale), :] = 0
159         x = x[:, :, 1:, 1:]
160
161         for n in range(m.size(0)):
162             for i in range(m.size(1)):
163                 for j in range(m.size(2)):
164                     if m[n, i, j] == 0:
165                         for k in range(2, scale - 2):
166                             for l in [0, 1]:
167                                 x[n, :, i * scale + k, j * scale + k - l] = 0
168                                 x[
169                                     n, :, i * scale + scale - 1 - k, j * scale + k - l
170                                 ] = 0
171
172         return x
173
174     def seq2img(self, seq, scale=15):
175         all = [
176             self.frame2img(
177                 seq[:, : self.height * self.width].reshape(-1, self.height, self.width),
178                 scale,
179             )
180         ]
181
182         separator = torch.full((seq.size(0), 3, self.height * scale - 1, 1), 0)
183
184         t = self.height * self.width
185
186         while t < seq.size(1):
187             direction_tokens = seq[:, t]
188             t += 1
189
190             direction_images = self.colors[
191                 torch.full(
192                     (direction_tokens.size(0), self.height * scale - 1, scale), 0
193                 )
194             ].permute(0, 3, 1, 2)
195
196             for n in range(direction_tokens.size(0)):
197                 if direction_tokens[n] == self.token_forward:
198                     for k in range(scale):
199                         for l in [0, 1]:
200                             direction_images[
201                                 n,
202                                 :,
203                                 (self.height * scale) // 2 - scale // 2 + k - l,
204                                 3 + scale // 2 - abs(k - scale // 2),
205                             ] = 0
206                 elif direction_tokens[n] == self.token_backward:
207                     for k in range(scale):
208                         for l in [0, 1]:
209                             direction_images[
210                                 n,
211                                 :,
212                                 (self.height * scale) // 2 - scale // 2 + k - l,
213                                 3 + abs(k - scale // 2),
214                             ] = 0
215                 else:
216                     for k in range(2, scale - 2):
217                         for l in [0, 1]:
218                             direction_images[
219                                 n,
220                                 :,
221                                 (self.height * scale) // 2 - scale // 2 + k - l,
222                                 k,
223                             ] = 0
224                             direction_images[
225                                 n,
226                                 :,
227                                 (self.height * scale) // 2 - scale // 2 + k - l,
228                                 scale - 1 - k,
229                             ] = 0
230
231             all += [
232                 separator,
233                 direction_images,
234                 separator,
235                 self.frame2img(
236                     seq[:, t : t + self.height * self.width].reshape(
237                         -1, self.height, self.width
238                     ),
239                     scale,
240                 ),
241             ]
242
243             t += self.height * self.width
244
245         return torch.cat(all, dim=3)
246
247     def seq2str(self, seq):
248         result = []
249         for s in seq:
250             result.append("".join([self.token2char[v] for v in s]))
251         return result
252
253     def save_image(self, input, result_dir, filename):
254         img = self.seq2img(input.to("cpu"))
255         image_name = os.path.join(result_dir, filename)
256         torchvision.utils.save_image(img.float() / 255.0, image_name, nrow=6, padding=4)
257
258     def save_quizzes(self, input, result_dir, filename_prefix):
259         self.save_image(input, result_dir, filename_prefix + ".png")
260
261
262 ######################################################################
263
264 if __name__ == "__main__":
265     import time
266
267     sky = Physics(height=10, width=15, speed=1, nb_iterations=100)
268
269     start_time = time.perf_counter()
270     frame_sequences = sky.generate_frame_sequences(nb=96)
271     delay = time.perf_counter() - start_time
272     print(f"{frame_sequences.size(0)/delay:02f} seq/s")
273
274     # print(sky.seq2str(seq[:4]))
275
276     for t in range(frame_sequences.size(1)):
277         img = sky.seq2img(frame_sequences[:, t])
278         torchvision.utils.save_image(
279             img.float() / 255.0,
280             f"/tmp/frame_{t:03d}.png",
281             nrow=8,
282             padding=6,
283             pad_value=0,
284         )
285
286     # m = (torch.rand(seq.size()) < 0.05).long()
287     # seq = (1 - m) * seq + m * 23
288
289     # img = sky.seq2img(frame_sequences[:60])
290
291     # torchvision.utils.save_image(
292     # img.float() / 255.0, "/tmp/world.png", nrow=6, padding=10, pad_value=0.1
293     # )