def loadin_central_fits(haloID,zl,bsz,nnn,band='ACS_F606_NEW.res'): GroupFirstSub = il.groupcat.loadHalos(basePath,135,fields=['GroupFirstSub']) sub_galnrs = GroupFirstSub[haloID] my_api = "9dc591936258a12cb7192ebf79450272" # Input your own api for Illustris database dl_base = 'http://www.illustris-project.org' cmd = 'wget --content-disposition --header="API-Key: '+my_api+'" "'+dl_base+ \ '/api/Illustris-1/snapshots/135/subhalos/'+str(sub_galnrs)+ \ '/stellar_mocks/broadband.fits"' if( not (os.path.isfile("./broadband_"+str(sub_galnrs)+".fits")) ): os.system(cmd) filename = "./broadband_"+str(sub_galnrs)+".fits" hdulist = pyfits.open(filename) nx1 = hdulist[3].header['NAXIS1'] nx2 = hdulist[3].header['NAXIS2'] Dcmr_zl0 = mm.cosmocalc(0.01, H0=70.4, WM=0.2726, WV=0.7274)['DL_Mpc'] Dcmr_zl1 = mm.cosmocalc(zl, H0=70.4, WM=0.2726, WV=0.7274)['DL_Mpc'] bsz_init = np.rad2deg(hdulist[3].header['FOV'])*3600.0*Dcmr_zl0/Dcmr_zl1 # arcsec dsx_init = bsz_init/nx1 hdulist.close() return_image = sunpy__load.load_broadband_image(filename,band) nnx1 = int(bsz/dsx_init) nnx2 = int(bsz/dsx_init) return_image_new = np.zeros((nnx1,nnx2)) if bsz >= bsz_init: return_image_new[nnx1/2-nx1/2:nnx1/2+nx1/2,nnx2/2-nx2/2:nnx2/2+nx2/2] = return_image else: return_image_new = return_image[nx1/2-nnx1/2:nx1/2+nnx1/2,nx2/2-nnx2/2:nx2/2+nnx2/2] return_image_new = ssi.congrid(return_image_new,(nnn,nnn)) return return_image_new
def get_Vmax(zlo, zup): z = zup V1 = cosmocalc(z, H0=Ho, WM=wm)['VCM_Gpc3'] * 1e9 V2 = cosmocalc(zlo, H0=Ho, WM=wm)['VCM_Gpc3'] * 1e9 area = SURVEY_AREA * sqDeg2sr vmax = area * (V1 - V2) / (4 * pi) #print 'vmax',vmax,V1,V2,zup,zlo,SURVEY_AREA*sqDeg2sr,sqDeg2sr return vmax
def __init__(self, redshift, H0=70.4, WM=0.2726, WV=0.7274): self.H0=H0 self.WM=WM self.WV=WV self.redshift = redshift self.lum_dist = (cosmocalc.cosmocalc(self.redshift, H0=self.H0, WM=self.WM, WV=self.WV))['DL_Mpc'] ## luminosity dist in mpc self.ang_diam_dist = (cosmocalc.cosmocalc(self.redshift, H0=self.H0, WM=self.WM, WV=self.WV))['DA_Mpc'] ## self.kpc_per_arcsec = (cosmocalc.cosmocalc(self.redshift, H0=self.H0, WM=self.WM, WV=self.WV))['PS_kpc']
def get_dL(z): """ Returns the comoving radial distance in Mpc """ if isinstance(z, float): return cosmocalc(z, H0=Ho, WM=wm)['DL_Mpc'] else: return [cosmocalc(zi, H0=Ho, WM=wm)['DL_Mpc'] for zi in z]
def volume(zmin,zmax,cos=[0.3,70]): ''' Calculating dv/dz for a given redshift range and cosmology ''' dz = zmax-zmin vmin = cosmocalc(zmin,H0=cos[1],WM=cos[0])['VCM_Gpc3']*1.0e9 # volume in Mpc^3 vmax = cosmocalc(zmax,H0=cos[1],WM=cos[0])['VCM_Gpc3']*1.0e9 # volume in Mpc^3 dv = vmax-vmin return dv/dz,vmax
def __init__(self, redshift, H0=70.4, WM=0.2726, WV=0.7274): self.H0=H0 self.WM=WM self.WV=WV self.redshift = redshift self.lum_dist = (cosmocalc.cosmocalc(self.redshift, H0=self.H0, WM=self.WM, WV=self.WV))['DL_Mpc'] ## luminosity dist in mpc self.ang_diam_dist = (cosmocalc.cosmocalc(self.redshift, H0=self.H0, WM=self.WM, WV=self.WV))['DA_Mpc'] ## self.kpc_per_arcsec = (cosmocalc.cosmocalc(self.redshift, H0=self.H0, WM=self.WM, WV=self.WV))['PS_kpc'] self.distance_modulus = 5.0 * ( np.log10(self.lum_dist*1.0e6) - 1.0 )
def NFW(r, M200, c200, zl, zs): #this code calculates the shear at a given distance r from an object at redshift zl of mass M200 and concentration c200 assuming a background distribution of zs #set cosmology h = 0.7 #hubble parameter Ho = h * 100.0 #km s^-1 Mpc-1 Om = 0.28 #cosmological parameter Ol = 0.72 #cosmological parameter c = 299792.0 #speed of light in km/s Mpc = 3.0856e19 #1Mpc in km cMpc = c / Mpc #speed of light in Mpc/s pc = 3.0856e16 #1pc in m Msun = 1.989e30 #1Msolar in kg G = 6.6726e-11 #G in m^3 kg-1 s-2 GG = G * (pc**(-3.0)) * (1e-18) * Msun #G in Mpc^3 Msun^-1 s^-2 Ez = np.sqrt(Om * (1.0 + zl)**3.0 + Ol) #evolution pcrit = 3.0 * ((Ho * Ez / Mpc)**2.0) / (8.0 * np.pi * GG) #calculate angular diameter distances in Mpc to lens and source dL = cosmocalc(zl, Ho, Om, Ol)['DA_Mpc'] dS = cosmocalc(zs, Ho, Om, Ol)['DA_Mpc'] dLS = (dS * (1.0 + zs) - dL * (1.0 + zl)) / (1.0 + zs) sigmacr = cMpc**2.0 * dS / ( 4.0 * GG * np.pi * dL * dLS ) #mean critical surface mass density in units Mpc^-2 Msolar p200 = 200.0 * pcrit #density that is 200 times critical p500 = 500.0 * pcrit #density that is 500 times critical r200 = (3.0 * M200 / (4.0 * np.pi * p200))**( 1.0 / 3.0) #radius within which the density is 200 times critical rs = r200 / c200 #characteristic radius in Mpc ps = (p200 * c200**3.0) / (3.0 * (np.log(1.0 + c200) - c200 / (1.0 + c200))) #core density in Msolar Mpc-3 r = np.atleast_1d(r) term = np.where(r <= rs, \ 2.0*np.arctanh(np.sqrt((1.0-(r/rs))/(1.0+(r/rs))))/(np.sqrt(1.0-np.square(r/rs))), \ 2.0*np.arctan(np.sqrt(((r/rs)-1.0)/(1.0+(r/rs))))/(np.sqrt(np.square(r/rs)-1.0))) sigma = 2.0 * rs * ps * (1.0 - term) / ((np.square(r / rs)) - 1.0) meansigma = 4.0 * rs * ps * (term + np.log( (r / rs) / 2.0)) / (np.square(r / rs)) rhoNFW = ps / ((r / rs) * np.square(1.0 + r / rs)) kappaNFW = sigma / sigmacr #calculate convergence meankappaNFW = meansigma / sigmacr #mean convergence gammaNFW = meankappaNFW - kappaNFW #calculate shear reducedshear = np.abs(gammaNFW) / (1.0 - kappaNFW ) #calculate reduced shear return reducedshear
def volume(zmin, zmax, cos=[0.3, 70]): ''' Calculating dv/dz for a given redshift range and cosmology ''' dz = zmax - zmin vmin = cosmocalc(zmin, H0=cos[1], WM=cos[0])['VCM_Gpc3'] * 1.0e9 # volume in Mpc^3 vmax = cosmocalc(zmax, H0=cos[1], WM=cos[0])['VCM_Gpc3'] * 1.0e9 # volume in Mpc^3 dv = vmax - vmin return dv / dz, vmax
def __init__(self, H0=70.0, WM=0.27, WV=0.73): self.H0 = H0 self.WM = WM self.WV = WV self.redshift_grid = np.logspace(-3, 2, 100) self.comoving_mpc_grid = np.asarray([ (cc.cosmocalc(zf, H0=self.H0, WM=self.WM, WV=self.WV))['DCMR_Mpc'] for zf in self.redshift_grid ]) self.DA_mpc_grid = np.asarray([(cc.cosmocalc(zf, H0=self.H0, WM=self.WM, WV=self.WV))['DA_Mpc'] for zf in self.redshift_grid])
def physicalSeparation(inputdata, redshift, H0=71.0, OmegaM=0.28): """ Calculates the physical distances between objects of given RAs and DECs at a given redshift. :param inputdata: coordinates (RA and DEC) of the objects. The input data should consist of four keys value pairs:: RA1: RA of the object from which to calculate the distance (float) DEC1: DEC of the object from which to calculate the distance (float) RA2: RAs of the objects (float or numpy array) DEC2: DECs of the objects (float or numpy array) :type inputdata: dict :param redshift: cosmological redshift of the object :type redshift: float :param H0: Hubble value [71/km/s/Mpc] :type H0: float :param OmegaM: Matter density :type OmegaM: float [0.28] :return: physical distance [distance], scale at a given redshift 1 arcsec = kpc [scale], separation on the sky in arcseconds [separation], cosmological parameters [cosmology] :rtype: dict """ sep = Coords.calcAngSepDeg(inputdata["RA1"], inputdata["DEC1"], inputdata["RA2"], inputdata["DEC2"]) d = cosmocalc(redshift, H0, OmegaM) dd = d["PS_kpc"] pd = angularSeparationToPhysical(sep, dd) return dict(distance=pd, scale=dd, separation=sep / DEGTOARCSEC, redshift=redshift, cosmology=d)
def Transform(): print("Formating input data to correct units") for k in range(len(input_files_data)): dist = (cosmocalc.cosmocalc( input_files_data[k]['red'], H0=70.4, WM=0.2726, WV=0.7274))['DL_Mpc'] #Calculate modulus distance dist *= 1e6 #transform into parsecs modulus_distance = 5.0 * (math.log10(dist) - 1.0) #Calculate modulus distance #DEBUG #print("DIST: " + str(dist)) #print("MOD_DIST: " + str(modulus_distance)) #print("FLUX (microJs): " +str(data['fl'][i])) input_files_data[k]['err'] = 2.5 * input_files_data[k]['err'] / input_files_data[k]['fl'] #Error from the transformation of luminosity to magnitude input_files_data[k]['fl'] = 23.9 - 2.5* np.log10(input_files_data[k]['fl'] ) # Int Into AB magnitude #print("Apparent AB mag: %.5e" % (input_files_data[k]['fl'][i])) input_files_data[k]['fl'] -= modulus_distance
def Transform( red, data_file, err_file): dist = (cosmocalc.cosmocalc( red, H0=70.4, WM=0.2726, WV=0.7274))['DL_Mpc'] #Calculate modulus distance dist *= 1e6 #transform into parsecs modulus_distance = 5.0 * (math.log10(dist) - 1.0) #Calculate modulus distance #DEBUG #print("DIST: " + str(dist)) #print("MOD_DIST: " + str(modulus_distance)) #print("FLUX (microJs): " +str(data['fl'][i])) err_file = 2.5 * err_file / data_file #Error from the transformation of luminosity to magnitude data_file = 23.9 - 2.5* np.log10(data_file ) # Int Into AB magnitude #print("Apparent AB mag: %.5e" % (input_files_data[k]['fl'][i])) data_file -= modulus_distance #Into absolute magn #print('%.5e %.5e'% (input_files_data[k]['fl'][i], input_files_data[k]['err'][i])) #print(" ") return (data_file, err_file)
def load_resolved_broadband_apparent_magnitudes(filename, redshift, camera=0, seed=12345, n_bands=36, **kwargs): """ loads n_band x n_pix x n_pix image array with apparent mags for synthetic images """ mags = sunpy.sunpy__load.load_all_broadband_photometry(filename, camera=0) for band in np.arange(n_bands): obj = synthetic_image(filename, band=int(band), seed=seed, redshift=redshift, **kwargs) img = obj.bg_image.return_image() # muJy / str if band==0: n_pixels = img.shape[0] all_images = np.zeros( (n_bands, n_pixels, n_pixels ) ) all_images[band, :, :] = img # muJy / str pixel_in_sr = (1e3*obj.bg_image.pixel_in_kpc /10.0)**2 all_images *= pixel_in_sr / 1e6 # in Jy for band in np.arange(n_bands): tot_img_in_Jy = np.sum(all_images[band,:,:]) # total image flux in Jy abmag = -2.5 * np.log10(tot_img_in_Jy / 3631 ) if verbose: print "the ab magnitude of band "+str(band)+" is :"+str(abmag)+" "+str(mags[band]) print abmag/mags[band], abmag - mags[band] print " " all_images = -2.5 * np.log10( all_images / 3631 ) # abmag in each pixel dist = (cosmocalc.cosmocalc(redshift, H0=70.4, WM=0.2726, WV=0.7274))['DL_Mpc'] * 1e6 dist_modulus = 5.0 * ( np.log10(dist) - 1.0 ) apparent_magnitudes = dist_modulus + all_images del mags, obj, img, n_pixels, all_images, pixel_in_sr, tot_img_in_Jy, abmag, dist, dist_modulus gc.collect() return apparent_magnitudes
def load_resolved_broadband_apparent_magnitudes(filename, redshift, camera=0, seed=12345, n_bands=36, **kwargs): """ loads n_band x n_pix x n_pix image array with apparent mags for synthetic images """ mags = sunpy.sunpy__load.load_all_broadband_photometry(filename, camera=0) for band in np.arange(n_bands): obj = synthetic_image(filename, band=int(band), seed=seed, redshift=redshift, **kwargs) img = obj.bg_image.return_image() # muJy / str if band==0: n_pixels = img.shape[0] all_images = np.zeros( (n_bands, n_pixels, n_pixels ) ) all_images[band, :, :] = img # muJy / str pixel_in_sr = (1e3*obj.bg_image.pixel_in_kpc /10.0)**2 all_images *= pixel_in_sr / 1e6 # in Jy for band in np.arange(n_bands): tot_img_in_Jy = np.sum(all_images[band,:,:]) # total image flux in Jy abmag = -2.5 * np.log10(tot_img_in_Jy / 3631 ) if verbose: print "the ab magnitude of band "+str(band)+" is :"+str(abmag)+" "+str(mags[band]) print abmag/mags[band], abmag - mags[band] print " " all_images = -2.5 * np.log10( all_images / 3631 ) # abmag in each pixel dist = (cosmocalc.cosmocalc(redshift, H0=70.4, WM=0.2726, WV=0.7274))['DL_Mpc'] * 1e6 dist_modulus = 5.0 * ( np.log10(dist) - 1.0 ) apparent_magnitudes = dist_modulus + all_images return apparent_magnitudes
def physicalSeparation(inputdata, redshift, H0=71.0, OmegaM=0.28): """ Calculates the physical distances between objects of given RAs and DECs at a given redshift. :param inputdata: coordinates (RA and DEC) of the objects. The input data should consist of four keys value pairs:: RA1: RA of the object from which to calculate the distance (float) DEC1: DEC of the object from which to calculate the distance (float) RA2: RAs of the objects (float or numpy array) DEC2: DECs of the objects (float or numpy array) :type inputdata: dict :param redshift: cosmological redshift of the object :type redshift: float :param H0: Hubble value [71/km/s/Mpc] :type H0: float :param OmegaM: Matter density :type OmegaM: float [0.28] :return: physical distance [distance], scale at a given redshift 1 arcsec = kpc [scale], separation on the sky in arcseconds [separation], cosmological parameters [cosmology] :rtype: dict """ sep = Coords.calcAngSepDeg(inputdata['RA1'], inputdata['DEC1'], inputdata['RA2'], inputdata['DEC2']) d = cosmocalc(redshift, H0, OmegaM) dd = d['PS_kpc'] pd = angularSeparationToPhysical(sep, dd) return dict(distance=pd, scale=dd, separation=sep / DEGTOARCSEC, redshift=redshift, cosmology=d)
def load_resolved_broadband_apparent_magnitudes(filename, redshift, camera=0, **kwargs): """ this is a little trickier b/c in W/m/m^2/str. First convert to abs mag, then dist correction """ images = load_all_broadband_images(filename,camera=0) # in W/m/m^2/str shape = [n_band, n_pix, n_pix] mags = load_all_broadband_photometry(filename, camera=0) n_pixels = images.shape[1] hdulist = fits.open(filename) lambda_eff = hdulist['FILTERS'].data['lambda_eff'] for index,this_lambda in enumerate(lambda_eff): to_nu = ((this_lambda**2 ) / (speedoflight_m)) #* pixel_area_in_str to_microjanskies = (1.0e6) * to_nu * (1.0e26) # 1 muJy/str (1Jy = 1e-26 W/m^2/Hz) images[index,:,:] = images[index,:,:] * to_microjanskies # to microjanskies / str pixel_in_kpc = load_fov(filename) / n_pixels pixel_in_sr = (1e3 * pixel_in_kpc / 10.0)**2 images *= pixel_in_sr # in muJy images /= 1e6 # in Jy for index,this_lambda in enumerate(lambda_eff): tot_img_in_Jy = np.sum(images[index,:,:]) # total image flux in Jy abmag = -2.5 * np.log10(tot_img_in_Jy / 3631 ) if False: print "the ab magnitude of this image is :"+str(abmag)+" "+str(mags[index]) print abmag/mags[index], abmag - mags[index] print index, np.sum(images[index,:,:]) images = -2.5 * np.log10( images / 3631 ) # abmag in each pixel dist = (cosmocalc.cosmocalc(redshift, H0=70.4, WM=0.2726, WV=0.7274))['DL_Mpc'] * 1e6 dist_modulus = 5.0 * ( np.log10(dist) - 1.0 ) apparent_magnitudes = dist_modulus + images return apparent_magnitudes
def load_resolved_broadband_apparent_magnitudes(filename, redshift, camera=0, **kwargs): """ this is a little trickier b/c in W/m/m^2/str. First convert to abs mag, then dist correction """ images = load_all_broadband_images(filename,camera=0) # in W/m/m^2/str shape = [n_band, n_pix, n_pix] mags = load_all_broadband_photometry(filename, camera=0) n_pixels = images.shape[1] hdulist = fits.open(filename) lambda_eff = hdulist['FILTERS'].data['lambda_eff'] for index,this_lambda in enumerate(lambda_eff): to_nu = ((this_lambda**2 ) / (speedoflight_m)) #* pixel_area_in_str to_microjanskies = (1.0e6) * to_nu * (1.0e26) # 1 muJy/str (1Jy = 1e-26 W/m^2/Hz) images[index,:,:] = images[index,:,:] * to_microjanskies # to microjanskies / str pixel_in_kpc = load_fov(filename) / n_pixels pixel_in_sr = (1e3 * pixel_in_kpc / 10.0)**2 images *= pixel_in_sr # in muJy images /= 1e6 # in Jy for index,this_lambda in enumerate(lambda_eff): tot_img_in_Jy = np.sum(images[index,:,:]) # total image flux in Jy abmag = -2.5 * np.log10(tot_img_in_Jy / 3631 ) if True: print "the ab magnitude of this image is :"+str(abmag)+" "+str(mags[index]) print abmag/mags[index], abmag - mags[index] print index, np.sum(images[index,:,:]) images = -2.5 * np.log10( images / 3631 ) # abmag in each pixel dist = (cosmocalc.cosmocalc(redshift, H0=70.4, WM=0.2726, WV=0.7274))['DL_Mpc'] * 1e6 dist_modulus = 5.0 * ( np.log10(dist) - 1.0 ) apparent_magnitudes = dist_modulus + images return apparent_magnitudes
def NFW(r, M200, c200, zl, zs): #this code calculates the shear at a given distance r from an object at redshift zl of mass M200 and concentration c200 assuming a background distribution of zs #set cosmology h = 0.7 #hubble parameter Ho = h*100.0 #km s^-1 Mpc-1 Om = 0.28 #cosmological parameter Ol = 0.72 #cosmological parameter c = 299792.0 #speed of light in km/s Mpc = 3.0856e19 #1Mpc in km cMpc = c/Mpc #speed of light in Mpc/s pc = 3.0856e16 #1pc in m Msun = 1.989e30 #1Msolar in kg G = 6.6726e-11 #G in m^3 kg-1 s-2 GG = G*(pc**(-3.0))*(1e-18)*Msun #G in Mpc^3 Msun^-1 s^-2 Ez = np.sqrt(Om*(1.0+zl)**3.0+Ol) #evolution pcrit= 3.0*((Ho*Ez/Mpc)**2.0)/(8.0*np.pi*GG) #calculate angular diameter distances in Mpc to lens and source dL = cosmocalc(zl,Ho,Om,Ol)['DA_Mpc'] dS = cosmocalc(zs, Ho,Om, Ol)['DA_Mpc'] dLS = (dS*(1.0+zs)-dL*(1.0+zl))/(1.0+zs) sigmacr=cMpc**2.0*dS/(4.0*GG*np.pi*dL*dLS) #mean critical surface mass density in units Mpc^-2 Msolar p200 = 200.0*pcrit #density that is 200 times critical p500 = 500.0*pcrit #density that is 500 times critical r200 = (3.0*M200/(4.0*np.pi*p200))**(1.0/3.0) #radius within which the density is 200 times critical rs = r200/c200 #characteristic radius in Mpc ps = (p200*c200**3.0)/(3.0*(np.log(1.0+c200)-c200/(1.0+c200))) #core density in Msolar Mpc-3 r = np.atleast_1d(r) term = np.where(r <= rs, \ 2.0*np.arctanh(np.sqrt((1.0-(r/rs))/(1.0+(r/rs))))/(np.sqrt(1.0-np.square(r/rs))), \ 2.0*np.arctan(np.sqrt(((r/rs)-1.0)/(1.0+(r/rs))))/(np.sqrt(np.square(r/rs)-1.0))) sigma = 2.0*rs*ps*(1.0-term)/((np.square(r/rs))-1.0) meansigma = 4.0*rs*ps*(term+np.log((r/rs)/2.0))/(np.square(r/rs)) rhoNFW = ps/((r/rs)*np.square(1.0+r/rs)) kappaNFW = sigma/sigmacr #calculate convergence meankappaNFW = meansigma/sigmacr #mean convergence gammaNFW = meankappaNFW-kappaNFW #calculate shear reducedshear = np.abs(gammaNFW)/(1.0-kappaNFW) #calculate reduced shear return reducedshear
def rr(x, pos=None): g = cosmocalc.cosmocalc(10.0**x, H0=71.0) if g['zage_Gyr'] < 1: return "%.2f" % g[ 'zage_Gyr'] # Return 2 dec place if age < 1; e.g 0.62 else: return "%.1f" % g[ 'zage_Gyr'] # Return 1 dec place if age > 1; e.g. 1.5
def plot_lum_rest(): '''f_{rest,V} = f_{rest_corr}*[nu_V/ ((1+z)nu_J)]^beta for flux \propto nu^beta and beta negative values''' clf() f_rest_corr = [ 2252.14, 1626.48, 403.717, 11783.2, 913.329, 549.616, 286.863, 990.110, 14.7689, 174.540, 1419.79, 149309.80115 ] beta = [ -1.35, -0.8, -0.96, -0.22, -1.73, -0.84, -3.48, -0.42, -3.81, -0.3, -1.7, -0.47 ] z_list_limits = [ 1.1588, 2.4274, 1.51, 0.54, 1.95, 1.6, 3.036, 2.346, 3.5, 1.165, 4.8, 0.9382 ] arrf = arr(f_rest_corr) arrb = arr(beta) arrz = arr(z_list_limits) nu_V = 5.444646098003629764065335753176043557e+14 nu_J = 2.398339664e+14 f_rest_V = arrf * (nu_V / ((1 + arrz) * nu_J))**(beta) print 'f_rest_V in microjansky:' print f_rest_V #convert to cgs from microjansky: f_rest_V = f_rest_V * 10**(-29) print 'f_rest_V in cgs:' print f_rest_V #get luminosity distance from cosmocalc (lambdaCDM: omega_M = 0.27 and omega_lambda=0.73) dist = [] for redshift in z_list_limits: dist += [cosmocalc.cosmocalc(z=redshift)['DL_cm']] arrd = arr(dist) print 'dist:' print arrd L_rest_V = f_rest_V * 4 * numpy.pi * arrd**2. / (1. + arrz) print 'L_rest_V:' print L_rest_V #convert to ABSOLUTE AB magnitude: parsec = 3.085677581e18 # cm F_10pc = L_rest_V / (4 * numpy.pi * (10 * parsec)**2) #flux density at 10 parsecs Absol_Mag = -2.5 * numpy.log10(F_10pc) - 48.60 #Absolute mag in AB mag hist(Absol_Mag, 6) xlabel('$M_v$', fontsize=27) ylabel('Number', fontsize=28) yticks(arr([0, 1., 2., 3., 4.])) ax = matplotlib.pyplot.gca() ax.set_xlim(ax.get_xlim()[::-1]) # reversing the xlimits savefig('Lum_dist_rest.eps') print 'Done' return Absol_Mag
def comovingVolume(arcmin2, zmin, zmax, H0=70, WM=0.28): """ Calculates the comoving volume between two redshifts when the sky survey has covered :math:`arcmin^{2}` region. :param arcmin2: area on the sky in :math:`arcmin^{2}` :param zmin: redshift of the front part of the volume :param zmax: redshift of the back part of the volume :param H0: Value of the Hubble constant :param WM: Value of the mass density :return: comoving volume between zmin and zmax of arcmin2 solid angle in Mpc**3 """ front = cosmocalc(zmin, H0, WM)['VCM_Gpc3'] back = cosmocalc(zmax, H0, WM)['VCM_Gpc3'] volume = (back - front) * 1e9 * arcminSquaredToSolidAnge(arcmin2) return volume
def comovingVolume(arcmin2, zmin, zmax, H0=70, WM=0.28): """ Calculates the comoving volume between two redshifts when the sky survey has covered :math:`arcmin^{2}` region. :param arcmin2: area on the sky in :math:`arcmin^{2}` :param zmin: redshift of the front part of the volume :param zmax: redshift of the back part of the volume :param H0: Value of the Hubble constant :param WM: Value of the mass density :return: comoving volume between zmin and zmax of arcmin2 solid angle in Mpc**3 """ front = cosmocalc(zmin, H0, WM)["VCM_Gpc3"] back = cosmocalc(zmax, H0, WM)["VCM_Gpc3"] volume = (back - front) * 1e9 * arcminSquaredToSolidAnge(arcmin2) return volume
def calc_Vmax(zef, l, bins, zup, zlo, skyarea, getLF=True, table=False): Vmax = [] dz = 0.1 if not type(zef) == float: z = [min(zup, ze) for ze in zef] else: z = 0.5 * (zup + zlo) * (1 + numpy.zeros(len(l))) print 'here?' V1 = [cosmocalc(zi, H0=Ho, WM=wm)['VCM_Gpc3'] * 1e9 for zi in z] V2 = cosmocalc(zlo, H0=Ho, WM=wm)['VCM_Gpc3'] * 1e9 #zmean = (z + zlo)/2 V1 = numpy.array(V1) vmax_old = skyarea * (V1 - V2) / (4 * pi) for i in range(len(z)): zup = z[i] z_i = zlo vmax = 0 while z_i < zup: V1 = cosmocalc(z_i, H0=Ho, WM=wm)['VCM_Gpc3'] * 1e9 z_i += dz V2 = cosmocalc(z_i, H0=Ho, WM=wm)['VCM_Gpc3'] * 1e9 vmax += skyarea * (V2 - V1) / (4 * pi) Vmax.append(vmax) #print vmax_old[i],vmax #for i in range(len(vmax)): #if vmax[i]<0: # print z[i],zef[i],zup #sys.exit() #for i in range(len(l)): #print 'done with Vmax old ',numpy.mean(vmax_old),' vs new ',numpy.mean(Vmax) Vmax = numpy.array(Vmax) #sys.exit() # Vmax.append(abs(vmax)) if getLF: return lumfunc(l, bins, Vmax, table) else: return Vmax #vmax_old#Vmax
def __init__(self, whichSurvey, manifestf, noiseZones=False, redshiftSlices=False): self.whichSurvey = whichSurvey self.noiseZones = noiseZones self.redshiftSlices = redshiftSlices self.manifestf = manifestf self.manifest = numpy.genfromtxt(self.manifestf) # Extract selected z slices self.manifest = self.manifest[[s - 1 for s in whichRedshiftSlices], :] self.whichRedshiftSlices = whichRedshiftSlices if self.redshiftSlices: # self.datafiles=['%s/sdss_dr12s%i.txt'%(outdir,r) for r in self.whichRedshiftSlices] #(whichSurvey,r) self.datafiles = [ '%s/data_cos_s%i.txt' % (outdir, r) for r in self.whichRedshiftSlices ] #self.datafiles= ['sims/161101b/sim.txt'] self.datafile = self.datafiles[0] self.numRedshiftSlices = len( whichRedshiftSlices) #self.manifest.shape[0] self.redshifts = self.manifest[:, 3] self.redshifts_min = self.manifest[:, 1] self.redshifts_max = self.manifest[:, 2] self.sliceAreasTemp = self.manifest[:, 4] # Needs to be rejigged self.sliceNoisesTemp = self.manifest[:, 5] # Needs to be rejigged self.zsliceData = {} self.dls = {} self.dlds = {} self.Vmax = {} self.sliceAreas = {} self.sliceNoises = {} self.fmag = {} # Rejig z information for r in range(self.numRedshiftSlices): z = self.redshifts[r] z_min = self.redshifts_min[r] z_max = self.redshifts_max[r] dataf = self.datafiles[r] self.zsliceData[z] = self.loadData(dataf) self.dls[z] = cosmocalc(z, H0=Ho, WM=wm)['DCMR_Mpc'] self.fmag[z] = (numpy.log10(lumfuncUtils.get_Lbins(\ [self.zsliceData[z][1][-1]],z,self.dls[z])[0]) - \ numpy.log10(lumfuncUtils.get_Lbins([self.zsliceData[z][1][-2]],z,\ self.dls[z])[0]))/0.4 self.dlds[z] = lumfuncUtils.get_dlds(z, self.dls[z]) self.Vmax[z] = lumfuncUtils.get_Vmax(z_min, z_max) self.sliceAreas[z] = self.sliceAreasTemp[r] self.sliceNoises[z] = self.sliceNoisesTemp[r] elif self.noiseZones: pass return
def calculate_shift( value, redshift, dist, modulus_distance): if dist == -1: dist = (cosmocalc.cosmocalc(redshift, H0=70.4, WM=0.2726, WV=0.7274))['DL_Mpc'] dist *= 1e6 modulus_distance = 5.0*(math.log10(dist) - 1.0) value = 23.9 - 2.5* math.log10(value) #Into AB mag from microJks value -= modulus_distance #Into absolute magnitude return value
def open_anytype(name, cols, zr=[], F='mJy', L=True, S=False, getz=False, Mi=False, ug=False, band='L'): if Mi: cols.append(Mi) if ug: cols.append(ug) cols.append(ug + 1) z, s, mi, u, g = numpy.loadtxt(name, usecols=cols, unpack=True) else: z, s, mi = numpy.loadtxt(name, usecols=cols, unpack=True) else: z, s = numpy.loadtxt(name, usecols=cols, unpack=True) if zr == []: pass else: s = s[numpy.where((z > zr[0]) & (z < zr[1]))] if Mi: mi = mi[numpy.where((z > zr[0]) & (z < zr[1]))] z = z[numpy.where((z > zr[0]) & (z < zr[1]))] if S: if Mi: return s[s > 0], z[s > 0], dl[s > 0], mi[s > 0] return s if F == 'Jy': s *= 1e-26 elif F == 'mJy': s *= 1e-29 else: #uJy s *= 1e-32 dl = [cosmocalc(zi, H0=Ho, WM=wm)['DCMR_Mpc'] for zi in z] dl = numpy.array(dl) * 3.08e22 l = math.pi * 4 * s * dl**2 * (1 + z)**(specindx + 1) if band == 'S': l *= 1 #(1.4/3)**(-.7)#before 27Feb this was just l*=1! if L: if ug: return l[l > 0], z[l > 0], mi[l > 0], u[l > 0], g[l > 0] if Mi: return l[l > 0], z[s > 0], mi[s > 0] if getz: return l[l > 0], z[s > 0] return l[l > 0] print z[0], s[0], l[0], dl[0] print len(l) return calcu_zeff(z, s, dl, l)
def process_stars(sspa, redshift, starmet, starsft): """ sft is in scale factor a """ #------------------------------------------------ #------------------------------------------------ #determine relations between redshift and age aou_cz=cosmocalc.cosmocalc(redshift)['zage_Gyr'] redshifts=numpy.arange(redshift,20,0.1) ages=[] for z in redshifts: aou_z=cosmocalc.cosmocalc(z)['zage_Gyr'] ages.append(aou_cz-aou_z) ages=numpy.array(ages) #------------------------------------------------ #------------------------------------------------ # Main Code print 'Total Number of Stars:',len(starmet) print '-------------------------------' print '-------------------------------' z =(1./starsft)-1 age = numpy.interp(z, redshifts, ages) * 1000. Zi = numpy.abs(sspa['Z'][:, None] - starmet[None, :]).argmin(axis=0) agei = numpy.empty(len(Zi), dtype='intp') for k in range(len(sspa)): mask = k == Zi agei[mask] = \ numpy.abs(sspa['age'][k][None, :] - age[mask][:, None]).argmin(axis=-1) # use rind to quickly access the Zi, agei from the raveled arrays) rind = numpy.int64(numpy.ravel_multi_index((Zi, agei), sspa['age'].shape)) stellar_mass_rec_frac = numpy.float32(sspa['frac']).take(rind) print stellar_mass_rec_frac.dtype return rind, stellar_mass_rec_frac
def process_stars(sspa, redshift, starmet, starsft): """ sft is in scale factor a """ #------------------------------------------------ #------------------------------------------------ #determine relations between redshift and age aou_cz = cosmocalc.cosmocalc(redshift)['zage_Gyr'] redshifts = numpy.arange(redshift, 20, 0.1) ages = [] for z in redshifts: aou_z = cosmocalc.cosmocalc(z)['zage_Gyr'] ages.append(aou_cz - aou_z) ages = numpy.array(ages) #------------------------------------------------ #------------------------------------------------ # Main Code print 'Total Number of Stars:', len(starmet) print '-------------------------------' print '-------------------------------' z = (1. / starsft) - 1 age = numpy.interp(z, redshifts, ages) * 1000. Zi = numpy.abs(sspa['Z'][:, None] - starmet[None, :]).argmin(axis=0) agei = numpy.empty(len(Zi), dtype='intp') for k in range(len(sspa)): mask = k == Zi agei[mask] = \ numpy.abs(sspa['age'][k][None, :] - age[mask][:, None]).argmin(axis=-1) # use rind to quickly access the Zi, agei from the raveled arrays) rind = numpy.int64(numpy.ravel_multi_index((Zi, agei), sspa['age'].shape)) stellar_mass_rec_frac = numpy.float32(sspa['frac']).take(rind) print stellar_mass_rec_frac.dtype return rind, stellar_mass_rec_frac
def plot_lum_rest(): '''f_{rest,V} = f_{rest_corr}*[nu_V/ ((1+z)nu_J)]^beta for flux \propto nu^beta and beta negative values''' clf() f_rest_corr = [2252.14, 1626.48, 403.717, 11783.2, 913.329, 549.616, 286.863, 990.110, 14.7689, 174.540, 1419.79, 149309.80115] beta = [-1.35, -0.8, -0.96, -0.22, -1.73, -0.84, -3.48, -0.42, -3.81, -0.3, -1.7, -0.47] z_list_limits = [1.1588, 2.4274, 1.51, 0.54, 1.95, 1.6, 3.036, 2.346, 3.5, 1.165, 4.8, 0.9382] arrf = arr(f_rest_corr) arrb = arr(beta) arrz = arr(z_list_limits) nu_V = 5.444646098003629764065335753176043557e+14 nu_J = 2.398339664e+14 f_rest_V = arrf * (nu_V/ ((1+arrz)*nu_J))**(beta) print 'f_rest_V in microjansky:' print f_rest_V #convert to cgs from microjansky: f_rest_V = f_rest_V*10**(-29) print 'f_rest_V in cgs:' print f_rest_V #get luminosity distance from cosmocalc (lambdaCDM: omega_M = 0.27 and omega_lambda=0.73) dist = [] for redshift in z_list_limits: dist += [cosmocalc.cosmocalc(z=redshift)['DL_cm']] arrd = arr(dist) print 'dist:' print arrd L_rest_V = f_rest_V*4*numpy.pi*arrd**2./(1.+arrz) print 'L_rest_V:' print L_rest_V #convert to ABSOLUTE AB magnitude: parsec = 3.085677581e18 # cm F_10pc = L_rest_V/(4 * numpy.pi * (10*parsec)**2) #flux density at 10 parsecs Absol_Mag = -2.5*numpy.log10(F_10pc) - 48.60 #Absolute mag in AB mag hist(Absol_Mag,6) xlabel('$M_v$', fontsize=27) ylabel('Number', fontsize=28) yticks(arr([0, 1., 2., 3., 4.])) ax = matplotlib.pyplot.gca() ax.set_xlim(ax.get_xlim()[::-1]) # reversing the xlimits savefig('Lum_dist_rest.eps') print 'Done' return Absol_Mag
def getDiameterDistances(data, redshift=0): """ Calculates a diameter distance in kpc / arc seconds from data for all unique redshifts. The redshift keyword indicates the column of redshifts. :requires: cosmocalc :param: data :param: redshift column :return: diameter distances :rtype: dictionary """ out = {} for x in set(data[:, redshift]): out[x] = cosmocalc(x, 71.0, 0.28)['PS_kpc'] #in kpc / arc seconds return out
def getDiameterDistances(data, redshift=0): """ Calculates a diameter distance in kpc / arc seconds from data for all unique redshifts. The redshift keyword indicates the column of redshifts. :requires: cosmocalc :param: data :param: redshift column :return: diameter distances :rtype: dictionary """ out = {} for x in set(data[:, redshift]): out[x] = cosmocalc(x, 71.0, 0.28)['PS_kpc'] #in kpc / arc seconds return out
def angularDiameterDistance(z, H0=70, WM=0.28): """ The angular diameter distance DA is defined as the ratio of an object's physical transverse size to its angular size (in radians). It is used to convert angular separations in telescope images into proper separations at the source. It is famous for not increasing indefinitely as z to inf; it turns over at z about 1 and thereafter more distant objects actually appear larger in angular size. :param z: redshift :type z: float :param H0: value of the Hubble constant :type H0: float :param WM: :math:`\\Omega_{\\mathrm{matter}}` :type WM: float :return: angular diameter distance :rtype: float """ return cosmocalc(z, H0, WM)["DA"]
def angularDiameterDistance(z, H0=70, WM=0.28): """ The angular diameter distance DA is defined as the ratio of an object's physical transverse size to its angular size (in radians). It is used to convert angular separations in telescope images into proper separations at the source. It is famous for not increasing indefinitely as z to inf; it turns over at z about 1 and thereafter more distant objects actually appear larger in angular size. :param z: redshift :type z: float :param H0: value of the Hubble constant :type H0: float :param WM: :math:`\\Omega_{\\mathrm{matter}}` :type WM: float :return: angular diameter distance :rtype: float """ return cosmocalc(z, H0, WM)['DA']
# kk = np.bitwise_and(obs_spec['wl'] > 3000, obs_spec['wl'] < 9000) i_z = 0 for ccd in db_f.get(filterid).keys(): # Get the filterid filter. f.read(filter_file, path='/%s/%s' % (filterid, ccd)) # For each defined redshift, eval the photometry and store on the database. db_m = db.get('/%s/%s/%s' % (filterid, ccd, 'library')) i_z = 0 for z in np.arange(z_from, z_to, z_step): if z == 0: d_L = 3.08567758e19 # 10 parsec in cm else: d_L = cosmocalc.cosmocalc(z)['DL_cm'] k_cosmo = L_sun / ( 4 * np.pi * np.power(d_L,2) ) O = zcor(obs_spec, z) O['flux'] = O['flux'] * k_cosmo x = spec2filterset(f.filterset, O, dlambda_eff = 3.0) # print 'z', z # print aux0[i_base] # # plt.figure(1) # plt.clf() # plt.plot(O['wl'][kk], O['flux'][kk]) # plt.figure(2)
def Get_fits(ClusterFile): flexscale = True #Because of the BUG! surveys = ['TGSS_alt'] #NVSS,WENNS,FIRST,TGSS print '###==== Step 0: Load pointings for TGSS ====###' pointings = [] for line in open('Surveys/TGSS_pointings.dat'): token = line.rstrip('\n').split() if len(token) < 2 or token[0][0] == '#': continue pointings.append((token[0], SkyCoord(ra=float(token[1]) * u.degree, dec=float(token[2]) * u.degree))) print 'Number of TGSS pointings:', len(pointings) print '###==== Step 1: Load cluster file and get parameters ====###' print 'Opening the file "' + infile + '" to get the clusters for search in image databases' with open(ClusterFile, 'rb') as csvfile: spamreader = csv.reader(csvfile, delimiter=';', quotechar='|') for CL in spamreader: if CL[0] and not CL[0][0] == '#' and CL[0] not in [ o.name for o in ClList ]: Cl_name = CL[0] if CL[12] in ['TRUE'] and Cl_name not in [ '' ]: #If Flag_INCLUDE==TRUE ; and Cl_name not in ['1RXS_J060313.4+421231'] RA = float(CL[2]) # d.XXXX Dec = float(CL[3]) # d.XXXX try: z = float(CL[4]) except: z = 0. cosmoPara = cosmocalc(z, H0=70, WM=0.29, WV=0.71) D_lum = cosmoPara['DL_cm'] # cm plsc = cosmoPara['PS_kpc'] # kpc/'' #create Class object GCl = galaxycluster(name=Cl_name, RA=RA, Dec=Dec, z=z) ClList.append(GCl) print '###==== Step 2: Fork fits files from servers for %s ====###' % ( Cl_name) det_id = Cl_name RA_h = str(RA / 15) # h.XXXX RA_hms = str(ephem.hours(str(decdeg2hms( float(RA))))).replace(':', ' ') # hh mm ss Dec_dms = str(ephem.degrees(str(float(Dec)))).replace( ':', ' ') # dd mm ss RA_hms_p = str(ephem.hours(str(decdeg2hms( float(RA))))).replace(':', '+') # hh+mm+ss Dec_dms_p = str(ephem.degrees(str(float(Dec)))).replace( ':', '+') # dd+mm+ss onempc = 1e3 / plsc #Imagesize = 30 # in Bogensekunden if onempc > 700 and flexscale: imN = ['2+2', '15+15'] imV = ['3+3', '22.5+22.5'] else: imN = ['1+1', '7.5+7.5'] imV = ['2+2', '15+15'] adressnvss = 'http://www.cv.nrao.edu/cgi-bin/postage.pl?ObjName=NVSS-' + det_id + '&RA=' + RA_hms_p + '&Dec=' + Dec_dms_p + '&Size=' + imN[ 0] + '&Cells=' + imN[ 1] + '&Equinox=2000&Type=application/octet-stream' adressfirst = 'http://third.ucllnl.org/cgi-bin/firstcutout?RA=' + RA_h + '&Dec=' + str( Dec ) + '&ImageSize=30&MaxInt=1&ImageType=FITSImage' #Image Size= 1 equals 1 arcmin adressvlss = 'http://www.cv.nrao.edu/cgi-bin/newVLSSpostage.pl?ObjName=VLSS' + det_id + '&RA=' + RA_hms_p + '&Dec=' + Dec_dms_p + '&Size=' + imV[ 0] + '&Cells=' + imV[ 1] + '&Equinox=2000&Type=application/octet-stream' #http://www.cv.nrao.edu/vlss/VLSSpostage.shtml #=== NVSS if 'NVSS' in surveys: print adressnvss for h in range(0, 5): try: web_file = urllib2.urlopen(adressnvss, timeout=18) out_file = open( 'ClusterRegionImages/NVSS/NVSS-' + det_id + '.fits', 'w') out_file.write(web_file.read()) out_file.close() except: continue else: break #=== FIRST if 'FIRST' in surveys: print adressfirst for h in range(0, 5): try: web_file = urllib2.urlopen(adressfirst, timeout=18) out_file = open( 'ClusterRegionImages/FIRST/FIRST-' + det_id + '.fits', 'w') out_file.write(web_file.read()) out_file.close() except: continue else: break #=== VLSS if 'VLSS' in surveys: print adressvlss for h in range(0, 5): try: web_file = urllib2.urlopen(adressvlss, timeout=18) out_file = open( 'ClusterRegionImages/VLSSr/VLSSr-' + det_id + '.fits', 'w') out_file.write(web_file.read()) out_file.close() except: continue else: break #=== WENSS if 'WENNS' in surveys: #Webside is easily callable, mayby only one request neccesairy url = 'http://www.astron.nl/wow' values = { 'POS': RA_hms + ' ' + Dec_dms, 'SIZE': '2.5, 2.5', 'Equinox': 'J2000', 'cutout': 1, 'surv_id': 1 } for h in range(0, 1): #range (0,5) try: data = urllib.urlencode(values) #print 'Data:',data queurl = url + '/testcode.php?' + data print 'WENSSurl:', queurl response = urllib2.urlopen(queurl) print 'Response:', response #print response.read() #print 'Response.geturl():',response.geturl() #print response.info() regionurl = '' for line in response: #print line.rstrip() #== Not used until a Region larger than 1*1 deg can get choosen #if not line.find('.fits.gz">cut') == -1: ##print line #substr = find_between( line , 'class="testo3"><a ', '</a></span><br/>') ##print 'Found in between', substr #regionurl = url + '/' + find_between( substr, 'href=', '.fits.gz>') + ".fits.gz" #print 'Regionurl:',regionurl if not line.find('.GZ</a>') == -1: substr = find_between( line, 'a href="survey1', '</a></span><br/>') #print 'Substr', substr regionurl = url + '/survey1/' + find_between( substr, '/', '.GZ>') + ".GZ" print 'WENSSRegionurl:', regionurl if not regionurl == '': web_file = urllib2.urlopen(regionurl, timeout=18) filename = 'ClusterRegionImages/WENSS/WENSS-' + det_id + '.fits.gz' out_file = open(filename, 'w') out_file.write(web_file.read()) out_file.close() os.system('gzip -d ' + filename) print 'WENSS ok for', det_id, '\n' except: continue else: break #=== TGSS if 'TGSS' in surveys: url = 'http://tgss.ncra.tifr.res.in/cgi-bin/tgss_postage.cgi' values = { 'raval': RA_hms, 'decval': Dec_dms, 'szval': '1.0', 'szunit': 'deg', 'fmtval': 'fits' } for h in range(0, 1): #range (0,5) try: data = urllib.urlencode(values) print 'Data:', data req = urllib2.Request(url, data) print 'Request:', req response = urllib2.urlopen(req) ##print response.read() print 'Response.geturl():', response.geturl() ##print response.info() regionurl = '' for line in response: #print line.rstrip() if not line.find( '<a href="opendat/tgss_') == -1: regionurl = 'http://tgss.ncra.tifr.res.in/' + find_between( line, "<a href=", ">") print 'TGSSurl:', regionurl if not regionurl == '': web_file = urllib2.urlopen(regionurl, timeout=18) out_file = open( 'ClusterRegionImages/TGSS/TGSS-' + det_id + '.fits', 'w') out_file.write(web_file.read()) out_file.close() print 'TGSS ok for', det_id, '\n' except: continue else: break #=== TGSS altenrative if 'TGSS_alt' in surveys: try: size = os.path.getsize( os.path.join( os.path.abspath("."), 'Images_TGSS/TGSS-' + det_id + '.fits')) except: size = -1 if size < 10000: if size > 0: os.remove( os.path.join( os.path.abspath("."), 'Images_TGSS/TGSS-' + det_id + '.fits')) print 'Target ' + det_id + ' was not found in the TGSS-catalogue. It is going to be downloaded.' ClusterPos = SkyCoord(ra=RA * u.degree, dec=Dec * u.degree) dist = [ p[1].separation(ClusterPos) for p in pointings ] mindist = min(dist) print 'TGSS-field minimal distance:', mindist index = dist.index(mindist) cutname = pointings[index][0] url = 'http://vo.astron.nl/tgssadr/q_fits/imgs/form' # http://vo.astron.nl/tgssadr/q_fits/imgs/form/login?nextURL=http%3A%2F%2Fvo.astron.nl%2Ftgssadr%2Fq_fits%2Fimgs%2Fform values = { 'hPOS': '%8.4f , %8.4f' % (RA, Dec), 'hSIZE': 0.5, '_FORMAT': "HTML", 'submit': 'submit' } #_queryForm" for h in range(0, 1): #range (0,5) try: #data = urllib.urlencode(values) #print 'Data:',data #req = urllib2.Request(url, data) #print 'Request:',req #response = urllib2.urlopen(req) ###print response.read() #print 'Response.geturl():',response.geturl() ##print response.info() #regionurl = '' #for line in response: ##print line.rstrip() #if not line.find('<a href="opendat/tgss_') == -1: #regionurl = 'http://tgss.ncra.tifr.res.in/' + find_between( line , "<a href=", ">") #print 'TGSSurl:',regionurl regionurl = 'http://vo.astron.nl/getproduct/tgssadr/fits/TGSSADR_%s_5x5.MOSAIC.FITS' % ( cutname ) #<a href="http://vo.astron.nl/getproduct/tgssadr/fits/TGSSADR_R43D11_5x5.MOSAIC.FITS" class="productlink">TGSSADR_R43D11_5x5.MOSAIC.FITS</a> print regionurl if not regionurl == '': web_file = urllib2.urlopen(regionurl, timeout=18) out_file = open( 'Images_TGSS/TGSS-' + det_id + '.fits', 'w') #out_file = open('ClusterRegionImages/TGSS/TGSS-' + det_id + '.fits', 'w') out_file.write(web_file.read()) out_file.close() print 'TGSS ok for', det_id, '\n' except: continue else: break else: print 'Target ' + det_id + ' already in the TGSS-catalogue' #import re #s = 'asdf=5;iwantthis123jasd' #result = re.search('asdf=5;(.*)123jasd', s) #print result.group(1) #import re #r = re.compile('Master(.*?)thon') #m = r.search(str1) #if m: #lyrics = m.group(1) #from urllib2 import Request, urlopen, URLError #req = Request(someurl) #try: #response = urlopen(req) #except URLError as e: #if hasattr(e, 'reason'): #print 'We failed to reach a server.' #print 'Reason: ', e.reason #elif hasattr(e, 'code'): #print 'The server couldn\'t fulfill the request.' #print 'Error code: ', e.code #else: ## everything is fine #Somehow Bugy #try: #if os.path.getsize(os.path.join(os.path.abspath("."), 'ClusterRegionImages/NVSS/NVSS-' + det_id + '.fits') ) < 500: #os.remove(os.path.join(os.path.abspath("."), 'ClusterRegionImages/NVSS/NVSS-' + det_id + '.fits')) #print 'Target ' + det_id + ' was not found in the NVSS-catalogue' #except: #print 'Target ' + det_id + ' was not found in the NVSS-catalogue, there was also no junk file' #else: #print 'Target ' + det_id + ' was not found in the NVSS-catalogue, there was also no junk file!' #try: #if os.path.getsize(os.path.join(os.path.abspath("."), 'ClusterRegionImages/FIRST/FIRST-' + det_id + '.fits') ) < 10000: #os.remove(os.path.join(os.path.abspath("."), 'ClusterRegionImages/FIRST/FIRST-' + det_id + '.fits')) #print 'Target ' + det_id + ' was not found in the FIRST-catalogue' #except: #print 'Target ' + det_id + ' was not found in the FIRST-catalogue, there was also no junk file' #else: #print 'Target ' + det_id + ' was not found in the FIRST-catalogue, there was also no junk file' #try: #if os.path.getsize(os.path.join(os.path.abspath("."), 'ClusterRegionImages/VLSSr/VLSSr-' + det_id + '.fits') ) < 500: #os.remove(os.path.join(os.path.abspath("."), 'ClusterRegionImages/VLSSr/VLSSr-' + det_id + '.fits')) #print 'Target ' + det_id + ' was not found in the VLSS-catalogue' #except: #print 'Target ' + det_id + ' was not found in the VLSS-catalogue, there was also no junk file' #else: #print 'Target ' + det_id + ' was not found in the VLSS-catalogue, there was also no junk file' #if os.path.getsize(os.path.join(os.path.abspath("."), 'ClusterRegionImages/TGSS/TGSS-' + det_id + '.fits') ) < 10000: #os.remove(os.path.join(os.path.abspath("."), 'ClusterRegionImages/TGSS/TGSS-' + det_id + '.fits')) #print 'Target ' + det_id + ' was not found in the TGSS-catalogue' #print >> file, "%6.0f"%det_id, "%12s"%ra_hms, "%13s"%dec_dms, "%6.2f"%z, "%8.2f"%L, "%6.2f"%scale, "%8.2f"%onempc return
def search_sdss(blazardir='/Users/willettk/Astronomy/Research/blazars/',blazarfile='plotkin_dr8_upload.txt',savstring='',envsize=1000,ngals=1000, save=False, timing=True): import sqlcl import cosmocalc import time timestart = time.time() # Read in the list of blazars from combined catalogs (Plotkin, BZCAT, TeVcat) pf = open(blazardir+blazarfile,'r') # Python dictionary for the relevant data to be returned sdss_data_zns = { 'objid':[], 'ra':[], 'dec':[], 'type':[], 'nchild':[], 'u':[], 'g':[], 'r':[], 'i':[], 'z':[], 'p_el':[], 'p_cw':[], 'p_acw':[], 'p_edge':[], 'p_dk':[], 'p_mg':[], 'p_cs':[], 'blazar_name':[] } sdss_data_zs = { 'objid':[], 'ra':[], 'dec':[], 'type':[], 'nchild':[], 'u':[], 'g':[], 'r':[], 'i':[], 'z':[], 'p_el':[], 'p_cw':[], 'p_acw':[], 'p_edge':[], 'p_dk':[], 'p_mg':[], 'p_cs':[], 'blazar_name':[] } sdss_data_nozoo = { 'objid':[], 'ra':[], 'dec':[], 'type':[], 'nchild':[], 'u':[], 'g':[], 'r':[], 'i':[], 'z':[], 'blazar_name':[] } errorarr = {'type':[],'name':[]} for line in pf: # blazar_name, blazar_ra, blazar_dec, blazar_z, blazar_type = line.split() blazar_z = float(blazar_z) # # Compute the angular size of 1000 kpc # platescale = cosmocalc.cosmocalc(z=blazar_z, H0=71, WM=0.27)['PS_kpc'] # kpc per arcsec angsize = envsize / platescale / 60. # # Query the SDSS DR8 catalog # blazar_query_zns = """ SELECT top %i p.objID, p.ra, p.dec, p.type, p.nchild, p.u, p.g, p.r, p.i, p.z, zns.p_el, zns.p_cw, zns.p_acw, zns.p_edge, zns.p_dk, zns.p_mg, zns.p_cs FROM fGetNearbyObjEq(%f,%f,%f) n JOIN PhotoObj p on p.objid = n.objid JOIN zooNoSpec zns on zns.objid = n.objid ORDER BY p.objID """ % (ngals, float(blazar_ra), float(blazar_dec), angsize) blazar_query_zs = """ SELECT top %i p.objID, p.ra, p.dec, p.type, p.nchild, p.u, p.g, p.r, p.i, p.z, zs.p_el, zs.p_cw, zs.p_acw, zs.p_edge, zs.p_dk, zs.p_mg, zs.p_cs FROM fGetNearbyObjEq(%f,%f,%f) n JOIN PhotoObj p on p.objid = n.objid JOIN zooSpec zs on zs.objid = n.objid ORDER BY p.objID """ % (ngals, float(blazar_ra), float(blazar_dec), angsize) blazar_query_nozoo = """ SELECT top %i p.objID, p.ra, p.dec, p.type, p.nchild, p.u, p.g, p.r, p.i, p.z FROM fGetNearbyObjEq(%f,%f,%f) n JOIN PhotoObj p on p.objid = n.objid ORDER BY p.objID """ % (ngals, float(blazar_ra), float(blazar_dec), angsize) # bqtime = time.time() # queryreturn_zns = sqlcl.query(blazar_query_zns, fmt='csv') queryreturn_zs = sqlcl.query(blazar_query_zs, fmt='csv') queryreturn_nozoo = sqlcl.query(blazar_query_nozoo, fmt='csv') # lqtime = time.time() # # Make sure queries do not exceed 60 per minute (intrinsic limit of database) # if (lqtime - bqtime) < 3.1: time.sleep(3.1 - (lqtime - bqtime)) # qr_read_zns = queryreturn_zns.read() qr_read_zs = queryreturn_zs.read() qr_read_nozoo = queryreturn_nozoo.read() # # Print detections to the screen # if (qr_read_zns[:26] != 'No objects have been found') and (qr_read_zns[:5] != 'ERROR'): print blazar_name # qrsplit = qr_read_zns.split() print qrsplit[1:] for n in arange(len(qrsplit[1:]))+1: neighbor_data = qrsplit[n].split(',') sdss_data_zns['objid'].append(neighbor_data[0]) sdss_data_zns['ra'].append(neighbor_data[1]) sdss_data_zns['dec'].append(neighbor_data[2]) sdss_data_zns['type'].append(neighbor_data[3]) sdss_data_zns['nchild'].append(neighbor_data[4]) sdss_data_zns['u'].append(neighbor_data[5]) sdss_data_zns['g'].append(neighbor_data[6]) sdss_data_zns['r'].append(neighbor_data[7]) sdss_data_zns['i'].append(neighbor_data[8]) sdss_data_zns['z'].append(neighbor_data[9]) sdss_data_zns['p_el'].append(neighbor_data[10]) sdss_data_zns['p_cw'].append(neighbor_data[11]) sdss_data_zns['p_acw'].append(neighbor_data[12]) sdss_data_zns['p_edge'].append(neighbor_data[13]) sdss_data_zns['p_dk'].append(neighbor_data[14]) sdss_data_zns['p_mg'].append(neighbor_data[15]) sdss_data_zns['p_cs'].append(neighbor_data[16]) sdss_data_zns['blazar_name'].append(blazar_name) if (qr_read_zs[:26] != 'No objects have been found') and (qr_read_zs[:5] != 'ERROR'): print blazar_name # qrsplit = qr_read_zs.split() print qrsplit[1:] for n in arange(len(qrsplit[1:]))+1: neighbor_data = qrsplit[n].split(',') sdss_data_zs['objid'].append(neighbor_data[0]) sdss_data_zs['ra'].append(neighbor_data[1]) sdss_data_zs['dec'].append(neighbor_data[2]) sdss_data_zs['type'].append(neighbor_data[3]) sdss_data_zs['nchild'].append(neighbor_data[4]) sdss_data_zs['u'].append(neighbor_data[5]) sdss_data_zs['g'].append(neighbor_data[6]) sdss_data_zs['r'].append(neighbor_data[7]) sdss_data_zs['i'].append(neighbor_data[8]) sdss_data_zs['z'].append(neighbor_data[9]) sdss_data_zs['p_el'].append(neighbor_data[10]) sdss_data_zs['p_cw'].append(neighbor_data[11]) sdss_data_zs['p_acw'].append(neighbor_data[12]) sdss_data_zs['p_edge'].append(neighbor_data[13]) sdss_data_zs['p_dk'].append(neighbor_data[14]) sdss_data_zs['p_mg'].append(neighbor_data[15]) sdss_data_zs['p_cs'].append(neighbor_data[16]) sdss_data_zs['blazar_name'].append(blazar_name) if (qr_read_nozoo[:26] != 'No objects have been found') and (qr_read_nozoo[:5] != 'ERROR'): print blazar_name # qrsplit = qr_read_nozoo.split() print qrsplit[1:] for n in arange(len(qrsplit[1:]))+1: neighbor_data = qrsplit[n].split(',') sdss_data_nozoo['objid'].append(neighbor_data[0]) sdss_data_nozoo['ra'].append(neighbor_data[1]) sdss_data_nozoo['dec'].append(neighbor_data[2]) sdss_data_nozoo['type'].append(neighbor_data[3]) sdss_data_nozoo['nchild'].append(neighbor_data[4]) sdss_data_nozoo['u'].append(neighbor_data[5]) sdss_data_nozoo['g'].append(neighbor_data[6]) sdss_data_nozoo['r'].append(neighbor_data[7]) sdss_data_nozoo['i'].append(neighbor_data[8]) sdss_data_nozoo['z'].append(neighbor_data[9]) sdss_data_nozoo['blazar_name'].append(blazar_name) if qr_read_zns[:5] == 'ERROR': errorarr['type'].append('zns') errorarr['name'].append(blazar_name) if qr_read_zs[:5] == 'ERROR': errorarr['type'].append('zs') errorarr['name'].append(blazar_name) if qr_read_nozoo[:5] == 'ERROR': errorarr['type'].append('nozoo') errorarr['name'].append(blazar_name) if save is True: import pickle # Save dictionary to file so it doesn't have to be rerun output = open('sdss_'+str(envsize)+'kpc_zns'+str(savstring)+'.pkl', 'w') pickle.dump(sdss_data_zns, output) output.close() output = open('sdss_'+str(envsize)+'kpc_zs'+str(savstring)+'.pkl', 'w') pickle.dump(sdss_data_zs, output) output.close() output = open('sdss_'+str(envsize)+'kpc_nozoo'+str(savstring)+'.pkl', 'w') pickle.dump(sdss_data_nozoo, output) output.close() print "Saved dictionaries to file" endtime = time.time() print 'Total time elapsed is %5.2f min' % ((endtime - starttime)*60)
def rr(x, pos=None): g = cosmocalc.cosmocalc(10.0 ** x, H0=71.0) if g["zage_Gyr"] < 1: return "%.2f" % g["zage_Gyr"] # Return 2 dec place if age < 1; e.g 0.62 else: return "%.1f" % g["zage_Gyr"] # Return 1 dec place if age > 1; e.g. 1.5
def plot_lum_rest(): '''f_{rest,V} = f_{rest_corr}*[nu_V/ ((1+z)nu_J)]^beta for flux \propto nu^beta and beta negative values''' clf() # # those are values from the lightcurve, where I have 3minutes*(1+z) = t_0, and then I get the value of of the lightcurve at t_0 # # me: right but what function # # Pierre: most of them are interpolations from Dan Perley's fits # 10:07 AM # some actually have values at times that are very close to 3 minutes *(1+z) and for those I just use the actual data points # f_rest_corr = [2252.14, 1626.48, 403.717, 11783.2, 913.329, 549.616, 286.863, 990.110, 14.7689, 174.540, 1419.79, 149309.80115] # beta = [-1.35, -0.8, -0.96, -0.22, -1.73, -0.84, -3.48, -0.42, -3.81, -0.3, -1.7, -0.47] beta = df_grb.beta # z_list_limits = [1.1588, 2.4274, 1.51, 0.54, 1.95, 1.6, 3.036, 2.346, 3.5, 1.165, 4.8, 0.9382] z_list_limits = df_grb.z arrb = arr(beta) arrz = arr(z_list_limits) # nu_V = 5.444646098003629764065335753176043557e+14 # nu_J = 2.398339664e+14 nu_V = qObs.V.freq nu_J = qObs.J.freq nu_K = qObs.Ks.freq nu_H = qObs.H.freq abs_mag = [] for nu_obs, f_obs in [(nu_J, jz3corrhost), (nu_H, hz3corrhost), (nu_K, kz3corrhost)]: arrf = arr(f_obs) f_rest_V = arrf * (nu_V / ((1 + arrz) * nu_obs))**(beta) print 'f_rest_V in microjansky:' print f_rest_V #convert to cgs from microjansky: f_rest_V = f_rest_V * 10**(-29) print 'f_rest_V in cgs:' print f_rest_V #get luminosity distance from cosmocalc (lambdaCDM: omega_M = 0.27 and omega_lambda=0.73) dist = [] for redshift in z_list_limits: dist += [cosmocalc.cosmocalc(z=redshift)['DL_cm']] arrd = arr(dist) print 'dist:' print arrd L_rest_V = f_rest_V * 4 * numpy.pi * arrd**2. / (1. + arrz) print 'L_rest_V:' print L_rest_V #convert to ABSOLUTE AB magnitude: parsec = 3.085677581e18 # cm F_10pc = L_rest_V / (4 * numpy.pi * (10 * parsec)**2) #flux density at 10 parsecs F_10pc = F_10pc.fillna(-1).astype('float') # type problems.. Absol_Mag = -2.5 * numpy.log10(F_10pc) - 48.60 #Absolute mag in AB mag abs_mag.append(Absol_Mag) plt.hist(np.array(abs_mag[1]), bins=np.linspace(-33.8, -25.5, 9), histtype='stepfilled', color=hc, linewidth=0, alpha=0.15) plt.hist(np.array(abs_mag[0]), bins=np.linspace(-33.8, -25.5, 9), histtype='stepfilled', color=jc, linewidth=0, alpha=0.15) plt.hist(np.array(abs_mag[2]), bins=np.linspace(-33.8, -25.5, 9), histtype='stepfilled', color=kc, linewidth=0, alpha=0.15) plt.hist(np.array(abs_mag[1]), bins=np.linspace(-33.8, -25.5, 9), histtype='step', color=hc, linewidth=11, label="$H$ detection") plt.hist(np.array(abs_mag[0]), bins=np.linspace(-33.8, -25.5, 9), histtype='step', color=jc, linewidth=7, label="$J$ detection") plt.hist(np.array(abs_mag[2]), bins=np.linspace(-33.8, -25.5, 9), histtype='step', color=kc, linewidth=3, label="$K$ detection") switch = -0.2 for ind in Absol_Mag.index[::-1]: # plt.text(Absol_Mag.loc[ind],1.0,ind,rotation=90,ha='center',va='center',fontsize=12) # plt.annotate(ind,xy=(abs_mag[0].loc[ind],0),xytext=(abs_mag[0].loc[ind],0.6-switch),color=jc,arrowprops=dict(arrowstyle="->",connectionstyle="arc3",color=jc),rotation=90,ha='center',va='center',fontsize=14) # plt.annotate(ind,xy=(abs_mag[1].loc[ind],0),xytext=(abs_mag[1].loc[ind],1.6-switch),color=hc,arrowprops=dict(arrowstyle="->",connectionstyle="arc3",color=hc),rotation=90,ha='center',va='center',fontsize=14) # plt.annotate(ind,xy=(abs_mag[2].loc[ind],0),xytext=(abs_mag[2].loc[ind],2.6-switch),color=kc,arrowprops=dict(arrowstyle="->",connectionstyle="arc3",color=kc),rotation=90,ha='center',va='center',fontsize=14) # plt.annotate(ind, xy=(abs_mag[1].loc[ind], 0), xytext=(abs_mag[1].loc[ind], offsets[ind]), color='dimgray', arrowprops=dict(arrowstyle="->", connectionstyle="arc3", color='gray', lw=2), rotation=90, ha='center', va='center', bbox=dict(boxstyle="round", fc="whitesmoke", ec="gray", lw=2), fontsize=16) switch *= -1 # hist(Absol_Mag,6,color="#88CCEE") plt.xlabel('Absolute Magnitude $M_V$', fontsize=20) plt.ylabel('Number', fontsize=20) plt.yticks(arr([0, 1., 2., 3., 4., 5., 6.])) ax = matplotlib.pyplot.gca() ax.set_xlim(ax.get_xlim()[::-1]) # reversing the xlimits ax.set_xlim((-24, -35)) ax.set_ylim((0, 3.5)) plt.title('$t=3$ min (rest frame)', fontsize=20) plt.legend(loc='upper left', fontsize=18, frameon=False) plt.savefig('Lum_dist_rest.eps') plt.savefig('Lum_dist_rest.png') print 'Done' return abs_mag
def quickPlot(galaxies=170, rvir=0.105): """ A single halo test :param galaxies: number of subhalo galaxies :param rvir: radius of the main halo [Mpc] """ conversion = 0.000277777778 # degree to arcsecond #redshift z = 4.477 #get the angular diameter distance to the galaxy dd = cosmocalc(z, 71.0, 0.28)['PS_kpc'] #in kpc / arc seconds #position of the main galaxy RADeg1 = 189.41432 decDeg1 = 62.166702 # get the random values rds = rand.randomUnitSphere(galaxies) # convert them to Cartesian coord rd = conv.convertSphericalToCartesian(rvir / dd / 2., rds['theta'], rds['phi']) data = { 'CD': np.matrix('-1 0; 0 1'), 'RA': RADeg1, 'DEC': decDeg1, 'X': rd['y'], 'Y': rd['z'] } result = conv.RAandDECfromStandardCoordinates(data) RADeg2 = result['RA'] decDeg2 = result['DEC'] #calculate the angular separation on the sky sep = Coords.calcAngSepDeg(RADeg1, decDeg1, RADeg2, decDeg2) / 2. physical_distance = sep * dd / conversion text = r'Random Positions, z={0:.2f}, radius of the halo = {1:.0f} kpc'.format( z, 1e3 * rvir) #make a figure fig = plt.figure(figsize=(12, 12)) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) rect = fig.add_subplot(224, visible=False).get_position() ax4 = Axes3D(fig, rect) ax1.hist(sep * 1e4, bins=12) ax2.hist(physical_distance, bins=12) ax3.scatter(0, 0, c='k', s=120, marker='s') ax3.scatter((RADeg2 - RADeg1) * 1e4, (decDeg2 - decDeg1) * 1e4, c='b', s=50, marker='o', alpha=0.45) #generate a sphere u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) #plot it as a wire frame ax4.plot_wireframe(x * 1e4 * rvir / dd, y * 1e4 * rvir / dd, z * 1e4 * rvir / dd, rstride=10, cstride=10, color='0.5', alpha=0.7) #plot the random points ax4.scatter(rd['x'] * 2e4, rd['y'] * 2e4, rd['z'] * 2e4, color='b', s=30, alpha=0.8) ax1.set_xlabel(r'Projected Separation [$10^{-4}$ deg]') ax2.set_xlabel(r'Projected Distance [kpc]') ax3.set_xlabel(r'$\Delta$RA [$10^{-4}$ deg]') #ax4.set_xlabel(r'$\Delta$RA [$10^{-4}$ deg]') ax3.set_ylabel(r'$\Delta$DEC [$10^{-4}$ deg]') #ax4.set_ylabel(r'$\Delta$DEC [$10^{-4}$ deg]') ax3.set_xlim(-200, 200) ax3.set_ylim(-100, 100) ax4.set_xlim3d(-150, 150) ax4.set_ylim3d(-150, 150) ax4.set_zlim3d(-150, 150) plt.annotate(text, (0.5, 0.95), xycoords='figure fraction', ha='center', va='center', fontsize=12) plt.savefig('RandomHalo.pdf')
pos_z_d = [pos_z[i] for i in w] print len(StellarMass_d), ' galaxies diluted' # ------------------------------------- # plot stellar mass function print 'plotting SMF...' # set up figure plt.figure() ax = plt.subplot(111) if (cone == True): volume = cosmocalc(Redshift_Depth, H0=Hubble_h*100.0)['VCM_Gpc3'] * (1000.0**3.0) * (oangle/41253.0) * factor else: volume = (BoxSize / Hubble_h)**3.0 binwidth = 0.1 mass = [np.log10(StellarMass[i] * 1.0e10 / Hubble_h) for i in xrange(len(StellarMass))] # sSFR = [Sfr[i] / (StellarMass[i] * 1.0e10 / Hubble_h) for i in xrange(len(StellarMass))] mi = 5.0 ma = 15.0 NB = (ma - mi) / binwidth (counts, binedges) = np.histogram(mass, range=(mi, ma), bins=NB) # Set the x-axis values to be the centre of the bins
def plot_stellarmasses(path, database, cut, redshifts, out_folder, obs_data, solid_angle=1.077 * 10 ** -5, ymin=10 ** 3, ymax=2 * 10 ** 6, xmin=0.5, xmax=100, nbins=15, sigma=3.0, H0=70.0, WM=0.28, zmax=6.0, write_out=False): ''' 160 square arcminutes in steradians = 1.354*10**-5 sr (steradians) Simulation was 10 times the GOODS realization, so the solid angle is 1.354*10**-4 :param sigma: sigma level of the errors to be plotted :param nbins: number of bins (for simulated data) :param area: actually 1 / area, used to weight galaxies ''' #fudge factor to handle errors that are way large fudge = ymin #subplot numbers columns = 2 rows = 3 #get data query = '''select galprop.mstar from galprop, FIR where galprop.gal_id = FIR.gal_id and galprop.halo_id = FIR.halo_id and %s''' % cut masses_limit = db.sqlite.get_data_sqlite(path, database, query) query = '''select galprop.mstar from galprop, FIR where galprop.gal_id = FIR.gal_id and galprop.halo_id = FIR.halo_id''' masses_total = db.sqlite.get_data_sqlite(path, database, query) #make the figure fig = P.figure() P.subplots_adjust(wspace=0.0, hspace=0.0) ax = P.subplot(rows, columns, 1) #get the co-moving volume to the backend vol = cosmocalc(zmax, H0, WM)['VCM_Gpc3'] #weight each galaxy wghts = N.zeros(len(masses_total)) + (1. / (solid_angle * vol * 1e9)) #calculate the differential stellar mass function #with log binning b, n, nu = df.diff_function_log_binning(masses_total, wgth=wghts, mmax=xmax, mmin=xmin, nbins=nbins, log=True) #get the knots x = 10 ** b y = n #plot the knots mtot = ax.plot(x, y, 'k-') #poisson error mask = nu > 0 err = (1. / (solid_angle * vol * 1e9)) * N.sqrt(nu[mask]) * sigma up = y[mask] + err lw = y[mask] - err lw[lw < ymin] = ymin stot = ax.fill_between(x[mask], up, lw, color='#728FCE') #limited mass wghts = N.zeros(len(masses_limit)) + (1. / (solid_angle * vol * 1e9)) b, n, nu = df.diff_function_log_binning(masses_limit, wgth=wghts, mmax=xmax, mmin=xmin, nbins=nbins, log=True) #get the knots x = 10 ** b y = n #plot the knots mlim = ax.plot(x, y, 'r-') #poisson error mask = nu > 0 err = (1. / (solid_angle * vol * 1e9)) * N.sqrt(nu[mask]) * sigma up = y[mask] + err lw = y[mask] - err lw[lw < ymin] = ymin slim = ax.fill_between(x[mask], up, lw, color='red') #write to the file if needed, using appending so might get long... if write_out: fh = open(out_folder + 'outputTotal.txt', 'a') fh.write('#Mstellar[log10(M_sun)] dN/dlog10(M_sun) high low\n') for aa, bb, cc, dd in zip(x[mask], y[mask], up, lw): fh.write('%e %e %e %e\n' % (aa, bb, cc, dd)) fh.close() #add annotation ax.annotate('Total', (0.5, 0.9), xycoords='axes fraction', ha='center') #set scale ax.set_xscale('log') ax.set_yscale('log') ax.set_xlim(10 ** xmin, 10 ** xmax) ax.set_ylim(ymin, ymax) ax.set_xticklabels([]) ptot = P.Rectangle((0, 0), 1, 1, fc='#728FCE') plim = P.Rectangle((0, 0), 1, 1, fc='red') sline = '%i$\sigma$ errors' % sigma P.legend((mtot, ptot, plim), ('All Galaxies', sline, '$S_{250} > 5$ mJy')) #redshift limited plots for i, red in enumerate(redshifts): query = '''select galprop.mstar from galprop, FIR where galprop.gal_id = FIR.gal_id and galprop.halo_id = FIR.halo_id and %s''' % (red) mtotal = db.sqlite.get_data_sqlite(path, database, query) query = '''select galprop.mstar from galprop, FIR where galprop.gal_id = FIR.gal_id and galprop.halo_id = FIR.halo_id and %s and %s''' % (cut, red) mlimit = db.sqlite.get_data_sqlite(path, database, query) #modify redshift string tmp = red.split() rtitle = r'$%s < z \leq %s$' % (tmp[2], tmp[6]) #make a subplot axs = P.subplot(rows, columns, i + 2) #get a comoving volume to the back end volb = cosmocalc(float(tmp[6]), H0, WM)['VCM_Gpc3'] volf = cosmocalc(float(tmp[2]), H0, WM)['VCM_Gpc3'] #weights wgvol = (1. / (solid_angle * volb * 1e9)) # wgvol = (1./(solid_angle*(volb-volf)*1e9)) wghts = N.zeros(len(mtotal)) + wgvol b, n, nu = df.diff_function_log_binning(mtotal, wgth=wghts, mmax=xmax, mmin=xmin, nbins=nbins, log=True) x = 10 ** b y = n #plot the knots axs.plot(x, y, 'k-') #poisson error mask = nu > 0 err = wgvol * N.sqrt(nu[mask]) * sigma up = y[mask] + err lw = y[mask] - err lw[lw < ymin] = ymin axs.fill_between(x[mask], up, lw, color='#728FCE') #limited mass wghts = N.zeros(len(mlimit)) + wgvol b, n, nu = df.diff_function_log_binning(mlimit, wgth=wghts, mmax=xmax, mmin=xmin, nbins=nbins, log=True) x = 10 ** b y = n #plot the knots axs.plot(x, y, 'r-') #poisson error mask = nu > 0 err = wgvol * N.sqrt(nu[mask]) * sigma up = y[mask] + err lw = y[mask] - err lw[lw < ymin] = ymin axs.fill_between(x[mask], up, lw, color='red') #write to output if write_out: fh = open(out_folder + 'outputredshiftbin%i.txt' % i, 'a') fh.write('#' + rtitle + '\n') fh.write('#Mstellar[log10(M_sun)] dN/dlog10(M_sun) high low\n') for aa, bb, cc, dd in zip(x[mask], y[mask], up, lw): fh.write('%e %e %e %e\n' % (aa, bb, cc, dd)) fh.close() #add annotation axs.annotate(rtitle, (0.5, 0.9), xycoords='axes fraction', ha='center') #set scales axs.set_xscale('log') axs.set_yscale('log') axs.set_xlim(10 ** xmin, 10 ** xmax) axs.set_ylim(ymin, ymax) #remove unnecessary ticks and add units if i % 2 == 0: axs.set_yticklabels([]) if i == 2 or i == 3: axs.set_xlabel(r'$M_{\star} \quad [M_{\odot}]$') if i == 2: axs.set_xticks(axs.get_xticks()[1:]) else: axs.set_xticklabels([]) if i == 1: axs.set_ylabel(r'$\frac{dN}{d \log_{10} M_{\star}} \ [Mpc^{-3} \ dex^{-1}]$') #save figure P.savefig(out_folder + 'stellarmassfunction.ps') P.close()
tmp = matched[matched[:, 3] == x] #redshift z = tmp[0][0] RADeg1 = tmp[0][1] decDeg1 = tmp[0][2] RADeg2 = tmp[1:, 1] decDeg2 = tmp[1:, 2] prop = tmp[:, 5] sep = Coords.calcAngSepDeg(RADeg1, decDeg1, RADeg2, decDeg2) dd = cosmocalc(z, 71.0, 0.28)['PS_kpc'] #dist.getDiameterDistances(data) physical_distance = (sep / dd) / conversion print z, RADeg1, RADeg2, decDeg1, decDeg2, prop print sep, physical_distance print ax.plot([z for foo in range(len(physical_distance))], physical_distance, 'bo') #P.show() print print cursor.execute('CREATE TABLE newTable (h1, g1, h2, g2, foo)') newqu = """INSERT INTO newTable
def plot_stellarmasses(path, database, cut, redshifts, out_folder, obs_data, solid_angle=1.077 * 10**-5, ymin=10**3, ymax=2 * 10**6, xmin=0.5, xmax=100, nbins=15, sigma=3.0, H0=70.0, WM=0.28, zmax=6.0, write_out=False): ''' 160 square arcminutes in steradians = 1.354*10**-5 sr (steradians) Simulation was 10 times the GOODS realization, so the solid angle is 1.354*10**-4 :param sigma: sigma level of the errors to be plotted :param nbins: number of bins (for simulated data) :param area: actually 1 / area, used to weight galaxies ''' #fudge factor to handle errors that are way large fudge = ymin #subplot numbers columns = 2 rows = 3 #get data query = '''select galprop.mstar from galprop, FIR where galprop.gal_id = FIR.gal_id and galprop.halo_id = FIR.halo_id and %s''' % cut masses_limit = db.sqlite.get_data_sqlite(path, database, query) query = '''select galprop.mstar from galprop, FIR where galprop.gal_id = FIR.gal_id and galprop.halo_id = FIR.halo_id''' masses_total = db.sqlite.get_data_sqlite(path, database, query) #make the figure fig = P.figure() P.subplots_adjust(wspace=0.0, hspace=0.0) ax = P.subplot(rows, columns, 1) #get the co-moving volume to the backend vol = cosmocalc(zmax, H0, WM)['VCM_Gpc3'] #weight each galaxy wghts = N.zeros(len(masses_total)) + (1. / (solid_angle * vol * 1e9)) #calculate the differential stellar mass function #with log binning b, n, nu = df.diff_function_log_binning(masses_total, wgth=wghts, mmax=xmax, mmin=xmin, nbins=nbins, log=True) #get the knots x = 10**b y = n #plot the knots mtot = ax.plot(x, y, 'k-') #poisson error mask = nu > 0 err = (1. / (solid_angle * vol * 1e9)) * N.sqrt(nu[mask]) * sigma up = y[mask] + err lw = y[mask] - err lw[lw < ymin] = ymin stot = ax.fill_between(x[mask], up, lw, color='#728FCE') #limited mass wghts = N.zeros(len(masses_limit)) + (1. / (solid_angle * vol * 1e9)) b, n, nu = df.diff_function_log_binning(masses_limit, wgth=wghts, mmax=xmax, mmin=xmin, nbins=nbins, log=True) #get the knots x = 10**b y = n #plot the knots mlim = ax.plot(x, y, 'r-') #poisson error mask = nu > 0 err = (1. / (solid_angle * vol * 1e9)) * N.sqrt(nu[mask]) * sigma up = y[mask] + err lw = y[mask] - err lw[lw < ymin] = ymin slim = ax.fill_between(x[mask], up, lw, color='red') #write to the file if needed, using appending so might get long... if write_out: fh = open(out_folder + 'outputTotal.txt', 'a') fh.write('#Mstellar[log10(M_sun)] dN/dlog10(M_sun) high low\n') for aa, bb, cc, dd in zip(x[mask], y[mask], up, lw): fh.write('%e %e %e %e\n' % (aa, bb, cc, dd)) fh.close() #add annotation ax.annotate('Total', (0.5, 0.9), xycoords='axes fraction', ha='center') #set scale ax.set_xscale('log') ax.set_yscale('log') ax.set_xlim(10**xmin, 10**xmax) ax.set_ylim(ymin, ymax) ax.set_xticklabels([]) ptot = P.Rectangle((0, 0), 1, 1, fc='#728FCE') plim = P.Rectangle((0, 0), 1, 1, fc='red') sline = '%i$\sigma$ errors' % sigma P.legend((mtot, ptot, plim), ('All Galaxies', sline, '$S_{250} > 5$ mJy')) #redshift limited plots for i, red in enumerate(redshifts): query = '''select galprop.mstar from galprop, FIR where galprop.gal_id = FIR.gal_id and galprop.halo_id = FIR.halo_id and %s''' % (red) mtotal = db.sqlite.get_data_sqlite(path, database, query) query = '''select galprop.mstar from galprop, FIR where galprop.gal_id = FIR.gal_id and galprop.halo_id = FIR.halo_id and %s and %s''' % (cut, red) mlimit = db.sqlite.get_data_sqlite(path, database, query) #modify redshift string tmp = red.split() rtitle = r'$%s < z \leq %s$' % (tmp[2], tmp[6]) #make a subplot axs = P.subplot(rows, columns, i + 2) #get a comoving volume to the back end volb = cosmocalc(float(tmp[6]), H0, WM)['VCM_Gpc3'] volf = cosmocalc(float(tmp[2]), H0, WM)['VCM_Gpc3'] #weights wgvol = (1. / (solid_angle * volb * 1e9)) # wgvol = (1./(solid_angle*(volb-volf)*1e9)) wghts = N.zeros(len(mtotal)) + wgvol b, n, nu = df.diff_function_log_binning(mtotal, wgth=wghts, mmax=xmax, mmin=xmin, nbins=nbins, log=True) x = 10**b y = n #plot the knots axs.plot(x, y, 'k-') #poisson error mask = nu > 0 err = wgvol * N.sqrt(nu[mask]) * sigma up = y[mask] + err lw = y[mask] - err lw[lw < ymin] = ymin axs.fill_between(x[mask], up, lw, color='#728FCE') #limited mass wghts = N.zeros(len(mlimit)) + wgvol b, n, nu = df.diff_function_log_binning(mlimit, wgth=wghts, mmax=xmax, mmin=xmin, nbins=nbins, log=True) x = 10**b y = n #plot the knots axs.plot(x, y, 'r-') #poisson error mask = nu > 0 err = wgvol * N.sqrt(nu[mask]) * sigma up = y[mask] + err lw = y[mask] - err lw[lw < ymin] = ymin axs.fill_between(x[mask], up, lw, color='red') #write to output if write_out: fh = open(out_folder + 'outputredshiftbin%i.txt' % i, 'a') fh.write('#' + rtitle + '\n') fh.write('#Mstellar[log10(M_sun)] dN/dlog10(M_sun) high low\n') for aa, bb, cc, dd in zip(x[mask], y[mask], up, lw): fh.write('%e %e %e %e\n' % (aa, bb, cc, dd)) fh.close() #add annotation axs.annotate(rtitle, (0.5, 0.9), xycoords='axes fraction', ha='center') #set scales axs.set_xscale('log') axs.set_yscale('log') axs.set_xlim(10**xmin, 10**xmax) axs.set_ylim(ymin, ymax) #remove unnecessary ticks and add units if i % 2 == 0: axs.set_yticklabels([]) if i == 2 or i == 3: axs.set_xlabel(r'$M_{\star} \quad [M_{\odot}]$') if i == 2: axs.set_xticks(axs.get_xticks()[1:]) else: axs.set_xticklabels([]) if i == 1: axs.set_ylabel( r'$\frac{dN}{d \log_{10} M_{\star}} \ [Mpc^{-3} \ dex^{-1}]$') #save figure P.savefig(out_folder + 'stellarmassfunction.ps') P.close()
def read_sdss(read_full_lines=True): """ Read MPA-JHU SDSS libraries. If 'read_full_lines' is set, then also read the full line catalog with fluxes etc. This is a big file so can take more time/memory. """ import unicorn.paper1 import cosmocalc sdss_path = unicorn.GRISM_HOME + 'ANALYSIS/SDSS/' print 'SDSS ICLASS...' if unicorn.paper1.sdss_iclass is None: unicorn.paper1.sdss_iclass = pyfits.open( sdss_path + 'gal_iclass_dr7_v5_2.fits')[0].data print 'SDSS Info, redshifts etc....' if unicorn.paper1.sdss_info is None: unicorn.paper1.sdss_info = pyfits.open( sdss_path + 'gal_info_dr7_v5_2.fits')[1].data if read_full_lines: print 'SDSS Full line data...' if unicorn.paper1.sdss_line is None: unicorn.paper1.sdss_line = pyfits.open( sdss_path + 'gal_line_dr7_v5_2.fits')[1].data print 'SDSS Total SFR...' if unicorn.paper1.sdss_totsfr is None: unicorn.paper1.sdss_totsfr = pyfits.open( sdss_path + 'gal_totsfr_dr7_v5_2.fits')[1].data print 'SDSS Total Specific SFR...' if unicorn.paper1.sdss_totspecsfr is None: unicorn.paper1.sdss_totspecsfr = pyfits.open( sdss_path + 'gal_totspecsfr_dr7_v5_2.fits')[1].data print 'SDSS Total stellar mass...' if unicorn.paper1.sdss_logm is None: unicorn.paper1.sdss_logm = pyfits.open(sdss_path + 'totlgm_dr7_v5_2.fits')[1].data print 'SDSS O/H abundances...' if unicorn.paper1.sdss_fiboh is None: unicorn.paper1.sdss_fiboh = pyfits.open( sdss_path + 'gal_fiboh_dr7_v5_2.fits')[1].data print 'SDSS-VAGC Sersic fits...' if unicorn.paper1.sdss_sersic is None: unicorn.paper1.sdss_sersic = pyfits.open(sdss_path + 'sersic_catalog.fits')[1].data # print 'SDSS-VAGC Coords...' if unicorn.paper1.sdss_vagc is None: unicorn.paper1.sdss_vagc = pyfits.open(sdss_path + 'object_catalog.fits')[1].data print 'Match between catalogs' if unicorn.paper1.idx_mpa_vagc is None: unicorn.paper1.idx_mpa_vagc = np.loadtxt(sdss_path + 'mpa_vagc.match', dtype=np.int) #### Keep only matches from VAGC unicorn.paper1.sdss_sersic = unicorn.paper1.sdss_sersic[ unicorn.paper1.idx_mpa_vagc] #### Get R50 in kpc zgrid = np.arange(100) / 100. * 4 + 1. / 100 scale = zgrid * 0. for i in range(100): cc = cosmocalc.cosmocalc(zgrid[i]) scale[i] = cc['PS_kpc'] unicorn.paper1.sdss_sersic.SERSIC_R50_i_KPC = unicorn.paper1.sdss_sersic.SERSIC_R50[:, 3] * np.interp( unicorn.paper1.sdss_info.Z, zgrid, scale)
def testRandomizer(): #calculate a test case conversion = 0.000277777778 # degree to arcsecond #random distance between z = 0 and 5 z = np.random.rand() * 5.0 #random separation of the main galaxy and the subhalo physical_distance = np.random.rand() * 1e3 #in kpc #get the angular diameter distance to the galaxy dd1 = cosmocalc(z, 71.0, 0.28)['PS_kpc'] #in kpc / arc seconds dd = (physical_distance / dd1) * conversion # to degrees # RA and DEC of the main galaxy, first one in GOODS south ra_main = 52.904892 #in degrees dec_main = -27.757082 #in degrees # get the random position rds = rand.randomUnitSphere(points=1) # convert the position to Cartesian coord # when dd is the radius of the sphere coordinates # the dd is in units of degrees here so the results # are also in degrees. rd = conv.convertSphericalToCartesian(dd, rds['theta'], rds['phi']) # Make the assumption that x is towards the observer # z is north and y is west. Now if we assume that our z and y # are Standard Coordinates, i.e., the projection of the RA and DEC # of an object onto the tangent plane of the sky. We can now # assume that the y coordinate is aligned with RA and the z coordinate # is aligned with DEC. The origin of this system is at the tangent point # in the dark matter halo. # Poor man's solution to the problem would be: new_ra = ra_main - (rd['y'][0] / np.cos(rd['z'][0])) new_dec = dec_main + rd['z'][0] # However, this only works if one is away from the pole. # More general solution can be derived using spherical geometry: data = {} data['CD'] = np.matrix('-1 0; 0 1') data['RA'] = ra_main data['DEC'] = dec_main data['X'] = rd['y'][0] data['Y'] = rd['z'][0] result = conv.RAandDECfromStandardCoordinates(data) #print the output print 'Redshift of the galaxy is %.3f while the subhaloes distance is %0.2f kpc' % ( z, physical_distance) print '\nCoordinates of the main halo galaxy are (RA and DEC):' print '%.7f %.7f' % (ra_main, dec_main) print astCoords.decimal2hms(ra_main, ':'), astCoords.decimal2dms(dec_main, ':') print '\nCoordinates for the subhalo galaxy are (RA and DEC):' print '%.7f %.7f' % (new_ra, new_dec) print astCoords.decimal2hms(new_ra, ':'), astCoords.decimal2dms(new_dec, ':') print 'or when using more accurate technique' print '%.7f %.7f' % (result['RA'], result['DEC']) print astCoords.decimal2hms(result['RA'], ':'), astCoords.decimal2dms( result['DEC'], ':') #print 'Shift in RA and DEC [degrees]:' #print rd['y'][0], (rd['z'][0]/np.cos(rd['z'][0])) print '\nShift in RA and DEC [seconds]:' print -rd['y'][0] / np.cos( rd['z'][0]) / conversion, rd['z'][0] / conversion print 'or again with the better method:' print(result['RA'] - ra_main) / conversion, (result['DEC'] - dec_main) / conversion
def quickPlot(galaxies=170, rvir=0.105): """ A single halo test :param galaxies: number of subhalo galaxies :param rvir: radius of the main halo [Mpc] """ conversion = 0.000277777778 # degree to arcsecond #redshift z = 4.477 #get the angular diameter distance to the galaxy dd = cosmocalc(z, 71.0, 0.28)['PS_kpc'] #in kpc / arc seconds #position of the main galaxy RADeg1 = 189.41432 decDeg1 = 62.166702 # get the random values rds = rand.randomUnitSphere(galaxies) # convert them to Cartesian coord rd = conv.convertSphericalToCartesian(rvir/dd/2., rds['theta'], rds['phi']) data = {'CD': np.matrix('-1 0; 0 1'), 'RA': RADeg1, 'DEC': decDeg1, 'X': rd['y'], 'Y': rd['z']} result = conv.RAandDECfromStandardCoordinates(data) RADeg2 = result['RA'] decDeg2 = result['DEC'] #calculate the angular separation on the sky sep = Coords.calcAngSepDeg(RADeg1, decDeg1, RADeg2, decDeg2) / 2. physical_distance = sep * dd / conversion text = r'Random Positions, z={0:.2f}, radius of the halo = {1:.0f} kpc'.format(z, 1e3 * rvir) #make a figure fig = plt.figure(figsize=(12,12)) ax1 = fig.add_subplot(221) ax2 = fig.add_subplot(222) ax3 = fig.add_subplot(223) rect = fig.add_subplot(224, visible=False).get_position() ax4 = Axes3D(fig, rect) ax1.hist(sep * 1e4, bins=12) ax2.hist(physical_distance, bins=12) ax3.scatter(0, 0, c='k', s=120, marker='s') ax3.scatter((RADeg2 - RADeg1) * 1e4, (decDeg2 - decDeg1) * 1e4, c='b', s=50, marker='o', alpha=0.45) #generate a sphere u = np.linspace(0, 2 * np.pi, 100) v = np.linspace(0, np.pi, 100) x = np.outer(np.cos(u), np.sin(v)) y = np.outer(np.sin(u), np.sin(v)) z = np.outer(np.ones(np.size(u)), np.cos(v)) #plot it as a wire frame ax4.plot_wireframe(x*1e4*rvir/dd, y*1e4*rvir/dd, z*1e4*rvir/dd, rstride=10, cstride=10, color='0.5', alpha=0.7) #plot the random points ax4.scatter(rd['x']*2e4, rd['y']*2e4, rd['z']*2e4, color='b', s=30, alpha=0.8) ax1.set_xlabel(r'Projected Separation [$10^{-4}$ deg]') ax2.set_xlabel(r'Projected Distance [kpc]') ax3.set_xlabel(r'$\Delta$RA [$10^{-4}$ deg]') #ax4.set_xlabel(r'$\Delta$RA [$10^{-4}$ deg]') ax3.set_ylabel(r'$\Delta$DEC [$10^{-4}$ deg]') #ax4.set_ylabel(r'$\Delta$DEC [$10^{-4}$ deg]') ax3.set_xlim(-200, 200) ax3.set_ylim(-100, 100) ax4.set_xlim3d(-150, 150) ax4.set_ylim3d(-150, 150) ax4.set_zlim3d(-150, 150) plt.annotate(text, (0.5, 0.95), xycoords='figure fraction', ha='center', va='center', fontsize=12) plt.savefig('RandomHalo.pdf')
flux_sdss_synth = np.array(flux_sdss_synth) goodness = s.chisquare(flux_sdss_corr[1:], flux_sdss_synth) absolute_goodness = goodness[0] / 3 # UV Synthetic equivalent fluxes ------------------------------------------------------------------------------- ## Only necessary for the example plot (with arrows) # k = np.abs(wavelengths_galex[0] - synthetic_wavelengths).argmin() # fuv_synth_flux = synthetic_fluxes[k] # # m = np.abs(wavelengths_galex[1] - synthetic_wavelengths).argmin() # nuv_synth_flux = synthetic_fluxes[m] # Absolute Magnitudes using Luminosity Distance ---------------------------------------------------------------- # This is optional to calculate,so for now it will be kept commented ------------------------------------------- luminosity_distance = cosmo.cosmocalc(redshift[index])["DL_Mpc"] # mag_fuv_abs = mag_fuv_dered_fm - 5 * np.log10(luminosity_distance) - 25 # mag_nuv_abs = mag_nuv_dered_fm - 5 * np.log10(luminosity_distance) - 25 mag_u_abs = mag_ab_u[index] - 5 * np.log10(luminosity_distance) - 25 mag_g_abs = mag_ab_g[index] - 5 * np.log10(luminosity_distance) - 25 mag_r_abs = mag_ab_r[index] - 5 * np.log10(luminosity_distance) - 25 mag_i_abs = mag_ab_i[index] - 5 * np.log10(luminosity_distance) - 25 mag_z_abs = mag_ab_z[index] - 5 * np.log10(luminosity_distance) - 25 # SDSS Fluxes Uncertainty -------------------------------------------------------------------------------------- model_mag_err_sdss_index = model_mag_err_sdss[index][0] sigma_flux = [] for i in range(sdss_mag_dered[index].size): if fiber_correction == 1: sigma_fiber_corr_square = 0.0 else:
def _get_angdist(self): if self._angdist is None: cc = cosmocalc(self.redshift) self._angdist = cc['DA_cm'] return self._angdist
#!/usr/bin/env python from pylab import* from matplotlib.ticker import AutoMinorLocator import numpy from lumfuncUtils import get_dl, get_Vmax,get_dsdl,get_z from utils import * from cosmocalc import cosmocalc Ho=70.0 wm=0.3 zbins =[0.1, 0.4, 0.6, 0.8, 1.0, 1.3, 1.6, 2.0, 2.5, 3.2, 4.0] t= [cosmocalc(zi,H0=70,WM = 0.3)['zage_Gyr'] for zi in zbins] BIN_COL = -1 SURVEY_NOISE=2.5 # uJy rc('legend', fontsize=23) def sfr(m,z,So=2.8,a1=0.23,a2=0.13,mo=10.8): return So - a1*z-numpy.log10(1+(10**(mo-a2*z)/10**(m))) def phi(m,m_star,phi1,phi2,a,b): m_m=10**(m-m_star) #print m_star, phi1,phi2,a,b sk=numpy.log(10)* (phi1*(m_m)**(a+1) + phi2*(m_m)**(1+b)) mf=numpy.exp(-m_m)*sk #print numpy.exp(-m_m) return mf #5 0.28<z<0.36, 7 0.45<z<0.56 9 0.68<z<0.82 10 0.82<z<1 11 1<z<1.2 13 1.45<z<1.75 #14 1.75<z<2.2 15 2.2<z<2.6 16 2.6z3.25 17 3.25z3.75 w_18=[[10.88 , -0.55 , -1.536, -2.555, -3.4 , 8.388, 1.592],\
def fried_plot(blazardir='/Users/willettk/Astronomy/Research/blazars/',blazarfile='plotkin_dr8_upload.txt',loaddata=True, envsize = 1000): from pylab import * import pickle import coords import cosmocalc # Retrieve data from saved file if loaddata is True: pkl_file = open(blazardir+'sdss_'+str(envsize)+'kpc_zns.pkl', 'r') sdss_data_zns = pickle.load(pkl_file) pkl_file.close() pkl_file = open(blazardir+'sdss_'+str(envsize)+'kpc_zs.pkl', 'r') sdss_data_zs = pickle.load(pkl_file) pkl_file.close() pkl_file = open(blazardir+'sdss_'+str(envsize)+'kpc_nozoo.pkl', 'r') sdss_data_nozoo = pickle.load(pkl_file) pkl_file.close() print "Loaded data from saved files." nz = sdss_data_nozoo zns = sdss_data_zns zs = sdss_data_zs # Reproduce Figure 1 in Fried et al. (1993), determining whether galaxy surface density for BL Lacs changes with galactocentric radius # Bin by redshift; start with the Fried+ bins at median z of 0.28, 0.65, 0.97 (bin widths of z ~ 0.30) # Quantities to plot: # - distance from host [kpc] # Dictionaries have the Python ID number, RA, and dec # Reload the original list of blazars; assume closest object to the center (choose cone radius and redshift) is the host galaxy. # For the remainder, convert angular distance to linear. Still assuming no redshift dependence? # Make a cut in apparent magnitude at r < 22 (identical to Fried paper) r = array(nz['r'],dtype='f') rind = where(r < 22) sdss_name = array(nz['blazar_name'])[rind[0]] sdss_ra = array(nz['ra'])[rind[0]] sdss_dec = array(nz['dec'])[rind[0]] angseparr = [] physseparr = [] angseparr_low = [] angseparr_mid = [] angseparr_hi = [] physseparr_low = [] physseparr_mid = [] physseparr_hi = [] b_ra = [] b_dec = [] z_low = [] z_mid = [] z_hi = [] pf = open(blazardir+blazarfile,'r') for line in pf: # blazar_name, blazar_ra, blazar_dec, blazar_z = line.split() if blazar_name != 'Plotkin_BLLac637': blazar_z = float(blazar_z) ind1 = list(sdss_name).index(blazar_name) ind2 = list(sdss_name).index(blazar_name[:-3]+'%(var)03d' % {'var':float(blazar_name[-3:])+1}) ra = sdss_ra dec = sdss_dec b_ra.append(blazar_ra) b_dec.append(blazar_dec) b_radec = (float(blazar_ra),float(blazar_dec)) for galaxy in arange(ind1,ind2): s_radec = (float(ra[galaxy]),float(dec[galaxy])) sdss_coords = coords.Position(s_radec) blazar_coords = coords.Position(b_radec) sep = sdss_coords.angsep(blazar_coords) platescale = cosmocalc.cosmocalc(z=blazar_z, H0=71, WM=0.27)['PS_kpc'] # kpc per arcsec sep_arcmin = sep.arcsec() / 60 sep_kpc = platescale*sep.arcsec() angseparr.append(sep_arcmin) physseparr.append(sep_kpc) if blazar_z < 0.46: angseparr_low.append(sep_arcmin) physseparr_low.append(sep_kpc) z_low.append(blazar_z) elif (blazar_z > 0.46) and (blazar_z < 0.81): angseparr_mid.append(sep_arcmin) physseparr_mid.append(sep_kpc) z_mid.append(blazar_z) elif (blazar_z > 0.81 and blazar_z < 1.048): angseparr_hi.append(sep_arcmin) physseparr_hi.append(sep_kpc) z_hi.append(blazar_z) # - galaxy surface density [N_gal / sq. arcmin] # Bin galaxies into bins of 100 kpc each (galactocentric distance) # For the galaxies at each distance from the host object, find the average number of galaxies per square arcminute in that field bins_kpc = (arange(10)+1)*100 bins_arcmin_low = zeros(10) bins_arcmin_mid = zeros(10) bins_arcmin_hi = zeros(10) for b in arange(10): bins_arcmin_low[b] = (bins_kpc[b]/cosmocalc.cosmocalc(z=0.28,H0=71, WM=0.27)['PS_kpc'] / 60) bins_arcmin_mid[b] = (bins_kpc[b]/cosmocalc.cosmocalc(z=0.65,H0=71, WM=0.27)['PS_kpc'] / 60) bins_arcmin_hi[b] = (bins_kpc[b]/cosmocalc.cosmocalc(z=0.97,H0=71, WM=0.27)['PS_kpc'] / 60) hist_low = np.histogram(angseparr_low,bins=bins_arcmin_low) hist_mid = np.histogram(angseparr_mid,bins=bins_arcmin_mid) hist_hi = np.histogram(angseparr_hi ,bins=bins_arcmin_hi ) # Assume the plate scale is for the median redshift in each distance class area_low = np.pi * ((array(bins_arcmin_low[1:10]))**2 - (array(bins_arcmin_low[0:9]))**2) area_mid = np.pi * ((array(bins_arcmin_mid[1:10]))**2 - (array(bins_arcmin_mid[0:9]))**2) area_hi = np.pi * ((array(bins_arcmin_hi[1:10]))**2 - (array(bins_arcmin_hi[0:9]))**2) density_low = hist_low[0] / area_low density_mid = hist_mid[0] / area_mid density_hi = hist_hi[0] / area_hi fig = figure(2) clf() ############### # Sort r-band magnitudes into redshift bins ############### subplot(321) hist_physsep = hist(r[:ind2],bins=arange(10,30),color='k') hist_physsep = hist(r[rind][:ind2],bins=arange(10,30),color='w') xlabel(r'$m_r$') ylabel(r'$N_{gal}$') subplot(323) hist_physsep_low = hist(physseparr_low,color='r') hist_physsep_mid = hist(physseparr_mid,color='g') hist_physsep_hi = hist(physseparr_hi,color='b') xlabel('Physical separation [kpc]') ylabel(r'$N_{gal}$') subplot(325) plot(b_ra, b_dec, 'kx') xlabel('RA') ylabel('Dec') ylim(-30,90) subplot(322) errorbar(bins_kpc[1:10], density_low/len(density_low), yerr=sqrt(density_low), color='r', fmt='o') xlabel('Physical separation [kpc]') ylabel(r'$N_{gal}/sq. arcmin$') xlim(0,1000) title(r'$\langle z\rangle = %f$' % mean(z_low)) axhline(y=mean(density_low),color='r',linewidth=2) subplot(324) errorbar(bins_kpc[1:10], density_mid/len(density_mid), yerr=sqrt(density_mid), color='g', fmt='o') xlabel('Physical separation [kpc]') ylabel(r'$N_{gal}/sq. arcmin$') xlim(0,1000) title(r'$\langle z\rangle = %f$' % mean(z_mid)) axhline(y=mean(density_mid),color='g',linewidth=2) subplot(326) errorbar(bins_kpc[1:10], density_hi/len(density_hi), yerr = sqrt(density_hi), color='b', fmt='o') xlabel('Physical separation [kpc]') ylabel(r'$N_{gal}/sq. arcmin$') xlim(0,1000) title(r'$\langle z\rangle = %f$' % mean(z_hi)) axhline(y=mean(density_hi),color='b',linewidth=2) subplots_adjust(hspace=0.5)
os.system('mkdir '+p.output_dir+'/neb') os.system('mkdir '+p.output_dir+'/SEDs') os.system('mkdir '+p.output_dir+'/StellarSEDs') #------------------- # for nebula emission nebula_lines = {'Peta': {0.0040000000000000001: 0.0184, 0.050000000000000003: 0.0184, 0.0080000000000000002: 0.0184, 0.00040000000000000002: 0.0184, 'l': 9014.8999999999996, 0.02: 0.0184}, '[OIII]4363.00': {0.0040000000000000001: 0.066000000000000003, 0.050000000000000003: 0.01, 0.0080000000000000002: 0.01, 0.00040000000000000002: 0.109, 'l': 4363.0, 0.02: 0.01}, '[NII]6583.45': {0.0040000000000000001: 0.17499999999999999, 0.050000000000000003: 0.40400000000000003, 0.0080000000000000002: 0.40400000000000003, 0.00040000000000000002: 0.014999999999999999, 'l': 6583.4499999999998, 0.02: 0.40400000000000003}, '[NII]5755.00': {0.0040000000000000001: 0.0, 0.050000000000000003: 0.01, 0.0080000000000000002: 0.01, 0.00040000000000000002: 0.0, 'l': 5755.0, 0.02: 0.01}, 'Hkappa': {0.0040000000000000001: 0.030550000000000001, 0.050000000000000003: 0.030550000000000001, 0.0080000000000000002: 0.030550000000000001, 0.00040000000000000002: 0.030550000000000001, 'l': 3750.0, 0.02: 0.030550000000000001}, 'Ptheta': {0.0040000000000000001: 0.0138, 0.050000000000000003: 0.0138, 0.0080000000000000002: 0.0138, 0.00040000000000000002: 0.0138, 'l': 8862.7999999999993, 0.02: 0.0138}, '[NII]6548.05': {0.0040000000000000001: 0.058999999999999997, 0.050000000000000003: 0.13600000000000001, 0.0080000000000000002: 0.13600000000000001, 0.00040000000000000002: 0.0050000000000000001, 'l': 6548.0500000000002, 0.02: 0.13600000000000001}, '[SII]6730.00': {0.0040000000000000001: 0.13800000000000001, 0.050000000000000003: 0.20999999999999999, 0.0080000000000000002: 0.20999999999999999, 0.00040000000000000002: 0.029000000000000001, 'l': 6730.0, 0.02: 0.20999999999999999}, '[OIII]1663.0': {0.0040000000000000001: 0.058000000000000003, 0.050000000000000003: 0.01, 0.0080000000000000002: 0.01, 0.00040000000000000002: 0.0, 'l': 1663.0, 0.02: 0.01}, '[OI]': {0.0040000000000000001: 0.041000000000000002, 0.050000000000000003: 0.13, 0.0080000000000000002: 0.13, 0.00040000000000000002: 0.0080000000000000002, 'l': 6300.0, 0.02: 0.13}, 'Htheta': {0.0040000000000000001: 0.053039999999999997, 0.050000000000000003: 0.053039999999999997, 0.0080000000000000002: 0.053039999999999997, 0.00040000000000000002: 0.053039999999999997, 'l': 3797.0, 0.02: 0.053039999999999997}, 'Hiota': {0.0040000000000000001: 0.039750000000000001, 0.050000000000000003: 0.039750000000000001, 0.0080000000000000002: 0.039750000000000001, 0.00040000000000000002: 0.039750000000000001, 'l': 3770.0, 0.02: 0.039750000000000001}, '[NI]': {0.0040000000000000001: 0.01, 0.050000000000000003: 0.029999999999999999, 0.0080000000000000002: 0.029999999999999999, 0.00040000000000000002: 0.0030000000000000001, 'l': 5199.0, 0.02: 0.029999999999999999}, '[CII]1335.0': {0.0040000000000000001: 0.0, 0.050000000000000003: 0.11, 0.0080000000000000002: 0.11, 0.00040000000000000002: 0.0, 'l': 1335.0, 0.02: 0.11}, '[SII]10336.41': {0.0040000000000000001: 0.0, 0.050000000000000003: 0.050000000000000003, 0.0080000000000000002: 0.050000000000000003, 0.00040000000000000002: 0.0, 'l': 10336.41, 0.02: 0.050000000000000003}, 'Heta': {0.0040000000000000001: 0.07306, 0.050000000000000003: 0.07306, 0.0080000000000000002: 0.07306, 0.00040000000000000002: 0.07306, 'l': 3835.0, 0.02: 0.07306}, 'Pgamma': {0.0040000000000000001: 0.090399999999999994, 0.050000000000000003: 0.090399999999999994, 0.0080000000000000002: 0.090399999999999994, 0.00040000000000000002: 0.090399999999999994, 'l': 10938.1, 0.02: 0.090399999999999994}, 'P12': {0.0040000000000000001: 0.0106, 0.050000000000000003: 0.0106, 0.0080000000000000002: 0.0106, 0.00040000000000000002: 0.0106, 'l': 8750.5, 0.02: 0.0106}, '[OIII]5006.84': {0.0040000000000000001: 4.7519999999999998, 0.050000000000000003: 4.0810000000000004, 0.0080000000000000002: 4.0810000000000004, 0.00040000000000000002: 3.1589999999999998, 'l': 5006.8400000000001, 0.02: 4.0810000000000004}, '[OII]3727.0': {0.0040000000000000001: 1.7909999999999999, 0.050000000000000003: 3.0099999999999998, 0.0080000000000000002: 3.0099999999999998, 0.00040000000000000002: 0.48899999999999999, 'l': 3727.0, 0.02: 3.0099999999999998}, '[NII]2141.0': {0.0040000000000000001: 0.0, 0.050000000000000003: 0.01, 0.0080000000000000002: 0.01, 0.00040000000000000002: 0.0, 'l': 2141.0, 0.02: 0.01}, '[NeIII]': {0.0040000000000000001: 0.41599999999999998, 0.050000000000000003: 0.29999999999999999, 0.0080000000000000002: 0.29999999999999999, 0.00040000000000000002: 0.29499999999999998, 'l': 3869.0, 0.02: 0.29999999999999999}, '[ArIII]7751.11': {0.0040000000000000001: 0.17599999999999999, 0.050000000000000003: 0.085999999999999993, 0.0080000000000000002: 0.085999999999999993, 0.00040000000000000002: 0.067000000000000004, 'l': 7751.1099999999997, 0.02: 0.085999999999999993}, 'Hxi': {0.0040000000000000001: 0.1051, 0.050000000000000003: 0.1051, 0.0080000000000000002: 0.1051, 0.00040000000000000002: 0.1051, 'l': 3889.0, 0.02: 0.1051}, '[HeI]6678.00': {0.0040000000000000001: 0.029999999999999999, 0.050000000000000003: 0.029999999999999999, 0.0080000000000000002: 0.029999999999999999, 0.00040000000000000002: 0.025999999999999999, 'l': 6678.0, 0.02: 0.029999999999999999}, 'H18': {0.0040000000000000001: 0.0090600000000000003, 0.050000000000000003: 0.0090600000000000003, 0.0080000000000000002: 0.0090600000000000003, 0.00040000000000000002: 0.0090600000000000003, 'l': 3692.0, 0.02: 0.0090600000000000003}, 'Pbeta': {0.0040000000000000001: 0.16300000000000001, 0.050000000000000003: 0.16300000000000001, 0.0080000000000000002: 0.16300000000000001, 0.00040000000000000002: 0.16300000000000001, 'l': 12818.1, 0.02: 0.16300000000000001}, 'H_epsilon + [NeIII]': {0.0040000000000000001: 0.28299999999999997, 0.050000000000000003: 0.159, 0.0080000000000000002: 0.159, 0.00040000000000000002: 0.27000000000000002, 'l': 3970.0, 0.02: 0.159}, 'Bdelta': {0.0040000000000000001: 0.01915, 0.050000000000000003: 0.01915, 0.0080000000000000002: 0.01915, 0.00040000000000000002: 0.01915, 'l': 19445.0, 0.02: 0.01915}, ' H_zeta+ [HeI]': {0.0040000000000000001: 0.192, 0.050000000000000003: 0.107, 0.0080000000000000002: 0.107, 0.00040000000000000002: 0.20300000000000001, 'l': 3889.0, 0.02: 0.107}, '[HeI]}': {0.0040000000000000001: 0.035999999999999997, 0.050000000000000003: 0.050000000000000003, 0.0080000000000000002: 0.050000000000000003, 0.00040000000000000002: 0.035999999999999997, 'l': 4471.0, 0.02: 0.050000000000000003}, '[SIII]6312.0': {0.0040000000000000001: 0.017000000000000001, 0.050000000000000003: 0.029999999999999999, 0.0080000000000000002: 0.029999999999999999, 0.00040000000000000002: 0.0089999999999999993, 'l': 6312.0, 0.02: 0.029999999999999999}, 'H13': {0.0040000000000000001: 0.02401, 0.050000000000000003: 0.02401, 0.0080000000000000002: 0.02401, 0.00040000000000000002: 0.02401, 'l': 3735.0, 0.02: 0.02401}, 'H14': {0.0040000000000000001: 0.019210000000000001, 0.050000000000000003: 0.019210000000000001, 0.0080000000000000002: 0.019210000000000001, 0.00040000000000000002: 0.019210000000000001, 'l': 3723.0, 0.02: 0.019210000000000001}, 'H15': {0.0040000000000000001: 0.01562, 0.050000000000000003: 0.01562, 0.0080000000000000002: 0.01562, 0.00040000000000000002: 0.01562, 'l': 3713.0, 0.02: 0.01562}, 'H16': {0.0040000000000000001: 0.012880000000000001, 0.050000000000000003: 0.012880000000000001, 0.0080000000000000002: 0.012880000000000001, 0.00040000000000000002: 0.012880000000000001, 'l': 3704.0, 0.02: 0.012880000000000001}, 'H17': {0.0040000000000000001: 0.01074, 0.050000000000000003: 0.01074, 0.0080000000000000002: 0.01074, 0.00040000000000000002: 0.01074, 'l': 3698.0, 0.02: 0.01074}, '[OIII]4958.91': {0.0040000000000000001: 1.617, 0.050000000000000003: 1.399, 0.0080000000000000002: 1.399, 0.00040000000000000002: 1.097, 'l': 4958.9099999999999, 0.02: 1.399}, '[CII]2326.00': {0.0040000000000000001: 0.0, 0.050000000000000003: 0.28999999999999998, 0.0080000000000000002: 0.28999999999999998, 0.00040000000000000002: 0.0, 'l': 2326.0, 0.02: 0.28999999999999998}, 'Lalpha': {0.0040000000000000001: 23.699999999999999, 0.050000000000000003: 23.699999999999999, 0.0080000000000000002: 23.699999999999999, 0.00040000000000000002: 23.699999999999999, 'l': 1216.0, 0.02: 23.699999999999999}, '[HeI]5876.00': {0.0040000000000000001: 0.108, 0.050000000000000003: 0.14000000000000001, 0.0080000000000000002: 0.14000000000000001, 0.00040000000000000002: 0.096000000000000002, 'l': 5876.0, 0.02: 0.14000000000000001}, '[ArIV]+[HeI]': {0.0040000000000000001: 0.014, 0.050000000000000003: 0.0, 0.0080000000000000002: 0.0, 0.00040000000000000002: 0.01, 'l': 4711.0, 0.02: 0.0}, '[CIII]': {0.0040000000000000001: 0.0, 0.050000000000000003: 0.17999999999999999, 0.0080000000000000002: 0.17999999999999999, 0.00040000000000000002: 0.0, 'l': 1909.0, 0.02: 0.17999999999999999}, 'Hbeta': {0.0040000000000000001: 1.0, 0.050000000000000003: 1.0, 0.0080000000000000002: 1.0, 0.00040000000000000002: 1.0, 'l': 4861.0, 0.02: 1.0}, 'Hdelta': {0.0040000000000000001: 0.2591, 0.050000000000000003: 0.2591, 0.0080000000000000002: 0.2591, 0.00040000000000000002: 0.2591, 'l': 4101.0, 0.02: 0.2591}, '[SIII]9530.85': {0.0040000000000000001: 0.0, 0.050000000000000003: 0.36499999999999999, 0.0080000000000000002: 0.36499999999999999, 0.00040000000000000002: 0.0, 'l': 9530.8500000000004, 0.02: 0.36499999999999999}, '[SII]6716.00': {0.0040000000000000001: 0.188, 0.050000000000000003: 0.29999999999999999, 0.0080000000000000002: 0.29999999999999999, 0.00040000000000000002: 0.036999999999999998, 'l': 6716.0, 0.02: 0.29999999999999999}, 'Bgamma': {0.0040000000000000001: 0.02928, 0.050000000000000003: 0.02928, 0.0080000000000000002: 0.02928, 0.00040000000000000002: 0.02928, 'l': 21656.0, 0.02: 0.02928}, 'Pdelta': {0.0040000000000000001: 0.055300000000000002, 0.050000000000000003: 0.055300000000000002, 0.0080000000000000002: 0.055300000000000002, 0.00040000000000000002: 0.055300000000000002, 'l': 10049.4, 0.02: 0.055300000000000002}, '[SII]10320.49': {0.0040000000000000001: 0.0, 0.050000000000000003: 0.058000000000000003, 0.0080000000000000002: 0.058000000000000003, 0.00040000000000000002: 0.0, 'l': 10320.49, 0.02: 0.058000000000000003}, '[SIII]9068.60': {0.0040000000000000001: 0.51000000000000001, 0.050000000000000003: 0.94499999999999995, 0.0080000000000000002: 0.94499999999999995, 0.00040000000000000002: 0.0, 'l': 9068.6000000000004, 0.02: 0.94499999999999995}, 'Palpha': {0.0040000000000000001: 0.30099999999999999, 0.050000000000000003: 0.30099999999999999, 0.0080000000000000002: 0.30099999999999999, 0.00040000000000000002: 0.30099999999999999, 'l': 18751.0, 0.02: 0.30099999999999999}, 'Balpha': {0.0040000000000000001: 0.089940000000000006, 0.050000000000000003: 0.089940000000000006, 0.0080000000000000002: 0.089940000000000006, 0.00040000000000000002: 0.089940000000000006, 'l': 40512.0, 0.02: 0.089940000000000006}, '[ArIII]7135.79': {0.0040000000000000001: 0.070999999999999994, 0.050000000000000003: 0.035000000000000003, 0.0080000000000000002: 0.035000000000000003, 0.00040000000000000002: 0.027, 'l': 7135.79, 0.02: 0.035000000000000003}, 'Hepsilon': {0.0040000000000000001: 0.15909999999999999, 0.050000000000000003: 0.15909999999999999, 0.0080000000000000002: 0.15909999999999999, 0.00040000000000000002: 0.15909999999999999, 'l': 3970.0, 0.02: 0.15909999999999999}, '[MgII]': {0.0040000000000000001: 0.31, 0.050000000000000003: 0.070000000000000007, 0.0080000000000000002: 0.070000000000000007, 0.00040000000000000002: 0.0, 'l': 2798.0, 0.02: 0.070000000000000007}, 'Pxi': {0.0040000000000000001: 0.025399999999999999, 0.050000000000000003: 0.025399999999999999, 0.0080000000000000002: 0.025399999999999999, 0.00040000000000000002: 0.025399999999999999, 'l': 9229.0, 0.02: 0.025399999999999999}, '[SII]4076.35': {0.0040000000000000001: 0.0070000000000000001, 0.050000000000000003: 0.010999999999999999, 0.0080000000000000002: 0.010999999999999999, 0.00040000000000000002: 0.002, 'l': 4076.3499999999999, 0.02: 0.010999999999999999}, 'Hgamma': {0.0040000000000000001: 0.46100000000000002, 0.050000000000000003: 0.46100000000000002, 0.0080000000000000002: 0.46100000000000002, 0.00040000000000000002: 0.46100000000000002, 'l': 4340.0, 0.02: 0.46100000000000002}, 'Pepsilon': {0.0040000000000000001: 0.036499999999999998, 0.050000000000000003: 0.036499999999999998, 0.0080000000000000002: 0.036499999999999998, 0.00040000000000000002: 0.036499999999999998, 'l': 9546.0, 0.02: 0.036499999999999998}, 'Bbeta': {0.0040000000000000001: 0.048509999999999998, 0.050000000000000003: 0.048509999999999998, 0.0080000000000000002: 0.048509999999999998, 0.00040000000000000002: 0.048509999999999998, 'l': 26252.0, 0.02: 0.048509999999999998}, '[SII]4068.6': {0.0040000000000000001: 0.017000000000000001, 0.050000000000000003: 0.029000000000000001, 0.0080000000000000002: 0.029000000000000001, 0.00040000000000000002: 0.0050000000000000001, 'l': 4068.5999999999999, 0.02: 0.029000000000000001}, 'Halpha': {0.0040000000000000001: 2.915, 0.050000000000000003: 2.915, 0.0080000000000000002: 2.915, 0.00040000000000000002: 2.915, 'l': 6562.0, 0.02: 2.915}, '[OII]7319.99': {0.0040000000000000001: 0.027, 0.050000000000000003: 0.025999999999999999, 0.0080000000000000002: 0.025999999999999999, 0.00040000000000000002: 0.012, 'l': 7319.9899999999998, 0.02: 0.025999999999999999}, '[SII]10286.73': {0.0040000000000000001: 0.0, 0.050000000000000003: 0.048000000000000001, 0.0080000000000000002: 0.048000000000000001, 0.00040000000000000002: 0.0, 'l': 10286.73, 0.02: 0.048000000000000001}, '[HeI]4026.0': {0.0040000000000000001: 0.014999999999999999, 0.050000000000000003: 0.014999999999999999, 0.0080000000000000002: 0.014999999999999999, 0.00040000000000000002: 0.014999999999999999, 'l': 4026.0, 0.02: 0.014999999999999999}, '[OII]7330.73': {0.0040000000000000001: 0.014, 0.050000000000000003: 0.014, 0.0080000000000000002: 0.014, 0.00040000000000000002: 0.0070000000000000001, 'l': 7330.7299999999996, 0.02: 0.014}, '[HeI]7065.00': {0.0040000000000000001: 0.023, 0.050000000000000003: 0.040000000000000001, 0.0080000000000000002: 0.040000000000000001, 0.00040000000000000002: 0.028000000000000001, 'l': 7065.0, 0.02: 0.040000000000000001}} velocity=1000. #------------------------------------------------ #------------------------------------------------ #determine relations between redshift and age aou_cz=cosmocalc.cosmocalc(p.snap_z)['zage_Gyr'] redshifts=np.arange(p.snap_z,20,0.1) ages=[] for z in redshifts: aou_z=cosmocalc.cosmocalc(z)['zage_Gyr'] ages.append(aou_cz-aou_z) ages=np.array(ages) #------------------------------------------------ #------------------------------------------------ # read in SSPs mets=[0.05,0.02,0.008,0.004,0.0004] metsl={0.05:'005',0.02:'002',0.008:'0008',0.004:'0004',0.0004:'00004'} ssp={}
def find_image(self,mstar,redshift,sfr,seed,xpix,ypix,hmag): sim_simname = self.simdata['col1'] sim_expfact = self.simdata['col2'] sim_sfr = self.simdata['col54'] sim_mstar = self.simdata['col56'] sim_redshift = 1.0/sim_expfact - 1.0 metalmass = self.simdata['col53'] sim_res_pc = self.simdata['col62'] sim_string = self.simdata['col60'] simage_loc = '/Users/gsnyder/Documents/Projects/HydroART_Morphology/Hyades_Data/images_rsync/' self.mstar_list.append(mstar) self.redshift_list.append(redshift) adjust_size=False print " " print "Searching for simulation with mstar,z,seed : ", mstar, redshift, seed wide_i = np.where(np.logical_and(np.logical_and(np.abs(sim_redshift-redshift)<0.3,np.abs(np.log10(sim_mstar)-mstar)<0.1),sim_sfr > -1))[0] Nwi = wide_i.shape[0] if Nwi==0: wide_i = np.where(np.logical_and(np.logical_and(np.abs(sim_redshift-redshift)<0.5,np.abs(np.log10(sim_mstar)-mstar)<0.4),sim_sfr > -1))[0] Nwi = wide_i.shape[0] if Nwi==0 and (mstar < 7.1): print " Can't find good sim, adjusting image parameters to get low mass things " wide_i = np.where(np.abs(sim_redshift-redshift)<0.3)[0] #wide_i is a z range llmi = np.argmin(np.log10(sim_mstar[wide_i])) #the lowest mass in this z range wlmi = np.where(np.abs(np.log10(sim_mstar[wide_i]) - np.log10(sim_mstar[wide_i[llmi]])) < 0.3)[0] #search within 0.3 dex of lowest available sims print " ", wide_i.shape, llmi, wlmi.shape wide_i = wide_i[wlmi] Nwi = wide_i.shape[0] print " ", Nwi adjust_size=True #assert(wide_i.shape[0] > 0) if Nwi==0: print " Could not find roughly appropriate simulation for mstar,z: ", mstar, redshift print " " self.image_files.append('') return 0#np.zeros(shape=(600,600)), -1 print " Found N candidates: ", wide_i.shape np.random.seed(seed) #choose random example and camera rps = np.random.random_integers(0,Nwi-1,1)[0] cn = str(np.random.random_integers(5,8,1)[0]) prefix = os.path.basename(sim_string[wide_i[rps]]) sim_realmstar = np.log10(sim_mstar[wide_i[rps]]) #we picked a sim with this log mstar mstar_factor = sim_realmstar - mstar rad_factor = 1.0 lum_factor = 1.0 if adjust_size==True: rad_factor = 10.0**(mstar_factor*0.5) #must **shrink** images by this factor, total flux by mstar factor lum_factor = 10.0**(mstar_factor) print ">>>FACTORS<<< ", prefix, sim_realmstar, mstar_factor, rad_factor, lum_factor im_folder = simage_loc + prefix +'_skipir/images' im_file = os.path.join(im_folder, prefix+'_skipir_CAMERA'+cn+'-BROADBAND_'+self.filter_string+'_simulation.fits') cn_file = os.path.join(im_folder, prefix+'_skipir_CAMERA'+cn+'-BROADBAND_'+self.filter_string+'_candelized_noise.fits') req1 = os.path.join(im_folder, prefix+'_skipir_CAMERA'+cn+'-BROADBAND_'+self.req_filters[0]+'_simulation.fits') req2 = os.path.join(im_folder, prefix+'_skipir_CAMERA'+cn+'-BROADBAND_'+self.req_filters[1]+'_simulation.fits') req3 = os.path.join(im_folder, prefix+'_skipir_CAMERA'+cn+'-BROADBAND_'+self.req_filters[2]+'_simulation.fits') req4 = os.path.join(im_folder, prefix+'_skipir_CAMERA'+cn+'-BROADBAND_'+self.req_filters[3]+'_simulation.fits') req5 = os.path.join(im_folder, prefix+'_skipir_CAMERA'+cn+'-BROADBAND_'+self.req_filters[4]+'_simulation.fits') ## Actually, probably want to keep trying some possible galaxies/files... is_file = os.path.lexists(im_file) and os.path.lexists(cn_file) and os.path.lexists(req1) and os.path.lexists(req2) and os.path.lexists(req3) and os.path.lexists(req4) and os.path.lexists(req5) #is_file = os.path.lexists(im_file) and os.path.lexists(cn_file) #and os.path.lexists(req1) and os.path.lexists(req2) and os.path.lexists(req3) if is_file==False: print " Could not find appropriate files: ", im_file, cn_file print " " self.image_files.append('') return 0 #np.zeros(shape=(600,600)), -1 self.image_files.append(im_file) cn_header = pyfits.open(cn_file)[0].header im_hdu = pyfits.open(im_file)[0] scalesim = cn_header.get('SCALESIM') #pc/pix Ps = cosmocalc.cosmocalc(redshift)['PS_kpc'] #kpc/arcsec print " Simulation pixel size at z: ", scalesim print " Plate scale for z: ", Ps print " Desired Kpc/pix at z: ", Ps*self.Pix_arcsec sunrise_image = np.float32(im_hdu.data) #W/m/m^2/Sr Sim_Npix = sunrise_image.shape[0] New_Npix = int( Sim_Npix*(scalesim/(1000.0*Ps*self.Pix_arcsec))/rad_factor ) #rad_factor reduces number of pixels (total size) desired if New_Npix==0: New_Npix=1 print " New galaxy pixel count: ", New_Npix rebinned_image = congrid.congrid(sunrise_image,(New_Npix,New_Npix)) #/lum_factor #lum_factor shrinks surface brightness by mass factor... but we're shrinking size first, so effective total flux already adjusted by this; may need to ^^ SB instead??? or fix size adjust SB? print " New galaxy image shape: ", rebinned_image.shape print " New galaxy image max: ", np.max(rebinned_image) #finite_bool = np.isfinite(rebinned_image) #num_infinite = np.where(finite_bool==False)[0].shape[0] #print " Number of INF pixels: ", num_infinite, prefix #self.N_inf.append(num_infinite) if xpix==-1: xpix = int( (self.Npix-1)*np.random.rand()) #np.random.random_integers(0,self.Npix-1,1)[0] ypix = int( (self.Npix-1)*np.random.rand()) #np.random.random_integers(0,self.Npix-1,1)[0] self.x_array.append(xpix) self.y_array.append(ypix) x1_choice = np.asarray([int(xpix-float(New_Npix)/2.0),0]) x1i = np.argmax(x1_choice) x1 = x1_choice[x1i] diff=0 if x1==0: diff = x1_choice[1]-x1_choice[0] x2_choice = np.asarray([x1 + New_Npix - diff,self.Npix]) x2i = np.argmin(x2_choice) x2 = int(x2_choice[x2i]) x1sim = abs(np.min(x1_choice)) x2sim = min(New_Npix,self.Npix-x1) y1_choice = np.asarray([int(ypix-float(New_Npix)/2.0),0]) y1i = np.argmax(y1_choice) y1 = y1_choice[y1i] diff=0 if y1==0: diff = y1_choice[1]-y1_choice[0] y2_choice = np.asarray([y1 + New_Npix - diff,self.Npix]) y2i = np.argmin(y2_choice) y2 = int(y2_choice[y2i]) y1sim = abs(np.min(y1_choice)) y2sim = min(New_Npix,self.Npix-y1) print " Placing new image at x,y in x1:x2, y1:y2 from xsim,ysim, ", xpix, ypix, x1,x2,y1,y2, x1sim, x2sim, y1sim, y2sim #image_slice = np.zeros_like(self.blank_array) print " done creating image slice" #bool_slice = np.int32( np.zeros(shape=(self.Npix,self.Npix))) image_cutout = rebinned_image[x1sim:x2sim,y1sim:y2sim] print " New image shape: ", image_cutout.shape pixel_Sr = (self.Pix_arcsec**2)/sq_arcsec_per_sr #pixel area in steradians: Sr/pixel to_nJy_per_Sr = (1.0e9)*(1.0e14)*(self.eff_lambda_microns**2)/c #((pixscale/206265.0)^2)* #sigma_nJy = 0.3*(2.0**(-0.5))*((1.0e9)*(3631.0/5.0)*10.0**(-0.4*self.maglim))*self.Pix_arcsec*(3.0*self.FWHM_arcsec) to_Jy_per_pix = to_nJy_per_Sr*(1.0e-9)*pixel_Sr #b = b*(to_nJy_per_Sr_b*fluxscale*bluefact) # + np.random.randn(Npix,Npix)*sigma_nJy/pixel_Sr image_cutout = image_cutout*to_Jy_per_pix #image_cutout*to_nJy_per_Sr #image_slice[x1:x2,y1:y2] = image_cutout*1.0 #bool_slice[x1:x2,y1:y2]=1 print " done slicing" #self.final_array += image_slice self.final_array[x1:x2,y1:y2] += image_cutout print " done adding image to final array" #finite_bool = np.isfinite(self.final_array) #num_infinite = np.where(finite_bool==False)[0].shape[0] #print " Final array INF count and max:", num_infinite, np.max(self.final_array) print " " return 1 #sunrise_image,scalesim
import continuum from sys import argv snap = readsubhalo.SnapDir(argv[1], p.snapshot_dir) #------------------------------------------------ # make output directories output_dir = snap.subhalodir + '/SED' os.system('mkdir '+ output_dir) #------------------------------------------------ #------------------------------------------------ #determine relations between redshift and age aou_cz=cosmocalc.cosmocalc(snap.redshift)['zage_Gyr'] redshifts=numpy.arange(snap.redshift,20,0.1) ages=[] for z in redshifts: aou_z=cosmocalc.cosmocalc(z)['zage_Gyr'] ages.append(aou_cz-aou_z) ages=numpy.array(ages) #------------------------------------------------ #------------------------------------------------ # read in SSPs mets=numpy.array([0.05,0.02,0.008,0.004,0.0004]) metsl={0.05:'005',0.02:'002',0.008:'0008',0.004:'0004',0.0004:'00004'} ssp={}
flux_nuv_corr = flux_nuv_fitzpatrick * correction_factor flux_fuv_corr = flux_fuv_fitzpatrick * correction_factor flux_galex_corr = np.array([float(flux_fuv_corr), float(flux_nuv_corr)]) flux_all_corr = np.array([float(flux_sdss_corr[0]), float(flux_sdss_corr[1]), float(flux_sdss_corr[2]), float(flux_sdss_corr[3]), float(flux_sdss_corr[4]), float(flux_fuv_corr), float(flux_nuv_corr)]) # UV Synthetic equivalent fluxes ------------------------------------------------------------------------------- k = np.abs(fuv_obs_wavelength - synthetic_wavelengths).argmin() fuv_synth_flux = synthetic_fluxes[k] m = np.abs(nuv_obs_wavelength - synthetic_wavelengths).argmin() nuv_synth_flux = synthetic_fluxes[m] # Absolute Magnitudes using Luminosity Distance ---------------------------------------------------------------- luminosity_distance = cosmo.cosmocalc(z[index])['DL_Mpc'] mag_fuv_abs = mag_fuv_dered_fm - 5 * np.log10(luminosity_distance) - 25 mag_nuv_abs = mag_nuv_dered_fm - 5 * np.log10(luminosity_distance) - 25 mag_u_abs = mag_ab_u[index] - 5 * np.log10(luminosity_distance) - 25 mag_g_abs = mag_ab_g[index] - 5 * np.log10(luminosity_distance) - 25 mag_r_abs = mag_ab_r[index] - 5 * np.log10(luminosity_distance) - 25 mag_i_abs = mag_ab_i[index] - 5 * np.log10(luminosity_distance) - 25 mag_z_abs = mag_ab_z[index] - 5 * np.log10(luminosity_distance) - 25 # Chi^2 selection --------------------------------------------------------------------------------------------- flux_sdss_synth = [] for n in range(wavelengths_sdss_griz.size): index_flux_synth = np.abs(wavelengths_sdss_griz[n] - synthetic_wavelengths).argmin() flux_synth = synthetic_fluxes[index_flux_synth] flux_sdss_synth.append(flux_synth) flux_sdss_synth = np.array(flux_sdss_synth)
def getDataSlow(db='database.db', path='/Users/sammy/Research/CANDELS/v2/'): """ Get data from the lcone table in db. :param db: name of the SQLite database file. :type db: string :param path: full path of the database file :type path: string :Warning: This is extremely slow way to pull out data from a database. Should be rewritten using table joins etc. so that less queries could be performed. :return: redshift, halo mass and radius, projected distances of subhalo galaxies [kpc], halo_id of the main halo :rtype: dict """ conversion = 0.000277777778 # degree to arcsecond redshifts = [ 'redshift < 0.5 and', 'redshift >= 0.5 and redshift < 1.0 and', 'redshift >= 1.0 and redshift < 2.0 and', 'redshift >= 2.0 and redshift < 3.0 and', 'redshift >= 3.0 and redshift < 4.0 and', 'redshift >= 4.0 and redshift < 5.0 and', 'redshift >= 5.0 and redshift < 6.0 and', 'redshift >= 6.0 and redshift < 7.0 and' ] for i, red in enumerate(redshifts): print red qr = 'select halo_id from lcone where %s gal_id > 1' % red #qr = 'select halo_id from lcone where %s mhalo > 12.7' % red #pull out data ids = sq.get_data_sqliteSMNfunctions(path, db, qr) uids = np.unique(ids) print len(uids), 'haloes' saveid = [] saveorig = [] savedist = [] savemhalo = [] saverhalo = [] saveredshift = [] #we should now look for each unique id for id in uids: query = 'select redshift, ra, dec, halo_id, mhalo, rhalo from lcone where halo_id = {0:d}'.format( id) #print query data = sq.get_data_sqliteSMNfunctions(path, db, query) #if multiples, then don't take it if len(set(data[:, 0])) > 1: print 'skipping', id continue if len(data[:, 1]) < 2: print 'no subhaloes', id, data[:, 1] continue #redshift z = data[0, 0] #look the diameter distance from the lookup table dd = cosmocalc(z, 71.0, 0.28)['PS_kpc'] #the first halo, assume it to be the main halo RADeg1 = data[0, 1] decDeg1 = data[0, 2] #the following haloes, assume to be subhaloes RADeg2 = data[1:, 1] decDeg2 = data[1:, 2] #calculate the angular separation on the sky sep = Coords.calcAngSepDeg(RADeg1, decDeg1, RADeg2, decDeg2) physical_distance = sep * dd / conversion #these are all the main halo parameters saveredshift.append(z) saveid.append(int(data[0, 3])) savemhalo.append(data[0, 4]) saverhalo.append(data[0, 5]) savedist.append(physical_distance) saveorig.append(id) out = dict(halo_ids=saveid, distances=savedist, original=saveorig, mhalo=savemhalo, rhalo=saverhalo, redshift=saveredshift) wr.cPickleDumpDictionary(out, 'distances%i.pickle' % (i + 1))
tmp = matched[matched[:, 3] == x] #redshift z = tmp[0][0] RADeg1 = tmp[0][1] decDeg1 = tmp[0][2] RADeg2 = tmp[1:, 1] decDeg2 = tmp[1:, 2] prop = tmp[:, 5] sep = Coords.calcAngSepDeg(RADeg1, decDeg1, RADeg2, decDeg2) dd = cosmocalc(z, 71.0, 0.28)['PS_kpc'] #dist.getDiameterDistances(data) physical_distance = (sep / dd) / conversion print z, RADeg1, RADeg2, decDeg1, decDeg2, prop print sep, physical_distance print ax.plot([z for foo in range(len(physical_distance))], physical_distance, 'bo') #P.show() print print cursor.execute('CREATE TABLE newTable (h1, g1, h2, g2, foo)')
#DEBUG #print(data['red']) #for i in range(len(data['wl'])): #print('%.5e %.5e %.5e\n' %(data['wl'][i], data['fl'][i], data['err'][i])) ################################################################### # # TRANSFORM INTO ABSOLUTE MAGNITUDES # ################################################################### for k in range(len(input_files_data)): dist = (cosmocalc.cosmocalc( input_files_data[k]['red'], H0=70.4, WM=0.2726, WV=0.7274))['DL_Mpc'] #Calculate modulus distance dist *= 1e6 #transform into parsecs modulus_distance = 5.0 * (math.log10(dist) - 1.0) #Calculate modulus distance #DEBUG #print("DIST: " + str(dist)) #print("MOD_DIST: " + str(modulus_distance)) for i in range(len(input_files_data[k]['wl'])): #print("FLUX (microJs): " +str(data['fl'][i])) input_files_data[k]['err'][i] = 2.5 * input_files_data[k]['err'][i] / input_files_data[k]['fl'][i]
from deproject import Deproject from cosmocalc import cosmocalc redshift = 0.004233 from math import pi dep = Deproject(numpy.arange(30., 640., 30)*0.492) dep.theta = 75 dep.angdist = cosmocalc(redshift)['DA_cm'] * 0.892 set_method("levmar") set_stat("chi2gehrels") for ann in range(dep.nshell): dep.load_pha('m87/r%dgrspec.pha' % (ann+1), annulus=ann) dep.set_source('xswabs*xsmekal') dep.ignore(None, 0.5) dep.ignore(1.8, 2.2) dep.ignore(7, None) dep.set_par('xswabs.nh', 0.0255) dep.freeze("xswabs.nh") dep.set_par('xsmekal.abundanc', 0.5) dep.thaw('xsmekal.abundanc') dep.set_par('xsmekal.redshift', redshift) dep.subtract() dep.fit()
LSLOPE2_MAX = 1 LSTAR_2_MIN = 20.0 LSTAR_2_MAX = 24.9 LSLOPE_2_MIN = -5.0 LSLOPE_2_MAX = 5.0 LSLOPE2_2_MIN = -5.0 LSLOPE2_2_MAX = 5.0 LNORM_2_MIN = -5.5 LNORM_2_MAX = 2 LSIGMA_MIN = 0.6 LSIGMA_MAX = 0.1 if setBreaks: dl = cosmocalc(redshifts[0], H0=Ho, WM=wm)['DL_Mpc'] l = math.pi * 4 * (Breaks[0] * 1e-32) * (dl * 3.08e22)**2 * ( 1 + redshifts[0])**((LF_SPEC_INDEX) + 1) LSTAR_MIN = LSTAR_MAX = 23.1 #LMAX_MIN=LMAX_MAX=24.6 print 'setting break' LSTAR_PRIOR = 'DELTA' #LMAX_PRIOR = 'DELTA' # LF redshift evolution (if > 1 z slice only) LZEVOL_MIN = -5.0 LZEVOL_MAX = 5.0 if len(whichRedshiftSlices) <= 1: LZEVOL_MIN = LZEVOL_MAX = 0.0 # delta fn on LZEVOL #S0_MIN=S0_MAX=S0_TRUE # delta fn on S0