本文整理汇总了Python中classy.Class.set方法的典型用法代码示例。如果您正苦于以下问题:Python Class.set方法的具体用法?Python Class.set怎么用?Python Class.set使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类classy.Class
的用法示例。
在下文中一共展示了Class.set方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_class_setup
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
def test_class_setup():
cosmology = astropy.cosmology.Planck13
assert cosmology.Om0 == cosmology.Odm0 + cosmology.Ob0
assert 1 == (cosmology.Om0 + cosmology.Ode0 + cosmology.Ok0 +
cosmology.Ogamma0 + cosmology.Onu0)
class_parameters = get_class_parameters(cosmology)
try:
from classy import Class
cosmo = Class()
cosmo.set(class_parameters)
cosmo.compute()
assert cosmo.h() == cosmology.h
assert cosmo.T_cmb() == cosmology.Tcmb0.value
assert cosmo.Omega_b() == cosmology.Ob0
# Calculate Omega(CDM)_0 two ways:
assert abs((cosmo.Omega_m() - cosmo.Omega_b()) -
(cosmology.Odm0 - cosmology.Onu0)) < 1e-8
assert abs(cosmo.Omega_m() - (cosmology.Om0 - cosmology.Onu0)) < 1e-8
# CLASS calculates Omega_Lambda itself so this is a non-trivial test.
calculated_Ode0 = cosmo.get_current_derived_parameters(
['Omega_Lambda'])['Omega_Lambda']
assert abs(calculated_Ode0 - (cosmology.Ode0 + cosmology.Onu0)) < 1e-5
cosmo.struct_cleanup()
cosmo.empty()
except ImportError:
pass
示例2: ClassCoreModule
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
class ClassCoreModule(object):
def __init__(self, mapping=DEFAULT_PARAM_MAPPING, constants=CLASS_DEFAULT_PARAMS):
"""
Core Module for the delegation of the computation of the cmb power
spectrum to the Class wrapper classy.
The defaults are for the 6 LambdaCDM cosmological parameters.
:param mapping: (optional) dict mapping name of the parameter to the index
:param constants: (optional) dict with constants overwriting CLASS defaults
"""
self.mapping = mapping
if constants is None:
constants = {}
self.constants = constants
def __call__(self, ctx):
p1 = ctx.getParams()
params = self.constants.copy()
for k,v in self.mapping.items():
params[k] = p1[v]
self.cosmo.set(params)
self.cosmo.compute()
if self.constants['lensing'] == 'yes':
cls = self.cosmo.lensed_cl()
else:
cls = self.cosmo.raw_cl()
Tcmb = self.cosmo.T_cmb()*1e6
frac = Tcmb**2 * cls['ell'][2:] * (cls['ell'][2:] + 1) / 2. / pi
ctx.add(CL_TT_KEY, frac*cls['tt'][2:])
ctx.add(CL_TE_KEY, frac*cls['te'][2:])
ctx.add(CL_EE_KEY, frac*cls['ee'][2:])
ctx.add(CL_BB_KEY, frac*cls['bb'][2:])
self.cosmo.struct_cleanup()
def setup(self):
"""
Create an instance of Class and attach it to self.
"""
self.cosmo = Class()
self.cosmo.set(self.constants)
self.cosmo.compute()
self.cosmo.struct_cleanup()
示例3: m_Pk
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
def m_Pk(k=np.logspace(-3, 0., 100), z=0.53, nl_model='trg'):
print k
cosmo = Class()
CLASS_INPUT = {}
CLASS_INPUT['Mnu'] = ([{'N_eff': 0.0, 'N_ncdm': 1, 'm_ncdm': 0.06, 'deg_ncdm': 3.0}], 'normal')
CLASS_INPUT['Output_spectra'] = ([{'output': 'mPk', 'P_k_max_1/Mpc': 1, 'z_pk': z}], 'power')
CLASS_INPUT['Nonlinear'] = ([{'non linear': nl_model}], 'power')
verbose = {}
# 'input_verbose': 1,
# 'background_verbose': 1,
# 'thermodynamics_verbose': 1,
# 'perturbations_verbose': 1,
# 'transfer_verbose': 1,
# 'primordial_verbose': 1,
# 'spectra_verbose': 1,
# 'nonlinear_verbose': 1,
# 'lensing_verbose': 1,
# 'output_verbose': 1
# }
cosmo.struct_cleanup()
cosmo.empty()
INPUTPOWER = []
INPUTNORMAL = [{}]
for key, value in CLASS_INPUT.iteritems():
models, state = value
if state == 'power':
INPUTPOWER.append([{}]+models)
else:
INPUTNORMAL.extend(models)
PRODPOWER = list(itertools.product(*INPUTPOWER))
DICTARRAY = []
for normelem in INPUTNORMAL:
for powelem in PRODPOWER: # itertools.product(*modpower):
temp_dict = normelem.copy()
for elem in powelem:
temp_dict.update(elem)
DICTARRAY.append(temp_dict)
scenario = {}
for dic in DICTARRAY:
scenario.update(dic)
setting = cosmo.set(dict(verbose.items()+scenario.items()))
cosmo.compute()
pk_out = []
for k_i in k:
pk_out.append(cosmo.pk(k_i,z))
return pk_out
示例4: loglkl
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
def loglkl(self, params):
cosmo = Class()
cosmo.set(params)
cosmo.compute()
chi2 = 0.
# for each point, compute angular distance da, radial distance dr,
# volume distance dv, sound horizon at baryon drag rs_d,
# theoretical prediction and chi2 contribution
for i in range(self.num_points):
da = cosmo.angular_distance(self.z[i])
dr = self.z[i] / cosmo.Hubble(self.z[i])
dv = pow(da * da * (1 + self.z[i]) * (1 + self.z[i]) * dr, 1. / 3.)
rs = cosmo.rs_drag()
if self.type[i] == 3:
theo = dv / rs
elif self.type[i] == 4:
theo = dv
elif self.type[i] == 5:
theo = da / rs
elif self.type[i] == 6:
theo = 1. / cosmo.Hubble(self.z[i]) / rs
elif self.type[i] == 7:
theo = rs / dv
chi2 += ((theo - self.data[i]) / self.error[i]) ** 2
# return ln(L)
# lkl = - 0.5 * chi2
# return -2ln(L)
lkl = chi2
return lkl
示例5: ComputeTransferData
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
def ComputeTransferData(settings, redshift):
database_key = settings.copy()
database_key.update({'redshift': tuple(redshift)})
database = Database.Database(config.DATABASE_DIR)
if database_key in database:
return database[database_key], redshift
else:
cosmo = Class()
cosmo.set(settings)
cosmo.compute()
outputData = [cosmo.get_transfer(z) for z in redshift]
# Calculate d_g/4+psi
for transfer_function_dict in outputData:
transfer_function_dict["d_g/4 + psi"] = transfer_function_dict["d_g"]/4 + transfer_function_dict["psi"]
# Now filter the relevant fields
fields = TRANSFER_QUANTITIES + ["k (h/Mpc)"]
outputData = [{field: outputData[i][field] for field in fields} for i in range(len(redshift))]
database[database_key] = outputData
return outputData, redshift
示例6: calculate_power
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
def calculate_power(cosmology, k_min, k_max, z=0, num_k=500, scaled_by_h=True,
n_s=0.9619, logA=3.0980):
"""
Calculate the power spectrum P(k,z) over the range k_min <= k <= k_max.
"""
try:
from classy import Class
cosmo = Class()
except ImportError:
raise RuntimeError('power.calculate_power requires classy.')
class_parameters = get_class_parameters(cosmology)
class_parameters['output'] = 'mPk'
if scaled_by_h:
class_parameters['P_k_max_h/Mpc'] = k_max
else:
class_parameters['P_k_max_1/Mpc'] = k_max
class_parameters['n_s'] = n_s
class_parameters['ln10^{10}A_s'] = logA
cosmo.set(class_parameters)
cosmo.compute()
if scaled_by_h:
k_scale = cosmo.h()
Pk_scale = cosmo.h()**3
else:
k_scale = 1.
Pk_scale = 1.
result = np.empty((num_k,), dtype=[('k', float), ('Pk', float)])
result['k'][:] = np.logspace(np.log10(k_min), np.log10(k_max), num_k)
for i, k in enumerate(result['k']):
result['Pk'][i] = cosmo.pk(k * k_scale, z) * Pk_scale
cosmo.struct_cleanup()
cosmo.empty()
return result
示例7: classy
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
class classy(SlikPlugin):
"""
Plugin for CLASS.
Credit: Brent Follin, Teresa Hamill, Andy Scacco
"""
def __init__(self):
super(classy,self).__init__()
try:
from classy import Class
except ImportError:
raise Exception("Failed to import CLASS python wrapper 'Classy'.")
self.model = Class()
def __call__(self,
**kwargs):
self.model.set(**kwargs)
self.model.compute()
ell = arange(l_max_scalar+1)
self.cmb_result = {'cl_%s'%x:(self.model.lensed_cl(l_max_scalar)[x.lower()])*Tcmb**2*1e12*ell*(ell+1)/2/pi
for x in ['TT','TE','EE','BB','PP','TP']}
self.model.struct_cleanup()
self.model.empty()
return self.cmb_result
def get_bao_observables(self, z):
return {'H':self.model.Hubble(z),
'D_A':self.model.angular_distance(z),
'c':1.0,
'r_d':(self.model.get_current_derived_parameters(['rs_rec']))['rs_rec']}
示例8: Class
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
#'k_step_sub':'0.01',
'k_per_decade_for_pk':k_per_decade,
'k_per_decade_for_bao':k_per_decade,
'k_min_tau0':k_min_tau0, # this value controls the minimum k value in the figure
'perturb_sampling_stepsize':'0.05',
'P_k_max_1/Mpc':P_k_max_inv_Mpc,
'compute damping scale':'yes', # needed to output and plot Silk damping scale
'gauge':'newtonian'}
###############
#
# call CLASS
#
###############
M = Class()
M.set(common_settings)
M.compute()
#
# define conformal time sampling array
#
times = M.get_current_derived_parameters(['tau_rec','conformal_age'])
tau_rec=times['tau_rec']
tau_0 = times['conformal_age']
tau1 = np.logspace(math.log10(tau_ini),math.log10(tau_rec),tau_num_early)
tau2 = np.logspace(math.log10(tau_rec),math.log10(tau_0),tau_num_late)[1:]
tau2[-1] *= 0.999 # this tiny shift avoids interpolation errors
tau = np.concatenate((tau1,tau2))
tau_num = len(tau)
#
# use table of background and thermodynamics quantitites to define some functions
# returning some characteristic scales
示例9: Class
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
from classy import Class
# In[ ]:
font = {'size' : 20, 'family':'STIXGeneral'}
axislabelfontsize='large'
matplotlib.rc('font', **font)
matplotlib.mathtext.rcParams['legend.fontsize']='medium'
# In[ ]:
#Lambda CDM
LCDM = Class()
LCDM.set({'Omega_cdm':0.25,'Omega_b':0.05})
LCDM.compute()
# In[ ]:
#Einstein-de Sitter
CDM = Class()
CDM.set({'Omega_cdm':0.95,'Omega_b':0.05})
CDM.compute()
# Just to cross-check that Omega_Lambda is negligible
# (but not exactly zero because we neglected radiation)
derived = CDM.get_current_derived_parameters(['Omega0_lambda'])
print derived
print "Omega_Lambda =",derived['Omega0_lambda']
示例10: Helium
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
'h':0.67556,
'omega_b':0.022032,
'omega_cdm':0.12038,
'A_s':2.215e-9,
'n_s':0.9619,
'tau_reio':0.0925,
# Take fixed value for primordial Helium (instead of automatic BBN adjustment)
'YHe':0.246,
# other output and precision parameters
'l_max_scalars':5000}
###############
#
# call CLASS
#
M = Class()
M.set(common_settings)
M.compute()
cl_tot = M.raw_cl(3000)
cl_lensed = M.lensed_cl(3000)
M.struct_cleanup() # clean output
M.empty() # clean input
#
M.set(common_settings) # new input
M.set({'temperature contributions':'tsw'})
M.compute()
cl_tsw = M.raw_cl(3000)
M.struct_cleanup()
M.empty()
#
M.set(common_settings)
M.set({'temperature contributions':'eisw'})
示例11: Class
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
# coding: utf-8
# In[ ]:
# import classy module
from classy import Class
# In[ ]:
# create instance of the class "Class"
LambdaCDM = Class()
# pass input parameters
LambdaCDM.set({'omega_b':0.022032,'omega_cdm':0.12038,'h':0.67556,'A_s':2.215e-9,'n_s':0.9619,'tau_reio':0.0925})
LambdaCDM.set({'output':'tCl,pCl,lCl,mPk','lensing':'yes','P_k_max_1/Mpc':3.0})
# run class
LambdaCDM.compute()
# In[ ]:
# get all C_l output
cls = LambdaCDM.lensed_cl(2500)
# To check the format of cls
cls.viewkeys()
# In[ ]:
ll = cls['ell'][2:]
示例12: N
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
if False: # In case you want to plot the N(z)s
fig, axs = plt.subplots(1, 2, figsize=(14, 5))
finer_z_grid = np.linspace(0, 2, num=2000)
for i, nz in enumerate(redshiftdistributions):
ic = str(i+1)
nz_grid = nz.eval(z_grid)
finer_nz_grid = nz.eval(finer_z_grid)
axs[i].plot(finer_z_grid, finer_nz_grid, label='Gaussian Mixture')
axs[i].plot(z_grid, nz_grid, label='Histogram-ized', ls='steps')
plt.show()
# Now run Class!
cosmo = Class()
# Scenario 1
cosmo.set(dict(mainparams.items()+scenario1.items()))
cosmo.compute()
cl1 = cosmo.density_cl(mainparams['l_max_lss'])
cosmo.struct_cleanup()
cosmo.empty()
# Scenario 2
cosmo.set(dict(mainparams.items()+scenario2.items()))
cosmo.compute()
cl2 = cosmo.density_cl(mainparams['l_max_lss'])
cosmo.struct_cleanup()
cosmo.empty()
# The Cls should be very close if the histogram is binned finely
nbins = len(redshiftdistributions)
print 'Comparing accuracy of N(z) representation: multigaussian vs histograms'
for i in range(nbins*(nbins+1)/2):
示例13: get_masses
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
'ncdm_fluid_approximation':3,
# You may uncomment this line to get more info on the ncdm sector from Class:
'background_verbose':1
}
# array of k values in 1/Mpc
kvec = np.logspace(-4,np.log10(3),100)
# array for storing legend
legarray = []
# loop over total mass values
for sum_masses in [0.1, 0.115, 0.13]:
# normal hierarchy
[m1, m2, m3] = get_masses(2.45e-3,7.50e-5, sum_masses, 'NH')
NH = Class()
NH.set(commonsettings)
NH.set({'m_ncdm':str(m1)+','+str(m2)+','+str(m3)})
NH.compute()
# inverted hierarchy
[m1, m2, m3] = get_masses(2.45e-3,7.50e-5, sum_masses, 'IH')
IH = Class()
IH.set(commonsettings)
IH.set({'m_ncdm':str(m1)+','+str(m2)+','+str(m3)})
IH.compute()
pkNH = []
pkIH = []
for k in kvec:
pkNH.append(NH.pk(k,0.))
pkIH.append(IH.pk(k,0.))
NH.struct_cleanup()
IH.struct_cleanup()
示例14: classy
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
class classy(SlikPlugin):
"""
Plugin for CLASS.
Credit: Brent Follin, Teresa Hamill, Andy Scacco
"""
#{cosmoslik name : class name} - This needs to be done even for variables with the same name (because of for loop in self.model.set)!
name_mapping = {'As':'A_s',
'ns':'n_s',
'r':'r',
'k_c':'k_c',
'alpha_exp':'alpha_exp',
'nt':'n_t',
'ombh2':'omega_b',
'omch2':'omega_cdm',
'omnuh2':'omega_ncdm',
'tau':'tau_reio',
'H0':'H0',
'massive_neutrinos':'N_ncdm',
'massless_neutrinos':'N_ur',
'Yp':'YHe',
'pivot_scalar':'k_pivot',
#'Tcmb':'T_cmb',
#'P_k_max_hinvMpc':'P_k_max_h/Mpc'
#'w':'w0_fld',
#'nrun':'alpha_s',
#'omk':'Omega_k',
#'l_max_scalar':'l_max_scalars',
#'l_max_tensor':'l_max_tensors'
}
def __init__(self):
super(classy,self).__init__()
try:
from classy import Class
except ImportError:
raise Exception("Failed to import CLASS python wrapper 'Classy'.")
self.model = Class()
def __call__(self,
ombh2,
omch2,
H0,
As,
ns,
k_c,
alpha_exp,
tau,
#omnuh2=0, #0.006 #None means that Class will take the default for this, maybe?
w=None,
r=None,
nrun=None,
omk=0,
Yp=None,
Tcmb=2.7255,
#massive_neutrinos=0,
massless_neutrinos=3.046,
l_max_scalar=3000,
l_max_tensor=3000,
pivot_scalar=0.05,
outputs=[],
**kwargs):
self.model.set(output='tCl, lCl, pCl',
lensing='yes',
l_max_scalars=l_max_scalar,
**{self.name_mapping[k]:v for k,v in locals().items()
if k in self.name_mapping and v is not None})
self.model.compute()
ell = arange(l_max_scalar+1)
self.cmb_result = {'cl_%s'%x:(self.model.lensed_cl(l_max_scalar)[x.lower()])*Tcmb**2*1e12*ell*(ell+1)/2/pi
for x in ['TT','TE','EE','BB','PP','TP']}
self.model.struct_cleanup()
self.model.empty()
return self.cmb_result
def get_bao_observables(self, z):
return {'H':self.model.Hubble(z),
'D_A':self.model.angular_distance(z),
'c':1.0,
'r_d':(self.model.get_current_derived_parameters(['rs_rec']))['rs_rec']}
示例15: TestClass
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import set [as 别名]
class TestClass(unittest.TestCase):
"""
Testing Class and its wrapper classy on different cosmologies
To run it, do
~] nosetest test_class.py
It will run many times Class, on different cosmological scenarios, and
everytime testing for different output possibilities (none asked, only mPk,
etc..)
"""
def setUp(self):
"""
set up data used in the tests.
setUp is called before each test function execution.
"""
self.cosmo = Class()
self.verbose = {
"input_verbose": 1,
"background_verbose": 1,
"thermodynamics_verbose": 1,
"perturbations_verbose": 1,
"transfer_verbose": 1,
"primordial_verbose": 1,
"spectra_verbose": 1,
"nonlinear_verbose": 1,
"lensing_verbose": 1,
"output_verbose": 1,
}
self.scenario = {"lensing": "yes"}
def tearDown(self):
self.cosmo.struct_cleanup()
self.cosmo.empty()
del self.scenario
@parameterized.expand(
itertools.product(
("LCDM", "Mnu", "Positive_Omega_k", "Negative_Omega_k", "Isocurvature_modes"),
(
{"output": ""},
{"output": "mPk"},
{"output": "tCl"},
{"output": "tCl pCl lCl"},
{"output": "mPk tCl lCl", "P_k_max_h/Mpc": 10},
{"output": "nCl sCl"},
{"output": "tCl pCl lCl nCl sCl"},
),
({"gauge": "newtonian"}, {"gauge": "sync"}),
({}, {"non linear": "halofit"}),
)
)
def test_wrapper_implementation(self, name, scenario, gauge, nonlinear):
"""Create a few instances based on different cosmologies"""
if name == "Mnu":
self.scenario.update({"N_ncdm": 1, "m_ncdm": 0.06})
elif name == "Positive_Omega_k":
self.scenario.update({"Omega_k": 0.01})
elif name == "Negative_Omega_k":
self.scenario.update({"Omega_k": -0.01})
elif name == "Isocurvature_modes":
self.scenario.update({"ic": "ad,nid,cdi", "c_ad_cdi": -0.5})
self.scenario.update(scenario)
if scenario != {}:
self.scenario.update(gauge)
self.scenario.update(nonlinear)
sys.stderr.write("\n\n---------------------------------\n")
sys.stderr.write("| Test case %s |\n" % name)
sys.stderr.write("---------------------------------\n")
for key, value in self.scenario.iteritems():
sys.stderr.write("%s = %s\n" % (key, value))
sys.stderr.write("\n")
setting = self.cosmo.set(dict(self.verbose.items() + self.scenario.items()))
self.assertTrue(setting, "Class failed to initialize with input dict")
cl_list = ["tCl", "lCl", "pCl", "nCl", "sCl"]
# Depending on the cases, the compute should fail or not
should_fail = True
output = self.scenario["output"].split()
for elem in output:
if elem in ["tCl", "pCl"]:
for elem2 in output:
if elem2 == "lCl":
should_fail = False
break
if not should_fail:
self.cosmo.compute()
else:
self.assertRaises(CosmoSevereError, self.cosmo.compute)
return
self.assertTrue(self.cosmo.state, "Class failed to go through all __init__ methods")
#.........这里部分代码省略.........