# -*- coding: utf-8 -*-
"""
Created on Mon Mar  6 15:59:04 2023

@author: regin
"""
import numpy as np
import matplotlib.pyplot as plt
from uncertainties import unumpy as unp
import statistics
import matplotlib.ticker as ticker
from matplotlib.legend_handler import HandlerTuple




plt.rcParams.update({
  "text.usetex": True,
})

size=20.0
plt.rcParams['figure.figsize'] = (6.4, 4.8) 
plt.rcParams['axes.labelsize'] =size
plt.rcParams['xtick.labelsize'] =size
plt.rcParams['ytick.labelsize'] =size
plt.rcParams['xtick.direction'] = "in"
plt.rcParams['ytick.direction'] = "in"
plt.rcParams['legend.fontsize'] =size
plt.rcParams['legend.title_fontsize'] =size
plt.rcParams['legend.frameon'] = False
plt.rcParams['legend.labelspacing'] = 0.05
plt.rcParams['lines.linewidth'] = 2.0
plt.rcParams['lines.markersize'] = 5.0
plt.rcParams['font.family'] = 'lmodern' 


def data_msd(data_path):
    #data=np.loadtxt(data_path,skiprows=1)
    #i,j,count_block,time_here,msd_here,msd_here_nc,msd_here_nc_cc,msd_here_isf = data[:,0],data[:,1],data[:,2],data[:,3],data[:,4],data[:,5],data[:,6],data[:,]
 
    f1 = open(data_path,'r')
    lines1 = f1.readlines()
    f1.close()

    i, j, count_block, time_here, msd_here, msd_here_nc, msd_here_nc_cc, msd_here_isf, msd_here_isf_nc, msd_here_isf_nc_erst, msd_here_isf_nc_kreuz = ([] for _ in range(11))
    
    for line in range(0,len(lines1[1:])):
            p=lines1[1:][line].split()
            if line%10!=0 or line==0:
                i.append(float(p[0]))
                j.append(float(p[1]))
                count_block.append(float(p[2]))
                time_here.append(float(p[3]))
                msd_here.append(float(p[4]))
                msd_here_nc.append(float(p[5]))
                msd_here_nc_cc.append(float(p[6]))
                msd_here_isf.append(float(p[7]))

  
    #in return i take the abs of the cc term. ATTENTION: it is the upper bound cc term 
    return i,j,count_block,time_here,msd_here,msd_here_nc,msd_here_nc_cc,msd_here_isf


def semsem(data,n):
    r=4
    l=int(n/r)
    # Divide data into r groups of l elements each
    data_split = np.split(data, r) #choose here for example 20=4*5 so 4 sets with 5 elements
    
    # Initialize an array to store the SEMs
    sems = np.empty([r,len(data[0])])
    
    # Loop over the groups and calculate the SEM for each
    for i in range(r):
        group = data_split[i]
        sems[i] = np.std(group, ddof=1,axis=0) / np.sqrt(l)  # we use 5 here because each group has 5 elements

    semsem = np.std(sems, ddof=1,axis=0) / np.sqrt(r) 
    return semsem

def meanstd_msd(num,pfad,pfad2):
    #ddof=1 to get unbias std means with 1/n-1 *sum over sample (NOT the whole smple but just random subset)
    start=0
    av1=3
    av2=6
    y=np.array([data_msd(pfad+str(i)+pfad2) for i in range(start,num)])

    time_here_mean=np.mean( np.array([y[i][3] for i in range(0,num-start)]), axis=0 )

    arr=np.array([y[i][4] for i in range(0,num-start)])
    msd_here_mean=np.mean(arr, axis=0 )
    msd_here_std=np.std(arr, axis=0, ddof=1)/np.sqrt(num)
    msd_here_std_std=semsem(arr,num)
            
    arr_nc= np.array([y[i][5] for i in range(0,num-start)])
    msd_here_nc_mean=np.mean(arr_nc, axis=0 )
    msd_here_nc_std=np.std(arr_nc, axis=0, ddof=1)/np.sqrt(num)
    msd_here_nc_std_std=semsem(arr_nc,num)

    arr_cc=np.array([y[i][6] for i in range(0,num-start)])
    msd_here_nc_cc_mean=np.mean(arr_cc, axis=0 )
    msd_here_nc_cc_std=np.std( arr_cc, axis=0,ddof=1 )/np.sqrt(num)
    msd_here_nc_cc_std_std=semsem(arr_cc,num)
    
    msd_here_nc_std_std=semsem(arr,num)
    msd_here_isf_mean=np.mean( np.array([y[i][7] for i in range(0,num-start)]), axis=0)
    msd_here_isf_std=np.std( np.array([y[i][7] for i in range(0,num-start)]), axis=0, ddof=1 )/np.sqrt(num)


    return time_here_mean,msd_here_mean,msd_here_std,msd_here_std_std,msd_here_nc_mean,msd_here_nc_std,msd_here_nc_std_std,msd_here_nc_cc_mean,msd_here_nc_cc_std,msd_here_nc_cc_std_std,msd_here_isf_mean,msd_here_isf_std #specialfälle



samplenumber4=100
time_01,msd_mean_01,msd_std_01,msd_std_std_01,msd_nc_mean_01,msd_nc_std_01,msd_nc_std_std_01,msd_nc_cc_mean_01,msd_nc_cc_std_01,msd_nc_cc_std_std_01,msd_isf_mean_01,msd_isf_std_01=meanstd_msd(samplenumber4,'../data/data_observables_periodic_steppotential_V0_modified_code/Data_observables_periodic_steppotential_V0_0_1/Data_','/data_observables_periodic_steppotential.dat')
time_1,msd_mean_1,msd_std_1,msd_std_std_1,msd_nc_mean_1,msd_nc_std_1,msd_nc_std_std_1,msd_nc_cc_mean_1,msd_nc_cc_std_1,msd_nc_cc_std_std_1,msd_isf_mean_1,msd_isf_std_1=meanstd_msd(samplenumber4,'../data/data_observables_periodic_steppotential_V0_modified_code/Data_observables_periodic_steppotential_V0_1/Data_','/data_observables_periodic_steppotential.dat')
time_3,msd_mean_3,msd_std_3,msd_std_std_3,msd_nc_mean_3,msd_nc_std_3,msd_nc_std_std_3,msd_nc_cc_mean_3,msd_nc_cc_std_3,msd_nc_cc_std_std_3,msd_isf_mean_3,msd_isf_std_3=meanstd_msd(samplenumber4,'../data/data_observables_periodic_steppotential_V0_modified_code/Data_observables_periodic_steppotential_V0_3/Data_','/data_observables_periodic_steppotential.dat')
time_5,msd_mean_5,msd_std_5,msd_std_std_5,msd_nc_mean_5,msd_nc_std_5,msd_nc_std_std_5,msd_nc_cc_mean_5,msd_nc_cc_std_5,msd_nc_cc_std_std_5,msd_isf_mean_5,msd_isf_std_5=meanstd_msd(samplenumber4,'../data/data_observables_periodic_steppotential_V0_modified_code/Data_observables_periodic_steppotential_V0_5/Data_','/data_observables_periodic_steppotential.dat')
time_10,msd_mean_10,msd_std_10,msd_std_std_10,msd_nc_mean_10,msd_nc_std_10,msd_nc_std_std_10,msd_nc_cc_mean_10,msd_nc_cc_std_10,msd_nc_cc_std_std_10,msd_isf_mean_10,msd_isf_std_10=meanstd_msd(samplenumber4,'../data/data_observables_periodic_steppotential_V0_modified_code/Data_observables_periodic_steppotential_V0_10/Data_','/data_observables_periodic_steppotential.dat')

D=1
#a=1/(2*np.pi)
a=1
tau=a**2/D
d=a




#----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

def periodic_step_potential(x, U, a):
    return np.where(np.mod(x, a) < a / 2, 0, U)





fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(7, 10)) 



left, bottom, width, height = [0.65, 0.59, 0.28, 0.09]
ax3 = fig.add_axes([left, bottom, width, height])

x = np.linspace(-0.51, 0.51, 1000)
ax3.hlines(0, -1, -0.5,linestyle='--', color='black')
ax3.hlines(1, 0.5, 1,linestyle='--', color='black')
ax3.set_xlim(-0.75, 0.75)
ax3.set_ylim(-0.15,1.15)
ax3.spines['bottom'].set_color('white')
ax3.spines['top'].set_color('white')
ax3.spines['left'].set_color('white')
ax3.spines['right'].set_color('white')
ax3.plot(x, periodic_step_potential(x, 1.0, 1.0),  color='black')
#ax3.set_yticks([0,1], [0,r"$\Delta U/k_{\mathrm{B}}T$"])
#ax3.set_xticks([-0.5,0,0.5], [r'$-a/2$',0,r'$a/2$'])
#ax3.set_xlabel(r'$x$')
ax3.set_ylabel(r'$U(x)$')
ax3.set_xticks([], [])
ax3.set_yticks([], [])
ax3.plot(0.25, 0.9, marker='o',markersize=12.0,color='b')
ax3.arrow(0.25, 0.9, 0.10, 0.0,head_width=0.15, head_length=0.08, width=0.01, fc='k', ec='k')
ax3.arrow(0.25, 0.9, -0.10, 0.0,head_width=0.15, head_length=0.08, width=0.01, fc='k', ec='k')


ax1.set_xscale('log')
ax1.set_yscale('log')
ax1.set_xlabel(r'$t/\tau$')
ax1.set_ylabel(r'$\langle \Delta x(t)^2\rangle/ a^2$', labelpad=10)

# Define custom ticks and tick labels for the x-ax1is
ax1.set_xticks([10**i for i in range(-5, 10)])
ax1.tick_params(axis='x', which='major', pad=5, length=4)
ax1.tick_params(axis='x', which='minor', length=2)
ax1.xaxis.set_minor_locator(ticker.LogLocator(subs=[2, 3, 4, 5, 6, 7, 8, 9],numticks=10))

# Define custom ticks and tick labels for the y-axis
ax1.set_yticks([10**i for i in range(-5, 5)])
ax1.tick_params(axis='y', which='minor', length=2)
ax1.yaxis.set_minor_locator(ticker.LogLocator(subs=[2, 3, 4, 5, 6, 7, 8, 9],numticks=10))

# Define custom colors and markers for each data point
plot_options = [{"color": "#93A9EB"},
                {"color": "#6887E3"},
                {"color": "#3D65DB"},
                {"color": "blue"},
                {"color": "#193073"}]

for i, (time, msd_mean, msd_std) in enumerate(zip([time_01, time_1, time_3, time_5, time_10],
                                                  [msd_mean_01, msd_mean_1, msd_mean_3, msd_mean_5, msd_mean_10],
                                                  [msd_std_01, msd_std_1, msd_std_3, msd_std_5, msd_std_10])):
    plot_opts = plot_options[i]
    plot_opts.update({"label": f'${{{[0.1, 1, 3, 5, 10][i]}}}$'})
    ax1.plot(time / tau, msd_mean / d ** 2, **plot_opts)

# Add legend with custom font size and style
x_free = np.logspace(-3, -1)
x_eff = np.logspace(0, 1)
plt.tight_layout()

legend = ax1.legend(title=r"$\Delta U/k_\mathrm{B} T$",handlelength=1.0, handletextpad=0.5, framealpha=1)
plt.setp(legend.get_title(), fontsize=size)
plt.setp(legend.get_texts(), fontsize=size)
plt.tight_layout()

ax1.tick_params(axis='both', which='both', right='on',top='on',pad=6)



ax2.set_xscale('log')
ax2.set_yscale('log')
ax2.set_xlabel(r'$t/\tau$')

# Data to plot
msd_data = [
    (time_1, msd_nc_mean_1, msd_nc_std_1, r"$1.0k_\mathrm{B} T$", 'solid', 'red', 19,19,-0.08), #red
    #(time_01, msd_nc_mean_01, msd_nc_std_01, r"$0.1 k_B T$", '--', 'blue', 13, 17,0), 
    (time_10, msd_nc_mean_10, msd_nc_std_10, r"$10k_\mathrm{B} T$", '-', '#6b0202',2,21,0.0005) #darkred
]

# Plot MSD data
for t, y, yerr, label, linestyle, color, position, rotation,yval in msd_data:
    ax2.errorbar(t/ tau, y/ d**2, yerr=yerr/ d**2, linestyle=linestyle, color=color)
    ax2.text(t[position]/tau, np.abs(y[position])/ d**2 +yval, r"$\Delta U$="+f"{label}", ha='left', va='bottom', rotation=rotation, color=color, fontsize=size)

# Plot complementary MSD data
complementary_data = [
    (time_1, np.abs(msd_nc_cc_mean_1), np.abs(msd_nc_cc_std_1), r"$1.0k_\mathrm{B} T$",'solid', '#0f9200',19,19,0.000009), #pink
    #(time_01, msd_nc_cc_mean_01, msd_nc_cc_std_01,r"$0.1 k_B T$", '--', 'red',13, 22,0.000015),
    (time_10, np.abs(msd_nc_cc_mean_10), msd_nc_cc_std_10, r"$10k_\mathrm{B} T$",'-', '#006203', 2, 21,0.00000045), #darkpink
]

for t, y, yerr, label, linestyle, color, position, rotation, yval in complementary_data:
    ax2.errorbar(t/tau, np.abs(y)/ d**2, yerr=2*yerr/ d**2, linestyle=linestyle, color=color)
    ax2.text(t[position]/tau, np.abs(y[position])/ d**2+yval, r"$\Delta U$="+f"{label}", ha='left', va='bottom', rotation=rotation, color=color, fontsize=size)

# Add custom legend
p1, = ax2.plot([0], [0], color="#0f9200", linestyle='-',linewidth=3.0)
p2, = ax2.plot([0], [0], color='#006203',  linestyle='-',linewidth=3.0)
p3, = ax2.plot([0], [0], linestyle='-', color='red',linewidth=3.0)
p4, = ax2.plot([0], [0], linestyle='-', color='#6b0202', linewidth=3.0)

legend2 = ax2.legend([(p1, p2), (p3, p4)], [r'$|\langle  \Delta x^{\mathrm{red}}(t) \Delta x(t)\rangle |/ a ^2$  ',
                     r'$\langle \Delta x^{\mathrm{red}} (t)^2\rangle / a^2$'], loc='upper left', handlelength=2.2,  handler_map={tuple: HandlerTuple(ndivide=None)})

ax2.add_artist(legend2)
ax1.text(-0.15, 0.95, '(a)', transform=ax1.transAxes, fontsize=20,
         verticalalignment='top')
ax2.text(-0.15, 0.95, '(b)', transform=ax2.transAxes, fontsize=20,
         verticalalignment='top')
ax2.tick_params(axis='both', which='both', right='on', top='on', pad=6)
ax2.set_ylim(8*10**(-12), 7*10**(2))

plt.tight_layout()
#plt.savefig('../plots/Fig_4.pdf') #for 1 und 10

plt.show()



#----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

fig, ax = plt.subplots()

# Set up plot
ax.set_xscale('log')
ax.set_yscale('log')
ax.set_xlabel(r'$t/\tau$')
ax.set_ylabel(r'$\Sigma (t)/a ^2$')

# Set the major and minor ticks on the y-axis
y_major_ticks = ticker.LogLocator(base=10, subs=[1.0], numticks=10)
y_minor_ticks = ticker.LogLocator(base=10, subs=np.arange(2, 10) * 0.1, numticks=10)
ax.yaxis.set_major_locator(y_major_ticks)
ax.yaxis.set_minor_locator(y_minor_ticks)

# Data to plot
msd_data = [

    (time_01, msd_std_01, np.zeros(len(time_10)), r"$1$ NS" , 'solid', "<", '#6BAED6','#6BAED6' ), #ultra lightblue
    (time_01, msd_nc_std_01, np.zeros(len(time_10)), r"$10$ NS", ':',">",'#ff7f7f','#ff7f7f' ), #ultra leightorange
    (time_1, msd_std_1, np.zeros(len(time_10)), r"$1$", 'solid',"o", 'blue','blue'), #leightblue
    (time_1, msd_nc_std_1, np.zeros(len(time_10)), r"$1$ NS" , ':', "s", 'red','red' ), #lightorange
    (time_10, msd_std_10, np.zeros(len(time_10)), r"$10$ ", '-', "^",  '#193073','#193073' ), #darkblue
    (time_10, msd_nc_std_10, np.zeros(len(time_10)), r"$10$ NS", ':',"D",'#6b0202','#6b0202' ), #darkorange

]

# Plot MSD data
for t, y, yerr, label, linestyle,marker, color,ecolor in msd_data:
    ax.errorbar(t/ tau, y/ d**2, yerr=yerr/ d**2, linewidth=1, ecolor=ecolor,linestyle=linestyle, marker=marker,color=color, label=label)
 
p2, = ax.plot([0], [0], 'o', linestyle='-', color="blue") #leightblue
p1, = ax.plot([0], [0], 's', linestyle=':', color='red') #leightorange
p3, = ax.plot([0], [0], 'D', linestyle=':', color='#6b0202') #darkorange
p4, = ax.plot([0], [0], '^', linestyle='-', color='#193073') #darkblue
p5, = ax.plot([0], [0], '>', linestyle=':', color='#ff7f7f') #ultra leight orange
p6, = ax.plot([0], [0], '<', linestyle='-', color='#6BAED6') #ultra lightblue

legend3 =  ax.legend(handles=[(r'red \medspace std'), (p5,p6), ( p1, p2), ( p3, p4)], labels=[r"$\Delta U/k_\mathrm{B} T$" ,r'$0.1$',r'$1.0$', r'$10.0$'],handlelength=3.2,handler_map={tuple: HandlerTuple(ndivide=None)})
ax.add_artist(legend3)

ax.tick_params(axis='both', which='both', right='on',top='on',pad=6)
plt.tight_layout()

#plt.savefig('../plots/Fig_5.pdf')
plt.show()


#------------------

samplenumber3=100
time_01,msd_mean_01,msd_std_01,msd_std_std_01,msd_nc_mean_01,msd_nc_std_01,msd_nc_std_std_01,msd_nc_cc_mean_01,msd_nc_cc_std_01,msd_nc_cc_std_std_01,msd_isf_mean_01,msd_isf_std_01=meanstd_msd(samplenumber3,'../data/data_observables_periodic_steppotential_V0_modified_code_small_times/Data_observables_periodic_steppotential_V0_0_1_small/Data_','/data_observables_periodic_steppotential.dat')
time_1,msd_mean_1,msd_std_1,msd_std_std_1,msd_nc_mean_1,msd_nc_std_1,msd_nc_std_std_1,msd_nc_cc_mean_1,msd_nc_cc_std_1,msd_nc_cc_std_std_1,msd_isf_mean_1,msd_isf_std_1=meanstd_msd(samplenumber3,'../data/data_observables_periodic_steppotential_V0_modified_code_small_times/Data_observables_periodic_steppotential_V0_1_small/Data_','/data_observables_periodic_steppotential.dat')

D=1
a=1
#a=2*np.pi
tau=a**2/D
d=a

dimension=1

def second_derivative(x, y, y_fehler):
    f4_der=[]
    x_f4=[]
    y_vacf = unp.uarray(y,y_fehler)
    for i in range(1,len(x)-1):
        if i%9!=0 and i!=8:
            h1 = x[i]-x[i-1]
            h2 = x[i+1]-x[i]
            f4_der.append((h1*y_vacf[i+1]-(h1+h2)*y_vacf[i]+h2*y_vacf[i-1])/(0.5*(h2*h1**2+h1*h2**2)))
            x_f4.append(x[i])

    x_f4=np.array(x_f4)
    f4_der=np.array(f4_der)


    #plt.errorbar(x_f4, unp.nominal_values(f4_der)/2./dimension, yerr=unp.std_devs(f4_der)/2./dimension,marker='.',linestyle="None")
  
   
    return x_f4[0:27], unp.nominal_values(f4_der[0:27])/2./dimension, unp.std_devs(f4_der[0:27])/2./dimension



# Create subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 6))


# Data to plot
msd_data_1 = [
    (time_1, -msd_mean_1, msd_std_1, "STD", '-', "s", 'blue', 'blue'), #blue
]

msd_data_2 = [
    (time_1, msd_nc_mean_1, msd_nc_std_1, "NC", '-', "o", 'red','red' ), #darkorange
]
beg = 1
abb = len(time_1)


# Plot MSD data in first subplot
for t, y, yerr, label, linestyle, marker, color, ecolor in msd_data_1:
    x, y, y_err = second_derivative(t, y, yerr)
    ax1.errorbar(x[:abb]/tau, y[:abb]/(d/tau)**2, yerr=y_err[:abb]/(d/tau)**2, marker=marker, linewidth=1, ecolor=ecolor, linestyle=linestyle, color=color, label=label)

ax1.set_xlabel(r'$t/\tau$')
ax1.set_ylabel(r'$-Z(t)a^2/D^2$')
ax1.set_xscale('log')
ax1.set_yscale('log')
ax1.set_xlim([9*10**(-5), 2*10**(0)])
ax1.set_ylim([8*10**(-5), 5* 10**(1)])
ax1.plot(time_1[beg:abb]/tau, 0.5*time_1[beg:abb]**(-1/2)*(d)**2, linestyle='--', color='grey')
ax1.text(0.007,3,r'$ t^{-1/2}/2\tau $',rotation=-32 ,fontsize=20, color="grey")
ax1.legend(loc=1)

# Plot MSD data in second subplot
for t, y, yerr, label, linestyle, marker, color, ecolor in msd_data_2:
    x, y, y_err = second_derivative(t, y, yerr)
    ax2.errorbar(x[:abb]/tau, y[:abb]/(d/tau)**2, yerr=y_err[:abb]/(d/tau)**2, marker=marker, linewidth=1, ecolor=ecolor, linestyle=linestyle, color=color, label=label)

ax2.set_xlabel(r'$t/\tau$')
ax2.set_xscale('log')
ax2.set_yscale('log')
ax2.plot(time_1[beg:abb]/tau, 0.5*time_1[beg:abb]**(-1/2)*(d)**2, linestyle='--', color='grey')
ax2.legend(loc='best')
ax2.set_xlim([9*10**(-5), 2*10**(0)])
ax2.set_ylim([8*10**(-5), 5* 10**(1)])

ax2.text(0.007,3,r'$t^{-1/2} /2\tau $',rotation=-32 ,fontsize=20, color="grey")
# Add annotation
ax1.text(0.05, 0.92, '(a)', transform=ax1.transAxes, fontsize=20,
        verticalalignment='top')
ax2.text(0.05, 0.92, '(b)', transform=ax2.transAxes, fontsize=20,
        verticalalignment='top')
# Adjust subplot spacing
plt.tight_layout()
ax1.tick_params(axis='both', which='both', right='on',top='on',pad=6)
ax2.tick_params(axis='both', which='both', right='on',top='on',pad=6)
#plt.savefig('../plots/Fig_6.pdf')
plt.show()


# Create subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 6))


# Data to plot
msd_data_1 = [
    (time_1, -msd_nc_cc_mean_1/0.0005, msd_nc_cc_std_1/0.0005, "Frenkel", '-', "s", 'blue', 'blue'), #blue
]

msd_data_2 = [
    (time_1, msd_nc_mean_1, msd_nc_std_1, "NC", '-', "o", 'red','red' ), #darkorange
]
beg = 1
abb = len(time_1)


# Plot MSD data in first subplot
for t, y, yerr, label, linestyle, marker, color, ecolor in msd_data_1:
    x, y, y_err = second_derivative(t, y, yerr)
    ax1.errorbar(x[:abb]/tau, y[:abb]/(d/tau)**2, yerr=y_err[:abb]/(d/tau)**2, marker=marker, linewidth=1, ecolor=ecolor, linestyle=linestyle, color=color, label=label)

ax1.set_xlabel(r'$t/\tau$')
ax1.set_ylabel(r'$-Z(t)a^2/D^2$')
ax1.set_xscale('log')
ax1.set_yscale('log')
ax1.set_xlim([9*10**(-5), 2*10**(0)])
ax1.set_ylim([8*10**(-5), 5* 10**(1)])
ax1.plot(time_1[beg:abb]/tau, 0.5*time_1[beg:abb]**(-1/2)*(d)**2, linestyle='--', color='grey')
ax1.text(0.007,3,r'$ t^{-1/2}/2\tau $',rotation=-32 ,fontsize=20, color="grey")
ax1.legend(loc=1)

# Plot MSD data in second subplot
for t, y, yerr, label, linestyle, marker, color, ecolor in msd_data_2:
    x, y, y_err = second_derivative(t, y, yerr)
    ax2.errorbar(x[:abb]/tau, y[:abb]/(d/tau)**2, yerr=y_err[:abb]/(d/tau)**2, marker=marker, linewidth=1, ecolor=ecolor, linestyle=linestyle, color=color, label=label)

ax2.set_xlabel(r'$t/\tau$')
ax2.set_xscale('log')
ax2.set_yscale('log')
ax2.plot(time_1[beg:abb]/tau, 0.5*time_1[beg:abb]**(-1/2)*(d)**2, linestyle='--', color='grey')
ax2.legend(loc='best')
ax2.set_xlim([9*10**(-5), 2*10**(0)])
ax2.set_ylim([8*10**(-5), 5* 10**(1)])

ax2.text(0.007,3,r'$t^{-1/2} /2\tau $',rotation=-32 ,fontsize=20, color="grey")
# Add annotation
ax1.text(0.05, 0.92, '(a)', transform=ax1.transAxes, fontsize=20,
        verticalalignment='top')
ax2.text(0.05, 0.92, '(b)', transform=ax2.transAxes, fontsize=20,
        verticalalignment='top')
# Adjust subplot spacing
plt.tight_layout()
ax1.tick_params(axis='both', which='both', right='on',top='on',pad=6)
ax2.tick_params(axis='both', which='both', right='on',top='on',pad=6)
#plt.savefig('../plots/Fig_neu_vacf.pdf')
plt.show()


#----------------------------------------------------------------------

