def get_MG_BPRP(g, dust_correct=False): global bayestar if dust_correct: if bayestar is None: bayestar = BayestarQuery() c = g.get_skycoord() ebv = bayestar.query(c) mg = g.get_G0(ebv=ebv) - g.distmod bprp = g.get_BP0(ebv=ebv) - g.get_RP0(ebv=ebv) else: mg = g.phot_g_mean_mag - g.distmod bprp = g.phot_bp_mean_mag - g.phot_rp_mean_mag return mg, bprp
def __init__(self, with_extinction_maps=False): self.redd_maps = {} with open(dir_path + 'extinction/extinction_coeffs_2017.dat') as f: self.R_V_grid = np.fromstring(f.readline(), dtype=np.float64, sep=' ') for l in f.readlines(): spl = l.split(" ", 1) self.redd_maps[spl[0]] = np.fromstring(spl[1], dtype=np.float64, sep=' ') self.interp_maps = { n: interp1d(self.R_V_grid, self.redd_maps[n]) for n in self.redd_maps } self.R_G = np.zeros((75, len(self.R_V_grid))) with open(dir_path + 'extinction/extinction_coeffs_G_2017.dat') as f: self.logTeffgrid = np.fromstring(f.readline(), dtype=np.float64, sep=' ') for n, l in enumerate(f.readlines()): self.R_G[n] = np.fromstring(l, dtype=np.float64, sep=' ') self.interp_G_maps = interp2d(self.R_V_grid, self.logTeffgrid, self.R_G) if (with_extinction_maps): self.sfd = SFDQuery() self.bayestar = BayestarQuery(max_samples=10) self.marshall = MarshallQuery() self.drimmel = mwdust.Drimmel03(filter='Landolt V')
def dust(l, b, distance, plot=False, max_samples=2, mode='median', model='bayes'): if model == 'sfd': c = SkyCoord(l, b, frame='galactic') sfd = SFDQuery() dust = sfd(c) if model == 'bayes': c = SkyCoord(l, b, distance = distance, frame='galactic') bayes = BayestarQuery(max_samples=max_samples) dust = bayes(c, mode=mode) if model == 'iphas': c = SkyCoord(l, b, distance = distance, frame='galactic') iphas = IPHASQuery() dust = iphas(c, mode=mode) if model == 'marshall': c = SkyCoord(l, b, distance = distance, frame='galactic') marshall = MarshallQuery() dust = marshall(c) if model == 'chen': c = SkyCoord(l, b, distance = distance, frame='galactic') chen = Chen2014Query() dust = chen(c) #cNoDist = SkyCoord(l, b, # frame='galactic') #bayesDustNoDist = bayes(cNoDist, mode=mode) #!!!!! Do something else than setting it equal to 0 !!!!! #if len(bayesDust) > 1: bayesDust[np.isnan(bayesDust)] = 0.0 if plot: fig, ax = plt.subplots(3, figsize=(5, 7.5)) ax[0].hist(np.log10(sfd(c)), bins=100, log=True, histtype='step') ax[1].hist(np.log10(bayesDustNoDist[bayesDustNoDist>0]), bins=100, log=True, histtype='step') ax[2].hist(np.log10(bayesDust[bayesDust >0]), bins=100, log=True, histtype='step') ax[0].set_xlabel('SFD Dust Attenuation') ax[1].set_xlabel('Bayestar Dust Attenuation No Distance') ax[2].set_xlabel('Bayestar Dust Attenuation') for a in ax: a.set_xlim(-4, 0.0) hist, bins = np.histogram(magsMatched['bmag'], bins=100) plt.hist(magsMatched['bmag'], bins=bins, histtype='step') plt.hist(magsMatched['bmag'] - B_RedCoeff*bayesDust, bins=bins, histtype='step') plt.tight_layout() return dust
def main(): w, h = (2056, 1024) l_0 = 130. # Set up Bayestar query object print('Loading bayestar map...') bayestar = BayestarQuery(max_samples=1) # Create a grid of coordinates print('Creating grid of coordinates...') l = np.linspace(-180. + l_0, 180. + l_0, 2 * w) b = np.linspace(-90., 90., 2 * h + 2) b = b[1:-1] l, b = np.meshgrid(l, b) l += (np.random.random(l.shape) - 0.5) * 360. / (2. * w) b += (np.random.random(l.shape) - 0.5) * 180. / (2. * h) ebv = np.empty(l.shape + (3, ), dtype='f8') for k, d in enumerate([0.5, 1.5, 5.]): # d = 5. # We'll query integrated reddening to a distance of 5 kpc coords = SkyCoord(l * u.deg, b * u.deg, d * u.kpc, frame='galactic') # Get the dust median reddening at each coordinate print('Querying map...') ebv[:, :, k] = bayestar.query(coords, mode='median') ebv[:, :, 2] -= ebv[:, :, 1] ebv[:, :, 1] -= ebv[:, :, 0] # Convert the output array to a PIL image and save print('Saving image...') img = numpy2pil(ebv[::-1, ::-1, :], 0., 1.5) img = img.resize((w, h), resample=PIL.Image.LANCZOS) fname = 'bayestar.png' img.save(fname) return 0
def main(): w,h = (2056,1024) l_0 = 130. # Set up Bayestar query object print('Loading bayestar map...') bayestar = BayestarQuery(max_samples=1) # Create a grid of coordinates print('Creating grid of coordinates...') l = np.linspace(-180.+l_0, 180.+l_0, 2*w) b = np.linspace(-90., 90., 2*h+2) b = b[1:-1] l,b = np.meshgrid(l, b) l += (np.random.random(l.shape) - 0.5) * 360./(2.*w) b += (np.random.random(l.shape) - 0.5) * 180./(2.*h) ebv = np.empty(l.shape+(3,), dtype='f8') for k,d in enumerate([0.5, 1.5, 5.]): # d = 5. # We'll query integrated reddening to a distance of 5 kpc coords = SkyCoord(l*u.deg, b*u.deg, d*u.kpc, frame='galactic') # Get the dust median reddening at each coordinate print('Querying map...') ebv[:,:,k] = bayestar.query(coords, mode='median') ebv[:,:,2] -= ebv[:,:,1] ebv[:,:,1] -= ebv[:,:,0] # Convert the output array to a PIL image and save print('Saving image...') img = numpy2pil(ebv[::-1,::-1,:], 0., 1.5) img = img.resize((w,h), resample=PIL.Image.LANCZOS) fname = 'bayestar.png' img.save(fname) return 0
def InitializeDustmap(config): # Fetch the planck data if we don't have it yet. if not os.path.exists(os.path.join(config['DataDirectory'], 'planck')): print('downloading planck data') from dustmaps.config import config as dustconfig dustconfig['data_dir'] = config['DataDirectory'] from dustmaps.planck import fetch fetch() planck = PlanckQuery() # Fetch the bayestar data if we don't have it yet. if not os.path.exists(os.path.join(config['DataDirectory'], 'bayestar')): print('downloading bayestar data') from dustmaps.config import config as dustconfig dustconfig['data_dir'] = config['DataDirectory'] from dustmaps.bayestar import fetch fetch() bayestar = BayestarQuery(version='bayestar2015') return planck, bayestar
def main(): c0 = SkyCoord.from_name('orion a', frame='galactic') print(c0) # l = np.arange(c0.l.deg - 5., c0.l.deg + 5., 0.05) # b = np.arange(c0.b.deg - 5., c0.b.deg + 5., 0.05) l0, b0 = (37., -16.) l = np.arange(l0 - 5., l0 + 5., 0.05) b = np.arange(b0 - 5., b0 + 5., 0.05) l, b = np.meshgrid(l, b) coords = SkyCoord(l * units.deg, b * units.deg, distance=1. * units.kpc, frame='galactic') sfd = SFDQuery() Av_sfd = 2.742 * sfd(coords) planck = PlanckQuery() Av_planck = 3.1 * planck(coords) bayestar = BayestarQuery(max_samples=1) Av_bayestar = 2.742 * bayestar(coords) fig = plt.figure(figsize=(12, 4), dpi=150) for k, (Av, title) in enumerate([(Av_sfd, 'SFD'), (Av_planck, 'Planck'), (Av_bayestar, 'Bayestar')]): ax = fig.add_subplot(1, 3, k + 1) ax.imshow(np.sqrt(Av)[::, ::-1], vmin=0., vmax=2., origin='lower', interpolation='nearest', cmap='binary', aspect='equal') ax.axis('off') ax.set_title(title) fig.subplots_adjust(wspace=0., hspace=0.) plt.savefig('comparison.png', dpi=150) return 0
def calc_extinct(): t = Table.read('lamost_rc_wise_gaia_PS1_2mass.fits') from astropy.coordinates import SkyCoord import astropy.units as units import dustmaps.bayestar from dustmaps.bayestar import BayestarQuery dustmaps.bayestar.fetch() bayestar = BayestarQuery(version='bayestar2019',max_samples=1) # 'bayestar2019' is the default print('here') avs = np.full(len(t),np.nan) inds = np.where(~np.isnan(t['dist']))[0] coords = SkyCoord(t['GLON'][inds]*units.deg, t['GLAT'][inds]*units.deg,distance=t['dist'][inds]*units.kpc, frame='galactic') reddening = bayestar(coords, mode='median') AK = .3026*reddening AV = AK/.05 avs[inds] = AV t['A_V'] = avs t.write('lamost_rc_wise_gaia_PS1_2mass_ext.fits',overwrite=True)
print("Loading Gaia catalog") with fits.open("kepler_dr2_1arcsec.fits") as data: gaia = pd.DataFrame(data[1].data, dtype="float64") gaia_mc = pd.merge(mc, gaia, on="kepid", how="left") # S/N cuts sn = gaia_mc.parallax.values / gaia_mc.parallax_error.values m = (sn > 10) m &= (gaia_mc.parallax.values > 0) * np.isfinite(gaia_mc.parallax.values) m &= gaia_mc.astrometric_excess_noise.values < 5 gaia_mc = gaia_mc.iloc[m] print("Loading Dustmaps") bayestar = BayestarQuery(max_samples=2, version='bayestar2019') print("Calculating Ebv") coords = SkyCoord(gaia_mc.ra.values * units.deg, gaia_mc.dec.values * units.deg, distance=gaia_mc.r_est.values * units.pc) ebv, flags = bayestar(coords, mode='percentile', pct=[16., 50., 84.], return_flags=True) # Calculate Av Av_bayestar = 2.742 * ebv Av = Av_bayestar[:, 1] Av_errm = Av - Av_bayestar[:, 0]
l*units.deg, b*units.deg, distance=1.*units.kpc, frame='galactic' ) #-------------------------------------------- # Then, we’ll load up and query three different dust maps: sfd = SFDQuery() Av_sfd = 2.742 * sfd(coords) planck = PlanckQuery() Av_planck = 3.1 * planck(coords) bayestar = BayestarQuery(max_samples=1) Av_bayestar = 2.742 * bayestar(coords) #-------------------------------------------- # We’ve assumed RV=3.1, and used the coefficient from Table 6 of Schlafly & Finkbeiner (2011) # to convert SFD and Bayestar reddenings to magnitudes of AV. # # Finally, we create the figure using matplotlib: fig = plt.figure(figsize=(12,4), dpi=150) for k,(Av,title) in enumerate([(Av_sfd, 'SFD'), (Av_planck, 'Planck'), (Av_bayestar, 'Bayestar')]): ax = fig.add_subplot(1,3,k+1) ax.imshow(
def InitializeDustmap(): # Initialize dustmaps using Bayestar2019 print('Initializing Bayestar2019.') #dustmaps.bayestar.fetch() bayestar = BayestarQuery(max_samples=1) return bayestar
def extinction(spec, red, coord): """ :param spec: (numpy array) XSpectrum1D objects: use clamato_read.py :param red: (numpy array) redshift values :param coord: (numpy array) coordinates :return: unred_spec: (numpy array) de-reddened spec """ import numpy as np from numpy.lib.polynomial import poly1d import astropy.units as u from astropy.coordinates import SkyCoord from dustmaps.bayestar import BayestarQuery from astropy.cosmology import WMAP9 as cosmo from linetools.spectra.xspectrum1d import XSpectrum1D r = range(len(spec)) Mpc = cosmo.comoving_distance(red) bayestar = BayestarQuery() coords = [ SkyCoord(coord[i][0] * u.deg, coord[i][1] * u.deg, distance=Mpc[i], frame='fk5') for i in r ] ebv = [bayestar(i) for i in coords] #to get the ebv values for each galaxy unred_spec = [] for i in r: x = 10000. / np.array(spec[i].wavelength) # Convert to inverse microns npts = x.size a = np.zeros(npts, dtype=np.float) b = np.zeros(npts, dtype=np.float) r_v = 3.1 good = np.where((x >= 0.3) & (x < 1.1)) if len(good[0]) > 0: a[good] = 0.574 * x[good]**(1.61) b[good] = -0.527 * x[good]**(1.61) good = np.where((x >= 1.1) & (x < 3.3)) if len(good[0]) > 0: # Use new constants from O'Donnell (1994) y = x[good] - 1.82 c1 = np.array([ 1., 0.104, -0.609, 0.701, 1.137, -1.718, -0.827, 1.647, -0.505 ]) # from O'Donnell c2 = np.array([ 0., 1.952, 2.908, -3.989, -7.985, 11.102, 5.491, -10.805, 3.347 ]) a[good] = poly1d(c1[::-1])(y) b[good] = poly1d(c2[::-1])(y) good = np.where((x >= 3.3) & (x < 8)) if len(good[0]) > 0: y = x[good] a[good] = 1.752 - 0.316 * y - (0.104 / ((y - 4.67)**2 + 0.341)) # + f_a b[good] = -3.090 + 1.825 * y + (1.206 / ((y - 4.62)**2 + 0.263)) # + f_b good = np.where((x >= 8) & (x <= 11)) if len(good[0]) > 0: y = x[good] - 8. c1 = np.array([-1.073, -0.628, 0.137, -0.070]) c2 = np.array([13.670, 4.257, -0.420, 0.374]) a[good] = poly1d(c1[::-1])(y) b[good] = poly1d(c2[::-1])(y) # Now apply extinction correction to input flux vector a_v = r_v * ebv[i] a_lambda = a_v * (a + b / r_v) funred = spec[i].flux * 10.**(0.4 * a_lambda) # Derive unreddened flux funred = np.asarray(funred) unred_spec.append(XSpectrum1D(spec[i].wavelength, funred, spec[i].sig)) return np.asarray(unred_spec)
distance = eval(sys.argv[3]) else: print('wrong number of parameters') print('Example: $ python dustmap_script.py 15h28m17.53s -58d35m13.9s 2.3') sys.exit(1) #source_ra = '15h28m17.53s' #source_dec = '-58d35m13.9s' #distance = 2.3 #print(source_ra, source_dec, distance) print('Estimating E(B-V) using dust maps:') coords = SkyCoord(source_ra, source_dec, distance=distance*units.kpc, frame='icrs') bayestar = BayestarQuery(max_samples=5, version='bayestar2017') print('## Bayestar (3D):', bayestar(coords, mode='median')) chen = Chen2014Query() print('## Chen 2014 (3D):', chen(coords)) iphas = IPHASQuery() print('## IPHAS (3D):', iphas(coords, mode='median')) marshal = MarshallQuery() print('## Marshall 2006 (3D):', marshal(coords)) sfdebv = SFDQuery() print('## SFD 1998/2011 (2D):', sfdebv(coords)) lenz = Lenz2017Query()