def show_most_influencing(dataX, dataY, scores, showX):
    """Plots the relevant samples

    Arguments:
        dataX {array} -- data array
        dataY {array} -- label array
        scores {array} -- influence scores
        showX {int} -- number of samples to show
    """
    sorted_indices = np.argsort(scores)
    showX = np.min([showX, len(sorted_indices)])
    harmful = sorted_indices[:showX]
    helpful = sorted_indices[-showX:][::-1]

    print('\nHelpful:')
    for pos, idx in enumerate(helpful):
        print('Position: %s | Idx: %s | Score: %s | Class: %s' %
              (pos, idx, scores[idx], int(dataY[idx])))

    print('\nHarmful:')
    for pos, idx in enumerate(harmful):
        print('Position: %s | Idx: %s | Score: %s | Class: %s' %
              (pos, idx, scores[idx], int(dataY[idx])))

    plot_size = int(np.ceil(np.sqrt(showX)))

    fig, axes1 = plt.subplots(plot_size, plot_size, figsize=(15, 10))
    fig.suptitle("Helpful")
    target_idx = 0
    for j in range(plot_size):
        for k in range(plot_size):
            if target_idx < showX:
                idx = helpful[target_idx]
                axes1[j][k].set_axis_off()
                axes1[j][k].plot(dataX[idx])
                axes1[j][k].set_title('Idx: %s | Class: %s' %
                                      (idx, int(dataY[idx])))
            else:
                axes1[j][k].set_visible(False)

            target_idx += 1

    fig, axes1 = plt.subplots(plot_size, plot_size, figsize=(15, 10))
    fig.suptitle("Harmful")
    target_idx = 0
    for j in range(plot_size):
        for k in range(plot_size):
            if target_idx < showX:
                idx = harmful[target_idx]
                axes1[j][k].set_axis_off()
                axes1[j][k].plot(dataX[idx])
                axes1[j][k].set_title('Idx: %s | Class: %s' %
                                      (idx, int(dataY[idx])))
            else:
                axes1[j][k].set_visible(False)

            target_idx += 1

    plt.show()
def compute_ROC_curve(preds, y_val, n_classes):

    '''

    Compute ROC curve and ROC area for each class

    '''

    fpr = dict()
    tpr = dict()
    roc_auc = dict()
    for i in range(n_classes):
        fpr[i], tpr[i], _ = roc_curve(y_val[:, i], preds[:, i])
        roc_auc[i] = auc(fpr[i], tpr[i])

    # Plot ROC curves
    fig, ax = plt.subplots(figsize=(16, 10))
    ax.plot([0, 1], [0, 1], 'k--')
    ax.set_xlim([0.0, 1.0])
    ax.set_ylim([0.0, 1.05])
    ax.set_xlabel('False Positive Rate')
    ax.set_ylabel('True Positive Rate')
    ax.set_title('ROC Curve for Each Class')
    for i in range(n_classes):
        ax.plot(fpr[i], tpr[i], linewidth=3, label='ROC curve (area = %0.2f) for %s' % (roc_auc[i], CLASSES[i]))
    ax.legend(loc="best", fontsize='x-large')
    ax.grid(alpha=.4)
    sns.despine()

    # Save the plot as an image
    fig.savefig('static/auc_plot.jpg', bbox_inches='tight', dpi=150)
    plt.show()
def cmp_overall_qoe_per_region(regions, regionName):
    google_QoE_folder = geographical_data_folder + "google/dataQoE/"
    azure_QoE_folder = geographical_data_folder + "azure/dataQoE/"
    amazon_QoE_folder = geographical_data_folder + "amazon/dataQoE/"

    qoogle_regional_qoes = load_all_session_qoes_per_region(google_QoE_folder)
    azure_regional_qoes = load_all_session_qoes_per_region(azure_QoE_folder)
    amazon_regional_qoes = load_all_session_qoes_per_region(amazon_QoE_folder)

    google_to_draw = []
    azure_to_draw = []
    amazon_to_draw = []
    for r in regions:
        google_to_draw.extend(qoogle_regional_qoes[r])
        azure_to_draw.extend(azure_regional_qoes[r])
        amazon_to_draw.extend(amazon_regional_qoes[r])

    fig, ax = plt.subplots()

    draw_cdf(google_to_draw, styles[0], "Google Cloud CDN")
    draw_cdf(azure_to_draw, styles[1], "Azure CDN (Verizon)")
    draw_cdf(amazon_to_draw, styles[2], "Amazon CloudFront")

    ax.set_xlabel(r'Session QoE (0-5)', fontsize=18)
    ax.set_ylabel(r'Percentage of PlanetLab users', fontsize=18)
    plt.xlim([0, 5])
    plt.ylim([0, 1])
    plt.legend(loc=2)

    imgName = img_folder + "compare_cloud_cdns_QoE_region_" + regionName
    plt.savefig(imgName + ".jpg")
    plt.savefig(imgName + ".pdf")
    plt.savefig(imgName + ".png")
    plt.show()
Пример #4
0
def showArray (array_path1,array_path2):
    for i in range (len(array_path1)):
        path1 = np.load(array_path1[i],mmap_mode = 'r+')
        path2 = np.load(array_path2[i],mmap_mode = 'r+')
        fig, ax = plt.subplots(ncols=2, nrows=1, figsize=(20, 10))
        ax[0].imshow(path1, cmap=plt.cm.gray)
        ax[1].imshow(path2, cmap=plt.cm.gray)
def cmp_overall_qoe_cps():
    google_QoE_folder = geographical_data_folder + "google/dataQoE/"
    azure_QoE_folder = geographical_data_folder + "azure/dataQoE/"
    amazon_QoE_folder = geographical_data_folder + "amazon/dataQoE/"

    qoogle_session_qoes = load_all_session_qoes(google_QoE_folder)
    azure_session_qoes = load_all_session_qoes(azure_QoE_folder)
    amazon_session_qoes = load_all_session_qoes(amazon_QoE_folder)

    fig, ax = plt.subplots()

    draw_cdf(qoogle_session_qoes, styles[0], "Google Cloud CDN")
    draw_cdf(azure_session_qoes, styles[1], "Azure CDN (Verizon)")
    draw_cdf(amazon_session_qoes, styles[2], "Amazon CloudFront")

    ax.set_xlabel(r'Session QoE (0-5)', fontsize=18)
    ax.set_ylabel(r'Percentage of PlanetLab users', fontsize=18)
    plt.xlim([0, 5])
    plt.ylim([0, 1])
    plt.legend(loc=2)

    imgName = img_folder + "compare_cloud_cdns_QoE_overall"
    plt.savefig(imgName + ".jpg")
    plt.savefig(imgName + ".pdf")
    plt.savefig(imgName + ".png")
    plt.show()
Пример #6
0
    def plot_day(self, df, record, label):
        datetimes = [
            datetime.datetime.strptime(d, '%Y-%m-%d') for d in df.index
        ]
        fig, (ax1, ax2) = plt.subplots(2, figsize=(12, 4))
        ax1.xaxis.set_major_locator(self.months)
        ax1.xaxis.set_major_formatter(self.months_fmt)
        ax1.xaxis.set_minor_locator(self.days)
        ax1.grid(True)
        ax1.set_ylabel(label)
        ax1.plot(datetimes, df['boll_band'])

        ax2.grid(True)
        ax2.set_ylabel('Price')
        ax2.plot(datetimes, df['close'], label='price')
        ax2.plot(datetimes, df['boll_ub'], label='boll_ub')
        ax2.plot(datetimes, df['boll'], label='boll')
        ax2.plot(datetimes, df['boll_lb'], label='boll_lb')
        plt.legend()

        fig.autofmt_xdate()
        fig.suptitle(label)
        x = record['Time'].loc[record['transaction'] == 'Buy']
        y = df['boll_band'].loc[x]
        ax1.scatter(x, y, label='test', marker='^', color='green')
        x = record['Time'].loc[record['transaction'] == 'Sell']
        y = df['boll_band'].loc[x]
        ax1.scatter(x, y, label='sell', marker='v', color='red')
        plt.show()
Пример #7
0
def print_eval_result(memoria_best_eval):
    temp_df = pd.DataFrame(memoria_best_eval)
    fig, ax = plt.subplots(figsize=(15,10))
    ff =temp_df.plot(kind='line',ax=ax)
    ff.set_title('Best Fitness by Iteration', size= 28 ) 
    ff.set_xlabel('Iteration',size= 20 )
    ff.set_ylabel('Fitness Evaluation',size= 20 )
Пример #8
0
def plot_sets(partitioner,
              start=0,
              end=10,
              step=1,
              tam=[5, 5],
              colors=None,
              save=False,
              file=None,
              axes=None,
              data=None,
              window_size=1,
              only_lines=False,
              legend=True):

    range = np.arange(start, end, step)
    ticks = []
    if axes is None:
        fig, axes = plt.subplots(nrows=1, ncols=1, figsize=tam)

    for ct, key in enumerate(partitioner.ordered_sets):
        fset = partitioner.sets[key]
        if not only_lines:
            for t in range:
                tdisp = t - (t % window_size)
                fset.membership(0, tdisp)
                param = fset.perturbated_parameters[str(tdisp)]

                if fset.mf == Membership.trimf:
                    if t == start:
                        line = axes.plot([t, t + 1, t], param, label=fset.name)
                        fset.metadata['color'] = line[0].get_color()
                    else:
                        axes.plot([t, t + 1, t],
                                  param,
                                  c=fset.metadata['color'])

                ticks.extend(["t+" + str(t), ""])
        else:
            tmp = []
            for t in range:
                tdisp = t - (t % window_size)
                fset.membership(0, tdisp)
                param = fset.perturbated_parameters[str(tdisp)]
                tmp.append(np.polyval(param, tdisp))
            axes.plot(range, tmp, ls="--", c="blue")

    axes.set_ylabel("Universe of Discourse")
    axes.set_xlabel("Time")
    plt.xticks([k for k in range], ticks, rotation='vertical')

    if legend:
        handles0, labels0 = axes.get_legend_handles_labels()
        lgd = axes.legend(handles0, labels0, loc=2, bbox_to_anchor=(1, 1))

    if data is not None:
        axes.plot(np.arange(start, start + len(data), 1), data, c="black")

    if file is not None:
        plt.tight_layout()
        Util.show_and_save_image(fig, file, save)
Пример #9
0
def display_object(coordinates):
    print("display_object() START ")
    # fig = plt.figure(1, figsize=(10, 5), dpi=90)
    # ax = fig.add_subplot(111)
    fig, ax = plt.subplots(1, figsize=(10, 5))

    latitude_start = -90
    latitude_end = 90
    longitude_start = 0
    longitude_end = 360
    break_between = 30
    break_between_minor = 10

    ax.set_xlim(longitude_start, longitude_end)
    ax.set_ylim(latitude_start, latitude_end)
    ax.set_xticks(np.arange(longitude_start, longitude_end,
                            break_between_minor),
                  minor=True)
    ax.set_yticks(np.arange(latitude_start, latitude_end, break_between_minor),
                  minor=True)
    ax.set_xticks(np.arange(longitude_start, longitude_end, break_between))
    ax.set_yticks(np.arange(latitude_start, latitude_end, break_between))

    ax.grid(which='both')

    # push grid lines behind the elements
    ax.set_axisbelow(True)

    for c in coordinates:
        #plt.scatter(c[0], c[1], marker='o', s=1)
        plt.fill(c[0], c[1])

    plt.show()
Пример #10
0
def draw_graph(graph, graphimg_file):
    """Draw the graph
    """
    fig, ax = plt.subplots()
    elarge = [(u, v) for (u, v, d) in graph.edges(data=True)
              if d['weight'] > 3]
    #print(elarge)
    esmall = [(u, v) for (u, v, d) in graph.edges(data=True)
              if d['weight'] <= 3]
    #print(elarge)
    # Draw the graph with networkx
    #pos=nx.spring_layout(graph)
    pos = nx.random_layout(graph)
    nx.draw_networkx_nodes(graph, pos, node_size=6)
    nx.draw_networkx_edges(graph, pos, edgelist=elarge, width=6)
    nx.draw_networkx_edges(graph,
                           pos,
                           edgelist=esmall,
                           width=6,
                           alpha=0.5,
                           edge_color='b',
                           style='dashed')
    #nx.draw_networkx(graph, pos, node_size=10, with_labels=False)
    # save image
    plt.savefig(graphimg_file)
Пример #11
0
def plot_sets(data, sets, titles, tam=[12, 10], save=False, file=None):
    num = len(sets)
    #fig = plt.figure(figsize=tam)
    maxx = max(data)
    minx = min(data)
    #h = 1/num
    #print(h)
    fig, axes = plt.subplots(nrows=num, ncols=1, figsize=tam)
    for k in np.arange(0, num):
        ticks = []
        x = []
        ax = axes[k]
        ax.set_title(titles[k])
        ax.set_ylim([0, 1.1])
        for key in sets[k].keys():
            s = sets[k][key]
            if s.mf == Membership.trimf:
                ax.plot(s.parameters, [0, 1, 0])
            elif s.mf == Membership.gaussmf:
                tmpx = [kk for kk in np.arange(s.lower, s.upper)]
                tmpy = [s.membership(kk) for kk in np.arange(s.lower, s.upper)]
                ax.plot(tmpx, tmpy)
            elif s.mf == Membership.trapmf:
                ax.plot(s.parameters, [0, 1, 1, 0])
            ticks.append(str(round(s.centroid, 0)) + '\n' + s.name)
            x.append(s.centroid)
        ax.xaxis.set_ticklabels(ticks)
        ax.xaxis.set_ticks(x)

    plt.tight_layout()

    Util.show_and_save_image(fig, file, save)
def showPlot(points):
    plt.figure()
    fig, ax = plt.subplots()
    # 주기적인 간격에 이 locator가 tick을 설정
    loc = ticker.MultipleLocator(base=0.2)
    ax.yaxis.set_major_locator(loc)
    plt.plot(points)
def plot_bars_means(q_mean, qj_mean_v1, qj_var_v1, pj_mean_v1, pj_var_v1, qs_hat_std_ols, qs_hat_avg_ols, simu_kind=""):
  x_pos = 1.5 * np.arange(8)
  print(qs_hat_avg_ols)
  print(qs_hat_std_ols)
  width=0.25
  bar_width=0.25
  fig, ax = plt.subplots()
  bar_ols=ax.bar(x_pos, np.array(qs_hat_avg_ols), yerr=np.array(qs_hat_std_ols), width=bar_width,align='center', alpha=0.5, ecolor='black', capsize=5)
  bar_qj=ax.bar(x_pos+width+width, np.array(qj_mean_v1), yerr=np.array(qj_var_v1),width=bar_width, align='center', alpha=0.5, ecolor='black', capsize=5)
  bar_pj=ax.bar(x_pos+width, np.array(pj_mean_v1), yerr=np.array(pj_var_v1), width=bar_width,align='center', alpha=0.5, ecolor='black', capsize=5)
  bar_q=ax.bar(x_pos+width+width+width, np.array(q_mean), width=bar_width, align='center', alpha=0.5, ecolor='black', capsize=5)
  ax.set_title('Compering mean and variance between the following simulation : '+ simu_kind)
  ax.set_xticks(x_pos)
  names=PARTY_NAMES
  rev_names = [name[::-1] for name in list(names)]
  long_names=[]
  dict = {"פה": "כחול לבן", "ג": "יהדות התורה", "שס": "שס", "מחל": "ליכוד", "ל": "ישראל ביתנו", "טב": "ימינה",
          "אמת": "עבודה גשר מרץ", "ודעם": "הרשימה המשותפת"}

  for name in rev_names:
      long_names.append(dict[name[::-1]][::-1])
  ax.set_xticklabels(long_names,rotation=45)
  ax.set_ylabel('vote precentange ')

  ax.yaxis.grid(True)
  dummy_1 = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)
  dummy_2 = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)
  ax.legend((bar_qj[0], bar_pj[0],bar_ols[0], bar_q), ("qj_hat","pj","qj_ols_hat", "q"))

  # Save the figure and show
  plt.tight_layout()
  plt.savefig('bar_plot_with_error_bars.png')
  plt.show()
Пример #14
0
def plot_images(images, cls_true, cls_pred=None):
    assert len(images) == len(cls_true) == 9

    # Create figure witth 3x3 sub-plots.
    fig, axes = plt.subplots(3, 3)
    fig.subplots_adjust(hspace=0.3, wspace=0.3)

    for i, ax in enumerate(axes.flat):
        # Plot image.
        ax.imshow(images[i].reshape(img_shape), cmap='binary')

        # Show true and predicted classes.
        if cls_pred is None:
            xlabel = "True: {0}".format(cls_true[i])
        else:
            xlabel = "True: {0}, Pred: {1}".format(cls_true[i], cls_pred[i])

        # Show the classes as the label on the x-axis.
        ax.set_xlabel(xlabel)

        # Remove ticks from the plot.
        ax.set_xticks([])
        ax.set_yticks([])

    plt.show()
Пример #15
0
def correlationPGN(dataset):
    allColsAsFeatures = dataset.columns.values[:-1]
    X = dataset[allColsAsFeatures]
    corr_matrix = X.corr()
    # Generate a mask for the upper triangle
    mask = np.zeros_like(corr_matrix, dtype=np.bool)
    mask[np.triu_indices_from(mask)] = True
    # Set up the matplotlib figure
    f, ax = plt.subplots(figsize=(11, 9))
    # Generate a custom diverging colormap
    cmap = sns.diverging_palette(220, 10, as_cmap=True)
    # Draw the heatmap with the mask and correct aspect ratio
    sns_corrplot = sns.heatmap(corr_matrix,
                               mask=mask,
                               cmap=cmap,
                               vmax=1,
                               vmin=-1,
                               center=0,
                               square=True,
                               linewidths=.5,
                               cbar_kws={"shrink": .8})
    sns_corrplot.get_figure()
    path = WORKING_PATH + "/___corrrr.png"
    plt.savefig(path)
    plt.clf()
    return path
Пример #16
0
    def stock_lineplot(self):
        _stock_info = self.get_stock_info()
        # 设置图片尺寸 14" x 7"
        plt.rc('figure', figsize=(14, 7))
        # 设置字体 14
        plt.rc('font', size=14)
        # 不显示网格
        plt.rc('axes', grid=False)
        # 设置背景颜色是白色
        plt.rc('axes', facecolor='white')
        # 显示中文标签
        plt.rcParams['font.sans-serif'] = ['SimHei']
        # 正常显示正负号
        plt.rcParams['axes.unicode_minus'] = False

        y_data = _stock_info['stock_percentage']
        x_data = pd.to_datetime(_stock_info['stock_count_time'])
        _, ax1 = plt.subplots()
        ax1.plot(x_data, y_data)
        # 添加标题和坐标说明
        ax1.set_ylabel(_stock_info.iloc[1][1] + u'百分比')
        ax1.set_xlabel("Day")
        ax1.set_title(u'股票占深交所上市及交易股票总数百分比')
        plt.savefig(self.stock_pltpath + _stock_info.iloc[1][1] + '.' +
                    'png')  # 保存图形到本地
Пример #17
0
    def plotCorrelationHeatMap(self, dataFrame):
        corr = round(dataFrame.corr(), 2)
        mask = np.zeros_like(corr, dtype=np.bool)
        mask[np.triu_indices_from(mask)] = True

        # Set up the matplotlib figure
        f, ax = mpl.subplots(figsize=(26, 26))

        # Generate a custom diverging colormap
        cmap = sns.diverging_palette(220, 10, as_cmap=True)

        # Draw the heatmap with the mask and correct aspect ratio
        sns.heatmap(corr,
                    cmap=cmap,
                    vmax=1,
                    vmin=-1,
                    center=0,
                    linewidths=.2,
                    cbar_kws={"shrink": .7},
                    annot=True,
                    annot_kws={
                        "fontsize": 5,
                        'fontweight': 'bold'
                    })

        f.savefig("Correlation.png")
        return f
Пример #18
0
def plotImages(images_arr):
    fig, axes = plt.subplots(1, 5, figsize=(20,20))
    axes = axes.flatten()
    for img, ax in zip( images_arr, axes):
        ax.imshow(img)
    plt.tight_layout()
    plt.show()
Пример #19
0
def pftsExploreOrderAndPartitions(data, save=False, file=None):
    fig, axes = plt.subplots(nrows=4, ncols=1, figsize=[6, 8])
    data_fs1 = Grid.GridPartitioner(data=data, npart=10).sets
    mi = []
    ma = []

    axes[0].set_title('Point Forecasts by Order')
    axes[2].set_title('Interval Forecasts by Order')

    for order in np.arange(1, 6):
        fts = pwfts.ProbabilisticWeightedFTS("")
        fts.shortname = "n = " + str(order)
        fts.train(data, sets=data_fs1.sets, order=order)
        point_forecasts = fts.forecast(data)
        interval_forecasts = fts.forecast_interval(data)
        lower = [kk[0] for kk in interval_forecasts]
        upper = [kk[1] for kk in interval_forecasts]
        mi.append(min(lower) * 0.95)
        ma.append(max(upper) * 1.05)
        for k in np.arange(0, order):
            point_forecasts.insert(0, None)
            lower.insert(0, None)
            upper.insert(0, None)
        axes[0].plot(point_forecasts, label=fts.shortname)
        axes[2].plot(lower, label=fts.shortname)
        axes[2].plot(upper)

    axes[1].set_title('Point Forecasts by Number of Partitions')
    axes[3].set_title('Interval Forecasts by Number of Partitions')

    for partitions in np.arange(5, 11):
        data_fs = Grid.GridPartitioner(data=data, npart=partitions).sets
        fts = pwfts.ProbabilisticWeightedFTS("")
        fts.shortname = "q = " + str(partitions)
        fts.train(data, sets=data_fs.sets, order=1)
        point_forecasts = fts.forecast(data)
        interval_forecasts = fts.forecast_interval(data)
        lower = [kk[0] for kk in interval_forecasts]
        upper = [kk[1] for kk in interval_forecasts]
        mi.append(min(lower) * 0.95)
        ma.append(max(upper) * 1.05)
        point_forecasts.insert(0, None)
        lower.insert(0, None)
        upper.insert(0, None)
        axes[1].plot(point_forecasts, label=fts.shortname)
        axes[3].plot(lower, label=fts.shortname)
        axes[3].plot(upper)

    for ax in axes:
        ax.set_ylabel('F(T)')
        ax.set_xlabel('T')
        ax.plot(data, label="Original", color="black", linewidth=1.5)
        handles, labels = ax.get_legend_handles_labels()
        ax.legend(handles, labels, loc=2, bbox_to_anchor=(1, 1))
        ax.set_ylim([min(mi), max(ma)])
        ax.set_xlim([0, len(data)])

    plt.tight_layout()

    cUtil.show_and_save_image(fig, file, save)
Пример #20
0
def pre_plot():
    labels = [chr(x) for x in range(ord('A'), ord('H')+1)]
    fig, ax = plt.subplots()
    colors = reversed(plt.cm.hsv(np.linspace(0,1,10)))
    ax.set_color_cycle(colors)
    plt.ylim(-1,6.5)
    return labels
Пример #21
0
def plot_residuals(targets, models, tam=[8, 8], save=False, file=None):
    fig, axes = plt.subplots(nrows=len(models), ncols=3, figsize=tam)

    for c, mfts in enumerate(models, start=0):
        if len(models) > 1:
            ax = axes[c]
        else:
            ax = axes
        forecasts = mfts.forecast(targets)
        res = residuals(targets, forecasts, mfts.order)
        mu = np.mean(res)
        sig = np.std(res)

        if c == 0: ax[0].set_title("Residuals", size='large')
        ax[0].set_ylabel(mfts.shortname, size='large')
        ax[0].set_xlabel(' ')
        ax[0].plot(res)

        if c == 0: ax[1].set_title("Residuals Autocorrelation", size='large')
        ax[1].set_ylabel('ACS')
        ax[1].set_xlabel('Lag')
        ax[1].acorr(res)

        if c == 0: ax[2].set_title("Residuals Histogram", size='large')
        ax[2].set_ylabel('Freq')
        ax[2].set_xlabel('Bins')
        ax[2].hist(res)

    plt.tight_layout()

    Util.show_and_save_image(fig, file, save)
Пример #22
0
def test_receptionmatrix(printvaleur=True):
    Map_hauteur = np.zeros(shape=(50, 50))
    Map_energie = np.zeros(shape=(50, 50))
    Map_hauteur[25, 25] = 5
    Map_energie[25, 25] = 100000000
    # Map_hauteur[5,6] =1
    # Map_energie[5, 6] =100000
    R = 2
    dteta = 5*10**-2
    dh = 0.5*10**-1
    nphoton = 20
    mat = sender(Map_hauteur, 25, 25, Map_energie, R, dteta, dh, nphoton, 1)

    def f(x):
        return np.log10(x)

    f = np.vectorize(f)
    np.set_printoptions(precision=3)
    print(mat)
    fig, ax = plt.subplots()
    ax.matshow(f(mat), cmap=plt.get_cmap("afmhot"))
    if printvaleur:
        for (i, j), z in np.ndenumerate(mat):
            ax.text(j, i, '{:0.01f}'.format(z), ha='center', va='center')
    plt.savefig('uniform_high_res.png', format='svg', dpi=2000)
    fig.show()
Пример #23
0
    def displayPreview(self, img, v, i):
        def handle_close(evt, self):
            self.__previewFigure = None
            self.__previewAxes = [None, None]

        if self.__previewFigure is None:  #preview window is not created yet, lets make it
            plt.ioff()
            self.__previewFigure, self.__previewAxes[0] = plt.subplots()
            divider = make_axes_locatable(self.__previewAxes[0])
            self.__previewAxes[1] = divider.append_axes('right',
                                                        size='5%',
                                                        pad=0.05)
            self.__previewFigure.canvas.mpl_connect(
                'close_event', lambda x: handle_close(x, self)
            )  # if preview figure is closed, lets clear the figure/axes handles so the next preview properly recreates the handles
            plt.ion()
            plt.show()

        for ax in self.__previewAxes:  #clear the axes
            ax.clear()
        img_handle = self.__previewAxes[0].imshow(img)
        self.__previewFigure.colorbar(img_handle, cax=self.__previewAxes[1])
        self.__previewAxes[0].set_title('{0} V, {1} A, {2} Laser'.format(
            v, i, self.laserpower))
        self.__previewFigure.canvas.draw()
        self.__previewFigure.canvas.flush_events()
        time.sleep(
            1e-4)  #pause allows plot to update during series of measurements
Пример #24
0
def single_plot_residuals(targets,
                          forecasts,
                          order,
                          tam=[8, 8],
                          save=False,
                          file=None):
    fig, ax = plt.subplots(nrows=1, ncols=3, figsize=tam)

    res = residuals(targets, forecasts, order)

    ax[0].set_title("Residuals", size='large')
    ax[0].set_ylabel("Model", size='large')
    ax[0].set_xlabel(' ')
    ax[0].plot(res)

    ax[1].set_title("Residuals Autocorrelation", size='large')
    ax[1].set_ylabel('ACS')
    ax[1].set_xlabel('Lag')
    ax[1].acorr(res)

    ax[2].set_title("Residuals Histogram", size='large')
    ax[2].set_ylabel('Freq')
    ax[2].set_xlabel('Bins')
    ax[2].hist(res)

    plt.tight_layout()

    Util.show_and_save_image(fig, file, save)
Пример #25
0
def _vis_proposals(im, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return

    class_name = 'obj'
    im = im[:, :, (2, 1, 0)]
    fig, ax = plt.subplots(figsize=(12, 12))
    ax.imshow(im, aspect='equal')
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        ax.add_patch(
            plt.Rectangle((bbox[0], bbox[1]),
                          bbox[2] - bbox[0],
                          bbox[3] - bbox[1],
                          fill=False,
                          edgecolor='red',
                          linewidth=3.5))
        ax.text(bbox[0],
                bbox[1] - 2,
                '{:s} {:.3f}'.format(class_name, score),
                bbox=dict(facecolor='blue', alpha=0.5),
                fontsize=14,
                color='white')

    ax.set_title(('{} detections with '
                  'p({} | box) >= {:.1f}').format(class_name, class_name,
                                                  thresh),
                 fontsize=14)
    plt.axis('off')
    plt.tight_layout()
    plt.draw()
Пример #26
0
def plot_boundary(theta, theta0):
    ps = [0.75, 0.5, 0.25]
    fig, ax = plt.subplots()
    for p in ps:
        logv = np.log(p / (1 - p))
        x = np.array([-0.5, 0.5])
        if p == 0.25:
            c = "red"  #0.25
        elif p == 0.75:
            c = "blue"  #0.75
        else:
            c = "purple"
        ax.plot(x, -theta[0] / theta[1] * x + (logv - theta0) / theta[1], c=c)
    # y = 1
    ax.scatter(get_first(x_mat, y_vec, 1),
               get_second(x_mat, y_vec, 1),
               label='tab:blue',
               c='tab:blue')
    # y = -1
    ax.scatter(get_first(x_mat, y_vec, -1),
               get_second(x_mat, y_vec, -1),
               label='tab:red',
               c='tab:red')
    ax.grid(True)
    #     ax.set(xlim=(-0.6, 0.6), ylim=(-0.6, 0.6))
    plt.show()
Пример #27
0
def apply_thresholds(image, show=True):
    img = np.copy(image)
    s_channel = cv2.cvtColor(img, cv2.COLOR_BGR2HLS)[:, :, 2]

    l_channel = cv2.cvtColor(img, cv2.COLOR_BGR2LUV)[:, :, 0]

    b_channel = cv2.cvtColor(img, cv2.COLOR_BGR2LAB)[:, :, 2]

    # Threshold color channel
    s_thresh_min = 180
    s_thresh_max = 255
    s_binary = np.zeros_like(s_channel)
    s_binary[(s_channel >= s_thresh_min) & (s_channel <= s_thresh_max)] = 1

    b_thresh_min = 155
    b_thresh_max = 200
    b_binary = np.zeros_like(b_channel)
    b_binary[(b_channel >= b_thresh_min) & (b_channel <= b_thresh_max)] = 1

    l_thresh_min = 225
    l_thresh_max = 255
    l_binary = np.zeros_like(l_channel)
    l_binary[(l_channel >= l_thresh_min) & (l_channel <= l_thresh_max)] = 1

    #color_binary = np.dstack((u_binary, s_binary, l_binary))

    combined_binary = np.zeros_like(s_binary)
    combined_binary[(l_binary == 1) | (b_binary == 1)] = 1

    if show == True:
        # Plotting thresholded images
        f, ((ax1, ax2, ax3), (ax4, ax5, ax6)) = plt.subplots(2,
                                                             3,
                                                             sharey='col',
                                                             sharex='row',
                                                             figsize=(10, 4))
        f.tight_layout()

        ax1.set_title('Original Image', fontsize=16)
        ax1.imshow(
            cv2.cvtColor(undistort(image, show=False), cv2.COLOR_BGR2RGB))

        ax2.set_title('Warped Image', fontsize=16)
        ax2.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB).astype('uint8'))

        ax3.set_title('s binary threshold', fontsize=16)
        ax3.imshow(s_binary, cmap='gray')

        ax4.set_title('b binary threshold', fontsize=16)
        ax4.imshow(b_binary, cmap='gray')

        ax5.set_title('l binary threshold', fontsize=16)
        ax5.imshow(l_binary, cmap='gray')

        ax6.set_title('Combined color thresholds', fontsize=16)
        ax6.imshow(combined_binary, cmap='gray')

    else:
        return combined_binary
Пример #28
0
def plot_results(scores, probs, title=""):
    fig, axs = plt.subplots(1, 2, figsize=(15, 5))
    fig.suptitle(title)
    for i in range(scores.shape[1]):
        axs[0].plot(range(scores.shape[0]), scores[:, i])

    for i in range(probs.shape[1]):
        axs[1].plot(range(probs.shape[0]), probs[:, i, 0])
    plt.show()
Пример #29
0
    def plot(self):
        fig, axes = plt.subplots(nrows=1, ncols=2)

        loss_ax, metric_ax = axes
        loss_ax.plot(self.epoch_losses)
        loss_ax.set_title('Loss')

        metric_ax.plot(self.epoch_metrics)
        metric_ax.set_title('Metric')
Пример #30
0
    def show_batch_stats(self, include_edges=False):
        lens = np.concatenate([sequences(batch, include_edges=include_edges, ignore_values=self.c2i['sil']) for _, y in self.train_dl for batch in y])
        fig, ax = plt.subplots(1)

        ax.hist(lens, bins=lens.max().astype('int'))
        ax.set_xlabel('Sequence length')
        ax.set_ylabel('No of counts')
        ax.set_xticks(np.arange(lens.max(), step=5))
        return lens
Пример #31
0
 def make(self, ncols = 2, swindow = (17,10), sfile = (8,3)):
     if self.__nr_show == 1: 
         f, axarr = p.subplots(1, 1, figsize=swindow)
         axarr = np.array([axarr])
     elif self.__nr_show > 1:
         nrows = int(np.ceil(1.*self.__nr_show/ncols))
         f, axarr = p.subplots(nrows, ncols, figsize=swindow)
     nplots = 0
     for n,plot in enumerate(self.__plots):
         if plot.show:
             self.__show(n,plot,axarr.flatten()[nplots])
             nplots += 1
         if plot.save: 
             self.__save(n,plot,sfile)
     if self.__nr_show > 0:
         f.tight_layout()
         p.show()
     self.__reset()
Пример #32
0
    def plot_system(self,zeropoint=1,fig=None,ax=None,clrbar=False):
        def _clrbar(ax,norm,cmap):
            import matplotlib
            import matplotlib.cm
            import matplotlib.colors as colors
            from mpl_toolkits.axes_grid1 import make_axes_locatable
            divider = make_axes_locatable(ax)
            cax = divider.append_axes('top',size='3%',pad=.05)
            cmap = matplotlib.cm.get_cmap(cmap)
            cb = matplotlib.colorbar.ColorbarBase(ax=cax,cmap=cmap,norm=norm,orientation='horizontal')
            cb.ax.xaxis.set_ticks_position('top')
            cb.ax.xaxis.set_label_position('top')

        import matplotlib.colors as colors
        norm = colors.LogNorm(vmin=1e-2,vmax=1e2)
        if ax is None:
            fig,ax=plt.subplots(figsize=(8,3))
            ax.set_ylim(0,2)
            ax.set_xscale('log')
            ax.set_xlim(1e-3,1e5)
            ax.set_xlabel('Period [days]')
            ax.minorticks_on()
            ax.set_yticklabels('')

        if clrbar:
            _clrbar(ax,norm,'coolwarm')
        ax.axhline(zeropoint,c='k',ls=':',zorder=0)
        print 'For ', self.system_name, ':'
        for i, planet in enumerate(self.planets):
            beta = self.get_AMDBeta(i)
            stest = planet.stability_type
            mass = planet.mass
            period = planet.period
            size = 200*np.log10(mass.value_in(units.MJupiter) * 1e-2/(3e-6) / (.1))
            print 'Planet #', i, 'has a AMDBeta of', beta, 'from the', stest, 'stability test.'
            ax.scatter(period.value_in(units.day),zeropoint,s=size,c=beta,cmap='coolwarm',norm=norm)
        return fig,ax
	photometry = segue.select_stars_in_area(filename,l,b,delta_l,delta_b,wanted_columns)

	good_data = np.isfinite(photometry["U"]) & np.isfinite(photometry["G"]) &
				np.isfinite(photometry["R"]) & np.isfinite(photometry["I"]) &
				np.isfinite(photometry["Z"]) 


	u = photometry["U"][good_data]
	g = photometry["G"][good_data]
	r = photometry["R"][good_data]
	i = photometry["I"][good_data]
	z = photometry["Z"][good_data]


	#Here are the projection plots
	fig,axes = plt.subplots(2,2)
	axes[0,0].plot(u-g,g-r,marker='o',linestyle='')
	axes[0,0].set_xlabel('u-g')
	axes[0,0].set_xlabel('g-r')

	axes[0,1].plot(g-r,r-i,marker='o',linestyle='')
	axes[0,1].set_xlabel('g-r')
	axes[0,1].set_xlabel('r-i')

	axes[1,0].plot(r-i,i-z,marker='o',linestyle='')
	axes[1,0].set_xlabel('r-i')
	axes[1,0].set_xlabel('i-z')

	axes[1,1].plot(u-g,r-i,marker='o',linestyle='')
	axes[1,1].set_xlabel('u-g')
	axes[1,1].set_xlabel('r-i')
Пример #34
0
x_min_list  = []
x_max_list  = []
y_max_list  = []
for kindle in resampled_df.keys():
    print kindle
    x_min_list.append(resampled_df[kindle].index.tolist()[0])
    x_max_list.append(resampled_df[kindle].index.tolist()[-1])
    y_max_list.append(max(resampled_df[kindle]["Ratings"]["count"]))
# 60 days before and after the first and last date
x_limes         = [ min(x_min_list) - timedelta(60), max(x_max_list) + timedelta(60)] 
y_limes_area    = [0, max(y_max_list) + 500]
y_limes_scatter = [0.5, 5.5]

# Plotting averaged ratings over time.
rows = len(resampled_df.keys())
f, ax_arr = plt.subplots(rows, sharex=True, sharey=True, figsize=(6, 12))

for i in range(len(kindles)):      
    
    # Twin the x-axis to make independent y-axes.
    ax_arr[i].set_xlim(x_limes)    
    ax = [ax_arr[i], ax_arr[i].twinx()]
    
    # Set product
    product = kindles[i]
    
    # Plot area at first:    
    ax[0].set_autoscaley_on(False)    
    ax[0].set_ylim(y_limes_area)
    ax[0].set_yticks(np.arange(0,y_limes_area[1], 2000))
    ax[0].plot(resampled_df[product].index.tolist(),
          ('pl-tree', '2-8'),
          ('kr-hier', '10-10'),
          ('kr-peri', '10-10'),
          ('kr-rand', '10-10')]
result = {}
for gtype, param in tqdm(gtypes):
    g = load_data_by_gtype(gtype, param)[0]
    rows = Parallel(n_jobs=-1)(delayed(experiment)(g, p, 100) for p in ps)
    result[gtype] = np.array(rows)


# In[66]:

result['grid']


# In[65]:

richify_line_style(plt)
fig, ax = plt.subplots(1, 1, figsize=(10, 7))
for g, m in result.items():
    ax.plot(ps, m[:, 0] / m[:, 1])
ax.legend(list(result.keys()), loc='lower right')
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_title('infection probability vs fraction of shortest path')
ax.set_xlabel('probability')
ax.set_ylabel('fraction')

fig.savefig('figs/p-vs-sp-path-fraction.pdf')
Пример #36
0
plt.plot(decade_mean.index, decade_mean.values, 'o-',
        color='r', lw=3, label='Decade Average')
plt.fill_between(decade_mean.index, (decade_mean + std).values,
                 (decade_mean - std).values, color='r', alpha=.2)
plt.scatter(data.year, data.score, alpha=.04, lw=0, color='k')
plt.xlabel("Year")
plt.ylabel("Score")
plt.legend(frameon=False)
remove_border()
#Again, there were AttributeErrors when I tried to create graphs

for year, subset in data.groupby('year'):
    print year, subset[subset.score == subset.score.max()].title.values
    
fig, axes = plt.subplots(nrows=4, ncols=6, figsize=(12, 8), 
                         tight_layout=True)

bins = np.arange(1950, 2013, 3)
for ax, genre in zip(axes.ravel(), genres):
    ax.hist(data[data[genre] == 1].year, 
            bins=bins, histtype='stepfilled', normed=True, color='r', alpha=.3, ec='none')
    ax.hist(data.year, bins=bins, histtype='stepfilled', ec='None', normed=True, zorder=0, color='#cccccc')
    
    ax.annotate(genre, xy=(1955, 3e-2), fontsize=14)
    ax.xaxis.set_ticks(np.arange(1950, 2013, 30))
    ax.set_yticks([])
    remove_border(ax, left=False)
    ax.set_xlabel('Year')
# More AttributeErrors and a NameError: 'axes' not defined
    
fig, axes = plt.subplots(nrows=4, ncols=6, figsize=(12, 8), tight_layout=True)
Пример #37
0
 def PlotAllChannels(self, event):
     fig, ax = plt.subplots(nrows=7, ncols=2, sharex=True, sharey=True, squeeze=False, figsize=(12, 12))
     plt.subplots_adjust(hspace=0, wspace=0.05)
     for xi in range(7):
         for yi in range(2):
             ax[xi][yi].plot(range(10), range(10))