Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

In this tutorial you will find a description of all the steps necessary to obtain the sources localisation of continuous (non averaged) data using a beamformer approach in FieldTrip for a group of subjects in using the MNI template.

Prerequisites

Input data

EEG signals (EEG)

Fieldtrip can import the data coming from our BrainAmps system. If a 3D digitalisation of the EEG electrodes coordinates was performed you should insert this information in the file using multiconv (see the appropriate tutorial). It is also possible to use an EEG template (you can do that after the EEG importation in FieldTrip).

MEG signals (MEG)

FieldTrip can import the fif files coming from our MEG system and those pre processed with our in-house tools. If you acquired simultaneous MEG+EEG data, FieldTrip will import both of them.

MRI

If you have the individual anatomy of each of your subjects (T1 MRI), you should process it with FieldTrip as described below.

If you don't have the individual anatomy, then you have to choose a template in FieldTrip.

Needed software

FieldTrip

For MEG fif files pre processed outside FieldTrip: You will need two in-house scripts to read the marker files we add to the MEG fif files (put them in your matlab path):

A short script to pre process the MRI in FieldTrip: pre_process_mri_for_ft.m

A simple script to visualize beamformer results: visuBF.m

D.I.C.S. analysis with FieldTrip

Overview of the process:

 

Suggested data organisation

The mat files generated by FieldTrip can be stored together with the pre-processed data. You may want to create a specific sub folder "FT" to store them in each subject.

 

 

Read data

The data should be pre processed (i.e. artefact free) at this point and the FieldTrip folder in your matlab path.MEG data

FieldTrip initialisation.

Code Block
themeConfluence
titleRead MEG data
ft_defaults ; %% Load fieldtrip configuration

%% Read two runs, define trials around LEFT_MVT_CLEAN marker (-2s to 2s around the marker), read also BIO005 which is an EMG.
[ trials ] = trial_definition_ft( {'cardiocor_blinkcor_run03_tsss.fif' 'cardiocor_blinkcor_run04_tsss.fif'}, 'LEFT_MVT_CLEAN', 2.0, 2.0, 'BIO005' ) ;

 

EEG

See with Nathalie

 

Image Removed

MRI processing

Code Block
titleMRI processing
mri=ft_read_mri(dicom_file_name);
%% Realign the MRI 

 

 

MRI processing and grid normalisation to the MNI space

This step should be done only one time. The results (aligned and segmented MRI, head model and grid) will be loaded when needed.

Code Block
titleMRI processing
mri=ft_read_mri(dicom_file_name);
 
%% Construire la grille du beamformer en d?formant le MNI sur le sujet
templatedir  = 'fieldtrip-20160105/template/sourcemodel';

template = load(fullfile(templatedir, 'standard_sourcemodel3d8mm'));

%% Realign the MRI to the MEG coordinate
cfg=[];
cfg.method = 'interactive' ;
cfg.coordsys = 'neuromag' ;
mri_aligned = ft_volumerealign(cfg,mri) ;

save('mri_aligned.mat', 'mri_aligned');

%% Segmentation
cfg           = [];
cfg.output    = 'brain';
segmentedmri  = ft_volumesegment(cfg, mri_aligned);

save('segmentedmri.mat', 'segmentedmri') ;

 
% construct volume conductor model (i.e. head model) for each subject
cfg = [];
cfg.method = 'singleshell';
vol = ft_prepare_headmodel(cfg, seg);
vol = ft_convert_units(vol, 'cm');
save('vol.mat', 'vol') ;

 

 

Image Removed

 

General configuration

Code Block
titleParameters
%% Load
 
% create the headsubject modelspecific createdgrid, duringusing the MRItemplate pregrid processing
load vol ; %% load head model located in the subject directory and obtained from the T1 MRI of the subject
 
%% Load the MRI data for visualisation purpose
load('mri_aligned.mat') ; %% MRI data needed for vizualisation
load('segmentedmri.mat') ;

overall_time_window = [-2 2] ; %% if you modify this modify the trials def above ! Is this used below ???

%% Define time window for active state and baseline
active_time_window = [0.2 0.6] ;
reference_time_window = [-1.4 -1.0] ;

%% Basic configuration of the beamformer
beamformer_lambda_normalization = '10%' ;
lead_field_depth_normalization = 'column' ;

%% Frequency of interest and associated width (we will examine here the 16 Hz to 28 Hz band)
freqofinterest = 22 ;
freqhalfwin = 6 ;

%% Select the channel of interest
channelsofinterest = {'MEG*2', 'MEG*3'}; %% Gradiometers on an Elekta system
%% channelsofinterest = {'MEG*1'} ; %% Magnetometer on an Elekta system

Data preparation

Code Block
titleData preparation
% Select time window of interest
cfg = [];
cfg.toilim = active_time_window ;
data_timewindow_active = ft_redefinetrial(cfg,trials);

% Select time window of control
cfg = [];
cfg.toilim = reference_time_window ;
data_timewindow_ref = ft_redefinetrial(cfg,trials);

% Concatenate for common spatial filter computation
data_all = ft_appenddata([], data_timewindow_active, data_timewindow_ref);
 
% Trials will full window
cfg = [];
cfg.toilim = overall_time_window ;
full_data_all = ft_redefinetrial(cfg,trials);

 

Time-Frequency analysis

Code Block
titleTime-Frequency analysis
cfg              = [];
cfg.output       = 'pow';
cfg.channel      = 'MEG';
cfg.method       = 'mtmconvol';
cfg.taper        = 'hanning';
cfg.foi          = 7:2:40;                         % analysis 2 to 30 Hz in steps of 2 Hz 
cfg.t_ftimwin    = ones(length(cfg.foi),1).*0.5;   % length of time window = 0.5 sec
cfg.toi          = -2.0:0.05:2.0;                  % time window "slides" from -2.0 to 2.0 sec in steps of 0.05 sec (50 ms)
cfg.trials       = 'all';

TFRhann = ft_freqanalysis(cfg, full_data_all);
 
%% Visualization
cfg = [];
cfg.xlim = [0.1 0.2];                
cfg.ylim = [20 20];                  
cfg.zlim = [-1e-28 1e-28];           
cfg.baseline     = [-0.2 -0.0]; 
cfg.baselinetype = 'absolute';
cfg.layout       = 'neuromag306mag.lay';

figure; ft_topoplotTFR(cfg,TFRhann);

% for the multiple plots also:
cfg = [];
cfg.ylim = [20 20];                  
cfg.baseline     = [-0.2 -0.0]; 
cfg.baselinetype = 'absolute';
cfg.layout       = 'neuromag306mag.lay';
cfg.xlim = [-0.4:0.1:0.4];
cfg.comment = 'xlim';
cfg.commentpos = 'title';
figure; ft_topoplotTFR(cfg,TFRhann);

cfg = [];
cfg.baseline     = [-1.0 -0.8]; 
cfg.baselinetype = 'absolute'; 
%% cfg.zlim         = [-1e-27 1e-27]; that has just been created
cfg = [];
cfg.grid.warpmni   = 'yes';
cfg.grid.template  = template.grid;
cfg.grid.nonlinear = 'yes'; % use non-linear normalization
cfg.mri            = mri_aligned ;
warped_grid          = ft_prepare_sourcemodel(cfg);
save('warped_grid.m', 'warped_grid')

% make a figure of the single subject headmodel, and grid positions
figure;
ft_plot_vol(vol, 'edgecolor', 'none'); alpha 0.5;
ft_plot_mesh(grid.pos(grid.inside,:));

 

 

Image Added

 

Data preparation

 

Here we load all the necessary stuff and we set the main parameters of the analysis:

 

  • time windows for active state and baseline
  • frequency of interest
  • beamformer configuration
  • MEG channels to be used in the analysis
  • Different sets of trials are prepared for the coming analysis

Code Block
titleData preparation
overall_time_window = [-2 2] ; %% if you modify this modify the trials def above ! Is this used below ???

%% Define time window for active state and baseline
active_time_window = [0.2 0.6] ;
reference_time_window = [-1.4 -1.0] ;

%% Basic configuration of the beamformer
beamformer_lambda_normalization = '10%' ;
lead_field_depth_normalization = 'column' ;

%% Frequency of interest and associated width (we will examine here the 16 Hz to 28 Hz band)
freqofinterest = 22 ;
freqhalfwin = 6 ;

% Define the list of subjects (local structure with for each selected subject, meg label, date of first meg session, date of second meg session, mri label, t1 name)
list_sujets = {
 {{'gamma03_s03'},{'140703'}, {'140710'}, {'S03'}, {'sGAMMA_T_02_GI-0003-00001-000176-01.img'}}
 {{'gamma07_s07'},{'141016'}, {'141104'}, {'S07'}, {'sGAMMA_CV_S07-0003-00001-000176-01.img'}}
 {{'gamma08_s08'},{'141107'}, {'141121'}, {'S08'}, {'sGAMMA_MS_S08-0003-00001-000176-01.img'}} 
 {{'gamma10_s10'},{'141105'}, {'141112'}, {'S10'}, {'sGAMMA_AH_S10-0003-00001-000176-01.img'}}
 {{'gamma18_s18'},{'150210'}, {'150217'}, {'S18'}, {'sGAMMA_S18-0003-00001-000176-01.img'}}
 {{'gamma19_s19'},{'150219'}, {'150922'}, {'S19'}, {'sGAMMA_CV_S19-0003-00001-000176-01.img'}}
 {{'gamma20_s20'},{'150306'}, {'150313'}, {'S20'}, {'sGAMMA_SR_S20-0003-00001-000176-01.img'}}
 {{'gamma22_s22'},{'150410'}, {'150326'},  {'S22'}, {'sGAMMA_S22_PS-0003-00001-000176-01.img'}}
 {{'gamma24_s24'},{'150410'}, {'150421'}, {'S24'}, {'sGAMMA_S24_KL-0003-00001-000176-01.img'}}
 {{'gamma25_s25'},{'150403'}, {'150413'}, {'S25'}, {'sGAMMA_S25_LP-0003-00001-000176-01.img'}}
 {{'gamma26_s26'},{'150423'}, {'150430'}, {'S26'}, {'sGAMMA_S26_SD-0003-00001-000176-01.img'}}
 {{'gamma27_s27'},{'150506'}, {'150513'}, {'S27'}, {'sGAMMA_S27_KP-0005-00001-000176-01.img'}}
 {{'gamma29_s29'},{'150527'}, {'150604'}, {'S29'}, {'sGAMMA_S29_AC-0003-00001-000176-01.img'}}
 {{'gamma31_s31'},{'150618'}, {'150703'}, {'S31'}, {'sGAMMA_S31_MA-0003-00001-000176-01.img'}}
 {{'gamma39_s39'},{'150929'}, {'151013'}, {'S39'}, {'sGAMMA_S39_LP-0003-00001-000176-01.img'}}
} ;

%% number of subjects
number_of_subjects = size(list_sujets, 1) ;

%% Frequencies of interest (here only one, we can define several if needed)
fois={{22,6, 'BETA_MNI'}} ;
number_of_fois = length(fois) ;
 
%% Charger la grille du beamformer en d?formant le MNI sur le sujet
templatedir  = 'fieldtrip-20160105/template/sourcemodel';

template = load(fullfile(templatedir, 'standard_sourcemodel3d8mm'));

 

D.I.C.S. Analysis

The spatial filters are computed here. We then contrast the two conditions before saving the results. One very important step necessary to allow an easy visualisation of the results is to change the localisation of the grid points back to the original templates ones. 

Code Block
%% Load the MRI data for visualisation purpose
load('mri_aligned.mat') ; %% MRI data needed for vizualisation
load('segmentedmri.mat') ;
 
index = 1 ;

 conf = [] ;
 %% marker of interest
 markers = 'Move_OK' ;
 
 %% output label
 conf.label = 'WIKI_' ;

%% Main Analysis
for i=1:number_of_subjects
    
    %% Enter subject dir
    cd(list_sujets{i}{1}{:})
    
	%% Load the head model created during the MRI pre processing
	load vol ; %% load head model located in the subject directory and obtained from the T1 MRI of the subject
 
	%% Load the warped MNI grid
	load warped_grid ;

    for exam=1:2
		
		%% Is the subject/session really here?        
        if ~isempty([list_sujets{i}{1+exam}{:}])
            %% enter exam subdirectory
          cfg.showlabels   = 'yes';   
cfg.layout       = 'neuromag306mag.lay';
figure; ft_multiplotTFR(cfg, TFRhann);

CSD Computation

Code Block
titleCSD computation
%% Compute cross-sepctral density matrices
powcsd_all = compute_crosprect(channelsofinterest, freqofinterest, freqhalfwin, data_all) ;
powcsd_active = compute_crosprect(channelsofinterest, freqofinterest, freqhalfwin, data_timewindow_active) ;

powcsd_ref = compute_crosprect(channelsofinterest, freqofinterest, freqhalfwin, data_timewindow_ref) ;

Image Removed

Image Removed

Image Removed

Image Removed

Forward operator

Code Block
titleForward operator
% Create leadfield grid
cfg                 = [];
cfg.channel         = channelsofinterest ;
cfg.grad            = powcsd_active.grad;
cfg.vol             = vol ;
cfg.dics.reducerank = 2; % default for MEG is 2, for EEG is 3
cfg.grid.resolution = 1.0;   % use a 3-D grid with a 0.5 cm resolution
cfg.grid.unit       = 'cm';
cfg.grid.tight      = 'yes';
cfg.normalize       =  lead_field_depth_normalization ; %% Depth normalization
[grid] = ft_prepare_leadfield(cfg);

 

 

Image Removed

 

 

D.I.C.S. Analysis

Code Block
%% Compute DICS filters for the concatenated data
cfgcd(list_sujets{i}{1+exam}{:})
			
			%% Datasets to be scanned for the marker of interest
            datasets = {'B_cardiocor_blinkcor_run01_pre_tsss.fif' 'B_cardiocor_blinkcor_run02_pre_tsss.fif' 'B_cardiocor_blinkcor_run03_pre_tsss.fif'} ;

			%% Read two runs, define trials around LEFT_MVT_CLEAN marker (-2s to 2s around the marker), read also BIO005 which is an EMG.
			[ trials ] = trial_definition_ft( datasets, markers, 2.0, 2.0, 'BIO005' ) ;

			% Select time window of interest
			cfg = [];
			cfg.toilim = active_time_window ;
			data_timewindow_active = ft_redefinetrial(cfg,trials);

			% Select time window of control
			cfg = [];
			cfg.toilim = reference_time_window ;
			data_timewindow_ref = ft_redefinetrial(cfg,trials);

			% Concatenate for common spatial filter computation
			data_all = ft_appenddata([], data_timewindow_active, data_timewindow_ref);
 
			% Trials with full window
			cfg = [];
			cfg.toilim = overall_time_window ;
			full_data_all = ft_redefinetrial(cfg,trials);
            
			% Create leadfield grid
			cfg                      = [];
			cfg.channelgrid        	= channelsofinterestwarped_grid ;
			cfg.methodvol         	= 'dics'hdm ;
			cfg.frequencychannel         = freqofinterestchannelsofinterest ;
			cfg.gridgrad            = gridpowcsd_active.grad;
			cfg.headmodelvol      = vol; cfg.senstype     = 'MEG'vol ;
			cfg.dics.keepfilter  reducerank = 'yes'2; % Wedefault wishfor toMEG useis the2, calculatedfor filterEEG lateris on3
			cfg.dics.projectnoisenormalize = 'yes';
cfg.dics.lambda     = beamformer_lambda lead_field_depth_normalization ;
source_all %% Depth normalization
			[grid] = ft_prepare_sourceanalysisleadfield(cfg, powcsd_all);
 %% Apply computed filters to each active and reference windows cfg for freq_index=1:number_of_fois

				foi = fois{freq_index}{1} ;
      = []; cfg.channel      = channelsofinterest ;
cfg.method       = 'dics';
cfg.frequency    = freqofinterest ;
cfg.grid         = grid;
cfg.grid.filter  = source_all.avg.filter;
cfg.dics.projectnoise = 'yes';
cfg.headmodelwof = fois{freq_index}{2} ;
 
				%% Analysis on MAG
				%% Select the channel of interest
				channelsofinterest = {'MEG*1'} ; %% Magnetometer on an Elekta system

				%% Compute DICS filters for the concatenated data
				cfg              = [];
				cfg.channel      = channelsofinterest ;
				cfg.method          = vol'dics';
				cfg.dics.lambdafrequency    = beamformer_lambda_normalizationfreqofinterest ;
				cfg.senstypegrid         ='MEG' grid;
				cfg.headmodel %% Source analysis active
source_active = ft_sourceanalysis(cfg, powcsd_active);

%% Source analysis reference
source_reference = ft_sourceanalysis(cfg, powcsd_ref);

%% Compute differences (power) between active and reference
source_diff = source_active ;
source_diff.avg.pow  = (source_active.avg.pow - source_reference.avg.pow) ./ (source_active.avg.pow + source_reference.avg.pow);

%% Display the results
visuBF( source_diff, 'title' )
%% MRI reslicing

mri_resliced = ft_volumereslice([], mri_aligned);

%% Display results superimposed on MRI

cfg            = [];
cfg.parameter = 'avg.pow';
source_active_int  = ft_sourceinterpolate(cfg, source_active, mri_resliced);
source_reference_int  = ft_sourceinterpolate(cfg, source_reference, mri_resliced);
source_diff_int  = source_active_int;
source_diff_int.pow  = (source_active_int.pow - source_reference_int.pow) ./ (source_active_int.pow + source_reference_int.pow);

%% Display the results
visuBF( source_diff_int, 'title' )

 

Image Removed

 

Image Removed

Image Removed

LCMV + DICS(EMG)

Code Block
titleLCMV
%% LCMV ANALYSIS TO GET TEMPORAL INFORMATION with virtual sensors %% Retrieve correct labelling of the trials data_all.trialinfo = [zeros(length(data_timewindow_active.trial), 1); ones(length(data_timewindow_ref.trial), 1)]; %% Compute covariance of the data (as a whole - both conditions) cfg = []; cfg.covariance = 'yes'; cfg.channel = channelsofinterest ; cfg.vartrllength = 0; cfg.covariancewindow = 'all'; cfg.trials = 'all'; tlock = ft_timelockanalysis(cfg, trials); %% Localisation of max beta suppression [minval, minpowindx] = min(source_diff.avg.pow(:)); pos_cm = source_diff.pos(minpowindx,:) ; %% You may choose yourself a location of interest pos_cm = [0.0 5.0 9.0 ] ; %% CS %% pos_cm = [0.0 -4.0 5.0 ] ; %% Others loc --- checked where ! %% Used to store the EP computed at each virtual sensor location evoked_virtual_zscore = {} ; evoked_virtual = {} ; index = 1 ; for i_scan = -60:5:60 %% Compute filter for corresponding virtual sensor cfg = []; cfg.method = 'lcmv';
= vol;
				cfg.senstype     = 'MEG';
				cfg.dics.keepfilter   = 'yes'; % We wish to use the calculated filter later on
				cfg.dics.projectnoise = 'yes';
				cfg.dics.lambda  = beamformer_lambda_normalization;
				source_all = ft_sourceanalysis(cfg, powcsd_all);

				%% Apply computed filters to each active and reference windows
				cfg              = [];
				cfg.channel      = channelsofinterest ;
				cfg.method       = 'dics';
				cfg.frequency    = freqofinterest ;
				cfg.grid         = grid;
				cfg.grid.filter  = source_all.avg.filter;
				cfg.dics.projectnoise = 'yes';
				cfg.headmodel          = vol;
				cfg.dics.lambda  = beamformer_lambda_normalization ;
				cfg.senstype     ='MEG' ;

				%% Source analysis active
				source_active = ft_sourceanalysis(cfg, powcsd_active);

				%% Source analysis reference
				source_reference = ft_sourceanalysis(cfg, powcsd_ref);

				%% Compute differences (power) between active and reference
				source_diff = source_active ;
				source_diff.avg.pow  = (source_active.avg.pow - source_reference.avg.pow) ./ (source_active.avg.pow + source_reference.avg.pow);

				%% Change grid locations for display in MNI
				source_diff.pos = template.sourcemodel.pos;
				source_diff.dim = template.sourcemodel.dim;


				save('source_diff', [conf.label '_' conf.markers '_PRE_MAG_' fois{freq_index}{3}]) ;

 				%% Analysis on MAG

				%% Select the channel of interest
				channelsofinterest = {'MEG*2', 'MEG*3'}; %% Gradiometers on an Elekta system

				%% Compute DICS filters for the concatenated data
				cfg              = [];
				cfg.channel      = channelsofinterest ;
				cfg.method       = 'dics';
				cfg.frequency    = freqofinterest ;
				cfg.grid         = grid;
				cfg.headmodel    = vol;
				cfg.senstype     = 'MEG';
				cfg.dics.keepfilter   = 'yes'; % We wish to use the calculated filter later on
				cfg.dics.projectnoise = 'yes';
				cfg.dics.lambda  = beamformer_lambda_normalization;
				source_all = ft_sourceanalysis(cfg, powcsd_all);

				%% Apply computed filters to each active and reference windows
				cfg              = [];
				cfg.channel      = channelsofinterest ;
				cfg.method       = 'dics';
				cfg.frequency    = freqofinterest ;
				cfg.grid         = grid;
				cfg.grid.filter  = source_all.avg.filter;
				cfg.dics.projectnoise = 'yes';
				cfg.headmodel          = vol
;
				cfg.dics.lambda  = beamformer_lambda_normalization ;
				cfg.
grid.pos
senstype     ='MEG' ;

				%% Source analysis 
= [pos_cm(1)+i_scan/10 pos_cm(2) pos_cm(3)] ; %% cfg.grid.pos = [pos_cm(1) pos_cm(2)+i_scan/10 pos_cm(3)] ; cfg.grid.inside = 1:size(cfg.grid.pos, 1); cfg.grid.outside = []; cfg.grid.unit = 'cm'; %% DO NOT FORGET THAT ! cfg.keepfilter
active
				source_active = ft_sourceanalysis(cfg, powcsd_active);

				%% Source analysis reference
				source_reference = ft_sourceanalysis(cfg, powcsd_ref);

				%% Compute differences (power) between active and reference
				source_diff = source_active ;
				source_diff.avg.pow  = (source_active.avg.pow - source_reference.avg.pow) ./ (source_active.avg.pow + source_reference.avg.pow);

				%% Change grid locations for display in MNI
				source_diff.pos = template.sourcemodel.pos;
				source_diff.dim = template.sourcemodel.dim;

				save('source_diff', [conf.label '_' conf.markers '_PRE_MAG_' fois{freq_index}{3}]) ;
            end
      
=
 
'yes';
     cd 
cfg
.
lcmv
.
fixedori

      
=
 
'yes';
 
%
end
project
 
on
 
axis
 
of
 
most
end 
variance
%% 
using
for 
SVD
exam
    cd 
cfg
.
lcmv
.
projectnoise

end 
= 'yes'
%% for subject

 





 

 

Basic statistical analysis

Code Block
ft_defaults ;

list_sujets = 
cfg.lcmv.lambda = beamformer_lambda_normalization ; cfg.lcmv.weightnorm = 'nai' ; cfg.lcmv.normalize = lead_field_depth_normalization ; %% Depth normalization source_idx = ft_sourceanalysis(cfg, tlock); beamformer = source_idx.avg.filter{1}; %% Apply filter to the raw data chansel = ft_channelselection(channelsofinterest, data_all.label); % find MEG sensor names chansel = match_str(data_all.label, chansel); pow_data = []; pow_data.label = {'pow_x', 'pow_y', 'pow_z'}; pow_data.time = trials.time; for i=1:length(trials.trial) pow_data.trial{i} = beamformer * trials.trial{i}(chansel,:); end % %% construct a single virtual channel in the maximum power orientation (not usefull if fixed orig above) % timeseries = cat(2, pow_data.trial{:}); % [u, s, v] = svd(timeseries, 'econ'); % % % this is equal to the first column of matrix V, apart from the scaling with s(1,1) % timeseriesmaxproj = u(:,1)' * timeseries; % virtualchanneldata = []; % virtualchanneldata.label = {'cortex'}; % virtualchanneldata.time = trials.time; % for i=1:length(trials.trial) % virtualchanneldata.trial{i} = u(:,1)' * beamformer * trials.trial{i}(chansel,:); % end %% Together with option fixedori (fixed oreintation) this is suffisent (we have only one vector not three) virtualchanneldata = []; virtualchanneldata.label = {'cortex'}; virtualchanneldata.time = trials.time; for i=1:length(trials.trial) virtualchanneldata.trial{i} = pow_data.trial{i} ; end
{
 {{'gamma03_s03'},{'140703'}, {'140710'}, {'S03'}, {'sGAMMA_T_02_GI-0003-00001-000176-01.img'}}
 {{'gamma07_s07'},{'141016'}, {'141104'}, {'S07'}, {'sGAMMA_CV_S07-0003-00001-000176-01.img'}}
 {{'gamma08_s08'},{'141107'}, {'141121'}, {'S08'}, {'sGAMMA_MS_S08-0003-00001-000176-01.img'}} 
 {{'gamma10_s10'},{'141105'}, {'141112'}, {'S10'}, {'sGAMMA_AH_S10-0003-00001-000176-01.img'}}
 {{'gamma18_s18'},{'150210'}, {'150217'}, {'S18'}, {'sGAMMA_S18-0003-00001-000176-01.img'}}
 {{'gamma19_s19'},{'150219'}, {'150922'}, {'S19'}, {'sGAMMA_CV_S19-0003-00001-000176-01.img'}}
 {{'gamma20_s20'},{'150306'}, {'150313'}, {'S20'}, {'sGAMMA_SR_S20-0003-00001-000176-01.img'}}
 {{'gamma22_s22'},{'150410'}, {'150326'},  {'S22'}, {'sGAMMA_S22_PS-0003-00001-000176-01.img'}}
 {{'gamma24_s24'},{'150410'}, {'150421'}, {'S24'}, {'sGAMMA_S24_KL-0003-00001-000176-01.img'}}
 {{'gamma25_s25'},{'150403'}, {'150413'}, {'S25'}, {'sGAMMA_S25_LP-0003-00001-000176-01.img'}}
 {{'gamma26_s26'},{'150423'}, {'150430'}, {'S26'}, {'sGAMMA_S26_SD-0003-00001-000176-01.img'}}
 {{'gamma27_s27'},{'150506'}, {'150513'}, {'S27'}, {'sGAMMA_S27_KP-0005-00001-000176-01.img'}}
 {{'gamma29_s29'},{'150527'}, {'150604'}, {'S29'}, {'sGAMMA_S29_AC-0003-00001-000176-01.img'}}
 {{'gamma31_s31'},{'150618'}, {'150703'}, {'S31'}, {'sGAMMA_S31_MA-0003-00001-000176-01.img'}}
 {{'gamma39_s39'},{'150929'}, {'151013'}, {'S39'}, {'sGAMMA_S39_LP-0003-00001-000176-01.img'}}
} ;

%% number of subjects
number_of_subjects = size(list_sujets, 1) ;

%% Frequencies of interest (here only one, we can define several if needed)
fois={{22,6, 'BETA_MNI'}} ;
number_of_fois = length(fois) ;

%% number of subjects
number_of_subjects = size(list_sujets, 1) ;

%% number of sessions
number_of_sessions = 2 ; 

list_labels = {'WIKI_'} ;
list_markers = {'Move_OK'} ;
list_frequencies = {'BETA'} ;

number_of_labels = length(list_labels) ;
number_of_markers = length(list_markers) ;
number_of_frequencies = length(list_frequencies) ;

for i_label = 1:number_of_labels
    for i_mk = 1:number_of_markers
            for i_freq = 1:number_of_frequencies  


                sources_mag = {} ;
                sources_grad = {} ;
                index_exams = 1 ;

                markers = list_markers{i_mk} ;    %% 
                label = list_labels{i_label} ;    %% 
                freq = list_frequencies{i_freq} ; %%

                %% 
%
Main Analysis


 
%%
 
Time-frequency
 
analysis
  
%
     
cfg
      %% Read MAG Results
    
=
 
[]; %
     
cfg.output
      nb_hv = 0 
'pow'
;
 
%
     
cfg.channel
      
=
 
'cortex';
  
%
 
cfg.method = 'mtmconvol'; %
conf.title_figure = [label '_' markers '_PRE_MAG_' freq '_MNI'] ;
     
cfg.taper
        
=
 
'hanning';
  
%
for i=1:number_of_subjects
      
cfg.foi
          
=
 
7:2:100;
   cd(list_sujets{i}{1}{:})
                    
% analysis 2 to 30 Hz in steps of 2 Hz %
list_sujets{i}{1}{:}
                 
cfg.t_ftimwin
   for 
= ones(length(cfg.foi),1).*0.5;
exam=1
  
%
 
length
 
of
 
time
 
window
 
=
 
0.5
 
sec
   
%
     
cfg.toi
   %% enter exam subdirectory
   
=
 
-2.0:0.05:2.0;
                  
%
 
time
 
window "slides" from -0.5 to 1.5 sec in steps of 0.05 sec (50 ms) %
if ~isempty([list_sujets{i}{1+exam}{:}])
                  
TFRvirtualchanneldata
 
=
 
ft_freqanalysis(cfg,
 
virtualchanneldata);
  
%
     
title(['X = ' num2str(pos_cm(1)+i_scan/10)]) ; %
cd(list_sujets{i}{1+exam}{:})        
print(['TF-virtualChannel_alpha_'
 
num2str(pos_cm(1)+i_scan/10)],'-dpng')
  
%
 
 
%
     
%%
 
Display
 
the
 
results
 
as
 
a
 
TF
 
map
  
%
     
cfg
 
=
 
[];
  
%
    
cfg.baseline
load([conf.title_figure '_diff.mat']) ;
  
=
 
reference_time_window
 
;
  
%
     
cfg.baselinetype
 
=
 
'db';
  
%
     
cfg.channelname
   
=
 
'cortex';
 
%
 
top
 
figure
 nb_hv 
%
= nb_hv + 1 ;
cfg.zlim
 
=
 
[-5
 
5]
 
;
  
%
     
figure;ft_singleplotTFR(cfg,
 
TFRvirtualchanneldata);
                sources_mag{nb_hv} = 
%%
source_diff 
Evoked
;
potential
 
on
 
the
 
virtual
 
sensor
      
cfg.demean
             
= 'yes';
     index_exams = index_exams + 1 ;
               
cfg.baselinewindow
      
=
 
reference_time_window;
      
evoked_virtual{index} = ft_timelockanalysis(cfg, virtualchanneldata);
cd ..
              
evoked_virtual_zscore{index}
 
=
 
evoked_virtual{index}
 
;
      
mean_bl
 
= mean(evoked_virtual{index}.avg(1,nearest(evoked_virtual{1}.time, -2.0):nearest(evoked_virtual{1}.time, -1.8)) ,2) ;
end
             
std_bl
 
=
 
std(evoked_virtual{index}.avg(1,nearest(evoked_virtual{1}.time,
 
-2.0):nearest(evoked_virtual{1}.time,
 
-1.8))
 
,
 
0,
 
2)
end 
;
%% for exam
   
evoked_virtual_zscore{index}.avg
 
=
 
(evoked_virtual{index}.avg
 
-
 
mean_bl)/std_bl
 
;
            
%%
cd 
Display
..
the
 
evoked
 
potential
      
cfg.ylim
 
=
 
[-0.2
 
0.2]
 
;
    end %% 
figure
for 
; ft_singleplotER(cfg, evoked_virtual{index}) ;
subject

 

     
title(['X = ' num2str(pos_cm(1)+i_scan/10)]) ;
           conf = 
print(
[
'EV-mag-virtualChannel_beta_' num2str(pos_cm(2)+i_scan/10)
]
,'-dpng')
 ; 
         
cfg.ylim
 
=
 
[-10
 
10]
 
;
   mean_hv = 
figure ; ft_singleplotER(cfg, evoked_virtual_zscore{index}) ;
zeros(size(sources{1}.avg.pow)) ;
              
title(['X
 
=
 
' num2str(pos_cm(1)+i_scan/10)]) ;
for i=1:nb_hv
       
print(['EV-mag-zscore-virtualChannel_beta_'
 
num2str(pos_cm(2)+i_scan/10)],'-dpng')
            
index
mean_hv = 
index
mean_hv + 
1
sources_mag{i}.avg.pow ;
 
end
     
figure
  
for
 
i
 
=
 
1:index-1
     
plot(evoked_virtual_zscore{1}.time, evoked_virtual_zscore{i}.avg)
end ;
    
hold
 
on
  
end
  
hold
 
off
      mean_sources_mag = 
%% Coherence with EMG
sources{i} ;
      
%%
 
%%
 
First
 
using
 
EMG
  
channelsofinterest
 
=
 
{'MEG*2',
 
'MEG*3'}; %% Gradiometers on an Elekta system
 mean_sources_mag.avg.pow = mean_hv / nb_hv ;
       
%%
 
Compute
 
cross
 
spectrum
 
matrix
  
cfg
   visuBF_MNI(mean_sources_mag, 'test')        
=
 
[];
  
cfg.method
     
=
 
'mtmfft';
  
cfg.output
     
=
 
'powandcsd';
  
cfg.taper
   

      
=
 
'dpss';
  
cfg.tapsmofrq
       
=
%% 
5;
Read GRAD 
cfg.foi
Results
            
=
 
10;
  
cfg.keeptrials = 'yes'; cfg.channel
 nb_hv = 0 ;
           
=
 
{'MEG*2'
 
'MEG*3'
 
'BIO005'};
  
cfg
conf.
channelcmb
title_figure = 
{'MEG*2'
[label '
MEG*2
_'
;
 
'MEG*3'
markers '
MEG*3';, 'MEG*2' 'MEG*3' ; 'MEG*2' 'BIO005' ; 'MEG*3' 'BIO005'};
_PRE_GRAD_' freq '_MNI'] ;
         
powcsd
       for i=1:number_of_subjects
  
=
 
ft_freqanalysis(cfg,
 
data_timewindow_active);
        
%
 
Create
 
leadfield
 
grid
  
cfg
   cd(list_sujets{i}{1}{:})
             
=
 
[];
  
cfg.channel
    list_sujets{i}{1}{:}
    
=
  
channelsofinterest
 
;
  
cfg.grad
           for exam=1
powcsd.grad;
  
cfg.vol
             
=
  
vol
 
;
  
cfg.dics.reducerank = 2; % default for MEG is 2, for EEG is 3 cfg.grid.resolution = 1.0; % use a 3-D grid with a 0.5 cm resolution cfg.grid.unit
%% enter exam subdirectory
                        if ~isempty([list_sujets{i}{1+exam}{:}])
       
=
 
'cm';
  
cfg.grid.tight
      
=
 
'yes';
  
cfg.normalize
       
=
  
lead_field_depth_normalization ; %% Depth normalization [grid] = ft_prepare_leadfield(cfg);
cd(list_sujets{i}{1+exam}{:})            
cfg
                 
=
 
[];
  
cfg.method
        
= 'dics'
load([conf.title_figure '_diff.mat']) ;
 
cfg.refchan
         
=
 
'BIO005';
  
cfg.frequency
       
=
 
freqofinterest
 
;
  
cfg.grid
    nb_hv = nb_hv + 1 ;
   
=
 
grid;
  
cfg.vol
             
=
 
vol;
  
cfg.grid.unit
      sources_grad{nb_hv} =
'cm'
 source_diff ;
 
cfg.dics.lambda
  
=
 
beamformer_lambda_normalization;
  
%%
 
cfg.dics.reducerank
 
=
 
2;
 
%
 
default
 
for
 
MEG
 
is
 
2,
 
for
 
EEG
 
is
 
3
     
source
    index_exams = index_exams + 1 ;
    
=
 
ft_sourceanalysis(cfg,
 
powcsd);
     
cfg
              
=
 
[];
  cd 
cfg.method
..
                        end
                    end %% for exam
                  
=
 
'ortho';
 cd 
cfg
..
funparameter

=
 
'coh'; ft_sourceplot(cfg, source);
               end %% for subject

                conf = [] ; 
                mean_hv = zeros(size(sources{1}.avg.pow)) ;
                for i=1:nb_hv
                    mean_hv = mean_hv + sources{i}.avg.pow ;
                end ;
                mean_sources_grad = sources{i} ;
                mean_sources_grad.avg.pow = mean_hv / nb_hv ;
                visuBF_MNI(mean_sources_grad, 'test')                
                %% print -djpeg -r300 ['VS_' conf.title_figure '.jpeg']
            end %% Frequency
    end %% Markers
end %% LABEL

 

cfg = [];
cfg.dim         = sources_mag{1}.dim;
cfg.method      = 'montecarlo';
cfg.parameter   = 'pow';
cfg.correctm    = 'max';
cfg.numrandomization = 2000;
cfg.alpha       = 0.01; % note that this only implies single-sided testing
cfg.tail        = 0;
cfg.statistic   = 'ft_statfun_depsamplesT';
cfg.uvar        = 1; % row of design matrix that contains unit variable (in this case: trials)
cfg.ivar        = 2; % row of design matrix that contains independent variable (the conditions)
cfg.design(1,:) = [ones(1,nb_hv)  ones(1,nb_hv)] ;
cfg.design(2,:) = [ones(1,nb_hv)  ones(1,nb_hv)*2] ;
stat_hv = ft_sourcestatistics(cfg, sources_mag{:}, sources_grad{:}) ;

visuBF_MNI_STAT(stat_hv, 'test') ;

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Image Added

 

 

 

 

 

 

 

 

 

 

 

 

Image Added

 

 

 

 

Image Added

Image Added