clear all
close all

N = 10;
T = 5;

s = 2308;
% s = 5346;
rng(s);
   
X = sign(randn(N,T) - 1);

rng('shuffle');

N = 10;
M = 50;
K = N;
T = 5;

U = 0.001*randn(M,N);
V = 0.001*randn(K,M);

epochs = 500;
k1 = 1;
k2 = 1;
r1 = 0.001;
r2 = 0.001;

P = randn(M,K);

for e = 1:epochs
    e_u = 0;
    e_v = 0;
    err = 0;
    for t = 1:T

        x1 = X(:,t);
        if t == T
            x2 = X(:,1);
        else
            x2 = X(:,t+1);             
        end
        
        z = sign(P*x2);
        u = threshold(k1 - z .* (U*x1));
        U = U + r1 * (u.*z) * (x1)';

        y = sign(U*x1);
        v = threshold(k2 - x2 .* (V*y));
        V = V + r2 * (v.*x2)*    y';

        e_u = e_u + sum(u);
        e_v = e_v + sum(v);

        err = err + sum(abs(x2 - sign((V*sign(U*x1)))));
    end   
    disp(sprintf('%d %d %d %d %d', e, sum(e_u), sum(e_v), err))
end

Y = zeros(N,T);
Y(:,1) = X(:,1);
for t = 1:T-1
    Y(:,t+1) = sign(V*sign(U*Y(:,t)));
end

sum(sum(abs(X-Y)))

Y = zeros(N,5*T);
Z = zeros(N,5*T);
Y(:,1) = X(:,1);
Z(:,1) = X(:,1);

rp = randperm(N);
for i = 1:2
    Y(rp(i),1) = -Y(rp(i),1);
end
for t = 1:5*T-1
    Y(:,t+1) = sign(V*sign(U*Y(:,t)));
    Z(:,t+1) = X(:,mod(t,T)+1);
end

% sum(sum(abs(X-Y)))

% figure('Position',[100 100 1200 600]);
s = [N 5*T];
xrange = [1 5*T];
yrange = [1 N];
% 
dx = diff(xrange)/(s(2)-1);
dy = diff(yrange)/(s(1)-1);
xg = linspace(xrange(1)-dx/2,xrange(2)+dx/2,s(2)+1);
yg = linspace(yrange(1)-dy/2,yrange(2)+dy/2,s(1)+1);

figure('Position',[100 100 1000 600]);
colormap(gray)
hi = imagesc(xrange,yrange,Y); hold on
hm = mesh(xg,yg,zeros(s+1));
hm.FaceColor = 'none';
hm.EdgeColor = 'k';
axis off;
axis equal;
