toolscosmo 0.1.9__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. tools_cosmo/__init__.py +13 -0
  2. tools_cosmo/basic_functions.py +7 -0
  3. tools_cosmo/bias.py +82 -0
  4. tools_cosmo/calculator.py +23 -0
  5. tools_cosmo/constants.py +31 -0
  6. tools_cosmo/cosmo.py +546 -0
  7. tools_cosmo/cosmo_equations.py +82 -0
  8. tools_cosmo/emulate_BoltmannSolver.py +58 -0
  9. tools_cosmo/input_data/cpl_class_emulator.pkl +0 -0
  10. tools_cosmo/luminosity_function.py +145 -0
  11. tools_cosmo/mass_accretion.py +250 -0
  12. tools_cosmo/massfct.py +249 -0
  13. tools_cosmo/param.py +217 -0
  14. tools_cosmo/plotting_function.py +82 -0
  15. tools_cosmo/run_BoltzmannSolver.py +310 -0
  16. tools_cosmo/source_model.py +311 -0
  17. toolscosmo/EFT.py +2049 -0
  18. toolscosmo/__init__.py +20 -0
  19. toolscosmo/_merger_trees.py +472 -0
  20. toolscosmo/basic_functions.py +7 -0
  21. toolscosmo/bias.py +82 -0
  22. toolscosmo/calculator.py +23 -0
  23. toolscosmo/constants.py +31 -0
  24. toolscosmo/cosmo.py +561 -0
  25. toolscosmo/cosmo_equations.py +82 -0
  26. toolscosmo/cython_ParkinsonColeHelly2008.cpp +23113 -0
  27. toolscosmo/emulate_BoltmannSolver.py +69 -0
  28. toolscosmo/extreme_value_stats.py +149 -0
  29. toolscosmo/generate_ic.py +362 -0
  30. toolscosmo/input_data/Schneider2018_wdm_hmf.pkl +0 -0
  31. toolscosmo/input_data/cpl_class_emulator.pkl +0 -0
  32. toolscosmo/luminosity_function.py +144 -0
  33. toolscosmo/mass_accretion.py +246 -0
  34. toolscosmo/massfct.py +245 -0
  35. toolscosmo/merger_trees.py +426 -0
  36. toolscosmo/neural_networks.py +256 -0
  37. toolscosmo/num_sim_data.py +13 -0
  38. toolscosmo/param.py +237 -0
  39. toolscosmo/plotting_function.py +82 -0
  40. toolscosmo/run_BoltzmannSolver.py +318 -0
  41. toolscosmo/scipy_func.py +12 -0
  42. toolscosmo/source_model.py +308 -0
  43. toolscosmo-0.1.9.dist-info/LICENSE +674 -0
  44. toolscosmo-0.1.9.dist-info/METADATA +95 -0
  45. toolscosmo-0.1.9.dist-info/RECORD +47 -0
  46. toolscosmo-0.1.9.dist-info/WHEEL +6 -0
  47. toolscosmo-0.1.9.dist-info/top_level.txt +1 -0
@@ -0,0 +1,13 @@
1
+ from . import param, cosmo, constants
2
+ from . import mass_accretion, source_model, luminosity_function
3
+ from . import run_BoltzmannSolver, emulate_BoltmannSolver
4
+ from . import massfct
5
+
6
+ from .param import *
7
+ from .cosmo import *
8
+ from .bias import *
9
+ # from .mass_accretion import *
10
+ # from .source_model import *
11
+ # from .constants import *
12
+ from .luminosity_function import *
13
+ from . import plotting_function
@@ -0,0 +1,7 @@
1
+ import numpy as np
2
+
3
+ def z_to_a(z):
4
+ return 1/(1+z)
5
+
6
+ def a_to_z(a):
7
+ return 1./a-1
tools_cosmo/bias.py ADDED
@@ -0,0 +1,82 @@
1
+ """
2
+
3
+ CALCULATE HALO BIAS
4
+
5
+ """
6
+
7
+ import numpy as np
8
+
9
+ from .cosmo import growth_factor, variance
10
+
11
+
12
+ def halo_bias(param):
13
+ """
14
+ bias function adopted from Cooray&Sheth Eq.68
15
+ """
16
+
17
+ window = param.mf.window
18
+ cc = param.mf.c
19
+ Om = param.cosmo.Om
20
+ rhoc = param.cosmo.rhoc
21
+ dc = param.mf.dc
22
+ p = param.mf.p
23
+ q = param.mf.q
24
+
25
+ rbin, var, dlnvardlnr = variance(param)
26
+
27
+ if (window == 'tophat' or window == 'gaussian'):
28
+ mbin = 4*np.pi*Om*rhoc*rbin**3/3
29
+
30
+ elif (window == 'sharpk' or window == 'smoothk'):
31
+ mbin = 4*np.pi*Om*rhoc*(cc*rbin)**3/3
32
+
33
+
34
+ if (param.cosmo.zbin=='lin'):
35
+ zz = np.linspace(param.cosmo.zmin,param.cosmo.zmax,param.cosmo.Nz)
36
+ elif (param.cosmo.zbin=='log'):
37
+ zz = np.logspace(np.log(param.cosmo.zmin),np.log(param.cosmo.zmax),param.cosmo.Nz,base=np.e)
38
+ else:
39
+ print("ERROR: neither lin nor log for binning. Abort")
40
+ exit()
41
+
42
+ Dz = growth_factor(zz, param)
43
+
44
+ bias = []
45
+ for i in range(len(zz)):
46
+ dcz = dc/Dz[i]
47
+ nu = dcz**2.0/var
48
+
49
+ if(param.code.bias=='spherical'):
50
+ #spherical collapse
51
+ bias += [1.0 + (nu - 1.0)/dc]
52
+
53
+ elif(param.code.bias=='ellipsoidal'):
54
+ #cooray and sheth
55
+ e1 = (q*nu - 1.0)/dc
56
+ E1 = 2.0*p/dc/(1.0 + (q*nu)**p)
57
+ bias += [1.0 + e1 + E1]
58
+
59
+ elif(param.code.bias=='tinker'):
60
+ #tinker
61
+ y = np.log10(200)
62
+ A = 1+0.24*y*np.exp(-(4/y)**4)
63
+ a = 0.44*y - 0.88
64
+ B = 0.183
65
+ b = 1.5
66
+ C = 0.019 + 0.107*y+0.19*np.exp(-(4/y)**4)
67
+ c = 2.4
68
+ bias += [1-A*nu**(a/2)/(nu**(a/2) + dc**a) + B*nu**(b/2) + C*nu**(c/2)]
69
+
70
+ elif(param.code.bias=='jing'):
71
+ #Jing98
72
+ par1 = 1 + (nu-1.0)/dc
73
+ par2 = (1 + 1/(2*nu**4 - 1.0))**(0.06-0.02*0.96)
74
+ bias += [par1*par2]
75
+
76
+ else:
77
+ print("ERROR: bias method does not exist!")
78
+ exit()
79
+
80
+ bias = np.array(bias)
81
+
82
+ return mbin, zz, bias
@@ -0,0 +1,23 @@
1
+ import numpy as np
2
+ from scipy.integrate import quad
3
+
4
+ from .basic_functions import *
5
+ from .cosmo_equations import *
6
+ from . import constants as const
7
+
8
+ def age_estimator(param, z):
9
+ '''
10
+ Age estimator of the Universe.
11
+
12
+ Parameters:
13
+ param (object): object containing the parameter values
14
+ z (float): redshift
15
+
16
+ Returns:
17
+ * The age of the universe in Gyr
18
+ '''
19
+ Feq = FriedmannEquation(param)
20
+ a = z_to_a(z)
21
+ I = lambda a: 1/a/Feq.H(a=a)
22
+ t = lambda a: quad(I, 0, a)[0]*const.Mpc_to_km/const.Gyr_to_s
23
+ return np.vectorize(t)(a)
@@ -0,0 +1,31 @@
1
+ """
2
+
3
+ CONSTANTS AND UNIT CONVERSIONS
4
+
5
+ """
6
+
7
+ #Constants
8
+ c = 2.99792e5 # Speed of light [km/s]
9
+ hP = 4.1357e-15 # Planck constant [eV/Hz]
10
+ m_p = 8.4119e-58 # Proton mass in [Msun]
11
+ kB = 1.380649e-16 # Boltzmann constsant [erg/K]
12
+ rhoc0 = 2.755e11 # Critical density at z=0 [h^2 Msun/Mpc^3]
13
+
14
+ nu_LL = 3.2898e15 # Lyman-limit frequency [Hz]
15
+ nu_al = 2.4674e15 # Lyman-alpha frequency [Hz]
16
+ nu_be = 2.9243e15 # Lyman-beta frequency [Hz]
17
+
18
+ f_He_bymass = 0.2453 # Helium fraction by mass from BBN
19
+ f_He_bynumb = 1/(1/f_He_bymass-1)/4 # Helium fraction by number
20
+
21
+ #Unit conversions
22
+ sec_per_yr = 3600*24*365.25 # Seconds per year
23
+ cm_per_Mpc = 3.08568e24 # Centimetres per Mpc
24
+ km_per_Mpc = cm_per_Mpc/1e5 # km per Mpc
25
+ eV_per_erg = 6.24151e11 # eV per erg
26
+
27
+
28
+ #Unsorted
29
+ c_kmps = 299792.
30
+ Mpc_to_km = 3.0860e19
31
+ Gyr_to_s = 3.1536e16
tools_cosmo/cosmo.py ADDED
@@ -0,0 +1,546 @@
1
+ """
2
+
3
+ FUNCTIONS RELATED TO COSMOLOGY
4
+
5
+ """
6
+ import numpy as np
7
+ from scipy.integrate import cumtrapz, trapz, quad, odeint
8
+ from scipy.interpolate import splrep, splev, interp1d
9
+ from astropy import cosmology, units
10
+
11
+ from .constants import rhoc0,c
12
+ from .run_BoltzmannSolver import *
13
+ from .emulate_BoltmannSolver import *
14
+
15
+ def prepare_cosmo_solver(param):
16
+ if param.code.verbose: print('Preparing cosmological solvers...')
17
+ if param.cosmo.solver.lower()=='astropy':
18
+ solver_estimator = astropy_cosmo(param).cosmo
19
+ if param.code.verbose: print('astropy will be used.')
20
+ elif param.cosmo.solver.lower()=='camb':
21
+ cosmo_camb = run_camb(param)
22
+ solver_estimator = cosmo_camb['results']
23
+ if param.file.ps.lower()=='camb':
24
+ PS = {'k': cosmo_camb['k'], 'P': cosmo_camb['P']}
25
+ param.file.ps = PS
26
+ else:
27
+ print('CAMB is used for cosmological calculations.')
28
+ print(f'Using CAMB instead of {param.file.ps} for modelling linear power spectrum will avoid running another Boltzmann solver.')
29
+ if param.code.verbose: print('CAMB will be used.')
30
+ elif param.cosmo.solver.lower()=='class':
31
+ cosmo_class = run_class(param)
32
+ solver_estimator = cosmo_class.class_module
33
+ if param.file.ps.lower()=='class':
34
+ PS = {'k': cosmo_class.k, 'P': cosmo_class.pk_lin}
35
+ param.file.ps = PS
36
+ else:
37
+ print('CLASS is used for cosmological calculations.')
38
+ print(f'Using CLASS instead of {param.file.ps} for modelling linear power spectrum will avoid running another Boltzmann solver.')
39
+ if param.code.verbose: print('CLASS will be used.')
40
+ else:
41
+ solver_estimator = None
42
+ param.cosmo.solver_estimator = solver_estimator
43
+ if param.code.verbose: print('...done')
44
+ return param
45
+
46
+ def rhoc_of_z(z,param):
47
+ """
48
+ Redshift dependence of critical density
49
+ (in comoving units where rho_b=const; same as in AHF)
50
+ """
51
+ Om = param.cosmo.Om
52
+ Ol = 1.0-Om
53
+ return rhoc0*(Om*(1.0+z)**3.0 + Ol)/(1.0+z)**3.0
54
+
55
+ def ez_grownu(z, om, omega_rad, omega_nu, oe):
56
+ # om, omega_nu, oe, h0 = theta
57
+ #omega_rad = 2.469e-5 * (H0/100.)**-2. * (1+0.2271*3.04)
58
+ rad_term = omega_rad * (1+z)**4.
59
+ ods = 1 - om - omega_rad
60
+ a = 1./(1+z)
61
+ aval = (1-oe)*(ods - 2*omega_nu)
62
+ cval = oe*(ods - 1)
63
+ bval = 2*omega_nu*(1 - oe)
64
+ nume = -bval + np.sqrt(bval**2. - 4.*aval*cval)
65
+ denom = 2.*aval
66
+ a_trans = pow(nume/denom, 2./3)
67
+ mat_term = om*(1+z)**3.
68
+ # print(omega_nu,oe,a)
69
+ if a > a_trans:
70
+ ttop = ods*a**3. + 2*omega_nu*(pow(a, 3./2) - a**3.)
71
+ tbot = 1 - ods *(1 - a**3) + 2 * omega_nu * (pow(a, 3./2) - a**3)
72
+ ods_a = ttop/tbot
73
+ elif a <=a_trans:
74
+ ods_a = oe
75
+ ezsq = (mat_term + rad_term)/(1-ods_a)
76
+ return np.sqrt(ezsq) #1./np.sqrt(ezsq)
77
+
78
+ def Ez_growing_nu(z, Om0=0.315, Ok0=0.0, Or0=5.4e-5, Onu0=0.01, Oe0=0.01):
79
+ return np.vectorize(ez_grownu)(z, Om0, Or0, Onu0, Oe0)
80
+
81
+ def Ez_model(param):
82
+ """
83
+ Normalised Hubble parameter.
84
+ Exotic dark energy models can be defined here.
85
+ """
86
+ try:
87
+ cosmo = param.cosmo.solver_estimator
88
+ except:
89
+ param = prepare_cosmo_solver(param)
90
+ cosmo = param.cosmo.solver_estimator
91
+
92
+ if param.cosmo.solver.lower()=='astropy':
93
+ Ez = lambda z: cosmo.efunc(z)
94
+ return Ez
95
+ elif param.cosmo.solver.lower()=='camb':
96
+ Ez = lambda z: cosmo.hubble_parameter(z)/cosmo.hubble_parameter(0)
97
+ return Ez
98
+ elif param.cosmo.solver.lower()=='class':
99
+ Ez = np.vectorize(lambda z: cosmo.Hubble(z)/cosmo.Hubble(0))
100
+ return Ez
101
+ elif param.cosmo.solver.lower()=='tools_cosmo':
102
+ pass
103
+ else:
104
+ print(f'{param.cosmo.solver} is unknown and, therefore, set to tools_cosmo.')
105
+
106
+ Om = param.cosmo.Om
107
+ Or = param.cosmo.Or
108
+ Ol = 1.0-Om-Or # Flat universe assumption
109
+ # print(param.DE.__dict__)
110
+ Olz = lambda z: Omega_DE(z, param)
111
+ if param.DE.name.lower() in ['wcdm','cpl','lcdm']:
112
+ Ez = lambda z: (Om*(1+z)**3 + Or*(1+z)**4 + Olz)**0.5
113
+ elif param.DE.name.lower()=='growing_neutrino_mass':
114
+ Ez = lambda z: Ez_growing_nu(z, Om0=Om, Ok0=0.0, Or0=Or, Onu0=param.DE.Onu, Oe0=param.DE.Oede)
115
+ else:
116
+ Ez = lambda z: (Om*(1+z)**3 + Or*(1+z)**4 + Ol)**0.5
117
+ return Ez
118
+
119
+ def hubble(z,param):
120
+ """
121
+ Hubble parameter
122
+ """
123
+ try:
124
+ cosmo = param.cosmo.solver_estimator
125
+ except:
126
+ param = prepare_cosmo_solver(param)
127
+ cosmo = param.cosmo.solver_estimator
128
+
129
+ if param.cosmo.solver.lower()=='astropy':
130
+ return cosmo.H(z).value
131
+ elif param.cosmo.solver.lower()=='camb':
132
+ return cosmo.hubble_parameter(z)
133
+ elif param.cosmo.solver.lower()=='class':
134
+ return np.vectorize(lambda z0: cosmo.Hubble(z0)/cosmo.Hubble(0)*cosmo.h()*100)(z)
135
+ elif param.cosmo.solver.lower()=='tools_cosmo':
136
+ pass
137
+ else:
138
+ print(f'{param.cosmo.solver} is unknown and, therefore, set to tools_cosmo.')
139
+
140
+ H0 = 100.0*param.cosmo.h0
141
+ Ez = Ez_model(param)
142
+ return H0 * Ez(z)
143
+
144
+
145
+ def growth_factor(z, param):
146
+ """
147
+ Growth factor from Longair textbook (Eq. 11.56).
148
+ Also see arXiv:astro-ph/0006089
149
+
150
+ z: array of redshifts from zmin to zmax
151
+ """
152
+ if param.code.Dz_solver.lower() in ['linder2005','linder(2005)','linder (2005)']:
153
+ # print('Linder (2005) fitting function')
154
+ return growth_factor_Linder2005(z, param)
155
+ elif param.code.Dz_solver.lower() in ['solveode','ode']:
156
+ # print('Solving the ODE')
157
+ return growth_factor_solveODE(z, param)
158
+ else:
159
+ # print('Hamilton (2000) fitting function')
160
+ Om = param.cosmo.Om
161
+ D0 = hubble(0,param) * (5.0*Om/2.0) * quad(lambda a: (a*hubble(1/a-1,param))**(-3), 0.01, 1, epsrel=5e-3, limit=100)[0]
162
+ Dz = []
163
+ for i in range(len(z)):
164
+ Dz += [hubble(z[i],param) * (5.0*Om/2.0) * quad(lambda a: (a*hubble(1/a-1,param))**(-3), 0.01, 1/(1+z[i]), epsrel=5e-3, limit=100)[0]]
165
+ Dz = np.array(Dz)
166
+ return Dz/D0
167
+
168
+ def w_DE(z, param):
169
+ if param.DE.name.lower()=='lcdm':
170
+ w = -1
171
+ elif param.DE.name.lower()=='wcdm':
172
+ w = param.DE.w
173
+ elif param.DE.name.lower()=='cpl':
174
+ w = param.DE.w0 + param.DE.wa*z/(1+z)
175
+ else:
176
+ wDE = param.DE.wDE
177
+ if wDE is None:
178
+ print(f'Dark energy equation of state w(z) for {param.DE.name} should be provided through param.DE.wDE variable.')
179
+ w = wDE(z)
180
+ return w
181
+
182
+ def Omega_DE(z, param):
183
+ '''
184
+ Evolution of dark energy density parameter.
185
+ '''
186
+ a = 1/(1+z)
187
+ # Define cosmological parameters
188
+ # H0 = param.cosmo.h0*100 # Hubble constant in km/s/Mpc
189
+ Omega_m = param.cosmo.Om # Matter density parameter
190
+ Omega_k = param.cosmo.Ok # Curvature density parameter
191
+ Omega_r = param.cosmo.Or # Radiation density parameter
192
+ Omega_L = param.cosmo.Ode # Dark energy density parameter
193
+ if Omega_L is None: Omega_L = 1-Omega_m-Omega_k-Omega_r
194
+
195
+ if param.DE.name.lower()=='lcdm':
196
+ w = -1
197
+ return Omega_L * a**(3*(1+w))
198
+ elif param.DE.name.lower()=='wcdm':
199
+ w = param.DE.w
200
+ return Omega_L * a**(3*(1+w))
201
+ elif param.DE.name.lower()=='cpl':
202
+ w0, wa = param.DE.w0, param.DE.wa
203
+ return Omega_L * a**(3*(1+w0+wa)) * np.exp(-wa*a)
204
+ else:
205
+ wDE = param.DE.wDE
206
+ integrand = lambda a_prime: (1 + wDE(a_prime)) / a_prime
207
+ integral, _ = quad(integrand, a, 1)
208
+ return Omega_L * np.exp(3 * integral)
209
+
210
+ def growth_factor_solveODE(z, param):
211
+ # Define cosmological parameters
212
+ H0 = param.cosmo.h0*100 # Hubble constant in km/s/Mpc
213
+ Omega_m = param.cosmo.Om # Matter density parameter
214
+ Omega_k = param.cosmo.Ok # Curvature density parameter
215
+ Omega_r = param.cosmo.Or # Radiation density parameter
216
+ Omega_L = param.cosmo.Ode # Dark energy density parameter
217
+ if Omega_L is None: Omega_L = 1-Omega_m-Omega_k-Omega_r
218
+
219
+ w = lambda a: w_DE(1/a-1, param)
220
+ Omega_DE_a = lambda a: Omega_DE(1/a-1, param)
221
+
222
+ def E(a):
223
+ return np.sqrt(Omega_m * a**-3 + Omega_r * a**-4 + Omega_k * a**-2 + Omega_DE_a(a))
224
+
225
+ def dEda(a):
226
+ # Derivative of Hubble parameter w.r.t scale factor
227
+ return - (3/2) * Omega_m * a**-4 / E(a) - 2 * Omega_r * a**-5 / E(a) - Omega_k * a**-3 / E(a) + (3 * (1 + w(a)) * Omega_DE_a(a)) / (2 * a * E(a))
228
+
229
+ def diff_Da(y, a):
230
+ # Define the growth factor differential equation
231
+ D, dDda = y
232
+ dD2da2 = - (3/(2 * a**2 * E(a)**2)) * Omega_m * D - (3/a + (1/E(a)) * (dEda(a))) * dDda
233
+ return [dDda, dD2da2]
234
+
235
+ # Initial conditions
236
+ a_init = 1e-2 # Initial scale factor (early universe)
237
+ D_init = a_init # Initial growth factor D(a) ≈ a
238
+ dDda_init = 1.0 # Initial derivative dD/da ≈ 1
239
+ y0 = [D_init, dDda_init]
240
+
241
+ # Scale factor range to solve over
242
+ a_vals = np.linspace(a_init, 1, 1000)
243
+ z_vals = 1/a_vals-1
244
+ # Solve the differential equation
245
+ sol = odeint(diff_Da, y0, a_vals)
246
+ # Extract the growth factor solution
247
+ D_vals = sol[:, 0]
248
+
249
+ Dz = interp1d(z_vals,D_vals)
250
+ return Dz(z)/Dz(0)
251
+
252
+ def growth_factor_Linder2005(z, param):
253
+ """
254
+ A fit for growth factor from Linder (2005, PhRvD, 72, 043529)
255
+ that should work for most DDE models.
256
+
257
+ z: array of redshifts from zmin to zmax
258
+ """
259
+ Om = param.cosmo.Om
260
+ H0 = hubble(0,param)
261
+ Ha = lambda a: hubble(1/a-1,param)
262
+ Oa = lambda a: Om*a**(-3)/(Ha(a)/H0)**2
263
+ wz = lambda z: w_DE(z, param)
264
+ w1 = wz(1)
265
+ gamma = 0.55+0.05*(1+w1) if w1>=-1 else 0.55+0.02*(1+w1)
266
+ D0 = np.exp(quad(lambda a: (Oa(a)**gamma-1)/a, 0.01, 1, epsrel=5e-3, limit=100)[0])
267
+ Dz = np.array([])
268
+ for i in range(len(z)):
269
+ ln_Da = quad(lambda a: (Oa(a)**gamma-1)/a, 0.01, 1/(1+z[i]), epsrel=5e-3, limit=100)[0]
270
+ Dz = np.append(Dz,np.exp(ln_Da))
271
+ return Dz/D0/(1+z)
272
+
273
+
274
+ def comoving_distance(z,param):
275
+ """
276
+ Comoving distance between z=0 and z.
277
+ """
278
+ try:
279
+ cosmo = param.cosmo.solver_estimator
280
+ except:
281
+ param = prepare_cosmo_solver(param)
282
+ cosmo = param.cosmo.solver_estimator
283
+
284
+ if param.cosmo.solver.lower()=='astropy':
285
+ # cosmo = astropy_cosmo(param).cosmo
286
+ return cosmo.comoving_distance(z).to('Mpc').value
287
+ elif param.cosmo.solver.lower()=='camb':
288
+ return cosmo.comoving_radial_distance(z)
289
+ elif param.cosmo.solver.lower()=='class':
290
+ return np.vectorize(lambda z0: cosmo.comoving_distance(z0))(z)
291
+ elif param.cosmo.solver.lower()=='tools_cosmo':
292
+ pass
293
+ else:
294
+ print(f'{param.cosmo.solver} is unknown and, therefore, set to tools_cosmo.')
295
+
296
+ if isinstance(z,list): z = np.array(z)
297
+ # dcom = cumtrapz(c/hubble(z,param),z,initial=0) # [Mpc]
298
+ # dcom = lambda z: quad(lambda x: c/hubble(x,param), 0, z)[0]
299
+ zspace = lambda z: np.logspace(-3,np.log10(z))
300
+ dcom = lambda z: trapz(c/hubble(zspace(z),param), zspace(z)) if z>0 else 0
301
+ return np.vectorize(dcom)(z)
302
+
303
+ def luminosity_distance(z,param):
304
+ """
305
+ Luminosity distance between z=0 and z.
306
+ """
307
+ try:
308
+ cosmo = param.cosmo.solver_estimator
309
+ except:
310
+ param = prepare_cosmo_solver(param)
311
+ cosmo = param.cosmo.solver_estimator
312
+
313
+ if param.cosmo.solver.lower()=='astropy':
314
+ # cosmo = astropy_cosmo(param).cosmo
315
+ return cosmo.luminosity_distance(z).to('Mpc').value
316
+ elif param.cosmo.solver.lower()=='camb':
317
+ return cosmo.luminosity_distance(z)
318
+ elif param.cosmo.solver.lower()=='class':
319
+ return np.vectorize(lambda z0: cosmo.luminosity_distance(z0))(z)
320
+ elif param.cosmo.solver.lower()=='tools_cosmo':
321
+ pass
322
+ else:
323
+ print(f'{param.cosmo.solver} is unknown and, therefore, set to tools_cosmo.')
324
+
325
+ if isinstance(z,list): z = np.array(z)
326
+ return comoving_distance(z,param)*(1+z) # [Mpc]
327
+
328
+ def distance_modulus(z,param):
329
+ """
330
+ Distance modulus between z=0 and z.
331
+ """
332
+ try:
333
+ cosmo = param.cosmo.solver_estimator
334
+ except:
335
+ param = prepare_cosmo_solver(param)
336
+ cosmo = param.cosmo.solver_estimator
337
+
338
+ if param.cosmo.solver.lower()=='astropy':
339
+ # cosmo = astropy_cosmo(param).cosmo
340
+ return cosmo.distmod(z).to('mag').value
341
+ elif param.cosmo.solver.lower()=='camb':
342
+ return 5*np.log10(cosmo.luminosity_distance(z))+25
343
+ elif param.cosmo.solver.lower()=='class':
344
+ D_L = np.vectorize(lambda z0: cosmo.luminosity_distance(z0))(z)
345
+ return 5*np.log10(D_L)+25
346
+ elif param.cosmo.solver.lower()=='tools_cosmo':
347
+ pass
348
+ else:
349
+ print(f'{param.cosmo.solver} is unknown and, therefore, set to tools_cosmo.')
350
+
351
+ if isinstance(z,list): z = np.array(z)
352
+ return 5*np.log10(luminosity_distance(z,param))+25
353
+
354
+
355
+ def delta_comoving_distance(z0,z1,param):
356
+ """
357
+ Comoving distance between z0 and z1
358
+ if z0 and z1 are close together (no integral)
359
+ """
360
+ zh = (z0+z1)/2
361
+ return (z1-z0)*c/hubble(zh,param)
362
+
363
+
364
+ def T_cmb(z,param):
365
+ """
366
+ CMB temperature
367
+ """
368
+ Tcmb0 = param.cosmo.Tcmb
369
+ return Tcmb0*(1+z)
370
+
371
+
372
+ def read_powerspectrum(param, **info):
373
+ """
374
+ Linear power spectrum from file
375
+ """
376
+ try:
377
+ names='k, P'
378
+ PS = np.genfromtxt(param.file.ps,usecols=(0,1),comments='#',dtype=None, names=names)
379
+ except:
380
+ PS = calc_Plin(param, **info)
381
+ return PS
382
+
383
+ def calc_Plin(param, **info):
384
+ # print(param.file.ps)
385
+ if param.file.ps.lower()=='camb':
386
+ r = run_camb(param)
387
+ PS = {'k': r['k'], 'P': r['P']}
388
+ elif param.file.ps.lower()=='class':
389
+ class_ = run_class(param, **info)
390
+ PS = {'k': class_.k, 'P': class_.pk_lin}
391
+ elif param.file.ps.lower() in ['bacco', 'baccoemu']:
392
+ PS = run_bacco(param, **info)
393
+ elif param.file.ps.lower() in ['classemu']:
394
+ PS = emulate_camb(param, **info)
395
+ else:
396
+ print('Provide linear power spectrum via param.file.ps')
397
+ print('Option: file, CLASS, CAMB, BACCO')
398
+ PS = None
399
+ return PS
400
+
401
+ def get_Plin(param, **info):
402
+ return read_powerspectrum(param, **info)
403
+
404
+ def wf(y,param):
405
+ """
406
+ Window function
407
+ """
408
+ window = param.mf.window
409
+ if (window=='tophat'):
410
+ w = 3.0*(np.sin(y) - y*np.cos(y))/y**3.0
411
+ w[y>100] = 0
412
+ elif (window=='sharpk'):
413
+ w = np.ones(y)
414
+ w[y>1]=0
415
+ elif (window=='gaussian'):
416
+ w = np.exp(-y**2.0/2.0)
417
+ elif (window=='smoothk'):
418
+ beta = param.mf.beta
419
+ w = 1/(1+y**beta)
420
+ else:
421
+ print("ERROR: undefined window function!")
422
+ exit()
423
+ return w
424
+
425
+
426
+ def dwf(y,param):
427
+ """
428
+ Derivative Of window function
429
+ dwf = dwf(kR)/dln(kR)
430
+ """
431
+ window = param.mf.window
432
+ if (window == 'tophat'):
433
+ dw = 3.0*((y**2.0 - 3.0)*np.sin(y) + 3.0*y*np.cos(y))/y**3.0
434
+ dw[y>100] = 0
435
+ elif (window == 'sharpk'):
436
+ """
437
+ delta function (must be accounted for in main code)
438
+ """
439
+ dw = 0.0
440
+ elif (window == 'gaussian'):
441
+ dw = - y**2.0*np.exp(-y**2.0/2.0)
442
+ elif (window=='smoothk'):
443
+ beta = param.mf.beta
444
+ dw = - beta*y**beta/(1+y**beta)**2
445
+ else:
446
+ print("ERROR: undefined window function!")
447
+ exit()
448
+ return dw
449
+
450
+
451
+ def variance(param):
452
+ """
453
+ variance of density perturbations at z=0
454
+ """
455
+ #window function
456
+ window = param.mf.window
457
+
458
+ #read in linear power spectrum
459
+ try:
460
+ PS = param.cosmo.plin
461
+ kmin = min(PS['k'])
462
+ kmax = max(PS['k'])
463
+ except:
464
+ # names='k, P'
465
+ # PS = np.genfromtxt(param.file.psfct,usecols=(0,1),comments='#',dtype=None, names=names)
466
+ PS = read_powerspectrum(param)
467
+ kmin = min(PS['k'])
468
+ kmax = max(PS['k'])
469
+
470
+ #set binning
471
+ Nrbin = param.code.Nrbin
472
+ rmin = param.code.rmin
473
+ rmax = param.code.rmax
474
+ rbin = np.logspace(np.log(rmin),np.log(rmax),Nrbin,base=np.e)
475
+
476
+ #calculate variance and derivative
477
+ if (window == 'tophat' or window == 'gaussian' or window == 'smoothk'):
478
+ var = []
479
+ dlnvardlnr = []
480
+ for i in range(Nrbin):
481
+ #var
482
+ itd_var = PS['k']**2 * PS['P'] * wf(PS['k']*rbin[i],param)**2
483
+ var += [trapz(itd_var,PS['k'])/(2*np.pi**2)]
484
+ #dlnvar/dlnr
485
+ itd_dvar = PS['k']**2 * PS['P'] * wf(PS['k']*rbin[i],param) * dwf(PS['k']*rbin[i],param)
486
+ dlnvardlnr += [2*np.trapz(itd_dvar,PS['k'])/(2*np.pi**2*var[i])]
487
+ var = np.array(var)
488
+ dlnvardlnr = np.array(dlnvardlnr)
489
+ elif (window == 'sharpk'):
490
+ #var
491
+ Plin_tck = splrep(PS['k'],PS['P'])
492
+ kbin = 1/rbin
493
+ kbin = kbin[::-1]
494
+ var = cumtrapz(kbin**2 * splev(kbin,Plin_tck),kbin,initial=1e-5) / (2*np.pi**2)
495
+ var = var[::-1]
496
+ #dlnvar/dlnr
497
+ dlnvardlnr = -1/(2*np.pi**2*var) * splev(1/rbin,Plin_tck)/rbin**3.0
498
+ else:
499
+ print("ERROR: undefined window function!")
500
+ exit()
501
+
502
+ #write varfct to file
503
+ try:
504
+ np.savetxt(param.file.varfct, np.vstack((rbin, var, dlnvardlnr)).T)
505
+ except IOError:
506
+ print('IOERROR: cannot write varfct!')
507
+ exit()
508
+
509
+ return rbin, var, dlnvardlnr
510
+
511
+ class astropy_cosmo:
512
+ '''
513
+ A class to use astropy as cosmological calculation.
514
+ '''
515
+ def __init__(self, param):
516
+ self.param = param
517
+ cosmo = self.set_model()
518
+
519
+ def set_model(self, param=None):
520
+ if param is None: param = self.param
521
+ Om = param.cosmo.Om
522
+ Ob = param.cosmo.Ob
523
+ Or = param.cosmo.Or
524
+ Ode = 'flat' if param.cosmo.Ode is None else param.cosmo.Ode
525
+ h0 = param.cosmo.h0
526
+ if param.DE.name.lower()=='wcdm':
527
+ w = param.DE.w
528
+ if Ode.lower()=='flat': cosmo = cosmology.FlatwCDM(h0*100, Om, w0=w)
529
+ else: cosmo = cosmology.wCDM(h0*100, Om, Ode, w0=w)
530
+ elif param.DE.name.lower() in ['cpl','w0wa']:
531
+ w0 = param.DE.w0
532
+ wa = param.DE.wa
533
+ # print(w0, wa)
534
+ if Ode.lower()=='flat': cosmo = cosmology.Flatw0waCDM(h0*100, Om, w0=w0, wa=wa)
535
+ else: cosmo = cosmology.w0waCDM(h0*100, Om, Ode, w0=w0, wa=wa)
536
+ elif param.DE.name.lower()=='growing_neutrino_mass':
537
+ cosmo = None
538
+ elif param.DE.name.lower()=='lcdm':
539
+ if Ode.lower()=='flat': cosmo = cosmology.FlatLambdaCDM(h0*100, Om)
540
+ else: cosmo = cosmology.LambdaCDM(h0*100, Om, Ode)
541
+ else:
542
+ cosmo = cosmology.FlatLambdaCDM(h0*100, Om)
543
+ print(f'Flat-LambdaCDM is assumed as {param.DE.name} is unknown.')
544
+ self.cosmo = cosmo
545
+ return cosmo
546
+