2 import os, subprocess, glob, random
8 Build a data dictionary with columns named according to (k,z) bins, a 9 threshold value, and some prefix. 11 Assumes that stats_arr has shape: (N_samp, N_thres, N_z, N_kbins) 14 N_sam, N_thres, N_z, N_kbins = stats_arr.shape
18 for n
in range(N_thres):
20 for m
in range(N_kbins):
21 key =
"tot_%s_h%d_k%d_z%d" % (prefix, n+1, m+1, j+1)
22 data_dict[key] = stats_arr[:,n, j, m]
28 Save a Latin hypercube to disk as a text file. Parameter columns will be 29 ordered alphabetically by name. 34 Filename for output file. 36 Dictionary containing parameter names (keys) and array of parameter 37 values for all sample points (values). 40 pnames = sample_points.keys()
42 hdr =
" ".join(pnames)
45 dat = np.column_stack([sample_points[p]
for p
in pnames])
46 np.savetxt(fname, dat, header=hdr, fmt=
"%4.4e")
47 print(
"Saved hypercube to '%s'." % fname)
52 Load a Latin hypercube from disk. Parameter columns will be ordered 53 alphabetically by name. 58 Filename to read sample points from. 63 Dictionary containing parameter names (keys) and array of parameter 64 values for all sample points (values). 68 hdr = f.readline()[2:-1].split(" ")
72 dat = np.loadtxt(fname).T
76 for i
in range(len(hdr)):
77 sample_points[hdr[i]] = dat[i]
83 Generate a Latin hypercube for a given set of parameters. 88 Number of samples points to draw from the hypercube. 91 Dictionary containing parameter names (keys) and tuple with min/max. 95 Path to directory containing 'class' executable. 98 Random seed to use when sampling from hypercube. 103 Dictionary containing parameter names (keys) and array of parameter 104 values for all sample points (values). 111 for key
in param_dict.keys():
112 sample_points[key] = np.zeros(samples)
113 Ndim = len(param_dict.keys())
114 pnames = [key
for key
in param_dict.keys()]
120 for i
in range(samples):
124 for j, p
in enumerate(pnames):
125 pmin, pmax = param_dict[p]
126 idx = random.choice(l[j])
129 sample_points[p][i] = pmin + (pmax - pmin) \
130 * (idx + 0.5) / float(samples)
137 default_params=
None, nonlin=
False, mode=
'std'):
139 Generate linear and non-linear power spectra using CCL, for a set of 140 points in cosmological parameter space and redshift. 145 Dictionary containing parameter names (keys) and array of parameter 146 values for all sample points (values). 149 Path of directory in which output files should be stored. 151 class_data_root : str 152 Root of filenames in which CLASS power spectra were stored. 155 Array of redshifts at which the power spectra should be evaluated. 157 default_params : dict, optional 158 Dictionary of default cosmological parameters, to be used if a 159 necessary parameter is not included in sample_points. 161 nonlin : bool, optional 162 Whether to load non-linear P(k). Default: False. 165 Which mode the CLASS run was performed in. Default: 'std'. 169 pnames = sample_points.keys()
170 Nsamp = sample_points[pnames[0]].size
173 for i
in range(Nsamp):
174 print(
"Calculating CCL power spectrum %d / %d" % (i, Nsamp))
177 class_file =
"%s_%05dz1_pk.dat" % (class_data_root, i)
178 k_class, pk_class = np.genfromtxt(class_file).T
179 k_class *= sample_points[
'h'][i]
182 class_file_nl =
"%s_%05dz1_pk_nl.dat" % (class_data_root, i)
183 k_class_nl, pk_class_nl = np.genfromtxt(class_file_nl).T
184 k_class_nl *= sample_points[
'h'][i]
188 for p
in sample_points.keys():
191 params[
'Omega_c'] = sample_points[p][i]
193 params[p] = sample_points[p][i]
196 params[
'transfer_function'] =
'boltzmann' 197 cosmo = ccl.Cosmology(**params)
201 for j, z
in enumerate(zvals):
204 pk_lin = ccl.linear_matter_power(cosmo, k_class, a)
206 pk_nl = ccl.nonlin_matter_power(cosmo, k_class_nl, a)
207 except KeyboardInterrupt:
210 print "--- Error running CLASS" 211 print "--- Parameters:", params
217 fname_nl =
"%s_nl_%s_%05d_z%d.dat" % (root, mode, i, j+1)
218 np.savetxt(fname_nl, np.column_stack((k_class_nl, pk_nl)))
220 fname_lin =
"%s_lin_%s_%05d_z%d.dat" % (root, mode, i, j+1)
221 np.savetxt(fname_lin, np.column_stack((k_class, pk_lin)))
224 if len(errored) > 0:
print "ERRORED:" 230 redshifts=np.arange(0., 3., 0.5)):
232 Generate CLASS .ini files for a set of parameters. 237 Dictionary containing parameter names (keys) and array of parameter 238 values for all sample points (values). 241 Path of directory in which .ini files should be stored. 243 nonlinear : bool, optional 244 Whether CLASS should return the linear or nonlinear (halofit) power 245 spectrum. Default: False. 248 Whether to include massive neutrinos. 250 redshifts : array_like, optional 251 Array of redshift values at which P(k) should be calculated. Default: 252 Five bins from 0.0 to 2.5 in increments of 0.5. 255 pnames = sample_points.keys()
256 Nsamp = sample_points[pnames[0]].size
259 for i
in range(Nsamp):
260 if i % 10 == 0: print(
" Writing CLASS .ini file %d / %d" % (i, Nsamp))
263 f = open(
"%s_%05d.ini" % (root, i),
'w')
266 f.write(
'root = %s_%05d\n' % (root, i))
271 if p ==
'w0' or p ==
'w_0':
272 f.write(
"w0_fld = %e\n" % sample_points[p][i])
273 elif p ==
'wa' or p ==
'w_a':
274 f.write(
"wa_fld = %e\n" % sample_points[p][i])
277 f.write(
"%s = %e\n" % (p, sample_points[p][i]))
280 f.write(
"z_pk = %s\n" % (
",".join([
"%3.3f" % z
for z
in redshifts])))
283 if nonlinear: f.write(
"non linear = halofit\n")
286 if 'Omega_k' not in pnames: f.write(
'Omega_k = 0.0\n')
289 N_ur = 2.0328
if mnu
else 3.046
290 N_ncdm = 1
if mnu
else 0
291 f.write(
"N_ur = %f\n" % N_ur)
292 f.write(
"N_ncdm = %f\n" % N_ncdm)
293 if mnu: f.write(
"m_ncdm = 0.06\n")
297 defaults =
"T_cmb = 2.725\n\ 298 #Omega_dcdmdr = 0.0\n\ 299 #Gamma_dcdm = 0.0 \n\ 304 #recombination = RECFAST\n\ 305 #reio_parametrization = reio_camb\n\ 307 #reionization_exponent = 1.5\n\ 308 #reionization_width = 0.5\n\ 309 #helium_fullreio_redshift = 3.5\n\ 310 #helium_fullreio_width = 0.5\n\ 311 #annihilation = 0.\n\ 312 #annihilation_variation = 0.\n\ 313 #annihilation_z = 1000\n\ 314 #annihilation_zmax = 2500\n\ 315 #annihilation_zmin = 30\n\ 316 #annihilation_f_halo = 20\n\ 317 #annihilation_z_halo = 8\n\ 318 #on the spot = yes\n\ 324 #P_k_ini type = analytic_Pk\n\ 327 P_k_max_h/Mpc = 100.\n\ 328 #l_max_scalars = 8000\n\ 332 write background = no\n\ 333 write thermodynamics = no\n\ 334 write primordial = no\n\ 335 write parameters = yeap\n\ 337 background_verbose = 1\n\ 338 thermodynamics_verbose = 1\n\ 339 perturbations_verbose = 1\n\ 340 transfer_verbose = 1\n\ 341 primordial_verbose = 1\n\ 342 spectra_verbose = 1\n\ 343 nonlinear_verbose = 1\n\ 344 lensing_verbose = 1\n\ 345 output_verbose = 1\n" 350 def run_class(fname_pattern, class_root, precision=False):
352 Run CLASS on a set of .ini files. 357 Pattern (glob format) for matching the .ini files to be run by CLASS. 360 Directory in which the 'class' executable is stored. 362 precision : bool, optional 363 Whether to run CLASS in high-precision mode (using the pk_ref.pre 368 fnames = glob.glob(fname_pattern)
373 for i, filename
in enumerate(fnames):
374 print(
"CLASS run %d / %d (%s)" % (i+1, len(fnames), filename))
377 cmd = [
'%s/class' % class_root, filename]
378 if precision: cmd += [
'%s/pk_ref.pre' % class_root,]
380 stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
381 basefile = os.path.splitext(
'%s' % filename)[0]
382 f = open(
'%s.txt' % basefile,
'w')
385 except KeyboardInterrupt:
390 print(
" CLASS run failed. Skipping.")
395 thresholds=[5e-5, 1e-4, 5e-4, 1e-3, 5e-3, 1e-2],
396 scale_ranges = [(1e-4, 1e-2), (1e-2, 1e-1), (1e-1, 1e0)],
397 z_vals = [
'1',
'2',
'3',
'4',
'5',
'6'],
400 Calculate summary stats for the deviation between CCL and reference power 401 spectra as a function of scale and redshift, for a large number of sample 402 points over the cosmological parameter space. 407 Dictionary containing parameter names (keys) and array of parameter 408 values for all sample points (values). 411 Root of filenames of CCL power spectrum files 413 class_data_root : str 414 Root of filenames of CLASS power spectrum files. If the string '_nl_' 415 is found in class_data_root, this will assume that nonlinear power 416 spectra should be loaded. 420 N_samp = sample_points[sample_points.keys()[0]].size
421 N_thres = len(thresholds)
423 N_kbins = len(scale_ranges)
426 if cache_name
is not None:
428 stats = np.load(
"%s.npy" % cache_name)
429 print(
" Loaded '%s' from cache." % cache_name)
431 frac_dev = np.load(
"%s.frac_dev.npy" % cache_name)
432 print(
" Loaded '%s.frac_dev' from cache." % cache_name)
434 k_arr = np.load(
"%s.k_arr.npy" % cache_name)
435 print(
" Loaded '%s.k_arr' from cache." % cache_name)
437 assert stats.shape == (N_samp, N_thres, N_z, N_kbins)
438 return stats, frac_dev, k_arr
440 print(
" Cache '%s' not found. Recomputing." % cache_name)
445 stats = np.zeros((N_samp, N_thres, N_z, N_kbins))
446 frac_dev = [[[]
for j
in range(N_z)]
for i
in range(N_samp)]
447 k_arr = [[[]
for j
in range(N_z)]
for i
in range(N_samp)]
450 for i
in range(N_samp):
451 print " Loading power spectra for parameter set %05d" % i
454 h = sample_points[
'h'][i]
462 fname_ccl =
"%s_%05d_z%d.dat" % (ccl_data_root, i, j+1)
463 if '_nl_' in class_data_root:
464 fname_class =
"%s_%05dz%d_pk_nl.dat" % (class_data_root, i, j+1)
466 fname_class =
"%s_%05dz%d_pk.dat" % (class_data_root, i, j+1)
469 pk_ccl_dat = np.loadtxt(fname_ccl)
470 ccl_k = pk_ccl_dat[:,0]
471 ccl_pk = pk_ccl_dat[:,1]
474 pk_class_dat = np.loadtxt(fname_class)
475 class_k = pk_class_dat[:,0]
476 class_pk = pk_class_dat[:,1] / h**3.
479 print ccl_pk.size, class_pk.size
480 assert ccl_pk.size == class_pk.size
483 frac_dev[i][j] = ccl_pk/class_pk - 1.
487 for m
in range(N_kbins):
488 kmin, kmax = scale_ranges[m]
489 idxs = np.logical_and(ccl_k >= kmin, ccl_k < kmax)
493 for n, thres
in enumerate(thresholds):
496 np.abs(ccl_pk[idxs]/class_pk[idxs] - 1.) / thres)
497 dev[np.where(dev < 0.)] = 0.
500 stats[i, n, j, m] = np.sum(dev)
504 print(
" Failed to compute stats for sample %05d." % i)
505 stats[i, :, :, :] = np.nan
508 if cache_name
is not None:
509 np.save(cache_name, stats)
510 np.save(
"%s.frac_dev" % cache_name, frac_dev)
511 np.save(
"%s.k_arr" % cache_name, k_arr)
512 return stats, np.array(frac_dev), k_arr
516 fname_template=
'../stats/lhs_mpk_err_lin_%05d_z%d.dat',
517 thresholds=[5e-5, 1e-4, 5e-4, 1e-3, 5e-3, 1e-2],
518 scale_ranges = [(1e-4, 1e-2), (1e-2, 1e-1), (1e-1, 1e0)],
519 z_vals = [
'1',
'2',
'3',
'4',
'5',
'6'],
522 Calculate summary stats for the deviation between CCL and reference power 523 spectra as a function of scale and redshift, for a large number of sample 524 points over the cosmological parameter space. 527 N_samp = params[
'id'].size
528 N_thres = len(thresholds)
530 N_kbins = len(scale_ranges)
533 if cache_name
is not None:
535 stats = np.load(
"%s.npy" % cache_name)
536 print " Loaded '%s' from cache." % cache_name
537 assert stats.shape == (N_samp, N_thres, N_z, N_kbins)
544 stats = np.zeros((N_samp, N_thres, N_z, N_kbins))
547 for i
in range(N_samp):
548 trial = params[
'id'][i]
549 print " Loading CCL power spectra for parameter set %05d" % i
555 fname = fname_template % (i, z_vals[j])
556 pk_ccl_dat = np.loadtxt(fname, skiprows=1)
557 ccl_k = pk_ccl_dat[:,0]
558 ccl_pk = pk_ccl_dat[:,1]
561 for m
in range(N_kbins):
562 kmin, kmax = scale_ranges[m]
563 idxs = np.logical_and(ccl_k >= kmin, ccl_k < kmax)
569 for n, thres
in enumerate(thresholds):
571 dev = np.log10(np.abs(ccl_pk[idxs]) / thres)
572 dev[np.where(dev < 0.)] = 0.
575 stats[i, n, j, m] = np.sum(dev)
578 if cache_name
is not None:
579 np.save(cache_name, stats)
def generate_latin_hypercube(samples, param_dict, class_root, seed=10)
def save_hypercube(fname, sample_points)
def load_summary_stats(sample_points, ccl_data_root, class_data_root, thresholds=[5e-5, e, e, e, e, e, scale_ranges=[(1e-4, 1e-2), e, e, e, e0, z_vals=['1', cache_name=None)
def build_data_dict(stats_arr, prefix)
def generate_class_ini(sample_points, root, nonlinear=False, mnu=False, redshifts=np.arange(0., 3., 0.5))
def load_hypercube(fname)
auto range(T const &first, T const &last) -> Generator< T >
def ccl_summary_stats(params, fname_template='../stats/lhs_mpk_err_lin_%05d_z%d.dat', thresholds=[5e-5, e, e, e, e, e, scale_ranges=[(1e-4, 1e-2), e, e, e, e0, z_vals=['1', cache_name=None)
def run_class(fname_pattern, class_root, precision=False)
def generate_ccl_pspec(sample_points, root, class_data_root, zvals, default_params=None, nonlin=False, mode='std')