Example #1
0
    def set_model(self, likelihoodModel):
        """
        Set the model to be used in the joint minimization.
        Must be a LikelihoodModel instance.
        """

        with suppress_stdout():

            self.lmc = LikelihoodModelConverter(likelihoodModel, self.irf)

            self.lmc.setFileSpectrumEnergies(self.emin, self.emax,
                                             self.Nenergies)

            xmlFile = str("%s.xml" % get_random_unique_name())

            temp_files = self.lmc.writeXml(xmlFile, self.ra, self.dec,
                                           self.rad)

        if self.kind == "BINNED":
            self.like = BinnedAnalysis.BinnedAnalysis(self.obs,
                                                      xmlFile,
                                                      optimizer="DRMNFB")

        else:

            self.like = UnbinnedAnalysis.UnbinnedAnalysis(self.obs,
                                                          xmlFile,
                                                          optimizer="DRMNFB")

        self.likelihoodModel = likelihoodModel

        # Here we need also to compute the logLike value, so that the model
        # in the XML file will be chanded if needed
        dumb = self.get_log_like()

        # Since now the Galactic template is in RAM, we can remove the temporary file
        os.remove(self.lmc._unique_filename)
        os.remove(xmlFile)

        # Delete temporary spectral files
        for temp_file in temp_files:

            os.remove(temp_file)

        # Build the list of the nuisance parameters
        new_nuisance_parameters = self._setNuisanceParameters()

        self.update_nuisance_parameters(new_nuisance_parameters)
Example #2
0
    def set_model(self, likelihoodModel):
        '''
        Set the model to be used in the joint minimization.
        Must be a LikelihoodModel instance.
        '''

        with suppress_stdout():

            self.lmc = LikelihoodModelConverter(likelihoodModel,
                                                self.irf)

            self.lmc.setFileSpectrumEnergies(self.emin, self.emax, self.Nenergies)

            xmlFile = '%s.xml' % get_random_unique_name()

            temp_files = self.lmc.writeXml(xmlFile, self.ra, self.dec, self.rad)

        if (self.kind == "BINNED"):
            self.like = BinnedAnalysis.BinnedAnalysis(self.obs,
                                                      xmlFile,
                                                      optimizer='DRMNFB')

        else:

            self.like = UnbinnedAnalysis.UnbinnedAnalysis(self.obs,
                                                          xmlFile,
                                                          optimizer='DRMNFB')

        self.likelihoodModel = likelihoodModel

        # Here we need also to compute the logLike value, so that the model
        # in the XML file will be chanded if needed
        dumb = self.get_log_like()

        # Since now the Galactic template is in RAM, we can remove the temporary file
        os.remove(self.lmc._unique_filename)
        os.remove(xmlFile)

        # Delete temporary spectral files
        for temp_file in temp_files:

            os.remove(temp_file)

        # Build the list of the nuisance parameters
        new_nuisance_parameters = self._setNuisanceParameters()

        self.update_nuisance_parameters(new_nuisance_parameters)
Example #3
0
    def _minimize(self):
        """
            Minimize the function using the Multinest sampler
         """

        n_dim = len(self.parameters)

        # We need to check if the MCMC
        # chains will have a place on
        # the disk to write and if not,
        # create one

        # chain_name = "multinest_minimizer/fit-"
        #
        # mcmc_chains_out_dir = ""
        # tmp = chain_name.split('/')
        # for s in tmp[:-1]:
        #     mcmc_chains_out_dir += s + '/'
        #
        # if not os.path.exists(mcmc_chains_out_dir):
        #
        #     os.makedirs(mcmc_chains_out_dir)

        with temporary_directory(
                prefix="multinest-",
                within_directory=os.getcwd()) as mcmc_chains_out_dir:

            outputfiles_basename = os.path.join(mcmc_chains_out_dir, "fit-")

            # print("\nMultinest is exploring the parameter space...\n")

            # Reset the likelihood values
            self._log_like_values = []

            sampler = pymultinest.run(
                self._func_wrapper,
                self._prior,
                n_dim,
                n_dim,
                outputfiles_basename=outputfiles_basename,
                n_live_points=self._setup_dict["live_points"],
                multimodal=True,
                resume=False,
            )

            # Use PyMULTINEST analyzer to gather parameter info

            # NOTE: I encapsulate this to avoid the output in the constructor of Analyzer

            with suppress_stdout():

                multinest_analyzer = pymultinest.analyse.Analyzer(
                    n_params=n_dim, outputfiles_basename=outputfiles_basename)

            # Get the function value from the chain
            func_values = multinest_analyzer.get_equal_weighted_posterior()[:,
                                                                            -1]

            # Store the sample for further use (if needed)

            self._sampler = sampler

            # Get the samples from the sampler

            _raw_samples = multinest_analyzer.get_equal_weighted_posterior(
            )[:, :-1]

        # Find the minimum of the function (i.e. the maximum of func_wrapper)

        idx = func_values.argmax()

        best_fit_values = _raw_samples[idx]

        minimum = func_values[idx] * (-1)

        return best_fit_values, minimum