示例#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
文件: 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()
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
    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
示例#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
	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
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
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
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
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
def plot_Barycenter(dataset_name, feat, unfeat, repo):

    if dataset_name==MNIST:
        _, _, test=get_data(dataset_name, repo, labels=True)
        xtest1,_,_, labels,_=test
    else:
        _, _, test=get_data(dataset_name, repo, labels=False)
        xtest1,_,_ =test
        labels=np.zeros((len(xtest1),))
    # get labels
    def bary_wdl2(index): return _bary_wdl2(index, xtest1, feat, unfeat)
    
    n=xtest1.shape[-1]
    
    num_class = (int)(max(labels)+1)
    barys=[bary_wdl2(np.where(labels==i)) for i in range(num_class)]
    pl.figure(1, (num_class, 1))
    for i in range(num_class):
        pl.subplot(1,10,1+i)
        pl.imshow(barys[i][0,0,:,:],cmap='Blues',interpolation='nearest')
        pl.xticks(())
        pl.yticks(())
        if i==0:
            pl.ylabel('DWE Bary.')
        if num_class >1:
            pl.title('{}'.format(i))
    pl.tight_layout(pad=0,h_pad=-2,w_pad=-2) 
    pl.savefig("imgs/{}_dwe_bary.pdf".format(dataset_name))
示例#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
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_
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 )
示例#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
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)
示例#26
0
def plotB3reg():
    w=loadStanFit('revE2B3BHreg.fit')
    printCI(w,'mmu')
    printCI(w,'mr')
    for b in range(2):
        subplot(1,2,b+1)
        plt.title('')
        px=np.array(np.linspace(-0.5,0.5,101),ndmin=2)
        a0=np.array(w['mmu'][:,b],ndmin=2).T
        a1=np.array(w['mr'][:,b],ndmin=2).T
        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))
        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'))
        man=np.array([-0.4,-0.2,0,0.2,0.4])
        mus=[]
        for m in range(len(man)):
            mus.append(loadStanFit('revE2B3BH%d.fit'%m)['mmu'][:,b])
        mus=np.array(mus).T
        errorbar(mus,x=man)
        ax.set_xticks(man)
        plt.xlim([-0.5,0.5])
        plt.ylim([-0.4,0.8])
        #plt.xlabel('Manipulated Displacement')
        if b==0:
            plt.ylabel('Perceived Displacemet')
            plt.gca().set_yticklabels([])
        subplot_annotate()
    plt.text(-1.1,-0.6,'Pivot Displacement',fontsize=8);
示例#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 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
示例#29
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')
示例#30
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
示例#31
0
magnetization = [get_magnetization(state) / (N_side**2)]

for step in range(0, N_MC_steps):
    i = rng.integers(0, N_side)
    j = rng.integers(0, N_side)
    old_contribution = contribution_to_energy(J, state, i, j, state[i, j])
    new_contribution = contribution_to_energy(J, state, i, j,
                                              flip_spin(state[i, j]))
    if should_accept_move(beta, new_contribution - old_contribution):
        state[i, j] = flip_spin(state[i, j])
        old_energy += new_contribution - old_contribution
    magnetization.append(get_magnetization(state) / (N_side**2))

plot(magnetization)
xlabel("time step")
ylabel("m")
title(fr"Average magnetization m per spin, $\beta={beta}, J={J}, k_B=1$")
show()
plt.close()

cmap = colors.ListedColormap(['#56b4e9', '#d55e00'])
bounds = [-1, 0, 1]
norm = colors.BoundaryNorm(bounds, cmap.N)

fig = plt.figure()
# plt = imshow(states[0], norm=norm, cmap=cmap, extent=[1, N_side, 1, N_side], animated=True)
# colorbar(cmap=cmap, ticks=[-1, 1], norm=norm, boundaries=bounds)

# def update_fig(i):
#     if i < N_MC_steps:
#         i += 1
示例#32
0
    def OnColoc(self, event=None, restrict_z=False, coloc_vs_z=False):
        from PYME.Analysis.Colocalisation import correlationCoeffs, edtColoc
        from scipy import interpolate
        voxelsize = [
            1e3 * self.image.mdh.getEntry('voxelsize.x'),
            1e3 * self.image.mdh.getEntry('voxelsize.y'),
            1e3 * self.image.mdh.getEntry('voxelsize.z')
        ]

        names = self.image.names

        if not getattr(self.image, 'labels', None) is None:
            have_mask = True

            mask = (self.image.labels > 0.5).squeeze()
        else:
            have_mask = False
            mask = None

        if not restrict_z:
            dlg = ColocSettingsDialog(self.dsviewer,
                                      voxelsize[0],
                                      names,
                                      have_mask=have_mask)
        else:
            dlg = ColocSettingsDialog(self.dsviewer,
                                      voxelsize[0],
                                      names,
                                      have_mask=have_mask,
                                      z_size=self.image.data.shape[2])
        dlg.ShowModal()

        bins = dlg.GetBins()
        chans = dlg.GetChans()
        use_mask = dlg.GetUseMask()

        zs, ze = (0, self.image.data.shape[2])
        if (self.image.data.shape[2] > 1) and restrict_z:
            zs, ze = dlg.GetZrange()

        zs, ze = (0, 1)
        if self.image.data.shape[2] > 1:
            zs, ze = dlg.GetZrange()
        dlg.Destroy()

        print('Use mask: %s' % use_mask)

        if not use_mask:
            mask = None

        #assume we have exactly 2 channels #FIXME - add a selector
        #grab image data
        imA = self.image.data[:, :, zs:ze, chans[0]].squeeze()
        imB = self.image.data[:, :, zs:ze, chans[1]].squeeze()

        #assume threshold is half the colour bounds - good if using threshold mode
        tA = self.do.Offs[chans[0]] + .5 / self.do.Gains[
            chans[0]]  #pylab.mean(self.ivps[0].clim)
        tB = self.do.Offs[chans[1]] + .5 / self.do.Gains[
            chans[1]]  #pylab.mean(self.ivps[0].clim)

        nameA = names[chans[0]]
        nameB = names[chans[1]]

        voxelsize = voxelsize[:imA.ndim]  #trunctate to number of dimensions

        print('Calculating Pearson and Manders coefficients ...')
        pearson = correlationCoeffs.pearson(imA, imB, roi_mask=mask)
        MA, MB = correlationCoeffs.thresholdedManders(imA,
                                                      imB,
                                                      tA,
                                                      tB,
                                                      roi_mask=mask)

        if coloc_vs_z:
            MAzs, MBzs = ([], [])
            FAzs, FBzs = ([], [])
            if self.image.data.shape[2] > 1:
                for z in range(self.image.data.shape[2]):
                    imAz = self.image.data[:, :, z, chans[0]].squeeze()
                    imBz = self.image.data[:, :, z, chans[1]].squeeze()
                    MAz, MBz = correlationCoeffs.thresholdedManders(
                        imAz, imBz, tA, tB)
                    FAz, FBz = correlationCoeffs.maskFractions(
                        imAz, imBz, tA, tB)
                    MAzs.append(MAz)
                    MBzs.append(MBz)
                    FAzs.append(FAz)
                    FBzs.append(FBz)

                print("M(A->B) %s" % MAzs)
                print("M(B->A) %s" % MBzs)
                print("Species A: %s, Species B: %s" % (nameA, nameB))

                pylab.figure()
                pylab.subplot(211)
                if 'filename' in self.image.__dict__:
                    pylab.title(self.image.filename)
                # nameB with nameA
                cAB, = pylab.plot(MAzs,
                                  'o',
                                  label='%s with %s' % (nameB, nameA))
                # nameA with nameB
                cBA, = pylab.plot(MBzs,
                                  '*',
                                  label='%s with %s' % (nameA, nameB))
                pylab.legend([cBA, cAB])
                pylab.xlabel('z slice level')
                pylab.ylabel('Manders coloc fraction')
                pylab.ylim(0, None)

                pylab.subplot(212)
                if 'filename' in self.image.__dict__:
                    pylab.title(self.image.filename)
                # nameB with nameA
                fA, = pylab.plot(FAzs, 'o', label='%s mask fraction' % (nameA))
                # nameA with nameB
                fB, = pylab.plot(FBzs, '*', label='%s mask fraction' % (nameB))
                pylab.legend([fA, fB])
                pylab.xlabel('z slice level')
                pylab.ylabel('Mask fraction')
                pylab.ylim(0, None)
                pylab.show()

        print('Performing distance transform ...')
        #bnA, bmA, binsA = edtColoc.imageDensityAtDistance(imB, imA > tA, voxelsize, bins, roi_mask=mask)
        #bnAA, bmAA, binsA = edtColoc.imageDensityAtDistance(imA, imA > tA, voxelsize, bins, roi_mask=mask)

        bins_, enrichment_BA, enclosed_BA, enclosed_area_A = edtColoc.image_enrichment_and_fraction_at_distance(
            imB, imA > tA, voxelsize, bins, roi_mask=mask)
        bins_, enrichment_AA, enclosed_AA, _ = edtColoc.image_enrichment_and_fraction_at_distance(
            imA, imA > tA, voxelsize, bins, roi_mask=mask)

        print('Performing distance transform (reversed) ...')
        #bnB, bmB, binsB = edtColoc.imageDensityAtDistance(imA, imB > tB, voxelsize, bins, roi_mask=mask)
        #bnBB, bmBB, binsB = edtColoc.imageDensityAtDistance(imB, imB > tB, voxelsize, bins, roi_mask=mask)

        bins_, enrichment_AB, enclosed_AB, enclosed_area_B = edtColoc.image_enrichment_and_fraction_at_distance(
            imA, imB > tB, voxelsize, bins, roi_mask=mask)
        bins_, enrichment_BB, enclosed_BB, _ = edtColoc.image_enrichment_and_fraction_at_distance(
            imB, imB > tB, voxelsize, bins, roi_mask=mask)

        #print binsB, bmB

        plots = []
        pnames = []

        # B from mA
        ####################
        plots_ = {}

        #plots_['Frac. %s from mask(%s)' % (nameB, nameA)] =
        plots.append(enclosed_BA.reshape(-1, 1, 1))
        pnames.append('Frac. %s from mask(%s)' % (nameB, nameA))

        plots.append(enrichment_BA.reshape(-1, 1, 1))
        pnames.append('Enrichment of %s at distance from mask(%s)' %
                      (nameB, nameA))

        edtColoc.plot_image_dist_coloc_figure(bins_, enrichment_BA,
                                              enrichment_AA, enclosed_BA,
                                              enclosed_AA, enclosed_area_A,
                                              pearson, MA, MB, nameA, nameB)

        plots.append(enclosed_AB.reshape(-1, 1, 1))
        pnames.append('Frac. %s from mask(%s)' % (nameA, nameB))

        plots.append(enrichment_AB.reshape(-1, 1, 1))
        pnames.append('Enrichment of %s at distance from mask(%s)' %
                      (nameA, nameB))

        edtColoc.plot_image_dist_coloc_figure(bins_, enrichment_AB,
                                              enrichment_BB, enclosed_AB,
                                              enclosed_BB, enclosed_area_B,
                                              pearson, MA, MB, nameB, nameA)

        pylab.show()

        im = ImageStack(plots, titleStub='Radial Distribution')
        im.xvals = bins[:-1]

        im.xlabel = 'Distance [nm]'

        im.ylabel = 'Fraction'
        im.defaultExt = '.txt'

        im.mdh['voxelsize.x'] = (bins[1] - bins[0]) * 1e-3
        im.mdh['ChannelNames'] = pnames
        im.mdh['Profile.XValues'] = im.xvals
        im.mdh['Profile.XLabel'] = im.xlabel
        im.mdh['Profile.YLabel'] = im.ylabel

        im.mdh['Colocalisation.Channels'] = names
        im.mdh['Colocalisation.Thresholds'] = [tA, tB]
        im.mdh['Colocalisation.Pearson'] = pearson
        im.mdh['Colocalisation.Manders'] = [MA, MB]
        try:
            im.mdh['Colocalisation.ThresholdMode'] = self.do.ThreshMode
        except:
            pass

        im.mdh['OriginalImage'] = self.image.filename

        ViewIm3D(im, mode='graph')
示例#33
0
print('flux is: %5.2f' % (evaluate_gaussian(o)))
calculated.append(evaluate_gaussian(o))

z, e = fitting_gaussian(data6, x6)
print('flux is: %5.2f' % (evaluate_gaussian(e)))
calculated.append(evaluate_gaussian(e))

i, u = fitting_gaussian(data7, x7)
print('flux is: %5.2f' % (evaluate_gaussian(u)))
calculated.append(evaluate_gaussian(u))


def line(x, m, b):
    return m * x + b


popt, covar = curve_fit(line, calculated, correct_values)

x = np.linspace(np.amin(calculated), np.amax(calculated))
y = line(x, *popt)

plt.figure(figsize=(12, 8))
plt.xlabel('Calculated Flux')
plt.ylabel('Observed Flux')
plt.plot(calculated, correct_values, label='Values')
plt.plot(x, y, label='Best Fit')
plt.show()
#print(t)
#print()
#print(a)
示例#34
0
(5.0,'2011/03/09 07:13:48'),
(5.1,'2011/03/09 06:25:12'),
(4.9,'2011/03/09 06:12:13'),
(2.9,'2011/03/09 05:33:50'),
(4.7,'2011/03/09 05:27:06'),
(5.3,'2011/03/09 04:45:54'),
(5.7,'2011/03/09 04:37:04'),
(5.2,'2011/03/09 04:32:10'),
(3.0,'2011/03/09 04:17:17'),
(4.8,'2011/03/09 04:15:39'),
(5.2,'2011/03/09 04:05:54'),
(2.5,'2011/03/09 03:51:21'),
(5.0,'2011/03/09 03:19:00'),
(5.2,'2011/03/09 03:08:36'),
(5.6,'2011/03/09 02:57:17'),
(7.2,'2011/03/09 02:45:20'),
(4.6,'2011/03/09 01:47:47'),
(4.7,'2011/03/09 01:30:27')]

ydata = []

for t in data:
	ydata.append(t[0])

pylab.plot(ydata)
pylab.title('Earthquake Magnitude in Japan from 3/9-3/12')
pylab.xlabel('Time')
pylab.ylabel('Magnitude')
pylab.show()

        beta_tmp *= 2.0
        #print('beta: %s -> %s' % (beta_tmp / 2.0, beta_tmp))
    Z = sum(rho[j, j] for j in range(nx + 1)) * dx
    Z_p = 0
    try:
        Z_p = Z_pert(cubic, quartic, beta, nx)
    except OverflowError:
        pass
    zets[0].append(Z)
    zets[1].append(Z_p)

#pi_of_x = [rho[j, j] / Z for j in range(nx + 1)]
#f = open('data_anharm_matrixsquaring_beta' + str(beta) + '.dat', 'w')
#for j in range(nx + 1):
#    f.write(str(x[j]) + ' ' + str(rho[j, j] / Z) + '\n')
#f.close()

pylab.plot(quartics, zets[0], 'r', linewidth=4.0)
pylab.plot(quartics, zets[1], 'b', linewidth=3.0)
pylab.plot(quartics, zets[0], 'rs', linewidth=4.0)
pylab.plot(quartics, zets[1], 'b^', linewidth=3.0)

#pylab.plot(x, pi_of_x, 'r', linewidth=4.0)
#t = [x*0.1 for x in range(-50, 50)]
#pylab.plot(t, [pi_quant(x, beta) for x in t], 'b--', linewidth=2.0)
pylab.xlabel('$quartic$', fontsize=16)
pylab.ylabel('$Z$', fontsize=16)
#pylab.title('$\\beta$=%s, quartic=%s' % (beta, quartic))
pylab.legend(('Z', 'Z_pert'), loc='upper right')
#pylab.xlim(-3.0, 3.0)
pylab.show()
示例#36
0
x = dx * i
z = -dz * j

dt = 1.0
l = numpy.arange(t[0] + 1, t[-1], dt)
#s = LSQUnivariateSpline(t, x, l, k = 5)
#ts= linspace(0,450,1000)
#Xs= s(ts)
#ts2= ts[1:996]
#d = numpy.array([s.derivatives(ts[i])[1] for i in range(1,996)])
#print d
pylab.subplot(311)
pylab.plot(t, x)
#pylab.plot(ts,Xs,'y-')
#pylab.plot(ts2,d,'r-')
pylab.ylabel("x/cm")
pylab.xlabel("t")
pylab.subplot(312)
pylab.ylabel("z/cm")
pylab.plot(
    t,
    z,
)
#pylab.plot(ts,Zs,'y-')
#pylab.plot(ts2,d,'b-')
pylab.xlabel("t")
pylab.subplot(313)
pylab.plot(x, z)
pylab.xlabel("x/cm")
pylab.ylabel("z/cm")
#pylab.savefig( '../Plots/94.png')
示例#37
0
# did the user request an x-axis limit below the maximum death value found in the input?
if xLimit < maxDeath :
    print('Requested xLimit (' + str(xLimit) + ') value is lower than max death value (' + str(maxDeath) + ')...aborting')
    sys.exit()

# are there more dimensions in the data then we have colors for?
if len(colorPalette) < np.max(rawData[:,0]) :
    print('The current colormap has insufficient colors to represent all the dimensions in the data...aborting')
    sys.exit()

# build barcode plot

pylab.grid(True, which='both')
pylab.xlim(-.025,xLimit+.025)
pylab.xlabel('Time')
pylab.ylabel('Index')

for i in range(len(rawData)) :
    mpl.pyplot.hlines(i+1, rawData[i,1], rawData[i,2], colors=colorPalette[int(rawData[i,0])])

# build the legend 
dimensions = []
for i in range(int(np.max(rawData[:,0]))+1) :
    dimensions.append(mpl.patches.Patch(color=colorPalette[i], label=r'$H_{}$'.format(i)))

#pylab.legend(handles=dimensions, loc='upper left', bbox_to_anchor=(.05,1))
if not args.nolegend :
    pylab.legend(handles=dimensions, loc='center right', bbox_to_anchor=(1,.65))

displayGraph(inFile[0:len(inFile)-4] + '-barcode')
示例#38
0
q = 0.5
MyCollector = Collector(p, q)
for index in range(101):
    for i in range(int(y[index])):
        data = BloomFilter(index, 4)
        bf = data.getBloomFilter()
        start = data.getSecurityDomain1()
        end = data.getSecurityDomain2()
        response = RRM(bf, p, q, start, end)
        pbf = response.randomer()
        MyCollector.receiver(pbf, start, end)
    #print(pbf)
result = MyCollector.getResult()
#print(result)

for i in range(0, 101):
    z[i] = int(result[i])

plt.bar(x, z, color='g')
plt.title('PLDP Mechanism with security domain')
plt.xlabel('residents\' age')
plt.ylabel('residents\'number')
plt.show()

a = 0
b = 0
for i in range(101):
    a += y[i]
    b += abs(z[i] - y[i])
print(b / a)
示例#39
0
vmin = -7
vmax = -2
pl.figure(2, figsize=(16, 9)).patch.set_facecolor('w')
pl.subplots_adjust(hspace=0.5, wspace=0.3, left=.07, right=.95)
sp1 = pl.subplot(2, 3, 1)
pl.pcolormesh(
    x_grid_probes,
    y_grid_probes,
    np.log10(np.sqrt(Ex_singlegrid_matrix**2 + Ey_singlegrid_matrix**2).T),
    vmin=vmin,
    vmax=vmax)
for ii in xrange(pic_multigrid.n_grids):
    sp1.plot(pic_multigrid.pic_list[ii].pic_internal.chamb.Vx,
             pic_multigrid.pic_list[ii].pic_internal.chamb.Vy, '.-')
pl.xlabel('x [m]')
pl.ylabel('y [m]')
cb = pl.colorbar()
pl.axis('equal')
cb.formatter.set_powerlimits((0, 0))
cb.update_ticks()
cb.set_label('E [V/m]')
pl.title('Singlegrid electric field', y=1.08)
sp1.ticklabel_format(style='sci', scilimits=(0, 0), axis='x')
sp1.ticklabel_format(style='sci', scilimits=(0, 0), axis='y')

sp2 = pl.subplot(2, 3, 4, sharex=sp1, sharey=sp1)
pl.pcolormesh(x_grid_probes,
              y_grid_probes,
              np.log10(
                  np.sqrt(Ex_multigrid_matrix**2 + Ey_multigrid_matrix**2).T),
              vmin=vmin,
# xmax = mean_sample+4*standardDeviation_sample
# smoothedPDF = smoothed.drawPDF(xmin,xmax, 251)
# smoothedPDF_draw = smoothedPDF.getDrawable(0)
# viewer.View(smoothedPDF_draw)

Sample_B = Beta.getSample(samplesize)
aSample_B = np.array(Sample_B).flatten()
# for i in range(samplesize-1):
	# print(format(str('{0:.3f}'.format(aSample_B[i]))))


plb.figure(1)
plb.hist(aSample_B, normed=True, bins=np.floor(np.sqrt(samplesize)), alpha=0.7, label='Tirages_meta-modele')
plb.hist(F, normed=True, bins=np.floor(np.sqrt(N_ref)), alpha=0.1, label='Tirages_monte-carlo')
plb.xlabel('Yf[%]')
plb.ylabel('Densite de probabilite')
plb.title = ('IT'+IT0+'_COMPARAISON_Hist_Loi')
red_patch = mpatches.Patch(color='red', label='Loi Beta')
plb.legend(handles=[red_patch])
plb.legend(loc='upper right')
plb.savefig('IT'+IT0+'/IT'+IT0+'_RESULT_PROBABILITY.png')



myDist_F = ot.BetaFactory().buildEstimator(FF)
myDist = myDist_F.getDistribution()
myDistPDF = myDist.drawPDF(-10.,55.,251)
myDist_Draw = myDistPDF.getDrawable(0)
myDist_Draw.setColor('blue')
myDist_Draw.setLegend('Monte-Carlo : '+str(N_ref)+' realisations')
示例#41
0
for band in range(m.bands()):
    pylab.hold(True)

    weight = m.bandWeights(band).T
    start = starts[band]

    x = scipy.arange(start - 1, start + weight.shape[1] + 1)
    y = [0] + list(weight[0, :]) + [0]

    pylab.plot(x, y)  #, color = 'black')

    ax = pylab.gca()

    # Show half of the spectrum
    ax.set_xlim([0, spectrumSize / 2])
    ax.set_ylim([0.0, 1.1])

    # Set the ticks units to radians per second
    ticks = ax.get_xticks()
    ax.set_xticklabels(
        ['%.2f' % (float(tick) / spectrumSize) for tick in ticks])

    # Set the title and labels
    pylab.title(
        'Magnitude of the Frequency Response of a \n Bark Bands implementation'
    )
    pylab.xlabel('Normalized Frequency')
    pylab.ylabel('|H(w)| (no unit)')

pylab.show()
示例#42
0
文件: movie.py 项目: mchandra/Bolt
    #plot_grid(x[::5, ::5], y[::5, ::5], alpha=0.5)
    pl.contourf(x,
                y,
                density.T,
                100,
                norm=MidpointNormalize(midpoint=0,
                                       vmin=density_min,
                                       vmax=density_max),
                cmap='bwr')
    #pl.colorbar()
    pl.title(r'Time = ' + "%.2f" % (time_array[start_index + file_number]) +
             " ps")

    #    pl.streamplot(x[:, 0], y[0, :],
    #                  j_x, j_y,
    #                  density=1, color='k',
    #                  linewidth=0.7, arrowsize=1
    #                 )
    #
    #    print (j_x)

    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' % (start_index + file_number) + '.png')
    pl.clf()
def buildOURWEATHERGraphWind(password, myGraphSampleCount):
    		print('buildOURWEATHERGraph - The time is: %s' % datetime.now())

		# open database
		con1 = mdb.connect('localhost', 'root', password, 'DataLogger' )
		# now we have to get the data, stuff it in the graph 

    		mycursor = con1.cursor()

		print myGraphSampleCount
		query = '(SELECT timestamp, deviceid, Current_Wind_Speed, Current_Wind_Gust, OurWeather_Station_Name, id FROM '+OURWEATHERtableName+' ORDER BY id DESC LIMIT '+ str(myGraphSampleCount) + ') ORDER BY id ASC' 

		print "query=", query
		try:
			mycursor.execute(query)
			result = mycursor.fetchall()
		except:
			e=sys.exc_info()[0]
			print "Error: %s" % e


		t = []   # time
		u = []   # Current Wind Speed
		v = []   # Current Wind Gust 
		averageWindSpeed = 0.0
 		currentCount = 0

		for record in result:
			t.append(record[0])
			u.append(kph2mph(record[2]))
			#v.append(record[3])
			averageWindSpeed = averageWindSpeed+kph2mph(record[2])
			currentCount=currentCount+1
			StationName = record[4]

		averageWindSpeed = averageWindSpeed/currentCount
		
		print ("count of t=",len(t))

		fds = dates.date2num(t) # converted
		# matplotlib date format object
		#hfmt = dates.DateFormatter('%H:%M:%S')
		hfmt = dates.DateFormatter('%m/%d-%H' ,tz=tz.gettz('US/Pacific'))

		fig = pyplot.figure()
		fig.set_facecolor('white')
		ax = fig.add_subplot(111,axisbg = 'white')
		ax.vlines(fds, -200.0, 1000.0,colors='w')



		#ax.xaxis.set_major_locator(dates.MinuteLocator(interval=1))
		ax.xaxis.set_major_formatter(hfmt)
		ax.set_ylim(bottom = -200.0)
		pyplot.xticks(rotation='45')
		pyplot.subplots_adjust(bottom=.3)
		pylab.plot(t, u, color='r',label="Wind Speed (MPH)" ,linestyle="o",marker=".")
		#pylab.plot(t, v, color='b',label="Wind Gust (MPH)" ,linestyle="o",marker=".")
		pylab.xlabel("Time (Pacific)")
		pylab.ylabel("Wind (MPH)")
		pylab.legend(loc='lower center')
		pylab.axis([min(t), max(t), min(u)-20, max(u)+20])
		pylab.figtext(.5, .05, ("%s Average Windspeed %6.2f MPH\n%s") %( StationName, averageWindSpeed, datetime.now()),fontsize=18,ha='center')

		pylab.grid(True)

		pyplot.show()
		pyplot.savefig("/var/www/html/OURWEATHERDataLoggerGraphWind.png", facecolor=fig.get_facecolor())	



		mycursor.close()       	 
		con1.close()

		fig.clf()
		pyplot.close()
		pylab.close()
		gc.collect()
		print "------OURWEATHERGraphWind finished now"
    X, y, eps=eps, l1_ratio=0.8, fit_intercept=False)

print("Computing regularization path using the positve elastic net...")
alphas_positive_enet, coefs_positive_enet, _ = enet_path(
    X, y, eps=eps, l1_ratio=0.8, positive=True, fit_intercept=False)

# Display results

pl.figure(1)
ax = pl.gca()
ax.set_color_cycle(2 * ['b', 'r', 'g', 'c', 'k'])
l1 = pl.plot(-np.log10(alphas_lasso), coefs_lasso.T)
l2 = pl.plot(-np.log10(alphas_enet), coefs_enet.T, linestyle='--')

pl.xlabel('-Log(alpha)')
pl.ylabel('coefficients')
pl.title('Lasso and Elastic-Net Paths')
pl.legend((l1[-1], l2[-1]), ('Lasso', 'Elastic-Net'), loc='lower left')
pl.axis('tight')


pl.figure(2)
ax = pl.gca()
ax.set_color_cycle(2 * ['b', 'r', 'g', 'c', 'k'])
l1 = pl.plot(-np.log10(alphas_lasso), coefs_lasso.T)
l2 = pl.plot(-np.log10(alphas_positive_lasso), coefs_positive_lasso.T,
              linestyle='--')

pl.xlabel('-Log(alpha)')
pl.ylabel('coefficients')
pl.title('Lasso and positive Lasso')
示例#45
0
if __name__ == "__main__":
    data_list = []
    h1 = HLL()
    h = countmemaybe.HyperLogLog()
    for i in range(100000):
        item = "seee%seeeed234rsdaf" % i
        x = h._hash(item)
        h1.add(x)
        h.add(x)
        data_list.append((i + 1, len(h1), len(h)))

    data_numpy = np.asarray(data_list)
    py.plot(data_numpy[:, 0],
            data_numpy[:, 1],
            ':',
            label="Single HLL Register")
    py.plot(data_numpy[:, 0],
            data_numpy[:, 2],
            '--',
            label="HLL with 16 registers")
    py.plot(data_numpy[:, 0], data_numpy[:, 0], label="Actual Size")
    py.legend(loc='upper left')

    py.title("Performance of a single HLL Register")
    py.xlabel("Size of the set")
    py.ylabel("Predicted size of the set")

    py.savefig("images/hll_single_reg.png")
    py.show()
def buildOURWEATHERGraphSolarVoltage(password, myGraphSampleCount):
    		print('buildOURWEATHERGraphSolar - The time is: %s' % datetime.now(timezone('US/Pacific')))

		# open database
		con1 = mdb.connect('localhost', 'root', password, 'DataLogger' )
		# now we have to get the data, stuff it in the graph 

    		mycursor = con1.cursor()

		print myGraphSampleCount
		query = '(SELECT timestamp, deviceid, Outdoor_Temperature, Outdoor_Humidity, Battery_Voltage, Battery_Current, Solar_Voltage, Solar_Current,  Load_Current, id FROM '+OURWEATHERtableName+' ORDER BY id DESC LIMIT '+ str(myGraphSampleCount) + ') ORDER BY id ASC' 

		print "query=", query
		try:
			mycursor.execute(query)
			result = mycursor.fetchall()
		except:
			e=sys.exc_info()[0]
			print "Error: %s" % e

		
		t = []   # time
		u = []   # Battery_Voltage
		v = []   # Solar_Voltage 
		averagePowerIn = 0.0
		averagePowerOut = 0.0
 		currentCount = 0

		for record in result:
			t.append(record[0])
			u.append(record[4])
			v.append(record[6])

		print ("count of t=",len(t))

		fds = dates.date2num(t) # converted
		# matplotlib date format object
		hfmt = dates.DateFormatter('%H:%M:%S')
		#hfmt = dates.DateFormatter('%m/%d-%H')

		fig = pyplot.figure()
		fig.set_facecolor('white')
		ax = fig.add_subplot(111,axisbg = 'white')
		ax.vlines(fds, -200.0, 1000.0,colors='w')
		
		ax2 = fig.add_subplot(111,axisbg = 'white')


		ax.xaxis.set_major_formatter(hfmt)
		pyplot.xticks(rotation='45')
		pyplot.subplots_adjust(bottom=.3)
		pylab.plot(t, u, color='red',label="Battery Voltage (V) ",linestyle="-",marker=".")
		pylab.plot(t, v, color='green',label="Solar Voltage (V) ",linestyle="-",marker=".")
		pylab.xlabel("Time")
		pylab.ylabel("Voltage (V)")
		pylab.legend(loc='upper left', fontsize='x-small')
		pylab.axis([min(t), max(t), 0, 7])


		pylab.figtext(.5, .05, ("Solar Voltage Performance OurWeather\n%s") % datetime.now(timezone('US/Pacific')),fontsize=18,ha='center')
		pylab.grid(True)

		pyplot.show()
		pyplot.savefig("/var/www/html/OURWEATHERDataLoggerGraphSolarVoltage.png", facecolor=fig.get_facecolor())	



		mycursor.close()       	 
		con1.close()

		fig.clf()
		pyplot.close()
		pylab.close()
		gc.collect()
		print "------OURWEATHERGraphSolarVoltage finished now"
示例#47
0
    def plot_histogram(self,
                       bins=None,
                       fig_args=None,
                       width=0.8,
                       font_size=18):
        ''' Plots a histogram of the number of transmissions '''
        if bins is None:
            max_infections = self.n_targets.max()
            bins = np.arange(0, max_infections + 2)

        # Analysis
        counts = np.histogram(self.n_targets, bins)[0]

        bins = bins[:-1]  # Remove last bin since it's an edge
        total_counts = counts * bins
        # counts = counts*100/counts.sum()
        # total_counts = total_counts*100/total_counts.sum()
        n_bins = len(bins)
        n_trans = sum(total_counts)
        index = np.linspace(0, 100, len(self.n_targets))
        sorted_arr = np.sort(self.n_targets)
        sorted_sum = np.cumsum(sorted_arr)
        sorted_sum = sorted_sum / sorted_sum.max() * 100
        change_inds = sc.findinds(np.diff(sorted_arr) != 0)

        # Plotting
        fig_args = sc.mergedicts(dict(figsize=(24, 15)))
        pl.rcParams['font.size'] = font_size
        fig = pl.figure(**fig_args)
        pl.set_cmap('Spectral')
        pl.subplots_adjust(left=0.08, right=0.92, bottom=0.08, top=0.92)
        colors = sc.vectocolor(n_bins)

        pl.subplot(1, 2, 1)
        w05 = width * 0.5
        w025 = w05 * 0.5
        pl.bar(bins - w025,
               counts,
               width=w05,
               facecolor='k',
               label='Number of events')
        for i in range(n_bins):
            label = 'Number of transmissions (events × transmissions per event)' if i == 0 else None
            pl.bar(bins[i] + w025,
                   total_counts[i],
                   width=w05,
                   facecolor=colors[i],
                   label=label)
        pl.xlabel('Number of transmissions per person')
        pl.ylabel('Count')
        pl.xticks(ticks=bins)
        pl.legend()
        pl.title('Numbers of events and transmissions')

        pl.subplot(2, 2, 2)
        total = 0
        for i in range(n_bins):
            new = total_counts[i] / n_trans * 100
            pl.bar(bins[i:],
                   new,
                   width=width,
                   bottom=total,
                   facecolor=colors[i])
            total += new
        pl.xticks(ticks=bins)
        pl.xlabel('Number of transmissions per person')
        pl.ylabel('Proportion of infections caused (%)')
        pl.title('Proportion of transmissions, by number of transmissions')

        pl.subplot(2, 2, 4)
        pl.plot(index, sorted_sum, lw=3, c='k', alpha=0.5)
        for i in range(len(change_inds)):
            pl.scatter([index[change_inds[i]]], [sorted_sum[change_inds[i]]],
                       s=150,
                       zorder=10,
                       c=[colors[i]],
                       label=f'Transmitted to {i+1} people')
        pl.xlabel(
            'Proportion of population, ordered by the number of people they infected (%)'
        )
        pl.ylabel('Proportion of infections caused (%)')
        pl.legend()
        pl.ylim([0, 100])
        pl.title('Proportion of transmissions, by proportion of population')

        pl.axes([0.25, 0.65, 0.2, 0.2])
        berry = [0.8, 0.1, 0.2]
        pl.plot(self.sim_results.t,
                self.sim_results.cum_infections,
                lw=2,
                c=berry)
        pl.xlabel('Day')
        pl.ylabel('Cumulative infections')

        return fig
def buildOURWEATHERGraphTemperature(password, myGraphSampleCount):
    		print('buildOURWEATHERGraph - The time is: %s' % datetime.now())

		# open database
		con1 = mdb.connect('localhost', 'root', password, 'DataLogger' )
		# now we have to get the data, stuff it in the graph 

    		mycursor = con1.cursor()

		print myGraphSampleCount
		query = '(SELECT timestamp, deviceid, Outdoor_Temperature, Outdoor_Humidity, OurWeather_Station_Name, id FROM '+OURWEATHERtableName+' ORDER BY id DESC LIMIT '+ str(myGraphSampleCount) + ') ORDER BY id ASC' 

		print "query=", query
		try:
			mycursor.execute(query)
			result = mycursor.fetchall()
		except:
			e=sys.exc_info()[0]
			print "Error: %s" % e


		t = []   # time
		u = []   # Outdoor temperature
		v = []   # Outdoor humidity
		averageTemperature = 0.0
 		currentCount = 0

		for record in result:
			t.append(record[0])
			u.append(CtoF(record[2]))
			v.append(record[3])
			averageTemperature = averageTemperature+ CtoF(record[2])
			currentCount=currentCount+1
			StationName = record[4]

		averageTemperature = averageTemperature/currentCount
		
		print ("count of t=",len(t))

		fds = dates.date2num(t) # converted
		# matplotlib date format object
		#hfmt = dates.DateFormatter('%H:%M:%S',tz=tz.gettz('US/Pacific'))
		hfmt = dates.DateFormatter('%m/%d-%H' ,tz=tz.gettz('US/Pacific'))

		fig = pyplot.figure()
		fig.set_facecolor('white')
		ax = fig.add_subplot(111,axisbg = 'white')
		ax.vlines(fds, -200.0, 1000.0,colors='w')
		
		ax2 = fig.add_subplot(111,axisbg = 'white')



		ax.xaxis.set_major_formatter(hfmt)
		pyplot.xticks(rotation='45')
		pyplot.subplots_adjust(bottom=.3)
		pylab.plot(t, u, color='r',label="Outside Temp (F) ",linestyle="-",marker=".")
		pylab.xlabel("Time(Pacific)")
		pylab.ylabel("degrees F")
		pylab.legend(loc='upper left')
		pylab.axis([min(t), max(t), -20, 110])

		ax2 = pylab.twinx()
		pylab.ylabel("% ")
		pylab.plot(t, v, color='b',label="Outside Hum %",linestyle="-",marker=".")
		pylab.axis([min(t), max(t), 0, 100])
		pylab.legend(loc='lower left')
		pylab.figtext(.5, .05, ("%s Average Temperature %6.2f F\n%s") %( StationName, averageTemperature, datetime.now()),fontsize=18,ha='center')
		pylab.grid(True)

		pyplot.show()
		pyplot.savefig("/var/www/html/OURWEATHERDataLoggerGraphTemperature.png", facecolor=fig.get_facecolor())	



		mycursor.close()       	 
		con1.close()

		fig.clf()
		pyplot.close()
		pylab.close()
		gc.collect()
		print "------OURWEATHERGraphTemperature finished now"
示例#49
0
    cut      = np.where((TRUEEWS == EW) & (es > 2.e4))
    pl.scatter(TRUEZS[cut], TRUEMAGS[cut], c='k', marker='x', alpha=0.2)

    print('Number with no redshifts in maximum exposure: %d' % len(es[cut]))

    cut      = np.where((TRUEEWS == EW) & (es < 2.e4))
    ##  plt.pcolormesh(xv, yv, zv, cmap=cmap, norm=norm) 
    pl.scatter(TRUEZS[cut], TRUEMAGS[cut], c=es[cut].astype(np.float), marker='^', cmap=cmap, norm=norm)
    
    plt.text(4.5, 26.25, EW+r'$\AA$')

    pl.xlim(np.unique(TRUEZS)[0], np.unique(TRUEZS)[-1])
    pl.ylim(np.unique(TRUEMAGS[np.isfinite(TRUEMAGS)])[0], np.unique(TRUEMAGS[np.isfinite(TRUEMAGS)])[-1])

    pl.xlabel(r'$z$')
    pl.ylabel(r'$r_{AB}$')

    ax      = pl.gca()
    divider = make_axes_locatable(ax)
    cax     = divider.append_axes("right", size="5%", pad=0.05)

    cb      = mpl.colorbar.ColorbarBase(cax, cmap=cmap, norm=norm, spacing='proportional', ticks=bounds+0.5,\
                                        boundaries=bounds, format='%.2lf')

    cb.set_ticklabels(bounds, update_ticks=True)
    cb.set_label('Exposure time [1500 s]', rotation=270, labelpad=20)
        
    plt.tight_layout()

    pl.savefig(os.environ['BEAST'] + '/redrock/plots/%s/%s/expgrid_%s.pdf' % (survey, target, EW.replace('.', 'p')), bbox_inches='tight')
示例#50
0
            data = reader.cleanData(data)

            ax = fig.add_subplot(211)
            print data.keys()
            n, bins, patches = pylab.hist(1e9 *
                                          np.array(data["+ WIDTH1Current"]),
                                          80,
                                          histtype="step",
                                          linewidth=3)
            maxValue = np.where(n == n.max())[0][0]
            #      maxValue = max( n[ 20 : ] )
            #      maxValue_index = list( n ).index( maxValue )
            p1, success, bin_centres = fit(n, bins, 100, bins[maxValue], 5,
                                           maxValue - 20, maxValue + 10)
            pylab.xlabel("Width (ns)")
            pylab.ylabel("Counts")
            print p1, success
            pylab.grid()
            #      ydata = fitfunc( p1, bin_centres )

            ax = fig.add_subplot(212)
            dataTimes = cutTimes(data["+ WIDTH1Current"],
                                 data["TIME(31Current"], p1[1], p1[2])
            meanValue = 1e9 * np.median(dataTimes)
            print "MeanValue:", meanValue
            n, bins, patches = pylab.hist(1e9 * np.array(dataTimes),
                                          100, [meanValue - 5, meanValue + 5],
                                          histtype="step",
                                          linewidth=3)
            maxValue = np.where(n == n.max())[0][0]
            p1, success, bin_centres = fit(n, bins, 100, bins[maxValue], 1,
示例#51
0
文件: main.py 项目: shyams2/Bolt
    # Declaring a linear system object which will 
    # evolve the defined physical system:
    nls = nonlinear_solver(system)
    n_nls_initial = nls.compute_moments('density')
    time_evolution(nls)
    n_nls    = nls.compute_moments('density')

    N_g      = nls.N_ghost
    error[i] = af.mean(af.abs(  n_nls[N_g:-N_g, N_g:-N_g] 
                              - n_nls_initial[N_g:-N_g, N_g:-N_g]
                             )
                      )
    
    pl.plot(n_nls[N_g:-N_g, 0])
    pl.plot(n_nls_initial[N_g:-N_g, 0], '--', color = 'black')
    pl.savefig(str(N[i])+'.png')
    pl.clf()

pl.loglog(N, error, 'o-', label = 'Numerical')
pl.loglog(N, error[0]*32/N, '--', color = 'black', 
          label = r'$O(N^{-1})$'
         )
pl.loglog(N, error[0]*32**2/N**2, '-.', color = 'black', 
          label = r'$O(N^{-2})$'
         )
pl.legend(loc = 'best')
pl.ylabel('Error')
pl.xlabel('$N$')
pl.savefig('convergence_plot.png')
示例#52
0
    def animate(self, *args, **kwargs):
        '''
        Animate the transmission tree.

        Args:
            animate    (bool):  whether to animate the plot (otherwise, show when finished)
            verbose    (bool):  print out progress of each frame
            markersize (int):   size of the markers
            sus_color  (list):  color for susceptibles
            fig_args   (dict):  arguments passed to pl.figure()
            axis_args  (dict):  arguments passed to pl.subplots_adjust()
            plot_args  (dict):  arguments passed to pl.plot()
            delay      (float): delay between frames in seconds
            font_size  (int):   size of the font
            colors     (list):  color of each person
            cmap       (str):   colormap for each person (if colors is not supplied)

        Returns:
            fig: the figure object
        '''

        # Settings
        animate = kwargs.get('animate', True)
        verbose = kwargs.get('verbose', False)
        msize = kwargs.get('markersize', 10)
        sus_color = kwargs.get('sus_color', [0.5, 0.5, 0.5])
        fig_args = kwargs.get('fig_args', dict(figsize=(24, 16)))
        axis_args = kwargs.get(
            'axis_args',
            dict(left=0.10,
                 bottom=0.05,
                 right=0.85,
                 top=0.97,
                 wspace=0.25,
                 hspace=0.25))
        plot_args = kwargs.get('plot_args', dict(lw=2, alpha=0.5))
        delay = kwargs.get('delay', 0.2)
        font_size = kwargs.get('font_size', 18)
        colors = kwargs.get('colors', None)
        cmap = kwargs.get('cmap', 'parula')
        pl.rcParams['font.size'] = font_size
        if colors is None:
            colors = sc.vectocolor(self.pop_size, cmap=cmap)

        # Initialization
        n = self.n_days + 1
        frames = [list() for i in range(n)]
        tests = [list() for i in range(n)]
        diags = [list() for i in range(n)]
        quars = [list() for i in range(n)]

        # Construct each frame of the animation
        for ddict in self.detailed:  # Loop over every person
            if ddict is None:
                continue  # Skip the 'None' node corresponding to seeded infections

            frame = sc.objdict()
            tdq = sc.objdict()  # Short for "tested, diagnosed, or quarantined"
            target = ddict.t
            target_ind = ddict['target']

            if not np.isnan(ddict['date']):  # If this person was infected

                source_ind = ddict[
                    'source']  # Index of the person who infected the target

                target_date = ddict['date']
                if source_ind is not None:  # Seed infections and importations won't have a source
                    source_date = self.detailed[source_ind]['date']
                else:
                    source_ind = 0
                    source_date = 0

                # Construct this frame
                frame.x = [source_date, target_date]
                frame.y = [source_ind, target_ind]
                frame.c = colors[source_ind]
                frame.i = True  # If this person is infected
                frames[int(target_date)].append(frame)

                # Handle testing, diagnosis, and quarantine
                tdq.t = target_ind
                tdq.d = target_date
                tdq.c = colors[int(target_ind)]
                date_t = target['date_tested']
                date_d = target['date_diagnosed']
                date_q = target['date_known_contact']
                if ~np.isnan(date_t) and date_t < n:
                    tests[int(date_t)].append(tdq)
                if ~np.isnan(date_d) and date_d < n:
                    diags[int(date_d)].append(tdq)
                if ~np.isnan(date_q) and date_q < n:
                    quars[int(date_q)].append(tdq)

            else:
                frame.x = [0]
                frame.y = [target_ind]
                frame.c = sus_color
                frame.i = False
                frames[0].append(frame)

        # Configure plotting
        fig = pl.figure(**fig_args)
        pl.subplots_adjust(**axis_args)
        ax = fig.add_subplot(1, 1, 1)

        # Create the legend
        ax2 = pl.axes([0.85, 0.05, 0.14, 0.9])
        ax2.axis('off')
        lcol = colors[0]
        na = np.nan  # Shorten
        pl.plot(na, na, '-', c=lcol, **plot_args, label='Transmission')
        pl.plot(na,
                na,
                'o',
                c=lcol,
                markersize=msize,
                **plot_args,
                label='Source')
        pl.plot(na,
                na,
                '*',
                c=lcol,
                markersize=msize,
                **plot_args,
                label='Target')
        pl.plot(na,
                na,
                'o',
                c=lcol,
                markersize=msize * 2,
                fillstyle='none',
                **plot_args,
                label='Tested')
        pl.plot(na,
                na,
                's',
                c=lcol,
                markersize=msize * 1.2,
                **plot_args,
                label='Diagnosed')
        pl.plot(na,
                na,
                'x',
                c=lcol,
                markersize=msize * 2.0,
                label='Known contact')
        pl.legend()

        # Plot the animation
        pl.sca(ax)
        for day in range(n):
            pl.title(f'Day: {day}')
            pl.xlim([0, n])
            pl.ylim([0, len(self)])
            pl.xlabel('Day')
            pl.ylabel('Person')
            flist = frames[day]
            tlist = tests[day]
            dlist = diags[day]
            qlist = quars[day]
            for f in flist:
                if verbose: print(f)
                pl.plot(f.x[0],
                        f.y[0],
                        'o',
                        c=f.c,
                        markersize=msize,
                        **plot_args)  # Plot sources
                pl.plot(f.x, f.y, '-', c=f.c,
                        **plot_args)  # Plot transmission lines
                if f.i:  # If this person is infected
                    pl.plot(f.x[1],
                            f.y[1],
                            '*',
                            c=f.c,
                            markersize=msize,
                            **plot_args)  # Plot targets
            for tdq in tlist:
                pl.plot(tdq.d,
                        tdq.t,
                        'o',
                        c=tdq.c,
                        markersize=msize * 2,
                        fillstyle='none')  # Tested; No alpha for this
            for tdq in dlist:
                pl.plot(tdq.d,
                        tdq.t,
                        's',
                        c=tdq.c,
                        markersize=msize * 1.2,
                        **plot_args)  # Diagnosed
            for tdq in qlist:
                pl.plot(tdq.d, tdq.t, 'x', c=tdq.c, markersize=msize *
                        2.0)  # Quarantine; no alpha for this
            pl.plot([0, day], [0.5, 0.5], c='k',
                    lw=5)  # Plot the endless march of time
            if animate:  # Whether to animate
                pl.pause(delay)

        return fig
示例#53
0
        start = time[0]
        end = time[len(time) - 1]

        time_folded = [t / (results[1]) for t in time]
        time_folded = [i % 1 for i in time_folded]

        #replace p with results[1]

        #phase = [math.fmod(((i-start)/results[1]),1) for i in time]

        pylab.cla()

        #UNCOMMENT TO SAVE PHASE FOLDED PLOT

        xlabel('Phase')
        ylabel('Corrected Flux (normalized to 0)')
        title('EPIC (name) Merged Phase Folded Light Curve: Period' + str(p) +
              ' Radius Ratio ' + str(r))
        plt.scatter(time_folded, merged_flux)
        #pylab.savefig("/Users/sheilasagear/OneDrive/K2_Research/bls-ktransit/LC_5/Period" + str(p) + "Radius" + str(r) + "/folded_pltPer" + str(p) + "Rad" + str(r) + '.png')

        #pylab.show()
        """
        high = results[3]*results[4]
        low = high - results[3]

        print(high, low)
        
        fit = numpy.zeros(1765) + high # H
        fit[results[5]:results[6]+1] = low # L
    
示例#54
0
def main():
    """Tests that EV compensation is applied.
    """
    LOCKED = 3

    NAME = os.path.basename(__file__).split(".")[0]

    with its.device.ItsSession() as cam:
        props = cam.get_camera_properties()
        its.caps.skip_unless(
            its.caps.ev_compensation(props) and its.caps.ae_lock(props))

        debug = its.caps.debug_mode()
        if debug:
            fmt = its.objects.get_largest_yuv_format(props)
        else:
            fmt = its.objects.get_smallest_yuv_format(props)

        ev_per_step = its.objects.rational_to_float(
            props['android.control.aeCompensationStep'])
        steps_per_ev = int(1.0 / ev_per_step)
        evs = range(-2 * steps_per_ev, 2 * steps_per_ev + 1, steps_per_ev)
        lumas = []
        reds = []
        greens = []
        blues = []

        # Converge 3A, and lock AE once converged. skip AF trigger as
        # dark/bright scene could make AF convergence fail and this test
        # doesn't care the image sharpness.
        cam.do_3a(ev_comp=0, lock_ae=True, do_af=False)

        for ev in evs:

            # Capture a single shot with the same EV comp and locked AE.
            req = its.objects.auto_capture_request()
            req['android.control.aeExposureCompensation'] = ev
            req["android.control.aeLock"] = True
            caps = cam.do_capture([req] * THRESH_CONVERGE_FOR_EV, fmt)
            for cap in caps:
                if (cap['metadata']['android.control.aeState'] == LOCKED):
                    y = its.image.convert_capture_to_planes(cap)[0]
                    tile = its.image.get_image_patch(y, 0.45, 0.45, 0.1, 0.1)
                    lumas.append(its.image.compute_image_means(tile)[0])
                    rgb = its.image.convert_capture_to_rgb_image(cap)
                    rgb_tile = its.image.get_image_patch(
                        rgb, 0.45, 0.45, 0.1, 0.1)
                    rgb_means = its.image.compute_image_means(rgb_tile)
                    reds.append(rgb_means[0])
                    greens.append(rgb_means[1])
                    blues.append(rgb_means[2])
                    break
            assert (cap['metadata']['android.control.aeState'] == LOCKED)

        pylab.plot(evs, lumas, '-ro')
        pylab.xlabel('EV Compensation')
        pylab.ylabel('Mean Luma (Normalized)')
        matplotlib.pyplot.savefig("%s_plot_means.png" % (NAME))

        # Trim extra saturated images
        while lumas and lumas[-1] >= YUV_SATURATION_MIN / YUV_FULL_SCALE:
            if (np.isclose(reds[-1], greens[-1],
                           YUV_SATURATION_TOL / YUV_FULL_SCALE)
                    and np.isclose(blues[-1], greens[-1],
                                   YUV_SATURATION_TOL / YUV_FULL_SCALE)):
                lumas.pop(-1)
                reds.pop(-1)
                greens.pop(-1)
                blues.pop(-1)
                print 'Removed saturated image.'
            else:
                break
        # Only allow positive EVs to give saturated image
        assert (len(lumas) > 2)
        luma_diffs = np.diff(lumas)
        min_luma_diffs = min(luma_diffs)
        print "Min of the luma value difference between adjacent ev comp: ", \
                min_luma_diffs
        # All luma brightness should be increasing with increasing ev comp.
        assert (min_luma_diffs > 0)
示例#55
0
def PowerCurrentGraph(source, days, delay):

    print("PowerCurrentGraph source:%s days:%s delay:%i" %
          (source, days, delay))
    print("sleeping :", delay)
    time.sleep(delay)
    print("PowerCurrentGraph running now")

    # blink GPIO LED when it's run
    GPIO.setup(18, GPIO.OUT)
    GPIO.output(18, True)
    time.sleep(0.2)
    GPIO.output(18, False)

    # now we have get the data, stuff it in the graph

    try:
        print("trying database")
        db = mdb.connect('localhost', 'root', config.MySQL_Password,
                         'GroveWeatherPi')

        cursor = db.cursor()

        query = "SELECT TimeStamp, solarCurrent, batteryCurrent, loadCurrent FROM PowerSystem where  now() - interval %i hour < TimeStamp" % (
            days * 24)
        cursor.execute(query)
        result = cursor.fetchall()

        t = []
        s = []
        u = []
        v = []
        #x = []

        for record in result:
            t.append(record[0])
            s.append(record[1])
            u.append(record[2])
            v.append(record[3])
            #x.append(record[4])
        fig = pyplot.figure()

        print("count of t=", len(t))
        #print (t)
        if (len(t) == 0):
            return
        #dts = map(datetime.datetime.fromtimestamp, t)
        #print dts
        #fds = dates.date2num(t) # converted
        # matplotlib date format object
        hfmt = dates.DateFormatter('%m/%d-%H')

        fig.set_facecolor('white')
        ax = fig.add_subplot(111, axisbg='white')
        #ax.vlines(fds, -200.0, 1000.0,colors='w')

        ax.xaxis.set_major_locator(dates.HourLocator(interval=6))
        ax.xaxis.set_major_formatter(hfmt)
        ax.set_ylim(bottom=-200.0)
        pyplot.xticks(rotation='vertical')
        pyplot.subplots_adjust(bottom=.3)
        pylab.plot(t, s, color='b', label="Solar", linestyle="-", marker=".")
        pylab.plot(t, u, color='r', label="Battery", linestyle="-", marker=".")
        pylab.plot(t, v, color='g', label="Load", linestyle="-", marker=".")
        #pylab.plot(t, x, color='m',label="Power Eff",linestyle="-",marker=".")
        pylab.xlabel("Hours")
        pylab.ylabel("Current ma")
        pylab.legend(loc='upper left')

        if (max(u) > max(s)):
            myMax = max(u) + 100.0
        else:
            myMax = max(s)
        pylab.axis([min(t), max(t), min(u), myMax])
        pylab.figtext(.5,
                      .05,
                      ("GroveWeatherPi Power Current Last %i Days" % days),
                      fontsize=18,
                      ha='center')
        pyplot.setp(ax.xaxis.get_majorticklabels(), rotation=70)

        pylab.grid(True)

        pyplot.show()
        try:
            pyplot.savefig(
                "/home/pi/RasPiConnectServer/static/PowerCurrentGraph.png",
                facecolor=fig.get_facecolor())
        except:
            pyplot.savefig(
                "/home/pi/SDL_Pi_GroveWeatherPi/static/PowerCurrentGraph.png",
                facecolor=fig.get_facecolor())

    except mdb.Error, e:

        print "Error %d: %s" % (e.args[0], e.args[1])
示例#56
0
def plots(opt):
    from astrometry.util.plotutils import antigray
    import tractor.sfd

    T = fits_table(opt.files[0])
    print('Read', len(T), 'bricks summarized in', opt.files[0])
    import pylab as plt
    import matplotlib

    B = fits_table('survey-bricks.fits.gz')
    print('Looking up brick bounds')
    ibrick = dict([(n, i) for i, n in enumerate(B.brickname)])
    bi = np.array([ibrick[n] for n in T.brickname])
    T.ra1 = B.ra1[bi]
    T.ra2 = B.ra2[bi]
    T.dec1 = B.dec1[bi]
    T.dec2 = B.dec2[bi]
    assert (np.all(T.ra2 > T.ra1))
    T.area = ((T.ra2 - T.ra1) * (T.dec2 - T.dec1) *
              np.cos(np.deg2rad((T.dec1 + T.dec2) / 2.)))
    del B
    del bi
    del ibrick

    print('Total sources:', sum(T.nobjs))
    print('Approx area:', len(T) / 16., 'sq deg')
    print('Area:', np.sum(T.area))
    print('g,r,z coverage:',
          sum((T.nexp_g > 0) * (T.nexp_r > 0) * (T.nexp_z > 0)) / 16.)

    decam = True
    # vs MzLS+BASS
    #release = 'MzLS+BASS DR4'
    release = 'DECaLS DR5'
    #release = 'DECaLS DR3'

    if decam:
        # DECam
        #ax = [360, 0, -21, 36]
        ax = [300, -60, -21, 36]

        def map_ra(r):
            return r + (-360 * (r > 300))

    else:
        # MzLS+BASS
        ax = [310, 90, 30, 80]

        def map_ra(r):
            return r

    udec = np.unique(T.dec)
    print('Number of unique Dec values:', len(udec))
    print('Number of unique Dec values in range', ax[2], ax[3], ':',
          np.sum((udec >= ax[2]) * (udec <= ax[3])))

    def radec_plot():
        plt.axis(ax)
        plt.xlabel('RA (deg)')
        if decam:
            # plt.xticks(np.arange(0, 361, 45))
            #tt = np.arange(0, 361, 60)
            #plt.xticks(tt, map_ra(tt))
            plt.xticks([-60, 0, 60, 120, 180, 240, 300],
                       [300, 0, 60, 120, 180, 240, 300])
        else:
            plt.xticks(np.arange(90, 311, 30))

        plt.ylabel('Dec (deg)')

        def plot_broken(rr, dd, *args, **kwargs):
            dr = np.abs(np.diff(rr))
            I = np.flatnonzero(dr > 90)
            #print('breaks:', rr[I])
            #print('breaks:', rr[I+1])
            if len(I) == 0:
                plt.plot(rr, dd, *args, **kwargs)
                return
            for lo, hi in zip(np.append([0], I + 1), np.append(I + 1, -1)):
                #print('Cut:', lo, ':', hi, '->', rr[lo], rr[hi-1])
                plt.plot(rr[lo:hi], dd[lo:hi], *args, **kwargs)

        # Galactic plane lines
        gl = np.arange(361)
        gb = np.zeros_like(gl)
        from astrometry.util.starutil_numpy import lbtoradec
        rr, dd = lbtoradec(gl, gb)
        plot_broken(map_ra(rr), dd, 'k-', alpha=0.5, lw=1)
        rr, dd = lbtoradec(gl, gb + 10)
        plot_broken(map_ra(rr), dd, 'k-', alpha=0.25, lw=1)
        rr, dd = lbtoradec(gl, gb - 10)
        plot_broken(map_ra(rr), dd, 'k-', alpha=0.25, lw=1)

    plt.figure(1, figsize=(8, 5))
    plt.subplots_adjust(left=0.1, right=0.98, top=0.93)

    plt.figure(2, figsize=(8, 4))
    #plt.subplots_adjust(left=0.06, right=0.98, top=0.98)
    plt.subplots_adjust(left=0.08, right=0.98, top=0.98)
    plt.figure(1)

    # Map of the tile centers we want to observe...
    if decam:
        O = fits_table('obstatus/decam-tiles_obstatus.fits')
    else:
        O = fits_table('mosaic-tiles_obstatus.fits')
    O.cut(O.in_desi == 1)
    rr, dd = np.meshgrid(np.linspace(ax[1], ax[0], 700),
                         np.linspace(ax[2], ax[3], 200))
    from astrometry.libkd.spherematch import match_radec
    I, J, d = match_radec(O.ra, O.dec, rr.ravel(), dd.ravel(), 1.)
    desimap = np.zeros(rr.shape, bool)
    desimap.flat[J] = True

    # Smoothed DESI boundary contours
    from scipy.ndimage.filters import gaussian_filter
    from scipy.ndimage.morphology import binary_dilation
    C = plt.contour(gaussian_filter(
        binary_dilation(desimap).astype(np.float32), 2), [0.5],
                    extent=[ax[1], ax[0], ax[2], ax[3]])
    plt.clf()
    desi_map_boundaries = C.collections[0]

    def desi_map_outline():
        segs = desi_map_boundaries.get_segments()
        for seg in segs:
            plt.plot(seg[:, 0], seg[:, 1], 'b-')

    def desi_map():
        # Show the DESI tile map in the background.
        plt.imshow(desimap,
                   origin='lower',
                   interpolation='nearest',
                   extent=[ax[1], ax[0], ax[2], ax[3]],
                   aspect='auto',
                   cmap=antigray,
                   vmax=8)

    base_cmap = 'viridis'

    # Dust map -- B&W version
    nr, nd = 610, 350
    plt.figure(2)
    plt.clf()
    dmap = np.zeros((nd, nr))
    rr = np.linspace(ax[0], ax[1], nr)
    dd = np.linspace(ax[2], ax[3], nd)
    rr = rr[:-1] + 0.5 * (rr[1] - rr[0])
    dd = dd[:-1] + 0.5 * (dd[1] - dd[0])
    rr, dd = np.meshgrid(rr, dd)
    I, J, d = match_radec(rr.ravel(),
                          dd.ravel(),
                          O.ra,
                          O.dec,
                          1.0,
                          nearest=True)
    iy, ix = np.unravel_index(I, rr.shape)
    #dmap[iy,ix] = O.ebv_med[J]
    sfd = tractor.sfd.SFDMap()
    ebv = sfd.ebv(rr[iy, ix], dd[iy, ix])
    dmap[iy, ix] = ebv
    mx = np.percentile(dmap[dmap > 0], 98)
    plt.imshow(dmap,
               extent=[ax[0], ax[1], ax[2], ax[3]],
               interpolation='nearest',
               origin='lower',
               aspect='auto',
               cmap='Greys',
               vmin=0,
               vmax=mx)
    #desi_map_outline()
    radec_plot()
    cax = colorbar_axes(plt.gca(), frac=0.12)
    cbar = plt.colorbar(cax=cax)
    cbar.set_label('Extinction E(B-V)')
    plt.savefig('ext-bw.pdf')
    plt.clf()
    dmap = sfd.ebv(rr.ravel(), dd.ravel()).reshape(rr.shape)
    plt.imshow(dmap,
               extent=[ax[0], ax[1], ax[2], ax[3]],
               interpolation='nearest',
               origin='lower',
               aspect='auto',
               cmap='Greys',
               vmin=0,
               vmax=0.25)
    desi_map_outline()
    radec_plot()
    cax = colorbar_axes(plt.gca(), frac=0.12)
    cbar = plt.colorbar(cax=cax)
    cbar.set_label('Extinction E(B-V)')
    plt.savefig('ext-bw-2.pdf')
    plt.figure(1)

    #sys.exit(0)

    plt.clf()
    depthlo, depthhi = 21.5, 25.5
    for band in 'grz':
        depth = T.get('galdepth_%s' % band)
        ha = dict(histtype='step', bins=50, range=(depthlo, depthhi))
        ccmap = dict(g='g', r='r', z='m')
        plt.hist(depth[depth > 0],
                 label='%s band' % band,
                 color=ccmap[band],
                 **ha)
    plt.xlim(depthlo, depthhi)
    plt.xlabel('Galaxy depth (median per brick) (mag)')
    plt.ylabel('Number of Bricks')
    plt.title(release)
    plt.savefig('galdepths.png')

    for band in 'grz':
        depth = T.get('galdepth_%s' % band)
        nexp = T.get('nexp_%s' % band)
        #lo,hi = 22.0-0.05, 24.2+0.05
        lo, hi = depthlo - 0.05, depthhi + 0.05
        nbins = 1 + int((depthhi - depthlo) / 0.1)
        ha = dict(histtype='step', bins=nbins, range=(lo, hi))
        ccmap = dict(g='g', r='r', z='m')
        area = 0.25**2
        plt.clf()
        I = np.flatnonzero((depth > 0) * (nexp == 1))
        plt.hist(depth[I],
                 label='%s band, 1 exposure' % band,
                 color=ccmap[band],
                 lw=1,
                 weights=area * np.ones_like(depth[I]),
                 **ha)
        I = np.flatnonzero((depth > 0) * (nexp == 2))
        plt.hist(depth[I],
                 label='%s band, 2 exposures' % band,
                 color=ccmap[band],
                 lw=2,
                 alpha=0.5,
                 weights=area * np.ones_like(depth[I]),
                 **ha)
        I = np.flatnonzero((depth > 0) * (nexp >= 3))
        plt.hist(depth[I],
                 label='%s band, 3+ exposures' % band,
                 color=ccmap[band],
                 lw=3,
                 alpha=0.3,
                 weights=area * np.ones_like(depth[I]),
                 **ha)
        plt.title('%s: galaxy depths, %s band' % (release, band))
        plt.xlabel('5-sigma galaxy depth (mag)')
        plt.ylabel('Square degrees')
        plt.xlim(lo, hi)
        plt.xticks(np.arange(depthlo, depthhi + 0.01, 0.2))
        plt.legend(loc='upper right')
        plt.savefig('depth-hist-%s.png' % band)

    for band in 'grz':
        plt.clf()
        desi_map()
        N = T.get('nexp_%s' % band)
        I = np.flatnonzero(N > 0)
        #cm = matplotlib.cm.get_cmap('jet', 6)
        #cm = matplotlib.cm.get_cmap('winter', 5)

        mx = 10
        cm = cmap_discretize(base_cmap, mx)
        plt.scatter(map_ra(T.ra[I]),
                    T.dec[I],
                    c=N[I],
                    s=3,
                    edgecolors='none',
                    vmin=0.5,
                    vmax=mx + 0.5,
                    cmap=cm)
        radec_plot()
        cax = colorbar_axes(plt.gca(), frac=0.08)
        plt.colorbar(cax=cax, ticks=range(mx + 1))
        plt.title('%s: Number of exposures in %s' % (release, band))
        plt.savefig('nexp-%s.png' % band)

        #cmap = cmap_discretize(base_cmap, 15)
        cmap = cmap_discretize(base_cmap, 10)
        plt.clf()
        desi_map()
        psf = T.get('psfsize_%s' % band)
        I = np.flatnonzero(psf > 0)
        plt.scatter(map_ra(T.ra[I]),
                    T.dec[I],
                    c=psf[I],
                    s=3,
                    edgecolors='none',
                    cmap=cmap,
                    vmin=0.5,
                    vmax=2.5)
        #vmin=0, vmax=3.)
        radec_plot()
        plt.colorbar()
        plt.title('%s: PSF size, band %s' % (release, band))
        plt.savefig('psfsize-%s.png' % band)

        plt.clf()
        desi_map()

        depth = T.get('galdepth_%s' % band) - T.get('ext_%s' % band)
        mn, mx = np.percentile(depth[depth > 0], [10, 98])
        mn = np.floor(mn * 10) / 10.
        mx = np.ceil(mx * 10) / 10.
        cmap = cmap_discretize(base_cmap, 1 + int((mx - mn + 0.001) / 0.1))
        I = (depth > 0)
        plt.scatter(map_ra(T.ra[I]),
                    T.dec[I],
                    c=depth[I],
                    s=3,
                    edgecolors='none',
                    vmin=mn - 0.05,
                    vmax=mx + 0.05,
                    cmap=cmap)
        radec_plot()
        plt.colorbar()
        plt.title(
            '%s: galaxy depth, band %s, median per brick, extinction-corrected'
            % (release, band))
        plt.savefig('galdepth-%s.png' % band)

        # B&W version
        plt.figure(2)
        plt.clf()
        mn, mx = np.percentile(depth[depth > 0], [2, 98])
        print('Raw mn,mx', mn, mx)
        mn = np.floor((mn + 0.05) * 10) / 10. - 0.05
        mx = np.ceil((mx - 0.05) * 10) / 10. + 0.05
        print('rounded mn,mx', mn, mx)
        nsteps = int((mx - mn + 0.001) / 0.1)
        print('discretizing into', nsteps, 'colormap bins')
        #nsteps = 1+int((mx-mn+0.001)/0.1)
        cmap = cmap_discretize(antigray, nsteps)
        nr, nd = 610, 228
        dmap = np.zeros((nd, nr))
        rr = np.linspace(ax[0], ax[1], nr)
        dd = np.linspace(ax[2], ax[3], nd)
        rr = rr[:-1] + 0.5 * (rr[1] - rr[0])
        dd = dd[:-1] + 0.5 * (dd[1] - dd[0])
        rr, dd = np.meshgrid(rr, dd)
        I, J, d = match_radec(rr.ravel(),
                              dd.ravel(),
                              T.ra,
                              T.dec,
                              0.2,
                              nearest=True)
        iy, ix = np.unravel_index(I, rr.shape)
        dmap[iy, ix] = depth[J]
        plt.imshow(dmap,
                   extent=[ax[0], ax[1], ax[2], ax[3]],
                   interpolation='nearest',
                   origin='lower',
                   aspect='auto',
                   cmap=cmap,
                   vmin=mn,
                   vmax=mx)
        desi_map_outline()
        radec_plot()
        cax = colorbar_axes(plt.gca(), frac=0.12)
        cbar = plt.colorbar(
            cax=cax, ticks=np.arange(20, 26, 0.5)
        )  #ticks=np.arange(np.floor(mn/5.)*5., 0.1+np.ceil(mx/5.)*5, 0.2))
        cbar.set_label('Depth (5-sigma, galaxy profile, AB mag)')
        plt.savefig('galdepth-bw-%s.pdf' % band)
        plt.figure(1)

        plt.clf()
        desi_map()
        ext = T.get('ext_%s' % band)
        mn = 0.
        mx = 0.5
        cmap = 'hot'
        cmap = cmap_discretize(cmap, 10)
        #cmap = cmap_discretize(base_cmap, 1+int((mx-mn+0.001)/0.1))
        plt.scatter(map_ra(T.ra),
                    T.dec,
                    c=ext,
                    s=3,
                    edgecolors='none',
                    vmin=mn,
                    vmax=mx,
                    cmap=cmap)
        radec_plot()
        plt.colorbar()
        plt.title('%s: extinction, band %s' % (release, band))
        plt.savefig('ext-%s.png' % band)

    T.ngal = T.nsimp + T.nrex + T.nexp + T.ndev + T.ncomp

    for col in [
            'nobjs', 'npsf', 'nsimp', 'nrex', 'nexp', 'ndev', 'ncomp', 'ngal'
    ]:
        if not col in T.get_columns():
            continue
        plt.clf()
        desi_map()
        N = T.get(col) / T.area
        mx = np.percentile(N, 99.5)
        plt.scatter(map_ra(T.ra),
                    T.dec,
                    c=N,
                    s=3,
                    edgecolors='none',
                    vmin=0,
                    vmax=mx)
        radec_plot()
        cbar = plt.colorbar()
        cbar.set_label('Objects per square degree')
        tt = 'of type %s' % col[1:]
        if col == 'nobjs':
            tt = 'total'
        plt.title('%s: Number of objects %s' % (release, tt))
        plt.savefig('nobjs-%s.png' % col[1:])

        # B&W version
        plt.figure(2)
        plt.clf()
        # plt.scatter(map_ra(T.ra), T.dec, c=N, s=3,
        #             edgecolors='none', vmin=0, vmax=mx, cmap=antigray)
        # Approximate pixel size in PNG plot
        # This doesn't work correctly -- we've already binned to brick resolution, so get moire patterns
        # nobjs,xe,ye = np.histogram2d(map_ra(T.ra), T.dec, weights=T.get(col),
        #                              bins=(nr,nd), range=((ax[1],ax[0]),(ax[2],ax[3])))
        # nobjs = nobjs.T
        # area = np.diff(xe)[np.newaxis,:] * (np.diff(ye) * np.cos(np.deg2rad(ye[:-1])))[:,np.newaxis]
        # nobjs /= area
        # plt.imshow(nobjs, extent=[ax[1],ax[0],ax[2],ax[3]], interpolation='nearest', origin='lower',
        #           aspect='auto')
        #print('Computing neighbours for nobjs plot...')
        nr, nd = 610, 228
        nobjs = np.zeros((nd, nr))
        rr = np.linspace(ax[0], ax[1], nr)
        dd = np.linspace(ax[2], ax[3], nd)
        rr = rr[:-1] + 0.5 * (rr[1] - rr[0])
        dd = dd[:-1] + 0.5 * (dd[1] - dd[0])
        rr, dd = np.meshgrid(rr, dd)
        I, J, d = match_radec(rr.ravel(),
                              dd.ravel(),
                              T.ra,
                              T.dec,
                              0.2,
                              nearest=True)
        iy, ix = np.unravel_index(I, rr.shape)
        nobjs[iy, ix] = T.get(col)[J] / T.area[J]
        #print('done')

        #mx = 2. * np.median(nobjs[nobjs > 0])
        mx = np.percentile(N, 99)

        plt.imshow(nobjs,
                   extent=[ax[0], ax[1], ax[2], ax[3]],
                   interpolation='nearest',
                   origin='lower',
                   aspect='auto',
                   cmap='Greys',
                   vmin=0,
                   vmax=mx)
        desi_map_outline()
        radec_plot()
        #cax = colorbar_axes(plt.gca(), frac=0.08)
        cax = colorbar_axes(plt.gca(), frac=0.12)
        cbar = plt.colorbar(cax=cax,
                            format=matplotlib.ticker.FuncFormatter(
                                lambda x, p: format(int(x), ',')))
        cbar.set_label('Objects per square degree')
        plt.savefig('nobjs-bw-%s.pdf' % col[1:])
        #plt.savefig('nobjs-bw-%s.png' % col[1:])
        plt.figure(1)

    Ntot = T.nobjs
    for col in ['npsf', 'nsimp', 'nrex', 'nexp', 'ndev', 'ncomp', 'ngal']:
        if not col in T.get_columns():
            continue
        plt.clf()
        desi_map()
        N = T.get(col) / (Ntot.astype(np.float32))
        N[Ntot == 0] = 0.
        print(col, 'max frac:', N.max())
        mx = np.percentile(N, 99.5)
        print('mx', mx)
        plt.scatter(map_ra(T.ra),
                    T.dec,
                    c=N,
                    s=3,
                    edgecolors='none',
                    vmin=0,
                    vmax=mx)
        radec_plot()
        plt.colorbar()
        plt.title('%s: Fraction of objects of type %s' % (release, col[1:]))
        plt.savefig('fobjs-%s.png' % col[1:])

        # B&W version
        plt.figure(2)
        plt.clf()
        #plt.scatter(map_ra(T.ra), T.dec, c=N * 100., s=3,
        #            edgecolors='none', vmin=0, vmax=mx*100., cmap=antigray)

        fobjs = np.zeros((nd, nr))
        rr = np.linspace(ax[0], ax[1], nr)
        dd = np.linspace(ax[2], ax[3], nd)
        rr = rr[:-1] + 0.5 * (rr[1] - rr[0])
        dd = dd[:-1] + 0.5 * (dd[1] - dd[0])
        rr, dd = np.meshgrid(rr, dd)
        I, J, d = match_radec(rr.ravel(),
                              dd.ravel(),
                              T.ra,
                              T.dec,
                              0.2,
                              nearest=True)
        iy, ix = np.unravel_index(I, rr.shape)
        fobjs[iy, ix] = N[J] * 100.

        #mx = 2. * np.median(fobjs[fobjs > 0])
        mx = np.percentile(N * 100., 99)

        plt.imshow(fobjs,
                   extent=[ax[0], ax[1], ax[2], ax[3]],
                   interpolation='nearest',
                   origin='lower',
                   aspect='auto',
                   cmap='Greys',
                   vmin=0,
                   vmax=mx)

        desi_map_outline()
        radec_plot()
        cax = colorbar_axes(plt.gca(), frac=0.12)
        cbar = plt.colorbar(
            cax=cax,
            format=matplotlib.ticker.FuncFormatter(lambda x, p: '%.2g' % x))
        cbar.set_label('Percentage of objects of type %s' % col[1:].upper())
        plt.savefig('fobjs-bw-%s.pdf' % col[1:])
        #plt.savefig('fobjs-bw-%s.png' % col[1:])
        plt.figure(1)

    return 0
示例#57
0
y = np.sin(X).ravel()

###############################################################################
# Add noise to targets
y[::5] += 3 * (0.5 - np.random.rand(8))

###############################################################################
# Fit regression model
from sklearn.svm import SVR

svr_rbf = SVR(kernel='rbf', C=1e3, gamma=0.1)
svr_lin = SVR(kernel='linear', C=1e3)
svr_poly = SVR(kernel='poly', C=1e3, degree=2)
y_rbf = svr_rbf.fit(X, y).predict(X)
y_lin = svr_lin.fit(X, y).predict(X)
y_poly = svr_poly.fit(X, y).predict(X)

###############################################################################
# look at the results
import pylab as pl
pl.scatter(X, y, c='k', label='data')
pl.hold('on')
pl.plot(X, y_rbf, c='g', label='RBF model')
pl.plot(X, y_lin, c='r', label='Linear model')
pl.plot(X, y_poly, c='b', label='Polynomial model')
pl.xlabel('data')
pl.ylabel('target')
pl.title('Support Vector Regression')
pl.legend()
pl.show()
示例#58
0
ax.contourf(xx, yy, Z, colors=[MAROON, BLUE], levels=[-1, 0, 1], alpha=0.5)

plt.scatter(X[y == 0, 0],
            X[y == 0, 1],
            color=MAROON,
            label='\emph{Iris setosa}')
plt.scatter(X[y == 1, 0],
            X[y == 1, 1],
            color=BLUE,
            label='\emph{Iris versicolor}')

plt.title('Decision tree')

plt.ylim(1, 5)
plt.xlabel('Sepal length')
plt.ylabel('Sepal width')
plt.tight_layout()

plt.savefig('../figures/tree_2d.pdf')

plt.figure()
plt.subplot(211)

x = X[:, 0]

plt.hist(x[y == 0],
         bins='auto',
         color=MAROON,
         label='\emph{Iris setosa}',
         histtype='stepfilled',
         alpha=0.8)
示例#59
0
                    interpolation='none',
                    alpha=1)
    img = pl.imshow(Hess[:, :, i],
                    cmap=cmapAlpha,
                    extent=[0, nx * dx, ny * dy, 0],
                    interpolation='none',
                    vmin=-vLim,
                    vmax=vLim)
    ax = pl.gca()

    #img.set_cmap('RdBu')
    ax.xaxis.tick_top()
    ax.xaxis.set_label_position('top')

    pl.xlabel("$x$ (m)")
    pl.ylabel("$y$ (m)")

    # Colorbar
    cb = pl.colorbar(
        img,
        ax=ax,
        orientation='horizontal',
        #           ticks=([-1, -0.5, 0, 0.5, 1]),
        #ticks=(),
        shrink=1,
        pad=0.01,
        aspect=20.0)
    cb.set_label(prefix + title[i])

    # Markers
    #pl.scatter(5000, 80, marker='*', color='xkcd:red', s=30, zorder=1)
示例#60
0
t2=time.time()

Qbefore = [0,0,0]
def newway(i,dt,k,N,A):
    global Qbefore

    Q = (Qbefore[i]+A/dt*N*(numpy.exp(dt/k)-1))*numpy.exp(-dt/k)
    Qbefore[i] = Q
    return Q , Qbefore[i]
    
flowvector = []
for i in range(len(rainvec)):
    flowvector.append(newway(0,dt,K,rainvec[i],area)[0])
t3=time.time()


'''plot'''
pl.figure(figsize=(14, 5), dpi=80)
#pl.xlim(0,10)
#pl.ylim(0,1.1)
pl.plot(flowlist)
pl.plot(flowvector)
pl.legend(loc='best')
pl.title('Model In - and Output', fontsize=20)
pl.xlabel('Time [dt]')
pl.ylabel('Volume [m^3]')
pl.grid(True)
pl.show()

print 'Simulationtime1: '+str(t2-t1)
print 'Simulationtime2: '+str(t3-t2)