-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate_movies.py
More file actions
270 lines (241 loc) · 10 KB
/
generate_movies.py
File metadata and controls
270 lines (241 loc) · 10 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
#!/usr/bin/python
# Copyright (c) 2011, Kendrick Shaw
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# use TeX for labels
from matplotlib import rc
rc('text', usetex=True)
rc('font', family='serif', serif=['Computer Modern Roman'])
from matplotlib import pyplot as plt
import numpy as np
import math
from multiprocessing import Pool
import subprocess
import shutil
import os
from os import path
import time
import sys
import getopt
import iris
import prc
import generate_figures
def generate_movie(fig_func, arg_func, filename, duration=10, fps=24,
pool=None, title_func=lambda t:"", title_pos=(0.5, 0.95)):
"""
Generates a movie with each frame generated by the given function.
"""
# if we weren't given a pool of worker threads to use, create one
if pool is None:
pool = Pool()#maxtasksperchild=10)
# generate a folder to store the individual frames of the movie
framefolder = filename + ".tmp"
os.mkdir(framefolder)
# generate the individual frames
num_frames = int(duration*fps)
figlist = [
(
fig_func,
arg_func(frame/float(num_frames)),
path.join(
framefolder,
"frame{0:09}.png".format(frame)
),
title_func(frame/float(num_frames)),
title_pos,
) for frame in range(num_frames)
]
# workaround: matplotlib leaks memory and maxtasksperchild requires
# python 2.7. Thus we will kill and restart the child processes by
# hand every 16 frames.
maxtasks = 16
for startfig in range(0, len(figlist), maxtasks):
pool.close()
pool.join()
pool = Pool()#maxtasksperchild=10)
results = [pool.apply_async(generate_figures.generate_figure, fig)
for fig in figlist[startfig:startfig+maxtasks]]
for result,frame in zip(results,range(startfig, startfig+maxtasks)):
result.wait()
print "Finished drawing frame {0}/{1}".format(frame+1, num_frames)
#results = [pool.apply_async(generate_figures.generate_figure, fig)
# for fig in figlist]
# wait until all of the frames have been generated
#for result,frame in zip(results,range(num_frames)):
# result.wait()
# print "Finished drawing frame {0}/{1}".format(frame+1, num_frames)
# run mencoder to create a movie from the frames
if os.uname()[0] == 'Darwin':
# install via macports using
# "sudo port install mplayer-devel +mencoder_extras"
# and "sudo port install mjpegtools"
mencoder = "/opt/local/bin/mencoder"
mplex = "/opt/local/bin/mplex"
else:
mencoder = "/usr/bin/mencoder"
mplex = "/usr/bin/mplex"
if filename[-4:] == '.mp4':
subprocess.call([mencoder,
"mf://{0}*.png".format(
path.join(framefolder, "frame")),
"-mf", "type=png:fps={0}".format(40),
"-of", "lavf", "-lavfopts", "format=mp4", "-vf-add",
"harddup",
"-oac", "lavc", "-ovc", "lavc", "-lavcopts",
"aglobal=1:vglobal=1:vcodec=mpeg4:vbitrate=1000:keyint=25",
"-oac", "copy", "-o", filename
])
elif filename[-4:] == '.mpg':
if (fps != 24 and fps != 30):
raise ValueError(
"Only 24 or 30 frames per second supported for mpeg-1"
+ "({0} requested)".format(fps))
subprocess.call([mencoder,
"mf://{0}*.png".format(
path.join(framefolder, "frame")),
"-mf", "type=png:fps={0}/1001".format(fps*1000),
#"-of", "mpeg", "-mpegopts", "format=dvd:tsaf",
"-of", "rawvideo",
"-vf-add", "harddup",
"-oac", "lavc", "-ovc", "lavc", "-lavcopts",
#"vcodec=mpeg2video:vrc_buf_size=1835:vrc_maxrate=9800:"
#+ "vbitrate=5000:keyint=18:vstrict=0", "-oac", "copy",
#"vcodec=mpeg1video:vrc_buf_size=327:vrc_minrate=1152:"
#+ "vrc_maxrate=1152:vbitrate=1152:keyint=15:acodec=mp2",
"vcodec=mpeg1video:vrc_buf_size=8000:vrc_minrate=5000:"
+ "vrc_maxrate=5000:vbitrate=5000:keyint=15:acodec=mp2",
"-o", "{0}.m2v".format(filename)
])
subprocess.call([mplex, "-b", "700", "-o", filename, "{0}.m2v".format(filename)])
os.remove("{0}.m2v".format(filename))
else:
raise ValueError("Unrecognized extension {0}".format(filename[-4:]))
# delete the temporary images of the frames
shutil.rmtree(str(framefolder))
# a simple test graph
def sinewave(freq):
# create a new figure
fig = plt.figure(figsize=(6,6))
axes = fig.add_axes([0.1, 0.1, 0.8, 0.8])
ts = np.linspace(0,10,1000)
axes.plot(ts, np.sin(freq*(2*math.pi)*ts), '-')
axes.set_ylim(-1,1)
return fig
# 'main' function structure based on
# http://www.artima.com/weblogs/viewpost.jsp?thread=4829
class Usage(Exception):
def __init__(self, msg):
self.msg = msg
def main(argv=None):
if argv is None:
argv = sys.argv
try:
try:
opts, args = getopt.getopt(argv[1:], "h", ["help"])
except getopt.error, msg:
raise Usage(msg)
if len(args) == 0:
args = ['iris', 'smooth',
#'iris_isochron_phase', 'iris_isochron_offset',
'iris_isochrons']
if 'sinewave' in args:
# a simple sinewave graph for debugging purposes (fast)
generate_movie(
sinewave,
lambda t: [(1+math.sin(2*math.pi*t))/2],
"sinewave.mpg",
duration=2,
title_func=lambda t: "Sinewave at {0:0<5.3f}".format(
(1+math.sin(2*math.pi*t))/2)
)
if 'iris' in args:
generate_movie(
generate_figures.iris_fig,
lambda t: [0.255*(1-math.cos(2*math.pi*t))/2, 0.15],
"iris.mpg",
title_func=lambda t:
"$a = {0:0<5.3f}$".format(
0.255*(1-math.cos(2*math.pi*t))/2)
)
if 'smooth' in args:
generate_movie(
generate_figures.sine_fig,
lambda t: [-0.5*(1-math.cos(2*math.pi*t))/2],
"smooth.mpg",
title_func=lambda t:
"$\mu = {0:0<4.2f}$".format(
0.5*(1-math.cos(2*math.pi*t))/2),
# paper's \mu = code's -\mu
title_pos=(0.87, 0.02),
duration=10
)
if 'iris_isochron_phase' in args:
generate_movie(
generate_figures.iris_isochron_fig,
lambda t: [0.2, 0.15, 2*math.pi*t],
"iris_isochron_phase.mpg",
title_func=lambda t:
"Isochron sets evolving together in time"
)
if 'iris_isochron_offset' in args:
generate_movie(
generate_figures.iris_isochron_fig,
lambda t: [0.001 + 0.246*(1-math.cos(2*math.pi*t))/2,
0.15, -2*math.pi],
"iris_isochron_offset.mpg",
title_func=lambda t:
"$a = {0:0<5.3f}$".format(
0.001 + 0.246*(1-math.cos(2*math.pi*t))/2)
)
if 'iris_isochrons' in args:
switchtime=5./16
generate_movie(
generate_figures.iris_isochron_fig,
lambda t: [
0.001 + 0.246*(1+math.cos(
2*math.pi*max(0,
(t-switchtime)/(1-switchtime)
)))/2,
0.15,
2*math.pi*(min(switchtime,t)/switchtime-2)
],
"iris_isochrons.mpg",
duration=15,
title_func=lambda t:
[
"Isochron sets evolving together in time",
"$a = {0:0<5.3f}$".format(
0.001 + 0.246*(1+math.cos(
2*math.pi*max(0,
(t-switchtime)/(1-switchtime)
)))/2
),
][t > switchtime]
)
except Usage, err:
print >>sys.stderr, err.msg
print >>sys.stderr, "for help use --help"
return 2
if __name__ == "__main__":
sys.exit(main())