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))

ax[0].set_title(
    r'Checking stability of $g_W(\tau_W)$ for $\tau_W = \lim_{g_{\text{int}}\to 0} \left[\ln\left(1+\frac{1}{g_{\text{int}}}\right)\right]^{-1}$',
    fontsize=pp.ttfont)

ax[0].set_ylabel(r'$g_W(\tau_W) = e^{-1/\tau_W} - \tau_W$')
ax[0].set_xlabel(r'$g_{\text{int}}$')

x = np.linspace(-.2, .1, 1000)
ax[0].plot(x,
           np.exp(-1. / np.log(1. + 1. / x.clip(0))) - x,
           label=r'$1/0$ = np.inf',
           linewidth=2.,
           alpha=.4)
ax[0].plot(x,
           np.exp(-1. / np.log(1. + 1. / x.clip(np.finfo(float).eps))) - x,
           label=r"$1/0$ = `eps'",
           linewidth=2.,
           alpha=.4)

ax[0].legend(loc='best', shadow=True, fontsize=pp.axfont)
pp.save_or_show(saveOrDisplay(save, __file__), PLOT_LOC)
minor_yticks = np.linspace(0, .05, 5*2+1, endpoint=True)

ax.xaxis.set_ticks(minor_xticks, minor = True)
ax.yaxis.set_ticks(minor_yticks, minor = True)

# Specify different settings for major and minor grids
ax.grid(which = 'minor', alpha = 0.3)
ax.grid(which = 'major', alpha = 0.7)

# im = np.asarray(Image.open('results/figures/archive/misc_appendixA3_acorr_img.png'))
# store.store(im, __file__, '_img')
im = store.load('results/data/numpy_objs/misc_appendixA3_acorr_img.json')
ax.imshow(im, extent=xlim+ylim, aspect='auto', label = r'paper')

m = 0.01
r = iter([np.sqrt(3)*m, .5*m*(3*np.sqrt(3)+np.sqrt(15)), .5*m*(3*np.sqrt(3)-np.sqrt(15))])

f = M2_Exp(next(r), m)
x = np.linspace(0, 1000, 1000, True)

plt.plot(x, f.eval(x), linewidth=4., color='red', alpha=0.6, linestyle="--", 
    label = r'$r = \sqrt{3}m$')
plt.plot(x, f.eval(x, tau=1/next(r)), linewidth=4., color='green', alpha=0.6, linestyle="--",
    label = r'$r = \frac{m}{2}(3\sqrt{3} + \sqrt{15})$')
plt.plot(x, f.eval(x, tau=1/next(r)), linewidth=4., color='blue', alpha=0.6, linestyle="--",
    label = r'$r = \frac{m}{2}(3\sqrt{3} - \sqrt{15})$')

ax.legend(loc='lower right', shadow=True, fancybox=True)

pp.save_or_show(saveOrDisplay(save, file_name), PLOT_LOC)
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
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(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
Exemple #6
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
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
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
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
Exemple #10
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
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