%Point matching test algorithm 
%Longin Jan Latecki, latecki@temple.edu, November 2012 

%the toy example for matching 7 points to 6 points called labels
%A is matrix of pairwise affinites of pairs (point, label)
%M is mutex matrix on pairs (point, label)

function [matchingaccuracy, time, points, labels]=pointmatching

close all
clear all
labels = [4 8; 4 10; 4 12; 6 10; 8 8; 10 10; 12 12; 14 14];

[size_l,~]=size(labels);
trueCorr=[1:size_l];

% generate points
points = labels;

% % add more points/duplicate points
% points = [points; 6 12];
% trueCorr = [trueCorr 4];

% add outliers
points = [points; 8 18];
trueCorr = [trueCorr 0];

% randomize order
[~, size_r] = size(trueCorr);
random_order = randperm(size_r);
trueCorr = trueCorr(random_order);
points = points(random_order',:);


% add noise
points = points + 0.3*randn(size(points)); %points plus noise


% % rotation (counterclockwise)
% %   shift to origin (0,0)
% mean_point=mean(points);
% points(:,1)=points(:,1)-mean_point(1);
% points(:,2)=points(:,2)-mean_point(2);
% %   rotate about origin (counterclockwise)
% %theta = deg2rad(-75);  % rotation angle
% theta = deg2rad(rand*360);  % rotation angle
% rot = [cos(theta) -sin(theta); sin(theta) cos(theta)];  % rotation matrix
% points = points*rot';
% %   shift back
% points(:,1)=points(:,1)+mean_point(1);
% points(:,2)=points(:,2)+mean_point(2);


% translation/shifting all points
points(:,1) = points(:,1) + randn*10;   % along x
points(:,2) = points(:,2) + randn*10;   % along y



npoints=length(points);
nlabels=length(labels);
%shows the configuration of points in blue and labels in red
figure; plot(points(:,1),points(:,2),'k*','MarkerSize',14);
for i=1:length(points)
    text(points(i,1)+0.05,points(i,2)+0.1,num2str(trueCorr(1,i)));
end
hold on; axis equal;
plot(labels(:,1),labels(:,2),'r^','MarkerSize',14); 
for i=1:length(labels)
    text(labels(i,1)+0.05,labels(i,2)+0.1,num2str(i));
end
title('point configuration');



%calling the matching function
t1 = tic;
[C]=pointmatchfun(points,labels,1); % at most 1 point for a label
time = toc(t1)

%computes the matching accuracy

if length(C)<length(trueCorr)
for i = 1: length(trueCorr) - length(C)
    C=[C 0];
end
end


matchingaccuracy= sum(C==trueCorr)/length(trueCorr)



% reverse the permutation
reverse_permutation = zeros(1,size_r);
for i=1:size_r
    reverse_permutation(1,random_order(1,i))=i;
end
C=C(reverse_permutation);


 %vizualization
CorrProb=zeros(npoints,nlabels);
for i=1:length(C)
    if C(i) <= nlabels && C(i) > 0
        CorrProb(i,C(i))=1;
    end
end
figure; imagesc(CorrProb); title('corr by pointmatchfun');

end



