Exemple #1
0
    def testFileLoadPlot(self):
        samples = loadMCSamples(self.root, settings={'ignore_rows': 0.1})
        g = plots.get_single_plotter(chain_dir=self.tempdir,
                                     analysis_settings={'ignore_rows': 0.1})
        self.assertEqual(
            g.samples_for_root('testchain').numrows, samples.numrows,
            "Inconsistent chain loading")
        self.assertEqual(
            g.samples_for_root('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.get_single_plotter()
        g.plot_3d(samples, ['x', 'y', 'x'])
        g.export(self.root + '_plot.pdf')

        g = plots.get_single_plotter(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'])
Exemple #2
0
def plot_mcmc_dr9regions():
    titles = {
        'bmzls': 'BASS/MzLS',
        'ndecals': 'DECaLS North',
        'sdecals': 'DECaLS South'
    }

    stg = {
        'mult_bias_correction_order': 0,
        'smooth_scale_2D': 0.15,
        'smooth_scale_1D': 0.3,
        'contours': [0.68, 0.95]
    }
    mc_kw = dict(names=['fnl', 'b', 'n0'],
                 labels=['f_{NL}', 'b', '10^{7}n_{0}'],
                 settings=stg)

    read_kw = dict(ndim=3, iscale=[2])
    mc_kw2 = dict(names=['fnl', 'b', 'n0', 'b2', 'n02'],
                  labels=['f_{NL}', 'b1', '10^{7}n_{0}', 'b2', '10^{7}n_{0}2'],
                  settings=stg)
    read_kw2 = dict(ndim=5, iscale=[2, 4])
    mc_kw3 = dict(names=['fnl', 'b', 'n0', 'b2', 'n02', 'b3', 'n03'],
                  labels=[
                      'f_{NL}', 'b1', '10^{7}n_{0}', 'b2', '10^{7}n_{0}2',
                      'b3', '10^{7}n_{0}3'
                  ],
                  settings=stg)
    read_kw3 = dict(ndim=7, iscale=[2, 4, 6])

    xlim = None

    with PdfPages('figs/fnl2d_dr9_regions.pdf') as pdf:

        for r in ['bmzls', 'ndecals', 'sdecals']:

            noweight = MCMC(
                f'/fs/ess/PHS0336/data/rongpu/imaging_sys/mcmc/0.57.0/mcmc_lrg_zero_{r}_noweight_steps10k_walkers50.npz',
                mc_kw=mc_kw,
                read_kw=read_kw)
            nnknown = MCMC(
                f'/fs/ess/PHS0336/data/rongpu/imaging_sys/mcmc/0.57.0/mcmc_lrg_zero_{r}_nn_known_steps10k_walkers50.npz',
                mc_kw=mc_kw,
                read_kw=read_kw)
            nnall = MCMC(
                f'/fs/ess/PHS0336/data/rongpu/imaging_sys/mcmc/0.57.0/mcmc_lrg_zero_{r}_nn_all_steps10k_walkers50.npz',
                mc_kw=mc_kw,
                read_kw=read_kw)

            # Triangle plot
            g = plots.get_single_plotter(width_inch=4 * 1.5)
            g.settings.legend_fontsize = 14
            g.plot_2d([noweight, nnknown, nnall], 'fnl', 'b', filled=True)
            g.add_legend(['No Correction', 'Conservative', 'Extreme'],
                         colored_text=True,
                         title=titles[r])
            g.subplots[0, 0].set_ylim((1.23, 1.6))
            add_scale(g.subplots[0, 0])
            g.fig.align_labels()
            pdf.savefig(bbox_inches='tight')
Exemple #3
0
 def test_styles(self):
     tmp = rcParams.copy()
     plots.set_active_style(tab10)
     g = plots.get_single_plotter()
     self.assertEqual(g.settings.line_styles.name, 'tab10')
     plots.set_active_style(planck)
     g = plots.get_single_plotter()
     self.assertTrue(g.settings.prob_y_ticks)
     plots.set_active_style(tab10)
     g = plots.get_single_plotter()
     self.assertEqual(g.settings.line_styles.name, 'tab10')
     plots.set_active_style()
     g = plots.get_single_plotter()
     self.assertFalse(g.settings.prob_y_ticks)
     g = plots.get_single_plotter(style='tab10')
     self.assertEqual(g.settings.line_styles.name, 'tab10')
     plots.set_active_style('planck')
     plots.set_active_style()
     self.assertDictEqual(tmp, rcParams)
Exemple #4
0
def plot_lfs_kde(cmd_list):
    g = plots.get_single_plotter(width_inch=2 * 3.464, ratio=0.75)
    colors = ['k']
    colors.extend(['r'] * (len(cmd_list) - 1))
    ct = 0
    for cmd in cmd_list:
        cmd_samples = MCSamples(samples=cmd, names=['color', 'mag'])
        if ct > 0:
            g.settings.linewidth = 0.5
        g.plot_1d(cmd_samples, 'mag', colors=[colors[ct]])
        ct += 1
Exemple #5
0
def Plot2D_Omegak(results_dir):
    labels = [
        "base_omegak_plikHM_TTTEEE_lowl_lowE",
        "base_omegak_plikHM_TTTEEE_lowl_lowE_BAO"
    ]
    datasets = [LoadDataset(label) for label in labels]
    
    g = plots.get_single_plotter(width_inch=5)
    g.settings.legend_frame = False
    g.plot_2d(datasets, ['omegak', 'omegam'], filled=True)
    g.add_legend(["PlikHM TTTEEE+lowl+lowE", "+BAO"], frameon=False)
    g.export(str(results_dir / "2D_omegak_omegam.pdf"))
    return 
Exemple #6
0
def Plot3D_Omegak_Omegam_H0(results_dir):
    labels = [
        "base_omegak_plikHM_TTTEEE_lowl_lowE",
        "base_omegak_plikHM_TTTEEE_lowl_lowE_BAO"
    ]
    datasets = [LoadDataset(label) for label in labels]

    g = plots.get_single_plotter(width_inch=5)
    g.settings.legend_frame = False
    g.plots_3d(datasets, [['omegak', 'omegam', 'H0'], ['omegak', 'omegam', 'H0']], nx=2, legend_labels=["PlikHM TTTEEE+lowl+lowE", "+BAO"], legend_ncol=2)
    #g.add_legend(["PlikHM TTTEEE+lowl+lowE", "+BAO"])
    g.export(str(results_dir / '3D_omega_k_omegam_h0.pdf'))
    return 
Exemple #7
0
 def test_styles(self):
     from getdist.styles.tab10 import style_name as tab10
     from getdist.styles.planck import style_name as planck
     from matplotlib import rcParams
     tmp = rcParams.copy()
     plots.set_active_style(tab10)
     g = plots.get_single_plotter()
     self.assertEqual(g.settings.line_styles.name, 'tab10')
     plots.set_active_style(planck)
     g = plots.get_single_plotter()
     self.assertTrue(g.settings.prob_y_ticks)
     plots.set_active_style(tab10)
     g = plots.get_single_plotter()
     self.assertEqual(g.settings.line_styles.name, 'tab10')
     plots.set_active_style()
     g = plots.get_single_plotter()
     self.assertFalse(g.settings.prob_y_ticks)
     g = plots.get_single_plotter(style='tab10')
     self.assertEqual(g.settings.line_styles.name, 'tab10')
     plots.set_active_style('planck')
     plots.set_active_style()
     self.assertDictEqual(tmp, rcParams)
Exemple #8
0





plt.close()
from getdist import plots, MCSamples
import getdist

samples1 = MCSamples(samples=samp1.T,names=['x1','x2','x3','x4','x5','x6','x7'], labels=names, label=r'True $n(z)$, $\Delta \chi^2 = 0.0$', weights=c1.weight, settings={'boundary_correction_order':0, 'mult_bias_correction_order':1})
samples2 = MCSamples(samples=samp2.T,names=['x1','x2','x3','x4','x5','x6','x7'], labels=names, label=r'wrong $n(z)$, $\Delta \chi^2 = 3.0$ ', weights=c2.weight, settings={'boundary_correction_order':0, 'mult_bias_correction_order':1})
samples3 = MCSamples(samples=samp3.T,names=['x1','x2','x3','x4','x5','x6','x7'], labels=names, label=r'wrong $n(z)$, $\Delta \chi^2 = 7.0$', weights=c3.weight, settings={'boundary_correction_order':0, 'mult_bias_correction_order':1})
samples4 = MCSamples(samples=samp4.T,names=['x1','x2','x3','x4','x5','x6','x7'], labels=names, label=r'wrong $n(z)$, $\Delta \chi^2 = 14$', weights=c4.weight, settings={'boundary_correction_order':0, 'mult_bias_correction_order':1})

gd = plots.get_single_plotter(width_inch=6, ratio=1)
gd.settings.legend_fontsize = 16
gd.settings.fontsize = 18
gd.settings.axes_fontsize = 16
gd.settings.axes_labelsize = 20
gd.settings.axis_tick_max_labels = 15
gd.settings.linewidth = 1.5
gd.settings.legend_colored_text=True
gd.settings.axis_tick_step_groups = [[2.5, 3, 4, 6, 8],[1, 2, 5, 10]]


col0 = ['#DDA0DD', '#FA86C9','#000000','#4682b4']
#['#8B0000','#8b008b','#191970','#FF69B4','#000000']
gd.triangle_plot([samples1, samples2, samples3, samples4],['x1','x2','x3','x4','x5','x6','x7'], filled=[True,False,False,False,False,False], contour_args=[{'alpha':0.6},{'alpha':1.},{'alpha':1.},{'alpha':1.}, {'alpha':1}, {'alpha':1}],contour_colors=['#7223AD','#3775A1','#A4CD64','#FF69B4','#A4CD64']) #, param_limits={'x1':(-2.5,5), 'x2':(-5,5), 'x3':(-5,5)})
#gd.plot_2d([samples1, samples2,samples3,samples4,samples5],['x1','x2'], filled=[True,True,True,True,False], colors=['#8B0000','#8b008b','#4682b4','#FF69B4','#000000' ], lims=[-1.5,4.5,-5.5,4])
#gd.add_legend(['redMaGiC high-$z$','redMaGiC low-$z$','eBOSS ELGs','eBOSS LRGs','DES Y3'], legend_loc='lower right');
Exemple #9
0
                                        r'\mathcal{M}_{\rm c}'], \
                                ranges={'a_1':(0.0, 0.8), \
                                        'iota':(0.0, np.pi), \
                                        'q':(0.02, 0.6), \
                                        'lambda_2':(0.0, 4000.0)}))

# snr-ordered colouring
n_targets = len(samples)
cm = mpcm.get_cmap('plasma')
cols = [mpc.rgb2hex(cm(x)) for x in np.linspace(0.2, 0.8, n_targets)[::-1]]

# generate figure and axes
n_col = 5
n_row = 8
fig, axes = mp.subplots(n_row, n_col, figsize=(20, 30))
g = gdp.get_single_plotter()

# set up points at which we want to plot the base run
i_xy_base = [[0, 1], [1, 0], [2, 1], [4, 4], [6, 4]]

# nummbers of different variants
n_spin_mag = 4
n_spin_dir = 2
n_inc = 5
n_q = 6

# @TODO
# 3 - credible intervals?

# plot spin magnitude variants
spin_mags = np.sqrt(targets['spin1x'] ** 2 + \
Exemple #10
0
def plot_lf(cmd):
    cmd_samples = MCSamples(samples=cmd, names=['color', 'mag'])
    g = plots.get_single_plotter(width_inch=2 * 3.464, ratio=0.75)
    g.plot_1d(cmd_samples, 'mag')
samp2 = np.array([
    c2.samples['cosmological_parameters--omega_m'],
    c2.samples['cosmological_parameters--s8']
])
samp3 = np.array([
    c3.samples['cosmological_parameters--omega_m'],
    c3.samples['cosmological_parameters--s8']
])
names = [r'$\Omega_{\rm m}$', r'$S_8$']

plt.close()
from getdist import plots, MCSamples
import getdist
import matplotlib.pyplot as plt

g = plots.get_single_plotter(width_inch=6, ratio=0.8)
g.settings.legend_fontsize = 12
g.settings.fontsize = 18
g.settings.axes_fontsize = 18
g.settings.axes_labelsize = 22
g.settings.axis_tick_max_labels = 15
g.settings.linewidth = 1.5
g.settings.legend_colored_text = True
g.settings.axis_tick_step_groups = [[2.5, 3, 4, 6, 8], [1, 2, 5, 10]]

samples1 = MCSamples(samples=samp1.T,
                     names=['x1', 'x2'],
                     labels=names,
                     label='DES Y3',
                     weights=c1.weight,
                     settings={
dirname = r'/home/nayantara/Desktop/Cosmology_Dvorkin/Project_Cosmology/Cosmo212/Results_JLA/OL2/'
names = ['omegam', 'omegal']
labels = ['\Omega_m', '\Omega_\Lambda']

for ch in range(Num_chains):
    itns = np.loadtxt(dirname + 'chfinal_' + str(ch) + '.txt')
    print(itns.shape)
    start = int(itns.shape[0] * burnin)
    matlist.append(itns[start:, :])
mat = np.vstack(matlist)
#mat[:, 1] = mat[:, 1]*100 #for hubble
samp_sne = MCSamples(samples=mat, names=names, labels=labels)

#Planck plotting (alone)
g = plots.get_single_plotter(
    chain_dir=
    r'/home/nayantara/Desktop/Cosmology_Dvorkin/Project_Cosmology/Datasets/Combined chains/chains_FL2'
)
roots = ['base_plikHM_TTTEEE_lowl_lowE_lensing']
pairs = [['omegam', 'H0']]
g.plots_2d(roots, param_pairs=pairs, filled=True, shaded=False)
g.export()

#Planck
names = ['omegam', 'H0']
labels = ['\Omega_m', 'H_0']
mat_pl = np.loadtxt('base_plikHM_TTTEEE_lowl_lowE_lensing_1.txt',
                    usecols=(29, 31))  #has 96 columns
names_pl = np.loadtxt('base_plikHM_TTTEEE_lowl_lowE_lensing.paramnames',
                      dtype=str,
                      delimiter=';')  #has 94 columns
samp_pl = MCSamples(samples=mat_pl, names=names, labels=labels)
Exemple #13
0
    samples = mcsamples.loadMCSamples(
        "{}/multinest".format(optimizer_directory))

    def get_params(samples):

        params = [name for name in samples.paramNames.names]

        return params
        # if str(name).startswith(
        #     "galaxies_{}".format(galaxy)
        # )

    params = get_params(samples=samples)

    plotter = plots.get_single_plotter(width_inch=16)
    plotter.triangle_plot(
        samples,
        filled=True,
    )
    plt.show()

    # #print(samples.samples.shape);exit()
    # fig = corner.corner(
    #     xs=samples.samples[:, 0:6],
    #     weights=samples.weights,
    #     bins=20,
    #     colors="b",
    #     truths=truths[0:6],
    #     labels=labels,
    #     smooth=1.0,
    v["progress"].plot(x="N",
                       y="Rminus1",
                       ax=ax[1],
                       color=colors[i],
                       legend=False,
                       logy=True)
plt.legend(results.keys())
plt.savefig(os.path.join(chain_dir, "progress.png"))

# Distributions of alpha posteriors
from getdist import plots

samples = [v["sample"] for k, v in results.items()]
line_args = [{"ls": "-", "color": colors[i]} for i in range(len(samples))]

g = plots.get_single_plotter(ratio=1, width_inch=6)
g.plot_1d(samples, "alpha", line_args=line_args)
plt.xlabel(r"$\alpha$ [deg.]")
plt.legend(results.keys())
plt.savefig(os.path.join(chain_dir, "posteriors.png"))

# Print mean and variance values
mean_mcmc = [result["sample"].getMeans()[0] for result in results.values()]
std_mcmc = [
    np.sqrt(result["sample"].getVars()[0]) for result in results.values()
]

df = pd.DataFrame(
    {
        "mean MCMC": mean_mcmc,
        "std. MCMC": std_mcmc,
Exemple #15
0
import matplotlib.pyplot as plt
# import IPython
import numpy as np
from global_tools import *

names = [
    "gamma", "log_{10}(g)", "log_{10}(M[GeV])", "N_a", "N_conv", "N_pr", "N_mu"
]
labels = [
    "gamma", "log_{10}(g)", "log_{10}(M[GeV])", "N_a", "N_conv", "N_pr", "N_mu"
]

gamma, log10_g, log10_M, N_a, N_conv, N_pr, N_mu, something_1, something_2, \
    something_3 = Read_Data_File(os.getcwd()+'/out/likelihood/ev.dat')

samps = np.array([gamma, log10_g, log10_M, N_a, N_conv, N_pr, N_mu]).T

samples = MCSamples(samples=samps, names=names, labels=labels)

plt.figure()
g = plots.get_single_plotter()
samples.updateSettings({
    'contours': [0.68, 0.90],
    'fine_bins_2D': 20,
    'smooth_scale_2D': 0.6
})
g.settings.num_plot_contours = 2
g.plot_2d(samples, 'log_{10}(M[GeV])', 'log_{10}(g)', shaded=True)
plt.plot(-1.94, -1.16, 'X', color='black', markersize=14)
g.export(os.getcwd() + '/out/plots/gMmarg.png')
Exemple #16
0
def plot_mcmc_mocks():
    stg = {
        'mult_bias_correction_order': 0,
        'smooth_scale_2D': 0.15,
        'smooth_scale_1D': 0.3,
        'contours': [0.68, 0.95]
    }
    mc_kw = dict(names=['fnl', 'b', 'n0'],
                 labels=['f_{NL}', 'b', '10^{7}n_{0}'],
                 settings=stg)

    read_kw = dict(ndim=3, iscale=[2])
    mc_kw2 = dict(names=['fnl', 'b', 'n0', 'b2', 'n02'],
                  labels=['f_{NL}', 'b1', '10^{7}n_{0}', 'b2', '10^{7}n_{0}2'],
                  settings=stg)
    read_kw2 = dict(ndim=5, iscale=[2, 4])
    mc_kw3 = dict(names=['fnl', 'b', 'n0', 'b2', 'n02', 'b3', 'n03'],
                  labels=[
                      'f_{NL}', 'b1', '10^{7}n_{0}', 'b2', '10^{7}n_{0}2',
                      'b3', '10^{7}n_{0}3'
                  ],
                  settings=stg)
    read_kw3 = dict(ndim=7, iscale=[2, 4, 6])
    fs = MCMC(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_fullsky_noweight_steps10k_walkers50.npz',
        mc_kw=mc_kw,
        read_kw=read_kw)
    bm = MCMC(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_bmzls_noweight_steps10k_walkers50.npz',
        mc_kw=mc_kw,
        read_kw=read_kw)
    nd = MCMC(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_ndecals_noweight_steps10k_walkers50.npz',
        mc_kw=mc_kw,
        read_kw=read_kw)
    sd = MCMC(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_sdecals_noweight_steps10k_walkers50.npz',
        mc_kw=mc_kw,
        read_kw=read_kw)
    bn = MCMC(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_bmzlsndecals_noweight_steps10k_walkers50.npz',
        mc_kw=mc_kw2,
        read_kw=read_kw2)
    joint = MCMC(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_bmzlsndecalssdecals_noweight_steps10k_walkers50.npz',
        mc_kw=mc_kw3,
        read_kw=read_kw3)

    stats = {}
    stats['Full Sky'] = read_chain(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_fullsky_noweight_steps10k_walkers50.npz',
        **read_kw)[0]
    stats['F. Sky [BMzLS scaled]'] = read_chain(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_fullskyscaled_noweight_steps10k_walkers50.npz',
        **read_kw)[0]
    stats['BASS/MzLS'] = read_chain(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_bmzls_noweight_steps10k_walkers50.npz',
        **read_kw)[0]
    stats['DECaLS North'] = read_chain(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_ndecals_noweight_steps10k_walkers50.npz',
        **read_kw)[0]
    stats['DECaLS South'] = read_chain(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_sdecals_noweight_steps10k_walkers50.npz',
        **read_kw)[0]

    stats['NGC'] = read_chain(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_ngc_noweight_steps10k_walkers50.npz',
        **read_kw)[0]
    stats['Joint (BMzLS+DECaLS N)'] = read_chain(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_bmzlsndecals_noweight_steps10k_walkers50.npz',
        **read_kw2)[0]

    stats['Joint (DECaLS N+DECaLS S)'] = read_chain(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_ndecalssdecals_noweight_steps10k_walkers50.npz',
        **read_kw2)[0]
    stats['DESI'] = read_chain(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_desi_noweight_steps10k_walkers50.npz',
        **read_kw)[0]
    stats['Joint (BMzLS+DECaLS)'] = read_chain(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_zero_bmzlsndecalssdecals_noweight_steps10k_walkers50.npz',
        **read_kw3)[0]

    # Triangle plot
    g = plots.get_single_plotter(width_inch=4 * 1.5)
    g.settings.legend_fontsize = 14

    g.plot_2d([bm, nd, sd, fs], 'fnl', 'b', filled=False)
    g.add_x_marker(0)
    g.add_y_marker(1.43)
    g.add_legend(['BASS/MzLS', 'DECaLS North', 'DECaLS South', 'Full Sky'],
                 colored_text=True,
                 legend_loc='lower left')
    #prsubplots(g.subplots[0, 0].get_xlim())
    # g.subplots[0, 0].set_xticklabels([])
    g.fig.align_labels()
    g.fig.savefig('figs/fnl2dmocks_area.pdf', bbox_inches='tight')

    # Triangle plot
    g = plots.get_single_plotter(width_inch=4 * 1.5)
    g.settings.legend_fontsize = 14

    g.plot_1d([bm, bn, joint], 'fnl', filled=False)
    g.add_x_marker(0)
    # g.add_y_marker(1.4262343145500318)
    g.add_legend([
        'BASS/MzLS', 'BASS/MzLs+DECaLS North', 'BASS/MzLS+DECaLS (North+South)'
    ],
                 colored_text=True)

    g.subplots[0, 0].set_xticks([-100, -75, -50, -25, 0, 25., 50.])
    # g.subplots[0, 0].set_xticklabels([])
    g.fig.align_labels()
    g.fig.savefig('figs/fnl1dmocks_joint.pdf', bbox_inches='tight')

    pstats = pd.DataFrame(stats,
                          index=[
                              'MAP [scipy]', 'MAP [chain]', 'Mean [chain]',
                              'Median [chain]', '16th', '84th'
                          ]).T

    bm = MCMC(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_po100_bmzls_noweight_steps10k_walkers50.npz',
        mc_kw=mc_kw,
        read_kw=read_kw)
    nd = MCMC(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_po100_ndecals_noweight_steps10k_walkers50.npz',
        mc_kw=mc_kw,
        read_kw=read_kw)
    sd = MCMC(
        '/fs/ess/PHS0336/data/lognormal/v2/mcmc/mcmc_lrg_po100_sdecals_noweight_steps10k_walkers50.npz',
        mc_kw=mc_kw,
        read_kw=read_kw)

    # Triangle plot
    g = plots.get_single_plotter(width_inch=4 * 1.5)
    g.settings.legend_fontsize = 14

    g.plot_2d([bm, nd, sd], 'fnl', 'b', filled=False)
    g.add_x_marker(100)
    g.add_y_marker(1.43)
    g.add_legend(['BASS/MzLS', 'DECaLS North', 'DECaLS South'],
                 colored_text=True,
                 legend_loc='lower left')
    #prsubplots(g.subplots[0, 0].get_xlim())
    # g.subplots[0, 0].set_xticklabels([])
    g.fig.align_labels()
    g.fig.savefig('figs/fnl2dmocks_po100.pdf', bbox_inches='tight')
    return pstats
Exemple #17
0
    def testPlots(self):
        self.samples = self.testdists.bimodal[0].MCSamples(12000, logLikes=True, random_state=10)
        g = plots.get_single_plotter(auto_close=True)
        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.new_plot()
        g.plot_1d(samples, 'y', normalized=True, marker=0.1, marker_color='b')
        g.new_plot()
        g.plot_2d(samples, 'x', 'y')
        g.new_plot()
        g.plot_2d(samples, 'x', 'y', filled=True)
        g.new_plot()
        g.plot_2d(samples, 'x', 'y', shaded=True)
        g.new_plot()
        g.plot_2d_scatter(samples, 'x', 'y', color='red', colors=['blue'])
        g.new_plot()
        g.plot_3d(samples, ['x', 'y', 'z'])

        g = plots.get_subplot_plotter(width_inch=8.5, auto_close=True)
        g.plots_1d(samples, ['x', 'y'], share_y=True)
        g.new_plot()
        g.triangle_plot(samples, ['x', 'y', 'z'])
        self.assertTrue(g.get_axes_for_params('x', 'z') == g.subplots[2, 0])
        self.assertTrue(g.get_axes_for_params('z', 'x', ordered=False) == g.subplots[2, 0])
        self.assertTrue(g.get_axes_for_params('x') == g.subplots[0, 0])
        self.assertTrue(g.get_axes_for_params('x', 'p', 'q') is None)
        self.assertTrue(g.get_axes(ax=('x', 'z')) == g.subplots[2, 0])
        self.assertTrue(g.get_axes(ax=(2, 0)) == g.subplots[2, 0])

        g.new_plot()
        g.triangle_plot(samples, ['x', 'y'], plot_3d_with_param='z')
        g.new_plot()
        g.rectangle_plot(['x', 'y'], ['z'], roots=samples, filled=True)
        prob2 = self.testdists.bimodal[1]
        samples2 = prob2.MCSamples(12000, random_state=10)
        g.new_plot()
        g.triangle_plot([samples, samples2], ['x', 'y'])
        g.new_plot()
        g.plots_2d([samples, samples2], param_pairs=[['x', 'y'], ['x', 'z']])
        g.new_plot()
        g.plots_2d([samples, samples2], 'x', ['z', 'y'])
        g.new_plot()
        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_plot_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')
        g.new_plot()
        omm = np.arange(0.1, 0.7, 0.01)
        g.add_bands(omm, 0.589 * omm ** (-0.25), 0.03 * omm ** (-0.25), nbands=3)

        g = plots.get_subplot_plotter()
        import copy
        for upper in [False, True]:
            g.triangle_plot([samples, samples2], ['x', 'y', 'z'], filled=True,
                            upper_roots=[copy.deepcopy(samples)], upper_kwargs={'contour_colors': ['green']},
                            legend_labels=['1', '2', '3'], upper_label_right=upper)
            for i in range(3):
                for j in range(i):
                    self.assertTrue(g.subplots[i, j].get_xlim() == g.subplots[j, i].get_ylim())
                    self.assertTrue(g.subplots[i, j].get_ylim() == g.subplots[j, i].get_xlim())
                    self.assertTrue(g.subplots[i, j].get_xlim() == g.subplots[j, j].get_xlim())
Exemple #18
0
def make_single_plot(chainfile,
                     savefile,
                     chainfile2=None,
                     pi1=0,
                     pi2=3,
                     true_parameter_values=None,
                     ranges=None,
                     string=True,
                     burnin=10000):
    """Make a getdist plot"""
    ticks = {}
    if string:
        pnames = [
            r"G\mu", r"\mathrm{StMBBH}", r"\mathrm{IMRI}", r"\mathrm{EMRI}"
        ]
    else:
        pnames = [
            r"T_\ast", r"\mathrm{StMBBH}", r"\mathrm{IMRI}", r"\mathrm{EMRI}",
            r"\alpha"
        ]  #, r"\beta"]
    prange = None
    if ranges is not None:
        prange = {pnames[i]: ranges[i] for i in range(len(pnames))}
    print("Sim=", savefile)
    subplot_instance = gdp.get_single_plotter()
    samples = np.loadtxt(chainfile)
    posterior_MCsamples = gd.MCSamples(samples=samples[burnin:],
                                       names=pnames,
                                       labels=pnames,
                                       label='',
                                       ranges=prange)
    if chainfile2 is not None:
        samples2 = np.loadtxt(chainfile2)
        posterior2 = gd.MCSamples(samples=samples2[burnin:],
                                  names=pnames,
                                  labels=pnames,
                                  label='',
                                  ranges=prange)
        subplot_instance.plot_2d([posterior_MCsamples, posterior2],
                                 pnames[pi1],
                                 pnames[pi2],
                                 filled=True)
        subplot_instance.add_legend(["LIGO+LISA", "LIGO+LISA+TianGo"])
    else:
        subplot_instance.plot_2d([posterior_MCsamples],
                                 pnames[pi1],
                                 pnames[pi2],
                                 filled=True)


#     colour_array = np.array(['black', 'red', 'magenta', 'green', 'green', 'purple', 'turquoise', 'gray', 'red', 'blue'])
#Ticks we want to show for each parameter
    if string:
        ticks = {
            pnames[0]: [
                np.log(1e-17),
                np.log(2e-17),
                np.log(5e-17),
                np.log(1e-16),
                np.log(2e-16),
                np.log(5e-16),
                np.log(1e-15)
            ]
        }
        ticklabels = {
            pnames[0]: [
                r"$10^{-17}$", r"$2\times 10^{-17}$", r"$5\times 10^{-17}$",
                r"$10^{-16}$", r"$2\times 10^{-16}$", r"$5\times 10^{-16}$",
                r"$10^{-15}$"
            ]
        }
    else:
        ticks = {
            pnames[0]: [
                np.log(1e3),
                np.log(2e3),
                np.log(5e3),
                np.log(1e4),
                np.log(2e4),
                np.log(5e4)
            ]
        }  #, np.log(1e6)]}#, np.log(1e11)
        #pnames[4]: [np.log(1e-4), np.log(1e-3), np.log(1e-2), np.log(0.1), 0]}
        ticklabels = {
            pnames[0]: [
                r"$10^{3}$", r"$2\times 10^3$", r"$5\times 10^3$", r"$10^{4}$",
                r"$2\times 10^4$", r"$5\times 10^{4}$"
            ]
        }  #, r"$10^{6}$"]}#, r"$10^{11}$"]},

    #Place horizontal and vertical lines for the true point
    ax = subplot_instance.subplots[0, 0]
    ax.yaxis.label.set_size(16)
    ax.xaxis.label.set_size(16)
    if pnames[pi2] in ticks:
        ax.set_yticks(ticks[pnames[pi2]])
        ax.set_yticklabels(ticklabels[pnames[pi2]])
    if pnames[pi1] in ticks:
        ax.set_xticks(ticks[pnames[pi1]])
        ax.set_xticklabels(ticklabels[pnames[pi1]])
    ax.axhline(true_parameter_values[pi2], color='gray', ls='--', lw=2)
    ax.axvline(true_parameter_values[pi1], color='gray', ls='--', lw=2)
    plt.savefig(savefile)