def plot(a, parameters): import matplotlib.pyplot as plt p = pymultinest.PlotMarginal(a) n_params = len(parameters) values = a.get_equal_weighted_posterior() s = a.get_stats() assert n_params == len(s['marginals']) prefix = a.outputfiles_basename 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) plot_marg(parameters, values, i, s, p) for j in range(i): plt.subplot(n_params, n_params, n_params * j + i + 1) p.plot_conditional(i, j, bins=20, cmap=plt.cm.gray_r) plt.xlabel(parameters[i]) plt.ylabel(parameters[j]) #plt.savefig('cond_%s_%s.pdf' % (params[i], params[j]), bbox_tight=True) #plt.close() plt.savefig(prefix + 'cond.pdf') plt.close() plt.figure(figsize=(4 * 4, 2 * math.ceil(n_params / 4.))) for i in range(n_params): plt.subplot(math.ceil(n_params / 4.), 4, i + 1) plot_marg(parameters, values, i, s, p) plt.savefig(prefix + 'marg.pdf', bbox_inches='tight') plt.close()
sys.stderr.write("""SYNOPSIS: %s <output-root> output-root: Where the output of a MultiNest run has been written to. Example: chains/1- %s""" % (sys.argv[0], __doc__)) sys.exit(1) prefix = sys.argv[1] parameters = json.load(file(prefix + 'params.json')) n_params = len(parameters) a = pymultinest.Analyzer(n_params=n_params, outputfiles_basename=prefix) s = a.get_stats() p = pymultinest.PlotMarginal(a) values = a.get_equal_weighted_posterior() assert n_params == len(s['marginals']) modes = s['modes'] dim2 = os.environ.get('D', '1' if n_params > 20 else '2') == '2' nbins = 100 if n_params < 3 else 20 if dim2: plt.figure(figsize=(5 * n_params, 5 * n_params)) for i in range(n_params): plt.subplot(n_params, n_params, i + 1) plt.xlabel(parameters[i]) m = s['marginals'][i] plt.xlim(m['5sigma'])
def marginal_plots(analyzer, d=None): """ Create marginal plots * analyzer: A instance of pymultinest.Analyzer * d: if more than 20 dimensions, by default only 1d marginal distributions are plotted. set d=2 if you want to force a 2d matrix plot """ prefix = analyzer.outputfiles_basename n_params = analyzer.n_params parameters = json.load(open(prefix + 'params.json')) a = analyzer s = a.get_stats() p = pymultinest.PlotMarginal(a) values = a.get_equal_weighted_posterior() assert n_params == len(s['marginals']) modes = s['modes'] dim2 = ((1 if n_params > 20 else 2) if d is None else d) == 2 if dim2: plt.figure(figsize=(5 * n_params, 5 * n_params)) for i in range(n_params): plt.subplot(n_params, n_params, i + 1) plt.xlabel(parameters[i]) m = s['marginals'][i] plt.xlim(m['5sigma']) oldax = plt.gca() x, w, patches = oldax.hist(values[:, i], bins=20, edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2) oldax.set_ylim(0, x.max()) newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False) p.plot_marginal(i, ls='-', color='blue', linewidth=3) newax.set_ylim(0, 1) ylim = newax.get_ylim() y = ylim[0] + 0.05 * (ylim[1] - ylim[0]) center = m['median'] low1, high1 = m['1sigma'] #print center, low1, high1 newax.errorbar(x=center, y=y, xerr=numpy.transpose( [[center - low1, high1 - center]]), color='blue', linewidth=2, marker='s') oldax.set_yticks([]) #newax.set_yticks([]) newax.set_ylabel("Probability") ylim = oldax.get_ylim() newax.set_xlim(m['5sigma']) oldax.set_xlim(m['5sigma']) #plt.close() for j in range(i): plt.subplot(n_params, n_params, n_params * (j + 1) + i + 1) p.plot_conditional(i, j, bins=20, cmap=plt.cm.gray_r) for m in modes: plt.errorbar(x=m['mean'][i], y=m['mean'][j], xerr=m['sigma'][i], yerr=m['sigma'][j]) plt.xlabel(parameters[i]) plt.ylabel(parameters[j]) plt.xlim(s['marginals'][i]['5sigma']) plt.ylim(s['marginals'][j]['5sigma']) #plt.savefig('cond_%s_%s.pdf' % (params[i], params[j]), bbox_tight=True) #plt.close() plt.savefig(prefix + 'marg.pdf') plt.savefig(prefix + 'marg.png') plt.close() else: from matplotlib.backends.backend_pdf import PdfPages print('1dimensional only. Set the D environment variable D=2 to force') print('2d marginal plots.') pp = PdfPages(prefix + 'marg1d.pdf') for i in range(n_params): plt.figure(figsize=(5, 5)) plt.xlabel(parameters[i]) m = s['marginals'][i] plt.xlim(m['5sigma']) oldax = plt.gca() x, w, patches = oldax.hist(values[:, i], bins=20, edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2) oldax.set_ylim(0, x.max()) newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False) p.plot_marginal(i, ls='-', color='blue', linewidth=3) newax.set_ylim(0, 1) ylim = newax.get_ylim() y = ylim[0] + 0.05 * (ylim[1] - ylim[0]) center = m['median'] low1, high1 = m['1sigma'] print(center, low1, high1) newax.errorbar(x=center, y=y, xerr=numpy.transpose( [[center - low1, high1 - center]]), color='blue', linewidth=2, marker='s') oldax.set_yticks([]) newax.set_ylabel("Probability") ylim = oldax.get_ylim() newax.set_xlim(m['5sigma']) oldax.set_xlim(m['5sigma']) plt.savefig(pp, format='pdf', bbox_inches='tight') plt.close() pp.close()
def mkplots(self): # run to make plots of the resulting posteriors. Modified from marginal_plots.py # from pymultinest. Produces basename+marg.pdf and basename+marge.png files prefix = self.basename parameters = json.load(file(prefix + 'params.json')) n_params = len(parameters) a = pymultinest.Analyzer(n_params=n_params, outputfiles_basename=prefix) s = a.get_stats() p = pymultinest.PlotMarginal(a) try: values = a.get_equal_weighted_posterior() except IOError as e: print 'Unable to open: %s' % e return assert n_params == len(s['marginals']) modes = s['modes'] dim2 = os.environ.get('D', '1' if n_params > 20 else '2') == '2' nbins = 100 if n_params < 3 else 20 if dim2: plt.figure(figsize=(5.1 * n_params, 5 * n_params)) for i in range(n_params): plt.subplot(n_params, n_params, i + 1) plt.xlabel(parameters[i]) m = s['marginals'][i] plt.xlim(m['5sigma']) oldax = plt.gca() x, w, patches = oldax.hist(values[:, i], bins=nbins, edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2) oldax.set_ylim(0, x.max()) newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False) p.plot_marginal(i, ls='-', color='blue', linewidth=3) newax.set_ylim(0, 1) ylim = newax.get_ylim() y = ylim[0] + 0.05 * (ylim[1] - ylim[0]) center = m['median'] low1, high1 = m['1sigma'] print center, low1, high1 newax.errorbar(x=center, y=y, xerr=np.transpose( [[center - low1, high1 - center]]), color='blue', linewidth=2, marker='s') oldax.set_yticks([]) #newax.set_yticks([]) newax.set_ylabel("Probability") ylim = oldax.get_ylim() newax.set_xlim(m['5sigma']) oldax.set_xlim(m['5sigma']) #plt.close() for j in range(i): plt.subplot(n_params, n_params, n_params * (j + 1) + i + 1) p.plot_conditional(i, j, bins=20, cmap=plt.cm.gray_r) for m in modes: plt.errorbar(x=m['mean'][i], y=m['mean'][j], xerr=m['sigma'][i], yerr=m['sigma'][j]) ax = plt.gca() if j == i - 1: plt.xlabel(parameters[i]) plt.ylabel(parameters[j]) [l.set_rotation(45) for l in ax.get_xticklabels()] else: ax.set_xticklabels([]) ax.set_yticklabels([]) plt.xlim([ m['mean'][i] - 5 * m['sigma'][i], m['mean'][i] + 5 * m['sigma'][i] ]) plt.ylim([ m['mean'][j] - 5 * m['sigma'][j], m['mean'][j] + 5 * m['sigma'][j] ]) #plt.savefig('cond_%s_%s.pdf' % (params[i], params[j]), bbox_tight=True) #plt.close() plt.tight_layout() plt.savefig(prefix + 'marg.pdf') plt.savefig(prefix + 'marg.png') plt.close() else: from matplotlib.backends.backend_pdf import PdfPages print '1dimensional only. Set the D environment variable D=2 to force' print '2d marginal plots.' pp = PdfPages(prefix + 'marg1d.pdf') for i in range(n_params): plt.figure(figsize=(5, 5)) plt.xlabel(parameters[i]) m = s['marginals'][i] plt.xlim(m['5sigma']) oldax = plt.gca() x, w, patches = oldax.hist(values[:, i], bins=20, edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2) oldax.set_ylim(0, x.max()) newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False) p.plot_marginal(i, ls='-', color='blue', linewidth=3) newax.set_ylim(0, 1) ylim = newax.get_ylim() y = ylim[0] + 0.05 * (ylim[1] - ylim[0]) center = m['median'] low1, high1 = m['1sigma'] print center, low1, high1 newax.errorbar(x=center, y=y, xerr=np.transpose( [[center - low1, high1 - center]]), color='blue', linewidth=2, marker='s') oldax.set_yticks([]) newax.set_ylabel("Probability") ylim = oldax.get_ylim() newax.set_xlim(m['5sigma']) oldax.set_xlim(m['5sigma']) plt.savefig(pp, format='pdf', bbox_inches='tight') plt.close() pp.close()
def plot2D(a, parameters, outputDirectory, outputPrefix, nbins=20): ''' Helper function for plotting 2D distributions from PyMultiNest. The arguments are: a - A PyMultiNest Analyzer object. parameters - A list containing the names of all parameters. outputDirectory - The directory in which to place output files. outputPrefix - The prefix for all output file names. nbins - The number of bins to use when plotting. Default is 20. There is no return value, as all output is written to files. ''' prefix = outputDirectory + '/' + outputPrefix n_params = len(parameters) p = pymultinest.PlotMarginal(a) values = a.get_equal_weighted_posterior() s = a.get_stats() modes = s['modes'] plt.figure(figsize=(2.5 * n_params, 2.5 * n_params)) for i in range(n_params): plt.subplot(n_params, n_params, i + 1) plt.xlabel(parameters[i]) m = s['marginals'][i] plt.xlim(m['5sigma']) oldax = plt.gca() x, w, patches = oldax.hist(values[:, i], bins=nbins, edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2) oldax.set_ylim(0, x.max()) newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False) p.plot_marginal(i, ls='-', color='blue', linewidth=3) newax.set_ylim(0, 1) ylim = newax.get_ylim() y = ylim[0] + 0.05 * (ylim[1] - ylim[0]) center = m['median'] low1, high1 = m['1sigma'] #print(center, low1, high1) newax.errorbar(x=center, y=y, xerr=np.transpose([[center - low1, high1 - center]]), color='blue', linewidth=2, marker='s') oldax.set_yticks([]) #newax.set_yticks([]) newax.set_ylabel("Probability") ylim = oldax.get_ylim() newax.set_xlim(m['5sigma']) oldax.set_xlim(m['5sigma']) #plt.close() for j in range(i): plt.subplot(n_params, n_params, n_params * (j + 1) + i + 1) p.plot_conditional(i, j, bins=20, cmap=plt.cm.gray_r) for m in modes: plt.errorbar(x=m['mean'][i], y=m['mean'][j], xerr=m['sigma'][i], yerr=m['sigma'][j]) plt.xlabel(parameters[i]) plt.ylabel(parameters[j]) #plt.savefig('cond_%s_%s.pdf' % (params[i], params[j]), bbox_tight=True) #plt.close() plt.tight_layout(rect=[0.07, 0.03, 0.97, 0.97], pad=0.2) plt.savefig(prefix + 'marg.pdf') plt.savefig(prefix + 'marg.png') plt.close()
def plot1D(a, parameters, outputDirectory, outputPrefix): ''' Helper function for plotting 1D distributions from PyMultiNest. The arguments are: a - A PyMultiNest Analyzer object. parameters - A list containing the names of all parameters. outputDirectory - The directory in which to place output files. outputPrefix - The prefix for all output file names. There is no return value, as all output is written to files. ''' prefix = outputDirectory + '/' + outputPrefix n_params = len(parameters) p = pymultinest.PlotMarginal(a) values = a.get_equal_weighted_posterior() s = a.get_stats() modes = s['modes'] pp = PdfPages(prefix + 'marg1d.pdf') for i in range(n_params): plt.figure(figsize=(3, 3)) plt.xlabel(parameters[i]) plt.locator_params(nbins=5) m = s['marginals'][i] iqr = m['q99%'] - m['q01%'] xlim = m['q01%'] - 0.3 * iqr, m['q99%'] + 0.3 * iqr #xlim = m['5sigma'] plt.xlim(xlim) oldax = plt.gca() x, w, patches = oldax.hist(values[:, i], bins=np.linspace(xlim[0], xlim[1], 20), edgecolor='grey', color='grey', histtype='stepfilled', alpha=0.2) oldax.set_ylim(0, x.max()) newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False) p.plot_marginal(i, ls='-', color='blue', linewidth=3) newax.set_ylim(0, 1) ylim = newax.get_ylim() y = ylim[0] + 0.05 * (ylim[1] - ylim[0]) center = m['median'] low1, high1 = m['1sigma'] #print center, low1, high1 newax.errorbar(x=center, y=y, xerr=np.transpose([[center - low1, high1 - center]]), color='blue', linewidth=2, marker='s') oldax.set_yticks([]) newax.set_ylabel("Probability") ylim = oldax.get_ylim() newax.set_xlim(xlim) oldax.set_xlim(xlim) plt.savefig(pp, format='pdf', bbox_inches='tight') plt.close() pp.close()
def marginals(prefix, params): print('model "%s"' % prefix) parameters = json.load(open(prefix + 'params.json')) n_params = len(parameters) # Get posterior data a = pymultinest.Analyzer(n_params = n_params, outputfiles_basename = prefix) s = a.get_stats() json.dump(s, open(prefix + 'stats.json', 'w'), indent=4) # Print posterior data print(' marginal likelihood:') print(' ln Z = %.1f +- %.1f' % (s['global evidence'], s['global evidence error'])) print(' parameters:') # Loop across parameters, obtain median and std.dev for p, m in zip(parameters, s['marginals']): lo, hi = m['1sigma'] med = m['median'] sigma = (hi - lo) / 2 i = max(0, int(-numpy.floor(numpy.log10(sigma))) + 1) fmt = '%%.%df' % i fmts = '\t'.join([' %-15s' + fmt + " +- " + fmt]) print(fmts % (p, med, sigma)) # Initialize PlotMarginal object print('creating marginal plot ...') p = pymultinest.PlotMarginal(a) # Get posterior and mode info values = a.get_equal_weighted_posterior() assert n_params == len(s['marginals']) modes = s['modes'] # Set $D = 1 if more than 20 parameters, 2 otherwise dim2 = os.environ.get('D', '1' if n_params > 20 else '2') == '2' nbins = 100 if n_params < 3 else 20 # If $D==2... if dim2: # Initialize plot fig = plt.figure(figsize=(5*n_params, 5*n_params)) # Loop across parameters, create 1D plot counter = 0 for key in params.keys(): for i in range(int(params[key]['nparams'])): par = params[key]['param'+str(i+1)] sp = par.split(',') ax1 = fig.add_subplot(n_params, n_params, n_params*i+(i+1)) ax1.set_xlabel(parameters[i].replace('_','\_')) # Get parameter statistics, set bounds to +/- 5sigma m = s['marginals'][i] # Histogram posterior x,w,patches = ax1.hist(values[:,i], bins=nbins, edgecolor='black', color='mediumslateblue',\ histtype='stepfilled', alpha=0.2,normed=True) if sp[2][:5] == 'param' or sp[3][:5]=='param': print('not printing prior...') else: add_prior(ax1,sp[1],float(sp[2]),float(sp[3])) ax1.set_ylim(0, x.max()) # y-value at which to place error-bar (1/20th of vertical extent) ylim = ax1.get_ylim() y = ylim[0] + 0.05*(ylim[1] - ylim[0]) # Place error-bar center = m['median'] low1, high1 = m['1sigma'] ax1.errorbar(x=center, y=y, xerr=numpy.transpose([[center - low1, high1 - center]]), color='blue', linewidth=2, marker='s') # Axis formatting ax1.set_ylabel("PDF") #ax1.set_xlim(m['5sigma']) # Loop across other parameters for j in range(i+1,n_params): # Set up 2D posterior plot ax2 = fig.add_subplot(n_params, n_params, n_params*j+(i+1),sharex=ax1) p.plot_conditional(i, j, cmap = 'Blues', bins='log') # Plot error bars for each mode for m in modes: ax2.errorbar(x=m['mean'][i], y=m['mean'][j], xerr=m['sigma'][i],\ yerr=m['sigma'][j]) # Axes labels ax2.set_xlabel(parameters[i].replace('_','\_')) ax2.set_ylabel(parameters[j].replace('_','\_')) # Save figure plt.savefig(prefix + 'marg.pdf') plt.savefig(prefix + 'marg.png') plt.close() # If $D==1... else: # Print stuff from matplotlib.backends.backend_pdf import PdfPages sys.stderr.write('1dimensional only. Set the D environment variable \n') sys.stderr.write('to D=2 to force 2d marginal plots.\n') pp = PdfPages(prefix + 'marg1d.pdf') # Proceed as above, but only plot 1D posterior plots for i in range(n_params): plt.figure(figsize=(3, 3)) plt.xlabel(parameters[i].replace('_','\_')) plt.locator_params(nbins=5) m = s['marginals'][i] iqr = m['q99%'] - m['q01%'] xlim = m['q01%'] - 0.3 * iqr, m['q99%'] + 0.3 * iqr #xlim = m['5sigma'] plt.xlim(xlim) oldax = plt.gca() x,w,patches = oldax.hist(values[:,i], bins=numpy.linspace(xlim[0], xlim[1], 20), edgecolor='black', color='grey', histtype='stepfilled', alpha=0.2) oldax.set_ylim(0, x.max()) newax = plt.gcf().add_axes(oldax.get_position(), sharex=oldax, frameon=False) p.plot_marginal(i, ls='-', color='blue', linewidth=3) newax.set_ylim(0, 1) ylim = newax.get_ylim() y = ylim[0] + 0.05*(ylim[1] - ylim[0]) center = m['median'] low1, high1 = m['1sigma'] #print center, low1, high1 newax.errorbar(x=center, y=y, xerr=numpy.transpose([[center - low1, high1 - center]]), color='blue', linewidth=2, marker='s') oldax.set_yticks([]) newax.set_ylabel("Probability") ylim = oldax.get_ylim() newax.set_xlim(xlim) oldax.set_xlim(xlim) plt.savefig(pp, format='pdf', bbox_inches='tight') plt.close() pp.close()