Example #1
0
def plot_single_1(fig,xLog,yLog,vx,vy,vlabs,titX,titY,titre):
  # fig= subplot(1,1,1)
  fig.grid(color='r', linestyle='-', linewidth=0.2)
  fig.grid(True)

  fig.set_xlabel(titX)
  fig.set_ylabel(titY)
  fig.set_title(titre) #, fontsize=fontsize)
  # fig.text(min(vx),max(vy),textt,
  #  fontsize=16,ha = 'left', va = 'top')
  
  # fig.set_xlim(0,1.)
  # fig.set_xlim(1e-3,1e+3)
  #fig.semilogx(A[iMin:iMax,iX],A[iMin:iMax,iY],  'bo')
  
  if xLog and yLog:
    fig.loglog(vx, vy, 'bo')
  else:
    if xLog:
      fig.semilogx(vx, vy, 'bo')
    elif yLog:
      fig.semilogy(vx, vy, 'bo')
    else:
      fig.plot(vx, vy, 'bo')
  
  if len(vlabs)>0:
    for label, x, y in zip(vlabs, vx, vy):
      plt.annotate(
        label, 
        xy = (x, y),
        xytext = (-2,2),
        textcoords = 'offset points', 
        ha = 'right', 
        va = 'bottom')
def plot_mixtures_vs_model(K):
    prefix = "mixtures_vs_model_K%02d" % K
    plt.figure(figsize=(5,5))
    plt.clf()
    for model in models[0:5]:
        pars = get_pars(model, K)
        amps = pars[0:K]
        sigmas = np.sqrt(pars[K:2 * K])
        plt.plot(sigmas, amps, "k-", alpha=0.5)
        plt.plot(sigmas, amps, "ko", ms=3.0)
        label = model
        tweak = 0.
        if model == "ser5": tweak = 5.
        if model == "dev": tweak = 1.
        plt.annotate(label, [sigmas[0], amps[0]], xytext=[-2,-10], textcoords="offset points", va="baseline", ha="center")
        plt.annotate(label, [sigmas[-1], amps[-1]], xytext=[4,-4+tweak], textcoords="offset points", va="baseline", ha="left")
    model = "ser"
    plt.xlabel(r"root-variance $\sqrt{v^{\mathrm{%s}}_m}$ (units of half-light radii)" % model)
    plt.ylabel(r"amplitudes $c^{\mathrm{%s}}_m$" % model)
    plt.title(r"approximations to ser profiles at $M^{\mathrm{ser}}=%d$" % K)
    plt.loglog()
    plt.xlim(0.5e-4, 2.e1)
    plt.ylim(0.5e-4, 2.e1)
    hogg_savefig(prefix + ".png")
    hogg_savefig(prefix + ".pdf")
    return None
def plot_mixtures_vs_K(model):
    prefix = "mixtures_vs_K_%s" % model
    plt.figure(figsize=(5,5))
    plt.clf()
    for K in Ks:
        pars = get_pars(model, K)
        amps = pars[0:K]
        sigmas = np.sqrt(pars[K:2 * K])
        plt.plot(sigmas, amps, "k-", alpha=0.5)
        plt.plot(sigmas, amps, "ko", ms=3.0)
        label = r"%d" % K
        tweak = 0.
        if model == "dev" or model == "luv":
            tweak = 4
            if K == 10:
                tweak = -2
        if model == "lux":
            tweak = 4 * (7 - K)
        plt.annotate(label, [sigmas[0], amps[0]], xytext=[-4,-4], textcoords="offset points", va="baseline", ha="right")
        plt.annotate(label, [sigmas[-1], amps[-1]], xytext=[4,-4+tweak], textcoords="offset points", va="baseline", ha="left")
    plt.xlabel(r"root-variance $\sqrt{v^{\mathrm{%s}}_m}$ (units of half-light radii)" % model)
    plt.ylabel(r"amplitudes $c^{\mathrm{%s}}_m$" % model)
    plt.title(r"approximations to %s" % model)
    plt.loglog()
    plt.xlim(0.5e-4, 2.e1)
    plt.ylim(0.5e-4, 2.e1)
    hogg_savefig(prefix + ".png")
    hogg_savefig(prefix + ".pdf")
    return None
Example #4
0
File: model.py Project: kdz/pystemm
def graph_file(obj, func_name, param, range, highlights):
    ## plots the named function on obj, taking param over its range (start, end)
    ## highlights are pairs of (x_value, "Text_to_show") to annotate on the graph plot
    ## saves the plot to a file and returns full file name

    import numpy, pylab

    func = getattr(obj, func_name)
    f = numpy.vectorize(func)
    x = numpy.linspace(*range)
    y = f(x)
    pylab.rc('font', family='serif', size=20)
    pylab.plot(x, y)
    pylab.xlabel(param)
    pylab.ylabel(func_name)
    hi_pts = [pt for pt, txt in highlights]
    pylab.plot(hi_pts, f(hi_pts), 'rD')
    for pt, txt in highlights:
        pt_y = func(pt)
        ann = txt + "\n(%s,%s)" % (pt, pt_y)
        pylab.annotate(ann, xy=(pt, pt_y))

    import os, time

    file = os.path.dirname(__file__) + "/generated_graphs/%s.%s.%s.pdf" % (type(obj).__name__, func_name, time.time())
    pylab.savefig(file, dpi=300)
    pylab.close()
    return file
def scattertext(X, phns, title):
    assert X.shape[1] == 2
    pl.scatter(X[:,0], X[:,1], s=0)
    for i, phn in enumerate(phns):
        pl.annotate(phn, (X[i,0], X[i,1]))
    pl.title(title)
    pl.show()
Example #6
0
def plot_words(wordVectors, set1p, set1n, imgFile):
  
  X = []
  labels = []
  for word in set1p+set1n:
    if word in wordVectors:
      labels.append(word)
      X.append(wordVectors[word])
    
  X = numpy.array(X)
  for r, row in enumerate(X):
    X[r] /= math.sqrt((X[r]**2).sum() + 1e-6) 
  
  Y = tsne(X, 2, 80, 20.0);
  Plot.scatter(Y[:,0], Y[:,1], s=0.1)
  for label, x, y in zip(labels, Y[:, 0], Y[:, 1]):
    if label in set1p:
      Plot.annotate(
        label, color="green", xy = (x, y), xytext = None,
        textcoords = None, bbox = None, arrowprops = None, size=10
      )
    if label in set1n:
      Plot.annotate(
        label, color="red", xy = (x, y), xytext = None,
        textcoords = None, bbox = None, arrowprops = None, size=10
      )

  Plot.savefig(imgFile, bbox_inches='tight')
  Plot.close()
	def create_plot_2d_speeches(self, withLabels = True):
		if withLabels:
			font = { 'fontname':'Tahoma', 'fontsize':0.5, 'verticalalignment': 'top', 'horizontalalignment':'center' }
			labels= [ (i['who'], i['date']) for i in self.data ]
			pylab.subplots_adjust(bottom =0.1)
			pylab.scatter(self.speech_2d[:,0], self.speech_2d[:,1], marker = '.' ,cmap = pylab.get_cmap('Spectral'))
			for label, x, y in zip(labels, self.speech_2d[:, 0], self.speech_2d[:, 1]):
			    pylab.annotate(
			        label, 
			        xy = (x, y), xytext = None,
			        ha = 'right', va = 'bottom', **font)
			        #,textcoords = 'offset points',bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),
			        #arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))

			pylab.title('U.S. Presidential Speeches(1790-2006)')
			pylab.xlabel('X')	
			pylab.ylabel('Y')

			pylab.savefig('plot_with_labels', bbox_inches ='tight', dpi = 1000, orientation = 'landscape', papertype = 'a0')
		else:
			pylab.subplots_adjust(bottom =0.1)
			pylab.scatter(self.speech_2d[:,0], self.speech_2d[:,1], marker = 'o' ,cmap = pylab.get_cmap('Spectral'))
			pylab.title('U.S. Presidential Speeches(1790-2006)')
			pylab.xlabel('X')	
			pylab.ylabel('Y')
			pylab.savefig('plot_without_labels', bbox_inches ='tight', dpi = 1000, orientation = 'landscape', papertype = 'a0')
		pylab.close()
Example #8
0
def PlotNumberOfTags(corpus):
    word_tag_dict = defaultdict(set)

    for (word, tag) in corpus:
        word_tag_dict[word].add(tag)
    # using Counter for efficiency (leaner than FreqDist)
    C = Counter(len(val) for val in word_tag_dict.itervalues())

    pylab.subplot(211)
    pylab.plot(C.keys(), C.values(), '-go', label='Linear Scale')
    pylab.suptitle('Word Ambiguity:')
    pylab.title('Number of Words by Possible Tag Number')
    pylab.box('off')                 # for better appearance
    pylab.grid('on')                 # for better appearance
    pylab.ylabel('Words With This Number of Tags (Linear)')
    pylab.legend(loc=0)
    # add value tags
    for x,y in zip(C.keys(), C.values()):
        pylab.annotate(str(y), (x,y + 0.5))

    pylab.subplot(212)
    pylab.plot(C.keys(), C.values(), '-bo', label='Logarithmic Scale')
    pylab.yscale('log') # to make the graph more readable, for the log graph version
    pylab.box('off')                 # for better appearance
    pylab.grid('on')                 # for better appearance
    pylab.xlabel('Number of Tags per Word')
    pylab.ylabel('Words With This Number of Tags (Log)')
    pylab.legend(loc=0)
    # add value tags
    for x,y in zip(C.keys(), C.values()):
        pylab.annotate(str(y), (x,y + 0.5))
        
    pylab.show()
Example #9
0
def plot_dens(x, y, filename, point):                   

    majorLocator   = MultipleLocator(1)
    majorFormatter = FormatStrFormatter('%d')
    minorLocator   = MultipleLocator(0.2)
  
#    fig = pl.figure()   
    fig, ax = plt.subplots()                        
    pl.plot(x, y, 'b-', x, y, 'k.')
    fig.suptitle(filename)
    # pl.plot(z, R, 'k.')
    #fig.set_xlim(0,4.0)
    #fig.set_ylim(0,3)                
    # fig = plt.gcf()
    plt.xticks(ticki)
#    plt.xticks(range(0,d_max_y,50))
    pl.xlim(0,12)
    pl.ylim(0,max(y))
    pl.xlabel('z [nm]')
    pl.ylabel('Density [kg/nm3]')
#    pl.grid(b=True, which='both', axis='both', color='r', linestyle='-', linewidth=0.5)
    # fig.set_size_inches(18.5,10.5)
    pl.annotate('first peak', xy=(point[0], point[1]),  xycoords='data', xytext=(-50, 30), textcoords='offset points', arrowprops=dict(arrowstyle="->"))

    ax.xaxis.set_major_locator(majorLocator)
    ax.xaxis.set_major_formatter(majorFormatter)

    #for the minor ticks, use no labels; default NullFormatter
    ax.xaxis.set_minor_locator(minorLocator)

    ax.xaxis.grid(True, which='minor')
    ax.yaxis.grid(True, which='major')

    return fig
	def geom_Plot(self,plot_Node_Names = 0,Highlights = None):
		pp.figure()
		pp.title('Network Geometry')
		for i in self.nodes:
			if i.type == 'Node':
				symbol = 'o'
				size = 10
			elif i.type == 'Reservoir':
				symbol = 's'
				size = 20
			elif i.type == 'Tank':
				symbol = (5,2)
				size = 20	
			c = 'k'
			if i.Name in Highlights:
				size = 40	
				c = 'r'	
				
			pp.scatter([i.xPos],[i.yPos],marker = symbol,s = size,c=c)
			if plot_Node_Names != 0:
				pp.annotate(i.Name,(i.xPos,i.yPos))
			
		for i in self.pipes:
			pp.plot([i.x1,i.x2],[i.y1,i.y2],'k')
			
		for i in self.valves:
			pp.plot([i.x1,i.x2],[i.y1,i.y2],'r')
			
		for i in self.pumps:
			pp.plot([i.x1,i.x2],[i.y1,i.y2],'g')
		pp.axis('equal')
		pp.show()
Example #11
0
def display_data(word_vectors, words, target_words=None):
  target_matrix = word_vectors.copy()
  if target_words:
    target_words = [line.strip().lower() for line in open(target_words)][:2000]
    rows = [words.index(word) for word in target_words if word in words]
    target_matrix = target_matrix[rows,:]
  else:
    rows = np.random.choice(len(word_vectors), size=1000, replace=False)
    target_matrix = target_matrix[rows,:]
  reduced_matrix = tsne(target_matrix, 2);

  Plot.figure(figsize=(200, 200), dpi=100)
  max_x = np.amax(reduced_matrix, axis=0)[0]
  max_y = np.amax(reduced_matrix, axis=0)[1]
  Plot.xlim((-max_x,max_x))
  Plot.ylim((-max_y,max_y))

  Plot.scatter(reduced_matrix[:, 0], reduced_matrix[:, 1], 20);

  for row_id in range(0, len(rows)):
      target_word = words[rows[row_id]]
      x = reduced_matrix[row_id, 0]
      y = reduced_matrix[row_id, 1]
      Plot.annotate(target_word, (x,y))
  Plot.savefig("word_vectors.png");
def ManetPlot():
	index_mob=0
	index_route=00
	plotting_time=0

	pl.ion()
	fig,ax=pl.subplots()
	for index_mob in range(len(time_plot)):
# plot the nodes with the positions given by index_mob of x_plot and yplot
		pl.scatter(x_plot[index_mob],y_plot[index_mob],s=100,c='g')
#		print x_plot[index_mob],y_plot[index_mob]
		for i, txt in enumerate(n):
		        pl.annotate(txt,(x_plot[index_mob, i]+10,y_plot[index_mob, i]+10))
		pl.xlabel('x axis')
		pl.ylabel('y axis')
	# set axis limits
		pl.xlim(0.0, xRange)
		pl.ylim(0.0, yRange)
		pl.title("Position updation at "+str(time_plot[index_mob]))
#		print time_plot[index_mob],route_table_time[index_route],ntemp,route_table[index_route,1:3]

#		print_neighbors(neighbor_nodes_time,time_neighb,x_plot[index_mob,:],y_plot[index_mob,:])
		pl.show()
		pl.pause(.0005)
	# show the plot on the screen
		pl.clf()
Example #13
0
    def draw_results(self, all_results):
        ## Plot the map
        # Define some styles for plots
        found_style = {'linewidth':1.5,
                       'marker':'o',
                       'markersize':4,
                       'color':'w'}
        executed_style = {'linewidth':4,
                          'marker':'.',
                          'markersize':15,
                          'color':'b'}
#        pdb.set_trace()
        for r, run_result in enumerate(all_results):
            
            for i, iter_result in enumerate(run_result['iter_results']):
                
                # Plot the executed part
                self.plot_plan_line(iter_result['start_state'],
                               iter_result['plan_executed'],
                               **executed_style)
                pylab.annotate(str(i), xy=iter_result['start_state'], xytext=(5, 5), textcoords='offset points')
                
                # Plot the found plan
                self.plot_plan_line(iter_result['start_state'],
                               iter_result['plan_found'],
                               **found_style)
                
                pylab.savefig('map_' + str(r) + '_it' + str(i) + '.png')
Example #14
0
def stringtest():

    import Levenshtein

    strings = [
        "King Crimson",
        "King Lear",
        "Denis Leary",
        "George Bush",
        "George W. Bush",
        "Barack Hussein Obama",
        "Saddam Hussein",
        "George Leary",
    ]

    dist = distmatrix(strings, c=lambda x, y: 1 - Levenshtein.ratio(x, y))

    p = fastmap(dist, 2)
    import pylab

    pylab.scatter([x[0] for x in p], [x[1] for x in p], c="r")
    for i, s in enumerate(strings):
        pylab.annotate(s, p[i])

    pylab.title("Levenshtein distance mapped to 2D coordinates")
    #    pylab.show()
    pylab.savefig("fastmap2.png")
Example #15
0
    def _plot(self, fits_params, tau, tsys, r2, sec_el, fit, hot_sky, path):
        """
        図の出力、保存
        """
        fig = pylab.figure()
        pylab.grid()
        pylab.ylabel("log((Phot-Psky)/Phot)")
        pylab.xlabel("secZ")

        pylab.plot(sec_el, hot_sky, "o", markersize=7)
        pylab.plot(sec_el, fit)
        pylab.annotate(
            "tau = %.2f, Tsys* = %.2f, R^2 = %.3f" % (tau, tsys, r2),
            xy=(0.6, 0.9),
            xycoords="axes fraction",
            size="small",
        )

        # if (fits_params[0]["BACKEND"])[-1]=="1" : direction="H"
        # elif (fits_params[0]["BACKEND"])[-1]=="2" : direction="V"
        # else : pass
        # figure_name = str(fits_params[0]["MOLECULE"])+direction+".png"
        figure_name = str(fits_params[0]["MOLECULE"]) + ".png"
        # file_manager.mkdir(path)
        pylab.savefig(path + figure_name)
        # file_manager.mkdir('/home/1.85m/data/Qlook/skydip/' + path.split('/')[-1])
        # pylab.savefig('/home/1.85m/data/Qlook/skydip/'+ path.split('/')[-1] + '/' + figure_name)

        """ 
Example #16
0
def tracePlot(outpath, base_name, order_num, raw, fit, mask):

    pl.figure("Trace Plot", figsize=(6, 5), facecolor='white')
    pl.title('trace, ' + base_name + ", order " + str(order_num), fontsize=14)
    pl.xlabel('column (pixels)')
    pl.ylabel('row (pixels)')
    
#     yrange = offraw.max() - offraw.min()
 
    x = np.arange(raw.shape[0])
    
    pl.plot(x[mask], raw[mask], "ko", mfc="none", ms=1.0, linewidth=1, label="derived")
    pl.plot(x, fit, "k-", mfc="none", ms=1.0, linewidth=1, label="fit")
        
    pl.plot(x[np.logical_not(mask)], raw[np.logical_not(mask)], 
        "ro", mfc="red", mec="red", ms=2.0, linewidth=2, label="ignored")

    
    rms = np.sqrt(np.mean(np.square(raw - fit)))
    pl.annotate('RMS residual = ' + "{:.3f}".format(rms), (0.3, 0.8), xycoords="figure fraction")
    
    pl.minorticks_on()
    pl.grid(True)
    pl.legend(loc='best', prop={'size': 8})

    fn = constructFileName(outpath, base_name, order_num, 'trace.png')
    pl.savefig(fn)
    pl.close()
    log_fn(fn)
    
    return
def construct_gs_hist(del_bl=8.,num_bl=10,beam_sig=0.09,fq=0.1):
    save_tag = 'grid_del_bl_{0:.2f}_num_bl_{1}_beam_sig_{2:.2f}_fq_{3:.3f}'.format(del_bl,num_bl,beam_sig,fq)
    save_tag_mc = 'grid_del_bl_{0:.2f}_num_bl_{1}_beam_sig_{2:.2f}_fq_{3}'.format(del_bl,num_bl,beam_sig,fq)
    ys = load_mc_data('{0}/monte_carlo/{1}'.format(data_loc,save_tag_mc))
    print 'ys ',ys.shape
    
    alms_fg = qgea.generate_sky_model_alms(gsm_fits_file,lmax=3)
    alms_fg = alms_fg[:,2]

    baselines,Q,lms = load_Q_file(gh='grid',del_bl=del_bl,num_bl=num_bl,beam_sig=beam_sig,fq=fq,lmax=3)
    N = total_noise_covar(0.1,baselines.shape[0],'{0}/gsm_matrices/gsm_{1}.npz'.format(data_loc,save_tag))
    MQN = return_MQdagNinv(Q,N,num_remov=None)
    print MQN
    ahat00s = n.array([])
    for ii in xrange(ys.shape[1]):
        #_,ahat,_ = qgea.test_recover_alms(ys[:,ii],Q,N,alms_fg,num_remov=None)
        ahat = uf.vdot(MQN,ys[:,ii])
        ahat00s = n.append(n.real(ahat[0]),ahat00s)
    #print ahat00s
    print ahat00s.shape
    _,bins,_ = p.hist(ahat00s,bins=36,normed=True)

    # plot best fit line
    mu,sigma = norm.fit(ahat00s)
    print "mu, sigma = ",mu,', ',sigma
    y_fit = mpl.mlab.normpdf(bins,mu,sigma)
    p.plot(bins, y_fit, 'r--', linewidth=2)

    p.xlabel('ahat_00')
    p.ylabel('Probability')
    p.title(save_tag)
    p.annotate('mu = {0:.2f}\nsigma = {1:.2f}'.format(mu,sigma), xy=(0.05, 0.5), xycoords='axes fraction')
    p.savefig('./figures/monte_carlo/{0}.pdf'.format(save_tag))
    p.clf()
Example #18
0
def createPlot(dataY, dataX, ticksX, annotations, axisY, axisX, dostep, doannotate):
    if not ticksX:
        ticksX = dataX
    
    if dostep:
        py.step(dataX, dataY, where='post', linestyle='-', label=axisY) # where=post steps after point
    else:
        py.plot(dataX, dataY, marker='o', ms=5.0, linestyle='-', label=axisY)
    
    if annotations and doannotate:
        for note, x, y in zip(annotations, dataX, dataY):
            py.annotate(note, (x, y), xytext=(2,2), xycoords='data', textcoords='offset points')

    py.xticks(np.arange(1, len(dataX)+1), ticksX, horizontalalignment='left', rotation=30)
    leg = py.legend()
    leg.draggable()
    py.xlabel(axisX)
    py.ylabel('time (s)')

    # Set X axis tick labels as rungs
    #print zip(dataX, dataY)
  
    py.draw()
    py.show()
    
    return
Example #19
0
def add_timeslices():
    times = pylab.array([0,200,400,600,1000,1400,2000,2800,3400,4800]) 
    for t in times:
        thours = t / 3600.
        pylab.plot([-400e3,0.],[thours,thours],'k')
        pylab.annotate('%s seconds' % t,[0.,thours],[30e3,thours],\
              arrowprops={'width':1,'color':'k','frac':0.2,'shrink':0.1})
def transmission(path,g,src,dest):
 global disp_count
 global bar_colors
 global edge_colors
 global node_colors
 k=0
 j=0
 list_of_edges = g.edges() 
 for node in path :
  k=path.index(node)
  disp_count = disp_count + 1
  if k != (len(path)-1):
   k=path[k+1]
   j=list_of_edges.index((node,k))
   initialize_edge_colors(j)
   #ec[disp_count].remove(-3000) 
   pylab.subplot(121) 
   nx.draw_networkx(g,pos = nx.circular_layout(g),node_color= node_colors,edge_color = edge_colors)
   pylab.annotate("Source",node_positions[src])
   pylab.annotate("Destination",node_positions[dest])
   pylab.title("Transmission")

   he=initializeEnergies(disp_count)
   print he
   pylab.subplot(122)
   pylab.bar(left=[1,2,3,4,5],height=[300,300,300,300,300],width=0.5,color = ['w','w','w','w','w'],linewidth=0) 
   pylab.bar(left=[1,2,3,4,5],height=initializeEnergies(disp_count),width=0.5,color = 'b') 
   pylab.title("Node energies")
   #pylab.legend(["already passed throgh","passing" , "yet to pass"])
   pylab.xlabel('Node number')
   pylab.ylabel('Energy') 
   pylab.suptitle('Leach Protocol', fontsize=12)
   pylab.pause(2)
  else :
     return
def plot_prob_effector(sens, fpr, xmax=1, baserate=0.1):
    """Plots a line graph of P(effector|positive test) against
    the baserate of effectors in the input set to the classifier.
        
    The baserate argument draws an annotation arrow
    indicating P(pos|+ve) at that baserate
    """
    assert 0.1 <= xmax <= 1, "Max x axis value must be in range [0,1]"
    assert 0.01 <= baserate <= 1, "Baserate annotation must be in range [0,1]"
    baserates = pylab.arange(0, 1.05, xmax * 0.005)  
    probs = [p_correct_given_pos(sens, fpr, b) for b in baserates]
    pylab.plot(baserates, probs, 'r')
    pylab.title("P(eff|pos) vs baserate; sens: %.2f, fpr: %.2f" % (sens, fpr))
    pylab.ylabel("P(effector|positive)")
    pylab.xlabel("effector baserate")
    pylab.xlim(0, xmax)
    pylab.ylim(0, 1)
    # Add annotation arrow
    xpos, ypos = (baserate, p_correct_given_pos(sens, fpr, baserate))
    if baserate < xmax:
        if xpos > 0.7 * xmax:
            xtextpos = 0.05 * xmax
        else:
            xtextpos = xpos + (xmax-xpos)/5.
        if ypos > 0.5:
            ytextpos = ypos - 0.05
        else:
            ytextpos = ypos + 0.05
        pylab.annotate('baserate: %.2f, P(pos|+ve): %.3f' % (xpos, ypos), 
                       xy=(xpos, ypos), 
                       xytext=(xtextpos, ytextpos),
                       arrowprops=dict(facecolor='black', shrink=0.05))
    else:
        pylab.text(0.05 * xmax, 0.95, 'baserate: %.2f, P(pos|+ve): %.3f' % \
                   (xpos, ypos))
Example #22
0
def graphTSPResults(resultsDir,numberOfTours):
    x=[]
    y=[]
    files=[open("%s/objectiveFunctionReport.txt" % resultsDir),
       open("%s/fitnessReport.txt" % resultsDir)]
    for f in files:
        x.append([])
        y.append([])
        i=len(x)-1
        for line in f:
            line=line.split(',')
            if line[0] != "gen":
                x[i].append(int(line[0]))
                y[i].append(float(line[1] if i==1 else line[2]))
            
    ylen=len(y[0])
    pl.subplot(2,1,1)
    pl.plot(x[0],y[0],'bo')
    pl.ylabel('Minimum Distance')
    pl.title("TSP with a %s City Tour" % numberOfTours)
    pl.annotate("{0:,}".format(y[0][0]),xy=(x[0][0],y[0][0]),  xycoords='data',
             xytext=(30, -30), textcoords='offset points',
             arrowprops=dict(arrowstyle="->") )
    pl.annotate("{0:,}".format(y[0][ylen-1]),xy=(x[0][ylen-1],y[0][ylen-1]),  xycoords='data',
             xytext=(-30,30), textcoords='offset points',
             arrowprops=dict(arrowstyle="->") )

    pl.subplot(2,1,2)
    pl.plot(x[1],y[1],'go')
    pl.xlabel('Generation')
    pl.ylabel('Fitness')
    pl.savefig("%s/tsp_result.png" % resultsDir)
    pl.clf()
Example #23
0
def plot_datasets(dataset_ids, title=None, legend=True, labels=True):
    """
    Plots one or more dataset.

    :param dataset_ids: list of datasets to plot
    :type dataset_ids: list of integers
    :param title: title of the plot
    :type title: string
    :param legend: whether or not to show legend
    :type legend: boolean
    :param labels: whether or not to plot point labels
    :type labels: boolean
    """
    title = title if title else "Datasets " + ",".join(
        [str(d) for d in dataset_ids])
    pl.title(title)

    data = {k: v for k, v in npoints.items() if k in dataset_ids}

    lines = [pl.plot(zip(*p)[0], zip(*p)[1], 'o-')[0] for p in data.values()]

    if legend:
        pl.legend(lines, data.keys())

    if labels:
        for x, y, l in [i for s in data.values() for i in s]:
            pl.annotate(str(l), xy=(x, y), xytext=(x, y + 0.1))

    pl.grid(True)

    return pl
Example #24
0
def plot_embedding(X, y, labels=None, image_file_name=None, title=None, cmap='gnuplot', density=False):
    import matplotlib.pyplot as plt
    from matplotlib import offsetbox
    from PIL import Image

    if title is not None:
        plt.title(title)
    if density:
        embed_dat_matrix_2D(X, y=y, instance_colormap=cmap)
    else:
        plt.scatter(X[:, 0], X[:, 1], c=y, cmap=cmap, alpha=.7, s=30, edgecolors='gray')
        plt.xticks([])
        plt.yticks([])
    if image_file_name is not None:
        num_instances = X.shape[0]
        ax = plt.subplot(111)
        for i in range(num_instances):
            img = Image.open(image_file_name + str(i) + '.png')
            imagebox = offsetbox.AnnotationBbox(offsetbox.OffsetImage(img, zoom=1), X[i], pad=0, frameon=False)
            ax.add_artist(imagebox)
    if labels is not None:
        for id in range(X.shape[0]):
            label = str(labels[id])
            x = X[id, 0]
            y = X[id, 1]
            plt.annotate(label, xy=(x, y), xytext=(0, 0), textcoords = 'offset points')
Example #25
0
def draw_circle_arcs(arcs,n=100,label=False,full=False,dots=False,jitter=None):
  import pylab
  for p,poly in enumerate(arcs):
    X = poly['x']
    q = poly['q']
    Xn = roll(X,-1,axis=0)
    l = magnitudes(Xn-X)
    center = .5*(X+Xn)+.25*(1/q-q).reshape(-1,1)*rotate_left_90(Xn-X)
    if 0:
      print 'draw %d: x0 %s, x1 %s, center %s'%(0,X[0],Xn[0],center[0])
      radius = .25*l*(1/q+q)
      print 'radius = %s'%radius
      assert allclose(magnitudes(X-center),abs(radius))
    theta = array([2*pi]) if full else 4*atan(q)
    points = center.reshape(-1,1,2)+Rotation.from_angle(theta[:,None]*arange(n+1)/n)*(X-center).reshape(-1,1,2)
    if dots:
      pylab.plot(X[:,0],X[:,1],'.')
    if full:
      for i,pp in enumerate(points):
        pylab.plot(pp[:,0],pp[:,1],'--')
        pylab.plot(center[i,0],center[i,1],'+')
        if label:
          pylab.annotate(str(arcs.offsets[p]+i),center[i])
    else:
      if label:
        for i in xrange(len(poly)):
          pylab.annotate(str(arcs.offsets[p]+i),points[i,n//2])
      points = concatenate([points.reshape(-1,2),[points[-1,-1]]])
      if jitter is not None:
         points += jitter*random.uniform(-1,1,points.shape) # Jitter if you want to be able to differentiate concident points:
      pylab.plot(points[:,0],points[:,1])
Example #26
0
def demo():
    """
    Show the available interface functions and the corresponding probability
    density functions.
    """

    # Plot the cdf and pdf
    import pylab
    w = 10
    perf = Erf(w)
    ptanh = Tanh(w)
    plinear = Linear(2.35*w)

    #arrowprops=dict(arrowstyle='wedge', connectionstyle='arc3', fc='0.6')
    #bbox=dict(boxstyle='round', fc='0.8')

    z = pylab.linspace(-3*w, 3*w, 800)
    pylab.subplot(211)
    pylab.plot(z, perf.cdf(z))
    pylab.plot(z, ptanh.cdf(z))
    pylab.plot(z, plinear.cdf(z))
    pylab.axvline(w, linewidth=2)
    pylab.annotate('1-sigma', xy=(w*1.1, 0.2))
    pylab.legend(['erf', 'tanh'])
    pylab.grid(True)
    pylab.subplot(212)
    pylab.plot(z, perf.pdf(z))
    pylab.plot(z, ptanh.pdf(z))
    pylab.plot(z, plinear.pdf(z))
    pylab.axvline(w, linewidth=2)
    pylab.annotate('1-sigma', xy=(w*1.1, 0.2))
    pylab.legend(['erf', 'tanh', 'linear'])
    pylab.grid(True)
Example #27
0
def graphSimpleResults(resultsDir):
    x=[]
    y=[]
    files=[open("%s/objectiveFunctionReport.txt" % resultsDir),
       open("%s/fitnessReport.txt" % resultsDir)]
    for f in files:
        x.append([])
        y.append([])
        i=len(x)-1
        for line in f:
            line=line.split(',')
            if line[0] != "gen":
                x[i].append(int(line[0]))
                y[i].append(float(line[1]))

    ylen=len(y[0])
    pl.subplot(2,1,1)
    pl.plot(x[0],y[0],'bo')
    pl.ylabel('Maximum x')
    pl.title('Maximizing x**2 with SGA')
    pl.annotate("{0:,}".format(y[0][0]),xy=(x[0][0],y[0][0]),  xycoords='data',
             xytext=(50, 30), textcoords='offset points',
             arrowprops=dict(arrowstyle="->") )
    pl.annotate("{0:,}".format(y[0][ylen-1]),xy=(x[0][ylen-1],y[0][ylen-1]),  xycoords='data',
             xytext=(-30, -30), textcoords='offset points',
             arrowprops=dict(arrowstyle="->") )

    pl.subplot(2,1,2)
    pl.plot(x[1],y[1],'go')
    pl.xlabel('Generation')
    pl.ylabel('Fitness')
    pl.savefig("%s/simple_result.png" % resultsDir)
Example #28
0
def annotator(data, labels, lang):
    labelStyle = 'normal' if lang == 'en' else 'italic'
    color = 'blue' if lang == 'en' else 'red'
    for label, x, y in zip(labels, data[:, 0], data[:, 1]):
        if label in ['man','hombre','woman','mujer']:
            pylab.scatter([x],[y],20,[color])
            pylab.annotate(label, xy = (x, y), style = labelStyle) 
Example #29
0
def plotScoringFunction(data, bestParameterSet, patients, scoringFunction):
    x = []
    y = []
    labels = []
    for i in range(data.shape[1]):
        if (
            abs((data[:, i][0]) - (bestParameterSet[0])) < 0.00001
            and abs((data[:, i][2]) - (bestParameterSet[2])) < 0.00001
            and abs((data[:, i][1]) - (bestParameterSet[1])) < 0.00001
            and abs((data[:, i][3]) - (bestParameterSet[3])) < 0.00001
            and abs((data[:, i][4]) - (bestParameterSet[4])) < 0.00001
        ):
            x += [data[:, i][5]]
            y += [data[:, i][6]]
            labels += [patients[i]]

    scoringFunction(x, y, plot=True)
    for label, xi, yi in zip(labels, x, y):
        plt.annotate(
            label,
            xy=(xi, yi),
            textcoords="offset points",
            ha="right",
            va="bottom",
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=0"),
        )
Example #30
0
def demo_fwhm():
    """
    Show the available interface functions and the corresponding probability
    density functions.
    """

    # Plot the cdf and pdf
    import pylab
    w = 10
    perf = Erf.as_fwhm(w)
    ptanh = Tanh.as_fwhm(w)

    z = pylab.linspace(-w, w, 800)
    pylab.subplot(211)
    pylab.plot(z, perf.cdf(z))
    pylab.plot(z, ptanh.cdf(z))
    pylab.legend(['erf', 'tanh'])
    pylab.grid(True)
    pylab.subplot(212)
    pylab.plot(z, perf.pdf(z), 'b')
    pylab.plot(z, ptanh.pdf(z), 'g')
    pylab.legend(['erf', 'tanh'])

    # Show fwhm
    arrowprops = dict(arrowstyle='wedge', connectionstyle='arc3', fc='0.6')
    bbox = dict(boxstyle='round', fc='0.8')
    pylab.annotate('erf FWHM', xy=(w/2, perf.pdf(0)/2),
                   xytext=(-35, 10), textcoords="offset points",
                   arrowprops=arrowprops, bbox=bbox)
    pylab.annotate('tanh FWHM', xy=(w/2, ptanh.pdf(0)/2),
                   xytext=(-35, -35), textcoords="offset points",
                   arrowprops=arrowprops, bbox=bbox)

    pylab.grid(True)
Example #31
0
def sbsplot(spec, output, show_lines, transitions, z, x_axis, x_col, x_min,
            x_max, y_axis, y_col, identifier):
    """
    """

    pdf = PdfPages(output)

    specs = glob.glob(spec)
    crrls.natural_sort(specs)

    # If only one file is passed, it probably contains a list
    if len(specs) == 1:
        specs = np.genfromtxt(specs[0], dtype=str)
        try:
            specs.shape[1]
            specs = glob.glob(spec)
        # Or a single file is to be plotted
        except IndexError:
            pass

    for s in specs:

        data = np.loadtxt(s)
        x = data[:, x_col]
        y = data[:, y_col]

        # Determine the subband name
        try:
            sb = re.findall('{0}\d+'.format(identifier), s)[0]
        except IndexError:
            print("Could not find SB number.")
            print("Will use the file name.")
            sb = s

        # Begin ploting
        fig = plt.figure(frameon=False)
        fig.suptitle(sb)
        ax = fig.add_subplot(1, 1, 1, adjustable='datalim')
        ax.step(x, y, 'k-', lw=1, where='mid')
        # Mark the transitions?
        if show_lines:
            trans = transitions.split(',')
            for o, t in enumerate(trans):

                if x[~np.isnan(x)][0] > x[~np.isnan(x)][1]:
                    r = -1
                else:
                    r = 1

                qns, freqs = crrls.find_lines_sb(x[~np.isnan(x)][::r], t, z)
                ylbl = np.ma.masked_invalid(y).mean()
                for label, i, j in zip(qns, freqs, [ylbl] * len(freqs)):
                    plt.annotate(label,
                                 xy=(i, j),
                                 xytext=(-10, 15 * o + 5),
                                 size='x-small',
                                 textcoords='offset points',
                                 ha='right',
                                 va='bottom',
                                 bbox=dict(boxstyle='round,pad=0.5',
                                           fc='yellow',
                                           alpha=0.5),
                                 arrowprops=dict(arrowstyle='->',
                                                 connectionstyle='arc3,rad=0'))
                    #if len(qns) > 0:
                    plt.annotate(tprops[t][0],
                                 xy=(i, j),
                                 xytext=(-4, 0),
                                 textcoords='offset points',
                                 size='xx-small')
                    plt.plot(freqs, [ylbl] * len(freqs),
                             marker='|',
                             ls='none',
                             ms=25,
                             c=tprops[t][1],
                             mew=8,
                             alpha=0.8)
        ax.set_xlabel(x_axis)
        ax.set_ylabel(y_axis)
        if x_max:
            ax.set_xlim(x_min, x_max)
        pdf.savefig(fig)
        plt.close(fig)

    pdf.close()
Example #32
0
def RunAnimation(arg):
    import os, sys, time
    import subprocess
    import psutil
    import pylab as pl
    from IPython import display
    import matplotlib.gridspec as gridspec
    import seaborn as sns
    import pandas as pd
    import numpy as np

    print("RunAnimation")
    sys.stdout.flush()

    deviceCount = arg
    # Need this only for animation of GPU usage to be consistent with
    #from py3nvml.py3nvml import *
    import py3nvml
    maxNGPUS = int(subprocess.check_output("nvidia-smi -L | wc -l",
                                           shell=True))
    print("\nNumber of GPUS:", maxNGPUS)

    py3nvml.py3nvml.nvmlInit()
    total_deviceCount = py3nvml.py3nvml.nvmlDeviceGetCount()
    if deviceCount == -1:
        deviceCount = total_deviceCount
    #for i in range(deviceCount):
    #    handle = nvmlDeviceGetHandleByIndex(i)
    #    print("Device {}: {}".format(i, nvmlDeviceGetName(handle)))
    #print ("Driver Version:", nvmlSystemGetDriverVersion())
    print("Animation deviceCount=%d" % (deviceCount))

    file = os.getcwd() + "/error.txt"
    print("opening %s" % (file))
    fig = pl.figure(figsize=(9, 9))
    pl.rcParams['xtick.labelsize'] = 14
    pl.rcParams['ytick.labelsize'] = 14
    gs = gridspec.GridSpec(3, 2, wspace=0.3, hspace=0.4)
    ax1 = pl.subplot(gs[0, -2])
    ax2 = pl.subplot(gs[0, 1])
    ax3 = pl.subplot(gs[1:, :])
    fig.suptitle('H2O.ai Machine Learning $-$ Generalized Linear Modeling',
                 size=18)

    pl.gcf().subplots_adjust(bottom=0.2)

    #cb = False
    from matplotlib.colors import ListedColormap
    cm = ListedColormap(sns.color_palette("RdYlGn", 10).as_hex())
    cc = ax3.scatter([0.001, 0.001], [0, 0], c=[0, 1], cmap=cm)
    cb = pl.colorbar(cc, ax=ax3)
    os.system("mkdir -p images")
    i = 0
    while (True):
        #try:
        #print("In try i=%d" % i)
        #sys.stdout.flush()

        #cpu
        snapshot = psutil.cpu_percent(percpu=True)
        cpu_labels = range(1, len(snapshot) + 1)
        plot_cpu_perf(ax1, cpu_labels, snapshot)

        #gpu
        gpu_snapshot = []
        gpu_labels = list(range(1, deviceCount + 1))
        import py3nvml
        for j in range(deviceCount):
            handle = py3nvml.py3nvml.nvmlDeviceGetHandleByIndex(j)
            util = py3nvml.py3nvml.nvmlDeviceGetUtilizationRates(handle)
            gpu_snapshot.append(util.gpu)
        gpu_snapshot = gpu_snapshot
        plot_gpu_perf(ax2, gpu_labels, gpu_snapshot)

        res = pd.read_csv(file,
                          sep="\s+",
                          header=None,
                          names=[
                              'time', 'pass', 'fold', 'a', 'i', 'alpha',
                              'lambda', 'trainrmse', 'ivalidrmse', 'validrmse'
                          ])

        res['rel_acc'] = ((42665 - res['validrmse']) / (42665 - 31000))
        res['alpha_prime'] = res['alpha'] + res['fold'].apply(
            lambda x: new_alpha(x))

        best = res.loc[res['rel_acc'] == np.max(res['rel_acc']), :]
        plot_glm_results(ax3, res, best.tail(1), cb)
        # flag for colorbar to avoid redrawing
        #cb = True

        # Add footnotes
        footnote_text = "*U.S. Census dataset (predict Income): 45k rows, 10k cols\nParameters: 5-fold cross-validation, " + r'$\alpha = \{\frac{i}{7},i=0\ldots7\}$' + ", "\
'full $\lambda$-' + "search"
        #pl.figtext(.05, -.04, footnote_text, fontsize = 14,)
        pl.annotate(footnote_text, (0, 0), (-30, -50),
                    fontsize=12,
                    xycoords='axes fraction',
                    textcoords='offset points',
                    va='top')

        #update the graphics
        display.display(pl.gcf())
        display.clear_output(wait=True)
        time.sleep(0.01)

        #save the images
        saveimage = 0
        if saveimage:
            file_name = './images/glm_run_%04d.png' % (i, )
            pl.savefig(file_name, dpi=200)
        i = i + 1
Example #33
0
def analyse_equil(F, R, Z):
    s = numpy.shape(F)
    nx = s[0]
    ny = s[1]

    #;;;;;;;;;;;;;;; Find critical points ;;;;;;;;;;;;;
    #
    # Need to find starting locations for O-points (minima/maxima)
    # and X-points (saddle points)
    #
    Rr = numpy.tile(R, nx).reshape(nx, ny).T  # needed for contour
    Zz = numpy.tile(Z, ny).reshape(nx, ny)

    contour1 = contour(Rr, Zz, gradient(F)[0], levels=[0.0], colors='r')
    contour2 = contour(Rr, Zz, gradient(F)[1], levels=[0.0], colors='r')

    draw()

    ### --- line crossings ---------------------------
    res = find_inter(contour1, contour2)

    rex = numpy.interp(res[0], R, numpy.arange(R.size)).astype(int)
    zex = numpy.interp(res[1], Z, numpy.arange(Z.size)).astype(int)

    w = numpy.where((rex > 2) & (rex < nx - 3) & (zex > 2) & (zex < nx - 3))
    nextrema = numpy.size(w)
    rex = rex[w].flatten()
    zex = zex[w].flatten()

    #;;;;;;;;;;;;;; Characterise extrema ;;;;;;;;;;;;;;;;;
    # Fit a surface through local points using 6x6 matrix
    # This is to determine the type of extrema, and to
    # refine the location
    #

    n_opoint = 0
    n_xpoint = 0

    # Calculate inverse matrix
    rio = numpy.array([-1, 0, 0, 0, 1, 1])  # R index offsets
    zio = numpy.array([0, -1, 0, 1, 0, 1])  # Z index offsets

    # Fitting a + br + cz + drz + er^2 + fz^2
    A = numpy.transpose([[numpy.zeros(6, numpy.int) + 1], [rio], [zio],
                         [rio * zio], [rio**2], [zio**2]])

    A = A[:, 0, :]

    for e in range(nextrema):

        # Fit in index space so result is index number
        print("Critical point " + str(e))

        valid = 1

        localf = numpy.zeros(6)
        for i in range(6):
            # Get the f value in a stencil around this point
            xi = (rex[e] + rio[i])  #> 0) < (nx-1) # Zero-gradient at edges
            yi = (zex[e] + zio[i])  #> 0) < (ny-1)
            localf[i] = F[xi, yi]

        res, _, _, _ = numpy.linalg.lstsq(A, localf)

        # Res now contains [a,b,c,d,e,f]
        #                  [0,1,2,3,4,5]

        # This determines whether saddle or extremum
        det = 4. * res[4] * res[5] - res[3]**2

        if det < 0.0:
            print("   X-point")
        else:
            print("   O-point")

    # Get location (2x2 matrix of coefficients)

        rinew = old_div((res[3] * res[2] - 2. * res[1] * res[5]), det)
        zinew = old_div((res[3] * res[1] - 2. * res[4] * res[2]), det)

        if (numpy.abs(rinew) > 1.) or (numpy.abs(zinew) > 1.0):
            #; Method has gone slightly wrong. Try a different method.
            #; Get a contour line starting at this point. Should
            #; produce a circle around the real o-point.
            print("   Fitted location deviates too much")
            if det < 0.0:
                print("   => X-point probably not valid")
                print("      deviation = " + numpy.str(rinew) + "," +
                      numpy.str(zinew))
                #valid = 0
#            else:
#
#                contour_lines, F, findgen(nx), findgen(ny), levels=[F[rex[e], zex[e]]], \
#                    path_info=info, path_xy=xy
#
#                if np.size(info) > 1 :
#                # More than one contour. Select the one closest
#                    ind = closest_line(info, xy, rex[e], zex[e])
#                    info = info[ind]
#                else: info = info[0]
#
#                rinew = 0.5*(MAX(xy[0, info.offset:(info.offset + info.n - 1)]) + \
#                     MIN(xy[0, info.offset:(info.offset + info.n - 1)])) - rex[e]
#                zinew = 0.5*(MAX(xy[1, info.offset:(info.offset + info.n - 1)]) + \
#                     MIN(xy[1, info.offset:(info.offset + info.n - 1)])) - zex[e]
#
#                if (np.abs(rinew) > 2.) or (np.abs(zinew) > 2.0) :
#                    print "   Backup method also failed. Keeping initial guess"
#                    rinew = 0.
#                    zinew = 0.
#
#

        if valid:
            fnew = (res[0] + res[1] * rinew + res[2] * zinew +
                    res[3] * rinew * zinew + res[4] * rinew**2 +
                    res[5] * zinew**2)

            rinew = rinew + rex[e]
            zinew = zinew + zex[e]

            print("   Starting index: " + str(rex[e]) + ", " + str(zex[e]))
            print("   Refined  index: " + str(rinew) + ", " + str(zinew))

            x = numpy.arange(numpy.size(R))
            y = numpy.arange(numpy.size(Z))
            rnew = numpy.interp(rinew, x, R)
            znew = numpy.interp(zinew, y, Z)

            print("   Position: " + str(rnew) + ", " + str(znew))
            print("   F = " + str(fnew))

            if det < 0.0:

                if n_xpoint == 0:
                    xpt_ri = [rinew]
                    xpt_zi = [zinew]
                    xpt_f = [fnew]
                    n_xpoint = n_xpoint + 1
                else:
                    # Check if this duplicates an existing point

                    if rinew in xpt_ri and zinew in xpt_zi:
                        print("   Duplicates existing X-point.")
                    else:
                        xpt_ri = numpy.append(xpt_ri, rinew)
                        xpt_zi = numpy.append(xpt_zi, zinew)
                        xpt_f = numpy.append(xpt_f, fnew)
                        n_xpoint = n_xpoint + 1

                scatter(rnew, znew, s=100, marker='x', color='r')

                annotate(numpy.str(n_xpoint - 1),
                         xy=(rnew, znew),
                         xytext=(10, 10),
                         textcoords='offset points',
                         size='large',
                         color='r')

                draw()
            else:

                if n_opoint == 0:
                    opt_ri = [rinew]
                    opt_zi = [zinew]
                    opt_f = [fnew]
                    n_opoint = n_opoint + 1
                else:
                    # Check if this duplicates an existing point

                    if rinew in opt_ri and zinew in opt_zi:
                        print("   Duplicates existing O-point")
                    else:
                        opt_ri = numpy.append(opt_ri, rinew)
                        opt_zi = numpy.append(opt_zi, zinew)
                        opt_f = numpy.append(opt_f, fnew)
                        n_opoint = n_opoint + 1

                scatter(rnew, znew, s=100, marker='o', color='r')

                annotate(numpy.str(n_opoint - 1),
                         xy=(rnew, znew),
                         xytext=(10, 10),
                         textcoords='offset points',
                         size='large',
                         color='b')
                draw()

    print("Number of O-points: " + numpy.str(n_opoint))
    print("Number of X-points: " + numpy.str(n_xpoint))

    if n_opoint == 0:
        opt_ri = [rinew]
        opt_zi = [zinew]
        opt_f = [fnew]
        n_opoint = n_opoint + 1

    print("Number of O-points: " + str(n_opoint))

    if n_opoint == 0:
        print("No O-points! Giving up on this equilibrium")
        return Bunch(n_opoint=0, n_xpoint=0, primary_opt=-1)

#;;;;;;;;;;;;;; Find plasma centre ;;;;;;;;;;;;;;;;;;;
# Find the O-point closest to the middle of the grid

    mind = (opt_ri[0] - (old_div(numpy.float(nx), 2.)))**2 + (
        opt_zi[0] - (old_div(numpy.float(ny), 2.)))**2
    ind = 0
    for i in range(1, n_opoint):
        d = (opt_ri[i] - (old_div(numpy.float(nx), 2.)))**2 + (
            opt_zi[i] - (old_div(numpy.float(ny), 2.)))**2
        if d < mind:
            ind = i
            mind = d

    primary_opt = ind
    print("Primary O-point is at " + str(numpy.interp(opt_ri[ind], x, R)) +
          ", " + str(numpy.interp(opt_zi[ind], y, Z)))
    print("")

    if n_xpoint > 0:

        # Find the primary separatrix

        # First remove non-monotonic separatrices
        nkeep = 0
        for i in range(n_xpoint):
            # Draw a line between the O-point and X-point

            n = 100  # Number of points
            farr = numpy.zeros(n)
            dr = old_div((xpt_ri[i] - opt_ri[ind]), numpy.float(n))
            dz = old_div((xpt_zi[i] - opt_zi[ind]), numpy.float(n))
            for j in range(n):
                # interpolate f at this location
                func = RectBivariateSpline(x, y, F)

                farr[j] = func(opt_ri[ind] + dr * numpy.float(j),
                               opt_zi[ind] + dz * numpy.float(j))

            # farr should be monotonic, and shouldn't cross any other separatrices

            maxind = numpy.argmax(farr)
            minind = numpy.argmin(farr)
            if (maxind < minind): maxind, minind = minind, maxind

            # Allow a little leeway to account for errors
            # NOTE: This needs a bit of refining
            if (maxind > (n - 3)) and (minind < 3):
                # Monotonic, so add this to a list of x-points to keep
                if nkeep == 0:
                    keep = [i]
                else:
                    keep = numpy.append(keep, i)

                nkeep = nkeep + 1

        if nkeep > 0:
            print("Keeping x-points ", keep)
            xpt_ri = xpt_ri[keep]
            xpt_zi = xpt_zi[keep]
            xpt_f = xpt_f[keep]
        else:
            "No x-points kept"

        n_xpoint = nkeep

        # Now find x-point closest to primary O-point
        s = numpy.argsort(numpy.abs(opt_f[ind] - xpt_f))
        xpt_ri = xpt_ri[s]
        xpt_zi = xpt_zi[s]
        xpt_f = xpt_f[s]
        inner_sep = 0
    else:

        # No x-points. Pick mid-point in f

        xpt_f = 0.5 * (numpy.max(F) + numpy.min(F))

        print("WARNING: No X-points. Setting separatrix to F = " + str(xpt_f))

        xpt_ri = 0
        xpt_zi = 0
        inner_sep = 0

#;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
# Put results into a structure

    result = Bunch(
        n_opoint=n_opoint,
        n_xpoint=n_xpoint,  # Number of O- and X-points
        primary_opt=primary_opt,  # Which O-point is the plasma centre
        inner_sep=inner_sep,  #Innermost X-point separatrix
        opt_ri=opt_ri,
        opt_zi=opt_zi,
        opt_f=opt_f,  # O-point location (indices) and psi values
        xpt_ri=xpt_ri,
        xpt_zi=xpt_zi,
        xpt_f=xpt_f)  # X-point locations and psi values

    return result
Example #34
0
    def loglogplot(self,
                   numin=1.0 * u.GHz,
                   numax=10.0 * u.GHz,
                   plottitle='',
                   params=None,
                   do_annotations=True,
                   dust=False,
                   dustT=False,
                   annotation_xpos=0.7,
                   **kwargs):
        import pylab as pl
        x = np.logspace(np.log10(numin.to(u.GHz).value),
                        np.log10(numax.to(u.GHz).value), 500)

        if params is None:
            params = self.params

        if dust:
            y = inufit_dust(*params)(x)
        elif dustT:
            y = inufit_dustT(*params)(x)
        else:
            y = inufit(*params)(x)

        y = u.Quantity(y, u.mJy)

        pl.loglog(x, y, **kwargs)
        pl.xlabel('Frequency (GHz)')
        pl.ylabel('Flux Density (mJy)')
        pl.title(plottitle)

        pl.errorbar(self.nu.value,
                    self.flux.to(u.mJy).value,
                    yerr=self.fluxerr.to(u.mJy).value,
                    zorder=10,
                    fmt='s',
                    markersize=3,
                    alpha=0.75,
                    **kwargs)

        self.physprops()
        if do_annotations:
            #pl.annotate("size (as): {0:0.2g}".format(self.srcsize), [annotation_xpos, .35],textcoords='axes fraction',xycoords='axes fraction')
            if hasattr(self, 'beta'):
                pl.annotate("$\\beta$: {0:0.3g}".format(self.beta),
                            [annotation_xpos, .4],
                            textcoords='axes fraction',
                            xycoords='axes fraction')
                pl.annotate("$T_{{dust}}$: {0:0.2g} K".format(self.dustT),
                            [annotation_xpos, .35],
                            textcoords='axes fraction',
                            xycoords='axes fraction')
            elif hasattr(self, 'alpha'):
                pl.annotate("$\\alpha$: {0:0.3g}".format(self.alpha),
                            [annotation_xpos, .35],
                            textcoords='axes fraction',
                            xycoords='axes fraction')

            pl.annotate("size (au): {0.value:0.2g}{0.unit:latex}".format(
                self.srcsize), [annotation_xpos, .3],
                        textcoords='axes fraction',
                        xycoords='axes fraction')
            pl.annotate("mass (msun): {0.value:0.2g}{0.unit:latex}".format(
                self.mass), [annotation_xpos, .25],
                        textcoords='axes fraction',
                        xycoords='axes fraction')
            pl.annotate("EM: {0.value:0.2g}{0.unit:latex}".format(self.em),
                        [annotation_xpos, .2],
                        textcoords='axes fraction',
                        xycoords='axes fraction')
            pl.annotate("Nu(Tau=1): {0:0.2g}".format(self.nutau),
                        [annotation_xpos, .15],
                        textcoords='axes fraction',
                        xycoords='axes fraction')
            pl.annotate("N(lyc): {0.value:0.2g}{0.unit:latex}".format(
                self.Nlyc), [annotation_xpos, .1],
                        textcoords='axes fraction',
                        xycoords='axes fraction')
            pl.annotate("dens: {0.value:0.2g}{0.unit:latex}".format(self.dens),
                        [annotation_xpos, .05],
                        textcoords='axes fraction',
                        xycoords='axes fraction')
                   right=0.98,
                   wspace=0.5,
                   hspace=0.9,
                   top=0.9)

pl.subplot(121)
pl.plot(apm.signal_weight_ran,
        dist_tuning_in.med,
        color=input_color,
        lw=2,
        label='Input')
pl.plot(apm.signal_weight_ran, grid_out_index[sel_betas_idxs, :].T, '-k', lw=1)

for sel_beta, sel_beta_idx in zip(sel_betas, sel_betas_idxs):
    pl.annotate('$%.2f$' % sel_beta,
                (0.4, grid_out_index[sel_beta_idx, x_idx]),
                fontsize=9)

pp.custom_axes()
pl.xlabel('Input-tuning strength $\\beta$  \n(after learning)')
pl.ylabel('Grid tuning index')

x_idx = np.argmin(np.abs(apm.signal_weight_ran - 0.25))

pl.subplot(122)
pl.plot(apm.signal_weight_ran, grid_amp_index[sel_betas_idxs, :].T, '-k', lw=1)

for sel_beta, sel_beta_idx in zip(sel_betas, sel_betas_idxs):
    pl.annotate('$%.2f$' % sel_beta,
                (0.25, grid_amp_index[sel_beta_idx, x_idx]),
                fontsize=9)
Example #36
0
def scatter(self,
            x,
            y,
            xerr=None,
            yerr=None,
            cov=None,
            corr=None,
            s_expr=None,
            c_expr=None,
            labels=None,
            selection=None,
            length_limit=50000,
            length_check=True,
            label=None,
            xlabel=None,
            ylabel=None,
            errorbar_kwargs={},
            ellipse_kwargs={},
            **kwargs):
    """Viz (small amounts) of data in 2d using a scatter plot

    Convenience wrapper around pylab.scatter when for working with small DataFrames or selections

    :param x: Expression for x axis
    :param y: Idem for y
    :param s_expr: When given, use if for the s (size) argument of pylab.scatter
    :param c_expr: When given, use if for the c (color) argument of pylab.scatter
    :param labels: Annotate the points with these text values
    :param selection: Single selection expression, or None
    :param length_limit: maximum number of rows it will plot
    :param length_check: should we do the maximum row check or not?
    :param label: label for the legend
    :param xlabel: label for x axis, if None .label(x) is used
    :param ylabel: label for y axis, if None .label(y) is used
    :param errorbar_kwargs: extra dict with arguments passed to plt.errorbar
    :param kwargs: extra arguments passed to pylab.scatter
    :return:
    """
    import pylab as plt
    x = _ensure_strings_from_expressions(x)
    y = _ensure_strings_from_expressions(y)
    label = str(label or selection)
    selection = _ensure_strings_from_expressions(selection)
    if length_check:
        count = self.count(selection=selection)
        if count > length_limit:
            raise ValueError(
                "the number of rows (%d) is above the limit (%d), pass length_check=False, or increase length_limit"
                % (count, length_limit))
    x_values = self.evaluate(x, selection=selection)
    y_values = self.evaluate(y, selection=selection)
    if s_expr:
        kwargs["s"] = self.evaluate(s_expr, selection=selection)
    if c_expr:
        kwargs["c"] = self.evaluate(c_expr, selection=selection)
    plt.xlabel(xlabel or self.label(x))
    plt.ylabel(ylabel or self.label(y))
    s = plt.scatter(x_values, y_values, label=label, **kwargs)
    if labels:
        label_values = self.evaluate(labels, selection=selection)
        for i, label_value in enumerate(label_values):
            plt.annotate(label_value, (x_values[i], y_values[i]))
    xerr_values = None
    yerr_values = None
    if cov is not None or corr is not None:
        from matplotlib.patches import Ellipse
        sx = self.evaluate(xerr, selection=selection)
        sy = self.evaluate(yerr, selection=selection)
        if corr is not None:
            sxy = self.evaluate(corr, selection=selection) * sx * sy
        elif cov is not None:
            sxy = self.evaluate(cov, selection=selection)
        cov_matrix = np.zeros((len(sx), 2, 2))
        cov_matrix[:, 0, 0] = sx**2
        cov_matrix[:, 1, 1] = sy**2
        cov_matrix[:, 0, 1] = cov_matrix[:, 1, 0] = sxy
        ax = plt.gca()
        ellipse_kwargs = dict(ellipse_kwargs)
        ellipse_kwargs['facecolor'] = ellipse_kwargs.get('facecolor', 'none')
        ellipse_kwargs['edgecolor'] = ellipse_kwargs.get('edgecolor', 'black')
        for i in range(len(sx)):
            eigen_values, eigen_vectors = np.linalg.eig(cov_matrix[i])
            indices = np.argsort(eigen_values)[::-1]
            eigen_values = eigen_values[indices]
            eigen_vectors = eigen_vectors[:, indices]
            v1 = eigen_vectors[:, 0]
            v2 = eigen_vectors[:, 1]
            varx = cov_matrix[i, 0, 0]
            vary = cov_matrix[i, 1, 1]
            angle = np.arctan2(v1[1], v1[0])
            # round off errors cause negative values?
            if eigen_values[1] < 0 and abs(
                (eigen_values[1] / eigen_values[0])) < 1e-10:
                eigen_values[1] = 0
            if eigen_values[0] < 0 or eigen_values[1] < 0:
                raise ValueError('neg val')
            width, height = np.sqrt(np.max(eigen_values)), np.sqrt(
                np.min(eigen_values))
            e = Ellipse(xy=(x_values[i], y_values[i]),
                        width=width,
                        height=height,
                        angle=np.degrees(angle),
                        **ellipse_kwargs)
            ax.add_artist(e)
    else:
        if xerr is not None:
            if _issequence(xerr):
                assert len(
                    xerr
                ) == 2, "if xerr is a sequence it should be of length 2"
                xerr_values = [
                    self.evaluate(xerr[0], selection=selection),
                    self.evaluate(xerr[1], selection=selection)
                ]
            else:
                xerr_values = self.evaluate(xerr, selection=selection)
        if yerr is not None:
            if _issequence(yerr):
                assert len(
                    yerr
                ) == 2, "if yerr is a sequence it should be of length 2"
                yerr_values = [
                    self.evaluate(yerr[0], selection=selection),
                    self.evaluate(yerr[1], selection=selection)
                ]
            else:
                yerr_values = self.evaluate(yerr, selection=selection)
        if xerr_values is not None or yerr_values is not None:
            errorbar_kwargs = dict(errorbar_kwargs)
            errorbar_kwargs['fmt'] = errorbar_kwargs.get('fmt', 'none')
            plt.errorbar(x_values,
                         y_values,
                         yerr=yerr_values,
                         xerr=xerr_values,
                         **errorbar_kwargs)
    return s
    for n1, v in enumerate(['average', 'absaverage', 'std']):
        l = {
            'average': '\navg\n',
            'absaverage': '\nabs\n',
            'std': '\nstd\n',
            }[v]
        value = {
            'average': average,
            'absaverage': absaverage,
            'std': std,
            }[v]
        label += l + ' ' + str(round(value[n], 3)) + '\n'
    pylab.annotate(label,
                   xy=(n + 0.0, 0.0),
                   xytext=errorslocation(n, n1),
                   arrowprops=None,
                   horizontalalignment='left', verticalalignment='center',
                   fontsize=ann_fontsize,
                   )

# plot compounds with largest errors
for n, l in enumerate(largest):
    for n1, (c, e) in enumerate(l):
        name = latex(c) + '\n'
        # matplotlib.pyparsing.ParseFatalException: Expected end of math '$'
        # $\rm{SiH}2_\rm{s}3\rm{B}1\rm{d}$ (at char 0), (line:1, col:1)
        name = name.replace('\\rm', '')
        label = name + ' ' + str(round(e, 2))
        pylab.annotate(label,
                       xy=(n + 0.05, e),
                       xytext=formulaslocation(n, n1),
Example #38
0
t = np.linspace(0.0, t_max, N)
s0 = v * t_max
s1 = 0 * t + s0
s2 = v * t
t2 = np.linspace(0.0, v * t_max, N)
tt = 0 * t

fig, ax = texfig.subplots()
ax.plot(s1, t, color='darkblue', lw=2)
ax.plot(s2, t, color='darkblue', lw=2)
ax.plot(t2, tt, color='darkblue', lw=2)
ax.plot(t2, tt - 0.2, color='darkblue', lw=0)  # ajuste de margem

# cdt
label = pylab.annotate(r"$c\Delta t$",
                       color='darkblue',
                       xy=(v * t_medio - 0.8, t_medio + 0.0),
                       size=fontsize)

# vdt
label = pylab.annotate(r"$v\Delta t$",
                       color='darkblue',
                       xy=(v * t_medio - 0.1, -0.45),
                       size=fontsize)

# cdt'
label = pylab.annotate(r"$c\Delta t^\prime$",
                       color='darkblue',
                       xy=(s0 + 0.1, t_medio * 0.8),
                       size=fontsize)

# # Legenda Luz 2
Example #39
0
pl.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
pl.plot([0, t], [np.cos(t), np.cos(t)],
        color='blue',
        linewidth=2.5,
        linestyle="--")
# pinta linea punteada
pl.scatter([
    t,
], [
    np.cos(t),
], 50, color='blue')  #pinta punto

pl.annotate(r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',
            xy=(t, np.sin(t)),
            xycoords='data',
            xytext=(+30, +30),
            textcoords='offset points',
            fontsize=16,
            arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))

pl.plot([t, t], [0, np.sin(t)], color='red', linewidth=2.5, linestyle="--")
pl.scatter([
    t,
], [
    np.sin(t),
], 50, color='red')

pl.annotate(r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$',
            xy=(t, np.cos(t)),
            xycoords='data',
            xytext=(-90, -50),
Example #40
0
e = float(sys.argv[4]) # Consumer production efficiency
K = float(sys.argv[5]) # Resource carrying capacity
gscale = 0.125 # Scaling factor for random Gaussian component of growth rate.

# Now define time -- integrate from 0 to 30, using 1000 points:
t = sc.arange(0, 100) # CHANGING START POINT WILL NOT CHANGE START TIME OF SIMULATION BELOW!!

x0 = 10
y0 = 5
z0 = sc.array([x0, y0])  # initials conditions: 10 prey and 5 predators per unit area

pops = sc.array([[x0, y0]])
for timestep in t[:-1]: # All but the last timestep or we'll have one more population step than time steps
    pops = sc.append(pops, [CR_t1(pops)], axis=0)

prey = pops[:,0]
predators = pops[:,1]
f1 = p.figure() #Open empty figure object
p.plot(t, prey, 'g-', label='Resource density') # Plot
p.plot(t, predators, 'b-', label='Consumer density')
p.grid()
# add parameters to plot
paramstring = "r = " + str(r) + "\na = " + str(a) + "\nz = " + str(z) + "\ne = " + str(e) + "\nK = " + str(K) + "\neps ~ N(0," + str(gscale) + ")"
p.annotate(paramstring, (t.size - 10, 5.1))
p.legend(loc='best')
p.xlabel('Timesteps')
p.ylabel('Population')
p.title('Consumer-Resource discrete population dynamics (w/ random Prey fluctuation)')
p.show()
f1.savefig('../Results/prey_and_predators_5.pdf')  # Save figure
Example #41
0
    # Get the x,y coordinates tuple of lists
    coords = performTrial(500, f)

    # Feed the x,y lists to pylab.plot
    pylab.plot(coords[0],
               coords[1],
               marker='D',
               linestyle=':',
               color='magenta')

xc = coords[0]
yc = coords[1]

# first coordinates
xf = xc[0]
yf = yc[0]

# last coordinates
xl = xc[len(xc) - 1]
yl = yc[len(yc) - 1]

pylab.plot(xf, yf, marker='*', color='blue')
pylab.plot(xl, yl, marker='*', color='blue')
pylab.annotate('Start', xy=(xf, yf), color='blue', weight='bold')
pylab.annotate('Finish', xy=(xl, yl), color='blue', weight='bold')

pylab.title('Roomba Trip', color='blue', weight='bold')
pylab.xlabel('East - West of the room', color='blue', weight='bold')
pylab.ylabel('North - South of the room', color='blue', weight='bold')
pylab.show()
import numpy as Math
import pylab as Plot

emb = input("Select the file of embeddings ")
label = input("Select the file of labels ")

matrix = Math.loadtxt(emb)
words = [line.strip() for line in open(label)]

target_words = [line.strip().lower() for line in open(label)][:2000]

rows = [label.index(word) for word in target_words if word in label]
target_matrix = matrix[rows, :]
reduced_matrix = tsne(target_matrix, 2)
Plot.figure(figsize=(200, 200), dpi=100)
max_x = Math.amax(reduced_matrix, axis=0)[0]
max_y = Math.amax(reduced_matrix, axis=0)[1]
Plot.xlim((-max_x, max_x))
Plot.ylim((-max_y, max_y))

Plot.scatter(reduced_matrix[:, 0], reduced_matrix[:, 1], 20)

for row_id in range(0, len(rows)):
    target_word = label[rows[row_id]]
    x = reduced_matrix[row_id, 0]
    y = reduced_matrix[row_id, 1]
    Plot.annotate(target_word, (x, y))

Plot.savefig("embeddings.png")
Example #43
0
ax.patch.set_facecolor('none')
# ax.view_init(azim=-45, elev=25)
ax.view_init(azim=-23, elev=34)

plt.xlabel("$\lambda_{\ell_2}$", fontsize=14)
plt.ylabel("$\lambda_{\mathrm{TV}}$", fontsize=14)
plt.title(r"$f(\beta^{(k)}) - f(\beta^{*})$", fontsize=16)

x, y, _ = proj3d.proj_transform(0.5, 1.0, np.min(Z), ax.get_proj())
label = pylab.annotate(
    "$(0.5, 1.0)$",
    fontsize=14,
    xy=(x, y),
    xytext=(50, 20),
    textcoords='offset points',
    ha='right',
    va='bottom',
    color="white",
    # bbox=dict(boxstyle='round, pad=0.5', fc='white', alpha=0.5),
    arrowprops=dict(arrowstyle='->',
                    connectionstyle='arc3, rad=0',
                    color="white"))


def update_position(e):
    x, y, _ = proj3d.proj_transform(0.5, 1.0, np.min(Z), ax.get_proj())
    label.xy = x, y
    label.update_positions(fig.canvas.renderer)
    fig.canvas.draw()

Example #44
0
e = 0.75 # Consumer production efficiency
K = 35 # Consumer carrying capacity

# Now define time -- integrate from 0 to 30, using 1000 points:
t = sc.linspace(0, 30, 1000)

x0 = 10
y0 = 5
z0 = sc.array([x0, y0])  # initials conditions: 10 prey and 5 predators per unit area

pops, infodict = integrate.odeint(dCR_dt, z0, t, full_output=True)

infodict['message']  # >>> 'Integration successful.'

prey, predators = pops.T  # What's this for?
print("Final resource population is: %d" % prey[-1]) #print final population levels to terminal
print("Final consumer population is: %d" % predators[-1])
f1 = p.figure()  # Open empty figure object
p.plot(t, prey, 'g-', label='Resource density')  # Plot
p.plot(t, predators, 'b-', label='Consumer density')
p.grid()
# add parameters to plot
paramstring = "r = " + str(r) + "\na = " + str(a) + "\nz = " + str(z) + "\ne = " + str(e) + "\nK = " + str(K)
p.annotate(paramstring, (26, 5.1))
p.legend(loc='best')
p.xlabel('Time')
p.ylabel('Population')
p.title('Consumer-Resource population dynamics')
p.show()
f1.savefig('../Results/prey_and_predators_3.pdf')  # Save figure
Example #45
0
        facecolor="r",
        edgecolor="r",
        label="Step Time")
ax1.set_ylabel("Time in ms", color="r")
ax2 = ax1.twinx()
ax2.plot(x,
         np.array(loop_times),
         color="b",
         linewidth=1.0,
         linestyle="-",
         label="Loop Time")
ax2.set_ylabel("Time in ms", color="b")
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
pl.xlabel("Number of Iterations")
pl.annotate("Max Loop Time: " + str('%.2f' % (loop_times[max_loop_time])),
            xy=(max_loop_time + 1, loop_times[max_loop_time]))
pl.annotate("Min Loop Time: " + str('%.2f' % (loop_times[min_loop_time])),
            xy=(min_loop_time + 1, loop_times[min_loop_time]))
pl.title("Step & Loop Times")
pl.savefig("plots/g19_lab09_plot01.png")
pl.clf()

#Plot 2

pl.figure(figsize=(8, 6), dpi=80)
pl.subplot(1, 1, 1)
pl.plot(x,
        np.array(step_times),
        color="red",
        linewidth=1.0,
        linestyle="-",
Example #46
0
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')

c = 'y'
m = 'o'
xs = 0
ys = 0
zs = 0
ax.scatter(xs, ys, zs, s=100, c=c, marker=m)
xs, ys, _ = proj3d.proj_transform(1, 1, 1, ax.get_proj())
label = pylab.annotate(params[0],
                       xy=(xs, ys),
                       xytext=(-30, 30),
                       textcoords='offset points',
                       ha='right',
                       va='bottom',
                       bbox=dict(boxstyle='round,pad=0.5',
                                 fc='yellow',
                                 alpha=0.5),
                       arrowprops=dict(arrowstyle='->',
                                       connectionstyle='arc3,rad=0'))


def update_position(e):
    x2, y2, _ = proj3d.proj_transform(1, 1, 1, ax.get_proj())
    label.xy = x2, y2
    label.update_positions(fig.canvas.renderer)
    fig.canvas.draw()


fig.canvas.mpl_connect('button_release_event', update_position)
Example #47
0
#AGREGRA UNA ANOTACION EN UN PUNTO CONOCIDO
t = 2 * np.pi / 3
#Para coseno------------------------------------------------------------------------------------
pl.plot([t, t], [0, 0], color='blue', linewidth=2.5, linestyle="--")
#pl.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5, linestyle="--")
pl.scatter([
    t,
], [
    np.cos(t),
], 50, color='blue')  #DEFINE LAS CARACTERISTICAS DEN PUNTO (CIRCULO)
pl.annotate(
    r'$sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$',  #DATOS A IMPRIMIR DEL TEXTO
    xy=(t, np.sin(t)),
    xycoords='data',  #COORDENADAS DE REFERENCIA PARA LA FLECHA Y EL TEXTO
    xytext=(+10, +30),
    textcoords='offset points',
    fontsize=16,  #INDICAN POSICION DEL TEXTO 
    arrowprops=dict(arrowstyle="->",
                    connectionstyle="arc3,rad=.2"))  #DIRECCION DE LA FLECHA
#Para seno--------------------------------------------------------------------------------------
pl.plot([t, t], [0, np.sin(t)], color='red', linewidth=2.5, linestyle="--")
pl.scatter([
    t,
], [
    np.sin(t),
], 50, color='red')
pl.annotate(
    r'$cos(\frac{2\pi}{3})=-\frac{1}{2}$',
    xy=(t, np.cos(t)),
    xycoords='data',
Example #48
0
def identify_plot(file, peptide, charge, modi_mass=[], zoom=1):

    #read file
    values, params, amplitude = id.read_mgf(file)
    #procentual amplitdues for relative abundance
    ampl = (amplitude / max(amplitude)) * 100
    #offset and scales for zoom into the spectra
    if zoom > 0 and zoom <= 1:
        offset = (max(ampl) * zoom) / 4
        y_lim_scale = max(ampl) * zoom
        one_per = y_lim_scale / 100
    # create theoretical fragmentation of given peptide
    theo_y = list(id.fragments_y(peptide, maxcharge=charge))
    theo_b = list(id.fragments_b(peptide, maxcharge=charge))

    # create plot title
    headline = 'File: ' + file + ', Peptide: ' + peptide + ' (charge ' + str(
        charge) + ')'

    #headline = 'File: '+ file
    #create figure
    py.figure()
    py.xlabel('m/z')
    py.ylabel('Intensity, rel. units %')
    py.title(headline)

    # plot experimental spectra in grey
    py.bar(values,
           ampl,
           width=2.5,
           linewidth=0.1,
           color='grey',
           alpha=0.3,
           label='data')

    # some label and axis configs
    py.xlim(xmin=0)
    py.ylim(ymax=y_lim_scale)
    py.xticks(np.arange(0, max(values) + 1, 50))
    py.tick_params(axis='both', which='major', labelsize=8)
    py.tick_params(axis='both', which='minor', labelsize=5)
    #

    # --- 0. benchmarks
    #0.1 plot theoretical spectras if no modi given
    if modi_mass == []:
        py.bar(theo_y,
               np.ones(len(theo_y)) * offset,
               linewidth=0.1,
               width=2.5,
               alpha=0.3,
               color='red',
               label='theo y')
        py.bar(theo_b,
               np.ones(len(theo_y)) * offset,
               linewidth=0.1,
               width=3.5,
               alpha=0.3,
               color='lightgreen',
               label='theo b')

        # 0.2 annotate peaks
        #0.2.1 theo y ions
        for i in np.arange(0, len(peptide)):
            py.annotate(peptide[i],
                        xy=(theo_y[i], offset),
                        xytext=(theo_y[i], offset + 2 * one_per),
                        bbox=dict(boxstyle='round,pad=0.2',
                                  fc='red',
                                  alpha=0.5))
            # 0.2.1 theo b ion
            py.annotate(peptide[i],
                        xy=(theo_b[i], offset),
                        xytext=(theo_b[i], offset + 6 * one_per),
                        bbox=dict(boxstyle='round,pad=0.2',
                                  fc='lightgreen',
                                  alpha=0.5))

    alpha = 0.75
    for mass in modi_mass:
        # --- 1. mono matches
        if mass == 0:
            # 1.0 use def identify to find matching aa sequences
            y_seq, y_mz, y_amp, b_seq, b_mz, b_amp = id.identify(
                file, peptide, charge, ['cc'], 0)

            # 1.1 plot peaks
            py.bar(y_mz,
                   y_amp,
                   width=5,
                   linewidth=0.1,
                   color='red',
                   label='y [M+1H]+' + str(charge))
            py.bar(b_mz,
                   b_amp,
                   width=5,
                   linewidth=0.1,
                   color='lightgreen',
                   label='b [M+1H]+' + str(charge))

            # 1.2  annotate labels to peak hits
            # 1.2.1 y ion label

            for i in np.arange(0, len(peptide)):
                if y_seq[i] == '-':
                    py.annotate(y_seq[i],
                                xy=(theo_y[i], 0),
                                xytext=(theo_y[i], offset + 4 * one_per))
                else:
                    py.annotate(y_seq[i],
                                xy=(y_mz[i], offset),
                                xytext=(y_mz[i], offset + 4 * one_per),
                                bbox=dict(boxstyle='round,pad=0.2', fc='red'))

            # 1.2.2 b ion label
                if b_seq[i] == '-':
                    py.annotate(b_seq[i],
                                xy=(theo_b[i], 0),
                                xytext=(theo_b[i], offset + 8 * one_per))
                else:
                    py.annotate(b_seq[i],
                                xy=(b_mz[i], offset),
                                xytext=(b_mz[i], offset + 8 * one_per),
                                bbox=dict(boxstyle='round,pad=0.2',
                                          fc='lightgreen'))

    # --- 2. cc matches
        else:
            #compute sequence
            y_seq, y_mz, y_amp, b_seq, b_mz, b_amp = id.identify(
                file, peptide, charge, ['cc'], mass)
            # 2.1. plot peaks
            py.bar(y_mz,
                   y_amp,
                   width=5,
                   linewidth=0.1,
                   color='orange',
                   label='y + ' + str(int(mass)) + '[M+1H]+' + str(charge),
                   alpha=alpha)
            py.bar(b_mz,
                   b_amp,
                   width=5,
                   linewidth=0.1,
                   color='blue',
                   label='b + ' + str(int(mass)) + '[M+1H]+' + str(charge),
                   alpha=alpha)

            # 2.2.annotate labels to peak
            # 2.2.1 y ions
            offset = offset + 12 * one_per
            for i in np.arange(0, len(peptide)):
                if y_seq[i] == '-':
                    py.annotate(y_seq[i],
                                xy=(theo_y[i] + (mass / charge), 0),
                                xytext=(theo_y[i] + (mass / charge), offset))
                else:
                    py.annotate(y_seq[i],
                                xy=(y_mz[i], offset),
                                xytext=(y_mz[i], offset),
                                bbox=dict(boxstyle='round,pad=0.2',
                                          fc='orange',
                                          alpha=alpha))

        # 2.2.2 b ions
                if b_seq[i] == '-':
                    py.annotate(b_seq[i],
                                xy=(theo_b[i] + (mass / charge), 0),
                                xytext=(theo_b[i] + (mass / charge),
                                        offset + 4 * one_per))
                else:
                    py.annotate(b_seq[i],
                                xy=(b_mz[i], offset),
                                xytext=(b_mz[i], offset + 4 * one_per),
                                bbox=dict(boxstyle='round,pad=0.2',
                                          fc='blue',
                                          alpha=alpha))
            alpha = alpha - 0.25

    #--- 3. reporter matches
    reporter = [284, 447]
    r_val = []
    r_amp = []
    # 3.1 check for occurence
    for i in reporter:
        closest = min(values, key=lambda x: abs(x - i))
        if round(closest) == i:
            r_val.append(closest)
            r_amp.append(ampl[values.tolist().index(closest)])
    # 3.2 plot occurence
    if r_val != []:
        py.bar(r_val, r_amp, width=5, color='yellow', label='reporter')
        # 3.2.1 annotate occurence
        for i in np.arange(0, len(r_val)):
            py.annotate(int(round(r_val[i])),
                        xy=(r_val[i], r_amp[i]),
                        ha='center',
                        xytext=(r_val[i], r_amp[i] + 2 * one_per),
                        bbox=dict(boxstyle='round,pad=0.2', fc='yellow'))

    py.legend(loc=2, prop={'size': 11})
    py.show()
def main():

    savePDF = True
    solidDens = False

    Lx = 12.0
    Ly = 12.0
    az = 47.5
    ay = 2.0

    bulkVol = 2.0 * Lx * Ly * az

    lowX7 = -6.0
    #lowX7 = -4.0   # boltzmannons
    highX7 = 2.9
    #highX7 = 2.5   # boltzmannons

    # define some plotting colors
    colors = [
        'Navy', 'DarkViolet', 'MediumSpringGreen', 'Salmon', 'Fuchsia',
        'Yellow', 'Maroon', 'Salmon', 'Blue'
    ]

    # -------------------------------------------------------------------------
    # bulk and film density on same plot
    figg = pl.figure(1)
    ax = figg.add_subplot(111)
    pl.xlabel(r'$\text{Potential Shift}\ [K]$', fontsize=20)
    pl.ylabel('Spatial Density ' + r'$[\si{\angstrom}^{-d}]$', fontsize=20)
    pl.grid(True)
    pl.xlim([-5.5, 3.5])
    #pl.ylim([0,0.07])
    pl.tick_params(axis='both', which='major', labelsize=16)
    pl.tick_params(axis='both', which='minor', labelsize=16)
    yticks = ax.yaxis.get_major_ticks()
    yticks[0].set_visible(False)

    # bulk SVP density line
    bulkVert = -30
    minMus = -5.5
    maxMus = 2.0
    boxSubtract = 1.6
    pl.plot([minMus, maxMus], [0.02198, 0.02198], 'k-', lw=3)
    pl.annotate(
        '3d SVP',
        xy=(maxMus - boxSubtract, 0.02195),  #xycoords='data',
        xytext=(-10, bulkVert),
        textcoords='offset points',
        bbox=dict(boxstyle="round", fc="0.8"),
        arrowprops=dict(arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=10"),
    )

    # film SVP density line
    pl.plot([minMus, maxMus], [0.0432, 0.0432], 'k-', lw=3)
    pl.annotate(
        '2d SVP',
        xy=(maxMus - boxSubtract, 0.0432),  #xycoords='data',
        xytext=(30, -30),
        textcoords='offset points',
        bbox=dict(boxstyle="round", fc="0.8"),
        arrowprops=dict(arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=10"),
    )

    if solidDens:
        pl.plot([minMus, maxMus], [0.0248, 0.0248], 'k-', lw=3)
        pl.annotate(
            'HCP solid SVP',
            xy=(maxMus - boxSubtract, 0.0248),  #xycoords='data',
            xytext=(-10, 30),
            textcoords='offset points',
            bbox=dict(boxstyle="round", fc="0.8"),
            arrowprops=dict(arrowstyle="->",
                            connectionstyle="angle,angleA=0,angleB=90,rad=10"),
        )

    # -------------------------------------------------------------------------
    # bulk density
    figg2 = pl.figure(2)
    ax2 = figg2.add_subplot(111)
    pl.xlabel(r'$\text{Potential Shift}\ [K]$', fontsize=20)
    pl.ylabel('Bulk Density ' + r'$[\si{\angstrom}^{-3}]$', fontsize=20)
    pl.grid(True)
    pl.xlim([-5.5, 0.5])
    pl.tick_params(axis='both', which='major', labelsize=16)
    pl.tick_params(axis='both', which='minor', labelsize=16)
    yticks = ax.yaxis.get_major_ticks()
    yticks[0].set_visible(False)

    # set up bulk SVP densities for plot
    bulkVert = 30  # changes text box above (positive) or below (negative) line
    boxSubtract = 1.6
    pl.plot([minMus, maxMus], [0.02198, 0.02198], 'k-', lw=3)
    pl.annotate(
        '3d SVP',
        xy=(maxMus - boxSubtract, 0.02198),  #xycoords='data',
        xytext=(-50, bulkVert),
        textcoords='offset points',
        bbox=dict(boxstyle="round", fc="0.8"),
        arrowprops=dict(arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=10"),
    )

    # -------------------------------------------------------------------------
    # number of particles in film region
    pl.figure(3)
    pl.xlabel(r'$\text{Potential Shift}\ [K]$', fontsize=20)
    pl.ylabel(r'$N_{\text{film}}$', fontsize=20)
    pl.grid(True)
    pl.tick_params(axis='both', which='major', labelsize=16)
    pl.tick_params(axis='both', which='minor', labelsize=16)
    yticks = ax.yaxis.get_major_ticks()
    yticks[0].set_visible(False)

    # -------------------------------------------------------------------------
    # normalized angular winding
    pl.figure(4)
    pl.xlabel(r'$\text{Potential Shift}\ [K]$', fontsize=20)
    pl.ylabel(r'$\Omega$', fontsize=20)
    pl.grid(True)
    pl.tick_params(axis='both', which='major', labelsize=16)
    pl.tick_params(axis='both', which='minor', labelsize=16)
    yticks = ax.yaxis.get_major_ticks()
    yticks[0].set_visible(False)

    # -------------------------------------------------------------------------
    # film density
    figg5 = pl.figure(5)
    ax5 = figg5.add_subplot(111)
    pl.xlabel(r'$\text{Potential Shift}\ [K]$', fontsize=20)
    pl.ylabel(r'$\text{Film Density}\ [\si{\angstrom}^{-2}]$', fontsize=20)
    pl.ylim([0.03, 0.05])
    pl.xlim([-5.5, 0.5])
    pl.grid(True)
    pl.tick_params(axis='both', which='major', labelsize=16)
    pl.tick_params(axis='both', which='minor', labelsize=16)
    yticks = ax.yaxis.get_major_ticks()
    yticks[0].set_visible(False)

    # film SVP density line
    pl.plot([lowX7, highX7], [0.0432, 0.0432], 'k-', lw=3)
    pl.annotate(
        '2d SVP',
        xy=(-4, 0.0432),  #xycoords='data',
        xytext=(30, -30),
        textcoords='offset points',
        bbox=dict(boxstyle="round", fc="0.8"),
        arrowprops=dict(arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=10"),
    )

    # -------------------------------------------------------------------------
    # superfluid fraction
    pl.figure(6)
    pl.xlabel(r'$\text{Potential Shift}\ [K]$', fontsize=20)
    pl.ylabel(r'$\rho_S/\rho$', fontsize=20)
    pl.grid(True)
    pl.xlim([-5.5, 0.5])
    pl.tick_params(axis='both', which='major', labelsize=16)
    pl.tick_params(axis='both', which='minor', labelsize=16)
    yticks = ax.yaxis.get_major_ticks()
    yticks[0].set_visible(False)

    # -------------------------------------------------------------------------
    # film/bulk densities subplot
    pl.figure(7)
    ax7a = pl.subplot(211)
    pl.ylabel(r'$\text{Film Density}\ [\si{\angstrom}^{-2}]$', fontsize=20)
    pl.ylim([0.035, 0.05])
    pl.grid(True)
    pl.tick_params(axis='both', which='major', labelsize=16)
    pl.tick_params(axis='both', which='minor', labelsize=16)
    yticks = ax.yaxis.get_major_ticks()
    yticks[0].set_visible(False)

    # film SVP density line
    pl.plot([lowX7, highX7], [0.0432, 0.0432], 'k-', lw=3)
    pl.annotate(
        '2d SVP',
        xy=(-2, 0.0432),  #xycoords='data',
        xytext=(30, -30),
        textcoords='offset points',
        bbox=dict(boxstyle="round", fc="0.8"),
        arrowprops=dict(arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=10"),
    )
    pl.setp(ax7a.get_xticklabels(), visible=False)

    ax7b = pl.subplot(212, sharex=ax7a)
    pl.xlabel(r'$\text{Potential Shift}\ [K]$', fontsize=20)
    pl.ylabel('Bulk Density ' + r'$[\si{\angstrom}^{-3}]$', fontsize=20)
    pl.grid(True)
    pl.xlim([lowX7, highX7])
    pl.tick_params(axis='both', which='major', labelsize=16)
    pl.tick_params(axis='both', which='minor', labelsize=16)
    yticks = ax7b.yaxis.get_major_ticks()
    yticks[0].set_visible(False)

    # set up bulk SVP densities for plot
    bulkVert = 15  # changes text box above (positive) or below (negative) line
    boxSubtract = 1.6
    pl.plot([lowX7, highX7], [0.02198, 0.02198], 'k-', lw=3)
    pl.annotate(
        '3d SVP',
        xy=(1.2, 0.02198),  #xycoords='data',
        xytext=(-50, bulkVert),
        textcoords='offset points',
        bbox=dict(boxstyle="round", fc="0.8"),
        arrowprops=dict(arrowstyle="->",
                        connectionstyle="angle,angleA=0,angleB=90,rad=10"),
    )

    # -------------------------------------------------------------------------
    # number of particles in bulk
    pl.figure(8)
    pl.xlabel(r'$\text{Potential Shift}\ [K]$', fontsize=20)
    pl.ylabel(r'$N_{\text{bulk}}$', fontsize=20)
    pl.grid(True)
    pl.xlim([-5.5, 0.5])
    pl.tick_params(axis='both', which='major', labelsize=16)
    pl.tick_params(axis='both', which='minor', labelsize=16)
    yticks = ax.yaxis.get_major_ticks()
    yticks[0].set_visible(False)

    # -------------------------------------------------------------------------
    Tvals = glob.glob('*T*')

    Markers = ['-o', '-d', '-*']

    for nT, Tval in enumerate(sorted(Tvals)):

        os.chdir(Tval)

        T = Tval[1:]

        Svals = glob.glob('S*')

        # --- loop through known directory structure --------------------------
        for nS, Sval in enumerate(sorted(Svals)):

            os.chdir(Sval)

            Vdirs = glob.glob('*V*')

            print os.getcwd()

            # store bulk separation value
            S = re.search(r'\d+', Sval).group(0)

            # get label for plot
            if 'distinguishable' in Sval:
                labell = 'S = ' + str(S) + ', Boltzmannons, T=' + str(T)
            else:
                labell = 'S = ' + str(S) + ', Bosons, T=' + str(T)
                shortlabell = 'S = ' + str(S) + ', T=' + str(T)

            # projected area of film region
            projArea = float(S) * Lx

            # accessible volume in cell
            #accessibleVol = Lx*(Ly*(float(S)+2.0*az) - float(S)*(Ly-2.0*ay))
            accessibleVol = 2.0 * Lx * Ly * az + 2.0 * ay * Lx * float(S)

            # multiply angular winding by norm. to be fixed in code later
            omegaNorm = 4.0 * (float(S) + 1.0 * Ly)**2

            # Arrays to hold all data
            Vs = pl.array([])
            Films = pl.array([])
            Bulks = pl.array([])
            filmErrs = pl.array([])
            bulkErrs = pl.array([])
            Omegas = pl.array([])
            omegaErrs = pl.array([])
            NumParts = pl.array([])
            NumPartErrs = pl.array([])
            Supers = pl.array([])
            SuperErrs = pl.array([])

            # pass potential shift directories for current S value
            for Vdir in Vdirs:

                os.chdir(Vdir)

                # get bipartition file name
                f = glob.glob('*Bipart*')[0]

                # get angular winding file name
                fw = glob.glob('*Ntwind*')[0]

                # get estimator file name (includes total number)
                fe = glob.glob('*Estimator*')[0]

                # get superfrac file name
                fs = glob.glob('*Super*')[0]

                # build array of film potential shifts from directory names
                Vs = pl.append(Vs, float(Vdir[1:]))

                # --- Densities -----------------------------------------------
                filmavg, filmstd, filmbins, bulkavg, bulkstd, bulkbins = pl.genfromtxt(
                    f, unpack=True, usecols=(0, 1, 2, 3, 4, 5), delimiter=',')

                # get rid of any items which are not numbers..
                # this is some beautiful Python juju.
                filmbins = filmbins[pl.logical_not(pl.isnan(filmbins))]
                filmstd = filmstd[pl.logical_not(pl.isnan(filmstd))]
                filmavg = filmavg[pl.logical_not(pl.isnan(filmavg))]
                bulkbins = bulkbins[pl.logical_not(pl.isnan(bulkbins))]
                bulkstd = bulkstd[pl.logical_not(pl.isnan(bulkstd))]
                bulkavg = bulkavg[pl.logical_not(pl.isnan(bulkavg))]
                filmweights = filmbins / pl.sum(filmbins)
                bulkweights = bulkbins / pl.sum(bulkbins)

                filmavg *= filmweights
                bulkavg *= bulkweights

                filmstd *= filmweights
                bulkstd *= bulkweights

                film = pl.sum(filmavg)
                bulk = pl.sum(bulkavg)
                filmstdErr = pl.sum(filmstd)
                bulkstdErr = pl.sum(bulkstd)

                Films = pl.append(Films, film)
                Bulks = pl.append(Bulks, bulk)
                filmErrs = pl.append(filmErrs, filmstdErr)
                bulkErrs = pl.append(bulkErrs, bulkstdErr)

                # ---- angular winding ----------------------------------------
                omegaAvg, omegaStd, omegaBins = pl.genfromtxt(fw,
                                                              unpack=True,
                                                              usecols=(3, 4,
                                                                       5),
                                                              delimiter=',')

                # get rid of any items which are not numbers..
                omegaBins = omegaBins[pl.logical_not(pl.isnan(omegaBins))]
                omegaStd = omegaStd[pl.logical_not(pl.isnan(omegaStd))]
                omegaAvg = omegaAvg[pl.logical_not(pl.isnan(omegaAvg))]

                # normalize data.
                omegaStd *= omegaNorm
                omegaAvg *= omegaNorm

                weights = omegaBins / pl.sum(omegaBins)

                omegaAvg *= weights
                omegaStd *= weights

                Omega = pl.sum(omegaAvg)
                omegaErr = pl.sum(omegaStd)

                Omegas = pl.append(Omegas, Omega)
                omegaErrs = pl.append(omegaErrs, omegaErr)

                # ---- total number -------------------------------------------
                numAvg, numStd, numBins = pl.genfromtxt(fe,
                                                        unpack=True,
                                                        usecols=(12, 13, 14),
                                                        delimiter=',')

                # get rid of any items which are not numbers..
                numBins = numBins[pl.logical_not(pl.isnan(numBins))]
                numStd = numStd[pl.logical_not(pl.isnan(numStd))]
                numAvg = numAvg[pl.logical_not(pl.isnan(numAvg))]

                weights = numBins / pl.sum(numBins)

                numAvg *= weights
                numStd *= weights

                numPart = pl.sum(numAvg)
                numPartErr = pl.sum(numStd)

                NumParts = pl.append(NumParts, numPart)
                NumPartErrs = pl.append(NumPartErrs, numPartErr)

                # ---- superfluid fraction ------------------------------------
                supAvg, supStd, supBins = pl.genfromtxt(fs,
                                                        unpack=True,
                                                        usecols=(0, 1, 2),
                                                        delimiter=',')

                # get rid of any items which are not numbers..
                supBins = supBins[pl.logical_not(pl.isnan(supBins))]
                supStd = supStd[pl.logical_not(pl.isnan(supStd))]
                supAvg = supAvg[pl.logical_not(pl.isnan(supAvg))]

                # normalize data.
                #supStd /= (1.0*accessibleVol)
                #supAvg /= (1.0*accessibleVol)

                weights = supBins / pl.sum(supBins)

                supAvg *= weights
                supStd *= weights

                supPart = pl.sum(supAvg)
                supPartErr = pl.sum(supStd)

                Supers = pl.append(Supers, supPart)
                SuperErrs = pl.append(SuperErrs, supPartErr)

                os.chdir('..')

            # Sort data in order of increasing chemical potential.
            # This is another bit of magical Python juju.
            Vs, Films, Bulks, filmErrs, bulkErrs, Omegas, omegaErrs,\
                    NumParts, NumPartErrs, Supers, SuperErrs = pl.asarray(
                    zip(*sorted(zip(Vs, Films, Bulks, filmErrs, bulkErrs,
                        Omegas, omegaErrs, NumParts, NumPartErrs, Supers,
                        SuperErrs))))

            pl.figure(1)
            pl.errorbar(Vs,
                        Films,
                        filmErrs,
                        fmt=Markers[nT],
                        color=colors[nS],
                        label=labell + ', 2d',
                        markersize=8)
            pl.errorbar(Vs,
                        Bulks,
                        bulkErrs,
                        fmt=Markers[nT],
                        mec=colors[nS],
                        label=labell + ', 3d',
                        mfc='None',
                        markersize=8)

            pl.figure(2)
            pl.errorbar(Vs,
                        Bulks,
                        bulkErrs,
                        fmt=Markers[nT],
                        color=colors[nS],
                        label=labell,
                        markersize=8)

            pl.figure(3)
            pl.errorbar(Vs,
                        Films * projArea,
                        fmt=Markers[nT],
                        color=colors[nS],
                        label=labell,
                        markersize=8)

            pl.figure(4)
            pl.errorbar(Vs,
                        Omegas,
                        omegaErrs,
                        fmt=Markers[nT],
                        color=colors[nS],
                        label=labell,
                        markersize=8)

            pl.figure(5)
            pl.errorbar(Vs,
                        Films,
                        filmErrs,
                        fmt=Markers[nT],
                        color=colors[nS],
                        label=labell,
                        markersize=8)

            pl.figure(6)
            pl.errorbar(Vs,
                        Supers,
                        SuperErrs,
                        fmt=Markers[nT],
                        color=colors[nS],
                        label=labell,
                        markersize=8)

            pl.figure(7)
            ax7a.errorbar(Vs,
                          Films,
                          filmErrs,
                          fmt=Markers[nT],
                          color=colors[nS],
                          label=shortlabell,
                          markersize=8)
            ax7b.errorbar(Vs,
                          Bulks,
                          bulkErrs,
                          fmt=Markers[nT],
                          color=colors[nS],
                          label=shortlabell,
                          markersize=8)

            pl.figure(8)
            pl.errorbar(Vs,
                        Bulks * bulkVol,
                        bulkErrs * bulkVol,
                        fmt=Markers[nT],
                        color=colors[nS],
                        label=labell,
                        markersize=8)

            os.chdir('..')

        os.chdir('..')

    pl.figure(1)
    pl.legend(loc=1)
    pl.tight_layout()
    pl.figure(2)
    pl.legend(loc=1)
    pl.tight_layout()

    pl.figure(3)
    pl.legend(loc=1)
    pl.tight_layout()

    pl.figure(4)
    pl.legend(loc=1)
    pl.tight_layout()

    pl.figure(5)
    pl.legend(loc=1)
    pl.tight_layout()

    pl.figure(6)
    pl.legend(loc=1)
    pl.tight_layout()

    pl.figure(7)
    pl.legend(loc=1, bbox_to_anchor=(1., 2.1))
    major_formatter = FuncFormatter(my_formatter)
    ax7a.yaxis.set_major_formatter(major_formatter)
    pl.tight_layout()
    if savePDF:
        pl.savefig('Bulk_Film_Dens_vs_Vshift_allS_allT_18APR.pdf',
                   format='pdf',
                   bbox_inches='tight')

    pl.figure(8)
    pl.legend(loc=1)
    pl.tight_layout()

    pl.show()
Example #50
0
z0 = sc.array([x0, y0
               ])  # initials conditions: 10 prey and 5 predators per unit area

pops, infodict = integrate.odeint(
    dR_dt, z0, t, full_output=True
)  #runs dR_dt as an integration with i.c z0 and over time interval t
# infodict just checks integration was successful
infodict['message']  # >>> 'Integration successful.'

prey, predators = pops.T  # Transposes to form correct format
final_prey = prey[-1]
final_predator = predators[-1]
f1 = p.figure()  #Open empty figure object
p.plot(t, prey, 'g-', label='Resource density')  # Plot
p.plot(t, predators, 'b-', label='Consumer density')
p.annotate('Constants: r = %r , a = %r , z = %r , e = %r , K = %r' %
           (r, a, z, e, K),
           xy=(20, 5),
           color="red")
p.annotate('Final prey = %.5s , Final predators = %.5s' %
           (final_prey, final_predator),
           xy=(25, 2),
           color="purple")
p.grid()
p.legend(loc='best')
p.xlabel('Time')
p.ylabel('Population')
p.title('Consumer-Resource population dynamics')
p.show()
f1.savefig('../Results/prey_and_predators_2A.pdf')  #Save figure
Example #51
0
                               zorder=10)

            plt.plot(np.nan,
                     np.nan,
                     '-',
                     c=COLORS['gal'],
                     label=r'${\rm PA_{GAL}} = %.0f$' % pa_gal)
            plt.plot(np.nan,
                     np.nan,
                     '-',
                     c=COLORS['fk5'],
                     label=r'${\rm PA_{CEL}} = %.0f$' % pa_cel)
            plt.legend(loc=2, fontsize=10)

            plt.annotate(r'$\ell,b = %.2f,%.2f$' % (glon, glat),
                         xy=(0.1, 0.1),
                         xycoords='axes fraction',
                         fontsize=10)
            plt.annotate(r'${\rm RA,DEC} = %.2f,%.2f$' % (ra, dec),
                         xy=(0.1, 0.15),
                         xycoords='axes fraction',
                         fontsize=10)

            #plt.annotate(r'${\rm PA_{GAL}} = %.0f$'%pa_gal,xy=(0.05,0.95),xycoords="axes fraction",fontsize=10)
            #plt.annotate(r'${\rm PA_{CEL}} = %.0f$'%pa_cel,xy=(0.05,0.90),xycoords="axes fraction",fontsize=10)
            #plt.annotate(r'${\rm PA_{CEL}} = %.0f$'%(pa_cel-180),xy=(0.05,0.85),xycoords="axes fraction",fontsize=10)

            ax.set_title('%s (%s)' % (name, frame[:3]))
            plt.savefig('%s_pa_%s.png' % (name, frame[:3]),
                        bbox_inches='tight')
            break
    plt.ion()
Example #52
0
    def direction(self):
        """
        Perform and plot the two main directions of the peaks, considering their previously
        calculated scale ,by calculating the Hessian at different sizes as the combination of
        gaussians and their first and second derivatives

        """
        import pylab
        i = 0
        j = 0
        vals = []
        vects = []
        kpx = self.keypoints.x
        kpy = self.keypoints.y
        sigma = self.keypoints.sigma
        img = self.raw
        pylab.figure()
        pylab.imshow(img, interpolation='nearest')

        for y, x, s in itertools.izip(kpy, kpx, sigma):
            s_patch = numpy.trunc(s * 2)

            if s_patch % 2 == 0:
                s_patch += 1

            if s_patch < 3: s_patch = 3

            if (x > s_patch / 2 and x < img.shape[1] - s_patch / 2 - 1
                    and y > s_patch / 2 and y < img.shape[0] - s_patch / 2):

                patch = img[y - (s_patch - 1) / 2:y + (s_patch - 1) / 2 + 1,
                            x - (s_patch - 1) / 2:x + (s_patch - 1) / 2 + 1]
                x_patch = numpy.arange(s_patch)
                Gx = numpy.exp(-4 * numpy.log(2) *
                               (x_patch - numpy.median(x_patch))**2 / s)
                Gy = Gx[:, numpy.newaxis]
                dGx = -Gx * 4 * numpy.log(2) / s * 2 * (x_patch -
                                                        numpy.median(x_patch))
                dGy = dGx[:, numpy.newaxis]
                d2Gx = -8 * numpy.log(2) / s * (
                    (x_patch - numpy.median(x_patch)) * dGx + Gx)
                d2Gy = d2Gx[:, numpy.newaxis]

                Hxx = d2Gx * Gy
                Hyy = d2Gy * Gx
                Hxy = dGx * dGy

                d2x = (Hxx.ravel() * patch.ravel()).sum()
                d2y = (Hyy.ravel() * patch.ravel()).sum()
                dxy = (Hxy.ravel() * patch.ravel()).sum()
                H = numpy.array([[d2y, dxy], [dxy, d2x]])
                val, vect = numpy.linalg.eig(H)

                #                 print 'new point'
                #                 print x, y
                #                 print val
                #                 print vect
                #                 print numpy.dot(vect[0],vect[1])
                e = numpy.abs(val[0] - val[1]) / numpy.abs(val[0] + val[1])
                j += 1
                #                 print j
                #                 print e
                if numpy.abs(val[1]) < numpy.abs(
                        val[0]
                ):  # reorganisation des valeurs propres et vecteurs propres
                    val[0], val[1] = val[1], val[0]
                    vect = vect[-1::-1, :]

                pylab.annotate(
                    "",
                    xy=(x + vect[0][0] * val[0], y + vect[0][1] * val[0]),
                    xytext=(x, y),
                    arrowprops=dict(facecolor='red', shrink=0.05),
                )

                pylab.annotate(
                    "",
                    xy=(x + vect[1][0] * val[1], y + vect[1][1] * val[1]),
                    xytext=(x, y),
                    arrowprops=dict(facecolor='red', shrink=0.05),
                )
                pylab.plot(x, y, 'og')
                vals.append(val)
                vects.append(vect)
        return vals, vects
                            edgecolor='purple')
        except KeyError:
            print "No TGT_RA found"

        wcshead = pywcs.WCS(header)
        lbfit = wcshead.wcs_pix2sky(fitpars[2:3], fitpars[3:4], 0)

        radecfit = coords.Position(numpy.concatenate(lbfit),
                                   system='galactic').j2000()

        try:
            JD = float(header['JD'])
            if JD > 2.4e6: JD -= 2.4e6
            pflux = planetflux(planet, JD)
            pylab.annotate(
                'Model Flux:     %8.6g Jy  Volts/Jy: %6.3g     Error (resid/Jy): %6.3g'
                % (pflux, ampl / pflux, resid_std / pflux), [0.6, 0.76],
                xycoords='figure fraction')
        except KeyError:
            print "No JD found"

        file_noprefix = re.compile("(.*/)?(.*)").search(file).groups()[1]
        pylab.annotate('%s' % file_noprefix, [0.5, 0.94],
                       xycoords='figure fraction',
                       size='large',
                       weight='bold')
        pylab.annotate('Fitted source_ra=%6.3f,source_dec=%6.3f' % radecfit,
                       [0.6, 0.88],
                       xycoords='figure fraction')
        pylab.annotate('Mean DC: %3.2f            Std DC: %3.2f' %
                       (meandc, stddc), [0.6, 0.85],
                       xycoords='figure fraction')
Example #54
0
    e = 0.75  # Consumer production efficiency

# Now define time -- integrate from 0 to 15, using 1000 points:
t = sc.linspace(0, 50, 5000)
K = 250
x0 = 10
y0 = 5
z0 = sc.array([x0, y0
               ])  # initials conditions: 10 prey and 5 predators per unit area

pops, infodict = integrate.odeint(
    dR_dt, z0, t, full_output=True
)  #runs dR_dt as an integration with i.c z0 and over time interval t
# infodict just checks integration was successful
infodict['message']  # >>> 'Integration successful.'

prey, predators = pops.T  # Transposes to form correct format
f1 = p.figure()  #Open empty figure object
p.plot(t, prey, 'g-', label='Resource density')  # Plot
p.plot(t, predators, 'b-', label='Consumer density')
p.annotate('r = %r , a = %r , z = %r , e = %r , K = %r' % (r, a, z, e, K),
           xy=(18, 1),
           color="red")
p.grid()
p.legend(loc='best')
p.xlabel('Time')
p.ylabel('Population')
p.title('Consumer-Resource population dynamics')
p.show()
f1.savefig('../Results/prey_and_predators_2.pdf')  #Save figure
Example #55
0
def bestfit(bestpars,
            pipe,
            title,
            method='polish',
            outfile='bestfit.pdf',
            *args,
            **kwargs):

    # segs = np.array([[5210,5240], [5360,5375], [5520,5540]])
    # segs = np.array([[5160,5190], [5880,5910], [5940,6000]])     # New APF
    # segs = np.array([[5220, 5250], [5545, 5575], [6120, 6150]])  # APF+Keck compatable
    # segs = np.array([[5220,5250], [5407,5437], [6120,6150]])     # APF+Keck compatable
    # segs = np.array([[5160,5190], [5277,5307], [5880,5910]])     # interesting, but not well-fit
    segs = np.array([[5160, 5190], [5545, 5575], [6120,
                                                  6150]])  # include Mg region
    # segs = np.array([[5250, 5280], [5545, 5575], [6120, 6150]])    # include Mg region

    teff = bestpars['teff']
    logg = bestpars['logg']
    feh = bestpars['fe']
    vsini = bestpars['vsini']
    psf = bestpars['psf']

    lib = smsyn.library.read_hdf(pipe.libfile,
                                 wavlim=(segs[0][0], segs[-1][-1]))
    spec = smsyn.io.spectrum.read_fits(pipe.smfile)

    try:
        absrv = spec.header['ABSRV']
        absrv_err = spec.header['ABSRV_ERR']
    except KeyError:
        absrv = absrv_err = 0.0

    fitwav = []
    fitflux = []
    fitres = []
    fitmod = []
    for s in pipe.segments:
        segment0 = s[0]
        output = pipe.polish_output[segment0]
        wav = output['wav']
        flux = output['flux']
        resid = output['resid']
        model = flux - resid

        fitwav.append(wav)
        fitflux.append(flux)
        fitres.append(resid)
        fitmod.append(model)

    wav = np.hstack(fitwav).flatten()
    flux = np.hstack(fitflux).flatten()
    resid = np.hstack(fitres).flatten()
    model = np.hstack(fitmod).flatten()

    fullwav = spec.wav
    # fullmod = lib.synth(lib.wav, teff, logg, feh, vsini, psf, rot_method='rotmacro')
    fullmod = lib.synth(spec.wav,
                        teff,
                        logg,
                        feh,
                        vsini,
                        psf,
                        rot_method='rotmacro')
    fullspec = spec.flux
    allres = spec.flux - fullmod
    wavmask = pipe.wav_exclude

    # print "Best parameters:\n", bestpars[['teff', 'logg', 'fe', 'vsini']]

    fig = pl.figure(figsize=(22, 13))
    pl.subplot2grid((3, 4), (0, 0))
    pl.subplots_adjust(bottom=0.07,
                       left=0.03,
                       right=0.95,
                       wspace=0.01,
                       hspace=0.15,
                       top=0.95)

    pl.suptitle(title, fontsize=28, horizontalalignment='center')

    for i, seg in enumerate(segs):
        pl.subplot2grid((3, 4), (i, 0), colspan=3)

        crop = np.where((wav >= seg[0]) & (wav <= seg[1]))[0]
        pltflux = flux[crop]
        if len(crop) == 0:
            # print "Unfit data for seg {}".format(seg)
            crop = np.where((fullwav >= seg[0]) & (fullwav <= seg[1]))[0]
            pltwav = fullwav[crop]
            pltflux = fullspec[crop]
            pltmod = fullmod[crop]
            pltflux *= (np.mean(pltmod) / np.mean(pltflux))
        else:
            pltwav = wav[crop]
            pltmod = model[crop]

        pl.plot(pltwav, pltflux, color='0.2', linewidth=3)
        pl.plot(pltwav, pltmod, 'b-', linewidth=2)

        pl.axhline(0, color='r', linewidth=2)
        pl.plot(pltwav, pltflux - pltmod, 'k-', color='0.2', linewidth=3)

        for w0, w1 in wavmask:
            if w0 > seg[0] or w1 < seg[1]:
                pl.axvspan(w0, w1, color='LightGray')

        pl.xticks(fontsize=16)
        pl.yticks(pl.yticks()[0][1:], fontsize=16)
        pl.ylim(-0.2, 1.15)
        pl.xlim(seg[0], seg[1])

        ax = pl.gca()
        ax.tick_params(pad=5)

    pl.xlabel('Wavelength [$\\AA$]', fontsize=20)

    # ACF plot
    flux[~np.isfinite(flux)] = 1.0
    lag, acftspec = ACF(flux)
    lag, acfmspec = ACF(model)
    dv = loglambda_wls_to_dv(wav, nocheck=True)
    dv = lag * dv + absrv

    pl.subplot2grid((3, 4), (2, 3))
    pl.plot(dv,
            acftspec,
            'k.',
            color='0.2',
            linewidth=3,
            label='ACF of spectrum')
    pl.plot(dv, acfmspec, color='b', linewidth=2, label='ACF of model')
    locs, labels = pl.yticks()
    pl.yticks(locs, [''] * len(locs))
    pl.xticks([-100, -50, 0, 50, 100], fontsize=16)
    pl.xlim(-100 + absrv, 100 + absrv)
    crop = np.where((dv > -100) & (dv < 100))[0]
    pl.ylim(min(acfmspec[crop]), max(acfmspec[crop]) + 0.2 * max(acfmspec))
    # pl.annotate('ACF', xy=(0.15, 0.85), xycoords='axes fraction')
    ax = pl.gca()
    ax.tick_params(pad=5)

    # CCF plot
    flux -= np.mean(flux)
    model -= np.mean(model)
    lag, ccftspec = CCF(flux, model)
    dv = loglambda_wls_to_dv(wav, nocheck=True)
    dv = lag * dv + absrv

    pl.plot(dv,
            ccftspec,
            color='0.2',
            linewidth=3,
            linestyle='dotted',
            label='CCF of model w/\nspectrum')
    pl.xlabel('$\\Delta v$ [km s$^{-1}$]', fontsize=20)
    ax = pl.gca()
    ax.tick_params(pad=5)

    pl.axvspan(absrv - absrv_err, absrv + absrv_err, color='0.8')
    pl.axvline(absrv,
               linestyle='dashed',
               color='0.5',
               label=u"RV = {:.01f} ± {:.01f} km/s".format(absrv, absrv_err))

    pl.legend(numpoints=2, loc='upper right', fontsize=12)

    ax = pl.gca()

    try:
        mstar, rstar = bestpars['iso_mass'], bestpars['iso_radius']
        hasiso = True
    except KeyError:
        hasiso = False

    pl.subplot2grid((3, 4), (0, 3))
    afs = 22
    # plotiso()
    plotHR(os.path.join(smsyn.CAT_DIR, 'library_v12.csv'), teff, logg)
    ax = pl.gca()
    ax.set_xticks([6500, 5500, 4500, 3500])

    labels = ['teff', 'logg', 'fe', 'vsini']
    names = ['T$_{\\rm eff}$', '$\\log{g}$', 'Fe/H', '$v\\sin{i}$']
    units = ['K', '', '', 'km s$^{-1}$']

    if hasiso:
        labels.append('iso_mass')
        labels.append('iso_radius')

        names.append("M$_{\\star}$")
        names.append("R$_{\\star}$")

        units.append('M$_{\\odot}$')
        units.append('R$_{\\odot}$')

    i = 0
    for k, n, u in zip(labels, names, units):

        val = bestpars[k]
        if k + '_err' in bestpars.keys():
            err = bestpars[k + '_err']
        elif k + '_err1' in bestpars.keys():
            err = bestpars[k + '_err1']
        elif k == 'vsini':
            err = val * 0.25

        if k == 'vsini':
            if val < 2:
                pl.annotate("{} $\leq$ 2 {}".format(n, u),
                            xy=(0.76, 0.575 - 0.04 * i),
                            xycoords="figure fraction",
                            fontsize=afs)
            elif val >= 70:
                pl.annotate("{} $\geq$ 70 {}".format(n, u),
                            xy=(0.76, 0.575 - 0.04 * i),
                            xycoords="figure fraction",
                            fontsize=afs)
            else:
                err = smsyn.plotting.utils.round_sig(err, 2)
                val, err, err = smsyn.plotting.utils.sigfig(val, err)
                pl.annotate("{} = {} $\\pm$ {} {}".format(n, val, err, u),
                            xy=(0.76, 0.575 - 0.04 * i),
                            xycoords="figure fraction",
                            fontsize=afs)
        else:
            err = smsyn.plotting.utils.round_sig(err, 2)
            val, err, err = smsyn.plotting.utils.sigfig(val, err)
            # print n, val, err

            pl.annotate("{} = {} $\\pm$ {} {}".format(n, val, err, u),
                        xy=(0.76, 0.575 - 0.04 * i),
                        xycoords="figure fraction",
                        fontsize=afs)
        i += 1

    pl.savefig(outfile)

    return pl.gcf()
def displayFormedClusters(g,src,dest,i):
 global node_colors
 global edge_colors
 global disp_count
 if  i == 1:
       x=np.linspace(-0.1,1,10)
       y1=np.linspace(0.8,0.35,10)
       y2=np.linspace(1.0,0.6,10)
       
       pylab.fill_between(x,y1,y2,color = 'pink')
       nx.draw_networkx(g,pos = nx.circular_layout(g),node_color= node_colors,edge_color = edge_colors)
       pylab.annotate("Source",node_positions[src])
       pylab.annotate("Destination",node_positions[dest])
       pylab.annotate("Cluster 1 - Head ",(0.0,0.9))
       pylab.suptitle('Leach Protocol', fontsize=12)
       pylab.title("Leach Protocol - Cluster 1")
       pylab.pause(2)
 if  i == 2:
       x=np.linspace(-0.1,0.7,10)
       y1=np.linspace(0.3,0.15,10)
       y2=np.linspace(0.15,-0.1,10)
       
       pylab.fill_between(x,y1,y2,color = 'pink')
       nx.draw_networkx(g,pos = nx.circular_layout(g),node_color= node_colors,edge_color = edge_colors)
       pylab.annotate("Source",node_positions[src])
       pylab.annotate("Destination",node_positions[dest])
       pylab.annotate("Cluster 2 - Head ",(0.0,0.1))
       pylab.title("Leach Protocol - Cluster 2")
       pylab.suptitle('Leach Protocol', fontsize=12) 
       pylab.pause(2)
 if  i == 3:
       pylab.fill_between([0.5,0.7],0.9,1.1,color = 'pink')
       nx.draw_networkx(g,pos = nx.circular_layout(g),node_color= node_colors,edge_color = edge_colors)
       pylab.annotate("Source",node_positions[src])
       pylab.annotate("Destination",node_positions[dest])
       pylab.annotate("Cluster 3 - Head ",(0.6,1.1))
       pylab.title("Leach Protocol - Cluster 3")
       pylab.suptitle('Leach Protocol', fontsize=12)
       pylab.pause(2) 
Example #57
0
EnvelData = []
os.path.walk(os.getcwd(), LoadEnvelData, EnvelData)
GeneData = []
os.path.walk(os.getcwd(), LoadGeneNumbers, GeneData)
Tags = []
os.path.walk(os.getcwd(), LoadIterestParam, Tags)

p.figure(1, figsize=(10, 6))
p.subplot(221)
i = 0
for item in EnvelData:
    XX = float(item[1][-i - 1])
    YY = float(item[0][-3])
    ax = p.plot(item[1], item[0], 'k-')
    ax = p.annotate('%1.3f' % (Tags[i], ),
                    xy=(XX, YY),
                    xycoords='data',
                    fontsize=AnnotateFontSize)
    i = i + 1
#p.xlabel('turbulence level ($ T $)', fontsize = AxisLabelFontSize)
p.ylabel('mean genotype\'s envelope surface', fontsize=AxisLabelFontSize)
p.xticks(size=AxisTickFontSize)
p.yticks(size=AxisTickFontSize)
p.grid()

p.subplot(223)
i = 0
for item in GeneData:
    XX = float(item[1][-i - 1])
    YY = float(item[0][-3])
    ax = p.plot(item[1], item[0], 'k-')
    ax = p.annotate('%1.3f' % (Tags[i], ),
Example #58
0
    snr = 10 * log10(peak / noise)
    lags = linspace(-sample_period * args.NFFT / 2,
                    sample_period * args.NFFT / 2,
                    num=args.NFFT)
    delay_lag = corr_coeff.argmax() - args.NFFT / 2
    if baseline[0] == delref:
        delays[baseline[1]] = delay_lag
    elif baseline[1] == delref:
        delays[baseline[0]] = -delay_lag
    delay_ns = lags[corr_coeff.argmax()]
    pylab.plot(lags, corr_coeff)
    pylab.title('{0} (x) {1}'.format(*baseline))
    pylab.annotate(
        '\nCorr. coef.:{0:.2f}\nSNR: {1:.2f} dB\nDelay (lags): {2}\nDelay (ns): {3:.2f}'
        .format(peak, snr, delay_lag, delay_ns),
        xy=(delay_ns, peak),
        xytext=(0.8, 0.8),
        textcoords='axes fraction',
        backgroundcolor='white',
        arrowprops=dict(facecolor='black', width=0.1, headwidth=4, shrink=0.1))
    pylab.ylabel('Correlation Coefficient')
    pylab.xlabel('Delay (ns)')
    pylab.xlim(-sample_period * args.NFFT / 4, sample_period * args.NFFT / 4)

# print out our measured delays
for element in elements:
    min_del = min(delays.values())
    logger.info('{0} delay is {1} samples'.format(
        element, delays[element] + abs(min_del)))

# show all plots
pylab.show()
Example #59
0
minlen_t = []
v_t = []
theta_t = []
for i in range(0, 1000, 10):
    minlen, v, theta = 0, v0 + i * 1., 0
    print 'v =  ', '%.2f' % v
    pro = PROPER_ANGLE(up, low, n, v, eps)
    minlen, theta, delta = pro.calculate(x0, y0, v, B_m, a, alpha, T0, g, dt,
                                         xtar, ytar)
    minlen_t.append(minlen)
    v_t.append(v)
    theta_t.append(theta)
minlen = 10**9
v = 10**9
theta = 0
for i in range(len(v_t)):
    if minlen_t[i] < 40 and v_t[i] < v:
        minlen, v, theta = minlen_t[i], v_t[i], theta_t[i]
print 'v=  %.2f' % v, '    theta=   %.2f  degree' % (theta * 180 / np.pi)
pro = TARGET_PLUS(x0, y0, v, theta, B_m, a, alpha, T0, g, dt)
pro.reinit(xtar, ytar, minlen)
pro.calculate()
pro.plot()
pl.scatter([xtar], [ytar], 50)
pl.annotate(r'target',
            xy=(xtar, ytar),
            xytext=(+5, +15),
            textcoords='offset points',
            fontsize=15)
pl.show(figure)
Example #60
0
           label=legend('Cu(EAM)'))
pylab.plot(Tilt_001_Wolf_Au_EAM[:, 0],
           1E-3 * Tilt_001_Wolf_Au_EAM[:, 1],
           color="green",
           marker='o',
           linestyle='',
           label=legend('Au(EAM)'))
if not args.labels_off:
    pylab.xlabel(xlabel(tex(r'[100]') + ' tilt angle ' + tex(r'\theta')),
                 labelpad=xlabelpad)
    pylab.ylabel(ylabel("Energy " + tex("(J/m^2)")), labelpad=ylabelpad)
offset = 0.5
if args.annotate:
    pylab.annotate(annotate(tex(r'(001)(001)')),
                   xycoords=('data', 'axes fraction'),
                   xy=(0 + offset, 1.05),
                   va="bottom",
                   ha="center",
                   rotation=90)
    pylab.annotate(annotate(tex(r'(0\bar{1}3)(013)')),
                   xycoords=('data', 'axes fraction'),
                   xy=(36.41 + offset, 1.05),
                   va="bottom",
                   ha="center",
                   rotation=90)
    pylab.annotate(annotate(tex(r'(0\bar{1}1)(011)')),
                   xycoords=('data', 'axes fraction'),
                   xy=(90 + offset, 1.05),
                   va="bottom",
                   ha="center",
                   rotation=90)