def export_gif(self, type_ic=None): ''' Returns a gif showing the behaviour of ultrametric difussion equations. type_ic: type of initial condition(normal,random,ones) default = normal establishes the values of initial condition vector. It can be distributed normally with mean 0 and variance 1, randomly and constant(ones in every entry of initial condition vector). ''' frames = [] u = self.ODESols(type_ic) for u_i, t_i in zip(u[0], u[1]): frame = self.animate(u_i, t_i, type_ic) frames.append(frame) name = 'G' + str(self.p) + '_' + str(abs(self.n)) + str(self.N) if (type_ic != None): gif.save(frames, name + "_" + type_ic + "_difussion.gif", duration=1000) else: gif.save(frames, "gifs/" + name + "_normal_difussion.gif", duration=1000)
def create_subplot_gif(TX, TY, TZ, nframes): frames = [] for i in range(nframes): frame = gif_scatter_subplots(i, TX[0:i + 1], TY[0:i + 1], TZ[0:i + 1]) frames.append(frame.copy( )) #.copy() addition is a temporary fix until PIL is updated gif.save(frames, f"subplots_example.gif", duration=100)
def sequential_prediction_command(args): data, to_predict, true_data, tide_height_nans = process_data(normalise_data=True) max_time = data.index.max() means = [] variances = [] predictions = [] data_chunks = [] for data_chunk in chunk(data): prediction, mean, var = sequential_predictions(data_chunk, max_time=max_time) means.append(mean) variances.append(var) predictions.append(prediction) data_chunks.append(data_chunk) @gif.frame def animate(i): plot = GPPlot( data_chunks[i], true_data, means[i], variances[i], [predictions[i]], TIDE_HEIGHT, join=False, ) plot.init_plot() plot.plot() frames = [animate(i) for i in range(len(means))] gif.save(frames, f"{args.fig_name}.gif", duration=60, unit="s", between="startend")
def saved_gif(): @gif.frame def plot(x, y): plt.scatter(x, y) frames = [plot([0, 5], [0, 5]), plot([0, 10], [0, 10])] gif.save(frames, "test-matplotlib.gif")
def logistic_map_gif(x0: float = 0.5, n_values: int = 100, start: float = 0, stop: float = 4.5, n_frames: int = 100, gif_duration: int = 10, **kwargs: Any) -> None: """Create the sequential logistic gif. Generate a gif showing how the plot of a logistic map changes for parameter values ranging between 0 and 4.5. Args: x0 (float): The initial starting value. n_values (int): The amount of values to compute per frame. start (float): Starting value for r. stop (float): Final value for r. n_frames (int): Number of frames to capture between start and stop. gif_duration (int): The duration of the gif to produce in seconds. **kwargs (Any): Possible extra kwargs. """ frames = [] for r in tqdm(np.linspace(start=start, stop=stop, num=n_frames)): frames.append(plot_sequential(x0, n_values, logistic, r=r)) gif.save(frames, Path() / 'src' / 'logistic_map.gif', duration=gif_duration, unit='s', between='startend')
def task_create_convergence_gif(produces, algorithm): start_x = np.array([2]) hessian = example_hessian if algorithm == "trust-ncg" else NotImplementedError res = minimize_with_history( example_criterion, start_x, method=algorithm, jac=example_gradient, hess=hessian ) # repeat the last point to show it longer in the gif points = res.history + [res.history[-1]] * 2 @gif.frame def _plot_history(points): fig, ax = plot_function() sns.rugplot(points, ax=ax) plt.plot( points[-1], example_criterion(points[-1]), marker="*", ) sns.despine() frames = [] for i in range(len(points)): frames.append(_plot_history(points[: i + 1])) gif.save(frames, produces, duration=2.5, unit="s")
def saved_gif(): @gif.frame def plot(x, y): plt.scatter(x, y) frames = [plot([10, 20], [30, 40]), plot([20, 30], [40, 50])] gif.save(frames, "test.gif")
def create_gif(plot, data, nframes, name): frames = [] for i in range(nframes): frame = plot(data[i]) frames.append(frame.copy( )) #.copy() addition is a temporary fix until PIL is updated gif.save(frames, f"{name}.gif", duration=100)
def task_create_stylized_algo_gif(produces, algorithm): plot_data = STYLIZED_ALGORITHMS[algorithm]() # repeat the last point to show it longer in the gif plot_data = plot_data + [plot_data[-1]] * 2 @gif.frame def visualize_step(evaluated_x, new_x, aux_line=None, remark=None): fig, ax = plot_function() sns.rugplot(x=evaluated_x) ax.plot([new_x], [example_criterion(new_x)], marker="*") if aux_line is not None: sns.lineplot(x=aux_line["x"], y=aux_line["y"]) if remark is not None: plt.subplots_adjust(bottom=0.25) plt.figtext( 0.5, 0.05, remark, multialignment="center", ha="center", wrap=True, fontsize=14, bbox={ "facecolor": "white", "alpha": 0.5, "pad": 5, "edgecolor": "#ffffff00", }, ) frames = [] for data in plot_data: frames.append(visualize_step(**data)) gif.save(frames, produces, duration=7.5, unit="s")
def plot_linreg_animate(E_batch, mu_P, S_P, n, sigma): frames = [] for alpha in np.geomspace(start=0.0001, stop=10 * n, num=100): #for alpha in np.linspace(start=0, stop=3 * n, num=40): frame = plot_linreg_internal(alpha, E_batch, mu_P, S_P, n, sigma) frames.append(frame) gif.save(frames, "../plots/linreg_anim.gif", duration=50)
def phase_intersect(): @gif.frame def make_frame(f2, phi_): plt.style.use('seaborn') fig = plt.figure(figsize=(9, 3)) max_t = 0.01 time = np.linspace(0.0, max_t, 2000) intersect1 = max_t / 3 intersect2 = intersect1 * 2 sin2 = np.sin(2 * np.pi * f2 * time + phi_) props = dict(boxstyle='round', facecolor='wheat', alpha=1.0) plt.plot(time, sin2, 'g') plt.axvline(x=intersect1, ls='--', color='black', lw=1.0) sin2_val1 = np.sin(2 * np.pi * f2 * intersect1 + phi_) plt.text(intersect1 - 0.00045, -1.275, 'Snapshot 1', bbox=props) plt.gcf().text(0.85, 0.65, 'Value at:') plt.gcf().text(0.85, 0.55, f'Snapshot 1 = {sin2_val1:+0.2f}') plt.axvline(x=intersect2, ls='--', color='black', lw=1.0) sin2_val2 = np.sin(2 * np.pi * f2 * intersect2 + phi_) plt.text(intersect2 - 0.00045, -1.275, 'Snapshot 2', bbox=props) plt.gcf().text(0.85, 0.45, f'Snapshot 2 = {sin2_val2:+0.2f}') plt.title(f'Frequency {f2:0.2f} Hz, Initial Phase {phi_ / np.pi:0.2f}' + r'$\pi$') plt.ylabel('Amplitude') plt.xlabel('Time (s)') plt.ylim([-1.4, 1.1]) plt.xlim([0.0, 0.01]) plt.subplots_adjust(right=0.85) for ax in fig.axes: ax.label_outer() plt.tight_layout(rect=[0, 0, .85, 1.0]) # plt.show() # f2 = 523.25 # C above A440 # make_frame(f2, 0.0) # return f2_min = 440.0 f2_max = 880.0 f2_steps = np.hstack([np.linspace(f2_min, f2_max, 20), np.ones(20) * f2_max, np.linspace(f2_max, f2_min, 20), np.ones(20) * f2_min]) phi_steps = np.hstack([np.zeros(20), np.linspace(0.0, 2 * np.pi, 20), np.ones(20) * 2 * np.pi, np.linspace(2 * np.pi, 0.0, 20), np.zeros(20)]) frames = [make_frame(f, p) for f, p in zip(f2_steps, phi_steps)] gif.save(frames, 'book/images/basics/phase_sensitivity.gif', duration=3.0)
def simulate(settings, organisms, foods, gen): total_time_steps = int(settings['gen_time'] / settings['dt']) #--- gif library tests frames = [] #--- CYCLE THROUGH EACH TIME STEP ---------------------+ for t_step in range(0, total_time_steps, 1): print(t_step) # PLOT SIMULATION FRAME if settings['plot'] == True and gen == settings['gens'] - 1: frame = plot_frame(settings, organisms, foods, gen, t_step) frames.append(frame) # UPDATE FITNESS FUNCTION for food in foods: for org in organisms: food_org_dist = dist(org.x, org.y, food.x, food.y) # UPDATE FITNESS FUNCTION if food_org_dist <= 0.075: org.fitness += food.energy food.respawn(settings) # RESET DISTANCE AND HEADING TO NEAREST FOOD SOURCE org.d_food = 100 org.r_food = 0 # CALCULATE HEADING TO NEAREST FOOD SOURCE for food in foods: for org in organisms: # CALCULATE DISTANCE TO SELECTED FOOD PARTICLE food_org_dist = dist(org.x, org.y, food.x, food.y) # DETERMINE IF THIS IS THE CLOSEST FOOD PARTICLE if food_org_dist < org.d_food: org.d_food = food_org_dist org.r_food = calc_heading(org, food) # GET ORGANISM RESPONSE for org in organisms: org.think() # UPDATE ORGANISMS POSITION AND VELOCITY for org in organisms: org.update_r(settings) org.update_vel(settings) org.update_pos(settings) if (len(frames) > 0): gif.save(frames, "test.gif", duration=settings['gen_time']) return organisms
def save_gif(): df = pd.DataFrame({"t": [1, 2], "x": [5, 10], "y": [5, 10]}) @gif.frame def plot(t): d = df[df["t"] == t] return alt.Chart(d).encode(x="x", y="y").mark_circle() frames = [plot(1), plot(2)] gif.save(frames, "test-altair.gif")
def animation_to_gif(fig, filename, frame_duration=100, width=1200, height=800): import gif @gif.frame def plot(f, i): f_ = go.Figure(data=f["frames"][i]["data"], layout=f["layout"]) f_["layout"]["updatemenus"] = [] f_.update_layout(title=f["frames"][i]["layout"]["title"], width=width, height=height) return f_ gif.save([plot(fig, i) for i in range(len(fig["frames"]))], filename, duration=frame_duration)
def plot_polyreg_animate(E_batch, mu_P, S_P, n, sigma, d, f): frames = [] for alpha in np.geomspace(start=1e-5, stop=1e+10, num=600): #for alpha in np.linspace(start=0, stop=3 * n, num=40): frame = plot_polyreg_internal(alpha, E_batch, mu_P, S_P, n, sigma, d, f) frames.append(frame) gif.save(frames, "../plots/polyreg_anim.gif", duration=50)
def AnimateTables3D(c, r, m, i, e, style=solid, dots=False): title = f"mod{m} 3D Times Tables" Setup3D(title, r) GeneratePoints(r, m) GenerateLocations() TablesGif3D(c, m, i, e, style, dots) print("Building gif. . .") s = StyleCheck(style) name = f"modtables3D_({c}-{e})mod{m}_{s}.gif" gif.save(frames, name, duration=100) print(name + " complete.\n")
def save_gif(self, iterations: int, duration=1000) -> None: self.tile() frames = [self.gif_plot()] for _ in range(iterations - 1): self.iterate(1) self.tile() frame = self.gif_plot() frames.append(frame) gif.save( frames, "{0}_{1}.gif".format(type(self).__name__, iterations), duration )
def plotting_gif(trajectories, outpath): """ trajectories: list of length number of timesteps, where each timestep is a list of trajectories in that timestep outpath: relative path to save gif """ imgs = [] for ts in tqdm(trajectories): imgs.append(gen_gif_img(ts)) gif.save(imgs, outpath, duration=300)
def gif_data(path, data): frames = [] num_frames = data.shape[0] print_progress = int(num_frames / 20) for i in range(num_frames): if i % print_progress == 0: print("GIF " + str(100 * i / num_frames) + "% complete") frame = get_frame(path, data, i) frames.append(frame) gif.save(frames, "path.gif", duration=1)
def plot_train_gif(self, gif_path, duration=3.5): @gif.frame def plot_gif_frame(gmms_params): self.visualize(gmms_params=gmms_params) frames = [] for gmms_params in self.train_record['gmms_params']: frame = plot_gif_frame(gmms_params=gmms_params) frames.append(frame) gif.save( frames, gif_path, duration=duration, unit='s', between='startend')
def save_gif(): df = pd.DataFrame({"t": [1, 2], "x": [5, 10], "y": [5, 10]}) @gif.frame def plot(t): d = df[df["t"] == t] fig = go.Figure() fig.add_trace(go.Scatter(x=d["x"], y=d["y"], mode="markers")) return fig frames = [plot(1), plot(2)] gif.save(frames, "test-plotly.gif")
def main(): pass sys = particles(f, 0.005) name_gif = "./move.gif" frames = [] for i in range(1000): frame = sys.printerSystem() frames.append(frame) sys() gif.save(frames, name_gif, duration=200)
def save_gif_with_options(): gif.options.matplotlib["dpi"] = 300 @gif.frame def plot(x, y): plt.scatter(x, y) frames = [plot([0, 5], [0, 5]), plot([0, 10], [0, 10])] gif.save(frames, "test-matplotlib_2s.gif", duration=2, unit="s", between="startend")
def main(): ndim = 2 nwalkers = 20 niterations = 1000 nthreads = 1 np.random.seed(1234) # Toy likelihood @emulate(CholeskyNnEmulator) def loglike(x): return np.array([-np.dot(x, x) ** 1]) loglike.output_err = True loglike.abs_err_local = 2 # Starting points for walkers p0 = np.random.normal(-1.0, 1.0, size=(nwalkers, ndim)) sampler = emcee.EnsembleSampler(nwalkers, ndim, loglike, threads=nthreads) # Sample with emcee with open("test.txt", "w") as f: for result in sampler.sample(p0, iterations=niterations, storechain=True): for pos, lnprob, err in zip(result[0], result[1], result[3]): for k in list(pos): f.write("%s " % str(k)) f.write("%s " % str(lnprob)) f.write("%s " % str(err)) f.write("\n") print("n exact evals:", loglike._nexact) print("n emul evals:", loglike._nemul) # Plot points sampled nframes = 50 duration = 10 frames = [] lim = (-3, 3) for i in range(0, niterations * nwalkers, niterations * nwalkers // nframes): x = sampler.chain.reshape(niterations * nwalkers, ndim)[:i] y = np.array(sampler.blobs).reshape(niterations * nwalkers)[:i] frame = plot(x, y, lim) frames.append(frame) gif.save(frames, "mc.gif", duration=duration)
def to_gif(self, fname, text, show_ascii=False, duration=300): """ Generate a GIF of the sequence disp.to_gif(fname, "text", show_ascii=False, duration=300) Generate a gif and write to the specified file naem. Duration specifies delay between each frame (miliseconds) Requires the gif package """ # Only import here (only needed for gifs) import gif @gif.frame def gif_frame(text, im, show_ascii): # Display the image plt.cla() plt.imshow(im) plt.axis('image') # Display the ascii representation if show_ascii: plt.text(65, 10, text, fontsize=30) frames = [] if not text: # Check if we have work to do im = self._images[':error'] frame = gif_frame('ER!', im, show_ascii) frames.append(frame) else: # Display the contents of text for ch in text: im = self._images[ch.lower()] frame = gif_frame(ch, im, show_ascii) frames.append(frame) # Display the ready message im = self._images[':ready'] frame = gif_frame('', im, show_ascii) frames.append(frame) gif.save(frames, fname, duration=duration)
def main(): """Makes a spinning globe .gif of Moon elevation""" imdata_small = load_lola_downsampled() moon_globe = ccrs.Globe(ellipse=None, # can remove after #1588/#564 semimajor_axis=Constants.moon_radius, flattening=Constants.moon_flattening) transform = ccrs.PlateCarree(globe=moon_globe) frames = [] all_the_angles = np.linspace(0, 360, 25)[:-1] for i, lon in enumerate(all_the_angles): print(f"{i+1}/{all_the_angles.size}...") frame = make_frame(imdata_small, moon_globe, transform, lon) frames.append(frame) gif.save(frames, os.path.join(Paths.fig_dir, "moon.gif"), duration=100)
def runAgent(agent, steps:int, name: str = None): """ Runs, generates and displays a gif in the colab notebook for gym classic control environments. Others like ALE don't need this method to display. parameters ---------- agent: Agent class Some agent class method steps: integer number of steps to run the policy on name: string name for the gif to be named after """ env = agent.env_test if agent.env_test is not None else agent.env policy = agent.policy procObs = agent.processObs name = name + ".gif" if name is not None else "runPolicy {}.gif".format(timeFormatedS()) frames = [] policy.test = True totR, epR, eps = 0, 0, 1 obs = env.reset() for _ in range(steps): frames.append(frame(env)) state = procObs(obs) action = policy.getAction(state) obs, reward, done, _ = env.step(action) epR += reward if done: obs = env.reset() eps += 1 totR += epR epR = 0 totR = totR / eps policy.test = False # Creates .gif gif.save(frames, name, duration = steps * 0.1, unit="s", between="startend") # Prints output print("Mean accumulate Reward {:.2f}, episodes {}".format(totR, eps)) # Displays gif repGIF(name)
def runPolicy(env, policy, steps:int, name:str = None): """ Runs, generates and displays a gif in the colab notebook for gym classic control environments. Others like ALE don't need this method to display. parameters ---------- env: gym environment The environment from the gym api policy: python object An object that works as the policy for said environment. Should accept the methods - .getAction(obs) - .test as bool steps: integer number of steps to run the policy on name: string name for the gif to be named after """ name = name + ".gif" if name is not None else "runPolicy {}.gif".format(timeFormatedS()) frames = [] policy.test = True totR, epR, eps = 0, 0, 1 obs = env.reset() for _ in range(steps): frames.append(frame(env)) action = policy.getAction(obs) obs, reward, done, _ = env.step(action) epR += reward if done: obs = env.reset() eps += 1 totR += epR epR = 0 totR = totR / eps policy.test = False # Creates .gif gif.save(frames, name, duration = steps * 0.1, unit="s", between="startend") # Prints output print("Mean accumulate Reward {:.2f}, episodes {}".format(totR, eps)) # Displays gif repGIF(name)
def save_gif(self, output, duration, start=0, stop=360, figsize=(15, 3), unit='s'): """ Saves the animation as an animated GIF. :param output: Output path. :param duration: Duration per frame. :param start: Start degree. :param stop: Stop degree. :param figsize: Figure size. Default is (15, 3). :param unit: Time units. Default is 's' for seconds. :return: None. """ frames = self.__get_gif_frames(start, stop, figsize) gif.save(frames, output, duration=duration, unit=unit)
def runEnv(env, steps:int, name:str = "lrun"): """ Run random steps in the environment """ name = name + ".gif" frames = [] totR, epR, eps = 0, 0, 1 env.reset() for _ in range(steps): frames.append(frame(env)) _, reward, done, _= env.step(env.action_space.sample()) epR += reward if done: env.reset() eps += 1 totR += epR epR = 0 totR = totR / eps gif.save(frames, name, duration = steps * 0.1, unit="s", between="startend") print("Mean accumulate Reward {:.2f}, episodes {}".format(totR, eps)) repGIF(name)