Exemplo n.º 1
0
 def ProgressPlotter(self, *args, **kwargs):
     """
     Generate the ProgressPlotter object which is the son of ProgressWatcher
     whose parameters are:
         n_params,
         interval_ms=200,
         outputfiles_basename="chains/1-"
     """
     return pymultinest.ProgressPlotter(self.__dim, *args, **kwargs)
    # Normal Log Likelihood
    modelNow = model(cube)(xdata)
    return -0.5*((modelNow - ydata)**2. / yuncs**2.).sum()


# In[ ]:

if not os.path.exists("chains"): os.mkdir("chains")

# number of dimensions our problem has
# parameters = ["x", "y"]
n_params = len(parameters)

plt.figure(figsize=(5*n_params, 5*n_params))
# we want to see some output while it is running
progress = pymultinest.ProgressPlotter(n_params = n_params, outputfiles_basename='chains/2-'); progress.start()
# threading.Timer(2, show, ["chains/2-phys_live.points.pdf"]).start() # delayed opening
# run MultiNest
pymultinest.run(myloglike, myprior, n_params, importance_nested_sampling = False, resume = False, verbose = True,             sampling_efficiency = 'model', n_live_points = 1000, outputfiles_basename='chains/2-')

# ok, done. Stop our progress watcher
progress.stop()

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


# In[ ]:

import json
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/")
Exemplo n.º 4
0
	#print "python cube after", [cube[i] for i in range(ndim)]

def myloglike(cube, ndim, nparams):
	chi = 1.
	#print "cube", [cube[i] for i in range(ndim)], cube
	for i in range(ndim):
		chi *= math.cos(cube[i] / 2.)
	#print "returning", math.pow(2. + chi, 5)
	return math.pow(2. + chi, 5)

# number of dimensions our problem has
parameters = ["x", "y"]
n_params = len(parameters)

# we want to see some output while it is running
progress = pymultinest.ProgressPlotter(n_params = n_params); progress.start()
threading.Timer(2, show, ["chains/1-phys_live.points.pdf"]).start() # delayed opening
# run MultiNest
pymultinest.run(myloglike, myprior, n_params, importance_nested_sampling = False, resume = True, verbose = True, sampling_efficiency = 'model', n_live_points = 1000)
# ok, done. Stop our progress watcher
progress.stop()

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

import json
# store name of parameters, always useful
with file('%sparams.json' % a.outputfiles_basename, 'w') as f:
	json.dump(parameters, f, indent=2)
# store derived stats
Exemplo n.º 5
0
    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$PWD/lib
    export LD_PRELOAD=/usr/lib/x86_64-linux-gnu/libgfortran.so.3
    export LD_PRELOAD=/opt/local/lib/openmpi//lib/libmpi.so:$LD_PRELOAD
    mpirun -np 4 python run_PyPolyChord.py

'''

# number of dimensions our problem has
n_params = mc.ndim
print '--->', mc.pam_names

mc.results_resumen(np.ones(n_params))
parameters = mc.pam_names

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,
                resume=True,
                sampling_efficiency='parameter',
                evidence_tolerance=0.2,
                max_iter=0,
                verbose=True,
                n_live_points=1000,
Exemplo n.º 6
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/")
if not os.path.exists("chains"): os.mkdir("chains")

# number of dimensions our problem has
# parameters = ["x", "y"]
n_params_SEM = len(parameters_SEM)

planetName = 'HAT38'
visitName = 'visit1'
modelName = 'single_exponential_model'
outputfiles_basename = 'chains/' + planetName + '-' + visitName + '-' + modelName + '-'

start = time()

plt.figure(figsize=(5 * n_params_SEM, 5 * n_params_SEM))
# we want to see some output while it is running
progress = pymultinest.ProgressPlotter(
    n_params=n_params_SEM, outputfiles_basename=outputfiles_basename)
progress.start()
# threading.Timer(2, show, ["chains/2-phys_live.points.pdf"]).start() # delayed opening
# run MultiNest
pymultinest.run(myloglike_SEM,
                myprior_SEM,
                n_params_SEM,
                importance_nested_sampling=False,
                resume=False,
                verbose=True,
                sampling_efficiency='model',
                n_live_points=1000,
                outputfiles_basename=outputfiles_basename)

# ok, done. Stop our progress watcher
progress.stop()