Skip to content

Commit

Permalink
Autogenerate paths while saving
Browse files Browse the repository at this point in the history
Improve `save` method in `AbstractAnimator`.
  • Loading branch information
NISH1001 committed Jan 17, 2021
1 parent 860173a commit 1f9407a
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 15 deletions.
54 changes: 48 additions & 6 deletions panim/animator.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
#!/usr/bin/env python3

import os

import copy
import time

Expand All @@ -11,6 +13,10 @@

import numpy as np

from loguru import logger

from .utils import IAmTime, create_directory

plt.style.use("dark_background")


Expand Down Expand Up @@ -60,7 +66,7 @@ def _animate(self, i):
of (X, Y) values
"""
if self.verbose:
print("Frame {}/{}".format(i, self.num_frames))
print("Frame {i}/{self.num_frames}")
res = self.update(i)
if type(res) is list:
for j, img in enumerate(self.img):
Expand All @@ -84,13 +90,49 @@ def animate(self, num_frames=1000):
repeat=False,
)

def save(self, filename="out/animation.mp4", fps=30, dpi=100):
def save(
self, filename: str = None, prefix: str = "", fps: int = 30, dpi: int = 100
):
start = time.time()
writer = animation.writers["ffmpeg"](fps=fps)
cname = self.__class__.__name__ if not prefix else prefix

iat = IAmTime()
if not filename:
outdir = self.autogenerate_path()
filename = f"{cname}-{iat.year}-{iat.month}-{iat.day}--{iat.hour}.{iat.minute}.{iat.second}.mp4"
if prefix:
filename = f"{prefix}-{filename}"
create_directory(outdir)
filename = os.path.join(outdir, filename)
else:
basedir = os.path.dirname(filename)
if not basedir or not basedir.startswith("out"):
basedir = "out/"
create_directory(basedir)

_, ext = os.path.splitext(filename)
if ext and ext != ".mp4":
raise ValueError(f"(filename={filename}). Extension has to be mp4")

if not ext:
ext = ".mp4"

basename, _ = os.path.splitext(os.path.basename(filename))
fname = f"{cname}-{basename}{ext}"
filename = os.path.join(basedir, fname)

# self.anim.save(filename, writer='imagemagick')
print("Saving {} to {}".format(self.__class__.__name__, filename))
logger.info(f"Saving {cname} to {filename}")
writer = animation.writers["ffmpeg"](fps=fps)
self.anim.save(filename, writer=writer, dpi=dpi)
print(f"Time Taken = {time.time() - start} seconds")
logger.debug(f"Time Taken = {time.time() - start} seconds")

def autogenerate_path(self):
iat = IAmTime()
basepath = "out/"
cname = self.__class__.__name__
timepath = f"{iat.year}--{iat.month}"
return os.path.join(basepath, cname, timepath)

def copy(self):
return copy.copy(self)
Expand Down Expand Up @@ -148,7 +190,7 @@ def __init__(self, **args):
self.image = plt.imshow(self.array, animated=True)

def _animate(self, i):
print("Frame {}/{}".format(i, self.num_frames))
print(f"Frame {i}/{self.num_frames}")
array = self.update(i)
self.image.set_array(array)
return (self.image,)
Expand Down
21 changes: 12 additions & 9 deletions panim/experiments.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@
from abc import ABCMeta, ABC, abstractmethod
from abc import ABC, abstractmethod


import numpy as np

from loguru import logger

from panim.animator import AbstractAnimator, AbstractImageAnimator

from panim.spiral import SpiralAnimator
Expand Down Expand Up @@ -45,7 +48,6 @@ def f(self, x, y):
return np.sin(x) + np.cos(y)

def update(self, i):
print(i)
# self.x += np.pi / 15.
# self.y += np.pi / 20.
self.img += 10
Expand Down Expand Up @@ -240,8 +242,8 @@ def __init__(self, nballs=5, **kwargs):
# velocity
self.balls["direction"] = np.random.choice([-1, 0.5, 1], (nballs, 2)) * 2.5

r = np.mean(self.image_size) // 10
print(f"Max radius = {r}")
r = np.mean(self.image_size) // 13
logger.info(f"Max radius = {r}")
self.balls["radius"] = np.random.randint(5, r, (nballs,))
self.array = np.zeros((self.image_size[1], self.image_size[0]))

Expand Down Expand Up @@ -273,7 +275,6 @@ def _generate_all_points_within(self, center, radius, npoints=10):
return xs, ys

def update(self, i):
print(i)
arr = np.zeros_like(self.array)
nr, nc = arr.shape
# xs = np.arange(0, nc, 1)
Expand Down Expand Up @@ -324,12 +325,14 @@ def update(self, i):

# x < 0, set direction +ve
if center[0] - radius < 0:
direction[0] *= np.random.uniform(0.5, 1, (1,))
# direction[0] *= np.random.uniform(0.5, 1, (1,))
direction[0] *= np.random.uniform(-1, -0.5, (1,))
center[0] = radius

# y < 0, set direction +ve
if center[1] - radius < 0:
direction[1] *= np.random.uniform(0.5, 1, (1,))
# direction[1] *= np.random.uniform(0.5, 1, (1,))
direction[1] *= np.random.uniform(-1, -0.5, (1,))
center[1] = radius

self.balls["direction"][i] = direction
Expand Down Expand Up @@ -361,10 +364,10 @@ def main():
# n=11,
# )
# animator = MetaBall4(nballs=5, width=200, height=200)
animator = MetaBall4(nballs=15, width=500, height=500)
print(animator)
animator = MetaBall4(nballs=15, width=500, height=400)
logger.info(animator)
animator.animate(500)
animator.save("out/metaballs-fps-24-balls-20.mp4", fps=24)
animator.save(fps=24)


if __name__ == "__main__":
Expand Down

0 comments on commit 1f9407a

Please sign in to comment.