Fast Methods for Cosmological Simulations
FastSim serves as a tool for quick N-body simulations in modified gravity.
param_space Namespace Reference

Functions

def build_data_dict (stats_arr, prefix)
 
def save_hypercube (fname, sample_points)
 
def load_hypercube (fname)
 
def generate_latin_hypercube (samples, param_dict, class_root, seed=10)
 
def generate_ccl_pspec (sample_points, root, class_data_root, zvals, default_params=None, nonlin=False, mode='std')
 
def generate_class_ini (sample_points, root, nonlinear=False, mnu=False, redshifts=np.arange(0., 3., 0.5))
 
def run_class (fname_pattern, class_root, precision=False)
 
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 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)
 

Function Documentation

def param_space.build_data_dict (   stats_arr,
  prefix 
)
Build a data dictionary with columns named according to (k,z) bins, a
threshold value, and some prefix.

Assumes that stats_arr has shape: (N_samp, N_thres, N_z, N_kbins)

Definition at line 6 of file param_space.py.

References Catch::Generators.range().

6 def build_data_dict(stats_arr, prefix):
7  """
8  Build a data dictionary with columns named according to (k,z) bins, a
9  threshold value, and some prefix.
10 
11  Assumes that stats_arr has shape: (N_samp, N_thres, N_z, N_kbins)
12  """
13  # Get no. of points in each dimension.
14  N_sam, N_thres, N_z, N_kbins = stats_arr.shape
15 
16  # Create dictionary with column names that can be used by ColumnDataSource
17  data_dict = {}
18  for n in range(N_thres):
19  for j in range(N_z):
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]
23  return data_dict
24 
25 
def build_data_dict(stats_arr, prefix)
Definition: param_space.py:6
auto range(T const &first, T const &last) -> Generator< T >
Definition: catch.hpp:3156
def param_space.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 
)
Calculate summary stats for the deviation between CCL and reference power
spectra as a function of scale and redshift, for a large number of sample
points over the cosmological parameter space.

Definition at line 520 of file param_space.py.

References Catch::Generators.range().

Referenced by load_summary_stats().

520  cache_name=None):
521  """
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.
525  """
526  # Get dimensions of stats array that will be constructed
527  N_samp = params['id'].size
528  N_thres = len(thresholds)
529  N_z = len(z_vals)
530  N_kbins = len(scale_ranges)
531 
532  # Check if data were cached
533  if cache_name is not None:
534  try:
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)
538  return stats, params
539  except:
540  raise
541 
542  # Create array to hold summary statistics, with shape:
543  # (N_samp, N_thres, N_z, N_kbins)
544  stats = np.zeros((N_samp, N_thres, N_z, N_kbins))
545 
546  # Loop over sample points in parameter space and calculate summary stats
547  for i in range(N_samp):
548  trial = params['id'][i]
549  print " Loading CCL power spectra for parameter set %05d" % i
550 
551  # Loop over redshift values
552  for j in range(N_z):
553 
554  # Load cached CCL power spectrum data
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]
559 
560  # Calculate summary stats in each k bin
561  for m in range(N_kbins):
562  kmin, kmax = scale_ranges[m]
563  idxs = np.logical_and(ccl_k >= kmin, ccl_k < kmax)
564 
565  # Calculate deviation statistic, Delta, for a range of
566  # threshold values (only values above the threshold are counted)
567  # FIXME: ccl_pk is actually the deviation, which was
568  # precomputed somewhere!
569  for n, thres in enumerate(thresholds):
570  # Calculate deviation statistic
571  dev = np.log10(np.abs(ccl_pk[idxs]) / thres)
572  dev[np.where(dev < 0.)] = 0.
573 
574  # Store result in stats array (N_samp, N_thres, N_z, N_kbins)
575  stats[i, n, j, m] = np.sum(dev)
576 
577  # Save to cache file
578  if cache_name is not None:
579  np.save(cache_name, stats)
580 
581  return stats, params
582 
auto range(T const &first, T const &last) -> Generator< T >
Definition: catch.hpp:3156
def param_space.generate_ccl_pspec (   sample_points,
  root,
  class_data_root,
  zvals,
  default_params = None,
  nonlin = False,
  mode = 'std' 
)
Generate linear and non-linear power spectra using CCL, for a set of
points in cosmological parameter space and redshift.

Parameters
----------
sample_points : dict
    Dictionary containing parameter names (keys) and array of parameter
    values for all sample points (values).

root : str
    Path of directory in which output files should be stored.

class_data_root : str
    Root of filenames in which CLASS power spectra were stored.

zvals : array_like
    Array of redshifts at which the power spectra should be evaluated.

default_params : dict, optional
    Dictionary of default cosmological parameters, to be used if a
    necessary parameter is not included in sample_points.

nonlin : bool, optional
    Whether to load non-linear P(k). Default: False.

mode : str, optional
    Which mode the CLASS run was performed in. Default: 'std'.

Definition at line 137 of file param_space.py.

References generate_class_ini(), and Catch::Generators.range().

Referenced by generate_latin_hypercube().

137  default_params=None, nonlin=False, mode='std'):
138  """
139  Generate linear and non-linear power spectra using CCL, for a set of
140  points in cosmological parameter space and redshift.
141 
142  Parameters
143  ----------
144  sample_points : dict
145  Dictionary containing parameter names (keys) and array of parameter
146  values for all sample points (values).
147 
148  root : str
149  Path of directory in which output files should be stored.
150 
151  class_data_root : str
152  Root of filenames in which CLASS power spectra were stored.
153 
154  zvals : array_like
155  Array of redshifts at which the power spectra should be evaluated.
156 
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.
160 
161  nonlin : bool, optional
162  Whether to load non-linear P(k). Default: False.
163 
164  mode : str, optional
165  Which mode the CLASS run was performed in. Default: 'std'.
166  """
167 
168  # Get list of parameter names
169  pnames = sample_points.keys()
170  Nsamp = sample_points[pnames[0]].size
171 
172  # Loop over sets of parameters, getting CCL power spectra for each
173  for i in range(Nsamp):
174  print("Calculating CCL power spectrum %d / %d" % (i, Nsamp))
175 
176  # Load the CLASS power spectra to get k bins (lin and NL can differ!)
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] # Convert to non-h^-1 units
180 
181  if nonlin:
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] # Convert to non-h^-1 units
185 
186  # Build parameter dictionary
187  params = {}
188  for p in sample_points.keys():
189  # Treat parameters with different naming conventions as special case
190  if p == 'Omega_cdm':
191  params['Omega_c'] = sample_points[p][i]
192  else:
193  params[p] = sample_points[p][i]
194 
195  # Instantiate CCL Cosmology object with this set of parameters
196  params['transfer_function'] = 'boltzmann'
197  cosmo = ccl.Cosmology(**params)
198 
199  # Loop over redshifts to get linear and nonlinear matter power spectra
200  errored = []
201  for j, z in enumerate(zvals):
202  try:
203  a = 1. / (1. + z)
204  pk_lin = ccl.linear_matter_power(cosmo, k_class, a)
205  if nonlin:
206  pk_nl = ccl.nonlin_matter_power(cosmo, k_class_nl, a)
207  except KeyboardInterrupt:
208  raise
209  except:
210  print "--- Error running CLASS"
211  print "--- Parameters:", params
212  errored.append(i)
213  continue
214 
215  # Save datafiles
216  if nonlin:
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)))
219  else:
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)))
222 
223  # Print runs that errored
224  if len(errored) > 0: print "ERRORED:"
225  for err in errored:
226  print err
227 
228 
auto range(T const &first, T const &last) -> Generator< T >
Definition: catch.hpp:3156
def param_space.generate_class_ini (   sample_points,
  root,
  nonlinear = False,
  mnu = False,
  redshifts = np.arange(0., 3., 0.5) 
)
Generate CLASS .ini files for a set of parameters.

Parameters
----------
sample_points : dict
    Dictionary containing parameter names (keys) and array of parameter
    values for all sample points (values).

root : str
    Path of directory in which .ini files should be stored.

nonlinear : bool, optional
    Whether CLASS should return the linear or nonlinear (halofit) power
    spectrum. Default: False.

mnu : bool, optional
    Whether to include massive neutrinos.

redshifts : array_like, optional
    Array of redshift values at which P(k) should be calculated. Default:
    Five bins from 0.0 to 2.5 in increments of 0.5.

Definition at line 230 of file param_space.py.

References Catch::Generators.range().

Referenced by generate_ccl_pspec().

230  redshifts=np.arange(0., 3., 0.5)):
231  """
232  Generate CLASS .ini files for a set of parameters.
233 
234  Parameters
235  ----------
236  sample_points : dict
237  Dictionary containing parameter names (keys) and array of parameter
238  values for all sample points (values).
239 
240  root : str
241  Path of directory in which .ini files should be stored.
242 
243  nonlinear : bool, optional
244  Whether CLASS should return the linear or nonlinear (halofit) power
245  spectrum. Default: False.
246 
247  mnu : bool, optional
248  Whether to include massive neutrinos.
249 
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.
253  """
254  # Get user-defined parameter names
255  pnames = sample_points.keys()
256  Nsamp = sample_points[pnames[0]].size
257 
258  # Loop over sample points
259  for i in range(Nsamp):
260  if i % 10 == 0: print(" Writing CLASS .ini file %d / %d" % (i, Nsamp))
261 
262  # Open file for writing
263  f = open("%s_%05d.ini" % (root, i), 'w')
264 
265  # Write output location into file (will be same as .ini file location)
266  f.write('root = %s_%05d\n' % (root, i))
267 
268  # Write user-defined cosmo parameters into file
269  for p in pnames:
270  # Handle commonly-used params that CLASS uses different names for
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])
275  else:
276  # Generic user-defined parameters
277  f.write("%s = %e\n" % (p, sample_points[p][i]))
278 
279  # Write output redshifts to file
280  f.write("z_pk = %s\n" % (",".join(["%3.3f" % z for z in redshifts])))
281 
282  # Write nonlinear switch to file, if specified
283  if nonlinear: f.write("non linear = halofit\n")
284 
285  # Write curvature parameter
286  if 'Omega_k' not in pnames: f.write('Omega_k = 0.0\n')
287 
288  # Write neutrino parameters
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")
294 
295  # Add various default CLASS settings to file
296  # NB: Need to set P_k_max_h/Mpc to a large value if doing halofit
297  defaults = "T_cmb = 2.725\n\
298 #Omega_dcdmdr = 0.0\n\
299 #Gamma_dcdm = 0.0 \n\
300 #Omega_fld = 0\n\
301 #Omega_scf = 0\n\
302 #a_today = 1.\n\
303 #YHe = BBN\n\
304 #recombination = RECFAST\n\
305 #reio_parametrization = reio_camb\n\
306 #z_reio = 11.357\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\
319 #decay = 0.\n\
320 output = mPk\n\
321 modes = s\n\
322 lensing = no\n\
323 #ic = ad\n\
324 #P_k_ini type = analytic_Pk\n\
325 #k_pivot = 0.05\n\
326 #alpha_s = 0.\n\
327 P_k_max_h/Mpc = 100.\n\
328 #l_max_scalars = 8000\n\
329 #l_max_lss = 1000\n\
330 headers = yes\n\
331 format = class\n\
332 write background = no\n\
333 write thermodynamics = no\n\
334 write primordial = no\n\
335 write parameters = yeap\n\
336 input_verbose = 1\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"
346  f.write(defaults)
347  f.close()
348 
349 
auto range(T const &first, T const &last) -> Generator< T >
Definition: catch.hpp:3156
def param_space.generate_latin_hypercube (   samples,
  param_dict,
  class_root,
  seed = 10 
)
Generate a Latin hypercube for a given set of parameters.

Parameters
----------
samples : int
    Number of samples points to draw from the hypercube.

param_dict : dict
    Dictionary containing parameter names (keys) and tuple with min/max.
    values (values).

class_root : str
    Path to directory containing 'class' executable.

seed : int, optional
    Random seed to use when sampling from hypercube.

Returns
-------
sample_points : dict
    Dictionary containing parameter names (keys) and array of parameter
    values for all sample points (values).

Definition at line 81 of file param_space.py.

References generate_ccl_pspec(), and Catch::Generators.range().

81 def generate_latin_hypercube(samples, param_dict, class_root, seed=10):
82  """
83  Generate a Latin hypercube for a given set of parameters.
84 
85  Parameters
86  ----------
87  samples : int
88  Number of samples points to draw from the hypercube.
89 
90  param_dict : dict
91  Dictionary containing parameter names (keys) and tuple with min/max.
92  values (values).
93 
94  class_root : str
95  Path to directory containing 'class' executable.
96 
97  seed : int, optional
98  Random seed to use when sampling from hypercube.
99 
100  Returns
101  -------
102  sample_points : dict
103  Dictionary containing parameter names (keys) and array of parameter
104  values for all sample points (values).
105  """
106  # Set random seed
107  random.seed(seed)
108 
109  # Create dictionary to hold sampled parameter values
110  sample_points = {}
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()]
115 
116  # List of indices for each dimension
117  l = [range(samples) for j in range(Ndim)]
118 
119  # Generate samples until there are no indices left to choose
120  for i in range(samples):
121 
122  # Randomly choose index and then remove the number that was chosen
123  # (Latin hypercubes require at most one item per row and column)
124  for j, p in enumerate(pnames):
125  pmin, pmax = param_dict[p]
126  idx = random.choice(l[j])
127 
128  # Get value at this sample point (add 0.5 to idx get bin centroid)
129  sample_points[p][i] = pmin + (pmax - pmin) \
130  * (idx + 0.5) / float(samples)
131  l[j].remove(idx) # Remove choice from list (sampling w/o replacement)
132 
133  return sample_points
134 
135 
def generate_latin_hypercube(samples, param_dict, class_root, seed=10)
Definition: param_space.py:81
auto range(T const &first, T const &last) -> Generator< T >
Definition: catch.hpp:3156
def param_space.load_hypercube (   fname)
Load a Latin hypercube from disk. Parameter columns will be ordered
alphabetically by name.

Parameters
----------
fname : str
    Filename to read sample points from.

Returns
-------
sample_points : dict
    Dictionary containing parameter names (keys) and array of parameter
    values for all sample points (values).

Definition at line 50 of file param_space.py.

References Catch::Generators.range().

50 def load_hypercube(fname):
51  """
52  Load a Latin hypercube from disk. Parameter columns will be ordered
53  alphabetically by name.
54 
55  Parameters
56  ----------
57  fname : str
58  Filename to read sample points from.
59 
60  Returns
61  -------
62  sample_points : dict
63  Dictionary containing parameter names (keys) and array of parameter
64  values for all sample points (values).
65  """
66  # Get header
67  f = open(fname, 'r')
68  hdr = f.readline()[2:-1].split(" ")
69  f.close()
70 
71  # Load data
72  dat = np.loadtxt(fname).T
73 
74  # Build dict
75  sample_points = {}
76  for i in range(len(hdr)):
77  sample_points[hdr[i]] = dat[i]
78  return sample_points
79 
80 
def load_hypercube(fname)
Definition: param_space.py:50
auto range(T const &first, T const &last) -> Generator< T >
Definition: catch.hpp:3156
def param_space.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 
)
Calculate summary stats for the deviation between CCL and reference power
spectra as a function of scale and redshift, for a large number of sample
points over the cosmological parameter space.

Parameters
----------
sample_points : dict
    Dictionary containing parameter names (keys) and array of parameter
    values for all sample points (values).

ccl_data_root : str
    Root of filenames of CCL power spectrum files

class_data_root : str
    Root of filenames of CLASS power spectrum files. If the string '_nl_'
    is found in class_data_root, this will assume that nonlinear power
    spectra should be loaded.

Definition at line 398 of file param_space.py.

References ccl_summary_stats(), and Catch::Generators.range().

Referenced by run_class().

398  cache_name=None):
399  """
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.
403 
404  Parameters
405  ----------
406  sample_points : dict
407  Dictionary containing parameter names (keys) and array of parameter
408  values for all sample points (values).
409 
410  ccl_data_root : str
411  Root of filenames of CCL power spectrum files
412 
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.
417 
418  """
419  # Get dimensions of stats array that will be constructed
420  N_samp = sample_points[sample_points.keys()[0]].size
421  N_thres = len(thresholds)
422  N_z = len(z_vals)
423  N_kbins = len(scale_ranges)
424 
425  # Check if data were cached
426  if cache_name is not None:
427  try:
428  stats = np.load("%s.npy" % cache_name)
429  print(" Loaded '%s' from cache." % cache_name)
430 
431  frac_dev = np.load("%s.frac_dev.npy" % cache_name)
432  print(" Loaded '%s.frac_dev' from cache." % cache_name)
433 
434  k_arr = np.load("%s.k_arr.npy" % cache_name)
435  print(" Loaded '%s.k_arr' from cache." % cache_name)
436 
437  assert stats.shape == (N_samp, N_thres, N_z, N_kbins)
438  return stats, frac_dev, k_arr
439  except:
440  print(" Cache '%s' not found. Recomputing." % cache_name)
441  pass
442 
443  # Create array to hold summary statistics, with shape:
444  # (N_samp, N_thres, N_z, N_kbins)
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)]
448 
449  # Loop over sample points in parameter space and calculate summary stats
450  for i in range(N_samp):
451  print " Loading power spectra for parameter set %05d" % i
452 
453  # Get Hubble parameter, h, for rescaling CLASS P(k) to Mpc units
454  h = sample_points['h'][i]
455 
456  # Try to get deviation
457  try:
458  # Loop over redshift values
459  for j in range(N_z):
460 
461  # Construct filenames for CCL and CLASS P(k) data files
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)
465  else:
466  fname_class = "%s_%05dz%d_pk.dat" % (class_data_root, i, j+1)
467 
468  # Load CCL power spectrum data
469  pk_ccl_dat = np.loadtxt(fname_ccl)
470  ccl_k = pk_ccl_dat[:,0]
471  ccl_pk = pk_ccl_dat[:,1]
472 
473  # Load CLASS power spectrum data
474  pk_class_dat = np.loadtxt(fname_class) #, skiprows=1)
475  class_k = pk_class_dat[:,0]
476  class_pk = pk_class_dat[:,1] / h**3.
477 
478  # Sanity checks
479  print ccl_pk.size, class_pk.size
480  assert ccl_pk.size == class_pk.size
481 
482  # Calculate fractional deviation
483  frac_dev[i][j] = ccl_pk/class_pk - 1.
484  k_arr[i][j] = ccl_k
485 
486  # Calculate summary stats in each k bin
487  for m in range(N_kbins):
488  kmin, kmax = scale_ranges[m]
489  idxs = np.logical_and(ccl_k >= kmin, ccl_k < kmax)
490 
491  # Calculate deviation statistic, Delta, for a range of
492  # threshold values (only values above the threshold are counted)
493  for n, thres in enumerate(thresholds):
494  # Calculate deviation statistic
495  dev = np.log10(
496  np.abs(ccl_pk[idxs]/class_pk[idxs] - 1.) / thres)
497  dev[np.where(dev < 0.)] = 0.
498 
499  # Store result in stats array (N_samp, N_thres, N_z, N_kbins)
500  stats[i, n, j, m] = np.sum(dev)
501  except:
502  raise
503  # If there were any failures, set stats to 'nan' for this sample point
504  print(" Failed to compute stats for sample %05d." % i)
505  stats[i, :, :, :] = np.nan
506 
507  # Save to cache file
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
513 
514 
auto range(T const &first, T const &last) -> Generator< T >
Definition: catch.hpp:3156
def param_space.run_class (   fname_pattern,
  class_root,
  precision = False 
)
Run CLASS on a set of .ini files.

Parameters
----------
fname_pattern : str
    Pattern (glob format) for matching the .ini files to be run by CLASS.

class_root : str
    Directory in which the 'class' executable is stored.

precision : bool, optional
    Whether to run CLASS in high-precision mode (using the pk_ref.pre
    precision file).

Definition at line 350 of file param_space.py.

References load_summary_stats().

350 def run_class(fname_pattern, class_root, precision=False):
351  """
352  Run CLASS on a set of .ini files.
353 
354  Parameters
355  ----------
356  fname_pattern : str
357  Pattern (glob format) for matching the .ini files to be run by CLASS.
358 
359  class_root : str
360  Directory in which the 'class' executable is stored.
361 
362  precision : bool, optional
363  Whether to run CLASS in high-precision mode (using the pk_ref.pre
364  precision file).
365 
366  """
367  # Get CLASS .ini files that will be run
368  fnames = glob.glob(fname_pattern)
369  fnames.sort()
370 
371  # Loop over all .ini files
372  failed = []
373  for i, filename in enumerate(fnames):
374  print("CLASS run %d / %d (%s)" % (i+1, len(fnames), filename))
375 
376  # Run CLASS and save the output
377  cmd = ['%s/class' % class_root, filename]
378  if precision: cmd += ['%s/pk_ref.pre' % class_root,]
379  try:
380  stdout = subprocess.check_output(cmd, stderr=subprocess.STDOUT)
381  basefile = os.path.splitext('%s' % filename)[0]
382  f = open('%s.txt' % basefile, 'w')
383  f.write(stdout)
384  f.close()
385  except KeyboardInterrupt:
386  raise
387  except:
388  raise
389  # CLASS run failed
390  print(" CLASS run failed. Skipping.")
391  failed.append(i)
392 
393 
def run_class(fname_pattern, class_root, precision=False)
Definition: param_space.py:350
def param_space.save_hypercube (   fname,
  sample_points 
)
Save a Latin hypercube to disk as a text file. Parameter columns will be
ordered alphabetically by name.

Parameters
----------
fname : str
    Filename for output file.
sample_points : dict
    Dictionary containing parameter names (keys) and array of parameter
    values for all sample points (values).

Definition at line 26 of file param_space.py.

26 def save_hypercube(fname, sample_points):
27  """
28  Save a Latin hypercube to disk as a text file. Parameter columns will be
29  ordered alphabetically by name.
30 
31  Parameters
32  ----------
33  fname : str
34  Filename for output file.
35  sample_points : dict
36  Dictionary containing parameter names (keys) and array of parameter
37  values for all sample points (values).
38  """
39  # Get parameter names and build header
40  pnames = sample_points.keys()
41  pnames.sort()
42  hdr = " ".join(pnames)
43 
44  # Build array
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)
48 
49 
def save_hypercube(fname, sample_points)
Definition: param_space.py:26