Example #1
0
def plot_scenario(strategies, names, scenario_id=1):
    probabilities = get_scenario(scenario_id)

    plt.figure(figsize=(6, 4.5))

    ax = plt.subplot(111)
    ax.spines["top"].set_visible(False)
    ax.spines["bottom"].set_visible(False)
    ax.spines["right"].set_visible(False)
    ax.spines["left"].set_visible(False)

    ax.get_xaxis().tick_bottom()
    ax.get_yaxis().tick_left()

    plt.yticks(fontsize=14)
    plt.xticks(fontsize=14)
    plt.xlim((0, 1300))

    # Remove the tick marks; they are unnecessary with the tick lines we just plotted.
    plt.tick_params(axis="both", which="both", bottom="on", top="off",
                    labelbottom="on", left="off", right="off", labelleft="on")

    for rank, (strategy, name) in enumerate(zip(strategies, names)):
        plot_strategy(probabilities, strategy, name, rank)

    plt.title("Bandits: " + str(probabilities), fontweight='bold')
    plt.xlabel('Number of Trials', fontsize=14)
    plt.ylabel('Cumulative Regret', fontsize=14)
    plt.legend(names)
    plt.show()
Example #2
0
def showOverlapTable(modes_x, modes_y, **kwargs):
    """Show overlap table using :func:`~matplotlib.pyplot.pcolor`.  *modes_x*
    and *modes_y* are sets of normal modes, and correspond to x and y axes of
    the plot.  Note that mode indices are incremented by 1.  List of modes
    is assumed to contain a set of contiguous modes from the same model.

    Default arguments for :func:`~matplotlib.pyplot.pcolor`:

      * ``cmap=plt.cm.jet``
      * ``norm=plt.normalize(0, 1)``"""

    import matplotlib.pyplot as plt

    overlap = abs(calcOverlap(modes_y, modes_x))
    if overlap.ndim == 0:
        overlap = np.array([[overlap]])
    elif overlap.ndim == 1:
        overlap = overlap.reshape((modes_y.numModes(), modes_x.numModes()))

    cmap = kwargs.pop('cmap', plt.cm.jet)
    norm = kwargs.pop('norm', plt.normalize(0, 1))
    show = (plt.pcolor(overlap, cmap=cmap, norm=norm, **kwargs),
            plt.colorbar())
    x_range = np.arange(1, modes_x.numModes() + 1)
    plt.xticks(x_range-0.5, x_range)
    plt.xlabel(str(modes_x))
    y_range = np.arange(1, modes_y.numModes() + 1)
    plt.yticks(y_range-0.5, y_range)
    plt.ylabel(str(modes_y))
    plt.axis([0, modes_x.numModes(), 0, modes_y.numModes()])
    if SETTINGS['auto_show']:
        showFigure()
    return show
Example #3
0
    def make_bar(
        x,
        y,
        f_name,
        title=None,
        legend=None,
        x_label=None,
        y_label=None,
        x_ticks=None,
        y_ticks=None,
    ):
        fig = plt.figure()

        if title is not None:
            plt.title(title, fontsize=16)
        if x_label is not None:
            plt.ylabel(x_label)
        if y_label is not None:
            plt.xlabel(y_label)
        if x_ticks is not None:
            plt.xticks(x, x_ticks)
        if y_ticks is not None:
            plt.yticks(y_ticks)

        plt.bar(x, y, align="center")

        if legend is not None:
            plt.legend(legend)

        plt.savefig(f_name)
        plt.close(fig)
Example #4
0
def tuning(x, y, err=None, smooth=None, ylabel=None, pal=None):
    """
    Plot a tuning curve
    """
    if smooth is not None:
        xs, ys = smoothfit(x, y, smooth)
        plt.plot(xs, ys, linewidth=4, color="black", zorder=1)
    else:
        ys = asarray([0])
    if pal is None:
        pal = sns.color_palette("husl", n_colors=len(x) + 6)
        pal = pal[2 : 2 + len(x)][::-1]
    plt.scatter(x, y, s=300, linewidth=0, color=pal, zorder=2)
    if err is not None:
        plt.errorbar(x, y, yerr=err, linestyle="None", ecolor="black", zorder=1)
    plt.xlabel("Wall distance (mm)")
    plt.ylabel(ylabel)
    plt.xlim([-2.5, 32.5])
    errTmp = err
    errTmp[isnan(err)] = 0
    rng = max([nanmax(ys), nanmax(y + errTmp)])
    plt.ylim([0 - rng * 0.1, rng + rng * 0.1])
    plt.yticks(linspace(0, rng, 3))
    plt.xticks(range(0, 40, 10))
    sns.despine()
    return rng
Example #5
0
def disc_norm():
    x = np.linspace(-3,3,100)
    y = st.norm.pdf(x,0,1)
    fig, ax = plt.subplots()
    fig.canvas.draw()
    
    ax.plot(x,y)
    
    fill1_x = np.linspace(-2,-1.5,100)
    fill1_y = st.norm.pdf(fill1_x,0,1)
    fill2_x = np.linspace(-1.5,-1,100)
    fill2_y = st.norm.pdf(fill2_x,0,1)
    ax.fill_between(fill1_x,0,fill1_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75)
    ax.fill_between(fill2_x,0,fill2_y,facecolor = 'blue', edgecolor = 'k',alpha = 0.75)
    for label in ax.get_yticklabels():
        label.set_visible(False)
    for tick in ax.get_xticklines():
        tick.set_visible(False)
    for tick in ax.get_yticklines():
        tick.set_visible(False)
    
    plt.rc("font", size = 16)
    plt.xticks([-2,-1.5,-1])
    labels = [item.get_text() for item in ax.get_xticklabels()]
    labels[0] = r"$v_k$"
    labels[1] = r"$\varepsilon_k$"
    labels[2] = r"$v_{k+1}$"
    ax.set_xticklabels(labels)
    plt.ylim([0, .45])

    
    plt.savefig('discnorm.pdf')
    plt.clf()
Example #6
0
def plot_jacobian(A, name, cmap= plt.cm.coolwarm, normalize=True, precision=1e-6):

    """
    Customized visualization of jacobian matrices for observing
    sparsity patterns
    """
    
    plt.figure()
    fig, ax = plt.subplots()
    
    if normalize is True:
        plt.imshow(A, interpolation='none', cmap=cmap,
                   norm = mpl.colors.Normalize(vmin=-1.,vmax=1.))
    else:
        plt.imshow(A, interpolation='none', cmap=cmap)        
    plt.colorbar(format=ticker.FuncFormatter(fmt))
    
    ax.spy(A, marker='.', markersize=0,  precision=precision)
    
    ax.spines['right'].set_visible(True)
    ax.spines['bottom'].set_visible(True)
    ax.xaxis.set_ticks_position('top')
    ax.yaxis.set_ticks_position('left')

    xlabels = np.linspace(0, A.shape[0], 5, True, dtype=int)
    ylabels = np.linspace(0, A.shape[1], 5, True, dtype=int)

    plt.xticks(xlabels)
    plt.yticks(ylabels)

    plt.savefig(name, bbox_inches='tight', pad_inches=0.05)
    
    plt.close()

    return
Example #7
0
    def graph_by_sender(self):

        mac_adresses = {}  # new dictionary
        for pkt in self.pcap_file:
            mac_adresses.update({pkt[Dot11].addr2: 0})
        for pkt in self.pcap_file:
            mac_adresses[pkt[Dot11].addr2] += 1

        MA = []
        for ma in mac_adresses:
            MA.append(mac_adresses[ma])

        plt.clf()
        plt.suptitle('Number of packets of every sender', fontsize=14, fontweight='bold')
        plt.bar(range(len(mac_adresses)), sorted(MA), align='center', color=MY_COLORS)

        plt.xticks(range(len(mac_adresses)), sorted(mac_adresses.keys()))

        plt.rcParams.update({'font.size': 10})

        plt.xlabel('Senders mac addresses')
        plt.ylabel('Number of packets')

        # Set tick colors:
        ax = plt.gca()
        ax.tick_params(axis='x', colors='k')
        ax.tick_params(axis='y', colors='r')
        ax.set_xticklabels(ax.xaxis.get_majorticklabels(), rotation=45)

        plt.show()
Example #8
0
def plot_head_map(mma, target_labels, source_labels):
  fig, ax = plt.subplots()
  heatmap = ax.pcolor(mma, cmap=plt.cm.Blues)

  # put the major ticks at the middle of each cell
  ax.set_xticks(numpy.arange(mma.shape[1])+0.5, minor=False)
  ax.set_yticks(numpy.arange(mma.shape[0])+0.5, minor=False)
  
  # without this I get some extra columns rows
  # http://stackoverflow.com/questions/31601351/why-does-this-matplotlib-heatmap-have-an-extra-blank-column
  ax.set_xlim(0, int(mma.shape[1]))
  ax.set_ylim(0, int(mma.shape[0]))

  # want a more natural, table-like display
  ax.invert_yaxis()
  ax.xaxis.tick_top()

  # source words -> column labels
  ax.set_xticklabels(source_labels, minor=False)
  # target words -> row labels
  ax.set_yticklabels(target_labels, minor=False)
  
  plt.xticks(rotation=45)

  #plt.tight_layout()
  plt.show()
def template_matching():
    img = cv2.imread('messi.jpg',0)
    img2 = img.copy()
    template = cv2.imread('face.png',0)
    w, h = template.shape[::-1]

    # All the 6 methods for comparison in a list
    methods = ['cv2.TM_CCOEFF', 'cv2.TM_CCOEFF_NORMED', 'cv2.TM_CCORR',
            'cv2.TM_CCORR_NORMED', 'cv2.TM_SQDIFF', 'cv2.TM_SQDIFF_NORMED']

    for meth in methods:
        img = img2.copy()
        method = eval(meth)

        # Apply template Matching
        res = cv2.matchTemplate(img,template,method)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

        # If the method is TM_SQDIFF or TM_SQDIFF_NORMED, take minimum
        if method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
            top_left = min_loc
        else:
            top_left = max_loc
        bottom_right = (top_left[0] + w, top_left[1] + h)

        cv2.rectangle(img,top_left, bottom_right, 255, 2)

        plt.subplot(121),plt.imshow(res,cmap = 'gray')
        plt.title('Matching Result'), plt.xticks([]), plt.yticks([])
        plt.subplot(122),plt.imshow(img,cmap = 'gray')
        plt.title('Detected Point'), plt.xticks([]), plt.yticks([])
        plt.suptitle(meth)

        plt.show()
	def barPlot(self, datalist, threshold, figname):

		tally = self.geneCount(datalist)

		#Limit the items plotted to those over 1% of the read mass
		geneplot = defaultdict()
		for g, n in tally.iteritems():
			if n > int(sum(tally.values())*threshold):
				geneplot[g] = n

		#Get plotting values
		olist = OrderedDict(sorted(geneplot.items(),key=lambda t: t[0]))
		summe = sum(olist.values())
		freq = [float(x)/float(summe) for x in olist.values()]
		
		#Create plot
		fig = plt.figure()
		width = .35
		ind = np.arange(len(geneplot.keys()))
		plt.bar(ind, freq)
		plt.xticks(ind + width, geneplot.keys())
		locs, labels = plt.xticks() 
		plt.setp(labels, rotation=90)
		plt.show()

		fig.savefig(figname)
		print("Saved bar plot as: "+figname)
Example #11
0
def plotSummaryBar(library, num, eventNames, sizes, times, events):
  import numpy as np
  import matplotlib.pyplot as plt

  eventColors = ['b', 'g', 'r', 'y']
  arches = sizes.keys()
  names  = []
  N      = len(sizes[arches[0]])
  width  = 0.2
  ind    = np.arange(N) - 0.25
  bars   = {}
  for arch in arches:
    bars[arch] = []
    bottom = np.zeros(N)
    for event, color in zip(eventNames, eventColors):
      names.append(arch+' '+event)
      times = np.array(events[arch][event])[:,0]
      bars[arch].append(plt.bar(ind, times, width, color=color, bottom=bottom))
      bottom += times
    ind += 0.3

  plt.xlabel('Number of Dof')
  plt.ylabel('Time (s)')
  plt.title('GPU vs. CPU Performance on '+library+' Example '+str(num))
  plt.xticks(np.arange(N), map(str, sizes[arches[0]]))
  #plt.yticks(np.arange(0,81,10))
  #plt.legend( (p1[0], p2[0]), ('Men', 'Women') )
  plt.legend([bar[0] for bar in bars[arches[0]]], eventNames, 'upper right', shadow = True)

  plt.show()
  return
def test_rotated_labels_parameters_different_values(x_tick_label_width,
                                                    y_tick_label_width):
    fig, ax = __plot()

    plt.xticks(ha='left', rotation=90)
    plt.yticks(ha='left', rotation=90)
    ax.xaxis.get_majorticklabels()[0].set_rotation(20)
    ax.yaxis.get_majorticklabels()[0].set_horizontalalignment('right')

    # convert to tikz file
    _, tmp_base = tempfile.mkstemp()
    tikz_file = tmp_base + '_tikz.tex'

    extra_dict = {}

    if x_tick_label_width:
        extra_dict['x tick label text width'] = x_tick_label_width
    if y_tick_label_width:
        extra_dict['y tick label text width'] = y_tick_label_width

    matplotlib2tikz.save(
        tikz_file,
        figurewidth='7.5cm',
        extra_axis_parameters=extra_dict
        )

    # close figure
    plt.close(fig)

    # delete file
    os.unlink(tikz_file)
def test_rotated_labels_parameters(x_alignment, y_alignment,
                                   x_tick_label_width, y_tick_label_width,
                                   rotation):
    fig, _ = __plot()

    if x_alignment:
        plt.xticks(ha=x_alignment, rotation=rotation)
    if y_alignment:
        plt.yticks(ha=y_alignment, rotation=rotation)

    # convert to tikz file
    _, tmp_base = tempfile.mkstemp()
    tikz_file = tmp_base + '_tikz.tex'

    extra_dict = {}

    if x_tick_label_width:
        extra_dict['x tick label text width'] = x_tick_label_width
    if y_tick_label_width:
        extra_dict['y tick label text width'] = y_tick_label_width

    matplotlib2tikz.save(
        tikz_file,
        figurewidth='7.5cm',
        extra_axis_parameters=extra_dict
        )

    # close figure
    plt.close(fig)

    # delete file
    os.unlink(tikz_file)
Example #14
0
def plt_data():
    t = [[0,1], [1,0], [1, 1], [0, 0]]
    t2 = [1, 1, 1, 0]
    X = np.array(t)
    Y = np.array(t2)

    h = .02  # step size in the mesh

    logreg = linear_model.LogisticRegression(C=1e5)

    # we create an instance of Neighbours Classifier and fit the data.
    logreg.fit(X, Y)
    # Plot the decision boundary. For that, we will assign a color to each
    # point in the mesh [x_min, m_max]x[y_min, y_max].
    x_min, x_max = X[:, 0].min() - .5, X[:, 0].max() + .5
    y_min, y_max = X[:, 1].min() - .5, X[:, 1].max() + .5
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    Z = logreg.predict(np.c_[xx.ravel(), yy.ravel()])

    # Put the result into a color plot
    Z = Z.reshape(xx.shape)
    plt.figure(1, figsize=(4, 3))
    plt.pcolormesh(xx, yy, Z, cmap=plt.cm.Paired)

    # Plot also the training points
    plt.scatter(X[:, 0], X[:, 1], c=Y, edgecolors='k', cmap=plt.cm.Paired)
    plt.xlabel('Sepal length')
    plt.ylabel('Sepal width')

    plt.xlim(xx.min(), xx.max())
    plt.ylim(yy.min(), yy.max())
    plt.xticks(())
    plt.yticks(())

    plt.show()
def plot_top_candidates(tweets, n, gop, save_to = None): 
  '''
  Plots the counts of top n candidate pair mentions given a Tweets class.
  Note: used for task 2.  
  ''' 
  counts = tweets.top_pairs(n, gop)

  pairs = [] 
  mentions = [] 
  for pair, ment in counts: 
    p = pair.split("|")
    c0 = CANDIDATE_NAMES[ p[0] ] 
    c1 = CANDIDATE_NAMES[ p[1] ]
    pairs.append(c0 + "\n" + c1)
    mentions.append(ment)

  

  fig = plt.figure(figsize = (FIGWIDTH, FIGHEIGHT)) 
  plt.bar(range(len(counts)), mentions)
  plt.xticks(range(len(counts)), pairs, rotation = 'vertical')

  if gop: 
    plt.title("Pairs of GOP Candidates Mentioned most Frequently together")
  else: 
    plt.title("Pairs of Candidates Mentioned most Frequently together")
  plt.xlabel("Number of Mentions")
  plt.ylabel("Number of Tweets")

  plt.show()
  if save_to: 
    fig.savefig(save_to)
Example #16
0
    def plot_impressions(self, *args, **kwargs):

        """
        Plots impressions over the duration of the test
        Allow setting a time range
        And Smoothing by taking an avergae over a window of records
        """
        
        # set up list of banner to process
        if len(args) == 0:
            names = self.names
        else:
            names = args

        #process keyword arguments
        smooth = kwargs.get('smooth', 1)
        start = kwargs.get('start', '2000')
        stop = kwargs.get('stop', '2050')

        fig = plt.figure(figsize=(10, 6), dpi=80)
        ax = fig.add_subplot(111)
        plt.xticks(rotation=70)
        formatter = DateFormatter('%Y-%m-%d %H:%M')

        plt.gcf().axes[0].xaxis.set_major_formatter(formatter)

        for name in names:
            d = self.data[name]['impressions']
            d = d[start:stop]        
            d = pd.rolling_mean(d, smooth)
            ax.plot(d.index, d['count'], label=name)

        ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))
        plt.ylabel('impressions')
        plt.show()
def plot_per_min_debate(tweets, cands, interval, \
  start = DEBATE_START // 60, end = DEBATE_END // 60, tic_inc = 15, save_to = None): 
  '''
  Plots data from beg of debate to end. For Task 4a. 
  Note: start and end should be in minutes, not seconds
  '''

  fig = plt.figure(figsize = (FIGWIDTH, FIGHEIGHT))

  period = range(start, end, interval)
  c_dict = tweets.get_candidate_mentions_per_minute(cands, interval, period)

  y = np.row_stack()
  for candidate in c_dict: 
    plt.plot(period, c_dict[candidate], label = CANDIDATE_NAMES[candidate])

  if interval == 1: 
    plt.title("Mentions per Minute During Debate")
  else: 
    plt.title("Mentions per {} minutes before, during, and after debate".\
      format(interval))
  plt.xlabel("Time")
  plt.ylabel("Number of Tweets")
  plt.legend()

  ticks_range = range(start, end, tic_inc)
  labels = list(map(lambda x: str(x - start) + " min", ticks_range))
  plt.xticks(ticks_range, labels, rotation = 'vertical')
  plt.xlim( (start, end) )
  
  if save_to: 
    fig.savefig(save_to)
  plt.show()
Example #18
0
    def plotPath(self, seq, poses_gt, poses_result):
        plot_keys = ["Ground Truth", "Ours"]
        fontsize_ = 20
        plot_num = -1

        poses_dict = {}
        poses_dict["Ground Truth"] = poses_gt
        poses_dict["Ours"] = poses_result

        fig = plt.figure()
        ax = plt.gca()
        ax.set_aspect('equal')

        for key in plot_keys:
            pos_xz = []
            # for pose in poses_dict[key]:
            for frame_idx in sorted(poses_dict[key].keys()):
                pose = poses_dict[key][frame_idx]
                pos_xz.append([pose[0, 3], pose[2, 3]])
            pos_xz = np.asarray(pos_xz)
            plt.plot(pos_xz[:, 0], pos_xz[:, 1], label=key)

        plt.legend(loc="upper right", prop={'size': fontsize_})
        plt.xticks(fontsize=fontsize_)
        plt.yticks(fontsize=fontsize_)
        plt.xlabel('x (m)', fontsize=fontsize_)
        plt.ylabel('z (m)', fontsize=fontsize_)
        fig.set_size_inches(10, 10)
        png_title = "sequence_{:02}".format(seq)
        plt.savefig(self.plot_path_dir + "/" + png_title + ".pdf", bbox_inches='tight', pad_inches=0)
def plot_stack_candidates(tweets, cands, interval, start = 0, \
  end = MAX_TIME // 60, tic_inc = 120, save_to = None): 
  '''
  Plots stackplot for the candidates in list cands over the time interval
  ''' 

  period = range(start, end, interval)
  percent_dict = tweets.mention_minute_percent(cands, interval, period)

  y = [] 
  fig = plt.figure(figsize = (FIGWIDTH, FIGHEIGHT))
  legends = [] 
  for candidate in percent_dict:
    y.append(percent_dict[candidate]) 
    legends.append(CANDIDATE_NAMES[candidate])
  plt.stackplot(period, y)

  plt.title("Percentage of Mentions per {} minutes before, during, \
    and after debate".format(interval))
  plt.xlabel("Time")
  plt.ylabel("Number of Tweets")
  plt.legend(y, legends)

  ticks_range = range(start, end, tic_inc)
  labels = list(map(lambda x: str(x - start) + " min", ticks_range))
  plt.xticks(ticks_range, labels, rotation = 'vertical')
  plt.xlim( (start, end) )
  plt.ylim( (0.0, 1.0))
  
  if save_to: 
    fig.savefig(save_to)
  plt.show()
Example #20
0
def make_overview_plot(filename, title, noip_arrs, ip_arrs):
    plt.title("Inner parallelism - " + title)

    
    plt.ylabel('Time (ms)', fontsize=12)

    x = 0
    barwidth = 0.5
    bargroupspacing = 1.5

    for z in zip(noip_arrs, ip_arrs):
        noip,ip = z
        noip_mean,noip_conf = conf_stats(noip)
        ip_mean,ip_conf = conf_stats(ip)

        b_noip = plt.bar(x, noip_mean, barwidth, color='r', yerr=noip_conf, ecolor='black', alpha=0.7)
        x += barwidth

        b_ip = plt.bar(x, ip_mean, barwidth, color='b', yerr=ip_conf, ecolor='black', alpha=0.7)
        x += bargroupspacing

    plt.xticks([0.5, 2.5, 4.5], ['50k', '100k', '200k'], rotation='horizontal')

    fontP = FontProperties()
    fontP.set_size('small')

    plt.legend([b_noip, b_ip], \
        ('no inner parallelism', 'inner parallelism'), \
        prop=fontP, loc='upper center', bbox_to_anchor=(0.5, -0.05), fancybox=True, shadow=True, ncol=2)
   
    plt.ylim([0,62000])
    plt.savefig(output_file(filename))
    plt.clf()
	def plotFFT(self):
	# Generates plot of the FFT output. To view, run plotFFT.py in a separate terminal
		figure1 = plt.figure(num= None, figsize=(12,12), dpi=80, facecolor='w', edgecolor='w')
		plot1 = figure1.add_subplot(111)
		line1, = plot1.plot( np.arange(0,512,0.5), np.zeros(1024), 'g-')
		plt.xlabel('freq (MHz)',fontsize = 12)
		plt.ylabel('Amplitude',fontsize = 12)
		plt.title('Pre-mixer FFT',fontsize = 12)
		plt.xticks(np.arange(0,512,50))
		plt.xlim((0,512))
		plt.grid()
		plt.show(block = False)
		count = 0 
		stop = 1.0e6
		while(count < stop):
			overflow = np.fromstring(self.fpga.read('overflow', 4), dtype = '>B')
			print overflow
			self.fpga.write_int('fft_snap_ctrl',0)
			self.fpga.write_int('fft_snap_ctrl',1)
			fft_snap = (np.fromstring(self.fpga.read('fft_snap_bram',(2**9)*8),dtype='>i2')).astype('float')
			I0 = fft_snap[0::4]
			Q0 = fft_snap[1::4]
			I1 = fft_snap[2::4]
			Q1 = fft_snap[3::4]
			mag0 = np.sqrt(I0**2 + Q0**2)
			mag1 = np.sqrt(I1**2 + Q1**2)
			fft_mags = np.hstack(zip(mag0,mag1))
			plt.ylim((0,np.max(fft_mags) + 300.))
			line1.set_ydata((fft_mags))
			plt.draw()
			count += 1
Example #22
0
def plot_wav_fft(wav_filename, desc=None):
    plt.clf()
    plt.figure(num=None, figsize=(6, 4))
    sample_rate, X = scipy.io.wavfile.read(wav_filename)
    spectrum = np.fft.fft(X)
    freq = np.fft.fftfreq(len(X), 1.0 / sample_rate)

    plt.subplot(211)
    num_samples = 200.0
    plt.xlim(0, num_samples / sample_rate)
    plt.xlabel("time [s]")
    plt.title(desc or wav_filename)
    plt.plot(np.arange(num_samples) / sample_rate, X[:num_samples])
    plt.grid(True)

    plt.subplot(212)
    plt.xlim(0, 5000)
    plt.xlabel("frequency [Hz]")
    plt.xticks(np.arange(5) * 1000)
    if desc:
        desc = desc.strip()
        fft_desc = desc[0].lower() + desc[1:]
    else:
        fft_desc = wav_filename
    plt.title("FFT of %s" % fft_desc)
    plt.plot(freq, abs(spectrum), linewidth=5)
    plt.grid(True)

    plt.tight_layout()

    rel_filename = os.path.split(wav_filename)[1]
    plt.savefig("%s_wav_fft.png" % os.path.splitext(rel_filename)[0],
                bbox_inches='tight')
Example #23
0
def plot_fidelity_lorentzian(constants):
	"""
		Plots the Fidelity vs FSS curve with and without decoherence.
	"""

	qd = QuantumDot(constants.xtau, constants.xxtau, constants.ptau, constants.FSS, constants.crosstau)

	fss = np.linspace(-10., 10., 500)*1e-6

	qd.crosstau = 0.
	no_decoherence = np.array([qd.ideal_fidelity_lorentzian(f)[0] for f in fss])

	qd.crosstau = 1.
	with_decoherence = np.array([qd.ideal_fidelity_lorentzian(f)[0] for f in fss])

	fss = fss/1e-6
	decoherence = qd.ideal_fidelity_lorentzian(1e-6)[1]

	plt.figure(figsize = (16./1.3, 9./1.3))
	plt.plot(fss, no_decoherence, 'r--', fss, with_decoherence, 'b--')

	plt.xlim([-10, 10]) ; plt.ylim([0.45, 1])
	plt.xlabel('Fine structure splitting $eV$') ; plt.ylabel('Fidelity')
	plt.xticks(np.linspace(-10, 10, 11))
	plt.legend(['No decoherence', 'With $1^{st}$ coherence: ' + np.array(decoherence).astype('|S3').tostring()])
	plt.show()
Example #24
0
    def make_line(
        x,
        y,
        f_name,
        title=None,
        legend=None,
        x_label=None,
        y_label=None,
        x_ticks=None,
        y_ticks=None,
    ):
        fig = plt.figure()

        if title is not None:
            plt.title(title, fontsize=16)
        if x_label is not None:
            plt.ylabel(x_label)
        if y_label is not None:
            plt.xlabel(y_label)
        if x_ticks is not None:
            plt.xticks(x, x_ticks)
        if y_ticks is not None:
            plt.yticks(y_ticks)

        if isinstance(y[0], list):
            for data in y:
                plt.plot(x, data)
        else:
            plt.plot(x, y)

        if legend is not None:
            plt.legend(legend)

        plt.savefig(f_name)
        plt.close(fig)
Example #25
0
def plot_gen(ping, now, t, nans, host, interactive=False, size="1280x640"):
    ''' Generates ping vs time plot '''
    if not interactive:
        import matplotlib
        matplotlib.use("Agg") # no need to load gui toolkit, can run headless
    import matplotlib.pyplot as plt
    
    size      = [int(dim) for dim in size.split('x')]
    datestr   = now[0].ctime().split()
    datestr   = datestr[0] + " " + datestr[1] + " " + datestr[2] + " " + datestr[-1]
    plt.figure(figsize=(size[0]/80.,size[1]/80.)) # dpi is 80
    plt.plot(now[~nans], ping[~nans], drawstyle='steps', marker='+')
    plt.title("Ping Results for {0}".format(host))
    plt.ylabel("Latency [ms]")
    plt.xlabel("Time, {0} [GMT -{1} hrs]".format(datestr, time.timezone/3600))
    plt.xticks(size=10)
    plt.yticks(size=10)
    plt.ylim(ping[~nans].min()-5, ping[~nans].max()+5)
    
    # plot packet losses
    start  = []
    finish = []
    for i in range(len(nans)):
        if nans[i] == True:
            if i == 0:
                start.append(i)
            elif nans[i] != nans[i-1]:
                start.append(i)
            #if i != len(nans) and nans[i+1] != nans[i]:
            #    finish.append(i)
                
    # add the red bars for bad pings
    for i in range(len(start)):
        plt.axvspan(now[start[i]], now[finish[i]+1], color='red')
    return plt
def export(data, F, k):
    '''Write data to a png image
    
    Arguments
    ---------
    data : numpy.ndarray
        array containing the data to be written as png image
    F : float
        feed rate of the current configuration
    k : float
        rate constant of the current configuration
    '''
        
    figsize = tuple(s / 72.0 for s in data.shape)
    fig = plt.figure(figsize=figsize, dpi=72.0, facecolor='white')
    fig.add_axes([0, 0, 1, 1], frameon=False)
    plt.xticks([])
    plt.yticks([])

    plt.imshow(data, cmap=plt.cm.RdBu_r, interpolation='bicubic')
    plt.gci().set_clim(0, 1)

    filename = './study/F{:03d}-k{:03d}.png'.format(int(1000*F), int(1000*k))
    plt.savefig(filename, dpi=72.0)
    plt.close()
Example #27
0
def fig(data, target):
    #FIXME
    plt.scatter(data, target,  color='black')
    plt.xticks(())
    plt.yticks(())

    plt.show()
Example #28
0
def filterFunc():
    rects = []
    hsv_planes = [[[]]]
    if os.path.isfile(Image_File):
        BGR=cv2.imread(Image_File)
        gray = cv2.cvtColor(BGR, cv2.COLOR_BGR2GRAY)
        img = gray
        f = np.fft.fft2(img)
        fshift = np.fft.fftshift(f)
        magnitude_spectrum = 20*np.log(np.abs(fshift))
        
        plt.subplot(221),plt.imshow(img, cmap = 'gray')
        plt.title('Input Image'), plt.xticks([]), plt.yticks([])
        
        plt.subplot(222),plt.imshow(magnitude_spectrum, cmap = 'gray')
        plt.title('Magnitude Spectrum'), plt.xticks([]), plt.yticks([])
        
        FiltzeredFFT = HighPassFilter(fshift, 60)
        plt.subplot(223),plt.imshow(np.abs(FiltzeredFFT), cmap = 'gray')
        plt.title('Filtered'), plt.xticks([]), plt.yticks([])
        
		
        f_ishift = np.fft.ifftshift(FiltzeredFFT)
        img_back = np.fft.ifft2(f_ishift)
        img_back = np.abs(img_back)
        plt.subplot(224),plt.imshow(np.abs(img_back), cmap = 'gray')
        plt.title('Filtered Image'), plt.xticks([]), plt.yticks([])
        plt.show()
def plot_t_converge_3(delta_t, t_min_mic, t_min_mac, t_min_ber):
    
    fig = plt.figure()
    ax = plt.gca()
    N = 5   
    
    
    bp = plt.boxplot([delta_t*t_min_mic, delta_t*t_min_mac, delta_t*t_min_ber],
                     notch=0, sym='+', vert=1, whis=1.5) #,medianprops=medianprops)
    plt.setp(bp['boxes'], color='black')
    plt.setp(bp['whiskers'], color='black')
    plt.setp(bp['fliers'], color='black', marker='+')
    
    #off = 1.0
    #ymin = delta_t * np.min([t_min_mic, t_min_mac, t_min_ber])
    #ymax = delta_t * np.max([t_min_mic, t_min_mac, t_min_ber])
    ax.set_ylim([0, 10.0])    
    ax.set_xlim([0.5, N-1.5])

    #plt.legend(loc='upper right', shadow=False, fontsize='large')     
    plt.ylabel('Time [s]')    
    plt.xlabel('Optimization Methods')
    #plt.yaxis.grid(True, linestyle='-', which='major', color='lightgrey', alpha=0.5)
    labels = ['Micro', 'Macro', 'Berman']
    x = [1,2,3]    
    plt.xticks(x, labels, rotation='vertical')

    return fig
Example #30
0
def resetTicks(x, y=None):
    """Reset X (and Y) axis ticks using values in given *array*.  Ticks in the
    current figure should not be fractional values for this function to work as
    expected."""

    import matplotlib.pyplot as plt
    if x is not None:
        try:
            xticks = plt.xticks()[0]
            xlist = list(xticks.astype(int))
            if xlist[-1] > len(x):
                xlist.pop()
            if xlist:
                xlist = list(x[xlist])
                plt.xticks(xticks, xlist + [''] * (len(xticks) - len(xlist)))
        except:
            LOGGER.warning('xticks could not be reset.')
    if y is not None:
        try:
            yticks = plt.yticks()[0]
            ylist = list(yticks.astype(int))
            if ylist[-1] > len(y):
                ylist.pop()
            if ylist:
                ylist = list(y[ylist])
                plt.yticks(yticks, ylist + [''] * (len(yticks) - len(ylist)))
        except:
            LOGGER.warning('xticks could not be reset.')
Example #31
0
def run(controller):
    maps_initialized = False
    while(True):
        #sleepで更新速度を制御
        time.sleep(0.1)
        frame = controller.frame()
        image = frame.images[0]
        if image.is_valid:
            if not maps_initialized:
                left_coordinates, left_coefficients = convert_distortion_maps(frame.images[0])
                right_coordinates, right_coefficients = convert_distortion_maps(frame.images[1])
                maps_initialized = True

            undistorted_left = undistort(image, left_coordinates, left_coefficients, 400, 400)
            undistorted_right = undistort(image, right_coordinates, right_coefficients, 400, 400)

            #画像を2値化(白黒に処理)
            ret,hand = cv2.threshold(undistorted_right,70,255,cv2.THRESH_BINARY)

            my_hand = hand[80:320,40:360]

            # 以下、最も広い白領域のみを残すための計算
            # まず、白領域の塊(クラスター)にラベルを振る
            img_dist, img_label = cv2.distanceTransformWithLabels(255-my_hand, cv2.DIST_L2, 5)
            img_label = np.uint8(img_label) & my_hand
            # ラベル0は黒領域なので除外
            img_label_not_zero = img_label[img_label != 0]
            # 最も多く現れたラベルが最も広い白領域のラベル
            if len(img_label_not_zero) != 0:
                m = stats.mode(img_label_not_zero)[0]
            else:
                m = 0
            # 最も広い白領域のみを残す
            this_hand = np.uint8(img_label == m)*255

            #膨張
            kernel = np.ones((5,5),np.uint8)
            this_hand = cv2.dilate(this_hand,kernel,iterations = 1)

            # 輪郭を抽出
            contours,hierarchy = cv2.findContours(this_hand,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
            cnt = contours[0]

            #重心を求める
            mu = cv2.moments(this_hand, False)
            mx,my= int(mu["m10"]/mu["m00"]) , int(mu["m01"]/mu["m00"])

            #手首の位置を求める
            frame = controller.frame()
            righthand = frame.hands.rightmost
            arm = righthand.arm

            i_box = frame.interaction_box
            normalized_tip = i_box.normalize_point(arm.wrist_position)
            app_x = 160  * normalized_tip.x + 80
            app_y = 120 * (normalized_tip.z) + 60
            app = (int(app_x),int(app_y))

            #重心と手首の位置から回転させる
            angle = 90 + math.degrees(math.atan2(my-app[1],mx-app[0]))
            trans = cv2.getRotationMatrix2D((mx,my), angle , 1.0)
            this_hand = cv2.warpAffine(this_hand, trans, (360,240))


            # 最大の白領域からscikit-learnに入力するためのベクトルを取得
            hand_vector = getImageVector(this_hand)

            # 学習済のニューラルネットワークから分類結果を取得
            result = clf.predict(hand_vector)
            # 分類結果を表示
            print(hand_class[result[0]])

            pp = clf.predict_proba(hand_vector)[0]
            #for i in range(6):
                #print(str(i) + ":{0:.10f}".format(Decimal(pp[i])))
            hc = [0,1,2,3,4,5]
            plt.cla()
            plt.bar(hc,pp)
            plt.xticks(hc,hand_class)
            plt.ylim([0,1])
            plt.draw()

            plt.pause(0.01)

            # 得られた二値化画像を画面に表示
            cv2.imshow('hand', this_hand)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break