def testFileLoadPlot(self): samples = loadMCSamples(self.root, settings={'ignore_rows': 0.1}) g = plots.getSinglePlotter(chain_dir=self.tempdir, analysis_settings={'ignore_rows': 0.1}) self.assertEqual( g.sampleAnalyser.samplesForRoot('testchain').numrows, samples.numrows, "Inconsistent chain loading") self.assertEqual( g.sampleAnalyser.samplesForRoot('testchain').getTable().tableTex(), samples.getTable().tableTex(), 'Inconsistent load result') samples.getConvergeTests(0.95) self.assertAlmostEqual( 0.0009368, samples.GelmanRubin, 5, 'Gelman Rubin error, got ' + str(samples.GelmanRubin)) g = plots.getSinglePlotter() g.plot_3d(samples, ['x', 'y', 'x']) g.export(self.root + '_plot.pdf') g = plots.getSinglePlotter(chain_dir=self.tempdir, analysis_settings={ 'ignore_rows': 0.1, 'contours': [0.68, 0.95, 0.99] }) g.settings.num_plot_contours = 3 g.plot_2d('testchain', ['x', 'y'])
def plot2D(rdic, par=[1, 2], tex=1): snstyle(tex) rdic = np.asarray(rdic) root = list(rdic[:, 0]) lengend = list(rdic[:, 1]) rn = len(root) Samp = [] minkaf = np.zeros(rn) data_num = np.zeros(rn) for i in range(rn): savefile_name = './chains/' + root[i] + '.npy' samples, theta_name, theta_fit, theta_fact, minkaf[i], data_num[ i] = np.load(savefile_name) Samp.append( MCSamples(samples=samples, names=theta_name, labels=theta_name)) pnames = Samp[0].getParamNames().names rn = len(root) g = plots.getSinglePlotter(width_inch=7) #samples.updateSettings({'contours': [0.68, 0.95, 0.99]}) #g.settings.num_plot_contours = 3 g.settings.lab_fontsize = 18 g.settings.axes_fontsize = 14 g.plot_2d(Samp, pnames[par[0] - 1].name, pnames[par[1] - 1].name) for i in range(rn): sns.kdeplot(Samp[i].samples[:, par[0] - 1], Samp[i].samples[:, par[1] - 1], cmap="Blues", shade=True, shade_lowest=False) g.add_legend(lengend, colored_text=True, fontsize=18) mpl.pyplot.tight_layout()
def plot1D(self, n, colorn=0, width_inch=8, **kwargs): g = plots.getSinglePlotter(width_inch=width_inch) g.plot_1d(self.Samp, self.param_names[n - 1], ls=lss, colors=colors[colorn:colorn + self._n], lws=[1.5] * self._n, **kwargs) # g.settings.figure_legend_frame = False ax = plt.gca() if all(self.lengend): leg = ax.legend(self.lengend, loc=1, fontsize=16, frameon=False) for line, text in zip(leg.get_lines(), leg.get_texts()): text.set_color(line.get_color()) if 'x_marker' in kwargs: g.add_x_marker(kwargs['x_marker'], lw=1.5) # if 'x_bands' in kwargs: # g.add_x_bands(0,0.01) if 'xaxis' in kwargs: ax.xaxis.set_major_locator(plt.MultipleLocator(kwargs['xaxis'])) if 'title' in kwargs: ax.set_title(kwargs['title']) # plt.tight_layout() if 'name' in kwargs: g.export(os.path.join(outdir, '%s.pdf' % kwargs['name'])) else: g.export( os.path.join(outdir + ''.join(self.root) + self.param_names[n - 1].replace('\\', '') + '_1D.pdf')) return g
def testFileLoadPlot(self): samples = loadMCSamples(self.root, settings={'ignore_rows': 0.1}) g = plots.getSinglePlotter(chain_dir=self.tempdir, analysis_settings={'ignore_rows': 0.1}) self.assertEqual(g.sampleAnalyser.samplesForRoot('testchain').numrows, samples.numrows, "Inconsistent chain loading") self.assertEqual(g.sampleAnalyser.samplesForRoot('testchain').getTable().tableTex(), samples.getTable().tableTex(), 'Inconsistent load result') samples.getConvergeTests(0.95) self.assertAlmostEqual(0.0009368, samples.GelmanRubin, 5, 'Gelman Rubin error, got ' + str(samples.GelmanRubin)) g = plots.getSinglePlotter() g.plot_3d(samples, ['x', 'y', 'x']) g.export(self.root + '_plot.pdf') g = plots.getSinglePlotter(chain_dir=self.tempdir, analysis_settings={'ignore_rows': 0.1, 'contours': [0.68, 0.95, 0.99]}) g.settings.num_plot_contours = 3 g.plot_2d('testchain', ['x', 'y'])
def plot_sampling(mcmc_config, param_info_wod, burned_chain, theta_ml, include_outlier_dist=False, include_ml=True): chain_tag = mcmc_config.chain_tag param_names_wod, param_labels_wod, param_guess_wod, param_priors_wod = param_info_wod print('\nProcessing MCMC chain...') if include_outlier_dist: ndim = burned_chain.shape[1] elif not include_outlier_dist: ndim = burned_chain.shape[1] - 3 names = param_labels_wod[0:ndim].copy() ranges_gd = {} for i in range(ndim): ranges_gd[param_labels_wod[i]] = (param_priors_wod[i][1], param_priors_wod[i][1]) gd_samples = MCSamples(samples=burned_chain[:, 0:ndim], names=param_names_wod[0:ndim], labels=param_labels_wod[0:ndim]) #, #ranges=ranges_gd[0:ndim]) if ndim == 1: fig = plots.getSinglePlotter(width_inch=5) fig.plot_1d(gd_samples, names[0], normalized=True) elif ndim > 1: fig = plots.getSubplotPlotter() fig.triangle_plot([gd_samples], filled=True) if include_ml: for i in range(ndim): ax = fig.subplots[i, i] ax.axvline(theta_ml[i], color='r', ls='-', alpha=0.75) for i in range(ndim - 1): for j in range(i + 1): ax = fig.subplots[i + 1, j] ax.plot(theta_ml[j], theta_ml[i + 1], 'w*', zorder=3, markersize=5.) plt.show() fig_name = 'MCMC_sampling_{}'.format(chain_tag) save_figure(mcmc_config, fig, fig_name, gd_plot=True) # plot_file = '{}/MCMC_sampling_{}.png'.format(plots_dir, chain_tag) # mcmc_fig.export(plot_file) plt.close()
def testPlots(self): self.samples = self.testdists.bimodal[0].MCSamples(12000, logLikes=True) g = plots.getSinglePlotter() samples = self.samples p = samples.getParams() samples.addDerived(p.x + (5 + p.y)**2, name='z') samples.addDerived(p.x, name='x.yx', label='forPattern') samples.addDerived(p.y, name='x.2', label='x_2') samples.updateBaseStatistics() g.plot_1d(samples, 'x') g.newPlot() g.plot_1d(samples, 'y', normalized=True, marker=0.1, marker_color='b') g.newPlot() g.plot_2d(samples, 'x', 'y') g.newPlot() g.plot_2d(samples, 'x', 'y', filled=True) g.newPlot() g.plot_2d(samples, 'x', 'y', shaded=True) g.newPlot() g.plot_2d_scatter(samples, 'x', 'y', color='red', colors=['blue']) g.newPlot() g.plot_3d(samples, ['x', 'y', 'z']) g = plots.getSubplotPlotter(width_inch=8.5) g.plots_1d(samples, ['x', 'y'], share_y=True) g.newPlot() g.triangle_plot(samples, ['x', 'y', 'z']) g.newPlot() g.triangle_plot(samples, ['x', 'y'], plot_3d_with_param='z') g.newPlot() g.rectangle_plot(['x', 'y'], ['z'], roots=samples, filled=True) prob2 = self.testdists.bimodal[1] samples2 = prob2.MCSamples(12000) g.newPlot() g.triangle_plot([samples, samples2], ['x', 'y']) g.newPlot() g.plots_2d([samples, samples2], param_pairs=[['x', 'y'], ['x', 'z']]) g.newPlot() g.plots_2d([samples, samples2], 'x', ['z', 'y']) g.newPlot() self.assertEqual( [name.name for name in samples.paramNames.parsWithNames('x.*')], ['x.yx', 'x.2']) g.triangle_plot(samples, 'x.*') samples.updateSettings({'contours': '0.68 0.95 0.99'}) g.settings.num_contours = 3 g.plot_2d(samples, 'x', 'y', filled=True) g.add_y_bands(0.2, 1.5) g.add_x_bands(-0.1, 1.2, color='red')
def testPlots(self): self.samples = self.testdists.bimodal[0].MCSamples(12000, logLikes=True) g = plots.getSinglePlotter() samples = self.samples p = samples.getParams() samples.addDerived(p.x + (5 + p.y) ** 2, name='z') samples.addDerived(p.x, name='x.yx', label='forPattern') samples.addDerived(p.y, name='x.2', label='x_2') samples.updateBaseStatistics() g.plot_1d(samples, 'x') g.newPlot() g.plot_1d(samples, 'y', normalized=True, marker=0.1, marker_color='b') g.newPlot() g.plot_2d(samples, 'x', 'y') g.newPlot() g.plot_2d(samples, 'x', 'y', filled=True) g.newPlot() g.plot_2d(samples, 'x', 'y', shaded=True) g.newPlot() g.plot_2d_scatter(samples, 'x', 'y', color='red', colors=['blue']) g.newPlot() g.plot_3d(samples, ['x', 'y', 'z']) g = plots.getSubplotPlotter(width_inch=8.5) g.plots_1d(samples, ['x', 'y'], share_y=True) g.newPlot() g.triangle_plot(samples, ['x', 'y', 'z']) g.newPlot() g.triangle_plot(samples, ['x', 'y'], plot_3d_with_param='z') g.newPlot() g.rectangle_plot(['x', 'y'], ['z'], roots=samples, filled=True) prob2 = self.testdists.bimodal[1] samples2 = prob2.MCSamples(12000) g.newPlot() g.triangle_plot([samples, samples2], ['x', 'y']) g.newPlot() g.plots_2d([samples, samples2], param_pairs=[['x', 'y'], ['x', 'z']]) g.newPlot() g.plots_2d([samples, samples2], 'x', ['z', 'y']) g.newPlot() self.assertEquals([name.name for name in samples.paramNames.parsWithNames('x.*')], ['x.yx', 'x.2']) g.triangle_plot(samples, 'x.*') samples.updateSettings({'contours': '0.68 0.95 0.99'}) g.settings.num_contours = 3 g.plot_2d(samples, 'x', 'y', filled=True) g.add_y_bands(0.2, 1.5) g.add_x_bands(-0.1, 1.2, color='red')
def single_plot(filename, legends, limits, out): chain1 = np.genfromtxt("like/"+filename[0])[:,:7] chain2 = np.genfromtxt("like/"+filename[1])[:,:7] chain1[:,3] = chain1[:,3]+(1-1./(1+0.266))*chain1[:,4] chain2[:,3] = chain2[:,3]+(1-1./(1+zp))*chain2[:,4] labels[3] ="w_\mathrm{p}" names[3] = "wp" samples1 = MCSamples(samples=chain1,names = names, labels = labels) samples2 = MCSamples(samples=chain2,names = names, labels = labels) samples1.fine_bins_2D = 20 samples2.fine_bins_2D = 20 g = plots.getSinglePlotter() g.plot_2d([samples1, samples2],"wp","wa", filled=[False,True],lims=limits,colors=['red','blue']) g.settings.legend_fontsize = 12 g.add_legend(legends) g.export('plots/'+out)
def simpleGetdist(self, **kwargs): """ Lewis (2019) arXiv:1910.13970v1 [astro-ph.IM] """ from getdist import plots, MCSamples, chains smooth2d = kwargs.pop("smooth2d", 0.3) smooth1d = kwargs.pop("smooth1d", 0.3) burnin = kwargs.pop("burnin", 0.2) colors = kwargs.pop( "colors", ['red', 'blue', 'black', 'green', 'yellow', 'purple', 'gray']) legend_labels = kwargs.pop("legend_labels", []) filled = kwargs.pop("filled", False) normalized = kwargs.pop("normalized", False) shaded = kwargs.pop("shaded", False) label = kwargs.pop("label", None) roots = kwargs.pop('roots', [self.root]) g = plots.getSinglePlotter(chain_dir=self.chainsdir, width_inch=10, ratio=0.9, scaling=2, analysis_settings={ 'smooth_scale_2D': smooth2d, 'smooth_scale_1D': smooth1d, 'ignore_rows': burnin }) g.triangle_plot(roots, self.listpars, diag1d_kwargs={'colors': colors}, colors=colors, legend_labels=legend_labels, filled=filled, normalized=normalized, shaded=shaded) self.image = "{}_getdist.png".format(self.filename) self.saveFig(label)
def plot2D(self, pp, colorn=0, contour_num=2, width_inch=8, **kwargs): g = plots.getSinglePlotter(width_inch=width_inch, ratio=1) g.settings.num_plot_contours = contour_num g.settings.axes_fontsize = 14 g.settings.lab_fontsize = 18 g.settings.legend_frame = False g.plot_2d(self.Samp, self.param_names[pp[0] - 1], self.param_names[pp[1] - 1], filled=True, **kwargs) if 'x_locator' in kwargs: ax = g.get_axes() ax.xaxis.set_major_locator(plt.MultipleLocator( kwargs['x_locator'])) del kwargs['x_locator'] if 'y_locator' in kwargs: ax = g.get_axes() ax.yaxis.set_major_locator(plt.MultipleLocator( kwargs['y_locator'])) del kwargs['y_locator'] if 'lims' in kwargs: [xmin, xmax, ymin, ymax] = kwargs['lims'] plt.xlim(xmin, xmax) plt.ylim(ymin, ymax) del kwargs['lims'] if 'x_marker' in kwargs: g.add_x_marker(kwargs['x_marker'], lw=1.5) if all(self.lengend): kwarg = kwargs.copy() if 'name' in kwarg: del kwarg['name'] g.add_legend(self.lengend, colored_text=True, fontsize=16, **kwarg) # plt.tight_layout() if 'name' in kwargs: g.export(os.path.join(outdir, '%s.pdf' % kwargs['name'])) else: g.export(os.path.join(outdir, ''.join(self.root) + '_2D.pdf')) return g
import getdist.plots as gplot import os from pylab import * import numpy as np from scipy.integrate import quad import matplotlib.pyplot as plt G=gplot.getSinglePlotter(chain_dir=r'/Users/scottpreston/Desktop/base') roots = ['base_r_plikHM_TTTEEE_lowTEB'] pairs = [[u'ns', u'r']] G.plots_2d(roots, param_pairs=pairs, filled=True, shaded=False) ylim(ymax=0.25) N = np.linspace(50.0, 60.0, 10) n = 2/3 n_1 = 2 n_2 = 4/3 n_3 = 3 n_4 = 1 n_5 = 1.125 def f_r0(N, n): # phi 2/3 for j in range(len(N)): return (16*n)/(4*N + n) def ns_N0(N, n): for k in range(len(N)): return 1 -2*(n + 2)/(4*N + n) def f_r1(N): #R^2 inflation
samps2 = samps1[0.1<=samps1[:,1],:] samps3 = samps2[samps2[:,0]<=85,:] cut_samps = samps3[50<=samps3[:,0],:] names = ["H","m"] labels = [r"H_0",r"\Omega_{m_0}"] samples = MCSamples(samples=cut_samps,names = names, labels = labels,ranges={'H':(50,85),'m':(0.1,0.7)}) samples1 = MCSamples(samples=samps,names = names, labels = labels,ranges={'H':(50,85),'m':(0.1,0.7)}) ''' 1D likelihoods ''' z1 = loadtxt('flat_LCDM_L(H0).dat', unpack=True) print('check 4') x1 = loadtxt('flat_LCDM_H0_1D.dat', unpack=True) g = plots.getSinglePlotter(width_inch=4) g.plot_1d(samples, 'H', ls=['solid']) plt.plot(x1, z1/max(z1), linestyle=':', color='blue') g.export('flat_LCDM_L(H0)_1D_MCMC_vs_grid_my_data.pdf') z1 = loadtxt('flat_LCDM_L(Om).dat', unpack=True) print('check 5') x1 = loadtxt('flat_LCDM_Om_1D.dat', unpack=True) g = plots.getSinglePlotter(width_inch=4) g.plot_1d(samples, 'm', ls=['solid']) plt.plot(x1, z1/max(z1), linestyle=':', color='blue') g.export('flat_LCDM_L(Om)_1D_MCMC_vs_grid_my_data.pdf') ''' 2D contours
g = plots.getSubplotPlotter(chain_dir= dir_name, width_inch=16, analysis_settings={'smooth_scale_2D': -1. , 'ignore_rows': 0.2}) g.settings.axes_fontsize = 18 g.settings.lab_fontsize = 20 g.settings.alpha_filled_add =0.9 g.plots_2d(roots, param_pairs=[['omegak','w'], ['omegak','wa'], ['w','wa']], nx=3, filled=True, legend_labels=False) g.add_legend(['PLANCK + DR12 LOWZ+CMASS', 'PLANCK + DR12 BAO', 'PLANCK + DR12 BAO+FS'], colored_text=True, legend_loc='upper right') g.export('owa_dr12_jla.pdf') roots = ['LCDM_ABfs8_PLK+DR12+ALLB'] g = plots.getSinglePlotter(chain_dir= dir_name, analysis_settings={'smooth_scale_2D': -1., 'ignore_rows': 0.2}) g.settings.axes_fontsize = 20 g.settings.lab_fontsize = 25 g.settings.alpha_filled_add =0.9 g.add_y_marker(0) g.add_x_marker(1) g.plot_2d(roots, 'Afs8','Bfs8', filled=True, legend_labels=False, colors = ['blue'], alphas=[0.8]) g.add_legend(['PLANCK+BAO+FS'], colored_text=True, legend_loc='upper right') g.export('mg.pdf') if True: roots = ['mnu_Alens_Afs8_PLK+DR12+ALLB', 'mnu_Alens_PLK+DR12+ALLB', 'mnu_Afs8_PLK+DR12+ALLB', 'mnu_PLK+DR12+ALLB'] g = plots.getSinglePlotter(chain_dir= dir_name, analysis_settings={'smooth_scale_2D': -1. , 'ignore_rows': 0.2})
import matplotlib.pyplot as plt from getdist import plots import planckStyle dir_name = '/Users/josevazquezgonzalez/Desktop/BOSS/BOSS_files/DR12/chains' roots = ['owcdmdr12','OkwoCDM_PLK+BAO12','OkwoCDM_PLK+DR12'] g= plots.getSinglePlotter(chain_dir = dir_name, ratio=1., analysis_settings={'smooth_scale_2D': -1.}) g.plot_2d(roots, param_pair=['omegak','w'], filled=True, legend_labels=False, line_args={'lw':2, 'ls':'-'}) #g = plots.getSubplotPlotter(chain_dir= dir_name, width_inch=16, analysis_settings={'smooth_scale_2D': -1.}) g.settings.axes_fontsize = 20 g.settings.lab_fontsize = 25 g.settings.alpha_filled_add =0.9 g.add_y_marker(-1) g.add_x_marker(0) #g.plots_2d(roots, param_pairs=[['omegak','w'], ['omegak','H0'], ['w','H0']], nx=3, filled=True, # legend_labels=False, line_args={'lw':2, 'ls':'-'}) #g.add_legend(['PLACK + DR12 LOWZ+CMASS', 'PLACK + DR12 BAO', 'PLACK + DR12 BAO+RSD'], # colored_text=True, legend_loc='upper right') g.export('OkwoCDM_10.pdf')
from getdist import plots dirs = [ "../completed_runs/standard_Mnu_nEff_mn_build/", "../completed_runs/standard_Mnu_nEff_bao_mn_build/", "../completed_runs/standard_Mnu_nEff_lrg_mn_build/", "../completed_runs/standard_Mnu_nEff_wigglez_mn_build" ] roots = [ "standard_neff_summnu_planck", "standard_neff_summnu_planck_bao_", "standard_neff_summnu_planck_lrg_", "standard_neff_summnu_planck_wigglez_" ] g = plots.getSinglePlotter(chain_dir=dirs) g.plot_2d(roots, "h", "ombh2", filled=True, lims=[0.55, 0.80, 0.020, 0.024]) g.settings.legend_fontsize = 12 g.add_legend(["Planck2015", "Planck2015+BAO", "Planck2015+LRG", "Planck2015+WiggleZ"], legend_loc="lower right") g.export("test.pdf")
from getdist import loadMCSamples, plots number_of_parameters = 14 samples = loadMCSamples('../output/chains/mcmc_final_output_HP', settings={'ignore_rows': 2}) g = plots.getSinglePlotter() g.settings.rcSizes(axes_fontsize=2, lab_fontsize=7) g.triangle_plot(samples, filled=True) g.export('../output/chains/triangle_figure_HP_R11_H.pdf') bestfit = samples.getLikeStats() means = samples.setMeans() filebestfit = open("../output/chains/bestfit.txt", 'w') filemeans = open("../output/chains/means.txt", 'w') #filebestfit.write("-log(Like) = "+str(bestfit.logLike_sample)+"\n") for index in range(number_of_parameters): filebestfit.write(str(bestfit.names[index].bestfit_sample) + "\n") filemeans.write(str(means[index]) + "\n")
pl.rcParams['axes.labelpad'] = '10.0' pl.rcParams['lines.dashed_pattern'] = 3.5, 1.0 #pl.rcParams['axes.formatter.limits']=-10,10 pl.rcParams['lines.dotted_pattern'] = 1.0, 0.7 pl.rcParams['xtick.labelsize'] = '15' pl.rcParams['ytick.labelsize'] = '15' pl.rcParams['axes.labelsize'] = '30' pl.rcParams['axes.labelsize'] = '30' pl.rcParams['xtick.major.pad'] = '10' pl.rcParams['xtick.minor.pad'] = '10' #pl.rcParams['hatch.color'] = 'black' pl.rc('axes', linewidth=2) g1 = gplot.getSinglePlotter(chain_dir=r'./planck') samples = g1.sampleAnalyser.samplesForRoot( 'base_plikHM_TTTEEE_lowl_lowE_lensing') param = samples.getParams() g1.settings.num_plot_contours = 2 g = plots.getSinglePlotter(width_inch=4, ratio=1) P = param.sigma8 * (param.omegam / 0.3)**0.5 samples.addDerived(P, name=r'S80') #, label=r'c/h_rd') k = param.H0 samples.addDerived(k, name=r'h') #, label=r'c/h_rd') samples.updateBaseStatistics() g.plot_2d([samples], [r'h', r'S80'], filled=True, colors=['magenta']) x = np.linspace(0, 120, 100) plt.fill_between(x, 0.70103627, 0.77290325, color='darkgrey', alpha='0.5') x = np.linspace(72.61, 75.45, 100)