Пример #1
0
 def __init__(self, yAxisMax, xAxisMax):
     self.yAxisMax = yAxisMax
     self.xAxisMax = xAxisMax
     self.camera = Camera(plt.figure())
     self.legends = [str(c) for c in range(self.xAxisMax)]
     self.y_pos = np.arange(self.xAxisMax)
Пример #2
0
# Initialize Figure
# =========================
# plot data
plt.figure()
sns.jointplot(X_g[:, 0], X_g[:, 1], s=5, color="red")
# Log the plot
wandb.log({"trained_latent": wandb.Image(plt)})


# =========================
# PLOTTING LAYERS
# =========================

# initialize figure
fig, ax = plt.subplots()
camera = Camera(fig)

X_g_ = X


for ilayer, iparam in enumerate(params):

    X_g_ = forward_f_jitted(iparam, X_g_)

    ax.scatter(X_g_[:, 0], X_g_[:, 1], s=1, color="Red")
    ax.set_xlim([X_g_[:, 0].min() - 0.1, X_g_[:, 0].max() + 0.1])
    ax.set_ylim([X_g_[:, 1].min() - 0.1, X_g_[:, 1].max() + 0.1])
    ax.text(0.4, 1.05, f"Layer: {int(ilayer+1)}", transform=ax.transAxes, fontsize=20)
    camera.snap()

animation = camera.animate(500)
Пример #3
0
 def __init__(self, board, player, visualization_speed):
     self.board = board
     self.player = player
     self.camera = Camera(plt.figure())
     self.G, self.pos = self.init_board_visualizer()
     self.speed = visualization_speed
Пример #4
0
# plt.imshow(test[0].reshape(64, 64, 3))
# plt.show()
hidden_layer = [192]

ae = Autoencoder(64 * 64 * 3, hidden_layer, 64, 0.00000002)

ae.train(test, test, 50, 0.0005,5, 0.5,10, 0.1, True)

outputs = []
latent_space = []
for inp in range(len(test)):

    encoded_input = ae.encode(test[inp])
    latent_space.append(encoded_input)
    outputs.append(ae.decode(encoded_input))
    #show_image(outputs[inp].reshape(64,64,3))


fig,axs = plt.subplots()
camera = Camera(fig)
for i in range(len(latent_space)-1):
    l1 = latent_space[i]
    l2 = latent_space[i+1]
    step = np.subtract(l1, l2) / 8
    for j in range(9):
        out = ae.decode(np.subtract(l1, step*j)).reshape(64, 64, 3)
        plt.imshow(np.clip(out.reshape(64,64,3) + 0.5, 0, 1))
        camera.snap()
animation = camera.animate(interval=10, repeat=True)
plt.show()
alphas = np.random.uniform(-1.0 * r, r, size=k)
x_0 = 0.3  #Set initial points
x_1 = 0.7

#Get orbit points
x_0_orbit_lst = fixed_noise_otbit(x_0, a, alphas)
x_1_orbit_lst = fixed_noise_otbit(x_1, a, alphas)

figure, axes = plt.subplots(1)
theta = np.linspace(0, 2 * np.pi, 1000)
x_coord = np.cos(theta)
y_coord = np.sin(theta)
axes.set_title('Synchronisation of two trajectories')

camera = Camera(figure)

for i in range(k):
    #Take the arc of the circle between f^n(x_0) and f^n(x_1)
    if x_0_orbit_lst[i] < x_1_orbit_lst[i]:
        arc = np.linspace(x_0_orbit_lst[i], x_1_orbit_lst[i])
    else:
        arc = np.linspace(x_1_orbit_lst[i], x_0_orbit_lst[i])
    axes.set_aspect(1)
    if i < 10 or i % 10 == 0:
        axes.plot(x_coord, y_coord, c='black')
        #Plot the end points and the arc
        axes.scatter(np.cos(2 * np.pi * x_0_orbit_lst[i]),
                     np.sin(2 * np.pi * x_0_orbit_lst[i]),
                     c='red')
        axes.scatter(np.cos(2 * np.pi * x_1_orbit_lst[i]),
Пример #6
0
class Plotter:
    def __init__(self, process_count, time_slice):
        self.process_count = process_count
        self.time_slice = time_slice
        self.time = 0
        self.fig = None
        self.camera = None
        self.lines = []
        colors = get_colors()
        keys = list(colors.keys())
        random.shuffle(keys)
        self.__colors = dict([(key, colors[key]) for key in keys])

    def _plot_frame_filas(self, ax_filas, frame, i):
        def list_to_str(array):
            return map(lambda x: str(x), array)

        padding_left = 0.3
        font_size = 16

        processor_l_queue = frame['processor']['low']

        l_label = 'Fila baixa prioridade processador = [' + ','.join(
            list_to_str(processor_l_queue)) + ']'
        ax_filas.text(padding_left,
                      0.21,
                      l_label,
                      fontsize=font_size,
                      transform=plt.gcf().transFigure)

        processor_h_queue = frame['processor']['high']
        h_label = 'Fila alta prioridade processador = [' + ','.join(
            list_to_str(processor_h_queue)) + ']'
        ax_filas.text(padding_left,
                      0.19,
                      h_label,
                      fontsize=font_size,
                      transform=plt.gcf().transFigure)

        mag_current = frame['ioDevices']['magneticTape']['current']
        mag_current_label = 'Processo utilizando fita magnética = '

        if (mag_current != None):
            mag_current_label = mag_current_label + str(mag_current)

        ax_filas.text(padding_left,
                      0.17,
                      mag_current_label,
                      fontsize=font_size,
                      transform=plt.gcf().transFigure)

        mag_queue = frame['ioDevices']['magneticTape']['queue']
        mag_label = 'Fila fita magnética = [' + ','.join(
            list_to_str(mag_queue)) + ']'
        ax_filas.text(padding_left,
                      0.15,
                      mag_label,
                      fontsize=font_size,
                      transform=plt.gcf().transFigure)

        printer_current = frame['ioDevices']['printer']['current']
        printer_current_label = 'Processo utilizando impressora = '

        if (printer_current != None):
            printer_current_label = printer_current_label + \
                str(printer_current)

        ax_filas.text(padding_left,
                      0.13,
                      printer_current_label,
                      fontsize=font_size,
                      transform=plt.gcf().transFigure)

        printer_queue = frame['ioDevices']['printer']['queue']
        printer_label = 'Fila impressora = [' + ','.join(
            list_to_str(printer_queue)) + ']'
        ax_filas.text(padding_left,
                      0.11,
                      printer_label,
                      fontsize=font_size,
                      transform=plt.gcf().transFigure)

        hd_current = frame['ioDevices']['hardDisk']['current']
        hd_current_label = 'Processo utilizando HD = '

        if (hd_current != None):
            hd_current_label = hd_current_label + str(hd_current)

        ax_filas.text(padding_left,
                      0.09,
                      hd_current_label,
                      fontsize=font_size,
                      transform=plt.gcf().transFigure)

        hd_queue = frame['ioDevices']['hardDisk']['queue']
        hd_label = 'Fila HD = [' + ','.join(list_to_str(hd_queue)) + ']'
        ax_filas.text(padding_left,
                      0.07,
                      hd_label,
                      fontsize=font_size,
                      transform=plt.gcf().transFigure)

        ax_filas.text(padding_left,
                      0.04,
                      f"Quantum = {self.time_slice}",
                      fontsize=font_size,
                      transform=plt.gcf().transFigure)
        ax_filas.text(padding_left,
                      0.02,
                      f"Tempo = {i}",
                      fontsize=font_size,
                      transform=plt.gcf().transFigure)

    def _plot_frame_processos(self, ax_processos, frame, i):
        pid = frame["pid"]

        if (frame["pid"] != None):
            pid = frame["pid"]
        else:
            pid = -1
        # Minimizando o numero de retas a serem plotadas
        if len(self.lines) == 0:
            color = list(self.__colors.values())[pid - 1]
            line = ([i - 1, i], [pid, pid], color)
            self.lines.append(line)
        else:
            (xx, yy, color) = self.lines[len(self.lines) - 1]
            if yy[0] == yy[1] == pid:
                new_line = ([xx[0], i], yy, color)
                self.lines[len(self.lines) - 1] = new_line
            else:
                color = list(self.__colors.values())[pid - 1]
                line = ([i - 1, i], [pid, pid], color)
                self.lines.append(line)

        for xx, yy, color in self.lines:
            # t = ax_processos.plot(xx, yy, color=color,
            #                       linewidth=20.0, label=label, solid_capstyle='butt')
            #t = plt.barh(pid, xx[1] - xx[0], left=xx, color = color, edgecolor = color, align='center', height=1)

            #Se o processador estiver ocioso, não ploto nada
            if (yy[0] == -1):
                continue
            else:
                ax_processos.fill_between(xx, yy[0] - 1, yy[0], color=color)
                txt = ax_processos.text(avg(xx[0], xx[1]),
                                        avg(yy[0] - 1, yy[0]),
                                        f"{yy[0]}",
                                        horizontalalignment='center',
                                        verticalalignment='center',
                                        color='white')
                #txt.set_path_effects([path_effects.withStroke(linewidth=2, foreground='w')])
                txt.set_path_effects([
                    path_effects.Stroke(linewidth=2, foreground='black'),
                    path_effects.Normal()
                ])

            # if(pid == -1):
            #     ax_processos.legend(t, ["Ocioso"])
            # else:
            #     ax_processos.legend(t, [f' PID {pid}'])

    def plot(self, frames, output_file="animation.gif"):
        print('Gerando gif...')

        fig, (ax_processos,
              ax_filas) = plt.subplots(2,
                                       1,
                                       sharey=True,
                                       gridspec_kw={'height_ratios': [3, 1]})
        fig.set_figheight(8 + (self.process_count * 0.2))
        fig.set_figwidth(8 + (len(frames) * 0.08))
        self.fig = fig
        self.camera = Camera(self.fig)

        ax_processos.set_ylim((0, self.process_count + 2))
        ax_processos.set_xlim((0, len(frames)))
        ax_processos.set_yticks(range(0, self.process_count + 2, 1))

        x_spacing = 5

        if (len(frames) > 100):
            x_spacing = 10
        elif (len(frames) > 200):
            x_spacing = 20
        elif ((len(frames) > 300)):
            x_spacing = 30
        elif ((len(frames) > 400)):
            x_spacing = 40
        elif ((len(frames) > 500)):
            x_spacing = 50

        ax_processos.set_xticks(range(0, len(frames), x_spacing))

        ax_processos.set_ylabel("PID")
        ax_processos.set_xlabel("Tempo")
        ax_processos.grid()
        ax_processos.get_yaxis().set_visible(False)

        ax_filas.axis("off")

        for i in range(0, len(frames)):
            sch_frame = frames[i - 1]
            self._plot_frame_processos(ax_processos, sch_frame, i)
            self._plot_frame_filas(ax_filas, sch_frame, i)
            self.camera.snap()

        animation = self.camera.animate(interval=50)
        animation.save(output_file, dpi=100, fps=5, writer="pillow")
Пример #7
0
import numpy as np
import matplotlib.pyplot as plt
from celluloid import Camera

fig, ax = plt.subplots()
cam = Camera(fig)
plt.xlim(-5, 5)
plt.ylim(-5, 5)
for i in range(1, 50):
    plt.scatter(range(50), range(50))
    cam.snap()

animation = cam.animate(interval=50)
animation.save('ss.mp4')
Пример #8
0
def generate_animation(
    f,
    n_particles=100,
    n_steps=200,
    w=1.0,
    c1=0.5,
    c2=1.0,
    init_range=[-1, 1],
    plot_range=[-1, 1],
    fps=10,
    seed=655321,
    filepath="animation.gif",
):
    """Runs a PSO metaheuristic over the function provided and generates an
    animated gif.

    Args:
        f (name): Name of the function defined in functions.py to optimize.
        n_particles (int, optional): Number of particles. Defaults to 100.
        n_steps (int, optional): Number of opt. steps. Defaults to 200.
        w (float, optional): Inertia parameter. Defaults to 1.0.
        c1 (float, optional): Cognitive parameter. Defaults to 0.5.
        c2 (float, optional): Social parameter. Defaults to 1.0.
        init_range (list, optional): Range to random uniform the particles.
        Defaults to [-1, 1].
        plot_range (list, optional): X and Y limits. Defaults to [-1, 1].
        fps (int, optional): Frames per second of the animation. Defaults to
        10.
        filepath (str, optional): Filepath to save the animation. Defaults to
        "animation.gif".
    """
    np.random.seed(seed)
    # Retrieve the function specified
    f = get_test_function(f)
    # Generate the meshgrid and values for contour plot
    x = np.linspace(plot_range[0], plot_range[1], 50)
    y = np.linspace(plot_range[0], plot_range[1], 50)
    X, Y = np.meshgrid(x, y)
    Z = f(X, Y)

    # Initialize the figure
    fig = plt.figure(figsize=(10, 8))
    camera = Camera(fig)

    # Initialize the algorithm
    pso = PSO(n_particles=n_particles,
              n_dims=2,
              w=w,
              c1=c1,
              c2=c2,
              init_range=init_range)

    for i in range(n_steps):
        # Plot positions
        ax = plt.axes(xlim=plot_range, ylim=plot_range)
        ax.contour(X, Y, np.log(Z))
        ax.scatter(pso.pos[:, 0], pso.pos[:, 1], c="b", s=4)
        camera.snap()
        # Evaluate positions
        evals = f(pso.pos[:, 0], pso.pos[:, 1])
        # Update positions
        pso.step(evaluations=evals)
    # Generate Animation
    animation = camera.animate()
    animation.save(filepath, writer="imagemagick", fps=10)
Пример #9
0
def createAnimation(inGrid, gridSize, generations, rulestring):
    """
    Executes {generations} number of time step updates to model the Game of Life
    while also taking snapshots to compile into an animation at the end
    """
    if not os.path.exists("GoL-gifs"): os.mkdir("GoL-gifs")
    filename = unique_file("GoL-gifs/LifeSim".format(generations), "gif")

    gridOn = input('Do you want to see gridlines? (y/n) ')
    while (gridOn != 'y') and (gridOn != 'n'):
        gridOn = input('Do you want to see gridlines? (y/n) ')

    fps = input('Please enter desired gif frame rate (ex. 5, 10, etc.): ')
    while not fps.isdigit():
        fps = input(
            'Enter desired gif frame rate as an integer (ex. 5, 10, etc.): ')

    if int(fps) <= 0:
        fps = 1
    Writer = animation.writers['pillow']
    writer = Writer(fps=int(fps), metadata=dict(artist='Me'), bitrate=1800)

    if (inGrid.shape[0] < gridSize[0]) or (inGrid.shape[1] < gridSize[1]):
        grid = addSpace(inGrid, gridSize)
    else:
        grid = inGrid.copy()

    fig = plt.figure()
    fig.set_size_inches(8, 8)
    camera = Camera(fig)
    if (gridOn == 'y'):
        ax = plt.gca()
        ax.set_xticks(np.arange(-.5, gridSize[1], 1), minor=True)
        ax.set_yticks(np.arange(-.5, gridSize[0], 1), minor=True)
        ax.grid(which='minor', color='w', linestyle='-', linewidth=2)
        ax.set_xticklabels([])
        ax.set_yticklabels([])
    else:
        plt.axis('off')
    plt.annotate('Generation (0/{})...'.format(generations),
                 xy=(50, 30),
                 xycoords='figure pixels',
                 size=20)
    plt.imshow(grid, cmap=GRID_CMAP)
    camera.snap()

    for i in range(generations):
        plt.annotate('Generation ({}/{})...'.format(i + 1, generations),
                     xy=(50, 30),
                     xycoords='figure pixels',
                     size=20)
        if (gridOn == 'y'):
            ax = plt.gca()
            ax.set_xticks(np.arange(-.5, gridSize[1], 1), minor=True)
            ax.set_yticks(np.arange(-.5, gridSize[0], 1), minor=True)
            ax.grid(which='minor', color='w', linestyle='-', linewidth=2)
            ax.set_xticklabels([])
            ax.set_yticklabels([])
        else:
            plt.axis('off')
        plt.imshow(updateGrid(grid, rulestring), cmap=GRID_CMAP)
        camera.snap()
        print('Generation ({}/{})...'.format(i + 1, generations))

    print()
    print('Creating animation... Please wait...')
    ani = camera.animate()
    ani.save(filename, writer=writer)
    print("Done! Saved as {}".format(filename))
    print()
#Se toma de la lista Xs1, que tiene las posiciones en x de cada particula en toda la caja, las posiciones del tope izquierdo hasta la mitad
for i in Xs1:
    temporal = []
    for j in i:
        if j > (-ancho) and j <= (0):
            temporal.append(j)
    Xs2.append(temporal)
#Se hace la lista de regreso para la lista recien llenada
for i in Xs2:
    Xr2.append(regreson(i))
t = [
    0
]  #Aqui se guardan las itereaciones realizadas. Es el contador de iteraciones
unico = 0  #Solo se usa una vez al momento de pasar de la mitad a la caja a toda la caja
fig = plt.figure()  #Se inicializa la figura para las graficas
camera = Camera(
    fig)  #Se inicializa el objeto que toma las capturas de pantalla.
primero = False  #Indica hasta cuando se mantiene en solo la mitad de la caja. Cuando se convierte en True pasa a toda la caja
segundo = True  #Indica hasta cuando se mantiene en toda la caja. Cuando pasa a False se mantiene ahi hasta que vuelve a ser True
Global = False  #Indica hasta cuando hacer todas las iteraciones (hasta cuando se mantiene dentro del while). Cuando para a True termina el proceso y procede a hacer el video
cont_primero = 0  #Indica el equilibrio en la primera mitad de la caja. Si llega a ser igual a 80 entonces permite que primero=True y comienza el proceso en toda la caja
cont_segundo = 0  #Indica el equilibrio cuando estan en toda la caja. Si llega a 60 entonces hace que Global=True y termina el while
while Global == False:
    mitad = 0  #Este contador siempre empieza en cero. Nos indica la cantidad de pelotas que hay del lado derecho de la caja
    xtemp = [
    ]  #Las posiciones actuales de cada particula en x. Este es el que se grafica y muestra la primera grafica del video
    ytemp = [
    ]  #Las posiciones actuales de cada particula en y. Este es el que se grafica y muestra la primera grafica del video.
    if primero == False:  #Hasta que primero=True termina este ciclo. Este ciclo es para la  mitad de la caja
        for i in range(len(Xs1)):
            if vueltax[
                    i] % 2 == 0:  #Si es un multiplo de 2, la particula va hacia la derecha y hace un copy de Xs2
Пример #11
0
import matplotlib.pyplot as plt
import numpy as np
from celluloid import Camera
from mpl_toolkits.mplot3d import Axes3D  # <--- This is important for 3d plotting


def z(x, y):
    res = np.sin(np.pi * x) * np.sin(np.pi * y)
    return res


if __name__ == '__main__':
    fig = plt.figure()
    ax = fig.gca(projection='3d')
    camera = Camera(fig)

    X, Y = np.mgrid[-1:1:30j, -1:1:30j]
    Z = z(X, Y)

    for counter_x in range(len(X[0])):
        for counter_y in range(len(Y[0])):
            _x = X[counter_x][0]
            _y = Y[0][counter_y]
            _z = np.sin(np.pi * _x) * np.sin(np.pi * _y)

    size = [1]

    x0s = []
    y0s = []
    z0s = []
Пример #12
0
    def animate(self, bp=None, fps=60):
        colors = cm.rainbow(np.linspace(0, 1, len(self.bodyparts2plot)))
        camera = Camera(plt.figure())

        for frame in range(self.startframe, self.endframe):
            if frame % 100 == 0:
                print("Animating Frame", frame)
            plt.scatter(self.df_x[:, frame],
                        self.df_y[:, frame],
                        c=colors,
                        s=100)  # how to handle low confidence

            for bp_index, bp_likelihood in enumerate(
                    self.df_likelihood[:, frame]):
                plt.annotate(
                    np.around(bp_likelihood, 2),
                    (self.df_x[bp_index, frame], self.df_y[bp_index, frame]))

            # https://stackoverflow.com/questions/2051744/reverse-y-axis-in-pyplot
            plt.ylim(720, 0)

            if bp == 'whiskers':
                self.plot_regres(*self.m_midline_arr[frame])
                self.plot_regres(*self.m_c1_l_arr[frame])
                self.plot_regres(*self.m_c1_r_arr[frame])

                angle_annotation = "Left Angle: " + str(
                    np.around(self.angle_l_arr[frame],
                              2)) + " Right Angle: " + str(
                                  np.around(self.angle_r_arr[frame], 2))
                plt.text(650, 0, angle_annotation)

            if bp == 'eyes':
                x1_l = [self.df_x[11, frame], self.df_x[15, frame]]
                y1_l = [self.df_y[11, frame], self.df_y[15, frame]]
                x2_l = [self.df_x[12, frame], self.df_x[14, frame]]
                y2_l = [self.df_y[12, frame], self.df_y[14, frame]]
                x1_r = [self.df_x[17, frame], self.df_x[21, frame]]
                y1_r = [self.df_y[17, frame], self.df_y[21, frame]]
                x2_r = [self.df_x[18, frame], self.df_x[20, frame]]
                y2_r = [self.df_y[18, frame], self.df_y[20, frame]]
                plt.plot(x1_l, y1_l, color='blue')
                plt.plot(x1_r, y1_r, color='blue')
                plt.plot(x2_l, y2_l, color='blue')
                plt.plot(x2_r, y2_r, color='blue')

                blink_annotation = "Left Blink Signal: " + str(
                    np.around(self.d_l_arr[frame],
                              2)) + " Right Blink Signal: " + str(
                                  np.around(self.d_r_arr[frame], 2))
                plt.text(400, 0, blink_annotation)

            frame_annotation = "Frame: " + str(frame)
            plt.text(0, 0, frame_annotation)

            camera.snap()

        print("Animating...")
        anim = camera.animate(blit=True)
        print("Saving...")
        anim_filename = 'animation_' + bp + str(fps) + "fps.mp4"
        anim.save(self.outpath + anim_filename, fps=fps)
Пример #13
0
def draw(down_case, up_case, to_plot):
    for p in to_plot:
        fig = plt.figure()
        camera = Camera(fig)
        if p['loc'] == 'up':
            x = up_case[p['x']].values
            y = up_case[p['y']].values
        else:
            x = down_case[p['x']].values
            y = down_case[p['y']].values

        if len(x) > 60:
            case_range = int(len(x) / 6)
        elif 60 >= len(x) >= 30:
            case_range = int(len(x) / 4)
        else:  # <30
            case_range = 5

        # ***************** IF WE WANT ORIGINAL SCALE *****************
        # plt.axis([0.0, 1368, 0.0, 912])

        # ***************** IF WE WANT DYNAMIC SCALE *****************
        plt.axis(xmin=min(x) - 200,
                 xmax=max(x) + 200,
                 ymin=min(y) - 200,
                 ymax=max(y) + 200)
        plt.title(f"{p['loc'].title()} - {p['text']} [{len(x)}]")

        di = 255 / len(x)
        colormap = [(0 + x * di / 256, .1, 1.0 - x * di / 256)
                    for x in range(len(x))]
        for i in range(len(x)):
            plt.plot(x[0], y[0], marker='o',
                     color='green')  # the start (first point)
            plt.plot(x[len(x) - 1], y[len(y) - 1], marker='o',
                     color='c')  # the end  (last point)
            plt.plot(np.mean(x), np.mean(y), marker='o',
                     color='yellow')  # total data average point

            plt.plot(midpointX, midpointY, marker='+',
                     color='k')  # the middle (black)
            plt.plot([midpointX - 77, midpointX - 77],
                     [midpointY - 72, midpointY + 72],
                     "k-",
                     linewidth=0.8)  # center black cube - left
            plt.plot([midpointX + 77, midpointX + 77],
                     [midpointY - 72, midpointY + 72],
                     "k-",
                     linewidth=0.8)  # center black cube - right
            plt.plot([midpointX - 77, midpointX + 77],
                     [midpointY - 72, midpointY - 72],
                     "k-",
                     linewidth=0.8)  # center black cube - bottom
            plt.plot([midpointX - 77, midpointX + 77],
                     [midpointY + 72, midpointY + 72],
                     "k-",
                     linewidth=0.8)  # center black cube - top

            plt.plot(np.mean(x[:case_range]),
                     np.mean(y[:case_range]),
                     marker='X',
                     color='xkcd:fluorescent green',
                     markeredgewidth=0.5,
                     markeredgecolor='b')  # the start (first 10)
            plt.plot(np.mean(x[-case_range:]),
                     np.mean(y[-case_range:]),
                     marker='X',
                     color='xkcd:red orange',
                     markeredgewidth=0.5,
                     markeredgecolor='b')  # the end (last 10)

            plt.scatter(x[:i + 1],
                        y[:i + 1],
                        marker='o',
                        color=colormap[:i + 1])

            camera.snap()

        animation = camera.animate(interval=_interval, repeat=False)
        animation.save(
            f'strabismus_{patient_id}_{exam_id}_{p["loc"]}_{p["text"]}_{exam_id}.gif',
            writer='pillow')

        plt.close(fig)
        print(
            f"Finished Animating Strabismus Plot for : {p['loc']} , {p['text']}"
        )
Пример #14
0
def plot_teller(teller_data, pre_data, teller_type, opened_eye):
    eye = opened_eye.lower()
    center_x = teller_data['X'].iloc[
        0]  # center of teller picture on the X scale
    center_y = teller_data['Y'].iloc[
        0]  # center of the teller picture on the Y scale
    width = teller_data['Width'].iloc[0]  # width of inner box
    height = teller_data['Height'].iloc[0]  # height of inner box
    teller_position = "left" if (center_x < 500) else "right"
    ind = teller_data['Index'].iloc[0]

    x = teller_data[f'{eye}x'].values
    y = teller_data[f'{eye}y'].values

    # last 20 points before teller.
    pre_data_subset_x = pre_data[f'{eye}x'].iloc[-30:].values
    pre_data_subset_y = pre_data[f'{eye}y'].iloc[-30:].values

    fig = plt.figure()
    camera = Camera(fig)

    if len(x) > 60:
        case_range = int(len(x) / 6)
    elif 60 >= len(x) >= 30:
        case_range = int(len(x) / 4)
    else:  # <30
        case_range = 5

    # Setting custom ticks
    # plt.xticks(np.arange(0, max(x)+50, step=50))
    # plt.yticks(np.arange(0, max(y)+50, step=50))

    # ***************** IF WE WANT DYNAMIC SCALE - BY VALUES *****************
    tmp_x_values = np.concatenate((x, pre_data_subset_x))
    tmp_y_values = np.concatenate((y, pre_data_subset_y))
    zoom_parameter = 150

    # ***************** IF WE WANT DYNAMIC SCALE - BY SCREEN WIDTH/HEIGHT *****************
    # plt.xlim(0, Termx)
    # plt.ylim(0, Termy)

    # ***************** IF WE WANT ORIGINAL SCALE *****************
    # plt.xlim(0, 1368)
    # plt.ylim(0, 912)

    di = 255 / len(x)
    colormap = [(0 + x * di / 256, .1, 1.0 - x * di / 256)
                for x in range(len(x))]
    # colormap = [ (x, .1, y) for x, y in zip(np.arange(1, 0, -1 / len(x)), np.arange(0, 1, 1 / len(x)))]

    for j in range(len(pre_data_subset_x)):
        plt.scatter(pre_data_subset_x[:j + 1],
                    pre_data_subset_y[:j + 1],
                    marker='s',
                    color='orange')
        plt.plot(center_x, center_y, marker='o', color='k')  # center of teller

        # Constructing the teller bound and it's outer box.
        if teller_position == "left":
            plt.plot([int(center_x - width),
                      int(center_x - width)],
                     [int(center_y - height),
                      int(center_y + height)], "k-")  # outer box - left
            plt.plot(
                [int(center_x + width / 1.5),
                 int(center_x + width / 1.5)],
                [int(center_y - height),
                 int(center_y + height)], "k-")  # outer box - right
            plt.plot([int(center_x + width),
                      int(center_x + width)],
                     [int(center_y - height),
                      int(center_y + height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - right - dashed
            plt.plot([int(center_x - width),
                      int(center_x + width / 1.5)],
                     [int(center_y + height),
                      int(center_y + height)], "k-")  # outer box - top
            plt.plot([int(center_x - width),
                      int(center_x + width / 1.5)],
                     [int(center_y - height),
                      int(center_y - height)], "k-")  # outer box - bottom
            plt.plot([int(center_x - width),
                      int(center_x + width)],
                     [int(center_y + height),
                      int(center_y + height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - top - dashed
            plt.plot([int(center_x - width),
                      int(center_x + width)],
                     [int(center_y - height),
                      int(center_y - height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - bottom - dashed
        else:
            plt.plot(
                [int(center_x - width / 1.5),
                 int(center_x - width / 1.5)],
                [int(center_y - height),
                 int(center_y + height)], "k-")  # outer box - left
            plt.plot([int(center_x - width),
                      int(center_x - width)],
                     [int(center_y - height),
                      int(center_y + height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - left - dashed
            plt.plot([int(center_x + width),
                      int(center_x + width)],
                     [int(center_y - height),
                      int(center_y + height)], "k-")  # outer box - right
            plt.plot([int(center_x - width / 1.5),
                      int(center_x + width)],
                     [int(center_y + height),
                      int(center_y + height)], "k-")  # outer box - top
            plt.plot([int(center_x - width / 1.5),
                      int(center_x + width)],
                     [int(center_y - height),
                      int(center_y - height)], "k-")  # outer box - bottom
            plt.plot([int(center_x - width),
                      int(center_x + width)],
                     [int(center_y + height),
                      int(center_y + height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - top - dashed
            plt.plot([int(center_x - width),
                      int(center_x + width)],
                     [int(center_y - height),
                      int(center_y - height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - bottom - dashed

        plt.plot([int(center_x - width / 2),
                  int(center_x - width / 2)],
                 [int(center_y - height / 2),
                  int(center_y + height / 2)], "k-")  # inner box - left
        plt.plot([int(center_x + width / 2),
                  int(center_x + width / 2)],
                 [int(center_y - height / 2),
                  int(center_y + height / 2)], "k-")  # inner box - right
        plt.plot([int(center_x - width / 2),
                  int(center_x + width / 2)],
                 [int(center_y + height / 2),
                  int(center_y + height / 2)], "k-")  # inner box - top
        plt.plot([int(center_x - width / 2),
                  int(center_x + width / 2)],
                 [int(center_y - height / 2),
                  int(center_y - height / 2)], "k-")  # inner box - bottom

        camera.snap()

    for i in range(len(x)):
        plt.plot(np.mean(x), np.mean(y), marker='o',
                 color='y')  # mean point of whole data.
        plt.plot(x[0], y[0], marker='o', color='green')  # the first point.
        plt.plot(x[len(x) - 1], y[len(y) - 1], marker='o',
                 color="c")  # the last point.

        plt.plot(center_x, center_y, marker='o', color='k')  # center of teller

        # Constructing the teller bound and it's outer box.
        if teller_position == "left":
            plt.plot([int(center_x - width),
                      int(center_x - width)],
                     [int(center_y - height),
                      int(center_y + height)], "k-")  # outer box - left
            plt.plot(
                [int(center_x + width / 1.5),
                 int(center_x + width / 1.5)],
                [int(center_y - height),
                 int(center_y + height)], "k-")  # outer box - right
            plt.plot([int(center_x + width),
                      int(center_x + width)],
                     [int(center_y - height),
                      int(center_y + height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - right - dashed
            plt.plot([int(center_x - width),
                      int(center_x + width / 1.5)],
                     [int(center_y + height),
                      int(center_y + height)], "k-")  # outer box - top
            plt.plot([int(center_x - width),
                      int(center_x + width / 1.5)],
                     [int(center_y - height),
                      int(center_y - height)], "k-")  # outer box - bottom
            plt.plot([int(center_x - width),
                      int(center_x + width)],
                     [int(center_y + height),
                      int(center_y + height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - top - dashed
            plt.plot([int(center_x - width),
                      int(center_x + width)],
                     [int(center_y - height),
                      int(center_y - height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - bottom - dashed
        else:
            plt.plot(
                [int(center_x - width / 1.5),
                 int(center_x - width / 1.5)],
                [int(center_y - height),
                 int(center_y + height)], "k-")  # outer box - left
            plt.plot([int(center_x - width),
                      int(center_x - width)],
                     [int(center_y - height),
                      int(center_y + height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - left - dashed
            plt.plot([int(center_x + width),
                      int(center_x + width)],
                     [int(center_y - height),
                      int(center_y + height)], "k-")  # outer box - right
            plt.plot([int(center_x - width / 1.5),
                      int(center_x + width)],
                     [int(center_y + height),
                      int(center_y + height)], "k-")  # outer box - top
            plt.plot([int(center_x - width / 1.5),
                      int(center_x + width)],
                     [int(center_y - height),
                      int(center_y - height)], "k-")  # outer box - bottom
            plt.plot([int(center_x - width),
                      int(center_x + width)],
                     [int(center_y + height),
                      int(center_y + height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - top - dashed
            plt.plot([int(center_x - width),
                      int(center_x + width)],
                     [int(center_y - height),
                      int(center_y - height)],
                     "k-",
                     linestyle='dashed',
                     linewidth=1.2)  # outer box - bottom - dashed

        plt.plot([int(center_x - width / 2),
                  int(center_x - width / 2)],
                 [int(center_y - height / 2),
                  int(center_y + height / 2)], "k-")  # inner box - left
        plt.plot([int(center_x + width / 2),
                  int(center_x + width / 2)],
                 [int(center_y - height / 2),
                  int(center_y + height / 2)], "k-")  # inner box - right
        plt.plot([int(center_x - width / 2),
                  int(center_x + width / 2)],
                 [int(center_y + height / 2),
                  int(center_y + height / 2)], "k-")  # inner box - top
        plt.plot([int(center_x - width / 2),
                  int(center_x + width / 2)],
                 [int(center_y - height / 2),
                  int(center_y - height / 2)], "k-")  # inner box - bottom

        plt.plot(np.mean(x[:case_range]),
                 np.mean(y[:case_range]),
                 marker='X',
                 color='xkcd:fluorescent green',
                 markeredgewidth=0.5,
                 markeredgecolor='b')  # the start (first 10)
        plt.plot(np.mean(x[-case_range:]),
                 np.mean(y[-case_range:]),
                 marker='X',
                 color='xkcd:red orange',
                 markeredgewidth=0.5,
                 markeredgecolor='b')  # the end (last 10)

        plt.title(
            f"Patient Id: {patient_id} Total Points: {len(x)}\nTeller: {teller_type} - Eye: {eye.upper()} - Teller Position: {'R' if teller_position == 'right' else 'L'} - Index: {ind}"
        )
        plt.text(x[i] + 5,
                 y[i] + 5,
                 f'{i+1}',
                 size='13',
                 color='white',
                 style='italic',
                 bbox={
                     'boxstyle': 'round',
                     'facecolor': 'gray',
                     'alpha': 0.8
                 })

        plt.scatter(x[:i + 1],
                    y[:i + 1],
                    marker='o',
                    color=colormap[:i + 1],
                    label=f"{i+1}")

        plt.xlim(
            min(tmp_x_values) - zoom_parameter,
            max(tmp_x_values) + zoom_parameter)
        plt.ylim(
            min(tmp_y_values) - zoom_parameter,
            max(tmp_y_values) + zoom_parameter)

        camera.snap()

    animation = camera.animate(interval=_interval, repeat=False)

    animation.save(
        f'tellers_{patient_id}_{exam_id}_{teller_type}_{ind}_{opened_eye}_{teller_position}.gif',
        writer='pillow')

    plt.close(fig)
    print(
        f"Finished Animating Teller Plot for : Patient Id : {patient_id}, Exam Id : {exam_id}, Teller Type : {teller_type}, Teller Index : {ind}, Opened Eye : {opened_eye}, Teller Position : {teller_position}"
    )
Пример #15
0
fig2.tight_layout()
plt.savefig("report/figures/sim_NIS_NEES.eps", format="eps")

# %% Movie time

if playMovie:
    try:
        print("recording movie...")

        from celluloid import Camera

        pauseTime = 0.05
        fig_movie, ax_movie = plt.subplots(num=6, clear=True)

        camera = Camera(fig_movie)

        ax_movie.grid()
        ax_movie.set(xlim=(mins[0], maxs[0]), ylim=(mins[1], maxs[1]))
        camera.snap()

        for k in tqdm(range(N)):
            ax_movie.scatter(*landmarks.T, c="r", marker="^")
            ax_movie.plot(*poseGT[:k, :2].T, "r-")
            ax_movie.plot(*pose_est[:k, :2].T, "g-")
            ax_movie.scatter(*lmk_est[k].T, c="b", marker=".")

            if k > 0:
                el = ellipse(pose_est[k, :2], P_hat[k][:2, :2], 5, 200)
                ax_movie.plot(*el.T, "g")
Пример #16
0
def binary_sorting_viz(y_true,
                       y_pred,
                       target_phenomenon='Presence',
                       steps=500,
                       pause=100,
                       cols=['blue', 'red']):
    '''

    :param y_true,y_pred:
    arrays or lists, the true and predicted labels for the data
    :param target_phenomenon:
    string, used for labelling
    :param steps:
    number of frames to use for movement
    :param pause:
    number of frames to wait for after movement, useful when using packages that don't handle ending commands
    well like IPython display widgets
    :param cols:
    list of colors, [0_cat color, 1_cat color]
    :return:
    a matplotlib animation object
    '''
    from celluloid import Camera
    from matplotlib.patches import Rectangle
    import matplotlib.patches as mpatches
    col0 = cols[0]
    col1 = cols[1]
    font_details = {'fontsize': 'large', 'ha': 'center', 'va': 'top'}

    init_pts_x = np.array([(-10 + 20 * s) + np.random.normal(scale=4)
                           for s in y_true])
    init_pts_y = np.array([np.random.normal(scale=.2) for s in y_true])

    final_pts_x = np.array([
        (s * (np.random.uniform(low=5, high=25)) + (1 - s) *
         (np.random.uniform(low=-25, high=-5)))[0] for s in y_pred
    ])
    final_pts_y = np.array([((np.random.uniform(low=3, high=5)))
                            for s in y_pred])

    fig, ax = plt.subplots()
    plt.ylim(-2, 5)
    plt.xlim(-28, 28)
    ax.axis('off')

    ax.text(-16, 2.8, f'No {target_phenomenon}', font_details)
    ax.text(14, 2.8, f'{target_phenomenon}', font_details)
    cam2 = Camera(fig)
    for t in np.linspace(0, 1, steps):
        ax.add_patch(Rectangle((-25, 3), 20, 2, fc=col0, alpha=.1))
        ax.add_patch(Rectangle((5, 3), 20, 2, fc=col1, alpha=.1))
        ax.text(-16, 2.8, f'No {target_phenomenon}\nPredicted', font_details)
        ax.text(14, 2.8, f'{target_phenomenon}\nPredicted', font_details)

        u = (init_pts_x * (1 - t) + final_pts_x * (t))
        v = (init_pts_y * (1 - t) + final_pts_y * (t))
        ax.legend(handles=[
            mpatches.Patch(color=col0, label=f'No {target_phenomenon}'),
            mpatches.Patch(color=col1, label=f'Has {target_phenomenon}')
        ],
                  bbox_to_anchor=(0.5, 0),
                  loc='lower center',
                  ncol=2)
        ax.scatter(u,
                   v,
                   color=[col1 if s == 1 else col0 for s in y_true],
                   alpha=.4,
                   edgecolors='black')
        cam2.snap()

    for r in range(pause):
        # adjust as linspace is adjusted
        ax.add_patch(Rectangle((-25, 3), 20, 2, fc=col0, alpha=.1))
        ax.add_patch(Rectangle((5, 3), 20, 2, fc=col1, alpha=.1))
        ax.text(-16, 2.8, f'No {target_phenomenon}\nPredicted', font_details)
        ax.text(14, 2.8, f'{target_phenomenon}\nPredicted', font_details)

        u = (final_pts_x)
        v = (final_pts_y)
        ax.legend(handles=[
            mpatches.Patch(color=col0, label=f'No {target_phenomenon}'),
            mpatches.Patch(color=col1, label=f'Has {target_phenomenon}')
        ],
                  bbox_to_anchor=(0.5, 0),
                  loc='lower center',
                  ncol=2)
        ax.scatter(u,
                   v,
                   color=[col1 if s == 1 else col0 for s in y_true],
                   alpha=.4,
                   edgecolors='black')
        cam2.snap()

        # Workaround to pause at end of video since matplotlib is awkward with that.
        # Very crude method done for expediency only
    plt.close()
    ani2 = cam2.animate()
    return ani2
Пример #17
0
        ship['y'] += ship['v_y']

        draw_orbit()
        draw_planet()
        plt.scatter(ship['x'], ship['y'], c='k')
        cam.snap()
        move_planet()
    animate(75)


# make Canvas
scale = 3
fig, axes = plt.subplots()
ax = plt.axes(xlim=(-20 * scale, 20 * scale), ylim=(-20 * scale, 20 * scale))
ax.set_aspect('equal')
cam = Camera(fig)

# planet parameters
seed = 93647227
np.random.seed(seed)
planet_radius = (4, 11, 18)
planet_radius = tuple(map(lambda x: scale * x, planet_radius))
planet_theta_init = np.random.uniform(-np.pi, np.pi, (3, ))
planet_theta = planet_theta_init.copy()
angular_velocity = np.sort(np.random.uniform(0, np.pi / 50, (3, )))[::-1]

# Initialize parameters
time = 150
n = 500
epsilon = 0.0
deceleration = 0.5
Пример #18
0
    n_det[i] = event_detected.sum()  # total number of detected photons
    f_det[i] = n_det[i] / n_em[i]  # ratio of detected to emitted photons

    print(
        f'{i+1} emitted events {n_em[i]}  detected events: {n_det[i]}  ratio {f_det[i]:.2e}'
    )

    #-----------------------------------------------------------------------------------------------------
    # animate the last experiment and save to animated gif

    if i < n_animate:
        from celluloid import Camera

        cols = ['tab:blue', 'tab:orange']
        fig, ax = plt.subplots(1, 1, figsize=(6, 6))
        cam = Camera(fig)
        ax.set_xlim(-1.5, 1.5)
        ax.set_ylim(-1.5, 1.5)
        ax.set_axis_off()

        # add the detector
        rect = patches.Rectangle((1, -np.tan(phi_dec / 2)),
                                 0.4,
                                 2 * np.tan(phi_dec / 2),
                                 linewidth=1,
                                 edgecolor='none',
                                 facecolor='black')

        n_det_cum = np.cumsum(event_detected)
        n_em_cum = np.cumsum(em)
Пример #19
0
def plot_delay_dcconverter(dir=None,
                           test=None,
                           files=["file"],
                           type="",
                           txt="txt",
                           div_delay=[0],
                           output="output",
                           PdfPages=PdfPages,
                           directory=directory,
                           ylim=4000,
                           title="title",
                           logo=True):
    im = image.imread(directory + dir + 'icon.png')
    col_row = plt.cm.BuPu(np.linspace(0.3, 0.9, 5))
    for file in files:
        fig = plt.figure()
        ax = fig.add_subplot(111)
        x_axis = []
        v_cin = []
        v_cout = []
        v_in = []
        with open(directory + dir + test + file + ".csv",
                  'r') as data:  # Get Data for the first Voltage
            reader = csv.reader(data)
            next(reader)
            next(reader)
            for row in reader:
                x_axis = np.append(
                    x_axis,
                    float(row[0]) + div_delay[files.index(file)])
                if type.startswith("_no") is not True:
                    v_in = np.append(v_in, float(row[1]))
                    v_cin = np.append(v_cin, float(row[2]))
                    v_cout = np.append(v_cout, float(row[3]))
                else:
                    v_cin = np.append(v_cin, float(row[1]))
                    v_cout = np.append(v_cout, float(row[2]))
        if type.startswith("_no") is not True:
            ax.errorbar(x_axis,
                        v_in,
                        yerr=0.0,
                        color="yellow",
                        fmt='-',
                        markerfacecolor='white',
                        ms=3,
                        label="Power supply voltage  $U_S$ [V]")
        ax.errorbar(x_axis,
                    v_cin,
                    yerr=0.0,
                    color="green",
                    fmt='-',
                    markerfacecolor='white',
                    ms=3,
                    label="supply voltage to the DC/DC module")
        ax.errorbar(x_axis,
                    v_cout,
                    yerr=0.0,
                    color="blue",
                    fmt='-',
                    markerfacecolor='white',
                    ms=3,
                    label="Output Voltage from the DC/DC module")
        ax.text(0.95,
                0.35,
                files[files.index(file)] + "V",
                fontsize=10,
                horizontalalignment='right',
                verticalalignment='top',
                transform=ax.transAxes,
                bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.2))
        # plt.axvline(x=-4.7227+div_delay[files.index(file)], linewidth=0.8, color="red", linestyle='dashed')
        # plt.axvline(x=-4.7227+div_delay[files.index(file)]+2.04*0.001, linewidth=0.8, color="red", linestyle='dashed')
        # plt.axhline(y=24, linewidth=0.8, color=colors[1], linestyle='dashed')
        ax.ticklabel_format(useOffset=False)
        ax.legend(loc="upper left", prop={'size': 8})
        ax.set_ylabel("Voltage [V]")
        ax.autoscale(enable=True, axis='x', tight=None)
        ax.set_title(title, fontsize=12)
        ax.set_ylim([-5, 25])
        # ax.set_xlim([-0.04,0])
        ax.grid(True)
        ax.set_xlabel("time $t$ [ms]")
        ax.set_ylabel(r'Voltage [V]')
        fig.figimage(im, 5, 5, zorder=1, alpha=0.2, resize=False)
        plt.tight_layout()
        PdfPages.savefig()
        plt.savefig(directory + dir + test + file + type + ".png",
                    bbox_inches='tight')
        plt.clf()

    # animation
    cam_fig = plt.figure()
    ax2 = cam_fig.add_subplot(111)
    camera = Camera(cam_fig)
    for file in files:
        x_axis = []
        v_cin = []
        v_cout = []
        v_in = []
        with open(directory + dir + test + file + ".csv",
                  'r') as data:  # Get Data for the first Voltage
            reader = csv.reader(data)
            next(reader)
            next(reader)
            for row in reader:
                x_axis = np.append(
                    x_axis,
                    float(row[0]) + div_delay[files.index(file)])
                if type.startswith("_no") is not True:
                    v_in = np.append(v_in, float(row[1]))
                    v_cin = np.append(v_cin, float(row[2]))
                    v_cout = np.append(v_cout, float(row[3]))
                else:
                    v_cin = np.append(v_cin, float(row[1]))
                    v_cout = np.append(v_cout, float(row[2]))
        if type.startswith("_no") is not True:
            vin = ax2.errorbar(x_axis,
                               v_in,
                               yerr=0.0,
                               color="yellow",
                               fmt='-',
                               markerfacecolor='white',
                               ms=3,
                               label="Power supply voltage  $U_S$ [V]")
        vcin = ax2.errorbar(x_axis,
                            v_cin,
                            yerr=0.0,
                            color="green",
                            fmt='-',
                            markerfacecolor='white',
                            ms=3,
                            label="supply voltage to the DC/DC module")
        vcout = ax2.errorbar(x_axis,
                             v_cout,
                             yerr=0.0,
                             color="blue",
                             fmt='-',
                             markerfacecolor='white',
                             ms=3,
                             label="Output Voltage from the DC/DC module")
        ax2.text(0.85,
                 0.35,
                 file + "V",
                 fontsize=10,
                 horizontalalignment='right',
                 verticalalignment='top',
                 transform=ax.transAxes,
                 bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.2))
        camera.snap()
    # ax2.ticklabel_format(useOffset=False)
    if type.startswith("_no") is not True:
        ax2.legend([vin, vcin, vcout], [
            "Power supply voltage  $U_S$ [V]",
            "supply voltage to the DC/DC module",
            "Output Voltage from the DC/DC module"
        ],
                   loc="upper left",
                   prop={'size': 8})
    else:
        ax2.legend([vcin, vcout], [
            "supply voltage to the DC/DC module",
            "Output Voltage from the DC/DC module"
        ],
                   loc="upper left",
                   prop={'size': 8})
    ax2.set_ylabel("Voltage [V]")
    ax2.autoscale(enable=True, axis='x', tight=None)
    ax2.set_title(title, fontsize=12)
    # ax2.set_ylim([-5,25])
    # ax2.set_xlim([-0.04,0])
    # ax2.get_xaxis().set_ticks([])
    ax2.grid(True)
    ax2.set_xlabel("time $t$ [ms]")
    ax2.set_ylabel(r'Voltage [V]')
    cam_fig.figimage(im, 5, 5, zorder=1, alpha=0.08, resize=False)
    animation = camera.animate()
    animation.save(directory + dir + test + "00_Animation" + type + ".gif",
                   writer='imagemagick',
                   fps=1)
Пример #20
0
import matplotlib
import pandas as pd
from matplotlib import pyplot as plt
from celluloid import Camera

#load irrigation dataset
irrigated_land = pd.read_csv('datasets/land_under_Irrigation.csv')
#print(irrigated_land.head())
# animation
fig = plt.figure(figsize=(80, 40))
camera = Camera(fig)  # bind camera object to matplotlib figure
for index, row in irrigated_land.iterrows():
    t = plt.bar(row['OBJECTID'], row['Total_Count'])
    plt.legend(t, [f'County {row["County"]}'])
    plt.title("Total acres of Land under Irrigation per County")
    camera.snap()

animation = camera.animate()
animation.save('celluloid_legends.gif', writer='imagemagick')
Пример #21
0
    rectangle = plt.Rectangle((coords[name][0], coords[name][1]),
                              coords[name][2],
                              coords[name][3],
                              fc=node_color,
                              alpha=0.36,
                              edgecolor='black')
    return rectangle


fig = plt.figure()
fig.set_size_inches(26, 19)
ax = plt.axes(xlim=(0, 76), ylim=(0, 50))
plt.axis('off')
plt.tight_layout()

camera = Camera(fig)

for key, value in coords.items():
    rectangle = draw_node(key, years[0], data)
    plt.gca().add_patch(rectangle)

    plt.text(value[0] + value[2] / 2.0,
             value[1] + 2.6,
             names[key],
             fontsize=18,
             horizontalalignment='center')

    if key in data.index:
        plt.text(value[0] + value[2] / 2.0,
                 value[1] + 1,
                 data.loc[key][years[0]],
Пример #22
0
    weights = min_weights
    print("Minimim test error: ", min_test_error)
    train_set_error_history = np.append(train_set_error_history,
                                        min_train_error)
    test_set_error_history = np.append(test_set_error_history, min_test_error)

################################################

# Plot results
fig, axes = plt.subplots()
x = []
train_y = []
test_y = []
plt.grid(True)
length = len(epochs_history)
camera = Camera(fig)

for i in range(length):
    x = np.append(x, epochs_history[i])
    train_y = np.append(train_y, [train_set_error_history[i]])
    plt.plot(x, train_y, 'b')
    test_y = np.append(test_y, [test_set_error_history[i]])
    plt.plot(x, test_y, 'r')
    camera.snap()
handles = [
    Line2D([0], [0], color='blue', label='Train error'),
    Line2D(range(1), range(1), color='red', label='Test error')
]
plt.legend(handles=handles, loc='upper right')
plt.title("Test and Train errors ( Test size = %i" % test_size +
          "; Train Size = %i" % train_size + " )")
Пример #23
0
 def __init__(self, title):
     self.title = title
     self.fig = plt.figure()
     self.camera = Camera(self.fig)
# Save the figure
Name3 = input('Give the name to the Q-h graph file:')
fig3.savefig('..\\report\\{}.jpg'.format(Name3))

# =============================================================================
# # Saving Result Matrices to TXT file Part
# =============================================================================
np.savetxt('..\\report\Matrix_h.txt', Mtrx_h, fmt='%1.1e')
np.savetxt('..\\report\Matrix_Q.txt', Mtrx_Q, fmt='%1.1e')

# Do the animations
from celluloid import Camera

# Animate both at one
fig3 = plt.figure(figsize=(18, 14))
Camera3 = Camera(fig3)
Camera4 = Camera(fig3)
plt.subplot(2, 1, 1)
plt.grid()
#plt.xlabel('Chainage (m)', size=15)
plt.ylabel('Water Depth (m)', size=15)
plt.xticks(size=12)
plt.yticks(size=12)
plt.title('1D Sain Venant Equation Solution by Preismmann Scheme',
          size=30,
          color='red')

for i in np.arange(1, N, 1):
    try:
        h_plot = Mtrx_h[i, :]
        plt.plot(x1, h_plot, label='T={0:.0f} sec'.format(i * Del_t))
Пример #25
0
nframes = 5305
df_likelihood = np.empty((len(bodyparts2plot), nframes))
df_x = np.empty((len(bodyparts2plot), nframes))
df_y = np.empty((len(bodyparts2plot), nframes))

for bpindex, bp in enumerate(bodyparts2plot):
    df_likelihood[bpindex, :] = data[DLCscorer, bp, 'likelihood'].values
    df_x[bpindex, :] = data[
        DLCscorer, bp,
        'x'].values  # an array of 26 arrays with 5305 elements each
    df_y[bpindex, :] = data[
        DLCscorer, bp,
        'y'].values  # an array of 26 arrays with 5305 elements each

colors = cm.rainbow(np.linspace(0, 1, len(bodyparts2plot)))
camera = Camera(plt.figure())

for frame in range(0, nframes):
    print("Processing Frame", frame)
    plt.scatter(df_x[:, frame], df_y[:, frame], c=colors,
                s=100)  # how to handle low confidence

    plt.ylim(
        720, 0
    )  # https://stackoverflow.com/questions/2051744/reverse-y-axis-in-pyplot

    m_midline = plot_regression(22, 26, frame)
    m_c1_l = plot_regression(0, 5, frame)
    m_c1_r = plot_regression(5, 10, frame)
    angle_l = np.degrees(
        np.arctan((m_midline - m_c1_l) / (1 + m_midline * m_c1_l)))
 n_pop = 100  # tamaño de la población
 n_elite = 3  # Los n-elite individuos más aptos pasarán directamente a la siguiente generación
 # Probabilidad de que se produzca una mutación para cada uno de los genes
 # del individuo.
 tasaMutacion = 0.01
 n_generaciones = 100  # Número de generaciones que se van a generar
 k = 10  # Número de pretendientes que se enfrentarán en torneo para reproducirse. Si k=0, entonces se seleccionan de forma proporcional al Fitness.
 df_ciudades = GA.generarDataFrameCiudades(lista_ciudades)
 ciudades = GA.llamarCiudades(lista_ciudades, df_ciudades)
 print("\n Se comienza a generar la población\n", end='\r')
 df = GA.IniciarPoblacion(n_pop, ciudades)
 i = 1
 print("\n Se ha generado la población parental con éxito. \n", end='\r')
 # generamos figura para la animación
 fig, ax = plt.subplots(figsize=(9, 6))
 camera = Camera(fig)
 df = df.reset_index(drop=True)
 mejorRuta = df.iloc[0]
 generacionMejorRuta = i
 while i <= n_generaciones:
     df = GA.cruzamientoPoblacion(df, df_ciudades, n_elite, tasaMutacion, k)
     df = df.reset_index(drop=True)
     nuevaRuta = df.iloc[0]
     if 1 / mejorRuta['Fitness'] > 1 / nuevaRuta['Fitness']:
         mejorRuta = nuevaRuta
         generacionMejorRuta = i
     print("Generación F{0} creada con éxito.".format(i), end='\r')
     fotograma(df)
     i += 1
 print("\n")
 print("Se ha terminado el proceso\n")
Пример #27
0
class Visualizer:
    def __init__(self, board, player, visualization_speed):
        self.board = board
        self.player = player
        self.camera = Camera(plt.figure())
        self.G, self.pos = self.init_board_visualizer()
        self.speed = visualization_speed

    def init_board_visualizer(self):
        G = nx.Graph()
        for current_cell in self.board.get_cells():
            x_pos = current_cell.get_location()[
                0]  # Positive x-pos to not horizontally flip graph
            y_pos = -current_cell.get_location()[
                1]  # Negative y-pos to vertically flip graph
            G.add_node(current_cell, pos=(x_pos, y_pos))
            for neighbor_cell in current_cell.get_neighbors():
                G.add_edge(current_cell, neighbor_cell
                           )  # edges can be added before nodes (networkx docs)
        return G, nx.get_node_attributes(G, 'pos')

    def draw_pegs_and_holes(self):
        nx.draw_networkx_nodes(self.G,
                               self.pos,
                               nodelist=self.board.get_holes(),
                               node_color='white',
                               linewidths=2,
                               edgecolors='black')
        nx.draw_networkx_nodes(self.G,
                               self.pos,
                               nodelist=self.board.get_pegs(),
                               node_color='black',
                               linewidths=2,
                               edgecolors="black")
        nx.draw_networkx_edges(self.G, self.pos)

    def draw_state_transition(self, action):
        self.draw_pegs_and_holes()
        if len(action) == 3:
            nx.draw_networkx_nodes(self.G,
                                   self.pos,
                                   nodelist=[action[0]],
                                   node_color='black',
                                   linewidths=2,
                                   edgecolors='green')
            nx.draw_networkx_nodes(self.G,
                                   self.pos,
                                   nodelist=[action[1]],
                                   node_color='black',
                                   linewidths=2,
                                   edgecolors='red')
            nx.draw_networkx_nodes(self.G,
                                   self.pos,
                                   nodelist=[action[2]],
                                   node_color='white',
                                   linewidths=2,
                                   edgecolors='yellow')
            nx.draw_networkx_edges(self.G, self.pos)
        self.camera.snap()  # Creates snapshot of transition

    def draw_board(self):
        self.draw_pegs_and_holes()
        self.camera.snap()

    def animate_visualiser(self):
        animation = self.camera.animate(interval=self.speed, repeat=False)
        animation.save('images/animation.gif')
        plt.show(block=False)
        plt.close()

    def visualize_episode(self, current_episode_saps):
        """ Visualizes the performed actions and resulting states in the given episode"""
        for state_action_pair in current_episode_saps:
            self.draw_state_transition(state_action_pair[1])
            self.player.perform_action(state_action_pair[1])
            self.draw_board()
        self.animate_visualiser()
Пример #28
0
#!/usr/bin/env python
"""Sinusoid animation."""

import numpy as np
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from celluloid import Camera

fig, axes = plt.subplots(2)
camera = Camera(fig)
t = np.linspace(0, 2 * np.pi, 128, endpoint=False)
for i in t:
    axes[0].plot(t, np.sin(t + i), color='blue')
    axes[1].plot(t, np.sin(t - i), color='blue')
    camera.snap()
animation = camera.animate(interval=50, blit=True)
animation.save(
    'sines.mp4',
    dpi=100,
    savefig_kwargs={
        'frameon': False,
        'pad_inches': 'tight'
    }
)
Пример #29
0
import math
import random
import time
from matplotlib import pyplot as plt
from celluloid import Camera
from Point import Point
from Vector import Vector

# Graham's algorithm + animation

fig = plt.figure()
camera = Camera(fig)


def init_points():
    points = []
    xs = [random.randint(0, 10) for _ in range(10)]
    ys = [random.randint(0, 10) for _ in range(10)]
    for i in range(len(xs)):
        x = Point(xs[i], ys[i])
        points.append(x)
    return points


def get_min_y(points: list):
    min_y = points[0].y
    for i in range(len(points)):
        if points[i].y < min_y:
            min_y = points[i].y
    return min_y

# Plot original grid in x-y space
x_axis_start = -5
x_axis_end = 5
x_axis_samples = 11
y_axis_start = -5
y_axis_end = 5
y_axis_samples = 11
xy_grid = generate_original_grid(x_axis_start, x_axis_end, x_axis_samples, y_axis_start, y_axis_end, y_axis_samples)
points_colors = list(map(get_colors, xy_grid[0], xy_grid[1]))
plot_original_grid(xy_grid, points_colors)

# Plot animated transformed grid in u-v space
fig = plt.figure(figsize=(5, 5), facecolor="w")
camera = Camera(fig)
uv_grid = np.column_stack([[2, 1], [-1, 1]])
transform = generate_stepwise_transform(uv_grid, xy_grid)
plot_transformed_grids(transform, points_colors, "Transformed grid in u-v space")
animate = camera.animate()
animate.save("uvspace.gif")
HTML(animate.to_html5_video())

# Plot animated 60 degree clockwise rotation grid
fig = plt.figure(figsize=(5, 5), facecolor="w")
camera = Camera(fig)
theta = np.pi/3
rotation_60 = np.column_stack([[np.cos(theta), np.sin(theta)], [-np.sin(theta), np.cos(theta)]])
transform = generate_stepwise_transform(rotation_60, xy_grid)
plot_transformed_grids(transform, points_colors, "Transformed grid\n60 degree clockwise rotation")
animate = camera.animate()