When providing the same input parameters and units, class and classy has the same outputs.
from classy import Class
import os
import io
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
def read_txt(path):
with open(path, 'r') as f:
# remove beginning `#`
text = f.read()[1:]
with io.StringIO(text) as f:
# input has 6 sig. fig. which fits in float32
return pd.read_csv(f, delim_whitespace=True, index_col=0, dtype=np.float32)
def read_class_txt(path, camb=False):
# read once
with open(path, 'r') as f:
text = f.read()
# get last comment line
comment = None
for line in text.split('\n'):
if line.startswith('#'):
comment = line
# remove beginning '#'
comment = comment[1:]
# parse comment line: get name after ':'
names = [name.split(':')[1] for name in comment.strip().split()]
with io.StringIO(text) as f:
df = pd.read_csv(f, delim_whitespace=True, index_col=0, comment='#', header=None, names=names)
return df if camb else df * 1.e12
def plot_compare(df1, df2, keys, log=False, relative=False):
'''plot to compare columns from `df1` and `df2`,
using columns from `df1`.
`keys`: tuple of str of names of `df1` and `df2`.
`relative`: if True, plot the relative error w.r.t. `df1` instead.
'''
for col in df1.columns:
# pd.merge(df1[col], df2[col], left_index=True, right_index=True).plot()
df_temp = pd.concat((df1[col], df2[col]), axis=1, join='inner', keys=(' '.join((key, col)) for key in keys))
if relative:
temp = df_temp.values
if log:
plt.loglog(df_temp.index, np.abs((temp[:, 0] - temp[:, 1]) / temp[:, 0]), label=col)
else:
plt.plot(df_temp.index, np.abs((temp[:, 0] - temp[:, 1]) / temp[:, 0]), label=col)
plt.legend()
plt.show()
else:
if log:
df_temp.plot(logx=True, logy=True)
else:
df_temp.plot()
path = os.path.expanduser('~/git/fork/class/output/base_2018_plikHM_TTTEEE_lowl_lowE_lensing_cl_lensed.dat')
!head -n 20 $path
df_class = read_class_txt(path, camb=True)
df_class.head()
LambdaCDM = Class()
# optional: clear content of LambdaCDM (to reuse it for another model)
LambdaCDM.struct_cleanup()
# optional: reset parameters to default
LambdaCDM.empty()
kwargs = {
# background parameters
'H0': 67.32117,
'omega_b': 0.02238280,
'N_ur': 2.03066666667,
'omega_cdm': 0.1201075,
'N_ncdm': 1,
'omega_ncdm': 0.0006451439,
'YHe': 0.2454006,
'tau_reio': 0.05430842,
'n_s': 0.9660499,
'A_s': 2.100549e-09,
'non linear': 'halofit',
'output': 'tCl,pCl,lCl,mPk',
'lensing': 'yes',
# 'P_k_max_1/Mpc': 3.,
# 'l_max_scalars': 3000,
}
LambdaCDM.set(kwargs)
LambdaCDM.compute()
df = pd.DataFrame(LambdaCDM.lensed_cl())
df.set_index('ell', inplace=True)
ell = df.index.values.astype(np.int32)
df *= ((ell * (ell + 1)) * 0.5 / np.pi)[:, None]
df.columns = ['TT', 'EE', 'TE', 'BB', 'phiphi', 'TPhi']
# df *= 1.e12
df.head()
plot_compare(df, df_class, ('classy', 'class'), relative=True)