close all; clc; clear;

%% =========================================================================
% Petersen case-control analysis
%
% A_i = LNM beta map of impaired patients for cognitive domain i
% B_i = LNM beta map of unimpaired/control patients for domain i
% D_i = case-control beta map
%
% Petersen's case-control contrast is:
%
%       D_i = A_i - B_i
%
% so the control beta can be reconstructed as:
%
%       B_i = A_i - D_i
%
% The analyses below follow the logic of the manuscript:
%   1. Reconstruct the six control maps B1-B6
%   2. Show one example in which a control map is exchanged
%   3. Repeat this for all A_i versus B_j combinations
%   4. Replace all A maps by one common mean(A), while keeping B_i specific
%   5. Do the reverse: keep A_i specific, but replace B by mean(B)
%   6. Optionally compare all A_i against one fixed mixed-lesion control
%% =========================================================================

%% Paths
projectDir = '/Users/martijn/DATA/FC_network_models/Scripts_Example_ToPublish_v12';
dataRoot = '/Users/martijn/DATA/FC_network_models/DATA/PETERSEN_lesion_network_maps';

sensitivityDir = fullfile(dataRoot,'LNM_onesample_parametric');
specificityDir = fullfile(dataRoot,'LNM_group_uncorrected');

addpath(projectDir);
setup_project(projectDir);

domains = {
    'attention_executive'
    'language'
    'processing_speed'
    'verbal_memory'
    'visuospatial_functions'
    'visuospatial_memory'
    };

labels = {
    'Attention/executive'
    'Language'
    'Processing speed'
    'Verbal memory'
    'Visuospatial functions'
    'Visuospatial memory'
    };

nDomains = numel(domains);

%% =========================================================================
% 1. Load the six case maps A_i and Petersen case-control maps D_i
%% =========================================================================

A = cell(nDomains,1);
B = cell(nDomains,1);
D = cell(nDomains,1);

for i = 1:nDomains

    fileA = fullfile(sensitivityDir,domains{i},'beta.nii.gz');
    fileD = fullfile(specificityDir,domains{i},'beta.nii.gz');

    A{i} = single(squeeze(load_nifti_volume(fileA)));
    D{i} = single(squeeze(load_nifti_volume(fileD)));

    % Petersen: D = A - B
    % Therefore reconstruct the control-group beta as:
    B{i} = A{i} - D{i};
end

%% Create one common brain mask and convert maps to vectors
mask = false(size(A{1}));

for i = 1:nDomains
    mask = mask | A{i}~=0 | B{i}~=0 | D{i}~=0;
end

for i = 1:nDomains
    mask = mask & isfinite(A{i}) & isfinite(B{i}) & isfinite(D{i});
end

Avec = zeros(nnz(mask),nDomains);
Bvec = zeros(nnz(mask),nDomains);
Dvec = zeros(nnz(mask),nDomains);

for i = 1:nDomains
    tmp = A{i}; Avec(:,i) = double(tmp(mask));
    tmp = B{i}; Bvec(:,i) = double(tmp(mask));
    tmp = D{i}; Dvec(:,i) = double(tmp(mask));
end

fprintf('\nNumber of analyzed voxels: %d\n',nnz(mask));

%% Check that reconstructed B gives back Petersen's D exactly
fprintf('\nReconstruction: A_i - B_i versus original D_i\n');

for i = 1:nDomains
    reconstructedD = Avec(:,i) - Bvec(:,i);
    r = corr(reconstructedD,Dvec(:,i));
    fprintf('%-25s r = %.5f\n',labels{i},r);
end

%% Optional check against Petersen's supplied beta_controlgroup.nii.gz
% If these files are present, this directly verifies the sign convention.

fprintf('\nReconstructed B versus supplied control-group beta\n');

for i = 1:nDomains

    fileB = fullfile(specificityDir,domains{i},'beta_controlgroup.nii.gz');

    if isfile(fileB)
        suppliedB = single(squeeze(load_nifti_volume(fileB)));
        r = corr(double(B{i}(mask)),double(suppliedB(mask)));
        fprintf('%-25s r = %.5f\n',labels{i},r);
    end
end

%% =========================================================================
% First observation: A maps are highly similar, D maps are less similar
%% =========================================================================

RA = corr(Avec);
RB = corr(Bvec);
RD = corr(Dvec);

idx = triu(true(nDomains),1);

fprintf('\nMean pairwise similarity\n');
fprintf('A maps: r = %.3f\n',mean(RA(idx)));
fprintf('B maps: r = %.3f\n',mean(RB(idx)));
fprintf('D maps: r = %.3f\n',mean(RD(idx)));

%% =========================================================================
% 2. ONE EXAMPLE: keep the LANGUAGE case map fixed, change its control
%
% Original language map:
%
%       D_language = A_language - B_language
%
% Now replace B_language by B_processing_speed:
%
%       D_new = A_language - B_processing_speed
%
% We ask whether this new "language" contrast still resembles the
% original language map, or instead moves toward the map associated
% with the newly introduced processing-speed control group.
%% =========================================================================

iLanguage = find(strcmp(domains,'language'));
iProcessing = find(strcmp(domains,'processing_speed'));

Dexample = Avec(:,iLanguage) - Bvec(:,iProcessing);

rLanguage = corr(Dexample,Dvec(:,iLanguage));
rProcessing = corr(Dexample,Dvec(:,iProcessing));

fprintf('\nExample: A_language - B_processing_speed\n');
fprintf('Correlation with original LANGUAGE D:          r = %.3f\n',rLanguage);
fprintf('Correlation with original PROCESSING SPEED D: r = %.3f\n',rProcessing);

%% =========================================================================
% 3. Repeat the same experiment for ALL A_i versus B_j combinations
%
%       D_cross(i,j) = A_i - B_j
%
% For each new map we compare it with:
%   - D_i : the published map belonging to the case group
%   - D_j : the published map belonging to the substituted control group
%% =========================================================================

rToCase = nan(nDomains,nDomains);
rToControl = nan(nDomains,nDomains);

fprintf('\nAll cross-condition comparisons\n');
fprintf('%-25s %-25s %10s %10s\n','Case A','Control B','r case','r control');

for i = 1:nDomains
    for j = 1:nDomains

        Dcross = Avec(:,i) - Bvec(:,j);

        rToCase(i,j) = corr(Dcross,Dvec(:,i));
        rToControl(i,j) = corr(Dcross,Dvec(:,j));

        if i ~= j
            fprintf('%-25s %-25s %10.3f %10.3f\n', ...
                labels{i},labels{j},rToCase(i,j),rToControl(i,j));
        end
    end
end

% Exclude the diagonal, because A_i-B_i is simply the original D_i.
offdiag = ~eye(nDomains);

fprintf('\nAcross all 30 cross-condition swaps:\n');
fprintf('Mean r with original CASE map:    %.3f\n',mean(rToCase(offdiag)));
fprintf('Mean r with substituted CONTROL map: %.3f\n',mean(rToControl(offdiag)));

fprintf('Control map gives higher correlation in %.1f%% of swaps\n', ...
    100*mean(rToControl(offdiag) > rToCase(offdiag)));

%% =========================================================================
% Also ask which of the six original Petersen D maps each cross-map
% resembles most strongly.
%% =========================================================================

fprintf('\nBest matching Petersen map for each cross-condition contrast\n');

bestMatch = nan(nDomains,nDomains);
bestR = nan(nDomains,nDomains);

for i = 1:nDomains
    for j = 1:nDomains

        Dcross = Avec(:,i) - Bvec(:,j);

        rAll = zeros(nDomains,1);

        for k = 1:nDomains
            rAll(k) = corr(Dcross,Dvec(:,k));
        end

        [bestR(i,j),bestMatch(i,j)] = max(rAll);

        if i ~= j
            fprintf('%-20s - %-20s  ->  %-25s r = %.3f\n', ...
                labels{i},labels{j},labels{bestMatch(i,j)},bestR(i,j));
        end
    end
end

%% =========================================================================
% 4. Remove domain-specific information from the CASE side
%
% Average all six A maps:
%
%       meanA = mean(A1...A6)
%
% Then construct:
%
%       D'_i = meanA - B_i
%
% If these maps still reproduce the original D_i maps, variation between
% the six case-control maps can be generated largely by the B_i maps even
% when the A side is made identical for every cognitive domain.
%% =========================================================================

meanA = mean(Avec,2);

fprintf('\nCommon case map: mean(A) - B_i\n');

rMeanA = nan(nDomains,1);

for i = 1:nDomains

    Dnew = meanA - Bvec(:,i);
    rMeanA(i) = corr(Dnew,Dvec(:,i));

    fprintf('%-25s r = %.3f\n',labels{i},rMeanA(i));
end

fprintf('Mean r = %.3f\n',mean(rMeanA));

%% =========================================================================
% 5. Reverse the analysis
%
% Now average the six control maps:
%
%       meanB = mean(B1...B6)
%
% but retain each original case map:
%
%       D'_i = A_i - meanB
%
% This tests how well the original D_i maps are recovered when the
% domain-specific information is retained only on the A side.
%% =========================================================================

meanB = mean(Bvec,2);

fprintf('\nCommon control map: A_i - mean(B)\n');

rMeanB = nan(nDomains,1);

for i = 1:nDomains

    Dnew = Avec(:,i) - meanB;
    rMeanB(i) = corr(Dnew,Dvec(:,i));

    fprintf('%-25s r = %.3f\n',labels{i},rMeanB(i));
end

fprintf('Mean r = %.3f\n',mean(rMeanB));

fprintf('\nDirect comparison\n');
fprintf('Keep specific B_i, use common A: mean r = %.3f\n',mean(rMeanA));
fprintf('Keep specific A_i, use common B: mean r = %.3f\n',mean(rMeanB));

%% =========================================================================
% Optional robustness check: leave the domain itself out of the average
%
% For domain i:
%
%       mean(A_other five) - B_i
%
% This is useful because the common A map then contains NO contribution
% from A_i itself.
%% =========================================================================

fprintf('\nLeave-one-out common A: mean(A_except_i) - B_i\n');

rMeanA_LOO = nan(nDomains,1);

for i = 1:nDomains

    other = setdiff(1:nDomains,i);
    meanA_LOO = mean(Avec(:,other),2);

    Dnew = meanA_LOO - Bvec(:,i);
    rMeanA_LOO(i) = corr(Dnew,Dvec(:,i));

    fprintf('%-25s r = %.3f\n',labels{i},rMeanA_LOO(i));
end

fprintf('Mean r = %.3f\n',mean(rMeanA_LOO));

%% =========================================================================
% 6. OPTIONAL: one fixed control group for all six cognitive domains
%
% This corresponds to the manuscript analysis in which all six case maps
% are compared against the same large mixed-lesion control map:
%
%       Dfixed_i = A_i - Bfixed
%
% If B is held constant, the high similarity already present among A_i
% should again result in highly similar case-control maps.
%
% Put the beta map of the fixed mixed control LNM below.
%% =========================================================================

fixedControlFile = '';

if ~isempty(fixedControlFile)

    Bfixed = single(squeeze(load_nifti_volume(fixedControlFile)));
    Bfixed = double(Bfixed(mask));

    Dfixed = zeros(size(Avec));

    for i = 1:nDomains
        Dfixed(:,i) = Avec(:,i) - Bfixed;
    end

    Rfixed = corr(Dfixed);

    fprintf('\nFixed control group for all six domains\n');
    fprintf('Mean pairwise r = %.3f\n',mean(Rfixed(idx)));

    disp(Rfixed);
end