def make_animation(self):
        """Returns plot with map of journey"""

        fig, ax = plt.subplots(figsize=(5, 5))
        camera = Camera(fig)  # use simple library from github
        for ant in self.all_best_ants:

            # unpacking coordinates using dictionary with cities
            x_points = [self.cities[city][0] for city in ant.visited_cities]
            y_points = [self.cities[city][1] for city in ant.visited_cities]

            ax.set_xlabel('X')
            ax.set_ylabel('Y')
            ax.set_title('Map of the cities. Total path: %1.1f' %
                         ant.total_dist())
            ax.set_xlim([0, 820])
            ax.set_ylim([0, 820])

            ax.plot(x_points, y_points, 'ko')  # plot points
            ax.plot(x_points, y_points, 'r-')  # plot lines between points
            ax.plot(x_points[-1], y_points[-1], 'go')
            ax.plot(x_points[0], y_points[0], 'bo')

            # place city's name on the plot
            for city in ant.visited_cities:
                x, y = self.cities[city]
                ax.text(x, y + 7, city, fontsize=11)

            camera.snap()  # make a screenshot for animation

        Writer = ani.writers['pillow']
        writer = Writer(fps=0.5)

        animation = camera.animate()
        animation.save('Ant_colony_algorithm.gif', writer=writer)
Exemplo n.º 2
0
    def make_animation(self):
        """Make animation of evolutionary algorithm and save it as .gif"""

        fig, ax = plt.subplots()
        camera = Camera(fig)  # use simple library from github

        for i, generation in enumerate(self.generations):  # plotting individuals for every generation
            x = [x[0] for x in generation]
            y = [x[1] for x in generation]

            ax.scatter(x, y, s=10, color='black')
            plt.title('Teach Based Optimisation')
            camera.snap()  # make a screenshot for animation

        x1 = np.linspace(self.lB, self.uB, 100)  # generate coordinates for plotting func
        x2 = np.linspace(self.lB, self.uB, 100)
        # grid of coordinates, result - shape1 = (1, 100), shape2 = (100, 1)
        xx1, xx2 = np.meshgrid(x1, x2, sparse=True)
        z = np.empty([xx1.shape[1], xx2.shape[0]])  # empty matrix (100, 100)

        for i in range(xx2.shape[0]):  # filling z matrix using prepared functions
            for j in range(xx1.shape[1]):
                z[i, j] = self.function([xx1[:, j][0], xx2[i][0]])

        # plotting 2d heatmap of given function
        plt.pcolormesh(xx1, xx2, z, alpha=0.6, shading='auto', )
        plt.xlim(self.lB, self.uB)
        plt.ylim(self.lB, self.uB)
        plt.colorbar()

        Writer = ani.writers['pillow']
        writer = Writer(fps=20)

        animation = camera.animate()
        animation.save('Learning_Based_opt.gif', writer=writer)
def animate_traffic(fname='animation.mp4', save=False):
    # initiate camera to take snaps after every road update
    fig = plt.figure()
    cam = Camera(fig)

    frame = 0
    for state in config.plot_data:
        frame += 1
        plt.gca().set_xlim([0, len(state)])
        plt.gca().set_ylim([0, 2])
        plt.gca().axis('off')
        plt.gca().grid(b=None)
        plt.text(0, 1.5, str(frame))
        # draws filled block at car position and empty block at empty position
        for i in range(len(state)):
            if state[i] != 0:
                rectangle = plt.Rectangle((i, 0.05), 1, 1.04, color="k")
            else:
                rectangle = plt.Rectangle((i, 0.05), 1, 1.04, fill=False)
            plt.gca().add_patch(rectangle)
        plt.gca().autoscale(tight=False, axis="x")
        cam.snap()
    ani = cam.animate(interval=500, blit=False)
    if save:
        ani.save(fname)
    return HTML(ani.to_html5_video())
Exemplo n.º 4
0
def plot_state_probs(state_probs_t, energy_t, system_size, interaction_shape, radius, alpha, path):
    states = np.array(get_states_str(system_size))
    fig = plt.figure(figsize=(9, 12))
    plt.title('N = {}, {}, radius = {}, alpha = {}'.format(system_size, interaction_shape, radius, alpha))
    plt.xlabel('State')
    plt.ylabel('Probability')
    camera = Camera(fig)
    for t in range(0, len(state_probs_t)):
        state_probs = state_probs_t[t]
        max_prob = 0
        ground_states = []
        for state_id in range(len(state_probs)):
            state_prob = state_probs[state_id]
            if state_prob - max_prob > 1e-10:
                ground_states = [state_id]
                max_prob = state_prob
            elif abs(state_prob - max_prob) < 1e-10:
                ground_states.append(state_id)
        plt.bar(range(len(state_probs)), state_probs)
        plt.xticks(ground_states, labels=states[ground_states], rotation='vertical')
        plt.ylim(bottom=0, top=1)
        plt.text(0.05, 0.95, '<H> = {}'.format(round(energy_t[t], 1)), transform=fig.transFigure, verticalalignment='top')
        # fig.tight_layout()
        camera.snap()
    animation = camera.animate()
    animation.save('{}/state_probs_alpha_{}.gif'.format(path, alpha), writer = 'imagemagick')
    plt.close()
    # sample spin lattice in ground state
    print(np.reshape(np.array([int(spin) for spin in states[ground_states[0]]]), system_size))
Exemplo n.º 5
0
    def fit(self, data, verbose=False):
        start_time = datetime.now()
        n, self.features = data.shape
        self.mu = np.random.randn(self.n_components, self.features)
        sig = np.eye(self.features)
        sig = [np.array([sig])] * self.n_components
        self.sig = np.concatenate(sig)

        old_param = np.concatenate([self.mu.flatten(), self.sig.flatten()])

        fig, axes = plt.subplots(1, 1)
        camera = Camera(fig)
        can_verbose = False

        for i in range(self.max_iter):
            r = self.e_step(data)
            self.m_step(data, r)
            new_param = np.concatenate([self.mu.flatten(), self.sig.flatten()])
            if np.linalg.norm(new_param - old_param) < self.stop_dist:
                break
            old_param = new_param

            if verbose:
                if self.features == 1:
                    can_verbose = True
                    self.one_dim_plot(data, axes, camera, i)
                elif self.features == 2:
                    can_verbose = True
                    self.two_dim_plot(data, axes, fig, camera, i)

        print('Finish fitting in: %s' %
              (datetime.now() - start_time).total_seconds())
        if can_verbose:
            animation = camera.animate()
            plt.show()
Exemplo n.º 6
0
    def savePlot(self, bf_data, rg, outfile=None):

        print("Saving plot.........")
        fig = plt.figure(figsize=(8, 5))
        ax = fig.add_subplot(111)
        camera = Camera(fig)

        for i in range(0, bf_data.shape[2]):
            """
                setting of minimum (plot_min) is arbitrary and 
                is set by looping through all the frames and guessing a number
                """
            plot_min = bf_data[:, :, i].max() - 10
            plot_max = bf_data[:, :, i].max()

            #plot result
            im = ax.imshow(bf_data[:, :, i].T,
                           cmap='plasma',
                           origin='lower',
                           vmin=plot_min,
                           vmax=plot_max,
                           extent=rg.extend(),
                           interpolation='bicubic')

            max_bf_data = bf_data[:, :, i].max()

            ax.set_aspect('equal')
            for axi in (ax.xaxis, ax.yaxis):
                for tic in axi.get_major_ticks():
                    tic.tick1line.set_visible(False)
                    tic.tick2line.set_visible(False)
                    tic.label1.set_visible(False)
                    tic.label2.set_visible(False)

            fig.tight_layout(pad=0)

            #save plot to create .gif
            camera.snap()

        animation = camera.animate(interval=100, blit=True)

        gif_name = 'temp' + '_dist_' + str(self.distance) + '_freq' + str(
            self.freq_query) + '.gif'

        #decide where to store the file (base self.outfile)
        if self.outfile is None:
            output_dir = os.path.dirname(self.wav_path) + "/"
        else:
            output_dir = self.outfile + "/"

        gif_path = output_dir + gif_name

        if not os.path.exists(output_dir):
            os.mkdir(output_dir)

        #save .gif
        animation.save(gif_path, writer='imagemagick')
        plt.close('all')

        return gif_path
Exemplo n.º 7
0
    def plot_2D_gif(self ):
        fig = plt.figure()
        camera = Camera(fig)
        axis = plt.axes(xlim =(-3.3,3.3),  
                ylim =(-3.3, 3.3))  
  
        axis.set_title('Plane 3R Simulation')
        axis.set_xlabel("X-axis")
        axis.set_ylabel("Y-axis")
        line1, = axis.plot([], [], lw = 3)  
        line2, = axis.plot([], [], lw = 3)  
        line3, = axis.plot([], [], lw = 3)  
        po, = axis.plot(0,0)
        p1, = axis.plot(0,0,'ro')
        p2, = axis.plot(0,0,'ro')
        p3, = axis.plot(0,0,'bo')

        for i in range(len(self.x1)):
            po, = axis.plot(0,0,'go')
            p1, = axis.plot(self.x1[i][1],self.y1[i][1],'ro')
            p2, = axis.plot(self.x2[i][1],self.y2[i][1],'ro')
            p3, = axis.plot(self.x3[i][1],self.y3[i][1],'bo')
            line1, = axis.plot(self.x1[i], self.y1[i],lw = 3) 
            line2, = axis.plot(self.x2[i], self.y2[i],lw = 3) 
            line3, = axis.plot(self.x3[i], self.y3[i],lw = 3)
            camera.snap()

        animation = camera.animate(interval = 200, repeat = False)
                          
        animation.save('3R_planer.gif')
Exemplo n.º 8
0
Arquivo: PSO.py Projeto: hantke/PSO
    def plot_animation(self, filename = 'plot.gif', xdim = 0, ydim = 1, best = None):
        """
        Make an animation of the position and history of the particles

        Args:
            filename (str, optional): Name of the gif file. Defaults to 'plot.gif'.
            xdim (int, optional): Dimention of the x-axis. Defaults to 0.
            ydim (int, optional): Dimention of the y-axis. Defaults to 1.
            best (array, optional): Location of the real value, to compare in the plot. Defaults to None.
        """
        if self.rank != 0: return 
        print('Warning! This plotting code is not efficient, fast or elegant... yet..')
        import plotting
        plotting.set_style() #Sergio's Style, Really Important!
        import matplotlib.pyplot as plt
        import matplotlib.gridspec as gridspec
        from celluloid import Camera
            
        fig,ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 10))
        ax.set_xlabel(r'$\rm X$', fontsize=40)
        ax.set_ylabel(r'$\rm Y$', fontsize=40)
        ax.set_xlim([self.bounds[xdim][xdim],self.bounds[xdim][ydim]])
        ax.set_ylim([self.bounds[ydim][xdim],self.bounds[ydim][ydim]])
        camera = Camera(fig)
        for step in range(self.niter):
            ax.text(0.05, 0.9, r'$\rm step=%d$'%(step), transform=ax.transAxes, fontsize=30)
            ax.scatter(self.swarm['pos_histo'][step,:,xdim], self.swarm['pos_histo'][step,:,ydim],s=70,c=['r','g','b','c','m','y'])
            if best is not None: ax.scatter([best[0],], [best[1],],s=100,c='k')
            camera.snap()
        animation = camera.animate()
        animation.save(filename, writer = 'imagemagick')
Exemplo n.º 9
0
def save_video(frame_list, filename, fps):
    fig, ax = plt.subplots()
    camera = Camera(fig)

    # h, w, _ = frame_list[0].shape
    # fig.set_size_inches(w,h)

    for frame in frame_list:

        # BGR to RGB
        ax.imshow(frame[:, :, ::-1])
        # ax.axis("off")
        ax.xaxis.set_visible(False)
        ax.yaxis.set_visible(False)
        ax.set_frame_on(False)
        plt.tight_layout()
        camera.snap()

        # plt.savefig("dd.png")
        # raise ValueError

    interval_value = 1000 / fps
    animation = camera.animate(interval=interval_value, blit=True)
    animation.save(filename,
                   dpi=100,
                   savefig_kwargs={
                       'facecolor': 'none',
                       'pad_inches': 'tight'
                   })
Exemplo n.º 10
0
class Plotter():
    def __init__(self, title):
        self.title = title
        self.fig = plt.figure()
        self.camera = Camera(self.fig)

    def plot(self, data, first_highlight, second_highlight=None):
        self.data = data
        self.length = len(data)
        colours = list('b' * self.length)

        colours[first_highlight] = 'r'  # First highlight red
        if second_highlight is not None:
            colours[
                second_highlight] = 'g'  # Makes second highlight green (if present)

        plt.bar(list(range(self.length)), data, color=colours)
        plt.title(self.title)
        plt.xlabel("Index")
        plt.ylabel("Magnitude")
        self.camera.snap()

    def animate(self, data, save_file, interval=200):
        colours = list('g' * len(data))
        plt.bar(list(range(len(data))), data, color=colours)
        plt.title(self.title)
        plt.xlabel("Index")
        plt.ylabel("Magnitude")
        self.camera.snap()
        print(self.camera.animate(repeat=False,
                                  interval=interval).to_html5_video(),
              file=open(os.path.join(sys.path[0], 'templates', save_file),
                        'w+'))
        plt.close()
Exemplo n.º 11
0
def PlotGauss(x, mu, nu, plan):
    from matplotlib import pyplot as mp
    from celluloid import Camera
    fig = mp.figure()
    camera = Camera(fig)

    S = 200
    for a in [1.0 / S * i for i in range(S + 1)]:
        s = r'$\alpha$=' + str(round(a, 2))
        mp.text(0, 0.0035, s, fontsize=15)
        mp.plot(x, mu, color='blue')
        mp.plot(x, nu, color='darkgreen')

        # Displacement Interpolation
        pi = [0 for _ in x]
        for i, j in plan:
            p = (1 - a) * x[i] + a * x[j]
            h = 0
            for hh, px in enumerate(x):
                if px >= p:
                    h = hh - 1
                    break
            beta = (p - x[h]) / (x[hh] - x[h])
            pi[h] += (1 - beta) * plan[i, j]
            pi[h + 1] += beta * plan[i, j]

        mp.plot(x, MovingAvg(pi, 9), color='red')

        camera.snap()

    animation = camera.animate()
    animation.save('displacement.mp4')
Exemplo n.º 12
0
def plot_sir(time_grid, sus, infected, recovered):
    fig = plt.figure()
    camera = Camera(fig)
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    x_data, sus_data, infected_data, recovered_data = [], [], [], []
    for i in range(len(time_grid)):
        x_data.append(time_grid[i])
        sus_data.append(sus[i])
        infected_data.append(infected[i])
        recovered_data.append(recovered[i])
        ax.plot(x_data, sus_data, "b", alpha=0.5, lw=2, label="Susceptible")
        ax.plot(x_data, infected_data, "r", alpha=0.5, lw=2, label="Infected")
        ax.plot(x_data,
                recovered_data,
                "gray",
                alpha=0.5,
                lw=2,
                label="Recovered")
        camera.snap()

    ax.set_xlabel("days")
    ax.set_ylabel("Number of People")

    anim = camera.animate(interval=1)

    # Can change to your desired file location
    f = r"c://Users/briar/Desktop/animation.gif"

    anim.save(f)
    plt.show()
Exemplo n.º 13
0
def Plot(Mu, Nu, plan):
    from math import sqrt
    from matplotlib import pyplot as mp
    from celluloid import Camera
    fig = mp.figure()
    camera = Camera(fig)
    fig.patch.set_visible(False)
    mp.axis('off')

    S = 100
    for a in reversed([sqrt(1.0 / S * i) for i in range(S + 1)]):
        # Displacement Interpolation
        pi = []
        px = []
        py = []
        for i, j in plan:
            x, y = Interpolate(Mu[i], Nu[j], a)
            pi.append(plan[i, j])
            px.append(x)
            py.append(y)

        mp.scatter(px, py, color='darkblue', alpha=0.5)

        camera.snap()
    # mp.show()
    animation = camera.animate()
    animation.save('auguri.mp4')
Exemplo n.º 14
0
 def plot_lattice_trajectory_movie(self, cmap='winter'):
     # Plots a movie of a lattice trajectory
     print('Plotting Movie')
     state_position_trajectory = self.phospho_state_position_trajectory()
     fig, ax = plt.subplots()
     ax.axis('off')
     ax.set_aspect('equal')
     camera = Camera(fig)
     # set up artist objects so that each plot shares the same legend regardless of the presence or absence of specific
     # phosphorylation states
     scatter = plt.scatter([0, 0, 0, 0], [0, 0, 0, 0],
                           c=[0, 1, 2, 3],
                           cmap=cmap)
     artists, _ = scatter.legend_elements()
     for state_position in state_position_trajectory:
         plt.scatter(state_position[:, 0],
                     state_position[:, 1],
                     c=state_position[:, 2],
                     vmin=0,
                     vmax=3,
                     cmap=cmap)
         plt.legend(handles=artists,
                    labels=['0 pY', '1 pY', '2 pY', '3 pY'],
                    bbox_to_anchor=(1.05, 1))
         plt.tight_layout()
         camera.snap()
     animation = camera.animate(interval=500, blit=True)
     animation.save(self.save_dir + 'movie.gif', writer='imagemagick')
     plt.clf()
Exemplo n.º 15
0
    def _show(self, name_gif):
        fig, ax = plt.subplots()
        fig.set_figwidth(10)  # ширина и
        fig.set_figheight(10)  # высота "Figure"
        plt.axis('off')
        camera = Camera(fig)

        # сделаем несколько начальных кадров, чтобы пользователь
        #   увидел начальную картинку
        for a in range(4):
            ax.pcolormesh(self.arr, edgecolors='grey')
            camera.snap()

        for i in range(130):
            ax.pcolormesh(self.arr, edgecolors='grey')
            camera.snap()
            self._upgrade_iteration_life()

            if self._is_game_over():
                break

        for a in range(4):
            ax.pcolormesh(self.arr, edgecolors='grey')
            camera.snap()

        animation = camera.animate()
        animation.save(name_gif, writer='imagemagick')
def gradient_descent(x, y):
    m_curr = b_curr = 0
    learning_rate = 0.001
    iterations = 1000
    cost_lst = []
    i_lst = []
    n = len(x)
    fig = plt.figure()
    camera = Camera(fig)
    plt.scatter(x, y, c='green', marker='+')
    for i in range(iterations):
        y_pred = m_curr * x + b_curr
        #plt.plot(x,y_pred,color='red')
        #camera.snap()
        cost = sum([value**2 for value in (y - y_pred)])

        cost_lst.append(cost)
        i_lst.append(i)
        plt.plot(i_lst, cost_lst, color='green')
        camera.snap()
        md = -(2 / n) * sum(x * (y - y_pred))
        bd = -(2 / n) * sum((y - y_pred))
        m_curr = m_curr - learning_rate * md
        b_curr = b_curr - learning_rate * bd

        print("m {} b {} cost {} i {}".format(m_curr, b_curr, cost, i))
    animate = camera.animate()
    plt.show()
Exemplo n.º 17
0
    def animate_training(self, x_train, y_train, x_test, y_test):
        """
        This method plots each iteration of the training process
        """
        # just shuffling so that the training is not the same every time you run it
        data = np.c_[x_train, y_train]
        df = pd.DataFrame(data)
        df_shuffled = df.sample(frac=1)
        shuffled_x_train = df_shuffled[[0, 1]].values
        shuffled_y_train = df_shuffled[[2]].values.ravel()

        # setting up celluloid
        fig, ax = plt.subplots(figsize=(16, 9))
        cam = Camera(fig)

        # tqdm makes a progressbar
        for i in tqdm(range(len(x_train))):
            try:
                self.fit(shuffled_x_train[:i + 1], shuffled_y_train[:i + 1])
                if i % 2 == 0 or i == len(x_train) - 1:
                    self.plot_decision_boundary(shuffled_x_train[:i + 1],
                                                shuffled_y_train[:i + 1], fig,
                                                ax, len(x_train), cam,
                                                shuffled_x_train,
                                                shuffled_y_train)
            except:
                pass
        return cam.animate()
Exemplo n.º 18
0
def plot_animation(log):
	f = plt.figure(figsize=(6,6))
	camera = Camera(f)
	lc = []
	lq = []
	x= []
	av_rw = []
	min_rw = []
	max_rw = []
	entropy = []
	for n,dict in enumerate(log):
		plt.subplot(2, 2, 1)
		plot_hist(dict['ah'], 'Buffer actions')
		plt.subplot(2, 2, 2)
		plot_hist(dict['rh'], 'Buffer rewards')
		plt.subplot(2, 2, 3)
		plot_hist(dict['trh'], 'Buffer state transitions')
		plt.subplot(2, 2, 4)
		plot_phase(dict['ph_path'], 'Phase portrait')
		
		camera.snap()
		
	animation = camera.animate()
	# plt.show()
	# animation.show()
	animation.save('animation_norm.mp4')
Exemplo n.º 19
0
def scenario_R0_moyenne(nb_simulations, taille, p_contamine, p_dissident,
                        d_contagion, p_contamination, amplitude, jours,
                        isolement, non_respect):
    R_moy = jours * [0]
    for _ in range(nb_simulations):
        simul = initialisation_simulation(taille, p_contamine, p_dissident,
                                          d_contagion, p_contamination)
        R0 = [simul.r0()]
        R_moy[0] += R0[0]
        for j in range(jours):
            iteration_simulation(simul, amplitude, d_contagion,
                                 p_contamination, isolement, non_respect)
            R0.append(simul.r0())
            R_moy[j] += R0[j]
    for j in range(jours):
        R_moy[j] = R_moy[j] / nb_simulations

    fig = plt.figure()
    camera = Camera(fig)
    Jours = [k for k in range(0, jours + 1)]
    for j in range(2, jours + 1):
        plt.plot(Jours[:j], R_moy[:j], label="Contaminés", color='gold')
        camera.snap()
    animation = camera.animate()
    plt.show()
Exemplo n.º 20
0
def main():
    raw_board = gen_board(int(argv[1]), int(argv[2]))
    timestamp = str(int(t()))

    for s, name in zip(search_algs, names):
        print(f'Usando algoritmo {name}...')
        board = deepcopy(raw_board)

        fig = figure()
        camera = Camera(fig)
        search_res = test_search(board, s.search, camera=camera)

        path = search_res['path']
        if path:
            for i, j in path[1:-1]:
                board[i][j] = 1

        # Show path for longer time
        for i in range(10):
            plot_board(board)
            camera.snap()

        animation = camera.animate()
        outname = f'{timestamp}_{name}_{argv[1]}x{argv[2]}.gif'
        animation.save('gifs/' + outname, writer='imagemagick')
        print(search_res)
Exemplo n.º 21
0
def animateAndSaveLogo(flow_analysis):
    """
    Draws, ainimates, and saves flow vectors

    :param flow_analysis: a FlowAnalysis object
    :return: None

    """

    drawn_frames = flow_analysis.draw_all_flow_frames_superimposed(
        scalebarFlag=True, scalebarLength=10, scale=10, line_thicknes=1)
    channel_name = flow_analysis.getChannelName()

    fig = plt.figure()
    camera = Camera(fig)
    plt.title("A logo made from " + channel_name)
    plt.style.use('seaborn-dark')
    plt.axis('off')

    for i in range(drawn_frames.shape[0]):
        plt.imshow(drawn_frames[i])
        camera.snap()

    animation = camera.animate()
    file_name = channel_name + ".mp4"
    saveme = savepath / file_name

    animation.save(str(saveme), writer='ffmpeg')
Exemplo n.º 22
0
    def plot_learning(self, X, y, filename, interval=100):
        self.w = np.zeros((X.shape[1] + 1, 1))
        X_ = np.hstack([np.ones((X.shape[0], 1)), X])

        fig = plt.figure(figsize=(9, 9))
        plt.axis('off')
        camera = Camera(fig)
        for epoch in range(self.iterations):
            y_pred = self._predict(X_)
            for i in range(X_.shape[0]):
                if y_pred[i] != y[i]:
                    update_sign = y[i] - y_pred[i]

                    self.w = self.w + self.alpha * (update_sign *
                                                    X_[i].reshape(-1, 1))

            visualize(X, y, self._predict(X_), self.w)
            camera.snap()

        animation = camera.animate(interval=interval, blit=True)
        animation.save(f'{filename}.gif',
                       dpi=100,
                       savefig_kwargs={
                           'frameon': False,
                           'pad_inches': 'tight'
                       })
Exemplo n.º 23
0
def update_graph(G, data):
    fig = plt.figure()
    camera = Camera(fig)
    layout = nx.spring_layout(G)
    colour_map = {}
    print(data)
    for n in data:
        colour_map[n] = []
        for i in data[n]:
            if data[n][i] > 0.8:
                colour_map[n].append('red')
            elif 0.6 < data[n][i] <= 0.8:
                colour_map[n].append('orange')
            elif 0.4 < data[n][i] <= 0.6:
                colour_map[n].append('yellow')
            elif 0.2 < data[n][i] <= 0.4:
                colour_map[n].append('green')
            else:
                colour_map[n].append('green')

        nx.draw(G, node_color=colour_map[n], pos=layout, node_size=30, width=0.25)
        plt.draw()
        camera.snap()

    new = camera.animate()
    new.save('animation_1.html')
    print('i made it')
Exemplo n.º 24
0
def render_polyline_animation(entry, constructed_order, output_dir):
    fig, ax = plt.subplots()
    camera = Camera(fig)
    meshname = entry['object_name']
    point_indices = get_points_in_order(constructed_order, limit=3)
    progressive = dict(object_name=entry['object_name'],
                       points=entry['points'][point_indices])
    draw_2d_polyline(progressive, ax)
    camera.snap()

    for cut_idx in range(4, len(constructed_order)):
        point_indices = get_points_in_order(constructed_order, limit=cut_idx)
        progressive = dict(
            object_name=f'{meshname} - After Modifier #{cut_idx - 3}',
            points=entry['points'][point_indices])
        draw_2d_polyline(progressive, ax)
        camera.snap()

    progressive = dict(object_name=f'{meshname} - Output',
                       points=entry['points'][point_indices])
    draw_2d_polyline(progressive, ax, with_vertices=False)
    camera.snap()
    animation = camera.animate()
    outdir = os.path.join(output_dir, 'animations')
    os.makedirs(outdir, exist_ok=True)
    outpath = os.path.join(outdir, f'{meshname}.gif')
    animation.save(outpath, writer='imagemagick')
Exemplo n.º 25
0
def animate(solver, data, outdir, i=None):
    """
    Make an animation to show how we did.
    """
    filename = "animation.gif" if i is None else ("animation_iter_%i.gif" % i)
    fig = plt.figure(figsize=(8, 4))
    ax_solver = fig.add_subplot(1, 2, 1)
    ax_data = fig.add_subplot(1, 2, 2)
    camera = Camera(fig)

    def _plot(ax, u, title=None, rot=False):
        if rot:
            # Unrotate
            u = u.T[::-1]
        ax.imshow(u, vmin=-10.0, vmax=10.0)
        ax.set_xticks(())
        ax.set_yticks(())
        if title is not None:
            ax.set_title(title)

    with torch.no_grad():
        for u_sol, u_data in zip(
                solver.to_data(data).detach().cpu().numpy(),
                data.wvf.detach().cpu().numpy()):
            _plot(ax_solver, u_sol, "Solver", rot=data.rot)
            _plot(ax_data, u_data, "Data", rot=data.rot)
            camera.snap()
    animation = camera.animate()
    print("Saving animation...")
    animation.save(os.path.join(outdir, filename))
    print("Done!")
    plt.close()
Exemplo n.º 26
0
def heatEQ(uo, uL, L, k, h, t, T0):
    L = L + 1
    r = k / h**2
    time = np.arange(0, t, k)
    x = np.arange(0, L, h)
    u = np.ones(len(x)) * T0
    u[0] = uo
    u[-1] = uL
    u_ = []
    u_.append(np.copy(u))
    c = np.copy(u)
    for j in range(len(time)):
        for i in range(len(u) - 2):
            c[i + 1] = (1 - 2 * r) * u[i + 1] + r * u[i] + r * u[i + 2]
        u_.append(np.copy(c))
        u = np.copy(c)
    fig = plt.figure()
    camera = Camera(fig)
    for i in range(len(u_)):
        plt.plot(u_[i], color="deeppink")
        camera.snap()
    animation = camera.animate()
    plt.xlabel("Position")
    plt.ylabel("Temperature")
    plt.show()
Exemplo n.º 27
0
def create_CT_gif(img_slices,
                  gif_file,
                  vmin=0,
                  vmax=80,
                  x_axis=None,
                  y_axis=None):
    fig, ax = plt.subplots(figsize=(10, 10))
    ax.set_aspect('equal')
    camera = Camera(fig)
    for ii in range(img_slices.shape[0]):
        if x_axis is not None and y_axis is not None:
            cax = ax.pcolormesh(x_axis,
                                y_axis,
                                np.flipud(img_slices[ii, :, :]),
                                vmin=vmin,
                                vmax=vmax,
                                cmap=plt.get_cmap("Greys").reversed())
        else:
            cax = ax.pcolormesh(np.flipud(img_slices[ii, :, :]),
                                vmin=vmin,
                                vmax=vmax,
                                cmap=plt.get_cmap("Greys").reversed())
        camera.snap()
    animation = camera.animate()
    animation.save(gif_file, writer='imagemagick')
Exemplo n.º 28
0
def heatEQ2D(uo, uL, L, h, k, T0, t):
    p = int(L / h)
    #L = L +1
    r = k / h**2
    time = np.arange(0, t, k)
    c = np.array([[T0] * p] * p)
    c[0, 0] = uo
    c[-1, -1] = uL

    u_ = []
    #print(c)
    for j in range(len(time)):
        for i in range(L - 2):
            for k in range(L - 2):
                c[i+1,k+1] = (((1-2*r)*c[k,i+1]) + (r*c[k,i]) + (r*c[k,i+2]))+\
                             (((1-2*r)*c[i+1,k]) + (r*c[i,k]) + (r*c[i+2,k]))
        u_.append(c)
        print(u_[0][1])

    #print(u_)
    fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
    x = c[0, :]
    y = c[:, 0]
    x, y = np.meshgrid(x, y)

    camera = Camera(fig)
    mycmap = plt.get_cmap('jet')
    for i in range(L):
        z = u_[i]
        ax.plot_surface(x, y, z, cmap=mycmap, linewidth=0, antialiased=False)
        camera.snap()
    anim = camera.animate(blit=False, interval=10)

    plt.show()
Exemplo n.º 29
0
def animate_target(Y, fit_values, title, filename, pad=2):
    length = Y.shape[0]
    fig = plt.figure()
    # load axis box
    ax = plt.axes()
    # set axis limit
    pad = 2
    ax.set_xlim(np.min(Y[::, 0]) - pad, np.max(Y[::, 0]) + pad)
    ax.set_ylim(np.min(Y[::, 1]) - pad, np.max(Y[::, 1]) + pad)
    camera = Camera(fig)
    for i in range(length):
        ax.plot(Y[0:(i + 1), 0],
                Y[0:(i + 1), 1],
                '-o',
                c='lightblue',
                alpha=0.5)
        ax.plot(fit_values[0:(i + 1), 0],
                fit_values[0:(i + 1), 1],
                c='green',
                alpha=0.75)
        ax.title.set_text(title)
        plt.pause(0.1)
        camera.snap()
    animation = camera.animate()
    animation.save(filename, writer='Pillow', fps=2)
Exemplo n.º 30
0
def visualize_skeleton_openpose_18(joints, filename="fig.png"):
    joints_edges = [[0, 1], [1, 2], [2, 3], [3, 4], [1, 5], [5, 6], [6, 7],
                    [1, 8], [8, 9], [9, 10], [1, 11], [11, 12], [12, 13],
                    [0, 14], [14, 16], [0, 15], [15, 17]]

    joints[joints[:, :, 2] < 0.1] = np.nan
    joints[np.isnan(joints[:, :, 2])] = np.nan

    # ani =   animation.FuncAnimation(fig, update_plot, frames=range(len(sequence)),
    #                               fargs=(sequence, scat))

    # plt.show()

    from celluloid import Camera

    fig = plt.figure()
    ax = fig.add_subplot(111)
    plt.gca().invert_yaxis()

    camera = Camera(fig)
    for frame in range(0, joints.shape[0]):

        scat = ax.scatter(joints[frame, :, 0], joints[frame, :, 1])
        for edge in joints_edges:
            ax.plot((joints[frame, edge[0], 0], joints[frame, edge[1], 0]),
                    (joints[frame, edge[0], 1], joints[frame, edge[1], 1]))

        camera.snap()

    animation = camera.animate(interval=30)
    plt.close()
    return animation