Пример #1
0
def plot(norm, subtitle, save):

    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    pp._updateRC()

    fig = plt.figure(figsize=(8, 8))  # make plot
    ax = []
    ax.append(fig.add_subplot(111))
    fig.suptitle(
        r'Magnitude of Change in Phase Space, $\Delta\mathcal{P}(x,p)$',
        fontsize=pp.ttfont)

    ax[0].set_title(subtitle, fontsize=pp.ttfont - 4)

    ax[0].set_xlabel(r'Integration Step, $n$')
    ax[0].set_ylabel(
        r"$|\Delta\mathcal{P}(x,\pi)| = \sqrt{(\pi_{t} + \pi_{\text{-}t})^2 + (x_{t} - x_{\text{-}t})^2}$"
    )

    n_steps = norm.size - 1  # norm contains 0th step
    steps = np.linspace(0, n_steps, n_steps + 1, True)

    ax[0].plot(steps, norm, linestyle='-', color='blue')

    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #2
0
def plot(x, y, z, save):
    """Plots a test image of the Bivariate Gaussian
    
    Required Inputs
        x,y,z   :: arrays        :: must all be same length
        save    :: string / bool :: save location or '' / False
    """

    pp = Pretty_Plotter()
    pp.s = 1.0
    pp._teXify()  # LaTeX

    fig = plt.figure(figsize=(5, 5))
    ax = fig.add_subplot(111)

    # create contour plot
    c = ax.contourf(x, y, z, 200, cmap=magma)

    # axis labels
    ax.set_xlabel(r'$\phi_1$', fontsize=pp.axfont)
    ax.set_ylabel(r'$\phi_2$', fontsize=pp.axfont)
    ax.grid(False)  # remove grid

    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #3
0
def plot(burn_in, samples, save):
    """Note that samples and burn_in contain the initial conditions"""
    
    pp = Pretty_Plotter()
    pp._teXify() # LaTeX
    pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    pp._updateRC()
    
    fig = plt.figure(figsize = (8, 8)) # make plot
    ax =[]
    ax.append(fig.add_subplot(111))
    
    name = "SHO"
    fig.suptitle(r'Example HMC path sampling the {} potential'.format(name),
        fontsize=16)
    
    ax[0].set_title(
        r'{} Burn-in Samples shown in orange'.format(burn_in.size-1))
    
    ax[0].set_ylabel(r'Sample, $n$')
    ax[0].set_xlabel(r"Position, $x$")
    
    # burn_in includes initial cond.
    # samples inclues final burn_in as initial cond.
    
    offst = burn_in.size # burn-in samples
    ax[0].plot(burn_in, np.arange(0, offst), #marker='x',
        linestyle='-', color='orange', label=r'Burn In')
    
    ax[0].plot(samples, np.arange(offst-1, offst-1 + samples.size), #marker='x',
        linestyle='-', color='blue', label=r'Sampling')
    
    pp.save_or_show(save, PLOT_LOC)
    pass
def plot(burn_in, samples, bg_xyz, save):
    """Note that samples and burn_in contain the initial conditions"""
    
    pp = Pretty_Plotter()
    pp._teXify() # LaTeX
    pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    pp.params['figure.subplot.top'] = 0.85
    pp._updateRC()
    
    fig = plt.figure(figsize=(8,8))
    ax = fig.add_subplot(111)
    
    ax.set_xlabel(r'$\mathrm{x_1}$')
    ax.set_ylabel(r'$\mathrm{x_2}$')
    
    fig.suptitle(r'Sampling a ring potential with HMC',
        fontsize=pp.ttfont)
    ax.set_title(r'Showing the burn-in \& first 100 HMC moves',
        fontsize=(pp.tfont-4))
    
    plt.grid(True)
    
    x, y, z = bg_xyz
    
    small = 1e-10
    mask = z<small
    z = np.ma.MaskedArray(z, mask, fill_value=np.nan)
    x = np.ma.MaskedArray(x, mask, fill_value=np.nan)
    y = np.ma.MaskedArray(y, mask, fill_value=np.nan)
    #
    levels = MaxNLocator(nbins=300).tick_values(z.min(), z.max())
    cmap = plt.get_cmap('viridis')
    norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
    
    # z = np.ma.array(z, mask=z < .01) # optionally mask to white below certain value
    cnt = ax.contourf(x, y, z,
            # levels=levels,
            # cmap=cmap,
            vmin=small,
        alpha=.3, antialiased=True)#, norm=LogNorm(vmin=z.min(), vmax=z.max()))
    
    
    l0 = ax.plot(burn_in[0,0], burn_in[0,1],
        marker='o', markerfacecolor='green'
        )

    l1 = ax.plot(burn_in[:,0], burn_in[:,1],
        color='grey', linestyle='--'
        # marker='o', markerfacecolor='red'
        )

    l2 = ax.plot(samples[:,0], samples[:,1],
        color='blue',
        marker='o', markerfacecolor='red'
        )
    
    cbar = plt.colorbar(cnt, ax=ax, shrink=0.9)
    cbar.ax.set_ylabel(r'Absolute change in Hamiltonian, $|{1 - e^{-\delta H(p,x)}}|$')
    pp.save_or_show(save, PLOT_LOC)
    pass
def plot(x, y, z, save):
    """Plots a test image of the Bivariate Gaussian
    
    Required Inputs
        x,y,z   :: arrays        :: must all be same length
        save    :: string / bool :: save location or '' / False
    """
    
    pp = Pretty_Plotter()
    pp._teXify() # LaTeX
    pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    pp.params['figure.subplot.top'] = 0.85
    pp._updateRC()
    
    fig = plt.figure(figsize=(8,8))
    ax = fig.add_subplot(111)
    
    # create contour plot
    c = ax.contourf(x, y, z, 100, cmap=plasma)
    
    # axis labels
    ax.set_xlabel(r'$x_1$')
    ax.set_ylabel(r'$x_2$')
    ax.grid(False) # remove grid
    
    fig.suptitle( # title
    r'Test plot of a 2D Multivariate (Bivariate) Gaussian', fontsize=pp.ttfont)
    
    ax.set_title( # subtitle
    r'Parameters: $\mu=\begin{pmatrix}0 & 0\end{pmatrix}$, $\Sigma = \begin{pmatrix} 1.0 & 0.8\\ 0.8 & 1.0 \end{pmatrix}$',
        fontsize=pp.tfont-4)
    
    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #6
0
def plot(acns, lines, subtitle, op_name, save):
    """Plots the two-point correlation function
    
    Required Inputs
        acs              :: {label:(x,y)} :: plots (x,y) as a stem plot with label=label
        lines            :: {label:(x,y)} :: plots (x,y) as a line with label=label
        subtitle :: str  :: subtitle for the plot
        op_name  :: str  :: the name of the operator for the title
        save     :: bool :: True saves the plot, False prints to the screen
    
    Optional Inputs
        all_lines :: bool :: if True, plots hamiltonian as well as all its components
    """

    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp._updateRC()

    fig = plt.figure(figsize=(8, 8))  # make plot
    ax = []
    ax.append(fig.add_subplot(111))

    # fig.suptitle(r"Autocorrelation Function for {}".format(op_name),
    # fontsize=pp.ttfont)

    ax[0].set_title(subtitle, fontsize=pp.ttfont)

    ax[0].set_xlabel(r'Fictitious time separation, $s$')

    ax[0].set_ylabel(r'Normalised Autocorrelation, $C(s)$')  # \
    # + r'(\hat{O}_{i+t} - \langle\hat{O}\rangle) \rangle}/{\langle \hat{O}_0^2 \rangle}$')

    for label, (x, y, e) in sorted(acns.iteritems()):
        c = next(measured_colours)
        # for some reason I occisionally need to add a fake plot
        # p2 = ax[0].add_patch(Rectangle((0, 0), 0, 0, fc=c, linewidth=0, alpha=.4, label=label))
        try:
            x, y, e = x[:250], y[:250], e[:250]
            if e is not None:
                # ax[0].fill_between(x, y-e, y+e, color=c, alpha=0.3, label=label)
                ax[0].errorbar(x,
                               y,
                               yerr=e,
                               c=c,
                               ecolor='k',
                               ms=3,
                               fmt='o',
                               alpha=0.5,
                               label=label)
            else:
                ax[0].scatter(x, y, c=c, ms=3, fmt='o', alpha=0.5, label=label)
        except Exception, e:
            print '\nFailed for "{}"'.format(label)
            print 'Wrong types? x:{} y:{} e:{}'.format(type(x), type(y),
                                                       type(e))
            print '\nError:'
            print e
def plot(samples, subtitle, y_label, save, extra_data=[]):
    """Note that samples and burn_in contain the initial conditions
    
    Required Inputs
        samples     :: the 1D numpy array to plot as a histogram
        subtitle    :: str :: subtitle for the plot
        y_label     :: str  :: the y axis label
        save        :: bool :: True saves the plot, False prints to the screen
    
    Optional Inputs
        extra_data :: list of dicts :: see below
    
    Expectations
        extra_data = [{'f':actual, 'label':theory},
                      {'f':fitted, 'label':None}]
        'f' contains a function with respect to a linear x range (x-axis) and the samples
        f(x, samples)
        'label' is a string or None
        
    """
    
    pp = Pretty_Plotter()
    pp._teXify() # LaTeX
    pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    pp._updateRC()
    
    fig = plt.figure(figsize = (8, 8)) # make plot
    ax =[]
    ax.append(fig.add_subplot(111))
    
    # burn_in includes initial cond.
    # samples inclues final burn_in as initial cond.
    fig.suptitle(subtitle,
        fontsize=16)
    ax[0].set_title(r'{} HMC samples'.format(samples.shape[0]), fontsize=pp.ttfont-4)
    
    ax[0].set_ylabel(y_label)
    ax[0].set_xlabel(r"Position, $x$")
    
    n, bins, patches = ax[0].hist(samples.ravel(), 50, normed=1, # histogram
        facecolor='green', alpha=0.2, label=r'Sampled data')
    
    n = 100 # size of linear space
    x = np.linspace(-5, 5, n)
    for i in extra_data: 
        params, fitted = i['f'](x, samples)
        ax[0].plot(x, fitted, 
            linewidth=2., alpha=0.6, label=i['label'].format(*params))
    
    ax[0].legend(loc='best', shadow=True, fontsize = pp.axfont)
    ax[0].grid(False)
    
    pp.save_or_show(save, PLOT_LOC)
    pass
def plot(lines, save=False):
    """Plots the two-point correlation function
    
    Required Inputs
        itau     :: {(x,y,e)} :: plots (x,y,e) as error bars
        pacc    :: {(x,y,e)} :: plots (x,y,e) as error bars
        # subtitle :: str  :: subtitle for the plot
        # op_name  :: str  :: the name of the operator for the title
        save     :: bool :: True saves the plot, False prints to the screen
    """
    
    pp = Pretty_Plotter()
    pp.s = 1.5
    pp._teXify() # LaTeX
    
    fig, ax = plt.subplots(1, figsize = (10, 8))
    ax = [ax]
    fig.suptitle(r"Showing that $n$ has little effect on $\tau_{\text{int}}$",
        fontsize=pp.ttfont+2)
    
    ax[0].set_title(r"HMC; lattice: $(100,)$; $m=0.01$; $M=10^5$; $\vartheta=\frac{\pi}{2}$", fontsize=pp.ttfont)
    
    ax[-1].set_xlabel(r'$\delta\tau$')
    
    ax[0].set_ylabel(r'$\tau_{\text{int}}$')
    for line in lines:
        m = next(markers)
        c = next(measured_colours)
        
        label = line['n_steps']
        x = line['step_size']
        y = line['itau']
        ax[0].scatter(x, y, alpha=0.5, c=c, marker=m, label=int(label))
    
    for a in ax:
        a.legend(loc='best', shadow=True, fontsize = pp.axfont)
        xi,xf = a.get_xlim()
        a.set_xlim(xmin=xi-0.01*(xf-xi), xmax=xf+0.01*(xf-xi)) # give a decent view of the first point
        
        yi,yf = a.get_ylim()
        a.set_ylim(ymax=yf + .05*(yf-yi), ymin=yi-.05*(yf-yi)) # give 5% extra room at top
    
    ax[0].legend(bbox_to_anchor=(0., -0.3, 1., .102), loc=9,
           ncol=6, mode="expand", borderaxespad=0.)
    fig.subplots_adjust(bottom=0.3)
    
    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #9
0
def plot(burn_in, samples, bg_xyz):
    """Note that samples and burn_in contain the initial conditions"""

    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    pp.params['figure.subplot.top'] = 0.85
    pp._updateRC()

    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111)

    ax.set_xlabel(r'$\mathrm{x_1}$')
    ax.set_ylabel(r'$\mathrm{x_2}$')

    fig.suptitle(r'Sampling Multivariate Gaussian with HMC',
                 fontsize=pp.ttfont)
    ax.set_title(
        r'Showing the burn-in \& first 100 HMC moves for:\ $\mu=\begin{pmatrix}0 & 0\end{pmatrix}$, $\Sigma = \begin{pmatrix} 1.0 & 0.8\\ 0.8 & 1.0 \end{pmatrix}$',
        fontsize=(pp.tfont - 4))

    plt.grid(True)

    x, y, z = bg_xyz
    # z = np.ma.array(z, mask=z < .01) # optionally mask to white below certain value
    cnt = ax.contourf(x, y, z, 100, cmap=viridis, alpha=.3, antialiased=True)

    l0 = ax.plot(burn_in[0, 0],
                 burn_in[0, 1],
                 marker='o',
                 markerfacecolor='green')

    l1 = ax.plot(burn_in[:, 0],
                 burn_in[:, 1],
                 color='grey',
                 linestyle='--'
                 # marker='o', markerfacecolor='red'
                 )

    l2 = ax.plot(samples[:, 0],
                 samples[:, 1],
                 color='blue',
                 marker='o',
                 markerfacecolor='red')
    cbar = plt.colorbar(p, ax=ax[0], shrink=0.9)
    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #10
0
def plot(burn_in, samples, save):
    """Note that samples and burn_in contain the initial conditions"""

    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    pp._updateRC()

    fig = plt.figure(figsize=(8, 8))  # make plot
    ax = []
    ax.append(fig.add_subplot(111))

    name = "QHO"
    fig.suptitle(
        r'HMC path configurations, sampling the {} potential'.format(name),
        fontsize=16)

    ax[0].set_title(
        r'{} Burn-in configurations shown in grey'.format(burn_in.shape[0] -
                                                          1))

    ax[0].set_ylabel(r'Time, $\tau$')
    ax[0].set_xlabel(r"Position, $x(\tau)$")

    for i in xrange(burn_in.shape[0]):
        offst = burn_in[i].size + 1  # burn-in samples
        ax[0].plot(burn_in[i],
                   np.arange(1, offst),
                   linestyle='--',
                   alpha=.2,
                   linewidth=3,
                   color='grey')

    for i in xrange(samples.shape[0]):
        offst = samples[i].size + 1  # burn-in samples
        ax[0].plot(samples[i],
                   np.arange(1, offst),
                   linestyle='-',
                   alpha=.3,
                   linewidth=3,
                   color='green')

    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #11
0
def plot(lines, subtitles, save):
    """
    Required Inputs
        lines       :: dict :: axis(int): (x(np.ndarray), y(np.ndarray), label(str))
        subtitles   :: dict :: axis(int): subtitle(str)
        save        :: bool/str :: string saves the plot as given string, False prints to the screen
    """
    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    pp._updateRC()

    fig, ax = plt.subplots(2, sharex=True, figsize=(8, 8))
    fig.subplots_adjust(hspace=0.2)

    fig.suptitle(
        r"Comparing methods of calculating $\mathcal{L}^{-1}F(\beta)$",
        fontsize=pp.ttfont)

    for i, subtitle in subtitles.iteritems():
        ax[i].set_title(subtitle, fontsize=pp.ttfont - 4)

    ax[-1].set_xlabel(
        r'Fictitious sample time, $t = \sum^j_{i=0}\tau_i \stackrel{j\to\infty}{=} j\bar{\tau} = j \delta \tau \bar{n}$'
    )

    for i, lines in lines.iteritems():
        for w, line in enumerate(lines):
            x, y, label = line
            style = '--' if not w % 2 else '-'
            ax[i].plot(x,
                       y,
                       label=label,
                       linewidth=(w + 1) * 2,
                       alpha=0.4,
                       linestyle=style)

    for i in ax:
        i.grid(True)
        i.legend(loc='best', shadow=True, fontsize=pp.tfont, fancybox=True)
        i.set_ylabel(r'Autocorrelation, $C(t)$')  # same y axis for all

    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #12
0
def plot(res, actual, save):
    """Plots 2 stacked figures:
        1. The ratio of changes in integrated autocorrelation time
        2. The ratio of changes in autocorrelation time
    
    Required Inputs
        probs           :: dict :: as below
        accepts         :: dict :: as below
        save            :: bool :: True saves the plot, False prints to the screen
    """
    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    pp._updateRC()

    fig, ax = plt.subplots(2, figsize=(8, 8))
    fig.suptitle(
        r'Comparisions of \verb|uWerr()| in \verb|python|:$A[X]$ and \verb|matlab|:$U[X]$',
        fontsize=pp.ttfont)
    ax[0].set_xlabel(r'Integration Window, $w$', fontsize=pp.tfont)

    x = np.arange(actual['itau_aav'].size)

    ax[0].set_title(r'Measuring the ratio $\Delta = 1 - \frac{U[X]}{A[X]}$',
                    fontsize=pp.tfont)
    ax[0].plot(x, (res['itau_aav'] - actual['itau_aav']) / res['itau_aav'],
               label=r'$X = \bar{\bar{\tau}}(w)$')
    ax[0].set_ylabel(r'$\Delta$', fontsize=pp.tfont - 2)
    ax[0].legend(loc='best', shadow=True, fontsize=pp.tfont, fancybox=True)

    diff_acorr = res['acorr'] - actual['acorr']
    ax[1].plot(x, diff_acorr / res['acorr'], label=r"$X = \Gamma(t)$")
    ax[1].set_ylabel(r"$\Delta$", fontsize=pp.tfont - 2)
    ax[1].legend(loc='best', shadow=True, fontsize=pp.tfont, fancybox=True)
    ax[1].set_xlabel(r'Autocorrelation Time, $t$', fontsize=pp.tfont)

    for i in ax:
        i.grid(True)
    pp.save_or_show(save, PLOT_LOC)
    pass
import matplotlib.ticker as plticker
import numpy as np
from PIL import Image
from scipy.signal import residuez, tf2zpk

from data import store
from plotter import Pretty_Plotter, PLOT_LOC
from common.utils import saveOrDisplay
from theory.autocorrelations import M2_Exp

file_name = __file__
save = False

# start plotting
pp = Pretty_Plotter()
pp._teXify() # LaTeX
pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
pp._updateRC()

dx = (0-2000)/10.
dy = (.0-.05)/5.

fig = plt.figure(figsize=(8,8))
ax = fig.add_subplot(111)

fig.suptitle(r"Verifying theory", fontsize=pp.tfont)
ax.set_title(r'Overlaying functions on an image of a published figure', fontsize=pp.tfont)
ax.set_xlabel(r'$t$', fontsize=pp.tfont)
ax.set_ylabel(r'$C_{M^2}(t)$', fontsize=pp.tfont)

xlim = (0, 2000)
def plot(
        probs,
        accepts,
        h_olds,
        h_news,
        exp_delta_hs,
        subtitle,
        labels,
        save,
        h_mdmc=None,
        mdmc_deltaH=None,  # for mdmc additions
):
    """Plots 3 stacked figures:
        1. the acceptance probability at each step
        2. the hamiltonian (old, new) at each step
        3. the exp{-delta H} at each step
    Overlayed with red bars is each instance in which a configuration was rejected
    by the Metropolis-Hastings accept/reject step
    
    Required Inputs
        probs           :: np.array :: acc. probs
        accepts         :: np.array :: array of boolean acceptances (True = accepted)
        h_olds          :: np.array :: old hamiltonian at each step
        h_news          :: np.array :: new hamiltonian at each step
        exp_delta_hs    :: np.array :: exp{-delta H} at each step
        h_mdmc          :: np.array :: 
        mdmc_deltaH     :: np.array ::
        subtitle        :: str      :: the subtitle to put in ax[0].set_title()
        save            :: bool :: True saves the plot, False prints to the screen
    """
    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    # pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
    pp._updateRC()

    fig, ax = plt.subplots(3, sharex=True, figsize=(8, 8))
    # fig.suptitle(r'Data from {} Metropolis acceptance steps'.format(len(probs)),
    #     fontsize=pp.ttfont)

    fig.subplots_adjust(hspace=0.2)

    l = probs.size  # length of HMC trajectory - lots rely on this being at the top

    ### Add top pseudo-title and bottom shared x-axis label
    ax[0].set_title(subtitle, fontsize=pp.tfont)
    ax[-1].set_xlabel(r'Markov Time, $j$')

    ### add the rejection points in the background
    xrng = range(1, l + 1)  # calculate xrange to match length
    for a in ax:  # iterate over each axis
        for x, val in zip(xrng, accepts):  # iterate over all rejection points
            if val == False:
                a.axvline(x=x, linewidth=4, color='red', alpha=0.2)

    ### add the lines to the plots
    ax[0].set_ylabel(r'Hamiltonian, $H_j$')
    ax[0].plot(xrng,
               h_olds,
               linestyle='-',
               color='blue',
               linewidth=2.,
               alpha=1,
               label=r'$H_{j-1}$')
    # ax[0].plot(xrng, h_news, linestyle='-', color='green', linewidth=2., alpha=0.4,
    #     label=r'$H(t)$')

    ax[1].set_ylabel(r'$\exp{-\delta H_j}$')

    ax[1].plot(xrng,
               exp_delta_hs,
               linestyle='-',
               color='blue',
               linewidth=2.,
               alpha=1,
               label=r'$\exp{ -\delta H_t}$')

    ax[2].set_ylabel(r'Acceptance $\rho_j$')
    ax[2].plot(xrng, probs, linestyle='-', color='blue', linewidth=2., alpha=1)

    ### test to see if we will plot all the intermediate MDMC steps
    plot_mdmc = (h_mdmc is not None) & (mdmc_deltaH is not None)

    if plot_mdmc:  # all these functions rely on l being calculated!!
        # functions to calculate the staggering of y and x
        # for the MDMC. Staggering means calculating the start and
        # end points of each single trajectory consisting of 1 MDMC integration
        n = h_mdmc.size / l - 1  # this calculates n_steps for the MDMC (in a backwards way)
        staggered_xi = np.arange(0, l)
        staggered_xf = np.arange(1, l + 1)
        staggered_y = lambda arr, offset: arr[0 + offset::(n + 1)]
        remove_links = lambda arr: [
            None if (i) % (n + 1) == 0 else a for i, a in enumerate(arr)
        ]

        ## calculate a linear space as a fraction of the HMC trajectory
        mdmc_x = np.asarray([
            np.linspace(i, j, n + 1)
            for i, j in zip(range(0, l), range(1, l + 1))
        ])
        mdmc_x = mdmc_x.flatten()

        ax[0].plot(mdmc_x,
                   remove_links(h_mdmc),
                   linestyle='--',
                   color='green',
                   linewidth=1,
                   alpha=1,
                   label=r'MDMC: $H_{j+1}$')
        ax[0].scatter(staggered_xi,
                      staggered_y(h_mdmc, 0),
                      color='red',
                      marker='o',
                      alpha=1,
                      label=r'Start MDMC')
        ax[0].scatter(staggered_xf,
                      staggered_y(h_mdmc, n),
                      color='red',
                      marker='x',
                      alpha=1,
                      label=r'End MDMC')

        ax[1].plot(mdmc_x,
                   remove_links(mdmc_deltaH),
                   linestyle='--',
                   color='blue',
                   linewidth=1.,
                   alpha=1,
                   label=r'MDMC: $\exp{ -\delta H_{j+1}$')
        ax[1].scatter(staggered_xi,
                      staggered_y(mdmc_deltaH, 0),
                      color='red',
                      marker='o',
                      alpha=1,
                      label=r'Start MDMC')
        ax[1].scatter(staggered_xf,
                      staggered_y(mdmc_deltaH, n),
                      color='red',
                      marker='x',
                      alpha=1,
                      label=r'End MDMC')

    ### adds labels to the plots
    for i, text in labels.iteritems():
        pp.add_label(ax[i], text, fontsize=pp.tfont)

    ### place legends
    ax[0].legend(loc='upper left',
                 shadow=True,
                 fontsize=pp.ipfont,
                 fancybox=True)
    ax[1].legend(loc='upper left',
                 shadow=True,
                 fontsize=pp.ipfont,
                 fancybox=True)

    ### formatting
    for i in ax:
        i.grid(True)
    # ax[1].set_yscale("log", nonposy='clip') # set logarithmic y-scale

    pp.save_or_show(save, PLOT_LOC)
    pass
def plot(itau, pacc, acorr, op, tint_th=None, pacc_th=None, op_th=None, save=False):
    """Plots the two-point correlation function
    
    Required Inputs
        itau     :: {(x,y,e)} :: plots (x,y,e) as error bars
        pacc    :: {(x,y,e)} :: plots (x,y,e) as error bars
        # subtitle :: str  :: subtitle for the plot
        # op_name  :: str  :: the name of the operator for the title
        save     :: bool :: True saves the plot, False prints to the screen
    """
    
    pp = Pretty_Plotter()
    pp._teXify() # LaTeX
    
    fig, ax = plt.subplots(3, sharex=True, figsize = (8, 8))
    fig.subplots_adjust(hspace=0.1)
    fig.suptitle(r"$\langle\rho_t\rangle_t$ and $\tau_{\text{int}}$ varying with $\delta\tau$ for $M^2$",
        fontsize=pp.ttfont)
    
    ax[0].set_title(r"HMC; lattice: $(100,)$; $n=20$; $m=0.1$; $M=10^5$", fontsize=pp.ttfont)
    
    ax[-1].set_xlabel(r'$\delta\tau$')
    
    ax[0].set_ylabel(r'$\tau_{\text{int}}$')
    x,y,e = itau
    ax[0].errorbar(x, y, yerr=e, ecolor='k', ms=3, fmt='o', alpha=0.5)
    if tint_th is not None:
        if len(tint_th) == 4:
            x,y,y_hi,y_lo = tint_th
            ax[0].fill_between(x, y_hi, y_lo, color='r', alpha=0.5, label='theory')
        else:
            x,y = tint_th
        ax[0].plot(x, y, c='r', alpha=1, linestyle='--')
    
    ax[1].set_ylabel(r'$\langle\rho_t\rangle_t$')
    x,y,e = pacc
    ax[1].errorbar(x, y, yerr=e, ecolor='k', ms=3, fmt='o', alpha=0.5)
    if pacc_th is not None:
        x,y = pacc_th
        ax[1].plot(x, y, c='r', alpha=0.7, linestyle='--', label='theory')
    
    # ax[2].set_ylabel(r'$\mathcal{C}_{\mathscr{X}^2}$')
    # x,y,e = acorr
    # for x_i,y_i,e_i in zip(x,y,e):
    #     c = next(measured_colours)
    #     ax[2].plot(np.arange(y_i.size), y_i, color=c, alpha=0.3, label=x_i)
    # ax[2].legend(loc='best', shadow=True, fancybox=True)
    ax[-1].set_ylabel(r'$\langle M^2_t\rangle_t$')
    x,y,e = op
    ax[-1].errorbar(x, y, yerr=e, ecolor='k', ms=3, fmt='o', alpha=0.5)
    if op_th is not None:
        x,y = op_th
        ax[-1].plot(x, y, c='r', alpha=0.7, linestyle='--', label='theory')
    
    for a in ax: 
        a.legend(loc='best', shadow=True, fontsize = pp.axfont)
        xi,xf = a.get_xlim()
        a.set_xlim(xmin=xi-0.05*(xf-xi)) # give a decent view of the first point
        
        yi,yf = a.get_ylim()
        a.set_ylim(ymax=yf + .05*(yf-yi), ymin=yi-.05*(yf-yi)) # give 5% extra room at top
    
    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #16
0
def plot(c_fn, errs, th_x_sq, spacing, subtitle, logscale, save):
    """Plots the two-point correlation function
    
    Required Inputs
        c_fn :: np.array :: correlation function
        err :: np.array :: errs in c_fn 
        spacing :: float :: the lattice spacing
        subtitle :: string :: subtitle for the plot
        save :: bool :: True saves the plot, False prints to the screen
        logscale :: bool :: adds a logscale
    
    Optional Inputs
        all_lines :: bool :: if True, plots hamiltonian as well as all its components
    """

    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp._updateRC()

    fig = plt.figure(figsize=(8, 8))  # make plot
    ax = []
    ax.append(fig.add_subplot(111))

    # fig.suptitle(r"Two-Point Correlation Function, $\langle x(0)x(\tau)\rangle$",
    # fontsize=pp.ttfont)

    ax[0].set_title(subtitle)

    ax[0].set_xlabel(r'Lattice Separation, $ia$')
    ax[0].set_ylabel(r'$\langle \phi_{t,x}\phi_{t,x+i} \rangle_{t,x}$')

    steps = np.linspace(0, spacing * c_fn.size, c_fn.size,
                        False)  # get x values
    # log_y = np.log(c_fn)        # regress for logarithmic scale
    # mask = np.isfinite(log_y)   # handles negatives in the logarithm
    # x = steps[mask]
    # y = log_y[mask]
    # linear regression of the exponential curve
    # m, c, r_val, p_val, std_err = stats.linregress(x, y)
    # fit = np.exp(m*steps + c)

    if th_x_sq is not None:
        th = ax[0].plot(steps,
                        th_x_sq,
                        color='green',
                        linewidth=3.,
                        linestyle='-',
                        alpha=0.2,
                        label=r'Theoretical prediction')

    # bf = ax[0].plot(steps, fit, color='blue',
    #      linewidth=3., linestyle = '-', alpha=0.2, label=r'fit: $y = e^{'\
    #          + '{:.2f}x'.format(m)+'}e^{'+'{:.2f}'.format(c) + r'}$')
    # err = c_fn*np.exp(c_fn)*errs
    f = ax[0].errorbar(steps,
                       c_fn,
                       yerr=errs,
                       ecolor='k',
                       ms=3,
                       fmt='o',
                       alpha=0.6,
                       label='Measured Data')

    ax[0].set_xlim(xmin=0)
    if logscale: ax[0].set_yscale("log", nonposy='clip')

    ax[0].legend(loc='best', shadow=True, fontsize=pp.axfont)
    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #17
0
def plot(x, lines, subtitle, op_name, save):
    """Plots the two-point correlation function
    
    Required Inputs
        x_vals   :: list :: list / np.ndarray of angles the routine was run for
        lines            :: {axis:(y, error)} :: contains (y,error) for each axis
        subtitle :: str  :: subtitle for the plot
        op_name  :: str  :: the name of the operator for the title
        save     :: bool :: True saves the plot, False prints to the screen
    """
    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp._updateRC()
    ax = []

    fig, ax = plt.subplots(4, sharex=True, figsize=(8, 8))
    # fig.suptitle(r"Integrated Autocorrelations for " \
    #     + r"{} and varying $\theta$".format(op_name), fontsize=pp.ttfont)

    fig.subplots_adjust(hspace=0.2)

    # Add top pseudo-title and bottom shared x-axis label
    ax[0].set_title(subtitle, fontsize=pp.tfont)
    ax[-1].set_xlabel(r'Mixing angle, $\vartheta$')
    ax[0].set_ylabel(r'$\tau_{\text{int}}$')
    ax[1].set_ylabel(r'$\langle X^2\rangle_{t}$')
    ax[2].set_ylabel(r'Int. window, $w$')
    ax[3].set_ylabel(r'$\langle \rho_t\rangle_t$')

    def formatFunc(tic, tic_loc):
        return r"${}\pi$".format(tic)

    ax[-1].get_xaxis().set_major_formatter(ticker.FuncFormatter(formatFunc))
    # Fix colours: A bug sometimes forces all colours the same
    colour = (i
              for i in random.sample(clist, len(clist)))  # defined top of file

    for k, v in lines.iteritems():
        for i, (y, err, label) in enumerate(v):
            if i > 0:
                s = '--'
                c = 'r'
            else:
                s = '-'
                c = next(colour)

            if err is None:
                ax[k].plot(x, y, c=c, lw=1., alpha=1, label=label, linestyle=s)
            else:
                y = np.asarray(y)
                err = np.asarray(err)
                ax[k].fill_between(x,
                                   y - err,
                                   y + err,
                                   color=c,
                                   alpha=1,
                                   label=label)
                # ax[k].errorbar(x, y, yerr=err, c=c, ecolor='k', ms=3, fmt='o', alpha=0.5,
                #     label=label)
            if i == 0:
                yi, yf = ax[k].get_ylim()
                ax[k].set_ylim(ymax=yf + .05 * (yf - yi),
                               ymin=yi - .05 * (yf - yi))
        ax[k].legend(loc='best', shadow=True, fontsize=pp.axfont)

    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #18
0
def anim(burn_in, samples, bg_xyz, save):

    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp.params['figure.subplot.top'] = 0.85
    pp._updateRC()

    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111)

    ax.set_xlabel(r'$\phi_{1}$', fontsize=pp.axfont)
    ax.set_ylabel(r'$\phi_{2}$', fontsize=pp.axfont)

    # fig.suptitle(r'Sampling a ring potential with HMC',
    # fontsize=pp.ttfont)
    # pot = r'$Q(\phi_{x}) = e^{-50|\phi_{x}^2 + \tfrac{1}{10}|}$'
    ax.set_title(r'Showing {} burn-in \& {} HMC moves'.format(
        max(burn_in.shape), max(samples.shape)),
                 fontsize=(pp.tfont))

    plt.grid(False)

    x, y, z = bg_xyz

    # small = 1e-1
    # mask = z<small
    # z = np.ma.MaskedArray(-z, mask, fill_value=0)
    # x = np.ma.MaskedArray(x, mask, fill_value=np.nan)
    # y = np.ma.MaskedArray(y, mask, fill_value=np.nan)

    # z = np.ma.array(z, mask=z < .01) # optionally mask to white below certain value
    cnt = ax.contourf(x, y, z, 100, cmap=viridis, alpha=.3, antialiased=True)

    l0 = ax.plot(burn_in[0, 0],
                 burn_in[0, 1],
                 marker='o',
                 markerfacecolor='green')

    l1 = ax.plot(
        burn_in[:, 0],
        burn_in[:, 1],
        color='green',
        linestyle='--',
        alpha=0.3,
        # marker='o', markerfacecolor='red',
    )

    points = ax.plot(samples[0, 0],
                     samples[0, 1],
                     color='blue',
                     alpha=0.7,
                     ms=3,
                     linestyle='',
                     marker='o')

    def getCollection(length=None, samples=samples, cmap='magma_r'):
        """Creates a collection from sample chain of shape: (length,dims)
        
        Optional Inputs 
            length :: int :: the include this many chain samples
        """

        if length is None: length = samples[:, 1].size
        x, y = samples[:, 0], samples[:, 1]
        points = np.array([x, y]).T.reshape(-1, 1, 2)
        segments = np.concatenate([points[:-1], points[1:]], axis=1)

        lc = LineCollection(segments,
                            cmap=plt.get_cmap(cmap),
                            norm=plt.Normalize(250, 1500))
        lc.set_array(np.arange(length))
        lc.set_linewidth(1.)
        lc.set_alpha(0.3)
        return lc

    length = 50

    def init():
        points.set_data([], [])
        return points,

    def animate(i):  # animation func
        # if i==1: del ax.collections[-2] # replace these lines

        points.set_data(samples[:i, 0], samples[:i, 1])
        # lc = getCollection(length=None)
        # col = ax.add_collection(lc)
        return points,

    anim = animation.FuncAnimation(fig,
                                   animate,
                                   np.arange(length),
                                   interval=50)
    plt.show()
    pass
Пример #19
0
def plot(itau,
         pacc,
         acorr,
         op,
         tint_th=None,
         pacc_th=None,
         op_th=None,
         save=False):
    """Plots the two-point correlation function
    
    Required Inputs
        itau     :: {(x,y,e)} :: plots (x,y,e) as error bars
        pacc    :: {(x,y,e)} :: plots (x,y,e) as error bars
        # subtitle :: str  :: subtitle for the plot
        # op_name  :: str  :: the name of the operator for the title
        save     :: bool :: True saves the plot, False prints to the screen
    """

    # annotate minimum values
    min_idx = np.argmin(itau[1])

    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX

    fig, ax = plt.subplots(3, sharex=True, figsize=(8, 8))
    fig.subplots_adjust(hspace=0.1)
    fig.suptitle(
        r"$\langle\rho_t\rangle_t$ and $\tau_{\text{int}}$ varying with $\delta\tau$ for $X^2$",
        fontsize=pp.ttfont)

    ax[0].set_title(r"HMC; lattice: $(100,)$; $n=20$; $m=0.1$; $M=10^5$",
                    fontsize=pp.ttfont)

    ax[-1].set_xlabel(r'$\delta\tau$')

    ax[0].set_ylabel(r'$\tau_{\text{int}}$')
    x, y, e = itau
    if len(x) > 100:
        ax[0].fill_between(x, y + e, y - e, alpha=0.5, label='Measured')
    else:
        ax[1].errorbar(x,
                       y,
                       yerr=e,
                       ecolor='k',
                       ms=3,
                       fmt='o',
                       alpha=0.5,
                       label='Measured')

    ax[0].scatter(x[min_idx], y[min_idx], c='r', alpha=1,
        label=r'min $\tau_{\text{int}}=' \
            + r'{:8.4f}$ at $\delta\tau={:5.3f}$'.format(y[min_idx],x[min_idx]))

    if tint_th is not None:
        if len(tint_th) == 4:
            x, y, y_hi, y_lo = tint_th
            ax[0].fill_between(x,
                               y_hi,
                               y_lo,
                               color='r',
                               alpha=0.5,
                               label='Theory')
        else:
            x, y = tint_th
            ax[0].plot(x, y, c='r', alpha=1, linestyle='-')

    ax[1].set_ylabel(r'$\langle\rho_t\rangle_t$')
    x, y, e = pacc

    if len(x) > 100:
        ax[1].fill_between(x, y + e, y - e, alpha=0.5, label='Measured')
        ax[1].plot(x, y, alpha=0.5)
    else:
        ax[1].errorbar(x,
                       y,
                       yerr=e,
                       ecolor='k',
                       ms=3,
                       fmt='o',
                       alpha=0.5,
                       label='Measured')

    ax[1].scatter(x[min_idx], y[min_idx], c='r', alpha=1,
        label=r'min $\tau_{\text{int}}$' \
            + r' at $\langle\rho_t\rangle_t={:5.3f}\pm{:.1f}$'.format(y[min_idx], e[min_idx]))

    if pacc_th is not None:
        x, y = pacc_th
        ax[1].plot(x, y, c='r', alpha=0.7, linestyle='--', label='Theory')

    ax[-1].set_ylabel(r'$\langle X^2_t\rangle_t$')
    x, y, e = op

    if len(x) > 100:
        ax[-1].fill_between(x, y + e, y - e, alpha=0.5, label='Measured')
    else:
        ax[-1].errorbar(x,
                        y,
                        yerr=e,
                        ecolor='k',
                        ms=3,
                        fmt='o',
                        alpha=0.5,
                        label='Measured')

    if op_th is not None:
        x, y = op_th
        ax[-1].plot(x, y, c='r', alpha=0.7, linestyle='-', label='Theory')

    for a in ax:
        xi, xf = a.get_xlim()
        a.set_xlim(xmin=xi - 0.01 * (xf - xi), xmax=xf + 0.01 *
                   (xf - xi))  # give a decent view of the first point

        yi, yf = a.get_ylim()
        a.set_ylim(ymax=yf + .05 * (yf - yi),
                   ymin=yi - .05 * (yf - yi))  # give 5% extra room at top

    ax[0].legend(loc='upper left', shadow=True, fontsize=pp.axfont)
    ax[-1].legend(loc='lower left', shadow=True, fontsize=pp.axfont)
    ax[1].legend(loc='best', shadow=True, fontsize=pp.axfont)
    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #20
0
def plot(scats, lines, subtitle, save):
    """Reproduces figure 1 from [1]
       
    
    Required Inputs
        lines           :: {label:(x,y)} :: plots (x,y) as a line with label=label
        scats           :: {label:(x,y)} :: plots (x,y) as a scatter with label=label
        subtitle        :: str      :: the subtitle to put in ax[0].set_title()
        save            :: bool :: True saves the plot, False prints to the screen
    """
    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp._updateRC()

    fig = plt.figure(figsize=(8, 8))  # make plot
    ax = []
    ax.append(fig.add_subplot(111))

    # fig.suptitle(r'Testing Acceptance Rate', fontsize=pp.ttfont)

    ax[0].set_title(subtitle, fontsize=pp.tfont)
    ax[-1].set_xlabel(r'Trajectory Length, $\tau=n\delta\tau$')

    ### add the lines to the plots
    ax[0].set_ylabel(r'Average Acceptance, $\langle \rho_t \rangle_t$')

    colour = [i for i in random.sample(clist, len(clist))]
    ms = [i for i in random.sample(mlist, len(mlist))]
    darkclist = [i for i in colors.cnames if 'dark' in i]
    darkcolour = [i for i in random.sample(darkclist, len(darkclist))]
    lightcolour = map(lambda strng: strng.replace('dark', ''), darkcolour)

    cs = iter(colour)
    m = iter(ms)
    lc = iter(lightcolour)
    # clist = [i for i in colors.ColorConverter.colors if i != 'w']
    # colour = (i for i in random.sample(clist, len(clist)))
    for label, line in lines.iteritems():
        ax[0].plot(*line,
                   linestyle='-',
                   color=next(lc),
                   linewidth=2.,
                   alpha=0.4,
                   label=label)

    for label, scats in scats.iteritems():
        x, y, e = scats
        ax[0].errorbar(x,
                       y,
                       yerr=e,
                       ecolor='k',
                       ms=6,
                       fmt=next(m),
                       alpha=0.9,
                       label=label,
                       c=next(cs),
                       lw=1,
                       elinewidth=1)
    ### place legends
    ax[0].legend(loc='best', shadow=True, fontsize=pp.ipfont, fancybox=True)

    ### formatting
    for i in ax:
        i.grid(True)

    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #21
0
# grab errors
print 'getting errors...'
ans = uWerr(op, a)
_, _, _, itau, itau_diff, _, acns = ans  # extract data
my_w = getW(itau, itau_diff, n=n_samples)  # get window length
my_err = acorrnErr(acns, my_w, n_samples)  # get autocorr errors
my_err *= np.sqrt(n_samples) / np.sqrt(counts)

# theory calclations
if cpp:
    th_x = np.linspace(min_sep, max_sep, 1000)
    th = np.array([hmc(p, phi, r, i) for i in th_x])

pp = Pretty_Plotter()
pp._teXify()
pp.params['text.latex.preamble'] = [r"\usepackage{amsmath}"]
pp.params['text.latex.preamble'] = [r"\usepackage{mathrsfs}"]
pp._updateRC()

fig = plt.figure(figsize=(8, 8))  # make plot
ax = []
fig, ax = plt.subplots(2, sharex=True, figsize=(8, 8))
ax[-1].set_xlabel(
    r'Fictitious time separation, $t : t = m\delta\tau$ for $m\in\mathbb{N}$')

main_title = r'HMC Autocorrelation Data for Exponentially Distributed Trajectories'
info_title = r'Samples: $10^{:d}$ Lattice: ({:d},{:d}), $m={:3.1f}$, $n={:d}$, '.format(
    int(np.log10(n_samples)), n, dim, m,
    n_steps) + r'$\delta\tau = \frac{2}{m(3\sqrt{3} - \sqrt{15})}\frac{1}{n}$'
th_label = r'Theory: $\mathcal{C}_{\text{HMC}}(t; P_{\text{acc}}=' + r'{:5.3f}, \phi = {:5.3f}, r={:5.3f}'.format(
def plot(y1, y2, subtitle, save, all_lines=False):
    """A plot of y1 and y2 as functions of the steps which
    are implicit from the length of the arrays
    
    Required Inputs
        y1 :: np.array :: conj kinetic energy array
        y2   :: np.array :: shape is either (n, 3) or (n,)
        subtitle :: string :: subtitle for the plot
        save :: bool :: True saves the plot, False prints to the screen
    
    Optional Inputs
        all_lines :: bool :: if True, plots hamiltonian as well as all its components
    """

    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp._updateRC()

    fig = plt.figure(figsize=(8, 8))  # make plot
    ax = []
    ax.append(fig.add_subplot(111))

    # fig.suptitle(r"Change in Energy during Leap Frog integration",
    #     fontsize=pp.ttfont)

    ax[0].set_title(subtitle, fontsize=pp.ttfont)

    ax[0].set_xlabel(r'Number of Leap Frog Steps, $n$', fontsize=pp.axfont)
    ax[0].set_ylabel(r'Change in Energy, $\delta E_{n} = E_{n} - E_0$',
                     fontsize=pp.axfont)

    steps = np.linspace(0, y1.size, y1.size, True)

    # check for multiple values in the potential
    multi_pot = (len(y2.shape) > 1)
    print multi_pot, y2.shape
    if multi_pot:
        action, k, u = zip(*y2)
        k = np.asarray(k)
        u = np.asarray(u)
    else:
        action = y2

    action = np.asarray(action)

    h = ax[0].plot(
        steps,
        y1 + np.asarray(action),  # Full Hamiltonian
        label=r"$\delta H_t = \delta T_n + \delta S_t$",
        color='blue',
        linewidth=5.,
        linestyle='-',
        alpha=1)

    if all_lines:
        t = ax[0].plot(
            steps,
            np.asarray(y1),  # Kinetic Energy (conjugate)
            label=r'$\delta T_n$',
            color='darkred',
            linewidth=2.,
            linestyle='-',
            alpha=1)

        if multi_pot:
            s = ax[0].plot(
                steps,
                np.asarray(action),  # Potential Energy (Action)
                label=
                r'$\delta \delta S_n = \sum_{n} (\delta T^{(s)}_n + \delta V^{(s)}_n)$',
                color='darkgreen',
                linewidth=1.,
                linestyle='-',
                alpha=1)

            t_s = ax[0].plot(
                steps,
                np.asarray(k),  # Kinetic Energy in Action
                label=r'$\sum_{n} \delta T^{(s)}_n$',
                color='red',
                linewidth=1.,
                linestyle='--',
                alpha=2.)

            v_s = ax[0].plot(
                steps,
                np.asarray(u),  # Potential Energy in Action
                label=r'$\sum_{n} \delta V^{(s)}_n$',
                color='green',
                linewidth=1.,
                linestyle='--',
                alpha=1.)
        else:
            s = ax[0].plot(
                steps,
                np.asarray(action),  # Potential Energy (Action)
                label=r'$\delta S(x,t) = \frac{1}{2}\delta \phi_{n,x}^2$',
                color='darkgreen',
                linewidth=3.,
                linestyle='-',
                alpha=1)

    # add legend
    ax[0].legend(loc='upper left', shadow=True, fontsize=pp.axfont)

    pp.save_or_show(save, PLOT_LOC)
    pass
def plot(burn_in, samples, bg_xyz, save):
    """Note that samples and burn_in contain the initial conditions"""

    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp.params['figure.subplot.top'] = 0.85
    pp._updateRC()

    fig = plt.figure(figsize=(8, 8))
    ax = fig.add_subplot(111)

    ax.set_xlabel(r'$\phi_{1}$', fontsize=pp.axfont)
    ax.set_ylabel(r'$\phi_{2}$', fontsize=pp.axfont)

    # fig.suptitle(r'Sampling a ring potential with HMC',
    # fontsize=pp.ttfont)
    pot = r'$Q(\phi_{x}) = e^{-50\left|\phi_{x}^2 + 1/10\right|}$'
    ax.set_title(r'{} burn-in \& {} MH moves'.format(max(burn_in.shape),
                                                     max(samples.shape)),
                 fontsize=pp.tfont)

    plt.grid(False)

    x, y, z = bg_xyz

    # small = 1e-1
    # mask = z<small
    # z = np.ma.MaskedArray(-z, mask, fill_value=0)
    # x = np.ma.MaskedArray(x, mask, fill_value=np.nan)
    # y = np.ma.MaskedArray(y, mask, fill_value=np.nan)

    cnt = ax.contourf(x, y, z, 100, cmap=viridis, alpha=.3, antialiased=True)

    l0 = ax.plot(burn_in[0, 0],
                 burn_in[0, 1],
                 marker='o',
                 markerfacecolor='green')

    l1 = ax.plot(
        burn_in[:, 0],
        burn_in[:, 1],
        color='green',
        linestyle='--',
        alpha=0.3,
        # marker='o', markerfacecolor='red'
    )

    x, y = samples[:, 0], samples[:, 1]
    points = np.array([x, y]).T.reshape(-1, 1, 2)
    segments = np.concatenate([points[:-1], points[1:]], axis=1)

    lc = LineCollection(segments,
                        cmap=plt.get_cmap('magma_r'),
                        norm=plt.Normalize(250, 1500))
    lc.set_array(np.arange(samples[:, 1].size))
    lc.set_linewidth(1.)
    lc.set_alpha(0.3)
    ax.add_collection(lc)

    l2 = ax.scatter(
        samples[:, 0],
        samples[:, 1],
        color='blue',
        alpha=0.7,
        s=3,
        marker='o',
    )

    pp.save_or_show(save, PLOT_LOC)
    pass
Пример #24
0
def plot(lines_d, x_lst, ws, subtitle, mcore, angle_labels, op_name, save):
    """Plots the two-point correlation function
    
    Required Inputs
        x_lst    :: list :: list of x_values for each angle that was run
        lines_d  :: {axis:[(y,label)]} :: plots (y,error,label) for each list item
        ws       :: list :: list of integration windows
        subtitle :: str  :: subtitle for the plot
        mcore    :: bool :: are there multicore operations? (>1 mixing angles)
        op_name  :: str  :: the name of the operator for the title
        angle_labels :: list :: the angle label text for legend plotting
        save     :: bool :: True saves the plot, False prints to the screen
    """

    pp = Pretty_Plotter()
    pp._teXify()  # LaTeX
    pp.params['text.latex.preamble'] = r"\usepackage{amsfonts}"
    pp.params['text.latex.preamble'] = r"\usepackage{amsmath}"
    pp._updateRC()

    fig = plt.figure(figsize=(8, 8))  # make plot
    ax = []

    fig, ax = plt.subplots(3, sharex=True, figsize=(8, 8))
    fig.suptitle(r"Autocorrelation and Errors for {}".format(op_name),
                 fontsize=pp.ttfont)

    fig.subplots_adjust(hspace=0.1)

    # Add top pseudo-title and bottom shared x-axis label
    ax[0].set_title(subtitle, fontsize=pp.tfont)
    ax[-1].set_xlabel(r'Window Length')

    if not mcore:  # don't want clutter in a multiple plot env.
        for a in range(1, len(ax)):  # Add the Window stop point as a red line
            # there is only one window item if not multiple lines
            ax[a].axvline(x=ws[0], linewidth=4, color='red', alpha=0.1)

    ax[0].set_ylabel(r'$g(w)$')
    ax[1].set_ylabel(r'$\tau_{\text{int}}(w)$')
    ax[2].set_ylabel(r'Autocorrelation, $\Gamma(t)$')

    #### plot for the 0th axis ####
    line_list = lines_d[0]
    axis = ax[0]
    theory_colours = iter(colour)
    measured_colours = iter(colour)
    for x, lines in zip(x_lst, line_list):
        m = next(marker)  # get next marker style
        c = next(measured_colours)  # get next colour
        th_c = next(theory_colours)
        # split into y function, errors in y and label
        y, e, l = lines  # in this case there are no errors or labels used

        # allow plots in diff colours for +/
        yp = y.copy()
        yp[yp < 0] = np.nan  # hide negative values
        ym = y.copy()
        ym[ym >= 0] = np.nan  # hide positive values

        if not mcore:
            axis.scatter(x,
                         yp,
                         marker='o',
                         color='g',
                         linewidth=2.,
                         alpha=0.6,
                         label=r'$g(t) \ge 0$')
            axis.scatter(x,
                         ym,
                         marker='x',
                         color='r',
                         linewidth=2.,
                         alpha=0.6,
                         label=r'$g(t) < 0$')
        else:
            axis.plot(x, yp, color=c, lw=1., alpha=0.6)  # label with the angle
            axis.plot(x, ym, color='r', lw=1., alpha=0.6)
            once_label = None  # set to blank so don't get multiple copies

    if not mcore: axis.legend(loc='best', shadow=True, fontsize=pp.axfont)

    #### plot the 1st axis ###
    # there is no angle label on the lines themselves on this axis
    # because the colours are synchronised across each plot
    # so the label on the bottom axis is enough
    line_list = lines_d[1]
    axis = ax[1]
    theory_colours = iter(colour)
    measured_colours = iter(colour)
    for x, lines in zip(x_lst, line_list):
        m = next(marker)  # get next marker style
        c = next(measured_colours)  # get next colour
        th_c = next(theory_colours)
        y, e, l, t = lines  # split into y function, errors, label and theory
        # try:
        #     axis.fill_between(x, y-e, y+e, color=c, alpha=0.5)
        # except:
        #     print "errors are dodgy"
        axis.errorbar(x,
                      y,
                      yerr=e,
                      markersize=3,
                      color=c,
                      fmt=m,
                      alpha=0.5,
                      ecolor='k')
        if t is not None:
            axis.axhline(y=t, linewidth=1, color=th_c, linestyle='--')

        # Only add informative label if there is only one line
        # adds a pretty text box above the middle plot with info
        # contained in the variable l - assigned in preparePlot()
        if not mcore: pp.add_label(axis, l, fontsize=pp.tfont)

    #### plot the 2nd axis ###
    # This plot explicitly list the labels for all the angles
    line_list = lines_d[2]
    axis = ax[2]
    theory_colours = iter(colour)
    measured_colours = iter(colour)
    for x, lines, a in zip(x_lst, line_list, angle_labels):
        m = next(marker)  # get next marker style
        c = next(measured_colours)  # get next colour
        th_c = next(theory_colours)
        y, e, l, t = lines  # split into y function, errors in y and label
        try:  # errors when there are low number of sims
            axis.fill_between(x, y - e, y + e, color=c, alpha=0.6, label=a)
            # axis.errorbar(x, y, yerr=e, label = a,
#                 markersize=3, color=c, fmt=m, alpha=0.5, ecolor='k')
        except:  # avoid crashing
            print 'Too few MCMC simulations to plot autocorrelations for: {}'.format(
                a)

        if t is not None:
            axis.plot(x,
                      t,
                      linewidth=1.2,
                      alpha=0.9,
                      color=th_c,
                      linestyle='--',
                      label='Theoretical')

    axis.legend(loc='best', shadow=True, fontsize=pp.axfont)

    #### start outdated section ####
    ## this won't work after the changes but shows the general idea of fitting a curve
    #
    # for i in range(1, len(lines)):              # add best fit lines
    #     x, y = lines[i][:2]
    #     popt, pcov = curve_fit(expFit, x, y)    # approx A+Bexp(-t/C)
    #     if not mcore:
    #         l_th = r'Fit: $f(t) = {:.1f} + {:.1f}'.format(popt[0], popt[1]) \
    #         + r'e^{-t/' +'{:.2f}'.format(popt[2]) + r'}$'
    #     else:
    #         l_th = None
    #     ax[i].plot(x, expFit(x, *popt), label = l_th,
    #         linestyle = '-', color=c, linewidth=2., alpha=.5)
    #### end outdated section ####

    # fix the limits so the plots have nice room
    xi, xf = ax[2].get_xlim()
    ax[2].set_xlim(xmin=xi - .05 * (xf - xi))  # decent view of the first point
    for a in ax:  # 5% extra room at top & add legend
        yi, yf = a.get_ylim()
        a.set_ylim(ymax=yf + .05 * (yf - yi), ymin=yi - .05 * (yf - yi))
    ax[-1].set_ylim(ymax=2)
    pp.save_or_show(save, PLOT_LOC)
    pass