function varargout=conn_process(options,varargin); global CONN_x if nargin<1, options=[]; end if ischar(options), switch(lower(options)), case 'all', disp(['CONN: RUNNING ALL ANALYSIS STEPS']); conn_process([0:13]); case 'all_voxel', disp(['CONN: RUNNING ALL ANALYSIS STEPS (roi-based analyses only)']); conn_process([0:3,5:6,8:9,11:12]); case 'all_roi', disp(['CONN: RUNNING ALL ANALYSIS STEPS (roi-based analyses only)']); conn_process([0:2,4:5,7:8,10,13]); case 'setup', disp(['CONN: RUNNING SETUP STEP']); conn_process([0:5]); case 'setup_roi', disp(['CONN: RUNNING SETUP STEP (roi-based analyses only)']); conn_process([0:2,4:5]); case 'preprocessing', disp(['CONN: RUNNING PREPROCESSING STEP']); conn_process([5,6:8],varargin{:}); case 'preprocessing_gui',disp(['CONN: RUNNING PREPROCESSING STEP']); conn_process([6:8],varargin{:}); case 'preprocessing_roi',disp(['CONN: RUNNING PREPROCESSING STEP (roi-based analyses only)']); conn_process([5,7:8],varargin{:}); case 'analyses', disp(['CONN: RUNNING ANALYSIS STEP']); conn_process([8,9:13],varargin{:}); case 'analyses_gui', disp(['CONN: RUNNING ANALYSIS STEP']); conn_process(9:13,CONN_x.Analysis); case 'analyses_roi', disp(['CONN: RUNNING ANALYSIS STEP (roi-based analyses only)']); conn_process([8,10,13],varargin{:}); case 'prepare_results', conn_process(12:13,varargin{:}); case 'prepare_results_roi',conn_process(13,varargin{:}); case 'results', conn_process(14:15,varargin{:}); case 'results_voxel', [varargout{1:nargout}]=conn_process(14,varargin{:}); case 'results_roi', [varargout{1:nargout}]=conn_process(15,varargin{:}); case 'update', conn gui_setup_saveas; conn_process all; conn save; end return; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Checks dimensionality of setup files %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==0), ERR={}; if isempty(CONN_x.filename)||isempty(dir(CONN_x.filename)),ERR{end+1}=['WARNING: Project not saved or empty project information']; end try, conn_updatefilepaths; catch, ERR{end+1}=['ERROR: Files not found. Check that all your functional/structural/ROIs/first-level covariate files point to existing files.']; end nl1covariates=length(CONN_x.Setup.l1covariates.names)-1; nconditions=length(CONN_x.Setup.conditions.names)-1; if nconditions<1, ERR{end+1}=['ERROR: No conditions defined. You must define at least one condition (use onset=0; duration=inf; for encompassing the entire scanning session)']; end for nsub=1:CONN_x.Setup.nsubjects, nsess=CONN_x.Setup.nsessions(min(length(CONN_x.Setup.nsessions),nsub)); if nsess<1,ERR{end+1}=['ERROR: Subject ',num2str(nsub),' has no functional data assigned (number of sessions = 0); increase the number of sessions in Setup->Basic or remove this subject']; end for nses=1:nsess, if length(CONN_x.Setup.nscans)0); idx2=[0;find(diff(idx1)>1);length(idx1)]; for n1=1:length(idx2)-1, idx=idx1(idx2(n1)+1:idx2(n1+1)); samples{ncondition}=cat(1,samples{ncondition},idx(:)); weights{ncondition}{1}=cat(1,weights{ncondition}{1},x(idx(:))); weights{ncondition}{2}=cat(1,weights{ncondition}{2},conn_hanning(length(idx))); end n=n+1; conn_waitbar(n/N,h); end filename=fullfile(filepath,['COV_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); if str2num(version('-release'))>=14, save(filename,'-V6','data','names'); else, save(filename,'data','names'); end for n1=1:length(data), if length(maxdims)=14, save(filename,'-V6','samples','weights','names'); else, save(filename,'samples','weights','names'); end end end conn_waitbar('close',h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates DATA_Subject###_Session###.mat files (percentage signal change data at analysis mask) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==3), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.data; h=conn_waitbar(0,['Step ',num2str(sum(options<=3)),'/',num2str(length(options)),': Importing functional data']); REDO='Yes';filename=fullfile(filepath,['DATA_Subject',num2str(1,'%03d'),'_Session',num2str(1,'%03d'),'.mat']); if ~isempty(dir(filename)),if isfield(CONN_x,'gui')&&isstruct(CONN_x.gui)&&isfield(CONN_x.gui,'overwrite'), REDO=CONN_x.gui.overwrite; else, REDO=questdlg('Overwrite existing subject results?','','Yes', 'No', 'Yes');end; end N=sum(CONN_x.Setup.nsessions); if length(CONN_x.Setup.nsessions)==1, N=N*CONN_x.Setup.nsubjects; end n=0; filename=deblank(CONN_x.Setup.structural{1}{1}); Vref=spm_vol(filename); if ~isfield(CONN_x.Setup,'normalized'),CONN_x.Setup.normalized=1;end if CONN_x.Setup.normalized, filename=fullfile(fileparts(which('spm')),'apriori','brainmask.nii'); Vmask=spm_vol(filename); elseif isfield(CONN_x.Setup,'usebrainmask')&&CONN_x.Setup.usebrainmask, Vmask1=spm_vol(CONN_x.Setup.rois.files{nsub}{1}{1}); Vmask2=spm_vol(CONN_x.Setup.rois.files{nsub}{2}{1}); Vmask3=spm_vol(CONN_x.Setup.rois.files{nsub}{3}{1}); Vmask=struct('mat',Vmask1.mat,'dim',Vmask1.dim,'fname',conn_prepend('mask_',CONN_x.Setup.functional{nsub}{1}{1}(1,:)),... 'dt',[spm_type('uint8') spm_platform('bigend')]); a=spm_read_vols(Vmask1)+spm_read_vols(Vmask2)+spm_read_vols(Vmask3); try, spm_write_vol(Vmask,a>0); catch, [temp_path,temp_filename,temp_ext]=fileparts(Vmask.fname); Vmask.fname=fullfile(pwd,[temp_filename,temp_ext]); spm_write_vol(Vmask,a>0); end Vmask=spm_vol(Vmask.fname); else, Vmask=[]; end for nsub=1:CONN_x.Setup.nsubjects, if ~CONN_x.Setup.normalized, filename=deblank(CONN_x.Setup.structural{nsub}{1}); Vref=spm_vol(filename); end nsess=CONN_x.Setup.nsessions(min(length(CONN_x.Setup.nsessions),nsub)); sfile=[];%conn_prepend('',CONN_x.Setup.structural{nsub}{1},'_seg_inv_sn.mat'); for nses=1:nsess, filename=fullfile(filepath,['DATA_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); if strcmp(REDO,'Yes')||isempty(dir(filename)), warning off;Vsource=spm_vol(CONN_x.Setup.functional{nsub}{nses}{1});warning on; CONN_x.Setup.nscans{nsub}{nses}=prod(size(Vsource)); if ~CONN_x.Setup.normalized&&(isempty(Vmask)), % computes analysis mask Vmask=Vsource(1); Vmask.fname=conn_prepend('mask_',CONN_x.Setup.functional{nsub}{1}{1}(1,:)); Vmask.dt=[spm_type('uint8') spm_platform('bigend')]; a=ones(Vmask.dim(1:3)); for nsest=1:nsess, if nsest==nses,Vsourcet=Vsource;else,warning off;Vsourcet=spm_vol(CONN_x.Setup.functional{nsub}{nsest}{1});warning on;end for nt=1:numel(Vsourcet), b=spm_read_vols(Vsourcet(nt)); mb=mean(b(b>mean(b(~isnan(b)))/8)); a=a&(b>0.80*mb); end end try, spm_write_vol(Vmask,a); catch, [temp_path,temp_filename,temp_ext]=fileparts(Vmask.fname); Vmask.fname=fullfile(pwd,[temp_filename,temp_ext]); spm_write_vol(Vmask,a); end end V=conn_create_vol(filename,Vsource,[],Vref,sfile,Vmask); end n=n+1; conn_waitbar(n/N,h); end end conn_waitbar('close',h); clear data; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates sDATA_Subject###_Session###.mat files (smoothed functional data) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if 0,%any(options==2.5), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.data; h=conn_waitbar(0,['Step ',num2str(sum(options<=3)),'/',num2str(length(options)),': Smoothing functional data']); N=sum(CONN_x.Setup.nsessions); if length(CONN_x.Setup.nsessions)==1, N=N*CONN_x.Setup.nsubjects; end n=0; for nsub=1:CONN_x.Setup.nsubjects, [spath,sfile,sext]=fileparts(deblank(CONN_x.Setup.structural{nsub}{1})); nsess=CONN_x.Setup.nsessions(min(length(CONN_x.Setup.nsessions),nsub)); for nses=1:nsess, filename=fullfile(filepath,['DATA_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); fileout=fullfile(filepath,['sDATA_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); Y0=conn_vol(filename); conn_reslice(fileout,Y0.matdim.mat,Y0.matdim.dim,Y0,[],CONN_x.Setup.fwhm); n=n+1; conn_waitbar(n/N,h); end end conn_waitbar('close',h); clear data; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates ROI_Subject###_Session###.mat files (activation timecourses for each roi) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==4), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.data; h=conn_waitbar(0,['Step ',num2str(sum(options<=4)),'/',num2str(length(options)),': Importing ROI data']); REDO='Yes';filename=fullfile(filepath,['ROI_Subject',num2str(1,'%03d'),'_Session',num2str(1,'%03d'),'.mat']); if ~isempty(dir(filename)),if isfield(CONN_x,'gui')&&isstruct(CONN_x.gui)&&isfield(CONN_x.gui,'overwrite'), REDO=CONN_x.gui.overwrite; else, REDO=questdlg('Overwrite existing subject results?','','Yes', 'No', 'Yes');end; end nrois=length(CONN_x.Setup.rois.names)-1; N=sum(CONN_x.Setup.nsessions); if length(CONN_x.Setup.nsessions)==1, N=N*CONN_x.Setup.nsubjects; end N=N*nrois; n=0; for nsub=1:CONN_x.Setup.nsubjects, clear Vmask; for nroi=1:nrois, Vmask{nroi}=CONN_x.Setup.rois.files{nsub}{nroi}{1}; end ERODE=1; % erosing level for white/csf masks (voxels) (set to 0 for no erosion) if ERODE>0, for nroi=2:3, Vmask{nroi}=conn_prepend('e',CONN_x.Setup.rois.files{nsub}{nroi}{1}); if (~conn_existfile(conn_prepend('e',CONN_x.Setup.rois.files{nsub}{nroi}{1}))), [nill,nill,ext]=fileparts(Vmask{nroi}); switch(ext), case {'.img','.nii','.hdr'}, V0=spm_vol(CONN_x.Setup.rois.files{nsub}{nroi}{1}); % mask X0=spm_read_vols(V0); idx1=find(X0(:)>.5); [idxx,idxy,idxz]=ind2sub(size(X0),idx1); idxt=find(idxx>ERODE&idxxERODE&idxyERODE&idxz1, idxt(n1)=0; end; end idxt=idxt(idxt>0); idx1=idx1(idxt); X1=zeros(size(X0));X1(idx1)=1;V0.fname=conn_prepend('e',CONN_x.Setup.rois.files{nsub}{nroi}{1});spm_write_vol(V0,X1); otherwise, Vmask{nroi}=CONN_x.Setup.rois.files{nsub}{nroi}{1}; end end end end nsess=CONN_x.Setup.nsessions(min(length(CONN_x.Setup.nsessions),nsub)); for nses=1:nsess, filename=fullfile(filepath,['ROI_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); if ~isempty(dir(filename)), old=load(filename);%,'data','names','source','xyz','sampledata'); else, old=[]; end filename=fullfile(filepath,['COV_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); covariates=load(filename);covariates=cat(2,covariates.data{:}); source=fullfile(filepath,['DATA_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); Vsource=CONN_x.Setup.functional{nsub}{nses}{1}; Vsource2=[]; for n1=1:size(Vsource,1), [Vsourcepath,Vsourcename,Vsourceext]=fileparts(Vsource(n1,:)); if Vsourcename(1)~='s' || (~conn_existfile(fullfile(Vsourcepath,[Vsourcename(2:end),Vsourceext]))), Vsource2=[]; break; end Vsource2=strvcat(Vsource2,fullfile(Vsourcepath,[Vsourcename(2:end),Vsourceext])); % exists un-smooth data? end if strcmp(REDO,'Yes')||isempty(old)||~isfield(old,'sampledata'), sampledata=conn_rex(Vsource,Vmask{1},'dims',256,'level','subsetvoxels','scaling','roi','select_clusters',0,'output_type','none'); else, sampledata=old.sampledata; end if ~isempty(Vsource2), Vsource=Vsource2; end clear data names xyz; nroi1=1; for nroi=1:nrois, if ~isfield(CONN_x.Setup.rois,'mask') || length(CONN_x.Setup.rois.mask)1, [data{nroi1},namesroi{nroi},params]=conn_rex(Vsource,Vmask{nroi},'summary_measure','eigenvariate','dims',CONN_x.Setup.rois.dimensions{nroi},'conjunction_mask',mask,'level',level,'scaling','roi','select_clusters',0,'covariates',covariates,'output_type','saverex'); else, [data{nroi1},namesroi{nroi},params]=conn_rex(Vsource,Vmask{nroi},'summary_measure','mean','conjunction_mask',mask,'level',level,'scaling','roi','select_clusters',0,'covariates',covariates,'output_type','saverex'); end [data{nroi1},ok]=conn_nan(data{nroi1}); data{nroi1}=detrend(data{nroi1},'constant'); if CONN_x.Setup.rois.multiplelabels(nroi), datatemp=data{nroi1}; [Vmaskfilepath,Vmaskfilename,Vmaskfileext]=fileparts(Vmask{nroi}); for n1=1:size(datatemp,2), data{nroi1}=datatemp(:,n1); names{nroi1}=namesroi{nroi}{n1}; if ~isempty(strmatch(Vmaskfilename,names{nroi1})), names{nroi1}=[CONN_x.Setup.rois.names{nroi},names{nroi1}(numel(Vmaskfilename)+1:end)]; end Z=params.ROIinfo.basis{params.ROIinfo.trans{n1}{1}}{params.ROIinfo.trans{n1}{2}}(params.ROIinfo.trans{n1}{4},params.ROIinfo.trans{n1}{3}); XYZ=params.ROIinfo.voxels{params.ROIinfo.trans{n1}{1}}{params.ROIinfo.trans{n1}{2}}(params.ROIinfo.trans{n1}{4},:); xyz{nroi1}=mean(XYZ(Z==max(Z),:),1); nroi1=nroi1+1; end else, names{nroi1}=CONN_x.Setup.rois.names{nroi}; n1=1; Z=params.ROIinfo.basis{params.ROIinfo.trans{n1}{1}}{params.ROIinfo.trans{n1}{2}}(params.ROIinfo.trans{n1}{4},params.ROIinfo.trans{n1}{3}); XYZ=params.ROIinfo.voxels{params.ROIinfo.trans{n1}{1}}{params.ROIinfo.trans{n1}{2}}(params.ROIinfo.trans{n1}{4},:); xyz{nroi1}=mean(XYZ(Z==max(Z),:),1); nroi1=nroi1+1; end filename=fullfile(filepath,['REX_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'_ROI',num2str(nroi),'.mat']); load('REX.mat');save(filename,'params'); end n=n+1; conn_waitbar(n/N,h); end filename=fullfile(filepath,['ROI_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); if str2num(version('-release'))>=14, save(filename,'-V6','data','names','source','xyz','sampledata'); else, save(filename,'data','names','source','xyz','sampledata');end end end % eliminates ROIs not present in all subjects/sessions for nsub=1:CONN_x.Setup.nsubjects, nsess=CONN_x.Setup.nsessions(min(length(CONN_x.Setup.nsessions),nsub)); for nses=1:nsess, filename=fullfile(filepath,['ROI_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); load(filename,'names'); if nsub==1&&nses==1,ROInamesall=names; else, temp=zeros(1,length(ROInamesall)); for n1=1:length(ROInamesall), idx=strmatch(ROInamesall{n1},names,'exact'); temp(n1)=~isempty(idx); end if ~all(temp), idx=find(~temp); for n1=1:length(idx), disp(['Warning: ROI ',ROInamesall{idx(n1)},' missing from Subject ',num2str(nsub),' Session ',num2str(nses)]); end end ROInamesall={ROInamesall{find(temp)}}; end end end tmp=[]; for nsub=1:CONN_x.Setup.nsubjects, nsess=CONN_x.Setup.nsessions(min(length(CONN_x.Setup.nsessions),nsub)); for nses=1:nsess, filename=fullfile(filepath,['ROI_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); load(filename,'data','names','source','xyz','sampledata'); temp=zeros(1,length(names)); for n1=1:length(names), idx=strmatch(names{n1},ROInamesall,'exact'); temp(n1)=~isempty(idx); end if ~all(temp), if isempty(tmp), tmp=questdlg('Remove regions with incomplete data?','','Yes', 'No', 'Yes'); end if strcmp(tmp,'Yes'), data={data{find(temp)}}; names={names{find(temp)}}; xyz={xyz{find(temp)}}; if str2num(version('-release'))>=14, save(filename,'-V6','data','names','source','xyz','sampledata'); else, save(filename,'data','names','source','xyz','sampledata');end end end end end conn_waitbar('close',h); ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % updates CONN_x.Preproc structure with a subset of ROIs plus all covariates %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==5), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.data; filename1=fullfile(filepath,['ROI_Subject',num2str(1,'%03d'),'_Session',num2str(1,'%03d'),'.mat']); filename2=fullfile(filepath,['COV_Subject',num2str(1,'%03d'),'_Session',num2str(1,'%03d'),'.mat']); if isempty(dir(filename1)), disp(['Not ready to process step conn_process_5']); return; end x1=load(filename1); x2=load(filename2); CONN_x.Preproc.variables.names=cat(2,x1.names,x2.names); CONN_x.Preproc.variables.types=cat(2,repmat({'roi'},[1,length(x1.names)]),repmat({'cov'},[1,length(x2.names)])); CONN_x.Preproc.variables.deriv=cat(2,repmat({0},[1,length(x1.names)]),repmat({1},[1,length(x2.names)])); CONN_x.Preproc.variables.dimensions={}; for n1=1:length(x1.names), CONN_x.Preproc.variables.dimensions{end+1}=size(x1.data{n1},2)*ones(1,2); end for n1=1:length(x2.names), CONN_x.Preproc.variables.dimensions{end+1}=size(x2.data{n1},2)*ones(1,2); end N1=length(x1.names);N2=length(x2.names); for nsub=1:CONN_x.Setup.nsubjects, nsess=CONN_x.Setup.nsessions(min(length(CONN_x.Setup.nsessions),nsub)); for nses=1:nsess, filename2=fullfile(filepath,['COV_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); x2=load(filename2); for n1=1:N2, CONN_x.Preproc.variables.dimensions{N1+n1}=max(CONN_x.Preproc.variables.dimensions{N1+n1},size(x2.data{n1},2)*ones(1,2)); end end end if isfield(CONN_x.Preproc.confounds,'names') && ~isempty(CONN_x.Preproc.confounds.names), initial=CONN_x.Preproc.confounds.names; dims=CONN_x.Preproc.confounds.dimensions; ders=CONN_x.Preproc.confounds.deriv; else, initial={'White Matter','CSF',x2.names{:}};dims={5,5}; ders={}; end CONN_x.Preproc.confounds.names={}; CONN_x.Preproc.confounds.types={}; CONN_x.Preproc.confounds.deriv={}; CONN_x.Preproc.confounds.dimensions={}; for n1=1:length(initial), idx=strmatch(initial{n1},CONN_x.Preproc.variables.names,'exact'); if ~isempty(idx), CONN_x.Preproc.confounds.names{end+1}=CONN_x.Preproc.variables.names{idx}; CONN_x.Preproc.confounds.types{end+1}=CONN_x.Preproc.variables.types{idx}; if length(ders)>=n1&&~isempty(ders{n1}), CONN_x.Preproc.confounds.deriv{end+1}=ders{n1}; else, CONN_x.Preproc.confounds.deriv{end+1}=CONN_x.Preproc.variables.deriv{idx};end if length(dims)>=n1&&~isempty(dims{n1}), CONN_x.Preproc.confounds.dimensions{end+1}=[min(dims{n1}(1),CONN_x.Preproc.variables.dimensions{idx}(1)),CONN_x.Preproc.variables.dimensions{idx}(1)]; else, CONN_x.Preproc.confounds.dimensions{end+1}=CONN_x.Preproc.variables.dimensions{idx}; end end end if ~isfield(CONN_x.Preproc,'filter')||isempty(CONN_x.Preproc.filter), CONN_x.Preproc.filter=[0,1/(2*CONN_x.Setup.RT)]; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates DATA_Subject###_Condition###.mat files (whole-brain data after removal of confounding effects & filtering) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==6), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.data; filepathresults=CONN_x.folders.preprocessing; nconditions=length(CONN_x.Setup.conditions.names)-1; h=conn_waitbar(0,['Step ',num2str(sum(options<=6)),'/',num2str(length(options)),': Preprocessing functional data']); REDO='Yes';filename=fullfile(filepathresults,['DATA_Subject',num2str(1,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); if ~isempty(dir(filename)),if isfield(CONN_x,'gui')&&isstruct(CONN_x.gui)&&isfield(CONN_x.gui,'overwrite'), REDO=CONN_x.gui.overwrite; else, REDO=questdlg('Overwrite existing subject results?','','Yes', 'No', 'Yes');end; end N=CONN_x.Setup.nsubjects; %sum(CONN_x.Setup.nsessions); if length(CONN_x.Setup.nsessions)==1, N=N*CONN_x.Setup.nsubjects; end n=0; for nsub=1:CONN_x.Setup.nsubjects, filename=fullfile(filepathresults,['DATA_Subject',num2str(nsub,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); if strcmp(REDO,'Yes')||isempty(dir(filename)), nsess=CONN_x.Setup.nsessions(min(length(CONN_x.Setup.nsessions),nsub)); clear Y X iX X1 X2 C; for nses=1:nsess, % loads all ROI COV COND data for this subject filename=fullfile(filepath,['DATA_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); if isempty(dir(filename)), disp(['Not ready to process step conn_process_6']); conn_waitbar('close',h); return; end Y{nses}=conn_vol(filename); filename=fullfile(filepath,['ROI_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); X1{nses}=load(filename); filename=fullfile(filepath,['COV_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); X2{nses}=load(filename); filename=fullfile(filepath,['COND_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); C{nses}=load(filename); X{nses}=conn_designmatrix(CONN_x.Preproc.confounds,X1{nses},X2{nses}); %X{nses}=conn_filter(CONN_x.Setup.RT,CONN_x.Preproc.filter,X{nses}); if size(X{nses},1)~=CONN_x.Setup.nscans{nsub}{nses}, error('Wrong dimensions'); end iX{nses}=pinv(X{nses}); end clear nsamples time0 dataroi conditionweights; for ncondition=1:nconditions, % computes number of samples per condition nsamples{ncondition}=0; for nses=1:nsess, nsamples{ncondition}=nsamples{ncondition}+length(C{nses}.samples{ncondition}); end % dataroi{ncondition}=cell(1,length(X1{1}.data)); conditionsweights{ncondition}=cell(1,length(C{1}.weights{ncondition})); for nses=1:nsess, for nweight=1:length(C{nses}.weights{ncondition}), conditionsweights{ncondition}{nweight}=cat(1,conditionsweights{ncondition}{nweight},C{nses}.weights{ncondition}{nweight}); end end end clear Yout; for ncondition=1:nconditions, filename=fullfile(filepathresults,['DATA_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); Yout{ncondition}=Y{1}; Yout{ncondition}.fname=filename; Yout{ncondition}.size.Nt=nsamples{ncondition}; Yout{ncondition}=conn_init_vol(Yout{ncondition}); end B=[]; for slice=1:Y{1}.matdim.dim(3), Bb=[]; if 1, % analyses per slice (all sessions together, faster but requires more memory) clear y; for nses=1:nsess, [y{nses},idx]=conn_get_slice(Y{nses},slice); if size(y{nses},1)~=CONN_x.Setup.nscans{nsub}{nses}, error('Wrong dimensions'); end if slice==1&&rank(X{nses})>=size(y{nses},1), disp(['Warning: Over-determined model (no degrees of freedom for subject ',num2str(nsub),' session ',num2str(nses),'). Please consider reducing the number, dimensions, or covariates order of the confounds or disregarding this subject/session']); end b=iX{nses}*y{nses}; y{nses}=y{nses}-X{nses}*b; y{nses}=conn_filter(CONN_x.Setup.RT,CONN_x.Preproc.filter,y{nses}); Bb=cat(1,Bb,b); end for ncondition=1:nconditions, ytemp=[]; for nses=1:nsess, ytemp=cat(1,ytemp,y{nses}(C{nses}.samples{ncondition},:)); end conn_write_slice(Yout{ncondition},ytemp,slice); end else, % analyses per slice/session (slower but requires less memory) for nses=1:nsess, [y,idx]=conn_get_slice(Y{nses},slice); if size(y,1)~=CONN_x.Setup.nscans{nsub}{nses}, error('Wrong dimensions'); end if slice==1&&rank(X{nses})>=size(y,1), disp(['Warning: Over-determined model (no degrees of freedom for subject ',num2str(nsub),' session ',num2str(nses),'). Please consider reducing the number, dimensions, or covariates order of the confounds or disregarding this subject/session']); end b=iX{nses}*y; y=y-X{nses}*b; y=conn_filter(CONN_x.Setup.RT,CONN_x.Preproc.filter,y); Bb=cat(1,Bb,b); for ncondition=1:nconditions, if nses==1, time0{ncondition}=0; end conn_write_slice(Yout{ncondition},y(C{nses}.samples{ncondition},:),slice,time0{ncondition}); time0{ncondition}=time0{ncondition}+length(C{nses}.samples{ncondition}); end end end if 0, %%% 0 to avoid memory errors B=cat(2,B,Bb); else if slice==1 V=struct('mat',Y{1}.matdim.mat,'dim',Y{1}.matdim.dim,'pinfo',[1;0;0],'fname',fullfile(filepathresults,['BETA_Subject',num2str(nsub,'%03d'),'.nii']),... 'dt',[spm_type('float32') spm_platform('bigend')]); V=repmat(V,[size(Bb,1),1]);for nh=1:numel(V),V(nh).n=[nh,1];end V=spm_create_vol(V); end t=nan+zeros(Y{1}.matdim.dim(1:2)); for n1=1:size(Bb,1), t(idx)=Bb(n1,:); V(n1)=spm_write_plane(V(n1),t,slice); end end conn_waitbar((n+slice/Y{1}.matdim.dim(3))/N,h); end if 0,%%% 0 to avoid memory errors t=nan+zeros(Y{1}.matdim.dim); %V=spm_vol(deblank(CONN_x.Setup.functional{nsub}{1}{1}(1,:))); V=V(1); %V=spm_vol(deblank(CONN_x.Setup.structural{nsub}{1})); V=V(1); V=CONN_x.Setup.structural{nsub}{3}; V=V(1); if isfield(V,'dt'), V.dt=[spm_type('float32') spm_platform('bigend')]; elseif length(V.dim)>3, V.dim(4)=spm_type('float32'); end for n1=1:size(B,1), t(Y{1}.voxels)=B(n1,:); V.fname=fullfile(filepathresults,['BETA_Subject',num2str(nsub),'_Regressor',num2str(n1,'%04d'),'.nii']); spm_write_vol(V,t); end end end n=n+1; conn_waitbar(n/N,h); end conn_waitbar('close',h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates ROI_Subject###_Condition###.mat files (roi data after removal of confounding effects & filtering) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==7), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.data; filepathresults=CONN_x.folders.preprocessing; nconditions=length(CONN_x.Setup.conditions.names)-1; h=conn_waitbar(0,['Step ',num2str(sum(options<=7)),'/',num2str(length(options)),': Preprocessing ROI data']); REDO='Yes';filename=fullfile(filepathresults,['ROI_Subject',num2str(1,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); %if ~isempty(dir(filename)),if isfield(CONN_x,'gui')&&isstruct(CONN_x.gui)&&isfield(CONN_x.gui,'overwrite'), REDO=CONN_x.gui.overwrite; else, REDO=questdlg('Overwrite existing subject results?','','Yes', 'No', 'Yes');end; end N=CONN_x.Setup.nsubjects; %sum(CONN_x.Setup.nsessions); if length(CONN_x.Setup.nsessions)==1, N=N*CONN_x.Setup.nsubjects; end n=0; for nsub=1:CONN_x.Setup.nsubjects, filename=fullfile(filepathresults,['ROI_Subject',num2str(nsub,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); if 1,%strcmp(REDO,'Yes')||isempty(dir(filename)), nsess=CONN_x.Setup.nsessions(min(length(CONN_x.Setup.nsessions),nsub)); clear Y X iX X1 X2 C; for nses=1:nsess, % loads all ROI COV COND data for this subject filename=fullfile(filepath,['ROI_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); if isempty(dir(filename)), disp(['Not ready to process step conn_process_7']); conn_waitbar('close',h); return; end X1{nses}=load(filename); filename=fullfile(filepath,['COV_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); X2{nses}=load(filename); filename=fullfile(filepath,['COND_Subject',num2str(nsub,'%03d'),'_Session',num2str(nses,'%03d'),'.mat']); C{nses}=load(filename); X{nses}=conn_designmatrix(CONN_x.Preproc.confounds,X1{nses},X2{nses}); %X{nses}=conn_filter(CONN_x.Setup.RT,CONN_x.Preproc.filter,X{nses}); if size(X{nses},1)~=CONN_x.Setup.nscans{nsub}{nses}, error('Wrong dimensions'); end iX{nses}=pinv(X{nses}); end clear nsamples time0 dataroi conditionweights; for ncondition=1:nconditions, % computes number of samples per condition nsamples{ncondition}=0; for nses=1:nsess, nsamples{ncondition}=nsamples{ncondition}+length(C{nses}.samples{ncondition}); end dataroi{ncondition}=cell(1,length(X1{1}.data)); conditionsweights{ncondition}=cell(1,length(C{1}.weights{ncondition})); for nses=1:nsess, for nweight=1:length(C{nses}.weights{ncondition}), conditionsweights{ncondition}{nweight}=cat(1,conditionsweights{ncondition}{nweight},C{nses}.weights{ncondition}{nweight}); end end end for nroi=1:length(X1{1}.data), for nses=1:nsess, y=X1{nses}.data{nroi}; if size(y,1)~=CONN_x.Setup.nscans{nsub}{nses}, error('Wrong dimensions'); end b=iX{nses}*y; y=y-X{nses}*b; y=conn_filter(CONN_x.Setup.RT,CONN_x.Preproc.filter,y); for ncondition=1:nconditions, dataroi{ncondition}{nroi}=cat(1,dataroi{ncondition}{nroi},y(C{nses}.samples{ncondition},:)); end end end for ncondition=1:nconditions, data=dataroi{ncondition}; names=X1{1}.names; xyz=X1{1}.xyz; %voxels=X1{1}.voxels; %weights=X1{1}.weights; source=X1{1}.source; conditionname=C{1}.names{ncondition}; conditionweights=conditionsweights{ncondition}; filename=fullfile(filepathresults,['ROI_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); if str2num(version('-release'))>=14, save(filename,'-V6','data','names','xyz','source','conditionweights','conditionname'); else, save(filename,'data','names','xyz','source','conditionweights','conditionname');end end end n=n+1; conn_waitbar(n/N,h); end conn_waitbar('close',h); ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates SVD_Subject###_Condition###.mat files (voxel-to-voxel SVD decomposition) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==7.5), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.preprocessing; nconditions=length(CONN_x.Setup.conditions.names)-1; h=conn_waitbar(0,['Step ',num2str(sum(options<=7.5)),'/',num2str(length(options)),': preprocessing voxel-to-voxel covariance']); REDO=[]; filename=fullfile(fileparts(which('spm')),'apriori','grey.nii'); Vmask=spm_vol(filename); filename=fullfile(filepath,['DATA_Subject',num2str(1,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); if isempty(dir(filename)), disp(['Not ready to process step conn_process_7.5']); return; end Y=conn_vol(filename); N=1.1*CONN_x.Setup.nsubjects*nconditions*Y.matdim.dim(3);n=0; for ncondition=1:nconditions, for nsub=1:CONN_x.Setup.nsubjects, filename=fullfile(filepath,['SVD_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); if isempty(REDO)&&~isempty(dir(filename)), if isfield(CONN_x,'gui')&&isstruct(CONN_x.gui)&&isfield(CONN_x.gui,'overwrite'), REDO=CONN_x.gui.overwrite; else, REDO=questdlg('Overwrite existing subject results?','','Yes', 'No', 'Yes');end; end if strcmp(REDO,'Yes')||(isempty(dir(filename))), filename=fullfile(filepath,['DATA_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); if isempty(dir(filename)), disp(['Not ready to process step conn_process_7.5']); return; end Y=conn_vol(filename); filename=fullfile(filepath,['ROI_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); X1=load(filename); DOF=max(0,Y.size.Nt*(min(1/(2*CONN_x.Setup.RT),CONN_x.Preproc.filter(2))-max(0,CONN_x.Preproc.filter(1)))/(1/(2*CONN_x.Setup.RT))-1); Cy=0;Cidx=[]; for slice=1:Y.matdim.dim(3), [y,idx]=conn_get_slice(Y,slice); [xyzx,xyzy]=ind2sub(Y.matdim.dim(1:2),idx);xyz=Y.matdim.mat*[xyzx,xyzy,zeros(size(xyzx))+slice,ones(size(xyzx))]'; z=spm_get_data(Vmask,pinv(Vmask(1).mat)*xyz); idxt=find(z>.30); if ~isempty(idxt), Cidx=cat(1,Cidx,idx(idxt)+(slice-1)*Y.matdim.dim(1)*Y.matdim.dim(2)); y=y(:,idxt); y=detrend(y.*repmat(X1.conditionweights{1},[1,size(y,2)]),'constant'); Cy=Cy+y*y'; end n=n+.1; conn_waitbar(n/N,h); end [Q1,D]=svd(Cy); D=diag(D); DIMS=min([128,ceil(DOF),sum(D>1e-4)]); Q1=Q1(:,1:DIMS); D=D(1:DIMS); filename=fullfile(filepath,['SVD_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); Yout=Y; Yout.fname=filename; Yout.size.Nt=DIMS+1; Yout.DOF=DOF; Yout.BASE.Q1=Q1; Yout.BASE.D=D; Yout=conn_init_vol(Yout,Cidx); for slice=1:Y.matdim.dim(3), [y,idx]=conn_get_slice(Y,slice); [xyzx,xyzy]=ind2sub(Y.matdim.dim(1:2),idx);xyz=Y.matdim.mat*[xyzx,xyzy,zeros(size(xyzx))+slice,ones(size(xyzx))]'; z=spm_get_data(Vmask,pinv(Vmask(1).mat)*xyz); idxt=find(z>.30); if ~isempty(idxt), y=y(:,idxt); y=detrend(y.*repmat(X1.conditionweights{1},[1,size(y,2)]),'constant'); Q2=Q1'*y; e=sum(abs(y).^2,1); for ndim=1:DIMS, conn_write_slice(Yout,Q2(ndim,:),slice,ndim-1); end conn_write_slice(Yout,e,slice,DIMS); end n=n+1; conn_waitbar(n/N,h); end else, n=n+1.1*Y.matdim.dim(3); end end end conn_waitbar('close',h); ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % updates CONN_x.Analyses structure with all ROIs %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==8), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.data; filename1=fullfile(filepath,['ROI_Subject',num2str(1,'%03d'),'_Session',num2str(1,'%03d'),'.mat']); if isempty(dir(filename1)), disp(['Not ready to process step conn_process_8']); return; end x1=load(filename1); if nargin>1,analyses=varargin{1}; % selected analysis only else, analyses=1:length(CONN_x.Analyses); end; analysisbak=CONN_x.Analysis; for ianalysis=analyses, CONN_x.Analysis=ianalysis; if isempty(CONN_x.Analyses(ianalysis).name),CONN_x.Analyses(ianalysis).name=['ANALYSIS_',num2str(ianalysis,'%02d')]; end; if ~exist(fullfile(CONN_x.folders.firstlevel,CONN_x.Analyses(ianalysis).name),'dir'), [ok,nill]=mkdir(CONN_x.folders.firstlevel,CONN_x.Analyses(ianalysis).name); end; CONN_x.Analyses(ianalysis).variables.names={}; CONN_x.Analyses(ianalysis).variables.types={}; CONN_x.Analyses(ianalysis).variables.deriv={}; CONN_x.Analyses(ianalysis).variables.dimensions={}; for n1=1:length(x1.names), idx=strmatch(x1.names{n1},CONN_x.Preproc.confounds.names,'exact'); if isempty(idx), CONN_x.Analyses(ianalysis).variables.names{end+1}=x1.names{n1}; CONN_x.Analyses(ianalysis).variables.types{end+1}='roi'; CONN_x.Analyses(ianalysis).variables.deriv{end+1}=0; CONN_x.Analyses(ianalysis).variables.dimensions{end+1}=[size(x1.data{n1},2),size(x1.data{n1},2)]; end end if isfield(CONN_x.Analyses(ianalysis).regressors,'names') && ~isempty(CONN_x.Analyses(ianalysis).regressors.names), initial=CONN_x.Analyses(ianalysis).regressors.names; dims=CONN_x.Analyses(ianalysis).regressors.dimensions; ders=CONN_x.Analyses(ianalysis).regressors.deriv; else, initial=CONN_x.Analyses(ianalysis).variables.names; dims={}; ders={}; end CONN_x.Analyses(ianalysis).regressors.names={}; CONN_x.Analyses(ianalysis).regressors.types={}; CONN_x.Analyses(ianalysis).regressors.deriv={}; CONN_x.Analyses(ianalysis).regressors.dimensions={}; for n1=1:length(initial), idx=strmatch(initial{n1},CONN_x.Analyses(ianalysis).variables.names,'exact'); if ~isempty(idx)&&~strcmp(initial{n1},'Grey Matter')&&~strcmp(initial{n1},'White Matter')&&~strcmp(initial{n1},'CSF'), CONN_x.Analyses(ianalysis).regressors.names{end+1}=CONN_x.Analyses(ianalysis).variables.names{idx}; CONN_x.Analyses(ianalysis).regressors.types{end+1}=CONN_x.Analyses(ianalysis).variables.types{idx}; if length(ders)>=n1&&~isempty(ders{n1}), CONN_x.Analyses(ianalysis).regressors.deriv{end+1}=ders{n1}; else, CONN_x.Analyses(ianalysis).regressors.deriv{end+1}=CONN_x.Analyses(ianalysis).variables.deriv{idx};end if length(dims)>=n1&&~isempty(dims{n1}), CONN_x.Analyses(ianalysis).regressors.dimensions{end+1}=[min(dims{n1}(1),CONN_x.Analyses(ianalysis).variables.dimensions{idx}(1)),CONN_x.Analyses(ianalysis).variables.dimensions{idx}(1)]; else, CONN_x.Analyses(ianalysis).regressors.dimensions{end+1}=CONN_x.Analyses(ianalysis).variables.dimensions{idx}; end end end if ~isfield(CONN_x.Analyses(ianalysis),'measure') || isempty(CONN_x.Analyses(ianalysis).measure), CONN_x.Analyses(ianalysis).measure=1; end if ~isfield(CONN_x.Analyses(ianalysis),'weight') || isempty(CONN_x.Analyses(ianalysis).weight), CONN_x.Analyses(ianalysis).weight=2; end end CONN_x.Analysis=analysisbak; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates resultsDATA_Subject###_Condition###.mat files (first-level voxel-to-voxel analysis) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==8.5), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.preprocessing; nconditions=length(CONN_x.Setup.conditions.names)-1; h=conn_waitbar(0,['Step ',num2str(sum(options<=8.5)),'/',num2str(length(options)),': voxel-to-voxel first-level analyses']); % workinprogress end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates resultsDATA_Subject###_Condition###_Source###.mat files (first-level ROI-to-voxel analysis) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==9), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.preprocessing; nconditions=length(CONN_x.Setup.conditions.names)-1; filename=fullfile(filepath,['ROI_Subject',num2str(1,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); if isempty(dir(filename)), disp(['Not ready to process step conn_process_9']); return; end X1=load(filename); if nargin>1,analyses=varargin{1}; % selected analysis only else, analyses=1:length(CONN_x.Analyses); end; h=conn_waitbar(0,['Step ',num2str(sum(options<=9)),'/',num2str(length(options)),': ROI-to-voxel first-level analyses']); REDO=[]; analysisbak=CONN_x.Analysis; for nanalyses=1:length(analyses), ianalysis=analyses(nanalyses); CONN_x.Analysis=ianalysis; % ianalysis=CONN_x.Analysis; filepathresults=fullfile(CONN_x.folders.firstlevel,CONN_x.Analyses(ianalysis).name); [X,nill,names]=conn_designmatrix(CONN_x.Analyses(ianalysis).regressors,X1,[]); nrois=size(X,2)-1; iroi=[];isnew=[];for nroi=1:nrois,[iroi(nroi),isnew(nroi)]=conn_sourcenames(names{nroi},'+');end filename=fullfile(filepath,['DATA_Subject',num2str(1,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); Y=conn_vol(filename); if nanalyses==1, N=CONN_x.Setup.nsubjects*nconditions*Y.matdim.dim(3)*length(analyses);n=0;end for ncondition=1:nconditions, for nsub=1:CONN_x.Setup.nsubjects, filename=fullfile(filepath,['DATA_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); Y=conn_vol(filename); filename=fullfile(filepath,['ROI_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); X1=load(filename); [X,nill,names]=conn_designmatrix(CONN_x.Analyses(ianalysis).regressors,X1,[]); clear Yout; for nroi=1:nrois, filename=fullfile(filepathresults,['resultsDATA_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'_Source',num2str(iroi(nroi),'%03d'),'.mat']); isnew(nroi)=isnew(nroi)|isempty(dir(filename)); end if any(isnew), switch(CONN_x.Analyses(ianalysis).measure), case {2,4}, %partial isnew=ones(size(isnew)); end end if isempty(REDO)&&~all(isnew), if isfield(CONN_x,'gui')&&isstruct(CONN_x.gui)&&isfield(CONN_x.gui,'overwrite'), REDO=CONN_x.gui.overwrite; else, REDO=questdlg('Overwrite existing subject results?','','Yes', 'No', 'Yes');end; end if strcmp(REDO,'No'), idxredo=find(isnew); X=cat(2,X(:,1),X(:,1+idxredo)); else, idxredo=1:nrois; end if length(idxredo)>0, switch(CONN_x.Analyses(ianalysis).weight), case 1, case 2, X=X.*repmat(X1.conditionweights{1},[1,size(X,2)]); case 3, X=X.*repmat(X1.conditionweights{2},[1,size(X,2)]); end switch(CONN_x.Analyses(ianalysis).measure), case {1,3}, %bivariate X=cat(2,X(:,1),detrend(X(:,2:end),'constant')); iX=pinv(diag(diag(X'*X))); DOF=max(0,Y.size.Nt*(min(1/(2*CONN_x.Setup.RT),CONN_x.Preproc.filter(2))-max(0,CONN_x.Preproc.filter(1)))/(1/(2*CONN_x.Setup.RT))-1); case {2,4}, %partial iX=pinv(X'*X); DOF=max(0,Y.size.Nt*(min(1/(2*CONN_x.Setup.RT),CONN_x.Preproc.filter(2))-max(0,CONN_x.Preproc.filter(1)))/(1/(2*CONN_x.Setup.RT))-rank(X)+1); end filename=fullfile(filepathresults,['seDATA_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); SEout=Y; SEout.fname=filename; SEout.size.Nt=1;%CONN_x.Setup.nsubjects; SEout.DOF=DOF; SEout=conn_init_vol(SEout); for nroi=1:length(idxredo), filename=fullfile(filepathresults,['resultsDATA_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'_Source',num2str(iroi(idxredo(nroi)),'%03d'),'.mat']); Yout{nroi}=Y; Yout{nroi}.fname=filename; Yout{nroi}.size.Nt=1;%CONN_x.Setup.nsubjects; Yout{nroi}=conn_init_vol(Yout{nroi}); end for slice=1:Y.matdim.dim(3), [y,idx]=conn_get_slice(Y,slice); switch(CONN_x.Analyses(ianalysis).weight), case 1, case 2, y=y.*repmat(X1.conditionweights{1},[1,size(y,2)]); case 3, y=y.*repmat(X1.conditionweights{2},[1,size(y,2)]); end B=iX*(X'*y); e=sqrt(sum(abs(detrend(y,'constant')).^2,1)); switch(CONN_x.Analyses(ianalysis).measure), case {1,2}, %correlation r=sqrt(diag(iX)); B=B./max(eps,r*e); B=atanh(max(eps-1,min(1-eps,B))); e(:)=1./max(eps,sqrt(DOF-3)); case {3,4}, %regression e=e/max(eps,DOF); end %disp([slice,nsub]) conn_write_slice(SEout,e,slice,0);%nsub-1); for nroi=1:length(idxredo); conn_write_slice(Yout{nroi},B(1+nroi,:),slice,0);%nsub-1); end n=n+1; conn_waitbar(n/N,h); end else, n=n+Y.matdim.dim(3); end end end end CONN_x.Analysis=analysisbak; conn_waitbar('close',h); ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates resultsROI_Subject###_Condition###.mat files (first-level ROI-to-ROI analyses) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==10), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.preprocessing; if nargin>1,analyses=varargin{1}; % selected analysis only else, analyses=1:length(CONN_x.Analyses); end; h=conn_waitbar(0,['Step ',num2str(sum(options<=10)),'/',num2str(length(options)),': ROI-to-ROI first-level analyses']); analysisbak=CONN_x.Analysis; for nanalyses=1:length(analyses), ianalysis=analyses(nanalyses); CONN_x.Analysis=ianalysis; % ianalysis=CONN_x.Analysis; filepathresults=fullfile(CONN_x.folders.firstlevel,CONN_x.Analyses(ianalysis).name); nconditions=length(CONN_x.Setup.conditions.names)-1; %REDO='Yes';filename=fullfile(filepathresults,['resultsROI_Subject',num2str(1,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); %if ~isempty(dir(filename)),if isfield(CONN_x,'gui')&&isstruct(CONN_x.gui)&&isfield(CONN_x.gui,'overwrite'), REDO=CONN_x.gui.overwrite; else, REDO=questdlg('Overwrite existing subject results?','','Yes', 'No', 'Yes');end; end if nanalyses==1, n=0; end for ncondition=1:nconditions, for nsub=1:CONN_x.Setup.nsubjects, filename=fullfile(filepathresults,['resultsROI_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); if 1,%strcmp(REDO,'Yes')||isempty(dir(filename)), filename=fullfile(filepath,['ROI_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); if isempty(dir(filename)), disp(['Not ready to process step conn_process_10']); conn_waitbar('close',h);return; end X1=load(filename); [X,nill,names]=conn_designmatrix(CONN_x.Analyses(ianalysis).regressors,X1,[]); nrois=size(X,2)-1; [X2,nill,names2]=conn_designmatrix(CONN_x.Analyses(ianalysis).variables,X1,[]); nrois2=size(X2,2)-1; idxroi1roi2=zeros(1,nrois); for n1=1:nrois,idxroi1roi2(n1)=strmatch(names{n1},names2,'exact');end X2=cat(2,X2(:,1),X2(:,1+idxroi1roi2),X2(:,1+setdiff(1:nrois2,idxroi1roi2))); names2=cat(2,{names2{idxroi1roi2}},{names2{setdiff(1:nrois2,idxroi1roi2)}}); if nanalyses==1&&nsub==1 && ncondition==1,N=CONN_x.Setup.nsubjects*nconditions*nrois2*length(analyses);end Z=zeros(nrois,nrois2);%+diag(nan+zeros(nrois,1)); SE=zeros(1,nrois2); switch(CONN_x.Analyses(ianalysis).weight), case 1, case 2, X=X.*repmat(X1.conditionweights{1},[1,size(X,2)]);X2=X2.*repmat(X1.conditionweights{1},[1,size(X2,2)]); case 3, X=X.*repmat(X1.conditionweights{2},[1,size(X,2)]);X2=X2.*repmat(X1.conditionweights{1},[1,size(X2,2)]); end switch(CONN_x.Analyses(ianalysis).measure), case {1,3}, %bivariate DOF=max(0,size(X,1)*(min(1/(2*CONN_x.Setup.RT),CONN_x.Preproc.filter(2))-max(0,CONN_x.Preproc.filter(1)))/(1/(2*CONN_x.Setup.RT))-1); case {2,4}, %partial DOF=max(0,size(X,1)*(min(1/(2*CONN_x.Setup.RT),CONN_x.Preproc.filter(2))-max(0,CONN_x.Preproc.filter(1)))/(1/(2*CONN_x.Setup.RT))-rank(X)+1); end for nroi=1:nrois2, y=X2(:,1+nroi); switch(CONN_x.Analyses(ianalysis).measure), case {1,3}, %bivariate x=cat(2,X(:,1),detrend(X(:,1+setdiff(1:nrois,nroi)),'constant')); iX=pinv(diag(diag(x'*x))); case {2,4}, %partial x=cat(2,X(:,1),X(:,1+setdiff(1:nrois,nroi))); iX=pinv(x'*x); end B=iX*(x'*y); e=sqrt(sum(abs(detrend(y,'constant')).^2,1)); switch(CONN_x.Analyses(ianalysis).measure), case {1,2}, %correlation r=sqrt(diag(iX)); B=B./max(eps,r*e); B(~isnan(B))=atanh(max(eps-1,min(1-eps,B(~isnan(B))))); SE(nroi)=1./max(eps,sqrt(DOF-3)); case {3,4}, SE(nroi)=e/max(eps,DOF); end Z(setdiff(1:nrois,nroi),nroi)=B(2:end); if nroi<=nrois,Z(nroi,nroi)=nan;end n=n+1; conn_waitbar(n/N,h); end % xyz={}; %note: this assumes constant number of dimensions per subject for analysis regressors % for n1=1:length(CONN_x.Analyses(ianalysis).regressors.names), % for n2=1:CONN_x.Analyses(ianalysis).regressors.deriv{n1}+1, % for n3=1:CONN_x.Analyses(ianalysis).regressors.dimensions{n1}(1), % idx=strmatch(CONN_x.Analyses(ianalysis).regressors.names{n1},X1.names,'exact'); % if isempty(idx), xyz{end+1}=''; else, xyz{end+1}=X1.xyz{idx}; end % end % end; % end xyz={}; %note: this assumes constant number of dimensions per subject for analysis regressors for n1=1:length(CONN_x.Analyses(ianalysis).variables.names), for n2=1:CONN_x.Analyses(ianalysis).variables.deriv{n1}+1, for n3=1:CONN_x.Analyses(ianalysis).variables.dimensions{n1}(1), idx=strmatch(CONN_x.Analyses(ianalysis).variables.names{n1},X1.names,'exact'); if isempty(idx), xyz{end+1}=''; else, xyz{end+1}=X1.xyz{idx}; end end end; end xyz=cat(2,{xyz{idxroi1roi2}},{xyz{setdiff(1:nrois2,idxroi1roi2)}}); regressors=CONN_x.Analyses(ianalysis).regressors; filename=fullfile(filepathresults,['resultsROI_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); save(filename,'Z','regressors','names','names2','xyz','SE','DOF'); end end end end CONN_x.Analysis=analysisbak; conn_waitbar('close',h); ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates BETA_Subject###_Condition###_Source###.mat files (first-level analysis results for SPM) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==11), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.preprocessing; if nargin>1,analyses=varargin{1}; % selected analysis only else, analyses=1:length(CONN_x.Analyses); end; h=conn_waitbar(0,['Step ',num2str(sum(options<=11)),'/',num2str(length(options)),': Creating BETA volumes']); analysisbak=CONN_x.Analysis; for nanalyses=1:length(analyses), ianalysis=analyses(nanalyses); CONN_x.Analysis=ianalysis; % ianalysis=CONN_x.Analysis; filepathresults=fullfile(CONN_x.folders.firstlevel,CONN_x.Analyses(ianalysis).name); nconditions=length(CONN_x.Setup.conditions.names)-1; %nrois=0;for n1=1:length(CONN_x.Analyses.regressors.names), nrois=nrois+CONN_x.Analyses.regressors.dimensions{n1}(1)*(CONN_x.Analyses.regressors.deriv{n1}+1); end; filename=fullfile(filepath,['ROI_Subject',num2str(1,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); if isempty(dir(filename)), disp(['Not ready to process step conn_process_11']); conn_waitbar('close',h);return; end X1=load(filename); [X,nill,names]=conn_designmatrix(CONN_x.Analyses(ianalysis).regressors,X1,[]); nrois=size(X,2)-1; iroi=[];isnew=[];for nroi=1:nrois,[iroi(nroi),isnew(nroi)]=conn_sourcenames(names{nroi},'-');end if any(isnew), error(['Non-existing ROI first-level data for ',names{find(isnew)},' subject ',num2str(nsub),'. Please repeat first-level analyses']); return; end if nanalyses==1, REDO=[]; n=0; N=CONN_x.Setup.nsubjects*nconditions*nrois*length(analyses); end clear Yout; for ncondition=1:nconditions, for nroi=1:nrois, for nsub=1:CONN_x.Setup.nsubjects, filename=fullfile(filepathresults,['BETA_Subject',num2str(nsub),'_Condition',num2str(ncondition,'%03d'),'_Source',num2str(iroi(nroi),'%03d'),'.nii']); if isempty(REDO)&&~(isnew(nroi)||isempty(dir(filename))), if isfield(CONN_x,'gui')&&isstruct(CONN_x.gui)&&isfield(CONN_x.gui,'overwrite'), REDO=CONN_x.gui.overwrite; else, REDO=questdlg('Overwrite existing subject results?','','Yes', 'No', 'Yes');end; end if strcmp(REDO,'Yes')||(isnew(nroi)||isempty(dir(filename))), filename=fullfile(filepathresults,['resultsDATA_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'_Source',num2str(iroi(nroi),'%03d'),'.mat']); Yout=conn_vol(filename); t=nan+zeros(Yout.matdim.dim); y=conn_get_time(Yout,1);%nsub); %V0=spm_vol(deblank(CONN_x.Setup.functional{nsub}{1}{1}(1,:))); V0=V0(1); %V=spm_vol(deblank(CONN_x.Setup.structural{nsub}{1})); V=V(1); V=CONN_x.Setup.structural{nsub}{3}; V=V(1); t(Yout.voxels)=y; V.fname=fullfile(filepathresults,['BETA_Subject',num2str(nsub),'_Condition',num2str(ncondition,'%03d'),'_Source',num2str(iroi(nroi),'%03d'),'.nii']); if isfield(V,'dt'), V.dt=[spm_type('float32') spm_platform('bigend')]; elseif length(V.dim)>3, V.dim(4)=spm_type('float32'); end spm_write_vol(V,t); if ~isfield(CONN_x.Setup,'docorr')||CONN_x.Setup.docorr, V.fname=fullfile(filepathresults,['corr_Subject',num2str(nsub),'_Condition',num2str(ncondition,'%03d'),'_Source',num2str(iroi(nroi),'%03d'),'.nii']); t=tanh(t); spm_write_vol(V,t); end end n=n+1; conn_waitbar(n/N,h); end end end fileout=fullfile(filepathresults,'_list_sources.txt'); fh=fopen(fileout,'wt'); for n1=1:length(CONN_x.Analyses(ianalysis).sourcenames),fprintf(fh,'Source%03d = %s\n',n1,CONN_x.Analyses(ianalysis).sourcenames{n1});end fclose(fh); fileout=fullfile(filepathresults,'_list_conditions.txt'); fh=fopen(fileout,'wt'); for n1=1:nconditions,fprintf(fh,'Condition%03d = %s\n',n1,CONN_x.Setup.conditions.names{n1});end fclose(fh); end CONN_x.Analysis=analysisbak; conn_waitbar('close',h); ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates resultsDATA_Condition###_Source###.mat files (combined first-level analyses) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==12), if ~isfield(CONN_x.Setup,'normalized'), CONN_x.Setup.normalized=1; end if ~CONN_x.Setup.normalized, disp(['Not spatially-normalized data. Skipping ROI-to-voxel second-level analyses']); else, [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.preprocessing; if nargin>1,analyses=varargin{1}; % selected analysis only else, analyses=1:length(CONN_x.Analyses); end; h=conn_waitbar(0,['Step ',num2str(sum(options<=12)),'/',num2str(length(options)),': Preparing second-level analyses']); analysisbak=CONN_x.Analysis; for nanalyses=1:length(analyses), ianalysis=analyses(nanalyses); CONN_x.Analysis=ianalysis; % ianalysis=CONN_x.Analysis; filepathresults=fullfile(CONN_x.folders.firstlevel,CONN_x.Analyses(ianalysis).name); nconditions=length(CONN_x.Setup.conditions.names)-1; filename=fullfile(filepath,['ROI_Subject',num2str(1,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); if isempty(dir(filename)), disp(['Not ready to process step conn_process_12']); conn_waitbar('close',h);return; end X1=load(filename); [X,nill,names]=conn_designmatrix(CONN_x.Analyses(ianalysis).regressors,X1,[]); nrois=size(X,2)-1; iroi=[];isnew=[];for nroi=1:nrois,[iroi(nroi),isnew(nroi)]=conn_sourcenames(names{nroi},'-');end if any(isnew), error(['Non-existing ROI first-level data for ',names{find(isnew)},'. Please repeat first-level analyses']); return; end if nanalyses==1, N=nconditions*nrois*length(analyses);n=0;end for ncondition=1:nconditions, for nroi=1:nrois, clear Yin Yout; for nsub=1:CONN_x.Setup.nsubjects, filename=fullfile(filepathresults,['resultsDATA_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'_Source',num2str(iroi(nroi),'%03d'),'.mat']); Yin(nsub)=conn_vol(filename); end filename=fullfile(filepathresults,['resultsDATA_Condition',num2str(ncondition,'%03d'),'_Source',num2str(iroi(nroi),'%03d'),'.mat']); Yout=Yin(1); Yout.fname=filename; Yout.size.Nt=CONN_x.Setup.nsubjects; Yout=conn_init_vol(Yout); conn_write_combine(Yin,Yout); n=n+1; conn_waitbar(n/N,h); end clear Yin Yout; for nsub=1:CONN_x.Setup.nsubjects, filename=fullfile(filepathresults,['seDATA_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); Yin(nsub)=conn_vol(filename); end filename=fullfile(filepathresults,['seDATA_Condition',num2str(ncondition,'%03d'),'.mat']); Yout=Yin(1); Yout.fname=filename; Yout.size.Nt=CONN_x.Setup.nsubjects; Yout.DOF=cat(2,Yin(:).DOF); Yout=conn_init_vol(Yout); conn_write_combine(Yin,Yout); end CONN_x.Analyses(ianalysis).sources=names; end CONN_x.Analysis=analysisbak; conn_waitbar('close',h); %CONN_x.Results.measure=CONN_x.Analyses(ianalysis).measure; end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates resultsROI_Condition###.mat files (combined first-level analyses) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==13), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.preprocessing; if nargin>1,analyses=varargin{1}; % selected analysis only else, analyses=1:length(CONN_x.Analyses); end; h=conn_waitbar(0,['Step ',num2str(sum(options<=13)),'/',num2str(length(options)),': Preparing second-level ROI analyses']); analysisbak=CONN_x.Analysis; for nanalyses=1:length(analyses), ianalysis=analyses(nanalyses); CONN_x.Analysis=ianalysis; % ianalysis=CONN_x.Analysis; filepathresults=fullfile(CONN_x.folders.firstlevel,CONN_x.Analyses(ianalysis).name); nconditions=length(CONN_x.Setup.conditions.names)-1; filename=fullfile(filepath,['ROI_Subject',num2str(1,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); if isempty(dir(filename)), disp(['Not ready to process step conn_process_13']); conn_waitbar('close',h);return; end X1=load(filename); [X,nill,names]=conn_designmatrix(CONN_x.Analyses(ianalysis).regressors,X1,[]); nrois=size(X,2)-1; [X2,nill,names2]=conn_designmatrix(CONN_x.Analyses(ianalysis).variables,X1,[]); nrois2=size(X2,2)-1; idxroi1roi2=zeros(1,nrois); for n1=1:nrois,idxroi1roi2(n1)=strmatch(names{n1},names2,'exact');end X2=cat(2,X2(:,1),X2(:,1+idxroi1roi2),X2(:,1+setdiff(1:nrois2,idxroi1roi2))); names2=cat(2,{names2{idxroi1roi2}},{names2{setdiff(1:nrois2,idxroi1roi2)}}); if nanalyses==1, n=0;N=CONN_x.Setup.nsubjects*nconditions*nrois*length(analyses); end for ncondition=1:nconditions, Z=zeros([nrois,nrois2,CONN_x.Setup.nsubjects]); xyz={}; SE=zeros([CONN_x.Setup.nsubjects,nrois2]); DOF=zeros([1,CONN_x.Setup.nsubjects]); for nsub=1:CONN_x.Setup.nsubjects, filename=fullfile(filepathresults,['resultsROI_Subject',num2str(nsub,'%03d'),'_Condition',num2str(ncondition,'%03d'),'.mat']); t=load(filename,'Z','regressors','names','names2','xyz','SE','DOF'); IDX=[];IDX2=[]; for nroi=1:nrois, idx=strmatch(names{nroi},t.names,'exact'); if isempty(idx), error(['Non-existing ROI first-level data for ',names{nroi},' subject ',num2str(nsub),'. Please repeat first-level analyses']); return; end IDX(nroi)=idx(1); n=n+1; conn_waitbar(n/N,h); end for nroi=1:nrois2, idx=strmatch(names2{nroi},t.names2,'exact'); if isempty(idx), error(['Non-existing ROI first-level data for ',names2{nroi},' subject ',num2str(nsub),'. Please repeat first-level analyses']); return; end IDX2(nroi)=idx(1); end Z(:,:,nsub)=t.Z(IDX,IDX2); xyz={t.xyz{IDX2}}; SE(nsub,:)=t.SE(IDX2); DOF(nsub)=t.DOF; end regressors=CONN_x.Analyses(ianalysis).regressors; filename=fullfile(filepathresults,['resultsROI_Condition',num2str(ncondition,'%03d'),'.mat']); save(filename,'Z','regressors','names','names2','xyz','SE','DOF'); end CONN_x.Analyses(ianalysis).sources=names; end CONN_x.Analysis=analysisbak; conn_waitbar('close',h); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates nDATA_Condition###_Source###.mat files (normalized first-level analysis results) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if 0,%any(options==8.5), [path,name,ext]=fileparts(CONN_x.filename); filepath=CONN_x.folders.preprocessing; nconditions=length(CONN_x.Setup.conditions.names)-1; nrois=0;for n1=1:length(CONN_x.Analyses.regressors.names), nrois=nrois+CONN_x.Analyses.regressors.dimensions{n1}(1)*(CONN_x.Analyses.regressors.deriv{n1}+1); end; h=conn_waitbar(0,['Step ',num2str(sum(options<=8)),'/',num2str(length(options)),': Processing functional data']); fileref=fullfile(fileparts(which('spm')),'canonical','avg152T1.nii'); V0=spm_vol(fileref); clear sfile; for nsub=1:CONN_x.Setup.nsubjects, [fpath,ffile,fext]=fileparts(deblank(CONN_x.Setup.structural{nsub}{1})); sfile{nsub}=fullfile(fpath,[ffile,'_seg_inv_sn.mat']); end N=nconditions*nrois; n=0; for ncondition=1:nconditions, for nroi=1:nrois, filename=fullfile(filepath,['DATA_Condition',num2str(ncondition,'%03d'),'_Source',num2str(nroi,'%03d'),'.mat']); fileout=fullfile(filepath,['nDATA_Condition',num2str(ncondition,'%03d'),'_Source',num2str(nroi,'%03d'),'.mat']); Y0=conn_vol(filename); conn_reslice(fileout,V0(1).mat,V0(1).dim,Y0,sfile,0*CONN_x.Setup.fwhm); n=n+1; conn_waitbar(n/N,h); end end conn_waitbar('close',h); ; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates second-level SPM.mat results (second-level analysis results for SPM) % CON_Subject### (source files for second-leve analyses) % CON_Subject###_Source###.nii (source files for source-specific second-level analyses) % between-subject contrasts of interest: % T-contrast: "connectivity results": as specified in "between subject contrast" % T-contrast: one per effect specified in "subject effects" (named as the corresponding second-level covariates) % F-contrast: "effects of interest": F- test for all effects in second-levle model %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==14), filepathresults1=fullfile(CONN_x.folders.firstlevel,CONN_x.Analyses(CONN_x.Analysis).name); filepathresults2=CONN_x.folders.secondlevel; if nargin>1, switch(lower(varargin{1})), case 'dosingle',dosinglecontrast=1; % performs one specific analysis case 'doall',dosinglecontrast=0; % one analysis per source case 'readsingle', dosinglecontrast=2; % performs one speficic analysis (if it does not exist already) otherwise, dosinglecontrast=0; end; else, dosinglecontrast=0; end if ~isfield(CONN_x,'Results'), disp(['Not ready to process step conn_process_14']); return; end nsources=CONN_x.Results.xX.nsources; csources=CONN_x.Results.xX.csources; nconditions=CONN_x.Results.xX.nconditions; cconditions=CONN_x.Results.xX.cconditions; sources=CONN_x.Analyses(CONN_x.Analysis).sources; if ~isfield(CONN_x.Results.xX,'modeltype')||isempty(CONN_x.Results.xX.modeltype), CONN_x.Results.xX.modeltype=1; end modeltype=CONN_x.Results.xX.modeltype; % if nargin>1&&varargin{1}>1, nsources=varargin{2}; csources=ones(1,length(nsources)); sources={sources{nsources}}; nsources=1:length(nsources); end % if nargin>1, dosinglecontrast=(varargin{1}==1); else, dosinglecontrast=length(nsources)~=1; end; %~(length(nsources)>1 & all(csources==1/length(nsources))); end if isfield(CONN_x.Results,'foldername')&&~isempty(CONN_x.Results.foldername), [ok,nill]=mkdir(filepathresults2,CONN_x.Results.foldername); filepathresults2=fullfile(filepathresults2,CONN_x.Results.foldername); CONN_x.Results.foldername=[]; else, foldername={[CONN_x.Analyses(CONN_x.Analysis).name,'.']}; foldername{end+1}=['SUBJECT_EFFECTS_']; for n1=1:length(CONN_x.Results.xX.nsubjecteffects), if ~any(diff(CONN_x.Results.xX.csubjecteffects)),foldername{end+1}=[CONN_x.Setup.l2covariates.names{CONN_x.Results.xX.nsubjecteffects(n1)},'.']; else, foldername{end+1}=[CONN_x.Setup.l2covariates.names{CONN_x.Results.xX.nsubjecteffects(n1)},'(',num2str(CONN_x.Results.xX.csubjecteffects(n1),'%2.1f'),')','.'];end end foldername{end+1}=['CONDITIONS_']; for n1=1:length(nconditions), if ~any(diff(cconditions)),foldername{end+1}=[CONN_x.Setup.conditions.names{nconditions(n1)},'.']; else, foldername{end+1}=[CONN_x.Setup.conditions.names{nconditions(n1)},'(',num2str(cconditions(n1),'%2.1f'),')','.'];end end foldername=strcat(foldername{:}); foldername(foldername==' '|foldername==filesep)='_'; [ok,nill]=mkdir(filepathresults2,foldername); if ok,filepathresults2=fullfile(filepathresults2,foldername); else,filepathresults2=uigetdir(filepathresults2,'Select a directory to write the results');end end if ~ischar(filepathresults2), return; end; % disp(['Second-level results stored in ',filepathresults2]); X=zeros(CONN_x.Setup.nsubjects,length(CONN_x.Setup.l2covariates.names)-1); for nsub=1:CONN_x.Setup.nsubjects, for ncovariate=1:length(CONN_x.Setup.l2covariates.names)-1; X(nsub,ncovariate)=CONN_x.Setup.l2covariates.values{nsub}{ncovariate}; end end nsubjects=find(any(X(:,CONN_x.Results.xX.nsubjecteffects)~=0,2)); clear SPMall; cwd=pwd; cd(filepathresults2); REDUCENAMES=1; if dosinglecontrast>0, foldername={}; for n2=1:length(nsources), txttmp=sources{nsources(n2)}; if REDUCENAMES&&length(txttmp)>2&&strcmp(txttmp(1:3),'BA.'), idxtxttmp=find(txttmp=='.');idxtxttmp2=find(txttmp=='_'); if length(idxtxttmp)>1&&length(idxtxttmp2)>1&&idxtxttmp(end)-12&&strcmp(txttmp(1:3),'BA.'), idxtxttmp=find(txttmp=='.');idxtxttmp2=find(txttmp=='_'); if length(idxtxttmp)>1&&length(idxtxttmp2)>1&&idxtxttmp(end)-11, for n2=1:size(C,1), c=C(n2,:); cname=CONN_x.Setup.l2covariates.names{CONN_x.Results.xX.nsubjecteffects(n2)}; %CONN_x.Results.xX.name{n2}; SPM.xCon(end+1) = spm_FcUtil('Set',cname,'T','c',c',SPM.xX.xKXs); end cname='effects of interest'; SPM.xCon(end+1) = spm_FcUtil('Set',cname,'F','c',C,SPM.xX.xKXs); end end SPM=spm_contrasts(SPM,1:length(SPM.xCon)); save('SPM.mat','SPM'); if ~isempty(dir('con_0001.img')), switch(CONN_x.Analyses(CONN_x.Analysis).measure), case {1,2}, %correlation V=spm_vol('con_0001.img'); t=spm_read_vols(V); V.fname='corr_0001.img'; spm_write_vol(V,tanh(t)); end end conn_waitbar(1/2+1/2*(n1/(length(SPMall))),h); if isfield(CONN_x,'gui')&&isnumeric(CONN_x.gui)&&CONN_x.gui, conn_display('SPM.mat',1); end end conn_waitbar('close',h); cd(cwd); case 2, % fixed-effects for n1=1:length(SPMall), cd(filepathresults3{n1}); csources=SPMall(n1).connvols.csources; cconditions=SPMall(n1).connvols.cconditions; Y=SPMall(n1).connvols.Y; SE=SPMall(n1).connvols.SE; xf=SPMall(n1).xX.X; filename='CON_spmT_0001.mat'; Yout=Y(1); Yout.fname=filename; Yout.size.Nt=1; Yout.DOF=sum([SE(:).DOF]); Yout=conn_init_vol(Yout); for slice=1:Y(1).matdim.dim(3), yf=0; se.data=0; se.dof=0; for ncondition=1:size(Y,2), for nsource=1:size(Y,1), [temp,y.idx]=conn_get_slice(Y(nsource,ncondition),slice); yf=yf+temp*csources(nsource)*cconditions(ncondition); end; [temp,nill]=conn_get_slice(SE(ncondition),slice); se.data=se.data+sum(csources.^2)*(cconditions(ncondition)*temp).^2; se.dof=se.dof+SE(ncondition).DOF; end se.data=sqrt(se.data); [B,opt]=conn_glmunivariate('estimatefixed',xf,yf,se); [H,F,p,dof,R]=conn_glmunivariate('evaluatefixed',opt,[],CONN_x.Results.xX.csubjecteffects); conn_write_slice(Yout,F,slice,0); conn_waitbar(1/2+1/2*((n1-1+slice/Y(1).matdim.dim(3))/(length(SPMall))),h); end t=nan+zeros(Yout.matdim.dim); y=conn_get_time(Yout,1); %V=spm_vol(deblank(CONN_x.Setup.structural{nsub}{1})); V=V(1); V=CONN_x.Setup.structural{1}{3}; V=V(1); t(Yout.voxels)=y; V.fname='spmT_0001.img'; if isfield(V,'dt'), V.dt=[spm_type('float32') spm_platform('bigend')]; elseif length(V.dim)>3, V.dim(4)=spm_type('float32'); end spm_write_vol(V,t); clear SPM; SPM.xCon(1).Vspm=V; SPM.xCon(1).eidf=inf; SPM.xX.erdf=Yout.DOF; SPM.xVol.R=[]; SPM.xVol.S=[]; save('SPM.mat','SPM'); if isfield(CONN_x,'gui')&&isnumeric(CONN_x.gui)&&CONN_x.gui, conn_display('SPM.mat',1); end end conn_waitbar('close',h); cd(cwd); end end end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Creates second-level ROI.mat results %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==15), filepathresults1=fullfile(CONN_x.folders.firstlevel,CONN_x.Analyses(CONN_x.Analysis).name); filepathresults2=CONN_x.folders.secondlevel; sources=CONN_x.Analyses(CONN_x.Analysis).sources; nconditions=CONN_x.Results.xX.nconditions; cconditions=CONN_x.Results.xX.cconditions; if nargin<=1, dosinglecontrast=0; nsources=1:length(sources); csources=ones(1,length(nsources)); else dosinglecontrast=1; nsources=varargin{1}; csources=varargin{2}; end if ~nargout, if isfield(CONN_x.Results,'foldername')&&~isempty(CONN_x.Results.foldername), [ok,nill]=mkdir(filepathresults2,CONN_x.Results.foldername); filepathresults2=fullfile(filepathresults2,CONN_x.Results.foldername); CONN_x.Results.foldername=[]; else, foldername={[CONN_x.Analyses(CONN_x.Analysis).name,'.']}; foldername{end+1}=['SUBJECT_EFFECTS_']; for n1=1:length(CONN_x.Results.xX.nsubjecteffects), if ~any(diff(CONN_x.Results.xX.csubjecteffects)),foldername{end+1}=[CONN_x.Setup.l2covariates.names{CONN_x.Results.xX.nsubjecteffects(n1)},'.']; else, foldername{end+1}=[CONN_x.Setup.l2covariates.names{CONN_x.Results.xX.nsubjecteffects(n1)},'(',num2str(CONN_x.Results.xX.csubjecteffects(n1),'%2.1f'),')','.'];end end foldername{end+1}=['CONDITIONS_']; for n1=1:length(nconditions), if ~any(diff(cconditions)),foldername{end+1}=[CONN_x.Setup.conditions.names{nconditions(n1)},'.']; else, foldername{end+1}=[CONN_x.Setup.conditions.names{nconditions(n1)},'(',num2str(cconditions(n1),'%2.1f'),')','.'];end end foldername=strcat(foldername{:}); foldername(foldername==' '|foldername==filesep)='_'; [ok,nill]=mkdir(filepathresults2,foldername); if ok,filepathresults2=fullfile(filepathresults2,foldername); else,filepathresults2=uigetdir(filepathresults2,'Select a directory to write the results');end % if isfield(CONN_x.Results,'foldername')&&~isempty(CONN_x.Results.foldername), % [ok,nill]=mkdir(filepathresults2,CONN_x.Results.foldername); % filepathresults2=fullfile(filepathresults2,CONN_x.Results.foldername); % else, % filepathresults2=CONN_x.folders.secondlevel; % filepathresults2=uigetdir(filepathresults2,'Select a directory to write the results'); % end end if ~ischar(filepathresults2), return; end; end X=zeros(CONN_x.Setup.nsubjects,length(CONN_x.Setup.l2covariates.names)-1); for nsub=1:CONN_x.Setup.nsubjects, for ncovariate=1:length(CONN_x.Setup.l2covariates.names)-1; X(nsub,ncovariate)=CONN_x.Setup.l2covariates.values{nsub}{ncovariate}; end end nsubjects=find(any(X(:,CONN_x.Results.xX.nsubjecteffects)~=0,2)); %h=conn_waitbar(0,['Step ',num2str(sum(options<=15)),'/',num2str(length(options)),': ROI data second-level analyses']); se.data=0; se.dof=0; y=0; Y=repmat({0},[1,length(nsources)]); for n0=1:length(nconditions), ncondition=nconditions(n0); filename=fullfile(filepathresults1,['resultsROI_Condition',num2str(ncondition,'%03d'),'.mat']); if isempty(dir(filename)), Ransw=questdlg('First-level ROI analyses have not completed. Perform now?','warning','Yes','No','Yes'); if strcmp(Ransw,'Yes'), conn_process('analyses_roi'); end end load(filename,'Z','names','names2','xyz','SE','DOF'); iroi=[];clear ixyz; for nroi=1:length(sources), roiname=sources{nroi}; tiroi=strmatch(roiname,names,'exact'); if isempty(tiroi), error(['Non-existing ROI first-level data for ',roiname,'. Please repeat first-level analyses']); return; end iroi(nroi)=tiroi(1); ixyz{nroi}=xyz{tiroi(1)}; end for n1=1:length(nsources), nroi=nsources(n1); yt=permute(Z(iroi(nroi),:,:),[3,2,1]); y=y+yt*csources(n1)*cconditions(n0); % subjects x rois Y{n1}=Y{n1}+yt*cconditions(n0); end se.data=se.data+(cconditions(n0)*SE).^2; se.dof=se.dof+DOF; end se.data=sqrt(se.data); %if nargin>1, dosinglecontrast=(varargin{1}==1); else, dosinglecontrast=~(length(nsources)>1 & all(csources==1/length(nsources))); end clear SPMall filepathresults3; %cwd=pwd; %cd(filepathresults2); if dosinglecontrast, ROIall.xX.X=X(nsubjects,CONN_x.Results.xX.nsubjecteffects);%CONN_x.Results.xX.X; ROIall.xX.name={CONN_x.Setup.l2covariates.names{CONN_x.Results.xX.nsubjecteffects}};%CONN_x.Results.xX.name; % if ~nargout, filepathresults3{n1}=filepathresults2; end ROIall.y=y(nsubjects,:); ROIall.se=se; ROIall.se.data=sqrt(sum(csources.^2))*ROIall.se.data; ROIall.se.data=ROIall.se.data(nsubjects,:); ROIall.se.dof=ROIall.se.dof(nsubjects); else for n1=1:length(nsources), ROIall(n1).xX.X=X(nsubjects,CONN_x.Results.xX.nsubjecteffects);%CONN_x.Results.xX.X; ROIall(n1).xX.name={CONN_x.Setup.l2covariates.names{CONN_x.Results.xX.nsubjecteffects}};%CONN_x.Results.xX.name; nroi=nsources(n1); roiname=sources{nroi}; % if ~nargout,[ok,nill]=mkdir(filepathresults2,roiname); filepathresults3{n1}=fullfile(filepathresults2,roiname); end ROIall(n1).y=Y{n1}(nsubjects,:); ROIall(n1).se=se; ROIall(n1).se.data=ROIall(n1).se.data(nsubjects,:); ROIall(n1).se.dof=ROIall(n1).se.dof(nsubjects); end end clear ROIout; for n1=1:length(ROIall), ROI=ROIall(n1); ROI.names=sources; ROI.xyz=ixyz; ROI.names2=names2; ROI.xyz2=xyz; ROI.cname='connectivity result'; ROI.c=CONN_x.Results.xX.csubjecteffects;%CONN_x.Results.xX.C; %[ROI.h,ROI.F,ROI.p,ROI.dof]=conn_glm(ROI.xX.X,ROI.y,ROI.c,[],'AA'); if ~isfield(CONN_x.Results.xX,'modeltype')||isempty(CONN_x.Results.xX.modeltype), CONN_x.Results.xX.modeltype=1; end if CONN_x.Results.xX.modeltype==1, [b,opt]=conn_glmunivariate('estimate',ROI.xX.X,ROI.y); [ROI.h,ROI.F,ROI.p,ROI.dof]=conn_glmunivariate('evaluate',opt,[],ROI.c); else, [b,opt]=conn_glmunivariate('estimatefixed',ROI.xX.X,ROI.y,ROI.se); [ROI.h,ROI.F,ROI.p,ROI.dof]=conn_glmunivariate('evaluatefixed',opt,[],ROI.c); end ROIout(n1)=ROI; % if ~(nargin>1), save(fullfile(filepathresults3{n1},'ROI.mat'),'ROI'); % elseif dosinglecontrast, varargout{1}=ROI; % elseif n1<=length(nsources), varargout{1}(n1)=ROI; end %conn_waitbar(1/2+1/2*(n1/(length(nsources)+1)),h); end varargout{1}=ROIout; if ~nargout, ROI=ROIout;save(fullfile(filepathresults2,'ROI.mat'),'ROI'); end %conn_waitbar('close',h); ; %cd(cwd); end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % Displays second-level SPM.mat results %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if any(options==16), conn_display; end %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % additional version-update step %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if 0,%any(options==17), [path,name,ext]=fileparts(CONN_x.filename); % filepath=fullfile(path,name,'data'); filepath=CONN_x.folders.preprocessing; filename=fullfile(filepath,['ROI_Subject',num2str(1,'%03d'),'_Condition',num2str(1,'%03d'),'.mat']); X1=load(filename); [X,nill,names]=conn_designmatrix(CONN_x.Analyses.regressors,X1,[]); CONN_x.Analyses(CONN_x.Analysis).sources=names; % CONN_x.Results.measure=CONN_x.Analyses.measure; end return; % from SPM5 function savefields(fnam,p) if length(p)>1, error('Can''t save fields.'); end; fn = fieldnames(p); if numel(fn)==0, return; end; for i=1:length(fn), eval([fn{i} '= p.' fn{i} ';']); end; if spm_matlab_version_chk('7') >= 0 save(fnam,'-V6',fn{:}); else save(fnam,fn{:}); end; function h=conn_waitbar(varargin); global CONN_x; h=[]; if isfield(CONN_x,'gui')&&isnumeric(CONN_x.gui)&&CONN_x.gui, if ischar(varargin{1}), h=varargin{2}; close(h); else, h=conn_timedwaitbar(varargin{:}); end else, if ischar(varargin{1}), conn_cumdisp; elseif ~varargin{1}, conn_cumdisp;disp(varargin{2}); else, conn_cumdisp([num2str(100*varargin{1},'%3.1f'),'% ']); end end function conn_cumdisp(txt); % CUMDISP persistent disp % cumdisp; initializes persistent display % cumdisp(text); displays persistent text % persistent oldtxt; if nargin<1, oldtxt=''; fprintf(1,'\n'); else, fprintf(1,[repmat('\b',[1,length(oldtxt)]),'%s'],txt); oldtxt=sprintf('%s',txt); end