% Plot graph
% uses SPE to draw an adjacency matrix as a graph in 2 or 3D
% 
% A - the binary adjacecy matrix representing the graph to draw
% figureNum - the number of the figure to draw the graph to
% numDimensions - 2 or 3
%
% Blake Shaw
% Columbia University
% 5/30/08



function plotGraphWithSPE(A, figureNum, numDimensions)


disp(sprintf('Running SPE...'));
[Yspe, Kspe, speEigVals] = spe(A, 0.99, 2, 0);

if numDimensions == 2
    plotEmbedding(Yspe, A, 'SPE embedding', figureNum);
elseif numDimensions == 3
    plotEmbedding3(Yspe, A, 'SPE embedding', figureNum);
else   
    fprintf('Please input a dimension of either 2 or 3');
end




%
% Auxiliary Functions
%


% Calculates affinity matrix (Linear kernel, RBF)
function [A] = calculateAffinityMatrix(X, affType, sigma)
    [D,N] = size(X);
    disp(sprintf('Calculating Distance Matrix'));
    
    A = zeros(N, N);
    
    if affType == 1
        disp(sprintf('Using Linear Kernel'));
        A = X' * X; 
        %A = cov(X);
    elseif affType == 2
        disp(sprintf('Using RBF Kernel'));
        A = zeros(N, N);
        R1 = X' * X;
        Z = diag(R1);
        R2 = ones(N, 1) * Z';
        R3 = Z * ones(N, 1)';
        A  = exp((1/sigma) * R1 - (1/(2*sigma)) * R2 - (1/(2*sigma)) * R3);
    end



% Creates a plot comparing two eigenvalue spectrums
function plotCompareEigSpectrums(oEigs, mveEigs, figureNum);
    figure(figureNum);
    clf;
    subplot(2,1,1);
    bar(oEigs);
    title('Original Eigenvalues');
    subplot(2,1,2);
    bar(mveEigs);
    title('Eigenvalues after MVE');

% Plots a 3d embedding
function plotEmbedding3(Y, neighbors, plotTitle, figureNum)
    figure(figureNum);
    clf;
    
    N = length(neighbors);
    
    scatter3(Y(1,:),Y(2,:), Y(3,:), 60,'filled'); axis equal;
    for i=1:N
        for j=1:N
            if neighbors(i, j) == 1
                line( [Y(1, i), Y(1, j)], [ Y(2, i), Y(2, j) ], [ Y(3, i), Y(3, j)], 'Color', [0, 0, 1], 'LineWidth', 1);
            end
        end
    end
    
    title(plotTitle);
    drawnow; 
    axis off;
    
    
% Plots a 2d embedding
function plotEmbedding(Y, neighbors, plotTitle, figureNum)
    figure(figureNum);
    clf;
    
    N = length(neighbors);
    
    scatter(Y(1,:),Y(2,:), 60,'filled'); axis equal;
    for i=1:N
        for j=1:N
            if neighbors(i, j) == 1
                line( [Y(1, i), Y(1, j)], [ Y(2, i), Y(2, j)], 'Color', [0, 0, 1], 'LineWidth', 1);
            end
        end
    end
    
    title(plotTitle);
    drawnow; 
    axis off;

% Performs kernel principal component analysis
function [Y, eigV] = kpca(A);

    N = length(A);
    
    K = A - repmat(sum(A)/N, N, 1) - repmat((sum(A)/N)', 1, N) + sum(sum(A))/(N^2); K = (K + K')/2;
    [V, D]=eig(K);
    D0 = diag(D);
    V = V * sqrt(D);
    Y=(V(:,end:-1:1))';
    eigV=D0(end:-1:1);
    
    [eigV, IDX] = sort(eigV, 'descend');
    Y = Y(IDX, :);
    

