예제 #1
0
def acorr_peaks_old(fs, maxlag, mask=None, lookahead=5, smooth=18,
                return_acorr=False, days=True):
    """Returns positions of acorr peaks, with corresponding local heights.
    """
    fs = np.atleast_1d(fs)
    if mask is None:
        mask = self.mask
    fs[mask] = 0
    
    corr = acor.function(fs,maxlag)
    lag = np.arange(maxlag)

    logging.debug('ac: {}'.format(corr))

    #lag, corr = acorr(fs, mask=mask, maxlag=maxlag)
    maxes, mins = peakdetect(corr, lag, lookahead=lookahead)
    maxes = np.array(maxes)
    mins = np.array(mins)

    logging.debug('maxes: {}'.format(maxes))

    #calculate "local heights".  First will always be a minimum.
    try: #this if maxes and mins are same length 
        lphs = np.concatenate([((maxes[:-1,1] - mins[:-1,1]) + (maxes[:-1,1] - mins[1:,1]))/2.,
                             np.array([maxes[-1,1]-mins[-1,1]])])
    except ValueError: #this if mins have one more
        lphs = ((maxes[:,1] - mins[:-1,1]) + (maxes[:,1] - mins[1:,1]))/2.

    if return_acorr:
        return corr, maxes[:-1,0], lphs[:-1] #leaving off the last one, just in case weirdness...
    else:
        return maxes[:-1,0], lphs[:-1] #leaving off the last one, just in case weirdness...
예제 #2
0
파일: acf.py 프로젝트: dfm/GProtation
def acf(x, y, maxlag=100):
    """Assumes regular sampling, zero-filled
    """
    cadence = np.median(np.diff(x))
    maxlag_cad = int(maxlag/cadence)
    ac = acor.function(y, maxlag_cad)
    lags = np.arange(len(ac))*cadence
    return lags, ac
예제 #3
0
    def autocorrelation_acor(self, paramIndex, walker=None):
        """
        Returns the autocorrelation fucntion for paramIndex.

        walker = None or int. If int, return the autocorrelation function for
        paramIndex for walker.

        Uses acor
        """
        import acor

        if walker:
            acor.function(self.chains[walker, :, paramIndex])
        else:
            mean = 0
            walkers = len(self.chains)
            for i in range(walkers):
                mean += acor.function(self.chains[i, :, paramIndex])
            return mean/float(walkers)
예제 #4
0
def test_IAC():
    """
    Test the un-metropolized XY model sampler and get the ACF and IAC.

    Nsteps is the number of MCMC steps.
    """
    L = 25  # Lattice size
    beta = 0.1  # Inverse temperature
    h = 0.05  # Step size
    n = 5  # Number of velocity verlet steps.
    Nsteps = int(1E4)  # Number of MCMC steps
    metropolize = False  # Do metropolize or not.

    if metropolize:
        [xy, rej_rate, mags] = HybridMC(L, beta, h, n, Nsteps, True, True)
        print("\nMetropolized Scheme")
        print("\nRejection Rate = {:.2f}%".format(100 * rej_rate))

    else:
        print("\nUn-Metropolized Scheme")
        [xy, mags] = HybridMC(L, beta, h, n, Nsteps, False, True)

    acf = acor.function(mags)

    # Time for the correlation to first reach 0 (within the tolerance).
    cor_time = np.where(acf <= 1E-6)[0][0]

    plt.figure(3)
    plt.rc('text', usetex=True)
    plt.rc('font', family='serif')
    plt.xlabel('Lag')
    plt.ylabel('Autocorrelation')
    if metropolize:
        plt.title('ACF of the Metropolized Scheme')
    else:
        plt.title('ACF of the Un-Metropolized Scheme')
    plt.plot(np.arange(cor_time + 1), acf[:cor_time + 1], 'b-')

    tau = acor.acor(mags, maxlag=cor_time)[0]
    print("\nIAC = {:.1f}\n".format(tau))
예제 #5
0
    def acorr(self, maxlag=None, smooth=18, days=True,
              recalc=False):
        if maxlag is None:
            maxlag = self.default_maxlag

        #don't recalculate the same thing if not necessary
        if self._ac is not None and not recalc:
            lag = self._lag
            ac = self._ac
        else:
            x = self.f.copy()
            x[self.mask] = 0

            #logging.debug('{} nans in x'.format((np.isnan(x)).sum()))

            ac = acor.function(x, maxlag)
            lag = np.arange(maxlag)

            #fit and subtract out quadratic
            if self.flatten_order is not None:
                c = np.polyfit(lag, ac, self.flatten_order)
                ac -= np.polyval(c, lag)
                self._ac_poly_coeffs = c

            #smooth AC function
            ac = gaussian_filter(ac, smooth)

            #set private variables for cached calculation
            self._ac = ac
            self._lag = lag
            self._maxlag = maxlag
            self._smooth = smooth

        if days:
            return lag*self.cadence,ac
        else:
            return lag,ac
예제 #6
0
##

N = int(1E7)  # Length of the chain.

mags = IsingSamplers.IsingSampler(N, L, beta, 'Gibbs', method='random')[1]
magSweep = IsingSamplers.IsingSampler(N, L, beta, 'Gibbs', method='sweep')[1]

tau = acor.acor(mags, maxlag=700)[0]
tauSweep = acor.acor(magSweep, maxlag=700)[0]

print("\n")
print("Estimated IAC of Gibbs Sampler (random):   ", tau)
print("Estimated IAC of Gibbs Sampler (sweeping): ", tauSweep)
print("\n")

autocorr = acor.function(mags, maxt=800)
autocorrSweep = acor.function(magSweep, maxt=800)
plt.figure(3)
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.plot(autocorr, c='b', label='Gibbs')
plt.plot(autocorrSweep, c='r', label='Metroplis Hastings')
plt.xlabel('Lag')
plt.ylabel('Correlation')
plt.title('Autocorrelation of Magnetization ($L = 10$, $\\beta=0.05$)')
plt.legend()

##
## Now change the temperature for beta = 1.
##
예제 #7
0
파일: plot.py 프로젝트: andycasey/sick
def autocorrelation(chain, index=0, limit=None, fig=None, figsize=None):
    """
    Plot the autocorrelation function for each parameter of a sampler chain.

    :param chain:
        The sampled parameter values.

    :type chain:
        :class:`numpy.ndarray`

    :param index: [optional]
        Index to calculate the autocorrelation from.

    :type index:
        int

    :param limit: [optional]
        Maximum number of MCMC steps to display. By default half of the chain
        will be shown.

    :type limit:
        int

    :param fig: [optional]
        Figure class to use.

    :type fig:
        :class:`matplotlib.Figure` or None

    :param figsize: [optional]
        The figure size (x-dimension, y-dimension) in inches.

    :type figsize:
        tuple or None
    """

    factor = 2.0
    lbdim = 0.2 * factor
    trdim = 0.2 * factor
    whspace = 0.10
    dimy = lbdim + factor + trdim
    dimx = lbdim + factor + trdim

    if fig is None:
        fig, ax = plt.subplots(figsize=figsize)
    else:
        ax = fig.axes[0]

    lm = lbdim / dimx
    bm = lbdim / dimy
    trm = (lbdim + factor) / dimy
    fig.subplots_adjust(left=lm,
                        bottom=bm,
                        right=trm,
                        top=trm,
                        wspace=whspace,
                        hspace=whspace)

    # Calculate the autocorrelation function for each parameter
    num_parameters = chain.shape[2]
    for i in xrange(num_parameters):
        try:
            rho = acor.function(np.mean(chain[:, index:, i], axis=0))
        except RuntimeError:
            logger.exception("Error in calculating auto-correlation function "\
                "for parameter index {}".format(i))
        else:
            ax.plot(rho, "k", lw=2)

    ax.xaxis.set_major_locator(MaxNLocator(5))
    [l.set_rotation(45) for l in ax.get_xticklabels()]

    ax.set_yticks([-0.5, 0, 0.5, 1.0])
    [l.set_rotation(45) for l in ax.get_yticklabels()]

    ax.axhline(0, color="k")
    ax.set_xlim(0, limit if limit is not None else chain.shape[1] / 2)
    ax.set_ylim(-0.5, 1)
    ax.set_ylabel("$\\rho$")
    ax.set_xlabel("Step")

    return fig
예제 #8
0
def autocorrelation(xs, burn_in, labels=None, fig=None):
    """
    Create a plot showing the autocorrelation in each parameter.

    :param xs:
        The sampled values. This should be a three dimensional array of size
        ``(n_walkers, n_steps, n_parameters)``

    :type xs:
        :class:`numpy.array`

    :param burn_in: [optional]
        The number of steps used for burn-in.

    :type burn_in:
        int

    :param labels: [optional]
        The labels for each parameter.

    :type labels:
        tuple of str

    :param fig: [optional]
        Figure class to use for the plotting.

    :type fig:
        :class:`matplotlib.Figure`

    :returns:
        A figure showing the autocorrelation in each parameter at every MCMC step.

    :rtype:
        :class:`matplotlib.Figure`
    """

    n_walkers, n_steps, K = xs.shape

    factor = 2.0
    lbdim = 0.5 * factor
    trdim = 0.2 * factor
    whspace = 0.10
    width = 15.
    height = factor*K + factor * (K - 1.) * whspace
    dimy = lbdim + height + trdim
    dimx = lbdim + width + trdim

    if fig is None:
        fig, axes = plt.subplots(K, 1, figsize=(dimx, dimy))

    else:
        try:
            axes = np.array(fig.axes).reshape((1, K))
        except:
            raise ValueError("Provided figure has {0} axes, but data has "
                "parameters K={1}".format(len(fig.axes), K))

    lm = lbdim / dimx
    bm = lbdim / dimy
    trm = (lbdim + height) / dimy
    fig.subplots_adjust(left=lm, bottom=bm, right=trm, top=trm,
        wspace=whspace, hspace=whspace)

    for k, ax in enumerate(axes):

        ax.plot(acor.function(np.mean(xs[:, burn_in:, k], axis=0)), color="k")

        if burn_in is not None:
            ax.axvline(burn_in, color="k", linestyle=":")

        ax.set_xlim(0, n_steps)
        if k < K - 1:
            ax.set_xticklabels([])
        else:
            ax.set_xlabel("Step")

        ax.yaxis.set_major_locator(MaxNLocator(4))
        [l.set_rotation(45) for l in ax.get_yticklabels()]
        if labels is not None:
            ax.set_ylabel(labels[k])
            ax.yaxis.set_label_coords(-0.05, 0.5)

    return fig
예제 #9
0
from matplotlib import pyplot as plt

N = int(1E6)  # Length of the chain.
L = 10
beta = 0.05

mags = IsingSamplers.IsingSampler(N, L, beta, 'Gibbs', method='random')[1]
magMH = IsingSamplers.IsingSampler(N, L, beta, 'Metroplis', method='random')[1]

tau = acor.acor(mags, maxlag=700)[0]
tauMH = acor.acor(magMH, maxlag=700)[0]

print("\n")
print("Estimated IAC of Gibbs Sampler    :   ", tau)
print("Estimated IAC of Metroplis Sampler:   ", tauMH)
print("\n")

autocorr = acor.function(mags, maxt=800)
autocorrMH = acor.function(magMH, maxt=800)
plt.figure(1)
plt.rc('text', usetex=True)
plt.rc('font', family='serif')
plt.plot(autocorr, c='b', label='Gibbs')
plt.plot(autocorrMH, c='r', label='Metroplis Hastings')
plt.xlabel('Lag')
plt.ylabel('Correlation')
plt.title('Autocorrelation of Magnetization ($L = 10$, $\\beta=0.05$)')
plt.legend()

plt.show()