clc
clear all
close all
%%%%%%%%%%%%%%%%Parameters Settings
N = 512;
g = 5;
J0 = 1/g;
k = 5;
a = 0.4;
tau = 3;
tau_v = 144;
dt = tau/10;
m = 150 * tau/tau_v;
v = 4.36 / 3 *1e-3;
Alpha=0.19;
T = 8*pi/v;
%%%%%%%%%%%%%%%%%%Matrix Construction
J = zeros(N, 1);
Iext = zeros(N, 1);
U = zeros(N, 1);
V = zeros(N, 1);
r = zeros(N, 1);
% Map all neurons to [-pi, pi)
x=linspace(-pi, pi, N+1);
pos = x(1: N);
for i = 1: N
		dx = min(pos(i)-pos(1), pi-pos(i));
		% choose the weight matrix to be a 2D Gaussian Distribution
		J(i) = J0/(sqrt(2*pi)*a) * exp(-(dx^2)/(2*a^2));
end
Jfft = fft(J);
%%%%%%%%%%%%%%

pos=pos';
loc=-pi*5/8;
centerx_U = zeros(1,length(T/dt));
centerx_I = zeros(1,length(T/dt));
j=1;
t = 0;
r_t = zeros(N,length(T/dt));
U_t = zeros(N,length(T/dt));
I_t = zeros(N,length(T/dt));
while t < T
        loc = loc + v * dt;
    if loc >= pi
        loc = loc - 2 * pi;
    end
    dis = min(abs(pos - loc), 2 * pi - abs(pos - loc));
    Iext = Alpha  * exp(-(dis.^2/(4*a^2)));
    Irec=ifft(Jfft.*fft(r));%;
    dU = dt * (-U - V + Iext+Irec)/tau;
	U = U + dU;
	dV = dt * (-V + m.*U) / tau_v;
	V = V + dV;
	U = max(U, 0);
	r = g.*U.^2./(1+k.*sum(U(:).^2));
    if t>T/4*3
        centerx_I(1,j)=loc;
        maxp = angle(exp(-1i.*pos)'*r);
        if loc > pi - 4*a && maxp < -pi+4*a
            maxp = maxp + 2 * pi;
        end

        if maxp > pi - 4*a && loc < -pi+4*a
            maxp = maxp - 2 * pi;
        end
        centerx_U(1,j)=maxp;
        r_t(:,j)=r(:);
        U_t(:,j) = U(:);
        I_t(:,j) = Iext(:);
        j=j+1;
    end
	t = t + dt;
end
time=1:length(centerx_U)/15;

L=centerx_U-centerx_I;
L_diff = L(time);
equi = centerx_I + mean(L_diff);
plot(time.*dt.*1e-3,centerx_U(time),'b','linewidth',2.5),hold on
plot(time.*dt.*1e-3,centerx_I(time),'r','linewidth',2.5),hold on
plot(time.*dt.*1e-3,equi(time),'k--','linewidth',2.5),hold on
set(gcf,'unit','centimeters','position',[25,17,15,10])
axis([0 max(time)*dt.*1e-3 -2.5 -0.8])
box off
xlabel('time','fontname','Arial')
ylabel('position','fontname','Arial')
set(gca,'linewidth',2.5,'fontsize',20,'fontname','Arial');
