
# importing required libraries 
from matplotlib import pyplot as plt 
import numpy as np 
import matplotlib.animation as animation 
import os

number_of_arrows = 20
# angle_vector = np.random.uniform(low=-np.pi,high=np.pi,size =number_of_arrows)

# np.savetxt("initial_angle_vector.txt", angle_vector)
angle_vector =np.genfromtxt("initial_angle_vector.txt")


multiplier= 0.40
  
# initializing a figure 
fig = plt.figure(figsize=(10,10)) 
  
# labeling the x-axis and y-axis 
axis = plt.axes() 


  
# lists storing x and y values 
x, y = [], [] 
  
line, = axis.plot(0, 0) 
  
  
def animate(frame_number):
    axis.clear()
    axis.spines[["left", "bottom"]].set_position(("data", 0))
    axis.spines[["left", "bottom"]].set_linewidth(4)
    # Hide the top and right spines.
    axis.spines[["top", "right"]].set_visible(False)
    axis.set_ylim((- multiplier*number_of_arrows,multiplier*number_of_arrows))
    axis.set_xlim((- multiplier*number_of_arrows,multiplier*number_of_arrows))
    axis.plot(1, 0, ">k", transform=axis.get_yaxis_transform(), clip_on=False,markersize=20)
    axis.plot(0, 1, "^k", transform=axis.get_xaxis_transform(), clip_on=False,markersize=20)
    axis.set_yticks([])
    axis.set_xticks([])
    # axis.set_xlabel("Re",loc="right")
    # axis.set_ylabel("Im",loc="top",rotation=0)

    global angle_vector 
    angle_vector +=  np.random.normal(loc=0,scale=0.01,size=number_of_arrows)
    x = 0
    y = 0
    for i in range(number_of_arrows):
        curr_angle = angle_vector[i]
        delta_x =  np.cos(curr_angle)
        delta_y =  np.sin(curr_angle)
        plt.arrow(x,y,delta_x,delta_y,width=0.1,length_includes_head=True,fc='b', ec='k')

        x += delta_x
        y += delta_y

    plt.arrow(0,0,x,y,width=0.2,length_includes_head=True,fc='r', ec='k')
  
anim = animation.FuncAnimation(fig, animate, frames=300,repeat_delay=500,repeat=True) 
# fig.suptitle('Long coherence time', fontsize=32) 
  
# saving to m4 using ffmpeg writer 
# writervideo = animation.FFMpegWriter(fps=60) 
anim.save("long_coherence.gif",fps=30) 
# plt.show()