本文整理汇总了Python中classy.Class.empty方法的典型用法代码示例。如果您正苦于以下问题:Python Class.empty方法的具体用法?Python Class.empty怎么用?Python Class.empty使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类classy.Class
的用法示例。
在下文中一共展示了Class.empty方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_class_setup
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [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: m_Pk
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [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
示例3: classy
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [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']}
示例4: calculate_power
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [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
示例5: classy
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [as 别名]
#.........这里部分代码省略.........
'omnuh2':'omega_ncdm',
'tau':'tau_reio',
'H0':'H0',
'massive_neutrinos':'N_ncdm',
'massless_neutrinos':'N_ur',
'Yp':'YHe',
'pivot_scalar':'k_pivot',
'omk':'Omega_k',
'l_max_scalar':'l_max_scalars',
'l_max_tensor':'l_max_tensors',
'Tcmb':'T_cmb'
}
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):
# d={}
# for k, v in kwargs.iteritems():
# if k in self.name_mapping and v is not None:
# d[self.name_mapping[k]]=v
# else:
# d[k]=v
#def __call__(self,
#ombh2,
#omch2,
#H0,
#As,
#ns,
#custom1,
#custom2,
#custom3,
#tau,
#w=None,
#r=None,
#nrun=None,
#omk=0,
#Yp=None,
#Tcmb=2.7255,
#massless_neutrinos=3.046,
#l_max_scalar=3000,
#l_max_tensor=3000,
#pivot_scalar=0.05,
#outputs=[],
#**kwargs):
#print kwargs
def __call__(self,**kwargs):
#print kwargs
#print kwargs['classparamlist']
#print kwargs['d']
d={}
for k,v in kwargs.iteritems():
if k in kwargs['classparamlist']:
if k in self.name_mapping and v is not None:
d[self.name_mapping[k]]=v
else:
d[k]=v
#d['P_k_ini type']='external_Pk'
#d['modes'] = 's,t'
self.model.set(**d)
l_max = d['l_max_scalars']
Tcmb = d['T_cmb']
#print l_max
#print d
self.model.compute()
ell = arange(l_max+1)
self.cmb_result = {'cl_%s'%x:(self.model.lensed_cl(l_max)[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']}
示例6: classy
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [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',
'phi0':'custom1',
'm6':'custom2',
'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',
}
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,
phi0,
m6,
tau,
w=None,
r=None,
nrun=None,
omk=0,
Yp=None,
Tcmb=2.7255,
massless_neutrinos=3.046,
l_max_scalar=3000,
l_max_tensor=3000,
pivot_scalar=0.05,
outputs=[],
**kwargs):
d={self.name_mapping[k]:v for k,v in locals().items()
if k in self.name_mapping and v is not None}
d['P_k_ini type']='external_Pk'
d['modes'] = 's,t'
self.model.set(output='tCl, lCl, pCl',
lensing='yes',
l_max_scalars=l_max_scalar,
command = '../LSODAtesnors/pk',
**d)
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']}
示例7: TestClass
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [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")
#.........这里部分代码省略.........
示例8: P
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [as 别名]
kk = np.logspace(-4,np.log10(3),1000) # k in h/Mpc
Pk = [] # P(k) in (Mpc/h)**3
h = LambdaCDM.h() # get reduced Hubble for conversions to 1/Mpc
for k in kk:
Pk.append(LambdaCDM.pk(k*h,0.)*h**3) # function .pk(k,z)
# In[ ]:
# plot P(k)
plt.figure(2)
plt.xscale('log');plt.yscale('log');plt.xlim(kk[0],kk[-1])
plt.xlabel(r'$k \,\,\,\, [h/\mathrm{Mpc}]$')
plt.ylabel(r'$P(k) \,\,\,\, [\mathrm{Mpc}/h]^3$')
plt.plot(kk,Pk,'b-')
# In[ ]:
plt.savefig('warmup_pk.pdf')
# In[ ]:
# optional: clear content of LambdaCDM (to reuse it for another model)
LambdaCDM.struct_cleanup()
# optional: reset parameters to default
LambdaCDM.empty()
# In[ ]:
示例9: Helium
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [as 别名]
'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'})
M.compute()
cl_eisw = M.raw_cl(3000)
M.struct_cleanup()
M.empty()
#
示例10: TestClass
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [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 = {
'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_parameters(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")
if self.cosmo.state:
print '--> Class is ready'
# Depending
#.........这里部分代码省略.........
示例11: classy
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [as 别名]
class classy(SlikPlugin):
"""
Plugin for CLASS.
Credit: Brent Follin, Teresa Hamill
"""
#{cosmoslik name : class name}
name_mapping = {'As':'A_s',
'ns':'n_s',
'r':'r',
'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'}
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,
tau,
omnuh2, #0.006
w=None,
r=None,
nrun=None,
omk=0,
Yp=None,
Tcmb=2.7255,
massive_neutrinos=1,
massless_neutrinos=2.046,
l_max_scalar=3000,
l_max_tensor=3000,
pivot_scalar=0.002,
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']}
示例12: Class
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [as 别名]
'custom3': 0,
'custom4': 0,
'custom5': 0}
#Get the unperturbed cls for comparison
cosmo = Class()
cosmo.set(params)
cosmo.compute()
clso=cosmo.lensed_cl(2508)['tt'][30:]
ell = cosmo.lensed_cl(2508)['ell'][30:]
for i in range(len(clso)):
clso[i]=ell[i]*(ell[i]+1)/(4*np.pi)*((2.726e6)**2)*clso[i]
a=np.zeros(5)
cosmo.struct_cleanup()
cosmo.empty()
dcls=np.zeros([clso.shape[0],5])
h=1e-6
for m in range(5):
a[m]=h
# Define your cosmology (what is not specified will be set to CLASS default parameters)
params = {
'output': 'tCl lCl',
'l_max_scalars': 2508,
'lensing': 'yes',
'P_k_ini type': 'external_Pk',
'command': 'python /home/andrew/Research/tools/class_public-2.4.3/external_Pk/generate_Pk_cosines.py',
'custom1': a[0],
'custom2': a[1],
'custom3': a[2],
'custom4': a[3],
示例13: TestClass
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [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..)
"""
@classmethod
def setUpClass(self):
self.faulty_figs_path = os.path.join(
os.path.sep.join(os.path.realpath(__file__).split(os.path.sep)[:-1]), "faulty_figs"
)
if os.path.isdir(self.faulty_figs_path):
shutil.rmtree(self.faulty_figs_path)
os.mkdir(self.faulty_figs_path)
@classmethod
def tearDownClass(self):
pass
def setUp(self):
"""
set up data used in the tests.
setUp is called before each test function execution.
"""
self.cosmo = Class()
self.cosmo_newt = 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 = {}
def tearDown(self):
self.cosmo.struct_cleanup()
self.cosmo.empty()
self.cosmo_newt.struct_cleanup()
self.cosmo_newt.empty()
del self.scenario
def poormansname(self, somedict):
string = "_".join([k + "=" + str(v) for k, v in somedict.iteritems()])
string = string.replace("/", "%")
string = string.replace(",", "")
string = string.replace(" ", "")
return string
@parameterized.expand(TUPLE_ARRAY)
def test_0wrapper_implementation(self, inputdict):
"""Create a few instances based on different cosmologies"""
self.scenario.update(inputdict)
self.name = self.poormansname(inputdict)
sys.stderr.write("\n\n---------------------------------\n")
sys.stderr.write("| Test case %s |\n" % self.name)
sys.stderr.write("---------------------------------\n")
for key, value in self.scenario.iteritems():
sys.stderr.write("%s = %s\n" % (key, value))
sys.stdout.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_dict = {"tCl": ["tt"], "lCl": ["pp"], "pCl": ["ee", "bb"]}
density_cl_list = ["nCl", "sCl"]
# 'lensing' is always set to yes. Therefore, trying to compute 'tCl' or
# 'pCl' will fail except if we also ask for 'lCl'. The flag
# 'should_fail' stores this status.
sys.stderr.write("Should")
should_fail = self.test_incompatible_input()
if should_fail:
sys.stderr.write(" fail...\n")
else:
sys.stderr.write(" not fail...\n")
if not should_fail:
self.cosmo.compute()
else:
self.assertRaises(CosmoSevereError, self.cosmo.compute)
return
#.........这里部分代码省略.........
示例14: classy
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [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: Model
# 需要导入模块: from classy import Class [as 别名]
# 或者: from classy.Class import empty [as 别名]
#.........这里部分代码省略.........
arguments: z=0 and output_format='class' (avaible options are
'class' or 'camb'). If different values are desired, first
item of trans must be {'z': value, 'output_format': value}.
pk = list with the minimum and maximum k values to store the present
matter power spectrum and the number of points [k_min, k_max,
number_points]. Default [10^-4, 10^1, 100].
extra = list of any of the method or objects defined in cosmo, e.g.
w0_smg(). It will store {'method': cosmo.w0_smg()}
update = if True update old computed[key] dictionary elsewise create a
new one. Default: True.
cosmo_msg = if True, print cosmo.compute() messages. Default: False.
"""
key = varied_name
if texname:
self.set_texnames({varied_name: texname})
elif key not in self.texnames: # texname will not be set at this stage. No check required
self.set_texnames({varied_name: varied_name})
if (not update) or (key not in self.computed.keys()):
self.computed[key] = od()
for val in values:
# key = "{}={}".format(varied_name, val)
params["parameters_smg"] = inip.vary_params(params["parameters_smg"], [[index_variable, val]])
# It might be after the try to not store empty dictionaries.
# Nevertheless, I find more useful having them to keep track of
# those failed and, perhaps, to implement a method to obtain them
# with Omega_smg_debug.
d = self.computed[key][val] = {}
self.cosmo.empty()
self.cosmo.set(params)
try:
self.cosmo.compute()
except Exception, e:
print "Error: skipping {}={}".format(key, val)
if cosmo_msg:
print e
continue
d['tunned'] = self.cosmo.get_current_derived_parameters(['tuning_parameter'])['tuning_parameter']
for lst in [[back, 'back', self.cosmo.get_background],
[thermo, 'thermo', self.cosmo.get_thermodynamics],
[prim, 'prim', self.cosmo.get_thermodynamics]]:
if lst[0]:
output = lst[2]()
if lst[0][0] == 'all':
d[lst[1]] = output
else:
d[lst[1]] = {}
for item in back:
if type(item) is list:
d[lst[1]].update({item[0]: output[item[0]][item[1]]})
else:
d[lst[1]].update({item: output[item]})
if pert:
# Perturbation is tricky because it can accept two optional
# argument for get_perturbations and this method returns a
# dictionary {'kind_of_pert': [{variable: list_values}]}, where