def test_parameterization():
    updated_info, products = run(info)
    sample = products["sample"]
    from getdist.mcsamples import loadCobayaSamples
    gdsample = loadCobayaSamples(updated_info, products["sample"])
    for i, point in sample:
        a = info[_params]["a"]
        b = get_external_function(info[_params]["b"])(a, point["bprime"])
        c = get_external_function(info[_params]["c"])(a, point["cprime"])
        e = get_external_function(e_func)(b)
        f = get_external_function(f_func)(b)
        g = get_external_function(info[_params]["g"]["derived"])(x_func(
            point["c"]))
        assert np.allclose(point[["b", "c", "e", "f", "g"]], [b, c, e, f, g])
        bcefg_getdist = [
            gdsample.samples[i][gdsample.paramNames.list().index(p)]
            for p in ["b", "c", "e", "f", "g"]
        ]
        assert np.allclose(bcefg_getdist, [b, c, e, f, g])
def test_parameterization():
    updated_info, products = run(info)
    sample = products["sample"]
    from getdist.mcsamples import loadCobayaSamples
    gdsample = loadCobayaSamples(updated_info, products["sample"])
    for i, point in sample:
        a = info[_params]["a"]
        b = get_external_function(info[_params]["b"])(a, point["bprime"])
        c = get_external_function(info[_params]["c"])(a, point["cprime"])
        e = get_external_function(e_func)(b)
        f = get_external_function(f_func)(b)
        g = get_external_function(info[_params]["g"]["derived"])(x_func(point["c"]))
        h = get_external_function(info[_params]["h"])(info[_params]["i"])
        j = get_external_function(info[_params]["j"])(b)
        k = get_external_function(info[_params]["k"]["derived"])(f)
        assert np.allclose(
            point[["b", "c", "e", "f", "g", "h", "j", "k"]], [b, c, e, f, g, h, j, k])
        # Test for GetDist too (except fixed ones, ignored by GetDist)
        bcefffg_getdist = [gdsample.samples[i][gdsample.paramNames.list().index(p)]
                           for p in ["b", "c", "e", "f", "g", "j", "k"]]
        assert np.allclose(bcefffg_getdist, [b, c, e, f, g, j, k])
Beispiel #3
0
def body_of_test(dimension=1,
                 n_modes=1,
                 info_sampler={},
                 tmpdir="",
                 modules=None):
    comm = MPI.COMM_WORLD
    rank = comm.Get_rank()
    # Info of likelihood and prior
    ranges = np.array([[-1, 1] for _ in range(dimension)])
    while True:
        info = info_random_gaussian_mixture(ranges=ranges,
                                            n_modes=n_modes,
                                            prefix="a_",
                                            O_std_min=O_std_min,
                                            O_std_max=O_std_max,
                                            derived=True)
        if n_modes == 1:
            break
        means = info["likelihood"]["gaussian_mixture"]["means"]
        distances = chain(*[[np.linalg.norm(m1 - m2) for m2 in means[i + 1:]]
                            for i, m1 in enumerate(means)])
        if min(distances) >= distance_factor * O_std_max:
            break
    if rank == 0:
        print("Original mean of the gaussian mode:")
        print(info["likelihood"]["gaussian_mixture"]["means"])
        print("Original covmat of the gaussian mode:")
        print(info["likelihood"]["gaussian_mixture"]["covs"])
    info[_sampler] = info_sampler
    if list(info_sampler.keys())[0] == "mcmc":
        if "covmat" in info_sampler["mcmc"]:
            info[_sampler]["mcmc"]["covmat_params"] = (list(
                info["params"].keys())[:dimension])
    info[_debug] = False
    info[_debug_file] = None
    info[_output_prefix] = getattr(tmpdir, "realpath()", lambda: tmpdir)()
    if modules:
        info[_path_install] = process_modules_path(modules)
    # Delay to one chain to check that MPI communication of the sampler is non-blocking
    #    if rank == 1:
    #        info["likelihood"]["gaussian_mixture"]["delay"] = 0.1
    updated_info, products = run(info)
    # Done! --> Tests
    if rank == 0:
        if list(info_sampler.keys())[0] == "mcmc":
            ignore_rows = 0.5
        else:
            ignore_rows = 0
        results = loadCobayaSamples(updated_info,
                                    products["sample"],
                                    ignore_rows=ignore_rows,
                                    name_tag="sample")
        clusters = None
        if "clusters" in products:
            clusters = [
                loadCobayaSamples(updated_info,
                                  products["clusters"][i]["sample"],
                                  name_tag="cluster %d" % (i + 1))
                for i in products["clusters"]
            ]
        # Plots!
        try:
            import getdist.plots as gdplots
            from getdist.gaussian_mixtures import MixtureND
            mixture = MixtureND(
                info[_likelihood]["gaussian_mixture"]["means"],
                info[_likelihood]["gaussian_mixture"]["covs"],
                names=[p for p in info[_params] if "deriv" not in p],
                label="truth")
            g = gdplots.getSubplotPlotter()
            to_plot = [mixture, results]
            if clusters:
                to_plot = to_plot + clusters
            g.triangle_plot(to_plot, )
            g.export("test.png")
        except:
            print("Plotting failed!")
        # 1st test: KL divergence
        if n_modes == 1:
            cov_sample, mean_sample = results.getCov(), results.getMeans()
            KL_final = KL_norm(
                m1=info[_likelihood]["gaussian_mixture"]["means"][0],
                S1=info[_likelihood]["gaussian_mixture"]["covs"][0],
                m2=mean_sample[:dimension],
                S2=cov_sample[:dimension, :dimension])
            print("Final KL: ", KL_final)
            assert KL_final <= KL_tolerance
        # 2nd test: clusters
        else:
            if "clusters" in products:
                assert len(products["clusters"].keys()) >= n_modes, (
                    "Not all clusters detected!")
                for c2 in clusters:
                    cov_c2, mean_c2 = c2.getCov(), c2.getMeans()
                    KLs = [
                        KL_norm(m1=info[_likelihood]["gaussian_mixture"]
                                ["means"][i_c1],
                                S1=info[_likelihood]["gaussian_mixture"]
                                ["covs"][i_c1],
                                m2=mean_c2[:dimension],
                                S2=cov_c2[:dimension, :dimension])
                        for i_c1 in range(n_modes)
                    ]
                    extra_tol = 4 * n_modes if n_modes > 1 else 1
                    assert min(KLs) <= KL_tolerance * extra_tol
            else:
                assert 0, "Could not check sample convergence: multimodal but no clusters"
        # 3rd test: Evidence
        if "logZ" in products:
            logZprior = sum(np.log(ranges[:, 1] - ranges[:, 0]))
            assert (products["logZ"] - logZ_nsigmas * products["logZstd"] <
                    -logZprior <
                    products["logZ"] + logZ_nsigmas * products["logZstd"])
Beispiel #4
0
# Export the results to GetDist
from getdist.mcsamples import loadCobayaSamples
gd_sample = loadCobayaSamples(updated_info, 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.getSubplotPlotter()
gdplot.triangle_plot(gd_sample, ["a", "b"], filled=True)