Beispiel #1
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))
Beispiel #2
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')
def time_evolution_changing_lambda(lams, x, h, tau, niter, L, a=5):
    interval = int(numpy.ceil(niter / len(lams)))

    print("Generating states ...")
    states = numpy.zeros((niter + 1, len(x)), dtype=complex)
    states[0] = phi(0, x - a)
    for n in range(niter):
        Vm = V1D(lams[n // interval], x)
        states[n][0] = 0
        states[n][-1] = 0
        states[n + 1] = implicit_scheme_step(states[n], tau, h, Vm)

    print("Animating TASK 2 ...")
    fig, ax = plt.subplots()
    fig.suptitle("Task 2: $N=0, a={0}, \\lambda \\in {1}$".format(a, lams))

    def animate(frame):
        print("Animating TASK 2\t{0} | {1}".format(niter, frame + 1))
        ax.clear()
        ax.set_title("$\\lambda={}$".format(lams[frame // interval]))
        ax.set_ylim(bottom=0, top=1.5)
        ax.plot(x, numpy.abs(states[frame])**2)

    animation = matplotlib.animation.FuncAnimation(fig,
                                                   animate,
                                                   frames=niter,
                                                   interval=5)
    animation.save("naloga2_L{0}_a{1}.mp4".format(L, a))
Beispiel #4
0
def anim_to_html(anim):
    if not hasattr(anim, '_encoded_video'):
        with NamedTemporaryFile(suffix='.mp4') as f:
            anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
            video = open(f.name, "rb").read()
        anim._encoded_video = video.encode("base64")
    
    return VIDEO_TAG.format(anim._encoded_video)
Beispiel #5
0
def anim_to_html(anim):
    if not hasattr(anim, '_encoded_video'):
        with NamedTemporaryFile(suffix='.mp4') as f:
            anim.save(f.name, fps=20, extra_args=['-vcodec', 'libx264'])
            video = open(f.name, "rb").read()
        anim._encoded_video = video.encode("base64")

    return VIDEO_TAG.format(anim._encoded_video)
Beispiel #6
0
 def _save(self, animation):
     print('Saving animation...this could take a while...')
     name = "{}masses_{}modes.mp4".format(
         self._beaded_string.number_of_beads,
         str(self._beaded_string.normal_modes))
     self._create_directory(ANIMATIONS_FOLDER)
     full_path = path.join(ANIMATIONS_FOLDER, name)
     animation.save(full_path,
                    savefig_kwargs={'facecolor': BACKGROUND_COLOR})
def main(param, name):

    from matplotlib import animation as anim
    import matplotlib.pyplot as plt
    import sys

    pc = Init(param)
    removed, infected, tree_dist, rand, beta_dist, l_time_dist, l_time, run_time, sea_ind = [
        pc.removed, pc.infected, pc.tree_dist, pc.rand, pc.beta_dist,
        pc.survival_times, pc.life_time, pc.run_time, pc.sea_ind
    ]
    cmap, norm, bounds = pc.Cmap()
    fig, ax = plt.subplots()
    im = ax.imshow(tree_dist + infected, clim=[0, 12], cmap=cmap)
    plt.colorbar(im, boundaries=bounds, norm=norm)
    ax.set_yticks([])
    ax.set_xticks([])
    ax.set_title('frame: 0')

    def animate(i, Infected, Tree_dist, Removed, Beta_dist, L_time_dist, Param,
                Rand, Plot_frame, Name, sea_ind):
        print(i)
        Infected_, Tree_dist_, Removed_ = pc.disease_algo(
            i, Infected, Tree_dist, Removed, Beta_dist, L_time_dist, Param,
            Rand)

        Infected[:], Tree_dist[:], Removed[:] = Infected_, Tree_dist_, Removed_
        plot_arr = Infected + Tree_dist + sea_ind + (Removed * 12)
        im.set_array(plot_arr)
        ax.set_title('frame: ' + str(i))
        # Uncomment for single frame plots
        #if i == 100 or i == 400:
        #Plot_frame(i, pc, Arr=plot_arr, Cmap=cmap, Norm=norm, Bounds=bounds, Name=Name, sea_ind=sea_ind, mode='anim')
        #if i == 1:
        #np.save('dat', plot_arr)
        #Plot_frame(i, pc, Arr=plot_arr, Cmap=cmap, Norm=norm, Bounds=bounds, Name=Name, sea_ind=sea_ind, mode='static')
        if len(np.where(Infected > 0)[0]) == 0:
            print('no infected left')
            sys.exit()
        else:
            return im,

    anim = anim.FuncAnimation(fig,
                              animate,
                              fargs=(infected, tree_dist, removed, beta_dist,
                                     l_time_dist, param, rand, pc.plot_frame,
                                     name, sea_ind),
                              frames=run_time,
                              interval=20,
                              blit=True)
    anim.save('simulations/' + name + '.mp4',
              fps=30,
              extra_args=['-vcodec', 'libx264'])
    return
Beispiel #8
0
def __animation_to_html(animation, fps):
    if not hasattr(animation, 'encoded_video'):
        with NamedTemporaryFile(suffix='.mp4') as f:
            animation.save(f.name,
                           fps=fps,
                           extra_args=[
                               '-vcodec', 'libx264', '-pix_fmt', 'yuv420p',
                               '-profile:v', 'baseline', '-level', '3.0'
                           ])
            video = open(f.name, "rb").read()
        animation.encoded_video = base64.b64encode(video).decode('ascii')

    return VIDEO_TAG.format(animation.encoded_video)
 def make_gif(self, data, nframes):
     fig = plt.figure()
     plt.xlim(-0.2, 0.2)
     plt.xticks(np.linspace(-0.2, 0.2, 10))
     hist = plt.hist(x=data[:, 0],
                     bins=20,
                     color='dodgerblue',
                     alpha=0.7,
                     rwidth=0.85)
     animation = FuncAnimation(fig,
                               HistGif.update_hist,
                               nframes,
                               fargs=(data, ))
     animation.save("test.gif", dpi=100, writer=self.writer)
Beispiel #10
0
def plot_spin_lattice(prob, spin_history, energy_history, interaction_shape, interaction_radius, system_size, path):
    fig = plt.figure()
    plt.title('N = {}, {}, radius = {}'.format(system_size, interaction_shape, interaction_radius))
    camera = Camera(fig)
    # plot 1 spin configuration per temperature
    for t in range(0, len(spin_history), 1000):
        x_up, y_up, x_down, y_down = get_spin_lattice(spin_history[t], prob)
        plt.scatter(x_up, y_up, s=20**2, c='red')
        plt.scatter(x_down, y_down, s=20**2, c='blue')
        plt.text(0.05, 0.95, 'E = {}'.format(round(energy_history[t], 1)), transform=fig.transFigure, verticalalignment='top')
        plt.gca().set_aspect('equal', adjustable='box')
        camera.snap()
    animation = camera.animate()
    animation.save('{}/spin_lattice_radius_{}.gif'.format(path, interaction_radius), writer = 'imagemagick')
    plt.close()
Beispiel #11
0
def main():
    robot = Robot()
    robot.velocity_command = 0.5
    robot.velocity = 0.0
    time = 0

    fig, ax = plt.subplots()
    ax.set_ylim(-.5, 2.5)
    ax.set_xlim(-1, 1)
    com, = plt.plot([0],[2.0], 'bo', label="CoM")
    leg1, = plt.plot([], [], 'ro', label="foot1")
    leg2, = plt.plot([], [], 'go', label="foot2")
    text = plt.text(-0.9, 1.0, '')
    plt.legend()

    def update(frame):
        if robot.time > 1.0:
            robot.velocity_command = -1.0
        robot.advance(0.02)

        def height(leg):
            if leg.state == LiftState.STANCE:
                return 0.0
            return 0.5
        leg1.set_data([robot.legs[0].pos], [height(robot.legs[0])])
        leg2.set_data([robot.legs[1].pos], [height(robot.legs[1])])

        text.set_text(
            ("velocity={:.2f}\nswing_time:{:.2f}\n" +
             "left time:{:.2f}\nright time:{:.2f}").format(
                 robot.velocity,
                 SWING_PERIOD_S,
                 robot.left_time,
                 robot.right_time,
                ))

        print(f"{robot.time:6.3f} {robot}")

        return [com, leg1, leg2, text]

    animation = FuncAnimation(fig, update, blit=True, interval=30,
                              frames=np.arange(0, 160))
    if len(sys.argv) > 1:
        animation.save(sys.argv[1],
                       writer=matplotlib.animation.ImageMagickWriter(fps=20))
    else:
        plt.show()
Beispiel #12
0
def ANIM(t_S,gros_vecteur,nom_fichier):
    fig = plt.figure(0)
    camera = Camera(fig)
    for i in range(round(len(t_S)/10)):
        with plt.xkcd():
            titles = 'time = '+str(np.round(t_S[i*10+9],2))+' s'
            plt.imshow(np.flip(np.transpose(gros_vecteur[:,:,i*10+9]),0),extent=[0,1,0,1],cmap='coolwarm')
         #   plt.plot(0.71,.08,'rx')
          #  plt.plot(0.25,0.75,'o',color='purple')
          #  plt.plot(0.5,0.5,'o',color='blue')
            plt.plot(0.5,0.5,'go')
            plt.text(0.3,1.05,titles)
            camera.snap()
        print(i)
        
    animation = camera.animate(interval = 150)
    animation.save('freefall.gif')
Beispiel #13
0
def animation_to_html(animation):
    """Embeds animation in html."""
    video_tag = """<video controls>
     <source src="data:video/x-m4v;base64,{0}" type="video/mp4">
     Your browser does not support the video tag.
    </video>"""

    if not hasattr(animation, '_encoded_video'):
        with NamedTemporaryFile(suffix='.mp4') as f:
            animation.save(
                f.name,
                fps=20,
                extra_args=['-vcodec', 'libx264', '-pix_fmt', 'yuv420p'])
            video = open(f.name, "rb").read()
        animation._encoded_video = video.encode("base64")

    return video_tag.format(animation._encoded_video)
def animate(x, states, filename, lam, h, interval_base=10):
    print("Rendering animation ...")
    fig, ax = plt.subplots()
    plt.suptitle("($\\lambda = {0}$)".format(lam))
    plt.xlabel(r"$x$")
    plt.ylabel(r"$|\psi|^2$")

    def animate_func(frame):
        print("{0} | {1}".format(len(states), frame))
        ax.clear()
        ax.set_ylim(bottom=0, top=1)
        ax.plot(x, numpy.abs(states[frame])**2 / (h**2))

    animation = matplotlib.animation.FuncAnimation(fig,
                                                   animate_func,
                                                   frames=len(states),
                                                   interval=interval_base)
    animation.save(filename + ".mp4")
Beispiel #15
0
def generate_hawkes(given_range,cell_division,max_intensity,T,num_frames,show_plot=True):
	
	sthp = Spatio_temp_hawkes(given_range,cell_division,max_intensity,T)
	sthp.simulate()
	data=np.array(sthp.data)

	if show_plot:

		dic_list=[{'x_axis':[],'y_axis':[]} for frame in range(num_frames)]

		for point in data:
			frame_diff =int(T/num_frames)
			ind = int(point[0]/frame_diff)
			#print ind
			dic_list[ind]['x_axis'].append(point[1])
			dic_list[ind]['y_axis'].append(point[2])

		frame_list = [DataFrame(dic) for dic in dic_list]

		# First set up the figure, the axis, and the plot element we want to animate
		fig = plt.figure()
		plt.grid(True)
		ax = plt.axes(xlim=(0, 100), ylim=(0, 100))
		line, = ax.plot([], [], 'bo', ms=6)	


		# initialization function: plot the background of each frame
		def init():
		    line.set_data([], [])
		    return line,

		# animation function of dataframes' list
		def animate(i):
		    line.set_data(frame_list[i]['x_axis'], frame_list[i]['y_axis'])
		    return line,

		# call the animator, animate every 300 ms
		# set number of frames to the length of your list of dataframes
		anim = animation.FuncAnimation(fig, animate, frames=num_frames, init_func=init, interval=300, blit=True)
		anim.save('../Self_Exciting_Process/space_time_Hawkes/Plots/space_time_Hawkes_simulation.mp4', fps=10, extra_args=['-vcodec', 'libx264'])

		plt.show()

	return data,sthp
def animate(x,
            states,
            filename,
            lam,
            h,
            tau,
            N,
            interval_base=200,
            interval_slow=500,
            range_slow=None,
            frames_slow=20):
    print("Rendering animation ...")
    fig, ax = plt.subplots()
    plt.suptitle(
        "Time evolution of anharmonic oscilator wave function\n($\\lambda = {0}, h = {1}, \\tau = {2}, N = {3}$)"
        .format(lam, h, tau, N))
    plt.xlabel(r"$x$")
    plt.ylabel(r"$|\psi|^2$")

    def animate_func(frame):
        ax.clear()
        ax.plot(x, numpy.abs(states[frame])**2)

    def animate_func2(frame):
        ax.clear()
        ax.plot(x, numpy.abs(states[frame + range_slow])**2)

    os.chdir("hw1_schroedinger-equation-spectrum-and-time-evolution/images/")

    animation = matplotlib.animation.FuncAnimation(fig,
                                                   animate_func,
                                                   frames=len(states),
                                                   interval=interval_base)
    animation.save(filename + ".html")

    if range_slow is not None:
        animation = matplotlib.animation.FuncAnimation(fig,
                                                       animate_func2,
                                                       frames=frames_slow,
                                                       interval=interval_slow)
        animation.save(filename + "_slow.html")
Beispiel #17
0
def collatz_paths_gif(n,to_save="",filename='Collatz_Paths.gif'):
	A = collatz_back(n)
	A = collatz_sort_2(A)
	A = collatz_sort_rev(A)
	S = collatz_pathsnumber(A)
	col = int(10/len(A))/10
	fig = plt.figure("Collatz-Paths")
	cam = Camera(fig)
	for i in range(len(A[0])):
		for j in range(len(A)):
			plt.plot(range(1,i+2),A[j][:i+1],color=(j*col,j*col,j*col),marker='.',markersize=10)
		plt.xticks(range(0,n+1,1))
		plt.text(1,int(max(map(max,A))/3),'Number of Collatz-Paths: '+str(S[i]),fontsize=12)
		plt.xlabel('Lenght of Collatz-Path')
		plt.ylabel('Initial Value')
		plt.title('Collatz-Paths',fontsize=16)
		plt.grid(True)
		cam.snap()
	animation = cam.animate(interval=1500)
	if to_save == "save":
		animation.save(filename, writer = 'imagemagick')
	plt.show()
def task2_extra3a():
    N = 0
    lam = 0
    L = 10
    h = 0.01
    tau = 0.001
    a = 3
    x = numpy.linspace(-L, L, int(2 * L / h) + 1)
    Vm = V1D(lam, x)
    niter = 20000

    states = numpy.zeros((niter + 1, len(x)), dtype=complex)
    states[0] = phi(0, x - a)
    initial = numpy.abs(states[0])**2
    for n in range(niter):
        states[n][0] = 0
        states[n][-1] = 0
        states[n + 1] = implicit_scheme_step(states[n], tau, h, Vm)

    print("Animating TASK 2 ...")
    fig, ax = plt.subplots()
    fig.suptitle("Time evolution ($a = 3$)")

    def animate(frame):
        print("Animating TASK 2\t{0} | {1}".format(niter, frame + 1))
        diff = (numpy.abs(states[frame])**2 - initial)
        dist = numpy.sqrt(diff.dot(diff))
        ax.clear()
        ax.set_title("$d(\\psi(0), \\psi({0})) = {1}$".format(
            frame, numpy.round(dist, decimals=5)))
        ax.set_ylim(bottom=0, top=1)
        ax.plot(x, initial, "k-", linewidth=1)
        ax.plot(x, numpy.abs(states[frame])**2)

    animation = matplotlib.animation.FuncAnimation(fig,
                                                   animate,
                                                   frames=niter,
                                                   interval=2)
    animation.save("naloga2_L{0}_a{1}.mp4".format(L, a))
    def bake(self, options):
        figure = pyplot.figure(figsize=(16, 9))
        pyplot.axis([-16 / 9, 16 / 9, -1, 1])
        pyplot.axis('off')
        axes = figure.axes[0]
        figure.subplots_adjust(left=0,
                               bottom=0,
                               right=1,
                               top=1,
                               wspace=None,
                               hspace=None)

        writer = matplotlib.animation.writers['ffmpeg'](
            fps=options.frame_rate,
            codec=options.codec,
            bitrate=options.bitrate,
            extra_args=options.extra_args)

        directory = "output"
        if not os.path.exists(directory):
            os.makedirs(directory)

        for i, scene in enumerate(self.scenes):
            print("== Scene ", str(i), " ==")

            for artist in scene.artists:
                axes.add_artist(artist)

            animation = scene.play(figure, options)

            animation.save(directory + "/scene" + str(i) + ".mp4",
                           writer=writer,
                           dpi=options.dpi)

            for artist in scene.artists:
                artist.remove()
Beispiel #20
0
    counts = 0
    for i in range(no_trials):
        x = random.uniform(0,1)
        if x < prob_photon:
            counts += 1
    return counts

prob_photon = 3.0e-3 #probability of receiving a photon in interval (p --> 0)
no_trials = 1000 #number of trials per second (n --> inf)
repeats = 1000

results = [] #counts from each interval
results_sequence = [] #the list of results (for the animation)
random.seed()

for i in range(repeats):
    results.append(counts(prob_photon, no_trials))
    results_sequence.append(copy.copy(results))

def update_hist(frame_no, results_sequence):
    plt.cla()
    plt.hist(results_sequence[frame_no])
    plt.xlim([0,8])

fig = plt.figure()
plt.xlim([0,8])
plt.hist(results_sequence[0], align = 'mid', bins = [0, 1, 2, 3, 4, 5, 6, 7, 8])

animation = animation.FuncAnimation(fig, update_hist, repeats, fargs=(results_sequence,), repeat = False)
animation.save('poisson_hist2.mp4', writer = 'ffmpeg',  fps = 5)
Beispiel #21
0
def main(args):
    """Command-line driver to visualize survey scheduling and progress.
    """
    # Set up the logger
    if args.debug:
        log = desiutil.log.get_logger(desiutil.log.DEBUG)
        args.verbose = True
    elif args.verbose:
        log = desiutil.log.get_logger(desiutil.log.INFO)
    else:
        log = desiutil.log.get_logger(desiutil.log.WARNING)

    # Freeze IERS table for consistent results.
    desisurvey.utils.freeze_iers()

    # Set the output path if requested.
    config = desisurvey.config.Configuration()
    if args.output_path is not None:
        config.set_output_path(args.output_path)
    if args.tiles_file is not None:
        config.tiles_file.set_value(args.tiles_file)

    # Look for the exposures file in the output path by default.
    args.exposures = config.get_path(args.exposures)

    # Initialize.
    animator = Animator(args.exposures, args.start, args.stop, args.label,
                        args.scores)
    log.info('Found {0} exposures from {1} to {2} ({3} nights).'.format(
        animator.num_exp, args.start, args.stop, animator.num_nights))
    animator.init_figure(args.nightly)

    if args.expid is not None:
        expid = animator.exposures['EXPID']
        assert np.all(expid == expid[0] + np.arange(len(expid)))
        if (args.expid < expid[0]) or (args.expid > expid[-1]):
            raise RuntimeError(
                'Requested exposure ID {0} not available.'.format(args.expid))
        animator.draw_exposure(args.expid - expid[0], args.nightly)
        save_name = args.save + '.png'
        plt.savefig(save_name)
        log.info('Saved {0}.'.format(save_name))
    else:
        nframes = animator.num_nights if args.nightly else animator.num_exp
        iexp = [0]

        def init():
            return animator.artists

        def update(iframe):
            if (iframe + 1) % args.log_interval == 0:
                log.info('Drawing frame {0}/{1}.'.format(iframe + 1, nframes))
            if args.nightly:
                while not animator.draw_exposure(iexp[0], nightly=True):
                    iexp[0] += 1
            else:
                animator.draw_exposure(iexp=iframe, nightly=False)
            return animator.artists

        log.info('Movie will be {:.1f} mins long at {:.1f} frames/sec.'.format(
            nframes / (60 * args.fps), args.fps))
        animation = matplotlib.animation.FuncAnimation(animator.figure,
                                                       update,
                                                       init_func=init,
                                                       blit=True,
                                                       frames=nframes)
        writer = matplotlib.animation.writers['ffmpeg'](
            bitrate=2400, fps=args.fps, metadata=dict(artist='surveymovie'))
        save_name = args.save + '.mp4'
        animation.save(save_name, writer=writer, dpi=animator.dpi)
        log.info('Saved {0}.'.format(save_name))
Beispiel #22
0
        dt = d[idx]["t"] - d[idx - 1]["t"]
        t = (t - d[idx - 1]["t"]) / dt
        pos = (posNext - posLast) * t + posLast
        return pos


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("map", help="input file containing map")
    parser.add_argument("schedule", help="schedule for agents")
    parser.add_argument(
        '--video',
        dest='video',
        default=None,
        help="output video file (or leave empty to show on screen)")
    parser.add_argument("--speed", type=int, default=1, help="speedup-factor")
    args = parser.parse_args()

    with open(args.map) as map_file:
        map = yaml.load(map_file)

    with open(args.schedule) as states_file:
        schedule = yaml.load(states_file)

    animation = Animation(map, schedule)

    if args.video:
        animation.save(args.video, args.speed)
    else:
        animation.show()
Beispiel #23
0
 def save_animated_graph(animation, writer, name):
     print("\nCurrently saving:", name)
     animation.save(name, writer=writer)
Beispiel #24
0
	if s1 < s2: 
		b1.health -= diff
		b2.strength += boost

	if b1.health < 0:
		bots.remove(b1)
		bots.append(new_bot())

	if b2.health < 0:
		bots.remove(b2)
		bots.append(new_bot())


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

number_of_frames = 200

def update_hist(num):
	for x in range(100):
		step_bots()
	plt.cla()
	plt.hist(np.array([b.aggro for b in bots]), range=(0, 1))

fig = plt.figure()
hist = plt.hist(np.array([b.aggro for b in bots]))

animation = animation.FuncAnimation(fig, update_hist, number_of_frames )
animation.save("state_of_nature.mp4")
    dose_imm.set_data(dataDoseMatrix)
    dose_imm.autoscale()
    # dose via bw
    #dataBixelweights = np.genfromtxt(pathOutputDir + relevantFilesBW[i], delimiter=',')
    #dose_bw = np.dot(np.matrix.transpose(dataDij),np.matrix.transpose(dataBixelweights))
    #dose_bw = np.reshape(dose_bw, np.shape(dataCT)[::-1])
    #dose_bw = np.transpose(dose_bw)
    #dose_imb.set_array(dose_bw)
    #dose_imb.autoscale()


Writer = anim.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)

anim = anim.FuncAnimation(fig,
                          animate,
                          frames=len(relevantFilesDose),
                          interval=50,
                          repeat=False)
anim.save('tmp.mp4', writer=writer)

#dataMinDoseMatrix = np.transpose(np.reshape(dataMinDoseMatrix, np.shape(dataCT)[::-1]))
#dataVOIMatrix = np.transpose(np.reshape(dataVOIMatrix, np.shape(dataCT)[::-1]))

#plt.imshow(dataMinDoseMatrix, cmap='jet', interpolation='none', alpha=0.6)
#plt.imshow(dataVOIMatrix, cmap='jet', interpolation='none', alpha=0.4)

#plt.contourf(maskedDose, cmap='jet', interpolation='none', alpha=0.4)

plt.show()
Beispiel #26
0
def main(args):
    """Command-line driver to visualize survey scheduling and progress.
    """
    # Set up the logger
    if args.debug:
        log = desiutil.log.get_logger(desiutil.log.DEBUG)
        args.verbose = True
    elif args.verbose:
        log = desiutil.log.get_logger(desiutil.log.INFO)
    else:
        log = desiutil.log.get_logger(desiutil.log.WARNING)

    # Freeze IERS table for consistent results.
    desisurvey.utils.freeze_iers()

    # Set the output path if requested.
    config = desisurvey.config.Configuration()
    if args.output_path is not None:
        config.set_output_path(args.output_path)
    if args.tiles_file is not None:
        config.tiles_file.set_value(args.tiles_file)

    # Look for the exposures file in the output path by default.
    args.exposures = config.get_path(args.exposures)

    # Initialize.
    animator = Animator(
        args.exposures, args.start, args.stop, args.label, args.scores)
    log.info('Found {0} exposures from {1} to {2} ({3} nights).'
             .format(animator.num_exp, args.start, args.stop,
                     animator.num_nights))
    animator.init_figure(args.nightly)

    if args.expid is not None:
        expid = animator.exposures['EXPID']
        assert np.all(expid == expid[0] + np.arange(len(expid)))
        if (args.expid < expid[0]) or (args.expid > expid[-1]):
            raise RuntimeError('Requested exposure ID {0} not available.'
                               .format(args.expid))
        animator.draw_exposure(args.expid - expid[0], args.nightly)
        save_name = args.save + '.png'
        plt.savefig(save_name)
        log.info('Saved {0}.'.format(save_name))
    else:
        nframes = animator.num_nights if args.nightly else animator.num_exp
        iexp = [0]
        def init():
            return animator.artists
        def update(iframe):
            if (iframe + 1) % args.log_interval == 0:
                log.info('Drawing frame {0}/{1}.'
                         .format(iframe + 1, nframes))
            if args.nightly:
                while not animator.draw_exposure(iexp[0], nightly=True):
                    iexp[0] += 1
            else:
                animator.draw_exposure(iexp=iframe, nightly=False)
            return animator.artists
        log.info('Movie will be {:.1f} mins long at {:.1f} frames/sec.'
                 .format(nframes / (60 * args.fps), args.fps))
        animation = matplotlib.animation.FuncAnimation(
            animator.figure, update, init_func=init, blit=True, frames=nframes)
        writer = matplotlib.animation.writers['ffmpeg'](
            bitrate=2400, fps=args.fps, metadata=dict(artist='surveymovie'))
        save_name = args.save + '.mp4'
        animation.save(save_name, writer=writer, dpi=animator.dpi)
        log.info('Saved {0}.'.format(save_name))
Beispiel #27
0
circle = drawLoop(p1, 2, 1, animRes)  # 2e^(2*pi*i*t)
Rd = drawLoop(p1, 2, 4, animRes)  # 2^d*e^(8*pi*i*t)

lSpace = straightLineHomotopy(pZ, Rd)
# lSpace = straightLineHomotopy(circle,Rd)

#print(lSpace)

#######################
# Visualizing results #
#######################
fig, ax = plt.subplots()
d1, = plt.plot([x.real for x in lSpace[0]], [x.imag for x in lSpace[0]],
               color='blue')
d2, = plt.plot([x.real for x in lSpace[animRes - 1]],
               [x.imag for x in lSpace[animRes - 1]],
               color='red')


# Animate
def animateH(i):
    d1.set_data([x.real for x in lSpace[i]], [x.imag for x in lSpace[i]])

anim = anim.FuncAnimation(fig, animateH, frames=list(range(0,animRes)), \
                                      interval=100, blit=False, repeat=True)

ax.set(xlabel='Re(z)', ylabel='Im(z)')
ax.set(title='Map from p(z) to a circle with d=3')
plt.draw()
anim.save('slh_6.mp4', fps=60, extra_args=['-vcodec', 'libx264'])
Beispiel #28
0
def animate3d(i):
    x = statet[:, 0]
    y = statet[:, 1]
    z = statet[:, 2]
    line3d.set_data(x[:i], y[:i], z[:i])
    return line3d,


ani = ani.FuncAnimation(fig,
                        animate,
                        len(statet[:, 0]),
                        interval=5,
                        blit=False)
#ani3d  = ani.FuncAnimation(fig, animate3d, len(statet[:,0]), interval = 5, blit=False)
#plt.plot(statet[:,0],statet[:,1])
ani.save('2dlorrenz.gif', writer='ffmpeg')
plt.show()
"""
ax = fig.gca(projection="3d")
ax.plot(statet[:, 0], statet[:, 1], statet[:, 2])
plt.draw()
plt.show()

#for updating frames
def update(i,factor):
    line.set_xdata(state[:,0])
    line.set_ydata(state[:,1])
    line.set_zdata(state[:,2])
 
    return line
"""
Beispiel #29
0
from matplotlib import pyplot as plt
from matplotlib import animation

fig, ax = plt.subplots()

x = np.arange(0, 2 * np.pi, 0.01)
line0 = ax.plot(x, np.cos(x))
line, = ax.plot(x, np.sin(x))


def init():
    line.set_ydata(np.sin(x))
    return line,


def animate(i):
    line.set_ydata(np.sin(x + i / 10.0))
    return line,


animation = animation.FuncAnimation(fig=fig,
                                    func=animate,
                                    frames=100,
                                    init_func=init,
                                    interval=20,
                                    blit=False)

animation.save('resetvalue.gif', writer='imagemagick')

plt.show()
Beispiel #30
0
plt.xlim(-world['x'] * 0.55, world['x'] * 0.55)
plt.ylim(-world['y'] * 0.55, world['y'] * 0.55)

plt.savefig('exports/test.png')


def update(frame_number):
    preysScatGraph.set_offsets(np.c_[preysData[frame_number]["x"],
                                     preysData[frame_number]["y"]])
    predatorsScatGraph.set_offsets(np.c_[predatorsData[frame_number]["x"],
                                         predatorsData[frame_number]["y"]])
    foodScatGraph.set_offsets(np.c_[foodData[frame_number]["x"],
                                    foodData[frame_number]["y"]])


animation = animation.FuncAnimation(fig,
                                    update,
                                    interval=40,
                                    frames=totalFrames)
# plt.show()
animation.save('exports/im.mp4', writer=writer)

title = 'worldSim'
message = 'Video is ready'

# notification.notify(title=title,
#                   message=message,
#                   app_icon=None,
#                   timeout=10,
#                   toast=False)
Beispiel #31
0
             1.75,
             "t={:2.3f}".format(t_eval[0]),
             fontsize=10,
             ha="center")
ax.text(0,
        1.85,
        "Solved by Pesudospectral with RK44".format(t_eval[0]),
        fontsize=10,
        ha="center")


def init():
    ax.set_xlim(*x_span)
    ax.set_ylim(-0.05, 2.)
    return ln,


def animate(i):
    ln.set_data(x_eval, w[i, :])
    tx.set_text("t={:2.3f}".format(t_eval[i]))
    return ln,


animation = animation.FuncAnimation(fig=fig,
                                    func=animate,
                                    frames=300,
                                    init_func=init,
                                    interval=20,
                                    blit=False)
animation.save('redraw.gif', writer='imagemagick')
Beispiel #32
0
# and outputs a long matrix that shows the continuous deformation
# of one loop into the other.

p = polynomial(lambda z: z**4 + z**2 - z + 2, r'$p(z) = z^4 + z^2 - z + 2$')

pZ = drawLoop(p, 2, 1, animRes)

# lSpace = straightLineHomotopy(circle,Rd)

#print(lSpace)

#######################
# Visualizing results #
#######################
fig, ax = plt.subplots()
plt.plot([x.real for x in pZ], [x.imag for x in pZ], color='blue')
d1, = plt.plot([pZ[0].real, 0], [pZ[0].imag, 0], marker='o', color='red')


# Animate
def animateH(i):
    d1.set_data([pZ[i].real, 0], [pZ[i].imag, 0])

anim = anim.FuncAnimation(fig, animateH, frames=list(range(0,animRes)), \
                                      interval=100, blit=False, repeat=True)

ax.set(xlabel='Re(z)', ylabel='Im(z)')
ax.set(title='w(p(z),0)')
plt.draw()
anim.save('wind1.mp4', fps=60, extra_args=['-vcodec', 'libx264'])
                if index == 1:
                    joint.goal_position = -angles[index] / np.pi * 180 - 90
                else:
                    joint.goal_position = -angles[index] / np.pi * 180
            else:
                joint.goal_position = angles[index] / np.pi * 180

        third_arm.r_m5.goal_position = 0

    if (animate):
        # Définition de la trajectoire
        arm_length = fk.get_robot_length(third_arm_parameters)
        t = np.arange(0, np.pi / 2, np.pi / 50)
        x = np.sin(t**2) * arm_length / 3
        y = np.sin(t) * arm_length / 3
        z = -np.sinh(t) * arm_length / 3

        x2 = np.sqrt(x)
        y2 = y**2
        z2 = z

        fig = matplotlib.pyplot.figure()

        # Génération de l'animation
        animation = plot_utils.animate_IK(third_arm_parameters, third_arm_starting_angles, x, y, z, fig, third_arm_bounds)

        # Sauvegarde de l'animation
        animation.save('output/test.mp4', writer=plot_utils.animation_writer)

        matplotlib.pyplot.show()
        return self.img, self.laser_filed_plot


fig = plt.gcf()
visualizer = VisualizeDynamicsPhaseSpace(fig, sys_params)
animation = matplotlib.animation.FuncAnimation(
    fig, visualizer, frames=np.arange(100), init_func=visualizer.empty_frame, repeat=True, blit=True
)

plt.show()

# Set up formatting for the movie files
writer = matplotlib.animation.writers['mencoder'](fps=5, metadata=dict(artist='Denys Bondar'))

# Save animation into the file
animation.save('strong_field_physics.mp4', writer=writer)

# extract the reference to quantum system
quant_sys = visualizer.quant_sys

#################################################################
#
# Plot the Ehrenfest theorems after the animation is over
#
#################################################################

# generate time step grid
dt = quant_sys.dt
times = dt * np.arange(len(quant_sys.X_average)) + dt

plt.subplot(131)
Beispiel #35
0
ax.add_geometries(counties.geometries(), cartopy.crs.PlateCarree(),
                  facecolor='#C2A385', edgecolor='grey', zorder=1)

# Interstates
interstate = cartopy.io.shapereader.Reader('data/interstates')
ax.add_geometries(interstate.geometries(), cartopy.crs.PlateCarree(),
                  facecolor='none', edgecolor='#B20000', zorder=1)

# Hydrography
#hydro = cartopy.io.shapereader.Reader('data/hydro')
#ax.add_geometries(hydro.geometries(), cartopy.crs.PlateCarree(),
#                 facecolor='none', edgecolor='#ADD6FF', zorder=1)

# Set limits in lat/lon space
# LonW, LonE, LatN, LatS
#ax.set_extent([-81.8, -80, 36, 34.5])

print("Building Figure...")
norm, cmap = ctables.registry.get_with_steps(colorTable, 5, 5)
plot = ax.pcolormesh(x, y, ref, cmap=cmap, norm=norm, zorder=2)
#ax.contourf(x, y, ref, cmap=cmap, norm=norm, zorder=2)
title_line1 = '%s %s - %i:%i' % (args.site,args.product,hour,minute)
plt.title(title_line1,color='k',fontsize=18,fontweight='bold',style='italic')

if args.animate == 'true':
	animation = animation.FuncAnimation(fig, update, interval=15, blit=False, frames=10)
	animation.save('nexpy.gif', writer='imagemagick', fps=15, dpi=40)

plt.show()

Beispiel #36
0
def save_animation(animation, filename):
    animation.save(filename)
x2=numpy.zeros(num)
x3=numpy.zeros(num)
x4=numpy.zeros(num)
vstack_tmp1=[]
vstack_tmp2=[]
vstack_tmp3=[]
vstack_tmp4=[]
for i in xrange(1,n+1):
        x1+=numpy.random.randn(num)
        x2+=numpy.random.gamma(1,1,num)
        x3+=numpy.random.uniform(0,1,num)
        x4+=numpy.random.beta(0.5,0.5,num)
        vstack_tmp1.append(x1/i)
        vstack_tmp2.append(x2/i)
        vstack_tmp3.append(x3/i)
        vstack_tmp4.append(x4/i)

data1=numpy.vstack(vstack_tmp1)
data2=numpy.vstack(vstack_tmp2)
data3=numpy.vstack(vstack_tmp3)
data4=numpy.vstack(vstack_tmp4)

fig = pyplot.figure(figsize=(9,8))

animation = animation.FuncAnimation(fig, update_hist, fargs=(data1, data2, data3, data4, num), frames=100, interval=100)
animation.save('day7_CentralLimit.mp4', fps=3)

clip = VideoFileClip("day7_CentralLimit.mp4")
clip.write_gif("day7_CentralLimit.gif")
#pyplot.show()