def basic_plot(self, output_name=""):
        p = pymultinest.PlotMarginalModes(self.a)
        plt.figure(figsize=(5 * self.ndim, 5 * self.ndim))
        #plt.subplots_adjust(wspace=0, hspace=0)
        for i in range(self.ndim):
            plt.subplot(self.ndim, self.ndim, self.ndim * i + i + 1)
            p.plot_marginal(i,
                            with_ellipses=True,
                            with_points=False,
                            grid_points=50)
            plt.ylabel("Probability")
            plt.xlabel(parameters[i])

            for j in range(i):
                plt.subplot(self.ndim, self.ndim, self.ndim * j + i + 1)
                #plt.subplots_adjust(left=0, bottom=0, right=0, top=0, wspace=0, hspace=0)
                p.plot_conditional(i,
                                   j,
                                   with_ellipses=False,
                                   with_points=True,
                                   grid_points=30)
                plt.xlabel(parameters[i])
                plt.ylabel(parameters[j])

        plt.savefig(self.output_directory + output_name +
                    ".pdf")  #, bbox_inches='tight')
def plotMarginal():
    import numpy as np
    import pymultinest
    from matplotlib import pyplot as plt
    outputFiles_rawbase = raw_input('Type path to chains folder: ')
    prefix = '%s/chains/1-'%outputFiles_rawbase
    
    open_params = open('%s/chains/.tmp_myCode/parameters.txt'%outputFiles_rawbase)
    paramNames = open_params.read().split()
    open_params.close()
    
    n_params = len(paramNames)

    a = pymultinest.Analyzer(n_params = n_params, outputfiles_basename = prefix)
    s = a.get_stats()

    p = pymultinest.PlotMarginalModes(a)

    for i in range(1,n_params):
#        plt.subplot(n_params, n_params, n_params * i + i + 1)
        #p.plot_marginal(i, ls='-', color='blue', linewidth=3)
        #p.plot_marginal(i, with_ellipses = True, dim2 = True, with_points = False, grid_points=50)
        
        
        for j in range(i):

            plt.subplot(n_params-1, n_params-1, (n_params-1) * j + i)
            p.plot_conditional(i, j, with_ellipses = False, with_points = False, grid_points=30)
            
        plt.subplot(n_params-1,n_params-1,(n_params-1)*(i-1) + i)
        plt.xlabel(paramNames[i])
        plt.ylabel(paramNames[i-1])

    plt.show()
def plotMarginal(n_params):
    import numpy as np
    import pymultinest
    from matplotlib import pyplot as plt
    outputFiles_rawbase = raw_input('Type path to chains folder: ')
    prefix = '%s/chains/1-' % outputFiles_rawbase

    if n_params == 8:
        paramNames = [
            r'$\epsilon_e$', 'E0', 'n', r'$\Gamma_0$', '$\epsilon_B$', 'p',
            r'$\theta_0$', r'$\alpha$'
        ]

    a = pymultinest.Analyzer(n_params=n_params, outputfiles_basename=prefix)
    s = a.get_stats()

    p = pymultinest.PlotMarginalModes(a)

    for i in range(1, n_params):
        #        plt.subplot(n_params, n_params, n_params * i + i + 1)
        #p.plot_marginal(i, ls='-', color='blue', linewidth=3)
        #p.plot_marginal(i, with_ellipses = True, dim2 = True, with_points = False, grid_points=50)

        for j in range(i):

            plt.subplot(n_params - 1, n_params - 1, (n_params - 1) * j + i)
            p.plot_conditional(i,
                               j,
                               with_ellipses=False,
                               with_points=True,
                               grid_points=30)

        plt.subplot(n_params - 1, n_params - 1, (n_params - 1) * (i - 1) + i)
        plt.xlabel(paramNames[i])
        plt.ylabel(paramNames[i - 1])

    plt.show()
Beispiel #4
0
def multinest(nu, D, Ninv, beam_mat, ndim, models_fit, label):

    import pymultinest
    import json

    if not os.path.exists("chains"): os.mkdir("chains")
    parameters = ["dust_beta", "dust_Td", "sync_beta"]
    n_params = len(parameters)

    def prior_multi(cube, ndim, nparams):
        cube[0] = 0 + 3 * cube[0]
        cube[1] = 5 + 95 * cube[1]
        cube[2] = -5 + 5 * cube[2]

    def loglike_multi(cube, ndim, nparams):
        dust_beta, dust_Td, sync_beta = cube[0], cube[1], cube[2]
        dust_params = np.array([dust_beta, dust_Td])
        sync_params = np.array([sync_beta])
        cmb_params = np.array([])
        (F_fg, F_cmb, F) = F_matrix(nu, dust_params, sync_params, cmb_params,
                                    models_fit)
        H = F_fg.T * Ninv * F_fg

        x_mat = np.linalg.inv(F.T * beam_mat.T * Ninv * beam_mat *
                              F) * F.T * beam_mat.T * Ninv * D  # Equation A3

        chi_square = (D - beam_mat * F * x_mat).T * Ninv * (
            D - beam_mat * F * x_mat)  # Equation A4

        return -chi_square - 0.5 * np.log(np.linalg.det(H))

    pymultinest.run(loglike_multi,
                    prior_multi,
                    n_params,
                    outputfiles_basename='chains/single_pixel_',
                    resume=False,
                    verbose=True,
                    n_live_points=1000,
                    importance_nested_sampling=False)
    a = pymultinest.Analyzer(n_params=n_params,
                             outputfiles_basename='chains/single_pixel_')
    s = a.get_stats()

    output = a.get_equal_weighted_posterior()
    outfile = 'test.out'
    pickle.dump(output, open(outfile, "wb"))

    # store name of parameters, always useful
    with open('%sparams.json' % a.outputfiles_basename, 'w') as f:
        json.dump(parameters, f, indent=2)
    # store derived stats
    with open('%sstats.json' % a.outputfiles_basename, mode='w') as f:
        json.dump(s, f, indent=2)
    print()
    print("-" * 30, 'ANALYSIS', "-" * 30)
    print("Global Evidence:\n\t%.15e +- %.15e" %
          (s['nested sampling global log-evidence'],
           s['nested sampling global log-evidence error']))

    # Plots
    p = pymultinest.PlotMarginalModes(a)
    plt.figure(figsize=(5 * n_params, 5 * n_params))

    for i in range(n_params):
        plt.subplot(n_params, n_params, n_params * i + i + 1)
        p.plot_marginal(i,
                        with_ellipses=True,
                        with_points=False,
                        grid_points=50)
        plt.ylabel("Probability")
        plt.xlabel(parameters[i])

        for j in range(i):
            plt.subplot(n_params, n_params, n_params * j + i + 1)
            p.plot_conditional(i,
                               j,
                               with_ellipses=False,
                               with_points=True,
                               grid_points=30)
            plt.xlabel(parameters[i])
            plt.ylabel(parameters[j])

    plt.savefig(
        "chains/single_pixel_marginals_multinest.pdf")  #, bbox_inches='tight')

    for i in range(n_params):
        outfile = '%s-mode-marginal-%d.pdf' % (a.outputfiles_basename, i)
        p.plot_modes_marginal(i, with_ellipses=True, with_points=False)
        plt.ylabel("Probability")
        plt.xlabel(parameters[i])
        plt.savefig(outfile, format='pdf', bbox_inches='tight')
        plt.close()

        outfile = '%s-mode-marginal-cumulative-%d.pdf' % (
            a.outputfiles_basename, i)
        p.plot_modes_marginal(i,
                              cumulative=True,
                              with_ellipses=True,
                              with_points=False)
        plt.ylabel("Cumulative probability")
        plt.xlabel(parameters[i])
        plt.savefig(outfile, format='pdf', bbox_inches='tight')
        plt.close()
Beispiel #5
0
                sampling_efficiency='model',
                n_live_points=500,
                outputfiles_basename='chains2/q_PL_twogal_redd_ssfr-')
#Analyse the results and plot the marginals
ana = pymultinest.Analyzer(
    n_params=n_params, outputfiles_basename='chains2/q_PL_twogal_redd_ssfr-')

plt.clf()

# Here we will plot all the marginals and whatnot, just to show off
# You may configure the format of the output here, or in matplotlibrc
# All pymultinest does is filling in the data of the plot.

# Copy and edit this file, and play with it.

p = pymultinest.PlotMarginalModes(ana)
plt.figure(figsize=(5 * n_params, 5 * n_params))
#plt.subplots_adjust(wspace=0, hspace=0)
for i in range(n_params):
    plt.subplot(n_params, n_params, n_params * i + i + 1)
    p.plot_marginal(i, with_ellipses=True, with_points=False, grid_points=50)
    plt.ylabel("Probability")
    plt.xlabel(parameters[i])

    for j in range(i):
        plt.subplot(n_params, n_params, n_params * j + i + 1)
        #plt.subplots_adjust(left=0, bottom=0, right=0, top=0, wspace=0, hspace=0)
        p.plot_conditional(i,
                           j,
                           with_ellipses=False,
                           with_points=True,
def dump():
    progress = pymultinest.ProgressPlotter(n_params = n_params, outputfiles_basename=dir_output+'chains/2-'); progress.start()
    threading.Timer(2, show, [dir_output+"chains/2-phys_live.points.pdf"]).start() # delayed opening
    # run MultiNest
    pymultinest.run(mc.multinest_call, mc.multinest_priors, n_params, importance_nested_sampling = False, resume = True,
                    verbose = True, sampling_efficiency = 'model', n_live_points = 1000, outputfiles_basename=dir_output+'chains/2-')
    # ok, done. Stop our progress watcher
    progress.stop()

    # lets analyse the results
    a = pymultinest.Analyzer(n_params = n_params, outputfiles_basename=dir_output+'chains/2-')
    s = a.get_stats()

    # store name of parameters, always useful
    with open('%sparams.json' % a.outputfiles_basename, 'w') as f:
        json.dump(parameters, f, indent=2)
    # store derived stats
    with open('%sstats.json' % a.outputfiles_basename, mode='w') as f:
        json.dump(s, f, indent=2)
    print()
    print("-" * 30, 'ANALYSIS', "-" * 30)
    print("Global Evidence:\n\t%.15e +- %.15e" % ( s['nested sampling global log-evidence'], s['nested sampling global log-evidence error'] ))

    import matplotlib.pyplot as plt
    plt.clf()


    # run MultiNest
    #pymultinest.run(mc.pymultinest_call, mc.pymultinest_priors, mc.ndim, outputfiles_basename=dir_output, resume = False, verbose = True)
    #json.dump(parameters, open(dir_output+'params.json', 'w')) # save parameter names

    # Here we will plot all the marginals and whatnot, just to show off
    # You may configure the format of the output here, or in matplotlibrc
    # All pymultinest does is filling in the data of the plot.

    # Copy and edit this file, and play with it.

    p = pymultinest.PlotMarginalModes(a)
    plt.figure(figsize=(5 * n_params, 5 * n_params))
    # plt.subplots_adjust(wspace=0, hspace=0)
    for i in range(n_params):
        plt.subplot(n_params, n_params, n_params * i + i + 1)
        p.plot_marginal(i, with_ellipses=True, with_points=False, grid_points=50)
        plt.ylabel("Probability")
        plt.xlabel(parameters[i])

        for j in range(i):
            plt.subplot(n_params, n_params, n_params * j + i + 1)
            # plt.subplots_adjust(left=0, bottom=0, right=0, top=0, wspace=0, hspace=0)
            p.plot_conditional(i, j, with_ellipses=False, with_points=True, grid_points=30)
            plt.xlabel(parameters[i])
            plt.ylabel(parameters[j])

    plt.savefig(dir_output+"chains/marginals_multinest.pdf")  # , bbox_inches='tight')
    show(dir_output+"chains/marginals_multinest.pdf")

    for i in range(n_params):
        outfile = '%s-mode-marginal-%d.pdf' % (a.outputfiles_basename, i)
        p.plot_modes_marginal(i, with_ellipses=True, with_points=False)
        plt.ylabel("Probability")
        plt.xlabel(parameters[i])
        plt.savefig(outfile, format='pdf', bbox_inches='tight')
        plt.close()

        outfile = '%s-mode-marginal-cumulative-%d.pdf' % (a.outputfiles_basename, i)
        p.plot_modes_marginal(i, cumulative=True, with_ellipses=True, with_points=False)
        plt.ylabel("Cumulative probability")
        plt.xlabel(parameters[i])
        plt.savefig(outfile, format='pdf', bbox_inches='tight')
        plt.close()

    print("Take a look at the pdf files in chains/")
Beispiel #7
0
    def analyze(self,
                outbase="output/test_",
                sampler=None,
                burnin_factor=0.5,
                resume=True):
        if self.backend == 'zeus':

            if not os.path.isfile(outbase + "zeus_chains.txt") or ~resume:
                if sampler is None:
                    raise ValueError
                print(
                    f" ==> Getting chains. thinning the chain and removing burn-in with factor {burnin_factor}"
                )
                chain = sampler.get_chain(flat=True,
                                          discard=burnin_factor,
                                          thin=10)
                np.savetxt(outbase + "zeus_chains.txt", chain)
            else:
                chain = np.loadtxt(outbase + "zeus_chains.txt")
            # Compute MAP estimate and 1-sigma quantiles
            olist = []
            bestlist = []
            for i in range(self.nparams):
                mcmc = np.percentile(chain[:, i], [16, 50, 84])
                olist.append(mcmc[1])
                bestlist.append(mcmc[1])
                q = np.diff(mcmc)
                olist.append(q[0])
                olist.append(q[1])
            self.write_line(outbase + "zeus_map.txt", np.array(olist))

            fig, axes = zeus.cornerplot(chain,
                                        labels=self.parameters,
                                        truth=[1, 0.75, 8],
                                        title_fmt='.4f')
            fig.savefig(
                f"{outbase}zeus_marginals_post.png")  #, bbox_inches='tight')

            return np.array(bestlist)

        elif self.backend == 'multinest':
            print(f"==> No burnin used with Multinest backend.")

            res = pmn.Analyzer(outputfiles_basename=outbase,
                               n_params=self.nparams)
            bestpar = res.get_best_fit()['parameters']
            stats = res.get_stats()['marginals']

            p = pmn.PlotMarginalModes(res)
            plt.figure(figsize=(5 * self.nparams, 5 * self.nparams))
            olist = []
            for i in range(self.nparams):
                median = stats[i]['median']
                onesigma = stats[i]['1sigma']
                low = median - onesigma[0]
                high = onesigma[1] - median
                olist.append(median)
                olist.append(stats[i]['sigma'])
                plt.subplot(self.nparams, self.nparams,
                            self.nparams * i + i + 1)
                p.plot_marginal(i,
                                with_ellipses=True,
                                with_points=False,
                                grid_points=50)

                plt.title(
                    f"${self.parameters[i]} = {stats[i]['median']:.4f}_{{-{low:.4f}}}^{{-{high:.4f}}}$"
                )
                plt.ylabel("Probability")
                plt.xlabel(self.parameters[i])

                for j in range(i):
                    plt.subplot(self.nparams, self.nparams,
                                self.nparams * j + i + 1)
                    #plt.subplots_adjust(left=0, bottom=0, right=0, top=0, wspace=0, hspace=0)
                    p.plot_conditional(i,
                                       j,
                                       with_ellipses=False,
                                       with_points=True,
                                       grid_points=30)
                    plt.xlabel(self.parameters[i])
                    plt.ylabel(self.parameters[j])
            self.write_line(outbase + "multinest_map.txt", np.array(olist))
            plt.savefig(f"{outbase}multinest_marginals_post.png"
                        )  #, bbox_inches='tight')
            return bestpar

        else:
            raise NotImplementedError
Beispiel #8
0
def run_mcmc(myloglike, myprior, nparams, parameters, **kwargs):
    import matplotlib.pyplot as plt
    outputfiles_basename = kwargs['outputfiles_basename']

    nrows = 2
    ncols = int(np.ceil(1.0 * nparams / nrows))
    fig, axL = plt.subplots(nrows=nrows,
                            ncols=ncols,
                            figsize=(20, 10),
                            sharey=True)
    axL = axL.flatten()
    for i in range(nparams):
        plt.sca(axL[i])
        plt.title(parameters[i])
        fig.set_tight_layout(True)
        plt.yscale('symlog', ythresh=0.05)
        plt.ylim(-1e10, -1)

    # we want to see some output while it is running
    progress = pymultinest.ProgressPlotter(
        n_params=nparams, outputfiles_basename=outputfiles_basename, axL=axL)

    progress.start()
    pdffn = "{}phys_live.points.png".format(outputfiles_basename)
    # delayed opening
    threading.Timer(10, show, [pdffn]).start()

    # run MultiNest
    pymultinest.run(myloglike, myprior, nparams, **kwargs)

    progress.stop()

    # lets analyse the results
    a = pymultinest.Analyzer(n_params=nparams,
                             outputfiles_basename=outputfiles_basename)
    s = a.get_stats()

    # store name of parameters, always useful
    with open('%sparams.json' % a.outputfiles_basename, 'w') as f:
        json.dump(parameters, f, indent=2)

    # store derived stats
    with open('%sstats.json' % a.outputfiles_basename, mode='w') as f:
        json.dump(s, f, indent=2)

    print()
    print("-" * 30, 'ANALYSIS', "-" * 30)
    print("Global Evidence:\n\t%.15e +- %.15e" %
          (s['nested sampling global log-evidence'],
           s['nested sampling global log-evidence error']))

    plt.clf()
    # Here we will plot all the marginals and whatnot, just to show off
    # You may configure the format of the output here, or in matplotlibrc
    # All pymultinest does is filling in the data of the plot.
    # Copy and edit this file, and play with it.
    p = pymultinest.PlotMarginalModes(a)
    plt.figure(figsize=(5 * nparams, 5 * nparams))
    #plt.subplots_adjust(wspace=0, hspace=0)
    for i in range(nparams):
        plt.subplot(nparams, nparams, nparams * i + i + 1)
        p.plot_marginal(i,
                        with_ellipses=True,
                        with_points=False,
                        grid_points=50)
        plt.ylabel("Probability")
        plt.xlabel(parameters[i])

        for j in range(i):
            plt.subplot(nparams, nparams, nparams * j + i + 1)
            p.plot_conditional(i,
                               j,
                               with_ellipses=False,
                               with_points=True,
                               grid_points=30)
            plt.xlabel(parameters[i])
            plt.ylabel(parameters[j])

    plt.savefig("chains/marginals_multinest.pdf")  #, bbox_inches='tight')
    show("chains/marginals_multinest.pdf")

    for i in range(nparams):
        outfile = '%s-mode-marginal-%d.pdf' % (a.outputfiles_basename, i)
        p.plot_modes_marginal(i, with_ellipses=True, with_points=False)
        plt.ylabel("Probability")
        plt.xlabel(parameters[i])
        plt.savefig(outfile, format='pdf', bbox_inches='tight')
        plt.close()

        outfile = '%s-mode-marginal-cumulative-%d.pdf' % (
            a.outputfiles_basename, i)
        p.plot_modes_marginal(i,
                              cumulative=True,
                              with_ellipses=True,
                              with_points=False)
        plt.ylabel("Cumulative probability")
        plt.xlabel(parameters[i])
        plt.savefig(outfile, format='pdf', bbox_inches='tight')
        plt.close()

    print("Take a look at the pdf files in chains/")
print("Global Evidence:\t%.3f +- %.3f" %
      (s_SEM['nested sampling global log-evidence'],
       s_SEM['nested sampling global log-evidence error']))

# In[ ]:

import matplotlib.pyplot as plt
plt.clf()

# Here we will plot all the marginals and whatnot, just to show off
# You may configure the format of the output here, or in matplotlibrc
# All pymultinest does is filling in the data of the plot.

# Copy and edit this file, and play with it.

p_SEM = pymultinest.PlotMarginalModes(a_SEM)
plt.figure(figsize=(5 * n_params_SEM, 5 * n_params_SEM))
#plt.subplots_adjust(wspace=0, hspace=0)
for i in range(n_params_SEM):
    plt.subplot(n_params_SEM, n_params_SEM, n_params_SEM * i + i + 1)
    p_SEM.plot_marginal(i,
                        with_ellipses=False,
                        with_points=False,
                        grid_points=50)
    plt.ylabel("Probability")
    plt.xlabel(parameters_SEM[i])

    for j in range(i):
        plt.subplot(n_params_SEM, n_params_SEM, n_params_SEM * j + i + 1)
        #plt.subplots_adjust(left=0, bottom=0, right=0, top=0, wspace=0, hspace=0)
        p_SEM.plot_conditional(i,
Beispiel #10
0
    def run(self):
        """
        Executes the inference
        """
        if self.prepare():
            # Run the inference
            pmn = pymultinest.run(self.loglike,
                                  self.prior,
                                  n_dims=sum(self.pstep > 0),
                                  outputfiles_basename=os.path.join(
                                      self.outputdir, self.fprefix),
                                  n_live_points=self.nlive,
                                  max_iter=self.niter,
                                  evidence_tolerance=self.dlogz,
                                  resume=self.resume)
            # Analyze the output
            a = pymultinest.Analyzer(n_params=len(self.pstep),
                                     outputfiles_basename=os.path.join(
                                         self.outputdir, self.fprefix))
            s = a.get_stats()
            self.bestp = a.get_best_fit()['parameters']
            self.outp = a.get_equal_weighted_posterior()[:, :-1].T
            # Update quantiles
            if self.kll is not None:
                for i in range(self.outp.shape[-1]):
                    self.kll.update(self.model(self.outp[:, i], fullout=True))

            if self.verb:
                print("Global Evidence:\n\t%.15e +- %.15e" % \
                      (s['nested sampling global log-evidence'],
                       s['nested sampling global log-evidence error']))

            # PyMultiNest plots
            n_params = self.outp.shape[0]
            if self.pnames is not None:
                parameters = self.pnames[self.pstep > 0]
            p = pymultinest.PlotMarginalModes(a)
            plt.figure(figsize=(5 * n_params, 5 * n_params))
            for i in range(n_params):
                plt.subplot(n_params, n_params, n_params * i + i + 1)
                p.plot_marginal(i,
                                with_ellipses=True,
                                with_points=False,
                                grid_points=50)
                plt.ylabel("Probability")
                plt.xlabel(parameters[i])

                for j in range(i):
                    plt.subplot(n_params, n_params, n_params * j + i + 1)
                    p.plot_conditional(i,
                                       j,
                                       with_ellipses=False,
                                       with_points=True,
                                       grid_points=30)
                    plt.xlabel(parameters[i])
                    plt.ylabel(parameters[j])

            plt.savefig(os.path.join(
                self.outputdir, ''.join(['marginals_multinest', self.fext])),
                        bbox_inches='tight')
            plt.close()

            # These are optional since the above contains the same info
            for i in range(n_params):
                p.plot_modes_marginal(i, with_ellipses=True, with_points=False)
                plt.ylabel("Probability")
                plt.xlabel(parameters[i])
                plt.savefig(''.join([
                    a.outputfiles_basename, 'mode-marginal-',
                    str(i), self.fext
                ]),
                            bbox_inches='tight')
                plt.close()

                p.plot_modes_marginal(i,
                                      cumulative=True,
                                      with_ellipses=True,
                                      with_points=False)
                plt.ylabel("Cumulative probability")
                plt.xlabel(parameters[i])
                plt.savefig(''.join([
                    a.outputfiles_basename, 'mode-marginal-cumulative-',
                    str(i), self.fext
                ]),
                            bbox_inches='tight')
                plt.close()

            # Save posterior and bestfit params
            if self.fsavefile is not None:
                np.save(self.fsavefile, self.outp)
            if self.fbestp is not None:
                np.save(self.fbestp, self.bestp)
        else:
            if self.verb:
                print("Sampler is not fully prepared to run. " + \
                      "Correct the above errors and try again.")
Beispiel #11
0
def run_multinest(**config):
	n_params = config['ndim']
	output_basename = config['output_basename']
	# we use a flat prior
        def myprior(cube, ndim, nparams):
                pass
	loglikelihood = config['loglikelihood']	
	def myloglike(cube, ndim, nparams):
		try:
			l = loglikelihood([cube[i] for i in range(ndim)])
		except Exception as e:
			print 'ERROR:', type(e), e
			sys.exit(-127)
		return l
	nlive_points = config['nlive_points']
	mn_args = dict(
		importance_nested_sampling = config['importance_nested_sampling'],
		outputfiles_basename = output_basename + 'out_',
		resume = False,
		verbose = True,
		n_params = n_params,
		n_live_points = nlive_points,
		sampling_efficiency = 'model',
		const_efficiency_mode = False,
		evidence_tolerance = 0.5,
		seed = config['seed'],
		max_iter = 2000000,
	)
	starttime = time.time()
	pymultinest.run(myloglike, myprior, mn_args['n_params'], **mn_args)
	duration = time.time() - starttime
	with file('%sparams.json' % mn_args['outputfiles_basename'], 'w') as f:
		parameters = ['%d' % (i+1) for i in range(mn_args['n_params'])]
		json.dump(parameters, f, indent=2)
	a = pymultinest.Analyzer(n_params = mn_args['n_params'],
		outputfiles_basename = mn_args['outputfiles_basename'])
	s = a.get_stats()
	results = dict(
		Z_computed = s['global evidence'],
        	Z_computed_err = s['global evidence error'],
        	duration = duration,
        )
        # store marginal plot for debugging
	if plot and config['seed'] == 0:
		import matplotlib.pyplot as plt
		p = pymultinest.PlotMarginalModes(a)
		plt.figure(figsize=(5*n_params, 5*n_params))
		for i in range(n_params):
			plt.subplot(n_params, n_params, n_params * i + i + 1)
			p.plot_marginal(i, with_ellipses = False, with_points = False, grid_points=50)
			plt.ylabel("Probability")
			plt.xlabel(parameters[i])
		
			for j in range(i):
				plt.subplot(n_params, n_params, n_params * j + i + 1)
				p.plot_conditional(i, j, with_ellipses = False, with_points = False, grid_points=30)
				plt.xlabel(parameters[i])
				plt.ylabel(parameters[j])
				plt.ylim(0, 1)
				plt.xlim(0, 1)

		plt.savefig('%smarg.png' % output_basename, bbox_inches='tight')
		plt.close()
	
	if not keep_results:
		# destroy the evidence (to save disk space)
		for f in glob.iglob(mn_args['outputfiles_basename'] + "*"):
			print 'deleting %s' % f
			os.remove(f)
	
        return results
Beispiel #12
0
 def PlotMarginalModes(self):
     """
     Generate the PlotMarginalModes object.
     """
     return pymultinest.PlotMarginalModes(self.analyzer)
Beispiel #13
0
def use_pymultinest(psf,
                    flux_ld,
                    flux_hd,
                    vel,
                    errvel,
                    params,
                    vel_model,
                    path,
                    rank=0,
                    slope=0,
                    quiet=False,
                    whd='',
                    incfix=False,
                    xfix=False,
                    yfix=False,
                    nbp=19000):
    """

    :param PSF psf: 
    :param Image flux_ld: 
    :param Image flux_hd: 
    :param Image vel: 
    :param Image errvel: 
    :param Union[ndarray, Iterable] params: 
    :param vel_model: 
    :param float slope: 
    :param int quiet: 
    :return: 
    """

    gal, xcen, ycen, pos_angl, incl, syst_vel, vmax, charac_rad, sig0, fwhm, psfz, smooth = params

    model = Model2D(flux_ld, flux_hd, sig0, slope=slope)

    def prior(cube, ndim, nparams):
        if xfix:
            cube[0] = cube[
                0] * 2 - 1 + xcen  # prior between xcen - 1 ans xcen + 1
        else:
            cube[0] = cube[0] * 10 - 5 + xcen

        if yfix:
            cube[1] = cube[1] * 2 - 1 + ycen
        else:
            cube[1] = cube[
                1] * 10 - 5 + ycen  # prior between ycen - 5 ans ycen + 5

        if incfix:
            cube[3] = cube[
                3] * 2 + incl - 1  # incl between incl - 1 and incl  + 1 degree
        else:
            cube[3] = cube[3] * 80 + 5  # incl between 5 and 85 degree

        cube[2] = cube[2] * 360 - 180  # pos angl between -180 and 180 degree
        cube[4] = cube[4] * 200 - 100  # sys vel between -500 and 500km/s
        cube[5] = cube[5] * 500  # vmax between 0 and 500km/s
        cube[6] = cube[6] * 14 + 1  # charac rad between 1 and 15

    def loglike(cube, ndim, nparams):

        model.set_parameters(cube[0], cube[1], cube[2], cube[3], cube[4],
                             cube[5], cube[6], flux_hd)
        model.velocity_map(psf, flux_ld, flux_hd, vel_model)

        chi2 = -(vel.data[flux_ld.mask] - model.vel_map[flux_ld.mask])**2 / (
            2 * errvel.data[flux_ld.mask]**2)

        return np.sum(chi2)

    params = ['xcen', 'ycen', 'pa', 'incl', 'vs', 'vm', 'rd']
    n_params = len(params)

    if rank == 0:
        dirname = 'multinest'
        if incfix or xfix or yfix:
            dirname += '_'
        if xfix:
            dirname += 'x'
        if yfix:
            dirname += 'y'
        if incfix:
            dirname += 'i'
        if os.path.isdir(path + dirname) is False:
            os.makedirs(path + dirname)

    if rank == 0:
        t1 = time.time()

    pymultinest.run(loglike,
                    prior,
                    n_params,
                    outputfiles_basename=path + '/multinest/output' + whd +
                    '_',
                    resume=False,
                    verbose=quiet,
                    max_iter=nbp,
                    n_live_points=1000)

    if rank == 0:

        t2 = time.time()

        print('\n fit done in: {:6.2f} s \n'.format(t2 - t1))

        output = pymultinest.Analyzer(n_params=n_params,
                                      outputfiles_basename=path +
                                      '/multinest/output' + whd + '_')
        stats = output.get_mode_stats()

        bestfit = stats['modes'][0]['maximum']
        model.set_parameters(*bestfit, flux_hd)

        print('', '-' * 81)
        print(
            '{0:^{width}}{1:^{width}}{2:^{width}}{3:^{width}}{4:^{width}}{5:^{width}}'
            '{6:^{width}}'.format('xcen',
                                  'ycen',
                                  'pa',
                                  'incl',
                                  'vs',
                                  'vm',
                                  'rd',
                                  width=12))
        print(
            '{0:^{width}.{prec}f}{1:^{width}.{prec}f}{2:^{width}.{prec}f}{3:^{width}.{prec}f}'
            '{4:^{width}.{prec}f}{5:^{width}.{prec}f}{6:^{width}.{prec}f}'.
            format(*bestfit, width=12, prec=6))
        print(
            '{0:^{width}.{prec}f}{1:^{width}.{prec}f}{2:^{width}.{prec}f}{3:^{width}.{prec}f}'
            '{4:^{width}.{prec}f}{5:^{width}.{prec}f}{6:^{width}.{prec}f}'.
            format(*stats['modes'][0]['sigma'], width=12, prec=6))
        print('', '-' * 81)

        if type(flux_hd) is ImageOverSamp:
            tools.write_fits(0, 0, 0, 0, 0, 0, 0, 0, flux_hd.data,
                             path + '/multinest/flux_hd_interpol')

        model.set_parameters(*bestfit, flux_hd)
        model.velocity_map(psf, flux_ld, flux_hd, vel_model)

        tools.write_fits(*bestfit,
                         sig0,
                         model.vel_map,
                         path + '/multinest/modv' + whd,
                         mask=flux_ld.mask)
        tools.write_fits(*bestfit, sig0, model.vel_map,
                         path + '/multinest/modv_full' + whd)
        tools.write_fits(*bestfit,
                         sig0,
                         vel.data - model.vel_map,
                         path + '/multinest/resv' + whd,
                         mask=flux_ld.mask)
        tools.write_fits(*bestfit,
                         sig0,
                         model.vel_map_hd,
                         path + '/multinest/modv_hd' + whd,
                         oversample=1 / flux_hd.oversample)
        model.vel_disp_map(flux_ld, flux_hd, psf)
        tools.write_fits(*bestfit,
                         sig0,
                         model.vel_disp,
                         path + '/mpfit/modd' + whd,
                         mask=flux_ld.mask)
        ascii.write(np.array([bestfit, stats['modes'][0]['sigma']]),
                    path + '/multinest/params_fit' + whd + '.txt',
                    names=['x', 'y', 'pa', 'incl', 'vs', 'vm', 'rd'],
                    format='fixed_width',
                    delimiter=None,
                    formats={
                        'x': '%.6f',
                        'y': '%.6f',
                        'pa': '%.6f',
                        'incl': '%.6f',
                        'vs': '%.6f',
                        'vm': '%.6f',
                        'rd': '%.6f'
                    },
                    overwrite=True)

        all_stats = output.get_stats()
        plot = True
        for i in range(n_params):
            if all_stats['marginals'][i]['sigma'] == 0:
                plot = False

        if plot:
            parameters = ['x', 'y', 'pa', 'incl', 'vs', 'vm', 'rd']
            p = pymultinest.PlotMarginalModes(output)
            plt.figure(figsize=(5 * n_params, 5 * n_params))
            # plt.subplots_adjust(wspace=0, hspace=0)
            for i in range(n_params):
                plt.subplot(n_params, n_params, n_params * i + i + 1)
                p.plot_marginal(i,
                                with_ellipses=False,
                                with_points=False,
                                grid_points=50)
                plt.ylabel("Probability")
                plt.xlabel(parameters[i])

                for j in range(i):
                    plt.subplot(n_params, n_params, n_params * j + i + 1)
                    # plt.subplots_adjust(left=0, bottom=0, right=0, top=0, wspace=0, hspace=0)
                    p.plot_conditional(i,
                                       j,
                                       with_ellipses=False,
                                       with_points=True,
                                       grid_points=30)
                    plt.xlabel(parameters[i])
                    plt.ylabel(parameters[j])

            plt.savefig(path + '/multinest/proba' + whd + '.pdf')
        else:
            print(
                '\n There is impossible to plot the statistics, one or more parameters has a sigma null \n'
            )