예제 #1
0
 def color(self, nslc_id_str):
     if not isinstance(nslc_id_str, str):
         try:
             nslc_id_str = '.'.join(nslc_id_str)
         except:
             raise
     try:
         return cm.gist_rainbow(self._color_dict[nslc_id_str])
     except AttributeError:
         self.set_color()
         return cm.gist_rainbow(self._color_dict[nslc_id_str])
 def color(self, nslc_id_str):
     if not isinstance(nslc_id_str, str):
         try:
             nslc_id_str = '.'.join(nslc_id_str)
         except:
             raise
     try:
         return cm.gist_rainbow(self._color_dict[nslc_id_str])
     except AttributeError:
         self.set_color()
         return cm.gist_rainbow(self._color_dict[nslc_id_str])
예제 #3
0
def vis_voxels(cfg, voxels, rgb=None, vis_axis=0):
    # TODO move to the other module and do import in the module
    import open3d
    threshold = cfg.vis_threshold
    xyz, occupancies = voxel2pc(voxels, threshold)

    # Pass xyz to Open3D.PointCloud and visualize
    pcd = open3d.PointCloud()
    pcd.points = open3d.Vector3dVector(xyz)

    if rgb is not None:
        rgbs = np.reshape(rgb, (-1, 3))

        colors = rgbs[occupancies, :]
        colors = np.clip(colors, 0.0, 1.0)

        pcd.colors = open3d.Vector3dVector(colors)
    else:
        voxels = np.squeeze(voxels)
        sh = voxels.shape
        rgb = np.zeros((sh[0], sh[1], sh[2], 3), dtype=np.float32)
        for k in range(sh[0]):
            color = cm.gist_rainbow(float(k) / (sh[0] - 1))[:3]
            if vis_axis == 0:
                rgb[k, :, :, :] = color
            elif vis_axis == 1:
                rgb[:, k, :, :] = color
            elif vis_axis == 2:
                rgb[:, :, k, :] = color
            else:
                assert (False)

        rgbs = np.reshape(rgb, (-1, 3))
        colors = rgbs[occupancies, :]
        pcd.colors = open3d.Vector3dVector(colors)

    if False:
        axis_vis = xyz[:, 0]
        min_ = np.min(axis_vis)
        max_ = np.max(axis_vis)
        colors = cm.gist_rainbow((axis_vis - min_) / (max_ - min_))[:, 0:3]
        pcd.colors = open3d.Vector3dVector(colors)

    # open3d.write_point_cloud("sync.ply", pcd)

    # Load saved point cloud and transform it into NumPy array
    # pcd_load = open3d.read_point_cloud("sync.ply")
    # xyz_load = np.asarray(pcd_load.points)
    # print(xyz_load)

    # visualization
    open3d.draw_geometries([pcd])
예제 #4
0
def main(argv):
    
    plt.figure(figsize=plt.figaspect(0.55))
    xd=np.linspace(0,4000,100)
    td = getTC(xd)
    plt1, = plt.plot(td,xd,'b--',lw=3)
    plt.grid()
    plt.xlabel(r'$\theta_D \rm[deg]$',fontsize=20)
    plt.ylabel(r'$x_d \rm[m]$',fontsize=20)
    
    plt.text(91.55, 1200, 'Zona permitida',
        bbox={'facecolor':'white', 'alpha':0.5, 'pad':10})
    
    plt.legend([plt1],["$x_d^{CUT}$"],loc=2)
    
    plt.savefig("thetaDCut.pdf",format="pdf")
    
    
    thD = np.arange(90.1,95,0.00001)
    cThD = np.cos(thD*kdeg2rad)
    #Xd = np.arange(100,1700,200)
    Xd = np.arange(100,3700,400)
    
    plt.figure(figsize=plt.figaspect(0.55))
    plots = []
    xds = []
    for x in Xd:
        cThE = np.sqrt((R**2 - ((R+x)**2) * (1-cThD**2))/R**2)
        auxP, = plt.plot(thD,(x*(R*cThE-(R+x)*cThD))/((R**2 - (R+x)**2)*cThD),c=cm.gist_rainbow(float(x-5)/Xd[-1],1),lw=2.5)
        plots.append(auxP)
        xds.append(str(x))
    plt.grid()
    plt.legend(plots,xds,loc=4,title=r'$\bf{x_d \rm [m]}$')
    plt.xlabel(r'$\theta_D \rm[deg]$',fontsize=20)
    plt.ylabel(r'$\frac{l_{plano}}{l_{curvo}}$',fontsize=20)
    plt.savefig("lPlane_lCurve.pdf",format="pdf")
    
    
    plt.figure(figsize=plt.figaspect(0.55))
    plots = []
    xds = []
    for x in Xd:
        cThE = -np.sqrt((R**2 - ((R+x)**2) * (1-cThD**2))/R**2)
        thE = np.arccos(cThE)*krad2deg
        auxP, = plt.plot(thD,thE,lw=2.5,c=cm.gist_rainbow(float(x-5)/Xd[-1],1))
        plots.append(auxP)
        xds.append(str(x))
    plt.grid()
    plt.legend(plots,xds,loc=4,title=r'$\bf{x_d \rm [m]}$')
    plt.xlabel(r'$\theta_D \rm[deg]$',fontsize=20)
    plt.ylabel(r'$\theta_E \rm[deg]$',fontsize=20)
    plt.savefig("thE_thD.pdf",format="pdf")
예제 #5
0
def plotprof(id=('A1', 'A2'), name='0'):
    print(name, ':', id)
    color = [cm.gist_rainbow(i) for i in np.linspace(1.0, 0.0, 9)]
    func, remax = make_funcs(id)
    fig = pyplot.figure(figsize=(5, 5))
    fig.subplots_adjust(bottom=0.15,
                        top=0.95,
                        left=0.15,
                        right=0.95,
                        hspace=0.0,
                        wspace=0.0)
    rmax = remax * 3.0001
    r = np.arange(rmax / 10000.0, rmax, rmax / 100.0)
    for i, iid in enumerate(id):
        print(i)
        for j in range(len(func[i])):
            for k, band in enumerate(bands):
                if k == 0:
                    label = "%s\_%i" % (iid, j)
                else:
                    label = ""
                pyplot.plot(r,
                            func[i][j][k](r),
                            linestyle=linestyle[i],
                            marker=None,
                            color=color[k],
                            label=label)
    pyplot.legend(loc='upper right', numpoints=1, prop={'size': 16})
    pyplot.xlabel('$r_{\mathrm{e}}$')
    pyplot.ylabel('$\mu$')
    #fig.gca().invert_yaxis()
    pyplot.xlim(0.0, rmax)
    pyplot.ylim(26, 16)
    fig.savefig('plots/profiles_%s.pdf' % name)
 def plotGaussian(self, data, **kwargs):
     clusters = self.clusters
     colors = iter(cm.gist_rainbow(numpy.linspace(0, 1, len(clusters))))
     centroids = self.centroids
     assignments = self.assignments
     covs = self.covs
     plt.subplot(121)
     ax = plt.gca()
     plt.xlabel('X1')
     plt.ylabel('X2')
     plt.title('Gaussian Mixture Model With K = '+str(clusters.shape[0]))
     for c in range(clusters.shape[0]):
         color = next(colors)
         eigvals, eigvecs = lg.eigh(covs[c])
         eigvals = 3. * numpy.sqrt(2.) * numpy.sqrt(eigvals)
         u = eigvecs[0]/lg.norm(eigvecs[0])
         angle = numpy.arctan(u[1]/u[0])
         angle = 180. * angle/numpy.pi
         ellipse = Ellipse(xy=centroids[c], width=eigvals[0],
                           height=eigvals[1], angle=180.+angle, color=color, linewidth=0.5, alpha=0.5, **kwargs)
         ax.add_artist(ellipse)
         plt.scatter(data[assignments == c, 0],
                     data[assignments == c, 1], color=color, s=10, marker="o")
     # end
     for c in range(centroids.shape[0]):
         plt.scatter(centroids[c][0], centroids[c]
                     [1], color="k", s=50, marker="*")
     plt.subplot(122)
     plt.xlabel('Iterations')
     plt.ylabel('Negative Log likelihood')
     plt.title("Loglikeihood vs Number Of Iterations")
     plt.plot(self.likelihoods[1:])
     plt.show()
def plot_model_comparison(f1_scores,labels):
    len_labels = len(labels)
    colors = cm.gist_rainbow(np.linspace(0.,1.,len_labels))
    width = 0.6
    num_features = np.arange(len_labels)
    fig, ax = plt.subplots(figsize=(8,6))
    bars = ax.bar(num_features, f1_scores, width)
    
    ax.set_title('F1 score comparison across models',fontsize=14)
    ax.set_xlabel('Model',fontsize=13)
    ax.set_ylabel('Average F1 Score',fontsize=13)
    ax.set_xticks(num_features)
    ax.set_xticklabels(labels,rotation=0,va='top',ha='center',fontsize=12)
    ax.set_ylim([0,1])
    ax.yaxis.set_major_locator(ticker.LinearLocator(numticks=6))
    
    for i,bar in enumerate(bars):
        bar.set_color(colors[i])
        height = bar.get_height()
        ax.annotate('{:.2f}'.format(height),
                    xy=(bar.get_x() + bar.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom',fontsize=12)
    return fig, ax
예제 #8
0
파일: vis3d.py 프로젝트: yurivish/holopy
def show_sphere_cluster(s, color):
    # Delayed imports to avoid hard dependencies on plotting packages and to
    # avoid the cost of importing them in noninteractive code
    from matplotlib import cm

    mlab = import_mayavi()

    # scale factor is 2 because mayavi interprets 4th
    # argument as a diameter, we keep track of radii
    # view is chosen to be looking from the incoming laser's point of view
    if color == 'rainbow':
        for i in arange(0, len(s.x)):
            numberofcolors = max(10, len(s.x))
            mlab.points3d(s.x[i],
                          s.y[i],
                          s.z[i],
                          s.r[i],
                          scale_factor=2.0,
                          resolution=32,
                          color=cm.gist_rainbow(float(i) /
                                                numberofcolors)[0:3])
            mlab.view(-90, 0, s.z[:].mean())
    else:
        mlab.points3d(s.x,
                      s.y,
                      s.z,
                      s.r,
                      scale_factor=2.0,
                      resolution=32,
                      color=color)
        mlab.view(-90, 0, s.z[:].mean())
예제 #9
0
def PlotXY(x,y,yf,a):
    fig=plt.figure()
    fig.set_size_inches(16.0,9.0)
    plt.style.use("ggplot")
    if(a.Plot=="animated"):
        plt.ion()
    color=iter(cm.gist_rainbow(np.linspace(0,1,len(yf[0:]))))   #gist_rainbow seems to be the same as grace
    if(a.Plot=="input" or a.Plot=="both"):
        plt.plot(x,y,color="black",label=a.InFilename.name,linewidth=2)
    if(a.Plot=="output" or a.Plot=="both" or a.Plot=="animated"):
        i=0
        for Window_length in Get_window_length_space(a):
            for Polyorder in Get_polyorder_space(a):
                if(Polyorder < Window_length):
                    for Deriv in Get_deriv_space(a):
                        for Delta in Get_delta_space(a):
                            plt.title("Savitzky-Golay filter: window_length="+str(a.window_length)+" polyorder="+str(a.polyorder)+" deriv="+str(a.deriv)+" delta="+str(a.delta))
                            labelstr=str(Window_length)+"|"+str(Polyorder)+"|"+str(Deriv)+"|"+str(Delta)
                            plt.grid(which="major",linestyle="-",linewidth="0.3")
                            plt.grid(which="minor",linestyle="-",linewidth="0.1")
                            if(a.Plot=="animated"):
                                plt.plot(x,y,color="black",label=a.InFilename.name,linewidth=2)
                                plt.plot(x,yf[i],color="red",label=labelstr,linewidth=1.25)
                                plt.legend()
                                plt.show()
                                plt.pause(a.delay)
                                fig.clear()
                            else:
                                plt.plot(x,yf[i],linewidth=0.75,label=labelstr,color=next(color))
                            i+=1
    if(a.Plot!="animated"):
        plt.legend()
        plt.show()
    return fig
def GetColorPalatte(sizes):
    colors = {}
    for i, n in enumerate(sorted(sizes.keys())):
        color = cm.gist_rainbow(i % (N_COLOR + 1) / float(N_COLOR))
        colors[i] = color
        colors[n] = color
    return colors
예제 #11
0
def SaveImage(x, y, yf, a):
    nspace = GetNspace(a)
    wspace = GetWspace(a)
    fig = plt.figure()
    fig.set_size_inches(16.0, 9.0)
    plt.minorticks_on()
    plt.grid(which="major", linestyle="-", linewidth="0.3")
    plt.grid(which="minor", linestyle="-", linewidth="0.1")
    plt.title("Butterworth filter: " + 'order(N=' + str(a.N) +
              ') critical freq. (Wn=' + str(a.Wn) + ')')
    color = iter(cm.gist_rainbow(np.linspace(0, 1, len(yf[0:]))))
    if (a.Plot == "input" or a.Plot == "both" or a.Plot == "animated"):
        plt.plot(x, y, color="black", label=a.InFilename.name, linewidth=1)
    if (a.Plot == "output" or a.Plot == "both" or a.Plot == "animated"):
        labelstr = ""
        i = 0
        for N in nspace:
            nstr = "N=" + str(N)
            for Wn in wspace:
                labelstr = nstr + " Wn=" + str(Wn)
                plt.plot(x, yf[i], linewidth=1, label=labelstr, c=next(color))
                i += 1
    plt.legend()
    if (a.ImgFilename):
        fig.savefig(a.ImgFilename, dpi=fig.dpi)
    return fig
예제 #12
0
파일: asen.py 프로젝트: realcatking/asen
    def plot_attention(self, imgs, heatmaps, tasks, alpha=0.5):
        global meta

        for i in range(len(tasks)):
            heatmap = heatmaps[i]
            heatmap = cv2.resize(heatmap, (224, 224),
                                 interpolation=cv2.INTER_CUBIC)
            heatmap = np.maximum(heatmap, 0)
            heatmap /= np.max(heatmap)
            heatmap_marked = np.uint8(cm.gist_rainbow(heatmap)[..., :3] * 255)
            heatmap_marked = cv2.cvtColor(heatmap_marked, cv2.COLOR_BGR2RGB)
            heatmap_marked = np.uint8(imgs[i] * alpha + heatmap_marked *
                                      (1. - alpha))
            heatmap_marked = heatmap_marked.transpose([2, 0, 1])

            win_name = 'img %d - %s' % (i, meta.data['ATTRIBUTES'][tasks[i]])
            if win_name not in self.plots:
                self.plots[win_name] = self.viz.image(
                    heatmap_marked, env=self.env, opts=dict(title=win_name))
                self.plots[win_name + 'heatmap'] = self.viz.heatmap(
                    heatmap, env=self.env, opts=dict(title=win_name))
            else:
                self.viz.image(heatmap_marked,
                               env=self.env,
                               win=self.plots[win_name],
                               opts=dict(title=win_name))
                self.viz.heatmap(heatmap,
                                 env=self.env,
                                 win=self.plots[win_name + 'heatmap'],
                                 opts=dict(title=win_name))
예제 #13
0
 def colors(self, N):
     colors = {}
     for i, n in enumerate(sorted(self._sizes.keys())):
         color = cm.gist_rainbow(i % (N + 1) / float(N))
         colors[i] = color
         colors[n] = color
     return colors
예제 #14
0
def PlotXY(x,y,yf,a):
    wspace=GetWspace(a)
    nspace=GetNspace(a)
    fig=plt.figure()
    fig.set_size_inches(16.0,9.0)
    plt.style.use("ggplot")
    if(a.Plot=="animated"):
        plt.ion()
    color=iter(cm.gist_rainbow(np.linspace(0,1,len(yf[0:]))))   #gist_rainbow seems to be the same as grace
    if(a.Plot=="input" or a.Plot=="both"):
        plt.plot(x,y,color="black",label=a.InFilename.name,linewidth=1)
    if(a.Plot=="output" or a.Plot=="both" or a.Plot=="animated"):
        labelstr=""
        i=0
        for w in wspace:
            wstr="w="+str(w)
            for n in nspace:
                labelstr=wstr+" n="+str(n)
                plt.minorticks_on()
                plt.grid(which="major",linestyle="-",linewidth="0.3")
                plt.grid(which="minor",linestyle="-",linewidth="0.1")
                plt.title("Wiener filter: "+'w='+str(a.w)+' n='+str(a.n))
                plt.legend()
                if(a.Plot=="animated"):
                    plt.plot(x,y,color="black",label=a.InFilename.name,linewidth=1)
                    plt.plot(x,yf[i],linewidth=1,label=labelstr,c="red")
                    plt.legend()
                    plt.show()
                    plt.pause(a.d)
                    fig.clear()
                else: plt.plot(x,yf[i],linewidth=1,label=labelstr,c=next(color))
                i+=1
    if(a.Plot!="animated"):
        plt.show()
    return fig
def display_community_location(all_districts, community_location):
    title = u'南京市小区分布图'
    ax = plt.gca()
    ax.set_aspect(1)
    handles = []
    labels = []
    colors = cm.gist_rainbow(np.linspace(0, 1, len(all_districts)))
    color_index = 0
    for district in all_districts:
        one_label = plt.scatter(community_location[district]['longitude'],
                                community_location[district]['latitude'],
                                color=colors[color_index],
                                s=0.5)
        handles.append(one_label)
        labels.append(district)
        color_index += 1

    fig_size = plt.rcParams["figure.figsize"]
    fig_size[0] = 4.0
    fig_size[1] = 4.0
    plt.rcParams["figure.figsize"] = fig_size

    plt.xlim((118.25, 119.5))
    plt.xlabel(u'经度(°,E)')
    plt.ylabel(u'纬度(°,N)')
    leg = plt.legend(handles=handles, labels=labels, loc='best')
    plt.tight_layout()
    plt.savefig(u'分布图\\' + title + '.png', dpi=500)
예제 #16
0
파일: vis.py 프로젝트: carneades271/holopy
def show_sphere_cluster(s, color):
    """
    This function to show a 3D rendering of a Spheres obj hasn't worked since
    HoloPy 3.0, due to Mayavi compatibility issues. We keep the code because
    we hope to re-implement this functionality eventually.
    """
    raise NotImplementedError("3D renders of Spheres not currently supported")
    # Delayed imports to avoid hard dependencies on plotting packages and to
    # avoid the cost of importing them in noninteractive code
    from matplotlib import cm

    mlab = import_mayavi()

    # scale factor is 2 because mayavi interprets 4th
    # argument as a diameter, we keep track of radii
    # view is chosen to be looking from the incoming laser's point of view
    if color == 'rainbow':
        for i in arange(0,len(s.x)):
            numberofcolors = max(10,len(s.x))
            mlab.points3d(s.x[i], s.y[i], s.z[i], s.r[i],
                scale_factor=2.0, resolution=32,
                color=cm.gist_rainbow(float(i)/numberofcolors)[0:3])
            mlab.view(-90,0,s.z[:].mean())
    else:
        mlab.points3d(s.x, s.y, s.z, s.r, scale_factor=2.0,
            resolution=32, color=color)
        mlab.view(-90,0,s.z[:].mean())
예제 #17
0
def anima(full_data_nodes, full_data_trains, nametoid):

    Niter = len(full_data_nodes)
    cm_vv = lambda x: cm.gist_rainbow(-0.48*x + 0.48)

    # Create Graph
    G = get_barcelona()

    pos = {i: G.node[i]['pos'] for i in range(len(G))}

    def update(num):
        ax.clear()
        nodes_this_step = full_data_nodes[num]
        trains_this_step = full_data_trains[num]
        dibuixa_xarxa()
        #print(nodes_this_step)
        #print(nodes_this_step)
        #nx.draw_networkx_nodes(G,pos,node_color=nodes_this_step,node_size=5, cmap = cm_vv) #Falta posar color segons ocupació
        nx.draw_networkx_nodes(G,pos,node_color=[cm_vv(nodes_this_step[i][1])[:4] for i in range(len(nodes_this_step))],node_size=50) #Falta posar color segons ocupació

        #Per a cada tren necessito: nd
        # [x_0, y_0, x_desti, y_desti, ocupacio sobre 1, fraccio_viatge]
        trens = [donam_el_tren(*i) for i in trains_this_step]
        #trens = None
        Trenets = collections.PatchCollection(trens, match_original = True, zorder=10)
        ax.add_collection(Trenets)
        #new_colors_edges= [cm_vv(np.random.random()) for _ in range(12)]
        #new_colors_nodes = [cm_vv(1) for _ in range(8)]

        # Scale plot ax
        """
        ax.set_title("Frame %d"%(num+1), fontweight="bold")
        ax.set_xticks([])
        ax.set_yticks([])
        plt.axis('equal')
        plt.title(str(num) + " segons")
        """
        #plt.title(str(num))

    fig, ax = plt.subplots(figsize=(40,20))

    magic_numbers = [-1,29,47,73,95,121]
    color = {1: 'red', 2: 'purple', 3: 'green', 4: 'yellow', 5: 'blue'}

    def dibuixa_xarxa():
        for i in range(1,6):
            nx.draw_networkx_edges(G,pos, edgelist = [(k, k+1) for k in range(magic_numbers[i-1]+1, magic_numbers[i])], width=5.0,edge_color=color[i], alpha = 0.2)

        for i in nametoid.keys():
            idd = list(nametoid[i].values())[0]
            gj = G.node[idd]
            plt.text(gj['pos'][0]+10, gj['pos'][1]+10, gj['name'][:8]+("" if len(gj['name']) <= 8 else "."), fontsize = 6, rotation = 10)

    dibuixa_xarxa()
    nx.draw_networkx_nodes(G,pos,node_color=cm_vv(0),node_size=50)
    anim = matplotlib.animation.FuncAnimation(fig, update, frames=Niter, interval = 1)
    #Writer = matplotlib.animation.writers['ffmpeg']
    #writer = Writer(fps=25, metadata=dict(artist='Me'), bitrate=1800)
    #anim.save('Llarg_final.mp4', writer = writer)
    plt.show()
예제 #18
0
def plot_mean_loss(history, path_resultados, test_name, db_name):
    print("Plotando a Loss")
    figure = plt.gcf()
    figure.set_size_inches(20, 8)
    ax = plt.subplot()
    plt.title('Loss')
    plt.ylabel('Loss')
    plt.xlabel('Época')
    colors = iter(colormap.gist_rainbow(np.linspace(0, 1, len(history))))
    i = 1
    for h in history:
        color = next(colors)
        plt.plot(h.history['loss'],
                 label='Treino ' + str(i),
                 color=color,
                 linestyle='solid')
        plt.plot(h.history['val_loss'],
                 label='Teste ' + str(i),
                 color=color,
                 linestyle='dotted')
        i += 1
    plt.legend()
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    ax.legend(loc='best', bbox_to_anchor=(1, 0.5))
    plt.grid(True)
    plt.savefig(path_resultados + '/' + test_name + '_' + db_name +
                "_loss.jpg")
    plt.cla()
    plt.clf()
예제 #19
0
 def __plotScorePlayerPlot(self, playerName, ax):
     colors = cm.gist_rainbow(
         np.linspace(0, 1, len(self.__getPartners(playerName))))
     for index, partnerName in enumerate(self.__getPartners(playerName)):
         payoff = np.sum(
             self.championship[playerName][partnerName]['payoff'])
         ax.bar(index, payoff, color=colors[index])
예제 #20
0
def plot_matches(image0, image1, kpts0, kpts1, scores=None, layout="lr"):
    """
    plot matches between two images. If score is nor None, then red: bad match, green: good match
    :param image0: reference image
    :param image1: current image
    :param kpts0: keypoints in reference image
    :param kpts1: keypoints in current image
    :param scores: matching score for each keypoint pair, range [0~1], 0: worst match, 1: best match
    :param layout: 'lr': left right; 'ud': up down
    :return:
    """
    H0, W0 = image0.shape[0], image0.shape[1]
    H1, W1 = image1.shape[0], image1.shape[1]

    if layout == "lr":
        H, W = max(H0, H1), W0 + W1
        out = 255 * np.ones((H, W, 3), np.uint8)
        out[:H0, :W0, :] = image0
        out[:H1, W0:, :] = image1
    elif layout == "ud":
        H, W = H0 + H1, max(W0, W1)
        out = 255 * np.ones((H, W, 3), np.uint8)
        out[:H0, :W0, :] = image0
        out[H0:, :W1, :] = image1
    else:
        raise ValueError("The layout must be 'lr' or 'ud'!")

    kpts0, kpts1 = np.round(kpts0).astype(int), np.round(kpts1).astype(int)

    # get color
    if scores is not None:
        smin, smax = scores.min(), scores.max()
        assert (0 <= smin <= 1 and 0 <= smax <= 1)

        color = cm.gist_rainbow(scores * 0.4)
        color = (np.array(color[:, :3]) * 255).astype(int)[:, ::-1]
    else:
        color = np.zeros((kpts0.shape[0], 3), dtype=int)
        color[:, 1] = 255

    for (x0, y0), (x1, y1), c in zip(kpts0, kpts1, color):
        c = c.tolist()
        if layout == "lr":
            cv2.line(out, (x0, y0), (x1 + W0, y1),
                     color=c,
                     thickness=1,
                     lineType=cv2.LINE_AA)
            # display line end-points as circles
            cv2.circle(out, (x0, y0), 2, c, -1, lineType=cv2.LINE_AA)
            cv2.circle(out, (x1 + W0, y1), 2, c, -1, lineType=cv2.LINE_AA)
        elif layout == "ud":
            cv2.line(out, (x0, y0), (x1, y1 + H0),
                     color=c,
                     thickness=1,
                     lineType=cv2.LINE_AA)
            # display line end-points as circles
            cv2.circle(out, (x0, y0), 2, c, -1, lineType=cv2.LINE_AA)
            cv2.circle(out, (x1, y1 + H0), 2, c, -1, lineType=cv2.LINE_AA)

    return out
예제 #21
0
def SaveImage(x,y,yf,a):
    nspace=GetNspace(a)
    wspace=GetWspace(a)
    fig=plt.figure()
    fig.set_size_inches(16.0,9.0)
    plt.minorticks_on()
    plt.grid(which="major",linestyle="-",linewidth="0.3")
    plt.grid(which="minor",linestyle="-",linewidth="0.1")
    plt.title("Wiener filter: "+'size(w='+str(a.w)+') noise power (n='+str(a.n)+')')
    color=iter(cm.gist_rainbow(np.linspace(0,1,len(yf[0:]))))
    if(a.Plot=="input" or a.Plot=="both" or a.Plot=="animated"):
        plt.plot(x,y,color="black",label=a.InFilename.name,linewidth=1)
    if(a.Plot=="output" or a.Plot=="both" or a.Plot=="animated"):
        labelstr=""
        i=0
        for w in wspace:
            wstr="w="+str(w)
            for n in nspace:
                labelstr=wstr+" n="+str(n)
                plt.plot(x,yf[i],linewidth=1,label=labelstr,c=next(color))
                i+=1
    plt.legend()
    if(a.ImgFilename):
        fig.savefig(a.ImgFilename,dpi=fig.dpi)
    return fig
def plotprof(id=('A1', 'A2'), name='0'):
    print name, ':', id
    color = [cm.gist_rainbow(i) for i in np.linspace(1.0, 0.0, 9)]
    func, remax = make_funcs(id)
    fig = pyplot.figure(figsize=(5, 5))
    fig.subplots_adjust(bottom=0.15, top=0.95, left=0.15, right=0.95, hspace=0.0, wspace=0.0)
    rmax = remax*3.0001
    r = np.arange(rmax/10000.0, rmax, rmax/100.0)
    for i, iid in enumerate(id):
        print i
        for j in range(len(func[i])):
            for k, band in enumerate(bands):
                if k == 0:
                    label = "%s\_%i"%(iid, j)
                else:
                    label = ""
                pyplot.plot(r, func[i][j][k](r), linestyle=linestyle[i],
                            marker=None, color=color[k], label=label)
    pyplot.legend(loc='upper right', numpoints=1, prop={'size': 16})
    pyplot.xlabel('$r_{\mathrm{e}}$')
    pyplot.ylabel('$\mu$')
    #fig.gca().invert_yaxis()
    pyplot.xlim(0.0, rmax)
    pyplot.ylim(26, 16)
    fig.savefig('plots/profiles_%s.pdf'%name)
예제 #23
0
def main():
    random.seed(time.time())
    print("Loading data set...")
    data = numpy.loadtxt('GMM_dataset.txt', dtype=float)
    km = kMeans(k=5, r=10, t=0.001)
    km.clusterData(data)
    print("K Means Centroids - ", km.centroids)
    print("K Means Sum Of Squared Error - ", km.rss)
    # Plotting starts here
    plt.subplot(121)
    plt.xlabel('X1')
    plt.ylabel('X2')
    plt.title("K Means Clustering With K = "+str(km.k))
    colors = iter(cm.gist_rainbow(numpy.linspace(0, 1, len(km.clusters))))
    for centroid in km.centroids:
        plt.scatter(km.centroids[centroid][0],
                    km.centroids[centroid][1], color="k", s=100, marker="*")

    for classification in km.clusters:
        color = next(colors)
        for features in km.clusters[classification]:
            plt.scatter(features[0], features[1],
                        color=color, s=10, marker="o")
        # end
    # end
    plt.subplot(122)
    plt.plot(km.rss)
    plt.title("Sum Of Squared Error vs Iterations")
    plt.xlabel("Iterations")
    plt.ylabel("Sum Of Squared Error")
    plt.show()
예제 #24
0
def phase_diff(mag, angle, thresh):
    angle_diff, angle_total = angle_data(angle)

    filter_points = get_interesting_filters(mag, thresh)

    i,j = filter_points[0], filter_points[1]

    plt.figure()
    plt.plot(angle_total[i,:], angle_total[j,:])
    plt.title("Total Angle")
    plt.xlabel("Filter %d" % i)
    plt.ylabel("Filter %d" % j)

    subsample = 2 ** 2
    x,y = angle_diff[i,:], angle_diff[j,:]
    x,y = x - np.mean(x), y - np.mean(y)
    x   = x[range(0, len(x), subsample)]
    y   = y[range(0, len(y), subsample)]

    plt.figure()
    plt.xlabel("I=%d" % i)
    plt.plot(x)

    a, b, r_value, c, std_err = stats.linregress(x,y)
    print ('i:%d, j:%d, r-squared: %f' % (i,j,r_value ** 2))
    print_every = len(x) / 8

    plt.figure()
    colors = cm.gist_rainbow(np.linspace(0, 1, len(y)))
    for (xi, yi, c, t) in zip(x,y,colors,range(len(y))):
        arg = "t=%d" % (subsample*t) if t % print_every == 0 else None
        plt.scatter(xi, yi, color=c, s=1, label=arg)
    plt.xlabel("Filter %d" % i)
    plt.ylabel("Filter %d" % j)
    plt.legend()
예제 #25
0
def plot_acc(history, path):
    figure = plt.gcf()
    figure.set_size_inches(24, 9)
    ax = plt.subplot()
    plt.title('Accuracy')
    plt.ylabel('Accuracy')
    plt.xlabel('Epoch')
    colors = iter(colormap.gist_rainbow(np.linspace(0, 1, len(history))))
    for i in range(len(history)):
        color = next(colors)
        plt.plot(history[i].history['acc'],
                 label='Train ' + str(i),
                 color=color,
                 linestyle='solid')
        plt.plot(history[i].history['val_acc'],
                 label='Test ' + str(i),
                 color=color,
                 linestyle='dotted')
    x1, x2, y1, y2 = plt.axis()
    plt.axis((x1, x2, 0.0, 1.0))
    plt.legend()
    box = ax.get_position()
    ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
    ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
    plt.grid(True)
    plt.savefig(path)
예제 #26
0
    def __init__(self, store):
        GLRealtimeProgram.__init__(self, 'Motion Plan Checkpoint')

        self.world = build_world(store)
        self.robot = self.world.robot('tx90l')

        self.robot_path = []

        mp = store.get('/robot/waypoints')

        self.dts = [wp[0] for wp in mp]
        self.commands = [{
            'robot': self.robot.getConfig()
        }] + [wp[1] for wp in mp]

        self.fps = 30.0
        self.dt = 1 / self.fps

        self.speed_scale = 1
        self.end_delay = 1

        self.n = 0
        self.start_time = -self.end_delay
        self.duration = sum(self.dts)

        self.dofs = self.robot.numLinks()

        self.trace_vbos = []
        for i in range(1, self.dofs):
            trace = self.trace_link(self.commands, i)
            data = numpy.array(trace, dtype=numpy.float32)
            color = cm.gist_rainbow(float(i - 1) / (self.dofs - 2))
            self.trace_vbos.append((color, vbo.VBO(data, GL_STATIC_DRAW)))
예제 #27
0
def visual_multiple(results_dicts):
    from matplotlib import cm as cm
    from matplotlib import pyplot as plt

    plt.rc("font", size=14)
    plt.rc("lines", linewidth=4)

    # initialize the figure
    fig = plt.figure()

    # get all the results
    metrics = list(list(results_dicts[0][1].values())[0].keys())
    n_metrics = len(metrics)

    # loop through metrics
    for idx_metric, metric in enumerate(metrics):
        ax = plt.subplot(n_metrics, 1, idx_metric + 1)

        # loop through results
        for idx_result, config_and_results_dict in enumerate(results_dicts):

            config, results_dict = config_and_results_dict

            for ds_name, results in results_dict.items():

                # get all the recorded indices
                idxs = list([
                    key for key in results[metric].keys()
                    if isinstance(key, int)
                ])

                # sort it ascending
                idxs.sort()

                label = None
                linestyle = "dotted"

                if ds_name == "training":
                    label = config["#"]
                    linestyle = "solid"

                ax.plot(
                    idxs,
                    [results[metric][idx] for idx in idxs],
                    label=label,
                    c=cm.gist_rainbow(
                        (float(idx_result) / len(results_dicts))),
                    linestyle=linestyle,
                    alpha=0.8,
                )

        ax.set_xlabel("epochs")
        ax.set_ylabel(metric)

    plt.legend(bbox_to_anchor=(1.04, 0), loc="lower left")
    plt.tight_layout()

    return fig
 def convertTimbre(self, timbre):
     #colormap timbre values to be loaded to strip
     #set timbre between 0 and 1
     #print(timbre[1])
     timbre_conv = 1 / (1 + math.exp(-timbre[1]/45))
     #print(timbre_conv)
     #convert timbre_conv to rgb using rainbow color map
     rgb = ([round(x*255) for x in cm.gist_rainbow(float(timbre_conv))[:3]])
     return rgb
예제 #29
0
def plot_vec_recorded(SACntw, Vvecs, outfolder='', vec_type='v', dsi='',
                      **kargs):

    if vec_type == 'v':
        ylim = (-70, 0)
        ylabel = 'Voltage (mV)'
    elif vec_type == 'sc':
        ylim = (0, 1)
        ylabel = '$\mathrm{G_{GABA}/G_{max}}$'

    amac_rec = SACntw.amac_rec
    colrs = cmx.gist_rainbow(np.linspace(0, 1, len(SACntw.celldata)))

    # plt.clf()
    # plt.subplots(figsize=(20, 20))

    label_null = ['SAC %g null' % (i) for i in amac_rec]
    label_pref = ['SAC %g preferred' % (i) for i in amac_rec]
    if 'subplot' in kargs.keys():
        plt.subplot(kargs['subplot'])
    else:
        plt.figure()
        plt.subplot(111)

    if dsi is not '':
        title = '\n'.join([('SAC%d DSI= %.2f' % (k, n))
                           for n, k in zip(dsi, amac_rec)])
        plt.title(title)
    for i in range(0, len(amac_rec)):
        for j in range(0, len(SACntw.x_rec)):
            vvec = Vvecs[i][2 * j + 1].as_numpy()[0:int(SACntw.h.tstop /
                                                        SACntw.sampinvl)]
            plt.plot(np.arange(0, SACntw.h.tstop, SACntw.sampinvl), vvec,
                     color=colrs[amac_rec[i]] * (j + 1) / len(SACntw.x_rec),
                     ls='--', lw=2, label=label_null[i])
            vvec = Vvecs[i][2 * j].as_numpy()[0:int(SACntw.h.tstop /
                                                    SACntw.sampinvl)]
            plt.plot(np.arange(0, SACntw.h.tstop, SACntw.sampinvl),
                     vvec, color=colrs[amac_rec[i]] * (j + 1) / len(SACntw.x_rec),
                     ls='-', lw=2, label=label_pref[i])
    plt.ylim(ylim)
    plt.ylabel(ylabel, fontsize=16)
    plt.xlim(50, SACntw.h.tstop)
    plt.xlabel('Time (ms)')
    plt.legend(prop={'size': 12}, loc='best',
               fancybox=False, ncol=len(Vvecs[0]),
               frameon=False, facecolor='inherit')

    if outfolder != '':  # Save to file if outfolder not empty
        name = ','.join(str(n) for n in amac_rec)

        namefig = os.path.join(outfolder,
                               (SACntw.synapse_type +
                                "_%s_%s_%s.png"))

        plt.savefig(namefig % (str(SACntw.today),
                               name, vec_type), dpi=300, transparent=True)
예제 #30
0
def generate_rainbow_palette(n_colors=256):
    '''
    Generate a rainbow color palette in RGBA format.
    '''
    result = np.zeros((n_colors, 4), dtype='uint8')
    for color_idx in range(n_colors):
        result[color_idx, :] = (np.asarray(cm.gist_rainbow(color_idx)) * \
            255).astype('uint8')
    return result
예제 #31
0
def cluster_use_dist_matrix(cluster_number, dtw_dist_matrix, distance_type,
                            linkage_type, all_community_location_array):
    title = u'时间序列聚类分布图(' + distance_type + ',' + linkage_type + ')'
    axis_labels = [{'x': u'经度(°,E)', 'y': u'纬度(°,N)'}]
    agg = AgglomerativeClustering(n_clusters=cluster_number,
                                  affinity='precomputed',
                                  linkage=linkage_type)
    agg.fit_predict(dtw_dist_matrix)  # Returns class labels.
    label_pred = agg.labels_

    lis = range(cluster_number)
    classes = ['{:d}'.format(x + 1) for x in lis]
    clustered_community = dict()
    for one_class in classes:
        clustered_community[one_class] = []
    count = 0
    for label in label_pred:
        clustered_community[classes[label]].append(
            all_community_location_array[count])
        count += 1
    for one_class in classes:
        clustered_community[one_class] = np.array(
            clustered_community[one_class])

    fig_size = plt.rcParams["figure.figsize"]
    fig_size[0] = 4.0
    fig_size[1] = 4.0
    plt.rcParams["figure.figsize"] = fig_size

    ax = plt.gca()
    ax.set_aspect(1)
    colors = cm.gist_rainbow(np.linspace(0, 1, cluster_number))
    color_index = 0
    handles = []
    labels = []
    for one_class in classes:
        one_label = plt.scatter(clustered_community[one_class][:, 0],
                                clustered_community[one_class][:, 1],
                                color=colors[color_index],
                                s=0.1,
                                marker='.')
        handles.append(one_label)
        labels.append(one_class)
        color_index += 1
    plt.xlim((118.25, 119.5))
    plt.xlabel(axis_labels[0]['x'])
    plt.ylabel(axis_labels[0]['y'])
    plt.legend(handles=handles, labels=labels, loc='best')

    plt.tight_layout()
    plt.savefig(u'聚类图\\' + title + '.png', dpi=500)

    return label_pred
    def convertTimbre(self, timbre):
        #colormap timbre values to be loaded to strip
        #set timbre between 0 and 1 using 1/e^x
        timbre_1 = 1 / (1 + math.exp(-timbre[1] / 45))  #using 'brightness'
        #timbre_3 = 1 / (1.05**abs(timbre[3])) #using 'attack'
        #timbre_a = round(1 / -(1 + math.exp((timbre[1]*abs(timbre[3]))/2500))+1, 10) #multiply those two
        #have 12 timbre values to choose from, here are variations I tested -currently set to what I believe to be best and most simple
        #see spotify api docs for more info on how these are calculated - noted they do not recommend using them directly

        #convert timbre to rgb using rainbow color map from matplotlib
        rgb = ([round(x * 255) for x in cm.gist_rainbow(float(timbre_1))[:3]])
        return rgb
def visualize_cluster(clusters, sse):
    colors = cm.gist_rainbow(np.linspace(0, 1, len(clusters)))
    for index, cluster in clusters:

        # clusters will be represented by different colors
        plt.scatter(cluster['X'], cluster['Y'], s=3, color=colors[index])

    plt.title('K-means Clustering with K = ' + str(len(clusters)) +
              ' (SSE = ' + str(sse) + ')')
    plt.xlabel('1st-attribute')
    plt.ylabel('2nd-attribute')
    plt.savefig('K_mean_' + str(len(clusters)) + '.png')
예제 #34
0
def kmeans_on_data(dataset, n_cl, save_bool, n_jobs):
	k_means = KMeans(init='random', n_clusters=n_cl, n_init=10, n_jobs=n_jobs)
	t0 = time.time()
	k_means.fit(dataset)
	t_batch = time.time() - t0
	k_means_labels = k_means.labels_
	k_means_cluster_centers = k_means.cluster_centers_
	k_means_labels_unique = np.unique(k_means_labels)
	# This Option saves the Clustercenters and labels for the data 
	# Also Plots the Data with Clusterlabels
	if save_bool:
		f_labels = open('Data/kmean_labels_k'+str(n_cl)+'.csv','w')
		f_cl_centers = open('Data/kmeans_ccenters_k'+str(n_cl)+'.csv','w')
		for c in k_means_labels:
			s = str(c)+'\n'
			f_labels.write(s)
		for c in range(len(k_means_cluster_centers[:,0])):
			line = ''
			for c2 in k_means_cluster_centers[c,:-2]:
				line = line + str(c2) + ','
			line = line + str(k_means_cluster_centers[c,-1]) + '\n'
			f_cl_centers.write(line)
		f_labels.close()
		f_cl_centers.close()

	# Plotting the Clusters
		fig = plt.figure()
		colors = cm.gist_rainbow(np.linspace(0, 1, n_cl))
		ax = fig.add_subplot(1,1,1)
		ax.set_title('K-Means Clustering with $K = '+str(n_cl) +'$, Inertia $= '+str(k_means.inertia_)+'$')
		ax.set_xlabel('PC1')
		ax.set_ylabel('PC2')
		# 
		C_Labels = []
		for i,clu in enumerate(k_means_cluster_centers):
			C_Labels.append('Cluster '+ str(i+1))
		Ps = []
		for k,col in zip(range(n_cl),colors):
			my_members = k_means_labels==k
			cluster_center = k_means_cluster_centers[k]
			ax.plot(data[my_members,0], data[my_members,1],linestyle='', markerfacecolor = col, marker='.')
			Ps.append(ax.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col, markeredgecolor='k', markersize=6, label = C_Labels[k]))
		
		ax.legend(loc = 'upper left', bbox_to_anchor = (0.85,1.00), fontsize = 12, markerscale = 0.7, numpoints = 1)
		plt.savefig('Plots/K-Means_k'+str(n_cl)+'.pdf', format = 'pdf')

		ax.set_xlim([-0.05,1])
		ax.set_ylim([-0.05,1])
		plt.savefig('Plots/K-Means_small_k'+str(n_cl)+'.pdf', format = 'pdf')
		plt.close('all')

	return k_means
예제 #35
0
파일: imixer.py 프로젝트: plant/envmixer
    def load(self, event):
        pp.ion()

        # Draw source spectrograms only once.
        for i in range(len(self.sounds)):
            pp.sca(self.spec_axes[i])

            basecolor = cm.gist_rainbow(float(i) / (len(self.sounds) - 1))[0:3]
            cmap = mplc.LinearSegmentedColormap('colors%d' % i, {
                'red': [
                    (0.0, 1.0, 1.0),
                    (1.0, basecolor[0], basecolor[0])
                ],
                'green': [
                    (0.0, 1.0, 1.0),
                    (1.0, basecolor[1], basecolor[1])
                ],
                'blue': [
                    (0.0, 1.0, 1.0),
                    (1.0, basecolor[2], basecolor[2])
                ]
            })

            pxx, freqs, t = mpl.mlab.specgram(self.sounds[i].wav, Fs=self.sounds[i].rate, NFFT=1024, noverlap=512)
            pxx = np.flipud(10. * np.log10(pxx))
            pxx = (pxx - np.amin(pxx)) / (np.amax(pxx) - np.amin(pxx))
            pxx = (np.tanh((pxx * 2 - 1)) + 1) / 2.0
            pxx = pxx ** 6

            self.spec_axes[i].imshow(pxx, cmap, extent=(0, np.amax(t), freqs[0], freqs[-1]))
            self.spec_axes[i].text(0, 0, self.sounds[i].filename)
            self.spec_axes[i].set_aspect('auto')
            self.spec_axes[i].set_xlim((0, np.amax(t)))
            self.spec_axes[i].get_xaxis().set_visible(False)
            self.spec_axes[i].set_ylim((np.amin(freqs), np.amax(freqs)))
            self.spec_axes[i].set_ylabel('Frequency (Hz)')

            pp.draw()

        self.preview_axes.set_xlabel('Time (s)')
        self.preview_axes.get_yaxis().set_visible(False)

        self.update(None)

        spp = self.gs.get_subplot_params()
        spp.left = 0.05
        spp.right = 0.95
        spp.hspace = 0.5

        pp.ioff()
예제 #36
0
def make_frame(t):

    global previous_time, alreadyZoomed

    # print t
    time = int((t / dt) % nt)
    # pdb.set_trace()
    print "t,time", t, time
    global sfs
    my_cm = n.append([[0, 0, 0, 0]], cm.gist_rainbow(n.linspace(0, 255, len(ibrains)).astype(n.uint16)), 0)
    my_cm = my_cm[:, :3]

    # pdb.set_trace()

    if len(sfs) != len(ibrains) or time != previous_time:
        mlab.clf()  # clear the figure (to reset the colors)
        for isample in range(len(ibrains)):
            print "isample: %s" % isample
            # data = ((n.array(bs[ibrains[isample]].objects[time]['labels'])>0)*(isample+1)).astype(n.float)
            data = ((n.array(bs[ibrains[isample]].objects[time]["labels"]) > 0)).astype(n.float)
            data = imaging.sortAxes(data, [2, 1, 0])
            s = ndimage.gaussian_filter(data, 1)
            if len(sfs) != len(ibrains):
                print "first time!"
                sf = mlab.pipeline.scalar_field(x, y, z, s)
                sf.spacing = spacing
                sfs.append(sf)
            else:
                print "only updating!"
                sfs[isample].set(scalar_data=s)
            del data, s
            contours = [0.5]
            mlab.pipeline.iso_surface(sfs[isample], contours=contours, figure=fig_myv, color=tuple(my_cm[isample + 1]))
            calcIso = True

    if t:
        print "rotating"
        scene.scene.camera.azimuth(360.0 / rotPeriod / fps)
        scene.scene.render()
    if not alreadyZoomed:
        scene.scene.camera.zoom(1.25)
        scene.scene.camera.zoom(1.25)
        scene.scene.camera.zoom(1.25)
        scene.scene.render()
        alreadyZoomed = True

    previous_time = time
    # return
    return mlab.screenshot(antialiased=True)
예제 #37
0
파일: kmr.py 프로젝트: myuuuuun/KMR
    def plot_simulation(self, ts_length, init=None, num_reps=None, **kwargs):
        if (not (isinstance(init, int) or init is None) or (not (num_reps is None or num_reps == 1))):
            print("複数の試行をplotすることはできません")
            exit(-1)

        simulated = self.simulate(ts_length, init, num_reps, start_init=True)
        if self.num_actions == 2:
            f_list = simulated

        elif self.num_actions > 2:
            # 状態番号のリストから、その状態に対応する人数リストのリストに変換
            simulated = self.from_stateindex_to_stateplayersnum(simulated)
        
        else:
            print("Error!")
            exit(-1)

        fig, ax = plt.subplots()
        plt.title("Simulation of KMR\nInitial state: {0}".format(simulated[0]))
        xlim = kwargs.get('xlim', False)
        ylim = kwargs.get('ylim', False)
        t_list = np.arange(0, ts_length+1, dtype=int)
        
        if self.num_actions == 2:
            plt.plot(t_list, f_list, color='b', linewidth=1, label="Num of action1")
            plt.plot(0, f_list[0], marker='o', color='r', label="Initial point")

        # 行動パターンが3つ以上の場合は、それぞれの行動をとっている人数の推移を折れ線で表現
        if self.num_actions > 2:
            for i in range(self.num_actions):
                f_list = simulated[:, i]
                plt.plot(t_list, f_list, color=cm.gist_rainbow(i*1.0/self.num_actions), linewidth=1, label="action{0}".format(i+1))

            plt.plot(np.zeros(self.num_actions, dtype=int), simulated[0], marker='o', color='r', label="Initial points")

        """
        points_x = [point[0] for point in points]
        points_y = [point[1] for point in points]
        plt.plot(points_x, points_y, 'o', color='r', label="点列")
        """
        
        plt.xlabel("time series")
        plt.ylabel("number of people")
        ax.set_xlim(0, ts_length+1)
        ax.set_ylim(0, self.num_players)

        plt.legend()
        plt.show()
예제 #38
0
    def PopulateFilesWidgets(self):
        self.filesWidgets = QtGui.QGraphicsWidget()
        self.filesWidgetsLayout = QtGui.QGraphicsGridLayout(self.filesWidgets)
        self.files={}
        self.filesP={}
        self.dynamicRows=1
        #Files Label
        self.filesLabel = QtGui.QLineEdit()
        self.filesLabel.setText("------------------------------Files--------------------------------------")
        self.filesLabel.isReadOnly()
        self.filesLabel.setStyleSheet(
            'font: bold 14px;background-color:black;border-style: outset;color: rgb(255,255,255)')
        self.filesLabelP = QtGui.QGraphicsProxyWidget()
        self.filesLabelP.setWidget(self.filesLabel)
        self.filesWidgetsLayout.addItem(self.filesLabelP, 0, 0, 1, 15)

        colorMap = iter(cm.gist_rainbow(np.linspace(0, 1, len(self.group))))
        column = 0
        for file, g in self.group:
            red, green, blue, a = next(colorMap)
            red = int(red * 255)
            green = int(green * 255)
            blue = int(blue * 255)
            self.colors[file] = QtGui.QColor(red, green, blue)
            # selectable files
            self.files[file] = QtGui.QCheckBox(file[-30:])
            self.files[file].setStyleSheet('background-color:black;'
                                           'border-style: outset;'
                                           'color: rgb({},{},{})'.format(red,green,blue))
            self.files[file].toggle()
            self.files[file].stateChanged.connect(self.CreateCanvases)
            self.filesP[file] = QtGui.QGraphicsProxyWidget()
            self.filesP[file].setWidget(self.files[file])
            if column > 6:
                self.dynamicRows += 1
                column = 0
            self.filesWidgetsLayout.addItem(self.filesP[file], self.dynamicRows, column)
            column += 1
        # add widgets do dynamic Layout
        self.dynamicRows += 1
        self.filesWidgets.setLayout(self.filesWidgetsLayout)
        self.win.addItem(self.filesWidgets, 0, 1)
def plotcolprof(id=('A1', 'A2'), name='0'):
    # need to decide and implement consistent annuli in which to determine colour
    # would be nice to plot lines for input model too
    # normalised at remax and offset for display purposes
    print name, ':', id
    offset = 0.5
    color = [cm.gist_rainbow(i) for i in np.linspace(1.0, 0.0, 9)]
    func, remax = make_funcs(id)
    fig = pyplot.figure(figsize=(5, 5))
    fig.subplots_adjust(bottom=0.15, top=0.95, left=0.15, right=0.95, hspace=0.0, wspace=0.0)
    rmax = remax*3.0001
    r = np.arange(rmax/10000.0, rmax, rmax/100.0)
    for i, iid in enumerate(id):
        print i
        for k in range(len(bands)-1):
            f1 = f2 = f1max = f2max = 0.0
            for j in range(len(func[i])):
                if k == 0:
                    #label = "%s_%i_%s-%s"%(iid, j, bands[k], bands[k+1])
                    #label = "%s_%i"%(iid, j)
                    label = "%s"%iid
                else:
                    label = ""
                # to use elliptically averaged surface brightnesses will need
                # to supply multi-component fits with single-Sersic info
                f1 += 10**(-0.4*func[i][j][k](r))
                f2 += 10**(-0.4*func[i][j][k+1](r))
                f1max += 10**(-0.4*func[i][j][k](remax))
                f2max += 10**(-0.4*func[i][j][k+1](remax))
            colour = -2.5*np.log10(f1/f2)
            colour_remax = -2.5*np.log10(f1max/f2max)
            colour -= colour_remax
            colour += offset*k
            pyplot.hlines([offset*k], 0.0, rmax, colors='grey')
            pyplot.plot(r, colour, linestyle=linestyle[i],
                        marker=None, color=color[k], label=label)
    pyplot.legend(loc='upper right', numpoints=1, prop={'size': 16})
    pyplot.xlabel('$r_{\mathrm{e}}$')
    pyplot.ylabel('Colour')
    pyplot.ylim(-1*offset, (len(bands)+1) * offset)
    pyplot.xlim(0.0, rmax)
    fig.savefig('plots/colprofiles_%s.pdf'%name)
예제 #40
0
파일: vis3d.py 프로젝트: barkls/holopy
def show_sphere_cluster(s,color):
    # Delayed imports to avoid hard dependencies on plotting packages and to
    # avoid the cost of importing them in noninteractive code
    from matplotlib import cm

    mlab = import_mayavi()

    # scale factor is 2 because mayavi interprets 4th
    # argument as a diameter, we keep track of radii
    # view is chosen to be looking from the incoming laser's point of view
    if color == 'rainbow':
        for i in arange(0,len(s.x)):
            numberofcolors = max(10,len(s.x))
            mlab.points3d(s.x[i], s.y[i], s.z[i], s.r[i],
                scale_factor=2.0, resolution=32,
                color=cm.gist_rainbow(float(i)/numberofcolors)[0:3])
            mlab.view(-90,0,s.z[:].mean())
    else:
        mlab.points3d(s.x, s.y, s.z, s.r, scale_factor=2.0,
            resolution=32, color=color)
        mlab.view(-90,0,s.z[:].mean())
예제 #41
0
def skypositions(systems):
    data_x = {} 
    data_y = {} 
    for s in systems:
        c = getCoordinates(s)
        if c is not None:
            ra, dec = c
            dm = s.find(".//discoverymethod")
            if dm is not None:
                dm = dm.text
            else:
                dm = "other"
            if dm not in data_x:
                data_x[dm] = []
                data_y[dm] = []
            data_x[dm].append(ra*180./math.pi)
            data_y[dm].append(dec*180./math.pi)

    rcParams.update({'figure.autolayout': True})

    fig = plt.figure(figsize=(700./96.,400./96.))
    plt.xlabel('right ascension [deg]')
    plt.ylabel('declination [deg]')
    plt.xlim(0., 360.)
    plt.ylim(-90., 90.)
    colors = iter(cm.gist_rainbow(np.linspace(0, 1, len(data_x))))
    for key in data_x:
        plt.scatter(data_x[key], data_y[key], s=20., edgecolor=(0,0,0,0.5), alpha=0.5, label=key, color=next(colors))
    plt.legend(loc='upper left',fontsize=12,scatterpoints=1)

    imgdata = StringIO.StringIO()
    fig.savefig(imgdata, format='svg')
    imgdata.seek(0)
    svg_dta = imgdata.buf
    imgdata.close()
    return svg_dta
예제 #42
0
    def plot(self, mu_elts=None, xlim=None, ylim=None, ax_fontsize=1.3, lg_fontsize=1.,
             lg_position=None, fermi_level = None, title=None, saved=False):
        """
        Produce defect Formation energy vs Fermi energy plot
        Args:
            mu_elts:
                a dictionnary of {Element:value} giving the chemical
                potential of each element
            xlim:
                Tuple (min,max) giving the range of the x (fermi energy) axis
            ylim:
                Tuple (min,max) giving the range for the formation energy axis
            ax_fontsize:
                float  multiplier to change axis label fontsize
            lg_fontsize:
                float  multiplier to change legend label fontsize
            lg_position:
                Tuple (horizontal-position, vertical-position) giving the position
                to place the legend.
                Example: (0.5,-0.75) will likely put it below the x-axis.
            saved:


        Returns:
            a matplotlib object

        """
        if xlim is None:
            xlim = (-0.5, self.band_gap+0.5)
        xy = {}
        lower_cap = -100.
        upper_cap = 100.
        y_range_vals = [] # for finding max/min values on y-axis based on x-limits
        for defnom, def_tl in self.transition_level_map.items():
            xy[defnom] = [[],[]]
            if def_tl:
                org_x = list(def_tl.keys())  # list of transition levels
                org_x.sort()  # sorted with lowest first

                #establish lower x-bound
                first_charge = max(def_tl[org_x[0]])
                for chg_ent in self.stable_entries[defnom]:
                    if chg_ent.charge == first_charge:
                        form_en = chg_ent.formation_energy(chemical_potentials=mu_elts,
                                                           fermi_level=lower_cap)
                        fe_left = chg_ent.formation_energy(chemical_potentials=mu_elts,
                                                           fermi_level=xlim[0])

                xy[defnom][0].append(lower_cap)
                xy[defnom][1].append(form_en)
                y_range_vals.append( fe_left)

                #iterate over stable charge state transitions
                for fl in org_x:
                    charge = max(def_tl[fl])
                    for chg_ent in self.stable_entries[defnom]:
                        if chg_ent.charge == charge:
                            form_en = chg_ent.formation_energy(chemical_potentials=mu_elts,
                                                               fermi_level=fl)
                    xy[defnom][0].append(fl)
                    xy[defnom][1].append(form_en)
                    y_range_vals.append( form_en)

                #establish upper x-bound
                last_charge = min(def_tl[org_x[-1]])
                for chg_ent in self.stable_entries[defnom]:
                    if chg_ent.charge == last_charge:
                        form_en = chg_ent.formation_energy(chemical_potentials=mu_elts,
                                                           fermi_level=upper_cap)
                        fe_right = chg_ent.formation_energy(chemical_potentials=mu_elts,
                                                            fermi_level=xlim[1])
                xy[defnom][0].append(upper_cap)
                xy[defnom][1].append(form_en)
                y_range_vals.append( fe_right)
            else:
                #no transition - just one stable charge
                chg_ent = self.stable_entries[defnom][0]
                for x_extrem in [lower_cap, upper_cap]:
                    xy[defnom][0].append( x_extrem)
                    xy[defnom][1].append( chg_ent.formation_energy(chemical_potentials=mu_elts,
                                                                   fermi_level=x_extrem)
                                          )
                for x_window in xlim:
                    y_range_vals.append( chg_ent.formation_energy(chemical_potentials=mu_elts,
                                                                   fermi_level=x_window)
                                          )

        if ylim is None:
            window = max(y_range_vals) - min(y_range_vals)
            spacer = 0.1 * window
            ylim = (min(y_range_vals) - spacer, max(y_range_vals) + spacer)

        if len(xy) <= 8:
            colors=cm.Dark2(np.linspace(0, 1, len(xy)))
        else:
            colors=cm.gist_rainbow(np.linspace(0, 1, len(xy)))

        plt.figure()
        plt.clf()
        width, height = 12, 8
        #plot formation energy lines
        for_legend = []
        for cnt, defnom in enumerate(xy.keys()):
            plt.plot(xy[defnom][0], xy[defnom][1], linewidth=3, color=colors[cnt])
            for_legend.append( self.stable_entries[defnom][0].copy())

        #plot transtition levels
        for cnt, defnom in enumerate(xy.keys()):
            x_trans, y_trans = [], []
            for x_val, chargeset in self.transition_level_map[defnom].items():
                x_trans.append( x_val)
                for chg_ent in self.stable_entries[defnom]:
                    if chg_ent.charge == chargeset[0]:
                        form_en = chg_ent.formation_energy(chemical_potentials=mu_elts,
                                                           fermi_level=x_val)
                y_trans.append( form_en)
            if len(x_trans):
                plt.plot(x_trans, y_trans,  marker='*', color=colors[cnt], markersize=12, fillstyle='full')

        #get latex-like legend titles
        legends_txt = []
        for dfct in for_legend:
            flds = dfct.name.split('_')
            if 'Vac' == flds[0]:
                base = '$Vac'
                sub_str = '_{'+flds[1]+'}$'
            elif 'Sub' == flds[0]:
                flds = dfct.name.split('_')
                base = '$'+flds[1]
                sub_str = '_{'+flds[3]+'}$'
            elif 'Int' == flds[0]:
                base = '$'+flds[1]
                sub_str = '_{inter}$'
            else:
                base = dfct.name
                sub_str = ''

            legends_txt.append( base + sub_str)

        if not lg_position:
            plt.legend(legends_txt, fontsize=lg_fontsize*width, loc=0)
        else:
            plt.legend(legends_txt, fontsize=lg_fontsize*width, ncol=3,
                       loc='lower center', bbox_to_anchor=lg_position)

        plt.ylim(ylim)
        plt.xlim(xlim)

        plt.plot([xlim[0], xlim[1]], [0, 0], 'k-')  # black dashed line for Eformation = 0
        plt.axvline(x=0.0, linestyle='--', color='k', linewidth=3) # black dashed lines for gap edges
        plt.axvline(x=self.band_gap, linestyle='--', color='k',
                    linewidth=3)

        if fermi_level is not None:
            plt.axvline(x=fermi_level, linestyle='-.', color='k', linewidth=2) # smaller dashed lines for gap edges

        plt.xlabel("Fermi energy (eV)", size=ax_fontsize*width)
        plt.ylabel("Defect Formation\nEnergy (eV)", size=ax_fontsize*width)
        if title:
            plt.title("{}".format(title), size=ax_fontsize*width)

        if saved:
            plt.savefig(str(title) + "FreyplnravgPlot.pdf")
        else:
            return plt
예제 #43
0
# -*- coding: utf-8 -*-
"""
Created on Fri May 08 13:57:40 2015

@author: adeshmu2
"""

from pylab import *
import numpy as np
#from mpltools import style
#from mpltools import layout
import matplotlib.cm as cm
from matplotlib import gridspec

colors = cm.gist_rainbow(np.linspace(0, 1, 9))
#plt.style.use('bmh')

# make a square figure and axes
#figure(1, figsize=(6,6))
#ax = axes([0.1, 0.1, 0.8, 0.8])
plt.rc('text', usetex=True)
plt.rc('font', family='serif')


# The slices will be ordered and plotted counter-clockwise.
labels = 'Electronics', 'Refrigerator', 'Dishwasher', 'Furnace','Washer/Dryer 1', 'Washer/Dryer 2', 'Microwave', 'Bathroom GFI','Kitchen Outlets'
#################################################################
# plot the data for Random Forest
fig = plt.figure(0,figsize=(15,6))
#gs = gridspec.GridSpec(1, 2, width_ratios=[1, 2]) 
ax1 = plt.subplot(121)
예제 #44
0
파일: plot.py 프로젝트: shirtsgroup/pygo
native = options.native
rmsd = options.rmsd
surfE = options.surfE
nosurfEhist = options.nosurfhist
id = options.id
direc = options.datafile
show = options.show
T=empty(numreplicas)
alpha=(trange[1]/trange[0])**(1/float(numreplicas-1))
T[0]=trange[0]
for i in range(1,numreplicas):
	T[i]=T[i-1]*alpha
if tfile:
	T = loadtxt(tfile)
print T
colors = cm.gist_rainbow(linspace(0,1,len(T)))[::-1]

if energy:
	files = []
	for i in range(len(T)):
		#files.append('./surface_replica_exchange/replica'+str(i)+'/energy'+str(int(T[i]))+'.txt')
		files.append(direc+'/energy'+str(int(T[i]))+'.npy')
		#files.append('./replicaexchange/replica'+str(i)+'/energy'+str(int(T[i]))+'.txt')
	nc=load(files[0])
	for file in files:
		nctemp=load(file)
		nc=vstack((nc,nctemp))
	nc=nc[1:numreplicas+1,:]
	plt.figure(1)
	for i,e in enumerate(nc):
		plt.plot(range(len(e)), e, label = str('%3.2f') % T[i] + 'K',color=colors[i])
예제 #45
0
spacing[1] *= -1
spacing[2] *= -1

shape = bs[0].ms[0].shape[::-1]

fig_myv = mlab.figure(size=(2000,2000), bgcolor=(0,0,0))
sfs = []
x,y,z = n.mgrid[0:shape[0],0:shape[1],0:shape[2]]
previous_time = -1

engine = mlab.get_engine()
# -------------------------------------------
scene = engine.scenes[0]
scene.scene.z_minus_view()

my_cm = n.append([[0,0,0,0]],cm.gist_rainbow(n.linspace(0,255,len(ibrains)).astype(n.uint16)),0)
my_cm = my_cm[:,:3]

surfacesDict = dict()
for itime in range(nt):
    for isample in ibrains:
        print itime,isample
        data = (n.array(bs[ibrains[isample]].objects[itime]['labels'])>0).astype(n.float)
        data = imaging.sortAxes(data,[2,1,0])
        s = sitk.gafi(sitk.SmoothingRecursiveGaussian(sitk.gifa(data),1.))
        isurf = mlab.pipeline.iso_surface(s,contours=0.5,figure=fig_myv,color=tuple(my_cm[isample+1]))
        # points = array(isurf.mapper.input.points)
        # mesh = tvtk.PolyData(points=points, polys=triangles)
        # mesh.point_data.scalars = temperature
        # mesh.point_data.scalars.name = 'Temperature'
예제 #46
0
import matplotlib.pyplot as plt

from matplotlib import cm
from numpy import linspace

import csv

start = 0.0
stop = 1.0
number_of_lines= 118
cm_subsection = linspace(start, stop, number_of_lines) 

colors = [ cm.gist_rainbow(x) for x in cm_subsection ]

for i, color in enumerate(colors):
    plt.axhline(i, color=color)

plt.ylabel('Line Number')
plt.show()
plt.close()










예제 #47
0
def labeled(data):
    return (data > 0)[:,:,None]*cm.gist_rainbow(data % 1)