diff --git a/bhv/visualization.py b/bhv/visualization.py index 7d7af01..7393c66 100644 --- a/bhv/visualization.py +++ b/bhv/visualization.py @@ -52,3 +52,9 @@ def pbm(self, file: 'IO[Any]', binary=False): for hv in self.hvs: file.write(hv.bitstring()) file.write('\n') + def gif(self, binary=False, H=100, W=100): + if binary: + return [b"P4\n" + bytes(str(W), "ascii") + b" " + bytes(str(H), "ascii") + b"\n" + hv.to_bytes() for hv in self.hvs] + + else: + raise NotImplementedError() diff --git a/examples/gol.py b/examples/gol.py index 81d210e..4a6f60f 100644 --- a/examples/gol.py +++ b/examples/gol.py @@ -2,6 +2,8 @@ # from bhv.native import NativePackedBHV as BHV from bhv.np import NumPyPacked64BHV as BHV from time import sleep, time_ns +import io +from PIL import Image as PImage init = [ @@ -166,8 +168,21 @@ def export(initial_viz: list[str], generations: int, filename: str): for _ in range(generations): petri_dish_history.append(step(petri_dish_history[-1])) - with open(filename, 'wb') as f: - Image(petri_dish_history).pbm(f, binary=True) + # with open(f"{filename}.pbm", 'wb') as f: + # Image(petri_dish_history).pbm(f, binary=True) + + t = Image(petri_dish_history).gif(binary=True, H=H, W=W) + frames = [PImage.open(io.BytesIO(frame)).convert('L') for frame in t] + + frames[0].save( + f"{filename}.gif", + save_all=True, + append_images=frames[1:], + duration=100, # Adjust the frame duration as needed + loop=0 + ) + + def benchmark(): @@ -190,5 +205,5 @@ def benchmark(): # run(init, 50) -benchmark() -# export(init, 8191, "../bhv/cnative/gol8192.pbm") +# benchmark() +export(init, 8191, "../bhv/cnative/gol8192.pbm")