def plot_fft_psbs(f=F_FIG_FFT_PSBS):
    plt.cla()
    plt.clf()
    accuracies = np.load(F_FFT_ACC_PSBS)
    plot_psbs_acc(accuracies)
    plt.plot([0, 0.02], [0, 0.02], 'r--', linewidth=2)
    plt.savefig(f)
def plot_grid_psbs(f=F_FIG_GRID_PSBS):
    plt.cla()
    plt.clf()
    accuracies = np.load(F_GRID_ACC_PSBS)
    plot_psbs_acc(accuracies)
    plt.plot([0, 0.02], [0, 0.02], 'b--', linewidth=2)
    plt.savefig(f)
def plot_rotated_histograms_for_cell_type(field_data, cell_type='grid', animal='mouse'):
    print('analyze ' + cell_type + ' cells')
    list_of_cells = field_data.unique_cell_id.unique()
    histograms = []
    for cell in list_of_cells:
        cell_type_filter = field_data['cell type'] == cell_type  # filter for cell type
        accepted = field_data['accepted_field'] == True
        fields_of_cell = field_data.unique_cell_id == cell  # filter for cell
        if not field_data[fields_of_cell & cell_type_filter & accepted].empty:
            histogram = field_data[fields_of_cell & cell_type_filter & accepted].hd_hist_from_all_fields_rotated.iloc[0]
            histograms.append(histogram)

    plt.cla()
    hd_polar_fig = plt.figure()
    ax = hd_polar_fig.add_subplot(1, 1, 1)
    print('Number of ' + cell_type + ' cells: ' + str(len(histograms)))
    histograms_to_plot = []
    for histogram in histograms:
        if not np.isnan(histogram).any():
            theta = np.linspace(0, 2 * np.pi, 361)
            ax = plt.subplot(1, 1, 1, polar=True)
            ax = plot_utility.style_polar_plot(ax)
            ax.plot(theta[:-1], histogram, color='gray', linewidth=2, alpha=70)
            histograms_to_plot.append(histogram)
    # combine them to make one polar plot
    average_histogram = np.average(histograms_to_plot, axis=0)
    theta = np.linspace(0, 2 * np.pi, 361)
    ax.plot(theta[:-1], average_histogram, color='red', linewidth=10)
    plt.savefig(analysis_path + animal + '_rotated_hd_histograms_' + cell_type + '.png', dpi=300, bbox_inches="tight")
    plt.close()
def plot_grid_vs_fft():
    plt.cla()
    plt.clf()
    acc_grid = np.load(F_GRID_ACC_DIAG)
    acc_fft = np.load(F_FFT_ACC_DIAG)
    compare_plot([acc_grid, acc_fft], ['GridNet', 'FFTNet'])
    plt.savefig(F_FIG_COMPARE_GRID_FFT)
def plot_peristimulus_raster(peristimulus_spikes, prm):
    assert len(peristimulus_spikes.groupby('session_id')['session_id'].nunique()) == 1
    save_path = prm.get_output_path() + '/Figures/opto_stimulation'
    if os.path.exists(save_path) is False:
        os.makedirs(save_path)
    cluster_ids = np.unique(peristimulus_spikes.cluster_id)
    for cluster in cluster_ids:
        cluster_rows_boolean = peristimulus_spikes.cluster_id.astype(int) == int(cluster)
        cluster_rows_annotated = peristimulus_spikes[cluster_rows_boolean]
        cluster_rows = cluster_rows_annotated.iloc[:, 2:]
        print(cluster_rows.head())
        plt.cla()
        peristimulus_figure = plt.figure()
        peristimulus_figure.set_size_inches(5, 5, forward=True)
        ax = peristimulus_figure.add_subplot(1, 1, 1)  # specify (nrows, ncols, axnum)
        sample_times = np.argwhere(cluster_rows.to_numpy().astype(int) == 1)[:, 1]
        trial_numbers = np.argwhere(cluster_rows.to_numpy().astype(int) == 1)[:, 0]
        stimulation_start = cluster_rows.shape[1] / 2 - 45  # todo remove magic number
        stimulation_end = cluster_rows.shape[1] / 2 + 45
        ax.axvspan(stimulation_start, stimulation_end, 0, cluster_rows.shape[0], alpha=0.5, color='lightblue')
        ax.vlines(x=sample_times, ymin=trial_numbers, ymax=(trial_numbers + 1), color='black', zorder=2, linewidth=3)
        plt.xlabel('Time (sampling points)')
        plt.ylabel('Trial (sampling points)')
        plt.ylim(0, cluster_rows.shape[0])
        plt.savefig(save_path + '/' + cluster + '_peristimulus_raster.png', dpi=300)
        plt.close()
def draw_heatmap(allstats, outfigure, order=None):
  conds, seqname, mean = allstats.Get(_.cond, _.seqname, _.mean)();
  df = pd.DataFrame({ 'conds': conds, 'seqname': seqname, 'mean':mean})
  df = df.pivot('conds', 'seqname', 'mean')
  plt.cla(); plt.clf();
  ax = sns.heatmap(df, center=1.0)
  plt.savefig('%s/condlibratios.svg' % output_dir)
Пример #7
0
def plot_real_vs_estimated(field,
                           norm_hist_real,
                           estimate,
                           animal,
                           ratio,
                           color='red'):
    plt.cla()
    fig, ax = plt.subplots()
    ax.plot(norm_hist_real, color=color, alpha=0.4, linewidth=5)
    ax.plot(estimate, color='black', alpha=0.4, linewidth=5)
    plt.title('hd ' + str(round(field.hd_score, 1)) + ' grid ' +
              str(round(field.grid_score, 1)) + ' ratio ' +
              str(round(ratio, 4)))
    # legend = plt.legend()
    # legend.get_frame().set_facecolor('none')
    plt.savefig(local_path + animal + field.session_id +
                str(field.cluster_id) + str(field.field_id) +
                'estimated_hd_rate_vs_real.png')
    plt.close()

    save_path = local_path + animal + field.session_id + str(
        field.cluster_id) + str(field.field_id) + 'estimated_hd_rate_vs_real'
    plot_polar_hd_hist(norm_hist_real,
                       estimate,
                       field.cluster_id,
                       save_path,
                       color1=color,
                       color2='black',
                       title='')
Пример #8
0
def plotEngine(input1,input2):

	### Draw columns in tables as functions of time ###
	if "," in input1:
		tableNames = input1.split(",")
		if tableNames[1] == "":
			tableNames = [tableNames[0]]
	if "," not in input1:
		tableNames = [input1]
	for i in range(0, len(tableNames)):

		table = np.array(sc.db.tableToArrayTR(tableNames[i]))
		if table != []:
			for j in range(2,len(sc.db.columnList(tableNames[i]))):
				if "NOPLT" not in sc.db.columnList(tableNames[i])[j]:
					pl.plot(table[:,1],table[:,j], label='%s ((elem %s))'%(sc.db.columnList(tableNames[i])[j],tableNames[i]))

	### Format Plot ###
	pl.legend(loc='best', fancybox=True, framealpha=.5)
	pl.xlabel('Time (Seconds)')
	if len(tableNames) > 1:
		note1 = " (multiple data sets)"
	if len(tableNames) == 1:
		note1 = ""
	pl.ylabel('%s%s'%(input2,note1))
	pl.savefig('%s/DXE_OUTPUT/DXE_OUT_MONITOR/DXE_OUT_MONITOR_%s.png' %(path(),input2))
	pl.clf()
	pl.cla()
Пример #9
0
def draw_lineplot(x, y, title="title", xlab="x", ylab="y", odir="", xlim=None, ylim=None, outfmt='eps'):

  if len(x) == 0 or len(y) == 0:
    return;
  #fi

  plt.cla();
  plt.plot(x, y, marker='x');
  plt.xlabel(xlab);
  plt.ylabel(ylab);
  plt.title(title);

  if xlim == None:
    xmin = min(x);
    xmax = max(x);
    xlim = [xmin, xmax];
  #fi

  if ylim == None:
    ymin = min(y);
    ymax = max(y);
    ylim = [ymin, ymax];
  #fi

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

  plt.savefig('%s%s.%s' % (odir + ('/' if odir else ""), '_'.join(title.split(None)), outfmt), format=outfmt);

  return '%s.%s' % ('_'.join(title.split(None)), outfmt), title;
Пример #10
0
def locate_objects(image_file):
    """
    Detects objects in an image using AlexNet output along with an SVM trained
    on the top 1000 principle components from HOG analysis.
    """
    pil_image = Image.open(image_file).convert('RGB')
    np_image = np.array(pil_image)
    windows = get_windows(np_image, 4)
    windows += get_windows(np_image, 8)
    windows += get_windows(np_image, 16)
    detections = []
    for w in windows:
        plot_window(np_image, w)
        pil_sub = pil_image.crop((w['xmin'], w['ymin'], w['xmax'], w['ymax']))
        np_sub = np_image[w['ymin']:w['ymax'], w['xmin']:w['xmax']]
        nn_out = alex_nn(Variable(
            preprocessFn(pil_sub).unsqueeze(0))).data.numpy()
        hog = get_hog_vector(np_sub)
        features = np.hstack((nn_out, pca.transform(hog.reshape(1, -1))))
        probs = svm_model.predict_proba(features)[0]
        label = svm_model.predict(features)
        max_idx = int(np.where(classes == label)[0])
        detections.append({
            'window': w,
            'p': probs[max_idx],
            'label': classes[max_idx]
        })
        plt.cla()
    best_detections = get_top_windows(detections)
    plot_detections(np_image, best_detections)
Пример #11
0
def judge_stable_analyze(data, col, address):
    num_counts = pd.crosstab(data['applymonth'], data[col], margins=True)
    num_counts_percents = num_counts.div(num_counts['All'], axis=0)
    num_counts_percents = num_counts_percents.drop('All', axis=1)
    num_counts_percents = num_counts_percents.drop('All', axis=0)

    bad_percents = pd.crosstab(index=data['applymonth'],
                               columns=data[col],
                               values=data['fraud_y'],
                               aggfunc='mean',
                               margins=True)
    bad_percents = bad_percents.drop('All', axis=1)
    bad_percents = bad_percents.drop('All', axis=0)

    plt.cla()
    plt.figure(2)
    ax1 = plt.subplot(121)
    ax2 = plt.subplot(122)
    for cn in num_counts_percents.columns:
        plt.sca(ax1)
        plt.plot(num_counts_percents[cn])
        plt.xticks(rotation=90)
        plt.legend()
        plt.title(col)
        plt.sca(ax2)
        plt.plot(bad_percents[cn])
        plt.xticks(rotation=90)
        plt.legend()
        plt.title(col)
    plt.savefig(address + col + '.jpg')
    plt.show()

    count_data = pd.concat([num_counts_percents, bad_percents], axis=0)
    count_data.to_csv(address + col + '.csv')
Пример #12
0
 def adjust(self):
     try:
         if self.isOpen:
             if not self.adjusted:
                 if not self.predicted:
                     self.predict()
                 self.adjust_img, predicted = self.auto.adjust(self.img)
                 if not predicted:
                     self.predict()
                     self.adjust_img, predicted = self.auto.adjust(self.img)
                 self.img = self.adjust_img
                 plt.cla()
                 self.fig, self.ax = plt.subplots()
                 self.ax.axis('off')
                 self.ax.imshow(self.showRoate(self.img)[:, :,
                                                         self.imgIndex],
                                interpolation='nearest',
                                aspect='auto',
                                cmap='gray')
                 cavan = FigureCanvas(self.fig)
                 for i in reversed(range(self.verticalLayout.count())):
                     self.verticalLayout.itemAt(i).widget().setParent(None)
                 self.verticalLayout.addWidget(cavan)
                 self.adjusted = True
             else:
                 pass
         else:
             QMessageBox.information(self, "Tip",
                                     "Please open file first:)")
     except:
         pass
Пример #13
0
def plot_distance_distribution_maps(distance_map, label, save_dir):

    plt.cla()
    n, h, w = distance_map.shape
    cm_rz = np.squeeze(np.reshape(tonumpy(distance_map), (n, h * w)), axis=0)
    gt = np.array(tonumpy(label), np.int32)
    gt_rz = np.squeeze(np.reshape(gt, (n, h * w)), axis=0)
    x_t, y_t = [], []
    colors = ['#0000ff', '#009900']
    markers = ['*', 'o']
    for i in range(h * w):
        t = np.random.random() * 2 * np.pi - np.pi
        dist, lbl = cm_rz[i], gt_rz[i]
        x, y = dist * np.cos(t), dist * np.sin(t)
        x_t.append(x), y_t.append(y)
    x_t, y_t = np.array(x_t), np.array(y_t)
    for i in range(2):
        plt.scatter(x_t[gt_rz == i], y_t[gt_rz == i], c=colors[i], s=40, marker=markers[i])
    plt.legend(['unchanged', 'changed'], loc='upper right')
    plt.xlim(min(x_t) * 1.2, max(x_t) * 1.2)
    plt.ylim(min(y_t) * 1.2, max(y_t) * 1.2)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.title('distance distribution')
    plt.grid(True)
    plt.savefig(save_dir)
Пример #14
0
def plot_curve(name_list,
               recall_list,
               precision_list,
               plot_path,
               sample_num=100):
    colorList = ['r', 'g', 'b', 'y', 'c', 'm', 'k', 'g', 'b']
    lineList = ['*', '^', 's', 'p', '*', 'v', 'd', 's', '^']
    plt.ioff()
    fig = plt.figure(figsize=(12, 10), dpi=180)
    for idx, name in enumerate(name_list):
        color_index = idx % (len(colorList))
        line_index = idx // (len(colorList)) % len(lineList)
        style = '{}{}-'.format(colorList[color_index], lineList[line_index])
        recall = recall_list[idx]
        precision = precision_list[idx]
        recall, precision = sample_index(recall,
                                         precision,
                                         sample_num=sample_num)
        plt.plot(recall, precision, style, label='{}'.format(name))
    plt.xlabel('time')
    plt.ylabel('price')
    plt.xticks(np.arange(0, max(recall), max(recall) / 10))
    plt.yticks(np.arange(0, max(precision), max(precision) / 10))
    plt.grid()
    plt.legend(loc=4)
    plt.savefig(plot_path)
    plt.clf()
    plt.cla()
    plt.close()
Пример #15
0
def draw_light_plot():
    if "userid" not in session:
        return redirect(url_for("index"))
    uid = session["userid"]
    if uid not in users:
        return redirect(url_for("index"))
    users[uid].record_as_active()

    plt.cla()  # Clear axis
    plt.clf()  # Clear figure
    plt.close()  # Close a figure window

    # create light summary plot
    fig = plt.figure()
    ax = fig.add_subplot(111)
    users[uid].summary.plot_light(ax)
    fig.patch.set_facecolor("#fff9f0")
    fig.set_size_inches(8, 8)

    # post-process for html
    canvas = FigureCanvas(fig)
    png_output = StringIO.StringIO()
    canvas.print_png(png_output)
    response = make_response(png_output.getvalue())
    response.headers["Content-Type"] = "image/png"

    plt.cla()  # Clear axis
    plt.clf()  # Clear figure
    plt.close()  # Close a figure window
    return response
Пример #16
0
def show_curve(method, step, text):
    pylab.cla()
    xlist = numpy.arange(a, b + step, step)
    ylist = []
    x = a
    while x <= b:
        r = method(x, step)
        ylist.append(r)
        x += step
    pylab.plot(xlist, ylist, label=text)
    print(f"Методом Рунге-Кутта: {ylist}")
    pylab.grid(True)
    pylab.legend()
    pylab.show()
    ylist2 = ylist
    ylist = []
    x = a
    while x <= b:
        r = accurate_solution(x)
        ylist.append(r)
        x += step
    pylab.cla()
    pylab.plot(xlist, ylist, label="Точное решение")
    print(f"Точное решение: {ylist}")
    pylab.grid(True)
    pylab.legend()
    pylab.show()
    rez = []
    for item in range(len(ylist)):
        rez.append(abs(ylist[item] - ylist2[item]))
    print(f"Погрешность между зачениями: {rez}")
Пример #17
0
    def plot_timeseries(self, ax=None, vmin=None, vmax=None,
            colorbar=False, label=True):

        if vmin is None:
            vmin = self.vmin

        if vmax is None:
            vmax = self.vmax

        if ax is None:
            ax = plt.gca()
        plt.sca(ax)
        plt.cla()
        plt.imshow(self.tser_arr[::-1,:], vmin=vmin, vmax=vmax,
            interpolation='Nearest', extent=self.extent, origin='upper',aspect='auto')
        plt.xlim(self.extent[0], self.extent[1])
        plt.ylim(self.extent[2], self.extent[3])
        # plt.vlines(self.ionogram_list[0].time, self.extent[2], self.extent[3], 'r')
        if label:
           celsius.ylabel('f / MHz')

        if colorbar:
            old_ax = plt.gca()
            plt.colorbar(
                    cax = celsius.make_colorbar_cax(), ticks=self.cbar_ticks
                ).set_label(r"$Log_{10} V^2 m^{-2} Hz^{-1}$")
            plt.sca(old_ax)
Пример #18
0
def plot_shuffled_number_of_bins_vs_observed(cells):
    for index, cell in cells.iterrows():
        shuffled_distribution = cell.number_of_different_bins_shuffled_corrected_p
        plt.cla()
        fig = plt.figure(figsize=(6, 3))
        plt.yticks([0, 1000])
        ax = fig.add_subplot(1, 1, 1)
        ax.hist(shuffled_distribution, bins=range(20), color='gray')
        ax.axvline(x=cell.number_of_different_bins_bh,
                   color='navy',
                   linewidth=3)
        ax.xaxis.set_tick_params(labelsize=20)
        ax.yaxis.set_tick_params(labelsize=20)
        max_x_value = max(cell.number_of_different_bins_bh,
                          shuffled_distribution.max())
        plt.xlim(0, max_x_value + 1)
        # plt.xscale('log')
        plt.ylabel('N', fontsize=24)
        plt.xlabel('Number of significant bins', fontsize=24)
        plt.tight_layout()
        plt.savefig(analysis_path + 'percentile/' + cell.session_id +
                    str(cell.cluster_id) + str(cell.field_id) +
                    'number_of_significant_bars_shuffled_vs_real_' +
                    str(cell.directional_percentile) + '.png')
        plt.close()
Пример #19
0
def save_image(dataRaw, dataFilter, threshold_u_l, dir_data, csv_name,
               del_samples_xyz):  #引数が大きすぎる気がする。del_samplesはセットで考えた方が綺麗に見えないかな?
    upper_x, lower_x, upper_y, lower_y, upper_z, lower_z = threshold_u_l
    del_samples_x, del_samples_y, del_samples_z = del_samples_xyz
    fig = plt.figure(figsize=(20, 10))
    fig.suptitle("Diff Filtered file: %s \n Delete times X:%d Y:%d Z:%d" %
                 (csv_name, del_samples_x, del_samples_y,
                  del_samples_z))  #ここから87ページまでは辞書とfor文を使って解決できないか?
    ax_raw_x = fig.add_subplot(231)
    ax_raw_y = fig.add_subplot(232)
    ax_raw_z = fig.add_subplot(233)
    ax_fil_x = fig.add_subplot(234, sharey=ax_raw_x)
    ax_fil_y = fig.add_subplot(235, sharey=ax_raw_y)
    ax_fil_z = fig.add_subplot(236, sharey=ax_raw_z)
    ax_raw_x.plot(range(len(dataRaw)), dataRaw[:, 0], "b-", lw=1)
    ax_raw_y.plot(range(len(dataRaw)), dataRaw[:, 1], "r-", lw=1)
    ax_raw_z.plot(range(len(dataRaw)), dataRaw[:, 2], "g-", lw=1)
    ax_raw_x.hlines([upper_x, lower_x],
                    xmin=0,
                    xmax=len(dataRaw),
                    linestyle="dashed",
                    lw=1)
    ax_raw_y.hlines([upper_y, lower_y],
                    xmin=0,
                    xmax=len(dataRaw),
                    linestyle="dashed",
                    lw=1)
    ax_raw_z.hlines([upper_z, lower_z],
                    xmin=0,
                    xmax=len(dataRaw),
                    linestyle="dashed",
                    lw=1)
    ax_fil_x.plot(range(len(dataFilter)), dataFilter[:, 0], "b-", lw=1)
    ax_fil_y.plot(range(len(dataFilter)), dataFilter[:, 1], "r-", lw=1)
    ax_fil_z.plot(range(len(dataFilter)), dataFilter[:, 2], "g-", lw=1)
    ax_fil_x.hlines([upper_x, lower_x],
                    xmin=0,
                    xmax=len(dataFilter),
                    linestyle="dashed",
                    lw=1)
    ax_fil_y.hlines([upper_y, lower_y],
                    xmin=0,
                    xmax=len(dataFilter),
                    linestyle="dashed",
                    lw=1)
    ax_fil_z.hlines([upper_z, lower_z],
                    xmin=0,
                    xmax=len(dataFilter),
                    linestyle="dashed",
                    lw=1)

    root, ext = os.path.splitext(csv_name)
    output_filename = os.path.join(dir_data + "filter/", root + ".png")
    fig.savefig(output_filename)
    plt.close(fig)

    plt.cla()
    plt.clf()
    del fig
Пример #20
0
def plot_flow_contentions(exp_num, exp_nums):
	global markerslist
	exp_num=str(exp_num)
	read_directory = log_dir+"exp"+exp_num+"/analysis/averages"
	conf = minidom.parse(log_dir+'exp'+exp_num+'/config.xml')
	configurations = conf.getElementsByTagName('config')
	copies=configurations[0].getElementsByTagName('copies')[0].childNodes[0].nodeValue
	priQ=configurations[0].getElementsByTagName('use_different_priorities')[0].childNodes[0].nodeValue
	purging=configurations[0].getElementsByTagName('purging')[0].childNodes[0].nodeValue

	directory=plot_dir+"exp"+str(exp_nums)
	if not os.path.exists(directory):
		os.mkdir( directory );

	files=[]
	for file in os.listdir(read_directory):
		if file.startswith("flowContentions"):
			files.append(file)
	
	while files:
		current_files = []
		current_files.append(files.pop())
		# print current_files[0][:-5]
		for k in xrange(1,int(copies)+1):
			try:
				i=files.index(current_files[0][:-5]+str(k)+".csv")
				current_files.append(files.pop(i))
				# print i
			except:
				pass
		#plot figure
		# print current_files
		fig=pl.figure()
		local_marker_list = markerslist[:]
		for f in current_files:
			flowIds=[]
			contentions=[]
			with open(read_directory+"/"+f, 'r') as csvfile:
				for line in csvfile:
					lineList = line.split(",")
					flowIds.append(lineList[0])
					contentions.append(lineList[1].split("\n")[0])
			lab=f[-5:-4]
			pl.plot(flowIds, contentions, label=lab,marker=local_marker_list.pop(0))
		lg = pl.legend(bbox_to_anchor=legend_pos)#(loc='center left', bbox_to_anchor=(1, 0.5))
		lg.draw_frame(True)
		t =f[-8:-6]
		if int(priQ):
			t=t+" - with queues"
		if int(purging):
			t=t+" - with purging"
		pl.title(t)
		pl.ylim([0,25])
		pl.xlim([2000,2500])

		fig.savefig(directory+"/exp"+exp_num+"_"+f[-8:-6]+".png", bbox_inches='tight',  transparent=False)
		pl.cla()   # Clear axis
		pl.clf()   # Clear figure
		pl.close() # Close a figure window
def plot_and_save_polar_histogram(histogram, name, color='gray', line_width=10):
    plt.cla()
    theta = np.linspace(0, 2 * np.pi, 361)
    ax = plt.subplot(1, 1, 1, polar=True)
    ax = plot_utility.style_polar_plot(ax)
    ax.plot(theta[:-1], histogram, color=color, linewidth=line_width)
    plt.savefig(analysis_path + 'rotated_hd_histograms_' + name + '.png', dpi=300, bbox_inches="tight")
    plt.close()
Пример #22
0
    def initAlgoritmo(self):
        self.area.setPlainText("")
        self.area.repaint()
        self.tabs.hide()
        plt.cla()

        if os.path.exists("grafico.jpg"):
            os.remove("grafico.jpg")
Пример #23
0
def bad_pix_qual(startx_fn, endx_fn, starty_fn, endy_fn, chosenPixels3d_fn):
    means_array_fn = np.zeros([endy_fn - starty_fn, endx_fn - startx_fn],
                              dtype='float')
    stds_array_fn = np.zeros([endy_fn - starty_fn, endx_fn - startx_fn],
                             dtype='float')
    heights_array_fn = np.zeros([endy_fn - starty_fn, endx_fn - startx_fn],
                                dtype='float')

    bad_fits_counter = 0
    means_fn = np.array([])
    stds_fn = np.array([])
    heights_fn = np.array([])
    x_vals_fn = np.array([])
    y_vals_fn = np.array([])

    for pix_y in range(0, (endy_fn - starty_fn)):  #(endy-starty)*(endx-startx)
        for pix_x in range(
                0, (endx_fn - startx_fn)):  #(endy-starty)*(endx-startx)
            badfit = False

            if (pix_x % 30 == 0 and pix_y % 30 == 0):
                print(pix_x, pix_y)
            histValues = plt.hist(chosenPixels3d_fn[:, pix_y, pix_x], bins=45)
            mphist = midpoints(histValues[1])
            # meanh=chosenPixels3d_fn[:,pix_y,pix_x].mean()
            meanh = mphist[histValues[0].argmax()]

            stdh = chosenPixels3d_fn[:, pix_y, pix_x].std()
            try:
                popt, pcov = curve_fit(gaus,
                                       mphist,
                                       histValues[0],
                                       p0=[15, meanh, stdh])
            except:
                bad_fits_counter += 1
                popt = [-1, -1, -1]
                badfit = True

            heights_array_fn[pix_y, pix_x] = popt[0]
            means_array_fn[pix_y, pix_x] = popt[1]
            stds_array_fn[pix_y, pix_x] = popt[2]
            #             if((pix_x==47) and (pix_y==32)):
            #                 plt.plot(histValues[1][:-1],gaus(histValues[1][:-1],*popt),'ro:',label='fit')
            #                 plt.show()
            plt.cla()
            # plt.clf()
            #             print(pix_x,pix_y,popt)
            # if badfit=False:
            x_vals_fn = np.append(x_vals_fn, pix_x)
            y_vals_fn = np.append(y_vals_fn, pix_y)
            heights_fn = np.append(heights_fn, popt[0])
            means_fn = np.append(means_fn, popt[1])
            stds_fn = np.append(stds_fn, popt[2])

    print("badfits", bad_fits_counter)

    return heights_fn, means_fn, stds_fn, x_vals_fn, y_vals_fn, means_array_fn, stds_array_fn, heights_array_fn
Пример #24
0
def ICP_matching(ppoints, cpoints):
    """
    icpマッチングを行うことでマスクアンカー、アノテーションとの残差を計算
    Iterative Closest Point matching
    - input
    ppoints: 2D points in the previous frame
    cpoints: 2D points in the current frame
    - output
    R: Rotation matrix
    T: Translation vector
    """
    H = None  # homogeneous transformation matrix

    dError = 1000.0
    preError = 1000.0
    count = 0
    ppoints = np.array([ppoints[0],ppoints[1]])
    cpoints = np.array([cpoints[0],cpoints[1]])
    while dError >= EPS:
        count += 1

        if show_animation:  # pragma: no cover

            plt.cla()
            plt.plot(ppoints[0, :], ppoints[1, :], ".r")
            plt.plot(cpoints[0, :], cpoints[1, :], ".b")
            plt.plot(0.0, 0.0, "xr")
            plt.axis("equal")
            plt.pause(1.0)
            plt.savefig("../../GoogleDrive/icp_test_{0}.png".format(count))

        inds, error = nearest_neighbor_assosiation(ppoints, cpoints)
        Rt, Tt = SVD_motion_estimation(ppoints[:, inds], cpoints)

        # update current points
        cpoints = (Rt @ cpoints) + Tt[:, np.newaxis]

        H = update_homogeneous_matrix(H, Rt, Tt)

        dError = abs(preError - error)
        preError = error

        if dError <= EPS:
            break
        elif MAXITER <= count:
            print("Not Converge...", error, dError, count)
            break

    R = np.array(H[0:2, 0:2])
    T = np.array(H[0:2, 2])

    try:
        R = math.degrees(math.acos(R[0][0]))
    except:
        R = 0

    return R,T
Пример #25
0
 def showSkyline(self, l):
     pylab.cla()
     for tpl in l:
         st = tpl[0]
         end = tpl[1]
         height = tpl[2]
         pylab.bar(st, height, (end - st))
     pylab.show()
     print "Done"
Пример #26
0
 def update_iq_power_plot_single(self, iq_power):
     # plt.figure (1)
     plt.cla()
     plt.plot(iq_power, 'd-', color='b')
     plt.grid(True)
     plt.ylim([-100, -30])
     plt.tight_layout()
     plt.show()
     plt.pause(0.00001)
Пример #27
0
def showSkyline(l):
    pylab.cla()
    for tuple in l:
        st = tuple[0]
        end = tuple[1]
        height = tuple[2]
        pylab.bar(st,height,(end-st))
    pylab.show()
    print "Done"
Пример #28
0
 def render(self, mode='human'):
     x = np.linspace(-self.length, self.length, 100)
     y = [self.func(i) for i in x]
     plt.cla()
     plt.plot(x, y, 'r', linewidth=2)
     plt.scatter(self.state, self.func(self.state), linewidth=10)
     plt.title(
         "Find the solution corresponding to the minimum objective value")
     plt.pause(0.1)
Пример #29
0
def draw_building_zoom():
    if "userid" not in session:
        return redirect(url_for("index"))
    uid = session["userid"]
    if uid not in users:
        return redirect(url_for("index"))
    users[uid].record_as_active()

    plt.cla()  # Clear axis
    plt.clf()  # Clear figure
    plt.close()  # Close a figure window

    fig = plt.figure()
    ax = fig.add_axes([0, 0, 1, 1])
    radius = ZOOM_SIZE / 2 * 1.5
    for key in users[uid].buildings:
        if users[uid].obs.distance_from_building(users[uid].buildings[key]) < radius:
            if key not in users[uid].building_keys_at_address:
                users[uid].buildings[key].plot_footprint(ax, color="k")
            else:
                users[uid].buildings[key].plot_footprint(ax, color=COLOR_LIGHTBROWN)
    users[uid].obs.plot_observers_location(ax, color="r")

    L = ZOOM_SIZE / 2  # half size of the plotted area in meters
    ax.set_xlim([users[uid].obs.x - L, users[uid].obs.x + L])
    ax.set_ylim([users[uid].obs.y - L, users[uid].obs.y + L])
    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    ax.axis("off")
    ax.set_aspect("equal")

    number_of_floors = users[uid].get_number_of_floors()
    ax.text(
        users[uid].obs.x,
        users[uid].obs.y + L / 5,
        "floors: " + str(number_of_floors),
        verticalalignment=u"center",
        horizontalalignment=u"center",
        size="large",
        color="r",
    )

    fig.patch.set_facecolor("#d4c3a8")
    fig.set_size_inches(5, 5)

    # post-process for html
    canvas = FigureCanvas(fig)
    png_output = StringIO.StringIO()
    canvas.print_png(png_output)
    response = make_response(png_output.getvalue())
    response.headers["Content-Type"] = "image/png"

    plt.cla()  # Clear axis
    plt.clf()  # Clear figure
    plt.close()  # Close a figure window
    return response
Пример #30
0
def fit_rotcur(galaxy, vmode):
    try:

        data = fits.getdata("./fits/%s.%s_model.fits" % (galaxy, vmode))

        R = data[0]
        V = data[1]
        mask = V > 5
        R = R[mask]
        V = V[mask]
        min_vel, max_vel = int(np.nanmin(V)), int(np.nanmax(V))
        temp = []
        v_max_temp = []
        R_turn_temp = []
        for i in model:
            best_params = fit_RC(R, V, i)
            data = best_params[:-1]
            Vmax, Rturn = data[0], data[1]
            if Vmax > 340: Vmax = 0
            if Vmax == 0: Vmax = np.nan
            temp.append(Vmax)
            temp.append(Rturn)
            v_max_temp.append(Vmax)
            R_turn_temp.append(Rturn)

            ax.plot(R, V, "k-")
            ax.plot(R, V, "ks")
            ax.plot(R, best_params[-1], label=i)

        mean_V, median_V, std_V = np.nanmedian(v_max_temp), np.nanmean(
            v_max_temp), np.nanstd(v_max_temp)
        mean_R, median_R, std_R = np.nanmedian(R_turn_temp), np.nanmean(
            R_turn_temp), np.nanstd(R_turn_temp)
        table = [
            galaxy, temp[0], temp[1], temp[2], temp[3], temp[4], temp[5],
            temp[6], temp[7], temp[8], temp[9], temp[10], temp[11], mean_V,
            median_V, std_V, mean_R, median_R, std_R
        ]
        write(table, "manga_vmax_velfit_1.5.%s.csv" % vmode, column=False)

        plt.legend(fontsize="xx-small")
        ax.set_xlabel("r (arcsec)", fontsize=12, labelpad=0)
        ax.set_ylabel('V$_\mathrm{ROT}$ (km/s)', fontsize=12, labelpad=0)
        ax.set_ylim(-50, max_vel + 50)
        AXIS(ax)
        plt.savefig("./vmax_rturn/%s.fit_rotcur.%s.png" % (galaxy, vmode),
                    dpi=300)
        #plt.show()
        plt.cla()
        return median_V, median_R

    except (IOError, OSError):
        table = [galaxy, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
        write(table, "manga_vmax_velfit_1.5.%s.csv" % vmode, column=False)
        return 1, 1
        pass
Пример #31
0
    def __del__(self):
        """
        Figures created through the pyplot interface
        (`matplotlib.pyplot.figure`) are retained until explicitly
        closed and may co nsume too much memory.
        """

        plt.cla()
        plt.clf()
        plt.close()
Пример #32
0
    def plot_once(self, data):
        u"""
        データを描画する

        Args:
            data: データ(list of value)
        """
        plt.cla()
        plt.plot(data)
        plt.pause(0.01)
Пример #33
0
 def write_tn(self, msi, ts):
     time_stamp = f'{ts:.2f}'.replace('.', '_')
     plt.figure()
     show_rgb_comp(msi, n_leds=self.n_leds)
     plt.savefig(os.path.join(self.tn_path, f'{time_stamp}_tn.png'))
     cv2.imwrite(os.path.join(self.tn_path, f'{time_stamp}_white.png'),
                 msi.mean(axis=2))
     plt.cla()
     plt.clf()
     plt.close()
Пример #34
0
    def __del__(self):
        """
        Figures created through the pyplot interface
        (`matplotlib.pyplot.figure`) are retained until explicitly
        closed and may co nsume too much memory.
        """

        plt.cla()
        plt.clf()
        plt.close()
Пример #35
0
    def plot_maps(self, df, file_name):
        cmap = plt.cm.coolwarm
        if self.scenario == 1:
            fig, axes = plt.subplots(nrows=2, ncols=1)

            # plotting class labels
            class_numbers = np.array(df['Class Number'])
            width = int(np.sqrt(len(class_numbers)))
            class_numbers = np.concatenate((class_numbers, 75 * np.ones(width - len(class_numbers) % width))).reshape(
                (-1, width))
            label_dict = dict([(label, i) for i, label in enumerate(self.labels)])
            label_dict['empty'] = len(label_dict)
            rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, len(label_dict))))
            axes[0].imshow(class_numbers, cmap=cmap)
            # axes[0].legend(handles=patches, loc=2, bbox_to_anchor=(1.01, 1))
            axes[0].tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
            axes[0].tick_params(axis='y', which='both', left=False, right=False, labelleft=False)

            # plotting tags
            tags = df['Tag']
            tags_enum = []
            tags_dict = dict([(tag, i) for i, tag in enumerate(np.unique(self.tags))])
            tags_dict['empty'] = len(tags_dict)
            for tag in tags:
                tags_enum.append(tags_dict[tag])
            tags_enum = np.array(tags_enum)
            tags_enum = np.concatenate((
                tags_enum, (len(tags_dict) - 1) * np.ones(width - len(tags_enum) % width))).reshape((-1, width))
            rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, len(tags_dict))))
            axes[1].imshow(tags_enum, cmap=cmap)
            # axes[1].legend(handles=patches, loc=2, bbox_to_anchor=(1.01, 1))
            axes[1].tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
            axes[1].tick_params(axis='y', which='both', left=False, right=False, labelleft=False)
        else:
            fig, axes = plt.subplots(1, 2, figsize=(6, 12))
            class_numbers = np.array(df['Class Number'])
            label_dict = dict([(label, i) for i, label in enumerate(self.labels)])
            label_dict['empty'] = len(label_dict)
            width = int(np.sqrt(len(class_numbers)))
            class_numbers = np.concatenate(
                (class_numbers, (len(label_dict) - 1) * np.ones(width - len(class_numbers) % width))).reshape((-1, width))
            rcParams['axes.prop_cycle'] = cycler(color=cmap(np.linspace(0, 1, len(label_dict))))
            axes[0].imshow(class_numbers, cmap=cmap)
            cmaplist = [cmap(int(i * 3.1)) for i in range(len(label_dict))]
            cmaplist[len(label_dict) - 1] = [1.0, 1.0, 1.0, 1.0]
            cmap = mpl.colors.LinearSegmentedColormap.from_list('Custom cmap', cmaplist, len(label_dict))
            axes[0].imshow(class_numbers, cmap=cmap)
            patches = [mpatches.Patch(color=cmap(v), label=k.upper()) for k, v in label_dict.items() if
                       v in class_numbers]
            axes[1].legend(handles=patches, ncol=len(patches) // 20 + 1)
            plt.tick_params(axis='x', which='both', bottom=False, top=False, labelbottom=False)
            plt.tick_params(axis='y', which='both', left=False, right=False, labelleft=False)
        plt.savefig(str(file_name))
        plt.cla()
        return
Пример #36
0
    def __init__(self, cells, value_function, cmap=default_colormap,
                 hold=True, vmin=None, vmax=None, **kwargs):
        """
        Creates a new map from cells

        :param cells:
        :param value_function:
        :param cmap:
        :param hold:
        :param vmin:
        :param vmax:
        :param kwargs:
        """

        if not hasattr(cmf.Cell, 'geometry'):
            raise NotImplementedError('The geometry of the cells can not be used, shapely is not installed')
        self.cmap = cmap
        self.cells = [c for c in cells if c.geometry]
        self.__f = value_function

        was_interactive = plt.isinteractive()

        if was_interactive:
            plt.ioff()

        self.polygons = {}

        def flatten_multipolygons(shape):
            if hasattr(shape, "geoms"):
                return shape.geoms
            else:
                return [shape]

        geos = [flatten_multipolygons(c.geometry) for c in self.cells]
        values = [self.f(c) for c in self.cells]
        self.maxvalue = vmax or max(values)
        self.minvalue = vmin or min(values)

        if self.minvalue >= self.maxvalue:
            self.minvalue = self.maxvalue - 1

        if not hold:
            plt.cla()

        for cell, shapes, v in zip(self.cells, geos, values):
            c = self.cmap(float(v - self.minvalue) / float(self.maxvalue - self.minvalue))
            self.polygons[cell] = [self.draw_shapes(s, c, **kwargs) for s in shapes]

        plt.axis('equal')
        norm = Normalize(self.minvalue, self.maxvalue)
        plt.matplotlib.cm.ScalarMappable.__init__(self, norm, cmap)

        if was_interactive:
            plt.draw()
            plt.ion()
def plots(u,xvals,t):
    plt.cla()
    plt.plot(xvals,u)
    plt.ylim(-0.1, 1.1)
    plt.xlim( 0.0, 1.0)
    plt.xlabel(r'$x$',fontsize = 15)
    plt.ylabel(r'$u$',fontsize = 15)
    plt.title(r'Time: $t$ = ' + str(t).ljust(4, str(0)))
    plt.grid("on")
    fig.canvas.draw()
    return
Пример #38
0
    def plot_frequency_altitude(self, f=2.0, ax=None, median_filter=False,
        vmin=None, vmax=None, altitude_range=(-99.9, 399.9), colorbar=False, return_image=False, annotate=True):

        if vmin is None:
            vmin = self.vmin

        if vmax is None:
            vmax = self.vmax

        if ax is None:
            ax = plt.gca()

        plt.sca(ax)
        plt.cla()
        freq_extent = (self.extent[0], self.extent[1],
            altitude_range[1], altitude_range[0])

        i = self.ionogram_list[0]
        inx = 1.0E6* (i.frequencies.shape[0] * f) / (i.frequencies[-1] - i.frequencies[0])
        img = self.tser_arr_all[:,int(inx),:]

        new_altitudes = np.arange(altitude_range[0], altitude_range[1], 14.)
        new_img = np.zeros((new_altitudes.shape[0], img.shape[1])) + np.nan

        for i in self.ionogram_list:
            e = int( round((i.time - self.extent[0]) / ais_code.ais_spacing_seconds ))

            pos = mex.iau_r_lat_lon_position(float(i.time))
            altitudes = pos[0] - ais_code.speed_of_light_kms * ais_code.ais_delays * 0.5 - mex.mars_mean_radius_km
            s = np.argsort(altitudes)
            new_img[:, e] = np.interp(new_altitudes, altitudes[s], img[s,e], left=np.nan, right=np.nan)

        plt.imshow(new_img, vmin=vmin, vmax=vmax,
            interpolation='Nearest', extent=freq_extent, origin='upper', aspect='auto')

        plt.xlim(freq_extent[0], freq_extent[1])
        plt.ylim(*altitude_range)

        ax.set_xlim(self.extent[0], self.extent[1])
        ax.xaxis.set_major_locator(celsius.SpiceetLocator())

        celsius.ylabel(r'Alt./km')
        if annotate:
            plt.annotate('f = %.1f MHz' % f, (0.02, 0.9),
                    xycoords='axes fraction', color='cyan', verticalalignment='top', fontsize='small')

        if colorbar:
            old_ax = plt.gca()
            plt.colorbar(cax = celsius.make_colorbar_cax(), ticks=self.cbar_ticks).set_label(r"$Log_{10} V^2 m^{-2} Hz^{-1}$")
            plt.sca(old_ax)

        if return_image:
            return new_img, freq_extent, new_altitudes
Пример #39
0
def draw_graph(plot_data, rankingSystem, numberOfUv, hue):
    plot_data['world_rank'] = plot_data['world_rank'].astype(int)
    ax = sns.pointplot(x='year', y='world_rank', hue=hue, data=plot_data);
    pylab.title("Top " + str(numberOfUv) + " university by " + rankingSystem, fontsize=26)
    pylab.xticks(fontsize=20)
    pylab.yticks(fontsize=20)
    pylab.ylabel("World Rank", fontsize=26)
    pylab.xlabel("Year", fontsize=26)
    pylab.savefig('resources/images/topuv.png')
    pylab.cla()
    pylab.clf()
    pylab.close()
Пример #40
0
def mkHistogram(data,sndx):
	print type(data[2])
	histDat = pl.hist(data,360,normed=1,color='black',histtype='step',label='Angle %s' %(sndx))
	pl.legend()
	pl.xlim(-180,180)
	pl.xlabel('Angle [deg.]',fontsize=16)
	pl.ylabel('Probability density',fontsize=16)
	pl.xticks(fontsize=12)
	pl.yticks(fontsize=12)
	pl.savefig('%s_hist.pdf' %(sndx))
	pl.cla()
	return histDat # sp.histogram(data,360)
Пример #41
0
def draw_gene_isoforms(D, gene_id, outfile, outfmt):

  import matplotlib.patches as mpatches;
  from matplotlib.collections import PatchCollection;

  ISO = D[_.orig_gene == gene_id].GroupBy(_.alt_gene).Without(_.orig_gene, _.orig_exon_start, _.orig_exon_end).Sort(_.alt_gene);

  plt.cla();

  y_loc   = 0;
  y_step  = 30;
  n_iso   = ISO.alt_gene.Shape()();
  origins = np.array([ [0, y] for y in xrange((y_step * (n_iso+1)),n_iso,-y_step) ]);
  patch_h = 10;

  xlim = [ ISO.exon_start.Min().Min()(), ISO.exon_end.Max().Max()()];
  ylim = [ y_step, (y_step * (n_iso+1)) + 2*patch_h];

  patches = [];
  
  for (origin, alt_id, starts, ends, exons, retention, alt5, alt3, skipped, new, ident) in zip(origins, *ISO()):

    plt.gca().text( min(starts), origin[1] + patch_h, alt_id, fontsize=10);
    for (exon_start, exon_end, exon_coverage, exon_retention, exon_alt5, exon_alt3, exon_skipped, exon_new, exon_ident) in zip(starts, ends, exons, retention, alt5, alt3, skipped, new, ident):
      if not(exon_skipped):
        patch = mpatches.FancyBboxPatch(origin + [ exon_start, 0], exon_end - exon_start, patch_h, boxstyle=mpatches.BoxStyle("Round", pad=0), color=draw_gene_isoforms_color(exon_retention, exon_alt5, exon_alt3, exon_skipped, exon_new, exon_ident));
        text_x, text_y = origin + [ exon_start, +patch_h/2];
        annots = zip(['Retention', "Alt 5'", "Alt 3'", "Skipped", 'New'], [exon_retention, exon_alt5, exon_alt3, exon_skipped, exon_new]);
        text  = '%s: %s' %( ','.join([str(exid) for exid in exon_coverage]), '\n'.join([ s for (s,b) in annots if b]));
        plt.gca().text(text_x, text_y, text, fontsize=10, rotation=-45);
        plt.gca().add_patch(patch);

        if all(ident):
          plt.gca().plot([exon_start, exon_start], [origin[1], 0], '--k', alpha=0.3);
          plt.gca().plot([exon_end, exon_end], [origin[1], 0], '--k', alpha=0.3);
        #fi
      #fi
    #efor
  #efor

  plt.xlim(xlim);
  plt.ylim(ylim);
  plt.title('Isoforms for gene %s' % gene_id);
  plt.xlabel('Location on chromosome');
  plt.gca().get_yaxis().set_visible(False);
  plt.gca().spines['top'].set_color('none');
  plt.gca().spines['left'].set_color('none');
  plt.gca().spines['right'].set_color('none');
  plt.tick_params(axis='x', which='both', top='off', bottom='on');
  plt.savefig(outfile, format=outfmt);

  return ISO;
Пример #42
0
def drawBarAXBarChart(bar1_series, bar2_series, title, xlabel, y_bar1_label, y_bar2_label, xticklabels, bar1_label, bar2_label):
    n_groups = xticklabels.size
    fig, ax = plt.subplots(dpi=100, figsize=(16,8))

    index = np.arange(n_groups)
    bar_width = 0.25

    opacity = 0.4
    error_config = {'ecolor': '0.3'}
    def autolabel(ax, rects):
        # attach some text labels
        for rect in rects:
            height = rect.get_height()
            ax.text(rect.get_x() + rect.get_width()/2., 1.005*height,
                    '%d' % int(height),
                    ha='center', va='bottom', fontproperties=myFont, size=tipSize-1)
    rects = plt.bar(index, bar1_series, bar_width,
                    alpha=opacity,
                    color='b',
                    error_kw=error_config,
                    label=bar1_label)
    autolabel(ax,rects)              
    plt.xlabel(xlabel, fontproperties=myFont, size=titleSize)
    plt.ylabel(y_bar1_label, fontproperties=myFont, size=titleSize, color='b')
    for label in ax.get_yticklabels():
        label.set_color('b')
    plt.title(title, fontproperties=myFont, size=titleSize)
    plt.xticks(index + (1/2.)*bar_width, xticklabels, fontproperties=myFont, size=tipSize)
    plt.legend(prop=font_manager.FontProperties(fname='/Library/Fonts/Songti.ttc', size=tipSize))
    
    print 'drawNBarChart',title,'1 over'
    ax1 = ax.twinx()
    rects1 = plt.bar(index+1*bar_width, bar2_series, bar_width,
                    alpha=opacity,
                    color='r',
                    error_kw=error_config,
                    label=bar2_label, axes=ax1)
    autolabel(ax1,rects1)              
    for label in ax1.get_yticklabels():
        label.set_color('r')
    plt.ylabel(y_bar2_label, fontproperties=myFont, size=titleSize, color='r')
    plt.xticks(index + (2/2.)*bar_width, xticklabels, fontproperties=myFont, size=tipSize)
    plt.legend((rects, rects1), (bar1_label, bar2_label),prop=font_manager.FontProperties(fname='/Library/Fonts/Songti.ttc', size=tipSize))
    
    plt.tight_layout()
    
    plt.savefig(sv_file_dir+'/'+title+'.png', format='png')
    plt.cla()
    plt.clf()
    plt.close()
    print 'drawNBarChart',title,'2 over'
Пример #43
0
def drawPieChart(data, labels, title):
    fig = plt.figure(dpi=100, figsize=(8,8))
    # first axes
    ax1 = fig.add_axes([0.1, 0.1, 0.8, 0.8])
    patches, texts, autotexts = ax1.pie(data, labels=labels, autopct='%1.1f%%', colors=['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'])
    plt.setp(autotexts, fontproperties=myFont, size=tipSize)
    plt.setp(texts, fontproperties=myFont, size=tipSize)
    ax1.set_title(title,fontproperties=myFont, size=titleSize)
    ax1.set_aspect(1)
    #plt.show()
    plt.savefig(sv_file_dir+'/'+title+'.png', format='png')
    plt.cla()
    plt.clf()
    plt.close()
    print 'drawPieChart',title,'over'
Пример #44
0
def draw_inverted_polar_plot():
    if "userid" not in session:
        return redirect(url_for("index"))
    uid = session["userid"]
    if uid not in users:
        return redirect(url_for("index"))
    users[uid].record_as_active()

    plt.cla()  # Clear axis
    plt.clf()  # Clear figure
    plt.close()  # Close a figure window

    fig = plt.figure()
    ax = fig.add_axes([0, 0, 1, 1])
    users[uid].sil.draw_inverted_polar(ax, color="k")
    this_year = dt.datetime.today().year
    dates_to_plot = [dt.datetime(this_year, 6, 21), dt.datetime.today(), dt.datetime(this_year, 12, 22)]
    morning_colors = ["#ffc469", "#fd8181", "#ffc469"]
    afternoon_colors = ["#f98536", "r", "#f98536"]
    labels = ["Jun 21", "today", "Dec 22"]
    text_colors = ["#f98536", "r", "#f98536"]
    for i in range(0, len(dates_to_plot)):
        d = dates_to_plot[i]
        cm = morning_colors[i]
        ca = afternoon_colors[i]
        ct = text_colors[i]
        l = labels[i]
        sun = SunPath(stepsize=SUN_STEPSIZE, lat=users[uid].obs.lat, lon=users[uid].obs.lon, date=d)
        sun.calculate_path()
        sun.calculate_visibility(users[uid].sil)
        sun.draw_inverted_polar(ax, morning_color=cm, afternoon_color=ca, text_color=ct, label=l)

    ax.axis("off")
    ax.set_aspect("equal")
    fig.patch.set_facecolor("#fff9f0")
    fig.set_size_inches(8, 8)

    # post-process for html
    canvas = FigureCanvas(fig)
    png_output = StringIO.StringIO()
    canvas.print_png(png_output)
    response = make_response(png_output.getvalue())
    response.headers["Content-Type"] = "image/png"

    plt.cla()  # Clear axis
    plt.clf()  # Clear figure
    plt.close()  # Close a figure window
    return response
Пример #45
0
def plot_update(fig, axarr, data1, data2, round):

    plt.cla()
    dota1 = data1 / STARTING_PCT
    dota2 = data2 / STARTING_PCT
    center_of_mass1 = ndimage.measurements.center_of_mass(dota1)
    center_of_mass2 = ndimage.measurements.center_of_mass(dota2)

    axarr = [plt.subplot(fig[0, 0]), plt.subplot2grid((2, 2), (1, 0), colspan=2), plt.subplot(fig[0, 1])]
    img1 = axarr[0].imshow(
        dota1,
        interpolation="nearest",
        cmap=plt.cm.ocean,
        extent=(0.5, np.shape(dota1)[0] + 0.5, 0.5, np.shape(dota1)[1] + 0.5),
    )
    axarr[0].plot([center_of_mass1[1]], [center_of_mass1[0]], "or")  # adds dot at center of mass
    axarr[0].plot([center_of_mass2[1]], [center_of_mass2[0]], "oy")  # adds dot for other teams c o m
    axarr[0].axis((1, 101, 1, 101))
    axarr[1].plot(avg_deal_data1, color="green")
    axarr[1].set_xlim(0, rounds)
    axarr[1].set_title("Current Round:" + str(round))
    axarr[0].set_title("Player1")
    axarr[2].set_title("Player2")
    axarr[0].set_ylabel("Give")
    axarr[0].set_xlabel("Accept")
    axarr[1].set_ylabel("Average Cash per Deal")
    axarr[1].set_xlabel("Round Number")
    plt.colorbar(img1, ax=axarr[0], label="Prevalence vs. Uniform")

    img2 = axarr[2].imshow(
        dota2,
        interpolation="nearest",
        cmap=plt.cm.ocean,
        extent=(0.5, np.shape(dota2)[0] + 0.5, 0.5, np.shape(dota2)[1] + 0.5),
    )
    axarr[2].plot([center_of_mass2[1]], [center_of_mass2[0]], "or")  # adds dot at center of mass
    axarr[2].plot([center_of_mass1[1]], [center_of_mass1[0]], "oy")  # adds dot for other teams c o m
    axarr[2].axis((1, 101, 1, 101))
    axarr[1].plot(avg_deal_data2, color="purple")

    plt.title("Current Round:" + str(round))
    axarr[2].set_ylabel("Give")
    axarr[2].set_xlabel("Accept")
    plt.colorbar(img2, ax=axarr[2], label="Prevalence vs. Uniform")

    plt.draw()
Пример #46
0
    def plot_frequency_range(self, f_min=0., f_max=0.2, ax=None, median=False,
        vmin=None, vmax=None, colorbar=False, max_value=False):

        if vmin is None:
            vmin = self.vmin

        if vmax is None:
            vmax = self.vmax

        if ax is None:
            ax = plt.gca()

        plt.sca(ax)
        plt.cla()
        freq_extent = (self.extent[0], self.extent[1],
            ais_code.ais_max_delay*1E3, ais_code.ais_min_delay*1E3)

        i = self.ionogram_list[0]
        inx, = np.where((i.frequencies > f_min*1E6) & (i.frequencies < f_max*1E6))

        if inx.shape[0] < 2:
            raise ValueError("Only %d frequency bins selected." % inx.shape[0])
        print("Averaging over %d frequency bins" % inx.shape[0])

        if median:
            if inx.shape[0] < 3:
                raise ValueError("Median here only really makes sense for 3 or more bins")
            img = np.median(self.tser_arr_all[:,inx,:],1)
        elif max_value:
            img = np.max(self.tser_arr_all[:,inx,:],1)
        else:
            img = np.mean(self.tser_arr_all[:,inx,:],1)
        plt.imshow(img, vmin=vmin, vmax=vmax,
            interpolation='Nearest', extent=freq_extent, origin='upper',aspect='auto')

        plt.xlim(freq_extent[0], freq_extent[1])
        plt.ylim(freq_extent[2], freq_extent[3])
        # plt.vlines(i.time,freq_extent[2],freq_extent[3], 'r')
        celsius.ylabel(r'$\tau_D / ms$' '\n' '%.1f-%.1f MHz' % (f_min, f_max))
        # plt.annotate('f = %.1f - %.1f MHz' % (f_min, f_max), (0.02, 0.9), xycoords='axes fraction',
            # color='grey', verticalalignment='top', fontsize='small')

        if colorbar:
            old_ax = plt.gca()
            plt.colorbar(cax = celsius.make_colorbar_cax(), ticks=self.cbar_ticks).set_label(r"$Log_{10} V^2 m^{-2} Hz^{-1}$")
            plt.sca(old_ax)
Пример #47
0
def mkProfile(hvals,sndx):
	xval = hvals[1][:-1]
	yval = hvals[0]
	yval = [-0.0019*float(300)*np.log(i) for i in yval]
	minVal = float(min(yval))
	yval = [i-minVal for i in yval]
	yvalS = smoothData(yval,10)
	pl.plot(xval,yval,'.',color='black',label='Calculated %s' %(sndx))
	pl.plot(xval,yvalS,'-',color='black',label='Smooth %s' %(sndx))
	pl.legend()
	pl.xlim(-180,180)
	pl.ylim(0,6)
        pl.xlabel('Angle [deg.]',fontsize=16)
        pl.ylabel('Energy [kcal/mol/deg2',fontsize=16)
	pl.xticks(fontsize=12)
        pl.yticks(fontsize=12)
        pl.savefig('%s_prof.pdf' %(sndx))
        pl.cla()
Пример #48
0
def density_of_accessing(picture_name):
    
    coordinats = []
    with open("matrix_processing_result.log") as file:
        for line in file:
            coordinats.append(list(map(int, line.split() )))

    xlist, ylist = zip(*coordinats)
    xlist = np.array(xlist)
    ylist = np.array(ylist)

    heatmap, xedges, yedges = np.histogram2d(xlist, ylist, bins=150)
    extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]

    plt.clf()
    plt.cla()
    plt.imshow(heatmap, extent=extent)

    plt.savefig(picture_name)
Пример #49
0
def draw_hist(x, title="title", xlab="x", ylab="y", normed=True, odir="", nbins=None, outfmt='eps'):

  if len(x) == 0:
    return;
  #fi

  plt.cla();
  if nbins:
    plt.hist(x, nbins, normed=normed);
  else:
    plt.hist(x, normed=normed);
  #fi
  plt.xlabel(xlab);
  plt.ylabel(ylab);
  plt.title(title);

  plt.savefig('%s%s.%s' % (odir + ('/' if odir else ""), '_'.join(title.split(None)), outfmt), format=outfmt);

  return '%s.%s' % ('_'.join(title.split(None)), outfmt), title;
Пример #50
0
def plot_update(fig, axarr, data, round):
    """Update the plot.

    Args:
        fig: 
        axarr:
        data:
        round:
    """

    # Clear plots
    plt.cla()

    # Compare distribution to uniform
    dota = data / STARTING_PCT

    # Create subplots
    axarr = [plt.subplot(fig[0,0]), plt.subplot(fig[1, 0])]

    # Plot data (or dota, rather...)
    img = axarr[0].imshow(dota, interpolation='nearest', cmap = plt.cm.ocean,
                          extent = (0.5, np.shape(dota)[0] + 0.5, 0.5, 
                                    np.shape(dota)[1] + 0.5))

    # Plot average deal data
    axarr[1].plot(avg_deal_data)
    axarr[1].set_xlim(0, rounds)

    # Show round
    plt.title("Current Round:" + str(round))

    # Set labels
    axarr[0].set_ylabel("Give")
    axarr[0].set_xlabel("Accept")
    axarr[1].set_ylabel("Average Cash per Deal")
    axarr[1].set_xlabel("Round Number")

    # Set color bar
    plt.colorbar(img,ax=axarr[0],label= "Prevalence vs. Uniform")

    # Draw plots
    plt.draw()
def splineFunction(xnodi,fnodi, xx, fType, sType):
    if(sType==0):
        s1 = interpolate.interp1d(xnodi, fnodi, 'linear')
        sname='lineare'
    else:
        s1 = interpolate.interp1d(xnodi, fnodi, 'cubic')
        sname='cubica'
        
    if(fType==0):
        fname='f=cos(x)'
    else:
        fname='g=1/(1+25*(x**2))' 
        
    ys = s1(xx)
    error.append(np.max(np.abs(ys-yy)))
    plt.figure(i)
    plt.cla()
    plt.title('Spline %s per la funzione %s' %(sname,fname))
    plt.plot(xx,ys,xnodi,fnodi,'o',xx,yy,'--')
    plt.show()
def animate(nframe):
  print "Animate %d" % nframe
  #if nframe > 0:
  plt.cla()
      
  xlim, ylim = plot_gt()      
  sl = 0.002*numpy.random.random()-0.001
  bi = 35*numpy.random.random()+50
  print sl
  print bi
  g = lambda t: sl*t + bi
  #g = lambda t: 0.00013*t + 70+nframe

  xx = g(T)
  plt.plot(T, xx, lw=5.0, color="r", alpha=0.5, label="current guess")

  me = np.sum( [ np.abs(g(_t)-f(_t)) for _t in t ] )

  global best_x, best_me
  if best_x is not None:
    plt.plot(T, best_x, lw=2.5, color="g", alpha=0.5,label="best guess")

  if best_x is None or me < best_me:
    best_me = me
    best_x = xx

  print me
  
  plt.text(5e5, 30, "Current error: %.2f" % me, fontsize=15, color='red',)
  plt.text(5e5, 50, "Best error:    %.2f" % best_me, fontsize=15, color='green',)

  plt.text(5e4, 450, "Attempt: %d" % (nframe+1))
    

  plt.xlim([0, 1e6])
  plt.ylim([0, 500])
  
  plt.legend()
  
  if nframe == 5:
    plt.savefig("random_guess_animation.png")
Пример #53
0
    def old_stuff(self):
        print res2['chi2'], res2['chi0']
        if self.verbose:
            print "New Period is %.8f day" % period
        
        plt.figure(2)
        plt.cla()
        tt=(self.x0/period) % 1.; s=tt.argsort()
        plt.errorbar (tt[s],new_y[s],self.dy_orig[s],fmt='o',c="b")
        plt.plot(tt[s],res2['model'][s],c="r")
        
        f = open("lc.dat","w")
        z = zip(tt[s] - 0.5,new_y[s],self.dy_orig[s])
        for l in z:
            f.write("%f %f %f\n" % l)
        f.close()
        
        f = open("lc0.dat","w")
        z = zip(self.x0,new_y,self.dy_orig)
        for l in z:
            f.write("%f %f %f\n" % l)
        f.close()
        
        
        psdr,res2 = lombr(self.x0,new_y,self.dy0,f0/2.,df,numf)
        period1=1./res2['freq']

        if self.verbose:
            print "New Period is %.8f day" % period1
        
        plt.figure(4)
        plt.cla()
        tt=(self.x0/period1) % 1.; s=tt.argsort()
        plt.errorbar (tt[s],new_y[s],self.dy_orig[s],fmt='o',c="b")
        plt.plot(tt[s],res2['model'][s],c="r")
        print res2['chi2'], res2['chi0']
        f = open("lc2.dat","w")
        z = zip(tt[s] - 0.5,new_y[s],self.dy_orig[s])
        for l in z:
            f.write("%f %f %f\n" % l)
        f.close()
Пример #54
0
def drawLineChart(pd_series, title, xlabel, ylabel, xticks, xticklabels):
    ax = pd_series.plot(figsize=(14,8))
    #for label in ax.get_xticklabels(): #xtick
    #    label.set_fontproperties(myFont)
    for label in ax.get_yticklabels(): #ytick
        label.set_fontproperties(myFont)
    for label in ax.get_label(): # legend
        label.set_fontproperties(myFont)
    ax.set_title(title, fontproperties=myFont, size=titleSize)
    ax.set_xlabel(xlabel, fontproperties=myFont, size=tipSize)
    ax.set_ylabel(ylabel, fontproperties=myFont, size=tipSize)
    ax.set_xticks(xticks)
    ax.set_xticklabels(xticklabels, fontproperties=myFont, size=tipSize)
    ax.xaxis.grid(True, which='major') #x坐标轴的网格使用主刻度  
    ax.yaxis.grid(True, which='major') #y坐标轴的网格使用主刻度  
    #ax.yaxis.grid(True, which='minor') #y坐标轴的网格使用次刻度  
    plt.savefig(sv_file_dir+'/'+title+'.png', format='png')
    plt.cla()
    plt.clf()
    plt.close()
    print 'drawLineChart',title,'over'
Пример #55
0
def main():
    """
    Main routine: Print User stats
    """
    if len(sys.argv) < 2:
        sys.exit('Usage: ' + sys.argv[0] +  ' [Accounting files]')
    else:
        joblist = sys.argv[1:]

    corehours = np.zeros(1000)
    jobs = jobstats.alljobs(joblist)
    for job in jobs:
        if job.cores < 1000:
            corehours[job.cores] += job.cores*job.walltime/3600.0
    
    plt.cla()
    plt.bar(range(1,1001), list(corehours))
    plt.xlabel('Cores')
    plt.ylabel('Core hours')
    plt.savefig('corehoursvprocs.png')
    return
Пример #56
0
def drawNBarChart(data_label_colors, xindex, xlabel, ylabel, title):
    n_groups = xindex.size
    fig, ax = plt.subplots(dpi=100, figsize=(14,8))

    index = np.arange(n_groups)
    bar_width = 0.35

    opacity = 0.4
    error_config = {'ecolor': '0.3'}
    
    def autolabel(rects):
        # attach some text labels
        for rect in rects:
            height = rect.get_height()
            ax.text(rect.get_x() + rect.get_width()/2., 1.005*height,
                    '%d' % int(height),
                    ha='center', va='bottom', fontproperties=myFont, size=tipSize-1)
    i = 0
    for data, label, color in data_label_colors:
        rects = plt.bar(index+i*bar_width, data, bar_width,
                    alpha=opacity,
                    color=color,
                    error_kw=error_config,
                    label=label)
        autolabel(rects)
        i += 1
                    
    ax.yaxis.grid(True, which='major') #y坐标轴的网格使用主刻度  
    plt.xlabel(xlabel, fontproperties=myFont, size=titleSize)
    plt.ylabel(ylabel, fontproperties=myFont, size=titleSize)
    plt.title(title, fontproperties=myFont, size=titleSize)
    plt.xticks(index + (len(data_label_colors)/2.)*bar_width, xindex, fontproperties=myFont, size=tipSize)
    plt.legend(prop=font_manager.FontProperties(fname='/Library/Fonts/Songti.ttc', size=tipSize))
    
    plt.tight_layout()
    plt.savefig(sv_file_dir+'/'+title+'.png', format='png')
    plt.cla()
    plt.clf()
    plt.close()
    print 'drawNBarChart',title,'over'
Пример #57
0
def bargraph_from_dict(h_dict, group_labels, log=False, colors=None, save=None,
                       title=None, xlabel=None, ylabel=None, legend=False, loc='best'):
    bars = len(h_dict) + 2 # Add one for a space between groups
    groups = len(group_labels)

    print h_dict
    for v in h_dict.values():
        if len(v) != groups:
            raise ValueError("h_dict must contain sequences with the same number as labels")

    plt.cla()
    plts = []
    if log:
        plt.yscale("log")

    if colors == "greyscale":
        colors = [str(i*(.75/len(h_dict))) for i in xrange(len(h_dict))]
    elif colors is None or colors == "spectrum":
        colors = "rygbcmk"

    keys = sorted(h_dict.keys())
    for n, k in enumerate(keys):
        plts.append(plt.bar(range(n+1, bars*groups+1, bars), h_dict[k],
                            color=colors[n % len(colors)]))
    plt.xticks([1 + i*bars + bars/2 for i in xrange(groups)], group_labels)

    if log:
        ymin, ymax = plt.ylim()
        ymin = min(reduce(lambda acc, x: acc+x, h_dict.values(), []))/2.0
        plt.ylim((ymin, ymax))
    if legend:
        plt.legend( [p[0] for p in plts], [k.replace('_', '\_') for k in keys], loc=loc)
    if title:
        plt.title(title)
    if ylabel:
        plt.ylabel(ylabel)
    if xlabel:
        plt.xlabel(xlabel)
    if save is not None:
        plt.savefig(save)
Пример #58
0
    def _get_pulsational_period(self,min_freq=10.0,doplot=False,max_pulse_period=400.0):
        self.x0 = self.t
        self.y = self.m
        self.dy = self.merr
        self.dy0 = np.sqrt(self.dy**2+self.sys_err**2)
        self.x0 -= self.x0.min()
        self.nepochs = len(self.x0)

        # define the frequency grid
        Xmax = self.x0.max()
        if not  self.fix_initial_period:
            f0 = 1.0/max_pulse_period; df = 0.1/Xmax; fe = min_freq
            numf = int((fe-f0)/df)
        else:
            f0 = 1./self.initial_period
            df = 1e-7
            numf = 1
            
        psdr,res2 = lombr(self.x0,self.y,self.dy0,f0,df,numf,detrend_order=1)
        period=1./res2['freq']
        self.rrlp = period
        if self.verbose:
            print "Initial pulstional Period is %.8f day" % self.rrlp
        
        self.features.update({"p_pulse_initial": self.rrlp})
        
        if self.allow_plotting and doplot:
            try:
                plt.figure(3)
                plt.cla()
                tt=(self.x0/period) % 1.; s=tt.argsort()
                plt.errorbar (tt,self.y,self.dy,fmt='o'); plt.plot(tt[s],res2['model'][s])
                plt.ylim(self.y.max()+0.05,self.y.min()-0.05)
                plt.title("P=%f" % (self.rrlp))
                plt.draw()
            except:
                pass
        return res2
Пример #59
0
    def plot_frequency(self, f=2.0, ax=None, median_filter=False,
        vmin=None, vmax=None, colorbar=False):

        if vmin is None:
            vmin = self.vmin

        if vmax is None:
            vmax = self.vmax

        if ax is None:
            ax = plt.gca()
        plt.sca(ax)
        plt.cla()
        freq_extent = (self.extent[0], self.extent[1],
            ais_code.ais_max_delay*1E3, ais_code.ais_min_delay*1E3)

        i = self.ionogram_list[0]
        inx = 1.0E6* (i.frequencies.shape[0] * f) / (i.frequencies[-1] - i.frequencies[0])
        img = self.tser_arr_all[:,int(inx),:]
        # img -= np.mean(img, 0)
        plt.imshow(img, vmin=vmin, vmax=vmax,
            interpolation='Nearest', extent=freq_extent, origin='upper',aspect='auto')
        # plt.imshow(img, interpolation='Nearest', extent=freq_extent, origin='upper',aspect='auto')

        plt.xlim(freq_extent[0], freq_extent[1])
        plt.ylim(freq_extent[2], freq_extent[3])
        # plt.vlines(i.time,freq_extent[2],freq_extent[3], 'r')
        celsius.ylabel(r'$\tau_D / ms$' '\n' '%.1f MHz' % f)
        # plt.annotate('f = %.1f MHz' % f, (0.02, 0.9), xycoords='axes fraction',
        #             color='grey', verticalalignment='top', fontsize='small')

        if colorbar:
            old_ax = plt.gca()
            plt.colorbar(cax = celsius.make_colorbar_cax(),
                        ticks=self.cbar_ticks).set_label(
                                r"$Log_{10} V^2 m^{-2} Hz^{-1}$")
            plt.sca(old_ax)