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 main(x0, pot, file_name, n_samples, n_burn_in,
        mixing_angles, step_sizes, separations, opFn ,n_steps = 1,
        tintTh=None, paccTh = None, opTh = None, plot_res=1000,
        save = False):
    """A wrapper function
    
    Required Inputs
        x0          :: np.array :: initial position input to the HMC algorithm
        pot         :: potential class :: defined in hmc.potentials
        file_name   :: string :: the final plot will be saved with a similar name if save=True
        n_samples   :: int :: number of HMC samples
        n_burn_in   :: int :: number of burn in samples
        mixing_angles :: iterable :: mixing angles for the HMC algorithm
        angle_labels  :: list :: list of labels for the angles provided
        opFn        :: func :: function for autocorellations - takes one input: samples
        op_name     :: str :: name of opFn for plotting
        separations :: iterable :: lengths of autocorellations
        max_sep     :: float :: define the max separation
    
    Optional Inputs
        rand_steps :: bool :: probability of with prob
        step_size :: float :: MDMC step size
        n_steps :: int :: number of MDMC steps
        spacing :: float :: lattice spacing
        acFunc :: func :: function for evaluating autocorrelations
        save :: bool :: True saves the plot, False prints to the screen
    """
    
    # required declarations. If no lines are provided this still allows iteration for 0 times
    lines = {}  # contains the label as the key and a tuple as (x,y) data in the entry
    acs = {}
    
    rng = np.random.RandomState()
    
    print 'Running Model: {}'.format(file_name)
    
    def coreFunc(a):
        """runs the below for an angle, a
        Allows multiprocessing across a range of values for a
        """
        i,d,a = a
        model = Model(x0, pot=pot, rng=rng, step_size = d,
          n_steps = n_steps, rand_steps=False)
        
        c = acorr.Autocorrelations_1d(model)
        c.runModel(n_samples=n_samples, n_burn_in=n_burn_in, mixing_angle = a, verbose=False, verb_pos=i)
        acs = c.getAcorr(separations, opFn, norm = False)
        
        # get parameters generated
        pacc = c.model.p_acc
        pacc_err = np.std(c.model.sampler.accept.accept_rates)
        ans = errors.uWerr(c.op_samples, acorr=acs)         # get errors
        op_av, op_diff, _, itau, itau_diff, _, acns = ans             # extract data
        w = errors.getW(itau, itau_diff, n=n_samples)       # get window length
        if not np.isnan(w):
            acns_err = errors.acorrnErr(acns, w, n_samples)     # get error estimates
            acs = acns
        else:
            acns_err = np.full(acs.shape, np.nan)
            itau = itau_diff = np.nan
        
        return op_av, op_diff, acs, acns_err, itau, itau_diff, pacc, pacc_err, w
    
    # use multiprocessings
    elms = step_sizes.size*mixing_angles.size
    combinations = np.zeros((elms,3))
    combinations[:,1:] = np.array(np.meshgrid(step_sizes, mixing_angles)).T.reshape(-1,2)
    combinations[:,0] = np.arange(elms)
    
    ans = prll_map(coreFunc, combinations, verbose=True)
    
    print 'Finished Running Model: {}'.format(file_name)
    
    # results have now been obtained. This operation is a dimension shuffle
    # Currently the first iterable dimension contains one copy of each item
    # Want to split into separate arrays each of length n
    op_av, op_diff, acs, acns_err, itau, itau_diff, pacc, pacc_err, w = zip(*ans)
    
    op_av       = np.array(op_av)
    op_diff     = np.array(op_diff)
    acs         = np.array(acs)
    acns_err    = np.array(acns_err)
    itau        = np.array(itau)
    itau_diff   = np.array(itau_diff)
    pacc        = np.array(pacc)
    pacc_err    = np.array(pacc_err).ravel()
    w           = np.array(w)
    
    # Bundle all data ready for Plot() and store data as .pkl or .json for future use
    all_plot = {'itau':(step_sizes, itau, itau_diff), 
                'pacc':(step_sizes, pacc, pacc_err),
                'acorr':(step_sizes, acs, acns_err),
                'op':(step_sizes, op_av, op_diff)
                }
    
    max_step = step_sizes[-1]
    min_step = step_sizes[0]
    step_sizes_th = np.linspace(min_step, max_step, plot_res)
    if paccTh is not None:
        accs = np.asarray(map(paccTh,step_sizes_th))
        all_plot['pacc_th'] = (step_sizes_th, accs)
        
        if tintTh is not None:
            # itau = np.asarray([tintTh(dtau,acc) for dtau, acc in zip(step_sizes_th, pacc)])
            # itau_hi = np.asarray([tintTh(dtau,acc) for dtau, acc in zip(step_sizes_th, pacc+pacc_err)])
            # itau_lo = np.asarray([tintTh(dtau,acc) for dtau, acc in zip(step_sizes_th, pacc-pacc_err)])
            # all_plot['tint_th'] = (step_sizes_th, itau, itau_hi, itau_lo)
            itau = np.asarray([tintTh(dtau,acc) for dtau, acc in zip(step_sizes_th, accs)])
            all_plot['tint_th'] = (step_sizes_th, itau)
    # do the same for the X^2 operators
    if opTh is not None:
        all_plot['op_th'] = (step_sizes_th, np.asarray(map(opTh,step_sizes_th)))

    store.store(all_plot, file_name, '_allPlot')
    
    plot(save = saveOrDisplay(save, file_name), **all_plot)
Exemple #4
0
# assert that the autocorrelation routine is the same
av_xx = comparison_xx.mean()
norm = ((comparison_xx-av_xx)**2).mean()
my_acorr = np.asarray(map(lambda s: myAcorr(comparison_xx, av_xx, s), np.asarray(separations)))

christian_class = Christian_Autocorrelation(comparison_xx)
christian_acorr = christian_class.acf()[:c_len]

christian_acorr = np.asarray(christian_acorr)
diffs = christian_acorr[:my_acorr.size] - my_acorr
print " > av. difference: {}".format(diffs.mean())

print 'Checking integration window calculation:'
christian_tint, christian_dtint, christian_w = christian_class.tauintW(False)
_,_,my_w = windowing(comparison_xx, av_xx, 1.0, comparison_xx.size, fast=True)

print "Christian Window:{}".format(christian_w)
print "My Window:{}".format(my_w)

ans = uWerr(comparison_xx, acorr=my_acorr)   # get errors
_, _, _, itau, itau_diff, _, acns = ans             # extract data
my_w = getW(itau, itau_diff, n=comparison_xx.size)       # get window length

my_err = acorrnErr(acns, my_w, comparison_xx.size)     # get autocorr errors
christian_acorr = np.asarray(christian_acorr)
christian_err = acorrnErr(christian_acorr, christian_w, comparison_xx.size)

all_plot = preparePlot(christian_acorr[:2*my_w], acns[:2*my_w], my_err[:2*my_w], christian_err[:2*my_w])
store(all_plot, file_name, '_allPlot')
plot(save = saveOrDisplay(save, file_name+"_compareAc"), **all_plot)
Exemple #5
0
# th = Theory(tau=tau, m=m)
# vFn = lambda x: th.eval(t=x, pa=pa, theta=np.pi/2)/th.eval(t=0, pa=pa, theta=np.pi/2.)
#
# l = a['lines'].keys()[0]
# x, f0 = a['lines'][l]
# f1 = vFn(x)
# a['lines'][l] = (x, f1)

# n = 100
# k = a['acns'].keys()[0]
# x,y, e = a['acns'][k]
# del a['acns'][k]
# k  =r'Measured data for $C_{\mathscr{M}^2}$'
# a['acns'][k] = x[:n], y[:n], e[:n]
#
# from scipy.optimize import curve_fit
# fn = lambda x, a, b, c: a*np.cos(b*x)**2+c
# fit,cov = curve_fit(fn, x[:20], y[:20])
#
# l = a['lines'].keys()[0]
# x, f0 = a['lines'][l]
# del a['lines'][l]
# l = r'Theory: $C_{\mathscr{M}^2}(s; \langle\rho\rangle_t = 0.99; \vartheta = \frac{\pi}{2})$'
# a['lines'][l] = (x, f0)
#
# f1 = fn(x, *fit)
# cos = r'${:3.2f}\cos^2{:3.2f}s+{:3.2f}$'.format(*fit)
# a['lines'][cos] = (x, f1)

plot(save=saveOrDisplay(save, file_name), **a)
Exemple #6
0
if __name__ == '__main__':
    d = './correlations/ref_code/'  # grab uWerr data from Matlab script
    with open(d + '/uWerr_out.dat') as f:
        actual = json.load(f)
    actual['itau_aav'] = np.loadtxt(d + 'uWerr_out_tauintFbb.dat')
    actual['acorr'] = np.loadtxt(d + 'uWerr_out_gammaFbb.dat')
    a = np.loadtxt(d + 'actime_tint20_samples.dat')
    # run the uWerr from here
    value, dvalue, ddvalue, tauint, dtauint, y, y2 = uWerr(a)
    res = {
        'value': value,
        'dvalue': dvalue,
        'ddvalue': ddvalue,
        'dtauint': dtauint,
        'tauint': tauint,
        # 'CFbbopt':c_aav,
        'itau_aav': y,
        'acorr': y2
    }

    w = np.around((ddvalue / dvalue)**2 * a.size - .5, 0)
    w2 = np.around((dtauint / tauint / 2.)**2 * a.size - .5 + tauint, 0)
    assert w == w2  # sanity check

    for k in sorted(res.keys()):
        print 'Param:{:8s} my code:{:8.4E}, UF:{:8.4E}, change: {:6.5f}%'.format(
            k, np.average(res[k]), np.average(actual[k]),
            np.average((res[k] - actual[k]) / res[k] * 100.))

    plot(res, actual, save=saveOrDisplay(save, file_name))
Exemple #7
0
    print 'Exp Residues', me.res
    print 'Exp Constant', me.const
    print

    t = np.linspace(0, 10, 1000)
    fE = lambda t: np.real(
        np.asarray(
            [a_i * np.exp(b_i * t)
             for a_i, b_i in zip(me.res, me.poles)]).sum(0))

    mu = np.cos(m * tau)**2
    r, p, k = residuez([mu, 0], [1, -np.cos(m * tau)**2])
    fF = lambda t: np.real(
        np.sum(k) + np.asarray(
            [a_i / b_i * b_i**(t / tau) for a_i, b_i in zip(r, p)]).sum(0))

    lines = {
        0: [(t, fE(t), r'\verb|scipy.signal.residuez()|'),
            (t, me.eval(t), r'Analytical partial fractioning')],
        1: [(t, fF(t), r'\verb|scipy.signal.residuez()|'),
            (t, mf.eval(t), r'Analytical partial fractioning')]
    }

    app = r"$\tau={:4.2f};m={:3.1f}$".format(tau, m)
    subtitles = {
        0: "Exponentially Distributed Trajectories " + app,
        1: "Fixed Trajectories " + app
    }

    plot(lines, subtitles, save=saveOrDisplay(save, file_name))