コード例 #1
0
ファイル: rocs.py プロジェクト: cbare/dreamtools
    def plot_roc(self, roc=None):
        """Plot ROC curves

        .. plot::
            :include-source:
            :width: 80%

            from dreamtools import rocs
            r = rocs.ROC()
            r.scores = [.9,.5,.6,.7,.1,.2,.6,.4,.7,.9, .2]
            r.classes = [1,0,1,0,0,1,1,0,0,1,1]
            r.plot_roc()

        """
        if roc == None:
            roc = self.get_roc()
        from pylab import plot, xlim, ylim ,grid, title, xlabel, ylabel
        x = roc['fpr']
        plot(x, roc['tpr'], '-o')
        plot([0,1], [0,1],'r')
        ylim([0, 1])
        xlim([0, 1])
        grid(True)
        title("ROC curve (AUC=%s)" % self.compute_auc(roc))
        xlabel("FPR")
        ylabel("TPR")
コード例 #2
0
ファイル: ps8b.py プロジェクト: Eymerich71/edx
def simulationWithoutDrugNick(numViruses, maxPop, maxBirthProb, clearProb,
                          numTrials):
    """
    Run the simulation and plot the graph for problem 3 (no drugs are used,
    viruses do not have any drug resistance).    
    For each of numTrials trial, instantiates a patient, runs a simulation
    for 300 timesteps, and plots the average virus population size as a
    function of time.

    numViruses: number of SimpleVirus to create for patient (an integer)
    maxPop: maximum virus population for patient (an integer)
    maxBirthProb: Maximum reproduction probability (a float between 0-1)        
    clearProb: Maximum clearance probability (a float between 0-1)
    numTrials: number of simulation runs to execute (an integer)
    """
    #Instantiate the viruses first, the patient second
    viruses= [ SimpleVirus(maxBirthProb, clearProb) for i in range(numViruses) ]
    patient = Patient(viruses, maxPop)
    #Execute the patient.update method 300 times for 100 trials
    steps = 300
    countList = [0 for i in range(300)]
    for trial in range(numTrials):
        for timeStep in range(steps):
            countList[timeStep] += patient.update()
    avgList = [ countList[i]/float(numTrials) for i in range(steps) ]
    #Plot a diagram with xAxis=timeSteps, yAxis=average virus population
    xAxis = [ x for x in range(steps) ]
    pylab.figure(2)
    pylab.plot(xAxis, avgList, 'ro', label='Simple Virus')
    pylab.xlabel('Number of elapsed time steps')
    pylab.ylabel('Average size of the virus population')
    pylab.title('Virus growth in a patient without the aid of any drag')
    pylab.legend()
    pylab.show()
コード例 #3
0
def check_vpd_ks2_astrometry():
    """
    Check the VPD and quiver plots for our KS2-extracted, re-transformed astrometry.
    """
    catFile = workDir + '20.KS2_PMA/wd1_catalog.fits'
    tab = atpy.Table(catFile)

    good = (tab.xe_160 < 0.05) & (tab.ye_160 < 0.05) & \
        (tab.xe_814 < 0.05) & (tab.ye_814 < 0.05) & \
        (tab.me_814 < 0.05) & (tab.me_160 < 0.05)

    tab2 = tab.where(good)

    dx = (tab2.x_160 - tab2.x_814) * ast.scale['WFC'] * 1e3
    dy = (tab2.y_160 - tab2.y_814) * ast.scale['WFC'] * 1e3

    py.clf()
    q = py.quiver(tab2.x_814, tab2.y_814, dx, dy, scale=5e2)
    py.quiverkey(q, 0.95, 0.85, 5, '5 mas', color='red', labelcolor='red')
    py.savefig(workDir + '20.KS2_PMA/vec_diffs_ks2_all.png')

    py.clf()
    py.plot(dy, dx, 'k.', ms=2)
    lim = 30
    py.axis([-lim, lim, -lim, lim])
    py.xlabel('Y Proper Motion (mas)')
    py.ylabel('X Proper Motion (mas)')
    py.savefig(workDir + '20.KS2_PMA/vpd_ks2_all.png')

    idx = np.where((np.abs(dx) < 10) & (np.abs(dy) < 10))[0]
    print('Cluster Members (within dx < 10 mas and dy < 10 mas)')
    print(('   dx = {dx:6.2f} +/- {dxe:6.2f} mas'.format(dx=dx[idx].mean(),
                                                        dxe=dx[idx].std())))
    print(('   dy = {dy:6.2f} +/- {dye:6.2f} mas'.format(dy=dy[idx].mean(),
                                                        dye=dy[idx].std())))
コード例 #4
0
ファイル: TestSuite.py プロジェクト: clemrom/pyoptic
 def testTelescope(self):
     import matplotlib
     matplotlib.use('AGG')
     import matplotlib.mlab as ml
     import pylab as pl
     import time        
     w0 = 8.0
     k = 2*np.pi/3.0
     gb = GaussianBeam(w0, k)
     lens = ThinLens(150, 150)
     gb2 = lens*gb
     self.assertAlmostEqual(gb2._z0, gb._z0 + 2*150.0)
     lens2 = ThinLens(300, 600)
     gb3 = lens2*gb2
     self.assertAlmostEqual(gb3._z0, gb2._z0 + 2*300.0)
     self.assertAlmostEqual(gb._w0, gb3._w0/2.0)
     z = np.arange(0, 150)
     z2 = np.arange(150, 600)
     z3 = np.arange(600, 900)
     pl.plot(z, gb.w(z, k), z2, gb2.w(z2, k), z3, gb3.w(z3, k))
     pl.grid()
     pl.xlabel('z')
     pl.ylabel('w')
     pl.savefig('testTelescope1.png')
     time.sleep(0.1)
     pl.close('all')        
コード例 #5
0
ファイル: show2.py プロジェクト: ipbs/ipbs
def plotear(xi,yi,zi):
    # mask inner circle
    interior1 = sqrt(((xi+1.5)**2) + (yi**2)) < 1.0 
    interior2 = sqrt(((xi-1.5)**2) + (yi**2)) < 1.0
    zi[interior1] = ma.masked
    zi[interior2] = ma.masked
    p.figure(figsize=(16,10))
    pyplot.jet()
    max=2.8
    min=0.4
    steps = 50
    levels=list()
    labels=list()
    for i in range(0,steps):
	levels.append(int((max-min)/steps*100*i)*0.01+min)
    for i in range(0,steps/2):
	labels.append(levels[2*i])
    CSF = p.contourf(xi,yi,zi,levels,norm=colors.LogNorm())
    CS = p.contour(xi,yi,zi,levels, format='%.3f', labelsize='18')
    p.clabel(CS,labels,inline=1,fontsize=9)
    p.title('electrostatic potential of two spherical colloids, R=lambda/3',fontsize=24)
    p.xlabel('z-coordinate (3*lambda)',fontsize=18)
    p.ylabel('radial coordinate r (3*lambda)',fontsize=18)
    # add a vertical bar with the color values
    cbar = p.colorbar(CSF,ticks=labels,format='%.3f')
    cbar.ax.set_ylabel('potential (reduced units)',fontsize=18)
    cbar.add_lines(CS)
    p.show()
コード例 #6
0
 def showHistory(self, figNum):
     pylab.figure(figNum)
     plot = pylab.plot(self.history, label = 'Test Stock')
     plot
     pylab.title('Closing Price, Test ' + str(figNum))
     pylab.xlabel('Day')
     pylab.ylabel('Price')
コード例 #7
0
ファイル: h2o_gbm.py プロジェクト: hardikk/h2o
def plotLists(xList, xLabel=None, eListTitle=None, eList=None, eLabel=None, fListTitle=None, fList=None, fLabel=None):
    if h2o.python_username!='kevin':
        return

    import pylab as plt
    print "xList", xList
    print "eList", eList
    print "fList", fList

    font = {'family' : 'normal',
            'weight' : 'normal',
            'size'   : 26}
    ### plt.rc('font', **font)
    plt.rcdefaults()

    if eList:
        if eListTitle:
            plt.title(eListTitle)
        plt.figure()
        plt.plot (xList, eList)
        plt.xlabel(xLabel)
        plt.ylabel(eLabel)
        plt.draw()

    if fList:
        if fListTitle:
            plt.title(fListTitle)
        plt.figure()
        plt.plot (xList, fList)
        plt.xlabel(xLabel)
        plt.ylabel(fLabel)
        plt.draw()

    if eList or fList:
        plt.show()
コード例 #8
0
def srcdiff_plot(env, model, **kwargs):
    obj_index       = kwargs.pop('obj_index', 0)
    src_index       = kwargs.pop('src_index', 0)
    with_colorbar   = kwargs.pop('with_colorbar', False)
    xlabel          = kwargs.pop('xlabel', r'arcsec')
    ylabel          = kwargs.pop('ylabel', r'arcsec')

    obj, data = model['obj,data'][obj_index]
    S = obj.basis.subdivision
    R = obj.basis.mapextent

    g = obj.basis.srcdiff_grid(data)[src_index]
    vmin = np.log10(np.amin(g[g>0]))
    g = g.copy() + 1e-10
    kw = default_kw(R, kwargs) #, vmin=vmin, vmax=vmin+2)

    #loglev = logspace(1, log(amax(g)-amin(g)), 20, base=math.e) + amin(g)
    pl.matshow(np.log10(g), **kw)
    matplotlib.rcParams['contour.negative_linestyle'] = 'solid'
    if with_colorbar: glspl.colorbar()
#   pl.over(contour, g, 50,  colors='w',               linewidths=1, 
#        extent=[-R,R,-R,R], origin='upper', extend='both')
    #pl.grid()

    pl.xlabel(xlabel)
    pl.ylabel(ylabel)
コード例 #9
0
def H0inv_plot(env, **kwargs):
    _hist(env, '1/H0', xlabel=r'$H_0^{-1}$ (Gyr)')
    return

    models      = kwargs.pop('models', env.models)
    obj_index   = kwargs.pop('obj_index', 0)
    key         = kwargs.pop('key', 'accepted')
    xlabel      = kwargs.pop('xlabel', r'$H_0^{-1}$ (Gyr)')
    ylabel      = kwargs.pop('ylabel', r'Count')

    # select a list to append to based on the 'accepted' property.
    l = [[], [], []]
    for m in models:
        obj, data = m['obj,data'][0] # For H0inv we only have to look at one model because the others are the same
        l[m.get(key,2)].append(data['1/H0'])
        #l[2].append(data['kappa'][1])

    #print amin(l[2]), amax(l[2])

    not_accepted, accepted, notag = l

    #print 'H0inv_plot',H0s

    for d,s in zip(l, _styles):
        if d:
            #print len(d), d
            #pl.hist(d, bins=20, histtype='step', edgecolor=s['c'], zorder=s['z'], label=s['label'])
            pl.hist(d, bins=np.ptp(d)//1+1, histtype='step', edgecolor=s['c'], zorder=s['z'], label=s['label'], **kwargs)

    #if not_accepted or accepted:
        #pl.legend()

    pl.axvline(13.7, c='k', ls=':', zorder = 2)

    pl.xlabel(xlabel)
    pl.ylabel(ylabel)

    if accepted or not not_accepted:
        if accepted:
            h = np.array(accepted)
        else:
            h = np.array(accepted + notag)

        hs = np.sort(h)
        l = len(hs)

        m = hs[l * 0.50]
        u = hs[l * (0.50 + 0.341)]
        l = hs[l * (0.50 - 0.341)]
        #u = hs[l * 0.68]
        #l = hs[l * 0.32]

        pl.axvline(m, c='r', ls='-', zorder = 2)
        pl.axvline(u, c='g', ls='-', zorder = 2)
        pl.axvline(l, c='g', ls='-', zorder = 2)

        Log( 'H0inv_plot: ', m, u, l )
        Log( 'H0inv_plot: ', m, (u-m), (m-l) )
    else:
        Log( "H0inv_plot: No H0inv values accepted" )
コード例 #10
0
def chisq_plot(env, **kwargs):
    _hist(env, 'sigp:chisq', xlabel=r'$\chi^2$')
    return

    models = kwargs.pop('models', env.models)
    objects = kwargs.pop('objects', None)
    key = kwargs.pop('key', 'accepted')

    # select a list to append to based on the 'accepted' property.
    l = [[], [], []]
    for m in models:
        # For H0 we only have to look at one model because the others are the same
        obj, data = m['obj,data'][0] 
        l[m.get(key,2)].append(data['sigp:chisq'])

    not_accepted, accepted, notag = l

    for d,s in zip(l, _styles):
        if d:
            pl.hist(d, histtype='step', edgecolor=s['c'], zorder=s['z'], label=s['label'], log=False, **kwargs)

    if not_accepted or accepted:
        pl.legend()

    pl.xlabel(_chisq_xlabel)
    pl.ylabel(r'Count')
コード例 #11
0
def grad_kappa_plot(env, model, obj_index, which='x', with_contours=False, only_contours=False, clevels=30, with_colorbar=True):
    obj, data = model['obj,data'][obj_index]

    R = obj.basis.mapextent

    grid = obj.basis.kappa_grid(data)
    grid = grid.copy()

    kw = default_kw(R)
    kw['vmin'] = -1
    kw['vmax'] =  2

    if not only_contours:
        print '!!!!!!', grid.shape
        if which == 'x': grid = np.diff(grid, axis=1)
        if which == 'y': grid = np.diff(grid, axis=0)
        print '!!!!!!', grid.shape
        pl.matshow(grid, **kw)
        if with_colorbar: 
            glspl.colorbar()

    if with_contours:
        kw.pop('cmap')
        pl.over(contour, grid, clevels, extend='both', colors='k', alpha=0.7, **kw)

    pl.xlabel('arcsec')
    pl.ylabel('arcsec')
コード例 #12
0
ファイル: quick_look.py プロジェクト: BKJackson/vq
	def plot_stress(self, block_ids=None, fignum=0):
		block_ids = self.check_block_ids_list(block_ids)
		#
		plt.figure(fignum)
		ax1=plt.gca()
		plt.clf()
		plt.figure(fignum)
		plt.clf()
		ax0=plt.gca()

		#
		for block_id in block_ids:
			rws = numpy.core.records.fromarrays(zip(*filter(lambda x: x['block_id']==block_id, self.shear_stress_sequences)), dtype=self.shear_stress_sequences.dtype)
			stress_seq = []
			for rw in rws:
				stress_seq += [[rw['sweep_number'], rw['shear_init']]]
				stress_seq += [[rw['sweep_number'], rw['shear_final']]]
			X,Y = zip(*stress_seq)
			#
			ax0.plot(X,Y, '.-', label='block_id: %d' % block_id)
			#
			plt.figure(fignum+1)
			plt.plot(rws['sweep_number'], rws['shear_init'], '.-', label='block_id: %d' % block_id)
			plt.plot(rws['sweep_number'], rws['shear_final'], '.-', label='block_id: %d' % block_id)
			plt.figure(fignum)
		ax0.plot([min(self.shear_stress_sequences['sweep_number']), max(self.shear_stress_sequences['sweep_number'])], [0., 0.], 'k-')
		ax0.legend(loc=0, numpoints=1)
		plt.figure(fignum)
		plt.title('Block shear_stress sequences')
		plt.xlabel('sweep number')
		plt.ylabel('shear stress')
コード例 #13
0
def time_delays_plot(env, **kwargs):

    models = kwargs.pop('models', env.models)
    obj_index = kwargs.pop('obj_index', 0)
    src_index = kwargs.pop('src_index', 0)
    key = kwargs.pop('key', 'accepted')

    d = defaultdict(list)
    for m in models:
        obj,data = m['obj,data'][obj_index]
        t0 = data['arrival times'][src_index][0]
        for i,t in enumerate(data['arrival times'][src_index][1:]):
            d[i].append( float('%0.6f'%convert('arcsec^2 to days', t-t0, obj.dL, obj.z, data['nu'])) )
            t0 = t

    s = product(range(1,1+len(d)), ['solid', 'dashed', 'dashdot', 'dotted'])
    for k,v in d.iteritems():
        #print 'td plot', k, len(v)
        #print v
        lw,ls = s.next()
        pl.hist(v, bins=25, histtype='step', color='k', ls=ls, lw=lw, label='%s - %s' % (str(k+1),str(k+2)), **kwargs)

    #pl.xlim(xmin=0)
    pl.ylim(ymin=0)
    pl.xlim(xmin=pl.xlim()[0] - 0.01*(pl.xlim()[1] - pl.xlim()[0]))
    pl.legend()

    pl.xlabel(_time_delays_xlabel)
    pl.ylabel(r'Count')
コード例 #14
0
ファイル: Matplot.py プロジェクト: CosmologyTaskForce/pymc
def geweke_plot(data, name, format='png', suffix='-diagnostic', path='./', fontmap = None, 
    verbose=1):
    # Generate Geweke (1992) diagnostic plots

    if fontmap is None: fontmap = {1:10, 2:8, 3:6, 4:5, 5:4}

    # Generate new scatter plot
    figure()
    x, y = transpose(data)
    scatter(x.tolist(), y.tolist())

    # Plot options
    xlabel('First iteration', fontsize='x-small')
    ylabel('Z-score for %s' % name, fontsize='x-small')

    # Plot lines at +/- 2 sd from zero
    pyplot((nmin(x), nmax(x)), (2, 2), '--')
    pyplot((nmin(x), nmax(x)), (-2, -2), '--')

    # Set plot bound
    ylim(min(-2.5, nmin(y)), max(2.5, nmax(y)))
    xlim(0, nmax(x))

    # Save to file
    if not os.path.exists(path):
        os.mkdir(path)
    if not path.endswith('/'):
        path += '/'
    savefig("%s%s%s.%s" % (path, name, suffix, format))
コード例 #15
0
ファイル: parse.py プロジェクト: tomasra/ga_sandbox
def param_set_averages_plot(results):
    averages_ocr = [
        a[1] for a in sorted(
            param_set_averages(results, metric='ocr').items(),
            key=lambda x: int(x[0].split('-')[1]))
    ]
    averages_q = [
        a[1] for a in sorted(
            param_set_averages(results, metric='q').items(),
            key=lambda x: int(x[0].split('-')[1]))
    ]
    averages_mse = [
        a[1] for a in sorted(
            param_set_averages(results, metric='mse').items(),
            key=lambda x: int(x[0].split('-')[1]))
    ]
    fig = plt.figure(figsize=(6, 4))
    # plt.tight_layout()
    plt.plot(averages_ocr, label='OCR', linewidth=2.0)
    plt.plot(averages_q, label='Q', linewidth=2.0)
    plt.plot(averages_mse, label='MSE', linewidth=2.0)
    plt.ylim([0, 1])
    plt.xlabel(u'Paslėptų neuronų skaičius')
    plt.ylabel(u'Vidurinė Q įverčio pokyčio reikšmė')
    plt.grid(True)
    plt.tight_layout()
    plt.legend(loc='lower right')
    plt.show()
コード例 #16
0
ファイル: kinetics.py プロジェクト: ajalan/RMG-Py
def generateKineticsModel(reaction, tunneling='', plot=False):
    
    logging.info('Calculating rate coefficient for {0}...'.format(reaction))
    
    if len(reaction.reactants) == 1:
        kunits = 's^-1'
    elif len(reaction.reactants) == 2:
        kunits = 'm^3/(mol*s)'
    elif len(reaction.reactants) == 3:
        kunits = 'm^6/(mol^2*s)'
    else:
        kunits = ''
    
    Tlist = 1000.0/numpy.arange(0.4, 3.35, 0.05)
    klist = reaction.calculateTSTRateCoefficients(Tlist, tunneling)
    arrhenius = Arrhenius().fitToData(Tlist, klist, kunits)
    klist2 = arrhenius.getRateCoefficients(Tlist)
    
    reaction.kinetics = arrhenius
    
    if plot:
        logging.info('Plotting kinetics model for {0}...'.format(reaction))
        import pylab
        pylab.semilogy(1000.0 / Tlist, klist  * reaction.degeneracy, 'ok')
        pylab.semilogy(1000.0 / Tlist, klist2 * reaction.degeneracy, '-k')
        pylab.xlabel('1000 / Temperature (1000/K)')
        pylab.ylabel('Rate coefficient (SI units)')
        pylab.show()
コード例 #17
0
ファイル: ps9.py プロジェクト: eshilts/intro-to-cs-6.00x
def plotHistogram(data, preTime):
    pylab.figure(1)
    pylab.hist(data, bins=10)
    pylab.xlabel("Virus Population At End of Simulation")
    pylab.ylabel("Number of Trials")
    pylab.title("{0} Time Steps Before Treatment Simulation".format(preTime))
    pylab.show()
コード例 #18
0
ファイル: VOCpr.py プロジェクト: ChrisYang/CRFdet
def drawPr(tp,fp,tot,show=True):
    """
        draw the precision recall curve
    """
    det=numpy.array(sorted(tp+fp))
    atp=numpy.array(tp)
    afp=numpy.array(fp)
    #pylab.figure()
    #pylab.clf()
    rc=numpy.zeros(len(det))
    pr=numpy.zeros(len(det))
    #prc=0
    #ppr=1
    for i,p in enumerate(det):
        pr[i]=float(numpy.sum(atp>=p))/numpy.sum(det>=p)
        rc[i]=float(numpy.sum(atp>=p))/tot
        #print pr,rc,p
    ap=0
    for c in numpy.linspace(0,1,num=11):
        if len(pr[rc>=c])>0:
            p=numpy.max(pr[rc>=c])
        else:
            p=0
        ap=ap+p/11
    if show:
        pylab.plot(rc,pr,'-g')
        pylab.title("AP=%.3f"%(ap))
        pylab.xlabel("Recall")
        pylab.ylabel("Precision")
        pylab.grid()
        pylab.show()
        pylab.draw()
    return rc,pr,ap
コード例 #19
0
ファイル: oldtimer.py プロジェクト: ianmsmith/oldtimer
def createPlot(dataY, dataX, ticksX, annotations, axisY, axisX, dostep, doannotate):
    if not ticksX:
        ticksX = dataX
    
    if dostep:
        py.step(dataX, dataY, where='post', linestyle='-', label=axisY) # where=post steps after point
    else:
        py.plot(dataX, dataY, marker='o', ms=5.0, linestyle='-', label=axisY)
    
    if annotations and doannotate:
        for note, x, y in zip(annotations, dataX, dataY):
            py.annotate(note, (x, y), xytext=(2,2), xycoords='data', textcoords='offset points')

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

    # Set X axis tick labels as rungs
    #print zip(dataX, dataY)
  
    py.draw()
    py.show()
    
    return
コード例 #20
0
def simulation1(numTrials, numSteps, loc):
    results = {'UsualDrunk': [], 'ColdDrunk': [], 'EDrunk': [], 'PhotoDrunk': [], 'DDrunk': []}
    drunken_types = {'UsualDrunk': UsualDrunk, 'ColdDrunk': ColdDrunk, 'EDrunk': EDrunk, 'PhotoDrunk': PhotoDrunk,
                     'DDrunk': DDrunk}
    for drunken in drunken_types.keys():
        #Create field
        initial_loc = Location(loc[0], loc[1])
        field = Field()
        print "Simu", drunken
        drunk = Drunk(drunken)
        drunk_man = drunken_types[drunken](drunk)
        field.addDrunk(drunk_man, initial_loc)
        #print drunk_man
        for trial in range(numTrials):
            distance = walkVector(field, drunk_man, numSteps)
            results[drunken].append((round(distance[0], 1), round(distance[1], 1)))
        print drunken, "=", results[drunken]
    for result in results.keys():
        # x, y = zip(*results[result])
        # print "x", x
        # print "y", y
        pylab.plot(*zip(*results[result]), marker='o', color='r', ls='')
        pylab.title(result)
        pylab.xlabel('X coordinateds')
        pylab.ylabel('Y coordinateds')
        pylab.xlim(-100, 100)
        pylab.ylim(-100, 100)
        pylab.figure()
    pylab.show
コード例 #21
0
ファイル: VOCpr.py プロジェクト: ChrisYang/CRFdet
def drawPrfastscore(tp,fp,scr,tot,show=True):
    tp=numpy.cumsum(tp)
    fp=numpy.cumsum(fp)
    rec=tp/tot
    prec=tp/(fp+tp)
    #dif=numpy.abs(prec[1:]-rec[1:])
    dif=numpy.abs(prec[::-1]-rec[::-1])
    pos=dif.argmin()
    pos=len(dif)-pos-1
    ap=0
    for t in numpy.linspace(0,1,11):
        pr=prec[rec>=t]
        if pr.size==0:
            pr=0
        p=numpy.max(pr);
        ap=ap+p/11;
    if show:    
        pylab.plot(rec,prec,'-g')
        pylab.title("AP=%.3f EPRthr=%.3f"%(ap,scr[pos]))
        pylab.xlabel("Recall")
        pylab.ylabel("Precision")
        pylab.grid()
        pylab.show()
        pylab.draw()
    return rec,prec,scr,ap,scr[pos]
コード例 #22
0
ファイル: benchmarkExample.py プロジェクト: Kun-Qu/petsc
def plotEventFlop(library, num, eventNames, sizes, times, events, filename = None):
  from pylab import legend, plot, savefig, semilogy, show, title, xlabel, ylabel
  import numpy as np

  arches = sizes.keys()
  bs     = events[arches[0]].keys()[0]
  data   = []
  names  = []
  for event, color in zip(eventNames, ['b', 'g', 'r', 'y']):
    for arch, style in zip(arches, ['-', ':']):
      if event in events[arch][bs]:
        names.append(arch+'-'+str(bs)+' '+event)
        data.append(sizes[arch][bs])
        data.append(1e-3*np.array(events[arch][bs][event])[:,1])
        data.append(color+style)
      else:
        print 'Could not find %s in %s-%d events' % (event, arch, bs)
  semilogy(*data)
  title('Performance on '+library+' Example '+str(num))
  xlabel('Number of Dof')
  ylabel('Computation Rate (GF/s)')
  legend(names, 'upper left', shadow = True)
  if filename is None:
    show()
  else:
    savefig(filename)
  return
コード例 #23
0
ファイル: GPP_calc_v1b.py プロジェクト: jberinge/DINGO12
def Doplots_monthly(mypathforResults,PlottingDF,variable_to_fill, Site_ID,units,item):   
    ANN_label=str(item+"_NN")     #Do Monthly Plots
    print "Doing MOnthly  plot"
    #t = arange(1, 54, 1)
    NN_label='Fc'
    Plottemp = PlottingDF[[NN_label,item]][PlottingDF['day_night']!=1]
    #Plottemp = PlottingDF[[NN_label,item]].dropna(how='any')
    figure(1)
    pl.title('Nightime ANN v Tower by year-month for '+item+' at '+Site_ID)

    try:
	xdata1a=Plottemp[item].groupby([lambda x: x.year,lambda x: x.month]).mean()
	plotxdata1a=True
    except:
	plotxdata1a=False
    try:
	xdata1b=Plottemp[NN_label].groupby([lambda x: x.year,lambda x: x.month]).mean()
	plotxdata1b=True
    except:
	plotxdata1b=False 
    if plotxdata1a==True:
	pl.plot(xdata1a,'r',label=item) 
    if plotxdata1b==True:
	pl.plot(xdata1b,'b',label=NN_label)
    pl.ylabel('Flux')    
    pl.xlabel('Year - Month')       
    pl.legend()
    pl.savefig(mypathforResults+'/ANN and Tower plots by year and month for variable '+item+' at '+Site_ID)
    #pl.show()
    pl.close()
    time.sleep(1)
コード例 #24
0
def plot_heatingrate(data_dict, filename, do_show=True):
    pl.figure(201)
    color_list = ['b','r','g','k','y','r','g','b','k','y','r',]
    fmtlist = ['s','d','o','s','d','o','s','d','o','s','d','o']
    result_dict = {}
    for key in data_dict.keys():
        x = data_dict[key][0]
        y = data_dict[key][1][:,0]
        y_err = data_dict[key][1][:,1]

        p0 = np.polyfit(x,y,1)
        fit = LinFit(np.array([x,y,y_err]).transpose(), show_graph=False)
        p1 = [0,0]
        p1[0] = fit.param_dict[0]['Slope'][0]
        p1[1] = fit.param_dict[0]['Offset'][0]
        print fit
        x0 = np.linspace(0,max(x))
        cstr = color_list.pop(0)
        fstr = fmtlist.pop(0)
        lstr = key + " heating: {0:.2f} ph/ms".format((p1[0]*1e3)) 
        pl.errorbar(x/1e3,y,y_err,fmt=fstr + cstr,label=lstr)
        pl.plot(x0/1e3,np.polyval(p0,x0),cstr)
        pl.plot(x0/1e3,np.polyval(p1,x0),cstr)
        result_dict[key] = 1e3*np.array(fit.param_dict[0]['Slope'])
    pl.xlabel('Heating time (ms)')
    pl.ylabel('nbar')
    if do_show:
        pl.legend()
        pl.show()
    if filename != None:
        pl.savefig(filename)
    return result_dict
コード例 #25
0
ファイル: shownet.py プロジェクト: 01bui/cuda-convnet
    def plot_cost(self):
        if self.show_cost not in self.train_outputs[0][0]:
            raise ShowNetError("Cost function with name '%s' not defined by given convnet." % self.show_cost)
        train_errors = [o[0][self.show_cost][self.cost_idx] for o in self.train_outputs]
        test_errors = [o[0][self.show_cost][self.cost_idx] for o in self.test_outputs]

        numbatches = len(self.train_batch_range)
        test_errors = numpy.row_stack(test_errors)
        test_errors = numpy.tile(test_errors, (1, self.testing_freq))
        test_errors = list(test_errors.flatten())
        test_errors += [test_errors[-1]] * max(0,len(train_errors) - len(test_errors))
        test_errors = test_errors[:len(train_errors)]

        numepochs = len(train_errors) / float(numbatches)
        pl.figure(1)
        x = range(0, len(train_errors))
        pl.plot(x, train_errors, 'k-', label='Training set')
        pl.plot(x, test_errors, 'r-', label='Test set')
        pl.legend()
        ticklocs = range(numbatches, len(train_errors) - len(train_errors) % numbatches + 1, numbatches)
        epoch_label_gran = int(ceil(numepochs / 20.)) # aim for about 20 labels
        epoch_label_gran = int(ceil(float(epoch_label_gran) / 10) * 10) # but round to nearest 10
        ticklabels = map(lambda x: str((x[1] / numbatches)) if x[0] % epoch_label_gran == epoch_label_gran-1 else '', enumerate(ticklocs))

        pl.xticks(ticklocs, ticklabels)
        pl.xlabel('Epoch')
#        pl.ylabel(self.show_cost)
        pl.title(self.show_cost)
コード例 #26
0
def plotB2reg(prefix=''):
    w=loadStanFit(prefix+'revE2B2LHregCa.fit')
    px=np.array(np.linspace(-0.5,0.5,101),ndmin=2)
    a1=np.array(w['ma'][:,4],ndmin=2).T+1
    a0=np.array(w['ma'][:,3],ndmin=2).T
    printCI(w,'ma')
    y=np.concatenate([sap(a0+a1*px,97.5,axis=0),sap(a0+a1*px[:,::-1],2.5,axis=0)])
    x=np.squeeze(np.concatenate([px,px[:,::-1]],axis=1))
    man=np.array([-0.4,-0.2,0,0.2,0.4])
    plt.plot(px[0,:],np.median(a0)+np.median(a1)*px[0,:],'red')
    #plt.plot([-1,1],[0.5,0.5],'grey')
    ax=plt.gca()
    ax.set_aspect(1)
    ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w'))
    y=np.concatenate([sap(a0+a1*px,75,axis=0),sap(a0+a1*px[:,::-1],25,axis=0)])
    ax.add_patch(plt.Polygon(np.array([x,y]).T,alpha=0.2,fill=True,fc='red',ec='w'))
    mus=[]
    for m in range(len(man)):
        mus.append(loadStanFit(prefix+'revE2B2LHC%d.fit'%m)['ma4']+man[m])
    mus=np.array(mus).T
    errorbar(mus,x=man)
    ax.set_xticks(man)
    plt.xlim([-0.5,0.5])
    plt.ylim([-0.6,0.8])
    plt.xlabel('Pivot Displacement')
    plt.ylabel('Perceived Displacemet')
コード例 #27
0
def plotForce():
    figure(size=3,aspect=0.5)
    subplot(1,2,1)
    from EvalTraj import plotFF
    plotFF(vp=351,t=28,f=900,cm=0.6,foffset=8)
    subplot_annotate()
    
    subplot(1,2,2)
    for i in [1,2,3,4]:
        R=np.squeeze(np.load('Rdpse%d.npy'%i))
        R=stats.nanmedian(R,axis=2)[:,1:,:]
        dps=np.linspace(-1,1,201)[1:]
        plt.plot(dps,R[:,:,2].mean(0));
    plt.legend([0,0.1,0.2,0.3],loc=3) 
    i=2
    R=np.squeeze(np.load('Rdpse%d.npy'%i))
    R=stats.nanmedian(R,axis=2)[:,1:,:]
    mn=np.argmin(R,axis=1)
    y=np.random.randn(mn.shape[0])*0.00002+0.0438
    plt.plot(np.sort(dps[mn[:,2]]),y,'+',mew=1,ms=6,mec=[ 0.39  ,  0.76,  0.64])
    plt.xlabel('Displacement of Force Origin')
    plt.ylabel('Average Net Force Magnitude')
    hh=dps[mn[:,2]]
    err=np.std(hh)/np.sqrt(hh.shape[0])*stats.t.ppf(0.975,hh.shape[0])
    err2=np.std(hh)/np.sqrt(hh.shape[0])*stats.t.ppf(0.75,hh.shape[0])
    m=np.mean(hh)
    print m, m-err,m+err
    np.save('force',[m, m-err,m+err,m-err2,m+err2])
    plt.xlim([-0.5,0.5])
    plt.ylim([0.0435,0.046])
    plt.grid(b=True,axis='x')
    subplot_annotate()
コード例 #28
0
def plot_sphere_x( s, fname ):
  """ put plot of ionization fractions from sphere `s` into fname """

  plt.figure()
  s.Edges.units = 'kpc'
  s.r_c.units = 'kpc'
  xx = s.r_c
  L = s.Edges[-1]

  plt.plot( xx, np.log10( s.xHe1 ),
            color='green', ls='-', label = r'$x_{\rm HeI}$' )
  plt.plot( xx, np.log10( s.xHe2 ),
            color='green', ls='--', label = r'$x_{\rm HeII}$' )
  plt.plot( xx, np.log10( s.xHe3 ),
            color='green', ls=':', label = r'$x_{\rm HeIII}$' )

  plt.plot( xx, np.log10( s.xH1 ),
            color='red', ls='-', label = r'$x_{\rm HI}$' )
  plt.plot( xx, np.log10( s.xH2 ),
            color='red', ls='--', label = r'$x_{\rm HII}$' )

  plt.xlim( -L/20, L+L/20 )
  plt.xlabel( 'r_c [kpc]' )

  plt.ylim( -4.5, 0.2 )
  plt.ylabel( 'log 10 ( x )' )

  plt.grid()
  plt.legend(loc='best', ncol=2)
  plt.tight_layout()
  plt.savefig( 'doc/img/x_' + fname )
コード例 #29
0
ファイル: omnibem.py プロジェクト: CancerRxGene/gdsctools
    def plot_number_alteration_by_tissue(self, fontsize=10, width=0.9):
        """Plot number of alterations

        .. plot::
            :width: 100%
            :include-source:

            from gdsctools import *
            data = gdsctools_data("test_omnibem_genomic_alterations.csv.gz")
            bem = OmniBEMBuilder(data)
            bem.filter_by_gene_list(gdsctools_data("test_omnibem_genes.txt"))
            bem.plot_number_alteration_by_tissue()

        """
        count = self.unified.groupby(['TISSUE_TYPE'])['GENE'].count()
        try:
            count.sort_values(inplace=True, ascending=False)
        except:
            count.sort(inplace=True, ascending=False)
        count.plot(kind="bar", width=width)
        pylab.grid()
        pylab.xlabel("Tissue Type", fontsize=fontsize)
        pylab.ylabel("Total number of alterations in cell lines",
                     fontsize=fontsize)
        try:pylab.tight_layout()
        except:pass
コード例 #30
0
def getOptCandGamma(cv_train, cv_label):
    print "Finding optimal C and gamma for SVM with RBF Kernel"
    C_range = 10.0 ** np.arange(-2, 9)
    gamma_range = 10.0 ** np.arange(-5, 4)
    param_grid = dict(gamma=gamma_range, C=C_range)
    cv = StratifiedKFold(y=cv_label, n_folds=40)

    # Use the svm.SVC() as the cost function to evaluate parameter choices
    # NOTE: Perhaps we should run computations in parallel if needed. Does it
    # do that already within the class?
    grid = GridSearchCV(svm.SVC(), param_grid=param_grid, cv=cv)
    grid.fit(cv_train, cv_label)

    score_dict = grid.grid_scores_
    scores = [x[1] for x in score_dict]
    scores = np.array(scores).reshape(len(C_range), len(gamma_range))
    pl.figure(figsize=(8,6))
    pl.subplots_adjust(left=0.05, right=0.95, bottom=0.15, top=0.95)
    pl.imshow(scores, interpolation='nearest', cmap=pl.cm.spectral)
    pl.xlabel('gamma')
    pl.ylabel('C')
    pl.colorbar()
    pl.xticks(np.arange(len(gamma_range)), gamma_range, rotation=45)
    pl.yticks(np.arange(len(C_range)), C_range)
    pl.show()

    print "The best classifier is: ", grid.best_estimator_
コード例 #31
0
import numpy
import pylab

select = 2

if select == 1:
    x = [0.5, 1, 2, 3, 4, 6, 8, 10, 15]
    y = [63.2, 58, 55.27, 53, 45.5, 41.7, 38.4, 29.8, 22]
    xl = 'Maximum Allowed Interrupt Rate (in KHz)'
    yl = 'Tx packet rate (in Kpps)'
    t = 'Tx packet rate as a function of the MAIR'

elif select == 2:
    x = [0.5, 1, 2, 3, 4, 6, 8, 9, 12, 15]
    y = [150, 182, 205, 185, 156, 110, 77, 59, 31, 14]
    xl = 'Maximum Allowed Interrupt Rate (in KHz)'
    yl = 'Rx critical rate (in Kpps)'
    t = 'Rx critical rate as a function of the MAIR'

pylab.plot(x, y)

pylab.xlabel(xl)
pylab.ylabel(yl)
pylab.title(t)
pylab.grid(True)
#pylab.savefig('simple_plot')

pylab.show()
コード例 #32
0
    def GasMassFunction(self, G):

        print('Plotting the cold gas mass function')

        plt.figure()  # New figure
        ax = plt.subplot(111)  # 1 plot on the figure

        binwidth = 0.1  # mass function histogram bin width

        # calculate all
        w = np.where(G.ColdGas > 0.0)[0]
        mass = np.log10(G.ColdGas[w] * 1.0e10 / self.Hubble_h)
        sSFR = (G.SfrDisk[w] + G.SfrBulge[w]) / (G.StellarMass[w] * 1.0e10 /
                                                 self.Hubble_h)
        mi = np.floor(min(mass)) - 2
        ma = np.floor(max(mass)) + 2
        NB = (ma - mi) / binwidth

        (counts, binedges) = np.histogram(mass, range=(mi, ma), bins=NB)

        # Set the x-axis values to be the centre of the bins
        xaxeshisto = binedges[:-1] + 0.5 * binwidth

        # additionally calculate red
        w = np.where(sSFR < 10.0**sSFRcut)[0]
        massRED = mass[w]
        (countsRED, binedges) = np.histogram(massRED, range=(mi, ma), bins=NB)

        # additionally calculate blue
        w = np.where(sSFR > 10.0**sSFRcut)[0]
        massBLU = mass[w]
        (countsBLU, binedges) = np.histogram(massBLU, range=(mi, ma), bins=NB)

        # Baldry+ 2008 modified data used for the MCMC fitting
        Zwaan = np.array([[6.933, -0.333], [7.057, -0.490], [7.209, -0.698],
                          [7.365, -0.667], [7.528, -0.823], [7.647, -0.958],
                          [7.809, -0.917], [7.971, -0.948], [8.112, -0.927],
                          [8.263, -0.917], [8.404, -1.062], [8.566, -1.177],
                          [8.707, -1.177], [8.853, -1.312], [9.010, -1.344],
                          [9.161, -1.448], [9.302, -1.604], [9.448, -1.792],
                          [9.599, -2.021], [9.740, -2.406], [9.897, -2.615],
                          [10.053, -3.031], [10.178, -3.677], [10.335, -4.448],
                          [10.492, -5.083]],
                         dtype=np.float32)

        ObrRaw = np.array([[7.300, -1.104], [7.576, -1.302], [7.847, -1.250],
                           [8.133, -1.240], [8.409, -1.344], [8.691, -1.479],
                           [8.956, -1.792], [9.231, -2.271], [9.507, -3.198],
                           [9.788, -5.062]],
                          dtype=np.float32)

        ObrCold = np.array([[8.009, -1.042], [8.215, -1.156], [8.409, -0.990],
                            [8.604, -1.156], [8.799, -1.208], [9.020, -1.333],
                            [9.194, -1.385], [9.404, -1.552], [9.599, -1.677],
                            [9.788, -1.812], [9.999, -2.312], [10.172, -2.656],
                            [10.362, -3.500], [10.551, -3.635],
                            [10.740, -5.010]],
                           dtype=np.float32)

        ObrCold_xval = np.log10(10**(ObrCold[:, 0]) / self.Hubble_h /
                                self.Hubble_h)
        ObrCold_yval = (10**(ObrCold[:, 1]) * self.Hubble_h * self.Hubble_h *
                        self.Hubble_h)
        Zwaan_xval = np.log10(10**(Zwaan[:, 0]) / self.Hubble_h /
                              self.Hubble_h)
        Zwaan_yval = (10**(Zwaan[:, 1]) * self.Hubble_h * self.Hubble_h *
                      self.Hubble_h)
        ObrRaw_xval = np.log10(10**(ObrRaw[:, 0]) / self.Hubble_h /
                               self.Hubble_h)
        ObrRaw_yval = (10**(ObrRaw[:, 1]) * self.Hubble_h * self.Hubble_h *
                       self.Hubble_h)

        plt.plot(ObrCold_xval,
                 ObrCold_yval,
                 color='black',
                 lw=7,
                 alpha=0.25,
                 label='Obr. \& Raw. 2009 (Cold Gas)')
        plt.plot(Zwaan_xval,
                 Zwaan_yval,
                 color='cyan',
                 lw=7,
                 alpha=0.25,
                 label='Zwaan et al. 2005 (HI)')
        plt.plot(ObrRaw_xval,
                 ObrRaw_yval,
                 color='magenta',
                 lw=7,
                 alpha=0.25,
                 label='Obr. \& Raw. 2009 (H2)')

        # Overplot the model histograms
        plt.plot(xaxeshisto,
                 counts / self.volume * self.Hubble_h * self.Hubble_h *
                 self.Hubble_h / binwidth,
                 'k-',
                 label='Model - Cold Gas')

        plt.yscale('log', nonposy='clip')
        plt.axis([8.0, 11.5, 1.0e-6, 1.0e-1])

        # Set the x-axis minor ticks
        ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))

        plt.ylabel(
            r'$\phi\ (\mathrm{Mpc}^{-3}\ \mathrm{dex}^{-1})$')  # Set the y...
        plt.xlabel(r'$\log_{10} M_{\mathrm{X}}\ (M_{\odot})$'
                   )  # and the x-axis labels

        leg = plt.legend(loc='lower left', numpoints=1, labelspacing=0.1)
        leg.draw_frame(False)  # Don't want a box frame
        for t in leg.get_texts():  # Reduce the size of the text
            t.set_fontsize('medium')

        outputFile = OutputDir + '3.GasMassFunction' + OutputFormat
        plt.savefig(outputFile)  # Save the figure
        print('Saved file to', outputFile)
        plt.close()

        # Add this plot to our output list
        OutputList.append(outputFile)
コード例 #33
0
    def BaryonicMassFunction(self, G):

        print('Plotting the baryonic mass function')

        plt.figure()  # New figure
        ax = plt.subplot(111)  # 1 plot on the figure

        binwidth = 0.1  # mass function histogram bin width

        # calculate BMF
        w = np.where(G.StellarMass + G.ColdGas > 0.0)[0]
        mass = np.log10(
            (G.StellarMass[w] + G.ColdGas[w]) * 1.0e10 / self.Hubble_h)

        mi = np.floor(min(mass)) - 2
        ma = np.floor(max(mass)) + 2
        NB = (ma - mi) / binwidth

        (counts, binedges) = np.histogram(mass, range=(mi, ma), bins=NB)

        # Set the x-axis values to be the centre of the bins
        xaxeshisto = binedges[:-1] + 0.5 * binwidth

        # Bell et al. 2003 BMF (h=1.0 converted to h=0.73)
        M = np.arange(7.0, 13.0, 0.01)
        Mstar = np.log10(5.3 * 1.0e10 / self.Hubble_h / self.Hubble_h)
        alpha = -1.21
        phistar = 0.0108 * self.Hubble_h * self.Hubble_h * self.Hubble_h
        xval = 10.0**(M - Mstar)
        yval = np.log(10.) * phistar * xval**(alpha + 1) * np.exp(-xval)

        if (whichimf == 0):
            # converted diet Salpeter IMF to Salpeter IMF
            plt.plot(np.log10(10.0**M / 0.7),
                     yval,
                     'b-',
                     lw=2.0,
                     label='Bell et al. 2003')  # Plot the SMF
        elif (whichimf == 1):
            # converted diet Salpeter IMF to Salpeter IMF, then to Chabrier IMF
            plt.plot(np.log10(10.0**M / 0.7 / 1.8),
                     yval,
                     'g--',
                     lw=1.5,
                     label='Bell et al. 2003')  # Plot the SMF

        # Overplot the model histograms
        plt.plot(xaxeshisto,
                 counts / self.volume * self.Hubble_h * self.Hubble_h *
                 self.Hubble_h / binwidth,
                 'k-',
                 label='Model')

        plt.yscale('log', nonposy='clip')
        plt.axis([8.0, 12.5, 1.0e-6, 1.0e-1])

        # Set the x-axis minor ticks
        ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))

        plt.ylabel(
            r'$\phi\ (\mathrm{Mpc}^{-3}\ \mathrm{dex}^{-1})$')  # Set the y...
        plt.xlabel(r'$\log_{10}\ M_{\mathrm{bar}}\ (M_{\odot})$'
                   )  # and the x-axis labels

        leg = plt.legend(loc='lower left', numpoints=1, labelspacing=0.1)
        leg.draw_frame(False)  # Don't want a box frame
        for t in leg.get_texts():  # Reduce the size of the text
            t.set_fontsize('medium')

        outputFile = OutputDir + '2.BaryonicMassFunction' + OutputFormat
        plt.savefig(outputFile)  # Save the figure
        print('Saved file to', outputFile)
        plt.close()

        # Add this plot to our output list
        OutputList.append(outputFile)
コード例 #34
0
    def StellarMassFunction(self, G):

        print('Plotting the stellar mass function')

        plt.figure()  # New figure
        ax = plt.subplot(111)  # 1 plot on the figure

        binwidth = 0.1  # mass function histogram bin width

        # calculate all
        w = np.where(G.StellarMass > 0.0)[0]
        mass = np.log10(G.StellarMass[w] * 1.0e10 / self.Hubble_h)
        sSFR = (G.SfrDisk[w] + G.SfrBulge[w]) / (G.StellarMass[w] * 1.0e10 /
                                                 self.Hubble_h)

        mi = np.floor(min(mass)) - 2
        ma = np.floor(max(mass)) + 2
        NB = (ma - mi) / binwidth

        (counts, binedges) = np.histogram(mass, range=(mi, ma), bins=NB)

        # Set the x-axis values to be the centre of the bins
        xaxeshisto = binedges[:-1] + 0.5 * binwidth

        # additionally calculate red
        w = np.where(sSFR < 10.0**sSFRcut)[0]
        massRED = mass[w]
        (countsRED, binedges) = np.histogram(massRED, range=(mi, ma), bins=NB)

        # additionally calculate blue
        w = np.where(sSFR > 10.0**sSFRcut)[0]
        massBLU = mass[w]
        (countsBLU, binedges) = np.histogram(massBLU, range=(mi, ma), bins=NB)

        # Baldry+ 2008 modified data used for the MCMC fitting
        Baldry = np.array([
            [7.05, 1.3531e-01, 6.0741e-02],
            [7.15, 1.3474e-01, 6.0109e-02],
            [7.25, 2.0971e-01, 7.7965e-02],
            [7.35, 1.7161e-01, 3.1841e-02],
            [7.45, 2.1648e-01, 5.7832e-02],
            [7.55, 2.1645e-01, 3.9988e-02],
            [7.65, 2.0837e-01, 4.8713e-02],
            [7.75, 2.0402e-01, 7.0061e-02],
            [7.85, 1.5536e-01, 3.9182e-02],
            [7.95, 1.5232e-01, 2.6824e-02],
            [8.05, 1.5067e-01, 4.8824e-02],
            [8.15, 1.3032e-01, 2.1892e-02],
            [8.25, 1.2545e-01, 3.5526e-02],
            [8.35, 9.8472e-02, 2.7181e-02],
            [8.45, 8.7194e-02, 2.8345e-02],
            [8.55, 7.0758e-02, 2.0808e-02],
            [8.65, 5.8190e-02, 1.3359e-02],
            [8.75, 5.6057e-02, 1.3512e-02],
            [8.85, 5.1380e-02, 1.2815e-02],
            [8.95, 4.4206e-02, 9.6866e-03],
            [9.05, 4.1149e-02, 1.0169e-02],
            [9.15, 3.4959e-02, 6.7898e-03],
            [9.25, 3.3111e-02, 8.3704e-03],
            [9.35, 3.0138e-02, 4.7741e-03],
            [9.45, 2.6692e-02, 5.5029e-03],
            [9.55, 2.4656e-02, 4.4359e-03],
            [9.65, 2.2885e-02, 3.7915e-03],
            [9.75, 2.1849e-02, 3.9812e-03],
            [9.85, 2.0383e-02, 3.2930e-03],
            [9.95, 1.9929e-02, 2.9370e-03],
            [10.05, 1.8865e-02, 2.4624e-03],
            [10.15, 1.8136e-02, 2.5208e-03],
            [10.25, 1.7657e-02, 2.4217e-03],
            [10.35, 1.6616e-02, 2.2784e-03],
            [10.45, 1.6114e-02, 2.1783e-03],
            [10.55, 1.4366e-02, 1.8819e-03],
            [10.65, 1.2588e-02, 1.8249e-03],
            [10.75, 1.1372e-02, 1.4436e-03],
            [10.85, 9.1213e-03, 1.5816e-03],
            [10.95, 6.1125e-03, 9.6735e-04],
            [11.05, 4.3923e-03, 9.6254e-04],
            [11.15, 2.5463e-03, 5.0038e-04],
            [11.25, 1.4298e-03, 4.2816e-04],
            [11.35, 6.4867e-04, 1.6439e-04],
            [11.45, 2.8294e-04, 9.9799e-05],
            [11.55, 1.0617e-04, 4.9085e-05],
            [11.65, 3.2702e-05, 2.4546e-05],
            [11.75, 1.2571e-05, 1.2571e-05],
            [11.85, 8.4589e-06, 8.4589e-06],
            [11.95, 7.4764e-06, 7.4764e-06],
        ],
                          dtype=np.float32)

        # Finally plot the data
        # plt.errorbar(
        #     Baldry[:, 0],
        #     Baldry[:, 1],
        #     yerr=Baldry[:, 2],
        #     color='g',
        #     linestyle=':',
        #     lw = 1.5,
        #     label='Baldry et al. 2008',
        #     )

        Baldry_xval = np.log10(10**Baldry[:, 0] / self.Hubble_h /
                               self.Hubble_h)
        if (whichimf == 1):
            Baldry_xval = Baldry_xval - 0.26  # convert back to Chabrier IMF
        Baldry_yvalU = (Baldry[:, 1] + Baldry[:, 2]
                        ) * self.Hubble_h * self.Hubble_h * self.Hubble_h
        Baldry_yvalL = (Baldry[:, 1] - Baldry[:, 2]
                        ) * self.Hubble_h * self.Hubble_h * self.Hubble_h

        plt.fill_between(Baldry_xval,
                         Baldry_yvalU,
                         Baldry_yvalL,
                         facecolor='purple',
                         alpha=0.25,
                         label='Baldry et al. 2008 (z=0.1)')

        # This next line is just to get the shaded region to appear correctly in the legend
        plt.plot(xaxeshisto,
                 counts / self.volume * self.Hubble_h * self.Hubble_h *
                 self.Hubble_h / binwidth,
                 label='Baldry et al. 2008',
                 color='purple',
                 alpha=0.3)

        # # Cole et al. 2001 SMF (h=1.0 converted to h=0.73)
        # M = np.arange(7.0, 13.0, 0.01)
        # Mstar = np.log10(7.07*1.0e10 /self.Hubble_h/self.Hubble_h)
        # alpha = -1.18
        # phistar = 0.009 *self.Hubble_h*self.Hubble_h*self.Hubble_h
        # xval = 10.0 ** (M-Mstar)
        # yval = np.log(10.) * phistar * xval ** (alpha+1) * np.exp(-xval)
        # plt.plot(M, yval, 'g--', lw=1.5, label='Cole et al. 2001')  # Plot the SMF

        # Overplot the model histograms
        plt.plot(xaxeshisto,
                 counts / self.volume * self.Hubble_h * self.Hubble_h *
                 self.Hubble_h / binwidth,
                 'k-',
                 label='Model - All')
        plt.plot(xaxeshisto,
                 countsRED / self.volume * self.Hubble_h * self.Hubble_h *
                 self.Hubble_h / binwidth,
                 'r:',
                 lw=2,
                 label='Model - Red')
        plt.plot(xaxeshisto,
                 countsBLU / self.volume * self.Hubble_h * self.Hubble_h *
                 self.Hubble_h / binwidth,
                 'b:',
                 lw=2,
                 label='Model - Blue')

        plt.yscale('log', nonposy='clip')
        plt.axis([8.0, 12.5, 1.0e-6, 1.0e-1])

        # Set the x-axis minor ticks
        ax.xaxis.set_minor_locator(plt.MultipleLocator(0.1))

        plt.ylabel(
            r'$\phi\ (\mathrm{Mpc}^{-3}\ \mathrm{dex}^{-1})$')  # Set the y...
        plt.xlabel(r'$\log_{10} M_{\mathrm{stars}}\ (M_{\odot})$'
                   )  # and the x-axis labels

        plt.text(12.2, 0.03, whichsimulation, size='large')

        leg = plt.legend(loc='lower left', numpoints=1, labelspacing=0.1)
        leg.draw_frame(False)  # Don't want a box frame
        for t in leg.get_texts():  # Reduce the size of the text
            t.set_fontsize('medium')

        outputFile = OutputDir + '1.StellarMassFunction' + OutputFormat
        plt.savefig(outputFile)  # Save the figure
        print('Saved file to', outputFile)
        plt.close()

        # Add this plot to our output list
        OutputList.append(outputFile)
コード例 #35
0
    def VelocityDistribution(self, G):

        print('Plotting the velocity distribution of all galaxies')

        seed(2222)

        mi = -40.0
        ma = 40.0
        binwidth = 0.5
        NB = (ma - mi) / binwidth

        # set up figure
        plt.figure()
        ax = plt.subplot(111)

        pos_x = G.Pos[:, 0] / self.Hubble_h
        pos_y = G.Pos[:, 1] / self.Hubble_h
        pos_z = G.Pos[:, 2] / self.Hubble_h

        vel_x = G.Vel[:, 0]
        vel_y = G.Vel[:, 1]
        vel_z = G.Vel[:, 2]

        dist_los = np.sqrt(pos_x * pos_x + pos_y * pos_y + pos_z * pos_z)
        vel_los = (pos_x / dist_los) * vel_x + (pos_y / dist_los) * vel_y + (
            pos_z / dist_los) * vel_z
        dist_red = dist_los + vel_los / (self.Hubble_h * 100.0)

        tot_gals = len(pos_x)

        (counts, binedges) = np.histogram(vel_los / (self.Hubble_h * 100.0),
                                          range=(mi, ma),
                                          bins=NB)
        xaxeshisto = binedges[:-1] + 0.5 * binwidth
        plt.plot(xaxeshisto,
                 counts / binwidth / tot_gals,
                 'k-',
                 label='los-velocity')

        (counts, binedges) = np.histogram(vel_x / (self.Hubble_h * 100.0),
                                          range=(mi, ma),
                                          bins=NB)
        xaxeshisto = binedges[:-1] + 0.5 * binwidth
        plt.plot(xaxeshisto,
                 counts / binwidth / tot_gals,
                 'r-',
                 label='x-velocity')

        (counts, binedges) = np.histogram(vel_y / (self.Hubble_h * 100.0),
                                          range=(mi, ma),
                                          bins=NB)
        xaxeshisto = binedges[:-1] + 0.5 * binwidth
        plt.plot(xaxeshisto,
                 counts / binwidth / tot_gals,
                 'g-',
                 label='y-velocity')

        (counts, binedges) = np.histogram(vel_z / (self.Hubble_h * 100.0),
                                          range=(mi, ma),
                                          bins=NB)
        xaxeshisto = binedges[:-1] + 0.5 * binwidth
        plt.plot(xaxeshisto,
                 counts / binwidth / tot_gals,
                 'b-',
                 label='z-velocity')

        plt.yscale('log', nonposy='clip')
        plt.axis([mi, ma, 1e-5, 0.5])
        # plt.axis([mi, ma, 0, 0.13])

        plt.ylabel(r'$\mathrm{Box\ Normalised\ Count}$')  # Set the y...
        plt.xlabel(r'$\mathrm{Velocity / H}_{0}$')  # and the x-axis labels

        leg = plt.legend(loc='upper left', numpoints=1, labelspacing=0.1)
        leg.draw_frame(False)  # Don't want a box frame
        for t in leg.get_texts():  # Reduce the size of the text
            t.set_fontsize('medium')

        outputFile = OutputDir + '11.VelocityDistribution' + OutputFormat
        plt.savefig(outputFile)  # Save the figure
        print('Saved file to', outputFile)
        plt.close()

        # Add this plot to our output list
        OutputList.append(outputFile)
コード例 #36
0
def display_2nd_moments(data=None):
    # remove the mean for all moments
    data = subMeanAll(data)
    pl.figure(figsize=(11, 5.5))
    pl.subplot(1, 2, 1)
    phi22 = 0.5 * np.arctan2(data[:, 3].imag, data[:, 3].real)
    x = data[:, 0].real
    y = data[:, 1].real
    phi22[x < 0] = phi22 + np.deg2rad(180)
    u = np.abs(data[:, 3]) * np.cos(phi22)
    v = np.abs(data[:, 3]) * np.sin(phi22)
    qvr = pl.quiver(x,
                    y,
                    u,
                    v,
                    width=0.004,
                    color='r',
                    pivot='middle',
                    headwidth=0.,
                    headlength=0.,
                    headaxislength=0.,
                    scale_units='width')
    qk = pl.quiverkey(qvr,
                      -150,
                      -240,
                      np.max(np.sqrt(u**2 + v**2)),
                      str(round(np.max(np.sqrt(u**2 + v**2)), 3)) + ' pix^2',
                      coordinates='data',
                      color='blue')
    pl.plot(x, y, 'b,')
    pl.xlim(-250, 250)
    pl.ylim(-250, 250)
    pl.grid(color='g')
    pl.xlabel('X [mm] (WEST)')
    pl.ylabel('Y [mm] (NORTH)')
    pl.title('M22')
    pl.subplot(1, 2, 2)
    m20sqr = np.sqrt(data[:, 2].real)
    x = data[:, 0].real
    y = data[:, 1].real
    m20sqr_med = np.median(m20sqr)
    m20sqr_diff = m20sqr - m20sqr_med
    m20sqr_diff_absmed = np.median(np.abs(m20sqr_diff))
    plotScale = 1. / m20sqr_diff_absmed * 100
    pos = m20sqr_diff >= 0
    neg = m20sqr_diff < 0
    pl.scatter(x[pos],
               y[pos],
               s=m20sqr_diff[pos] * plotScale,
               c='r',
               alpha=0.5)
    pl.scatter(x[neg],
               y[neg],
               s=-m20sqr_diff[neg] * plotScale,
               c='b',
               alpha=0.5)
    pl.scatter(-230, -210, s=m20sqr_diff_absmed * plotScale, c='b', alpha=0.5)
    pl.text(-200, -215, '-' + str(round(m20sqr_diff_absmed, 6)) + ' pix')
    pl.scatter(-230, -230, s=m20sqr_diff_absmed * plotScale, c='r', alpha=0.5)
    pl.text(-200, -235, str(round(m20sqr_diff_absmed, 6)) + ' pix')
    pl.plot(x, y, 'y,')
    pl.grid(color='g')
    pl.xlim(-250, 250)
    pl.ylim(-250, 250)
    pl.xlabel('X [mm] (WEST)')
    pl.ylabel('Y [mm] (NORTH)')
    pl.title('median ' + r'$\sqrt{M20}$: ' +
             str(round(scale * m20sqr_med, 3)) + ' [arcsec]')
    return '---done!--'
コード例 #37
0
    pl.grid()
    pl.title('mag: 15, CCD: S4, Truth')
    pl.subplot(2, 1, 2)
    pl.boxplot(momtsWTrue.imag)
    pl.xticks(np.arange(1, 5),
              ['M20.imag', 'M22.imag', 'M31.imag', 'M33.imag'])
    pl.grid()

    #----distribution ----
    pl.figure(figsize=(15, 9))
    pl.subplot(2, 3, 1)
    pl.hist(momtsW[:, 0].real, bins=10, normed=False)
    pl.title(
        str(round(np.mean(momtsW[:, 0].real), 6)) + r'$\pm$' +
        str(round(np.std(momtsW[:, 0].real) / np.sqrt(momtsW.shape[0]), 6)))
    pl.xlabel('Wmoment M20')
    pl.subplot(2, 3, 2)
    pl.hist(momtsW[:, 1].real, bins=10, normed=False)
    pl.title(
        str(round(np.mean(momtsW[:, 1].real), 6)) + r'$\pm$' +
        str(round(np.std(momtsW[:, 1].real) / np.sqrt(momtsW.shape[0]), 6)))
    pl.xlabel('Wmoment M22.real')
    pl.subplot(2, 3, 3)
    pl.hist(momtsW[:, 1].imag, bins=10, normed=False)
    pl.title(
        str(round(np.mean(momtsW[:, 1].imag), 6)) + r'$\pm$' +
        str(round(np.std(momtsW[:, 1].imag) / np.sqrt(momtsW.shape[0]), 6)))
    pl.xlabel('Wmoment M22.imag')
    pl.subplot(2, 3, 4)
    pl.hist(momtsA[:, 0].real, bins=10, normed=False)
    pl.title(
コード例 #38
0
if __name__ == '__main__':
    # Simple convergence demo.

    # A few modules we need
    import pylab as P
    import numpy as N

    # Create a list of points 'nrange' where we'll compute Wallis' formula
    nrange = N.linspace(10, 2000, 20).astype(int)
    # Make an array of such values
    wpi = N.array(map(pi, nrange))
    # Compute the difference against the value of pi in numpy (standard
    # 16-digit value)
    diff = abs(wpi - N.pi)

    # Make a new figure and build a semilog plot of the difference so we can
    # see the quality of the convergence

    P.figure()
    # Line plot with red circles at the data points
    P.semilogy(nrange, diff, '-o', mfc='red')

    # A bit of labeling and a grid
    P.title(r"Convergence of Wallis' product formula for $\pi$")
    P.xlabel('Number of terms')
    P.ylabel(r'Absolute Error')
    P.grid()

    # Display the actual plot
    P.show()
コード例 #39
0
Z = sum(rho[j, j] for j in range(nx + 1)) * dx
pi_of_x = [rho[j, j] / Z for j in range(nx + 1)]

# graphics
'''
y = [j * dtau for j in range(N)]
pylab.plot(x, y, 'b-')
pylab.xlabel('$x$', fontsize=18)
pylab.ylabel('$\\tau$', fontsize=18)
pylab.title('Levi harmonic path, N= %i, $\\beta$ = %.0f'%(N, beta))
pylab.xlim(-3.0, 3.0)
pylab.savefig('plot_B2_levi_path_beta%s.png' % beta)
pylab.show()
'''

pylab.hist(data, density=True, bins=200, label='Levi-path')
pylab.plot(x, pi_of_x, label='matrix-square')
list_x = [0.1 * a for a in range(-30, 31)]
list_y = [math.sqrt(math.tanh(beta / 2.0)) / math.sqrt(math.pi) * \
          math.exp(-x ** 2 * math.tanh(beta / 2.0)) for x in list_x]
#pylab.plot(list_x, list_y, label='analytic')
pylab.legend()
pylab.xlabel('$x$')
pylab.ylabel('$\\pi(x)$ (normalized)')
pylab.title(
    'metro_levi_free_anharmonic\n(beta=%s, N=%i, n_steps=%i, Ncut=%i)' %
    (beta, N, n_steps, Ncut))
pylab.xlim(-2, 2)
pylab.savefig('plot_C1_metro_levi_free.png')
pylab.show()
コード例 #40
0
ファイル: anaCR.py プロジェクト: jlzhang001/simulations
  seffta[i] = np.trapz(seffpa*np.sin(th*pi/180),th*pi/180)
  sefftc[i] = np.trapz(seffpc*np.sin(th*pi/180),th*pi/180)
  sefftopt[i] = np.trapz(seffpopt*np.sin(th*pi/180),th*pi/180)
  
## Compute event rate
print ''
ee = pow(10,eu)
print 'Energy:',ee,'eV'
print 'Apperture (agressive):',seffta,'km2.sr'
print 'Apperture (conservative):',sefftc,'km2.sr'
print 'Optimal apperture:',sefftopt[0],'km2.sr'
pl.figure(2)
pl.plot(eu,seffta,label='Agressive')
pl.plot(eu,sefftc,label='Conservative')
pl.plot(eu,sefftopt,label='Optimal')
pl.xlabel('Energy (eV)')
pl.ylabel('Apperture (km$^2$.sr)')
pl.grid(True)
pl.legend(loc='best')
pl.title("GRAND CR apperture")
#pl.show() 

seffta = seffta*1e6  #m2
sefftc = sefftc*1e6  #m2
sefftopt = sefftopt*1e6  #m2
dt = 3600*24*ndays  #1 day
evt1da = np.trapz(seffta*J1*pow(ee,-gamma1)*dt,ee)
evt1dc = np.trapz(sefftc*J1*pow(ee,-gamma1)*dt,ee)
evt1dopt = np.trapz(sefftopt*J1*pow(ee,-gamma1)*dt,ee)
print 'Expected daily event rate in 10^17-10^18eV (agressive):',evt1da
print 'Expected daily event rate in 10^17-10^18eV (conservative):',evt1dc
コード例 #41
0
set_weights_bias2((100, 10), X.dtype, w4, b4)

for i in range(noIters):
    trX, trY = shuffle_data(trX, trY)
    for start, end in zip(range(0, len(trX), batch_size),
                          range(batch_size, len(trX), batch_size)):
        cost = train3(trX[start:end], trY[start:end])
    a3.append(np.mean(np.argmax(teY, axis=1) == predict(teX)))
    trainCost3.append(cost / (len(trX) // batch_size))
    print(a[i])

pylab.figure()
pylab.plot(range(noIters), a, label='SGD')
pylab.plot(range(noIters), a2, label='SGD with momentum')
pylab.plot(range(noIters), a3, label='RMSprop')
pylab.xlabel('epochs')
pylab.ylabel('test accuracy')
pylab.legend(loc='lower right')
pylab.title('test accuracy ')
pylab.savefig('testAccuracy')

pylab.figure()
pylab.plot(range(noIters), trainCost, label='SGD')
pylab.plot(range(noIters), trainCost2, label='SGD with momentum')
pylab.plot(range(noIters), trainCost3, label='RMSprop')
pylab.xlabel('epochs')
pylab.ylabel('training cost')
pylab.legend(loc='upper right')
pylab.title('training cost')
pylab.savefig('trainingCost')
コード例 #42
0
        residual3 = delta_tensor_norm(statistic_res, check_tensor)

        x_values.append(train_percent)
        y_values1.append(residual1)
        y_values2.append(residual2)
        y_values3.append(residual3)
        train_percent += 0.2

    pylab.plot(x_values,
               y_values1,
               'rs',
               linewidth=1,
               linestyle="-",
               label=u"MTT")
    pylab.plot(x_values,
               y_values2,
               'ks',
               linewidth=1,
               linestyle="-",
               label=u"DTA")
    pylab.plot(x_values,
               y_values3,
               'gs',
               linewidth=1,
               linestyle="-",
               label=u"Baseline")
    pylab.xlabel(u"训练集比重")
    pylab.ylabel(u"平均误差")
    pylab.title(u"训练集比重与平均误差的关系")
    pylab.legend(loc='center right')
    pylab.show()
コード例 #43
0
ファイル: plot2.py プロジェクト: AlexanderToifl/RIV
def lin_fit(crvfile,
            refcrvfile,
            outname,
            dump_frequency,
            Er,
            Ed,
            recoil_relaxation_time=10000,
            start_timeoffset=500):

    crv = CRV.CRV(crvfile)[0]
    eps = crv['lz']
    x = crv['step']
    pyy = crv['pyy']
    n_atoms = crv['atoms'][0]

    crv1 = CRV.CRV(refcrvfile)[0]
    eps_ref = crv1['lz']

    #  eps = np.subtract(eps,eps_ref)

    print eps

    nrecoils = []

    #pressure tensor component
    pxx = []
    ezz = []
    ezz_ref = []

    dump_factor = int(recoil_relaxation_time / dump_frequency)

    pressure_conversion = 1e9  #GPa -> Pa

    #reduce timeaxis to recoil axis
    for i in range(len(x) / dump_factor):
        nrecoils.append((x[i * dump_factor] - start_timeoffset) /
                        float(recoil_relaxation_time))
        pxx.append(pyy[i * dump_factor] * pressure_conversion)
        # ezz.append(((eps[i*dump_factor] - eps[0])/eps[0] - (eps_ref[i*dump_factor] - eps_ref[0])/eps_ref[0]))
        # ezz.append(abs( (eps[i*dump_factor] -eps_ref[i*dump_factor])/ (eps[0] - eps_ref[0])))
        ezz.append(((-eps[dump_factor] + eps[i * dump_factor])))
        ezz_ref.append(((-eps_ref[dump_factor] + eps_ref[i * dump_factor])))

    del nrecoils[0]
    del pxx[0]
    del ezz[0]
    del ezz_ref[0]

    #number of displacements per target atom
    ndpa = np.multiply(nrecoils, (Er / (2.5 * Ed * n_atoms)))

    fit_start = 0
    fit_end = 20

    dezz = np.multiply(np.subtract(ezz, ezz_ref), 1. / eps[dump_factor])

    #fit1
    popt1, pcov1 = opt.curve_fit(
        lambda ndpa, eta, offset: eta_lin(ndpa, pxx[0], eta, offset),
        ndpa[fit_start:fit_end], dezz[fit_start:fit_end])
    #popt1 = [1,1]

    #fit2
    # popt2, pcov2 = opt.curve_fit( lambda ndpa,eta,offset: eta_lin(ndpa,pxx[0],eta,offset), ndpa[0:fit_start], ezz[0:fit_start])
    #popt2 = [1,1]
    #anotate to add value to plot
    # print 'RIV (lin)= {:.4e}'.format(popt1[0])

    # npa interpolated
    ndpa_interp = np.linspace(0, ndpa[-1] * 1.5, 1000)

    fig = plt.figure(1, figsize=fsize)

    plt.xlim(0, ndpa_interp[-1])

    # plt.ylim(ezz[-1]*0.8, ezz[-1]*1.1)

    plt.grid()

    plt.plot(ndpa[fit_start:fit_end],
             dezz[fit_start:fit_end],
             'bs',
             markeredgecolor='blue',
             markerfacecolor='None',
             markeredgewidth=mew,
             markersize=ms,
             label='MD Simulation')
    # plt.plot(ndpa, ezz_ref, 'bs', markeredgecolor = 'magenta',  markerfacecolor= 'None', markeredgewidth=mew,  markersize = ms,  label = 'MD Simulation Reference')
    plt.plot(ndpa_interp,
             eta_lin(ndpa_interp, pxx[0], *popt1),
             'r-',
             linewidth=lw,
             label='Fit')
    #  plt.plot(ndpa_interp, eta_lin(ndpa_interp,pxx[0],*popt2), '-', color = 'black', linewidth = lw, label='Fit2')
    plt.xlabel('Number of displacements per atom')
    plt.ylabel(r'$ \Delta \varepsilon_{zz} $')

    # legtitle  = r'$ \eta_{ri,1} = $' + '{:.4e}'.format(popt1[0]) + ' $ \mathrm{Pa \cdot dpa} $' + '\n' +  r'$ \eta_{ri,2} = $' + '{:.4e}'.format(popt2[0]) + ' $ \mathrm{Pa \cdot dpa} $' + '\n'r'$\sigma_0 = $' + '{:.2e}'.format(abs(pxx[0])) + r'$\,\mathrm{Pa}$' + '\n' +  r'$E_D = ' + '{:.1e}'.format(Ed) + 'eV $'+ '\n' + r'$ E_R = $' + '{:.1e}'.format(Er) + ' $ eV $'
    legtitle = r'$ \eta^\prime = $' + '{:.4e}'.format(
        popt1[0]
    ) + ' $ \mathrm{Pa \cdot dpa} $' + '\n' r'$\sigma_0 = $' + '{:.2e}'.format(
        abs(pxx[0])
    ) + r'$\,\mathrm{Pa}$' + '\n' + r'$E_D = ' + '{:.1e}'.format(
        Ed) + '\mathrm{eV} $' + '\n' + r'$ E_R = $' + '{:.1e}'.format(
            Er) + ' $ \mathrm{eV} $'
    plt.legend(loc='best',
               shadow=False,
               title=legtitle,
               prop={'size': legpropsize},
               numpoints=1)

    #every other tick label
    for label in plt.gca().xaxis.get_ticklabels()[::2]:
        label.set_visible(False)

    #plt.show()
    fig.tight_layout()
    fig.savefig(outname)
    print "Png file written to " + outname
    plt.close("all")
コード例 #44
0
# extract the time course for different labels from the stc
stc_lh = stc.in_label(aud_lh)
stc_rh = stc.in_label(aud_rh)
stc_bh = stc.in_label(aud_lh + aud_rh)

# calculate center of mass and transform to mni coordinates
vtx, _, t_lh = stc_lh.center_of_mass('sample')
mni_lh = mne.vertex_to_mni(vtx, 0, 'sample')[0]
vtx, _, t_rh = stc_rh.center_of_mass('sample')
mni_rh = mne.vertex_to_mni(vtx, 1, 'sample')[0]

# plot the activation
pl.figure()
pl.axes([.1, .275, .85, .625])
hl = pl.plot(stc.times, stc_lh.data.mean(0), 'b')
hr = pl.plot(stc.times, stc_rh.data.mean(0), 'g')
hb = pl.plot(stc.times, stc_bh.data.mean(0), 'r')
pl.xlabel('Time (s)')
pl.ylabel('Source amplitude (dSPM)')
pl.xlim(stc.times[0], stc.times[-1])

# add a legend including center-of-mass mni coordinates to the plot
labels = [
    'LH: center of mass = %s' % mni_lh.round(2),
    'RH: center of mass = %s' % mni_rh.round(2), 'Combined LH & RH'
]
pl.figlegend([hl, hr, hb], labels, 'lower center')
pl.suptitle('Average activation in auditory cortex labels', fontsize=20)
pl.show()
コード例 #45
0
        U, S, D = HOSVD(numpy.array(tensor), 0.7)

        A = reconstruct(S, U)
        print "reconstruct tensor: ", A
        print frobenius_norm(tensor-A)

        avg_precision, avg_recall, avg_f1_score, availability = recommend(A, recommends, unknow_poi_set, time_slice, top_k, order)
        print "avg_precision: ", avg_precision
        print "avg_recall: ", avg_recall
        print "avg_f1_score: ", avg_f1_score
        print "availability: ", availability

        y_values1.append(avg_precision)
        y_values2.append(avg_recall)
        y_values3.append(avg_f1_score)
        y_values4.append(availability)
        x_values.append(cluster_radius)
        cluster_radius += 0.1

    pylab.plot(x_values, y_values1, 'rs', linewidth=1, linestyle="-", label=u"准确率")
    pylab.plot(x_values, y_values2, 'gs', linewidth=1, linestyle="-", label=u"召回率")
    pylab.plot(x_values, y_values3, 'bs', linewidth=1, linestyle="-", label=u"f1值")
    # pylab.plot(x_values, y_values4, 'ks', linewidth=1, linestyle="-", label=u"可用率")
    pylab.xlabel(u"poi近邻集合的半径(km)")
    pylab.ylabel(u"准确率-召回率")
    pylab.title(u"poi近邻集合的半径与准确率-召回率之间的关系")
    pylab.legend(loc='center right')
    # pylab.xlim(1, 10)
    # pylab.ylim(0, 1.)
    pylab.show()
コード例 #46
0
        DATASET_INDEX,
        dataset_prefix='large_kitchen_appliances',
        batch_size=128)

    print("--- Run Time = %s seconds ---" % ((time.time() - start_time)))
    print("--- Run Time = %s minutes ---" %
          ((time.time() - start_time) / 60.0))
    text_file = open("training_time.txt", "w")
    text_file.write("--- Run Time =" + str(((time.time() - start_time))) +
                    " seconds ---" + "\n" + "--- Run Time = " +
                    str(((time.time() - start_time) / 60.0)) + " minutes ---" +
                    "\n")
    print(history.history.keys())

    plt.plot(history.history['loss'])
    plt.xlabel('epoch', fontsize=16)
    plt.ylabel('loss', fontsize=16)
    plt.savefig("./resulted_plotes/train_loss.jpg")
    plt.show()

    plt.plot(history.history['loss'])
    plt.plot(history.history['val_loss'])
    plt.legend(['train', 'validation'], loc='upper right', fontsize='large')

    plt.ylabel('loss', fontsize=16)
    plt.xlabel('epoch', fontsize=16)
    plt.savefig("./resulted_plotes/all_loss.jpg")
    plt.show()

    plt.plot(history.history['acc'])
    plt.plot(history.history['val_acc'])
コード例 #47
0
ファイル: Lab08_Q3.py プロジェクト: hjohnson1701/PHY407
#plot initial wave for t=0
plt.figure
plt.plot(x, u[0], label='t=0.0')

#loop over time, excluding the initial condition
for j in range(1, Nt - 1):
    #current time
    t = j * dt
    #loop over x, excluding the boundry
    for i in range(1, Nx - 1):
        #formula constant
        beta = epsilon * dt / dx
        #apply leapfrog step
        u[j + 1,
          i] = u[j - 1, i] - beta / 2 * ((u[j, i + 1])**2 - (u[j, i - 1])**2)

    #plot the function at the given times
    if abs(t - t2) < delta:
        plt.plot(x, u[j], label='t=0.5')
    elif abs(t - t3) < delta:
        plt.plot(x, u[j], label='t=1.0')
    elif abs(t - t4) < delta:
        plt.plot(x, u[j], label='t=1.5')

#plotting values
plt.xlabel("Position, x")
plt.ylabel("Displacement, u(x,t)")
plt.title("Solutions to Burger's equation")
plt.grid()
plt.legend()
plt.savefig("../images/burgers.png", dpi=600)
コード例 #48
0
ファイル: plot2.py プロジェクト: AlexanderToifl/RIV
def exp_fit(crvfile,
            outname,
            dump_frequency,
            Er,
            Ed,
            Ebi,
            recoil_relaxation_time=30000,
            start_timeoffset=500):
    ## CRV File - renamed to .crv and manually changed header (crv format) from extracted data file

    ## PNG output

    ## timestep used in recoil.in during recoil insertion --> datapoint after each recoil

    crv = CRV.CRV(crvfile)[0]

    #extract mech. stress tensor in x or y
    pyy = crv['pyy']
    x = crv['step']
    n_atoms = crv['atoms'][0]
    #calc timeaxis out of pxx or pyy size
    #x = np.arange(0,len(pyy)*timestep,timestep)

    #number of recoils
    nrecoils = []

    #pressure tensor component
    pxx = []

    dump_factor = int(recoil_relaxation_time / dump_frequency)

    print dump_factor

    #reduce timeaxis to recoil axis
    for i in range(len(x) / dump_factor):
        nrecoils.append((x[i * dump_factor] - start_timeoffset) /
                        float(recoil_relaxation_time))
        pxx.append(abs(pyy[i * dump_factor] / pyy[0]))

    #number of displacements per target atom
    ndpa = np.multiply(nrecoils, (Er / (2.5 * Ed * n_atoms)))

    #fit
    popt, pcov = opt.curve_fit(lambda ndpa, eta: eta_exp(ndpa, Ebi, eta),
                               ndpa,
                               pxx,
                               p0=2e8)

    #anotate to add value to plot
    print 'RIV (exp)= {:.4e}'.format(popt[0])

    # npa interpolated
    ndpa_interp = np.linspace(0, ndpa[-1] * 5, 1000)

    fig = plt.figure(1, figsize=fsize)

    plt.xlim(0, ndpa_interp[-1])
    #plt.ylim(0.95*pxx[-1] , 1)
    plt.grid()

    plt.plot(ndpa,
             pxx,
             'bs',
             markeredgecolor='blue',
             markerfacecolor='None',
             markeredgewidth=mew,
             markersize=ms,
             label='MD Simulation')
    plt.plot(ndpa_interp,
             eta_exp(ndpa_interp, Ebi, *popt),
             'r-',
             linewidth=lw,
             label='Fit')
    plt.xlabel('Number of displacements per atom')
    plt.ylabel(r'$ \frac{\sigma}{\vert \sigma_0 \vert} $')

    legtitle = r'$ \eta_{ri} = $' + '{:.4e}'.format(
        popt[0]
    ) + ' $ Pa \cdot dpa $' + '\n' + r'$ E_{bi} = $' + '{:.3e}'.format(
        Ebi) + ' $ Pa $' + '\n' + r'$ E_D = $' + '{:.1e}'.format(
            Ed) + ' $ \mathrm{eV} $' + '\n' + r'$ E_R = $' + '{:.1e}'.format(
                Er) + ' $ \mathrm{eV} $'

    plt.legend(loc='best',
               shadow=False,
               title=legtitle,
               prop={'size': legpropsize},
               numpoints=1)

    #every other tick label
    for label in plt.gca().xaxis.get_ticklabels()[::2]:
        label.set_visible(False)

    #plt.show()
    fig.savefig(outname)
    print "Png file written to " + outname
    plt.close("all")

    return popt[0]
コード例 #49
0
# Plots the drag coefficient against the particle Reynolds number.
from math import sqrt, pi
from numpy import *
import pylab
from fluidity_tools import stat_parser

C_wen_yu = zeros(200000)
C_stokes = zeros(200000)
particle_Re = arange(0.001, 1000, 0.005)
for i in range(0, len(particle_Re)):
    # Drag coefficients for the Wen & Yu and Stokes drag correlations respectively.
    C_wen_yu[i] = (24.0 / particle_Re[i]) * (1.0 +
                                             0.15 * particle_Re[i]**0.687)
    C_stokes[i] = (24.0 / particle_Re[i])

s = stat_parser("./mphase_wen_yu_drag_correlation.stat")
numerical_particle_Re_wen_yu = s["Tephra"]["ParticleReynoldsNumber"]["max"][-1]
numerical_C_wen_yu = s["Tephra"]["DragCoefficient"]["max"][-1]

pylab.loglog(particle_Re, C_stokes, "-r", label="Stokes drag correlation")
pylab.loglog(particle_Re, C_wen_yu, "-g", label="Wen & Yu drag correlation")
pylab.loglog(numerical_particle_Re_wen_yu,
             numerical_C_wen_yu,
             "*b",
             label="Numerical result")
pylab.legend(loc=1)
pylab.xlabel("ParticleReynoldsNumber")
pylab.ylabel("DragCoefficient")

pylab.show()
コード例 #50
0
s = init.create_state_random_packing(imsize=36,
                                     radius=5.0,
                                     sigma=0.05,
                                     seed=10)
bl_pos = s.explode(s.create_block('pos'))
bl_rad = s.explode(s.create_block('rad'))

f = s.fisher_information(bl_pos + bl_rad)

inv = np.linalg.inv(f)
crb = np.sqrt(np.diag(inv))

bp = 3 * s.N
br = 4 * s.N
pl.figure()
pl.imshow(inv)
pl.colorbar()
pl.hlines(bp, 0, br, lw=1)
pl.vlines(bp, 0, br, lw=1)
pl.xlim(0, br - 1)
pl.ylim(0, br - 1)
pl.title("Dense suspension CRB")

pl.figure()
pl.semilogy(crb, 'o')
pl.xlabel("Parameter index")
pl.ylabel("CRB")
pl.title("Dense suspension CRB")
pl.xlim(0, br)
pl.show()
コード例 #51
0
ファイル: fig8.py プロジェクト: dalbis/grid_origin
    pl.figure(figsize=(1.7, 1.7))
    pl.subplots_adjust(left=0.4,
                       right=0.9,
                       top=0.85,
                       bottom=0.3,
                       wspace=0.2,
                       hspace=0.6)

    pl.subplot(1, 1, 1, aspect='equal')
    pl.plot(batch_phases[batch_idx][:, 0],
            batch_phases[batch_idx][:, 1],
            '.k',
            ms=7)
    pp.custom_axes()
    pl.xlabel('Grid phase-x [m]')
    pl.ylabel('Grid phase-y [m]')
    pl.xlim(-0.3, 0.3)
    pl.ylim(-0.3, 0.3)
    pl.xticks([-0.3, 0., 0.3])
    pl.yticks([-0.3, 0., 0.3])
    pl.savefig(figures_path + '/fig8' + suffix[batch_idx] + '1.eps',
               dpi=300,
               transparent=True)

    # angles
    pl.figure(figsize=(4., 1.5))
    pl.subplots_adjust(left=0.3, right=1, top=0.85, bottom=0.3, wspace=0.2)

    pl.subplot(1, 3, 1)
    bins, edges = np.histogram(np.array(batch_angles[batch_idx]) * 180 / np.pi,
コード例 #52
0
        line = xy.readline()

        #split into two separate lists: x and y
        x_and_y = line.split()

        # If we do not have 2 words then it must be blank lines at the end of the file.
        if len(x_and_y) != 2:
            break  #exits loop
    except:

        # If we failed to read a line then we must have got to the end.
        break  #exits loop

    #append x and y where x value is the first column and y is second column
    #save these values as floats- if this is not possible it will go to except
    x.append(float(x_and_y[0]))
    y.append(float(x_and_y[1]))

#convert x and y lists to numpy arrays

x = np.array(x)
y = np.array(y)

pylab.plot(x, y)
pylab.xlabel("x")
pylab.ylabel("y")
pylab.show()

print "Maximum x: ", max(x)
print "Maximum y: ", max(y)
コード例 #53
0
    def plotReport( self, summ={} ,fignum=1 ):

        if not ( summ.has_key('summaryminor') and summ.has_key('summarymajor') and summ.has_key('threshold') and summ['summaryminor'].shape[0]==6 ):
            print 'Cannot make summary plot. Please check contents of the output dictionary from tclean.'
            return summ

        import pylab as pl
        from numpy import max as amax

        # 0 : iteration number (within deconvolver, per cycle)
        # 1 : peak residual
        # 2 : model flux
        # 3 : cyclethreshold
        # 4 : deconvolver id
        # 5 : subimage id (channel, stokes..)

        pl.ioff()

        pl.figure(fignum)
        pl.clf();
        minarr = summ['summaryminor']
        if minarr.size==0:
            casalog.post("Zero iteration: no summary plot is generated.", "WARN")
        else:
	    iterlist = minarr[0,:]
	    eps=0.0
	    peakresstart=[]
	    peakresend=[]
	    modfluxstart=[]
	    modfluxend=[]
	    itercountstart=[]
	    itercountend=[]
	    peakresstart.append( minarr[1,:][0] )
	    modfluxstart.append( minarr[2,:][0] )
	    itercountstart.append( minarr[0,:][0] + eps )
	    peakresend.append( minarr[1,:][0] )
	    modfluxend.append( minarr[2,:][0] )
	    itercountend.append( minarr[0,:][0] + eps )
	    for ii in range(0,len(iterlist)-1):
		if iterlist[ii]==iterlist[ii+1]:
		    peakresend.append( minarr[1,:][ii] )
		    peakresstart.append( minarr[1,:][ii+1] ) 
		    modfluxend.append( minarr[2,:][ii] )
		    modfluxstart.append( minarr[2,:][ii+1] )
		    itercountend.append( iterlist[ii]-eps )
		    itercountstart.append( iterlist[ii]+eps )

	    peakresend.append( minarr[1,:][len(iterlist)-1] )
	    modfluxend.append( minarr[2,:][len(iterlist)-1] )
	    itercountend.append( minarr[0,:][len(iterlist)-1] + eps )

    #        pl.plot( iterlist , minarr[1,:] , 'r.-' , label='peak residual' , linewidth=1.5, markersize=8.0)
    #        pl.plot( iterlist , minarr[2,:] , 'b.-' , label='model flux' )
    #        pl.plot( iterlist , minarr[3,:] , 'g--' , label='cycle threshold' )

	    pl.plot( itercountstart , peakresstart , 'r.--' , label='peak residual (start)')
	    pl.plot( itercountend , peakresend , 'r.-' , label='peak residual (end)',linewidth=2.5)
	    pl.plot( itercountstart , modfluxstart , 'b.--' , label='model flux (start)' )
	    pl.plot( itercountend , modfluxend , 'b.-' , label='model flux (end)',linewidth=2.5 )
	    pl.plot( iterlist , minarr[3,:] , 'g--' , label='cycle threshold', linewidth=2.5 )
	    maxval = amax( minarr[1,:] )
	    maxval = max( maxval, amax( minarr[2,:] ) )
	    
	    bcols = ['b','g','r','y','c']
	    minv=1
	    niterdone = len(minarr[4,:])
	  
	    if len(summ['summarymajor'].shape)==1 and summ['summarymajor'].shape[0]>0 :       
		pl.vlines(summ['summarymajor'],0,maxval, label='major cycles', linewidth=2.0)

	    pl.hlines( summ['threshold'], 0, summ['iterdone'] , linestyle='dashed' ,label='threshold')
	
	    pl.xlabel( 'Iteration Count' )
	    pl.ylabel( 'Peak Residual (red), Model Flux (blue)' )

	    ax = pl.axes()
	    box = ax.get_position()
	    ax.set_position([box.x0, box.y0, box.width, box.height*0.8])

	    pl.legend(loc='lower center', bbox_to_anchor=(0.5, 1.05),
		      ncol=3, fancybox=True, shadow=True)

	    pl.savefig('summaryplot_'+str(fignum)+'.png')
	    pl.ion()

        return summ;
コード例 #54
0
populations[0].record_v()
populations[0].record_gsyn()
populations[0].record()

p.run(runtime)

v = populations[0].get_v(compatible_output=True)
gsyn = populations[0].get_gsyn(compatible_output=True)
spikes = populations[0].getSpikes(compatible_output=True)

if spikes is not None:
    print spikes
    pylab.figure()
    pylab.plot([i[1] for i in spikes], [i[0] for i in spikes], ".")
    pylab.xlabel('Time/ms')
    pylab.ylabel('spikes')
    pylab.title('spikes')
    pylab.show()
else:
    print "No spikes received"

# Make some graphs

if v is not None:
    ticks = len(v) / nNeurons
    pylab.figure()
    pylab.xlabel('Time/ms')
    pylab.ylabel('v')
    pylab.title('v')
    for pos in range(0, nNeurons, 20):
コード例 #55
0
ファイル: vis_proj_dgs.py プロジェクト: hasanmoudud/darcoda
# along x
pylab.subplot(3, 3, 7)
pylab.xticks([])
pylab.yticks([])
f = open("map_x_amr.dat", 'rb')
s = f.read(2 * RM + struct.calcsize("2i"))
par, nx, ny, par = struct.unpack(SRM + "i" + "i" + SRM, s)

for i in arange(Ntick):
    xval = 1000 * (yc + (i - Nspace / 2) * BL / Nspace - yc)
    yval = 1000 * (zc + (i - Nspace / 2) * BL / Nspace - zc)
    xt.append("%.0f" % xval)
    yt.append("%.0f" % yval)
pylab.xticks(nx / Nspace * arange(Ntick), xt, fontsize=fs)
pylab.yticks(ny / Nspace * arange(Ntick), yt, fontsize=fs)
pylab.xlabel(r"$r\quad[{\rm kpc}/h]$", fontsize=fs)
pylab.ylabel(r"$r\quad[{\rm kpc}/h]$", fontsize=fs)

s = f.read(RM)
binvalues = ar.array(IMGSIZE)
binvalues.read(f, nx * ny)
data = numpy.array(binvalues, 'float')
data = numpy.reshape(data, (ny, nx))
data2 = numpy.zeros((ny, nx), 'float')
f.close()

for i in xrange(nx):
    for j in xrange(ny):
        data2[j, i] = data[ny - j - 1, i]
pylab.imshow(data2, aspect=1, cmap=cm.hsv)
コード例 #56
0
def fe55_gain_fitter(signals,
                     ccdtemp=-95,
                     make_plot=False,
                     xrange=None,
                     bins=100,
                     hist_nsig=10,
                     title='',
                     plot_filename=None,
                     interactive=True,
                     ylog=True):
    """
    Function to fit the distribution of charge cluster DN values from
    a Fe55 dataset.  A two Gaussian model of Mn K-alpha and K-beta
    lines is assumed with the ratio between the K-alpha and K-beta
    energies fixed at 5.889/6.49 and the the Gaussian width of the
    lines set equal.

    The gain (Ne/DN), location and sigma of the K-alpha peak (in units
    of DN) are returned as a tuple.

    If make_plot=True, then a matplotlib plot of the distribution and
    fit is displayed.

    If xrange is not None, then that 2-element tuple is used as the
    histogram x-range.

    If xrange is None, then the histogram x-range is set to 
    +/- hist_nsig*clipped_stdev about the median of the signal
    distribution.
    """
    flags = afwMath.MEDIAN | afwMath.STDEVCLIP
    try:
        stats = afwMath.makeStatistics(signals.tolist(), flags)
    except:
        print signals
        raise
    median = stats.getValue(afwMath.MEDIAN)
    stdev = stats.getValue(afwMath.STDEVCLIP)
    if xrange is None:
        # Set range of histogram to include both Kalpha and Kbeta peaks.
        xmin = max(median - hist_nsig * stdev, 200)
        xmax = min(median * 1785. / 1620. + hist_nsig * stdev, 1000)
        xrange = xmin, xmax
    # Save pylab interactive state.
    pylab_interactive_state = pylab.isinteractive()
    # Determine distribution mode and take that as the location of the
    # Kalpha peak
    hist = np.histogram(signals, bins=bins, range=xrange)
    xpeak = hist[1][np.where(hist[0] == max(hist[0]))][0]
    xrange = max(0, xpeak - 200), xpeak * 1785. / 1620. + 200
    hist = np.histogram(signals, bins=bins, range=xrange)
    yrange = 1, max(hist[0]) * 1.5
    if make_plot:
        if interactive:
            pylab.ion()
        else:
            pylab.ioff()
#        fig = pylab.figure()
#        axes = fig.add_subplot(111)
        win = plot.Window()
        hist = pylab.hist(signals,
                          bins=bins,
                          range=xrange,
                          histtype='bar',
                          color='b',
                          log=ylog)
        if ylog:
            plot.setAxis(xrange, yrange)
    else:
        pylab.ioff()


#        hist = np.histogram(signals, bins=bins, range=xrange)
    x = (hist[1][1:] + hist[1][:-1]) / 2.
    y = hist[0]
    ntot = sum(y)
    #
    # Starting values for two Gaussian fit. The relative
    # normalizations are initially set at the expected line ratio
    # of K-alpha/K-beta = 0.88/0.12.  The relative peak locations
    # and relative widths are fixed in fe55_lines(...) above.
    #
    p0 = (ntot * 0.88, median, stdev / 2., ntot * 0.12)
    pars, _ = scipy.optimize.curve_fit(fe55_lines, x, y, p0=p0)

    kalpha_peak, kalpha_sigma = pars[1], pars[2]
    fe55_yield = Fe55Yield(ccdtemp)
    gain = fe55_yield.alpha()[0] / kalpha_peak

    if make_plot:
        pylab.xlabel('Bias Corrected Event Signal (DN)')
        pylab.ylabel('Entries / bin')
        xx = np.linspace(x[0], x[-1], 1000)
        pylab.plot(xx, fe55_lines(xx, *pars), 'r--', markersize=3, linewidth=1)
        pylab.annotate(("K-alpha peak = %i DN\n\n" + "Gain = %.2f e-/DN\n\n") %
                       (kalpha_peak, gain), (0.5, 0.7),
                       xycoords='axes fraction')
        win.set_title(title)
        if plot_filename is not None:
            pylab.savefig(plot_filename)
    # Restore pylab interactive state.
    pylab.interactive(pylab_interactive_state)
    return gain, kalpha_peak, kalpha_sigma
コード例 #57
0
idx1 = 10000
idx2 = idx1 + frameSize
index1 = idx1 * 1.0 / framerate
index2 = idx2 * 1.0 / framerate
acf = pt.ACF(waveData[idx1:idx2])
acf[0:10] = -acf[0]
acfmax = np.argmax(acf)
print(acfmax)
print(framerate * 1.0 / acfmax)

pl.subplot(411)
pl.title("pitchTrack")
pl.plot(time, waveData)
pl.plot([index1, index1], [-1, 1], 'r')
pl.plot([index2, index2], [-1, 1], 'r')
pl.xlabel("time (seconds)")
pl.ylabel("Amplitude")

pl.subplot(412)
pl.plot(np.arange(frameSize), waveData[idx1:idx2], 'r')
pl.xlabel("index in 1 frame")
pl.ylabel("Amplitude")

pl.subplot(413)
pl.plot(np.arange(frameSize), acf, 'g')
pl.xlabel("index in 1 frame")
pl.ylabel("ACF")

# pitch tracking
acfmethod = pt.ACF
pitchtrack = pt.PitchTrack(waveData, framerate, frameSize, overLap, acfmethod)
コード例 #58
0
def compareAbsorption(recipe, curvNo, noIndicators):
    worker = recipe.getWorker("AddColumn")
    table = worker.plugCompute.getResult(
        subscriber=TextSubscriber("Result Functional"))
    xPos = table[u"x-position"]
    yPos = table[u"y-position"]
    index = curvNo2Index(table[u"pixel"], curvNo)
    title_template = "$%%s_{%s}$(%s %s,%s %s)=%%s %%s" % (
        curvNo, xPos.data[index], xPos.unit.unit.name(), yPos.data[index],
        yPos.unit.unit.name())

    worker = recipe.getWorker("ThicknessModeller")
    simulation = worker.plugCalcAbsorption.getResult()

    thickness = table[u"thickness"]
    residuum = (simulation.dimensions[0].data - thickness.data[index])**2
    absorption = simulation.data[residuum.argmin(), :]
    pylab.plot(simulation.dimensions[1].data,
               absorption,
               label="$%s$ functional" % simulation.shortname)
    title = "Functional based: " + title_template % (
        thickness[index].shortname, thickness.data[index],
        thickness.unit.unit.name())

    try:
        worker = recipe.getWorker("Res Direct")
        table = worker.plugCompute.getResult(
            subscriber=TextSubscriber("Result without Functional"))
        thickness = table[u"thickness"]
        residuum = (simulation.dimensions[0].data - thickness.data[index])**2
        absorption = simulation.data[residuum.argmin(), :]
        pylab.plot(simulation.dimensions[1].data,
                   absorption,
                   label="$%s$ immediate" % simulation.shortname)
        title += "\nImmediate: " + title_template % (
            thickness[index].shortname, thickness.data[index],
            thickness.unit.unit.name())
    except:
        pass

    worker = recipe.getWorker("Slicing")
    noisyAbsorption = worker.plugExtract.getResult()
    worker = recipe.getWorker("MRA Exp")
    minimaPos = worker.plugMra.getResult()[r'\lambda_{min}'].inUnitsOf(
        simulation.dimensions[1])
    maximaPos = worker.plugMra.getResult()[r'\lambda_{max}'].inUnitsOf(
        simulation.dimensions[1])
    pylab.plot(noisyAbsorption.dimensions[1].inUnitsOf(
        simulation.dimensions[1]).data,
               noisyAbsorption.data[index, :],
               label="$%s$" % noisyAbsorption.shortname)
    if not noIndicators:
        pylab.vlines(minimaPos.data[:, index],
                     0.1,
                     1.0,
                     label="$%s$" % minimaPos.shortname)
        pylab.vlines(minimaPos.data[:, index] + minimaPos.error[:, index],
                     0.1,
                     1.0,
                     label="$\\Delta%s$" % minimaPos.shortname,
                     linestyle='dashed')
        pylab.vlines(minimaPos.data[:, index] - minimaPos.error[:, index],
                     0.1,
                     1.0,
                     label="$\\Delta%s$" % minimaPos.shortname,
                     linestyle='dashed')
        pylab.vlines(maximaPos.data[:, index],
                     0.1,
                     1.0,
                     label="$%s$" % maximaPos.shortname)
        pylab.vlines(maximaPos.data[:, index] + maximaPos.error[:, index],
                     0.1,
                     1.0,
                     label="$\\Delta%s$" % maximaPos.shortname,
                     linestyle='dashed')
        pylab.vlines(maximaPos.data[:, index] - maximaPos.error[:, index],
                     0.1,
                     1.0,
                     label="$\\Delta%s$" % maximaPos.shortname,
                     linestyle='dashed')
    pylab.title(title)
    pylab.xlabel(simulation.dimensions[1].label)
    pylab.legend(loc="lower left")
コード例 #59
0
# plot analytic solution
tt = numpy.linspace(0.0, 1.0, 1000)

pylab.plot(tt, analytic(tt), label="analytic solution")

# plot RK4 solution -- we need a step of 1.e-3 or smaller to get this
# right, because that is the fastest timescale.  If you go above 2.e-3,
# it blows up severely
tRK4, yRK4 = rk4(y0, 1.e-3, 1.0)

pylab.plot(tRK4, yRK4, label=r"R-K 4, $\tau = 10^{-3}$")

pylab.xlim(0.0, 0.1)

pylab.xlabel("t")
pylab.ylabel("y")

leg = pylab.legend()
ltext = leg.get_texts()
pylab.setp(ltext, fontsize='small')
leg.draw_frame(0)

pylab.savefig("stiff-rk4-dt-1e-3.png")

# now do dt = 2.5e-3
pylab.clf()

pylab.plot(tt, analytic(tt), label="analytic solution")

tRK4, yRK4 = rk4(y0, 2.5e-3, 1.0)
コード例 #60
0
ファイル: post.py プロジェクト: mchandra/Bolt
t_final = 0.1
time = np.arange(dt, t_final + dt, dt)

N_q1 = domain.N_q1
N_q2 = domain.N_q2

h5f = h5py.File('dump/0000.h5', 'r')
q1 = h5f['q1'][:].reshape(N_q1, N_q2)
q2 = h5f['q2'][:].reshape(N_q1, N_q2)
n = h5f['n'][:].reshape(N_q1, N_q2)
h5f.close()

pl.plot(q1[:, 0], n[:, 0])
pl.title('Time = 0')
pl.ylim([0, 65])
pl.xlabel(r'$x$')
pl.ylabel(r'$n$')
pl.savefig('images/0000.png')
pl.clf()

for time_index, t0 in enumerate(time):

    h5f = h5py.File('dump/%04d' % (time_index + 1) + '.h5', 'r')
    n = h5f['n'][:].reshape(N_q1, N_q2)
    h5f.close()

    if ((time_index + 1) % 20 == 0):
        pl.plot(q1[:, 0], n[:, 0])
        pl.title('Time =' + str(t0))
        pl.xlabel(r'$x$')
        pl.ylabel(r'$n$')