Exemple #1
0
def _run_hist2d(nm, N=50000, seed=1234, **kwargs):
    print(" .. {0}".format(nm))

    if not os.path.exists(FIGURE_PATH):
        os.makedirs(FIGURE_PATH)

    # Generate some fake data.
    np.random.seed(seed)
    x = np.random.randn(N)
    y = np.random.randn(N)

    fig, ax = pl.subplots(1, 1, figsize=(8, 8))
    triangle.hist2d(x, y, ax=ax, **kwargs)
    fig.savefig(os.path.join(FIGURE_PATH, "hist2d_{0}.png".format(nm)))
    pl.close(fig)
Exemple #2
0
def _run_hist2d(nm, N=50000, seed=1234, **kwargs):
    print(" .. {0}".format(nm))

    if not os.path.exists(FIGURE_PATH):
        os.makedirs(FIGURE_PATH)

    # Generate some fake data.
    np.random.seed(seed)
    x = np.random.randn(N)
    y = np.random.randn(N)

    fig, ax = pl.subplots(1, 1, figsize=(8, 8))
    triangle.hist2d(x, y, ax=ax, **kwargs)
    fig.savefig(os.path.join(FIGURE_PATH, "hist2d_{0}.png".format(nm)))
    pl.close(fig)
Exemple #3
0
def plot_hist(samples,col_string,flag):
	
	M = samples[:,4]
	if flag==0:
		R = samples[:,5]
	else:
		R=[]
		g=samples[:,5]
		for i,grav in enumerate(g):
			R.append(ns.R(M[i],grav))
		R=numpy.array(R)
	
	#Q = samples[:,1]
	#mdot = samples[:,3]
	#Tc = samples[:,0]

	Q = samples[:,0]
	Tc = samples[:,3]
	
	#n, bins, patches = plt.hist(g, 25, normed=1,alpha=0.1,color=col_string)
	
	if 0:
		ind = (mdot>0.05).nonzero()
		T_c = Tc[ind]
		g = g[ind]
		Q = Q[ind]
		mdot = mdot[ind]
	
	if 0:
		triangle.hist2d(Tc,g,plot_datapoints=False,bins=25,extent=[(1,3),(0.5,3)])
		#triangle.hist2d(Tc,g,plot_datapoints=False,bins=25,extent=[(2,12),(0.5,3)])
		plt.xlabel(r'$T_c (10^7 K)$')
		plt.ylabel(r'$g_{14}$')

	if 0:
		triangle.hist2d(g,Q,plot_datapoints=False,bins=25,extent=[(0.5,3),(-3,2)])
		plt.ylabel(r'$Q_{imp}$')
		plt.xlabel(r'$g_{14}$')

	if 1:
		triangle.hist2d(R,M,plot_datapoints=False,bins=25,extent=[(8,16),(1.1,2.5)])
		plt.ylabel(r'$M$')
		plt.xlabel(r'$R$')

		Ranal = numpy.arange(100)*0.01*12.0 + 4.0
		Manal = []
		for R in Ranal:
			M=0.0
			while (ns.grav(M,R)<2.0):
				M+=0.01
			Manal.append(M)
		plt.plot(Ranal,Manal)
		Manal = []
		for R in Ranal:
			M=0.0
			while (ns.grav(M,R)<1.5):
				M+=0.01
			Manal.append(M)
		plt.plot(Ranal,Manal)
		Manal = []
		for R in Ranal:
			M=0.0
			while (ns.grav(M,R)<1.0):
				M+=0.01
			Manal.append(M)
		plt.plot(Ranal,Manal)
		
		plt.plot(Ranal,Ranal/4.36,'.')
		

	if 0:
		triangle.hist2d(g,mdot,plot_datapoints=False,bins=25,extent=[(0.5,3),(0.0,0.5)])
		plt.ylabel(r'$Accretion rate$')
		plt.xlabel(r'$g_{14}$')
Exemple #4
0
def corner_plot(s, labels, extents, bf, id):
    """ Plotting function to visualise the gaussian peaks found by the sampler function. 2D contour plots of tq against tau are plotted along with kernelly smooth histograms for each parameter.
        
        :s:
         Array of shape (#, 2) for either the smooth or disc produced by the emcee EnsembleSampler in the sample function of length determined by the number of walkers which resulted at the specified peak.
        
        :labels:
        List of x and y axes labels i.e. disc or smooth parameters
        
        :extents:
        Range over which to plot the samples, list shape [[xmin, xmax], [ymin, ymax]]
        
        :bf:
        Best fit values for the distribution peaks in both tq and tau found from mapping the samples. List shape [(tq, poserrtq, negerrtq), (tau, poserrtau, negerrtau)]
        
        :id:
        ID number to specify which galaxy this plot is for. 
        
        RETURNS:
        :fig:
        The figure object
        """
    x, y = s[:,0], s[:,1]
    fig = P.figure(figsize=(6.25,6.25))
    ax2 = P.subplot2grid((3,3), (1,0), colspan=2, rowspan=2)
    ax2.set_xlabel(labels[0])
    ax2.set_ylabel(labels[1])
    triangle.hist2d(x, y, ax=ax2, bins=100, extent=extents, plot_contours=True)
    ax2.axvline(x=bf[0][0], linewidth=1)
    ax2.axhline(y=bf[1][0], linewidth=1)
    [l.set_rotation(45) for l in ax2.get_xticklabels()]
    [j.set_rotation(45) for j in ax2.get_yticklabels()]
    ax2.tick_params(axis='x', labeltop='off')
    ax1 = P.subplot2grid((3,3), (0,0),colspan=2)
    den = kde.gaussian_kde(x[N.logical_and(x>=extents[0][0], x<=extents[0][1])])
    pos = N.linspace(extents[0][0], extents[0][1], 750)
    ax1.plot(pos, den(pos), 'k-', linewidth=1)
    ax1.axvline(x=bf[0][0], linewidth=1)
    ax1.axvline(x=bf[0][0]+bf[0][1], c='b', linestyle='--')
    ax1.axvline(x=bf[0][0]-bf[0][2], c='b', linestyle='--')
    ax1.set_xlim(extents[0][0], extents[0][1])
    ax12 = ax1.twiny()
    ax12.set_xlim(extents[0][0], extents[0][1])
    ax12.set_xticks(N.array([1.87, 3.40, 6.03, 8.77, 10.9, 12.5]))
    ax12.set_xticklabels(N.array([3.5, 2.0 , 1.0, 0.5, 0.25, 0.1]))
    [l.set_rotation(45) for l in ax12.get_xticklabels()]
    ax12.tick_params(axis='x', labelbottom='off')
    ax12.set_xlabel(r'$z$')
    ax1.tick_params(axis='x', labelbottom='off', labeltop='off')
    ax1.tick_params(axis='y', labelleft='off')
    ax3 = P.subplot2grid((3,3), (1,2), rowspan=2)
    ax3.tick_params(axis='x', labelbottom='off')
    ax3.tick_params(axis='y', labelleft='off')
    den = kde.gaussian_kde(y[N.logical_and(y>=extents[1][0], y<=extents[1][1])])
    pos = N.linspace(extents[1][0], extents[1][1], 750)
    ax3.plot(den(pos), pos, 'k-', linewidth=1)
    ax3.axhline(y=bf[1][0], linewidth=1)
    ax3.axhline(y=bf[1][0]+bf[1][1], c='b', linestyle='--')
    ax3.axhline(y=bf[1][0]-bf[1][2], c='b', linestyle='--')
    ax3.set_ylim(extents[1][0], extents[1][1])
    if os.path.exists(str(int(id))+'.jpeg') == True:
        ax4 = P.subplot2grid((3,3), (0,2), rowspan=1, colspan=1)
        img = mpimg.imread(str(int(id))+'.jpeg')
        ax4.imshow(img)
        ax4.tick_params(axis='x', labelbottom='off', labeltop='off')
        ax4.tick_params(axis='y', labelleft='off', labelright='off')
    P.tight_layout()
    P.subplots_adjust(wspace=0.0)
    P.subplots_adjust(hspace=0.0)
    return fig
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('--d4000', action='store_true', help='DEEP2: EW([OII]) vs D(4000)')
    parser.add_argument('--linesigma', action='store_true',
                        help='DEEP2: emission-line velocity width distribution')
    parser.add_argument('--oiiihb', action='store_true',
                        help='[OIII]/H-beta vs various line-ratios')

    if len(sys.argv)==1:
        parser.print_help()
        sys.exit(1)
    args = parser.parse_args()

    qadir = os.path.join(os.getenv('DESISIM'),'doc','tex',
                         'simulate-templates','figures')
    cflux, cwave, cmeta = read_base_templates(objtype='elg',observed=True)

    # Set sns preferences.  Pallet choices: deep, muted, bright, pastel, dark, colorblind
    sns.set(style='white', font_scale=1.5, palette='dark')
    
    # Figure: DEEP2 [OII] emission-line velocity width distribution 
    if args.oiiihb:
        from astropy.io import fits

        atlas = fits.getdata(os.path.join(os.getenv('IM_PROJECTS_DIR'),'desi','data',
                                          'atlas-emlines.fits.gz'),1)
        sdss = fits.getdata(os.path.join(os.getenv('IM_PROJECTS_DIR'),'desi','data',
                                          'sdss-emlines.fits.gz'),1)
        hii = fits.getdata(os.path.join(os.getenv('IM_PROJECTS_DIR'),'desi','data',
                                        'hii-emlines.fits.gz'),1)

        oiiihb = np.array(zip(sdss['OIIIHB'],atlas['OIIIHB'])).flatten()
        oiihb  = np.array(zip(sdss['OIIHB'], atlas['OIIHB'])).flatten()
        niihb  = np.array(zip(sdss['NIIHB'], atlas['NIIHB'])).flatten()
        siihb  = np.array(zip(sdss['SIIHB'], atlas['SIIHB'])).flatten()
        #oiiihb = np.array(zip(sdss['OIIIHB'][0,:],hii['OIIIHB'][0,:])).flatten()
        #oiihb  = np.array(zip(sdss['OIIHB'][0,:], hii['OIIHB'][0,:])).flatten()
        #niihb  = np.array(zip(sdss['NIIHB'][0,:], hii['NIIHB'][0,:])).flatten()
        #siihb  = np.array(zip(sdss['SIIHB'][0,:], hii['SIIHB'][0,:])).flatten()

        oiihbcoeff = sci.polyfit(oiiihb,oiihb,3)
        niihbcoeff = sci.polyfit(oiiihb,niihb,2)
        siihbcoeff = sci.polyfit(oiiihb,siihb,2)
        #siihbcoeff = sci.polyfit(oiiihb,siihb,2)
        print('[OIII]/Hb vs [OII]/Hb coefficients: ', oiihbcoeff)
        print('[OIII]/Hb vs [NII]/Hb coefficients: ', niihbcoeff)
        print('[OIII]/Hb vs [SII]/Hb coefficients: ', siihbcoeff)

        xlim = [-1.3,1.2]
        oiiihbaxis = np.linspace(-1.1,1.0,100)

        # [OIII]/Hb vs [OII]/Hb
        #fig = plt.subplots(figsize=(8,6))
        fig, ax = plt.subplots(3, sharex=True, figsize=(6,8))
        plt.tick_params(axis='both', which='major', labelsize=12)
        #fig = plt.figure(figsize=(8,6))

        ylim = [-1.5,1.0]
        #triangle.hist2d(sdss['OIIIHB'], sdss['OIIHB'], plot_density=False, ax=ax[0],
        #                contour_kwargs={'lw': 10})
        sns.kdeplot(sdss['OIIIHB'], sdss['OIIHB'], ax=ax[0], cut=[xlim,ylim],
                    gridsize=40)
        #ax[0].plot(hii['OIIIHB'][0], hii['OIIHB'][0], 's', markersize=2)
        #ax[0].plot(atlas['OIIIHB'], atlas['OIIHB'], 'o', markersize=2)

        #ax[0].plot(oiiihbaxis, sci.polyval(oiihbcoeff,oiiihbaxis), lw=3)
        ax[0].set_xlim(xlim)
        ax[0].set_ylim(ylim)
        #ax[0].xlabel(r'log$_{10}$ ([O III] $\lambda$5007 / H$\beta$)',fontsize=14)
        ax[0].set_ylabel(r'log$_{10}$ ([O II] $\lambda$3727 / H$\beta$)')
        #ax[0].tick_params(axis='both', which='major', labelsize=14)
        #fig.subplots_adjust(bottom=0.1)

        # [OIII]/Hb vs [NII]/Hb
        ylim = [-2.0,1.0]
        #sns.kdeplot(sdss['OIIIHB'][0], sdss['NIIHB'][0],range=[xlim,ylim], ax=ax[1])
        #ax[1].plot(hii['OIIIHB'][0], hii['NIIHB'][0], 's', markersize=3)
        #ax[1].plot(atlas['OIIIHB'], atlas['NIIHB'], 'o', markersize=2)
        #ax[1].plot(oiiihbaxis, sci.polyval(niihbcoeff,oiiihbaxis), lw=3)

        ax[1].set_xlim(xlim)
        ax[1].set_ylim(ylim)
        ax[1].set_ylabel(r'log$_{10}$ ([N II] $\lambda$6584 / H$\beta$)')

        # [OIII]/Hb vs [SII]/Hb
        ylim = [-1.0,0.5]
        #sns.kdeplot(sdss['OIIIHB'][0], sdss['SIIHB'][0],range=[xlim,ylim], ax=ax[2])
        #ax[2].plot(hii['OIIIHB'][0], hii['SIIHB'][0], 's', markersize=3)

        #ax[2].plot(atlas['OIIIHB'], atlas['SIIHB'], 'o', markersize=2)
        #ax[2].plot(oiiihbaxis, sci.polyval(siihbcoeff,oiiihbaxis), lw=3)

        ax[2].set_xlim(xlim)
        ax[2].set_ylim(ylim)
        ax[2].set_xlabel(r'log$_{10}$ ([O III] $\lambda$5007 / H$\beta$)')
        ax[2].set_ylabel(r'log$_{10}$ ([S II] $\lambda$6716,31 / H$\beta$)')

        fig.subplots_adjust(left=0.2)
        fig.savefig(qadir+'/oiiihb.pdf')
        
    # Figure: DEEP2 [OII] emission-line velocity width distribution 
    if args.linesigma:
        from astropy.modeling import models, fitting
        sigma = cmeta['SIGMA_KMS']
        sigminmax = np.log10([8.0,500.0])
        binsz = 0.05
        nbin = long((sigminmax[1]-sigminmax[0])/binsz)
        ngal, bins = np.histogram(np.log10(sigma), bins=nbin, range=sigminmax)
        cbins = (bins[:-1] + bins[1:]) / 2.0
        #ngal, bins, patches = plt.hist(sigma, bins=30)

        ginit = models.Gaussian1D(ngal.max(), mean=70.0, stddev=20.0)
        gfit = fitting.LevMarLSQFitter()
        gauss = gfit(ginit,cbins,ngal)
        
        xgauss = np.linspace(sigminmax[0],sigminmax[1],nbin*10)
        fig = plt.figure(figsize=(8,6))
        plt.bar(10**cbins, ngal, align='center', width=binsz*np.log(10)*10**cbins)
        plt.plot(10**xgauss, gauss(xgauss), '-', lw=3, color='black')
        plt.xlim(10**sigminmax)
        plt.xlabel('log$_{10}$ Emission-line Velocity Width $\sigma$ (km/s)',fontsize=18)
        plt.ylabel('Number of Galaxies',fontsize=18)
        plt.tick_params(axis='both', which='major', labelsize=14)

        plt.text(0.95,0.9,'$<log_{10}$'+' $\sigma>$ = '+
                 '{:.3f}$\pm${:.3f} km/s'.format(gauss.mean.value,gauss.stddev.value),
                 horizontalalignment='right',color='black',
                 transform=plt.gca().transAxes, fontsize=18)

        fig.subplots_adjust(bottom=0.1)
        fig.savefig(qadir+'/linesigma.pdf')
        
    # Figure: DEEP2 EW([OII]) vs D(4000)
    if args.d4000:
        d4000 = cmeta['D4000']
        ewoii = np.log10(cmeta['OII_3727_EW'])
        bins, stats = medxbin(d4000,ewoii,0.05,minpts=20,xmin=1.0,xmax=1.7)
        
        coeff = sci.polyfit(bins,stats['median'],2)
        #print(coeff,len(bins))
        #print(stats['median'], stats['sigma'], np.mean(stats['sigma']))
        
        strcoeff = []
        for cc in coeff: strcoeff.append('{:.4f}'.format(cc))
        
        plt.ioff()
        fig = plt.figure(figsize=(8,6))
        hist2d = triangle.hist2d(d4000, ewoii, plot_density=False)
        plt.xlim([0.9,1.8])
        plt.xlabel('D$_{n}$(4000)', fontsize=18)
        plt.ylabel('log$_{10}$ EW([O II] $\lambda\lambda3726,29$) ($\AA$, rest-frame)',
                   fontsize=18)
        plt.text(0.95,0.9,'{'+','.join(strcoeff)+'}',horizontalalignment='right',color='black',
                 transform=plt.gca().transAxes, fontsize=18)
        plt.errorbar(bins,stats['median'],yerr=stats['sigma'],color='dodgerblue',fmt='o',markersize=8)
        plt.plot(bins,sci.polyval(coeff,bins),color='red')
        #hist2d = triangle.hist2d(np.array([d4000,ewoii]).transpose())
        #plt.plot(d4000,ewoii,'bo')
        fig.savefig(qadir+'/d4000_ewoii.pdf')
def main():

    parser = argparse.ArgumentParser()
    parser.add_argument('--d4000',
                        action='store_true',
                        help='DEEP2: EW([OII]) vs D(4000)')
    parser.add_argument(
        '--linesigma',
        action='store_true',
        help='DEEP2: emission-line velocity width distribution')
    parser.add_argument('--oiiihb',
                        action='store_true',
                        help='[OIII]/H-beta vs various line-ratios')

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)
    args = parser.parse_args()

    qadir = os.path.join(os.getenv('DESISIM'), 'doc', 'tex',
                         'simulate-templates', 'figures')
    cflux, cwave, cmeta = read_base_templates(objtype='elg', observed=True)

    # Set sns preferences.  Pallet choices: deep, muted, bright, pastel, dark, colorblind
    sns.set(style='white', font_scale=1.5, palette='dark')

    # Figure: DEEP2 [OII] emission-line velocity width distribution
    if args.oiiihb:
        from astropy.io import fits

        atlas = fits.getdata(
            os.path.join(os.getenv('IM_PROJECTS_DIR'), 'desi', 'data',
                         'atlas-emlines.fits.gz'), 1)
        sdss = fits.getdata(
            os.path.join(os.getenv('IM_PROJECTS_DIR'), 'desi', 'data',
                         'sdss-emlines.fits.gz'), 1)
        hii = fits.getdata(
            os.path.join(os.getenv('IM_PROJECTS_DIR'), 'desi', 'data',
                         'hii-emlines.fits.gz'), 1)

        oiiihb = np.array(list(zip(sdss['OIIIHB'], atlas['OIIIHB']))).flatten()
        oiihb = np.array(list(zip(sdss['OIIHB'], atlas['OIIHB']))).flatten()
        niihb = np.array(list(zip(sdss['NIIHB'], atlas['NIIHB']))).flatten()
        siihb = np.array(list(zip(sdss['SIIHB'], atlas['SIIHB']))).flatten()
        #oiiihb = np.array(zip(sdss['OIIIHB'][0,:],hii['OIIIHB'][0,:])).flatten()
        #oiihb  = np.array(zip(sdss['OIIHB'][0,:], hii['OIIHB'][0,:])).flatten()
        #niihb  = np.array(zip(sdss['NIIHB'][0,:], hii['NIIHB'][0,:])).flatten()
        #siihb  = np.array(zip(sdss['SIIHB'][0,:], hii['SIIHB'][0,:])).flatten()

        oiihbcoeff = sci.polyfit(oiiihb, oiihb, 3)
        niihbcoeff = sci.polyfit(oiiihb, niihb, 2)
        siihbcoeff = sci.polyfit(oiiihb, siihb, 2)
        #siihbcoeff = sci.polyfit(oiiihb,siihb,2)
        print('[OIII]/Hb vs [OII]/Hb coefficients: ', oiihbcoeff)
        print('[OIII]/Hb vs [NII]/Hb coefficients: ', niihbcoeff)
        print('[OIII]/Hb vs [SII]/Hb coefficients: ', siihbcoeff)

        xlim = [-1.3, 1.2]
        oiiihbaxis = np.linspace(-1.1, 1.0, 100)

        # [OIII]/Hb vs [OII]/Hb
        #fig = plt.subplots(figsize=(8,6))
        fig, ax = plt.subplots(3, sharex=True, figsize=(6, 8))
        plt.tick_params(axis='both', which='major', labelsize=12)
        #fig = plt.figure(figsize=(8,6))

        ylim = [-1.5, 1.0]
        #triangle.hist2d(sdss['OIIIHB'], sdss['OIIHB'], plot_density=False, ax=ax[0],
        #                contour_kwargs={'lw': 10})
        sns.kdeplot(sdss['OIIIHB'],
                    sdss['OIIHB'],
                    ax=ax[0],
                    cut=[xlim, ylim],
                    gridsize=40)
        #ax[0].plot(hii['OIIIHB'][0], hii['OIIHB'][0], 's', markersize=2)
        #ax[0].plot(atlas['OIIIHB'], atlas['OIIHB'], 'o', markersize=2)

        #ax[0].plot(oiiihbaxis, sci.polyval(oiihbcoeff,oiiihbaxis), lw=3)
        ax[0].set_xlim(xlim)
        ax[0].set_ylim(ylim)
        #ax[0].xlabel(r'log$_{10}$ ([O III] $\lambda$5007 / H$\beta$)',fontsize=14)
        ax[0].set_ylabel(r'log$_{10}$ ([O II] $\lambda$3727 / H$\beta$)')
        #ax[0].tick_params(axis='both', which='major', labelsize=14)
        #fig.subplots_adjust(bottom=0.1)

        # [OIII]/Hb vs [NII]/Hb
        ylim = [-2.0, 1.0]
        #sns.kdeplot(sdss['OIIIHB'][0], sdss['NIIHB'][0],range=[xlim,ylim], ax=ax[1])
        #ax[1].plot(hii['OIIIHB'][0], hii['NIIHB'][0], 's', markersize=3)
        #ax[1].plot(atlas['OIIIHB'], atlas['NIIHB'], 'o', markersize=2)
        #ax[1].plot(oiiihbaxis, sci.polyval(niihbcoeff,oiiihbaxis), lw=3)

        ax[1].set_xlim(xlim)
        ax[1].set_ylim(ylim)
        ax[1].set_ylabel(r'log$_{10}$ ([N II] $\lambda$6584 / H$\beta$)')

        # [OIII]/Hb vs [SII]/Hb
        ylim = [-1.0, 0.5]
        #sns.kdeplot(sdss['OIIIHB'][0], sdss['SIIHB'][0],range=[xlim,ylim], ax=ax[2])
        #ax[2].plot(hii['OIIIHB'][0], hii['SIIHB'][0], 's', markersize=3)

        #ax[2].plot(atlas['OIIIHB'], atlas['SIIHB'], 'o', markersize=2)
        #ax[2].plot(oiiihbaxis, sci.polyval(siihbcoeff,oiiihbaxis), lw=3)

        ax[2].set_xlim(xlim)
        ax[2].set_ylim(ylim)
        ax[2].set_xlabel(r'log$_{10}$ ([O III] $\lambda$5007 / H$\beta$)')
        ax[2].set_ylabel(r'log$_{10}$ ([S II] $\lambda$6716,31 / H$\beta$)')

        fig.subplots_adjust(left=0.2)
        fig.savefig(qadir + '/oiiihb.pdf')

    # Figure: DEEP2 [OII] emission-line velocity width distribution
    if args.linesigma:
        from astropy.modeling import models, fitting
        sigma = cmeta['SIGMA_KMS']
        sigminmax = np.log10([8.0, 500.0])
        binsz = 0.05
        nbin = int((sigminmax[1] - sigminmax[0]) / binsz)
        ngal, bins = np.histogram(np.log10(sigma), bins=nbin, range=sigminmax)
        cbins = (bins[:-1] + bins[1:]) / 2.0
        #ngal, bins, patches = plt.hist(sigma, bins=30)

        ginit = models.Gaussian1D(ngal.max(), mean=70.0, stddev=20.0)
        gfit = fitting.LevMarLSQFitter()
        gauss = gfit(ginit, cbins, ngal)

        xgauss = np.linspace(sigminmax[0], sigminmax[1], nbin * 10)
        fig = plt.figure(figsize=(8, 6))
        plt.bar(10**cbins,
                ngal,
                align='center',
                width=binsz * np.log(10) * 10**cbins)
        plt.plot(10**xgauss, gauss(xgauss), '-', lw=3, color='black')
        plt.xlim(10**sigminmax)
        plt.xlabel('log$_{10}$ Emission-line Velocity Width $\sigma$ (km/s)',
                   fontsize=18)
        plt.ylabel('Number of Galaxies', fontsize=18)
        plt.tick_params(axis='both', which='major', labelsize=14)

        plt.text(0.95,
                 0.9,
                 '$<log_{10}$' +
                 ' $\sigma>$ = ' + '{:.3f}$\pm${:.3f} km/s'.format(
                     gauss.mean.value, gauss.stddev.value),
                 horizontalalignment='right',
                 color='black',
                 transform=plt.gca().transAxes,
                 fontsize=18)

        fig.subplots_adjust(bottom=0.1)
        fig.savefig(qadir + '/linesigma.pdf')

    # Figure: DEEP2 EW([OII]) vs D(4000)
    if args.d4000:
        d4000 = cmeta['D4000']
        ewoii = np.log10(cmeta['OII_3727_EW'])
        bins, stats = medxbin(d4000,
                              ewoii,
                              0.05,
                              minpts=20,
                              xmin=1.0,
                              xmax=1.7)

        coeff = sci.polyfit(bins, stats['median'], 2)
        #print(coeff,len(bins))
        #print(stats['median'], stats['sigma'], np.mean(stats['sigma']))

        strcoeff = []
        for cc in coeff:
            strcoeff.append('{:.4f}'.format(cc))

        plt.ioff()
        fig = plt.figure(figsize=(8, 6))
        hist2d = triangle.hist2d(d4000, ewoii, plot_density=False)
        plt.xlim([0.9, 1.8])
        plt.xlabel('D$_{n}$(4000)', fontsize=18)
        plt.ylabel(
            'log$_{10}$ EW([O II] $\lambda\lambda3726,29$) ($\AA$, rest-frame)',
            fontsize=18)
        plt.text(0.95,
                 0.9,
                 '{' + ','.join(strcoeff) + '}',
                 horizontalalignment='right',
                 color='black',
                 transform=plt.gca().transAxes,
                 fontsize=18)
        plt.errorbar(bins,
                     stats['median'],
                     yerr=stats['sigma'],
                     color='dodgerblue',
                     fmt='o',
                     markersize=8)
        plt.plot(bins, sci.polyval(coeff, bins), color='red')
        #hist2d = triangle.hist2d(np.array([d4000,ewoii]).transpose())
        #plt.plot(d4000,ewoii,'bo')
        fig.savefig(qadir + '/d4000_ewoii.pdf')
Exemple #7
0
for n in range(len(ts)):
    urs_past[n,:] = N.interp(past, times[2:], urs[n,:])

nuvs_past = N.zeros((len(ts), len(past)))
for n in range(len(ts)):
    nuvs_past[n,:] = N.interp(past, times[2:], nuvs[n,:])

rmags_past = N.zeros((len(ts), len(past)))
for n in range(len(ts)):
    rmags_past[n,:] = N.interp(past, times[2:], rmags[n,:])


fig = P.figure(figsize=(24,5))
for n in range(len(past)):
    ax = P.subplot(1, len(past), n)
    triangle.hist2d(rmags_past[:,n], urs_past[:,n], ax=ax)
    ax.set_xlabel(r'predicted $M_r$')
    #ax.set_ylabel(r'predicted $u-r$ colour')
    ax.set_xlim((-18, -25))
    ax.set_ylim((-3, 4))
ax = P.subplot(1, 5, 1)
ax.set_ylabel(r'predicted $u-r$ colour')
P.tight_layout()
fig.savefig('cmd_evo.pdf')

fig = P.figure(figsize=(24,5))
for n in range(len(past)):
    ax = P.subplot(1, len(past), n)
    triangle.hist2d(urs_past[:,n], nuvs_past[:,n], ax=ax)
    #ax.set_ylabel(r'predicted $NUV-u$ colour')
    ax.set_xlabel(r'predicted $u-r$ colour')
#P.figure()
#for m in range(len(tau)):
#    P.plot(N.log10(full_mass[m,:]), N.log10(full_sfr[m,:]))
#P.plot(x,y, color='r')
#P.plot(x, uy, color='r', linestyle='dashed')
#P.plot(x, ly, color='r', linestyle='dashed')
#P.xlim((8, 12.25))
#P.ylim((-2.5, 2.0))
#P.show()

log_sfr = N.log10(sfr)

fig = P.figure(figsize=(13,9))

ax1 = P.subplot(2,3,1, aspect='auto')
triangle.hist2d(avg_mass, avg_sfr, ax=ax1, bins=50, extent=([8.0, 12.0],[-2.5,2.0]))
ax1.plot(m,sfr_138, color='b')
ax1.plot(m, sfr_138+0.3, color='b', linestyle='dashed')
ax1.plot(m, sfr_138-0.3, color='b', linestyle='dashed')
ax1.tick_params(labelbottom='off')
ax1.set_yticks([-2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0])
ax1.set_yticklabels([-2.5, -2.0, -1.5, -1.0, -0.5, 0.0, 0.5, 1.0, 1.5, 2.0])
[l.set_rotation(45) for l in ax1.get_xticklabels()]
[l.set_rotation(45) for l in ax1.get_yticklabels()]
ax1.set_ylabel(r'$\log SFR [M_{\odot} yr^{-1}]$')
ax1.set_ylim(-2.5, 2.0)
ax1.text(8.3, 1.5, 'GZ2 galaxies')

ax2 = P.subplot(2,3,2, aspect='auto')
triangle.hist2d(N.log10(mass[:,0]), log_sfr[:,0], ax=ax2, bins=50, extent=([8.0, 12.0],[-2.5, N.max(log_sfr[:,0])]))
ax2.plot(m,sfr_138, color='b')
Exemple #9
0
bc_early = bc[bc[:,2] >=0.8]
print 'bc_e', len(bc_early)

rs_disc = rs[rs[:,3] > 0.5]
print 'rs_d', len(rs_disc)
rs_smooth = rs[rs[:,2] > 0.5]
print 'rs_s', len(rs_smooth)
rs_late = rs[rs[:,3] >= 0.8]
print 'rs_l', len(rs_late)
rs_early = rs[rs[:,2] >=0.8]
print 'rs_e', len(rs_early)

#Smooth- and disc-like against clean samples
P.figure(figsize=(13,9))
ax1=P.subplot(2, 3, 1)
triangle.hist2d(colours[:,0], colours[:,1], ax=ax1, extent=[(0.75,3.25), (-1, 5)], bins=50, plot_datapoints=False)
[l.set_rotation(45) for l in ax1.get_xticklabels()]
ax1.set_xticks([1.0, 1.5, 2.0, 2.5, 3.0])
ax1.set_xticklabels([1.0, 1.5, 2.0, 2.5, 3.0])
ax1.set_yticks([-1, 0, 1, 2, 3, 4, 5])
ax1.set_yticklabels([-1, 0, 1, 2, 3, 4, 5])
ax1.set_ylabel(r'$NUV - u$')
ax1.text(0.85, 4.5, 'All Galaxies', color='Black')
[l.set_rotation(45) for l in ax1.get_yticklabels()]

ax2 = P.subplot(2,3,2, sharey=ax1, sharex=ax1)
triangle.hist2d(s_like[:,0], s_like[:,1], ax=ax2, extent=[(0.75,3.25), (-1, 5)], bins=50, plot_datapoints=False)
ax2.tick_params(axis='y', labelleft='off')
ax2.tick_params(axis='x', labelbottom='off')
ax2.text(0.85, 4.25, r'Smooth-like ($p_s > 0.5$)', color='k')
def load_sdss_dr12(path):
    data_file = fits.open(path)
    # print(data_file[1].data.field)
    sdss_nam = data_file[1].data.field('SDSS_NAME')
    # f = 82900
    # print(sdss_nam[f:f+100])
    z_warning = data_file[1].data.field('zWarning')
    z = data_file[1].data.field('z_vi')
    # mask = np.logical_and(np.logical_and((z >= 1.0), (z <= 2.3)), (z_warning == 0))
    # mask =  np.ones(np.shape(z)).astype(bool)#(z_warning == 0)
    mask =  (z_warning == 0)
    z = z[mask]


    mi = data_file[1].data.field('MI')[mask]



    # print(len(mi))
    dgmi = data_file[1].data.field('DGMI')[mask]

    bands = ['u', 'g', 'r', 'i', 'z']
    data = {}
    length_data = []
    for i, k in enumerate(bands):
        data[k] = (data_file[1].data.field('PSFMAG')[:,i])[mask] - (data_file[1].data.field('EXTINCTION_RECAL')[:,i])[mask]
        length_data.append(len(data[k]))

    nam = np.array(['082045.38+130618.9', '115043.86-002354.1', '121940.36-010007.4', '123602.33-033129.9', '135425.24-001357.9', '143148.09+053558.0', '143748.28-014710.7'])
    # for n in nam:
    #     print(str(n))
    #     print([zip(i,k) for i,k in enumerate(sdss_nam) if str(n) == str(k)])
    # [print(k) for i,k in enumerate(sdss_nam)]



    u_obj = np.array([16.340282535250985, 16.868115642182865, 16.868490820682688, 16.829230761566329, 16.443006053710171, 16.86379118669786, 15.633876668255006 ])
    u_obj_sdss = np.array([16.28, 17.10, 17.22, 17.09, 16.98, 16.99, 15.86])
    g_obj = np.array([16.173628740863542, 16.942949312866595, 16.609497093992836, 16.763042601191465, 16.361315268986992, 16.878526911269127, 15.622724562677639])
    g_obj_sdss = np.array([16.13, 17.06, 16.92, 16.99, 16.78, 16.88, 15.76])
    r_obj = np.array([15.983908769640571, 16.910639809893361, 16.53028330223578, 16.606965809044731, 16.259465400302297, 16.763917281092667, 15.381490575686691])
    r_obj_sdss = np.array([15.91, 16.99, 16.82, 16.90, 16.67, 16.75, 15.48])
    i_obj = np.array([15.960828249585155, 16.647157166516017, 16.356895490345813, 16.375764327940693, 16.113968031003473, 16.585061165051222, 15.355882945611519])
    i_obj_sdss = np.array([15.87, 16.78, 16.63, 16.66, 16.51, 16.52, 15.41])
    z_obj = np.array([15.949328467438541, 16.501224893192735, 16.341537724690703, 16.366777188037226, 16.161932733774769, 16.349770828709673, 15.386318026049175])
    z_obj_sdss = np.array([15.83, 16.60, 16.61, 16.71, 16.51, 16.25, 15.41])
    mi_obj = np.array([-28.887216966079912, -29.492018441782825, -29.206175823944648, -29.521104883342353, -29.343074749485346, -29.759800580770957, -29.85016859018959])
    zz_obj = np.array([1.1242971107973012, 1.9798694976693576, 1.5830422701934881, 1.8463767030959246, 1.5123220764878522, 2.0997959346967061, 1.3089485173836708])


    K_corr = np.array([-0.048, -0.248, -0.268, -0.287, -0.258, -0.233, -0.143, -0.0])
    Mz0 = np.array([-28.512270824785411, -29.337462849149809, -29.032421150963174, -29.423493429879706, -29.153275130431958, -29.555455539949492, -29.524955755590376,  -29.523504957708496])
    ric = Mz0 - K_corr
    print(ric)

    print(np.mean(mi), np.std(mi))
    print(np.mean(ric), np.std(ric))


    print(np.mean(1 - u_obj / u_obj_sdss), np.std(1 - u_obj / u_obj_sdss))
    print(np.mean(1 - g_obj / g_obj_sdss), np.std(1 - g_obj / g_obj_sdss))
    print(np.mean(1 - r_obj / r_obj_sdss), np.std(1 - r_obj / r_obj_sdss))
    print(np.mean(1 - i_obj / i_obj_sdss), np.std(1 - i_obj / i_obj_sdss))
    print(np.mean(1 - z_obj / z_obj_sdss), np.std(1 - z_obj / z_obj_sdss))

    print(np.mean( u_obj -  u_obj_sdss), np.std( u_obj - u_obj_sdss))
    print(np.mean( g_obj -  g_obj_sdss), np.std( g_obj - g_obj_sdss))
    print(np.mean( r_obj -  r_obj_sdss), np.std( r_obj - r_obj_sdss))
    print(np.mean( i_obj -  i_obj_sdss), np.std( i_obj - i_obj_sdss))
    print(np.mean( z_obj -  z_obj_sdss), np.std( z_obj - z_obj_sdss))
    # pl.show()
    colors = ['z', 'g - i', 'i']
    gi = data['g'] - data['i']



    # data_color = np.array(zip(mi , gi))
    data_color = np.array(zip(z , gi, data['i']))




    # data_color = data_color[(np.logical_and(np.logical_and(data_color[:,0] > -40.0, data_color[:,1] >= -5), data_color[:,0] < -28.0))]
    data_color = data_color[(np.logical_and(data_color[:,0] > -40.0, data_color[:,1] >= -5))]
    # data = data[(np.logical_and(data_color[:,0] > -40.0, data_color[:,1] >= -5))]
    data_color = data_color[(data_color[:,1] >= -5)]
    # data = data[(np.logical_and(data_color[:,0] > -40.0, data_color[:,1] >= -5))]

    color_data = pd.DataFrame(data_color, columns=colors)


    # latexify()
    # Set up the subplot grid
    ratio = 5
    fig_width = 8

    golden_mean = (np.sqrt(5)-1.0)/2.0    # Aesthetic ratio
    fig_height = 1.0 * fig_width*golden_mean



    latexify(columns=2)
    fig = pl.figure()
    gs = pl.GridSpec(ratio + 1, ratio + 1)

    ax = fig.add_subplot(gs[1:, :-1])
    # ax_marg_x = fig.add_subplot(gs[0, :-1], sharex=ax)
    ax_marg_y = fig.add_subplot(gs[1:, -1], sharey=ax)

    x = np.array(color_data['z'])
    y = np.array(color_data['g - i'])
    imag = np.array(color_data['i'])


    import triangle

    print(np.mean(x), np.std(x))

    # print(np.shape(x))

    mask = (imag < 17.0) & ((1 < x) & (x < 2.3))
    # ax.scatter(mi_obj, g_obj - i_obj, s = 15, c=sns.xkcd_rgb["denim blue"], alpha = 0.7)
    triangle.hist2d(x, y, bins=200, ax=ax, smooth=0.3)
    ax.scatter(x[mask] , y[mask] ,  marker='o', s=10, facecolor=cmap[1], lw = 0, cmap=cmap, alpha= 1.0)
    ax.scatter(zz_obj, g_obj - i_obj, s = 25, c=cmap[2], alpha = 1.0)

    format_axes(ax)
    format_axes(ax_marg_y)
    pl.setp(ax_marg_y.get_yticklabels(), visible=False)
    pl.setp(ax_marg_y.yaxis.get_majorticklines(), visible=False)
    pl.setp(ax_marg_y.yaxis.get_minorticklines(), visible=False)
    pl.setp(ax_marg_y.xaxis.get_majorticklines(), visible=False)
    pl.setp(ax_marg_y.xaxis.get_minorticklines(), visible=False)
    pl.setp(ax_marg_y.get_xticklabels(), visible=False)
    ax_marg_y.xaxis.grid(False)
    despine(ax=ax_marg_y, bottom=True)
    sns.distplot(y, hist=False, kde=True, ax=ax_marg_y, kde_kws={"shade": True, "color": sns.xkcd_rgb["black"], "gridsize": 200, "alpha": 0.2},
                 vertical=True, axlabel=False)
    sns.distplot(g_obj - i_obj, hist=False, rug=True, kde=False, ax=ax_marg_y, rug_kws={"height": 1.5, "color": cmap[2], "alpha": 1.0},
                 vertical=True, axlabel=False)
    # sns.distplot(y[mask], hist=False, rug=True, kde=False, ax=ax_marg_y, rug_kws={"height": 0.5, "color": cmap[1], "alpha": 0.3},
    #              vertical=True, axlabel=False)
    sns.distplot(y[mask], hist=False, kde=True, ax=ax_marg_y, kde_kws={"shade": True, "color": cmap[1], "gridsize": 200, "alpha": 0.3},
                 vertical=True, axlabel=False)
    # sns.kdeplot(color_data, ax = ax, cmap='Greys', n_levels=50, norm=PowerNorm(gamma=0.3),
    #             shade=True, gridsize=100, linewidths = (0.5,), alpha=0.7)











    # ax.set_xlabel(r"M$_i$(z=2)")
    ax.set_xlabel(r"z")
    ax.set_ylabel(r"$g - i$")



    # ax.set_xlim((np.mean(x) - 5* np.std(x), np.mean(x) + 2* np.std(x)))
    ax.set_xlim((0.0, 3.5))
    ax.set_ylim((-0.5, 1.0))

    format_axes(ax)
    for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
                 ax.get_xticklabels() + ax.get_yticklabels()):
        item.set_fontsize(16)

    fig.tight_layout()
    pl.savefig('../documents/figs/color_comparison2.pdf')
    pl.show()
Exemple #11
0
		#print 'HI Col Dens', datain[0:5,1]
		#print 'EM', datain[0:5,2]
		#print 'Ha', datain[0:5,3]
		#print 'Temp', datain[0:5,0]


		#ok so this is fine but how do I make the numbers fit correctly?
		otro = 0
		j = 0
		while j < 3:
			i = j + 1
			while i < 4:
				print 'Plot axes: ',count,otro
				print 'Data axes: ',j, i
				ax = axes[count,otro]
				triangle.hist2d(datain[:,j],datain[:,i],ax=ax) 
				ax.locator_params(axis='x',nbins=4)
				ax.set_xlim(fieldlims[j])
				ax.set_ylim(fieldlims[i])
				if count == 0:
					ax.set_title(fields[i])
				if count== 3:
					ax.set_xlabel(fields[j])
				if otro == 0:
					ax.set_ylabel('Radius = '+str(rad))
				#ax.locator_params(axis='x',tight=True,nbins=5)
				otro = otro + 1
				i = i + 1
			j = j + 1
		radcount = radcount + 1
		count = count + 1
Exemple #12
0
def xx_plot(epoch, model, features, filters, figname, fgal=0.5):
    """
    Plot the single epoch and xd posts versus coadd
    """
    # fetch Stripe 82 data
    X, Xcov = fetch_prepped_s82data(epoch, fgal, features, filters)
    Xcoadd, Xcoaddcov = fetch_prepped_s82data(epoch, fgal, features,
                                              filters, use_single=False)
    N = 20000
    X = X[:N]
    Xcov = Xcov[:N]
    Xcoadd = Xcoadd[:N]
    Xcoaddcov = Xcoaddcov[:N]

    # unpickle the XD model
    if type(model) == str: 
        f = open(model, 'rb')
        model = cPickle.load(f)
        f.close()

    # Calculate the posteriors, draw samples
    a, m, v = model.posterior(X, Xcov)
    posts = np.zeros_like(X)
    for i in range(X.shape[0]):
        posts[i] = model.sample(a[i], m[i], v[i], size=1)

    lo = [0.01, 0.02, 0.06]
    hi = [0.99, 0.96, 0.98]
    idx = [0, 1, 4]
    bins = [100, 100, 300]
    label = ['psfmag $r$', 'modelmag $u-g$', 'modelmag $i-z$']
    N = len(idx)
    fs = 5
    lsize = 20
    f = pl.figure(figsize=(N * fs, 2 * fs))
    pl.subplots_adjust(wspace=0.3)
    for i in range(N):
        x = X[:, idx[i]]
        y = Xcoadd[:, idx[i]]
        p = posts[:, idx[i]]
        ind = (y > -999) & (Xcoaddcov[:, idx[i]][:, idx[i]] < 10.)
        x = x[ind]
        y = y[ind]
        p = p[ind]
        ax = pl.subplot(2, N, i + 1)
        v = np.sort(x)
        mn, mx = v[np.int(lo[i] * x.shape[0])], v[np.int(hi[i] * x.shape[0])]
        hist2d(x, y, ax=ax, bins=bins[i], plot_contours=True,
               plot_datapoints=True)
        pl.plot([mn, mx], [mn, mx], 'r', lw=2)
        pl.ylabel('Coadd ' + label[i], fontsize=lsize)
        pl.xlabel('Single Epoch ' + label[i], fontsize=lsize)
        pl.xlim(mn, mx)
        pl.ylim(mn, mx)
        ax = pl.subplot(2, N, i + 4)
        hist2d(p, y, ax=ax, bins=bins[i], plot_contours=True,
               plot_datapoints=True)
        pl.plot([mn, mx], [mn, mx], 'r', lw=2)
        pl.xlim(mn, mx)
        pl.ylim(mn, mx)
        pl.ylabel('Coadd ' + label[i], fontsize=lsize)
        pl.xlabel('XD Posterior ' + label[i], fontsize=lsize)
    f.savefig(figname, bbox_inches='tight')
Exemple #13
0
def corner_plot(s, labels, extents, bf, id):
    """ Plotting function to visualise the gaussian peaks found by the sampler function. 2D contour plots of tq against tau are plotted along with kernelly smooth histograms for each parameter.
        
        :s:
         Array of shape (#, 2) for either the smooth or disc produced by the emcee EnsembleSampler in the sample function of length determined by the number of walkers which resulted at the specified peak.
        
        :labels:
        List of x and y axes labels i.e. disc or smooth parameters
        
        :extents:
        Range over which to plot the samples, list shape [[xmin, xmax], [ymin, ymax]]
        
        :bf:
        Best fit values for the distribution peaks in both tq and tau found from mapping the samples. List shape [(tq, poserrtq, negerrtq), (tau, poserrtau, negerrtau)]
        
        :id:
        ID number to specify which galaxy this plot is for. 
        
        RETURNS:
        :fig:
        The figure object
        """
    x, y = s[:,0], s[:,1]
    fig = P.figure(figsize=(6.25,6.25))
    ax2 = P.subplot2grid((3,3), (1,0), colspan=2, rowspan=2)
    ax2.set_xlabel(labels[0])
    ax2.set_ylabel(labels[1])
    triangle.hist2d(x, y, ax=ax2, bins=100, extent=extents, plot_contours=True)
    ax2.axvline(x=bf[0][0], linewidth=1)
    ax2.axhline(y=bf[1][0], linewidth=1)
    [l.set_rotation(45) for l in ax2.get_xticklabels()]
    [j.set_rotation(45) for j in ax2.get_yticklabels()]
    ax2.tick_params(axis='x', labeltop='off')
    ax1 = P.subplot2grid((3,3), (0,0),colspan=2)
    den = kde.gaussian_kde(x[N.logical_and(x>=extents[0][0], x<=extents[0][1])])
    pos = N.linspace(extents[0][0], extents[0][1], 750)
    ax1.plot(pos, den(pos), 'k-', linewidth=1)
    ax1.axvline(x=bf[0][0], linewidth=1)
    ax1.axvline(x=bf[0][0]+bf[0][1], c='b', linestyle='--')
    ax1.axvline(x=bf[0][0]-bf[0][2], c='b', linestyle='--')
    ax1.set_xlim(extents[0][0], extents[0][1])
    ax12 = ax1.twiny()
    ax12.set_xlim(extent[0][0], extent[0][1])
    ax12.set_xticks(N.array([1.87, 3.40, 6.03, 8.77, 10.9, 12.5]))
    ax12.set_xticklabels(N.array([3.5, 2.0 , 1.0, 0.5, 0.25, 0.1]))
    [l.set_rotation(45) for l in ax12.get_xticklabels()]
    ax12.tick_params(axis='x', labelbottom='off')
    ax12.set_xlabel(r'$z$')
    ax1.tick_params(axis='x', labelbottom='off', labeltop='off')
    ax1.tick_params(axis='y', labelleft='off')
    ax3 = P.subplot2grid((3,3), (1,2), rowspan=2)
    ax3.tick_params(axis='x', labelbottom='off')
    ax3.tick_params(axis='y', labelleft='off')
    den = kde.gaussian_kde(y[N.logical_and(y>=extents[1][0], y<=extents[1][1])])
    pos = N.linspace(extents[1][0], extents[1][1], 750)
    ax3.plot(den(pos), pos, 'k-', linewidth=1)
    ax3.axhline(y=bf[1][0], linewidth=1)
    ax3.axhline(y=bf[1][0]+bf[1][1], c='b', linestyle='--')
    ax3.axhline(y=bf[1][0]-bf[1][2], c='b', linestyle='--')
    ax3.set_ylim(extents[1][0], extents[1][1])
    if os.path.exists(str(int(id))+'.jpeg') == True:
        ax4 = P.subplot2grid((3,3), (0,2), rowspan=1, colspan=1)
        img = mpimg.imread(str(int(id))+'.jpeg')
        ax4.imshow(img)
        ax4.tick_params(axis='x', labelbottom='off', labeltop='off')
        ax4.tick_params(axis='y', labelleft='off', labelright='off')
    P.tight_layout()
    P.subplots_adjust(wspace=0.0)
    P.subplots_adjust(hspace=0.0)
    save_fig = 'starfpy_result_'+str(int(id))+'_'+str(time.strftime('%H_%M_%d_%m_%y'))+'.pdf'
    fig.savefig(save_fig)
    return fig
            mrpmK = np.delete(mrpmK,bad)

#Need to make these points show up now
plt.plot(mrpmK,meqw,'o',color='#C0C0C0', ms=1.5,mec='none')
#    , zorder=100, alpha=0.1, rasterized=True)

#eqw_bins = np.delete(eqw_bins,-1)+0.25
#col_bins = colorcenter
#contour_fill = plt.contourf(col_bins,eqw_bins,zeqw[0],
#     logbins,cmap=cm.get_cmap("Greys"),norm=norm)
#contour_lines = plt.contour(col_bins,eqw_bins,zeqw[0],
#     logbins,colors='Grey',label='SDSS Field')
#print logbins

hist2d(mrpmK,meqw,col_bins,bins=100)
triangle.hist2d(mrpmK,meqw,plot_contours=False)

plt.errorbar(colorcenter,p_avg,p_std,coloredges,fmt='o',color='b',
    mec='b',label='Praesepe',
    capsize=0)
plt.errorbar(colorcenter+0.01,h_avg,h_std,coloredges,fmt='D',mfc='OrangeRed',
    color='OrangeRed',mec='OrangeRed',label='Hyades',capsize=0)
plt.xlabel('(r\'-K)',fontsize='x-large')
plt.ylabel(r'Average $H\alpha$ EqW',fontsize='x-large')
plt.ylim(7,-11)
plt.xlim(0.25,6.8)
plt.legend(loc=4,numpoints=1)

#plt.clabel(contour_lines,fmt='%i',fontsize=10,manual=True,rightside_up=True)
ax = plt.gca()
ax.tick_params(which='both',labelsize='large',top=False)
pos = [0.40328598,0.47176743,0.46131516]
fields = ["HAlpha_Emissivity", "HAlphaEmissionArc","Temperature"] 

rad = 108.0/pf['kpc']
data = pf.h.sphere(pos,rad)

datain = np.zeros((len(data['Temperature']),3))
for i in range(3):
	datain[:,i] = np.log10(data[fields[i]])

fileout='cloudy_eq_test.png'
triangle.corner(datain,labels=['Cloudy HAlpha','Equation HAlpha','Temperature']).savefig(fileout)
plt.close()

ratio = np.log10(data['HAlphaEmissionArc']/data["HAlpha_Emissivity"])
triangle.hist2d(np.log10(data['Temperature']),ratio)
plt.xlabel('Temperature')
plt.ylabel('Ratio Equation/Cloudy')
plt.savefig('ratio_equation_cloudy_temp.png')
plt.close()

idx = np.where(np.log10(data['Temperature']) > 4.5)
triangle.hist2d(np.log10(data['Temperature'][idx]),ratio[idx])
plt.xlabel('Temperature')
plt.ylabel('Ratio Equation/Cloudy')
plt.savefig('ratio_equation_cloudy_tempnocold.png')
plt.close()

x = np.linspace(-48,33,15)
triangle.hist2d(datain[:,0],datain[:,1])
plt.xlabel('Cloudy HAlpha')
Exemple #16
0
def plot_hist(samples, col_string, flag):

    M = samples[:, 4]
    if flag == 0:
        R = samples[:, 5]
    else:
        R = []
        g = samples[:, 5]
        for i, grav in enumerate(g):
            R.append(ns.R(M[i], grav))
        R = numpy.array(R)

    #Q = samples[:,1]
    #mdot = samples[:,3]
    #Tc = samples[:,0]

    Q = samples[:, 0]
    Tc = samples[:, 3]

    #n, bins, patches = plt.hist(g, 25, normed=1,alpha=0.1,color=col_string)

    if 0:
        ind = (mdot > 0.05).nonzero()
        T_c = Tc[ind]
        g = g[ind]
        Q = Q[ind]
        mdot = mdot[ind]

    if 0:
        triangle.hist2d(Tc,
                        g,
                        plot_datapoints=False,
                        bins=25,
                        extent=[(1, 3), (0.5, 3)])
        #triangle.hist2d(Tc,g,plot_datapoints=False,bins=25,extent=[(2,12),(0.5,3)])
        plt.xlabel(r'$T_c (10^7 K)$')
        plt.ylabel(r'$g_{14}$')

    if 0:
        triangle.hist2d(g,
                        Q,
                        plot_datapoints=False,
                        bins=25,
                        extent=[(0.5, 3), (-3, 2)])
        plt.ylabel(r'$Q_{imp}$')
        plt.xlabel(r'$g_{14}$')

    if 1:
        triangle.hist2d(R,
                        M,
                        plot_datapoints=False,
                        bins=25,
                        extent=[(8, 16), (1.1, 2.5)])
        plt.ylabel(r'$M$')
        plt.xlabel(r'$R$')

        Ranal = numpy.arange(100) * 0.01 * 12.0 + 4.0
        Manal = []
        for R in Ranal:
            M = 0.0
            while (ns.grav(M, R) < 2.0):
                M += 0.01
            Manal.append(M)
        plt.plot(Ranal, Manal)
        Manal = []
        for R in Ranal:
            M = 0.0
            while (ns.grav(M, R) < 1.5):
                M += 0.01
            Manal.append(M)
        plt.plot(Ranal, Manal)
        Manal = []
        for R in Ranal:
            M = 0.0
            while (ns.grav(M, R) < 1.0):
                M += 0.01
            Manal.append(M)
        plt.plot(Ranal, Manal)

        plt.plot(Ranal, Ranal / 4.36, '.')

    if 0:
        triangle.hist2d(g,
                        mdot,
                        plot_datapoints=False,
                        bins=25,
                        extent=[(0.5, 3), (0.0, 0.5)])
        plt.ylabel(r'$Accretion rate$')
        plt.xlabel(r'$g_{14}$')