Ejemplo n.º 1
0
def load_clik(*args, **kwargs):
    """
    Just a wrapper around :func:`component.load_external_module`, that checks that we are
    not being fooled by the wrong `clik <https://pypi.org/project/click/>`_.
    """
    clik = load_external_module(*args, **kwargs)
    if not hasattr(clik, "try_lensing"):
        raise ComponentNotInstalledError(
            kwargs.get("logger"), "Loaded wrong clik: `https://pypi.org/project/click/`")
    return clik
Ejemplo n.º 2
0
 def is_installed(cls, reload=False, **kwargs):
     if not kwargs.get("code", True):
         return True
     try:
         return bool(load_external_module(
             "pypolychord", path=kwargs["path"],
             get_import_path=get_compiled_import_path,
             min_version=cls._pc_repo_version, reload=reload,
             logger=get_logger(cls.__name__), not_installed_level="debug"))
     except ComponentNotInstalledError:
         return False
Ejemplo n.º 3
0
 def initialize(self):
     """Importing CLASS from the correct path, if given, and if not, globally."""
     try:
         install_path = (lambda p: self.get_path(p)
                         if p else None)(self.packages_path)
         min_version = None if self.ignore_obsolete else self._classy_repo_version
         self.classy_module = load_external_module(
             "classy",
             path=self.path,
             install_path=install_path,
             min_version=min_version,
             get_import_path=self.get_import_path,
             logger=self.log,
             not_installed_level="debug")
     except VersionCheckError as excpt:
         raise VersionCheckError(
             str(excpt) + " If you are using CLASS unmodified, upgrade with"
             "`cobaya-install classy --upgrade`. If you are using a modified CLASS, "
             "set the option `ignore_obsolete: True` for CLASS.")
     except ComponentNotInstalledError as excpt:
         raise ComponentNotInstalledError(
             self.log, (f"Could not find CLASS: {excpt}. "
                        "To install it, run `cobaya-install classy`"))
     self.classy = self.classy_module.Class()
     super().initialize()
     # Add general CLASS stuff
     self.extra_args["output"] = self.extra_args.get("output", "")
     if "sBBN file" in self.extra_args:
         self.extra_args["sBBN file"] = (
             self.extra_args["sBBN file"].format(classy=self.path))
     # Normalize `non_linear` vs `non linear`: prefer underscore
     # Keep this convention throughout the rest of this module!
     if "non linear" in self.extra_args:
         if "non_linear" in self.extra_args:
             raise LoggedError(self.log, (
                 "In `extra_args`, only one of `non_linear` or `non linear`"
                 " should be defined."))
         self.extra_args["non_linear"] = self.extra_args.pop("non linear")
     # Normalize non_linear None|False --> "none"
     # Use default one if not specified
     if self.extra_args.get("non_linear", "dummy_string") in (None, False):
         self.extra_args["non_linear"] = non_linear_null_value
     elif ("non_linear" not in self.extra_args
           or self.extra_args["non_linear"] is True):
         self.extra_args["non_linear"] = non_linear_default_code
     # Derived parameters that may not have been requested, but will be necessary later
     self.derived_extra = []
Ejemplo n.º 4
0
 def initialize(self):
     """Imports the PolyChord sampler and prepares its arguments."""
     try:
         install_path = (lambda _p: self.get_path(_p) if _p else None)(
             self.packages_path)
         self.pc = load_external_module(
             "pypolychord", path=self.path, install_path=install_path,
             min_version=self._pc_repo_version,
             get_import_path=get_compiled_import_path, logger=self.log,
             not_installed_level="debug")
     except ComponentNotInstalledError as excpt:
         raise ComponentNotInstalledError(
             self.log, (f"Could not find PolyChord: {excpt}. "
                        "To install it, run `cobaya-install polychord`"))
     with NoLogging(logging.CRITICAL):
         settings = load_external_module(
             "pypolychord.settings", path=self.path, install_path=install_path,
             get_import_path=get_compiled_import_path, logger=self.log)
     # Prepare arguments and settings
     self.n_sampled = len(self.model.parameterization.sampled_params())
     self.n_derived = len(self.model.parameterization.derived_params())
     self.n_priors = len(self.model.prior)
     self.n_likes = len(self.model.likelihood)
     self.nDims = self.model.prior.d()
     self.nDerived = (self.n_derived + self.n_priors + self.n_likes)
     if self.logzero is None:
         self.logzero = np.nan_to_num(-np.inf)
     if self.max_ndead == np.inf:
         self.max_ndead = -1
     self._quants_d_units = ["nlive", "max_ndead"]
     for p in self._quants_d_units:
         if getattr(self, p) is not None:
             setattr(self, p, NumberWithUnits(
                 getattr(self, p), "d", scale=self.nDims, dtype=int).value)
     self._quants_nlive_units = ["nprior", "nfail"]
     for p in self._quants_nlive_units:
         if getattr(self, p) is not None:
             setattr(self, p, NumberWithUnits(
                 getattr(self, p), "nlive", scale=self.nlive, dtype=int).value)
     # Fill the automatic ones
     if getattr(self, "feedback", None) is None:
         values = {logging.CRITICAL: 0, logging.ERROR: 0, logging.WARNING: 0,
                   logging.INFO: 1, logging.DEBUG: 2}
         self.feedback = values[self.log.getEffectiveLevel()]
     # Prepare output folders and prefixes
     if self.output:
         self.file_root = self.output.prefix
         self.read_resume = self.output.is_resuming()
     else:
         output_prefix = share_mpi(hex(int(self._rng.random() * 16 ** 6))[2:]
                                   if is_main_process() else None)
         self.file_root = output_prefix
         # dummy output -- no resume!
         self.read_resume = False
     self.base_dir = self.get_base_dir(self.output)
     self.raw_clusters_dir = os.path.join(self.base_dir, self._clusters_dir)
     self.output.create_folder(self.base_dir)
     if self.do_clustering:
         self.clusters_folder = self.get_clusters_dir(self.output)
         self.output.create_folder(self.clusters_folder)
     self.mpi_info("Storing raw PolyChord output in '%s'.", self.base_dir)
     # Exploiting the speed hierarchy
     if self.blocking:
         blocks, oversampling_factors = self.model.check_blocking(self.blocking)
     else:
         if self.measure_speeds:
             self.model.measure_and_set_speeds(n=self.measure_speeds,
                                               random_state=self._rng)
         blocks, oversampling_factors = self.model.get_param_blocking_for_sampler(
             oversample_power=self.oversample_power)
     self.mpi_info("Parameter blocks and their oversampling factors:")
     max_width = len(str(max(oversampling_factors)))
     for f, b in zip(oversampling_factors, blocks):
         self.mpi_info("* %" + "%d" % max_width + "d : %r", f, b)
     # Save blocking in updated info, in case we want to resume
     self._updated_info["blocking"] = list(zip(oversampling_factors, blocks))
     blocks_flat = list(chain(*blocks))
     self.ordering = [
         blocks_flat.index(p) for p in self.model.parameterization.sampled_params()]
     self.grade_dims = [len(block) for block in blocks]
     # Steps per block
     # NB: num_repeats is ignored by PolyChord when int "grade_frac" given,
     # so needs to be applied by hand.
     # In num_repeats, `d` is interpreted as dimension of each block
     self.grade_frac = [
         int(o * read_dnumber(self.num_repeats, dim_block))
         for o, dim_block in zip(oversampling_factors, self.grade_dims)]
     # Assign settings
     pc_args = ["nlive", "num_repeats", "nprior", "nfail", "do_clustering",
                "feedback", "precision_criterion", "logzero",
                "max_ndead", "boost_posterior", "posteriors", "equals",
                "cluster_posteriors", "write_resume", "read_resume",
                "write_stats", "write_live", "write_dead", "write_prior",
                "maximise", "compression_factor", "synchronous", "base_dir",
                "file_root", "grade_dims", "grade_frac", "nlives"]
     # As stated above, num_repeats is ignored, so let's not pass it
     pc_args.pop(pc_args.index("num_repeats"))
     self.pc_settings = settings.PolyChordSettings(
         self.nDims, self.nDerived, seed=(self.seed if self.seed is not None else -1),
         **{p: getattr(self, p) for p in pc_args if getattr(self, p) is not None})
     # prior conversion from the hypercube
     bounds = self.model.prior.bounds(
         confidence_for_unbounded=self.confidence_for_unbounded)
     # Check if priors are bounded (nan's to inf)
     inf = np.where(np.isinf(bounds))
     if len(inf[0]):
         params_names = list(self.model.parameterization.sampled_params())
         params = [params_names[i] for i in sorted(set(inf[0]))]
         raise LoggedError(
             self.log, "PolyChord needs bounded priors, but the parameter(s) '"
                       "', '".join(params) + "' is(are) unbounded.")
     locs = bounds[:, 0]
     scales = bounds[:, 1] - bounds[:, 0]
     # This function re-scales the parameters AND puts them in the right order
     self.pc_prior = lambda x: (locs + np.array(x)[self.ordering] * scales).tolist()
     # We will need the volume of the prior domain, since PolyChord divides by it
     self.logvolume = np.log(np.prod(scales))
     # Prepare callback function
     if self.callback_function is not None:
         self.callback_function_callable = (
             get_external_function(self.callback_function))
     self.last_point_callback = 0
     # Prepare runtime live and dead points collections
     self.live = SampleCollection(self.model, None, name="live")
     self.dead = SampleCollection(self.model, self.output, name="dead")
     # Done!
     if is_main_process():
         self.log.debug("Calling PolyChord with arguments:")
         for p, v in inspect.getmembers(self.pc_settings, lambda a: not (callable(a))):
             if not p.startswith("_"):
                 self.log.debug("  %s: %s", p, v)
Ejemplo n.º 5
0
    def initialize(self):
        """Importing CAMB from the correct path, if given."""
        try:
            install_path = (lambda p: self.get_path(p)
                            if p else None)(self.packages_path)
            min_version = None if self.ignore_obsolete else self._min_camb_version
            self.camb = load_external_module(
                "camb",
                path=self.path,
                install_path=install_path,
                min_version=min_version,
                get_import_path=self.get_import_path,
                logger=self.log,
                not_installed_level="debug")
        except VersionCheckError as excpt:
            raise VersionCheckError(
                str(excpt) + " If you are using CAMB unmodified, upgrade with"
                "`cobaya-install camb --upgrade`. If you are using a modified CAMB, "
                "set the option `ignore_obsolete: True` for CAMB.")
        except ComponentNotInstalledError as excpt:
            raise ComponentNotInstalledError(
                self.log, (f"Could not find CAMB: {excpt}. "
                           "To install it, run `cobaya-install camb`"))
        super().initialize()
        self.extra_attrs = {
            "Want_CMB": False,
            "Want_cl_2D_array": False,
            'WantCls': False
        }
        # Derived parameters that may not have been requested, but will be necessary later
        self.derived_extra = []
        # Some default settings
        self.needs_perts = False
        self.limber = False
        self.non_linear_sources = False
        self.non_linear_pk = False
        self._base_params = None
        self._needs_lensing_cross = False
        self._sigmaR_z_indices = {}

        if self.external_primordial_pk:
            self.extra_args['initial_power_model'] \
                = self.camb.initialpower.SplinedInitialPower
            self.initial_power_args, self.power_params = {}, []
        else:
            power_spectrum = self.camb.CAMBparams.make_class_named(
                self.extra_args.get('initial_power_model',
                                    self.camb.initialpower.InitialPowerLaw),
                self.camb.initialpower.InitialPower)
            self.initial_power_args, self.power_params = \
                self._extract_params(power_spectrum.set_params)

        nonlin = self.camb.CAMBparams.make_class_named(
            self.extra_args.get('non_linear_model',
                                self.camb.nonlinear.Halofit),
            self.camb.nonlinear.NonLinearModel)

        self.nonlin_args, self.nonlin_params = self._extract_params(
            nonlin.set_params)

        self.requires = str_to_list(getattr(self, "requires", []))
        self._transfer_requires = [
            p for p in self.requires if p not in self.get_can_support_params()
        ]
        self.requires = [
            p for p in self.requires if p not in self._transfer_requires
        ]