Ejemplo n.º 1
0
def test_manual_columns():
    old_params = ['x0', 'x1', 'x2', 'x3', 'x4']
    mcmc_params = ['logL']
    ns_params = ['logL', 'logL_birth', 'nlive']
    mcmc = MCMCSamples(root='./tests/example_data/gd')
    ns = NestedSamples(root='./tests/example_data/pc')
    assert_array_equal(mcmc.columns, old_params + mcmc_params)
    assert_array_equal(ns.columns, old_params + ns_params)

    new_params = ['y0', 'y1', 'y2', 'y3', 'y4']
    mcmc = MCMCSamples(root='./tests/example_data/gd', columns=new_params)
    ns = NestedSamples(root='./tests/example_data/pc', columns=new_params)
    assert_array_equal(mcmc.columns, new_params + mcmc_params)
    assert_array_equal(ns.columns, new_params + ns_params)
Ejemplo n.º 2
0
def test_plotting_with_integer_names():
    np.random.seed(3)
    samples_1 = MCMCSamples(data=np.random.rand(1000, 3))
    samples_2 = MCMCSamples(data=np.random.rand(1000, 3))
    fig, ax = samples_1.plot_2d([0, 1, 2])
    samples_2.plot_2d(ax)

    fig, ax = samples_1.plot_1d([0, 1, 2])
    samples_2.plot_1d(ax)

    assert samples_1[0].shape == (1000,)
    assert_array_equal(samples_1.loc[:, 0], samples_1[0])
    assert_array_equal(samples_1.loc[:, 0], samples_1.iloc[:, 0])
    with pytest.raises(KeyError):
        samples_1['0']
Ejemplo n.º 3
0
def test_weighted_merging():
    # Generate some data to try it out:
    samples_1 = NestedSamples(root='./tests/example_data/pc')
    samples_2 = NestedSamples(root='./tests/example_data/pc_250')
    samples_1['xtest'] = 7*samples_1['x3']
    samples_2['xtest'] = samples_2['x3']
    mean1 = samples_1.mean()['xtest']
    mean2 = samples_2.mean()['xtest']

    # Test with evidence weights
    weight1 = np.exp(samples_1.logZ())
    weight2 = np.exp(samples_2.logZ())
    samples = merge_samples_weighted([samples_1, samples_2])
    mean = samples.mean()['xtest']
    assert np.isclose(mean, (mean1*weight1+mean2*weight2)/(weight1+weight2))

    # Test with explicit weights
    weight1 = 31
    weight2 = 13
    samples = merge_samples_weighted(
        [samples_1, samples_2], weights=[weight1, weight2])
    mean = samples.mean()['xtest']
    assert np.isclose(mean, (mean1*weight1+mean2*weight2)/(weight1+weight2))

    # Test if correct exceptions are raised:
    # MCMCSamples are passed without weights
    with pytest.raises(ValueError):
        merge_samples_weighted([MCMCSamples(samples_1)])
    # len(weights) != len(samples)
    with pytest.raises(ValueError):
        merge_samples_weighted([samples_1, samples_2], weights=[1, 2, 3])
    # A samples is passed and not a sequence
    with pytest.raises(TypeError):
        merge_samples_weighted(samples_1, weights=[1, 2, 3])
Ejemplo n.º 4
0
def test_root_and_label():
    np.random.seed(3)
    ns = NestedSamples(root='./tests/example_data/pc')
    assert(ns.root == './tests/example_data/pc')
    assert(ns.label == 'pc')

    ns = NestedSamples()
    assert(ns.root is None)
    assert(ns.label is None)

    mc = MCMCSamples(root='./tests/example_data/gd')
    assert (mc.root == './tests/example_data/gd')
    assert(mc.label == 'gd')

    mc = MCMCSamples()
    assert(mc.root is None)
    assert(mc.label is None)
Ejemplo n.º 5
0
def test_to_getdist():
    try:
        anesthetic_samples = MCMCSamples(root='./tests/example_data/gd')
        getdist_samples = to_getdist(anesthetic_samples)

        assert_array_equal(getdist_samples.samples, anesthetic_samples)
        assert_array_equal(getdist_samples.weights, anesthetic_samples.weights)

        for param, p in zip(getdist_samples.getParamNames().names,
                            anesthetic_samples.columns):
            assert param.name == p
    except ModuleNotFoundError:
        pass
Ejemplo n.º 6
0
def test_weighted_merging():
    # Generate some data to try it out:
    samples_1 = NestedSamples(root='./tests/example_data/pc')
    samples_2 = NestedSamples(root='./tests/example_data/pc_250')
    samples_1['xtest'] = 7*samples_1['x3']
    samples_2['xtest'] = samples_2['x3']
    samples_1.tex['xtest'] = "$x_{t,1}$"
    samples_2.tex['xtest'] = "$x_{t,2}$"
    mean1 = samples_1.mean()['xtest']
    mean2 = samples_2.mean()['xtest']

    # Test with evidence weights
    weight1 = np.exp(samples_1.logZ())
    weight2 = np.exp(samples_2.logZ())
    samples = merge_samples_weighted([samples_1, samples_2],
                                     label='Merged label')
    mean = samples.mean()['xtest']
    assert np.isclose(mean, (mean1*weight1+mean2*weight2)/(weight1+weight2))

    # Test tex and label
    for key in samples.keys():
        if key in samples_2.keys():
            assert samples.tex[key] == samples_2.tex[key]
        else:
            assert samples.tex[key] == samples_1.tex[key]
    assert samples.label == 'Merged label'

    # Test that label is None when no label is passed
    samples_1.label = "1"
    samples_2.label = "2"
    samples = merge_samples_weighted([samples_1, samples_2])
    assert samples.label is None

    # Test with explicit weights
    weight1 = 31
    weight2 = 13
    samples = merge_samples_weighted(
        [samples_1, samples_2], weights=[weight1, weight2])
    mean = samples.mean()['xtest']
    assert np.isclose(mean, (mean1*weight1+mean2*weight2)/(weight1+weight2))

    # Test if correct exceptions are raised:
    # MCMCSamples are passed without weights
    with pytest.raises(ValueError):
        merge_samples_weighted([MCMCSamples(samples_1)])
    # len(weights) != len(samples)
    with pytest.raises(ValueError):
        merge_samples_weighted([samples_1, samples_2], weights=[1, 2, 3])
    # A samples is passed and not a sequence
    with pytest.raises(TypeError):
        merge_samples_weighted(samples_1, weights=[1, 2, 3])
Ejemplo n.º 7
0
def test_MCMCSamples_importance_sample():
    np.random.seed(3)
    mc0 = MCMCSamples(root='./tests/example_data/gd')

    with pytest.raises(NotImplementedError):
        mc0.importance_sample(mc0.logL, action='spam')

    mc_masked = mc0.importance_sample(mc0.logL, action='replace')
    assert_array_equal(mc0.logL, mc_masked.logL)
    assert_array_equal(mc0.weights, mc_masked.weights)

    mc_masked = mc0.importance_sample(np.zeros_like(mc0.logL), action='add')
    assert_array_equal(mc0.logL, mc_masked.logL)
    assert_array_equal(mc0.weights, mc_masked.weights)

    mask = ((mc0.x0 > -0.3) & (mc0.x2 > 0.2) & (mc0.x4 < 3.5)).to_numpy()
    mc_masked = mc0[mask]

    mc1 = mc0.importance_sample(mask, action='mask')
    assert_array_equal(mc_masked.logL, mc1.logL)
    assert_array_equal(mc_masked.weights, mc1.weights)
    assert mc0.tex == mc1.tex
    assert mc0.limits == mc1.limits
    assert mc0.root == mc1.root
    assert mc0.label == mc1.label
    assert mc1._metadata == mc0._metadata
    assert mc0 is not mc1
    assert mc0.tex is not mc1.tex
    assert mc0.limits is not mc1.limits

    mc0.importance_sample(mask, action='mask', inplace=True)
    assert type(mc0) is MCMCSamples
    assert_array_equal(mc0, mc1)
    assert mc0.tex == mc1.tex
    assert mc0.limits == mc1.limits
    assert mc0.root == mc1.root
    assert mc0.label == mc1.label
    assert mc1._metadata == mc0._metadata
    assert mc0 is not mc1
    assert mc0.tex is not mc1.tex
    assert mc0.limits is not mc1.limits
Ejemplo n.º 8
0
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)
Ejemplo n.º 9
0
def test_build_mcmc():
    numpy.random.seed(3)
    nsamps = 1000
    ndims = 3
    samples = numpy.random.randn(nsamps, ndims)
    logL = numpy.random.rand(nsamps)
    w = numpy.random.randint(1, 20, size=nsamps)
    params = ['A', 'B', 'C']
    tex = {'A': '$A$', 'B': '$B$', 'C': '$C$'}
    limits = {'A': (-1, 1), 'B': (-2, 2), 'C': (-3, 3)}

    mcmc = MCMCSamples(data=samples)
    assert (len(mcmc) == nsamps)
    assert_array_equal(mcmc.columns, numpy.array([0, 1, 2], dtype=object))

    mcmc = MCMCSamples(data=samples, logL=logL)
    assert (len(mcmc) == nsamps)
    assert_array_equal(mcmc.columns,
                       numpy.array([0, 1, 2, 'logL'], dtype=object))

    mcmc = MCMCSamples(data=samples, w=w)
    assert (len(mcmc) == nsamps)
    assert_array_equal(mcmc.columns,
                       numpy.array([0, 1, 2, 'weight'], dtype=object))

    mcmc = MCMCSamples(data=samples, w=w, logL=logL)
    assert (len(mcmc) == nsamps)
    assert_array_equal(mcmc.columns,
                       numpy.array([0, 1, 2, 'logL', 'weight'], dtype=object))

    mcmc = MCMCSamples(data=samples, columns=params)
    assert (len(mcmc) == nsamps)
    assert_array_equal(mcmc.columns, ['A', 'B', 'C'])

    mcmc = MCMCSamples(data=samples, tex=tex)
    for p in params:
        assert (mcmc.tex[p] == tex[p])

    mcmc = MCMCSamples(data=samples, limits=limits)
    for p in params:
        assert (mcmc.limits[p] == limits[p])

    assert (mcmc.root is None)
Ejemplo n.º 10
0
def test_plot_1d_colours():
    np.random.seed(3)
    gd = MCMCSamples(root="./tests/example_data/gd")
    gd.drop(columns='x3', inplace=True)
    pc = NestedSamples(root="./tests/example_data/pc")
    pc.drop(columns='x4', inplace=True)
    mn = NestedSamples(root="./tests/example_data/mn")
    mn.drop(columns='x2', inplace=True)

    plot_types = ['kde', 'hist']
    if 'astropy' in sys.modules:
        plot_types += ['astropyhist']
    if 'fastkde' in sys.modules:
        plot_types += ['fastkde']

    for plot_type in plot_types:
        fig = plt.figure()
        fig, axes = make_1d_axes(['x0', 'x1', 'x2', 'x3', 'x4'], fig=fig)
        gd.plot_1d(axes, plot_type=plot_type, label="gd")
        pc.plot_1d(axes, plot_type=plot_type, label="pc")
        mn.plot_1d(axes, plot_type=plot_type, label="mn")
        gd_colors = []
        pc_colors = []
        mn_colors = []
        for x, ax in axes.iteritems():
            handles, labels = ax.get_legend_handles_labels()
            for handle, label in zip(handles, labels):
                if isinstance(handle, Rectangle):
                    color = to_hex(handle.get_facecolor())
                else:
                    color = handle.get_color()

                if label == 'gd':
                    gd_colors.append(color)
                elif label == 'pc':
                    pc_colors.append(color)
                elif label == 'mn':
                    mn_colors.append(color)

        assert(len(set(gd_colors)) == 1)
        assert(len(set(mn_colors)) == 1)
        assert(len(set(pc_colors)) == 1)
        plt.close("all")
Ejemplo n.º 11
0
def test_MCMCSamples_importance_sample():
    np.random.seed(3)
    mc0 = MCMCSamples(root='./tests/example_data/gd')

    with pytest.raises(NotImplementedError):
        mc0.importance_sample(mc0.logL, action='spam')

    # new gaussian logL
    logL_i = norm.logpdf(mc0.x3, loc=0.4, scale=0.1)

    # add logL
    mc1 = mc0.importance_sample(np.zeros_like(mc0.logL), action='add')
    assert_array_equal(mc0.logL, mc1.logL)
    assert_array_equal(mc0.weights, mc1.weights)
    mc1 = mc0.importance_sample(logL_new=logL_i)
    assert np.all(mc1.logL.to_numpy() != mc0.logL.to_numpy())
    assert not np.all(mc1.weights == mc0.weights)

    # replace logL
    mc2 = mc0.importance_sample(mc0.logL, action='replace')
    assert_array_equal(mc0.logL, mc2.logL)
    assert_array_equal(mc0.weights, mc2.weights)
    mc2 = mc0.importance_sample(mc0.logL.to_numpy()+logL_i, action='replace')
    assert np.all(mc2.logL.to_numpy() != mc0.logL.to_numpy())
    assert not np.all(mc2.weights == mc0.weights)
    assert_array_equal(mc1.logL.to_numpy(), mc2.logL.to_numpy())
    assert_array_almost_equal(mc1.logL.to_numpy(), mc2.logL.to_numpy())

    # mask logL
    mask = ((mc0.x0 > -0.3) & (mc0.x2 > 0.2) & (mc0.x4 < 3.5)).to_numpy()
    mc_masked = mc0[mask]
    mc3 = mc0.importance_sample(mask, action='mask')
    assert_array_equal(mc_masked.logL, mc3.logL)
    assert_array_equal(mc_masked.weights, mc3.weights)
    assert np.all(mc3.x0 > -0.3)

    for mc in [mc1, mc2, mc3]:
        assert mc.tex == mc0.tex
        assert mc.limits == mc0.limits
        assert mc.root == mc0.root
        assert mc.label == mc0.label
        assert mc._metadata == mc0._metadata
        assert mc is not mc0
        assert mc.tex is not mc0.tex
        assert mc.limits is not mc0.limits

    mc0.importance_sample(mask, action='mask', inplace=True)
    assert type(mc0) is MCMCSamples
    assert_array_equal(mc3, mc0)
    assert mc3.tex == mc0.tex
    assert mc3.limits == mc0.limits
    assert mc3.root == mc0.root
    assert mc3.label == mc0.label
    assert mc3._metadata == mc0._metadata
    assert mc3 is not mc0
    assert mc3.tex is not mc0.tex
    assert mc3.limits is not mc0.limits
Ejemplo n.º 12
0
        "plikHM_TTTEEE_lowl_lowE_lensing.tar.gz",
        "plikHM_TTTEEE_lowl_lowE_lensing_NS.tar.gz"
]:
    github_url = "https://github.com/williamjameshandley/cosmo_example/raw/master/"
    url = github_url + filename
    open(filename, 'wb').write(requests.get(url).content)
    tarfile.open(filename).extractall()

#| ## Marginalised posterior plotting
#| Import anesthetic and load the MCMC samples:

import matplotlib.pyplot as plt
from anesthetic import MCMCSamples, make_2d_axes

mcmc_root = 'plikHM_TTTEEE_lowl_lowE_lensing/base_plikHM_TTTEEE_lowl_lowE_lensing'
mcmc = MCMCSamples(root=mcmc_root)

#| We have plotting tools for 1D plots ...

fig, axes = mcmc.plot_1d('omegabh2')

#| ... multiple 1D plots ...

fig, axes = mcmc.plot_1d(['omegabh2', 'omegach2', 'H0', 'tau', 'logA', 'ns'])
fig.tight_layout()

#| ... triangle plots ...

mcmc.plot_2d(['omegabh2', 'omegach2', 'H0'],
             types={
                 'lower': 'kde',
Ejemplo n.º 13
0
def test_plot_2d_legend():
    np.random.seed(3)
    ns = NestedSamples(root='./tests/example_data/pc')
    mc = MCMCSamples(root='./tests/example_data/gd')
    params = ['x0', 'x1', 'x2', 'x3']

    # Test label kwarg for kde
    fig, axes = make_2d_axes(params, upper=False)
    ns.plot_2d(axes, label='l1', types=dict(diagonal='kde', lower='kde'))
    mc.plot_2d(axes, label='l2', types=dict(diagonal='kde', lower='kde'))

    for y, row in axes.iterrows():
        for x, ax in row.iteritems():
            if ax is not None:
                handles, labels = ax.get_legend_handles_labels()
                assert(labels == ['l1', 'l2'])
                if x == y:
                    assert(all([isinstance(h, Line2D) for h in handles]))
                else:
                    assert(all([isinstance(h, Rectangle) for h in handles]))
    plt.close('all')

    # Test label kwarg for hist and scatter
    fig, axes = make_2d_axes(params, lower=False)
    ns.plot_2d(axes, label='l1', types=dict(diagonal='hist', upper='scatter'))
    mc.plot_2d(axes, label='l2', types=dict(diagonal='hist', upper='scatter'))

    for y, row in axes.iterrows():
        for x, ax in row.iteritems():
            if ax is not None:
                handles, labels = ax.get_legend_handles_labels()
                assert(labels == ['l1', 'l2'])
                if x == y:
                    assert(all([isinstance(h, Rectangle) for h in handles]))
                else:
                    assert(all([isinstance(h, Line2D)
                                for h in handles]))
    plt.close('all')

    # test default labelling
    fig, axes = make_2d_axes(params, upper=False)
    ns.plot_2d(axes)
    mc.plot_2d(axes)

    for y, row in axes.iterrows():
        for x, ax in row.iteritems():
            if ax is not None:
                handles, labels = ax.get_legend_handles_labels()
                assert(labels == ['pc', 'gd'])
    plt.close('all')

    # Test label kwarg to constructors
    ns = NestedSamples(root='./tests/example_data/pc', label='l1')
    mc = MCMCSamples(root='./tests/example_data/gd', label='l2')
    params = ['x0', 'x1', 'x2', 'x3']

    fig, axes = make_2d_axes(params, upper=False)
    ns.plot_2d(axes)
    mc.plot_2d(axes)

    for y, row in axes.iterrows():
        for x, ax in row.iteritems():
            if ax is not None:
                handles, labels = ax.get_legend_handles_labels()
                assert(labels == ['l1', 'l2'])
    plt.close('all')
Ejemplo n.º 14
0
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")
Ejemplo n.º 15
0
def test_build_mcmc():
    np.random.seed(3)
    nsamps = 1000
    ndims = 3
    data = np.random.randn(nsamps, ndims)
    logL = np.random.rand(nsamps)
    weights = np.random.randint(1, 20, size=nsamps)
    params = ['A', 'B', 'C']
    tex = {'A': '$A$', 'B': '$B$', 'C': '$C$'}
    limits = {'A': (-1, 1), 'B': (-2, 2), 'C': (-3, 3)}

    mcmc = MCMCSamples(data=data)
    assert(len(mcmc) == nsamps)
    assert_array_equal(mcmc.columns, np.array([0, 1, 2], dtype=object))

    mcmc = MCMCSamples(data=data, logL=logL)
    assert(len(mcmc) == nsamps)
    assert_array_equal(mcmc.columns, np.array([0, 1, 2, 'logL'], dtype=object))

    mcmc = MCMCSamples(data=data, weights=weights)
    assert(len(mcmc) == nsamps)
    assert_array_equal(mcmc.columns, np.array([0, 1, 2], dtype=object))
    assert(mcmc.index.nlevels == 2)

    mcmc = MCMCSamples(data=data, weights=weights, logL=logL)
    assert(len(mcmc) == nsamps)
    assert_array_equal(mcmc.columns, np.array([0, 1, 2, 'logL'], dtype=object))
    assert(mcmc.index.nlevels == 2)

    mcmc = MCMCSamples(data=data, columns=params)
    assert(len(mcmc) == nsamps)
    assert_array_equal(mcmc.columns, ['A', 'B', 'C'])

    mcmc = MCMCSamples(data=data, tex=tex)
    for p in params:
        assert(mcmc.tex[p] == tex[p])

    mcmc = MCMCSamples(data=data, limits=limits)
    for p in params:
        assert(mcmc.limits[p] == limits[p])

    ns = NestedSamples(data=data, logL=logL, weights=weights)
    assert(len(ns) == nsamps)
    assert(np.all(np.isfinite(ns.logL)))
    logL[:10] = -1e300
    weights[:10] = 0.
    mcmc = MCMCSamples(data=data, logL=logL, weights=weights, logzero=-1e29)
    ns = NestedSamples(data=data, logL=logL, weights=weights, logzero=-1e29)
    assert_array_equal(mcmc.columns, np.array([0, 1, 2, 'logL'], dtype=object))
    assert(mcmc.index.nlevels == 2)
    assert_array_equal(ns.columns, np.array([0, 1, 2, 'logL'], dtype=object))
    assert(ns.index.nlevels == 2)
    assert(np.all(mcmc.logL[:10] == -np.inf))
    assert(np.all(ns.logL[:10] == -np.inf))
    assert(np.all(mcmc.logL[10:] == logL[10:]))
    assert(np.all(ns.logL[10:] == logL[10:]))

    mcmc = MCMCSamples(data=data, logL=logL, weights=weights, logzero=-1e301)
    ns = NestedSamples(data=data, logL=logL, weights=weights, logzero=-1e301)
    assert(np.all(np.isfinite(mcmc.logL)))
    assert(np.all(np.isfinite(ns.logL)))
    assert(np.all(mcmc.logL == logL))
    assert(np.all(ns.logL == logL))

    assert(mcmc.root is None)
Ejemplo n.º 16
0
def test_read_montepython():
    np.random.seed(3)
    mcmc = MCMCSamples(root='./tests/example_data/mp')
    mcmc.plot_2d(['x0', 'x1', 'x2', 'x3'])
    mcmc.plot_1d(['x0', 'x1', 'x2', 'x3'])
    plt.close("all")
Ejemplo n.º 17
0
def test_NS_input_fails_in_MCMCSamples():
    with pytest.raises(ValueError) as excinfo:
        MCMCSamples(root='./tests/example_data/pc')
    assert "Please use NestedSamples instead which has the same features as " \
           "MCMCSamples and more. MCMCSamples should be used for MCMC " \
           "chains only." in str(excinfo.value)
Ejemplo n.º 18
0
def test_read_getdist_discard_burn_in():
    np.random.seed(3)
    mcmc = MCMCSamples(burn_in=0.3, root='./tests/example_data/gd')
    mcmc.plot_2d(['x0', 'x1', 'x2', 'x3'])
    mcmc.plot_1d(['x0', 'x1', 'x2', 'x3'])

    # for 2 getdist chains of length 5000
    mcmc0 = MCMCSamples(root='./tests/example_data/gd')
    mcmc1 = MCMCSamples(burn_in=1000, root='./tests/example_data/gd')
    for key in ['x0', 'x1', 'x2', 'x3', 'x4']:
        assert_array_equal(mcmc0[key][1000:5000], mcmc1[key][:4000])
    mcmc1.plot_2d(['x0', 'x1', 'x2', 'x3', 'x4'])
    mcmc1.plot_1d(['x0', 'x1', 'x2', 'x3', 'x4'])
Ejemplo n.º 19
0
def test_discard_burn_in(root):
    np.random.seed(3)
    mcmc = MCMCSamples(burn_in=0.3, root='./tests/example_data/' + root)
    mcmc.plot_2d(['x0', 'x1', 'x2', 'x3'])
    mcmc.plot_1d(['x0', 'x1', 'x2', 'x3'])

    # for 2 chains of length 1000
    mcmc0 = MCMCSamples(root='./tests/example_data/' + root)
    mcmc1 = MCMCSamples(burn_in=1000, root='./tests/example_data/' + root)
    for key in ['x0', 'x1', 'x2', 'x3', 'x4']:
        if key in mcmc0:
            assert key in mcmc1
            assert_array_equal(mcmc0[key][1000:2000], mcmc1[key][:1000])
    mcmc1.plot_2d(['x0', 'x1', 'x2', 'x3', 'x4'])
    mcmc1.plot_1d(['x0', 'x1', 'x2', 'x3', 'x4'])
Ejemplo n.º 20
0
def test_read_fail():
    with pytest.raises(FileNotFoundError):
        MCMCSamples(root='./tests/example_data/foo')
Ejemplo n.º 21
0
        x1 = x[-1] + np.random.randn(ndims) * 0.1
        l1 = loglikelihood(x1)
        if np.random.rand() < np.exp(l1 - l[-1]):
            x.append(x1)
            l.append(l1)
            w.append(1)
        else:
            w[-1] += 1
    return np.array(x), np.array(l), np.array(w)


np.random.seed(0)
data, logL, weights = mcmc_sim()
mcmc = MCMCSamples(data=data,
                   columns=columns,
                   logL=logL,
                   weights=weights,
                   tex=tex)
mcmc['minuslogL'] = -mcmc.logL
mcmc['weight'] = mcmc.weights

# MCMC multiple files
root = './tests/example_data/gd'
roots.append(root)
mcmc[['weight', 'minuslogL'] + columns][:len(mcmc) // 2].to_csv(root +
                                                                '_1.txt',
                                                                sep=' ',
                                                                index=False,
                                                                header=False)
mcmc[['weight', 'minuslogL'] + columns][len(mcmc) // 2:].to_csv(root +
                                                                '_2.txt',
Ejemplo n.º 22
0
    while len(x) < 10000:
        x1 = x[-1] + np.random.randn(ndims) * 0.1
        l1 = loglikelihood(x1)
        if np.random.rand() < np.exp(l1 - l[-1]):
            x.append(x1)
            l.append(l1)
            w.append(1)
        else:
            w[-1] += 1
    return np.array(x), np.array(l), np.array(w)


np.random.seed(0)
data, logL, w = mcmc_sim()
mcmc = MCMCSamples(data=data, columns=columns, logL=logL, w=w, tex=tex)
mcmc['chi2'] = -2 * mcmc.logL

# MCMC multiple files
root = './tests/example_data/gd'
roots.append(root)
mcmc[['weight', 'chi2'] + columns][:len(mcmc) // 2].to_csv(root + '_1.txt',
                                                           sep=' ',
                                                           index=False,
                                                           header=False)
mcmc[['weight', 'chi2'] + columns][len(mcmc) // 2:].to_csv(root + '_2.txt',
                                                           sep=' ',
                                                           index=False,
                                                           header=False)

# MCMC single file
Ejemplo n.º 23
0
def test_read_getdist():
    np.random.seed(3)
    mcmc = MCMCSamples(root='./tests/example_data/gd')
    mcmc.plot_2d(['x0', 'x1', 'x2', 'x3'])
    mcmc.plot_1d(['x0', 'x1', 'x2', 'x3'])

    mcmc = MCMCSamples(root='./tests/example_data/gd_single')
    mcmc.plot_2d(['x0', 'x1', 'x2', 'x3'])
    mcmc.plot_1d(['x0', 'x1', 'x2', 'x3'])
    plt.close("all")
Ejemplo n.º 24
0
import tarfile

for filename in ["plikHM_TTTEEE_lowl_lowE_lensing.tar.gz","plikHM_TTTEEE_lowl_lowE_lensing_NS.tar.gz"]:
    github_url = "https://github.com/williamjameshandley/cosmo_example/raw/master/"
    url = github_url + filename
    open(filename, 'wb').write(requests.get(url).content)
    tarfile.open(filename).extractall()


#| ## Marginalised posterior plotting
#| Import anesthetic and load the MCMC samples:

%matplotlib notebook
from anesthetic import MCMCSamples
mcmc_root = 'plikHM_TTTEEE_lowl_lowE_lensing/base_plikHM_TTTEEE_lowl_lowE_lensing'
mcmc = MCMCSamples(root=mcmc_root)

#| We have plotting tools for 1D plots ...

fig, axes = mcmc.plot_1d('omegabh2') ;

#| ... multiple 1D plots ...

fig, axes = mcmc.plot_1d(['omegabh2','omegach2','H0','tau','logA','ns']);
fig.tight_layout()

#| ... triangle plots ...

mcmc.plot_2d(['omegabh2','omegach2','H0'], types={'lower':'kde','diagonal':'kde'});

#| ... triangle plots (with the equivalent scatter plot filling up the left hand side) ...