Exemplo n.º 1
0
def make_frame_mpl(t):

    global thresh, ax0, ax1

    i = int(t)

    if i < thresh:

        line.set_data(x[0:i], y[tStart:tStart + i])
        patch.set_data(x[0:i], z[tStart:tStart + i])
        #ax1.fill_between(x[i-1:i], 0, z[i-1:i],color="blue",alpha=0.5);
        #        for X, p in zip(x[0:i],patch) :
        #            if X == 1:
        #                p.set_height(1);
        last_frame = mplfig_to_npimage(fig)
        return last_frame

    else:

        delta = i - thresh

        ax0.set_xlim(tStart + delta, tStart + i)
        ax1.set_xlim(tStart + delta, tStart + i)
        line.set_data(x[delta:i], y[tStart + delta:tStart + i])
        patch.set_data(x[delta:i], z[tStart + delta:tStart + i])
        #ax1.fill_between(x[i-1:i], 0, z[i-1:i],color="blue",alpha=0.5);
        #        for X, p in zip(x[delta:i],patch) :
        #            if X == 1:
        #                p.set_height(1);
        last_frame = mplfig_to_npimage(fig)
        return last_frame
Exemplo n.º 2
0
    def make_frame_mpl(t):
        i = int(t)
        if i < kwargs["video_photometry"]["display_threshold"]*kwargs["video_photometry"]["plot_acceleration"]:
            try:
                behavior_plot.set_data(x_data[0:i], y_data[0][0:i])
                df_plot.set_data(x_data[0:i], y_data[1][0:i])
            except :
                print("Oups a problem occured")
    
            last_frame = mplfig_to_npimage(live_figure)
            return last_frame
        else:
            delta = (i/kwargs["video_photometry"]["plot_acceleration"]) - kwargs["video_photometry"]["display_threshold"]
        
            live_ax0.set_xlim(x_data[0]+delta, x_data[0]+(i/kwargs["video_photometry"]["plot_acceleration"]))
            live_ax1.set_xlim(x_data[0]+delta, x_data[0]+(i/kwargs["video_photometry"]["plot_acceleration"]))
            
            try:
                behavior_plot.set_data(x_data[0:i], y_data[0][0:i])
                df_plot.set_data(x_data[0:i], y_data[1][0:i])
            except:
                print("Oups a problem occured")

            last_frame = mplfig_to_npimage(live_figure)
            return last_frame
Exemplo n.º 3
0
 def make_frame_mpl(t):
     i = int(t)
     if i < thresh*plotAcceleration:
         try:
             cotton_graph.set_data(x[0:i], yData[0][0:i])
             # cotton_graph.fill_between(x[0:i], 0, y0[0:i], color="blue", alpha=0.8)
             # eventGraph.set_data(x[0:i], y1)
             # calciumGraph.set_data(x[0:i], y2[0:i])
             df_graph.set_data(x[0:i], yData[3][0:i])
         except:
             print("Oups a problem occured")
 
         last_frame = mplfig_to_npimage(live_fig)
         return last_frame
     else:
         delta = (i/plotAcceleration) - thresh
     
         liveAx0.set_xlim(x[0]+delta, x[0]+(i/plotAcceleration))
         # liveAx1.set_xlim(x[0]+delta, x[0]+(i/plotAcceleration))
         # liveAx2.set_xlim(x[0]+delta, x[0]+(i/plotAcceleration))
         live_ax3.set_xlim(x[0]+delta, x[0]+(i/plotAcceleration))
         try:
             cotton_graph.set_data(x[0:i], yData[0][0:i])
             # cotton_graph.fill_between(x[0:i], 0, y0[0:i], color="blue", alpha=0.8)
             # eventGraph.set_data(x[0:i], y1[0:i])
             # calciumGraph.set_data(x[0:i], y2[0:i])
             df_graph.set_data(x[0:i], yData[3][0:i])
         except:
             print("Oups a problem occured")
 
         last_frame = mplfig_to_npimage(live_fig)
         return last_frame
Exemplo n.º 4
0
def displayBarChart():
    plt.cla()
    h, w, _ = frame.shape
    index = np.arange(3)
    labels = df_Classes['ClassAr']

    # display only to 3

    PredClasses = model.predict(img64Array).reshape(32)
    tempTop3Index = np.argpartition(-PredClasses, 3)
    Top3Index = tempTop3Index[:3]

    tempTop3Values = np.partition(-PredClasses, 3)
    Top3Values = -tempTop3Values[:3]

    for lbl in labels:
        lbl = get_display(arabic_reshaper.reshape(lbl))

    # fig, ax = plt.subplots(figsize=(3, 2), facecolor='w')
    ax.bar(index, Top3Values)
    ax.set_ylabel('Score')
    ax.set_title('Prediction Prop')
    ax.set_xticks(index)
    ax.set_xticklabels(labels)
    plt.tight_layout()

    graphRGB = mplfig_to_npimage(fig)
    gh, gw, _ = graphRGB.shape

    # frame[:gh, w - gw:, :] = mplfig_to_npimage(fig)
    return mplfig_to_npimage(fig)
Exemplo n.º 5
0
    def _make_path_frame(self, t):
        self._timeData.append(t)
        try:
            pathTile = self._pathIterator.__next__()
        except StopIteration:
            return mplfig_to_npimage(self._vfig)

        self._frameupdate(pathTile, self._PATH_TILE)
        return mplfig_to_npimage(self._vfig)
Exemplo n.º 6
0
def make_frame_for_heatmap(t, maps, cmap, fps, fig, ax, global_vmax): 
    ind = np.floor(t*fps).astype(np.int)
    if ind>=len(maps):
        return bindings.mplfig_to_npimage(fig) 
    local_vmax = maps[ind].max()
    
    ax.clear()
    ax.imshow(maps[ind], cmap=cmap, vmax=max(local_vmax, 0.5*global_vmax))
    ax.axis('off')
    return bindings.mplfig_to_npimage(fig)
Exemplo n.º 7
0
    def make_frame(t):
        i = min(int(np.round(t / meshsize)), len(r_history) - 1)
        ax = axs[0]
        ax.clear()
        color = "blue"
        x_ticks = np.arange(1, len(conv) + 1)
        ax.set_ylim([0, 1])
        ax.set_xlim([0, len(conv)])
        ax.plot(x_ticks[:(i + 1)], conv[:(i + 1)], "o",
                color=color)  # , label=r"{} $\mu = {:.2f}, i = {}$".format(title, factor, num_sweeps))
        if i >= num_sweeps:
            ax.scatter([num_sweeps], [conv[num_sweeps - 1]], 120, facecolors='none', edgecolors=color)
        ax.set_ylabel("Residual Reduction Factor")
        ax.set_xlabel("Sweep #")
        ax.grid(True)

        ax = axs[1]
        ax.clear()
        ax.plot(x_history[i][:, 0])
        x_init = x_history[0][:, 0]
        ax.set_ylim([min(x_init) - 0.01, max(x_init) + 0.01])
        ax.set_title("Error after {} sweeps".format(i))

        ax = axs[2]
        ax.clear()
        ax.plot(r_history[i][:, 0])
        r_init = r_history[0][:, 0]
        ax.set_ylim([min(r_init) - 0.01, max(r_init) + 0.01])
        ax.set_title("Residual after {} sweeps".format(i))

        return mplfig_to_npimage(fig)
Exemplo n.º 8
0
def make_frame(t):
    top_nucleotide_index = t * graphic_record.sequence_length / duration
    graphic_record.top_position = top_nucleotide_index
    ax, _ = graphic_record.plot(figure_width=8)
    np_image = mplfig_to_npimage(ax.figure)
    plt.close(ax.figure)
    return np_image
Exemplo n.º 9
0
    def make_frame(t):
        """Return an image of the frame for time t"""
        fig = plt.gcf()
        ax = plt.gca()
        f_idx = int(t * fps)
        start = hop * f_idx
        end = start + window
        to_plot = pianoroll[start:end].T / 128.
        extent = (start, end - 1, 0, 127)
        ax.imshow(to_plot, cmap=cmap, aspect='auto', vmin=0, vmax=1,
                  origin='lower', interpolation='none', extent=extent)

        if xtick == 'beat':
            next_major_idx = beat_resolution - start % beat_resolution
            if start % beat_resolution < beat_resolution//2:
                next_minor_idx = beat_resolution//2 - start % beat_resolution
            else:
                next_minor_idx = (beat_resolution//2 - start % beat_resolution
                                  + beat_resolution)
            xticks_major = np.arange(next_major_idx, window, beat_resolution)
            xticks_minor = np.arange(next_minor_idx, window, beat_resolution)
            if end % beat_resolution < beat_resolution//2:
                last_minor_idx = beat_resolution//2 - end % beat_resolution
            else:
                last_minor_idx = (beat_resolution//2 - end % beat_resolution
                                  + beat_resolution)
            xtick_labels = np.arange((start + next_minor_idx)//beat_resolution,
                                     (end + last_minor_idx)//beat_resolution)
            ax.set_xticks(xticks_major)
            ax.set_xticklabels('')
            ax.set_xticks(xticks_minor, minor=True)
            ax.set_xticklabels(xtick_labels, minor=True)
            ax.tick_params(axis='x', which='minor', width=0)

        return mplfig_to_npimage(fig)
Exemplo n.º 10
0
def make_frame(t):
    axes.clear()

    #wind=np.array([0.1,0.1])
    wind=np.zeros(2)
    saving=np.zeros((N,2))
# ------------------------UPDATING ACCELERATION---------------------------------------
    for i in range(N):
        aux=cohesion(state,N,i)
        #aux=np.zeros(2)
        aux2=exclusion(state,N,i)
        #aux2=np.zeros(2)
        aux3=aligment(state,N,i)
        #aux3=np.zeros(2)
        saving[i][0]=aux[0]+aux2[0]+aux3[0]+0.0*random()
        saving[i][1]=aux[1]+aux2[1]+aux3[1]+0.0*random()
    #UPDATING
    for i in range(N):
        state[i][5]=saving[i][0]
        state[i][6]=saving[i][1]
#---------------------------------------------------------------------------------

    #Updating VELOCITIES
    for i in range(N):
        aux=updating_velocity(state,N,i)
        state[i][3]=aux[0]+wind[0]
        state[i][4]=aux[1]+wind[1]
        aux4=cruise_v(state,i)
        state[i][3]=state[i][3]+aux4[0]
        state[i][4]=state[i][4]+aux4[1]


    #Updating positions
    for i in range(N):
        aux=updating_position(state,N,i)
        state[i][1]=aux[0]
        if ((state[i][1] >= float(L)) or (state[i][1] <= float(-L))): #BOUNDARY CONDITIONS
            state[i][3]=-state[i][3]
            state[i][1]=state[i][1]+2.0*state[i][3]
        state[i][2]=aux[1]
        if ((state[i][2] >= float(L)) or (state[i][2] <= float(-L))):
            state[i][4]=-state[i][4]
            state[i][2]=state[i][2]+2.0*state[i][4]

    #SAVE DATE ON FILE
    #if controls==True:
    #data=pd.DataFrame(state,columns="#N x1 x2 v1 v2".split())
    #data.to_csv('data.dat', header=True, index=False, sep='\t', mode='a')


    #CREATE ARROWS
    for i in range (N):
        pass
        speed=sqrt(state[i][3]**2+state[i][4]**2)
        plt.arrow(state[i][1],state[i][2],state[i][3]/speed,state[i][4]/speed,head_width=10)
    axes.axes.get_xaxis().set_ticks([]) #ERASE XTICS ON X_AXE
    axes.axes.get_yaxis().set_ticks([])
    #fig.savefig("filename.png", dpi=200) # plot canvas
    #plt.show()
    return mplfig_to_npimage(fig)
Exemplo n.º 11
0
 def make_frame_mpl(t):
     ax.clear()
     t = int(t * FPS) + 1
     one_sec_loc = loc[(t - FPS):(t + 1)].reshape(
         -1, 10, 2) if t > FPS else loc[:t].reshape(-1, 10, 2)
     draw(G, one_sec_loc)
     return mplfig_to_npimage(fig_mpl)  # 图形的RGB图像
Exemplo n.º 12
0
        def make_frame_mpl(t):

            frame = int(round(t * fps))
            imshow_heatmaps.set_data(absMotions[frame])

            return mplfig_to_npimage(
                savefig_heatmaps)  # RGB image of the figure
def draw_frame_x(df, t, fps, voronoi=False):
    fig, ax, dfFrame = footyviz.draw_frame(df, t=t, fps=fps)
    if voronoi:
        fig, ax, dfFrame = footyviz.add_voronoi_to_fig(fig, ax, dfFrame)
    image = mplfig_to_npimage(fig)
    plt.close()
    return image
Exemplo n.º 14
0
 def make_frame(t):
     ax.clear()
     ax.axis('off')
     ax.set_title(title, fontsize=16)
     self.step()
     ax.imshow(into_array(bset), cmap=cmap, animated=True)
     return (mplfig_to_npimage(fig))
Exemplo n.º 15
0
def make_frame_mpl_for_map_points(t):
    i = int(t * 40)
    n = 1. / (pdist(X_iter[..., i], 'sqeuclidean') + 1)
    Q = n / (2.0 * np.sum(n))
    Q = squareform(Q)
    im.set_data(Q)
    return mplfig_to_npimage(f)
Exemplo n.º 16
0
def make_frame(t):
    index_max = int((1.0 * t / 1000) * number_of_points)
    line.set_xdata(jupiter_traj[:index_max, 0])
    line.set_ydata(jupiter_traj[:index_max, 1])
    line.set_zdata(jupiter_traj[:index_max, 2])

    return mplfig_to_npimage(fig)
Exemplo n.º 17
0
    def animate(t):

        # Access our initialized variables from outside the function
        global last_t
        global tempgraph

        # Round time to nearest 0.5 second. This limits the number of times we
        # update the graph. Each graph update costs 10-20 seconds to draw, so by
        # limiting this, we can render the graph an order of magnitude faster
        temp_t = np.round(t * 2) / 2.0

        # Only update the graph if we are at the next 0.5 seconds
        if t > 0 and temp_t != last_t:

            # Update our timekeeping variable
            last_t = temp_t

            # Delete the previous graph, otherwise we will keep plotting over
            # the same graphs again and again
            for coll in (ax.collections):
                ax.collections.remove(coll)

            # Load only the played portion of the mp3 and plot them
            y2, sr2 = librosa.load('extracted_audio.mp3',
                                   mono=False,
                                   duration=t)
            waveplot(y2, sr=sr2, color='b', alpha=0.8)
            waveplot(y, sr=sr, color='b', alpha=0.25)

            # Update the output graph
            tempgraph = mplfig_to_npimage(fig)

        return tempgraph
Exemplo n.º 18
0
    def update(frame_number):
        # print frame_number
        x, y = gen.next()
        f.set_pos(xx + x, yy + y)
        # f.set_pos(frame_number,100)
        src = f.next()
        img.set_array(src)

        a, z = ld.get_value(copy(src))
        # print x,y, z
        img2.set_array(a)
        # print z, x, y
        xs.append(xx + x)
        ys.append(yy + y)
        line.set_data(xs, ys)
        scatter2.set_data([xx + x], [yy + y])

        ts.append(time.time() - st)
        # print z
        z /= 3716625.0
        z += 0.1 * random.random()

        pattern.set_point(z, x, y)
        zs.append(z)
        # print zs
        tvint.set_data(ts, zs)

        tcs.append(f.time_constant)
        rcs.append(f.cradius)
        tc.set_data(ts, tcs)

        rs.set_data(ts, rcs)
        return mplfig_to_npimage(fig)
Exemplo n.º 19
0
 def make_frame(t):
     ax.clear()
     ax.axis('off')
     ax.set_title(title, fontsize=16)
     self.step()
     self.plot(ax, cmap)
     return (mplfig_to_npimage(fig))
Exemplo n.º 20
0
def update(t):
    global dt,ddt,v,prob,x0,y0,n
    prova = t/(8.0*dt) + ddt          #every 4 time steps, ddt is a small increment for the int to work properly
    Npart =  1 + int((prova))
    x = np.empty([Npart])             #x-positions of the particles
    y = np.empty([Npart])             #y-positions of the particles
    for j in range(0,Npart):
        x[j] = x0[j]
        y[j] = y0[j]
        if n[j]==0:     #if it's the first time that changes
            if x[j]>=-1.1 and x[j]<-0.5:    #if it's close to 0
                randnumber=np.random.random(size=None)   #gives us a random number
                if randnumber<=prob:
                    x0[j] = x0[j] + float(v*dt)  #keeps going to the right
                    y0[j] = y0[j] - float(v*dt)  #keeps going onwards (y=0)
                    n[j]=1                       #n=1 means that it passed
                else:
                    x0[j] = x0[j] - float(v*dt)  #goes to the left
                    y0[j] = y0[j] - float(v*dt)  #goes down
                    n[j]=2                       #n=2 means particle going backwards
            else:       #still not in the separating region
                x0[j] = x0[j] + float(v*dt)  #keeps going to the right
                y0[j] = y0[j] - float(v*dt)  #keeps going onwards (y=0)
        else:
            if n[j]==1:
                x0[j] = x0[j] + float(v*dt)
                y0[j] = y0[j] - float(v*dt)
            elif n[j]==2:
                x0[j] = x0[j] - float(v*dt)  #goes to the left
                y0[j] = y0[j] - float(v*dt)  #goes  down     
    line.set_xdata(x)
    line.set_ydata(y)
    line2.set_xdata(x)
    line2.set_ydata(y)
    return mplfig_to_npimage(fig_mpl)
Exemplo n.º 21
0
def frame(n, state):

    fig = plt.figure()

    cm = plt.get_cmap('gist_rainbow')
    col = {i + 1: cm(1. * i / n) for i in range(n)}

    h = n / 2 + 0.5
    plt.xlim(0, 6)
    plt.ylim(0, h + 1.5)
    x_lab = {'a': 1, 'b': 3, 'c': 5}
    plt.xticks(())
    plt.yticks(())

    eps = 0.6 / (n - 1)
    axis = plt.gca()
    for key in state:
        l = x_lab[key]
        values = copy.deepcopy(state[key])
        plt.plot([l, l], [0.5 * len(values) + 0.07, h],
                 color='0.25',
                 linewidth=5.0)
        k = -1
        while len(values) > 0:
            k += 1
            i = max(values)
            values.remove(i)
            axis.add_patch(
                Rectangle((l - 0.8 + (n - i) * eps, k * 0.5),
                          (1 - 0.2 - (n - i) * eps) * 2,
                          0.5,
                          facecolor=col[i],
                          alpha=1))

    return mplfig_to_npimage(fig)
Exemplo n.º 22
0
def voxel(vox, color=None, f_name=None, npimage=False, view=(30, 45)):
    assert (vox.ndim == 3)

    vox = vox.transpose(2, 0, 1)
    color = color.transpose(2, 0, 1)
    if color is None or len(np.unique(color)) <= 2:
        color = 'red'
    else:
        color_map = plt.get_cmap('coolwarm')
        color = color_map(color)

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    #ax.voxels(vox, facecolors=color, edgecolor='k')
    ax.voxels(vox, edgecolor='k')
    ax.view_init(view[0], view[1])

    if npimage:
        return mplfig_to_npimage(fig)

    if f_name is not None:
        params = utils.read_params()
        f_name = os.path.join(params["DIRS"]["OUTPUT"], f_name)
        utils.make_prev_dirs(f_name)
        fig.savefig(f_name, bbox_inches='tight', dpi=2400)
        fig.clf()
        plt.close()
        return

    return fig.show()
Exemplo n.º 23
0
    def update(frame_number):
        # print frame_number
        x, y = gen.next()
        f.set_pos(xx + x, yy + y)
        # f.set_pos(frame_number,100)
        src = f.next()
        img.set_array(src)

        a, z = ld.get_value(copy(src))
        # print x,y, z
        img2.set_array(a)
        # print z, x, y
        xs.append(xx + x)
        ys.append(yy + y)
        line.set_data(xs, ys)
        scatter2.set_data([xx + x], [yy + y])

        ts.append(time.time() - st)
        # print z
        z /= 3716625.0
        z += 0.1 * random.random()

        pattern.set_point(z, x, y)
        zs.append(z)
        # print zs
        tvint.set_data(ts, zs)

        tcs.append(f.time_constant)
        rcs.append(f.cradius)
        tc.set_data(ts, tcs)

        rs.set_data(ts, rcs)
        return mplfig_to_npimage(fig)
Exemplo n.º 24
0
def get_frame(i):
    i = int(i * fps)
    plt.clf()
    ax = fig.add_subplot(111, projection='3d')
    ax.set_xlim(-mx, mx)
    ax.set_ylim(-mx, mx)
    ax.set_zlim(-mx, mx)

    if (t[-1] < 1.0):
        plt.title('t = ' + str(t[i]) + ' s', fontsize=36)
    else:
        plt.title('t = ' + time.strftime('%H:%M:%S', time.gmtime(t[i])),
                  fontsize=36)

    RR = np.reshape(R[i], (3, 3), order='F')
    points = P.dot(np.dot(Q, (RR.T))) + x[i]

    ax.add_collection3d(
        mplot3d.art3d.Poly3DCollection(points,
                                       facecolor=[0.5, 0.5, 0.5],
                                       lw=0.5,
                                       edgecolor=[0, 0, 0],
                                       alpha=0.66))

    plt.setp(ax.get_xticklabels(), visible=False)
    plt.setp(ax.get_yticklabels(), visible=False)
    plt.setp(ax.get_zticklabels(), visible=False)

    return mplfig_to_npimage(fig)
def draw_frame_x(hometeam,awayteam, t, figax=None, fps=25, 
                 team_colors=('r','b'), field_dimen = (106.0,68.0), 
                 include_player_velocities=False, PlayerMarkerSize=10, PlayerAlpha=0.7,dpi=100):
    """ draw_frame_x(hometeam,awayteam, t)
    
    Generates an image of the frame t*fps compatible with moviepy
    
    Parameters
    -----------
        hometeam: home team tracking data DataFrame. Movie will be created from all rows in the DataFrame
        awayteam: away team tracking data DataFrame. The indices *must* match those of the hometeam DataFrame
        t: time of the frame
        fig,ax: Can be used to pass in the (fig,ax) objects of a previously generated pitch. Set to (fig,ax) to use an existing figure, or None (the default) to generate a new pitch plot,
        frames_per_second: frames per second to assume when generating the movie. Default is 25.
        team_colors: Tuple containing the team colors of the home & away team. Default is 'r' (red, home team) and 'b' (blue away team)
        field_dimen: tuple containing the length and width of the pitch in meters. Default is (106,68)
        include_player_velocities: Boolean variable that determines whether player velocities are also plotted (as quivers). Default is False
        PlayerMarkerSize: size of the individual player marlers. Default is 10
        PlayerAlpha: alpha (transparency) of player markers. Defaault is 0.7
        
    Returns
    -----------
       a numpy image compatible with moviepy.VideoClip
    """

    #we have to convert t*fps to int because t is a float
    fig,ax=plot_frame(hometeam.iloc[int(t*fps)], awayteam.iloc[int(t*fps)], figax=figax, 
                           team_colors=team_colors, field_dimen = field_dimen, 
                           include_player_velocities=include_player_velocities, PlayerMarkerSize=PlayerMarkerSize, PlayerAlpha=PlayerAlpha)
    
    image = mplfig_to_npimage(fig)
    plt.close()
    return image
Exemplo n.º 26
0
def animate(t):
    myIndex = int(t*myFPS)
    myCLOBFrameInfo = myCLOBFrameInfos[myIndex]
    myFrameEndTime = myCLOBFrameInfo.endTime
    myFBAFrameInfo = myFBAFrameInfos[myIndex]
    # myFBAFrameInfo = next(i for i in myFBAFrameInfos[::-1] if i.endTime <= myFrameEndTime)
    myTimeStamp = myCLOBFrameInfo.endTime
    
    drawTradeInfoOnAxis(plt, ax0, myFrameEndTime, myCLOBFrameInfo, myCLOBFrameInfos, myTimeBucketDiff, myCLOBBidBar, myCLOBOfferBar, myFBAMatchBar,
                        myPriceMin, myPriceMax, myAxisAlpha, True, myFBAInterval) # put in fba match bar in there
    
    drawTradeInfoOnAxis(plt, ax1, myFrameEndTime, myFBAFrameInfo, myFBAFrameInfos, myTimeBucketDiff, myFBABidBar, myFBAOfferBar, myFBAMatchBar,
                        myPriceMin, myPriceMax, myAxisAlpha, False, myFBAInterval)
    
    global myFBALastEndTime
    global myIsMatched
    global myTradeTime
    global myMatchPrice
    global myMatchSize
    global myFBATrades
    
    myBidTracker.set_xdata([myTimeStamps[myIndex]])
    myBidTracker.set_ydata([myBids[myIndex]])
    myOfferTracker.set_xdata([myTimeStamps[myIndex]])
    myOfferTracker.set_ydata([myOffers[myIndex]])
    for myTrade in myCLOBFrameInfo.trades:
        ax2.plot(myTimeStamps[myIndex], myTrade.price, color = myTradeColor, marker = 'x', alpha = .4, markersize = myTrade.tradeVolume/10)
        ax2.plot(myTimeStamps[myIndex], myTrade.price, color = myTradeColor, marker = '.', alpha = .4, markersize = myTrade.tradeVolume/20)
    fig.canvas.draw()
    ax2.set_title(myTimeStamp.strftime("%d/%m/%y %H:%M:%S"), color="white", alpha = .35)    
    return(mplfig_to_npimage(fig))
Exemplo n.º 27
0
def get_fig_by_frame(categories, f_index, f_size):
    f_dpi = 100
    f_w, f_h = f_size
    fig = plt.figure(figsize=(f_w / f_dpi, f_h / f_dpi), dpi=f_dpi)
    ax = fig.add_subplot(111)
    for k in categories.keys():
        ax.plot(categories[k], label=k)
        ax.fill_between(np.arange(len(categories[k])),
                        0,
                        categories[k],
                        alpha=0.4)
    ax.legend()
    ax.set_ylabel('Area %')
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['left'].set_visible(False)
    ax.grid(axis='y')
    [t.set_visible(False) for t in ax.get_xticklines()]
    # draw vertical line
    ax.axvline(x=f_index)
    fig.tight_layout()
    imfig = mplfig_to_npimage(fig)
    plt.close(fig)
    h, w, _ = imfig.shape
    return (h, w), imfig
Exemplo n.º 28
0
def make_frame(t):
    # print(t)
    ax.clear()#清除画布
    # ax.plot(x, sinc(x**2) + np.sin(x + 2*np.pi/duration * t), lw=3)#画图
    ax.set_ylim(0, 2.5)
    ax.set_xlim(0, 2.5)
    # ax.set_facecolor('black')#设置当前画布背景颜色
    # t=0
    rot_dif = 90
    rot = max(min(100*t,90+rot_dif),rot_dif)#最小90度,最大180度
    rot = 90
    # rot = max(100*t,rot_dif)

    r = 0.3#半径
    x = 0+r*np.cos(rot*math.pi/180)
    y = 0+r*np.sin(rot*math.pi/180)

    t1 = t
    rot_dif1 = 90
    rot1 = max(min(100*t1,90+rot_dif1),rot_dif1)
    r1 = 0.1
    x1 = 0.5+r1*np.cos(rot1*math.pi/180)
    y1 = 0+r1*np.sin(rot1*math.pi/180)

    plt.text(x, y, u'test',horizontalalignment='left',verticalalignment='bottom',
             fontdict = {'size': 54, 'color': 'red','rotation':rot-rot_dif})
    # plt.text(x1, y1, u'testhello这个是测试',
    #          fontdict = {'size': 30, 'color': 'red','rotation':rot1-rot_dif1,'ha':"left",'va':"bottom"})
    return mplfig_to_npimage(fig)#生成一帧
Exemplo n.º 29
0
 def make_frame(t):
     ax.clear()
     ax.set_xlim(-x_max, x_max)
     ax.set_ylim(-y_max, y_max)
     #plt.setp([ax.get_xticklines(), ax.get_yticklines(),ax.get_xticklabels(), ax.get_yticklabels()], color='w')
     #ax.set(facecolor='silver')
     i = int(t * fps)
     for e in range(0, N_addfig, 3):
         pos = np.transpose(data[0:2, i, :])  #data[0,i,:]
         col = data[2, i, :] * data[2, i, :] + data[3, i, :] * data[3, i, :]
         #C = m.set_array(yy)
         #s=(e+1)*1.2
         s = 8
         ax.scatter(pos[:, 0],
                    pos[:, 1],
                    c=col,
                    alpha=1,
                    marker='o',
                    s=s,
                    cmap=cmap,
                    norm=norm)
         i = i + 3
     ax.set_title('Time:' + str(round((i - 1.0) / frame_time + 0.001, 2)) +
                  's')
     return mplfig_to_npimage(fig_mpl)
Exemplo n.º 30
0
def make_frame_mpl(t):
    global pdate,phour,popen,phigh,plow,pclose
    global displaynum,frame
    global xindex
    global xhour,xopen,xhigh,xlow,xclose

    ax_mpl.clear()
    ax_mpl.grid()
    update_frame()
    ax_mpl.set_title(str(pdate[frame])+" "+str(phour[frame])+" "+str(xclose[displaynum-1]))

    up   = np.array( [ True if po  < pc and po != None else False for po, pc in zip(xopen,xclose)] )
    down = np.array( [ True if po  > pc and po != None else False for po, pc in zip(xopen,xclose)] )
    side = np.array( [ True if po == pc and po != None else False for po, pc in zip(xopen,xclose)] )
    tbase= np.array( [ True if ho == 0  and ho != None else False for ho in xhour] )

    ax_mpl.set_ylim(xlow.min()*0.999,xhigh.max()*1.001)

    ax_mpl.vlines(xindex, xopen, xopen+[0.00001], color='black', linewidth=3.0, label='_nolegend_')
    if True in up:
        ax_mpl.vlines(xindex[up]  , xlow[up]   , xhigh[up]   , color='red'  , linewidth=0.6, label='_nolegend_')
        ax_mpl.vlines(xindex[up]  , xopen[up]  , xclose[up]  , color='red'  , linewidth=3.0, label='_nolegend_')
    if True in down:
        ax_mpl.vlines(xindex[down], xlow[down] , xhigh[down] , color='green', linewidth=0.6, label='_nolegend_')
        ax_mpl.vlines(xindex[down], xopen[down], xclose[down], color='green', linewidth=3.0, label='_nolegend_')
    if True in side:
        ax_mpl.vlines(xindex[side], xlow[side] , xhigh[side] , color='black', linewidth=0.6, label='_nolegend_')
        ax_mpl.vlines(xindex[side], xopen[side], xclose[side], color='black', linewidth=3.0, label='_nolegend_')

    if True in tbase:
        ax_mpl.vlines(xindex[tbase], xlow.min()*0.999, xhigh.max()*1.001 , color='black', linewidth=0.6, label='_nolegend_')

    return mplfig_to_npimage(fig_mpl) # RGB image of the figure
Exemplo n.º 31
0
def specptrogram_raw_to_image_arrays(x, y_array):
    """
    Takes one array of not changing x values and the corresponding arrays of y values and produces len(y_array) plots
    :param x: array-like, contains x values
    :param y_array: list of array-like, each entry must be of the same length as x
    :return: list of len(y_array)
    """
    # ensure same x- and y-axis for all graphs
    y_flat = np.array(y_array).flatten()
    logger.debug(f"x_shape: {np.shape(x)}, y_shape: {np.shape(y_array)}")
    xlim = (min(x), max(x))
    ylim = (max((1e-20, min(y_flat))), max(y_flat))
    xlabel = 'Frequency'
    ylabel = 'Volume'

    fig, ax = plt.subplots()
    line, = ax.plot(x, np.zeros(len(x)), ls='-')
    ax.set_xscale('log')
    ax.set_yscale('log')
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)

    images = list()
    for y in tqdm(y_array, desc='making graphs'):
        mask = np.array(y) > 0
        this_x, this_y = np.array(x)[mask], np.array(y)[mask]
        line.set_data(this_x, this_y)
        images.append(mplfig_to_npimage(fig))

    logger.debug(f'returning list of length {len(images)}')
    return images
Exemplo n.º 32
0
def make_frame(t):
    """Deklarace callback funkce zavolane pri renderingu kazdeho snimku videa."""
    axis.clear()

    global max

    # celkový počet vypočtených bodů na Lorenzově atraktoru
    n = 10 + max * 10

    ax = fig.gca(projection='3d')
    max += 1

    # rozměry grafu ve směru osy x
    ax.set_xlim(-30, 30)

    # rozměry grafu ve směru osy y
    ax.set_ylim(-30, 30)

    # rozměry grafu ve směru osy z
    ax.set_zlim(0, 50)

    draw_attractor(ax, n, 0.0, 1.0, 0.95)
    draw_attractor(ax, n, 0.0, 1.0, 1.25)

    # konverze na objekt typu "frame"
    return mplfig_to_npimage(fig)
Exemplo n.º 33
0
 def animation(self, t):
     self.update()
     self.ax.clear()
     plt.title('Gray-Scott Model')
     self.ax.imshow(self.u, interpolation='nearest', cmap=self.color)
     plt.axis('off')
     return mplfig_to_npimage(self.fig)
Exemplo n.º 34
0
def make_frame_mpl(t):
    if (t // 1) % 2:
        model.meanfield_coordinate_descent_step()
    else:
        model.resample_model()
    model.plot(update=True,draw=False)
    return mplfig_to_npimage(fig)
Exemplo n.º 35
0
def make_frame_mpl(t):
    i = int(t*40)
    n = 1. / (pdist(X_iter[..., i], "sqeuclidean") + 1)
    Q = n / (2.0 * np.sum(n))
    Q = squareform(Q)
    im.set_data(Q)
    return mplfig_to_npimage(f)
 def make_gif(u):
     newX,newY = X[u*40],Y[u*40]
     scat.set_offsets(np.transpose(np.vstack([newX,newY])))
     newx=[x[k][u*40] for k in range(120)]
     newy=[y[k][u*40] for k in range(120)]
     scatt.set_offsets(np.transpose(np.vstack([newx,newy])))
     return mplfig_to_npimage(fig_mpl)
Exemplo n.º 37
0
    def make_frame(t):
        """ returns an image of the frame at time t """
        # ... create the frame with any library
        fitness = fitness_list[int(t)]
        __sum_fit = sum(fitness)
        __mean_fit = float(__sum_fit) / float(len(fitness))
        from scipy.stats import tstd, iqr, variation, entropy
        __sd_fit = tstd(fitness)
        __iqr = iqr(fitness)
        __v = variation(fitness)
        __e = entropy(fitness)

        fig = plt.figure()
        plt.hist(fitness)  # ,bins=int(params['POPULATION_SIZE']*0.1))
        plt.title("Moving Point - Population Fitness Histogram - Generation " +
                  str(int(t)))
        plt.axis([0, 20000, 0, params['POPULATION_SIZE']])
        plt.ylabel('#Individuals')
        plt.xlabel('Fitness')
        plt.grid(True)
        __hist_text = "$\mu=" + "{0:.2f}".format(
            __mean_fit) + ",\ \sigma=" + "{0:.2f}".format(
                __sd_fit) + ",\ entropy=" + "{0:.2f}".format(
                    __e) + ",\ iqr=" + "{0:.2f}".format(__iqr) + "$"
        plt.text(1000, params['POPULATION_SIZE'] * .9, __hist_text)
        return mplfig_to_npimage(fig)  # (Height x Width x 3) Numpy array
Exemplo n.º 38
0
def update(t):
    global dt,ddt,v,prob,x0f,y0f,x0p,y0p,x0b,y0b,n
    prova = t/(8.0*dt) + ddt          #every 4 time steps, ddt is a small increment for the int to work properly
    Npart =  1 + int((prova))
    xf = np.empty([Npart])             #x-positions of the forward-particles
    yf = np.empty([Npart])             #y-positions of the forward-particles
    xb = np.empty([Npart])             #x-positions of the backward-particles
    yb = np.empty([Npart])             #y-positions of the backward-particles
    xp = np.empty([Npart])             #x-positions of the previous-particles
    yp = np.empty([Npart])             #y-positions of the previous-particles
    for j in range(0,Npart):      
        if n[j]==0:     #if it's the first time that changes
            xp[j] = x0p[j]
            yp[j] = y0p[j]
            xf[j] = -20
            yf[j] = -20
            xb[j] = -20
            yb[j] = -20   #stop moving (out of range)
            if xp[j]>=-1.1 and xp[j]<-0.5:    #if it's close to 0
                x0f[j] = x0f[j] + float(v*dt)  #keeps going to the right
                y0f[j] = y0f[j] - float(v*dt)  #keeps going onwards (y=0)
                x0b[j] = x0b[j] - float(v*dt)  #goes to the left
                y0b[j] = y0b[j] - float(v*dt)  #goes down
                x0p[j] = -20
                y0p[j] = -20  #stop moving
                n[j]=1            
            else:       #still not in the separating region
                x0f[j] = x0f[j] + float(v*dt)  #keeps going to the right
                y0f[j] = y0f[j] - float(v*dt)  #keeps going onwards (y=0)
                x0b[j] = x0b[j] + float(v*dt)  #keeps going to the right
                y0b[j] = y0b[j] - float(v*dt)  #keeps going onwards (y=0)
                x0p[j] = x0p[j] + float(v*dt)  #keeps going to the right
                y0p[j] = y0p[j] - float(v*dt)  #keeps going onwards (y=0)
        else:
            xf[j] = x0f[j]
            yf[j] = y0f[j]
            xb[j] = x0b[j]
            yb[j] = y0b[j]
            xp[j] = x0p[j]
            yp[j] = y0p[j]
            x0f[j] = x0f[j] + float(v*dt)
            y0f[j] = y0f[j] - float(v*dt)
            x0b[j] = x0b[j] - float(v*dt)  #goes to the left
            y0b[j] = y0b[j] - float(v*dt)  #goes  down
            x0p[j] = -20
            y0p[j] = -20  #stop moving
    line.set_xdata(xf)
    line.set_ydata(yf)
    line2.set_xdata(xf)
    line2.set_ydata(yf)
    line3.set_xdata(xb)
    line3.set_ydata(yb)
    line4.set_xdata(xb)
    line4.set_ydata(yb)
    line5.set_xdata(xp)
    line5.set_ydata(yp)
    line6.set_xdata(xp)
    line6.set_ydata(yp)
    return mplfig_to_npimage(fig_mpl)
Exemplo n.º 39
0
def make_frame_mpl(t):
    i = int(t*40)
    x = X_iter[..., i]
    sc.set_offsets(x)
    for j, txt in zip(range(10), txts):
        xtext, ytext = np.median(x[y_data == j, :], axis=0)
        txt.set_x(xtext)
        txt.set_y(ytext)
    return mplfig_to_npimage(f)
Exemplo n.º 40
0
 def make_frame_mpl(t):
     self.t = t
     self.update()
     fig = plt.figure(figsize=(W*inches_per_pt, H*inches_per_pt))
     fig, ax = self.plot_structure(fig=fig, ax=None, scale=scale)
     #ax.clear()
     ax.axis('off')
     #fig, ax = self.plot_structure(fig=fig, ax=ax)
     return mplfig_to_npimage(fig) # RGB image of the figure
 def make_gif(u):
     newXS,newYS = XS[u*40],YS[u*40]
     newXM,newYM = XM[u*40],YM[u*40]
     scat.set_offsets(np.transpose(np.vstack([newXS,newYS])));
     newx=[xnew[k][u*40] for k in range(120)]
     newy=[ynew[k][u*40] for k in range(120)]
     scatt.set_offsets(np.transpose(np.vstack([newx,newy])));
     scattt.set_offsets(np.transpose(np.vstack([newXM,newYM])));
     return mplfig_to_npimage(fig_mpl)
Exemplo n.º 42
0
def make_frame_mpl(t):
    # line.set_ydata( zz(2*np.pi*t/duration))  # <= Update the curve
	# im = Image.open(filenameList[int(t)])
	im = cv2.imread(filenameList[int(t)])
	print int(t)
	# original_duration = im.info['duration']
	# frames = [frame.copy() for frame in ImageSequence.Iterator(im)]    
	# plt.imshow(im)
	plt.imshow(im)
	return mplfig_to_npimage(fig_mpl) # RGB image of the figure
Exemplo n.º 43
0
    def make_frame(t):
        amp, frq = local_rfft([snd[chan]], to_frames(t), rfft_len, 'sqr', rfft,
                              lambda x: np.sqrt(rfft_len))
        frq = abs(sample_frq * frq)  # Hz
        thres = 0.01  # threshold for peak detection, fraction of max
        peaks = get_peaks(amp, frq, thres)
        fig, _ = plot_fft(frq, amp[0], title='', peaks=peaks[0])
        frame = mplfig_to_npimage(fig)
        matplotlib.pyplot.close()

        return frame
Exemplo n.º 44
0
def animate(t):
    global last_i, last_frame

    i = int(t)
    if i == last_i:
        return last_frame

    fig = figures[i]

    last_frame = mplfig_to_npimage(fig)
    return last_frame
def make_frame_mpl_S5direct(t):
    newr1=[S5direct_r1[k][t*20] for k in range(120)]
    newr2=[S5direct_r2[k][t*20] for k in range(120)]
    newR1=S5R1[t*20]
    newR2=S5R2[t*20]
    # updates the data for each frame
    # this creates Nx2 matrix
    scatr_S5direct.set_offsets(np.transpose(np.vstack([newr1,newr2])))
    scatR_S5direct.set_offsets(np.transpose(np.vstack([newR1,newR2])))
    
    return mplfig_to_npimage(fig_mpl_S5direct)
Exemplo n.º 46
0
def update_lines(t):
    plt.cla();
    frame=data[int(t*10)]
    x=frame[0]
    y=frame[1]
    u=frame[2]
    v=frame[3]
    scal=[]
    for idx in range(0,len(x)):
        scal.append((u[idx]*u[idx]+v[idx]*v[idx])*60)
    ax.scatter(x, y, s=scal,c='k',alpha=0.4)
    return mplfig_to_npimage(fig)
Exemplo n.º 47
0
    def Evolve(self, t):
        # t : seconds
        x = self.center[0]
        y = self.center[1]
        print("time:", t)
        self.mand = self.mand + numpy.rot90(self.mand)
        d = 2 * ((self.evolveRate) ** (t * 10))
        print("radius:", d)
        self.mand = self.GetMandelbort(cx=x, cy=y, d=d, border_length=200)
        self.GenerateImg(dpi=200, cx=x, cy=y, bgcolor=self.MyColor)
        return mplfig_to_npimage(fig=self.figure)

        pass
Exemplo n.º 48
0
def animate(t):
    global last_i, last_frame

    i = int(t)
    if i == last_i:
        return last_frame

    xn = x + np.sin(2 * np.pi * time[i] / 10.0)
    yn = y + np.cos(2 * np.pi * time[i] / 8.0)
    p[0].set_data(xn, yn)

    last_i = i
    last_frame = mplfig_to_npimage(fig)
    return last_frame
Exemplo n.º 49
0
        def make_frame(t):
            plt.clf()

            im = plt.contourf(data[int(t * size / duration)])
            plt.clim(-60, 40)
            plt.colorbar()

            def setvisible(self, vis):
                for c in self.collections: c.set_visible(vis)

            im.set_visible = types.MethodType(setvisible, im)
            im.axes = plt.gca()

            # plt.title(self.plot_title)
            return mplfig_to_npimage(fig)
Exemplo n.º 50
0
def make_frame(t):
    ax.clear()
    ax.axis('off')
    ax.set_title("SVC classification", fontsize=16)

    classifier = svm.SVC(gamma=2, C=1)
    # the varying weights make the points appear one after the other
    weights = np.minimum(1, np.maximum(0, t**2+10-np.arange(50)))
    classifier.fit(X, Y, sample_weight=weights)
    Z = classifier.decision_function(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)
    ax.contourf(xx, yy, Z, cmap=plt.cm.bone, alpha=0.8,
                vmin=-2.5, vmax=2.5, levels=np.linspace(-2,2,20))
    ax.scatter(X[:,0], X[:,1], c=Y, s=50*weights, cmap=plt.cm.bone)

    return mplfig_to_npimage(fig)
Exemplo n.º 51
0
 def make_tsne_frame(t):
     i = int(t*40)
     x = X_iter[..., i]
     if arg.components == 2:
         scat.set_offsets(x)
     else: # components = 3D
         # manually set private offsets bc: matplotlib is stupid
         x = np.swapaxes(x,0,1).tolist()
         scat._offsets3d = x
     ''' TODO
     for j, txt in zip(range(10), txts):
         xtext, ytext = np.median(x[y == j, :], axis=0)
         txt.set_x(xtext)
         txt.set_y(ytext)
     '''
     return mplfig_to_npimage(fig)
Exemplo n.º 52
0
    def make_frame(t):
        fig = plt.figure()
        print(t)

        # trim the number of points
        X_ = X_2d[t*diff:t*diff+diff,0]
        # X = X_[:1000] # trim down
        Y_ = X_2d[t*diff:t*diff+diff,1]
        # Y = Y_[:1000] # trim down

        fig, ax = plt.subplots()
        ax.scatter(X_,Y_,c=labels)

        fig.patch.set_visible(False)
        ax.axis('off')

        return mplfig_to_npimage(fig)
def animate(i):
    #print "Animate"
    line_index = 0
    global list_obj, list_lines, ax1 ## list_obj is all the objects which need to be updated at each time step
    for o in list_obj:
        o.update()
        for probe in o.getProbes():
            #print probe.name, "at", probe.position
            if probe.name in displayed_probes:
                list_lines[line_index].set_data(probe.time_buffer, probe.value_buffer)
            line_index+=1
        xmin, xmax = ax1.get_xlim()
        if o.t > xmax:
            ax1.set_xlim(xmin, 2*xmax)
            ax1.figure.canvas.draw()
    NF_mp.set_data(xrange(0,width), NF.V)
    NF_firing.set_data(xrange(0,width), NF.GainFunction(NF.V))
    if RECORD_VIDEO:
        return mplfig_to_npimage(fig) 
    else:
        return list_lines
Exemplo n.º 54
0
    def make_frame(t):
        fig = plt.figure()
        print(t)

        # get colours from hsl values 
        # colour = colorsys.hls_to_rgb(360*labels[t]/10, 0.5, 0.5)
        my_labels = np.genfromtxt('./csv_txt_tests/mnist_ys.csv', delimiter=',')
        print "label shape", my_labels.shape

        # trim the labels
        colour = my_labels[:1000,0]

        # trim the number of points
        X_ = X_2d[t*10000:t*10000+10000,0]
        X = X_[:1000]
        Y_ = X_2d[t*10000:t*10000+10000,1]
        Y = Y_[:1000]

        plt.scatter(X,Y,c=colour)

        return mplfig_to_npimage(fig)
Exemplo n.º 55
0
def make_frame_mpl(t):
    model.resample_model()
    model.plot(fig=fig,update=True,draw=False,plot_slice=plot_slice)
    plt.tight_layout()
    return mplfig_to_npimage(fig)
Exemplo n.º 56
0
def make_frame_mpl(t):
    # Update data
    img.set_data(im_stack[fps * t + 1, :, :])
    ax.set_title('t = {:06.3f} (ms)'.format(1e3 * t * fps * dT * cal_iter))
    return mplfig_to_npimage(fig_mpl)  # RGB image of the figure
Exemplo n.º 57
0
def make_frame_mpl(t):
    traits = model_run.next()
    im.set_data(traits.reshape(10, 10))
    for i, trait in enumerate(traits):
        ax.texts[i].set_text("%s" % trait)
    return mplfig_to_npimage(f)
Exemplo n.º 58
0
def make_frame_mpl(t):
    model.resample_model()
    model.plot_stateseq(model.states_list[0],ax=ax,update=True,draw=False,plot_slice=plot_slice)
    return mplfig_to_npimage(fig)
Exemplo n.º 59
0
 def video_fn(t):
     """make one frame of video"""
     t += bbox.start_time
     fn = getattr(profile, plot_type)
     fig = fn(t=t, bbox=bbox)
     return mplfig_to_npimage(fig)
Exemplo n.º 60
0
def make_frame_mpl(t):
    line.set_ydata( zz(2*np.pi*t/duration))  # <= Update the curve
    return mplfig_to_npimage(fig_mpl) # RGB image of the figure