def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.configure(bg=BG_COLOR)
self.trends = Figure(figsize=(5, 5), dpi=100)
self.a = self.trends.add_subplot(111)
canvas = FigureCanvasTkAgg(self.trends, self)
canvas.show()
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1)
toolbar = NavigationToolbar2TkAgg(canvas, self)
toolbar.update()
canvas._tkcanvas.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=1)
self.animation = FuncAnimation(self.trends, self.animate, 5000)
python类FuncAnimation()的实例源码
def run(self):
"""
Entry point for the live plotting when started as a separate process. This starts the loop
"""
self.entity_name = current_process().name
plogger.info("Starting new thread %s", self.entity_name)
self.context = zmq.Context()
self.socket = self.context.socket(zmq.SUB)
self.socket.connect("tcp://localhost:%d" % self.port)
topic = pickle.dumps(self.var_name, protocol=pickle.HIGHEST_PROTOCOL)
self.socket.setsockopt(zmq.SUBSCRIBE, topic)
plogger.info("Subscribed to topic %s on port %d", self.var_name, self.port)
self.init(**self.init_kwargs)
# Reference to animation required so that GC doesn't clean it up.
# WILL NOT work if you remove it!!!!!
# See: http://matplotlib.org/api/animation_api.html
ani = animation.FuncAnimation(self.fig, self.loop, interval=100)
self.plt.show()
def __init__(self, session, config, live=False):
if not isinstance(session, NTStorage):
raise('Session must be of type \'NTStorage\'')
self.session = session
self.config = config
self.live = live
self.f = None
self.axarr = None
self._setup_graph()
if self.live:
session.add_listener(self.update_listener)
self.ani = animation.FuncAnimation(self.f, self.redraw, interval=1)
def play(self, timerange):
"""play an animation
Strongly recommend not stepping though each timesteps; use some skips!
:param timerange: range generator of time steps to animate
"""
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig = plt.figure()
plt.pcolormesh(self.lat, self.axial, self.arfidata[:, :, 0])
plt.axes().set_aspect('equal')
plt.gca().invert_yaxis()
plt.xlabel('Lateral (mm)')
plt.ylabel('Axial (mm)')
anim = animation.FuncAnimation(fig, self.animate, frames=timerange,
blit=False)
plt.show()
def initialize(self):
self.fig = plt.figure()
self.axes_dict = self.create_fig(self.fig)
for plot_key in self.plot_layers.keys():
plot_layer = self.plot_layers[plot_key]
if plot_key not in self.axes_dict:
raise KeyError("No axis created for plot %s" % plot_key)
plot_layer.create_fig(self.fig, self.axes_dict[plot_key])
# matplotlib.animation.Animation._blit_draw = _blit_draw
self.anim = animation.FuncAnimation(self.fig, self.update_func, init_func=self.init_func, frames=None,
interval=1000 / self.fps, blit=True)
print("show")
plt.ion()
plt.show()
print("continue")
def plot_hist(str_name, save_name='dist'):
data_array = utils.get_data(str_name)
params = np.squeeze(np.array(data_array['information']))
ind_array = data_array['params']['epochsInds']
DKL_YgX_YgT = utils.extract_array(params, 'DKL_YgX_YgT')
p_ts = utils.extract_array(params, 'pts')
H_Xgt = utils.extract_array(params, 'H_Xgt')
f, (axes) = plt.subplots(3, 1)
#axes = [axes]
f.subplots_adjust(left=0.14, bottom=0.1, right=.928, top=0.94, wspace=0.13, hspace=0.55)
colors = LAYERS_COLORS
line_ani = animation.FuncAnimation(f, update_bars_num_of_ts, len(p_ts), repeat=False,
interval=1, blit=False, fargs=[p_ts,H_Xgt,DKL_YgX_YgT, axes,ind_array])
Writer = animation.writers['ffmpeg']
writer = Writer(fps=50)
#Save the movie
line_ani.save(save_name+'_movie.mp4',writer=writer,dpi=250)
plt.show()
def panimate(ax, dt, pcoll, patches, boundaries, **kwargs):
particles = pcoll.P
coll = ellipse_collection(ax, particles)
def init():
return ()
#ax.clear()
#ax.add_patch(rect)
#return (rect, )
def animate(i):
if i == 0:
for patch in patches:
ax.add_patch(patch)
ax.add_collection(coll)
else:
move(particles, dt, boundaries)
xy = np.array([p.x[::2].flatten() for p in particles])
coll.set_offsets(xy)
return tuple(patches + [coll])
kwargs = dict(dict(frames=1800, interval=10, blit=True), **kwargs)
ani = animation.FuncAnimation(ax.figure, animate, init_func=init, **kwargs)
return ani
def _animate_bbvi(self, stored_parameters, stored_predictive_likelihood):
""" Produces animated plot of BBVI optimization
Returns
----------
None (changes model attributes)
"""
from matplotlib.animation import FuncAnimation, writers
import matplotlib.pyplot as plt
import seaborn as sns
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ud = BBVINLLTAnimate(ax,self.data,stored_parameters,self.index,self.z_no,self.link)
anim = FuncAnimation(fig, ud, frames=np.arange(stored_parameters.shape[0]), init_func=ud.init,
interval=10, blit=True)
plt.plot(self.data)
plt.xlabel("Time")
plt.ylabel(self.data_name)
plt.show()
def _animate_bbvi(self,stored_latent_variables,stored_predictive_likelihood):
""" Produces animated plot of BBVI optimization
Returns
----------
None (changes model attributes)
"""
from matplotlib.animation import FuncAnimation, writers
import matplotlib.pyplot as plt
import seaborn as sns
fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
ud = BBVINLLMAnimate(ax,self.data,stored_latent_variables,self.index,self.z_no,self.link)
anim = FuncAnimation(fig, ud, frames=np.arange(stored_latent_variables.shape[0]), init_func=ud.init,
interval=10, blit=True)
plt.plot(self.data)
plt.xlabel("Time")
plt.ylabel(self.data_name)
plt.show()
def plot_animated_heatmap(windows, title, ax_props=None, more_props=None):
fig, im, footer = plot_heatmap(windows[0], title, ax_props, more_props)
axes = fig.get_axes()
ax1, ax2 = axes
redraws = [im, footer, ax1.xaxis, ax1.yaxis, ax2.xaxis, ax2.yaxis]
anim = animation.FuncAnimation(
fig,
update_animated_heatmap,
frames=windows,
fargs=(more_props['name'], axes, im, footer, redraws),
interval=250,
blit=True,
)
return anim,
def main():
print('plotting data...')
analogPlot = AnalogPlot(200)
# set up animation
fig = plt.figure()
ax = plt.axes(xlim=(0, 200), ylim=(-1000, 8000))
a0, = ax.plot([], [])
a1, = ax.plot([], [])
anim = animation.FuncAnimation(fig, analogPlot.update,
fargs=(a0, a1),
interval=40,
frames=300,
blit=True)
plt.show()
# anim.save('animation.mp4', fps=30,
# extra_args=['-vcodec', 'libx264'])
print('exiting.')
# call main
def PlotLearn(R, A, Y):
intA = [BinVecToInt(j) for j in A]
intY = [BinVecToInt(j) for j in Y]
fig, ax = mpl.subplots(figsize=(20, 10))
ax.plot(intA, intY, label ='Orig')
l, = ax.plot(intA, intY, label ='Pred')
ax.legend(loc = 'upper left')
#Updates the plot in ax as model learns data
def UpdateF(i):
R.fit(A, Y)
YH = R.predict(A)
S = MSE(Y, YH)
intYH = [BinVecToInt(j) for j in YH]
l.set_ydata(intYH)
ax.set_title('Iteration: ' + str(i * 64) + ' - MSE: ' + str(S))
return l,
ani = mpla.FuncAnimation(fig, UpdateF, frames = 2000, interval = 128, repeat = False)
#ani.save('foo.gif')
mpl.show()
return ani
def anim(filename,varname,cax):
template = filename+'_%03i.nc'
nc0 = Dataset(template%(0),'r') # open proc 0 nc file
nt = len(nc0.dimensions['t'])
nc0.close()
def animate(i):
global kt
time,z2d=read(filename,varname,kt)
im.set_data(z2d)
ti.set_text('%.0f '%time)
kt +=5
return im,ti
fig=plt.figure()
ax = fig.add_subplot(111)
time,z2d=read(filename,varname,0)
im=ax.imshow(z2d,vmin=cax[0],vmax=cax[1])
ti=ax.text(100,-50,'%.0f '%time)
print('launch the animation')
global kt
kt = 0
ani = animation.FuncAnimation(fig, animate,arange(nt),interval=5, blit=True)
plt.show()
def animate(self, compute_step, iterations, train_data_update_freq=20, test_data_update_freq=100, one_test_at_start=True, more_tests_at_start=False, save_movie=False):
def animate_step(i):
if (i == iterations // train_data_update_freq): #last iteration
compute_step(iterations, True, True)
else:
for k in range(train_data_update_freq):
n = i * train_data_update_freq + k
request_data_update = (n % train_data_update_freq == 0)
request_test_data_update = (n % test_data_update_freq == 0) and (n > 0 or one_test_at_start)
if more_tests_at_start and n < test_data_update_freq: request_test_data_update = request_data_update
compute_step(n, request_test_data_update, request_data_update)
# makes the UI a little more responsive
plt.pause(0.001)
if not self.is_paused():
return self._mpl_update_func()
self._animation = animation.FuncAnimation(self._mpl_figure, animate_step, int(iterations // train_data_update_freq + 1), init_func=self._mlp_init_func, interval=16, repeat=False, blit=False)
if save_movie:
mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18'])
self._animation.save("./tensorflowvisu_video.mp4", writer=mywriter)
else:
plt.show(block=True)
def realtime_plot(lines_conf, data_generator=None):
fig = plt.figure()
lines = []
if not isinstance(lines_conf, list):
lines_conf = [lines_conf]
for index, line_conf in enumerate(lines_conf):
axes = fig.add_subplot(len(lines_conf), 1, index + 1)
axes.axis(line_conf.axis_lim)
line = axes.plot(line_conf.axes_x, line_conf.axes_y)[0]
lines.append(line)
def update(lines_data):
if len(lines) <= 1 and not isinstance(lines_data, list):
lines_data = [lines_data]
for index, line in enumerate(lines):
line.set_ydata(lines_data[index])
return lines
ani = animation.FuncAnimation(fig, update, frames=data_generator, interval=20)
plt.show()
Exercise14.py 文件源码
项目:computationalphysics_N2013301020050
作者: ShixingWang
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def movie(self):
# New figure with white background
fig = plt.figure(figsize=(6,6), facecolor='white')
# New axis over the whole figure, no frame and a 1:1 aspect ratio
ax = fig.add_axes([0,0,1,1], frameon=False, aspect=1)
line, = ax.plot([], [], lw=2)
def init():
line.set_data([], [])
return line,
def animate(i):
x = self.X
y = self.Y[i]
line.set_data(list(x), list(y))
return line,
anim1=animation.FuncAnimation(fig, animate, init_func=init, frames=3000, interval=30)
plt.show()
return 0
def animate1D(self, fileName, numberOfFrames):
"Animate a 1D nuclear wavefunction as it evolves in time"
d = self.mySpace.nuclearDimensionality
if d != 1:
raise NuclearWavefunction.unplotableNuclearWavefunction()
plottingAmplitude = np.abs(self.timePositionAmplitude)
yMin = np.min(plottingAmplitude)
yMax = np.max(plottingAmplitude)
fig = plt.figure()
ax = plt.axes(xlim=(-self.mySpace.xMax, self.mySpace.xMax), ylim = (yMin, yMax))
line, = ax.plot([], [])
def init():
line.set_data([], [])
return line,
def animate(i):
line.set_data(self.mySpace.xValues, plottingAmplitude[i])
return line,
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames = numberOfFrames, interval=20, blit=True)
anim.save(fileName, fps=20)
def animateFrequency(self, filename):
"Animate a 2D nuclear wavefunction as it evolves in time"
plottingAmplitude = np.abs(self.filteredNonresphasingFrequencySignals + self.filteredResphasingFrequencySignals)
zMin = np.min(plottingAmplitude)
zMax = np.max(plottingAmplitude)
contourLevels = 100
contourSpacings = np.linspace(zMin, zMax, contourLevels)
yVals = self.probeFrequencies
xVals = self.pumpFrequencies
fig = plt.figure()
im = plt.contourf(xVals, yVals, plottingAmplitude[0], contourSpacings)
ax = fig.gca()
def animate(i, data, ax, fig):
ax.cla()
im = ax.contourf(xVals, yVals, data[i], contourSpacings)
plt.title(str(i))
return im,
anim = animation.FuncAnimation(fig, animate, frames = self.rawNonresphasingFrequencySignals.shape[0], interval=20, blit=True, fargs=(plottingAmplitude, ax, fig) )
anim.save(filename, fps=20)
def __init__(self, var_xarray, Nsteps, vmin, vmax, animationname):
# Global definitions
self.var = var_xarray
self.Nsteps = Nsteps
self.vmin = vmin
self.vmax = vmax
# Figure and axes
self.fig = plt.figure()
# self.ax = self.fig.axes()
# Animation definitio
anim = animation.FuncAnimation(self.fig, self.update, xrange(Nsteps), interval=1, blit=False)
# Writer FFMpeg needed for mp4 film
mywriter = animation.FFMpegWriter(bitrate=500)
anim.save(animationname, writer=mywriter, fps=1, extra_args=['-vcodec', 'libx264'], dpi=300)
# No init_plot needed
def animate(self, compute_step, iterations, train_data_update_freq=20, test_data_update_freq=100, one_test_at_start=True, more_tests_at_start=False, save_movie=False):
def animate_step(i):
if (i == iterations // train_data_update_freq): #last iteration
compute_step(iterations, True, True)
else:
for k in range(train_data_update_freq):
n = i * train_data_update_freq + k
request_data_update = (n % train_data_update_freq == 0)
request_test_data_update = (n % test_data_update_freq == 0) and (n > 0 or one_test_at_start)
if more_tests_at_start and n < test_data_update_freq: request_test_data_update = request_data_update
compute_step(n, request_test_data_update, request_data_update)
# makes the UI a little more responsive
plt.pause(0.001)
if not self.is_paused():
return self._mpl_update_func()
self._animation = animation.FuncAnimation(self._mpl_figure, animate_step, int(iterations // train_data_update_freq + 1), init_func=self._mlp_init_func, interval=16, repeat=False, blit=False)
if save_movie:
mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18'])
self._animation.save("./tensorflowvisu_video.mp4", writer=mywriter)
else:
plt.show(block=True)
def animateMatrices(matrices,outputFilename = None):
fig = plot.figure() # make figure
im = plot.imshow(matrices[0], cmap=plot.get_cmap('bone'), vmin=0.0, vmax=1.0)
# function to update figure
def updatefig(j):
# set the data in the axesimage object
im.set_array(matrices[j])
# return the artists set
return im,
# kick off the animation
ani = animation.FuncAnimation(fig, updatefig, frames=range(len(matrices)),
interval=50, blit=True)
if outputFilename != None:
ani.save(outputFilename, dpi = 80,writer = 'imagemagick')
plot.show()
def train(self, training_agent, total_episode, save_movie=False):
def animate_func(step):
#self.step = step
if step > total_episode:
print("Finish training ")
#plt.close()
else:
training_agent(episode=step, visual=self)
plt.pause(1.001) # makes the UI a little more responsive
if not self.ispause:
return self._update()
self.am = animation.FuncAnimation(self._fig, animate_func, total_episode, init_func=self._init, interval=16, repeat=False, blit=False)
if save_movie:
mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18'])
self.am.save("./video.mp4", writer=mywriter)
else:
plt.show(block=True)
def save_frames(images, filename):
num_sequences, n_steps, w, h = images.shape
fig = plt.figure()
im = plt.imshow(combine_multiple_img(images[:, 0]), cmap=plt.cm.get_cmap('Greys'), interpolation='none')
plt.axis('image')
def updatefig(*args):
im.set_array(combine_multiple_img(images[:, args[0]]))
return im,
ani = animation.FuncAnimation(fig, updatefig, interval=500, frames=n_steps)
# Either avconv or ffmpeg need to be installed in the system to produce the videos!
try:
writer = animation.writers['avconv']
except KeyError:
writer = animation.writers['ffmpeg']
writer = writer(fps=3)
ani.save(filename, writer=writer)
plt.close(fig)
def plot_anim(self, movesets, **kwargs):
pass
# DOESNT WORK SINE THE LENGTH OF A MOVESET IS VARIABLE
# setup = self.plot_moveset(movesets[0], show=False, export=True, export_plots=True, plot=True)
# fig = setup['fig']
# ax = setup['ax']
# plots = setup['plots']
#
# def update(i):
# label = 'Generation {}'.format(i)
# path, bumps = self.plot_moveset(movesets[i], export_data=True)
# path_xs, path_ys = Labyrinth._transform_array_into_xy(path)
# bumps_xs, bumps_ys = Labyrinth._transform_array_into_xy(bumps)
# # plots[0].set_offsets(bumps_xs, bumps_ys)
# # plots[1].set_offsets(path[0])
# # plots[2].set_offsets((path_xs[-1], path_ys[-1]))
# for i, j in enumerate(range(len(path)-2, -1, -1), 3):
# plots[i].set_positions([path_xs[i], path_ys[i]], [path_xs[i + 1], path_ys[i + 1]])
# # plots[len(plots)-1]
# return plots
#
# mywriter = animation.FFMpegWriter()
# ani = animation.FuncAnimation(fig, update, frames=np.arange(0, len(movesets)), interval=200)
# ani.save('asd.mp4', writer=mywriter)
def viz():
# Prepare data
X = np.arange(0, 10, 0.1)
test_y = X * np.sin(X)
# e = np.random.normal(0, 1, size=len(X))
# train_y = test_y + e
train_y = test_y.copy()
X = X[:, None]
print("X's shape = %s, train_y's shape = %s, test_y's shape = %s"
% (X.shape, train_y.shape, test_y.shape))
# Visualize
fig, ax = plt.subplots(1, 1, sharex=True, sharey=True, figsize=[7, 7], facecolor='w')
ani = animation.FuncAnimation(fig, run_boosted_regression_tree, range(25),
fargs=(X, train_y, test_y, ax),
blit=False, interval=1000, repeat=True)
plt.show()
# ani.save('BoostedRegressor.gif', writer='imagemagick')
tensorflowvisu.py 文件源码
项目:tensorflow-mnist-tutorial
作者: martin-gorner
项目源码
文件源码
阅读 30
收藏 0
点赞 0
评论 0
def animate(self, compute_step, iterations, train_data_update_freq=20, test_data_update_freq=100, one_test_at_start=True, more_tests_at_start=False, save_movie=False):
def animate_step(i):
if (i == iterations // train_data_update_freq): #last iteration
compute_step(iterations, True, True)
else:
for k in range(train_data_update_freq):
n = i * train_data_update_freq + k
request_data_update = (n % train_data_update_freq == 0)
request_test_data_update = (n % test_data_update_freq == 0) and (n > 0 or one_test_at_start)
if more_tests_at_start and n < test_data_update_freq: request_test_data_update = request_data_update
compute_step(n, request_test_data_update, request_data_update)
# makes the UI a little more responsive
plt.pause(0.001)
if not self.is_paused():
return self._mpl_update_func()
self._animation = animation.FuncAnimation(self._mpl_figure, animate_step, int(iterations // train_data_update_freq + 1), init_func=self._mlp_init_func, interval=16, repeat=False, blit=False)
if save_movie:
mywriter = animation.FFMpegWriter(fps=24, codec='libx264', extra_args=['-pix_fmt', 'yuv420p', '-profile:v', 'high', '-tune', 'animation', '-crf', '18'])
self._animation.save("./tensorflowvisu_video.mp4", writer=mywriter)
else:
plt.show(block=True)
def animate(Vh, state, same_colorbar=True, colorbar=True,
subplot_loc=None, mytitle=None, show_axis='off', logscale=False):
fig = plt.figure()
vmin = None
vmax = None
if same_colorbar:
vmin = 1e30
vmax = -1e30
for s in state.data:
smax = s.max()
smin = s.min()
if smax > vmax:
vmax = smax
if smin < vmin:
vmin = smin
def my_animate(i):
time_stamp = "Time: {0:f} s"
obj = dl.Function(Vh, state.data[i])
t = mytitle + time_stamp.format(state.times[i])
plt.clf()
return plot(obj, colorbar=True, subplot_loc=None, mytitle=t, show_axis='off', vmin=vmin, vmax=vmax, logscale=False)
return animation.FuncAnimation(fig, my_animate, np.arange(0, state.nsteps), blit=True)
def __call__(self, sample):
'''
For given instance, obtain data from OpenBCI and a) save to .CSV, and
b) update the graph.
'''
t = timeit.default_timer() - self.start_time
# print timeSinceStart|Sample Id
if self.verbose:
print("CSV: %f | %d" % (t, sample.id))
row = ''
row += str(t)
row += self.delim
row += str(sample.id)
row += self.delim
for i in sample.channel_data:
row += str(i)
row += self.delim
for i in sample.aux_data:
row += str(i)
row += self.delim
# remove last comma
row += '\n'
with open(self.file_name, 'a') as f:
f.write(row)
ani = animation.FuncAnimation(self.fig, animate, interval=1000)
plt.show()
def visualize(self, num=100, save=False):
"""
Visualizes given Sorting Algorithm
:param num: Number of points that has to be chosen for visualization
:param save: Boolean indicating whether to save animation in 'output' directory
"""
plt.title(self.sorter.name + " Visualization")
plt.xlabel("Array Index")
plt.ylabel("Element")
data = np.arange(num)
ran.shuffle(data)
self.sorter.sort(data, visualization=True)
self.hist_arr = self.sorter.hist_array
self.scatter = plt.scatter(np.arange(self.hist_arr.shape[1]), self.hist_arr[0]) # plt.scatter(x-array,y-array)
self.animation = animation.FuncAnimation(self.fig, self.__update, frames=self.hist_arr.shape[0], repeat=False,
blit=False, interval=1)
if save:
import os
import errno
path = "output"
try:
os.makedirs(path)
except OSError as exc:
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
path = os.path.join('output', self.sorter.name + ".mp4")
p1 = Process(
target=lambda: self.animation.save(path, writer=animation.FFMpegWriter(fps=100)))
p1.start()
plt.show()
def theta_anim(self):
#
# Animate the contour plot from above by varying theta from 0 to 2*pi
#
self.theta = 0
x,y,z = self.location_contours([0.2, 0.2, 0.2, self.theta])
self.fig = plt.figure()
self.im = plt.imshow(z, interpolation='bilinear', origin='lower', cmap=cm.inferno)
CBI = plt.colorbar(self.im, orientation='horizontal', shrink=0.8)
plt.title('Contour Plot - Q')
ani = animation.FuncAnimation(self.fig, self.update_theta, interval=50, blit=False)
plt.show()