def apogeerc(**kwargs): """ NAME: apogeerc PURPOSE: read the APOGEE RC data INPUT: IF the apogee package is not installed: dr= (13) SDSS data release ELSE you can use the same keywords as apogee.tools.read.rcsample: main= (default: False) if True, only select stars in the main survey dr= data reduction to load the catalog for (automatically set based on APOGEE_REDUX if not given explicitly) OUTPUT: APOGEE RC sample data HISTORY: 2013-10-08 - Written - Bovy (IAS) """ if not _APOGEE_LOADED: warnings.warn( "Falling back on simple APOGEE interface; for more functionality, install the jobovy/apogee package" ) dr = kwargs.get('dr', 13) filePath = path.apogeercPath(dr=dr) if not os.path.exists(filePath): download.apogeerc(dr=dr) return fitsio.read(filePath, 1) else: return apread.rcsample(**kwargs)
def get_rcsample(): """ NAME: get_rcsample PURPOSE: get the RC sample INPUT: None so far OUTPUT: sample HISTORY: 2015-02-10 - Started - Bovy (IAS@KITP) """ data = apread.rcsample() # Cut to statistical sample data = data[data['STAT'] == 1] # Add the M_H-based distances data = esutil.numpy_util.add_fields(data, [('RC_DIST_H', float), ('RC_DM_H', float), ('RC_GALR_H', float), ('RC_GALPHI_H', float), ('RC_GALZ_H', float)]) rcd = rcdist() jk = data['J0'] - data['K0'] z = isodist.FEH2Z(data['METALS'], zsolar=0.017) data['RC_DIST_H'] = rcd(jk, z, appmag=data['H0'], mh=True) data['RC_DM_H'] = 5. * numpy.log10(data['RC_DIST_H']) + 10. XYZ = bovy_coords.lbd_to_XYZ(data['GLON'], data['GLAT'], data['RC_DIST_H'], degree=True) R, phi, Z = bovy_coords.XYZ_to_galcencyl(XYZ[:, 0], XYZ[:, 1], XYZ[:, 2], Xsun=8., Zsun=0.025) data['RC_GALR_H'] = R data['RC_GALPHI_H'] = phi data['RC_GALZ_H'] = Z # Add the average alpha/Fe data = esutil.numpy_util.add_fields(data, [('AVG_ALPHAFE', float)]) data['AVG_ALPHAFE'] = avg_alphafe(data) # Apply -0.1 offset in [Fe/H] data[_FEHTAG] += -0.10 # Remove locations outside of the Pan-STARRS dust map # In the Southern hemisphere data = data[data['LOCATION_ID'] != 4266] #240,-18 data = data[data['LOCATION_ID'] != 4331] #5.5,-14.2 data = data[data['LOCATION_ID'] != 4381] #5.2,-12.2 data = data[data['LOCATION_ID'] != 4332] #1,-4 data = data[data['LOCATION_ID'] != 4329] #0,-5 data = data[data['LOCATION_ID'] != 4351] #0,-2 data = data[data['LOCATION_ID'] != 4353] #358,0 data = data[data['LOCATION_ID'] != 4385] #358.6,1.4 # Close to the ecliptic pole where there's no data (is it the ecliptic pole? data = data[data['LOCATION_ID'] != 4528] #120,30 data = data[data['LOCATION_ID'] != 4217] #123,22.4 # Remove stars w/ DM < 8.49, because for standard candle RC, these cannot be in the sample data = data[data['RC_DM_H'] > 8.49] return data
def plot_vr(plotfilename): #Read the APOGEE-RC data and pixelate it #APOGEE-RC data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) data= data[indx] #Get velocity field xmin, xmax= 5.5, 13.5 dx= 1. pix= pixelize_sample.pixelXY(data, xmin=xmin,xmax=xmax, ymin=-dx/2.,ymax=dx/2., dx=dx,dy=dx) # dx=_RCDX,dy=_RCDX) vr= pix.plot(lambda x: dvlosgal(x), returnz=True,justcalc=True) vrunc= pix.plot(lambda x: dvlosgal(x), func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)), returnz=True,justcalc=True) sr= pix.plot(lambda x: dvlosgal(x), func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x))), returnz=True,justcalc=True) srunc= pix.plot(lambda x: dvlosgal(x), func=disperror, returnz=True,justcalc=True) #print numpy.median(vr.flatten()[numpy.array([True,True,False,True,True,True,True,True,True],dtype='bool')]) print vr.flatten() print vrunc.flatten() print sr.flatten() print srunc.flatten() rs= numpy.arange(xmin+dx/2.,xmax-dx/2.+0.00001,dx) print rs bovy_plot.bovy_print() srAxes= pyplot.axes([0.1,0.5,0.8,0.4]) vrAxes= pyplot.axes([0.1,0.1,0.8,0.4]) pyplot.sca(srAxes) pyplot.errorbar(rs,sr.flatten(),yerr=srunc.flatten(), marker='o',ls='none',ms=6.,color='k') pyplot.xlim(0.,15.) pyplot.ylim(9.5,49.) #srAxes.set_yscale('log') bovy_plot._add_ticks(yticks=False) bovy_plot._add_axislabels(r'$ $', r'$\sigma_R\,(\mathrm{km\,s}^{-1})$') nullfmt = NullFormatter() # no labels srAxes.xaxis.set_major_formatter(nullfmt) pyplot.sca(vrAxes) pyplot.errorbar(rs,vr.flatten(),yerr=vrunc.flatten(), marker='o',ls='none',ms=6.,color='k') pyplot.plot([0.,20.],numpy.median(vr.flatten())*numpy.ones(2),'k--') bovy_plot._add_ticks() pyplot.xlim(0.,15.) pyplot.ylim(-14.,14.) bovy_plot._add_axislabels(r'$R\,(\mathrm{kpc})$', r'$\langle V_R\rangle\,(\mathrm{km\,s}^{-1})$') bovy_plot.bovy_end_print(plotfilename) return None
def get_rcsample(): """ NAME: get_rcsample PURPOSE: get the RC sample INPUT: None so far OUTPUT: sample HISTORY: 2015-02-10 - Started - Bovy (IAS@KITP) """ data= apread.rcsample() # Cut to statistical sample data= data[data['STAT'] == 1] # Add the M_H-based distances data= esutil.numpy_util.add_fields(data,[('RC_DIST_H', float), ('RC_DM_H', float), ('RC_GALR_H', float), ('RC_GALPHI_H', float), ('RC_GALZ_H', float)]) rcd= rcdist() jk= data['J0']-data['K0'] z= isodist.FEH2Z(data['METALS'],zsolar=0.017) data['RC_DIST_H']= rcd(jk,z,appmag=data['H0'],mh=True) data['RC_DM_H']= 5.*numpy.log10(data['RC_DIST_H'])+10. XYZ= bovy_coords.lbd_to_XYZ(data['GLON'], data['GLAT'], data['RC_DIST_H'], degree=True) R,phi,Z= bovy_coords.XYZ_to_galcencyl(XYZ[:,0], XYZ[:,1], XYZ[:,2], Xsun=8.,Zsun=0.025) data['RC_GALR_H']= R data['RC_GALPHI_H']= phi data['RC_GALZ_H']= Z # Add the average alpha/Fe data= esutil.numpy_util.add_fields(data,[('AVG_ALPHAFE', float)]) data['AVG_ALPHAFE']= avg_alphafe(data) # Apply -0.1 offset in [Fe/H] data[_FEHTAG]+= -0.10 # Remove locations outside of the Pan-STARRS dust map # In the Southern hemisphere data= data[data['LOCATION_ID'] != 4266] #240,-18 data= data[data['LOCATION_ID'] != 4331] #5.5,-14.2 data= data[data['LOCATION_ID'] != 4381] #5.2,-12.2 data= data[data['LOCATION_ID'] != 4332] #1,-4 data= data[data['LOCATION_ID'] != 4329] #0,-5 data= data[data['LOCATION_ID'] != 4351] #0,-2 data= data[data['LOCATION_ID'] != 4353] #358,0 data= data[data['LOCATION_ID'] != 4385] #358.6,1.4 # Close to the ecliptic pole where there's no data (is it the ecliptic pole? data= data[data['LOCATION_ID'] != 4528] #120,30 data= data[data['LOCATION_ID'] != 4217] #123,22.4 # Remove stars w/ DM < 8.49, because for standard candle RC, these cannot be in the sample data= data[data['RC_DM_H'] > 8.49] return data
def determine_kxky_error(): #Load fiducial bar model spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015%s.sav' % _HIVRESSTR)[1::2,1::2] #spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-14%s.sav' % _HIVRESSTR)[1::2,1::2]*0.85 #spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-7%s.sav' % _HIVRESSTR)[1::2,1::2]*0.25 psd2d= bovy_psd.psd2d(spvlos) kmax= 1./_RCDX #Calculate maximum psd2d[psd2d.shape[0]/2-1:psd2d.shape[0]/2+2,psd2d.shape[1]/2-1:psd2d.shape[1]/2+2]= 0. tmax= numpy.unravel_index(numpy.argmax(psd2d),psd2d.shape) tmax0= float(psd2d.shape[0]/2-tmax[0])/psd2d.shape[0]*2 tmax1= float(tmax[1]-psd2d.shape[1]/2)/psd2d.shape[1]*2 print tmax0*kmax, tmax1*kmax bovy_plot.bovy_print() bovy_plot.bovy_dens2d(psd2d.T,origin='lower',cmap='jet', interpolation='nearest', xrange=[-kmax,kmax], yrange=[-kmax,kmax], xlabel=r'$k_x\,(\mathrm{kpc}^{-1})$', ylabel=r'$k_y\,(\mathrm{kpc}^{-1})$') bovy_plot.bovy_end_print('/Users/bovy/Desktop/test.png') #Read the data for the noise data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx) data= data[indx] #Get residuals dx= _RCDX pix= pixelize_sample.pixelXY(data, xmin=_RCXMIN,xmax=_RCXMAX, ymin=_RCYMIN,ymax=_RCYMAX, dx=dx,dy=dx) resvunc= pix.plot('VHELIO_AVG', func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)), returnz=True,justcalc=True) #Now do 1000 MC simulations to determine the error on kmax nmc= 1000 kxmax= numpy.zeros(nmc) kymax= numpy.zeros(nmc) for ii in range(nmc): newresv= spvlos+numpy.random.normal(size=spvlos.shape)*resvunc/220. simpsd2d= bovy_psd.psd2d(newresv*220.) simpsd2d[simpsd2d.shape[0]/2-1:simpsd2d.shape[0]/2+2,simpsd2d.shape[1]/2-1:simpsd2d.shape[1]/2+2]= 0. tmax= numpy.unravel_index(numpy.argmax(simpsd2d),psd2d.shape) tmax0= float(psd2d.shape[0]/2-tmax[0])/psd2d.shape[0]*2 tmax1= float(tmax[1]-psd2d.shape[1]/2)/psd2d.shape[1]*2 kmax= 1./_RCDX kxmax[ii]= tmax0*kmax kymax[ii]= tmax1*kmax print numpy.mean(kxmax), numpy.std(kxmax) print numpy.mean(kymax), numpy.std(kymax) return None
def apogeerc(**kwargs): """ NAME: apogeerc PURPOSE: read the APOGEE RC data INPUT: main= (default: False) if True, only select stars in the main survey dr= data reduction to load the catalog for (automatically set based on APOGEE_REDUX if not given explicitly) OUTPUT: APOGEE RC sample data HISTORY: 2013-10-08 - Written - Bovy (IAS) """ if not _APOGEE_LOADED: raise ImportError("Loading the APOGEE RC data requires the jobovy/apogee module to be installed") return apread.rcsample(**kwargs)
def match_apokasc_rc(rcfile=None): #First read apokasc kascdata= apread.apokasc() #Then read rc if rcfile is None: rcdata= apread.rcsample() else: rcdata= fitsio.read(rcfile) print len(rcdata), numpy.sum(rcdata['ADDL_LOGG_CUT']) rcdata= rcdata[rcdata['ADDL_LOGG_CUT'] == 1] #Match h=esutil.htm.HTM() m1,m2,d12 = h.match(kascdata['RA'],kascdata['DEC'], rcdata['RA'],rcdata['DEC'], 2./3600.,maxmatch=1) kascdata= esutil.numpy_util.add_fields(kascdata,[('RC', int)]) kascdata['RC']= 0 kascdata['RC'][m1]= 1 return kascdata
def apogeerc(xmatch=None, **kwargs): """ NAME: apogeerc PURPOSE: read the APOGEE RC data INPUT: IF the apogee package is not installed: dr= (14) SDSS data release ELSE you can use the same keywords as apogee.tools.read.rcsample: main= (default: False) if True, only select stars in the main survey dr= data reduction to load the catalog for (automatically set based on APOGEE_REDUX if not given explicitly) ALWAYS ALSO xmatch= (None) if set, cross-match against a Vizier catalog (e.g., vizier:I/345/gaia2 for Gaia DR2) using gaia_tools.xmatch.cds and return the overlap +gaia_tools.xmatch.cds keywords OUTPUT: APOGEE RC sample data[,xmatched table] HISTORY: 2013-10-08 - Written - Bovy (IAS) 2018-05-09 - Add xmatch - Bovy (UofT) """ if not _APOGEE_LOADED: warnings.warn( "Falling back on simple APOGEE interface; for more functionality, install the jobovy/apogee package" ) dr = kwargs.get('dr', 14) filePath = path.apogeercPath(dr=dr) if not os.path.exists(filePath): download.apogeerc(dr=dr) data = fitsread(filePath, 1) if not xmatch is None: ma, mai = _xmatch_cds(data, xmatch, filePath, **kwargs) return (data[mai], ma) else: return data else: kwargs['xmatch'] = xmatch return apread.rcsample(**kwargs)
def match_apokasc_rc(rcfile=None,addl_logg_cut=False): #First read apokasc kascdata= apread.apokasc() #Then read rc if rcfile is None: rcdata= apread.rcsample() else: rcdata= fitsio.read(rcfile) if addl_logg_cut: rcdata= rcdata[rcdata['ADDL_LOGG_CUT'] == 1] print "RC catalog has %i entries ..." % len(rcdata) #Match h=esutil.htm.HTM() m1,m2,d12 = h.match(kascdata['RA'],kascdata['DEC'], rcdata['RA'],rcdata['DEC'], 2./3600.,maxmatch=1) kascdata= esutil.numpy_util.add_fields(kascdata,[('RC', int)]) kascdata['RC']= 0 kascdata['RC'][m1]= 1 return kascdata
def match_apokasc_rc(rcfile=None,addl_logg_cut=False): #First read apokasc kascdata= apread.apokasc() #Then read rc if rcfile is None: rcdata= apread.rcsample() else: rcdata= fitsio.read(rcfile) if addl_logg_cut: rcdata= rcdata[rcdata['ADDL_LOGG_CUT'] == 1] print("RC catalog has %i entries ..." % len(rcdata)) #Match h=esutil.htm.HTM() m1,m2,d12 = h.match(kascdata['RA'],kascdata['DEC'], rcdata['RA'],rcdata['DEC'], 2./3600.,maxmatch=1) kascdata= esutil.numpy_util.add_fields(kascdata,[('RC', int)]) kascdata['RC']= 0 kascdata['RC'][m1]= 1 return kascdata
def returncat(): RCcat = apread.rcsample() # Now need to read in ascii Ness Sample fields = ['APOGEE_ID', 'RC_DIST', 'RC_GALR', 'RC_GALPHI', 'RC_GALZ', 'TEFF', 'LOGG', 'FE_H', 'ALPHAFE', 'RC_GALR'] # Using the Rccatalog to provide data types for making record array # with ness catalog # The last 'RC_GALR' is just to steal the datatype to make the age array ness_dtypes = [RCcat[field].dtype for field in fields] ness_cat = read_ness_cat() # TEST NESS CAT if (ness_cat['ID'] == RCcat['APOGEE_ID']).all(): print("Ness Catalog and RC Catalog successfully merged.") print('RC catalog and Cannon catalog have matching APOGEE_IDs') else: print("Ness Catalog merge unsuccessful. You lose!") sys.exit() newnames = ["cannon_"+i for i in ness_cat.dtype.names] ness_cat.dtype.names = newnames # Just add in delta corrections from PPMXL pm_corr_file = os.path.join(_apogee_data_dir, 'qso_gal_pm_corrections') corr_fields = ['corr_RA', 'corr_DEC', 'dgaluRA', 'dgaluDEC', 'dqsouRA', 'dqsouDEC'] corr_dtypes = ness_dtypes[1:7] ndtypes_corr = [(i, j) for i, j in zip(corr_fields, corr_dtypes)] pmcorr_cat = np.genfromtxt(pm_corr_file, dtype=ndtypes_corr) pmcorr_cat.sort(order='corr_RA') # Need to sort all against RA, then join print ('Sum difference of RA in correction file and RC cat: {0}'.format( np.sum(pmcorr_cat['corr_RA'] - RCcat['RA']))) print ('Sum difference of DEC in correction file and RC cat: {0}'.format( np.sum(pmcorr_cat['corr_DEC'] - RCcat['DEC']))) RC_cannon_cat = rfn.merge_arrays([RCcat, ness_cat, pmcorr_cat], asrecarray=True, flatten=True) return RC_cannon_cat
def plot_rcresidualkinematics(plotfilename,sbd10=False,vc=220.): #Read the APOGEE-RC data and pixelate it #APOGEE-RC data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) data= data[indx] #Get velocity field pixrc= pixelize_sample.pixelXY(data, xmin=_RCXMIN,xmax=_RCXMAX, ymin=_RCYMIN,ymax=_RCYMAX, dx=_RCDX,dy=_RCDX) bovy_plot.bovy_print() vmin, vmax= -16., 16. if sbd10: pixrc.plot(lambda x: dvlosgal(x,vc=vc,vtsun=vc+12.), zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los,rot}}\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax) pyplot.annotate(r'$V_c = %i\,\mathrm{km\,s}^{-1}, V_{\odot-c}= 12\,\mathrm{km\,s}^{-1}$' % vc, (0.5,1.1),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=18.) else: resv= pixrc.plot(lambda x: dvlosgal(x,vc=vc,vtsun=vc+24.), zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los,rot}}\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax,returnz=True) notNan= True-numpy.isnan(resv) print numpy.sum(notNan) print numpy.median(resv[notNan]) print 1.4826*numpy.median(numpy.fabs(resv[notNan]-numpy.median(resv[notNan]))) print numpy.mean(resv[notNan]) print numpy.std(resv[notNan]) pyplot.annotate(r'$V_c = %i\,\mathrm{km\,s}^{-1}, V_{\odot-c}= 24\,\mathrm{km\,s}^{-1}$' % vc, (0.5,1.1),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=18.) bovy_plot.bovy_end_print(plotfilename) return None
def determine_vsolar_error(spiral=False): #Read the APOGEE-RC data and pixelate it #APOGEE-RC data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) data= data[indx] #Set up the Dehnen DF that we will sample from dfc= dehnendf(beta=0.,profileParams=(3./8.,33.3,31.4/220.)) trueVsolar= 24./220. ntrials= 100 mockvsolars= [] for ii in range(ntrials): print "Working on %i / %i" % (ii+1,ntrials) mockvsolars.append(determine_vsolar_mock(data,dfc,trueVsolar,spiral)) mockvsolars= numpy.array(mockvsolars) print mockvsolars print numpy.mean(mockvsolars-24.), numpy.std(mockvsolars) print numpy.sum(numpy.fabs(mockvsolars-24.) > 1.)/float(ntrials) return None
def plot_psd2d(plotfilename): data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx) data= data[indx] #Get residuals dx= _RCDX binsize= .8#.765 pix= pixelize_sample.pixelXY(data, xmin=_RCXMIN,xmax=_RCXMAX, ymin=_RCYMIN,ymax=_RCYMAX, dx=dx,dy=dx) resv= pix.plot(lambda x: dvlosgal(x,vtsun=220.+22.6), returnz=True,justcalc=True) resvunc= pix.plot('VHELIO_AVG', func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)), returnz=True,justcalc=True) psd2d= bovy_psd.psd2d(resv) tmax= numpy.unravel_index(numpy.argmax(psd2d),psd2d.shape) tmax0= float(psd2d.shape[0]/2-tmax[0])/psd2d.shape[0]*2 tmax1= float(tmax[1]-psd2d.shape[1]/2)/psd2d.shape[1]*2 kmax= 1./_RCDX print tmax0*kmax, tmax1*kmax #kmax= numpy.amax(numpy.fft.fftfreq(resv.shape[0]*2,_RCDX)) bovy_plot.bovy_print() bovy_plot.bovy_dens2d(psd2d.T,origin='lower',cmap='jet', interpolation='nearest', xrange=[-kmax,kmax], yrange=[-kmax,kmax], xlabel=r'$k_x\,(\mathrm{kpc}^{-1})$', ylabel=r'$k_y\,(\mathrm{kpc}^{-1})$') bovy_plot.bovy_end_print(plotfilename) if True: spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_hivres.sav')[1::2,1::2] potscale= 1.
down95= numpy.zeros(len(ds)) for ii in range(len(ds)): tdist= numpy.cumsum(vlos_dist[ii,:])/numpy.sum(vlos_dist[ii,:]) mid50[ii]= plotvloss[numpy.argmin(numpy.fabs(tdist-0.5))] down95[ii]= plotvloss[numpy.argmin(numpy.fabs(tdist-0.025))] up95[ii]= plotvloss[numpy.argmin(numpy.fabs(tdist-0.975))] interpmid50= interpolate.UnivariateSpline(ds,mid50,k=3) interpup95= interpolate.UnivariateSpline(ds,up95,k=3) interpdown95= interpolate.UnivariateSpline(ds,down95,k=3) #Plot median bovy_plot.bovy_plot(plotds,interpmid50(ds)+15., 'w--',lw=2.,overplot=True) bovy_plot.bovy_plot(plotds,interpmid50(ds),'w-',lw=2.,overplot=True) #Plot 95% bovy_plot.bovy_plot(plotds,interpup95(ds),'-',color='0.3',overplot=True) bovy_plot.bovy_plot(plotds,interpdown95(ds),'-',color='0.3',overplot=True) data= apread.rcsample() data= data[(numpy.fabs(data['GLON']-90.) < 5.)*(numpy.fabs(data['RC_GALZ']) < 0.05)] print numpy.amin(data['GLON']) print numpy.amax(data['GLON']) print len(data) bovy_plot.bovy_plot(data['RC_DIST'],data['VHELIO_AVG'], 'o',mfc='.45',mec='0.45', ms=5.,overplot=True,zorder=10) bovy_plot.bovy_text(r'$l=90^\circ,\, |Z| < 50\,\mathrm{pc}$', bottom_left=True,size=18.) bovy_plot.bovy_text(r'$\mathrm{solar\ motion}\ =\ 25\,\mathrm{km\,s}^{-1}$' +'\n'+r'$\mathrm{dashed}\ \rightarrow\ 10\,\mathrm{km\,s}^{-1}$', top_right=True,size=18.) bovy_plot.bovy_end_print(sys.argv[1])
def get_spectra(name, red_clump, location): """Return cluster data, spectra, spectral errors, photometric Teffs, and bitmask from APOGEE. If the data file for the specified cluster already exists locally, import the data from the file (cluster data, spectra, spectral errors, bitmask). If the data file does not exist, obtain the APOGEE spectra from a specified cluster from the allStar catalogue, replacing ASPCAP abundances with astroNN abundances. Parameters ---------- name : str Name of desired cluster (i.e. 'NGC 2682') red_clump : str If the red clump stars in rcsample are to be removed, set to 'True'. If all stars are to be used, set to 'False'. location : str If running locally, set to 'personal'. If running on the server, set to 'server'. Returns ------- apogee_cluster_data (all stars) or apogee_cluster_data_final (red clumps removed) : structured array All cluster data from APOGEE spectra_50 (all stars) or spectra_final (red clumps removed) : tuple Array of floats representing the cleaned-up fluxes in the APOGEE spectra with red clump stars removed spectra_err_50 (all stars) or spectra_err_final (red clumps removed) : tuple Array of floats representing the cleaned-up spectral errors from the APOGEE spectra with red clump stars removed good_T (all stars) or T_final (red clumps removed) : tuple Array of floats representing the effective temperatures of the stars in the cluster between 4000K and 5000K full_bitmask (all stars) or bitmask_final (red clumps removed) : tuple Array of ints (1 or 0), cleaned in the same way as the spectra, representing the bad pixels in the APOGEE_PIXMASK bitmask """ #Path, strip spaces in cluster name if location == 'personal': path = '/Users/chloecheng/Personal/' + str(name).replace(' ', '') + '.hdf5' elif location == 'server': path = '/geir_data/scr/ccheng/AST425/Personal/' + str(name).replace(' ', '') + '.hdf5' #If the data file for this cluster exists, save the data to variables if glob.glob(path): if red_clump == 'False': file = h5py.File(path, 'r') apogee_cluster_data = file['apogee_cluster_data'][()] spectra_50 = file['spectra'][()] spectra_err_50 = file['spectra_errs'][()] good_T = file['T'][()] full_bitmask = file['bitmask'][()] file.close() print(name, ' complete.') return apogee_cluster_data, spectra_50, spectra_err_50, good_T, full_bitmask elif red_clump == 'True': file = h5py.File(path, 'r') apogee_cluster_data_final = file['apogee_cluster_data'][()] spectra_final = file['spectra'][()] spectra_err_final = file['spectra_errs'][()] T_final = file['T'][()] bitmask_final = file['bitmask'][()] file.close() print(name, ' complete.') return apogee_cluster_data_final, spectra_final, spectra_err_final, T_final, bitmask_final #If the file does not exist, get the data from APOGEE else: #Get red clump stars from rcsample rc_data = rcsample(dr='14') rc_stars = [] for i in range(len(rc_data)): #rc_stars.append(rc_data[i][2]) - REMOVE IN FINAL VERSION rc_stars.append(rc_data[i][2].decode('UTF-8')) rc_stars = np.array(rc_stars) #Read in APOGEE catalogue data, removing duplicated stars and replacing ASPCAP with astroNN abundances apogee_cat = apread.allStar(use_astroNN_abundances=True) unique_apoids,unique_inds = np.unique(apogee_cat['APOGEE_ID'],return_index=True) apogee_cat = apogee_cat[unique_inds] #Read in overall cluster information cls = afits.open('occam_cluster-DR14.fits') cls = cls[1].data #Read in information about cluster members members = afits.open('occam_member-DR14.fits') members = members[1].data #Select all members of a given cluster cluster_members = (members['CLUSTER']==name) & (members['MEMBER_FLAG']=='GM') #second part of the mask indicates to only use giant stars member_list = members[cluster_members] #Find APOGEE entries for that cluster #numpy.in1d finds the 1D intersection between two lists. #In this case we're matching using the unique APOGEE ID assigned to each star #The indices given by numpy.in1d are for the first argument, so in this case the apogee catalogue cluster_inds = np.in1d((apogee_cat['APOGEE_ID']).astype('U100'),member_list['APOGEE_ID']) apogee_cluster_data = apogee_cat[cluster_inds] T = photometric_Teff(apogee_cluster_data) #Mark red clump stars in the members of the cluster as NaNs cluster_stars = member_list['APOGEE_ID'] cluster_marked = np.copy(cluster_stars) for i in range(len(cluster_stars)): for j in range(len(rc_stars)): if cluster_stars[i] == rc_stars[j]: cluster_marked[i] = np.nan #Get spectra, spectral errors, and bitmask for each star - apStar #We can use the APOGEE package to read each star's spectrum #We'll read in the ASPCAP spectra, which have combined all of the visits for each star and removed the spaces between the spectra number_of_members = len(member_list) spectra = np.zeros((number_of_members, 7514)) spectra_errs = np.zeros((number_of_members, 7514)) bitmask = np.zeros((number_of_members, 7514)) for s,star in enumerate(apogee_cluster_data): spectra[s] = apread.aspcapStar(star['LOCATION_ID'],star['APOGEE_ID'],ext=1,header=False,dr='14',aspcapWavegrid=True) spectra_errs[s] = apread.aspcapStar(star['LOCATION_ID'],star['APOGEE_ID'],ext=2,header=False,dr='14',aspcapWavegrid=True) bitmask[s] = apread.apStar(star['LOCATION_ID'],star['APOGEE_ID'],ext=3,header=False,dr='14', aspcapWavegrid=True)[1] #Set all entries in bitmask to integers bitmask = bitmask.astype(int) bitmask_flip = np.zeros_like(bitmask) for i in range(len(spectra)): for j in range(7514): if bitmask[i][j] == 0: bitmask_flip[i][j] = 1 else: bitmask_flip[i][j] = 0 #Remove empty spectra full_spectra = [] full_spectra_errs = [] full_bitmask = [] full_T = [] full_stars = [] for i in range(len(spectra)): if any(spectra[i,:] != 0): full_spectra.append(spectra[i]) full_spectra_errs.append(spectra_errs[i]) full_bitmask.append(bitmask_flip[i]) full_T.append(T[i]) full_stars.append(i) full_spectra = np.array(full_spectra) full_spectra_errs = np.array(full_spectra_errs) full_bitmask = np.array(full_bitmask) full_T = np.array(full_T) full_stars = np.array(full_stars) full_marked_stars = cluster_marked[full_stars] #Create array of NaNs to replace flagged values in spectra masked_spectra = np.empty_like(full_spectra) masked_spectra_errs = np.empty_like(full_spectra_errs) masked_spectra[:] = np.nan masked_spectra_errs[:] = np.nan #Mask the spectra for i in range(len(full_spectra)): for j in range(7514): if full_bitmask[i][j] != 0: masked_spectra[i][j] = full_spectra[i][j] masked_spectra_errs[i][j] = full_spectra_errs[i][j] #Cut stars that are outside of the temperature limits good_T_inds = (full_T > 4000) & (full_T < 5000) final_spectra = masked_spectra[good_T_inds] final_spectra_errs = masked_spectra_errs[good_T_inds] good_T = full_T[good_T_inds] apogee_cluster_data = apogee_cluster_data[good_T_inds] full_bitmask = full_bitmask[good_T_inds] final_stars = full_marked_stars[good_T_inds] rgs = (final_stars != 'nan') #Get indices for final red giant stars to be used #Want an SNR of 200 so set those errors that have a larger SNR to have an SNR of 200 spectra_err_200 = np.zeros_like(final_spectra_errs) for i in range(len(final_spectra)): for j in range(7514): if final_spectra[i][j]/final_spectra_errs[i][j] <= 200: spectra_err_200[i][j] = final_spectra_errs[i][j] else: spectra_err_200[i][j] = final_spectra[i][j]/200 #Cut errors with SNR of less than 50 spectra_50 = np.copy(final_spectra) spectra_err_50 = np.copy(spectra_err_200) for i in range(len(final_spectra)): for j in range(7514): if final_spectra[i][j]/spectra_err_200[i][j] <= 50: spectra_50[i][j] = np.nan spectra_err_50[i][j] = np.nan #Cut red clumps logg = apogee_cluster_data['LOGG'] apogee_cluster_data_final = apogee_cluster_data[rgs] spectra_final = spectra_50[rgs] spectra_err_final = spectra_err_50[rgs] T_final = good_T[rgs] bitmask_final = full_bitmask[rgs] if red_clump == 'False': #Write to file file = h5py.File(path, 'w') file['apogee_cluster_data'] = apogee_cluster_data file['spectra'] = spectra_50 file['spectra_errs'] = spectra_err_50 file['T'] = good_T file['bitmask'] = full_bitmask file.close() print(name, 'complete') return apogee_cluster_data, spectra_50, spectra_err_50, good_T, full_bitmask elif red_clump == 'True': #Write to file file = h5py.File(path, 'w') file['apogee_cluster_data'] = apogee_cluster_data_final file['spectra'] = spectra_final file['spectra_errs'] = spectra_err_final file['T'] = T_final file['bitmask'] = bitmask_final file.close() print(name, 'complete') return apogee_cluster_data_final, spectra_final, spectra_err_final, T_final, bitmask_final
def determine_vsolar(plotfilename): #Read the APOGEE-RC data and pixelate it #APOGEE-RC data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) data= data[indx] #Get velocity field pixrc= pixelize_sample.pixelXY(data, xmin=_RCXMIN,xmax=_RCXMAX, ymin=_RCYMIN,ymax=_RCYMAX, dx=_RCDX,dy=_RCDX) vsolars= numpy.linspace(0.,40.,51) lpower= large_scale_power(pixrc,vsolars,vc=220.,dx=_RCDX) bovy_plot.bovy_print() line1= bovy_plot.bovy_plot(vsolars,lpower,'k-',lw=2., xrange=[vsolars[0],vsolars[-1]], yrange=[0.,22.9], xlabel=r'$V_{\odot-c}\,(\mathrm{km\,s}^{-1})$', ylabel=r'$\sqrt\langle P_k(0.2 < k / (\mathrm{kpc}^{-1}) < 0.9)\rangle\,(\mathrm{km\,s}^{-1})$') #Find the minimum by fitting a second order polynomial p= numpy.polyfit(vsolars,lpower,2) minvsolar= -0.5*p[1]/p[0] bovy_plot.bovy_plot([minvsolar,minvsolar],[-10.,100.],'k-',lw=0.8, overplot=True) bovy_plot.bovy_text(22.65,1., r'$V_{\odot-c}=%.1f\,\mathrm{km\,s}^{-1}$' % minvsolar, size=15.) lpower240= large_scale_power(pixrc,vsolars,vc=240.,dx=_RCDX) line2= bovy_plot.bovy_plot(vsolars,lpower240,'k--',lw=2.,overplot=True) lpower200= large_scale_power(pixrc,vsolars,vc=200.,dx=_RCDX) line3= bovy_plot.bovy_plot(vsolars,lpower200,'k-.',lw=2.,overplot=True) lpowerbetam0p2= large_scale_power(pixrc,vsolars,dx=_RCDX,beta=-0.1) line4= bovy_plot.bovy_plot(vsolars,lpowerbetam0p2, '--',dashes=(20,10), color='0.6',lw=3.,overplot=True) lpowerbetap0p2= large_scale_power(pixrc,vsolars,dx=_RCDX,beta=0.1) line5= bovy_plot.bovy_plot(vsolars,lpowerbetap0p2, '--',dashes=(20,10), color='0.4',lw=3.,overplot=True) lva= large_scale_power(pixrc,vsolars,vc=220.,dx=_RCDX,hs=6./8.,hR=3./8.) line6= bovy_plot.bovy_plot(vsolars,lva, '-',color='0.8',lw=5.,overplot=True,zorder=-1) #Add legend legend1= pyplot.legend((line3[0],line1[0],line2[0]), (r'$V_c = 200\,\mathrm{km\,s}^{-1}$', r'$V_c = 220\,\mathrm{km\,s}^{-1}$', r'$V_c = 240\,\mathrm{km\,s}^{-1}$'), loc='upper left',#bbox_to_anchor=(.91,.375), numpoints=2, prop={'size':14}, frameon=False) legend2= pyplot.legend((line4[0],line5[0]), (r'$\beta = -0.1$', r'$\beta = \phantom{-}0.1$'), loc='upper right',bbox_to_anchor=(1.,.96), numpoints=2, prop={'size':14}, frameon=False) legend3= pyplot.legend((line6[0],), (r'$\Delta V_a(R_0) =5\,\mathrm{km\,s}^{-1}$',), loc='lower left',#bbox_to_anchor=(1.,.96), numpoints=2, prop={'size':12}, frameon=False) pyplot.gca().add_artist(legend1) pyplot.gca().add_artist(legend2) pyplot.gca().add_artist(legend3) bovy_plot.bovy_end_print(plotfilename) return None
def plot_rckinematics(plotfilename,subsun=False): #Set up 3 axes bovy_plot.bovy_print(fig_width=8.,axes_labelsize=14) axdx= 1./3. #APOGEE-RC observations tdy= (_RCYMAX-_RCYMIN+4.5)/(_RCXMAX-_RCXMIN+4.5)*axdx obsAxes= pyplot.axes([0.1,(1.-tdy)/2.,axdx,tdy]) pyplot.sca(obsAxes) data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) data= data[indx] #Get velocity field pixrc= pixelize_sample.pixelXY(data, xmin=_RCXMIN-2.25,xmax=_RCXMAX+2.25, ymin=_RCYMIN-2.25,ymax=_RCYMAX+2.25, dx=_RCDX,dy=_RCDX) if subsun: vmin, vmax= 0., 250. pixrc.plot(lambda x: vlosgal(x), func=lambda x: numpy.fabs(numpy.median(x)), zlabel=r'$|\mathrm{median}\ V^{\mathrm{GC}}_{\mathrm{los}}|\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax) else: vmin, vmax= -75., 75. img= pixrc.plot('VHELIO_AVG', vmin=vmin,vmax=vmax,overplot=True, colorbar=False) resv= pixrc.plot('VHELIO_AVG', justcalc=True,returnz=True) #for later bovy_plot.bovy_text(r'$\mathrm{typical\ uncertainty\!:}\ 3\,\mathrm{km\,s}^{-1}$', bottom_left=True,size=8.25) bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',top_right=True,size=10.) pyplot.annotate(r'$\mathrm{APOGEE\!-\!RC\ data}$', (0.5,1.09),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=10.) pyplot.axis([pixrc.xmin,pixrc.xmax,pixrc.ymin,pixrc.ymax]) bovy_plot._add_ticks() bovy_plot._add_axislabels(r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$', r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$') #Colorbar cbaxes = pyplot.axes([0.1625,(1.-tdy)/2.+tdy+0.065,2.*axdx-0.195,0.02]) CB1= pyplot.colorbar(img,orientation='horizontal', cax=cbaxes)#,ticks=[-16.,-8.,0.,8.,16.]) CB1.set_label(r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',labelpad=-35,fontsize=14.) #Now calculate the expected field xgrid= numpy.arange(_RCXMIN-2.25+_RCDX/2.,_RCXMAX+2.25+_RCDX/2.,_RCDX) ygrid= numpy.arange(_RCYMIN-2.25+_RCDX/2.,_RCYMAX+2.25+_RCDX/2.,_RCDX) xv,yv= numpy.meshgrid(xgrid,ygrid,indexing='ij') rs= numpy.sqrt(xv**2.+yv**2.) phis= numpy.arctan2(yv,xv) d,l= bovy_coords.rphi_to_dl_2d(rs/8.,phis) expec_vlos= numpy.empty((len(xgrid),len(ygrid))) for ii in range(len(xgrid)): for jj in range(len(ygrid)): expec_vlos[ii,jj]= modelvlosgal(rs[ii,jj],phis[ii,jj],l[ii,jj], vc=218.,vtsun=242.) modelAxes= pyplot.axes([0.03+axdx,(1.-tdy)/2.,axdx,tdy]) pyplot.sca(modelAxes) xlabel=r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$' ylabel=r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$' indx= True-numpy.isnan(resv) plotthis= copy.copy(expec_vlos) plotthis[numpy.isnan(resv)]= numpy.nan #turn these off bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet', interpolation='nearest', xlabel=xlabel,ylabel=ylabel, xrange=[_RCXMIN-2.25,_RCXMAX+2.25], yrange=[_RCYMIN-2.25,_RCYMAX+2.25], contours=False, vmin=vmin,vmax=vmax,overplot=True,zorder=3) if True: #Now plot the pixels outside the APOGEE data set plotthis= copy.copy(expec_vlos) plotthis[True-numpy.isnan(resv)]= numpy.nan #turn these off bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet', interpolation='nearest', alpha=0.3, xrange=[_RCXMIN-2.25,_RCXMAX+2.25], yrange=[_RCYMIN-2.25,_RCYMAX+2.25], contours=False, vmin=vmin,vmax=vmax,overplot=True, zorder=0) pyplot.annotate(r'$\mathrm{Bovy\ et.\ al\ (2012)\ model}$', (1.02,1.09),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=10.,zorder=3) pyplot.axis([_RCXMIN-2.25,_RCXMAX+2.25,_RCYMIN-2.25,_RCYMAX+2.25]) bovy_plot._add_ticks() bovy_plot._add_axislabels(xlabel,r'$ $') #Finally, add a polar plot of the whole disk res= 51 rmin, rmax= 0.2, 2.4 xgrid= numpy.linspace(0.,2.*numpy.pi*(1.-1./res/2.), 2.*res) ygrid= numpy.linspace(rmin,rmax,res) nx= len(xgrid) ny= len(ygrid) savefile= 'expec_vlos.sav' if os.path.exists(savefile): savefile= open(savefile,'rb') expec_vlos= pickle.load(savefile) savefile.close() else: expec_vlos= numpy.zeros((nx,ny)) for ii in range(nx): for jj in range(ny): R, phi= ygrid[jj], xgrid[ii] d,l= bovy_coords.rphi_to_dl_2d(R,phi) expec_vlos[ii,jj]= modelvlosgal(R*8.,phi,l, vc=218.,vtsun=242.) save_pickles(savefile,expec_vlos) plotxgrid= numpy.linspace(xgrid[0]-(xgrid[1]-xgrid[0])/2., xgrid[-1]+(xgrid[1]-xgrid[0])/2., len(xgrid)+1) plotygrid= numpy.linspace(ygrid[0]-(ygrid[1]-ygrid[0])/2., ygrid[-1]+(ygrid[1]-ygrid[0])/2., len(ygrid)+1) fullmodelAxes= pyplot.axes([-0.05+2.*axdx,(1.-tdy)/2.,axdx,tdy],polar=True) ax= fullmodelAxes pyplot.sca(fullmodelAxes) vmin, vmax= -150., 150. zlabel= r'$\mathrm{line\!-\!of\!-\!sight\ velocity}\ (\mathrm{km\,s}^{-1})$' out= ax.pcolor(plotxgrid,plotygrid,expec_vlos.T,cmap='jet', vmin=vmin,vmax=vmax,clip_on=False) shrink= 0.8 if False: CB1= pyplot.colorbar(out,shrink=shrink) bbox = CB1.ax.get_position().get_points() CB1.ax.set_position(transforms.Bbox.from_extents(bbox[0,0]+0.025, bbox[0,1], bbox[1,0], bbox[1,1])) CB1.set_label(zlabel) from matplotlib.patches import FancyArrowPatch arr= FancyArrowPatch(posA=(numpy.pi+0.1,1.8), posB=(3*numpy.pi/2.+0.1,1.8), arrowstyle='->', connectionstyle='arc3,rad=%4.2f' % (numpy.pi/8.-0.05), shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, mutation_aspect=None,fc='k') ax.add_patch(arr) bovy_plot.bovy_text(numpy.pi+0.17,1.7,r'$\mathrm{Galactic\ rotation}$', rotation=-30.,size=9.) radii= numpy.array([0.5,1.,1.5,2.,2.5]) labels= [] for r in radii: ax.plot(numpy.linspace(0.,2.*numpy.pi,501,), numpy.zeros(501)+r,ls='-',color='0.65',zorder=1,lw=0.5) labels.append(r'$%i$' % int(r*8.)) pyplot.rgrids(radii,labels=labels,angle=147.5) thetaticks = numpy.arange(0,360,45) # set ticklabels location at x times the axes' radius ax.set_thetagrids(thetaticks,frac=1.16,backgroundcolor='w',zorder=3) bovy_plot.bovy_text(3.*numpy.pi/4.+0.06,2.095,r'$\mathrm{kpc}$',size=10.) pyplot.ylim(0.,2.8) #Plot the box xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101) ys= numpy.ones(101)*(_RCYMIN-2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the box xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101) ys= numpy.ones(101)*(_RCYMAX+2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the box ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101) xs= numpy.ones(101)*(_RCXMIN-2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the box ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101) xs= numpy.ones(101)*(_RCXMAX+2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the connectors on the modelAxes xlow=-4.*8. ylow= 2.77*8. xs= numpy.linspace(xlow,(_RCXMAX+2.25),101) ys= (ylow-(_RCYMAX+2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2) line[0].set_clip_on(False) xlow=-4.*8. ylow= -2.77*8. xs= numpy.linspace(xlow,(_RCXMAX+2.25),101) ys= (ylow-(_RCYMIN-2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2) line[0].set_clip_on(False) #Colorbar cbaxes = pyplot.axes([0.01+2.*axdx,(1.-tdy)/2.+tdy+0.065,axdx-0.125,0.02]) CB1= pyplot.colorbar(out,orientation='horizontal', cax=cbaxes,ticks=[-150.,-75.,0.,75.,150.]) #CB1.set_label(r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$',labelpad=-35,fontsize=14.) bovy_plot.bovy_end_print(plotfilename,dpi=300) return None
def plot_rckinematics(plotfilename,subsun=False): #Set up 3 axes bovy_plot.bovy_print(fig_width=8.,axes_labelsize=14) axdx= 1./3. #APOGEE-RC observations tdy= (_RCYMAX-_RCYMIN+4.5)/(_RCXMAX-_RCXMIN+4.5)*axdx obsAxes= pyplot.axes([0.1,(1.-tdy)/2.,axdx,tdy]) pyplot.sca(obsAxes) data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) data= data[indx] #Get velocity field pixrc= pixelize_sample.pixelXY(data, xmin=_RCXMIN-2.25,xmax=_RCXMAX+2.25, ymin=_RCYMIN-2.25,ymax=_RCYMAX+2.25, dx=_RCDX,dy=_RCDX) vmin, vmax= -16.,16. img= pixrc.plot(lambda x: dvlosgal(x,vtsun=220.+24.), vmin=vmin,vmax=vmax,overplot=True, colorbar=False) resv= pixrc.plot(lambda x: dvlosgal(x,vtsun=220.+24.), justcalc=True,returnz=True) #for later pyplot.annotate(r'$\mathrm{APOGEE\!-\!RC\ data}$', (0.5,1.09),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=10.) pyplot.axis([pixrc.xmin,pixrc.xmax,pixrc.ymin,pixrc.ymax]) bovy_plot._add_ticks() bovy_plot._add_axislabels(r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$', r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$') #Colorbar cbaxes = pyplot.axes([0.1+axdx/2.,(1.-tdy)/2.+tdy+0.065,2.*axdx-0.195,0.02]) CB1= pyplot.colorbar(img,orientation='horizontal', cax=cbaxes)#,ticks=[-16.,-8.,0.,8.,16.]) CB1.set_label(r'$\mathrm{median}\ \Delta V_{\mathrm{los,rot}}\,(\mathrm{km\,s}^{-1})$',labelpad=-35,fontsize=14.) #Now calculate the expected field expec_vlos= galpy_simulations.vlos_altrect('../sim/bar_altrect_alpha0.015_hivres.sav')*220. modelAxes= pyplot.axes([0.03+axdx,(1.-tdy)/2.,axdx,tdy]) pyplot.sca(modelAxes) xlabel=r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$' ylabel=r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$' indx= True-numpy.isnan(resv) plotthis= copy.copy(expec_vlos) plotthis[numpy.isnan(resv)]= numpy.nan #turn these off bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet', interpolation='nearest', xlabel=xlabel,ylabel=ylabel, xrange=[_RCXMIN-2.25,_RCXMAX+2.25], yrange=[_RCYMIN-2.25,_RCYMAX+2.25], contours=False, vmin=vmin,vmax=vmax,overplot=True,zorder=3) if True: #Now plot the pixels outside the APOGEE data set plotthis= copy.copy(expec_vlos) plotthis[True-numpy.isnan(resv)]= numpy.nan #turn these off bovy_plot.bovy_dens2d(plotthis.T,origin='lower',cmap='jet', interpolation='nearest', alpha=0.3, xrange=[_RCXMIN-2.25,_RCXMAX+2.25], yrange=[_RCYMIN-2.25,_RCYMAX+2.25], contours=False, vmin=vmin,vmax=vmax,overplot=True, zorder=0) pyplot.annotate(r'$\mathrm{Favored\ bar\ model}$', (1.02,1.09),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=10.,zorder=3) pyplot.axis([_RCXMIN-2.25,_RCXMAX+2.25,_RCYMIN-2.25,_RCYMAX+2.25]) bovy_plot._add_ticks() bovy_plot._add_axislabels(xlabel,r'$ $') #Finally, add a polar plot of the whole disk res= 51 rmin, rmax= 0.2, 2.4 xgrid= numpy.linspace(0.,2.*numpy.pi*(1.-1./res/2.), 2.*res) ygrid= numpy.linspace(rmin,rmax,res) expec_vlos= galpy_simulations.vlos_polar('../sim/bar_polar_alpha0.015_hivres.sav')*220. plotxgrid= numpy.linspace(xgrid[0]-(xgrid[1]-xgrid[0])/2., xgrid[-1]+(xgrid[1]-xgrid[0])/2., len(xgrid)+1) plotygrid= numpy.linspace(ygrid[0]-(ygrid[1]-ygrid[0])/2., ygrid[-1]+(ygrid[1]-ygrid[0])/2., len(ygrid)+1) fullmodelAxes= pyplot.axes([-0.05+2.*axdx,(1.-tdy)/2.,axdx,tdy],polar=True) ax= fullmodelAxes pyplot.sca(fullmodelAxes) out= ax.pcolor(plotxgrid,plotygrid,expec_vlos.T,cmap='jet', vmin=vmin,vmax=vmax,clip_on=False) from matplotlib.patches import FancyArrowPatch arr= FancyArrowPatch(posA=(numpy.pi+0.1,1.8), posB=(3*numpy.pi/2.+0.1,1.8), arrowstyle='->', connectionstyle='arc3,rad=%4.2f' % (numpy.pi/8.-0.05), shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, mutation_aspect=None,fc='k',zorder=10) ax.add_patch(arr) bovy_plot.bovy_text(numpy.pi+0.17,1.7,r'$\mathrm{Galactic\ rotation}$', rotation=-30.,size=9.) radii= numpy.array([0.5,1.,1.5,2.,2.5]) labels= [] for r in radii: ax.plot(numpy.linspace(0.,2.*numpy.pi,501,), numpy.zeros(501)+r,ls='-',color='0.65',zorder=1,lw=0.5) labels.append(r'$%i$' % int(r*8.)) pyplot.rgrids(radii,labels=labels,angle=147.5) thetaticks = numpy.arange(0,360,45) # set ticklabels location at x times the axes' radius ax.set_thetagrids(thetaticks,frac=1.16,backgroundcolor='w',zorder=3) bovy_plot.bovy_text(3.*numpy.pi/4.+0.06,2.095,r'$\mathrm{kpc}$',size=10.) pyplot.ylim(0.,2.8) # Plot the bar position ets= numpy.linspace(0.,2.*numpy.pi,501,) a= 0.421766 b= a*0.4 dtr= numpy.pi/180. ax.plot(ets, a*b/numpy.sqrt((b*numpy.cos(ets-25.*dtr))**2. +(a*numpy.sin(ets-25.*dtr))**2.), zorder=1,lw=1.5,color='w') #Plot the box xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101) ys= numpy.ones(101)*(_RCYMIN-2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the box xs= numpy.linspace(_RCXMIN-2.25,_RCXMAX+2.25,101) ys= numpy.ones(101)*(_RCYMAX+2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the box ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101) xs= numpy.ones(101)*(_RCXMIN-2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the box ys= numpy.linspace(_RCYMIN-2.25,_RCYMAX+2.25,101) xs= numpy.ones(101)*(_RCXMAX+2.25) rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) ax.plot(phis,rs,'--',lw=1.25,color='k') #Plot the connectors on the modelAxes xlow=-4.*8. ylow= 2.77*8. xs= numpy.linspace(xlow,(_RCXMAX+2.25),101) ys= (ylow-(_RCYMAX+2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2) line[0].set_clip_on(False) xlow=-4.*8. ylow= -2.77*8. xs= numpy.linspace(xlow,(_RCXMAX+2.25),101) ys= (ylow-(_RCYMIN-2.25))/(xlow-(_RCXMAX+2.25))*(xs-xlow)+ylow rs= numpy.sqrt(xs**2.+ys**2.)/8. phis= numpy.arctan2(ys,xs) line= ax.plot(phis,rs,':',lw=1.,color='k',zorder=2) line[0].set_clip_on(False) bovy_plot.bovy_end_print(plotfilename,dpi=300) return None
def plot_metallicity(basesavefilename, datafilename=None): # First read the sample if not datafilename is None: data = fitsio.read(datafilename) else: data = apread.rcsample() if _ADDLLOGGCUT: data = data[data["ADDL_LOGG_CUT"] == 1] # Cut indx = (numpy.fabs(data["RC_GALZ"]) < 0.05) * (data["METALS"] > -1000.0) print "Using %i stars for low-Z metallicity gradient analysis" % numpy.sum(indx) data = data[indx] # First do the metallicity gradient rs = numpy.arange(0.5, 18.5001, 0.85) fehs = numpy.zeros_like(rs) + numpy.nan sigfehs = numpy.zeros_like(rs) + numpy.nan efehs = numpy.zeros_like(rs) + numpy.nan for ii in range(len(rs) - 1): tindx = (data["RC_GALR"] > rs[ii]) * (data["RC_GALR"] <= rs[ii + 1]) if numpy.sum(tindx) < 20: continue fehs[ii] = numpy.median(data["METALS"][tindx]) sigfehs[ii] = numpy.std(data["METALS"][tindx]) efehs[ii] = numpy.std(data["METALS"][tindx]) / numpy.sqrt(numpy.sum(tindx)) # Plot bovy_plot.bovy_print(fig_width=6.0) bovy_plot.bovy_plot( rs + 0.5 * (rs[1] - rs[0]), fehs, "ko", xlabel=r"$R\,(\mathrm{kpc})$", ylabel=r"$\mathrm{median\ [Fe/H]}\,(\mathrm{dex})$", xrange=[0.0, 15.0], yrange=[-0.6, 0.5], zorder=10, ) pyplot.errorbar(rs + 0.5 * (rs[1] - rs[0]), fehs, yerr=efehs, marker="None", ls="none", color="k", zorder=9) # bovy_plot.bovy_plot(data['RC_GALR'],data['METALS'],'k,',overplot=True) # FIT indx = True - numpy.isnan(fehs) bestfit = optimize.curve_fit( linfit, (rs + 0.5 * (rs[1] - rs[0]))[indx], fehs[indx], sigma=efehs[indx], p0=(-0.1, 0.0) ) if _JACKERRS: fitrs = (rs + 0.5 * (rs[1] - rs[0]))[indx] fitfehs = fehs[indx] fitefehs = efehs[indx] np = len(fitfehs) fitp0 = [] fitp1 = [] for ii in range(np): findx = numpy.ones(np, dtype="bool") findx[ii] = False tbestfit = optimize.curve_fit(linfit, fitrs[findx], fitfehs[findx], sigma=fitefehs[findx], p0=(-0.1, 0.0)) fitp0.append(tbestfit[0][0]) fitp1.append(tbestfit[0][1]) fitp0 = numpy.array(fitp0) fitp1 = numpy.array(fitp1) p0err = numpy.sqrt((np - 1.0) * numpy.var(fitp0)) p1err = numpy.sqrt((np - 1.0) * numpy.var(fitp1)) print "radial metallicity errors" print bestfit[0][0], p0err print bestfit[0][1], p1err bovy_plot.bovy_plot( rs + 0.5 * (rs[1] - rs[0]), bestfit[0][0] * ((rs + 0.5 * (rs[1] - rs[0]) - 8.0)) + bestfit[0][1], "k--", overplot=True, ) bovy_plot.bovy_text(r"$|Z| < 50\,\mathrm{pc}$", top_right=True, size=18.0) bovy_plot.bovy_text( r"$[\mathrm{Fe/H}] = %.2f\,\frac{\mathrm{dex}}{\mathrm{kpc}}\,(R-8\,\mathrm{kpc}) + %.2f$" % (bestfit[0][0], bestfit[0][1]), bottom_left=True, size=18.0, ) bovy_plot.bovy_end_print(basesavefilename + "_radialgradient." + _EXT) # Now plot azimuthal stuff # First read the sample again if not datafilename is None: data = fitsio.read(datafilename) else: data = apread.rcsample() if _ADDLLOGGCUT: data = data[data["ADDL_LOGG_CUT"] == 1] # Cut indx = (numpy.fabs(data["RC_GALZ"]) < 0.25) * (data["METALS"] > -1000.0) print "Using %i stars for low-Z azimuthal metallicity gradient analysis" % numpy.sum(indx) data = data[indx] pix = pixelize_sample.pixelXY(data) bovy_plot.bovy_print() pix.plot("METALS", zlabel=r"$\mathrm{median\ [Fe/H]}\,(\mathrm{dex})$", vmin=-0.4, vmax=0.3) if "l30" in appath._APOGEE_REDUX: bovy_plot.bovy_text(r"$\mathrm{typical\ uncertainty\!:}\ 0.015\,\mathrm{dex}$", bottom_left=True, size=17.0) elif "v6" in appath._APOGEE_REDUX and int(appath._APOGEE_REDUX[1:]) > 600: bovy_plot.bovy_text(r"$\mathrm{typical\ uncertainty\!:}\ 0.015\,\mathrm{dex}$", bottom_left=True, size=17.0) else: bovy_plot.bovy_text(r"$\mathrm{typical\ uncertainty\!:}\ 0.02\,\mathrm{dex}$", bottom_left=True, size=18.0) bovy_plot.bovy_text(r"$|Z| < 250\,\mathrm{pc}$", top_right=True, size=18.0) bovy_plot.bovy_end_print(basesavefilename + "_XY." + _EXT) # R,phi pix = pixelize_sample.pixelXY(data, rphi=True, ymin=-22.5, ymax=37.5, dy=5.0) bovy_plot.bovy_print() metals2d = pix.plot( "METALS", # func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)), zlabel=r"$\delta\,\mathrm{median\ [Fe/H]}\,(\mathrm{dex})$", # vmin=0.,vmax=0.05,submediany=False,returnz=True) vmin=-0.1, vmax=0.1, submediany=True, returnz=True, ) sigs = [] for ii in range(metals2d.shape[0]): tindx = True - numpy.isnan(metals2d[ii, :]) if numpy.sum(tindx) > 2: sigs.append(1.4826 * numpy.median(numpy.fabs(metals2d[ii, tindx]))) sigs = numpy.array(sigs) print numpy.median(sigs), numpy.amax(sigs), sigs # bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',bottom_left=True,size=18.) bovy_plot.bovy_end_print(basesavefilename + "_RPHI." + _EXT) # vs. alpha # First read the sample if not datafilename is None: data = fitsio.read(datafilename) else: data = apread.rcsample() if _ADDLLOGGCUT: data = data[data["ADDL_LOGG_CUT"] == 1] # Cut indx = (numpy.fabs(data["RC_GALZ"]) < 0.1) * (data["METALS"] > -1000.0) data = data[indx] bovy_plot.bovy_print() bovy_plot.bovy_plot( data["METALS"], data["ALPHAFE"], "k.", ms=2.0, xlabel=r"$[\mathrm{Fe/H}]\,(\mathrm{dex})$", ylabel=r"$[\alpha/\mathrm{Fe}]\,(\mathrm{dex})$", xrange=[-1.0, 0.5], yrange=[-0.15, 0.35], onedhists=True, bins=31, ) bovy_plot.bovy_text(r"$|Z| < 100\,\mathrm{pc}$", top_right=True, size=18.0) bovy_plot.bovy_text(r"$\mathrm{raw\ sample\ counts}$", bottom_left=True, size=18.0) bovy_plot.bovy_end_print(basesavefilename + "_alpha." + _EXT) # vs. alpha # First read the sample if not datafilename is None: data = fitsio.read(datafilename) else: data = apread.rcsample() if _ADDLLOGGCUT: data = data[data["ADDL_LOGG_CUT"] == 1] # Cut indx = (numpy.fabs(data["RC_GALZ"]) > 0.5) * (numpy.fabs(data["RC_GALZ"]) < 1.0) * (data["METALS"] > -1000.0) data = data[indx] bovy_plot.bovy_print() bovy_plot.bovy_plot( data["METALS"], data["ALPHAFE"], "k.", ms=2.0, xlabel=r"$[\mathrm{Fe/H}]\,(\mathrm{dex})$", ylabel=r"$[\alpha/\mathrm{Fe}]\,(\mathrm{dex})$", xrange=[-1.0, 0.5], yrange=[-0.15, 0.35], onedhists=True, bins=31, ) bovy_plot.bovy_text(r"$0.5\,\mathrm{kpc} < |Z| < 1\,\mathrm{kpc}$", top_right=True, size=18.0) bovy_plot.bovy_text(r"$\mathrm{raw\ sample\ counts}$", bottom_left=True, size=18.0) bovy_plot.bovy_end_print(basesavefilename + "_alpha_0.5z1." + _EXT) # vs. alpha # First read the sample if not datafilename is None: data = fitsio.read(datafilename) else: data = apread.rcsample() if _ADDLLOGGCUT: data = data[data["ADDL_LOGG_CUT"] == 1] # Cut indx = (numpy.fabs(data["RC_GALZ"]) > 1.0) * (numpy.fabs(data["RC_GALZ"]) < 2.0) * (data["METALS"] > -1000.0) data = data[indx] bovy_plot.bovy_print() bovy_plot.bovy_plot( data["METALS"], data["ALPHAFE"], "k.", ms=2.0, xlabel=r"$[\mathrm{Fe/H}]\,(\mathrm{dex})$", ylabel=r"$[\alpha/\mathrm{Fe}]\,(\mathrm{dex})$", xrange=[-1.0, 0.5], yrange=[-0.15, 0.35], onedhists=True, bins=21, ) bovy_plot.bovy_text(r"$1\,\mathrm{kpc} < |Z| < 2\,\mathrm{kpc}$", top_right=True, size=18.0) bovy_plot.bovy_text(r"$\mathrm{raw\ sample\ counts}$", bottom_left=True, size=18.0) bovy_plot.bovy_end_print(basesavefilename + "_alpha_1z2." + _EXT) # vs. alpha # First read the sample if not datafilename is None: data = fitsio.read(datafilename) else: data = apread.rcsample() if _ADDLLOGGCUT: data = data[data["ADDL_LOGG_CUT"] == 1] # Cut indx = (data["STAT"] == 1) * (data["METALS"] > -1000.0) data = data[indx] hist, edges = numpy.histogramdd( numpy.array([data["METALS"], data["ALPHAFE"]]).T, bins=[15, 10], range=[[-1.0, 0.5], [-0.15, 0.35]] ) bovy_plot.bovy_print() bovy_plot.bovy_dens2d( hist.T, contours=False, shrink=0.78, cmap="gist_yarg", origin="lower", xrange=[-1.0, 0.5], yrange=[-0.15, 0.35], vmin=50.0, vmax=1000.0, xlabel=r"$[\mathrm{Fe/H}]\,(\mathrm{dex})$", ylabel=r"$[\alpha/\mathrm{Fe}]\,(\mathrm{dex})$", interpolation="nearest", colorbar=True, ) bovy_plot.bovy_text(r"$\mathrm{main\ sample}$", top_right=True, size=18.0) bovy_plot.bovy_text(r"$\mathrm{raw\ sample\ counts}$", bottom_left=True, size=18.0) bovy_plot.bovy_end_print(basesavefilename + "_alpha_main." + _EXT)
import numpy import apogee.tools.read as apread _DATA = apread.rcsample() #such that we can re-use it in different tests def test_int64(): #Test that there aren't 64-bit integers for key in _DATA.dtype.names: assert not numpy.issubdtype( _DATA[key].dtype, numpy.int64 ), "Tag '%s' in the RC catalog is a 64-bit signed integer that might give problems for some readers" % key return None
def get_spectra(name, red_clump, location): """Return cluster data, spectra, spectral errors, photometric Teffs, and bitmask from APOGEE. If the data file for the specified cluster already exists locally, import the data from the file (cluster data, spectra, spectral errors, bitmask). If the data file does not exist, obtain the APOGEE spectra from a specified cluster from the allStar catalogue, replacing ASPCAP abundances with astroNN abundances. Parameters ---------- name : str Name of desired cluster (i.e. 'PJ_26') red_clump : bool If the red clump stars in rcsample are to be removed, set to True. If all stars are to be used, set to False. Returns ------- cluster_data_full (all stars) or cluster_data (red clumps removed) : structured array All cluster data from APOGEE cluster_spectra_full (all stars) or cluster_spectra (red clumps removed) : tuple Array of floats representing the cleaned-up fluxes in the APOGEE spectra with red clump stars removed cluster_spectra_errs_full (all stars) or cluster_spectra_errs (red clumps removed) : tuple Array of floats representing the cleaned-up spectral errors from the APOGEE spectra with red clump stars removed cluster_T_full (all stars) or cluster_T (red clumps removed) : tuple Array of floats representing the effective temperatures of the stars in the cluster between 4000K and 5000K full_bitmask (all stars) or bitmask_final (red clumps removed) : tuple Array of ints (1 or 0), cleaned in the same way as the spectra, representing the bad pixels in the APOGEE_PIXMASK bitmask """ if location == 'personal': path = '/Users/chloecheng/Personal/' + str(name) + '.hdf5' elif location == 'server': path = '/geir_data/scr/ccheng/AST425/Personal/' + str(name) + '.hdf5' #If the data file for this cluster exists, save the data to variables if glob.glob(path): if red_clump == 'False': file = h5py.File(path, 'r') cluster_data_full = file['apogee_cluster_data'][()] cluster_spectra_full = file['spectra'][()] cluster_spectra_errs_full = file['spectra_errs'][()] cluster_T_full = file['T'][()] full_bitmask = file['bitmask'][()] file.close() print(name, ' complete.') return cluster_data_full, cluster_spectra_full, cluster_spectra_errs_full, cluster_T_full, full_bitmask elif red_clump == 'True': file = h5py.File(path, 'r') cluster_data = file['apogee_cluster_data'][()] cluster_spectra = file['spectra'][()] cluster_spectra_errs = file['spectra_errs'][()] cluster_T = file['T'][()] bitmask_final = file['bitmask'][()] file.close() print(name, ' complete.') return cluster_data, cluster_spectra, cluster_spectra_errs, cluster_T, bitmask_final #If the file does not exist else: #Get red clump stars from rcsample rc_data = rcsample(dr='14') rc_stars = [] for i in range(len(rc_data)): if location == 'personal': rc_stars.append(rc_data[i][2]) elif location == 'server': rc_stars.append(rc_data[i][2].decode('UTF-8')) rc_stars = np.array(rc_stars) #Read in PJ catalogue data if location == 'personal': apogee_cluster_data = np.load( '/Users/chloecheng/Personal/published_clusters.npy') elif location == 'server': apogee_cluster_data = np.load( '/geir_data/scr/ccheng/AST425/Personal/published_clusters.npy') #Get temperatures #T = photometric_Teff(apogee_cluster_data) T = apogee_cluster_data['TEFF'] #Get spectra for each star number_of_members = 360 spectra = np.zeros((number_of_members, 7514)) spectra_errs = np.zeros((number_of_members, 7514)) bitmask = np.zeros((number_of_members, 7514)) missing_spectra = [] stars = [] for s, star in enumerate(apogee_cluster_data): loc = star['FIELD'].decode('utf-8') apo = star['APOGEE_ID'].decode('utf-8') stars.append(apo) try: spectra[s] = apread.aspcapStar( loc, apo, ext=1, header=False, dr='16', aspcapWavegrid=True, telescope=star['TELESCOPE'].decode('utf-8')) spectra_errs[s] = apread.aspcapStar( loc, apo, ext=2, header=False, dr='16', aspcapWavegrid=True, telescope=star['TELESCOPE'].decode('utf-8')) bitmask[s] = apread.apStar( loc, apo, ext=3, header=False, dr='16', aspcapWavegrid=True, telescope=star['TELESCOPE'].decode('utf-8'))[1] #If the spectrum is missing, set bitmask to value that will be removed except OSError: bitmask[s] = -1.0 missing_spec.append(s) print('missing ', star['APOGEE_ID'].decode("utf-8")) #Mark red clump stars PJ_stars = np.array(stars) PJ_marked = np.copy(PJ_stars) for i in range(len(PJ_stars)): for j in range(len(rc_stars)): if PJ_stars[i] == rc_stars[j]: PJ_marked[i] = np.nan #Set all entries in bitmask to integers bitmask = bitmask.astype(int) bitmask_flip = np.zeros_like(bitmask) for i in range(len(spectra)): for j in range(7514): if bitmask[i][j] == 0: bitmask_flip[i][j] = 1 else: bitmask_flip[i][j] = 0 #Remove empty spectra full_spectra = [] full_spectra_errs = [] full_bitmask = [] full_stars = [] full_T = [] for i in range(len(spectra)): if any(spectra[i, :] != 0): full_spectra.append(spectra[i]) full_spectra_errs.append(spectra_errs[i]) full_bitmask.append(bitmask_flip[i]) full_stars.append(i) full_T.append(T[i]) full_spectra = np.array(full_spectra) full_spectra_errs = np.array(full_spectra_errs) full_bitmask = np.array(full_bitmask) full_stars = np.array(full_stars) full_T = np.array(full_T) full_marked_stars = PJ_marked[full_stars] #Create array of nans to replace flagged values in spectra masked_spectra = np.empty_like(full_spectra) masked_spectra_errs = np.empty_like(full_spectra_errs) masked_spectra[:] = np.nan masked_spectra_errs[:] = np.nan #Mask the spectra for i in range(len(full_spectra)): for j in range(7514): if full_bitmask[i][j] != 0: masked_spectra[i][j] = full_spectra[i][j] masked_spectra_errs[i][j] = full_spectra_errs[i][j] #Cut stars that are outside of the temperature limits good_T_inds = (full_T > 4000) & (full_T < 5000) final_spectra = masked_spectra[good_T_inds] final_spectra_errs = masked_spectra_errs[good_T_inds] good_T = full_T[good_T_inds] apogee_cluster_data = apogee_cluster_data[good_T_inds] full_bitmask = full_bitmask[good_T_inds] final_stars = full_marked_stars[good_T_inds] #ADDED rgs = (final_stars != 'nan') #ADDED #Want an SNR of 200 so set those errors that have a larger SNR to have an SNR of 200 spectra_err_200 = np.zeros_like(final_spectra_errs) for i in range(len(final_spectra)): for j in range(7514): if final_spectra[i][j] / final_spectra_errs[i][j] <= 200: spectra_err_200[i][j] = final_spectra_errs[i][j] else: spectra_err_200[i][j] = final_spectra[i][j] / 200 #Cut errors with SNR of less than 50 spectra_50 = np.copy(final_spectra) spectra_err_50 = np.copy(spectra_err_200) for i in range(len(final_spectra)): for j in range(7514): if final_spectra[i][j] / spectra_err_200[i][j] <= 50: spectra_50[i][j] = np.nan spectra_err_50[i][j] = np.nan #Separate out individual clusters cluster_ids = apogee_cluster_data['CLUSTER_ID'] PJ_26 = [] PJ_95 = [] PJ_471 = [] PJ_162 = [] PJ_398 = [] PJ_151 = [] PJ_230 = [] PJ_939 = [] PJ_262 = [] PJ_289 = [] PJ_359 = [] PJ_396 = [] PJ_899 = [] PJ_189 = [] PJ_574 = [] PJ_641 = [] PJ_679 = [] PJ_1976 = [] PJ_88 = [] PJ_1349 = [] PJ_1811 = [] for i in range(len(apogee_cluster_data)): if cluster_ids[i] == 26: PJ_26.append(i) elif cluster_ids[i] == 95: PJ_95.append(i) elif cluster_ids[i] == 471: PJ_471.append(i) elif cluster_ids[i] == 162: PJ_162.append(i) elif cluster_ids[i] == 398: PJ_398.append(i) elif cluster_ids[i] == 151: PJ_151.append(i) elif cluster_ids[i] == 230: PJ_230.append(i) elif cluster_ids[i] == 939: PJ_939.append(i) elif cluster_ids[i] == 262: PJ_262.append(i) elif cluster_ids[i] == 289: PJ_289.append(i) elif cluster_ids[i] == 359: PJ_359.append(i) elif cluster_ids[i] == 396: PJ_396.append(i) elif cluster_ids[i] == 899: PJ_899.append(i) elif cluster_ids[i] == 189: PJ_189.append(i) elif cluster_ids[i] == 574: PJ_574.append(i) elif cluster_ids[i] == 641: PJ_641.append(i) elif cluster_ids[i] == 679: PJ_679.append(i) elif cluster_ids[i] == 1976: PJ_1976.append(i) elif cluster_ids[i] == 88: PJ_88.append(i) elif cluster_ids[i] == 1349: PJ_1349.append(i) elif cluster_ids[i] == 1811: PJ_1811.append(i) cluster_dict = { 'PJ_26': PJ_26, 'PJ_95': PJ_95, 'PJ_471': PJ_471, 'PJ_162': PJ_162, 'PJ_398': PJ_398, 'PJ_151': PJ_151, 'PJ_230': PJ_230, 'PJ_939': PJ_939, 'PJ_262': PJ_262, 'PJ_289': PJ_289, 'PJ_359': PJ_359, 'PJ_396': PJ_396, 'PJ_899': PJ_899, 'PJ_189': PJ_189, 'PJ_574': PJ_574, 'PJ_641': PJ_641, 'PJ_679': PJ_679, 'PJ_1976': PJ_1976, 'PJ_88': PJ_88, 'PJ_1349': PJ_1349, 'PJ_1811': PJ_1811 } cluster_data_full = apogee_cluster_data[cluster_dict[name]] cluster_spectra_full = spectra_50[cluster_dict[name]] cluster_spectra_errs_full = spectra_err_50[cluster_dict[name]] cluster_T_full = good_T[cluster_dict[name]] #Cut red clump stars cluster_rgs = rgs[cluster_dict[name]] cluster_data = cluster_data_full[cluster_rgs] cluster_spectra = cluster_spectra_full[cluster_rgs] cluster_spectra_errs = cluster_spectra_errs_full[cluster_rgs] cluster_T = cluster_T_full[cluster_rgs] bitmask_final = full_bitmask[rgs] if red_clump == 'False': #Write to file file = h5py.File(path, 'w') file['apogee_cluster_data'] = cluster_data_full file['spectra'] = cluster_spectra_full file['spectra_errs'] = cluster_spectra_errs_full file['T'] = cluster_T_full file['bitmask'] = full_bitmask file.close() print(name, 'complete') return cluster_data_full, cluster_spectra_full, cluster_spectra_errs_full, cluster_T_full, full_bitmask elif red_clump == 'True': #Write to file file = h5py.File(path, 'w') file['apogee_cluster_data'] = cluster_data file['spectra'] = cluster_spectra file['spectra_errs'] = cluster_spectra_errs file['T'] = cluster_T file['bitmask'] = bitmask_final file.close() print(name, 'complete') return cluster_data, cluster_spectra, cluster_spectra_errs, cluster_T, bitmask_final
import sys os.environ['APOGEE_REDUX']='v603' os.environ['APOGEE_DATA']='/Users/jquark/obs_data/apogee/' import apogee.tools.read as apread import numpy as np #import galpy.util.bovy_coords as bovy_coords import matplotlib as mpl from matplotlib import pyplot as plt import numpy as np import numpy.lib.recfunctions as rfn apogee_data_dir = '/Users/jquark/obs_data/apogee' ness_age_cat_file = os.path.join(apogee_data_dir, 'HWR_redclump_sample.txt') RCcat = apread.rcsample() fields = ['APOGEE_ID', 'RC_DIST', 'RC_GALR', 'RC_GALPHI', 'RC_GALZ', 'TEFF', 'LOGG', 'FE_H', 'ALPHAFE', 'RC_GALR'] #Using the Rccatalog to provide data types for making record array with ness catalog # The last 'RC_GALR' is just to steal the datatype to make the age array ness_dtypes=[RCcat[field].dtype for field in fields] ness_fields = ['APOGEE_ID', 'RC_DIST', 'RC_GALR', 'RC_GALPHI', 'RC_GALZ', 'TEFF', 'LOGG', 'FE_H', 'ALPHAFE', 'AGE'] ndtypes = [(i,j) for i,j in zip(ness_fields, ness_dtypes)] ness_cat = np.loadtxt(ness_age_cat_file, dtype=ndtypes) ###can write out record array here and now ### ### After this, change the columns for the merging print((RCcat['APOGEE_ID']==ness_cat['APOGEE_ID']).all())
def plot_psd_model(plotfilename,type): #Load fiducial # spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-14%s.sav' % _HIVRESSTR) spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015%s.sav' % _HIVRESSTR) potscale= 1. simpsd1d= bovy_psd.psd1d(spvlos*potscale,0.33333333,binsize=0.8) tks= simpsd1d[0][1:-3] xrange=[.08,4.] if type.lower() == 'elliptical': eres= 31 p= 0. vloscp= galpy_simulations.vlos_elliptical(res=eres,cp=0.02,sp=0.,p=p) vlossp= galpy_simulations.vlos_elliptical(res=eres,sp=0.02,cp=0.,p=p) vloscpsp= galpy_simulations.vlos_elliptical(res=eres,p=p, sp=0.02/numpy.sqrt(2.), cp=0.02/numpy.sqrt(2.)) p=2. vloscpp2= galpy_simulations.vlos_elliptical(res=eres,cp=0.01,sp=0.,p=p) vlosspp2= galpy_simulations.vlos_elliptical(res=eres,sp=0.01,cp=0.,p=p) vloscpspp2= galpy_simulations.vlos_elliptical(res=eres,p=p, sp=0.01/numpy.sqrt(2.), cp=0.01/numpy.sqrt(2.)) p=-3. vloscppm3= galpy_simulations.vlos_elliptical(res=eres,cp=0.05,sp=0.,p=p) vlossppm3= galpy_simulations.vlos_elliptical(res=eres,sp=0.05,cp=0.,p=p) vloscpsppm3= galpy_simulations.vlos_elliptical(res=eres,p=p, sp=0.05/numpy.sqrt(2.), cp=0.05/numpy.sqrt(2.)) xgrid= numpy.linspace((_RCXMIN-8.)/8.+_RCDX/8./2., (_RCXMAX-8.)/8.-_RCDX/8./2., eres) dx= (xgrid[1]-xgrid[0])*8. psdcp= bovy_psd.psd1d(vloscp,dx,binsize=0.8) psdsp= bovy_psd.psd1d(vlossp,dx,binsize=0.8) psdcpsp= bovy_psd.psd1d(vloscpsp,dx,binsize=0.8) psdcpp2= bovy_psd.psd1d(vloscpp2,dx,binsize=0.8) psdspp2= bovy_psd.psd1d(vlosspp2,dx,binsize=0.8) psdcpspp2= bovy_psd.psd1d(vloscpspp2,dx,binsize=0.8) psdcppm3= bovy_psd.psd1d(vloscppm3,dx,binsize=0.8) psdsppm3= bovy_psd.psd1d(vlossppm3,dx,binsize=0.8) psdcpsppm3= bovy_psd.psd1d(vloscpsppm3,dx,binsize=0.8) ks= psdcp[0][1:-3] scale= 4.*numpy.pi*220. bovy_plot.bovy_print(fig_width=8.,fig_height=4.5,axes_labelsize=20) line1= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcp[1][1:-3]), 'k-',lw=2., semilogx=True, # xlabel=r'$k\,(\mathrm{kpc}^{-1})$', ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1})$', xrange=xrange, yrange=[0.,11.9],zorder=1) line2= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsp[1][1:-3]), 'k--',lw=2., overplot=True,zorder=1) line3= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcpsp[1][1:-3]), 'k-.',lw=2.,zorder=1, overplot=True) line4= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcpp2[1][1:-3]), '-',lw=2.,color='c',zorder=1, overplot=True) line5= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdspp2[1][1:-3]), '--',lw=2.,color='c',zorder=1, overplot=True) line6= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcpspp2[1][1:-3]), '-.',lw=2.,color='c',zorder=1, overplot=True) line7= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcppm3[1][1:-3]), '-',lw=2.,color='r',zorder=1, overplot=True) line8= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsppm3[1][1:-3]), '--',lw=2.,color='r',zorder=1, overplot=True) line9= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdcpsppm3[1][1:-3]), '-.',lw=2.,color='r',zorder=1, overplot=True) pyplot.annotate(r'$\mathrm{Elliptical\ perturbation}\ (m=2\ \mathrm{mode})$', (0.5,1.08),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=20.) l1= pyplot.legend((line1[0],line2[0],line3[0]), (r'$\phi_b = 0^\circ$', r'$\phi_b = 45^\circ$', r'$\phi_b = 90^\circ$'), loc='lower left',#bbox_to_anchor=(.91,.375), numpoints=8, prop={'size':16}, frameon=False) l2= pyplot.legend((line1[0],line4[0],line7[0]), (r'$\epsilon(R) = 0.02$', r'$\epsilon(R) = 0.01\,\left(\frac{R}{R_0}\right)^2$', r'$\epsilon(R) = 0.05\,\left(\frac{R}{R_0}\right)^{-3}$'), loc='upper right',#bbox_to_anchor=(.91,.375), numpoints=8, prop={'size':16}, frameon=False) pyplot.gca().add_artist(l1) pyplot.gca().add_artist(l2) elif type.lower() == 'bar': vlosbar= galpy_simulations.vlos('../sim/bar_rect_alpha0.015%s.sav' % _HIVRESSTR) vlosslowbar= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_slow%s.sav' % _HIVRESSTR) vlosbarsmallangle= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_angle10%s.sav' % _HIVRESSTR) vlosbarlargeangle= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_angle40%s.sav' % _HIVRESSTR) vlosbarsmallrolr= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_rolr0.85%s.sav' % _HIVRESSTR) vlosbarlargerolr= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_rolr0.95%s.sav' % _HIVRESSTR) eres= 19 xgrid= numpy.linspace((_RCXMIN-8.)/8.+_RCDX/8./2., (_RCXMAX-8.)/8.-_RCDX/8./2., eres) dx= (xgrid[1]-xgrid[0])*8. psdbar= bovy_psd.psd1d(vlosbar,dx,binsize=0.8) psdslowbar= bovy_psd.psd1d(vlosslowbar,dx,binsize=0.8) psdsbarsmallangle= bovy_psd.psd1d(vlosbarsmallangle,dx,binsize=0.8) psdsbarlargeangle= bovy_psd.psd1d(vlosbarlargeangle,dx,binsize=0.8) psdsbarsmallrolr= bovy_psd.psd1d(vlosbarsmallrolr,dx,binsize=0.8) psdsbarlargerolr= bovy_psd.psd1d(vlosbarlargerolr,dx,binsize=0.8) ks= psdbar[0][1:-3] scale= 4.*numpy.pi*220. bovy_plot.bovy_print(fig_width=8.,fig_height=4.5,axes_labelsize=20) line1= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdbar[1][1:-3]), '-',lw=2.,color='0.65', semilogx=True, # xlabel=r'$k\,(\mathrm{kpc}^{-1})$', ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1})$', xrange=xrange, yrange=[0.,11.9],zorder=1) line2= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdslowbar[1][1:-3]), 'r-',lw=2., overplot=True,zorder=1) line3= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsbarsmallangle[1][1:-3])*0.9, '-',lw=2.,color='gold', overplot=True,zorder=1) line4= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsbarlargeangle[1][1:-3])*1.1, 'b-',lw=2., overplot=True,zorder=1) line5= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsbarsmallrolr[1][1:-3])*0.9, 'g-',lw=2., overplot=True,zorder=1) line6= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psdsbarlargerolr[1][1:-3]), 'c-',lw=2., overplot=True,zorder=1) pyplot.annotate(r'$\mathrm{Bar\ perturbation\ (rotating}\ m=2\ \mathrm{mode})$', (0.5,1.08),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=20.) l1= pyplot.legend((line1[0],line2[0]), (r'$\mathrm{Fast\ bar\ growth}$', r'$\mathrm{Slow\ bar\ growth}$'), loc='upper right',#bbox_to_anchor=(.91,.375), numpoints=8, prop={'size':16}, frameon=False) l2= pyplot.legend((line3[0],line4[0],line5[0],line6[0]), (r'$\mathrm{Fast}\ \&\ \mathrm{bar\ angle} = 10^\circ$', r'$\mathrm{Fast}\ \&\ \mathrm{bar\ angle} = 40^\circ$', r'$\mathrm{Fast}\ \&\ R_{\mathrm{OLR}} = 0.85\,R_0$', r'$\mathrm{Fast}\ \&\ R_{\mathrm{OLR}} = 0.95\,R_0$'), loc='lower left',#bbox_to_anchor=(.91,.375), numpoints=8, prop={'size':16}, frameon=False) pyplot.gca().add_artist(l1) pyplot.gca().add_artist(l2) elif type.lower() == 'spiral': vlosfid= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-14%s.sav' % _HIVRESSTR) vloslpitch= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-7%s.sav' % _HIVRESSTR) vlosdiffgamma= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_gamma0.3%s.sav' % _HIVRESSTR) vlosdiffomegas= galpy_simulations.vlos('../sim/spiral_rect_alpha-14%s.sav' % _HIVRESSTR) vlosdiffm= galpy_simulations.vlos('../sim/spiral_rect_m4_alpha-14%s.sav' % _HIVRESSTR) vlosdiffm2= galpy_simulations.vlos('../sim/spiral_rect_m4_alpha-14_gamma0.4%s.sav' % _HIVRESSTR) potscale= 0.85 eres= 19 xgrid= numpy.linspace((_RCXMIN-8.)/8.+_RCDX/8./2., (_RCXMAX-8.)/8.-_RCDX/8./2., eres) dx= (xgrid[1]-xgrid[0])*8. psdfid= bovy_psd.psd1d(vlosfid,dx,binsize=0.8) psdlpitch= bovy_psd.psd1d(vloslpitch,dx,binsize=0.8) psddiffgamma= bovy_psd.psd1d(vlosdiffgamma,dx,binsize=0.8) psddiffomegas= bovy_psd.psd1d(vlosdiffomegas,dx,binsize=0.8) psddiffm= bovy_psd.psd1d(vlosdiffm,dx,binsize=0.8) psddiffm2= bovy_psd.psd1d(vlosdiffm2,dx,binsize=0.8) ks= psdfid[0][1:-3] scale= 4.*numpy.pi*220. bovy_plot.bovy_print(fig_width=8.,fig_height=4.5,axes_labelsize=20) line1= bovy_plot.bovy_plot(ks,potscale*scale*numpy.sqrt(psdfid[1][1:-3]), 'k-',lw=2, semilogx=True, # xlabel=r'$k\,(\mathrm{kpc}^{-1})$', ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1})$', xrange=xrange, yrange=[0.,11.9],zorder=1) potscale= 0.25 line2= bovy_plot.bovy_plot(ks,potscale*scale*numpy.sqrt(psdlpitch[1][1:-3]), '-',lw=2.,zorder=1,color='gold', overplot=True) potscale= 0.5 line3= bovy_plot.bovy_plot(ks,potscale*scale*numpy.sqrt(psddiffgamma[1][1:-3]), 'r-',lw=2.,zorder=1, overplot=True) line4= bovy_plot.bovy_plot(ks,4.*scale*numpy.sqrt(psddiffomegas[1][1:-3]), 'b-',lw=2.,zorder=1, overplot=True) line5= bovy_plot.bovy_plot(ks,10./7.*scale*numpy.sqrt(psddiffm[1][1:-3]), 'g-',lw=2.,zorder=1, overplot=True) line6= bovy_plot.bovy_plot(ks,10./6.*scale*numpy.sqrt(psddiffm2[1][1:-3]), 'c-',lw=2.,zorder=1, overplot=True) pyplot.annotate(r'$\mathrm{Spiral\ perturbation}$', (0.5,1.08),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=20.) l1= pyplot.legend((line1[0],line2[0],line3[0], line4[0],line5[0],line6[0]), (r'$\mathrm{Fiducial\ spiral}$', r'$\mathrm{Pitch\ angle} = 16^\circ$', r'$\gamma = 17^\circ$'), loc='upper right',#bbox_to_anchor=(.91,.375), numpoints=8, prop={'size':16}, frameon=False) l2= pyplot.legend((line4[0],line5[0],line6[0]), (r'$\Omega_s = 0.65\,\Omega_0$', r'$\Omega_s = 0.65\,\Omega_0\ \&\ m=4$', r'$\Omega_s = 0.65\,\Omega_0\ \&\ m=4\ \&\ \gamma = 23^\circ$'), loc='lower left',#bbox_to_anchor=(.91,.375), numpoints=8, prop={'size':16}, frameon=False) pyplot.gca().add_artist(l1) pyplot.gca().add_artist(l2) elif type.lower() == 'bird': _nSims= 8 #Read the Bird data birdData= numpy.load('../pecvel/dr12_1_5gyr_8pos.npz') #Get residuals for all simulations dx= _RCDX binsize= .8#.765 scale= 4.*numpy.pi tmp= bovy_psd.psd1d(birdData['dVlos1'],dx,binsize=binsize) #just to get the size ks= tmp[0][1:-3] psds= numpy.zeros((len(tmp[1]),_nSims)) if True: import apogee.tools.read as apread import pixelize_sample data= apread.rcsample() data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx) data= data[indx] #Get residuals dx= _RCDX pix= pixelize_sample.pixelXY(data, xmin=_RCXMIN,xmax=_RCXMAX, ymin=_RCYMIN,ymax=_RCYMAX, dx=dx,dy=dx) resv= pix.plot('VHELIO_AVG',returnz=True,justcalc=True) rc_mask= numpy.ones(resv.shape,dtype='bool') rc_mask[True-numpy.isnan(resv)]= False if _SUBTRACTERRORS: for ii in range(_nSims): sim= ii+1 tmpPsd= bovy_psd.psd1d(birdData['dVlos%i' % sim], dx,binsize=binsize)[1] #Simulations for the noise nnoise= _NNOISE noisepsd= numpy.empty((nnoise,len(tmpPsd))) for jj in range(nnoise): newresv= \ numpy.random.normal(size=birdData['dVlos%i' % sim].shape)\ *birdData['sig_dVlos%i' % sim].reshape((9,9))\ *(True-rc_mask) # *(True-birdData['rc_mask']) noisepsd[jj,:]= bovy_psd.psd1d(newresv,dx,binsize=binsize)[1] psds[:,ii]= tmpPsd-numpy.median(noisepsd,axis=0) #Calculate median PSD and spread around this medPsd= scale*numpy.median(numpy.sqrt(psds),axis=1)[1:-3] flucPsd=\ 1.4826*scale*numpy.median(numpy.fabs(numpy.sqrt(psds)[1:-3] -numpy.tile(medPsd/scale, (psds.shape[1],1)).T),axis=1) bovy_plot.bovy_print(fig_width=8.,fig_height=4.5,axes_labelsize=20) def my_formatter(x, pos): return r'$%g$' % x major_formatter = FuncFormatter(my_formatter) line1= bovy_plot.bovy_plot(ks,medPsd, 'k-',lw=2, semilogx=True, xlabel=r'$k\,(\mathrm{kpc}^{-1})$', ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1})$', xrange=xrange, yrange=[0.,11.9],zorder=1) pyplot.gca().xaxis.set_major_formatter(major_formatter) goodIndx= True-numpy.isnan(flucPsd) pyplot.fill_between(ks[goodIndx],(medPsd-flucPsd)[goodIndx], y2=(medPsd+flucPsd)[goodIndx], color='0.45',zorder=-1) pyplot.annotate(r'$\mathrm{Cosmological\ simulation}$', (0.5,1.08),xycoords='axes fraction', horizontalalignment='center', verticalalignment='top',size=20.) bovy_plot.bovy_text(r'$\mathrm{Median\ and\ range\ from}$'+'\n' +r'$\mathrm{8\ APOGEE\!-\!like\ volumes}$', top_right=True,size=16.) bovy_plot.bovy_plot([0.4,0.65],[7.55,10.],'k-',overplot=True) #Also plot fiducial scale= 4.*numpy.pi*220. bovy_plot.bovy_plot(tks, scale*numpy.sqrt(simpsd1d[1][1:-3]), '-',color='0.65',lw=4.,overplot=True,zorder=0) if not type.lower() == 'bird': nullfmt = NullFormatter() # no labels pyplot.gca().xaxis.set_major_formatter(nullfmt) bovy_plot.bovy_end_print(plotfilename) return None
import numpy import apogee.tools.read as apread _DATA= apread.rcsample() #such that we can re-use it in different tests def test_int64(): #Test that there aren't 64-bit integers for key in _DATA.dtype.names: assert not numpy.issubdtype(_DATA[key].dtype,numpy.int64), "Tag '%s' in the RC catalog is a 64-bit signed integer that might give problems for some readers" % key return None
def bovy_metallicity_gradient(plotfilename,savefilename,largewave=False): # First read the RC catalog and cut it to stars near the plane data= apread.rcsample() if _HIZ: indx= (numpy.fabs(data['RC_GALZ']) > 0.6)*(data['METALS'] > -1000.) else: indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) data= data[indx] # Now go through bins in R Rmin, Rmax, dR= 5.5, 13., 0.1 Rs= numpy.arange(Rmin+dR/2.,Rmax+dR/2.,dR) nR= len(Rs) # Read one spectrum to learn the size of the array spec, hdr= apread.aspcapStar(4424,'2M00025587+5849278',ext=1) if os.path.exists(savefilename): # Reload previously calculated median spectrum savefile= open(savefilename,'rb') median_spec= pickle.load(savefile) savefile.close() else: median_spec= numpy.zeros((len(spec),nR)) # Now run through all the spectra and get the median tot= 0 for ii in range(nR): indx= (data['RC_GALR'] >= Rs[ii]-dR/2.)\ *(data['RC_GALR'] < Rs[ii]+dR/2.) tot+= numpy.sum(indx) print numpy.sum(indx), tot allspec= numpy.empty((len(spec),numpy.sum(indx))) for jj in range(numpy.sum(indx)): specdata= \ apread.aspcapStar(data['LOCATION_ID'][indx][jj], data['APOGEE_ID'][indx][jj], ext=1,header=False) specerr= \ apread.aspcapStar(data['LOCATION_ID'][indx][jj], data['APOGEE_ID'][indx][jj], ext=2,header=False) allspec[:,jj]= specdata allspec[specerr > 1.,jj]= numpy.nan allspec[specerr == 0.,jj]= numpy.nan for jj in range(len(spec)): if _PLOTMAD: median_spec[jj,ii]= \ numpy.median(numpy.fabs(allspec[jj,True-numpy.isnan(allspec[jj,:])]-numpy.median(allspec[jj,True-numpy.isnan(allspec[jj,:])]))) else: median_spec[jj,ii]= \ numpy.median(allspec[jj, True-numpy.isnan(allspec[jj,:])]) save_pickles(savefilename,median_spec) # Wavelengths wave= 10.**(numpy.arange(hdr['CRVAL1'], hdr['CRVAL1']+len(spec)*hdr['CDELT1'], hdr['CDELT1'])) # Normalization, first calculate the spectrum near Ro absmax= 0.98 absindx= (median_spec > absmax)*\ numpy.tile(( (wave < 15929.)+(wave > 15929.5) ),(nR,1)).T median_spec[absindx]= absmax #focus on real absorption lines, except for V rospec= numpy.zeros(len(spec)) roindx= numpy.argmin(numpy.fabs(Rs-8.)) for jj in range(len(spec)): rospec[jj]= numpy.median(median_spec[jj,roindx-3:roindx+4]) if not _PLOTMAD: # Normalization by spectrum at Ro roindx= numpy.argmin(numpy.fabs(Rs-8.)) for jj in range(nR): # Normalize by the solar radius median_spec[:,jj]/= rospec median_spec-= 1. vmin=-0.035 vmax=0.035 vmin=-0.04 vmax=0.04 # Now plot if False: startindx, endindx= 3652, 4100#3915 if largewave: startindx, endindx= 7000,7600#7375, 7889 else: startindx, endindx= 2500, 3100 # Make N separate plots showing different wavelength regions bovy_plot.bovy_print(fig_width=8.4,fig_height=3., axes_labelsize=10,text_fontsize=9,legend_fontsize=9, xtick_labelsize=8,ytick_labelsize=8) startindxs= [322,1790,2707,3852,4738,5820,7187] #DIB is at 818 endindxs= [590,1940,2857,4021,5068,5955,7400] nregions= len(startindxs) # Calculate the width of the plot dx= numpy.array([endindxs[ii]-startindxs[ii] for ii in range(nregions)], dtype='float') specdx= numpy.sum(dx) # for later dx/= numpy.sum(dx) totdx= 0.85 skipdx= 0.015 dx*= (totdx-(nregions-1)*skipdx) for ii in range(nregions): # Setup the axes if ii == 0: left, bottom, width, height= 0.1, 0.1, dx[ii],0.8 else: left, bottom, width, height= 0.1+numpy.cumsum(dx)[ii-1]+skipdx*ii,\ 0.1, dx[ii], 0.8 thisax= pyplot.axes([left,bottom,width,height]) fig= pyplot.gcf() fig.sca(thisax) startindx, endindx= startindxs[ii], endindxs[ii] aspect= (hdr['CRVAL1']+(endindx-0.5)*hdr['CDELT1']-hdr['CRVAL1']-(startindx-0.5)*hdr['CDELT1'])\ /(Rs[-1]+dR/2.-Rs[0]+dR/2.) aspect/= dx[ii]*5. yrange= [Rs[0]-dR/2.,Rs[-1]+dR/2.] xrange=[hdr['CRVAL1']+(startindx-0.5)*hdr['CDELT1']-numpy.log10(_LAMBDANORM),\ hdr['CRVAL1']+(endindx-0.5)*hdr['CDELT1']-numpy.log10(_LAMBDANORM)] extent= [xrange[0],xrange[1],yrange[0],yrange[1]] pyplot.imshow(-median_spec[startindx:endindx,:].T, origin='lower',cmap='coolwarm', vmin=vmin,vmax=vmax, extent=extent, interpolation='nearest', #interpolation='bicubic', aspect=aspect) pyplot.axis(extent) #pyplot.xticks(rotation=-45.) pyplot.xlim(xrange[0],xrange[1]) pyplot.ylim(yrange[0],yrange[1]) thisax.xaxis.set_major_locator(ticker.MultipleLocator(0.001)) bovy_plot._add_ticks() if ii > 0: nullfmt = NullFormatter() # no labels thisax.yaxis.set_major_formatter(nullfmt) else: pyplot.ylabel(r'$R\,(\mathrm{kpc})$') # Remove spines between different wavelength regions if ii == 0: thisax.spines['right'].set_visible(False) thisax.tick_params(right=False,which='both') elif ii == (nregions-1): thisax.spines['left'].set_visible(False) thisax.tick_params(labelleft='off') thisax.tick_params(left=False,which='both') else: thisax.spines['left'].set_visible(False) thisax.spines['right'].set_visible(False) thisax.tick_params(labelleft='off') thisax.tick_params(left=False,which='both') thisax.tick_params(right=False,which='both') # Plot cut-out markers d = .015 # how big to make the diagonal lines in axes coordinates kwargs = dict(transform=thisax.transAxes, color='k', clip_on=False) slope= 1./(dx[ii]+0.2*skipdx)/3. if ii == 0: thisax.plot((1-slope*d,1+slope*d),(-d,+d), **kwargs) thisax.plot((1-slope*d,1+slope*d),(1-d,1+d), **kwargs) elif ii == (nregions-1): thisax.plot((-slope*d,+slope*d),(-d,+d), **kwargs) thisax.plot((-slope*d,+slope*d),(1-d,1+d), **kwargs) else: thisax.plot((1-slope*d,1+slope*d),(-d,+d), **kwargs) thisax.plot((1-slope*d,1+slope*d),(1-d,1+d), **kwargs) thisax.plot((-slope*d,+slope*d),(-d,+d), **kwargs) thisax.plot((-slope*d,+slope*d),(1-d,1+d), **kwargs) # Draw solar line if ii == (nregions-1): xend= hdr['CRVAL1']+(endindx-0.5)*hdr['CDELT1']-numpy.log10(_LAMBDANORM) # Total wavelength span, incl. skipdx parts totaldx= hdr['CDELT1']*specdx*\ (1.+(nregions-1)*skipdx/(totdx-(nregions-1)*skipdx)) thisax.plot((xend-totaldx,xend),(8.,8.), color='k',ls='--',lw=1.5,marker='None',clip_on=False) # Label the lines _label_all_lines(wave[startindx],wave[endindx]) # Add the x-axis label thisax= pyplot.axes([0.1,0.175,0.85,0.65]) pyplot.gcf().sca(thisax) thisax.spines['left'].set_visible(False) thisax.spines['right'].set_visible(False) thisax.spines['bottom'].set_visible(False) thisax.spines['top'].set_visible(False) thisax.tick_params(labelleft='off') thisax.tick_params(left=False,which='both') thisax.tick_params(right=False,which='both') thisax.tick_params(labelbottom='off') thisax.tick_params(bottom=False,which='both') thisax.tick_params(top=False,which='both') pyplot.xlabel(r'$\log \big(\lambda / 15,000 \AA\big)$') thisax.set_zorder(-1) bovy_plot.bovy_end_print(plotfilename,dpi=600) return None
def plot_2dkinematics(basesavefilename,datafilename=None): #Plot 2D los field #First read the sample if not datafilename is None: data= fitsio.read(datafilename) else: data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx) data= data[indx] pix= pixelize_sample.pixelXY(data) vmin, vmax= -75., 75. bovy_plot.bovy_print() pix.plot('VHELIO_AVG', zlabel=r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax) bovy_plot.bovy_text(r'$\mathrm{typical\ uncertainty\!:}\ 3\,\mathrm{km\,s}^{-1}$', bottom_left=True,size=18.) bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',top_right=True,size=18.) bovy_plot.bovy_end_print(basesavefilename+'_XY.'+_EXT) #R,phi pix= pixelize_sample.pixelXY(data,rphi=True, ymin=-22.5,ymax=37.5, # dx=0.3,dy=2.) # dx=3.,dy=20.) dx=1.,dy=5.) bovy_plot.bovy_print() pix.plot('VHELIO_AVG', zlabel=r'$\mathrm{median}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax) #bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',bottom_left=True,size=18.) bovy_plot.bovy_end_print(basesavefilename+'_RPHI.'+_EXT) #Plot the dispersion / sqrt(n) pix= pixelize_sample.pixelXY(data, dx=1.,dy=1.) bovy_plot.bovy_print() pix.plot('VHELIO_AVG', func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)), zlabel=r'$\delta\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$', vmin=0.,vmax=10.) #bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',bottom_left=True,size=18.) bovy_plot.bovy_end_print(basesavefilename+'_RPHI_vlosunc.'+_EXT) #Plot the dispersion bovy_plot.bovy_print() pix.plot('VHELIO_AVG', func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x))), zlabel=r'$\mathrm{MAD}\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$', vmin=0.,vmax=40.) #bovy_plot.bovy_text(r'$|Z| < 250\,\mathrm{pc}$',bottom_left=True,size=18.) bovy_plot.bovy_end_print(basesavefilename+'_RPHI_vlosdisp.'+_EXT) #Now plot the los velocity corrected for the Solar motion #XY vmin, vmax= -250., 250. bovy_plot.bovy_print() resv= pix.plot(lambda x: vlosgal(x), zlabel=r'$\mathrm{median}\ V_{\mathrm{los,rot}}\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax,returnz=True) bovy_plot.bovy_end_print(basesavefilename+'_Vrot_XY.'+_EXT) pix= pixelize_sample.pixelXY(data,rphi=True, ymin=-22.5,ymax=37.5, dx=1.,dy=5.) #R,phi vmin, vmax= -250., 250. bovy_plot.bovy_print() resv= pix.plot(lambda x: vlosgal(x), zlabel=r'$\mathrm{median}\ V_{\mathrm{los,rot}}\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax,returnz=True) #Plot tangent point rs= numpy.linspace(6.,8.,101) bovy_plot.bovy_plot(rs,numpy.arccos(rs/8.)*180./numpy.pi,'k--',lw=2., overplot=True) bovy_plot.bovy_plot(rs,-numpy.arccos(rs/8.)*180./numpy.pi,'k--',lw=2., overplot=True) bovy_plot.bovy_end_print(basesavefilename+'_Vrot_RPHI.'+_EXT) #Now plot the residuals wrt the Bovy et al. (2012) disk model #R,phi vmin, vmax= -20., 20. bovy_plot.bovy_print() resv= pix.plot(lambda x: dvlosgal(x,beta=0.,vc=220.), zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax,returnz=True) medindx= True-numpy.isnan(resv) meanresv= numpy.mean(resv[medindx]) sigresv= numpy.std(resv[medindx]) bovy_plot.bovy_text(r'$\mathrm{Residual} = %.1f \pm %.1f / %i\,\mathrm{km\,s}^{-1}$' % (meanresv,sigresv,round(numpy.sqrt(numpy.sum(medindx)))), top_left=True,size=16.) bovy_plot.bovy_end_print(basesavefilename+'_dVBovy12_RPHI.'+_EXT) #XY pixXY= pixelize_sample.pixelXY(data, xmin=5.,xmax=13, ymin=-3.,ymax=4., dx=1.,dy=1.) vmin, vmax= -20., 20. bovy_plot.bovy_print() pixXY.plot(lambda x: dvlosgal(x,beta=0.,vc=220.), zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax,returnz=False) medindx= True-numpy.isnan(resv) meanresv= numpy.mean(resv[medindx]) sigresv= numpy.std(resv[medindx]) bovy_plot.bovy_text(r'$\mathrm{Residual} = %.1f \pm %.1f / %i\,\mathrm{km\,s}^{-1}$' % (meanresv,sigresv,round(numpy.sqrt(numpy.sum(medindx)))), top_left=True,size=16.) bovy_plot.bovy_end_print(basesavefilename+'_dVBovy12_XY.'+_EXT) #Plot a histogram of the residuals bovy_plot.bovy_print() bovy_plot.bovy_hist(resv[medindx],color='k',bins=11,xrange=[-25.,25.], yrange=[0.,15.], histtype='step',normed=False, xlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$') xs= numpy.linspace(-25.,25.,1001) bovy_plot.bovy_plot(xs, 50./11.*numpy.sum(medindx)/numpy.sqrt(2.*numpy.pi)/sigresv\ *numpy.exp(-0.5*(xs-meanresv)**2./sigresv**2.), 'k-',lw=2,overplot=True) bovy_plot.bovy_end_print(basesavefilename+'_dVBovy12_hist.'+_EXT) #Now plot the residuals wrt the Bovy et al. (2012) disk model w/ Vc-240 and standard solar motion #R,phi vmin, vmax= -20., 20. bovy_plot.bovy_print() resv= pix.plot(lambda x: dvlosgal(x,beta=0.,vc=240.,vtsun=252.), zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax,returnz=True) medindx= True-numpy.isnan(resv) #bovy_plot.bovy_text(r'$\mathrm{Residual} = %.1f \pm %.1f / %i\,\mathrm{km\,s}^{-1}$' % (numpy.median(resv[medindx]),numpy.median(numpy.fabs(resv[medindx]-numpy.median(resv[medindx])))*1.4826,round(numpy.sqrt(numpy.sum(medindx)))), # top_left=True,size=16.) bovy_plot.bovy_end_print(basesavefilename+'_dVBovy12Vc240VsSBD_RPHI.'+_EXT) #Now plot the residuals wrt the Bovy et al. (2012) disk model w/ Vc-220 and standard solar motion #R,phi vmin, vmax= -20., 20. bovy_plot.bovy_print() resv= pix.plot(lambda x: dvlosgal(x,beta=0.,vc=220.,vtsun=232.), zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax,returnz=True) medindx= True-numpy.isnan(resv) # bovy_plot.bovy_text(r'$\mathrm{Residual} = %.1f \pm %.1f / %i\,\mathrm{km\,s}^{-1}$' % (numpy.median(resv[medindx]),numpy.median(numpy.fabs(resv[medindx]-numpy.median(resv[medindx])))*1.4826,round(numpy.sqrt(numpy.sum(medindx)))), # top_left=True,size=16.) bovy_plot.bovy_end_print(basesavefilename+'_dVBovy12Vc220VsSBD_RPHI.'+_EXT) #FFT dx= 1. pix= pixelize_sample.pixelXY(data, xmin=5.,xmax=13, ymin=-3.,ymax=4., dx=dx,dy=dx) resv= pix.plot(lambda x: dvlosgal(x), zlabel=r'$\mathrm{median}\ \Delta V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$', vmin=vmin,vmax=vmax,returnz=True) resvunc= pix.plot('VHELIO_AVG', func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)), zlabel=r'$\delta\ V_{\mathrm{los}}\,(\mathrm{km\,s}^{-1})$', vmin=0.,vmax=10.,returnz=True) import psds binsize= 1.5 psd2d= psds.power_spectrum(resv, binsize=binsize,wavenumber=True) #Simulate the noise newresv= numpy.random.normal(size=resv.shape)*resvunc newresvuni= numpy.random.normal(size=resv.shape)*5. psd2dnoise= psds.power_spectrum(newresv, binsize=binsize,wavenumber=True) psd2duni= psds.power_spectrum(newresvuni, binsize=binsize,wavenumber=True) bovy_plot.bovy_print() ks= psd2d[0][1:]/dx bovy_plot.bovy_plot(ks,numpy.sqrt(psd2d[1]/numpy.prod(resv.shape)/16.\ /(ks[1]-ks[0]))[1:],'ko-', xlabel=r'$k\,(\mathrm{kpc}^{-1})$', ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1}\,\mathrm{kpc}^{1/2})$', xrange=[0.,1./dx/2.], yrange=[0.,10.], semilogy=False) bovy_plot.bovy_plot(ks,numpy.sqrt(psd2dnoise[1]/numpy.prod(resv.shape)/16.\ /(ks[1]-ks[0]))[1:], '-',color='0.5',overplot=True,lw=2.) bovy_plot.bovy_plot(ks,numpy.sqrt(psd2duni[1]/numpy.prod(resv.shape)/16.\ /(ks[1]-ks[0]))[1:], '-',color='b',overplot=True,lw=2.) bovy_plot.bovy_end_print(basesavefilename+'_FFTPSD.'+_EXT) return None
def plot_distancedist(basesavefilename): #First read the sample data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Histogram bovy_plot.bovy_print(fig_width=6.) bovy_plot.bovy_hist(data['RC_DIST'], histtype='step', color='k', lw=1.5, bins=51, xrange=[0.,10.], xlabel=r'$\mathrm{distance}\,(\mathrm{kpc})$', ylabel=r'$\mathrm{Number\ of\ stars}$',zorder=10) ax= pyplot.gca() ax2= ax.twinx() pyplot.sca(ax2) bovy_plot.bovy_plot(sorted(data['RC_DIST']), numpy.linspace(1./len(data),1.,len(data)), 'k-', overplot=True) ax2.set_xlim(0.,10.) ax2.set_ylim(0.,1.) bovy_plot._add_ticks() ax2.set_ylabel(r'$\mathrm{cumulative\ distribution}$') bovy_plot.bovy_end_print(basesavefilename+'_hist.'+_EXT) #RZ bovy_plot.bovy_print() bovy_plot.bovy_plot(data['RC_GALR'],data['RC_GALZ'], 'k.',ms=2., xrange=[0.,16.], yrange=[-3.,3.], xlabel=r'$R\,(\mathrm{kpc})$', ylabel=r'$Z\,(\mathrm{kpc})$', onedhists=True) xarr, dx=1.5, -1. from matplotlib.patches import FancyArrowPatch _legendsize= 16 arr= FancyArrowPatch(posA=(xarr+0.05,0.), posB=(xarr+dx*10./8.,0.), arrowstyle='->', connectionstyle='arc3,rad=%4.2f' % (0.), shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, mutation_aspect=None,fc='k') ax = pyplot.gca() ax.add_patch(arr) bovy_plot.bovy_text(xarr+7.*dx/8.,-0.45,r'$\mathrm{GC}$', size=_legendsize) arr= FancyArrowPatch(posA=(1.5,-0.05), posB=(1.5,.75), arrowstyle='->', connectionstyle='arc3,rad=%4.2f' % (0.), shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, mutation_aspect=None,fc='k') ax = pyplot.gca() ax.add_patch(arr) bovy_plot.bovy_text(1.59,0.2,r'$\mathrm{NGP}$', size=_legendsize) bovy_plot.bovy_end_print(basesavefilename+'_RZ.'+_EXT) #XY bovy_plot.bovy_print() bovy_plot.bovy_plot(data['RC_GALR']*numpy.cos(data['RC_GALPHI']), data['RC_GALR']*numpy.sin(data['RC_GALPHI']), 'k.', xrange=[0.,16.], yrange=[5.,-5.], xlabel=r'$X_{\mathrm{GC}}\,(\mathrm{kpc})$', ylabel=r'$Y_{\mathrm{GC}}\,(\mathrm{kpc})$', onedhists=True,ms=2.) xarr, dx= 2.2, -2. arr= FancyArrowPatch(posA=(xarr,0.), posB=(xarr+dx,0.), arrowstyle='->', connectionstyle='arc3,rad=%4.2f' % (0.), shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, mutation_aspect=None,fc='k') ax = pyplot.gca() ax.add_patch(arr) bovy_plot.bovy_text(xarr+7.*dx/8.,-0.25,r'$\mathrm{GC}$', size=_legendsize) xcen, ycen, dr, t= -2., 0., 4., 14.*numpy.pi/180. arr= FancyArrowPatch(posA=(xcen+dr*numpy.cos(t), ycen+dr*numpy.sin(t)), posB=(xcen+dr*numpy.cos(-t), ycen+dr*numpy.sin(-t)), arrowstyle='<-', connectionstyle='arc3,rad=%4.2f' % (2.*t), shrinkA=2.0, shrinkB=2.0, mutation_scale=20.0, mutation_aspect=None,fc='k') ax.add_patch(arr) bovy_plot.bovy_end_print(basesavefilename+'_XY.'+_EXT)
def plot_fehafe(basefilename): #First read the sample data= apread.rcsample() data= data[data['SNR'] >= 70.] if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #R and z ranges to plot Rmins= [5.,7.,9.] Rmaxs= [7.,9.,11.] zmins= [0.,0.5,1.] zmaxs= [0.5,1.,2.] nRbins= len(Rmins) nzbins= len(zmins) for ii in range(nRbins): for jj in range(nzbins): #Cut data to relevant range tindx= (data['RC_GALR'] > Rmins[ii])\ *(data['RC_GALR'] <= Rmaxs[ii])\ *(numpy.fabs(data['RC_GALZ']) > zmins[jj])\ *(numpy.fabs(data['RC_GALZ']) <= zmaxs[jj]) tdata= data[tindx] bovy_plot.bovy_print() if (_SCATTERPLOT or len(tdata) > 1500) and not _ADDBOVYRIX: bovy_plot.scatterplot(tdata['METALS'], tdata['ALPHAFE'], 'k.', levels=[0.68,.90], #special.erf(numpy.arange(1,3)/numpy.sqrt(2.)), xrange=[-1.2,0.7], yrange=[-0.12,0.42], xlabel=r'$[\mathrm{Fe/H}]$', ylabel=r'$[\alpha/\mathrm{H}]$', onedhists=True,bins=31,onedhistsbins=21) else: axScatter,axHistx, axHisty=\ bovy_plot.bovy_plot(tdata['METALS'], tdata['ALPHAFE'], 'k.', xrange=[-1.2,0.7], yrange=[-0.12,0.42], xlabel=r'$[\mathrm{Fe/H}]$', ylabel=r'$[\alpha/\mathrm{H}]$', onedhists=True,bins=21) if _ADDBOVYRIX: add_bovy_rix(axScatter,Rmins[ii],Rmaxs[ii],zmins[jj],zmaxs[jj]) if not _NOLINE: #Overplot ridge line bovy_plot.bovy_plot([-0.8,0.3],[ridge1(-0.8),ridge1(0.3)], '-',lw=2.,color='y',overplot=True) bovy_plot.bovy_text(r'$%i < R / \mathrm{kpc} \leq %i$' % (Rmins[ii],Rmaxs[ii]) +'\n'+r'$%.1f < |z| / \mathrm{kpc} \leq %.1f$' % (zmins[jj],zmaxs[jj]), top_left=True,size=16.) bovy_plot.bovy_end_print(basefilename+'_%iR%i_%.1fz%.1f.' % (Rmins[ii],Rmaxs[ii],zmins[jj],zmaxs[jj])+_EXT) #Plot z bins only zmins= [0.,0.5,1.,2.] zmaxs= [0.5,1.,2.,4.] nzbins= len(zmins) for jj in range(nzbins): #Cut data to relevant range tindx= (data['RC_GALR'] > 4.)\ *(data['RC_GALR'] <= 9.)\ *(numpy.fabs(data['RC_GALZ']) > zmins[jj])\ *(numpy.fabs(data['RC_GALZ']) <= zmaxs[jj]) tdata= data[tindx] bovy_plot.bovy_print() if (_SCATTERPLOT or len(tdata) > 1500) and not _ADDBOVYRIX: bovy_plot.scatterplot(tdata['METALS'], tdata['ALPHAFE'], 'k.', levels=[0.68,.90], xrange=[-1.2,0.7], yrange=[-0.12,0.42], xlabel=r'$[\mathrm{Fe/H}]$', ylabel=r'$[\alpha/\mathrm{H}]$', onedhists=True,bins=31,onedhistsbins=31) else: axScatter,axHistx, axHisty=\ bovy_plot.bovy_plot(tdata['METALS'], tdata['ALPHAFE'], 'k.', xrange=[-1.2,0.7], yrange=[-0.12,0.42], xlabel=r'$[\mathrm{Fe/H}]$', ylabel=r'$[\alpha/\mathrm{H}]$', onedhists=True,bins=21) if _ADDBOVYRIX: add_bovy_rix(axScatter,4.,9.,zmins[jj],zmaxs[jj]) #Overplot ridge line bovy_plot.bovy_plot([-0.8,0.3],[ridge1(-0.8),ridge1(0.3)], '-',lw=2.,color='y',overplot=True) bovy_plot.bovy_text(r'$%.1f < |z| / \mathrm{kpc} \leq %.1f$' % (zmins[jj],zmaxs[jj]), top_left=True,size=16.) bovy_plot.bovy_end_print(basefilename+'_%.1fz%.1f.' % (zmins[jj],zmaxs[jj])+_EXT) #Plot scatter in the high-alpha sequence #Histograms in 3 R bins bovy_plot.bovy_print(fig_width=7.) overplot= False colors= ['y','k','r'] labelposx= 0.235 labelposy= [13.,11.,9.] for ii in range(nRbins): tindx= (data['RC_GALR'] > Rmins[ii])\ *(data['RC_GALR'] <= Rmaxs[ii])\ *(numpy.fabs(data['RC_GALZ']) <= 3.) tdata= data[tindx] hindx= determine_highalpha(tdata) tdata= tdata[hindx] bovy_plot.bovy_hist(tdata['ALPHAFE']-ridge1(tdata['METALS']), color=colors[ii],histtype='step', bins=28,range=[-0.275,0.25],yrange=[0.,15.], weights=numpy.ones(len(tdata)), xlabel=r'$\delta[\alpha\mathrm{/Fe}]$', overplot=overplot,normed=True) dafe= tdata['ALPHAFE']-ridge1(tdata['METALS']) dafe= dafe[(numpy.fabs(tdata['RC_GALZ']) > .5)] txa, txm, txc= run_xd(dafe) print txm.flatten(), numpy.sqrt(txc.flatten()), txa[0]*len(dafe) bovy_plot.bovy_plot([txm[0,0],txm[0,0]],[0.,200.],'--',lw=2., color=colors[ii],overplot=True) bovy_plot.bovy_text(labelposx,labelposy[ii], r'$%i < R \leq %i: \sigma = %.3f$' % (Rmins[ii],Rmaxs[ii],numpy.sqrt(txc[0,0,0])), size=16.,color=colors[ii],ha='right') overplot= True bovy_plot.bovy_end_print(basefilename+'_afefehhist.%s' % _EXT) #High SN bovy_plot.bovy_print(fig_width=7.) overplot= False for ii in range(nRbins): tindx= (data['RC_GALR'] > Rmins[ii])\ *(data['RC_GALR'] <= Rmaxs[ii])\ *(numpy.fabs(data['RC_GALZ']) <= 3.)\ *(data['SNR'] >= 150.) tdata= data[tindx] hindx= determine_highalpha(tdata) tdata= tdata[hindx] bovy_plot.bovy_hist(tdata['ALPHAFE']-ridge1(tdata['METALS']), color=colors[ii],histtype='step', bins=19,range=[-0.275,0.15],yrange=[0.,19.5], weights=numpy.ones(len(tdata)), xlabel=r'$\delta[\alpha\mathrm{/Fe}]$', normed=True, overplot=overplot) dafe= tdata['ALPHAFE']-ridge1(tdata['METALS']) dafe= dafe[(numpy.fabs(tdata['RC_GALZ']) > .5)] txa, txm, txc= run_xd(dafe) print txm.flatten(), numpy.sqrt(txc.flatten()) bovy_plot.bovy_plot([txm[0,0],txm[0,0]],[0.,200.],'--',lw=2., color=colors[ii],overplot=True) overplot= True bovy_plot.bovy_end_print(basefilename+'_afefehhist_highsn.%s' % _EXT) return None
def plot_psd(plotfilename): data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] #Cut indx= (numpy.fabs(data['RC_GALZ']) < 0.25)*(data['METALS'] > -1000.) print "Using %i stars for low-Z 2D kinematics analysis" % numpy.sum(indx) data= data[indx] #Get residuals dx= _RCDX binsize= .8#.765 pix= pixelize_sample.pixelXY(data, xmin=_RCXMIN,xmax=_RCXMAX, ymin=_RCYMIN,ymax=_RCYMAX, dx=dx,dy=dx) resv= pix.plot(lambda x: dvlosgal(x,vtsun=220.+22.5), returnz=True,justcalc=True) resvunc= pix.plot('VHELIO_AVG', func=lambda x: 1.4826*numpy.median(numpy.fabs(x-numpy.median(x)))/numpy.sqrt(len(x)), returnz=True,justcalc=True) psd1d= bovy_psd.psd1d(resv,dx,binsize=binsize) print psd1d #Simulations for constant 3.25 km/s nnoise= _NNOISE noisepsd= numpy.empty((nnoise,len(psd1d[0])-4)) for ii in range(nnoise): newresv= numpy.random.normal(size=resv.shape)*3.25 noisepsd[ii,:]= bovy_psd.psd1d(newresv,dx,binsize=binsize)[1][1:-3] scale= 4.*numpy.pi#3.25/numpy.median(numpy.sqrt(noisepsd)) print scale #Simulations for the actual noise nnoise= _NNOISE noisepsd= numpy.empty((nnoise,len(psd1d[0])-4)) for ii in range(nnoise): newresv= numpy.random.normal(size=resv.shape)*resvunc noisepsd[ii,:]= bovy_psd.psd1d(newresv,dx,binsize=binsize)[1][1:-3] ks= psd1d[0][1:-3] if _ADDGCS: xrange=[.03,110.] else: xrange= [0.,1.] yrange= [0.,11.9] if _PROPOSAL: bovy_plot.bovy_print(fig_width=7.5,fig_height=3.) else: bovy_plot.bovy_print(fig_width=7.5,fig_height=4.5) apop= bovy_plot.bovy_plot(ks,scale*numpy.sqrt(psd1d[1][1:-3] -_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)), 'ko',lw=2., zorder=12, xlabel=r'$k\,(\mathrm{kpc}^{-1})$', ylabel=r'$\sqrt{P_k}\,(\mathrm{km\,s}^{-1})$', semilogx=_ADDGCS, xrange=xrange,yrange=yrange) if _DUMP2FILE: with open('bovy-apogee-psd.dat','w') as csvfile: writer= csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) csvfile.write('#APOGEE\n') for ii in range(len(ks)): writer.writerow([ks[ii], (scale*numpy.sqrt(psd1d[1][1:-3]-_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)))[ii], (scale*0.5*(psd1d[2][1:-3]**2.+_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)**2.)**0.5/numpy.sqrt(psd1d[1][1:-3]))[ii]]) if _PROPOSAL: pyplot.gcf().subplots_adjust(bottom=0.15) pyplot.errorbar(ks,scale*numpy.sqrt(psd1d[1][1:-3]-_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)), yerr=scale*0.5*(psd1d[2][1:-3]**2. +_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)**2.)**0.5/numpy.sqrt(psd1d[1][1:-3]), marker='None',ls='none',color='k') if _PLOTBAND: # bovy_plot.bovy_plot(ks, # scale*numpy.median(numpy.sqrt(noisepsd),axis=0), # '--',lw=2.,zorder=10, # color='0.85',overplot=True) # bovy_plot.bovy_plot(ks, # scale*numpy.sqrt(numpy.sort(noisepsd # -_SUBTRACTERRORS*numpy.median(noisepsd,axis=0),axis=0)[int(numpy.floor(0.99*_NNOISE)),:]), # zorder=1,ls='--',overplot=True, # color='0.65') pyplot.fill_between(ks, scale*numpy.sqrt(numpy.sort(noisepsd -_SUBTRACTERRORS*numpy.median(noisepsd,axis=0),axis=0)[int(numpy.floor(_SIGNIF*_NNOISE)),:]), zorder=0, color='0.65') #Add a simple model of a spiral potential if _ADDSIMPLESPIRAL: if False: alpha= -12.5 spvlos= simulate_vlos_spiral(alpha=alpha, gamma=1.2, xmin=_RCXMIN,xmax=_RCXMAX, ymin=_RCYMIN,ymax=_RCYMAX, dx=0.01) potscale= 1.35*1.2 print numpy.arctan(2./alpha)/numpy.pi*180., numpy.sqrt(0.035/numpy.fabs(alpha)/2.)*potscale*220., numpy.sqrt(0.035/numpy.fabs(alpha))*potscale*220. simpsd1d= bovy_psd.psd1d(spvlos*220.*potscale,0.01,binsize=binsize) tks= simpsd1d[0][1:-3] bovy_plot.bovy_plot(tks, scale*numpy.sqrt(simpsd1d[1][1:-3]), 'k--',lw=2.,overplot=True) #A better simulation # spvlos= galpy_simulations.vlos('../sim/spiral_rect_omegas0.33_alpha-14.sav') spvlos= galpy_simulations.vlos('../sim/bar_rect_alpha0.015_hivres.sav') potscale= 1. simpsd1d= bovy_psd.psd1d(spvlos*220.*potscale,0.33333333,binsize=binsize) tks= simpsd1d[0][1:-3] # alpha=-14. # print numpy.arctan(2./-14.)/numpy.pi*180., numpy.sqrt(0.075/numpy.fabs(alpha)/2.)*potscale*220., numpy.sqrt(0.075/numpy.fabs(alpha))*potscale*220. line1= bovy_plot.bovy_plot(tks, scale*numpy.sqrt(simpsd1d[1][1:-3]), 'k--',lw=2.,overplot=True) if _DUMP2FILE: with open('bovy-bar-psd.dat','w') as csvfile: writer= csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL) for ii in range(len(ks)): writer.writerow([tks[ii],(scale*numpy.sqrt(simpsd1d[1][1:-3]))[ii]]) #bovy_plot.bovy_plot(tks[tks > 0.7], # scale*numpy.sqrt(simpsd1d[1][1:-3][tks > 0.7]+4./scale**2.*(1.-numpy.tanh(-(tks[tks > 0.7]-0.9)/0.1))/2.), # 'k-.',lw=2.,overplot=True) #line2= bovy_plot.bovy_plot(tks, # scale*numpy.sqrt(simpsd1d[1][1:-3]+4./scale**2.), # 'k-.',lw=2.,overplot=True,dashes=(10,5,3,5)) l1= pyplot.legend((line1[0],), # (r'$\mathrm{Spiral}:\ \delta \phi_{\mathrm{rms}} = (10\,\mathrm{km\,s}^{-1})^2,$'+'\n'+r'$\mathrm{pitch\ angle} = 8^\circ$'+'\n'+r'$\mathrm{Sun\ near\ 2\!:\!1\ Lindblad\ resonance}$',), (r'$\mathrm{Bar}:\ F_{R,\mathrm{bar}} / F_{R,\mathrm{axi}} = 1.5\%,$'+'\n'+r'$\mathrm{angle} = 25^\circ,$'+'\n'+r'$\mathrm{Sun\ near\ 2\!:\!1\ Lindblad\ resonance}$',), loc='upper right',#bbox_to_anchor=(.91,.375), numpoints=8, prop={'size':14}, frameon=False) #Add the lopsided and ellipticity constraints from Rix/Zaritsky if _ADDRIX: pyplot.errorbar([1./16.],[5.6], yerr=[5.6/2.], marker='d',color='0.6', mew=1.5,mfc='none',mec='0.6') pyplot.errorbar([1./8./numpy.sqrt(2.)],[6.4], yerr=numpy.reshape(numpy.array([6.4/0.045*0.02,6.4/0.045*0.03]),(2,1)), marker='d',color='0.6',mec='0.6', mew=1.5,mfc='none') if _ADDGCS: ks_gcs, psd_gcs, e_psd_gcs, gcsp= plot_psd_gcs() if _ADDRAVE: ks_rave, psd_rave, e_psd_rave, ravep= plot_psd_rave() if _ADDRED: plot_psd_red() l2= pyplot.legend((apop[0],ravep[0],gcsp[0]), (r'$\mathrm{APOGEE}$', r'$\mathrm{RAVE}$', r'$\mathrm{GCS}$'), loc='upper right',bbox_to_anchor=(.95,.750), numpoints=1, prop={'size':14}, frameon=False) pyplot.gca().add_artist(l1) pyplot.gca().add_artist(l2) #Plot an estimate of the noise, based on looking at the bands nks= numpy.linspace(2.,120.,2) if not 'mba23' in socket.gethostname(): pyplot.fill_between(nks,[2.,2.],hatch='/',color='k',facecolor=(0,0,0,0), lw=0.) # edgecolor=(0,0,0,0)) pyplot.plot(nks,[2.,2.],color='k',lw=1.5) nks= numpy.linspace(0.17,2.,2) def linsp(x): return .8/(numpy.log(0.17)-numpy.log(2.))*(numpy.log(x)-numpy.log(0.17))+2.8 if not 'mba23' in socket.gethostname(): pyplot.fill_between(nks,linsp(nks),hatch='/',color='k',facecolor=(0,0,0,0), lw=0.) # edgecolor=(0,0,0,0)) #Plot lines pyplot.plot([0.17,0.17],[0.,2.8],color='k',lw=1.5) pyplot.plot(nks,linsp(nks)+0.01,color='k',lw=1.5) bovy_plot.bovy_text(0.19,.5,r'$95\,\%\,\mathrm{noise\ range}$', bbox=dict(facecolor='w',edgecolor='w'),fontsize=14.) if _INTERP: interpks= list(ks[:-5]) interppsd= list((scale*numpy.sqrt(psd1d[1][1:-3]-_SUBTRACTERRORS*numpy.median(noisepsd,axis=0)))[:-5]) interppsd_w= (scale*0.5*psd1d[2][1:-3]/numpy.sqrt(psd1d[1][1:-3]))[:-5] interppsd_w[:8]*= 0.025 #fiddling to get a decent fit interppsd_w[3:5]*= 0.001 interppsd_w= list(interppsd_w) interpks.append(0.025) interppsd.append(10.**-5.) interppsd_w.append(0.00001) interpks.append(110.) interppsd.append(1.) interppsd_w.append(0.00001) if _ADDGCS: interpks.extend(ks_gcs) interppsd.extend(psd_gcs) interppsd_w.extend(e_psd_gcs) if _ADDRAVE: interpks.extend(ks_rave[5:]) interppsd.extend(psd_rave[5:]) interppsd_w.extend(e_psd_rave[5:]) interpks= numpy.array(interpks) sortindx= numpy.argsort(interpks) interpks= interpks[sortindx] interppsd= numpy.array(interppsd)[sortindx] interppsd_w= interppsd/numpy.array(interppsd_w)[sortindx] interpindx= True-numpy.isnan(interppsd) #interpspec= interpolate.InterpolatedUnivariateSpline(interpks[interpindx], interpspec= interpolate.UnivariateSpline(numpy.log(interpks[interpindx]), numpy.log(interppsd[interpindx]/3.), w=interppsd_w, k=3,s=len(interppsd_w)*0.8) pks= numpy.linspace(interpks[0],interpks[-1],201) #bovy_plot.bovy_plot(pks, # 3.*numpy.exp(interpspec(numpy.log(pks))), # 'k-',overplot=True) def my_formatter(x, pos): return r'$%g$' % x def my_formatter2(x, pos): return r'$%g$' % (1./x) major_formatter = FuncFormatter(my_formatter) major_formatter2 = FuncFormatter(my_formatter2) ax= pyplot.gca() ax.xaxis.set_major_formatter(major_formatter) if not _PROPOSAL: ax2= pyplot.twiny() xmin, xmax= ax.xaxis.get_view_interval() ax2.set_xscale('log') ax2.xaxis.set_view_interval(1./xmin,1./xmax,ignore=True) ax2.set_xlabel('$\mathrm{Approximate\ scale}\,(\mathrm{kpc})$', fontsize=12.,ha='center',x=0.5) ax2.xaxis.set_major_formatter(major_formatter) bovy_plot.bovy_end_print(plotfilename,dpi=300) return None
def get_spectra( name, red_clump, location ): ###Function to read the allStar file and get the spectra, correct spectra for ###small and large uncertainties, remove red clump stars """Return cluster data, spectra, spectral errors, photometric Teffs, and bitmask from APOGEE. If the data file for the specified cluster already exists locally, import the data from the file (cluster data, spectra, spectral errors, bitmask). If the data file does not exist, obtain the APOGEE spectra from a specified cluster from the allStar catalogue, replacing ASPCAP abundances with astroNN abundances. Parameters ---------- name : str Name of desired cluster (i.e. 'NGC 2682') red_clump : str If the red clump stars in rcsample are to be removed, set to 'True'. If all stars are to be used, set to 'False'. location : str If running locally, set to 'personal'. If running on the server, set to 'server'. Returns ------- apogee_cluster_data (all stars) or apogee_cluster_data_final (red clumps removed) : structured array All cluster data from APOGEE spectra_50 (all stars) or spectra_final (red clumps removed) : tuple Array of floats representing the cleaned-up fluxes in the APOGEE spectra with red clump stars removed spectra_err_50 (all stars) or spectra_err_final (red clumps removed) : tuple Array of floats representing the cleaned-up spectral errors from the APOGEE spectra with red clump stars removed good_T (all stars) or T_final (red clumps removed) : tuple Array of floats representing the effective temperatures of the stars in the cluster between 4000K and 5000K full_bitmask (all stars) or bitmask_final (red clumps removed) : tuple Array of ints (1 or 0), cleaned in the same way as the spectra, representing the bad pixels in the APOGEE_PIXMASK bitmask """ #Path, strip spaces in cluster name if location == 'personal': ###If running on my Mac path = '/Users/chloecheng/Personal/' + str(name).replace( ' ', '') + '.hdf5' ###Path to folder named after cluster elif location == 'server': ###If running on the server path = '/geir_data/scr/ccheng/AST425/Personal/' + str(name).replace( ' ', '') + '.hdf5' ###Path to cluster folder #If the data file for this cluster exists, save the data to variables and return them if glob.glob(path): ###If the file exists if red_clump == 'False': ###If we're keeping all of the stars, read in the data file = h5py.File(path, 'r') apogee_cluster_data = file['apogee_cluster_data'][()] spectra_50 = file['spectra'][()] spectra_err_50 = file['spectra_errs'][()] good_T = file['T'][()] full_bitmask = file['bitmask'][()] file.close() print(name, ' complete.') ###Notification that this function is done return apogee_cluster_data, spectra_50, spectra_err_50, good_T, full_bitmask elif red_clump == 'True': ###If we're removing the red clumps, read in the data file = h5py.File(path, 'r') apogee_cluster_data_final = file['apogee_cluster_data'][()] spectra_final = file['spectra'][()] spectra_err_final = file['spectra_errs'][()] T_final = file['T'][()] bitmask_final = file['bitmask'][()] file.close() print(name, ' complete.') ###Notification that this function is done return apogee_cluster_data_final, spectra_final, spectra_err_final, T_final, bitmask_final #If the file does not exist, get the data from APOGEE else: ###If the file does not exist #Get red clump stars from rcsample rc_data = rcsample(dr='14') ###Get the rcsample data for DR14 rc_stars = [] ###Empty list for the stars for i in range(len(rc_data)): ###Iterate through the rcsample data if location == 'personal': ###If running on Mac rc_stars.append( rc_data[i][2]) ###Append just the names of the stars elif location == 'server': ###If running on server rc_stars.append( rc_data[i][2].decode('UTF-8') ) ###Append just the names of the stars (decode because on server the names are bitwise for some reason) rc_stars = np.array( rc_stars) ###Make list of red clump star names into array #Read in APOGEE catalogue data, removing duplicated stars and replacing ASPCAP with astroNN abundances apogee_cat = apread.allStar( use_astroNN_abundances=True ) ###Read the allStar file, using the astroNN abundances unique_apoids, unique_inds = np.unique( apogee_cat['APOGEE_ID'], return_index=True) ###Get the APOGEE IDs apogee_cat = apogee_cat[unique_inds] ###Get the APOGEE IDs #Read in overall cluster information cls = afits.open('occam_cluster-DR14.fits') ###Read in the OCCAM data cls = cls[1].data ###Get the cluster information #Read in information about cluster members members = afits.open( 'occam_member-DR14.fits') ###Read in the OCCAM members data members = members[1].data ###Get the member information #Select all members of a given cluster cluster_members = (members['CLUSTER'] == name) & ( members['MEMBER_FLAG'] == 'GM' ) #second part of the mask indicates to only use giant stars member_list = members[ cluster_members] ###Make a list of all member stars in the cluster #Find APOGEE entries for that cluster #numpy.in1d finds the 1D intersection between two lists. #In this case we're matching using the unique APOGEE ID assigned to each star #The indices given by numpy.in1d are for the first argument, so in this case the apogee catalogue cluster_inds = np.in1d((apogee_cat['APOGEE_ID']).astype('U100'), member_list['APOGEE_ID'] ) ###Get the indices of the cluster members apogee_cluster_data = apogee_cat[ cluster_inds] ###Get the allStar data for these members T = photometric_Teff( apogee_cluster_data ) ###Compute the photometric effective temperature #Mark red clump stars in the members of the cluster as NaNs cluster_stars = member_list[ 'APOGEE_ID'] ###Get a list of all the names of the member stars in the cluster cluster_marked = np.copy( cluster_stars ) ###Create a copy of this list to mark which stars are red clumps for i in range(len(cluster_stars) ): ###Iterate through all of the stars in the cluster for j in range(len( rc_stars)): ###Iterate through all of the rcsample stars if cluster_stars[i] in rc_stars[ j]: ###If a cluster member is also a member of the rcsample stars cluster_marked[ i] = np.nan ###Replace the name of that star with a NaN to ignore it #Get spectra, spectral errors, and bitmask for each star - apStar #We can use the APOGEE package to read each star's spectrum #We'll read in the ASPCAP spectra, which have combined all of the visits for each star and removed the spaces between the spectra number_of_members = len( member_list) ###Number of members in the cluster spectra = np.zeros((number_of_members, 7514)) ###Create an empty array to add the spectra spectra_errs = np.zeros( (number_of_members, 7514)) ###Create an empty array to add the spectral errors bitmask = np.zeros((number_of_members, 7514)) ###Create an empty array to add the bitmask for s, star in enumerate( apogee_cluster_data): ###Iterate through the allStar data spectra[s] = apread.aspcapStar( star['LOCATION_ID'], star['APOGEE_ID'], ext=1, header=False, dr='14', aspcapWavegrid=True) ###Get the spectra spectra_errs[s] = apread.aspcapStar( star['LOCATION_ID'], star['APOGEE_ID'], ext=2, header=False, dr='14', aspcapWavegrid=True) ###Get the spectral errors bitmask[s] = apread.apStar( star['LOCATION_ID'], star['APOGEE_ID'], ext=3, header=False, dr='14', aspcapWavegrid=True)[1] ###Get the bitmask #Set all entries in bitmask to integers bitmask = bitmask.astype( int) ###Set all entries in the bitmask to integers bitmask_flip = np.zeros_like( bitmask ) ###Create an empty array for the bitmask with flipped entries for i in range( len(spectra )): ###Iterate through the number of stars in the cluster for j in range(7514): ###Iterate through the wavelength range if bitmask[i][j] == 0: ###If the bitmask entry is set to 0 bitmask_flip[i][j] = 1 ###Set it to 1 else: ###If the bitmask entry is not set to 0 bitmask_flip[i][j] = 0 ###Set it to 0 ###I do this part because the unmasked entries are always 0 in the original bitmask but I think before I was maybe adding in other values to include in the mask that may not have necessarily been 1 so I just set all masked bits to 0 and all unmasked bits to 1 (or maybe this just made more sense in my head for masked to be 0 and unmasked to be 1) #Remove empty spectra full_spectra = [ ] ###Empty list for the spectra sans empty ones, list not array because we don't know how many stars will be eliminated full_spectra_errs = [ ] ###Empty list for the spectral errors sans empty spectra full_bitmask = [] ###Empty list for bitmask sans empty spectra full_T = [] ###Empty list for temperatures sans empty spectra full_stars = [] ###Empty list for indices of stars sans empty spectra for i in range(len(spectra)): ###Iterate through the number of stars if any(spectra[i, :] != 0 ): ###For all of the rows whose entries are not all 0 full_spectra.append(spectra[i]) ###Append those spectra full_spectra_errs.append( spectra_errs[i]) ###Append those spectral errors full_bitmask.append( bitmask_flip[i]) ###Append those bitmask rows full_T.append(T[i]) ###Append those temperatures full_stars.append(i) ###Append the indices of those stars full_spectra = np.array(full_spectra) ###Make list into array full_spectra_errs = np.array( full_spectra_errs) ###Make list into array full_bitmask = np.array(full_bitmask) ###Make list into array full_T = np.array(full_T) ###Make list into array full_stars = np.array(full_stars) ###Make list into array full_marked_stars = cluster_marked[ full_stars] ###Use array of stars left to index marked stars so we know which ones are red clump stars #Create array of NaNs to replace flagged values in spectra masked_spectra = np.empty_like( full_spectra ) ###Create an empty array that is the same shape as full_spectra masked_spectra_errs = np.empty_like( full_spectra_errs ) ###Create an empty array that is the same shape as full_spectra_errs masked_spectra[:] = np.nan ###Set all of the entries to NaNs masked_spectra_errs[:] = np.nan ###Set all of the entries to NaNs #Mask the spectra for i in range( len(full_spectra)): ###Iterate through the number of stars for j in range(7514): ###Iterate through the wavelength range if full_bitmask[i][ j] != 0: ###If the bitmask is not 0 (i.e. if the bit is unmasked) masked_spectra[i][j] = full_spectra[i][ j] ###Retain the value of the unmasked spectra here masked_spectra_errs[i][j] = full_spectra_errs[i][ j] ###Retain the value of the unmasked spectral errors here ###All of the masked bits that were not captured by this if statement will remain NaNs and will thus be ignored #Cut stars that are outside of the temperature limits good_T_inds = (full_T > 4000) & ( full_T < 5000 ) ###Get the indices of the temperatures that are between 4000K and 5000K final_spectra = masked_spectra[ good_T_inds] ###Index the spectra to only keep stars that are within the temperature limits final_spectra_errs = masked_spectra_errs[ good_T_inds] ###Index the spectral errors to only keep stars within Teff limits good_T = full_T[ good_T_inds] ###Index the temperatures to keep only stars within Teff limits apogee_cluster_data = apogee_cluster_data[ good_T_inds] ###Index the allStar data to keep stars only within Teff limits full_bitmask = full_bitmask[ good_T_inds] ###Index the bitmask to keep stars only within Teff limits final_stars = full_marked_stars[ good_T_inds] ###Index the array of red-clump-marked stars to keep only those within Teff limits rgs = (final_stars != 'nan' ) #Get indices for final red giant stars to be used #Want an SNR of 200 so set those errors that have a larger SNR to have an SNR of 200 spectra_err_200 = np.zeros_like( final_spectra_errs ) ###Create an empty array to add corrected spectral errors to - shape will not change, just altering values for i in range(len(final_spectra)): ###Iterate through the stars for j in range(7514): ###Iterate through wavelength range if final_spectra[i][j] / final_spectra_errs[i][ j] <= 200: ###If errors are of a reasonable size spectra_err_200[i][j] = final_spectra_errs[i][ j] ###Leave them as they are else: ###If errors are too small spectra_err_200[i][j] = final_spectra[i][ j] / 200 ###Make them a bit bigger #Cut errors with SNR of less than 50 spectra_50 = np.copy( final_spectra ) ###Create a copy of the spectra to cut large error pixels spectra_err_50 = np.copy( spectra_err_200 ) ###Create a copy of the spectral errors to cut large error pixels for i in range(len(final_spectra)): ###Iterate through stars for j in range(7514): ###Iterate through wavelength range if final_spectra[i][j] / spectra_err_200[i][ j] <= 50: ###If an error is too big spectra_50[i][ j] = np.nan ###Set the corresponding entry in the spectra to be a NaN, will be ignored spectra_err_50[i][ j] = np.nan ###Set the corresponding entry in the spectral errors to be a NaN, will be ignored #Cut red clumps logg = apogee_cluster_data[ 'LOGG'] ###Get the logg values for the cluster (all corrections have been applied) apogee_cluster_data_final = apogee_cluster_data[ rgs] ###Get the allStar data for the RGB stars only (no red clumps) spectra_final = spectra_50[ rgs] ###Get the spectra for the RGB stars only spectra_err_final = spectra_err_50[ rgs] ###Get the spectral errors for the RGB stars only T_final = good_T[rgs] ###Get the temperatures for the RGB stars only bitmask_final = full_bitmask[ rgs] ###Get the bitmask for the RGB stars only if red_clump == 'False': ###If we are looking at all of the stars, save all data before red clumps were cut to file #Write to file file = h5py.File(path, 'w') file['apogee_cluster_data'] = apogee_cluster_data file['spectra'] = spectra_50 file['spectra_errs'] = spectra_err_50 file['T'] = good_T file['bitmask'] = full_bitmask file.close() print(name, 'complete') ###Notification that this function is done return apogee_cluster_data, spectra_50, spectra_err_50, good_T, full_bitmask elif red_clump == 'True': ###If we are removing the red clump stars, save the data after red clumps cut to file #Write to file file = h5py.File(path, 'w') file['apogee_cluster_data'] = apogee_cluster_data_final file['spectra'] = spectra_final file['spectra_errs'] = spectra_err_final file['T'] = T_final file['bitmask'] = bitmask_final file.close() print(name, 'complete') ###Notification that this function is done return apogee_cluster_data_final, spectra_final, spectra_err_final, T_final, bitmask_final
def plot_sigmar(plotfilename,plotfilename2): #First read the sample data= apread.rcsample() if _ADDLLOGGCUT: data= data[data['ADDL_LOGG_CUT'] == 1] data= data[(data['PMMATCH'] == 1)] #Good velocities galy= data['RC_GALR']*numpy.sin(data['RC_GALPHI']) indx= (numpy.fabs(galy) < .75)*(numpy.fabs(data['RC_GALZ']) < 0.25) #(numpy.fabs(data['GLAT']) < 1.51) data= data[indx] print len(data) rs= numpy.arange(3.5,16.501,.5) sigrs= numpy.zeros_like(rs)+numpy.nan mvrs= numpy.zeros_like(rs)+numpy.nan emvrs= numpy.zeros_like(rs)+numpy.nan esigrs= numpy.zeros_like(rs)+numpy.nan pmesigrs= numpy.zeros_like(rs)+numpy.nan std= robstd #std= numpy.std for ii in range(len(rs)-1): tindx= (data['RC_GALR'] > rs[ii])\ *(data['RC_GALR'] <= rs[ii+1]) print rs[ii], numpy.sum(tindx) sigrs[ii]= std(data['GALVR'][tindx]) mvrs[ii]= numpy.median(data['GALVR'][tindx]) emvrs[ii]= sigrs[ii]/numpy.sqrt(numpy.sum(tindx)) esigrs[ii]= disperror(data['GALVR'][tindx],std) pmesigrs[ii]= 4.74047*numpy.sqrt(numpy.mean(data['RC_DIST'][tindx]**2.\ *data['PMRA_ERR'][tindx]**2.\ *numpy.sin(data['GLON'][tindx]/180.*numpy.pi+data['RC_GALPHI'][tindx])**2.)) #Now plot bovy_plot.bovy_print() print sigrs print esigrs bovy_plot.bovy_plot(rs+0.5*(rs[1]-rs[0]),sigrs,'ko',semilogy=True, xlabel=r'$R\,(\mathrm{kpc})$', ylabel=r'$\sigma_R\,(\mathrm{km\,s}^{-1})$', xrange=[0.,18.], yrange=[10.,100.]) pyplot.errorbar(rs+0.5*(rs[1]-rs[0]),sigrs,yerr=esigrs,marker='None', ls='none',color='k') #bovy_plot.bovy_plot(rs+0.5*(rs[1]-rs[0]),pmesigrs,'ks',overplot=True) #Fit indx= (True-numpy.isnan(sigrs))*(True-numpy.isinf(sigrs))*(sigrs > 0.) #esigrs[3]= 100. bestfit= optimize.curve_fit(expfit,(rs+0.5*(rs[1]-rs[0]))[indx], sigrs[indx],sigma=esigrs[indx], p0=(numpy.log(32.),numpy.log(12.))) print numpy.exp(bestfit[0]), bestfit[1] bovy_plot.bovy_plot(rs+0.5*(rs[1]-rs[0]), numpy.exp(bestfit[0][0])\ *numpy.exp(-(rs+0.5*(rs[1]-rs[0])-8.)/numpy.exp(bestfit[0][1])), 'k--',overplot=True) pyplot.yticks([10,20,30,40,50,60,70,80,90,100],[r'$10$',r'$20$',r'$30$',r'$40$',r'$50$',r'$60$',r'$70$',r'$80$',r'$90$',r'$100$']) bovy_plot.bovy_text(r'$|Z| < 50\,\mathrm{pc}$',top_right=True,size=18.) bovy_plot.bovy_text(r'$\sigma_R = %.0f\,\mathrm{km\,s}^{-1}\,\exp\left(-\left[R-8\,\mathrm{kpc}\right] / %.0f\,\mathrm{kpc}\right)$' % (numpy.exp(bestfit[0][0]),numpy.exp(bestfit[0][1])), bottom_left=True,size=14.) bovy_plot.bovy_end_print(plotfilename) #Now plot vr #First read the sample #data= apread.rcsample() #data= data[(data['PMMATCH'] == 1)] #Good velocities #galy= data['RC_GALR']*numpy.sin(data['RC_GALPHI']) #indx= (numpy.fabs(galy) < .5)*(numpy.fabs(data['RC_GALZ']) < 0.1) #(numpy.fabs(data['GLAT']) < 1.51) #data= data[indx] print len(data) rs= numpy.arange(3.5,16.501,3.) sigrs= numpy.zeros_like(rs)+numpy.nan mvrs= numpy.zeros_like(rs)+numpy.nan emvrs= numpy.zeros_like(rs)+numpy.nan esigrs= numpy.zeros_like(rs)+numpy.nan pmesigrs= numpy.zeros_like(rs)+numpy.nan for ii in range(len(rs)-1): tindx= (data['RC_GALR'] > rs[ii])\ *(data['RC_GALR'] <= rs[ii+1]) print rs[ii], numpy.sum(tindx) sigrs[ii]= std(data['GALVR'][tindx]) mvrs[ii]= numpy.median(data['GALVR'][tindx]) emvrs[ii]= sigrs[ii]/numpy.sqrt(numpy.sum(tindx)) esigrs[ii]= disperror(data['GALVR'][tindx],std) pmesigrs[ii]= 4.74047*numpy.sqrt(numpy.mean(data['RC_DIST'][tindx]**2.\ *data['PMRA_ERR'][tindx]**2.\ *numpy.sin(data['GLON'][tindx]/180.*numpy.pi+data['RC_GALPHI'][tindx])**2.)) print rs+0.5*(rs[1]-rs[0]),mvrs bovy_plot.bovy_print() bovy_plot.bovy_plot(rs+0.5*(rs[1]-rs[0]),mvrs,'ko', xlabel=r'$R\,(\mathrm{kpc})$', ylabel=r'$\mathrm{median}\ v_R\,(\mathrm{km\,s}^{-1})$', xrange=[0.,18.], yrange=[-10.,10.]) pyplot.errorbar(rs+0.5*(rs[1]-rs[0]),mvrs,yerr=emvrs,marker='None', ls='none',color='k') bovy_plot.bovy_text(r'$|Z| < 50\,\mathrm{pc}$',top_right=True,size=18.) bovy_plot.bovy_end_print(plotfilename2)