def redshift_lum_distance_sampler(cosmo_dict, num_injs, seed): zmin = cosmo_dict['zmin'] zmax = cosmo_dict['zmax'] keys = list(cosmo_dict.keys()) if 'Om0' in keys: Om0 = cosmo_dict['Om0'] else: Om0 = None if 'Ode0' in keys: Ode0 = cosmo_dict['Ode0'] else: Ode0 = None if 'H0' in keys: H0 = cosmo_dict['H0'] else: H0 = None if None in (Om0, Ode0, H0): cosmo = apcosm.Planck15 else: cosmo = apcosm.LambdaCDM(H0=H0, Om0=Om0, Ode0=Ode0) if cosmo_dict['sampler'] == 'inversion': nzs = None z_vec = uniform_comoving_volume_redshift_inversion_sampler( zmin, zmax, cosmo, num_injs, seed, nzs) elif cosmo_dict['sampler'] == 'rejection': nzs = 40 z_vec = uniform_comoving_volume_redshift_rejection_sampler( zmin, zmax, cosmo, num_injs, seed, nzs) return z_vec, cosmo.luminosity_distance(z_vec).value
def __init__(self): """Initialize a cosmological model and arrays to interpolate redshift to comoving distance. Note that H0 = 100 h km/s/Mpc is used. For now the cosmological parameters measured by Planck (P.A.R. Ade et al., Paper XIII, A&A 594:A13, 2016) are used. """ h = 0.677 pl15 = cosmology.LambdaCDM(name='pl15', H0=100 * u.km / (u.Mpc * u.s), Om0=0.307, Ob0=0.0486, Ode0=0.693, Tcmb0=2.725 * u.K, Neff=3.05, m_nu=np.asarray([0., 0., 0.06]) * u.eV) z0 = 0. z1 = 3. nz = int((z1 - z0) / 0.001) + 1 self.z = np.linspace(z0, z1, nz) self.r = np.zeros(nz, dtype=float) self.r[1:] = pl15.comoving_distance(self.z[1:]) # Define an interpolation. Use the 1D cubic monotonic interpolator # from scipy. self.r_vs_z = interpolate.PchipInterpolator(self.z, self.r)
def main(params): # Read spectra, depends on file type rfSpecs = ReadGalaxev(params['dotsed'], params['dotfourcolor']) # Read Filters filters = readFilters(params['filter_dir'], params['filter_names']) # Make cosmology print(params['cosmology'][0]) if params['cosmology'][0] == 'lcdm': cosmo = cosmology.LambdaCDM(Om0=params['cosmology'][1], Ode0=params['cosmology'][2], H0=params['cosmology'][3]) else: wmaps, ns = [cosmology.WMAP5, cosmology.WMAP7, cosmology.WMAP9], [5., 7., 9.] cosmo = wmaps[ns.index(params['cosmology'][1])] # Parse zs if params['redshifts'][0] == 'range': redshifts = np.arange(params['redshifts'][1], params['redshifts'][2], params['redshifts'][3]) elif params['redshifts'][0] == 'values': redshifts = np.array(params['redshifts'][1:]) else: raise ValueError('Redshifts must be specified as a range or values.') # Dust Stuff if params['ebvs'][0] == 'range': ebvs = np.arange(params['ebvs'][1], params['ebvs'][2], params['ebvs'][3]) elif params['ebvs'][0] == 'values': ebvs = params['ebvs'][1:] # make bbseds i = 0 for rfspec in rfSpecs: newbbspex = redshift.ProcessSpectrum(rfspec,filters=filters,cosmo=cosmo,\ zs=redshifts,dustLaw=params['dust_law'],ebvs=ebvs,returnMag=params['returnmags']) if i == 0: bbseds = newbbspex i += 1 else: bbseds += newbbspex # Write output header head, sparams = WriteBBsedHeader(params, bbseds[0].params.keys(), params['returnmags']) bbsOut = [] for bbs in bbseds: line = [] for sparam in sparams: line.append(bbs.params[sparam]) for fil in params['filter_names']: line.append(bbs.mags[fil[0][:fil[0].index('.')]].value) bbsOut.append(line) bbsOut = np.array(bbsOut) np.savetxt(params['output_file'], bbsOut, header=head) return (head, bbsOut)
def set_model(self, hubble0, omega_m0, omega_de0): """ read cosmologies from configuration file and reset table """ # Set astropy cosmology model self.model = cosmology.LambdaCDM( H0=hubble0, Om0=omega_m0, Ode0=omega_de0,) # Set up redshift-comoving table self._set_comoving_table()
def get_cosmology_parameters(raw_params): """ Returns ------- cosmo : astropy.cosmology object object containing cosmological parameters """ omega_m0 = float(raw_params['omega_m']) # Present-day matter density omega_l0 = float(raw_params['omega_l']) # Present-day dark energy density omega_k0 = float(raw_params['omega_k']) # Present-day spatial curvature density hubble_h0 = float(raw_params['h']) # Present-day reduced Hubble constant: h0 = H0 / (100 km/s/Mpc) H0 = hubble_h0*100. cosmo = ac.LambdaCDM(H0=H0, Om0=omega_m0, Ode0=omega_l0) return cosmo
def establish_cosmology(cfg=cfg): user_cosmo = cfg['misc']['cosmology'] if user_cosmo in cosmology.realizations.available: cosmo = cosmology.default_cosmology.get_cosmology_from_string( user_cosmo) elif isinstance(user_cosmo, dict): try: if user_cosmo.get('flat'): cosmo = cosmology.FlatLambdaCDM( user_cosmo['H0'], user_cosmo['Om0'], Tcmb0=user_cosmo.get('Tcmb0', 2.725), Neff=user_cosmo.get('Neff', 3.04), m_nu=u.Quantity(user_cosmo.get('m_nu', [0.0, 0.0, 0.0]), u.eV), name=user_cosmo.get("name", "user_cosmology"), Ob0=user_cosmo.get('Ob0', 0.0455), ) else: cosmo = cosmology.LambdaCDM( user_cosmo['H0'], user_cosmo['Om0'], user_cosmo['Ode0'], Tcmb0=user_cosmo.get('Tcmb0', 2.725), Neff=user_cosmo.get('Neff', 3.04), m_nu=u.Quantity(user_cosmo.get('m_nu', [0.0, 0.0, 0.0]), u.eV), name=user_cosmo.get("name", "user_cosmology"), Ob0=user_cosmo.get('Ob0', 0.0455), ) except (KeyError, NameError) as e: log(f'{e}') log('Exception while processing user-defined cosmology') raise RuntimeError('Error parsing user-defined cosmology') else: log(f"Invalid user-defined cosmology [{user_cosmo}]") log(f"Try setting it to one of [{cosmology.realizations.available}]") raise RuntimeError("No valid cosmology specified") log(f'Using {cosmo.name} for cosmological calculations') log(f'{cosmo}') return cosmo
def _get_cosmology(): if cfg.get('misc'): if cfg["misc"].get('cosmology'): if cfg["misc"]["cosmology"] in cosmology.parameters.available: cosmo = cosmology.default_cosmology.get_cosmology_from_string( cfg["misc"]["cosmology"]) elif isinstance(cfg["misc"]["cosmology"], dict): par = cfg["misc"]["cosmology"] try: if par.get('flat'): cosmo = cosmology.FlatLambdaCDM( par['H0'], par['Om0'], Tcmb0=par.get('Tcmb0', 2.725), Neff=par.get('Neff', 3.04), m_nu=u.Quantity( par.get('m_nu', [0.0, 0.0, 0.0]), u.eV), name=par.get("name", "user_cosmology"), Ob0=par.get('Ob0', 0.0455), ) else: cosmo = cosmology.LambdaCDM( par['H0'], par['Om0'], par['Ode0'], Tcmb0=par.get('Tcmb0', 2.725), Neff=par.get('Neff', 3.04), m_nu=u.Quantity( par.get('m_nu', [0.0, 0.0, 0.0]), u.eV), name=par.get("name", "user_cosmology"), Ob0=par.get('Ob0', 0.0455), ) except (KeyError, NameError) as e: log(f'{e}') log('exception in determining user defined cosmology') cosmo = fallback_cosmology else: log('cosmology: dont know how to deal with the user supplied cosmology' ) cosmo = fallback_cosmology else: cosmo = fallback_cosmology log(f'using {cosmo.name} for cosmological calculations') log(f'{cosmo}') return cosmo
def set_cosmology(cosmology=None): """ Get an instance of a astropy.cosmology.FLRW subclass. To avoid repeatedly instantiating the same class, test if it is the same as the last used cosmology. Parameters ========== cosmology: astropy.cosmology.FLRW, str, dict Description of cosmology, one of: None - Use DEFAULT_COSMOLOGY Instance of astropy.cosmology.FLRW subclass String with name of known Astropy cosmology, e.g., "Planck13" Dictionary with arguments required to instantiate the cosmology class. Returns ======= cosmo: astropy.cosmology.FLRW Cosmology instance """ from astropy import cosmology as cosmo _set_default_cosmology() if cosmology is None: cosmology = DEFAULT_COSMOLOGY elif isinstance(cosmology, cosmo.FLRW): cosmology = cosmology elif isinstance(cosmology, str): cosmology = cosmo.__dict__[cosmology] elif isinstance(cosmology, dict): if 'Ode0' in cosmology.keys(): if 'w0' in cosmology.keys(): cosmology = cosmo.wCDM(**cosmology) else: cosmology = cosmo.LambdaCDM(**cosmology) else: cosmology = cosmo.FlatLambdaCDM(**cosmology) COSMOLOGY[0] = cosmology if cosmology.name is not None: COSMOLOGY[1] = cosmology.name else: COSMOLOGY[1] = repr(cosmology)
fits_table(d,halos.names+['RA_AVG','DEC_AVG','Z_AVG'],data_loc+'/halos2.fits') ## Calculate Cluster Richnesses cluster_rich = False if cluster_rich == True: root = '/nfs/christoq_ls/nkern' data_loc = 'MassRich/TRUTH_CAUSTIC' write_loc = 'individual' C4 = CFOUR({'H0':70,'chris_data_root':'/nfs/christoq_ls/MILLENNIUM/Henriques/TRUTH_CAUSTIC'}) C = Caustic() H0 = 72.0 c = 2.99792e5 Cosmo = cosmo.LambdaCDM(H0,0.3,0.7) keys = ['C','H0','c','Cosmo','C4'] varib = ez.create(keys,locals()) R = RICHNESS(varib) # Load Halos halos = fits.open(root+'/C4/'+data_loc+'/halos.fits')[1].data HaloID = halos['orig_order'] RA = halos['ra_avg'] DEC = halos['dec_avg'] Z = halos['z_avg'] RVIR = halos['RVIR'] # Load Galaxy Data gals = fits.open('/nfs/christoq_ls/MILLENNIUM/Henriques/TRUTH_CAUSTIC/m19.1_allgals_wsdss_specerrs_abs.fits')[1].data
from classylss.binding import * import astropy.cosmology as ac import astropy.units as units import numpy from numpy.testing import assert_allclose import pytest # define the astropy cosmologies c_flat = ac.FlatLambdaCDM(H0=70, Om0=0.3, Ob0=0.04, Tcmb0=2.7255) c_open = ac.LambdaCDM(H0=70, Om0=0.3, Ob0=0.04, Ode0=0.65, Tcmb0=2.7255) c_closed = ac.LambdaCDM(H0=70, Om0=0.3, Ob0=0.04, Ode0=0.85, Tcmb0=2.7255) @pytest.mark.parametrize("c2, a_max", [ (c_flat, 1.0), (c_open, 1.0), (c_closed, 1.0), (c_flat, 2.0), (c_open, 2.0), (c_closed, 2.0), ]) def test_against_astropy(c2, a_max): if a_max > 1.0: z = numpy.array([1.0, 0., -0.25]) else: z = numpy.array([1.0, 0.]) # classylss pars = {'h':c2.h, 'Omega_cdm':c2.Odm0, 'Omega_b':c2.Ob0, 'Omega_k':c2.Ok0, 'T_cmb':c2.Tcmb0.value, 'a_max':a_max} cosmo = ClassEngine(pars) ba = Background(cosmo) # age this = ba.time(z) that = c2.age(z).value assert_allclose(this, that, rtol=1e-3, atol=1e-3, err_msg='z = %s' %z)
import numpy as np import Config import BulletConstants from Classes import Array2d from scipy.interpolate import griddata from astropy.io import ascii from astropy.coordinates import SkyCoord from astropy import units as u import astropy.cosmology as cosmo Cosmo = cosmo.LambdaCDM(73., 0.270, 0.7299) class galaxy: def __init__(self): self.n = 0 #initial image position self.x0 = [] self.y0 = [] #current image position self.xc = [] self.yc = [] #source position self.xs = [] self.ys = [] #redshift and redshift factor self.z = [] self.zf = [] #magnification self.mag = [] self.rms = [] self.chi = []
def check_redshifts(): import astropy.cosmology as cc cosmo = cc.LambdaCDM(H0=70, Om0=0.3, Ode0=0.7) c = catIO.Readfile('../Catalog/SN-MARSHALL-F160W.reform.cat') c*k = c.number < -100 zc = catIO.Readfile('marshall_redshifts.dat') for id in zc.id: idi = int(id[-5:]) #print idi, c*k.sum() c*k = c*k | (c.number == idi) # star = (c.mag_auto[c*k] < 24) & (c.flux_radius[c*k] < 2.6) cat, zout, fout = unicorn.analysis.read_catalogs('UDS') mat = catIO.CoordinateMatcher(cat) dr, idx = mat.match_list(c.x_world, c.y_world) logm, logm_z, z_phot = fout.lmass[idx][c*k], fout.z[idx][c*k], zout.z_peak[idx][c*k] ok = (zc.z_max > 0) & ~star dz95 = (zc.u95-zc.l95)/(1+zc.z_max) dz68 = (zc.u68-zc.l68)/(1+zc.z_max) best = ok & (dz68 < 0.015) #plt.scatter(zc.z_max[best], zc.mag[best], alpha=0.5) #plt.scatter(zc.z_max[best], logm[best], alpha=0.5) zr = [0,4] zrange = np.log(1+np.array(zr)) dz = 0.01 nbins = zrange[1]/dz h = np.histogram(np.log(1+zc.z_max[best]), bins=nbins, range=zrange) h_idx = np.digitize(np.log(1+zc.z_max), h[1]) z = np.exp(h[1][:-1]*0.5+h[1][1:]*0.5)-1 cmv = h[1]*0. for i in range(len(h[1])): cmv[i] = cosmo.comoving_volume(h[1][i])/(4*np.pi*(360./2/np.pi)**2) survey_area = (2.2/60.)**2 #sq deg dcmv = np.diff(cmv)*survey_area nh = np.maximum(h[0], 0.01) plt.plot(z, nh, linestyle='steps') peak = np.abs(np.log(1+zc.z_max)-np.log(1+0.904)) < 0.005 peak = np.abs(np.log(1+zc.z_max)-np.log(1+1.912)) < 0.005 peak = np.abs(np.log(1+zc.z_max)-np.log(1+2.310)) < 0.005 zbin = 0.904; bin_id = np.arange(len(h[1]))[z >= zbin][0]+1 zbin = 1.912; bin_id = np.arange(len(h[1]))[z >= zbin][0]+1 zbin = 1.522; bin_id = np.arange(len(h[1]))[z >= zbin][0]+1 zbin = 2.310; bin_id = np.arange(len(h[1]))[z >= zbin][0]+1 sel = (h_idx == bin_id) & best fp = open('/tmp/view_list','w') for id in zc.id[sel]: fp.write('%s.new_zfit.png\n' %(id)) fp.write('%s.new_zfit.2D.png\n' %(id)) fp.write('%s_stack.png\n' %(id)) fp.close() os.system('open `cat /tmp/view_list`') plt.scatter(c.x_image, c.y_image, color='black', alpha=0.1) plt.scatter(c.x_image[c*k][sel], c.y_image[c*k][sel], color='red', alpha=0.8)
def __init__(self, H0=73.0, Om0=0.25, Ok0=None, w0=None, wa=None): """ Initialize the cosmology wrapper with the parameters specified (e.g. does not account for massive neutrinos) param [in] H0 is the Hubble parameter at the present epoch in km/s/Mpc param [in] Om0 is the current matter density paramter (fraction of critical density) param [in] Ok0 is the current curvature density parameter param [in] w0 is the current dark energy equation of state w0 paramter param[in] wa is the current dark energy equation of state wa paramter The total dark energy equation of state as a function of z is w = w0 + wa z/(1+z) Currently, this wrapper class expects you to specify either a LambdaCDM (flat or non-flat) cosmology or a w0, wa (flat or non-flat) cosmology. The default cosmology is taken as the cosmology used in the Millennium Simulation (Springel et al 2005, Nature 435, 629 or arXiv:astro-ph/0504097) Om0 = 0.25 Ob0 = 0.045 (baryons; not currently used in this code) H0 = 73.0 Ok0 = 0.0, (implying Ode0 approx 0.75) w0 = -1.0 wa = 0.0 where Om0 + Ok0 + Ode0 + Ogamma0 + Onu0 = 1.0 sigma_8 = 0.9 (rms mass flucutation in an 8 h^-1 Mpc sphere; not currently used in this code) ns = 1 (index of the initial spectrum of linear mas perturbations; not currently used in this code) """ self.activeCosmology = None if w0 is not None and wa is None: wa = 0.0 isCosmologicalConstant = False if (w0 is None and wa is None) or (w0==-1.0 and wa==0.0): isCosmologicalConstant = True isFlat = False if Ok0 is None or (numpy.abs(Ok0) < flatnessthresh): isFlat = True if isCosmologicalConstant and isFlat: universe = cosmology.FlatLambdaCDM(H0=H0, Om0=Om0) elif isCosmologicalConstant: tmpmodel = cosmology.FlatLambdaCDM(H0=H0, Om0=Om0) Ode0 = 1.0 - Om0 - tmpmodel.Ogamma0 - tmpmodel.Onu0 - Ok0 universe = cosmology.LambdaCDM(H0=H0, Om0=Om0, Ode0=Ode0) elif isFlat: universe = cosmology.Flatw0waCDM(H0=H0, Om0=Om0, w0=w0, wa=wa) else: tmpmodel = cosmology.Flatw0waCDM(H0=H0, Om0=Om0, w0=w0, wa=wa) Ode0 = 1.0 - Om0 - tmpmodel.Ogamma0 - tmpmodel.Onu0 - Ok0 universe = cosmology.w0waCDM(H0=H0, Om0=Om0, Ode0=Ode0, w0=w0, wa=wa) self.setCurrent(universe)
def cluster_rich(data_loc, halo_file, chris_data_root, chris_data_file, newfilename, write_data=True, clobber=True): """ Calculate a Cluster's richness via Miller N200 and Kern N200 data_loc : e.g. MassRich/TRUTH_CAUSTIC halo_file : e.g. halos.fits chris_data_root : e.g. /nfs/christoq_ls/C4/sdssdr12 chris_data_file : e.g. DR12_GalaxyPhotoData_wabs_wedges.fits or m19.1_allgals_wsdss_specerrs_abs.fits """ # Run through Kern richness estimator, mainly to get cluster pairs root = '/nfs/christoq_ls/nkern' C4 = CFOUR({'H0': 70, 'chris_data_root': chris_data_root}) C = Caustic() H0 = 70.0 c = 2.99792e5 Cosmo = cosmo.LambdaCDM(H0, 0.3, 0.7) keys = ['C', 'H0', 'c', 'Cosmo', 'C4'] varib = ez.create(keys, locals()) R = RICHNESS(varib) # Load Halos halos = fits.open(data_loc + '/' + halo_file)[1].data HaloID = halos['orig_order'] RA = halos['ra_avg'] DEC = halos['dec_avg'] Z = halos['z_avg'] RVIR = halos['RVIR'] # Load Galaxy Data gals = fits.open(chris_data_root + '/' + chris_data_file)[1].data # Change gals keys according to SDSSDR12 galaxy file if data_loc[-4:] != 'DR12': gals = dict(map(lambda x: (x, gals[x]), gals.names)) gals['objid'] = gals.pop('GAL_HALOID') gals['ra'] = gals.pop('GAL_RA') gals['dec'] = gals.pop('GAL_DEC') gals['z'] = gals.pop('GAL_Z_APP') gals['u_mag'] = gals.pop('GAL_SDSS_U') gals['g_mag'] = gals.pop('GAL_SDSS_G') gals['r_mag'] = gals.pop('GAL_SDSS_R') gals['i_mag'] = gals.pop('GAL_SDSS_I') gals['z_mag'] = gals.pop('GAL_SDSS_Z') gals['r_absmag'] = gals.pop('R_ABSMAG') # Derive Gal Cut Out Parameters arcs = np.array( Cosmo.arcsec_per_kpc_proper(Z)) * 15000. / 3600. # 15 Mpc in degrees # Kern richness arrays kern_N200 = [] HVD = [] pair_avg = [] Nspec = [] kern_obs_tot = [] kern_obs_back = [ ] # obs_back is number of non-member galaxies in central aperture around cluster (aka. already scaled to inner aperture) # Miller Richness Arrays new = fits.open(chris_data_root + '/richness_cr200_bcg/new.fits')[0].data newb = fits.open(chris_data_root + '/richness_cr200_bcg/newb.fits')[0].data newb *= 0.2 miller_N200 = [] miller_obs_tot = [] miller_obs_back = [] colfac = 9 bakfac = 1 mag3 = 4 v = 2 radfac = 1 # Loop over clusters print '' print '-' * 40 print '...calculating cluster richnesses' for i in range(len(HaloID)): if i % 100 == 0: print '...working on cluster ' + str(i) + ' out of ' + str( len(HaloID)) # Define Cluster parameters clus_ra = RA[i] clus_dec = DEC[i] clus_z = Z[i] clus_rvir = RVIR[i] haloid = HaloID[i] if np.isnan(clus_ra) == True or np.isnan(clus_dec) == True or np.isnan( clus_z) == True: richness.append(0) HVD.append(0) pair_avg.append(False) Nspec.append(0) continue # 15 Mpc in degrees of declination and degrees of RA d_dec = arcs[i] d_ra = d_dec / np.cos(clus_dec * np.pi / 180) d_z = 0.04 # Cut Out Galaxy Data Around Cluster cut = np.where((np.abs(gals['ra'] - clus_ra) < d_ra) & (np.abs(gals['dec'] - clus_dec) < d_dec) & (np.abs(gals['z'] - clus_z) < d_z))[0] gal_ra = gals['ra'][cut] gal_dec = gals['dec'][cut] gal_z = gals['z'][cut] gal_gmags = gals['g_mag'][cut] gal_rmags = gals['r_mag'][cut] gal_imags = gals['i_mag'][cut] gal_absr = gals['r_absmag'][cut] # Run Kern Richness Estimator rich = R.richness_est(gal_ra, gal_dec, gal_z, np.zeros(len(gal_z)), gal_gmags, gal_rmags, gal_imags, gal_absr, haloid, clus_ra, clus_dec, clus_z, clus_rvir=clus_rvir, spec_list=None, use_specs=False, use_bcg=False, fit_rs=False, fixed_vdisp=False, fixed_aperture=False, plot_sky=False, plot_gr=False, plot_phase=False, find_pairs=True) kern_N200.append(rich) HVD.append(R.vel_disp) pair_avg.append(R.pair) Nspec.append(R.Nspec) kern_obs_tot.append(R.obs_tot) kern_obs_back.append(R.obs_back_scaled) # Append Miller Richness Values k = halos['orig_order'][i] miller_N200.append(new[k, colfac, mag3, v, radfac] - newb[k, bakfac, mag3, v, radfac]) miller_obs_tot.append(new[k, colfac, mag3, v, radfac]) miller_obs_back.append(newb[k, bakfac, mag3, v, radfac]) kern_N200 = np.array(kern_N200) HVD = np.array(HVD) pair_avg = np.array(pair_avg) Nspec = np.array(Nspec) kern_obs_tot = np.array(kern_obs_tot) kern_obs_back = np.array(kern_obs_back) miller_N200 = np.array(miller_N200) miller_obs_tot = np.array(miller_obs_tot) miller_obs_back = np.array(miller_obs_back) print '...finished calculating richnesses' ## Write Data Out if write_data == True: print '...writing out halos.fits file' # Dictionary of new columns new_keys = [ 'kern_N200', 'HVD', 'pair_avg', 'Nspec', 'kern_obs_tot', 'kern_obs_back', 'miller_N200', 'miller_obs_tot', 'miller_obs_back' ] new_dic = ez.create(new_keys, locals()) # Original fits record file orig_table = halos # Write out own fits file keys = ['HaloID', 'RVIR'] + new_keys dic = ez.create(keys, locals()) fits_table(dic, keys, data_loc + '/richnesses.fits', clobber=True) # Append new columns fits_append(orig_table, new_dic, new_keys, filename=data_loc + '/' + newfilename, clobber=clobber) print '-' * 40 print ''
def hod_from_parameters(redshift=0, OmegaM0=0.27, OmegaL0=0.73, OmegaB0=0.046, H0=70.0, use_camb=True, init_power_amplitude=2.2e-9, init_power_spect_index=0.96, camb_halofit_version=None, camb_kmax=200.0, camb_k_per_logint=30, powesp_matter_file=None, powesp_linz0_file=None, hod_type=1, hod_mass_min=1e11, hod_mass_1=1e12, hod_alpha=1.0, hod_siglogM=0.5, hod_mass_0=1e11, f_gal=1.0, gamma=1.0, logM_min=8.0, logM_max=16.0, logM_step=0.005, scale_dep_bias=True, use_mvir_limit=True, halo_exclusion_model=2, use_tinker_bias_params=True, hankelN=6000, hankelh=0.0005, rmin=0.01, rmax=100.0, nr=100, rlog=True, fprof_grid_log_krvir=None, fprof_grid_log_conc=None, fprof_grid_gamma=None, fprof_grid_profile=None, fprof_grid_rhos=None, fprof_hankelN=12000, fprof_hankelh=1e-6, fprof_Nk_interp=100, fprof_Nm_interp=100): """ Construct an HODClustering object defining all the needed parameters. """ assert redshift >= 0 if redshift > 10: raise UserWarning("You entered a quite high value of redshift (>10). \ I am not sure these models are valid there, proceed at your own risk.") # First, build the Cosmology object # As we work always using distances in Mpc/h, we should be # fine setting H0=100 assert OmegaM0 >= 0 if (OmegaM0 + OmegaL0) != 1: raise UserWarning("You are using a non-flat cosmology. \ Are you sure that is what you really want?") cosmo_object = ac.LambdaCDM(H0=100, Om0=OmegaM0, Ode0=OmegaL0) # Calculate or read in the needed PowerSpectrum objects if use_camb: pk_matter_object = get_camb_pk(redshift=redshift, OmegaM0=OmegaM0, OmegaL0=OmegaL0, OmegaB0=OmegaB0, H0=H0, Pinit_As=init_power_amplitude, Pinit_n=init_power_spect_index, nonlinear=True, halofit_model=camb_halofit_version, kmax=camb_kmax, k_per_logint=camb_k_per_logint) pk_linz0_object = get_camb_pk(redshift=0, OmegaM0=OmegaM0, OmegaL0=OmegaL0, OmegaB0=OmegaB0, H0=H0, Pinit_As=init_power_amplitude, Pinit_n=init_power_spect_index, nonlinear=False, kmax=camb_kmax, k_per_logint=camb_k_per_logint) else: pk_matter_object = PowerSpectrum.fromfile(powesp_matter_file) pk_linz0_object = PowerSpectrum.fromfile(powesp_linz0_file) # Build the HOD object hod_object = hodmodel.HODModel(hod_type=hod_type, mass_min=hod_mass_min, mass_1=hod_mass_1, alpha=hod_alpha, siglogM=hod_siglogM, mass_0=hod_mass_0) # Build the halo model object. # We have two options for the parameters defining the bias: # - Use the original bias parameters from Sheth (2001), MoWhite2002 # - Use the modified parameters following Tinker (2005) if use_tinker_bias_params: bpar = 0.35 cpar = 0.8 else: bpar = 0.5 cpar = 0.6 halo_object = halomodel.HaloModelMW02(cosmo=cosmo_object, powesp_lin_0=pk_linz0_object, redshift=redshift, par_b=bpar, par_c=cpar) # Now, create the Hankel FourierTransform object needed for the conversions # P(k) --> xi(r) ft_hankel = hankel.SymmetricFourierTransform(ndim=3, N=hankelN, h=hankelh) # Define the array of r-values for the HODClustering object assert rmax > rmin assert rmin >= 0 assert nr > 0 if rlog: rvals_array = np.logspace(np.log10(rmin), np.log10(rmax), nr) else: rvals_array = np.linspace(rmin, rmax, nr) # Create the Hankel FourierTransform object corresponding to the conversion # of the halo radial profiles from config. to Fourier space fprof_ft_hankel = hankel.SymmetricFourierTransform(ndim=3, N=fprof_hankelN, h=fprof_hankelh) # And finally, define the clustering object model_clustering_object = \ HODClustering(redshift=redshift, cosmo=cosmo_object, powesp_matter=pk_matter_object, hod_instance=hod_object, halo_instance=halo_object, powesp_lin_0=pk_linz0_object, f_gal=f_gal, gamma=gamma, logM_min=logM_min, logM_max=logM_max, logM_step=logM_step, scale_dep_bias=scale_dep_bias, use_mvir_limit=use_mvir_limit, halo_exclusion_model=halo_exclusion_model, ft_hankel=ft_hankel, rvalues=rvals_array, fprof_grid_log_krvir=fprof_grid_log_krvir, fprof_grid_log_conc=fprof_grid_log_conc, fprof_grid_gamma=fprof_grid_gamma, fprof_grid_profile=fprof_grid_profile, fprof_grid_rhos=fprof_grid_rhos, fprof_ft_hankel=fprof_ft_hankel, fprof_Nk_interp=fprof_Nk_interp, fprof_Nm_interp=fprof_Nm_interp) print("New HODClustering object created, " f"galaxy density = {model_clustering_object.gal_dens:.4} (h/Mpc)^3") return model_clustering_object