Пример #1
0
    def rmsdSpreadSubplot(multiplier=1.0, layout=(-1, -1)):
        rmsd_data   = dict( (e, rad_data[e]['innov'][quant])  for e in rad_data.iterkeys() )
        spread_data = dict( (e, rad_data[e]['spread'][quant]) for e in rad_data.iterkeys() )

        times = temp.getTimes()
        n_t = len(times)

        for exp, exp_name in exp_names.iteritems():
            pylab.plot(sawtooth(times, times)[:(n_t + 1)], rmsd_data[exp][:(n_t + 1)], color=colors[exp], linestyle='-')
            pylab.plot(times[(n_t / 2):], rmsd_data[exp][n_t::2], color=colors[exp], linestyle='-')
 
        for exp, exp_name in exp_names.iteritems():
            pylab.plot(sawtooth(times, times)[:(n_t + 1)], spread_data[exp][:(n_t + 1)], color=colors[exp], linestyle='--')
            pylab.plot(times[(n_t / 2):], spread_data[exp][n_t::2], color=colors[exp], linestyle='--')

        ylim = pylab.ylim()
        pylab.plot(times, -1 * np.ones((len(times),)), color='#999999', linestyle='-', label="RMS Innovation")
        pylab.plot(times, -1 * np.ones((len(times),)), color='#999999', linestyle='--', label="Spread")

        pylab.axhline(y=7, color='k', linestyle=':')
        pylab.axvline(x=14400, color='k', linestyle=':')

        pylab.ylabel("RMS Innovation/Spread (dBZ)", size='large')

        pylab.xlim(times[0], times[-1])
        pylab.ylim(ylim)

        pylab.legend(loc=4)

        pylab.xticks(times[::2], [ "" for t in times[::2] ])
        pylab.yticks(size='x-large')
        return
Пример #2
0
def demo_envelopes():

    for i, demo in enumerate(demos):
        try:
            prev = subplot(len(demos), 1, i+1, sharex=prev, sharey=prev)
        except NameError:
            prev = subplot(len(demos), 1, i+1)
        title(repr(demo).strip('{}').replace("'", ""))
        prev.yaxis.set_visible(False)
        prev.xaxis.set_visible(False)

        # Generate carrier of appropriate length for the trial
        #carrier = np.random.normal(size=demo['trial_dur']*fs)
        carrier = np.random.uniform(low=-1, high=1, size=demo['trial_dur']*fs)
        t, waveform, trial_trigs, set_trigs = generate_waveform(carrier, **demo)
        #fill_between(t, waveform, -waveform)
        plot(t, waveform, 'k')
        for trig in set_trigs:
            axvline(trig/fs, color='b', lw=5)
        #for trig in trial_trigs:
        #    axvline(trig/fs, color='b', lw=2.5)
        trig_times = np.true_divide(trial_trigs, fs)
        plot(trig_times, np.ones(len(trig_times)), 'ro')
    prev.xaxis.set_visible(True)
    gcf().subplots_adjust(left=0.05, right=0.95, bottom=0.05, top=0.95,
                          hspace=0.5)
    axis(xmin=-1, ymin=-1.1, ymax=1.1)
    show()
Пример #3
0
    def plotAgainstGFP(self, extradataA = [], extradataG = [], intensity = [], seq = []):
        fig1 = pylab.figure(figsize = (25, 10))
        print len(self.GFP)
        for i in xrange(min(len(data.cat), 3)):
            print len(self.GFP[self.categories == i])
            vect = []
            pylab.subplot(1,3,i+1)
            #pylab.hist(self.GFP[self.categories == i], bins = 20, color = data.colors[i])
            pop = self.GFP[self.categories == i]
            pylab.plot(self.GFP[self.categories == i], self.angles[self.categories == i], data.colors[i]+'o', markersize = 8)#, label = data.cat[i])
            print "cat", i, "n pop", len(self.GFP[(self.categories == i) & (self.GFP > -np.log(12.5))])
            x = np.linspace(np.min(self.GFP[self.categories == i]), np.percentile(self.GFP[self.categories == i], 80),40)
            #fig1.canvas.mpl_connect('pick_event', onpick)
            for j in x:
                vect.append(np.median(self.angles[(self.GFP > j) & (self.categories == i)]))

            pylab.plot([-4.5, -0.5], [vect[0], vect[0]], data.colors[i], label = "mediane de la population entiere", linewidth = 5)
            print vect[0], vect[np.argmax(x > -np.log(12.5))]
            pylab.plot([-np.log(12.5), -0.5], [vect[np.argmax(x > -np.log(12.5))] for k in  [0,1]], data.colors[i], label = "mediane de la population de droite", linewidth = 5, ls = '--')
            pylab.axvline(x = -np.log(12.5), color = 'm', ls = '--', linewidth = 3)
            pylab.xlim([-4.5, -0.5])
            pylab.legend(loc = 2, prop = {'size':17})

            pylab.title(data.cat[i].split(',')[0], fontsize = 24)
            pylab.xlabel('score GFP', fontsize = 20)
            pylab.ylabel('Angle (degre)', fontsize = 20)
            pylab.tick_params(axis='both', which='major', labelsize=20)
            pylab.ylim([-5, 105])
            ##pylab.xscale('log')
        pylab.show()
Пример #4
0
def lookatresults(data, modes, theta=None, vert=False, labels=None):


    P = data[-1][0]
    n = P.shape[0]

    if labels == None:
        labels = [""] * n
    else:
        pass 

    if vert == True:
        subplots = range(n*100+11,n*100+n+11,1)
        figsize = (6, 3*n)
    elif vert == 'four':
        subplots = [221, 222, 223, 224]
        figsize = (10, 10)
    else:
        subplots = range(100+n*10+1,100+n*10+1+n,1)
        figsize = (5*n, 3)

    f = stats.gaussian_kde(data[-1][0])
    int_guess = np.mean(data[-1][0], axis=1)
    modes = minimize(neg, int_guess, args=(f)).x

    thetas = []
    P = data[-1][0]
    labelpad = 20

    for i in xrange(n):
        x = P[i]
        t = r'$\theta_{3:}$ {1:.2f} +{2:.2f}/-{0:.2f}'.format(
            modes[i]-stats.scoreatpercentile(x, 16),
            modes[i],
            stats.scoreatpercentile(x, 84)-modes[i], i+1)

        thetas.append(t)

    if P.shape[1] > 10:
        bins = np.sqrt(P.shape[1])
    else:
        bins=10
    fig = plt.figure(figsize=figsize)
    
    for i in xrange(n):
        print subplots[i]
        plt.subplot(int(subplots[i]))
        #plt.title(thetas[0])
        ker = stats.gaussian_kde(P[i])
        h = plt.hist(P[i], bins=bins, normed=True, alpha=1)
        x = np.linspace(h[1][0],h[1][-1],1000)
        plt.plot(x,ker(x))
        plt.xlabel(labels[i], labelpad=labelpad, fontsize=24)
        if theta != None:
            plt.axvline(theta[0])

    for t in thetas: 
        print t

    return fig
Пример #5
0
 def imshow_box(f,im, x,y,s):
     '''imshow_box(f,im, x,y,s)
     f: figure
     im: image
     x: center coordinate for box
     y: center coord
     s: box shape, (width, height)
     '''
     global coord
     P.figure(f.number)
     P.clf();
     P.imshow(im);
     P.axhline(y-s[1]/2.)
     P.axhline(y+s[1]/2.)
     P.axvline(x-s[0]/2.)
     P.axvline(x+s[0]/2.)
     xy=crop(m,s,y,x)
     coord=(0.5*(xy[2]+xy[3]), 0.5*(xy[0]+xy[1]))
     P.title(str('x: %d y: %d' % (x,y)));        
     P.figure(999);
     P.imshow(master[xy[0]:xy[1],xy[2]:xy[3]])
     P.title('Master');
     P.figure(998);
     df=(master[xy[0]:xy[1],xy[2]:xy[3]]-slave)
     P.imshow(np.abs(df))
     P.title(str('RMS: %0.6f' % np.sqrt((df**2.).mean()) ));        
Пример #6
0
def plot_adsorbed_circles(adsorbed_x,adsorbed_y,radius, width, label=""):
    import pylab
    from matplotlib.patches import Circle

    # Plot each run
    fig = pylab.figure()
    ax = fig.add_subplot(111)
    for p in range(len(adsorbed_x)):
        ax.add_patch(Circle((adsorbed_x[p], adsorbed_y[p]), radius))
        # Plot "image" particles to verify that periodic boundary conditions are working
#        if adsorbed_x[p] < radius:
#            ax.add_patch(Circle((adsorbed_x[p] + width,adsorbed_y[p]), radius, facecolor='red'))
#        elif adsorbed_x[p] > (width-radius):
#            ax.add_patch(Circle((adsorbed_x[p] - width,adsorbed_y[p]), radius, facecolor='red'))
#        if adsorbed_y[p] < radius:
#            ax.add_patch(Circle((adsorbed_x[p],adsorbed_y[p] + width), radius, facecolor='red'))
#        elif adsorbed_y[p] > (width-radius):
#            ax.add_patch(Circle((adsorbed_x[p],adsorbed_y[p] - width), radius, facecolor='red'))

    ax.set_aspect(1.0)
    pylab.axhline(y=0, color='k')
    pylab.axhline(y=width, color='k')
    pylab.axvline(x=0, color='k')
    pylab.axvline(x=width, color='k')
    pylab.axis([-0.1*width, width*1.1, -0.1*width, width*1.1])
    pylab.xlabel("non-dimensional x")
    pylab.ylabel("non-dimensional y")
    pylab.title("Adsorbed particles at theta="+label)

    return ax
Пример #7
0
def plotDirections(aabb=(),mask=0,bins=20,numHist=True,noShow=False,sphSph=False):
	"""Plot 3 histograms for distribution of interaction directions, in yz,xz and xy planes and
	(optional but default) histogram of number of interactions per body. If sphSph only sphere-sphere interactions are considered for the 3 directions histograms.

	:returns: If *noShow* is ``False``, displays the figure and returns nothing. If *noShow*, the figure object is returned without being displayed (works the same way as :yref:`yade.plot.plot`).
	"""
	import pylab,math
	from yade import utils
	for axis in [0,1,2]:
		d=utils.interactionAnglesHistogram(axis,mask=mask,bins=bins,aabb=aabb,sphSph=sphSph)
		fc=[0,0,0]; fc[axis]=1.
		subp=pylab.subplot(220+axis+1,polar=True);
		# 1.1 makes small gaps between values (but the column is a bit decentered)
		pylab.bar(d[0],d[1],width=math.pi/(1.1*bins),fc=fc,alpha=.7,label=['yz','xz','xy'][axis])
		#pylab.title(['yz','xz','xy'][axis]+' plane')
		pylab.text(.5,.25,['yz','xz','xy'][axis],horizontalalignment='center',verticalalignment='center',transform=subp.transAxes,fontsize='xx-large')
	if numHist:
		pylab.subplot(224,polar=False)
		nums,counts=utils.bodyNumInteractionsHistogram(aabb if len(aabb)>0 else utils.aabbExtrema())
		avg=sum([nums[i]*counts[i] for i in range(len(nums))])/(1.*sum(counts))
		pylab.bar(nums,counts,fc=[1,1,0],alpha=.7,align='center')
		pylab.xlabel('Interactions per body (avg. %g)'%avg)
		pylab.axvline(x=avg,linewidth=3,color='r')
		pylab.ylabel('Body count')
	if noShow: return pylab.gcf()
	else:
		pylab.ion()
		pylab.show()
Пример #8
0
def test():
    from pandas import DataFrame
    X = np.linspace(0.01, 1.0, 10)
    Y = np.log(X)
    Y -= Y.min()
    Y /= Y.max()
    Y *= 0.95

    #Y = X

    df = DataFrame({'X': X, 'Y': Y})
    P = Pareto(df, 'X', 'Y')

    data = []
    for val in np.linspace(0,1,15):
        data.append(dict(val=val, x=P.lookup_x(val), y=P.lookup_y(val)))
        pl.axvline(val, alpha=.5)
        pl.axhline(val, alpha=.5)
    dd = DataFrame(data)
    pl.scatter(dd.y, dd.val, lw=0, c='r')
    pl.scatter(dd.val, dd.x, lw=0, c='g')
    print dd

    #P.scatter(c='r', lw=0)
    P.show_frontier(c='r', lw=4)
    pl.show()
Пример #9
0
def plotLDDecaySpaceTime2d(ld0=1):
    T=np.arange(0,1500+1,500)
    L=1e6+1
    pos=500000
    r=2*1e-8
    s=0.01;x0=0.005
    # s=0.05;x0=1e-3

    positions=np.arange(0,L,1000)
    dist=abs(positions - pos)
    def getColor(n):
        color=['k','red','blue','g','m','c','coral']
        return color[:n]
    plt.figure(figsize=(25,12))
    for t,color in zip(T,getColor(len(T))):
        LD(t,ld0,s,x0,r,dist,positions).plot(ax=plt.gca(),linewidth=2, color=color,label='t={}'.format(t))
    for t,color in zip(T,getColor(len(T))):
        if not t :continue
        pd.Series(ld0*np.exp(-r*t*(dist)),index=positions).plot(ax=plt.gca(),style='--',color=color,linewidth=2)
    plt.legend(map(lambda x: 't={}'.format(x),T),loc='best');

    plt.axvline(500000,color='k',linewidth=2)
    plt.gca().axvspan(475000, 525000, alpha=0.25, color='black')
    plt.grid();plt.ylim([-0.05,1.1]);plt.xlabel('Position');plt.ylabel('LD to Position 500K');plt.title('Space-Time Decay of LD under Neutral Evolution');
    # plt.savefig(Simulation.paperFiguresPath+'LDDecay2d')
    plt.show()
Пример #10
0
def equil():


    eq_m = -0.0001
    rise_rate = 0.0125
    mag = 20
    ts = linspace(0, 400, 500)
    f = F(ts, mag=mag)
#     g = eq_m * f
    g = G(ts, f, rate=eq_m)
    b = rise_rate * ts

    fg = f + g + b
    plot(ts, f, label='F Equilibration')
    plot(ts, g, label='G Consumption')
    plot(ts, fg, label='F-G (Sniff Evo)')

    rf, rollover_F, vi_F = calc_optimal_eqtime(ts, f)
    rfg, rollover_FG, vi_FG = calc_optimal_eqtime(ts, fg)
    m = 2 * eq_m * mag

    axvline(x=rollover_F, ls='--', color='blue')
    axvline(x=rollover_FG, ls='--', color='red')

    idx = list(ts).index(rollover_F)

    b = fg[idx] - m * rollover_F
    evo = polyval((m, b), ts)
    plot(ts, evo, ls='-.', color='blue', label='Static Evo. A')
    # ee = where(evo > mag)[0]
    # to_F = ts[max(ee)]
    # print 'F', rollover_F, b, to_F


    b = vi_FG - m * rollover_FG
    evo = polyval((m, b), ts)
    plot(ts, evo, ls='-.', color='red', label='Static Evo. B')

    print polyval((m, b), 200)
    ee = where(evo > mag)[0]
#     to_FG = ts[max(ee)]
#     print 'FG', rollover_FG, b, to_FG

#     axvline(x=to_FG, ls='-', color='red')
#     axvline(x=to_F, ls='-', color='blue')

    axhline(y=mag, ls='-', color='black')
#    plot([ti], [mag], 'bo')

    legend(loc=0)
#     ylim(2980, 3020)
    ylim(18, 21)
    xlim(0, 20)
    ylabel('Intensity')
    xlabel('t (s)')
#    fig = gcf()
#    fig.text(0.1, 0.01, 'asdfasfasfsadfsdaf')


    show()
Пример #11
0
def _show_rates(rate, wo, wt, attenuator, tau_NP, tau_P):
    import pylab

    #pylab.figure()
    pylab.errorbar(rate, wt[0], yerr=wt[1], fmt='g.', label='attenuated')
    pylab.errorbar(rate, wo[0], yerr=wo[1], fmt='b.', label='unattenuated')

    pylab.xscale('log')
    pylab.yscale('log')
    pylab.xlabel('incident rate (counts/second)')
    pylab.ylabel('observed rate (counts/second)')
    pylab.legend(loc='best')
    pylab.grid(True)
    pylab.plot(rate, rate/attenuator, 'g-', label='target')
    pylab.plot(rate, rate, 'b-', label='target')

    Ipeak, Rpeak = peak_rate(tau_NP=tau_NP, tau_P=tau_P)
    if rate[0] <= Ipeak <= rate[-1]:
        pylab.axvline(x=Ipeak, ls='--', c='b')
        pylab.text(x=Ipeak, y=0.05, s=' %g'%Ipeak,
                   ha='left', va='bottom',
                   transform=pylab.gca().get_xaxis_transform())
    if False:
        pylab.axhline(y=Rpeak, ls='--', c='b')
        pylab.text(y=Rpeak, x=0.05, s=' %g\n'%Rpeak,
                   ha='left', va='bottom',
                   transform=pylab.gca().get_yaxis_transform())
Пример #12
0
    def plot(self):
        f = pylab.figure(figsize=(8,4))
        co = [] #colors container
        for zScore, r in itertools.izip(self.zScores, self.log2Ratio):
            if zScore < self.pCut:
                if r > 0:
                    co.append(Colors().greenColor)
                elif r < 0:
                    co.append(Colors().redColor)
                else:
                    raise Exception
            else:
                co.append(Colors().blueColor)

        #print "Probability this is from a normal distribution: %.3e" %stats.normaltest(self.log2Ratio)[1]
        ax = f.add_subplot(121)
        pylab.axvline(self.meanLog2Ratio, color=Colors().redColor)
        pylab.axvspan(self.meanLog2Ratio-(2*self.stdLog2Ratio), 
                      self.meanLog2Ratio+(2*self.stdLog2Ratio), color=Colors().blueColor, alpha=0.2)
        his = pylab.hist(self.log2Ratio, bins=50, color=Colors().blueColor)
        pylab.xlabel("log2 Ratio %s/%s" %(self.sampleNames[1], self.sampleNames[0]))
        pylab.ylabel("Frequency")
        
        ax = f.add_subplot(122, aspect='equal')
        pylab.scatter(self.genes1, self.genes2, c=co, alpha=0.5)        
        pylab.ylabel("%s RPKM" %self.sampleNames[1])
        pylab.xlabel("%s RPKM" %self.sampleNames[0])
        pylab.yscale('log')
        pylab.xscale('log')
        pylab.tight_layout()
Пример #13
0
def esat_comparison_plot(t=_np.linspace(173.15, 373.15, 20), std="Hyland_Wexler", percent=True, log=False):
    import pylab
    import brewer2mpl

    methods = list(esat(0, method="return"))
    methods.remove(std)
    print len(methods)
    pylab.rcParams.update({"axes.color_cycle": brewer2mpl.get_map("Paired", "qualitative", 12).mpl_colors})
    y = esat(t, method=std, info=False)
    i = 0
    style = "-"
    for im in methods:
        if i > 11:
            style = "--"
        print im
        if percent:
            pylab.plot(t, 100.0 * (esat(t, method=im, info=False) - y) / y, lw=2, ls=style)
        else:
            pylab.plot(t, esat(t, method=im, info=False) - y, lw=2, ls=style)
        i += 1
    pylab.legend(methods, loc="upper right", fontsize=8)
    pylab.xlabel("Temperature [K]")
    if percent:
        # pylab.semilogy()
        pylab.ylabel("Water Vapor Pressure Difference [%]")
    else:
        pylab.ylabel("Water Vapor Pressure [Pa]")
    pylab.title("Comparison of Water Vapor Calculations Ref:" + std)
    pylab.xlim(_np.round(t[0]), _np.round(t[-1]))
    pylab.grid()
    pylab.axvline(x=273.15, color="k")
    if log:
        pylab.yscale("log")
Пример #14
0
	def plot_statistic_vs_burnin(self, param, points=20, mean=True, error=False, showpoints=True):
		samples = self.samples[parameters[param]]
		burn = np.linspace(0, len(samples), points)[:-1].astype(int)
		means = []
		stds=[]
		for b in burn:
			if mean:
				means.append( np.mean(samples[b:]) )

			if error:
				stds.append(np.std(samples[b:]))


		if mean:
			plt.plot(burn, means, "-", color="purple", lw=2.0, label="mean")
			if showpoints:
				plt.plot(burn, means, "o", color="purple")
			plt.ylabel("mean %s"%labels[param])

		if error:
			plt.plot(burn, stds, "-", color="midnightblue", lw=2.0, label="error")
			if showpoints:
				plt.plot(burn, stds, "o", color="midnightblue")
			plt.ylabel("error %s"%labels[param])

		if error and mean:
			plt.ylabel("error or mean %s"%labels[param])
			plt.legend(loc="upper left")


		plt.xlabel("points discarded")
		

		plt.axvline(len(samples), color="k", lw=2)
def simFlips(numFlips, numTrials):      # performs and displays the simulation result
    diffs = []                          # diffs to know if there was a fair Trial. It has the absolute differences of heads and tails in each trial
    for i in xrange(0, numTrials):           
        heads, tails = flipTrial(numFlips)
        diffs.append(abs(heads - tails))
                
    diffs = pylab.array(diffs)          # create an array of diffs
    diffMean = sum(diffs)/len(diffs)    # average of absolute differences of heads and tails from each trial
    diffPercent = (diffs/float(numFlips)) * 100     # create an array of percentage of each diffs from its no. of flips.
    percentMean = sum(diffPercent)/len(diffPercent)     # create a percent mean of all diffPercents in the array
    
    pylab.hist(diffs)                   # displays the distribution of elements in diffs array
    pylab.axvline(diffMean, color = 'r', label = 'Mean')
    pylab.legend()
    titleString = str(numFlips) + ' Flips, ' + str(numTrials) + ' Trials'
    pylab.title(titleString)
    pylab.xlabel('Difference between heads and tails')
    pylab.ylabel('Number of Trials')
    
    pylab.figure()
    pylab.plot(diffPercent)
    pylab.axhline(percentMean, color = 'r', label = 'Mean')
    pylab.legend()
    pylab.title(titleString)
    pylab.xlabel('Trial Number')
    pylab.ylabel('Percent Difference between heads and tails')
	def draw_img_for_viewing(self):
		if(not options.inspectOnly):
			print "Press 'p' to save PNG."
		global colmax
		global colmin
		P.close('all')
		fig = P.figure(num=None, figsize=(13.5, 5), dpi=100, facecolor='w', edgecolor='k')
		cid1 = fig.canvas.mpl_connect('key_press_event', self.on_keypress_for_viewing)
		cid2 = fig.canvas.mpl_connect('button_press_event', self.on_click)
		canvas = fig.add_subplot(121)
		canvas.set_title(self.filename)
		self.axes = P.imshow(self.inarr, origin='lower', vmax = colmax, vmin = colmin)
		#self.axes = P.imshow(self.inarr, origin='lower', vmax = 2000, vmin = 0)
		self.colbar = P.colorbar(self.axes, pad=0.01)
		self.orglims = self.axes.get_clim()
		canvas = fig.add_subplot(122)
		canvas.set_title("angular average")
		maxAngAvg = (self.inangavg).max()
		for i,j in eDD.iceHInvAngQ.iteritems():
			self.HIceQ[i] = eDD.get_pix_from_invAngsQ_and_detectorDist(runtag,j,self.detectorDistance, wavelengthInAngs=self.wavelength)

		numQLabels = len(self.HIceQ.keys())+1
		labelPosition = maxAngAvg/numQLabels
		for i,j in self.HIceQ.iteritems():
			P.axvline(j,0,colmax,color='r')
			P.text(j,labelPosition,str(i), rotation="45")
			labelPosition += maxAngAvg/numQLabels

		P.plot(self.inangavg)
		P.show()
Пример #17
0
def plot(kmv):
    py.scatter([d / float(2 ** 32 - 1)
                for d in kmv.data[:-1]], [0] * (len(kmv.data) - 1), alpha=0.25)
    py.axvline(x=(kmv.data[-2] / float(2 ** 32 - 1)), c='r')
    py.gca().get_yaxis().set_visible(False)
    py.gca().get_xaxis().set_ticklabels([])
    py.gca().get_xaxis().set_ticks([x / 10. for x in xrange(11)])
def problem4():
    numViruses = 100
    viruses = [ResistantVirus(0.1, 0.05, {'guttagonol':False}, .005) for i in xrange(numViruses)] # list comprehension
    patient = Patient(viruses,1000)
    time = 0
    timetodrug = 10
    timetoend = timetodrug + 150
    popNums = []
    resistNums = []
    while time <= timetodrug:
        popNums.append(patient.update())
        time += 1  
    patient.addPrescription('guttagonol')
    while time <= timetoend:
        popNums.append(patient.update())
        resistNums.append( patient.getResistPop(patient.getPrescriptions()) )
        time += 1
    pylab.figure()
    pylab.plot(popNums, '-r', label = 'Total Population')
    if resistNums[-1] > 0:
        pylab.plot(xrange(timetodrug+1,timetoend+1), resistNums, '-b', label = 'Resistant Population')
        pylab.legend()
    pylab.axis([-5, timetoend+5, -5, 600])
    pylab.ylabel ('Population Size')
    pylab.xlabel ('Time elapsed')
    pylab.title ('ResistantVirus pop over time, w/ Guttagonol added after ' + str(timetodrug) + ' ticks')
    pylab.axvline (x=timetodrug, linestyle = '--')
    
    print "Highest population of resistant bugs was: " + str(resistNums[-1])
    pylab.show()
Пример #19
0
def debug_plot(a, b, nodes, fs, coeffs):
    global _debug_fig, _debug_cancelled
    if _debug_cancelled:
        return
    if 'show' not in locals():
        from pylab import axes, subplot, subplots_adjust, figure, draw, plot, axvline, xlim, title, waitforbuttonpress, gcf
        from matplotlib.widgets import Button
    if _debug_fig is None:
        #curfig = gcf()
        #print dir(curfig)
        _debug_fig = figure()
        ax = _debug_fig.add_subplot(111)
        #subplots_adjust(bottom=0.15)
        butax = axes([0.8, 0.015, 0.1, 0.04])
        button = Button(butax, 'Debug', hovercolor='0.975')
        def debug(event):
            import pdb; pdb.set_trace()
        button.on_clicked(debug)
        _debug_fig.sca(ax)
        draw()
        #figure(curfig)
    _debug_fig.gca().clear()
    plot(nodes, fs, linewidth=5, figure = _debug_fig)
    axvline(a, color="r", figure = _debug_fig)
    axvline(b, color="r", figure = _debug_fig)
    d = 0.05 * (b-a)
    _debug_fig.gca().set_xlim(a-d, b+d)
    title("press key in figure for next debugplot or close window to continue")
    try:
        while not _debug_cancelled and not _debug_fig.waitforbuttonpress(-1):
            pass
    except:
        _debug_cancelled = True
Пример #20
0
    def main(self):
        global weights, densities, weighted_densities
        plt.figure()

        cluster = clusters.SingleStation()
        self.station = cluster.stations[0]

        R = np.linspace(0, 100, 100)
        densities = []
        weights = []
        for E in np.linspace(1e13, 1e17, 10000):
            relative_flux = E ** -2.7
            Ne = 10 ** (np.log10(E) - 15 + 4.8)
            self.ldf = KascadeLdf(Ne)
            min_dens = self.calculate_minimum_density_for_station_at_R(R)

            weights.append(relative_flux)
            densities.append(min_dens)
        weights = np.array(weights)
        densities = np.array(densities).T

        weighted_densities = (np.sum(weights * densities, axis=1) /
                              np.sum(weights))
        plt.plot(R, weighted_densities)
        plt.yscale('log')
        plt.ylabel("Min. density [m^{-2}]")
        plt.xlabel("Core distance [m]")
        plt.axvline(5.77)
        plt.show()
Пример #21
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)
    def draw_cell_size_distribution_diagram(self, diagram_file_name, cell_list):

        cell_distribution_hashmap = {}
        nr_of_points_list = []
        for cell in cell_list:
            value = cell_distribution_hashmap.get(cell.get_nr_of_points(), 0)
            cell_distribution_hashmap[cell.get_nr_of_points()] = value + 1
            nr_of_points_list.append(cell.get_nr_of_points())

        index_max = cell_distribution_hashmap.keys()[-1] + 3
        index_min = 0

        value_list = []
        for index in range(index_min, index_max):
            value_list.append(cell_distribution_hashmap.get(index, 0))


        median_value = numpy.median(nr_of_points_list)
        print '[i] calculated median value: %f' % median_value

        mean_value =  float(sum(value_list)) / len(value_list)
        print '[i] calculated mean value: %f' % mean_value

        pylab.plot(value_list, 'r',  label='cell size distribution')
        pylab.axvline(x=median_value, label='median')

        pylab.xlabel('cell size [pixel]')
        pylab.ylabel('cell count [cells]')
        pylab.title('cell size distribution')
        pylab.grid(True)
        pylab.legend(loc= 'best')

        pylab.savefig(self.log_path + '/' + diagram_file_name)
Пример #23
0
def Cross(x0=0.0, y0=0.0, clr='black', ls='dashed', lw=1, zorder=0):
    """
    Draw cross through zero
    =======================
    """
    axvline(x0, color=clr, linestyle=ls, linewidth=lw, zorder=zorder)
    axhline(y0, color=clr, linestyle=ls, linewidth=lw, zorder=zorder)
    def dofit(xs, slambdas, alpha, sinbeta, gamma, delta, band, y):
        xs = np.array(xs)
        ok = np.isfinite(slambdas)
        lsf = Fit.do_fit_wavelengths(xs[ok], lines[ok], alpha, sinbeta, 
                gamma, delta, band, y, error=slambdas[ok])
        (order, pixel_y, alpha, sinbeta, gamma, delta) = lsf.params

        print "order alpha    sinbeta   gamma  delta"
        print "%1.0i %5.7f %3.5f %3.2e %5.2f" % (order, alpha, sinbeta, 
                gamma, delta)

        ll = Fit.wavelength_model(lsf.params, pix)
        if DRAW:
            pl.figure(3)
            pl.clf()
            pl.plot(ll, spec)
            pl.title("Pixel %4.4f" % pos)
            for lam in lines:
                pl.axvline(lam, color='r')

            pl.draw()
    
        return [np.abs((
            Fit.wavelength_model(lsf.params, xs[ok]) - lines[ok]))*1e4, 
                lsf.params]
Пример #25
0
    def test_band_unpolarized(self):
        """polarizedのPROCAR用"""
        # import seaborn
        path = os.path.join(self.path, 'unpolarized', 'C_P63mmmc')
        dos = collect_vasp.Doscar(os.path.join(path, 'DOSCAR_polarized'))
        dos.get_data()
        e_fermi = dos.fermi_energy  # DOSCARからのEf
        band = collect_vasp.Procar(os.path.join(path, 'PROCAR_band'),
                                   is_polarized=False)
        band['energy'] = band['energy'] - e_fermi
        band.output_keys = ['kpoint_id', 'energy', "spin"]
        kp_label = band.get_turning_kpoints_pmg(os.path.join(path, 'KPOINTS_band'))

        # plot
        plt = pylab.figure(figsize=(7, 7/1.618))
        ax1 = plt.add_subplot(111)
        ax1.set_ylabel("Energy from $E_F$(meV)")
        ax1.set_xlabel("BZ direction")

        # 枠
        for i in kp_label[0]:
            pylab.axvline(x=i, ls=':', color='gray')
        pylab.axhline(y=0, ls=':', color='gray')

        ax1.scatter(band['kpoint_id'], band['energy'], s=3, c='blue',
                    linewidths=0)
        ax1.set_xlim(0, band['kpoint_id'][-1])

        pylab.xticks(kp_label[0], kp_label[1])
        pylab.show()
Пример #26
0
def simpleExample():
	# Create a signal
	N = 256
	signal = numpy.zeros(N,numpy.complex128)
	# Make our signal 1 in the middle, zero elsewhere
	signal[N/2] = 1.0
	# plot our signal
	pylab.figure()
	pylab.plot(abs(signal))
	# Do the GFT on the signal
	SIGNAL = gft.gft1d(signal,'gaussian')
	# plot the magnitude of the signal
	pylab.figure()
	pylab.plot(abs(SIGNAL),'b')
	
	# get the partitions
	partitions = gft.partitions(N)
	# for each partition, draw a line on the graph.  Since the partitions only indicate the
	# positive frequencies, we need to draw partitions on both sides of the DC
	for i in partitions[0:len(partitions)/2]:
		pylab.axvline((N/2+i),color='r',alpha=0.2)
		pylab.axvline((N/2-i),color='r',alpha=0.2)
		
	# finally, interpolate the GFT spectrum and plot a spectrogram
	pylab.figure()
	pylab.imshow(abs(gft.gft1dInterpolateNN(SIGNAL)))
def demo_perfidious(n):
    plt.figure()

    r = (np.arange(n)+1)/float(n+1)

    bases = [(PowerBasis(), "Power"),
             (ChebyshevBasis(interval=(1./(n+1),n/float(n+1))),"Chebyshev"), 
             (LagrangeBasis(interval=(1./(n+1),n/float(n+1))),"Lagrange"), 
             (LagrangeBasis(r),"Specialized Lagrange")]

    xs = np.linspace(0,1,50*n)
    
    for (i,(b,l)) in enumerate(bases):
        p = b.from_roots(r)
        plt.subplot(len(bases),1,i+1)
        plt.semilogy(xs,np.abs(p(xs)),label=l)
        plt.xlim(0,1)
        plt.ylim(min=1)
        
        for j in range(n):
            plt.axvline((j+1)/float(n+1),linestyle=":",color="black")
        plt.legend(loc="best")
    print b.points
    print p.coefficients
    plt.subplot(len(bases),1,1)
    plt.title('The "perfidious polynomial" for n=%d' % n)
Пример #28
0
 def plot(self, gs):
     unit_len = self.show_len * 1. / 5.
     if self.s.now - self.show_len < 0:
         return 
         
     price = self.price[0][self.s.now - self.show_len : self.s.now]
     profile_range = [price.min(), price.max() + 1]
     floor, ceil = profile_range[0] - 1, profile_range[1] + 1
         
     d = self.output(3, profile_range)
     
     ax = plt.subplot(gs)
     plt.plot(price)
     day_begin = np.where(self.s.history['time_in_ticks'][self.s.now - self.show_len : self.s.now] == 0)[0]
     for x in day_begin:
         plt.axvline(x, color='r', linestyle=':')
     y = self.smoothed_pivot_profile[floor : ceil]
     plt.barh(np.arange(floor, ceil) - 0.5, y * unit_len, 1.0, label=self.name,
              alpha=0.2, color='r', edgecolor='none')
     
     last_price = int(get(self.price))
     support = last_price + int(round((d['S_offset']) * self.volatility))
     resistance = last_price + int(round((d['R_offset']) * self.volatility))
     highlighted = [support, resistance]
     plt.barh(np.array(highlighted) - 0.5, self.smoothed_pivot_profile[highlighted] * unit_len, 1.0,
              alpha=1.0, color='r', edgecolor='none')
     ax.set_xticks(np.arange(0, self.show_len * 1.22, unit_len))
     ax.xaxis.grid(b=True, linestyle='--')
     ax.yaxis.grid(b=False)
     plt.legend(loc='upper right')
     return ax
Пример #29
0
def test():
    if 0:
        from pandas import DataFrame
        X = np.linspace(0.01, 1.0, 10)
        Y = np.log(X)
        Y -= Y.min()
        Y /= Y.max()
        Y *= 0.95

        df = DataFrame({'X': X, 'Y': Y})
        P = Pareto(df, 'X', 'Y')

        data = []
        for val in np.linspace(0,1,15):
            data.append(dict(val=val, x=P.lookup_x(val), y=P.lookup_y(val)))
            pl.axvline(val, alpha=.5)
            pl.axhline(val, alpha=.5)
        dd = DataFrame(data)
        pl.scatter(dd.y, dd.val, lw=0, c='r')
        pl.scatter(dd.val, dd.x, lw=0, c='g')
        print dd

        #P.scatter(c='r', lw=0)
        P.show_frontier(c='r', lw=4)
        pl.show()

    X,Y = np.random.normal(0,1,size=(2, 30))

    for maxX in [0,1]:
        for maxY in [0,1]:
            pl.figure()
            pl.title('max x: %s, max y: %s' % (maxX, maxY))
            pl.scatter(X,Y,lw=0)
            show_frontier(X, Y, maxX=maxX, maxY=maxY)
            pl.show()
Пример #30
0
def measure_tae():
   print "Measuring initial perception of all orientations..."
   before=test_all_orientations(0.0,0.0)
   pylab.figure(figsize=(5,5))
   vectorplot(degrees(before.keys()),  degrees(before.keys()),style="--") # add a dashed reference line
   vectorplot(degrees(before.values()),degrees(before.keys()),\
             title="Initial perceived values for each orientation")

   print "Adapting to pi/2 gaussian at the center of retina for 90 iterations..."
   for p in ["LateralExcitatory","LateralInhibitory","LGNOnAfferent","LGNOffAfferent"]:
      # Value is just an approximate match to bednar:nc00; not calculated directly
      topo.sim["V1"].projections(p).learning_rate = 0.005

   inputs = [pattern.Gaussian(x = 0.0, y = 0.0, orientation = pi/2.0,
                     size=0.088388, aspect_ratio=4.66667, scale=1.0)]
   topo.sim['Retina'].input_generator.generators = inputs
   topo.sim.run(90)


   print "Measuring adapted perception of all orientations..."
   after=test_all_orientations(0.0,0.0)
   before_vals = array(before.values())
   after_vals  = array(after.values())
   diff_vals   = before_vals-after_vals # Sign flipped to match conventions

   pylab.figure(figsize=(5,5))
   pylab.axvline(90.0)
   pylab.axhline(0.0)
   vectorplot(wrap(-90.0,90.0,degrees(diff_vals)),degrees(before.keys()),\
             title="Difference from initial perceived value for each orientation")
Пример #31
0
def select_stars(input_cat, cluster, detect_band, website):
    ''' REMEMBER SATURATE !@#$!@#%@%^#%&!@#$%!@#$!@#$!#$^$%^ MAXVAL '''
    import pylab, pyfits, scipy

    porig = pyfits.open(input_cat)
    p = porig[1].data

    reg = open('regstart.reg', 'w')
    reg.write(
        'global color=blue dashlist=8 3 width=1 font="helvetica 10 normal" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\nphysical\n'
    )
    for x, y in zip(p.field('Xpos'), p.field('Ypos')):
        reg.write('circle(' + str(x) + ',' + str(y) + ',18)#' + '\n')
    reg.close()

    from copy import copy
    ''' if seeing is really bad (unfocused) use FLUX_RADIUS '''

    masks = []
    ok = 0
    seeings = p.field('FLUX_RADIUS')[0]
    radius_var = 'FLUX_RADIUS'
    ap_type = prefix(detect_band)  #'APER1-SUBARU-10_2-1-W-J-V'
    ''' need to isolate the star column '''

    mask = (p.field('Flag') == 0) * (p.field(ap_type) > -90)
    array = p[mask]

    #mask = array.field('IMAFLAGS_ISO' ) == 0
    save_array = copy(array)

    if 0:
        pylab.clf()
        pylab.scatter(p.field(radius_var), p.field(ap_type), c='red')

        pylab.xlim([0, 10])
        pylab.ylim([-20, 0])
        pylab.xlabel(radius_var)
        pylab.ylabel(ap_type)
        pylab.savefig('/Volumes/mosquitocoast/patrick/kpno/' + run +
                      '/work_night/' + snpath + '/starcolumn' + star_select +
                      '.pdf')

    from copy import copy

    array = copy(save_array)
    pylab.clf()
    a, b, varp = pylab.hist(array.field(radius_var),
                            bins=scipy.arange(1.0, 8, 0.1))

    #pylab.savefig('/Users/pkelly/Dropbox/star'  + 'hist.pdf')
    z = zip(a, b)
    z.sort()
    max_meas = z[-1][1]

    def get_width_upper(max, width, upper, array_in):

        from copy import copy
        array = copy(array_in)
        ''' now pick objects somewhat larger than star column '''
        mask = array.field(radius_var) > max + width
        array = array[mask]
        rads = array.field(radius_var)  #[mask]
        mask = rads < max + width + 0.6
        array = array[mask]
        mags = array.field(ap_type)
        mags.sort()
        ''' take 20% percentile and subtract 0.5 mag '''
        if len(mags) == 0:
            upper = 99
        else:
            upper = mags[int(len(mags) * 0.2)]  #+ 0.5

        array = copy(array_in)
        maskA = array.field(ap_type) < upper  #+ 0.5
        maskB = array.field(radius_var) < max + width
        maskC = array.field(radius_var) > max - width
        mask = scipy.logical_and(maskA, maskB, maskC)
        array = array[mask]
        rads = array.field(radius_var)

        pylab.clf()
        a, b, varp = pylab.hist(array.field(radius_var),
                                bins=scipy.arange(1.0, 8, 0.04))
        z = zip(a, b)
        z.sort()
        max = z[-1][1]
        width = 1.0 * scipy.std(rads)
        print 'width', width, 'max', max, 'upper', upper, 'rads', rads
        return max, width, upper

    max, width, upper = get_width_upper(max_meas, 0.3, 100, copy(save_array))
    # print max, max_meas, width, upper
    max, width, upper = get_width_upper(max, width, upper, copy(save_array))

    pylab.clf()
    pylab.scatter(save_array.field(radius_var),
                  save_array.field(ap_type),
                  s=0.01)
    pylab.axvline(x=max - width, c='red')
    pylab.axvline(x=max + width, c='red')
    pylab.axhline(y=upper, c='red')

    if False:
        mask = save_array.field('CLASS_STAR_reg_') > 0.9
        print save_array.field('CLASS_STAR_reg_')
        pm = save_array[mask]
        pylab.scatter(pm.field(radius_var), pm.field(ap_type), c='red')

    pylab.xlim([0, 10])
    #pylab.ylim([-20,0])
    pylab.xlabel(radius_var)
    pylab.ylabel(ap_type)
    pylab.savefig(website + 'stars.png')
    #pylab.show()

    #reg = open('regall.reg','w')
    #reg.write('global color=yellow dashlist=8 3 width=1 font="helvetica 10 normal" select=1 highlite=1 dash=0 fixed=0 edit=1 move=1 delete=1 include=1 source=1\nphysical\n')
    #for x,y in zip(p.field('X_IMAGE_reg_g'),p.field('Y_IMAGE_reg_g')):
    #    reg.write('circle(' + str(x) + ',' + str(y) + ',19)#' + '\n')
    #reg.close()

    return max, width
Пример #32
0
    def plot(self, filename=None):
        """
        Plot vrep and derivative together with fit info.

        parameters:
        ===========
        filename:     graphics output file name
        """
        try:
            import pylab as pl
        except:
            raise AssertionError('pylab could not be imported')
        r=np.linspace(0,self.r_cut)
        v=[self(x,der=0) for x in r]
        vp=[self(x,der=1) for x in r]
        rmin=0.95*min([d[0] for d in self.deriv])
        rmax = 1.1*self.r_cut

        fig=pl.figure()
        pl.subplots_adjust(wspace=0.25)

        # Vrep
        pl.subplot(1,2,1)
        pl.ylabel(r'$V_{rep}(r)$  (eV)')
        pl.xlabel(r'$r$  ($\AA$)')
        if self.r_dimer!=None:
            pl.axvline(x=self.r_dimer,c='r',ls=':')
        pl.axvline(x=self.r_cut,c='r',ls=':')
        pl.plot(r,v)
        pl.ylim(ymin=0,ymax=self(rmin))
        pl.xlim(xmin=rmin, xmax=self.r_cut)

        # Vrep'
        pl.subplot(1,2,2)
        pl.ylabel(r'$dV_{rep}(r)/dr$ (eV/$\AA$)')
        pl.xlabel(r'$r$ ($\AA$)')
        pl.plot(r,vp,label=r'$dV_{rep}(r)/dr$')
        for s in self.deriv:
            pl.scatter( [s[0]],[s[1]],s=100*s[2],c=s[3],label=s[4])
        pl.axvline(x=self.r_cut,c='r',ls=':')
        if self.r_dimer!=None:
            pl.axvline(x=self.r_dimer,c='r',ls=':')

        ymin = 0
        for point in self.deriv:
            if rmin<=point[0]<=rmax: ymin = min(ymin,point[1])
        ymax = np.abs(ymin)*0.1
        pl.axhline(0,ls='--',c='k')
        if self.r_dimer!=None:
            pl.text(self.r_dimer, ymax, r'$r_{dimer}$')
        pl.text(self.r_cut, ymax, r'$r_{cut}$')
        pl.xlim(xmin=rmin, xmax=rmax)
        pl.ylim(ymin=ymin, ymax=ymax)
        #pl.subtitle('Fitting for %s and %s' % (self.sym1, self.sym2))
        pl.rc('font', size=10)
        pl.rc('legend',fontsize=8)
        pl.legend(loc=4)
        file = '%s_%s_repulsion.pdf' % (self.sym1, self.sym2)
        if filename!=None:
            file=filename
        pl.savefig(file)
        pl.clf()
Пример #33
0
idxs = np.random.randint(0, high=p.n**2, size=200)

pp.custom_axes()
pl.ylabel('Synaptic Weight')
pl.xlabel('Time [s]')

pl.xlim(snap_times[1] if pl.gca().get_xscale() == 'log' else 0, p.sim_time)
if logx:
    pl.gca().set_xscale('log')
    pl.xlim(6e3, 1e6)

pl.ylim(0., 0.4)
pl.yticks([0, 0.2, 0.4])

if time_first_sat is not None:
    pl.axvline(time_first_sat, color='gray')

for snap_idx in snap_plot_idxs:
    pl.plot(snap_times[snap_idx],
            0.015,
            marker='v',
            mfc=pp.red,
            ms=10,
            mec='k')

#eigenvalues
pl.subplot(121)
pl.xlabel('Frequency [1/m]')
pl.ylabel('Eigenvalue')

pl.plot(eigs_freqs, raw_eigs - p.a, '-k')
Пример #34
0
pl.imshow(lena, cmap=pl.cm.gray, vmin=vmin, vmax=256)

# compressed lena
pl.figure(2, figsize=(3, 2.2))
pl.imshow(lena_compressed, cmap=pl.cm.gray, vmin=vmin, vmax=vmax)

# equal bins lena
regular_values = np.linspace(0, 256, n_clusters + 1)
regular_labels = np.searchsorted(regular_values, lena) - 1
regular_values = .5 * (regular_values[1:] + regular_values[:-1])  # mean
regular_lena = np.choose(regular_labels.ravel(), regular_values)
regular_lena.shape = lena.shape
pl.figure(3, figsize=(3, 2.2))
pl.imshow(regular_lena, cmap=pl.cm.gray, vmin=vmin, vmax=vmax)

# histogram
pl.figure(4, figsize=(3, 2.2))
pl.clf()
pl.axes([.01, .01, .98, .98])
pl.hist(X, bins=256, color='.5', edgecolor='.5')
pl.yticks(())
pl.xticks(regular_values)
values = np.sort(values)
for center_1, center_2 in zip(values[:-1], values[1:]):
    pl.axvline(.5 * (center_1 + center_2), color='b')

for center_1, center_2 in zip(regular_values[:-1], regular_values[1:]):
    pl.axvline(.5 * (center_1 + center_2), color='b', linestyle='--')

pl.show()
def plotCorrespondences(imgsources, refsources, matches, wcs, W, H, prefix):
    ix = np.array([s.getXAstrom() for s in imgsources])
    iy = np.array([s.getYAstrom() for s in imgsources])

    rx, ry = [], []
    for r in refsources:
        xy = wcs.skyToPixel(r.getRaDec())
        rx.append(xy[0])
        ry.append(xy[1])
    rx = np.array(rx)
    ry = np.array(ry)

    # correspondences we could have hit...
    ixy = np.vstack((ix, iy)).T
    rxy = np.vstack((rx, ry)).T
    dcell = 50.
    radius = dcell * np.sqrt(2.)
    # print 'ixy', ixy.shape
    # print 'rxy', rxy.shape

    if False:
        (inds, dists) = spherematch.match(rxy, ixy, radius)
        mi = inds[:, 0]
        ii = inds[:, 1]
        matchx = rx[mi]
        matchy = ry[mi]
        matchdx = ix[ii] - matchx
        matchdy = iy[ii] - matchy
        ok = (matchdx >= -dcell) * (matchdx <= dcell) * (matchdy >= -dcell) * (
            matchdy <= dcell)
        matchx = matchx[ok]
        matchy = matchy[ok]
        matchdx = matchdx[ok]
        matchdy = matchdy[ok]
        mi = mi[ok]
        ii = ii[ok]
        print('Found %i matches within %g pixels' % (len(dists), radius))

    ncells = 18.
    cellsize = np.sqrt(W * H / ncells)
    nw = int(round(W / cellsize))
    nh = int(round(H / cellsize))
    # print 'Grid cell size', cellsize
    # print 'N cells', nw, 'x', nh
    edgesx = np.linspace(0, W, nw + 1)
    edgesy = np.linspace(0, H, nh + 1)

    binx = np.digitize(rx, edgesx)
    biny = np.digitize(ry, edgesy)
    binx = np.clip(binx - 1, 0, nw - 1)
    biny = np.clip(biny - 1, 0, nh - 1)

    bin = biny * nw + binx

    plt.clf()

    for i in range(nh):
        for j in range(nw):
            thisbin = i * nw + j
            R = (bin == thisbin)
            # print 'cell %i, %i' % (j, i)
            # print '%i ref sources' % sum(R)
            if sum(R) == 0:
                continue
            (inds, dists) = spherematch.match(rxy[R, :], ixy, radius)
            # print 'Found %i matches within %g pixels' % (len(dists), radius)
            ri = inds[:, 0]
            # un-cut ref inds...
            ri = (np.flatnonzero(R))[ri]
            ii = inds[:, 1]

            matchx = rx[ri]
            matchy = ry[ri]
            matchdx = ix[ii] - matchx
            matchdy = iy[ii] - matchy
            ok = (matchdx >= -dcell) * (matchdx <= dcell) * (
                matchdy >= -dcell) * (matchdy <= dcell)
            # matchx = matchx[ok]
            # matchy = matchy[ok]
            matchdx = matchdx[ok]
            matchdy = matchdy[ok]
            # print 'Cut to %i within %g x %g square' % (sum(ok), dcell*2, dcell*2)

            # Subplot places plots left-to-right, TOP-to-BOTTOM.
            plt.subplot(nh, nw, 1 + ((nh - i - 1) * nw + j))

            plt.plot(matchdx, matchdy, 'ro', mec='r', mfc='r', ms=5, alpha=0.2)
            plt.plot(matchdx,
                     matchdy,
                     'ro',
                     mec='r',
                     mfc='none',
                     ms=5,
                     alpha=0.2)
            plt.axhline(0, color='k', alpha=0.5)
            plt.axvline(0, color='k', alpha=0.5)
            plt.xticks([], [])
            plt.yticks([], [])
            plt.axis('scaled')
            plt.axis([-dcell, dcell, -dcell, dcell])

    fn = prefix + '-missed.png'
    print('Saving', fn)
    plt.savefig(fn)
Пример #36
0
def contourTri(chain, **kwargs):
    """
    #Given a chain, labels and a list of which parameters to plot, plots the contours
    # Arguments:
    # chain=an array of the chain (not using weights, i.e. each row counts only once)
    # p= a list of integers: the two parameters you want to plot (refers to two columns in the chain)
    #kwargs:        labels= the labels of the parameters (list of strings)
    #               col=a tuple of the two colours for the contour plot
    #               line=boolean whether or not to just do a line contour plot
    #               outfile='triangle.png'
    #               binsize=50
    #               reconstruct=boolean whether or not to plot reconstruction
    #               autoscale=boolean whether or not to autoscale axes
    #               ranges=dictionary of plot range lists, labelled by
    #                      parameter name, e.g. {'A':[0.0,1.0],etc.}
    #               title=outdir
    p is now ignored
    """

    # Collate the contour-region info
    bundle = chain

    TRUNCATE_C = False
    TRUNCATE_C_LIMIT = 2.0  #1.0e4
    C_COL = 4  #0
    FONTSIZE = 4
    ROTATION = 60.0
    FIGSIZE = (8.27, 11.69)
    DPI = 400
    AXIS_LABEL_OFFSET = -0.9

    # !!!! BEWARE THE BINSIZE --- PLOT IS A STRONG FUNCTION OF THIS
    if 'binsize' in kwargs:
        binsize = kwargs['binsize']
    else:
        binsize = 50
    print('Using binsize = %i' % binsize)

    if 'labels' in kwargs:
        labels = kwargs['labels']
        parameters = labels  # How did this ever work without??
    else:
        labels = ['x', 'y']

    if 'ranges' in kwargs:
        ranges = kwargs['ranges']
    else:
        ranges = None

    if 'title' in kwargs:
        title = kwargs['title']
    else:
        title = ''

    if 'autoscale' in kwargs:
        autoscale = kwargs['autoscale']
    else:
        autoscale = True

    p = range(len(labels))
    pairs = trianglePairs(p)
    nparams = len(p)

    # Start setting up the plot
    ipanel = 0
    ax = {}
    pylab.clf()
    for panel in pairs:
        ipanel += 1
        H, xedges, yedges = numpy.histogram2d(chain[:, panel[0]],
                                              chain[:, panel[1]],
                                              bins=(binsize, binsize))

        x = []
        y = []
        z = []
        for i in range(len(xedges[:-1])):
            for j in range(len(yedges[:-1])):
                x.append(xedges[:-1][i])
                y.append(yedges[:-1][j])
                z.append(H[i, j])

        SMOOTH = False
        if SMOOTH:
            sz = 50
            smth = 80e6
            spl = interpolate.bisplrep(x, y, z, s=smth)
            X = numpy.linspace(min(xedges[:-1]), max(xedges[:-1]), sz)
            Y = numpy.linspace(min(yedges[:-1]), max(yedges[:-1]), sz)
            Z = interpolate.bisplev(X, Y, spl)
        else:
            X = xedges[:-1]
            Y = yedges[:-1]
            Z = H

        #I think this is the weird thing I have to do to make the contours work properly
        X1 = numpy.zeros([len(X), len(X)])
        Y1 = numpy.zeros([len(X), len(X)])
        for i in range(len(X)):
            X1[:, i] = X
            Y1[i, :] = Y
        X = X1
        Y = Y1

        N100, N95, N68 = find_confidence(Z)

        if 'col' in kwargs:
            col = kwargs['col']
        else:
            col = ('#a3c0f6', '#0057f6')  #A pretty blue

        # Now construct the subplot
        ax[ipanel] = pylab.subplot2grid((nparams, nparams),
                                        panel[::-1])  # Reverse quadrant

        if 'line' in kwargs and kwargs['line'] == True:
            CS = pylab.contour(X,
                               Y,
                               Z,
                               levels=[N95, N68, N100],
                               colors=col,
                               linewidth=100)
        else:
            CS = pylab.contourf(X, Y, Z, levels=[N95, N68, N100], colors=col)

        # Identify points lying within 68 percent contour region
        #print ipanel,bundle.shape,chain.shape
        #v=CS.collections[0].get_paths()[0].vertices
        #w=CS.collections[1].get_paths()[0].vertices
        #print v[:,0]
        #print v[:,1]
        #b=bundle[:,[panel[0],panel[1]]]
        #mask=Path(v).contains_points(b)
        #mask2=Path(w).contains_points(b)
        #print panel[0],panel[1],b[:,0].size,b[:,0][mask].size,b[:,0][mask2].size,labels[panel[0]],labels[panel[1]]

        if 'truth' in kwargs and kwargs['truth'] is not None:
            truth = kwargs['truth']
            pylab.plot(truth[labels[panel[0]]], truth[labels[panel[1]]], 'r+', \
                       markersize=20)

        if 'labelDict' in kwargs and kwargs['labelDict'] is not None:
            labelDict = kwargs['labelDict']
        else:
            labelDict = dict((name, name) for name in parameters)

        # Set the axis labels only for left and bottom:
        #print ax[ipanel].get_xlabel(),ax[ipanel].get_ylabel()
        if panel[1] == (nparams - 1):
            ax[ipanel].set_xlabel(labelDict[labels[panel[0]]], fontsize=6)
            ax[ipanel].xaxis.set_label_coords(
                0.5, AXIS_LABEL_OFFSET)  # align axis labels
            x_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
            ax[ipanel].xaxis.set_major_formatter(x_formatter)
        else:
            ax[ipanel].set_xlabel('')
            ax[ipanel].get_xaxis().set_ticklabels([])
        if panel[0] == 0:
            ax[ipanel].set_ylabel(labelDict[labels[panel[1]]], fontsize=6)
            ax[ipanel].yaxis.set_label_coords(AXIS_LABEL_OFFSET,
                                              0.5)  # align axis labels
            y_formatter = matplotlib.ticker.ScalarFormatter(useOffset=False)
            ax[ipanel].yaxis.set_major_formatter(y_formatter)
        else:
            ax[ipanel].set_ylabel('')
            ax[ipanel].get_yaxis().set_ticklabels([])

        # Set plot limits
        if autoscale:
            # HACK FOR C ONLY:
            if TRUNCATE_C and panel[0] == C_COL:
                xxlo, xxhi = ax[ipanel].xaxis.get_data_interval()
                if xxhi > TRUNCATE_C_LIMIT:
                    pylab.xlim(xxlo, TRUNCATE_C_LIMIT)
                #ax[ipanel].set_xscale('log')
                autoscale = True
                #locs,labels = plt.xticks()
                #plt.xticks(locs, map(lambda x: "%g" % x, locs*1.0e5))
        else:
            xlo = ranges[labels[panel[0]]][0]
            xhi = ranges[labels[panel[0]]][1]
            ylo = ranges[labels[panel[1]]][0]
            yhi = ranges[labels[panel[1]]][1]
            pylab.xlim(xlo, xhi)
            pylab.ylim(ylo, yhi)

        # Some housekeeping
        pylab.xticks(fontsize=FONTSIZE, rotation=ROTATION)
        pylab.yticks(fontsize=FONTSIZE, rotation=0)

    # Set up the 1-D plots on the diagonal
    for iparam in range(nparams):
        #        b=numpy.histogram(R,bins=bins)
        J, edges = numpy.histogram(chain[:, iparam],
                                   density=True,
                                   bins=binsize)
        ax1d = pylab.subplot2grid((nparams, nparams), (iparam, iparam))
        pylab.plot(edges[:-1], J, color='k')
        #print iparam,nparams,labels[iparam]

        if 'truth' in kwargs and kwargs['truth'] is not None:
            truth = kwargs['truth']
            pylab.axvline(truth[parameters[iparam]], color='r')

        if iparam == 0:
            ax1d.set_ylabel(labelDict[labels[iparam]], fontsize=6)
            ax1d.yaxis.set_label_coords(AXIS_LABEL_OFFSET,
                                        0.5)  # align axis labels
        if iparam == (nparams - 1):
            ax1d.set_xlabel(labelDict[labels[iparam]], fontsize=6)
            ax1d.xaxis.set_label_coords(0.5,
                                        AXIS_LABEL_OFFSET)  # align axis labels

        # Set plot limits
        #parameters=['x', 'y', 'S', 'sig', 'Q', 'el', 'em', 'R']
        if autoscale:
            # HACK FOR C ONLY:
            if TRUNCATE_C and iparam == C_COL:
                xxlo, xxhi = ax1d.xaxis.get_data_interval()
                if xxhi > TRUNCATE_C_LIMIT:
                    pylab.xlim(xxlo, TRUNCATE_C_LIMIT)
                #ax1d.set_xscale('log')
                autoscale = True
        if not autoscale:
            xlo, xhi = ranges[parameters[iparam]]
            pylab.xlim(xlo, xhi)
        if iparam < (nparams - 1):
            ax1d.get_xaxis().set_ticklabels([])
        ax1d.get_yaxis().set_ticklabels([])
        pylab.xticks(fontsize=FONTSIZE, rotation=ROTATION)
        pylab.yticks(fontsize=FONTSIZE)
        #if iparam == 0: ax1d.set_xscale('log')
    #ax1d.set_xscale('linear')

    #axinfo=pylab.subplot2grid((nparams,nparams),(0,nparams-3))
    axinfo = pylab.subplot2grid((nparams, nparams),
                                (0, nparams - nparams % 2 - 1))
    axinfo.get_xaxis().set_visible(False)
    axinfo.get_yaxis().set_visible(False)
    pylab.axis('off')
    pylab.title(title)

    # Plot the truth - this needs to be generalized for non-lumfunc
    if 'truth' in kwargs and kwargs['truth'] is not None:
        truth = kwargs['truth']
        note = ['nparams %i\n truth:' % nparams]
        for k, v in truth.items():
            notelet = '%s = %4.2f' % (k, v)
            note.append(notelet)
        pylab.text(0, 0, '\n'.join(note))

        if 'reconstruct' in kwargs:
            reconstruct = kwargs['reconstruct']
            axrecon = pylab.subplot2grid((nparams, nparams), (0, nparams - 2), \
                                         rowspan=2, colspan=2)
            axrecon.set_xscale('log')
            axrecon.set_yscale('log')
            pylab.xticks(fontsize=FONTSIZE, rotation=60)
            pylab.yticks(fontsize=FONTSIZE)
            median_bins = medianArray(reconstruct[0])
            dnds = calculateDnByDs(median_bins, reconstruct[1])
            dndsN = calculateDnByDs(median_bins, ksNoisy)
            print(median_bins)
            print(dnds)
            print(truth.items())
            recon = numpy.zeros(numpy.shape(median_bins))
            post = numpy.zeros(numpy.shape(median_bins))
            print(
                '# i Smedian ks dnds dndsS2.5 NRecon dndsRecon dndsS2.5Recon log10dnds log10dndsR diffR dndsN'
            )
            if nparams == 4:
                (C, alpha, Smin, Smax) \
                    = (truth['C'], truth['alpha'], truth['Smin'], truth['Smax'])
                area = 10.0  # Hack
                # Reconstruct powerLaw points given truth
                for i in range(len(median_bins)):
                    recon[i] = powerLawFuncS(median_bins[i], \
                                             C, alpha, Smin, Smax, area)
                    post[i] = powerLawFuncS(median_bins[i], \
                                            9.8, -0.63, 0.04, 14.1, area)
                #recon *= lumfunc.ksRaw
                #dndsR=lumfunc.calculateDnByDs(median_bins,recon)
                # **** XXXX Where does the 1000 come from!? :(( XXXX
                dndsR = recon * 1000.0
                dndsP = post * 1000.0
                # cols: i Smedian ks dnds dndsS2.5 NRecon dndsRecon
                # dndsS2.5Recon log10dnds log10dndsR diffR dndsN
                for i in range(len(median_bins)):
                    print('%i %f %i %i %i %i %i %i %f %f %i %i' % (i, median_bins[i], \
                                                                   reconstruct[-1][i], dnds[i], \
                                                                   dnds[i] * median_bins[i] ** 2.5, recon[i], dndsR[i], \
                                                                   dndsR[i] * median_bins[i] ** 2.5,
                                                                   numpy.log10(dnds[i]), \
                                                                   numpy.log10(dndsR[i]), int(dndsR[i] - dnds[i]),
                                                                   dndsN[i]))

                    #print recon
            pylab.xlim(reconstruct[0][0], reconstruct[0][-1])
            #pylab.ylim(1.0e2,1.0e8)

            #pylab.plot(median_bins,dnds*numpy.power(median_bins,2.5)*lumfunc.sqDeg2sr,'+')
            power = 2.5
            pylab.plot(median_bins,
                       dnds * sqDeg2sr * numpy.power(median_bins, power), '+')
            pylab.plot(median_bins,
                       dndsR * sqDeg2sr * numpy.power(median_bins, power), '-')
            pylab.plot(median_bins,
                       dndsN * sqDeg2sr * numpy.power(median_bins, power), '+')
            pylab.plot(median_bins,
                       dndsP * sqDeg2sr * numpy.power(median_bins, power), '-')
            #pylab.plot(dnds,dndsR*numpy.power(median_bins,1.0))
            #b=lumfunc.simtable(lumfunc.bins,a=-1.5,seed=1234,noise=10.0,dump=False)

    if 'outfile' in kwargs:
        outfile = kwargs['outfile']

        if not os.path.exists(os.path.split(outfile)[0]):
            os.mkdir(os.path.split(outfile)[0])

        pylab.savefig(outfile, figsize=FIGSIZE, dpi=DPI)
        print('Run: open %s' % outfile)
        #pylab.close()
    else:
        pylab.show()

    return bundle
Пример #37
0
# testing ############################################################################################
if __name__ == '__main__':
    prob = 0

    if prob == 0:
        x = linspace(0, 10, 100)
        y = x**1.5
        plot(x, y, 'b-', label='sim')
        ver = int(sys.version[0])
        if ver < 3:
            Arc(0, 0, 10)
            Arc(0, 0, 20, clr='magenta')
        Arrow(-10, 0, max(x), max(y))
        Text(0, 25, r'$\sigma$')
        Text(0, 25, r'$\sigma$', y_offset=-10)
        axvline(0, color='black', zorder=-1)
        axhline(0, color='black', zorder=-1)
        FigGrid()
        axis('equal')
        legend(loc='upper left')
        xlabel(r'$x$')
        ylabel(r'$y$')
        show()

    if prob == 1:
        ITout = get_itout(
            [0., 0.1, 0.15, 0.2, 0.23, 0.23, 0.23, 0.3, 0.8, 0.99],
            [0., 0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 1.])
        print(ITout)

    if prob == 2:
Пример #38
0
def PlotChains(conv_length,
               p=None,
               n_chains=None,
               chain_filenames=None,
               saveplot=False,
               filename="ChainPlot.pdf",
               labels=None):
    """
  Plot the MCMC chains. Can be very slow for long chains, should probably add a range.
  
  """

    #get chain names tuple
    if n_chains == None and chain_filenames == None:
        chain_filenames = ("MCMC_chain", )
    if n_chains != None:
        chain_filenames = ["MCMC_chain_%d" % i for i in range(1, n_chains + 1)]
    if type(chain_filenames) is str:
        chain_filenames = [
            chain_filenames,
        ]

    if p == None:  #get total number of parmaeters if not supplued
        #no_pars = len(open(chain_filenames[0],'r').readline().split())-1
        no_pars = np.load(chain_filenames[0] + '.npy')[0].size - 1
        p = range(no_pars)
    else:
        no_pars = len(p)

    if labels == None:  #create labels for plots if not provided
        labels = ['p[%d]' % p[q] for q in range(no_pars)]

#  pylab.figure(len(pylab.get_fignums())+1,(9,no_pars*2)) #new figure
#  pylab.clf() #clear figure

    for i, file in enumerate(chain_filenames):

        #loop over the parameters
        for q in range(no_pars):

            Data = np.load(file +
                           '.npy')[:,
                                   p[q]]  #read in data - data is stored in q+1

            #create axes 1 and plot chain
            #axes [x(left),y(lower),width,height]
            pylab.axes([
                0.1, 1. - (q + 1 - 0.15) * (1. / no_pars), 0.6,
                (1. / no_pars) * 0.75
            ])
            pylab.plot(Data, '-')
            pylab.axvline(conv_length, color='r', linestyle='--')
            pylab.ylabel(labels[q])
            if (q + 1) == no_pars: pylab.xlabel("N")

            #create axes 2 and plot histogram
            pylab.axes([
                0.75, 1. - (q + 1 - 0.15) * (1. / no_pars), 0.2,
                (1. / no_pars) * 0.75
            ])
            pylab.hist(Data[conv_length:], 20, histtype='step')
            pylab.xticks([])
            pylab.yticks([])

    if saveplot:  #save the plots
        print "Saving chain plots..."
        pylab.savefig(filename)
Пример #39
0
phonon.set_band_structure(bands)
phonon.plot_band_structure(dir_labels)
ylim(0, 20.)

# save results to file band.yaml
bs = BandStructure(bands,
                   phonon.dynamical_matrix,
                   phonon.primitive,
                   factor=VaspToTHz)

if write_yaml:
    bs.write_yaml()

# add vertical lines to plot
for p in bs.special_point:
    axvline(p, color='k')

# Example showing how to load previously saved results
if read_yaml:
    special_points, distances, frequencies = band_plot_from_file(
        gca(), 'band.yaml')

    # set x axis labels
    sp = special_points[:]
    for p in sp:
        axvline(p, color='k')
    xticks(sp, dir_labels)

    # plot SW
    for freqs in np.array(frequencies).transpose():
        plot(distances, freqs, 'k-', label='SW')
import numpy as np
import pylab as plt
plt.ion()


root = 'bastien_v0'

plt.figure()
x, y = np.loadtxt(root+'_two_sigma', unpack=1)
plt.fill(x, y, color='C0', alpha=0.3)
x, y = np.loadtxt(root+'_one_sigma', unpack=1)
plt.fill(x, y, color='C0', alpha=1)
plt.xlabel(r'$f\sigma_8$', fontsize=16)
plt.ylabel(r'$\sigma_v$ [km/s]', fontsize=16)
plt.xlim(0.3, 0.6)
plt.ylim(150, 300)
plt.axvline(0.4505, color='k', ls='--')
plt.tight_layout()
Пример #41
0
    # Set the params of the hmm
    cmrf1 = CMRF(hmm1)
    cmrf2 = CMRF(hmm2)
    feat = 'HHHHHHHHHHHH'

    # Plot the entire sequence space
    ll_list1, ll_list2 = [], []
    for seq in product('ab', repeat=12):
        ll_list1.append(cmrf1.score(seq, feat))
        ll_list2.append(cmrf2.score(seq, feat))
    ll_list3, ll_list4 = [], []
    for seq in b.kseqlist:
        ll_list3.append(cmrf1.score(seq, feat))
        ll_list4.append(cmrf2.score(seq, feat))

    pl.figure()
    pl.plot(ll_list1, ll_list2, 'b*')
    pl.plot(ll_list3, ll_list4, 'r*')

    pl.xlabel('Energy1:')
    pl.ylabel('Energy2:')
    pl.title('Energy Plot')
    xmin, xmax = pl.xlim()
    ymin, ymax = pl.ylim()
    pl.xlim(-2, xmax)
    pl.ylim(-2, ymax)
    pl.axvline()
    pl.axhline()
    pl.savefig('../docs/tex/pics/sim4_nosmooth_3.png')
    pl.show()
Пример #42
0
        runsum += temp
        k += 1

    netsnr = (runsum)**0.5

# Write Network SNR data to H5 file
with h5py.File(params.statfile, 'a') as hf:
    ds = hf.create_dataset('net_snr/'+params.dsname, data=netsnr)
    ds.attrs['q'] = q
    ds.attrs['mchirp'] = mchirp

# Generate plot

plotname = cwd + '/' + plotsout[0]
pylab.plot([],[], ' ', label="Network SNR: {}".format(round(netsnr,3)))
pylab.axvline(params.tc, color='k', linestyle='--')
pylab.axhline(params.threshold, color='r', linestyle=':')

pylab.legend(loc=1)
pylab.title(params.title)
pylab.grid()
pylab.tight_layout()
pylab.savefig(plotname, dpi=400)


coinc = SingleCoincForGraceDB(trig_ifos, results, psds=psds, low_frequency_cutoff=20, followup_data=followup_data)

xmlname = params.xml

coinc.save(xmlname)
Пример #43
0
def jointSolve(d, orders):
    import pylab
    path = __path__[0]

    lines = {}
    lines['cuar'] = numpy.loadtxt(path + "/data/cuar.lines")
    lines['hgne'] = numpy.loadtxt(path + "/data/hgne.lines")
    lines['xe'] = numpy.loadtxt(path + "/data/xe.lines")

    startsoln = numpy.load(path + "/data/esi_wavesolution.dat")
    startsoln = numpy.load(path + '/data/shao_wave.dat')
    startsoln = [i for i, j in startsoln]
    alldata = d['arc']
    arclist = d.keys()
    arclist.remove('arc')
    soln = []
    if alldata.shape[1] > 3000:
        xvals = numpy.arange(4096.)
        resolve = False
        cuslice = slice(3860, 3940)
        fw1 = 75.
        fw2 = 9
        WIDTH = 4
    else:
        xvals = numpy.arange(2048.)
        resolve = True
        cuslice = slice(1930, 1970)
        fw1 = 37.
        fw2 = 7
        WIDTH = 3
    for i in range(10):
        solution = startsoln[i]
        start, end = orders[i]
        if resolve == True:
            tmp = numpy.arange(0.5, 4096., 2.)
            w = sf.genfunc(tmp, 0., solution)
            solution = sf.lsqfit(numpy.array([xvals, w]).T, 'chebyshev', 3)

        data = numpy.nanmedian(alldata[start:end], axis=0)
        data[numpy.isnan(data)] = 0.
        if i == 0:
            data[cuslice] = numpy.median(data)
        bak = ndimage.percentile_filter(data, 50., int(fw1))
        data -= bak

        peaks = []
        p = ndimage.maximum_filter(data, fw2)
        std = clip(numpy.trim_zeros(data), 3.)[1]
        peak = numpy.where((p > 30. * std) & (p == data))[0]
        for p in peak:
            if p - WIDTH < 0 or p + WIDTH + 1 > xvals.size:
                continue
            x = xvals[p - WIDTH:p + WIDTH + 1].copy()
            f = data[p - WIDTH:p + WIDTH + 1].copy()
            fitdata = numpy.array([x, f]).T
            fit = numpy.array([0., f.max(), xvals[p], 1.])
            fit, chi = sf.ngaussfit(fitdata, fit, weight=1)
            peaks.append(fit[2])

        for converge in range(10):
            wave = 10**sf.genfunc(xvals, 0., solution)

            refit = []
            corr = []
            err = wave[wave.size / 2] - wave[wave.size / 2 - 1]
            p = 10.**sf.genfunc(peaks, 0., solution)
            for arc in arclist:
                for k in range(p.size):
                    if i == 0 and p[k] > 4344.:
                        continue
                    cent = p[k]
                    diff = cent - lines[arc]
                    corr.append(diff[abs(diff).argmin()])
            corr = numpy.array(corr)
            corr = corr[abs(corr) < 5 * err]
            m, s = clip(corr)
            corr = numpy.median(corr[abs(corr - m) < 5. * s])
            for arc in arclist:
                for k in range(p.size):
                    if i == 0 and p[k] > 4344.:
                        continue
                    pos = peaks[k]
                    cent = p[k]
                    diff = abs(cent - lines[arc] - corr)
                    if diff.min() < 2. * err:
                        refit.append([pos, lines[arc][diff.argmin()]])
            refit = numpy.asarray(refit)
            solution = sf.lsqfit(refit, 'polynomial', 3)
            refit = []
            err = solution['coeff'][1]
            p = sf.genfunc(peaks, 0., solution)
            for k in range(p.size):
                delta = 1e9
                match = None
                for arc in arclist:
                    for j in lines[arc]:
                        if i == 0 and j > 4344.:
                            continue
                        diff = abs(p[k] - j)
                        if diff < delta and diff < 1. * err:
                            delta = diff
                            match = j
                if match is not None:
                    refit.append([peaks[k], match])
            refit = numpy.asarray(refit)
            refit[:, 1] = numpy.log10(refit[:, 1])
            solution = sf.lsqfit(refit, 'chebyshev', 3)

            solution2 = sf.lsqfit(refit[:, ::-1], 'chebyshev', 3)

            g = 10**sf.genfunc(peaks, 0., solution)
            g2 = 10**sf.genfunc(peak, 0., solution)
            w = 10**sf.genfunc(xvals, 0., solution)
            if (w == wave).all():
                print("Order %d converged in %d iterations" % (i, converge))
                soln.append([solution, solution2])
                break
                pylab.plot(w, data)
                for arc in arclist:
                    for j in lines[arc]:
                        if j > w[0] and j < w[-1]:
                            pylab.axvline(j, c='b')
                for j in 10**refit[:, 1]:
                    if j > w[0] and j < w[-1]:
                        pylab.axvline(j, c='r')
                for j in g:
                    pylab.axvline(j, c='g')
                for j in g2:
                    pylab.axvline(j, c='c')
                pylab.show()
                break

    return soln
Пример #44
0
# Prepare axis
ax = fig.gca()
ax.grid(color='k', linestyle=':', linewidth=0.2)
ax.yaxis.grid(True)
ax.xaxis.grid(False)

# Separate the different classes of models
height = 102
background_alpha = 0.15
x1 = 8 * dist_bars + (dist_bars - bar_width) / 2.0 - 1.0
x2 = 10 * dist_bars + (dist_bars - bar_width) / 2.0 - 1.0
x3 = 12 * dist_bars + (dist_bars - bar_width) / 2.0 - 1.0
x4 = 16 * dist_bars + (dist_bars - bar_width) / 2.0 - 1.0
x5 = 18 * dist_bars + (dist_bars - bar_width) / 2.0 - 1.0
linewidth = 2
pl.axvline(x1, ymin=0, ymax=1.07, color='k', clip_on=False, lw=linewidth)
pl.axvline(x2, ymin=0, ymax=1.07, color='k', clip_on=False, lw=linewidth)
pl.axvline(x3, ymin=0, ymax=1.07, color='k', clip_on=False, lw=linewidth)
pl.axvline(x4, ymin=0, ymax=1.07, color='k', clip_on=False, lw=linewidth)
ax.text(x1 / 2.0, 103, "R-IL", ha='center', fontsize=8)
ax.text((x2 - x1) / 2. + x1, 103, "R-IL$_{200}$", ha='center', fontsize=8)
ax.text((x3 - x2) / 2. + x2, 103, "pure IL", ha='center', fontsize=8)
ax.text((x4 - x3) / 2. + x3, 103, "pure RL", ha='center', fontsize=8)
ax.text((x5 - x4) / 2. + x4, 103, "comp.", ha='center', fontsize=8)

# patch1 = pl.matplotlib.patches.Rectangle([x1,0], width=x2-x1, height=height, facecolor='c', alpha=background_alpha, edgecolor=None, linewidth=0)
# ax.add_artist(patch1)
# patch2 = pl.matplotlib.patches.Rectangle([x2,0], width=10, height=height, facecolor='m', alpha=background_alpha, edgecolor=None, linewidth=0)
# ax.add_artist(patch2)

success_matrix = convert_to_float(success_fract.as_matrix())
Пример #45
0
    def plot_pdos(self, elements=None, title='PDOS', ext='eps', xlim=[-10, 5]):
        """
        Plot projected density of states
        """

        dos_columns, total_dos = self.get_total_dos()

        ix = dos_columns.index('Energy (E-Ef)')
        iy = dos_columns.index('Total DOS Spin Up')

        energy = total_dos[:, ix]
        idx1 = np.min(np.argwhere(energy >= xlim[0]))
        idx2 = np.max(np.argwhere(energy <= xlim[1]))
        total_dos = total_dos[idx1:idx2]
        energy = total_dos[:, ix]
        dos = total_dos[:, iy]

        if self.ispin == 2:
            iyd = dos_columns.index('Total DOS Spin Down')
            dos_down = -total_dos[:, iyd]

        pdos_columns, pdos_data = self.get_pdos()
        for k in pdos_data.keys():
            pdos_data[k] = pdos_data[k][idx1:idx2]
        symbols = self.atoms.get_chemical_symbols()
        all_elements = list(set(symbols))
        if not elements:
            elements = {}
            for e in all_elements:
                elements.update({e: "all"})

        color_dict = {'Oall': "red", 'H': "grey", 'N': "blue", 'S': 'yellow'}
        colors = [
            'seagreen', 'orange', 'skyblue', 'pink', 'magenta', 'indigo',
            'coral'
        ]
        j = 0
        for e, orb in elements.items():
            for o in orb:
                if e + o not in color_dict:
                    color_dict.update({e + o: colors[j]})
                    j += 1
        print(color_dict)
        # Plots
        fig = plt.figure(figsize=(10.0, 6.0))  # Create figure.

        plt.plot(energy, dos, color='black',
                 label='Total DOS')  # Plot DOS spin up.

        if self.ispin == 2:
            plt.plot(energy, dos_down, label='',
                     color='black')  # Plot DOS spin down.

        for e, orbitals in elements.items():
            if e[-1].isdigit():
                idx = [i for i in range(len(e)) if e[i].isdigit()][0]

                atom_indices = [int(e[idx:])]
                print(atom_indices)
            else:
                atom_indices = [i for i, s in enumerate(symbols) if s == e]

            if not isinstance(orbitals, list):
                orbitals = [orbitals]

            for orbital_plot in orbitals:
                if orbital_plot == 'all':
                    orb_indices_up = [
                        i for i, p in enumerate(pdos_columns) if p[-2:] == 'up'
                    ]
                    orb_indices_down = [
                        i for i, p in enumerate(pdos_columns)
                        if p[-4:] == 'down'
                    ]
                else:
                    if orbital_plot in ['s', 'p', 'd', 'f', 't2g', 'eg']:
                        orbitals = self.expand_orbitals(orbital_plot)
                    else:
                        orbitals = [orbital_plot]

                    orbitals_up = [o + '_up' for o in orbitals]
                    orbitals_down = [o + '_down' for o in orbitals]
                    orb_indices_up = [
                        io for io, o in enumerate(pdos_columns)
                        if o in orbitals_up
                    ]
                    orb_indices_down = [
                        io for io, o in enumerate(pdos_columns)
                        if o in orbitals_down
                    ]

                pdos_up = 0
                pdos_down = 0
                for i in atom_indices:
                    pdos_up += np.sum(pdos_data[i][:, orb_indices_up], axis=1)
                    pdos_down += np.sum(pdos_data[i][:, orb_indices_down],
                                        axis=1)

                color = color_dict[e + orbital_plot]
                extra_label = ''

                s_labels = ['up', 'down']
                labels = [None, None]
                sgn = 1
                for i, pdos_i in enumerate([pdos_up, pdos_down]):
                    s_label = s_labels[i]
                    if len(pdos_i) == 0:
                        continue
                    if i == 0:
                        label = '{}({})'.format(e, orbital_plot)
                    else:
                        label = None
                    plt.plot(energy, pdos_i, color=color, label=label)

        plt.axvline(x=[0.0], color='k', linestyle='--', linewidth=1.2)

        plt.xlabel('(E - E$_F$) [eV]')  # x axis label.
        plt.ylabel('(P)DOS [states eV$^{-1}$]')  # x axis label.
        plt.legend()
        plt.title(title)
        plt.show()

        fig.savefig('PDOS.eps')  # {}.{}'.format(title, ext))
Пример #46
0
def solve(d, orders):
    path = os.path.split(__file__)[0]

    lines = {}
    lines['cuar'] = numpy.loadtxt(path + "/data/cuar.lines")
    lines['hgne'] = numpy.loadtxt(path + "/data/hgne.lines")
    lines['xe'] = numpy.loadtxt(path + "/data/xe.lines")

    if pyversion == 2:
        startsoln = numpy.load(path + "/data/esi_wavesoln_py27.dat",
                               allow_pickle=True)
    else:
        startsoln = numpy.load(path + "/data/esi_wavesoln_py3.dat",
                               allow_pickle=True)

    #arclist = d.keys() # Under python 3 this does not produce a list
    #                        and so arclist[0] below fails
    arclist = list(d)
    arclist.sort()
    soln = []
    if d[arclist[0]].shape[1] > 3000:
        xvals = numpy.arange(4096.)
        cuslice = slice(3860, 3940)
        fw1 = 75.
        fw2 = 9
    else:
        xvals = numpy.arange(1., 4096., 2.)
        cuslice = slice(1930, 1970)
        fw1 = 37.
        fw2 = 5
    """
    Do a temporary kludge.  In some cases, the finding of the orders
    fails, and only 9 orders are found.  In this case, we need to skip
    the first of the orders
    """
    if len(orders) == 9:
        ordstart = 1
        dord = 1
    else:
        ordstart = 0
        dord = 0
    for i in range(ordstart, 10):
        solution = startsoln[i]
        start, end = orders[(i - dord)]

        peaks = {}
        trace = {}
        fitD = {}
        WIDTH = 4
        import pylab
        for arc in arclist:
            data = numpy.nanmedian(d[arc][start:end], axis=0)
            data[scipy.isnan(data)] = 0.
            if i == 0 and arc == 'cuar':
                data[cuslice] = numpy.median(data)
            trace[arc] = data.copy()
            bak = ndimage.percentile_filter(data, 50., int(fw1))
            bak = getContinuum(bak, 40.)
            data -= bak
            fitD[arc] = data / d[arc][start:end].std(0)
            p = ndimage.maximum_filter(data, fw2)
            std = clip(scipy.trim_zeros(data), 3.)[1]
            nsig = ndimage.uniform_filter((data > 7. * std) * 1., 3)
            peak = scipy.where((nsig == 1) & (p > 10. * std) & (p == data))[0]
            peaks[arc] = []
            for p in peak:
                if p - WIDTH < 0 or p + WIDTH + 1 > xvals.size:
                    continue
                x = xvals[p - WIDTH:p + WIDTH + 1].copy()  #-xvals[p]
                f = data[p - WIDTH:p + WIDTH + 1].copy()
                fitdata = scipy.array([x, f]).T
                fit = scipy.array([0., f.max(), xvals[p], 1.])
                fit, chi = sf.ngaussfit(fitdata, fit, weight=1)
                peaks[arc].append(fit[2])  #+xvals[p])
        for converge in range(15):
            wave = 10**sf.genfunc(xvals, 0., solution)

            refit = []
            corrA = {}
            err = wave[int(wave.size / 2)] - wave[int(wave.size / 2 - 1)]
            for arc in arclist:
                corr = []
                p = 10.**sf.genfunc(peaks[arc], 0., solution)
                for k in range(p.size):
                    cent = p[k]
                    diff = cent - lines[arc]
                    corr.append(diff[abs(diff).argmin()])
                corr = numpy.array(corr)
                if corr.size < 4:
                    continue
                m, s = clip(corr)
                corr = numpy.median(corr[abs(corr - m) < 5. * s])
                print(corr)
                corrA[arc] = corr
                #        corr = m

                #for arc in arclist:
                p = 10.**sf.genfunc(peaks[arc], 0., solution)
                for k in range(p.size):
                    pos = peaks[arc][k]
                    cent = p[k]
                    diff = abs(cent - lines[arc] - corr)
                    if diff.min() < 2. * err:
                        refit.append([pos, lines[arc][diff.argmin()]])
            refit = scipy.asarray(refit)
            solution = sf.lsqfit(refit, 'polynomial', 3)
            refit = []
            err = solution['coeff'][1]
            for arc in arclist:
                data = trace[arc]
                for pos in peaks[arc]:
                    cent = sf.genfunc(pos, 0., solution)
                    delta = 1e9
                    match = None
                    for j in lines[arc]:
                        diff = abs(cent - j)
                        if diff < delta and diff < 1. * err:
                            delta = diff
                            match = j
                    if match is not None:
                        refit.append([pos, match])
            refit = scipy.asarray(refit)
            refit[:, 1] = numpy.log10(refit[:, 1])
            solution = sf.lsqfit(refit, 'chebyshev', 3)

            #refit[:,0],refit[:,1] = refit[:,1].copy(),refit[:,0].copy()
            #refit = numpy.array([refit[:,1],refit[:,0]]).T
            #refit = refit[:,::-1]
            solution2 = sf.lsqfit(refit[:, ::-1], 'chebyshev', 3)
            #soln.append([solution,solution2])

            w = 10**sf.genfunc(xvals, 0., solution)
            if (w == wave).all() or converge > 8:
                print("Order %d converged in %d iterations" % (i, converge))
                soln.append([solution, solution2])
                break
                for arc in arclist:
                    pylab.plot(w, trace[arc])
                    pylab.plot(w, fitD[arc])
                    pp = 10**sf.genfunc(peaks[arc], 0., solution)
                    for p in pp:
                        pylab.axvline(p, c='k')
                for j in 10**refit[:, 1]:
                    if j > w[0] and j < w[-1]:
                        pylab.axvline(j)
                pylab.show()
                break
    return soln
#Wing.Airfoil = 'S1223_A'

LLT = ACLiftingLine(Wing)

y = npy.linspace(-Wing.b/2/IN, Wing.b/2/IN, 61)*IN

#LLT.nSpan = 101
LLT.Alpha3d = 5*ARCDEG

pyl.figure(4)
pyl.plot(y/IN, LLT.Cl(y))
pyl.grid(True)
pyl.ylim([1.0,1.6])
pyl.xlabel("y (in)")
pyl.ylabel("Cl")
pyl.axvline(x=Wing.Aileron.Tip()/IN)
pyl.axvline(x=Wing.Aileron.Root()/IN)


Fbs = npy.linspace(0.3, 0.6, 4)
TRs = npy.linspace(0.2, 0.6, 5)


LoD = {}
CL  = {}
e   = {}

for Fb in Fbs:
    LoD[Fb] = {}
    CL[Fb] = {}
    e[Fb] = {}
Пример #48
0
                                       vmin=density_min,
                                       vmax=density_max),
                cmap='bwr')
    pl.colorbar()
    pl.title(r'Time = ' + "%.2f" % (time_array[file_number]) + " ps")

    pl.streamplot(x[:, 0],
                  y[0, :],
                  vel_drift_x,
                  vel_drift_y,
                  density=2.,
                  color='k',
                  linewidth=0.7,
                  arrowsize=1)

    pl.axvline(4.25, ymin=0., ymax=0.33, color='k', ls='--', lw=3)
    pl.axvline(4.25, ymin=0.66, ymax=1.0, color='k', ls='--', lw=3)

    pl.axvline(1.73 / 2, color='k', ls='--')
    pl.axvline(1.73 + 1.73 / 2, color='k', ls='--')

    pl.xlim([q1[0], q1[-1]])
    pl.ylim([q2[0], q2[-1]])

    pl.gca().set_aspect('equal')
    pl.xlabel(r'$x\;(\mu \mathrm{m})$')
    pl.ylabel(r'$y\;(\mu \mathrm{m})$')
    pl.suptitle('$\\tau_\mathrm{mc} = \infty$, $\\tau_\mathrm{mr} = \infty$')
    pl.savefig('images/dump_' + '%06d' % file_number + '.png')
    pl.clf()
Пример #49
0
        # write out the segment list to a segwizard file
        tmpoutfile = idirectory + "/" + ifo + "_selectedsegs.txt"
        segmentsUtils.tosegwizard(file(tmpoutfile, 'w'), tmplist)

        # plot the segment lists
        if opts.plot_segments:
            pylab.figure()
            pylab.hold(True)
            y = pylab.asarray([0, 0])
            y = y + 0.1
            for seg in tmplist:
                pylab.plot(seg, y, 'b', linewidth=4)
            y = y + 0.1
            for seg in segdict[ifo]:
                pylab.plot(seg, y, 'k', linewidth=4)
            pylab.axvline(interval[0], color='g')
            pylab.axvline(interval[1], color='g')
            pylab.axvline(interval[0] - overlap / 2 - paddata, color='r')
            pylab.axvline(interval[1] + overlap / 2 + paddata, color='r')
            pylab.ylim([0.0, 0.5])
            pylab.xlim(
                [interval[0] - 2 * minsciseg, interval[1] + 2 * minsciseg])
            pylab.savefig(ifo + "-" + idirectory + ".png")

    # Next thing is to generate the dag for this interval of time.
    # The steps here are:
    #   1. make dir for zero-lag and playground
    #   2. copy in ini file (and modify if needed)
    #   3. generate dag
    #   4. make dir for injections and run inspinj
    #   5. repeat 2 & 3
Пример #50
0
def createPlots(subPlots=True,scatterSize=60,wider=False):
	global currLineRefs
	figs=set([l.line.get_axes().get_figure() for l in currLineRefs]) # get all current figures
	for f in figs: pylab.close(f) # close those
	currLineRefs=[] # remove older plots (breaks live updates of windows that are still open)
	if len(plots)==0: return # nothing to plot
	if subPlots:
		# compute number of rows and colums for plots we have
		subCols=int(round(math.sqrt(len(plots)))); subRows=int(math.ceil(len(plots)*1./subCols))
		if wider: subRows,subCols=subCols,subRows
	for nPlot,p in enumerate(plots.keys()):
		pStrip=p.strip().split('=',1)[0]
		if not subPlots: pylab.figure()
		else: pylab.subplot(subRows,subCols,nPlot+1)
		if plots[p]==None: # image plot
			if not pStrip in imgData.keys(): imgData[pStrip]=[]
			# fake (empty) image if no data yet
			if len(imgData[pStrip])==0 or imgData[pStrip][-1]==None: img=Image.new('RGBA',(1,1),(0,0,0,0))
			else: img=Image.open(imgData[pStrip][-1])
			img=pylab.imshow(img,origin='lower')
			currLineRefs.append(LineRef(img,None,None,imgData[pStrip],None,pStrip))
			pylab.gca().set_axis_off()
			continue
		plots_p=[addPointTypeSpecifier(o) for o in tuplifyYAxis(plots[p])]
		plots_p_y1,plots_p_y2=[],[]; y1=True
		missing=set() # missing data columns
		if pStrip not in data.keys(): missing.add(pStrip)
		for d in plots_p:
			if d[0]==None:
				y1=False; continue
			if y1: plots_p_y1.append(d)
			else: plots_p_y2.append(d)
			if d[0] not in data.keys() and not callable(d[0]) and not hasattr(d[0],'keys'): missing.add(d[0])
		if missing:
			if len(data.keys())==0 or len(data[data.keys()[0]])==0: # no data at all yet, do not add garbage NaNs
				for m in missing: data[m]=[]
			else:
				print 'Missing columns in plot.data, adding NaN: ',','.join(list(missing))
				addDataColumns(missing)
		def createLines(pStrip,ySpecs,isY1=True,y2Exists=False):
			'''Create data lines from specifications; this code is common for y1 and y2 axes;
			it handles y-data specified as callables, which might create additional lines when updated with liveUpdate.
			'''
			# save the original specifications; they will be smuggled into the axes object
			# the live updated will run yNameFuncs to see if there are new lines to be added
			# and will add them if necessary
			yNameFuncs=set([d[0] for d in ySpecs if callable(d[0])]) | set([d[0].keys for d in ySpecs if hasattr(d[0],'keys')])
			yNames=set()
			ySpecs2=[]
			for ys in ySpecs:
				# ys[0]() must return list of strings, which are added to ySpecs2; line specifier is synthesized by tuplifyYAxis and cannot be specified by the user
				if callable(ys[0]): ySpecs2+=[(ret,ys[1]) for ret in ys[0]()]
				elif hasattr(ys[0],'keys'): ySpecs2+=[(yy,'') for yy in ys[0].keys()]
				else: ySpecs2.append(ys)
			if len(ySpecs2)==0:
				print 'yade.plot: creating fake plot, since there are no y-data yet'
				line,=pylab.plot([nan],[nan])
				line2,=pylab.plot([nan],[nan])
				currLineRefs.append(LineRef(line,None,line2,[nan],[nan]))
			# set different color series for y1 and y2 so that they are recognizable
			if pylab.rcParams.has_key('axes.color_cycle'): pylab.rcParams['axes.color_cycle']='b,g,r,c,m,y,k' if not isY1 else 'm,y,k,b,g,r,c'
			for d in ySpecs2:
				yNames.add(d)
				line,=pylab.plot(data[pStrip],data[d[0]],d[1],label=xlateLabel(d[0]))
				line2,=pylab.plot([],[],d[1],color=line.get_color(),alpha=afterCurrentAlpha)
				# use (0,0) if there are no data yet
				scatterPt=[0,0] if len(data[pStrip])==0 else (data[pStrip][current],data[d[0]][current])
				# if current value is NaN, use zero instead
				scatter=pylab.scatter(scatterPt[0] if not math.isnan(scatterPt[0]) else 0,scatterPt[1] if not math.isnan(scatterPt[1]) else 0,s=scatterSize,color=line.get_color(),**scatterMarkerKw)
				currLineRefs.append(LineRef(line,scatter,line2,data[pStrip],data[d[0]]))
			axes=line.axes
			labelLoc=(legendLoc[0 if isY1 else 1] if y2Exists>0 else 'best')
			l=pylab.legend(loc=labelLoc)
			if hasattr(l,'draggable'): l.draggable(True)
			if scientific:
				pylab.ticklabel_format(style='sci',scilimits=(0,0),axis='both')
				# fixes scientific exponent placement for y2: https://sourceforge.net/mailarchive/forum.php?thread_name=20101223174750.GD28779%40ykcyc&forum_name=matplotlib-users
				if not isY1: axes.yaxis.set_offset_position('right')
			if isY1:
				pylab.ylabel((', '.join([xlateLabel(_p[0]) for _p in ySpecs2])) if p not in xylabels or not xylabels[p][1] else xylabels[p][1])
				pylab.xlabel(xlateLabel(pStrip) if (p not in xylabels or not xylabels[p][0]) else xylabels[p][0])
			else:
				pylab.ylabel((', '.join([xlateLabel(_p[0]) for _p in ySpecs2])) if (p not in xylabels or len(xylabels[p])<3 or not xylabels[p][2]) else xylabels[p][2])
			# if there are callable/dict ySpecs, save them inside the axes object, so that the live updater can use those
			if yNameFuncs:
				axes.yadeYNames,axes.yadeYFuncs,axes.yadeXName,axes.yadeLabelLoc=yNames,yNameFuncs,pStrip,labelLoc # prepend yade to avoid clashes
		createLines(pStrip,plots_p_y1,isY1=True,y2Exists=len(plots_p_y2)>0)
		if axesWd>0:
			pylab.axhline(linewidth=axesWd,color='k')
			pylab.axvline(linewidth=axesWd,color='k')
		# create y2 lines, if any
		if len(plots_p_y2)>0:
			pylab.twinx() # create the y2 axis
			createLines(pStrip,plots_p_y2,isY1=False,y2Exists=True)
		if 'title' in O.tags.keys(): pylab.title(O.tags['title'])
Пример #51
0
            y = torch.relu(self.fc3[i](y))
            y = torch.cat([y, z[i].unsqueeze(0)], 0)
            y = torch.relu(self.fc4[i](y))
            f = self.fc5[i](y)
            f_list.append(f)
        f_list = torch.cat(f_list, 0)
        return f_list


# Generate test z0 and x0
z0 = np.array([0.10, 0.50])
x0 = model(z0)
x_dim = len(x0)
z_dim = len(z0)

# Initialize loss list
losses = []

# And the first run
xz1 = swyft.init_xz(model, n_sims = n_sims, n_dim = z_dim)
network1 = Network(x_dim, z_dim, n_hidden, xz_init = xz1)
losses += swyft.train(network1, xz1, n_steps = n_steps, lr = 1e-3, n_particles = n_particles)
losses += swyft.train(network1, xz1, n_steps = n_steps, lr = 1e-4, n_particles = n_particles)

# Plot results
z_lnL = swyft.estimate_lnL(network1, x0, swyft.get_z(xz1))
plt.plot(z_lnL[0]['z'], np.exp(z_lnL[0]['lnL']))
plt.axvline(0.1)
plt.axvline(0.9)
plt.savefig("figs/testrun_04.png")
Пример #52
0
def lr_results(df,X_test,y_test,y_pred,path,fn,stats_list,mdlinst):
    df_results = df.loc[y_test.index, :]
    df_results['predOPS'] = y_pred
    df_results['error'] = 100 * ( ( df_results['OPS'] - df_results['predOPS'] ) / df_results['OPS'])
    df_results['abserror'] = np.abs(100 * ( ( df_results['OPS'] - df_results['predOPS'] ) / df_results['OPS']))
    #
    df_results['predOPS'] = df_results['predOPS']
    df_results['OPS'] = df_results['OPS']
    df_results['error'] = df_results['error']
    df_out = df_results[stats_list]
    save_stats_file(path,fn, df_out)
    #  calculate Rsquared, Adj Rsquared, MSE, RMSE and Fstatistic using my routine
    Rsquared, AdjRsquared, MSE, RMSE, Fstatistic, MeanOfError, StdOfError, AbsErrorSum = calc_regression_stats(X_test,y_test,y_pred)
    # print statistics
    print('R Squared: %1.4f' % Rsquared)
    print('Adjusted R Squared: %1.4f' % AdjRsquared)
    print('F Statistic: %1.4f' % Fstatistic)
    print('MSE: %1.4f' % MSE)
    print('RMSE: %1.4f' % RMSE)
    print('Test Observations:',format(len(y_test)))
    print('Sum of Abs Pct Error: %5.1f' % AbsErrorSum)
    print('Pct Mean Error: %1.4f' % MeanOfError)
    print('Pct Std Dev Error: %1.4f' % StdOfError)
    # print plots
    fig, ax = plt.subplots()
    ax.grid()
    acc = df_results.error
    ptile = np.percentile(acc,[15,85,2.5,97.5])
    sns.regplot(x=df_out['OPS'], y=df_out['predOPS'],
                line_kws={"color":"r","alpha":0.7,"lw":5},
                scatter_kws={"color":"b","s":8}
               )
    plt.title('Actual OPS vs. Predicted OPS')
    plt.xlabel('Actual OPS')
    plt.ylabel('Predicted OPS')
    plt.show()
    fig, ax = plt.subplots()
    ax.grid()
    plt.hist(acc,bins=25)
    plt.title('Error : Actual OPS - Predicted OPS')
    plt.xlabel('Error')
    plt.ylabel('Frequency')
    lab = 'Sampling Mean: %1.2f' % round(np.mean(df_out.error),2)
    lab1 = 'Conf Interval 15 ( %1.3f' % ptile[0] + ' )'
    lab2 = 'Conf Interval 85 ( %1.3f' % ptile[1] + ' )'
    lab3 = 'Conf Interval 2.5 ( %1.3f' % ptile[2] + ' )'
    lab4 = 'Conf Interval 97.5 ( %1.3f' % ptile[3] + ' )'
    plb.axvline(round(np.mean(df_out.error),2),label=lab, color='brown')
    plb.axvline(round(ptile[0],3), label=lab1, color='red')
    plb.axvline(round(ptile[1],3), label=lab2, color='red')
    plb.axvline(round(ptile[2],3), label=lab3, color='green')
    plb.axvline(round(ptile[3],3), label=lab4, color='green')
    leg=plt.legend()
    plt.show()
    fig, ax = plt.subplots()
    ax.grid()
    # plot QQ Plot to see if normal
    probplot(acc,dist="norm",plot=plb)
    _ = plt.title('QQ Plot of OPS Data\n',weight='bold', size=16)
    _ = plt.ylabel('Ordered Values', labelpad=10, size=14)
    _ = plt.xlabel('Theoritical Quantiles', labelpad=10, size = 14)
    ax = plt.gca()
    ax.yaxis.set_major_formatter(mtick.StrMethodFormatter('{x:1.3f}'))
    plt.xticks(np.arange(-4,5,1))
    plb.show()
    fig, ax = plt.subplots()
    ax.grid()
    plt.plot(y_pred, (y_pred-y_test), marker='.',linestyle='none',color='b')
    plt.title('Predicted OPS vs. Residuals')
    plt.xlabel('Predicted OPS')
    plt.ylabel('Residuals')
    plt.show()
    return True
Пример #53
0
S = 3600.
clfpos()
plt.plot(dra * S, ddec * S, 'k-')
for i in [i0, i90]:
    L = 0.3 / 4
    plt.arrow(0,
              0,
              dra[i] * S,
              ddec[i] * S,
              shape='full',
              overhang=0,
              head_length=L,
              head_width=0.5 * L,
              fc='k',
              length_includes_head=True)
plt.axvline(0., color='k', alpha=0.3)
plt.axhline(0., color='k', alpha=0.3)
plt.axis('equal')
plt.xticks([])
plt.yticks([])
ps.savefig()

mod0 = mod

g1.shape = s2
mod = tractor.getModelImage(0)

plog(mod)

t = np.deg2rad(70.)
R = np.array([[np.cos(t), np.sin(t)], [-np.sin(t), np.cos(t)]])
Пример #54
0
        region_mean = np.mean(data, 0)

        ###plotting commands
        pl.plot(times, region_mean, color=colorList[c],
                linewidth=lWidth)  #plot the data
        #pl.title(chan)
        pl.ylim([eegymin, eegymax])  #set the y limits
        pl.xlim([eegxmin, eegxmax])  #set the x limits
        pl.box('off')  # turn off the box frame
        pl.axhline(y=0, xmin=0, xmax=1, color='k',
                   linewidth=2)  #draw a thicker horizontal line at 0
        yfactor = abs(eegymax) + abs(eegymin)
        pl.axvline(
            x=0,
            ymin=(.5 - (vertScaleBar / float(yfactor))),
            ymax=(.5 + (vertScaleBar / float(yfactor))),
            color='k',
            linewidth=2
        )  #draw a vertical line at 0 that goes 1/8 of the range in each direction from the middle (e.g., if the range is -8:8, =16, 1/8 of 16=2, so -2:2).

        pl.yticks(np.array([]))  #turn off the y tick labels
        pl.xticks(np.array([]))  #turn off the x tick labels
        pl.tick_params(axis='both',
                       right='off',
                       left='off',
                       bottom='off',
                       top='off')  #turn off all the tick marks

        #draw vertical lines every hundred ms
        pl.axvline(x=100, ymin=.48, ymax=.52, color='k', linewidth=2)
        pl.axvline(x=200, ymin=.48, ymax=.52, color='k', linewidth=2)
Пример #55
0
    for jj in range(len(S)):
        clmplt.append(clmbrate[ii][jj])
        grnplt.append(grndroll[ii][jj])

    pyl.plot(clmplt, grnplt, ls='--', lw=2)
    lgnd.append('TW = %2.2f (in)' % (TotalWeight[ii] / LBF))

for jj in range(len(S)):
    clmplt = []
    grnplt = []
    for ii in range(len(TotalWeight)):
        clmplt.append(clmbrate[ii][jj])
        grnplt.append(grndroll[ii][jj])

    pyl.plot(clmplt, grnplt, lw=2)
    lgnd.append('S = %4.0f (in^2)' % (S[jj] / IN**2))

#lgnd.append('W = %2.0f (lbf)' % (Aircraft.TotalWeight / LBF))

pyl.plot()
pyl.axhline(y=190, color='k', lw=1)
pyl.axvline(x=74.37, color='k', lw=1)
#pyl.axvline(x = 100, color = 'k', lw = 1)
pyl.ylim(160, 220)
pyl.xlim(65, 100)
pyl.title('Groundroll and Climb Rate for Varying Wing Area and TotalWeight')
pyl.xlabel('Lift Off Climb Rate (ft/min)')
pyl.ylabel('Groundroll (ft)')
pyl.legend(lgnd, loc='best', numpoints=1, labelspacing=0.0)

pyl.show()
                                                  usecols=[0, 1, 2])

        ### plot enclosed intensity vs. angle
        pl.plot(np.log10(theta), enc_int_norm, lw=3.0)

    ### add legend
    legend = pl.legend(
        ([r"$%.2f$" % j for j in plaw_exp]),
        frameon=False,
        loc='upper left',
        handlelength=1.5,
        title="$\mathrm{power}$-$\mathrm{law}$ \n $\mathrm{exponent}$")
    pl.setp(legend.get_title(), fontsize='xx-small')

    ### add line marking enclosed intensity at theta = 1 deg
    pl.axvline(np.log10(1.), color='k', linestyle='--', lw=1.5)

    ### minor ticks
    xminticks = MultipleLocator(0.1)
    yminticks = MultipleLocator(0.05)
    pl.gca().xaxis.set_minor_locator(xminticks)
    pl.gca().yaxis.set_minor_locator(yminticks)

    pl.xlim([-2., 2.])

    pl.xlabel(r'$\mathrm{log}(\theta) \ [\mathrm{deg}]$')
    pl.ylabel(r'$\mathrm{Normalized \ Enclosed \ Intensity}$')
    #pl.title(r'$\mathrm{%i \ Layer \ Luneburg \ Lens}$'%layers[i])

    print ""
    print ">>> Saving enclosed intensity plot to " + os.path.join(
Пример #57
0
    def normalized_plot(what,alphaGammaName,N=1000,stride=50,aHi=[],legendAlpha=.5):
        '''
        Create normalized plot as it appears in :cite:`Maugis1992` including range of axes with normalized quantities. This function is mainly useful for documentation of Woo itself.

        :param what: one of ``a(delta)``, ``F(delta)``, ``a(F)``
        :param alphaGammaName: list of (alpha,gamma,name) tuples which are passed to the :obj:`SchwarzModel` constructor
        :param N: numer of points in linspace for each axis
        :param stride: stride for plotting inverse relationships (with points)
        :param aHi: with ``what==a(delta)``, show upper bracket for $a$ for i-th model, if *i* appears in the list
        '''
        assert what in ('a(delta)','F(delta)','a(F)')
        import pylab
        invKw=dict(linewidth=4,alpha=.3)
        kw=dict(linewidth=2)
        pylab.figure()
        for i,(alpha,gamma,name) in enumerate(alphaGammaName):
            m=SchwarzModel.makeDefault(alpha=alpha,gamma=gamma,name=name)
            if what=='a(delta)':
                ddHat=numpy.linspace(-1.3,2.,num=N)
                aaHat=numpy.linspace(0,2.1,num=N)
                pylab.plot(m.deltaHat_aHat(aaHat),aaHat,label=r'$\alpha$=%g %s'%(m.alpha,m.name),**kw)
                ddH=m.deltaHat_aHat(aaHat)
                if i in aHi: pylab.plot(ddH,[m.aHat(m.aHi(m.deltaUnhat(dh))) for dh in ddH],label=r'$\alpha$=%g $a_{\mathrm{hi}}$'%m.alpha,linewidth=1,alpha=.4)
                pylab.plot(ddHat[::stride],m.aHat_deltaHat(ddHat[::stride],loading=True),'o',**invKw)
                pylab.plot(ddHat[::stride],m.aHat_deltaHat(ddHat[::stride],loading=False),'o',**invKw)
            elif what=='F(delta)':
                ffHat=numpy.linspace(-2.1,1.5,num=N)
                ddHat=numpy.linspace(-1.3,2.,num=N)
                pylab.plot(ddHat,m.fHat_aHat(m.aHat_deltaHat(ddHat)),label=r'$\alpha$=%g %s'%(m.alpha,m.name),**kw)
                pylab.plot(ddHat,m.fHat_aHat(m.aHat_deltaHat(ddHat,loading=False)),**kw)
                pylab.plot([m.deltaHat(m.delta_a(m.a_F(m.fUnhat(fh))[0])) for fh in ffHat[::stride]],ffHat[::stride],'o',**invKw)
                pylab.plot([m.deltaHat(m.delta_a(m.a_F(m.fUnhat(fh))[1])) for fh in ffHat[::stride]],ffHat[::stride],'o',**invKw)
            elif what=='a(F)':
                aaHat=numpy.linspace(0,2.5,num=N)
                ffHat=numpy.linspace(-3,4,num=N)
                pylab.plot(ffHat,[a[0] for a in m.aHat_fHat(ffHat)],label=r'$\alpha$=%g %s'%(m.alpha,m.name),**kw)
                pylab.plot(ffHat,[a[1] for a in m.aHat_fHat(ffHat)],**kw)
                pylab.plot(m.fHat_aHat(aaHat[::stride]),aaHat[::stride],'o',label=None,**invKw)
        if what=='a(delta)': 
            ddH=[m.deltaHat(HertzModel.delta_a(m,m.aUnhat(a))) for a in aaHat]
            pylab.plot(ddH,aaHat,label='Hertz',**kw)
            pylab.xlabel(r'$\hat\delta$')
            pylab.ylabel(r'$\hat a$')
            pylab.ylim(ymax=2.1)
            pylab.xlim(xmax=2.)
        elif what=='F(delta)':
            pylab.plot(ddHat,[m.fHat(HertzModel.F_delta(m,m.deltaUnhat(d))) for d in ddHat],label='Hertz',**kw)
            pylab.xlabel(r'$\hat\delta$')
            pylab.ylabel(r'$\hat P$')
            pylab.xlim(-1.3,2)
            pylab.ylim(-2.1,2)
            pylab.axhline(color='k')
            pylab.axvline(color='k')
        elif what=='a(F)':
            pylab.plot(ffHat,[m.aHat(HertzModel.a_F(m,m.fUnhat(f))) for f in ffHat],label='Hertz',**kw)
            pylab.xlabel(r'$\hat P$')
            pylab.ylabel(r'$\hat a$')
            pylab.xlim(xmax=4)
        pylab.grid(True)
        try:
            pylab.legend(loc='best',framealpha=legendAlpha)
        except:
            pylab.legend(loc='best')
Пример #58
0
    reservoir.reset_states = False

    # optimize the ridge parameter
    gridsearch_parameters = {readout:{'ridge_param': 10 ** numx.arange(-6, 0, .5)}}

    # Instantiate an optimizer
    loss_function = Oger.utils.timeslice(range(-freerun_steps, 0), Oger.utils.nrmse)
    opt = Oger.evaluation.Optimizer(gridsearch_parameters, loss_function)

    # Do the grid search
    opt.grid_search([[], train_signals], flow,
                    cross_validate_function=Oger.evaluation.leave_one_out)

    # get the optimal flow
    opt_flow = opt.get_optimal_flow(verbose=True)

    # Train the optimized flow to do one-step ahead prediction using the teacher-forced signal
    # An additional input giving the frequency of the desired sine wave is also given   
    opt_flow.train([[] , train_signals])

    # execute the trained flow on a test signal
    freerun_output = opt_flow.execute(test_signals[0][0])

    # plot the test results
    pylab.plot(test_signals[0][0][:, 1], 'b')
    pylab.plot(freerun_output, 'g')
    pylab.axvline(test_signals[0][0].shape[0] - freerun_steps + 1, pylab.ylim()[0], pylab.ylim()[1], color='r')

    pylab.show()
Пример #59
0
x = x.T
y = y.T

pl.figure(figsize=(5, 5))
pl.subplot(1, 2, 1)
pl.clf()
pl.axes([0, 0, 1, 1])

contours = pl.contour(np.sqrt((x - 3)**2 + (y - 2)**2),
                      extent=[-3, 6, -2.5, 5],
                      cmap=pl.cm.gnuplot)
pl.clabel(contours, inline=1, fmt='%1.1f', fontsize=14)

pl.plot([-3, 6], [1.5, -1.5], 'k', linewidth=2)

pl.plot(3, 2, 'ko')
pl.text(3 - .2, 2 + .3, '$Global minimum$', size=15)

pl.plot(2.3, -0.29, 'ro')
pl.text(2.3 + .2, -0.29, '$Optimum$', size=15)
pl.text(6.1, -1.6, '$h(x) = 0 $', size=15)

pl.axvline(0, color='k')
pl.axhline(0, color='k')

pl.text(-.9, 4.4, '$x_2$', size=20)
pl.text(5.6, -.6, '$x_1$', size=20)
pl.axis('equal')
pl.axis('off')
pl.show()
Пример #60
0
frame= par.xyz0[2], par.xyz1[2], w[0], 1

# theoretical frequencies of the g-modes
wth, bv, haut=theory(kx, par.cs0, par.lxyz[0])
P.subplot(311)
im=P.imshow(w2[w<1, :, kx], aspect='auto', origin='lower', 
extent=frame, cmap=P.get_cmap('binary'))
for n in range(3): P.axhline(wth[n], ls='--', color='b')
P.title('kx=%i'%kx)
P.xlabel('z')
P.ylabel('frequency')

# integrated spectrum
P.subplot(312)
P.semilogy(w[w < 1], inte[w < 1, kx])
for n in range(3): P.axvline(wth[n], ls='--', color='k')
P.xlabel('frequency')

#
#  vertical profile: zoom in around a given frequency
#
w0=wth[node] 
wmin=w0-dw ; wmax=w0+dw
ind = N.where(w >= wmin, 1, 0)*N.where(w <= wmax, 1, 0)
ind = N.asarray(N.nonzero(ind))[0, :]
print('Zoom in wth', w[ind])
f = w2[ind, :, kx]
prof = f.mean(axis=0)

P.subplot(313)
P.plot(grid.z, prof/prof.max(), label='simulation')