function U03_test_kmeans
%U03_TEST_KMEANS           Test kmeans.
%
%usage
%  U03_test_kmeans
%
%author
%  saputra@cs.tu-berlin.de

% filename of script to test
filename = 'kmeans.m';

% generate data set
mu_1 = [-4; 0];
mu_2 = [4; 0];
mu_3 = [0; sqrt(48)];
ns = 50;
X = [(randn(2, ns) + repmat(mu_1, 1, ns)) (randn(2, ns) + repmat(mu_2, 1, ns)) (randn(2, ns) + repmat(mu_3, 1, ns))];
correct_r = [ones(1, ns) 2*ones(1, ns) 3*ones(1, ns)];
correct_same_cluster = (repmat(correct_r, 3*ns, 1) == repmat(correct_r', 1, 3*ns));

% run test
if exist(filename, 'file')
    fprintf(['Testing ' filename  '...\n']);
    [mu, r] = kmeans(X, 3);
    assert_equal(size(correct_r), size(r), 'Size of r does not match. Remember: r has to be a row vector!');
    same_cluster = (repmat(r, 3*ns, 1) == repmat(r', 1, 3*ns));
    num_correct_clusterings = sum(sum(triu(correct_same_cluster == same_cluster, 1)));
    fprintf('Pairwise correct cluster belongings: %.2f %%\n', 100*(num_correct_clusterings/11175));
    fprintf('Please run the test multiple times. You should nearly always get 100 %%\n');
else
    fprintf([filename 'not found.\n']);
end

function [] = assert_equal(A, B, error, success)

if max(max(abs(A - B))) > 1e-3
    fprintf(['Error: ' error '\n']);
    expected = A
    got = B
else
    if nargin > 3
        fprintf(['OK: ' success '\n']);
    end
end
