import numpy as np
import matplotlib.pyplot as plt


def read_data(dir_str):
    '''
    此函数读取txt文件中的数据
    数据内容：科学计数法保存的多行两列数据
    输入：txt文件的路径
    输出：小数格式的数组，行列与txt文件中相同
    '''
    data_temp=[]
    with open(dir_str) as fdata:
        while True:
            line=fdata.readline()
            if not line:
                break
            #data_temp.append([])
            #print(line)
            #print(i for i in line.split(" "))
            data_temp.append([float(i) for i in line.split(' ')])
    return np.array(data_temp)


data_array = read_data('7600_all_way_0.0025.txt')
print(data_array.shape)
print(data_array)

plt.figure()

AnkleL_rotation = []
for j in range(7315):
    AnkleL_rotation.append(data_array[j][29])
AnkleL_rotation = np.array(AnkleL_rotation)
AnkleL_rotation_avg = []
time = np.arange(AnkleL_rotation.shape[0])

for i in range(7200):
    x=0
    for j in range(50):
        x+=AnkleL_rotation[i+j]
    AnkleL_rotation_avg.append(x/50)
plt.plot(time[:6000],AnkleL_rotation_avg[:6000],label='AnkleR_rotation_avg')
# plt.plot(time[:6000],AnkleL_rotation[:6000],label='AnkleL_rotation_avg')
plt.legend(loc='upper left')
plt.xlabel('Time (step) ')
plt.ylabel('AnkleL_rotation_avg (rad)')
plt.legend(loc=2)
#plt.show()
plt.vlines(1280, 0.38,0.7, colors = "r", linestyles = "dashed")
plt.vlines(2740, 0.38,0.7, colors = "r", linestyles = "dashed")
plt.vlines(3920, 0.38,0.7, colors = "r", linestyles = "dashed")
plt.vlines(5080, 0.38,0.7, colors = "r", linestyles = "dashed")
# plt.savefig('AnkleL_rotation_avg-timestep.svg',dpi=600,format='svg')


ave_plain1 = np.average(AnkleL_rotation[0:1280])
ave_up = np.average(AnkleL_rotation[1281:2740])
ave_plain2 = np.average(AnkleL_rotation[2741:3920])
ave_down = np.average(AnkleL_rotation[3921:5080])
ave_plain3 = np.average(AnkleL_rotation[5081:6000])
ave_line = np.zeros(6000)

ave_line[0:1281] = ave_plain1
ave_line[1281:2741] = ave_up
ave_line[2741:3921] = ave_plain2
ave_line[3921:5081] = ave_down
ave_line[5081:6000] = ave_plain3

# plt.plot(time[:6000],ave_line)
plt.plot(time[1281:2741],ave_line[1281:2741],color="greenyellow",linewidth=4)
plt.plot(time[3921:5081],ave_line[3921:5081],color="greenyellow",linewidth=4)
plt.ylim(0.4,0.7)
plt.show()
# plt.savefig('AnkleR_rotation_avg-timestep.svg',dpi=600,format='svg')