Example #1
1
def plot_2d_clusters(X, labels, centers):
    """
    Given an observation array, a label vector, and the location of the centers
    plot the clusters
    """

    clabels = set(labels)
    K = len(clabels)

    if len(centers) != K:
        raise ValueError("Expecting the number of unique labels and centres to"
                         " be the same!")

    # Plot the true clusters
    figure(figsize=(10, 10))
    ax = gca()

    vor = Voronoi(centers)

    voronoi_plot_2d(vor, ax)

    colors = cm.hsv(np.arange(K)/float(K))
    for k, col in enumerate(colors):
        my_members = labels == k
        scatter(X[my_members, 0], X[my_members, 1], c=col, marker='o', s=20)

    for k, col in enumerate(colors):
        cluster_center = centers[k]
        scatter(cluster_center[0], cluster_center[1], c=col, marker='o', s=200)

    axis('tight')
    axis('equal')
    title('Clusters')
    def PlotMonthBar(self):
        """活跃时间柱形图"""
        date_list = GetNDayList(self.today_dt, 30)
        md_list = list(map(ymd2md, date_list))

        fig, ax = plt.subplots(figsize=(8, 6))

        days = np.arange(30)
        plt.bar(days,
                height=self.activate,
                label='activate',
                color=cm.hsv(0.6),
                alpha=0.8)

        avg_hours = self.activate.mean()
        plt.axhline(y=avg_hours, ls=":", lw=4, c=cm.hsv(0))

        # params
        fontsize = 20
        plt.legend(fontsize=fontsize - 2, loc='upper left')
        plt.xlabel(u"日期", fontsize=fontsize)
        plt.ylabel(u"时长(小时)", fontsize=fontsize)
        plt.xticks(fontsize=fontsize - 5)
        plt.yticks(fontsize=fontsize)
        plt.xticks(ticks=range(0, 30 + 1, 4), labels=md_list[::4])

        plt.title("近一个月学习投入情况(平均{0:.2f}小时)".format(avg_hours),
                  fontsize=fontsize + 5)

        plt.savefig(self.fig_path, dpi=150, bbox_inches='tight')
        plt.close()
def test_matplotlib_rainbow():
    fig = plt.figure(figsize=(6, 4), dpi=96)
    ax = fig.add_subplot(111)

    #im = np.array(list(list([0,0,0,0.8] for _ in range(64)) for _ in range(64)))
    im = np.random.random((64, 64, 4))
    ax.imshow(im, aspect='auto', cmap=cm)  # cmap=cm cmap=cm.hsv
    ax.imshow(im, aspect='auto', extent=[100, 228, 100, 228], origin='lower')

    for i in range(0, 360, 4):
        ax.plot(i, i, 'o', color=getColStr(*getHSV2RGB(i / 360.0)))

    ax.plot(np.arange(360) - 30, np.arange(360) - 10, 'm')

    ax.plot(np.arange(360) - 30, np.arange(360), getColStr(*getHSV2RGB(0.5)))

    # ax.plot(np.arange(360) + 10, np.arange(360) - 30, cmap=cm.hsv) # BAD
    ax.set_color_cycle([cm.hsv(_ / 360.0) for _ in range(360)])
    for i in range(360):
        ax.plot(np.arange(i, i + 2) + 10,
                np.arange(i, i + 2) - 30,
                linewidth=3)

    # print ax._get_lines.get_next_color() # matplotlib >= 3 ?
    # print ax._get_lines.color_cycle # matplotlib >= 3 ?
    print ax.get_lines()[-1].get_color()
    print ax.get_lines()[-360].get_color()

    ax.set_color_cycle([cm.hsv(_ / 8.0) for _ in range(8)])
    for i in range(8):
        ax.plot(np.arange(360) - 5 - i * 2, np.arange(360) - 30)

    ax.set_xlim([-50, 400])
    ax.set_ylim([-50, 400])
    plt.show()
Example #4
0
def draw_lines(paras, u_set, v_set, pic_path):
    """ 1つの画像にエピポーラ線描画 """

    # 画像の読み込み
    img = np.array(Image.open(pic_path))

    # 画像のサイズ
    height, width, _ = img.shape

    # エピポーラ線を1本ずつ描画
    for i, (a, b, c) in enumerate(paras):

        line = np.empty((0, 2))

        # x=0, w, y=0, hとの4交点のうち、画像枠内にある2点を選択
        u1 = -c / a
        u2 = -(b * height + c) / a
        v1 = -c / b
        v2 = -(a * width + c) / b

        if 0 <= u1 <= width:
            line = np.append(line, np.array([[u1, 0]]), axis=0)

        if 0 <= u2 <= width:
            line = np.append(line, np.array([[u2, height]]), axis=0)

        if 0 <= v1 <= height:
            line = np.append(line, np.array([[0, v1]]), axis=0)

        if 0 <= v2 <= height:
            line = np.append(line, np.array([[width, v2]]), axis=0)

        # 2点を結ぶ線分を描画
        plt.plot(line[:, 0],
                 line[:, 1],
                 marker="None",
                 color=cm.hsv(i / len(u_set)))

    data_name = [i for i in range(len(u_set))]

    # 対応点のプロット
    for (i, j, k) in zip(u_set, v_set, data_name):
        plt.plot(i, j, 'o', color=cm.hsv(k / len(u_set)))
        plt.annotate(str(k), xy=(i, j))

    # 画像の読み込み
    img = np.array(Image.open(pic_path))

    # 画像の表示
    plt.imshow(img)

    plt.show()
    plt.close()
Example #5
0
def plot_spd2(Is, filename=None):
    rc('axes', linewidth=0.5)
    rc('font', size=7, family='serif')
    rc('xtick', top=True, direction='in')
    rc('xtick.major', size=2.5, width=0.5)
    rc('ytick', right=True, direction='in')
    rc('ytick.major', size=2.5, width=0.5)
    fig = plt.figure(figsize=(len(Is) * 5, 5), dpi=100)

    for k, I in enumerate(Is):
        ax = fig.add_subplot(100 + len(Is) * 10 + (k + 1))

        imagedims = I.shape[:2]
        vals, vecs = np.linalg.eig(I)

        FA = np.sqrt(0.5 * (vals[..., 0]**2 + vals[..., 1]**2) -
                     vals[..., 0] * vals[..., 1])
        FA /= np.linalg.norm(Is[0], axis=(-2, -1))

        lvals = np.log(vals)
        GA = np.sqrt(0.5 * (lvals[..., 0]**2 + lvals[..., 1]**2) -
                     lvals[..., 0] * lvals[..., 1])
        GA /= 1 + GA

        angles = 180 + 180 * np.arctan2(vecs[..., 0, 0], vecs[..., 1,
                                                              0]) / np.pi
        vals /= 0.5 * vals.max()

        X, Y = np.meshgrid(np.arange(imagedims[0]), np.arange(imagedims[1]))
        XY = np.vstack((X.ravel(), Y.ravel())).T
        ec = EllipseCollection(vals[..., 0],
                               vals[..., 1],
                               angles,
                               units='x',
                               offsets=XY,
                               transOffset=ax.transData,
                               edgecolors=0.8 * cm.hsv(GA.ravel())[:, :-1],
                               facecolors=1.0 * cm.hsv(GA.ravel())[:, :-1],
                               linewidths=0.5)
        ax.add_collection(ec)
        ax.autoscale_view()
        ax.invert_yaxis()
        ax.axis("equal")

    if filename is None:
        plt.show()
    else:
        canvas = FigureCanvasAgg(fig)
        canvas.print_figure(filename)
        plt.close(fig)
Example #6
0
def plot_2d_clusters(X, labels, centers):
    """
    Given an observation array, a label vector, and the location of the centers
    plot the clusters
    """

    clabels = set(labels)
    K = len(clabels)

    if len(centers) != K:
        raise ValueError("Expecting the number of unique labels and centres to"
                         " be the same!")

    # Plot the true clusters
    figure(figsize=(10, 10))
    ax = gca()

    vor = Voronoi(centers)

    voronoi_plot_2d(vor, ax)

    colors = cm.hsv(np.arange(K) / float(K))
    for k, col in enumerate(colors):
        my_members = labels == k
        scatter(X[my_members, 0], X[my_members, 1], c=col, marker='o', s=20)

    for k, col in enumerate(colors):
        cluster_center = centers[k]
        scatter(cluster_center[0], cluster_center[1], c=col, marker='o', s=200)

    axis('tight')
    axis('equal')
    title('Clusters')
Example #7
0
def plot_spectra_grid(file_set,protein,ligands,ligand):
    grid = len(protein) + len(ligand)
    
    # pick the correct file
    proteins = file_set.keys()
    index = ligands.index(ligand)
    file = file_set[protein][index]
    
    # pick a title
    title = "%s - %s" %(protein, ligand)
    
    # make a dataframe
    df = xml2df(file)
    
    # plot the spectra
    fig = plt.figure();
    ax = df['fluorescence'].iloc[:,12].plot(ylim=(0,100000),legend=False, linewidth=4,color='m');
    ax.axvline(x=480,color='0.7',linestyle='--');
    for i in range(11):
        #s = df['fluorescence'].iloc[:,i].plot(ylim=(0,100000),linewidth=3,c=cm.hsv(i*15), ax = ax, title=title);
        df['fluorescence'].iloc[:,i].plot(ylim=(0,100000),linewidth=3,c=cm.hsv(i*15), ax = ax);
        df['fluorescence'].iloc[:,11+i].plot(ylim=(0,100000),legend=False, linewidth=4,c=cm.gray(i*15+50), ax = ax, fontsize =20);
    sns.despine()
    plt.xlim(320,600)
    plt.yticks([])
    plt.xlabel('wavelength (nm)', fontsize=20)
    plt.tight_layout();
    plt.savefig('%s.eps'%title, type='eps', dpi=1000)
def pathsByLength(geo, targ_dict, background=True):
  """
  Overlay paths all on one tree colored by path length.
  """
  lengths = [targ_dict[s]['pathLength'] for s in targ_dict.keys()]
  plt.figure(figsize=(4,6))
  
  if background:
    branchpts = []
    # Plot by branches
    for b in geo.branches: 
      branchpts.append([[n.x, n.y] for n in b.nodes])
    for b in branchpts: # Plot the background skeleton first
        for s in range(len(b)-1):
          plt.plot([b[s][0], b[s+1][0]],
                   [b[s][1], b[s+1][1]], color='black', alpha=0.3)
  
  # Plot each thing
  pDF = PathDistanceFinder(geo, geo.soma)
  for t in targ_dict.keys():
    targ = [seg for seg in geo.segments if 
              seg.filamentIndex==targ_dict[t]['closestFil']][0]
    path = pDF.pathTo(targ)    # This makes sure the colors range the whole spectrm
    pcolor = (targ_dict[t]['pathLength']-min(lengths))/(max(lengths)-min(lengths))
    for p in range(len(path)-1):
      c0, c1 = path[p].coordAt(0), path[p+1].coordAt(0)
      plt.plot([c0[0], c1[0]], [c0[1], c1[1]], linewidth=3,
               color=cm.hsv(pcolor), alpha=0.7)
  plt.show()
    def PlotWaterFall(self):
        """活跃时间瀑布图"""
        fontsize = 20

        st = time.time()
        fig, axes = joypy.joyplot(self.frequent,
                                  column=['hour'],
                                  by="date",
                                  grid=True,
                                  xlabelsize=fontsize,
                                  ylabelsize=fontsize,
                                  figsize=(10, 6),
                                  ylim='own',
                                  fill=True,
                                  linecolor=None,
                                  background=None,
                                  xlabels=True,
                                  ylabels=True,
                                  range_style='all',
                                  x_range=np.arange(25),
                                  color=cm.hsv(0.68))

        # params
        plt.xlabel(u"小时", fontsize=fontsize)
        plt.xticks(ticks=list(range(0, 24, 4)) + [24],
                   labels=list(range(0, 24, 4)) + [24],
                   fontsize=fontsize)
        plt.title(u"近一周学习情况", fontsize=fontsize + 5)
        plt.grid(linestyle="--", alpha=0.45)

        plt.savefig(self.fig_path, dpi=150, bbox_inches='tight')
        plt.close()
Example #10
0
    def PlotDayBar(self):
        """活跃时间柱形图"""
        fig, ax = plt.subplots(figsize=(8, 6))

        hours = np.arange(24)
        # bar
        plt.bar(hours,
                height=self.activate_data,
                label='activate',
                color=cm.hsv(0.4),
                alpha=0.8)

        # params
        fontsize = 20
        plt.legend(fontsize=fontsize - 2, loc='upper left')
        plt.xlabel(u"小时", fontsize=fontsize)
        plt.ylabel(u"时长(秒)", fontsize=fontsize)
        plt.xticks(fontsize=fontsize - 5)
        plt.yticks(fontsize=fontsize)
        plt.xticks(ticks=range(24), labels=hours)
        sumhours = sum(self.activate_data) / 3600
        plt.title("今日学习投入情况 (%.2f 小时)" % sumhours, fontsize=fontsize + 5)

        plt.savefig(self.fig_path, dpi=150, bbox_inches='tight')
        plt.close()
Example #11
0
def scatter_all_seeds(results, title):
    plt.close()
    results = np.array(results)

    for seed in seeds:
        mask = results[:, 0] == int(seed)
        time = results[mask, 1] / 60 / 60
        error = results[mask, 2]
        if is_regression:
            error = np.log10(error)

        plt.plot(time,
                 error,
                 linestyle='solid',
                 linewidth=.5,
                 marker='o',
                 markersize=5,
                 color=cm.hsv(float(seed) / number_seeds, 1),
                 alpha=.75)

    plt.xlabel("Time (h)")
    if is_regression:
        plt.ylabel("log(RMSE)")
    else:
        plt.ylabel("% class. error")
        plt.ylim(0, 100)

    plt.margins(0.1, 0.1)

    plt.title(title)
    plt.savefig("%s/plots%s/trajectories-%s.scatter.png" %
                (os.environ['AUTOWEKA_PATH'], suffix, title))
Example #12
0
def animate():
    global graph, pfad, kreis, ctr, cnt

    # neuen Punkt generieren
    pts, R, attached = dla()

    # Pfad und Kreis updaten
    x,y = zip(*pts)
    pfad.set_data(x, y)
    kreis.set_data([ctr + R*cos(phi) for phi in linspace(0,2*pi,100)],
                   [ctr + R*sin(phi) for phi in linspace(0,2*pi,100)])

    # und letzten Punkt permanent ausgeben, falls angelagert
    if attached:
        graph.scatter(x[-1], y[-1], s=4, c=cm.hsv(cnt), linewidth=0)
        cnt += 0.1

    # Groesse anpasse
    graph.axis((0,M-1,0,M-1))

    # periodisch die Funktion wieder aufrufen, wenn noch ok
    if R >= 0.4*M:
        print "Radius %d ist zu gross geworden" % R
    else:
        figure.canvas.manager.window.after(200, animate)

    figure.canvas.draw()
Example #13
0
def draw_meshgrid(fig,ax):
    # Draw mesh for each red with skipping
    for i in range(0,sLut_3d_size,sSkip):
        ax.plot_wireframe(s**t[i,0:
            sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,0],
            s**t[i,0:sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,1],
            s**t[i,0:sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,2],
            color=cm.hsv(float(i)/float(sLut_3d_size)))
    
    # Draw last mesh if skipped in the loop above
    if((sLut_3d_size - 1) % sSkip):
        ax.plot_wireframe(s**t[sLut_3d_size - 1,0:
            sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,0],
            s**t[sLut_3d_size - 1,0:sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,1],
            s**t[sLut_3d_size - 1,0:sLut_3d_size:sSkip,0:sLut_3d_size:sSkip,2],
            color=cm.hsv(1.0))
 def plot_tsne(self, window, vector_size):
     cprint("モデルのt-NSEによる出力を始めます。", "yellow")
     os.chdir(self.model_dir)
     model = Doc2Vec.load("model_v{}_w{}".format(vector_size, window))
     figsize(15, 15)
     plt.rcParams['font.family'] = 'IPAexGothic'
     tag_name = [i.split("_")[0] for i in os.listdir(self.train_dir)]
     train_data = [model[tag] for tag in tag_name]
     reduced_data = TSNE(n_components=2,
                         random_state=0).fit_transform(train_data)
     for i, tag in enumerate(tag_name):
         plt.scatter(reduced_data[i, 0],
                     reduced_data[i, 1],
                     color=cm.hsv(i / 160))
     texts = [
         plt.text(reduced_data[i, 0],
                  reduced_data[i, 1],
                  str(tag_name[i]),
                  ha='center',
                  va='center') for i in range(len(reduced_data))
     ]
     adjust_text(texts)
     plt.xticks(color="None")
     plt.yticks(color="None")
     os.chdir(self.image_dir)
     plt.savefig("image_tsne_w{}_v{}.png".format(window, vector_size))
Example #15
0
def scatter_all_seeds(results, title):
    plt.close()
    results = np.array(results)

    for seed in seeds:
        mask = results[:, 0] == seed
        time = results[mask, 1].astype(float)
        time = np.divide(time, 3600.)
        error = results[mask, 2].astype(float)
        if is_regression:
            error = np.log10(error)

        plt.plot(time,
                 error,
                 linestyle='solid',
                 linewidth=.5,
                 color=cm.hsv(float(seed) / number_seeds, 1),
                 alpha=.75)

    plt.xlabel("Time (h)")
    if is_regression:
        plt.ylabel("log(RMSE)")
    else:
        plt.ylabel("% class. error")
        plt.ylim(0, 100)

    plt.margins(0.1, 0.1)

    plt.title(title)
    plt.savefig("%s/plots%s/smac-runs-%s.individual.png" %
                (os.environ['AUTOWEKA_PATH'], suffix, title))
Example #16
0
def plot_2Ddata(X, y, dots_alpha=.5, noticks=False):
    colors = cm.hsv(np.linspace(0, .7, len(np.unique(y))))
    for i, label in enumerate(np.unique(y)):
        plt.scatter(X[y==label][:,0], X[y==label][:,1], color=colors[i], alpha=dots_alpha)
    if noticks:
        plt.xticks([])
        plt.yticks([])
Example #17
0
def colorflow(fx, fy, rgba=False, zero_mean=True):
    """Create a colored flow field from (fx,fy) flow

    Optical flow fields are represented with color as angle and saturation
    as magnitude. This implementation optionally represents magntiude in
    the alpha channel for better blending with the original image.

    Args:
        fx,fy: The flow fields

    Keyword Args:
        rgba: If True, represent magnitude with an alpha channel rather than
            saturation (default: False)
        zero_mean: Remove the mean of the flow field before computing the
            visualization. This remove the global interpretability of the flow
            field, but makes better utilization of the color space
    """

    if zero_mean:
        fx, fy = fx - fx.mean(), fy - fy.mean()

    # angle is color, magnitude is saturation
    angle, magnitude = np.arctan2(fy, fx), np.sqrt(fx**2 + fy**2)
    color, saturation = angle / np.pi * 0.5 + 0.5, magnitude / magnitude.max()
    rgb = cm.hsv(color)

    # compute the colored flow field
    if rgba:
        rgb[..., 3] = saturation
    else:
        rgb = 1.0 - saturation[..., None] * (1.0 - rgb[..., :3])
    return rgb
Example #18
0
def plot_tsne_pca_new(data, labels):
    max_label = max(labels)
    max_items = np.random.choice(range(data.shape[0]), size=1200, replace=False) #1370
    
    pca = PCA(n_components=2).fit_transform(data[max_items,:].todense())
    tsne = TSNE().fit_transform(PCA(n_components=50).fit_transform(data[max_items,:].todense()))
    
    
    idx = np.random.choice(range(pca.shape[0]), size=300, replace=False)
    # print(max_items)
    label_subset = labels[max_items]
    label_subset = [cm.hsv(i/max_label) for i in label_subset[idx]]
    
    # f, ax = plt.subplots(1, 2, figsize=(14, 6))
    
    # ax[0].scatter(pca[idx, 0], pca[idx, 1], c=label_subset)
    # ax[0].set_title('PCA Cluster Plot')
    
    # ax[1].scatter(tsne[idx, 0], tsne[idx, 1], c=label_subset)
    # ax[1].set_title('TSNE Cluster Plot')

    f, ax = plt.subplots(1)
    ax.scatter(tsne[idx, 0], tsne[idx, 1], c=label_subset)
    ax.set_title('TSNE Cluster Plot')
    f.savefig('./drive/My Drive/ALDA_Project/clusters_news.png')
Example #19
0
def histogram(names, values, title="", xlabel="", ylabel=""):

    if not names or not values:
        return _empty_chart(title, xlabel, ylabel)

    figure = mpl_Figure()
    canvas = mpl_FigureCanvas(figure)
    figure.set_canvas(canvas)

    ax = figure.add_subplot(111, projection=BasicChart.name)

    colors = [cm.hsv(float(i)/len(values)) for i in xrange(len(values))]
    n, bins, patches = ax.hist(
        values, 10, normed=0, histtype="bar", label=names, color=colors)

    for label in ax.xaxis.get_ticklabels():
        label.set_rotation(-35)
        label.set_horizontalalignment('left')

    ax.plegend = ax.legend(loc="upper right", fancybox=True, shadow=True)

    ax.xaxis.set_major_formatter(mpl_FuncFormatter(
        lambda time, pos: utils.time_to_string(time)[:-7]))
    ax.set_xlim(xmin=0)
    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    return ChartWidget(figure, xlock=True)
Example #20
0
 def style_map(i, j, op_i, op_string, op_j, strength):
     """define the plot style for a given coupling."""
     key = (op_i, op_string, op_j)
     style = {}
     style['linewidth'] = np.abs(strength) * matplotlib.rcParams['lines.linewidth']
     style['color'] = hsv(norm_angle(np.angle(strength)))
     return style
def pair_scatter(experiments, pair_on, save_path, markers=["*", "o"]):
    gpu_ids = np.unique(experiments["str_gpu_id"])
    pair_vals = np.unique(experiments[pair_on])

    if len(pair_vals) != 2:
        raise Exception("The pair_on parameter is invalid")

    colors = cm.hsv((255 * np.arange(len(gpu_ids)) / len(gpu_ids)).astype("uint8"))

    plt.figure()

    for i, gpu_id in enumerate(gpu_ids):
        experiment_inds = experiments["str_gpu_id"] == gpu_id
        experiments_tmp = experiments[experiment_inds]

        exps = list()
        for pair_val in pair_vals:
            exp = experiments_tmp[experiments_tmp[pair_on] == pair_val]

            exp = exp.iloc[np.argmax(exp["iter_time_mu"].values)]
            exps.append(exp)

        exps = pd.DataFrame(exps)

        plt.plot(
            exps["batch_size"],
            exps["iter_time_mu"],
            color=colors[i],
            label="GPU IDs: " + gpu_id,
        )

        for pair in range(2):

            label = None
            if i == 0:
                label = pair_vals[pair]

            plt.scatter(
                exps["batch_size"].iloc[pair],
                exps["iter_time_mu"].iloc[pair],
                color="k",
                marker=markers[pair],
                label=label,
            )

    plt.legend(bbox_to_anchor=(1, 1))

    plt.xlabel("batch size")
    plt.ylabel("avg iter time (s)")

    ylim = list(plt.ylim())
    ylim[0] = 0
    plt.ylim(ylim)

    batch_sizes = np.unique(experiments["batch_size"])
    batch_sizes = batch_sizes[batch_sizes < plt.xlim()[1]]
    plt.xticks(batch_sizes)

    plt.savefig(save_path, dpi=120, bbox_inches="tight")
    plt.close()
Example #22
0
def histogram(names, values, title="", xlabel="", ylabel=""):

    if not names or not values:
        return _empty_chart(title, xlabel, ylabel)

    figure = mpl_Figure()
    canvas = mpl_FigureCanvas(figure)
    figure.set_canvas(canvas)

    ax = figure.add_subplot(111, projection=BasicChart.name)

    colors = [cm.hsv(float(i) / len(values)) for i in xrange(len(values))]
    n, bins, patches = ax.hist(values,
                               10,
                               normed=0,
                               histtype="bar",
                               label=names,
                               color=colors)

    for label in ax.xaxis.get_ticklabels():
        label.set_rotation(-35)
        label.set_horizontalalignment('left')

    ax.plegend = ax.legend(loc="upper right", fancybox=True, shadow=True)

    ax.xaxis.set_major_formatter(
        mpl_FuncFormatter(lambda time, pos: utils.time_to_string(time)[:-7]))
    ax.set_xlim(xmin=0)
    ax.set_title(title)
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)

    return ChartWidget(figure, xlock=True)
Example #23
0
 def plot(self, X, class_label):
     rcParams.update({"legend.fontsize": 6})
     # get the class labels
     list_class_label = np.unique(class_label)
     nclass = len(list_class_label)
     # permutation of indices
     # 0 = sepal_length, 1 = sepal_width, 2 = petal_length, 3 = petal_width
     list_permutation = [[[0, 1], [0, 2], [0, 3]], [[1, 2], [1, 3], [2, 3]]]
     # generate figure showing data for all possible combinations of 2 features
     nrow = 2
     ncol = 3
     fig, axs = plt.subplots(nrow, ncol, figsize=(10, 7))
     fig.suptitle("Iris Data")
     for row in range(nrow):
         for col in range(ncol):
             for i, classname in enumerate(list_class_label):
                 idx = np.where(class_label == classname)[0]
                 # scatter plot in x0-x1 plane where x0,x1 are entries 0,1 from list_permutation
                 axs[row,
                     col].scatter(X[list_permutation[row][col][0], idx],
                                  X[list_permutation[row][col][1], idx],
                                  color=cm.hsv((i + 1) / nclass),
                                  s=15,
                                  label=classname)
                 axs[row, col].set_xlabel(
                     self.feature[list_permutation[row][col][0]])
                 axs[row, col].set_ylabel(
                     self.feature[list_permutation[row][col][1]])
                 axs[row, col].legend(loc="upper left")
Example #24
0
def main():
    # generate a fresh DiGraph
    generatedigraph(G)

    # user inputs center nodes
    node = input("Please enter a center node, or press ENTER to quit: ")
    while (node != ""):
        center_nodes.append(int(node))
        node = input("Please enter a center node, or press ENTER to quit: ")

    # obtains the Voronoi cells
    cells = nx.voronoi_cells(G, center_nodes)
    partition = set(map(frozenset, cells.values()))
    cells_list = list(sorted(map(sorted, partition)))
    print(cells_list)

    # adds color corresponding to Voronoi cell
    for i in range(0, len(cells_list)):
        for j in range(0, len(cells_list[i])):
            color_map.append(cm.hsv(1 / (i + .5)))

    pos = nx.spring_layout(G)
    nx.draw_networkx_nodes(G,
                           pos,
                           with_labels=True,
                           node_color=color_map,
                           edge_color='k',
                           node_size=200,
                           alpha=0.5)
    pylab.title('Voronoi cells', fontsize=15)
    pylab.show()
def save(img, mu, counter):
    batch_size, out_shape = img.shape[0], img.shape[1:3]
    marker_list = ["o", "v", "s", "|", "_"]
    directory = os.path.join('../images/landmarks/')
    if not os.path.exists(directory):
        os.makedirs(directory)
    s = out_shape[0] // 8
    n_parts = mu.shape[-2]
    mu_img = (mu + 1.) / 2. * np.array(out_shape)[0]
    steps = batch_size
    step_size = 1

    for i in range(0, steps, step_size):
        plt.imshow(img[i])
        for j in range(n_parts):
            plt.scatter(mu_img[i, j, 1],
                        mu_img[i, j, 0],
                        s=s,
                        marker=marker_list[np.mod(j, len(marker_list))],
                        color=cm.hsv(float(j / n_parts)))

        plt.axis('off')
        fname = directory + str(counter) + '_' + str(i) + '.png'
        plt.savefig(fname, bbox_inches='tight')
        plt.close()
    def createPlotWithCol(self, dataFrames, column, args, doc):
        fig = plt.figure(figsize=(10, 5))
        ax = fig.add_subplot(111)
        ax.set_position([0.1, 0.35, .85, .6])

        fishes_names = [i for i in itertools.chain.from_iterable(args.values())]
        colors = cmx.hsv(np.linspace(0, 1, len(fishes_names)))

        if column == 'Area' or column == 'Circularity':
            for fishName, color in zip(fishes_names, colors):
                data_len = len(getDataByColumn(fishName, column, dataFrames))
                x_perc = np.linspace(0, 100, data_len)
                ax.plot(x_perc, getDataByColumn(fishName, column, dataFrames), label=fishName, color=color)

            x_axix_format = '%.0f%%'
            xticks = mtick.FormatStrFormatter(x_axix_format)
            ax.xaxis.set_major_formatter(xticks)
            ax.grid(True)

            plt.xlabel('Number of slice (%)', labelpad=5)
            plt.ylabel(self.unitsInfo[column])
            
            ax.legend(loc='center', bbox_to_anchor=(0.5, -0.35), ncol=6, prop={'size': 12})

        imgdata = BytesIO()
        fig.savefig(imgdata, format='png')
        imgdata.seek(0)
        img = Image(imgdata)
        img._restrictSize(doc.width, doc.height)

        return img
def find_shorts_open_circuits(datapoints,
                              dev_name="various devices",
                              lot='lot'):
    wafernames = []
    colors = cm.hsv(np.linspace(0, 1, 10))
    datapoints = sorted(datapoints, key=lambda x: x.wafername)
    for i in range(0, len(datapoints)):
        wafernames = np.append(wafernames, datapoints[i].wafername)
    wafernames = list(set(wafernames))
    fig, ax = plt.subplots()
    fig.suptitle("Potential Shorts/Open Circuits for: " + lot + " Device: " +
                 dev_name)
    for i in range(0, len(datapoints)):
        for j in range(0, len(wafernames)):
            plt.subplot(int(len(wafernames) / 3) + 1, 3, j + 1)
            wafer_outline = plt.Circle((5000, 30000),
                                       50000,
                                       color='blue',
                                       fill=False)
            plt.xlabel("X Coordinate")
            plt.ylabel("Y Coordinate")

            plt.ylim(-25000, 85000)
            plt.xlim(-50000, 60000)

            if datapoints[i].Vcomp - .01 <= datapoints[
                    i].Vmeas <= datapoints[i].Vcomp + .01:
                if datapoints[i].wafername == wafernames[j]:
                    if datapoints[i].wafername != datapoints[
                            i - 1].wafername or i == 0:
                        plt.plot(datapoints[i].x_coord,
                                 datapoints[i].y_coord,
                                 color=colors[j],
                                 marker='o',
                                 label=str(wafernames[j]))
                        plt.legend()
                        plt.gcf().gca().add_artist(wafer_outline)
                    else:
                        plt.plot(datapoints[i].x_coord,
                                 datapoints[i].y_coord,
                                 color=colors[j],
                                 marker='o')
            elif datapoints[i].Icomp - .00001 <= datapoints[
                    i].Imeas <= datapoints[i].Icomp + .00001:
                if datapoints[i].wafername == wafernames[j]:
                    if datapoints[i].wafername != datapoints[
                            i - 1].wafername or i == 0:
                        plt.plot(datapoints[i].x_coord,
                                 datapoints[i].y_coord,
                                 color=colors[j],
                                 marker='x',
                                 label=str(wafernames[j]))
                        plt.legend()
                        plt.gcf().gca().add_artist(wafer_outline)
                    else:
                        plt.plot(datapoints[i].x_coord,
                                 datapoints[i].y_coord,
                                 color=colors[j],
                                 marker='x')
Example #28
0
def animate(i):
    x_ = x[i]
    y_ = y[i]
    z_ = z[i]
    n = int(i / tb) * float(tb / N)
    print(i, n)
    cm_ = cm.hsv(n)
    ax.scatter(x_, y_, z_, s=40, alpha=0.3, marker="o", c=cm_)
Example #29
0
def np_batch_colour_map(heat_map):
    c = heat_map.shape[-1]
    colour = []
    for i in range(c):
        colour.append(cm.hsv(float(i / c))[:3])
    np_colour = np.array(colour)
    colour_map = np.einsum('bijk,kl->bijl', heat_map, np_colour)
    return colour_map
Example #30
0
def batch_colour_map(heat_map):
    c = heat_map.get_shape().as_list()[-1]
    colour = []
    for i in range(c):
        colour.append(cm.hsv(float(i / c))[:3])
    colour = tf.constant(colour)
    colour_map = tf.einsum('bijk,kl->bijl', heat_map, colour)
    return colour_map
Example #31
0
def batch_colour_map(heat_map, device):
    c = heat_map.shape[1]
    colour = []
    for i in range(c):
        colour.append(cm.hsv(float(i / c))[:3])  # does that work?
    colour = torch.tensor(colour, dtype=torch.float).to(device)
    colour_map = contract('bkij, kl -> blij', heat_map, colour)
    return colour_map
Example #32
0
def np_batch_colour_map(heat_map, device):
    c = heat_map.shape[1]
    colour = []
    for i in range(c):
        colour.append(cm.hsv(float(i / c))[:3])
    np_colour = np.array(colour).to(device)
    colour_map = contract('bkij,kl->blij', heat_map, np_colour)
    return colour_map
Example #33
0
def show_histogram(values):
    n, bins, patches = plt.hist(values.reshape(-1), 50, normed=1)
    bin_centers = 0.5 * (bins[:-1] + bins[1:])

    for c, p in zip(normalize(bin_centers), patches):
        plt.setp(p, 'facecolor', cm.hsv(c))

    plt.show()
Example #34
0
def plot_2Ddata(X, y, dots_alpha=.5, noticks=False, ax=None):
    ax = plt if ax is None else ax
    colors = cm.hsv(np.linspace(0, .7, len(np.unique(y))))
    for i, label in enumerate(np.unique(y)):
        ax.scatter(X[y==label][:,0], X[y==label][:,1], color=colors[i], alpha=dots_alpha)
    if noticks:
        ax.set_xticks([])
        ax.set_yticks([])
Example #35
0
def getColColor(ch):
    if ch >= 1 and ch <= 59: color = cm.hsv(0. / 8.)
    elif ch >= 61 and ch <= 119: color = cm.hsv(1. / 8.)
    elif ch >= 121 and ch <= 179: color = cm.hsv(2. / 8.)
    elif ch >= 181 and ch <= 239: color = cm.hsv(3. / 8.)
    elif ch >= 241 and ch <= 299: color = cm.hsv(4. / 8.)
    elif ch >= 301 and ch <= 359: color = cm.hsv(5. / 8.)
    elif ch >= 361 and ch <= 419: color = cm.hsv(6. / 8.)
    elif ch >= 421 and ch <= 479: color = cm.hsv(7. / 8.)
    return color
Example #36
0
def command(paths):
    """ Show a lowest elevation image. """
    # order
    index = dict(
        NL60=0,
        NL61=1,
        nhb=2,
        ess=3,
        emd=4,
        JAB=5,
    )

    # load
    d_rang, d_elev, d_anth = {}, {}, {}
    for p in paths:
        with h5py.File(p, 'r') as h5:
            for r in h5:
                if r in d_rang or r == 'ase':
                    continue
                d_rang[r] = h5[r]['range'][:]
                d_elev[r] = h5[r]['elevation'][:]
                d_anth[r] = h5[r].attrs['antenna_height']
    radars = d_anth.keys()
    elev = np.ma.empty((len(radars),) + d_rang[radars[0]].shape)
    rang = np.ma.empty((len(radars),) + d_rang[radars[0]].shape)
    anth = np.empty((len(radars), 1, 1))
    for r in radars:
        elev[index[r]] = np.ma.masked_equal(d_elev[r], config.NODATAVALUE)
        rang[index[r]] = np.ma.masked_equal(d_rang[r], config.NODATAVALUE)
        anth[index[r]] = float(d_anth[r]) / 1000

    # calculate
    theta = calc.calculate_theta(
        rang=rang, elev=np.radians(elev), anth=anth,
    )
    alt = calc.calculate_height(
        theta=theta, elev=np.radians(elev), anth=anth,
    )
    which = np.ma.where(
        alt == alt.min(0),
        np.indices(alt.shape)[0],
        -1,
    ).max(0)
    what = alt.min(0)

    # colors
    hue = cm.hsv(colors.Normalize(vmax=len(radars))(which), bytes=True)
    sat = 1 - colors.Normalize(vmax=5, clip=True)(what)[..., np.newaxis]

    hue[..., :3] *= sat
    hue[sat.mask[..., 0]] = 255
    Image.fromarray(hue).save('elevation_image.png')
    return 0
Example #37
0
def create_pred_movie_no_conf(conf, predList, moviename, outmovie, outtype):
    predLocs, predscores, predmaxscores = predList
    #     assert false, 'stop here'
    tdir = tempfile.mkdtemp()

    cap = cv2.VideoCapture(moviename)
    nframes = int(cap.get(cvc.FRAME_COUNT))

    cmap = cm.get_cmap('jet')
    rgba = cmap(np.linspace(0, 1, conf.n_classes))

    fig = mpl.figure.Figure(figsize=(9, 4))
    canvas = FigureCanvasAgg(fig)
    for curl in range(nframes):
        framein = myutils.readframe(cap, curl)
        framein = crop_images(framein, conf)

        fig.clf()
        ax1 = fig.add_subplot(1, 2, 1)
        ax1.imshow(framein[:, :, 0], cmap=cm.gray)
        ax1.scatter(predLocs[curl, :, 0, 0], predLocs[curl, :, 0, 1],  # hold=True,
                    c=cm.hsv(np.linspace(0, 1 - old_div(1., conf.n_classes), conf.n_classes)),
                    s=20, linewidths=0, edgecolors='face')
        ax1.axis('off')
        ax2 = fig.add_subplot(1, 2, 2)
        if outtype == 1:
            curpreds = predscores[curl, :, :, :, 0]
        elif outtype == 2:
            curpreds = predscores[curl, :, :, :, 0] * 2 - 1

        rgbim = create_pred_image(curpreds, conf.n_classes)
        ax2.imshow(rgbim)
        ax2.axis('off')

        fname = "test_{:06d}.png".format(curl)

        # to printout without X.
        # From: http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
        # The size * the dpi gives the final image size
        #   a4"x4" image * 80 dpi ==> 320x320 pixel image
        canvas.print_figure(os.path.join(tdir, fname), dpi=80)

        # below is the easy way.
    #         plt.savefig(os.path.join(tdir,fname))

    tfilestr = os.path.join(tdir, 'test_*.png')
    mencoder_cmd = "mencoder mf://" + tfilestr + " -frames " + "{:d}".format(
        nframes) + " -mf type=png:fps=15 -o " + outmovie + " -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=2000000"
    os.system(mencoder_cmd)
    cap.release()
Example #38
0
    def _on_update(self, histogram, rois):
        if histogram not in self.map:
            return
        source, s_out = self.map[histogram]
        N = len(rois)
        data = source()

        gray = self._make_gray(data)
        s_out.data = regular_array2rgbx(gray)
        for i in range(N):
            color = (255 * plt_cm.hsv([float(i) / max(N, 10)])).astype('uint8')
            color = regular_array2rgbx(color)
            r = rois[i]
            mask = (data < r.right) & (data >= r.left)
            s_out.data[mask] = color
        s_out.update_plot()
def plot_seimicity_rate(earthquakes, time = 'hour', figsize = (8,8)):
    '''
    Function get from Thomas Lecocq
    http://www.geophysique.be/2013/09/25/seismicity-rate-using-obspy-and-pandas/
    '''
    
    m_range = (-1,11)
    time = time.lower()
    
    if time == 'second':
        time_format = '%y-%m-%d, %H:%M:%S %p'
    elif time == 'minute':
        time_format = '%y-%m-%d, %H:%M %p'
    elif time == 'hour':
        time_format = '%y-%m-%d, %H %p'
    elif time == 'day':
        time_format = '%y-%m-%d'
    elif time == 'month':
        time_format = '%y-%m'
    elif time == 'year':
        time_format = '%y'
    else:
        time_format = '%y-%m-%d, %H %p'
    
    df = eq2df(earthquakes)

    #Arrange quakes by their magnitude and color appropiately
    
    bins = np.arange(m_range[0], m_range[1])
    labels = np.array(["[%i:%i)"%(i,i+1) for i in bins])
    colors = [cm.hsv(float(i+1)/(len(bins)-1)) for i in bins]
    df['Magnitude_Range'] = pd.cut(df['mag'], bins=bins, labels=False)
    
    df['Magnitude_Range'] = labels[df['Magnitude_Range'].values]
    
    df['Year_Month_day'] = [di.strftime(time_format) for di in df.index]
    
    rate = pd.crosstab(df.Year_Month_day, df.Magnitude_Range)
    
    rate.plot(kind='bar',stacked=True,color=colors,figsize=figsize)
    plt.legend(loc='best')
    plt.ylabel('Number of earthquakes')
    plt.xlabel('Date and Time')
    plt.tight_layout()
    plt.grid()
    plt.show()
def plot_mse(mse_list,label_list):
    for i,mse in enumerate(mse_list):
        c = cm.hsv(np.linspace(0,1,len(mse_list)+1))
        data_x = range(mse.shape[0])
        data_y = mse;
        plt.plot(data_x,data_y,color=c[i,:])
    plt.title('Sparse autoencoder training curve MSE')
    plt.xlabel('Epoch')
    plt.ylabel('MSE')
    plt.legend(label_list,'upper right')
    plt.grid(True)
    plt.xlim(0,2000)
    plt.ylim(0,100)
    f = plt.gcf();
    f.set_size_inches(19.2,10.8)
    plt.savefig('../result_images/mnist_dictionary_training.png',dpi=100)
    plt.close()
Example #41
0
def gen_colors(clusters):
    """
    Takes 'clusters' and creates a list of colors so a cluster has a color.
    
    :param clusters: A flat list of integers where an integer represents which
        cluster the information belongs to.
    :type clusters: list
    
    :returns: colorm : list
        A list of colors obtained from matplotlib colormap cm.hsv. The
        length of 'colorm' is the same as the number of distinct
        clusters.
    """
    import matplotlib.cm as cm
    
    n = len(set(clusters))
    colorm = [cm.hsv(i * 1.0 /n, 1) for i in xrange(n)]
    return colorm
Example #42
0
    def DisplaySavedMapFrame(self, worldFrame, resourcesGRMaxE, frameNo, colours, creatSpec):
        TileBlitSize = (int(self.tw*(self.RESIZE[0]/float(self.SIZE[0]))), int(self.tw*(self.RESIZE[1]/float(self.SIZE[1]))))
        sizeRat0 = self.RESIZE[0]/float(self.SIZE[0])
        sizeRat1 = self.RESIZE[1]/float(self.SIZE[1])
        done = False
        step = 0
        while not done:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    done = True
                    pygame.quit()
                    return
            if step == 0:
                t0 = time.time()
                self.screen.fill(self.WHITE)
                resources = worldFrame[2]
                for a,b in np.ndindex((resources.shape[0], resources.shape[1])):
                    x, y = self.gridWidth-a-1, self.gridHeight-b-1
                    image = pygame.transform.scale(self.gameMap.get_tile_image(x,y,0), TileBlitSize) #pre-scaled at load time
                    self.screen.blit(image, self.TransformMap(np.array([x, y])))
                    if resourcesGRMaxE[0][x][y] > 0:
                        if len(worldFrame) == 4:
                            resourcesGRMaxE[1][x][y] *= worldFrame[3]
                        tempTransPos = self.TransformResourcePos(np.array([x,y]))
                        polygonPos = [(tempTransPos[0], tempTransPos[1]+int((self.th/16.)*sizeRat1)), (tempTransPos[0]+int((self.tw*7./16.)*sizeRat0), tempTransPos[1]+int((self.th/2.)*sizeRat1)), (tempTransPos[0], tempTransPos[1]+int((self.th*15./16.)*sizeRat1)), (tempTransPos[0]-int((self.tw*7./16.)*sizeRat0), tempTransPos[1]+int((self.tw/4.)*sizeRat1))]
                        polygonColour = self.RED[0]*worldFrame[2][x][y]/float(resourcesGRMaxE[1][x][y])
                        pygame.draw.aalines(self.screen, [polygonColour, 0, 0], True, polygonPos, 1)
                        #pygame.draw.polygon(self.screen, PolygonColourArray[x][y][step], PolygonPosArray[x][y], 1)
                t1 = time.time()

                for i in xrange(len(worldFrame[0])):
                    for j in xrange(len(creatSpec)):
                        if worldFrame[0][i][0] == creatSpec[j][0]:
                            creaturePos = self.TransformPos(np.array([worldFrame[0][i][1], worldFrame[0][i][2]]))
                            creatureColour = cm.hsv(colours[j], bytes=True)[0:3]
                            pygame.draw.circle(self.screen, self.WHITE, creaturePos, 5)
                            pygame.draw.circle(self.screen, self.BLACK, creaturePos, 4)
                            pygame.draw.circle(self.screen, creatureColour, creaturePos, 2)
                t2 = time.time()
                
                print('Frame time = %s, for1 = %s, for2 = %s' % (time.time()-t0, t1-t0, t2-t1))
                pygame.display.flip()
            self.clock.tick(15)
            step += 1
def plot_G(ax, Gs, weights, intersect):
    
    G_x=np.arange(0,5,.001)
    l = len(Gs)
    G_ys = []
    for i in xrange(l):
        c = cm.hsv(float(i)/l,1)
        mu = Gs[i][0]
        var = Gs[i][1]
        
        G_y = mlab.normpdf(G_x, mu, var**.5)*weights[i]
        G_ys.append(G_y)
        ax.plot(G_x,G_y,color=c)
        ax.plot(mu,-.001,"^",ms=10,alpha=.7,color=c)
    
    #ax.plot(G_x,np.power(G_ys[1]-G_ys[0],1),color='k')
    if intersect[0] !=None:
        ax.plot(intersect[0],intersect[1],"|",ms=10,alpha=.7,color='k')
    ax.plot([0,5],[0,0],color='k')
def plot_seimicity_rate(earthquakes, time="hour", figsize=(12, 8)):
    """
    Function get from Thomas Lecocq
    http://www.geophysique.be/2013/09/25/seismicity-rate-using-obspy-and-pandas/
    """

    m_range = (-1, 11)
    time = time.lower()

    if time == "second":
        time_format = "%y-%m-%d, %H:%M:%S %p"
    elif time == "minute":
        time_format = "%y-%m-%d, %H:%M %p"
    elif time == "hour":
        time_format = "%y-%m-%d, %H %p"
    elif time == "day":
        time_format = "%y-%m-%d"
    elif time == "month":
        time_format = "%y-%m"
    elif time == "year":
        time_format = "%y"
    else:
        time_format = "%y-%m-%d, %H %p"

    df = eq2df(earthquakes)

    bins = np.arange(m_range[0], m_range[1])
    labels = np.array(["[%i:%i)" % (i, i + 1) for i in bins])
    colors = [cm.hsv(float(i + 1) / (len(bins) - 1)) for i in bins]
    df["Magnitude_Range"] = pd.cut(df["mag"], bins=bins, labels=False)

    df["Magnitude_Range"] = labels[df["Magnitude_Range"].values]

    df["Year_Month_day"] = [di.strftime(time_format) for di in df.index]

    rate = pd.crosstab(df.Year_Month_day, df.Magnitude_Range)

    rate.plot(kind="bar", stacked=True, color=colors, figsize=figsize)
    plt.legend(bbox_to_anchor=(1.20, 1.05))
    plt.ylabel("Number of earthquakes")
    plt.xlabel("Date and Time")
    plt.show()
    def simple_plot(self, fn_out):

        cps = self.mus
        plt.rc('grid',color='0.75',linestyle='l',linewidth='0.1')
        fig, ax_arr = plt.subplots(1,3)
        fig.set_figwidth(9)
        fig.set_figheight(4)
        axescolor  = '#f6f6f6'
        print ax_arr 
        print self.bics
        print self.params

        ax_arr[1].plot(self.params, self.bics)

        n, bins, patches = ax_arr[0].hist(cps,alpha=.9,ec='none',normed=1,color='#8DABFC',bins=len(cps)/10)
        #self.addGMM(gX.gmm, axarr[1,1], cps, gX.labels, overlaps)
        
        G_x=np.arange(0,max(cps)+1,.1)
        l = self.gmm.means.shape[0]
        
        for i in xrange(l):
            c = cm.hsv(float(i)/l,1)
            mu = self.gmm.means[i,0]
            #var = self.gmm.covars[i][0][0]
            var = self.gmm.covars[i]

            G_y = mlab.normpdf(G_x, mu, var**.5)*self.gmm.weights[i]
            ax_arr[0].plot(G_x,G_y,color=c)
            ax_arr[0].plot(mu,-.001,"^",ms=10,alpha=.7,color=c)
        
        if np.amax(cps)<2:
            ax_arr[0].set_xlim(0,2)
        ylims = ax_arr[0].get_ylim()
        if ylims[1] > 10:
            ax_arr[0].set_ylim(0,10)

        fig.sca(ax_arr[2]) 
        dendro = hclust.dendrogram(self.Z, orientation='right')
        ylims = ax_arr[2].get_ylim()
        ax_arr[2].set_ylim(ylims[0]-1, ylims[1]+1)

        fig.savefig(fn_out)
Example #46
0
    def draw_data(self, data):
        totalsize = sum(zip(*data)[1])     # get sum of subentry sizes
        unit = 1.5 * np.pi / totalsize

        angle = 0.5 * np.pi
        if self.log:
            maxy = max(map(np.log2, zip(*data)[2]))
        else:
            maxy = max(zip(*data)[2])
        for d in data:
            relangle = unit * d[1]

            if len(d[3]) > 0 or self.mode == 'user':
                # scale colours since the legend occupies a quarter
                scaledangle = (angle - 0.5*np.pi) * (2 / 1.5)
                colour = cm.hsv(scaledangle/(2*np.pi))
            else:
#                colour = cm.Greys(scaledangle/(2*np.pi))
                colour = "#999999"

            if self.log:
                # take logarithm to accomodate for big differences
                y = np.log2(d[2])
            else:
                y = d[2]

            bar = ax.bar(angle, y, width=relangle, bottom=maxy*0.2,
                         color=colour, label=d[0],
                         picker=True)
            angle += relangle

            if self.mode == 'dir':
                desc = '{0}\n{1}G'.format(d[0], d[1])
            elif self.mode == 'user':
                desc = '{0}\n{1}%'.format(d[0], d[1])
            self.draw_desc(bar[0], d, desc)

        self.draw_legend(maxy)

        fig.canvas.draw()
Example #47
0
def plot_2d_GMMs(X, labels, means, covs, percentcontour=0.66, npoints=30):
    """
    Given an observation array, a label vector (integer values), and GMM mean
    and covariance parameters, plot the clusters and parameters.
    """

    clabels = set(labels)
    K = len(clabels)

    if len(means) != len(covs) != K:
        raise ValueError("Expecting the number of unique labels, means and"
                         "covariances to be the same!")

    phi = np.linspace(-np.pi, np.pi, npoints)

    circle = np.array([np.sin(phi), np.cos(phi)]).T

    figure(figsize=(10, 10))
    gca()

    colors = cm.hsv(np.arange(K)/float(K))
    for k, col in zip(clabels, colors):

        # points
        my_members = labels == k
        scatter(X[my_members, 0], X[my_members, 1], c=col, marker='o', s=20)

        # means
        cluster_center = means[k, :]
        scatter(cluster_center[0], cluster_center[1], c=col, marker='o', s=200)

        # covariance
        L = la.cholesky(np.array(covs[k]) * chi2.ppf(percentcontour, [3])
                        + 1e-5 * np.eye(covs[k].shape[0]))
        covpoints = circle.dot(L) + means[k, :]
        plot(covpoints[:, 0], covpoints[:, 1], color=col, linewidth=3)

    axis('tight')
    axis('equal')
    title('Clusters')
Example #48
0
def plot_distances(x, y, labels):
    print "----"
    print labels
    print x
    print y
    print "----"

    fig, ax = plt.subplots()
    colors = np.random.rand(21)  # 21 datasets
    dataset_dict = dict()
    markers = dict()
    markers['RAND'] = '>'
    markers['SMAC'] = 'o'
    markers['TPE'] = (5, 1)

    # shape by strategy 
    # color by dataset
    color_index = 0
    for p in range(0, len(x)):
        tmp = labels[p].split('.')
        dataset = tmp[0]

        dataset_index = datasets.index(dataset)
        color = cm.hsv(dataset_index / 25., 1)

        strategy = tmp[1]
        plt.plot(x[p], y[p], marker=markers[strategy], c=color, alpha=.75, label=labels[p])

    # plt.tight_layout()
    plt.title('error variance vs configuration dissimilarity')
    plt.xlabel('MCPS dissimilarity')
    plt.ylabel('Error variance')
    # TODO fix legend
    # handles, labels = ax.get_legend_handles_labels()
    # lgd = ax.legend(handles, labels, loc='center right', bbox_to_anchor=(0.5,-0.1), numpoints=1)
    plt.savefig('../distances%s/_all.png' % suffix, dpi=200, bbox_inches='tight')
    plt.close("all")
Example #49
0
 def __init__(self):
     self.read_block_par_file()
     self.nblocks = len(self.blocks)
     self.fibers_per_block = len(self.blocks[1])
     self.reach = self.fiber_reach()
     self.colors = [cm.hsv(x) for x in np.linspace(0,1,len(self.blocks))]
Example #50
0
    def create_pred_movie(self, movie_name, out_movie, max_frames=-1, flipud=False, trace=True):
        conf = self.conf
        sess = self.init_net(0,True)
        predLocs, pred_scores, pred_max_scores = self.classify_movie(movie_name, sess, end_frame=max_frames, flipud=flipud)
        tdir = tempfile.mkdtemp()

        cap = movies.Movie(movie_name)
        nframes = int(cap.get_n_frames())
        if max_frames > 0:
            nframes = max_frames

        fig = mpl.figure.Figure(figsize=(9, 4))
        canvas = FigureCanvasAgg(fig)
        sc = self.conf.unet_rescale

        color = cm.hsv(np.linspace(0, 1 - 1./conf.n_classes, conf.n_classes))
        trace_len = 30
        for curl in range(nframes):
            frame_in = cap.get_frame(curl)
            if len(frame_in) == 2:
                frame_in = frame_in[0]
                if frame_in.ndim == 2:
                    frame_in = frame_in[:,:, np.newaxis]
            frame_in = PoseTools.crop_images(frame_in, conf)

            if flipud:
                frame_in = np.flipud(frame_in)
            fig.clf()
            ax1 = fig.add_subplot(1, 1, 1)
            if frame_in.shape[2] == 1:
                ax1.imshow(frame_in[:,:,0], cmap=cm.gray)
            else:
                ax1.imshow(frame_in)
            xlim = ax1.get_xlim()
            ylim = ax1.get_ylim()

            ax1.scatter(predLocs[curl, :, 0],
                        predLocs[curl, :, 1],
                c=color*0.9, linewidths=0,
                edgecolors='face',marker='+',s=45)
            if trace:
                for ndx in range(conf.n_classes):
                    curc = color[ndx,:].copy()
                    curc[3] = 0.5
                    e = np.maximum(0,curl-trace_len)
                    ax1.plot(predLocs[e:curl,ndx,0],
                             predLocs[e:curl, ndx, 1],
                             c = curc,lw=0.8)
            ax1.axis('off')
            ax1.set_xlim(xlim)
            ax1.set_ylim(ylim)
            fname = "test_{:06d}.png".format(curl)

            # to printout without X.
            # From: http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
            # The size * the dpi gives the final image size
            #   a4"x4" image * 80 dpi ==> 320x320 pixel image
            canvas.print_figure(os.path.join(tdir, fname), dpi=160)

            # below is the easy way.
        #         plt.savefig(os.path.join(tdir,fname))

        tfilestr = os.path.join(tdir, 'test_*.png')
        mencoder_cmd = "mencoder mf://" + tfilestr + " -frames " + "{:d}".format(
            nframes) + " -mf type=png:fps=15 -o " + out_movie + " -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=2000000"
        os.system(mencoder_cmd)
        cap.close()
        tf.reset_default_graph()
Example #51
0
import numpy as np
import matplotlib.pylab as plt
import matplotlib.cm as cm

loci = 10000
runs = 200
data = np.zeros((runs,loci))

i = 0
for line in open('out.txt', 'rb'):
    hist = line.split()
    data[i,int(hist[0])-1] = int(hist[2])
    if (int(hist[0]) == loci):
        i+=1

for i in range(15):
    print sum(data[i,:])
    plt.plot(range(loci),data[i,:], 'o', color=cm.hsv(i/15.,1), label='Generation %i'%(5*i))
plt.xlabel("Block Width")
plt.ylabel("Count")
plt.legend()
plt.show()
#convert dates into float numbers (can be inefficient with a large amount of data)
x = [date2num(date) for (date, value) in data]
y = [value for (date, value) in data]

#preparing to plot
fig = plt.figure()
graph = fig.add_subplot(111)
graph.grid(True)
y_max = 70000  # max range of y-axis
width = 0.3
plt.yticks(range(0, 75000, 2500))
plt.axis([x[0]-1, x[len(x)-1]+1, 0, y_max])

# Plot the data
for i in range(len(data)):
    graph.bar(data[i][0], data[i][1], width=width, color=cm.hsv(int(data[i][1]/255)))

#formatting dates
dateFmt = mpl.dates.DateFormatter('%Y-%m-%d')
graph.xaxis.set_major_formatter(dateFmt)
daysLoc = mpl.dates.DayLocator(interval=1)
graph.xaxis.set_major_locator(daysLoc)
fig.autofmt_xdate(bottom=0.15, rotation=45)  # adjust for date labels display
fig.subplots_adjust(left=0.15)

#annotations and titles
x_label = plt.xlabel('\nDate')
plt.setp(x_label, fontsize=24, color='black')
y_label = plt.ylabel('Energy consumption [W]\n')
plt.setp(y_label, fontsize=24, color='black')
title = plt.title('Energy consumption per day\n')
def differential_displacement(base_system, disl_system, burgers_vector, plot_range, 
       neighbor_list = None, neighbor_list_cutoff = None, component = 'standard',
       axes = None, plot_scale = 1, save_file = None, show = True):
    """
    Function for generating a differential displacement plot for a 
    dislocation containing system.
    
    Arguments:
    base_system -- atomman.System defect-free reference system corresponding 
                   to disl_system.
    disl_system -- atomman.System system containing the defect.
    burgers_vector -- 3x1 numpy array for the dislocation's Burgers vector.
    plot_range -- 3x3 numpy array specifying the Cartesian space to include 
                  atoms in the plot.
    
    Optional Keyword Arguments:
    neighbor_list -- pre-computed neighbor list for base_system.
    neighbor_list_cutoff -- cutoff for computing a neighbor list for 
                            base_system.
    component -- indicates the style of the calculation to use.
    axes -- 3x3 numpy array indicating the crystallographic 
                             axes corresponding to the box's Cartesian axes. 
                             If given, only used for transforming the 
                             burgers_vector.
    plot_scale -- scalar for multiplying the magnitude of the differential 
                  displacement arrows.
    save_file -- if given then the plot will be saved to a file with this name.
    show -- Boolean flag for showing the figure. Default is True.  
    """
    #Burgers vector setup
    if axes is not None:
        T = am.tools.axes_check(axes)
        burgers_vector = T.dot(burgers_vector)
    burgers_vector_magnitude = np.linalg.norm(burgers_vector)
    burgers_vector_uvect = burgers_vector / burgers_vector_magnitude    
    
    #neighbor list setup
    if neighbor_list is not None:
        assert neighbor_list_cutoff is None, 'neighbor_list and neighbor_list_cutoff cannot both be given'
    elif neighbor_list_cutoff is not None:
        neighbor_list = am.NeighborList(base_system, neighbor_list_cutoff)
    elif 'neighbors' in base_system.prop:
        neighbor_list = base_system.prop['neighbors']
    elif 'nlist' in base_system.prop:
        neighbor_list = base_system.prop['nlist']
    
    if isinstance(neighbor_list, am.NeighborList):
        objectnlist = True
    else:
        objectnlist = False
    
    #Identify atoms in plot range
    base_pos = base_system.atoms_prop(key='pos')
    plot_range_indices = np.where((base_pos[:, 0] > plot_range[0,0]) & (base_pos[:, 0] < plot_range[0,1]) & 
                                  (base_pos[:, 1] > plot_range[1,0]) & (base_pos[:, 1] < plot_range[1,1]) &
                                  (base_pos[:, 2] > plot_range[2,0]) & (base_pos[:, 2] < plot_range[2,1]))[0]
    
    #initial plot setup and parameters
    fig, ax1, = plt.subplots(1, 1, squeeze=True, figsize=(7,7), dpi=72)
    ax1.axis([plot_range[0,0], plot_range[0,1], plot_range[1,0], plot_range[1,1]])
    atom_circle_radius = burgers_vector_magnitude / 10
    arrow_width_scale = 1. / 200.

    #Loop over all atoms i in plot range
    for i in plot_range_indices:

        #Plot a circle for atom i
        color = cm.hsv((base_pos[i, 2] - plot_range[2,0]) / (plot_range[2,1] - plot_range[2,0]))
        ax1.add_patch(mpatches.Circle(base_pos[i, :2], atom_circle_radius, fc=color, ec='k'))
    
        #make list of all neighbors for atom i
        if objectnlist:
            neighbor_indices = neighbor_list[i]
        else:
            neighbor_indices = neighbor_list[i, 1 : neighbor_list[i, 0] + 1]

        #Compute distance vectors between atom i and its neighbors for both systems        
        base_dvectors = base_system.dvect(int(i), neighbor_indices)
        disl_dvectors = disl_system.dvect(int(i), neighbor_indices)
    
        #Compute differential displacement vectors
        dd_vectors = disl_dvectors - base_dvectors
        
        #Compute centerpoint positions for the vectors
        arrow_centers = base_pos[i] + base_dvectors / 2
        
        if component == 'standard':
            #compute unit distance vectors
            base_uvectors = base_dvectors / np.linalg.norm(base_dvectors, axis=1)[:,np.newaxis]

            #compute component of the dd_vector parallel to the burgers vector
            dd_components = dd_vectors.dot(burgers_vector_uvect)        
            dd_components[dd_components > burgers_vector_magnitude / 2] -= burgers_vector_magnitude
            dd_components[dd_components < -burgers_vector_magnitude / 2] += burgers_vector_magnitude
            
            #scale arrow lengths and vectors
            arrow_lengths = base_uvectors * dd_components[:,np.newaxis] * plot_scale
            arrow_widths = arrow_width_scale * dd_components * plot_scale
        
            #plot the arrows
            for center, length, width in zip(arrow_centers, arrow_lengths, arrow_widths):
                if width > 1e-7:
                    ax1.quiver(center[0], center[1], length[0], length[1], pivot='middle',
                               angles='xy', scale_units='xy', scale=1, width=width)
                
        elif component == 'xy':
            #scale arrow lengths and vectors
            arrow_lengths = dd_vectors[:, :2] * plot_scale
            arrow_lengths[dd_vectors[:, 2] > 0] *= -1
            arrow_widths = arrow_width_scale * (arrow_lengths[:,0]**2+arrow_lengths[:,1]**2)**0.5

            #plot the arrows
            for center, length, width in zip(arrow_centers, arrow_lengths, arrow_widths):
                if width > 1e-7:
                    ax1.quiver(center[0], center[1], length[0], length[1], width=width,
                               pivot='middle', angles='xy', scale_units='xy', scale=1)

    if save_file is not None:
        plt.savefig(save_file, dpi=800)
    if show == False:
        plt.close(fig)
    plt.show()        
Example #54
0
def file_size_over_time_plot(plot_type="bar", given_machine=None, trim=True, \
start_date=None, return_svg_data=False):
    """Makes a plot of the amount of space the project files took up at
    specific times.
    """
    # Get the data and structure it

    data = get_formatted_data()

    data = sorted(data, key=itemgetter(3))
    grouped_data = [list(g) for k, g in itertools.groupby(data, itemgetter(3))]

    sorted_data = trim_data(grouped_data, trim)
    if start_date is not None:
        sorted_data = [p for p in sorted_data if p[1][0] > start_date]

    # Add the additional days to the project tp use when plotting
    for project in sorted_data:
        for i in range(1, len(project[0])):
            project[1].append(project[1][0] + datetime.timedelta(days=i))

    # Plot

    fig = plt.figure()
    ax = fig.add_subplot(111)
    stack_heights = defaultdict(int)

    bytes_per_gigabyte = 1024. ** 3

    machines = set([])
    for group in sorted_data:
        machines.add(group[2])
    mc_val = dict(zip(machines, [float(i) / len(machines) for i in range(len(machines))]))
    if given_machine is not None:
        filtered_grouped_data = [group for group in sorted_data if group[2] == given_machine]
        sorted_data = filtered_grouped_data
    for i, group in enumerate(sorted_data):
        clr = cm.hsv(mc_val[group[2]])
        sizes = [s / bytes_per_gigabyte for s in group[0]]
        days = group[1]
        heights = []
        for day in days:
            heights.append(stack_heights[day])

        if plot_type == 'bar':
            ax.bar(days, sizes, bottom=heights, color=clr, width=1.0, lw=0.1)

        for size, day in zip(sizes, days):
            stack_heights[day] += size

    plt.ylabel('Size (GB)')
    figure_title = 'Dataset sizes'
    if given_machine is not None:
        figure_title += ' - Machine ' + given_machine
    ax.set_title(figure_title)

    if plot_type == 'plot':
        sorted_stacked = sorted(stack_heights.items(), key=itemgetter(0))
        days = [l[0] for l in sorted_stacked]
        stacks = [l[1] for l in sorted_stacked]
        zip_of_data = dict(zip(days, stacks))
        daylist = [days[0] + datetime.timedelta(days=x) for x in range(0, (days[-1] - days[0]).days)]
        stacklist = []
        for day in daylist:
            stacklist.append(zip_of_data.get(day, 0))

        plt.plot(daylist, stacklist)

    # fig.savefig("../sizegraphing/stacked_sizes.pdf")
    if return_svg_data:
        fig.set_size_inches(10, 2)
        svg_data = get_svg_data(fig)
        return svg_data
    else:
        plt.show()
Example #55
0
    def create_pred_movie_trx(self, movie_name, out_movie, trx, fly_num, max_frames=-1, start_at=0, flipud=False, trace=True):
        conf = self.conf
        sess = self.init_net(0,True)
        predLocs = self.classify_movie_trx(movie_name, trx, sess, end_frame=max_frames, flipud=flipud, start_frame=start_at)
        tdir = tempfile.mkdtemp()

        cap = movies.Movie(movie_name,interactive=False)
        T = sio.loadmat(trx)['trx'][0]
        n_trx = len(T)

        end_frames = np.array([x['endframe'][0,0] for x in T])
        first_frames = np.array([x['firstframe'][0,0] for x in T]) - 1
        if max_frames < 0:
            max_frames = end_frames.max()

        nframes = max_frames - start_at
        fig = mpl.figure.Figure(figsize=(8, 8))
        canvas = FigureCanvasAgg(fig)
        sc = self.conf.unet_rescale

        color = cm.hsv(np.linspace(0, 1 - 1./conf.n_classes, conf.n_classes))
        trace_len = 3
        cur_trx = T[fly_num]
        c_x = None
        c_y = None
        for curl in range(nframes):
            fnum = curl + start_at
            frame_in = cap.get_frame(curl+start_at)
            if len(frame_in) == 2:
                frame_in = frame_in[0]
                if frame_in.ndim == 2:
                    frame_in = frame_in[:,:, np.newaxis]

            trx_fnum = fnum - first_frames[fly_num]
            x = int(round(cur_trx['x'][0, trx_fnum])) - 1
            y = int(round(cur_trx['y'][0, trx_fnum])) - 1
            theta = -cur_trx['theta'][0, trx_fnum]
            R = [[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]
            # -1 for 1-indexing in matlab and 0-indexing in python
            if c_x is None:
                c_x = x; c_y = y;

            if (np.abs(c_x - x) > conf.imsz[0]*3./8.*2.) or (np.abs(c_y - y) > conf.imsz[0]*3./8.*2.):
                c_x = x; c_y = y


            assert conf.imsz[0] == conf.imsz[1]

            frame_in, _ = multiResData.get_patch_trx(frame_in, c_x, c_y, -math.pi/2, conf.imsz[0]*2, np.zeros([2, 2]))
            frame_in = frame_in[:, :, 0:conf.imgDim]

            if flipud:
                frame_in = np.flipud(frame_in)
            fig.clf()
            ax1 = fig.add_subplot(1, 1, 1)
            if frame_in.shape[2] == 1:
                ax1.imshow(frame_in[:,:,0], cmap=cm.gray)
            else:
                ax1.imshow(frame_in)
            xlim = ax1.get_xlim()
            ylim = ax1.get_ylim()

            hsz_p = conf.imsz[0]/2 # half size for pred
            hsz_s = conf.imsz[0] # half size for showing
            for fndx in range(n_trx):
                ct = T[fndx]
                if (fnum < first_frames[fndx]) or (fnum>=end_frames[fndx]):
                    continue
                trx_fnum = fnum - first_frames[fndx]
                x = int(round(ct['x'][0, trx_fnum])) - 1
                y = int(round(ct['y'][0, trx_fnum])) - 1
                theta = -ct['theta'][0, trx_fnum] - math.pi/2
                R = [[np.cos(theta), -np.sin(theta)], [np.sin(theta), np.cos(theta)]]

                # curlocs = np.dot(predLocs[curl,fndx,:,:]-[hsz_p,hsz_p],R)
                curlocs = predLocs[curl,fndx,:,:] #-[hsz_p,hsz_p]
                ax1.scatter(curlocs[ :, 0]*sc - c_x + hsz_s,
                            curlocs[ :, 1]*sc - c_y  + hsz_s,
                    c=color*0.9, linewidths=0,
                    edgecolors='face',marker='+',s=30)
                if trace:
                    for ndx in range(conf.n_classes):
                        curc = color[ndx,:].copy()
                        curc[3] = 0.5
                        e = np.maximum(0,curl-trace_len)
                        # zz = np.dot(predLocs[e:(curl+1),fndx,ndx,:]-[hsz_p,hsz_p],R)
                        zz = predLocs[e:(curl+1),fndx,ndx,:]
                        ax1.plot(zz[:,0]*sc - c_x + hsz_s,
                                 zz[:,1]*sc - c_y + hsz_s,
                                 c = curc,lw=0.8,alpha=0.6)
            ax1.set_xlim(xlim)
            ax1.set_ylim(ylim)
            ax1.axis('off')
            fname = "test_{:06d}.png".format(curl)

            # to printout without X.
            # From: http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
            # The size * the dpi gives the final image size
            #   a4"x4" image * 80 dpi ==> 320x320 pixel image
            canvas.print_figure(os.path.join(tdir, fname), dpi=300)

            # below is the easy way.
        #         plt.savefig(os.path.join(tdir,fname))

        tfilestr = os.path.join(tdir, 'test_*.png')
        mencoder_cmd = "mencoder mf://" + tfilestr + " -frames " + "{:d}".format(
            nframes) + " -mf type=png:fps=15 -o " + out_movie + " -ovc lavc -lavcopts vcodec=mpeg4:vbitrate=2000000"
        os.system(mencoder_cmd)
        cap.close()
        tf.reset_default_graph()
sel_list = np.sort(toa_sel[0].keys()).astype(list)


# In[9]:


for i,n in enumerate(nums):

    form = {'num':n,'surf':srf_str[surf[i]],'lbl':labels[i],'aod':aods_calipso[i]}
    fig,ax = plt.subplots(2,1,figsize=(12,9))

    ax[0].hist(dftoa[i],bins=40,alpha=1.0,edgecolor='None',label='all retrievals')
    ax[0].axvline(np.mean(dftoa[i]),color='k',lw=3,label='Mean')
    ax[0].axvline(np.median(dftoa[i]),color='grey',ls='--',lw=2,label='Median')
    cs = cm.hsv(np.arange(27)/27.0)
    ms = ['s','*','x','d']
    for j,k in enumerate(np.sort(toa_sel[i].keys())):
        ax[0].axvline(toa_sel[i][k],lw=1,label=k,ls='-',color=tuple(cs[j,:]),marker=ms[j%4],ms=10)
    ax[0].axvspan(np.mean(dftoa[i])-np.std(dftoa[i]), np.mean(dftoa[i])+np.std(dftoa[i]), alpha=0.2, color='red',label='Std')
    ax[0].set_xlabel('DARE TOA [W/m$^2$]')
    ax[0].set_ylabel('Number of solutions')
    box = ax[0].get_position()
    ax[0].set_position([box.x0, box.y0, box.width * 0.65, box.height])


    ax[1].hist(dfsfc[i],bins=40,alpha=1.0,edgecolor='None',label='all retrievals')
    ax[1].axvline(np.mean(dfsfc[i]),color='k',lw=3,label='Mean')
    ax[1].axvline(np.median(dfsfc[i]),color='grey',ls='--',lw=2,label='Median')
    for j,k in enumerate(np.sort(sfc_sel[i].keys())):
        ax[1].axvline(sfc_sel[i][k],lw=1,label=k,ls='-',color=tuple(cs[j,:]),marker=ms[j%4],ms=10)
x = np.linspace(1, 10, 100)
y = np.linspace(1, 2*np.pi, 100)
[X, Z] = np.meshgrid(x, y)


scale = 256.0/360.0

# Auswahl eines Zufaelligen Winkels auf dem Farbkreis
winkel = np.random.random_integers(0, 360, 1)

# Bestimmung des gegenueberliegenden Winkels
co_winkel = (winkel + 180) % 360

print winkel
print co_winkel

winkel_scal = int(winkel * scale)
co_winkel_scal = int(co_winkel * scale)

print cm.hsv(winkel_scal)
print cm.hsv(co_winkel_scal)

ax1 = plt.subplot(1, 2, 1)
ax1.patch.set_facecolor(cm.hsv(winkel_scal))
#plt.pcolor(x, y, Z)
#plt.autoscale(axis='both', tight='both')
ax2 = plt.subplot(1, 2, 2)
ax2.patch.set_facecolor(cm.hsv(co_winkel_scal))

plt.show()
def process_files(xml_files):
    """
    Main entry point.
    """

    ### Define xml files.

    xml_files = sys.argv[1:]

    so_many = len(xml_files)
    print "****This script is about to make png files for %s xml files. ****"  % so_many

    for file in xml_files:

        ### Parse XML file.

        root = etree.parse(file)

        ### Remove extension from xml filename.

        file_name = os.path.splitext(file)[0]

        ### Extract plate type and barcode.

        plate = root.xpath("/*/Header/Parameters/Parameter[@Name='Plate']")[0]
        plate_type = plate.attrib['Value']

        try:
            bar = root.xpath("/*/Plate/BC")[0]
            barcode = bar.text
        except:
            barcode = 'no barcode'

        ### Define Sections.

        Sections = root.xpath("/*/Section")
        much = len(Sections)
        print "****The xml file " + file + " has %s data sections:****" % much
        for sect in Sections:
            print sect.attrib['Name']

        for i, sect in enumerate(Sections):

            ### Extract Parameters for this section.

            path = "/*/Section[@Name='" + sect.attrib['Name'] + "']/Parameters"

            parameters = root.xpath(path)[0]
            print "parameters:"
            print parameters

            ### Parameters are extracted slightly differently depending on Absorbance or Fluorescence read.
            # Attach these to title1, title2, or title3, depending on section which will be the same for all 4 files.

            if  parameters[0].attrib['Value'] == "Absorbance":
                result = extract(["Mode", "Wavelength Start", "Wavelength End", "Wavelength Step Size"], parameters)
                globals()["title"+str(i)] = '%s, %s, %s, %s' % tuple(result)

            else:
                result = extract(["Gain", "Excitation Wavelength", "Emission Wavelength", "Part of Plate", "Mode"], parameters)
                globals()["title"+str(i)] = '%s, %s, %s, \n %s, %s' % tuple(result)

            print "****The %sth section has the parameters:****" %i
            print globals()["title"+str(i)]

            ### Extract Reads for this section.

            Sections = root.xpath("/*/Section")

            reads = root.xpath("/*/Section[@Name='" + sect.attrib['Name'] + "']/*/Well")

            wellIDs = [read.attrib['Pos'] for read in reads]

            data = [(s.text, float(s.attrib['WL']), r.attrib['Pos'])
                     for r in reads
                     for s in r]

            dataframe = pd.DataFrame(data, columns=['fluorescence','wavelength (nm)','Well'])
        
            ### dataframe_rep replaces 'OVER' (when fluorescence signal maxes out) with '3289277', an arbitrarily high number

            dataframe_rep = dataframe.replace({'OVER':'3289277'})

            dataframe_rep[['fluorescence']] = dataframe_rep[['fluorescence']].astype('float')

            ### Create large_dataframe1, large_dataframe2, and large_dataframe3 that collect data for each section
            ### as we run through cycle through sections and files.

            globals()["dataframe_pivot"+str(i)] = pd.pivot_table(dataframe_rep, index = 'wavelength (nm)', columns= ['Well'])
        
            print 'The max fluorescence value in this dataframe is %s'% globals()["dataframe_pivot"+str(i)].values.max()

            globals()["large_dataframe"+str(i)] = pd.concat([globals()["large_dataframe"+str(i)],globals()["dataframe_pivot"+str(i)]])

    ### Plot, making a separate png for each section.

    for i, sect in enumerate(Sections):

        section_name = sect.attrib['Name']
    
        path = "/*/Section[@Name='" + sect.attrib['Name'] + "']/Parameters"
        parameters = root.xpath(path)[0]
    
        if  parameters[0].attrib['Value'] == "Absorbance":
            section_ylim = [0,0.2]
        else:
            section_ylim = [0,40000]

        Alphabet = ['A','B','C','D','E','F','G','H']

        fig, axes = plt.subplots(nrows=3, ncols=3, figsize=(12, 12))
        for j,A in enumerate(Alphabet):
            for k in range(1,12):
                try:
                    globals()["large_dataframe"+str(i)].fluorescence.get(A + str(k)).plot(ax=axes[(j/3)%3,j%3], title=A, c=cm.hsv(k*15), ylim=section_ylim, xlim=[240,800])
                except:
                    print "****No row %s.****" %A

        fig.suptitle('%s \n %s \n Barcode = %s' % (globals()["title"+str(i)], plate_type, barcode), fontsize=14)
        fig.subplots_adjust(hspace=0.3)
        plt.savefig('%s_%s.png' % (file_name, section_name))
        

    return
Example #59
0
    def __init__(self):

        self.TARGET_FPS = 30
        cam_w,cam_h=(640,480)
        timer_w=480
        # self.resolution = (cam_w+timer_w,cam_h)
        
        pygame.init()
        pygame.mouse.set_visible(False)

        # get resolution
        # OVERRIDE - THIS IS SUDDENLY SUPER BUGGY ON MY MACHINE (BUT NOT IAN'S)???
        # self.fullresolution = (int(pygame.display.Info().current_w), int(pygame.display.Info().current_h))
        # self.smallresolution = (int(pygame.display.Info().current_w*2/3), int(pygame.display.Info().current_h*2/3))
        self.fullresolution = (1024,768)
        self.smallresolution = (int(self.fullresolution[0]*2.0/3),int(self.fullresolution[1]*2.0/3))


        #window = pygame.display.set_mode((w,h), DOUBLEBUF)
        #window = pygame.display.set_mode((w,h), FULLSCREEN)
        if options.startfullscreen:
            self.resolution = self.fullresolution
            window = pygame.display.set_mode(self.resolution,pygame.FULLSCREEN) 
            self.fullscreen = 1

        else:
            self.resolution = self.smallresolution
            window = pygame.display.set_mode(self.resolution) # do not start full
            self.fullscreen = 0

        print self.fullresolution    
        print self.resolution

        self.sounds = Sounds()

        #ISPIRO: Load goal image. Pygame handles png transparency gracefully
        self.ball = pygame.image.load("img/gray.png")
        self.ball_w = self.ball.get_width()
        self.ball_h = self.ball.get_height()

        self.brush = pygame.image.load("img/small.png")
        self.brush_w = self.brush.get_width()
        self.brush_h = self.brush.get_height()

        self.vortex = pygame.image.load("img/vortex.png");
        self.vortex_w = self.vortex.get_width()
        self.vortex_h = self.vortex.get_height()
        
        self.sum_surface = pygame.Surface((10,10))

        self.font = pygame.font.SysFont(None,80)

        if options.vicon_file is not None:
            self.simulation_mode = True
        else:
            self.simulation_mode = False
            print "Running in live mode. "\
                  "Possession will hang here if you are not connected to a Vicon Proxy server"

        if self.simulation_mode:
            self.f = open(options.vicon_file,'r')
            # should we read ahead?
            for i in xrange(options.line):
                self.f.readline()
        else:
            # Initialize the object...
            print "Waiting for Vicon..."
            self.vp = ViconProxy()

        if options.objects is None:
            print "Automatic object detection mode"
            while options.objects is None:
                print "Looking for objects..."
                options.objects = self.lookfor_objects()
                # Handle events
                self.handle_events()
        else:
            print "Objects are defined on command line"

        try:
            assert(options.objects is not None)
        except:
            print "Make sure you define 1 or more vicon objects through -o"
            sys.exit(1)

        self.set_surfaces()

        # ISPIRO: Need a mask image for blitting circles
        # original mask to match camera
        self.mask = pygame.Surface((options.camerawidth,options.cameraheight))
        # resized mask
        self.bigmask = pygame.Surface((self.camsurface_w,self.camsurface_h))
        
        self.cameras = []
        for c in options.cameras:
            self.cameras.append(Camera(c,img_size = (options.camerawidth,options.cameraheight),fps=self.TARGET_FPS,mirrored=options.mirrored))

        self.balls = []
        for o in options.objects:
            self.balls.append(Ball(self.f if self.simulation_mode else self.vp,o) )

        # set up team colors
        if options.boygirl:
            # we know there are only two teams
            self.teamcolors = [cm.hsv(0.61),cm.hsv(0.86)]
        else:
            self.teamcolors = [cm.jet(x) for x in np.linspace(0.2,0.8,options.numteams)]
        # set up object colors (using a different colormap)
        # self.objectcolors = [cm.spring(x) for x in np.linspace(0,1,len(options.objects))]
        self.objectcolors = [cm.summer(x) for x in np.linspace(0,1,len(options.objects))]
        
        self.score = [0]*options.numteams
        # self.update_score()
        
        self.accumulator = 0
        self.digit = options.game_time
        self.clock = pygame.time.Clock()
    [('entityListName', '50a'), ('intervalLow', 'f4'), ('unjudged', '50a'), ('judgmentLevel', 'd4'), ('metric', '50a'),
     ('mean', 'f4'), ('stdev', 'f4'), ('intervalType', '50a')])


def createStatsRecord(entityListName, intervalLow, unjudgedAs, judgmentLevel, metricname, mean, stdev, intervalType):
    return np.array([(entityListName, intervalLow, unjudgedAs, judgmentLevel, metricname, mean, stdev, intervalType)],
                    dtype=stats_dtype)


records = []

fig = plt.figure()

allteams = ['CWI', 'LSIS', 'PRIS', 'SCIAITeam', 'UMass_CIIR', 'UvA', 'helsinki', 'hltcoe', 'igpi2012', 'udel_fang',
            'uiucGSLIS']
teamColors = {team: cm.hsv(1. * i / len(allteams), 1) for i, team in enumerate(np.unique(allteams))}

print teamColors


def teamColor(team):
    return teamColors[team]


teamss = []


def createWeightPlot(prefix, entityList, title):
    if len(entityList) == 1:
        entityListName = entityList[0]
    else: