
% keystrokes
load('keystrokes.mat')

N = length(ids);
stejne = []; ruzne =[];
for ii = 1:N
    for jj= ii+1:N
        d = compareKeystrokes(latencies(ii,:),latencies(jj,:));
        if(ids(ii)==ids(jj))
            stejne(end+1) = d;
        else
            ruzne(end+1) = d;
        end
    end
end
%%
[ns,xs] = hist(stejne,100);
[nr,xr] = hist(ruzne,100);

figure
b1 = bar(xs,ns/length(stejne),'b','EdgeColor','b');
hold on
b = bar(xr,nr/sum(nr),'r','EdgeColor','r');

b.FaceAlpha=0.5;
b1.FaceAlpha=0.5;

legend('stejne','ruzne')
xlabel('euclidean distance [ms]')
ylabel('P [-]')
title('keystroke latencies - distributions')
xlim([0 1400])

% ch = get(b1,'child');set(ch,'facealpha',.7);
% ch = get(b,'child');set(ch,'facealpha',.7);

%%
scores = [stejne ruzne];
labels = [zeros(size(stejne)) ones(size(ruzne))];
[X,Y,T,AUC] = perfcurve(labels,scores,1);

%%
figure;
plot(X,Y); axis square;
xlabel('FAR'); ylabel('TAR'); title(sprintf('ROC keystokes [AUC=%.2f]',AUC))
% hold on; line([0 0],[1 1],'Color','r','LineStyle','--')

%%
figure; plot(T,[X,1-Y]); legend('FRR','FAR'); xlabel('threshold'); ylabel('Error')
            
%% compare keystrokes function       
function d = compareKeystrokes(a,b)
    % d = compareKeystrokes(a,b)
    % compute euclidean distance d between two latency vectors a, b

    % d = sqrt(sum((a-b).^2));
    d = norm(a-b,2);
end