I want to calculate the correlation time. First I calculate the auto-correlation function:
$$ \begin{align} \chi(t) = &\frac{1}{t_{max}-t}\sum\limits_{t'=0}^{t_{max}-t}m(t')m(t'+t)\\ &-\frac{1}{t_{max}-t}\sum\limits_{t'=0}^{t_{max}-t}m(t')\frac{1}{t_{max}-t}\sum\limits_{t'=0}^{t_{max}-t}m(t'+t)\\ &\sim e^{-t/\tau} \end{align} $$
The correlation-time can be calculated by fitting the autocorrelation function, i.e., \$\chi(t)\$ in exponential. For this I have written the following code:
def autocorrelation(M):
start_time = time.time()
tau = 1
sweeps = len(M)
auto = np.zeros(sweeps)
for t in range(sweeps):
some_time = sweeps-t
first_term = np.average(M[:some_time]*M[t:sweeps])
S1 = np.average(M[:some_time])
S2 = np.average(M[t:sweeps])
auto_temp = first_term - S1*S2
if auto_temp > 0:
auto[t] = auto_temp
else:#remove oscillating part
break
if auto[0] != 0:
auto = auto[auto>0]
auto = auto/auto[0] #normalization
len_auto = len(auto)
if len_auto > 1: #draw a straight line if you have atleast two points
tau = int(-1/np.polyfit(np.arange(len_auto), np.log(auto), 1, w=np.sqrt(auto))[0])
tau = max(tau,1)
logging.info(f"Correlation time = {tau}")
return tau
If you put in list M = m, the function will calculate autocorrelation function and return correlation time, i.e., \$\tau\$. I also thought of using NumPy's correlate and convolve, but I could not understand them well. I tried auto_convolve = numpy.convolve(m,m,mode = "same"), after normalization, the auto/auto[0] was not same as auto_convolve/auto_convolve[0].
Your post appears to contain code that is not properly formatted as code.\$\endgroup\$