Ejemplo n.º 1
0
    def cornerpoints(self, **kwargs):

        try:
            dyplot.cornerpoints(results=self.samples.results,
                                labels=self.model.parameter_labels_latex,
                                **kwargs)

            self.output.to_figure(structure=None, auto_filename="cornerpoints")
        except ValueError:
            pass
Ejemplo n.º 2
0
def test_gaussian():
    logz_tol = 1
    sampler = dynesty.NestedSampler(loglikelihood_gau,
                                    prior_transform_gau,
                                    ndim_gau,
                                    nlive=nlive)
    sampler.run_nested(print_progress=printing)

    # add samples
    # check continuation behavior
    sampler.run_nested(dlogz=0.1, print_progress=printing)

    # get errors
    nerr = 2
    for i in range(nerr):
        sampler.reset()
        sampler.run_nested(print_progress=False)
        results = sampler.results
        pos = results.samples
        wts = np.exp(results.logwt - results.logz[-1])
        mean, cov = dyfunc.mean_and_cov(pos, wts)
        logz = results.logz[-1]
        assert (np.abs(logz - logz_truth_gau) < logz_tol)
    # check summary
    res = sampler.results
    res.summary()

    # check plots
    dyplot.runplot(sampler.results)
    plt.close()
    dyplot.traceplot(sampler.results)
    plt.close()
    dyplot.cornerpoints(sampler.results)
    plt.close()
    dyplot.cornerplot(sampler.results)
    plt.close()
    dyplot.boundplot(sampler.results,
                     dims=(0, 1),
                     it=3000,
                     prior_transform=prior_transform_gau,
                     show_live=True,
                     span=[(-10, 10), (-10, 10)])
    plt.close()
    dyplot.cornerbound(sampler.results,
                       it=3500,
                       prior_transform=prior_transform_gau,
                       show_live=True,
                       span=[(-10, 10), (-10, 10)])
    plt.close()
Ejemplo n.º 3
0
    def cornerpoints(self, **kwargs):

        if conf.instance["general"]["test"]["test_mode"]:
            return None

        try:
            dyplot.cornerpoints(results=self.samples.results,
                                labels=self.model.parameter_labels_latex,
                                **kwargs)

            self.output.to_figure(structure=None, auto_filename="cornerpoints")
        except ValueError:
            pass

        self.mat_plot_1d.figure.close()
Ejemplo n.º 4
0
def main(args=None):
    if args.results == "none":
        ndim = len(JOINT_PRIOR)
        date = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
        image_positions = pd.read_csv(args.image_positions)
        pprint(image_positions)
        # A=0, B=1, C=2, D=3
        x_image = image_positions["theta_x"].to_numpy()
        y_image = image_positions["theta_y"].to_numpy()
        quad_model = QuadPseudoNIELensModel(x_image, y_image, args.plate_scale)
        time_delays = pd.read_csv(args.time_delays)
        pprint(time_delays)

        # Expected: DA=0, DB=1, DC=2 (index)
        sigma_t = time_delays["sigma"].to_numpy()  # units of days
        delta_t = time_delays["delta_t"].to_numpy()
        joint_loglikelihood = joint_loglikelihood_func(quad_model, delta_t,
                                                       sigma_t)

        with Pool(args.nworkers) as pool:
            sampler = DynamicNestedSampler(joint_loglikelihood,
                                           joint_prior_transform,
                                           ndim,
                                           pool=pool,
                                           nlive=args.nlive,
                                           queue_size=args.nworkers)
            sampler.run_nested()
            res = sampler.results

        # save results
        with open(f"../results/joint_result_{date}.p", "wb") as f:
            pickle.dump(res, f)
    else:  # we just want to plot the result from an older run
        with open(args.results, "rb") as f:
            res = pickle.load(f)
        ndim = res.samples.shape[1]

    if args.plot_results:
        # trace plot
        fig, axs = dyplot.traceplot(
            res,
            show_titles=True,
            trace_cmap='plasma',
            connect=True,
            connect_highlight=range(5),
            labels=LABELS,
        )
        fig.tight_layout(pad=2.0)
        fig.savefig("../figures/joint_inference_trace_plot.png",
                    bbox_inches="tight")

        # corner points plot
        fig, axes = plt.subplots(ndim - 1, ndim - 1, figsize=(15, 15))
        axes.reshape([ndim - 1, ndim - 1])
        fg, ax = dyplot.cornerpoints(res,
                                     cmap='plasma',
                                     kde=False,
                                     fig=(fig, axes),
                                     labels=LABELS)
        fg.savefig("../figures/joint_inference_cornerpoints.png",
                   bbox_inches="tight")

        # corner plot
        fig, axes = plt.subplots(ndim, ndim, figsize=(15, 15))
        axes.reshape([ndim, ndim])
        fg, ax = dyplot.cornerplot(res,
                                   fig=(fig, axes),
                                   color="b",
                                   labels=LABELS,
                                   show_titles=True)
        fg.savefig("../figures/joint_inference_corner_plot.png",
                   bbox_inches="tight")

        #### marginalized posterior #####
        Ddt = res.samples[:, 0]  # histogram of Ddt
        weights = np.exp(
            res['logwt'] -
            res['logz'][-1])  # posterior probability (Bayes theorem)

        # eliminate outliers with low and high + estimate confidance interval
        low, fifth, median, ninety_fifth, high = weighted_quantile(
            Ddt, [0.0001, 0.05, 0.5, 0.95, 0.9999], weights)
        error_plus = ninety_fifth - median  # error estimate with 5th percentile
        error_minus = median - fifth  # error estimate with 95th percentile
        good = (Ddt > low) & (Ddt < high)  # remove outliers
        Ddt = Ddt[good]
        weights = weights[good]

        plt.figure(figsize=(8, 8))
        plt.hist(Ddt, bins=100, weights=weights)
        plt.title(r"$D_{\Delta t}$=%.2f$^{+%.2f}_{-%.2f}$" %
                  (median, error_plus, error_minus))
        plt.xlabel(r"$D_{\Delta t}$")
        plt.savefig("../figures/marginalized_posterior_Ddt.png")

        # assume a flat LambdCDM model (with negligible radiation)

        # We need to model kappa_ext for this step
        def integrand(z):
            return 1 / np.sqrt(args.omega_m * (1 + z)**3 + args.omega_l)

        Dd = quad(integrand, 0, args.z_lens)[0] / (1 + args.z_lens)
        Ds = quad(integrand, 0, args.z_source)[0] / (1 + args.z_source)
        Dds = quad(integrand, args.z_lens,
                   args.z_source)[0] / (1 + args.z_source)
        factor = (1 + args.z_lens) * Ds * Dd / Dds
        H0 = (c * factor / Ddt / u.Mpc).to(u.km / u.s / u.Mpc).value

        plt.figure(figsize=(8, 8))
        fifth, median, ninety_fifth = weighted_quantile(
            H0, [0.05, 0.5, 0.95], weights)
        error_plus = ninety_fifth - median
        error_minus = median - fifth
        plt.hist(H0, bins=100, weights=weights)
        plt.title(r"$H_0$=%.2f$^{+%.2f}_{-%.2f}$" %
                  (median, error_plus, error_minus))
        plt.xlabel(r"$H_0$ [km s$^{-1}$ Mpc$^{-1}$]")
        plt.savefig("../figures/marginalized_posterior_H0.png")
Ejemplo n.º 5
0
def test_gaussian(dynamic, periodic, ndim, bound):
    rstate = get_rstate()
    g = Gaussian(ndim=ndim)
    if periodic:
        periodic = [0]
    else:
        periodic = None
    if dynamic:
        sampler = dynesty.DynamicNestedSampler(g.loglikelihood,
                                               g.prior_transform,
                                               g.ndim,
                                               nlive=nlive,
                                               rstate=rstate,
                                               periodic=periodic,
                                               bound=bound)
    else:
        sampler = dynesty.NestedSampler(g.loglikelihood,
                                        g.prior_transform,
                                        g.ndim,
                                        nlive=nlive,
                                        rstate=rstate,
                                        periodic=periodic,
                                        bound=bound)
    sampler.run_nested(print_progress=printing)
    results = sampler.results
    # check plots
    dyplot.runplot(results)
    dyplot.runplot(results, span=[(0., 10.), 0.001, 0.2, (5., 6.)])
    dyplot.runplot(results, logplot=True)
    dyplot.runplot(results,
                   fig=(plt.gcf(), plt.gcf().axes),
                   max_x_ticks=0,
                   max_y_ticks=0)
    plt.close()
    dyplot.traceplot(results)
    dyplot.traceplot(results, smooth=[10] * ndim)
    dyplot.traceplot(results, connect=True)
    dyplot.traceplot(results,
                     fig=(plt.gcf(), plt.gcf().axes),
                     show_titles=True,
                     truths=np.zeros(ndim),
                     verbose=True,
                     max_n_ticks=0)
    plt.close()

    truths = np.zeros(ndim)
    truths[0] = -.1
    span = [[-10, 10]] * ndim
    if ndim > 1:
        truths[1] = .1
        span[1] = .9

    dyplot.cornerplot(results, show_titles=True, truths=truths)
    dyplot.cornerplot(results,
                      smooth=10,
                      verbose=True,
                      hist2d_kwargs=dict(plot_datapoints=True),
                      max_n_ticks=0)
    plt.close()
    if ndim != 1:
        # cornerbound
        dyplot.cornerbound(results,
                           it=500,
                           prior_transform=g.prior_transform,
                           show_live=True,
                           span=span)
        dyplot.cornerbound(results,
                           it=500,
                           show_live=True,
                           span=span,
                           fig=(plt.gcf(), plt.gcf().axes))
        plt.close()
        # boundplot
        dyplot.boundplot(results,
                         dims=(0, 1)[:min(ndim, 2)],
                         it=1000,
                         prior_transform=g.prior_transform,
                         show_live=True,
                         span=span)
        dyplot.boundplot(results, dims=(0, 1)[:min(ndim, 2)], it=1000)
        plt.close()

        # cornerpoints
        dyplot.cornerpoints(results)
        plt.close()
        dyplot.cornerpoints(results, span=span, truths=truths, max_n_ticks=0)
        plt.close()
def plot(n, alpha, beta, dlogz_val=.1, interloper=False, d=1):
    x_k = np.round(generator(n, alpha, beta, d), 2)  #round up

    #append values if interloper is true
    if (interloper == True):
        interloper_x_k = np.round(generator(n, alpha + 3, beta, d), 2)
        x_k = np.append(x_k, interloper_x_k)

    #feed parameters for alpha and beta

    def lighthouse_logl(params):

        return log_likelihood(x_k, params[0], params[1])

    #prior transform, using documentation for range -1000, 1000

    def prior_transform(u):
        return [2000 * u[0] - 1000, 1000 * u[1]]

    ndim = 2
    sampler = dynesty.NestedSampler(lighthouse_logl,
                                    prior_transform,
                                    ndim,
                                    bound='single',
                                    nlive=200)
    sampler.run_nested(dlogz=dlogz_val, print_progress=False)
    results = sampler.results

    #runplot

    dyplot.runplot(results)
    #plt.savefig('int_run_plot' + str(dlogz_val)+".png", dpi =300)
    plt.show()

    #cornerpoints plot

    fig = plt.subplots(1, 1, figsize=(10, 10))
    dyplot.cornerpoints(results,
                        fig=fig,
                        cmap='plasma',
                        truths=np.zeros(ndim),
                        kde=False)
    fig[1].set_ylabel('$\\beta$')
    fig[1].set_xlabel('$\\alpha$')
    plt.tight_layout()
    plt.xlim(-10, 10)
    plt.ylim(0, 10)
    plt.savefig('int_corner1' + str(dlogz_val) + ".png", dpi=300)
    plt.show()

    #traceplot

    fig = plt.subplots(2, 2, figsize=(15, 10))
    dyplot.traceplot(results,
                     fig=fig,
                     truth_color='black',
                     trace_cmap='viridis',
                     connect=True,
                     connect_highlight=range(5),
                     show_titles=True)
    fig[1][1, 1].set_xlabel('$\\beta$')
    fig[1][0, 1].set_xlabel('$\\alpha$')
    fig[1][1, 0].set_ylabel('$\\beta$')
    fig[1][0, 0].set_ylabel('$\\alpha$')
    plt.tight_layout()
    #plt.savefig('int_trace' + str(dlogz_val)+".png", dpi =300)
    plt.show()

    print(results.samples[-1])
Ejemplo n.º 7
0
# check summary
sys.stderr.write('\nResults\n')
res = sampler.results
res.summary()

# check plots
sys.stderr.write('\nPlotting\n')
sys.stderr.write('Summary/Run Plot\n')
dyplot.runplot(sampler.results)
plt.close()
sys.stderr.write('Trace Plot\n')
dyplot.traceplot(sampler.results)
plt.close()
sys.stderr.write('Sub-Corner Plot (Points)\n')
dyplot.cornerpoints(sampler.results)
plt.close()
sys.stderr.write('Corner Plot (Contours)\n')
dyplot.cornerplot(sampler.results)
plt.close()
sys.stderr.write('2-D Bound Plot\n')
dyplot.boundplot(sampler.results,
                 dims=(0, 1),
                 it=3000,
                 prior_transform=prior_transform,
                 show_live=True,
                 span=[(-10, 10), (-10, 10)])
plt.close()
sys.stderr.write('Sub-Corner Plot (Bounds)\n')
dyplot.cornerbound(sampler.results,
                   it=3500,
        res = sampler.sampler.results
    else:
        res = sampler.results

    # Make the traceplots and the bound plots.

    plot_status(res, labels=labels, periodic=periodic)

# Generate a plot of the weighted samples.

fig, ax = plt.subplots(ndim - 1, ndim - 1, figsize=(10, 10))

dyplot.cornerpoints(res,
                    cmap="plasma",
                    kde=False,
                    fig=(fig, ax),
                    labels=labels)

fig.savefig("cornerpoints.png")

# Generate a corner plot from Dynesty.

fig, ax = plt.subplots(ndim, ndim, figsize=(15, 15))

dyplot.cornerplot(res, color="blue", show_titles=True, max_n_ticks=3, \
        quantiles=None, fig=(fig, ax), labels=labels)

fig.savefig("cornerplot.png")

# Convert the results to a more traditional set of samples that you would