Example #1
0
def animate_emission(hmm, obs_map, M=8, height=12, width=12, delay=1):
    # Parameters.
    lim = 1200
    text_x_offset = 40
    text_y_offset = 80
    x_offset = 580
    y_offset = 520
    R = 420
    r = 100
    arrow_size = 20
    arrow_p1 = 0.03
    arrow_p2 = 0.02
    arrow_p3 = 0.06

    # Initialize.
    n_states = len(hmm.A)
    obs_map_r = obs_map_reverser(obs_map)
    wordclouds = states_to_wordclouds(hmm, obs_map, max_words=20, show=False)

    # Initialize plot.
    fig, ax = plt.subplots()
    fig.set_figheight(height)
    fig.set_figwidth(width)
    ax.grid('off')
    plt.axis('off')
    ax.set_xlim([0, lim])
    ax.set_ylim([0, lim])

    # Plot each wordcloud.
    for i, wordcloud in enumerate(wordclouds):
        x = x_offset + int(R * np.cos(np.pi * 2 * i / n_states))
        y = y_offset + int(R * np.sin(np.pi * 2 * i / n_states))
        ax.imshow(wordcloud.to_array(),
                  extent=(x - r, x + r, y - r, y + r),
                  aspect='auto',
                  zorder=-1)

    # Initialize text.
    text = ax.text(text_x_offset, lim - text_y_offset, '', fontsize=24)

    # Make the arrows.
    zorder_mult = n_states**2 * 100
    arrows = []
    for i in range(n_states):
        row = []
        for j in range(n_states):
            # Arrow coordinates.
            x_i = x_offset + R * np.cos(np.pi * 2 * i / n_states)
            y_i = y_offset + R * np.sin(np.pi * 2 * i / n_states)
            x_j = x_offset + R * np.cos(np.pi * 2 * j / n_states)
            y_j = y_offset + R * np.sin(np.pi * 2 * j / n_states)

            dx = x_j - x_i
            dy = y_j - y_i
            d = np.sqrt(dx**2 + dy**2)

            if i != j:
                arrow = ax.arrow(x_i + (r / d + arrow_p1) * dx + arrow_p2 * dy,
                                 y_i + (r / d + arrow_p1) * dy + arrow_p2 * dx,
                                 (1 - 2 * r / d - arrow_p3) * dx,
                                 (1 - 2 * r / d - arrow_p3) * dy,
                                 color=(1 - hmm.A[i][j], ) * 3,
                                 head_width=arrow_size,
                                 head_length=arrow_size,
                                 zorder=int(hmm.A[i][j] * zorder_mult))
            else:
                arrow = ax.arrow(x_i,
                                 y_i,
                                 0,
                                 0,
                                 color=(1 - hmm.A[i][j], ) * 3,
                                 head_width=arrow_size,
                                 head_length=arrow_size,
                                 zorder=int(hmm.A[i][j] * zorder_mult))

            row.append(arrow)
        arrows.append(row)

    emission, states = hmm.generate_emission(M)

    def animate(i):
        if i >= delay:
            i -= delay

            if i == 0:
                arrows[states[0]][states[0]].set_color('red')
            elif i == 1:
                arrows[states[0]][states[0]].set_color(
                    (1 - hmm.A[states[0]][states[0]], ) * 3)
                arrows[states[i - 1]][states[i]].set_color('red')
            else:
                arrows[states[i - 2]][states[i - 1]].set_color(
                    (1 - hmm.A[states[i - 2]][states[i - 1]], ) * 3)
                arrows[states[i - 1]][states[i]].set_color('red')

            # Set text.
            text.set_text(' '.join([obs_map_r[e]
                                    for e in emission][:i + 1]).capitalize())

            return arrows + [text]

    # Animate!
    print('\nAnimating...')
    anim = FuncAnimation(fig, animate, frames=M + delay, interval=1000)

    return anim
Example #2
0
    parser.add_argument(
        "--images",
        help="Background activation = 1, ant activation = 2 both = 3",
        action="store_true")
    args = parser.parse_args()
    if not os.path.exists(args.map):
        raise IOError("Map file not found")

    if args.solution and not os.path.exists(args.solution):
        raise IOError("Solution file not found")
    data = parse(args.map, args.solution)
    # Graph
    G = nx.Graph()
    G.add_edges_from(data['tunnels'])
    # Fruchterman-Reingold force-directed algorithm's to set rooms.
    pos = nx.spring_layout(G)
    # Ants speed
    speed_rate = 7
    # create an array of * on the ants object
    ants = make_ants(pos, speed_rate, data)
    # size of the graph
    fig = plt.figure(figsize=(15, 10))
    ant_img = read_png('./images/Fourmisse.png')
    ani = FuncAnimation(fig,
                        re_init,
                        frames=data['num_turns'] * speed_rate,
                        fargs=(G, pos, speed_rate, data, ants, args, ant_img),
                        interval=30,
                        repeat=True)
    plt.show()
Example #3
0
def init():
    line, = ax.plot(dist.pos[0], dist.pos[1])
    return line,


def animate(i):
    dist.update_pos()
    x = dist.pos[0]
    y = dist.pos[1]
    z = dist.pos[2]
    line.set_data(np.asarray([x]), np.asarray([y]))
    line.set_3d_properties(np.asarray([z]), 'z')
    return line,


ax.set_xlim3d([-5.0, 5.0])
ax.set_ylim3d([-5.0, 5.0])
ax.set_zlim3d([-5.0, 5.0])

ax.axis([-5, 5, -5, 5])
anim = FuncAnimation(fig,
                     animate,
                     init_func=init,
                     frames=200,
                     interval=1000,
                     blit=True)
FFMpegWriter = animation.writers['ffmpeg']
writer = animation.FFMpegWriter()

anim.save('polya.mp4', writer=writer)
Example #4
0
    line.set_data([], [])
    return line, text

def animate(i):
    text.set_text("T= " + f'{i:g}' + " K")
    y = Spectral_Radiance(i)
    line.set_data(x, y)
    return line, text




#create animation
anim = FuncAnimation(fig,
                     animate,
                     init_func=anim_init,
                     frames=temperature_range,
                     interval=85,
                     blit=True)

ax.plot(x, Spectral_Radiance(wb/x), linestyle="dashed") #Wien curve



#format display
max_y = np.amax(Spectral_Radiance(max_temp))
text.set_x(max_x*0.75)
text.set_y(max_y*0.75)
ax.set_xlim(xmin=0, xmax=max_x)
ax.set_ylim(ymin=0, ymax=max_y*1.1)
ax.grid()
fig.tight_layout()
Example #5
0
    curva_param.append(ax[-1].plot(param_list[:, i], np.arange(len_params),
                                   'r.-'))
    ax[-1].set_xlabel('{:3.3f}'.format(param_list[-1, i]))
curva_datos = ax[0].plot(x_datos, y_datos, 'o', markersize=4, label='datos')
curva_modelo = ax[0].plot(x_datos, y_modelo, 'r-', label='modelo fiteado')

ax[0].set_xlabel("x")
ax[0].set_ylabel("y")
ax[0].legend(loc='best')


def actualizar(i):
    etiqueta = 'paso {:>2d}'.format(i)
    print(etiqueta)
    curva_modelo[0].set_ydata(modelo(param_list[i], x_datos))
    for j in range(num_params):
        curva_param[j][0].set_ydata(np.arange(0, 1 + i))
        curva_param[j][0].set_xdata(param_list[0:i + 1, j])
        ax[1 + j].set_xlabel('{:3.3f}'.format(param_list[i, j]))

    ax[0].set_title(etiqueta)
    return [curva_modelo[0]] + [y[0] for y in curva_param] + ax


anim = FuncAnimation(fig,
                     actualizar,
                     frames=np.arange(len_params),
                     interval=250)

# anim.save('ajuste-least_squares.gif', dpi=80, writer='imagemagick')
Example #6
0
    def _generate_and_save_gif(self,
                               top_images,
                               bottom_images,
                               size_fig,
                               is_mask=False):
        """
        Create figure with two images for sct_fmri_moco and sct_dmri_moco and save gif

        :param top_images: list of images of mosaic before motion correction
        :param bottom_images: list of images of mosaic after motion correction
        :param size_fig: size of figure in inches
        :param is_mask: display grid on top of mosaic
        :return:
        """

        if is_mask:
            aspect = self.aspect_mask
        else:
            aspect = self.aspect_img

        fig = Figure()
        FigureCanvas(fig)
        fig.set_size_inches(size_fig[0], size_fig[1], forward=True)
        fig.subplots_adjust(left=0, top=0.9, bottom=0.1)

        ax1 = fig.add_subplot(211)
        null_image = np.zeros(np.shape(top_images[0]))
        img1 = ax1.imshow(null_image, cmap='gray', aspect=float(aspect))
        ax1.set_title('Before motion correction',
                      fontsize=8,
                      loc='left',
                      pad=2)
        ax1.get_xaxis().set_visible(False)
        ax1.get_yaxis().set_visible(False)
        self._add_orientation_label(ax1)
        if is_mask:
            QcImage.grid(self, top_images[0], ax1)

        ax2 = fig.add_subplot(212)
        img2 = ax2.imshow(null_image, cmap='gray', aspect=float(aspect))
        ax2.set_title('After motion correction', fontsize=8, loc='left', pad=2)
        ax2.get_xaxis().set_visible(False)
        ax2.get_yaxis().set_visible(False)
        self._add_orientation_label(ax2)
        if is_mask:
            QcImage.grid(self, bottom_images[0], ax2)

        ann = ax2.annotate('',
                           xy=(0, .025),
                           xycoords='figure fraction',
                           horizontalalignment='left',
                           verticalalignment='bottom',
                           fontsize=6)

        def update_figure(i):
            img1.set_data(top_images[i])
            img1.set_clim(vmin=np.amin(top_images[i]),
                          vmax=np.amax(top_images[i]))
            img2.set_data(bottom_images[i])
            img2.set_clim(vmin=np.amin(bottom_images[i]),
                          vmax=np.amax(bottom_images[i]))
            ann.set_text(f'Volume: {i + 1}/{len(top_images)}')

        # FuncAnimation creates an animation by repeatedly calling the function update_figure for each frame
        ani = FuncAnimation(fig, update_figure, frames=len(top_images))

        if is_mask:
            gif_out_path = self.qc_report.qc_params.abs_overlay_img_path()
        else:
            gif_out_path = self.qc_report.qc_params.abs_bkg_img_path()

        if self._fps is None:
            self._fps = 3
        writer = PillowWriter(self._fps)
        logger.info('Saving gif %s', gif_out_path)
        ani.save(gif_out_path, writer=writer, dpi=self.qc_report.qc_params.dpi)
plt.scatter(data[apples][:, 0], data[apples][:, 1], color = "red", marker=".", label="Apples")
plt.scatter(data[pears][:, 0], data[pears][:, 1], color = "green", marker=".", label="Pears")
plt.xlabel("yellowness")
plt.ylabel("symmetry")
line, = plt.plot([], [], color="black", linewidth=2)  # создаём линию, которая будет показывать границу разделения

from matplotlib.animation import FuncAnimation

perceptron_for_weights_line = create_perceptron(2)  # создаём перцептрон нужной размерности со случайными весами

from functools import partial
weights_ani = partial(
    step_by_step_weights, p=perceptron_for_weights_line, input_matrix=data[:, :-1], y=data[:, -1][:,np.newaxis]
)  # про partial почитайте на https://docs.python.org/3/library/functools.html#functools.partial

ani = FuncAnimation(fig, func=plot_line, frames=weights_ani, blit=False, interval=10, repeat=True)
# если Jupyter не показывает вам анимацию - раскомментируйте строчку ниже и посмотрите видео
#ani.save("perceptron_seeking_for_solution.mp4", fps=15)
plt.show()

## Не забудьте остановить генерацию новых картинок, прежде чем идти дальше (кнопка "выключить" в правом верхнем углу графика)


# Он также подготовил несколько примеров, чтобы проиллюстрировать философию обучения перцептрона, которая не всегда интуитивна.
# 
# Во-первых, количество неправильно классифицированных примеров не всегда уменьшается. То есть в процессе обучения у перцептрона могут случаться "взлёты и падения" - делился мудростью Зюк.

# In[71]:


def step_by_step_errors(p, input_matrix, y, max_steps=1e6):
        delta_c = '{:.2e}'.format(np.max(SV_plt[-1,:]) - np.min(SV_plt[-1,:]))
   
        cax.cla()
        ticks = np.linspace(np.min(SV_plt), np.max(SV_plt),5)
        cbar = fig.colorbar(cf, cax=cax, ticks=ticks, format='%.7f')
        cbar.set_label(r'%s Density, $\rho$ [kg/m$^3$]' %plt_species)
        
        if t_movie[i] < 1.0:
            t_current = '{:.2e}'.format(t_movie[i])
        else:
            t_current = '{:.2f}'.format(t_movie[i])
        
        ax.set_title('Time: ' + t_current + ' s\n' 
                     r'$\Delta\rho_{max}$ outlet: ' + delta_c + r' kg/m$^3$')
        
        fig.tight_layout(pad=wht_space)
        
    anim = FuncAnimation(fig, animate, interval=500, frames=len(t_movie))
    
    anim.save('animation.html')
    
# Move back to original cwd after files are saved:
os.chdir(cwd)

""" Comments and future steps """
"-----------------------------------------------------------------------------"
# Add species complexity so that model can be extended to work for Fuel Cell
# processes.

# Determine appropriate discretization in x-y space for grid independence.
print (start_point)
# plotpoints = groud_truth.ix[0,1:4].values
ax.scatter(*start_point, s=100, c='black', marker='v', label='origin')
# scat = ax.scatter([],[],[],  c='r')
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')


# colors = itertools.cycle(['r', 'y', 'b'])
def update(frame_number, groud_truth):
	# global plotpoints, ax, scat
	# plotpoints = [groud_truth.ix[:frame_number, 1].values, groud_truth.ix[:frame_number, 2].values, groud_truth.ix[:frame_number, 3].values]  
	# # print (plotpoints)
	# # print ('-------------------- ')
	# scat = ax.scatter(*plotpoints,c='r')
	# return plotpoints, scat
	# print (groud_truth.ix[frame_number, 1], groud_truth.ix[frame_number, 2], groud_truth.ix[frame_number, 3])
	# print ('----------------------')
	# scat.__offsets3d = (groud_truth.ix[frame_number, 1], groud_truth.ix[frame_number, 2], groud_truth.ix[frame_number, 3])
	ax.scatter(groud_truth.ix[:frame_number, 1], groud_truth.ix[:frame_number, 2], groud_truth.ix[:frame_number, 3], c='r', s=1)
	


# The interval should be 50ms, because the camera is 20Hz.

if args.d == True:
	animation = FuncAnimation(fig, update, fargs=(groud_truth,), interval=1)
else:
	ax.scatter(groud_truth.ix[:, 1], groud_truth.ix[:, 2], groud_truth.ix[:, 3], c='red', alpha=0.1, s=1 )
plt.show()
Example #10
0
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = ax.plot([], [], 'r-', animated=False)


def init():
    ax.set_xlim(0, 100)
    ax.set_ylim(0, 200)
    return ln,


def update(frame):
    # y = 2 * frame
    xdata.append(frame)
    ydata.append(2 * frame)
    ln.set_data(xdata, ydata)
    return ln,


ani = FuncAnimation(fig,
                    update,
                    frames=np.linspace(0, 100, 128),
                    init_func=init,
                    blit=True)
plt.show()
Example #11
0
        imgplot = ax.imshow(imgB, animated=True)
        ax.axis('off')
        ## small delay for the visualiation of the beat itself
        ani.event_source.interval = 40
    elif ((frame % 4) == 3):  # the frame 4
        ## Heart beat (small amplitude to mimick two-phase beating)
        ax.clear()
        imgplot = ax.imshow(imgC, animated=True)
        ax.axis('off')
        ## small delay for the visualiation of the beat itself
        ani.event_source.interval = 40

    return imgplot, ln


### Animation
ani = FuncAnimation(fig,
                    update,
                    frames=dat.size * 4,
                    init_func=init,
                    blit=False,
                    repeat=False)

### Saving options (do not really work to keep the "real-time" of the animation
#ani.save(filename='anim.mp4')
# ani.save('anim.gif',writer='imagemagick')
# ani.to_html5_video()

### Show the animation
plt.show()
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation, FFMpegFileWriter

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'b', animated=True)
f = np.linspace(-3, 9, 400)


def init():
    ax.set_xlim(-3, 9)
    ax.set_ylim(-0.25, 2)
    ln.set_data(xdata, ydata)
    return ln,


def update(frame):
    xdata.append(frame)
    ydata.append(np.exp(-frame**2))
    ln.set_data(xdata, ydata)
    return ln,


ani = FuncAnimation(fig,
                    update,
                    frames=f,
                    init_func=init,
                    blit=True,
                    interval=2.5,
                    repeat=False)
plt.show()
Example #13
0
def simulate():
    # Set up parameters for the simulation
    xlim = 10  # The x-dimension goes from -xlim to xlim
    n = 500  # The x-dimension is discretized in n parts
    x = np.linspace(-xlim, xlim, n)  # The x-dimension
    dx = x[1] - x[0]  # The size of a step in the x-dimension
    dt = 0.05  # The timestep
    m = 1  # The mass
    hbar = 1  # The reduced Plank's constant
    t0 = 0  # The initial time value

    # The harmonic potential
    k = 0.5
    v = se_functions.harmonic_v(x, k)

    # # The barrier potential
    # potential = 0
    # barrier = 50
    # v = se_functions.square_v(x, barrier, 0.5, 0.01, potential)

    # # The well potential
    # potential = 0
    # barrier = -10
    # v = se_functions.square_v(x, barrier, 0.5, 0.01, potential)

    # The wave packet for the harmonic potential
    sigma = 0.5
    x0 = -7
    k0 = 0
    psi0 = se_functions.gauss_wave_init(x, sigma, x0, k0)

    # # The wave packet for barrier/well potentials
    # sigma = 1
    # x0 = -7
    # k0 = 7
    # psi0 = se_functions.gauss_wave_init(x, sigma, x0, k0)

    # The Schrödinger equation to be solved
    se = se_equations.SchrodingerEquation1D(x, v, dx, dt, psi0, m, hbar, t0)

    # The solver used for the simulation
    se_solver = se_solvers.SeSolver1DCN(se)

    # The harmonic potential to be plotted
    vplot = se.v / 30 - 0.7

    # # The barrier potential to be plotted
    # vplot = se.v / 50

    # # The well potential to be plotted
    # vplot = se.v / 10

    # Set up the plot
    rc('text', usetex=True)
    fig = plt.figure()
    ylim = np.max([np.max(se.prob()), np.max(np.abs(vplot))]) * 1.1
    ax = fig.add_subplot(111, xlim=(-xlim, xlim), ylim=(-ylim, ylim))

    potential_plot_data, = ax.plot(se.x, vplot, 'grey', label='$V(x)$')
    probability_plot_data, = plt.plot([], [],
                                      'xkcd:pastel orange',
                                      label=r'$\Psi^* \Psi $')
    psi_plot_data, = ax.plot([], [], 'xkcd:medium blue', label=r'$\Psi(x, t)$')

    plt.legend(
        handles=[potential_plot_data, probability_plot_data, psi_plot_data],
        loc=1,
        prop={'size': 20})

    ax.set_xlabel("$x$", fontsize=24)
    ax.set_ylabel(r"$\Psi$", fontsize=24)
    ax.set_xticklabels([])
    ax.set_yticklabels([])

    plt.tight_layout()
    plt.subplots_adjust(top=0.9)

    def init():
        psi_plot_data.set_data(se.x, se.psi)
        probability_plot_data.set_data(se.x, se.prob())
        return psi_plot_data, probability_plot_data

    def update(frame):
        se_solver.iterate()
        psi_plot_data.set_data(se.x, se.psi)
        probability_plot_data.set_data(se.x, se.prob())
        return psi_plot_data, probability_plot_data

    plt.show()
    return FuncAnimation(fig, update, init_func=init, interval=1, blit=False)
def contar_kmeans(img):
    data = np.reshape(img, (-1, 3))
    data = np.float32(data)
    criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
    flags = cv2.KMEANS_RANDOM_CENTERS
    compactness, labels, centers = cv2.kmeans(data, 1, None, criteria, 10,
                                              flags)
    return centers[0]


#Inicialização
captura = cv2.VideoCapture(0)
imagem = grab_frame(captura)

#Cria os dois subplots
ax1 = plt.subplot(1, 2, 1)
ax2 = plt.subplot(1, 2, 2)

#Cria duas imagens nos subplots
im1 = ax1.imshow(imagem)
im2 = ax2.imshow(retangulo(imagem))

#Animação e atualização
ani = FuncAnimation(plt.gcf(), atualizar, interval=200)

#Fechar
cid = plt.gcf().canvas.mpl_connect("key_press_event", close)
#Mostrar o gráfico
plt.show()
Example #15
0
    return points,


def animate(frame):
    step()
    points.set_data(x[:, 0], x[:, 1])
    if frame is frames - 1:
        plt.close()
    return points,


totalTime = 10
frames = int(totalTime / dt)
anim = FuncAnimation(fig,
                     animate,
                     frames=range(frames),
                     init_func=init,
                     interval=dt * 1000)
plt.show()
"""
mport matplotlib.pyplot as plt
import numpy as np
import random
from matplotlib.animation import FuncAnimation

n = 4      # Number of particles
m = np.ones(n)      # Particle masses
x = np.zeros((n,2))  # Particle positions (x and y for ith particle in x[i,0], x[i,1])
v = np.zeros((n,2))  # Particle velocities
f = np.zeros((n,2))  # Force accumulator
dt = 0.005           # Time step
Example #16
0
ax.set_ylim(0, 1)


# animation effect function
def update(frame):
    global pos, colors, csize

    # transparency
    colors[:, 3] = np.maximum(0, colors[:, 3] - 1.0 / n)

    # increase the size when apply animation
    csize += (size_max - size_min) / n

    # frame rate
    i = frame % 50
    pos[i] = np.random.uniform(0, 1, 2)
    csize[i] = size_min
    colors[i, 3] = 1

    # update scatter graph
    scat_graph.set_edgecolor(colors)
    scat_graph.set_sizes(csize)
    scat_graph.set_offsets(pos)
    return scat_graph


# creates animation effect (n frame per second)
animation = FuncAnimation(fig, update, interval=5)

plt.show()
def main(argv):
    parser = argparse.ArgumentParser(
        description="Plot the loss evolving through time")

    parser.add_argument("metrics",
                        type=file_or_stdin,
                        help="The file containing the loss")

    parser.add_argument("--to_file", help="Save the animation to a video file")
    parser.add_argument("--step",
                        type=int,
                        default=1000,
                        help="Change that many datapoints in between frames")
    parser.add_argument("--n_points",
                        type=int,
                        default=10000,
                        help="That many points in each frame")
    parser.add_argument("--frames",
                        type=lambda x: slice(*map(maybe_int, x.split(":"))),
                        default=":",
                        help="Choose only those frames")
    parser.add_argument("--lim",
                        type=lambda x: map(float, x.split(",")),
                        help="Define the limits of the axes")
    parser.add_argument("--no_colorbar",
                        action="store_false",
                        dest="colorbar",
                        help="Do not display a colorbar")

    args = parser.parse_args(argv)
    loss = np.loadtxt(args.metrics)

    fig, ax = plt.subplots()
    lr = LinearRegression()
    sc = ax.scatter(loss[:args.n_points, 0],
                    loss[:args.n_points, 1],
                    c=colors(loss[:args.n_points, 2]))
    lims = args.lim if args.lim else [0, loss[:, 0].max()]
    ln, = ax.plot(lims, lims, "--", color="black", label="linear fit")
    ax.set_xlim(lims)
    ax.set_ylim(lims)
    ax.set_xlabel("$L(\cdot)$")
    ax.set_ylabel("$\hat{L}(\cdot)$")
    if args.colorbar:
        mappable = ScalarMappable(cmap="viridis")
        mappable.set_array(loss[:10000, 2])
        plt.colorbar(mappable)

    STEP = args.step
    N_POINTS = args.n_points

    def update(i):
        s = i * STEP
        e = s + N_POINTS
        lr.fit(loss[s:e, :1], loss[s:e, 1].ravel())
        ln.set_ydata([
            lr.intercept_.ravel(),
            lr.intercept_.ravel() + lims[1] * lr.coef_.ravel()
        ])
        ax.set_title("Showing samples %d to %d" % (s, e))
        sc.set_facecolor(colors(loss[s:e, 2]))
        sc.set_offsets(loss[s:e, :2])
        return ax, sc, ln

    anim = FuncAnimation(fig,
                         update,
                         interval=100,
                         frames=np.arange(len(loss) / STEP)[args.frames],
                         blit=False,
                         repeat=False)
    if args.to_file:
        writer = animation_writers["ffmpeg"](fps=15)
        anim.save(args.to_file, writer=writer)
    else:
        plt.show()
    df_expanded = df_expanded.interpolate()
    df_rank_expanded = df_rank_expanded.interpolate()
    labels = df_expanded.columns
    return df_expanded, df_rank_expanded, labels


if __name__ == '__main__':
    # 处理mpl中文字体问题
    mpl.rcParams["font.sans-serif"] = ["SimHei"]
    mpl.rcParams["axes.unicode_minus"] = False
    # 连接hive读数据并数据预处理
    conn = hive.Connection(host='127.0.0.1', port=10000, auth='CUSTOM', username='******', password='******')
    df = pd.read_sql(
        sql="SELECT c_day,team_name,ten_days_buy_amt FROM data_market.ads_team_controlrates_monitor_so where c_day < '2020-08-24'",
        con=conn)
    data_res = df.set_index(['c_day', 'team_name']).unstack().fillna(0).head(11)
    # 去除一级行索引
    data_res1 = data_res.droplevel(level=0, axis=1)
    # 挑选几只战队和适当时间比较
    data_res1 = data_res1[['178战队', '698战队', 'Avenger战队', '众志战队', '传奇战队', '先锋战队', '光芒战队', '凌霄战队', '利刃战队', '北斗战队']]
    data_res2 = data_res1.loc['2020-08-13':'2020-08-23']
    # 平滑过渡
    df_expanded, df_rank_expanded, labels = prepare_data(data_res2)
    # 动画
    fig = plt.Figure(figsize=(6, 3.5), dpi=144)
    ax = fig.add_subplot()
    anim = FuncAnimation(fig=fig, func=update, frames=len(df_expanded),
                         interval=200, repeat=False)
    # 展示
    html = anim.to_html5_video()
    HTML(html)
Example #19
0
def make_gif(data_to_plot,
             frames=np.arange(10),
             interval=120,
             fig_sz=(8, 6),
             dpi=100,
             cmap='Greys',
             mode='stim',
             file_name=None,
             save_dir='./gifs/'):

    if not os.path.isdir(os.path.dirname(save_dir)):
        os.makedirs(os.path.dirname(save_dir))

    if file_name is None:
        file_name = mode + '.gif'

    if mode == 'stim':
        # start the fig
        fig, _ax = plt.subplots()
        fig.set_size_inches(fig_sz)
        # fig.set_tight_layout(True)

        # find absmax for vmin/vmax and plot the first frame
        _abs_max = np.max(abs(data_to_plot))
        _plt = _ax.imshow(data_to_plot[0, ...],
                          cmap=cmap,
                          vmin=-_abs_max,
                          vmax=_abs_max)
        fig.colorbar(_plt)

        # start anim object
        anim = FuncAnimation(fig,
                             _gif_update,
                             fargs=[_plt, _ax, data_to_plot, mode],
                             frames=frames,
                             interval=interval)
        anim.save(save_dir + file_name, dpi=dpi, writer='imagemagick')

    elif mode == 'subs':
        width_y, width_x, nlags, ker_n = data_to_plot.shape
        col_n = int(np.ceil(np.sqrt(ker_n)))
        row_n = int(np.ceil(ker_n / col_n))

        _plt_dict = {}

        fig, axes = plt.subplots(row_n, col_n)
        fig.set_size_inches((col_n * 2, row_n * 2))

        _abs_max = np.max(abs(data_to_plot))
        for ii in range(row_n):
            for jj in range(col_n):
                which_sub = ii * col_n + jj
                if which_sub >= ker_n:
                    continue

                axes[ii, jj].xaxis.set_ticks([])
                axes[ii, jj].yaxis.set_ticks([])
                tmp_plt = axes[ii, jj].imshow(data_to_plot[..., 0, which_sub],
                                              cmap='Greys',
                                              vmin=-_abs_max,
                                              vmax=_abs_max)
                _plt_dict.update({'ax_%s_%s' % (ii, jj): tmp_plt})

        # start anim object
        anim = FuncAnimation(fig,
                             _gif_update,
                             fargs=[fig, _plt_dict, data_to_plot, mode],
                             frames=np.arange(nlags),
                             interval=interval)
        anim.save(save_dir + file_name, dpi=dpi, writer='imagemagick')

    else:
        raise ValueError, 'Not implemented yet.'

    plt.close()
    print('...your GIF is done! "%s" was saved at %s.' % (file_name, save_dir))
Example #20
0
    if not q.empty():
        dataBlock = q.get_nowait()
        index = 0
        for data1 in dataBlock:
            ydata[frame * 100 + index] = data1
            index += 1

    ln.set_data(xdata, ydata)
    return ln,


try:
    stream = sd.Stream(samplerate=FS,
                       channels=1,
                       blocksize=100,
                       callback=callback)
    ani = FuncAnimation(fig,
                        update,
                        frames=40,
                        init_func=init,
                        interval=10,
                        blit=True)
    mp.myPlotterStreamShow(fig, stream)

    plt.show()
    stream.start()

except Exception as e:
    stream.stop()
    print("Error")
Example #21
0
import speedtest
import time
plt.style.use('fivethirtyeight')
plt.ylim((0,150))
st = speedtest.Speedtest()
timeList= []
speed = []
startTime = time.time()
index = count()


def animate(i):
    plt.cla()
    plt.ylim((0,150))
    dls = st.download() /1000 /1000
    curTime = time.time() - startTime
    timeList.append(curTime)
    speed.append(dls)
    print(dls )
    plt.plot(timeList,speed)

    plt.legend(loc='upper left')
    plt.xlabel("Time (sec)")
    plt.ylabel("MB/s")
    plt.tight_layout()


ani = FuncAnimation(plt.gcf(), animate, interval=10000)

plt.tight_layout()
plt.show()
Example #22
0
def animate_pendulum_X(p, t, skip=1, see_plot=0):
    #t = np.linspace(0, 10, 200)
    #p = integrate_pendulum(n, t)
    N_links = int(len(p[0])/4)
    x, y = get_xy_coords(p, N_links)
    fig, ax = plt.subplots(figsize=(6, 6))
    fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
    ax.axis('off')
    ax.set(xlim=(-1, 1), ylim=(-1, 1))
    x=x[::skip]
    y=y[::skip]
    
    origin = np.zeros((len(x),1))
    
    xlist=[]
    ylist=[]
    
    #draw lines from origin to first 2 nodes
    xs=np.hstack([origin,x[:,0:1]])
    xlist.append(xs)
    xs=np.hstack([origin,x[:,1:2]])
    xlist.append(xs)
    xs=np.hstack([x[:,0:1],x[:,1:2]])
    xlist.append(xs)
    
    ys=np.hstack([origin,y[:,0:1]])
    ylist.append(ys)
    ys=np.hstack([origin,y[:,1:2]])
    ylist.append(ys)
    ys=np.hstack([y[:,0:1],y[:,1:2]])
    ylist.append(ys)
    
    
    for i in range(N_links-1):
        xs=np.hstack([x[:,2*i+0:2*i+1],x[:,2*i+2:2*i+3]])
        xlist.append(xs)
        xs=np.hstack([x[:,2*i+2:2*i+3],x[:,2*i+3:2*i+4]])
        xlist.append(xs)
        xs=np.hstack([x[:,2*i+3:2*i+4],x[:,2*i+1:2*i+2]])
        xlist.append(xs)
        xs=np.hstack([x[:,2*i+0:2*i+1],x[:,2*i+3:2*i+4]])
        xlist.append(xs)
        xs=np.hstack([x[:,2*i+2:2*i+3],x[:,2*i+1:2*i+2]])
        xlist.append(xs)
        ys=np.hstack([y[:,2*i+0:2*i+1],y[:,2*i+2:2*i+3]])
        ylist.append(ys)
        ys=np.hstack([y[:,2*i+2:2*i+3],y[:,2*i+3:2*i+4]])
        ylist.append(ys)
        ys=np.hstack([y[:,2*i+3:2*i+4],y[:,2*i+1:2*i+2]])
        ylist.append(ys)        
        ys=np.hstack([y[:,2*i+0:2*i+1],y[:,2*i+3:2*i+4]])
        ylist.append(ys)
        ys=np.hstack([y[:,2*i+2:2*i+3],y[:,2*i+1:2*i+2]])
        ylist.append(ys)
        
    total = 5*(N_links-1)+3
    
    global xtemp
    xtemp = xlist
    global ytemp
    ytemp =ylist
    
    line, = ax.plot([], [], 'o-', lw=2)
    
    lines = []
    for index in range(total):
        if index <3:
            colors = "black"
        else:
            colors = "blue"
        lobj = ax.plot([], [], 'o-', lw=2, color=colors)[0]
        lines.append(lobj)
    
    def init():
        #line.set_data([], [])
        for line in lines:
            line.set_data([],[])
        return lines

    def animate(i):
        """
        line.set_data(x[i], y[i]+2)
        return line,
        """
        
        #for index in range(0,1):
        for lnum,line in enumerate(lines):
            line.set_data(xlist[lnum][i], ylist[lnum][i]+1) # set data for each line separately. 

        return lines
        
    anim = FuncAnimation(fig, animate, frames=len(t)/skip,
                                   interval=1,
                                   blit=True, init_func=init)
    #1000/skip * t.max() / len(t)
    
    if see_plot==0:
        plt.close(fig)
    return anim
Example #23
0
grafic(list_time, acceleration, 'tempo s', ' aceleracao m/s^2')
grafic(position_x, list_v_x, 'posicao x (metro)', 'velocidade m/s')
grafic(position_z, list_v_z, 'posicao z (metro)', 'velocidade m/s')

#Animação do pêndulo
logical = input('Deseja abrir a simulação? Digite s ou n' '\n')
if logical == 's':

    fig, ax = plt.subplots()
    xdata, ydata = position_x, position_z
    ln, = plt.plot([], [], 'ro', animated=True)
    spring, = plt.plot([], [], 'b-', linewidth=2)

    def init():
        ax.set_xlim(-2 * L, 2 * L)
        ax.set_ylim(2 * L, 0)
        return ln,

    def update(n):
        spring.set_data([0.0, xdata[n]], [0.0, ydata[n]])
        ln.set_data(xdata[n], ydata[n])
        return spring, ln

    ani = FuncAnimation(fig,
                        update,
                        n,
                        interval=0.001,
                        init_func=init,
                        blit=True)
    plt.show()
Example #24
0
        for j in range(node_numbers):
            if i != j and edge_list[i][j] > threshold:
                G.add_edge(names[i],
                           names[j],
                           weight=edge_list[i][j] * 10,
                           color="red")
                count += 1

    edges = G.edges()
    edges_weight_list = [G[u][v]['weight'] for u, v in edges]
    edges_color_list = [G[u][v]['color'] for u, v in edges]
    print("edge:", count)
    # print(len(edges_color_list))

    nx.draw_networkx_edges(G,
                           pos,
                           width=edges_weight_list,
                           arrowstyle="->",
                           edge_color=edges_color_list)

    # limits = plt.axis('off')  # turn of axis
    plt.xlabel("Day: " + str(k + 1) + " to " + str(k + 61))

    return G


anim = FuncAnimation(fig, animate, frames=T, repeat=False, interval=500)
plt.tight_layout()
anim.save('ani1.gif', dpi=300)
plt.show()
Example #25
0
from picamera.array import PiRGBArray
from picamera import PiCamera
import time
import cv2
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

camera = PiCamera()
rawCapture = PiRGBArray(camera)
time.sleep(0.1)


def grab_frame():
    camera.capture(rawCapture, format="bgr", use_video_port=True)
    image = rawCapture.array
    rawCapture.truncate(0)
    return image


ax1 = plt.subplot(1, 2, 1)
im1 = ax1.imshow(grab_frame())


def update(i):
    frame = grab_frame()
    im1.set_data(frame)
    return im1,


ani = FuncAnimation(plt.gcf(), update, interval=5, blit=True)
plt.show()
 def __init__(self, window):
     """Initialize spectrogram canvas graphs."""
     # Initialize variables to default values.
     self.window = window
     self.samples = 100  # Number of samples to store
     self.fftSize = 256  # Initial FFT size just to render something in the charts
     self.sampleRate = 0
     self.binFreq = 0
     self.binCount = self.fftSize / 2
     self.graphUpdateHz = 10  # Update rate of the animation
     self.coloredBin = None
     self.magnitudes = np.zeros((self.samples, self.binCount))
     # Tell numpy to ignore errors like taking the log of 0
     np.seterr(all='ignore')
     # Set up figure to hold plots
     self.figure = Figure(figsize=(1024, 768),
                          dpi=72,
                          facecolor=(1, 1, 1),
                          edgecolor=(0, 0, 0))
     # Set up 4x4 grid to hold 2 plots and colorbar
     gs = GridSpec(2, 2, height_ratios=[1, 2], width_ratios=[9.5, 0.5])
     gs.update(left=0.075, right=0.925, bottom=0.05, top=0.95, wspace=0.05)
     # Set up frequency histogram bar plot
     self.histAx = self.figure.add_subplot(gs[0])
     self.histAx.set_title('Frequency Histogram')
     self.histAx.set_ylabel('Intensity (decibels)')
     self.histAx.set_xlabel('Frequency Bin (hz)')
     self.histAx.set_xticks([])
     self.histPlot = self.histAx.bar(np.arange(self.binCount),
                                     np.zeros(self.binCount),
                                     width=1.0,
                                     linewidth=0.0,
                                     facecolor='blue')
     # Set up spectrogram waterfall plot
     self.spectAx = self.figure.add_subplot(gs[2])
     self.spectAx.set_title('Spectrogram')
     self.spectAx.set_ylabel('Sample Age (seconds)')
     self.spectAx.set_xlabel('Frequency Bin (hz)')
     self.spectAx.set_xticks([])
     self.spectPlot = self.spectAx.imshow(self.magnitudes,
                                          aspect='auto',
                                          cmap=get_cmap('jet'))
     # Add formatter to translate position to age in seconds
     self.spectAx.yaxis.set_major_formatter(
         FuncFormatter(lambda x, pos: '%d' % (x *
                                              (1.0 / self.graphUpdateHz))))
     # Set up spectrogram color bar
     cbAx = self.figure.add_subplot(gs[3])
     self.figure.colorbar(
         self.spectPlot,
         cax=cbAx,
         use_gridspec=True,
         format=FuncFormatter(lambda x, pos: '%d' % (x * 100.0)))
     cbAx.set_ylabel('Intensity (decibels)')
     # Initialize canvas
     super(SpectrogramCanvas, self).__init__(self.figure)
     # Hook up mouse and animation events
     self.mpl_connect('motion_notify_event', self._mouseMove)
     self.ani = FuncAnimation(self.figure,
                              self._update,
                              interval=1000.0 / self.graphUpdateHz,
                              blit=False)
def extract_current_folder():
    ''' 
    Extracts all photometry in the current folder, and animates one of the result sources
    Only treats fits file starting with hst and finishing with .fits
    '''
    global windows, xvv, yvv
    print('Extracting sources at positions : ', src_list)

    print('Filename\tEpoch\tMagnitudes')
    filenames = os.listdir('.')
    filenames.sort()
    mags = []
    times = []
    for f in filenames:
        if not f.startswith('hst') or not f.endswith('.fits'):
            continue

        # Extracting time and magnitude from current file
        time, mag = extract_photometry(f)
        times.append(time)
        mags.append(mag)

    mags = np.asarray(mags)
    times = np.asarray(times)

    # Plotting the magnitudes 1 by 1 to remove the NaNs
    for sid, _ in enumerate(src_list):
        # Sorting the files and magnitudes in Epoch order in case the files are
        # not already sorted
        mask = ~np.isnan(mags[:, sid])

        cur_mags = mags[mask, sid]
        cur_times = times[mask]

        N = cur_mags.shape[0]

        sorted_ids = [i for i in range(N)]
        sorted_ids.sort(key=lambda x: cur_times[x])

        cur_mags = cur_mags[sorted_ids]
        cur_times = cur_times[sorted_ids]
        plt.plot(cur_times, cur_mags, '-+')
    plt.show()

    # Animation part ... A bit ugly
    if wid > -1:
        # Ordering times
        N = len(windows)
        sorted_ids = [i for i in range(N)]
        sorted_ids.sort(key=lambda x: times[x])

        # 3D matrix : dim 0 -> Time, dim 1 -> y, dim 2 -> x
        windows = np.asarray(windows)[sorted_ids, :, :]

        max_v = windows.max()
        min_v = windows.min()
        z = windows[0]

        # Building figure
        fig = plt.figure(figsize=(10, 10))
        ax = fig.add_subplot(111, projection='3d')
        p = ax.plot_surface(xvv, yvv, z)

        # Number of interpolation points
        inter_t = 60
        inter_x = 100
        inter_y = 100

        ox = xvv[0, :]
        oy = yvv[:, 0]
        ot = times[sorted_ids]

        # Generating vector coords and meshgrid
        tv = np.linspace(ot.min(), ot.max(), inter_t)
        xv = np.linspace(xvv.min(), xvv.max(), inter_x)
        yv = np.linspace(yvv.min(), yvv.max(), inter_y)
        MT, MX, MY = np.meshgrid(tv, xv, yv, indexing='ij')

        # Rolling back to 1D for interpolation
        MT = MT.ravel()
        MX = MX.ravel()
        MY = MY.ravel()

        # Interpolation
        pos = np.stack((MT, MX, MY)).T
        f = RegularGridInterpolator((ot, ox, oy), windows)
        w_array = f(pos)
        w_array = w_array.reshape((inter_t, inter_x, inter_y))

        # Rebuilding 2D position matrices
        MX, MY = np.meshgrid(xv, yv)

        # Update function for matplotlib's anim
        def update(i):
            print('Rendering frame {}/{}'.format(i + 1, inter_t))
            z = w_array[i]
            ax.clear()
            p = ax.plot_surface(MX, MY, z)
            ax.set_zlim(min_v, max_v)
            return p,

        def init():
            update(0)

        # And rendering
        ani = FuncAnimation(fig,
                            update,
                            init_func=init,
                            frames=range(1, inter_t))
        Writer = animation.writers['ffmpeg']
        w = Writer(fps=15, bitrate=1800)
        print('Saving animation')
        ani.save('pulse.mp4', writer=w)
        plt.close('all')
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro', animated=True)


def init():
    ax.set_xlim(-1.5, 1.5)
    ax.set_ylim(-1.5, 1.5)
    return ln,


def update(frame):
    xdata.append(np.cos(frame))
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,


ani = FuncAnimation(fig,
                    update,
                    frames=np.linspace(0, 2 * np.pi, 50),
                    init_func=init,
                    blit=True)
ax.set_aspect(1. / ax.get_data_ratio())

plt.show()
Example #29
0
def animateTSP(country, history, points):
    """

    :param country: string
    :param history: list[int, float, float]
    :param points: list[int, float, float]
    :return:
    """
    try:
        # Prepare the coordinates for plotting the trip
        cityName = []
        latitude = []
        longitude = []
        for city in points:
            cityName.append(city[0])
            latitude.append(city[1] / 1000.)
            longitude.append(city[2] / 1000.)
        cityName.append(cityName[0])
        latitude.append(latitude[0])
        longitude.append(longitude[0])

        plt.figure(figsize=(7, 7))

        # Specify tripMap width and height
        if country == "Djibouti":
            tripMap = Basemap(width=350000,
                              height=270000,
                              resolution='i',
                              projection='tmerc',
                              lat_0=11.572076,
                              lon_0=43.145645)
        else:
            tripMap = Basemap(width=250000,
                              height=250000,
                              resolution='i',
                              projection='tmerc',
                              lat_0=25.286106,
                              lon_0=51.534817)

        tripMap.drawmapboundary(fill_color='aqua')
        tripMap.fillcontinents(color='#FFE4B5', lake_color='aqua')
        tripMap.drawcoastlines()
        tripMap.drawcountries()

        # Range the frames
        _frames = len(history) // 1500
        _frameRange = range(0, len(history), _frames)

        # Path is represented as line
        line = tripMap.plot([], [], 'D-', markersize=3, linewidth=1,
                            color='r')[0]

        # initial function
        def init_func():
            # Draw node dots on graph
            x = [longitude[i] for i in history[0]]
            y = [latitude[i] for i in history[0]]
            x, y = tripMap(x, y)
            tripMap.plot(x, y, 'bo', markersize=3)

            # Empty initialization
            line.set_data([], [])

            return line,

        # animate function
        def gen_function(frame):
            # Update the graph for each frame
            x = [longitude[i] for i in history[frame] + [history[frame][0]]]
            y = [latitude[i] for i in history[frame] + [history[frame][0]]]
            x, y = tripMap(x, y)
            line.set_data(x, y)

            return line

        # Animate the graph
        _animation = FuncAnimation(plt.gcf(),
                                   func=gen_function,
                                   frames=_frameRange,
                                   init_func=init_func,
                                   interval=10,
                                   repeat=False)
        plt.show()

    except:
        EH()
Example #30
0
    ymain.append(y1)
    yintegral.append(y2)
    ydiff.append(y3)

    line_main.set_data(xdata, ymain)
    line_integral.set_data(xdata, yintegral)
    line_diff.set_data(xdata, ydiff)
    return [line_main, line_integral, line_diff]


# Можно изменить figsize, если не вмещается окошко. lw - толщина линии
fig, ax = plt.subplots(3, 1, figsize=(7, 10))
line_main, = ax[0].plot([], [], 'b', lw=1.5)
line_integral, = ax[1].plot([], [], 'r', lw=1.5)
line_diff, = ax[2].plot([], [], 'g', lw=1.5)

ax[0].grid()
ax[1].grid()
ax[2].grid()
# Название графиков
ax[0].set_title('Main function')
ax[1].set_title('Integration')
ax[2].set_title('Differentiation')

xdata, ymain, yintegral, ydiff = [], [], [], []

# Установить номер COM-порта и скорость
ser = serial.Serial('COM3', 115200)
# interval - период опроса COM порта в миллисекундах
ani = FuncAnimation(fig, run, interval=10, init_func=init)
plt.show()