From 4822a900c487bdcef39355176f97a094df5e6081 Mon Sep 17 00:00:00 2001 From: Johanna Dorst <jdorst@mpi.localnet> Date: Sat, 8 May 2021 09:36:26 +0200 Subject: [PATCH] Johannas fMRS commit --- algorithms/@LCModel_Caller/FitSpectrum.m | 3 + algorithms/@MR_spectroS/getPpmVector.m | 2 +- algorithms/ImportLCModelBasis.m | 6 +- fMRS_processing/BoldEffectfMRS.m | 378 ++++++++-- .../BoldEffectfMRS_SlidingAverage.m | 506 +++++++++++++ .../BoldEffectfMRS_summedSpectra.m | 654 ++++++++++++++++ fMRS_processing/Corr_BOLD_Met.m | 239 ++++++ .../DoMARSSMetabolitesLineBroadening.m | 12 +- fMRS_processing/Statistics.m | 116 ++- fMRS_processing/createLCModelConfigfMRS.m | 22 +- fMRS_processing/createLCModelConfigfMRSDiff.m | 6 + fMRS_processing/doFitting_fMRS_Met.m | 38 +- fMRS_processing/doFitting_fMRS_Met_Summed.m | 160 ++-- fMRS_processing/doFitting_fMRS_Met_v2.m | 304 ++++++-- .../doFitting_fMRS_SlidingAverage.m | 456 +++++++++--- .../doFitting_fMRS_SlidingAverage_Summed.m | 700 ++++++++++++++++++ fMRS_processing/doFitting_fMRS_TimeCourse.m | 252 ++++++- .../doFitting_fMRS_TimeCourse_Summed.m | 546 ++++++++++++++ .../plot_properties_Reproducibility.m | 85 +++ fMRS_processing/reconstruct_1H_fMRS.m | 346 +++++++-- fMRS_processing/splinefit.m | 526 +++++++++++++ fMRS_processing/subtractBaseline_GradEcho.m | 164 ++++ fMRS_processing/subtractBaseline_fMRS.m | 8 +- fMRS_processing/subtractGradientModulation.m | 205 +++++ .../subtract_MMBaseline_LCModelBaseline.m | 248 +++++++ postprocessing/plot_All_Fit_Metabolites.m | 17 +- postprocessing/startLCModel.m | 2 +- 27 files changed, 5548 insertions(+), 453 deletions(-) create mode 100644 fMRS_processing/BoldEffectfMRS_SlidingAverage.m create mode 100644 fMRS_processing/BoldEffectfMRS_summedSpectra.m create mode 100644 fMRS_processing/Corr_BOLD_Met.m create mode 100644 fMRS_processing/doFitting_fMRS_SlidingAverage_Summed.m create mode 100644 fMRS_processing/doFitting_fMRS_TimeCourse_Summed.m create mode 100644 fMRS_processing/plot_properties_Reproducibility.m create mode 100644 fMRS_processing/splinefit.m create mode 100644 fMRS_processing/subtractBaseline_GradEcho.m create mode 100644 fMRS_processing/subtractGradientModulation.m create mode 100644 fMRS_processing/subtract_MMBaseline_LCModelBaseline.m diff --git a/algorithms/@LCModel_Caller/FitSpectrum.m b/algorithms/@LCModel_Caller/FitSpectrum.m index bda877a..4a56b95 100644 --- a/algorithms/@LCModel_Caller/FitSpectrum.m +++ b/algorithms/@LCModel_Caller/FitSpectrum.m @@ -28,6 +28,9 @@ this.currentOutputFiles = currentOutputFiles; this.currentControlFilePath = [this.homePath this.controlFilesPathRemote this.currentControlFile]; +remoteFilePath = [this.homePath this.outputFilesPathRemote]; +[this.connection, res] = sshfrommatlabissue(this.connection, ['mkdir ' remoteFilePath]); + [this.connection, res] = sshfrommatlabissue(this.connection, [this.homePath this.LCModelPath ' < ' this.currentControlFilePath]); if (copyFileLocally) diff --git a/algorithms/@MR_spectroS/getPpmVector.m b/algorithms/@MR_spectroS/getPpmVector.m index 118f130..46ac40a 100644 --- a/algorithms/@MR_spectroS/getPpmVector.m +++ b/algorithms/@MR_spectroS/getPpmVector.m @@ -10,7 +10,7 @@ bw = linspace(-bw/2,bw/2,size(this.Data{1},this.kx_dim) * zeroFillFactor); if strcmp(this.Parameter.Headers.Nucleus,'31P') ppm = bw/(txFreq*1e-6); else - ppm = bw/(txFreq*1e-6) + 4.7; + ppm = bw/(txFreq*1e-6) + 4.66; end end \ No newline at end of file diff --git a/algorithms/ImportLCModelBasis.m b/algorithms/ImportLCModelBasis.m index 4efb06c..4bd8cfd 100644 --- a/algorithms/ImportLCModelBasis.m +++ b/algorithms/ImportLCModelBasis.m @@ -12,9 +12,9 @@ if ~(strcmp(filepath(end),'\') || strcmp(filepath(end),'/')) filepath = [filepath '/']; end -if ~contains(filename,'.raw', 'IgnoreCase',true) - filename = strcat(filename, '.RAW'); -end +% if ~contains(filename,'.raw', 'IgnoreCase',true) +% filename = strcat(filename, '.RAW'); +% end %open the .RAW data filename = strcat(filepath, filename); % diff --git a/fMRS_processing/BoldEffectfMRS.m b/fMRS_processing/BoldEffectfMRS.m index 9c10336..dba988b 100644 --- a/fMRS_processing/BoldEffectfMRS.m +++ b/fMRS_processing/BoldEffectfMRS.m @@ -10,7 +10,7 @@ BlockNo = cell(1,nBlocks); for k = 1:nBlocks BlockNo{k} = strcat('_Block', num2str(k)); end -woBaseline = false; +woBaseline = false; %false, true subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... '4085';'3333';'4012';'4085';'6524'}; @@ -56,21 +56,26 @@ OutputFilesPathLocal = strcat(localFilePathBase, 'Output/BOLD/'); % OutputFilesPathLocal,nBlocks,PeakRange,metabType,woBaseline) % end % -% %correlation FWHM, Amplitude +%correlation FWHM, Amplitude % metabType = {'NAA', 'Cr'}; +% metabType = {'Water', 'NAA'}; +% metabType = {'Water', 'Cr'}; +% % metabType = {'Water'}; % if exist('excludeSubjects') % CorrBOLDSpearman(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) % else % CorrBOLDSpearman(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) % end -% % CorrBOLDCategorical(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) +% % % CorrBOLDCategorical(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) %correlation Water, Metabolite Concentration -metabType = {'Lac'}; +% metabType = {'Lac'}; if exist('excludeSubjects') - CorrBOLDSpearman_MetConc(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) + CorrBOLDSpearman_MetConc({'Lac'},visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) + CorrBOLDSpearman_MetConc({'Glu'},visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) else - CorrBOLDSpearman_MetConc(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) + CorrBOLDSpearman_MetConc({'Lac'},visualType,BOLDType,OutputFilesPathLocal,woBaseline) + CorrBOLDSpearman_MetConc({'Glu'},visualType,BOLDType,OutputFilesPathLocal,woBaseline) end end @@ -90,12 +95,22 @@ end impFileMat = strcat(OutputFilesPathLocal,impName,'.mat'); BOLDData = load(impFileMat); fields = fieldnames(BOLDData); -BOLDDataXY(1) = BOLDData.(fields{1}); +BOLDDataXY(1) = BOLDData.(fields{1}); %Subj x Block +%convert to vector with correct order: +%subj1_block1,subj1_block2,...,subj1_block10,subj2_block1,... +N = length(BOLDDataXY.amplitude); +BOLDWaterAmp = zeros(N*N,1); BOLDWaterFWHM = zeros(N*N,1); +for i=1:N + for j=1:N + BOLDWaterAmp((i-1)*N + j) = BOLDDataXY.amplitude(i,j); + BOLDWaterFWHM((i-1)*N + j) = BOLDDataXY.fwhm(i,j); + end +end %import Met Conc impNameMetConc = strcat('BlockConc_Stim_woBOLDCorr_MMBSummed',woBaseline) impFileMatMetConc = strcat(OutputFilesPathLocal(1:end-5),impNameMetConc,'.mat'); -BOLDData = load(impNameMetConc); +BOLDData = load(impFileMatMetConc); fields = fieldnames(BOLDData); BOLDData_temp = BOLDData.(fields{1}); if exist('excludeSubjects') @@ -113,11 +128,11 @@ if exist('excludeSubjects') end BOLDData_temp([excludeIdx],:) = []; end -indexMet = strcmp(BOLDData_temp(1,2:end),metabType); +indexMet = strcmp(BOLDData_temp(1,:),metabType); idxMet = find(indexMet); -BOLDData_temp = BOLDData_temp(2:end-4,2:end); -for i = 1:length(BOLDData_temp) - BOLDData_Met{i} = BOLDData_temp{i,idxMet}; +% BOLDData_temp = BOLDData_temp(2:end-4,2:end); +for i = 1:length(BOLDData_temp)-5 + BOLDData_Met{i} = BOLDData_temp{i+1,idxMet}; end if exist('excludeSubjects') @@ -132,45 +147,113 @@ for i = 1:subjLength subjects((1+(i-1)*10):(10+(i-1)*10)) = subjects((1+(i-1)*10):(10+(i-1)*10)).*i; end -%for FWHM -fwhmTab = table(BOLDDataXY(1).fwhm(:),cell2mat(BOLDData_Met'),subjects); +%for FWHM (Water Hz vs Met a.u.) +fwhmTab = table(BOLDWaterFWHM,cell2mat(BOLDData_Met'),subjects); BOLDData_FWHM = table2array(fwhmTab); %Spearman correlation [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Spearman'); % [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); %linear regression -fit = fitlm(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2)); +fit = fitlm(BOLDData_FWHM(:,2),BOLDData_FWHM(:,1)); figure hold on % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') plot(fit) -xlabel(['FWHM Water / Hz']) -ylabel(['Concentration ',metabType, ' / a.u.']) -title(['Correlation FWHM Water & concentration', metabType, woBaseline], 'Interpreter', 'none') +xlabel(['Concentration ' , char(metabType), ' / a.u.']) +ylabel(['FWHM Water / Hz']) +title(['Correlation FWHM Water & concentration ', char(metabType), woBaseline], 'Interpreter', 'none') txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; -text(max(BOLDData_FWHM(:,1)-0.5),max(BOLDData_FWHM(:,2)-1),txt) +text(max(BOLDData_FWHM(:,2)-1),max(BOLDData_FWHM(:,1)-0.5),txt) +set(gca, 'FontWeight','bold'); +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); fig2saveFWHM = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhmConc.fig')); -savefig(fig2saveFWHM) - -%for amplitude -ampTab = table(BOLDDataXY(1).amplitude(:),cell2mat(BOLDData_Met'),subjects); +% savefig(fig2saveFWHM) + +%for FWHM (Delta Water Hz vs Delta Met a.u.) +subjectsDelta = subjects; +subjectsDelta(1:10:end,:) = []; +tempFWHM = []; tempAmp = []; temp_Met = [];MetForDiff = cell2mat(BOLDData_Met'); +for i = 1:length(subjects)/10 +% %for Delta a.u. / Delta Hz + tempFWHM = [tempFWHM; diff(BOLDWaterFWHM(1+(i-1)*10:10+(i-1)*10))]; + tempAmp = [tempAmp ; diff(BOLDWaterAmp(1+(i-1)*10:10+(i-1)*10))]; + temp_Met = [temp_Met ; diff(MetForDiff(1+(i-1)*10:10+(i-1)*10))]; +% %for Delta in % +% tempBaseline_FWHM = BOLDWaterFWHM(2+(i-1)*10); +% tempFWHM = [tempFWHM; BOLDWaterFWHM(1+(i-1)*10:10+(i-1)*10)./tempBaseline_FWHM*100-100]; +% tempBaseline_Amp = BOLDWaterAmp(2+(i-1)*10); +% tempAmp = [tempAmp; BOLDWaterAmp(1+(i-1)*10:10+(i-1)*10)./tempBaseline_Amp*100-100]; +% % % tempBaseline_Met = MetForDiff(2+(i-1)*10); +% % % temp_Met = [temp_Met; MetForDiff(1+(i-1)*10:10+(i-1)*10)./tempBaseline_Met*100-100]; +end +% tempFWHM(1:10:end,:) = []; tempAmp(1:10:end,:) = []; +BOLDDataXYDiff.fwhm = tempFWHM; BOLDDataXYDiff.amplitude = tempAmp; BOLDData_Met_Diff = temp_Met; +fwhmTabDelta = table(BOLDDataXYDiff(1).fwhm(:),BOLDData_Met_Diff,subjectsDelta); +BOLDData_FWHM_Delta = table2array(fwhmTabDelta); +%Spearman correlation +[RHODelta,PVALDelta] = corr(BOLDData_FWHM_Delta(:,2),BOLDData_FWHM_Delta(:,1),'Type','Spearman'); +% [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); +%linear regression +fitDelta = fitlm(BOLDData_FWHM_Delta(:,2),BOLDData_FWHM_Delta(:,1)); +figure +hold on +% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') +plot(fitDelta) +xlabel([char(916), ' Concentration ' , char(metabType), ' / a.u.']) +ylabel([char(916), ' FWHM Water / Hz']) +% ylabel([char(916), ' FWHM Water / %']) +title(['Correlation ', char(916), 'FWHM Water & concentration ', char(metabType), woBaseline], 'Interpreter', 'none') +txt = {['R = ' num2str(RHODelta)],['p < ' num2str(PVALDelta)]}; +text(max(BOLDData_FWHM_Delta(:,2))-0.2,max(BOLDData_FWHM_Delta(:,1)),txt); +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); + +fig2saveFWHMDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_DeltafwhmConc.fig')); +% fig2saveFWHMDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_DeltafwhmConc_Perc.fig')); +savefig(fig2saveFWHMDelta) + +%for amplitude (Water a.u. vs Met a.u.) +ampTab = table(BOLDWaterAmp,cell2mat(BOLDData_Met'),subjects); BOLDData_amp = table2array(ampTab); %Spearman correlation -[RHO,PVAL] = corr(BOLDData_amp(:,1),BOLDData_amp(:,2),'Type','Spearman'); +[RHO,PVAL] = corr(BOLDData_amp(:,2),BOLDData_amp(:,1),'Type','Spearman'); %linear regression -fit = fitlm(BOLDData_amp(:,1),BOLDData_amp(:,2)); +fit = fitlm(BOLDData_amp(:,2),BOLDData_amp(:,1)); figure hold on % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') plot(fit) -xlabel(['Amplitude Water / a.u.']) -ylabel(['Concentration ',metabType, ' / a.u.']) -title(['Correlation Amplitude Water & concentration', metabType, woBaseline], 'Interpreter', 'none') +xlabel(['Concentration ' , char(metabType), ' / a.u.']) +ylabel(['Amplitude Water / a.u.']) +title(['Correlation Amplitude Water & concentration ', char(metabType), woBaseline], 'Interpreter', 'none') txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; -text((min(BOLDData_amp(:,1))+min(BOLDData_amp(:,1))*0.05),(max(BOLDData_amp(:,2))-max(BOLDData_amp(:,2))*0.05),txt) +text((max(BOLDData_amp(:,2))-max(BOLDData_amp(:,2))*0.1),(min(BOLDData_amp(:,1))+min(BOLDData_amp(:,1))*0.05),txt) +set(gca, 'FontWeight','bold'); +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); fig2saveAmplitude = fullfile(OutputFilesPathLocal, strcat(file2save,'_ampConc.fig')); -savefig(fig2saveAmplitude) +% savefig(fig2saveAmplitude) + +%for amplitude (Delta Water a.u. vs Delta Met a.u.) +ampTabDelta = table(BOLDDataXYDiff(1).amplitude(:),BOLDData_Met_Diff,subjectsDelta); +BOLDData_amp_Delta = table2array(ampTabDelta); +%Spearman correlation +[RHODelta,PVALDelta] = corr(BOLDData_amp_Delta(:,2),BOLDData_amp_Delta(:,1),'Type','Spearman'); +%linear regression +fitDelta = fitlm(BOLDData_amp_Delta(:,2),BOLDData_amp_Delta(:,1)); +figure +hold on +% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') +plot(fitDelta) +xlabel([char(916), ' Concentration ' , char(metabType), ' / a.u.']) +ylabel([char(916), ' Amplitude Water / a.u.']) +% ylabel([char(916), ' Amplitude Water / %']) +title(['Correlation ', char(916), 'Amplitude Water & concentration ', char(metabType), woBaseline], 'Interpreter', 'none') +txt = {['R = ' num2str(RHODelta)],['p < ' num2str(PVALDelta)]}; +text((max(BOLDData_amp_Delta(:,2))-max(BOLDData_amp_Delta(:,2))*0.3),(min(BOLDData_amp_Delta(:,1))-min(BOLDData_amp_Delta(:,1))*0.1),txt); +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); +fig2saveAmplitudeDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_DeltaampConc.fig')); +% fig2saveAmplitudeDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_DeltaampConc_Perc.fig')); +savefig(fig2saveAmplitudeDelta) end function CorrBOLDSpearman(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) @@ -197,59 +280,192 @@ for idxmetab = 1:length(metabType) impFileMat = strcat(OutputFilesPathLocal,impName,'.mat'); BOLDData = load(impFileMat); fields = fieldnames(BOLDData); - BOLDDataXY(idxmetab) = BOLDData.(fields{1}); + BOLDDataXY(idxmetab) = BOLDData.(fields{1});%Subj x Block + %convert to vector with correct order: + %subj1_block1,subj1_block2,...,subj1_block10,subj2_block1,... + N = length(BOLDDataXY(idxmetab).amplitude); + BOLDWaterAmp = zeros(N*N,1); BOLDWaterFWHM = zeros(N*N,1); + for i=1:N + for j=1:N + BOLDWaterAmp((i-1)*N + j) = BOLDDataXY(idxmetab).amplitude(i,j); + BOLDWaterFWHM((i-1)*N + j) = BOLDDataXY(idxmetab).fwhm(i,j); + end + end + BOLDDataXY(idxmetab).amplitude = BOLDWaterAmp; + BOLDDataXY(idxmetab).fwhm = BOLDWaterFWHM; end if exist('excludeSubjects') - file2save = strcat('Corr_',metabType{1},'_',metabType{2},'_',visualType,BOLDType,woBaseline,'_Excluded'); + if length(metabType) == 2 + file2save = strcat('Corr_',metabType{1},'_',metabType{2},'_',visualType,BOLDType,woBaseline,'_Excluded'); + elseif length(metabType) == 1 + file2save = strcat('Corr_',metabType{1},'_FWHMAmp_',visualType,BOLDType,woBaseline,'_Excluded'); + end else - file2save = strcat('Corr_',metabType{1},'_',metabType{2},'_',visualType,BOLDType,woBaseline); + if length(metabType) == 2 + file2save = strcat('Corr_',metabType{1},'_',metabType{2},'_',visualType,BOLDType,woBaseline); + elseif length(metabType) == 1 + file2save = strcat('Corr_',metabType{1},'_FWHMAmp_',visualType,BOLDType,woBaseline); + end end -subjLength = length(BOLDDataXY(1).fwhm); +subjLength = length(BOLDDataXY(1).fwhm)/10; subjects = ones(subjLength*10,1); for i = 1:subjLength subjects((1+(i-1)*10):(10+(i-1)*10)) = subjects((1+(i-1)*10):(10+(i-1)*10)).*i; end -%for FWHM -fwhmTab = table(BOLDDataXY(1).fwhm(:),BOLDDataXY(2).fwhm(:),subjects); -BOLDData_FWHM = table2array(fwhmTab); -%Spearman correlation -[RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Spearman'); -% [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); -%linear regression -fit = fitlm(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2)); -figure -hold on -% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') -plot(fit) -xlabel(['FWHM ',num2str(metabType{1}), ' / Hz']) -ylabel(['FWHM ',num2str(metabType{2}), ' / Hz']) -title(['Correlation FWHM ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') -txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; -text(min(BOLDData_FWHM(:,1)+1),max(BOLDData_FWHM(:,2)-1),txt) - -fig2saveFWHM = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhm.fig')); -savefig(fig2saveFWHM) - -%for amplitude -ampTab = table(BOLDDataXY(1).amplitude(:),BOLDDataXY(2).amplitude(:),subjects); -BOLDData_amp = table2array(ampTab); -%Spearman correlation -[RHO,PVAL] = corr(BOLDData_amp(:,1),BOLDData_amp(:,2),'Type','Spearman'); -%linear regression -fit = fitlm(BOLDData_amp(:,1),BOLDData_amp(:,2)); -figure -hold on -% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') -plot(fit) -xlabel(['Amplitude ',num2str(metabType{1}), ' / a.u.']) -ylabel(['Amplitude ',num2str(metabType{2}), ' / a.u.']) -title(['Correlation Amplitude ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') -txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; -text((min(BOLDData_amp(:,1))+min(BOLDData_amp(:,1))*0.05),(max(BOLDData_amp(:,2))-max(BOLDData_amp(:,2))*0.05),txt) -fig2saveAmplitude = fullfile(OutputFilesPathLocal, strcat(file2save,'_amp.fig')); -savefig(fig2saveAmplitude) +if length(metabType) == 2 + %for FWHM (Hz) + fwhmTab = table(BOLDDataXY(1).fwhm(:),BOLDDataXY(2).fwhm(:),subjects); + BOLDData_FWHM = table2array(fwhmTab); + %Spearman correlation + [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Spearman'); + % [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); + %linear regression + fit = fitlm(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fit) + xlabel(['FWHM ',num2str(metabType{1}), ' / Hz']) + ylabel(['FWHM ',num2str(metabType{2}), ' / Hz']) + title(['Correlation FWHM ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; + text(min(BOLDData_FWHM(:,1)+1),max(BOLDData_FWHM(:,2)-1),txt) + set(gca, 'FontWeight','bold'); + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); + + fig2saveFWHM = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhm.fig')); + savefig(fig2saveFWHM) + + %for FWHM (Delta Hz) + subjectsDelta = subjects; + subjectsDelta(1:10:end,:) = []; + for idxmetab = 1:length(metabType) + tempFWHM = []; tempAmp = []; + for i = 1:length(subjects)/10 + tempFWHM = [tempFWHM; diff(BOLDDataXY(idxmetab).fwhm(1+(i-1)*10:10+(i-1)*10))]; + tempAmp = [tempAmp ; diff(BOLDDataXY(idxmetab).amplitude(1+(i-1)*10:10+(i-1)*10))]; + end + BOLDDataXYDiff(idxmetab).fwhm = tempFWHM; BOLDDataXYDiff(idxmetab).amplitude = tempAmp; + end + fwhmTabDelta = table(BOLDDataXYDiff(1).fwhm(:),BOLDDataXYDiff(2).fwhm(:),subjectsDelta); + BOLDData_FWHM_Delta = table2array(fwhmTabDelta); + %Spearman correlation + [RHODelta,PVALDelta] = corr(BOLDData_FWHM_Delta(:,1),BOLDData_FWHM_Delta(:,2),'Type','Spearman'); + % [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); + %linear regression + fitDelta = fitlm(BOLDData_FWHM_Delta(:,1),BOLDData_FWHM_Delta(:,2)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fitDelta) + xlabel([char(916) 'FWHM ',num2str(metabType{1}), ' / Hz']) + ylabel([char(916) 'FWHM ',num2str(metabType{2}), ' / Hz']) + title(['Correlation ' char(916) 'FWHM ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHODelta)],['p < ' num2str(PVALDelta)]}; + text(min(BOLDData_FWHM_Delta(:,1))+min(BOLDData_FWHM_Delta(:,1)*0.01),max(BOLDData_FWHM_Delta(:,2))-max(BOLDData_FWHM_Delta(:,2))*0.01,txt) + set(gca, 'FontWeight','bold'); + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); + + fig2saveFWHMDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_Deltafwhm.fig')); + savefig(fig2saveFWHMDelta) + + %for amplitude (a.u.) + ampTab = table(BOLDDataXY(1).amplitude(:),BOLDDataXY(2).amplitude(:),subjects); + BOLDData_amp = table2array(ampTab); + %Spearman correlation + [RHO,PVAL] = corr(BOLDData_amp(:,1),BOLDData_amp(:,2),'Type','Spearman'); + %linear regression + fit = fitlm(BOLDData_amp(:,1),BOLDData_amp(:,2)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fit) + xlabel(['Amplitude ',num2str(metabType{1}), ' / a.u.']) + ylabel(['Amplitude ',num2str(metabType{2}), ' / a.u.']) + title(['Correlation Amplitude ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; + text((min(BOLDData_amp(:,1))+min(BOLDData_amp(:,1))*0.05),(max(BOLDData_amp(:,2))-max(BOLDData_amp(:,2))*0.05),txt) + set(gca, 'FontWeight','bold'); + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); + fig2saveAmplitude = fullfile(OutputFilesPathLocal, strcat(file2save,'_amp.fig')); + savefig(fig2saveAmplitude) + + %for amplitude (Delta a.u.) + ampTabDelta = table(BOLDDataXYDiff(1).amplitude(:),BOLDDataXYDiff(2).amplitude(:),subjectsDelta); + BOLDData_amp_Delta = table2array(ampTabDelta); + %Spearman correlation + [RHODelta,PVALDelta] = corr(BOLDData_amp_Delta(:,1),BOLDData_amp_Delta(:,2),'Type','Spearman'); + %linear regression + fitDelta = fitlm(BOLDData_amp_Delta(:,1),BOLDData_amp_Delta(:,2)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fitDelta) + xlabel([char(916) 'Amplitude ',num2str(metabType{1}), ' / a.u.']) + ylabel([char(916) 'Amplitude ',num2str(metabType{2}), ' / a.u.']) + title(['Correlation ' char(916) 'Amplitude ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHODelta)],['p < ' num2str(PVALDelta)]}; + text((max(BOLDData_amp_Delta(:,1))-max(BOLDData_amp_Delta(:,1))*0.25),(min(BOLDData_amp_Delta(:,2))-min(BOLDData_amp_Delta(:,2))*0.25),txt) + set(gca, 'FontWeight','bold'); + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); + fig2saveAmplitudeDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_Deltaamp.fig')); + savefig(fig2saveAmplitudeDelta) + +elseif length(metabType) == 1 + %for FWHM (Hz) / Amp (a.u.) + fwhmAmpTab = table(BOLDDataXY(1).fwhm(:),BOLDDataXY(1).amplitude(:),subjects); + BOLDData = table2array(fwhmAmpTab); + %Spearman correlation + [RHO,PVAL] = corr(BOLDData(:,1),BOLDData(:,2),'Type','Spearman'); + % [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); + %linear regression + fit = fitlm(BOLDData(:,1),BOLDData(:,2)); + figure + hold on + plot(fit) + xlabel(['FWHM ',num2str(metabType{1}), ' / Hz']) + ylabel(['Amplitude ',num2str(metabType{1}), ' / a.u.']) + title(['Correlation FWHM & Amplitude ', num2str(metabType{1}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; + text(min(BOLDData(:,1))+min(BOLDData(:,1))*0.001,min(BOLDData(:,2))+min(BOLDData(:,2))*0.001,txt) + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); + + fig2save = fullfile(OutputFilesPathLocal, strcat(file2save,'.fig')); + savefig(fig2save) + + %for FWHM (Delta Hz) / Amp (Delta a.u.) + subjectsDelta = subjects; + subjectsDelta(1:10:end,:) = []; + for idxmetab = 1:length(metabType) + tempFWHM = []; tempAmp = []; + for i = 1:length(subjects)/10 + tempFWHM = [tempFWHM; diff(BOLDDataXY(idxmetab).fwhm(1+(i-1)*10:10+(i-1)*10))]; + tempAmp = [tempAmp ; diff(BOLDDataXY(idxmetab).amplitude(1+(i-1)*10:10+(i-1)*10))]; + end + BOLDDataXYDiff(idxmetab).fwhm = tempFWHM; BOLDDataXYDiff(idxmetab).amplitude = tempAmp; + end + fwhmAmpTabDelta = table(BOLDDataXYDiff(1).fwhm(:),BOLDDataXYDiff(1).amplitude(:),subjectsDelta); + BOLDData_Delta = table2array(fwhmAmpTabDelta); + %Spearman correlation + [RHODelta,PVALDelta] = corr(BOLDData_Delta(:,1),BOLDData_Delta(:,2),'Type','Spearman'); + %linear regression + fitDelta = fitlm(BOLDData_Delta(:,1),BOLDData_Delta(:,2)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fitDelta) + xlabel([char(916) 'FWHM ',num2str(metabType{1}), ' / Hz']) + ylabel([char(916) 'Amplitude ',num2str(metabType{1}), ' / Hz']) + title(['Correlation ' char(916) 'FWHM & Amplitude ', num2str(metabType{1}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHODelta)],['p < ' num2str(PVALDelta)]}; + text(min(BOLDData_Delta(:,1)),min(BOLDData_Delta(:,2)),txt) + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); + + fig2saveDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_Delta.fig')); + savefig(fig2saveDelta) +end end @@ -320,7 +536,7 @@ end BOLD.fwhm = fwhmArray; BOLD.amplitude = amplitudeArray; eval([file2save '= BOLD']); exportFileMat = [OutputFilesPathLocal, strcat(file2save,'.mat')]; -save(exportFileMat,file2save) +% save(exportFileMat,file2save) x = linspace(320/60/4,(320*5/60-320/60/4),10); figure @@ -346,9 +562,10 @@ end patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) ylim([yLimits(1) yLimits(2)]); -xlim([0 320*5/60]); +xlim([0 320*5/60]); set(gca, 'FontWeight','bold'); +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); fig2save = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhm.fig')); -savefig(fig2save) +% savefig(fig2save) figure hold on @@ -379,9 +596,10 @@ end patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) ylim([yLimits(1) yLimits(2)]); -xlim([0 320*5/60]); +xlim([0 320*5/60]); set(gca, 'FontWeight','bold'); +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); fig2save = fullfile(OutputFilesPathLocal, strcat(file2save,'_amplitude.fig')); -savefig(fig2save) +% savefig(fig2save) close all %plot mean, std of BOLD @@ -440,10 +658,10 @@ end patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) ylim([yLimits(1) yLimits(2)]); -xlim([0 320*5/60]); +xlim([0 320*5/60]); set(gca, 'FontWeight','bold'); set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 12, 18]); fig2save = fullfile(OutputFilesPathLocal, strcat(file2save,'_Mean.fig')); -savefig(fig2save) +% savefig(fig2save) end function CorrBOLDCategorical(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) diff --git a/fMRS_processing/BoldEffectfMRS_SlidingAverage.m b/fMRS_processing/BoldEffectfMRS_SlidingAverage.m new file mode 100644 index 0000000..2f17605 --- /dev/null +++ b/fMRS_processing/BoldEffectfMRS_SlidingAverage.m @@ -0,0 +1,506 @@ +function BoldEffectfMRS_SlidingAverage() +clear; clc; close all; + +pathName = 'fMRS SlidingAverage data path'; +[localFilePathBase] = pathToDataFolder(pathName); +visualType = 'Stim'; %'Stim', 'Rest' +BOLDType = '_woBOLDCorr'; +nBlocks = 10; +nAv = 37; +AvNo = cell(1,nAv); +for k = 1:nAv + AvNo{k} = strcat('_Av', num2str(k)); +end +woBaseline = false; + +subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... + '4085';'3333';'4012';'4085';'6524'}; +% prefixes = {'2020-02-18_';}; +prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... + '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... + '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; +suffixFolder = '_fMRS'; +excludeSubjects = {'5166';'9810';'5269'}; + +subjectsPath = strcat(prefixes, subjects, suffixFolder); +preprocessedFilesPathLocal = strcat(localFilePathBase, subjectsPath, '/'); +OutputFilesPathLocal = strcat(localFilePathBase, 'Output/BOLD/'); + +% % %for Water +% PeakRange = [4 5]; %ppm where to find the peak +% metabType = 'Water'; +% if exist('excludeSubjects') +% CalcBOLDEffect(subjects,AvNo,visualType,BOLDType,preprocessedFilesPathLocal,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType,'',excludeSubjects) +% else +% CalcBOLDEffect(subjects,AvNo,visualType,BOLDType,preprocessedFilesPathLocal,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType) +% end +% %for NAA (2.008 ppm) +% PeakRange = [1.8 2.3]; %ppm where to find the peak +% metabType = 'NAA'; +% if exist('excludeSubjects') +% CalcBOLDEffect(subjects,AvNo,visualType,BOLDType,preprocessedFilesPathLocal,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType,woBaseline,excludeSubjects) +% else +% CalcBOLDEffect(subjects,AvNo,visualType,BOLDType,preprocessedFilesPathLocal,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType,woBaseline) +% end +% %for Cr (methyl signal of tCr: 3.027ppm) +% PeakRange = [2.9 3.15]; %ppm where to find the peak +% metabType = 'Cr'; +% if exist('excludeSubjects') +% CalcBOLDEffect(subjects,AvNo,visualType,BOLDType,preprocessedFilesPathLocal,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType,woBaseline,excludeSubjects) +% else +% CalcBOLDEffect(subjects,AvNo,visualType,BOLDType,preprocessedFilesPathLocal,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType,woBaseline) +% end +% +% %correlation FWHM, Amplitude +% metabType = {'NAA', 'Cr'}; +% if exist('excludeSubjects') +% CorrBOLDSpearman(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) +% else +% CorrBOLDSpearman(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) +% end +% % CorrBOLDCategorical(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) + +%correlation Water, Metabolite Concentration +%%%%% didn't check this for metabolites from sliding average %%%%% +metabType = {'Lac'}; +if exist('excludeSubjects') + CorrBOLDSpearman_MetConc(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) +else + CorrBOLDSpearman_MetConc(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) +end + +end + +function CorrBOLDSpearman_MetConc(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end + +if exist('excludeSubjects') + impName = strcat('BOLD_Water_',visualType,BOLDType,'_SlidingAverage_Excluded'); +else + impName = strcat('BOLD_Water_',visualType,BOLDType,'_SlidingAverage'); +end +impFileMat = strcat(OutputFilesPathLocal,impName,'.mat'); +BOLDData = load(impFileMat); +fields = fieldnames(BOLDData); +BOLDDataXY(1) = BOLDData.(fields{1}); + +%import Met Conc +impNameMetConc = strcat('BlockConc_Stim_woBOLDCorr_MMBSummed',woBaseline) +impFileMatMetConc = strcat(OutputFilesPathLocal(1:end-5),impNameMetConc,'.mat'); +BOLDData = load(impNameMetConc); +fields = fieldnames(BOLDData); +BOLDData_temp = BOLDData.(fields{1}); +if exist('excludeSubjects') + n = length(BOLDData_temp); + m = length(excludeSubjects); + nstep = 1; + for j = 1:m + for i = 1:n + xx = find(~cellfun(@isempty,strfind(BOLDData_temp(i,1),excludeSubjects{j}))); + if ~isempty(xx) + excludeIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + BOLDData_temp([excludeIdx],:) = []; +end +indexMet = strcmp(BOLDData_temp(1,2:end),metabType); +idxMet = find(indexMet); +BOLDData_temp = BOLDData_temp(2:end-4,2:end); +for i = 1:length(BOLDData_temp) + BOLDData_Met{i} = BOLDData_temp{i,idxMet}; +end + +if exist('excludeSubjects') + file2save = strcat('Corr_Water_',metabType{1},'_Conc_',visualType,BOLDType,woBaseline,'_Excluded'); +else + file2save = strcat('Corr_Water_',metabType{1},'_Conc_',visualType,BOLDType,woBaseline); +end + +subjLength = length(BOLDDataXY(1).fwhm); +subjects = ones(subjLength*10,1); +for i = 1:subjLength + subjects((1+(i-1)*10):(10+(i-1)*10)) = subjects((1+(i-1)*10):(10+(i-1)*10)).*i; +end + +%for FWHM +fwhmTab = table(BOLDDataXY(1).fwhm(:),cell2mat(BOLDData_Met'),subjects); +BOLDData_FWHM = table2array(fwhmTab); +%Spearman correlation +[RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Spearman'); +% [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); +%linear regression +fit = fitlm(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2)); +figure +hold on +% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') +plot(fit) +xlabel(['FWHM Water / Hz']) +ylabel(['Concentration ',metabType, ' / a.u.']) +title(['Correlation FWHM Water & concentration', metabType, woBaseline], 'Interpreter', 'none') +txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; +text(max(BOLDData_FWHM(:,1)-0.5),max(BOLDData_FWHM(:,2)-1),txt) + +fig2saveFWHM = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhmConc.fig')); +savefig(fig2saveFWHM) + +%for amplitude +ampTab = table(BOLDDataXY(1).amplitude(:),cell2mat(BOLDData_Met'),subjects); +BOLDData_amp = table2array(ampTab); +%Spearman correlation +[RHO,PVAL] = corr(BOLDData_amp(:,1),BOLDData_amp(:,2),'Type','Spearman'); +%linear regression +fit = fitlm(BOLDData_amp(:,1),BOLDData_amp(:,2)); +figure +hold on +% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') +plot(fit) +xlabel(['Amplitude Water / a.u.']) +ylabel(['Concentration ',metabType, ' / a.u.']) +title(['Correlation Amplitude Water & concentration', metabType, woBaseline], 'Interpreter', 'none') +txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; +text((min(BOLDData_amp(:,1))+min(BOLDData_amp(:,1))*0.05),(max(BOLDData_amp(:,2))-max(BOLDData_amp(:,2))*0.05),txt) +fig2saveAmplitude = fullfile(OutputFilesPathLocal, strcat(file2save,'_ampConc.fig')); +savefig(fig2saveAmplitude) +end + +function CorrBOLDSpearman(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end + +for idxmetab = 1:length(metabType) + if strcmp(metabType{idxmetab}(1:2),'Wa') + if exist('excludeSubjects') + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType,'_Excluded'); + else + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType); + end + else + if exist('excludeSubjects') + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType,woBaseline,'_Excluded'); + else + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType,woBaseline); + end + end + impFileMat = strcat(OutputFilesPathLocal,impName,'.mat'); + BOLDData = load(impFileMat); + fields = fieldnames(BOLDData); + BOLDDataXY(idxmetab) = BOLDData.(fields{1}); +end +if exist('excludeSubjects') + file2save = strcat('Corr_',metabType{1},'_',metabType{2},'_',visualType,BOLDType,woBaseline,'_Excluded'); +else + file2save = strcat('Corr_',metabType{1},'_',metabType{2},'_',visualType,BOLDType,woBaseline); +end + +subjLength = length(BOLDDataXY(1).fwhm); +subjects = ones(subjLength*10,1); +for i = 1:subjLength + subjects((1+(i-1)*10):(10+(i-1)*10)) = subjects((1+(i-1)*10):(10+(i-1)*10)).*i; +end + +%for FWHM +fwhmTab = table(BOLDDataXY(1).fwhm(:),BOLDDataXY(2).fwhm(:),subjects); +BOLDData_FWHM = table2array(fwhmTab); +%Spearman correlation +[RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Spearman'); +% [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); +%linear regression +fit = fitlm(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2)); +figure +hold on +% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') +plot(fit) +xlabel(['FWHM ',num2str(metabType{1}), ' / Hz']) +ylabel(['FWHM ',num2str(metabType{2}), ' / Hz']) +title(['Correlation FWHM ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') +txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; +text(min(BOLDData_FWHM(:,1)+1),max(BOLDData_FWHM(:,2)-1),txt) + +fig2saveFWHM = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhm.fig')); +savefig(fig2saveFWHM) + +%for amplitude +ampTab = table(BOLDDataXY(1).amplitude(:),BOLDDataXY(2).amplitude(:),subjects); +BOLDData_amp = table2array(ampTab); +%Spearman correlation +[RHO,PVAL] = corr(BOLDData_amp(:,1),BOLDData_amp(:,2),'Type','Spearman'); +%linear regression +fit = fitlm(BOLDData_amp(:,1),BOLDData_amp(:,2)); +figure +hold on +% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') +plot(fit) +xlabel(['Amplitude ',num2str(metabType{1}), ' / a.u.']) +ylabel(['Amplitude ',num2str(metabType{2}), ' / a.u.']) +title(['Correlation Amplitude ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') +txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; +text((min(BOLDData_amp(:,1))+min(BOLDData_amp(:,1))*0.05),(max(BOLDData_amp(:,2))-max(BOLDData_amp(:,2))*0.05),txt) +fig2saveAmplitude = fullfile(OutputFilesPathLocal, strcat(file2save,'_amp.fig')); +savefig(fig2saveAmplitude) +end + + + + +function CalcBOLDEffect(subjects,AvNo,visualType,BOLDType,preprocessedFilesPathLocal,... + OutputFilesPathLocal,nBlocks,PeakRange,metabType,woBaseline,excludeSubjects) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +SelProcValues = SelectedProcessingValues(); +fwhmArray = zeros(length(subjects),length(AvNo)); +amplitudeArray = zeros(length(subjects),length(AvNo)); +for idxSubject = 1:length(subjects) + for nBl = 1:length(AvNo) + impName = strcat(subjects{idxSubject},'_',visualType,BOLDType,AvNo{nBl},woBaseline); + impFileMat = strcat(preprocessedFilesPathLocal{idxSubject},impName,'.mat'); + dataPerBlock = load(impFileMat); + fields = fieldnames(dataPerBlock); + dataPerBlock = dataPerBlock.(fields{1}); + SelProcValues.PeakRange = PeakRange; %ppm + currentValue = SelProcValues.PeakRange; + currentValue = convertPPMtoIndex(dataPerBlock, currentValue,1); + currentValue =[find(currentValue==1,1,'first') find(currentValue==1,1,'last')]; + SelProcValues.PeakRange = [currentValue(1) currentValue(2)]; + bandwidth = dataPerBlock.Parameter.Headers.Bandwidth_Hz; + datafid = squeeze(dataPerBlock.Data{1}); + peakRange = get(SelProcValues, 'PeakRange'); + + if strcmp(metabType(1:2),'Wa') + datafid = datafid(:,2); + dataSpecReal = real(fftshift(fft(datafid))); + else + datafid = datafid(:,1); + dataSpecReal = real(fftshift(fft(datafid))); + end + + fwhmArray(idxSubject,nBl) = linewidth(datafid, SelProcValues, bandwidth); + amplitudeArray(idxSubject,nBl) = max(abs(dataSpecReal(peakRange(1):peakRange(2)))); + end +end + +if exist('excludeSubjects') + n = length(subjects); + m = length(excludeSubjects); + nstep = 1; + for j = 1:m + for i = 1:n + xx = find(~cellfun(@isempty,strfind(subjects(i,1),excludeSubjects{j}))); + if ~isempty(xx) + excludeIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + fwhmArray([excludeIdx],:) = []; + amplitudeArray([excludeIdx],:) = []; + subjects([excludeIdx],:) = []; +end + +if exist('excludeSubjects') + file2save = strcat('BOLD_',metabType,'_',visualType,BOLDType,woBaseline,'_SlidingAverage_Excluded'); +else + file2save = strcat('BOLD_',metabType,'_',visualType,BOLDType,woBaseline,'_SlidingAverage'); +end +BOLD.fwhm = fwhmArray; BOLD.amplitude = amplitudeArray; +eval([file2save '= BOLD']); +exportFileMat = [OutputFilesPathLocal, strcat(file2save,'.mat')]; +save(exportFileMat,file2save) + +x = linspace(16*5,(320*5-16*5),37)/60; +figure +hold on +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 15, 30]); +for idxSubject = 1:length(subjects) + plot(x,(fwhmArray(idxSubject,:)+(idxSubject-1)*1.3),'o-') +end +title ([num2str(file2save),' fwhm'], 'Interpreter', 'none'); +xlabel 't / min'; +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:nBlocks/2 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < nBlocks/2 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:nBlocks/4 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +xlim([0 320*5/60]); +fig2save = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhm.fig')); +savefig(fig2save) + +figure +hold on +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 15, 30]); +for idxSubject = 1:length(subjects) + if strcmp(metabType(1:2),'Cr') + plot(x,(amplitudeArray(idxSubject,:)+(idxSubject-1)*0.001),'o-') + elseif strcmp(metabType(1:3),'NAA') + plot(x,(amplitudeArray(idxSubject,:)+(idxSubject-1)*0.002),'o-') + else strcmp(metabType(1:3),'Wat') + plot(x,(amplitudeArray(idxSubject,:)+(idxSubject-1)*2),'o-') + end +end +title ([num2str(file2save),' amplitude'], 'Interpreter', 'none'); +xlabel 't / min'; +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:nBlocks/2 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < nBlocks/2 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:nBlocks/4 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +xlim([0 320*5/60]); +fig2save = fullfile(OutputFilesPathLocal, strcat(file2save,'_amplitude.fig')); +savefig(fig2save) +close all + +%plot mean, std of BOLD +n = length(fwhmArray); +for indexOfBlock = 1:length(AvNo) + fwhmArray_mean{1,indexOfBlock} = mean(fwhmArray(:,indexOfBlock)); + fwhmArray_std{1,indexOfBlock} = std(fwhmArray(:,indexOfBlock)); + amplitudeArray_mean{1,indexOfBlock} = mean(amplitudeArray(:,indexOfBlock)); + amplitudeArray_std{1,indexOfBlock} = std(amplitudeArray(:,indexOfBlock)); +end + +figure +subplot(2,1,1) +hold on +x = linspace(16*5,(320*5-16*5),37)/60; +errorbar(x,cell2mat(fwhmArray_mean),cell2mat(fwhmArray_std)) +title ([num2str(file2save),' fwhm, mean'], 'Interpreter', 'none'); +ylabel 'FWHM / Hz'; + +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:nBlocks/2 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < nBlocks/2 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:nBlocks/4 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +xlim([0 320*5/60]); + +subplot(2,1,2) +hold on +errorbar(x,cell2mat(amplitudeArray_mean),cell2mat(amplitudeArray_std)) +title ([num2str(file2save),' amplitude, mean'], 'Interpreter', 'none'); +xlabel 't / min';ylabel 'Amplitude / a.u.'; + +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:nBlocks/2 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < nBlocks/2 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:nBlocks/4 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +xlim([0 320*5/60]); +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 12, 18]); +fig2save = fullfile(OutputFilesPathLocal, strcat(file2save,'_Mean.fig')); +savefig(fig2save) +end + +function CorrBOLDCategorical(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end + +for idxmetab = 1:length(metabType) + if strcmp(metabType{idxmetab}(1:2),'Wa') + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType); + else + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType,woBaseline); + end + impFileMat = strcat(OutputFilesPathLocal,impName,'.mat'); + BOLDData = load(impFileMat); + fields = fieldnames(BOLDData); + BOLDDataXY(idxmetab) = BOLDData.(fields{1}); +end +file2save = strcat('Corr_',metabType{1},'_',metabType{2},'_',visualType,BOLDType,woBaseline); +figure +subjects = ones(130,1); +for i = 1:13 + subjects((1+(i-1)*10):(10+(i-1)*10)) = subjects((1+(i-1)*10):(10+(i-1)*10)).*i; +end +fwhmTab = table(BOLDDataXY(1).fwhm(:),BOLDDataXY(2).fwhm(:),subjects); +fwhmTab.subjects = categorical(fwhmTab.subjects); +fit = fitlm(fwhmTab,'Var2~Var1*subjects'); +w = linspace(min(BOLDDataXY(1).fwhm(:)),max(BOLDDataXY(1).fwhm(:))); + +plot(BOLDDataXY(1).fwhm,BOLDDataXY(2).fwhm,'o') +xlabel(['FWHM ',num2str(metabType{1}), ' / Hz']) +ylabel(['FWHM ',num2str(metabType{2}), ' / Hz']) +title(['Correlation FWHM ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') +for i = 1:size(BOLDDataXY(1).fwhm,1) + line(w,feval(fit,w,num2str(i))) +end +fig2saveFWHM = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhm.fig')); +savefig(fig2saveFWHM) + +figure +fwhmAmp = table(BOLDDataXY(1).amplitude(:),BOLDDataXY(2).amplitude(:),subjects); +fwhmAmp.subjects = categorical(fwhmAmp.subjects); +fit = fitlm(fwhmAmp,'Var2~Var1*subjects'); +w = linspace(min(BOLDDataXY(1).amplitude(:)),max(BOLDDataXY(1).amplitude(:))); + +plot(BOLDDataXY(1).amplitude,BOLDDataXY(2).amplitude,'o') +xlabel(['Amplitude ',num2str(metabType{1}), ' / a.u.']) +ylabel(['Amplitude ',num2str(metabType{2}), ' / a.u.']) +title(['Correlation Amplitude ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') +for i = 1:size(BOLDDataXY(1).fwhm,1) + line(w,feval(fit,w,num2str(i))) +end +fig2saveAmplitude = fullfile(OutputFilesPathLocal, strcat(file2save,'_amp.fig')); +savefig(fig2saveAmplitude) + +% close all +end \ No newline at end of file diff --git a/fMRS_processing/BoldEffectfMRS_summedSpectra.m b/fMRS_processing/BoldEffectfMRS_summedSpectra.m new file mode 100644 index 0000000..6bfffd9 --- /dev/null +++ b/fMRS_processing/BoldEffectfMRS_summedSpectra.m @@ -0,0 +1,654 @@ +function BoldEffectfMRS_summedSpectra() +clear; clc; close all; + +pathName = 'fMRS TimeCourse data path'; +[localFilePathBase] = pathToDataFolder(pathName); +visualType = 'Stim'; %'Stim', 'Rest' +BOLDType = '_woBOLDCorr'; +nBlocks = 10; +BlockNo = cell(1,nBlocks); +for k = 1:nBlocks + BlockNo{k} = strcat('_Block', num2str(k)); +end +woBaseline = false; %false, false + +subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... + '4085';'3333';'4012';'4085';'6524'}; +% prefixes = {'2020-02-18_';}; +prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... + '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... + '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; +suffixFolder = '_fMRS'; +excludeSubjects = {'5166';'9810';'5269'}; %doesn't work for not excludeSubjects + +if exist('excludeSubjects') + n = length(subjects); + m = length(excludeSubjects); + nstep = 1; + for j = 1:m + for i = 1:n + xx = find(~cellfun(@isempty,strfind(subjects(i,1),excludeSubjects{j}))); + if ~isempty(xx) + excludeIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + subjects([excludeIdx],:) = []; + prefixes([excludeIdx],:) = []; +end + +numberOfSubjects = length(subjects); +defaultSubject = 'XXXX'; +subjectsPath = strcat(prefixes, subjects, suffixFolder); +preprocessedFilesPathLocal = strcat(localFilePathBase, subjectsPath, '/'); +OutputFilesPathLocal = strcat(localFilePathBase, 'Output_v2_MMBSummed/BOLD/'); +outputFileNameBase = strcat(defaultSubject, '_', num2str(visualType), BOLDType); +extensionMat = '.mat'; + +%% sum fMRS spectra of all volunteers, weighted with water fit (need to run doFitting_fMRS_Water.m first) +% WaterReferenceTable = (readtable(strcat(OutputFilesPathLocal,'WaterReference_Fit.xlsx'))); +% WaterReferenceID = table2cell(WaterReferenceTable(2:end,1)); +% WaterReference = str2double(table2array(WaterReferenceTable(2:end,2:end))); +% fMRSDataScaled = zeros(4096,numberOfSubjects,2,length(BlockNo)); %samples, subjects, data/water +% for indexCurrentSubject = 1:numberOfSubjects +% for indexBlock = 1:length(BlockNo) +% idx = find(ismember(WaterReferenceID, strcat(prefixes{indexCurrentSubject}, subjects{indexCurrentSubject}))); +% currentScalingFactor = WaterReference(idx,1); +% currentfMRSDataPath = strcat(localFilePathBase,subjectsPath{indexCurrentSubject}); +% load(strrep(strcat(currentfMRSDataPath, '\',outputFileNameBase,BlockNo{indexBlock},extensionMat),defaultSubject,subjects{indexCurrentSubject})); +% currentfMRSData = squeeze(this.Data{1}); +% currentfMRSDataScaled = currentfMRSData./currentScalingFactor; +% fMRSDataScaled(:,indexCurrentSubject,:,indexBlock) = currentfMRSDataScaled; +% end +% end +% cd ('D:\PAPER\1H_fMRS\Data_TimeCourse\SummedData') +% fMRSData_Summed_Path = strcat(localFilePathBase,'SummedData\'); +% this.Parameter.Filepath = fMRSData_Summed_Path; +% fMRSData_Summed = squeeze(sum(fMRSDataScaled,2)); +% this.Parameter.Filename = 'fMRSData_Summed_Block1_v2_MMBSummed_Excluded'; +% fMRSData_Summed_Block1 = fMRSData_Summed(:,:,1); fMRSData_Summed_Block1 = permute(fMRSData_Summed_Block1,[1 3 4 5 6 7 8 9 2]); +% % this.Data{1} = fMRSData_Summed_Block1; save('fMRSData_Summed_Block1','this'); this.ExportLcmRaw(fMRSData_Summed_Path,'fMRSData_Summed_Block1','Yes', 'Yes'); +% this.Data{1} = fMRSData_Summed_Block1; save(strcat('fMRSData_Summed_',visualType,BOLDType,'_Block1'),'this'); this.ExportLcmRaw(fMRSData_Summed_Path,strcat('fMRSData_Summed_',visualType,BOLDType,'_Block1'),'Yes', 'Yes'); +% this.Parameter.Filename = 'fMRSData_Summed_Block2_v2_MMBSummed_Excluded'; +% fMRSData_Summed_Block2 = fMRSData_Summed(:,:,2); fMRSData_Summed_Block2 = permute(fMRSData_Summed_Block2,[1 3 4 5 6 7 8 9 2]); +% this.Data{1} = fMRSData_Summed_Block2; save(strcat('fMRSData_Summed_',visualType,BOLDType,'_Block2'),'this'); this.ExportLcmRaw(fMRSData_Summed_Path,strcat('fMRSData_Summed_',visualType,BOLDType,'_Block2'),'Yes', 'Yes'); +% this.Parameter.Filename = 'fMRSData_Summed_Block3_v2_MMBSummed_Excluded'; +% fMRSData_Summed_Block3 = fMRSData_Summed(:,:,3); fMRSData_Summed_Block3 = permute(fMRSData_Summed_Block3,[1 3 4 5 6 7 8 9 2]); +% this.Data{1} = fMRSData_Summed_Block3; save(strcat('fMRSData_Summed_',visualType,BOLDType,'_Block3'),'this'); this.ExportLcmRaw(fMRSData_Summed_Path,strcat('fMRSData_Summed_',visualType,BOLDType,'_Block3'),'Yes', 'Yes'); +% this.Parameter.Filename = 'fMRSData_Summed_Block4_v2_MMBSummed_Excluded'; +% fMRSData_Summed_Block4 = fMRSData_Summed(:,:,4); fMRSData_Summed_Block4 = permute(fMRSData_Summed_Block4,[1 3 4 5 6 7 8 9 2]); +% this.Data{1} = fMRSData_Summed_Block4; save(strcat('fMRSData_Summed_',visualType,BOLDType,'_Block4'),'this'); this.ExportLcmRaw(fMRSData_Summed_Path,strcat('fMRSData_Summed_',visualType,BOLDType,'_Block4'),'Yes', 'Yes'); +% this.Parameter.Filename = 'fMRSData_Summed_Block5_v2_MMBSummed_Excluded'; +% fMRSData_Summed_Block5 = fMRSData_Summed(:,:,5); fMRSData_Summed_Block5 = permute(fMRSData_Summed_Block5,[1 3 4 5 6 7 8 9 2]); +% this.Data{1} = fMRSData_Summed_Block5; save(strcat('fMRSData_Summed_',visualType,BOLDType,'_Block5'),'this'); this.ExportLcmRaw(fMRSData_Summed_Path,strcat('fMRSData_Summed_',visualType,BOLDType,'_Block5'),'Yes', 'Yes'); +% this.Parameter.Filename = 'fMRSData_Summed_Block6_v2_MMBSummed_Excluded'; +% fMRSData_Summed_Block6 = fMRSData_Summed(:,:,6); fMRSData_Summed_Block6 = permute(fMRSData_Summed_Block6,[1 3 4 5 6 7 8 9 2]); +% this.Data{1} = fMRSData_Summed_Block6; save(strcat('fMRSData_Summed_',visualType,BOLDType,'_Block6'),'this'); this.ExportLcmRaw(fMRSData_Summed_Path,strcat('fMRSData_Summed_',visualType,BOLDType,'_Block6'),'Yes', 'Yes'); +% this.Parameter.Filename = 'fMRSData_Summed_Block7_v2_MMBSummed_Excluded'; +% fMRSData_Summed_Block7 = fMRSData_Summed(:,:,7); fMRSData_Summed_Block7 = permute(fMRSData_Summed_Block7,[1 3 4 5 6 7 8 9 2]); +% this.Data{1} = fMRSData_Summed_Block7; save(strcat('fMRSData_Summed_',visualType,BOLDType,'_Block7'),'this'); this.ExportLcmRaw(fMRSData_Summed_Path,strcat('fMRSData_Summed_',visualType,BOLDType,'_Block7'),'Yes', 'Yes'); +% this.Parameter.Filename = 'fMRSData_Summed_Block8_v2_MMBSummed_Excluded'; +% fMRSData_Summed_Block8 = fMRSData_Summed(:,:,8); fMRSData_Summed_Block8 = permute(fMRSData_Summed_Block8,[1 3 4 5 6 7 8 9 2]); +% this.Data{1} = fMRSData_Summed_Block8; save(strcat('fMRSData_Summed_',visualType,BOLDType,'_Block8'),'this'); this.ExportLcmRaw(fMRSData_Summed_Path,strcat('fMRSData_Summed_',visualType,BOLDType,'_Block8'),'Yes', 'Yes'); +% this.Parameter.Filename = 'fMRSData_Summed_Block9_v2_MMBSummed_Excluded'; +% fMRSData_Summed_Block9 = fMRSData_Summed(:,:,9); fMRSData_Summed_Block9 = permute(fMRSData_Summed_Block9,[1 3 4 5 6 7 8 9 2]); +% this.Data{1} = fMRSData_Summed_Block9; save(strcat('fMRSData_Summed_',visualType,BOLDType,'_Block9'),'this'); this.ExportLcmRaw(fMRSData_Summed_Path,strcat('fMRSData_Summed_',visualType,BOLDType,'_Block9'),'Yes', 'Yes'); +% this.Parameter.Filename = 'fMRSData_Summed_Block10_v2_MMBSummed_Excluded'; +% fMRSData_Summed_Block10 = fMRSData_Summed(:,:,10); fMRSData_Summed_Block10 = permute(fMRSData_Summed_Block10,[1 3 4 5 6 7 8 9 2]); +% this.Data{1} = fMRSData_Summed_Block10; save(strcat('fMRSData_Summed_',visualType,BOLDType,'_Block10'),'this'); this.ExportLcmRaw(fMRSData_Summed_Path,strcat('fMRSData_Summed_',visualType,BOLDType,'_Block10'),'Yes', 'Yes'); + +%% BOLD FWHM / Amplitude +% % for Water (not useful w/o baseline, since it doesn't have a baseline) +% PeakRange = [4 5]; %ppm where to find the peak +% metabType = 'Water'; +% if exist('excludeSubjects') +% CalcBOLDEffect(BlockNo,visualType,BOLDType,localFilePathBase,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType,'') +% else +% CalcBOLDEffect(BlockNo,visualType,BOLDType,localFilePathBase,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType) +% end +% +% %for NAA (2.008 ppm) +% PeakRange = [1.8 2.3]; %ppm where to find the peak +% metabType = 'NAA'; +% if exist('excludeSubjects') +% CalcBOLDEffect(BlockNo,visualType,BOLDType,localFilePathBase,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType,woBaseline) +% else +% CalcBOLDEffect(BlockNo,visualType,BOLDType,localFilePathBase,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType,woBaseline) +% end +% +% %for Cr (methyl signal of tCr: 3.027ppm) +% PeakRange = [2.9 3.15]; %ppm where to find the peak +% metabType = 'Cr'; +% if exist('excludeSubjects') +% CalcBOLDEffect(BlockNo,visualType,BOLDType,localFilePathBase,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType,woBaseline) +% else +% CalcBOLDEffect(BlockNo,visualType,BOLDType,localFilePathBase,... +% OutputFilesPathLocal,nBlocks,PeakRange,metabType,woBaseline) +% end +% +% % correlation FWHM, Amplitude +metabType = {'NAA', 'Cr'}; +metabType = {'Water', 'NAA'}; +metabType = {'Water', 'Cr'}; +% metabType = {'Water'}; +if exist('excludeSubjects') + CorrBOLDSpearman(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) +else + CorrBOLDSpearman(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) +end +% % % % didn't check this for summed data +% % % % CorrBOLDCategorical(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) + +%% correlation Water, Metabolite Concentration +% metabType = {'Glu'}; +if exist('excludeSubjects') + CorrBOLDSpearman_MetConc({'Cr'},visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects); close all + CorrBOLDSpearman_MetConc({'PCr'},visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects); close all + CorrBOLDSpearman_MetConc({'Lac'},visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects); close all + CorrBOLDSpearman_MetConc({'Glu'},visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects); close all +else + CorrBOLDSpearman_MetConc({'Cr'},visualType,BOLDType,OutputFilesPathLocal,woBaseline) + CorrBOLDSpearman_MetConc({'PCr'},visualType,BOLDType,OutputFilesPathLocal,woBaseline) +% CorrBOLDSpearman_MetConc({'Lac'},visualType,BOLDType,OutputFilesPathLocal,woBaseline) +% CorrBOLDSpearman_MetConc({'Glu'},visualType,BOLDType,OutputFilesPathLocal,woBaseline) +end + +end + +function CorrBOLDSpearman_MetConc(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end + +if exist('excludeSubjects') + impName = strcat('BOLD_Water_',visualType,BOLDType,'_Excluded_SummedData'); +else + impName = strcat('BOLD_Water_',visualType,BOLDType,'_SummedData'); +end +impFileMat = strcat(OutputFilesPathLocal,impName,'.mat'); +BOLDData = load(impFileMat); +fields = fieldnames(BOLDData); +BOLDDataXY(1) = BOLDData.(fields{1}); + +%import Met Conc +impNameMetConc = strcat('BlockConc_Summed_Stim_woBOLDCorr_MMBSummed_v2',woBaseline); +impFileMatMetConc = strcat(OutputFilesPathLocal(1:end-5),impNameMetConc,'.mat'); +BOLDData = load(impFileMatMetConc); +fields = fieldnames(BOLDData); +BOLDData_temp = BOLDData.(fields{1}); +indexMet = strcmp(BOLDData_temp(1,:),metabType); +idxMet = find(indexMet); +for i = 1:10 + BOLDData_Met(i) = BOLDData_temp{i+1,idxMet}; %Met conc per block +end + +if exist('excludeSubjects') + file2save = strcat('Corr_Water_',metabType{1},'_Conc_Summed_',visualType,BOLDType,woBaseline,'_Excluded'); +else + file2save = strcat('Corr_Water_',metabType{1},'_Conc_Summed_',visualType,BOLDType,woBaseline); +end + +% subjLength = length(BOLDDataXY(1).fwhm); +subjLength = 1; +subjects = ones(subjLength*10,1); +for i = 1:subjLength + subjects((1+(i-1)*10):(10+(i-1)*10)) = subjects((1+(i-1)*10):(10+(i-1)*10)).*i; +end + +%for FWHM (Water Hz vs Met a.u.) +fwhmTab = table(BOLDDataXY(1).fwhm(:),BOLDData_Met',subjects); +BOLDData_FWHM = table2array(fwhmTab); +%Spearman correlation +[RHO,PVAL] = corr(BOLDData_FWHM(:,2),BOLDData_FWHM(:,1),'Type','Spearman'); +% [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); +%linear regression +fit = fitlm(BOLDData_FWHM(:,2),BOLDData_FWHM(:,1)); +figure +hold on +% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') +plot(fit); box on +xlabel(['Concentration ' , char(metabType), ' / a.u.']) +ylabel(['FWHM Water / Hz']) +title(['Correlation FWHM Water & concentration ', char(metabType), woBaseline], 'Interpreter', 'none') +txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; +text(max(BOLDData_FWHM(:,2))-0.2,max(BOLDData_FWHM(:,1)),txt); +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); + +fig2saveFWHM = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhmConc.fig')); +% savefig(fig2saveFWHM) + +%for FWHM (Delta Water Hz vs Delta Met a.u.) +subjectsDelta = subjects(1:9); +fwhmTabDelta = table(diff(BOLDDataXY(1).fwhm(:)),diff(BOLDData_Met'),subjectsDelta); +BOLDData_FWHM_Delta = table2array(fwhmTabDelta); +%Spearman correlation +[RHODelta,PVALDelta] = corr(BOLDData_FWHM_Delta(:,2),BOLDData_FWHM_Delta(:,1),'Type','Spearman'); +% [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); +%linear regression +fitDelta = fitlm(BOLDData_FWHM_Delta(:,2),BOLDData_FWHM_Delta(:,1)); +figure +hold on +% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') +plot(fitDelta); box on +xlabel([char(916), ' Concentration ' , char(metabType), ' / a.u.']) +ylabel([char(916), ' FWHM Water / Hz']) +title(['Correlation ', char(916), 'FWHM Water & concentration ', char(metabType), woBaseline], 'Interpreter', 'none') +txt = {['R = ' num2str(RHODelta)],['p < ' num2str(PVALDelta)]}; +text(max(BOLDData_FWHM_Delta(:,2))-0.2,max(BOLDData_FWHM_Delta(:,1)),txt); +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); + +fig2saveFWHMDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_DeltafwhmConc.fig')); +% savefig(fig2saveFWHMDelta) + +%for amplitude (Water a.u. vs Met a.u.) +ampTab = table(BOLDDataXY(1).amplitude(:),BOLDData_Met',subjects); +BOLDData_amp = table2array(ampTab); +%Spearman correlation +[RHO,PVAL] = corr(BOLDData_amp(:,2),BOLDData_amp(:,1),'Type','Spearman'); +%linear regression +fit = fitlm(BOLDData_amp(:,2),BOLDData_amp(:,1)); +figure +hold on +% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') +plot(fit) +ylim([1430 1500]); box on +xlabel(['Concentration ' , char(metabType), ' / a.u.']) +ylabel(['Amplitude Water / a.u.']) +title(['Correlation Amplitude Water & concentration ', char(metabType), woBaseline], 'Interpreter', 'none') +txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; +text((max(BOLDData_amp(:,2))-max(BOLDData_amp(:,2))*0.06),(min(BOLDData_amp(:,1))+min(BOLDData_amp(:,1))*0.01),txt); +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); +lines = findobj(gcf,'Type','Line'); +for i = 1:numel(lines) +lines(i).LineWidth = 1.5; +end +fig2saveAmplitude = fullfile(OutputFilesPathLocal, strcat(file2save,'_ampConc.fig')); +savefig(fig2saveAmplitude) + +%for amplitude (Delta Water a.u. vs Delta Met a.u.) +ampTabDelta = table(diff(BOLDDataXY(1).amplitude(:)),diff(BOLDData_Met'),subjectsDelta); +BOLDData_amp_Delta = table2array(ampTabDelta); +%Spearman correlation +[RHODelta,PVALDelta] = corr(BOLDData_amp_Delta(:,2),BOLDData_amp_Delta(:,1),'Type','Spearman'); +%linear regression +fitDelta = fitlm(BOLDData_amp_Delta(:,2),BOLDData_amp_Delta(:,1)); +figure +hold on +% plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') +plot(fitDelta); box on +xlabel([char(916), ' Concentration ' , char(metabType), ' / a.u.']) +ylabel([char(916), ' Amplitude Water / a.u.']) +title(['Correlation ', char(916), 'Amplitude Water & concentration ', char(metabType), woBaseline], 'Interpreter', 'none') +txt = {['R = ' num2str(RHODelta)],['p < ' num2str(PVALDelta)]}; +text((max(BOLDData_amp_Delta(:,2))-max(BOLDData_amp_Delta(:,2))*0.2),(min(BOLDData_amp_Delta(:,1))+min(BOLDData_amp_Delta(:,1))*0.01),txt); +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); +fig2saveAmplitudeDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_DeltaampConc.fig')); +% savefig(fig2saveAmplitudeDelta) +end + +function CorrBOLDSpearman(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline,excludeSubjects) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end + +for idxmetab = 1:length(metabType) + if strcmp(metabType{idxmetab}(1:2),'Wa') + if exist('excludeSubjects') + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType,'_Excluded_SummedData'); + else + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType,'_SummedData'); + end + else + if exist('excludeSubjects') + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType,woBaseline,'_Excluded_SummedData'); + else + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType,woBaseline,'_SummedData'); + end + end + impFileMat = strcat(OutputFilesPathLocal,impName,'.mat'); + BOLDData = load(impFileMat); + fields = fieldnames(BOLDData); + BOLDDataXY(idxmetab) = BOLDData.(fields{1}); +end + +if exist('excludeSubjects') + if length(metabType) == 2 + file2save = strcat('Corr_',metabType{1},'_',metabType{2},'_',visualType,BOLDType,woBaseline,'_Excluded_SummedData'); + elseif length(metabType) == 1 + file2save = strcat('Corr_',metabType{1},'_FWHMAmp_',visualType,BOLDType,woBaseline,'_Excluded_SummedData'); + end +else + if length(metabType) == 2 + file2save = strcat('Corr_',metabType{1},'_',metabType{2},'_',visualType,BOLDType,woBaseline,'_SummedData'); + elseif length(metabType) == 1 + file2save = strcat('Corr_',metabType{1},'_FWHMAmp_',visualType,BOLDType,woBaseline,'_SummedData'); + end +end + +% subjLength = length(BOLDDataXY(1).fwhm); +subjLength = 1; +subjects = ones(subjLength*10,1); +for i = 1:subjLength + subjects((1+(i-1)*10):(10+(i-1)*10)) = subjects((1+(i-1)*10):(10+(i-1)*10)).*i; +end + +if length(metabType) == 2 + %for FWHM (Hz) + fwhmTab = table(BOLDDataXY(1).fwhm(:),BOLDDataXY(2).fwhm(:),subjects); + BOLDData_FWHM = table2array(fwhmTab); + %Spearman correlation + [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Spearman'); + % [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); + %linear regression + fit = fitlm(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fit); box on; + xlabel(['FWHM ',num2str(metabType{1}), ' / Hz']) + ylabel(['FWHM ',num2str(metabType{2}), ' / Hz']) + title(['Correlation FWHM ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; + text(min(BOLDData_FWHM(:,1)),max(BOLDData_FWHM(:,2)),txt) + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); + lines = findobj(gcf,'Type','Line'); + for i = 1:numel(lines) + lines(i).LineWidth = 1.5; + end + fig2saveFWHM = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhm.fig')); +% savefig(fig2saveFWHM) + + %for FWHM (Delta Hz) + subjectsDelta = subjects(1:9); + fwhmTabDelta = table(diff(BOLDDataXY(1).fwhm(:)),diff(BOLDDataXY(2).fwhm(:)),subjectsDelta); + BOLDData_FWHM_Delta = table2array(fwhmTabDelta); + %Spearman correlation + [RHODelta,PVALDelta] = corr(BOLDData_FWHM_Delta(:,1),BOLDData_FWHM_Delta(:,2),'Type','Spearman'); + %linear regression + fitDelta = fitlm(BOLDData_FWHM_Delta(:,1),BOLDData_FWHM_Delta(:,2)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fitDelta); box on; + xlabel([char(916) 'FWHM ',num2str(metabType{1}), ' / Hz']) + ylabel([char(916) 'FWHM ',num2str(metabType{2}), ' / Hz']) + title(['Correlation ' char(916) 'FWHM ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHODelta)],['p < ' num2str(PVALDelta)]}; + text(min(BOLDData_FWHM_Delta(:,1)),max(BOLDData_FWHM_Delta(:,2)),txt) + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); + lines = findobj(gcf,'Type','Line'); + for i = 1:numel(lines) + lines(i).LineWidth = 1.5; + end + fig2saveFWHMDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_Deltafwhm.fig')); +% savefig(fig2saveFWHMDelta) + + %for amplitude (a.u.) + ampTab = table(BOLDDataXY(1).amplitude(:),BOLDDataXY(2).amplitude(:),subjects); + BOLDData_amp = table2array(ampTab); + %Spearman correlation + [RHO,PVAL] = corr(BOLDData_amp(:,1),BOLDData_amp(:,2),'Type','Spearman'); + %linear regression + fit = fitlm(BOLDData_amp(:,1),BOLDData_amp(:,2)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fit); box on; + xlabel(['Amplitude ',num2str(metabType{1}), ' / a.u.']) + ylabel(['Amplitude ',num2str(metabType{2}), ' / a.u.']) + title(['Correlation Amplitude ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; + text(min(BOLDData_amp(:,1)),max(BOLDData_amp(:,2)),txt) + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); + lines = findobj(gcf,'Type','Line'); + for i = 1:numel(lines) + lines(i).LineWidth = 1.5; + end + fig2saveAmplitude = fullfile(OutputFilesPathLocal, strcat(file2save,'_amp.fig')); +% savefig(fig2saveAmplitude) + + %for amplitude (Delta a.u.) + ampTabDelta = table(diff(BOLDDataXY(1).amplitude(:)),diff(BOLDDataXY(2).amplitude(:)),subjectsDelta); + BOLDData_amp_Delta = table2array(ampTabDelta); + %Spearman correlation + [RHODelta,PVALDelta] = corr(BOLDData_amp_Delta(:,1),BOLDData_amp_Delta(:,2),'Type','Spearman'); + %linear regression + fitDelta = fitlm(BOLDData_amp_Delta(:,1),BOLDData_amp_Delta(:,2)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fitDelta); box on; + xlabel([char(916) 'Amplitude ',num2str(metabType{1}), ' / a.u.']) + ylabel([char(916) 'Amplitude ',num2str(metabType{2}), ' / a.u.']) + title(['Correlation ' char(916) 'Amplitude ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHODelta)],['p < ' num2str(PVALDelta)]}; + text(min(BOLDData_amp_Delta(:,1)),max(BOLDData_amp_Delta(:,2)),txt) + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); + lines = findobj(gcf,'Type','Line'); + for i = 1:numel(lines) + lines(i).LineWidth = 1.5; + end + fig2saveAmplitudeDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_Deltaamp.fig')); +% savefig(fig2saveAmplitudeDelta) + +elseif length(metabType) == 1 + %for FWHM (Hz) / Amp (a.u.) + fwhmAmpTab = table(BOLDDataXY(1).fwhm(:),BOLDDataXY(1).amplitude(:),subjects); + BOLDData = table2array(fwhmAmpTab); + %Spearman correlation + [RHO,PVAL] = corr(BOLDData(:,1),BOLDData(:,2),'Type','Spearman'); + % [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); + %linear regression + fit = fitlm(BOLDData(:,2),BOLDData(:,1)); + figure + hold on + plot(fit); box on; + xlabel(['Amplitude ',num2str(metabType{1}), ' / a.u.']) + ylabel(['FWHM ',num2str(metabType{1}), ' / Hz']) + title(['Correlation FWHM & Amplitude ', num2str(metabType{1}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; + text(min(BOLDData(:,2))+min(BOLDData(:,2))*0.001,min(BOLDData(:,1))+min(BOLDData(:,1))*0.001,txt) + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); + lines = findobj(gcf,'Type','Line'); + for i = 1:numel(lines) + lines(i).LineWidth = 1.5; + end + fig2save = fullfile(OutputFilesPathLocal, strcat(file2save,'.fig')); + savefig(fig2save) + + %for FWHM (Delta Hz) / Amp (Delta a.u.) + subjectsDelta = subjects(1:9); + fwhmAmpTabDelta = table(diff(BOLDDataXY(1).fwhm(:)),diff(BOLDDataXY(1).amplitude(:)),subjectsDelta); + BOLDData_Delta = table2array(fwhmAmpTabDelta); + %Spearman correlation + [RHODelta,PVALDelta] = corr(BOLDData_Delta(:,1),BOLDData_Delta(:,2),'Type','Spearman'); + %linear regression + fitDelta = fitlm(BOLDData_Delta(:,2),BOLDData_Delta(:,1)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fitDelta); box on; + xlabel([char(916) 'Amplitude ',num2str(metabType{1}), ' / a.u.']) + ylabel([char(916) 'FWHM ',num2str(metabType{1}), ' / Hz']) + title(['Correlation ' char(916) 'FWHM & Amplitude ', num2str(metabType{1}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHODelta)],['p < ' num2str(PVALDelta)]}; + text(min(BOLDData_Delta(:,2)),min(BOLDData_Delta(:,1))+0.05,txt) + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); set(gca, 'FontWeight','bold'); + lines = findobj(gcf,'Type','Line'); + for i = 1:numel(lines) + lines(i).LineWidth = 1.5; + end + fig2saveDelta = fullfile(OutputFilesPathLocal, strcat(file2save,'_Delta.fig')); +% savefig(fig2saveDelta) +end +end + + + + +function CalcBOLDEffect(BlockNo,visualType,BOLDType,preprocessedFilesPathLocal,... + OutputFilesPathLocal,nBlocks,PeakRange,metabType,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; + fitVersion = '_v2'; +else + woBaseline = ''; + fitVersion = ''; +end +SelProcValues = SelectedProcessingValues(); +fwhmArray = zeros(1,length(BlockNo)); +amplitudeArray = zeros(1,length(BlockNo)); +for nBl = 1:length(BlockNo) + impName = strcat('fMRSData_Summed_',visualType,BOLDType,fitVersion, BlockNo{nBl},woBaseline); + impFileMat = strcat(preprocessedFilesPathLocal,'SummedData\',impName,'.mat'); + dataPerBlock = load(impFileMat); + fields = fieldnames(dataPerBlock); + dataPerBlock = dataPerBlock.(fields{1}); + SelProcValues.PeakRange = PeakRange; %ppm + currentValue = SelProcValues.PeakRange; + currentValue = convertPPMtoIndex(dataPerBlock, currentValue,1); + currentValue =[find(currentValue==1,1,'first') find(currentValue==1,1,'last')]; + SelProcValues.PeakRange = [currentValue(1) currentValue(2)]; + bandwidth = dataPerBlock.Parameter.Headers.Bandwidth_Hz; + datafid = squeeze(dataPerBlock.Data{1}); + peakRange = get(SelProcValues, 'PeakRange'); + + if strcmp(metabType(1:2),'Wa') + datafid = datafid(:,2); + dataSpecReal = real(fftshift(fft(datafid))); + else + datafid = datafid(:,1); + dataSpecReal = real(fftshift(fft(datafid))); + end + + fwhmArray(1,nBl) = linewidth(datafid, SelProcValues, bandwidth); + amplitudeArray(1,nBl) = max(abs(dataSpecReal(peakRange(1):peakRange(2)))); +end + +file2save = strcat('BOLD_',metabType,'_',visualType,BOLDType,woBaseline,'_Excluded_SummedData'); + +BOLD.fwhm = fwhmArray; BOLD.amplitude = amplitudeArray; +eval([file2save '= BOLD']); +exportFileMat = [OutputFilesPathLocal, strcat(file2save,'.mat')]; +% save(exportFileMat,file2save) + +x = linspace(320/60/4,(320*5/60-320/60/4),10); +figure +plot(x,fwhmArray,'o-') + +title ([num2str(file2save),' fwhm'], 'Interpreter', 'none'); +xlabel 't / min'; +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:nBlocks/2 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < nBlocks/2 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:nBlocks/4 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +xlim([0 320*5/60]);set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +set(gca, 'FontWeight','bold'); +fig2save = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhm.fig')); +% savefig(fig2save) + +figure +plot(x,amplitudeArray./10,'o-') + +title ([num2str(file2save),' amplitude'], 'Interpreter', 'none'); +xlabel 't / min'; +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:nBlocks/2 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < nBlocks/2 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:nBlocks/4 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +xlim([0 320*5/60]);set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +set(gca, 'FontWeight','bold'); +fig2save = fullfile(OutputFilesPathLocal, strcat(file2save,'_amplitude.fig')); +% savefig(fig2save) +close all +end + +function CorrBOLDCategorical(metabType,visualType,BOLDType,OutputFilesPathLocal,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end + +for idxmetab = 1:length(metabType) + if strcmp(metabType{idxmetab}(1:2),'Wa') + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType); + else + impName = strcat('BOLD_',metabType{idxmetab},'_',visualType,BOLDType,woBaseline); + end + impFileMat = strcat(OutputFilesPathLocal,impName,'.mat'); + BOLDData = load(impFileMat); + fields = fieldnames(BOLDData); + BOLDDataXY(idxmetab) = BOLDData.(fields{1}); +end +file2save = strcat('Corr_',metabType{1},'_',metabType{2},'_',visualType,BOLDType,woBaseline); +figure +subjects = ones(130,1); +for i = 1:13 + subjects((1+(i-1)*10):(10+(i-1)*10)) = subjects((1+(i-1)*10):(10+(i-1)*10)).*i; +end +fwhmTab = table(BOLDDataXY(1).fwhm(:),BOLDDataXY(2).fwhm(:),subjects); +fwhmTab.subjects = categorical(fwhmTab.subjects); +fit = fitlm(fwhmTab,'Var2~Var1*subjects'); +w = linspace(min(BOLDDataXY(1).fwhm(:)),max(BOLDDataXY(1).fwhm(:))); + +plot(BOLDDataXY(1).fwhm,BOLDDataXY(2).fwhm,'o') +xlabel(['FWHM ',num2str(metabType{1}), ' / Hz']) +ylabel(['FWHM ',num2str(metabType{2}), ' / Hz']) +title(['Correlation FWHM ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') +for i = 1:size(BOLDDataXY(1).fwhm,1) + line(w,feval(fit,w,num2str(i))) +end +fig2saveFWHM = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhm.fig')); +savefig(fig2saveFWHM) + +figure +fwhmAmp = table(BOLDDataXY(1).amplitude(:),BOLDDataXY(2).amplitude(:),subjects); +fwhmAmp.subjects = categorical(fwhmAmp.subjects); +fit = fitlm(fwhmAmp,'Var2~Var1*subjects'); +w = linspace(min(BOLDDataXY(1).amplitude(:)),max(BOLDDataXY(1).amplitude(:))); + +plot(BOLDDataXY(1).amplitude,BOLDDataXY(2).amplitude,'o') +xlabel(['Amplitude ',num2str(metabType{1}), ' / a.u.']) +ylabel(['Amplitude ',num2str(metabType{2}), ' / a.u.']) +title(['Correlation Amplitude ', num2str(metabType{1}), ' & ', num2str(metabType{2}), woBaseline], 'Interpreter', 'none') +for i = 1:size(BOLDDataXY(1).fwhm,1) + line(w,feval(fit,w,num2str(i))) +end +fig2saveAmplitude = fullfile(OutputFilesPathLocal, strcat(file2save,'_amp.fig')); +savefig(fig2saveAmplitude) + +% close all +end \ No newline at end of file diff --git a/fMRS_processing/Corr_BOLD_Met.m b/fMRS_processing/Corr_BOLD_Met.m new file mode 100644 index 0000000..5636b7d --- /dev/null +++ b/fMRS_processing/Corr_BOLD_Met.m @@ -0,0 +1,239 @@ +function Corr_BOLD_Met() +clear; clc; close all; + +pathName = 'fMRS data path'; +[localFilePathBase] = pathToDataFolder(pathName); +StimType = {'RestOFF', 'RestON'}; %'StimOFF', 'StimON', 'RestOFF', 'RestON' +if ~isempty(strfind(StimType{1},'Stim')) + visualType = 'Stim'; +elseif ~isempty(strfind(StimType{1},'Rest')) + visualType = 'Rest'; +else + error('StimType needs to be Stim or Rest'); +end +BOLDTypes = {'_woBOLDCorr128', '_withBOLDCorr128','_woBOLDCorr64', '_woBOLDCorr64#1', '_withBOLDCorr64', '_withBOLDCorr64#1'}; +MMBType = '_MMBSummed_v2'; +woBaseline = false; %false, true + +subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... + '4085';'3333';'4012';'4085';'6524'}; +prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... + '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... + '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; +suffixFolder = '_fMRS'; +excludeSubjects = {'5166';'9810';'5269'}; + +subjectsPath = strcat(prefixes, subjects, suffixFolder); +preprocessedFilesPathLocal = strcat(localFilePathBase, subjectsPath, '/'); +OutputFilesPathLocal = strcat(localFilePathBase, 'Output_v2_MMBSummed/BOLD/'); +OutputConcDiffPathLocal = strcat('D:\PAPER\1H_fMRS\Statistics\'); + +% for idxBOLDType = 1:length(BOLDTypes) +% BOLDType = BOLDTypes{idxBOLDType}; +% %for Water +% PeakRange = [4 5]; %ppm where to find the peak +% metabType = 'Water'; +% CalcBOLDEffect(subjects,subjectsPath,StimType,visualType,BOLDType,preprocessedFilesPathLocal,... +% OutputFilesPathLocal,PeakRange,metabType,'') +% end +% % %for NAA (2.008 ppm) +% % PeakRange = [1.8 2.3]; %ppm where to find the peak +% % metabType = 'NAA'; +% % CalcBOLDEffect(subjects,subjectsPath,StimType,visualType,BOLDType,preprocessedFilesPathLocal,... +% % OutputFilesPathLocal,PeakRange,metabType,'') +% % %for Cr (methyl signal of tCr: 3.027ppm) +% % PeakRange = [2.9 3.15]; %ppm where to find the peak +% % metabType = 'Cr'; +% % CalcBOLDEffect(subjects,subjectsPath,StimType,visualType,BOLDType,preprocessedFilesPathLocal,... +% % OutputFilesPathLocal,PeakRange,metabType,'') +% % + +% correlation Water, Metabolite Concentration +metabType = {'Lac', 'Glu', 'Cr', 'PCr'}; +for idxBOLDType = 1:length(BOLDTypes) + BOLDType = BOLDTypes{idxBOLDType}; + if exist('excludeSubjects') + CorrBOLDSpearman_MetConc(metabType,visualType,BOLDType,MMBType,OutputFilesPathLocal,woBaseline,subjects,prefixes,excludeSubjects,OutputConcDiffPathLocal) + else + CorrBOLDSpearman_MetConc(metabType,visualType,BOLDType,MMBType,OutputFilesPathLocal,woBaseline) + end +end + +end + +function CorrBOLDSpearman_MetConc(metabType,visualType,BOLDType,MMBType,OutputFilesPathLocal,woBaseline,subjects,prefixes,excludeSubjects,OutputConcDiffPathLocal) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end + +if exist('excludeSubjects','var') + n = length(subjects); + m = length(excludeSubjects); + nstep = 1; + for j = 1:m + for i = 1:n + xx = find(~cellfun(@isempty,strfind(subjects(i,1),excludeSubjects{j}))); + if ~isempty(xx) + excludeIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + subjects([excludeIdx],:) = []; + prefixes([excludeIdx],:) = []; +end +subjectsPath = strcat(prefixes, subjects, '_fMRS/'); + +for idxOfSubj = 1:length(subjects) + %import BOLD Water data, absolute change in amplitude (a.u.) and FWHM + %(Hz), not percent change + impWaterName = strcat(visualType,BOLDType,'_WaterBOLD'); + impWaterFileMat = strrep(strcat(OutputFilesPathLocal,subjectsPath{idxOfSubj},impWaterName,'.mat'),'#','_'); + BOLDData = load(impWaterFileMat); + fields = fieldnames(BOLDData); + BOLDDataXY = BOLDData.(fields{1}); + FWHMChange = 100/BOLDDataXY.fwhm(1)*BOLDDataXY.fwhm(2)-100; + AmpChange = 100/BOLDDataXY.amplitude(1)*BOLDDataXY.amplitude(2)-100; + %import Metabolite data, concentration differences in percent per + %metabolite and subject (all subjects in one table) + %%%%D:\PAPER\1H_fMRS\Statistics\ConcDiff_Stim_woBOLDCorr64_1_MMBSummed_v2_Excluded.mat + + + if exist('excludeSubjects','var') + impMetName = strcat('ConcDiff_',visualType,BOLDType,MMBType,'_Excluded'); + else + impMetName = strcat('ConcDiff_',visualType,BOLDType,MMBType); + end + impWaterFileMat = strrep(strcat(OutputConcDiffPathLocal,impMetName,'.mat'),'#','_'); + MetData = load(impWaterFileMat); + fields = fieldnames(MetData); + MetData = MetData.(fields{1}); + metaboliteNames = MetData.Properties.VariableNames; + subjectNames = MetData.Properties.RowNames; + for idxMet = 1:length(metabType) + indexMetChange = strcmp(metaboliteNames,metabType{idxMet}); + idxMetChange = find(indexMetChange); + idxSubjRow = find(~cellfun(@isempty,strfind(subjectNames,subjectsPath{idxOfSubj}(1:15)))); + MetChange(idxMet) = MetData{idxSubjRow,idxMetChange}; + end + Data_Corr(idxOfSubj,:) = [AmpChange FWHMChange MetChange]; +end +rowNames = strcat(prefixes, subjects); +columnNames = {'Amp_H2O' 'FWHM_H2O' metabType{1} metabType{2} metabType{3} metabType{4}}; +Data_Corr_PercChange = array2table(Data_Corr,'rowNames',rowNames,'VariableNames',columnNames); + +if exist('excludeSubjects', 'var') & ~isempty(excludeSubjects) + ExpNamePercChange = strcat('Diff_BOLD_Met_', num2str(visualType), BOLDType, MMBType, '_Excluded'); +else + ExpNamePercChange = strcat('ConcDiff_', num2str(visualType), BOLDType, MMBType); +end +ExpNamePercChange = strrep(ExpNamePercChange,'#1','_1'); +eval([ExpNamePercChange '=Data_Corr_PercChange']); +exportFileMatDiff = [OutputFilesPathLocal ,strcat(ExpNamePercChange,'.mat')]; +save(exportFileMatDiff,ExpNamePercChange) + +subjLength = 1; +subjectsCorr = ones(subjLength*10,1); +for i = 1:subjLength + subjectsCorr((1+(i-1)*10):(10+(i-1)*10)) = subjectsCorr((1+(i-1)*10):(10+(i-1)*10)).*i; +end + +for idxMet = 1:length(metabType) + if exist('excludeSubjects') + file2save = strcat('Corr_BOLD_',metabType{idxMet},'_',visualType,BOLDType,MMBType,'_Excluded'); + else + file2save = strcat('Corr_BOLD_',metabType{idxMet},'_',visualType,BOLDType,MMBType); + end + %for FWHM (Water Hz % vs Met a.u. %) + fwhmTab = table(Data_Corr(:,2),Data_Corr(:,idxMet+2),subjectsCorr); + BOLDData_FWHM = table2array(fwhmTab); + %Spearman correlation + [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Spearman'); + % [RHO,PVAL] = corr(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'Type','Pearson'); + %linear regression + fit = fitlm(BOLDData_FWHM(:,2),BOLDData_FWHM(:,1)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fit) + xlabel([char(916), char(metabType{idxMet}), ' / %']) + ylabel([char(916), 'FWHM Water / %']) + title(['Correlation ', char(916), 'FWHM Water & ', char(916), char(metabType{idxMet}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; + text(max(BOLDData_FWHM(:,2))-max(BOLDData_FWHM(:,2))*0.5,min(BOLDData_FWHM(:,1))-min(BOLDData_FWHM(:,1))*0.1,txt) + set(gca, 'FontWeight','bold'); + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); + + fig2saveFWHM = fullfile(OutputFilesPathLocal, strcat(file2save,'_fwhm.fig')); + savefig(fig2saveFWHM) + + %for amplitude (Water a.u. vs Met a.u.) + ampTab = table(Data_Corr(:,1),Data_Corr(:,idxMet+2),subjectsCorr); + BOLDData_amp = table2array(ampTab); + %Spearman correlation + [RHO,PVAL] = corr(BOLDData_amp(:,2),BOLDData_amp(:,1),'Type','Spearman'); + %linear regression + fit = fitlm(BOLDData_amp(:,2),BOLDData_amp(:,1)); + figure + hold on + % plot(BOLDData_FWHM(:,1),BOLDData_FWHM(:,2),'o') + plot(fit) + xlabel([char(916), char(metabType{idxMet}), ' / %']) + ylabel([char(916), 'Amplitude Water / %']) + title(['Correlation ', char(916), 'Amplitude Water & ', char(916), char(metabType{idxMet}), woBaseline], 'Interpreter', 'none') + txt = {['R = ' num2str(RHO)],['p < ' num2str(PVAL)]}; + text((max(BOLDData_amp(:,2))-max(BOLDData_amp(:,2))*0.5),(min(BOLDData_amp(:,1))+min(BOLDData_amp(:,1))*0.05),txt) + set(gca, 'FontWeight','bold'); + set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); + fig2saveAmplitude = fullfile(OutputFilesPathLocal, strcat(file2save,'_amp.fig')); + savefig(fig2saveAmplitude) +end +end + + +function CalcBOLDEffect(subjects,subjectsPath,StimType,visualType,BOLDType,preprocessedFilesPathLocal,... + OutputFilesPathLocal,PeakRange,metabType,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +SelProcValues = SelectedProcessingValues(); +fwhmArray = zeros(1,length(StimType)); +amplitudeArray = zeros(1,length(StimType)); +for idxSubject = 1:length(subjects) + for nStimType = 1:length(StimType) + impName = strcat(subjects{idxSubject},'_',StimType{nStimType},BOLDType,woBaseline); + impFileMat = strcat(preprocessedFilesPathLocal{idxSubject},impName,'.mat'); + dataPerBlock = load(impFileMat); + fields = fieldnames(dataPerBlock); + dataPerBlock = dataPerBlock.(fields{1}); + SelProcValues.PeakRange = PeakRange; %ppm + currentValue = SelProcValues.PeakRange; + currentValue = convertPPMtoIndex(dataPerBlock, currentValue,1); + currentValue =[find(currentValue==1,1,'first') find(currentValue==1,1,'last')]; + SelProcValues.PeakRange = [currentValue(1) currentValue(2)]; + bandwidth = dataPerBlock.Parameter.Headers.Bandwidth_Hz; + datafid = squeeze(dataPerBlock.Data{1}); + peakRange = get(SelProcValues, 'PeakRange'); + + if strcmp(metabType(1:2),'Wa') + datafid = datafid(:,2); + dataSpecReal = real(fftshift(fft(datafid))); + else + datafid = datafid(:,1); + dataSpecReal = real(fftshift(fft(datafid))); + end + + fwhmArray(1,nStimType) = linewidth(datafid, SelProcValues, bandwidth); + amplitudeArray(1,nStimType) = max(abs(dataSpecReal(peakRange(1):peakRange(2)))); + end + file2save = strrep(strcat(visualType,BOLDType,woBaseline,'_WaterBOLD'),'#','_'); + BOLD.fwhm = fwhmArray; BOLD.amplitude = amplitudeArray; + eval([file2save '= BOLD']); + exportFileMat = [OutputFilesPathLocal, strcat(subjectsPath{idxSubject},'/',file2save,'.mat')]; + save(exportFileMat,file2save) +end +end \ No newline at end of file diff --git a/fMRS_processing/DoMARSSMetabolitesLineBroadening.m b/fMRS_processing/DoMARSSMetabolitesLineBroadening.m index ebb02e4..b812224 100644 --- a/fMRS_processing/DoMARSSMetabolitesLineBroadening.m +++ b/fMRS_processing/DoMARSSMetabolitesLineBroadening.m @@ -1,9 +1,9 @@ function DoMARSSMetabolitesLineBroadening() -% filepath = 'D:\CODE\MARSS\2020-02-18\sLASER_15x18x20_120V_Tx2.4ppm_Water\RawBasis_for_MARSSinput'; -filepath = 'D:\PAPER\1H_fMRS\Data\Basis_sets\MARSS_Output\sLASER_15x18x20_120V_Tx2.4ppm\RawBasis_for_MARSSinput'; +filepath = 'D:\PAPER\1H_fMRS\Data\Basis_sets\Basis_sets_15x18x20_TE24ms_URef120V_Ref24ppm_LineBroadened'; +% filepath = 'D:\PAPER\1H_fMRS\Data\Basis_sets\MARSS_Output\sLASER_15x18x20_120V_Tx2.4ppm\RawBasis_for_MARSSinput'; -metaboliteFileNames = {'sI'}; +metaboliteFileNames = {'GradEcho'}; plotBasis = true; @@ -34,19 +34,19 @@ for indexMetabolite = 1 : length(metaboliteFileNames) L = -1; %linewidth in Hz, L positive: line broadening, L negative: resolution enhancement W = exp(-t'*pi*L).*exp(- t'.^2*(Fgau)^2); newData = oldData.*W; - +newData = oldData; addSinglet = true; dwellTimeMs = dwellTime * 1e3; % filePathExport = [filepath '\Basis_sets_LineBroadened\']; - filePathExport = [filepath '\Basis_sets_LineBroadened_negative\']; + filePathExport = [filepath '\Basis_sets_LineBroadened\']; mkdir(filePathExport) ExportLCModelBasis((newData/100)', dwellTimeMs, scanFrequency, filePathExport, ... filtered_metabolite_name, metaboliteFileNames{indexMetabolite}, addSinglet, ... - false, 4.7, 0.5,'Yes',24,'jd_semiLASER'); + false, 4.7, 3000,'Yes',24,'jd_semiLASER'); bw = linspace(-bandwidth/2,bandwidth/2,length(newData)); ppmVector = bw/(scanFrequency) + 4.7; diff --git a/fMRS_processing/Statistics.m b/fMRS_processing/Statistics.m index d075a5f..796ba60 100644 --- a/fMRS_processing/Statistics.m +++ b/fMRS_processing/Statistics.m @@ -7,7 +7,7 @@ clear; clc; close all; pathName = 'fMRS data path'; sampleCriteria = {'Output'}; [localFilePathBase] = pathToDataFolder(pathName, sampleCriteria); -StimType = {'RestON', 'RestOFF'}; %'StimON', 'StimOFF', 'RestON', 'RestOFF' +StimType = {'StimON', 'StimOFF'}; %'StimON', 'StimOFF', 'RestON', 'RestOFF' if ~isempty(strfind(StimType{1},'Stim')) visualType = 'Stim'; elseif ~isempty(strfind(StimType{1},'Rest')) @@ -15,8 +15,8 @@ elseif ~isempty(strfind(StimType{1},'Rest')) else error('StimType needs to be Stim or Rest'); end -BOLDType = '_withBOLDCorr64_1'; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _woBOLDCorr64_1, _withBOLDCorr64, _withBOLDCorr64_1 -MMBType = '_MMBSummed'; %_MMBIndFiltered, _MMBSummed, _MMBInd, _MMBSimulated, _MMBSummed_v2 +BOLDType = '_woBOLDCorr128'; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _woBOLDCorr64_1, _withBOLDCorr64, _withBOLDCorr64_1 +MMBType = '_MMBSummed_v2'; %_MMBIndFiltered, _MMBSummed, _MMBInd, _MMBSimulated, _MMBSummed_v2 % subjects = {'2823';}; subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... '4085';'3333';'4012';'4085';'6524'}; @@ -26,12 +26,16 @@ prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; excludeSubjects = {'5166';'9810';'5269'}; if strcmp(MMBType,'_MMBSummed') - excludeMet = {'Glc';'NAA_NAAG';'Glu_Gln';'Glyc';'mI_Glyc';'PCh'}; %for v1 + excludeMet = {'NAA';'GABA';'Gln';'Glyc';'GSH';'mI';'NAAG';'PCh';'GPC';'PE';'Scyllo';'Tau';'Glc';'NAA_NAAG';'Glu_Gln';'Glyc';'mI_Glyc';'PCh'}; %for v1 elseif strcmp(MMBType,'_MMBSummed_v2') - excludeMet = {'Glc';'NAA_NAAG';'Glu_Gln'}; %for v2 + excludeMet = {'NAA';'Asc';'GABA';'Glc';'Gln';'GSH';'mI';'NAAG';'tCh';'PE';'Scyllo';'Tau';'NAA_NAAG';'Glu_Gln'}; %for v2 end %% file paths setup -LCModelOutputPath = [localFilePathBase, 'Output/']; +if ~isempty(strfind(MMBType,'_v2')) + LCModelOutputPath = [localFilePathBase, 'Output_v2_MMBSummed/']; +else + LCModelOutputPath = [localFilePathBase, 'Output/']; +end ExpName = strcat('LCModelFit_', num2str(visualType), BOLDType, MMBType); exportFileMat = [LCModelOutputPath ,strcat(ExpName,'.mat')]; @@ -64,32 +68,72 @@ PercDiff = 100./OFF.*ON-100; PercDiffMean = mean(PercDiff); PercDiffStd = std(PercDiff); -% two-sided Wilcoxon signed rank test -% for indexOfMetabolite = 1:length(metaboliteNames) -% if isempty(find(~isnan(PercDiff(:,indexOfMetabolite)))) -% p(indexOfMetabolite) = NaN; -% h(indexOfMetabolite) = 0; -% else -% [p(indexOfMetabolite),h(indexOfMetabolite)] = signrank(PercDiff(:,indexOfMetabolite)); -% end -% end - -%paired two-tailed t-test +%% two-sided Wilcoxon signed rank test +for indexOfMetabolite = 1:length(metaboliteNames) + if isempty(find(~isnan(PercDiff(:,indexOfMetabolite)))) + p_Wilc(indexOfMetabolite) = NaN; + h_Wilc(indexOfMetabolite) = 0; + else + [p_Wilc(indexOfMetabolite),h_Wilc(indexOfMetabolite)] = signrank(PercDiff(:,indexOfMetabolite)); + end +end + +%check histogram of p-values +edges = linspace(0,1,length(p_Wilc)); +histogram(p_Wilc,edges) + +%Benjamini-Hochberg correction for multiple testing +[h_BH_Wilc, crit_p_Wilc, adj_ci_cvrg_Wilc, adj_p_Wilc]=fdr_bh(p_Wilc,0.05,'pdep','yes'); +%h=1: reject H0, h=0: H0 not rejected +%crit_p: max p-value that is significant +%adj_ci_cvrg: BH adjusted confidence interval coverage +%adj_p: N pj / j, all adjusted p-values less than or equal to q are significant + + +if exist('excludeMet') + [~,n] = size(metaboliteNames); + m = length(excludeMet); + nstep = 1; + for j = 1:m + for i = 1:n + xx = strcmp(metaboliteNames(1,i),excludeMet{j}); +% xx = find(~cellfun(@isempty,strcmp(metaboliteNames(1,i),excludeMet{j}))); +% if ~isempty(xx) + if xx + excludeMetIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + pExclMet_Wilc = p_Wilc; + pExclMet_Wilc(excludeMetIdx) = []; + [h_BH_ExclMet_Wilc, crit_p_ExclMet_Wilc, adj_ci_cvrg_ExclMet_Wilc, adj_p_ExclMet_Wilc]=fdr_bh(pExclMet_Wilc,0.05,'pdep','yes'); + temph = ones(1,length(h_Wilc))*NaN; temp_p = ones(1,length(p_Wilc))*NaN; tempidx = [0 sort(excludeMetIdx)]; nstep = 1; + for j = 1:length(tempidx)-1 + temp_p((tempidx(j)+1):(tempidx(j+1)-1)) = adj_p_ExclMet_Wilc((tempidx(j)+2-nstep):(tempidx(j+1)-nstep)); + temph((tempidx(j)+1):(tempidx(j+1)-1)) = h_BH_ExclMet_Wilc((tempidx(j)+2-nstep):(tempidx(j+1)-nstep)); + nstep = nstep + 1; + end + h_BH_ExclMet_Wilc = temph; + adj_p_ExclMet_Wilc = temp_p; +end + +%% paired two-tailed t-test (data need to be normally distributed, which they aren't here! -> use nonparametric Wilcoxon) for indexOfMetabolite = 1:length(metaboliteNames) if isempty(find(~isnan(PercDiff(:,indexOfMetabolite)))) - h(indexOfMetabolite) = NaN; - p(indexOfMetabolite) = 0; + h_ttest(indexOfMetabolite) = NaN; + p_ttest(indexOfMetabolite) = 0; else - [h(indexOfMetabolite),p(indexOfMetabolite)] = ttest(PercDiff(:,indexOfMetabolite)); + [h_ttest(indexOfMetabolite),p_ttest(indexOfMetabolite)] = ttest(PercDiff(:,indexOfMetabolite)); end end %check histogram of p-values -edges = linspace(0,1,length(p)); -histogram(p,edges) +edges = linspace(0,1,length(p_ttest)); +histogram(p_ttest,edges) %Benjamini-Hochberg correction for multiple testing -[h_BH, crit_p, adj_ci_cvrg, adj_p]=fdr_bh(p,0.05,'pdep','yes'); +[h_BH_ttest, crit_p_ttest, adj_ci_cvrg_ttest, adj_p_ttest]=fdr_bh(p_ttest,0.05,'pdep','yes'); %h=1: reject H0, h=0: H0 not rejected %crit_p: max p-value that is significant %adj_ci_cvrg: BH adjusted confidence interval coverage @@ -111,20 +155,21 @@ if exist('excludeMet') end end end - pExclMet = p; - pExclMet(excludeMetIdx) = []; - [h_BH_ExclMet, crit_p_ExclMet, adj_ci_cvrg_ExclMet, adj_p_ExclMet]=fdr_bh(pExclMet,0.05,'pdep','yes'); - temph = ones(1,length(h))*NaN; temp_p = ones(1,length(p))*NaN; tempidx = [0 sort(excludeMetIdx)]; nstep = 1; + pExclMet_ttest = p_ttest; + pExclMet_ttest(excludeMetIdx) = []; + [h_BH_ExclMet_ttest, crit_p_ExclMet_ttest, adj_ci_cvrg_ExclMet_ttest, adj_p_ExclMet_ttest]=fdr_bh(pExclMet_ttest,0.05,'pdep','yes'); + temph = ones(1,length(h_ttest))*NaN; temp_p = ones(1,length(p_ttest))*NaN; tempidx = [0 sort(excludeMetIdx)]; nstep = 1; for j = 1:length(tempidx)-1 - temp_p((tempidx(j)+1):(tempidx(j+1)-1)) = adj_p_ExclMet((tempidx(j)+2-nstep):(tempidx(j+1)-nstep)); - temph((tempidx(j)+1):(tempidx(j+1)-1)) = h_BH_ExclMet((tempidx(j)+2-nstep):(tempidx(j+1)-nstep)); + temp_p((tempidx(j)+1):(tempidx(j+1)-1)) = adj_p_ExclMet_ttest((tempidx(j)+2-nstep):(tempidx(j+1)-nstep)); + temph((tempidx(j)+1):(tempidx(j+1)-1)) = h_BH_ExclMet_ttest((tempidx(j)+2-nstep):(tempidx(j+1)-nstep)); nstep = nstep + 1; end - h_BH_ExclMet = temph; - adj_p_ExclMet = temp_p; + h_BH_ExclMet_ttest = temph; + adj_p_ExclMet_ttest = temp_p; end +%% save data in table if exist('excludeSubjects') m = length(excludeSubjects); for k = 1:m @@ -136,9 +181,9 @@ end rowNames = strcat(prefixes, subjects); % rowNames = [rowNames; 'Mean'; 'Std'; 'p-Value'; 'h-Value']; if exist ('excludeMet') - rowNames = [rowNames; 'Mean'; 'Std'; 'p-Value'; 'h-Value'; 'p_BH'; 'h_BH'; 'p_BH_Excl'; 'h_BH_Excl']; + rowNames = [rowNames; 'Mean'; 'Std'; 'p-Value_Wilc'; 'h-Value_Wilc'; 'p_BH_Wilc'; 'h_BH_Wilc'; 'p_BH_Excl_Wilc'; 'h_BH_Excl_Wilc'; 'p-Value_ttest'; 'h-Value_ttest'; 'p_BH_ttest'; 'h_BH_ttest'; 'p_BH_Excl_ttest'; 'h_BH_Excl_ttest']; else - rowNames = [rowNames; 'Mean'; 'Std'; 'p-Value'; 'h-Value'; 'p_BH'; 'h_BH']; + rowNames = [rowNames; 'Mean'; 'Std'; 'p-Value_Wilc'; 'h-Value_Wilc'; 'p_BH_Wilc'; 'h_BH_Wilc'; 'p-Value_ttest'; 'h-Value_ttest'; 'p_BH_ttest'; 'h_BH_ttest']; end if exist('excludeSubjects') ExpNameDiff = strcat('ConcDiff_', num2str(visualType), BOLDType, MMBType, '_Excluded'); @@ -146,14 +191,15 @@ else ExpNameDiff = strcat('ConcDiff_', num2str(visualType), BOLDType, MMBType); end if exist ('excludeMet') - ConcentrationsDiff_xx = array2table([PercDiff; PercDiffMean; PercDiffStd; p; h; adj_p; h_BH; adj_p_ExclMet; h_BH_ExclMet],'rowNames',rowNames,'VariableNames',metaboliteNames); + ConcentrationsDiff_xx = array2table([PercDiff; PercDiffMean; PercDiffStd; p_Wilc; h_Wilc; adj_p_Wilc; h_BH_Wilc; adj_p_ExclMet_Wilc; h_BH_ExclMet_Wilc; p_ttest; h_ttest; adj_p_ttest; h_BH_ttest; adj_p_ExclMet_ttest; h_BH_ExclMet_ttest],'rowNames',rowNames,'VariableNames',metaboliteNames); else - ConcentrationsDiff_xx = array2table([PercDiff; PercDiffMean; PercDiffStd; p; h; adj_p; h_BH],'rowNames',rowNames,'VariableNames',metaboliteNames); + ConcentrationsDiff_xx = array2table([PercDiff; PercDiffMean; PercDiffStd; p_Wilc; h_Wilc; adj_p_Wilc; h_BH_Wilc; p_ttest; h_ttest; adj_p_ttest; h_BH_ttest],'rowNames',rowNames,'VariableNames',metaboliteNames); end eval([ExpNameDiff '=ConcentrationsDiff_xx']); exportFileMatDiff = ['D:\PAPER\1H_fMRS\Statistics\' ,strcat(ExpNameDiff,'.mat')]; save(exportFileMatDiff,ExpNameDiff) +close all %% plot concentrations mean and std % y = table2array(ConcDiff_Stim_withBOLDCorr64_MMBSummed(14,[1:4,6:7,9:12,14:17])); % x = 1:14; diff --git a/fMRS_processing/createLCModelConfigfMRS.m b/fMRS_processing/createLCModelConfigfMRS.m index 37c9b57..c2195ac 100644 --- a/fMRS_processing/createLCModelConfigfMRS.m +++ b/fMRS_processing/createLCModelConfigfMRS.m @@ -1,6 +1,7 @@ function outputFile = createLCModelConfigfMRS(downField_MM_Met, controlFilesPath, outputControlFilesPath, defaultControlFile, ... currentfMRS, defaultfMRS, defaultLCModelUser, currentLCModelUser, spectrumFileName, defaultSpectrum,... - waterRefFileName, defaultWaterRef, subjectsPath, defaultSubjectsPath, subjectID, defaultSubject, MMBType, defaultMMB, fMRSDataSuff) + waterRefFileName, defaultWaterRef, subjectsPath, defaultSubjectsPath, subjectID, defaultSubject, MMBType,... + defaultMMB, fMRSDataSuff) % Intro comments need to be rewritten % Creates the control files for the TE series, given a default control file. % the newly generated files will be placed in the same path as indicated by @@ -17,7 +18,7 @@ fitSettingsDefaultFileID = fopen([controlFilesPath defaultControlFile], 'r'); mkdir(outputControlFilesPath); outputFile = strcat(outputControlFilesPath, 'fitsettings_fMRS_', spectrumFileName, controlFileSuffix); -if exist('fMRSDataSuff', 'var') +if exist('fMRSDataSuff', 'var') & ~isempty(fMRSDataSuff) spectrumFileName = strcat(fMRSDataSuff, spectrumFileName); end @@ -27,10 +28,23 @@ display(outputFile); while(~feof(fitSettingsDefaultFileID)) s = fgetl(fitSettingsDefaultFileID); k = strfind(s,'FILRAW'); - currentfMRSextended = strcat(currentfMRS, MMBType); + currentfMRSextended = strcat(currentfMRS, MMBType); + if strfind(spectrumFileName,'_woBaseline') + if strfind(MMBType,'v2') + currentfMRSNew = strcat(currentfMRS,'_v2_woBaseline'); + else + currentfMRSNew = strcat(currentfMRS,'_woBaseline'); + end + else +% if strfind(MMBType,'v2') +% currentfMRSNew = strcat(currentfMRS,'_v2'); +% else + currentfMRSNew = currentfMRS; +% end + end if ~isempty(k) s = strrep(s, defaultLCModelUser, currentLCModelUser); - s = strrep(s, defaultfMRS, currentfMRS); + s = strrep(s, defaultfMRS, currentfMRSNew); s = strrep(s, defaultSubjectsPath, subjectsPath); s = strrep(s, defaultSpectrum, spectrumFileName); s = strrep(s, defaultWaterRef, waterRefFileName); diff --git a/fMRS_processing/createLCModelConfigfMRSDiff.m b/fMRS_processing/createLCModelConfigfMRSDiff.m index fc73058..c540f98 100644 --- a/fMRS_processing/createLCModelConfigfMRSDiff.m +++ b/fMRS_processing/createLCModelConfigfMRSDiff.m @@ -21,6 +21,12 @@ if defaultControlFile(1:29) == 'fitsettings_fMRS_XXXX_StimOFF' % else outputFile = strcat(outputControlFilesPath, 'fitsettings_fMRS_', spectrumFileName, controlFileSuffix); % end +elseif defaultControlFile(1:32) == 'fitsettings_fMRS_v2_XXXX_StimOFF' + % if ~isempty(strfind(MMBType,'_Excluded')) + % outputFile = strcat(outputControlFilesPath, 'fitsettings_fMRS_', spectrumFileName, '_Excluded', controlFileSuffix); + % else + outputFile = strcat(outputControlFilesPath, 'fitsettings_fMRS_', spectrumFileName, controlFileSuffix); + % end else outputFile = strcat(outputControlFilesPath, defaultControlFile); outputFile = strrep(outputFile, 'Difference_XXXX_StimOFF', spectrumFileName); diff --git a/fMRS_processing/doFitting_fMRS_Met.m b/fMRS_processing/doFitting_fMRS_Met.m index 1869158..5fcfc55 100644 --- a/fMRS_processing/doFitting_fMRS_Met.m +++ b/fMRS_processing/doFitting_fMRS_Met.m @@ -16,14 +16,14 @@ elseif ~isempty(strfind(StimType{1},'Rest')) else error('StimType needs to be Stim or Rest'); end -BOLDType = {'_withBOLDCorr64#1'}; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _woBOLDCorr64#1, _withBOLDCorr64, _withBOLDCorr64#1 +BOLDType = {'_withBOLDCorr128'}; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _woBOLDCorr64#1, _withBOLDCorr64, _withBOLDCorr64#1 orderFMRS = strcat(StimType,BOLDType);% % orderFMRS = {'StimON_woBOLDCorr128', 'StimOFF_woBOLDCorr128'}; MMBType = '_MMBSummed'; %_MMBIndFiltered, _MMBSummed, _MMBInd, _MMBSimulated -subjects = {'6524';}; +subjects = {'3333';}; % subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... % '4085';'3333';'4012';'4085';'6524'}; -prefixes = {'2020-03-13_';}; +prefixes = {'2020-03-10_';}; % prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... % '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... % '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; @@ -61,23 +61,23 @@ subjectsLCModelOutputPath = strcat(LCModelOutputPath, subjectsPath, '/'); %% process fMRS data and save .RAW file dataPath = strcat(localFilePathBase,subjectsPath, '/'); -% for i = 1:length(dataPath) -% currentFolder = num2str(cell2mat(dataPath(i))); -% cd (currentFolder); -% subFolderName = dir(dataPath{i}); -% if ~isempty(strfind(StimType{1},'Stim')) -% dataFile = dir('*Stim*.dat'); -% elseif ~isempty(strfind(StimType{1},'Rest')) -% dataFile = dir('*Rest*.dat'); -% else -% error('StimType needs to be Stim or Rest'); -% end -% % nBlocks = 5; +for i = 1:length(dataPath) + currentFolder = num2str(cell2mat(dataPath(i))); + cd (currentFolder); + subFolderName = dir(dataPath{i}); + if ~isempty(strfind(StimType{1},'Stim')) + dataFile = dir('*Stim*.dat'); + elseif ~isempty(strfind(StimType{1},'Rest')) + dataFile = dir('*Rest*.dat'); + else + error('StimType needs to be Stim or Rest'); + end + nBlocks = 5; % nBlocks = 10; -% PCSteps = 16; -% reconstruct_1H_fMRS(currentFolder,dataFile.name,1,1,nBlocks,false,PCSteps,[],1,visualType); %currentFolder, fid_id, isMC, isInVivo, nBlocks, nOnAverages, PCSteps, weights, saveResults -% close all; cd ..; -% end + PCSteps = 16; + reconstruct_1H_fMRS(currentFolder,dataFile.name,1,1,nBlocks,false,PCSteps,[],1,visualType); %currentFolder, fid_id, isMC, isInVivo, nBlocks, nOnAverages, PCSteps, weights, saveResults + close all; cd ..; +end %% basic configurations % LCModelTableFits = strcat(outputFileNameBase, orderFMRS, extensionTable); diff --git a/fMRS_processing/doFitting_fMRS_Met_Summed.m b/fMRS_processing/doFitting_fMRS_Met_Summed.m index 4a97b8c..6796666 100644 --- a/fMRS_processing/doFitting_fMRS_Met_Summed.m +++ b/fMRS_processing/doFitting_fMRS_Met_Summed.m @@ -1,10 +1,13 @@ function doFitting_fMRS_Met_Summed() +%check StimType, BOLDType, MMBType + clear; clc; close all; -pathName = 'fMRS data path'; +% pathName = 'fMRS data path'; %first version, no modulus correction for gradient sideband removal +pathName = 'fMRS data path modulus'; %second version, with modulus correction for gradient sideband, only UF can be processed sampleCriteria = {'Summed_fMRSData'}; [localFilePathBase] = pathToDataFolder(pathName, sampleCriteria); -StimType = {'RestON', 'RestOFF'}; %'RestON', 'RestOFF', 'StimON', 'StimOFF' +StimType = {'StimON', 'StimOFF'}; %'RestON', 'RestOFF', 'StimON', 'StimOFF' if ~isempty(strfind(StimType{1},'Stim')) visualType = 'Stim'; elseif ~isempty(strfind(StimType{1},'Rest')) @@ -12,9 +15,9 @@ elseif ~isempty(strfind(StimType{1},'Rest')) else error('StimType needs to be Stim or Rest'); end -BOLDType = {'_woBOLDCorr64#1'}; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _withBOLDCorr64, _woBOLDCorr64#1 +BOLDType = {'_woBOLDCorr128'}; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _withBOLDCorr64, _woBOLDCorr64#1 orderFMRS = strcat(StimType,BOLDType); -MMBType = '_MMBSummed'; %only usefull with summed MMB +MMBType = '_MMBSummed_v2'; %_MMBSummed_v2, only useful with summed MMB subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... '4085';'3333';'4012';'4085';'6524'}; prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... @@ -50,13 +53,21 @@ extensionMat = '.mat'; defaultfMRS = 'StimOFF'; defaultSubject = 'XXXX'; defaultSubjectsPath = 'YYYY'; -defaultMMB = '_MMBSummed'; +if ~isempty(strfind(MMBType,'_v2')) + defaultMMB = '_MMBSummed_v2'; +else + defaultMMB = '_MMBSummed'; +end defaultLCModelUser = 'jdorst'; outputFileNameBase_OFF = strcat(defaultSubject, '_', num2str(visualType), 'OFF', BOLDType{1}); outputFileNameBase_ON = strcat(defaultSubject, '_', num2str(visualType), 'ON', BOLDType{1}); outputFileNameBase_WRef = strcat(defaultSubject, '_WRef'); -controlFilesBase = 'fitsettings_fMRS_XXXX_'; +if ~isempty(strfind(MMBType,'_v2')) + controlFilesBase = 'fitsettings_fMRS_v2_XXXX_'; +else + controlFilesBase = 'fitsettings_fMRS_XXXX_'; +end % controlFilesBaseDiff = 'fitsettings_fMRS_Difference_XXXX_'; % if visualType == 'Rest' % controlFilesBaseDiff = 'fitsettings+_fMRS_Difference_XXXX_'; @@ -78,7 +89,15 @@ numberOfSubjects = length(subjects); controlFilesPathRemote = '/Desktop/1H_fMRS/LCModelConfig/'; controlFilesPathLocal = [localFilePathBase, 'LCModelConfig/']; LCModelOutputFilesPathRemote = '/Desktop/1H_fMRS/Output/'; -LCModelOutputPath = [localFilePathBase, 'Output/']; +if ~isempty(strfind(MMBType,'_v2')) + if ~isempty(strfind(localFilePathBase,'Modulus')) + LCModelOutputPath = [localFilePathBase, 'Output_v2_MMBSummed_Modulus/']; + else + LCModelOutputPath = [localFilePathBase, 'Output_v2_MMBSummed/']; + end +else + LCModelOutputPath = [localFilePathBase, 'Output/']; +end defaultControlFile = strcat(controlFilesBase, defaultfMRS, controlFilesBaseSuffix); defaultControlFileDiff = strcat(controlFilesBaseDiff, defaultfMRS, controlFilesBaseSuffix); @@ -92,7 +111,7 @@ summedLCModelOutputFilesRemote = strcat(LCModelOutputFilesPathRemote, summedPath summedLCModelOutputPath = strcat(LCModelOutputPath, summedPath, '/'); %% do the LCModel fitting -LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); +% LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); %% sum fMRS spectra of all volunteers, weighted with water fit (need to run doFitting_fMRS_Water.m first) @@ -141,15 +160,23 @@ exportFileMatOFF = [fMRSData_Summed_Path, strcat(fMRSData_Summed_OFF_BOLD,'.mat' load(strrep(strcat(currentfMRSDataPath, '\',outputFileNameBase_OFF,extensionMat),defaultSubject,subjects{indexCurrentSubject})); fMRSData_Summed_OFF_MR_spectroS = aOFF; fMRSData_Summed_OFF_MR_spectroS.Data{1} = fMRSData_Summed_OFF; -fMRSData_Summed_OFF_MR_spectroS.ExportLcmRaw(fMRSData_Summed_Path, fMRSData_Summed_OFF_BOLD, 'Yes', 'Yes'); save(exportFileMatOFF,'fMRSData_Summed_OFF_MR_spectroS') -% % % % LCModelCallerInstance.CopyDataToRemote(fMRSData_Summed_Path, LCModelfMRSDataPathRemote, strcat(fMRSData_Summed_OFF_BOLD,extensionRAW)) +if ~isempty(strfind(localFilePathBase,'Modulus')) + fMRSData_Summed_OFF = real(fMRSData_Summed_OFF).*2; + fMRSData_Summed_OFF_MR_spectroS.Data{1} = fMRSData_Summed_OFF; +end +fMRSData_Summed_OFF_MR_spectroS.ExportLcmRaw(fMRSData_Summed_Path, fMRSData_Summed_OFF_BOLD, 'Yes', 'Yes'); + load(strrep(strcat(currentfMRSDataPath, '\',outputFileNameBase_ON,extensionMat),defaultSubject,subjects{indexCurrentSubject})); fMRSData_Summed_ON_MR_spectroS = aON; fMRSData_Summed_ON_MR_spectroS.Data{1} = fMRSData_Summed_ON; -fMRSData_Summed_ON_MR_spectroS.ExportLcmRaw(fMRSData_Summed_Path, fMRSData_Summed_ON_BOLD, 'Yes', 'Yes'); save(exportFileMatON,'fMRSData_Summed_ON_MR_spectroS') -% % % % LCModelCallerInstance.CopyDataToRemote(fMRSData_Summed_Path, LCModelfMRSDataPathRemote, strcat(fMRSData_Summed_ON_BOLD,extensionRAW)) +if ~isempty(strfind(localFilePathBase,'Modulus')) + fMRSData_Summed_ON = real(fMRSData_Summed_ON).*2; + fMRSData_Summed_ON_MR_spectroS.Data{1} = fMRSData_Summed_ON; +end +fMRSData_Summed_ON_MR_spectroS.ExportLcmRaw(fMRSData_Summed_Path, fMRSData_Summed_ON_BOLD, 'Yes', 'Yes'); + %% create and save difference spectrum from summed indiviually BOLD corrected spectra fMRSData_Summed_ON = squeeze(fMRSData_Summed_ON); @@ -229,44 +256,6 @@ if ~isempty(strfind(BOLDType{1},'woBOLDCorr')) fMRSData_Summed_noBOLD.Parameter.ReconFlags.isfMRSDifference = 0; fMRSData_Summed_noBOLD = fMRSData_Summed_noBOLD.fMRSDifference; - % timePoints = size(fMRSData_Summed_noBOLD.Data{1},1); - % dwellTime = fMRSData_Summed_noBOLD.Parameter.Headers.DwellTimeSig_ns * 1e-9; %in secs - % timeVector = linspace(0,(timePoints-1)*dwellTime,timePoints)'; - % plot(real(fftshift(fft(data(:,1,1).*exp(-pi*0.3*timeVector).*exp(1i*2*pi*0.09*timeVector))))-real(fftshift(fft(data(:,1,2))))) - - figure; hold on; - data = squeeze(fMRSData_Summed_noBOLD.Data{1}); - ppmVector = fMRSData_Summed_noBOLD.getPpmVector; - plot(ppmVector,real(fftshift(fft(data(:,1,1))))) - plot(ppmVector,real(fftshift(fft(data(:,1,2))))) - plot(ppmVector,real(fftshift(fft(data(:,1,3))))) - set(gca, 'XDir','reverse') - xlim([0.5 4.5]); legend('On','Off','Residual') - - if exist('excludeSubjects') - fig2save_fMRSData_Summed_noBOLD = fullfile(fMRSData_Summed_Path, strcat('Diff_',visualType,strrep(BOLDType{1},'#','_'),MMBType,'_Excluded_BOLDafterSum.fig')); - else - fig2save_fMRSData_Summed_noBOLD = fullfile(fMRSData_Summed_Path, strcat('Diff_',visualType,strrep(BOLDType{1},'#','_'),MMBType,'_BOLDafterSum.fig')); - end - savefig(fig2save_fMRSData_Summed_noBOLD) - close all; - - %save only residual - temp = squeeze(fMRSData_Summed_noBOLD.Data{1}); - temp = temp(:,:,3); - fMRSData_Difference_BOLDafterSummation_MRSpectro = fMRSData_Summed_noBOLD; - fMRSData_Difference_BOLDafterSummation_MRSpectro.Data{1} = permute(temp,[1 3 4 5 6 7 8 9 2]); - if exist('excludeSubjects') - fMRSData_Difference_BOLDafterSummation = strcat('Diff_',visualType,strrep(BOLDType{1},'#','_'),MMBType,'_Excluded_BOLDafterSum'); - else - fMRSData_Difference_BOLDafterSummation = strcat('Diff_',visualType,strrep(BOLDType{1},'#','_'),MMBType,'_BOLDafterSum'); - end - eval([fMRSData_Difference_BOLDafterSummation '=fig2save_fMRSData_Summed_noBOLD']); - exportFileMatDifferenceBOLDafterSummation = [fMRSData_Summed_Path, strcat(fMRSData_Difference_BOLDafterSummation, '.mat')]; - save(exportFileMatDifferenceBOLDafterSummation,'fMRSData_Difference_BOLDafterSummation_MRSpectro') - fMRSData_Difference_BOLDafterSummation_MRSpectro.ExportLcmRaw(fMRSData_Summed_Path, fMRSData_Difference_BOLDafterSummation, 'Yes', 'Yes'); - clear temp - %save ON OFF %ON temp = squeeze(fMRSData_Summed_noBOLD.Data{1}); @@ -280,7 +269,11 @@ if ~isempty(strfind(BOLDType{1},'woBOLDCorr')) end eval([fMRSData_Summed_ON_BOLDafterSummation '=fMRSData_Summed_ON_afterSummation']); exportFileMatON = [fMRSData_Summed_Path, strcat(fMRSData_Summed_ON_BOLDafterSummation,'.mat')]; - save(exportFileMatON,'fMRSData_Summed_ON_BOLDafterSummation') + save(exportFileMatON,'fMRSData_Summed_ON_afterSummation') + if ~isempty(strfind(localFilePathBase,'Modulus')) + temp = real(temp).*2; + fMRSData_Summed_ON_afterSummation.Data{1} = temp; + end fMRSData_Summed_ON_afterSummation.ExportLcmRaw(fMRSData_Summed_Path, fMRSData_Summed_ON_BOLDafterSummation, 'Yes', 'Yes'); %OFF temp = squeeze(fMRSData_Summed_noBOLD.Data{1}); @@ -294,9 +287,60 @@ if ~isempty(strfind(BOLDType{1},'woBOLDCorr')) end eval([fMRSData_Summed_OFF_BOLDafterSummation '=fMRSData_Summed_OFF_afterSummation']); exportFileMatON = [fMRSData_Summed_Path, strcat(fMRSData_Summed_OFF_BOLDafterSummation,'.mat')]; - save(exportFileMatON,'fMRSData_Summed_OFF_BOLDafterSummation') + save(exportFileMatON,'fMRSData_Summed_OFF_afterSummation') + if ~isempty(strfind(localFilePathBase,'Modulus')) + temp = real(temp).*2; + fMRSData_Summed_OFF_afterSummation.Data{1} = temp; + end fMRSData_Summed_OFF_afterSummation.ExportLcmRaw(fMRSData_Summed_Path, fMRSData_Summed_OFF_BOLDafterSummation, 'Yes', 'Yes'); + % create and save difference spectrum + %save only residual + temp = squeeze(fMRSData_Summed_noBOLD.Data{1}); + temp = temp(:,:,3); + fMRSData_Difference_BOLDafterSummation_MRSpectro = fMRSData_Summed_noBOLD; + fMRSData_Difference_BOLDafterSummation_MRSpectro.Data{1} = permute(temp,[1 3 4 5 6 7 8 9 2]); + if exist('excludeSubjects') + fMRSData_Difference_BOLDafterSummation = strcat('Diff_',visualType,strrep(BOLDType{1},'#','_'),MMBType,'_Excluded_BOLDafterSum'); + fig2save_fMRSData_Summed_noBOLD = fullfile(fMRSData_Summed_Path, strcat('Diff_',visualType,strrep(BOLDType{1},'#','_'),MMBType,'_Excluded_BOLDafterSum.fig')); + else + fMRSData_Difference_BOLDafterSummation = strcat('Diff_',visualType,strrep(BOLDType{1},'#','_'),MMBType,'_BOLDafterSum'); + fig2save_fMRSData_Summed_noBOLD = fullfile(fMRSData_Summed_Path, strcat('Diff_',visualType,strrep(BOLDType{1},'#','_'),MMBType,'_BOLDafterSum.fig')); + end + eval([fMRSData_Difference_BOLDafterSummation '=fig2save_fMRSData_Summed_noBOLD']); + exportFileMatDifferenceBOLDafterSummation = [fMRSData_Summed_Path, strcat(fMRSData_Difference_BOLDafterSummation, '.mat')]; + save(exportFileMatDifferenceBOLDafterSummation,'fMRSData_Difference_BOLDafterSummation_MRSpectro') + if ~isempty(strfind(localFilePathBase,'Modulus')) + temp = real(temp).*2; + fMRSData_Difference_BOLDafterSummation_MRSpectro.Data{1} = temp; + end + fMRSData_Difference_BOLDafterSummation_MRSpectro.ExportLcmRaw(fMRSData_Summed_Path, fMRSData_Difference_BOLDafterSummation, 'Yes', 'Yes'); + clear temp + + % create and save figure + % timePoints = size(fMRSData_Summed_noBOLD.Data{1},1); + % dwellTime = fMRSData_Summed_noBOLD.Parameter.Headers.DwellTimeSig_ns * 1e-9; %in secs + % timeVector = linspace(0,(timePoints-1)*dwellTime,timePoints)'; + % plot(real(fftshift(fft(data(:,1,1).*exp(-pi*0.3*timeVector).*exp(1i*2*pi*0.09*timeVector))))-real(fftshift(fft(data(:,1,2))))) + + figure; hold on; + data = squeeze(fMRSData_Summed_noBOLD.Data{1}); + ppmVector = fMRSData_Summed_noBOLD.getPpmVector; + plot(ppmVector,real(fftshift(fft(real(data(:,1,1)))))) + plot(ppmVector,real(fftshift(fft(real(data(:,1,2)))))) + plot(ppmVector,real(fftshift(fft(real(data(:,1,3)))))) + set(gca, 'XDir','reverse') + xlim([0.5 4.5]); legend('On','Off','Residual') + + if exist('excludeSubjects') + fig2save_fMRSData_Summed_noBOLD = fullfile(fMRSData_Summed_Path, strcat('Diff_',visualType,strrep(BOLDType{1},'#','_'),MMBType,'_Excluded_BOLDafterSum.fig')); + else + fig2save_fMRSData_Summed_noBOLD = fullfile(fMRSData_Summed_Path, strcat('Diff_',visualType,strrep(BOLDType{1},'#','_'),MMBType,'_BOLDafterSum.fig')); + end + savefig(fig2save_fMRSData_Summed_noBOLD) + close all; + + end %% sum Water reference spectra of all volunteers, weighted with water fit (need to run doFitting_fMRS_Water.m first) WaterReferenceTable = (readtable(strcat(LCModelOutputPath,'WaterReference_Fit.xlsx'))); @@ -344,11 +388,13 @@ if exist('excludeSubjects') waterRefFileName = strcat(waterRefFileName,'_Excluded'); currentControlFiles = strrep(LCModelControlFiles, defaultSubject, 'Summed'); currentControlFiles = strrep(currentControlFiles,'.control','_Excluded.control'); + currentControlFiles = strrep(currentControlFiles,'fMRS_v2_','fMRS_'); currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, 'Summed'); currentOutputFiles = strcat(currentOutputFiles,'_Excluded'); else waterRefFileName = strrep(defaultWaterRef, defaultSubject, 'fMRSData_Summed'); currentControlFiles = strrep(LCModelControlFiles, defaultSubject, 'Summed'); + currentControlFiles = strrep(currentControlFiles,'fMRS_v2_','fMRS_'); currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, 'Summed'); end @@ -484,12 +530,14 @@ if ~isempty(strfind(BOLDType{1},'woBOLDCorr')) waterRefFileName = strcat(waterRefFileName,'_Excluded'); currentControlFiles = strrep(LCModelControlFiles, defaultSubject, 'Summed'); currentControlFiles = strrep(currentControlFiles,'.control','_Excluded_BOLDafterSum.control'); + currentControlFiles = strrep(currentControlFiles,'fMRS_v2_','fMRS_'); currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, 'Summed'); currentOutputFiles = strcat(currentOutputFiles,'_Excluded_BOLDafterSum'); else waterRefFileName = strrep(defaultWaterRef, defaultSubject, 'fMRSData_Summed'); currentControlFiles = strrep(LCModelControlFiles, defaultSubject, 'Summed'); currentControlFiles = strrep(currentControlFiles,'.control','_BOLDafterSum.control'); + currentControlFiles = strrep(currentControlFiles,'fMRS_v2_','fMRS_'); currentOutputFiles = strrep(strcat(LCModelOutputFiles,'_BOLDafterSum'), defaultSubject, 'Summed'); end @@ -741,9 +789,9 @@ if ~isempty(strfind(BOLDType{1},'woBOLDCorr')) % save table to file if exist('excludeSubjects') - ExpName = strrep(strcat('LCModelFit_Summed_', num2str(visualType),BOLDType, MMBType, '_Exc_BOLDafterSu'),'#','_'); + ExpName = strrep(strcat('LCModelFit_Summed_', num2str(visualType),BOLDType, MMBType, '_Exc_BOLDaftS'),'#','_'); else - ExpName = strrep(strcat('LCModelFit_Summed_', num2str(visualType),BOLDType, MMBType, '_BOLDafterSum'),'#','_'); + ExpName = strrep(strcat('LCModelFit_Summed_', num2str(visualType),BOLDType, MMBType, '_BOLDaftS'),'#','_'); end ExpName = ExpName{1}; %convert 1x1cell to string exportFileXlsx = [LCModelOutputPath ,strcat(ExpName,'.xlsx')]; @@ -770,9 +818,9 @@ if ~isempty(strfind(BOLDType{1},'woBOLDCorr')) rowNames = {'PercDiff'}; if exist('excludeSubjects') - ExpNameDiff = strrep(strcat('ConcDiff_Summed_', num2str(visualType),BOLDType, MMBType,'_Excl_BOLDafterSum'),'#','_'); + ExpNameDiff = strrep(strcat('ConcDiff_Summed_', num2str(visualType),BOLDType, MMBType,'_Excl_BOLDaftS'),'#','_'); else - ExpNameDiff = strrep(strcat('ConcDiff_Summed_', num2str(visualType),BOLDType, MMBType,'_BOLDafterSum'),'#','_'); + ExpNameDiff = strrep(strcat('ConcDiff_Summed_', num2str(visualType),BOLDType, MMBType,'_BOLDaftS'),'#','_'); end ExpNameDiff = ExpNameDiff{1}; %convert 1x1cell to string ConcDiff_Summed = array2table(PercDiff,'rowNames',rowNames,'VariableNames',metaboliteNames); diff --git a/fMRS_processing/doFitting_fMRS_Met_v2.m b/fMRS_processing/doFitting_fMRS_Met_v2.m index 6ce5b6a..6d702cc 100644 --- a/fMRS_processing/doFitting_fMRS_Met_v2.m +++ b/fMRS_processing/doFitting_fMRS_Met_v2.m @@ -1,14 +1,16 @@ function doFitting_fMRS_Met_v2() clear; clc; close all; -%check StimType, BOLDType, MMBType +%check pathName, StimType, BOLDType, MMBType %check nBlocks in reconstruct! %for v2 (+Asc, -Glyc, PCh&GPC -> tCh), check MMBType, defaultMMB, currentControlFiles -pathName = 'fMRS data path'; -sampleCriteria = {'Output', 'LCModelConfig'}; -[localFilePathBase] = pathToDataFolder(pathName, sampleCriteria); +% pathName = 'fMRS data path'; %first version, no modulus correction for gradient sideband removal +pathName = 'fMRS data path modulus'; %second version, with modulus correction for gradient sideband, only UF can be processed +% pathName = 'fMRS data path 06-38ppm'; %third version, LCModel Fit w/o Cr/PCr at 3.9ppm +% sampleCriteria = {'Output', 'LCModelConfig'}; +[localFilePathBase] = pathToDataFolder(pathName); StimType = {'StimON', 'StimOFF'}; %'StimON', 'StimOFF', 'RestON', 'RestOFF' if ~isempty(strfind(StimType{1},'Stim')) visualType = 'Stim'; @@ -17,19 +19,26 @@ elseif ~isempty(strfind(StimType{1},'Rest')) else error('StimType needs to be Stim or Rest'); end -BOLDType = {'_woBOLDCorr64#1'}; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _woBOLDCorr64#1, _withBOLDCorr64, _withBOLDCorr64#1 +BOLDTypes = {'_woBOLDCorr128', '_withBOLDCorr128','_woBOLDCorr64', '_woBOLDCorr64#1', '_withBOLDCorr64', '_withBOLDCorr64#1'}; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _woBOLDCorr64#1, _withBOLDCorr64, _withBOLDCorr64#1 +% BOLDTypes = {'_woBOLDCorr64#1'}; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _woBOLDCorr64#1, _withBOLDCorr64, _withBOLDCorr64#1 +for idxBOLDType = 1:length(BOLDTypes) + BOLDType = BOLDTypes(idxBOLDType); orderFMRS = strcat(StimType,BOLDType);% -% orderFMRS = {'StimON_woBOLDCorr128', 'StimOFF_woBOLDCorr128'}; MMBType = '_MMBSummed_v2'; %_MMBIndFiltered, _MMBSummed, _MMBInd, _MMBSimulated -% subjects = {'3333';}; -subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... - '4085';'3333';'4012';'4085';'6524'}; -% prefixes = {'2020-03-10_';}; -prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... - '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... - '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; -% excludeSubjects = {'5166';'9810';'5269'}; +subjects = {'3333';}; +% subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... +% '4085';'3333';'4012';'4085';'6524'}; +prefixes = {'2020-03-10_';}; +% prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... +% '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... +% '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; +excludeSubjects = {'5166';'9810';'5269'}; suffixFolder = '_fMRS'; +if strcmp(MMBType,'_MMBSummed') + excludeMet = {'NAA';'GABA';'Gln';'Glyc';'GSH';'mI';'NAAG';'PCh';'GPC';'PE';'Scyllo';'Tau';'Glc';'NAA_NAAG';'Glu_Gln';'Glyc';'mI_Glyc';'PCh'}; %for v1 +elseif strcmp(MMBType,'_MMBSummed_v2') + excludeMet = {'NAA';'Asc';'GABA';'Glc';'Gln';'GSH';'mI';'NAAG';'tCh';'PE';'Scyllo';'Tau';'NAA_NAAG';'Glu_Gln'}; %for v2 +end extensionTable = '.table'; extensionCoord = '.coord'; @@ -39,8 +48,6 @@ defaultSubjectsPath = 'YYYY'; % defaultMMB = '_MMBSummed'; defaultMMB = '_MMBSummed_v2'; defaultLCModelUser = 'jdorst'; -outputFileNameBaseWithoutMetabolite_OFF = strcat(defaultSubject, '_StimOFF_woBOLDCorr128'); -outputFileNameBaseWithoutMetabolite_ON = strcat(defaultSubject, '_StimON_woBOLDCorr128'); % controlFilesBase = 'fitsettings_fMRS_XXXX_'; controlFilesBase = 'fitsettings_fMRS_v2_XXXX_'; @@ -51,7 +58,16 @@ outputFileNameBase = strcat(defaultSubject, '_'); controlFilesPathRemote = '/Desktop/1H_fMRS/LCModelConfig/'; controlFilesPathLocal = [localFilePathBase, 'LCModelConfig/']; LCModelOutputFilesPathRemote = '/Desktop/1H_fMRS/Output/'; -LCModelOutputPath = [localFilePathBase, 'Output/']; +if ~isempty(strfind(localFilePathBase,'Modulus')) + LCModelOutputPath = [localFilePathBase, 'Output_v2_MMBSummed_Modulus/']; + modulus = true; +elseif ~isempty(strfind(localFilePathBase,'06-38ppm')) + LCModelOutputPath = [localFilePathBase, 'Output_v2_MMBSummed_06-38ppm/']; + modulus = false; +else + LCModelOutputPath = [localFilePathBase, 'Output_v2_MMBSummed/']; + modulus = false; +end defaultControlFile = strcat(controlFilesBase, defaultfMRS, controlFilesBaseSuffix); subjectsPath = strcat(prefixes, subjects, suffixFolder); @@ -65,29 +81,34 @@ subjectsLCModelOutputPath = strcat(LCModelOutputPath, subjectsPath, '/'); %% process fMRS data and save .RAW file dataPath = strcat(localFilePathBase,subjectsPath, '/'); -% for i = 1:length(dataPath) -% currentFolder = num2str(cell2mat(dataPath(i))); -% cd (currentFolder); -% subFolderName = dir(dataPath{i}); -% if ~isempty(strfind(StimType{1},'Stim')) -% dataFile = dir('*Stim*.dat'); -% elseif ~isempty(strfind(StimType{1},'Rest')) -% dataFile = dir('*Rest*.dat'); -% else -% error('StimType needs to be Stim or Rest'); -% end -% % nBlocks = 5; -% nBlocks = 10; -% PCSteps = 16; -% reconstruct_1H_fMRS(currentFolder,dataFile.name,1,1,nBlocks,false,PCSteps,[],1,visualType); %currentFolder, fid_id, isMC, isInVivo, nBlocks, nOnAverages, PCSteps, weights, saveResults -% close all; cd ..; -% end - +if ~isempty(strfind(BOLDType{1},'wo')) + for i = 1:length(dataPath) + currentFolder = num2str(cell2mat(dataPath(i))); + cd (currentFolder); + subFolderName = dir(dataPath{i}); + if ~isempty(strfind(StimType{1},'Stim')) + dataFile = dir('*Stim*.dat'); + elseif ~isempty(strfind(StimType{1},'Rest')) + dataFile = dir('*Rest*.dat'); + else + error('StimType needs to be Stim or Rest'); + end + if ~isempty(strfind(BOLDType{1},'128')) + nBlocks = 5; + else + nBlocks = 10; + end + PCSteps = 16; + reconstruct_1H_fMRS(currentFolder,dataFile.name,1,1,nBlocks,false,PCSteps,[],1,visualType,BOLDType{1}, modulus); %currentFolder, fid_id, isMC, isInVivo, nBlocks, nOnAverages, PCSteps, weights, saveResults + close all; cd ..; + end +end +% % % % end %% basic configurations -% LCModelTableFits = strcat(outputFileNameBase, orderFMRS, extensionTable); -% LCModelTableFitsCoord = strcat(outputFileNameBase, orderFMRS, extensionCoord); LCModelOutputFiles = strcat(outputFileNameBase, orderFMRS, MMBType); +LCModelOutputFileswoBaseline = strcat(outputFileNameBase, orderFMRS, MMBType, '_woBaseline'); LCModelControlFiles = strcat(controlFilesBase, orderFMRS, MMBType, controlFilesBaseSuffix); +LCModelControlFileswoBaseline = strcat(controlFilesBase, orderFMRS, MMBType, '_woBaseline', controlFilesBaseSuffix); defaultWaterRef = strcat(outputFileNameBase, 'WRef'); % @@ -95,9 +116,9 @@ numberOfFMRS = length(orderFMRS); numberOfSubjects = length(subjects); %% do the LCModel fitting -% LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); +% % % LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); -% do the actual LCModel fitting +% % do the actual LCModel fitting parfor indexCurrentSubject = 1:numberOfSubjects %% do the LCModel fitting LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); @@ -124,16 +145,84 @@ parfor indexCurrentSubject = 1:numberOfSubjects fittingLCModel(LCModelCallerInstance, currentControlFiles, currentOutputFiles, subjectsControlFilesPathRemote{indexCurrentSubject}, ... subjectsControlFilesPathLocal{indexCurrentSubject}, preprocessedFilesPathLocal{indexCurrentSubject}); end +if exist('excludeSubjects') + createConcTable(numberOfSubjects,orderFMRS,LCModelOutputFiles,LCModelOutputPath,defaultSubject,prefixes,subjects,subjectsPath,... + visualType,BOLDType,MMBType,excludeSubjects,excludeMet) +else + createConcTable(numberOfSubjects,orderFMRS,LCModelOutputFiles,LCModelOutputPath,defaultSubject,prefixes,subjects,subjectsPath,... + visualType,BOLDType,MMBType,'',excludeMet) +end + +%% subtract baseline from difference spectrum and fit again +% only useful for MMBSummed +if strcmp(MMBType(1:10),'_MMBSummed') + % LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); + parfor indexCurrentSubject = 1:numberOfSubjects + %% do the LCModel fitting + LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); + + LCModelCallerInstance = LCModelCallerInstance.ConfigurePaths(subjectsControlFilesPathRemote{indexCurrentSubject}, subjectsLCModelOutputFilesRemote{indexCurrentSubject}, ... + subjectsLCModelOutputPath{indexCurrentSubject}); + + currentControlFileswoBaseline = strrep(LCModelControlFileswoBaseline, defaultSubject, subjects{indexCurrentSubject}); + currentControlFileswoBaseline = strrep(currentControlFileswoBaseline,'fMRS_v2_','fMRS_'); + currentControlFileswoBaseline = strrep(currentControlFileswoBaseline,'#1','_1'); + if ~isempty(strfind(MMBType,'_v2')) + currentDataFiles = strrep(strcat(outputFileNameBase, orderFMRS, '_v2'), defaultSubject, subjects{indexCurrentSubject}); + else + currentDataFiles = strrep(strcat(outputFileNameBase, visualType, BOLDType), defaultSubject, subjects{indexCurrentSubject}); + end + + % currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, subjects{indexCurrentSubject}); + waterRefFileName = strrep(defaultWaterRef, defaultSubject, subjects{indexCurrentSubject}); + currentDataPath = strcat(localFilePathBase,subjectsPath{indexCurrentSubject}, '/'); + for indexFMRS = 1:length(currentDataFiles) + % currentOutputFileswoBaseline = currentOutputFileswoBaseline{indexFMRS}; + currentFMRS = orderFMRS{indexFMRS}; + currentFMRS = strrep(currentFMRS,'#1','_1'); + currentLCModelOutputFile = LCModelOutputFiles{indexFMRS}; + currentLCModelOutputFile = strrep(currentLCModelOutputFile,'#1','_1'); + %check save option for .mat file in subtractBaseline_fMRS + currentOutputFileswoBaseline = strrep(LCModelOutputFileswoBaseline, defaultSubject, subjects{indexCurrentSubject}); + subtractBaseline_fMRS(currentDataPath,subjectsLCModelOutputPath{indexCurrentSubject},currentDataFiles{indexFMRS},currentOutputFileswoBaseline{indexFMRS},'NAA') + currentOutputFileswoBaseline = strrep(currentOutputFileswoBaseline,'#1','_1'); + createLCModelConfigfMRS('fMRS', controlFilesPathLocal, subjectsControlFilesPathLocal{indexCurrentSubject}, defaultControlFile, ... + currentFMRS, defaultfMRS, defaultLCModelUser, LCModelCallerInstance.LCModelUser, currentOutputFileswoBaseline{indexFMRS}, currentLCModelOutputFile,... + waterRefFileName, defaultWaterRef, subjectsPath{indexCurrentSubject}, defaultSubjectsPath, subjects{indexCurrentSubject},... + defaultSubject, MMBType, defaultMMB,''); + end + fittingLCModel(LCModelCallerInstance, currentControlFileswoBaseline, currentOutputFileswoBaseline, subjectsControlFilesPathRemote{indexCurrentSubject}, ... + subjectsControlFilesPathLocal{indexCurrentSubject}, preprocessedFilesPathLocal{indexCurrentSubject}); + + end + if exist('excludeSubjects') + createConcTable(numberOfSubjects,orderFMRS,LCModelOutputFiles,LCModelOutputPath,defaultSubject,prefixes,subjects,subjectsPath,... + visualType,BOLDType,MMBType,excludeSubjects,excludeMet,1) + else + createConcTable(numberOfSubjects,orderFMRS,LCModelOutputFiles,LCModelOutputPath,defaultSubject,prefixes,subjects,subjectsPath,... + visualType,BOLDType,MMBType,'',excludeMet,1) + end +end +end +end %% create concentration table +function createConcTable(numberOfSubjects,orderFMRS,LCModelOutputFiles,LCModelOutputPath,defaultSubject,prefixes,subjects,subjectsPath,... + visualType,BOLDType,MMBType,excludeSubjects,excludeMet,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; + LCModelOutputFiles = strrep(LCModelOutputFiles,'#1','_1'); +else + woBaseline = ''; +end tableConcentrations = []; isFirstIter = 1; s = 1; for indexCurrentSubject = 1:numberOfSubjects for indexorderFMRS = 1:length(orderFMRS) % retrieve parameters - currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, subjects{indexCurrentSubject}); + currentOutputFiles = strrep(strcat(LCModelOutputFiles,woBaseline), defaultSubject, subjects{indexCurrentSubject}); currentPath = strcat(LCModelOutputPath,subjectsPath{indexCurrentSubject},'/',currentOutputFiles,'.table'); [c1 c2 c3 c4] = textread(currentPath{indexorderFMRS},'%s %s %s %s'); @@ -184,7 +273,7 @@ for indexCurrentSubject = 1:numberOfSubjects end % save table to file -ExpName = strcat('LCModelFit_', num2str(visualType), BOLDType{1}, MMBType); +ExpName = strcat('LCModelFit_', num2str(visualType), BOLDType{1}, MMBType, woBaseline); ExpName = strrep(ExpName,'#1','_1'); exportFileXlsx = [LCModelOutputPath ,strcat(ExpName,'.xlsx')]; xlswrite(exportFileXlsx, {LCModelOutputPath}, 1, 'A1'); @@ -202,7 +291,7 @@ LCModelFitTable = eval(rawFile); metaboliteNames = LCModelFitTable(1,4:2:end-2); metaboliteNames = strrep(metaboliteNames,'+','_'); -if exist('excludeSubjects') +if exist('excludeSubjects', 'var') & ~isempty(excludeSubjects) [n,~] = size(LCModelFitTable); m = length(excludeSubjects); nstep = 1; @@ -224,59 +313,136 @@ PercDiff = 100./OFF.*ON-100; PercDiffMean = mean(PercDiff); PercDiffStd = std(PercDiff); -%two-sided Wilcoxon signed rank test -% for indexOfMetabolite = 1:length(metaboliteNames) -% if isempty(find(~isnan(PercDiff(:,indexOfMetabolite)))) -% p(indexOfMetabolite) = NaN; -% h(indexOfMetabolite) = 0; -% else -% [p(indexOfMetabolite),h(indexOfMetabolite)] = signrank(PercDiff(:,indexOfMetabolite)); -% end -% end - -%paired two-tailed t-test +%% two-sided Wilcoxon signed rank test for indexOfMetabolite = 1:length(metaboliteNames) if isempty(find(~isnan(PercDiff(:,indexOfMetabolite)))) - h(indexOfMetabolite) = NaN; - p(indexOfMetabolite) = 0; + p_Wilc(indexOfMetabolite) = NaN; + h_Wilc(indexOfMetabolite) = 0; else - [h(indexOfMetabolite),p(indexOfMetabolite)] = ttest(PercDiff(:,indexOfMetabolite)); + [p_Wilc(indexOfMetabolite),h_Wilc(indexOfMetabolite)] = signrank(PercDiff(:,indexOfMetabolite)); end end %check histogram of p-values -edges = linspace(0,1,length(p)); -histogram(p,edges) +edges = linspace(0,1,length(p_Wilc)); +histogram(p_Wilc,edges) %Benjamini-Hochberg correction for multiple testing -[h_BH, crit_p, adj_ci_cvrg, adj_p]=fdr_bh(p,0.05,'pdep','yes'); +[h_BH_Wilc, crit_p_Wilc, adj_ci_cvrg_Wilc, adj_p_Wilc]=fdr_bh(p_Wilc,0.05,'pdep','yes'); %h=1: reject H0, h=0: H0 not rejected %crit_p: max p-value that is significant %adj_ci_cvrg: BH adjusted confidence interval coverage %adj_p: N pj / j, all adjusted p-values less than or equal to q are significant -if exist('excludeSubjects') + +if exist('excludeMet') + [~,n] = size(metaboliteNames); + m = length(excludeMet); + nstep = 1; + for j = 1:m + for i = 1:n + xx = strcmp(metaboliteNames(1,i),excludeMet{j}); +% xx = find(~cellfun(@isempty,strcmp(metaboliteNames(1,i),excludeMet{j}))); +% if ~isempty(xx) + if xx + excludeMetIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + pExclMet_Wilc = p_Wilc; + pExclMet_Wilc(excludeMetIdx) = []; + [h_BH_ExclMet_Wilc, crit_p_ExclMet_Wilc, adj_ci_cvrg_ExclMet_Wilc, adj_p_ExclMet_Wilc]=fdr_bh(pExclMet_Wilc,0.05,'pdep','yes'); + temph = ones(1,length(h_Wilc))*NaN; temp_p = ones(1,length(p_Wilc))*NaN; tempidx = [0 sort(excludeMetIdx)]; nstep = 1; + for j = 1:length(tempidx)-1 + temp_p((tempidx(j)+1):(tempidx(j+1)-1)) = adj_p_ExclMet_Wilc((tempidx(j)+2-nstep):(tempidx(j+1)-nstep)); + temph((tempidx(j)+1):(tempidx(j+1)-1)) = h_BH_ExclMet_Wilc((tempidx(j)+2-nstep):(tempidx(j+1)-nstep)); + nstep = nstep + 1; + end + h_BH_ExclMet_Wilc = temph; + adj_p_ExclMet_Wilc = temp_p; +end + +%% paired two-tailed t-test (data need to be normally distributed, which they aren't here! -> use nonparametric Wilcoxon) +for indexOfMetabolite = 1:length(metaboliteNames) + if isempty(find(~isnan(PercDiff(:,indexOfMetabolite)))) + h_ttest(indexOfMetabolite) = NaN; + p_ttest(indexOfMetabolite) = 0; + else + [h_ttest(indexOfMetabolite),p_ttest(indexOfMetabolite)] = ttest(PercDiff(:,indexOfMetabolite)); + end +end + +%check histogram of p-values +edges = linspace(0,1,length(p_ttest)); +histogram(p_ttest,edges) + +%Benjamini-Hochberg correction for multiple testing +[h_BH_ttest, crit_p_ttest, adj_ci_cvrg_ttest, adj_p_ttest]=fdr_bh(p_ttest,0.05,'pdep','yes'); +%h=1: reject H0, h=0: H0 not rejected +%crit_p: max p-value that is significant +%adj_ci_cvrg: BH adjusted confidence interval coverage +%adj_p: N pj / j, all adjusted p-values less than or equal to q are significant + +if exist('excludeMet', 'var') + [~,n] = size(metaboliteNames); + m = length(excludeMet); + nstep = 1; + for j = 1:m + for i = 1:n + xx = strcmp(metaboliteNames(1,i),excludeMet{j}); +% xx = find(~cellfun(@isempty,strcmp(metaboliteNames(1,i),excludeMet{j}))); +% if ~isempty(xx) + if xx + excludeMetIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + pExclMet_ttest = p_ttest; + pExclMet_ttest(excludeMetIdx) = []; + [h_BH_ExclMet_ttest, crit_p_ExclMet_ttest, adj_ci_cvrg_ExclMet_ttest, adj_p_ExclMet_ttest]=fdr_bh(pExclMet_ttest,0.05,'pdep','yes'); + temph = ones(1,length(h_ttest))*NaN; temp_p = ones(1,length(p_ttest))*NaN; tempidx = [0 sort(excludeMetIdx)]; nstep = 1; + for j = 1:length(tempidx)-1 + temp_p((tempidx(j)+1):(tempidx(j+1)-1)) = adj_p_ExclMet_ttest((tempidx(j)+2-nstep):(tempidx(j+1)-nstep)); + temph((tempidx(j)+1):(tempidx(j+1)-1)) = h_BH_ExclMet_ttest((tempidx(j)+2-nstep):(tempidx(j+1)-nstep)); + nstep = nstep + 1; + end + h_BH_ExclMet_ttest = temph; + adj_p_ExclMet_ttest = temp_p; +end +if exist('excludeSubjects', 'var') & ~isempty(excludeSubjects) m = length(excludeSubjects); for k = 1:m - [~, idx(k)] = ismember(excludeSubjects(k), subjects) + [~, idx(k)] = ismember(excludeSubjects(k), subjects); end prefixes([idx],:) = []; subjects([idx],:) = []; end - rowNames = strcat(prefixes, subjects); -% rowNames = [rowNames; 'Mean'; 'Std'; 'p-Value'; 'h-Value']; -rowNames = [rowNames; 'Mean'; 'Std'; 'p-Value'; 'h-Value'; 'p_BH'; 'h_BH']; -if exist('excludeSubjects') - ExpNameDiff = strcat('ConcDiff_', num2str(visualType), BOLDType, MMBType, '_Excluded'); +if exist('excludeMet', 'var') + rowNames = [rowNames; 'Mean'; 'Std'; 'p-Value_Wilc'; 'h-Value_Wilc'; 'p_BH_Wilc'; 'h_BH_Wilc'; 'p_BH_Excl_Wilc'; 'h_BH_Excl_Wilc'; 'p-Value_ttest'; 'h-Value_ttest'; 'p_BH_ttest'; 'h_BH_ttest'; 'p_BH_Excl_ttest'; 'h_BH_Excl_ttest']; +else + rowNames = [rowNames; 'Mean'; 'Std'; 'p-Value_Wilc'; 'h-Value_Wilc'; 'p_BH_Wilc'; 'h_BH_Wilc'; 'p-Value_ttest'; 'h-Value_ttest'; 'p_BH_ttest'; 'h_BH_ttest']; +end +if exist('excludeSubjects', 'var') & ~isempty(excludeSubjects) + ExpNameDiff = strcat('ConcDiff_', num2str(visualType), BOLDType, MMBType, '_Excluded_woBaseline'); else - ExpNameDiff = strcat('ConcDiff_', num2str(visualType), BOLDType, MMBType); + ExpNameDiff = strcat('ConcDiff_', num2str(visualType), BOLDType, MMBType, '_woBaseline'); end ExpNameDiff = ExpNameDiff{1}; %convert 1x1cell to string ExpNameDiff = strrep(ExpNameDiff,'#1','_1'); -ConcentrationsDiff_xx = array2table([PercDiff; PercDiffMean; PercDiffStd; p; h; adj_p; h_BH],'rowNames',rowNames,'VariableNames',metaboliteNames); +if exist ('excludeMet') + ConcentrationsDiff_xx = array2table([PercDiff; PercDiffMean; PercDiffStd; p_Wilc; h_Wilc; adj_p_Wilc; h_BH_Wilc; adj_p_ExclMet_Wilc; h_BH_ExclMet_Wilc; p_ttest; h_ttest; adj_p_ttest; h_BH_ttest; adj_p_ExclMet_ttest; h_BH_ExclMet_ttest],'rowNames',rowNames,'VariableNames',metaboliteNames); +else + ConcentrationsDiff_xx = array2table([PercDiff; PercDiffMean; PercDiffStd; p_Wilc; h_Wilc; adj_p_Wilc; h_BH_Wilc; p_ttest; h_ttest; adj_p_ttest; h_BH_ttest],'rowNames',rowNames,'VariableNames',metaboliteNames); +end + +% ConcentrationsDiff_xx = array2table([PercDiff; PercDiffMean; PercDiffStd; p; h; adj_p; h_BH],'rowNames',rowNames,'VariableNames',metaboliteNames); eval([ExpNameDiff '=ConcentrationsDiff_xx']); exportFileMatDiff = [LCModelOutputPath ,strcat(ExpNameDiff,'.mat')]; save(exportFileMatDiff,ExpNameDiff) -end \ No newline at end of file +close all +end + diff --git a/fMRS_processing/doFitting_fMRS_SlidingAverage.m b/fMRS_processing/doFitting_fMRS_SlidingAverage.m index 9db466f..2726558 100644 --- a/fMRS_processing/doFitting_fMRS_SlidingAverage.m +++ b/fMRS_processing/doFitting_fMRS_SlidingAverage.m @@ -8,6 +8,7 @@ fitversion = 'v2'; pathName = 'fMRS SlidingAverage data path'; sampleCriteria = {'Output', 'LCModelConfig'}; [localFilePathBase] = pathToDataFolder(pathName, sampleCriteria); + visualType = 'Rest'; %'Stim', 'Rest' BOLDType = '_woBOLDCorr'; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _withBOLDCorr64 if fitversion == 'v2' @@ -25,15 +26,10 @@ for k = 1:nBlocks end % subjects = {'2823';}; -% subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... -% '4085';'3333';'4012';'4085';'6524'}; -subjects = {'5166';'9810';'2774';'1658';'5269';'1706';'1004';... +subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... '4085';'3333';'4012';'4085';'6524'}; % prefixes = {'2020-02-18_';}; -% prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... -% '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... -% '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; -prefixes = {'2020-02-21_';'2020-02-21_';'2020-02-26_';... +prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; excludeSubjects = {'5166';'9810';'5269'}; @@ -61,6 +57,18 @@ end controlFilesBaseSuffix = '.control'; outputFileNameBase = strcat(defaultSubject, '_'); + +pathNameBaseline = 'fMRS TimeCourse data path'; +sampleCriteriaBaseline = {'Output_v2_MMBSummed', 'Output', 'LCModelConfig'}; +[localFilePathBaseBaseline] = pathToDataFolder(pathNameBaseline, sampleCriteriaBaseline); +if fitversion == 'v2' + localBaselinePath = [localFilePathBaseBaseline, 'Output_v2_MMBSummed/']; + BaselineFiles = strcat('BaselineConc_',num2str(visualType), BOLDType, MMBType); +else + localBaselinePath = [localFilePathBaseBaseline, 'Output/']; + BaselineFiles = strcat('BaselineConc_',num2str(visualType), BOLDType, MMBType); +end + %% file paths setup controlFilesPathRemote = '/Desktop/1H_fMRS/LCModelConfig/'; controlFilesPathLocal = [localFilePathBase, 'LCModelConfig/']; @@ -108,118 +116,380 @@ numberOfSubjects = length(subjects); % LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); % do the actual LCModel fitting -parfor indexCurrentSubject = 1:numberOfSubjects - %% do the LCModel fitting - LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); - - LCModelCallerInstance = LCModelCallerInstance.ConfigurePaths(subjectsControlFilesPathRemote{indexCurrentSubject}, subjectsLCModelOutputFilesRemote{indexCurrentSubject}, ... - subjectsLCModelOutputPath{indexCurrentSubject}); - - if fitversion == 'v2' - currentControlFiles = strrep(LCModelControlFiles, strcat('v2_',defaultSubject), subjects{indexCurrentSubject}); - else - currentControlFiles = strrep(LCModelControlFiles, defaultSubject, subjects{indexCurrentSubject}); - end - currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, subjects{indexCurrentSubject}); - waterRefFileName = strrep(defaultWaterRef, defaultSubject, subjects{indexCurrentSubject}); - - %% create the control file series - for nBl = 1:nBlocks - currentOutputFile = currentOutputFiles{nBl}; - currentFMRS = strcat(visualType,BOLDType); -% MMBType_temp = strrep(MMBType,'_v2',''); - createLCModelConfigfMRSTimeCourse(controlFilesPathLocal, subjectsControlFilesPathLocal{indexCurrentSubject}, defaultControlFile, ... - currentFMRS, defaultVisual, currentOutputFile,... - waterRefFileName, defaultWaterRef, subjectsPath{indexCurrentSubject}, defaultSubjectsPath, subjects{indexCurrentSubject},... - defaultSubject, MMBType, defaultMMB, BlockNo{nBl}); - end - - fittingLCModel(LCModelCallerInstance, currentControlFiles, currentOutputFiles, subjectsControlFilesPathRemote{indexCurrentSubject}, ... - subjectsControlFilesPathLocal{indexCurrentSubject}, preprocessedFilesPathLocal{indexCurrentSubject}); -end +% for indexCurrentSubject = 1:numberOfSubjects +% %% do the LCModel fitting +% LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); +% +% LCModelCallerInstance = LCModelCallerInstance.ConfigurePaths(subjectsControlFilesPathRemote{indexCurrentSubject}, subjectsLCModelOutputFilesRemote{indexCurrentSubject}, ... +% subjectsLCModelOutputPath{indexCurrentSubject}); +% +% if fitversion == 'v2' +% currentControlFiles = strrep(LCModelControlFiles, strcat('v2_',defaultSubject), subjects{indexCurrentSubject}); +% else +% currentControlFiles = strrep(LCModelControlFiles, defaultSubject, subjects{indexCurrentSubject}); +% end +% currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, subjects{indexCurrentSubject}); +% waterRefFileName = strrep(defaultWaterRef, defaultSubject, subjects{indexCurrentSubject}); +% +% %% create the control file series +% for nBl = 1:nBlocks +% currentOutputFile = currentOutputFiles{nBl}; +% currentFMRS = strcat(visualType,BOLDType); +% % MMBType_temp = strrep(MMBType,'_v2',''); +% createLCModelConfigfMRSTimeCourse(controlFilesPathLocal, subjectsControlFilesPathLocal{indexCurrentSubject}, defaultControlFile, ... +% currentFMRS, defaultVisual, currentOutputFile,... +% waterRefFileName, defaultWaterRef, subjectsPath{indexCurrentSubject}, defaultSubjectsPath, subjects{indexCurrentSubject},... +% defaultSubject, MMBType, defaultMMB, BlockNo{nBl}); +% end +% +% fittingLCModel(LCModelCallerInstance, currentControlFiles, currentOutputFiles, subjectsControlFilesPathRemote{indexCurrentSubject}, ... +% subjectsControlFilesPathLocal{indexCurrentSubject}, preprocessedFilesPathLocal{indexCurrentSubject}); +% end -% Create and save table with baseline concentrations fitted with baseline, taken from second block of first REST -% createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... -% LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,0) +%%% not useful here, take it from Data_TimeCourse +% % % Create and save table with baseline concentrations fitted with baseline, taken from second block of first REST +% % createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... +% % LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,0) -% Create and save table from fitted concentrations with baseline, taken from -% all blocks -for indexCurrentSubject = 1:numberOfSubjects -createConcTableBlock(BlockNo,LCModelOutputFiles,defaultSubject,subjects{indexCurrentSubject},... - LCModelOutputPath,subjectsPath{indexCurrentSubject},prefixes{indexCurrentSubject},visualType,BOLDType,MMBType,0) -end +% % Create and save table from fitted concentrations with baseline, taken from +% % all blocks +% for indexCurrentSubject = 1:numberOfSubjects +% createConcTableBlock(BlockNo,LCModelOutputFiles,defaultSubject,subjects{indexCurrentSubject},... +% LCModelOutputPath,subjectsPath{indexCurrentSubject},prefixes{indexCurrentSubject},visualType,BOLDType,MMBType,0) +% end %% subtract baseline from difference spectrum and fit again %only useful for MMBSummed if strcmp(MMBType(1:10),'_MMBSummed') % LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); - parfor indexCurrentSubject = 1:numberOfSubjects - %% do the LCModel fitting - LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); - - LCModelCallerInstance = LCModelCallerInstance.ConfigurePaths(subjectsControlFilesPathRemote{indexCurrentSubject}, subjectsLCModelOutputFilesRemote{indexCurrentSubject}, ... - subjectsLCModelOutputPath{indexCurrentSubject}); +% for indexCurrentSubject = 1:numberOfSubjects +% %% do the LCModel fitting +% LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); % - if fitversion == 'v2' - currentControlFileswoBaseline = strrep(LCModelControlFileswoBaseline, strcat('v2_',defaultSubject), subjects{indexCurrentSubject}); - else - currentControlFileswoBaseline = strrep(LCModelControlFileswoBaseline, defaultSubject, subjects{indexCurrentSubject}); - end - currentDataFiles = strrep(strcat(outputFileNameBase, visualType, BOLDType, BlockNo), defaultSubject, subjects{indexCurrentSubject}); - currentOutputFileswoBaseline = strrep(LCModelOutputFileswoBaseline, defaultSubject, subjects{indexCurrentSubject}); - currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, subjects{indexCurrentSubject}); - waterRefFileName = strrep(defaultWaterRef, defaultSubject, subjects{indexCurrentSubject}); - currentDataPath = strcat(localFilePathBase,subjectsPath{indexCurrentSubject}, '/'); - for nBl = 1:nBlocks - %check save option for .mat file in subtractBaseline_fMRS - subtractBaseline_fMRS(currentDataPath,subjectsLCModelOutputPath{indexCurrentSubject},currentDataFiles{nBl},currentOutputFileswoBaseline{nBl},'NAA') - currentFMRS = strcat(visualType,BOLDType); - createLCModelConfigfMRSTimeCourse(controlFilesPathLocal, subjectsControlFilesPathLocal{indexCurrentSubject}, defaultControlFile, ... - currentFMRS, defaultVisual, currentOutputFileswoBaseline{nBl},... - waterRefFileName, defaultWaterRef, subjectsPath{indexCurrentSubject}, defaultSubjectsPath, subjects{indexCurrentSubject},... - defaultSubject, MMBType, defaultMMB, strcat(BlockNo{nBl}, '_woBaseline')); - end - fittingLCModel(LCModelCallerInstance, currentControlFileswoBaseline, currentOutputFileswoBaseline, subjectsControlFilesPathRemote{indexCurrentSubject}, ... - subjectsControlFilesPathLocal{indexCurrentSubject}, preprocessedFilesPathLocal{indexCurrentSubject}); - - end - - % Create and save table with baseline concentrations fitted w/o baseline, taken from second block of first REST - % createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... - % LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,1) +% LCModelCallerInstance = LCModelCallerInstance.ConfigurePaths(subjectsControlFilesPathRemote{indexCurrentSubject}, subjectsLCModelOutputFilesRemote{indexCurrentSubject}, ... +% subjectsLCModelOutputPath{indexCurrentSubject}); +% % +% if fitversion == 'v2' +% currentControlFileswoBaseline = strrep(LCModelControlFileswoBaseline, strcat('v2_',defaultSubject), subjects{indexCurrentSubject}); +% else +% currentControlFileswoBaseline = strrep(LCModelControlFileswoBaseline, defaultSubject, subjects{indexCurrentSubject}); +% end +% currentDataFiles = strrep(strcat(outputFileNameBase, visualType, BOLDType, BlockNo), defaultSubject, subjects{indexCurrentSubject}); +% currentOutputFileswoBaseline = strrep(LCModelOutputFileswoBaseline, defaultSubject, subjects{indexCurrentSubject}); +% currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, subjects{indexCurrentSubject}); +% waterRefFileName = strrep(defaultWaterRef, defaultSubject, subjects{indexCurrentSubject}); +% currentDataPath = strcat(localFilePathBase,subjectsPath{indexCurrentSubject}, '/'); +% for nBl = 1:nBlocks +% %check save option for .mat file in subtractBaseline_fMRS +% subtractBaseline_fMRS(currentDataPath,subjectsLCModelOutputPath{indexCurrentSubject},currentDataFiles{nBl},currentOutputFileswoBaseline{nBl},'NAA') +% currentFMRS = strcat(visualType,BOLDType); +% createLCModelConfigfMRSTimeCourse(controlFilesPathLocal, subjectsControlFilesPathLocal{indexCurrentSubject}, defaultControlFile, ... +% currentFMRS, defaultVisual, currentOutputFileswoBaseline{nBl},... +% waterRefFileName, defaultWaterRef, subjectsPath{indexCurrentSubject}, defaultSubjectsPath, subjects{indexCurrentSubject},... +% defaultSubject, MMBType, defaultMMB, strcat(BlockNo{nBl}, '_woBaseline')); +% end +% fittingLCModel(LCModelCallerInstance, currentControlFileswoBaseline, currentOutputFileswoBaseline, subjectsControlFilesPathRemote{indexCurrentSubject}, ... +% subjectsControlFilesPathLocal{indexCurrentSubject}, preprocessedFilesPathLocal{indexCurrentSubject}); +% +% end + %%% not useful here, take it from Data_TimeCourse +% % Create and save table with baseline concentrations fitted w/o baseline, taken from second block of first REST +% % createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... +% % LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,1) % Create and save table from fitted concentrations w/o baseline, taken from all blocks - for indexCurrentSubject = 1:numberOfSubjects - createConcTableBlock(BlockNo,LCModelOutputFiles,defaultSubject,subjects{indexCurrentSubject},... - LCModelOutputPath,subjectsPath{indexCurrentSubject},prefixes{indexCurrentSubject},visualType,BOLDType,MMBType,1) - end +% for indexCurrentSubject = 1:numberOfSubjects +% createConcTableBlock(BlockNo,LCModelOutputFiles,defaultSubject,subjects{indexCurrentSubject},... +% LCModelOutputPath,subjectsPath{indexCurrentSubject},prefixes{indexCurrentSubject},visualType,BOLDType,MMBType,1) +% end end %% create concentration time course from fit with and w/o Baseline ExpName = strcat('BlockConc_', subjects, '_', num2str(visualType), BOLDType, MMBType); if exist('excludeSubjects') -% createConcTimeCourseFigExcluded(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,excludeSubjects,'Lac',0) -% createConcTimeCourseFigExcluded(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,excludeSubjects,'Glu',0) -% createConcTimeCourseFigExcluded(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,excludeSubjects,'Cr',0) -% createConcTimeCourseFigExcluded(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,excludeSubjects,'PCr',0) +% createConcTimeCourseBoxplot(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,'Lac',excludeSubjects,0) +% createConcTimeCourseBoxplot(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,'Glu',excludeSubjects,0) + % createConcTimeCourseFigExcluded(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,excludeSubjects,'Lac',0) + % createConcTimeCourseFigExcluded(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,excludeSubjects,'Glu',0) +% createConcTimeCourseFigExcluded(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,excludeSubjects,'Cr',0) +% createConcTimeCourseFigExcluded(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,excludeSubjects,'PCr',0) +% createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,'Glu',excludeSubjects,0) +% createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,'GSH',excludeSubjects,0) +% createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,'Cr',excludeSubjects,0) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,'PCr',excludeSubjects,0) if strcmp(MMBType(1:10),'_MMBSummed') - createConcTimeCourseFigExcluded(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,excludeSubjects,'Glu',1) +% createConcTimeCourseFigExcluded(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,excludeSubjects,'Glu',1) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,'Glu',excludeSubjects,1) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,'Lac',excludeSubjects,1) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,'Cr',excludeSubjects,1) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,'PCr',excludeSubjects,1) end else % createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,'Lac',0) % createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,'Glu',0) % createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,'Cr',0) - createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,'PCr',0) - if strcmp(MMBType(1:10),'_MMBSummed') - createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,'Lac',1) - createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,'Glu',1) - end +% createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,'PCr',0) +createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,'Glu','',0) +% if strcmp(MMBType(1:10),'_MMBSummed') +% createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,'Lac',1) +% createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,'Glu',1) +% end end close all end +function createConcTimeCourseBoxplot(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,metabToFig,excludeSubjects,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +ExpName = strcat(ExpName, woBaseline); +exportFileMat = strcat(subjectsLCModelOutputPath,ExpName,'.mat'); + +if exist('excludeSubjects') & ~isempty(excludeSubjects) + n = length(ExpName); + m = length(excludeSubjects); + nstep = 1; + for j = 1:m + for i = 1:n + xx = find(~cellfun(@isempty,strfind(exportFileMat(i,1),excludeSubjects{j}))); + if ~isempty(xx) + excludeIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + ExpName([excludeIdx],:) = []; + exportFileMat([excludeIdx],:) = []; +end + +for k = 1:numel(exportFileMat) + tmp = load(exportFileMat{k}); + dataTimeCourse(:,:,k) = tmp.(ExpName{k}); +end + +metaboliteNames = dataTimeCourse(1,:,1); +indexMet = strcmp(metaboliteNames,metabToFig); +% idxMet = find(not(cellfun('isempty',indexMet))); +idxMet = find(indexMet == true); + +%Baseline concentration +if exist('excludeSubjects') & ~isempty(excludeSubjects) + BaselineFiles = strcat(BaselineFiles,'_Excluded'); +end +baselineConcFile = strcat(localBaselinePath,BaselineFiles); + +baselineConcTemp = load(strcat(baselineConcFile,'.mat')); +baselineConc = baselineConcTemp.(BaselineFiles); +[o,~] = size(baselineConc); +for q = 2:o-2 + baselineConcIdxMet(1,q-1) = baselineConc{q,idxMet}; +end + +% MetConc = cell2mat(squeeze(dataTimeCourse(2:end,idxMet,:))); +MetConc = squeeze(dataTimeCourse(2:end,idxMet,:)); + +%calculate concentration change of data points with reference to baseline +[a,b] = size(MetConc); +for av = 1:a + for sub = 1:b + PercChange(av,sub) = (MetConc{av,sub}-baselineConcIdxMet(1,sub))/baselineConcIdxMet(1,sub)*100; + end +end + +% for k = 1:size(MetConc,1) +% PercChange_Mean(k) = mean(PercChange(k,:)); +% PercChange_Std(k) = std(PercChange(k,:)); +% end + +figure +x = linspace(16*5,(320*5-16*5),37)/60; +positions = 1:length(x)+0.5; +hold on +boxplot(PercChange','Labels',x,'positions',positions) +hold on +% plot([0,320*5/60],[0 0]) +plot([0,38],[0 0]) +xlabel 't / min'; ylabel 'Concentration change / %.' +if ~isempty(find(~cellfun(@isempty,strfind(ExpName,'Rest')))) + visualType = 'Rest'; +else + visualType = 'Stim' +end +title ([metabToFig, ' ', visualType,' time course, subjects excluded']) +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +set(gca,'FontWeight','bold'); +% xlim([0 320*5/60]); +xlim([0 38]) + +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:5 +% boxoff = [boxoff 320/60*i 320/60*i]; + boxoff = [boxoff 38/5*i 38/5*i]; + if i < 5 +% boxon = [boxon 320/60*i 320/60*i]; + boxon = [boxon 38/5*i 38/5*i]; + end +end +for ii = 1:2.5 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +set(gca,'XTick',[]) +set(gca, 'XTick', [0 320/60*1.34 320/60*1.34*2 320/60*1.34*3 320/60*1.34*4 320/60*1.34*5]); +set(gca,'XTickLabel',['0 ';'5 ';'10';'15';'20';'25']); +PathName = strcat(LCModelOutputPath,'SlAvTimeCourse/'); +if ~isempty(find(~cellfun(@isempty,strfind(ExpName,'Rest')))) + metabToFig = strcat(metabToFig,'_Rest'); +else + metabToFig = strcat(metabToFig,'_Stim'); +end +if ~isempty(find(~cellfun(@isempty,strfind(ExpName,'_v2')))) + if exist('excludeSubjects') & ~isempty(excludeSubjects) + fig2save = fullfile(PathName, strcat(metabToFig, '_v2', woBaseline, '_PercChange_Excluded_Boxplot.fig')); + else + fig2save = fullfile(PathName, strcat(metabToFig, '_v2', woBaseline, '_PercChange_Boxplot.fig')); + end +else + if exist('excludeSubjects') & ~isempty(excludeSubjects) + fig2save = fullfile(PathName, strcat(metabToFig, woBaseline, '_PercChange_Excluded_Boxplot.fig')); + else + fig2save = fullfile(PathName, strcat(metabToFig, woBaseline, '_PercChange_Boxplot.fig')); + end +end +savefig(fig2save) +end + +function createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,localBaselinePath,BaselineFiles,subjects,metabToFig,excludeSubjects,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +ExpName = strcat(ExpName, woBaseline); +exportFileMat = strcat(subjectsLCModelOutputPath,ExpName,'.mat'); + +if exist('excludeSubjects') & ~isempty(excludeSubjects) + n = length(ExpName); + m = length(excludeSubjects); + nstep = 1; + for j = 1:m + for i = 1:n + xx = find(~cellfun(@isempty,strfind(exportFileMat(i,1),excludeSubjects{j}))); + if ~isempty(xx) + excludeIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + ExpName([excludeIdx],:) = []; + exportFileMat([excludeIdx],:) = []; +end + +for k = 1:numel(exportFileMat) + tmp = load(exportFileMat{k}); + dataTimeCourse(:,:,k) = tmp.(ExpName{k}); +end + +metaboliteNames = dataTimeCourse(1,:,1); +indexMet = strcmp(metaboliteNames,metabToFig); +% idxMet = find(not(cellfun('isempty',indexMet))); +idxMet = find(indexMet == true); + +%Baseline concentration +if exist('excludeSubjects') & ~isempty(excludeSubjects) + BaselineFiles = strcat(BaselineFiles,'_Excluded'); +end +baselineConcFile = strcat(localBaselinePath,BaselineFiles); + +baselineConcTemp = load(strcat(baselineConcFile,'.mat')); +baselineConc = baselineConcTemp.(BaselineFiles); +[o,~] = size(baselineConc); +for q = 2:o-2 + baselineConcIdxMet(1,q-1) = baselineConc{q,idxMet}; +end + +[n,~,m] = size(dataTimeCourse); +for k = 2:n + for l = 1:m + MetConc(k-1,l) = dataTimeCourse(k,idxMet(1),l); + end +end + +%calculate concentration change of data points with reference to baseline +[a,b] = size(MetConc); +for av = 1:a + for sub = 1:b + PercChange(av,sub) = (MetConc{av,sub}-baselineConcIdxMet(1,sub))/baselineConcIdxMet(1,sub)*100; + end +end + +for k = 1:size(MetConc,1) + PercChange_Mean(k) = mean(PercChange(k,:)); + PercChange_Std(k) = std(PercChange(k,:)); +end + +figure +x = linspace(16*5,(320*5-16*5),37)/60; +hold on +errorbar(x,PercChange_Mean,PercChange_Std) +hold on +plot([0,320*5/60],[0 0]) +xlabel 't / min'; ylabel 'Concentration change / %.' +if ~isempty(find(~cellfun(@isempty,strfind(ExpName,'Rest')))) + visualType = 'Rest'; +else + visualType = 'Stim' +end +title ([metabToFig, ' ', visualType,' time course, subjects excluded']) +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +set(gca,'FontWeight','bold'); +xlim([0 320*5/60]); + +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:5 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < 5 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:2.5 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +PathName = strcat(LCModelOutputPath,'SlAvTimeCourse/'); +if ~isempty(find(~cellfun(@isempty,strfind(ExpName,'Rest')))) + metabToFig = strcat(metabToFig,'_Rest'); +else + metabToFig = strcat(metabToFig,'_Stim'); +end +if ~isempty(find(~cellfun(@isempty,strfind(ExpName,'_v2')))) + if exist('excludeSubjects') & ~isempty(excludeSubjects) + fig2save = fullfile(PathName, strcat(metabToFig, '_v2', woBaseline, '_PercChange_Excluded.fig')); + else + fig2save = fullfile(PathName, strcat(metabToFig, '_v2', woBaseline, '_PercChange.fig')); + end +else + if exist('excludeSubjects') & ~isempty(excludeSubjects) + fig2save = fullfile(PathName, strcat(metabToFig, woBaseline, '_PercChange_Excluded.fig')); + else + fig2save = fullfile(PathName, strcat(metabToFig, woBaseline, '_PercChange.fig')); + end +end +savefig(fig2save) +end + function createConcTimeCourseFigExcluded(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,excludeSubjects,metabToFig,woBaseline) if exist('woBaseline', 'var') & woBaseline == true woBaseline = '_woBaseline'; @@ -273,6 +543,7 @@ errorbar(x,MetConc_Mean,MetConc_Std) xlabel 't / min'; ylabel 'Concentration / a.u.' title ([metabToFig,' time course, subjects excluded']) set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +set(gca,'FontWeight','bold'); xlim([0 320*5/60]); yLimits = get(gca,'YLim'); @@ -341,6 +612,7 @@ errorbar(x,MetConc_Mean,MetConc_Std) xlabel 't / min'; ylabel 'Concentration / a.u.' title ([metabToFig,' time course']) set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +set(gca,'FontWeight','bold'); xlim([0 320*5/60]); yLimits = get(gca,'YLim'); diff --git a/fMRS_processing/doFitting_fMRS_SlidingAverage_Summed.m b/fMRS_processing/doFitting_fMRS_SlidingAverage_Summed.m new file mode 100644 index 0000000..679e37f --- /dev/null +++ b/fMRS_processing/doFitting_fMRS_SlidingAverage_Summed.m @@ -0,0 +1,700 @@ +function doFitting_fMRS_SlidingAverage_Summed() +clear; clc; close all; + +fitversion = 'v2'; +pathName = 'fMRS SlidingAverage data path'; +sampleCriteria = {'Output', 'LCModelConfig'}; +[localFilePathBase] = pathToDataFolder(pathName, sampleCriteria); + +visualType = 'Stim'; %'Stim', 'Rest' +BOLDType = '_woBOLDCorr'; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _withBOLDCorr64 +if strcmp(fitversion,'v2') + MMBType = '_MMBSummed_v2'; %_MMBIndFiltered, _MMBSummed, _MMBInd, _MMBSimulated +else + MMBType = '_MMBSummed'; %_MMBIndFiltered, _MMBSummed, _MMBInd, _MMBSimulated +end +nOfSpectra = 32; %how many spectra should be averaged? Need full PC+MC +nslidingAv = 8; %how many spectra should be skipped before next averaging +nBlocks = (320 - nOfSpectra)/nslidingAv + 1; %here 320 averages per .dat file acquired. nBlocks = #spectra after sliding average + +BlockNo = cell(1,nBlocks); +for k = 1:nBlocks + BlockNo{k} = strcat('_Av', num2str(k)); +end + +% subjects = {'2823';}; +subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... + '4085';'3333';'4012';'4085';'6524'}; +% prefixes = {'2020-02-18_';}; +prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... + '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... + '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; +excludeSubjects = {'5166';'9810';'5269'}; +suffixFolder = '_fMRS'; + +if exist('excludeSubjects','var') + n = length(subjects); + m = length(excludeSubjects); + nstep = 1; + for j = 1:m + for i = 1:n + xx = find(~cellfun(@isempty,strfind(subjects(i,1),excludeSubjects{j}))); + if ~isempty(xx) + excludeIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + subjects([excludeIdx],:) = []; + prefixes([excludeIdx],:) = []; +end +numberOfSubjects = length(subjects); + +extensionTable = '.table'; +extensionCoord = '.coord'; +defaultVisual = 'Stim'; +defaultSubject = 'XXXX'; +defaultSubjectsPath = 'YYYY'; +if fitversion == 'v2' + defaultMMB = '_MMBSummed_v2'; +else + defaultMMB = '_MMBSummed'; +end +defaultLCModelUser = 'jdorst'; +defaultWaterRef = 'XXXX_WRef'; + +if fitversion == 'v2' + controlFilesBase = 'fitsettings_v2_XXXX_'; +else + controlFilesBase = 'fitsettings_XXXX_'; +end +controlFilesBaseSuffix = '.control'; +outputFileNameBase = strcat(defaultSubject, '_'); +outputFileNameBase_WRef = strcat(defaultSubject, '_WRef'); + +pathNameBaseline = 'fMRS TimeCourse data path'; +sampleCriteriaBaseline = {'Output_v2_MMBSummed', 'Output', 'LCModelConfig'}; +[localFilePathBaseBaseline] = pathToDataFolder(pathNameBaseline, sampleCriteriaBaseline); +if fitversion == 'v2' + localBaselinePath = [localFilePathBaseBaseline, 'Output_v2_MMBSummed/']; + BaselineFiles = strcat('BaselineConc_',num2str(visualType), BOLDType, MMBType); +else + localBaselinePath = [localFilePathBaseBaseline, 'Output/']; + BaselineFiles = strcat('BaselineConc_',num2str(visualType), BOLDType, MMBType); +end + +%% file paths setup +controlFilesPathRemote = '/Desktop/1H_fMRS/LCModelConfig/'; +controlFilesPathLocal = [localFilePathBase, 'LCModelConfig/']; +LCModelOutputFilesPathRemote = '/Desktop/1H_fMRS/Output/'; +LCModelOutputPath = [localFilePathBase, 'Output/']; +defaultControlFile = strcat(controlFilesBase, defaultVisual, controlFilesBaseSuffix); + +subjectsPath = strcat(prefixes, subjects, suffixFolder); +summedPath = 'Summed_fMRSData'; + +subjectsControlFilesPathRemote = strcat(controlFilesPathRemote, summedPath, '/'); +subjectsControlFilesPathLocal = strcat(controlFilesPathLocal, summedPath, '/'); +preprocessedFilesPathLocal = strcat(localFilePathBase, summedPath, '/'); +subjectsLCModelOutputFilesRemote = strcat(LCModelOutputFilesPathRemote, summedPath, '/'); +subjectsLCModelOutputPath = strcat(LCModelOutputPath, summedPath, '/'); + + +%% sum fMRS spectra of all volunteers, weighted with water fit (need to run +%doFitting_fMRS_Water.m & doFitting_fMRS_SlidingAverage.m first) +% WaterReferenceTable = (readtable(strcat(LCModelOutputPath,'WaterReference_Fit.xlsx'))); +% WaterReferenceID = table2cell(WaterReferenceTable(2:end,1)); +% WaterReference = str2double(table2array(WaterReferenceTable(2:end,2:end))); +% for indexCurrentSubject = 1:numberOfSubjects +% for nBl = 1:nBlocks +% idx = find(ismember(WaterReferenceID, strcat(prefixes{indexCurrentSubject}, subjects{indexCurrentSubject}))); +% currentScalingFactor = WaterReference(idx,1); +% currentfMRSDataPath = strcat(localFilePathBase,subjectsPath{indexCurrentSubject},'\'); +% currentDataFile = strcat(subjects{indexCurrentSubject},'_',visualType,'_woBOLDCorr','_Av',num2str(nBl),'.mat'); +% load([currentfMRSDataPath,currentDataFile]); +% currentfMRSData = squeeze(this.Data{1}); +% currentfMRSDataScaled = currentfMRSData./currentScalingFactor; +% fMRSDataScaled(:,:,indexCurrentSubject,nBl) = currentfMRSDataScaled; +% end +% end +% %sum over all subjects +% fMRSData_Summed = squeeze(sum(fMRSDataScaled,3)); +% %save summed data +% for nBl = 1:nBlocks +% current_fMRSData_Summed = fMRSData_Summed(:,:,nBl); +% current_fMRSData_Summed = permute(current_fMRSData_Summed,[1 3 4 5 6 7 8 9 2]); +% this.Data{1} = current_fMRSData_Summed; +% fMRSData_Summed_Path = strcat(localFilePathBase,summedPath); +% this.Parameter.Filepath = fMRSData_Summed_Path; +% this.Parameter.Filename = strcat('fMRSData_Summed_',visualType,BOLDType,'_SlidingAverages'); +% if exist('excludeSubjects','var') +% this.Parameter.Filename = strcat('fMRSData_Summed_',visualType,BOLDType,'_SlidingAverages_Excluded_Av',num2str(nBl)); +% exportFile = strcat(fMRSData_Summed_Path,'\Summed_',visualType,BOLDType,'_Excluded_Av',num2str(nBl)); +% else +% this.Parameter.Filename = strcat('fMRSData_Summed_',visualType,BOLDType,'_SlidingAverages_Av',num2str(nBl)); +% exportFile = strcat(fMRSData_Summed_Path,'\Summed_',visualType,BOLDType,'_Av',num2str(nBl)); +% end +% save(strcat(exportFile,'.mat'),'this') +% this.ExportLcmRaw('',exportFile, 'Yes', 'Yes'); +% end + +%% sum Water reference spectra of all volunteers, weighted with water fit (need to run doFitting_fMRS_Water.m first) +% WaterReferenceTable = (readtable(strcat(LCModelOutputPath,'WaterReference_Fit.xlsx'))); +% WaterReferenceID = table2cell(WaterReferenceTable(2:end,1)); +% WaterReference = str2double(table2array(WaterReferenceTable(2:end,2:end))); +% WRefDataScaled = zeros(4096,numberOfSubjects); %samples, subjects, data/water +% for indexCurrentSubject = 1:numberOfSubjects +% idx = find(ismember(WaterReferenceID, strcat(prefixes{indexCurrentSubject}, subjects{indexCurrentSubject}))); +% currentScalingFactor = WaterReference(idx,1); +% currentWRefDataPath = strcat(localFilePathBase,subjectsPath{indexCurrentSubject}); +% load(strrep(strcat(currentWRefDataPath, '\',outputFileNameBase_WRef,'.mat'),defaultSubject,subjects{indexCurrentSubject})); +% currentfMRSData_WRef = squeeze(a.Data{1}); +% currentfMRSDataScaled_WRef = currentfMRSData_WRef./currentScalingFactor; +% WRefDataScaled(:,indexCurrentSubject) = currentfMRSDataScaled_WRef; +% end +% %sum over all subjects +% fMRSData_Summed_WRef = squeeze(sum(WRefDataScaled,2)); +% %save summed data +% this = a; +% this.Data{1} = fMRSData_Summed_WRef; +% this.Parameter.Filepath = fMRSData_Summed_Path; +% this.Parameter.Filename = 'fMRSData_Summed_WRef'; +% if exist('excludeSubjects','var') +% exportFileWRef = strcat(fMRSData_Summed_Path,'\WRef_Summed_Excluded'); +% else +% exportFileWRef = strcat(fMRSData_Summed_Path,'\WRef_Summed'); +% end +% save(strcat(exportFileWRef,'.mat'),'this') +% this.ExportLcmRaw('',exportFileWRef, 'Yes', 'Yes'); + +%% do the LCModel fitting +if exist('excludeSubjects','var') + LCModelOutputFiles = strcat('Summed_', visualType, MMBType, '_Excluded', BlockNo); + LCModelOutputFileswoBaseline = strcat('Summed_', visualType, MMBType, '_Excluded', BlockNo, '_woBaseline'); + LCModelControlFiles = strcat(controlFilesBase, 'Summed_', visualType, MMBType, '_Excluded', BlockNo, controlFilesBaseSuffix); + LCModelControlFileswoBaseline = strcat(controlFilesBase, 'Summed_', visualType, MMBType, '_Excluded', BlockNo, '_woBaseline', controlFilesBaseSuffix); + waterRefFileName = 'WRef_Summed_Excluded'; +else + LCModelOutputFiles = strcat('Summed_', visualType, MMBType, BlockNo); + LCModelOutputFileswoBaseline = strcat('Summed_', visualType, MMBType, BlockNo, '_woBaseline'); + LCModelControlFiles = strcat(controlFilesBase, 'Summed_', visualType, MMBType, BlockNo, controlFilesBaseSuffix); + LCModelControlFileswoBaseline = strcat(controlFilesBase, 'Summed_', visualType, MMBType, BlockNo, '_woBaseline', controlFilesBaseSuffix); + waterRefFileName = 'WRef_Summed'; +end + + +%% do the LCModel fitting +% LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); +% +% LCModelCallerInstance = LCModelCallerInstance.ConfigurePaths(subjectsControlFilesPathRemote, subjectsLCModelOutputFilesRemote, ... +% subjectsLCModelOutputPath); +% +% if strcmp(fitversion,'v2') +% currentControlFiles = strrep(LCModelControlFiles, strcat('_v2_',defaultSubject), ''); +% else +% currentControlFiles = strrep(LCModelControlFiles, strcat('_',defaultSubject), ''); +% end +% currentOutputFiles = strrep(LCModelOutputFiles,'Corr','Corr_v2'); +% +% +% % create the control file series +% for nBl = 1:nBlocks +% currentOutputFile = currentOutputFiles{nBl}; +% if exist('excludeSubjects','var') +% currentFMRS = strcat(visualType,BOLDType,'_Excluded'); +% else +% currentFMRS = strcat(visualType,BOLDType); +% end +% createLCModelConfigfMRSTimeCourse(controlFilesPathLocal, subjectsControlFilesPathLocal, defaultControlFile, ... +% currentFMRS, defaultVisual, currentOutputFile,... +% waterRefFileName, defaultWaterRef, 'Summed_fMRSData', defaultSubjectsPath, 'Summed',... +% defaultSubject, MMBType, defaultMMB, BlockNo{nBl}); +% end +% if exist('excludeSubjects','var') +% currentOutputFilesLCModel = strcat('Summed_',visualType,BOLDType,'_Excluded',MMBType,BlockNo); +% else +% currentOutputFilesLCModel = strcat('Summed_',visualType,BOLDType,MMBType,BlockNo); +% end +% fittingLCModel(LCModelCallerInstance, currentControlFiles, currentOutputFilesLCModel, subjectsControlFilesPathRemote, ... +% subjectsControlFilesPathLocal, preprocessedFilesPathLocal); + +%% +%%% doesn't exist in Data_TimeCourse, but same as nBl = 5 (33-64 average) +% % Create and save table with baseline concentrations fitted with baseline, taken from second block of first REST +% createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... +% LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,0) + +% % Create and save table from fitted concentrations with baseline, taken from +% % all blocks +% if exist('excludeSubjects','var') +% createConcTableBlock(BlockNo,currentOutputFilesLCModel,defaultSubject,'Summed',... +% LCModelOutputPath,'Summed_fMRSData',visualType,strcat(BOLDType,'_Excl'),MMBType,0) +% else +% createConcTableBlock(BlockNo,currentOutputFilesLCModel,defaultSubject,'Summed',... +% LCModelOutputPath,'Summed_fMRSData',visualType,BOLDType,MMBType,0) +% end + +%% subtract baseline from difference spectrum and fit again +%only useful for MMBSummed +if strcmp(MMBType(1:10),'_MMBSummed') + %% do the LCModel fitting +% LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); +% +% LCModelCallerInstance = LCModelCallerInstance.ConfigurePaths(subjectsControlFilesPathRemote, subjectsLCModelOutputFilesRemote, ... +% subjectsLCModelOutputPath); +% % +% if fitversion == 'v2' +% currentControlFileswoBaseline = strrep(LCModelControlFileswoBaseline, strcat('_v2_',defaultSubject), ''); +% else +% currentControlFileswoBaseline = strrep(LCModelControlFileswoBaseline, strcat('_',defaultSubject), ''); +% end +% if exist('excludeSubjects','var') +% currentDataFiles = strrep(strcat(outputFileNameBase, visualType, BOLDType, '_Excluded', BlockNo), defaultSubject, 'Summed'); +% else +% currentDataFiles = strrep(strcat(outputFileNameBase, visualType, BOLDType, BlockNo), defaultSubject, 'Summed'); +% end +% +% if exist('excludeSubjects','var') +% currentOutputFileswoBaseline = strcat('Summed_',visualType,BOLDType,'_Excluded',MMBType,BlockNo); +% else +% currentOutputFileswoBaseline = strcat('Summed_',visualType,BOLDType,MMBType,BlockNo); +% end +% currentDataPath = strcat(localFilePathBase,'Summed_fMRSData\'); +% for nBl = 1:nBlocks +% %check save option for .mat file in subtractBaseline_fMRS +% subtractBaseline_fMRS(currentDataPath,subjectsLCModelOutputPath,currentDataFiles{nBl},currentOutputFileswoBaseline{nBl},'NAA') +% currentFitsettingsOutputFileswoBaseline = LCModelOutputFileswoBaseline{nBl}; +% if exist('excludeSubjects','var') +% currentFMRS = strcat(visualType,BOLDType,'_Excluded'); +% else +% currentFMRS = strcat(visualType,BOLDType); +% end +% createLCModelConfigfMRSTimeCourse(controlFilesPathLocal, subjectsControlFilesPathLocal, defaultControlFile, ... +% currentFMRS, defaultVisual, currentFitsettingsOutputFileswoBaseline,... +% waterRefFileName, defaultWaterRef, 'Summed_fMRSData', defaultSubjectsPath, 'Summed',... +% defaultSubject, MMBType, defaultMMB, strcat(BlockNo{nBl}, '_woBaseline')); +% end +% if exist('excludeSubjects','var') +% currentOutputFilesLCModelwoBaseline = strcat('Summed_',visualType,BOLDType,'_Excluded',MMBType,BlockNo,'_woBaseline'); +% else +% currentOutputFilesLCModelwoBaseline = strcat('Summed_',visualType,BOLDType,MMBType,BlockNo,'_woBaseline'); +% end +% fittingLCModel(LCModelCallerInstance, currentControlFileswoBaseline, currentOutputFilesLCModelwoBaseline, subjectsControlFilesPathRemote, ... +% subjectsControlFilesPathLocal, preprocessedFilesPathLocal); + + %% not useful here, take it from Data_TimeCourse + % Create and save table with baseline concentrations fitted w/o baseline, taken from second block of first REST + % createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... + % LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,1) + + % Create and save table from fitted concentrations w/o baseline, taken from all blocks +% if exist('excludeSubjects','var') +% createConcTableBlock(BlockNo,currentOutputFilesLCModelwoBaseline,defaultSubject,'Summed',... +% LCModelOutputPath,'Summed_fMRSData',visualType,strcat(BOLDType,'_Excl'),MMBType,1) +% else +% createConcTableBlock(BlockNo,currentOutputFilesLCModelwoBaseline,defaultSubject,'Summed',... +% LCModelOutputPath,'Summed_fMRSData',visualType,BOLDType,MMBType,1) +% end +end + + +%% create concentration time course from fit with and w/o Baseline +if exist('excludeSubjects','var') + ExpName = strcat('BlockConc_Summed_', num2str(visualType), strcat(BOLDType,'_Excl'), MMBType); +else + ExpName = strcat('BlockConc_Summed_', num2str(visualType), BOLDType, MMBType); +end + +% createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,'PCr',0) +% createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,'Cr',0) + +createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,'Cr',0) +createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,'PCr',0) +if strcmp(MMBType(1:10),'_MMBSummed') + createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,'PCr',1) + createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,'Cr',1) + + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,'Cr',1) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,'PCr',1) +end + +close all + +end + +function createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,metabToFig,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +ExpName = strcat(ExpName, woBaseline); +exportFileMat = strcat(subjectsLCModelOutputPath,ExpName,'.mat'); + +tmp = load(exportFileMat); +dataTimeCourse(:,:) = tmp.(ExpName); + +metaboliteNames = dataTimeCourse(1,:); +indexMet = strcmp(metaboliteNames,metabToFig); +idxMet = find(indexMet == true); + +%Baseline concentration, equals 5th sliding average +baselineConcIdxMet = dataTimeCourse{6,idxMet}; + +[n,~] = size(dataTimeCourse); +for k = 2:n + MetConc(k-1) = dataTimeCourse(k,idxMet(1)); +end + +%calculate concentration change of data points with reference to baseline +[~,b] = size(MetConc); +for av = 1:b + PercChange(av) = (MetConc{1,av}-baselineConcIdxMet)/baselineConcIdxMet*100; +end + +figure +x = linspace(16*5,(320*5-16*5),37)/60; +hold on +plot(x,PercChange) +hold on +plot([0,320*5/60],[0 0]) +xlabel 't / min'; ylabel 'Concentration change / %.' +if ~isempty(strfind(ExpName,'Rest')) + visualType = 'Rest'; +else + visualType = 'Stim'; +end +title ([metabToFig,', ',ExpName], 'Interpreter', 'none') +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +xlim([0 320*5/60]); + +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:5 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < 5 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:2.5 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +PathName = strcat(LCModelOutputPath,'SlAvTimeCourse/'); + +if ~isempty(strfind(ExpName,'Rest')) + metabToFig = strcat(metabToFig,'_Rest_Summed'); +else + metabToFig = strcat(metabToFig,'_Stim_Summed'); +end +if ~isempty(strfind(ExpName,'_v2')) + if ~isempty(strfind(ExpName,'Excl')) + fig2save = fullfile(PathName, strcat(metabToFig, '_v2', woBaseline, '_PercChange_Excluded.fig')); + else + fig2save = fullfile(PathName, strcat(metabToFig, '_v2', woBaseline, '_PercChange.fig')); + end +else + if ~isempty(strfind(ExpName,'Excl')) + fig2save = fullfile(PathName, strcat(metabToFig, woBaseline, '_PercChange_Excluded.fig')); + else + fig2save = fullfile(PathName, strcat(metabToFig, woBaseline, '_PercChange.fig')); + end +end +savefig(fig2save) +end + +function createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,metabToFig,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +ExpName = strcat(ExpName, woBaseline); +exportFileMat = strcat(subjectsLCModelOutputPath,ExpName,'.mat'); + +tmp = load(exportFileMat); +dataTimeCourse(:,:) = tmp.(ExpName); + +metaboliteNames = dataTimeCourse(1,:,1); +indexMet = strcmp(metaboliteNames,metabToFig); +idxMet = find(indexMet == true); + +[n,~] = size(dataTimeCourse); +for k = 2:n + MetConc(k-1) = dataTimeCourse(k,idxMet(1)); +end + +figure +x = linspace(16*5,(320*5-16*5),37)/60; +hold on +% errorbar(x,MetConc_Mean,MetConc_Std) +plot(x,cell2mat(MetConc)) +xlabel 't / min'; ylabel 'Concentration / a.u.' +title ([metabToFig,', ',ExpName], 'Interpreter', 'none') +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +xlim([0 320*5/60]); + +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:5 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < 5 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:2.5 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +PathName = strcat(LCModelOutputPath,'SlAvTimeCourse/'); +if ~isempty(strfind(ExpName,'Rest')) + metabToFig = strcat(metabToFig,'_Rest_Summed'); +else + metabToFig = strcat(metabToFig,'_Stim_Summed'); +end +if ~isempty(strfind(ExpName,'_v2')) + if ~isempty(strfind(ExpName,'Excl')) + fig2save = fullfile(PathName, strcat(metabToFig, '_v2', woBaseline, '_Excluded.fig')); + else + fig2save = fullfile(PathName, strcat(metabToFig, '_v2', woBaseline, '.fig')); + end +else + if ~isempty(strfind(ExpName,'Excl')) + fig2save = fullfile(PathName, strcat(metabToFig, woBaseline, '_Excluded.fig')); + else + fig2save = fullfile(PathName, strcat(metabToFig, woBaseline, '.fig')); + end +end +savefig(fig2save) +end + +% function createConcTimeCourseFig(ExpName,LCModelOutputPath,subjectsLCModelOutputPath,subjects,metabToFig,woBaseline) +% if exist('woBaseline', 'var') & woBaseline == true +% woBaseline = '_woBaseline'; +% else +% woBaseline = ''; +% end +% ExpName = strcat(ExpName, woBaseline); +% +% exportFileMat = strcat(subjectsLCModelOutputPath,ExpName,'.mat'); +% +% for k = 1:numel(exportFileMat) +% tmp = load(exportFileMat{k}); +% dataTimeCourse(:,:,k) = tmp.(ExpName{k}); +% end +% +% metaboliteNames = dataTimeCourse(1,:,1); +% indexMet = strcmp(metaboliteNames,metabToFig); +% % idxMet = find(not(cellfun('isempty',indexMet))); +% idxMet = find(indexMet == true); +% +% [n,~,m] = size(dataTimeCourse); +% for k = 2:n +% for l = 1:m +% MetConc(k-1,l) = dataTimeCourse(k,idxMet(1),l); +% end +% end +% +% for k = 1:size(MetConc,1) +% MetConc_Mean(k) = mean(cell2mat(MetConc(k,:))); +% MetConc_Std(k) = std(cell2mat(MetConc(k,:))); +% end +% +% figure +% x = linspace(16*5,(320*5-16*5),37)/60; +% hold on; +% errorbar(x,MetConc_Mean,MetConc_Std) +% xlabel 't / min'; ylabel 'Concentration / a.u.' +% title ([metabToFig,' time course']) +% set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +% xlim([0 320*5/60]); +% +% yLimits = get(gca,'YLim'); +% boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +% for i = 1:5 +% boxoff = [boxoff 320/60*i 320/60*i]; +% if i < 5 +% boxon = [boxon 320/60*i 320/60*i]; +% end +% end +% for ii = 1:2.5 +% boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +% boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +% end +% patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +% patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +% ylim([yLimits(1) yLimits(2)]); +% PathName = strcat(LCModelOutputPath,'SlAvTimeCourse/'); +% if ~isempty(find(~cellfun(@isempty,strfind(ExpName,'v2')))) +% fig2save = fullfile(PathName, strcat(metabToFig, '_v2', woBaseline, '.fig')); +% else +% fig2save = fullfile(PathName, strcat(metabToFig, woBaseline, '.fig')); +% end +% savefig(fig2save) +% end + +function createConcTableBlock(BlockNo,LCModelOutputFiles,defaultSubject,subjects,... + LCModelOutputPath,subjectsPath,visualType,BOLDType,MMBType,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +tableConcentrations = []; +isFirstIter = 1; +s = 1; + for nBl = 1:length(BlockNo) + % retrieve parameters + currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, subjects); + currentPath = strcat(LCModelOutputPath,subjectsPath,'/',currentOutputFiles{nBl},'.table'); + [c1 c2 c3 c4] = textread(currentPath,'%s %s %s %s'); + + if isFirstIter + start = find(strcmp(c1,'Conc.')); + start = start + 1; + finish = find(strcmpi(c1,'$$MISC')) - 1; + tableConcentrations{1,1} = 'ID'; + + s = 2; + for j=start:finish + if(strcmp(c4{j},'')==1) + c3_split = strsplit(c3{j},'+'); + if length(c3_split) == 1 + c3_split = strsplit(c3{j},'-'); + end + tableConcentrations{1,s} = c3_split{2}; + else + tableConcentrations{1,s} = c4{j}; + if length(tableConcentrations{1,s}) == 3 & tableConcentrations{1,s} == 'Leu' + tableConcentrations{1,s} = 'MMB'; + end + end + tableConcentrations{1,s+1} = 'CRLB %'; + s = s + 2; + end + tableConcentrations{1,s} = 'water concentration'; + end + + % add ID and Water conc to table + tableConcentrations{nBl+1,1} = strcat(subjects, '_', visualType, BlockNo{nBl}); + index_wconc = find(strcmp(c1,'wconc=')); + wconc_LCModel = str2num(c2{index_wconc}); + tableConcentrations{nBl+1,end} = wconc_LCModel; + % add metabolites to table + s = 2; + for j=start:finish + % add quantified metabolite + tableConcentrations{nBl+1,s} = str2num( c1{j}); + % add CRLB + tableConcentrations{nBl+1,s+1} = str2num( c2{j}(1:end-1)); + s = s+2; + end + + isFirstIter = false; + + end + +% save table to file +ExpName = strcat('BlockConc_', subjects, '_', num2str(visualType), BOLDType, MMBType, woBaseline); +exportFileXlsx = [LCModelOutputPath,subjectsPath,'/',strcat(ExpName,'.xlsx')]; +xlswrite(exportFileXlsx, {LCModelOutputPath}, 1, 'A1'); +cellPosition = 'A2'; +xlswrite(exportFileXlsx, tableConcentrations, 1, cellPosition); + +exportFileMat = [LCModelOutputPath,subjectsPath,'/',strcat(ExpName,'.mat')]; +eval([ExpName '= tableConcentrations']); %use of eval not recommended, change it +save(exportFileMat, ExpName) +end + +function createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... + LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +tableConcentrations = []; +isFirstIter = 1; +s = 1; +for indexCurrentSubject = 1:numberOfSubjects + for nBl = 2 %take baseline from second block of first REST + % retrieve parameters + currentOutputFiles = strrep(strcat(LCModelOutputFiles,woBaseline), defaultSubject, subjects{indexCurrentSubject}); + currentPath = strcat(LCModelOutputPath,subjectsPath{indexCurrentSubject},'/',currentOutputFiles{nBl},'.table'); + [c1 c2 c3 c4] = textread(currentPath,'%s %s %s %s'); + + if isFirstIter + start = find(strcmp(c1,'Conc.')); + start = start + 1; + finish = find(strcmpi(c1,'$$MISC')) - 1; + tableConcentrations{1,1} = 'ID'; + + s = 2; + for j=start:finish + if(strcmp(c4{j},'')==1) + c3_split = strsplit(c3{j},'+'); + if length(c3_split) == 1 + c3_split = strsplit(c3{j},'-'); + end + tableConcentrations{1,s} = c3_split{2}; + else + tableConcentrations{1,s} = c4{j}; + if length(tableConcentrations{1,s}) == 3 & tableConcentrations{1,s} == 'Leu' + tableConcentrations{1,s} = 'MMB'; + end + end + tableConcentrations{1,s+1} = 'CRLB %'; + s = s + 2; + end + tableConcentrations{1,s} = 'water concentration'; + end + + % add ID and Water conc to table + tableConcentrations{indexCurrentSubject+1,1} = strcat(prefixes{indexCurrentSubject}, subjects{indexCurrentSubject}, BlockNo{nBl}); + index_wconc = find(strcmp(c1,'wconc=')); + wconc_LCModel = str2num(c2{index_wconc}); + tableConcentrations{indexCurrentSubject+1,end} = wconc_LCModel; + % add metabolites to table + s = 2; + for j=start:finish + %add quantified metabolite + tableConcentrations{indexCurrentSubject+1,s} = str2num( c1{j}); + %add CRLB + tableConcentrations{indexCurrentSubject+1,s+1} = str2num( c2{j}(1:end-1)); + s = s+2; + end + + isFirstIter = false; + + end +end + +%calculate mean, std +[n,m] = size(tableConcentrations); +subArray = cell2mat(tableConcentrations(2:end,2:end)); +meanValue = mean(subArray); +stdValue = std(subArray); +tableConcentrations{n+1,1} = 'mean'; +tableConcentrations{n+2,1} = 'std'; +for indexOfMetab = 1:m-1 + tableConcentrations{n+1,indexOfMetab+1} = meanValue(1,indexOfMetab); + tableConcentrations{n+2,indexOfMetab+1} = stdValue(1,indexOfMetab); +end + +% save table to file +ExpName = strcat('BaselineConc_', num2str(visualType), BOLDType, MMBType, woBaseline); +exportFileXlsx = [LCModelOutputPath ,strcat(ExpName,'.xlsx')]; +xlswrite(exportFileXlsx, {LCModelOutputPath}, 1, 'A1'); +cellPosition = 'A2'; +xlswrite(exportFileXlsx, tableConcentrations, 1, cellPosition); + +exportFileMat = [LCModelOutputPath ,strcat(ExpName,'.mat')]; +eval([ExpName '= tableConcentrations']); %use of eval not recommended, change it +save(exportFileMat, ExpName) +end \ No newline at end of file diff --git a/fMRS_processing/doFitting_fMRS_TimeCourse.m b/fMRS_processing/doFitting_fMRS_TimeCourse.m index 8e60958..ef79288 100644 --- a/fMRS_processing/doFitting_fMRS_TimeCourse.m +++ b/fMRS_processing/doFitting_fMRS_TimeCourse.m @@ -1,12 +1,15 @@ function doFitting_fMRS_TimeCourse() clear; clc; close all; +allVisTypes = {'Stim', 'Rest'}; %'Stim', 'Rest' + +for i = 1:length(allVisTypes) pathName = 'fMRS TimeCourse data path'; sampleCriteria = {'Output', 'LCModelConfig'}; [localFilePathBase] = pathToDataFolder(pathName, sampleCriteria); -visualType = 'Rest'; %'Stim', 'Rest' -BOLDType = '_woBOLDCorr'; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _withBOLDCorr64 -MMBType = '_MMBSummed'; %_MMBIndFiltered, _MMBSummed, _MMBInd, _MMBSimulated +visualType = allVisTypes{i}; %'Stim', 'Rest' +BOLDType = '_woBOLDCorr'; %only _woBOLDCorr reasonable since block wise fitting for metabolite time courses +MMBType = '_MMBSummed_v2'; %_MMBIndFiltered, _MMBSummed, _MMBInd, _MMBSimulated % nBlocks = 5; nBlocks = 10; @@ -30,12 +33,20 @@ extensionCoord = '.coord'; defaultVisual = 'Stim'; defaultSubject = 'XXXX'; defaultSubjectsPath = 'YYYY'; -defaultMMB = '_MMBSummed'; +if ~isempty(strfind(MMBType,'_v2')) + defaultMMB = '_MMBSummed_v2'; +else + defaultMMB = '_MMBSummed'; +end defaultLCModelUser = 'jdorst'; outputFileNameBaseWithoutMetabolite_OFF = strcat(defaultSubject, '_StimOFF_woBOLDCorr128'); outputFileNameBaseWithoutMetabolite_ON = strcat(defaultSubject, '_StimON_woBOLDCorr128'); -controlFilesBase = 'fitsettings_XXXX_'; +if ~isempty(strfind(MMBType,'_v2')) + controlFilesBase = 'fitsettings_v2_XXXX_'; +else + controlFilesBase = 'fitsettings_XXXX_'; +end controlFilesBaseSuffix = '.control'; outputFileNameBase = strcat(defaultSubject, '_'); @@ -43,7 +54,11 @@ outputFileNameBase = strcat(defaultSubject, '_'); controlFilesPathRemote = '/Desktop/1H_fMRS/LCModelConfig/'; controlFilesPathLocal = [localFilePathBase, 'LCModelConfig/']; LCModelOutputFilesPathRemote = '/Desktop/1H_fMRS/Output/'; -LCModelOutputPath = [localFilePathBase, 'Output/']; +if ~isempty(strfind(MMBType,'_v2')) + LCModelOutputPath = [localFilePathBase, 'Output_v2_MMBSummed/']; +else + LCModelOutputPath = [localFilePathBase, 'Output/']; +end defaultControlFile = strcat(controlFilesBase, defaultVisual, controlFilesBaseSuffix); subjectsPath = strcat(prefixes, subjects, suffixFolder); @@ -94,6 +109,7 @@ numberOfSubjects = length(subjects); % subjectsLCModelOutputPath{indexCurrentSubject}); % % currentControlFiles = strrep(LCModelControlFiles, defaultSubject, subjects{indexCurrentSubject}); +% currentControlFiles = strrep(currentControlFiles,'fitsettings_v2_','fitsettings_'); % currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, subjects{indexCurrentSubject}); % waterRefFileName = strrep(defaultWaterRef, defaultSubject, subjects{indexCurrentSubject}); % @@ -113,17 +129,22 @@ numberOfSubjects = length(subjects); % end % % % Create and save table with baseline concentrations fitted with baseline, taken from second block of first REST -% createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... -% LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,0) +% if exist('excludeSubjects') +% createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... +% LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,0,excludeSubjects) +% else +% createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... +% LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,0) +% end % % % Create and save table from fitted concentrations with baseline, take from blocks 3-10 % createConcTableBlock(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... % LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,0) %% subtract baseline from difference spectrum and fit again -%only useful for MMBSummed +% only useful for MMBSummed % if strcmp(MMBType(1:10),'_MMBSummed') -% LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); +% % LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); % parfor indexCurrentSubject = 1:numberOfSubjects % %% do the LCModel fitting % LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); @@ -132,7 +153,12 @@ numberOfSubjects = length(subjects); % subjectsLCModelOutputPath{indexCurrentSubject}); % % currentControlFileswoBaseline = strrep(LCModelControlFileswoBaseline, defaultSubject, subjects{indexCurrentSubject}); -% currentDataFiles = strrep(strcat(outputFileNameBase, visualType, BOLDType, BlockNo), defaultSubject, subjects{indexCurrentSubject}); +% currentControlFileswoBaseline = strrep(currentControlFileswoBaseline,'fitsettings_v2_','fitsettings_'); +% if ~isempty(strfind(MMBType,'_v2')) +% currentDataFiles = strrep(strcat(outputFileNameBase, visualType, BOLDType, '_v2', BlockNo), defaultSubject, subjects{indexCurrentSubject}); +% else +% currentDataFiles = strrep(strcat(outputFileNameBase, visualType, BOLDType, BlockNo), defaultSubject, subjects{indexCurrentSubject}); +% end % currentOutputFileswoBaseline = strrep(LCModelOutputFileswoBaseline, defaultSubject, subjects{indexCurrentSubject}); % currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, subjects{indexCurrentSubject}); % waterRefFileName = strrep(defaultWaterRef, defaultSubject, subjects{indexCurrentSubject}); @@ -152,8 +178,13 @@ numberOfSubjects = length(subjects); % end % % % Create and save table with baseline concentrations fitted w/o baseline, taken from second block of first REST -% createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... +% if exist('excludeSubjects') +% createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... +% LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,1,excludeSubjects) +% else +% createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... % LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,1) +% end % % % Create and save table from fitted concentrations w/o baseline, taken from blocks 3-10 % createConcTableBlock(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... @@ -166,21 +197,188 @@ ExpName = strcat('BlockConc_', num2str(visualType), BOLDType, MMBType); if exist('excludeSubjects') createConcTimeCourseFig(ExpName,LCModelOutputPath,subjects,nBlocks,'Lac',0,excludeSubjects) createConcTimeCourseFig(ExpName,LCModelOutputPath,subjects,nBlocks,'Glu',0,excludeSubjects) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjects,nBlocks,'Lac',0,excludeSubjects) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjects,nBlocks,'Glu',0,excludeSubjects) if strcmp(MMBType(1:10),'_MMBSummed') createConcTimeCourseFig(ExpName,LCModelOutputPath,subjects,nBlocks,'Lac',1,excludeSubjects) createConcTimeCourseFig(ExpName,LCModelOutputPath,subjects,nBlocks,'Glu',1,excludeSubjects) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjects,nBlocks,'Lac',1,excludeSubjects) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjects,nBlocks,'Glu',1,excludeSubjects) end else createConcTimeCourseFig(ExpName,LCModelOutputPath,subjects,nBlocks,'Lac',0) createConcTimeCourseFig(ExpName,LCModelOutputPath,subjects,nBlocks,'Glu',0) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjects,nBlocks,'Lac',0) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjects,nBlocks,'Glu',0) if strcmp(MMBType(1:10),'_MMBSummed') createConcTimeCourseFig(ExpName,LCModelOutputPath,subjects,nBlocks,'Lac',1) createConcTimeCourseFig(ExpName,LCModelOutputPath,subjects,nBlocks,'Glu',1) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjects,nBlocks,'Lac',1) + createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjects,nBlocks,'Glu',1) end end close all end +end + +function createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,subjects,nBlocks,metabToFig,woBaseline,excludeSubjects) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +ExpName = strcat(ExpName, woBaseline); + +exportFileMat = [LCModelOutputPath ,strcat(ExpName,'.mat')]; +dataTimeCourse = load(exportFileMat); +fields = fieldnames(dataTimeCourse); +dataTimeCourse = dataTimeCourse.(fields{1}); +metaboliteNames = (dataTimeCourse(1,:)); +indexMet = strfind(metaboliteNames,metabToFig); +idxMet = find(not(cellfun('isempty',indexMet))); + +if exist('excludeSubjects') + n = length(dataTimeCourse); + m = length(excludeSubjects); + nstep = 1; + for j = 1:m + for i = 1:n + xx = find(~cellfun(@isempty,strfind(dataTimeCourse(i,1),excludeSubjects{j}))); + if ~isempty(xx) + excludeIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + dataTimeCourse([excludeIdx],:) = []; +end + +%Baseline concentration, equals 2nd block (second 64 averages of first +%REST) +nsteps = 1; +for i = 3:floor(length(dataTimeCourse)/10):length(dataTimeCourse) + baselineConcIdxMet(nsteps,1) = dataTimeCourse{i,idxMet}; + nsteps = nsteps + 1; +end + +[n,~] = size(dataTimeCourse); +for k = 2:n + MetConc(k-1) = dataTimeCourse(k,idxMet(1)); +end + +%calculate concentration change of data points with reference to baseline +[~,b] = size(MetConc); +for av = 1:b-4 + PercChange(av) = (MetConc{1,av}-baselineConcIdxMet(ceil(av/10)))/baselineConcIdxMet(ceil(av/10))*100; +end + +% figure +% x = linspace(320/60/4,(320*5/60-320/60/4),10); +% hold on +% [ss,~] = size(dataTimeCourse); +% for idxSubject = 1:floor(ss/nBlocks) +% if metabToFig == 'Lac' +% plot(x,cell2mat(dataTimeCourse(((idxSubject-1)*10+2):((idxSubject-1)*10+11),idxMet(1)))+(idxSubject-1)*1.5,'d-') +% elseif metabToFig == 'Glu' +% plot(x,cell2mat(dataTimeCourse(((idxSubject-1)*10+2):((idxSubject-1)*10+11),idxMet(1)))+(idxSubject-1)*5,'d-') +% else +% error('can only plot Lac and Glu so far'); +% end +% end +% xlabel 't / min'; ylabel 'Concentration Change / %' +% if exist('excludeSubjects') +% if ~isempty(strfind(ExpName,'Rest')) +% title ([metabToFig,' time course, subjects excluded, Rest']) +% else +% title ([metabToFig,' time course, subjects excluded, Stim']) +% end +% else +% if ~isempty(strfind(ExpName,'Rest')) +% title ([metabToFig,' time course, Rest']) +% else +% title ([metabToFig,' time course, Stim']) +% end +% end +% +% yLimits = get(gca,'YLim'); +% boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +% for i = 1:nBlocks/2 +% boxoff = [boxoff 320/60*i 320/60*i]; +% if i < nBlocks/2 +% boxon = [boxon 320/60*i 320/60*i]; +% end +% end +% for ii = 1:nBlocks/4 +% boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +% boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +% end +% patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +% patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +% ylim([yLimits(1) yLimits(2)]); +% xlim([0 320*5/60]); set(gca, 'FontWeight','bold'); +% set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 12, 20]); +% PathName = strcat(LCModelOutputPath,'BlockConcTimeCourse/'); +% if exist('excludeSubjects') +% fig2save = fullfile(PathName, strcat(ExpName, '_', metabToFig, '_Excluded_PercChange.fig')); +% else +% fig2save = fullfile(PathName, strcat(ExpName, '_', metabToFig, '_PercChange.fig')); +% end +% savefig(fig2save) + + +% PercChange_temp = cell2mat(dataTimeCourse(2:end-4,2:end)); +for indexOfBlock = 1:nBlocks + PercChange_mean{indexOfBlock,1} = mean(PercChange(1,indexOfBlock:nBlocks:end)); + PercChange_std{indexOfBlock,1} = std(PercChange(1,indexOfBlock:nBlocks:end)); +end + +figure +x = linspace(320/60/4,(320*5/60-320/60/4),10); +hold on +errorbar(x,cell2mat(PercChange_mean),cell2mat(PercChange_std),'-d') +xlabel 't / min'; ylabel 'Mean Concentration Change / %' +if exist('excludeSubjects') + if ~isempty(strfind(ExpName,'Rest')) + title ([metabToFig,' time course, subjects excluded, Rest']) + else + title ([metabToFig,' time course, subjects excluded, Stim']) + end +else + if ~isempty(strfind(ExpName,'Rest')) + title ([metabToFig,' time course, Rest']) + else + title ([metabToFig,' time course, Stim']) + end +end + +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:nBlocks/2 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < nBlocks/2 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:nBlocks/4 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +xlim([0 320*5/60]); set(gca, 'FontWeight','bold') +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +PathName = strcat(LCModelOutputPath,'BlockConcTimeCourse/'); +if exist('excludeSubjects') + fig2save = fullfile(PathName, strcat(ExpName, '_', metabToFig, '_Mean_Excluded_PercChange.fig')); +else + fig2save = fullfile(PathName, strcat(ExpName, '_', metabToFig, '_Mean_PercChange.fig')); +end +savefig(fig2save) + +end + function createConcTimeCourseFig(ExpName,LCModelOutputPath,subjects,nBlocks,metabToFig,woBaseline,excludeSubjects) if exist('woBaseline', 'var') & woBaseline == true @@ -257,7 +455,7 @@ end patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) ylim([yLimits(1) yLimits(2)]); -xlim([0 320*5/60]); +xlim([0 320*5/60]); set(gca, 'FontWeight','bold'); set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 12, 20]); PathName = strcat(LCModelOutputPath,'BlockConcTimeCourse/'); if exist('excludeSubjects') @@ -311,7 +509,7 @@ end patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) ylim([yLimits(1) yLimits(2)]); -xlim([0 320*5/60]); +xlim([0 320*5/60]); set(gca, 'FontWeight','bold'); set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); PathName = strcat(LCModelOutputPath,'BlockConcTimeCourse/'); if exist('excludeSubjects') @@ -430,12 +628,30 @@ save(exportFileMat, ExpName) end function createConcTableBaseline(numberOfSubjects,BlockNo,LCModelOutputFiles,defaultSubject,subjects,... - LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,woBaseline) + LCModelOutputPath,subjectsPath,prefixes,visualType,BOLDType,MMBType,woBaseline,excludeSubjects) if exist('woBaseline', 'var') & woBaseline == true woBaseline = '_woBaseline'; else woBaseline = ''; end +if exist('excludeSubjects') + n = length(subjects); + m = length(excludeSubjects); + nstep = 1; + for j = 1:m + for i = 1:n + xx = find(~cellfun(@isempty,strfind(subjects(i,1),excludeSubjects{j}))); + if ~isempty(xx) + excludeIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + subjects([excludeIdx],:) = []; + prefixes([excludeIdx],:) = []; + subjectsPath([excludeIdx],:) = []; + numberOfSubjects = length(subjects); +end tableConcentrations = []; isFirstIter = 1; s = 1; @@ -505,7 +721,11 @@ for indexOfMetab = 1:m-1 end % save table to file -ExpName = strcat('BaselineConc_', num2str(visualType), BOLDType, MMBType, woBaseline); +if exist('excludeSubjects') + ExpName = strcat('BaselineConc_', num2str(visualType), BOLDType, MMBType, woBaseline, '_Excluded'); +else + ExpName = strcat('BaselineConc_', num2str(visualType), BOLDType, MMBType, woBaseline); +end exportFileXlsx = [LCModelOutputPath ,strcat(ExpName,'.xlsx')]; xlswrite(exportFileXlsx, {LCModelOutputPath}, 1, 'A1'); cellPosition = 'A2'; diff --git a/fMRS_processing/doFitting_fMRS_TimeCourse_Summed.m b/fMRS_processing/doFitting_fMRS_TimeCourse_Summed.m new file mode 100644 index 0000000..84955dc --- /dev/null +++ b/fMRS_processing/doFitting_fMRS_TimeCourse_Summed.m @@ -0,0 +1,546 @@ +function doFitting_fMRS_TimeCourse_Summed() +clear; clc; close all; + +%%%%% +% summed data created with +% D:\MR_spectroS\fMRS_processing\BOLDEffectfMRS_summedSpectra.m +% saved in D:\PAPER\1H_fMRS\Data_TimeCourse\SummedData +%%%%% + +allVisTypes = {'Stim'}; %'Stim', 'Rest' + +for i = 1:length(allVisTypes) +pathName = 'fMRS TimeCourse data path'; +sampleCriteria = {'Output', 'LCModelConfig'}; +[localFilePathBase] = pathToDataFolder(pathName, sampleCriteria); +visualType = allVisTypes{i}; %'Stim', 'Rest' +BOLDType = '_woBOLDCorr'; %only _woBOLDCorr reasonable since block wise fitting for metabolite time courses +MMBType = '_MMBSummed_v2'; %_MMBIndFiltered, _MMBSummed, _MMBInd, _MMBSimulated +% nBlocks = 5; +nBlocks = 10; + +BlockNo = cell(1,nBlocks); +for k = 1:nBlocks + BlockNo{k} = strcat('_Block', num2str(k)); +end + +% subjects = {'2823';}; +subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... + '4085';'3333';'4012';'4085';'6524'}; +% prefixes = {'2020-02-18_';}; +prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... + '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... + '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; +suffixFolder = '_fMRS'; +excludeSubjects = {'5166';'9810';'5269'}; + +% if exist('excludeSubjects') +% n = length(subjects); +% m = length(excludeSubjects); +% nstep = 1; +% for j = 1:m +% for i = 1:n +% xx = find(~cellfun(@isempty,strfind(subjects(i,1),excludeSubjects{j}))); +% if ~isempty(xx) +% excludeIdx(nstep) = i; +% nstep = nstep + 1; +% end +% end +% end +% subjects([excludeIdx],:) = []; +% prefixes([excludeIdx],:) = []; +% end + + +extensionTable = '.table'; +extensionCoord = '.coord'; +defaultVisual = 'Stim'; +defaultSubject = 'XXXX'; +defaultSubjectsPath = 'YYYY'; +if ~isempty(strfind(MMBType,'_v2')) + defaultMMB = '_MMBSummed_v2'; +else + defaultMMB = '_MMBSummed'; +end +defaultLCModelUser = 'jdorst'; +outputFileNameBaseWithoutMetabolite_OFF = strcat(defaultSubject, '_StimOFF_woBOLDCorr128'); +outputFileNameBaseWithoutMetabolite_ON = strcat(defaultSubject, '_StimON_woBOLDCorr128'); + +if ~isempty(strfind(MMBType,'_v2')) + controlFilesBase = 'fitsettings_v2_XXXX_'; +else + controlFilesBase = 'fitsettings_XXXX_'; +end +controlFilesBaseSuffix = '.control'; +outputFileNameBase = strcat(defaultSubject, '_'); + +%% file paths setup +controlFilesPathRemote = '/Desktop/1H_fMRS/LCModelConfig/'; +controlFilesPathLocal = [localFilePathBase, 'LCModelConfig/']; +LCModelOutputFilesPathRemote = '/Desktop/1H_fMRS/Output/'; +if ~isempty(strfind(MMBType,'_v2')) + LCModelOutputPath = [localFilePathBase, 'Output_v2_MMBSummed/']; +else + LCModelOutputPath = [localFilePathBase, 'Output/']; +end +defaultControlFile = strcat(controlFilesBase, defaultVisual, controlFilesBaseSuffix); + +% subjectsPath = strcat(prefixes, subjects, suffixFolder); +summedPath = 'Summed_fMRSData'; + +summedControlFilesPathRemote = strcat(controlFilesPathRemote, summedPath, '/'); +summedControlFilesPathLocal = strcat(controlFilesPathLocal, summedPath, '/'); +preprocessedFilesPathLocal = strcat(localFilePathBase, 'SummedData/'); +summedLCModelOutputFilesRemote = strcat(LCModelOutputFilesPathRemote, summedPath, '/'); +summedLCModelOutputPath = strcat(LCModelOutputPath, summedPath, '/'); + + +%% basic configurations +LCModelOutputFiles = strcat(outputFileNameBase, visualType, BOLDType, MMBType, BlockNo); +LCModelOutputFileswoBaseline = strcat(outputFileNameBase, visualType, BOLDType, MMBType, BlockNo, '_woBaseline'); +LCModelControlFiles = strcat(controlFilesBase, visualType, BOLDType, MMBType, BlockNo, controlFilesBaseSuffix); +LCModelControlFileswoBaseline = strcat(controlFilesBase, visualType, BOLDType, MMBType, BlockNo, '_woBaseline', controlFilesBaseSuffix); +defaultWaterRef = strcat(outputFileNameBase, 'WRef'); + +numberOfSubjects = length(subjects); + +%% do the LCModel fitting +% LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); +% +% LCModelCallerInstance = LCModelCallerInstance.ConfigurePaths(summedControlFilesPathRemote, summedLCModelOutputFilesRemote, ... +% summedLCModelOutputPath); +% +% currentControlFiles = strrep(LCModelControlFiles, defaultSubject, 'Summed'); +% currentControlFiles = strrep(currentControlFiles,'.control','_Excluded.control'); +% currentControlFiles = strrep(currentControlFiles,'fitsettings_v2_','fitsettings_'); +% currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, 'Summed'); +% currentOutputFiles = strcat(currentOutputFiles,'_Excluded'); +% waterRefFileName = strrep(defaultWaterRef, defaultSubject, 'fMRSData_Summed'); +% waterRefFileName = strcat(waterRefFileName,'_Excluded'); +% +% %%create the control file series +% for nBl = 1:nBlocks +% currentOutputFile = currentOutputFiles{nBl}; +% currentFMRS = strcat(visualType,BOLDType); +% % % % currentLCModelOutputFile = LCModelOutputFiles{nBl}; +% createLCModelConfigfMRSTimeCourse(controlFilesPathLocal, summedControlFilesPathLocal, defaultControlFile, ... +% currentFMRS, defaultVisual, currentOutputFile,... +% waterRefFileName, defaultWaterRef, summedPath, defaultSubjectsPath, 'fMRSData_Summed',... +% defaultSubject, MMBType, defaultMMB, BlockNo{nBl}); +% end +% +% outputFiles = strcat('fMRSData_',strrep(LCModelOutputFiles, defaultSubject, 'Summed')); +% fittingLCModel(LCModelCallerInstance, currentControlFiles, outputFiles, summedControlFilesPathRemote, ... +% summedControlFilesPathLocal, preprocessedFilesPathLocal); +% %% +% % % always excludeSubjects, only 10 subjects in summed RAW file, see D:\MR_spectroS\fMRS_processing\BoldEffectfMRS_summedSpectra.m +% createConcTableBaseline(BlockNo,outputFiles,... +% LCModelOutputPath,summedPath,visualType,BOLDType,MMBType,0) +% % +% % % Create and save table from fitted concentrations with baseline, take from blocks 3-10 +% createConcTableBlock(BlockNo,outputFiles,defaultSubject,... +% LCModelOutputPath,summedPath,visualType,BOLDType,MMBType,0) +% +% %% subtract baseline from difference spectrum and fit again +% % only useful for MMBSummed +% if strcmp(MMBType(1:10),'_MMBSummed') +% %% do the LCModel fitting +% LCModelCallerInstance = startLCModel(controlFilesPathRemote, LCModelOutputFilesPathRemote, LCModelOutputPath); +% +% LCModelCallerInstance = LCModelCallerInstance.ConfigurePaths(summedControlFilesPathRemote, summedLCModelOutputFilesRemote, ... +% summedLCModelOutputPath); +% +% currentControlFileswoBaseline = strrep(LCModelControlFileswoBaseline, defaultSubject, 'Summed'); +% currentControlFileswoBaseline = strrep(currentControlFileswoBaseline,'.control','_Excluded.control'); +% currentControlFileswoBaseline = strrep(currentControlFileswoBaseline,'fitsettings_v2_','fitsettings_'); +% if ~isempty(strfind(MMBType,'_v2')) +% currentDataFiles = strcat('fMRSData_Summed_', visualType, BOLDType, '_v2', BlockNo); +% else +% currentDataFiles = strcat('fMRSData_Summed_', visualType, BOLDType, BlockNo); +% end +% currentOutputFileswoBaseline = strrep(LCModelOutputFileswoBaseline, defaultSubject, 'Summed'); +% currentOutputFileswoBaseline = strcat(currentOutputFileswoBaseline,'_Excluded'); +% currentOutputFiles = strrep(LCModelOutputFiles, defaultSubject, 'Summed'); +% currentOutputFiles = strcat(currentOutputFiles,'_Excluded'); +% waterRefFileName = strrep(defaultWaterRef, defaultSubject, 'fMRSData_Summed'); +% waterRefFileName = strcat(waterRefFileName,'_Excluded'); +% currentDataPath = strcat(localFilePathBase,'SummedData', '/'); +% for nBl = 1:nBlocks +% %check save option for .mat file in subtractBaseline_fMRS +% subtractBaseline_fMRS(currentDataPath,summedLCModelOutputPath,currentDataFiles{nBl},strcat('fMRSData_',currentOutputFileswoBaseline{nBl}),'NAA') +% currentFMRS = strcat(visualType,BOLDType); +% createLCModelConfigfMRSTimeCourse(controlFilesPathLocal, summedControlFilesPathLocal, defaultControlFile, ... +% currentFMRS, defaultVisual, currentOutputFileswoBaseline{nBl},... +% waterRefFileName, defaultWaterRef, summedPath, defaultSubjectsPath, 'fMRSData_Summed',... +% defaultSubject, MMBType, defaultMMB, strcat(BlockNo{nBl}, '_woBaseline')); +% end +% outputFileswoBaseline = strcat('fMRSData_',strrep(LCModelOutputFileswoBaseline, defaultSubject, 'Summed')); +% fittingLCModel(LCModelCallerInstance, currentControlFileswoBaseline, outputFileswoBaseline, summedControlFilesPathRemote, ... +% summedControlFilesPathLocal, preprocessedFilesPathLocal); +% +% % +% % % Create and save table with baseline concentrations fitted w/o baseline, taken from second block of first REST +% % always excludeSubjects, only 10 subjects in summed RAW file, see D:\MR_spectroS\fMRS_processing\BoldEffectfMRS_summedSpectra.m +% createConcTableBaseline(BlockNo,outputFiles,... +% LCModelOutputPath,summedPath,visualType,BOLDType,MMBType,1) +% % +% % % Create and save table from fitted concentrations w/o baseline, taken from blocks 3-10 +% createConcTableBlock(BlockNo,outputFiles,defaultSubject,... +% LCModelOutputPath,summedPath,visualType,BOLDType,MMBType,1) +% end + + +%% create concentration time course from fit with and w/o Baseline +ExpName = strcat('BlockConc_Summed_', num2str(visualType), BOLDType, MMBType); +% always excludeSubjects, only 10 subjects in summed RAW file, see D:\MR_spectroS\fMRS_processing\BoldEffectfMRS_summedSpectra.m +createConcTimeCourseFig(ExpName,LCModelOutputPath,nBlocks,'Lac',0) +createConcTimeCourseFig(ExpName,LCModelOutputPath,nBlocks,'Glu',0) +createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,nBlocks,'Lac',0) +createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,nBlocks,'Glu',0) +createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,nBlocks,'Cr',0) +if strcmp(MMBType(1:10),'_MMBSummed') + createConcTimeCourseFig(ExpName,LCModelOutputPath,nBlocks,'Lac',1) + createConcTimeCourseFig(ExpName,LCModelOutputPath,nBlocks,'Glu',1) +createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,nBlocks,'Lac',1) +createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,nBlocks,'Glu',1) +end +close all + +end +end + +function createConcTimeCourseFig(ExpName,LCModelOutputPath,nBlocks,metabToFig,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +ExpName = strcat(ExpName, woBaseline); + +exportFileMat = [LCModelOutputPath ,strcat(ExpName,'.mat')]; +dataTimeCourse = load(exportFileMat); +fields = fieldnames(dataTimeCourse); +dataTimeCourse = dataTimeCourse.(fields{1}); +metaboliteNames = (dataTimeCourse(1,:)); +indexMet = strfind(metaboliteNames,metabToFig); +idxMet = find(not(cellfun('isempty',indexMet))); + +figure +x = linspace(320/60/4,(320*5/60-320/60/4),10); +hold on +[ss,~] = size(dataTimeCourse); +for idxSubject = 1:floor(ss/nBlocks) +% if metabToFig == 'Lac' + plot(x,cell2mat(dataTimeCourse(((idxSubject-1)*10+2):((idxSubject-1)*10+11),idxMet(1)))+(idxSubject-1)*1.5,'d-') +% elseif metabToFig == 'Glu' +% plot(x,cell2mat(dataTimeCourse(((idxSubject-1)*10+2):((idxSubject-1)*10+11),idxMet(1)))+(idxSubject-1)*5,'d-') +% else +% error('can only plot Lac and Glu so far'); +% end +end +xlabel 't / min'; ylabel 'Concentration / a.u.' +if ~isempty(strfind(ExpName,'Rest')) + title ([metabToFig,' time course, fit from summed data, subjects excluded, Rest']) +else + title ([metabToFig,' time course, fit from summed data, subjects excluded, Stim']) +end + +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:nBlocks/2 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < nBlocks/2 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:nBlocks/4 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +xlim([0 320*5/60]); set(gca, 'FontWeight','bold') +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +PathName = strcat(LCModelOutputPath,'BlockConcTimeCourse/'); +fig2save = fullfile(PathName, strcat(ExpName, '_', metabToFig, '_Excluded.fig')); +savefig(fig2save) + +end + +function createConcTimeCourseFigPercChange(ExpName,LCModelOutputPath,nBlocks,metabToFig,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +ExpName = strcat(ExpName, woBaseline); + +exportFileMat = [LCModelOutputPath ,strcat(ExpName,'.mat')]; +dataTimeCourse = load(exportFileMat); +fields = fieldnames(dataTimeCourse); +dataTimeCourse = dataTimeCourse.(fields{1}); +metaboliteNames = (dataTimeCourse(1,:)); +indexMet = strfind(metaboliteNames,metabToFig); +idxMet = find(not(cellfun('isempty',indexMet))); + +%Baseline concentration, equals 2nd block (second 64 averages of first +%REST) +baselineConcIdxMet = dataTimeCourse{3,idxMet}; + +[n,~] = size(dataTimeCourse); +for k = 2:n + MetConc(k-1) = dataTimeCourse(k,idxMet(1)); +end + +%calculate concentration change of data points with reference to baseline +[~,b] = size(MetConc); +for av = 1:b-4 + PercChange(av) = (MetConc{1,av}-baselineConcIdxMet)/baselineConcIdxMet*100; +end + +figure +x = linspace(320/60/4,(320*5/60-320/60/4),10); +hold on +plot(x,PercChange,'d-') +plot([0,320*5/60],[0 0]) +xlabel 't / min'; ylabel 'Concentration change / %' +if ~isempty(strfind(ExpName,'Rest')) + title ([metabToFig,' time course, fit from summed data, subjects excluded, Rest']) +else + title ([metabToFig,' time course, fit from summed data, subjects excluded, Stim']) +end + +yLimits = get(gca,'YLim'); +boxoff = [0 0]; boxon = []; boxyoff = [yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; boxyon = []; n = 1; +for i = 1:nBlocks/2 + boxoff = [boxoff 320/60*i 320/60*i]; + if i < nBlocks/2 + boxon = [boxon 320/60*i 320/60*i]; + end +end +for ii = 1:nBlocks/4 + boxyoff = [boxyoff yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; + boxyon = [boxyon yLimits(1) yLimits(2) yLimits(2) yLimits(1)]; +end +patch(boxoff,boxyoff,[0 0 1],'FaceAlpha',0.2) +patch(boxon,boxyon,[1 0 0],'FaceAlpha',0.2) +ylim([yLimits(1) yLimits(2)]); +xlim([0 320*5/60]); set(gca, 'FontWeight','bold') +set(gcf, 'Units', ' centimeters', 'OuterPosition', [0, 0, 18, 12.6]); +PathName = strcat(LCModelOutputPath,'BlockConcTimeCourse/'); +fig2save = fullfile(PathName, strcat(ExpName, '_', metabToFig, '_Excluded_PercChange.fig')); +savefig(fig2save) + +end + +function createConcTableBlock(BlockNo,LCModelOutputFiles,defaultSubject,... + LCModelOutputPath,summedPath,visualType,BOLDType,MMBType,woBaseline) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +tableConcentrations = []; +isFirstIter = 1; +s = 1; +for nBl = 1:length(BlockNo) + % retrieve parameters + currentOutputFiles = strrep(strcat(LCModelOutputFiles,woBaseline), defaultSubject, 'fMRSData_Summed'); + currentPath = strcat(LCModelOutputPath,summedPath,'/',currentOutputFiles{nBl},'.table'); + [c1 c2 c3 c4] = textread(currentPath,'%s %s %s %s'); + + if isFirstIter + start = find(strcmp(c1,'Conc.')); + start = start + 1; + finish = find(strcmpi(c1,'$$MISC')) - 1; + tableConcentrations{1,1} = 'ID'; + + s = 2; + for j=start:finish + if(strcmp(c4{j},'')==1) + c3_split = strsplit(c3{j},'+'); + if length(c3_split) == 1 + c3_split = strsplit(c3{j},'-'); + end + tableConcentrations{1,s} = c3_split{2}; + else + tableConcentrations{1,s} = c4{j}; + if length(tableConcentrations{1,s}) == 3 & tableConcentrations{1,s} == 'Leu' + tableConcentrations{1,s} = 'MMB'; + end + end + tableConcentrations{1,s+1} = 'CRLB %'; + s = s + 2; + end + tableConcentrations{1,s} = 'water concentration'; + end + + % add ID and Water conc to table + % tableConcentrations{(length(BlockNo)-2)*(indexCurrentSubject-1)+nBl-1,1} = strcat(prefixes{indexCurrentSubject}, subjects{indexCurrentSubject}, BlockNo{nBl}); + tableConcentrations{nBl+1,1} = strcat('fMRSData_Summed', BlockNo{nBl}); + index_wconc = find(strcmp(c1,'wconc=')); + wconc_LCModel = str2num(c2{index_wconc}); + tableConcentrations{nBl+1,end} = wconc_LCModel; + % add metabolites to table + s = 2; + for j=start:finish + % add quantified metabolite + tableConcentrations{nBl+1,s} = str2num( c1{j}); + % add CRLB + tableConcentrations{nBl+1,s+1} = str2num( c2{j}(1:end-1)); + s = s+2; + end + + isFirstIter = false; + +end + +% calculate mean, std +[n,m] = size(tableConcentrations); +subArray = cell2mat(tableConcentrations(2:end,2:end)); +subArrayON1 = subArray(3:10:end,:); +subArrayON2 = subArray(4:10:end,:); +subArrayON3 = subArray(7:10:end,:); +subArrayON4 = subArray(8:10:end,:); +subArrayON = [subArrayON1; subArrayON2; subArrayON3; subArrayON4]; +meanValueON = mean(subArrayON); +stdValueON = std(subArrayON); +tableConcentrations{n+1,1} = 'meanON'; +tableConcentrations{n+2,1} = 'stdON'; +for indexOfMetab = 1:m-1 + tableConcentrations{n+1,indexOfMetab+1} = meanValueON(1,indexOfMetab); + tableConcentrations{n+2,indexOfMetab+1} = stdValueON(1,indexOfMetab); +end +subArrayOFF1 = subArray(5:10:end,:); +subArrayOFF2 = subArray(6:10:end,:); +subArrayOFF3 = subArray(9:10:end,:); +subArrayOFF4 = subArray(10:10:end,:); +subArrayOFF = [subArrayOFF1; subArrayOFF2; subArrayOFF3; subArrayOFF4]; +meanValueOFF = mean(subArrayOFF); +stdValueOFF = std(subArrayOFF); +tableConcentrations{n+3,1} = 'meanOFF'; +tableConcentrations{n+4,1} = 'stdOFF'; +for indexOfMetab = 1:m-1 + tableConcentrations{n+3,indexOfMetab+1} = meanValueOFF(1,indexOfMetab); + tableConcentrations{n+4,indexOfMetab+1} = stdValueOFF(1,indexOfMetab); +end + +% save table to file +ExpName = strcat('BlockConc_Summed_', num2str(visualType), BOLDType, MMBType, woBaseline); +exportFileXlsx = [LCModelOutputPath ,strcat(ExpName,'.xlsx')]; +xlswrite(exportFileXlsx, {LCModelOutputPath}, 1, 'A1'); +cellPosition = 'A2'; +xlswrite(exportFileXlsx, tableConcentrations, 1, cellPosition); + +exportFileMat = [LCModelOutputPath ,strcat(ExpName,'.mat')]; +eval([ExpName '= tableConcentrations']); %use of eval not recommended, change it +save(exportFileMat, ExpName) +end + +function createConcTableBaseline(BlockNo,LCModelOutputFiles,... + LCModelOutputPath,summedPath,visualType,BOLDType,MMBType,woBaseline,excludeSubjects) +if exist('woBaseline', 'var') & woBaseline == true + woBaseline = '_woBaseline'; +else + woBaseline = ''; +end +% if exist('excludeSubjects') +% n = length(subjects); +% m = length(excludeSubjects); +% nstep = 1; +% for j = 1:m +% for i = 1:n +% xx = find(~cellfun(@isempty,strfind(subjects(i,1),excludeSubjects{j}))); +% if ~isempty(xx) +% excludeIdx(nstep) = i; +% nstep = nstep + 1; +% end +% end +% end +% subjects([excludeIdx],:) = []; +% prefixes([excludeIdx],:) = []; +% subjectsPath([excludeIdx],:) = []; +% numberOfSubjects = length(subjects); +% end +tableConcentrations = []; +isFirstIter = 1; +s = 1; +for nBl = 2 %take baseline from second block of first REST + % retrieve parameters + currentOutputFiles = strcat(LCModelOutputFiles,woBaseline); + currentPath = strcat(LCModelOutputPath,summedPath,'/',currentOutputFiles{nBl},'.table'); + [c1 c2 c3 c4] = textread(currentPath,'%s %s %s %s'); + + if isFirstIter + start = find(strcmp(c1,'Conc.')); + start = start + 1; + finish = find(strcmpi(c1,'$$MISC')) - 1; + tableConcentrations{1,1} = 'ID'; + + s = 2; + for j=start:finish + if(strcmp(c4{j},'')==1) + c3_split = strsplit(c3{j},'+'); + if length(c3_split) == 1 + c3_split = strsplit(c3{j},'-'); + end + tableConcentrations{1,s} = c3_split{2}; + else + tableConcentrations{1,s} = c4{j}; + if length(tableConcentrations{1,s}) == 3 & tableConcentrations{1,s} == 'Leu' + tableConcentrations{1,s} = 'MMB'; + end + end + tableConcentrations{1,s+1} = 'CRLB %'; + s = s + 2; + end + tableConcentrations{1,s} = 'water concentration'; + end + + % add ID and Water conc to table + tableConcentrations{1,1} = strcat('fMRSData_Summed', BlockNo{nBl}); + index_wconc = find(strcmp(c1,'wconc=')); + wconc_LCModel = str2num(c2{index_wconc}); + tableConcentrations{1,end} = wconc_LCModel; + % add metabolites to table + s = 2; + for j=start:finish + %add quantified metabolite + tableConcentrations{1,s} = str2num( c1{j}); + %add CRLB + tableConcentrations{1,s+1} = str2num( c2{j}(1:end-1)); + s = s+2; + end + + isFirstIter = false; + +end + +% %calculate mean, std +% [n,m] = size(tableConcentrations); +% subArray = cell2mat(tableConcentrations(2:end,2:end)); +% meanValue = mean(subArray); +% stdValue = std(subArray); +% tableConcentrations{n+1,1} = 'mean'; +% tableConcentrations{n+2,1} = 'std'; +% for indexOfMetab = 1:m-1 +% tableConcentrations{n+1,indexOfMetab+1} = meanValue(1,indexOfMetab); +% tableConcentrations{n+2,indexOfMetab+1} = stdValue(1,indexOfMetab); +% end + +% save table to file +% if exist('excludeSubjects') +% ExpName = strcat('BaselineConc_Summed_', num2str(visualType), BOLDType, MMBType, woBaseline, '_Excluded'); +% else + ExpName = strcat('BaselineConc_Summed_', num2str(visualType), BOLDType, MMBType, woBaseline); +% end +exportFileXlsx = [LCModelOutputPath ,strcat(ExpName,'.xlsx')]; +xlswrite(exportFileXlsx, {LCModelOutputPath}, 1, 'A1'); +cellPosition = 'A2'; +xlswrite(exportFileXlsx, tableConcentrations, 1, cellPosition); + +exportFileMat = [LCModelOutputPath ,strcat(ExpName,'.mat')]; +eval([ExpName '= tableConcentrations']); %use of eval not recommended, change it +save(exportFileMat, ExpName) +end \ No newline at end of file diff --git a/fMRS_processing/plot_properties_Reproducibility.m b/fMRS_processing/plot_properties_Reproducibility.m new file mode 100644 index 0000000..bb6ec38 --- /dev/null +++ b/fMRS_processing/plot_properties_Reproducibility.m @@ -0,0 +1,85 @@ +function plot_properties_Reproducibility() +clear; clc; close all; + +pathName = 'fMRS TimeCourse data path'; +sampleCriteria = {'Output', 'LCModelConfig'}; +[localFilePathBase] = pathToDataFolder(pathName, sampleCriteria); +visualType = 'Stim'; %'Stim', 'Rest' +BOLDType = '_woBOLDCorr'; %only _woBOLDCorr reasonable since block wise fitting for metabolite time courses +MMBType = '_MMBSummed_v2'; %_MMBIndFiltered, _MMBSummed, _MMBInd, _MMBSimulated +% nBlocks = 5; +nBlocks = 10; + +BlockNo = cell(1,nBlocks); +for k = 1:nBlocks + BlockNo{k} = strcat('_Block', num2str(k)); +end + +% subjects = {'2823';}; +subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... + '4085';'3333';'4012';'4085';'6524'}; +% prefixes = {'2020-02-18_';}; +prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... + '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... + '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; +suffixFolder = '_fMRS'; +excludeSubjects = {'5166';'9810';'5269'}; + +if exist('excludeSubjects') + n = length(subjects); + m = length(excludeSubjects); + nstep = 1; + for j = 1:m + for i = 1:n + xx = find(~cellfun(@isempty,strfind(subjects(i,1),excludeSubjects{j}))); + if ~isempty(xx) + excludeIdx(nstep) = i; + nstep = nstep + 1; + end + end + end + subjects([excludeIdx],:) = []; + prefixes([excludeIdx],:) = []; +end + +subjectsPath = strcat(prefixes, subjects, suffixFolder); + +%load Rest data per block, then mean, std, plot +for indexCurrentSubject = 1:length(subjects) + currentDataFilePath = [localFilePathBase,subjectsPath{indexCurrentSubject}]; + for nBl = 1:nBlocks + % currentData = load(strcat(currentDataFilePath,'\',subjects{indexCurrentSubject},'_',visualType,BOLDType,BlockNo{nBl})); + % fields = fieldnames(currentData); + % currentData = currentData.(fields{1}); + %hopefully saved as 'this' + load(strcat(currentDataFilePath,'\',subjects{indexCurrentSubject},'_',visualType,BOLDType,BlockNo{nBl})); + Data_temp = squeeze(real(fftshift(fft(this.Data{1})))); + Data(indexCurrentSubject,nBl,:,:) = squeeze(real(fftshift(fft(this.Data{1})))); %Subjects x Blocks x Data x Water/Met + end + DataBlockMean_Met(indexCurrentSubject,:) = squeeze(mean(Data(indexCurrentSubject,:,:,2),2)); + DataBlockStd_Met(indexCurrentSubject,:) = squeeze(std(Data(indexCurrentSubject,:,:,2))); + DataBlockMean_H2O(indexCurrentSubject,:) = squeeze(mean(Data(indexCurrentSubject,:,:,1),2)); + DataBlockStd_H2O(indexCurrentSubject,:) = squeeze(std(Data(indexCurrentSubject,:,:,1))); +end +ppmvector = this.getPpmVector(); +colors = {[0 0.7 0]; [0 0.4 0.8]; [0.8 0 0.8]; [0.8 0.4 0];[0 0.5 0.5]; [0.4 0 0.8]; [1 0 0]; [0 0.6 0.3]; [1 0 0.5]; [0 0 1];}; + +for indexCurrentSubject = 1:length(subjects) + lo = (DataBlockMean_Met(indexCurrentSubject,:) - DataBlockStd_Met(indexCurrentSubject,:)) + 0.01 * (indexCurrentSubject-1); hi = DataBlockMean_Met(indexCurrentSubject,:) + DataBlockStd_Met(indexCurrentSubject,:) + 0.01 * (indexCurrentSubject-1); +% figure + hp = patch([ppmvector ppmvector(end:-1:1) ppmvector(1)], [lo hi(end:-1:1) lo(1)], 'r'); + hold on; + hl = line(ppmvector,DataBlockMean_Met(indexCurrentSubject,:) + 0.01 * (indexCurrentSubject-1)); + set(hp, 'facecolor', colors{indexCurrentSubject},'FaceAlpha',.3, 'edgecolor', colors{indexCurrentSubject},'EdgeAlpha',.2); + set(hl, 'color', colors{indexCurrentSubject}); + set(gca,'xdir','reverse') + xlim([0.6 8.5]); xlabel 'f / ppm' + title(['Reproducibility ',visualType]) +end +figPath2save = fullfile(localFilePathBase, 'Output_v2_MMBSummed\Reproducibility'); +fig2save = [figPath2save, '\Reproducibility_all_',visualType,'.fig']; +% fig2save = [figPath2save, '\Reproducibility_first3_',visualType,'.fig']; +% fig2save = [figPath2save, '\Reproducibility_second3_',visualType,'.fig']; +% fig2save = [figPath2save, '\Reproducibility_last4_',visualType,'.fig']; +savefig(fig2save) +end \ No newline at end of file diff --git a/fMRS_processing/reconstruct_1H_fMRS.m b/fMRS_processing/reconstruct_1H_fMRS.m index 21fdc20..bbf4e3d 100644 --- a/fMRS_processing/reconstruct_1H_fMRS.m +++ b/fMRS_processing/reconstruct_1H_fMRS.m @@ -1,4 +1,5 @@ -function [a] = reconstruct_1H_fMRS(currentFolder,fid_id, isMC, isInVivo, nBlocks, nOnAverages, PCSteps, weights, saveResults,visualType) +function [a] = reconstruct_1H_fMRS(currentFolder,fid_id, isMC, isInVivo,... + nBlocks, nOnAverages, PCSteps, weights, saveResults, visualType,BOLDType,modulus) nsamplesBeforeEcho = 4; @@ -10,6 +11,10 @@ if ~exist('saveResults', 'var') saveResults = true; end +if ~exist('modulus', 'var') + error('choose modulus type true or false'); +end + if nBlocks == 5 nAvg2save = '#64'; elseif nBlocks == 10 @@ -82,10 +87,14 @@ end %% if isInVivo %% truncate before anything - trunc_ms = 250; +% if exist('modulus','var') && (modulus == 1) +% trunc_ms = 200; +% else + trunc_ms = 250; +% end truncPoint = floor( trunc_ms/(a.Parameter.Headers.DwellTimeSig_ns*1e-6)); a = a.Truncate(truncPoint); - + a = a.FrequencyAlign; end if isMC @@ -95,14 +104,17 @@ if isMC a = a.ReconData; end -%average data block-wise + +%% %average data block-wise if ~exist('nBlocks', 'var') a.Parameter.AverageSettings.nBlocks = 1; else a.Parameter.AverageSettings.nBlocks = nBlocks; end -a = a.AverageData; +if exist('modulus','var') && (modulus == 0) + a = a.AverageData; +end %eddy current correction if isMC @@ -127,34 +139,154 @@ else a = a.CombineCoils; end -%% setup the settings for the FrequencyAlignFreqDomain -a.Parameter.FreqAlignFreqDomainSettings.selectedCoil = 1; % check for max SNR coil -a.Parameter.FreqAlignFreqDomainSettings.selectedMix = 1; - -%indices of Interest: given in ppm -% water peak -a.Parameter.FreqAlignFreqDomainSettings.peaksInPpm = 2.008; - -%set zeroFillingParameter to get smooth approximations -a.Parameter.FreqAlignFreqDomainSettings.zeroFillFactor = 50; +%% +%prepare Lenkinski correction, correct only spectra, not water +if exist('modulus','var') && (modulus == 1) + % setup the settings for the FrequencyAlignFreqDomain + a.Parameter.FreqAlignFreqDomainSettings.selectedCoil = 1; % check for max SNR coil + a.Parameter.FreqAlignFreqDomainSettings.selectedMix = 1; + + %indices of Interest: given in ppm + % NAA peak + a.Parameter.FreqAlignFreqDomainSettings.peaksInPpm = 2.008; + + %set zeroFillingParameter to get smooth approximations + a.Parameter.FreqAlignFreqDomainSettings.zeroFillFactor = 50; + + %search area (+-) in ppm + if isInVivo + a.Parameter.FreqAlignFreqDomainSettings.searchArea = 0.1; + else + a.Parameter.FreqAlignFreqDomainSettings.searchArea = 0.2; + end + %spline filtering is not needed if the spectra are not too noisy. + %flag to do spline filtering + a.Parameter.FreqAlignFreqDomainSettings.doSplineSmoothing = false; + %spline filtering coefficient + a.Parameter.FreqAlignFreqDomainSettings.splineSmoothingCoeff = 0.01; + % do the actual Frequency Alignment + a = a.FrequencyAlignFreqDomain; + + ppmvector = a.getPpmVector(); + [~, idx5] = min(abs(ppmvector-5.55)); + idxend = length(ppmvector); + for idxAv = 1:size(a.Data{1},12) + currentDataFID = squeeze(a.Data{1}(:,1,1,1,1,1,1,1,1,1,1,idxAv)); + currentData_spec = fftshift(fft(currentDataFID(:,1))); + + x = 0:50; + g = exp(-((x-0)./15) .^(2)); + [~, idxHalf] = min(abs(g-0.5*max(g))); + g2 = g(idxHalf+2:end); + g2 = fliplr(g2)*(-1)+max(g); + filter = [ones(1,2241-45),g2,g(idxHalf:end)]; + filter = [filter, zeros(1,length(currentData_spec)-length(filter),1)]; + currentData_spec_mod = currentData_spec.*filter'; +% figure +% plot(ppmvector,filter.*max(real(currentData_spec))); hold on +% plot(ppmvector,real(currentData_spec_mod)) + +% currentData_fid_mod = ifft(ifftshift(abs(currentData_spec_mod)); + currentData_fid_mod = ifft(ifftshift(currentData_spec_mod)); +% currentData_fid_mod_trunc = currentData_fid_mod; +% currentData_fid_mod_trunc(truncPoint:end) = 0; + +% figure +% plot(ppmvector,real(fftshift(fft(currentDataFID)))) +% hold on +% plot(ppmvector,real(fftshift(fft(currentData_fid_mod)))) +% plot(ppmvector,real(fftshift(fft(currentData_fid_mod_trunc)))) +% plot(ppmvector,real(fftshift(fft(currentDataFID-currentData_fid_mod_trunc)))) +% +% figure +% plot(ppmvector,real(fftshift(fft((currentDataFID./2))))) +% hold on +% plot(ppmvector,real(fftshift(fft(real(currentData_fid_mod))))) +% plot(ppmvector,real(fftshift(fft(real(currentData_fid_mod_trunc))))) +% plot(ppmvector,real(fftshift(fft(real(currentData_fid_mod)-real(currentData_fid_mod_trunc))))) +% plot(ppmvector,real(fftshift(fft((currentDataFID./2)-real(currentData_fid_mod_trunc))))) +% set(gca, 'XDir','reverse') +% xlim([0.5 4.2]); +% +% figure +% plot(ppmvector,real(fftshift(fft((currentDataFID./2))))) +% hold on +% plot(ppmvector,real(fftshift(fft(abs(currentData_fid_mod))))) +% plot(ppmvector,real(fftshift(fft(abs(currentData_fid_mod_trunc))))) +% plot(ppmvector,real(fftshift(fft(abs(currentData_fid_mod)-abs(currentData_fid_mod_trunc))))) +% plot(ppmvector,real(fftshift(fft((currentDataFID./2)-abs(currentData_fid_mod_trunc))))) +% set(gca, 'XDir','reverse') +% xlim([0.5 4.2]); + + + +% val5 = currentData_spec(idx5); +% valend = currentData_spec(idxend); +% yval = linspace(val5,valend,(idxend-idx5)); +% currentData_spec_mod = [currentData_spec(1:idx5); yval']; +% % currentData_spec_mod = currentData_spec_mod-valend; +% currentData_fid_mod = ifft(ifftshift(currentData_spec_mod)); + %flip tail + tail = flipud(currentData_fid_mod(truncPoint:end,1)); + tail = [tail; zeros(4096-length(tail),1)]; + summedFIDs = tail + currentData_fid_mod; + %truncate fid to remove tail (LCModel doesn't like the tail) + currentData_fid_mod_trunc = summedFIDs; + currentData_fid_mod_trunc(truncPoint:end) = 0; +% currentData_fid_mod_trunc_Lenkinski = complex(real(currentData_fid_mod_trunc),zeros(size(currentData_fid_mod_trunc))); +% currentData_fid_mod_Lenkinski = complex(real(currentData_fid_mod),zeros(size(currentData_fid_mod))); +% %add tail of FID to FID, then truncate +% tail = flipud(currentData_fid_mod_Lenkinski(1600:end,1)); +% tail = [tail; zeros(4096-length(tail),1)]; +% tail = complex(tail,zeros(size(currentData_fid_mod_Lenkinski))); +% summedFIDs = tail + currentData_fid_mod_Lenkinski; +% summedFIDsTrunc = summedFIDs; +% summedFIDsTrunc(truncPoint:end) = 0; + Data_Mod(:,1,1,1,1,1,1,1,1,1,1,idxAv) = currentData_fid_mod_trunc; + end + a.Data{1}(:,1,1,1,1,1,1,1,1,1,1,:) = Data_Mod; + + + %average data block-wise + if ~exist('nBlocks', 'var') + a.Parameter.AverageSettings.nBlocks = 1; + else + a.Parameter.AverageSettings.nBlocks = nBlocks; + end + + a = a.AverageData; +end -%search area (+-) in ppm -if isInVivo - a.Parameter.FreqAlignFreqDomainSettings.searchArea = 0.1; -else - a.Parameter.FreqAlignFreqDomainSettings.searchArea = 0.2; +%% setup the settings for the FrequencyAlignFreqDomain +if exist('modulus','var') && (modulus == 0) + a.Parameter.FreqAlignFreqDomainSettings.selectedCoil = 1; % check for max SNR coil + a.Parameter.FreqAlignFreqDomainSettings.selectedMix = 1; + + %indices of Interest: given in ppm + % NAA peak + a.Parameter.FreqAlignFreqDomainSettings.peaksInPpm = 2.008; + + %set zeroFillingParameter to get smooth approximations + a.Parameter.FreqAlignFreqDomainSettings.zeroFillFactor = 50; + + %search area (+-) in ppm + if isInVivo + a.Parameter.FreqAlignFreqDomainSettings.searchArea = 0.1; + else + a.Parameter.FreqAlignFreqDomainSettings.searchArea = 0.2; + end + %spline filtering is not needed if the spectra are not too noisy. + %flag to do spline filtering + a.Parameter.FreqAlignFreqDomainSettings.doSplineSmoothing = false; + %spline filtering coefficient + a.Parameter.FreqAlignFreqDomainSettings.splineSmoothingCoeff = 0.01; + % do the actual Frequency Alignment + a = a.FrequencyAlignFreqDomain; end -%spline filtering is not needed if the spectra are not too noisy. -%flag to do spline filtering -a.Parameter.FreqAlignFreqDomainSettings.doSplineSmoothing = false; -%spline filtering coefficient -a.Parameter.FreqAlignFreqDomainSettings.splineSmoothingCoeff = 0.01; -% do the actual Frequency Alignment -a = a.FrequencyAlignFreqDomain; %% water suppression if isInVivo - a.Parameter.HsvdSettings.bound = [-100 100]; + a.Parameter.HsvdSettings.bound = [-80 80]; else a.Parameter.HsvdSettings.bound = [-100 100]; end @@ -171,12 +303,14 @@ if isMC end %truncate data -if isInVivo - trunc_ms = 150; -% trunc_ms = 100; %MM - truncPoint = floor( trunc_ms/(a.Parameter.Headers.DwellTimeSig_ns*1e-6)); - a = a.Truncate(truncPoint); -end +% if exist('modulus','var') && (modulus == 0) + if isInVivo + trunc_ms = 150; + % trunc_ms = 100; %MM + truncPoint = floor( trunc_ms/(a.Parameter.Headers.DwellTimeSig_ns*1e-6)); + a = a.Truncate(truncPoint); + end +% end %% fMRS processing @@ -426,26 +560,28 @@ end %average on and off blocks if nBlocks == 5 %size(a.Data{1},a.meas_dim) paradigm(1) = -1; -elseif nBlocks == 10 %take second 32 averages of each ON/OFF block - paradigm = ones(1,2*nBlocks); - for i = 1:2:2*nBlocks - paradigm(i) = -1; - if (i == 11) || (i == 19) - paradigm(i) = 0; - elseif (i == 7) || (i == 15) - paradigm(i) = 1; +elseif nBlocks == 10 + if ~isempty(strfind(BOLDType,'64#1')) %take first 32 averages of each ON/OFF block + paradigm = ones(1,2*nBlocks); + for i = 1:2:2*nBlocks + paradigm(i) = -1; + if (i == 9) || (i == 17) + paradigm(i) = 0; + elseif (i == 5) || (i == 13) + paradigm(i) = 1; + end + end + else %take second 32 averages of each ON/OFF block + paradigm = ones(1,2*nBlocks); + for i = 1:2:2*nBlocks + paradigm(i) = -1; + if (i == 11) || (i == 19) + paradigm(i) = 0; + elseif (i == 7) || (i == 15) + paradigm(i) = 1; + end end end -% elseif nBlocks == 10 %take first 32 averages of each ON/OFF block -% paradigm = ones(1,2*nBlocks); -% for i = 1:2:2*nBlocks -% paradigm(i) = -1; -% if (i == 9) || (i == 17) -% paradigm(i) = 0; -% elseif (i == 5) || (i == 13) -% paradigm(i) = 1; -% end -% end end a.Parameter.fMRSAveSettings.paradigm = paradigm; a = a.fMRSAverage; %now dim 1=ON, 2=OFF @@ -454,14 +590,27 @@ data = squeeze(a.Data{1}); ppmVector = a.getPpmVector; plot(ppmVector,real(fftshift(fft(data(:,1,1))))) plot(ppmVector,real(fftshift(fft(data(:,1,2))))) +plot(ppmVector,real(fftshift(fft(data(:,1,1)-data(:,1,2))))) +if exist('modulus','var') && (modulus == 1) + plot(ppmVector,real(fftshift(fft(real(data(:,1,1)-data(:,1,2)).*2)))) +end +% plot(ppmVector,real(fftshift(fft(abs(data(:,1,1)-data(:,1,2)).*2)))) set(gca, 'XDir','reverse') -xlim([0.5 4.5]); legend('On','Off') +if exist('modulus','var') && (modulus == 1) + xlim([0.5 4.5]); legend('On','Off','Residual') +else + xlim([0.5 4.5]); legend('On','Off','Residual','Real Residual') +end if saveResults if nBlocks == 5 fig2save_ONOFF = fullfile(currentFolder, [num2str(visualType) '_ONOFF_128.fig']); elseif nBlocks == 10 - fig2save_ONOFF = fullfile(currentFolder, [num2str(visualType) '_ONOFF_64.fig']); + if ~isempty(strfind(BOLDType,'64#1')) + fig2save_ONOFF = fullfile(currentFolder, [num2str(visualType) '_ONOFF_64#1.fig']); + else + fig2save_ONOFF = fullfile(currentFolder, [num2str(visualType) '_ONOFF_64.fig']); + end end savefig(fig2save_ONOFF) close all; @@ -477,29 +626,57 @@ if saveResults if nBlocks == 5 save([filename '_' num2str(visualType) 'ON_woBOLDCorr128.mat'], 'aON') elseif nBlocks == 10 - save([filename '_' num2str(visualType) 'ON_woBOLDCorr64.mat'], 'aON') + if ~isempty(strfind(BOLDType,'64#1')) + data2save_ONOFF = [filename '_' num2str(visualType) 'ON_woBOLDCorr64#1.mat']; + else + data2save_ONOFF = [filename '_' num2str(visualType) 'ON_woBOLDCorr64.mat']; + end + save(data2save_ONOFF, 'aON') end %export to LCModel Stimulus ON addSinglet0ppm = true; + if exist('modulus','var') && (modulus == 1) + aON = a; + aON.Data{1} = complex(real(data(:,:,:,:,:,:,:,:,:,:,:,1).*2),zeros(size(data(:,:,:,:,:,:,:,:,:,:,:,1)))); + end if nBlocks == 5 aON.ExportLcmRaw('',[filename '_' num2str(visualType) 'ON_woBOLDCorr128'], addSinglet0ppm); elseif nBlocks == 10 - aON.ExportLcmRaw('',[filename '_' num2str(visualType) 'ON_woBOLDCorr64'], addSinglet0ppm); + if ~isempty(strfind(BOLDType,'64#1')) + aON.ExportLcmRaw('',[filename '_' num2str(visualType) 'ON_woBOLDCorr64#1'], addSinglet0ppm); + else + aON.ExportLcmRaw('',[filename '_' num2str(visualType) 'ON_woBOLDCorr64'], addSinglet0ppm); + end end + %saving the file Stimulus OFF aOFF = a; aOFF.Data{1} = data(:,:,:,:,:,:,:,:,:,:,:,2); if nBlocks == 5 save([filename '_' num2str(visualType) 'OFF_woBOLDCorr128.mat'], 'aOFF') elseif nBlocks == 10 - save([filename '_' num2str(visualType) 'OFF_woBOLDCorr64.mat'], 'aOFF') + if ~isempty(strfind(BOLDType,'64#1')) + data2save_ONOFF = [filename '_' num2str(visualType) 'OFF_woBOLDCorr64#1.mat']; + else + data2save_ONOFF = [filename '_' num2str(visualType) 'OFF_woBOLDCorr64.mat']; + end + save(data2save_ONOFF, 'aOFF') end + %export to LCModel Stimulus OFF addSinglet0ppm = true; + if exist('modulus','var') && (modulus == 1) + aOFF = a; + aOFF.Data{1} = complex(real(data(:,:,:,:,:,:,:,:,:,:,:,2).*2),zeros(size(data(:,:,:,:,:,:,:,:,:,:,:,2)))); + end if nBlocks == 5 aOFF.ExportLcmRaw('',[filename '_' num2str(visualType) 'OFF_woBOLDCorr128'], addSinglet0ppm); elseif nBlocks == 10 - aOFF.ExportLcmRaw('',[filename '_' num2str(visualType) 'OFF_woBOLDCorr64'], addSinglet0ppm); + if ~isempty(strfind(BOLDType,'64#1')) + aOFF.ExportLcmRaw('',[filename '_' num2str(visualType) 'OFF_woBOLDCorr64#1'], addSinglet0ppm); + else + aOFF.ExportLcmRaw('',[filename '_' num2str(visualType) 'OFF_woBOLDCorr64'], addSinglet0ppm); + end end end @@ -518,14 +695,25 @@ ppmVector = a.getPpmVector; plot(ppmVector,real(fftshift(fft(data(:,1,1))))) plot(ppmVector,real(fftshift(fft(data(:,1,2))))) plot(ppmVector,real(fftshift(fft(data(:,1,3))))) +if exist('modulus','var') && (modulus == 1) + plot(ppmVector,real(fftshift(fft(real(data(:,1,3).*2))))) +end set(gca, 'XDir','reverse') -xlim([0.5 4.5]); legend('On','Off','Residual') +if exist('modulus','var') && (modulus == 1) + xlim([0.5 4.5]); legend('On','Off','Residual') +else + xlim([0.5 4.5]); legend('On','Off','Residual','Real Residual') +end if saveResults if nBlocks == 5 fig2save_ONOFF_BOLDCorr = fullfile(currentFolder, [num2str(visualType) '_ONOFF_BOLDCorr128.fig']); elseif nBlocks == 10 - fig2save_ONOFF_BOLDCorr = fullfile(currentFolder, [num2str(visualType) '_ONOFF_BOLDCorr64.fig']); + if ~isempty(strfind(BOLDType,'64#1')) + fig2save_ONOFF_BOLDCorr = fullfile(currentFolder, [num2str(visualType) '_ONOFF_BOLDCorr64#1.fig']); + else + fig2save_ONOFF_BOLDCorr = fullfile(currentFolder, [num2str(visualType) '_ONOFF_BOLDCorr64.fig']); + end end savefig(fig2save_ONOFF_BOLDCorr) close all; @@ -540,15 +728,29 @@ if saveResults if nBlocks == 5 save([filename '_' num2str(visualType) 'ON_withBOLDCorr128.mat'], 'aON') elseif nBlocks == 10 - save([filename '_' num2str(visualType) 'ON_withBOLDCorr64.mat'], 'aON') + if ~isempty(strfind(BOLDType,'64#1')) + data2save_ONOFF = [filename '_' num2str(visualType) 'ON_withBOLDCorr64#1.mat']; + else + data2save_ONOFF = [filename '_' num2str(visualType) 'ON_withBOLDCorr64.mat']; + end + save(data2save_ONOFF, 'aON') end %export to LCModel Stimulus ON addSinglet0ppm = true; + if exist('modulus','var') && (modulus == 1) + aON = a; + aON.Data{1} = complex(real(data(:,:,:,:,:,:,:,:,:,:,:,1).*2),zeros(size(data(:,:,:,:,:,:,:,:,:,:,:,1)))); +% aON.Data{1} = real(data(:,:,:,:,:,:,:,:,:,:,:,1).*2); + end if nBlocks == 5 aON.ExportLcmRaw('',[filename '_' num2str(visualType) 'ON_withBOLDCorr128'], addSinglet0ppm); elseif nBlocks == 10 - aON.ExportLcmRaw('',[filename '_' num2str(visualType) 'ON_withBOLDCorr64'], addSinglet0ppm); + if ~isempty(strfind(BOLDType,'64#1')) + aON.ExportLcmRaw('',[filename '_' num2str(visualType) 'ON_withBOLDCorr64#1'], addSinglet0ppm); + else + aON.ExportLcmRaw('',[filename '_' num2str(visualType) 'ON_withBOLDCorr64'], addSinglet0ppm); + end end %saving the file Stimulus OFF @@ -557,15 +759,29 @@ if saveResults if nBlocks == 5 save([filename '_' num2str(visualType) 'OFF_withBOLDCorr128.mat'], 'aOFF') elseif nBlocks == 10 - save([filename '_' num2str(visualType) 'OFF_withBOLDCorr64.mat'], 'aOFF') - end + if ~isempty(strfind(BOLDType,'64#1')) + data2save_ONOFF = [filename '_' num2str(visualType) 'OFF_withBOLDCorr64#1.mat']; + else + data2save_ONOFF = [filename '_' num2str(visualType) 'OFF_withBOLDCorr64.mat']; + end + save(data2save_ONOFF, 'aOFF') + end %export to LCModel Stimulus OFF addSinglet0ppm = true; + if exist('modulus','var') && (modulus == 1) + aOFF = a; + aOFF.Data{1} = complex(real(data(:,:,:,:,:,:,:,:,:,:,:,2).*2),zeros(size(data(:,:,:,:,:,:,:,:,:,:,:,2)))); +% aOFF.Data{1} = real(data(:,:,:,:,:,:,:,:,:,:,:,1).*2); + end if nBlocks == 5 aOFF.ExportLcmRaw('',[filename '_' num2str(visualType) 'OFF_withBOLDCorr128'], addSinglet0ppm); elseif nBlocks == 10 - aOFF.ExportLcmRaw('',[filename '_' num2str(visualType) 'OFF_withBOLDCorr64'], addSinglet0ppm); + if ~isempty(strfind(BOLDType,'64#1')) + aOFF.ExportLcmRaw('',[filename '_' num2str(visualType) 'OFF_withBOLDCorr64#1'], addSinglet0ppm); + else + aOFF.ExportLcmRaw('',[filename '_' num2str(visualType) 'OFF_withBOLDCorr64'], addSinglet0ppm); + end end end diff --git a/fMRS_processing/splinefit.m b/fMRS_processing/splinefit.m new file mode 100644 index 0000000..c448a51 --- /dev/null +++ b/fMRS_processing/splinefit.m @@ -0,0 +1,526 @@ +function pp = splinefit(varargin) +%SPLINEFIT Fit a spline to noisy data. +% PP = SPLINEFIT(X,Y,BREAKS) fits a piecewise cubic spline with breaks +% (knots) BREAKS to the noisy data (X,Y). X is a vector and Y is a vector +% or an ND array. If Y is an ND array, then X(j) and Y(:,...,:,j) are +% matched. Use PPVAL to evaluate PP. +% +% PP = SPLINEFIT(X,Y,P) where P is a positive integer interpolates the +% breaks linearly from the sorted locations of X. P is the number of +% spline pieces and P+1 is the number of breaks. +% +% OPTIONAL INPUT +% Argument places 4 to 8 are reserved for optional input. +% These optional arguments can be given in any order: +% +% PP = SPLINEFIT(...,'p') applies periodic boundary conditions to +% the spline. The period length is MAX(BREAKS)-MIN(BREAKS). +% +% PP = SPLINEFIT(...,'r') uses robust fitting to reduce the influence +% from outlying data points. Three iterations of weighted least squares +% are performed. Weights are computed from previous residuals. +% +% PP = SPLINEFIT(...,BETA), where 0 < BETA < 1, sets the robust fitting +% parameter BETA and activates robust fitting ('r' can be omitted). +% Default is BETA = 1/2. BETA close to 0 gives all data equal weighting. +% Increase BETA to reduce the influence from outlying data. BETA close +% to 1 may cause instability or rank deficiency. +% +% PP = SPLINEFIT(...,N) sets the spline order to N. Default is a cubic +% spline with order N = 4. A spline with P pieces has P+N-1 degrees of +% freedom. With periodic boundary conditions the degrees of freedom are +% reduced to P. +% +% PP = SPLINEFIT(...,CON) applies linear constraints to the spline. +% CON is a structure with fields 'xc', 'yc' and 'cc': +% 'xc', x-locations (vector) +% 'yc', y-values (vector or ND array) +% 'cc', coefficients (matrix). +% +% Constraints are linear combinations of derivatives of order 0 to N-2 +% according to +% +% cc(1,j)*y(x) + cc(2,j)*y'(x) + ... = yc(:,...,:,j), x = xc(j). +% +% The maximum number of rows for 'cc' is N-1. If omitted or empty 'cc' +% defaults to a single row of ones. Default for 'yc' is a zero array. +% +% EXAMPLES +% +% % Noisy data +% x = linspace(0,2*pi,100); +% y = sin(x) + 0.1*randn(size(x)); +% % Breaks +% breaks = [0:5,2*pi]; +% +% % Fit a spline of order 5 +% pp = splinefit(x,y,breaks,5); +% +% % Fit a spline of order 3 with periodic boundary conditions +% pp = splinefit(x,y,breaks,3,'p'); +% +% % Constraints: y(0) = 0, y'(0) = 1 and y(3) + y"(3) = 0 +% xc = [0 0 3]; +% yc = [0 1 0]; +% cc = [1 0 1; 0 1 0; 0 0 1]; +% con = struct('xc',xc,'yc',yc,'cc',cc); +% +% % Fit a cubic spline with 8 pieces and constraints +% pp = splinefit(x,y,8,con); +% +% % Fit a spline of order 6 with constraints and periodicity +% pp = splinefit(x,y,breaks,con,6,'p'); +% +% See also SPLINE, PPVAL, PPDIFF, PPINT +% Author: Jonas Lundgren <splinefit@gmail.com> 2010 +% 2009-05-06 Original SPLINEFIT. +% 2010-06-23 New version of SPLINEFIT based on B-splines. +% 2010-09-01 Robust fitting scheme added. +% 2010-09-01 Support for data containing NaNs. +% 2011-07-01 Robust fitting parameter added. +% Check number of arguments +narginchk(3,8); +% Check arguments +[x,y,dim,breaks,n,periodic,beta,constr] = arguments(varargin{:}); +% Evaluate B-splines +base = splinebase(breaks,n); +pieces = base.pieces; +A = ppval(base,x); +% Bin data +[~,ibin] = histc(x,[-inf,breaks(2:end-1),inf]); +% Sparse system matrix +mx = numel(x); +ii = [ibin; ones(n-1,mx)]; +ii = cumsum(ii,1); +jj = repmat(1:mx,n,1); +if periodic + ii = mod(ii-1,pieces) + 1; + A = sparse(ii,jj,A,pieces,mx); +else + A = sparse(ii,jj,A,pieces+n-1,mx); +end +% Don't use the sparse solver for small problems +if pieces < 20*n/log(1.7*n) + A = full(A); +end +% Solve +if isempty(constr) + % Solve Min norm(u*A-y) + u = lsqsolve(A,y,beta); +else + % Evaluate constraints + B = evalcon(base,constr,periodic); + % Solve constraints + [Z,u0] = solvecon(B,constr); + % Solve Min norm(u*A-y), subject to u*B = yc + y = y - u0*A; + A = Z*A; + v = lsqsolve(A,y,beta); + u = u0 + v*Z; +end +% Periodic expansion of solution +if periodic + jj = mod(0:pieces+n-2,pieces) + 1; + u = u(:,jj); +end +% Compute polynomial coefficients +ii = [repmat(1:pieces,1,n); ones(n-1,n*pieces)]; +ii = cumsum(ii,1); +jj = repmat(1:n*pieces,n,1); +C = sparse(ii,jj,base.coefs,pieces+n-1,n*pieces); +coefs = u*C; +coefs = reshape(coefs,[],n); +% Make piecewise polynomial +pp = mkpp(breaks,coefs,dim); +%-------------------------------------------------------------------------- +function [x,y,dim,breaks,n,periodic,beta,constr] = arguments(varargin) +%ARGUMENTS Lengthy input checking +% x Noisy data x-locations (1 x mx) +% y Noisy data y-values (prod(dim) x mx) +% dim Leading dimensions of y +% breaks Breaks (1 x (pieces+1)) +% n Spline order +% periodic True if periodic boundary conditions +% beta Robust fitting parameter, no robust fitting if beta = 0 +% constr Constraint structure +% constr.xc x-locations (1 x nx) +% constr.yc y-values (prod(dim) x nx) +% constr.cc Coefficients (?? x nx) +% Reshape x-data +x = varargin{1}; +mx = numel(x); +x = reshape(x,1,mx); +% Remove trailing singleton dimensions from y +y = varargin{2}; +dim = size(y); +while numel(dim) > 1 && dim(end) == 1 + dim(end) = []; +end +my = dim(end); +% Leading dimensions of y +if numel(dim) > 1 + dim(end) = []; +else + dim = 1; +end +% Reshape y-data +pdim = prod(dim); +y = reshape(y,pdim,my); +% Check data size +if mx ~= my + mess = 'Last dimension of array y must equal length of vector x.'; + error('arguments:datasize',mess) +end +% Treat NaNs in x-data +inan = find(isnan(x)); +if ~isempty(inan) + x(inan) = []; + y(:,inan) = []; + mess = 'All data points with NaN as x-location will be ignored.'; + warning('arguments:nanx',mess) +end +% Treat NaNs in y-data +inan = find(any(isnan(y),1)); +if ~isempty(inan) + x(inan) = []; + y(:,inan) = []; + mess = 'All data points with NaN in their y-value will be ignored.'; + warning('arguments:nany',mess) +end +% Check number of data points +mx = numel(x); +if mx == 0 + error('arguments:nodata','There must be at least one data point.') +end +% Sort data +if any(diff(x) < 0) + [x,isort] = sort(x); + y = y(:,isort); +end +% Breaks +if isscalar(varargin{3}) + % Number of pieces + p = varargin{3}; + if ~isreal(p) || ~isfinite(p) || p < 1 || fix(p) < p + mess = 'Argument #3 must be a vector or a positive integer.'; + error('arguments:breaks1',mess) + end + if x(1) < x(end) + % Interpolate breaks linearly from x-data + dx = diff(x); + ibreaks = linspace(1,mx,p+1); + [~,ibin] = histc(ibreaks,[0,2:mx-1,mx+1]); + breaks = x(ibin) + dx(ibin).*(ibreaks-ibin); + else + breaks = x(1) + linspace(0,1,p+1); + end +else + % Vector of breaks + breaks = reshape(varargin{3},1,[]); + if isempty(breaks) || min(breaks) == max(breaks) + mess = 'At least two unique breaks are required.'; + error('arguments:breaks2',mess); + end +end +% Unique breaks +if any(diff(breaks) <= 0) + breaks = unique(breaks); +end +% Optional input defaults +n = 4; % Cubic splines +periodic = false; % No periodic boundaries +robust = false; % No robust fitting scheme +beta = 0.5; % Robust fitting parameter +constr = []; % No constraints +% Loop over optional arguments +for k = 4:nargin + a = varargin{k}; + if ischar(a) && isscalar(a) && lower(a) == 'p' + % Periodic conditions + periodic = true; + elseif ischar(a) && isscalar(a) && lower(a) == 'r' + % Robust fitting scheme + robust = true; + elseif isreal(a) && isscalar(a) && isfinite(a) && a > 0 && a < 1 + % Robust fitting parameter + beta = a; + robust = true; + elseif isreal(a) && isscalar(a) && isfinite(a) && a > 0 && fix(a) == a + % Spline order + n = a; + elseif isstruct(a) && isscalar(a) + % Constraint structure + constr = a; + else + error('arguments:nonsense','Failed to interpret argument #%d.',k) + end +end +% No robust fitting +if ~robust + beta = 0; +end +% Check exterior data +h = diff(breaks); +xlim1 = breaks(1) - 0.01*h(1); +xlim2 = breaks(end) + 0.01*h(end); +if x(1) < xlim1 || x(end) > xlim2 + if periodic + % Move data inside domain + P = breaks(end) - breaks(1); + x = mod(x-breaks(1),P) + breaks(1); + % Sort + [x,isort] = sort(x); + y = y(:,isort); + else + mess = 'Some data points are outside the spline domain.'; + warning('arguments:exteriordata',mess) + end +end +% Return +if isempty(constr) + return +end +% Unpack constraints +xc = []; +yc = []; +cc = []; +names = fieldnames(constr); +for k = 1:numel(names) + switch names{k} + case {'xc'} + xc = constr.xc; + case {'yc'} + yc = constr.yc; + case {'cc'} + cc = constr.cc; + otherwise + mess = 'Unknown field ''%s'' in constraint structure.'; + warning('arguments:unknownfield',mess,names{k}) + end +end +% Check xc +if isempty(xc) + mess = 'Constraints contains no x-locations.'; + error('arguments:emptyxc',mess) +else + nx = numel(xc); + xc = reshape(xc,1,nx); +end +% Check yc +if isempty(yc) + % Zero array + yc = zeros(pdim,nx); +elseif numel(yc) == 1 + % Constant array + yc = zeros(pdim,nx) + yc; +elseif numel(yc) ~= pdim*nx + % Malformed array + error('arguments:ycsize','Cannot reshape yc to size %dx%d.',pdim,nx) +else + % Reshape array + yc = reshape(yc,pdim,nx); +end +% Check cc +if isempty(cc) + cc = ones(size(xc)); +elseif numel(size(cc)) ~= 2 + error('arguments:ccsize1','Constraint coefficients cc must be 2D.') +elseif size(cc,2) ~= nx + mess = 'Last dimension of cc must equal length of xc.'; + error('arguments:ccsize2',mess) +end +% Check high order derivatives +if size(cc,1) >= n + if any(any(cc(n:end,:))) + mess = 'Constraints involve derivatives of order %d or larger.'; + error('arguments:difforder',mess,n-1) + end + cc = cc(1:n-1,:); +end +% Check exterior constraints +if min(xc) < xlim1 || max(xc) > xlim2 + if periodic + % Move constraints inside domain + P = breaks(end) - breaks(1); + xc = mod(xc-breaks(1),P) + breaks(1); + else + mess = 'Some constraints are outside the spline domain.'; + warning('arguments:exteriorconstr',mess) + end +end +% Pack constraints +constr = struct('xc',xc,'yc',yc,'cc',cc); +%-------------------------------------------------------------------------- +function pp = splinebase(breaks,n) +%SPLINEBASE Generate B-spline base PP of order N for breaks BREAKS +breaks = breaks(:); % Breaks +breaks0 = breaks'; % Initial breaks +h = diff(breaks); % Spacing +pieces = numel(h); % Number of pieces +deg = n - 1; % Polynomial degree +% Extend breaks periodically +if deg > 0 + if deg <= pieces + hcopy = h; + else + hcopy = repmat(h,ceil(deg/pieces),1); + end + % to the left + hl = hcopy(end:-1:end-deg+1); + bl = breaks(1) - cumsum(hl); + % and to the right + hr = hcopy(1:deg); + br = breaks(end) + cumsum(hr); + % Add breaks + breaks = [bl(deg:-1:1); breaks; br]; + h = diff(breaks); + pieces = numel(h); +end +% Initiate polynomial coefficients +coefs = zeros(n*pieces,n); +coefs(1:n:end,1) = 1; +% Expand h +ii = [1:pieces; ones(deg,pieces)]; +ii = cumsum(ii,1); +ii = min(ii,pieces); +H = h(ii(:)); +% Recursive generation of B-splines +for k = 2:n + % Antiderivatives of splines + for j = 1:k-1 + coefs(:,j) = coefs(:,j).*H/(k-j); + end + Q = sum(coefs,2); + Q = reshape(Q,n,pieces); + Q = cumsum(Q,1); + c0 = [zeros(1,pieces); Q(1:deg,:)]; + coefs(:,k) = c0(:); + % Normalize antiderivatives by max value + fmax = repmat(Q(n,:),n,1); + fmax = fmax(:); + for j = 1:k + coefs(:,j) = coefs(:,j)./fmax; + end + % Diff of adjacent antiderivatives + coefs(1:end-deg,1:k) = coefs(1:end-deg,1:k) - coefs(n:end,1:k); + coefs(1:n:end,k) = 0; +end +% Scale coefficients +scale = ones(size(H)); +for k = 1:n-1 + scale = scale./H; + coefs(:,n-k) = scale.*coefs(:,n-k); +end +% Reduce number of pieces +pieces = pieces - 2*deg; +% Sort coefficients by interval number +ii = [n*(1:pieces); deg*ones(deg,pieces)]; +ii = cumsum(ii,1); +coefs = coefs(ii(:),:); +% Make piecewise polynomial +pp = mkpp(breaks0,coefs,n); +%-------------------------------------------------------------------------- +function B = evalcon(base,constr,periodic) +%EVALCON Evaluate linear constraints +% Unpack structures +breaks = base.breaks; +pieces = base.pieces; +n = base.order; +xc = constr.xc; +cc = constr.cc; +% Bin data +[~,ibin] = histc(xc,[-inf,breaks(2:end-1),inf]); +% Evaluate constraints +nx = numel(xc); +B0 = zeros(n,nx); +for k = 1:size(cc,1) + if any(cc(k,:)) + B0 = B0 + repmat(cc(k,:),n,1).*ppval(base,xc); + end + % Differentiate base + coefs = base.coefs(:,1:n-k); + for j = 1:n-k-1 + coefs(:,j) = (n-k-j+1)*coefs(:,j); + end + base.coefs = coefs; + base.order = n-k; +end +% Sparse output +ii = [ibin; ones(n-1,nx)]; +ii = cumsum(ii,1); +jj = repmat(1:nx,n,1); +if periodic + ii = mod(ii-1,pieces) + 1; + B = sparse(ii,jj,B0,pieces,nx); +else + B = sparse(ii,jj,B0,pieces+n-1,nx); +end +%-------------------------------------------------------------------------- +function [Z,u0] = solvecon(B,constr) +%SOLVECON Find a particular solution u0 and null space Z (Z*B = 0) +% for constraint equation u*B = yc. +yc = constr.yc; +tol = 1000*eps; +% Remove blank rows +ii = any(B,2); +B2 = full(B(ii,:)); +% Null space of B2 +if isempty(B2) + Z2 = []; +else + % QR decomposition with column permutation + [Q,R,~] = qr(B2); + R = abs(R); + jj = all(R < R(1)*tol, 2); + Z2 = Q(:,jj)'; +end +% Sizes +[m,ncon] = size(B); +m2 = size(B2,1); +nz = size(Z2,1); +% Sparse null space of B +Z = sparse(nz+1:nz+m-m2,find(~ii),1,nz+m-m2,m); +Z(1:nz,ii) = Z2; +% Warning rank deficient +if nz + ncon > m2 + mess = 'Rank deficient constraints, rank = %d.'; + warning('solvecon:deficient',mess,m2-nz); +end +% Particular solution +u0 = zeros(size(yc,1),m); +if any(yc(:)) + % Non-homogeneous case + u0(:,ii) = yc/B2; + % Check solution + if norm(u0*B - yc,'fro') > norm(yc,'fro')*tol + mess = 'Inconsistent constraints. No solution within tolerance.'; + error('solvecon:inconsistent',mess) + end +end +%-------------------------------------------------------------------------- +function u = lsqsolve(A,y,beta) +%LSQSOLVE Solve Min norm(u*A-y) +% Avoid sparse-complex limitations +if issparse(A) && ~isreal(y) + A = full(A); +end +% Solution +u = y/A; +% Robust fitting +if beta > 0 + [m,n] = size(y); + alpha = 0.5*beta/(1-beta)/m; + for k = 1:3 + % Residual + r = u*A - y; + rr = r.*conj(r); + rrmean = sum(rr,2)/n; + rrmean(~rrmean) = 1; + rrhat = (alpha./rrmean)'*rr; + % Weights + w = exp(-rrhat); + spw = spdiags(w',0,n,n); + % Solve weighted problem + u = (y*spw)/(A*spw); + end +end \ No newline at end of file diff --git a/fMRS_processing/subtractBaseline_GradEcho.m b/fMRS_processing/subtractBaseline_GradEcho.m new file mode 100644 index 0000000..4dae3a6 --- /dev/null +++ b/fMRS_processing/subtractBaseline_GradEcho.m @@ -0,0 +1,164 @@ +function subtractBaseline_GradEcho(currentDataPath,subjectsLCModelOutputPath,currentLCModelFit,currentLCModelFitWithoutMetabolite, Met); + +% currentLCModelMatFit = strrep(strcat(currentLCModelFit, '.mat'),'#','_'); +% +% indexStart = strfind(currentLCModelFitWithoutMetabolite,'_woBaseline'); +% if ~isempty(indexStart) +% currentLCModelOutputFit = currentLCModelFitWithoutMetabolite(1:indexStart-1); +% currentLCModelCoordFit = strcat(currentLCModelOutputFit, '.coord'); +% else +% currentLCModelCoordFit = strcat(currentLCModelFitWithoutMetabolite, '.coord'); +% end + +% if ~isempty(strfind(currentLCModelFitWithoutMetabolite, '_v2')) + currentRawOutputFile = 'D:\PAPER\1H_fMRS\Data\Output\2020-02-28_1706_fMRS\adiff.coord'; +% else +% currentRawOutputFile = strcat(currentLCModelFit, '_woBaseline'); +% end + +% if Met == 'Lac' +% Met = 1.314; +% elseif Met == 'NAA' + Met = 3.911; +% else +% error('Met needs to be Lac or NAA'); +% end +% metabolitesToSubtract = {'Glu'}; +doNullingOfDownField = false; +% reconstructedSpectra = strcat(currentDataPath,currentLCModelMatFit); +% reconstructedSpectraWithoutMetabolite = strcat(currentDataPath, currentRawOutputFile); +reconstructedSpectra = 'D:\PAPER\1H_fMRS\Data\2020-02-28_1706_fMRS\adiff.mat'; +reconstructedSpectraWithoutMetabolite = strcat('D:\PAPER\1H_fMRS\Data\2020-02-28_1706_fMRS\', currentRawOutputFile); + +phase90 = -90 * pi/180; +zeroFillFactor = 2; + +%plot configs +FontSize = 14; +LineWidth = 1.5; + +% load(reconstructedSpectra, 'a'); +a = load(reconstructedSpectra); +fields = fieldnames(a); +a = a.(fields{1}); +subjectsLCModelOutputPath = 'D:\PAPER\1H_fMRS\Data\Output\2020-02-28_1706_fMRS\'; +currentLCModelCoordFit = 'adiff.coord'; +[nOfPoints, ppmVector, phasedData, fitData, baselineData, residualData, ... + metaboliteNames, metaboliteData, tableConcentrations, ppmStart, ppmEnd, ... + scanFrequency, frequencyShift, ppmGap] = ... + extractFits(subjectsLCModelOutputPath,currentLCModelCoordFit); + +% align the two spectra +fid = a.Data{1}; +spectrum = fftshift(fft(fid(:,1,1,1,1,1,1,1,1,1,1,1),size(fid,1)*zeroFillFactor)); +ppmSpectrum = a.getPpmVector(zeroFillFactor); + +[~, maxPpmValueSpectrum] = getMaxPeak(ppmSpectrum', real(spectrum), Met, 0.1); +[~, maxPpmValueLCModel] = getMaxPeak(ppmVector, phasedData, Met, 0.1); + +frequencyShiftDiff = maxPpmValueSpectrum - maxPpmValueLCModel; +fMRSData_withBaseline = a.ApplyFrequencyShift(frequencyShiftDiff); +%get the aligned reconstructed spectra +fid = fMRSData_withBaseline.Data{1}; +spectrum = fftshift(fft(fid(:,1,1,1,1,1,1,1,1,1,1,1),size(fid,1)*zeroFillFactor)); +% max of the reconstructed spectrum +if isempty(ppmGap) + ppmSpectrumMask = (ppmSpectrum < ppmStart) & (ppmSpectrum > ppmEnd); + [~,idx] = find(ppmSpectrumMask == 1); + ppmSpectrumMask(idx(1)-1) = 1; + ppmSpectrumMask(idx(end)+1) = 1; + ppmMetaboliteMask = (ppmVector < ppmStart) & (ppmVector > ppmEnd); +else + ppmSpectrumMask = (ppmSpectrum < ppmGap) & (ppmSpectrum > ppmEnd); + ppmMetaboliteMask = (ppmVector < ppmGap) & (ppmVector > ppmEnd); +end +maxSpectrum = max(real(spectrum(ppmSpectrumMask))); %spectrum between 0.6 and 4.1 ppm +% max of the LCModel fit +maxPhasedData = max(phasedData); +% calculate scaling +scalingFactor = maxSpectrum/maxPhasedData; +oldSpectrum = spectrum; +% for indexMetabolite = 1:length(metabolitesToSubtract) +% metaboliteToSubtract = metabolitesToSubtract{indexMetabolite}; +% indexMetaboliteToSubtract = find(strcmp(metaboliteNames,metaboliteToSubtract)); +% if isempty(indexMetaboliteToSubtract) +% error('Metabolite %s not found in fit',metaboliteToSubtract); +% end + +% spectrumToSubtract = metaboliteData{1}.metaboliteSpectrum(ppmMetaboliteMask); + spectrumToSubtract = metaboliteData{1}.metaboliteSpectrum; +% spectrumToSubtract = baselineData; + spectrumToSubtract(1) = 0; + %eliminate first point, which is anyway an error; Also scale it + spectrumToSubtractFlipped = flipud(spectrumToSubtract).*scalingFactor; + + spectrumToSubtractReal = zeros(size(oldSpectrum)); + spectrumToSubtractReal(ppmSpectrumMask) = spectrumToSubtractReal(ppmSpectrumMask) + spectrumToSubtractFlipped; + fidToSubtract = ifft(ifftshift(complex(spectrumToSubtractReal))); + fidToSubtract(length(fidToSubtract)/2:end)=0; + spectrumToSubtractPhased90 = fftshift(fft(fidToSubtract .* exp(1i*phase90))).*2; %multiply by 2 to account for nulling the half of the FID + spectrumToSubtractImag = real(spectrumToSubtractPhased90); + newSpectrumReal = real(oldSpectrum) - spectrumToSubtractReal; + newSpectrumImag = imag(oldSpectrum) - spectrumToSubtractImag; + gradmodSpectrum = complex(spectrumToSubtractReal,spectrumToSubtractImag); + gradmodSpectrumFID = ifft(ifftshift(gradmodSpectrum)); + newSpectrum = complex(newSpectrumReal, newSpectrumImag); + + if (doNullingOfDownField) + newSpectrum(length(newSpectrum)/2:end) = 0; + end + + oldSpectrum = newSpectrum; +% end + +figure +% plot(ppmVector, phasedData.*scalingFactor) +% hold on +plot(ppmSpectrum, real(spectrum),'r') +hold on +plot(ppmSpectrum, real(newSpectrum),'k') +set(gca,'xDir','reverse') +xlim([3.5 5.9]) +title(sprintf('Difference spectrum with and w/o grad mod')) +legend('Before subtraction','After subtration') + +% fig2save_Conc = fullfile(currentDataPath, strcat(strrep(currentRawOutputFile,'#','_'), '.fig')); +% savefig(fig2save_Conc) + +close all + +% figure(101) +% hold on +% p1 = plot(ppmSpectrum, real(spectrum), 'r'); +% hold on +% p2 = plot(ppmSpectrum, real(newSpectrum),'k'); +% xlim([0 4.2]) +% xlabel('[ppm]'); +% % ylim([(indexTE+1) * offsetPlot-offsetPlot*0.5 5e-5]); +% set(gca,'xDir','reverse') +% set(gca,'ytick',[]); +% set(gca,'fontsize',FontSize); +% set(p1,'LineWidth',LineWidth); +% set(p2,'LineWidth',LineWidth); +% title('Macromolecular baseline with and w/o the Cr peak') + +fMRSData_woGradMod = fMRSData_withBaseline; +newFid = ifft(ifftshift(newSpectrum)); +fMRSData_woGradMod.Data{1} = newFid; +% trunc_ms = 250; +% truncPoint = floor( trunc_ms/(fMRSData_woBaseline.Parameter.Headers.DwellTimeSig_ns*1e-6)); +% fMRSData_woBaseline = fMRSData_woBaseline.Truncate(truncPoint); + +ExpName = fullfile(currentDataPath, strcat(currentRawOutputFile, '.fig')); +save(strrep(reconstructedSpectraWithoutMetabolite,'#','_'),'fMRSData_woBaseline'); +% fMRSData_woBaseline.ExportLcmRaw(currentDataPath, strrep(currentRawOutputFile,'#','_'), 'Yes', 'Yes'); +end + +function [maxValue, maxPpmValue] = getMaxPeak(ppmVector, spectrum, peakPpm, searchAreaPpm) +minPpm = peakPpm - searchAreaPpm; +maxPpm = peakPpm + searchAreaPpm; +ppmMask = (ppmVector > minPpm) & (ppmVector < maxPpm); +tempSpectrum = spectrum .* ppmMask; +[maxValue, maxIndex] = max(real(tempSpectrum)); +maxPpmValue = ppmVector(maxIndex); +end diff --git a/fMRS_processing/subtractBaseline_fMRS.m b/fMRS_processing/subtractBaseline_fMRS.m index 4d60e2d..890b7f9 100644 --- a/fMRS_processing/subtractBaseline_fMRS.m +++ b/fMRS_processing/subtractBaseline_fMRS.m @@ -25,7 +25,11 @@ else end % metabolitesToSubtract = {'Glu'}; doNullingOfDownField = false; -reconstructedSpectra = strcat(currentDataPath,currentLCModelMatFit); +if ~isempty(strfind(currentLCModelFit,'#')) + reconstructedSpectra = strrep(strcat(currentDataPath,strrep(currentLCModelMatFit,'_1','#1')),'_v2',''); +else + reconstructedSpectra = strrep(strcat(currentDataPath,currentLCModelMatFit),'_v2',''); +end reconstructedSpectraWithoutMetabolite = strcat(currentDataPath, currentRawOutputFile); phase90 = -90 * pi/180; @@ -62,7 +66,7 @@ if isempty(ppmGap) ppmSpectrumMask = (ppmSpectrum < ppmStart) & (ppmSpectrum > ppmEnd); [~,idx] = find(ppmSpectrumMask == 1); ppmSpectrumMask(idx(1)-1) = 1; - ppmSpectrumMask(idx(end)+1) = 1; +% ppmSpectrumMask(idx(end)+1) = 1; ppmMetaboliteMask = (ppmVector < ppmStart) & (ppmVector > ppmEnd); else ppmSpectrumMask = (ppmSpectrum < ppmGap) & (ppmSpectrum > ppmEnd); diff --git a/fMRS_processing/subtractGradientModulation.m b/fMRS_processing/subtractGradientModulation.m new file mode 100644 index 0000000..85b0e65 --- /dev/null +++ b/fMRS_processing/subtractGradientModulation.m @@ -0,0 +1,205 @@ +function subtractGradientModulation(a) +% a needs difference spectrum in mix 1, and water spectrum in mix 2 + +%% +%%%%%% +% Optimization protocol to fit modulation and subtract it from spectrum. +% Works bad for summed spectra, doesn't work at all for individual spectra +% since SNR is too low, modulation peak cannot be fitted +%%%%%% +%% + +a.Parameter.FreqAlignFreqDomainSettings.peaksInPpm = 4.66; +a.Parameter.FreqAlignFreqDomainSettings.selectedMix = 2; +a = a.FrequencyAlignFreqDomain(); + +fid = a.Data{1}(:,1,1,1,1,1,1,1,1,1); +ppmVector = a.getPpmVector(); +%ppm range where to minimize (DF grad mod peak) +% ppmRange = [3.7 4.3]; +ppmRange = [5.1 5.7]; +ppmRangeIndices = (ppmVector < ppmRange(2)) & (ppmVector > ppmRange(1)); +%ppm range where to calculate baseline offset from +ppmRangeBaseline = [9.0 13]; +ppmRangeIndicesBaseline = (ppmVector < ppmRangeBaseline(2)) & (ppmVector > ppmRangeBaseline(1)); +%ppm range for linear smoothness correction +ppmRangeSmoothness1 = [5.4 5.45]; +ppmRangeIndicesSmoothness1 = (ppmVector < ppmRangeSmoothness1(2)) & (ppmVector > ppmRangeSmoothness1(1)); +ppmRangeSmoothness2 = [5.375 5.475]; +ppmRangeIndicesSmoothness2 = (ppmVector < ppmRangeSmoothness2(2)) & (ppmVector > ppmRangeSmoothness2(1)); +ppmRangeIndicesSmoothness2 = ppmRangeIndicesSmoothness2 & (~ppmRangeIndicesSmoothness1); + +time = (0:length(fid) - 1)' * (1/a.Parameter.Headers.Bandwidth_Hz); +phase0 = 0; %phase of grad mod start value +conc = 10; %grad mod concentration start value +shift0 = 0; %freq shift of grad mod start value +conc2 = 1e5; %water concentration start value + +%create peak to fit gradient modulation downfield +scanFrequency = a.Parameter.Headers.ScanFrequency; +% f = (3.99-4.66) *scanFrequency*1E-6; %Hz +f = (5.42-4.66) *scanFrequency*1E-6; %Hz +f_water = (4.7-4.66) *scanFrequency*1E-6; %Hz +T2 = 0.2; %s +singlet = exp(1i*2*pi*f*time).*exp(-time/T2); +Fgau = 30; %parameter that sets the decay rate +W = exp(- time.^2*(Fgau)^2); +singletDF = singlet.*W; + +%create broad water peak to mimic water residual in spectrum +T2_water = 0.03; %s +waterPeakSpectrum = fftshift(fft(exp(1i*2*pi*f_water*time).*exp(-time/T2_water).*exp(- time.^2*(500)^2))); + +%scale singlet to 0.01663 +maxValSinglet2 = max(real(fftshift(fft(singletDF)))); +singletDF = singletDF ./ maxValSinglet2 .* 0.01663; +singletSpec = fftshift(fft(singletDF)); +% figure +% plot(ppmVector,real(gradmodSpectrum)); hold on; +% plot(ppmVector,(real(fftshift(fft((-singlet2)))))) +% plot(ppmVector,(real(waterPeakSpectrum))) +% xlim([5.2 5.6]); hold off + +x0 = [phase0, conc, shift0,conc2]; +lb = [-180, 0, -15,0]; +ub = [180, Inf, 15,Inf]; +options = optimset('Algorithm', 'trust-region-reflective', ... + 'FinDiffType', 'central', ... + 'Jacobian', 'off', ... + 'DerivativeCheck', 'on', ... + 'TolFun', 1e-40, ... + 'TolX', 1e-40, ... + 'MaxFunEvals', 20000); +[x,resnorm,residual,exitflag,output] = lsqnonlin(@(xSolver)CostFunGradientMod(xSolver,fid, singletSpec, ppmRangeIndices, time, ... + ppmRangeIndicesBaseline, waterPeakSpectrum, false, ppmVector, ppmRangeIndicesSmoothness1, ppmRangeIndicesSmoothness2), x0, lb, ub,options); +calculated_phase0 = x(1) +calculated_conc = x(2) +calculated_shift = x(3) +[~, phasedGradModDF, fidShifted] = CostFunGradientMod(x, fid, singletSpec, ppmRangeIndices, time, ... + ppmRangeIndicesBaseline, waterPeakSpectrum, true, ppmVector, ppmRangeIndicesSmoothness1, ppmRangeIndicesSmoothness2); +% figure; +% spectrumShifted = fftshift(fft(fidShifted)); +% plot(ppmVector, real(spectrumShifted)); +% hold on +% plot(ppmVector, real(phasedGradMod)); +% plot(ppmVector, real(spectrumShifted-phasedGradMod)); + +% shift the gradient modulation back to the position in the original fid (a.Data{1}) +phasedGradModFid = ifft(ifftshift(phasedGradModDF)); +phasedGradModFid = phasedGradModFid .* exp(1i * calculated_shift *2*pi * time); +phasedGradModDF = fftshift(fft(phasedGradModFid)); + +figure; +spectrum = fftshift(fft(fid)); +plot(ppmVector, real(spectrum)); +hold on +plot(ppmVector, real(phasedGradModDF)); +plot(ppmVector, real(spectrum-phasedGradModDF)); +set(gca, 'XDir','reverse') + +% check frequency of MC water +zeroFillFactor = 16; +fidWater = a.Data{1}(:,1,1,1,1,1,1,1,2); +spectrumWater = fftshift(fft(fidWater(:,1),size(fidWater,1)*zeroFillFactor)); +ppmSpectrum = a.getPpmVector(zeroFillFactor); + +[~, idxWater] = max(spectrumWater); +ppmWater = ppmSpectrum(idxWater); +% calculate shift gradient modulation to the diff of MC water (~- 4.66) +phasedGradModDFfid = ifft(ifftshift(phasedGradModDF)); +spectrumPhasedGradModDF = fftshift(fft(phasedGradModDFfid(:,1),size(phasedGradModDFfid,1)*zeroFillFactor)); +[~, idxGM] = max(abs(spectrumPhasedGradModDF)); +ppmGM_DF = ppmSpectrum(idxGM); +deltappm_DF = ppmGM_DF - ppmWater; + +% mirror the gradient modulation into the upfield +% idxUF = idxWater-(idxGM-idxWater); +% phasedGradModUF_wrongShift = flipud(-phasedGradModDF); +% [val_wrongShift_max, idxUF_wrongShift_max] = max(real(phasedGradModUF_wrongShift)); +% [val_wrongShift_min, idxUF_wrongShift_min] = min(real(phasedGradModUF_wrongShift)); +% if abs(val_wrongShift_max) > abs(val_wrongShift_min) +% idxUF_wrongShift = idxUF_wrongShift_max; +% else +% idxUF_wrongShift = idxUF_wrongShift_min; +% end +% if idxUF_wrongShift > idxUF +% idxUF_Diff = idxUF_wrongShift - idxUF; +% phasedGradModUF = phasedGradModUF_wrongShift(idxUF_Diff+1:end); +% phasedGradModUF = [phasedGradModUF; (ones(idxUF_Diff,1).*phasedGradModUF_wrongShift(end))]; +% else +% idxUF_Diff = idxUF - idxUF_wrongShift; +% phasedGradModUF = (ones(idxUF_Diff,1).*phasedGradModUF_wrongShift(idxUF_Diff)); +% phasedGradModUF = [phasedGradModUF; phasedGradModUF_wrongShift(1:end-idxUF_Diff)]; +% end +% phasedGradMod = phasedGradModUF + phasedGradModDF; + +ppmGM_UF = ppmWater - deltappm_DF; +scanFrequency = a.Parameter.Headers.ScanFrequency; +f = (ppmGM_UF-4.66) *scanFrequency*1E-6; %Hz +f_water = (4.7-4.66) *scanFrequency*1E-6; %Hz +T2 = 0.2; %s +singlet = exp(1i*2*pi*f*time).*exp(-time/T2); +Fgau = 30; %parameter that sets the decay rate +W = exp(- time.^2*(Fgau)^2); +singletUF = singlet.*W; +xUF = x; +xUF(1) = x(1)-180; %punktsymmetrisch +xUF(3) = 0; +maxValSingletUF = max(real(fftshift(fft(singletUF)))); +singletUF = singletUF ./ maxValSingletUF .* 0.01663; +singletSpecUF = fftshift(fft(singletUF)); +[~, phasedGradModUF, fidUF] = CostFunGradientMod(xUF, fid, singletSpecUF, ppmRangeIndices, time, ... + ppmRangeIndicesBaseline, waterPeakSpectrum, true, ppmVector, ppmRangeIndicesSmoothness1, ppmRangeIndicesSmoothness2); + +% subtract gradient modulation from fid +phasedGradMod = phasedGradModUF + phasedGradModDF; +spectrum_woGM = spectrum-phasedGradMod; +figure +plot(ppmVector, phasedGradMod); +hold on +plot(ppmVector, spectrum); +plot(ppmVector, spectrum_woGM); +set(gca, 'XDir','reverse') +legend('FitModel','Spectrum','wo GM') +end +function [res, phasedGradMod, fid] = CostFunGradientMod(x, fid, gradmodSpectrum, ppmRangeIndices, time, ... + ppmRangeIndicesBaseline, waterPeakSpectrum, do_plot, ppmVector, ppmRangeIndicesSmoothness1, ppmRangeIndicesSmoothness2) + phase0 = x(1); + conc = x(2); + shift = x(3); + conc2 = x(4); + + %shift spectrum, not GM peak to fit. Have to shift spectrum back in the + %end + fid = fid .* exp(-1i * shift *2*pi * time); + spectrum = fftshift(fft(fid)); + %apply phase and scale with conc the gradModSpectrum (singlet model used to fit) + phasedGradMod = gradmodSpectrum .* exp(-1i * pi/180 * phase0) .* conc; + % + residual = spectrum-phasedGradMod-waterPeakSpectrum.*conc2; + + %calculate baseline offset + baselineROI = residual(ppmRangeIndicesBaseline); + baselineOffset = mean(baselineROI); + %residual + residual = residual-baselineOffset; +% + residualROI = residual(ppmRangeIndices); + residualROI_1 = residual(ppmRangeIndicesSmoothness1);%peak + residualROI_2 = residual(ppmRangeIndicesSmoothness2);%around peak + nonLinearity = mean(residualROI_1) - mean(residualROI_2);%nonlinearity constraint calculation + nonLinearityMatrix = repmat(nonLinearity, length(residualROI),1); + % get the res on the desired range + res = [real(residualROI); imag(residualROI); real(nonLinearityMatrix); imag(nonLinearityMatrix)]; + if do_plot + figure; + plot(ppmVector,real(spectrum-baselineOffset)); + hold on; + plot(ppmVector,real(residual.*ppmRangeIndices')); + plot(ppmVector,real(residual)); + plot(ppmVector,real(phasedGradMod)); + plot(ppmVector,real(waterPeakSpectrum.*conc2)) + set(gca, 'XDir','reverse') + legend('spectrum w/o offset','residual around GM DF peak','residual','phased peak to fit','water peak baseline'); + end +end \ No newline at end of file diff --git a/fMRS_processing/subtract_MMBaseline_LCModelBaseline.m b/fMRS_processing/subtract_MMBaseline_LCModelBaseline.m new file mode 100644 index 0000000..0347442 --- /dev/null +++ b/fMRS_processing/subtract_MMBaseline_LCModelBaseline.m @@ -0,0 +1,248 @@ +function subtract_MMBaseline_LCModelBaseline() +pathName = 'fMRS data path'; %first version, no modulus correction for gradient sideband removal +% pathName = 'fMRS data path modulus'; %second version, with modulus correction for gradient sideband, only UF can be processed +% sampleCriteria = {'Output', 'LCModelConfig'}; +[localFilePathBase] = pathToDataFolder(pathName); +StimType = {'RestON', 'RestOFF'}; %'StimON', 'StimOFF', 'RestON', 'RestOFF' +if ~isempty(strfind(StimType{1},'Stim')) + visualType = 'Stim'; +elseif ~isempty(strfind(StimType{1},'Rest')) + visualType = 'Rest'; +else + error('StimType needs to be Stim or Rest'); +end +Met = 'NAA'; +if Met == 'Lac' + Met = 1.314; +elseif Met == 'NAA' + Met = 2.008; +else + error('Met needs to be Lac or NAA'); +end +BOLDTypes = {'_woBOLDCorr128', '_withBOLDCorr128', '_woBOLDCorr64', '_woBOLDCorr64#1', '_withBOLDCorr64', '_withBOLDCorr64#1'}; %_woBOLDCorr128, _withBOLDCorr128, _woBOLDCorr64, _woBOLDCorr64#1, _withBOLDCorr64, _withBOLDCorr64#1 +for idxBOLDType = 1:length(BOLDTypes) + BOLDType = BOLDTypes(idxBOLDType); + ordersFMRS = strcat(StimType,BOLDType);% + for idxOrderFMRS = 1:length(ordersFMRS) + orderFMRS = ordersFMRS{idxOrderFMRS}; + MMBType = '_MMBSummed_v2'; %_MMBIndFiltered, _MMBSummed, _MMBInd, _MMBSimulated + % subjects = {'3333';}; + subjects = {'2823';'5166';'9810';'2774';'1658';'5269';'1706';'1004';... + '4085';'3333';'4012';'4085';'6524'}; + % prefixes = {'2020-03-10_';}; + prefixes = {'2020-02-18_';'2020-02-21_';'2020-02-21_';'2020-02-26_';... + '2020-02-27_';'2020-02-27_';'2020-02-28_';'2020-03-02_';.... + '2020-03-02_';'2020-03-10_';'2020-03-10_';'2020-03-13_';'2020-03-13_';}; + excludeSubjects = {'5166';'9810';'5269'}; + numberOfSubjects = length(subjects); + suffixFolder = '_fMRS'; + if strcmp(MMBType,'_MMBSummed') + excludeMet = {'NAA';'GABA';'Gln';'Glyc';'GSH';'mI';'NAAG';'PCh';'GPC';'PE';'Scyllo';'Tau';'Glc';'NAA_NAAG';'Glu_Gln';'Glyc';'mI_Glyc';'PCh'}; %for v1 + elseif strcmp(MMBType,'_MMBSummed_v2') + excludeMet = {'NAA';'Asc';'GABA';'Glc';'Gln';'GSH';'mI';'NAAG';'tCh';'PE';'Scyllo';'Tau';'NAA_NAAG';'Glu_Gln'}; %for v2 + end + + extensionTable = '.table'; + extensionCoord = '.coord'; + defaultfMRS = 'StimOFF'; + defaultSubject = 'XXXX'; + defaultSubjectsPath = 'YYYY'; + % defaultMMB = '_MMBSummed'; + defaultMMB = '_MMBSummed_v2'; + defaultLCModelUser = 'jdorst'; + + % controlFilesBase = 'fitsettings_fMRS_XXXX_'; + controlFilesBase = 'fitsettings_fMRS_v2_XXXX_'; + controlFilesBaseSuffix = '.control'; + outputFileNameBase = strcat(defaultSubject, '_'); + + %% file paths setup + controlFilesPathRemote = '/Desktop/1H_fMRS/LCModelConfig/'; + controlFilesPathLocal = [localFilePathBase, 'LCModelConfig/']; + LCModelOutputFilesPathRemote = '/Desktop/1H_fMRS/Output/'; + if ~isempty(strfind(localFilePathBase,'Modulus')) + LCModelOutputPath = [localFilePathBase, 'Output_v2_MMBSummed_Modulus/']; + else + LCModelOutputPath = [localFilePathBase, 'Output_v2_MMBSummed/']; + end + defaultControlFile = strcat(controlFilesBase, defaultfMRS, controlFilesBaseSuffix); + + subjectsPath = strcat(prefixes, subjects, suffixFolder); + + subjectsControlFilesPathRemote = strcat(controlFilesPathRemote, subjectsPath, '/'); + subjectsControlFilesPathLocal = strcat(controlFilesPathLocal, subjectsPath, '/'); + preprocessedFilesPathLocal = strcat(localFilePathBase, subjectsPath, '/'); + subjectsLCModelOutputFilesRemote = strcat(LCModelOutputFilesPathRemote, subjectsPath, '/'); + subjectsLCModelOutputPaths = strcat(LCModelOutputPath, subjectsPath, '/'); + LCModelOutputFiles = strcat(outputFileNameBase, orderFMRS, MMBType); + LCModelOutputFileswoBaseline = strcat(outputFileNameBase, orderFMRS, MMBType, '_woBaseline'); + + %% process fMRS data and save .RAW file + dataPath = strcat(localFilePathBase,subjectsPath, '/'); + + for indexCurrentSubject = 1:numberOfSubjects + subjectsLCModelOutputPath = subjectsLCModelOutputPaths{indexCurrentSubject}; + currentOutputFileswoBaseline = strrep(LCModelOutputFileswoBaseline, defaultSubject, subjects{indexCurrentSubject}); + + currentDataPath = strcat(localFilePathBase,subjectsPath{indexCurrentSubject}, '/'); + currentLCModelFit = strrep(strcat(outputFileNameBase, orderFMRS, '_v2'), defaultSubject, subjects{indexCurrentSubject}); + currentLCModelMatFit = strrep(strcat(currentLCModelFit, '.mat'),'#','_'); + + + indexStart = strfind(currentOutputFileswoBaseline,'_woBaseline'); + if ~isempty(indexStart) + currentLCModelOutputFit = currentOutputFileswoBaseline(1:indexStart-1); + currentLCModelCoordFit = strcat(currentLCModelOutputFit, '.coord'); + else + currentLCModelCoordFit = strcat(currentOutputFileswoBaseline, '.coord'); + end + + if ~isempty(strfind(currentOutputFileswoBaseline, '_v2')) + currentRawOutputFile = strcat(strrep(currentLCModelFit,'_Av','_v2_Av'), '_woBaseline_MMB'); + else + currentRawOutputFile = strcat(currentLCModelFit, '_woBaseline_MMB'); + end + + + % metabolitesToSubtract = {'Glu'}; + doNullingOfDownField = false; + if ~isempty(strfind(currentLCModelFit,'#')) + reconstructedSpectra = strrep(strcat(currentDataPath,strrep(currentLCModelMatFit,'_1','#1')),'_v2',''); + else + reconstructedSpectra = strrep(strcat(currentDataPath,currentLCModelMatFit),'_v2',''); + end + reconstructedSpectraWithoutMetabolite = strcat(strcat(currentDataPath,'MMBSubtracted/'), currentRawOutputFile); + + phase90 = -90 * pi/180; + zeroFillFactor = 2; + + %plot configs + FontSize = 14; + LineWidth = 1.5; + + % load(reconstructedSpectra, 'a'); + a = load(reconstructedSpectra); + fields = fieldnames(a); + a = a.(fields{1}); + [nOfPoints, ppmVector, phasedData, fitData, baselineData, residualData, ... + metaboliteNames, metaboliteData, tableConcentrations, ppmStart, ppmEnd, ... + scanFrequency, frequencyShift, ppmGap] = ... + extractFits(subjectsLCModelOutputPath,currentLCModelCoordFit); + + % align the two spectra + fid = a.Data{1}; + spectrum = fftshift(fft(fid(:,1,1,1,1,1,1,1,1,1,1,1),size(fid,1)*zeroFillFactor)); + ppmSpectrum = a.getPpmVector(zeroFillFactor); + + [~, maxPpmValueSpectrum] = getMaxPeak(ppmSpectrum', real(spectrum), Met, 0.1); + [~, maxPpmValueLCModel] = getMaxPeak(ppmVector, phasedData, Met, 0.1); + + frequencyShiftDiff = maxPpmValueSpectrum - maxPpmValueLCModel; + fMRSData_withBaseline = a.ApplyFrequencyShift(frequencyShiftDiff); + %get the aligned reconstructed spectra + fid = fMRSData_withBaseline.Data{1}; + spectrum = fftshift(fft(fid(:,1,1,1,1,1,1,1,1,1,1,1),size(fid,1)*zeroFillFactor)); + % max of the reconstructed spectrum + if isempty(ppmGap) + ppmSpectrumMask = (ppmSpectrum < ppmStart) & (ppmSpectrum > ppmEnd); + [~,idx] = find(ppmSpectrumMask == 1); + ppmSpectrumMask(idx(1)-1) = 1; + % ppmSpectrumMask(idx(end)+1) = 1; + ppmMetaboliteMask = (ppmVector < ppmStart) & (ppmVector > ppmEnd); + else + ppmSpectrumMask = (ppmSpectrum < ppmGap) & (ppmSpectrum > ppmEnd); + ppmMetaboliteMask = (ppmVector < ppmGap) & (ppmVector > ppmEnd); + end + maxSpectrum = max(real(spectrum(ppmSpectrumMask))); %spectrum between 0.6 and 4.1 ppm + % max of the LCModel fit + maxPhasedData = max(phasedData); + % calculate scaling + scalingFactor = maxSpectrum/maxPhasedData; + oldSpectrum = spectrum; + % for indexMetabolite = 1:length(metabolitesToSubtract) + metaboliteToSubtract = 'Leu'; + indexMetaboliteToSubtract = find(strcmp(metaboliteNames,metaboliteToSubtract)); + if isempty(indexMetaboliteToSubtract) + error('Metabolite %s not found in fit',metaboliteToSubtract); + end + ppmMetaboliteMask(1) = 1;ppmMetaboliteMask(end) = 1; + spectrumToSubtract = metaboliteData{indexMetaboliteToSubtract}.metaboliteSpectrum(ppmMetaboliteMask); + spectrumToSubtract = spectrumToSubtract + baselineData; + spectrumToSubtract(1) = 0; + %eliminate first point, which is anyway an error; Also scale it + spectrumToSubtractFlipped = flipud(spectrumToSubtract).*scalingFactor; + + spectrumToSubtractReal = zeros(size(oldSpectrum)); + spectrumToSubtractReal(ppmSpectrumMask) = spectrumToSubtractReal(ppmSpectrumMask) + spectrumToSubtractFlipped; + fidToSubtract = ifft(ifftshift(complex(spectrumToSubtractReal))); + fidToSubtract(length(fidToSubtract)/2:end)=0; + spectrumToSubtractPhased90 = fftshift(fft(fidToSubtract .* exp(1i*phase90))).*2; %multiply by 2 to account for nulling the half of the FID + spectrumToSubtractImag = real(spectrumToSubtractPhased90); + newSpectrumReal = real(oldSpectrum) - spectrumToSubtractReal; + newSpectrumImag = imag(oldSpectrum) - spectrumToSubtractImag; + newSpectrum = complex(newSpectrumReal, newSpectrumImag); + + if (doNullingOfDownField) + newSpectrum(length(newSpectrum)/2:end) = 0; + end + + oldSpectrum = newSpectrum; + % end + + figure + % plot(ppmVector, phasedData.*scalingFactor) + % hold on + plot(ppmSpectrum, real(spectrum),'r') + hold on + plot(ppmSpectrum, real(newSpectrum),'k') + set(gca,'xDir','reverse') + xlim([0 4.2]) + title(sprintf('Difference spectrum with and w/o baseline + MM')) + legend('Before subtraction','After subtration') + + fig2save_Conc = fullfile(strcat(currentDataPath,'MMBSubtracted/'), strcat(strrep(currentRawOutputFile,'#','_'), '.fig')); + savefig(fig2save_Conc) + + close all + + % figure(101) + % hold on + % p1 = plot(ppmSpectrum, real(spectrum), 'r'); + % hold on + % p2 = plot(ppmSpectrum, real(newSpectrum),'k'); + % xlim([0 4.2]) + % xlabel('[ppm]'); + % % ylim([(indexTE+1) * offsetPlot-offsetPlot*0.5 5e-5]); + % set(gca,'xDir','reverse') + % set(gca,'ytick',[]); + % set(gca,'fontsize',FontSize); + % set(p1,'LineWidth',LineWidth); + % set(p2,'LineWidth',LineWidth); + % title('Macromolecular baseline with and w/o the Cr peak') + + fMRSData_woBaseline = fMRSData_withBaseline; + newFid = ifft(ifftshift(newSpectrum)); + fMRSData_woBaseline.Data{1} = newFid; + % trunc_ms = 250; + % truncPoint = floor( trunc_ms/(fMRSData_woBaseline.Parameter.Headers.DwellTimeSig_ns*1e-6)); + % fMRSData_woBaseline = fMRSData_woBaseline.Truncate(truncPoint); + + ExpName = fullfile(strcat(currentDataPath,'MMBSubtracted/'), strcat(currentRawOutputFile, '.fig')); + % % eval([currentOutputFileswoBaseline '=fMRSData_woBaseline']) + % % save(reconstructedSpectraWithoutMetabolite,currentRawOutputFile); + save(strrep(reconstructedSpectraWithoutMetabolite,'#','_'),'fMRSData_woBaseline'); + fMRSData_woBaseline.ExportLcmRaw(strcat(currentDataPath,'MMBSubtracted/'), strrep(currentRawOutputFile,'#','_'), 'Yes', 'Yes'); + + end + end +end +end + +function [maxValue, maxPpmValue] = getMaxPeak(ppmVector, spectrum, peakPpm, searchAreaPpm) +minPpm = peakPpm - searchAreaPpm; +maxPpm = peakPpm + searchAreaPpm; +ppmMask = (ppmVector > minPpm) & (ppmVector < maxPpm); +tempSpectrum = spectrum .* ppmMask; +[maxValue, maxIndex] = max(real(tempSpectrum)); +maxPpmValue = ppmVector(maxIndex); +end diff --git a/postprocessing/plot_All_Fit_Metabolites.m b/postprocessing/plot_All_Fit_Metabolites.m index e346aa8..4f0dc25 100644 --- a/postprocessing/plot_All_Fit_Metabolites.m +++ b/postprocessing/plot_All_Fit_Metabolites.m @@ -9,8 +9,9 @@ if ~iscell(FileName) end if ~exist('downField_MM_Met','var') - downField_MM_Met = 'Met moiety'; - downField_MM_Met = 'DF'; +% downField_MM_Met = 'Met moiety'; + downField_MM_Met = 'Met moiety fMRS'; +% downField_MM_Met = 'DF'; % downField_MM_Met = 'MM'; end @@ -21,11 +22,18 @@ if ~exist('saveFigures','var') end switch downField_MM_Met - case 'Met moiety' + case 'Met moiety' metaboliteNames = {'Asp' 'Cr' 'Cr_CH2' 'GABA' 'Glu' 'Gln' 'GSH' 'Glyc' 'Lac' 'mI' 'NAA_as' 'NAA_ac' 'NAAG' 'Scyllo' 'Tau' 'tCho_P'}; metaboliteLabels = {'Asp';'tCr(CH_3)';'tCr(CH_2)';'GABA';'Glu';'Gln';'GSH';'Glyc';'Lac';'mI';'NAA(CH_2)';'NAA(CH_3)';'NAAG';'Scyllo';'Tau';'tCho+';}; xLimits = [0.5 4.097]; offsetMetabolite = 0.1; + case 'Met moiety fMRS' +% metaboliteNames = {'Asp' 'Cr' 'PCr' 'GABA' 'Gln' 'Glu' 'GPC' 'GSH' 'Glyc' 'Lac' 'mI' 'NAA' 'NAAG' 'PE' 'Scyllo' 'Tau'}; +% metaboliteLabels = {'Asp';'Cr';'PCr';'GABA';'Gln';'Glu';'GPC';'GSH';'Glyc';'Lac';'mI';'NAA';'NAAG';'PE';'Scyllo';'Tau';}; + metaboliteNames = {'Asc' 'Asp' 'Cr' 'PCr' 'GABA' 'Gln' 'Glu' 'GSH' 'Lac' 'mI' 'NAA' 'NAAG' 'tCh' 'PE' 'Scyllo' 'Tau'}; + metaboliteLabels = {'Asc';'Asp';'Cr';'PCr';'GABA';'Gln';'Glu';'GSH';'Lac';'mI';'NAA';'NAAG';'tCh';'PE';'Scyllo';'Tau';}; + xLimits = [0.5 4.097]; + offsetMetabolite = 0.1; case 'Met' metaboliteNames = {'NAA' 'NAAG' 'Asp' 'Glu' 'Gln' 'GABA' 'Lac' ... 'Cr+PCr' 'Cho+GPC+PCh' 'mI' 'sI' 'Gly' 'Glc' 'GSH' 'PE' 'Tau'}; @@ -219,6 +227,7 @@ for index =1:length(FileName) ylim([-0.21 0.115]); ylim([-0.21 0.1]); % ylim([-0.16 0.115]); + ylim([-2 1.1]); end set(gca,'xDir','reverse') set(gca,'ytick',[]); @@ -233,7 +242,7 @@ for index =1:length(FileName) set(figId, 'Units', 'Normalized', 'OuterPosition', [0, 0.04, 1, 0.96]); set(gca, 'Position', [0.13,0.11,0.75,0.815]) set(gca, 'Position', [0.13,0.11,0.75,0.88]) - saveas(figId, [PathName,FileName{index}(1:end-6), '.tif']); +% saveas(figId, [PathName,FileName{index}(1:end-6), '.tif']); savefig(figId, [PathName,FileName{index}(1:end-6), '.fig'],'compact'); end end diff --git a/postprocessing/startLCModel.m b/postprocessing/startLCModel.m index e4d7a28..289ff9c 100644 --- a/postprocessing/startLCModel.m +++ b/postprocessing/startLCModel.m @@ -1,7 +1,7 @@ function [LCModelCallerInstance] = startLCModel(controlFilesPathRemote, outputFilesPathRemote, outputFilesPathLocal) %% configuration of connection -LCModelUser = 'tborbath@mpi.localnet'; +LCModelUser = 'jdorst'; % I recommend you to change this password and the user name above, but please don't commit it LCModelPassword = 'XXXX'; -- GitLab