def load_samples(file_root): """Check that input chain exist, at least in zipped format, and read them.""" try: samples = loadMCSamples(file_root) except IOError: if os.path.exists(file_root + '.txt.gz'): print('unzip chain', file_root) cmd = 'gzip -dk ' + file_root + '.txt.gz' os.system(cmd) samples = loadMCSamples(file_root) else: raise IOError('No chains found (not even zipped): ' + file_root) return samples
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 limits(self): """Infer param limits from <root>.yaml in cobaya format.""" s = loadMCSamples(file_root=self.root) return { p.name: (s.ranges.getLower(p.name), s.ranges.getUpper(p.name)) for p in s.paramNames.names if s.ranges.getLower(p.name) is not None or s.ranges.getUpper(p.name) is not None }
def test_read_cobayamcmc(): np.random.seed(3) mcmc = MCMCSamples(root='./tests/example_data/cb') mcmc.plot_2d(['x0', 'x1']) mcmc.plot_1d(['x0', 'x1']) plt.close("all") # compare directly with getdist mcmc_gd = getdist.loadMCSamples(file_root="./tests/example_data/cb") assert_array_almost_equal(mcmc.logL, mcmc_gd.loglikes, decimal=15)
def load_from_file(self,rootname,**kwargs): #Load from file #self.samples=[] #for f in rootname: idchain=kwargs.pop('idchain', 0) print('mcsample: rootname, idchain',rootname,idchain) self.samples=gd.loadMCSamples(rootname,**kwargs)#.makeSingle() if idchain>0: self.samples.samples=self.samples.getSeparateChains()[idchain-1].samples self.samples.loglikes=self.samples.getSeparateChains()[idchain-1].loglikes self.samples.weights=self.samples.getSeparateChains()[idchain-1].weights
def test_planck_chains(self): if os.path.exists(self.path): root = os.path.join(self.path, 'compare_devel_drag') samples = loadMCSamples(root, settings={'ignore_rows': 0.3}, no_cache=True) self.assertAlmostEqual(samples.mean('ombh2'), 0.0223749, 6) self.assertAlmostEqual(samples.getUpper('H0'), 100, 6) self.assertEqual(samples.getLower('sigma8'), None) samples.saveAsText(r'planck_test') ranges = ParamBounds('planck_test.ranges') for par in samples.paramNames.names: self.assertEqual(samples.getUpper(par.name), ranges.getUpper(par.name))
def test_chains(self): if os.path.exists(self.path): root = os.path.join(self.path, 'DES_shear') samples = loadMCSamples(root, settings={'ignore_rows': 0.3}, no_cache=True) self.assertAlmostEqual(samples.mean('ombh2'), 0.02764592190482377, 6) pars = samples.getParamSampleDict(10) self.assertAlmostEqual(0.06, pars['mnu'], 6) self.assertAlmostEqual(samples.getUpper('ns'), 1.07, 6) self.assertAlmostEqual(samples.getLower('ns'), 0.87, 6) self.assertEqual(samples.getLower('DES_DzS2'), None) self.assertAlmostEqual(0, pars['omk']) from getdist.command_line import getdist_command res = getdist_command([root]) self.assertTrue('-log(Like) = 95.49' in res, res)
def __init__(self, Chains, ignore_rows=0.3): self.root = list(np.asarray(Chains)[:, 0]) self.lengend = list(np.asarray(Chains)[:, 1]) self.aic_g = False self.Samp = [] self._n = len(Chains) self.minkaf = np.zeros(self._n) self.data_num = np.zeros(self._n) for i in list(range(self._n)): self.Samp.append( loadMCSamples('./chains/' + self.root[i], settings={'ignore_rows': ignore_rows})) self.param_names = [] for na in self.Samp[0].getParamNames().names: self.param_names.append(na.name)
def setUp(self): # get path: self.here = os.path.dirname(os.path.abspath(__file__)) # get chains: self.chain_1 = loadMCSamples(self.here + '/../../test_chains/DES') self.chain_2 = loadMCSamples(self.here + '/../../test_chains/Planck18TTTEEE') self.chain_12 = loadMCSamples(self.here + '/../../test_chains/Planck18TTTEEE_DES') self.chain_prior = loadMCSamples(self.here + '/../../test_chains/prior') # thin the chain: self.chain_1.getConvergeTests() self.chain_2.getConvergeTests() self.chain_12.getConvergeTests() self.chain_prior.getConvergeTests() self.chain_1.weighted_thin(int(self.chain_1.indep_thin)) self.chain_2.weighted_thin(int(self.chain_2.indep_thin)) self.chain_12.weighted_thin(int(self.chain_12.indep_thin)) self.chain_prior.weighted_thin(int(self.chain_prior.indep_thin)) # get difference chain: self.diff_chain = pd.parameter_diff_chain(self.chain_1, self.chain_2, boost=1)
def get_models_from_mcsamples(mcsamples, lk_names, extras=None, n=None, progress=True): if type(mcsamples) == str: mcsamples = loadMCSamples(mcsamples) if n is not None: samples = mcsamples.samples[np.random.choice( mcsamples.samples.shape[0], size=n)] else: samples = mcsamples.samples out = {} lk = load_likelihood_from_yaml(mcsamples.rootname + '.yml') top_level = True if isinstance(lk, LikelihoodContainer): top_level = False if top_level and len(lk_names) > 1: raise ValueError( "you have specified more lk_names than actually exist!") for params in tqdm(samples, disable=not progress): ctx = lk.get_ctx(params=params) model = lk.reduce_model(ctx=ctx, params=params) if top_level: ctx = {lk_names[0]: ctx} model = {lk_names[0]: model} for lk_name in lk_names: if lk_name not in out: out[lk_name] = {} if "model" not in out[lk_name]: out[lk_name]['model'] = [] out[lk_name]['model'].append(model[lk_name]) for extra in (extras or []): if extra in ctx[lk_name]: out[lk_name][extra] = ctx[lk_name][extra] return out
def samples_from_getdist_chains(params, file_root, latex=False, **kwargs): """ Extract samples and weights from getdist chains. Parameters ---------- params: list(str) Names of parameters to be supplied to second argument of f(x|theta). file_root: str, optional Root name for getdist chains files. This variable automatically defines: - chains_file = file_root.txt - paramnames_file = file_root.paramnames but can be overidden by chains_file or paramnames_file. latex: bool, optional Also return an array of latex strings for those paramnames. Any additional keyword arguments are forwarded onto getdist, e.g: samples_from_getdist_chains(params, file_root, settings={'ignore_rows':0.5}) Returns ------- samples: numpy.array 2D Array of samples. `shape=(len(samples), len(params))` weights: numpy.array Array of weights. `shape = (len(params),)` latex: list(str), optional list of latex strings for each parameter (if latex is provided as an argument) """ import getdist samples = getdist.loadMCSamples(file_root, **kwargs) weights = samples.weights indices = [samples.index[p] for p in params] samps = samples.samples[:, indices] if latex: latex = [samples.parLabel(p) for p in params] return samps, weights, latex else: return samps, weights
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 paramnames(self): r"""Read header of <root>.1.txt to infer the paramnames. This is the data file of the first chain. It should have as many columns as there are parameters (sampled and derived) plus an additional two corresponding to the weights (first column) and the logposterior (second column). The first line should start with a # and should list the parameter names corresponding to the columns. This will be used as label in the pandas array. Uses GetDist's `loadMCSamples` to infer the tex dictionary. """ try: with open(self.root + ".1.txt") as f: header = f.readline()[1:] paramnames = header.split()[2:] s = loadMCSamples(file_root=self.root) tex = {p.name: '$' + p.label + '$' for p in s.paramNames.names} return paramnames, tex except IOError: return super().paramnames()
def callGetDist(chainsFilePrefix, plotName, nParams, plotLegend): """ produces triangular posterior plots using getDist for first nParams parameters from chains file as labelled in that file and in .paramnames plotName should contain image type extension (e.g. .png) Args: chainsFilePrefix : string chains file excluding the '.txt' prefix plotName : string name of plot nParams : int dimensionality of parameter space plotLegend : list used for plot legend """ print(plotName) try: import getdist.plots import getdist.loadMCSamples except ImportError: try: import getdist except ImportError: print("can't import getdist. Exiting...") sys.exit(1) save = True paramList = ['p' + str(i + 1) for i in range(nParams)] chains = [getdist.loadMCSamples(chain) for chain in chainsFilePrefix] g = getdist.plots.getSubplotPlotter(width_inch=6) g.triangle_plot(chains, paramList, filled=False, legend_labels=plotLegend) if save: g.export(plotName) else: plt.show() return g
day = f'{today.year}_{today.month}_{10}' N = 2 GL_min = "8.0" GL_max = 76.8 points = 10000 directory = f"graphs/{day}/" tag = "parameter_range_run" # directory = f"graphs/{today.year}_6_23/" for model in [model27, model28]: if not os.path.isdir(directory): os.makedirs(directory) samples = loadMCSamples( f'posterior_data/{day}/{model.__name__}{tag}_N{N}_GLmin{GL_min}_GLmax{GL_max}_p{points}' ) # samples = loadMCSamples(f'posterior_data/{day}/{model.__name__}small_except_c_omega_N{N}_GLmin{GL_min}_GLmax{GL_max}_p{points}') g = plots_edit.get_subplot_plotter() g.triangle_plot(samples, filled=True) # plt.savefig(f"{directory}2D_posterior_{model.__name__}.png") # plt.savefig(f"special_graphs/2D_posterior_{model.__name__}_edit.png") # fig = plt.gcf() # fig2, axis = plt.subplots() # fig.axes[0].scatter([0], [0])
def main(): # Generate the x values of our data for i in range(len(xdata)): xdata[i] = float(i) # Set the noise stddev of the y values for i in range(len(ydata)): ydata_err[i] = 100.0 params_value = [ 900, 400, 100, 0 ] # Generate the y values of our data for i in range(len(ydata)): # Evaluate gaussian ydata[i] = evaluate_gaussian(xdata[i], params_value[0], params_value[1], params_value[2], params_value[3]) # Add noise ydata[i] += random.gauss(0, ydata_err[i]) filename = 'output/out' if not os.path.exists('./output'): os.makedirs('./output') # Run MultiNest! pymultinest.run(my_loglike, my_prior, params_count, outputfiles_basename=filename, resume=False, verbose=True, importance_nested_sampling=True, multimodal=False, const_efficiency_mode=False, n_live_points=100, evidence_tolerance=0.3, sampling_efficiency=0.8, max_iter=0) # Perform result analysis analyzer = pymultinest.Analyzer(outputfiles_basename=filename, n_params=params_count) stats = analyzer.get_stats() # Pretty print results to a JSON file results_json = json.dumps(stats, sort_keys=True, indent=2) with open('pretty_results.json', 'w') as f: f.write(results_json) # Generate best-fit model ydata_best_fit = numpy.empty(data_length) for i in range(len(ydata_best_fit)): ydata_best_fit[i] = evaluate_gaussian(xdata[i], stats['modes'][0]['maximum'][0], stats['modes'][0]['maximum'][1], stats['modes'][0]['maximum'][2], stats['modes'][0]['maximum'][3]) # Plot data vs best fit fig = pyplot.figure() ax = fig.add_subplot(1, 1, 1) ax.plot(ydata, color='#5e3c99') ax.plot(ydata_best_fit, color='#e66101', linewidth=6) pyplot.savefig('data_vs_best_fit.png') # Corner plot samples = getdist.loadMCSamples(filename+'.txt') plotter = getdist.plots.getSubplotPlotter() plotter.triangle_plot([samples], filled=True) plotter.export('corner_plot.png')
#!/usr/bin/python import getdist import numpy as np import os import pyccl as ccl MP_root = '/mnt/zfsusers/gravityls_3/codes/montepython_emilio' des_root = os.path.join(MP_root, 'chains/cl_cross_corr_des_full_kappa_l8/') des = getdist.loadMCSamples(os.path.join(des_root, '2020-03-09_1000000_'), settings={'ignore_rows': 0.1}) growth_root = os.path.join( MP_root, 'chains/cl_cross_corr_des_growth_dpk0_fixed_kappa_l8/') growth = getdist.loadMCSamples(os.path.join(growth_root, '2020-03-09_1000000_'), settings={'ignore_rows': 0.1}) def S8z(mcmc, a, MG=False, size=None): p = mcmc.getParams() if size is None: size = p.A_s.size S8_ar = np.zeros((size, a.size)) for i in range(size): cosmo = ccl.Cosmology(h=p.h[i], Omega_c=p.Omega_c[i], Omega_b=p.Omega_b[i], A_s=1e-9 * p.A_s[i], n_s=p.n_s[i],
from getdist import loadMCSamples, plots, covmat import numpy as np import os, fnmatch samples = loadMCSamples('/home/projects/dea/mcmc/chains/mcmc_final_output', settings={'ignore_rows': .0}) g = plots.getSinglePlotter() g.settings.rcSizes(axes_fontsize=2, lab_fontsize=7) p = samples.getParams() bestfit = samples.getLikeStats() means = samples.setMeans() stats = samples.getMargeStats() stats.saveAsText('/home/projects/dea/mcmc/chains/1Dstatistics.txt') print '1D STATISTICS FILE CREATED' f = plots.getSubplotPlotter() f.settings.rcSizes(axes_fontsize=2, lab_fontsize=7) f.plots_1d(samples) f.export('/home/projects/dea/mcmc/figures/1D_plots.pdf')
#!/usr/bin/python26 from __future__ import print_function from getdist import plots, MCSamples, loadMCSamples import getdist, IPython A611 = loadMCSamples('chains/examp/A611') new_chains = raw_input('Path to new chains:').strip() A6112 = loadMCSamples(new_chains) g = plots.getSubplotPlotter(width_inch=8) g.settings.axes_fontsize = 8 g.settings.alpha_filled_add = 0.4 g.triangle_plot([A611, A6112], ['1', '2', '3', '4', '5', '6'], filled_compare=True, legend_labels=['Example', 'New chains'], legend_loc='upper right', line_args=[{ 'ls': '--', 'color': 'green' }, { 'lw': 2, 'color': 'darkblue' }], contour_colors=['green', 'darkblue']) g.export('A611_tri.png')
def load_from_file(rootname): #Load from file self.samples = [] for f in rootname: self.samples.append(gd.loadMCSamples(rootname))
from getdist import loadMCSamples, plots number_of_parameters = 12 samples = loadMCSamples('../output/mcmc_output', settings={'ignore_rows': 2}) g = plots.getSinglePlotter() g.settings.rcSizes(axes_fontsize=2, lab_fontsize=7) g.triangle_plot(samples, filled=True) g.export('triangle_figure.pdf') bestfit = samples.getLikeStats() means = samples.setMeans() filebestfit = open("../output/bestfit.txt", 'w') filemeans = open("../output/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") filebestfit.close()
"standard_neff_summnu_planck_szclusters" ] colors=['blue', 'green', 'red', 'magenta', 'gray'] labels = ['Planck15', 'Planck15+BAO', 'Planck15+LRG', 'Planck15+WZ', 'Planck15+Clusters'] # Reorder list for plotting order = [0, 4, 3, 1, 2] dirs = [dirs[i] for i in order] roots = [roots[i] for i in order] colors = [colors[i] for i in order] labels = [labels[i] for i in order] samples = [] for root in [d+r for d, r in zip(dirs, roots)]: samples.append(loadMCSamples(root)) for samp in samples: p = samp.getParams() samp.addDerived((p.ombh2+p.omch2)/p.h**2, name="omm", label="\Omega_M") # Single plot #g = plots.getSinglePlotter() #g.plot_2d(samples, "omm", "sigma8", filled=True)#, lims=[0.20, 0.40, 0.55, 0.80]) #g.settings.legend_fontsize = 12 #g.add_legend(["Planck15", "Planck15+BAO", "Planck15+LRG", "Planck15+WiggleZ", "Planck+Clusters"], legend_loc="lower left") # Subplots g = plots.getSubplotPlotter() g.settings.figure_legend_frame = False g.settings.legend_frac_subplot_margin = 0.2
import numpy as np import os, fnmatch filenames = fnmatch.filter(os.listdir("../output/chains/NC-CMB-run3/"), "mcmc_*.txt") for index in range(len(filenames)): os.rename( "../output/chains/NC-CMB-run3/" + str(filenames[index]), "../output/chains/NC-CMB-run3/mcmc_final_output_" + str(index + 1) + ".txt") number_of_parameters = 11 samples = loadMCSamples('../output/chains/NC-CMB-run3/mcmc_final_output', settings={'ignore_rows': 0.}) #print 'CONVERGENCE FOR SAMPLES WITH LENSING ', samples.getGelmanRubin() g = plots.getSinglePlotter() g.settings.rcSizes(axes_fontsize=2, lab_fontsize=7) p = samples.getParams() samples.addDerived(np.log(1.e1**10 * p.A_s), name='ln1010As', label='\ln 10^{10}A_s') samples.addDerived(np.log10(p.cs2_fld), name='logcs2fld', label='\log c_s^2')
args = parser.parse_args() # Load the chains chains = [] for path in args.chains: try: prefix = [x for x in os.listdir(path) if re.match('.*__..txt', x)] except FileNotFoundError: prefix = [] print('WARNING: chains not found at {}'.format(path)) continue prefix.sort() chain = loadMCSamples(os.path.join(path, prefix[0][:-6]), no_cache=False, settings={ 'ignore_rows': args.ignore_rows, 'smooth_scale_1D': args.smooth_scale_1D, 'smooth_scale_2D': args.smooth_scale_2D }) chains.append(chain) # Load legends legends = [] if args.legends and len(args.legends) == len(chains): legends = args.legends else: legends = [re.split('/', x.root)[-2] for x in chains] # Load output file if args.output: output_file = args.output
def setUp(self): # get path: self.here = os.path.dirname(os.path.abspath(__file__)) # get chains: self.chain = loadMCSamples(self.here + '/../../test_chains/DES')
def LoadDataset(label): return getdist.loadMCSamples(str(STRING_TO_CHAIN[label]))
from getdist import plots, loadMCSamples ednew = loadMCSamples('../results/chains/braneworld', settings={'ignore_rows': 0.3}) g = plots.getSubplotPlotter() g.plot_2d(ednew, ['l', 'z'], filled=True) g.export('fig2.pdf')
import matplotlib.pyplot as plt from matplotlib import rcParams from getdist import plots, loadMCSamples # Generic properties from matplotlib rcParams['font.family'] = 'serif' rcParams['text.usetex'] = True path_to_chains = '../data/' chain_file = ['Post_FM_MWP_WDMP_data3_MWdwarfs'] labels = [r'LSST MW Sats. + Spec.'] samplesMC = [] # Load samples for cfile in chain_file: samplesMC.append(loadMCSamples(path_to_chains + cfile + '/' + cfile)) g = plots.getSinglePlotter() g.settings.figure_legend_frame = True g.settings.tight_layout = True g.settings.legend_fontsize = 16 g.settings.lab_fontsize = 20 g.plot_2d(samplesMC, ['m_WDM', 'log_sigma_o_m'], filled=True, legend_loc='lower left', line_args=[{ 'lw': 1.5, 'color': 'tab:blue' }, { 'lw': 1.5, 'color': '#85C1E9',
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")
gd_pars = gd_root + '.paramnames' #print(gd_pars) if not osp.exists(gd_pars): # prevent race conditions: can have all processes trying # to create a symlink simultaneously, with the slow ones # finding it's already been created despite not existing # before this if statement try: os.symlink(template, gd_pars) except OSError as e: if e.errno != errno.EEXIST: raise e # read in samples and fill in derived parameters gd_samples = gd.loadMCSamples(gd_root) pars = gd_samples.getParams() m_1, m_2 = chirp_q_to_comp_masses(pars.chirp_mass, \ pars.mass_ratio) gd_samples.addDerived(m_1, name='mass_1', label=r'm_{\rm BH}') gd_samples.addDerived(m_2, name='mass_2', label=r'm_{\rm NS}') if aligned_spins: gd_samples.addDerived(np.abs(pars.chi_1), name='a_1', label='a_1') # optionally importance sample the input mass priors if imp_sample: # extract posterior samples relevant for reweighting m_c_samples = pars.chirp_mass q_inv_samples = pars.mass_ratio m_1_samples, m_2_samples = \
ff.write('\n') ff.close() print(corrs) #np.savetxt(roots+'_'+pinfo+'.txt', corrs, fmt='%16.8f') return #=================================== if __name__ == "__main__": arg = [] for ss in sys.argv[1:]: arg.append('%s' % ss) roots = arg[0] samples = loadMCSamples(roots, dist_settings={'ignore_rows': 0.3}) pname = samples.getParams() #la1 = np.pi*pname.DAstar*1000.0/pname.rstar #samples.addDerived(la1, name='lA1', label='l_A') la2 = np.pi / (pname.thetastar / 100.0) samples.addDerived(la2, name='lA', label='l_A') R = np.sqrt( pname.omegam * pname.H0**2) * pname.DAstar * 1000.0 / (c_light / 1000) samples.addDerived(R, name='R', label='R') samples.contours = np.array([0.68, 0.95, 0.99]) samples.updateBaseStatistics() #triangleplot(samples) #outputcorrelation(roots,samples) outputdats(samples)
path, name = os.path.split(fileroot) if path == '': fileroot = './' + fileroot chains = fileroot + '.txt' fparam = fileroot + '.paramnames' frange = fileroot + '.ranges' ofile = fileroot + 'mystats.txt' if not os.path.isfile(chains): print('Error: cannot access {}'.format(chains), file=sys.stderr) sys.exit(1) np.savetxt(fparam, np.transpose([names, labels]), fmt='%s') np.savetxt(frange, np.transpose([names, lowbound, upbound]), fmt='%s') # Load sample from FILE_ROOT.txt sample = loadMCSamples(fileroot, \ settings={'fine_bins_2D':1024,'fine_bins':8192}) stats = sample.getMargeStats() par = stats.parWithName(names[0]) lower = par.limits[0].lower upper = par.limits[0].upper sigma = (upper - lower) * 0.5 best = (upper + lower) * 0.5 # Read evidence from FILE_ROOTstats.dat fstat = fileroot + 'stats.dat' with open(fstat, "r") as f: f.readline() line = f.readline() evi = float(line.split(':')[1].split()[0])