Exemplo n.º 1
0
def step_size_sigma(title,
                    samples,
                    time,
                    σ,
                    stepsize,
                    post,
                    plot,
                    legend_pos=None):
    nplot = len(samples)
    nsample = len(time)
    figure, axis = pyplot.subplots(figsize=(10, 7))
    axis.set_xlabel("Time")
    axis.set_ylabel(r"$σ$")
    axis.set_title(title)
    axis.set_xlim([10.0, nsample])
    axis.semilogx(time,
                  numpy.full((len(time)), σ),
                  label="Target σ",
                  color="#000000")
    for i in range(nplot):
        axis.semilogx(time,
                      stats.cumsigma(samples[i]),
                      label=f"stepsize={format(stepsize[i], '2.2f')}")
    if legend_pos is None:
        axis.legend()
    else:
        axis.legend(bbox_to_anchor=legend_pos)
    config.save_post_asset(figure, post, plot)
Exemplo n.º 2
0
def pdf_samples_contour(pdf, p, q, xrange, yrange, contour_values, labels,
                        title, file):
    npts = 500
    fxy, x, y = grid_pdf(pdf, xrange, yrange, npts)
    bins = [
        numpy.linspace(xrange[0], xrange[1], 100),
        numpy.linspace(yrange[0], yrange[1], 100)
    ]
    figure, axis = pyplot.subplots(figsize=(11, 9))
    axis.set_xlabel(labels[0])
    axis.set_ylabel(labels[1])
    axis.set_title(title)
    hist, _, _, image = axis.hist2d(p,
                                    q,
                                    normed=True,
                                    bins=bins,
                                    cmap=config.alternate_color_map)
    contour = axis.contour(x,
                           y,
                           fxy,
                           contour_values,
                           cmap=config.alternate_contour_color_map)
    axis.clabel(contour,
                contour.levels[::2],
                fmt="%.3f",
                inline=True,
                fontsize=15)
    figure.colorbar(image)
    config.save_post_asset(figure, "hamiltonian_monte_carlo", file)
def integration_error_plot(p0, q0, nsteps, ε, plot_file):
    contour_value = p0**2+ q0**2
    p_leapfrog, q_leapfrog = leapfrog(p0, q0, nsteps, ε)
    p_euler_cromer, q_euler_cromer = euler_cromer(p0, q0, nsteps, ε)
    p_euler, q_euler = euler(p0, q0, nsteps, ε)
    p_momentum_verlet, q_momentum_verlet = momentum_verlet(p0, q0, nsteps, ε)

    error_leapfrog = 100.0*numpy.abs(numpy.sqrt(p_leapfrog[1:-1]**2 + q_leapfrog[1:-1]**2) - numpy.sqrt(contour_value))/numpy.sqrt(contour_value)
    error_euler_cromer = 100.0*numpy.abs(numpy.sqrt(p_euler_cromer[1:-1]**2 + q_euler_cromer[1:-1]**2) - numpy.sqrt(2.0))/numpy.sqrt(2.0)
    error_euler = 100.0*numpy.abs(numpy.sqrt(p_euler[1:-1]**2 + q_euler[1:-1]**2) - numpy.sqrt(2.0))/numpy.sqrt(2.0)
    error_momentum_verlet = 100.0*numpy.abs(numpy.sqrt(p_momentum_verlet[1:-1]**2 + q_momentum_verlet[1:-1]**2) - numpy.sqrt(2.0))/numpy.sqrt(2.0)

    t_plot = numpy.linspace(0.0, nsteps*ε, nsteps+1)

    figure, axis = pyplot.subplots(figsize=(10, 7))
    axis.set_xlabel("t")
    axis.set_ylabel("% Error")
    axis.set_title(f"Hamiltion's Equations Integration Error: Δt={ε}, nsteps={nsteps}")
    axis.set_xlim([0.0, t])
    axis.plot(t_plot[1:-1], error_leapfrog, label="Leapfrog")
    axis.plot(t_plot[1:-1], error_euler_cromer, label="Euler Cromer")
    axis.plot(t_plot[1:-1], error_euler, label="Euler")
    axis.plot(t_plot[1:-1], error_momentum_verlet, label="Momentum Verlet")
    config.save_post_asset(figure, "hamiltonian_monte_carlo", plot_file)
    axis.legend(bbox_to_anchor=(0.35, 0.9))
Exemplo n.º 4
0
def parametric_contour_plot(μ1, μ2, σ1, σ2, γ, legend_box, contour_values, plot_name):
    npts = 500
    θ = numpy.linspace(0.0, 2.0 * numpy.pi, npts)
    c = [pdf_contour_constant(μ1, μ2, σ1, σ2, γ, v) for v in contour_values]
    f = pdf_parametric_contour(μ1, μ2, σ1, σ2, γ)

    figure, axis = pyplot.subplots(figsize=(8, 8))
    axis.set_xlabel(r"$u$")
    axis.set_ylabel(r"$v$")
    if (σ1 > σ2):
        axis.set_xlim([-3.2*σ1, 3.2*σ1])
        axis.set_ylim([-3.2*σ1, 3.2*σ1])
    elif (σ2 > σ1):
        axis.set_xlim([-3.2*σ2, 3.2*σ2])
        axis.set_ylim([-3.2*σ2, 3.2*σ2])
    else:
        axis.set_xlim([-3.2*σ1, 3.2*σ1])
        axis.set_ylim([-3.2*σ2, 3.2*σ2])

    title = f"Bivariate Normal Distribution: γ={format(γ, '2.1f')}, " + \
             r"$σ_u$=" + f"{format(σ1, '2.1f')}, " + r"$σ_v$=" + \
             f"{format(σ2, '2.1f')}"
    axis.set_title(title)

    for n in range(len(c)):
        y1, y2 = f(θ, c[n])
        axis.plot(y1, y2, label=f"= {format(contour_values[n], '2.3f')}")

    axis.legend(bbox_to_anchor=legend_box)
    config.save_post_asset(figure, "bivariate_normal_distribution", plot_name)
Exemplo n.º 5
0
def contour_plot_sigma_correlation_scan(μ1, μ2, σ1, σ2, γ, contour_value, legend, plot_name):
    npts = 500
    θ = numpy.linspace(0.0, 2.0 * numpy.pi, npts)

    figure, axis = pyplot.subplots(figsize=(8, 8))
    axis.set_xlabel(r"$u$")
    axis.set_ylabel(r"$v$")
    σ = numpy.amax([σ1, σ2])
    axis.set_xlim([-2.5*σ, 2.5*σ])
    axis.set_ylim([-2.5*σ, 2.5*σ])
    title = f"Bivariate Normal Distribution: " + \
             r"$σ_u$=" + f"{format(σ1, '2.1f')}, " + r"$σ_v$=" + \
             f"{format(σ2, '2.1f')}, K={format(contour_value, '2.2f')}"
    axis.set_title(title)

    for i in range(len(γ)):
        c = pdf_contour_constant(μ1, μ2, σ1, σ2, γ[i], contour_value)
        f = pdf_parametric_contour(μ1, μ2, σ1, σ2, γ[i])
        y1, y2 = f(θ, c)
        axis.plot(y1, y2, label=f"γ = {format(γ[i], '2.2f')}")

    x1 = numpy.linspace(-2.5*σ, 2.5*σ, npts)
    slope = γ[-1]*σ2/σ1/abs(γ[-1])
    axis.plot(x1, slope*x1, zorder = 6, color="#003B6F", alpha=0.1)

    axis.legend(bbox_to_anchor=legend)
    config.save_post_asset(figure, "bivariate_normal_distribution", plot_name)
def verification_time_series(title, p, q, time, ylim, file):
    nplots = 2
    figure, axis = pyplot.subplots(nrows=nplots, ncols=1, sharex=True, figsize=(10, 4*nplots))
    axis[0].set_title(title)
    axis[-1].set_xlabel("Time")

    q1 = [q[0](t) for t in time]
    q2 = [q[1](t) for t in time]
    axis[0].set_xlim([time[0], time[-1]])
    axis[0].set_ylim(ylim)
    axis[0].set_ylabel("q")
    axis[0].plot(time, q1, label=r"$q_1$")
    axis[0].plot(time, q2, label=r"$q_2$")
    axis[0].legend()

    p1 = [p[0](t) for t in time]
    p2 = [p[1](t) for t in time]
    axis[1].set_xlim([time[0], time[-1]])
    axis[1].set_ylim(ylim)
    axis[1].set_ylabel("p")
    axis[1].plot(time, p1, label=r"$p_1$")
    axis[1].plot(time, p2, label=r"$p_2$")
    axis[1].legend()

    config.save_post_asset(figure, "hamiltonian_monte_carlo", file)
Exemplo n.º 7
0
def time_series(title, samples, time, ylim, plot):
    figure, axis = pyplot.subplots(figsize=(12, 4))
    axis.set_title(title)
    axis.set_xlabel("Time")
    axis.set_xlim([time[0], time[-1]])
    axis.set_ylim(ylim)
    axis.plot(time, samples, lw="1")
    config.save_post_asset(figure, "hamiltonian_monte_carlo", plot)
Exemplo n.º 8
0
def univariate_pdf_plot(pdf, x, x_title, title, file):
    figure, axis = pyplot.subplots(figsize=(10, 7))
    axis.set_xlabel(x_title)
    axis.set_ylabel("PDF")
    axis.set_xlim([x[0], x[-1]])
    axis.set_title(title)
    axis.plot(x, [pdf(j) for j in x])
    config.save_post_asset(figure, "hamiltonian_monte_carlo", file)
Exemplo n.º 9
0
def time_series(title, samples, time, ylim, post, plot):
    nplots = len(samples)
    figure, axis = pyplot.subplots(figsize=(12, 4))
    axis.set_title(title)
    axis.set_xlabel("Time")
    axis.set_xlim([time[0], time[-1] + 1])
    axis.set_ylim(ylim)
    axis.plot(time, samples, lw="1")
    config.save_post_asset(figure, post, plot)
Exemplo n.º 10
0
def autocor(title, samples, max_lag, plot):
    figure, axis = pyplot.subplots(figsize=(10, 7))
    axis.set_title(title)
    axis.set_ylabel(r"$\gamma_{\tau}$")
    axis.set_xlabel("Time Lag (τ)")
    axis.set_xlim([0, max_lag])
    axis.set_ylim([-0.05, 1.0])
    ac = stats.autocorrelate(samples)
    axis.plot(range(max_lag), numpy.real(ac[:max_lag]))
    config.save_post_asset(figure, "hamiltonian_monte_carlo", plot)
Exemplo n.º 11
0
def canonical_distribution_contour_plot(kinetic_energy, potential_energy, contour_values, title, plot_name):
    npts = 500
    x1_grid, x2_grid, f_x1_x2 = canonical_distribution_mesh(kinetic_energy, potential_energy, npts)
    figure, axis = pyplot.subplots(figsize=(8, 8))
    axis.set_xlabel(r"$q$")
    axis.set_ylabel(r"$p$")
    axis.set_xlim([-3.2, 3.2])
    axis.set_ylim([-3.2, 3.2])
    axis.set_title(title)
    contour = axis.contour(x1_grid, x2_grid, f_x1_x2, contour_values, cmap=config.contour_color_map)
    axis.clabel(contour, contour.levels[::2], fmt="%.3f", inline=True, fontsize=15)
    config.save_post_asset(figure, "hamiltonian_monte_carlo", plot_name)
Exemplo n.º 12
0
def cumulative_standard_deviation(title, samples, time, σ, ylim, file):
    nsample = len(time)
    figure, axis = pyplot.subplots(figsize=(10, 7))
    axis.set_xlabel("Time")
    axis.set_ylabel(r"$σ$")
    axis.set_title(title)
    axis.set_ylim(ylim)
    axis.set_xlim([10.0, nsample])
    axis.semilogx(time,
                  numpy.full((len(time)), σ),
                  label="Target σ",
                  color="#000000")
    axis.semilogx(time, stats.cumsigma(samples))
    config.save_post_asset(figure, "hamiltonian_monte_carlo", file)
Exemplo n.º 13
0
def plot_sampled_pdf(title, f, samples, plot_name):
    figure, axis = pyplot.subplots(figsize=(10, 6))
    axis.set_prop_cycle(config.distribution_sample_cycler)
    axis.set_title(title)
    axis.set_ylabel("PDF")
    axis.set_xlabel(r"$X$")
    axis.set_ylim([0, 2.0])
    axis.set_yticks([0.2, 0.6, 1.0, 1.4, 1.8])
    axis.set_xlim([0.0, 1.6])
    axis.hist(samples, 30, density=True, rwidth=0.8, label=f"Samples", zorder=5)
    x = numpy.linspace(0.0, 1.6, 500)
    axis.plot(x, f(x), label=f"Target PDF", zorder=7)
    axis.legend(bbox_to_anchor=(0.3, 0.85))
    config.save_post_asset(figure, "rejection_sampling", plot_name)
Exemplo n.º 14
0
def acceptance(title, x, y, xlim, example_idx, post, plot):
    figure, axis = pyplot.subplots(figsize=(10, 7))
    axis.set_xlabel("Step Size")
    axis.set_ylabel("Acceptance %")
    axis.set_title(title)
    axis.set_xlim(xlim)
    axis.set_ylim([0.7, 200.0])
    axis.set_prop_cycle(config.alternate_cycler)
    axis.loglog(x,
                y,
                zorder=5,
                marker='o',
                markersize=15.0,
                linestyle="None",
                markeredgewidth=1.0)
    axis.loglog(
        x[example_idx[0]],
        y[example_idx[0]],
        zorder=5,
        marker='o',
        markersize=15.0,
        linestyle="None",
        markeredgewidth=1.0,
        label=
        f" Small Step Size: ({format(x[example_idx[0]], '.2f')}, {format(y[example_idx[0]], '2.0f')}%)"
    )
    axis.loglog(
        x[example_idx[1]],
        y[example_idx[1]],
        zorder=5,
        marker='o',
        markersize=15.0,
        linestyle="None",
        markeredgewidth=1.0,
        label=
        f" Best Step Size:   ({format(x[example_idx[1]], '.2f')}, {format(y[example_idx[1]], '2.0f')}%)"
    )
    axis.loglog(
        x[example_idx[2]],
        y[example_idx[2]],
        zorder=5,
        marker='o',
        markersize=15.0,
        linestyle="None",
        markeredgewidth=1.0,
        label=
        f" Large Step Size: ({format(x[example_idx[2]], '.2f')}, {format(y[example_idx[2]], '2.0f')}%)"
    )
    axis.legend(bbox_to_anchor=(0.55, 0.6))
    config.save_post_asset(figure, post, plot)
Exemplo n.º 15
0
def step_size_autocor(title, samples, stepsize, npts, post, plot):
    nplot = len(samples)
    figure, axis = pyplot.subplots(figsize=(12, 9))
    axis.set_title(title)
    axis.set_ylabel(r"$\gamma_{\tau}$")
    axis.set_xlabel("Time Lag (τ))")
    axis.set_xlim([0, npts])
    for i in range(nplot):
        ac = stats.autocorrelate(samples[i])
        axis.plot(range(npts),
                  numpy.real(ac[:npts]),
                  label=f"stepsize={format(stepsize[i], '2.2f')}")
    axis.legend(bbox_to_anchor=(0.7, 0.6))
    config.save_post_asset(figure, post, plot)
Exemplo n.º 16
0
def relaxation_plot(πt, nsteps, plot_name):
    steps = [i for i in range(0, nsteps + 1)]
    figure, axis = pyplot.subplots(figsize=(10, 6))
    axis.set_xlabel("Time")
    axis.set_ylabel("Probability")
    axis.set_title(r"$\pi_t$ Relaxation to Equilibrium")
    axis.set_ylim([0, 0.55])
    axis.set_yticks([0.1, 0.2, 0.3, 0.4, 0.5])
    axis.set_xlim([0, nsteps])
    axis.plot(steps, [πt[i][0, 0] for i in steps], label=f"0", lw="3", zorder=10)
    axis.plot(steps, [πt[i][0, 1] for i in steps], label=f"1", lw="3", zorder=10)
    axis.plot(steps, [πt[i][0, 2] for i in steps], label=f"2", lw="3", zorder=10)
    axis.plot(steps, [πt[i][0, 3] for i in steps], label=f"3", lw="3", zorder=10)
    axis.legend(bbox_to_anchor=(0.8, 0.15))
    config.save_post_asset(figure, "discrete_state_markov_chain_equilibrium", plot_name)
Exemplo n.º 17
0
def mean_convergence(title, samples, μ, plot_name):
    nsamples = len(samples)
    time = range(nsamples)
    figure, axis = pyplot.subplots(figsize=(10, 6))
    axis.set_xlabel("Sample Number")
    axis.set_ylabel("μ")
    axis.set_title(title)
    axis.set_xlim([1.0, nsamples])
    axis.set_ylim( [0.5, 1.5])
    cmean = stats.cummean(samples)
    μs = numpy.full(len(samples), μ)
    axis.semilogx(time, μs, label="Target μ")
    axis.semilogx(time, cmean, label="Sampled μ")
    axis.legend(bbox_to_anchor=([0.9, 0.9]))
    config.save_post_asset(figure, "rejection_sampling", plot_name)
Exemplo n.º 18
0
def distribution_samples(x, y, xrange, yrange, labels, title, file):
    bins = [
        numpy.linspace(xrange[0], xrange[1], 100),
        numpy.linspace(yrange[0], yrange[1], 100)
    ]
    figure, axis = pyplot.subplots(figsize=(11, 9))
    axis.set_xlabel(labels[0])
    axis.set_ylabel(labels[1])
    axis.set_title(title)
    hist, _, _, image = axis.hist2d(x,
                                    y,
                                    normed=True,
                                    bins=bins,
                                    cmap=config.alternate_color_map)
    figure.colorbar(image)
    config.save_post_asset(figure, "hamiltonian_monte_carlo", file)
Exemplo n.º 19
0
def sigma_convergence(title, samples, σ, plot_name):
    nsamples = len(samples)
    time = range(nsamples)
    figure, axis = pyplot.subplots(figsize=(10, 6))
    axis.set_xlabel("Sample Number")
    axis.set_ylabel("σ")
    axis.set_title(title)
    axis.set_xlim([1.0, nsamples])
    axis.set_ylim([0.0, 0.5])
    axis.set_yticks([0.1, 0.2, 0.3, 0.4])
    csigma = stats.cumsigma(samples)
    σs = numpy.full(len(samples), σ)
    axis.semilogx(time, σs, label="Target σ")
    axis.semilogx(time, csigma, label="Sampled σ")
    axis.legend(bbox_to_anchor=([0.95, 0.9]))
    config.save_post_asset(figure, "rejection_sampling", plot_name)
Exemplo n.º 20
0
def pdf_samples(title, pdf, samples, post, plot, xrange=None, ylimit=None):
    figure, axis = pyplot.subplots(figsize=(10, 7))
    axis.set_xlabel(r"$X$")
    axis.set_title(title)
    axis.set_prop_cycle(config.distribution_sample_cycler)
    _, bins, _ = axis.hist(samples, 50, rwidth=0.8, density=True, label=f"Samples", zorder=5)
    if xrange is None:
        delta = (bins[-1] - bins[0]) / 500.0
        xrange = numpy.arange(bins[0], bins[-1], delta)
    sample_distribution = [pdf(val) for val in xrange]
    axis.set_xlim([xrange[0], xrange[-1]])
    if ylimit is not None:
        axis.set_ylim(ylimit)
    axis.plot(xrange, sample_distribution, label=f"Target PDF", zorder=6)
    axis.legend(bbox_to_anchor=(0.75, 0.9))
    config.save_post_asset(figure, post, plot)
Exemplo n.º 21
0
def hamiltons_equations_integration_plot(kinetic_energy, potential_energy, contour_value, p, q, title, legend_anchor, plot_name):
    npts = 500
    x1_grid, x2_grid, f_x1_x2 = canonical_distribution_mesh(kinetic_energy, potential_energy, npts)
    figure, axis = pyplot.subplots(figsize=(8, 8))
    axis.set_xlabel(r"$q$")
    axis.set_ylabel(r"$p$")
    axis.set_xlim([-3.2, 3.2])
    axis.set_ylim([-3.2, 3.2])
    axis.set_title(title)
    contour = axis.contour(x1_grid, x2_grid, f_x1_x2, [contour_value], cmap=config.contour_color_map, alpha=0.3)
    axis.clabel(contour, contour.levels[::2], fmt="%.3f", inline=True, fontsize=15)
    axis.plot(q, p, lw=1, color="#320075")
    axis.plot(q[0], p[0], marker='o', color="#FF9500", markersize=13.0, label="Start")
    axis.plot(q[-1], p[-1], marker='o', color="#320075", markersize=13.0, label="End")
    axis.legend(bbox_to_anchor=legend_anchor)
    config.save_post_asset(figure, "hamiltonian_monte_carlo", plot_name)
Exemplo n.º 22
0
def contour_axis_plot_sigma_scan(μ1, μ2, σ1, σ2, γ, contour_value, legend, plot_name):
    npts = 500
    θ = numpy.linspace(0.0, 2.0 * numpy.pi, npts)
    figure, axis = pyplot.subplots(figsize=(8, 8))
    title = f"Bivariate Normal Distribution: " + \
             r"$σ_u$=" + f"{format(σ1, '2.1f')}, " + r"$\gamma$=" + \
             f"{format(γ, '2.1f')}, K={format(contour_value, '2.2f')}"
    axis.set_title(title)
    axis.set_xlabel(r"$\theta$")
    axis.set_ylabel(r"$r(\theta)$")
    for i in range(len(σ2)):
        c = pdf_contour_constant(μ1, μ2, σ1, σ2[i], γ, contour_value)
        rf = r(μ1, μ2, σ1, σ2[i], γ)
        axis.plot(θ, rf(θ, c), label=f"$σ_v$ = {format(σ2[i], '2.2f')}")

    axis.legend(bbox_to_anchor=legend)
    config.save_post_asset(figure, "bivariate_normal_distribution", plot_name)
Exemplo n.º 23
0
def transform_plot(μ1, μ2, σ1, σ2, γ, xrange, yrange, xnudge, ynudge, unudge, anudge, legend, plot_name):
    npts = 500
    figure, axis = pyplot.subplots(figsize=(9, 9))
    axis.set_xlabel("x")
    axis.set_ylabel("y")
    axis.set_ylim(yrange)
    axis.set_xlim(xrange)
    title = f"Bivariate Normal Transformation: γ={format(γ, '2.1f')}, " + \
             r"$σ_u$=" + f"{format(σ1, '2.1f')}, " + r"$σ_v$=" + \
             f"{format(σ2, '2.1f')}"
    axis.set_title(title)

    ar = (yrange[1] - yrange[0]) / (xrange[1] - xrange[0])
    θ = (180.0 / numpy.pi) * numpy.arctan(-γ / (ar * numpy.sqrt(1-γ**2))) + anudge

    c = [-4.0, -2.0, 0.0, 2.0, 4.0]
    x1 = numpy.zeros(len(c))
    for i in range(len(c)):
        y2 = numpy.linspace(3.0 * yrange[0], 3.0 * yrange[1], npts)
        transform_y1 = pdf_transform_y1_constant(μ1, μ2, σ1, σ2, γ, c[i])
        x1_y1, x2_y1 = transform_y1(y2)
        x1[i] = x1_y1[0]
        axis.text(x1[i] - 0.35, unudge[i], f"u={format(c[i], '2.0f')}", fontsize=18, rotation=90.0)
        if i == 0:
            axis.plot(x1_y1, x2_y1, color="#0067C4", label=r"Constant $u$")
        else:
            axis.plot(x1_y1, x2_y1, color="#0067C4")

    for i in range(len(c)):
        y1 = numpy.linspace(3.0 * yrange[0], 3.0 * yrange[1], npts)
        transform_y2 = pdf_transform_y2_constant(μ1, μ2, σ1, σ2, γ, c[i])
        x1_y2, x2_y2 = transform_y2(y1)
        if i == len(c) - 1:
            xoffset = x1[i] - 2.0 * xnudge
        else:
            xoffset = x1[i] + xnudge
        x2 = (γ * xoffset - (c[i] - μ2) / σ2) / numpy.sqrt(1.0 - γ**2)
        axis.text(xoffset, x2 + ynudge[i], f"v={format(c[i], '2.0f')}", fontsize=18, rotation=θ)
        if i == 0:
            axis.plot(x1_y2, x2_y2, color="#FF9500", label=r"Constant $v$")
        else:
            axis.plot(x1_y2, x2_y2, color="#FF9500")

    axis.legend(bbox_to_anchor=legend)
    config.save_post_asset(figure, "bivariate_normal_distribution", plot_name)
Exemplo n.º 24
0
def acceptance_plot(title, h, y_samples, ymax, xmax, legend_loc, plot_name):
    nsamples = len(y_samples)
    x_values = numpy.linspace(0.0, xmax, 500)
    samples, u, accepted_mask = rejection_sample(h, y_samples, ymax)
    rejected_mask = numpy.logical_not(accepted_mask)
    efficiency = 100.0 * (len(samples) / nsamples)
    figure, axis = pyplot.subplots(figsize=(10, 6))
    axis.set_title(title + f", Accepted {format(efficiency, '2.0f')}%")
    axis.set_ylim([0, 1.05])
    axis.set_yticks([0.2, 0.4, 0.6, 0.8, 1.0])
    axis.set_ylabel(r"$h(Y)/c$")
    axis.set_xlabel(r"$Y$")
    axis.set_xlim([0.0, 1.6])
    axis.plot(x_values, h(x_values) / ymax, zorder=5, lw=3, color="#5600C9")
    axis.scatter(y_samples[accepted_mask], u[accepted_mask], label="Accepted Samples", alpha=0.5, zorder=5)
    axis.scatter(y_samples[rejected_mask], u[rejected_mask], label="Rejected Samples", alpha=0.4, zorder=5)
    axis.legend(bbox_to_anchor=legend_loc, framealpha=0.9, edgecolor="#DDDDDD")
    config.save_post_asset(figure, "rejection_sampling", plot_name)
Exemplo n.º 25
0
def acceptance_plot(title, x, y, idx, text_pos, best_idx, xlim, plot):
    slope, y0, r2 = acceptance_regress(x[idx:], y[idx:])
    xfit = numpy.linspace(-1.0, 3.0, 100)
    bbox = dict(boxstyle='square,pad=1', facecolor="#FFFFFF", edgecolor="white")
    figure, axis = pyplot.subplots(figsize=(10, 7))
    axis.set_xlabel("Relative Step Size")
    axis.set_ylabel("Acceptance %")
    axis.set_title(title)
    axis.set_xlim(xlim)
    axis.set_prop_cycle(config.alternate_cycler)
    axis.set_ylim([0.05, 200.0])
    axis.loglog(x, y, zorder=6, marker='o', markersize=15.0, linestyle="None", markeredgewidth=1.0, label="Simulations")
    axis.loglog(x[best_idx], y[best_idx], zorder=6, marker='o', markersize=15.0, linestyle="None", markeredgewidth=1.0, label=f"({format(x[best_idx], '.3f')}, {format(y[best_idx], '2.0f')}%)")
    axis.loglog(10**xfit, acceptance_fit(xfit, slope, y0), zorder=5, color="#320075", label="Fit")
    axis.loglog(numpy.linspace(xlim[0], xlim[1], 100), numpy.full((100), 100.0), zorder=5, color="#320075")
    axis.text(text_pos[0], text_pos[1], f"slope={format(slope, '2.2f')}", fontsize=16, bbox=bbox)
    axis.legend(bbox_to_anchor=(0.5, 0.5))
    config.save_post_asset(figure, "metropolis_hastings_sampling", plot)
Exemplo n.º 26
0
def pdf_contour_plot(pdf, contour_values, xrange, yrange, labels, title,
                     plot_name):
    npts = 500
    f_x1_x2, x1_grid, x2_grid = grid_pdf(pdf, xrange, yrange, npts)
    figure, axis = pyplot.subplots(figsize=(8, 8))
    axis.set_xlabel(labels[0])
    axis.set_ylabel(labels[1])
    axis.set_title(title)
    contour = axis.contour(x1_grid,
                           x2_grid,
                           f_x1_x2,
                           contour_values,
                           cmap=config.contour_color_map)
    axis.clabel(contour,
                contour.levels[::2],
                fmt="%.3f",
                inline=True,
                fontsize=15)
    config.save_post_asset(figure, "hamiltonian_monte_carlo", plot_name)
Exemplo n.º 27
0
def phase_space_plot(p, q, title, labels, legend_anchor, plot_name):
    figure, axis = pyplot.subplots(figsize=(9, 9))
    axis.set_xlabel(labels[0])
    axis.set_ylabel(labels[1])
    axis.set_title(title)
    axis.plot(q, p, lw=1, color="#320075")
    axis.plot(q[0],
              p[0],
              marker='o',
              color="#FF9500",
              markersize=13.0,
              label="Start")
    axis.plot(q[-1],
              p[-1],
              marker='o',
              color="#320075",
              markersize=13.0,
              label="End")
    axis.legend(bbox_to_anchor=legend_anchor)
    config.save_post_asset(figure, "hamiltonian_monte_carlo", plot_name)
Exemplo n.º 28
0
def surface_plot(μ1, μ2, σ1, σ2, γ, zticks, plot_name):
    x1_grid, x2_grid, f_x1_x2 = pdf_mesh(μ1, μ2, σ1, σ2, γ)
    figure, axis = pyplot.subplots(figsize=(10, 10))
    title = f"Bivariate Normal Distribution: γ={format(γ, '2.1f')}, " + \
             r"$σ_u$=" + f"{format(σ1, '2.1f')}, " + r"$σ_v$=" + \
             f"{format(σ2, '2.1f')}"
    axis.set_title(title)
    axis.set_yticklabels([])
    axis.set_xticklabels([])

    axis_z = figure.add_subplot(111, projection='3d')
    axis_z.set_xlabel(r"$u$")
    axis_z.set_ylabel(r"$v$")
    axis_z.set_zticks(zticks)
    axis_z.set_xticks([-σ1*3.0, -σ1*2.0, -σ1, 0.0, σ1, σ1*2.0, σ1*3.0])
    axis_z.set_yticks([-σ2*3.0, -σ2*2.0, -σ2, 0.0, σ2, σ2*2.0, σ2*3.0])
    axis_z.plot_wireframe(x1_grid, x2_grid, f_x1_x2, rstride=25, cstride=25)
    axis_z.elev = 55.0
    axis_z.azim = 45.0
    config.save_post_asset(figure, "bivariate_normal_distribution", plot_name)
Exemplo n.º 29
0
def phase_space_time_series(title, PQ, time, ylim, file):
    nplots = 2
    figure, axis = pyplot.subplots(nrows=nplots, ncols=1, sharex=True, figsize=(10, 4*nplots))
    axis[0].set_title(title)
    axis[-1].set_xlabel("Time")

    axis[0].set_xlim([time[0], time[-1]])
    axis[0].set_ylim(ylim)
    axis[0].set_ylabel("q")
    axis[0].plot(time, numpy.real(PQ[:, 2, 0]), label=r"$q_1$")
    axis[0].plot(time, numpy.real(PQ[:, 3, 0]), label=r"$q_2$")
    axis[0].legend()

    axis[1].set_xlim([time[0], time[-1]])
    axis[1].set_ylim(ylim)
    axis[1].set_ylabel("p")
    axis[1].plot(time, numpy.real(PQ[:, 0, 0]), label=r"$p_1$")
    axis[1].plot(time, numpy.real(PQ[:, 1, 0]), label=r"$p_2$")
    axis[1].legend()

    config.save_post_asset(figure, "hamiltonian_monte_carlo", file)
Exemplo n.º 30
0
def contour_plot_sigma1_scan(μ1, μ2, σ1, σ2, γ, contour_value, legend, plot_name):
    npts = 500
    θ = numpy.linspace(0.0, 2.0 * numpy.pi, npts)

    figure, axis = pyplot.subplots(figsize=(8, 8))
    axis.set_xlabel(r"$u$")
    axis.set_ylabel(r"$v$")
    axis.set_xlim([-5.0, 5.0])
    axis.set_ylim([-5.0, 5.0])
    title = f"Bivariate Normal Distribution: γ={format(γ, '2.1f')}, " + \
         r"$σ_v$=" + f"{format(σ2, '2.1f')}, " + r"$K$=" + \
         f"{format(contour_value, '2.2f')}"
    axis.set_title(title)

    for i in range(len(σ1)):
        c = pdf_contour_constant(μ1, μ2, σ1[i], σ2, γ, contour_value)
        f = pdf_parametric_contour(μ1, μ2, σ1[i], σ2, γ)
        y1, y2 = f(θ, c)
        axis.plot(y1, y2, label=r"$σ_u$" + f" = {format(σ1[i], '2.3f')}")

    axis.legend(bbox_to_anchor=legend)
    config.save_post_asset(figure, "bivariate_normal_distribution", plot_name)