Ejemplo n.º 1
0
 def __init__(self, base_folder=None, likelihoods=None):
     fullnames = odict([["commander", "commander_v4.1_lm49.clik"],
                        ["camspec", "CAMspec_v6.2TN_2013_02_26_dist.clik"],
                        ["lowlike", "lowlike_v222.clik"]])
     likelihoods_fullnames = []
     if likelihoods:
         for lik in likelihoods:
             if lik.lower() in fullnames:
                 likelihoods_fullnames.append(fullnames[lik.lower()])
             else:
                 raise ValueError("Likelihood name not recognised: %s.\n" %
                                  lik + "Valid ones are " +
                                  str(fullnames.keys()))
         self._likelihoods_names = likelihoods_fullnames
     else:
         self._likelihoods_names = fullnames.values()
     # Initialize!
     self._likelihoods = odict()
     for lik in self._likelihoods_names:
         full_path = os.path.join(base_folder, lik)
         try:
             self._likelihoods[lik] = clik.clik(full_path)
         except clik.lkl.CError:
             raise ValueError("'clik' failed to initialise the requested " +
                              "likelihood %s" % lik +
                              ", probably because it was" +
                              " not found on the given folder: '%s'" %
                              full_path)
     # Get nuisance parameters
     self._nuisance_parameters = dict(
         [lik_name, {}] for lik_name in self._likelihoods_names)
     for lik in self._likelihoods_names:
         names = self._likelihoods[lik].extra_parameter_names
         self._nuisance_parameters[lik] = ({} if not names else odict(
             [[pname, None] for pname in names]))
Ejemplo n.º 2
0
def main_CMB(argv):
    lklfile = argv[1]
    lkl = clik.clik(lklfile)
    for clfile in argv[2:]:
        cls = nm.loadtxt(clfile)
        nres = lkl(cls.flat[:])
        print(nres)
 def __init__(self, base_folder=None, likelihoods=None):
     fullnames = odict([["commander", "commander_v4.1_lm49.clik"],
                        ["camspec",   "CAMspec_v6.2TN_2013_02_26_dist.clik"],
                        ["lowlike",   "lowlike_v222.clik"]])
     likelihoods_fullnames = []
     if likelihoods:
         for lik in likelihoods:
             if lik.lower() in fullnames:
                 likelihoods_fullnames.append(fullnames[lik.lower()])
             else:
                 raise ValueError("Likelihood name not recognised: %s.\n"%lik+ 
                                  "Valid ones are "+str(fullnames.keys()))
         self._likelihoods_names = likelihoods_fullnames
     else:
         self._likelihoods_names = fullnames.values()
     # Initialize!
     self._likelihoods = odict()
     for lik in self._likelihoods_names:
         full_path = os.path.join(base_folder, lik)
         try:
             self._likelihoods[lik] = clik.clik(full_path)
         except clik.lkl.CError:
             raise ValueError("'clik' failed to initialise the requested "+
                              "likelihood %s"%lik+", probably because it was"+
                              " not found on the given folder: '%s'"%full_path)
     # Get nuisance parameters
     self._nuisance_parameters = dict([lik_name,{}]
                                      for lik_name in self._likelihoods_names)
     for lik in self._likelihoods_names:
         names = self._likelihoods[lik].extra_parameter_names
         self._nuisance_parameters[lik] = ({} if not names else
             odict([[pname,None] for pname in names]))
Ejemplo n.º 4
0
 def initialise(self):
     # Importing Planck's clik library (only once!)
     try:
         clik
     except NameError:
         if not self.path:
             path_to_installation = get_path_to_installation()
             if path_to_installation:
                 self.path_clik = os.path.join(path_to_installation, "code",
                                               common_path)
                 self.path_data = os.path.join(path_to_installation, "data",
                                               common_path)
             else:
                 self.log.error(
                     "No path given to the Planck likelihood. Set the "
                     "likelihood property 'path' or the common property "
                     "'%s'.", _path_install)
                 raise HandledException
         else:
             self.path_clik = self.path
         self.log.info("Importing clik from %s", self.path_clik)
         # test and import clik
         is_installed_clik(self.path_clik,
                           log_and_fail=True,
                           import_it=False)
         import clik
     # Loading the likelihood data
     clik_file = os.path.join(self.path_data, self.clik_file)
     # for lensing, some routines change. Intializing a flag for easier
     # testing of this condition
     self.lensing = "lensing" in self.name
     try:
         self.clik = (clik.clik_lensing(clik_file)
                      if self.lensing else clik.clik(clik_file))
     except clik.lkl.CError:
         self.log.error(
             "The .clik file was not found where specified in the 'clik_file' field "
             "of the settings of this likelihood. Maybe the 'path' given is not "
             "correct? The full path where the .clik file was searched for is '%s'",
             clik_file)
         raise HandledException
     self.expected_params = list(self.clik.extra_parameter_names)
     # line added to deal with a bug in planck likelihood release:
     # A_planck called A_Planck in plik_lite
     if "plikHM_lite" in self.name:
         i = self.expected_params.index('A_Planck')
         self.expected_params[i] = 'A_planck'
         self.log.info(
             "Corrected nuisance parameter name A_Planck to A_planck")
     # Check that the parameters are the right ones
     assert set(self.input_params.keys()) == set(self.expected_params), (
         "Likelihoods parameters do not coincide with the ones clik understands."
     )
     # Placeholder for vector passed to clik
     self.l_maxs = self.clik.get_lmax()
     length = (len(self.l_maxs)
               if self.lensing else len(self.clik.get_has_cl()))
     self.vector = np.zeros(
         np.sum(self.l_maxs) + length + len(self.expected_params))
Ejemplo n.º 5
0
    def __init__(self,
                 clik_file,
                 **nuisance):
        
        super(clik,self).__init__(**nuisance)

        import clik as _clik
        self.clik = _clik.clik(clik_file)            
    def setup(self):
        """
        Sets up the Planck likelihood
        """

        self.likes = []
        for i, f in enumerate(self.clik_files):
            l = clik.clik(f)
            self.likes.append(l)
            nn = len(l.extra_parameter_names)
            if nn != len(self.nu_inds[i]):
                raise Warning('Index arrays %i does not have correct shape.'%i)
Ejemplo n.º 7
0
def do_all_chi2(dffile,bestfit,npar=0):
  import clik
  from scipy.stats.distributions import chi2
  lkl = clik.clik(dffile)
  lkl_full = lkl(bffile_from_cosmomc(dffile,bestfit))
  lkl_add = get_lkl_coadd(dffile,bestfit,all=True)
  n_add = len(lkl_add[1])
  lkl_add=lkl_add[-1]
  nextra = len(lkl.extra_parameter_names)
  oo,Jt0 = ordering_from_smica(dffile)
  n_full = len(oo)
  print ("full lkl  : %g (%g deg) -> %g PTE %g"%(lkl_full,n_full-nextra-npar, -lkl_full*2./(n_full-nextra-npar), chi2.sf(lkl_full*-2,n_full-nextra-npar)))
  print ("coadd lkl : %g (%g deg) -> %g PTE %g"%(lkl_add,n_add-nextra-npar, -lkl_add*2./(n_add-nextra-npar), chi2.sf(lkl_add*-2,n_add-nextra-npar)))
    def setup(self):
        """
        Sets up the Planck likelihood
        """

        self.likes = []
        for i, f in enumerate(self.clik_files):
            l = clik.clik(f)
            self.likes.append(l)
            nn = len(l.extra_parameter_names)
            if nn != len(self.nu_inds[i]):
                raise Warning('Index arrays %i does not have correct shape.' %
                              i)
Ejemplo n.º 9
0
def main(argv):
    pars = clik.miniparse(argv[1])
    cl = nm.loadtxt(pars.initdata)

    lkl = clik.clik(pars.input_object)

    offset = nm.sum(nm.array(lkl.lmax) + 1)
    offset += lkl.extra_parameter_names.index(pars.parameter)

    ps = nm.linspace(pars.float.beg, pars.float.end, pars.float.step)
    res = ps * 0.
    for i, v in enumerate(ps):
        cl[offset] = v
        res[i] = lkl(cl)
    res = nm.array([ps, res]).T

    res.tofile(pars.res, sep="\n")
Ejemplo n.º 10
0
    def __init__(self,
                 clik_file,
                 auto_reject_errors=False,
                 lensing=None,
                 **nuisance):

        super().__init__(**arguments())

        from clik import clik, clik_lensing

        if lensing or "lensing" in clik_file:
            loaded_cliks[clik_file] = self.clik = loaded_cliks[
                clik_file] if clik_file in loaded_cliks else clik_lensing(
                    clik_file)
            self.lensing = True
            self.clik_specs = ['pp'] + clik_specs

        else:
            loaded_cliks[clik_file] = self.clik = loaded_cliks[
                clik_file] if clik_file in loaded_cliks else clik(clik_file)
            self.lensing = False
            self.clik_specs = clik_specs
Ejemplo n.º 11
0
import os
import clik
import numpy as np

### Some important variables ###
clik_root = os.environ.get('PLANCK_2015_DATA')
if clik_root == None:
    raise ValueError('The environment variable PLANCK_2015_DATA is not set.')

### Planck 2015 lite high ells TT
hell_TTlite = clik.clik(clik_root + '/hi_l/plik_lite/plik_lite_v18_TT.clik')
hell_TTlite_pars = hell_TTlite.get_extra_parameter_names()


def get_loglike(class_input, likes_input, class_run):
    args = np.concatenate(
        (class_run.lensed_cl()['tt'][:2509] * 1e12 * class_run.T_cmb()**2.,
         np.array([likes_input[par] for par in hell_TTlite_pars])))
    return hell_TTlite(args)
Ejemplo n.º 12
0
def main_CMB(argv):
  clikl = clik.clik(sys.argv[1])

  extn = clikl.extra_parameter_names
  
  lkl = hpy.File(sys.argv[1],"r")["clik"]
  
  print("clik lkl file =  %s"%sys.argv[1])
  print("  number of likelihoods = %d"%lkl.attrs["n_lkl_object"])
  print("  lmax ( "+ " ".join([nl+" = %d"%ll for nl,ll in zip(("TT","EE","BB","TE","TB","EB"),lkl.attrs["lmax"]) if ll >-1])+" )")
  print("  number of varying extra parameters %d"%(len(extn)))
  for n in extn:
    print("    %s"%n)
  if "prior" in lkl:
    names = lkl["prior"].attrs["name"]
    names = [names[i*256:(i+1)*256].strip() for i in range(len(names)/256)]
    print("  gaussian priors on %s"%", ".join(names))
    loc = lkl["prior/loc"][:]
    print("  at \n    %s"%" ".join([str(l) for l in loc]))
    var = lkl["prior/var"][:]
    if len(var)==len(loc):
      var = nm.diag(var)
    var.shape=(len(loc),-1)
    print("  with variance")
    print("\n".join(["    "+" ".join([str(v) for v in vl]) for vl in var]))
  if "default" in lkl:
    loc = lkl["default/loc"][:] 
    print("  number of fixed parameters = %d"%len(loc))
    nms = lkl["default"].attrs["name"]
    nms = [nms[i*256:i*256+256].strip() for i in range(len(loc))]
    for n,l in zip(nms,loc):
      print("    %s = %g"%(n,l))

  ilkl = 0
  for lkli_n in ("lkl_%d"%v for v in range(lkl.attrs["n_lkl_object"])):
    lkli = lkl[lkli_n]
    print("\n  %s"%lkli_n)
    print("    lkl_type = %s"%lkli.attrs["lkl_type"])
    print("    unit = %g"%lkli.attrs["unit"])
    
    if "lmax" in lkli.attrs:
      lmax = lkli.attrs["lmax"]
      lmin = 0
      if "lmin" in lkli.attrs:
        lmin = lkli.attrs["lmin"]
      ellh = False
    else:
      ell = lkli.attrs["ell"]
      lmax = nm.max(ell)      
      lmin = nm.min(ell)
      ellh = not nm.alltrue((ell[1:]-ell[:-1]) == 1)
    
    print("    "+" ".join([nl+" = [%d , %d]"%(lmin,lmax) for nl,hl in zip(("TT","EE","BB","TE","TB","EB"),lkli.attrs["has_cl"]) if hl ])+" (discontinous)"*ellh)
    
    if "wl" in lkli.attrs:
      print("    has window function")
    if "nbins" in lkli.attrs:
      print("    nbins = %d"%lkli.attrs["nbins"])
    if lkli.attrs["lkl_type"]=="smica":
      print("    component 0 : CMB")
      for nc in range(1,lkli.attrs["n_component"]):
        if "component_name" in lkli["component_%d"%nc]:
          print("    component %d : %s"%(nc,lkli["component_%d"%nc].attrs["component_name"]))
        else:
          print("    component %d : %s"%(nc,lkli["component_%d"%nc].attrs["component_type"]))

    extn = clikl.get_extra_parameter_names_by_lkl(ilkl)
    print("    number of extra parameters = %d %s"%(len(extn),extn))
    ilkl +=1
Ejemplo n.º 13
0
 def initialize(self):
     if "2015" in self.get_name():
         for line in _deprecation_msg_2015.split("\n"):
             self.log.warning(line)
     code_path = common_path
     data_path = get_data_path(self.__class__.get_qualified_class_name())
     if self.path:
         has_clik = False
     else:
         try:
             import clik
             has_clik = True
         except ImportError:
             clik = None
             has_clik = False
     if not has_clik:
         if not self.path:
             if self.packages_path:
                 self.path_clik = os.path.join(self.packages_path, "code", code_path)
             else:
                 raise LoggedError(
                     self.log, "No path given to the Planck likelihood. Set the "
                               "likelihood property 'path' or the common property "
                               "'%s'.", _packages_path)
         else:
             self.path_clik = self.path
         self.log.info("Importing clik from %s", self.path_clik)
         # test and import clik
         is_installed_clik(self.path_clik, log_and_fail=True, import_it=False)
         import clik
     # Loading the likelihood data
     if not os.path.isabs(self.clik_file):
         self.path_data = getattr(self, "path_data", os.path.join(
             self.path or self.packages_path, "data", data_path))
         self.clik_file = os.path.join(self.path_data, self.clik_file)
     # Differences in the wrapper for lensing and non-lensing likes
     self.lensing = clik.try_lensing(self.clik_file)
     try:
         self.clik = clik.clik_lensing(self.clik_file) if self.lensing \
             else clik.clik(self.clik_file)
     except clik.lkl.CError:
         # Is it that the file was not found?
         if not os.path.exists(self.clik_file):
             raise LoggedError(
                 self.log, "The .clik file was not found where specified in the "
                           "'clik_file' field of the settings of this likelihood. "
                           "Maybe the 'path' given is not correct? The full path where"
                           " the .clik file was searched for is '%s'", self.clik_file)
         # Else: unknown clik error
         self.log.error("An unexpected error occurred in clik (possibly related to "
                        "multiple simultaneous initialization, or simultaneous "
                        "initialization of incompatible likelihoods (e.g. polarised "
                        "vs non-polarised 'lite' likelihoods. See error info below:")
         raise
     self.l_maxs = self.clik.get_lmax()
     # calculate requirements here so class can also be separately instantiated
     requested_cls = ["tt", "ee", "bb", "te", "tb", "eb"]
     if self.lensing:
         has_cl = [lmax != -1 for lmax in self.l_maxs]
         requested_cls = ["pp"] + requested_cls
     else:
         has_cl = self.clik.get_has_cl()
     self.requested_cls = [cl for cl, i in zip(requested_cls, has_cl) if int(i)]
     self.l_maxs_cls = [lmax for lmax, i in zip(self.l_maxs, has_cl) if int(i)]
     self.expected_params = list(self.clik.extra_parameter_names)
     # Placeholder for vector passed to clik
     length = (len(self.l_maxs) if self.lensing else len(self.clik.get_has_cl()))
     self.vector = np.zeros(np.sum(self.l_maxs) + length + len(self.expected_params))
Ejemplo n.º 14
0
import os
import clik
import numpy as np

### Some important variables ###
clik_root = os.environ.get('PLANCK_2018_DATA')
if clik_root == None:
    raise ValueError('The environment variable PLANCK_2018_DATA is not set.')

### Planck 2018 low ells TT
lell_TT = clik.clik(clik_root + '/low_l/commander/commander_dx12_v3_2_29.clik')
lell_TT_pars = lell_TT.get_extra_parameter_names()


def get_loglike(class_input, likes_input, class_run):
    args = np.concatenate(
        (class_run.lensed_cl()['tt'][:30] * 1e12 * class_run.T_cmb()**2.,
         np.array([likes_input[par] for par in lell_TT_pars])))
    return lell_TT(args)
Ejemplo n.º 15
0
import os
import clik
import numpy as np

### Some important variables ###
clik_root = os.environ.get('PLANCK_2018_DATA')
if clik_root == None:
    raise ValueError('The environment variable PLANCK_2018_DATA is not set.')

### Planck 2018 low ells EE, BB
lell_EEBB = clik.clik(
    clik_root + '/low_l/simall/simall_100x143_offlike5_EEBB_Aplanck_B.clik')
lell_EEBB_pars = lell_EEBB.get_extra_parameter_names()


def get_loglike(class_input, likes_input, class_run):
    args = np.concatenate(
        (class_run.lensed_cl()['ee'][:30] * 1e12 * class_run.T_cmb()**2.,
         class_run.lensed_cl()['bb'][:30] * 1e12 * class_run.T_cmb()**2.,
         np.array([likes_input[par] for par in lell_EEBB_pars])))
    return lell_EEBB(args)
Ejemplo n.º 16
0
 def initialize(self):
     if "2015" in self.name:
         for line in _deprecation_msg_2015.split("\n"):
             self.log.warning(line)
     code_path = common_path
     data_path = get_data_path(self.__class__.get_module_name())
     if self.path:
         has_clik = False
     else:
         try:
             import clik
             has_clik = True
         except ImportError:
             has_clik = False
     if not has_clik:
         if not self.path:
             if self.path_install:
                 self.path_clik = os.path.join(self.path_install, "code",
                                               code_path)
             else:
                 raise LoggedError(
                     self.log,
                     "No path given to the Planck likelihood. Set the "
                     "likelihood property 'path' or the common property "
                     "'%s'.", _path_install)
         else:
             self.path_clik = self.path
         self.log.info("Importing clik from %s", self.path_clik)
         # test and import clik
         is_installed_clik(self.path_clik,
                           log_and_fail=True,
                           import_it=False)
         import clik
     # Loading the likelihood data
     if not os.path.isabs(self.clik_file):
         self.path_data = getattr(
             self, "path_data",
             os.path.join(self.path or self.path_install, "data",
                          data_path))
         self.clik_file = os.path.join(self.path_data, self.clik_file)
     # Differences in the wrapper for lensing and non-lensing likes
     self.lensing = clik.try_lensing(self.clik_file)
     try:
         self.clik = (clik.clik_lensing(self.clik_file)
                      if self.lensing else clik.clik(self.clik_file))
     except clik.lkl.CError:
         # Is it that the file was not found?
         if not os.path.exists(self.clik_file):
             raise LoggedError(
                 self.log,
                 "The .clik file was not found where specified in the "
                 "'clik_file' field of the settings of this likelihood. Maybe the "
                 "'path' given is not correct? The full path where the .clik file was "
                 "searched for is '%s'", self.clik_file)
         # Else: unknown clik error
         self.log.error(
             "An unexpected error occurred in clik (possibly related to "
             "multiple simultaneous initialization, or simultaneous "
             "initialization of incompatible likelihoods (e.g. polarised "
             "vs non-polarised 'lite' likelihoods. See error info below:")
         raise
     # Check that the parameters are the right ones
     self.expected_params = list(self.clik.extra_parameter_names)
     differences = are_different_params_lists(self.input_params,
                                              self.expected_params,
                                              name_A="given",
                                              name_B="expected")
     if differences:
         raise LoggedError(
             self.log, "Configuration error in parameters: %r. "
             "If this has happened without you fiddling with the defaults, "
             "please open an issue in GitHub.", differences)
     # Placeholder for vector passed to clik
     self.l_maxs = self.clik.get_lmax()
     length = (len(self.l_maxs)
               if self.lensing else len(self.clik.get_has_cl()))
     self.vector = np.zeros(
         np.sum(self.l_maxs) + length + len(self.expected_params))
Ejemplo n.º 17
0
import os
import clik
import numpy as np

### Some important variables ###
clik_root = os.environ.get('PLANCK_2015_DATA')
if clik_root == None:
    raise ValueError('The environment variable PLANCK_2015_DATA is not set.')

### Planck 2015 lite high ells TT, TE, EE
hell_TTTEEElite = clik.clik(clik_root + '/hi_l/plik_lite/plik_lite_v18_TTTEEE.clik')
hell_TTTEEElite_pars = hell_TTTEEElite.get_extra_parameter_names()
def get_loglike(class_input, likes_input, class_run):
    args = np.concatenate((
        class_run.lensed_cl()['tt'][:2509] * 1e12 * class_run.T_cmb()**2.,
        class_run.lensed_cl()['ee'][:2509] * 1e12 * class_run.T_cmb()**2.,
        class_run.lensed_cl()['te'][:2509] * 1e12 * class_run.T_cmb()**2.,
        np.array([likes_input[par] for par in hell_TTTEEElite_pars])
    ))
    return hell_TTTEEElite(args)
Ejemplo n.º 18
0
def getLk(plikfile):
    lkl = cache.get(plikfile, None)
    if not lkl:
        lkl = clik.clik(plikfile)
        cache[plikfile] = lkl
    return lkl
Ejemplo n.º 19
0
import os
import clik
import numpy as np

### Some important variables ###
clik_root = os.environ.get('PLANCK_2018_DATA')
if clik_root == None:
    raise ValueError('The environment variable PLANCK_2018_DATA is not set.')

### Planck 2018 high ells TT
hell_TT = clik.clik(clik_root + '/hi_l/plik/plik_rd12_HM_v22_TT.clik')
hell_TT_pars = hell_TT.get_extra_parameter_names()


def get_loglike(class_input, likes_input, class_run):
    args = np.concatenate(
        (class_run.lensed_cl()['tt'][:2509] * 1e12 * class_run.T_cmb()**2.,
         np.array([likes_input[par] for par in hell_TT_pars])))
    return hell_TT(args)
Ejemplo n.º 20
0
import os
import clik
import numpy as np

### Some important variables ###
clik_root = os.environ.get('PLANCK_2015_DATA')
if clik_root == None:
    raise ValueError('The environment variable PLANCK_2015_DATA is not set.')

### Planck 2015 low ells TT, EE, BB
lell_TEB = clik.clik(clik_root +
                     '/low_l/bflike/lowl_SMW_70_dx11d_2014_10_03_v5c_Ap.clik')
lell_TEB_pars = lell_TEB.get_extra_parameter_names()


def get_loglike(class_input, likes_input, class_run):
    args = np.concatenate(
        (class_run.lensed_cl()['tt'][:30] * 1e12 * class_run.T_cmb()**2.,
         class_run.lensed_cl()['ee'][:30] * 1e12 * class_run.T_cmb()**2.,
         class_run.lensed_cl()['bb'][:30] * 1e12 * class_run.T_cmb()**2.,
         class_run.lensed_cl()['te'][:30] * 1e12 * class_run.T_cmb()**2.,
         np.array([likes_input[par] for par in lell_TEB_pars])))
    return lell_TEB(args)
Ejemplo n.º 21
0
import os
import clik
import numpy as np

### Some important variables ###
clik_root = os.environ.get('PLANCK_2015_DATA')
if clik_root == None:
    raise ValueError('The environment variable PLANCK_2015_DATA is not set.')

### Planck 2015 low ells TT
lell_TT = clik.clik(clik_root +
                    '/low_l/commander/commander_rc2_v1.1_l2_29_B.clik')
lell_TT_pars = lell_TT.get_extra_parameter_names()


def get_loglike(class_input, likes_input, class_run):
    args = np.concatenate(
        (class_run.lensed_cl()['tt'][:30] * 1e12 * class_run.T_cmb()**2.,
         np.array([likes_input[par] for par in lell_TT_pars])))
    return lell_TT(args)
Ejemplo n.º 22
0
def change_cls(dffile,bestfit,cls):
  import  clik
  clo = nm.loadtxt(bestfit)
  clo[:len(clik.clik(dffile).cc.get_extra_parameter_names())] = cls
  return cls
Ejemplo n.º 23
0
def getLk(plikfile):
    lkl = cache.get(plikfile, None)
    if not lkl:
        lkl = clik.clik(plikfile)
        cache[plikfile] = lkl
    return lkl
Ejemplo n.º 24
0
    def __init__(self,
                 clik_file,
                 auto_reject_errors=False,
                 lensing=None,
                 **nuisance):

        super().__init__(**arguments())

        from clik import clik, clik_lensing
        
        if lensing or "lensing" in clik_file:
            loaded_cliks[clik_file] = self.clik = loaded_cliks[clik_file] if clik_file in loaded_cliks else clik_lensing(clik_file)
            self.lensing = True
            self.clik_specs = ['pp'] + clik_specs
            
        else:
            loaded_cliks[clik_file] = self.clik = loaded_cliks[clik_file] if clik_file in loaded_cliks else clik(clik_file)
            self.lensing = False
            self.clik_specs = clik_specs
Ejemplo n.º 25
0
zcmb, zhel, dz, mb, dmb, x1, dx1, color, dcolor, thirdvar, cov_m_s, cov_m_c, cov_s_c, set_jla = loadtxt('/sto/home/willribeiro/Data/jla_lcparams.txt', usecols=(1,2,3,4,5,6,7,8,9,10,14,15,16,17), unpack=True)
sigma_coh, sigma_lens, zfile = loadtxt('/sto/home/willribeiro/Data/sigma_mu.txt', usecols=(0,1,2), unpack=True)

V0 = sc.genfromtxt('/sto/home/willribeiro/Data/jla_v0_covmatrix.dat')
Va = sc.genfromtxt('/sto/home/willribeiro/Data/jla_va_covmatrix.dat')
Vb = sc.genfromtxt('/sto/home/willribeiro/Data/jla_vb_covmatrix.dat')
V0a = sc.genfromtxt('/sto/home/willribeiro/Data/jla_v0a_covmatrix.dat')
V0b = sc.genfromtxt('/sto/home/willribeiro/Data/jla_v0b_covmatrix.dat')
Vab = sc.genfromtxt('/sto/home/willribeiro/Data/jla_vab_covmatrix.dat')


####################################################################################################################################
#DATA FOR CMB FROM PLANCK LIKELIHOODS

lkl_highl = clik.clik('/sto/home/willribeiro/Data/plik_dx11dr2_HM_v18_TT.clik')
lkl_lowl = clik.clik('/sto/home/willribeiro/Data/lowl_SMW_70_dx11d_2014_10_03_v5c_Ap.clik')


########################################################################################################################################
#DEFINING SOME PARAMETERS

z1, z2, z3, z4, z5, z6, zlim = 0.0, 0.25, 0.50, 0.85, 1.25, 2.0, 2.25 #redshift bins
wlim = -1.0 #limiting w for redshifts higher than zlim

wgamma = 0.00002469 #wgamma for photons, this is well fixed by COBE satellite (Amendola, (2.45))
light = 299792.458 #speed of light in km/s
H0_jla = 70.0 #fiducial H0 value for supernovae (it has no influence on the final results)
cib_index = -1.3 #fixed nuisance from Planck

#Log information from terminal in txt
Ejemplo n.º 26
0
    def __init__(self, clikfile, paramnames=None):
        # paramnames will be used to do the mapping to the extra parameters
        self.dffile = clikfile
        self.name = os.path.splitext(os.path.basename(clikfile))[0]
        if isinstance(paramnames, (list, tuple)):
            self.parnames = paramnames
        else:
            if paramnames is None:
                # match versions to the baseline .paramnames file
                for rem in ['_', 'a_', 'b_', 'c_', 'd_']:
                    name = self.name.replace(rem, '_').replace('_bin1', '')
                    paramnames = os.path.join(
                        os.path.dirname(__file__),
                        '../../data/' + name + '.paramnames')
                    if os.path.exists(paramnames):
                        break
            self.paramnamefile = paramnames
            self.paramnames = ParamNames(paramnames)
            self.parnames = self.paramnames.list()

        self.clik = clik.clik(clikfile)
        self._translate_parname(self.parnames)

        self.fi = hpy.File(self.dffile)

        # some metadata
        self.hascl = self.fi["clik/lkl_0/has_cl"]
        self.lmin = self.fi["clik/lkl_0/lmin"]
        self.lmax = self.fi["clik/lkl_0/lmax"]

        self.mt = self.fi["clik/lkl_0/m_channel_T"] * self.hascl[0]
        self.me = self.fi["clik/lkl_0/m_channel_P"] * self.hascl[1]
        self.mb = self.fi["clik/lkl_0/m_channel_P"] * self.hascl[2]
        self.m = self.mt + self.me + self.mb

        self.nb = self.fi["clik/lkl_0/nbins"] / self.hascl.sum()
        self.rq_shape = (self.nb, self.m, self.m)

        # binning details
        self.blmin = self.fi["clik/lkl_0/bin_lmin"]
        self.blmax = self.fi["clik/lkl_0/bin_lmax"]
        self.b_ws = self.fi["clik/lkl_0/bin_ws"]
        # the binning matrix is also simply obtained this way (but using it is slower than using the binning details, 'cause it's full of zeros)
        self.bns = php.read_bins(self.fi["clik/lkl_0"])

        # compute the binned ells
        self.lm = np.dot(self.bns[:self.nb, :self.lmax - self.lmin + 1],
                         np.arange(self.lmin, self.lmax + 1))

        # get the calibration part (and beam for plik 2015)
        # cal and bal are functions that expect a vector of parameters whose name and ordering are given by cal.varpar and bal.varpar
        # overal calibration is given by cal(pars)*vec(pars)*outer(acmb,acmb)[nm.newaxis,:,:]
        self.cal = smh.calTP_from_smica(self.dffile)
        self.bal = smh.beamTP_from_smica(self.dffile)
        self.acmb = self.fi["clik/lkl_0/A_cmb"]

        # get the binned Cl data array
        self.rqh = self.fi["clik/lkl_0/Rq_hat"]
        self.rqh.shape = self.rq_shape

        # get the additive nuisance components
        self.prms = smh.parametric_from_smica(self.dffile)
        self.prms_name = [p.get_name() for p in self.prms]

        # get the selection vector
        self.oo, self.Jt = smh.ordering_from_smica(self.dffile)

        # get the inverse covariance
        self.siginv = self.fi["clik/lkl_0/criterion_gauss_mat"]
        self.siginv.shape = (len(self.oo), len(self.oo))

        ls = np.arange(self.lmax + 1)
        self.llp1 = ls * (ls + 1) / (2 * np.pi)
        self.llp1[0] = 1
        self.indices = [(0, 0), (1, 1), (2, 2), (0, 1), (0, 2), (1, 2)]
        self.spectra = ["tt", "ee", "bb", "te", "tb", "eb"]
Ejemplo n.º 27
0
import os
import clik
import numpy as np

### Some important variables ###
clik_root = os.environ.get('PLANCK_2015_DATA')
if clik_root == None:
    raise ValueError('The environment variable PLANCK_2015_DATA is not set.')

### Planck 2015 high ells TT
hell_TT = clik.clik(clik_root + '/hi_l/plik/plik_dx11dr2_HM_v18_TT.clik')
hell_TT_pars = hell_TT.get_extra_parameter_names()


def get_loglike(class_input, likes_input, class_run):
    args = np.concatenate(
        (class_run.lensed_cl()['tt'][:2509] * 1e12 * class_run.T_cmb()**2.,
         np.array([likes_input[par] for par in hell_TT_pars])))
    return hell_TT(args)
Ejemplo n.º 28
0
 def init(self, p):
     import clik
     self.files = p.get(('clik','files'),{})
     self.cliks = {k:clik.clik(v) for k,v in self.files.items()}