Skip to content

Commit 1f9407a

Browse files
committed
Autogenerate paths while saving
Improve `save` method in `AbstractAnimator`.
1 parent 860173a commit 1f9407a

File tree

2 files changed

+60
-15
lines changed

2 files changed

+60
-15
lines changed

panim/animator.py

Lines changed: 48 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#!/usr/bin/env python3
22

3+
import os
4+
35
import copy
46
import time
57

@@ -11,6 +13,10 @@
1113

1214
import numpy as np
1315

16+
from loguru import logger
17+
18+
from .utils import IAmTime, create_directory
19+
1420
plt.style.use("dark_background")
1521

1622

@@ -60,7 +66,7 @@ def _animate(self, i):
6066
of (X, Y) values
6167
"""
6268
if self.verbose:
63-
print("Frame {}/{}".format(i, self.num_frames))
69+
print("Frame {i}/{self.num_frames}")
6470
res = self.update(i)
6571
if type(res) is list:
6672
for j, img in enumerate(self.img):
@@ -84,13 +90,49 @@ def animate(self, num_frames=1000):
8490
repeat=False,
8591
)
8692

87-
def save(self, filename="out/animation.mp4", fps=30, dpi=100):
93+
def save(
94+
self, filename: str = None, prefix: str = "", fps: int = 30, dpi: int = 100
95+
):
8896
start = time.time()
89-
writer = animation.writers["ffmpeg"](fps=fps)
97+
cname = self.__class__.__name__ if not prefix else prefix
98+
99+
iat = IAmTime()
100+
if not filename:
101+
outdir = self.autogenerate_path()
102+
filename = f"{cname}-{iat.year}-{iat.month}-{iat.day}--{iat.hour}.{iat.minute}.{iat.second}.mp4"
103+
if prefix:
104+
filename = f"{prefix}-{filename}"
105+
create_directory(outdir)
106+
filename = os.path.join(outdir, filename)
107+
else:
108+
basedir = os.path.dirname(filename)
109+
if not basedir or not basedir.startswith("out"):
110+
basedir = "out/"
111+
create_directory(basedir)
112+
113+
_, ext = os.path.splitext(filename)
114+
if ext and ext != ".mp4":
115+
raise ValueError(f"(filename={filename}). Extension has to be mp4")
116+
117+
if not ext:
118+
ext = ".mp4"
119+
120+
basename, _ = os.path.splitext(os.path.basename(filename))
121+
fname = f"{cname}-{basename}{ext}"
122+
filename = os.path.join(basedir, fname)
123+
90124
# self.anim.save(filename, writer='imagemagick')
91-
print("Saving {} to {}".format(self.__class__.__name__, filename))
125+
logger.info(f"Saving {cname} to {filename}")
126+
writer = animation.writers["ffmpeg"](fps=fps)
92127
self.anim.save(filename, writer=writer, dpi=dpi)
93-
print(f"Time Taken = {time.time() - start} seconds")
128+
logger.debug(f"Time Taken = {time.time() - start} seconds")
129+
130+
def autogenerate_path(self):
131+
iat = IAmTime()
132+
basepath = "out/"
133+
cname = self.__class__.__name__
134+
timepath = f"{iat.year}--{iat.month}"
135+
return os.path.join(basepath, cname, timepath)
94136

95137
def copy(self):
96138
return copy.copy(self)
@@ -148,7 +190,7 @@ def __init__(self, **args):
148190
self.image = plt.imshow(self.array, animated=True)
149191

150192
def _animate(self, i):
151-
print("Frame {}/{}".format(i, self.num_frames))
193+
print(f"Frame {i}/{self.num_frames}")
152194
array = self.update(i)
153195
self.image.set_array(array)
154196
return (self.image,)

panim/experiments.py

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,11 @@
1414
from abc import ABCMeta, ABC, abstractmethod
1515
from abc import ABC, abstractmethod
1616

17+
1718
import numpy as np
1819

20+
from loguru import logger
21+
1922
from panim.animator import AbstractAnimator, AbstractImageAnimator
2023

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

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

243-
r = np.mean(self.image_size) // 10
244-
print(f"Max radius = {r}")
245+
r = np.mean(self.image_size) // 13
246+
logger.info(f"Max radius = {r}")
245247
self.balls["radius"] = np.random.randint(5, r, (nballs,))
246248
self.array = np.zeros((self.image_size[1], self.image_size[0]))
247249

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

275277
def update(self, i):
276-
print(i)
277278
arr = np.zeros_like(self.array)
278279
nr, nc = arr.shape
279280
# xs = np.arange(0, nc, 1)
@@ -324,12 +325,14 @@ def update(self, i):
324325

325326
# x < 0, set direction +ve
326327
if center[0] - radius < 0:
327-
direction[0] *= np.random.uniform(0.5, 1, (1,))
328+
# direction[0] *= np.random.uniform(0.5, 1, (1,))
329+
direction[0] *= np.random.uniform(-1, -0.5, (1,))
328330
center[0] = radius
329331

330332
# y < 0, set direction +ve
331333
if center[1] - radius < 0:
332-
direction[1] *= np.random.uniform(0.5, 1, (1,))
334+
# direction[1] *= np.random.uniform(0.5, 1, (1,))
335+
direction[1] *= np.random.uniform(-1, -0.5, (1,))
333336
center[1] = radius
334337

335338
self.balls["direction"][i] = direction
@@ -361,10 +364,10 @@ def main():
361364
# n=11,
362365
# )
363366
# animator = MetaBall4(nballs=5, width=200, height=200)
364-
animator = MetaBall4(nballs=15, width=500, height=500)
365-
print(animator)
367+
animator = MetaBall4(nballs=15, width=500, height=400)
368+
logger.info(animator)
366369
animator.animate(500)
367-
animator.save("out/metaballs-fps-24-balls-20.mp4", fps=24)
370+
animator.save(fps=24)
368371

369372

370373
if __name__ == "__main__":

0 commit comments

Comments
 (0)