def anim_plot(self, path_x, path_y, Nodes_posi, samples, goal, obstacles, final_path): imgs = [] finish_buffa = 20 # 終了後もそのまま数秒表示したいので for i in range(path_x.shape[1] + finish_buffa): img = [] if i >= path_x.shape[1]: i = path_x.shape[1] - 1 img_text = self.axis.text(0.05, 0.9, 'step = {0}'.format(i), transform=self.axis.transAxes) img.append(img_text) img_goal_text = self.axis.text(0.35, 0.5, 'GOAL!!', transform=self.axis.transAxes, fontsize=30) img.append(img_goal_text) img_final_path = self.axis.plot(final_path[:, 0], final_path[:, 1], color='r', linewidth=5) img.extend(img_final_path) # step数を追加 img_text = self.axis.text(0.05, 0.9, 'step = {0}'.format(i), transform=self.axis.transAxes) img.append(img_text) # goalを追加 img_goal = self.axis.plot(goal[0], goal[1], '*', color='r') img.extend(img_goal) # obstaclesを追加 for k in range(obstacles.shape[0]): circle_x, circle_y = self.circle_make(obstacles[k, 0], obstacles[k, 1], obstacles[k, 2]) img_obstacle = self.axis.plot(circle_x, circle_y, color='k') img.extend(img_obstacle) # sampleを追加 img_sample = self.axis.plot(samples[i, 0], samples[i, 1], '*', color='b') img.extend(img_sample) # nodeを追加 img_nodes = self.axis.plot(Nodes_posi[:i + 2, 0], Nodes_posi[:i + 2, 1], '.', color='k') img.extend(img_nodes) # pathを追加 for k in range(i + 1): img_path = self.axis.plot(path_x[:, k], path_y[:, k], color='b') img.extend(img_path) print('i = {0}'.format(i)) imgs.append(img) animation = ani.ArtistAnimation(self.fig, imgs) print('save_animation?') shuold_save_animation = int(input()) if shuold_save_animation: animation.save('basic_animation.gif', writer='imagemagick') plt.show()
return values if __name__ == "__main__": fig = plt.figure(figsize=(8, 8)) images = [] """ start_step = int(sum(ep_lens[0][:EP2])) finish_step = int(start_step + ep_lens[0][EP2]) for i in range(start_step, finish_step): values = get_values(reader["step_states"][0][i]) # values = get_values((0, 0, (i - 12) / 180 * np.pi, 0)) images.append([plt.imshow(values, animated=True, cmap="gray")]) """ for i in range(70): values = track_get_values(i * 40 / 60 - 17.5) images.append([plt.imshow(values, animated=True, cmap="gray")]) ani = animation.ArtistAnimation( fig, images, interval=300, blit=True, repeat_delay=1000 ) plt.show()
if (abs(doty[i][0] - midx) <= m): temp.append(doty[i]) sum = sum + 1 if temp.__len__() > 1: frames = pen[-1].copy() frames = getrect(frames, midx - m, midx + m, temp[0][1], temp[sum - 1][1]) artists.append(frames) pen.append(frames) for j in range(0, sum, 1): for k in range(j + 1, sum, 1): if (abs(temp[k][1] - temp[j][1]) <= m): res = pow((pow((temp[k][0] - temp[j][0]), 2) + pow( (temp[k][1] - temp[j][1]), 2)), 0.5) frames = pen[-1].copy() frames = frames + plt.plot((temp[j][0], temp[k][0]), (temp[j][1], temp[k][1]), linewidth=1) artists.append(frames) pen.append(frames) if (res < m): m = res return m res = fenzhi(0, 17, 0) print(res) anim = animation.ArtistAnimation(fig, artists, interval=1000) plt.show()
cuda.memcpy_dtoh(a, output_gpu) plt.imshow(a) fig = plt.figure() b = np.zeros([nbligne, nbcol], dtype=np.float32) ims = [] def create_anim(): for seuil in np.arange(0.2, 4, 0.01): mandel(np.int32(nbligne), np.int32(nbcol), np.float32(seuil), np.float32(-2), np.float32(2), np.float32(-2), np.float32(2), output_gpu, block=(BLOCKDIMx, BLOCKDIMy, 1), grid=(GRIDDIMx, GRIDDIMy, 1)) cuda.memcpy_dtoh(b, output_gpu) im = plt.imshow(b, animated=True) ims.append([im]) # lancer la fonction ci dessus pour creer l'animation et decommenter ci dessous pour la voir create_anim() ani = animation.ArtistAnimation(fig, ims, interval=5, blit=True) plt.show()
def animate(i): line.set_ydata(np.sin(x + i / 10.0)) # update the data return line, # Init only required for blitting to give a clean slate. def init(): line.set_ydata(np.ma.array(x, mask=True)) return line, ani = anim.FuncAnimation(fig, animate, np.arange(1, 200), init_func=init, interval=25, blit=True) Writer = anim.writers['ffmpeg'] writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800) ims = [] for add in np.arange(15): ims.append((plt.pcolor(x, y, base + add, norm=plt.Normalize(0, 30)), )) im_ani = anim.ArtistAnimation(fig, ims, interval=50, repeat_delay=3000, blit=True) im_ani.save('test_liveim.mp4', writer=writer)
for x_ind, x in enumerate(x_dom): for z_ind, z in enumerate(z_dom): im[x_ind, z_ind] = den_long_spline(x, z)[0][0] if x_ind == half_pts: line[z_ind] = den_long_spline(x_dom[half_pts], z)[0][0] image = ax1.imshow(im, extent=(z_dom[0], z_dom[-1], x_dom[0], x_dom[-1]), vmin=0, vmax=1, animated=True) image1 = image if d == 0: line1, = ax2.plot(z_dom, line, color=color, label='line out') else: line1, = ax2.plot(z_dom, line, color=color) artist.append([image1, texts1, line1]) ax2.legend(loc='upper right') #cbaxes = fig.add_axes([0.125, .9, 0.775, 0.03]) #plt.colorbar(image, cax=cbaxes, orientation='horizontal') ani = an.ArtistAnimation(fig, artist) writer = an.FFMpegWriter(fps=10, codec='h264') ani.save(svar.den_path + 'movies/long.mp4', writer=writer) plt.close()
return np.sin(x) + np.cos(y) x = np.linspace(0, 2 * np.pi, 120) y = np.linspace(0, 2 * np.pi, 120).reshape(-1, 1) fig, ax = plt.subplots(figsize=(3.5, 3.5)) fig.subplots_adjust(bottom=0, top=1, left=0, right=1) ax.axis('off') ims = [] for i in range(120): x += np.pi / 20. y += np.pi / 20. im = ax.imshow(f(x, y), cmap=plt.get_cmap('plasma'), animated=True) ims.append([im]) ani = anim.ArtistAnimation(fig, artists=ims, interval=10, repeat_delay=0) # Uncomment to save as mp4 movie file. Need ffmpeg. # ani.save('sncs2d.mp4', writer='ffmpeg') # need ffmpeg !) fig.show() """ Introduction to Python for Science & Engineering by David J. Pine Code last edited: 2018-09-19 Makes a movie from images generated on the fly using matplotlib's ArtistAnimation routine. Adapted from https://matplotlib.org/examples/animation/dynamic_image2.html """
texty = 0.95 * Ny for n in range(100, Nt): frame = dataCube[:, :, n] im = ax1.imshow(frame, norm=norm, interpolation='none', origin='lower') tx = ax1.text(textx, texty, 'E = ' + '{0:.3f}'.format(E[n]) + ' V', color='w', family='sans-serif', size=24, va='top', ha='left', weight='bold') ims.append([im, tx]) ani = animation.ArtistAnimation(fig, ims, interval=10, repeat=False) path = filePath + '_curr_Movie.mp4' ani.save(path, bitrate=20000) plt.show() #GUI-triggered functions to output cv of a single region ncv = 1 def exportCV(x, y): global ncv curr = dataCube[y, x, :] cv = sp.stack((E, curr), axis=-1) path = filePath + '_' + str(ncv) + '_x' + str(x) + '_y' + str(y) + '.txt'
color='red', linewidth=2) line1e, = ax1.plot([x[head]], [y[head]], [z[head]], color='red', marker='o', markeredgecolor='r') line2, = ax2.plot(y[:i], z[:i], color='black') line2a, = ax2.plot(y[head_slice], z[head_slice], color='red', linewidth=2) line2e, = ax2.plot(y[head], z[head], color='red', marker='o', markeredgecolor='r') line3, = ax3.plot(x[:i], z[:i], color='black') line3a, = ax3.plot(x[head_slice], z[head_slice], color='red', linewidth=2) line3e, = ax3.plot(x[head], z[head], color='red', marker='o', markeredgecolor='r') lines.append( [line1, line1a, line1e, line2, line2a, line2e, line3, line3a, line3e]) plt.tight_layout() ani = animation.ArtistAnimation(fig, lines, interval=50, blit=True) plt.show() fn = 'line_animation_3d_with_two_2d_artistanimation' ani.save('%s.mp4' % (fn), writer='ffmpeg', fps=1000 / 50)
def MaskComparison(Sreference, mask1, mask2, animate=True, frametime=1000): """ Produce animation to compare the performance of two masks for a given SLSTR image Parameters ---------- Sreference: str or satpy Scene object SLSTR file to produce an image of. Either scene object or path to SLSTR files mask1: array First mask to compare. mask2: array Second mask to compare. frametime: int Time to display each image before showing next image in ms. Default is 1000 Returns ---------- ani: matplotlib.animation object """ maskdiff = mask1 - mask2 maskdiff = np.abs(maskdiff) matches = 1 - np.mean(maskdiff) matches_percent = str(matches * 100)[:5] mask1cov = 1 - np.mean(mask1) mask1cov_percent = str(mask1cov * 100)[:5] mask2cov = 1 - np.mean(mask2) mask2cov_percent = str(mask2cov * 100)[:5] print("##################################################") print("Masks agree for " + matches_percent + "% of image") print("Mask 1 image coverage: " + mask1cov_percent + "%") print("Mask 2 image coverage: " + mask2cov_percent + "%") rgb, TitleStr = FalseColour(Sreference, plot=False) if animate is True: fig = plt.figure() plt.title(TitleStr) FC = [plt.imshow(rgb)] im1 = [plt.imshow(mask1, cmap='Blues')] im2 = [plt.imshow(mask2, cmap='Reds')] ims = [FC, im1, FC, im2] ani = animation.ArtistAnimation(fig, ims, interval=frametime, blit=True, repeat_delay=0) plt.show() return (ani) else: plt.figure() plt.title(TitleStr) plt.imshow(rgb) plt.figure() plt.title(TitleStr) plt.imshow(mask1, cmap='Blues') plt.figure() plt.title(TitleStr) plt.imshow(mask2, cmap='Reds') plt.show()
def demo_gmm(): x1 = hstack([rand_gauss(400, array([50, 40]), array([[100, 70], [70, 100]])), rand_gauss(200, array([55, 75]), array([[25, 0], [0, 25]]))]) x2 = hstack([rand_gauss(400, array([45, 60]), array([[40, 0], [0, 40]])), rand_gauss(200, array([30, 40]), array([[20, 0], [0, 40]]))]) (mu1, cov1) = train_gauss(x1) (mu2, cov2) = train_gauss(x2) p1 = p2 = 0.5 plt.plot(x1[0, :], x1[1, :], 'r.') plt.plot(x2[0, :], x2[1, :], 'b.') gellipse(mu1, cov1, 100, 'r') gellipse(mu2, cov2, 100, 'b') ax = plt.gca() plt.show() # make hard decision - return one to decide for calss X1 and zero otherwise hard_decision = lambda x: logpdf_gauss(x, mu1, cov1) + log(p1) > logpdf_gauss(x, mu2, cov2) + log(p2) # compute posterior probability for class X1 x1_posterior = lambda x: logistic_sigmoid(logpdf_gauss(x, mu1, cov1) + log(p1) - logpdf_gauss(x, mu2, cov2) - log(p2)) fig, (ax1, ax2) = plt.subplots(1, 2) plot2dfun(hard_decision, ax, 100, ax=ax1) ax1.plot(x1[0, :], x1[1, :], 'r.') ax1.plot(x2[0, :], x2[1, :], 'b.') gellipse(mu1, cov1, 100, 'r', ax=ax1) gellipse(mu2, cov2, 100, 'b', ax=ax1) plot2dfun(x1_posterior, ax, 100, ax=ax2) ax2.plot(x1[0, :], x1[1, :], 'r.') ax2.plot(x2[0, :], x2[1, :], 'b.') gellipse(mu1, cov1, 100, 'r', ax=ax2) gellipse(mu2, cov2, 100, 'b', ax=ax2) plt.show() m1 = 2 mus1 = x1[:, randint(1, x1.shape[1], (m1))] covs1 = tile(cov1, (m1, 1, 1)) ws1 = ones((m1)) / m1 m2 = 2 mus2 = x2[:, randint(1, x2.shape[1], (m2))] covs2 = tile(cov2, (m2, 1, 1)) ws2 = ones((m2)) / m2 fig = plt.figure() ims = [] for i in range(30): im = plt.plot(x1[0, :], x1[1, :], 'r.') + plt.plot(x2[0, :], x2[1, :], 'b.') for j in range(m1): im += gellipse(mus1[:, j], covs1[j, :, :], 100, 'r', lw=round(ws1[j] * 10)) for j in range(m2): im += gellipse(mus2[:, j], covs2[j, :, :], 100, 'b', lw=round(ws2[j] * 10)) ims.append(im) (ws1, mus1, covs1, ttl1) = train_gmm(x1, ws1, mus1, covs1) (ws2, mus2, covs2, ttl2) = train_gmm(x2, ws2, mus2, covs2) print('Total log-likelihood: %s for class X1; %s for class X2' % (ttl1, ttl2)) anim = animation.ArtistAnimation(fig, ims, interval=200, repeat_delay=3000, blit=True) plt.show() fig, (ax1, ax2) = plt.subplots(1, 2) hard_decision = lambda x: logpdf_gmm(x, ws1, mus1, covs1) + log(p1) > logpdf_gmm(x, ws2, mus2, covs2) + log(p2) plot2dfun(hard_decision, ax, 100, ax=ax1) ax1.plot(x1[0, :], x1[1, :], 'r.') ax1.plot(x2[0, :], x2[1, :], 'b.') for j in range(m1): gellipse(mus1[:, j], covs1[j, :, :], 100, 'r', lw=round(ws1[j] * 10), ax=ax1) for j in range(m2): gellipse(mus2[:, j], covs2[j, :, :], 100, 'b', lw=round(ws2[j] * 10), ax=ax1) x1_posterior = lambda x: logistic_sigmoid(logpdf_gmm(x, ws1, mus1, covs1) + log(p1) - logpdf_gmm(x, ws2, mus2, covs2) - log(p2)) plot2dfun(x1_posterior, ax, 100, ax=ax2) ax2.plot(x1[0, :], x1[1, :], 'r.') ax2.plot(x2[0, :], x2[1, :], 'b.') for j in range(m1): gellipse(mus1[:, j], covs1[j, :, :], 100, 'r', lw=round(ws1[j] * 10), ax=ax2) for j in range(m2): gellipse(mus2[:, j], covs2[j, :, :], 100, 'b', lw=round(ws2[j] * 10), ax=ax2) plt.show()
import matplotlib.pyplot as plt import matplotlib.animation as animation import pandas as pd model_data = pd.read_csv("./tetrismodel.csv") count = 83 * 83 fig = plt.figure(figsize=(8, 8)) ims = [] for i in range(1000): data = model_data[:][i*count:(i+1)*count-1] im = plt.scatter(data['x'], data['y'], s=10, c=data['color'], marker='o') ims.append([im]) ani = animation.ArtistAnimation(fig, ims, interval=50, repeat=1) ani.save('tetrismodel.mp4') plt.show()
import matplotlib.pyplot as plt import matplotlib.animation as anim import numpy as np import types #create image with format (time,x,y) image = np.random.rand(10, 10, 10) image2 = np.random.rand(10, 10, 10) #setup figure fig = plt.figure() ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) #set up list of images for animation ims = [] for time in xrange(np.shape(image)[1]): im = ax1.imshow(image[time, :, :]) # im2 = ax2.imshow(image2[time,:,:]) im2, = ax2.plot(image[0:time, 5, 5]) # def setvisible(self,vis): # for c in self.collections: c.set_visible(vis) # im2.set_visible = types.MethodType(setvisible,im2,None) # im2.axes = plt.gca() ims.append([im, im2]) #run animation ani = anim.ArtistAnimation(fig, ims, interval=50, blit=False) plt.show()
def plot_video_topoplot_with_juxta128(data, juxtaData, time_axis, channel_positions, times_to_plot=[5.4355, 5.439], time_window=0.000034, time_step=0.000034, sampling_freq=30000, zlimits=[-300, 100],filename='I:\Ephys\Data juxta_extra\data_25_11_72um\paper\\mymovie.avi'): ''' This function creates a video file of time ordered heatmaps. Inputs: data is a numpy array containing the data to produce all the heatmaps. time_axis is a numpy array containing the time points of sampling. (in seconds) channel_positions is a Pandas Series with the positions of the electrodes (this is the output of polytrode_channels function) times_to_plot defines the upper and lower bound of the time window to be used. (in seconds) time_window defines the size of the window to calculate the average. (in seconds) time_step is the time interval between consecutive heatmaps (in seconds). sampling_freq is the sampling frequency, in Hz, at which the data was acquired. zlimits defines the limits of the magnitude of all heatmaps. filename is the path to the output video file. ''' global images, sub_time_indices fig = plt.figure() ax1 = fig.add_subplot(1, 2, 1) ax2 = fig.add_subplot(1, 2, 2) sample_step = int(time_step * sampling_freq) sub_time_indices = np.arange(find_closest(time_axis, times_to_plot[0]), find_closest(time_axis, times_to_plot[1])) sub_time_indices = sub_time_indices[0::sample_step] print(sub_time_indices) if np.size(channel_positions) <= 64: text_y = 8.3 elif np.size(channel_positions) <= 128: text_y = 17 text_x = -8 images = [] for t in sub_time_indices: samples = [t, t + (time_window*sampling_freq)] print(t) data_to_plot = np.mean(data[:, int(samples[0]):int(samples[1])], 1) image, scat = plot_topoplot128(ax2, channel_positions, data_to_plot, show=False, interpmethod="quadric", gridscale=5, zlimits=zlimits) ax2.set_yticks([], minor=False) ax2.set_xticks([], minor=False) stringy = '%.2f' % (time_axis[t]*1000) stringy = 't' + '=' + stringy + ' ms' txt = plt.text(x=text_x, y=text_y, s=stringy) #ax2.text(4,22, '\u00B5V') ax2.set_title("JTA voltage at t / \u00B5V") if t < np.max(sub_time_indices) - 30 - np.min(sub_time_indices): pointsToPlot = juxtaData[ t-15:t-15+30] else: pointsToPlot = juxtaData[t-15:t-15+30] grafico, = ax1.plot(np.arange(-15, 15)/30., pointsToPlot, 'b') #ax1.set_yticks([0], minor=False) #ax1.set_yticks([0], minor=True) #ax1.yaxis.grid(False, which='major') #ax1.yaxis.grid(False, which='minor') ax1.set_xticks([0]) ax1.grid(True) ax1.set_title("Juxta Signal/ mV") images.append([grafico, image, scat, txt]) FFwriter = animation.FFMpegWriter() ani = animation.ArtistAnimation(fig, images, interval=1000, blit=True, repeat_delay=1000) plt.colorbar(mappable=image) if filename is not None: ani.save(filename, writer=FFwriter, fps=0.5, bitrate=5000, dpi=300, extra_args=['h264']) plt.show()
ub = t[idx] if idx < len(t) else t[len(t) - 1] for j in range(0, 10): tau = (lb + ub) / 2 if dist(src_x(tau), src_y(tau), obs_x(ti), obs_y(ti)) < (ti - tau) * sonic: lb = tau else: ub = tau signal.append(org(tau) / ((ti - tau) * gain + 1)) # アニメーションの準備 fig = plt.figure() ims = [] for ti in t[::step]: im = plt.plot(src_x(ti), src_y(ti), 'ro', obs_x(ti), obs_y(ti), 'bo') ims.append(im) # 音の再生(別スレッド) thread_p = threading.Thread(target=play, args=([signal])) thread_p.start() # アニメーションの再生 ani = animation.ArtistAnimation(fig, ims, interval=1000 * step / fs, repeat=False) plt.show() # なんかちょっとずれる!
fig = plt.figure() ax = fig.add_axes([0, 0, 1, 1]) ax.axis('off') #create empty list for images myimages = [] #create array to loop through - should correspond to num of images T = np.arange(0, 1100, 50) #loops through images for i in range(len(T)): #read in figure fname = 'C:/Users/Amanda/Desktop/3DFigs/year%i.png' % T[ i] #this is where your images are saved img = mgimg.imread(fname) #read in images imgplot = plt.imshow(img) #plot #append image to the list myimages.append([imgplot]) #animate using mpl.animation.ArtistAnimation my_anim = animation.ArtistAnimation(fig, myimages) #define writer to save animation writer = animation.ImageMagickFileWriter(fps=2) #save animation my_anim.save('C:/Users/Amanda/Desktop/test.gif', writer=writer, dpi=300)
ax1.set_xlim(t_start, t_end) ax1.set_ylim(-1, 1) ax1.xaxis.set_major_locator(plt.MultipleLocator(np.pi / 2)) ax1.xaxis.set_major_formatter(plt.FuncFormatter(multiple_formatter())) ax1.grid(True) ax1.hlines(0, t_start, t_end, color="black", alpha=0.5) ax1.vlines(0, -1, 1, color="black", alpha=0.5) ax1.set_xlabel(r'$t \rightarrow$') ax1.set_ylabel(r'$A_m \rightarrow$') plt.subplots_adjust(top=0.9, bottom=0.2, right=0.9, left=0.1, wspace=0.3) ims = [] for t in interval: x0, y0 = on_circle(t, init_phase) p = ax0.plot([0, x0], [0, y0], c = 'black')\ + ax0.plot([0, 0], [0, y0], c = 'blue', lw = 3)\ + ax0.plot([0, x0], [y0, y0], ls = '--', c = 'black', lw = 1)\ + ax0.plot(0, y0, marker = 'o', c = 'blue', ms = 5)\ + ax0.plot(x0, y0, marker = 'o', c = 'black', ms = 5)\ + ax1.plot(t, wave(t, init_phase), marker = 'o', c ='blue', ms= 5)\ + ax1.plot([t, t], [0, wave(t, init_phase)], c = 'blue', lw = 3) ims.append(p) ani = animation.ArtistAnimation(fig, ims, interval=100, repeat=True) #ani.save('pendulum.gif', writer='imagemagick') plt.show()
y_ = reg.predict(X, _weights) correct, = ax1.plot(X.squeeze(), y, '.r') prediction, = ax1.plot(X.squeeze(), y_, 'b') lines1.append(prediction) lines1.append(correct) ax1.legend([prediction, correct], ["Fitted Line", "Data"]) loss, = ax2.plot(potential_weights, losses, 'b') current_loss, = ax2.plot(_weights[0], _loss, 'Xr', markersize=10) ax2.legend([loss, current_loss], ["Loss", "Current Loss"]) lines2.append(current_loss) lines2.append(loss) ims.append([*lines1, *lines2]) anim = animation.ArtistAnimation(fig, ims, interval=200, blit=True, repeat_delay=100) # anim.save("visualization/gif/gradient_descent.mp4") plt.show()
'Decrease stress levels, sleep more and engage.', 'Stay curious and try our StudyBuddy feature.' ] fig, ax = plt.subplots() figure = ax.imshow(image) ims = [] for iternum in [0, 1, 2]: title = plt.text(0.5, 1.01, suggestions[iternum], ha="center", va="bottom", color=np.random.rand(3), transform=ax.transAxes, fontsize=12) ims.append([ figure, title, ]) animated = animation.ArtistAnimation(fig, ims, interval=5000, blit=False, repeat_delay=2000) ax.axis('off') plt.show()
def create_plot_animation(plt, trajs, shuffled_ped_ids, target_id, inv_lookup ,seq_lenght, marker, colors, name, data_frames, true_target_id_values, plot_directory, style, num_of_color): # method to create a video for each frame print("Video creation for ", name, " is starting...") min_r = style[0] max_r = style[1] plot_offset = style[2] plt.gca().set_xlim([min_r - true_target_id_values[0] - plot_offset, max_r - true_target_id_values[0]+ plot_offset]) plt.gca().set_ylim([min_r - true_target_id_values[1]- plot_offset, max_r - true_target_id_values[1]+ plot_offset]) frames = [] marker_cycle = itertools.cycle(marker) marker_arr = [] for frame_num in range(0, seq_lenght-1): frame_obj = [] plt.gca().set_prop_cycle(cycler('color', colors)) for elem_index ,index in enumerate(shuffled_ped_ids): filtered_true_x = trajs[index][0][0] filtered_true_y = trajs[index][0][1] filtered_pred_x = trajs[index][1][0] filtered_pred_y = trajs[index][1][1] real_true_index = min(frame_num, len(filtered_true_x)) real_pred_index = min(frame_num, len(filtered_pred_x)) marker_cycle = get_marker_style(marker, marker_cycle , elem_index, num_of_color) if frame_num == 0: curr_marker = next(marker_cycle) marker_arr.append(curr_marker) #if len(filtered_true_x) < frame_num or len(filtered_pred_x) < frame_num: # del trajs[index] # continue ped_id = inv_lookup[index] selected_frames = data_frames[0:frame_num+1] frame_str = "Frame: "+str(int(selected_frames[-1])) true_ped_text = 'ped '+str(ped_id)+' true' pred_ped_text = 'ped '+str(ped_id)+' pred.' if ped_id == target_id: true_ped_text = 'target ped '+str(ped_id)+' true' pred_ped_text = 'target ped '+str(ped_id)+' pred.' if frame_num == 0: pred_sc = plt.scatter(filtered_pred_x[0:real_pred_index+1], filtered_pred_y[0:real_pred_index+1], marker= marker_arr[elem_index], label = pred_ped_text) else: pred_sc = plt.scatter(filtered_pred_x[0:real_pred_index+1], filtered_pred_y[0:real_pred_index+1], marker= marker_arr[elem_index]) frame_obj.append(pred_sc) if frame_num == 0: true_sc = plt.scatter(filtered_true_x[0:real_true_index+1], filtered_true_y[0:real_true_index+1], marker= marker_arr[elem_index], label = true_ped_text) else: true_sc = plt.scatter(filtered_true_x[0:real_true_index+1], filtered_true_y[0:real_true_index+1], marker= marker_arr[elem_index]) frame_obj.append(true_sc) title = plt.text(0.5,1.01,frame_str, ha="center",va="bottom",color=np.random.rand(3), transform=plt.gca().transAxes, fontsize="large") frame_obj.append(title) frames.append(frame_obj) plt.gca().legend(loc='best') ani = animation.ArtistAnimation(plt.gcf(), frames, interval=1200, blit=False, repeat_delay=1000) ani.save(plot_directory+'/'+name+'.mp4') print("Video creation ended.")
ret = comm.gather(combine_data, root=0) if rank == 0: ret1 = numpy.reshape(range(COLS), (1, COLS)) ret1[0:COLS] = 0 last_row = ret1[0:COLS] for aaa in range(1, size): ret1 = numpy.r_[ret1, ret[aaa]] ret1 = numpy.r_[ret1, last_row] local_data = numpy.copy(ret1) im = plt.imshow(local_data, animated=True, interpolation='None') ims.append([im]) if numpy.sum(local_data) == 0: print("Extinction Occurs at generation = ", generation) break if rank == 0: print("Present Generation = %d" % (generation)) ani = animation.ArtistAnimation(fig, ims, interval=25, blit=False, repeat_delay=500) ani.save('animate_life.mp4') plt.show() #### mpirun -n 16 python animatelifempi.py
def anime(frames, fig, t_int, interval=100): """Plot animation with images frames """ ani = animation.ArtistAnimation(fig, frames, interval=interval, blit=True) return ani
def pheromoneConvergence(report: Report, output: str = 'PheromoneConvergence.mp4', color: str = 'Oranges'): """ Method that generates a video showing how the values of the pheromone matrix evolve throughout the iterations of the algorithm. Parameters ---------- report: antco.Report antco.report.Report instance returned by the antco.run() function. output: str Name of the output file under which the video will be saved. color: str Matplotlib colormap used to represent the pheromone values. """ # Check that the parameters necessary to represent convergence can be obtained. try: report.get('pheromones') except Exception: raise Exception( 'The Report instance does not have the "pheromones" value, make sure you have saved ' 'the "pheromones" value throughout the interactions of the algorithm using the method ' 'report.save("pheromones").') pheromone_evolution = report.get('pheromones') # Get max and min value min_val, max_val = None, None for values in pheromone_evolution.values(): p_min = np.min(values) p_max = np.max(values) if min_val is None or p_min < min_val: min_val = p_min if max_val is None or p_max > max_val: max_val = p_max cmap = plt.cm.get_cmap(color) fig, ax = plt.subplots() ims = [] for it, values in pheromone_evolution.items(): im = ax.imshow(values, vmin=min_val, vmax=max_val, cmap=cmap, animated=True) if it == 1: # Initial frame ax.imshow(values, vmin=min_val, vmax=max_val, cmap=cmap) ims.append([im]) ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000) # Save animation ani.save(output) plt.show()
def train_autoencoder(model, optimizer, loader_train, loader_test, num_epochs, **anim): state_np = np.random.get_state() state_py = random.getstate() state_torch = torch.random.get_rng_state() if 'animation_data' in anim: animation_enable = True animation_data = anim['animation_data'] if 'animation_colour' in anim: animation_colour = anim['animation_colour'] else: animation_colour = [['#539ecd'] * len(animation_data.dataset)] n_features = len(animation_colour) cols = math.ceil(math.sqrt(n_features)) rows = math.ceil(n_features / cols) # Create figure fig, axes = plt.subplots(rows, cols, figsize=(2 * cols, 2 * rows)) fig.tight_layout(rect=[0, 0, 1, 0.93]) axes = axes.flatten() if 'animation_labels' in anim: animation_labels = anim['animation_labels'] else: animation_labels = [f'Feature {i}' for i in range(n_features)] for i, ax in enumerate(axes): if i < n_features: ax.axis('equal') ax.axis([-3, 1, -3, 1]) ax.title.set_text(animation_labels[i]) plt.setp(ax.get_xticklabels(), visible=False) plt.setp(ax.get_yticklabels(), visible=False) else: ax.axis('off') frames = [] else: animation_enable = False random.setstate(state_py) np.random.set_state(state_np) torch.random.set_rng_state(state_torch) model.train() train_losses = [] test_losses = [] for epoch in range(num_epochs): train_loss = 0 # TRAIN for i, data in enumerate(loader_train): model.train() data = data.to(model.device).float() out = model(data) loss = model.loss_fn(out, data) optimizer.zero_grad() loss.backward() optimizer.step() train_loss += loss.item() # DISPLAY/SAVE TRAINING LOSSES print("TRAIN: \tEpoch {0:2}, Loss:{1:8.4f}".format( epoch, train_loss / len(loader_train))) train_losses.append(train_loss / len(loader_train)) # DISPLAY/SAVE TESTING LOSSES model.eval() with torch.no_grad(): test_loss = 0 for i, data in enumerate(loader_test): data = data.to(model.device).float() out = model(data) total = model.loss_fn(out, data) test_loss += total.item() print("TEST: \tEpoch {0:2}, Loss:{1:8.4f}".format( epoch, test_loss / len(loader_test))) test_losses.append(test_loss / len(loader_test)) if animation_enable: state_np = np.random.get_state() state_py = random.getstate() state_torch = torch.random.get_rng_state() encoded = model.encode_inputs(animation_data) # encoded = np.random.rand(len(animation_colour[0]),2) frame = [] title = plt.figtext(0.5, 0.97, "Epoch: {0:4}".format(epoch), size=plt.rcParams["axes.titlesize"], ha="center") frame.append(title) for i, ax in enumerate(axes): if i < n_features: ax.axis('equal') ax.axis([-3, 1, -3, 1]) scat = ax.scatter(encoded[:, 0], encoded[:, 1], c=animation_colour[i], s=2) frame.append(scat) frames.append(frame) random.setstate(state_py) np.random.set_state(state_np) torch.random.set_rng_state(state_torch) ret = {'train_loss': train_losses, 'test_loss': test_losses} if animation_enable: anim_obj = animation.ArtistAnimation(fig, frames, interval=50, blit=False) if 'animation_path' in anim: anim_obj.save(anim['animation_path'], fps=15) # ret['gif'] = anim_obj.to_jshtml() plt.clf() return ret
# This note is extremely useful to understand how to return a 2d array! # https://stackoverflow.com/questions/43013870/how-to-make-c-return-2d-array-to-python?noredirect=1&lq=1 # We can never pass a 2d array, therefore return 1d array in a C function perlinNoise2D.restype = ndpointer(dtype=ctypes.c_float, shape=(resolution.y, resolution.x)) result = perlinNoise2D(ctypes.c_int(lattice.x), ctypes.c_int(lattice.y), ctypes.c_int(resolution.x), ctypes.c_int(resolution.y)) plt.imshow(result, cmap='gray') plt.tight_layout() plt.savefig("noise2d.png") plt.show() result = octavePerlin2d((8, 16), (512, 1024), 4) plt.imshow(result, cmap='gray') plt.tight_layout() plt.savefig("octavenoise2d.png") plt.show() noise = octavePerlin3d((1, 4, 4), (40, 256, 256), 4) fig = plt.figure() images = [[ plt.imshow(layer, cmap='hot', interpolation='lanczos', animated=True) ] for layer in noise] animation = animation.ArtistAnimation(fig, images, interval=50, blit=False) plt.tight_layout() animation.save('cppnoise.gif', writer="imagemagick", fps=20, dpi=100) plt.show()
def plot_animation(self, interval=400, xinch=5, yinch=5, notebook=True, smoothness=400): xlim = (np.min(self.X[:, 1]) - 0.2 * np.std(self.X[:, 1]), np.max(self.X[:, 1]) - 0.2 * -np.std(self.X[:, 1])) ylim = (np.min(self.X[:, 2]) - 0.2 * np.std(self.X[:, 2]), np.max(self.X[:, 2]) - 0.2 * -np.std(self.X[:, 2])) ycolor = np.where(self.y > 0, "#DC0026", "#457CB6") yshape = np.where(self.y > 0, "o", "^") xlin = np.linspace(xlim[0], xlim[1], smoothness) ylin = np.linspace(ylim[0], ylim[1], smoothness) xv, yv = np.meshgrid(xlin, ylin) pinp = np.c_[xv.ravel(), yv.ravel()] pinp = np.column_stack((np.ones(pinp.shape[0]), pinp)) if notebook: plt.ioff() fig = plt.figure() fig.subplots_adjust(left=0, right=1, bottom=0, top=1) ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=xlim, ylim=ylim) for s, c, x, y in zip(yshape, ycolor, self.X[:, 1], self.X[:, 2]): ax.scatter(x, y, c=c, marker=s) conts = [] for i in range(self.alpha_steps.shape[0]): z = self._predict(pinp, self.alpha_steps[i, ]) z = z.reshape(xv.shape) cont = ax.contourf(xv, yv, z, colors=["#DC0026", "#457CB6"], alpha=1 / 5) te = ax.text(0.10, 0.95, u"Step: {}".format(i), bbox={ 'facecolor': 'w', 'alpha': 0.5, 'pad': 5 }, transform=ax.transAxes, ha="center") conts.append(cont.collections + [te]) fig.set_size_inches(xinch, yinch, True) anim = animation.ArtistAnimation(fig, conts, interval=interval, blit=False) return anim
def Heat(): ''' The following function solves the homogenous Heat equation associated with Dirichlet and Neuman boundary conditions: u_t(x,y,t) = u_xx(x,y,t) + u_yy(x,y,t) , (x,y) in [0,1] x [0,1], t>0 u(x,0,t) = 1.0 , u(x,1,t) = 0.0 , u_x(0,y,t) = u_x(1,y,t) = 0.0 t>0 u(x,y,0) = 0.0 , (x,y) in (0,1) x (0,1), on a grid of N by N points using the method of finite differences: This is aconsistent scheme for approximation of the solution of this problem (called the theta-method) delta_{h}^{-1} u_{h,n} = theta * nabla_{h}^2 u_{h}^{n+1} +(1-theta) * nabla_{h}^2 u_{h}^{n} 0<=theta<=1 The resulting linear system is then solved using a Jacobi preconditioned sparse congugate gradient method. For theta = 0.5, the approximation is second order in both space and time. ''' N=20 k=0.01 theta=0.5 tol=1e-10 h = 1./N GAMMA = k/h**2 # Constructing Evolution matrices. # Resulting system is Anew u^n+1 = Aold u^n + c aold = (1.0 - theta)*GAMMA bold = 1.0 - 4.0*(1.0 - theta)*GAMMA anew = -theta*GAMMA bnew = 1.0 + 4.0*theta*GAMMA def HeatMat(a,b,N): offdiag = np.full( (N-1)*N , a ) offdiag[0:(N-1)] *= 2.0 T = np.diag([a]*(N-2),-1) + np.diag([b]*(N-1)) + np.diag([a]*(N-2),1) A = sparse.csr_matrix(np.kron(np.eye(N+1),T) + np.diag(offdiag[::-1],-(N-1)) + np.diag(offdiag,(N-1))) return A Aold = HeatMat(aold,bold,N) Anew = HeatMat(anew,bnew,N) c = np.zeros(Anew.shape[0]) for i in xrange(N+1): c[i*(N-1)] = GAMMA fig = plt.figure() plt.title("Solution to heat equation") plt.xlabel("x") plt.ylabel("y") uold = np.zeros(Anew.shape[0]) U = np.vstack((np.ones(N+1),np.reshape(uold, (N-1,N+1) ,order='F'),np.zeros(N+1))) ims = [] im = plt.imshow(U, cmap='hot', interpolation='nearest',extent=(0.0,1.0,0.0,1.0), animated=True) plt.colorbar() ims.append([im]) while True: unew = spl.cg(Anew,Aold.dot(uold[:]) + c, M = np.diag([bnew]*(N-1)*(N+1)),tol=tol) U = np.vstack((np.ones(N+1),np.reshape(unew[0], (N-1,N+1) ,order='F'),np.zeros(N+1))) im = plt.imshow(U, cmap='hot', interpolation='nearest',extent=(0.0,1.0,0.0,1.0), animated=True) #plt.colorbar() ims.append([im]) if np.linalg.norm(unew[0]-uold,np.Inf)/np.linalg.norm(unew[0],np.Inf)<tol: break uold = copy(unew[0]) ani = animation.ArtistAnimation(fig, ims, interval=50, blit=True, repeat_delay=1000) ani.save('Heat.mp4') return U
a = 1.2 capacity = 100 num = 20 x_size = 8.0 y_size = 6.0 # 初期化(初期値設定) n = np.zeros(num) n[0] = 2 list_plot = [] # 時間発展方程式 fig = plt.figure() for t in range(1, num): delta = int(a * n[t - 1] * (1 - n[t - 1] / capacity)) n[t] = delta * dt + n[t - 1] x_n = np.random.rand(int(n[t])) * x_size y_n = np.random.rand(int(n[t])) * y_size img = plt.scatter(x_n, y_n, color="black") list_plot.append([img]) # グラフ(アニメーション)描画 plt.grid() anim = animation.ArtistAnimation(fig, list_plot, interval=200, repeat_delay=1000) rc('animation', html='jshtml') plt.close() anim
def Visualize(self, path=None, filename=None, viz_type='difference', save_video=False): if path is None: path = self.result_path if filename is None: filename = '/results' im = [] if self.n <= 1: # 1d fig = mpl.figure() x = np.linspace(x_start, x_end, self.m) counter = 1 for step in sorted(glob.glob(path + filename + '*.txt')): tmp = np.loadtxt(step) mpl.title('t=%.3f/%.3f' % (counter * self.dt, self.T * self.dt)) if viz_type == 'difference': im.append( mpl.plot(x, (self.exact(x, np.zeros( self.m), counter * self.dt) - tmp), 'b-')) elif viz_type == 'exact': im.append( mpl.plot( x, self.exact(x, np.zeros(self.m), counter * self.dt), '-b')) else: im.append(mpl.plot(x, tmp, 'b-')) if save_video: fig.savefig(step.split('.')[0] + '.png') counter += 1 ani = animation.ArtistAnimation(fig, im) if save_video: self.MakeVideo(sorted(glob.glob(path + filename + '*.png'))) mpl.show() else: X, Y = np.meshgrid(np.linspace(0, 1, self.m), np.linspace(0, 1, self.n)) mpl.ion() fig = mpl.figure() ax = fig.add_subplot(111, projection='3d') counter = 1 for step in sorted(glob.glob(path + filename + '*.txt')): # time.sleep(0.3) tmp = np.loadtxt(step) if viz_type == 'difference': wframe = ax.plot_wireframe( X, Y, (self.exact(X, Y, (counter * self.dt)) - tmp)) elif viz_type == 'exact': wframe = ax.plot_wireframe( X, Y, self.exact(X, Y, (counter * self.dt))) else: wframe = ax.plot_wireframe(X, Y, tmp) mpl.draw() if counter == 1 and viz_type != 'difference': # pass ax.set_autoscaley_on(False) if save_video: fig.savefig(step.split('.')[0] + '.png') ax.collections.remove(wframe) counter += 1 if save_video: self.MakeVideo(sorted(glob.glob(path + filename + '*.png')))
fig = plt.figure(figsize=(8,5)) plt.subplots_adjust(bottom=0.0, top=1.0, left=0.0, right=1.0) # loop date curr_date = start_date curr_date_d = datetime.datetime.strptime(curr_date, '%Y-%m-%d') end_date_d = datetime.datetime.strptime(end_date, '%Y-%m-%d') while curr_date_d <= end_date_d: # current date curr_date = str(curr_date_d)[0:10] print('--------------------- ' + curr_date + ' ---------------------') # read image imgname = fig_dir + varn + '_' + lev + 'hPa' \ + '_' + curr_date + '.png' print('read ' + imgname) img = mpimg.imread(imgname) img_list.append([plt.imshow(img, animated=True)]) # go to next day curr_date_d = curr_date_d + datetime.timedelta(days=1) ani = animation.ArtistAnimation(fig, img_list, interval=600, blit=True, repeat_delay=20000) out_file = fig_dir + varn + '_' + lev + 'hPa' \ + '_' + start_date + '_' + end_date + '.gif' ani.save(out_file, dpi=300)