%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% function D = evaluate_swaps(P,A,B)
%
% Computes D_ij, the differential in score from swapping nodes 
% i and j before applying the permutation stored in
% the sparse matrix P
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

function [D,dMax] = evaluate_swaps(P,A,B)

% LINEAR TERM
G = compute_gradient(P,A,B);
sumGP2 = sum(G.*P,2);
L = full(G*P'+P*G'-sumGP2-sumGP2');

% QUADRATIC TERM
Bp = P*B*P';
dA = diag(A);
dB = diag(Bp);
Q = min(dA,dB) + min(dA,dB') - min(dA,Bp) - min(dA,Bp') + ...
    min(A,Bp) + min(A,Bp') - min(A,dB) - min(A,dB');
    
% COMBINE TERMS
D = L+Q+Q';
dMax = max(D,[],'all');

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
