Exemple #1
0
def plot_dist_corner_getdist(samples,
                             labels=None,
                             names=None,
                             filled=True,
                             sample_labels=None):
    if isinstance(samples, (list, tuple)):
        if sample_labels is None:
            sample_labels = [
                'samples {0:d}'.format(i) for i in range(len(samples))
            ]
        samps = [
            MCSamples(samples=samples0,
                      names=names,
                      labels=labels,
                      label=str(slabels0))
            for samples0, slabels0 in zip(samples, sample_labels)
        ]
        g = plots.get_subplot_plotter()
        g.triangle_plot(samps, filled=filled)
    else:
        samps = MCSamples(samples=samples, names=names, labels=labels)
        g = plots.get_subplot_plotter()
        g.triangle_plot(samps, filled=filled)
    plt.show()
    return None
Exemple #2
0
    def testMixtures(self):
        from getdist.gaussian_mixtures import Mixture2D, GaussianND

        cov1 = [[0.001 ** 2, 0.0006 * 0.05], [0.0006 * 0.05, 0.05 ** 2]]
        cov2 = [[0.01 ** 2, -0.005 * 0.03], [-0.005 * 0.03, 0.03 ** 2]]
        mean1 = [0.02, 0.2]
        mean2 = [0.023, 0.09]
        mixture = Mixture2D([mean1, mean2], [cov1, cov2], names=['zobs', 't'], labels=[r'z_{\rm obs}', 't'],
                            label='Model')
        tester = 0.03
        cond = mixture.conditionalMixture(['zobs'], [tester])
        marge = mixture.marginalizedMixture(['zobs'])
        # test P(x,y) = P(y)P(x|y)
        self.assertAlmostEqual(mixture.pdf([tester, 0.15]), marge.pdf([tester]) * cond.pdf([0.15]))

        samples = mixture.MCSamples(3000, label='Samples', random_state=10)
        g = plots.get_subplot_plotter()
        g.triangle_plot([samples, mixture], filled=False)
        g.new_plot()
        g.plot_1d(cond, 't')

        s1 = 0.0003
        covariance = [[s1 ** 2, 0.6 * s1 * 0.05, 0], [0.6 * s1 * 0.05, 0.05 ** 2, 0.2 ** 2], [0, 0.2 ** 2, 2 ** 2]]
        mean = [0.017, 1, -2]
        gauss = GaussianND(mean, covariance)
        g = plots.get_subplot_plotter()
        g.triangle_plot(gauss, filled=True)
Exemple #3
0
    def test_specifics(self):
        testdists = Test2DDistributions()
        samples = testdists.bimodal[0].MCSamples(1000, logLikes=True, random_state=10)
        g = plots.get_subplot_plotter(auto_close=True)
        g.settings.prob_label = r'$P$'
        g.settings.prob_y_ticks = True
        g.plot_1d(samples, 'x', _no_finish=True)
        ax = g.get_axes()
        self.assertTrue(np.allclose(ax.get_yticks(), [0, 0.5, 1]), "Wrong probability ticks")

        def check_ticks(bounds, expected):
            ax.set_xlim(bounds)
            ticks = ax.get_xticks()
            if len(ticks) != len(expected) or not np.allclose(ticks, expected):
                raise self.failureException("Wrong ticks %s for bounds %s" % (ticks, bounds))

        check_ticks([-5.2, 5.2], [-4, -2, 0, 2, 4])
        check_ticks([0, 8.2], [0, 2, 4, 6, 8])
        check_ticks([0.0219, 0.02232], [0.022, 0.0222])
        check_ticks([-0.009, 0.009], [-0.008, 0., 0.008])
        g.make_figure(nx=2, ny=1, sharey=True)
        ax = g.get_axes()
        g._set_main_axis_properties(ax.xaxis, True)
        ax.set_yticks([])
        check_ticks([-0.009, 0.009], [-0.006, 0., 0.006])
        check_ticks([1, 1.0004], [1.0001, 1.0003])
Exemple #4
0
def newGraph_Confidence(result):
    H_0 = [ii[0] for ii in result]
    omega_m0 = [ii[1] for ii in result]
    omega_q0 = [ii[2] for ii in result]
    alpha = [ii[3] for ii in result]
    alpha_x = [ii[4] for ii in result]
    m = [ii[5] for ii in result]

    names = [
        "H_0", "\Omega_{m_0}", "\Omega_{Q_0}", r"\tilde{\alpha}",
        r"\tilde{\alpha}_x", "m"
    ]
    #names = ["H_0"]
    labels = names

    newShape = [H_0, omega_m0, omega_q0, alpha, alpha_x, m]
    #newShape = [H_0]
    values = np.array(newShape).T
    #print(values.shape)
    s1 = MCSamples(samples=values, names=names, labels=labels)
    g = plots.get_subplot_plotter()
    s1.updateSettings({'contours': [0.68, 0.95, 0.99]})
    g.settings.colormap = "binary"
    g.settings.num_plot_contours = 3
    g.triangle_plot([s1], shaded=True, title_limit=1)

    plt.savefig("result.pdf")
Exemple #5
0
def Eval(model, q_x_z, training_dataset, results_dir):
    approximate_posterior = training_dataset.copy(label=r"$q_x(x)$")
    approximate_posterior.samples = q_x_z.sample(training_dataset.samples.shape[0]).numpy()

    g = plots.get_subplot_plotter(width_inch=6.5)
    g.triangle_plot([training_dataset, approximate_posterior], ['omegabh2', 'omegach2', 'theta', 'tau', 'omegak', 'logA', 'ns'], filled=True)
    g.export(str(results_dir / "densities" / "corner.pdf"))

    return 
Exemple #6
0
    def plot3D(self, pp, colorn=None, contour_num=2, **kwargs):
        if colorn:
            colorss = colors[colorn - 1:colorn - 1 + self._n]
        else:
            colorss = None

        if pp == 0:
            t_name = self.param_names
        else:
            t_name = []
            for i in pp:
                t_name.append(self.param_names[i - 1])
        g = plots.get_subplot_plotter(width_inch=9)
        g.settings.num_plot_contours = contour_num
        g.settings.legend_fontsize = 20
        g.settings.axes_fontsize = 14
        g.settings.lab_fontsize = 18
        g.settings.figure_legend_frame = False
        g.settings.alpha_filled_add = 0.8
        if all(self.lengend):
            print(t_name)
            g.triangle_plot(self.Samp,
                            t_name,
                            filled_compare=True,
                            legend_labels=self.lengend,
                            contour_colors=colorss,
                            legend_loc='upper right',
                            **kwargs)
        else:
            g.triangle_plot(self.Samp,
                            t_name,
                            filled_compare=True,
                            contour_colors=colorss,
                            **kwargs)
        if 'tline' in kwargs:
            for ax in g.subplots[:, 0]:
                ax.axvline(kwargs['tline'], color='k', ls='--', alpha=0.5)


#        plt.tight_layout()
        if 'ax_range' in kwargs:
            for axi in kwargs['ax_range']:
                g.subplots[-1, axi[0] - 1].xaxis.set_major_locator(
                    plt.MultipleLocator(axi[1]))
                if axi[0] - 1 > 0:
                    g.subplots[axi[0] - 1, 0].yaxis.set_major_locator(
                        plt.MultipleLocator(axi[1]))
        if 'xlim' in kwargs:
            for xi in kwargs['xlim']:
                for ax in g.subplots[:, xi[0] - 1]:
                    if ax is not None:
                        ax.set_xlim(xi[1][0], xi[1][1])
        if 'name' in kwargs:
            g.export(os.path.join(outdir, '%s.pdf' % kwargs['name']))
        else:
            g.export(os.path.join(outdir, ''.join(self.root) + '_tri.pdf'))
        return g
Exemple #7
0
def cornerplot(sampledf, weights=None, labels=None, markers=None, ranges=None):
    names = sampledf.columns
    samples = MCSamples(samples=sampledf.to_numpy(),
                        names=names,
                        weights=weights,
                        labels=labels,
                        ranges=ranges)
    #samples.updateSettings({'contours': [0.68, 0.95, 0.99]})
    g = plots.get_subplot_plotter()
    return g.triangle_plot(samples, filled=True, markers=markers)
Exemple #8
0
def Plot1D_Omegak_H0_Omegam(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_subplot_plotter(width_inch=5)
    g.settings.figure_legend_frame = False
    g.plots_1d(datasets, ['omegak', 'H0', 'omegam'], nx=3, legend_labels=["PlikHM TTTEEE+lowl+lowE", "+BAO"], legend_ncol=2)
    g.export(str(results_dir / "1D_omegak_H0_omegam.pdf"))
    return 
Exemple #9
0
def plot_corner(results, outprefix=None, **kwargs):
    """
    Store a simple corner plot in outprefix_corner.pdf, based on samples
    extracted from fit.

    Additional kwargs are passed to MCSamples.
    """
    la = get_flat_posterior(results)
    samples = []
    paramnames = []
    badlist = ['lp__']
    badlist += [
        k for k in la.keys()
        if 'log' in k and k.replace('log', '') in la.keys()
    ]

    for k in sorted(la.keys()):
        print('%20s: %.4f +- %.4f' % (k, la[k].mean(), la[k].std()))
        if k not in badlist and la[k].ndim == 2:
            samples.append(la[k])
            paramnames.append(k)

    if len(samples) == 0:
        arrays = [
            k for k in la.keys()
            if la[k].ndim == 3 and la[k].shape[2] <= 20 and k not in badlist
        ]
        if len(arrays) != 1:
            warnings.warn("no scalar variables found")
            return

        k = arrays[0]
        # flatten across chains and column for each variable
        samples = la[k]
        paramnames = ['%s[%d]' % (k, i + 1) for i in range(la[k].shape[1])]

    samples = numpy.transpose(samples)
    import matplotlib.pyplot as plt
    from getdist import MCSamples, plots
    settings = kwargs.pop('settings', dict(smooth_scale_2D=3.0))
    samples_g = MCSamples(samples=samples,
                          names=paramnames,
                          settings=settings,
                          **kwargs)
    g = plots.get_subplot_plotter()
    g.settings.num_plot_contours = 3
    g.triangle_plot([samples_g],
                    filled=False,
                    contour_colors=plt.cm.Set1.colors)
    if outprefix is not None:
        plt.savefig(outprefix + '_corner.pdf', bbox_inches='tight')
        plt.close()
Exemple #10
0
def plot_multicomp_velo_2corr(store,
                              group_name,
                              outname='velo_2corr',
                              truths=None):
    group = store.hdf[group_name]
    ncomp = group.attrs['ncomp']
    assert ncomp == 2
    n_params = store.hdf.attrs['n_params']
    post = group['posteriors'][...][:, :-2]  # param values
    par_names = store.model.get_par_names(ncomp)
    ix_v = store.model.IX_VCEN
    ix_s = store.model.IX_SIGM
    par_labels = [''] * n_params * ncomp
    par_labels[ncomp *
               ix_v] = r'$v_\mathrm{lsr}\, (1) \ [\mathrm{km\,s^{-1}}]$'
    par_labels[ncomp * ix_v +
               1] = r'$v_\mathrm{lsr}\, (2) \ [\mathrm{km\,s^{-1}}]$'
    par_labels[ncomp *
               ix_s] = r'$\sigma_\mathrm{v}\, (1) \ [\mathrm{km\,s^{-1}}]$'
    par_labels[ncomp * ix_s +
               1] = r'$\sigma_\mathrm{v}\, (2) \ [\mathrm{km\,s^{-1}}]$'
    samples = getdist.MCSamples(samples=post,
                                names=par_names,
                                labels=par_labels,
                                sampler='nested')
    samples.updateSettings({'contours': [0.68, 0.90]})
    fig = gd_plt.get_subplot_plotter()
    x_names = ['v1', 's1']
    y_names = ['v2', 's2']
    if truths is not None:
        xmarkers = {k: truths[k] for k in x_names}
        ymarkers = {k: truths[k] for k in y_names}
    else:
        xmarkers, ymarkers = None, None
    fig.rectangle_plot(x_names,
                       y_names,
                       roots=samples,
                       filled=True,
                       line_args={
                           'lw': 2,
                           'color': 'peru'
                       },
                       xmarkers=xmarkers,
                       ymarkers=ymarkers)
    fig.export(f'{outname}.pdf')
    plt.close('all')
def triangulo(datos, labels = []):
    '''
    DESCRIPTION: Esta funcion realiza una grafica triangular para visualizar los resultados
    IN: datos = lista con puntos de datos (cada uno es una lista con valores para cada parametro)
        labels = nombre de los parametros (default p_i)
    OUT: Grafica triangular con histogramas 1d y 2d de todas la combinaciones
    '''
    g = plots.get_subplot_plotter(subplot_size=2)
    
    #Checamos si se asignó nombre a los parametros
    if labels!=[]:
        samples = MCSamples(samples=np.array(datos), labels = labels, names = labels)
    
    else:
        samples = MCSamples(samples=np.array(datos))
    
    #graficamos
    g.triangle_plot(samples, filled=True, title_limit=1)
Exemple #12
0
def plot_corner(group, outname='corner', truths=None):
    ncomp = group.attrs['ncomp']
    par_labels = ammonia.TEX_LABELS.copy()
    par_labels[3] = r'$\log(N) \ [\log(\mathrm{cm^{-2}})]$'
    n_params = group.attrs['n_params'] // ncomp
    names = ammonia.get_par_names()
    post = group['posteriors'][...][:, :-2]  # posterior param values
    if truths is not None:
        markers = {
            p: truths[i * ncomp:(i + 1) * ncomp]
            for i, p in zip(range(n_params), ammonia.get_par_names())
        }
    else:
        markers = None
    # Give each model component parameter set its own sampler object so that
    # each can be over-plotted in its own color.
    samples = [
        getdist.MCSamples(samples=post[:, ii::ncomp],
                          names=names,
                          labels=par_labels,
                          label=f'Component {ii+1}',
                          name_tag=f'{ii}',
                          sampler='nested') for ii in range(ncomp)
    ]
    [s.updateSettings({'contours': [0.68, 0.90]}) for s in samples]
    fig = gd_plt.get_subplot_plotter()
    fig.triangle_plot(
        samples,
        filled=True,
        line_args=[{
            'lw': 2,
            'color': 'tab:orange'
        }, {
            'lw': 2,
            'color': 'tab:blue'
        }, {
            'lw': 2,
            'color': 'tab:green'
        }],
        markers=markers,
    )
    fig.export(f'{outname}.pdf')
    plt.close('all')
Exemple #13
0
def plot_corner(store, group_name, outname='corner', truths=None):
    n_params = store.hdf.attrs['n_params']
    par_names = store.model.get_par_names()
    par_labels = store.hdf.attrs['tex_labels_with_units']
    group = store.hdf[group_name]
    ncomp = group.attrs['ncomp']
    post = group['posteriors'][...][:, :-2]  # posterior param values
    if truths is not None:
        markers = {
            p: truths[i * ncomp:(i + 1) * ncomp]
            for i, p in zip(range(n_params), par_names)
        }
    else:
        markers = None
    # Give each model component parameter set its own sampler object so that
    # each can be over-plotted in its own color.
    samples = [
        getdist.MCSamples(samples=post[:, ii::ncomp],
                          names=par_names,
                          labels=par_labels,
                          label=f'Component {ii+1}',
                          name_tag=f'{ii}',
                          sampler='nested') for ii in range(ncomp)
    ]
    [s.updateSettings({'contours': [0.68, 0.90]}) for s in samples]
    fig = gd_plt.get_subplot_plotter()
    fig.triangle_plot(
        samples,
        filled=True,
        line_args=[{
            'lw': 2,
            'color': 'tab:orange'
        }, {
            'lw': 2,
            'color': 'tab:blue'
        }, {
            'lw': 2,
            'color': 'tab:green'
        }],
        markers=markers,
    )
    fig.export(f'{outname}.pdf')
    plt.close('all')
Exemple #14
0
def triangle_plot(list_of_obj, **kwargs):

    # if isinstance(list_of_obj, list):
    #     for obj in list_of_obj:
    #         print(obj.sampler)
    #     exit()

    plotter = plots.get_subplot_plotter(width_inch=12, )

    # NOTE:
    plotter.settings.num_plot_contours = 2

    plotter.triangle_plot(list_of_obj,
                          legend_labels=kwargs["legend_labels"],
                          line_args=kwargs["line_args"],
                          contour_args=kwargs["contour_args"],
                          markers=kwargs["markers"],
                          legend_loc='upper right',
                          legend_kwargs={"fontsize": 20})
Exemple #15
0
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from getdist import plots

mpl.use("Agg")

freq = [90, 150, 220]
spec_in_freq = {}
spec_in_freq[90] = ["dr6_pa5_f090", "dr6_pa6_f090"]
spec_in_freq[150] = ["dr6_pa4_f150", "dr6_pa5_f150", "dr6_pa6_f150"]
spec_in_freq[220] = ["dr6_pa4_f220"]

for f in freq:

    roots = []
    for spec in spec_in_freq[f]:
        roots += ["mcmc_%s" % spec]
    params = ["eps_min", "lmax", "beta"]

    g = plots.get_subplot_plotter(
        chain_dir=os.path.join(os.getcwd(), "chains"),
        analysis_settings={"ignore_rows": 0.3},
    )
    kwargs = dict(colors=["k"], lws=[1])
    g.triangle_plot(roots, params, **kwargs, diag1d_kwargs=kwargs)
    g.subplots[0, 0].plot([], [], color="k", label="PSpipe")
    g.subplots[0, 0].legend(loc="upper left", bbox_to_anchor=(1, 1))
    plt.savefig("chain_results_%s.png" % f)
Exemple #16
0
                                    'm1': [mod1low, mod1up],
                                    'm2': [mod2low, mod2up]
                                })  #,weights=1/10**first)#,loglikes=like)
        else:
            samples = MCSamples(samples=samps,
                                names=names,
                                labels=labels,
                                ranges={'m1': [mod1low, mod1up]})
    elif (np.any(il == 5)):
        ai, = np.where(il == 5)
        names[ai] = 'm2'
        samples = MCSamples(samples=samps,
                            names=names,
                            labels=labels,
                            ranges={'m2': [mod2low, mod2up]})  #,loglikes=like)
    g = plots.get_subplot_plotter(width_inch=7.5)
    g.settings.axes_fontsize = 20
    g.settings.axes_labelsize = 20
    g.triangle_plot([samples], filled=True, color='red')
    mpl.show()
    print(r"Confidence interval at 2$\sigma$")
    print(samples.getTable().tableTex())

elif total == 3:
    first = data[:, il[0]]
    second = data[:, il[1]]
    third = data[:, il[2]]
    samps = np.column_stack((first, second, third))
    ndim = 3
    names = np.array(["x%s" % i for i in range(ndim)])
    labels = label[il]
Exemple #17
0
#%%
%matplotlib qt5
ndim = 4
names = ['M_{abs}','\Omega_{m}','b','H_{0}']
labels=names
samples1 = MCSamples(samples=samples_1,names = names, labels = labels,ranges={'b':[0, None]})
samples1 = samples1.copy(label=r'Lowest-order with $0.3\sigma$ smoothing',
             settings={'mult_bias_correction_order':0,'smooth_scale_2D':0.3, 'smooth_scale_1D':0.3})

samples2 = MCSamples(samples=samples_2,names = names, labels = labels,ranges={'b':[0, None]})
samples2 = samples2.copy(label=r'Lowest-order with $0.3\sigma$ smoothing',
             settings={'mult_bias_correction_order':0,'smooth_scale_2D':0.3, 'smooth_scale_1D':0.3})

samples3 = MCSamples(samples=samples_3,names = names, labels = labels,ranges={'b':[0, None]})
samples3 = samples3.copy(label=r'Lowest-order with $0.3\sigma$ smoothing',
             settings={'mult_bias_correction_order':0,'smooth_scale_2D':0.3, 'smooth_scale_1D':0.3})
samples0 = MCSamples(samples=samples_0,names = names, labels = labels,ranges={'b':[0, None]})
samples0 = samples0.copy(label=r'Lowest-order with $0.3\sigma$ smoothing',
             settings={'mult_bias_correction_order':0,'smooth_scale_2D':0.3, 'smooth_scale_1D':0.3})


g = plots.get_subplot_plotter()
g.triangle_plot([samples0, samples1, samples2, samples3],
                contour_colors=['grey','g','r','b'],
                filled=True, params = names ,
                contour_lws=1.5,
#                param_limits = dict
                legend_labels = ['CC+SN', 'CC+SN+AGN', 'CC+SN+BAO','CC+SN+BAO+AGN'])

plt.savefig('/home/matias/Desktop/contornos_EXP.png')
Exemple #18
0
def plot_contours_dynesty(chaintags,
                          legend_labels=None,
                          params_toplot=None,
                          colors=None,
                          legend_loc='upper center',
                          legend_fontsize=20,
                          vertical_markers=None,
                          vertical_marker_color='grey'):
    bounds = utils.get_emulator_bounds()
    sample_arr = []
    for i, chaintag in enumerate(chaintags):

        chain_fn = f'../chains/chains_{chaintag}.h5'
        fw = h5py.File(chain_fn, 'r')
        param_names = fw.attrs['param_names']
        if vertical_markers is None:
            vertical_markers_toplot = fw.attrs['true_values']
        else:
            vertical_markers_toplot = vertical_markers
        fw.close()

        pickle_fn = f'{pickle_dir}/results_{chaintag}.pkl'
        with open(pickle_fn, 'rb') as pf:
            res = pickle.load(pf)
            samples = res['samples']
            lnweight = np.array(res['logwt'])
            lnevidence = np.array(res['logz'])

        if params_toplot is not None:
            idxs = []
            for pm in params_toplot:
                idxs.append(np.where(param_names == pm))
            idxs = np.array(idxs).flatten()
            samples = samples[:, idxs]
            # weight and evidence are for all parameters, shape (n_samps,)
            # so don't need to slice
            param_names = params_toplot
            vertical_markers_toplot = vertical_markers_toplot[idxs]

        labels = [param_labels[pn] for pn in param_names]
        ranges = [bounds[pn] for pn in param_names]

        #[-1] bc just care about final evidence value
        weights = np.exp(lnweight - lnevidence[-1])
        weights = weights.flatten()

        samps = MCSamples(names=param_names, labels=labels)
        samps.setSamples(samples, weights=weights)
        sample_arr.append(samps)

    marker_args = {'color': vertical_marker_color}

    g = plots.get_subplot_plotter()
    g.settings.alpha_filled_add = 0.4
    g.settings.figure_legend_frame = False
    g.settings.legend_fontsize = legend_fontsize
    g.settings.axis_marker_lw = 1.0
    g.settings.axis_marker_color = 'dimgrey'
    g.triangle_plot(sample_arr,
                    filled=True,
                    contour_colors=colors,
                    names=param_names,
                    legend_labels=legend_labels,
                    markers=vertical_markers_toplot,
                    title_limit=1,
                    legend_loc=legend_loc,
                    marker_args=marker_args,
                    axis_marker_color='red')
    return g
Exemple #19
0
def plot_contours(chaintags,
                  legend_labels=None,
                  params_toplot=None,
                  nsteps=None,
                  colors=None,
                  legend_loc='upper center',
                  legend_fontsize=20,
                  weight_with_dynesty=False):

    bounds = utils.get_emulator_bounds()
    sample_arr = []
    for i, chaintag in enumerate(chaintags):

        resample_chains = False
        if 'dynesty' in chaintag:
            resample_chains = True
            assert not (nsteps != None and resample_chains
                        ), "if resampling, shouldn't be selecting nsteps!"

        chain_fn = f'../chains/chains_{chaintag}.h5'
        fw = h5py.File(chain_fn, 'r')

        chain_dset = fw['chain']
        chain = np.array(chain_dset)
        print(chaintag, ':', chain.shape)
        if nsteps:
            chain = chain[:, :nsteps, :]

        lnprob_dset = fw['lnprob']
        param_names = fw.attrs['param_names']
        true_values = fw.attrs['true_values']

        if params_toplot is not None:
            idxs = []
            for pm in params_toplot:
                idxs.append(np.where(param_names == pm))
            idxs = np.array(idxs).flatten()
            chain = chain[:, :, idxs]
            param_names = params_toplot
            true_values = true_values[idxs]

        nwalkers, nchain, ndim = chain.shape

        samples = chain.reshape(-1, chain.shape[-1])
        labels = [param_labels[pn] for pn in param_names]
        ranges = [bounds[pn] for pn in param_names]

        if resample_chains:
            lnweight_dset = fw['lnweight']
            lnevidence_dset = fw['lnevidence']
            #[-1] bc just care about final evidence value
            lnweight = np.array(lnweight_dset)[0]  #[0] bc an extra array dim
            lnevidence = np.array(lnevidence_dset)[0]
            weights = np.exp(lnweight - lnevidence[-1])
            weights = weights.flatten()

            samples = np.empty((nchain, ndim))
            for nd in range(ndim):
                cn = chain[:, :, nd].flatten()
                if weight_with_dynesty:
                    samples[:, nd] = dynesty.utils.resample_equal(cn, weights)
                else:
                    samples[:, nd] = cn
        else:
            weights = None

        fw.close()

        if weight_with_dynesty:
            weights = None

        # have not gotten ranges to work
        samps = MCSamples(names=param_names, labels=labels, ranges=ranges)
        # for some reason get slightly diff answer if don't use setSamples and pass them straight to MCSamples!
        samps.setSamples(samples, weights=weights)
        sample_arr.append(samps)

    g = plots.get_subplot_plotter()
    g.settings.alpha_filled_add = 0.4
    g.settings.figure_legend_frame = False
    g.settings.legend_fontsize = legend_fontsize
    g.settings.axis_marker_lw = 1.0
    g.settings.axis_marker_color = 'dimgrey'
    g.triangle_plot(
        sample_arr,
        filled=True,
        contour_colors=colors,
        names=param_names,
        legend_labels=legend_labels,
        markers=true_values,
        title_limit=1,
        legend_loc=legend_loc,
        #marker_args={'color': 'orange', 'lw':1.5}
    )
    return g
Exemple #20
0
# Export the results to GetDist
from getdist.mcsamples import MCSamplesFromCobaya

gd_sample = MCSamplesFromCobaya(updated_info, sampler.products()["sample"])
# Analyze and plot
mean = gd_sample.getMeans()[:2]
covmat = gd_sample.getCovMat().matrix[:2, :2]
print("Mean:")
print(mean)
print("Covariance matrix:")
print(covmat)
# %matplotlib inline  # uncomment if running from the Jupyter notebook
import getdist.plots as gdplt

gdplot = gdplt.get_subplot_plotter()
gdplot.triangle_plot(gd_sample, ["a", "b"], filled=True)
Exemple #21
0
def run_test_program(plots=('dists_2D', 'dists_1D'),
                     sims=100,
                     nsamp=default_nsamp,
                     mbc=1,
                     bco=1):
    import time

    chains.print_load_details = False
    plt.rc("ytick", direction="in")
    plt.rc("xtick", direction="in")

    test1D = Test1DDistributions()
    test2D = Test2DDistributions()
    test_settings = {
        'mult_bias_correction_order': mbc,
        'boundary_correction_order': bco,
        'smooth_scale_1D': -1,
        'smooth_scale_2D': -1
    }
    g = get_subplot_plotter(subplot_size=2)

    colors = ['k', 'C0', 'C1', 'C2', 'C3', 'C4']

    if 'ISE_1D' in plots:
        compare_method(test1D.distributions(),
                       nx=3,
                       test_settings=[
                           {
                               'mult_bias_correction_order': 1,
                               'boundary_correction_order': 1
                           },
                           {
                               'mult_bias_correction_order': 2,
                               'boundary_correction_order': 1
                           },
                           {
                               'mult_bias_correction_order': 0,
                               'boundary_correction_order': 0
                           },
                           {
                               'mult_bias_correction_order': 0,
                               'boundary_correction_order': 1
                           },
                           {
                               'mult_bias_correction_order': 0,
                               'boundary_correction_order': 2
                           },
                       ],
                       colors=colors,
                       linestyles=['-', '-', ':', '-.', '--'],
                       fname='compare_method_1d_N%s.pdf' % nsamp,
                       sims=sims,
                       nsamp=nsamp)

    if 'ISE_2D' in plots:
        compare_method(test2D.distributions(),
                       nx=4,
                       test_settings=[
                           {
                               'mult_bias_correction_order': 1,
                               'boundary_correction_order': 1
                           },
                           {
                               'mult_bias_correction_order': 2,
                               'boundary_correction_order': 1
                           },
                           {
                               'mult_bias_correction_order': 0,
                               'boundary_correction_order': 0
                           },
                           {
                               'mult_bias_correction_order': 0,
                               'boundary_correction_order': 1
                           },
                       ],
                       colors=colors,
                       linestyles=['-', '-', ':', '-.', '--'],
                       fname='compare_method_2d_N%s.pdf' % nsamp,
                       sims=sims,
                       nsamp=nsamp)

    if plots is None or 'dists_1D' in plots:
        g.new_plot()
        start = time.time()
        compare1D(g,
                  test1D.distributions(),
                  nsamp=nsamp,
                  settings=test_settings)
        print('1D timing:', time.time() - start)
        join_subplots(g.subplots)
        plt.savefig('test_dists_1D_mbc%s_bco%s_N%s.pdf' % (mbc, bco, nsamp),
                    bbox_inches='tight')

    if plots is None or 'dists_2D' in plots:
        g.new_plot()
        start = time.time()
        compare2D(g,
                  test2D.distributions(),
                  nsamp=nsamp,
                  settings=test_settings)
        print('2D timing:', time.time() - start)
        join_subplots(g.subplots)
        plt.savefig('test_dists_2D_mbc%s_bco%s_N%s.pdf' % (mbc, bco, nsamp),
                    bbox_inches='tight')
from getdist import plots
import matplotlib.pyplot as plt

g = plots.get_subplot_plotter(chain_dir=r'/home/app/Git/LCDM-NS/cobaya')
roots = []
roots.append('cobaya without SSIM/run')
roots.append('cobaya with SSIM - CSD3/run')
roots.append('cobaya with iPPR - CSD3/run')
# roots.append('cobaya with SSIM - PC/run')
params = ['logA', 'n_s', 'theta_s_1e2', 'omega_b', 'omega_cdm', 'tau_reio']
g.triangle_plot(roots, params, filled=True, colors=['blue', 'grey', 'red'])
g.export()
plt.savefig('../illustrations/cosmology.pdf')
plt.show()

roots = []
roots.append('cobaya with SSIM - CSD3/run')
# roots.append('cobaya with iPPR - CSD3/run')
# roots.append('cobaya without SSIM/run')
roots.append('cobaya with SSIM - PC/run')
params = ['logA', 'n_s', 'theta_s_1e2', 'omega_b', 'omega_cdm', 'tau_reio']
g.triangle_plot(roots, params, filled=True, colors=['grey', 'orange'])
g.export()
plt.savefig('../illustrations/cosmo-pc.pdf')
plt.show()
Exemple #23
0
                               ranges={'d':(d_min, d_max), \
                                       'm_1':(m_min_bh, m_max_bh), \
                                       'm_2':(m_min_ns, m_max_ns), \
                                       'm_c':(m_c_min, m_c_max), \
                                       'q_inv':(q_inv_min, q_inv_max)}, \
                               label='SMF Priors')
        bgw_gds = gd.MCSamples(samples=bgw_samples, \
                               names=['d', 'm_1', 'm_2', 'm_c', 'q_inv'], \
                               labels=[r'D_L', 'm_1', 'm_2', 'M_c', '1/q'], \
                               ranges={'d':(d_min, d_max), \
                                       'm_1':(m_min_bh_bgw, m_max_bh_bgw), \
                                       'm_2':(m_min_ns_bgw, m_max_ns_bgw), \
                                       'm_c':(m_c_min, m_c_max), \
                                       'q_inv':(q_inv_min, q_inv_max)}, \
                               label='Bilby Priors')
        g = gdp.get_subplot_plotter()
        g.settings.lw_contour = lw
        cm = mpcm.get_cmap('plasma')
        g.triangle_plot([bgw_gds, smf_gds], filled=True, \
                        line_args=[{'lw':lw, 'color':'C0'}, \
                                   {'lw':lw, 'color':'C1'}], \
                        colors=['C0', 'C1'])
        n_pars = smf_samples.shape[1]
        for i in range(n_pars):
            for j in range(0, i + 1):
                g.subplots[i, j].grid(False)
        plot_file = outdir + '/' + label + '_bilby_prior_comp.pdf'
        g.export(plot_file)
        exit()

# calculate tidal deformabilities for all NSs
def main(args):

    np.random.seed(2)
    Ndata = args.ndata
    jitter_true = 0.1
    phase_true = 2.0
    period_true = 180
    amplitude_true = args.contrast / Ndata * jitter_true
    paramnames = ['amplitude', 'jitter', 'phase', 'period']
    ndim = len(paramnames)
    
    x = np.linspace(0, 360, 1000)
    y = amplitude_true * sin(x / period_true * 2 * pi + phase_true)
    
    if True:
        plt.plot(x, y)
        x = np.random.uniform(0, 360, Ndata)
        y = np.random.normal(amplitude_true * sin(x / period_true * 2 * pi + phase_true), jitter_true)
        plt.errorbar(x, y, yerr=jitter_true, marker='x', ls=' ')
        plt.savefig('testsine.pdf', bbox_inches='tight')
        plt.close()
    
    
    def loglike(params):
        amplitude, jitter, phase, period = params
        predicty = amplitude * sin(x / period * 2 * pi + phase)
        logl = (-0.5 * log(2 * pi * jitter**2) - 0.5 * ((predicty - y) / jitter)**2).sum()
        return logl
    
    def transform(x):
        z = np.empty_like(x)
        z[0] = 10**(x[0] * 4 - 2)
        z[1] = 10**(x[1] * 1 - 1.5)
        z[2] = 2 * pi * x[2]
        z[3] = 10**(x[3] * 4 - 1)
        #z[:,4] = 2 * pi / x[:,3]
        return z

    loglike(transform(np.ones(ndim)*0.5))
    
    from snowline import ReactiveImportanceSampler
    
    sampler = ReactiveImportanceSampler(paramnames, loglike, transform=transform)
    
    sampler.run()
    
    sampler.print_results()
    
    from getdist import MCSamples, plots

    samples_g = MCSamples(samples=sampler.results['samples'],
                           names=sampler.results['paramnames'],
                           label='Gaussian',
                           settings=dict(smooth_scale_2D=3), sampler='nested')

    mcsamples = [samples_g]
    g = plots.get_subplot_plotter(width_inch=8)
    g.settings.num_plot_contours = 3
    g.triangle_plot(mcsamples, filled=False, contour_colors=plt.cm.Set1.colors)
    plt.savefig('testsine_posterior.pdf', bbox_inches='tight')
    plt.close()
Exemple #25
0
# Just plotting (loading on-the-fly)
import getdist.plots as gdplt
import os

folder, name = os.path.split(os.path.abspath(info["output"]))
gdplot = gdplt.get_subplot_plotter(chain_dir=folder)
gdplot.triangle_plot(name, ["a", "b"], filled=True)
Exemple #26
0
#samples = loadMCSamples(chainLoadSample, settings={'ignore_rows':0.3})
# It was already burned
samples = loadMCSamples(chainLoadSample)

# C5::
# PDF files of the posteriors:
posteriors = download_dir + posteriors_dir + fileStr + "_histograms.pdf"

# C6::
# PDF files of the confidence regions files:
confidenceL = download_dir + confidenceL_dir + fileStr + "_confidence.pdf"

# C7::
# Multiple 1D subplots

g = plots.get_subplot_plotter(width_inch=10)

# Plot and save to a file:
g.plots_1d(samples, ['p1', 'p2', 'p3', 'p4', 'p5', 'p6'], nx=6)
g.export(posteriors)

# C8::
# Multiple 2D subplots
g = plots.get_subplot_plotter(subplot_size=2.0)
g.settings.scaling = False  # prevent scaling down font sizes even though small subplots

# Plot and save to a file:
g.plots_2d(samples,
           param_pairs=[['p1', 'p2'], ['p1', 'p3'], ['p1', 'p4'], ['p2', 'p3'],
                        ['p2', 'p4'], ['p3', 'p4']],
           nx=6,
plt.subplots_adjust(bottom=0.175, left=0.175, hspace=0, wspace=0)

print('Saving...')
plt.savefig(
    '/Users/hattifattener/Documents/y3cosmicshear/plots/1x2pt_external_maglim.pdf'
)
plt.savefig(
    '/Users/hattifattener/Documents/y3cosmicshear/plots/1x2pt_external_maglim.png'
)

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

g = plots.get_subplot_plotter()  #(width_inch=6, ratio=1)
g.settings.legend_fontsize = 18
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]]

samples = MCSamples(samples=samp0.T,
                    names=['x1', 'x2', 'x3'],
                    labels=names,
                    label='DES Y3',
                    weights=c0.weight,
                    settings={
Exemple #28
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())