├── Guide_MULAN.fig ├── User Guide MULAN.pdf ├── Interface ├── NameList.png ├── GUI_Preprocess.fig ├── MULAN_gen_data.fig ├── GUIevaluationROC2.fig ├── mln_cell2struct.m ├── mln_norm_data.m ├── mln_localizationwindows.m ├── mln_showparams.m ├── mln_plotROCcurve.m ├── mln_plotTime4Analysis.m ├── mln_showConnectionMatrix.m ├── mln_tofindNet.m ├── mln_initialparamsmethods.m ├── mln_showTimeSeriesLFP.m ├── mln_statesplot.m ├── mln_Result2fileSV.m ├── MULAN_gen_data.m~ ├── MULAN_gen_data.m └── GUI_Preprocess.m ├── Calculation ├── MULANLOGO.png ├── mln_normalizeNet.m ├── getPsd.m ├── getPsd_wavelet.m ├── NormalizeMatrixSymmetric.m ├── mln_Dir2Partial.m ├── mln_defineStructure.m ├── MULANCalMUltiBP.m ├── mln_issymetricM.m ├── mln_icalcMatGranger.m ├── updateResultMulti.m ├── MULANCalMUltiBP_Oct.m ├── mln_compareparams.m ├── mln_icalcMatMvar.m ├── istimeM.m ├── mln_chis.m ├── mln_icalcMatH2.m ├── mln_h2pair.m ├── mln_icalcMatTimeBasic.m ├── updateResult.m~ ├── getconher.m ├── updateResult.m ├── mln_icalcMatFreqBasic.m ├── getcc.m ├── mln_calcMatTimeBasic.m ├── mln_setgroupmethlogparam.m ├── mln_setgroupmethlogparam.m~ ├── mln_calcMatTE.m ├── mln_calcMatFreqBasic.m ├── mln_calcMatFreqBasic.m~ ├── mln_calcMatMITime.m ├── mln_calcMatH2.m ├── mln_Result2file.m ├── mln_Result2file.m~ ├── mln_calcMatGranger.m ├── mln_calcMatMvar.m ├── mln_calcMatMvar.m~ ├── mln_icalcMatTE.m ├── mln_icalcMatMITime.m ├── cca_regress.m ├── mln_calc_FalseRate.m ├── MulanCal.m ├── MulanCal.m~ ├── mvfilter.m ├── awt_freqlist.m ├── cca_partialgc.m └── covm.m ├── Evaluation ├── ExAUCnmmN5L5.mat ├── mln_xorder_cell.m ├── mln_MethodStructuresAUC.m ├── mln_showAUC.m~ └── mln_showAUC.m ├── GenerateData ├── structureN5L5.mat ├── spm_rand_mar.m ├── spm_sqrtm.m ├── spm_gx_erp.m ├── spm_lx_erp.m ├── spm_inv.m ├── spm_vec.m ├── spm_Q.m ├── spm_ssr_priors.m ├── spm_unvec.m ├── mln_generate_nmm.m~ ├── spm_gx_fmri.m ├── mln_generate_henon.m ├── mln_generate_henon.m~ ├── mln_generate_linear.m ├── mln_generate_nmm.m ├── spm_cat.m ├── spm_svd.m ├── mln_generate_fMRI.m ├── spm_dx.m ├── spm_expm.m ├── mln_generate_rossler.m~ ├── mln_generate_rossler.m ├── spm_erp_L.m ├── spm_lfp_priors.m ├── spm_L_priors.m ├── spm_int_L.m ├── spm_dcm_fmri_priors.m ├── spm_int_J.m └── spm_diff.m ├── ClusterComputation ├── nmmParams.mat ├── mln_generateParams.m ├── mln_CalEvaN.m~ └── mln_CalEvaN.m ├── Examples ├── data │ └── ExnmmCS100S20N3000.mat └── Results │ └── Granger_ExnmmCS100S20N3000.mat └── README.md /Guide_MULAN.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/Guide_MULAN.fig -------------------------------------------------------------------------------- /User Guide MULAN.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/User Guide MULAN.pdf -------------------------------------------------------------------------------- /Interface/NameList.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/Interface/NameList.png -------------------------------------------------------------------------------- /Calculation/MULANLOGO.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/Calculation/MULANLOGO.png -------------------------------------------------------------------------------- /Evaluation/ExAUCnmmN5L5.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/Evaluation/ExAUCnmmN5L5.mat -------------------------------------------------------------------------------- /GenerateData/structureN5L5.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/GenerateData/structureN5L5.mat -------------------------------------------------------------------------------- /Interface/GUI_Preprocess.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/Interface/GUI_Preprocess.fig -------------------------------------------------------------------------------- /Interface/MULAN_gen_data.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/Interface/MULAN_gen_data.fig -------------------------------------------------------------------------------- /ClusterComputation/nmmParams.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/ClusterComputation/nmmParams.mat -------------------------------------------------------------------------------- /Interface/GUIevaluationROC2.fig: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/Interface/GUIevaluationROC2.fig -------------------------------------------------------------------------------- /Calculation/mln_normalizeNet.m: -------------------------------------------------------------------------------- 1 | function net=mln_normalizeNet(net1) 2 | 3 | maxnet=max(max(abs(net1))); 4 | net=net1/maxnet; -------------------------------------------------------------------------------- /Examples/data/ExnmmCS100S20N3000.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/Examples/data/ExnmmCS100S20N3000.mat -------------------------------------------------------------------------------- /Examples/Results/Granger_ExnmmCS100S20N3000.mat: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HuifangWang/MULAN/HEAD/Examples/Results/Granger_ExnmmCS100S20N3000.mat -------------------------------------------------------------------------------- /Evaluation/mln_xorder_cell.m: -------------------------------------------------------------------------------- 1 | function indx=mln_xorder_cell(oCells,nCells) 2 | Nindx=length(nCells); 3 | indx=NaN(Nindx,1); 4 | for iindx=1:Nindx 5 | indx(iindx)=find(strcmp(nCells{iindx},oCells)); 6 | end -------------------------------------------------------------------------------- /Interface/mln_cell2struct.m: -------------------------------------------------------------------------------- 1 | function params=mln_cell2struct(cparams) 2 | nparams=size(cparams,1); 3 | for i=1:nparams 4 | parafiled=char(cparams{i,1}); 5 | 6 | params.(parafiled)=cparams{i,2}; 7 | end -------------------------------------------------------------------------------- /Calculation/getPsd.m: -------------------------------------------------------------------------------- 1 | function psd = getPsd(lfp, fs, freqs) 2 | [Nchannel,nTime]=size(lfp); 3 | nFreq=length(freqs); 4 | psd=zeros(Nchannel,nTime,nFreq); 5 | for i=1:Nchannel 6 | psd(i,:,:)=awt_freqlist(lfp(i,:), fs, freqs); 7 | end -------------------------------------------------------------------------------- /Calculation/getPsd_wavelet.m: -------------------------------------------------------------------------------- 1 | function psd = getPsd_wavelet(lfp, fs, freqs) 2 | [Nchannel,nTime]=size(lfp); 3 | nFreq=length(freqs); 4 | psd=zeros(Nchannel,nTime,nFreq); 5 | for i=1:Nchannel 6 | psd(i,:,:)=awt_freqlist(lfp(i,:), fs, freqs); 7 | end -------------------------------------------------------------------------------- /Interface/mln_norm_data.m: -------------------------------------------------------------------------------- 1 | function xnM=mln_norm_data(x) 2 | xnM=x; 3 | nchan=size(x,1); 4 | for i=1:nchan 5 | ix=x(i,:); 6 | mn = mean(ix); 7 | sd = std(ix); 8 | sd(sd==0) = 1; 9 | 10 | xn = bsxfun(@minus,ix,mn); 11 | xn = bsxfun(@rdivide,xn,sd); 12 | xnM(i,:)=xn; 13 | end -------------------------------------------------------------------------------- /Calculation/NormalizeMatrixSymmetric.m: -------------------------------------------------------------------------------- 1 | function N=NormalizeMatrixSymmetric(M) 2 | 3 | %% this function is to Normalize Symmetric Matrix N=M_ij^2/M_iiM_jj 4 | N=M; 5 | Nchan=size(M,1); 6 | for i=1:Nchan 7 | for j=i:Nchan 8 | N(i,j)=abs(M(i,j)^2)/(M(i,i)*M(j,j)); 9 | end 10 | end -------------------------------------------------------------------------------- /Calculation/mln_Dir2Partial.m: -------------------------------------------------------------------------------- 1 | function P=mln_Dir2Partial(M) 2 | 3 | %% This function transfers a Matrix M to Partial ones P 4 | 5 | nchannel=size(M,1); 6 | M=M-diag(diag(M))+eye(nchannel); 7 | IM=-inv(M); 8 | P=(IM ./ repmat(sqrt(abs(diag(IM))),1,nchannel)) ./ repmat(sqrt(abs(diag(IM)))',nchannel,1)+eye(nchannel); 9 | -------------------------------------------------------------------------------- /Interface/mln_localizationwindows.m: -------------------------------------------------------------------------------- 1 | function iw=mln_localizationwindows(ts,params,fs) 2 | % this function is to find the corresponding window to the given time t 3 | ps=ts*fs; 4 | overlap_p=params.wins*params.overlap; 5 | iw=floor((ps-overlap_p)/(params.wins-overlap_p))+1; 6 | if iw<=0 7 | iw=1; 8 | end 9 | 10 | -------------------------------------------------------------------------------- /Calculation/mln_defineStructure.m: -------------------------------------------------------------------------------- 1 | function mln_defineStructure() 2 | 3 | %% structure 1: Node 6, NL=4; common source 4 | 5 | PGS{1}=[1 3 4;2 2 5]; 6 | PGS{2}=[2 3 3 4;1 2 3 5]; 7 | PGS{3}=[1 3 4 5;2 2 6 6]; 8 | PGS{4}=[1 3 3 4 4 5;2 2 3 6 5 6]; 9 | PGS{5}=[1 5 4 3 4;2 2 2 2 3]; 10 | PGS{6}=[1 5 4 3 4 5;2 2 2 2 3 1]; 11 | 12 | save('structureSG1.mat','PGS') -------------------------------------------------------------------------------- /ClusterComputation/mln_generateParams.m: -------------------------------------------------------------------------------- 1 | function mln_generateParams() 2 | 3 | calParams.defwindow='150'; 4 | calParams.defoverlap='0.5'; 5 | calParams.defmodelorders='5'; 6 | calParams.minfreq='1'; 7 | calParams.maxfreq='30'; 8 | calParams.stepfreq='0.5'; 9 | calParams.defbins='16'; 10 | calParams.defMaxDelay='5'; 11 | 12 | save('nmmParams.mat','calParams'); -------------------------------------------------------------------------------- /Calculation/MULANCalMUltiBP.m: -------------------------------------------------------------------------------- 1 | function MULANCalMUltiBP(dirname,prenom,paramsfile,VGroupMethlog) 2 | % Huifang Wang, Marseille, August 26, 2013, Calculate all datasets with 3 | % basic prenom 4 | paramsfile=[dirname,'/',paramsfile]; 5 | load(paramsfile,'calParams') 6 | 7 | MulanCal(dirname,prenom,calParams,VGroupMethlog); 8 | mln_Result2file(dirname,prenom,VGroupMethlog) 9 | 10 | -------------------------------------------------------------------------------- /Calculation/mln_issymetricM.m: -------------------------------------------------------------------------------- 1 | function issym=mln_issymetricM(method) 2 | SymmetricM={'BCorrU', 'PCorrU' , 'BCohF' , 'BCohW' , 'PCohF' , 'PCohW' 'BH2U' 'PH2U',... 3 | 'Smvar' , 'COH1' , 'COH2' , 'pCOH1' , 'pCOH2' , 'BMITU', 'PMITU'}; 4 | 5 | xf=find(strcmp(method,SymmetricM)); 6 | if isempty(xf) 7 | issym=0; 8 | else 9 | issym=1; 10 | end 11 | -------------------------------------------------------------------------------- /Calculation/mln_icalcMatGranger.m: -------------------------------------------------------------------------------- 1 | function Mat=icalcMatGranger(lfp,modelOrder) 2 | [nchan,~]=size(lfp); 3 | STATFLAG=0; 4 | %Nr=1; 5 | 6 | ret = cca_partialgc(lfp,modelOrder,STATFLAG); 7 | %ret= cca_granger_regress(lfp,modelOrder,STATFLAG); 8 | Mat.GC=ret.gc; 9 | Mat.PGC=mln_Dir2Partial(Mat.GC+eye(nchan)); 10 | Mat.CondGC=ret.fg; 11 | 12 | %Mat.SGCausal=pwcausal(lfp,Nr,Nl,modelOrder,fs,freq); 13 | -------------------------------------------------------------------------------- /Interface/mln_showparams.m: -------------------------------------------------------------------------------- 1 | function TextParams=mln_showparams(ParamsStru) 2 | %% this function will make the parmasters can be demostrated by GUI 3 | TextParams=''; 4 | if isstruct(ParamsStru) 5 | params_names=fieldnames(ParamsStru); 6 | Np=length(params_names); 7 | for i=1:Np 8 | iparams=[params_names(i),num2str(ParamsStru.(char((params_names(i)))))]; 9 | TextParams=[TextParams;iparams]; 10 | end 11 | end -------------------------------------------------------------------------------- /Calculation/updateResultMulti.m: -------------------------------------------------------------------------------- 1 | function updateResultMulti(Resultfile,netMatrix) 2 | % Update file Resultfile 3 | %% Huifang Wang Apr.10, 2012, Marseille 4 | 5 | prevar=load(Resultfile); 6 | if isstruct(prevar) 7 | Rconnect=prevar; 8 | if isstruct(netMatrix) 9 | Methlogs=fieldnames(netMatrix); 10 | Nmeth=length(Methlogs); 11 | for i=1:Nmeth 12 | iMethlogs=char(Methlogs(i)); 13 | Rconnect.(iMethlogs)=netMatrix.(iMethlogs); 14 | save(Resultfile,'-struct','Rconnect'); 15 | end 16 | end 17 | end -------------------------------------------------------------------------------- /Interface/mln_plotROCcurve.m: -------------------------------------------------------------------------------- 1 | %% function plot ROC 2 | function plotROCcurve(Fpr,Tpr,auc,ha2) 3 | cla(ha2); 4 | rf=[0,1]; 5 | %hold on 6 | Fpr=[Fpr;0]; %% put the [0,0] as the beginning point to be drew 7 | Tpr=[Tpr;0]; 8 | plot(Fpr,Tpr,'g-','linewidth',2,'parent',ha2); 9 | set(ha2,'NextPlot','add'); 10 | plot(rf,rf,'parent',ha2); 11 | %set(get(ha2,'XLabel'),'String','False positive rate '); 12 | %set(get(ha2,'YLabel'),'String','True positive rate'); 13 | %title('ROC'); 14 | axis(ha2,'tight') 15 | htext=findobj(ha2,'Type','text'); 16 | delete(htext); 17 | text(0.4,0.3,num2str(auc),'parent',ha2); 18 | %hold off -------------------------------------------------------------------------------- /Calculation/MULANCalMUltiBP_Oct.m: -------------------------------------------------------------------------------- 1 | function MULANCalMUltiBP_Oct(dirname,prenom,idata,paramsfile) 2 | % Huifang Wang, Marseille, August 26, 2013, Calculate all datasets with 3 | % basic prenom 4 | idata=str2double(idata); 5 | paramsfile=[dirname,'/',paramsfile]; 6 | load(paramsfile,'calParams') 7 | 8 | mkdir([dirname,'/Results']); 9 | mkdir([dirname,'/ToutResults']); 10 | VGroupMethlog={'TimeBasic','FreqBasic','Hsquare','Granger','FreqAH','MutualInform','TE'}; 11 | 12 | dataprenom=[prenom,num2str(idata)]; 13 | MulanCal(dirname,dataprenom,calParams,VGroupMethlog); 14 | mln_Result2file(dirname,dataprenom,VGroupMethlog); 15 | 16 | -------------------------------------------------------------------------------- /Interface/mln_plotTime4Analysis.m: -------------------------------------------------------------------------------- 1 | function mln_plotTime4Analysis(g) 2 | 3 | figure('name',g.Methlog); 4 | Net=g.Net; 5 | fs=g.fs; 6 | 7 | Nchan=size(Net,1); 8 | NT=size(Net,3); 9 | if length(size(Net))>3 10 | iwNet=squeeze(Net(:,:,:,iw)); 11 | else 12 | iwNet=Net; 13 | end 14 | ymax=max(max(max(iwNet))); 15 | ymin=min(min(min(iwNet))); 16 | T=(1:NT)/fs; 17 | meanC=mean(Net,3); 18 | for i=1:Nchan 19 | for j=1:Nchan 20 | subplot(Nchan,Nchan,(i-1)*Nchan+j); 21 | mCij=meanC(i,j)*ones(size(T)); 22 | plot(T,squeeze(Net(i,j,:)),'b--',T,mCij,'m-','Linewidth',2); 23 | set(gca,'YLim',[ymin,ymax]); 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /Calculation/mln_compareparams.m: -------------------------------------------------------------------------------- 1 | function issame=mln_compareparams(oldparams,newparams) 2 | %% compare two sets of parameters 3 | %fieldold=fieldnames(oldparams); 4 | % Huifang Wang Marseille, Nov, 12 5 | % Huifang Wang, update 13 Feb. 14 6 | fieldnew=fieldnames(newparams); 7 | Nfield=length(fieldnew); 8 | issame=0; 9 | for i=1:Nfield 10 | ifield=fieldnew{i}; 11 | p1=oldparams.(ifield); 12 | p2=newparams.(ifield); 13 | if ischar(p1) 14 | p1=str2double(p1); 15 | end 16 | if ischar(p2) 17 | p2=str2double(p2); 18 | end 19 | if p1==p2; 20 | issame=1; 21 | else 22 | issame=0; 23 | return; 24 | end 25 | end 26 | -------------------------------------------------------------------------------- /Calculation/mln_icalcMatMvar.m: -------------------------------------------------------------------------------- 1 | function Mat=mln_icalcMatMvar(lfp,Morder,freqs,fs) 2 | [AR,~,PE] = mvar(lfp,Morder); 3 | nchannel = size(AR,1); % number of channels 4 | A = [eye(nchannel),-AR]; 5 | B = eye(nchannel); 6 | C = PE(:,nchannel*Morder+1:nchannel*(Morder+1)); 7 | 8 | %Net=zeros(nchannel); 9 | % %% sum 10 | % for i=1:Morder 11 | % Net=Net+AR(:,(i-1)*nchannel+1:i*nchannel); 12 | % end 13 | AR03=reshape(AR,nchannel,nchannel,Morder); 14 | Net=max(abs(AR03),[],3); 15 | Mat.MVAR=Net; 16 | [Mat.Smvar, Mat.hmvar, Mat.PDC, Mat.COH1, Mat.DTF, Mat.DC1, Mat.pCOH1, Mat.dDTF, Mat.ffDTF, Mat.pCOH2,Mat.oPDCF, Mat.COH2, Mat.GGC, Mat.Af, Mat.GPDC, Mat.AS] = mvfreqz(B,A,C,freqs,fs); -------------------------------------------------------------------------------- /GenerateData/spm_rand_mar.m: -------------------------------------------------------------------------------- 1 | function [y] = spm_rand_mar(m,n,a) 2 | % generates random variates from an autoregressive process 3 | % FORMAT [y] = spm_rand_mar(m,n,a) 4 | % m - time bins 5 | % n - variates 6 | % a - autoregression coefficients 7 | % 8 | % see also: spm_rand_power_law 9 | %__________________________________________________________________________ 10 | % Copyright (C) 2012 Wellcome Trust Centre for Neuroimaging 11 | 12 | % Karl Friston 13 | % $Id: spm_rand_mar.m 5633 2013-09-10 13:58:03Z karl $ 14 | 15 | 16 | % create random process 17 | %-------------------------------------------------------------------------- 18 | y = spm_sqrtm(spm_Q(a,m))*randn(m,n); 19 | 20 | -------------------------------------------------------------------------------- /Calculation/istimeM.m: -------------------------------------------------------------------------------- 1 | function istimeM=istimeM(Methlog) 2 | %% this function is used to tell issymetricM whether Methlog can obtain a 3 | %% symetric results or not: issymetricM=1 if Methlog can get symtric matrices 4 | istimeM=0; 5 | timeMs={'BCorrD','BCorrU','PCorrD','PCorrU','GC','PGC','CondGC',... 6 | 'BH2D','PH2U','PH2D','BH2U','BSynchroS','BSynchroH','BSynchroN',... 7 | 'PSynchroS','PSynchroH','PSynchroN','BMITD1','BMITD2',... 8 | 'PMITD1','PMITD2','BMITU', 'PMITU', 'DPSPLVH',... 9 | 'DPSENTH','BTED','BTEU','PTED','PTEU'}; 10 | %Nonsymetric={'Af','PDC','PDCF','DTF'}; 11 | 12 | NMlog=length(Methlog); 13 | if ~isempty(find(strncmpi(timeMs,Methlog,NMlog)==1,1)) 14 | istimeM=1; 15 | end -------------------------------------------------------------------------------- /GenerateData/spm_sqrtm.m: -------------------------------------------------------------------------------- 1 | function [K] = spm_sqrtm(V) 2 | % Matrix square root for sparse symmetric positive semi-definite matrices 3 | % FORMAT [K] = spm_sqrtm(V) 4 | % 5 | % This routine covers and extends sqrtm functionality by using a 6 | % computationally expedient approximation that can handle sparse 7 | % symmetric positive semi-definite matrices. 8 | %__________________________________________________________________________ 9 | % Copyright (C) 2005-2013 Wellcome Trust Centre for Neuroimaging 10 | 11 | % Karl Friston 12 | % $Id: spm_sqrtm.m 5219 2013-01-29 17:07:07Z spm $ 13 | 14 | %-------------------------------------------------------------------------- 15 | [u,s] = spm_svd(V,0,1e-16); 16 | s = sqrt(abs(diag(s))); 17 | m = length(s); 18 | s = sparse(1:m,1:m,s); 19 | K = u*s*u'; 20 | -------------------------------------------------------------------------------- /Interface/mln_showConnectionMatrix.m: -------------------------------------------------------------------------------- 1 | function showConnectionMatrix(net,ha,fbar,Params) 2 | % Huifang Wang, sep. 6, + set color bar after delete the diagonal 3 | nchan=size(net,1); 4 | if ~isempty(find(strncmpi(fieldnames(Params),'str',3)==1,1)) 5 | nodenames=Params.str; 6 | else 7 | nodenames=num2cell(1:nchan); 8 | end 9 | 10 | 11 | cla(ha) 12 | axis equal; 13 | 14 | hold all; 15 | if isempty(net) 16 | return; 17 | end 18 | net=net-diag(diag(net)); 19 | imagesc(net,'parent',ha); 20 | axis tight; 21 | set(ha,'Ydir','reverse'); 22 | maxClim=max(max(abs(net))); 23 | minClim=-maxClim; 24 | colormap(ha,jet); 25 | set(ha,'CLim',[minClim maxClim]); 26 | if fbar 27 | colorbar('peer',ha,'CLim',[minClim maxClim]); 28 | end 29 | if ~isempty(nodenames) 30 | set(ha,'YTick',1:nchan,'YTickLabel',nodenames); 31 | set(ha,'XTick',1:nchan,'XTickLabel',nodenames); 32 | end -------------------------------------------------------------------------------- /GenerateData/spm_gx_erp.m: -------------------------------------------------------------------------------- 1 | function [y] = spm_gx_erp(x,u,P,M) 2 | % observer for a neural mass model of erps 3 | % FORMAT [y] = spm_gx_erp(x,u,P,M) 4 | % x - state vector 5 | % y - measured voltage y = L*x(:) 6 | %__________________________________________________________________________ 7 | % 8 | % David O, Friston KJ (2003) A neural mass model for MEG/EEG: coupling and 9 | % neuronal dynamics. NeuroImage 20: 1743-1755 10 | %__________________________________________________________________________ 11 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 12 | 13 | % Karl Friston 14 | % $Id: spm_gx_erp.m 2393 2008-10-23 14:58:50Z karl $ 15 | 16 | % parameterised lead field times [perturbations] of states 17 | %-------------------------------------------------------------------------- 18 | L = spm_lx_erp(P,M); 19 | y = L*(spm_vec(x) - spm_vec(M.x)); 20 | 21 | -------------------------------------------------------------------------------- /Interface/mln_tofindNet.m: -------------------------------------------------------------------------------- 1 | function Net=mln_tofindNet(Resultfile,Methlog,params,flaguse) 2 | Net=[]; 3 | if exist(Resultfile) 4 | NetSaved=load(Resultfile); 5 | oddfieldname=fieldnames(NetSaved); 6 | NMlog=length(Methlog); 7 | if ~isempty(find(strncmpi(oddfieldname,Methlog,NMlog)==1,1))% if there is results about 'Methlog' 8 | % try to find the results with the same parameters 9 | Nmethlog=length(NetSaved.(Methlog)); 10 | 11 | for i=1:Nmethlog 12 | if mln_compareparams(NetSaved.(Methlog)(i).Params,params) 13 | Net=NetSaved.(Methlog)(i); 14 | switch flaguse 15 | case 'E' 16 | if length(size(Net))>3 17 | Net.Mat=squeeze(mean(abs(Net.Mat),3)); 18 | end 19 | end 20 | break; 21 | end 22 | end 23 | 24 | end 25 | 26 | end 27 | -------------------------------------------------------------------------------- /Interface/mln_initialparamsmethods.m: -------------------------------------------------------------------------------- 1 | function paramsdata=mln_initialparamsmethods(paramsfields) 2 | defwindow='350'; 3 | defoverlap='0.5'; 4 | defmodelorders='5'; 5 | minfreq='1'; 6 | maxfreq='40'; 7 | stepfreq='0.5'; 8 | defbins='16'; 9 | defPatternN='10'; 10 | defNeighborN='10'; 11 | defMaxDelay='12'; 12 | 13 | param_df=struct('wins',defwindow,... 14 | 'overlap',defoverlap,... 15 | 'modelOrder',defmodelorders,... 16 | 'minfreq',minfreq,'maxfreq',maxfreq,'stepfreq',stepfreq,... 17 | 'bins',defbins,... 18 | 'NeighborN',defNeighborN,... 19 | 'PatternN',defPatternN,... 20 | 'MaxDelay',defMaxDelay); 21 | 22 | Nparamf=length(paramsfields); 23 | paramsdata=cell(Nparamf,2); 24 | for i=1:Nparamf 25 | paramsdata{i,1}=paramsfields{i}; 26 | paramsdata{i,2}=param_df.(paramsfields{i}); 27 | end 28 | -------------------------------------------------------------------------------- /GenerateData/spm_lx_erp.m: -------------------------------------------------------------------------------- 1 | function [L] = spm_lx_erp(P,M) 2 | % observer matrix for a neural mass model of erps: y = G*x 3 | % FORMAT [G] = spm_lx_erp(P,M) 4 | % x - state vector 5 | % G - where y = L*x; G = dy/dx 6 | %__________________________________________________________________________ 7 | % 8 | % David O, Friston KJ (2003) A neural mass model for MEG/EEG: coupling and 9 | % neuronal dynamics. NeuroImage 20: 1743-1755 10 | %__________________________________________________________________________ 11 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 12 | 13 | % Karl Friston 14 | % $Id: spm_lx_erp.m 2393 2008-10-23 14:58:50Z karl $ 15 | 16 | % parameterised lead field times source contribution to ECD 17 | %-------------------------------------------------------------------------- 18 | L = spm_erp_L(P,M); % lead field per source 19 | L = kron(P.J,L); % lead-field per state 20 | -------------------------------------------------------------------------------- /Calculation/mln_chis.m: -------------------------------------------------------------------------------- 1 | function chis=mln_chis(Mat,x) 2 | 3 | %% chis is the c hist of bootstrapping of Mat 4 | 5 | nboot=1000; 6 | nbins=100; 7 | 8 | 9 | [Nnode,~,Nwin]=size(Mat); 10 | isizeboot=Nnode*(Nnode-1); 11 | 12 | MatBoot=NaN( isizeboot*nboot,1); 13 | 14 | iMat=mean(abs(Mat),3); 15 | iMat(1:size(iMat,1)+1:end) = NaN; 16 | a=reshape(iMat,Nnode*Nnode,1); 17 | MatBoot(1:isizeboot,1)=a(~isnan(a)); 18 | 19 | for iboot=2:nboot 20 | iBoot_ind=randi(Nwin,[1,Nwin]); 21 | iBoot_Mat=Mat(:,:,iBoot_ind); 22 | iMat=mean(abs(iBoot_Mat),3); 23 | iMat(1:size(iMat,1)+1:end) = NaN; 24 | a=reshape(iMat,Nnode*Nnode,1); 25 | MatBoot((iboot-1)*isizeboot+1:iboot*isizeboot,1)=a(~isnan(a)); 26 | end 27 | xi=linspace(min(MatBoot),max(MatBoot),nbins); 28 | n_elements = histc(MatBoot,xi); 29 | c_elements = cumsum(n_elements); 30 | c_elements=c_elements./max(c_elements); 31 | %% the means for all windows 32 | chis=c_elements(find(xi>=x,1)); 33 | -------------------------------------------------------------------------------- /GenerateData/spm_inv.m: -------------------------------------------------------------------------------- 1 | function X = spm_inv(A,TOL) 2 | % inverse for ill-conditioned matrices 3 | % FORMAT X = spm_inv(A,TOL) 4 | % 5 | % A - matrix 6 | % X - inverse 7 | % 8 | % TOL - tolerance: default = max(eps(norm(A,'inf'))*max(m,n),exp(-32)) 9 | % 10 | % This routine simply adds a small diagonal matrix to A and calls inv.m 11 | %__________________________________________________________________________ 12 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 13 | 14 | % Karl Friston 15 | % $Id: spm_inv.m 4360 2011-06-14 16:46:37Z ged $ 16 | 17 | % check A 18 | %-------------------------------------------------------------------------- 19 | [m,n] = size(A); 20 | if isempty(A), X = sparse(n,m); return, end 21 | 22 | % tolerance 23 | %-------------------------------------------------------------------------- 24 | if nargin == 1 25 | TOL = max(eps(norm(A,'inf'))*max(m,n),exp(-32)); 26 | end 27 | 28 | % inverse 29 | %-------------------------------------------------------------------------- 30 | X = inv(A + speye(m,n)*TOL); 31 | -------------------------------------------------------------------------------- /Interface/mln_showTimeSeriesLFP.m: -------------------------------------------------------------------------------- 1 | function mln_showTimeSeriesLFP(lfp,st,wins,scale,Params,a1) 2 | 3 | % st: start time 4 | %wins: how large wins to show; 5 | %scale: 6 | 7 | spoint=floor(st*Params.fs)+1; 8 | winspoint=floor(wins*Params.fs); 9 | lfp=lfp(:,spoint:winspoint+spoint); 10 | [nChannel,ttpoint]=size(lfp); 11 | %spacechannel=7; 12 | ylabel=nChannel:-1:1; 13 | if isempty(find(strncmpi(fieldnames(Params),'str',3)==1,1)) 14 | YLabels = num2cell(ylabel); 15 | else 16 | YLabels=Params.str; 17 | end 18 | lfp=flipud(lfp); 19 | cla(a1,'reset'); 20 | %hold on; 21 | 22 | 23 | ttime=(spoint:winspoint+spoint)./Params.fs; 24 | 25 | %lfp = detrend(lfp); 26 | 27 | SeparateBy = scale*(max(lfp(:)) - min(lfp(:))); 28 | plot(a1, ttime, lfp' + SeparateBy*repmat((1:nChannel),[ttpoint,1])); 29 | 30 | %set(a1,'ylim',[0 SeparateBy*(nChannel+1)]); 31 | set(a1,'xlim',[st ttime(end)]) 32 | 33 | 34 | set(a1,'YTick',SeparateBy*(1:nChannel)); 35 | set(a1,'YTickLabel',fliplr(YLabels)); 36 | %set(a1,'Ydir','reverse'); 37 | %Y_Limit=get(a1,'YLim'); 38 | %plot([t,t],Y_Limit,'color','red','parent',a1); 39 | %hold off -------------------------------------------------------------------------------- /Calculation/mln_icalcMatH2.m: -------------------------------------------------------------------------------- 1 | function Mat=icalcMatH2(lfp,modelOrder,bins) 2 | 3 | %% calculate the correlation coefficient with delay 4 | nchannel=size(lfp,1); 5 | Mat.BH2D=zeros(nchannel); 6 | ijh2=zeros(modelOrder,1); 7 | for i=1:nchannel 8 | for j=1:nchannel 9 | for tou=0:modelOrder 10 | ijh2(tou+1)=mln_h2pair(lfp(i,:),lfp(j,:),tou,bins); 11 | end 12 | [~,Iij]=max(abs(ijh2)); 13 | Mat.BH2D(j,i)=ijh2(Iij); 14 | end 15 | end 16 | Mat.BH2U=max(Mat.BH2D,Mat.BH2D'); 17 | %Mat.DH2E=updateEC(Mat.DH2E); 18 | Mat.PH2U=mln_Dir2Partial(Mat.BH2U); 19 | Mat.PH2D=mln_Dir2Partial(Mat.BH2D); 20 | 21 | % %% updated effective connectivity function 22 | % function M1=updateEC(M) 23 | % M1=M; 24 | % [Ni,Nj]=size(M); 25 | % for i=1:Ni 26 | % for j=i:Nj 27 | % if M(i,j)>M(j,i) 28 | % M1(j,i)=0; 29 | % M1(i,j)=M(i,j); 30 | % else 31 | % M1(i,j)=0; 32 | % M1(j,i)=M(j,i); 33 | % end 34 | % if abs(M(i,j)-M(j,i))<=0.001 35 | % M1(j,i)=M(j,i); 36 | % M1(j,i)=M(j,i); 37 | % 38 | % end 39 | % end 40 | % end -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | MULAN 2 | ===== 3 | 4 | MULAN: MULTIPLE CONNECTIVITY ANALYSIS 5 | 6 | The MULAN (MULtiple connectivity ANalysis) MATLAB toolbox helps researchers to 7 | evaluate connectivity analysis methods in a systematic way. Prior to applying 8 | specific methods to a given dataset, MULAN can be used to generate relevant 9 | simulated signals, identify valid parameter ranges for the methods, and 10 | evaluate their performance and robustness against underlying connection 11 | strengths, graph structures and noise levels. Lastly, new methods can easily be 12 | added and tested using this toolbox. 13 | 14 | 15 | ##MULAN setup 16 | 17 | To begin using MULAN, just place the MULAN1 files in any accessible folder on 18 | your computer and make sure to either set the MULAN1 folder as the current path 19 | in MATLAB or add the folder containing MULAN1 to the MATLAB path. 20 | 21 | # References 22 | Wang HE, Bénar CG, Quilichini PP, Friston KJ, Jirsa VK, Bernard C. A systematic framework for functional connectivity measures. Front Neurosci. 2014;8(December):1-22. doi:10.3389/fnins.2014.00405. 23 | 24 | The codes for the second story of the MULAN series are in: 25 | https://github.com/HuifangWang/MULANIICodes 26 | -------------------------------------------------------------------------------- /Calculation/mln_h2pair.m: -------------------------------------------------------------------------------- 1 | function xyh2=mln_h2pair(x,y,tou,bins) 2 | Nt=length(x); 3 | %% update x y pair with delay tou 4 | x=x(1:Nt-tou); 5 | y=y(1+tou:Nt); 6 | 7 | Maxx=max(x); 8 | Minx=min(x); 9 | stepx=(Maxx-Minx)/bins; 10 | xbin=Minx:stepx:Maxx; 11 | %% define xbar and ybar 12 | xbar=zeros(1,bins); 13 | ybar=xbar; 14 | sxy=zeros(1,bins-1); 15 | for ibins=1:bins 16 | ibinx=find(xbin(ibins)<= x & x <=xbin(ibins+1)); 17 | if isempty(ibinx) 18 | xbar(ibins)=xbar(ibins-1)+stepx; 19 | ybar(ibins)=ybar(ibins-1); 20 | else 21 | xbar(ibins)=mean(x(ibinx)); 22 | ybar(ibins)=mean(y(ibinx)); 23 | end 24 | end 25 | 26 | for ibins=1:bins-1 27 | sxy(ibins)=(ybar(ibins+1)-ybar(ibins))/(xbar(ibins+1)-xbar(ibins)); 28 | end 29 | %%% compute the yh=h(x) 30 | yh=zeros(size(x)); 31 | for i=1:Nt-tou 32 | indexbin=find(xbar>x(i),1); 33 | 34 | if isempty(indexbin) 35 | indexbin=bins-1; 36 | end 37 | 38 | if indexbin==bins 39 | indexbin=bins-1; 40 | end 41 | if indexbin==1 42 | indexbin_1=1; 43 | else 44 | indexbin_1=indexbin-1; 45 | end 46 | yh(i)=sxy(indexbin_1)*(x(i)-xbar(indexbin_1))+ybar(indexbin_1); 47 | end 48 | 49 | yyh = bsxfun(@minus, y, yh); 50 | varyyh = var(yyh); 51 | vary=var(y); 52 | xyh2=1-varyyh/vary; 53 | -------------------------------------------------------------------------------- /Calculation/mln_icalcMatTimeBasic.m: -------------------------------------------------------------------------------- 1 | function Mat=icalcMatTimeBasic(lfp,modelOrder) 2 | 3 | %% calculate the correlation coefficient with delay 4 | %% Huifang Wang, 12, June, 12 5 | %% Huifang Wang 04, June, 13 update the method name 6 | 7 | nchannel=size(lfp,1); 8 | Mat.BCorrU=zeros(nchannel); 9 | Mat.BCorrD=zeros(nchannel); 10 | for i=1:nchannel 11 | for j=i:nchannel 12 | ijxcorr=xcov(lfp(i,:),lfp(j,:),modelOrder,'coeff'); 13 | [~,Imax]=max(abs(ijxcorr)); 14 | %Mat.DCorrSym(i,j)=C; 15 | Mat.BCorrU(i,j)=ijxcorr(Imax); 16 | Mat.BCorrU(j,i)=Mat.BCorrU(i,j); 17 | Cij=ijxcorr((0:modelOrder)+modelOrder+1); 18 | [Dij,ImaxDij]=max(abs(Cij)); 19 | Cji=ijxcorr((-modelOrder:0)+modelOrder+1); 20 | [Dji,ImaxDji]=max(abs(Cji)); 21 | % if Dij>Dji 22 | % Mat.DCorrE(j,i)=0; 23 | % Mat.DCorrE(i,j)=Cij(ImaxDij); 24 | % else 25 | % Mat.DCorrE(i,j)=0; 26 | % Mat.DCorrE(j,i)=Cji(ImaxDji); 27 | % 28 | % end 29 | % if abs(Dij-Dji)<=0.001 30 | % Mat.DCorrE(j,i)=Cji(ImaxDji); 31 | % Mat.DCorrE(i,j)=Cij(ImaxDij); 32 | % 33 | % end 34 | Mat.BCorrD(j,i)=Dji;%% updated Dec. 13 35 | Mat.BCorrD(i,j)=Dij; 36 | end 37 | 38 | end 39 | 40 | Mat.PCorrD=mln_Dir2Partial(Mat.BCorrD); 41 | Mat.PCorrU=mln_Dir2Partial(Mat.BCorrU); 42 | 43 | -------------------------------------------------------------------------------- /Calculation/updateResult.m~: -------------------------------------------------------------------------------- 1 | function updateResult(Resultfile,Net,params) 2 | % update the Resultfile with adding net with structure name Methlog 3 | %%% Huifang Wang Apr.10, 2012, Marseille 4 | %%% Huifang Wang June 20, update for save multi methods at the same time in 5 | %%% order to save saving time 6 | VMethodlog=fieldnames(Net); 7 | Nmethod=length(VMethodlog); 8 | if ~exist(Resultfile,'file') 9 | for j=1:Nmethod 10 | Methlog=char(VMethodlog(j)); 11 | Rconnect.(Methlog)(1).Mat=Net.(Methlog); 12 | if ~isempty(params) 13 | Rconnect.(Methlog)(1).Params=params; 14 | end 15 | end 16 | else 17 | %Net.Params=params; 18 | prevar=load(Resultfile); 19 | if isstruct(prevar) 20 | Rconnect=prevar; 21 | 22 | for j=1:Nmethod 23 | Methlog=char(VMethodlog(j)); 24 | NMlog=length(Methlog); 25 | oldfieldname=fieldnames(Rconnect); 26 | if isempty(find(strncmpi(oldfieldname,Methlog,NMlog)==1,1)) 27 | Rconnect.(Methlog)(1).Mat=Net.(Methlog); 28 | if ~isempty(params) 29 | Rconnect.(Methlog)(1).Params=params; 30 | end 31 | else 32 | Rconnect.(Methlog)(end+1).Mat=Net.(Methlog); 33 | if ~isempty(params) 34 | Rconnect.(Methlog)(end).Params=params; 35 | end 36 | 37 | end 38 | end 39 | 40 | end 41 | 42 | end 43 | 44 | save(Resultfile,'-struct','Rconnect'); -------------------------------------------------------------------------------- /Calculation/getconher.m: -------------------------------------------------------------------------------- 1 | function relations=getconher(lfp,params,band) 2 | [Nchannel,nTime]=size(lfp); 3 | Npairs_ch=Nchannel*(Nchannel-1)/2; 4 | fs=params.fs; 5 | ntw=60; 6 | switch band 7 | case 'S1' 8 | freqs=params.freqs.s1; 9 | case 'Delta' 10 | freqs=params.freqs.delta; 11 | 12 | case 'Theta' 13 | freqs=params.freqs.theta; 14 | 15 | case 'beta' 16 | freqs=params.freqs.beta; 17 | 18 | case 'gamma' 19 | freqs=params.freqs.gamma; 20 | 21 | end 22 | nFreq=length(freqs); 23 | % relations = struct('cfs', zeros(Nchannel,nTime,nFreq), ... 24 | % 'crossM', zeros(Npairs_ch,nTime,nFreq), ... 25 | % 'crossP', zeros(Npairs_ch,nTime,nFreq),... 26 | % 'cohM', zeros(Npairs_ch,nTime,nFreq), ... 27 | % 'cohP', zeros(Npairs_ch,nTime,nFreq)); 28 | 29 | relations = struct('cfs', zeros(Nchannel,nTime,nFreq), ... 30 | 'crossM', zeros(Npairs_ch,nTime,nFreq), ... 31 | 'cohM', zeros(Npairs_ch,nTime,nFreq)); 32 | cfs = getPsd(lfp,fs,freqs); 33 | for i=1:Nchannel 34 | for j=i+1:Nchannel 35 | cfs1(:,:)=cfs(i,:,:); 36 | cfs2(:,:)=cfs(j,:,:); 37 | [cross, coh]=getcc(cfs1,cfs2,'ntw',ntw); 38 | n_pairs=(i-1)*(Nchannel-1)-(i-1)*(i-2)/2+(j-i); 39 | relations.crossM(n_pairs,:,:)=abs(cross); 40 | relations.cohM(n_pairs,:,:)=abs(coh); 41 | 42 | end 43 | end 44 | 45 | for i=1:Nchannel 46 | relations.cfs(i,:,:)=abs(cfs(i,:,:)); 47 | end 48 | -------------------------------------------------------------------------------- /Calculation/updateResult.m: -------------------------------------------------------------------------------- 1 | function updateResult(Resultfile,Net,params) 2 | % update the Resultfile with adding net with structure name Methlog 3 | %%% Huifang Wang Apr.10, 2012, Marseille 4 | %%% Huifang Wang June 20, update for save multi methods at the same time in 5 | %%% order to save saving time 6 | [cdata] = imread('MULANLOGO.png'); 7 | VMethodlog=fieldnames(Net); 8 | Nmethod=length(VMethodlog); 9 | if ~exist(Resultfile,'file') 10 | for j=1:Nmethod 11 | Methlog=char(VMethodlog(j)); 12 | Rconnect.(Methlog)(1).Mat=Net.(Methlog); 13 | if ~isempty(params) 14 | Rconnect.(Methlog)(1).Params=params; 15 | end 16 | end 17 | else 18 | %Net.Params=params; 19 | prevar=load(Resultfile); 20 | if isstruct(prevar) 21 | Rconnect=prevar; 22 | 23 | for j=1:Nmethod 24 | Methlog=char(VMethodlog(j)); 25 | NMlog=length(Methlog); 26 | oldfieldname=fieldnames(Rconnect); 27 | if isempty(find(strncmpi(oldfieldname,Methlog,NMlog)==1,1)) 28 | Rconnect.(Methlog)(1).Mat=Net.(Methlog); 29 | if ~isempty(params) 30 | Rconnect.(Methlog)(1).Params=params; 31 | end 32 | else 33 | Rconnect.(Methlog)(end+1).Mat=Net.(Methlog); 34 | if ~isempty(params) 35 | Rconnect.(Methlog)(end).Params=params; 36 | end 37 | 38 | end 39 | end 40 | 41 | end 42 | 43 | end 44 | 45 | 46 | msgbox('Calculation completed','Success','custom',cdata); 47 | save(Resultfile,'-struct','Rconnect'); -------------------------------------------------------------------------------- /GenerateData/spm_vec.m: -------------------------------------------------------------------------------- 1 | function [vX] = spm_vec(varargin) 2 | % vectorises a numeric, cell or structure array 3 | % FORMAT [vX] = spm_vec(X); 4 | % X - numeric, cell or stucture array[s] 5 | % vX - vec(X) 6 | %__________________________________________________________________________ 7 | % 8 | % e.g.: 9 | % spm_vec({eye(2) 3}) = [1 0 0 1 3]' 10 | %__________________________________________________________________________ 11 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 12 | 13 | % Karl Friston 14 | % $Id: spm_vec.m 5691 2013-10-11 16:53:00Z karl $ 15 | 16 | % initialise X and vX 17 | %-------------------------------------------------------------------------- 18 | if nargin == 1 19 | X = varargin{1}; 20 | else 21 | X = varargin; 22 | end 23 | 24 | 25 | % vectorise numerical arrays 26 | %-------------------------------------------------------------------------- 27 | if isnumeric(X) 28 | vX = X(:); 29 | 30 | % vectorise logical arrays 31 | %-------------------------------------------------------------------------- 32 | elseif islogical(X) 33 | vX = X(:); 34 | 35 | % vectorise structure into cell arrays 36 | %-------------------------------------------------------------------------- 37 | elseif isstruct(X) 38 | vX = []; 39 | f = fieldnames(X); 40 | X = X(:); 41 | for i = 1:numel(f) 42 | vX = cat(1,vX,spm_vec({X.(f{i})})); 43 | end 44 | 45 | % vectorise cells into numerical arrays 46 | %-------------------------------------------------------------------------- 47 | elseif iscell(X) 48 | vX = []; 49 | for i = 1:numel(X) 50 | vX = cat(1,vX,spm_vec(X{i})); 51 | end 52 | else 53 | vX = []; 54 | end 55 | -------------------------------------------------------------------------------- /GenerateData/spm_Q.m: -------------------------------------------------------------------------------- 1 | function [Q] = spm_Q(a,n,q) 2 | % returns an (n x n) (inverse) autocorrelation matrix for an AR(p) process 3 | % FORMAT [Q] = spm_Q(a,n,q) 4 | % 5 | % a - vector of (p) AR coefficients 6 | % n - size of Q 7 | % q - switch to return inverse autocorrelation or precision [default q = 0] 8 | %__________________________________________________________________________ 9 | % spm_Q uses a Yule-Walker device to compute K where: 10 | % 11 | % y = K*z 12 | % 13 | % such that y is an AR(p) process generated from an i.i.d innovation 14 | % z. This means 15 | % 16 | % cov(y) = = K*K' 17 | % 18 | % If called with q ~= 0, a first order process is assumed when evaluating 19 | % the precision (inverse covariance) matrix; i.e., a = a(1) 20 | %__________________________________________________________________________ 21 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 22 | 23 | % Karl Friston 24 | % $Id: spm_Q.m 4836 2012-08-10 15:55:21Z karl $ 25 | 26 | % default 27 | %-------------------------------------------------------------------------- 28 | try, q; catch, q = 0; end 29 | 30 | if q 31 | 32 | % compute P (precision) 33 | %---------------------------------------------------------------------- 34 | A = [-a(1) (1 + a(1)^2) -a(1)]; 35 | Q = spdiags(ones(n,1)*A,[-1:1],n,n); 36 | else 37 | 38 | % compute Q (covariance) 39 | %---------------------------------------------------------------------- 40 | p = length(a); 41 | A = [1 -a(:)']; 42 | P = spdiags(ones(n,1)*A,-[0:p],n,n); 43 | K = inv(P); 44 | K = K.*(abs(K) > 1e-4); 45 | Q = K*K'; 46 | Q = toeplitz(Q(:,1)); 47 | end 48 | 49 | -------------------------------------------------------------------------------- /Calculation/mln_icalcMatFreqBasic.m: -------------------------------------------------------------------------------- 1 | function Mat=mln_icalcMatFreqBasic(lfp,freqs,fs) 2 | 3 | %% Huifang Wang, 04, June, 13 update the method name 4 | 5 | nchannel=size(lfp,1); 6 | 7 | Nwins=8; 8 | % Number of arrows and flag for plots. 9 | [Nchannel,Ntimes]=size(lfp); 10 | Nfreqs=length(freqs); 11 | %flag_SMOOTH = true; 12 | NTW = min([round(0.05*Ntimes),20]); 13 | nfft=(Nfreqs-1)*2; 14 | window=floor(Ntimes/Nwins); 15 | noverlap=floor(window/2); 16 | %z=[Nchannel,Ntimes,Nfreqs]; 17 | %% calculate for wavelet 18 | %% initialization 19 | 20 | zbar=[Nchannel,Nchannel,Nfreqs]; 21 | DCohw=zeros(zbar); 22 | %DCohwN=zeros(zbar); 23 | DCohf=zeros(zbar); 24 | cfs.w = getPsd(lfp,fs,freqs); 25 | %cfs.f=zeros(Nchannel,Nfreqs); 26 | % for i=1:Nchannel 27 | % cfs.f(i,:) = pwelch(lfp(i,:), window, noverlap, nfft, fs)'; 28 | % end 29 | for i=1:Nchannel 30 | for j=i:Nchannel 31 | %% wavelet 32 | cfs1(:,:)=cfs.w(i,:,:); 33 | cfs2(:,:)=cfs.w(j,:,:); 34 | [cross, ~]=getcc(cfs1,cfs2,'ntw',NTW); 35 | DCohw(i,j,:)=squeeze(mean(abs(cross),1)); 36 | %DCohwN(i,j,:)=squeeze(mean(abs(coh),1)); 37 | %% fft 38 | %cfs_fcross(i,j,:) = cpsd(lfp(i,:), lfp(j,:), window, noverlap, nfft, fs); 39 | DCohf(i,j,:) = mscohere(lfp(i,:), lfp(j,:), window, noverlap, nfft, fs); 40 | end 41 | end 42 | for i=1:Nfreqs 43 | iDCohw=NormalizeMatrixSymmetric(DCohw(:,:,i)); 44 | Mat.BCohW(:,:,i)=iDCohw'+iDCohw-diag(diag(iDCohw)); 45 | Mat.PCohW(:,:,i)=mln_Dir2Partial(Mat.BCohW(:,:,i)); 46 | 47 | iDCohf=DCohf(:,:,i); 48 | Mat.BCohF(:,:,i)=iDCohf'+iDCohf-diag(diag(iDCohf)); 49 | Mat.PCohF(:,:,i)=mln_Dir2Partial(Mat.BCohF(:,:,i)); 50 | end 51 | %Mat.cfs=cfs; 52 | -------------------------------------------------------------------------------- /Calculation/getcc.m: -------------------------------------------------------------------------------- 1 | function [cross, coh]=getcc(cfs1,cfs2,varargin) 2 | %%%% get the cross spectrum and coherence from 3 | 4 | nbIN = nargin; 5 | 6 | % Parameters for Smoothing (Width of Windows). 7 | flag_SMOOTH = true; 8 | NSW = []; 9 | NTW = []; 10 | 11 | % Number of arrows and flag for plots. 12 | 13 | 14 | if nbIN>2 15 | nbIN = nbIN-2; 16 | k = 1; 17 | while k<=nbIN 18 | argNAM = varargin{k}; 19 | if k0) 33 | flag_SMOOTH = true; 34 | end 35 | if ~isempty(NTW) && isequal(fix(NTW),NTW) && (NTW>0) 36 | flag_SMOOTH = true; 37 | else 38 | NTW = min([round(0.05*length(s1)),20]); 39 | end 40 | 41 | cfs_s10 = cfs1; 42 | cfs_s1 = smoothCFS(abs(cfs_s10).^2,flag_SMOOTH,NSW,NTW); 43 | cfs_s1 = sqrt(cfs_s1); 44 | cfs_s2 = cfs2; 45 | cfs_s20 = cfs_s2; 46 | cfs_s2 = smoothCFS(abs(cfs_s20).^2,flag_SMOOTH,NSW,NTW); 47 | cfs_s2 = sqrt(cfs_s2); 48 | cross = conj(cfs_s10).*cfs_s20; 49 | cross = smoothCFS(cross,flag_SMOOTH,NSW,NTW); 50 | coh= cross./(cfs_s1.*cfs_s2); 51 | 52 | function CFS = smoothCFS(CFS,flag_SMOOTH,NSW,NTW) 53 | 54 | if ~flag_SMOOTH , return; end 55 | if ~isempty(NTW) 56 | len = NTW; 57 | F = ones(1,len)/len; 58 | CFS = conv2(CFS,F,'same'); 59 | end 60 | if ~isempty(NSW) 61 | len = NSW; 62 | F = ones(1,len)/len; 63 | CFS = conv2(CFS,F','same'); 64 | end 65 | %--- -------------------------------------------------------------------------------- /Evaluation/mln_MethodStructuresAUC.m: -------------------------------------------------------------------------------- 1 | % Huifang Wang, Sep. 26, 2013 2 | % Huifang Wang, Nov. 26, 2013 update Method Structure AUC for mlnI 3 | function flg=mln_MethodStructuresAUC(dirname,prenom) 4 | 5 | flg=0; % flg for the error 6 | 7 | 8 | filename=['./',dirname,'/ToutResults/Tout_',prenom,'.mat']; 9 | 10 | calresult=load(filename); 11 | fieldname=fieldnames(calresult); 12 | % remove params and connectivity 13 | fieldname(strcmp('Params',fieldname))=[]; 14 | 15 | fieldname(strcmp('Connectivity',fieldname))=[]; 16 | %% 17 | %idx=find(strcmp('pCOH1',fieldname)); 18 | %fieldname(idx)=[]; 19 | %% 20 | Nmethod=length(fieldname); 21 | Meths.MSAUC=zeros(Nmethod,1); 22 | Meths.Mth=zeros(Nmethod,1); 23 | filesaved=['AUC_',prenom,'.mat']; 24 | 25 | Meths.Methodnames=fieldname; 26 | 27 | Meths.Connectivity=calresult.Connectivity; 28 | 29 | for imethod=1:Nmethod 30 | Methods=fieldname{imethod}; 31 | Mat=calresult.(Methods); 32 | if isnan(max(Mat)) 33 | 34 | auc=0; 35 | chis=1; 36 | iMat=NaN(size(Mat,1)); 37 | 38 | else 39 | iMat=mean(abs(Mat),3); 40 | iMat=iMat-diag(diag(iMat)); 41 | [~,~,~,~,~,~,~,~,auc,~,thresh3] =mln_calc_FalseRate(iMat,calresult.Connectivity,mln_issymetricM(Methods),1); 42 | chis=mln_chis(Mat,thresh3(1)); 43 | end 44 | Meths.MSAUC(imethod,1)=auc; 45 | 46 | if isempty(chis) 47 | pause 48 | end 49 | Meths.Mth(imethod,1)=chis; 50 | Meths.Mat(:,:,imethod)=iMat; 51 | end 52 | 53 | 54 | save(['./',dirname,'/AUC/',filesaved],'Meths'); 55 | -------------------------------------------------------------------------------- /Calculation/mln_calcMatTimeBasic.m: -------------------------------------------------------------------------------- 1 | function mln_calcMatTimeBasic(Resultfile,VMethlog,lfp,params) 2 | %% to calculate the connectivity matrix for Time Basic methods in Methlog 3 | % Methlog: 'DCorrSym','DCorrDir','PCorrSym','PCorrDir' 4 | % Huifang Wang, June 8, 2012, Inserm U1106, Marseille 5 | Methlog=char(VMethlog{1}); 6 | NMlog=length(Methlog); 7 | if exist(Resultfile,'file') 8 | Rconnect=load(Resultfile); 9 | oddfieldname=fieldnames(Rconnect); 10 | if ~isempty(find(strncmpi(oddfieldname,Methlog,NMlog)==1,1))% if there is results about 'Methlog' 11 | % try to find the results with the same parameters 12 | Nmethlog=length(Rconnect.(Methlog)); 13 | for i=1:Nmethlog 14 | if mln_compareparams(Rconnect.(Methlog)(i).Params,params) 15 | %Net=Rconnect.(Methlog)(i); 16 | return; 17 | end 18 | end 19 | end 20 | end 21 | %% if there is not the result then calculate 22 | 23 | [Nchannel, Ntime]=size(lfp); 24 | 25 | if ~params.overlap==0 26 | overlap_p=params.wins*params.overlap; 27 | Nwindows=floor((Ntime-overlap_p)/(params.wins-overlap_p)); 28 | else 29 | overlap_p=0; 30 | Nwindows=floor(Ntime/params.wins); 31 | end 32 | % initialization 33 | Dmatf=[Nchannel,Nchannel,Nwindows]; 34 | NMeths=length(VMethlog); 35 | for i=1:NMeths 36 | iMeth=char(VMethlog{i}); 37 | if ~isempty(iMeth) 38 | Mat.(iMeth)=zeros(Dmatf); 39 | end 40 | end 41 | 42 | VMethodlog=fieldnames(Mat); 43 | Nmethod=length(VMethodlog); 44 | for i=1:Nwindows 45 | i_lfp=lfp(:,floor((i-1)*(params.wins-overlap_p)+1):floor(i*params.wins-(i-1)*overlap_p)); 46 | iMat=mln_icalcMatTimeBasic(i_lfp,params.MaxDelay); 47 | for j=1:Nmethod 48 | Mat.(char(VMethodlog(j)))(:,:,i)=iMat.(char(VMethodlog(j))); 49 | end 50 | end 51 | 52 | updateResult(Resultfile,Mat,params); -------------------------------------------------------------------------------- /Calculation/mln_setgroupmethlogparam.m: -------------------------------------------------------------------------------- 1 | function [methods_in_group,paramsfields]=setgroupmethlogparam(GroupMethlog) 2 | % set the group methods and param depends on the method Group 3 | % Huifang Wang Dec 14, 2012 4 | % Huifang Wang June 4, 2013 5 | switch GroupMethlog 6 | case 'TimeBasic' 7 | methods_in_group={'BCorrU','BCorrD','PCorrU','PCorrD'}; 8 | paramsfields={'wins','overlap','MaxDelay'}; 9 | case 'FreqBasic' 10 | methods_in_group={'BCohF','BCohW','PCohF','PCohW'}; 11 | paramsfields={'wins','overlap','minfreq','maxfreq','stepfreq'}; 12 | case 'Hsquare' 13 | methods_in_group={'BH2U','PH2U','BH2D','PH2D'}; 14 | paramsfields={'wins','overlap','MaxDelay','bins'}; 15 | case 'SynchroSNH' 16 | methods_in_group={'DSynchroS','PSynchroS','DSynchroH','PSynchroH','DSynchroN','PSynchroN'}; 17 | paramsfields={'wins','overlap','NeighborN','modelOrder','PatternN'}; 18 | case 'Granger' 19 | methods_in_group={'GC','PGC','CondGC'}; 20 | paramsfields={'wins','overlap','modelOrder'}; 21 | case 'FreqAH' 22 | methods_in_group={'MVAR','Smvar','hmvar','PDC','COH1','COH2',... 23 | 'DTF','DC1','dDTF','ffDTF','pCOH1','pCOH2','AS','oPDCF','GGC','Af','GPDC'}; 24 | paramsfields={'wins','overlap','modelOrder','minfreq','maxfreq','stepfreq'}; 25 | case 'MutualInform' 26 | methods_in_group={'BMITU','PMITU','BMITD1','PMITD1','BMITD2','PMITD2'}; 27 | paramsfields={'wins','overlap','MaxDelay','bins'}; 28 | case 'PhaseSynch' 29 | methods_in_group={'DPSPLVH','DPSENTH'}; 30 | paramsfields={'wins','overlap','MaxDelay'}; 31 | case 'TE' 32 | methods_in_group={'BTEU','BTED','PTEU','PTED'}; 33 | paramsfields={'wins','overlap','MaxDelay'}; 34 | 35 | end -------------------------------------------------------------------------------- /Calculation/mln_setgroupmethlogparam.m~: -------------------------------------------------------------------------------- 1 | function [methods_in_group,paramsfields]=mln_setgroupmethlogparam(GroupMethlog) 2 | % set the group methods and param depends on the method Group 3 | % Huifang Wang Dec 14, 2012 4 | % Huifang Wang June 4, 2013 5 | switch GroupMethlog 6 | case 'TimeBasic' 7 | methods_in_group={'BCorrU','BCorrD','PCorrU','PCorrD'}; 8 | paramsfields={'wins','overlap','MaxDelay'}; 9 | case 'FreqBasic' 10 | methods_in_group={'BCohF','BCohW','PCohF','PCohW'}; 11 | paramsfields={'wins','overlap','minfreq','maxfreq','stepfreq'}; 12 | case 'Hsquare' 13 | methods_in_group={'BH2U','PH2U','BH2D','PH2D'}; 14 | paramsfields={'wins','overlap','MaxDelay','bins'}; 15 | case 'SynchroSNH' 16 | methods_in_group={'DSynchroS','PSynchroS','DSynchroH','PSynchroH','DSynchroN','PSynchroN'}; 17 | paramsfields={'wins','overlap','NeighborN','modelOrder','PatternN'}; 18 | case 'Granger' 19 | methods_in_group={'GC','PGC','CondGC'}; 20 | paramsfields={'wins','overlap','modelOrder'}; 21 | case 'FreqAH' 22 | methods_in_group={'MVAR','Smvar','hmvar','PDC','COH1','COH2',... 23 | 'DTF','DC1','dDTF','ffDTF','pCOH1','pCOH2','AS','oPDCF','GGC','Af','GPDC'}; 24 | paramsfields={'wins','overlap','modelOrder','minfreq','maxfreq','stepfreq'}; 25 | case 'MutualInform' 26 | methods_in_group={'BMITU','PMITU','BMITD1','PMITD1','BMITD2','PMITD2'}; 27 | paramsfields={'wins','overlap','MaxDelay','bins'}; 28 | case 'PhaseSynch' 29 | methods_in_group={'DPSPLVH','DPSENTH'}; 30 | paramsfields={'wins','overlap','MaxDelay'}; 31 | case 'TE' 32 | methods_in_group={'BTEU','BTED','PTEU','PTED'}; 33 | paramsfields={'wins','overlap','MaxDelay'}; 34 | 35 | end -------------------------------------------------------------------------------- /Calculation/mln_calcMatTE.m: -------------------------------------------------------------------------------- 1 | function mln_calcMatTE(Resultfile,VMethlog,lfp,params) 2 | 3 | % Huifang Wang, Nov 8, 2013, Inserm U1106, Marseille 4 | if iscell(VMethlog) 5 | Methlog=char(VMethlog{1}); 6 | else 7 | Methlog=VMethlog; 8 | end 9 | NMlog=length(Methlog); 10 | if exist(Resultfile,'file') 11 | Rconnect=load(Resultfile); 12 | oddfieldname=fieldnames(Rconnect); 13 | if ~isempty(find(strncmpi(oddfieldname,Methlog,NMlog)==1,1))% if there is results about 'Methlog' 14 | % try to find the results with the same parameters 15 | Nmethlog=length(Rconnect.(Methlog)); 16 | for i=1:Nmethlog 17 | if mln_compareparams(Rconnect.(Methlog)(i).Params,params) 18 | %Net=Rconnect.(Methlog)(i); 19 | return; 20 | end 21 | end 22 | end 23 | end 24 | %% if there is not the result then calculate 25 | 26 | [Nchannel, Ntime]=size(lfp); 27 | 28 | if ~params.overlap==0 29 | overlap_p=params.wins*params.overlap; 30 | Nwindows=floor((Ntime-overlap_p)/(params.wins-overlap_p)); 31 | else 32 | overlap_p=0; 33 | Nwindows=floor(Ntime/params.wins); 34 | end 35 | % initialization 36 | Dmatt=[Nchannel,Nchannel,Nwindows]; 37 | NMeths=length(VMethlog); 38 | for i=1:NMeths 39 | iMeth=char(VMethlog{i}); 40 | if ~isempty(iMeth) 41 | Mat.(iMeth)=zeros(Dmatt); 42 | end 43 | end 44 | 45 | 46 | VMethodlog=fieldnames(Mat); 47 | Nmethod=length(VMethodlog); 48 | for i=1:Nwindows 49 | i_lfp=lfp(:,floor((i-1)*(params.wins-overlap_p)+1):floor(i*params.wins-(i-1)*overlap_p)); 50 | iMat=mln_icalcMatTE(i_lfp,params.MaxDelay); 51 | for j=1:Nmethod 52 | jMethodlog=char(VMethodlog(j)); 53 | if istimeM(jMethodlog) 54 | Mat.(jMethodlog)(:,:,i)=iMat.(jMethodlog); 55 | else 56 | Mat.(jMethodlog)(:,:,:,i)=iMat.(jMethodlog); 57 | end 58 | end 59 | end 60 | 61 | updateResult(Resultfile,Mat,params); -------------------------------------------------------------------------------- /Calculation/mln_calcMatFreqBasic.m: -------------------------------------------------------------------------------- 1 | function calcMatFreqBasic(Resultfile,VMethlog,lfp,params) 2 | %% to calculate the connectivity matrix for FreqBasic methods in Methlog 3 | 4 | % Huifang Wang, June 9, 2012, Inserm U1106, Marseille 5 | Methlog=char(VMethlog{1}); 6 | NMlog=length(Methlog); 7 | if exist(Resultfile,'file') 8 | Rconnect=load(Resultfile); 9 | oddfieldname=fieldnames(Rconnect); 10 | if ~isempty(find(strncmpi(oddfieldname,Methlog,NMlog)==1,1))% if there is results about 'Methlog' 11 | % try to find the results with the same parameters 12 | Nmethlog=length(Rconnect.(Methlog)); 13 | for i=1:Nmethlog 14 | if compareparams(Rconnect.(Methlog)(i).Params,params) 15 | %Net=Rconnect.(Methlog)(i); 16 | return; 17 | end 18 | end 19 | end 20 | end 21 | %% if there is not the result then calculate 22 | 23 | [Nchannel, Ntime]=size(lfp); 24 | freqs=params.minfreq:params.stepfreq:params.maxfreq; 25 | Nfreq=length(freqs); 26 | 27 | if ~params.overlap==0 28 | overlap_p=params.wins*params.overlap; 29 | Nwindows=floor((Ntime-overlap_p)/(params.wins-overlap_p)); 30 | else 31 | overlap_p=0; 32 | Nwindows=floor(Ntime/params.wins); 33 | end 34 | % initialization 35 | Dmatf=[Nchannel,Nchannel,Nfreq,Nwindows]; 36 | NMeths=length(VMethlog); 37 | for i=1:NMeths 38 | iMeth=char(VMethlog{i}); 39 | if ~isempty(iMeth) 40 | Mat.(iMeth)=zeros(Dmatf); 41 | end 42 | end 43 | VMethodlog=fieldnames(Mat); 44 | Nmethod=length(VMethodlog); 45 | for i=1:Nwindows 46 | i_lfp=lfp(:,floor((i-1)*(params.wins-overlap_p)+1):floor(i*params.wins-(i-1)*overlap_p)); 47 | iMat=mln_icalcMatFreqBasic(i_lfp,freqs,params.fs); 48 | for j=1:Nmethod 49 | Mat.(char(VMethodlog(j)))(:,:,:,i)=iMat.(char(VMethodlog(j))); 50 | end 51 | % Mat.psd.w(:,floor((i-1)*params.wins+1):floor(i*params.wins),:)=iMat.cfs.w; 52 | % Mat.psd.f(:,i,:)=iMat.cfs.f; 53 | end 54 | updateResult(Resultfile,Mat,params); -------------------------------------------------------------------------------- /Calculation/mln_calcMatFreqBasic.m~: -------------------------------------------------------------------------------- 1 | function calcMatFreqBasic(Resultfile,VMethlog,lfp,params) 2 | %% to calculate the connectivity matrix for FreqBasic methods in Methlog 3 | 4 | % Huifang Wang, June 9, 2012, Inserm U1106, Marseille 5 | Methlog=char(VMethlog{1}); 6 | NMlog=length(Methlog); 7 | if exist(Resultfile,'file') 8 | Rconnect=load(Resultfile); 9 | oddfieldname=fieldnames(Rconnect); 10 | if ~isempty(find(strncmpi(oddfieldname,Methlog,NMlog)==1,1))% if there is results about 'Methlog' 11 | % try to find the results with the same parameters 12 | Nmethlog=length(Rconnect.(Methlog)); 13 | for i=1:Nmethlog 14 | if compareparams(Rconnect.(Methlog)(i).Params,params) 15 | %Net=Rconnect.(Methlog)(i); 16 | return; 17 | end 18 | end 19 | end 20 | end 21 | %% if there is not the result then calculate 22 | 23 | [Nchannel, Ntime]=size(lfp); 24 | freqs=params.minfreq:params.stepfreq:params.maxfreq; 25 | Nfreq=length(freqs); 26 | 27 | if ~params.overlap==0 28 | overlap_p=params.wins*params.overlap; 29 | Nwindows=floor((Ntime-overlap_p)/(params.wins-overlap_p)); 30 | else 31 | overlap_p=0; 32 | Nwindows=floor(Ntime/params.wins); 33 | end 34 | % initialization 35 | Dmatf=[Nchannel,Nchannel,Nfreq,Nwindows]; 36 | NMeths=length(VMethlog); 37 | for i=1:NMeths 38 | iMeth=char(VMethlog{i}); 39 | if ~isempty(iMeth) 40 | Mat.(iMeth)=zeros(Dmatf); 41 | end 42 | end 43 | VMethodlog=fieldnames(Mat); 44 | Nmethod=length(VMethodlog); 45 | for i=1:Nwindows 46 | i_lfp=lfp(:,floor((i-1)*(params.wins-overlap_p)+1):floor(i*params.wins-(i-1)*overlap_p)); 47 | iMat=mln_icalcMatFreqBasic(i_lfp,freqs,params.fs); 48 | for j=1:Nmethod 49 | Mat.(char(VMethodlog(j)))(:,:,:,i)=iMat.(char(VMethodlog(j))); 50 | end 51 | % Mat.psd.w(:,floor((i-1)*params.wins+1):floor(i*params.wins),:)=iMat.cfs.w; 52 | % Mat.psd.f(:,i,:)=iMat.cfs.f; 53 | end 54 | updateResult(Resultfile,Mat,params); -------------------------------------------------------------------------------- /Calculation/mln_calcMatMITime.m: -------------------------------------------------------------------------------- 1 | function mln_calcMatMITime(Resultfile,VMethlog,lfp,params) 2 | 3 | %% to calculate the connectivity matrix for Mvar_based methods in Methlog 4 | % Methlog: 'MVAR': MVAR 5 | % Huifang Wang, June 8, 2012, Inserm U1106, Marseille 6 | if iscell(VMethlog) 7 | Methlog=char(VMethlog{1}); 8 | else 9 | Methlog=VMethlog; 10 | end 11 | NMlog=length(Methlog); 12 | if exist(Resultfile,'file') 13 | Rconnect=load(Resultfile); 14 | oddfieldname=fieldnames(Rconnect); 15 | if ~isempty(find(strncmpi(oddfieldname,Methlog,NMlog)==1,1))% if there is results about 'Methlog' 16 | % try to find the results with the same parameters 17 | Nmethlog=length(Rconnect.(Methlog)); 18 | for i=1:Nmethlog 19 | if mln_compareparams(Rconnect.(Methlog)(i).Params,params) 20 | %Net=Rconnect.(Methlog)(i); 21 | return; 22 | end 23 | end 24 | end 25 | end 26 | %% if there is not the result then calculate 27 | 28 | [Nchannel, Ntime]=size(lfp); 29 | 30 | if ~params.overlap==0 31 | overlap_p=params.wins*params.overlap; 32 | Nwindows=floor((Ntime-overlap_p)/(params.wins-overlap_p)); 33 | else 34 | overlap_p=0; 35 | Nwindows=floor(Ntime/params.wins); 36 | end 37 | % initialization 38 | Dmatt=[Nchannel,Nchannel,Nwindows]; 39 | NMeths=length(VMethlog); 40 | for i=1:NMeths 41 | iMeth=char(VMethlog{i}); 42 | if ~isempty(iMeth) 43 | Mat.(iMeth)=zeros(Dmatt); 44 | end 45 | end 46 | 47 | 48 | VMethodlog=fieldnames(Mat); 49 | Nmethod=length(VMethodlog); 50 | for i=1:Nwindows 51 | i_lfp=lfp(:,floor((i-1)*(params.wins-overlap_p)+1):floor(i*params.wins-(i-1)*overlap_p)); 52 | iMat=mln_icalcMatMITime(i_lfp,params); 53 | for j=1:Nmethod 54 | jMethodlog=char(VMethodlog(j)); 55 | if istimeM(jMethodlog) 56 | Mat.(jMethodlog)(:,:,i)=iMat.(jMethodlog); 57 | else 58 | Mat.(jMethodlog)(:,:,:,i)=iMat.(jMethodlog); 59 | end 60 | end 61 | end 62 | 63 | updateResult(Resultfile,Mat,params); -------------------------------------------------------------------------------- /Calculation/mln_calcMatH2.m: -------------------------------------------------------------------------------- 1 | function mln_calcMatH2(Resultfile,VMethlog,lfp,params) 2 | 3 | %% to calculate the connectivity matrix for Mvar_based methods in Methlog 4 | % Methlog: 'MVAR': MVAR 5 | % Huifang Wang, June 8, 2012, Inserm U1106, Marseille 6 | Methlog=char(VMethlog{1}); 7 | NMlog=length(Methlog); 8 | if exist(Resultfile,'file') 9 | Rconnect=load(Resultfile); 10 | oddfieldname=fieldnames(Rconnect); 11 | if ~isempty(find(strncmpi(oddfieldname,Methlog,NMlog)==1,1))% if there is results about 'Methlog' 12 | % try to find the results with the same parameters 13 | Nmethlog=length(Rconnect.(Methlog)); 14 | for i=1:Nmethlog 15 | if mln_compareparams(Rconnect.(Methlog)(i).Params,params) 16 | %Net=Rconnect.(Methlog)(i); 17 | return; 18 | end 19 | end 20 | end 21 | end 22 | %% if there is not the result then calculate 23 | 24 | [Nchannel, Ntime]=size(lfp); 25 | 26 | if ~params.overlap==0 27 | overlap_p=params.wins*params.overlap; 28 | Nwindows=floor((Ntime-overlap_p)/(params.wins-overlap_p)); 29 | else 30 | overlap_p=0; 31 | Nwindows=floor(Ntime/params.wins); 32 | end 33 | % initialization 34 | Dmatt=[Nchannel,Nchannel,Nwindows]; 35 | NMeths=length(VMethlog); 36 | for i=1:NMeths 37 | iMeth=char(VMethlog{i}); 38 | if ~isempty(iMeth) 39 | if istimeM(iMeth) 40 | Mat.(iMeth)=zeros(Dmatt); 41 | else Mat.(iMeth)=zeros(Dmatf); 42 | end 43 | end 44 | end 45 | 46 | VMethodlog=fieldnames(Mat); 47 | Nmethod=length(VMethodlog); 48 | for i=1:Nwindows 49 | i_lfp=lfp(:,floor((i-1)*(params.wins-overlap_p)+1):floor(i*params.wins-(i-1)*overlap_p)); 50 | iMat=mln_icalcMatH2(i_lfp,params.MaxDelay,params.bins); 51 | for j=1:Nmethod 52 | jMethodlog=char(VMethodlog(j)); 53 | if istimeM(jMethodlog) 54 | Mat.(jMethodlog)(:,:,i)=iMat.(jMethodlog); 55 | else 56 | Mat.(jMethodlog)(:,:,:,i)=iMat.(jMethodlog); 57 | end 58 | end 59 | end 60 | 61 | updateResult(Resultfile,Mat,params); -------------------------------------------------------------------------------- /Calculation/mln_Result2file.m: -------------------------------------------------------------------------------- 1 | %% change the format of results 2 | % Huifang Wang Marseille 3 | 4 | function mln_Result2file(dirname,dataprenom,GroupMethlog) 5 | datafile=[dirname,'/data/',dataprenom,'.mat']; 6 | %GroupMethlog={'TimeBasic','FreqBasic','Hsquare','Granger','FreqAH','MutualInform'}; 7 | is3dimemsion=[1,0,1,1,0,1,1]; 8 | for igroup=1:length(GroupMethlog) 9 | Resultfile=[dirname,'/Results/',GroupMethlog{igroup},'_',dataprenom]; 10 | is3d=is3dimemsion(igroup); 11 | iNetSaved=load(Resultfile); 12 | fieldname=fieldnames(iNetSaved); 13 | for imethods=1:length(fieldname) 14 | Methlog=fieldname{imethods}; 15 | if strncmpi(Methlog,'Standard',8) 16 | continue; 17 | end 18 | 19 | if is3d 20 | Mat=iNetSaved.(Methlog).Mat; 21 | else 22 | NetCalcd=iNetSaved.(Methlog); 23 | Mat=squeeze(mean(abs(NetCalcd.Mat),3)); 24 | 25 | end 26 | NewStru.(Methlog)=Mat; 27 | 28 | end 29 | iParams=iNetSaved.(Methlog).Params; 30 | if igroup==1 31 | NewStru.Params=iParams; 32 | else 33 | NewStru.Params=updateP(NewStru.Params,iParams); 34 | end 35 | end 36 | 37 | load(datafile,'Connectivity'); 38 | Connectivity=mln_normalizeNet(Connectivity-diag(diag(Connectivity))); 39 | NewStru.Connectivity=Connectivity; 40 | filesaved=[dirname,'/ToutResults/Tout_',dataprenom]; 41 | save(filesaved,'-struct','NewStru') 42 | 43 | % delete the files 44 | % for igroup=1:length(GroupMethlog) 45 | % Resultfile=[dirname,'/Results/',GroupMethlog{igroup},'_',dataprenom,'.mat']; 46 | % delete(Resultfile); 47 | % end 48 | 49 | function NParams=updateP(S1,S2) 50 | fNames1 = fieldnames(S1); 51 | fNames2 = fieldnames(S2); 52 | diff = setdiff(fNames2,fNames1); 53 | NParams=S1; 54 | if isempty(diff) 55 | return; 56 | else 57 | numFields = length(diff); 58 | 59 | for i=1:numFields 60 | 61 | % get values for each struct for this field 62 | NParams.(diff{i})=S2.(diff{i}); 63 | 64 | end 65 | 66 | end 67 | 68 | 69 | -------------------------------------------------------------------------------- /Calculation/mln_Result2file.m~: -------------------------------------------------------------------------------- 1 | %% change the format of results 2 | % Huifang Wang Marseille 3 | 4 | function mln_Result2file(dirname,dataprenom,GroupMethlog) 5 | datafile=[dirname,'/data/',dataprenom,'.mat']; 6 | %GroupMethlog={'TimeBasic','FreqBasic','Hsquare','Granger','FreqAH','MutualInform'}; 7 | is3dimemsion=[1,0,1,1,0,1,1]; 8 | for igroup=1:length(GroupMethlog) 9 | Resultfile=[dirname,'/Results/',GroupMethlog{igroup},'_',dataprenom]; 10 | is3d=is3dimemsion(igroup); 11 | iNetSaved=load(Resultfile); 12 | fieldname=fieldnames(iNetSaved); 13 | for imethods=1:length(fieldname) 14 | Methlog=fieldname{imethods}; 15 | if strncmpi(Methlog,'Standard',8) 16 | continue; 17 | end 18 | 19 | if is3d 20 | Mat=iNetSaved.(Methlog).Mat; 21 | else 22 | NetCalcd=iNetSaved.(Methlog); 23 | Mat=squeeze(mean(abs(NetCalcd.Mat),3)); 24 | 25 | end 26 | NewStru.(Methlog)=Mat; 27 | 28 | end 29 | iParams=iNetSaved.(Methlog).Params; 30 | if igroup==1 31 | NewStru.Params=iParams; 32 | else 33 | NewStru.Params=updateP(NewStru.Params,iParams); 34 | end 35 | end 36 | 37 | load(datafile,'Connectivity'); 38 | Connectivity=normalizeNet(Connectivity-diag(diag(Connectivity))); 39 | NewStru.Connectivity=Connectivity; 40 | filesaved=[dirname,'/ToutResults/Tout_',dataprenom]; 41 | save(filesaved,'-struct','NewStru') 42 | 43 | % delete the files 44 | % for igroup=1:length(GroupMethlog) 45 | % Resultfile=[dirname,'/Results/',GroupMethlog{igroup},'_',dataprenom,'.mat']; 46 | % delete(Resultfile); 47 | % end 48 | 49 | function NParams=updateP(S1,S2) 50 | fNames1 = fieldnames(S1); 51 | fNames2 = fieldnames(S2); 52 | diff = setdiff(fNames2,fNames1); 53 | NParams=S1; 54 | if isempty(diff) 55 | return; 56 | else 57 | numFields = length(diff); 58 | 59 | for i=1:numFields 60 | 61 | % get values for each struct for this field 62 | NParams.(diff{i})=S2.(diff{i}); 63 | 64 | end 65 | 66 | end 67 | 68 | 69 | -------------------------------------------------------------------------------- /ClusterComputation/mln_CalEvaN.m~: -------------------------------------------------------------------------------- 1 | 2 | function mln_CalEvaN(dirname,prenom,strfile,paramsfile,nc,is,npts,cs,models) 3 | % Generate the data, calucate the connection methods by all given methods and evalution the results by AUC. 4 | % dirname: the folder to store all files 5 | % prenom: spectial name for new datasets 6 | % strfile: the file stores the structures 7 | % Paramsfile: the params used in the calucation 8 | %Examples: mln_CalEvaN nmm nmm GenerateData/structureN5L5 nmmParams 5 20 3000 1 nmm 9 | % dirname is the direction name which 10 | 11 | % Huifang Wang, Marseille, Nov 25, 2013, Calculate all 12 | % datasets, Get the AUC 13 | VGroupMethlog={'TimeBasic','FreqBasic','Hsquare','Granger','FreqAH','MutualInform','TE'}; 14 | 15 | if ~exist(dirname,'dir') 16 | mkdir(dirname); 17 | end 18 | datadir=[dirname,'/data']; 19 | if ~exist(datadir,'dir') 20 | mkdir(datadir); 21 | end 22 | Resultsdir=[dirname,'/Results']; 23 | if ~exist(Resultsdir,'dir') 24 | mkdir(Resultsdir); 25 | end 26 | Resultsdir=[dirname,'/ToutResults']; 27 | if ~exist(Resultsdir,'dir') 28 | mkdir(Resultsdir); 29 | end 30 | Resultsdir=[dirname,'/AUC']; 31 | if ~exist(Resultsdir,'dir') 32 | mkdir(Resultsdir); 33 | end 34 | 35 | %mln_generateParams(dirname); 36 | if exist([paramsfile,'.mat'],'file') 37 | strfile1=which([paramsfile,'.mat']); 38 | 39 | %strfilethere=['./',dirname,'/',strfile,'.mat']; 40 | 41 | copyfile (strfile1, ['./',dirname]); 42 | end 43 | 44 | is=str2double(is); 45 | nc=str2double(nc); 46 | npts=str2double(npts); 47 | cs=str2double(cs); 48 | switch models 49 | case 'nmm' 50 | dataname=mln_generate_nmm(is,nc,strfile,dirname,prenom,cs,npts); 51 | case 'fMRI' 52 | dataname=mln_generate_nmm(is,nc,strfile,dirname,prenom,cs,npts); 53 | case 'linear' 54 | dataname=mln_generate_linear(dirname,prename,npts,strfile,is,cs,1); 55 | case 'rossler' 56 | dataname=mln_generate_rossler(dirname,prename,npts,strfile,is,cs,0,0,1); 57 | case 'henon' 58 | dataname=mln_generate_henon(dirname,prename,npts,strfile,is,cs,0,0,1); 59 | end 60 | 61 | MULANCalMUltiBP(dirname,dataname,paramsfile,VGroupMethlog) 62 | mln_MethodStructuresAUC(dirname,dataname); 63 | -------------------------------------------------------------------------------- /Calculation/mln_calcMatGranger.m: -------------------------------------------------------------------------------- 1 | function mln_calcMatGranger(Resultfile,VMethlog,lfp,params) 2 | %% to calculate the connectivity matrix for Mvar_based methods in Methlog 3 | % Methlog: 'MVAR': MVAR 4 | % Huifang Wang, June 8, 2012, Inserm U1106, Marseille 5 | Methlog=char(VMethlog{1}); 6 | NMlog=length(Methlog); 7 | if exist(Resultfile,'file') 8 | Rconnect=load(Resultfile); 9 | 10 | oddfieldname=fieldnames(Rconnect); 11 | if ~isempty(find(strncmpi(oddfieldname,Methlog,NMlog)==1,1))% if there is results about 'Methlog' 12 | % try to find the results with the same parameters 13 | Nmethlog=length(Rconnect.(Methlog)); 14 | for i=1:Nmethlog 15 | if mln_compareparams(Rconnect.(Methlog)(i).Params,params) 16 | %Net=Rconnect.(Methlog)(i); 17 | return; 18 | end 19 | end 20 | end 21 | end 22 | %% if there is not the result then calculate 23 | 24 | [Nchannel, Ntime]=size(lfp); 25 | %Nfreq=length(params.freqs); 26 | 27 | if ~params.overlap==0 28 | overlap_p=params.wins*params.overlap; 29 | Nwindows=floor((Ntime-overlap_p)/(params.wins-overlap_p)); 30 | else 31 | overlap_p=0; 32 | Nwindows=floor(Ntime/params.wins); 33 | end 34 | % initialization 35 | Dmatt=[Nchannel,Nchannel,Nwindows]; 36 | %Dmatf=[Nchannel,Nchannel,Nfreq,Nwindows]; 37 | NMeths=length(VMethlog); 38 | for i=1:NMeths 39 | iMeth=char(VMethlog{i}); 40 | if ~isempty(iMeth) 41 | if istimeM(iMeth) 42 | Mat.(iMeth)=zeros(Dmatt); 43 | else Mat.(iMeth)=zeros(Dmatf); 44 | end 45 | end 46 | end 47 | 48 | VMethodlog=fieldnames(Mat); 49 | Nmethod=length(VMethodlog); 50 | for i=1:Nwindows 51 | display([num2str(i) '/' num2str(Nwindows) '...']); 52 | i_lfp=lfp(:,floor((i-1)*(params.wins-overlap_p)+1):floor(i*params.wins-(i-1)*overlap_p)); 53 | iMat=mln_icalcMatGranger(i_lfp,params.modelOrder); 54 | for j=1:Nmethod 55 | jMethodlog=char(VMethodlog(j)); 56 | if istimeM(jMethodlog) 57 | Mat.(jMethodlog)(:,:,i)=iMat.(jMethodlog); 58 | else 59 | Mat.(jMethodlog)(:,:,:,i)=iMat.(jMethodlog); 60 | end 61 | end 62 | end 63 | 64 | updateResult(Resultfile,Mat,params); -------------------------------------------------------------------------------- /Calculation/mln_calcMatMvar.m: -------------------------------------------------------------------------------- 1 | function mln_calcMatMvar(Resultfile,VMethlog,lfp,params) 2 | %% to calculate the connectivity matrix for Mvar_based methods in Methlog 3 | % Methlog: 'MVAR': MVAR 4 | % Huifang Wang, May 28, 2012, Inserm U1106, Marseille 5 | Methlog=char(VMethlog{1}); 6 | NMlog=length(Methlog); 7 | if exist(Resultfile,'file') 8 | Rconnect=load(Resultfile); 9 | oddfieldname=fieldnames(Rconnect); 10 | if ~isempty(find(strncmpi(oddfieldname,Methlog,NMlog)==1,1))% if there is results about 'Methlog' 11 | % try to find the results with the same parameters 12 | Nmethlog=length(Rconnect.(Methlog)); 13 | for i=1:Nmethlog 14 | if mln_compareparams(Rconnect.(Methlog)(i).Params,params) 15 | %Net=Rconnect.(Methlog)(i); 16 | return; 17 | end 18 | end 19 | end 20 | end 21 | %% if there is not the result then calculate 22 | 23 | [Nchannel, Ntime]=size(lfp); 24 | freqs=params.minfreq:params.stepfreq:params.maxfreq; 25 | Nfreq=length(freqs); 26 | 27 | if ~params.overlap==0 28 | overlap_p=params.wins*params.overlap; 29 | Nwindows=floor((Ntime-overlap_p)/(params.wins-overlap_p)); 30 | else 31 | overlap_p=0; 32 | Nwindows=floor(Ntime/params.wins); 33 | end 34 | % initialization 35 | Dmatf=[Nchannel,Nchannel,Nfreq,Nwindows]; 36 | NMeths=length(VMethlog); 37 | for i=1:NMeths 38 | iMeth=char(VMethlog{i}); 39 | if ~isempty(iMeth) 40 | Mat.(iMeth)=zeros(Dmatf); 41 | if strncmpi(VMethlog{i},'MVAR',4) || strncmpi(VMethlog{i},'AS',2) 42 | Mat.(iMeth)=zeros([Nchannel,Nchannel,Nwindows]); 43 | end 44 | end 45 | end 46 | 47 | VMethodlog=fieldnames(Mat); 48 | Nmethod=length(VMethodlog); 49 | %%% calculate 50 | for i=1:Nwindows 51 | i_lfp=lfp(:,floor((i-1)*(params.wins-overlap_p)+1):floor(i*params.wins-(i-1)*overlap_p)); 52 | iMat=mln_icalcMatMvar(i_lfp',params.modelOrder,freqs,params.fs); 53 | for j=1:Nmethod 54 | if strncmpi(VMethodlog{j},'MVAR',4) || strncmpi(VMethodlog{j},'AS',2) 55 | Mat.(char(VMethodlog(j)))(:,:,i)=iMat.(char(VMethodlog(j))); 56 | else 57 | Mat.(char(VMethodlog(j)))(:,:,:,i)=iMat.(char(VMethodlog(j))); 58 | end 59 | end 60 | end 61 | 62 | updateResult(Resultfile,Mat,params); 63 | % if nargout>0 64 | % varargout=Mat; 65 | % end -------------------------------------------------------------------------------- /Calculation/mln_calcMatMvar.m~: -------------------------------------------------------------------------------- 1 | function mln_calcMatMvar(Resultfile,VMethlog,lfp,params) 2 | %% to calculate the connectivity matrix for Mvar_based methods in Methlog 3 | % Methlog: 'MVAR': MVAR 4 | % Huifang Wang, May 28, 2012, Inserm U1106, Marseille 5 | Methlog=char(VMethlog{1}); 6 | NMlog=length(Methlog); 7 | if exist(Resultfile,'file') 8 | Rconnect=load(Resultfile); 9 | oddfieldname=fieldnames(Rconnect); 10 | if ~isempty(find(strncmpi(oddfieldname,Methlog,NMlog)==1,1))% if there is results about 'Methlog' 11 | % try to find the results with the same parameters 12 | Nmethlog=length(Rconnect.(Methlog)); 13 | for i=1:Nmethlog 14 | if mln_compareparams(Rconnect.(Methlog)(i).Params,params) 15 | %Net=Rconnect.(Methlog)(i); 16 | return; 17 | end 18 | end 19 | end 20 | end 21 | %% if there is not the result then calculate 22 | 23 | [Nchannel, Ntime]=size(lfp); 24 | freqs=params.minfreq:params.stepfreq:params.maxfreq; 25 | Nfreq=length(freqs); 26 | 27 | if ~params.overlap==0 28 | overlap_p=params.wins*params.overlap; 29 | Nwindows=floor((Ntime-overlap_p)/(params.wins-overlap_p)); 30 | else 31 | overlap_p=0; 32 | Nwindows=floor(Ntime/params.wins); 33 | end 34 | % initialization 35 | Dmatf=[Nchannel,Nchannel,Nfreq,Nwindows]; 36 | NMeths=length(VMethlog); 37 | for i=1:NMeths 38 | iMeth=char(VMethlog{i}); 39 | if ~isempty(iMeth) 40 | Mat.(iMeth)=zeros(Dmatf); 41 | if strncmpi(VMethlog{i},'MVAR',4) || strncmpi(VMethlog{i},'AS',2) 42 | Mat.(iMeth)=zeros([Nchannel,Nchannel,Nwindows]); 43 | end 44 | end 45 | end 46 | 47 | VMethodlog=fieldnames(Mat); 48 | Nmethod=length(VMethodlog); 49 | %%% calculate 50 | for i=1:Nwindows 51 | i_lfp=lfp(:,floor((i-1)*(params.wins-overlap_p)+1):floor(i*params.wins-(i-1)*overlap_p)); 52 | iMat=mln_icalcMatMvar(i_lfp',params.modelOrder,freqs,params.fs); 53 | for j=1:Nmethod 54 | if strncmpi(VMethodlog{j},'MVAR',4) || strncmpi(VMethodlog{j},'AS',2) 55 | Mat.(char(VMethodlog(j)))(:,:,i)=iMat.(char(VMethodlog(j))); 56 | else 57 | Mat.(char(VMethodlog(j)))(:,:,:,i)=iMat.(char(VMethodlog(j))); 58 | end 59 | end 60 | end 61 | 62 | updateResult(Resultfile,Mat,params); 63 | % if nargout>0 64 | % varargout=Mat; 65 | % end -------------------------------------------------------------------------------- /Interface/mln_statesplot.m: -------------------------------------------------------------------------------- 1 | function mln_statesplot(lfp,Params,delay) 2 | Nchan=size(lfp,1); 3 | %% if Number of channels is larger than 6, we divided the figures with each 4 | %% one less or equals 6x6 5 | NumberChanforPage=6; 6 | Npage=(floor(Nchan/NumberChanforPage)+1); 7 | if isempty(find(strncmpi(fieldnames(Params),'str',3)==1,1)); 8 | str=1:Nchan; 9 | else 10 | str=Params.str; 11 | end 12 | if Nchan>NumberChanforPage 13 | for ipage=1:Npage 14 | if ipage==Npage 15 | ichanV=(ipage-1)*NumberChanforPage+1:Nchan; 16 | 17 | else 18 | ichanV=(ipage-1)*NumberChanforPage+1:ipage*NumberChanforPage; 19 | end 20 | istr=str(ichanV); 21 | for jpage=1:Npage 22 | hf=figure('name',['States plot for ', num2str(delay), ' time delay in Page ',num2str(ipage), ' , ',num2str(jpage)]); 23 | 24 | if jpage==Npage 25 | jchanV=(jpage-1)*NumberChanforPage+1:Nchan; 26 | else 27 | jchanV=(jpage-1)*NumberChanforPage+1:jpage*NumberChanforPage; 28 | end 29 | jstr=str(jchanV); 30 | plotstatesplot(hf,ichanV,jchanV,istr,jstr,lfp,delay) 31 | end 32 | end 33 | else 34 | hf=figure('name',['States plot for ', num2str(delay), 'time delay ']); 35 | istr=str; 36 | jstr=str; 37 | ichanV=1:Nchan; 38 | plotstatesplot(hf,ichanV,ichanV,istr,jstr,lfp,delay) 39 | 40 | end 41 | 42 | 43 | %for idelay=0:NSP 44 | function plotstatesplot(hf,ichanV,jchanV,istr,jstr,lfp,idelay) 45 | Nchan=max(length(ichanV),length(jchanV)); 46 | for i=1:length(ichanV) 47 | ilfp=lfp(ichanV(i),idelay+1:end); 48 | for j=1:length(jchanV) 49 | 50 | jlfp=lfp(jchanV(j),1:end-idelay); 51 | subplot(Nchan,Nchan,(i-1)*Nchan+j,'parent',hf); 52 | plot(ilfp,jlfp,'b.'); 53 | axis equal; 54 | if i==1 55 | if isempty(jstr) 56 | title(['C',num2str(jchanV(j))]); 57 | else 58 | title(jstr(j)); 59 | end 60 | end 61 | if j==1 62 | if isempty(istr) 63 | ylabel(['C',num2str(ichanV(i))]); 64 | else 65 | ylabel(istr(i)); 66 | end 67 | end 68 | end 69 | end 70 | %end 71 | 72 | 73 | 74 | 75 | -------------------------------------------------------------------------------- /Calculation/mln_icalcMatTE.m: -------------------------------------------------------------------------------- 1 | function Mat=mln_icalcMatTE(lfp,maxlag) 2 | %% this function is used to calculate the Transfer Entropy with time 3 | %% delay 4 | % Nov, 13, Huifang Wang Marseille based on Andrea Brovelli's code 5 | 6 | [nchan,lengthx]=size(lfp); 7 | BTED=zeros(nchan,nchan,maxlag); 8 | 9 | 10 | for tau=1:maxlag; 11 | 12 | ind_tx=[tau+1:lengthx]'; 13 | ind_tx=repmat(ind_tx, [1, tau+1]) - repmat( [0:tau], [lengthx-tau 1]); 14 | for ichan=1:nchan; 15 | for jchan=ichan+1:nchan; 16 | [BTED(jchan,ichan,tau),BTED(ichan,jchan,tau)]=cal_te_xy(lfp(ichan,:),lfp(jchan,:),ind_tx); 17 | 18 | end 19 | end 20 | end 21 | Mat.BTED=max(BTED,[],3); 22 | Mat.BTEU=max(Mat.BTED,Mat.BTED');%% updated Huifang Dec, 13, 2012 23 | Mat.PTED=mln_Dir2Partial(Mat.BTED+eye(size(Mat.BTED))); 24 | Mat.PTEU=mln_Dir2Partial(Mat.BTEU+eye(size(Mat.BTEU))); 25 | 26 | %% subfunction 27 | function [texy, teyx]=cal_te_xy(sx,sy,ind_tx) 28 | 29 | x=squeeze(sx(1,ind_tx)); 30 | y=squeeze(sy(1,ind_tx)); 31 | sizetx=size(ind_tx); 32 | x = reshape(x, sizetx); 33 | y = reshape(y, sizetx); 34 | 35 | 36 | % ---From Andrea Brovelli------------------------------------------------------------------ 37 | % TE( x -> y ) 38 | % --------------------------------------------------------------------- 39 | % Conditional Entropy Hycy: H(Y_i+1|Y_i) = H(Y_i+1) - H(Y_i) 40 | det_yi1 = det(cov(y)); 41 | det_yi = det(cov(y(:,2:end))); 42 | Hycy = log(det_yi1) - log(det_yi); 43 | % Conditional Entropy Hycx: H(Y_i+1|Y_i,Y_i) 44 | det_yxi1 = det(cov([ y x(:,2:end) ])); 45 | det_yxi = det(cov([ y(:,2:end) x(:,2:end) ])); 46 | Hycx = log(det_yxi1) - log(det_yxi); 47 | % Transfer Entropy x -> y 48 | texy = Hycy - Hycx; 49 | 50 | % --------------------------------------------------------------------- 51 | % TE( y -> x ) 52 | % --------------------------------------------------------------------- 53 | % Conditional Entropy Hxcx: H(X_i+1|X_i) = H(X_i+1) - H(X_i) 54 | det_xi1 = det(cov(x)); 55 | det_xi = det(cov(x(:,2:end))); 56 | Hxcx = log(det_xi1) - log(det_xi); 57 | % Conditional Entropy Hxcy: H(X_i+1|X_i,Y_i) 58 | det_xyi1 = det(cov([x y(:,2:end) ])); 59 | det_xyi = det(cov([x(:,2:end) y(:,2:end) ])); 60 | Hxcy = log(det_xyi1) - log(det_xyi); 61 | % Transfer Entropy y -> x 62 | teyx = Hxcx - Hxcy; 63 | -------------------------------------------------------------------------------- /ClusterComputation/mln_CalEvaN.m: -------------------------------------------------------------------------------- 1 | 2 | function mln_CalEvaN(dirname,prenom,strfile,paramsfile,nc,is,npts,cs,models) 3 | % Generate the data, calucate the connection methods by all given methods and evalution the results by AUC. 4 | % dirname: the folder to store all files 5 | % prenom: spectial name for new datasets 6 | % strfile: the file stores the structures 7 | % Paramsfile: the params used in the calucation 8 | % nc: the channels of data 9 | % is: which structure stored in the structure file 10 | % npts: length of data 11 | % cs: the connection strength 12 | % models: 'nmm','fMRI','linear','rossler', 'henon' 13 | 14 | %Examples: mln_CalEvaN nmm nmm GenerateData/structureN5L5 nmmParams 5 20 3000 1 nmm 15 | % dirname is the direction name which 16 | 17 | % Huifang Wang, Marseille, Nov 25, 2013, Calculate all 18 | % datasets, Get the AUC 19 | VGroupMethlog={'TimeBasic','FreqBasic','Hsquare','Granger','FreqAH','MutualInform','TE'}; 20 | 21 | if ~exist(dirname,'dir') 22 | mkdir(dirname); 23 | end 24 | datadir=[dirname,'/data']; 25 | if ~exist(datadir,'dir') 26 | mkdir(datadir); 27 | end 28 | Resultsdir=[dirname,'/Results']; 29 | if ~exist(Resultsdir,'dir') 30 | mkdir(Resultsdir); 31 | end 32 | Resultsdir=[dirname,'/ToutResults']; 33 | if ~exist(Resultsdir,'dir') 34 | mkdir(Resultsdir); 35 | end 36 | Resultsdir=[dirname,'/AUC']; 37 | if ~exist(Resultsdir,'dir') 38 | mkdir(Resultsdir); 39 | end 40 | 41 | %mln_generateParams(dirname); 42 | if exist([paramsfile,'.mat'],'file') 43 | strfile1=which([paramsfile,'.mat']); 44 | 45 | %strfilethere=['./',dirname,'/',strfile,'.mat']; 46 | 47 | copyfile (strfile1, ['./',dirname]); 48 | end 49 | 50 | is=str2double(is); 51 | nc=str2double(nc); 52 | npts=str2double(npts); 53 | cs=str2double(cs); 54 | switch models 55 | case 'nmm' 56 | dataname=mln_generate_nmm(is,nc,strfile,dirname,prenom,cs,npts); 57 | case 'fMRI' 58 | dataname=mln_generate_fMRI(is,nc,strfile,dirname,prenom,cs,npts); 59 | case 'linear' 60 | dataname=mln_generate_linear(dirname,prename,npts,strfile,is,cs,1); 61 | case 'rossler' 62 | dataname=mln_generate_rossler(dirname,prename,npts,strfile,is,cs,0,0,1); 63 | case 'henon' 64 | dataname=mln_generate_henon(dirname,prename,npts,strfile,is,cs,0,0,1); 65 | end 66 | 67 | MULANCalMUltiBP(dirname,dataname,paramsfile,VGroupMethlog) 68 | mln_MethodStructuresAUC(dirname,dataname); 69 | -------------------------------------------------------------------------------- /GenerateData/spm_ssr_priors.m: -------------------------------------------------------------------------------- 1 | function [pE,pC] = spm_ssr_priors(pE,pC) 2 | % augments prior moments of a neural mass model for ssr analyses 3 | % FORMAT [pE,pC] = spm_ssr_priors(pE,pC) 4 | % 5 | % pE - prior expectation 6 | % 7 | % adds 8 | % 9 | % input and noise parameters 10 | %-------------------------------------------------------------------------- 11 | % pE.a - amplitude of AR component 12 | % pE.b - amplitude of IID component 13 | % pE.c - amplitude of AR noise (channel specific and non-specific) 14 | % pE.d - amplitude of IID noise (channel specific and non-specific) 15 | % 16 | %-------------------------------------------------------------------------- 17 | % 18 | % pC - prior (co)variances 19 | % 20 | % Because priors are specified under log normal assumptions, most 21 | % parameters are simply scaling coefficients with a prior expectation 22 | % and variance of one. After log transform this renders pE = 0 and 23 | % pC = 1; The prior expectations of what they scale are specified in 24 | % spm_lfp_fx 25 | %__________________________________________________________________________ 26 | % 27 | % David O, Friston KJ (2003) A neural mass model for MEG/EEG: coupling and 28 | % neuronal dynamics. NeuroImage 20: 1743-1755 29 | %__________________________________________________________________________ 30 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 31 | 32 | % Karl Friston 33 | % $Id: spm_ssr_priors.m 4402 2011-07-21 12:37:24Z karl $ 34 | 35 | % catch 36 | %-------------------------------------------------------------------------- 37 | try, pE.L; catch, pE.L = 1; end 38 | 39 | % number of LFP channels 40 | %-------------------------------------------------------------------------- 41 | if size(pE.L,1) == 1, n = size(pE.L,2); else, n = 1; end 42 | if size(pE.C,1), m = size(pE.C,2); else, m = 1; end 43 | 44 | % add prior on spectral density of innovations (pink and white coeficients) 45 | %-------------------------------------------------------------------------- 46 | pE.a = sparse(2,m); pC.a = sparse(2,m) + 1/16; % neuronal innovations 47 | pE.b = sparse(2,1); pC.b = sparse(2,1) + 1/16; % channel noise non-specific 48 | pE.c = sparse(2,n); pC.c = sparse(2,n) + 1/16; % channel noise specific 49 | 50 | % neuronal innovations 51 | %-------------------------------------------------------------------------- 52 | pE.d = sparse(4,m); pC.d = sparse(4,m) + 1/32; 53 | 54 | 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /GenerateData/spm_unvec.m: -------------------------------------------------------------------------------- 1 | function [varargout] = spm_unvec(vX,varargin) 2 | % unvectorises a vectorised array 3 | % FORMAT [varargout] = spm_unvec(vX,varargin); 4 | % varargin - numeric, cell or structure array 5 | % vX - spm_vec(X) 6 | % 7 | % i.e. X = spm_unvec(spm_vec(X),X) 8 | % [X1,X2,...] = spm_unvec(spm_vec(X1,X2,...),X1,X2,...) 9 | % 10 | % see spm_vec 11 | %__________________________________________________________________________ 12 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 13 | 14 | % Karl Friston 15 | % $Id: spm_unvec.m 5701 2013-10-17 15:13:45Z guillaume $ 16 | 17 | % deal to multiple outputs if necessary 18 | %-------------------------------------------------------------------------- 19 | if nargout > 1 20 | varargout = spm_unvec(vX,varargin); 21 | return 22 | end 23 | if length(varargin) == 1 24 | X = varargin{1}; 25 | else 26 | X = varargin; 27 | end 28 | 29 | % vectorise first argument 30 | %-------------------------------------------------------------------------- 31 | vX = spm_vec(vX); 32 | 33 | % reshape numerical arrays 34 | %-------------------------------------------------------------------------- 35 | if isnumeric(X) || islogical(X) 36 | if ndims(X) > 2 37 | X(:) = full(vX); 38 | else 39 | X(:) = vX; 40 | end 41 | varargout = {X}; 42 | return 43 | end 44 | 45 | % fill in structure arrays 46 | %-------------------------------------------------------------------------- 47 | if isstruct(X) 48 | f = fieldnames(X); 49 | for i = 1:length(f) 50 | c = {X.(f{i})}; 51 | if isnumeric(c) 52 | n = numel(c); 53 | else 54 | n = length(spm_vec(c)); 55 | end 56 | c = spm_unvec(vX(1:n),c); 57 | [X.(f{i})] = deal(c{:}); 58 | vX = vX(n + 1:end); 59 | end 60 | varargout = {X}; 61 | return 62 | end 63 | 64 | % fill in cell arrays 65 | %-------------------------------------------------------------------------- 66 | if iscell(X) 67 | for i = 1:numel(X) 68 | if isnumeric(X{i}) 69 | n = numel(X{i}); 70 | else 71 | n = length(spm_vec(X{i})); 72 | end 73 | X{i} = spm_unvec(vX(1:n),X{i}); 74 | vX = vX(n + 1:end); 75 | end 76 | varargout = {X}; 77 | return 78 | end 79 | 80 | % else 81 | %-------------------------------------------------------------------------- 82 | X = []; 83 | varargout = {X}; 84 | -------------------------------------------------------------------------------- /Interface/mln_Result2fileSV.m: -------------------------------------------------------------------------------- 1 | %% change the format of results 2 | % Huifang Wang Marseille 3 | % single file for choose GroupMethlog 4 | function filesaved=mln_Result2fileSV(dirname,dataprenom,GroupMethlog) 5 | datafile=[dirname,'/data/',dataprenom]; 6 | %GroupMethlog={'TimeBasic','FreqBasic','Hsquare','Granger','FreqAH','MutualInform'}; 7 | 8 | for igroup=1:length(GroupMethlog) 9 | Resultfile=[dirname,'/Results/',GroupMethlog{igroup},'_',dataprenom]; 10 | inameGroup=GroupMethlog{igroup}; 11 | iNetSaved=load(Resultfile); 12 | fieldname=fieldnames(iNetSaved); 13 | for imethods=1:length(fieldname) 14 | Methlog=fieldname{imethods}; 15 | if strncmpi(Methlog,'Standard',8) 16 | continue; 17 | end 18 | 19 | if is3dGroup(inameGroup) 20 | Mat=iNetSaved.(Methlog).Mat; 21 | else 22 | NetCalcd=iNetSaved.(Methlog); 23 | Mat=squeeze(mean(abs(NetCalcd.Mat),3)); 24 | 25 | end 26 | NewStru.(Methlog)=Mat; 27 | 28 | end 29 | iParams=iNetSaved.(Methlog).Params; 30 | if igroup==1 31 | NewStru.Params=iParams; 32 | else 33 | NewStru.Params=updateP(NewStru.Params,iParams); 34 | end 35 | end 36 | 37 | load(datafile,'Connectivity'); 38 | Connectivity=mln_normalizeNet(Connectivity-diag(diag(Connectivity))); 39 | NewStru.Connectivity=Connectivity; 40 | datadir=[dirname,'/ToutResults']; 41 | if ~exist(datadir,'dir') 42 | mkdir(datadir); 43 | end 44 | filesaved=[datadir,'/Tout_',dataprenom]; 45 | 46 | save(filesaved,'-struct','NewStru') 47 | 48 | % delete the files 49 | % for igroup=1:length(GroupMethlog) 50 | % Resultfile=[dirname,'/Results/',GroupMethlog{igroup},'_',dataprenom,'.mat']; 51 | % delete(Resultfile); 52 | % end 53 | 54 | function NParams=updateP(S1,S2) 55 | fNames1 = fieldnames(S1); 56 | fNames2 = fieldnames(S2); 57 | diff = setdiff(fNames2,fNames1); 58 | NParams=S1; 59 | if isempty(diff) 60 | return; 61 | else 62 | numFields = length(diff); 63 | 64 | for i=1:numFields 65 | 66 | % get values for each struct for this field 67 | NParams.(diff{i})=S2.(diff{i}); 68 | 69 | end 70 | 71 | end 72 | 73 | function is3d=is3dGroup(inameGroup) 74 | is3d=1; 75 | NMlog=length(inameGroup); 76 | is4dVector={'FreqBasic','FreqAH'}; 77 | N4d=length(is4dVector); 78 | for i4d=1:N4d 79 | if ~isempty(find(strncmpi(is4dVector,inameGroup,NMlog)==1,1)) 80 | is3d=0; 81 | return; 82 | end 83 | end 84 | 85 | -------------------------------------------------------------------------------- /Calculation/mln_icalcMatMITime.m: -------------------------------------------------------------------------------- 1 | function Mat=icalcMatMITime(lfp,params) 2 | %% this function is used to calculate the mutual Inforamtion with time 3 | %% delay 4 | % June, 12, Huifang Wang Marseille 5 | maxlag=params.MaxDelay; 6 | bins=params.bins; 7 | 8 | 9 | [nchan,ntime]=size(lfp); 10 | BMITD2=zeros(nchan,nchan,maxlag+1); 11 | BMITD1=zeros(nchan,nchan,maxlag+1); 12 | 13 | for tau=0:maxlag; 14 | for ichan=1:nchan; 15 | for jchan=1:nchan; 16 | P2=hist2xy(lfp(ichan,:),lfp(jchan,:),bins,tau); 17 | P1x=sum(P2,2); % distribution for x 18 | P1y=sum(P2,1); % distribution for y 19 | %% compute the mutual information 20 | I1=[-sum((P1x(P1x~=0)).*log(P1x(P1x~=0))), -sum((P1y(P1y~=0)).*log(P1y(P1y~=0)))]; % entropies of Px and Py 21 | I2=-sum(P2(P2~=0).*log(P2(P2~=0))); % entropy of joint distribution Pxy 22 | I2_syserr=(length(P1x(P1x~=0))+length(P1y(P1y~=0))-length(P2(P2~=0).*log(P2(P2~=0)))-1)/(2*ntime); % standard error for estimation of entropy 23 | BMITD2(jchan,ichan,tau+1)=I1(1)+I1(2)-I2+I2_syserr; 24 | BMITD1(jchan,ichan,tau+1)=I1(1)+I1(2)-I2; 25 | %% different way to calculate the mutual information 26 | %P1x1y=P1x*P1y+eps.*ones(bins); 27 | %MI2=sum(sum(P2.*logw0(P2./P1x1y))); 28 | end 29 | end 30 | end 31 | Mat.BMITD2=max(BMITD2,[],3)/log(bins); 32 | Mat.BMITD1=max(BMITD1,[],3)/log(bins); 33 | Mat.BMITU=max(Mat.BMITD1,Mat.BMITD1');%% updated Huifang Dec, 13, 2012 34 | Mat.PMITD2=mln_Dir2Partial(Mat.BMITD2); 35 | Mat.PMITD1=mln_Dir2Partial(Mat.BMITD1); 36 | Mat.PMITU=mln_Dir2Partial(Mat.BMITU); 37 | 38 | %% subfunction 39 | function pxy=hist2xy(x,y,nbin,tau) 40 | % normalise the value range to [0 1) 41 | x1 = (x - min(x)) / max(x - min(x)) - eps; 42 | y1 = (y - min(y)) / max(y - min(y)) - eps; 43 | 44 | % this is the smart trick from CRP Toolbox:mi; main trick: put the first data to values [1:1:nbin] and the second data to [nbin:nbin:nbin^2] 45 | temp = fix(x1(1:(end-tau)) * nbin) + (fix(y1((tau+1):end) * nbin)) * nbin; 46 | 47 | % call Matlab histc function (faster than hist) 48 | p=histc(temp,0:(nbin^2-1))'; 49 | pxy=reshape(p,nbin,nbin)/length(x); 50 | % function y=logw0(x) 51 | % y=x; 52 | % nx=size(x,1); 53 | % for i=1:nx 54 | % for j=1:nx 55 | % if x(i,j)==0 56 | % y(i,j)=0; 57 | % else 58 | % y(i,j)=log(x(i,j)); 59 | % end 60 | % end 61 | % end 62 | -------------------------------------------------------------------------------- /GenerateData/mln_generate_nmm.m~: -------------------------------------------------------------------------------- 1 | % Huifang Wang For nmm Structure cluster Version 2 | % related to the structures and pink noise 3 | % Karl Friston 4 | % $Id: spm_csd_demo.m 4402 2011-07-21 12:37:24Z karl $ 5 | function dataname=mln_generate_nmm(is,nc,strfile,dirname,prename,cs,N) 6 | 7 | dataname=[prename,'nmmCS',num2str(100*cs),'S',num2str(is)]; 8 | filename=['./',dirname,'/data/',dataname,'.mat']; 9 | [cdata] = imread('MULANLOGO.png'); 10 | if exist(filename,'file') 11 | 12 | msgbox('Operation Completed','Success','custom',cdata); 13 | else 14 | 15 | % number of sources and LFP channels (usually the same) 16 | %-------------------------------------------------------------------------- 17 | n = nc; % number of sources 18 | % CS=1; 19 | % specify network (connections) 20 | %-------------------------------------------------------------------------- 21 | A{1}=zeros(n); %A{1} = tril(ones(n,n),-1); % a forward connection 22 | A{2} = zeros(n);%triu(ones(n,n),+1); % a backward connection 23 | A{3} = sparse(n,n); % lateral connections 24 | B = {}; % trial-specific modulation 25 | C = speye(n,n); % sources receiving innovations 26 | 27 | % get priors 28 | %-------------------------------------------------------------------------- 29 | [pE,pC] = spm_lfp_priors(A,B,C); % neuronal priors 30 | [pE,pC] = spm_ssr_priors(pE,pC); % spectral priors 31 | [pE,pC] = spm_L_priors(n,pE,pC); % spatial priors 32 | 33 | % create LFP model 34 | %-------------------------------------------------------------------------- 35 | M.IS = 'spm_lfp_mtf'; 36 | M.FS = 'spm_lfp_sqrt'; 37 | M.f = 'spm_fx_lfp'; 38 | M.g = 'spm_gx_erp'; 39 | M.x = sparse(n,13); 40 | M.n = n*13; 41 | M.pE = pE; 42 | M.pC = pC; 43 | M.m = n; 44 | M.l = nc; 45 | M.Hz = [1:64]'; 46 | 47 | 48 | 49 | % or generate data 50 | %========================================================================== 51 | 52 | % Integrate with pink noise process 53 | %-------------------------------------------------------------------------- 54 | 55 | U.dt = 8/1000; 56 | U.u = randn(N,M.m)/100; 57 | %U.u=zeros(N,M.m)/16; 58 | U.u = sqrt(spm_Q(1/16,N))*U.u; 59 | 60 | load(strfile,'PGS'); 61 | %=============================================================== 62 | P = pE; 63 | Astru=PGS{is}; 64 | SparseA=sparse(Astru(1,:),Astru(2,:),1); 65 | P.A{1}=full(SparseA); 66 | P.A{1}(nc,nc)=0; 67 | P.A{1}=P.A{1}.*cs; 68 | 69 | 70 | LFP = spm_int_L(P,M,U); 71 | LFP=LFP'; 72 | Params.fs=1000/8; 73 | Connectivity=P.A{1}; 74 | Connectivity(Connectivity<0)=0; 75 | 76 | save(filename,'LFP','Connectivity','Params'); 77 | msgbox('Operation Completed','Success','custom',cdata); 78 | 79 | end 80 | 81 | -------------------------------------------------------------------------------- /GenerateData/spm_gx_fmri.m: -------------------------------------------------------------------------------- 1 | function [g,dgdx] = spm_gx_fmri(x,u,P,M) 2 | % Simulated BOLD response to input 3 | % FORMAT [g,dgdx] = spm_gx_fmri(x,u,P,M) 4 | % g - BOLD response (%) 5 | % x - state vector (see spm_fx_dcm) 6 | % P - Parameter vector (see spm_fx_dcm) 7 | % M - model specification structure (see spm_nlsi) 8 | %__________________________________________________________________________ 9 | % 10 | % This function implements the BOLD signal model described in: 11 | % 12 | % Stephan KE, Weiskopf N, Drysdale PM, Robinson PA, Friston KJ (2007) 13 | % Comparing hemodynamic models with DCM. NeuroImage 38: 387-401. 14 | %__________________________________________________________________________ 15 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 16 | 17 | % Karl Friston & Klaas Enno Stephan 18 | % $Id: spm_gx_fmri.m 5667 2013-10-02 18:26:06Z karl $ 19 | 20 | 21 | % Biophysical constants for 1.5T 22 | %========================================================================== 23 | 24 | % time to echo (TE) (default 0.04 sec) 25 | %-------------------------------------------------------------------------- 26 | TE = 0.04; 27 | 28 | % resting venous volume (%) 29 | %-------------------------------------------------------------------------- 30 | V0 = 4; 31 | 32 | % estimated region-specific ratios of intra- to extra-vascular signal 33 | %-------------------------------------------------------------------------- 34 | ep = exp(P.epsilon); 35 | 36 | % slope r0 of intravascular relaxation rate R_iv as a function of oxygen 37 | % saturation S: R_iv = r0*[(1 - S)-(1 - S0)] (Hz) 38 | %-------------------------------------------------------------------------- 39 | r0 = 25; 40 | 41 | % frequency offset at the outer surface of magnetized vessels (Hz) 42 | %-------------------------------------------------------------------------- 43 | nu0 = 40.3; 44 | 45 | % resting oxygen extraction fraction 46 | %-------------------------------------------------------------------------- 47 | E0 = 0.4; 48 | 49 | %-Coefficients in BOLD signal model 50 | %========================================================================== 51 | k1 = 4.3*nu0*E0*TE; 52 | k2 = ep*r0*E0*TE; 53 | k3 = 1 - ep; 54 | 55 | %-Output equation of BOLD signal model 56 | %========================================================================== 57 | v = exp(x(:,4)); 58 | q = exp(x(:,5)); 59 | g = V0*(k1 - k1.*q + k2 - k2.*q./v + k3 - k3.*v); 60 | 61 | if nargout == 1, return, end 62 | 63 | 64 | %-derivative dgdx 65 | %========================================================================== 66 | [n m] = size(x); 67 | dgdx = cell(1,m); 68 | [dgdx{:}] = deal(sparse(n,n)); 69 | dgdx{1,4} = diag(-V0*(k3.*v - k2.*q./v)); 70 | dgdx{1,5} = diag(-V0*(k1.*q + k2.*q./v)); 71 | dgdx = spm_cat(dgdx); 72 | -------------------------------------------------------------------------------- /Evaluation/mln_showAUC.m~: -------------------------------------------------------------------------------- 1 | %% show the results 2 | % show the AUC array for varying the number of windows 3 | function mln_showAUC 4 | load('ExAUCnmmN5L5.mat','AUCall','Informa') 5 | colormapnowall=colormap(lines); 6 | cs=Informa.cs; 7 | is=Informa.is; 8 | model=Informa.model; 9 | dcs=60; 10 | struct='N5L5'; 11 | dirname=['/Volumes/HWMac1/MULANpre/',struct,'S/',model]; 12 | prenom=[model,struct]; 13 | 14 | 15 | shownMethods={'BCohF','PCohF','BCohW','PCohW',... 16 | 'BCorrU','PCorrU','BCorrD','PCorrD', 'BH2U','PH2U','BH2D','PH2D','BMITU','PMITU','BMITD1','PMITD1','BMITD2','PMITD2'... 17 | 'BTEU','PTEU','BTED','PTED',..., 18 | 'GC','PGC','CondGC','MVAR','AS','Af','PDC','oPDCF','GPDC','DC1','DTF','GGC','ffDTF','dDTF','COH1','pCOH1','COH2','pCOH2','Smvar','hmvar'}; 19 | 20 | Nis=length(is); 21 | Nmethods=42; 22 | Ncs=length(cs); 23 | 24 | 25 | 26 | Meths.Methodnames=Informa.Methodnames; 27 | 28 | 29 | AUCm=mean(AUCall,3); 30 | neworderMethod=mln_xorder_cell(Meths.Methodnames,shownMethods); 31 | AUCm=AUCm(neworderMethod,:,:)'; 32 | 33 | screensize=(get(0,'ScreenSize');[1,1,]) 34 | 35 | cutedge=10; 36 | hf=figure('name',[dirname,', AUC'],'color','w','position',[cutedge,cutedge,screensize(3)-cutedge,screensize(4)-cutedge,]); 37 | ha=subplot(2,1,1); 38 | imagesc(squeeze(AUCm)); 39 | 40 | colormap(jet) 41 | set(ha,'XTick',1:Nmethods,'XTickLabel',shownMethods); 42 | xticklabel_rotate; 43 | set(ha,'YTick',1:Ncs,'YTickLabel',num2cell(cs/100),'YDir','normal'); 44 | set(ha,'CLim',[0.7,1]); 45 | title(['AUC average values cross over all poissible structure:',Informa.model]) 46 | 47 | set(ha,'Fontsize',12); 48 | 49 | 50 | %return; 51 | 52 | colormapnow=colormapnowall([1:7],:); 53 | 54 | %hf=figure('color','w'); 55 | ha=subplot(2,1,2); 56 | hold on 57 | %MULANics=squeeze(MLN_AUCM(cs==dcs,:)); 58 | %boxplot(MULANics,'color','g'); 59 | 60 | AUCMics=squeeze(AUCall(:,cs==dcs,:)); 61 | AUCMics=AUCMics(neworderMethod,:); 62 | %AUCMics=[AUCMics;MULANics]; 63 | %boxplot(AUCMics','plotstyle','compact','notch','on'); 64 | 65 | xTicklabel=shownMethods; 66 | %xTicklabel{39}='MULAN' 67 | 68 | boxplot(AUCMics','notch','on','medianstyle','target','labels',xTicklabel,'labelorientation','inline') 69 | %set(ha,'XTickLabel',xTicklabel,'labelorientation','inline') 70 | numbers=[4 4 4 6 4 3 17]; 71 | for inumbers=1:length(numbers) 72 | istart=sum(numbers([1:inumbers-1]))+1; 73 | ifini=sum(numbers([1:inumbers])); 74 | colorgroup(istart:ifini,:)=repmat(colormapnow(inumbers,:),numbers(inumbers),1); 75 | end 76 | colorgroup=colorgroup(end:-1:1,:); 77 | hobj = findobj(gca,'Tag','Box'); 78 | for j=1:length(hobj) 79 | patch(get(hobj(j),'XData'),get(hobj(j),'YData'),colorgroup(j,:),'FaceAlpha',.5); 80 | end 81 | 82 | set(gca,'YLim',[0.3,1]) 83 | title(['Boxplot on 154 different structures: connection strength=',num2str(dcs/100)]); 84 | 85 | 86 | 87 | -------------------------------------------------------------------------------- /GenerateData/mln_generate_henon.m: -------------------------------------------------------------------------------- 1 | % make connectivity simulations for Henon systems 2 | %% this function is used to generate the henon map nonlinear systems with 3 | %%% noise and delay 4 | %% Huifang Wang Sep. 4, 2012 5 | function [dataname,flg]=mln_generate_henon(dirname,prename,npts,strfile,is,cs,odelay,flag_noise,SNR) 6 | 7 | dataname=[prename,'henonCS',num2str(100*cs),'S',num2str(is),'N',num2str(npts)]; 8 | filename=['./',dirname,'/data/',dataname,'.mat']; 9 | [cdata] = imread('MULANLOGO.png'); 10 | if exist(filename,'file') 11 | 12 | msgbox('Data already there','Success','custom',cdata); 13 | else 14 | if ~exist(dirname,'dir') 15 | mkdir(dirname); 16 | end 17 | datadir=[dirname,'/data']; 18 | if ~exist(datadir,'dir') 19 | mkdir(datadir); 20 | end 21 | flg=0; % good data 22 | % delaydelay =0 default 23 | 24 | load(strfile,'PGS'); 25 | %Nglist=length(PGS); 26 | 27 | Astru=PGS{is}; 28 | SparseA=sparse(Astru(1,:),Astru(2,:),1); 29 | P.A=full(SparseA); 30 | nchan=max(max(Astru)); 31 | P.A(nchan,nchan)=0; 32 | P.A=P.A*cs; 33 | a=1.4; 34 | 35 | if mod(nchan,2) 36 | b=randi([20 27],1,nchan)/100; 37 | else 38 | b=[randi([20,25],1,nchan/2)/100,randi([25,30],1,nchan/2)/100]; 39 | end 40 | %b=[0.25,0.22,0.3,0.29,0.27,0.28]; 41 | d=ones(1,nchan); % systems with 5 channels 42 | 43 | %flag_noise=0; 44 | %SNR=20; 45 | startTime=100; 46 | ofs=100; % original sample frenquecy which depends on the ode RelTol 47 | CM=P.A; 48 | 49 | T=0:npts; 50 | NT=length(T); 51 | X=zeros(nchan,NT); 52 | if odelay==0 53 | for iT=3:NT 54 | for ichan=1:nchan 55 | xij=bsxfun(@times,X(1:nchan,iT-1), X(ichan,iT-1)); 56 | X(ichan,iT)=d(ichan)-(CM(ichan,:)*xij+(a-sum(CM(ichan,:)))*X(ichan,iT-1)^2)+b(ichan)*X(ichan,iT-2); 57 | end 58 | end 59 | 60 | end 61 | %%%%%%%%%%%%%%%%%%%%%% 62 | startT=find(T>startTime,1); 63 | T=T(startT:end)-startTime; 64 | X=X(:,startT:end); 65 | 66 | TotalTime=npts-startTime; 67 | 68 | 69 | %% save the data 70 | LFP=X; 71 | if ~isempty(find(isnan(max(LFP))==1)) || ~isempty(find(LFP>1000)) 72 | flg=1; %%% baddata 73 | dataname=[]; 74 | return; 75 | end 76 | 77 | Connectivity=CM; 78 | Params.npts= TotalTime*ofs; 79 | Params.fs=ofs; 80 | Params.model.abc=[a,b,d]; 81 | Params.flag_noise=flag_noise; 82 | Params.SNR=SNR; 83 | Params.fs=100; 84 | save(filename,'LFP','Connectivity','Params'); 85 | msgbox('Data Generated','Success','custom',cdata); 86 | 87 | end 88 | 89 | 90 | function C2=insertdelay(C1,DelayV) 91 | odelay=max(max(DelayV)); 92 | if odelay==0 93 | C2=C1; 94 | return; 95 | end 96 | nchan=size(C1,1); 97 | 98 | C2=zeros(nchan,odelay*nchan); 99 | for i=1:odelay 100 | [row,col]=find(DelayV==i); 101 | C0=zeros(nchan,nchan); 102 | C0(row,col)=C1(row,col); 103 | C2(:,(i-1)*nchan+1:i*nchan)=C0; 104 | end 105 | 106 | 107 | -------------------------------------------------------------------------------- /GenerateData/mln_generate_henon.m~: -------------------------------------------------------------------------------- 1 | % make connectivity simulations for Henon systems 2 | %% this function is used to generate the henon map nonlinear systems with 3 | %%% noise and delay 4 | %% Huifang Wang Sep. 4, 2012 5 | function [dataname,flg]=mln_Generate_henondata(dirname,prename,npts,strfile,is,cs,odelay,flag_noise,SNR) 6 | 7 | dataname=[prename,'henonCS',num2str(100*cs),'S',num2str(is),'N',num2str(npts)]; 8 | filename=['./',dirname,'/data/',dataname,'.mat']; 9 | [cdata] = imread('MULANLOGO.png'); 10 | if exist(filename,'file') 11 | 12 | msgbox('Data already there','Success','custom',cdata); 13 | else 14 | if ~exist(dirname,'dir') 15 | mkdir(dirname); 16 | end 17 | datadir=[dirname,'/data']; 18 | if ~exist(datadir,'dir') 19 | mkdir(datadir); 20 | end 21 | flg=0; % good data 22 | % delaydelay =0 default 23 | 24 | load(strfile,'PGS'); 25 | %Nglist=length(PGS); 26 | 27 | Astru=PGS{is}; 28 | SparseA=sparse(Astru(1,:),Astru(2,:),1); 29 | P.A=full(SparseA); 30 | nchan=max(max(Astru)); 31 | P.A(nchan,nchan)=0; 32 | P.A=P.A*cs; 33 | a=1.4; 34 | 35 | if mod(nchan,2) 36 | b=randi([20 27],1,nchan)/100; 37 | else 38 | b=[randi([20,25],1,nchan/2)/100,randi([25,30],1,nchan/2)/100]; 39 | end 40 | %b=[0.25,0.22,0.3,0.29,0.27,0.28]; 41 | d=ones(1,nchan); % systems with 5 channels 42 | 43 | %flag_noise=0; 44 | %SNR=20; 45 | startTime=100; 46 | ofs=100; % original sample frenquecy which depends on the ode RelTol 47 | CM=P.A; 48 | 49 | T=0:npts; 50 | NT=length(T); 51 | X=zeros(nchan,NT); 52 | if odelay==0 53 | for iT=3:NT 54 | for ichan=1:nchan 55 | xij=bsxfun(@times,X(1:nchan,iT-1), X(ichan,iT-1)); 56 | X(ichan,iT)=d(ichan)-(CM(ichan,:)*xij+(a-sum(CM(ichan,:)))*X(ichan,iT-1)^2)+b(ichan)*X(ichan,iT-2); 57 | end 58 | end 59 | 60 | end 61 | %%%%%%%%%%%%%%%%%%%%%% 62 | startT=find(T>startTime,1); 63 | T=T(startT:end)-startTime; 64 | X=X(:,startT:end); 65 | 66 | TotalTime=npts-startTime; 67 | 68 | 69 | %% save the data 70 | LFP=X; 71 | if ~isempty(find(isnan(max(LFP))==1)) || ~isempty(find(LFP>1000)) 72 | flg=1; %%% baddata 73 | dataname=[]; 74 | return; 75 | end 76 | 77 | Connectivity=CM; 78 | Params.npts= TotalTime*ofs; 79 | Params.fs=ofs; 80 | Params.model.abc=[a,b,d]; 81 | Params.flag_noise=flag_noise; 82 | Params.SNR=SNR; 83 | Params.fs=100; 84 | save(filename,'LFP','Connectivity','Params'); 85 | msgbox('Data Generated','Success','custom',cdata); 86 | 87 | end 88 | 89 | 90 | function C2=insertdelay(C1,DelayV) 91 | odelay=max(max(DelayV)); 92 | if odelay==0 93 | C2=C1; 94 | return; 95 | end 96 | nchan=size(C1,1); 97 | 98 | C2=zeros(nchan,odelay*nchan); 99 | for i=1:odelay 100 | [row,col]=find(DelayV==i); 101 | C0=zeros(nchan,nchan); 102 | C0(row,col)=C1(row,col); 103 | C2(:,(i-1)*nchan+1:i*nchan)=C0; 104 | end 105 | 106 | 107 | -------------------------------------------------------------------------------- /GenerateData/mln_generate_linear.m: -------------------------------------------------------------------------------- 1 | % make connectivity simulations for superAR 2 | function [dataname,flag_LFP]=mln_generate_linear(dirname,prename,npts,strfile,is,cs,delaydelay) 3 | % Huifang Wang based on the code from Christian Benar 4 | % test for MVAR modelling 5 | % MVAR simulation code coming from demo7 from biosig toolbox 6 | dataname=[prename,'linearCS',num2str(100*cs),'S',num2str(is),'N',num2str(npts)]; 7 | filename=['./',dirname,'/data/',dataname,'.mat']; 8 | [cdata] = imread('MULANLOGO.png'); 9 | if exist(filename,'file') 10 | 11 | msgbox('Data already there','Success','custom',cdata); 12 | else 13 | if ~exist(dirname,'dir') 14 | mkdir(dirname); 15 | end 16 | datadir=[dirname,'/data']; 17 | if ~exist(datadir,'dir') 18 | mkdir(datadir); 19 | end 20 | % Variables: 21 | % nreal: number of realizations 22 | % overfact_list: oversampling factors (new order = oversamp factor x original order) 23 | % AR_array: simulated MVAR parameters 24 | % y_array: simulated signals nchan x npts x nover x nreal; 25 | 26 | 27 | load(strfile,'PGS'); 28 | %Nglist=length(PGS); 29 | 30 | Astru=PGS{is}; 31 | SparseA=sparse(Astru(1,:),Astru(2,:),1); 32 | P.A=full(SparseA); 33 | nchan=max(max(Astru)); 34 | Nlink=size(Astru,2); 35 | orderModel=randi(3,[1,Nlink]); 36 | AR0=zeros(nchan,nchan*3); 37 | AR0(1,1)=.95*sqrt(2); 38 | AR0(1,nchan+1)=-0.9025; 39 | for ilink=1:Nlink 40 | AR0(Astru(2,ilink),nchan*(orderModel(ilink)-1)+Astru(1,ilink)) =cs; 41 | end 42 | %auto_chans=1; % channels with auto-regressive parts 43 | 44 | %delaydelay=1; 45 | AR0=putdelay(AR0,delaydelay); 46 | norder= size(AR0,2)/nchan; % order of original model 47 | flag_LFP=1; 48 | % init 49 | %RandStream.setDefaultStream(RandStream('mt19937ar','seed',sum(100*clock))); 50 | 51 | x = randn(nchan,npts); 52 | % Simulated MVAR process 53 | LFP= mvfilter(eye(nchan),[eye(nchan),-AR0],x); 54 | if max(max(LFP))<1000 55 | flag_LFP=0; 56 | end 57 | 58 | Net=zeros(nchan,nchan); 59 | % for i=1:norder 60 | % Net=Net+AR0(:,(i-1)*nchan+1:i*nchan); 61 | % end 62 | AR03=reshape(AR0,nchan,nchan,norder); 63 | Net=max(abs(AR03),[],3); 64 | 65 | Connectivity=Net; 66 | Params.npts=npts; 67 | Params.fs=100; 68 | save(filename,'LFP','Connectivity','Params'); 69 | msgbox('Data Generated','Success','custom',cdata); 70 | 71 | end 72 | function AR=putdelay(AR0,delaydelay) 73 | nchan = size(AR0,1); % number of channels 74 | norder= size(AR0,2)/nchan; 75 | cur_order=(norder-1)*(delaydelay)+1; 76 | AR=zeros(nchan,cur_order*nchan); 77 | for i=1:norder 78 | AR(:,(i-1)*delaydelay*nchan+(1:nchan))=AR0(:,(i-1)*nchan+(1:nchan)); 79 | end; 80 | auto_chans=1; 81 | % keep channels with autoregressive aprt (or else they could be unstable) 82 | for i=1:length(auto_chans) 83 | AR(auto_chans(i),:)=0; 84 | AR(auto_chans(i),1:size(AR0,2))=AR0(auto_chans(i),:); 85 | end 86 | 87 | 88 | -------------------------------------------------------------------------------- /GenerateData/mln_generate_nmm.m: -------------------------------------------------------------------------------- 1 | % Huifang Wang For nmm Structure cluster Version 2 | % related to the structures and pink noise 3 | % Karl Friston 4 | % $Id: spm_csd_demo.m 4402 2011-07-21 12:37:24Z karl $ 5 | function dataname=mln_generate_nmm(is,nc,strfile,dirname,prename,cs,N) 6 | 7 | dataname=[prename,'nmmCS',num2str(100*cs),'S',num2str(is),'N',num2str(N)]; 8 | filename=['./',dirname,'/data/',dataname,'.mat']; 9 | [cdata] = imread('MULANLOGO.png'); 10 | if exist(filename,'file') 11 | 12 | msgbox('Data already there','Success','custom',cdata); 13 | else 14 | if ~exist(dirname,'dir') 15 | mkdir(dirname); 16 | end 17 | datadir=[dirname,'/data']; 18 | if ~exist(datadir,'dir') 19 | mkdir(datadir); 20 | end 21 | 22 | % number of sources and LFP channels (usually the same) 23 | %-------------------------------------------------------------------------- 24 | n = nc; % number of sources 25 | % CS=1; 26 | % specify network (connections) 27 | %-------------------------------------------------------------------------- 28 | A{1}=zeros(n); %A{1} = tril(ones(n,n),-1); % a forward connection 29 | A{2} = zeros(n);%triu(ones(n,n),+1); % a backward connection 30 | A{3} = sparse(n,n); % lateral connections 31 | B = {}; % trial-specific modulation 32 | C = speye(n,n); % sources receiving innovations 33 | 34 | % get priors 35 | %-------------------------------------------------------------------------- 36 | [pE,pC] = spm_lfp_priors(A,B,C); % neuronal priors 37 | [pE,pC] = spm_ssr_priors(pE,pC); % spectral priors 38 | [pE,pC] = spm_L_priors(n,pE,pC); % spatial priors 39 | 40 | % create LFP model 41 | %-------------------------------------------------------------------------- 42 | M.IS = 'spm_lfp_mtf'; 43 | M.FS = 'spm_lfp_sqrt'; 44 | M.f = 'spm_fx_lfp'; 45 | M.g = 'spm_gx_erp'; 46 | M.x = sparse(n,13); 47 | M.n = n*13; 48 | M.pE = pE; 49 | M.pC = pC; 50 | M.m = n; 51 | M.l = nc; 52 | M.Hz = [1:64]'; 53 | 54 | 55 | 56 | % or generate data 57 | %========================================================================== 58 | 59 | % Integrate with pink noise process 60 | %-------------------------------------------------------------------------- 61 | 62 | U.dt = 8/1000; 63 | U.u = randn(N,M.m)/100; 64 | %U.u=zeros(N,M.m)/16; 65 | U.u = sqrt(spm_Q(1/16,N))*U.u; 66 | 67 | load(strfile,'PGS'); 68 | %=============================================================== 69 | P = pE; 70 | Astru=PGS{is}; 71 | SparseA=sparse(Astru(1,:),Astru(2,:),1); 72 | P.A{1}=full(SparseA); 73 | P.A{1}(nc,nc)=0; 74 | P.A{1}=P.A{1}.*cs; 75 | 76 | 77 | LFP = spm_int_L(P,M,U); 78 | LFP=LFP'; 79 | Params.fs=1000/8; 80 | Connectivity=P.A{1}; 81 | Connectivity(Connectivity<0)=0; 82 | 83 | save(filename,'LFP','Connectivity','Params'); 84 | msgbox('Data Generated','Success','custom',cdata); 85 | 86 | end 87 | 88 | -------------------------------------------------------------------------------- /Evaluation/mln_showAUC.m: -------------------------------------------------------------------------------- 1 | %% show the results 2 | % show the AUC array for varying the number of windows 3 | % Huifang Wang Feb 7, 2014, Demo for demonstrate the AUC array and Boxplot in the paper 4 | 5 | function mln_showAUC 6 | load('ExAUCnmmN5L5.mat','AUCall','Informa') 7 | colormapnowall=colormap(lines); 8 | cs=Informa.cs; 9 | is=Informa.is; 10 | model=Informa.model; 11 | dcs=60; 12 | struct='N5L5'; 13 | dirname=['/Volumes/HWMac1/MULANpre/',struct,'S/',model]; 14 | prenom=[model,struct]; 15 | 16 | 17 | shownMethods={'BCohF','PCohF','BCohW','PCohW',... 18 | 'BCorrU','PCorrU','BCorrD','PCorrD', 'BH2U','PH2U','BH2D','PH2D','BMITU','PMITU','BMITD1','PMITD1','BMITD2','PMITD2'... 19 | 'BTEU','PTEU','BTED','PTED',..., 20 | 'GC','PGC','CondGC','MVAR','AS','Af','PDC','oPDCF','GPDC','DC1','DTF','GGC','ffDTF','dDTF','COH1','pCOH1','COH2','pCOH2','Smvar','hmvar'}; 21 | 22 | Nis=length(is); 23 | Nmethods=42; 24 | Ncs=length(cs); 25 | 26 | 27 | 28 | Meths.Methodnames=Informa.Methodnames; 29 | 30 | 31 | AUCm=mean(AUCall,3); 32 | neworderMethod=mln_xorder_cell(Meths.Methodnames,shownMethods); 33 | AUCm=AUCm(neworderMethod,:,:)'; 34 | 35 | screensize=min(get(0,'ScreenSize'),[1,1,1440,900]); 36 | 37 | cutedge=10; 38 | hf=figure('name',[dirname,', AUC'],'color','w','position',[cutedge,cutedge,screensize(3)-cutedge,screensize(4)-cutedge,]); 39 | ha=subplot(2,1,1); 40 | imagesc(squeeze(AUCm)); 41 | 42 | colormap(jet) 43 | set(ha,'XTick',1:Nmethods,'XTickLabel',shownMethods); 44 | xticklabel_rotate; 45 | set(ha,'YTick',1:Ncs,'YTickLabel',num2cell(cs/100),'YDir','normal'); 46 | set(ha,'CLim',[0.7,1]); 47 | title(['AUC average values cross over all poissible structure:',Informa.model],'Fontsize',15) 48 | 49 | set(ha,'Fontsize',12); 50 | 51 | 52 | %return; 53 | 54 | colormapnow=colormapnowall([1:7],:); 55 | 56 | %hf=figure('color','w'); 57 | ha=subplot(2,1,2); 58 | hold on 59 | %MULANics=squeeze(MLN_AUCM(cs==dcs,:)); 60 | %boxplot(MULANics,'color','g'); 61 | 62 | AUCMics=squeeze(AUCall(:,cs==dcs,:)); 63 | AUCMics=AUCMics(neworderMethod,:); 64 | %AUCMics=[AUCMics;MULANics]; 65 | %boxplot(AUCMics','plotstyle','compact','notch','on'); 66 | 67 | xTicklabel=shownMethods; 68 | %xTicklabel{39}='MULAN' 69 | 70 | boxplot(AUCMics','notch','on','medianstyle','target','labels',xTicklabel,'labelorientation','inline') 71 | %set(ha,'XTickLabel',xTicklabel,'labelorientation','inline') 72 | numbers=[4 4 4 6 4 3 17]; 73 | for inumbers=1:length(numbers) 74 | istart=sum(numbers([1:inumbers-1]))+1; 75 | ifini=sum(numbers([1:inumbers])); 76 | colorgroup(istart:ifini,:)=repmat(colormapnow(inumbers,:),numbers(inumbers),1); 77 | end 78 | colorgroup=colorgroup(end:-1:1,:); 79 | hobj = findobj(gca,'Tag','Box'); 80 | for j=1:length(hobj) 81 | patch(get(hobj(j),'XData'),get(hobj(j),'YData'),colorgroup(j,:),'FaceAlpha',.5); 82 | end 83 | 84 | set(gca,'YLim',[0.3,1]) 85 | title(['Boxplot on 154 different structures: connection strength=',num2str(dcs/100)],'Fontsize',15); 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /GenerateData/spm_cat.m: -------------------------------------------------------------------------------- 1 | function [x] = spm_cat(x,d) 2 | % Convert a cell array into a matrix 3 | % FORMAT [x] = spm_cat(x,d) 4 | % x - cell array 5 | % d - dimension over which to concatenate [default - both] 6 | %__________________________________________________________________________ 7 | % Empty array elements are replaced by sparse zero partitions 8 | % and single 0 entries are expanded to conform to the non-empty 9 | % non zero elements. 10 | % 11 | % e.g.: 12 | % > x = spm_cat({eye(2) []; 0 [1 1; 1 1]}) 13 | % > full(x) = 14 | % 15 | % 1 0 0 0 16 | % 0 1 0 0 17 | % 0 0 1 1 18 | % 0 0 1 1 19 | % 20 | % If called with a dimension argument; a cell array is returned 21 | %__________________________________________________________________________ 22 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 23 | 24 | % Karl Friston 25 | % $Id: spm_cat.m 5219 2013-01-29 17:07:07Z spm $ 26 | 27 | 28 | % check x is not already a matrix 29 | %-------------------------------------------------------------------------- 30 | if ~iscell(x), return, end 31 | 32 | % if concatenation over a specific dimension 33 | %-------------------------------------------------------------------------- 34 | [n,m] = size(x); 35 | if nargin > 1 36 | 37 | % concatenate over first dimension 38 | %---------------------------------------------------------------------- 39 | if d == 1 40 | y = cell(1,m); 41 | for i = 1:m 42 | y{i} = spm_cat(x(:,i)); 43 | end 44 | 45 | % concatenate over second 46 | %---------------------------------------------------------------------- 47 | elseif d == 2 48 | 49 | y = cell(n,1); 50 | for i = 1:n 51 | y{i} = spm_cat(x(i,:)); 52 | end 53 | 54 | % only viable for 2-D arrays 55 | %---------------------------------------------------------------------- 56 | else 57 | error('uknown option') 58 | end 59 | x = y; 60 | return 61 | 62 | end 63 | 64 | % find dimensions to fill in empty partitions 65 | %-------------------------------------------------------------------------- 66 | for i = 1:n 67 | for j = 1:m 68 | if iscell(x{i,j}) 69 | x{i,j} = spm_cat(x{i,j}); 70 | end 71 | [u,v] = size(x{i,j}); 72 | I(i,j) = u; 73 | J(i,j) = v; 74 | end 75 | end 76 | I = max(I,[],2); 77 | J = max(J,[],1); 78 | 79 | % sparse and empty partitions 80 | %-------------------------------------------------------------------------- 81 | [n,m] = size(x); 82 | for i = 1:n 83 | for j = 1:m 84 | if isempty(x{i,j}) 85 | x{i,j} = sparse(I(i),J(j)); 86 | end 87 | end 88 | end 89 | 90 | % concatenate 91 | %-------------------------------------------------------------------------- 92 | for i = 1:n 93 | y{i,1} = cat(2,x{i,:}); 94 | end 95 | try 96 | x = sparse(cat(1,y{:})); 97 | catch 98 | x = cat(1,y{:}); 99 | end 100 | -------------------------------------------------------------------------------- /GenerateData/spm_svd.m: -------------------------------------------------------------------------------- 1 | function [U,S,V] = spm_svd(X,U,T) 2 | % Computationally efficient SVD (that can handle sparse arguments) 3 | % FORMAT [U,S,V] = spm_svd(X,u,t) 4 | % X - {m x n} matrix 5 | % u - threshold for normalized eigenvalues (default = 1e-6) 6 | % t - threshold for raw eigenvalues (default = 0) 7 | % 8 | % U - {m x p} singular vectors 9 | % V - {m x p} singular variates 10 | % S - {p x p} singular values 11 | %__________________________________________________________________________ 12 | % Copyright (C) 1994-2011 Wellcome Trust Centre for Neuroimaging 13 | 14 | % Karl Friston 15 | % $Id: spm_svd.m 4604 2011-12-20 18:21:03Z guillaume $ 16 | 17 | 18 | % default thresholds 19 | %-------------------------------------------------------------------------- 20 | if nargin < 2, U = 1e-6; end 21 | if nargin < 3, T = 0; end 22 | 23 | % deal with sparse matrices 24 | %-------------------------------------------------------------------------- 25 | [M, N] = size(X); 26 | p = find(any(X,2)); 27 | q = find(any(X,1)); 28 | X = X(p,q); 29 | 30 | % SVD 31 | %-------------------------------------------------------------------------- 32 | [i, j, s] = find(X); 33 | [m, n] = size(X); 34 | if any(i - j) 35 | 36 | % off-leading diagonal elements - full SVD 37 | %---------------------------------------------------------------------- 38 | X = full(X); 39 | if m > n 40 | 41 | [v, S, v] = svd(X'*X,0); 42 | S = sparse(S); 43 | s = diag(S); 44 | j = find(s*length(s)/sum(s) >= U & s >= T); 45 | v = v(:,j); 46 | u = spm_en(X*v); 47 | S = sqrt(S(j,j)); 48 | 49 | elseif m < n 50 | 51 | [u, S, u] = svd(X*X',0); 52 | S = sparse(S); 53 | s = diag(S); 54 | j = find(s*length(s)/sum(s) >= U & s >= T); 55 | u = u(:,j); 56 | v = spm_en(X'*u); 57 | S = sqrt(S(j,j)); 58 | 59 | else 60 | 61 | [u, S, v] = svd(X,0); 62 | S = sparse(S); 63 | s = diag(S).^2; 64 | j = find(s*length(s)/sum(s) >= U & s >= T); 65 | v = v(:,j); 66 | u = u(:,j); 67 | S = S(j,j); 68 | end 69 | 70 | else 71 | S = sparse(1:n,1:n,s,m,n); 72 | u = speye(m,n); 73 | v = speye(m,n); 74 | [i, j] = sort(-s); 75 | S = S(j,j); 76 | v = v(:,j); 77 | u = u(:,j); 78 | s = diag(S).^2; 79 | j = find(s*length(s)/sum(s) >= U & s >= T); 80 | v = v(:,j); 81 | u = u(:,j); 82 | S = S(j,j); 83 | 84 | end 85 | 86 | % replace in full matrices 87 | %-------------------------------------------------------------------------- 88 | j = length(j); 89 | U = sparse(M,j); 90 | V = sparse(N,j); 91 | if j 92 | U(p,:) = u; 93 | V(q,:) = v; 94 | end 95 | -------------------------------------------------------------------------------- /GenerateData/mln_generate_fMRI.m: -------------------------------------------------------------------------------- 1 | function dataname=mln_generate_fMRI(is,nc,strfile,dirname,prename,cs,T) 2 | 3 | % Huifang from 4 | % Karl Friston 5 | % $Id: DEM_demo_large_fMRI.m 5691 2013-10-11 16:53:00Z karl $ 6 | 7 | 8 | dataname=[prename,'fmriCS',num2str(100*cs),'S',num2str(is),'N',num2str(T)]; 9 | filename=['./',dirname,'/data/',dataname,'.mat']; 10 | [cdata] = imread('MULANLOGO.png'); 11 | if exist(filename,'file') 12 | 13 | msgbox('Data already there','Success','custom',cdata); 14 | else 15 | if ~exist(dirname,'dir') 16 | mkdir(dirname); 17 | end 18 | datadir=[dirname,'/data']; 19 | if ~exist(datadir,'dir') 20 | mkdir(datadir); 21 | end 22 | % Simulate timeseries 23 | %========================================================================== 24 | %rng('default') 25 | 26 | % DEM Structure: create random inputs 27 | % ------------------------------------------------------------------------- 28 | %Nc = 8; % number of runs 29 | %T = 512; % number of observations (scans) 30 | TR = 2; % repetition time or timing 31 | n = nc; % number of regions or nodes 32 | t = (1:T)*TR; % observation times 33 | 34 | % priors 35 | % ------------------------------------------------------------------------- 36 | options.nmax = 8; % effective number of notes 37 | 38 | options.nonlinear = 0; 39 | options.two_state = 0; 40 | options.stochastic = 0; 41 | options.centre = 1; 42 | options.induced = 1; 43 | 44 | A = ones(n,n); 45 | B = zeros(n,n,0); 46 | C = zeros(n,n); 47 | D = zeros(n,n,0); 48 | pP = spm_dcm_fmri_priors(A,B,C,D,options); 49 | 50 | load(strfile,'PGS'); 51 | 52 | %========================================================================== 53 | 54 | Astru=PGS{is}; 55 | SparseA=sparse(Astru(1,:),Astru(2,:),1); 56 | P.A=full(SparseA); 57 | P.A(nc,nc)=0; 58 | pP.A=P.A.*cs/8; 59 | 60 | % true parameters (reciprocal connectivity) 61 | % ------------------------------------------------------------------------- 62 | %pP.A = randn(n,n)/8; 63 | pP.A = pP.A - diag(diag(pP.A)); 64 | pP.C = eye(n,n); 65 | pP.transit = randn(n,1)/16; 66 | 67 | % simulate response to endogenous fluctuations 68 | %========================================================================== 69 | 70 | % integrate states 71 | % ------------------------------------------------------------------------- 72 | U.u = spm_rand_mar(T,n,1/2)/2; % endogenous fluctuations 73 | U.dt = TR; 74 | M.f = 'spm_fx_fmri'; 75 | M.x = sparse(n,5); 76 | x = spm_int_J(pP,M,U); 77 | 78 | % haemodynamic observer 79 | % ------------------------------------------------------------------------- 80 | for i = 1:T 81 | y(i,:) = spm_gx_fmri(spm_unvec(x(i,:),M.x),[],pP)'; 82 | end 83 | 84 | % observation noise process 85 | % ------------------------------------------------------------------------- 86 | %e = spm_rand_mar(T,n,1/2)/8; 87 | 88 | LFP=y'; 89 | Params.fs=1/TR; 90 | Connectivity=pP.A; 91 | %Connectivity(Connectivity<0)=0; 92 | save(filename,'LFP','Connectivity','Params'); 93 | msgbox('Data Generated','Success','custom',cdata); 94 | 95 | end -------------------------------------------------------------------------------- /GenerateData/spm_dx.m: -------------------------------------------------------------------------------- 1 | function [dx] = spm_dx(dfdx,f,t) 2 | % returns dx(t) = (expm(dfdx*t) - I)*inv(dfdx)*f 3 | % FORMAT [dx] = spm_dx(dfdx,f,[t]) 4 | % dfdx = df/dx 5 | % f = dx/dt 6 | % t = integration time: (default t = Inf); 7 | % if t is a cell (i.e., {t}) then t is set to: 8 | % exp(t - log(diag(-dfdx)) 9 | % 10 | % dx = x(t) - x(0) 11 | %-------------------------------------------------------------------------- 12 | % Integration of a dynamic system using local linearization. This scheme 13 | % accommodates nonlinearities in the state equation by using a functional of 14 | % f(x) = dx/dt. This uses the equality 15 | % 16 | % expm([0 0 ]) = (expm(t*dfdx) - I)*inv(dfdx)*f 17 | % [t*f t*dfdx] 18 | % 19 | % When t -> Inf this reduces to 20 | % 21 | % dx(t) = -inv(dfdx)*f 22 | % 23 | % These are the solutions to the gradient ascent ODE 24 | % 25 | % dx/dt = k*f = k*dfdx*x => 26 | % 27 | % dx(t) = expm(t*k*dfdx)*x(0) 28 | % = expm(t*k*dfdx)*inv(dfdx)*f(0) - 29 | % expm(0*k*dfdx)*inv(dfdx)*f(0) 30 | % 31 | % When f = dF/dx (and dfdx = dF/dxdx), dx represents the update from a 32 | % Gauss-Newton ascent on F. This can be regularised by specifying {t} 33 | % A heavy regularization corresponds to t = -4 and a light 34 | % regularization would be t = 4. This version of spm_dx uses an augmented 35 | % system and the Pade approximation to compute requisite matrix 36 | % exponentials 37 | % 38 | % references: 39 | % 40 | % Friston K, Mattout J, Trujillo-Barreto N, Ashburner J, Penny W. (2007). 41 | % Variational free energy and the Laplace approximation. NeuroImage. 42 | % 34(1):220-34 43 | % 44 | % Ozaki T (1992) A bridge between nonlinear time-series models and 45 | % nonlinear stochastic dynamical systems: A local linearization approach. 46 | % Statistica Sin. 2:113-135. 47 | % 48 | %__________________________________________________________________________ 49 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 50 | 51 | % Karl Friston 52 | % $Id: spm_dx.m 5691 2013-10-11 16:53:00Z karl $ 53 | 54 | % defaults 55 | %-------------------------------------------------------------------------- 56 | 57 | if nargin < 3, t = Inf; end 58 | 59 | % t is a regulariser 60 | %-------------------------------------------------------------------------- 61 | sw = warning('off','MATLAB:log:logOfZero'); 62 | if iscell(t) 63 | t = exp(t{:} - log(diag(-dfdx))); 64 | end 65 | warning(sw); 66 | 67 | % use a [pseudo]inverse if all t > TOL 68 | %========================================================================== 69 | if min(t) > exp(16) 70 | 71 | dx = -spm_pinv(dfdx)*spm_vec(f); 72 | dx = spm_unvec(dx,f); 73 | 74 | else 75 | 76 | % ensure t is a scalar or matrix 77 | %---------------------------------------------------------------------- 78 | if isvector(t), t = diag(t); end 79 | 80 | % augment Jacobian and take matrix exponential 81 | %====================================================================== 82 | J = spm_cat({0 []; t*spm_vec(f) t*dfdx}); 83 | dx = expm(full(J)); 84 | dx = spm_unvec(dx(2:end,1),f); 85 | 86 | end 87 | dx = real(dx); 88 | 89 | -------------------------------------------------------------------------------- /GenerateData/spm_expm.m: -------------------------------------------------------------------------------- 1 | function [x] = spm_expm(J,x) 2 | % approximate matrix exponential using a Taylor expansion 3 | % FORMAT [y] = spm_expm(J,x) 4 | % FORMAT [y] = spm_expm(J) 5 | % y = expm(J)*x: 6 | % y = expm(J); 7 | % 8 | % This routine covers and extends expm functionality by using a 9 | % comoutationally expedient approximation that can handle sparse 10 | % matrices when dealing with the special case of expm(J)*x, where x 11 | % is a vector, in an efficient fashion 12 | %__________________________________________________________________________ 13 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 14 | 15 | % Karl Friston 16 | % $Id: spm_expm.m 3813 2010-04-07 19:21:49Z karl $ 17 | 18 | 19 | 20 | if nargin == 1 || nargin == 2 21 | 22 | % expm(J) use Pade approximation 23 | %====================================================================== 24 | 25 | % ensure norm is < 1/2 by scaling by power of 2 26 | %---------------------------------------------------------------------- 27 | J = full(J); 28 | I = eye(size(J)); 29 | [f,e] = log2(norm(J,'inf')); 30 | s = max(0,e + 1); 31 | J = J/2^s; 32 | X = J; 33 | c = 1/2; 34 | E = I + c*J; 35 | D = I - c*J; 36 | q = 6; 37 | p = 1; 38 | for k = 2:q 39 | c = c*(q - k + 1)/(k*(2*q - k + 1)); 40 | X = J*X; 41 | cX = c*X; 42 | E = E + cX; 43 | if p 44 | D = D + cX; 45 | else 46 | D = D - cX; 47 | end 48 | p = ~p; 49 | end 50 | 51 | E = D\E; % E = inv(D)*E 52 | 53 | % Undo scaling by repeated squaring E = E^(2^s) 54 | %---------------------------------------------------------------------- 55 | for k = 1:s 56 | E = E*E; 57 | end 58 | 59 | % Multiply by x if necessary 60 | %---------------------------------------------------------------------- 61 | if nargin > 1 62 | x = E*x; 63 | else 64 | x = E; 65 | end 66 | return 67 | 68 | 69 | % Alternative evaluation of exp(J)*x for large matrices 70 | %========================================================================== 71 | else 72 | 73 | % compute y = expm(J)*x = (1 + J + J*J/2! + J*J*J/3! + ...)*x 74 | %---------------------------------------------------------------------- 75 | fx = J*x; 76 | s = 0; 77 | for i = 2:64 78 | 79 | % accumulate high-order terms until convergence 80 | %----------------------------------------------------------- 81 | nx = norm(fx,1); 82 | if ~nx 83 | return 84 | end 85 | fx = fx/nx; 86 | 87 | % take care to accumulate scaling in log-space 88 | %------------------------------------------------------------------ 89 | s(i,1) = s(i - 1) + log(nx) - log(i - 1); 90 | x(:,i) = fx; 91 | fx = J*fx; 92 | 93 | % add expansion terms if convergence 94 | %------------------------------------------------------------------ 95 | if s(i) < -16 96 | x = x*exp(s); 97 | return 98 | end 99 | end 100 | 101 | % If no convergence 102 | %---------------------------------------------------------------------- 103 | disp('reverting to full pade') 104 | x = spm_expm(J)*x(:,1); 105 | 106 | end 107 | -------------------------------------------------------------------------------- /Calculation/cca_regress.m: -------------------------------------------------------------------------------- 1 | % ----------------------------------------------------------------------- 2 | % FUNCTION: cca_regress.m 3 | % PURPOSE: perform multivariate regression 4 | % 5 | % INPUT: X - nvar (rows) by nobs (cols) observation matrix 6 | % NLAGS - number of lags to include in model 7 | % STATFLAG - perform Whiteness/Consistency checks or not 8 | % 9 | % OUTPUT: ret.beta - coefficients 10 | % ret.u - residuals 11 | % ret.rss - sum-square-error of residuals 12 | % ret.Z - covariance matrix of residuals 13 | % ret.waut - Durbin Watson autocorrelated residual sig val 14 | % ret.cons - model consistency (Ding et al 2000) 15 | % 16 | % Written AKS Sep 13 2004 17 | % Updated AKS December 2005 18 | % Updated AKS Aug 2009 to implement whiteness & consistency check 19 | % Ref: Seth, A.K. (2005) Network: Comp. Neural. Sys. 16(1):35-55 20 | % COPYRIGHT NOTICE AT BOTTOM 21 | % ----------------------------------------------------------------------- 22 | function [ret] = cca_regress(X,nlags,STATFLAG) 23 | 24 | if nargin<3, 25 | STATFLAG = 0; 26 | end 27 | 28 | % figure regression parameters 29 | [nvar,nobs] = size(X); 30 | if(nvar>nobs) error('nvar>nobs, check input matrix'); end 31 | 32 | % remove sample means if present (no constant terms in this regression) 33 | m = mean(X'); 34 | if(abs(sum(m)) > 0.0001) 35 | mall = repmat(m',1,nobs); 36 | X = X-mall; 37 | end 38 | 39 | % construct lag matrices 40 | lags = -999*ones(nvar,nobs-nlags,nlags); 41 | for jj=1:nvar 42 | for ii=1:nlags 43 | lags(jj,:,nlags-ii+1) = X(jj,ii:nobs-nlags+ii-1); 44 | end 45 | end 46 | 47 | % regression (no constant term) 48 | regressors = zeros(nobs-nlags,nvar*nlags); 49 | for ii=1:nvar, 50 | s1 = (ii-1)*nlags+1; 51 | regressors(:,s1:s1+nlags-1) = squeeze(lags(ii,:,:)); 52 | end 53 | for ii=1:nvar 54 | xvec = X(ii,:)'; 55 | xdep = xvec(nlags+1:end); 56 | beta(:,ii) = regressors\xdep; 57 | xpred(:,ii) = regressors*beta(:,ii); % keep hold of predicted values 58 | u(:,ii) = xdep-xpred(:,ii); 59 | RSS(ii) = sum(u(:,ii).^2); 60 | end 61 | 62 | % check whiteness & consistency if required 63 | if STATFLAG, 64 | for ii=1:nvar, 65 | waut(ii) = cca_whiteness(X,u(:,ii)); 66 | end 67 | cons = cca_consistency(X,xpred); 68 | else 69 | waut = -1; 70 | cons = -1; 71 | end 72 | 73 | % organize output structure 74 | ret.beta = beta; 75 | ret.u = u; 76 | ret.rss = RSS; 77 | ret.cons = cons; 78 | ret.waut = waut; 79 | ret.Z = cov(u); 80 | 81 | % This file is part of GCCAtoolbox. 82 | % It is Copyright (C) Anil Seth (2005-2009) 83 | % 84 | % GCCAtoolbox is free software: you can redistribute it and/or modify 85 | % it under the terms of the GNU General Public License as published by 86 | % the Free Software Foundation, either version 3 of the License, or 87 | % (at your option) any later version. 88 | % 89 | % GCCAtoolbox is distributed in the hope that it will be useful, 90 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 91 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 92 | % GNU General Public License for more details. 93 | % 94 | % You should have received a copy of the GNU General Public License 95 | % along with GCCAtoolbox. If not, see . 96 | 97 | 98 | -------------------------------------------------------------------------------- /Calculation/mln_calc_FalseRate.m: -------------------------------------------------------------------------------- 1 | %%function [ih,f0,f1,Fpr,Tpr,Fnr,pFDR,t,auc,flag_use,th_offcut_roc]=calc_FalseRate(iM,Standard_Net,issymetricM) 2 | % Huifang Wang, April, 2012, Inserm U1106 3 | % Huifang, Sep.,12; updated; 4 | % Huifang, 21, Feb; cutoff of auc 5 | %th_offcut_roc=[th,iFPR,iTPR]; 6 | function varargout =mln_calc_FalseRate(iM,Standard_Net,issymetricM,issample) 7 | 8 | % iM is the Matrix to be evaluated; Standard_Net is the Matrix as 9 | % reference; issymetricM=[1,1] means both Matrix are sysmetrics 10 | nout = max(nargout,1); 11 | %issample=1; 12 | flag_use=1; 13 | %% Get the distribution of the pairs with H0=T and the pairs with H0=F 14 | % 15 | 16 | bi_Standard=Standard_Net(:,:)~=0; 17 | if sum(issymetricM) % if either one of Matrix are symmetric then 18 | bi=bi_Standard| bi_Standard'; 19 | %iM=max(iM,iM'); % directed Matrix becomes to a symmetric one 20 | else bi=bi_Standard; 21 | end 22 | %iM=mean(Norm_multiNet,3); 23 | H0=iM(~bi); 24 | H1=iM(bi); 25 | NH0=length(H0); 26 | NH1=length(H1); 27 | 28 | if isempty(H0) || isempty(H1) 29 | flag_use=0; %% this is not the good way to 30 | varargout{nout-1}=0; 31 | varargout {nout}=flag_use; 32 | return 33 | end 34 | Nsteps=100; 35 | ih=linspace(min(min(iM)),max(max(iM)),Nsteps); 36 | t=ih(ih>=0); 37 | 38 | if issample==0 39 | %% Get the kineral density estimate 40 | 41 | f0=ksdensity(H0,ih,'kernel','normal','function','pdf'); 42 | f1=ksdensity(H1,ih,'kernel','normal','function','pdf'); 43 | g0=ksdensity(H0,ih,'function','cdf'); 44 | g1=ksdensity(H1,ih,'function','cdf'); 45 | 46 | % calulate the False positive rate and True positive rate from keneral 47 | % denisity estimate 48 | % when min(ih0)<0 49 | 50 | Nt=length(t); 51 | Fpr=zeros(Nt,1); 52 | Tpr=zeros(Nt,1); 53 | pFDR=Fpr; 54 | %FDR=Fpr; 55 | prh0=NH0/(NH0+NH1); 56 | prh1=NH1/(NH0+NH1); 57 | corernposition=[0,1]; 58 | dMatrix=zeros(Nt,1); 59 | i=1; 60 | Fpr(1)=1; 61 | Tpr(1)=1; 62 | pFDR(i)=Fpr(i)*prh0/(Fpr(i)*prh0+Tpr(i)*prh1); 63 | dMatrix(i)=norm([Fpr(i)-corernposition(1),Tpr(i)-corernposition(2)]); 64 | for i=2:Nt 65 | Fpr(i)=1-g0(ih==t(i)); 66 | Tpr(i)=1-g1(ih==t(i)); 67 | pFDR(i)=Fpr(i)*prh0/(Fpr(i)*prh0+Tpr(i)*prh1); 68 | dMatrix(i)=norm([Fpr(i)-corernposition(1),Tpr(i)-corernposition(2)]); 69 | end 70 | 71 | [~,indexMin]=min(dMatrix); 72 | th_offcut_roc=[t(indexMin),Fpr(indexMin),Tpr(indexMin)]; 73 | else 74 | %% count FPR and TPR 75 | 76 | NH0=length(H0); 77 | NH1=length(H1); 78 | f0=[]; 79 | f1=[]; 80 | 81 | Nt=length(t); 82 | Fpr=zeros(Nt,1); 83 | Tpr=zeros(Nt,1); 84 | pFDR=Fpr; 85 | prh0=NH0/(NH0+NH1); 86 | prh1=NH1/(NH0+NH1); 87 | corernposition=[0,1]; 88 | dMatrix=zeros(Nt,1); 89 | Fpr(1)=1; 90 | Tpr(1)=1; 91 | i=1; 92 | pFDR(i)=Fpr(i)*prh0/(Fpr(i)*prh0+Tpr(i)*prh1); 93 | dMatrix(i)=norm([Fpr(i)-corernposition(1),Tpr(i)-corernposition(2)]); 94 | for i=2:Nt 95 | Fpr(i)=(sum(H0>t(i)))/NH0; 96 | Tpr(i)=(sum(H1>=t(i)))/NH1; 97 | pFDR(i)=Fpr(i)*prh0/(Fpr(i)*prh0+Tpr(i)*prh1); 98 | dMatrix(i)=norm([Fpr(i)-corernposition(1),Tpr(i)-corernposition(2)]); 99 | end 100 | [~,indexMin]=min(dMatrix); 101 | th_offcut_roc=[t(indexMin),Fpr(indexMin),Tpr(indexMin)]; 102 | end 103 | 104 | Fnr=bsxfun(@minus,1,Tpr); 105 | if isempty(find(iM)) 106 | auc=0.5; 107 | else 108 | 109 | auc = 0.5*sum( (Fpr(2:end)-Fpr(1:end-1)).*(Tpr(2:end)+Tpr(1:end-1)) ); 110 | auc = abs(auc); 111 | end 112 | 113 | varargout {1}=ih; 114 | varargout {2}=f0; 115 | varargout {3}=f1; 116 | varargout {4}=Fpr; 117 | varargout {5}=Tpr; 118 | varargout {6}=Fnr; 119 | varargout {7}=pFDR; 120 | varargout {8}=t; 121 | varargout {9}=auc; 122 | varargout {10}=flag_use; 123 | varargout{11}=th_offcut_roc; -------------------------------------------------------------------------------- /Calculation/MulanCal.m: -------------------------------------------------------------------------------- 1 | 2 | function MulanCal(dirname,dataprenom,calParams,VGroupMethlog) 3 | % Huifang Wang, Marseille, August 18, 2013, Calculate all methods 4 | 5 | datafile=[dirname,'/data/',dataprenom,'.mat']; 6 | 7 | data=load(datafile); 8 | Params=data.Params; 9 | 10 | %% load the data 11 | 12 | if exist(datafile,'file') 13 | try 14 | prevar = load(datafile); 15 | if isstruct(prevar) 16 | fileprevar=fieldnames(prevar); 17 | iLFP=strncmpi(fileprevar,'LFP',3); 18 | if ~isempty(find(strncmpi(fileprevar,'LFP',1)==1,1)) 19 | lfp = prevar.(char(fileprevar(iLFP))); 20 | 21 | else 22 | errordlg('Which date want to process?') 23 | end 24 | 25 | if size(lfp,1)>size(lfp,2) 26 | lfp=lfp'; 27 | else 28 | lfp=lfp; 29 | end 30 | 31 | end 32 | catch ME 33 | errordlg('filename is invalid') 34 | end 35 | end 36 | 37 | if ~isempty(find(strncmpi(fileprevar,'Params',6)==1,1)) 38 | 39 | Params= prevar.Params; 40 | 41 | end 42 | 43 | if ~isempty(find(strncmpi(fileprevar,'Connectivity',12)==1,1)) 44 | 45 | ReferenceMatrix= prevar.Connectivity; 46 | 47 | end 48 | 49 | %% Calculate the 50 | 51 | %%%% Get parameters 52 | %VGroupMethlog={'TimeBasic','FreqBasic','Hsquare','Granger','FreqAH','MutualInform','TE'}; 53 | 54 | %%% Define the file to store results 55 | Ngroup=length(VGroupMethlog); 56 | for igroup=1:Ngroup 57 | GroupMethlog=VGroupMethlog{igroup}; 58 | Resultfile=[dirname,'/Results/',GroupMethlog,'_',dataprenom,'.mat']; 59 | [Methlogs,paramsfields]=mln_setgroupmethlogparam(GroupMethlog); 60 | params=initialparamsmethodsGiven(paramsfields,calParams); 61 | params.fs=Params.fs; 62 | switch GroupMethlog 63 | case 'TimeBasic' 64 | mln_calcMatTimeBasic(Resultfile,Methlogs,lfp,params); 65 | case 'FreqBasic' 66 | mln_calcMatFreqBasic(Resultfile,Methlogs,lfp,params); 67 | case 'Hsquare' 68 | mln_calcMatH2(Resultfile,Methlogs,lfp,params); 69 | case 'Granger' 70 | mln_calcMatGranger(Resultfile,Methlogs,lfp,params); 71 | case 'FreqAH' 72 | mln_calcMatMvar(Resultfile,Methlogs,lfp,params); 73 | case 'MutualInform' 74 | mln_calcMatMITime(Resultfile,Methlogs,lfp,params); 75 | case 'TE' 76 | mln_calcMatTE(Resultfile,Methlogs,lfp,params); 77 | end 78 | end 79 | 80 | function params=initialparamsmethodsGiven(paramsfields,calParams) 81 | 82 | param_df=struct('wins',calParams.defwindow,... 83 | 'overlap',calParams.defoverlap,... 84 | 'modelOrder',calParams.defmodelorders,... 85 | 'minfreq',calParams.minfreq,'maxfreq',calParams.maxfreq,'stepfreq',calParams.stepfreq,... 86 | 'bins',calParams.defbins,... 87 | 'MaxDelay',calParams.defMaxDelay); 88 | 89 | Nparamf=length(paramsfields); 90 | paramsdata=cell(Nparamf,2); 91 | for i=1:Nparamf 92 | paramsdata{i,1}=paramsfields{i}; 93 | paramsdata{i,2}=param_df.(paramsfields{i}); 94 | end 95 | params=mln_cell2struct(paramsdata); 96 | 97 | function params=mln_cell2struct(cparams) 98 | nparams=size(cparams,1); 99 | for i=1:nparams 100 | parafiled=char(cparams(i,1)); 101 | 102 | params.(parafiled)=str2double(cparams(i,2)); 103 | 104 | end 105 | 106 | -------------------------------------------------------------------------------- /Calculation/MulanCal.m~: -------------------------------------------------------------------------------- 1 | 2 | function MulanCal(dirname,dataprenom,calParams,VGroupMethlog) 3 | % Huifang Wang, Marseille, August 18, 2013, Calculate all methods 4 | 5 | 6 | 7 | datafile=[dirname,'/data/',dataprenom,'.mat']; 8 | 9 | data=load(datafile); 10 | Params=data.Params; 11 | 12 | %% load the data 13 | 14 | if exist(datafile,'file') 15 | try 16 | prevar = load(datafile); 17 | if isstruct(prevar) 18 | fileprevar=fieldnames(prevar); 19 | iLFP=strncmpi(fileprevar,'LFP',3); 20 | if ~isempty(find(strncmpi(fileprevar,'LFP',1)==1,1)) 21 | lfp = prevar.(char(fileprevar(iLFP))); 22 | 23 | else 24 | errordlg('Which date want to process?') 25 | end 26 | 27 | if size(lfp,1)>size(lfp,2) 28 | lfp=lfp'; 29 | else 30 | lfp=lfp; 31 | end 32 | 33 | end 34 | catch ME 35 | errordlg('filename is invalid') 36 | end 37 | end 38 | 39 | if ~isempty(find(strncmpi(fileprevar,'Params',6)==1,1)) 40 | 41 | Params= prevar.Params; 42 | 43 | end 44 | 45 | if ~isempty(find(strncmpi(fileprevar,'Connectivity',12)==1,1)) 46 | 47 | ReferenceMatrix= prevar.Connectivity; 48 | 49 | end 50 | 51 | %% Calculate the 52 | 53 | %%%% Get parameters 54 | %VGroupMethlog={'TimeBasic','FreqBasic','Hsquare','Granger','FreqAH','MutualInform','TE'}; 55 | 56 | %%% Define the file to store results 57 | Ngroup=length(VGroupMethlog); 58 | for igroup=1:Ngroup 59 | GroupMethlog=VGroupMethlog{igroup}; 60 | Resultfile=[dirname,'/Results/',GroupMethlog,'_',dataprenom,'.mat']; 61 | [Methlogs,paramsfields]=setgroupmethlogparam(GroupMethlog); 62 | params=initialparamsmethodsGiven(paramsfields,calParams); 63 | params.fs=Params.fs; 64 | switch GroupMethlog 65 | case 'TimeBasic' 66 | mln_calcMatTimeBasic(Resultfile,Methlogs,lfp,params); 67 | case 'FreqBasic' 68 | mln_calcMatFreqBasic(Resultfile,Methlogs,lfp,params); 69 | case 'Hsquare' 70 | mln_calcMatH2(Resultfile,Methlogs,lfp,params); 71 | case 'Granger' 72 | mln_calcMatGranger(Resultfile,Methlogs,lfp,params); 73 | case 'FreqAH' 74 | mln_calcMatMvar(Resultfile,Methlogs,lfp,params); 75 | case 'MutualInform' 76 | mln_calcMatMITime(Resultfile,Methlogs,lfp,params); 77 | case 'TE' 78 | mln_calcMatTE(Resultfile,Methlogs,lfp,params); 79 | end 80 | end 81 | 82 | function params=initialparamsmethodsGiven(paramsfields,calParams) 83 | 84 | param_df=struct('wins',calParams.defwindow,... 85 | 'overlap',calParams.defoverlap,... 86 | 'modelOrder',calParams.defmodelorders,... 87 | 'minfreq',calParams.minfreq,'maxfreq',calParams.maxfreq,'stepfreq',calParams.stepfreq,... 88 | 'bins',calParams.defbins,... 89 | 'MaxDelay',calParams.defMaxDelay); 90 | 91 | Nparamf=length(paramsfields); 92 | paramsdata=cell(Nparamf,2); 93 | for i=1:Nparamf 94 | paramsdata{i,1}=paramsfields{i}; 95 | paramsdata{i,2}=param_df.(paramsfields{i}); 96 | end 97 | params=HF_cell2struct(paramsdata); 98 | 99 | function params=HF_cell2struct(cparams) 100 | nparams=size(cparams,1); 101 | for i=1:nparams 102 | parafiled=char(cparams(i,1)); 103 | 104 | params.(parafiled)=str2double(cparams(i,2)); 105 | 106 | end 107 | 108 | -------------------------------------------------------------------------------- /Calculation/mvfilter.m: -------------------------------------------------------------------------------- 1 | 2 | function [x,z]=mvfilter(B,A,x,z) 3 | % Multi-variate filter function 4 | % 5 | % Y = MVFILTER(B,A,X) 6 | % [Y,Z] = MVFILTER(B,A,X,Z) 7 | % 8 | % Y = MVFILTER(B,A,X) filters the data in matrix X with the 9 | % filter described by cell arrays A and B to create the filtered 10 | % data Y. The filter is a 'Direct Form II Transposed' 11 | % implementation of the standard difference equation: 12 | % 13 | % a0*Y(n) = b0*X(:,n) + b1*X(:,n-1) + ... + bq*X(:,n-q) 14 | % - a1*Y(:,n-1) - ... - ap*Y(:,n-p) 15 | % 16 | % A=[a0,a1,a2,...,ap] and B=[b0,b1,b2,...,bq] must be matrices of 17 | % size Mx((p+1)*M) and Mx((q+1)*M), respectively. 18 | % a0,a1,...,ap, b0,b1,...,bq are matrices of size MxM 19 | % a0 is usually the identity matrix I or must be invertible 20 | % X should be of size MxN, if X has size NxM a warning 21 | % is raised, and the output Y is also transposed. 22 | % 23 | % A simulated MV-AR process can be generiated with 24 | % Y = mvfilter(eye(M), [eye(M),-AR],randn(M,N)); 25 | % 26 | % A multivariate inverse filter can be realized with 27 | % [AR,RC,PE] = mvar(Y,P); 28 | % E = mvfilter([eye(M),-AR],eye(M),Y); 29 | % 30 | % see also: MVAR, FILTER 31 | 32 | % $Id: mvfilter.m 6981 2010-03-02 23:38:34Z schloegl $ 33 | % Copyright (C) 1996-2003 by Alois Schloegl 34 | % 35 | % This program is free software: you can redistribute it and/or modify 36 | % it under the terms of the GNU General Public License as published by 37 | % the Free Software Foundation, either version 3 of the License, or 38 | % (at your option) any later version. 39 | % 40 | % This program is distributed in the hope that it will be useful, 41 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 42 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 43 | % GNU General Public License for more details. 44 | % 45 | % You should have received a copy of the GNU General Public License 46 | % along with this program. If not, see . 47 | 48 | 49 | [ra, ca] = size(A); 50 | [rb, cb] = size(B); 51 | [M, N ] = size(x); 52 | 53 | if (ra~=rb), 54 | fprintf(2,'ERROR MVFILTER: number of rows of A and B do not fit\n'); 55 | return; 56 | end; 57 | if nargin<4, 58 | z = []; %zeros(M,oo); 59 | end; 60 | 61 | if (M~=ra), 62 | if (N==ra), 63 | fprintf(2,'Warning MVFILTER: dimensions fit only to transposed data. X has been transposed.\n'); 64 | x = x.'; 65 | %[x,z] = mvfilter(B,A,x,z); x = x.'; return; 66 | else 67 | fprintf(2,'ERROR MVFILTER: dimensions do not fit\n'); 68 | return; 69 | end; 70 | end; 71 | 72 | p = ca/M-1; 73 | q = cb/M-1; 74 | oo = max(p,q); 75 | 76 | if isempty(z) 77 | z = zeros(M,oo); 78 | else 79 | if any(size(z)~=[M,oo]) 80 | fprintf('Error MVFILTER: size of z does not fit\n'); 81 | [size(z),oo,M] 82 | return; 83 | end; 84 | end; 85 | 86 | %%%%% normalization to A{1}=I; 87 | if p<=q, 88 | for k=1:p, 89 | %A{k}=A{k}/A{1}; 90 | A(:,k*M+(1:M)) = A(:,k*M+(1:M)) / A(:,1:M); 91 | end; 92 | A(:,1:M) = eye(M); 93 | else 94 | for k=0:q, 95 | %B{k}=B{k}/A{1}; 96 | B(:,k*M+(1:M)) = B(:,k*M+(1:M)) / A(:,1:M); 97 | end; 98 | end; 99 | 100 | for k = 1:N, 101 | acc = B(:,1:M) * x(:,k) + z(:,1); % / A{1}; 102 | z = [z(:,2:oo), zeros(M,1)]; 103 | for l = 1:q, 104 | z(:,l) = z(:,l) + B(:,l*M+(1:M)) * x(:,k); 105 | end; 106 | for l = 1:p, 107 | z(:,l) = z(:,l) - A(:,l*M+(1:M)) * acc; 108 | end; 109 | x(:,k) = acc; 110 | end; 111 | 112 | -------------------------------------------------------------------------------- /GenerateData/mln_generate_rossler.m~: -------------------------------------------------------------------------------- 1 | % make connectivity simulations for Rossler systems 2 | %% this function is used to generate the henon map nonlinear systems with 3 | %%% noise and delay 4 | %% Huifang Wang Sep. 4, 2012 5 | function [dataname,flgLFP]=mln_generate_rossler(dirname,prename,npts,strfile,is,cs,odelay,flag_noise,SNR) 6 | dataname=[prename,'fmriCS',num2str(100*cs),'S',num2str(is),'N',num2str(T)]; 7 | filename=['./',dirname,'/data/',dataname,'.mat']; 8 | [cdata] = imread('MULANLOGO.png'); 9 | if exist(filename,'file') 10 | 11 | msgbox('Data already there','Success','custom',cdata); 12 | else 13 | if ~exist(dirname,'dir') 14 | mkdir(dirname); 15 | end 16 | datadir=[dirname,'/data']; 17 | if ~exist(datadir,'dir') 18 | mkdir(datadir); 19 | end 20 | % delaydelay =0 default 21 | flgLFP=1; 22 | 23 | load(strfile,'PGS'); 24 | %Nglist=length(PGS); 25 | 26 | Astru=PGS{is}; 27 | SparseA=sparse(Astru(1,:),Astru(2,:),1); 28 | P.A=full(SparseA); 29 | nchan=max(max(Astru)); 30 | P.A(nchan,nchan)=0; 31 | P.A=P.A*cs; 32 | 33 | %flag_noise=0; 34 | %SNR=20; 35 | startTime=100; 36 | ofs=100; % original sample frenquecy which depends on the ode RelTol 37 | CM=P.A; 38 | 39 | DelayV=ones(5)*odelay;%% without the delay 40 | %DelayV=[0,0,30,0,0 ;30,0,0,0,0;0,30,0,0,0;0,0,0,0,50;0,0,0,0,0];% rossler 9,11,12,13 41 | odelay=max(max(DelayV)); 42 | C2=insertdelay(CM,DelayV); 43 | 44 | 45 | X0=zeros(3*nchan,1)'; 46 | a=0.15; 47 | b=0.2; 48 | c=10; 49 | % d=ones(nchan,1)+0.05*rand(nchan,1); 50 | %d=[1+0.015,1-0.015,1,1+0.01,1-0.01]; % systems with 5 channels to rossler 1-6; 51 | %d=[1+0.01,1+0.005,1,1-0.01,1-0.015]; % systems with 5 channels to rossler 7-12; 52 | if mod(nchan,2) 53 | d=1+randi([-100 100],1,nchan)/1000; 54 | else 55 | d=[1+randi([1 100],1,nchan/2)/1000,1-randi([1 2],1,nchan/2)/1000]; 56 | end 57 | 58 | CM=C2*cs; 59 | dt=1/ofs; 60 | p=struct('a',a,'b',b,'c',c,'d',d); 61 | %%%%%%%%%%%%%Generate the data%%%%% 62 | %odeoptions=odeset('RelTol',1e-3); 63 | %[T, X] = ode15s(@(T,X)rossler(T,X,a,b,c,d,CM,flag_noise,SNR),[0, SimulationTime],X0,odeoptions); 64 | T=0:dt:npts; 65 | NT=length(T); 66 | X=zeros(3*nchan,NT); 67 | if odelay==0 68 | for iT=2:NT 69 | X0=X(:,iT-1); 70 | f=rosslerN(p,CM,X0,flag_noise,SNR); 71 | X(:,iT)=X(:,iT-1)+f*dt; 72 | end 73 | else 74 | for iT=1+odelay:NT 75 | X0=X(:,iT-odelay:iT-1); 76 | f=rosslerN(p,CM,X0,flag_noise,SNR); 77 | X(:,iT)=X(:,iT-1)+f*dt; 78 | end 79 | end 80 | %%%%%%%%%%%%%%%%%%%%%% 81 | startT=find(T>startTime,1); 82 | T=T(startT:end)-startTime; 83 | X=X(:,startT:end); 84 | Y=X(((1:nchan)-1)*3+1,:); 85 | 86 | TotalTime=npts-startTime; 87 | %% save the data 88 | LFP=Y; 89 | dataname=[prename,'CS',num2str(100*cs),'S',num2str(is)]; 90 | 91 | if ~isempty(find(isnan(max(LFP))==1)) || ~isempty(find(LFP>1000)) 92 | flgLFP=0; 93 | return; 94 | end 95 | 96 | 97 | Connectivity=P.A; 98 | Params.npts= TotalTime*ofs; 99 | Params.fs=ofs; 100 | Params.model.abc=[a, b,c]; 101 | Params.model.d=d; 102 | Params.flag_noise=flag_noise; 103 | Params.delay=DelayV; 104 | Params.SNR=SNR; 105 | AllState.X=X; 106 | AllState.T=T; 107 | 108 | save(['./',dirname,'/data/',dataname,'.mat'],'LFP','Connectivity','Params'); 109 | 110 | function f=rosslerN(p,CM,X0,flag_noise,SNR) 111 | a=p.a; 112 | b=p.b; 113 | c=p.c; 114 | d=p.d; 115 | [nchan,nchandelay]=size(CM); 116 | norder=nchandelay/nchan; 117 | f=zeros(nchan*3,1); 118 | Anoise=1/10^(SNR/20); 119 | Xd=fliplr(X0); 120 | X=X0(:,end); 121 | 122 | for ichan=1:nchan 123 | dxji=bsxfun(@minus,Xd(((1:nchan)-1)*3+1,:), X((ichan-1)*3+1)); 124 | dxji=reshape(dxji,nchan*norder,1); 125 | f((ichan-1)*3+1)=-d(ichan)*X((ichan-1)*3+2)-X((ichan-1)*3+3)+CM(ichan,:)*dxji+flag_noise*Anoise*X((ichan-1)*3+1)*rand(1); 126 | f((ichan-1)*3+2)=d(ichan)*X((ichan-1)*3+1)+a*X((ichan-1)*3+2); 127 | f((ichan-1)*3+3)=b+X((ichan-1)*3+3)*(X((ichan-1)*3+1)-c); 128 | end 129 | 130 | function C2=insertdelay(C1,DelayV) 131 | odelay=max(max(DelayV)); 132 | if odelay==0 133 | C2=C1; 134 | return; 135 | end 136 | nchan=size(C1,1); 137 | 138 | C2=zeros(nchan,odelay*nchan); 139 | for i=1:odelay 140 | [row,col]=find(DelayV==i); 141 | C0=zeros(nchan,nchan); 142 | C0(row,col)=C1(row,col); 143 | C2(:,(i-1)*nchan+1:i*nchan)=C0; 144 | end -------------------------------------------------------------------------------- /GenerateData/mln_generate_rossler.m: -------------------------------------------------------------------------------- 1 | % make connectivity simulations for Rossler systems 2 | %% this function is used to generate the henon map nonlinear systems with 3 | %%% noise and delay 4 | %% Huifang Wang Sep. 4, 2012 5 | function [dataname,flgLFP]=mln_generate_rossler(dirname,prename,npts,strfile,is,cs,odelay,flag_noise,SNR) 6 | dataname=[prename,'rosslerCS',num2str(100*cs),'S',num2str(is),'N',num2str(npts)]; 7 | filename=['./',dirname,'/data/',dataname,'.mat']; 8 | [cdata] = imread('MULANLOGO.png'); 9 | if exist(filename,'file') 10 | 11 | msgbox('Data already there','Success','custom',cdata); 12 | else 13 | if ~exist(dirname,'dir') 14 | mkdir(dirname); 15 | end 16 | datadir=[dirname,'/data']; 17 | if ~exist(datadir,'dir') 18 | mkdir(datadir); 19 | end 20 | % delaydelay =0 default 21 | flgLFP=1; 22 | 23 | load(strfile,'PGS'); 24 | %Nglist=length(PGS); 25 | 26 | Astru=PGS{is}; 27 | SparseA=sparse(Astru(1,:),Astru(2,:),1); 28 | P.A=full(SparseA); 29 | nchan=max(max(Astru)); 30 | P.A(nchan,nchan)=0; 31 | P.A=P.A*cs; 32 | 33 | %flag_noise=0; 34 | %SNR=20; 35 | startTime=100; 36 | ofs=100; % original sample frenquecy which depends on the ode RelTol 37 | CM=P.A; 38 | 39 | DelayV=ones(5)*odelay;%% without the delay 40 | %DelayV=[0,0,30,0,0 ;30,0,0,0,0;0,30,0,0,0;0,0,0,0,50;0,0,0,0,0];% rossler 9,11,12,13 41 | odelay=max(max(DelayV)); 42 | C2=insertdelay(CM,DelayV); 43 | 44 | 45 | X0=zeros(3*nchan,1)'; 46 | a=0.15; 47 | b=0.2; 48 | c=10; 49 | % d=ones(nchan,1)+0.05*rand(nchan,1); 50 | %d=[1+0.015,1-0.015,1,1+0.01,1-0.01]; % systems with 5 channels to rossler 1-6; 51 | %d=[1+0.01,1+0.005,1,1-0.01,1-0.015]; % systems with 5 channels to rossler 7-12; 52 | if mod(nchan,2) 53 | d=1+randi([-100 100],1,nchan)/1000; 54 | else 55 | d=[1+randi([1 100],1,nchan/2)/1000,1-randi([1 2],1,nchan/2)/1000]; 56 | end 57 | 58 | CM=C2*cs; 59 | dt=1/ofs; 60 | p=struct('a',a,'b',b,'c',c,'d',d); 61 | %%%%%%%%%%%%%Generate the data%%%%% 62 | %odeoptions=odeset('RelTol',1e-3); 63 | %[T, X] = ode15s(@(T,X)rossler(T,X,a,b,c,d,CM,flag_noise,SNR),[0, SimulationTime],X0,odeoptions); 64 | T=0:dt:npts; 65 | NT=length(T); 66 | X=zeros(3*nchan,NT); 67 | if odelay==0 68 | for iT=2:NT 69 | X0=X(:,iT-1); 70 | f=rosslerN(p,CM,X0,flag_noise,SNR); 71 | X(:,iT)=X(:,iT-1)+f*dt; 72 | end 73 | else 74 | for iT=1+odelay:NT 75 | X0=X(:,iT-odelay:iT-1); 76 | f=rosslerN(p,CM,X0,flag_noise,SNR); 77 | X(:,iT)=X(:,iT-1)+f*dt; 78 | end 79 | end 80 | %%%%%%%%%%%%%%%%%%%%%% 81 | startT=find(T>startTime,1); 82 | T=T(startT:end)-startTime; 83 | X=X(:,startT:end); 84 | Y=X(((1:nchan)-1)*3+1,:); 85 | 86 | TotalTime=npts-startTime; 87 | %% save the data 88 | LFP=Y; 89 | dataname=[prename,'CS',num2str(100*cs),'S',num2str(is)]; 90 | 91 | if ~isempty(find(isnan(max(LFP))==1)) || ~isempty(find(LFP>1000)) 92 | flgLFP=0; 93 | return; 94 | end 95 | 96 | 97 | Connectivity=P.A; 98 | Params.npts= TotalTime*ofs; 99 | Params.fs=ofs; 100 | Params.model.abc=[a, b,c]; 101 | Params.model.d=d; 102 | Params.flag_noise=flag_noise; 103 | Params.delay=DelayV; 104 | Params.SNR=SNR; 105 | AllState.X=X; 106 | AllState.T=T; 107 | 108 | save(filename,'LFP','Connectivity','Params'); 109 | msgbox('Data Generated','Success','custom',cdata); 110 | 111 | end 112 | function f=rosslerN(p,CM,X0,flag_noise,SNR) 113 | a=p.a; 114 | b=p.b; 115 | c=p.c; 116 | d=p.d; 117 | [nchan,nchandelay]=size(CM); 118 | norder=nchandelay/nchan; 119 | f=zeros(nchan*3,1); 120 | Anoise=1/10^(SNR/20); 121 | Xd=fliplr(X0); 122 | X=X0(:,end); 123 | 124 | for ichan=1:nchan 125 | dxji=bsxfun(@minus,Xd(((1:nchan)-1)*3+1,:), X((ichan-1)*3+1)); 126 | dxji=reshape(dxji,nchan*norder,1); 127 | f((ichan-1)*3+1)=-d(ichan)*X((ichan-1)*3+2)-X((ichan-1)*3+3)+CM(ichan,:)*dxji+flag_noise*Anoise*X((ichan-1)*3+1)*rand(1); 128 | f((ichan-1)*3+2)=d(ichan)*X((ichan-1)*3+1)+a*X((ichan-1)*3+2); 129 | f((ichan-1)*3+3)=b+X((ichan-1)*3+3)*(X((ichan-1)*3+1)-c); 130 | end 131 | 132 | function C2=insertdelay(C1,DelayV) 133 | odelay=max(max(DelayV)); 134 | if odelay==0 135 | C2=C1; 136 | return; 137 | end 138 | nchan=size(C1,1); 139 | 140 | C2=zeros(nchan,odelay*nchan); 141 | for i=1:odelay 142 | [row,col]=find(DelayV==i); 143 | C0=zeros(nchan,nchan); 144 | C0(row,col)=C1(row,col); 145 | C2(:,(i-1)*nchan+1:i*nchan)=C0; 146 | end -------------------------------------------------------------------------------- /GenerateData/spm_erp_L.m: -------------------------------------------------------------------------------- 1 | function [L] = spm_erp_L(P,M) 2 | % returns [projected] lead field L as a function of position and moments 3 | % FORMAT [L] = spm_erp_L(P,M) 4 | % P - model parameters 5 | % M - model specification 6 | % L - lead field 7 | %__________________________________________________________________________ 8 | % 9 | % The lead field (L) is constructed using the specific parameters in P and, 10 | % where necessary information in the dipole structure M.dipfit. For ECD 11 | % models P.Lpos and P.L encode the position and moments of the ECD. The 12 | % field M.dipfit.type: 13 | % 14 | % 'ECD', 'LFP' or 'IMG' 15 | % 16 | % determines whether the model is ECD or not. For imaging reconstructions 17 | % the paramters P.L are a (m x n) matrix of coefficients that scale the 18 | % contrition of n sources to m = M.dipfit.Nm modes encoded in M.dipfit.G. 19 | % 20 | % For LFP models (the default) P.L simply encodes the electrode gain for 21 | % each source contributing a LFP. 22 | % 23 | % see; Kiebel et al. (2006) NeuroImage 24 | %__________________________________________________________________________ 25 | % Copyright (C) 2005 Wellcome Trust Centre for Neuroimaging 26 | 27 | % Karl Friston 28 | % $Id: spm_erp_L.m 4336 2011-05-31 16:49:34Z rosalyn $ 29 | 30 | % Create a persient variable that rembers the last locations 31 | %-------------------------------------------------------------------------- 32 | persistent LastLpos LastL 33 | 34 | 35 | % type of spatial model and modality 36 | %========================================================================== 37 | try, type = M.dipfit.type; catch, type = 'LFP'; end 38 | 39 | switch type 40 | 41 | % parameterised lead field - ECD 42 | %---------------------------------------------------------------------- 43 | case{'ECD'} 44 | 45 | % number of sources - n 46 | %------------------------------------------------------------------ 47 | n = size(P.L,2); 48 | 49 | % re-compute lead field only if any dipoles changed 50 | %---------------------------------------------------------- 51 | try 52 | Id = find(any(LastLpos ~= P.Lpos)); 53 | catch 54 | Id = 1:n; 55 | end 56 | 57 | % record new spatial parameters 58 | %---------------------------------------------------------- 59 | LastLpos = P.Lpos; 60 | for i = Id 61 | if any(P.Lpos(:,i)>=200) 62 | Lf = zeros(M.dipfit.Nc, 3); 63 | else 64 | Lf = ft_compute_leadfield(transform_points(M.dipfit.datareg.fromMNI, P.Lpos(:,i)'), M.dipfit.sens, M.dipfit.vol); 65 | end 66 | LastL(:,:,i) = Lf; 67 | end 68 | G = spm_cond_units(LastL); 69 | for i = 1:n 70 | L(:,i) = G(:,:,i)*P.L(:,i); 71 | end 72 | 73 | % Imaging solution {specified in M.dipfit.G} 74 | %---------------------------------------------------------------------- 75 | case{'IMG'} 76 | 77 | % number of sources - n 78 | %------------------------------------------------------------------ 79 | n = size(P.L,2); 80 | 81 | % re-compute lead field only if any coeficients have changed 82 | %------------------------------------------------------------------ 83 | try 84 | Id = find(any(LastLpos ~= P.L)); 85 | catch 86 | Id = 1:n; 87 | end 88 | for i = Id 89 | LastL(:,i) = M.dipfit.G{i}*P.L(:,i); 90 | end 91 | 92 | % record new spatial parameters 93 | %------------------------------------------------------------------ 94 | LastLpos = P.L; 95 | L = LastL; 96 | 97 | % LFP electrode gain 98 | %---------------------------------------------------------------------- 99 | case{'LFP'} 100 | m = length(P.L); 101 | try 102 | n = M.dipfit.Ns; 103 | catch 104 | n = m; 105 | end 106 | L = sparse(1:m,1:m,P.L,m,n); 107 | 108 | otherwise 109 | warndlg('unknown spatial model') 110 | end 111 | 112 | % ------------------------------------------------------------------------- 113 | function new = transform_points(M, old) 114 | old(:,4) = 1; 115 | new = old * M'; 116 | new = new(:,1:3); 117 | -------------------------------------------------------------------------------- /Calculation/awt_freqlist.m: -------------------------------------------------------------------------------- 1 | function [wt,freqlist,psi_array] = awt_freqlist(x,Fs,freqlist,type,xi) 2 | % awt_freqlist analytical wavelet transform, where one can specify the list of desired frequencies 3 | % 4 | % [wt,freqlist,psi_array] = awt_freqlist(x,Fs,freqlist,type,xi) 5 | % 6 | % Inputs: 7 | % x the signal to be analyzed 8 | % Fs the sampling frequency 9 | % freqlist list of frequencies at which to compute wt (optional) 10 | % (or set to [] for automatic definition) 11 | % type type of wavelet to use (Gabor, Lusin or Sombrero) 12 | % xi the number of oscillations parameter 13 | % Outputs: 14 | % wt: time-frequency image 15 | % freqlist: useful in case of automatic definition of frequencies 16 | % psi_array : array of analysis functions (complex values) 17 | % 18 | % Maureen Clerc, Christian Benar, october 2007 19 | % modified from awt from wavelab toolbox 20 | 21 | % History of changes 22 | % 1/11/2007: (cgb) psi_array: output in complex 23 | % 3/06/2008: (cgb) init of psi_array to size of wt 24 | 25 | n = length(x); 26 | sigma2 = 1; 27 | x = x(:); 28 | omega = [(0:n/2) (-ceil(n/2)+1:-1)].*Fs/n; % CGB added ceil: TO BE CHECKED 29 | omega = omega(:); 30 | 31 | fftx = fft(x); 32 | 33 | % to compute min and max center frequency values: 34 | %tolerance = 1.5; % such that an acceptable "zero" is exp(-tolerance^2/2) 35 | tolerance = 0.5; % cgb 36 | %tolerance = 1; % cgb 37 | 38 | if nargin<2 39 | Fs = 1; 40 | end 41 | if nargin<4 42 | type = 'Gabor'; 43 | end 44 | if nargin<5 45 | xi = 5; % only useful for Gabor 46 | end 47 | 48 | % compute min and max valid center frequencies, according to wavelet type 49 | switch(type) 50 | case 'Gabor' 51 | mincenterfreq = 2*tolerance*sqrt(sigma2)*Fs*xi./n; 52 | maxcenterfreq = Fs*xi/(xi+tolerance/sqrt(sigma2)); 53 | case 'Lusin1' 54 | % to be computed 55 | case 'Sombrero' 56 | [mincenterfreq,maxcenterfreq] = FindSombreroBounds(tolerance,sigma2,n,Fs); 57 | end 58 | if (nargin<3 || isempty(freqlist) ) 59 | nvoice = 12; 60 | freqlist= 2.^(log2(mincenterfreq):1/nvoice:log2(maxcenterfreq)); 61 | end 62 | 63 | switch(type) 64 | case 'Gabor' 65 | s_array = xi./freqlist; 66 | minscale = xi./maxcenterfreq; 67 | maxscale = xi./mincenterfreq; 68 | case 'Lusin1' 69 | % to be computed 70 | case 'Sombrero' 71 | s_array = sqrt(2/sigma2)./freqlist; 72 | minscale = sqrt(2/sigma2)/maxcenterfreq; 73 | maxscale = sqrt(2/sigma2)/mincenterfreq; 74 | end 75 | nscale = length(freqlist); 76 | wt = zeros(n,nscale); 77 | scaleindices=find(s_array(:)'>=minscale & s_array(:)'<=maxscale); 78 | %psi_array=zeros(n,length(scaleindices)); 79 | psi_array=zeros(n,nscale); 80 | for kscale=scaleindices 81 | s=s_array(kscale); 82 | switch(type) 83 | case 'Gabor' 84 | freq = (s .* omega - xi); 85 | Psi = realpow(4.*pi.*sigma2,1/4)*sqrt(s) *exp(-sigma2/2*freq.*freq); 86 | 87 | % Psi = Psi .* (omega>0); 88 | case 'Lusin1' 89 | % to be completed 90 | case 'Sombrero' 91 | freq = s.*omega; 92 | Psi = -realpow(pi*sigma2^5,1/4)*sqrt(8/3)*freq.^2.*sqrt(s).*exp(-sigma2/2*freq.*freq); 93 | Psi = Psi .* (omega>0); 94 | end; 95 | 96 | wt(1:n,kscale) = ifft(fftx.*Psi); 97 | psi_array(:,kscale)=ifft(Psi); 98 | end 99 | 100 | 101 | function [mincenterfreq,maxcenterfreq] = FindSombreroBounds(tol,sigma2,n,Fs) 102 | s = 0.02; % an intermediate scale according to which the min and max scale will be computed 103 | t = (1:n)/Fs./s; 104 | psi = 2*realpow(pi,-1/4)/sqrt(3).*(t.^2-1).*exp(-t.^2./(2*sigma2)); 105 | psi = psi./max(psi); 106 | % in the decreasing part of psi, find first sub-threshold 107 | i = find(abs(psi)exp(-tol^2/2) & hatpsi-circshift(hatpsi,[0 1])<0,1,'last'); 114 | smin = i/(n/2)*s; %l'echelle min a laquelle le sombrero ne sort pas de la fenetre frequentielle 115 | maxcenterfreq = sqrt(2/sigma2)/smin; 116 | -------------------------------------------------------------------------------- /GenerateData/spm_lfp_priors.m: -------------------------------------------------------------------------------- 1 | function [E,V] = spm_lfp_priors(A,B,C) 2 | % prior moments for a neural mass model of ERPs 3 | % FORMAT [pE,pC] = spm_lfp_priors(A,B,C) 4 | % 5 | % A{3},B{m},C - binary constraints on extrinsic connectivity 6 | % 7 | % pE - prior expectation 8 | % 9 | % synaptic parameters 10 | %-------------------------------------------------------------------------- 11 | % pE.T - synaptic time constants 12 | % pE.H - synaptic densities 13 | % pE.R - activation function parameters 14 | % 15 | % connectivity parameters 16 | %-------------------------------------------------------------------------- 17 | % pE.A - extrinsic - coupling 18 | % pE.B - extrinsic - trial-dependent 19 | % pE.C - extrinsic - stimulus input 20 | % pE.G - intrinsic 21 | % pE.D - extrinsic delays 22 | % pE.I - intrinsic delays 23 | % 24 | %-------------------------------------------------------------------------- 25 | % 26 | % pC - prior (co)variances 27 | % 28 | % Because priors are specified under log normal assumptions, most 29 | % parameters are simply scaling coefficients with a prior expectation 30 | % and variance of one. After log transform this renders pE = 0 and 31 | % pC = 1; The prior expectations of what they scale are specified in 32 | % spm_lfp_fx 33 | %__________________________________________________________________________ 34 | % 35 | % David O, Friston KJ (2003) A neural mass model for MEG/EEG: coupling and 36 | % neuronal dynamics. NeuroImage 20: 1743-1755 37 | %__________________________________________________________________________ 38 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 39 | 40 | % Karl Friston 41 | % $Id: spm_lfp_priors.m 4096 2010-10-22 19:40:34Z karl $ 42 | 43 | % defaults 44 | %-------------------------------------------------------------------------- 45 | if nargin < 3 % a single source model 46 | A = {0 0 0}; 47 | B = {0}; 48 | C = 1; 49 | end 50 | n = size(C,1); % number of sources 51 | 52 | % disable log zero warning 53 | %-------------------------------------------------------------------------- 54 | warning('off','MATLAB:log:logOfZero'); 55 | 56 | % parameters for neural-mass forward model 57 | %========================================================================== 58 | 59 | % sigmoid parameters 60 | %-------------------------------------------------------------------------- 61 | E.R = [0 0]; V.R = [1 1]/8; 62 | 63 | % set intrinsic [excitatory] time constants 64 | %-------------------------------------------------------------------------- 65 | E.T = log(ones(n,2)); V.T = ones(n,2)/8; % time constants 66 | E.H = log(ones(n,1)); V.H = ones(n,1)/16; % synaptic density 67 | 68 | % set intrinsic connections 69 | %-------------------------------------------------------------------------- 70 | E.G = log(ones(n,5)); V.G = ones(n,5)/16; % intrinsic connections 71 | 72 | 73 | % set extrinsic connectivity 74 | %-------------------------------------------------------------------------- 75 | Q = sparse(n,n); 76 | i=1; 77 | E.A{i} = log(A{i} + eps); % forward 78 | V.A{i} = A{i}/2; % backward 79 | Q = Q | A{i}; 80 | 81 | for i = 2:length(A) 82 | A{i} = ~~A{i}; 83 | E.A{i} = log(A{i} + eps); % forward 84 | V.A{i} = A{i}/2; % backward 85 | Q = Q | A{i}; % and lateral connections 86 | end 87 | 88 | for i = 1:length(B) 89 | B{i} = ~~B{i}; 90 | E.B{i} = 0*B{i}; % input-dependent scaling 91 | V.B{i} = B{i}/2; 92 | Q = Q | B{i}; 93 | end 94 | C = ~~C; 95 | E.C = C*32 - 32; % where inputs enter 96 | V.C = C/32; 97 | 98 | % set delay 99 | %-------------------------------------------------------------------------- 100 | E.D = sparse(n,n); V.D = Q/16; % extrinsic delays 101 | E.I = 0; V.I = 1/32; % intrinsic delays 102 | warning('on','MATLAB:log:logOfZero'); 103 | 104 | 105 | return 106 | 107 | % demo for log-normal pdf 108 | %-------------------------------------------------------------------------- 109 | x = [1:64]/16; 110 | for i = [2 16] 111 | v = 1/i; 112 | p = 1./x.*exp(-log(x).^2/(2*v))/sqrt(2*pi*v); 113 | plot(x,p) 114 | text(x(16),p(16),sprintf('variance = 1/%i',1/v)) 115 | hold on 116 | end 117 | xlabel('scaling') 118 | ylabel('density') 119 | grid on 120 | hold off 121 | -------------------------------------------------------------------------------- /Calculation/cca_partialgc.m: -------------------------------------------------------------------------------- 1 | function ret = cca_partialgc(X,nlags,STATFLAG) 2 | % ----------------------------------------------------------------------- 3 | % FUNCTION: cca_partialgc.m 4 | % PURPOSE: perform multivariate regression with partial granger 5 | % causality 6 | % 7 | % INPUT: X - nvar (rows) by nobs (cols) observation matrix 8 | % NLAGS - number of lags to include in model 9 | % STATFLAG - do whiteness test (1) or not (0) 10 | % 11 | % OUTPUT: ret.gc - standard conditional Granger causality 12 | % ret.fg - Partial Granger causality 13 | % ret.doifg - difference of influence (for partial) 14 | % ret.waut - Durbin-Watson residual autocorrelation sig value 15 | % ret.cons - model consistency (Ding et al 2000 method) 16 | % 17 | % This function is based on original code provided by S. Guo, first 18 | % author of the below paper 19 | % 20 | % REF: Guo, S., Seth, A.K., Kendrick, K., Zhou, C., and Feng, J. (2008). 21 | % Partial Granger causality: Eliminating exogenous inputs and latent variables. 22 | % Journal of Neuroscience Methods. 172(1):79-93. 23 | % 24 | % NOTE: statistical distribution for partial granger is not known, 25 | % bootstrapping/surrogate methods must be used to assess significance. 26 | % 27 | % AKS Apr 01 2009 28 | % Updated AKS Aug 2009 to implement whiteness/consistency test 29 | % COPYRIGHT NOTICE AT BOTTOM 30 | % ----------------------------------------------------------------------- 31 | 32 | % figure regression parameters 33 | nobs = size(X,2); 34 | nvar = size(X,1); 35 | if(nvar>nobs) error('error in cca_partialgc: nvar>nobs, check input matrix'); end 36 | 37 | % remove sample means if present (no constant terms in this regression) 38 | m = mean(X'); 39 | if(abs(sum(m)) > 0.0001) 40 | mall = repmat(m',1,nobs); 41 | X = X-mall; 42 | end 43 | 44 | % loop through variables 45 | GC = zeros(nvar); 46 | %GC = GC.*NaN; 47 | FG = zeros(nvar); 48 | %FG = FG.*NaN; 49 | doi = zeros(nvar); 50 | for i=1:nvar-1 51 | for j=i+1:nvar 52 | B=X; 53 | L=ones(size(X)); % Huifang Wang modified for the case there is 0 in the signals 54 | L(i,:)=0; 55 | L(j,:)=0; 56 | L=logical(L); 57 | %B(i,:)=0; 58 | %B(j,:)=0; 59 | %L=B~=0; 60 | Z_remain=reshape(B(L),(nvar-2),nobs); 61 | Z1=[X(i,:);X(j,:);Z_remain]; 62 | Z2=[X(j,:);X(i,:);Z_remain]; 63 | Z1_delete=[Z1(1,:);Z1((3:nvar),:)]; 64 | Z2_delete=[Z2(1,:);Z2((3:nvar),:)]; 65 | [GC(i,j) FG(i,j)] = cond_gc(Z1,Z1_delete,nobs,nvar,nlags); 66 | [GC(j,i) FG(j,i)] = cond_gc(Z2,Z2_delete,nobs,nvar,nlags); 67 | doi(i,j) = FG(i,j)-FG(j,i); 68 | doi(j,i) = FG(j,i)-FG(i,j); 69 | end 70 | end 71 | ret.gc = GC; 72 | ret.fg = FG; 73 | ret.doifg = doi; 74 | 75 | if STATFLAG, 76 | T = cca_regress(X,nlags,1); 77 | ret.waut = T.waut; 78 | ret.cons = T.cons; 79 | else 80 | ret.waut = -1; 81 | ret.cons = -1; 82 | end 83 | 84 | 85 | %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 86 | function [gc,fg] = cond_gc(X,Xr,nobs,nvar,nlags) 87 | 88 | ret1 = cca_regress(X,nlags); 89 | ret2 = cca_regress(Xr,nlags); 90 | Su = ret1.Z; % unrestricted, sigma 91 | Sr = ret2.Z; % restricted, S 92 | 93 | % coefficients of noise covariance matrix for restricted regression 94 | S_11 = [Sr(1,1)]; 95 | S_12 = [Sr(1,2:(nvar-1))]; 96 | S_21 = [Sr(2:(nvar-1),1)]; 97 | S_22 = [Sr(2:(nvar-1),2:(nvar-1))]; 98 | 99 | % coefficients of noise covariance matrix for unrestricted regression 100 | sigma_11 = [Su(1,1)]; 101 | sigma_12 = [Su(1,3:nvar)]; 102 | sigma_21 = [Su(3:nvar,1)]; 103 | sigma_22 = [Su(3:nvar,3:nvar)]; 104 | 105 | % standard conditional GC 106 | gc = log(S_11/sigma_11); 107 | 108 | % partial GC 109 | fg = log(det(S_11-S_12*inv(S_22)*S_21)/det(sigma_11-sigma_12*inv(sigma_22)*sigma_21)); 110 | 111 | 112 | % This file is part of GCCAtoolbox. 113 | % It is Copyright (C) Anil Seth (2007-2009) and S. Guo 114 | % 115 | % GCCAtoolbox is free software: you can redistribute it and/or modify 116 | % it under the terms of the GNU General Public License as published by 117 | % the Free Software Foundation, either version 3 of the License, or 118 | % (at your option) any later version. 119 | % 120 | % GCCAtoolbox is distributed in the hope that it will be useful, 121 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 122 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 123 | % GNU General Public License for more details. 124 | % 125 | % You should have received a copy of the GNU General Public License 126 | % along with GCCAtoolbox. If not, see . 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | -------------------------------------------------------------------------------- /GenerateData/spm_L_priors.m: -------------------------------------------------------------------------------- 1 | function [pE,pC] = spm_L_priors(dipfit,pE,pC) 2 | % prior moments for the lead-field parameters of ERP models 3 | % FORMAT [pE,pC] = spm_L_priors(dipfit) 4 | % 5 | % dipfit - forward model structure: 6 | % 7 | % dipfit.type - 'ECD', 'LFP' or 'IMG' 8 | % dipfit.symmetry - distance (mm) for symmetry constraints (ECD) 9 | % dipfit.location - allow changes in source location (ECD) 10 | % dipfit.Lpos - x,y,z source positions (mm) (ECD) 11 | % dipfit.Nm - number of modes (IMG) 12 | % dipfit.Ns - number of sources 13 | % dipfit.Nc - number of channels 14 | % 15 | % pE - prior expectation 16 | % pC - prior covariance 17 | % 18 | % adds spatial parameters 19 | %-------------------------------------------------------------------------- 20 | % pE.Lpos - position - ECD 21 | % pE.L - orientation - ECD 22 | % coefficients of local modes - Imaging 23 | % gain of electrodes - LFP 24 | % pE.J - contributing states (length(J) = number of states per source 25 | % 26 | %__________________________________________________________________________ 27 | % 28 | % David O, Friston KJ (2003) A neural mass model for MEG/EEG: coupling and 29 | % neuronal dynamics. NeuroImage 20: 1743-1755 30 | %__________________________________________________________________________ 31 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 32 | 33 | % Karl Friston 34 | % $Id: spm_L_priors.m 4348 2011-06-10 20:50:23Z karl $ 35 | 36 | % defaults 37 | %-------------------------------------------------------------------------- 38 | try, model = dipfit.model; catch, model = 'LFP'; end 39 | try, type = dipfit.type; catch, type = 'LFP'; end 40 | try, location = dipfit.location; catch, location = 0; end 41 | try, symmetry = dipfit.symmetry; catch, symmetry = 0; end 42 | try, pC; catch, pC = []; end 43 | 44 | 45 | % number of sources 46 | %-------------------------------------------------------------------------- 47 | try 48 | n = dipfit.Ns; 49 | m = dipfit.Nc; 50 | catch 51 | n = dipfit; 52 | m = n; 53 | end 54 | 55 | % location priors (4 mm) 56 | %-------------------------------------------------------------------------- 57 | if location, V = 2^2; else, V = 0; end 58 | 59 | % parameters for electromagnetic forward model 60 | %========================================================================== 61 | switch type 62 | 63 | case{'ECD'} % mean and variance 64 | %------------------------------------------------------------------ 65 | pE.Lpos = dipfit.Lpos; pC.Lpos = ones(3,n)*V; % positions 66 | pE.L = sparse(3,n); pC.L = ones(3,n)*exp(8); % orientations 67 | 68 | case{'IMG'} 69 | %------------------------------------------------------------------ 70 | m = dipfit.Nm; % number modes 71 | pE.Lpos = sparse(3,0); pC.Lpos = sparse(3,0); % positions 72 | pE.L = sparse(m,n); pC.L = ones(m,n)*exp(8); % modes 73 | 74 | case{'LFP'} 75 | %------------------------------------------------------------------ 76 | pE.Lpos = sparse(3,0); pC.Lpos = sparse(3,0); % positions 77 | pE.L = ones(1,m); pC.L = ones(1,m)*64; % gains 78 | 79 | otherwise 80 | warndlg('Unknown spatial model') 81 | 82 | end 83 | 84 | % contributing states (encoded in J) 85 | %========================================================================== 86 | switch model 87 | 88 | case{'ERP','SEP'} 89 | %------------------------------------------------------------------ 90 | pE.J = sparse(1,[1 7 9],[0.2 0.2 0.6],1,9); % 9 states 91 | pC.J = pE.J/16; 92 | 93 | case{'CMC'} 94 | %------------------------------------------------------------------ 95 | pE.J = sparse(1,[1 3 7],[0.2 0.8 0.2],1,8); % 8 states 96 | pC.J = sparse(1,[3 7],1,1,8)/16; 97 | 98 | case{'LFP'} 99 | %------------------------------------------------------------------ 100 | pE.J = sparse(1,[1 7 9],[0.2 0.2 0.6],1,13); % 13 states 101 | pC.J = pE.J/16; 102 | 103 | case{'NMM'} 104 | %------------------------------------------------------------------ 105 | pE.J = sparse(1,[1,2,3],[0.1 0.1 1],1,9); % 9 states 106 | pC.J = sparse(1,[1,2],[1/32 1/128],1,9); 107 | 108 | case{'MFM'} 109 | %------------------------------------------------------------------ 110 | pE.J = sparse(1,[1,2,3],[0.1 0.1 1],1,36); % 36 states = 111 | pC.J = sparse(1,[1,2],[1/64 1/128],1,36); % 9 1st + 27 2nd 112 | 113 | case{'DEM','NFM'} 114 | %------------------------------------------------------------------ 115 | pE.J = []; % null 116 | pC.J = []; 117 | 118 | 119 | otherwise 120 | warndlg('Unknown neural model') 121 | 122 | end 123 | -------------------------------------------------------------------------------- /GenerateData/spm_int_L.m: -------------------------------------------------------------------------------- 1 | function [y] = spm_int_L(P,M,U) 2 | % integrates a MIMO nonlinear system using a fixed Jacobian: J(x(0)) 3 | % FORMAT [y] = spm_int_L(P,M,U) 4 | % P - model parameters 5 | % M - model structure 6 | % U - input structure or matrix 7 | % 8 | % y - (v x l) response y = g(x,u,P) 9 | %__________________________________________________________________________ 10 | % Integrates the MIMO system described by 11 | % 12 | % dx/dt = f(x,u,P,M) 13 | % y = g(x,u,P,M) 14 | % 15 | % using the update scheme: 16 | % 17 | % x(t + dt) = x(t) + U*dx(t)/dt 18 | % 19 | % U = (expm(dt*J) - I)*inv(J) 20 | % J = df/dx 21 | % 22 | % at input times. This integration scheme evaluates the update matrix (U) 23 | % at the expansion point 24 | % 25 | %-------------------------------------------------------------------------- 26 | % 27 | % SPM solvers or integrators 28 | % 29 | % spm_int_ode: uses ode45 (or ode113) which are one and multi-step solvers 30 | % respectively. They can be used for any ODEs, where the Jacobian is 31 | % unknown or difficult to compute; however, they may be slow. 32 | % 33 | % spm_int_J: uses an explicit Jacobian-based update scheme that preserves 34 | % nonlinearities in the ODE: dx = (expm(dt*J) - I)*inv(J)*f. If the 35 | % equations of motion return J = df/dx, it will be used; otherwise it is 36 | % evaluated numerically, using spm_diff at each time point. This scheme is 37 | % infallible but potentially slow, if the Jacobian is not available (calls 38 | % spm_dx). 39 | % 40 | % spm_int_E: As for spm_int_J but uses the eigensystem of J(x(0)) to eschew 41 | % matrix exponentials and inversion during the integration. It is probably 42 | % the best compromise, if the Jacobian is not available explicitly. 43 | % 44 | % spm_int_B: As for spm_int_J but uses a first-order approximation to J 45 | % based on J(x(t)) = J(x(0)) + dJdx*x(t). 46 | % 47 | % spm_int_L: As for spm_int_B but uses J(x(0)). 48 | % 49 | % spm_int_U: like spm_int_J but only evaluates J when the input changes. 50 | % This can be useful if input changes are sparse (e.g., boxcar functions). 51 | % It is used primarily for integrating EEG models 52 | % 53 | % spm_int: Fast integrator that uses a bilinear approximation to the 54 | % Jacobian evaluated using spm_bireduce. This routine will also allow for 55 | % sparse sampling of the solution and delays in observing outputs. It is 56 | % used primarily for integrating fMRI models 57 | %__________________________________________________________________________ 58 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 59 | 60 | % Karl Friston 61 | % $Id: spm_int_L.m 4281 2011-03-31 19:49:57Z karl $ 62 | 63 | 64 | % convert U to U.u if necessary 65 | %-------------------------------------------------------------------------- 66 | if ~isstruct(U), u.u = U; U = u; end 67 | try, dt = U.dt; catch, dt = 1; end 68 | 69 | % state equation; add [0] states if not specified 70 | %-------------------------------------------------------------------------- 71 | try 72 | f = fcnchk(M.f,'x','u','P','M'); 73 | catch 74 | f = inline('sparse(0,1)','x','u','P','M'); 75 | M.n = 0; 76 | M.x = sparse(0,0); 77 | end 78 | 79 | % and output nonlinearity 80 | %-------------------------------------------------------------------------- 81 | try 82 | g = fcnchk(M.g,'x','u','P','M'); 83 | catch 84 | g = []; 85 | end 86 | 87 | % Initial states and inputs 88 | %-------------------------------------------------------------------------- 89 | try 90 | u = U.u(1,:); 91 | catch 92 | u = sparse(1,M.m); 93 | end 94 | try 95 | x = M.x; 96 | catch 97 | x = sparse(0,1); 98 | M.x = x; 99 | end 100 | 101 | % dx(t)/dt and Jacobian df/dx and check for delay operator 102 | %-------------------------------------------------------------------------- 103 | try 104 | [fx dfdx D] = spm_fx_lfp(x,u,P,M); 105 | catch 106 | try 107 | [fx dfdx] = spm_fx_lfp(x,u,P,M); 108 | catch 109 | dfdx = spm_cat(spm_diff(f,x,u,P,M,1)); 110 | end 111 | D = 1; 112 | end 113 | dfdx = full(dfdx); 114 | p = max(abs(real(eig(dfdx)))); 115 | N = ceil(max(1,dt*p*2)); 116 | n = length(spm_vec(x)); 117 | Q = (spm_expm(dt*D*dfdx/N) - speye(n,n))*spm_inv(dfdx); 118 | 119 | % integrate 120 | %========================================================================== 121 | for i = 1:size(U.u,1) 122 | 123 | % input 124 | %---------------------------------------------------------------------- 125 | try 126 | u = U.u(i,:); 127 | end 128 | 129 | % update dx = (expm(dt*J) - I)*inv(J)*fx 130 | %---------------------------------------------------------------------- 131 | for j = 1:N 132 | x = spm_vec(x) + Q*spm_vec(spm_fx_lfp(x,u,P,M)); 133 | x = spm_unvec(x,M.x); 134 | end 135 | 136 | % output - implement g(x) 137 | %---------------------------------------------------------------------- 138 | if ~isempty(g) 139 | y(:,i) = spm_vec(spm_gx_erp(x,u,P,M)); 140 | else 141 | y(:,i) = spm_vec(x); 142 | end 143 | 144 | end 145 | 146 | % transpose 147 | %-------------------------------------------------------------------------- 148 | y = real(y'); 149 | -------------------------------------------------------------------------------- /GenerateData/spm_dcm_fmri_priors.m: -------------------------------------------------------------------------------- 1 | function [pE,pC,x] = spm_dcm_fmri_priors(A,B,C,D,options) 2 | % Returns the priors for a two-state DCM for fMRI. 3 | % FORMAT:[pE,pC,x] = spm_dcm_fmri_priors(A,B,C,D,options) 4 | % 5 | % options.two_state: (0 or 1) one or two states per region 6 | % options.stochastic: (0 or 1) exogenous or endogenous fluctuations 7 | % 8 | % INPUT: 9 | % A,B,C,D - constraints on connections (1 - present, 0 - absent) 10 | % 11 | % OUTPUT: 12 | % pE - prior expectations (connections and hemodynamic) 13 | % pC - prior covariances (connections and hemodynamic) 14 | % x - prior (initial) states 15 | %__________________________________________________________________________ 16 | % 17 | % References for state equations: 18 | % 1. Marreiros AC, Kiebel SJ, Friston KJ. Dynamic causal modelling for 19 | % fMRI: a two-state model. 20 | % Neuroimage. 2008 Jan 1;39(1):269-78. 21 | % 22 | % 2. Stephan KE, Kasper L, Harrison LM, Daunizeau J, den Ouden HE, 23 | % Breakspear M, Friston KJ. Nonlinear dynamic causal models for fMRI. 24 | % Neuroimage 42:649-662, 2008. 25 | %__________________________________________________________________________ 26 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 27 | 28 | % Karl Friston 29 | % $Id: spm_dcm_fmri_priors.m 5692 2013-10-13 13:44:05Z karl $ 30 | 31 | % number of regions 32 | %-------------------------------------------------------------------------- 33 | n = length(A); 34 | 35 | % check options and D (for nonlinear coupling) 36 | %-------------------------------------------------------------------------- 37 | try, options.stochastic; catch, options.stochastic = 0; end 38 | try, options.induced; catch, options.induced = 0; end 39 | try, options.two_state; catch, options.two_state = 0; end 40 | try, options.backwards; catch, options.backwards = 0; end 41 | try, D; catch, D = zeros(n,n,0); end 42 | 43 | 44 | % prior (initial) states and shrinkage priors on A for endogenous DCMs 45 | %-------------------------------------------------------------------------- 46 | if options.two_state, x = sparse(n,6); else, x = sparse(n,5); end 47 | if options.backwards, A(:,:,2) = A; end 48 | 49 | % connectivity priors and intitial states 50 | %========================================================================== 51 | if options.two_state 52 | 53 | % (6) initial states 54 | %---------------------------------------------------------------------- 55 | x = sparse(n,6); 56 | 57 | % enforce optimisation of intrinsic (I to E) connections 58 | %---------------------------------------------------------------------- 59 | for i = 1:size(A,3) 60 | A(:,:,i) = A(:,:,i) + eye(n,n); 61 | end 62 | A = A > 0; 63 | 64 | % prior expectations and variances 65 | %---------------------------------------------------------------------- 66 | pE.A = A*32 - 32; 67 | pE.B = B*0; 68 | pE.C = C*0; 69 | pE.D = D*0; 70 | 71 | % prior covariances 72 | %---------------------------------------------------------------------- 73 | pC.A = A/4; 74 | pC.B = B/4; 75 | pC.C = C*4; 76 | pC.D = D/4; 77 | 78 | else 79 | 80 | % (6 - 1) initial states 81 | %---------------------------------------------------------------------- 82 | x = sparse(n,5); 83 | 84 | % self-inhibition is a log scale parameter 85 | %---------------------------------------------------------------------- 86 | for i = 1:size(A,3) 87 | A(:,:,i) = A(:,:,i) - diag(diag(A(:,:,i))); 88 | end 89 | A = A > 0; 90 | 91 | % prior expectations 92 | %---------------------------------------------------------------------- 93 | pE.A = A/128; 94 | pE.B = B*0; 95 | pE.C = C*0; 96 | pE.D = D*0; 97 | 98 | % prior covariances 99 | %---------------------------------------------------------------------- 100 | if options.stochastic 101 | for i = 1:size(A,3) 102 | pC.A(:,:,i) = A(:,:,i)/64 + eye(n,n)/256; 103 | end 104 | else 105 | for i = 1:size(A,3) 106 | pC.A(:,:,i) = A(:,:,i)/64 + eye(n,n)/256; 107 | end 108 | end 109 | pC.B = B; 110 | pC.C = C; 111 | pC.D = D; 112 | 113 | end 114 | 115 | % and add hemodynamic priors 116 | %========================================================================== 117 | pE.transit = sparse(n,1); pC.transit = sparse(n,1) + exp(-6); 118 | pE.decay = sparse(n,1); pC.decay = sparse(n,1) + exp(-6); 119 | pE.epsilon = sparse(1,1); pC.epsilon = sparse(1,1) + exp(-6); 120 | 121 | 122 | % add prior on spectral density of fluctuations (amplitude and exponent) 123 | %-------------------------------------------------------------------------- 124 | if options.induced 125 | 126 | pE.a = sparse(2,n); pC.a = sparse(2,n) + 1/64; % neuronal fluctuations 127 | pE.b = sparse(2,1); pC.b = sparse(2,1) + 1/64; % channel noise global 128 | pE.c = sparse(2,n); pC.c = sparse(2,n) + 1/64; % channel noise specific 129 | 130 | end 131 | 132 | % prior covariance matrix 133 | %-------------------------------------------------------------------------- 134 | pC = diag(spm_vec(pC)); 135 | 136 | return 137 | -------------------------------------------------------------------------------- /Interface/MULAN_gen_data.m~: -------------------------------------------------------------------------------- 1 | function varargout = MULAN_gen_data(varargin) 2 | % MULAN_GEN_DATA M-file for MULAN_gen_data.fig 3 | % MULAN_GEN_DATA, by itself, creates a new MULAN_GEN_DATA or raises the existing 4 | % singleton*. 5 | % 6 | % H = MULAN_GEN_DATA returns the handle to a new MULAN_GEN_DATA or the handle to 7 | % the existing singleton*. 8 | % 9 | % MULAN_GEN_DATA('CALLBACK',hObject,eventData,handles,...) calls the local 10 | % function named CALLBACK in MULAN_GEN_DATA.M with the given input arguments. 11 | % 12 | % MULAN_GEN_DATA('Property','Value',...) creates a new MULAN_GEN_DATA or raises the 13 | % existing singleton*. Starting from the left, property value pairs are 14 | % applied to the GUI before MULAN_gen_data_OpeningFcn gets called. An 15 | % unrecognized property name or invalid value makes property application 16 | % stop. All inputs are passed to MULAN_gen_data_OpeningFcn via varargin. 17 | % 18 | % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one 19 | % instance to run (singleton)". 20 | % 21 | % See also: GUIDE, GUIDATA, GUIHANDLES 22 | 23 | % Edit the above text to modify the response to help MULAN_gen_data 24 | 25 | % Last Modified by GUIDE v2.5 03-Feb-2014 16:16:28 26 | 27 | % Begin initialization code - DO NOT EDIT 28 | gui_Singleton = 1; 29 | gui_State = struct('gui_Name', mfilename, ... 30 | 'gui_Singleton', gui_Singleton, ... 31 | 'gui_OpeningFcn', @MULAN_gen_data_OpeningFcn, ... 32 | 'gui_OutputFcn', @MULAN_gen_data_OutputFcn, ... 33 | 'gui_LayoutFcn', [] , ... 34 | 'gui_Callback', []); 35 | if nargin && ischar(varargin{1}) 36 | gui_State.gui_Callback = str2func(varargin{1}); 37 | end 38 | 39 | if nargout 40 | [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); 41 | else 42 | gui_mainfcn(gui_State, varargin{:}); 43 | end 44 | % End initialization code - DO NOT EDIT 45 | 46 | 47 | % --- Executes just before MULAN_gen_data is made visible. 48 | function MULAN_gen_data_OpeningFcn(hObject, eventdata, handles, varargin) 49 | % This function has no output args, see OutputFcn. 50 | % hObject handle to figure 51 | % eventdata reserved - to be defined in a future version of MATLAB 52 | % handles structure with handles and user data (see GUIDATA) 53 | % varargin command line arguments to MULAN_gen_data (see VARARGIN) 54 | 55 | % Choose default command line output for MULAN_gen_data 56 | handles.output = hObject; 57 | Paramsdata=initial_param_data(); 58 | param_to_show=mln_showparams(Paramsdata); 59 | set(handles.Parameterset,'Data',param_to_show); 60 | 61 | % Update handles structure 62 | guidata(hObject, handles); 63 | 64 | % UIWAIT makes MULAN_gen_data wait for user response (see UIRESUME) 65 | % uiwait(handles.figure1); 66 | 67 | 68 | % --- Outputs from this function are returned to the command line. 69 | function varargout = MULAN_gen_data_OutputFcn(hObject, eventdata, handles) 70 | % varargout cell array for returning output args (see VARARGOUT); 71 | % hObject handle to figure 72 | % eventdata reserved - to be defined in a future version of MATLAB 73 | % handles structure with handles and user data (see GUIDATA) 74 | 75 | % Get default command line output from handles structure 76 | varargout{1} = handles.output; 77 | 78 | 79 | % --- Executes on button press in Gen_nmm. 80 | function Gen_nmm_Callback(hObject, eventdata, handles) 81 | % hObject handle to Gen_nmm (see GCBO) 82 | % eventdata reserved - to be defined in a future version of MATLAB 83 | % handles structure with handles and user data (see GUIDATA) 84 | 85 | 86 | % --- Executes on button press in Gen_rossler. 87 | function Gen_rossler_Callback(hObject, eventdata, handles) 88 | % hObject handle to Gen_rossler (see GCBO) 89 | % eventdata reserved - to be defined in a future version of MATLAB 90 | % handles structure with handles and user data (see GUIDATA) 91 | 92 | 93 | % --- Executes on button press in Gen_linear. 94 | function Gen_linear_Callback(hObject, eventdata, handles) 95 | % hObject handle to Gen_linear (see GCBO) 96 | % eventdata reserved - to be defined in a future version of MATLAB 97 | % handles structure with handles and user data (see GUIDATA) 98 | 99 | 100 | % --- Executes on button press in Gen_henon. 101 | function Gen_henon_Callback(hObject, eventdata, handles) 102 | % hObject handle to Gen_henon (see GCBO) 103 | % eventdata reserved - to be defined in a future version of MATLAB 104 | % handles structure with handles and user data (see GUIDATA) 105 | 106 | 107 | % --- Executes on button press in Gen_fmri. 108 | function Gen_fmri_Callback(hObject, eventdata, handles) 109 | % hObject handle to Gen_fmri (see GCBO) 110 | % eventdata reserved - to be defined in a future version of MATLAB 111 | % handles structure with handles and user data (see GUIDATA) 112 | 113 | function paramsdata=initial_param_data() 114 | 115 | param_df=struct('strfile',1,..., 116 | 'Nums_Nodes',5,..., 117 | 'No_Net',1,..., 118 | 'CS',1,..., 119 | 'Nsignals',1000); 120 | 121 | paramsfields=fieldnames(param_df); 122 | Nparamf=length(paramsfields); 123 | paramsdata=cell(Nparamf,2); 124 | for i=1:Nparamf 125 | paramsdata{i,1}=paramsfields{i}; 126 | paramsdata{i,2}=param_df.(paramsfields{i}); 127 | end 128 | 129 | -------------------------------------------------------------------------------- /GenerateData/spm_int_J.m: -------------------------------------------------------------------------------- 1 | function [y] = spm_int_J(P,M,U) 2 | % integrates a MIMO nonlinear system using the Jacobian 3 | % FORMAT [y] = spm_int_J(P,M,U) 4 | % P - model parameters 5 | % M - model structure 6 | % U - input structure or matrix 7 | % 8 | % y - (v x l) response y = g(x,u,P) 9 | %__________________________________________________________________________ 10 | % Integrates the MIMO system described by 11 | % 12 | % dx/dt = f(x,u,P,M) 13 | % y = g(x,u,P,M) 14 | % or 15 | % dx/dt = f(x,u,P) 16 | % y = g(x,u,P) 17 | % 18 | % using the update scheme: 19 | % 20 | % x(t + dt) = x(t) + U*dx(t)/dt 21 | % 22 | % U = (expm(dt*J) - I)*inv(J) 23 | % J = df/dx 24 | % 25 | % at input times. This integration scheme evaluates the update matrix (Q) 26 | % at each time point 27 | % 28 | %-------------------------------------------------------------------------- 29 | % 30 | % SPM solvers or integrators 31 | % 32 | % spm_int_ode: uses ode45 (or ode113) which are one and multi-step solvers 33 | % respectively. They can be used for any ODEs, where the Jacobian is 34 | % unknown or difficult to compute; however, they may be slow. 35 | % 36 | % spm_int_J: uses an explicit Jacobian-based update scheme that preserves 37 | % nonlinearities in the ODE: dx = (expm(dt*J) - I)*inv(J)*f. If the 38 | % equations of motion return J = df/dx, it will be used; otherwise it is 39 | % evaluated numerically, using spm_diff at each time point. This scheme is 40 | % infallible but potentially slow, if the Jacobian is not available (calls 41 | % spm_dx). 42 | % 43 | % spm_int_E: As for spm_int_J but uses the eigensystem of J(x(0)) to eschew 44 | % matrix exponentials and inversion during the integration. It is probably 45 | % the best compromise, if the Jacobian is not available explicitly. 46 | % 47 | % spm_int_B: As for spm_int_J but uses a first-order approximation to J 48 | % based on J(x(t)) = J(x(0)) + dJdx*x(t). 49 | % 50 | % spm_int_L: As for spm_int_B but uses J(x(0)). 51 | % 52 | % spm_int_U: like spm_int_J but only evaluates J when the input changes. 53 | % This can be useful if input changes are sparse (e.g., boxcar functions). 54 | % It is used primarily for integrating EEG models 55 | % 56 | % spm_int: Fast integrator that uses a bilinear approximation to the 57 | % Jacobian evaluated using spm_bireduce. This routine will also allow for 58 | % sparse sampling of the solution and delays in observing outputs. It is 59 | % used primarily for integrating fMRI models 60 | %__________________________________________________________________________ 61 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 62 | 63 | % Karl Friston 64 | % $Id: spm_int_J.m 5667 2013-10-02 18:26:06Z karl $ 65 | 66 | 67 | % convert U to U.u if necessary and M(1) to M 68 | %-------------------------------------------------------------------------- 69 | if ~isstruct(U), u.u = U; U = u; end 70 | try, dt = U.dt; catch, dt = 1; end 71 | M = M(1); 72 | 73 | % state equation; add [0] states if not specified 74 | %-------------------------------------------------------------------------- 75 | try 76 | f = fcnchk(M.f,'x','u','P','M'); 77 | catch 78 | f = inline('sparse(0,1)','x','u','P','M'); 79 | M.n = 0; 80 | M.x = sparse(0,0); 81 | end 82 | 83 | % and output nonlinearity 84 | %-------------------------------------------------------------------------- 85 | try 86 | g = fcnchk(M.g,'x','u','P','M'); 87 | catch 88 | g = inline('x','x','v','P','M'); 89 | end 90 | 91 | % Initial states and inputs 92 | %-------------------------------------------------------------------------- 93 | try 94 | u = U.u(1,:); 95 | catch 96 | u = sparse(1,M.m); 97 | end 98 | try 99 | x = M.x; 100 | catch 101 | x = sparse(0,1); 102 | M.x = x; 103 | end 104 | 105 | % check function format 106 | %-------------------------------------------------------------------------- 107 | try 108 | spm_fx_fmri(x,u,P,M); 109 | catch 110 | f = inline(char(f),'x','v','P','M'); 111 | end 112 | try 113 | g(x,u,P,M); 114 | catch 115 | g = inline(char(g),'x','v','P','M'); 116 | end 117 | 118 | % default delay operator 119 | %-------------------------------------------------------------------------- 120 | D = 1; 121 | 122 | % integrate 123 | %========================================================================== 124 | for i = 1:size(U.u,1) 125 | 126 | % input 127 | %---------------------------------------------------------------------- 128 | try 129 | u = U.u(i,:); 130 | end 131 | 132 | % dx(t)/dt and Jacobian df/dx 133 | %---------------------------------------------------------------------- 134 | if nargout(f) >= 3 135 | [fx,dfdx,D] = spm_fx_fmri(x,u,P,M); 136 | 137 | elseif nargout(f) == 2 138 | [fx,dfdx] = spm_fx_fmri(x,u,P,M); 139 | 140 | else 141 | fx = spm_fx_fmri(x,u,P,M); 142 | dfdx = spm_cat(spm_diff(f,x,u,P,M,1)); 143 | end 144 | 145 | % update dx = (expm(dt*J) - I)*inv(J)*fx 146 | %---------------------------------------------------------------------- 147 | x = spm_unvec(spm_vec(x) + spm_dx(D*dfdx,D*fx,dt),x); 148 | 149 | % output - implement g(x) 150 | %---------------------------------------------------------------------- 151 | y(:,i) = spm_vec(g(x,u,P,M)); 152 | 153 | end 154 | 155 | % transpose 156 | %-------------------------------------------------------------------------- 157 | y = real(y'); 158 | 159 | -------------------------------------------------------------------------------- /GenerateData/spm_diff.m: -------------------------------------------------------------------------------- 1 | function [varargout] = spm_diff(varargin) 2 | % matrix high-order numerical differentiation 3 | % FORMAT [dfdx] = spm_diff(f,x,...,n) 4 | % FORMAT [dfdx] = spm_diff(f,x,...,n,V) 5 | % FORMAT [dfdx] = spm_diff(f,x,...,n,'q') 6 | % 7 | % f - [inline] function f(x{1},...) 8 | % x - input argument[s] 9 | % n - arguments to differentiate w.r.t. 10 | % 11 | % V - cell array of matrices that allow for differentiation w.r.t. 12 | % to a linear transformation of the parameters: i.e., returns 13 | % 14 | % df/dy{i}; x = V{i}y{i}; V = dx(i)/dy(i) 15 | % 16 | % q - flag to preclude default concatenation of dfdx 17 | % 18 | % dfdx - df/dx{i} ; n = i 19 | % dfdx{p}...{q} - df/dx{i}dx{j}(q)...dx{k}(p) ; n = [i j ... k] 20 | % 21 | % 22 | % - a cunning recursive routine 23 | %__________________________________________________________________________ 24 | % Copyright (C) 2008 Wellcome Trust Centre for Neuroimaging 25 | 26 | % Karl Friston 27 | % $Id: spm_diff.m 4060 2010-09-01 17:17:36Z karl $ 28 | 29 | % create inline object 30 | %-------------------------------------------------------------------------- 31 | f = varargin{1}; 32 | 33 | % parse input arguments 34 | %-------------------------------------------------------------------------- 35 | if iscell(varargin{end}) 36 | x = varargin(2:(end - 2)); 37 | n = varargin{end - 1}; 38 | V = varargin{end}; 39 | q = 1; 40 | elseif isnumeric(varargin{end}) 41 | x = varargin(2:(end - 1)); 42 | n = varargin{end}; 43 | V = cell(1,length(x)); 44 | q = 1; 45 | elseif ischar(varargin{end}) 46 | x = varargin(2:(end - 2)); 47 | n = varargin{end - 1}; 48 | V = cell(1,length(x)); 49 | q = 0; 50 | else 51 | error('improper call') 52 | end 53 | 54 | % check transform matrices V = dxdy 55 | %-------------------------------------------------------------------------- 56 | for i = 1:length(x) 57 | try 58 | V{i}; 59 | catch 60 | V{i} = []; 61 | end 62 | if isempty(V{i}) && any(n == i); 63 | V{i} = speye(length(spm_vec(x{i}))); 64 | end 65 | end 66 | 67 | % initialise 68 | %-------------------------------------------------------------------------- 69 | m = n(end); 70 | xm = spm_vec(x{m}); 71 | dx = exp(-8); 72 | J = cell(1,size(V{m},2)); 73 | 74 | % proceed to derivatives 75 | %========================================================================== 76 | if length(n) == 1 77 | 78 | % dfdx 79 | %---------------------------------------------------------------------- 80 | f0 = feval(f,x{:}); 81 | for i = 1:length(J) 82 | xi = x; 83 | xmi = xm + V{m}(:,i)*dx; 84 | xi{m} = spm_unvec(xmi,x{m}); 85 | fi = feval(f,xi{:}); 86 | J{i} = spm_dfdx(fi,f0,dx); 87 | end 88 | 89 | % return numeric array for first-order derivatives 90 | %====================================================================== 91 | 92 | % vectorise f 93 | %---------------------------------------------------------------------- 94 | f = spm_vec(f0); 95 | 96 | % if there are no arguments to differentiate w.r.t. ... 97 | %---------------------------------------------------------------------- 98 | if isempty(xm) 99 | J = sparse(length(f),0); 100 | 101 | % or there are no arguments to differentiate 102 | %---------------------------------------------------------------------- 103 | elseif isempty(f) 104 | J = sparse(0,length(xm)); 105 | end 106 | 107 | % or differentiation of a vector 108 | %---------------------------------------------------------------------- 109 | if isvec(f0) && q 110 | 111 | % concatenate into a matrix 112 | %------------------------------------------------------------------ 113 | if size(f0,2) == 1 114 | else 115 | J = spm_cat(J')'; 116 | end 117 | end 118 | 119 | % assign output argument and return 120 | %---------------------------------------------------------------------- 121 | varargout{1} = J; 122 | varargout{2} = f0; 123 | 124 | else 125 | 126 | % dfdxdxdx.... 127 | %---------------------------------------------------------------------- 128 | f0 = cell(1,length(n)); 129 | [f0{:}] = spm_diff(f,x{:},n(1:end - 1),V); 130 | 131 | for i = 1:length(J) 132 | xi = x; 133 | xmi = xm + V{m}(:,i)*dx; 134 | xi{m} = spm_unvec(xmi,x{m}); 135 | fi = spm_diff(f,xi{:},n(1:end - 1),V); 136 | J{i} = spm_dfdx(fi,f0{1},dx); 137 | end 138 | varargout = [{J} f0]; 139 | end 140 | 141 | 142 | function dfdx = spm_dfdx(f,f0,dx) 143 | % cell subtraction 144 | %-------------------------------------------------------------------------- 145 | if iscell(f) 146 | dfdx = f; 147 | for i = 1:length(f(:)) 148 | dfdx{i} = spm_dfdx(f{i},f0{i},dx); 149 | end 150 | elseif isstruct(f) 151 | dfdx = (spm_vec(f) - spm_vec(f0))/dx; 152 | else 153 | dfdx = (f - f0)/dx; 154 | end 155 | 156 | 157 | function is = isvec(v) 158 | % isvector(v) returns true if v is 1-by-n or n-by-1 where n>=0 159 | %__________________________________________________________________________ 160 | 161 | % vec if just two dimensions, and one (or both) unity 162 | %-------------------------------------------------------------------------- 163 | is = length(size(v)) == 2 && isnumeric(v); 164 | is = is && (size(v,1) == 1 || size(v,2) == 1); 165 | -------------------------------------------------------------------------------- /Interface/MULAN_gen_data.m: -------------------------------------------------------------------------------- 1 | function varargout = MULAN_gen_data(varargin) 2 | % MULAN_GEN_DATA M-file for MULAN_gen_data.fig 3 | % MULAN_GEN_DATA, by itself, creates a new MULAN_GEN_DATA or raises the existing 4 | % singleton*. 5 | % 6 | % H = MULAN_GEN_DATA returns the handle to a new MULAN_GEN_DATA or the handle to 7 | % the existing singleton*. 8 | % 9 | % MULAN_GEN_DATA('CALLBACK',hObject,eventData,handles,...) calls the local 10 | % function named CALLBACK in MULAN_GEN_DATA.M with the given input arguments. 11 | % 12 | % MULAN_GEN_DATA('Property','Value',...) creates a new MULAN_GEN_DATA or raises the 13 | % existing singleton*. Starting from the left, property value pairs are 14 | % applied to the GUI before MULAN_gen_data_OpeningFcn gets called. An 15 | % unrecognized property name or invalid value makes property application 16 | % stop. All inputs are passed to MULAN_gen_data_OpeningFcn via varargin. 17 | % 18 | % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one 19 | % instance to run (singleton)". 20 | % 21 | % See also: GUIDE, GUIDATA, GUIHANDLES 22 | 23 | % Edit the above text to modify the response to help MULAN_gen_data 24 | 25 | % Last Modified by GUIDE v2.5 03-Feb-2014 16:16:28 26 | 27 | % Begin initialization code - DO NOT EDIT 28 | gui_Singleton = 1; 29 | gui_State = struct('gui_Name', mfilename, ... 30 | 'gui_Singleton', gui_Singleton, ... 31 | 'gui_OpeningFcn', @MULAN_gen_data_OpeningFcn, ... 32 | 'gui_OutputFcn', @MULAN_gen_data_OutputFcn, ... 33 | 'gui_LayoutFcn', [] , ... 34 | 'gui_Callback', []); 35 | if nargin && ischar(varargin{1}) 36 | gui_State.gui_Callback = str2func(varargin{1}); 37 | end 38 | 39 | if nargout 40 | [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); 41 | else 42 | gui_mainfcn(gui_State, varargin{:}); 43 | end 44 | % End initialization code - DO NOT EDIT 45 | 46 | 47 | % --- Executes just before MULAN_gen_data is made visible. 48 | function MULAN_gen_data_OpeningFcn(hObject, eventdata, handles, varargin) 49 | % This function has no output args, see OutputFcn. 50 | % hObject handle to figure 51 | % eventdata reserved - to be defined in a future version of MATLAB 52 | % handles structure with handles and user data (see GUIDATA) 53 | % varargin command line arguments to MULAN_gen_data (see VARARGIN) 54 | 55 | % Choose default command line output for MULAN_gen_data 56 | handles.output = hObject; 57 | Paramsdata=initial_param_data(); 58 | set(handles.Parameterset,'Data',Paramsdata); 59 | axes(handles.Logo); 60 | imshow('MULANLOGO.png'); 61 | % Update handles structure 62 | guidata(hObject, handles); 63 | 64 | % UIWAIT makes MULAN_gen_data wait for user response (see UIRESUME) 65 | % uiwait(handles.figure1); 66 | 67 | 68 | % --- Outputs from this function are returned to the command line. 69 | function varargout = MULAN_gen_data_OutputFcn(hObject, eventdata, handles) 70 | % varargout cell array for returning output args (see VARARGOUT); 71 | % hObject handle to figure 72 | % eventdata reserved - to be defined in a future version of MATLAB 73 | % handles structure with handles and user data (see GUIDATA) 74 | 75 | % Get default command line output from handles structure 76 | varargout{1} = handles.output; 77 | 78 | 79 | % --- Executes on button press in Gen_nmm. 80 | function Gen_nmm_Callback(hObject, eventdata, handles) 81 | % hObject handle to Gen_nmm (see GCBO) 82 | % eventdata reserved - to be defined in a future version of MATLAB 83 | % handles structure with handles and user data (see GUIDATA) 84 | cparams=get(handles.Parameterset,'Data'); 85 | params=mln_cell2struct(cparams); 86 | mln_generate_nmm(params.No_Net,params.Nums_Nodes,params.strfile,params.dir,params.filename,params.CS,params.Nsignals); 87 | %(is,nc,strfile,dirname,prename,cs,N) 88 | 89 | 90 | % --- Executes on button press in Gen_rossler. 91 | function Gen_rossler_Callback(hObject, eventdata, handles) 92 | % hObject handle to Gen_rossler (see GCBO) 93 | % eventdata reserved - to be defined in a future version of MATLAB 94 | % handles structure with handles and user data (see GUIDATA) 95 | cparams=get(handles.Parameterset,'Data'); 96 | params=mln_cell2struct(cparams); 97 | mln_generate_rossler(params.dir,params.filename,params.Nsignals,params.strfile,params.No_Net,params.CS,0,0,0); 98 | 99 | %dirname,prename,npts,strfile,is,cs,odelay,flag_noise,SNR 100 | % --- Executes on button press in Gen_linear. 101 | function Gen_linear_Callback(hObject, eventdata, handles) 102 | % hObject handle to Gen_linear (see GCBO) 103 | % eventdata reserved - to be defined in a future version of MATLAB 104 | % handles structure with handles and user data (see GUIDATA) 105 | cparams=get(handles.Parameterset,'Data'); 106 | params=mln_cell2struct(cparams); 107 | mln_generate_linear(params.dir,params.filename,params.Nsignals,params.strfile,params.No_Net,params.CS,1); 108 | %mln_generate_linear(dirname,prename,npts,strfile,is,cs,delaydelay) 109 | 110 | % --- Executes on button press in Gen_henon. 111 | function Gen_henon_Callback(hObject, eventdata, handles) 112 | % hObject handle to Gen_henon (see GCBO) 113 | % eventdata reserved - to be defined in a future version of MATLAB 114 | % handles structure with handles and user data (see GUIDATA) 115 | cparams=get(handles.Parameterset,'Data'); 116 | params=mln_cell2struct(cparams); 117 | mln_generate_henon(params.dir,params.filename,params.Nsignals,params.strfile,params.No_Net,params.CS,0,0,0); 118 | 119 | 120 | % --- Executes on button press in Gen_fmri. 121 | function Gen_fmri_Callback(hObject, eventdata, handles) 122 | % hObject handle to Gen_fmri (see GCBO) 123 | % eventdata reserved - to be defined in a future version of MATLAB 124 | % handles structure with handles and user data (see GUIDATA) 125 | cparams=get(handles.Parameterset,'Data'); 126 | params=mln_cell2struct(cparams); 127 | mln_generate_fMRI(params.No_Net,params.Nums_Nodes,params.strfile,params.dir,params.filename,params.CS,params.Nsignals); 128 | 129 | function paramsdata=initial_param_data() 130 | 131 | param_df=struct('dir','Examples',..., 132 | 'filename','Ex',..., 133 | 'strfile','structureN5L5',..., 134 | 'Nums_Nodes',5,..., 135 | 'No_Net',20,..., 136 | 'CS',1,..., 137 | 'Nsignals',3000); 138 | 139 | paramsfields=fieldnames(param_df); 140 | Nparamf=length(paramsfields); 141 | paramsdata=cell(Nparamf,2); 142 | for i=1:Nparamf 143 | paramsdata{i,1}=paramsfields{i}; 144 | paramsdata{i,2}=param_df.(paramsfields{i}); 145 | end 146 | 147 | -------------------------------------------------------------------------------- /Interface/GUI_Preprocess.m: -------------------------------------------------------------------------------- 1 | function varargout = GUI_Preprocess(varargin) 2 | % GUI_PREPROCESS MATLAB code for GUI_Preprocess.fig 3 | % GUI_PREPROCESS, by itself, creates a new GUI_PREPROCESS or raises the existing 4 | % singleton*. 5 | % 6 | % H = GUI_PREPROCESS returns the handle to a new GUI_PREPROCESS or the handle to 7 | % the existing singleton*. 8 | % 9 | % GUI_PREPROCESS('CALLBACK',hObject,eventData,handles,...) calls the local 10 | % function named CALLBACK in GUI_PREPROCESS.M with the given input arguments. 11 | % 12 | % GUI_PREPROCESS('Property','Value',...) creates a new GUI_PREPROCESS or raises the 13 | % existing singleton*. Starting from the left, property value pairs are 14 | % applied to the GUI before GUI_Preprocess_OpeningFcn gets called. An 15 | % unrecognized property name or invalid value makes property application 16 | % stop. All inputs are passed to GUI_Preprocess_OpeningFcn via varargin. 17 | % 18 | % *See GUI Options on GUIDE's Tools menu. Choose "GUI allows only one 19 | % instance to run (singleton)". 20 | % 21 | % See also: GUIDE, GUIDATA, GUIHANDLES 22 | 23 | % Edit the above text to modify the response to help GUI_Preprocess 24 | 25 | % Last Modified by GUIDE v2.5 15-Feb-2013 17:59:36 26 | 27 | % Begin initialization code - DO NOT EDIT 28 | gui_Singleton = 1; 29 | gui_State = struct('gui_Name', mfilename, ... 30 | 'gui_Singleton', gui_Singleton, ... 31 | 'gui_OpeningFcn', @GUI_Preprocess_OpeningFcn, ... 32 | 'gui_OutputFcn', @GUI_Preprocess_OutputFcn, ... 33 | 'gui_LayoutFcn', [] , ... 34 | 'gui_Callback', []); 35 | if nargin && ischar(varargin{1}) 36 | gui_State.gui_Callback = str2func(varargin{1}); 37 | end 38 | 39 | if nargout 40 | [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:}); 41 | else 42 | gui_mainfcn(gui_State, varargin{:}); 43 | end 44 | % End initialization code - DO NOT EDIT 45 | 46 | 47 | % --- Executes just before GUI_Preprocess is made visible. 48 | function GUI_Preprocess_OpeningFcn(hObject, eventdata, handles, varargin) 49 | % This function has no output args, see OutputFcn. 50 | % hObject handle to figure 51 | % eventdata reserved - to be defined in a future version of MATLAB 52 | % handles structure with handles and user data (see GUIDATA) 53 | % varargin command line arguments to GUI_Preprocess (see VARARGIN) 54 | 55 | % Choose default command line output for GUI_Preprocess 56 | paramsfields={'wins','overlap','minfreq','maxfreq','stepfreq'}; 57 | Paramsdata=mln_initialparamsmethods(paramsfields); 58 | handles.varinput=varargin{1}; 59 | axes(handles.Logo); 60 | imshow('MULANLOGO.png'); 61 | 62 | set(handles.Parameterset,'Data',Paramsdata); 63 | 64 | handles.output = hObject; 65 | 66 | % Update handles structure 67 | guidata(hObject, handles); 68 | 69 | % UIWAIT makes GUI_Preprocess wait for user response (see UIRESUME) 70 | % uiwait(handles.figure1); 71 | 72 | 73 | % --- Outputs from this function are returned to the command line. 74 | function varargout = GUI_Preprocess_OutputFcn(hObject, eventdata, handles) 75 | % varargout cell array for returning output args (see VARARGOUT); 76 | % hObject handle to figure 77 | % eventdata reserved - to be defined in a future version of MATLAB 78 | % handles structure with handles and user data (see GUIDATA) 79 | 80 | % Get default command line output from handles structure 81 | varargout{1} = handles.output; 82 | 83 | 84 | % --- Executes on button press in FourierT. 85 | function FourierT_Callback(hObject, eventdata, handles) 86 | % hObject handle to FourierT (see GCBO) 87 | % eventdata reserved - to be defined in a future version of MATLAB 88 | % handles structure with handles and user data (see GUIDATA) 89 | cparams=get(handles.Parameterset,'Data'); 90 | params=mln_cell2struct(cparams); 91 | params=mln_struct_str2num(params); 92 | raw_data=load(handles.varinput.datafile); 93 | lfp=raw_data.LFP; 94 | fs=raw_data.Params.fs; 95 | freqs=params.minfreq:params.stepfreq:params.maxfreq; 96 | [Psd,freqs,times] = getPsd_fourier(lfp, params.wins,floor(params.overlap*params.wins),fs, freqs); 97 | plot_psd(Psd,raw_data.Params,'Fourier',freqs,times); 98 | 99 | % --- Executes on button press in WaveletT. 100 | function WaveletT_Callback(hObject, eventdata, handles) 101 | % hObject handle to WaveletT (see GCBO) 102 | % eventdata reserved - to be defined in a future version of MATLAB 103 | % handles structure with handles and user data (see GUIDATA) 104 | cparams=get(handles.Parameterset,'Data'); 105 | params=mln_cell2struct(cparams); 106 | params=mln_struct_str2num(params); 107 | raw_data=load(handles.varinput.datafile); 108 | 109 | freqs=params.minfreq:params.stepfreq:params.maxfreq; 110 | 111 | raw_data=load(handles.varinput.datafile); 112 | fileprevar=fieldnames(raw_data); 113 | iLFP=strncmpi(fileprevar,'LFP',3); 114 | if ~isempty(find(strncmpi(fileprevar,'LFP',1)==1,1)) 115 | lfp = raw_data.(char(fileprevar(iLFP))); 116 | end 117 | fs=raw_data.Params.fs; 118 | Psd=getPsd_wavelet(lfp, fs, freqs); 119 | Ntimes=size(Psd,2); 120 | times=(1:Ntimes)/fs; 121 | plot_psd(Psd,raw_data.Params,'Wavelet',freqs,times); 122 | 123 | function plot_psd(Psd,Params,flag,freqs,times) 124 | Nchan=size(Psd,1); 125 | %% if Number of channels is larger than 6, we divided the figures with each 126 | %% one less or equals 6x6 127 | NumberChanforPage=6; 128 | Npage=(floor(Nchan/NumberChanforPage)+1); 129 | %% define the name of channels 130 | if isempty(find(strncmpi(fieldnames(Params),'str',3)==1,1)); 131 | str=1:Nchan; 132 | else 133 | str=Params.str; 134 | end 135 | 136 | %% 137 | if Nchan>NumberChanforPage 138 | for ipage=1:Npage 139 | if ipage==Npage 140 | ichanV=(ipage-1)*NumberChanforPage+1:Nchan; 141 | 142 | else 143 | ichanV=(ipage-1)*NumberChanforPage+1:ipage*NumberChanforPage; 144 | end 145 | istr=str(ichanV); 146 | hf=figure('name',['Sepctrum Analysis', flag, 'in Page ',num2str(ipage), ' / ',num2str(Npage)]); 147 | plotPsd(hf,ichanV,istr,Psd,freqs,times); 148 | 149 | end 150 | else 151 | 152 | ichanV=1:Nchan; 153 | istr=str; 154 | hf=figure('name',['Sepctrum Analysis', flag, 'in Page ','1/1']); 155 | plotPsd(hf,ichanV,istr,Psd,freqs,times); 156 | end 157 | 158 | 159 | %for idelay=0:NSP 160 | function plotPsd(hf,ichanV,istr,Psd,freqs,times) 161 | Nchan=length(ichanV); 162 | for i=1:length(ichanV) 163 | 164 | ha=subplot(Nchan,1,i,'parent',hf); 165 | imagesc(times,freqs,squeeze(abs(Psd(i,:,:)))'); 166 | set(ha,'YDir','normal'); 167 | if iscell(istr) 168 | title(istr{i}); 169 | else 170 | title(num2str(istr(i))); 171 | end 172 | 173 | end 174 | %end 175 | function [psd,freqs,times] = getPsd_fourier(lfp, window,noverlap,fs, freqs) 176 | [Nchannel,~]=size(lfp); 177 | [psd1,freqs,times]=spectrogram(lfp(1,:),window,noverlap,freqs,fs); 178 | [nFreq,nTime]=size(psd1); 179 | psd=zeros(Nchannel,nTime,nFreq); 180 | psd(1,:,:)=psd1'; 181 | for i=2:Nchannel 182 | psd(i,:,:)=spectrogram(lfp(i,:),window,noverlap,freqs,fs)'; 183 | end 184 | 185 | 186 | function nparams=mln_struct_str2num(params) 187 | pfn=fieldnames(params); 188 | for ifield=1:length(pfn) 189 | nparams.(pfn{ifield})=str2double(params.(pfn{ifield})); 190 | end 191 | -------------------------------------------------------------------------------- /Calculation/covm.m: -------------------------------------------------------------------------------- 1 | function [CC,NN] = covm(X,Y,Mode,W) 2 | % COVM generates covariance matrix 3 | % X and Y can contain missing values encoded with NaN. 4 | % NaN's are skipped, NaN do not result in a NaN output. 5 | % The output gives NaN only if there are insufficient input data 6 | % 7 | % COVM(X,Mode); 8 | % calculates the (auto-)correlation matrix of X 9 | % COVM(X,Y,Mode); 10 | % calculates the crosscorrelation between X and Y 11 | % COVM(...,W); 12 | % weighted crosscorrelation 13 | % 14 | % Mode = 'M' minimum or standard mode [default] 15 | % C = X'*X; or X'*Y correlation matrix 16 | % 17 | % Mode = 'E' extended mode 18 | % C = [1 X]'*[1 X]; % l is a matching column of 1's 19 | % C is additive, i.e. it can be applied to subsequent blocks and summed up afterwards 20 | % the mean (or sum) is stored on the 1st row and column of C 21 | % 22 | % Mode = 'D' or 'D0' detrended mode 23 | % the mean of X (and Y) is removed. If combined with extended mode (Mode='DE'), 24 | % the mean (or sum) is stored in the 1st row and column of C. 25 | % The default scaling is factor (N-1). 26 | % Mode = 'D1' is the same as 'D' but uses N for scaling. 27 | % 28 | % C = covm(...); 29 | % C is the scaled by N in Mode M and by (N-1) in mode D. 30 | % [C,N] = covm(...); 31 | % C is not scaled, provides the scaling factor N 32 | % C./N gives the scaled version. 33 | % 34 | % see also: DECOVM, XCOVF 35 | 36 | % $Id: covm.m 8223 2011-04-20 09:16:06Z schloegl $ 37 | % Copyright (C) 2000-2005,2009 by Alois Schloegl 38 | % This function is part of the NaN-toolbox 39 | % http://pub.ist.ac.at/~schloegl/matlab/NaN/ 40 | 41 | % This program is free software; you can redistribute it and/or modify 42 | % it under the terms of the GNU General Public License as published by 43 | % the Free Software Foundation; either version 3 of the License, or 44 | % (at your option) any later version. 45 | % 46 | % This program is distributed in the hope that it will be useful, 47 | % but WITHOUT ANY WARRANTY; without even the implied warranty of 48 | % MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 49 | % GNU General Public License for more details. 50 | % 51 | % You should have received a copy of the GNU General Public License 52 | % along with this program; If not, see . 53 | 54 | 55 | global FLAG_NANS_OCCURED; 56 | 57 | if nargin<3, 58 | W = []; 59 | if nargin==2, 60 | if isnumeric(Y), 61 | Mode='M'; 62 | else 63 | Mode=Y; 64 | Y=[]; 65 | end; 66 | elseif nargin==1, 67 | Mode = 'M'; 68 | Y = []; 69 | elseif nargin==0, 70 | error('Missing argument(s)'); 71 | end; 72 | 73 | elseif (nargin==3) && isnumeric(Y) && ~isnumeric(Mode); 74 | W = []; 75 | 76 | elseif (nargin==3) && ~isnumeric(Y) && isnumeric(Mode); 77 | W = Mode; 78 | Mode = Y; 79 | Y = []; 80 | 81 | elseif (nargin==4) && ~isnumeric(Mode) && isnumeric(Y); 82 | ; %% ok 83 | else 84 | error('invalid input arguments'); 85 | end; 86 | 87 | Mode = upper(Mode); 88 | 89 | [r1,c1]=size(X); 90 | if ~isempty(Y) 91 | [r2,c2]=size(Y); 92 | if r1~=r2, 93 | error('X and Y must have the same number of observations (rows).'); 94 | end; 95 | else 96 | [r2,c2]=size(X); 97 | end; 98 | 99 | persistent mexFLAG2; 100 | persistent mexFLAG; 101 | if isempty(mexFLAG2) 102 | mexFLAG2 = exist('covm_mex','file'); 103 | end; 104 | if isempty(mexFLAG) 105 | mexFLAG = exist('sumskipnan_mex','file'); 106 | end; 107 | 108 | 109 | if ~isempty(W) 110 | W = W(:); 111 | if (r1~=numel(W)) 112 | error('Error COVM: size of weight vector does not fit number of rows'); 113 | end; 114 | %w = spdiags(W(:),0,numel(W),numel(W)); 115 | %nn = sum(W(:)); 116 | nn = sum(W); 117 | else 118 | nn = r1; 119 | end; 120 | 121 | 122 | if mexFLAG2 && mexFLAG && ~isempty(W), 123 | %% the mex-functions here are much slower than the m-scripts below 124 | %% however, the mex-functions support weighting of samples. 125 | if isempty(FLAG_NANS_OCCURED), 126 | %% mex-files require that FLAG_NANS_OCCURED is not empty, 127 | %% otherwise, the status of NAN occurence can not be returned. 128 | FLAG_NANS_OCCURED = logical(0); % default value 129 | end; 130 | 131 | if any(Mode=='D') || any(Mode=='E'), 132 | [S1,N1] = sumskipnan(X,1,W); 133 | if ~isempty(Y) 134 | [S2,N2] = sumskipnan(Y,1,W); 135 | else 136 | S2 = S1; N2 = N1; 137 | end; 138 | if any(Mode=='D'), % detrending mode 139 | X = X - ones(r1,1)*(S1./N1); 140 | if ~isempty(Y) 141 | Y = Y - ones(r1,1)*(S2./N2); 142 | end; 143 | end; 144 | end; 145 | 146 | [CC,NN] = covm_mex(real(X), real(Y), FLAG_NANS_OCCURED, W); 147 | %% complex matrices 148 | if ~isreal(X) && ~isreal(Y) 149 | [iCC,inn] = covm_mex(imag(X), imag(Y), FLAG_NANS_OCCURED, W); 150 | CC = CC + iCC; 151 | end; 152 | if isempty(Y) Y = X; end; 153 | if ~isreal(X) 154 | [iCC,inn] = covm_mex(imag(X), real(Y), FLAG_NANS_OCCURED, W); 155 | CC = CC - i*iCC; 156 | end; 157 | if ~isreal(Y) 158 | [iCC,inn] = covm_mex(real(X), imag(Y), FLAG_NANS_OCCURED, W); 159 | CC = CC + i*iCC; 160 | end; 161 | 162 | if any(Mode=='D') && ~any(Mode=='1'), % 'D1' 163 | NN = max(NN-1,0); 164 | end; 165 | if any(Mode=='E'), % extended mode 166 | NN = [nn, N2; N1', NN]; 167 | CC = [nn, S2; S1', CC]; 168 | end; 169 | 170 | 171 | elseif ~isempty(W), 172 | 173 | error('Error COVM: weighted COVM requires sumskipnan_mex and covm_mex but it is not available'); 174 | 175 | %% weighted covm without mex-file support 176 | %% this part is not working. 177 | 178 | elseif ~isempty(Y), 179 | if (~any(Mode=='D') && ~any(Mode=='E')), % if Mode == M 180 | NN = real(X==X)'*real(Y==Y); 181 | FLAG_NANS_OCCURED = any(NN(:)